@mccaskie-labs/workbench-agreements 0.0.0-stage → 0.1.1

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,493 @@
1
+ // The app's own agreement tables, copied into the project's
2
+ // supabase/migrations as one file and its down file
3
+ // (`npx workbench-agreements migration`).
4
+ //
5
+ // Only the service role reaches them: the signing route, the app's own pages
6
+ // (behind its sign-in, checking the account themselves) and the cron all run
7
+ // server side. So the tables have RLS on with no policies, and the functions
8
+ // are granted to service_role only.
9
+ //
10
+ // - An agreement holds the PDF's key in the app's R2 bucket and its SHA-256,
11
+ // never the PDF itself. A signed copy's key and SHA-256 are added when the
12
+ // last signer signs.
13
+ // - A signer's token is their private link. It is kept as given, because the
14
+ // reminder emails send the same link again; only the service role reads it.
15
+ // - An email code is kept only as a hash, for 10 minutes and 5 tries.
16
+ // - agreement_events is the audit trail: one row per thing that happened,
17
+ // with the time, and the IP address and browser when the project keeps
18
+ // them (record_device). Rows are only ever added, never changed.
19
+ // - Signing locks the agreement's row, so two last signers at once can't both
20
+ // finish it, and one signing just as it expires is refused.
21
+ //
22
+ // It creates functions, so Control asks for approval to apply it even on
23
+ // staging. The down file drops everything the up file made.
24
+ const FUNCTIONS = [
25
+ ["agreements_create", "jsonb"],
26
+ ["agreements_get", "uuid"],
27
+ ["agreements_open", "text"],
28
+ ["agreements_tokens", "uuid"],
29
+ ["agreements_event", "uuid, uuid, text, timestamptz, text, text, jsonb"],
30
+ ["agreements_sign", "uuid, timestamptz, text, text, text, text, text, text, boolean"],
31
+ ["agreements_decline", "uuid, timestamptz, text, text, text"],
32
+ ["agreements_void", "uuid, text, timestamptz"],
33
+ ["agreements_complete", "uuid, text, text, timestamptz"],
34
+ ["agreements_copies_sent", "uuid, timestamptz, integer"],
35
+ ["agreements_code_sent", "uuid, text, timestamptz, timestamptz, text, text"],
36
+ ["agreements_code_try", "uuid, text, timestamptz, text, text"],
37
+ ["agreements_invited", "uuid, timestamptz, text"],
38
+ ["agreements_scan", "timestamptz, integer"],
39
+ ["agreements_list", "text, integer"],
40
+ ["agreements_by_hash", "text"],
41
+ ["agreements_old", "timestamptz, timestamptz, integer"],
42
+ ["agreements_delete", "uuid[]"],
43
+ ];
44
+ const grants = FUNCTIONS.map(([f, args]) => `revoke execute on function public.${f}(${args}) from public, anon, authenticated;\ngrant execute on function public.${f}(${args}) to service_role;`).join("\n");
45
+ const drops = [...FUNCTIONS].reverse().map(([f, args]) => `drop function public.${f}(${args});`).join("\n");
46
+ export const agreementsMigration = {
47
+ up: `create table public.agreements (
48
+ id uuid primary key,
49
+ account text not null check (char_length(account) between 1 and 200),
50
+ subject_type text check (char_length(subject_type) between 1 and 60),
51
+ subject_id text check (char_length(subject_id) between 1 and 200),
52
+ title text not null check (char_length(title) between 1 and 200),
53
+ business text not null check (char_length(business) between 1 and 200),
54
+ language text not null default 'en' check (language in ('en', 'tl', 'taglish')),
55
+ status text not null default 'out' check (status in ('out', 'completed', 'declined', 'voided', 'expired')),
56
+ document_key text not null check (char_length(document_key) between 1 and 300),
57
+ document_sha256 text not null check (document_sha256 ~ '^[0-9a-f]{64}$'),
58
+ pages integer not null check (pages between 1 and 2000),
59
+ copy_to text[] not null default '{}' check (cardinality(copy_to) <= 5),
60
+ identity text not null check (identity in ('link', 'email_code')),
61
+ created_at timestamptz not null,
62
+ expires_at timestamptz not null,
63
+ completed_at timestamptz,
64
+ signed_key text check (char_length(signed_key) between 1 and 300),
65
+ signed_sha256 text check (signed_sha256 ~ '^[0-9a-f]{64}$'),
66
+ copies_sent_at timestamptz,
67
+ ended_at timestamptz,
68
+ end_reason text check (char_length(end_reason) <= 500),
69
+ check ((subject_type is null) = (subject_id is null)),
70
+ check ((status = 'completed') = (completed_at is not null)),
71
+ check ((status = 'completed') = (signed_sha256 is not null) and (signed_sha256 is null) = (signed_key is null)),
72
+ check ((status in ('declined', 'voided', 'expired')) = (ended_at is not null)),
73
+ check (expires_at > created_at)
74
+ );
75
+
76
+ comment on table public.agreements is 'Agreements sent to be signed (workbench-agreements): the PDF''s key in the app''s R2 bucket and its SHA-256, the signed copy''s once complete, and the status. Service role only.';
77
+
78
+ create index agreements_account on public.agreements (account, created_at desc);
79
+ create index agreements_subject on public.agreements (subject_type, subject_id) where subject_id is not null;
80
+ create index agreements_out on public.agreements (expires_at) where status = 'out';
81
+ create index agreements_document_sha on public.agreements (document_sha256);
82
+ create index agreements_signed_sha on public.agreements (signed_sha256) where signed_sha256 is not null;
83
+
84
+ create table public.agreement_signers (
85
+ id uuid primary key default gen_random_uuid(),
86
+ agreement_id uuid not null references public.agreements (id) on delete cascade,
87
+ position smallint not null check (position between 1 and 5),
88
+ name text not null check (char_length(name) between 1 and 120),
89
+ email text not null check (char_length(email) between 3 and 254 and email ~ '^[^@\\s]+@[^@\\s]+$'),
90
+ role text check (char_length(role) between 1 and 60),
91
+ token text not null unique check (token ~ '^[A-Za-z0-9_-]{43}$'),
92
+ status text not null default 'waiting' check (status in ('waiting', 'signed', 'declined')),
93
+ invited_at timestamptz,
94
+ reminders smallint not null default 0 check (reminders between 0 and 3),
95
+ last_reminded_at timestamptz,
96
+ verified_at timestamptz,
97
+ code_hash text check (code_hash ~ '^[0-9a-f]{64}$'),
98
+ code_sent_at timestamptz,
99
+ code_expires_at timestamptz,
100
+ code_tries smallint not null default 0,
101
+ signed_at timestamptz,
102
+ method text check (method in ('typed', 'drawn')),
103
+ typed_name text check (char_length(typed_name) between 2 and 120),
104
+ signature_key text check (char_length(signature_key) between 1 and 300),
105
+ consent text check (char_length(consent) between 1 and 1000),
106
+ sign_ip text check (char_length(sign_ip) <= 64),
107
+ sign_user_agent text check (char_length(sign_user_agent) <= 400),
108
+ declined_at timestamptz,
109
+ decline_reason text check (char_length(decline_reason) <= 500),
110
+ unique (agreement_id, position),
111
+ check ((status = 'signed') = (signed_at is not null) and (signed_at is null) = (method is null) and (method is null) = (typed_name is null) and (typed_name is null) = (consent is null)),
112
+ check ((method = 'drawn') = (signature_key is not null)),
113
+ check ((status = 'declined') = (declined_at is not null))
114
+ );
115
+
116
+ comment on table public.agreement_signers is 'Who signs each agreement, their private link, and how and when they signed (workbench-agreements). Name, email and, when the project keeps them, IP address and browser are personal details, kept for the agreement''s retention. Service role only.';
117
+
118
+ create index agreement_signers_agreement on public.agreement_signers (agreement_id, position);
119
+ create index agreement_signers_waiting on public.agreement_signers (agreement_id) where status = 'waiting';
120
+
121
+ create table public.agreement_events (
122
+ id bigint generated always as identity primary key,
123
+ agreement_id uuid not null references public.agreements (id) on delete cascade,
124
+ signer_id uuid references public.agreement_signers (id) on delete cascade,
125
+ kind text not null check (kind in ('created', 'invited', 'reminded', 'opened', 'code_sent', 'code_failed', 'verified', 'document_viewed', 'signed', 'declined', 'voided', 'expired', 'completed', 'copy_sent', 'copy_downloaded')),
126
+ at timestamptz not null,
127
+ ip text check (char_length(ip) <= 64),
128
+ user_agent text check (char_length(user_agent) <= 400),
129
+ detail jsonb check (detail is null or (jsonb_typeof(detail) = 'object' and octet_length(detail::text) <= 2000))
130
+ );
131
+
132
+ comment on table public.agreement_events is 'The audit trail of each agreement (workbench-agreements): what happened, when, and the IP address and browser when the project keeps them. Rows are only added. Service role only.';
133
+
134
+ create index agreement_events_agreement on public.agreement_events (agreement_id, at, id);
135
+
136
+ alter table public.agreements enable row level security;
137
+ alter table public.agreement_signers enable row level security;
138
+ alter table public.agreement_events enable row level security;
139
+
140
+ revoke all on public.agreements, public.agreement_signers, public.agreement_events from anon, authenticated;
141
+
142
+ -- One agreement as JSON, with its signers in order (tokens and code hashes left out).
143
+ create function public.agreements_json(a public.agreements)
144
+ returns jsonb
145
+ language sql
146
+ stable
147
+ security invoker
148
+ set search_path = ''
149
+ as $$
150
+ select to_jsonb(a) || jsonb_build_object('signers', coalesce((
151
+ select jsonb_agg(to_jsonb(s) - 'token' - 'code_hash' order by s.position)
152
+ from public.agreement_signers s where s.agreement_id = a.id
153
+ ), '[]'::jsonb));
154
+ $$;
155
+
156
+ revoke execute on function public.agreements_json(public.agreements) from public, anon, authenticated;
157
+ grant execute on function public.agreements_json(public.agreements) to service_role;
158
+
159
+ -- p: { id, account, subject_type?, subject_id?, title, business, language, document_key, document_sha256, pages, copy_to, identity, created_at, expires_at, signers: [{ position, name, email, role?, token }] }
160
+ create function public.agreements_create(p jsonb)
161
+ returns uuid
162
+ language plpgsql
163
+ security invoker
164
+ set search_path = ''
165
+ as $$
166
+ declare
167
+ a_id uuid := (p->>'id')::uuid;
168
+ at timestamptz := (p->>'created_at')::timestamptz;
169
+ begin
170
+ insert into public.agreements (id, account, subject_type, subject_id, title, business, language, document_key, document_sha256, pages, copy_to, identity, created_at, expires_at)
171
+ values (a_id, p->>'account', p->>'subject_type', p->>'subject_id', p->>'title', p->>'business', p->>'language', p->>'document_key', p->>'document_sha256',
172
+ (p->>'pages')::integer, coalesce((select array_agg(x) from jsonb_array_elements_text(p->'copy_to') x), '{}'), p->>'identity', at, (p->>'expires_at')::timestamptz);
173
+ insert into public.agreement_signers (agreement_id, position, name, email, role, token)
174
+ select a_id, (s->>'position')::smallint, s->>'name', s->>'email', s->>'role', s->>'token'
175
+ from jsonb_array_elements(p->'signers') s;
176
+ insert into public.agreement_events (agreement_id, kind, at, detail)
177
+ values (a_id, 'created', at, jsonb_build_object('signers', jsonb_array_length(p->'signers'), 'pages', (p->>'pages')::integer, 'sha256', p->>'document_sha256'));
178
+ return a_id;
179
+ end;
180
+ $$;
181
+
182
+ -- One agreement with its signers and its audit trail, or null.
183
+ create function public.agreements_get(p_id uuid)
184
+ returns jsonb
185
+ language sql
186
+ stable
187
+ security invoker
188
+ set search_path = ''
189
+ as $$
190
+ select public.agreements_json(a) || jsonb_build_object('events', coalesce((
191
+ select jsonb_agg(to_jsonb(e) order by e.at, e.id) from public.agreement_events e where e.agreement_id = a.id
192
+ ), '[]'::jsonb))
193
+ from public.agreements a where a.id = p_id;
194
+ $$;
195
+
196
+ -- What a signing link opens: the agreement, which signer this is, and the other signers' names. Null for an unknown token.
197
+ create function public.agreements_open(p_token text)
198
+ returns jsonb
199
+ language sql
200
+ stable
201
+ security invoker
202
+ set search_path = ''
203
+ as $$
204
+ select jsonb_build_object('agreement', public.agreements_json(a), 'signer_id', s.id)
205
+ from public.agreement_signers s join public.agreements a on a.id = s.agreement_id
206
+ where s.token = p_token;
207
+ $$;
208
+
209
+ -- The waiting signers' private links, to email or share again.
210
+ create function public.agreements_tokens(p_id uuid)
211
+ returns jsonb
212
+ language sql
213
+ stable
214
+ security invoker
215
+ set search_path = ''
216
+ as $$
217
+ select coalesce(jsonb_agg(jsonb_build_object('signer_id', s.id, 'token', s.token) order by s.position), '[]'::jsonb)
218
+ from public.agreement_signers s where s.agreement_id = p_id and s.status = 'waiting';
219
+ $$;
220
+
221
+ create function public.agreements_event(p_agreement uuid, p_signer uuid, p_kind text, p_at timestamptz, p_ip text, p_ua text, p_detail jsonb)
222
+ returns void
223
+ language sql
224
+ security invoker
225
+ set search_path = ''
226
+ as $$
227
+ insert into public.agreement_events (agreement_id, signer_id, kind, at, ip, user_agent, detail)
228
+ values (p_agreement, p_signer, p_kind, p_at, p_ip, p_ua, p_detail);
229
+ $$;
230
+
231
+ -- Signs for one signer. { ok, reason?, all_signed }. reason: not_found, closed, expired, done, not_verified.
232
+ create function public.agreements_sign(p_signer uuid, p_at timestamptz, p_method text, p_typed_name text, p_signature_key text, p_consent text, p_ip text, p_ua text, p_require_verified boolean)
233
+ returns jsonb
234
+ language plpgsql
235
+ security invoker
236
+ set search_path = ''
237
+ as $$
238
+ declare
239
+ s public.agreement_signers;
240
+ a public.agreements;
241
+ waiting integer;
242
+ begin
243
+ select * into s from public.agreement_signers where id = p_signer;
244
+ if not found then return jsonb_build_object('ok', false, 'reason', 'not_found'); end if;
245
+ select * into a from public.agreements where id = s.agreement_id for update;
246
+ select * into s from public.agreement_signers where id = p_signer for update;
247
+ if a.status <> 'out' then return jsonb_build_object('ok', false, 'reason', 'closed'); end if;
248
+ if a.expires_at <= p_at then return jsonb_build_object('ok', false, 'reason', 'expired'); end if;
249
+ if s.status <> 'waiting' then return jsonb_build_object('ok', false, 'reason', 'done'); end if;
250
+ if p_require_verified and s.verified_at is null then return jsonb_build_object('ok', false, 'reason', 'not_verified'); end if;
251
+ update public.agreement_signers
252
+ set status = 'signed', signed_at = p_at, method = p_method, typed_name = p_typed_name, signature_key = p_signature_key,
253
+ consent = p_consent, sign_ip = p_ip, sign_user_agent = p_ua
254
+ where id = p_signer;
255
+ insert into public.agreement_events (agreement_id, signer_id, kind, at, ip, user_agent, detail)
256
+ values (a.id, p_signer, 'signed', p_at, p_ip, p_ua, jsonb_build_object('method', p_method));
257
+ select count(*) into waiting from public.agreement_signers where agreement_id = a.id and status <> 'signed';
258
+ return jsonb_build_object('ok', true, 'all_signed', waiting = 0, 'agreement_id', a.id);
259
+ end;
260
+ $$;
261
+
262
+ create function public.agreements_decline(p_signer uuid, p_at timestamptz, p_reason text, p_ip text, p_ua text)
263
+ returns jsonb
264
+ language plpgsql
265
+ security invoker
266
+ set search_path = ''
267
+ as $$
268
+ declare
269
+ s public.agreement_signers;
270
+ a public.agreements;
271
+ begin
272
+ select * into s from public.agreement_signers where id = p_signer;
273
+ if not found then return jsonb_build_object('ok', false, 'reason', 'not_found'); end if;
274
+ select * into a from public.agreements where id = s.agreement_id for update;
275
+ select * into s from public.agreement_signers where id = p_signer for update;
276
+ if a.status <> 'out' then return jsonb_build_object('ok', false, 'reason', 'closed'); end if;
277
+ if s.status <> 'waiting' then return jsonb_build_object('ok', false, 'reason', 'done'); end if;
278
+ update public.agreement_signers set status = 'declined', declined_at = p_at, decline_reason = nullif(p_reason, '') where id = p_signer;
279
+ update public.agreements set status = 'declined', ended_at = p_at, end_reason = nullif(p_reason, '') where id = a.id;
280
+ insert into public.agreement_events (agreement_id, signer_id, kind, at, ip, user_agent)
281
+ values (a.id, p_signer, 'declined', p_at, p_ip, p_ua);
282
+ return jsonb_build_object('ok', true, 'agreement_id', a.id);
283
+ end;
284
+ $$;
285
+
286
+ create function public.agreements_void(p_id uuid, p_reason text, p_at timestamptz)
287
+ returns boolean
288
+ language plpgsql
289
+ security invoker
290
+ set search_path = ''
291
+ as $$
292
+ begin
293
+ update public.agreements set status = 'voided', ended_at = p_at, end_reason = p_reason where id = p_id and status = 'out';
294
+ if not found then return false; end if;
295
+ insert into public.agreement_events (agreement_id, kind, at, detail) values (p_id, 'voided', p_at, jsonb_build_object('reason', p_reason));
296
+ return true;
297
+ end;
298
+ $$;
299
+
300
+ -- Marks an agreement complete once every signer has signed. False when it isn't out, or someone hasn't signed.
301
+ create function public.agreements_complete(p_id uuid, p_signed_key text, p_signed_sha256 text, p_at timestamptz)
302
+ returns boolean
303
+ language plpgsql
304
+ security invoker
305
+ set search_path = ''
306
+ as $$
307
+ begin
308
+ perform 1 from public.agreements where id = p_id for update;
309
+ if exists (select 1 from public.agreement_signers where agreement_id = p_id and status <> 'signed') then return false; end if;
310
+ update public.agreements set status = 'completed', completed_at = p_at, signed_key = p_signed_key, signed_sha256 = p_signed_sha256 where id = p_id and status = 'out';
311
+ if not found then return false; end if;
312
+ insert into public.agreement_events (agreement_id, kind, at, detail) values (p_id, 'completed', p_at, jsonb_build_object('sha256', p_signed_sha256));
313
+ return true;
314
+ end;
315
+ $$;
316
+
317
+ create function public.agreements_copies_sent(p_id uuid, p_at timestamptz, p_count integer)
318
+ returns void
319
+ language plpgsql
320
+ security invoker
321
+ set search_path = ''
322
+ as $$
323
+ begin
324
+ update public.agreements set copies_sent_at = p_at where id = p_id and status = 'completed' and copies_sent_at is null;
325
+ if found then
326
+ insert into public.agreement_events (agreement_id, kind, at, detail) values (p_id, 'copy_sent', p_at, jsonb_build_object('emails', p_count));
327
+ end if;
328
+ end;
329
+ $$;
330
+
331
+ -- Keeps a new code's hash. { ok, reason? }: reason wait when one went less than a minute ago.
332
+ create function public.agreements_code_sent(p_signer uuid, p_code_hash text, p_at timestamptz, p_expires timestamptz, p_ip text, p_ua text)
333
+ returns jsonb
334
+ language plpgsql
335
+ security invoker
336
+ set search_path = ''
337
+ as $$
338
+ declare
339
+ s public.agreement_signers;
340
+ begin
341
+ select * into s from public.agreement_signers where id = p_signer for update;
342
+ if not found then return jsonb_build_object('ok', false, 'reason', 'not_found'); end if;
343
+ if s.code_sent_at is not null and s.code_sent_at > p_at - interval '60 seconds' then return jsonb_build_object('ok', false, 'reason', 'wait'); end if;
344
+ update public.agreement_signers set code_hash = p_code_hash, code_sent_at = p_at, code_expires_at = p_expires, code_tries = 0 where id = p_signer;
345
+ insert into public.agreement_events (agreement_id, signer_id, kind, at, ip, user_agent) values (s.agreement_id, p_signer, 'code_sent', p_at, p_ip, p_ua);
346
+ return jsonb_build_object('ok', true);
347
+ end;
348
+ $$;
349
+
350
+ -- Checks a code: ok, wrong, expired, locked (5 wrong tries) or none (no code sent).
351
+ create function public.agreements_code_try(p_signer uuid, p_code_hash text, p_at timestamptz, p_ip text, p_ua text)
352
+ returns text
353
+ language plpgsql
354
+ security invoker
355
+ set search_path = ''
356
+ as $$
357
+ declare
358
+ s public.agreement_signers;
359
+ begin
360
+ select * into s from public.agreement_signers where id = p_signer for update;
361
+ if not found or s.code_hash is null then return 'none'; end if;
362
+ if s.code_tries >= 5 then return 'locked'; end if;
363
+ if s.code_expires_at <= p_at then return 'expired'; end if;
364
+ if s.code_hash <> p_code_hash then
365
+ update public.agreement_signers set code_tries = code_tries + 1 where id = p_signer;
366
+ insert into public.agreement_events (agreement_id, signer_id, kind, at, ip, user_agent) values (s.agreement_id, p_signer, 'code_failed', p_at, p_ip, p_ua);
367
+ return case when s.code_tries + 1 >= 5 then 'locked' else 'wrong' end;
368
+ end if;
369
+ update public.agreement_signers set verified_at = p_at, code_hash = null, code_expires_at = null, code_tries = 0 where id = p_signer;
370
+ insert into public.agreement_events (agreement_id, signer_id, kind, at, ip, user_agent) values (s.agreement_id, p_signer, 'verified', p_at, p_ip, p_ua);
371
+ return 'ok';
372
+ end;
373
+ $$;
374
+
375
+ -- Records an invitation (p_kind invited) or a reminder (reminded) emailed to a signer.
376
+ create function public.agreements_invited(p_signer uuid, p_at timestamptz, p_kind text)
377
+ returns void
378
+ language plpgsql
379
+ security invoker
380
+ set search_path = ''
381
+ as $$
382
+ declare
383
+ a_id uuid;
384
+ begin
385
+ if p_kind = 'invited' then
386
+ update public.agreement_signers set invited_at = coalesce(invited_at, p_at) where id = p_signer returning agreement_id into a_id;
387
+ elsif p_kind = 'reminded' then
388
+ update public.agreement_signers set reminders = reminders + 1, last_reminded_at = p_at where id = p_signer returning agreement_id into a_id;
389
+ else
390
+ raise exception 'p_kind must be invited or reminded';
391
+ end if;
392
+ if a_id is not null then
393
+ insert into public.agreement_events (agreement_id, signer_id, kind, at) values (a_id, p_signer, p_kind, p_at);
394
+ end if;
395
+ end;
396
+ $$;
397
+
398
+ -- The cron's view: agreements it has just expired, ones to finish (everyone signed), ones whose copies weren't sent, and waiting signers who were invited by email.
399
+ create function public.agreements_scan(p_at timestamptz, p_limit integer)
400
+ returns jsonb
401
+ language plpgsql
402
+ security invoker
403
+ set search_path = ''
404
+ as $$
405
+ declare
406
+ expired jsonb;
407
+ begin
408
+ with e as (
409
+ update public.agreements set status = 'expired', ended_at = p_at
410
+ where id in (select id from public.agreements where status = 'out' and expires_at <= p_at order by expires_at limit p_limit for update skip locked)
411
+ returning id
412
+ ), ev as (
413
+ insert into public.agreement_events (agreement_id, kind, at) select id, 'expired', p_at from e returning agreement_id
414
+ )
415
+ select coalesce(jsonb_agg(agreement_id), '[]'::jsonb) into expired from ev;
416
+ return jsonb_build_object(
417
+ 'expired', expired,
418
+ 'finish', coalesce((select jsonb_agg(a.id) from (select a.id from public.agreements a where a.status = 'out'
419
+ and not exists (select 1 from public.agreement_signers s where s.agreement_id = a.id and s.status <> 'signed') limit p_limit) a), '[]'::jsonb),
420
+ 'copies', coalesce((select jsonb_agg(a.id) from (select id from public.agreements where status = 'completed' and copies_sent_at is null limit p_limit) a), '[]'::jsonb),
421
+ 'waiting', coalesce((select jsonb_agg(jsonb_build_object('signer_id', s.id, 'agreement_id', s.agreement_id, 'invited_at', s.invited_at, 'reminders', s.reminders, 'last_reminded_at', s.last_reminded_at))
422
+ from (select s.* from public.agreement_signers s join public.agreements a on a.id = s.agreement_id
423
+ where a.status = 'out' and s.status = 'waiting' and s.invited_at is not null and s.reminders < 3 limit p_limit) s), '[]'::jsonb)
424
+ );
425
+ end;
426
+ $$;
427
+
428
+ -- An account's agreements, newest first, with their signers.
429
+ create function public.agreements_list(p_account text, p_limit integer)
430
+ returns jsonb
431
+ language sql
432
+ stable
433
+ security invoker
434
+ set search_path = ''
435
+ as $$
436
+ select coalesce(jsonb_agg(public.agreements_json(a) order by a.created_at desc), '[]'::jsonb)
437
+ from (select * from public.agreements where account = p_account order by created_at desc limit p_limit) a;
438
+ $$;
439
+
440
+ -- Which agreement a PDF is, by its SHA-256: the original or the signed copy. Null when none.
441
+ create function public.agreements_by_hash(p_sha256 text)
442
+ returns jsonb
443
+ language sql
444
+ stable
445
+ security invoker
446
+ set search_path = ''
447
+ as $$
448
+ select jsonb_build_object('id', a.id, 'title', a.title, 'status', a.status, 'completed_at', a.completed_at,
449
+ 'which', case when a.signed_sha256 = p_sha256 then 'signed' else 'original' end)
450
+ from public.agreements a where a.document_sha256 = p_sha256 or a.signed_sha256 = p_sha256
451
+ order by (a.signed_sha256 = p_sha256) desc nulls last, a.created_at desc limit 1;
452
+ $$;
453
+
454
+ -- Agreements past their retention: completed before p_signed_before, or ended (declined, voided, expired) before p_unsigned_before. With the file keys to delete first.
455
+ create function public.agreements_old(p_signed_before timestamptz, p_unsigned_before timestamptz, p_limit integer)
456
+ returns jsonb
457
+ language sql
458
+ stable
459
+ security invoker
460
+ set search_path = ''
461
+ as $$
462
+ select coalesce(jsonb_agg(jsonb_build_object('id', a.id, 'keys',
463
+ to_jsonb(array_remove(array[a.document_key, a.signed_key], null) || coalesce((select array_agg(signature_key) from public.agreement_signers where agreement_id = a.id and signature_key is not null), '{}')))), '[]'::jsonb)
464
+ from (select * from public.agreements
465
+ where (status = 'completed' and completed_at < p_signed_before) or (status in ('declined', 'voided', 'expired') and ended_at < p_unsigned_before)
466
+ limit p_limit) a;
467
+ $$;
468
+
469
+ create function public.agreements_delete(p_ids uuid[])
470
+ returns integer
471
+ language plpgsql
472
+ security invoker
473
+ set search_path = ''
474
+ as $$
475
+ declare
476
+ n integer;
477
+ begin
478
+ delete from public.agreements where id = any (p_ids) and status <> 'out';
479
+ get diagnostics n = row_count;
480
+ return n;
481
+ end;
482
+ $$;
483
+
484
+ ${grants}
485
+ grant select, insert, update, delete on public.agreements, public.agreement_signers, public.agreement_events to service_role;
486
+ `,
487
+ down: `${drops}
488
+ drop function public.agreements_json(public.agreements);
489
+ drop table public.agreement_events;
490
+ drop table public.agreement_signers;
491
+ drop table public.agreements;
492
+ `,
493
+ };
package/dist/page.d.ts ADDED
@@ -0,0 +1,46 @@
1
+ import type { AgreementLanguage, SigningMethod } from "./config.ts";
2
+ import { type AgreementStrings, type AgreementWordKey } from "./words.ts";
3
+ export interface PageCommon {
4
+ language: AgreementLanguage;
5
+ t?: AgreementStrings;
6
+ styles?: readonly string[];
7
+ }
8
+ /** What the signing page shows. */
9
+ export interface SigningView {
10
+ title: string;
11
+ business: string;
12
+ signerName: string;
13
+ signerEmail: string;
14
+ others: readonly string[];
15
+ /** Already formatted for the business's time zone. */
16
+ expires: string;
17
+ pages: number;
18
+ /** The PDF's address, relative to the page. */
19
+ documentHref: string;
20
+ }
21
+ export interface SigningFormState {
22
+ problems?: readonly AgreementWordKey[];
23
+ name?: string;
24
+ method?: SigningMethod;
25
+ consentRead?: boolean;
26
+ consentEsign?: boolean;
27
+ }
28
+ /** The signing page: read, tick, name, sign; and a fold to decline. */
29
+ export declare function renderSigningPage(v: SigningView, methods: readonly SigningMethod[], o: PageCommon & SigningFormState): string;
30
+ /** The email code check, before the agreement opens. */
31
+ export declare function renderCodePage(v: Pick<SigningView, "title" | "business" | "signerEmail">, o: PageCommon & {
32
+ sent?: boolean;
33
+ problems?: readonly AgreementWordKey[];
34
+ }): string;
35
+ /** After signing: done, or waiting for the others. */
36
+ export declare function renderDonePage(v: Pick<SigningView, "title">, o: PageCommon & {
37
+ signedAt: string;
38
+ completed: boolean;
39
+ downloadHref?: string;
40
+ }): string;
41
+ export type EndedReason = "declined_by_you" | "voided" | "expired" | "declined";
42
+ /** A closed agreement, or a link that leads nowhere. */
43
+ export declare function renderEndedPage(reason: EndedReason | "not_found", o: PageCommon & {
44
+ title?: string;
45
+ business?: string;
46
+ }): string;
package/dist/page.js ADDED
@@ -0,0 +1,118 @@
1
+ // The pages a signer sees, all plain HTML with a wb-agreement-* class on
2
+ // every element (AGREEMENT_STYLES): the signing page, the email code check,
3
+ // and the done, declined, ended and not-found pages. The signing page works
4
+ // without its script for a typed signature; drawing needs the script.
5
+ import { SIGN_SCRIPT } from "./script.js";
6
+ import { agreementWord } from "./words.js";
7
+ const DEFAULT_STYLESHEETS = ["/styles/workbench.css", "/styles/project.css"];
8
+ const esc = (s) => s.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
9
+ const htmlLang = (l) => (l === "en" ? "en" : "fil");
10
+ function shell(o, title, body, script = false) {
11
+ return [
12
+ `<!doctype html><html lang="${htmlLang(o.language)}"><head><meta charset="utf-8">`,
13
+ `<title>${esc(title)}</title>`,
14
+ '<meta name="robots" content="noindex, nofollow">',
15
+ '<meta name="referrer" content="no-referrer">',
16
+ '<meta name="viewport" content="width=device-width, initial-scale=1">',
17
+ ...(o.styles ?? DEFAULT_STYLESHEETS).map((s) => `<link rel="stylesheet" href="${esc(s)}">`),
18
+ "</head>",
19
+ `<body><main class="wb-agreement">`,
20
+ body,
21
+ "</main>",
22
+ ...(script ? [`<script>${SIGN_SCRIPT}</script>`] : []),
23
+ "</body></html>",
24
+ "",
25
+ ].join("\n");
26
+ }
27
+ const w = (o, key, params) => esc(agreementWord(o.t, o.language, key, params));
28
+ function problemsHtml(o, problems) {
29
+ if (!problems?.length)
30
+ return "";
31
+ return `<div class="wb-agreement-problems" role="alert"><p class="wb-agreement-problems-title">${w(o, "problem.title")}</p><ul class="wb-agreement-problem-list">${problems
32
+ .map((p) => `<li class="wb-agreement-problem">${w(o, p)}</li>`)
33
+ .join("")}</ul></div>`;
34
+ }
35
+ function headerHtml(o, v) {
36
+ const pages = v.pages === 1 ? agreementWord(o.t, o.language, "page.pages_one") : agreementWord(o.t, o.language, "page.pages_many", { count: v.pages });
37
+ return [
38
+ `<h1 class="wb-agreement-title">${esc(v.title)}</h1>`,
39
+ `<p class="wb-agreement-meta">${w(o, "page.from", { business: v.business })}</p>`,
40
+ `<p class="wb-agreement-meta">${w(o, "page.for", { name: v.signerName })}</p>`,
41
+ ...(v.others.length ? [`<p class="wb-agreement-meta">${w(o, "page.others", { names: v.others.join(", ") })}</p>`] : []),
42
+ `<p class="wb-agreement-meta">${w(o, "page.expires", { date: v.expires })}</p>`,
43
+ `<a class="wb-agreement-read" href="${esc(v.documentHref)}" target="_blank" rel="noopener">${w(o, "page.read")}</a>`,
44
+ `<p class="wb-agreement-hint">${w(o, "page.read_hint", { pages })}</p>`,
45
+ ].join("\n");
46
+ }
47
+ const hidden = (name, value) => `<input class="wb-agreement-data" type="hidden" name="${name}" value="${esc(value)}">`;
48
+ /** The signing page: read, tick, name, sign; and a fold to decline. */
49
+ export function renderSigningPage(v, methods, o) {
50
+ const method = o.method && methods.includes(o.method) ? o.method : methods[0];
51
+ const check = (name, key, on) => `<label class="wb-agreement-check"><input class="wb-agreement-check-input" type="checkbox" name="${name}" value="yes" required${on ? " checked" : ""}><span>${w(o, key)}</span></label>`;
52
+ const radio = (m) => `<label class="wb-agreement-method"><input class="wb-agreement-method-input" type="radio" name="method" value="${m}"${m === method ? " checked" : ""}><span>${w(o, m === "typed" ? "method.typed" : "method.drawn")}</span></label>`;
53
+ const parts = [
54
+ headerHtml(o, v),
55
+ problemsHtml(o, o.problems),
56
+ `<form class="wb-agreement-form" method="post" data-sign>`,
57
+ hidden("action", "sign"),
58
+ check("consent_read", "consent.read", o.consentRead),
59
+ check("consent_esign", "consent.esign", o.consentEsign),
60
+ `<div class="wb-agreement-field"><label class="wb-agreement-label" for="wb-agreement-name">${w(o, "name.label")}</label><input class="wb-agreement-input" id="wb-agreement-name" type="text" name="name" autocomplete="name" required minlength="2" maxlength="120" value="${esc(o.name ?? v.signerName)}"><p class="wb-agreement-hint">${w(o, "name.hint")}</p></div>`,
61
+ methods.length > 1
62
+ ? `<fieldset class="wb-agreement-methods"><legend class="wb-agreement-methods-legend">${w(o, "method.label")}</legend>${methods.map(radio).join("")}</fieldset>`
63
+ : hidden("method", method),
64
+ ...(methods.includes("typed")
65
+ ? [`<div class="wb-agreement-typed"${method === "typed" ? "" : " hidden"}><p class="wb-agreement-hint">${w(o, "typed.preview")}</p><p class="wb-agreement-typed-name" aria-hidden="true">${esc(o.name ?? v.signerName)}</p></div>`]
66
+ : []),
67
+ ...(methods.includes("drawn")
68
+ ? [
69
+ `<div class="wb-agreement-pad"${method === "drawn" ? "" : " hidden"}><p class="wb-agreement-hint">${w(o, "drawn.hint")}</p><canvas class="wb-agreement-canvas" width="600" height="240" aria-label="${w(o, "method.drawn")}"></canvas><button class="wb-agreement-clear" type="button">${w(o, "drawn.clear")}</button>${hidden("signature", "")}</div>`,
70
+ ]
71
+ : []),
72
+ `<button class="wb-agreement-sign" type="submit">${w(o, "sign")}</button>`,
73
+ `<p class="wb-agreement-hint">${w(o, "sign_hint", { name: o.name ?? v.signerName })}</p>`,
74
+ "</form>",
75
+ `<details class="wb-agreement-decline"><summary class="wb-agreement-decline-summary">${w(o, "decline.open")}</summary>`,
76
+ `<form class="wb-agreement-form" method="post">${hidden("action", "decline")}<div class="wb-agreement-field"><label class="wb-agreement-label" for="wb-agreement-reason">${w(o, "decline.reason", { business: v.business })}</label><textarea class="wb-agreement-textarea" id="wb-agreement-reason" name="reason" maxlength="500"></textarea></div><button class="wb-agreement-decline-button" type="submit">${w(o, "decline")}</button></form>`,
77
+ "</details>",
78
+ ];
79
+ return shell(o, v.title, parts.filter(Boolean).join("\n"), true);
80
+ }
81
+ /** The email code check, before the agreement opens. */
82
+ export function renderCodePage(v, o) {
83
+ const body = [
84
+ `<h1 class="wb-agreement-title">${w(o, "code.title")}</h1>`,
85
+ `<p class="wb-agreement-meta">${esc(v.title)}</p>`,
86
+ `<p class="wb-agreement-meta">${w(o, "page.from", { business: v.business })}</p>`,
87
+ problemsHtml(o, o.problems),
88
+ `<p class="wb-agreement-text">${o.sent ? w(o, "code.sent", { email: v.signerEmail }) : w(o, "code.text", { email: v.signerEmail })}</p>`,
89
+ ...(o.sent
90
+ ? [
91
+ `<form class="wb-agreement-form" method="post">${hidden("action", "check_code")}<div class="wb-agreement-field"><label class="wb-agreement-label" for="wb-agreement-code">${w(o, "code.label")}</label><input class="wb-agreement-input" id="wb-agreement-code" type="text" name="code" inputmode="numeric" autocomplete="one-time-code" pattern="[0-9]{6}" maxlength="6" required></div><button class="wb-agreement-sign" type="submit">${w(o, "code.check")}</button></form>`,
92
+ ]
93
+ : []),
94
+ `<form class="wb-agreement-form" method="post">${hidden("action", "send_code")}<button class="${o.sent ? "wb-agreement-decline-button" : "wb-agreement-sign"}" type="submit">${w(o, "code.send")}</button></form>`,
95
+ ];
96
+ return shell(o, agreementWord(o.t, o.language, "code.title"), body.filter(Boolean).join("\n"));
97
+ }
98
+ /** After signing: done, or waiting for the others. */
99
+ export function renderDonePage(v, o) {
100
+ const body = [
101
+ `<h1 class="wb-agreement-title">${w(o, "done.title")}</h1>`,
102
+ `<p class="wb-agreement-meta">${esc(v.title)}</p>`,
103
+ `<p class="wb-agreement-text">${w(o, o.completed ? "done.text" : "done.waiting", { date: o.signedAt })}</p>`,
104
+ ...(o.completed && o.downloadHref ? [`<a class="wb-agreement-download" href="${esc(o.downloadHref)}">${w(o, "done.download")}</a>`] : []),
105
+ ];
106
+ return shell(o, agreementWord(o.t, o.language, "done.title"), body.join("\n"));
107
+ }
108
+ /** A closed agreement, or a link that leads nowhere. */
109
+ export function renderEndedPage(reason, o) {
110
+ const business = o.business ?? "";
111
+ const [title, text] = reason === "not_found" ? ["not_found.title", "not_found.text"] : reason === "declined_by_you" ? ["declined.title", "declined.text"] : ["ended.title", `ended.${reason}`];
112
+ const body = [
113
+ `<h1 class="wb-agreement-title">${w(o, title)}</h1>`,
114
+ ...(o.title ? [`<p class="wb-agreement-meta">${esc(o.title)}</p>`] : []),
115
+ `<p class="wb-agreement-text">${w(o, text, { business })}</p>`,
116
+ ];
117
+ return shell(o, agreementWord(o.t, o.language, title), body.join("\n"));
118
+ }