Skip to content

Open-source document signature platform. Not affiliated with DocuSign.

TypeScript

Refuse a provider signature in someone else's name

Claudeec1a85a923a4
diff --git a/docs/self-hosting.md b/docs/self-hosting.md
index 26d06f7..24a318f 100644
--- a/docs/self-hosting.md
+++ b/docs/self-hosting.md
@@ -150,6 +150,7 @@ What ends up in the PDF:
- Each signer's signature is a PAdES signature in a revision of its own, holding their filled-in fields. The revisions only add to the file, so every earlier signer's signature stays valid, and a PDF reader lists one signature per signer with the name from their certificate.
- When the last signer has signed, the install adds the certificates and revocation answers (B-LT), and with `SEAL_TIMESTAMP_URL` an archive timestamp too (B-LTA), as for the seal above. If the provider did not timestamp a signature, the install's timestamp server does.
- The signed PDF does not get the install's seal, because the signers' signatures already cover all of it. The certificate of completion is still sealed, and lists each signer's certificate, its issuer, and the provider.
+- The certificate has to be in the name the document was sent to, so a signing link passed to someone else does not let them sign. Case, accents, punctuation, word order and ID numbers in the certificate's name do not count, and a middle name or title on one side only is allowed, but otherwise a certificate in another name is refused and the signer is asked to have the sender correct the name. Enter each signer's name as it is on their ID.
- For a qualified signature, the install refuses a certificate that does not say it is qualified and held on a qualified signature device (the EU QC statements). It does not look the issuer up on the EU trusted lists; PDF readers and the EU's own validator do that when the document is checked.
Not available in Part 11 mode, where signers sign with their accounts instead.
diff --git a/src/app/sign/[token]/page.tsx b/src/app/sign/[token]/page.tsx
index ad6a0ba..d3df637 100644
--- a/src/app/sign/[token]/page.tsx
+++ b/src/app/sign/[token]/page.tsx
@@ -18,7 +18,7 @@ type SignPageProps = {
searchParams: Promise<{ signatureProblem?: string | string[] }>;
};
-const SIGNATURE_PROBLEMS = ["cancelled", "expired", "failed"] as const;
+const SIGNATURE_PROBLEMS = ["cancelled", "expired", "failed", "name"] as const;
export default async function SignPage({
params,
diff --git a/src/components/signing/signing-live-shell.tsx b/src/components/signing/signing-live-shell.tsx
index 5759ad4..25e5bf7 100644
--- a/src/components/signing/signing-live-shell.tsx
+++ b/src/components/signing/signing-live-shell.tsx
@@ -429,7 +429,8 @@ function buildSigningSubmissionPayload(
}
/** Why a signer came back from their signing provider without signing. */
-export type ProviderSignatureProblem = "cancelled" | "expired" | "failed";
+export type ProviderSignatureProblem =
+ "cancelled" | "expired" | "failed" | "name";
function describeProviderProblem(
problem: ProviderSignatureProblem,
@@ -440,6 +441,8 @@ function describeProviderProblem(
return `You did not finish signing at ${providerName}. Nothing was signed, so you can try again.`;
case "expired":
return "Your earlier signing session ended before it finished. Nothing was signed, so you can try again.";
+ case "name":
+ return `The certificate you signed with at ${providerName} is not in the name this document was sent to. Nothing was signed. If the name is wrong, ask the sender to send the document again under the name on your certificate.`;
default:
return `${providerName} could not complete your signature. Nothing was signed. Try again, or ask the sender for help.`;
}
diff --git a/src/lib/provider-signing.dbtest.ts b/src/lib/provider-signing.dbtest.ts
index 4239b7b..3a3aa15 100644
--- a/src/lib/provider-signing.dbtest.ts
+++ b/src/lib/provider-signing.dbtest.ts
@@ -300,11 +300,33 @@ function submissionFor(signer: {
};
}
-/** The signer goes to the provider, signs, and comes back. */
+const certificates = new Map<string, ReturnType<TestPki["issueSigner"]>>();
+
+/** A qualified certificate in this name, from the test CA. */
+function certificateFor(name: string) {
+ const issued =
+ certificates.get(name) ??
+ pki.issueSigner({ commonName: name, qualified: true });
+
+ certificates.set(name, issued);
+
+ return {
+ chain: [issued.certificate, pki.caCertificate],
+ privateKeyPem: issued.privateKeyPem,
+ };
+}
+
+/**
+ * The signer goes to the provider, signs (with a certificate in their own
+ * name, unless `as` names someone else), and comes back.
+ */
async function signAtProvider(
token: string,
signer: { fields: { id: string; type: string }[]; name: string },
+ { as = signer.name }: { as?: string } = {},
) {
+ standIns.setSigner(certificateFor(as));
+
const started = await startProviderSigning(token, submissionFor(signer), {
database,
storageService,
@@ -511,13 +533,13 @@ test("two signers sign with qualified signatures, each in a revision of their ow
assert.equal(signedEvents.rows.length, 2);
- for (const row of signedEvents.rows) {
+ for (const [index, row] of signedEvents.rows.entries()) {
assert.equal(row.metadata.providerSignature?.level, "qualified");
assert.equal(row.metadata.providerSignature?.provider, "eID Easy");
assert.equal(row.metadata.providerSignature?.method, "smart-id-signature");
assert.match(
String(row.metadata.providerSignature?.certificateSubject),
- /Qualified Signer/,
+ index === 0 ? /Riley Recipient/ : /Casey Second/,
);
}
@@ -756,3 +778,39 @@ test("an ended session keeps no secrets, and the daily cleanup ends abandoned on
["", ""],
);
});
+
+test("a certificate in someone else's name does not sign for the invited signer", async () => {
+ const draft = await createDraft();
+
+ await send(draft, "qualified");
+
+ const token = await linkFor(draft.riley.id);
+ // Someone holding Riley's link signs in at the provider as themselves.
+ const other = await signAtProvider(token, draft.riley, {
+ as: "Morgan Other",
+ });
+
+ await assert.rejects(
+ other.finish(),
+ (error: unknown) =>
+ error instanceof ProviderSigningError &&
+ error.problem === "name" &&
+ error.token === token &&
+ /Morgan Other/.test(error.message),
+ );
+ assert.deepEqual(await sessionStates(draft.envelopeId), ["failed"]);
+
+ const signer = await database.query<{ status: string }>(
+ `select status from signers where id = $1`,
+ [draft.riley.id],
+ );
+
+ assert.equal(signer.rows[0]?.status, "notified");
+
+ // Riley, in their own name, can still sign.
+ await (await signAtProvider(token, draft.riley)).finish();
+ assert.deepEqual(await sessionStates(draft.envelopeId), [
+ "completed",
+ "failed",
+ ]);
+});
diff --git a/src/lib/provider-signing.ts b/src/lib/provider-signing.ts
index 1d18dfe..8f0c876 100644
--- a/src/lib/provider-signing.ts
+++ b/src/lib/provider-signing.ts
@@ -14,6 +14,7 @@ import {
} from "./services/seal-identity.ts";
import {
addSignatureTimestamp,
+ certificateMatchesName,
checkSignerSignature,
SignerSignatureError,
type SignatureLevel,
@@ -72,12 +73,15 @@ type SessionRow = {
provider: string;
revisionKey: string;
secretData: string;
+ /** The name the document was sent to this signer under. */
+ signerName: string;
state: "completed" | "failed" | "pending" | "signing";
submittedAt: number;
};
/** Why a signer is sent back to the signing page, as the page shows it. */
-export type ProviderSigningProblem = "cancelled" | "expired" | "failed";
+export type ProviderSigningProblem =
+ "cancelled" | "expired" | "failed" | "name";
export class ProviderSigningError extends Error {
readonly problem: ProviderSigningProblem;
@@ -287,6 +291,14 @@ export async function startProviderSigning(
return { redirectUrl: step.redirectUrl };
}
+/** A signature by a certificate in someone else's name. */
+class SignerNameError extends SignerSignatureError {
+ constructor(message: string) {
+ super(message);
+ this.name = "SignerNameError";
+ }
+}
+
function alreadyClaimed(token: string): ProviderSigningError {
return new ProviderSigningError(
"This signing session is already being completed.",
@@ -359,19 +371,21 @@ export async function resumeProviderSigning(
database,
`
SELECT
- id,
- envelope_id AS "envelopeId",
- provider,
- level,
- state,
- base_sha256 AS "baseSha256",
- revision_key AS "revisionKey",
- content_digest AS "contentDigest",
- secret_data AS "secretData",
- submitted_at AS "submittedAt",
- expires_at AS "expiresAt"
- FROM provider_signing_sessions
- WHERE id = $1
+ sessions.id,
+ sessions.envelope_id AS "envelopeId",
+ sessions.provider,
+ sessions.level,
+ sessions.state,
+ sessions.base_sha256 AS "baseSha256",
+ sessions.revision_key AS "revisionKey",
+ sessions.content_digest AS "contentDigest",
+ sessions.secret_data AS "secretData",
+ sessions.submitted_at AS "submittedAt",
+ sessions.expires_at AS "expiresAt",
+ signers.name AS "signerName"
+ FROM provider_signing_sessions AS sessions
+ JOIN signers ON signers.id = sessions.signer_id
+ WHERE sessions.id = $1
`,
[sessionId],
);
@@ -474,6 +488,14 @@ export async function resumeProviderSigning(
const checked = checkSignerSignature(step.cms, contentDigest, {
level: session.level,
});
+
+ // The signature has to be the invited signer's own: a signing link
+ // passed to someone else does not let them sign in their name.
+ if (!certificateMatchesName(checked.certificate, session.signerName)) {
+ throw new SignerNameError(
+ `The certificate is in the name of ${checked.subject}, not ${session.signerName}, who this document was sent to.`,
+ );
+ }
const timestampUrl = readEnv(env, "SEAL_TIMESTAMP_URL");
let cms = step.cms;
let timestamped = checked.timestamped;
@@ -549,9 +571,12 @@ export async function resumeProviderSigning(
if (error instanceof SignerSignatureError) {
console.error("[signing] The provider's signature was refused:", error);
- throw new ProviderSigningError(error.message, "failed", secret.token, {
- cause: error,
- });
+ throw new ProviderSigningError(
+ error.message,
+ error instanceof SignerNameError ? "name" : "failed",
+ secret.token,
+ { cause: error },
+ );
}
throw new ProviderSigningError(
diff --git a/src/lib/services/pdf-revision.test.ts b/src/lib/services/pdf-revision.test.ts
index 5ac9419..e64c893 100644
--- a/src/lib/services/pdf-revision.test.ts
+++ b/src/lib/services/pdf-revision.test.ts
@@ -15,6 +15,7 @@ import {
addLongTermValidation,
createValidationFetch,
describePadesLevel,
+ parseCertificate,
resetValidationCache,
} from "./pdf-ltv.ts";
import {
@@ -26,6 +27,8 @@ import { buildCadesSignature, requestDocumentTimestamp } from "./pdf-seal.ts";
import { startTestPki, type TestPki } from "./pki-test-support.ts";
import {
addSignatureTimestamp,
+ certificateHolderNames,
+ certificateMatchesName,
checkSignerSignature,
ecdsaSignatureAsDer,
SignerSignatureError,
@@ -461,6 +464,51 @@ test("raw ECDSA r and s are encoded, even when they start like a SEQUENCE", () =
);
});
+test("a certificate matches the name a signer was sent the document under", async () => {
+ await withPki(async (pki) => {
+ const plain = parseCertificate(
+ pki.issueSigner({ commonName: "Alice Example" }).certificate,
+ );
+ const national = parseCertificate(
+ pki.issueSigner({
+ commonName: "MÄNNIK,MARI-LIIS,47101010033",
+ givenName: "MARI-LIIS",
+ surname: "MÄNNIK",
+ }).certificate,
+ );
+
+ assert.deepEqual(certificateHolderNames(national), [
+ "MARI-LIIS MÄNNIK",
+ "MÄNNIK,MARI-LIIS,47101010033",
+ ]);
+
+ for (const name of [
+ "Alice Example",
+ "alice example",
+ "Example, Alice",
+ "Dr. Alice Example",
+ "Alice B. Example",
+ ]) {
+ assert.equal(certificateMatchesName(plain, name), true, name);
+ }
+
+ for (const name of ["Bob Example", "Alice", "Alice Sample", ""]) {
+ assert.equal(certificateMatchesName(plain, name), false, name);
+ }
+
+ // Accents, hyphens, case and the ID code in the common name do not count.
+ for (const name of [
+ "Mari-Liis Männik",
+ "Mari Liis Mannik",
+ "Männik Mari-Liis",
+ ]) {
+ assert.equal(certificateMatchesName(national, name), true, name);
+ }
+
+ assert.equal(certificateMatchesName(national, "Kadri Männik"), false);
+ });
+});
+
test("the signature slot fits a chain and a timestamp", () => {
assert.ok(SIGNER_SIGNATURE_BYTES >= 16_384);
});
diff --git a/src/lib/services/pki-test-support.ts b/src/lib/services/pki-test-support.ts
index b0d95b5..e7336aa 100644
--- a/src/lib/services/pki-test-support.ts
+++ b/src/lib/services/pki-test-support.ts
@@ -98,26 +98,48 @@ function sortedSet(items: Buffer[]): Buffer {
return der.set(...[...items].sort(Buffer.compare));
}
+/** A subject attribute, as UTF8String when it is not plain ASCII. */
+function subjectAttribute(
+ type: string,
+ value: string,
+): forge.pki.CertificateField {
+ return /^[\x00-\x7f]*$/.test(value)
+ ? { type, value }
+ : {
+ type,
+ // forge writes a UTF8String's value as UTF-8 itself.
+ value,
+ // forge reads this as the value's tag, though its types say class.
+ valueTagClass: forge.asn1.Type.UTF8 as unknown as forge.asn1.Class,
+ };
+}
+
function issueCertificate({
ca = false,
commonName,
extensions = [],
+ givenName,
issuer,
keys,
serial,
+ surname,
}: {
ca?: boolean;
commonName: string;
extensions?: object[];
+ givenName?: string;
issuer: { certificate: forge.pki.Certificate | null; keys: KeyPair };
keys: KeyPair;
serial: string;
+ surname?: string;
}): forge.pki.Certificate {
const certificate = forge.pki.createCertificate();
const notBefore = new Date(Date.now() - 24 * 60 * 60 * 1000);
const notAfter = new Date(Date.now() + 365 * 24 * 60 * 60 * 1000);
const subject = [
- { name: "commonName", value: commonName },
+ subjectAttribute("2.5.4.3", commonName),
+ ...(surname ? [subjectAttribute("2.5.4.4", surname)] : []),
+ ...(givenName ? [subjectAttribute("2.5.4.42", givenName)] : []),
{ name: "organizationName", value: "Harbour & Finch Test CA" },
];
@@ -167,7 +189,10 @@ export type TestPki = {
*/
issueSigner: (options: {
commonName: string;
+ /** Given name and surname, as national eID certificates carry them. */
+ givenName?: string;
qualified?: boolean;
+ surname?: string;
}) => SealIdentity & { certificate: Buffer };
/** A seal identity issued by the CA, its chain holding only itself. */
seal: SealIdentity;
@@ -489,7 +514,12 @@ export async function startTestPki(): Promise<TestPki> {
};
let signerSerial = 0x4000;
- const issueSigner: TestPki["issueSigner"] = ({ commonName, qualified }) => {
+ const issueSigner: TestPki["issueSigner"] = ({
+ commonName,
+ givenName,
+ qualified,
+ surname,
+ }) => {
const keys = makeKeys();
// QCStatements: QcCompliance, QcSSCD, QcType esign (ETSI EN 319 412-5).
const qcStatements = {
@@ -511,9 +541,11 @@ export async function startTestPki(): Promise<TestPki> {
const certificate = issueCertificate({
commonName,
extensions: [infoAccess, crlPoints, ...(qualified ? [qcStatements] : [])],
+ givenName,
issuer: { certificate: ca, keys: caKeys },
keys,
serial: signerSerial.toString(16),
+ surname,
});
return {
diff --git a/src/lib/services/signer-cms.ts b/src/lib/services/signer-cms.ts
index dd8ba43..c5d9981 100644
--- a/src/lib/services/signer-cms.ts
+++ b/src/lib/services/signer-cms.ts
@@ -612,6 +612,99 @@ export function isQualifiedSignatureCertificate(
);
}
+const NAME_OIDS = {
+ commonName: "2.5.4.3",
+ givenName: "2.5.4.42",
+ surname: "2.5.4.4",
+} as const;
+
+/** A DirectoryString's text, or null for a kind not read here. */
+function readDirectoryString(bytes: Buffer, tlv: Tlv): string | null {
+ const content = contentBytes(bytes, tlv);
+
+ switch (tlv.tag) {
+ case 0x0c: // UTF8String
+ return content.toString("utf8");
+ case 0x13: // PrintableString
+ case 0x14: // TeletexString, read as Latin-1
+ case 0x16: // IA5String
+ return content.toString("latin1");
+ case 0x1e: // BMPString, UTF-16 big-endian
+ return Buffer.from(content).swap16().toString("utf16le");
+ default:
+ return null;
+ }
+}
+
+/**
+ * The names a certificate gives its holder: the given name and surname
+ * together, when it has both, and its common name.
+ */
+export function certificateHolderNames(certificate: Certificate): string[] {
+ const bytes = certificate.subjectName;
+ const values = new Map<string, string[]>();
+
+ for (const set of children(bytes, readTlv(bytes))) {
+ for (const item of children(bytes, set)) {
+ const [type, value] = children(bytes, item);
+ const text = value ? readDirectoryString(bytes, value) : null;
+
+ if (type && text) {
+ const oid = readOid(bytes, type);
+
+ values.set(oid, [...(values.get(oid) ?? []), text]);
+ }
+ }
+ }
+
+ const given = values.get(NAME_OIDS.givenName)?.join(" ");
+ const surname = values.get(NAME_OIDS.surname)?.join(" ");
+
+ return [
+ ...(given && surname ? [`${given} ${surname}`] : []),
+ ...(values.get(NAME_OIDS.commonName) ?? []),
+ ];
+}
+
+/** A name's words, without case, accents, punctuation or numbers. */
+function nameWords(name: string): Set<string> {
+ return new Set(
+ name
+ .normalize("NFKD")
+ .replace(/\p{M}+/gu, "")
+ .toLocaleLowerCase("en")
+ .split(/[^\p{L}\p{N}]+/u)
+ .filter((word) => word.length > 0 && !/\p{N}/u.test(word)),
+ );
+}
+
+/**
+ * Whether a certificate is in the name a signer was sent the document
+ * under. Case, accents, punctuation and word order do not count, nor do
+ * numbers (some national certificates put the holder's ID code in the
+ * common name). A name may have words the other lacks, such as a middle
+ * name or a title, as long as at least two words match and every word of
+ * the shorter name is in the longer; a one-word name has to match exactly.
+ */
+export function certificateMatchesName(
+ certificate: Certificate,
+ invitedName: string,
+): boolean {
+ const invited = nameWords(invitedName);
+
+ return certificateHolderNames(certificate).some((name) => {
+ const words = nameWords(name);
+ const [shorter, longer] =
+ words.size <= invited.size ? [words, invited] : [invited, words];
+
+ return (
+ shorter.size > 0 &&
+ [...shorter].every((word) => longer.has(word)) &&
+ (shorter.size >= 2 || words.size === invited.size)
+ );
+ });
+}
+
/**
* Checks a signer's CMS before it goes into the document: it signs exactly
* `contentDigest` (SHA-256 of the revision's signed bytes), it verifies with
diff --git a/src/lib/services/signing-provider-test-support.ts b/src/lib/services/signing-provider-test-support.ts
index 1f91028..4bd2333 100644
--- a/src/lib/services/signing-provider-test-support.ts
+++ b/src/lib/services/signing-provider-test-support.ts
@@ -34,6 +34,8 @@ export type StandInSigner = {
export type ProviderStandIns = {
close: () => Promise<void>;
+ /** Who signs from now on, as if another person signed in. */
+ setSigner: (next: StandInSigner) => void;
cscUrl: string;
eidEasyUrl: string;
state: {
@@ -96,7 +98,7 @@ function cmsForDigest(signer: StandInSigner, digest: Buffer): Buffer {
}
export async function startProviderStandIns(
- signer: StandInSigner,
+ firstSigner: StandInSigner,
{ port = 0 }: { port?: number } = {},
): Promise<ProviderStandIns> {
const state: ProviderStandIns["state"] = {
@@ -106,6 +108,7 @@ export async function startProviderStandIns(
signedWith: null,
signerCancels: false,
};
+ let signer = firstSigner;
const credential = (id: string | undefined): StandInSigner | null =>
id === "credential-1"
? signer
@@ -390,6 +393,9 @@ export async function startProviderStandIns(
}),
cscUrl: `${base}/csc`,
eidEasyUrl: `${base}/eideasy`,
+ setSigner: (next) => {
+ signer = next;
+ },
state,
};
}