Skip to content

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

TypeScript

Warn the signer while typing when a text box is full

Claude9201d18ee0ac
diff --git a/src/app/api/signing/[token]/fit/route.ts b/src/app/api/signing/[token]/fit/route.ts
new file mode 100644
index 0000000..7ddd41d
--- /dev/null
+++ b/src/app/api/signing/[token]/fit/route.ts
@@ -0,0 +1,99 @@
+import { NextResponse } from "next/server";
+import { ZodError } from "zod";
+
+import { getDb } from "@/lib/db/connection";
+import { logRouteError } from "@/lib/security/logging";
+import {
+ applyRateLimit,
+ buildRateLimitKey,
+} from "@/lib/security/route-controls";
+import { getClientIpAddress } from "@/lib/security/request";
+import {
+ checkSigningFieldFit,
+ SigningAccessError,
+ SigningMutationError,
+ SigningVerificationRequiredError,
+} from "@/lib/signing";
+import {
+ verificationRequiredResponse,
+ verifiedMethodsForRequest,
+} from "@/lib/signing-route";
+
+type FitRouteContext = {
+ params: Promise<{
+ token: string;
+ }>;
+};
+
+const NO_STORE = { "cache-control": "private, no-store" };
+
+export async function POST(request: Request, context: FitRouteContext) {
+ const { token } = await context.params;
+ const rateLimitResponse = await applyRateLimit({
+ category: "signing_field_fit",
+ key: buildRateLimitKey([
+ "signing-field-fit",
+ token,
+ getClientIpAddress(request.headers) ?? "unknown",
+ ]),
+ // Asked as the signer types, after each pause.
+ limit: 300,
+ request,
+ windowMs: 10 * 60 * 1000,
+ });
+
+ if (rateLimitResponse) {
+ return rateLimitResponse;
+ }
+
+ try {
+ return NextResponse.json(
+ await checkSigningFieldFit(
+ token,
+ await request.json().catch(() => null),
+ {
+ database: getDb(),
+ verifiedMethods: verifiedMethodsForRequest(token, request),
+ },
+ ),
+ { headers: NO_STORE },
+ );
+ } catch (error) {
+ if (error instanceof ZodError) {
+ return NextResponse.json(
+ { error: "Invalid request." },
+ { headers: NO_STORE, status: 400 },
+ );
+ }
+
+ if (error instanceof SigningVerificationRequiredError) {
+ return verificationRequiredResponse(error);
+ }
+
+ if (error instanceof SigningMutationError) {
+ return NextResponse.json(
+ { error: error.message },
+ { headers: NO_STORE, status: error.statusCode },
+ );
+ }
+
+ if (error instanceof SigningAccessError) {
+ return NextResponse.json(
+ { error: error.message, state: error.state },
+ { headers: NO_STORE, status: error.statusCode },
+ );
+ }
+
+ logRouteError(error, {
+ category: "signing_field_fit_failure",
+ ipAddress: getClientIpAddress(request.headers),
+ message: "Unexpected failure while checking an answer fits its box.",
+ path: request.url,
+ });
+
+ return NextResponse.json(
+ { error: "The answer could not be checked right now." },
+ { headers: NO_STORE, status: 500 },
+ );
+ }
+}
diff --git a/src/components/signing/signing-live-shell.tsx b/src/components/signing/signing-live-shell.tsx
index cc18951..bbf6a5e 100644
--- a/src/components/signing/signing-live-shell.tsx
+++ b/src/components/signing/signing-live-shell.tsx
@@ -222,6 +222,22 @@ function getRadioGroup(
);
}
+function withoutKey(record: Record<string, number>, key: string) {
+ if (!(key in record)) {
+ return record;
+ }
+
+ const next = { ...record };
+
+ delete next[key];
+
+ return next;
+}
+
+function describeTooLongAnswer(maxCharacters: number) {
+ return `This answer is too long to fit in its box on the document. Shorten it to ${maxCharacters} characters or fewer.`;
+}
+
/** A number field holding something that is not a number. */
function hasInvalidNumber(
field: SigningCurrentField,
@@ -522,6 +538,14 @@ export function SigningLiveShell({
useState<SignatureModalState | null>(null);
const [submitError, setSubmitError] = useState<string | null>(null);
const [textValues, setTextValues] = useState<Record<string, string>>({});
+ // Text answers too long for their box on the finished document, with how
+ // many characters would fit. Checked on the server as the signer types,
+ // with the fonts the document is drawn with.
+ const [tooLongAnswers, setTooLongAnswers] = useState<Record<string, number>>(
+ {},
+ );
+ const checkedAnswersRef = useRef<Record<string, string>>({});
+ const latestTextValuesRef = useRef(textValues);
const [drawnSignatureVersion, setDrawnSignatureVersion] = useState(0);
const [zoomLevel, setZoomLevel] = useState(DEFAULT_DOCUMENT_ZOOM_LEVEL);
const [localDateLabel] = useState(() =>
@@ -578,7 +602,16 @@ export function SigningLiveShell({
const invalidNumberCount = record.currentSignerFields.filter((field) =>
hasInvalidNumber(field, textValues),
).length;
- const canFinish = remainingFields === 0 && invalidNumberCount === 0;
+ const tooLongFields = record.currentSignerFields.filter(
+ (field) => field.type === "text" && tooLongAnswers[field.id] !== undefined,
+ );
+ const canFinish =
+ remainingFields === 0 &&
+ invalidNumberCount === 0 &&
+ tooLongFields.length === 0;
+ const isInvalidEntry = (field: SigningCurrentField) =>
+ hasInvalidNumber(field, textValues) ||
+ (field.type === "text" && tooLongAnswers[field.id] !== undefined);
const requiredFieldCount = countAnswerableFields(
record.currentSignerFields,
(field) => field.required,
@@ -591,6 +624,68 @@ export function SigningLiveShell({
);
const isDocumentReady = pdfRenderState === "ready";
+ useEffect(() => {
+ latestTextValuesRef.current = textValues;
+
+ const changed = record.currentSignerFields.filter(
+ (field) =>
+ field.type === "text" &&
+ (textValues[field.id] ?? "").trim() !==
+ (checkedAnswersRef.current[field.id] ?? ""),
+ );
+
+ if (changed.length === 0) {
+ return;
+ }
+
+ // After a pause in typing, not on every key.
+ const timer = window.setTimeout(() => {
+ for (const field of changed) {
+ const value = (textValues[field.id] ?? "").trim();
+
+ checkedAnswersRef.current[field.id] = value;
+
+ if (!value) {
+ setTooLongAnswers((current) => withoutKey(current, field.id));
+ continue;
+ }
+
+ void fetch(record.fieldFitUrl, {
+ body: JSON.stringify({ fieldId: field.id, value }),
+ headers: { "content-type": "application/json" },
+ method: "POST",
+ })
+ .then(async (response) => {
+ const payload = (await response.json().catch(() => null)) as {
+ fits?: boolean;
+ maxCharacters?: number;
+ } | null;
+
+ // An answer changed since is checked again on its own.
+ if (
+ !response.ok ||
+ !payload ||
+ (latestTextValuesRef.current[field.id] ?? "").trim() !== value
+ ) {
+ return;
+ }
+
+ setTooLongAnswers((current) =>
+ payload.fits === false &&
+ typeof payload.maxCharacters === "number"
+ ? { ...current, [field.id]: payload.maxCharacters }
+ : withoutKey(current, field.id),
+ );
+ })
+ .catch(() => {
+ // Signing checks it again when the signer finishes.
+ });
+ }
+ }, 400);
+
+ return () => window.clearTimeout(timer);
+ }, [record.currentSignerFields, record.fieldFitUrl, textValues]);
+
function applyZoomLevel(nextZoomLevel: number) {
if (nextZoomLevel <= DEFAULT_DOCUMENT_ZOOM_LEVEL) {
setIsDocumentPanning(false);
@@ -982,7 +1077,14 @@ export function SigningLiveShell({
field={field}
key={field.id}
localDateLabel={localDateLabel}
- isInvalid={hasInvalidNumber(field, textValues)}
+ isInvalid={isInvalidEntry(field)}
+ tooLongMessage={
+ tooLongAnswers[field.id] !== undefined
+ ? describeTooLongAnswer(
+ tooLongAnswers[field.id]!,
+ )
+ : null
+ }
signerName={record.signer.name}
onCheckboxChange={(checked) => {
setSubmitError(null);
@@ -1079,6 +1181,17 @@ export function SigningLiveShell({
{NUMBER_ENTRY_MESSAGE}
</p>
) : null}
+ {tooLongFields.map((field) => (
+ <p
+ className="mt-1.5 text-[0.8125rem] font-semibold leading-5 text-(--danger)"
+ key={field.id}
+ role="alert"
+ >
+ A text box on page {field.page} is full: shorten your answer
+ to {tooLongAnswers[field.id]} characters or fewer so all of
+ it fits on the document.
+ </p>
+ ))}
<div
aria-hidden="true"
className="mt-3 h-2 overflow-hidden rounded-full bg-(--surface-strong)"
@@ -1125,7 +1238,7 @@ export function SigningLiveShell({
record.currentSignerFields,
enteredValues,
)}
- isInvalid={hasInvalidNumber(field, textValues)}
+ isInvalid={isInvalidEntry(field)}
key={field.id}
label={`${getSummaryLabel(field)} · Page ${field.page}`}
value={getCompletionValue(
@@ -1478,6 +1591,7 @@ function CurrentSignerField({
signatureEntry,
signerName,
textValue,
+ tooLongMessage = null,
}: {
checkboxValue: boolean;
field: SigningCurrentField;
@@ -1491,6 +1605,8 @@ function CurrentSignerField({
/** What a name field shows: the name the sender gave this signer. */
signerName: string;
textValue: string;
+ /** Set when a text answer is too long for its box on the document. */
+ tooLongMessage?: string | null;
}) {
const frame = getFieldFrame(field);
const showInlineLabel = shouldShowInlineFieldLabel(field);
@@ -1568,11 +1684,17 @@ function CurrentSignerField({
if (field.type === "text") {
return (
<div
- className="absolute z-2 overflow-hidden rounded-[0.375rem] border-2 border-(--accent) bg-[rgb(var(--accent-rgb)/0.07)] focus-within:bg-white"
+ className={`absolute z-2 overflow-hidden rounded-[0.375rem] border-2 focus-within:bg-white ${
+ tooLongMessage
+ ? "border-(--danger) bg-(--danger-soft)"
+ : "border-(--accent) bg-[rgb(var(--accent-rgb)/0.07)]"
+ }`}
data-signing-field="true"
style={frame}
+ title={tooLongMessage ?? undefined}
>
<input
+ aria-invalid={tooLongMessage ? true : undefined}
aria-label={getFieldLabel(field)}
className="h-full w-full border-none bg-transparent px-2 text-sm text-(--fg) outline-none placeholder:text-(--placeholder)"
id={`signing-field-${field.id}`}
diff --git a/src/lib/long-text-field.dbtest.ts b/src/lib/long-text-field.dbtest.ts
index 6b659c7..3377754 100644
--- a/src/lib/long-text-field.dbtest.ts
+++ b/src/lib/long-text-field.dbtest.ts
@@ -10,6 +10,7 @@ import type { EmailService } from "./services/email.ts";
import { issueSigningLink } from "./services/signing-links.ts";
import type { StorageService } from "./services/storage.ts";
import {
+ checkSigningFieldFit,
recordSignerConsent,
SigningMutationError,
submitSigningForToken,
@@ -166,6 +167,33 @@ test("an answer too long for its box is refused, one that wraps to fit is taken"
return { status: signer.rows[0]?.status, value: field.rows[0]?.value };
};
+ // As the signer types: the same answer, checked before they finish.
+ const tooLongNow = await checkSigningFieldFit(
+ link.token,
+ { fieldId: textId, value: `BEGIN ${"W".repeat(240)} FINISH-MARKER` },
+ { database },
+ );
+
+ assert.equal(tooLongNow.fits, false);
+ assert.ok(!tooLongNow.fits && tooLongNow.maxCharacters > 0);
+ assert.deepEqual(
+ await checkSigningFieldFit(
+ link.token,
+ { fieldId: textId, value: "Approved" },
+ { database },
+ ),
+ { fits: true },
+ );
+ await assert.rejects(
+ checkSigningFieldFit(
+ link.token,
+ { fieldId: signatureId, value: "Riley Recipient" },
+ { database },
+ ),
+ (error: unknown) =>
+ error instanceof SigningMutationError && error.statusCode === 404,
+ );
+
await assert.rejects(
sign(`BEGIN ${"W".repeat(240)} FINISH-MARKER`),
(error: unknown) =>
diff --git a/src/lib/schemas/signing.ts b/src/lib/schemas/signing.ts
index b9450ce..d83226b 100644
--- a/src/lib/schemas/signing.ts
+++ b/src/lib/schemas/signing.ts
@@ -68,6 +68,8 @@ export const signingPayloadSchema = z.object({
currentSignerFields: z.array(signingCurrentFieldSchema),
disclosure: signingDisclosureSchema,
declineUrl: z.string().trim().min(1),
+ /** Checks, as the signer types, that an answer fits its box. */
+ fieldFitUrl: z.string().trim().min(1),
documentUrl: z.string().trim().min(1),
envelopeId: idSchema,
envelopeTitle: envelopeTitleSchema,
@@ -150,6 +152,12 @@ export const signerCheckRequestSchema = z.discriminatedUnion("method", [
}),
]);
+/** What the signer has typed so far in one field, to check it fits. */
+export const signingFieldFitRequestSchema = z.object({
+ fieldId: idSchema,
+ value: z.string().max(5000),
+});
+
export const signerConsentRequestSchema = z.object({
disclosureVersion: z.string().trim().min(1).max(40),
});
diff --git a/src/lib/signing.ts b/src/lib/signing.ts
index a8097d2..651b763 100644
--- a/src/lib/signing.ts
+++ b/src/lib/signing.ts
@@ -30,6 +30,7 @@ import {
import {
signerCheckRequestSchema,
signerConsentRequestSchema,
+ signingFieldFitRequestSchema,
signingPayloadSchema,
signingDeclineResponseSchema,
type SigningVerificationState,
@@ -320,6 +321,10 @@ function getSigningConsentUrl(token: string): string {
return `/api/signing/${encodeURIComponent(token)}/consent`;
}
+function getSigningFieldFitUrl(token: string): string {
+ return `/api/signing/${encodeURIComponent(token)}/fit`;
+}
+
function getSigningDeclineUrl(token: string): string {
return `/api/signing/${encodeURIComponent(token)}/decline`;
}
@@ -1617,6 +1622,47 @@ export async function verifySignerCheck(
}
/** Records that the signer agreed to use electronic records and signatures. */
+/**
+ * Whether what the signer has typed so far fits the field's box on the
+ * finished document, checked as they type, so they learn before they finish.
+ * The same check signing makes, with the same fonts.
+ */
+export async function checkSigningFieldFit(
+ token: string,
+ input: unknown,
+ {
+ database = getDb(),
+ verifiedMethods = [],
+ }: Pick<SubmitSigningOptions, "database" | "verifiedMethods"> = {},
+): Promise<{ fits: true } | { fits: false; maxCharacters: number }> {
+ const parsed = signingFieldFitRequestSchema.parse(input);
+ const context = await resolveSigningContext(token, { database });
+
+ await assertSignerChecksPassed(context, verifiedMethods, database);
+
+ const field = context.fields.find(
+ (entry) =>
+ entry.id === parsed.fieldId &&
+ entry.signerId === context.signer.id &&
+ (entry.type === "text" ||
+ entry.type === "number" ||
+ entry.type === "dropdown"),
+ );
+
+ if (!field) {
+ throw new SigningMutationError("That field is not yours to fill in.", 404);
+ }
+
+ const tooLong = await findTypedValueTooLongForField(
+ [{ field, value: parsed.value }],
+ context.pages,
+ );
+
+ return tooLong
+ ? { fits: false, maxCharacters: tooLong.maxCharacters }
+ : { fits: true };
+}
+
export async function recordSignerConsent(
token: string,
input: unknown,
@@ -1872,6 +1918,7 @@ export async function getSigningPayloadForToken(
return signingPayloadSchema.parse({
consentUrl: getSigningConsentUrl(token),
+ fieldFitUrl: getSigningFieldFitUrl(token),
consentedAt: checkState.consentedAt,
currentSignerFields,
disclosure: {