Skip to content

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

TypeScript

Fix the review notes on embedded signing

Claudea1cdbeb30a9d
diff --git a/docs/api.md b/docs/api.md
index f47dcac..eb8f96a 100644
--- a/docs/api.md
+++ b/docs/api.md
@@ -451,11 +451,12 @@ curl https://sign.example.com/api/v1/envelopes/8c1d…/signers/51ab…/embed-lin
}
```
-Put `url` in a frame on the page at `origin`:
+Put `url` in a frame on the page at `origin`, exactly as it came, with its
+`origin` parameter:
```html
<iframe
- src="https://sign.example.com/embed/sign/…"
+ src="https://sign.example.com/embed/sign/…?origin=https%3A%2F%2Fapp.example.com"
title="Sign your agreement"
style="width: 100%; height: 800px; border: 0"
></iframe>
diff --git a/src/app/api/admin/embed-origins/route.ts b/src/app/api/admin/embed-origins/route.ts
index faac566..ceb2e95 100644
--- a/src/app/api/admin/embed-origins/route.ts
+++ b/src/app/api/admin/embed-origins/route.ts
@@ -10,11 +10,17 @@ import {
handleWebhookAdmin,
noStore,
readJsonObject,
+ type AdminRouteWords,
} from "@/lib/webhooks/admin-route";
// The sites allowed to show signing pages in a frame (embedded signing).
// Administrators only, not on hosted installs.
+const EMBEDDING_WORDS: AdminRouteWords = {
+ failure: "Unexpected failure in an embedded signing settings request.",
+ hosted: "Embedded signing is for self-hosted installs.",
+};
+
function embeddingErrorResponse(error: unknown): Response {
if (error instanceof EmbeddingError) {
return NextResponse.json(
@@ -27,11 +33,15 @@ function embeddingErrorResponse(error: unknown): Response {
}
export function GET(request: Request) {
- return handleWebhookAdmin(request, "embed_origin_list_failure", async () =>
- NextResponse.json(
- { origins: await listEmbedOrigins() },
- { headers: noStore },
- ),
+ return handleWebhookAdmin(
+ request,
+ "embed_origin_list_failure",
+ async () =>
+ NextResponse.json(
+ { origins: await listEmbedOrigins() },
+ { headers: noStore },
+ ),
+ EMBEDDING_WORDS,
);
}
@@ -50,6 +60,7 @@ export function POST(request: Request) {
return embeddingErrorResponse(error);
}
},
+ EMBEDDING_WORDS,
);
}
@@ -68,5 +79,6 @@ export function DELETE(request: Request) {
return embeddingErrorResponse(error);
}
},
+ EMBEDDING_WORDS,
);
}
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 d23691d..5de67b8 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,4 +1,5 @@
-import { apiJson } from "@/lib/api/http";
+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 { issueEmbedLink } from "@/lib/embedding";
@@ -21,9 +22,24 @@ export async function POST(request: Request, context: RouteContext) {
}
const { id, signerId } = await context.params;
- const body = (await request.json().catch(() => null)) as {
- origin?: unknown;
- } | null;
+ const raw = await readBodyWithin(request, MAX_JSON_BODY_BYTES);
+
+ if (!raw) {
+ return bodyTooLarge();
+ }
+
+ // No body gets the same answer as a body without an origin, which
+ // says what to send.
+ const text = new TextDecoder().decode(raw);
+ let body: { origin?: unknown } | null = null;
+
+ if (text.trim()) {
+ try {
+ body = JSON.parse(text) as { origin?: unknown } | null;
+ } catch {
+ return apiError(400, "invalid_request", "The body is not valid JSON.");
+ }
+ }
const link = await issueEmbedLink({
apiKeyId: api.actor.apiKeyId,
diff --git a/src/components/settings/embedding-panel.tsx b/src/components/settings/embedding-panel.tsx
index 1154889..2c38f67 100644
--- a/src/components/settings/embedding-panel.tsx
+++ b/src/components/settings/embedding-panel.tsx
@@ -15,11 +15,14 @@ type Payload = {
origins?: Array<{ createdAt: number; origin: string }>;
} | null;
+type Change = { method: "DELETE" | "POST"; origin: string };
+
export function EmbeddingPanel() {
const [origins, setOrigins] = useState<string[] | null>(null);
const [value, setValue] = useState("");
const [error, setError] = useState<string | null>(null);
- const [pending, setPending] = useState<string | null>(null);
+ // What is being changed, so each button names only its own change.
+ const [pending, setPending] = useState<Change | null>(null);
const [revision, setRevision] = useState(0);
useEffect(() => {
@@ -51,8 +54,8 @@ export function EmbeddingPanel() {
};
}, [revision]);
- async function change(method: "DELETE" | "POST", origin: string) {
- setPending(origin);
+ async function change(method: Change["method"], origin: string) {
+ setPending({ method, origin });
setError(null);
try {
@@ -75,8 +78,18 @@ export function EmbeddingPanel() {
return;
}
+ // The list changes at once, in case reading it again fails.
if (method === "POST") {
+ const added = payload?.origin ?? origin;
+
setValue("");
+ setOrigins((current) =>
+ current && !current.includes(added) ? [...current, added] : current,
+ );
+ } else {
+ setOrigins((current) =>
+ current ? current.filter((listed) => listed !== origin) : current,
+ );
}
setRevision((current) => current + 1);
@@ -133,7 +146,7 @@ export function EmbeddingPanel() {
onClick={() => void change("POST", value)}
type="button"
>
- {pending === value && value ? "Adding..." : "Allow site"}
+ {pending?.method === "POST" ? "Adding..." : "Allow site"}
</button>
</div>
@@ -167,7 +180,9 @@ export function EmbeddingPanel() {
onClick={() => void change("DELETE", origin)}
type="button"
>
- {pending === origin ? "Removing..." : "Remove"}
+ {pending?.method === "DELETE" && pending.origin === origin
+ ? "Removing..."
+ : "Remove"}
</button>
</li>
))}
diff --git a/src/lib/api/openapi.ts b/src/lib/api/openapi.ts
index 52138a8..978ea8c 100644
--- a/src/lib/api/openapi.ts
+++ b/src/lib/api/openapi.ts
@@ -553,9 +553,33 @@ export function buildOpenApiDocument(serverUrl: string) {
},
responses: {
"201": {
+ content: {
+ "application/json": {
+ schema: {
+ properties: {
+ expiresAt: {
+ description:
+ "When the link stops working if it is not opened.",
+ format: "date-time",
+ type: "string",
+ },
+ object: { const: "embed_link", type: "string" },
+ url: {
+ description:
+ "The page to show in the frame, with its origin parameter. Use it as it is.",
+ format: "uri",
+ type: "string",
+ },
+ },
+ required: ["object", "url", "expiresAt"],
+ type: "object",
+ },
+ },
+ },
description:
"The link to frame (url) and when it stops working if not opened (expiresAt). Each call replaces the signer's last link.",
},
+ "413": errorResponse,
...errors,
},
summary:
diff --git a/src/lib/embedding.dbtest.ts b/src/lib/embedding.dbtest.ts
index fa28f14..3689528 100644
--- a/src/lib/embedding.dbtest.ts
+++ b/src/lib/embedding.dbtest.ts
@@ -491,26 +491,38 @@ test("removing a site stops the links made for it, opened or not", async () => {
const envelope = await create(admin);
const token = await linkFor(admin, envelope.id, envelope.signers[0]!.id);
+ // A second link that is never opened.
+ const waiting = await create(admin);
+ const unopened = await linkFor(admin, waiting.id, waiting.signers[0]!.id);
assert.deepEqual(await openEmbedLink(token, ORIGIN, database), { ok: true });
await removeEmbedOrigin(admin, ORIGIN, database);
+ const isExpired = (error: unknown) =>
+ error instanceof SigningAccessError && error.state === "expired";
+
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",
+ isExpired,
+ );
+ await assert.rejects(
+ getSigningPayloadForToken(unopened, { database }),
+ isExpired,
);
- // Adding the site back does not revive the old link; a new one works.
+ // Adding the site back revives neither 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",
+ isExpired,
+ );
+ await assert.rejects(
+ getSigningPayloadForToken(unopened, { database }),
+ isExpired,
);
const fresh = await linkFor(admin, envelope.id, envelope.signers[0]!.id);
diff --git a/src/lib/services/pdf-finalize.ts b/src/lib/services/pdf-finalize.ts
index cf38396..1984a04 100644
--- a/src/lib/services/pdf-finalize.ts
+++ b/src/lib/services/pdf-finalize.ts
@@ -1253,10 +1253,11 @@ function currentSignerIdentityStart(
return starts[starts.length - 1] ?? 0;
}
-/** What the record shows about how one signer was identified and agreed. */
/**
* For a signature made inside another app: identity then rests on that app
- * having signed the person in, and the certificate says so.
+ * having signed the person in. The record shows only where the link was
+ * given, not that the app checked who opened it, so the certificate says
+ * the check was left to the app rather than that it happened.
*/
function describeEmbeddedDelivery(embedded: Record<string, unknown>): string {
const origin =
@@ -1266,9 +1267,10 @@ function describeEmbeddedDelivery(embedded: Record<string, unknown>): string {
? ` through the API key "${embedded.apiKeyName}"`
: "";
- return `a signing link given to the app at ${origin}${key} (embedded signing; that app identified the signer)`;
+ return `a signing link given to the app at ${origin}${key} (embedded signing; identifying the signer was left to that app)`;
}
+/** What the record shows about how one signer was identified and agreed. */
function describeSignerEvidence(
signer: SignerRecord,
auditEvents: readonly AuditEventRecord[],
diff --git a/src/lib/webhooks/admin-route.ts b/src/lib/webhooks/admin-route.ts
index cd4c8cb..b49596d 100644
--- a/src/lib/webhooks/admin-route.ts
+++ b/src/lib/webhooks/admin-route.ts
@@ -12,13 +12,28 @@ import { WebhookEndpointError, type WebhookActor } from "./endpoints.ts";
// What every /api/admin/webhooks route shares: administrators only, not on
// a hosted install, never cached, and known errors become plain messages.
+// The embedded signing settings use it too, with their own words.
export const noStore = { "cache-control": "private, no-store" };
+/** What a feature's settings routes say when they cannot run. */
+export type AdminRouteWords = {
+ /** Logged with an unexpected failure. */
+ failure: string;
+ /** The answer on a hosted install. */
+ hosted: string;
+};
+
+const WEBHOOK_WORDS: AdminRouteWords = {
+ failure: "Unexpected failure in a webhook settings request.",
+ hosted: "Webhooks are for self-hosted installs.",
+};
+
export async function handleWebhookAdmin(
request: Request,
category: string,
run: (actor: WebhookActor) => Promise<Response>,
+ words: AdminRouteWords = WEBHOOK_WORDS,
): Promise<Response> {
const sessionResult = await requireAdminSession(request);
@@ -28,7 +43,7 @@ export async function handleWebhookAdmin(
if ((await getSettings()).hosted) {
return NextResponse.json(
- { error: "Webhooks are for self-hosted installs." },
+ { error: words.hosted },
{ headers: noStore, status: 400 },
);
}
@@ -53,7 +68,7 @@ export async function handleWebhookAdmin(
logRouteError(error, {
category,
ipAddress: actor.ipAddress ?? null,
- message: "Unexpected failure in a webhook settings request.",
+ message: words.failure,
path: getRequestPathname(request),
userId: actor.userId,
});