166 lines
6.5 KiB
TypeScript
166 lines
6.5 KiB
TypeScript
import { createHash, randomBytes } from "node:crypto";
|
|
import { readFile } from "node:fs/promises";
|
|
import { createRequire } from "node:module";
|
|
import { plainAddPlaceholder } from "@signpdf/placeholder-plain";
|
|
import { P12Signer } from "@signpdf/signer-p12";
|
|
import { SignPdf } from "@signpdf/signpdf";
|
|
|
|
const requireNode = createRequire(import.meta.url);
|
|
const SUBFILTER_ETSI_CADES_DETACHED = "ETSI.CAdES.detached";
|
|
|
|
export type PadesSealResult = {
|
|
readonly bytes: Uint8Array;
|
|
readonly mode: "pades_cades_detached" | "unsigned_dev_fallback";
|
|
readonly signedPdfSha256: string;
|
|
readonly certificateConfigured: boolean;
|
|
readonly tsa: null | {
|
|
readonly url: string;
|
|
readonly requestSha256: string;
|
|
readonly responseSha256: string;
|
|
readonly responseBase64: string;
|
|
};
|
|
};
|
|
|
|
type PadesSealConfig = {
|
|
readonly p12Base64?: string;
|
|
readonly p12Path?: string;
|
|
readonly p12Passphrase?: string;
|
|
readonly tsaUrl?: string;
|
|
readonly tsaAuthorizationHeader?: string;
|
|
readonly requirePades: boolean;
|
|
readonly signatureLength: number;
|
|
};
|
|
|
|
type ForgeModule = {
|
|
readonly asn1: {
|
|
readonly Class: { readonly UNIVERSAL: number };
|
|
readonly Type: { readonly SEQUENCE: number; readonly INTEGER: number; readonly OCTETSTRING: number; readonly OID: number; readonly NULL: number; readonly BOOLEAN: number };
|
|
create(tagClass: number, type: number, constructed: boolean, value: string | readonly unknown[]): unknown;
|
|
oidToDer(oid: string): { getBytes(): string };
|
|
toDer(node: unknown): { getBytes(): string };
|
|
};
|
|
};
|
|
|
|
function getEnv(name: string): string | undefined {
|
|
const value = process.env[name]?.trim();
|
|
return value ? value : undefined;
|
|
}
|
|
|
|
function resolvePadesSealConfig(): PadesSealConfig {
|
|
return {
|
|
p12Base64: getEnv("SIGNATURE_P12_BASE64"),
|
|
p12Path: getEnv("SIGNATURE_P12_PATH"),
|
|
p12Passphrase: process.env.SIGNATURE_P12_PASSPHRASE ?? "",
|
|
tsaUrl: getEnv("SIGNATURE_TSA_URL"),
|
|
tsaAuthorizationHeader: getEnv("SIGNATURE_TSA_AUTHORIZATION"),
|
|
requirePades: getEnv("SIGNATURE_REQUIRE_PADES") === "true",
|
|
signatureLength: Number(getEnv("SIGNATURE_PLACEHOLDER_LENGTH") ?? "32768"),
|
|
};
|
|
}
|
|
|
|
function sha256Hex(bytes: Uint8Array): string {
|
|
return createHash("sha256").update(bytes).digest("hex");
|
|
}
|
|
|
|
function binaryString(bytes: Uint8Array): string {
|
|
return Buffer.from(bytes).toString("binary");
|
|
}
|
|
|
|
async function loadP12Buffer(config: PadesSealConfig): Promise<Buffer | null> {
|
|
if (config.p12Base64) return Buffer.from(config.p12Base64, "base64");
|
|
if (config.p12Path) return readFile(config.p12Path);
|
|
return null;
|
|
}
|
|
|
|
export function buildRfc3161TimestampRequest(messageHash: Uint8Array, nonce: Uint8Array = randomBytes(16)): Buffer {
|
|
const forge = requireNode("node-forge") as ForgeModule;
|
|
const asn1 = forge.asn1;
|
|
const positiveNonce = nonce[0] && nonce[0] >= 0x80 ? Buffer.concat([Buffer.from([0]), Buffer.from(nonce)]) : Buffer.from(nonce);
|
|
const sha256Algorithm = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
|
|
asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, asn1.oidToDer("2.16.840.1.101.3.4.2.1").getBytes()),
|
|
asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, ""),
|
|
]);
|
|
const messageImprint = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
|
|
sha256Algorithm,
|
|
asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, binaryString(messageHash)),
|
|
]);
|
|
const request = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [
|
|
asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, binaryString(Buffer.from([1]))),
|
|
messageImprint,
|
|
asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, binaryString(positiveNonce)),
|
|
asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BOOLEAN, false, binaryString(Buffer.from([0xff]))),
|
|
]);
|
|
return Buffer.from(asn1.toDer(request).getBytes(), "binary");
|
|
}
|
|
|
|
async function requestTimestampToken(input: { tsaUrl: string; authorizationHeader?: string; pdfBytes: Uint8Array }) {
|
|
const messageHash = createHash("sha256").update(input.pdfBytes).digest();
|
|
const requestBody = buildRfc3161TimestampRequest(messageHash);
|
|
const requestArrayBuffer = requestBody.buffer.slice(requestBody.byteOffset, requestBody.byteOffset + requestBody.byteLength) as ArrayBuffer;
|
|
const response = await fetch(input.tsaUrl, {
|
|
method: "POST",
|
|
headers: {
|
|
"Content-Type": "application/timestamp-query",
|
|
Accept: "application/timestamp-reply",
|
|
...(input.authorizationHeader ? { Authorization: input.authorizationHeader } : {}),
|
|
},
|
|
body: requestArrayBuffer,
|
|
});
|
|
if (!response.ok) {
|
|
throw new Error(`TSA request failed with status ${response.status}`);
|
|
}
|
|
const responseBytes = new Uint8Array(await response.arrayBuffer());
|
|
return {
|
|
url: input.tsaUrl,
|
|
requestSha256: sha256Hex(requestBody),
|
|
responseSha256: sha256Hex(responseBytes),
|
|
responseBase64: Buffer.from(responseBytes).toString("base64"),
|
|
};
|
|
}
|
|
|
|
export async function sealPdfWithPades(input: {
|
|
readonly pdfBytes: Uint8Array;
|
|
readonly title: string;
|
|
readonly signerName: string;
|
|
readonly contactInfo: string;
|
|
readonly location: string;
|
|
readonly reason: string;
|
|
readonly signingTime?: Date;
|
|
}): Promise<PadesSealResult> {
|
|
const config = resolvePadesSealConfig();
|
|
const p12Buffer = await loadP12Buffer(config);
|
|
if (!p12Buffer) {
|
|
if (config.requirePades) throw new Error("SIGNATURE_P12_BASE64 or SIGNATURE_P12_PATH is required when SIGNATURE_REQUIRE_PADES=true.");
|
|
return {
|
|
bytes: input.pdfBytes,
|
|
mode: "unsigned_dev_fallback",
|
|
signedPdfSha256: sha256Hex(input.pdfBytes),
|
|
certificateConfigured: false,
|
|
tsa: null,
|
|
};
|
|
}
|
|
|
|
const signingTime = input.signingTime ?? new Date();
|
|
const pdfWithPlaceholder = plainAddPlaceholder({
|
|
pdfBuffer: Buffer.from(input.pdfBytes),
|
|
reason: input.reason,
|
|
contactInfo: input.contactInfo,
|
|
name: input.signerName,
|
|
location: input.location,
|
|
signingTime,
|
|
signatureLength: Number.isFinite(config.signatureLength) && config.signatureLength > 0 ? config.signatureLength : 32768,
|
|
subFilter: SUBFILTER_ETSI_CADES_DETACHED,
|
|
appName: "HiveGrid",
|
|
});
|
|
const signer = new P12Signer(p12Buffer, { passphrase: config.p12Passphrase, asn1StrictParsing: false });
|
|
const signed = await new SignPdf().sign(pdfWithPlaceholder, signer, signingTime);
|
|
const tsa = config.tsaUrl ? await requestTimestampToken({ tsaUrl: config.tsaUrl, authorizationHeader: config.tsaAuthorizationHeader, pdfBytes: signed }) : null;
|
|
return {
|
|
bytes: signed,
|
|
mode: "pades_cades_detached",
|
|
signedPdfSha256: sha256Hex(signed),
|
|
certificateConfigured: true,
|
|
tsa,
|
|
};
|
|
}
|