Open-source document signature platform. Not affiliated with DocuSign.
TypeScript
Fix what the first review of provider signing found
Claude95d1c9c18cdb
diff --git a/src/lib/permitted-uses.ts b/src/lib/permitted-uses.tsindex 06f5cf2..3bf3ee5 100644--- a/src/lib/permitted-uses.ts+++ b/src/lib/permitted-uses.ts@@ -3,7 +3,7 @@// version is stored with each send, so the record shows which list the// sender confirmed.-export const PERMITTED_USE_VERSION = "2026-11-13";+export const PERMITTED_USE_VERSION = "2026-11-14";export const PERMITTED_USE_PATH = "/electronic-signatures";export type UseSection = { heading: string; items: string[] };diff --git a/src/lib/provider-signing.dbtest.ts b/src/lib/provider-signing.dbtest.tsindex 968f684..19693ec 100644--- a/src/lib/provider-signing.dbtest.ts+++ b/src/lib/provider-signing.dbtest.ts@@ -626,3 +626,75 @@ test("a signer who does not finish at the provider can try again", async () => {assert.ok(envelope.rows[0]?.revision_key);});++test("a return while another is saving the signature leaves that one to finish", async () => {+ const draft = await createDraft();++ await send(draft, "advanced");++ const riley = await signAtProvider(+ await linkFor(draft.riley.id),+ draft.riley,+ );+ const sessionId = riley.query.get("state") ?? "";+ const session = await database.query<{ revision_key: string }>(+ `select revision_key from provider_signing_sessions where id = $1`,+ [sessionId],+ );++ // Another return claimed the session first and is saving it.+ await database.query(+ `update provider_signing_sessions set state = 'signing' where id = $1`,+ [sessionId],+ );++ await assert.rejects(+ riley.finish(),+ (error: unknown) =>+ error instanceof ProviderSigningError && error.problem === "expired",+ );+ assert.deepEqual(await sessionStates(draft.envelopeId), ["signing"]);+ assert.equal(await stored(session.rows[0]!.revision_key), true);+});++test("the next signer's turn starts when the signer is back from the provider", async () => {+ const draft = await createDraft();++ await send(draft, "advanced");++ const riley = await signAtProvider(+ await linkFor(draft.riley.id),+ draft.riley,+ );+ const left = await database.query<{ submitted_at: string }>(+ `select submitted_at from provider_signing_sessions where id = $1`,+ [riley.query.get("state") ?? ""],+ );+ const leftAt = Number(left.rows[0]!.submitted_at);++ // The signer takes a while at the provider.+ await new Promise((resolve) => setTimeout(resolve, 1100));++ const backAt = Math.floor(Date.now() / 1000);++ await riley.finish();++ const signers = await database.query<{+ id: string;+ last_notified_at: string | null;+ signed_at: string | null;+ turn_started_at: string | null;+ }>(+ `select id, signed_at, turn_started_at, last_notified_at from signers where envelope_id = $1`,+ [draft.envelopeId],+ );+ const rileyRow = signers.rows.find((row) => row.id === draft.riley.id)!;+ const caseyRow = signers.rows.find((row) => row.id === draft.casey.id)!;++ // Riley signed when the signed revision says, before leaving.+ assert.equal(Number(rileyRow.signed_at), leftAt);+ assert.ok(leftAt < backAt);+ // Casey's turn, and the invitation, start once Riley is back.+ assert.ok(Number(caseyRow.turn_started_at) >= backAt);+ assert.ok(Number(caseyRow.last_notified_at) >= backAt);+});diff --git a/src/lib/provider-signing.ts b/src/lib/provider-signing.tsindex 031d27d..4c37848 100644--- a/src/lib/provider-signing.ts+++ b/src/lib/provider-signing.ts@@ -371,6 +371,17 @@ export async function resumeProviderSigning();}+ // Another return for this session (a reload, or the provider calling back+ // twice) is finishing it. Leave it to finish: failing the session here+ // would delete the revision it is saving.+ if (session.state === "signing" || session.state === "completed") {+ throw new ProviderSigningError(+ "This signing session is already being completed.",+ "expired",+ secret.token,+ );+ }+if (session.state !== "pending" ||session.expiresAt < Math.floor(Date.now() / 1000)@@ -522,28 +533,8 @@ export async function resumeProviderSigning(},);- // The revision this one was built on is inside it now.- const previous = await queryOne<{ revisionKey: string }>(- database,- `- SELECT revision_key AS "revisionKey"- FROM provider_signing_sessions- WHERE envelope_id = $1- AND state = 'completed'- AND id <> $2- AND revision_key <> $3- ORDER BY completed_at DESC- LIMIT 1- `,- [session.envelopeId, session.id, session.revisionKey],- );-- if (previous) {- await storageService- .deleteObject(previous.revisionKey)- .catch(() => undefined);- }-+ // The revision this one was built on is inside it now. Saving the+ // submission deleted it (see commitProviderRevision in signing.ts).return { redirectPath: result.redirectPath };} catch (error) {await failSession(session, database, storageService);diff --git a/src/lib/services/pdf-revision.test.ts b/src/lib/services/pdf-revision.test.tsindex 9530734..5ac9419 100644--- a/src/lib/services/pdf-revision.test.ts+++ b/src/lib/services/pdf-revision.test.ts@@ -1,6 +1,6 @@import assert from "node:assert/strict";import { execFile } from "node:child_process";-import { createHash } from "node:crypto";+import { createHash, generateKeyPairSync, sign, verify } from "node:crypto";import { mkdtemp, rm, writeFile } from "node:fs/promises";import os from "node:os";import path from "node:path";@@ -27,6 +27,7 @@ import { startTestPki, type TestPki } from "./pki-test-support.ts";import {addSignatureTimestamp,checkSignerSignature,+ ecdsaSignatureAsDer,SignerSignatureError,} from "./signer-cms.ts";@@ -358,6 +359,108 @@ test("a qualified signature needs a qualified certificate", async () => {});});+test("a signature timestamp counts only when it is for the signature and verifies", async () => {+ await withPki(async (pki) => {+ const alice = pki.issueSigner({ commonName: "Alice Example" });+ const prepared = await prepareSignerRevision(+ await prepareRevisionZero(await makeSource()),+ {+ fields: aliceFields,+ images: new Map(),+ signature: { fieldName: "Alice", signingTime: new Date() },+ },+ );+ const [signature] = findSignatures(prepared.bytes);+ const covered = Buffer.concat([+ Buffer.from(prepared.bytes.subarray(0, signature!.byteRange[1])),+ Buffer.from(prepared.bytes.subarray(signature!.byteRange[2])),+ ]);+ const plain = Buffer.from(await buildCadesSignature(covered, alice));+ const timestampCount = (cms: Buffer) =>+ cms.toString("latin1").split(+ // The timeStampToken attribute's OID, as DER.+ Buffer.from("060b2a864886f70d010910020e", "hex").toString("latin1"),+ ).length - 1;+ const check = (cms: Buffer) =>+ checkSignerSignature(cms, prepared.digest, { level: "advanced" });++ // An empty timestamp attribute, a token for another signature, and+ // something that is not a token at all.+ const empty = await addSignatureTimestamp(plain, async () =>+ Buffer.alloc(0),+ );+ const otherSignature = await addSignatureTimestamp(plain, () =>+ requestDocumentTimestamp(Buffer.alloc(32, 7), pki.timestampUrl),+ );+ const notAToken = await addSignatureTimestamp(plain, async () =>+ Buffer.from("3000", "hex"),+ );++ for (const cms of [plain, empty, otherSignature, notAToken]) {+ assert.equal(check(cms).timestamped, false);+ }++ // Each is replaced by a real one, and only one is left.+ for (const cms of [empty, otherSignature, notAToken]) {+ const repaired = await addSignatureTimestamp(cms, (imprint) =>+ requestDocumentTimestamp(imprint, pki.timestampUrl),+ );++ assert.equal(check(repaired).timestamped, true);+ assert.equal(timestampCount(repaired), 1);++ // One that checks out is kept as it is.+ const again = await addSignatureTimestamp(repaired, () => {+ throw new Error("A good timestamp is not replaced.");+ });++ assert.deepEqual(again, repaired);+ }+ });+});++test("raw ECDSA r and s are encoded, even when they start like a SEQUENCE", () => {+ const { privateKey, publicKey } = generateKeyPairSync("ec", {+ namedCurve: "P-256",+ });+ const data = Buffer.from("signed attributes");+ const raw = sign("sha256", data, {+ dsaEncoding: "ieee-p1363",+ key: privateKey,+ });+ const asDer = ecdsaSignatureAsDer(raw);++ assert.ok(+ verify("sha256", data, { dsaEncoding: "der", key: publicKey }, asDer),+ );++ // A signature already in DER is left alone.+ const alreadyDer = sign("sha256", data, {+ dsaEncoding: "der",+ key: privateKey,+ });++ assert.deepEqual(ecdsaSignatureAsDer(alreadyDer), alreadyDer);++ // 64 raw bytes whose first two read as a 62-byte SEQUENCE.+ const lookalike = Buffer.concat([+ Buffer.from([0x30, 0x3e, 0x04, 0x3c]),+ Buffer.alloc(60, 0x11),+ ]);+ const encoded = ecdsaSignatureAsDer(lookalike);++ assert.notDeepEqual(encoded, lookalike);+ assert.deepEqual(+ encoded,+ Buffer.concat([+ Buffer.from([0x30, 0x44, 0x02, 0x20]),+ lookalike.subarray(0, 32),+ Buffer.from([0x02, 0x20]),+ lookalike.subarray(32),+ ]),+ );+});+test("the signature slot fits a chain and a timestamp", () => {assert.ok(SIGNER_SIGNATURE_BYTES >= 16_384);});diff --git a/src/lib/services/signer-cms.ts b/src/lib/services/signer-cms.tsindex 0f782a9..dd8ba43 100644--- a/src/lib/services/signer-cms.ts+++ b/src/lib/services/signer-cms.ts@@ -58,6 +58,7 @@ export const CMS_OIDS = {signingTime: "1.2.840.113549.1.9.5",sha1: "1.3.14.3.2.26",timeStampToken: "1.2.840.113549.1.9.16.2.14",+ tstInfo: "1.2.840.113549.1.9.16.1.4",} as const;const HASHES: Record<string, string> = {@@ -129,21 +130,48 @@ export function signatureAlgorithmFor(certificate: Certificate): Buffer {: algorithm(CMS_OIDS.sha256WithRsa);}+/**+ * Whether a signature is an ECDSA-Sig-Value in DER: a SEQUENCE of exactly+ * two positive INTEGERs, minimally encoded, filling the whole value. Raw+ * r and s can start with the bytes of a SEQUENCE by chance, but not pass+ * all of this.+ */+function isDerEcdsaSignature(signature: Buffer): boolean {+ try {+ const outer = readTlv(signature);++ if (outer.tag !== TAG.sequence || outer.end !== signature.length) {+ return false;+ }++ const parts = children(signature, outer);++ return (+ parts.length === 2 &&+ parts.every((part) => {+ const value = contentBytes(signature, part);++ return (+ part.tag === TAG.integer &&+ value.length > 0 &&+ // Positive, and no needless leading zero.+ (value[0]! & 0x80) === 0 &&+ !(value.length > 1 && value[0] === 0 && (value[1]! & 0x80) === 0)+ );+ })+ );+ } catch {+ return false;+ }+}+/*** An ECDSA signature as DER, from the raw r and s some services return.* A signature already in DER is returned as it is.*/export function ecdsaSignatureAsDer(signature: Buffer): Buffer {- if (signature[0] === TAG.sequence) {- try {- const outer = readTlv(signature);-- if (outer.end === signature.length) {- return signature;- }- } catch {- // Not DER after all.- }+ if (isDerEcdsaSignature(signature)) {+ return signature;}const half = signature.length / 2;@@ -224,7 +252,7 @@ type ParsedSignerInfo = {signedAttributes: Buffer;signedAttributeValues: Map<string, Tlv[]>;signerIdentifier: Tlv;- unsignedAttributeIds: string[];+ unsignedAttributeValues: Map<string, Tlv[]>;};function readAttributes(bytes: Buffer, tlv: Tlv): Map<string, Tlv[]> {@@ -265,19 +293,41 @@ function readSignedData(cms: Buffer): {return { parts: children(cms, signedData), signedData };}-function readSignerInfo(cms: Buffer): ParsedSignerInfo {+/**+ * The one SignerInfo of a CMS SignedData. A signer's signature is detached+ * (the content type only, no content); a timestamp token carries its TSTInfo+ * as the content, returned here as `content`.+ */+function readSignerInfo(+ cms: Buffer,+ kind: "detached" | "timestamp" = "detached",+): ParsedSignerInfo & { content: Buffer | null } {const { parts } = readSignedData(cms);const encapsulated = parts[2];+ const encapsulatedParts = encapsulated ? children(cms, encapsulated) : [];+ let content: Buffer | null = null;++ if (kind === "detached") {+ if (+ encapsulatedParts.length !== 1 ||+ readOid(cms, encapsulatedParts[0]!) !== CMS_OIDS.data+ ) {+ throw new SignerSignatureError(+ "The signature is not a detached signature of data.",+ );+ }+ } else {+ const wrapped = encapsulatedParts[1];++ if (+ encapsulatedParts.length !== 2 ||+ readOid(cms, encapsulatedParts[0]!) !== CMS_OIDS.tstInfo ||+ wrapped?.tag !== contextTag(0)+ ) {+ throw new SignerSignatureError("The timestamp token has no TSTInfo.");+ }- // Detached: the content type only, no content.- if (- !encapsulated ||- children(cms, encapsulated).length !== 1 ||- readOid(cms, children(cms, encapsulated)[0]!) !== CMS_OIDS.data- ) {- throw new SignerSignatureError(- "The signature is not a detached signature of data.",- );+ content = contentBytes(cms, children(cms, wrapped)[0]!);}const certificates = parts@@ -310,6 +360,7 @@ function readSignerInfo(cms: Buffer): ParsedSignerInfo {return {bytes: cms,certificates,+ content,digestAlgorithm: readOid(cms, children(cms, digestAlgorithm!)[0]!),signature: contentBytes(cms, signatureValue!),signatureAlgorithm: {@@ -322,10 +373,10 @@ function readSignerInfo(cms: Buffer): ParsedSignerInfo {signedAttributes: signed,signedAttributeValues: readAttributes(cms, signedAttributes),signerIdentifier: signerIdentifier!,- unsignedAttributeIds:+ unsignedAttributeValues:unsigned && unsigned.tag === contextTag(1)- ? [...readAttributes(cms, unsigned).keys()]- : [],+ ? readAttributes(cms, unsigned)+ : new Map(),};}@@ -465,6 +516,67 @@ function assertSigningCertificate(}}+/**+ * Whether a timestamp token is a signature timestamp for this signature+ * value: its TSTInfo's message imprint is the hash of the value, its signed+ * attributes hold the hash of that TSTInfo, and the time-stamping authority's+ * signature over them verifies with the certificate the token carries.+ */+function isTimestampFor(+ bytes: Buffer,+ token: Tlv,+ signatureValue: Buffer,+): boolean {+ try {+ const info = readSignerInfo(elementBytes(bytes, token), "timestamp");+ const tstInfo = info.content!;+ // TSTInfo { version, policy, messageImprint, ... }+ const imprint = children(tstInfo, children(tstInfo, readTlv(tstInfo))[2]!);+ const imprintHash =+ HASHES[readOid(tstInfo, children(tstInfo, imprint[0]!)[0]!)];+ const digestHash = HASHES[info.digestAlgorithm];+ const contentType = info.signedAttributeValues.get(CMS_OIDS.contentType);+ const messageDigest = info.signedAttributeValues.get(+ CMS_OIDS.messageDigest,+ );++ if (+ !imprintHash ||+ !digestHash ||+ !contentBytes(tstInfo, imprint[1]!).equals(+ createHash(imprintHash).update(signatureValue).digest(),+ ) ||+ contentType?.length !== 1 ||+ readOid(info.bytes, contentType[0]!) !== CMS_OIDS.tstInfo ||+ messageDigest?.length !== 1 ||+ !contentBytes(info.bytes, messageDigest[0]!).equals(+ createHash(digestHash).update(tstInfo).digest(),+ )+ ) {+ return false;+ }++ const authority = findSigner(+ info,+ info.certificates.map((certificate) => parseCertificate(certificate)),+ );++ return verifyValue(info, authority.x509.publicKey);+ } catch {+ return false;+ }+}++/** Whether the CMS carries a signature timestamp that checks out. */+function hasSignatureTimestamp(info: ParsedSignerInfo): boolean {+ const tokens =+ info.unsignedAttributeValues.get(CMS_OIDS.timeStampToken) ?? [];++ return tokens.some((token) =>+ isTimestampFor(info.bytes, token, info.signature),+ );+}+export type SignatureLevel = "advanced" | "qualified";export type CheckedSignerSignature = {@@ -476,7 +588,10 @@ export type CheckedSignerSignature = {qualified: boolean;serialNumber: string;subject: string;- /** The CMS carries a signature timestamp (PAdES B-T). */+ /**+ * The CMS carries a signature timestamp (PAdES B-T) for this signature,+ * signed by the time-stamping authority whose certificate it includes.+ */timestamped: boolean;validTo: Date;};@@ -596,7 +711,7 @@ export function checkSignerSignature(qualified,serialNumber: signer.serial.toString("hex"),subject: displayName(signer.x509.subject),- timestamped: info.unsignedAttributeIds.includes(CMS_OIDS.timeStampToken),+ timestamped: hasSignatureTimestamp(info),validTo,};}@@ -604,9 +719,11 @@ export function checkSignerSignature(// --- Changing --------------------------------------------------------------/**- * Adds a signature timestamp (PAdES B-T) to a CMS that has none: the- * timestamp token for the SHA-256 of the signature value, as an unsigned- * attribute. The signature itself is unchanged.+ * Adds a signature timestamp (PAdES B-T) to a CMS without one that checks+ * out: the timestamp token for the SHA-256 of the signature value, as an+ * unsigned attribute. A timestamp attribute that does not check out (empty,+ * for another signature, or not verifying) is replaced. The signature itself+ * is unchanged.*/export async function addSignatureTimestamp(cms: Uint8Array,@@ -615,7 +732,7 @@ export async function addSignatureTimestamp(const bytes = Buffer.from(cms);const info = readSignerInfo(bytes);- if (info.unsignedAttributeIds.includes(CMS_OIDS.timeStampToken)) {+ if (hasSignatureTimestamp(info)) {return bytes;}@@ -632,7 +749,13 @@ export async function addSignatureTimestamp(.map((field) => elementBytes(bytes, field));const attributes = [...(unsigned- ? children(bytes, unsigned).map((item) => elementBytes(bytes, item))+ ? children(bytes, unsigned)+ .filter(+ (item) =>+ readOid(bytes, children(bytes, item)[0]!) !==+ CMS_OIDS.timeStampToken,+ )+ .map((item) => elementBytes(bytes, item)): []),attribute(CMS_OIDS.timeStampToken, token),];diff --git a/src/lib/services/signing-provider-test-support.ts b/src/lib/services/signing-provider-test-support.tsindex 24839e0..1f91028 100644--- a/src/lib/services/signing-provider-test-support.ts+++ b/src/lib/services/signing-provider-test-support.ts@@ -41,6 +41,13 @@ export type ProviderStandIns = {lastAuthorize: URLSearchParams | null;/** Signing requests refused for a hash nobody authorized. */refusedHashes: number;+ /**+ * A second certificate the signer holds at the CSC provider, listed+ * before their own (for example an ordinary one beside a qualified one).+ */+ otherCredential: StandInSigner | null;+ /** The credential the last CSC signature was made with. */+ signedWith: string | null;/** When true, the signer cancels at the provider. */signerCancels: boolean;};@@ -94,9 +101,17 @@ export async function startProviderStandIns(): Promise<ProviderStandIns> {const state: ProviderStandIns["state"] = {lastAuthorize: null,+ otherCredential: null,refusedHashes: 0,+ signedWith: null,signerCancels: false,};+ const credential = (id: string | undefined): StandInSigner | null =>+ id === "credential-1"+ ? signer+ : id === "credential-0"+ ? state.otherCredential+ : null;const documents = new Map<string,{ digest: Buffer; redirect: string; signed: boolean }@@ -283,7 +298,11 @@ export async function startProviderStandIns(return;}- json(response, 200, { credentialIDs: ["credential-1"] });+ json(response, 200, {+ credentialIDs: state.otherCredential+ ? ["credential-0", "credential-1"]+ : ["credential-1"],+ });return;}@@ -293,9 +312,18 @@ export async function startProviderStandIns(return;}+ const holder = credential(+ (JSON.parse(body) as { credentialID?: string }).credentialID,+ );++ if (!holder) {+ json(response, 400, { error: "invalid_request" });+ return;+ }+json(response, 200, {cert: {- certificates: signer.chain.map((item) => item.toString("base64")),+ certificates: holder.chain.map((item) => item.toString("base64")),status: "valid",},key: { algo: [CMS_OIDS.rsaEncryption], status: "enabled" },@@ -324,11 +352,19 @@ export async function startProviderStandIns(return;}+ const holder = credential(input.credentialID);++ if (!holder) {+ json(response, 400, { error: "invalid_request" });+ return;+ }+tokens.delete((request.headers.authorization ?? "").slice(7));+ state.signedWith = input.credentialID;json(response, 200, {signatures: [privateEncrypt(- signer.privateKeyPem,+ holder.privateKeyPem,Buffer.concat([SHA256_DIGEST_INFO, hash]),).toString("base64"),],diff --git a/src/lib/services/signing-providers.test.ts b/src/lib/services/signing-providers.test.tsindex 227075a..1e04e9b 100644--- a/src/lib/services/signing-providers.test.ts+++ b/src/lib/services/signing-providers.test.ts@@ -2,7 +2,7 @@ import assert from "node:assert/strict";import { createHash } from "node:crypto";import test from "node:test";-import { startTestPki } from "./pki-test-support.ts";+import { startTestPki, type TestPki } from "./pki-test-support.ts";import {followSigner,STAND_IN_CLIENT,@@ -23,7 +23,7 @@ const RETURN_URL = "https://sign.example.org/api/signing/provider/return";const digest = createHash("sha256").update("revision bytes").digest();async function withStandIns(- body: (standIns: ProviderStandIns) => Promise<void>,+ body: (standIns: ProviderStandIns, pki: TestPki) => Promise<void>,) {const pki = await startTestPki();const signer = pki.issueSigner({@@ -36,7 +36,7 @@ async function withStandIns(});try {- await body(standIns);+ await body(standIns, pki);} finally {await standIns.close();await pki.close();@@ -44,11 +44,14 @@ async function withStandIns(}/** Runs a provider's whole flow, following each redirect as a browser. */-async function signWith(provider: SigningProvider) {+async function signWith(+ provider: SigningProvider,+ level: "advanced" | "qualified" = "qualified",+) {const started = await provider.start({contentDigest: digest,documentName: "Supply agreement / 2026",- level: "qualified",+ level,returnUrl: RETURN_URL,signer: { email: "[email protected]", name: "Alice Example" },state: "session-1",@@ -160,6 +163,67 @@ test("a CSC provider signs after the signer chooses a certificate and authorizes});});+test("for a qualified signature the CSC provider uses the signer's qualified certificate", async () => {+ await withStandIns(async (standIns, pki) => {+ const ordinary = pki.issueSigner({ commonName: "Alice Example" });+ const provider = createCscProvider({+ apiUrl: standIns.cscUrl,+ clientId: STAND_IN_CLIENT.id,+ clientSecret: STAND_IN_CLIENT.secret,+ name: "Test QTSP",+ });++ // Alice also holds an ordinary certificate there, listed first.+ standIns.state.otherCredential = {+ chain: [ordinary.certificate, pki.caCertificate],+ privateKeyPem: ordinary.privateKeyPem,+ };++ const qualified = await signWith(provider, "qualified");++ assert.equal(standIns.state.signedWith, "credential-1");+ assert.equal(+ checkSignerSignature(qualified.cms, digest, { level: "qualified" })+ .qualified,+ true,+ );++ // For an advanced signature the first usable one does.+ const advanced = await signWith(provider, "advanced");++ assert.equal(standIns.state.signedWith, "credential-0");+ assert.equal(+ checkSignerSignature(advanced.cms, digest, { level: "advanced" })+ .qualified,+ false,+ );++ // With only an ordinary certificate there, a qualified signature stops+ // before the signer is asked to authorize anything.+ const onlyOrdinary = await startProviderStandIns({+ chain: [ordinary.certificate, pki.caCertificate],+ privateKeyPem: ordinary.privateKeyPem,+ });++ try {+ await assert.rejects(+ signWith(+ createCscProvider({+ apiUrl: onlyOrdinary.cscUrl,+ clientId: STAND_IN_CLIENT.id,+ clientSecret: STAND_IN_CLIENT.secret,+ name: "Test QTSP",+ }),+ ),+ /Test QTSP has no qualified signing certificate/,+ );+ assert.equal(onlyOrdinary.state.lastAuthorize?.get("scope"), "service");+ } finally {+ await onlyOrdinary.close();+ }+ });+});+test("a signer who cancels at the CSC provider is told where it stopped", async () => {await withStandIns(async (standIns) => {standIns.state.signerCancels = true;diff --git a/src/lib/services/signing-providers.ts b/src/lib/services/signing-providers.tsindex 61388f7..5002215 100644--- a/src/lib/services/signing-providers.ts+++ b/src/lib/services/signing-providers.ts@@ -8,6 +8,7 @@ import {CMS_OIDS,ecdsaSignatureAsDer,hasEcKey,+ isQualifiedSignatureCertificate,signatureAlgorithmFor,type SignatureLevel,} from "./signer-cms.ts";@@ -280,6 +281,21 @@ type CscCredentialInfo = {key?: { status?: string };};+/**+ * Whether a certificate can make a signature of this level. For a qualified+ * signature it has to say it is qualified, on a qualified device; the CMS is+ * checked again after signing. A certificate that cannot be read is skipped.+ */+function meetsLevel(certificate: Buffer, level: SignatureLevel): boolean {+ try {+ const parsed = parseCertificate(certificate);++ return level !== "qualified" || isQualifiedSignatureCertificate(parsed);+ } catch {+ return false;+ }+}+export function createCscProvider({apiUrl,clientId,@@ -358,6 +374,10 @@ export function createCscProvider({);}+ // The level the envelope asks for, kept from the start.+ const level: SignatureLevel =+ data.level === "qualified" ? "qualified" : "advanced";+if (data.step === "service") {// The signer signed in: find their certificate, and ask them to// authorize the signature of exactly this hash.@@ -386,7 +406,8 @@ export function createCscProvider({if (certificates.length > 0 &&(info.cert?.status ?? "valid") === "valid" &&- (info.key?.status ?? "enabled") === "enabled"+ (info.key?.status ?? "enabled") === "enabled" &&+ meetsLevel(certificates[0]!, level)) {chosen = { certificates, id: credentialID };break;@@ -395,13 +416,12 @@ export function createCscProvider({if (!chosen) {throw new SigningProviderError(- `${name} has no usable signing certificate for this signer.`,+ level === "qualified"+ ? `${name} has no qualified signing certificate for this signer.`+ : `${name} has no usable signing certificate for this signer.`,);}- // Read now, so a certificate that cannot be read stops here.- parseCertificate(chosen.certificates[0]!);-const signedAttributes = buildSignedAttributes({certificate: chosen.certificates[0]!,contentDigest,@@ -487,11 +507,11 @@ export function createCscProvider({method: "csc",};},- async start({ returnUrl, state }) {+ async start({ level, returnUrl, state }) {const first = pkce();return {- data: { step: "service", verifier: first.verifier },+ data: { level, step: "service", verifier: first.verifier },kind: "redirect",redirectUrl: authorizeUrl({ scope: "service" },diff --git a/src/lib/signing.ts b/src/lib/signing.tsindex f34ae4d..64f3d0c 100644--- a/src/lib/signing.ts+++ b/src/lib/signing.ts@@ -1912,36 +1912,45 @@ async function reauthenticatePart11Signer(* Makes a provider-signed revision the envelope's current one, within the* transaction that records the signature. Refused when another revision was* committed since this signer began, so no signature is ever built on a- * revision that is no longer the latest.+ * revision that is no longer the latest. Returns the storage key of the+ * revision it replaces (null when it was built on the source PDF), which the+ * new one contains and which can go once the transaction commits.*/async function commitProviderRevision(tx: DbExecutor,envelopeId: string,completion: ProviderSignatureCompletion,now: number,-) {- const revision = await tx.query(+): Promise<string | null> {+ // Locked, so the revision read here is the one the update below replaces.+ const current = await queryOne<{ revisionKey: string | null }>(+ tx,`- UPDATE envelopes- SET revision_key = $1, revision_sha256 = $2- WHERE id = $3- AND revision_sha256 IS NOT DISTINCT FROM $4+ SELECT revision_key AS "revisionKey"+ FROM envelopes+ WHERE id = $1+ AND revision_sha256 IS NOT DISTINCT FROM $2+ FOR UPDATE`,- [- completion.revision.key,- completion.revision.sha256,- envelopeId,- completion.baseSha256,- ],+ [envelopeId, completion.baseSha256],);- if (revision.rowCount !== 1) {+ if (!current) {throw new SigningMutationError("The document changed while you were signing. Open your signing link again.",409,);}+ await tx.query(+ `+ UPDATE envelopes+ SET revision_key = $1, revision_sha256 = $2+ WHERE id = $3+ `,+ [completion.revision.key, completion.revision.sha256, envelopeId],+ );+const session = await tx.query(`UPDATE provider_signing_sessions@@ -1954,6 +1963,19 @@ async function commitProviderRevision(if (session.rowCount !== 1) {throw new SigningMutationError("This signing session has ended.", 409);}++ return current.revisionKey === completion.revision.key+ ? null+ : current.revisionKey;+}++async function deleteReplacedRevision(+ key: string | null,+ storageService: StorageService,+) {+ if (key) {+ await storageService.deleteObject(key).catch(() => undefined);+ }}type SigningContext = Awaited<ReturnType<typeof resolveSigningContext>>;@@ -2207,8 +2229,13 @@ export async function submitSigningForToken({ database, emailService, requestMeta, verifyPassword },);const storageService = givenStorageService ?? createStorageService();- const submittedAt =- providerSignature?.submittedAt ?? Math.floor(Date.now() / 1000);+ // When the signer signed. Through a provider, that is when they left for+ // it, the time the signed revision itself states. The next signer's turn+ // starts now, however long the provider took.+ const routedAt = Math.floor(Date.now() / 1000);+ const submittedAt = providerSignature?.submittedAt ?? routedAt;+ // The revision this signer's replaces, deleted once the change is saved.+ let replacedRevisionKey: string | null = null;const {currentSignerFields,currentSignerId,@@ -2245,7 +2272,7 @@ export async function submitSigningForToken(// Only the link itself. When it ends is settled further down, from// the deadline as it stands once the envelope is locked.- nextSignerLink = await issueSigningLink({ issuedAt: submittedAt });+ nextSignerLink = await issueSigningLink({ issuedAt: routedAt });}for (const upload of drawnSignatureUploads) {@@ -2301,7 +2328,7 @@ export async function submitSigningForToken(AND status = 'sent'RETURNING expires_at AS "expiresAt"`,- [submittedAt, context.envelope.id],+ [routedAt, context.envelope.id],);if (!lockedEnvelope) {@@ -2315,11 +2342,11 @@ export async function submitSigningForToken(nextSignerDeadline = lockedEnvelope.expiresAt;if (providerSignature) {- await commitProviderRevision(+ replacedRevisionKey = await commitProviderRevision(tx,context.envelope.id,providerSignature,- submittedAt,+ routedAt,);}@@ -2398,10 +2425,10 @@ export async function submitSigningForToken(`,[nextSignerLink.tokenHash,- nextSignerLinkExpiresAt(lockedEnvelope.expiresAt, submittedAt),- submittedAt,- submittedAt,- submittedAt,+ nextSignerLinkExpiresAt(lockedEnvelope.expiresAt, routedAt),+ routedAt,+ routedAt,+ routedAt,nextSigner.id,context.envelope.id,],@@ -2430,6 +2457,7 @@ export async function submitSigningForToken();}, database);signingStatePersisted = true;+ await deleteReplacedRevision(replacedRevisionKey, storageService);try {const delivery = await emailService.send(@@ -2534,11 +2562,11 @@ export async function submitSigningForToken(await lockSentEnvelope(context.envelope.id, tx);if (providerSignature) {- await commitProviderRevision(+ replacedRevisionKey = await commitProviderRevision(tx,context.envelope.id,providerSignature,- submittedAt,+ routedAt,);}@@ -2663,6 +2691,7 @@ export async function submitSigningForToken();}, database);signingStatePersisted = true;+ await deleteReplacedRevision(replacedRevisionKey, storageService);} catch (error) {await Promise.all(storedArtifactKeys.map((key) =>