Open-source document signature platform. Not affiliated with DocuSign.
TypeScript
Fix the review findings on embedded signing
Claude5571a1d99d00
diff --git a/docs/api.md b/docs/api.mdindex f5c1cda..bc01105 100644--- a/docs/api.md+++ b/docs/api.md@@ -461,6 +461,11 @@ Put `url` in a frame on the page at `origin`:hours, or until the envelope's deadline if that is sooner. Ask for a newlink each time you show the page; a new link replaces the signer's lastone.+- Changing the envelope's deadline never makes a link last longer, though+ an earlier deadline still cuts it short.+- Removing a site from the list stops every link made for it at once,+ even one that is open. Ask for a new link for a site that is still+ allowed.- A signer who is not yet at their turn gets 409. With several signers, thenext one's turn starts when the one before signs: watch for the`signer.signed` webhook, whose `data.envelope` shows who is `notified`diff --git a/docs/self-hosting.md b/docs/self-hosting.mdindex d3d6cc5..a18b974 100644--- a/docs/self-hosting.md+++ b/docs/self-hosting.md@@ -186,7 +186,7 @@ An administrator can add webhook endpoints under Settings, Organization, Webhook### Embedded signing-An app can show the signing page inside its own site, for envelopes it sends through the API with embedded delivery: no invitations are emailed, and the app says who the signer is. An administrator lists the sites allowed to do this under Settings, Organization, Embedded signing; with none listed it is off, and no page can be framed. See [Embedded signing](api.md#embedded-signing).+An app can show the signing page inside its own site, for envelopes it sends through the API with embedded delivery: no invitations are emailed, and the app says who the signer is. An administrator lists the sites allowed to do this under Settings, Organization, Embedded signing; with none listed it is off, and no page can be framed. Removing a site stops the links already made for it. See [Embedded signing](api.md#embedded-signing).### Send the audit trail to your SIEMdiff --git a/src/lib/embedding.dbtest.ts b/src/lib/embedding.dbtest.tsindex 9c5174a..c18fa87 100644--- a/src/lib/embedding.dbtest.ts+++ b/src/lib/embedding.dbtest.ts@@ -24,12 +24,17 @@ import {removeEmbedOrigin,} from "./embedding.ts";import {+ changeEnvelopeDeadline,correctSentEnvelopeSigner,EnvelopeMutationError,} from "./envelopes.ts";import { ReminderMutationError, sendManualEnvelopeNudge } from "./reminders.ts";import { hashOpaqueToken } from "./services/opaque-tokens.ts";-import { getSigningPayloadForToken, SigningAccessError } from "./signing.ts";+import {+ declineSigningForToken,+ getSigningPayloadForToken,+ SigningAccessError,+} from "./signing.ts";import { setWebhookDrainScheduler } from "./webhooks/outbox.ts";// Embedded signing against a real Postgres and real files. Run with@@ -445,3 +450,156 @@ test("an emailed envelope gets no embed links, and an embedded one no reminderserror instanceof EnvelopeMutationError && error.statusCode === 409,);});++async function linkFor(admin: ApiActor, envelopeId: string, signerId: string) {+ const link = await issueEmbedLink(+ { envelopeId, origin: ORIGIN, signerId, userId: admin.userId },+ { database },+ );++ return tokenOf(link.url);+}++async function signerLink(signerId: string) {+ const row = await database.query<{+ expiresAt: number;+ openedAt: number | null;+ }>(+ `+ select signing_token_expires_at as "expiresAt",+ embed_link_opened_at as "openedAt"+ from signers where id = $1+ `,+ [signerId],+ );++ return row.rows[0]!;+}++test("removing a site stops the links made for it, opened or not", async () => {+ const admin = await createAdmin();++ await addEmbedOrigin(admin, ORIGIN, { database });++ const envelope = await create(admin);+ const token = await linkFor(admin, envelope.id, envelope.signers[0]!.id);++ assert.deepEqual(await openEmbedLink(token, ORIGIN, database), { ok: true });+ await removeEmbedOrigin(admin, ORIGIN, database);++ assert.deepEqual(await openEmbedLink(token, ORIGIN, database), {+ ok: false,+ reason: "wrong_origin",+ });+ await assert.rejects(+ getSigningPayloadForToken(token, { database }),+ (error: unknown) =>+ error instanceof SigningAccessError && error.state === "expired",+ );++ // Adding the site back does not revive the old link; a new one works.+ await addEmbedOrigin(admin, ORIGIN, { database });+ await assert.rejects(+ getSigningPayloadForToken(token, { database }),+ (error: unknown) =>+ error instanceof SigningAccessError && error.state === "expired",+ );++ const fresh = await linkFor(admin, envelope.id, envelope.signers[0]!.id);++ assert.ok(await getSigningPayloadForToken(fresh, { database }));+});++test("a new deadline does not bring back or stretch an embedded link", async () => {+ const admin = await createAdmin();++ await addEmbedOrigin(admin, ORIGIN, { database });++ const envelope = await create(admin);+ const signerId = envelope.signers[0]!.id;+ const token = await linkFor(admin, envelope.id, signerId);+ const before = await signerLink(signerId);++ await changeEnvelopeDeadline(+ admin.userId,+ envelope.id,+ { expiresInDays: 30, senderEmail: admin.email },+ { database },+ );+ assert.equal((await signerLink(signerId)).expiresAt, before.expiresAt);++ // An expired link stays expired.+ await database.query(+ `update signers set signing_token_expires_at = $2 where id = $1`,+ [signerId, Math.floor(Date.now() / 1000) - 1],+ );+ await changeEnvelopeDeadline(+ admin.userId,+ envelope.id,+ { expiresInDays: 30, senderEmail: admin.email },+ { database },+ );+ await assert.rejects(+ getSigningPayloadForToken(token, { database }),+ (error: unknown) =>+ error instanceof SigningAccessError && error.state === "expired",+ );+});++test("an old link opened while it is being replaced does not open the new one", async () => {+ const admin = await createAdmin();++ await addEmbedOrigin(admin, ORIGIN, { database });++ const envelope = await create(admin);+ const signerId = envelope.signers[0]!.id;+ const oldToken = await linkFor(admin, envelope.id, signerId);+ let replaced = false;+ // Replaces the link between openEmbedLink's read and its update.+ const racing = {+ query: async (text: string, values?: unknown[]) => {+ const result = await database.query(text, values);++ if (!replaced) {+ replaced = true;+ await linkFor(admin, envelope.id, signerId);+ }++ return result;+ },+ } as unknown as pg.Pool;++ await openEmbedLink(oldToken, ORIGIN, racing);+ assert.ok(replaced);++ const after = await signerLink(signerId);++ assert.equal(after.openedAt, null);+ assert.ok(after.expiresAt - Date.now() / 1000 <= 15 * 60 + 1);+});++test("a signer who declines in the app is recorded as declining there", async () => {+ const admin = await createAdmin();++ await addEmbedOrigin(admin, ORIGIN, { database });++ const envelope = await create(admin);+ const signerId = envelope.signers[0]!.id;+ const token = await linkFor(admin, envelope.id, signerId);++ await openEmbedLink(token, ORIGIN, database);+ await declineSigningForToken(token, { reason: "Wrong terms" }, { database });++ const declined = await database.query<{ metadata: Record<string, unknown> }>(+ `+ select metadata from audit_events+ where envelope_id = $1 and event = 'declined'+ `,+ [envelope.id],+ );++ assert.deepEqual(declined.rows[0]?.metadata.embedded, {+ apiKeyName: "Portal",+ origin: ORIGIN,+ });+});diff --git a/src/lib/embedding.ts b/src/lib/embedding.tsindex 8ecf681..7c14091 100644--- a/src/lib/embedding.ts+++ b/src/lib/embedding.ts@@ -181,6 +181,23 @@ export async function removeEmbedOrigin(throw new EmbeddingError("That site is not on the list.", 404);}+ // Links already made for the site stop working at once, opened or+ // not. The signer's row is kept: the app can ask for a link for a+ // site that is still allowed.+ const now = nowInSeconds();++ await tx.query(+ `+ UPDATE signers+ SET signing_token_expires_at = LEAST(signing_token_expires_at, $2 - 1),+ updated_at = $2+ WHERE embed_origin = $1+ AND status = 'notified'+ AND signing_token_hash IS NOT NULL+ `,+ [origin, now],+ );+await recordSystemAuditEvent({actorEmail: actor.email,@@ -343,13 +360,17 @@ export async function openEmbedLink(envelopeExpiresAt: number | null;expiresAt: number | null;id: string;+ originAllowed: boolean;}>(database,`SELECT s.id, s.embed_origin AS "embedOrigin",s.embed_link_opened_at AS "embedLinkOpenedAt",s.signing_token_expires_at AS "expiresAt",- e.delivery, e.expires_at AS "envelopeExpiresAt"+ e.delivery, e.expires_at AS "envelopeExpiresAt",+ EXISTS (+ SELECT 1 FROM embed_allowed_origins a WHERE a.origin = s.embed_origin+ ) AS "originAllowed"FROM signers sJOIN envelopes e ON e.id = s.envelope_idWHERE s.signing_token_hash = $1@@ -365,7 +386,8 @@ export async function openEmbedLink(return { ok: false, reason: "not_embedded" };}- if (!origin || row.embedOrigin !== origin) {+ // The site must still be on the list: removing it stops its links.+ if (!origin || row.embedOrigin !== origin || !row.originAllowed) {return { ok: false, reason: "wrong_origin" };}@@ -379,14 +401,17 @@ export async function openEmbedLink(row.envelopeExpiresAt ?? now + EMBED_SESSION_SECONDS,);+ // Matched on the token too: a link replaced since the read above must+ // not be marked opened, or given a session, by the old one.await database.query(`UPDATE signersSET embed_link_opened_at = $2,signing_token_expires_at = GREATEST(signing_token_expires_at, $3)WHERE id = $1 AND embed_link_opened_at IS NULL+ AND signing_token_hash = $4 AND signing_token_expires_at >= $2`,- [row.id, now, sessionEnd],+ [row.id, now, sessionEnd, hashOpaqueToken(token)],);}diff --git a/src/lib/envelopes.ts b/src/lib/envelopes.tsindex 14a68fb..8add4c9 100644--- a/src/lib/envelopes.ts+++ b/src/lib/envelopes.ts@@ -2885,7 +2885,14 @@ export async function changeEnvelopeDeadline(await tx.query(`UPDATE signers- SET signing_token_expires_at = $1, updated_at = $2+ -- A link made for an app keeps its own short life: a later+ -- deadline must not bring it back or stretch it, though an+ -- earlier one still cuts it short.+ SET signing_token_expires_at = CASE+ WHEN embed_origin IS NULL THEN $1+ ELSE LEAST(signing_token_expires_at, $1)+ END,+ updated_at = $2WHERE envelope_id = $3AND status = 'notified'AND signing_token_hash IS NOT NULL@@ -2917,6 +2924,9 @@ export async function changeEnvelopeDeadline(const SENT_ENVELOPE_SIGNER_CORRECTION_MESSAGE ="Only an envelope that is out for signature can have a signer corrected.";+const EMBEDDED_SIGNER_CORRECTION_MESSAGE =+ "This envelope is signed in another app, which says who signs. Void it and send a new one to change a signer.";+/*** Fixes the name and/or email of a signer who has not signed or declined on* an envelope that is out for signature. The signing link they already have@@ -2946,10 +2956,7 @@ export async function correctSentEnvelopeSigner(const parsedInput = correctSentSignerSchema.parse(input);if (await isEmbeddedEnvelope(envelopeId, database, userId)) {- throw new EnvelopeMutationError(- "This envelope is signed in another app, which says who signs. Void it and send a new one to change a signer.",- 409,- );+ throw new EnvelopeMutationError(EMBEDDED_SIGNER_CORRECTION_MESSAGE, 409);}// Read settings before taking the envelope lock: an uncached read inside the@@ -2960,6 +2967,7 @@ export async function correctSentEnvelopeSigner(return withTransaction(async (tx) => {const envelope = await queryOne<{+ delivery: string;expiresAt: number | null;part11: boolean;status: EnvelopeRecord["status"];@@ -2970,6 +2978,7 @@ export async function correctSentEnvelopeSigner(tx,`SELECT+ delivery,expires_at AS "expiresAt",part11,status,@@ -2994,6 +3003,12 @@ export async function correctSentEnvelopeSigner();}+ // Checked again on the locked row: an embedded send may have landed+ // since the check above.+ if (envelope.delivery === "embedded") {+ throw new EnvelopeMutationError(EMBEDDED_SIGNER_CORRECTION_MESSAGE, 409);+ }+if (envelope.part11) {throw new EnvelopeMutationError("This envelope was sent in Part 11 mode. The signer's identity is bound to their account and cannot be corrected.",diff --git a/src/lib/services/pdf-finalize.ts b/src/lib/services/pdf-finalize.tsindex c29a3c4..87fb3ea 100644--- a/src/lib/services/pdf-finalize.ts+++ b/src/lib/services/pdf-finalize.ts@@ -959,9 +959,17 @@ function describeSignerEvidence(}}+ // A signer who declined in another app has no signed event; the+ // declined event carries the same record of where it happened.+ const declined =+ signed === undefined && signer.status === "declined"+ ? forSigner.findLast((event) => event.event === "declined")+ : undefined;+ const embeddedSource = signed ?? declined;const embedded =- signed?.metadata?.embedded && typeof signed.metadata.embedded === "object"- ? (signed.metadata.embedded as Record<string, unknown>)+ embeddedSource?.metadata?.embedded &&+ typeof embeddedSource.metadata.embedded === "object"+ ? (embeddedSource.metadata.embedded as Record<string, unknown>): null;const checks = [embeddeddiff --git a/src/lib/signing.ts b/src/lib/signing.tsindex 12f9356..b17f416 100644--- a/src/lib/signing.ts+++ b/src/lib/signing.ts@@ -1029,6 +1029,7 @@ function buildSignedAuditEvent(input: {function buildDeclinedAuditEvent(input: {declinedAt: number;+ embedded?: { apiKeyName: string | null; origin: string | null } | null;envelopeId: string;reason?: string;requestMeta: SigningRequestMeta;@@ -1048,6 +1049,7 @@ function buildDeclinedAuditEvent(input: {signerId: input.signer.id,signerName: input.signer.name,signerOrder: input.signer.signOrder,+ ...(input.embedded ? { embedded: input.embedded } : {}),},userAgent: input.requestMeta.userAgent ?? null,};@@ -3065,8 +3067,16 @@ export async function declineSigningForToken();}+ // Declined inside another app: the certificate says where, not that an+ // emailed link was used.+ const embedded = await readEmbedEvidence(+ context.envelope.id,+ currentSignerId,+ database,+ );const declinedAuditEvent = buildDeclinedAuditEvent({declinedAt,+ embedded,envelopeId: context.envelope.id,reason: declineReason,requestMeta,