Files
sign/packages/signing/transports/local-cert.ts

52 lines
1.5 KiB
TypeScript
Raw Normal View History

2023-09-25 15:57:10 +10:00
import fs from 'node:fs';
2024-03-15 22:26:09 +11:00
import { signWithP12 } from '@documenso/pdf-sign';
import { addSigningPlaceholder } from '../helpers/add-signing-placeholder';
import { updateSigningPlaceholder } from '../helpers/update-signing-placeholder';
2023-09-25 15:57:10 +10:00
export type SignWithLocalCertOptions = {
pdf: Buffer;
};
export const signWithLocalCert = async ({ pdf }: SignWithLocalCertOptions) => {
2024-03-15 22:26:09 +11:00
const { pdf: pdfWithPlaceholder, byteRange } = updateSigningPlaceholder({
pdf: await addSigningPlaceholder({ pdf }),
});
const pdfWithoutSignature = Buffer.concat([
pdfWithPlaceholder.subarray(0, byteRange[1]),
pdfWithPlaceholder.subarray(byteRange[2]),
]);
const signatureLength = byteRange[2] - byteRange[1];
2023-09-25 15:57:10 +10:00
2024-03-15 22:26:09 +11:00
let cert: Buffer | null = null;
2023-09-25 15:57:10 +10:00
if (process.env.NEXT_PRIVATE_SIGNING_LOCAL_FILE_CONTENTS) {
2024-03-15 22:26:09 +11:00
cert = Buffer.from(process.env.NEXT_PRIVATE_SIGNING_LOCAL_FILE_CONTENTS, 'base64');
2023-09-25 15:57:10 +10:00
}
2024-03-15 22:26:09 +11:00
if (!cert) {
cert = Buffer.from(
2023-09-25 15:57:10 +10:00
fs.readFileSync(process.env.NEXT_PRIVATE_SIGNING_LOCAL_FILE_PATH || './example/cert.p12'),
);
}
2024-03-15 22:26:09 +11:00
const signature = signWithP12({
cert,
content: pdfWithoutSignature,
password: process.env.NEXT_PRIVATE_SIGNING_PASSPHRASE || undefined,
});
const signatureAsHex = signature.toString('hex');
const signedPdf = Buffer.concat([
pdfWithPlaceholder.subarray(0, byteRange[1]),
Buffer.from(`<${signatureAsHex.padEnd(signatureLength - 2, '0')}>`),
pdfWithPlaceholder.subarray(byteRange[2]),
]);
2023-09-25 15:57:10 +10:00
2024-03-15 22:26:09 +11:00
return signedPdf;
2023-09-25 15:57:10 +10:00
};