# @embedpdf/core-signature — . AddValidationInfoOptions [InterfaceDeclaration] (from packages/core/signature/src/collect.ts): export interface AddValidationInfoOptions{ trust: TrustPort; revocation?: RevocationSource | null; known?: Partial; fields?: readonly FormFieldRef[]; partial?: boolean; maxCrlBytes?: number; } AddValidationInfoResult [InterfaceDeclaration] (from packages/core/signature/src/collect.ts): export interface AddValidationInfoResult{ added: ValidationInfoCounts; verdicts: SignatureVerdict[]; } AppliedValidationTime [TypeAliasDeclaration] (from packages/core/signature/src/trust.ts): export type AppliedValidationTime = |{ readonly kind: 'now'} |{ readonly kind: 'timestamp'; readonly stampedAt: string; readonly tokenVerified: true; readonly genTime: string; } ; BuildDetachedCmsInput [InterfaceDeclaration] (from packages/core/signature/src/cms/build.ts): export interface BuildDetachedCmsInput{ digest: Uint8Array; hash: Exclude; profile: SignatureProfile; signer: RawSigner; signingTime?: string; } CmsError [ClassDeclaration] (from packages/core/signature/src/cms/error.ts): export class CmsError extends Error{ constructor( readonly reason: 'malformed' | 'unsupported', message: string, ){ super(message); this.name = 'CmsError'; } } CmsSigner [InterfaceDeclaration] (from packages/core/signature/src/sign.ts): export interface CmsSigner{ readonly kind: 'cms'; readonly hash?: Exclude; sign(input:{ digest: Uint8Array; algorithm: Exclude; subFilter: SignatureSubFilter | 'ETSI.RFC3161'; } ): Promise; } CompletionGate [TypeAliasDeclaration] (from packages/core/signature/src/gate.ts): export type CompletionGate = |{ ok: true} |{ ok: false; reason: CompletionRefusal; detail: string} ; CompletionProfile [TypeAliasDeclaration] (from packages/core/signature/src/gate.ts): export type CompletionProfile = SignatureProfile | 'timestamp'; CompletionRefusal [TypeAliasDeclaration] (from packages/core/signature/src/gate.ts): export type CompletionRefusal = | 'malformed' | 'too-large' | 'algorithm-mismatch' | 'digest-mismatch' | 'signature-invalid' | 'profile-violation'; CryptographyVerdict [TypeAliasDeclaration] (from packages/core/signature/src/cms/verify.ts): export type CryptographyVerdict = 'valid' | 'invalid' | 'unsupported'; HttpRevocationSourceOptions [InterfaceDeclaration] (from packages/core/signature/src/revocation/http-source.ts): export interface HttpRevocationSourceOptions{ url: string; headers?: Record; fetch?: typeof globalThis.fetch; timeoutMs?: number; retries?: number; } HttpTimestampAuthorityOptions [InterfaceDeclaration] (from packages/core/signature/src/signers/timestamp-http.ts): export interface HttpTimestampAuthorityOptions{ url: string; hash?: Exclude; policy?: string; headers?: Record; fetch?: typeof globalThis.fetch; timeoutMs?: number; retries?: number; } IntegrityVerdict [TypeAliasDeclaration] (from packages/core/signature/src/verdict.ts): export type IntegrityVerdict = 'valid' | 'invalid' | 'indeterminate'; LongTermGap [InterfaceDeclaration] (from packages/core/signature/src/long-term.ts): export interface LongTermGap{ certificate: string | null; reason: LongTermGapReason; } LongTermGapReason [TypeAliasDeclaration] (from packages/core/signature/src/long-term.ts): export type LongTermGapReason = 'no-timestamp' | 'untrusted' | 'no-answer' | 'revoked'; LongTermVerdict [InterfaceDeclaration] (from packages/core/signature/src/long-term.ts): export interface LongTermVerdict{ enabled: boolean; provenAt: string | null; expiresAt: string | null; documentTimestampedAt: string | null; missing: LongTermGap[]; } ModificationsVerdict [TypeAliasDeclaration] (from packages/core/signature/src/verdict.ts): export type ModificationsVerdict = 'unchanged' | 'permitted' | 'forbidden' | 'indeterminate'; ParsedCms [InterfaceDeclaration] (from packages/core/signature/src/cms/parse.ts): export interface ParsedCms{ digestAlgorithm: DigestAlgorithm; messageDigest: Uint8Array; signingTime: string | null; signerCertificate: Uint8Array; certificates: Uint8Array[]; signatureAlgorithm: string; signingCertificateV2: boolean; timestampToken: Uint8Array | null; } PersonalKeyRecord [InterfaceDeclaration] (from packages/core/signature/src/signers/personal.ts): export interface PersonalKeyRecord{ privateKey: CryptoKey; certificate: Uint8Array; } PersonalKeyStore [InterfaceDeclaration] (from packages/core/signature/src/signers/personal.ts): export interface PersonalKeyStore{ load(subject: string): Promise; save(subject: string, record: PersonalKeyRecord): Promise; remove(subject: string): Promise; } PersonalSigner [InterfaceDeclaration] (from packages/core/signature/src/signers/personal.ts): export interface PersonalSigner extends RawSigner{ readonly certificate: Uint8Array; readonly subject: string; } RawSignatureAlgorithm [TypeAliasDeclaration] (from packages/core/signature/src/cms/build.ts): export type RawSignatureAlgorithm = 'RSA-PKCS1-v1_5' | 'RSA-PSS' | 'ECDSA'; RawSigner [InterfaceDeclaration] (from packages/core/signature/src/cms/build.ts): export interface RawSigner{ readonly kind: 'raw'; readonly certificateChain: Uint8Array[]; readonly algorithm: RawSignatureAlgorithm; readonly hash: Exclude; sign(signedAttributesDer: Uint8Array): Promise; } RevocationReason [TypeAliasDeclaration] (from packages/core/signature/src/revocation/answer.ts): export type RevocationReason = | 'unspecified' | 'key-compromise' | 'ca-compromise' | 'affiliation-changed' | 'superseded' | 'cessation-of-operation' | 'certificate-hold' | 'remove-from-crl' | 'privilege-withdrawn' | 'aa-compromise'; RevocationRequest [TypeAliasDeclaration] (from packages/core/signature/src/revocation/source.ts): export type RevocationRequest = |{ kind: 'ocsp'; url: string; body: Uint8Array} |{ kind: 'crl'; url: string} |{ kind: 'issuer'; url: string} ; RevocationRouteRequest [InterfaceDeclaration] (from packages/core/signature/src/revocation/http-source.ts): export interface RevocationRouteRequest{ kind: RevocationRequest['kind']; url: string; body?: string; } RevocationSource [InterfaceDeclaration] (from packages/core/signature/src/revocation/source.ts): export interface RevocationSource{ fetch(request: RevocationRequest): Promise; } RevocationVerdict [TypeAliasDeclaration] (from packages/core/signature/src/long-term.ts): export type RevocationVerdict = 'good' | 'revoked' | 'unknown'; SignInput [TypeAliasDeclaration] (from packages/core/signature/src/sign.ts): export type SignInput = SignaturePrepareInput &{ key: SignerPort; timestampAuthority?: CmsSigner; timestampTrust?: TrustPort; } ; SignatureProfile [TypeAliasDeclaration] (from packages/core/signature/src/cms/build.ts): export type SignatureProfile = 'pkcs7' | 'cades-b'; SignatureVerdict [InterfaceDeclaration] (from packages/core/signature/src/verdict.ts): export interface SignatureVerdict{ signature: Signature; integrity: IntegrityVerdict; cryptography: CryptographyVerdict; trust: TrustStatus; trustReason?: string; validationTime: AppliedValidationTime; revocation: RevocationVerdict; revocationReason?: string; modifications:{ verdict: ModificationsVerdict; detail?: string; basis: 'persisted' | 'working-copy'; laterRevisions?: number; undone?: boolean; } ; summary: 'valid' | 'valid-untrusted' | 'invalid' | 'indeterminate'; cms: ParsedCms | null; timestamp: TimestampVerdict | null; longTerm: LongTermVerdict; } SignerPort [TypeAliasDeclaration] (from packages/core/signature/src/sign.ts): export type SignerPort = CmsSigner | RawSigner; TestCertificateAuthority [InterfaceDeclaration] (from packages/core/signature/src/signers/test-authority.ts): export interface TestCertificateAuthority{ readonly certificate: Uint8Array; issueSigner(options?:{ commonName?: string; algorithm?: 'RSA-PKCS1-v1_5' | 'RSA-PSS' | 'ECDSA'; hash?: 'sha256' | 'sha384' | 'sha512'; unrevocable?: Unrevocable; } ): Promise; readonly revocation: RevocationSource; revoke( signer: Pick | Uint8Array, options?:{ at?: Date; reason?: RevocationReason} , ): void; } TestSigner [InterfaceDeclaration] (from packages/core/signature/src/signers/webcrypto.ts): export interface TestSigner extends RawSigner{ readonly certificate: Uint8Array; readonly privateKey: CryptoKey; } TestTimestampAuthority [InterfaceDeclaration] (from packages/core/signature/src/signers/webcrypto.ts): export interface TestTimestampAuthority extends CmsSigner{ readonly certificate: Uint8Array; } TimestampVerdict [TypeAliasDeclaration] (from packages/core/signature/src/verdict.ts): export type TimestampVerdict = TimestampFacts & ( |{ readonly summary: 'valid' | 'valid-untrusted'; readonly stampedAt: string; readonly authorityCertificate: Uint8Array; } |{ readonly summary: 'invalid' | 'indeterminate'; readonly stampedAt: string | null; readonly authorityCertificate: Uint8Array | null; } ); TrustPort [InterfaceDeclaration] (from packages/core/signature/src/trust.ts): export interface TrustPort{ anchors(): Promise; timestampAnchors?(): Promise; } TrustStatus [TypeAliasDeclaration] (from packages/core/signature/src/trust.ts): export type TrustStatus = 'trusted' | 'untrusted' | 'unknown'; TrustVerdict [InterfaceDeclaration] (from packages/core/signature/src/trust.ts): export interface TrustVerdict{ status: TrustStatus; reason?: string; path?: Uint8Array[]; withoutIssuer?: Uint8Array; } Unrevocable [TypeAliasDeclaration] (from packages/core/signature/src/signers/test-authority.ts): export type Unrevocable = 'validity-assured' | 'no-rev-avail'; ValidateSignaturesOptions [InterfaceDeclaration] (from packages/core/signature/src/verdict.ts): export interface ValidateSignaturesOptions{ trust?: TrustPort | null; validationTime?: ValidationTime |{ kind: 'earliest-timestamp'} ; revocation?: RevocationSource | null; until?: 'persisted' | 'working-copy'; } ValidationTime [TypeAliasDeclaration] (from packages/core/signature/src/trust.ts): export type ValidationTime = |{ kind: 'now'} |{ kind: 'timestamp'; stampedAt: string; tokenVerified: true; genTime?: string; } |{ kind: 'timestamp'; genTime: string; tokenVerified: true; stampedAt?: undefined; } ; addValidationInfo [FunctionDeclaration] (from packages/core/signature/src/collect.ts): export async function addValidationInfo( doc: DocumentHandle, options: AddValidationInfoOptions, ): Promise{ if (!doc.signatures) throw new Error('this engine does not implement signatures'); if (!options?.trust){ throw new EngineError( EngineErrorCode.InvalidArg, 'addValidationInfo() needs `trust`: the answers kept are the ones for paths you trust', { details:{ field: 'trust'} } , ); } const{ trust} = options; await doc.signatures.addValidationInfo({ } ); const snapshot = await doc.signatures.list(); const pool = await readValidationPool(doc); const readings: Reading[] = []; for (const signature of snapshot.signatures){ if (signature.signed) readings.push(await read(doc, snapshot, signature, pool)); } const wanted = wantedAmong(readings, options.fields); for (const der of options.known?.certificates ?? []) pool.addCertificate(der, false); for (const der of options.known?.ocspResponses ?? []) pool.addAnswer('ocsp', der, false); for (const der of options.known?.crls ?? []) pool.addAnswer('crl', der, false); const problems = await fillPool({ readings, wanted: (reading) => wanted.has(reading), trust, pool, source: options.revocation ?? null, maxCrlBytes: options.maxCrlBytes ?? DEFAULT_MAX_CRL_BYTES, times: [EARLIEST], } ); const judged = await judge(readings, trust, pool, EARLIEST); const store ={ certificates: new Map(), ocspResponses: new Map(), crls: new Map(), } ; const keep = (list: Map, der: Uint8Array) => list.set(toHex(der), der); for (const reading of readings){ if (!wanted.has(reading)) continue; const judgement = judged.judgements.get(reading)!; const findings = await longTermFindings( longTermInputOf(reading, judgement, judged.documentTimestamps, pool, 'anywhere'), ); if (!findings.verdict.enabled && !options.partial){ throw failureOf(reading, findings, problems); } for (const path of [judgement.path, judgement.reliesOn?.path]){ for (const der of path ?? []) keep(store.certificates, der); } for (const row of findings.rows){ if (row.evidence && !row.evidence.inFile){ keep(row.evidence.kind === 'ocsp' ? store.ocspResponses : store.crls, row.evidence.der); } if (row.answer && row.answer.says !== 'nothing' && row.answer.responder){ keep(store.certificates, row.answer.responder); } } } let added: ValidationInfoCounts ={ certificates: 0, ocspResponses: 0, crls: 0} ; if (store.certificates.size + store.ocspResponses.size + store.crls.size > 0){ const stored = await doc.signatures.addValidationInfo({ certificates: [...store.certificates.values()], ocspResponses: [...store.ocspResponses.values()], crls: [...store.crls.values()], } ); added = stored.added; } const verdicts = await validateSignatures(doc, { trust} ); if (!options.partial){ for (const reading of readings){ if (!wanted.has(reading)) continue; const verdict = verdicts.find((entry) => entry.signature.index === reading.signature.index); if (!verdict?.longTerm.enabled){ throw new EngineError( EngineErrorCode.Unknown, `the validation data was stored, and the signature in "${ reading.signature.fieldName} " still does not read as complete`, { details:{ field: reading.signature.fieldName, missing: verdict?.longTerm.missing} } , ); } } } return{ added, verdicts} ; } attachSignatureTimestamp [FunctionDeclaration] (from packages/core/signature/src/cms/attach.ts): export async function attachSignatureTimestamp(input:{ cms: Uint8Array; authority: CmsSigner; trust?: TrustPort; } ): Promise{ const{ cms, authority} = input; let parts: CmsParts; try{ parts = readCmsParts(cms); } catch (error){ throw signingRefused('malformed', error instanceof CmsError ? error.message : String(error)); } if (parts.timestampTokens.length > 0){ throw new EngineError( EngineErrorCode.InvalidArg, 'the signature already carries a timestamp, from the service that signed it; leave out `timestampAuthority`', { details:{ field: 'timestampAuthority'} } , ); } const algorithm = authority.hash ?? 'sha256'; const digest = new Uint8Array( await ensureEngine().digest( WEBCRYPTO_HASH[algorithm], toArrayBuffer(signatureValueOf(parts.signerInfo)), ), ); const token = await authority.sign({ digest, algorithm, subFilter: 'ETSI.RFC3161'} ); const check = await checkTimestampToken({ token, stamped:{ kind: 'digest', digest, algorithm} , certificates: parts.certificates, } ); if (check.verdict !== 'valid'){ throw signingRefused(refusalFor(check.problem!), `the timestamp: ${ detailFor(check)} `); } if (input.trust) await requireTrustedAuthority(check, input.trust, parts.certificates); try{ return addUnsignedAttribute(cms, timestampTokenAttribute(token)); } catch (error){ throw signingRefused('malformed', error instanceof CmsError ? error.message : String(error)); } } buildDetachedCms [FunctionDeclaration] (from packages/core/signature/src/cms/build.ts): export async function buildDetachedCms(input: BuildDetachedCmsInput): Promise{ const engine = ensureEngine(); if (input.digest.byteLength !== DIGEST_LENGTH[input.hash]){ throw new Error( `digest is ${ input.digest.byteLength} bytes; ${ input.hash} needs ${ DIGEST_LENGTH[input.hash]} `, ); } if (input.signer.hash !== input.hash){ throw new Error( `the signer hashes with ${ input.signer.hash} , the document was prepared with ${ input.hash} `, ); } if (input.signer.certificateChain.length === 0){ throw new Error('the signer carries no certificate'); } const chain = input.signer.certificateChain.map((der) => pkijs.Certificate.fromBER(toArrayBuffer(der)), ); const signerCert = chain[0]; const attributes: pkijs.Attribute[] = [ new pkijs.Attribute({ type: OID.contentType, values: [new asn1js.ObjectIdentifier({ value: OID.data} )], } ), new pkijs.Attribute({ type: OID.messageDigest, values: [new asn1js.OctetString({ valueHex: toArrayBuffer(input.digest)} )], } ), ]; if (input.profile === 'pkcs7' && input.signingTime){ attributes.push( new pkijs.Attribute({ type: OID.signingTime, values: [cmsTime(new Date(input.signingTime))], } ), ); } if (input.profile === 'cades-b'){ const certHash = await engine.digest( 'SHA-256', toArrayBuffer(input.signer.certificateChain[0]), ); const issuerSerial = new pkijs.IssuerSerial({ issuer: new pkijs.GeneralNames({ names: [new pkijs.GeneralName({ type: 4, value: signerCert.issuer} )], } ), serialNumber: signerCert.serialNumber, } ); const essCertId = new asn1js.Sequence({ value: [new asn1js.OctetString({ valueHex: certHash} ), issuerSerial.toSchema()], } ); attributes.push( new pkijs.Attribute({ type: OID.signingCertificateV2, values: [new asn1js.Sequence({ value: [new asn1js.Sequence({ value: [essCertId]} )]} )], } ), ); } const digestAlgorithm = new pkijs.AlgorithmIdentifier({ algorithmId: OID_BY_DIGEST[input.hash]} ); const signerInfo = new pkijs.SignerInfo({ version: 1, sid: new pkijs.IssuerAndSerialNumber({ issuer: signerCert.issuer, serialNumber: signerCert.serialNumber, } ), digestAlgorithm, signedAttrs: signedAttributesOf(attributes), signatureAlgorithm: signatureAlgorithmFor(input.signer.algorithm, input.hash), } ); const raw = await input.signer.sign(signedAttributesDer(signerInfo)); signerInfo.signature = new asn1js.OctetString({ valueHex: cmsSignatureValue(input.signer.algorithm, raw), } ); const signedData = new pkijs.SignedData({ version: 1, digestAlgorithms: [digestAlgorithm], encapContentInfo: new pkijs.EncapsulatedContentInfo({ eContentType: OID.data} ), certificates: chain, signerInfos: [signerInfo], } ); const contentInfo = new pkijs.ContentInfo({ contentType: OID.signedData, content: signedData.toSchema(true), } ); return new Uint8Array(contentInfo.toSchema().toBER(false)); } certificateCommonName [FunctionDeclaration] (from packages/core/signature/src/signers/self-signed.ts): export function certificateCommonName(der: Uint8Array): string | null{ ensureEngine(); const copy = new Uint8Array(der.byteLength); copy.set(der); const cert = pkijs.Certificate.fromBER(copy.buffer); const cn = cert.subject.typesAndValues.find((entry) => entry.type === OID.commonName); const value = cn?.value as{ valueBlock?:{ value?: unknown} } | undefined; const text = value?.valueBlock?.value; return typeof text === 'string' && text.length > 0 ? text : null; } completeSignature [FunctionDeclaration] (from packages/core/signature/src/sign.ts): export async function completeSignature( doc: DocumentHandle, input:{ prepared: SignaturePrepared; cms: Uint8Array; timestampAuthority?: CmsSigner; timestampTrust?: TrustPort; } , ): Promise{ assertTimestampOptions( input.prepared.subFilter === 'ETSI.RFC3161', input.timestampAuthority, input.timestampTrust, ); try{ return await completePrepared(doc, input); } catch (error){ if (EngineError.is(error, EngineErrorCode.SignatureRefused)){ throw new EngineError( EngineErrorCode.SignatureRefused, `${ error.message} . The signing stays prepared, and this CMS will be refused again: cancel it and prepare again`, { details: error.details, cause: error} , ); } throw error; } } createTestCertificateAuthority [FunctionDeclaration] (from packages/core/signature/src/signers/test-authority.ts): export async function createTestCertificateAuthority( options:{ commonName?: string; url?: string; now?: () => Date} ={ } , ): Promise{ ensureEngine(); const now = options.now ?? (() => new Date()); const url = (options.url ?? 'http://test-authority.example').replace(/\/$/, ''); const addresses ={ ocsp: `${ url} /ocsp`, crl: `${ url} /crl`, issuer: `${ url} /issuer`} ; const commonName = options.commonName ?? 'EmbedPDF test certificate authority'; const dates = () => ({ notBefore: new Date(now().getTime() - DAY), notAfter: new Date(now().getTime() + 365 * DAY), } ); const rootKeys = await generateSigningKeyPair('RSA-PKCS1-v1_5', 'sha256', true); const root: Issuer ={ certificate: await issueCertificate({ kind: 'authority', commonName, publicKey: rootKeys.publicKey, privateKey: rootKeys.privateKey, ...dates(), } ), privateKey: rootKeys.privateKey, } ; const responderKeys = await generateSigningKeyPair('RSA-PKCS1-v1_5', 'sha256', true); const responder: Issuer ={ certificate: await issueCertificate({ kind: 'responder', commonName: `${ commonName} (OCSP responder)`, publicKey: responderKeys.publicKey, issuer: root, ...dates(), } ), privateKey: responderKeys.privateKey, } ; const der = (certificate: pkijs.Certificate) => new Uint8Array(certificate.toSchema(true).toBER(false)); const rootDer = der(root.certificate); const issued: pkijs.Certificate[] = []; const unrevocableOnes = new Set(); const revoked = new Map(); const serialOf = (certificate: pkijs.Certificate) => new Uint8Array(certificate.serialNumber.valueBlock.valueHexView); const bySerial = (serial: Uint8Array) => issued.find((certificate) => bytesEqual(serialOf(certificate), serial)) ?? null; const answer = async (request: RevocationRequest): Promise =>{ if (!request.url.startsWith(url)){ throw new Error(`the test certificate authority does not answer at ${ request.url} `); } if (request.kind === 'issuer') return rootDer; if (request.kind === 'crl'){ return buildCrl({ issuer: root, thisUpdate: now(), nextUpdate: new Date(now().getTime() + 7 * DAY), revoked: [...revoked].map(([certificate, entry]) => ({ serialNumber: certificate.serialNumber, at: entry.at, reason: entry.reason, } )), } ); } const parsed = asn1js.fromBER(toArrayBuffer(request.body)); if (parsed.offset === -1) throw new Error('the OCSP request is not valid DER'); const asked = new pkijs.OCSPRequest({ schema: parsed.result} ).tbsRequest.requestList[0]; if (!asked) throw new Error('the OCSP request asks about no certificate'); const certificate = bySerial( new Uint8Array(asked.reqCert.serialNumber.valueBlock.valueHexView), ); const entry = certificate ? revoked.get(certificate) : undefined; return buildOcspResponse({ certificate: certificate ?? root.certificate, issuer: root.certificate, asked: asked.reqCert, signer: responder, status: !certificate ? 'unknown' : entry ?{ revokedAt: entry.at, reason: entry.reason} : 'good', producedAt: now(), thisUpdate: now(), nextUpdate: new Date(now().getTime() + HOUR), } ); } ; return{ certificate: rootDer, async issueSigner(signerOptions ={ } ){ const hash = signerOptions.hash ?? 'sha256'; const keys = await generateSigningKeyPair( signerOptions.algorithm ?? 'RSA-PKCS1-v1_5', hash, true, ); const{ unrevocable} = signerOptions; const certificate = await issueCertificate({ kind: 'signer', commonName: signerOptions.commonName ?? 'EmbedPDF test signer', publicKey: keys.publicKey, issuer: root, addresses: unrevocable ?{ issuer: addresses.issuer} : addresses, ...(unrevocable ?{ unrevocable} :{ } ), ...dates(), } ); issued.push(certificate); if (unrevocable) unrevocableOnes.add(certificate); const leaf = der(certificate); const signer = webCryptoSigner({ privateKey: keys.privateKey, certificateChain: [leaf, rootDer], hash, } ); return{ ...signer, certificate: leaf, privateKey: keys.privateKey} ; } , revocation:{ fetch: answer} , revoke(signer, revokeOptions ={ } ){ const bytes = signer instanceof Uint8Array ? signer : signer.certificate; const certificate = issued.find((candidate) => bytesEqual(der(candidate), bytes)); if (!certificate){ throw new Error('the test certificate authority did not issue this certificate'); } if (unrevocableOnes.has(certificate)){ throw new Error('this certificate was issued as one that cannot be withdrawn'); } revoked.set(certificate, { at: revokeOptions.at ?? now(), reason: revokeOptions.reason ?? null, } ); } , } ; } createTestSigner [FunctionDeclaration] (from packages/core/signature/src/signers/webcrypto.ts): export async function createTestSigner( options:{ commonName?: string; algorithm?: 'RSA-PKCS1-v1_5' | 'RSA-PSS' | 'ECDSA'; hash?: 'sha256' | 'sha384' | 'sha512'; } ={ } , ): Promise{ const{ selfSignedCertificate} = await import('./self-signed'); const hash = options.hash ?? 'sha256'; const keys = await generateSigningKeyPair(options.algorithm ?? 'RSA-PKCS1-v1_5', hash, true); const certificate = await selfSignedCertificate({ publicKey: keys.publicKey, privateKey: keys.privateKey, commonName: options.commonName ?? 'EmbedPDF test signer', hash, } ); const signer = webCryptoSigner({ privateKey: keys.privateKey, certificateChain: [certificate], hash, } ); return{ ...signer, certificate, privateKey: keys.privateKey} ; } createTestTimestampAuthority [FunctionDeclaration] (from packages/core/signature/src/signers/webcrypto.ts): export async function createTestTimestampAuthority( options:{ commonName?: string} ={ } , ): Promise{ const{ timestampAuthorityCertificate} = await import('./self-signed'); const keys = await generateSigningKeyPair('RSA-PKCS1-v1_5', 'sha256', true); const certificate = await timestampAuthorityCertificate({ publicKey: keys.publicKey, privateKey: keys.privateKey, commonName: options.commonName ?? 'EmbedPDF test timestamp authority', hash: 'sha256', } ); const authority = webCryptoSigner({ privateKey: keys.privateKey, certificateChain: [certificate], } ); const{ buildTimestampToken} = await import('../cms/timestamp'); return{ kind: 'cms', certificate, sign: ({ digest, algorithm} ) => buildTimestampToken({ digest, hash: algorithm, authority} ), } ; } ecdsaRawFromDer [FunctionDeclaration] (from packages/core/signature/src/signers/ecdsa.ts): export function ecdsaRawFromDer(der: Uint8Array, curve: 'P-256' | 'P-384' | 'P-521'): Uint8Array{ const size = NUMBER_SIZE[curve]; const invalid = (why: string) => new EngineError(EngineErrorCode.InvalidArg, `not a DER ECDSA signature: ${ why} `, { details:{ field: 'der'} , } ); let numbers; try{ const sequence = readElement(der, 0, der.byteLength); if (sequence.tag !== 0x30) throw invalid('it is not a sequence'); numbers = childrenOf(der, sequence); } catch (error){ throw error instanceof CmsError ? invalid('it does not parse') : error; } if (numbers.length !== 2 || numbers.some((number) => number.tag !== 0x02)){ throw invalid('it does not hold two integers'); } const raw = new Uint8Array(size * 2); numbers.forEach((number, index) =>{ let start = number.contentStart; while (start < number.contentEnd - 1 && der[start] === 0) start++; const length = number.contentEnd - start; if (length > size) throw invalid(`a number is ${ length} bytes, ${ curve} takes ${ size} `); raw.set(der.subarray(start, number.contentEnd), (index + 1) * size - length); } ); return raw; } generateSigningKeyPair [FunctionDeclaration] (from packages/core/signature/src/signers/webcrypto.ts): export async function generateSigningKeyPair( algorithm: 'RSA-PKCS1-v1_5' | 'RSA-PSS' | 'ECDSA', hash: 'sha256' | 'sha384' | 'sha512', extractable: boolean, ): Promise{ return (await globalThis.crypto.subtle.generateKey( algorithm === 'ECDSA' ?{ name: 'ECDSA', namedCurve: 'P-256'} :{ name: algorithm === 'RSA-PSS' ? 'RSA-PSS' : 'RSASSA-PKCS1-v1_5', modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]), hash: WEBCRYPTO_HASH[hash], } , extractable, ['sign', 'verify'], )) as CryptoKeyPair; } httpRevocationSource [FunctionDeclaration] (from packages/core/signature/src/revocation/http-source.ts): export function httpRevocationSource(options: HttpRevocationSourceOptions): RevocationSource{ const{ url: route, timeoutMs = 10_000, retries = 1} = options; async function ask(request: RevocationRequest): Promise{ const send = options.fetch ?? globalThis.fetch; const details = (more: Record ={ } ) => ({ source: request.url, route, ...more, } ); const noAnswer = (why: string, cause?: unknown) => new EngineError( EngineErrorCode.Network, `${ request.url} did not answer through ${ route} : ${ why} `, { details: details(), cause} , ); const payload: RevocationRouteRequest ={ kind: request.kind, url: request.url, ...(request.kind === 'ocsp' ?{ body: toBase64(request.body)} :{ } ), } ; const timeout = new AbortController(); const timer = setTimeout(() => timeout.abort(), timeoutMs); try{ let response: Response; try{ response = await send(route, { method: 'POST', headers:{ 'content-type': 'application/json', ...options.headers} , body: JSON.stringify(payload), signal: timeout.signal, } ); } catch (error){ if (timeout.signal.aborted) throw noAnswer(`no reply within ${ timeoutMs} ms`, error); throw noAnswer((error as Error).message, error); } if (response.status >= 500 || response.status === 429){ throw noAnswer(`HTTP ${ response.status} ${ await said(response)} `); } if (!response.ok){ const refusal = await refusalOf(response); throw new EngineError( EngineErrorCode.SignatureRefused, `the route at ${ route} refused to ask ${ request.url} : ${ refusal.message ?? `HTTP ${ response.status} `} `, { details: details({ httpStatus: response.status, reason: refusal.reason} )} , ); } try{ return new Uint8Array(await response.arrayBuffer()); } catch (error){ throw noAnswer( timeout.signal.aborted ? `no reply within ${ timeoutMs} ms` : `the reply broke off: ${ (error as Error).message} `, error, ); } } finally{ clearTimeout(timer); } } return{ async fetch(request){ for (let attempt = 0; ; attempt++){ try{ return await ask(request); } catch (error){ const noAnswer = EngineError.is(error, EngineErrorCode.Network); if (!noAnswer || attempt >= retries) throw error; await new Promise((resolve) => setTimeout(resolve, RETRY_DELAY_MS)); } } } , } ; } httpTimestampAuthority [FunctionDeclaration] (from packages/core/signature/src/signers/timestamp-http.ts): export function httpTimestampAuthority(options: HttpTimestampAuthorityOptions): CmsSigner{ const{ url, policy, timeoutMs = 10_000, retries = 1} = options; const details = (more: Record ={ } ) => ({ authority: url, ...more} ); const refused = (message: string, more: Record, cause?: unknown) => new EngineError(EngineErrorCode.SignatureRefused, message, { details: details(more), cause} ); const wrongAnswer = (reason: CompletionRefusal, what: string) => refused(`the timestamp authority at ${ url} ${ what} `, { reason} ); async function ask(query: Uint8Array): Promise{ const send = options.fetch ?? globalThis.fetch; const noAnswer = (why: string, cause?: unknown) => new EngineError( EngineErrorCode.Network, `the timestamp authority at ${ url} did not answer: ${ why} `, { details: details(), cause} , ); const timeout = new AbortController(); const timer = setTimeout(() => timeout.abort(), timeoutMs); try{ let response: Response; try{ response = await send(url, { method: 'POST', headers:{ 'content-type': 'application/timestamp-query', ...options.headers} , body: new Uint8Array(query), signal: timeout.signal, } ); } catch (error){ if (timeout.signal.aborted) throw noAnswer(`no reply within ${ timeoutMs} ms`, error); const hint = 'document' in globalThis ? '. In a browser most authorities cannot be called directly: call yours through a route on your own server' : ''; throw noAnswer(`${ (error as Error).message} ${ hint} `, error); } if (response.status >= 500 || response.status === 429){ throw noAnswer(`HTTP ${ response.status} `); } if (!response.ok){ throw refused( `the timestamp authority at ${ url} refused the request: HTTP ${ response.status} `, { httpStatus: response.status} , ); } try{ return new Uint8Array(await response.arrayBuffer()); } catch (error){ throw noAnswer( timeout.signal.aborted ? `no reply within ${ timeoutMs} ms` : `the reply broke off: ${ (error as Error).message} `, error, ); } } finally{ clearTimeout(timer); } } return{ kind: 'cms', hash: options.hash ?? 'sha256', async sign({ digest, algorithm, subFilter} ){ if (subFilter !== 'ETSI.RFC3161'){ throw new EngineError( EngineErrorCode.InvalidArg, "a timestamp authority can't sign a document: pass it as `timestampAuthority`, or sign with `kind: 'timestamp'`", { details: details()} , ); } const [protocol, parse, timestamp, engine] = await Promise.all([ import('../cms/timestamp-protocol'), import('../cms/parse'), import('../cms/timestamp'), import('../cms/engine'), ]); const nonce = engine.randomPositiveInteger(); const query = protocol.buildTimestampRequest({ digest, algorithm, policy, nonce} ); let reply: Uint8Array; for (let attempt = 0; ; attempt++){ try{ reply = await ask(query); break; } catch (error){ const noAnswer = EngineError.is(error, EngineErrorCode.Network); if (!noAnswer || attempt >= retries) throw error; await new Promise((resolve) => setTimeout(resolve, RETRY_DELAY_MS)); } } let response; try{ response = protocol.readTimestampResponse(reply); } catch (error){ throw refused( `the timestamp authority at ${ url} sent a reply that can't be read: ${ (error as Error).message} `, { reason: 'malformed'} , error, ); } if (!response.granted){ const said = [response.failInfo, response.statusText].filter(Boolean).join(': '); throw refused( `the timestamp authority at ${ url} refused the request${ said ? ` (${ said} )` : ''} `, { failInfo: response.failInfo} , ); } if (!response.token) throw wrongAnswer('malformed', 'granted the request but sent no token'); let info; try{ info = timestamp.readTimestampInfo( parse.readCmsParts(response.token, 'tst-info').eContent!, ); } catch (error){ throw refused( `the timestamp authority at ${ url} sent a token that can't be read: ${ (error as Error).message} `, { reason: 'malformed'} , error, ); } if (info.imprintAlgorithm !== algorithm){ throw wrongAnswer( 'algorithm-mismatch', `stamped a ${ info.imprintAlgorithm} digest where ${ algorithm} was asked for`, ); } if (!engine.bytesEqual(info.imprint, digest)){ throw wrongAnswer('digest-mismatch', 'stamped another digest than the one it was sent'); } if (!info.nonce || !engine.bytesEqual(info.nonce, timestamp.withoutLeadingZeros(nonce))){ throw wrongAnswer( 'profile-violation', "sent a token that doesn't answer this request: its nonce is not the one sent", ); } if (policy && info.policy !== policy){ throw wrongAnswer( 'profile-violation', `issued the token under policy ${ info.policy} where ${ policy} was asked for`, ); } return response.token; } , } ; } indexedDbKeyStore [FunctionDeclaration] (from packages/core/signature/src/signers/personal.ts): export function indexedDbKeyStore( dbName: string, options:{ storeName?: string} ={ } , ): PersonalKeyStore{ const storeName = options.storeName ?? 'keys'; let opening: Promise | null = null; const open = (): Promise =>{ opening ??= new Promise((resolve, reject) =>{ const request = indexedDB.open(dbName, 1); request.onupgradeneeded = () =>{ if (!request.result.objectStoreNames.contains(storeName)){ request.result.createObjectStore(storeName); } } ; request.onsuccess = () => resolve(request.result); request.onerror = () => reject(request.error ?? new Error('indexedDB open failed')); } ); return opening; } ; const run = async ( mode: IDBTransactionMode, op: (store: IDBObjectStore) => IDBRequest, ): Promise =>{ const db = await open(); return new Promise((resolve, reject) =>{ const tx = db.transaction(storeName, mode); const request = op(tx.objectStore(storeName)); request.onsuccess = () => resolve(request.result); request.onerror = () => reject(request.error ?? new Error('indexedDB request failed')); } ); } ; return{ load: async (subject) => ((await run('readonly', (store) => store.get(subject))) as PersonalKeyRecord | undefined) ?? null, save: (subject, record) => run('readwrite', (store) => store.put(record, subject)).then(() => undefined), remove: (subject) => run('readwrite', (store) => store.delete(subject)).then(() => undefined), } ; } memoryKeyStore [FunctionDeclaration] (from packages/core/signature/src/signers/personal.ts): export function memoryKeyStore(): PersonalKeyStore{ const records = new Map(); return{ load: async (subject) => records.get(subject) ?? null, save: async (subject, record) =>{ records.set(subject, record); } , remove: async (subject) =>{ records.delete(subject); } , } ; } parseDetachedCms [FunctionDeclaration] (from packages/core/signature/src/cms/parse.ts): export function parseDetachedCms(cms: Uint8Array): ParsedCms{ return parseCmsInternal(cms).parsed; } personalSigner [FunctionDeclaration] (from packages/core/signature/src/signers/personal.ts): export async function personalSigner(input:{ subject: string; store: PersonalKeyStore; algorithm?: 'RSA-PKCS1-v1_5' | 'RSA-PSS' | 'ECDSA'; hash?: 'sha256' | 'sha384' | 'sha512'; } ): Promise{ const{ ensureEngine} = await import('../cms/engine'); ensureEngine(); const hash = input.hash ?? 'sha256'; let record = await input.store.load(input.subject); if (!record){ const{ selfSignedCertificate} = await import('./self-signed'); const keys = await generateSigningKeyPair(input.algorithm ?? 'RSA-PKCS1-v1_5', hash, false); const certificate = await selfSignedCertificate({ publicKey: keys.publicKey, privateKey: keys.privateKey, commonName: input.subject, hash, } ); record ={ privateKey: keys.privateKey, certificate} ; await input.store.save(input.subject, record); } const signer = webCryptoSigner({ privateKey: record.privateKey, certificateChain: [record.certificate], hash, } ); return{ ...signer, certificate: record.certificate, subject: input.subject} ; } profileFor [FunctionDeclaration] (from packages/core/signature/src/sign.ts): export function profileFor(subFilter: SignatureSubFilter): SignatureProfile; remoteSigner [FunctionDeclaration] (from packages/core/signature/src/signers/remote.ts): export function remoteSigner(input:{ sign: (request:{ digest: Uint8Array; algorithm: 'sha256' | 'sha384' | 'sha512'; subFilter: 'adbe.pkcs7.detached' | 'ETSI.CAdES.detached' | 'ETSI.RFC3161'; } ) => Promise; } ): CmsSigner{ return{ kind: 'cms', sign: (request) => input.sign(request), } ; } selfSignedCertificate [FunctionDeclaration] (from packages/core/signature/src/signers/self-signed.ts): export async function selfSignedCertificate(input:{ publicKey: CryptoKey; privateKey: CryptoKey; commonName: string; hash: 'sha256' | 'sha384' | 'sha512'; validityDays?: number; } ): Promise{ return buildSelfSignedCertificate(input, 'signing'); } sign [FunctionDeclaration] (from packages/core/signature/src/sign.ts): export async function sign( doc: DocumentHandle, input: SignInput, ): Promise{ const{ key, timestampAuthority, timestampTrust, ...rest} = input; const timestamp = rest.kind === 'timestamp'; if (timestamp && key.kind !== 'cms'){ throw new EngineError( EngineErrorCode.InvalidArg, 'a document timestamp needs a timestamp authority: a CMS key that returns an RFC 3161 token', { details:{ field: 'key'} } , ); } assertTimestampOptions(timestamp, timestampAuthority, timestampTrust); const subFilter = timestamp ? 'ETSI.RFC3161' : (rest.subFilter ?? 'ETSI.CAdES.detached'); const profile = profileFor(subFilter); const prepared = await doc.signatures.prepare({ ...rest, ...(timestamp ?{ } :{ subFilter: subFilter as SignatureSubFilter} ), digest: rest.digest ?? key.hash ?? 'sha256', ...(timestampAuthority && rest.contentsSizeBytes === undefined ?{ contentsSizeBytes: TIMESTAMPED_CONTENTS_SIZE} :{ } ), } ); try{ const cms = await cmsFor(key, prepared, subFilter, profile); return await completePrepared(doc, { prepared, cms, timestampAuthority, timestampTrust} ); } catch (error){ await doc.signatures.cancel(prepared.signingId).catch(() => undefined); throw error; } } validateChain [FunctionDeclaration] (from packages/core/signature/src/trust.ts): export async function validateChain( cms: Uint8Array | ParsedCmsInternal, trust: TrustPort | null, at: ValidationTime ={ kind: 'now'} , ): Promise{ return validateChainAmong(cms, trust, at, []); } validateSignatures [FunctionDeclaration] (from packages/core/signature/src/verdict.ts): export async function validateSignatures( doc: DocumentHandle, options: ValidateSignaturesOptions ={ } , ): Promise{ if (!doc.signatures) throw new Error('this engine does not implement signatures'); const snapshot = await doc.signatures.list(); const trust = options.trust ?? null; const pool = await readValidationPool(doc); const readings: Reading[] = []; for (const signature of snapshot.signatures){ if (signature.signed) readings.push(await read(doc, snapshot, signature, pool)); } const requested = options.validationTime ?? EARLIEST; if (options.revocation && trust){ await fillPool({ readings, trust, pool, source: options.revocation, maxCrlBytes: DEFAULT_MAX_CRL_BYTES, times: requested.kind === 'earliest-timestamp' ? [EARLIEST] : [EARLIEST, requested], } ); } const atTimestamps = await judge(readings, trust, pool, EARLIEST); const judged = requested.kind === 'earliest-timestamp' ? atTimestamps : await judge(readings, trust, pool, requested); const verdicts: SignatureVerdict[] = []; for (const reading of readings){ const judgement = judged.judgements.get(reading)!; const proof = atTimestamps.judgements.get(reading)!; const modifications = await modificationsOf( doc, snapshot, reading.signature, options.until ?? 'persisted', ); const revoked = judgement.trust === 'trusted' && judgement.revocation === 'revoked'; let summary: SignatureVerdict['summary']; if ( reading.integrity === 'invalid' || reading.cryptography === 'invalid' || modifications.verdict === 'forbidden' ){ summary = 'invalid'; } else if ( reading.integrity === 'indeterminate' || reading.cryptography === 'unsupported' || modifications.verdict === 'indeterminate' ){ summary = 'indeterminate'; } else if (revoked){ summary = 'invalid'; } else{ summary = judgement.trust === 'trusted' ? 'valid' : 'valid-untrusted'; } verdicts.push({ signature: reading.signature, integrity: reading.integrity, cryptography: reading.cryptography, trust: judgement.trust, trustReason: judgement.trustReason, validationTime: judgement.validationTime, revocation: judgement.revocation, ...(judgement.revocationReason ?{ revocationReason: judgement.revocationReason} :{ } ), modifications, summary, cms: reading.cms, timestamp: judgement.timestamp, longTerm: await longTermVerdict( longTermInputOf(reading, proof, atTimestamps.documentTimestamps, pool, 'file'), ), } ); } return verdicts; } verifyCmsSignature [FunctionDeclaration] (from packages/core/signature/src/cms/verify.ts): export async function verifyCmsSignature( cms: Uint8Array | ParsedCmsInternal, ): Promise{ let internal: ParsedCmsInternal; try{ internal = cms instanceof Uint8Array ? parseCmsInternal(cms) : cms; } catch (error){ return error instanceof CmsError && error.reason === 'unsupported' ? 'unsupported' : 'invalid'; } const binding = await checkCertificateBinding(internal); if (binding === 'invalid') return 'invalid'; const signature = await verifySignerSignature(internal); if (signature !== 'valid') return signature; return binding === 'unsupported' ? 'unsupported' : 'valid'; } verifyForCompletion [FunctionDeclaration] (from packages/core/signature/src/gate.ts): export async function verifyForCompletion(input:{ cms: Uint8Array; prepared: SignaturePrepared; profile: CompletionProfile; } ): Promise{ const{ cms, prepared, profile} = input; if (cms.byteLength > prepared.contentsSizeBytes){ return{ ok: false, reason: 'too-large', detail: `the signature is ${ cms.byteLength} bytes and ${ prepared.contentsSizeBytes} were reserved: ${ reserveAdvice(cms.byteLength)} `, } ; } if (profile === 'timestamp') return verifyDocumentTimestamp(cms, prepared); let internal; try{ internal = parseCmsInternal(cms); } catch (error){ return{ ok: false, reason: 'malformed', detail: error instanceof CmsError ? error.message : String(error), } ; } const parsed = internal.parsed; if (parsed.digestAlgorithm !== prepared.algorithm){ return{ ok: false, reason: 'algorithm-mismatch', detail: `the CMS digests with ${ parsed.digestAlgorithm} , the document was prepared with ${ prepared.algorithm} `, } ; } if (!bytesEqual(parsed.messageDigest, prepared.digest)){ return{ ok: false, reason: 'digest-mismatch', detail: 'the CMS message digest is not the prepared digest', } ; } if (profile === 'cades-b'){ if (!parsed.signingCertificateV2){ return{ ok: false, reason: 'profile-violation', detail: 'CAdES requires the ESS signing-certificate-v2 attribute', } ; } if (parsed.signingTime){ return{ ok: false, reason: 'profile-violation', detail: 'PAdES forbids the CMS signing-time attribute', } ; } } const cryptography = await verifyCmsSignature(internal); if (cryptography !== 'valid'){ return{ ok: false, reason: 'signature-invalid', detail: cryptography === 'unsupported' ? 'the signature or its certificate binding uses an algorithm that is not supported' : 'the signature does not verify', } ; } const signatureValue = signatureValueOf(internal.signerInfo); for (const token of internal.timestampTokens){ const check = await checkTimestampToken({ token, stamped:{ kind: 'bytes', bytes: signatureValue} , certificates: internal.certificates, } ); if (check.verdict === 'invalid'){ return{ ok: false, reason: check.problem === 'imprint' ? 'digest-mismatch' : 'signature-invalid', detail: `the signature's timestamp does not belong to it: ${ check.detail} `, } ; } } return{ ok: true} ; } verifyTimestampToken [FunctionDeclaration] (from packages/core/signature/src/verdict.ts): export async function verifyTimestampToken(input:{ token: Uint8Array; digest: Uint8Array; algorithm: DigestAlgorithm; trust?: TrustPort | null; } ): Promise{ const check = await checkTimestampToken({ token: input.token, stamped:{ kind: 'digest', digest: input.digest, algorithm: input.algorithm} , } ); const pool = new ValidationPool(); if (check.token) pool.addCarried(check.token.certificates, check.token.revocation); return (await judgeToken(check, input.trust ?? null, NOW, pool)).verdict; } webCryptoSigner [FunctionDeclaration] (from packages/core/signature/src/signers/webcrypto.ts): export function webCryptoSigner(input:{ privateKey: CryptoKey; certificateChain: Uint8Array[]; hash?: Exclude; } ): RawSigner{ const keyAlgorithm = input.privateKey.algorithm as RsaHashedKeyAlgorithm | EcKeyAlgorithm; let algorithm: RawSignatureAlgorithm; let hash: Exclude; switch (keyAlgorithm.name){ case 'RSASSA-PKCS1-v1_5': algorithm = 'RSA-PKCS1-v1_5'; hash = hashFromWebCrypto((keyAlgorithm as RsaHashedKeyAlgorithm).hash.name); break; case 'RSA-PSS': algorithm = 'RSA-PSS'; hash = hashFromWebCrypto((keyAlgorithm as RsaHashedKeyAlgorithm).hash.name); break; case 'ECDSA': algorithm = 'ECDSA'; hash = input.hash ?? 'sha256'; break; default: throw new Error(`unsupported WebCrypto key algorithm ${ keyAlgorithm.name} `); } return{ kind: 'raw', certificateChain: input.certificateChain, algorithm, hash, async sign(data){ const params: AlgorithmIdentifier | RsaPssParams | EcdsaParams = algorithm === 'RSA-PSS' ?{ name: 'RSA-PSS', saltLength:{ sha256: 32, sha384: 48, sha512: 64} [hash]} : algorithm === 'ECDSA' ?{ name: 'ECDSA', hash: WEBCRYPTO_HASH[hash]} :{ name: 'RSASSA-PKCS1-v1_5'} ; const copy = new Uint8Array(data.byteLength); copy.set(data); const signature = await globalThis.crypto.subtle.sign(params, input.privateKey, copy); return new Uint8Array(signature); } , } ; }