feat(pdf): implement qpdf-wasm for secure encryption/decryption

- Replace PDFKit with qpdf-wasm for more robust and secure PDF encryption/decryption
- Add support for owner password and granular permission controls
- Improve UI with better security explanations and options
This commit is contained in:
abdullahalam123
2025-10-24 00:11:18 +05:30
parent be6c15fef2
commit 466646d15b
4 changed files with 294 additions and 143 deletions

4
package-lock.json generated
View File

@@ -1,12 +1,12 @@
{ {
"name": "bento-pdf", "name": "bento-pdf",
"version": "1.1.0", "version": "1.1.1",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "bento-pdf", "name": "bento-pdf",
"version": "1.1.0", "version": "1.1.1",
"license": "Apache-2.0", "license": "Apache-2.0",
"dependencies": { "dependencies": {
"@fontsource/cedarville-cursive": "^5.2.7", "@fontsource/cedarville-cursive": "^5.2.7",

View File

@@ -1,79 +1,126 @@
import { showLoader, hideLoader, showAlert } from '../ui.js'; import { showLoader, hideLoader, showAlert } from '../ui.js';
import { downloadFile, readFileAsArrayBuffer } from '../utils/helpers.js'; import { downloadFile, readFileAsArrayBuffer } from '../utils/helpers.js';
import { state } from '../state.js'; import { state } from '../state.js';
import PDFDocument from 'pdfkit/js/pdfkit.standalone'; import createModule from '@neslinesli93/qpdf-wasm';
import blobStream from 'blob-stream';
import * as pdfjsLib from 'pdfjs-dist'; let qpdfInstance: any = null;
async function initializeQpdf() {
if (qpdfInstance) {
return qpdfInstance;
}
showLoader('Initializing decryption engine...');
try {
qpdfInstance = await createModule({
locateFile: () => '/qpdf.wasm',
});
} catch (error) {
console.error('Failed to initialize qpdf-wasm:', error);
showAlert(
'Initialization Error',
'Could not load the decryption engine. Please refresh the page and try again.'
);
throw error;
} finally {
hideLoader();
}
return qpdfInstance;
}
export async function decrypt() { export async function decrypt() {
const file = state.files[0]; const file = state.files[0];
// @ts-expect-error TS(2339) FIXME: Property 'value' does not exist on type 'HTMLEleme... Remove this comment to see the full error message const password = (
const password = document.getElementById('password-input').value; document.getElementById('password-input') as HTMLInputElement
if (!password.trim()) { )?.value;
if (!password?.trim()) {
showAlert('Input Required', 'Please enter the PDF password.'); showAlert('Input Required', 'Please enter the PDF password.');
return; return;
} }
const inputPath = '/input.pdf';
const outputPath = '/output.pdf';
let qpdf: any;
try { try {
showLoader('Preparing to process...'); showLoader('Initializing decryption...');
const pdfData = (await readFileAsArrayBuffer(file)) as ArrayBuffer; qpdf = await initializeQpdf();
const pdf = await pdfjsLib.getDocument({
data: pdfData,
password: password,
}).promise;
const numPages = pdf.numPages;
const pageImages = [];
for (let i = 1; i <= numPages; i++) { showLoader('Reading encrypted PDF...');
document.getElementById('loader-text').textContent = const fileBuffer = await readFileAsArrayBuffer(file);
`Processing page ${i} of ${numPages}...`; const uint8Array = new Uint8Array(fileBuffer as ArrayBuffer);
const page = await pdf.getPage(i);
const viewport = page.getViewport({ scale: 2.0 }); qpdf.FS.writeFile(inputPath, uint8Array);
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d'); showLoader('Decrypting PDF...');
canvas.height = viewport.height;
canvas.width = viewport.width; const args = [inputPath, '--password=' + password, '--decrypt', outputPath];
await page.render({
canvasContext: context, try {
viewport: viewport, qpdf.callMain(args);
canvas: canvas, } catch (qpdfError: any) {
}).promise; console.error('qpdf execution error:', qpdfError);
pageImages.push({
data: canvas.toDataURL('image/jpeg', 0.8), if (
width: viewport.width, qpdfError.message?.includes('invalid password') ||
height: viewport.height, qpdfError.message?.includes('password')
}); ) {
throw new Error('INVALID_PASSWORD');
}
throw qpdfError;
} }
document.getElementById('loader-text').textContent = showLoader('Preparing download...');
'Building unlocked PDF...'; const outputFile = qpdf.FS.readFile(outputPath, { encoding: 'binary' });
const doc = new PDFDocument({
size: [pageImages[0].width, pageImages[0].height],
});
const stream = doc.pipe(blobStream());
for (let i = 0; i < pageImages.length; i++) {
if (i > 0)
doc.addPage({ size: [pageImages[i].width, pageImages[i].height] });
doc.image(pageImages[i].data, 0, 0, {
width: pageImages[i].width,
height: pageImages[i].height,
});
}
doc.end();
stream.on('finish', function () { if (!outputFile || outputFile.length === 0) {
const blob = stream.toBlob('application/pdf'); throw new Error('Decryption resulted in an empty file.');
}
const blob = new Blob([outputFile], { type: 'application/pdf' });
downloadFile(blob, `unlocked-${file.name}`); downloadFile(blob, `unlocked-${file.name}`);
hideLoader(); hideLoader();
showAlert('Success', 'Decryption complete! Your download has started.'); showAlert(
}); 'Success',
} catch (error) { 'PDF decrypted successfully! Your download has started.'
);
} catch (error: any) {
console.error('Error during PDF decryption:', error); console.error('Error during PDF decryption:', error);
hideLoader(); hideLoader();
if (error.name === 'PasswordException') {
showAlert('Incorrect Password', 'The password you entered is incorrect.'); if (error.message === 'INVALID_PASSWORD') {
showAlert(
'Incorrect Password',
'The password you entered is incorrect. Please try again.'
);
} else if (error.message?.includes('password')) {
showAlert(
'Password Error',
'Unable to decrypt the PDF with the provided password.'
);
} else { } else {
showAlert('Error', 'An error occurred. The PDF might be corrupted.'); showAlert(
'Decryption Failed',
`An error occurred: ${error.message || 'The password you entered is wrong or the file is corrupted.'}`
);
}
} finally {
try {
if (qpdf?.FS) {
try {
qpdf.FS.unlink(inputPath);
} catch (e) {
console.warn('Failed to unlink input file:', e);
}
try {
qpdf.FS.unlink(outputPath);
} catch (e) {
console.warn('Failed to unlink output file:', e);
}
}
} catch (cleanupError) {
console.warn('Failed to cleanup WASM FS:', cleanupError);
} }
} }
} }

View File

@@ -1,86 +1,140 @@
import { showLoader, hideLoader, showAlert } from '../ui.js'; import { showLoader, hideLoader, showAlert } from '../ui.js';
import { downloadFile, readFileAsArrayBuffer } from '../utils/helpers.js'; import { downloadFile, readFileAsArrayBuffer } from '../utils/helpers.js';
import { state } from '../state.js'; import { state } from '../state.js';
import PDFDocument from 'pdfkit/js/pdfkit.standalone'; import createModule from '@neslinesli93/qpdf-wasm';
import blobStream from 'blob-stream';
import * as pdfjsLib from 'pdfjs-dist'; let qpdfInstance: any = null;
async function initializeQpdf() {
if (qpdfInstance) {
return qpdfInstance;
}
showLoader('Initializing encryption engine...');
try {
qpdfInstance = await createModule({
locateFile: () => '/qpdf.wasm',
});
} catch (error) {
console.error('Failed to initialize qpdf-wasm:', error);
showAlert(
'Initialization Error',
'Could not load the encryption engine. Please refresh the page and try again.'
);
throw error;
} finally {
hideLoader();
}
return qpdfInstance;
}
export async function encrypt() { export async function encrypt() {
const file = state.files[0]; const file = state.files[0];
const password = ( const userPassword =
document.getElementById('password-input') as HTMLInputElement (document.getElementById('user-password-input') as HTMLInputElement)
).value; ?.value || '';
if (!password.trim()) { const ownerPassword =
showAlert('Input Required', 'Please enter a password.'); (document.getElementById('owner-password-input') as HTMLInputElement)
?.value || '';
if (!userPassword) {
showAlert('Input Required', 'Please enter a user password.');
return; return;
} }
const inputPath = '/input.pdf';
const outputPath = '/output.pdf';
let qpdf: any;
try { try {
showLoader('Preparing to process...'); showLoader('Initializing encryption...');
const pdfData = await readFileAsArrayBuffer(file); qpdf = await initializeQpdf();
const pdf = await pdfjsLib.getDocument({ data: pdfData as ArrayBuffer })
.promise;
const numPages = pdf.numPages;
const pageImages = [];
for (let i = 1; i <= numPages; i++) { showLoader('Reading PDF...');
document.getElementById('loader-text').textContent = const fileBuffer = await readFileAsArrayBuffer(file);
`Processing page ${i} of ${numPages}...`; const uint8Array = new Uint8Array(fileBuffer as ArrayBuffer);
const page = await pdf.getPage(i);
const viewport = page.getViewport({ scale: 2.0 }); qpdf.FS.writeFile(inputPath, uint8Array);
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d'); showLoader('Encrypting PDF with 256-bit AES...');
canvas.height = viewport.height;
canvas.width = viewport.width; const args = [
await page.render({ inputPath,
canvasContext: context, '--encrypt',
viewport: viewport, userPassword,
canvas: canvas, ownerPassword, // Can be empty
}).promise; '256',
pageImages.push({ ];
data: canvas.toDataURL('image/jpeg', 0.8),
width: viewport.width, if (ownerPassword) {
height: viewport.height, args.push(
}); '--modify=none',
'--extract=n',
'--print=none',
'--accessibility=n',
'--annotate=n',
'--assemble=n',
'--form=n',
'--modify-other=n',
);
} }
document.getElementById('loader-text').textContent = if (!ownerPassword) {
'Encrypting and building PDF...'; args.push('--allow-insecure');
const doc = new PDFDocument({
size: [pageImages[0].width, pageImages[0].height],
pdfVersion: '1.7ext3', // Use 256-bit AES encryption
userPassword: password,
ownerPassword: password,
permissions: {
printing: 'highResolution',
modifying: false,
copying: false,
annotating: false,
fillingForms: false,
contentAccessibility: true,
documentAssembly: false,
},
});
const stream = doc.pipe(blobStream());
for (let i = 0; i < pageImages.length; i++) {
if (i > 0)
doc.addPage({ size: [pageImages[i].width, pageImages[i].height] });
doc.image(pageImages[i].data, 0, 0, {
width: pageImages[i].width,
height: pageImages[i].height,
});
} }
doc.end();
stream.on('finish', function () { args.push('--', outputPath);
const blob = stream.toBlob('application/pdf');
try {
qpdf.callMain(args);
} catch (qpdfError: any) {
console.error('qpdf execution error:', qpdfError);
throw new Error(
'Encryption failed: ' + (qpdfError.message || 'Unknown error')
);
}
showLoader('Preparing download...');
const outputFile = qpdf.FS.readFile(outputPath, { encoding: 'binary' });
if (!outputFile || outputFile.length === 0) {
throw new Error('Encryption resulted in an empty file.');
}
const blob = new Blob([outputFile], { type: 'application/pdf' });
downloadFile(blob, `encrypted-${file.name}`); downloadFile(blob, `encrypted-${file.name}`);
hideLoader(); hideLoader();
showAlert('Success', 'Encryption complete! Your download has started.');
}); let successMessage = 'PDF encrypted successfully with 256-bit AES!';
} catch (error) { if (!ownerPassword) {
successMessage +=
' Note: Without an owner password, the PDF has no usage restrictions.';
}
showAlert('Success', successMessage);
} catch (error: any) {
console.error('Error during PDF encryption:', error); console.error('Error during PDF encryption:', error);
hideLoader(); hideLoader();
showAlert('Error', 'An error occurred. The PDF might be corrupted.'); showAlert(
'Encryption Failed',
`An error occurred: ${error.message || 'The PDF might be corrupted.'}`
);
} finally {
try {
if (qpdf?.FS) {
try {
qpdf.FS.unlink(inputPath);
} catch (e) {
console.warn('Failed to unlink input file:', e);
}
try {
qpdf.FS.unlink(outputPath);
} catch (e) {
console.warn('Failed to unlink output file:', e);
}
}
} catch (cleanupError) {
console.warn('Failed to cleanup WASM FS:', cleanupError);
}
} }
} }

View File

@@ -380,22 +380,72 @@ export const toolTemplates = {
`, `,
encrypt: () => ` encrypt: () => `
<h2 class="text-2xl font-bold text-white mb-4">Encrypt PDF</h2> <h2 class="text-2xl font-bold text-white mb-4">Encrypt PDF</h2>
<p class="mb-6 text-gray-400">Upload a PDF to create a new, password-protected version.</p> <p class="mb-6 text-gray-400">Add 256-bit AES password protection to your PDF.</p>
${createFileInputHTML()} ${createFileInputHTML()}
<div id="file-display-area" class="mt-4 space-y-2"></div> <div id="file-display-area" class="mt-4 space-y-2"></div>
<div id="encrypt-options" class="hidden space-y-4 mt-6"> <div id="encrypt-options" class="hidden space-y-4 mt-6">
<div> <div>
<label for="password-input" class="block mb-2 text-sm font-medium text-gray-300">Set Encryption Password</label> <label for="user-password-input" class="block mb-2 text-sm font-medium text-gray-300">User Password</label>
<input type="password" id="password-input" class="w-full bg-gray-700 border border-gray-600 text-white rounded-lg p-2.5" placeholder="Enter a strong password"> <input required type="password" id="user-password-input" class="w-full bg-gray-700 border border-gray-600 text-white rounded-lg p-2.5" placeholder="Password to open the PDF">
<p class="text-xs text-gray-500 mt-1">Required to open and view the PDF</p>
</div> </div>
<div class="p-4 bg-gray-900 border border-yellow-500/30 text-yellow-200 rounded-lg"> <div>
<h3 class="font-semibold text-base mb-2">Important Note</h3> <label for="owner-password-input" class="block mb-2 text-sm font-medium text-gray-300">Owner Password (Optional)</label>
<p class="text-sm text-gray-400">To create the secure file, each page is converted into an image. This means you won't be able to select text or click links in the final encrypted PDF.</p> <input type="password" id="owner-password-input" class="w-full bg-gray-700 border border-gray-600 text-white rounded-lg p-2.5" placeholder="Password for full permissions (recommended)">
<p class="text-xs text-gray-500 mt-1">Allows changing permissions and removing encryption</p>
</div>
<!-- Restriction checkboxes (shown when owner password is entered) -->
<div id="restriction-options" class="hidden p-4 bg-gray-800 border border-gray-700 rounded-lg">
<h3 class="font-semibold text-base mb-2 text-white">🔒 Restrict PDF Permissions</h3>
<p class="text-sm text-gray-400 mb-3">Select which actions to disable:</p>
<div class="space-y-2">
<label class="flex items-center space-x-2">
<input type="checkbox" id="restrict-modify" checked>
<span>Disable all modifications (--modify=none)</span>
</label>
<label class="flex items-center space-x-2">
<input type="checkbox" id="restrict-extract" checked>
<span>Disable text and image extraction (--extract=n)</span>
</label>
<label class="flex items-center space-x-2">
<input type="checkbox" id="restrict-print" checked>
<span>Disable all printing (--print=none)</span>
</label>
<label class="flex items-center space-x-2">
<input type="checkbox" id="restrict-accessibility">
<span>Disable accessibility text copying (--accessibility=n)</span>
</label>
<label class="flex items-center space-x-2">
<input type="checkbox" id="restrict-annotate">
<span>Disable annotations (--annotate=n)</span>
</label>
<label class="flex items-center space-x-2">
<input type="checkbox" id="restrict-assemble">
<span>Disable page assembly (--assemble=n)</span>
</label>
<label class="flex items-center space-x-2">
<input type="checkbox" id="restrict-form">
<span>Disable form filling (--form=n)</span>
</label>
<label class="flex items-center space-x-2">
<input type="checkbox" id="restrict-modify-other">
<span>Disable other modifications (--modify-other=n)</span>
</label>
</div>
</div>
<div class="p-4 bg-yellow-900/20 border border-yellow-500/30 text-yellow-200 rounded-lg">
<h3 class="font-semibold text-base mb-2">⚠️ Security Recommendation</h3>
<p class="text-sm text-gray-300">For strong security, set both passwords. Without an owner password, the security restrictions (printing, copying, etc.) can be easily bypassed.</p>
</div>
<div class="p-4 bg-green-900/20 border border-green-500/30 text-green-200 rounded-lg">
<h3 class="font-semibold text-base mb-2">✓ High-Quality Encryption</h3>
<p class="text-sm text-gray-300">256-bit AES encryption without quality loss. Text remains selectable and searchable.</p>
</div> </div>
<button id="process-btn" class="btn-gradient w-full mt-6">Encrypt & Download</button> <button id="process-btn" class="btn-gradient w-full mt-6">Encrypt & Download</button>
</div> </div>
<canvas id="pdf-canvas" class="hidden"></canvas> `,
`,
decrypt: () => ` decrypt: () => `
<h2 class="text-2xl font-bold text-white mb-4">Decrypt PDF</h2> <h2 class="text-2xl font-bold text-white mb-4">Decrypt PDF</h2>
<p class="mb-6 text-gray-400">Upload an encrypted PDF and provide its password to create an unlocked version.</p> <p class="mb-6 text-gray-400">Upload an encrypted PDF and provide its password to create an unlocked version.</p>