Skip to content

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

TypeScript

Fix the issues found in review of the compliance changes

Claude216f05842869
diff --git a/src/components/verify/verify-form.tsx b/src/components/verify/verify-form.tsx
index 662d87e..0cec82d 100644
--- a/src/components/verify/verify-form.tsx
+++ b/src/components/verify/verify-form.tsx
@@ -98,6 +98,8 @@ export function VerifyForm() {
accept="application/pdf,.pdf"
aria-label="PDF to verify"
className="mx-auto mt-4 block text-sm"
+ // One file at a time, so a verdict cannot land on the wrong one.
+ disabled={isChecking}
onChange={handleFile}
type="file"
/>
diff --git a/src/lib/downloads.ts b/src/lib/downloads.ts
index 6a13262..0666997 100644
--- a/src/lib/downloads.ts
+++ b/src/lib/downloads.ts
@@ -831,6 +831,26 @@ export async function renewRecipientDownloadLinks(
);
}
+ // The new links replace the old ones, so keep the old rows to put back
+ // if the email does not go out: the signer can then try again.
+ const previousTokens = await queryMany<{
+ createdAt: number;
+ expiresAt: number;
+ fileType: string;
+ tokenHash: string;
+ }>(
+ database,
+ `
+ SELECT
+ token_hash AS "tokenHash",
+ file_type AS "fileType",
+ expires_at AS "expiresAt",
+ created_at AS "createdAt"
+ FROM recipient_download_tokens
+ WHERE envelope_id = $1 AND signer_id = $2
+ `,
+ [envelope.id, signer.id],
+ );
const issuedAt = Math.floor(Date.now() / 1000);
const [signedLink, evidenceLink] = await Promise.all([
envelope.status === "completed"
@@ -855,12 +875,34 @@ export async function renewRecipientDownloadLinks(
),
]);
- await sendLinks({
- envelope,
- evidenceUrl: evidenceLink.url,
- signedUrl: signedLink?.url ?? null,
- signer,
- });
+ try {
+ await sendLinks({
+ envelope,
+ evidenceUrl: evidenceLink.url,
+ signedUrl: signedLink?.url ?? null,
+ signer,
+ });
+ } catch (error) {
+ for (const previous of previousTokens) {
+ await database.query(
+ `
+ UPDATE recipient_download_tokens
+ SET token_hash = $1, expires_at = $2, created_at = $3
+ WHERE envelope_id = $4 AND signer_id = $5 AND file_type = $6
+ `,
+ [
+ previous.tokenHash,
+ previous.expiresAt,
+ previous.createdAt,
+ envelope.id,
+ signer.id,
+ previous.fileType,
+ ],
+ );
+ }
+
+ throw error;
+ }
return { maskedEmail: maskEmail(signer.email) };
}
diff --git a/src/lib/retention.ts b/src/lib/retention.ts
index a16aec4..c4d2171 100644
--- a/src/lib/retention.ts
+++ b/src/lib/retention.ts
@@ -460,8 +460,18 @@ type FinishedEnvelopeRow = EnvelopeArtifactRow & {
title: string;
};
-async function listFinishedEnvelopesOlderThan(
- finishedBefore: number,
+/**
+ * Finished envelopes there is something to do with now: not yet warned and
+ * inside the warning window, or warned long enough ago and past the period.
+ * Envelopes waiting out their notice are left out, so they cannot fill the
+ * batch and hold back the ones behind them.
+ */
+async function listFinishedEnvelopesToHandle(
+ {
+ deleteBefore,
+ warnBefore,
+ warnedBefore,
+ }: { deleteBefore: number; warnBefore: number; warnedBefore: number },
database: DbExecutor,
): Promise<FinishedEnvelopeRow[]> {
return queryMany<FinishedEnvelopeRow>(
@@ -483,11 +493,20 @@ async function listFinishedEnvelopesOlderThan(
FROM envelopes e
JOIN "user" u ON u.id = e.user_id
WHERE e.status IN ('completed', 'declined', 'voided')
- AND COALESCE(e.completed_at, e.declined_at, e.voided_at, e.updated_at) < $1
+ AND (
+ (
+ e.retention_warned_at IS NULL
+ AND COALESCE(e.completed_at, e.declined_at, e.voided_at, e.updated_at) < $1
+ )
+ OR (
+ e.retention_warned_at <= $3
+ AND COALESCE(e.completed_at, e.declined_at, e.voided_at, e.updated_at) < $2
+ )
+ )
ORDER BY "finishedAt" ASC, e.id ASC
LIMIT 500
`,
- [finishedBefore],
+ [warnBefore, deleteBefore, warnedBefore],
);
}
@@ -543,7 +562,14 @@ async function applyRetentionPeriod(
) {
const warnBefore =
now - (retentionDays - RETENTION_WARNING_DAYS) * DAY_IN_SECONDS;
- const candidates = await listFinishedEnvelopesOlderThan(warnBefore, database);
+ const candidates = await listFinishedEnvelopesToHandle(
+ {
+ deleteBefore: now - retentionDays * DAY_IN_SECONDS,
+ warnBefore,
+ warnedBefore: now - RETENTION_MIN_NOTICE_DAYS * DAY_IN_SECONDS,
+ },
+ database,
+ );
const fieldImagesByEnvelopeId = await listFieldImagesForEnvelopeIds(
candidates.map((envelope) => envelope.id),
database,
@@ -573,19 +599,21 @@ async function applyRetentionPeriod(
continue;
}
+ // Files first: a failure leaves the row, so the next run retries.
+ await deleteStorageKeys(
+ buildEnvelopeStorageKeys(
+ envelope,
+ fieldImagesByEnvelopeId.get(envelope.id) ?? [],
+ ),
+ storageService,
+ );
+
const deleted = await database.query(
`DELETE FROM envelopes WHERE id = $1 AND status = $2`,
[envelope.id, envelope.status],
);
if (deleted.rowCount === 1) {
- await deleteStorageKeys(
- buildEnvelopeStorageKeys(
- envelope,
- fieldImagesByEnvelopeId.get(envelope.id) ?? [],
- ),
- storageService,
- );
summary.finishedEnvelopesDeleted += 1;
}
} catch (error) {
@@ -628,11 +656,9 @@ export async function deleteEnvelopesAndFiles(
envelopes.map((envelope) => envelope.id),
database,
);
- const deleted = await database.query(
- `DELETE FROM envelopes WHERE id = ANY($1::text[])`,
- [envelopes.map((envelope) => envelope.id)],
- );
-
+ // Files first, then rows: if a file cannot be deleted, the row (and the
+ // list of its files) is still there for the next attempt. Deleting a
+ // file that is already gone succeeds.
for (const envelope of envelopes) {
await deleteStorageKeys(
buildEnvelopeStorageKeys(
@@ -640,14 +666,14 @@ export async function deleteEnvelopesAndFiles(
fieldImagesByEnvelopeId.get(envelope.id) ?? [],
),
storageService,
- ).catch((error) => {
- console.error(
- `Failed to delete files of envelope ${envelope.id}:`,
- error,
- );
- });
+ );
}
+ const deleted = await database.query(
+ `DELETE FROM envelopes WHERE id = ANY($1::text[])`,
+ [envelopes.map((envelope) => envelope.id)],
+ );
+
return deleted.rowCount ?? 0;
}
diff --git a/src/lib/services/audit.ts b/src/lib/services/audit.ts
index dedae39..95f9240 100644
--- a/src/lib/services/audit.ts
+++ b/src/lib/services/audit.ts
@@ -10,6 +10,7 @@ import {
queryMany,
withTransaction,
} from "../db/connection.ts";
+import { canonicalJson } from "../utils/canonical-json.ts";
export type AuditEventMetadata = Record<string, unknown> | null;
@@ -98,25 +99,6 @@ type ChainedFields = {
userAgent: string | null;
};
-/** Key order is fixed so the same row always hashes the same way. */
-function canonicalJson(value: unknown): string {
- if (Array.isArray(value)) {
- return `[${value.map(canonicalJson).join(",")}]`;
- }
-
- if (value && typeof value === "object") {
- return `{${Object.keys(value)
- .sort()
- .map(
- (key) =>
- `${JSON.stringify(key)}:${canonicalJson((value as Record<string, unknown>)[key])}`,
- )
- .join(",")}}`;
- }
-
- return JSON.stringify(value ?? null);
-}
-
export function computeAuditRowHash(
previousHash: string | null,
fields: ChainedFields,
diff --git a/src/lib/services/pdf-finalize.ts b/src/lib/services/pdf-finalize.ts
index c84a472..e0974c3 100644
--- a/src/lib/services/pdf-finalize.ts
+++ b/src/lib/services/pdf-finalize.ts
@@ -19,6 +19,7 @@ import {
} from "../schemas/envelope.ts";
import type { FieldRecord } from "../schemas/field.ts";
import type { SignerRecord } from "../schemas/signer.ts";
+import { canonicalJson } from "../utils/canonical-json.ts";
import { normalizedRectToPdfRect } from "../utils/pdf-coords.ts";
import { sha256Hex } from "./pdf-seal.ts";
import { saveInstallSealedPdf, type SealPurpose } from "./seal-identity.ts";
@@ -88,7 +89,7 @@ export function computeAuditFingerprint(
): string {
return sha256Hex(
new TextEncoder().encode(
- JSON.stringify({
+ canonicalJson({
events: auditEvents.map((event) => [
event.id,
event.createdAt,
@@ -122,6 +123,8 @@ function redactAuditEventMetadataForRecipients(
const nextMetadata = { ...metadata };
delete nextMetadata.signerEmail;
+ // Who an email went to is another party's address.
+ delete nextMetadata.recipient;
return Object.keys(nextMetadata).length > 0 ? nextMetadata : null;
}
diff --git a/src/lib/services/pdf-seal.test.ts b/src/lib/services/pdf-seal.test.ts
index ab9059f..cf3edf5 100644
--- a/src/lib/services/pdf-seal.test.ts
+++ b/src/lib/services/pdf-seal.test.ts
@@ -160,55 +160,83 @@ test("a sealed PDF verifies, and any change to it is detected", async (t) => {
}
});
-test("a timestamp token from the service is stored with the signature", async () => {
- const identity = makeIdentity();
- // A stand-in service: answers "granted" with a token that is just a
- // recognisable ContentInfo. The real token's own signature is not checked
- // here; only that it is requested and stored in the right place.
- const marker = forge.asn1.create(
- forge.asn1.Class.UNIVERSAL,
- forge.asn1.Type.SEQUENCE,
- true,
- [
- forge.asn1.create(
- forge.asn1.Class.UNIVERSAL,
- forge.asn1.Type.OID,
- false,
- forge.asn1.oidToDer(SEAL_TEST_OIDS.signedData).getBytes(),
- ),
- ],
- );
- let requestContentType: string | undefined;
+// A stand-in time-stamping service. It answers "granted" with a token
+// shaped like a real one (ContentInfo > SignedData > TSTInfo) that echoes
+// the request's hash and nonce, or a wrong hash when told to. The token's
+// own signature is not made: readers check that, not this code.
+async function withTimestampServer(
+ { wrongImprint = false }: { wrongImprint?: boolean },
+ run: (url: string, seen: { contentType?: string }) => Promise<void>,
+) {
+ const a = forge.asn1;
+ const seq = (value: forge.asn1.Asn1[]) =>
+ a.create(a.Class.UNIVERSAL, a.Type.SEQUENCE, true, value);
+ const oid = (value: string) =>
+ a.create(
+ a.Class.UNIVERSAL,
+ a.Type.OID,
+ false,
+ a.oidToDer(value).getBytes(),
+ );
+ const integer = (value: string) =>
+ a.create(a.Class.UNIVERSAL, a.Type.INTEGER, false, value);
+ const seen: { contentType?: string } = {};
const server = createServer((request, response) => {
- requestContentType = request.headers["content-type"];
- request.resume();
+ seen.contentType = request.headers["content-type"];
+
+ const chunks: Buffer[] = [];
+
+ request.on("data", (chunk: Buffer) => chunks.push(chunk));
request.on("end", () => {
- const answer = forge.asn1.create(
- forge.asn1.Class.UNIVERSAL,
- forge.asn1.Type.SEQUENCE,
- true,
- [
- forge.asn1.create(
- forge.asn1.Class.UNIVERSAL,
- forge.asn1.Type.SEQUENCE,
- true,
- [
- forge.asn1.create(
- forge.asn1.Class.UNIVERSAL,
- forge.asn1.Type.INTEGER,
- false,
- String.fromCharCode(0),
- ),
- ],
- ),
- marker,
- ],
- );
+ // TimeStampReq { version, messageImprint, nonce, certReq }
+ const query = a.fromDer(Buffer.concat(chunks).toString("binary"));
+ const [, messageImprint, nonce] = query.value as forge.asn1.Asn1[];
+ const imprintFields = messageImprint!.value as forge.asn1.Asn1[];
+ const hashed = wrongImprint
+ ? "x".repeat(32)
+ : (imprintFields[1]!.value as string);
+ const tstInfo = seq([
+ integer(String.fromCharCode(1)),
+ oid("1.2.3.4"),
+ seq([
+ imprintFields[0]!,
+ a.create(a.Class.UNIVERSAL, a.Type.OCTETSTRING, false, hashed),
+ ]),
+ integer(String.fromCharCode(7)),
+ a.create(
+ a.Class.UNIVERSAL,
+ a.Type.GENERALIZEDTIME,
+ false,
+ "20261112120000Z",
+ ),
+ integer(nonce!.value as string),
+ ]);
+ const token = seq([
+ oid(SEAL_TEST_OIDS.signedData),
+ a.create(a.Class.CONTEXT_SPECIFIC, 0, true, [
+ seq([
+ integer(String.fromCharCode(3)),
+ a.create(a.Class.UNIVERSAL, a.Type.SET, true, []),
+ seq([
+ oid(SEAL_TEST_OIDS.tstInfo),
+ a.create(a.Class.CONTEXT_SPECIFIC, 0, true, [
+ a.create(
+ a.Class.UNIVERSAL,
+ a.Type.OCTETSTRING,
+ false,
+ a.toDer(tstInfo).getBytes(),
+ ),
+ ]),
+ ]),
+ ]),
+ ]),
+ ]);
+ const answer = seq([seq([integer(String.fromCharCode(0))]), token]);
response.writeHead(200, {
"content-type": "application/timestamp-reply",
});
- response.end(Buffer.from(forge.asn1.toDer(answer).getBytes(), "binary"));
+ response.end(Buffer.from(a.toDer(answer).getBytes(), "binary"));
});
});
@@ -217,21 +245,43 @@ test("a timestamp token from the service is stored with the signature", async ()
try {
const address = server.address();
const port = typeof address === "object" && address ? address.port : 0;
+
+ await run(`http://127.0.0.1:${String(port)}/`, seen);
+ } finally {
+ server.close();
+ }
+}
+
+test("a timestamp token from the service is stored with the signature", async () => {
+ const identity = makeIdentity();
+
+ await withTimestampServer({}, async (timestampUrl, seen) => {
const cms = await buildCadesSignature(new Uint8Array([1, 2, 3]), identity, {
- timestampUrl: `http://127.0.0.1:${String(port)}/`,
+ timestampUrl,
});
const der = Buffer.from(cms).toString("binary");
- assert.equal(requestContentType, "application/timestamp-query");
+ assert.equal(seen.contentType, "application/timestamp-query");
assert.ok(
der.includes(
forge.asn1.oidToDer(SEAL_TEST_OIDS.timeStampToken).getBytes(),
),
"the token attribute is present",
);
- } finally {
- server.close();
- }
+ });
+});
+
+test("a timestamp token for some other request is refused", async () => {
+ const identity = makeIdentity();
+
+ await withTimestampServer({ wrongImprint: true }, async (timestampUrl) => {
+ await assert.rejects(
+ buildCadesSignature(new Uint8Array([1, 2, 3]), identity, {
+ timestampUrl,
+ }),
+ /does not answer this request/,
+ );
+ });
});
test("a PKCS#12 bundle from a certificate authority can be used", () => {
diff --git a/src/lib/services/pdf-seal.ts b/src/lib/services/pdf-seal.ts
index 84ea214..f146774 100644
--- a/src/lib/services/pdf-seal.ts
+++ b/src/lib/services/pdf-seal.ts
@@ -26,6 +26,7 @@ const OID = {
signedData: "1.2.840.113549.1.7.2",
signingCertificateV2: "1.2.840.113549.1.9.16.2.47",
timeStampToken: "1.2.840.113549.1.9.16.2.14",
+ tstInfo: "1.2.840.113549.1.9.16.1.4",
} as const;
// Room for the CMS structure, a certificate chain and a timestamp token.
@@ -110,6 +111,17 @@ function derOf(value: forge.asn1.Asn1): string {
}
/** Builds the detached CMS SignedData that goes into the PDF. */
+/** The issuer Name exactly as encoded in the certificate (RFC 5280 4.1). */
+function certificateIssuerAsn1(certificate: forge.asn1.Asn1): forge.asn1.Asn1 {
+ const tbs = (certificate.value as forge.asn1.Asn1[])[0]!;
+ const fields = tbs.value as forge.asn1.Asn1[];
+ // [0] version is optional; after it come serial, signature, issuer.
+ const offset =
+ fields[0]!.tagClass === forge.asn1.Class.CONTEXT_SPECIFIC ? 1 : 0;
+
+ return fields[offset + 2]!;
+}
+
export async function buildCadesSignature(
content: Uint8Array,
identity: SealIdentity,
@@ -119,13 +131,17 @@ export async function buildCadesSignature(
throw new PdfSealError("The seal identity has no certificate.");
}
- const certificates = identity.certificateChainPem.map((pem) =>
- forge.pki.certificateFromPem(pem),
+ // The certificates as they were issued, byte for byte. Re-encoding them
+ // through forge's parsed form can change non-ASCII names, which would
+ // break both the certificate and the issuer match below.
+ const certificateAsn1s = identity.certificateChainPem.map((pem) =>
+ forge.asn1.fromDer(forge.pem.decode(pem)[0]!.body),
);
- const signingCertificate = certificates[0]!;
- const signingCertificateDer = derOf(
- forge.pki.certificateToAsn1(signingCertificate),
+ const signingCertificateAsn1 = certificateAsn1s[0]!;
+ const signingCertificate = forge.pki.certificateFromAsn1(
+ signingCertificateAsn1,
);
+ const signingCertificateDer = derOf(signingCertificateAsn1);
const contentDigest = createHash("sha256").update(content).digest();
const certificateDigest = createHash("sha256")
.update(Buffer.from(signingCertificateDer, "binary"))
@@ -155,7 +171,7 @@ export async function buildCadesSignature(
}
const issuerAndSerial = seq([
- forge.pki.distinguishedNameToAsn1(signingCertificate.issuer),
+ certificateIssuerAsn1(signingCertificateAsn1),
integer(forge.util.hexToBytes(signingCertificate.serialNumber)),
]);
const signerInfo = seq([
@@ -173,12 +189,7 @@ export async function buildCadesSignature(
integer(String.fromCharCode(1)),
set([seq([oid(OID.sha256), nullValue()])]),
seq([oid(OID.data)]),
- contextTag(
- 0,
- certificates.map((certificate) =>
- forge.pki.certificateToAsn1(certificate),
- ),
- ),
+ contextTag(0, certificateAsn1s),
set([signerInfo]),
]);
const contentInfo = seq([oid(OID.signedData), contextTag(0, [signedData])]);
@@ -190,6 +201,65 @@ export async function buildCadesSignature(
* Asks an RFC 3161 service to timestamp the signature value, and returns the
* token (a CMS ContentInfo) to store beside it.
*/
+function stripLeadingZeros(bytes: string): string {
+ return bytes.replace(/^\x00+/, "");
+}
+
+/**
+ * Checks that a token answers this request: its TSTInfo carries the hash of
+ * this signature and this request's nonce (RFC 3161 2.4.2). The token's own
+ * signature is the time-stamping service's, and PDF readers check it.
+ */
+function assertTokenMatchesRequest(
+ token: forge.asn1.Asn1,
+ imprint: Buffer,
+ nonce: Buffer,
+) {
+ try {
+ // ContentInfo { contentType, [0] SignedData }
+ const signedData = (
+ (token.value as forge.asn1.Asn1[])[1]!.value as forge.asn1.Asn1[]
+ )[0]!;
+ // SignedData { version, digestAlgorithms, encapContentInfo, ... }
+ const encapsulated = (signedData.value as forge.asn1.Asn1[])[2]!;
+ const [contentType, explicitContent] =
+ encapsulated.value as forge.asn1.Asn1[];
+
+ if (asn1.derToOid(contentType!.value as string) !== OID.tstInfo) {
+ throw new Error("not a TSTInfo");
+ }
+
+ const octetString = (explicitContent!.value as forge.asn1.Asn1[])[0]!;
+ const tstInfo = asn1.fromDer(octetString.value as string);
+ // TSTInfo { version, policy, messageImprint, serialNumber, genTime,
+ // accuracy?, ordering?, nonce?, ... }
+ const fields = tstInfo.value as forge.asn1.Asn1[];
+ const messageImprint = fields[2]!.value as forge.asn1.Asn1[];
+ const hashed = messageImprint[1]!.value as string;
+ const tokenNonce = fields
+ .slice(5)
+ .find(
+ (field) =>
+ field.tagClass === asn1.Class.UNIVERSAL &&
+ field.type === asn1.Type.INTEGER,
+ )?.value as string | undefined;
+
+ if (
+ hashed !== imprint.toString("binary") ||
+ tokenNonce === undefined ||
+ stripLeadingZeros(tokenNonce) !==
+ stripLeadingZeros(nonce.toString("binary"))
+ ) {
+ throw new Error("imprint or nonce differs");
+ }
+ } catch (error) {
+ throw new PdfSealError(
+ "The time-stamping service sent a token that does not answer this request.",
+ { cause: error },
+ );
+ }
+}
+
async function requestTimestampToken(
signatureValue: Buffer,
timestampUrl: string,
@@ -262,6 +332,8 @@ async function requestTimestampToken(
throw new PdfSealError("The time-stamping service refused the request.");
}
+ assertTokenMatchesRequest(parts[1], imprint, nonce);
+
return parts[1];
}
diff --git a/src/lib/services/seal-identity.ts b/src/lib/services/seal-identity.ts
index 47b7912..bd0b6f0 100644
--- a/src/lib/services/seal-identity.ts
+++ b/src/lib/services/seal-identity.ts
@@ -126,6 +126,9 @@ async function identityFromDatabase(
database: DbPool,
): Promise<CachedIdentity> {
const key = encryptionKey(env);
+ // Read before the transaction: settings come through another connection,
+ // which a full pool could not give while this one waits on the lock.
+ const branding = await getBranding(env);
return withTransaction(async (tx) => {
// One instance makes the key; any other waits here and then reads it.
@@ -162,7 +165,6 @@ async function identityFromDatabase(
);
}
- const branding = await getBranding(env);
const { privateKey, publicKey } = generateKeyPairSync("rsa", {
modulusLength: 3072,
privateKeyEncoding: { format: "pem", type: "pkcs8" },
diff --git a/src/lib/signer-checks.ts b/src/lib/signer-checks.ts
index 648ab96..8931172 100644
--- a/src/lib/signer-checks.ts
+++ b/src/lib/signer-checks.ts
@@ -8,7 +8,7 @@ import {
import { type DbExecutor, getDb, queryOne } from "./db/connection.ts";
import { hashOpaqueToken } from "./services/opaque-tokens.ts";
-import { resolveAuthSecret } from "./utils/env.ts";
+import { isProduction, resolveAuthSecret } from "./utils/env.ts";
// Extra checks a sender can ask for before a signer may open and sign:
//
@@ -131,7 +131,20 @@ export function checkEmailCode(code: string, storedHash: string): boolean {
}
function cookieSecret(): string {
- return resolveAuthSecret() ?? "signudoc-development-only";
+ const secret = resolveAuthSecret();
+
+ if (secret) {
+ return secret;
+ }
+
+ // A known key would let anyone forge a passed check.
+ if (isProduction(process.env)) {
+ throw new Error(
+ "Signer checks need an auth secret: set BETTER_AUTH_SECRET or a database password.",
+ );
+ }
+
+ return "signudoc-development-only";
}
export function verificationCookieName(signingTokenHash: string): string {
@@ -205,7 +218,12 @@ export function readCookie(
const [key, ...rest] = part.trim().split("=");
if (key === name) {
- return decodeURIComponent(rest.join("="));
+ try {
+ return decodeURIComponent(rest.join("="));
+ } catch {
+ // A malformed value is treated as no cookie.
+ return null;
+ }
}
}
diff --git a/src/lib/signer-data.ts b/src/lib/signer-data.ts
index 47785ae..d4a85c0 100644
--- a/src/lib/signer-data.ts
+++ b/src/lib/signer-data.ts
@@ -1,4 +1,10 @@
-import { type DbExecutor, getDb, queryMany } from "./db/connection.ts";
+import {
+ type DbExecutor,
+ type DbPool,
+ getDb,
+ queryMany,
+ withTransaction,
+} from "./db/connection.ts";
import { deleteEnvelopesAndFiles } from "./retention.ts";
import { emailSchema } from "./schemas/common.ts";
@@ -153,7 +159,7 @@ export type SignerErasureResult = {
export async function eraseSignerData(
rawEmail: unknown,
confirmation: unknown,
- database: DbExecutor = getDb(),
+ database: DbPool = getDb(),
): Promise<SignerErasureResult> {
const email = parseEmail(rawEmail);
@@ -173,17 +179,36 @@ export async function eraseSignerData(
);
const inProgress = envelopes.filter((row) => row.envelopeStatus === "sent");
- if (drafts.length > 0) {
- await database.query(
- `
- DELETE FROM fields WHERE signer_id = ANY($1::text[])
- `,
- [drafts.map((row) => row.signerId)],
- );
- await database.query(`DELETE FROM signers WHERE id = ANY($1::text[])`, [
- drafts.map((row) => row.signerId),
- ]);
- }
+ // Lock the drafts and look at their status again: one that was sent in
+ // the meantime is skipped, not stripped of a signer mid-signing.
+ const removedFromDrafts =
+ drafts.length === 0
+ ? []
+ : await withTransaction(async (tx) => {
+ const stillDrafts = await tx.query<{ id: string }>(
+ `
+ SELECT id FROM envelopes
+ WHERE id = ANY($1::text[]) AND status = 'draft'
+ FOR UPDATE
+ `,
+ [drafts.map((row) => row.envelopeId)],
+ );
+ const draftIds = new Set(stillDrafts.rows.map((row) => row.id));
+ const signerIds = drafts
+ .filter((row) => draftIds.has(row.envelopeId))
+ .map((row) => row.signerId);
+
+ await tx.query(
+ `DELETE FROM fields WHERE signer_id = ANY($1::text[])`,
+ [signerIds],
+ );
+ await tx.query(`DELETE FROM signers WHERE id = ANY($1::text[])`, [
+ signerIds,
+ ]);
+
+ return drafts.filter((row) => draftIds.has(row.envelopeId));
+ }, database);
+ const raced = drafts.filter((row) => !removedFromDrafts.includes(row));
const deletedEnvelopes = await deleteEnvelopesAndFiles(
[...new Set(finished.map((row) => row.envelopeId))],
@@ -192,8 +217,8 @@ export async function eraseSignerData(
return {
deletedEnvelopes,
- removedFromDrafts: drafts.length,
- skippedInProgress: inProgress.map((row) => ({
+ removedFromDrafts: removedFromDrafts.length,
+ skippedInProgress: [...inProgress, ...raced].map((row) => ({
id: row.envelopeId,
title: row.envelopeTitle,
})),
diff --git a/src/lib/signing.ts b/src/lib/signing.ts
index 29f49b2..9b3db7f 100644
--- a/src/lib/signing.ts
+++ b/src/lib/signing.ts
@@ -1133,13 +1133,32 @@ export async function sendSignerEmailCode(
`<p>It works for ${String(minutes)} minutes. If you did not just open a signing link, ignore this email.</p>`,
].join("");
const body = withUserEmailLegalFooter({ htmlBody, textBody }, branding);
- const delivery = await emailService.send({
- htmlBody: body.htmlBody,
- subject: `Your code for "${context.envelope.title}"`,
- template: "signing_code",
- textBody: body.textBody,
- to: context.signer.email,
- });
+ let delivery: Awaited<ReturnType<EmailService["send"]>>;
+
+ try {
+ delivery = await emailService.send({
+ htmlBody: body.htmlBody,
+ subject: `Your code for "${context.envelope.title}"`,
+ template: "signing_code",
+ textBody: body.textBody,
+ to: context.signer.email,
+ });
+ } catch (error) {
+ // Not sent, so the signer may ask again at once.
+ await database.query(
+ `
+ UPDATE signers
+ SET
+ email_code_hash = NULL,
+ email_code_expires_at = NULL,
+ email_code_sent_at = NULL,
+ email_code_attempts = 0
+ WHERE id = $1 AND email_code_hash = $2
+ `,
+ [context.signer.id, issued.hash],
+ );
+ throw error;
+ }
await recordEmailSent(
{
@@ -1184,27 +1203,54 @@ export async function verifySignerCheck(
if (parsed.method === "access_code") {
passed = checkAccessCode(parsed.code, state.accessCodeHash!);
} else {
- if (
- !state.emailCodeHash ||
- state.emailCodeExpiresAt === null ||
- state.emailCodeExpiresAt < now
- ) {
+ // Count the attempt and read the code in one statement, so parallel
+ // guesses cannot share an attempt.
+ const attempt = await database.query<{
+ attempts: number;
+ hash: string;
+ }>(
+ `
+ UPDATE signers
+ SET email_code_attempts = email_code_attempts + 1
+ WHERE id = $1
+ AND email_code_hash IS NOT NULL
+ AND email_code_expires_at >= $2
+ AND email_code_attempts < $3
+ RETURNING email_code_hash AS hash, email_code_attempts AS attempts
+ `,
+ [context.signer.id, now, EMAIL_CODE_MAX_ATTEMPTS],
+ );
+ const current = attempt.rows[0];
+
+ if (!current) {
throw new SigningMutationError(
"That code has expired. Send a new one.",
410,
);
}
- passed = checkEmailCode(parsed.code, state.emailCodeHash);
-
- const attempts = state.emailCodeAttempts + 1;
+ if (checkEmailCode(parsed.code, current.hash)) {
+ // Used once: only the request that clears it passes.
+ const consumed = await database.query(
+ `
+ UPDATE signers
+ SET email_code_hash = NULL, email_code_expires_at = NULL
+ WHERE id = $1 AND email_code_hash = $2
+ `,
+ [context.signer.id, current.hash],
+ );
- await database.query(
- passed || attempts >= EMAIL_CODE_MAX_ATTEMPTS
- ? `UPDATE signers SET email_code_hash = NULL, email_code_expires_at = NULL, email_code_attempts = $1 WHERE id = $2`
- : `UPDATE signers SET email_code_attempts = $1 WHERE id = $2`,
- [attempts, context.signer.id],
- );
+ passed = consumed.rowCount === 1;
+ } else if (current.attempts >= EMAIL_CODE_MAX_ATTEMPTS) {
+ await database.query(
+ `
+ UPDATE signers
+ SET email_code_hash = NULL, email_code_expires_at = NULL
+ WHERE id = $1 AND email_code_hash = $2
+ `,
+ [context.signer.id, current.hash],
+ );
+ }
}
await recordAuditEvent(
diff --git a/src/lib/utils/canonical-json.ts b/src/lib/utils/canonical-json.ts
new file mode 100644
index 0000000..a442c1f
--- /dev/null
+++ b/src/lib/utils/canonical-json.ts
@@ -0,0 +1,22 @@
+/**
+ * JSON with object keys in sorted order and undefined members left out, so
+ * a value hashes the same before it is stored and after Postgres hands it
+ * back from a jsonb column (which keeps neither key order nor undefined).
+ */
+export function canonicalJson(value: unknown): string {
+ if (Array.isArray(value)) {
+ return `[${value.map(canonicalJson).join(",")}]`;
+ }
+
+ if (value && typeof value === "object") {
+ const record = value as Record<string, unknown>;
+
+ return `{${Object.keys(record)
+ .filter((key) => record[key] !== undefined)
+ .sort()
+ .map((key) => `${JSON.stringify(key)}:${canonicalJson(record[key])}`)
+ .join(",")}}`;
+ }
+
+ return JSON.stringify(value ?? null);
+}