Repository navigation
Expand file tree
/
Copy pathworker.js
More file actions
1382 lines (1297 loc) · 57.5 KB
/
Copy pathworker.js
File metadata and controls
1382 lines (1297 loc) · 57.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const COOKIE_NAME = 'possums_session';
const WHO_COOKIE = 'possums_who';
const COOKIE_MAX_AGE = 60 * 60 * 24 * 30;
const SESSION_VALUE = 'ok';
const FEED_KINDS = ['bottle', 'breast_l', 'breast_r', 'solid'];
const NAPPY_KINDS = ['wet', 'dirty', 'both'];
const SPITUP_KINDS = ['small', 'medium', 'large', 'projectile'];
const WHO_VALUES = ['parent1', 'parent2'];
const PARENTS_KEY = 'config:parents';
const AUTH_KEY = 'config:auth';
const SECRET_KEY = 'config:session_secret';
const VAPID_KEY = 'config:vapid';
const PUSH_SUBS_KEY = 'push:subs';
const BABY_KEY = 'config:baby';
const RESET_TOKEN_KEY = 'reset_token';
const RESET_COOLDOWN_KEY = 'reset_cooldown';
const DEFAULT_PARENTS = { parent1: 'Parent 1', parent2: 'Parent 2' };
const PBKDF2_ITERS = 100000;
const readParents = async (env) => {
const raw = await env.POSSUMS_KV.get(PARENTS_KEY);
if (!raw) return { ...DEFAULT_PARENTS };
try {
const o = JSON.parse(raw);
return {
parent1: typeof o.parent1 === 'string' && o.parent1 ? o.parent1 : DEFAULT_PARENTS.parent1,
parent2: typeof o.parent2 === 'string' && o.parent2 ? o.parent2 : DEFAULT_PARENTS.parent2,
};
} catch { return { ...DEFAULT_PARENTS }; }
};
const writeParents = (env, obj) => env.POSSUMS_KV.put(PARENTS_KEY, JSON.stringify(obj));
const readBaby = async (env) => {
const raw = await env.POSSUMS_KV.get(BABY_KEY);
if (!raw) return { dob: '', gender: '' };
try {
const o = JSON.parse(raw);
return {
dob: typeof o.dob === 'string' ? o.dob : '',
gender: o.gender === 'boy' || o.gender === 'girl' ? o.gender : '',
};
} catch { return { dob: '', gender: '' }; }
};
const writeBaby = (env, obj) => env.POSSUMS_KV.put(BABY_KEY, JSON.stringify(obj));
const b64uEncode = (buf) => {
const bytes = buf instanceof Uint8Array ? buf : new Uint8Array(buf);
let bin = '';
for (const b of bytes) bin += String.fromCharCode(b);
return btoa(bin).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
};
const b64uDecode = (str) => {
const b64 = str.replace(/-/g, '+').replace(/_/g, '/') + '='.repeat((4 - (str.length % 4)) % 4);
return Uint8Array.from(atob(b64), (c) => c.charCodeAt(0));
};
const concatBytes = (...arrs) => {
const out = new Uint8Array(arrs.reduce((n, a) => n + a.length, 0));
let off = 0;
for (const a of arrs) { out.set(a, off); off += a.length; }
return out;
};
const utf8 = (s) => new TextEncoder().encode(s);
const getVapid = async (env) => {
const raw = await env.POSSUMS_KV.get(VAPID_KEY);
if (raw) {
try {
const o = JSON.parse(raw);
if (o.publicKey && o.privateJwk) return o;
} catch { /* regenerate below */ }
}
const pair = await crypto.subtle.generateKey({ name: 'ECDSA', namedCurve: 'P-256' }, true, ['sign']);
const publicKey = b64uEncode(await crypto.subtle.exportKey('raw', pair.publicKey));
const privateJwk = await crypto.subtle.exportKey('jwk', pair.privateKey);
const o = { publicKey, privateJwk };
await env.POSSUMS_KV.put(VAPID_KEY, JSON.stringify(o));
return o;
};
const readSubs = async (env) => {
const raw = await env.POSSUMS_KV.get(PUSH_SUBS_KEY);
const out = { parent1: [], parent2: [] };
if (!raw) return out;
try {
const o = JSON.parse(raw);
for (const who of WHO_VALUES) if (Array.isArray(o[who])) out[who] = o[who];
} catch { /* empty */ }
return out;
};
const writeSubs = (env, subs) => env.POSSUMS_KV.put(PUSH_SUBS_KEY, JSON.stringify(subs));
const hkdf = async (salt, ikm, info, bytes) => {
const key = await crypto.subtle.importKey('raw', ikm, 'HKDF', false, ['deriveBits']);
return new Uint8Array(await crypto.subtle.deriveBits({ name: 'HKDF', hash: 'SHA-256', salt, info }, key, bytes * 8));
};
// RFC 8291 aes128gcm payload encryption.
async function encryptPayload(sub, payload) {
const uaPublic = b64uDecode(sub.keys.p256dh);
const authSecret = b64uDecode(sub.keys.auth);
const eph = await crypto.subtle.generateKey({ name: 'ECDH', namedCurve: 'P-256' }, true, ['deriveBits']);
const asPublic = new Uint8Array(await crypto.subtle.exportKey('raw', eph.publicKey));
const uaKey = await crypto.subtle.importKey('raw', uaPublic, { name: 'ECDH', namedCurve: 'P-256' }, false, []);
const ecdh = new Uint8Array(await crypto.subtle.deriveBits({ name: 'ECDH', public: uaKey }, eph.privateKey, 256));
const prk = await hkdf(authSecret, ecdh, concatBytes(utf8('WebPush: info\0'), uaPublic, asPublic), 32);
const salt = crypto.getRandomValues(new Uint8Array(16));
const cek = await hkdf(salt, prk, utf8('Content-Encoding: aes128gcm\0'), 16);
const nonce = await hkdf(salt, prk, utf8('Content-Encoding: nonce\0'), 12);
const aes = await crypto.subtle.importKey('raw', cek, 'AES-GCM', false, ['encrypt']);
const plain = concatBytes(utf8(payload), new Uint8Array([2]));
const cipher = new Uint8Array(await crypto.subtle.encrypt({ name: 'AES-GCM', iv: nonce }, aes, plain));
const header = new Uint8Array(21);
header.set(salt, 0);
new DataView(header.buffer).setUint32(16, 4096);
header[20] = asPublic.length;
return concatBytes(header, asPublic, cipher);
}
async function vapidAuth(vapid, endpoint, subject) {
const aud = new URL(endpoint).origin;
const head = b64uEncode(utf8(JSON.stringify({ typ: 'JWT', alg: 'ES256' })));
const claims = b64uEncode(utf8(JSON.stringify({ aud, exp: Math.floor(Date.now() / 1000) + 12 * 3600, sub: subject })));
const key = await crypto.subtle.importKey('jwk', vapid.privateJwk, { name: 'ECDSA', namedCurve: 'P-256' }, false, ['sign']);
const sig = await crypto.subtle.sign({ name: 'ECDSA', hash: 'SHA-256' }, key, utf8(`${head}.${claims}`));
return `vapid t=${head}.${claims}.${b64uEncode(sig)}, k=${vapid.publicKey}`;
}
// status: 'ok', 'gone' (subscription dead, drop it) or 'error'.
async function sendOnePush(vapid, sub, payload) {
try {
const body = await encryptPayload(sub, JSON.stringify(payload));
const r = await fetch(sub.endpoint, {
method: 'POST',
headers: {
Authorization: await vapidAuth(vapid, sub.endpoint, sub.subject || 'https://possums.invalid'),
'Content-Encoding': 'aes128gcm',
'Content-Type': 'application/octet-stream',
TTL: '86400',
Urgency: 'high',
},
body,
});
if (r.ok) return { status: 'ok' };
const text = await r.text().catch(() => '');
console.log('push send failed', r.status, text);
return { status: r.status === 404 || r.status === 410 ? 'gone' : 'error', detail: `${r.status} ${text}` };
} catch (err) {
console.log('push send failed', err);
return { status: 'error', detail: String(err) };
}
}
// Push to every device registered for the given parents; prunes dead subscriptions.
async function pushToParents(env, whos, payload) {
const subs = await readSubs(env);
const targets = whos.flatMap((w) => subs[w].map((sub) => ({ who: w, sub })));
if (!targets.length) return { sent: 0, failed: 0, errors: [] };
const vapid = await getVapid(env);
const results = await Promise.all(targets.map((t) => sendOnePush(vapid, t.sub, payload)));
const dead = new Set(targets.filter((_, i) => results[i].status === 'gone').map((t) => t.sub.endpoint));
if (dead.size) {
for (const w of WHO_VALUES) subs[w] = subs[w].filter((x) => !dead.has(x.endpoint));
await writeSubs(env, subs);
}
return {
sent: results.filter((r) => r.status === 'ok').length,
failed: results.filter((r) => r.status !== 'ok').length,
errors: results.filter((r) => r.detail).map((r) => r.detail),
};
}
async function sendPush(env, loggedBy, message) {
if (!loggedBy || !message) return;
const other = loggedBy === 'parent1' ? 'parent2' : 'parent1';
const parents = await readParents(env);
const title = parents[loggedBy] || (loggedBy === 'parent1' ? 'Parent 1' : 'Parent 2');
await pushToParents(env, [other], { title, body: message, url: '/' });
}
const fireNotify = (env, ctx, loggedBy, message) => {
const p = sendPush(env, loggedBy, message).catch((err) => console.log('notify failed', err));
if (ctx?.waitUntil) ctx.waitUntil(p);
};
const fmtDur = (sec) => {
const s = Math.max(0, Math.floor(sec));
const h = Math.floor(s / 3600);
const m = Math.floor((s % 3600) / 60);
if (h > 0) return `${h}h ${m}m`;
if (m > 0) return `${m}m`;
return `${s}s`;
};
const NAPPY_LABEL = { wet: 'wet', dirty: 'dirty', both: 'wet + dirty' };
function summarizeFeed(f) {
if (f.kind === 'breast_l' || f.kind === 'breast_r') {
const side = f.kind === 'breast_l' ? 'left' : 'right';
const dur = f.duration_seconds ? ` for ${fmtDur(f.duration_seconds)}` : '';
return `Breastfed (${side})${dur}`;
}
if (f.kind === 'solid') {
return f.amount_ml != null ? `Gave ${f.amount_ml}g of solids` : 'Gave solids';
}
if (f.amount_ml != null && f.started_ml != null) return `Gave a ${f.amount_ml}ml bottle (offered ${f.started_ml}ml)`;
if (f.amount_ml != null) return `Gave a ${f.amount_ml}ml bottle`;
return 'Gave a bottle';
}
function summarizeSimple(name, row) {
switch (name) {
case 'feeds': return summarizeFeed(row);
case 'nappies': return `Changed a ${NAPPY_LABEL[row.kind] ?? row.kind} nappy`;
case 'spitups': return `Logged a ${row.kind} spit-up`;
case 'meds': {
const dose = row.dose != null ? ` ${row.dose}${row.unit ?? ''}` : '';
return `Gave ${row.name}${dose}`;
}
case 'growths': {
const parts = [];
if (row.weight_kg) parts.push(`${row.weight_kg}kg`);
if (row.height_cm) parts.push(`${row.height_cm}cm`);
if (row.head_cm) parts.push(`head ${row.head_cm}cm`);
return parts.length ? `Logged growth (${parts.join(', ')})` : 'Logged growth';
}
case 'baths': return 'Gave a bath';
case 'milestones': return `Milestone: ${row.title}`;
case 'temps': return `Took temperature (${row.temp_c.toFixed(1)}°C)`;
}
return 'Logged an activity';
}
function summarizeTimedStart(name) {
if (name === 'naps') return 'Started a sleep';
if (name === 'pumps') return 'Started pumping';
if (name === 'tummy_times') return 'Started tummy time';
return 'Started a timer';
}
function summarizeTimedEnd(name, row) {
const ms = new Date(row.ended_at).getTime() - new Date(row.started_at).getTime();
const dur = fmtDur(Math.floor(ms / 1000));
if (name === 'naps') return `Ended sleep (${dur})`;
if (name === 'pumps') {
const ml = (row.ml_left ?? 0) + (row.ml_right ?? 0);
return ml > 0 ? `Ended pumping (${dur}, ${ml}ml)` : `Ended pumping (${dur})`;
}
if (name === 'tummy_times') return `Ended tummy time (${dur})`;
return `Ended timer (${dur})`;
}
const escapeAttr = (s) =>
String(s).replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
const getWho = (request) => {
const v = getCookie(request, WHO_COOKIE);
return WHO_VALUES.includes(v) ? v : null;
};
const enc = new TextEncoder();
const randomHex = (n) =>
[...crypto.getRandomValues(new Uint8Array(n))].map((b) => b.toString(16).padStart(2, '0')).join('');
const hexToBytes = (hex) => new Uint8Array(hex.match(/.{1,2}/g)?.map((h) => parseInt(h, 16)) ?? []);
async function pbkdf2Hex(password, saltHex) {
const baseKey = await crypto.subtle.importKey(
'raw', enc.encode(password), { name: 'PBKDF2' }, false, ['deriveBits']
);
const bits = await crypto.subtle.deriveBits(
{ name: 'PBKDF2', hash: 'SHA-256', salt: hexToBytes(saltHex), iterations: PBKDF2_ITERS },
baseKey, 256
);
return [...new Uint8Array(bits)].map((b) => b.toString(16).padStart(2, '0')).join('');
}
const readAuthKV = async (env) => {
const raw = await env.POSSUMS_KV.get(AUTH_KEY);
if (!raw) return null;
try { return JSON.parse(raw); } catch { return null; }
};
const isSetupNeeded = async (env) => {
if (await env.POSSUMS_KV.get(AUTH_KEY)) return false;
return !env.PASSWORD;
};
const checkPassword = async (env, password) => {
if (typeof password !== 'string' || !password) return false;
const kvAuth = await readAuthKV(env);
if (kvAuth?.salt && kvAuth?.hash) {
const candidate = await pbkdf2Hex(password, kvAuth.salt);
if (candidate.length !== kvAuth.hash.length) return false;
let diff = 0;
for (let i = 0; i < candidate.length; i++) diff |= candidate.charCodeAt(i) ^ kvAuth.hash.charCodeAt(i);
return diff === 0;
}
return env.PASSWORD ? password === env.PASSWORD : false;
};
const getSessionSecret = async (env) => {
const kvSecret = await env.POSSUMS_KV.get(SECRET_KEY);
return kvSecret ?? env.SESSION_SECRET ?? '';
};
async function hmacHex(secret, data) {
const key = await crypto.subtle.importKey(
'raw', enc.encode(secret),
{ name: 'HMAC', hash: 'SHA-256' }, false, ['sign']
);
const sig = await crypto.subtle.sign('HMAC', key, enc.encode(data));
return [...new Uint8Array(sig)].map((b) => b.toString(16).padStart(2, '0')).join('');
}
async function signSession(secret) {
return `${SESSION_VALUE}.${await hmacHex(secret, SESSION_VALUE)}`;
}
async function verifySession(secret, token) {
if (!token) return false;
const i = token.lastIndexOf('.');
if (i < 0) return false;
const value = token.slice(0, i);
const tag = token.slice(i + 1);
if (value !== SESSION_VALUE) return false;
const expected = await hmacHex(secret, value);
if (tag.length !== expected.length) return false;
let diff = 0;
for (let j = 0; j < tag.length; j++) diff |= tag.charCodeAt(j) ^ expected.charCodeAt(j);
return diff === 0;
}
function getCookie(request, name) {
const header = request.headers.get('Cookie');
if (!header) return null;
for (const part of header.split(';')) {
const [k, ...rest] = part.trim().split('=');
if (k === name) return rest.join('=');
}
return null;
}
async function isAuthed(request, env) {
const secret = await getSessionSecret(env);
if (!secret) return false;
return verifySession(secret, getCookie(request, COOKIE_NAME));
}
function json(body, init = {}) {
return new Response(JSON.stringify(body), {
...init,
headers: { 'content-type': 'application/json', ...(init.headers || {}) },
});
}
const badRequest = (msg) => json({ error: msg }, { status: 400 });
const renderLoginHtml = (err = '', name = '') => `<!doctype html>
<html lang="en-AU">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<meta name="theme-color" content="#fbf7f0">
<title>Possums – Sign in</title>
<link rel="icon" type="image/svg+xml" href="/favicon.svg">
<link rel="stylesheet" href="/styles.css">
<style>
body { background: #fbf7f0; }
.login { min-height: 100dvh; display: grid; place-items: center; padding: 24px; }
.login__card { width: 100%; max-width: 320px; display: grid; gap: 16px; }
.login__title { text-align: center; font-size: 32px; margin: 0; font-weight: 600; }
.login__form { display: grid; gap: 12px; }
.login__input { font: inherit; padding: 14px 16px; border: 1px solid #d8cfbf; border-radius: 14px; background: #fff; }
.login__btn { font: inherit; padding: 14px; border-radius: 14px; border: 0; background: #2c2620; color: #fff; font-weight: 600; cursor: pointer; }
.login__err { color: #b3261e; font-size: 14px; text-align: center; min-height: 1em; margin: 0; }
.login__forgot { font: inherit; font-size: 14px; background: none; border: 0; color: #6b6258; cursor: pointer; text-decoration: underline; padding: 4px; justify-self: center; }
.login__forgot:disabled { opacity: .5; cursor: default; }
.login__forgot-msg { font-size: 13px; text-align: center; min-height: 1em; margin: 0; color: #6b6258; }
</style>
</head>
<body>
<main class="login">
<div class="login__card">
<h1 class="login__title">Possums</h1>
<form class="login__form" method="post" action="/login">
<input class="login__input" type="text" name="name" placeholder="Your name" autocomplete="username" autocapitalize="words" autofocus required value="${escapeAttr(name)}">
<input class="login__input" type="password" name="password" placeholder="Password" autocomplete="current-password" required>
<button class="login__btn" type="submit">Sign in</button>
<p class="login__err">${escapeAttr(err)}</p>
</form>
<button class="login__forgot" id="forgotBtn" type="button">Forgot password?</button>
<p class="login__forgot-msg" id="forgotMsg"></p>
<script>
document.getElementById('forgotBtn').addEventListener('click', async function() {
const btn = this;
const msg = document.getElementById('forgotMsg');
btn.disabled = true;
msg.textContent = 'Sending…';
try {
const r = await fetch('/forgot', { method: 'POST' });
const j = await r.json();
msg.textContent = j.ok ? 'Reset link sent to your devices.' : (j.error || 'Failed.');
if (!j.ok) btn.disabled = false;
} catch {
msg.textContent = 'Network error.';
btn.disabled = false;
}
});
</script>
</div>
</main>
</body>
</html>`;
function loginPage(err = '', name = '') {
return new Response(renderLoginHtml(err, name), {
headers: { 'content-type': 'text/html; charset=utf-8' },
});
}
function cookieFlags(url) {
const secure = url.protocol === 'https:' ? '; Secure' : '';
return `Path=/; HttpOnly; SameSite=Lax${secure}`;
}
async function handleLogin(request, env, url) {
const form = await request.formData();
const typedName = String(form.get('name') ?? '').trim();
const typedPwd = String(form.get('password') ?? '');
const parents = await readParents(env);
const norm = (s) => s.trim().toLowerCase();
let who = null;
if (typedName && norm(parents.parent1) === norm(typedName)) who = 'parent1';
else if (typedName && norm(parents.parent2) === norm(typedName)) who = 'parent2';
if (!who) return loginPage('Name not recognised.', typedName);
if (!(await checkPassword(env, typedPwd))) return loginPage('Wrong password.', typedName);
const secret = await getSessionSecret(env);
const token = await signSession(secret);
const flags = cookieFlags(url);
const headers = new Headers({ Location: '/' });
headers.append('Set-Cookie', `${COOKIE_NAME}=${token}; Max-Age=${COOKIE_MAX_AGE}; ${flags}`);
headers.append('Set-Cookie', `${WHO_COOKIE}=${who}; Max-Age=${COOKIE_MAX_AGE}; ${flags}`);
return new Response(null, { status: 302, headers });
}
function logoutResponse(url) {
const flags = cookieFlags(url);
const headers = new Headers({ Location: '/login' });
headers.append('Set-Cookie', `${COOKIE_NAME}=; Max-Age=0; ${flags}`);
headers.append('Set-Cookie', `${WHO_COOKIE}=; Max-Age=0; ${flags}`);
return new Response(null, { status: 302, headers });
}
const renderSetupHtml = (err = '', vals = {}) => `<!doctype html>
<html lang="en-AU">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<meta name="theme-color" content="#fbf7f0">
<title>Possums – Setup</title>
<link rel="icon" type="image/svg+xml" href="/favicon.svg">
<link rel="stylesheet" href="/styles.css">
<style>
body { background: #fbf7f0; }
.setup { min-height: 100dvh; display: grid; place-items: center; padding: 24px; }
.setup__card { width: 100%; max-width: 380px; display: grid; gap: 16px; }
.setup__title { text-align: center; font-size: 32px; margin: 0; font-weight: 600; }
.setup__intro { text-align: center; color: #6b6258; margin: 0; }
.setup__form { display: grid; gap: 12px; }
.setup__form label { display: grid; gap: 6px; font-size: 14px; color: #6b6258; }
.setup__input { font: inherit; padding: 14px 16px; border: 1px solid #d8cfbf; border-radius: 14px; background: #fff; }
.setup__btn { font: inherit; padding: 14px; border-radius: 14px; border: 0; background: #2c2620; color: #fff; font-weight: 600; cursor: pointer; }
.setup__err { color: #b3261e; font-size: 14px; text-align: center; min-height: 1em; margin: 0; }
.setup__hint { font-size: 12px; color: #8a8275; margin: 0; }
</style>
</head>
<body>
<main class="setup">
<div class="setup__card">
<h1 class="setup__title">Welcome to Possums</h1>
<p class="setup__intro">Set up your tracker in one go. You'll sign in with a parent name + the password you choose here.</p>
<form class="setup__form" method="post" action="/setup">
<label>Parent 1 name
<input class="setup__input" type="text" name="parent1" required maxlength="60" autocapitalize="words" value="${escapeAttr(vals.parent1 ?? '')}">
</label>
<label>Parent 2 name
<input class="setup__input" type="text" name="parent2" required maxlength="60" autocapitalize="words" value="${escapeAttr(vals.parent2 ?? '')}">
</label>
<label>Shared password
<input class="setup__input" type="password" name="password" required minlength="6" autocomplete="new-password">
</label>
<label>Confirm password
<input class="setup__input" type="password" name="password2" required minlength="6" autocomplete="new-password">
</label>
<p class="setup__hint">Both parents share this password. Sign in by typing your name + the password.</p>
<button class="setup__btn" type="submit">Finish setup</button>
<p class="setup__err">${escapeAttr(err)}</p>
</form>
</div>
</main>
</body>
</html>`;
function setupPage(err = '', vals = {}) {
return new Response(renderSetupHtml(err, vals), {
headers: { 'content-type': 'text/html; charset=utf-8' },
});
}
async function handleSetup(request, env, url) {
if (!(await isSetupNeeded(env))) {
return new Response(null, { status: 302, headers: { Location: '/login' } });
}
if (request.method === 'GET') return setupPage();
if (request.method !== 'POST') return new Response('Method not allowed', { status: 405 });
const form = await request.formData();
const parent1 = String(form.get('parent1') ?? '').trim();
const parent2 = String(form.get('parent2') ?? '').trim();
const password = String(form.get('password') ?? '');
const password2 = String(form.get('password2') ?? '');
const vals = { parent1, parent2 };
if (!parent1 || !parent2) return setupPage('Both parent names are required.', vals);
if (parent1.length > 60 || parent2.length > 60) return setupPage('Names must be 60 characters or fewer.', vals);
if (parent1.trim().toLowerCase() === parent2.trim().toLowerCase()) {
return setupPage('Parent names must be different.', vals);
}
if (password.length < 6) return setupPage('Password must be at least 6 characters.', vals);
if (password !== password2) return setupPage('Passwords do not match.', vals);
const salt = randomHex(16);
const hash = await pbkdf2Hex(password, salt);
const secret = randomHex(32);
await env.POSSUMS_KV.put(PARENTS_KEY, JSON.stringify({ parent1, parent2 }));
await env.POSSUMS_KV.put(AUTH_KEY, JSON.stringify({ salt, hash, iters: PBKDF2_ITERS, alg: 'pbkdf2-sha256' }));
await env.POSSUMS_KV.put(SECRET_KEY, secret);
const token = await signSession(secret);
const flags = cookieFlags(url);
const headers = new Headers({ Location: '/' });
headers.append('Set-Cookie', `${COOKIE_NAME}=${token}; Max-Age=${COOKIE_MAX_AGE}; ${flags}`);
headers.append('Set-Cookie', `${WHO_COOKIE}=parent1; Max-Age=${COOKIE_MAX_AGE}; ${flags}`);
return new Response(null, { status: 302, headers });
}
async function handleChangePassword(request, env) {
if (request.method !== 'POST') return new Response('Method not allowed', { status: 405 });
const b = await readBody(request);
if (!b) return badRequest('json required');
const current = String(b.current ?? '');
const next = String(b.next ?? '');
if (next.length < 6) return badRequest('new password must be at least 6 characters');
if (!(await checkPassword(env, current))) return json({ error: 'current password is wrong' }, { status: 401 });
const salt = randomHex(16);
const hash = await pbkdf2Hex(next, salt);
await env.POSSUMS_KV.put(AUTH_KEY, JSON.stringify({ salt, hash, iters: PBKDF2_ITERS, alg: 'pbkdf2-sha256' }));
return json({ ok: true });
}
async function handleForgot(request, env, url) {
if (request.method !== 'POST') return new Response('Method not allowed', { status: 405 });
const last = await env.POSSUMS_KV.get(RESET_COOLDOWN_KEY);
if (last && Date.now() - Number(last) < 86400000) {
return json({ error: 'Reset link already sent today.' }, { status: 429 });
}
const subs = await readSubs(env);
if (!subs.parent1.length && !subs.parent2.length) {
return json({ error: 'No devices have notifications enabled.' }, { status: 400 });
}
const token = randomHex(32);
const link = `${url.origin}/reset?token=${token}`;
const res = await pushToParents(env, WHO_VALUES, { title: 'Possums password reset', body: 'Tap to reset your password.', url: link });
if (!res.sent) return json({ error: 'Could not deliver the reset link.' }, { status: 502 });
await env.POSSUMS_KV.put(RESET_TOKEN_KEY, token, { expirationTtl: 3600 });
await env.POSSUMS_KV.put(RESET_COOLDOWN_KEY, String(Date.now()), { expirationTtl: 86400 });
return json({ ok: true });
}
const renderResetHtml = (parents, err = '') => `<!doctype html>
<html lang="en-AU">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<meta name="theme-color" content="#fbf7f0">
<title>Possums – Reset password</title>
<link rel="icon" type="image/svg+xml" href="/favicon.svg">
<link rel="stylesheet" href="/styles.css">
<style>
body { background: #fbf7f0; }
.reset { min-height: 100dvh; display: grid; place-items: center; padding: 24px; }
.reset__card { width: 100%; max-width: 320px; display: grid; gap: 16px; }
.reset__title { text-align: center; font-size: 24px; margin: 0; font-weight: 600; }
.reset__form { display: grid; gap: 12px; }
.reset__label { display: grid; gap: 6px; font-size: 14px; color: #6b6258; }
.reset__input, .reset__select { font: inherit; padding: 14px 16px; border: 1px solid #d8cfbf; border-radius: 14px; background: #fff; }
.reset__btn { font: inherit; padding: 14px; border-radius: 14px; border: 0; background: #2c2620; color: #fff; font-weight: 600; cursor: pointer; }
.reset__err { color: #b3261e; font-size: 14px; text-align: center; min-height: 1em; margin: 0; }
</style>
</head>
<body>
<main class="reset">
<div class="reset__card">
<h1 class="reset__title">Reset password</h1>
<form class="reset__form" method="post">
<label class="reset__label">Sign in as
<select class="reset__select" name="who">
<option value="parent1">${escapeAttr(parents.parent1)}</option>
<option value="parent2">${escapeAttr(parents.parent2)}</option>
</select>
</label>
<label class="reset__label">New password
<input class="reset__input" type="password" name="password" required minlength="6" autocomplete="new-password">
</label>
<label class="reset__label">Confirm password
<input class="reset__input" type="password" name="password2" required minlength="6" autocomplete="new-password">
</label>
<button class="reset__btn" type="submit">Reset password</button>
<p class="reset__err">${escapeAttr(err)}</p>
</form>
</div>
</main>
</body>
</html>`;
async function handleReset(request, env, url) {
const token = url.searchParams.get('token') ?? '';
const stored = await env.POSSUMS_KV.get(RESET_TOKEN_KEY);
if (!token || !stored || token !== stored) {
return new Response(renderLoginHtml('Reset link is invalid or expired.'), {
headers: { 'content-type': 'text/html; charset=utf-8' },
});
}
const parents = await readParents(env);
if (request.method === 'GET') {
return new Response(renderResetHtml(parents), {
headers: { 'content-type': 'text/html; charset=utf-8' },
});
}
if (request.method !== 'POST') return new Response('Method not allowed', { status: 405 });
const form = await request.formData();
const who = String(form.get('who') ?? '');
const password = String(form.get('password') ?? '');
const password2 = String(form.get('password2') ?? '');
if (!WHO_VALUES.includes(who)) {
return new Response(renderResetHtml(parents, 'Pick an account.'), {
headers: { 'content-type': 'text/html; charset=utf-8' },
});
}
if (password.length < 6) {
return new Response(renderResetHtml(parents, 'Password must be at least 6 characters.'), {
headers: { 'content-type': 'text/html; charset=utf-8' },
});
}
if (password !== password2) {
return new Response(renderResetHtml(parents, 'Passwords do not match.'), {
headers: { 'content-type': 'text/html; charset=utf-8' },
});
}
const salt = randomHex(16);
const hash = await pbkdf2Hex(password, salt);
await env.POSSUMS_KV.put(AUTH_KEY, JSON.stringify({ salt, hash, iters: PBKDF2_ITERS, alg: 'pbkdf2-sha256' }));
await env.POSSUMS_KV.delete(RESET_TOKEN_KEY);
const secret = await getSessionSecret(env);
const sessionToken = await signSession(secret);
const flags = cookieFlags(url);
const headers = new Headers({ Location: '/' });
headers.append('Set-Cookie', `${COOKIE_NAME}=${sessionToken}; Max-Age=${COOKIE_MAX_AGE}; ${flags}`);
headers.append('Set-Cookie', `${WHO_COOKIE}=${who}; Max-Age=${COOKIE_MAX_AGE}; ${flags}`);
return new Response(null, { status: 302, headers });
}
/* ---------- data layer ---------- */
const readList = async (env, key) => {
const raw = await env.POSSUMS_KV.get(key);
return raw ? JSON.parse(raw) : [];
};
const writeList = (env, key, list) => env.POSSUMS_KV.put(key, JSON.stringify(list));
const nowSec = () => new Date().toISOString().slice(0, 19);
const nextId = (list) => {
let m = 0;
for (const r of list) if (r.id > m) m = r.id;
return m + 1;
};
const topNBy = (list, field, limit) =>
[...list].sort((a, b) => (a[field] < b[field] ? 1 : a[field] > b[field] ? -1 : 0)).slice(0, limit);
const parseLimit = (url, def = 50, max = 500) => {
const n = Number(url.searchParams.get('limit')) || def;
return Math.min(Math.max(1, n), max);
};
const readBody = async (request) => {
try { return await request.json(); } catch { return null; }
};
const isStr = (v, min = 0, max = Infinity) =>
typeof v === 'string' && v.length >= min && v.length <= max;
const isStrOrNull = (v, max) =>
v == null || (typeof v === 'string' && v.length <= max);
const isIntOrNull = (v, min, max) =>
v == null || (Number.isInteger(v) && v >= min && v <= max);
const isNumOrNull = (v, min, max) =>
v == null || (typeof v === 'number' && Number.isFinite(v) && v >= min && v <= max);
const mergeDefined = (existing, b, fields) => {
const out = { ...existing };
for (const f of fields) if (f in b) out[f] = b[f];
return out;
};
const simple = {
feeds: {
key: 'feeds',
tf: 'started_at',
validate(b) {
if (!isStr(b.started_at, 10)) return 'started_at required';
if (b.kind !== undefined && !FEED_KINDS.includes(b.kind)) return 'bad kind';
if (!isIntOrNull(b.amount_ml, 0, 2000)) return 'bad amount_ml';
if (!isIntOrNull(b.started_ml, 0, 2000)) return 'bad started_ml';
if (!isIntOrNull(b.duration_seconds, 0, 36000)) return 'bad duration_seconds';
if (!isStrOrNull(b.notes, 500)) return 'bad notes';
return null;
},
build(b) {
return {
started_at: b.started_at,
kind: b.kind ?? 'bottle',
amount_ml: b.amount_ml ?? null,
started_ml: b.started_ml ?? null,
duration_seconds: b.duration_seconds ?? null,
notes: b.notes ?? null,
};
},
validatePatch(b) {
if (b.started_at !== undefined && !isStr(b.started_at, 10)) return 'bad started_at';
if (b.kind !== undefined && !FEED_KINDS.includes(b.kind)) return 'bad kind';
if (b.amount_ml !== undefined && !isIntOrNull(b.amount_ml, 0, 2000)) return 'bad amount_ml';
if (b.started_ml !== undefined && !isIntOrNull(b.started_ml, 0, 2000)) return 'bad started_ml';
if (b.duration_seconds !== undefined && !isIntOrNull(b.duration_seconds, 0, 36000)) return 'bad duration_seconds';
if (b.notes !== undefined && !isStrOrNull(b.notes, 500)) return 'bad notes';
return null;
},
applyPatch(existing, b) {
return mergeDefined(existing, b, ['started_at', 'kind', 'amount_ml', 'started_ml', 'duration_seconds', 'notes']);
},
},
nappies: {
key: 'nappies',
tf: 'changed_at',
validate(b) {
if (!isStr(b.changed_at, 10)) return 'changed_at required';
if (!NAPPY_KINDS.includes(b.kind)) return 'bad kind';
if (!isStrOrNull(b.notes, 500)) return 'bad notes';
return null;
},
build(b) { return { changed_at: b.changed_at, kind: b.kind, notes: b.notes ?? null }; },
validatePatch(b) {
if (b.changed_at !== undefined && !isStr(b.changed_at, 10)) return 'bad changed_at';
if (b.kind !== undefined && !NAPPY_KINDS.includes(b.kind)) return 'bad kind';
if (b.notes !== undefined && !isStrOrNull(b.notes, 500)) return 'bad notes';
return null;
},
applyPatch(existing, b) {
return mergeDefined(existing, b, ['changed_at', 'kind', 'notes']);
},
},
spitups: {
key: 'spitups',
tf: 'happened_at',
validate(b) {
if (!isStr(b.happened_at, 10)) return 'happened_at required';
if (!SPITUP_KINDS.includes(b.kind)) return 'bad kind';
if (!isStrOrNull(b.notes, 500)) return 'bad notes';
return null;
},
build(b) { return { happened_at: b.happened_at, kind: b.kind, notes: b.notes ?? null }; },
validatePatch(b) {
if (b.happened_at !== undefined && !isStr(b.happened_at, 10)) return 'bad happened_at';
if (b.kind !== undefined && !SPITUP_KINDS.includes(b.kind)) return 'bad kind';
if (b.notes !== undefined && !isStrOrNull(b.notes, 500)) return 'bad notes';
return null;
},
applyPatch(existing, b) {
return mergeDefined(existing, b, ['happened_at', 'kind', 'notes']);
},
},
meds: {
key: 'meds',
tf: 'given_at',
validate(b) {
if (!isStr(b.given_at, 10)) return 'given_at required';
if (!isStr(b.name, 1, 120)) return 'name required';
if (!isNumOrNull(b.dose, 0, 10000)) return 'bad dose';
if (!isStrOrNull(b.unit, 20)) return 'bad unit';
if (!isStrOrNull(b.notes, 500)) return 'bad notes';
return null;
},
build(b) {
return {
given_at: b.given_at, name: b.name.trim(),
dose: b.dose ?? null, unit: b.unit ?? null, notes: b.notes ?? null,
};
},
validatePatch(b) {
if (b.given_at !== undefined && !isStr(b.given_at, 10)) return 'bad given_at';
if (b.name !== undefined && !isStr(b.name, 1, 120)) return 'bad name';
if (b.dose !== undefined && !isNumOrNull(b.dose, 0, 10000)) return 'bad dose';
if (b.unit !== undefined && !isStrOrNull(b.unit, 20)) return 'bad unit';
if (b.notes !== undefined && !isStrOrNull(b.notes, 500)) return 'bad notes';
return null;
},
applyPatch(existing, b) {
const patched = mergeDefined(existing, b, ['given_at', 'name', 'dose', 'unit', 'notes']);
if (typeof patched.name === 'string') patched.name = patched.name.trim();
return patched;
},
},
growths: {
key: 'growths',
tf: 'measured_at',
validate(b) {
if (!isStr(b.measured_at, 10)) return 'measured_at required';
if (!isNumOrNull(b.weight_kg, 0, 50)) return 'bad weight_kg';
if (!isNumOrNull(b.height_cm, 0, 200)) return 'bad height_cm';
if (!isNumOrNull(b.head_cm, 0, 100)) return 'bad head_cm';
if (!isStrOrNull(b.notes, 500)) return 'bad notes';
return null;
},
build(b) {
return {
measured_at: b.measured_at,
weight_kg: b.weight_kg ?? null,
height_cm: b.height_cm ?? null,
head_cm: b.head_cm ?? null,
notes: b.notes ?? null,
};
},
validatePatch(b) {
if (b.measured_at !== undefined && !isStr(b.measured_at, 10)) return 'bad measured_at';
if (b.weight_kg !== undefined && !isNumOrNull(b.weight_kg, 0, 50)) return 'bad weight_kg';
if (b.height_cm !== undefined && !isNumOrNull(b.height_cm, 0, 200)) return 'bad height_cm';
if (b.head_cm !== undefined && !isNumOrNull(b.head_cm, 0, 100)) return 'bad head_cm';
if (b.notes !== undefined && !isStrOrNull(b.notes, 500)) return 'bad notes';
return null;
},
applyPatch(existing, b) {
return mergeDefined(existing, b, ['measured_at', 'weight_kg', 'height_cm', 'head_cm', 'notes']);
},
},
baths: {
key: 'baths',
tf: 'bathed_at',
validate(b) {
if (!isStr(b.bathed_at, 10)) return 'bathed_at required';
if (!isStrOrNull(b.notes, 500)) return 'bad notes';
return null;
},
build(b) { return { bathed_at: b.bathed_at, notes: b.notes ?? null }; },
validatePatch(b) {
if (b.bathed_at !== undefined && !isStr(b.bathed_at, 10)) return 'bad bathed_at';
if (b.notes !== undefined && !isStrOrNull(b.notes, 500)) return 'bad notes';
return null;
},
applyPatch(existing, b) {
return mergeDefined(existing, b, ['bathed_at', 'notes']);
},
},
milestones: {
key: 'milestones',
tf: 'reached_at',
validate(b) {
if (!isStr(b.reached_at, 10)) return 'reached_at required';
if (!isStr(b.title, 1, 120)) return 'title required';
if (!isStrOrNull(b.notes, 500)) return 'bad notes';
return null;
},
build(b) { return { reached_at: b.reached_at, title: b.title.trim(), notes: b.notes ?? null }; },
validatePatch(b) {
if (b.reached_at !== undefined && !isStr(b.reached_at, 10)) return 'bad reached_at';
if (b.title !== undefined && !isStr(b.title, 1, 120)) return 'bad title';
if (b.notes !== undefined && !isStrOrNull(b.notes, 500)) return 'bad notes';
return null;
},
applyPatch(existing, b) {
const patched = mergeDefined(existing, b, ['reached_at', 'title', 'notes']);
if (typeof patched.title === 'string') patched.title = patched.title.trim();
return patched;
},
},
temps: {
key: 'temps',
tf: 'taken_at',
validate(b) {
if (!isStr(b.taken_at, 10)) return 'taken_at required';
if (!isNumOrNull(b.temp_c, 25, 45) || b.temp_c == null) return 'bad temp_c';
if (!isStrOrNull(b.notes, 500)) return 'bad notes';
return null;
},
build(b) { return { taken_at: b.taken_at, temp_c: b.temp_c, notes: b.notes ?? null }; },
validatePatch(b) {
if (b.taken_at !== undefined && !isStr(b.taken_at, 10)) return 'bad taken_at';
if (b.temp_c !== undefined && !isNumOrNull(b.temp_c, 25, 45)) return 'bad temp_c';
if (b.temp_c === null) return 'bad temp_c';
if (b.notes !== undefined && !isStrOrNull(b.notes, 500)) return 'bad notes';
return null;
},
applyPatch(existing, b) {
return mergeDefined(existing, b, ['taken_at', 'temp_c', 'notes']);
},
},
};
const timed = {
naps: {
key: 'naps',
tf: 'started_at',
label: 'nap',
validateStart(b) {
if (!isStr(b.started_at, 10)) return 'started_at required';
if (b.ended_at != null && !isStr(b.ended_at, 10)) return 'bad ended_at';
if (!isStrOrNull(b.notes, 500)) return 'bad notes';
return null;
},
buildStart(b) { return { started_at: b.started_at, ended_at: b.ended_at ?? null, notes: b.notes ?? null }; },
validatePatch(b) {
if (b.started_at !== undefined && !isStr(b.started_at, 10)) return 'bad started_at';
if (b.ended_at !== undefined && b.ended_at !== null && !isStr(b.ended_at, 10)) return 'bad ended_at';
if (b.notes !== undefined && !isStrOrNull(b.notes, 500)) return 'bad notes';
return null;
},
applyPatch(existing, b) {
return {
...existing,
started_at: b.started_at ?? existing.started_at,
ended_at: 'ended_at' in b ? b.ended_at : existing.ended_at,
notes: 'notes' in b ? b.notes : existing.notes,
};
},
applyEnd(existing, b) { return { ...existing, ended_at: b?.ended_at ?? nowSec() }; },
},
pumps: {
key: 'pumps',
tf: 'started_at',
label: 'pump',
validateStart(b) {
if (!isStr(b.started_at, 10)) return 'started_at required';
if (b.ended_at != null && !isStr(b.ended_at, 10)) return 'bad ended_at';
if (!isIntOrNull(b.ml_left, 0, 2000)) return 'bad ml_left';
if (!isIntOrNull(b.ml_right, 0, 2000)) return 'bad ml_right';
if (!isStrOrNull(b.notes, 500)) return 'bad notes';
return null;
},
buildStart(b) {
return {
started_at: b.started_at, ended_at: b.ended_at ?? null,
ml_left: b.ml_left ?? null, ml_right: b.ml_right ?? null, notes: b.notes ?? null,
};
},
validatePatch(b) {
if (b.started_at !== undefined && !isStr(b.started_at, 10)) return 'bad started_at';
if (b.ended_at !== undefined && b.ended_at !== null && !isStr(b.ended_at, 10)) return 'bad ended_at';
if (b.ml_left !== undefined && !isIntOrNull(b.ml_left, 0, 2000)) return 'bad ml_left';
if (b.ml_right !== undefined && !isIntOrNull(b.ml_right, 0, 2000)) return 'bad ml_right';
if (b.notes !== undefined && !isStrOrNull(b.notes, 500)) return 'bad notes';
return null;
},
applyPatch(existing, b) {
return mergeDefined(existing, b, ['started_at', 'ended_at', 'ml_left', 'ml_right', 'notes']);
},
applyEnd(existing, b) {
return {
...existing,
ended_at: b?.ended_at ?? nowSec(),
ml_left: b?.ml_left ?? existing.ml_left,
ml_right: b?.ml_right ?? existing.ml_right,
};
},
},
tummy_times: {
key: 'tummy_times',
tf: 'started_at',
label: 'tummy time',
validateStart(b) {
if (!isStr(b.started_at, 10)) return 'started_at required';
if (b.ended_at != null && !isStr(b.ended_at, 10)) return 'bad ended_at';
if (!isStrOrNull(b.notes, 500)) return 'bad notes';
return null;
},
buildStart(b) { return { started_at: b.started_at, ended_at: b.ended_at ?? null, notes: b.notes ?? null }; },
validatePatch(b) {