Skip to content

Commit

Permalink
Add encryption support and access privileges
Browse files Browse the repository at this point in the history
Based on foliojs/pdfkit#820 upstream
Fixes #672
  • Loading branch information
klimeryk committed Mar 29, 2024
1 parent 68bfc57 commit 4376bcb
Show file tree
Hide file tree
Showing 5 changed files with 727 additions and 36 deletions.
14 changes: 7 additions & 7 deletions packages/pdfkit/src/document.js
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ class PDFDocument extends stream.Readable {
this._id = PDFSecurity.generateFileID(this.info);

// Initialize security settings
// this._security = PDFSecurity.create(this, options);
this._security = PDFSecurity.create(this, options);

// Write the header PDF version
this._write(`%PDF-${this.version}`);
Expand Down Expand Up @@ -276,9 +276,9 @@ class PDFDocument extends stream.Readable {
this._root.data.ViewerPreferences.end();
}

// if (this._security) {
// this._security.end();
// }
if (this._security) {
this._security.end();
}

if (this._waiting === 0) {
return this._finalize();
Expand Down Expand Up @@ -307,9 +307,9 @@ class PDFDocument extends stream.Readable {
ID: [this._id, this._id]
};

// if (this._security) {
// trailer.Encrypt = this._security.dictionary;
// }
if (this._security) {
trailer.Encrypt = this._security.dictionary;
}

this._write('trailer');
this._write(PDFObject.convert(trailer));
Expand Down
39 changes: 28 additions & 11 deletions packages/pdfkit/src/object.js
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ const swapBytes = function (buff) {
};

class PDFObject {
static convert(object) {
static convert(object, encryptFn = null) {
// String literals are converted to the PDF name type
if (typeof object === 'string') {
return `/${object}`;
Expand All @@ -51,20 +51,28 @@ class PDFObject {
}

// If so, encode it as big endian UTF-16
let stringBuffer;
if (isUnicode) {
string = swapBytes(Buffer.from(`\ufeff${string}`, 'utf16le')).toString(
'binary'
);
stringBuffer = swapBytes(Buffer.from(`\ufeff${string}`, 'utf16le'));
} else {
stringBuffer = Buffer.from(string.valueOf(), 'ascii');
}

// Encrypt the string when necessary
if (encryptFn) {
string = encryptFn(stringBuffer).toString('binary');
} else {
string = stringBuffer.toString('binary');
}

// Escape characters as required by the spec
string = string.replace(escapableRe, (c) => escapable[c]);

return `(${string})`;

// Buffers are converted to PDF hex strings
}

// Buffers are converted to PDF hex strings
if (Buffer.isBuffer(object)) {
return `<${object.toString('hex')}>`;
}
Expand All @@ -74,20 +82,29 @@ class PDFObject {
}

if (object instanceof Date) {
return (
`(D:${pad(object.getUTCFullYear(), 4)}` +
let string =
`D:${pad(object.getUTCFullYear(), 4)}` +
pad(object.getUTCMonth() + 1, 2) +
pad(object.getUTCDate(), 2) +
pad(object.getUTCHours(), 2) +
pad(object.getUTCMinutes(), 2) +
pad(object.getUTCSeconds(), 2) +
'Z)'
);
'Z';

// Encrypt the string when necessary
if (encryptFn) {
string = encryptFn(Buffer.from(string, 'ascii')).toString('binary');

// Escape characters as required by the spec
string = string.replace(escapableRe, c => escapable[c]);
}

return `(${string})`;
}

if (Array.isArray(object)) {
const items = Array.from(object)
.map((e) => PDFObject.convert(e))
.map(e => PDFObject.convert(e, encryptFn))
.join(' ');
return `[${items}]`;
}
Expand All @@ -96,7 +113,7 @@ class PDFObject {
const out = ['<<'];
for (let key in object) {
const val = object[key];
out.push(`/${key} ${PDFObject.convert(val)}`);
out.push(`/${key} ${PDFObject.convert(val, encryptFn)}`);
}

out.push('>>');
Expand Down
5 changes: 4 additions & 1 deletion packages/pdfkit/src/reference.js
Original file line number Diff line number Diff line change
Expand Up @@ -69,8 +69,11 @@ class PDFReference extends stream.Writable {
finalize() {
this.offset = this.document._offset;

const encryptFn = this.document._security
? this.document._security.getEncryptFn(this.id, this.gen)
: null;
this.document._write(`${this.id} ${this.gen} obj`);
this.document._write(PDFObject.convert(this.data));
this.document._write(PDFObject.convert(this.data, encryptFn));

if (this.chunks.length) {
this.document._write('stream');
Expand Down
147 changes: 147 additions & 0 deletions packages/pdfkit/src/saslprep/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
import {
isUnassignedCodePoint,
isCommonlyMappedToNothing,
isNonASCIISpaceCharacter,
isProhibitedCharacter,
isBidirectionalRAL,
isBidirectionalL
} from './lib/code-points';

// 2.1. Mapping

/**
* non-ASCII space characters [StringPrep, C.1.2] that can be
* mapped to SPACE (U+0020)
*/
const mapping2space = isNonASCIISpaceCharacter;

/**
* the "commonly mapped to nothing" characters [StringPrep, B.1]
* that can be mapped to nothing.
*/
const mapping2nothing = isCommonlyMappedToNothing;

// utils
const getCodePoint = character => character.codePointAt(0);
const first = x => x[0];
const last = x => x[x.length - 1];

/**
* Convert provided string into an array of Unicode Code Points.
* Based on https://stackoverflow.com/a/21409165/1556249
* and https://www.npmjs.com/package/code-point-at.
* @param {string} input
* @returns {number[]}
*/
function toCodePoints(input) {
const codepoints = [];
const size = input.length;

for (let i = 0; i < size; i += 1) {
const before = input.charCodeAt(i);

if (before >= 0xd800 && before <= 0xdbff && size > i + 1) {
const next = input.charCodeAt(i + 1);

if (next >= 0xdc00 && next <= 0xdfff) {
codepoints.push((before - 0xd800) * 0x400 + next - 0xdc00 + 0x10000);
i += 1;
continue;
}
}

codepoints.push(before);
}

return codepoints;
}

/**
* SASLprep.
* @param {string} input
* @param {Object} opts
* @param {boolean} opts.allowUnassigned
* @returns {string}
*/
function saslprep(input, opts = {}) {
if (typeof input !== 'string') {
throw new TypeError('Expected string.');
}

if (input.length === 0) {
return '';
}

// 1. Map
const mapped_input = toCodePoints(input)
// 1.1 mapping to space
.map(character => (mapping2space(character) ? 0x20 : character))
// 1.2 mapping to nothing
.filter(character => !mapping2nothing(character));

// 2. Normalize
const normalized_input = String.fromCodePoint
.apply(null, mapped_input)
.normalize('NFKC');

const normalized_map = toCodePoints(normalized_input);

// 3. Prohibit
const hasProhibited = normalized_map.some(isProhibitedCharacter);

if (hasProhibited) {
throw new Error(
'Prohibited character, see https://tools.ietf.org/html/rfc4013#section-2.3'
);
}

// Unassigned Code Points
if (opts.allowUnassigned !== true) {
const hasUnassigned = normalized_map.some(isUnassignedCodePoint);

if (hasUnassigned) {
throw new Error(
'Unassigned code point, see https://tools.ietf.org/html/rfc4013#section-2.5'
);
}
}

// 4. check bidi

const hasBidiRAL = normalized_map.some(isBidirectionalRAL);

const hasBidiL = normalized_map.some(isBidirectionalL);

// 4.1 If a string contains any RandALCat character, the string MUST NOT
// contain any LCat character.
if (hasBidiRAL && hasBidiL) {
throw new Error(
'String must not contain RandALCat and LCat at the same time,' +
' see https://tools.ietf.org/html/rfc3454#section-6'
);
}

/**
* 4.2 If a string contains any RandALCat character, a RandALCat
* character MUST be the first character of the string, and a
* RandALCat character MUST be the last character of the string.
*/

const isFirstBidiRAL = isBidirectionalRAL(
getCodePoint(first(normalized_input))
);
const isLastBidiRAL = isBidirectionalRAL(
getCodePoint(last(normalized_input))
);

if (hasBidiRAL && !(isFirstBidiRAL && isLastBidiRAL)) {
throw new Error(
'Bidirectional RandALCat character must be the first and the last' +
' character of the string, see https://tools.ietf.org/html/rfc3454#section-6'
);
}

return normalized_input;
}

export default saslprep;

0 comments on commit 4376bcb

Please sign in to comment.