@mccaskie-labs/workbench-agreements 0.3.1 → 0.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,726 @@
1
+ // Open documents (spec 25, docs/capabilities/25-signed-forms.md): saved
2
+ // wording plus a form's questions, signed by anyone from a link or a QR code
3
+ // with no signers named beforehand, for themselves or for a child, valid for
4
+ // one event or a number of months. The same identity check, consent words,
5
+ // audit trail and signed copy with its certificate as an agreement.
6
+ //
7
+ // Everything stays in the app: the PDFs, drawn signatures and uploaded files
8
+ // in its own R2 bucket, the records in its own database (documentsMigration).
9
+ // Workbench holds none of it, and nothing a signer types, draws or uploads
10
+ // goes to the Gateway; only the emails do.
11
+ //
12
+ // Links, under the agreements path (`sign` by default):
13
+ // /sign/d/<slug> the document's public link (a QR code points here)
14
+ // /sign/r/<token> a link the app asked for, one per place on a booking
15
+ // /sign/s/<token> one person's signing, once they have said who they are
16
+ // each with /document.pdf, and /sign/s/<token>/signed.pdf once signed.
17
+ import { checkFiles, labelKeys, readForm, renderForm, sensitiveFields, validate } from "@mccaskie-labs/workbench-forms";
18
+ import { buildSignedCopy, pdfPages } from "./certificate.js";
19
+ import { AGREEMENT_LANGUAGES, SIGNING_METHODS } from "./config.js";
20
+ import { AgreementsError } from "./errors.js";
21
+ import { renderCodePage, renderDonePage, renderEndedPage, renderOpenSigningPage, renderOpenStartPage } from "./page.js";
22
+ import { codeHash, isToken, newCode, newToken, sha256Hex } from "./secrets.js";
23
+ import { readDrawnSignature } from "./signature.js";
24
+ import { agreementWord } from "./words.js";
25
+ /** Names the signing page uses itself: a form an open document asks can't have a field by one of these. */
26
+ export const RESERVED_FIELDS = ["action", "name", "email", "method", "signature", "consent_read", "consent_esign", "child", "child_name", "relationship", "child_declare", "code", "reason"];
27
+ const DAY_MS = 86_400_000;
28
+ const CODE_MS = 10 * 60_000;
29
+ /** A started signing that isn't finished in a day times out. */
30
+ const SESSION_MS = DAY_MS;
31
+ const MAX_FORM_BYTES = 300_000;
32
+ const EMAIL = /^[^@\s]+@[^@\s]+\.[^@\s]+$/;
33
+ const SLUG = /^[a-z0-9][a-z0-9-]{2,59}$/;
34
+ const text = (v, min, max) => typeof v === "string" && v.trim().length >= min && v.trim().length <= max;
35
+ const iso = (s) => (s ? new Date(s).toISOString() : null);
36
+ /** Adds whole calendar months in UTC, keeping the day where the month has it (31 January + 1 month is 28 or 29 February). */
37
+ export function addMonths(d, months) {
38
+ const out = new Date(d);
39
+ const day = out.getUTCDate();
40
+ out.setUTCDate(1);
41
+ out.setUTCMonth(out.getUTCMonth() + months);
42
+ const last = new Date(Date.UTC(out.getUTCFullYear(), out.getUTCMonth() + 1, 0)).getUTCDate();
43
+ out.setUTCDate(Math.min(day, last));
44
+ return out;
45
+ }
46
+ export function openDocuments(kit) {
47
+ const { config, call, now } = kit;
48
+ const p = config.path;
49
+ const pathRe = new RegExp(`^/${p}/(d|r|s)/([A-Za-z0-9_-]+)(?:/(document|signed)\\.pdf)?/?$`);
50
+ const publicLink = (slug) => `${kit.base}/${p}/d/${slug}`;
51
+ const word = (language, key, params) => agreementWord(kit.t, language, key, params);
52
+ const lasts = (d) => (d.validity_months ? word(d.language, "open.lasts_months", { months: d.validity_months }) : word(d.language, "open.lasts_event"));
53
+ const formFor = (d) => (d.form ? kit.forms[d.form] : undefined);
54
+ const formWords = (language) => (key, params) => kit.t?.(key, params, language);
55
+ const toDocument = (d) => ({
56
+ id: d.id,
57
+ account: d.account,
58
+ slug: d.slug,
59
+ version: d.version,
60
+ title: d.title,
61
+ business: d.business,
62
+ language: d.language,
63
+ documentSha256: d.document_sha256,
64
+ pages: d.pages,
65
+ form: d.form,
66
+ forChild: d.for_child,
67
+ validity: d.validity_months ? { months: d.validity_months } : "event",
68
+ copyTo: d.copy_to ?? [],
69
+ createdAt: iso(d.created_at),
70
+ retiredAt: iso(d.retired_at),
71
+ url: publicLink(d.slug),
72
+ ...(d.signed !== undefined ? { signed: Number(d.signed) } : {}),
73
+ });
74
+ const toSignature = (s, d) => ({
75
+ id: s.id,
76
+ slug: d?.slug ?? s.slug,
77
+ version: d?.version ?? s.version,
78
+ title: d?.title ?? s.title,
79
+ subject: s.subject_type && s.subject_id ? { type: s.subject_type, id: s.subject_id } : null,
80
+ name: s.name,
81
+ email: s.email,
82
+ forChild: s.for_child,
83
+ childName: s.child_name,
84
+ relationship: s.relationship,
85
+ answers: s.answers ?? {},
86
+ sensitive: s.sensitive,
87
+ files: (s.files ?? []).map(({ field, name, kind, size, sha256 }) => ({ field, name, kind, size, sha256 })),
88
+ signedAt: iso(s.signed_at),
89
+ validUntil: iso(s.valid_until),
90
+ method: s.method,
91
+ typedName: s.typed_name,
92
+ signedSha256: s.signed_sha256,
93
+ sensitiveDeletedAt: iso(s.sensitive_deleted_at),
94
+ });
95
+ async function full(id) {
96
+ if (!/^[0-9a-f-]{36}$/i.test(id))
97
+ return null;
98
+ return call("documents_signature", { p_id: id }, "reading the signature");
99
+ }
100
+ function eventText(s, d, e) {
101
+ const who = `${s.name} (${s.email})`;
102
+ const from = e.ip ? ` from ${e.ip}` : "";
103
+ switch (e.kind) {
104
+ case "started":
105
+ return `${who} started signing ${d.title}, version ${d.version} (SHA-256 ${d.document_sha256.slice(0, 16)}…)${e.detail?.request ? ", from a link sent for a booking" : ", from its public link"}${from}`;
106
+ case "code_sent":
107
+ return `One-time code emailed to ${s.email}`;
108
+ case "code_failed":
109
+ return `A wrong code was entered${from}`;
110
+ case "verified":
111
+ return `${who} entered the emailed code${from}`;
112
+ case "opened":
113
+ return `${who} opened the signing page${from}`;
114
+ case "document_viewed":
115
+ return `${who} opened the document's PDF${from}`;
116
+ case "signed":
117
+ return `${who} signed (${e.detail?.method === "drawn" ? "drew their signature" : "typed their name"})${s.for_child ? ` for ${s.child_name}, as their ${s.relationship === "guardian" ? "legal guardian" : "parent"}` : ""}${from}`;
118
+ default:
119
+ return null;
120
+ }
121
+ }
122
+ async function finish(id) {
123
+ const r = await full(id);
124
+ if (!r || r.signature.status !== "signed" || r.signature.signed_key)
125
+ return false;
126
+ const { signature: s, document: d } = r;
127
+ const doc = await kit.load(d.document_key);
128
+ const f = formFor(d);
129
+ const sensitive = new Set(f ? sensitiveFields(f.form) : []);
130
+ const facts = [];
131
+ if (f) {
132
+ for (const [name, def] of Object.entries(f.form.fields)) {
133
+ if (sensitive.has(name) || def.kind === "file")
134
+ continue;
135
+ const label = labelKeys(f.form.name, name).map((k) => kit.t?.(k, undefined, d.language)).find((x) => x !== undefined) ?? name;
136
+ const v = s.answers?.[name];
137
+ const value = v === null || v === undefined ? "" : typeof v === "boolean" ? (v ? "Yes" : "No") : Array.isArray(v) ? v.join(", ") : String(v);
138
+ facts.push({ label, value });
139
+ }
140
+ }
141
+ const held = [sensitive.size ? `${sensitive.size} sensitive answer${sensitive.size === 1 ? "" : "s"}` : "", s.files?.length ? `${s.files.length} file${s.files.length === 1 ? "" : "s"}` : ""].filter(Boolean).join(" and ");
142
+ const note = `${held ? `${held} ${held.includes(" and ") || s.files?.length > 1 || sensitive.size > 1 ? "are" : "is"} kept by ${d.business} and not printed here. ` : ""}SHA-256 of all the answers${s.files?.length ? " and files" : ""}: ${s.answers_sha256}.`;
143
+ const all = r.events.map((e) => ({ at: e.at, what: eventText(s, d, e) })).filter((e) => e.what !== null);
144
+ const signedAt = s.signed_at;
145
+ const role = s.for_child ? word("en", "child.on_behalf", { child: s.child_name, relationship: s.relationship === "guardian" ? "legal guardian" : "parent" }) : null;
146
+ const bytes = await buildSignedCopy({
147
+ kind: "open",
148
+ document: doc,
149
+ id: s.id,
150
+ title: d.title,
151
+ business: d.business,
152
+ createdAt: s.created_at,
153
+ completedAt: signedAt,
154
+ documentSha256: d.document_sha256,
155
+ signers: [
156
+ {
157
+ name: s.name,
158
+ email: s.email,
159
+ role,
160
+ method: s.method,
161
+ typedName: s.typed_name,
162
+ signedAt,
163
+ identity: config.identity === "email_code" ? "open_email_code" : "open_link",
164
+ ip: s.sign_ip,
165
+ userAgent: s.sign_user_agent,
166
+ signature: s.signature_key ? await kit.load(s.signature_key) : null,
167
+ },
168
+ ],
169
+ events: all.length > 300 ? all.slice(0, 300) : all,
170
+ timeZone: config.time_zone,
171
+ locale: kit.locale,
172
+ ...(f ? { answers: { facts, note } } : {}),
173
+ });
174
+ const sha = await sha256Hex(bytes);
175
+ const key = `documents/${s.id}/signed.pdf`;
176
+ await kit.store(key, bytes, "application/pdf");
177
+ return call("documents_complete", { p_id: s.id, p_signed_key: key, p_signed_sha256: sha, p_at: now().toISOString() }, "completing the signature");
178
+ }
179
+ async function sendCopy(id) {
180
+ const r = await full(id);
181
+ if (!r || !r.signature.signed_key || r.signature.copies_sent_at)
182
+ return false;
183
+ const { signature: s, document: d } = r;
184
+ const bytes = await kit.load(s.signed_key);
185
+ const to = [...new Set([s.email, ...(d.copy_to ?? [])].map((e) => e.toLowerCase()))];
186
+ const params = { name: s.name, title: d.title, business: d.business, id: s.id, sha256: s.signed_sha256 };
187
+ await kit.mailer.send({
188
+ to,
189
+ subject: word(d.language, "email.open_signed.subject", params),
190
+ text: word(d.language, "email.open_signed.text", params),
191
+ template: "agreement.open_signed",
192
+ ...(kit.replyTo ? { replyTo: kit.replyTo } : {}),
193
+ attachments: [{ filename: `${kit.slug(d.title)}-signed.pdf`, mimeType: "application/pdf", bytes }],
194
+ idempotencyKey: `document-signed-${s.id}`,
195
+ });
196
+ await call("documents_copies_sent", { p_id: s.id, p_at: now().toISOString(), p_count: to.length }, "recording the copies");
197
+ return true;
198
+ }
199
+ // ---- the owner's side ----
200
+ const api = {
201
+ async save(req) {
202
+ if (!text(req.account, 1, 200))
203
+ throw new AgreementsError("invalid_request", "account must be 1 to 200 characters");
204
+ if (typeof req.slug !== "string" || !SLUG.test(req.slug))
205
+ throw new AgreementsError("invalid_request", "slug must be 3 to 60 lower-case letters, digits and dashes, starting with a letter or digit");
206
+ if (!text(req.title, 1, 200))
207
+ throw new AgreementsError("invalid_request", "title must be 1 to 200 characters");
208
+ if (!text(req.business, 1, 200))
209
+ throw new AgreementsError("invalid_request", "business must be 1 to 200 characters");
210
+ if (!(req.document instanceof Uint8Array) || req.document.length > 10 * 1024 * 1024)
211
+ throw new AgreementsError("invalid_request", "document must be the PDF's bytes, up to 10 MB");
212
+ if (req.form !== undefined && !kit.forms[req.form])
213
+ throw new AgreementsError("invalid_request", `form ${req.form} isn't one of createAgreements' documentForms`);
214
+ const forChild = req.forChild ?? "never";
215
+ if (!["never", "allowed", "always"].includes(forChild))
216
+ throw new AgreementsError("invalid_request", "forChild must be never, allowed or always");
217
+ const v = req.validity;
218
+ const months = v === "event" ? null : v && typeof v === "object" && Number.isInteger(v.months) && v.months >= 1 && v.months <= 120 ? v.months : undefined;
219
+ if (months === undefined)
220
+ throw new AgreementsError("invalid_request", 'validity must be "event" or { months: 1 to 120 }');
221
+ const copyTo = (req.copyTo ?? []).map((e) => e.trim());
222
+ if (copyTo.length > 5 || copyTo.some((e) => e.length > 254 || !EMAIL.test(e)))
223
+ throw new AgreementsError("invalid_request", "copyTo must list up to 5 email addresses");
224
+ const language = req.language ?? config.language;
225
+ if (!AGREEMENT_LANGUAGES.includes(language))
226
+ throw new AgreementsError("invalid_request", "language must be en, tl or taglish");
227
+ const pages = await pdfPages(req.document);
228
+ const sha = await sha256Hex(req.document);
229
+ const id = crypto.randomUUID();
230
+ const key = `documents/versions/${id}/document.pdf`;
231
+ await kit.store(key, req.document, "application/pdf");
232
+ const r = await call("documents_save", {
233
+ p: {
234
+ id,
235
+ account: req.account.trim(),
236
+ slug: req.slug,
237
+ title: req.title.trim(),
238
+ business: req.business.trim(),
239
+ language,
240
+ document_key: key,
241
+ document_sha256: sha,
242
+ pages,
243
+ form: req.form ?? null,
244
+ for_child: forChild,
245
+ validity_months: months,
246
+ copy_to: copyTo,
247
+ created_at: now().toISOString(),
248
+ },
249
+ }, "saving the document").catch(async (e) => {
250
+ await kit.remove([key]).catch(() => { });
251
+ throw e;
252
+ });
253
+ if (!r.ok) {
254
+ await kit.remove([key]).catch(() => { });
255
+ throw new AgreementsError("conflict", `the link ${req.slug} belongs to another account: pick another slug`);
256
+ }
257
+ return toDocument((await call("documents_get", { p_id: id }, "reading the document")));
258
+ },
259
+ async get(slug) {
260
+ if (typeof slug !== "string" || !SLUG.test(slug))
261
+ return null;
262
+ const d = await call("documents_current", { p_slug: slug }, "reading the document");
263
+ return d ? toDocument(d) : null;
264
+ },
265
+ async list(account, limit = 50) {
266
+ if (!text(account, 1, 200))
267
+ throw new AgreementsError("invalid_request", "account must be 1 to 200 characters");
268
+ const rows = await call("documents_list", { p_account: account, p_limit: Math.min(Math.max(1, Math.floor(limit)), 200) }, "listing documents");
269
+ return (rows ?? []).map(toDocument);
270
+ },
271
+ async retire(account, slug) {
272
+ if (!text(account, 1, 200) || typeof slug !== "string" || !SLUG.test(slug))
273
+ return false;
274
+ return call("documents_retire", { p_slug: slug, p_account: account, p_at: now().toISOString() }, "retiring the document");
275
+ },
276
+ link: publicLink,
277
+ async share(slug) {
278
+ const d = await api.get(slug);
279
+ if (!d)
280
+ return null;
281
+ const msg = word(d.language, "share.open", { title: d.title, business: d.business, url: d.url });
282
+ return { url: d.url, text: msg, whatsapp: `https://wa.me/?text=${encodeURIComponent(msg)}` };
283
+ },
284
+ async request(req) {
285
+ const d = typeof req.slug === "string" && SLUG.test(req.slug) ? await call("documents_current", { p_slug: req.slug }, "reading the document") : null;
286
+ if (!d)
287
+ throw new AgreementsError("not_found", `no document ${req.slug}`);
288
+ if (!req.subject || !text(req.subject.type, 1, 60) || !text(req.subject.id, 1, 200))
289
+ throw new AgreementsError("invalid_request", "subject must be { type, id }");
290
+ if (!Number.isInteger(req.places) || req.places < 1 || req.places > 50)
291
+ throw new AgreementsError("invalid_request", "places must be 1 to 50");
292
+ const t = now();
293
+ if (req.validUntil && !(req.validUntil.getTime() > t.getTime()))
294
+ throw new AgreementsError("invalid_request", "validUntil must be in the future");
295
+ const expires = req.expiresAt ?? req.validUntil ?? new Date(t.getTime() + config.expires_after_days * DAY_MS);
296
+ if (!(expires.getTime() > t.getTime()))
297
+ throw new AgreementsError("invalid_request", "expiresAt must be in the future");
298
+ if (req.email && (!EMAIL.test(req.email.to?.trim() ?? "") || !text(req.email.name, 1, 120)))
299
+ throw new AgreementsError("invalid_request", "email must be { to, name }");
300
+ const toks = Array.from({ length: req.places }, () => newToken());
301
+ await call("documents_request", {
302
+ p: {
303
+ document_id: d.id,
304
+ subject_type: req.subject.type,
305
+ subject_id: req.subject.id,
306
+ valid_until: d.validity_months ? null : (req.validUntil?.toISOString() ?? null),
307
+ created_at: t.toISOString(),
308
+ expires_at: expires.toISOString(),
309
+ tokens: toks,
310
+ },
311
+ }, "making the links");
312
+ const links = toks.map((x) => `${kit.base}/${p}/r/${x}`);
313
+ if (req.email) {
314
+ const params = { name: req.email.name.trim(), business: d.business, title: d.title, date: kit.dateLabel(expires.toISOString()), links: links.map((l, i) => `${i + 1}. ${l}`).join("\n") };
315
+ await kit.mailer.send({
316
+ to: req.email.to.trim(),
317
+ subject: word(d.language, "email.request.subject", params),
318
+ text: word(d.language, "email.request.text", params),
319
+ template: "agreement.request",
320
+ ...(kit.replyTo ? { replyTo: kit.replyTo } : {}),
321
+ idempotencyKey: `document-request-${d.id}-${req.subject.type}-${req.subject.id}-${toks[0].slice(0, 8)}`,
322
+ });
323
+ }
324
+ return { links };
325
+ },
326
+ async valid(slug, person, subject) {
327
+ if (typeof slug !== "string" || !SLUG.test(slug) || typeof person?.email !== "string")
328
+ return null;
329
+ const r = await call("documents_valid", { p_slug: slug, p_email: person.email.trim(), p_child: person.child?.trim().replace(/\s+/g, " ") ?? null, p_subject_type: subject?.type ?? null, p_subject_id: subject?.id ?? null, p_at: now().toISOString() }, "checking the signature");
330
+ return r ? { id: r.id, version: r.version, signedAt: iso(r.signed_at), validUntil: iso(r.valid_until) } : null;
331
+ },
332
+ async signatures(account, opts = {}) {
333
+ if (!text(account, 1, 200))
334
+ throw new AgreementsError("invalid_request", "account must be 1 to 200 characters");
335
+ const rows = await call("documents_signatures", { p_account: account, p_slug: opts.slug ?? null, p_limit: Math.min(Math.max(1, Math.floor(opts.limit ?? 50)), 200) }, "listing signatures");
336
+ return (rows ?? []).map((s) => toSignature(s));
337
+ },
338
+ async signature(id) {
339
+ const r = await full(id);
340
+ if (!r || r.signature.status !== "signed")
341
+ return null;
342
+ return {
343
+ ...toSignature(r.signature, r.document),
344
+ account: r.document.account,
345
+ events: r.events.map((e) => ({ kind: e.kind, at: iso(e.at), ip: e.ip, userAgent: e.user_agent })),
346
+ };
347
+ },
348
+ async file(id, which) {
349
+ const r = await full(id);
350
+ if (!r || r.signature.status !== "signed")
351
+ return null;
352
+ if (which === "signed")
353
+ return r.signature.signed_key ? { bytes: await kit.load(r.signature.signed_key), contentType: "application/pdf", name: `${kit.slug(r.document.title)}-signed.pdf` } : null;
354
+ const f = (r.signature.files ?? []).find((x) => x.field === which.field);
355
+ if (!f)
356
+ return null;
357
+ const contentType = { pdf: "application/pdf", jpeg: "image/jpeg", png: "image/png", webp: "image/webp", heic: "image/heic", docx: "application/vnd.openxmlformats-officedocument.wordprocessingml.document" }[f.kind] ?? "application/octet-stream";
358
+ return { bytes: await kit.load(f.key), contentType, name: f.name };
359
+ },
360
+ };
361
+ // ---- the route ----
362
+ async function handle(request, ctx) {
363
+ const url = new URL(request.url);
364
+ const m = pathRe.exec(url.pathname);
365
+ if (!m)
366
+ return null;
367
+ const [, where, key, file] = m;
368
+ const method = request.method.toUpperCase();
369
+ const head = method === "HEAD";
370
+ const notFound = () => kit.html(404, renderEndedPage("not_found", kit.common(config.language)), false, head);
371
+ if (method === "POST") {
372
+ if (file)
373
+ return kit.bare(405, { allow: "GET, HEAD" });
374
+ const origin = request.headers.get("origin");
375
+ if (origin && origin !== url.origin && origin !== new URL(kit.base).origin)
376
+ return kit.bare(403);
377
+ }
378
+ else if (method !== "GET" && !head)
379
+ return kit.bare(405, { allow: "GET, HEAD, POST" });
380
+ const { ip, ua } = kit.device(request);
381
+ const at = now();
382
+ if (where === "d" || where === "r") {
383
+ let d;
384
+ let req = null;
385
+ if (where === "d") {
386
+ if (!SLUG.test(key))
387
+ return notFound();
388
+ d = await call("documents_current", { p_slug: key }, "reading the document");
389
+ }
390
+ else {
391
+ if (!isToken(key))
392
+ return notFound();
393
+ const o = await call("documents_request_open", { p_token: key }, "opening the link");
394
+ d = o?.document ?? null;
395
+ req = o?.request ?? null;
396
+ }
397
+ if (!d)
398
+ return notFound();
399
+ const o = { ...kit.common(d.language), business: d.business };
400
+ if (file === "signed")
401
+ return notFound();
402
+ if (file === "document")
403
+ return kit.pdf(await kit.load(d.document_key), `${kit.slug(d.title)}.pdf`, head);
404
+ if (req?.signature_id)
405
+ return kit.html(410, renderEndedPage("used", { ...o, title: d.title }), false, head);
406
+ if (req && Date.parse(req.expires_at) <= at.getTime())
407
+ return kit.html(410, renderEndedPage("expired", { ...o, title: d.title }), false, head);
408
+ const self = `/${p}/${where}/${key}`;
409
+ const view = { title: d.title, business: d.business, lasts: lasts(d), pages: d.pages, documentHref: `${self}/document.pdf` };
410
+ if (method !== "POST")
411
+ return kit.html(200, renderOpenStartPage(view, o), false, head);
412
+ const body = await request.text();
413
+ if (body.length > MAX_FORM_BYTES)
414
+ return kit.bare(413);
415
+ const form = new URLSearchParams(body);
416
+ if (form.get("action") !== "start")
417
+ return kit.bare(400);
418
+ const name = (form.get("name") ?? "").trim().replace(/\s+/g, " ");
419
+ const email = (form.get("email") ?? "").trim();
420
+ const problems = [];
421
+ if (name.length < 2 || name.length > 120)
422
+ problems.push("problem.name");
423
+ if (email.length > 254 || !EMAIL.test(email))
424
+ problems.push("problem.email");
425
+ if (problems.length)
426
+ return kit.html(400, renderOpenStartPage(view, { ...o, name, email, problems }), false, false);
427
+ const token = newToken();
428
+ const id = crypto.randomUUID();
429
+ const r = await call("documents_start", { p: { id, document_id: d.id, request_id: req?.id ?? null, token, name, email, created_at: at.toISOString(), ip, ua } }, "starting the signing");
430
+ if (!r.ok) {
431
+ if (r.reason === "busy")
432
+ return kit.html(429, renderOpenStartPage(view, { ...o, name, email, problems: ["problem.busy"] }), false, false);
433
+ return kit.html(410, renderEndedPage(r.reason ?? "retired", { ...o, title: d.title }), false, false);
434
+ }
435
+ if (config.identity === "email_code")
436
+ await sendCode(id, email, d, at, ip, ua);
437
+ return kit.redirect(`/${p}/s/${token}`);
438
+ }
439
+ // where === "s": one person's signing.
440
+ if (!isToken(key))
441
+ return notFound();
442
+ const opened = await call("documents_open", { p_token: key }, "opening the signing");
443
+ if (!opened)
444
+ return notFound();
445
+ const { signature: s, document: d } = opened;
446
+ const o = { ...kit.common(d.language), business: d.business };
447
+ const self = `/${p}/s/${key}`;
448
+ const ev = (kind) => ctx.waitUntil(call("documents_event", { p_signature: s.id, p_kind: kind, p_at: now().toISOString(), p_ip: ip, p_ua: ua, p_detail: null }, "recording the event").catch((e) => console.error("workbench-agreements: an event wasn't recorded", e)));
449
+ const needCode = config.identity === "email_code" && !s.verified_at;
450
+ const stale = s.status === "pending" && Date.parse(s.created_at) <= at.getTime() - SESSION_MS;
451
+ const retired = s.status === "pending" && !s.request_id && !!d.retired_at;
452
+ if (file === "signed") {
453
+ if (!s.signed_key)
454
+ return notFound();
455
+ if (!head)
456
+ ev("copy_downloaded");
457
+ return kit.pdf(await kit.load(s.signed_key), `${kit.slug(d.title)}-signed.pdf`, head);
458
+ }
459
+ if (file === "document") {
460
+ if (s.status === "pending" && (needCode || stale))
461
+ return notFound();
462
+ if (!head)
463
+ ev("document_viewed");
464
+ return kit.pdf(await kit.load(d.document_key), `${kit.slug(d.title)}.pdf`, head);
465
+ }
466
+ const view = { title: d.title, business: d.business, lasts: lasts(d), pages: d.pages, documentHref: `${self}/document.pdf`, signerName: s.name };
467
+ const f = formFor(d);
468
+ const questions = (result, input) => f ? renderForm(f.form, f.context, { action: self, t: formWords(d.language), submit: "ui.wbagreement.open.sign", fieldsOnly: true, ...(result ? { result } : {}), ...(input ? { input } : {}) }) : undefined;
469
+ const multipart = !!f && Object.values(f.form.fields).some((x) => x.kind === "file");
470
+ if (method !== "POST") {
471
+ if (s.status === "signed") {
472
+ return kit.html(200, renderDonePage({ title: d.title }, { ...o, signedAt: kit.dateLabel(s.signed_at), completed: true, ...(s.signed_key ? { downloadHref: `${self}/signed.pdf` } : {}), open: true }), false, head);
473
+ }
474
+ if (stale)
475
+ return kit.html(410, renderEndedPage("stale", { ...o, title: d.title }), false, head);
476
+ if (retired)
477
+ return kit.html(410, renderEndedPage("retired", { ...o, title: d.title }), false, head);
478
+ if (needCode)
479
+ return kit.html(200, renderCodePage({ title: d.title, business: d.business, signerEmail: s.email }, { ...o, sent: !!s.code_expires_at && Date.parse(s.code_expires_at) > at.getTime() }), false, head);
480
+ if (!head)
481
+ ev("opened");
482
+ return kit.html(200, renderOpenSigningPage(view, config.methods, { ...o, forChild: d.for_child, child: d.for_child === "always", ...(f ? { questions: questions() } : {}), multipart }), true, head);
483
+ }
484
+ if (s.status !== "pending" || stale || retired)
485
+ return kit.redirect(self);
486
+ const type = request.headers.get("content-type") ?? "";
487
+ const isMultipart = type.toLowerCase().startsWith("multipart/form-data");
488
+ const limit = MAX_FORM_BYTES + (multipart && f ? Object.values(f.form.fields).reduce((n, x) => n + (x.kind === "file" ? ((f.context.bounds[x.limit]?.max ?? 0) * 1024 * 1024) : 0), 0) : 0);
489
+ const length = Number(request.headers.get("content-length") ?? "0");
490
+ if (length > limit)
491
+ return kit.bare(413);
492
+ let data;
493
+ try {
494
+ if (isMultipart) {
495
+ if (!multipart)
496
+ return kit.bare(415);
497
+ data = await request.formData();
498
+ }
499
+ else {
500
+ const body = await request.text();
501
+ if (body.length > MAX_FORM_BYTES)
502
+ return kit.bare(413);
503
+ data = new URLSearchParams(body);
504
+ }
505
+ }
506
+ catch {
507
+ return kit.bare(400);
508
+ }
509
+ const str = (k) => {
510
+ const v = data.get(k);
511
+ return typeof v === "string" ? v : "";
512
+ };
513
+ const action = str("action");
514
+ if (action === "send_code" || action === "check_code") {
515
+ if (!needCode)
516
+ return kit.redirect(self);
517
+ const v = { title: d.title, business: d.business, signerEmail: s.email };
518
+ if (action === "send_code") {
519
+ const ok = await sendCode(s.id, s.email, d, at, ip, ua);
520
+ return kit.html(ok ? 200 : 429, renderCodePage(v, { ...o, sent: true, ...(ok ? {} : { problems: ["problem.code_wait"] }) }), false, false);
521
+ }
522
+ const code = str("code").replace(/\s/g, "");
523
+ const r = /^\d{6}$/.test(code) ? await call("documents_code_try", { p_signature: s.id, p_code_hash: await codeHash(s.id, code), p_at: at.toISOString(), p_ip: ip, p_ua: ua }, "checking the code") : "wrong";
524
+ if (r === "ok")
525
+ return kit.redirect(self);
526
+ const problem = r === "expired" || r === "none" ? "problem.code_expired" : r === "locked" ? "problem.code_locked" : "problem.code";
527
+ return kit.html(400, renderCodePage(v, { ...o, sent: r === "wrong", problems: [problem] }), false, false);
528
+ }
529
+ if (action !== "sign")
530
+ return kit.bare(400);
531
+ if (needCode)
532
+ return kit.redirect(self);
533
+ // Read and check everything, then show every problem at once.
534
+ const name = str("name").trim().replace(/\s+/g, " ");
535
+ const chosen = (str("method") || config.methods[0]);
536
+ const state = { name, consentRead: str("consent_read") === "yes", consentEsign: str("consent_esign") === "yes" };
537
+ if (SIGNING_METHODS.includes(chosen))
538
+ state.method = chosen;
539
+ const forChild = d.for_child === "always" || (d.for_child === "allowed" && str("child") === "yes");
540
+ const childName = str("child_name").trim().replace(/\s+/g, " ");
541
+ const relationship = str("relationship");
542
+ Object.assign(state, { child: forChild, childName, childDeclared: str("child_declare") === "yes", ...(relationship === "parent" || relationship === "guardian" ? { relationship } : {}) });
543
+ const problems = [];
544
+ if (forChild) {
545
+ if (childName.length < 2 || childName.length > 120)
546
+ problems.push("problem.child_name");
547
+ if (relationship !== "parent" && relationship !== "guardian")
548
+ problems.push("problem.relationship");
549
+ if (!state.childDeclared)
550
+ problems.push("problem.child_declare");
551
+ }
552
+ let result;
553
+ let input;
554
+ let checked;
555
+ if (f) {
556
+ input = readForm(f.form, data);
557
+ result = validate(f.form, input, f.context);
558
+ if (result.ok) {
559
+ checked = await checkFiles(f.form, result);
560
+ if (!checked.ok)
561
+ result = { ...result, ok: false, problems: [...result.problems, ...checked.problems] };
562
+ }
563
+ if (!result.ok)
564
+ problems.push("problem.questions");
565
+ }
566
+ if (!state.consentRead)
567
+ problems.push("problem.consent_read");
568
+ if (!state.consentEsign)
569
+ problems.push("problem.consent_esign");
570
+ if (name.length < 2 || name.length > 120)
571
+ problems.push("problem.name");
572
+ if (!config.methods.includes(chosen))
573
+ problems.push("problem.method");
574
+ let png;
575
+ if (chosen === "drawn" && config.methods.includes("drawn")) {
576
+ const dr = readDrawnSignature(str("signature"));
577
+ if ("problem" in dr)
578
+ problems.push("problem.drawn");
579
+ else
580
+ png = dr.png;
581
+ }
582
+ if (problems.length) {
583
+ return kit.html(400, renderOpenSigningPage(view, config.methods, { ...o, ...state, forChild: d.for_child, problems, ...(f ? { questions: questions(result, input) } : {}), multipart }), true, false);
584
+ }
585
+ // Store the uploads and the drawn signature, then sign under the row lock.
586
+ const stored = [];
587
+ const files = [];
588
+ for (const c of checked?.files ?? []) {
589
+ const k = `documents/${s.id}/files/${c.field}${c.ext}`;
590
+ await kit.store(k, c.bytes, c.contentType);
591
+ stored.push(k);
592
+ files.push({ field: c.field, name: c.name, kind: c.kind, size: c.bytes.length, sha256: await sha256Hex(c.bytes), key: k });
593
+ }
594
+ let signatureKey = null;
595
+ if (png) {
596
+ signatureKey = `documents/${s.id}/signature.png`;
597
+ await kit.store(signatureKey, png, "image/png");
598
+ stored.push(signatureKey);
599
+ }
600
+ const answers = {};
601
+ const sensitive = {};
602
+ if (f && result) {
603
+ const secret = new Set(sensitiveFields(f.form));
604
+ for (const [k, v] of Object.entries(result.values)) {
605
+ if (f.form.fields[k].kind === "file")
606
+ continue;
607
+ (secret.has(k) ? sensitive : answers)[k] = v;
608
+ }
609
+ }
610
+ const hasSensitive = Object.keys(sensitive).length > 0;
611
+ const answersSha = await sha256Hex(JSON.stringify({ answers, sensitive: hasSensitive ? sensitive : null, files: files.map((x) => ({ field: x.field, name: x.name, sha256: x.sha256 })) }));
612
+ const signedAt = now();
613
+ const validUntil = d.validity_months ? addMonths(signedAt, d.validity_months).toISOString() : null;
614
+ const consent = [word(d.language, "consent.read"), word(d.language, "open.consent_esign"), ...(forChild ? [word(d.language, "child.declare")] : [])].join(" ").slice(0, 2000);
615
+ const r = await call("documents_sign", {
616
+ p: {
617
+ id: s.id,
618
+ at: signedAt.toISOString(),
619
+ name,
620
+ for_child: forChild,
621
+ child_name: forChild ? childName : null,
622
+ relationship: forChild ? relationship : null,
623
+ answers,
624
+ sensitive: hasSensitive ? sensitive : null,
625
+ files,
626
+ answers_sha256: answersSha,
627
+ method: chosen,
628
+ typed_name: name,
629
+ signature_key: signatureKey,
630
+ consent,
631
+ ip,
632
+ ua,
633
+ valid_until: validUntil,
634
+ require_verified: config.identity === "email_code",
635
+ started_after: new Date(signedAt.getTime() - SESSION_MS).toISOString(),
636
+ },
637
+ }, "signing");
638
+ if (!r.ok) {
639
+ await kit.remove(stored).catch(() => { });
640
+ const reason = r.reason === "used" ? "used" : r.reason === "retired" ? "retired" : r.reason === "stale" ? "stale" : null;
641
+ return reason ? kit.html(410, renderEndedPage(reason, { ...o, title: d.title }), false, false) : kit.redirect(self);
642
+ }
643
+ // The signed copy, with request-link validity for one event.
644
+ try {
645
+ if (await finish(s.id))
646
+ ctx.waitUntil(sendCopy(s.id).catch((e) => console.error("workbench-agreements: the signed copy wasn't sent; tick() will try again", e)));
647
+ }
648
+ catch (e) {
649
+ console.error("workbench-agreements: the signed copy wasn't made; tick() will try again", e);
650
+ }
651
+ return kit.redirect(self);
652
+ }
653
+ async function sendCode(id, email, d, at, ip, ua) {
654
+ const code = newCode();
655
+ const r = await call("documents_code_sent", { p_signature: id, p_code_hash: await codeHash(id, code), p_at: at.toISOString(), p_expires: new Date(at.getTime() + CODE_MS).toISOString(), p_ip: ip, p_ua: ua }, "keeping the code");
656
+ if (!r.ok)
657
+ return false;
658
+ await kit.mailer.send({ to: email, subject: word(d.language, "email.open_code.subject", { title: d.title }), text: word(d.language, "email.code.text", { code }), template: "agreement.code" });
659
+ return true;
660
+ }
661
+ async function tick() {
662
+ const out = { finished: 0, copies: 0, renewed: 0, failed: 0 };
663
+ const at = now();
664
+ const renewDays = config.renew_days_before ?? 14;
665
+ const scan = await call("documents_scan", { p_at: at.toISOString(), p_renew_by: new Date(at.getTime() + renewDays * DAY_MS).toISOString(), p_limit: 100 }, "scanning signatures");
666
+ const attempt = async (what, fn) => {
667
+ try {
668
+ return await fn();
669
+ }
670
+ catch (e) {
671
+ out.failed++;
672
+ console.error(`workbench-agreements: ${what} failed`, e);
673
+ return false;
674
+ }
675
+ };
676
+ for (const id of scan.finish) {
677
+ if (await attempt(`making ${id}'s signed copy`, () => finish(id))) {
678
+ out.finished++;
679
+ if (await attempt(`sending ${id}'s copy`, () => sendCopy(id)))
680
+ out.copies++;
681
+ }
682
+ }
683
+ for (const id of scan.copies)
684
+ if (await attempt(`sending ${id}'s copy`, () => sendCopy(id)))
685
+ out.copies++;
686
+ if (renewDays > 0) {
687
+ for (const id of scan.renew) {
688
+ const ok = await attempt(`reminding ${id} to sign again`, async () => {
689
+ const r = await full(id);
690
+ if (!r || !r.signature.valid_until)
691
+ return false;
692
+ const { signature: s, document: d } = r;
693
+ const current = await call("documents_current", { p_slug: d.slug }, "reading the document");
694
+ if (!current)
695
+ return call("documents_renewal_sent", { p_id: id, p_at: now().toISOString() }, "recording the reminder");
696
+ const params = { name: s.name, title: current.title, business: current.business, date: kit.dateLabel(s.valid_until), url: publicLink(current.slug), child: s.for_child ? ` (${s.child_name})` : "" };
697
+ await kit.mailer.send({
698
+ to: s.email,
699
+ subject: word(current.language, "email.renew.subject", params),
700
+ text: word(current.language, "email.renew.text", params),
701
+ template: "agreement.renew",
702
+ ...(kit.replyTo ? { replyTo: kit.replyTo } : {}),
703
+ idempotencyKey: `document-renew-${id}`,
704
+ });
705
+ return call("documents_renewal_sent", { p_id: id, p_at: now().toISOString() }, "recording the reminder");
706
+ });
707
+ if (ok)
708
+ out.renewed++;
709
+ }
710
+ }
711
+ return out;
712
+ }
713
+ async function cleanup() {
714
+ const t = now();
715
+ const signedBefore = new Date(t);
716
+ signedBefore.setUTCFullYear(signedBefore.getUTCFullYear() - config.retention.signed_years);
717
+ const sensitiveBefore = new Date(t.getTime() - (config.retention.sensitive_days_after ?? 30) * DAY_MS);
718
+ const old = await call("documents_old", { p_signed_before: signedBefore.toISOString(), p_sensitive_before: sensitiveBefore.toISOString(), p_pending_before: new Date(t.getTime() - 2 * DAY_MS).toISOString(), p_at: t.toISOString(), p_limit: 200 }, "finding old signatures");
719
+ const keys = [...old.delete, ...old.scrub, ...old.documents].flatMap((o) => o.keys);
720
+ await kit.remove(keys);
721
+ const scrubbed = old.scrub.length ? await call("documents_scrub", { p_ids: old.scrub.map((o) => o.id), p_at: t.toISOString() }, "deleting sensitive answers") : 0;
722
+ const deleted = await call("documents_delete", { p_signatures: old.delete.map((o) => o.id), p_documents: old.documents.map((o) => o.id), p_requests_before: new Date(t.getTime() - config.retention.unsigned_days * DAY_MS).toISOString() }, "deleting old signatures");
723
+ return { deleted, scrubbed };
724
+ }
725
+ return { api, handle, tick, cleanup };
726
+ }