Skip to content

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

TypeScript

Stop a signing whose link expired mid-submission, and fix five embedding details

Claudeb193541fd791
diff --git a/docs/api.md b/docs/api.md
index cd00305..3516435 100644
--- a/docs/api.md
+++ b/docs/api.md
@@ -503,7 +503,8 @@ Put `url` in a frame on the page at `origin`, exactly as it came, with its
signers who share a step are all `notified` at once: watch for the
`signer.signed` webhook, whose `data.envelope` shows who is `notified`
now.
-- Asking for links is limited to 300 per 10 minutes per account.
+- Asking for links is limited to 300 per 10 minutes per key. Past that the
+ answer is 429 with `Retry-After`.
### Hear what happened
diff --git a/src/app/api/v1/envelopes/[id]/signers/[signerId]/embed-link/route.ts b/src/app/api/v1/envelopes/[id]/signers/[signerId]/embed-link/route.ts
index 56850bf..872de42 100644
--- a/src/app/api/v1/envelopes/[id]/signers/[signerId]/embed-link/route.ts
+++ b/src/app/api/v1/envelopes/[id]/signers/[signerId]/embed-link/route.ts
@@ -1,6 +1,10 @@
import { MAX_JSON_BODY_BYTES, readBodyWithin } from "@/lib/api/body";
import { apiError, apiJson, bodyTooLarge } from "@/lib/api/http";
-import { applyAccountLimit, handleApi } from "@/lib/api/route";
+import {
+ API_EMBED_LINK_LIMIT,
+ applyAccountLimit,
+ handleApi,
+} from "@/lib/api/route";
import { issueEmbedLink } from "@/lib/embedding";
type RouteContext = { params: Promise<{ id: string; signerId: string }> };
@@ -11,11 +15,7 @@ type RouteContext = { params: Promise<{ id: string; signerId: string }> };
export async function POST(request: Request, context: RouteContext) {
return handleApi(request, "write", "api_embed_link_failure", async (api) => {
- const limited = await applyAccountLimit(api, {
- key: "api-embed-link",
- limit: 300,
- windowMs: 10 * 60 * 1000,
- });
+ const limited = await applyAccountLimit(api, API_EMBED_LINK_LIMIT);
if (limited) {
return limited;
diff --git a/src/components/settings/embedding-panel.tsx b/src/components/settings/embedding-panel.tsx
index 9a0b264..3f2a677 100644
--- a/src/components/settings/embedding-panel.tsx
+++ b/src/components/settings/embedding-panel.tsx
@@ -137,7 +137,6 @@ export function EmbeddingPanel() {
className="field-input"
disabled={pending !== null}
inputMode="url"
- maxLength={255}
name="embed-origin"
onChange={(event) => setValue(event.target.value)}
placeholder="https://app.example.com"
diff --git a/src/lib/api/openapi.ts b/src/lib/api/openapi.ts
index 43e4d8a..3e93b5e 100644
--- a/src/lib/api/openapi.ts
+++ b/src/lib/api/openapi.ts
@@ -268,7 +268,7 @@ export function buildOpenApiDocument(
delivery: {
default: "email",
description:
- "embedded: signers sign inside your app (see POST /envelopes/{id}/signers/{signerId}/embed-link), and no invitations or reminders are emailed.",
+ "embedded: signers sign inside your app (see POST /envelopes/{id}/signers/{signerId}/embed-link), and no invitations or reminders are emailed. It needs a site on the install's list of allowed sites, simple signatures (signatureLevel simple), no signer accessCode or requireEmailCode, and an install that is not in Part 11 mode; otherwise the send is refused with 400.",
enum: ["email", "embedded"],
type: "string",
},
@@ -285,6 +285,8 @@ export function buildOpenApiDocument(
type: ["integer", "null"],
},
signatureLevel: {
+ description:
+ "advanced and qualified are sent by email only, not with delivery embedded.",
enum: ["simple", "advanced", "qualified"],
type: "string",
},
diff --git a/src/lib/api/route.dbtest.ts b/src/lib/api/route.dbtest.ts
index 9340c60..95533f4 100644
--- a/src/lib/api/route.dbtest.ts
+++ b/src/lib/api/route.dbtest.ts
@@ -174,3 +174,26 @@ test("only refusals a retry would get again are kept for the key", () => {
assert.equal(route.isKept(429), false);
assert.equal(route.isKept(503), false);
});
+
+test("the embed-link limit refuses in its own words, with Retry-After", async () => {
+ const context = await createContext(`unused-${randomUUID()}`);
+ const limit = {
+ ...route.API_EMBED_LINK_LIMIT,
+ key: `test-embed-link-${randomUUID()}`,
+ limit: 1,
+ };
+
+ assert.equal(await route.applyAccountLimit(context, limit), null);
+
+ const refused = await route.applyAccountLimit(context, limit);
+
+ assert.equal(refused?.status, 429);
+ assert.ok(Number(refused?.headers.get("retry-after")) > 0);
+ assert.deepEqual(await refused?.json(), {
+ error: {
+ code: "rate_limited",
+ message:
+ "This key has asked for too many signing links for now. Wait and try again.",
+ },
+ });
+});
diff --git a/src/lib/api/route.ts b/src/lib/api/route.ts
index b2c88bd..0054b06 100644
--- a/src/lib/api/route.ts
+++ b/src/lib/api/route.ts
@@ -179,7 +179,13 @@ export async function handleApi(
type ApiResult = { body: unknown; status: number };
-type AccountLimit = { key: string; limit: number; windowMs: number };
+type AccountLimit = {
+ key: string;
+ limit: number;
+ /** What the 429 says. Left out, it speaks of envelopes made or sent. */
+ refusal?: string;
+ windowMs: number;
+};
/**
* Whether a response is kept for retries: not a 5xx, and not a 429. A
@@ -359,7 +365,7 @@ async function applyAccountLimits(
});
if (!state.allowed) {
- return accountLimitRefusal(state.retryAfterSeconds);
+ return accountLimitRefusal(state.retryAfterSeconds, limit.refusal);
}
}
}
@@ -407,6 +413,15 @@ export const API_SEND_LIMIT = {
windowMs: 60 * 60 * 1000,
};
+/** Signing links for embedded envelopes: per key, every 10 minutes. */
+export const API_EMBED_LINK_LIMIT = {
+ key: "api-embed-link",
+ limit: 300,
+ refusal:
+ "This key has asked for too many signing links for now. Wait and try again.",
+ windowMs: 10 * 60 * 1000,
+};
+
/**
* Counts this request against a per-key limit on creating or sending. These
* are looser than the web app's per-person limits, since an app sends in
@@ -424,18 +439,18 @@ export async function applyAccountLimit(
return decision.allowed
? null
- : accountLimitRefusal(decision.retryAfterSeconds);
+ : accountLimitRefusal(decision.retryAfterSeconds, input.refusal);
}
function accountLimitKey(context: ApiContext, input: AccountLimit) {
return `${input.key}:${context.actor.apiKeyId}`;
}
-function accountLimitRefusal(retryAfterSeconds: number): Response {
- return apiError(
- 429,
- "rate_limited",
- "This key has created or sent too many envelopes for now. Wait and try again.",
- { "retry-after": String(retryAfterSeconds) },
- );
+function accountLimitRefusal(
+ retryAfterSeconds: number,
+ message = "This key has created or sent too many envelopes for now. Wait and try again.",
+): Response {
+ return apiError(429, "rate_limited", message, {
+ "retry-after": String(retryAfterSeconds),
+ });
}
diff --git a/src/lib/embedding.dbtest.ts b/src/lib/embedding.dbtest.ts
index 59132a6..c7f6032 100644
--- a/src/lib/embedding.dbtest.ts
+++ b/src/lib/embedding.dbtest.ts
@@ -14,7 +14,7 @@ import {
createEnvelopeForApi,
type ApiActor,
} from "./api/envelopes.ts";
-import { openTestDatabase } from "./db/test-database.ts";
+import { openTestDatabase, waitUntilBlockedBy } from "./db/test-database.ts";
import { ELECTRONIC_RECORDS_DISCLOSURE_VERSION } from "./electronic-records-disclosure.ts";
import {
addEmbedOrigin,
@@ -37,6 +37,7 @@ import {
getSigningPayloadForToken,
recordSignerConsent,
SigningAccessError,
+ SigningMutationError,
submitSigningForToken,
} from "./signing.ts";
import { setWebhookDrainScheduler } from "./webhooks/outbox.ts";
@@ -195,7 +196,15 @@ async function create(
async function invitationsTo(email: string): Promise<number> {
const dir = process.env.EMAIL_CAPTURE_DIR!;
- const files = await readdir(dir).catch(() => [] as string[]);
+ // No outbox yet means nothing was sent; any other failure must not pass
+ // for an empty one.
+ const files = await readdir(dir).catch((error: unknown) => {
+ if ((error as { code?: string }).code === "ENOENT") {
+ return [] as string[];
+ }
+
+ throw error;
+ });
let count = 0;
for (const file of files) {
@@ -744,6 +753,136 @@ test("a signer who declines in the app is recorded as declining there", async ()
});
});
+test("a finished embedded link opened again in its site says what happened, not that it expired", 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 field = await database.query<{ id: string }>(
+ `select id from fields where envelope_id = $1 and signer_id = $2`,
+ [envelope.id, signerId],
+ );
+
+ await openEmbedLink(token, ORIGIN, database);
+ await recordSignerConsent(
+ token,
+ { disclosureVersion: ELECTRONIC_RECORDS_DISCLOSURE_VERSION },
+ { database },
+ );
+ await submitSigningForToken(
+ token,
+ {
+ clientTimezoneOffsetMinutes: 0,
+ fields: [
+ {
+ fieldId: field.rows[0]!.id,
+ imageDataUrl: DRAWN_SIGNATURE,
+ inputMethod: "drawn",
+ type: "signature",
+ },
+ ],
+ },
+ { database },
+ );
+
+ const openedAt = (await signerLink(signerId)).openedAt;
+
+ // The spent link passes the site checks, so the page goes on to say the
+ // signer already signed...
+ assert.deepEqual(await openEmbedLink(token, ORIGIN, database), {
+ ok: true,
+ });
+ await assert.rejects(
+ getSigningPayloadForToken(token, { database }),
+ (error: unknown) =>
+ error instanceof SigningAccessError && error.state === "already-signed",
+ );
+ // ...it opens nothing, and another site still learns nothing.
+ assert.equal((await signerLink(signerId)).openedAt, openedAt);
+ assert.deepEqual(
+ await openEmbedLink(token, "https://other.example.com", database),
+ { ok: false, reason: "wrong_origin" },
+ );
+});
+
+test("a signing already under way when its site is removed does not finish", 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 field = await database.query<{ id: string }>(
+ `select id from fields where envelope_id = $1 and signer_id = $2`,
+ [envelope.id, signerId],
+ );
+
+ await openEmbedLink(token, ORIGIN, database);
+ await recordSignerConsent(
+ token,
+ { disclosureVersion: ELECTRONIC_RECORDS_DISCLOSURE_VERSION },
+ { database },
+ );
+
+ // The removal holds the signer's row while the submission starts, and
+ // expires the link (as removeEmbedOrigin does) once the submission waits.
+ const remover = await database.connect();
+ let submitted: Promise<unknown> | undefined;
+
+ try {
+ await remover.query("begin");
+ await remover.query(`select id from signers where id = $1 for update`, [
+ signerId,
+ ]);
+ submitted = submitSigningForToken(
+ token,
+ {
+ clientTimezoneOffsetMinutes: 0,
+ fields: [
+ {
+ fieldId: field.rows[0]!.id,
+ imageDataUrl: DRAWN_SIGNATURE,
+ inputMethod: "drawn",
+ type: "signature",
+ },
+ ],
+ },
+ { database },
+ );
+ // Handled at once, so a failure before it waits is reported below
+ // instead of as an unhandled rejection.
+ submitted.catch(() => undefined);
+
+ await waitUntilBlockedBy(database, remover);
+ await remover.query(
+ `update signers set signing_token_expires_at = $2 where id = $1`,
+ [signerId, Math.floor(Date.now() / 1000) - 1],
+ );
+ await remover.query("commit");
+ } finally {
+ await remover.query("rollback").catch(() => undefined);
+ await submitted?.catch(() => undefined);
+ remover.release();
+ }
+
+ await assert.rejects(
+ submitted!,
+ (error: unknown) =>
+ error instanceof SigningMutationError && error.statusCode === 409,
+ );
+
+ const signer = await database.query<{ status: string }>(
+ `select status from signers where id = $1`,
+ [signerId],
+ );
+
+ assert.equal(signer.rows[0]?.status, "notified");
+});
+
test("the evidence names the key that asked for the link, not the one that made the envelope", async () => {
const admin = await createAdmin();
diff --git a/src/lib/embedding.ts b/src/lib/embedding.ts
index 75d6ec4..330e375 100644
--- a/src/lib/embedding.ts
+++ b/src/lib/embedding.ts
@@ -377,6 +377,11 @@ export type EmbedOpenResult =
* Checks that an embedded link is opened for the site it was made for,
* and on first opening gives it the rest of a signing session. Leaves
* other problems (expired, already signed) to the signing page itself.
+ *
+ * A link that signing or declining took away (spent) passes the same site
+ * checks, so its frame can show what happened (signed, completed) instead
+ * of saying the link expired. It opens nothing: the signing page only
+ * reports its state.
*/
export async function openEmbedLink(
token: string,
@@ -391,6 +396,7 @@ export async function openEmbedLink(
envelopeExpiresAt: number | null;
expiresAt: number | null;
id: string;
+ live: boolean;
originAllowed: boolean;
}>(
database,
@@ -398,13 +404,16 @@ export async function openEmbedLink(
SELECT s.id, s.embed_origin AS "embedOrigin",
s.embed_link_opened_at AS "embedLinkOpenedAt",
s.signing_token_expires_at AS "expiresAt",
+ COALESCE(s.signing_token_hash = $1, false) AS "live",
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 s
JOIN envelopes e ON e.id = s.envelope_id
- WHERE s.signing_token_hash = $1
+ WHERE s.signing_token_hash = $1 OR s.spent_signing_token_hash = $1
+ ORDER BY "live" DESC
+ LIMIT 1
`,
[hashOpaqueToken(token)],
);
@@ -422,6 +431,10 @@ export async function openEmbedLink(
return { ok: false, reason: "wrong_origin" };
}
+ if (!row.live) {
+ return { ok: true };
+ }
+
if (
row.embedLinkOpenedAt === null &&
row.expiresAt !== null &&
diff --git a/src/lib/signing.ts b/src/lib/signing.ts
index 00a0683..20f5cd2 100644
--- a/src/lib/signing.ts
+++ b/src/lib/signing.ts
@@ -789,6 +789,9 @@ async function lockSentEnvelope(
* before any of their rows are written. The token is read once when the
* page is opened; a correction can replace the hash in the meantime and
* leave status as notified, which the later UPDATE used to treat as enough.
+ * The link must also not have expired since: removing an embedding site
+ * expires its links, and a submission already under way must not finish
+ * on one.
*/
async function lockSignerForPresentedToken(
tx: DbExecutor,
@@ -811,9 +814,10 @@ async function lockSignerForPresentedToken(
AND envelope_id = $2
AND status = 'notified'
AND signing_token_hash = $3
+ AND (signing_token_expires_at IS NULL OR signing_token_expires_at >= $4)
FOR NO KEY UPDATE
`,
- [signerId, envelopeId, tokenHash],
+ [signerId, envelopeId, tokenHash, Math.floor(Date.now() / 1000)],
);
if (!locked) {