@mccaskie-labs/workbench-agreements 0.0.0-stage → 0.1.0
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.
- package/CHANGELOG.md +5 -0
- package/README.md +38 -2
- package/dist/agreements.d.ts +197 -0
- package/dist/agreements.js +614 -0
- package/dist/certificate.d.ts +40 -0
- package/dist/certificate.js +194 -0
- package/dist/cli.d.ts +10 -0
- package/dist/cli.js +119 -0
- package/dist/config.d.ts +42 -0
- package/dist/config.js +81 -0
- package/dist/errors.d.ts +8 -0
- package/dist/errors.js +9 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.js +13 -0
- package/dist/migration.d.ts +4 -0
- package/dist/migration.js +493 -0
- package/dist/page.d.ts +46 -0
- package/dist/page.js +118 -0
- package/dist/script.d.ts +3 -0
- package/dist/script.js +31 -0
- package/dist/secrets.d.ts +7 -0
- package/dist/secrets.js +26 -0
- package/dist/signature.d.ts +9 -0
- package/dist/signature.js +35 -0
- package/dist/styles.d.ts +33 -0
- package/dist/styles.js +68 -0
- package/dist/words.d.ts +73 -0
- package/dist/words.js +162 -0
- package/package.json +51 -4
|
@@ -0,0 +1,614 @@
|
|
|
1
|
+
// createAgreements: agreements over the app's own database
|
|
2
|
+
// (agreementsMigration), R2 bucket and the Worker route that serves the
|
|
3
|
+
// signing pages. Give it the service client: the route reads and writes for
|
|
4
|
+
// anyone holding a signing link, so RLS can't be the limit there. The app's
|
|
5
|
+
// own pages check the signed-in owner's account before get(), list(), void()
|
|
6
|
+
// or the downloads.
|
|
7
|
+
import { AGREEMENT_LANGUAGES, checkAgreementsConfig, MAX_SIGNERS, SIGNING_METHODS } from "./config.js";
|
|
8
|
+
import { buildSignedCopy, pdfPages } from "./certificate.js";
|
|
9
|
+
import { AgreementsError } from "./errors.js";
|
|
10
|
+
import { renderCodePage, renderDonePage, renderEndedPage, renderSigningPage } from "./page.js";
|
|
11
|
+
import { signScriptHash } from "./script.js";
|
|
12
|
+
import { codeHash, isToken, newCode, newToken, sha256Hex } from "./secrets.js";
|
|
13
|
+
import { readDrawnSignature } from "./signature.js";
|
|
14
|
+
import { agreementWord } from "./words.js";
|
|
15
|
+
const DAY_MS = 86_400_000;
|
|
16
|
+
const CODE_MS = 10 * 60_000;
|
|
17
|
+
const MAX_DOCUMENT_BYTES = 10 * 1024 * 1024;
|
|
18
|
+
const MAX_FORM_BYTES = 300_000;
|
|
19
|
+
const LOCAL = /^http:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/;
|
|
20
|
+
const EMAIL = /^[^@\s]+@[^@\s]+\.[^@\s]+$/;
|
|
21
|
+
const fail = (what, error) => {
|
|
22
|
+
throw new AgreementsError("database", `${what}: ${error?.message ?? "unknown error"}`, { cause: error });
|
|
23
|
+
};
|
|
24
|
+
const text = (v, min, max) => typeof v === "string" && v.trim().length >= min && v.trim().length <= max;
|
|
25
|
+
const slug = (s) => s
|
|
26
|
+
.normalize("NFKD")
|
|
27
|
+
.replace(/[̀-ͯ]/g, "")
|
|
28
|
+
.toLowerCase()
|
|
29
|
+
.replace(/[^a-z0-9]+/g, "-")
|
|
30
|
+
.replace(/^-+|-+$/g, "")
|
|
31
|
+
.slice(0, 60) || "agreement";
|
|
32
|
+
const iso = (s) => (s ? new Date(s).toISOString() : null);
|
|
33
|
+
function toAgreement(r) {
|
|
34
|
+
return {
|
|
35
|
+
id: r.id,
|
|
36
|
+
account: r.account,
|
|
37
|
+
subject: r.subject_type && r.subject_id ? { type: r.subject_type, id: r.subject_id } : null,
|
|
38
|
+
title: r.title,
|
|
39
|
+
business: r.business,
|
|
40
|
+
language: r.language,
|
|
41
|
+
status: r.status,
|
|
42
|
+
documentSha256: r.document_sha256,
|
|
43
|
+
signedSha256: r.signed_sha256,
|
|
44
|
+
pages: r.pages,
|
|
45
|
+
copyTo: r.copy_to ?? [],
|
|
46
|
+
createdAt: iso(r.created_at),
|
|
47
|
+
expiresAt: iso(r.expires_at),
|
|
48
|
+
completedAt: iso(r.completed_at),
|
|
49
|
+
copiesSentAt: iso(r.copies_sent_at),
|
|
50
|
+
endedAt: iso(r.ended_at),
|
|
51
|
+
endReason: r.end_reason,
|
|
52
|
+
signers: r.signers.map((s) => ({
|
|
53
|
+
id: s.id,
|
|
54
|
+
position: s.position,
|
|
55
|
+
name: s.name,
|
|
56
|
+
email: s.email,
|
|
57
|
+
role: s.role,
|
|
58
|
+
status: s.status,
|
|
59
|
+
invitedAt: iso(s.invited_at),
|
|
60
|
+
verifiedAt: iso(s.verified_at),
|
|
61
|
+
signedAt: iso(s.signed_at),
|
|
62
|
+
method: s.method,
|
|
63
|
+
typedName: s.typed_name,
|
|
64
|
+
declinedAt: iso(s.declined_at),
|
|
65
|
+
declineReason: s.decline_reason,
|
|
66
|
+
})),
|
|
67
|
+
...(r.events
|
|
68
|
+
? { events: r.events.map((e) => ({ kind: e.kind, at: iso(e.at), signerId: e.signer_id, ip: e.ip, userAgent: e.user_agent, detail: e.detail })) }
|
|
69
|
+
: {}),
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
const PAGE_CSP = (script) => `default-src 'none'; img-src 'self' data:; style-src 'self' https:; script-src ${script}; connect-src 'none'; base-uri 'none'; form-action 'self'; frame-ancestors 'none'`;
|
|
73
|
+
export function createAgreements(opts) {
|
|
74
|
+
const config = checkAgreementsConfig(opts.config, "createAgreements({ config })");
|
|
75
|
+
const now = opts.now ?? (() => new Date());
|
|
76
|
+
const base = opts.baseUrl.replace(/\/+$/, "");
|
|
77
|
+
if (!/^https:\/\/[a-z0-9.-]+(:\d+)?$/i.test(base) && !LOCAL.test(base))
|
|
78
|
+
throw new AgreementsError("invalid_config", "baseUrl must be the project's https address with no path, such as https://example.app");
|
|
79
|
+
const { db, files, mailer } = opts;
|
|
80
|
+
const locale = opts.locale ?? "en-AU";
|
|
81
|
+
const pathRe = new RegExp(`^/${config.path}/([A-Za-z0-9_-]+)(?:/(document|signed)\\.pdf)?/?$`);
|
|
82
|
+
const linkFor = (token) => `${base}/${config.path}/${token}`;
|
|
83
|
+
async function call(fn, args, what) {
|
|
84
|
+
const { data, error } = await db.rpc(fn, args);
|
|
85
|
+
if (error)
|
|
86
|
+
fail(what, error);
|
|
87
|
+
return data;
|
|
88
|
+
}
|
|
89
|
+
const dateLabel = (isoTime) => new Intl.DateTimeFormat(locale, { dateStyle: "medium", timeStyle: "short", timeZone: config.time_zone }).format(new Date(isoTime));
|
|
90
|
+
const word = (language, key, params) => agreementWord(opts.t, language, key, params);
|
|
91
|
+
async function load(key) {
|
|
92
|
+
const obj = await files.get(key).catch((e) => {
|
|
93
|
+
throw new AgreementsError("storage", `reading ${key}: ${e.message}`, { cause: e });
|
|
94
|
+
});
|
|
95
|
+
if (!obj)
|
|
96
|
+
throw new AgreementsError("storage", `${key} is missing from the file store`);
|
|
97
|
+
return new Uint8Array(await obj.arrayBuffer());
|
|
98
|
+
}
|
|
99
|
+
async function store(key, bytes, contentType) {
|
|
100
|
+
try {
|
|
101
|
+
await files.put(key, bytes, { httpMetadata: { contentType } });
|
|
102
|
+
}
|
|
103
|
+
catch (e) {
|
|
104
|
+
throw new AgreementsError("storage", `saving ${key}: ${e.message}`, { cause: e });
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
async function raw(id) {
|
|
108
|
+
if (!/^[0-9a-f-]{36}$/i.test(id))
|
|
109
|
+
return null;
|
|
110
|
+
return (await call("agreements_get", { p_id: id }, "reading the agreement")) ?? null;
|
|
111
|
+
}
|
|
112
|
+
async function tokens(id) {
|
|
113
|
+
const rows = await call("agreements_tokens", { p_id: id }, "reading the signing links");
|
|
114
|
+
return new Map((rows ?? []).map((r) => [r.signer_id, r.token]));
|
|
115
|
+
}
|
|
116
|
+
async function emailSigner(a, s, token, kind) {
|
|
117
|
+
const params = { name: s.name, business: a.business, title: a.title, date: dateLabel(a.expires_at), url: linkFor(token) };
|
|
118
|
+
await mailer.send({
|
|
119
|
+
to: s.email,
|
|
120
|
+
subject: word(a.language, `email.${kind}.subject`, params),
|
|
121
|
+
text: word(a.language, `email.${kind}.text`, params),
|
|
122
|
+
template: `agreement.${kind}`,
|
|
123
|
+
...(opts.replyTo ? { replyTo: opts.replyTo } : {}),
|
|
124
|
+
idempotencyKey: `agreement-${kind}-${s.id}-${kind === "invite" ? "1" : String(now().toISOString().slice(0, 10))}`,
|
|
125
|
+
});
|
|
126
|
+
await call("agreements_invited", { p_signer: s.id, p_at: now().toISOString(), p_kind: kind === "invite" ? "invited" : "reminded" }, "recording the email");
|
|
127
|
+
}
|
|
128
|
+
function eventText(a, e) {
|
|
129
|
+
const s = a.signers.find((x) => x.id === e.signer_id);
|
|
130
|
+
const who = s ? `${s.name} (${s.email})` : "";
|
|
131
|
+
const from = e.ip ? ` from ${e.ip}` : "";
|
|
132
|
+
switch (e.kind) {
|
|
133
|
+
case "created":
|
|
134
|
+
return `${a.business} sent the agreement to be signed (SHA-256 ${a.document_sha256.slice(0, 16)}…)`;
|
|
135
|
+
case "invited":
|
|
136
|
+
return `Signing link emailed to ${who}`;
|
|
137
|
+
case "reminded":
|
|
138
|
+
return `Reminder emailed to ${who}`;
|
|
139
|
+
case "opened":
|
|
140
|
+
return `${who} opened the signing page${from}`;
|
|
141
|
+
case "code_sent":
|
|
142
|
+
return `One-time code emailed to ${who}`;
|
|
143
|
+
case "code_failed":
|
|
144
|
+
return `${who} entered a wrong code${from}`;
|
|
145
|
+
case "verified":
|
|
146
|
+
return `${who} entered the emailed code${from}`;
|
|
147
|
+
case "document_viewed":
|
|
148
|
+
return `${who} opened the agreement's PDF${from}`;
|
|
149
|
+
case "signed":
|
|
150
|
+
return `${who} signed (${e.detail?.method === "drawn" ? "drew their signature" : "typed their name"})${from}`;
|
|
151
|
+
default:
|
|
152
|
+
return null;
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
async function finish(id) {
|
|
156
|
+
const a = await raw(id);
|
|
157
|
+
if (!a || a.status !== "out" || a.signers.some((s) => s.status !== "signed"))
|
|
158
|
+
return false;
|
|
159
|
+
const document = await load(a.document_key);
|
|
160
|
+
const completedAt = now().toISOString();
|
|
161
|
+
const signers = await Promise.all(a.signers.map(async (s) => ({
|
|
162
|
+
name: s.name,
|
|
163
|
+
email: s.email,
|
|
164
|
+
role: s.role,
|
|
165
|
+
method: s.method,
|
|
166
|
+
typedName: s.typed_name,
|
|
167
|
+
signedAt: s.signed_at,
|
|
168
|
+
identity: a.identity,
|
|
169
|
+
ip: s.sign_ip,
|
|
170
|
+
userAgent: s.sign_user_agent,
|
|
171
|
+
signature: s.signature_key ? await load(s.signature_key) : null,
|
|
172
|
+
})));
|
|
173
|
+
const all = (a.events ?? []).map((e) => ({ at: e.at, what: eventText(a, e) })).filter((e) => e.what !== null);
|
|
174
|
+
const events = all.length > 300 ? [...all.slice(0, 299), { at: all[all.length - 1].at, what: `… and ${all.length - 299} more events, kept in the app's database` }] : all;
|
|
175
|
+
events.push({ at: completedAt, what: "Everyone has signed: agreement complete" });
|
|
176
|
+
const signed = await buildSignedCopy({ document, id: a.id, title: a.title, business: a.business, createdAt: a.created_at, completedAt, documentSha256: a.document_sha256, signers, events, timeZone: config.time_zone, locale });
|
|
177
|
+
const sha = await sha256Hex(signed);
|
|
178
|
+
const key = `agreements/${a.id}/signed.pdf`;
|
|
179
|
+
await store(key, signed, "application/pdf");
|
|
180
|
+
return call("agreements_complete", { p_id: a.id, p_signed_key: key, p_signed_sha256: sha, p_at: completedAt }, "completing the agreement");
|
|
181
|
+
}
|
|
182
|
+
async function sendCopies(id) {
|
|
183
|
+
const a = await raw(id);
|
|
184
|
+
if (!a || a.status !== "completed" || a.copies_sent_at || !a.signed_key)
|
|
185
|
+
return false;
|
|
186
|
+
const bytes = await load(a.signed_key);
|
|
187
|
+
const to = [...new Set([...a.signers.map((s) => s.email), ...(a.copy_to ?? [])].map((e) => e.toLowerCase()))];
|
|
188
|
+
const params = { title: a.title, id: a.id, sha256: a.signed_sha256 };
|
|
189
|
+
await mailer.send({
|
|
190
|
+
to,
|
|
191
|
+
subject: word(a.language, "email.signed.subject", params),
|
|
192
|
+
text: word(a.language, "email.signed.text", params),
|
|
193
|
+
template: "agreement.signed",
|
|
194
|
+
...(opts.replyTo ? { replyTo: opts.replyTo } : {}),
|
|
195
|
+
attachments: [{ filename: `${slug(a.title)}-signed.pdf`, mimeType: "application/pdf", bytes }],
|
|
196
|
+
idempotencyKey: `agreement-signed-${a.id}`,
|
|
197
|
+
});
|
|
198
|
+
await call("agreements_copies_sent", { p_id: a.id, p_at: now().toISOString(), p_count: to.length }, "recording the copies");
|
|
199
|
+
return true;
|
|
200
|
+
}
|
|
201
|
+
async function notifyDeclined(id, signerId) {
|
|
202
|
+
const a = await raw(id);
|
|
203
|
+
const s = a?.signers.find((x) => x.id === signerId);
|
|
204
|
+
if (!a || !s || !a.copy_to?.length)
|
|
205
|
+
return;
|
|
206
|
+
const reason = s.decline_reason ? ` They said: "${s.decline_reason}"` : "";
|
|
207
|
+
await mailer.send({
|
|
208
|
+
to: a.copy_to,
|
|
209
|
+
subject: word("en", "email.declined.subject", { title: a.title }),
|
|
210
|
+
text: word("en", "email.declined.text", { name: s.name, title: a.title, reason }),
|
|
211
|
+
template: "agreement.declined",
|
|
212
|
+
idempotencyKey: `agreement-declined-${a.id}`,
|
|
213
|
+
});
|
|
214
|
+
}
|
|
215
|
+
// ---- the route ----
|
|
216
|
+
const device = (request) => config.record_device ? { ip: request.headers.get("cf-connecting-ip")?.slice(0, 64) ?? null, ua: request.headers.get("user-agent")?.slice(0, 400) ?? null } : { ip: null, ua: null };
|
|
217
|
+
async function html(status, body, script, head) {
|
|
218
|
+
return new Response(head ? null : body, {
|
|
219
|
+
status,
|
|
220
|
+
headers: {
|
|
221
|
+
"content-type": "text/html; charset=utf-8",
|
|
222
|
+
"cache-control": "no-store",
|
|
223
|
+
"x-robots-tag": "noindex, nofollow",
|
|
224
|
+
"referrer-policy": "no-referrer",
|
|
225
|
+
"x-content-type-options": "nosniff",
|
|
226
|
+
"content-security-policy": PAGE_CSP(script ? await signScriptHash() : "'none'"),
|
|
227
|
+
},
|
|
228
|
+
});
|
|
229
|
+
}
|
|
230
|
+
const redirect = (to) => new Response(null, { status: 303, headers: { location: to, "cache-control": "no-store", "referrer-policy": "no-referrer" } });
|
|
231
|
+
const bare = (status, extra = {}) => new Response(null, { status, headers: { "cache-control": "no-store", ...extra } });
|
|
232
|
+
const pdf = (bytes, name, head) => new Response(head ? null : bytes, {
|
|
233
|
+
headers: {
|
|
234
|
+
"content-type": "application/pdf",
|
|
235
|
+
"content-disposition": `inline; filename="${name}"`,
|
|
236
|
+
"cache-control": "private, no-store",
|
|
237
|
+
"x-robots-tag": "noindex, nofollow",
|
|
238
|
+
"referrer-policy": "no-referrer",
|
|
239
|
+
"x-content-type-options": "nosniff",
|
|
240
|
+
"content-security-policy": "default-src 'none'; frame-ancestors 'self'",
|
|
241
|
+
},
|
|
242
|
+
});
|
|
243
|
+
return {
|
|
244
|
+
async create(req) {
|
|
245
|
+
if (!text(req.account, 1, 200))
|
|
246
|
+
throw new AgreementsError("invalid_request", "account must be 1 to 200 characters");
|
|
247
|
+
if (!text(req.title, 1, 200))
|
|
248
|
+
throw new AgreementsError("invalid_request", "title must be 1 to 200 characters");
|
|
249
|
+
if (!text(req.business, 1, 200))
|
|
250
|
+
throw new AgreementsError("invalid_request", "business must be 1 to 200 characters");
|
|
251
|
+
if (!(req.document instanceof Uint8Array) || req.document.length > MAX_DOCUMENT_BYTES)
|
|
252
|
+
throw new AgreementsError("invalid_request", "document must be the PDF's bytes, up to 10 MB");
|
|
253
|
+
const signers = req.signers;
|
|
254
|
+
if (!Array.isArray(signers) || signers.length < 1 || signers.length > MAX_SIGNERS)
|
|
255
|
+
throw new AgreementsError("invalid_request", `signers must list 1 to ${MAX_SIGNERS} people`);
|
|
256
|
+
const seen = new Set();
|
|
257
|
+
for (const [i, s] of signers.entries()) {
|
|
258
|
+
if (!text(s?.name, 1, 120))
|
|
259
|
+
throw new AgreementsError("invalid_request", `signers[${i}].name must be 1 to 120 characters`);
|
|
260
|
+
if (typeof s.email !== "string" || s.email.length > 254 || !EMAIL.test(s.email.trim()))
|
|
261
|
+
throw new AgreementsError("invalid_request", `signers[${i}].email isn't an email address`);
|
|
262
|
+
if (s.role !== undefined && !text(s.role, 1, 60))
|
|
263
|
+
throw new AgreementsError("invalid_request", `signers[${i}].role must be 1 to 60 characters`);
|
|
264
|
+
const e = s.email.trim().toLowerCase();
|
|
265
|
+
if (seen.has(e))
|
|
266
|
+
throw new AgreementsError("invalid_request", `signers[${i}].email is listed twice: each person signs once`);
|
|
267
|
+
seen.add(e);
|
|
268
|
+
}
|
|
269
|
+
const copyTo = (req.copyTo ?? []).map((e) => e.trim());
|
|
270
|
+
if (copyTo.length > 5 || copyTo.some((e) => e.length > 254 || !EMAIL.test(e)))
|
|
271
|
+
throw new AgreementsError("invalid_request", "copyTo must list up to 5 email addresses");
|
|
272
|
+
const subject = req.subject;
|
|
273
|
+
if (subject && (!text(subject.type, 1, 60) || !text(subject.id, 1, 200)))
|
|
274
|
+
throw new AgreementsError("invalid_request", "subject must be { type, id }");
|
|
275
|
+
const language = req.language ?? config.language;
|
|
276
|
+
if (!AGREEMENT_LANGUAGES.includes(language))
|
|
277
|
+
throw new AgreementsError("invalid_request", "language must be en, tl or taglish");
|
|
278
|
+
const t = now();
|
|
279
|
+
const expires = req.expiresAt ?? new Date(t.getTime() + config.expires_after_days * DAY_MS);
|
|
280
|
+
if (!(expires.getTime() > t.getTime()))
|
|
281
|
+
throw new AgreementsError("invalid_request", "expiresAt must be in the future");
|
|
282
|
+
const pages = await pdfPages(req.document);
|
|
283
|
+
const sha = await sha256Hex(req.document);
|
|
284
|
+
const id = crypto.randomUUID();
|
|
285
|
+
const key = `agreements/${id}/document.pdf`;
|
|
286
|
+
await store(key, req.document, "application/pdf");
|
|
287
|
+
const toks = signers.map(() => newToken());
|
|
288
|
+
await call("agreements_create", {
|
|
289
|
+
p: {
|
|
290
|
+
id,
|
|
291
|
+
account: req.account.trim(),
|
|
292
|
+
subject_type: subject?.type ?? null,
|
|
293
|
+
subject_id: subject?.id ?? null,
|
|
294
|
+
title: req.title.trim(),
|
|
295
|
+
business: req.business.trim(),
|
|
296
|
+
language,
|
|
297
|
+
document_key: key,
|
|
298
|
+
document_sha256: sha,
|
|
299
|
+
pages,
|
|
300
|
+
copy_to: copyTo,
|
|
301
|
+
identity: config.identity,
|
|
302
|
+
created_at: t.toISOString(),
|
|
303
|
+
expires_at: expires.toISOString(),
|
|
304
|
+
signers: signers.map((s, i) => ({ position: i + 1, name: s.name.trim(), email: s.email.trim(), role: s.role?.trim() ?? null, token: toks[i] })),
|
|
305
|
+
},
|
|
306
|
+
}, "saving the agreement").catch(async (e) => {
|
|
307
|
+
await files.delete(key).catch(() => { });
|
|
308
|
+
throw e;
|
|
309
|
+
});
|
|
310
|
+
const a = (await raw(id));
|
|
311
|
+
const links = a.signers.map((s, i) => ({ id: s.id, name: s.name, email: s.email, url: linkFor(toks[i]) }));
|
|
312
|
+
if (req.invite !== false)
|
|
313
|
+
for (const [i, s] of a.signers.entries())
|
|
314
|
+
await emailSigner(a, s, toks[i], "invite");
|
|
315
|
+
return { id, documentSha256: sha, signers: links };
|
|
316
|
+
},
|
|
317
|
+
async invite(id) {
|
|
318
|
+
const a = await raw(id);
|
|
319
|
+
if (!a)
|
|
320
|
+
throw new AgreementsError("not_found", `no agreement ${id}`);
|
|
321
|
+
if (a.status !== "out")
|
|
322
|
+
throw new AgreementsError("conflict", `agreement ${id} is ${a.status}`);
|
|
323
|
+
const toks = await tokens(id);
|
|
324
|
+
let n = 0;
|
|
325
|
+
for (const s of a.signers) {
|
|
326
|
+
const token = toks.get(s.id);
|
|
327
|
+
if (s.status !== "waiting" || !token)
|
|
328
|
+
continue;
|
|
329
|
+
await emailSigner(a, s, token, s.invited_at ? "reminder" : "invite");
|
|
330
|
+
n++;
|
|
331
|
+
}
|
|
332
|
+
return n;
|
|
333
|
+
},
|
|
334
|
+
async share(id) {
|
|
335
|
+
const a = await raw(id);
|
|
336
|
+
if (!a)
|
|
337
|
+
throw new AgreementsError("not_found", `no agreement ${id}`);
|
|
338
|
+
if (a.status !== "out")
|
|
339
|
+
return [];
|
|
340
|
+
const toks = await tokens(id);
|
|
341
|
+
return a.signers
|
|
342
|
+
.filter((s) => toks.has(s.id))
|
|
343
|
+
.map((s) => {
|
|
344
|
+
const url = linkFor(toks.get(s.id));
|
|
345
|
+
const msg = word(a.language, "share.text", { name: s.name.split(/\s+/)[0], title: a.title, url });
|
|
346
|
+
return { id: s.id, name: s.name, email: s.email, url, text: msg, whatsapp: `https://wa.me/?text=${encodeURIComponent(msg)}` };
|
|
347
|
+
});
|
|
348
|
+
},
|
|
349
|
+
async get(id) {
|
|
350
|
+
const a = await raw(id);
|
|
351
|
+
return a ? toAgreement(a) : null;
|
|
352
|
+
},
|
|
353
|
+
async list(account, limit = 50) {
|
|
354
|
+
if (!text(account, 1, 200))
|
|
355
|
+
throw new AgreementsError("invalid_request", "account must be 1 to 200 characters");
|
|
356
|
+
const rows = await call("agreements_list", { p_account: account, p_limit: Math.min(Math.max(1, Math.floor(limit)), 200) }, "listing agreements");
|
|
357
|
+
return (rows ?? []).map(toAgreement);
|
|
358
|
+
},
|
|
359
|
+
async void(id, reason) {
|
|
360
|
+
if (!text(reason, 1, 500))
|
|
361
|
+
throw new AgreementsError("invalid_request", "reason must be 1 to 500 characters");
|
|
362
|
+
if (!/^[0-9a-f-]{36}$/i.test(id))
|
|
363
|
+
return false;
|
|
364
|
+
return call("agreements_void", { p_id: id, p_reason: reason.trim(), p_at: now().toISOString() }, "withdrawing the agreement");
|
|
365
|
+
},
|
|
366
|
+
async file(id, which) {
|
|
367
|
+
const a = await raw(id);
|
|
368
|
+
if (!a)
|
|
369
|
+
return null;
|
|
370
|
+
const key = which === "signed" ? a.signed_key : a.document_key;
|
|
371
|
+
return key ? load(key) : null;
|
|
372
|
+
},
|
|
373
|
+
async verify(bytes) {
|
|
374
|
+
const r = await call("agreements_by_hash", { p_sha256: await sha256Hex(bytes) }, "checking the PDF");
|
|
375
|
+
return r ? { id: r.id, title: r.title, status: r.status, which: r.which, completedAt: iso(r.completed_at) } : null;
|
|
376
|
+
},
|
|
377
|
+
async handle(request, ctx) {
|
|
378
|
+
const url = new URL(request.url);
|
|
379
|
+
const m = pathRe.exec(url.pathname);
|
|
380
|
+
if (!m)
|
|
381
|
+
return null;
|
|
382
|
+
const [, token, file] = m;
|
|
383
|
+
const method = request.method.toUpperCase();
|
|
384
|
+
const head = method === "HEAD";
|
|
385
|
+
const common = (language) => ({ language, ...(opts.t ? { t: opts.t } : {}), ...(opts.styles ? { styles: opts.styles } : {}) });
|
|
386
|
+
const notFound = () => html(404, renderEndedPage("not_found", common(config.language)), false, head);
|
|
387
|
+
if (method === "POST") {
|
|
388
|
+
if (file)
|
|
389
|
+
return bare(405, { allow: "GET, HEAD" });
|
|
390
|
+
const origin = request.headers.get("origin");
|
|
391
|
+
if (origin && origin !== url.origin && origin !== new URL(base).origin)
|
|
392
|
+
return bare(403);
|
|
393
|
+
}
|
|
394
|
+
else if (method !== "GET" && !head)
|
|
395
|
+
return bare(405, { allow: "GET, HEAD, POST" });
|
|
396
|
+
if (!isToken(token))
|
|
397
|
+
return notFound();
|
|
398
|
+
const opened = await call("agreements_open", { p_token: token }, "opening the agreement");
|
|
399
|
+
if (!opened)
|
|
400
|
+
return notFound();
|
|
401
|
+
const a = opened.agreement;
|
|
402
|
+
const s = a.signers.find((x) => x.id === opened.signer_id);
|
|
403
|
+
const o = common(a.language);
|
|
404
|
+
const at = now();
|
|
405
|
+
const { ip, ua } = device(request);
|
|
406
|
+
const ev = (kind, detail = null) => call("agreements_event", { p_agreement: a.id, p_signer: s.id, p_kind: kind, p_at: now().toISOString(), p_ip: ip, p_ua: ua, p_detail: detail }, "recording the event");
|
|
407
|
+
const self = `/${config.path}/${token}`;
|
|
408
|
+
const closed = a.status === "voided" || a.status === "expired" || a.status === "declined" ? a.status : a.status === "out" && Date.parse(a.expires_at) <= at.getTime() ? "expired" : null;
|
|
409
|
+
const needCode = a.identity === "email_code" && !s.verified_at;
|
|
410
|
+
const filename = (suffix) => `${slug(a.title)}${suffix}.pdf`;
|
|
411
|
+
if (file === "signed") {
|
|
412
|
+
if (a.status !== "completed" || !a.signed_key || s.status !== "signed")
|
|
413
|
+
return notFound();
|
|
414
|
+
const bytes = await load(a.signed_key);
|
|
415
|
+
if (!head)
|
|
416
|
+
ctx.waitUntil(ev("copy_downloaded").catch((e) => console.error("workbench-agreements: an event wasn't recorded", e)));
|
|
417
|
+
return pdf(bytes, filename("-signed"), head);
|
|
418
|
+
}
|
|
419
|
+
if (file === "document") {
|
|
420
|
+
if (s.status === "declined" || (s.status === "waiting" && (closed || needCode)))
|
|
421
|
+
return notFound();
|
|
422
|
+
const bytes = await load(a.document_key);
|
|
423
|
+
if (!head)
|
|
424
|
+
ctx.waitUntil(ev("document_viewed").catch((e) => console.error("workbench-agreements: an event wasn't recorded", e)));
|
|
425
|
+
return pdf(bytes, filename(""), head);
|
|
426
|
+
}
|
|
427
|
+
const view = {
|
|
428
|
+
title: a.title,
|
|
429
|
+
business: a.business,
|
|
430
|
+
signerName: s.name,
|
|
431
|
+
signerEmail: s.email,
|
|
432
|
+
others: a.signers.filter((x) => x.id !== s.id).map((x) => x.name),
|
|
433
|
+
expires: dateLabel(a.expires_at),
|
|
434
|
+
pages: a.pages,
|
|
435
|
+
documentHref: `${self}/document.pdf`,
|
|
436
|
+
};
|
|
437
|
+
const codeSent = !!s.code_expires_at && Date.parse(s.code_expires_at) > at.getTime();
|
|
438
|
+
if (method !== "POST") {
|
|
439
|
+
if (s.status === "declined")
|
|
440
|
+
return html(200, renderEndedPage("declined_by_you", { ...o, title: a.title, business: a.business }), false, head);
|
|
441
|
+
if (s.status === "signed")
|
|
442
|
+
return html(200, renderDonePage(view, { ...o, signedAt: dateLabel(s.signed_at), completed: a.status === "completed", ...(a.status === "completed" ? { downloadHref: `${self}/signed.pdf` } : {}) }), false, head);
|
|
443
|
+
if (closed)
|
|
444
|
+
return html(410, renderEndedPage(closed, { ...o, title: a.title, business: a.business }), false, head);
|
|
445
|
+
if (needCode)
|
|
446
|
+
return html(200, renderCodePage(view, { ...o, sent: codeSent }), false, head);
|
|
447
|
+
if (!head)
|
|
448
|
+
ctx.waitUntil(ev("opened").catch((e) => console.error("workbench-agreements: an event wasn't recorded", e)));
|
|
449
|
+
return html(200, renderSigningPage(view, config.methods, o), true, head);
|
|
450
|
+
}
|
|
451
|
+
// POST: one of sign, decline, send_code, check_code.
|
|
452
|
+
const body = await request.text();
|
|
453
|
+
if (body.length > MAX_FORM_BYTES)
|
|
454
|
+
return bare(413);
|
|
455
|
+
const form = new URLSearchParams(body);
|
|
456
|
+
const action = form.get("action");
|
|
457
|
+
if (s.status !== "waiting" || closed)
|
|
458
|
+
return redirect(self);
|
|
459
|
+
if (action === "send_code" || action === "check_code") {
|
|
460
|
+
if (a.identity !== "email_code" || s.verified_at)
|
|
461
|
+
return redirect(self);
|
|
462
|
+
if (action === "send_code") {
|
|
463
|
+
const code = newCode();
|
|
464
|
+
const r = await call("agreements_code_sent", { p_signer: s.id, p_code_hash: await codeHash(s.id, code), p_at: at.toISOString(), p_expires: new Date(at.getTime() + CODE_MS).toISOString(), p_ip: ip, p_ua: ua }, "keeping the code");
|
|
465
|
+
if (!r.ok)
|
|
466
|
+
return html(429, renderCodePage(view, { ...o, sent: true, problems: ["problem.code_wait"] }), false, false);
|
|
467
|
+
await mailer.send({
|
|
468
|
+
to: s.email,
|
|
469
|
+
subject: word(a.language, "email.code.subject", { title: a.title }),
|
|
470
|
+
text: word(a.language, "email.code.text", { code }),
|
|
471
|
+
template: "agreement.code",
|
|
472
|
+
});
|
|
473
|
+
return html(200, renderCodePage(view, { ...o, sent: true }), false, false);
|
|
474
|
+
}
|
|
475
|
+
const code = (form.get("code") ?? "").replace(/\s/g, "");
|
|
476
|
+
const r = /^\d{6}$/.test(code)
|
|
477
|
+
? await call("agreements_code_try", { p_signer: s.id, p_code_hash: await codeHash(s.id, code), p_at: at.toISOString(), p_ip: ip, p_ua: ua }, "checking the code")
|
|
478
|
+
: "wrong";
|
|
479
|
+
if (r === "ok")
|
|
480
|
+
return redirect(self);
|
|
481
|
+
const problem = r === "expired" || r === "none" ? "problem.code_expired" : r === "locked" ? "problem.code_locked" : "problem.code";
|
|
482
|
+
return html(400, renderCodePage(view, { ...o, sent: r === "wrong", problems: [problem] }), false, false);
|
|
483
|
+
}
|
|
484
|
+
if (action === "decline") {
|
|
485
|
+
if (needCode)
|
|
486
|
+
return redirect(self);
|
|
487
|
+
const reason = (form.get("reason") ?? "").trim().slice(0, 500);
|
|
488
|
+
const r = await call("agreements_decline", { p_signer: s.id, p_at: at.toISOString(), p_reason: reason, p_ip: ip, p_ua: ua }, "declining");
|
|
489
|
+
if (r.ok)
|
|
490
|
+
ctx.waitUntil(notifyDeclined(a.id, s.id).catch((e) => console.error("workbench-agreements: the business wasn't told of the decline", e)));
|
|
491
|
+
return redirect(self);
|
|
492
|
+
}
|
|
493
|
+
if (action !== "sign")
|
|
494
|
+
return bare(400);
|
|
495
|
+
if (needCode)
|
|
496
|
+
return redirect(self);
|
|
497
|
+
const name = (form.get("name") ?? "").trim().replace(/\s+/g, " ");
|
|
498
|
+
const chosen = (form.get("method") ?? config.methods[0]);
|
|
499
|
+
const state = { name, consentRead: form.get("consent_read") === "yes", consentEsign: form.get("consent_esign") === "yes" };
|
|
500
|
+
if (SIGNING_METHODS.includes(chosen))
|
|
501
|
+
state.method = chosen;
|
|
502
|
+
const problems = [];
|
|
503
|
+
if (!state.consentRead)
|
|
504
|
+
problems.push("problem.consent_read");
|
|
505
|
+
if (!state.consentEsign)
|
|
506
|
+
problems.push("problem.consent_esign");
|
|
507
|
+
if (name.length < 2 || name.length > 120)
|
|
508
|
+
problems.push("problem.name");
|
|
509
|
+
if (!config.methods.includes(chosen))
|
|
510
|
+
problems.push("problem.method");
|
|
511
|
+
let png;
|
|
512
|
+
if (chosen === "drawn" && config.methods.includes("drawn")) {
|
|
513
|
+
const d = readDrawnSignature(form.get("signature") ?? "");
|
|
514
|
+
if ("problem" in d)
|
|
515
|
+
problems.push("problem.drawn");
|
|
516
|
+
else
|
|
517
|
+
png = d.png;
|
|
518
|
+
}
|
|
519
|
+
if (problems.length)
|
|
520
|
+
return html(400, renderSigningPage(view, config.methods, { ...o, ...state, problems }), true, false);
|
|
521
|
+
let signatureKey = null;
|
|
522
|
+
if (png) {
|
|
523
|
+
signatureKey = `agreements/${a.id}/signatures/${s.id}.png`;
|
|
524
|
+
await store(signatureKey, png, "image/png");
|
|
525
|
+
}
|
|
526
|
+
const consent = [agreementWord(opts.t, a.language, "consent.read"), agreementWord(opts.t, a.language, "consent.esign")].join(" ").slice(0, 1000);
|
|
527
|
+
const r = await call("agreements_sign", { p_signer: s.id, p_at: now().toISOString(), p_method: chosen, p_typed_name: name, p_signature_key: signatureKey, p_consent: consent, p_ip: ip, p_ua: ua, p_require_verified: a.identity === "email_code" }, "signing");
|
|
528
|
+
if (!r.ok && signatureKey)
|
|
529
|
+
await files.delete(signatureKey).catch(() => { });
|
|
530
|
+
if (r.ok && r.all_signed) {
|
|
531
|
+
try {
|
|
532
|
+
if (await finish(a.id))
|
|
533
|
+
ctx.waitUntil(sendCopies(a.id).catch((e) => console.error("workbench-agreements: the signed copies weren't sent; tick() will try again", e)));
|
|
534
|
+
}
|
|
535
|
+
catch (e) {
|
|
536
|
+
console.error("workbench-agreements: the signed copy wasn't made; tick() will try again", e);
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
return redirect(self);
|
|
540
|
+
},
|
|
541
|
+
async tick() {
|
|
542
|
+
const out = { expired: 0, finished: 0, copies: 0, reminded: 0, failed: 0 };
|
|
543
|
+
const at = now();
|
|
544
|
+
const scan = await call("agreements_scan", { p_at: at.toISOString(), p_limit: 100 }, "scanning agreements");
|
|
545
|
+
out.expired = scan.expired.length;
|
|
546
|
+
const attempt = async (what, f) => {
|
|
547
|
+
try {
|
|
548
|
+
return await f();
|
|
549
|
+
}
|
|
550
|
+
catch (e) {
|
|
551
|
+
out.failed++;
|
|
552
|
+
console.error(`workbench-agreements: ${what} failed`, e);
|
|
553
|
+
return false;
|
|
554
|
+
}
|
|
555
|
+
};
|
|
556
|
+
for (const id of scan.finish) {
|
|
557
|
+
if (await attempt(`finishing ${id}`, () => finish(id))) {
|
|
558
|
+
out.finished++;
|
|
559
|
+
if (await attempt(`sending ${id}'s copies`, () => sendCopies(id)))
|
|
560
|
+
out.copies++;
|
|
561
|
+
}
|
|
562
|
+
}
|
|
563
|
+
for (const id of scan.copies)
|
|
564
|
+
if (await attempt(`sending ${id}'s copies`, () => sendCopies(id)))
|
|
565
|
+
out.copies++;
|
|
566
|
+
const waits = config.reminders.after_days;
|
|
567
|
+
const byAgreement = new Map();
|
|
568
|
+
for (const w of scan.waiting) {
|
|
569
|
+
const wait = waits[w.reminders];
|
|
570
|
+
if (wait === undefined)
|
|
571
|
+
continue;
|
|
572
|
+
const from = Date.parse(w.last_reminded_at ?? w.invited_at);
|
|
573
|
+
if (at.getTime() < from + wait * DAY_MS)
|
|
574
|
+
continue;
|
|
575
|
+
byAgreement.set(w.agreement_id, [...(byAgreement.get(w.agreement_id) ?? []), w]);
|
|
576
|
+
}
|
|
577
|
+
for (const [id, due] of byAgreement) {
|
|
578
|
+
await attempt(`reminding ${id}'s signers`, async () => {
|
|
579
|
+
const a = await raw(id);
|
|
580
|
+
if (!a || a.status !== "out")
|
|
581
|
+
return;
|
|
582
|
+
const toks = await tokens(id);
|
|
583
|
+
for (const w of due) {
|
|
584
|
+
const s = a.signers.find((x) => x.id === w.signer_id);
|
|
585
|
+
const token = toks.get(w.signer_id);
|
|
586
|
+
if (!s || !token || s.status !== "waiting")
|
|
587
|
+
continue;
|
|
588
|
+
await emailSigner(a, s, token, "reminder");
|
|
589
|
+
out.reminded++;
|
|
590
|
+
}
|
|
591
|
+
});
|
|
592
|
+
}
|
|
593
|
+
return out;
|
|
594
|
+
},
|
|
595
|
+
async cleanup() {
|
|
596
|
+
const t = now();
|
|
597
|
+
const signedBefore = new Date(t);
|
|
598
|
+
signedBefore.setUTCFullYear(signedBefore.getUTCFullYear() - config.retention.signed_years);
|
|
599
|
+
const old = await call("agreements_old", { p_signed_before: signedBefore.toISOString(), p_unsigned_before: new Date(t.getTime() - config.retention.unsigned_days * DAY_MS).toISOString(), p_limit: 200 }, "finding old agreements");
|
|
600
|
+
if (!old?.length)
|
|
601
|
+
return { deleted: 0 };
|
|
602
|
+
const keys = old.flatMap((o) => o.keys);
|
|
603
|
+
try {
|
|
604
|
+
for (let i = 0; i < keys.length; i += 1000)
|
|
605
|
+
await files.delete(keys.slice(i, i + 1000));
|
|
606
|
+
}
|
|
607
|
+
catch (e) {
|
|
608
|
+
throw new AgreementsError("storage", `deleting old agreements' files: ${e.message}`, { cause: e });
|
|
609
|
+
}
|
|
610
|
+
const deleted = await call("agreements_delete", { p_ids: old.map((o) => o.id) }, "deleting old agreements");
|
|
611
|
+
return { deleted };
|
|
612
|
+
},
|
|
613
|
+
};
|
|
614
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { type PDFFont } from "pdf-lib";
|
|
2
|
+
import type { IdentityCheck, SigningMethod } from "./config.ts";
|
|
3
|
+
export interface CertificateSigner {
|
|
4
|
+
name: string;
|
|
5
|
+
email: string;
|
|
6
|
+
role?: string | null;
|
|
7
|
+
method: SigningMethod;
|
|
8
|
+
typedName: string;
|
|
9
|
+
signedAt: string;
|
|
10
|
+
identity: IdentityCheck;
|
|
11
|
+
ip?: string | null;
|
|
12
|
+
userAgent?: string | null;
|
|
13
|
+
/** The drawn signature's PNG. */
|
|
14
|
+
signature?: Uint8Array | null;
|
|
15
|
+
}
|
|
16
|
+
export interface CertificateEvent {
|
|
17
|
+
at: string;
|
|
18
|
+
what: string;
|
|
19
|
+
}
|
|
20
|
+
export interface CertificateInput {
|
|
21
|
+
document: Uint8Array;
|
|
22
|
+
id: string;
|
|
23
|
+
title: string;
|
|
24
|
+
business: string;
|
|
25
|
+
createdAt: string;
|
|
26
|
+
completedAt: string;
|
|
27
|
+
documentSha256: string;
|
|
28
|
+
signers: readonly CertificateSigner[];
|
|
29
|
+
events: readonly CertificateEvent[];
|
|
30
|
+
timeZone: string;
|
|
31
|
+
locale?: string;
|
|
32
|
+
}
|
|
33
|
+
/** The page count, refusing a file pdf-lib can't open or one that is encrypted (a signed copy couldn't be made from it). */
|
|
34
|
+
export declare function pdfPages(bytes: Uint8Array): Promise<number>;
|
|
35
|
+
/** Text a standard font can draw: each character it can't becomes its plain letter, or "?". */
|
|
36
|
+
export declare function winAnsi(font: PDFFont, s: string): string;
|
|
37
|
+
/** "23 Nov 2026, 9:05:12 pm AEDT (10:05:12 UTC)". */
|
|
38
|
+
export declare function bothTimes(iso: string, timeZone: string, locale?: string): string;
|
|
39
|
+
/** The signed copy's bytes. */
|
|
40
|
+
export declare function buildSignedCopy(c: CertificateInput): Promise<Uint8Array>;
|