From 6df34436171f5b0fad1fd343de08621ce3a8b669 Mon Sep 17 00:00:00 2001 From: Shelley Vohr Date: Wed, 31 Jan 2024 10:48:41 +0100 Subject: [PATCH] fix: validate `printToPDF` `margins` against `pageSize` (#41157) fix: validate margins against pageSize --- lib/browser/api/web-contents.ts | 12 +++++++++++- spec/api-web-contents-spec.ts | 14 ++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/lib/browser/api/web-contents.ts b/lib/browser/api/web-contents.ts index 2dbd19c92794..7fcd5dec3f04 100644 --- a/lib/browser/api/web-contents.ts +++ b/lib/browser/api/web-contents.ts @@ -220,6 +220,16 @@ function parsePageSize (pageSize: string | ElectronInternal.PageSize) { let pendingPromise: Promise | undefined; WebContents.prototype.printToPDF = async function (options) { const margins = checkType(options.margins ?? {}, 'object', 'margins'); + const pageSize = parsePageSize(options.pageSize ?? 'letter'); + + const { top, bottom, left, right } = margins; + const validHeight = [top, bottom].every(u => u === undefined || u <= pageSize.paperHeight); + const validWidth = [left, right].every(u => u === undefined || u <= pageSize.paperWidth); + + if (!validHeight || !validWidth) { + throw new Error('margins must be less than or equal to pageSize'); + } + const printSettings = { requestID: getNextId(), landscape: checkType(options.landscape ?? false, 'boolean', 'landscape'), @@ -236,7 +246,7 @@ WebContents.prototype.printToPDF = async function (options) { preferCSSPageSize: checkType(options.preferCSSPageSize ?? false, 'boolean', 'preferCSSPageSize'), generateTaggedPDF: checkType(options.generateTaggedPDF ?? false, 'boolean', 'generateTaggedPDF'), generateDocumentOutline: checkType(options.generateDocumentOutline ?? false, 'boolean', 'generateDocumentOutline'), - ...parsePageSize(options.pageSize ?? 'letter') + ...pageSize }; if (this._printToPDF) { diff --git a/spec/api-web-contents-spec.ts b/spec/api-web-contents-spec.ts index 7251a4e9fb32..12f1c623fd42 100644 --- a/spec/api-web-contents-spec.ts +++ b/spec/api-web-contents-spec.ts @@ -2053,6 +2053,20 @@ describe('webContents module', () => { } }); + it('rejects when margins exceed physical page size', async () => { + await w.loadURL('data:text/html,

Hello, World!

'); + + await expect(w.webContents.printToPDF({ + pageSize: 'Letter', + margins: { + top: 100, + bottom: 100, + left: 5, + right: 5 + } + })).to.eventually.be.rejectedWith('margins must be less than or equal to pageSize'); + }); + it('does not crash when called multiple times in parallel', async () => { await w.loadURL('data:text/html,

Hello, World!

');