Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add encryption support and access privileges #2696

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/young-dodos-invent.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@react-pdf/pdfkit": minor
---

Add encryption support and access privileges
3 changes: 3 additions & 0 deletions packages/pdfkit/jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export default {
testRegex: 'tests/unit/.*?(spec)\\.js$',
};
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
2 changes: 1 addition & 1 deletion packages/pdfkit/src/font/embedded.js
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ const createEmbeddedFont = (PDFFont) =>
fontFile.data.Subtype = 'CIDFontType0C';
}

fontFile.end(this.subset.encode());
fontFile.end(Buffer.from(this.subset.encode()));

const familyClass =
((this.font['OS/2'] != null
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
82 changes: 33 additions & 49 deletions packages/pdfkit/src/reference.js
Original file line number Diff line number Diff line change
@@ -1,89 +1,73 @@
import zlib from 'zlib';
import stream from 'stream';
import PDFObject from './object';

class PDFReference extends stream.Writable {
constructor(document, id, data) {
super({ decodeStrings: false });

this.finalize = this.finalize.bind(this);
class PDFReference {
constructor(document, id, data = {}) {
this.document = document;
this.id = id;
if (data == null) {
data = {};
}
this.data = data;

this.gen = 0;
this.deflate = null;
this.compress = this.document.compress && !this.data.Filter;
this.uncompressedLength = 0;
this.chunks = [];
}

initDeflate() {
this.data.Filter = 'FlateDecode';

this.deflate = zlib.createDeflate();
this.deflate.on('data', (chunk) => {
this.chunks.push(chunk);
return (this.data.Length += chunk.length);
});

return this.deflate.on('end', this.finalize);
this.buffer = [];
}

_write(chunk, encoding, callback) {
if (!(chunk instanceof Uint8Array)) {
write(chunk) {
if (!Buffer.isBuffer(chunk)) {
chunk = Buffer.from(chunk + '\n', 'binary');
}

this.uncompressedLength += chunk.length;
if (this.data.Length == null) {
this.data.Length = 0;
}

this.buffer.push(chunk);
this.data.Length += chunk.length;
if (this.compress) {
if (!this.deflate) {
this.initDeflate();
}
this.deflate.write(chunk);
} else {
this.chunks.push(chunk);
this.data.Length += chunk.length;
return (this.data.Filter = 'FlateDecode');
}

return callback();
}

end() {
super.end(...arguments);

if (this.deflate) {
return this.deflate.end();
end(chunk) {
if (chunk) {
this.write(chunk);
}

return this.finalize();
}

finalize() {
this.offset = this.document._offset;

const encryptFn = this.document._security
? this.document._security.getEncryptFn(this.id, this.gen)
: null;

if (this.buffer.length) {
this.buffer = Buffer.concat(this.buffer);
if (this.compress) {
this.buffer = zlib.deflateSync(this.buffer);
}

if (encryptFn) {
this.buffer = encryptFn(this.buffer);
}

this.data.Length = this.buffer.length;
}

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) {
if (this.buffer.length) {
this.document._write('stream');
for (let chunk of Array.from(this.chunks)) {
this.document._write(chunk);
}
this.document._write(this.buffer);

this.chunks.length = 0; // free up memory
this.buffer = []; // free up memory
this.document._write('\nendstream');
}

this.document._write('endobj');
return this.document._refEnd(this);
this.document._refEnd(this);
}

klimeryk marked this conversation as resolved.
Show resolved Hide resolved
toString() {
Expand Down
Loading