# @embedpdf/angular — ./signature AnalyzeInput [InterfaceDeclaration] (from packages/engine/core/src/signature/analysis/types.ts): export interface AnalyzeInput{ since:{ signatureIndex: number} |{ revisionIndex: number} ; until?: 'persisted' | 'working-copy' |{ revisionIndex: number} ; exploratoryLevel?: ModificationLevel; detail?: 'summary' | 'full'; } 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; } ; ChangeAnalysis [InterfaceDeclaration] (from packages/engine/core/src/signature/analysis/types.ts): export interface ChangeAnalysis{ mode: 'authoritative' | 'exploratory'; policyVersion: number; basis:{ version: BaseVersionInfo; editsVersion: number; source: 'persisted' | 'working-copy'} ; since:{ revisionIndex: number; signatureIndex: number | null} ; until:{ revisionIndex: number} ; restrictions: RestrictionAnchor[]; current: Assessment &{ method: 'net-state' | 'net-state+replay'} ; later:{ revisionCount: number; undoneObjectNumbers: number[]; } ; verdict: StepVerdict; steps: RevisionAnalysis[]; } 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; } DocMdpPermission [TypeAliasDeclaration] (from packages/engine/core/src/signature/types.ts): export type DocMdpPermission = 1 | 2 | 3; DocumentProtection [InterfaceDeclaration] (from packages/engine/core/src/signature/types.ts): export interface DocumentProtection{ enforced: ModificationLevel | null; judged: ModificationLevel | null; certification:{ signatureIndex: number; permission: DocMdpPermission} | null; fieldLocks: DocumentFieldLock[]; policyVersion: number; } EpdfSignature [ClassDeclaration] (from packages/framework/angular/signature/src/signature.ts): @Injectable({ providedIn: 'root'} ) export class EpdfSignature extends pluginService({ name: 'EpdfSignature', feature: 'withSignature()', token: SignatureToken, state: signatureState, methods: [ 'getSnapshot', 'getStatus', 'listSignatures', 'listUnsignedFields', 'getSignature', 'listVerdicts', 'getVerdict', 'getProtection', 'getPending', 'isBusy', 'getMode', 'getTarget', 'sign', 'prepareSignature', 'completeSignature', 'cancelPending', 'fillField', 'clearField', 'placeMark', 'setTarget', 'requestInspection', 'refresh', 'validate', 'validateField', 'addValidationInfo', 'analyzeChanges', 'readRevision', 'canSign', 'canFill', 'canCertify', 'canReadRevision', 'canAddValidationInfo', ], events: [ 'onSigned', 'onFilled', 'onCleared', 'onValidated', 'onProtectionChanged', 'onInvalidationPredicted', 'onTargetChanged', 'onSignRequested', 'onInspectionRequested', ], } ){ private readonly stamp = new CapabilityBinding( this.binding.host, () => StampToken, injectDocumentScope(), ); private readonly libraries = this.stamp.select( (stamp) => stamp.listLibraries({ kind: SIGNATURES_LIBRARY_KIND} ), NO_LIBRARIES, ); private readonly assets = this.stamp.select((stamp) => stamp.listAssets(), NO_ASSETS); readonly signerRows: Signal = computed(() => signerRowsOf(this.libraries(), this.assets()), ); } FieldLockSpec [InterfaceDeclaration] (from packages/engine/core/src/signature/types.ts): export interface FieldLockSpec{ action: FieldLockAction; fields: string[]; permission?: DocMdpPermission; } FormFieldRef [TypeAliasDeclaration] (from packages/engine/core/src/identity/FormFieldRef.ts): export type FormFieldRef = |{ kind: 'objectNumber'; objectNumber: number} |{ kind: 'fqn'; name: string} ; 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; } INITIALS_MARK_NAME [VariableDeclaration] (from packages/plugin/signature/src/contract.ts): INITIALS_MARK_NAME = 'initials' 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[]; } Mark [TypeAliasDeclaration] (from packages/plugin/signature/src/contract.ts): export type Mark ={ assetId: string} |{ source: BinarySource} ; MarkRole [TypeAliasDeclaration] (from packages/plugin/signature/src/contract.ts): export type MarkRole = 'signature' | 'initials'; 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; } PlaceMarkResult [TypeAliasDeclaration] (from packages/plugin/signature/src/contract.ts): export type PlaceMarkResult = |{ status: 'signed'; field: FormFieldRef; result: SignFieldResult} |{ status: 'filled'; field: FormFieldRef} |{ status: 'requested'; field: FormFieldRef} |{ status: 'placed'; annotation: AnnotationRef} ; PrepareSignatureInput [InterfaceDeclaration] (from packages/plugin/signature/src/contract.ts): export interface PrepareSignatureInput{ field: FormFieldRef; mark?: Mark; appearance?: BinarySource; signer?: SignatureSignerInput; certify?:{ permission: DocMdpPermission} ; lock?: FieldLockSpec; subFilter?: SignatureSubFilter; digest?: Exclude; timestampAuthority?: CmsSigner | null; } 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'; SIGNATURES_LIBRARY_KIND [VariableDeclaration] (from packages/plugin/signature/src/contract.ts): SIGNATURES_LIBRARY_KIND = 'signatures' SIGNATURE_DEFAULTS [VariableDeclaration] (from packages/plugin/signature/src/contract.ts): SIGNATURE_DEFAULTS: SignatureSettings ={ signingKey: null, mode: null, timestampAuthority: null, revocation: null, documentTimestamp: false, trust: null, allowCertify: false, } SIGNATURE_MARK_NAME [VariableDeclaration] (from packages/plugin/signature/src/contract.ts): SIGNATURE_MARK_NAME = 'signature' SignFieldInput [InterfaceDeclaration] (from packages/plugin/signature/src/contract.ts): export interface SignFieldInput{ field: FormFieldRef; mark: Mark; signingKey?: SigningKey; timestampAuthority?: CmsSigner | null; signer?: SignatureSignerInput; appearance?: BinarySource; certify?:{ permission: DocMdpPermission} ; lock?: FieldLockSpec; } SignFieldResult [InterfaceDeclaration] (from packages/plugin/signature/src/contract.ts): export interface SignFieldResult extends SignatureCompleteResult{ readonly validationInfo: ValidationInfoAdded | null; readonly validationInfoError: PluginError | null; } Signature [InterfaceDeclaration] (from packages/engine/core/src/signature/types.ts): export interface Signature{ index: number; field: FormFieldRef; fieldName: string; widget: FormFieldWidget | null; signed: boolean; kind: SignatureKind; filter: string | null; subFilter: string | null; byteRange: [number, number, number, number] | null; contentsSizeBytes: number; coverage: SignatureCoverage | null; revisionIndex: number | null; signer: SignatureSigner; docMdp: DocMdpPermission | null; catalogCertification: boolean; fieldMdp: FieldLockSpec | null; lock: FieldLockSpec | null; seedValue: SignatureSeedValue | null; } SignatureCapability [InterfaceDeclaration] (from packages/plugin/signature/src/contract.ts): export interface SignatureCapability extends SettingsApi{ getSnapshot(): SignatureSnapshot | null; getStatus(): ResourceStatus; listSignatures(): readonly SignatureInfo[]; listUnsignedFields(): readonly FormFieldRef[]; getSignature(field: SignatureFieldAddress): SignatureInfo | null; listVerdicts(): readonly SignatureVerdict[] | null; getVerdict(field: SignatureFieldAddress): SignatureVerdict | null; getProtection(): DocumentProtection | null; getPending(): SignaturePending | null; isBusy(): boolean; getMode(): SignatureMode; getTarget(): FormFieldRef | null; sign(input: SignFieldInput, options?: OperationOptions): Promise; prepareSignature( input: PrepareSignatureInput, options?: OperationOptions, ): Promise; completeSignature( signingId: string, cms: Uint8Array, options?: OperationOptions, ): Promise; cancelPending(options?: OperationOptions): Promise; fillField(field: FormFieldRef, mark: Mark, options?: OperationOptions): Promise; clearField(field: FormFieldRef, options?: OperationOptions): Promise; placeMark( mark: Mark, target:{ field: FormFieldRef} | StampPlacement, options?: OperationOptions, ): Promise; setTarget(field: FormFieldRef | null): void; requestInspection(field: FormFieldRef): void; refresh(options?: OperationOptions): Promise; validate(options?: SignatureValidateOptions): Promise; validateField( field: SignatureFieldAddress, options?: SignatureValidateOptions, ): Promise; addValidationInfo( field?: SignatureFieldAddress, options?: OperationOptions, ): Promise; analyzeChanges(input: AnalyzeInput, options?: OperationOptions): Promise; readRevision( target: SignatureFieldAddress |{ revisionIndex: number} , options?: OperationOptions, ): Promise; canSign(field: FormFieldRef): boolean; canFill(field: FormFieldRef): boolean; canCertify(): boolean; canReadRevision(): boolean; canAddValidationInfo(): boolean; readonly onSigned: EventHook; readonly onFilled: EventHook; readonly onCleared: EventHook; readonly onValidated: EventHook; readonly onProtectionChanged: EventHook; readonly onInvalidationPredicted: EventHook; readonly onTargetChanged: EventHook; readonly onSignRequested: EventHook; readonly onInspectionRequested: EventHook; } SignatureClearedEvent [InterfaceDeclaration] (from packages/plugin/signature/src/contract.ts): export interface SignatureClearedEvent{ readonly field: FormFieldRef; } SignatureCompleteResult [InterfaceDeclaration] (from packages/engine/core/src/signature/types.ts): export interface SignatureCompleteResult{ status: 'completed' | 'already-completed'; signature: Signature; version: BaseVersionInfo; previous: DocumentVersionRef; protection: DocumentProtection; meta: MutationMeta; } SignatureConfig [TypeAliasDeclaration] (from packages/plugin/signature/src/contract.ts): export type SignatureConfig = Partial; SignatureFieldAddress [TypeAliasDeclaration] (from packages/plugin/signature/src/contract.ts): export type SignatureFieldAddress = FormFieldRef | AnnotationRef | FormWidget; SignatureFilledEvent [InterfaceDeclaration] (from packages/plugin/signature/src/contract.ts): export interface SignatureFilledEvent{ readonly field: FormFieldRef; } SignatureInfo [InterfaceDeclaration] (from packages/plugin/signature/src/contract.ts): export interface SignatureInfo extends Signature{ readonly verdict: SignatureVerdict | null; } SignatureInspectionRequestedEvent [InterfaceDeclaration] (from packages/plugin/signature/src/contract.ts): export interface SignatureInspectionRequestedEvent{ readonly field: FormFieldRef; } SignatureInvalidationPredictedEvent [InterfaceDeclaration] (from packages/plugin/signature/src/contract.ts): export interface SignatureInvalidationPredictedEvent{ readonly field: FormFieldRef; readonly detail: string; } SignatureMode [TypeAliasDeclaration] (from packages/plugin/signature/src/contract.ts): export type SignatureMode = 'sign' | 'visual' | 'ask'; SignaturePending [InterfaceDeclaration] (from packages/plugin/signature/src/contract.ts): export interface SignaturePending{ readonly signingId: string; readonly field: FormFieldRef; } SignaturePrepared [InterfaceDeclaration] (from packages/engine/core/src/signature/types.ts): export interface SignaturePrepared{ signingId: string; digest: Uint8Array; algorithm: Exclude; byteRange: [number, number, number, number]; contentsSizeBytes: number; subFilter: SignatureSubFilter | 'ETSI.RFC3161'; expectedVersion: DocumentVersionRef; expiresAt: string | null; field?: FormFieldRef; } SignatureProtectionChangedEvent [InterfaceDeclaration] (from packages/plugin/signature/src/contract.ts): export interface SignatureProtectionChangedEvent{ readonly protection: DocumentProtection; } SignatureSettings [InterfaceDeclaration] (from packages/plugin/signature/src/contract.ts): export interface SignatureSettings{ readonly signingKey: SigningKey | null; readonly mode: SignatureMode | null; readonly timestampAuthority: CmsSigner | null; readonly revocation: RevocationSource | null; readonly documentTimestamp: boolean; readonly trust: TrustPort | null; readonly allowCertify: boolean; } SignatureSignRequestedEvent [InterfaceDeclaration] (from packages/plugin/signature/src/contract.ts): export interface SignatureSignRequestedEvent{ readonly field: FormFieldRef; readonly mark: Mark; } SignatureSignedEvent [InterfaceDeclaration] (from packages/plugin/signature/src/contract.ts): export interface SignatureSignedEvent{ readonly field: FormFieldRef; readonly result: SignatureCompleteResult; readonly origin: EventOrigin; } SignatureSnapshot [InterfaceDeclaration] (from packages/engine/core/src/signature/types.ts): export interface SignatureSnapshot{ chainValid: boolean; revisions: PdfRevision[]; signatures: Signature[]; protection: DocumentProtection; } SignatureState [InterfaceDeclaration] (from packages/plugin/signature/src/state.ts): export interface SignatureState{ readonly signatures: readonly SignatureInfo[]; readonly protection: DocumentProtection | null; readonly target: FormFieldRef | null; readonly busy: boolean; readonly pending: SignaturePending | null; readonly status: ResourceStatus; } SignatureTargetChangedEvent [InterfaceDeclaration] (from packages/plugin/signature/src/contract.ts): export interface SignatureTargetChangedEvent{ readonly field: FormFieldRef | null; } SignatureToken [VariableDeclaration] (from packages/plugin/signature/src/token.ts): SignatureToken = createCapabilityToken('signature', { hint: `add signaturePlugin() from '@embedpdf/plugin-signature' to your plugins list`, promises:{ sign: true, prepareSignature: true, completeSignature: true, cancelPending: true, fillField: true, clearField: true, placeMark: true, refresh: true, validate: true, validateField: true, addValidationInfo: true, analyzeChanges: true, readRevision: true, } , } ) SignatureValidateOptions [InterfaceDeclaration] (from packages/plugin/signature/src/contract.ts): export interface SignatureValidateOptions extends OperationOptions{ readonly validationTime?: ValidationTime |{ readonly kind: 'earliest-timestamp'} ; readonly until?: 'persisted' | 'working-copy'; } SignatureValidatedEvent [InterfaceDeclaration] (from packages/plugin/signature/src/contract.ts): export interface SignatureValidatedEvent{ readonly verdicts: readonly SignatureVerdict[]; } 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; SignerRow [InterfaceDeclaration] (from packages/plugin/signature/src/contract.ts): export interface SignerRow{ readonly libraryId: string; readonly name: string; readonly library: StampLibrary; readonly signatures: StampAsset[]; readonly initials: StampAsset | null; } SigningKey [TypeAliasDeclaration] (from packages/plugin/signature/src/contract.ts): export type SigningKey = SignerPort | (() => SignerPort | Promise); 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; } ValidationInfoAdded [InterfaceDeclaration] (from packages/plugin/signature/src/contract.ts): export interface ValidationInfoAdded{ readonly added: ValidationInfoCounts; readonly documentTimestamp: FormFieldRef | null; } ValidationInfoCounts [TypeAliasDeclaration] (from packages/engine/core/src/signature/types.ts): export type ValidationInfoCounts = Record; 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; } ; 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} ), } ; } 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), } ; } markRoleOf [VariableDeclaration] (from packages/plugin/signature/src/contract.ts): markRoleOf = (asset: Pick): MarkRole => asset.name === INITIALS_MARK_NAME ? 'initials' : 'signature' 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); } , } ; } 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} ; } 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), } ; } signaturePlugin [VariableDeclaration] (from packages/plugin/signature/src/signature.plugin.ts): signaturePlugin = (config?: SignatureConfig) => definePlugin({ id: 'signature', token: SignatureToken, scope: 'document', requires: [FormToken], optional: [InteractionToken, StampToken, AnnotationToken], state: initialSignatureModel, settings:{ defaults: SIGNATURE_DEFAULTS, registered: config, whole: ['signingKey', 'timestampAuthority', 'revocation', 'trust'], } , create: createSignatureController, } ) signatureState [VariableDeclaration] (from packages/plugin/signature/src/state.ts): signatureState = defineState(SignatureToken, { read: (signature): SignatureState => ({ signatures: signature.listSignatures(), protection: signature.getProtection(), target: signature.getTarget(), busy: signature.isBusy(), pending: signature.getPending(), status: signature.getStatus(), } ), empty:{ signatures: NO_SIGNATURES, protection: null, target: null, busy: false, pending: null, status: 'idle', } , } ) signerRowsOf [FunctionDeclaration] (from packages/plugin/signature/src/contract.ts): export function signerRowsOf( libraries: readonly StampLibrary[], assets: readonly StampAsset[], ): SignerRow[]{ return libraries .filter((library) => library.kind === SIGNATURES_LIBRARY_KIND) .map((library) =>{ const own = assets.filter((asset) => asset.libraryId === library.id); return{ libraryId: library.id, name: library.name, library, signatures: own.filter((asset) => markRoleOf(asset) === 'signature'), initials: own.find((asset) => markRoleOf(asset) === 'initials') ?? null, } ; } ); } 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); } , } ; } withSignature [FunctionDeclaration] (from packages/framework/angular/signature/src/signature.ts): export function withSignature(config?: SignatureConfig): EmbedPdfFeature{ return{ plugins: [signaturePlugin(config)], services: [EpdfSignature]} ; }