@milesroxas/design-hub 0.13.0 → 0.14.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.
Files changed (67) hide show
  1. package/README.md +1 -1
  2. package/core/prototype.test.ts +12 -1
  3. package/core/prototype.ts +21 -2
  4. package/core/review/model.ts +71 -6
  5. package/core/review/service.test.ts +536 -1
  6. package/core/review/service.ts +452 -25
  7. package/core/review/store.ts +45 -4
  8. package/dist/core/prototype.d.ts +20 -2
  9. package/dist/core/prototype.js +17 -2
  10. package/dist/core/review/model.d.ts +42 -3
  11. package/dist/core/review/model.js +52 -3
  12. package/dist/core/review/service.d.ts +81 -7
  13. package/dist/core/review/service.js +407 -23
  14. package/dist/core/review/store.d.ts +29 -2
  15. package/dist/core/review/store.js +4 -0
  16. package/dist/scripts/client.d.ts +1 -1
  17. package/dist/scripts/client.js +1 -1
  18. package/dist/scripts/lib/dns.d.ts +16 -2
  19. package/dist/scripts/lib/dns.js +66 -3
  20. package/dist/scripts/lib/fake-host.d.ts +16 -1
  21. package/dist/scripts/lib/fake-host.js +36 -1
  22. package/dist/scripts/lib/host.d.ts +2 -0
  23. package/dist/scripts/lib/resend.d.ts +36 -0
  24. package/dist/scripts/lib/resend.js +66 -0
  25. package/dist/scripts/lib/studio-deps.d.ts +7 -0
  26. package/dist/scripts/lib/studio-deps.js +6 -1
  27. package/dist/scripts/lib/studios.d.ts +2 -2
  28. package/dist/scripts/lib/studios.js +5 -5
  29. package/dist/scripts/lib/vercel-host.js +6 -0
  30. package/dist/scripts/people.d.ts +16 -4
  31. package/dist/scripts/people.js +67 -17
  32. package/dist/scripts/studio.d.ts +19 -3
  33. package/dist/scripts/studio.js +327 -6
  34. package/dist/server/api.d.ts +14 -2
  35. package/dist/server/api.js +71 -17
  36. package/dist/server/dev.js +21 -1
  37. package/dist/server/gate.d.ts +26 -3
  38. package/dist/server/gate.js +323 -52
  39. package/dist/server/mailer.d.ts +60 -0
  40. package/dist/server/mailer.js +104 -0
  41. package/dist/server/mailers/fake.d.ts +8 -0
  42. package/dist/server/mailers/fake.js +16 -0
  43. package/dist/server/mailers/resend.d.ts +21 -0
  44. package/dist/server/mailers/resend.js +49 -0
  45. package/dist/server/session.js +4 -1
  46. package/dist/vercel/proxy.js +10 -3
  47. package/dist/vite/plugin.js +3 -1
  48. package/kit/ui/Menu.tsx +29 -18
  49. package/kit/ui/layer.ts +41 -0
  50. package/package.json +1 -1
  51. package/shell/review/Bar.tsx +1 -0
  52. package/shell/review/Card.tsx +17 -7
  53. package/shell/review/People.tsx +908 -134
  54. package/shell/review/Review.tsx +2 -2
  55. package/shell/review/anchor.ts +6 -1
  56. package/shell/review/client.ts +41 -7
  57. package/shell/review/menu-place.test.ts +41 -0
  58. package/shell/review/place.test.ts +26 -1
  59. package/shell/review/place.ts +17 -0
  60. package/shell/review/review.css +97 -11
  61. package/shell/review/view.test.ts +115 -1
  62. package/shell/review/view.ts +92 -2
  63. package/shell/studio/StudioHub.tsx +1 -0
  64. package/shell/studio/hub.css +99 -13
  65. package/skills/miles-deploy/SKILL.md +24 -3
  66. package/templates/studio/.env.example +6 -0
  67. package/templates/studio/package.json +1 -1
@@ -21,6 +21,8 @@ import {
21
21
  authorOf,
22
22
  type Checked,
23
23
  type Client,
24
+ CODE,
25
+ type Code,
24
26
  type Comment,
25
27
  checkAccess,
26
28
  checkAnchor,
@@ -28,6 +30,7 @@ import {
28
30
  checkBody,
29
31
  checkClientInput,
30
32
  checkControl,
33
+ checkEmail,
31
34
  checkPersonInput,
32
35
  checkProjectInput,
33
36
  checkPrototypeAudience,
@@ -35,6 +38,8 @@ import {
35
38
  checkTriage,
36
39
  checkViewAs,
37
40
  DEFAULT_ACCESS,
41
+ EMAIL_PROBLEM,
42
+ emailOf,
38
43
  HANDOFF_SECONDS,
39
44
  type Handoff,
40
45
  HOST_SECONDS,
@@ -46,6 +51,8 @@ import {
46
51
  LINK_DAYS,
47
52
  type Link,
48
53
  LOCAL_CLIENT,
54
+ NOT_AN_EMAIL,
55
+ NOT_VALID,
49
56
  type Person,
50
57
  type PersonKind,
51
58
  type Profile,
@@ -63,6 +70,10 @@ import { type KV, keyOf, sweepPrefix } from './store.ts';
63
70
 
64
71
  export type ErrorCode = 'unauthorized' | 'forbidden' | 'not_found' | 'invalid';
65
72
 
73
+ /** What a refusal over fields says: a sentence when the address is the one thing wrong, else that fields are not valid. */
74
+ const notValid = (problems: string[]) =>
75
+ problems.length === 1 && problems[0] === EMAIL_PROBLEM ? NOT_AN_EMAIL : NOT_VALID;
76
+
66
77
  export class ReviewError extends Error {
67
78
  code: ErrorCode;
68
79
  problems: string[];
@@ -81,20 +92,106 @@ export type Deps = {
81
92
  now: () => Date;
82
93
  random: (bytes: number) => Uint8Array;
83
94
  triage: Triager | null;
95
+ /**
96
+ * The key a sign-in code is stored under, as an HMAC (on a studio site, the
97
+ * gate's secret). The service reads no environment: a caller that makes or
98
+ * checks codes gives it; without one, askCode and useCode throw.
99
+ */
100
+ codeKey: string | null;
84
101
  };
85
102
 
86
103
  const DAY_MS = 86_400_000;
104
+ const MINUTE_MS = 60_000;
105
+ const HOUR_MS = 3_600_000;
87
106
 
88
107
  const defaults: Deps = {
89
108
  now: () => new Date(),
90
109
  random: (n) => crypto.getRandomValues(new Uint8Array(n)),
91
110
  triage: null,
111
+ codeKey: null,
92
112
  };
93
113
 
114
+ const encoder = new TextEncoder();
115
+
116
+ /** HMAC-SHA256 of `message` under `key`, as hex. */
117
+ async function hmacHex(key: string, message: string): Promise<string> {
118
+ const k = await crypto.subtle.importKey(
119
+ 'raw',
120
+ encoder.encode(key),
121
+ { name: 'HMAC', hash: 'SHA-256' },
122
+ false,
123
+ ['sign'],
124
+ );
125
+ return hex(new Uint8Array(await crypto.subtle.sign('HMAC', k, encoder.encode(message))));
126
+ }
127
+
128
+ /** Whether two hex digests are equal, looking at every character whatever differs. */
129
+ function sameDigest(a: string, b: string): boolean {
130
+ let diff = a.length ^ b.length;
131
+ for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i % (b.length || 1));
132
+ return diff === 0;
133
+ }
134
+
135
+ /** What a typed code is: its digits, spaces allowed between them, exactly CODE.digits of them; else null. */
136
+ function codeOf(input: unknown): string | null {
137
+ if (typeof input !== 'string') return null;
138
+ const digits = input.replace(/\s+/g, '');
139
+ return digits.length === CODE.digits && /^\d+$/.test(digits) ? digits : null;
140
+ }
141
+
142
+ /** A stored code that is well formed, or null. */
143
+ function readCode(json: string | null): Code | null {
144
+ try {
145
+ const c = json === null ? null : JSON.parse(json);
146
+ return c && typeof c.hash === 'string' && typeof c.expiresAt === 'string' && typeof c.sentAt === 'string'
147
+ ? { hash: c.hash, expiresAt: c.expiresAt, sentAt: c.sentAt }
148
+ : null;
149
+ } catch {
150
+ return null;
151
+ }
152
+ }
153
+
94
154
  /** What a link's token looks like: 32 random bytes, base64url. Anything else is never looked up. */
95
155
  const LINK_TOKEN = /^[\w-]{20,100}$/;
96
156
  const linkKey = async (token: string) => hex(await sha256(token));
97
157
 
158
+ /**
159
+ * What a link or a code was claimed by, for a second press (email.md,
160
+ * section 3): the person, their epoch then, a hash of the browser's `try`
161
+ * cookie (null when it sent none), and when.
162
+ */
163
+ type Claim = { person: string; epoch: number; by: string | null; at: string };
164
+ /** How long a claim stands for the browser that made it: a second press of the same link or code inside it signs that browser in. */
165
+ const CLAIM_SECONDS = 60;
166
+
167
+ function readClaim(json: string | null): Claim | null {
168
+ try {
169
+ const c = json === null ? null : JSON.parse(json);
170
+ return c && typeof c.person === 'string' && Number.isInteger(c.epoch) && typeof c.at === 'string'
171
+ ? { person: c.person, epoch: c.epoch, by: typeof c.by === 'string' ? c.by : null, at: c.at }
172
+ : null;
173
+ } catch {
174
+ return null;
175
+ }
176
+ }
177
+
178
+ /** A browser's `try` cookie as a claim keeps it: its hash, or null for none, or one that is not a value the gate makes. */
179
+ const browserOf = async (value: string | null | undefined) =>
180
+ typeof value === 'string' && LINK_TOKEN.test(value) ? hex(await sha256(`try\n${value}`)) : null;
181
+
182
+ /**
183
+ * The gate's cap per network address, per clock minute (email.md, section 3):
184
+ * sign-in POSTs (a link's Continue, asking for a code, using one) and views of
185
+ * a link's page, each counted apart.
186
+ */
187
+ const CAP = { post: 10, view: 60 } as const;
188
+ export type CapKind = keyof typeof CAP;
189
+
190
+ /** What a mail provider answered a send: taken, refused, or no answer at all (server/mailer.ts). */
191
+ export type Sent = 'sent' | 'refused' | 'down';
192
+ /** When a mail the studio sent was last taken, and last not: null for never. */
193
+ export type MailRecord = { okAt: string | null; failedAt: string | null };
194
+
98
195
  /**
99
196
  * How long a slug or host stays out of reach after its client is archived:
100
197
  * twice the time a studio site's instance keeps a host's answer. An instance
@@ -224,14 +321,14 @@ export function createReview(kv: KV, overrides: Partial<Deps> = {}) {
224
321
  }
225
322
 
226
323
  function valid<T>(checked: Checked<T>): T {
227
- if (!checked.ok) throw new ReviewError('invalid', 'Some fields are not valid.', checked.problems);
324
+ if (!checked.ok) throw new ReviewError('invalid', notValid(checked.problems), checked.problems);
228
325
  return checked.value;
229
326
  }
230
327
 
231
328
  // Every field checked before any throws, so one save names every problem.
232
329
  function validAll<T extends unknown[]>(...checks: { [K in keyof T]: Checked<T[K]> }): T {
233
330
  const problems = checks.flatMap((c) => (c.ok ? [] : c.problems));
234
- if (problems.length) throw new ReviewError('invalid', 'Some fields are not valid.', problems);
331
+ if (problems.length) throw new ReviewError('invalid', NOT_VALID, problems);
235
332
  return checks.map((c) => (c as { value: unknown }).value) as T;
236
333
  }
237
334
 
@@ -253,7 +350,8 @@ export function createReview(kv: KV, overrides: Partial<Deps> = {}) {
253
350
  // Any revocation record means revoked, an empty one included: it reads as the start of time.
254
351
  const revokedAt = revoked == null ? null : revoked || new Date(0).toISOString();
255
352
  const client = home === 'studio' ? null : home.client;
256
- return { ...profile, client, revokedAt, epoch: Number(epoch ?? 0) };
353
+ // A profile stored before email existed has none: links only.
354
+ return { ...profile, email: profile.email ?? null, client, revokedAt, epoch: Number(epoch ?? 0) };
257
355
  };
258
356
  const personAt = async (home: Home, id: string): Promise<Person | null> => {
259
357
  const [json, revoked, epoch] = await Promise.all([
@@ -283,6 +381,196 @@ export function createReview(kv: KV, overrides: Partial<Deps> = {}) {
283
381
  /** Not revoked, and their access has not ended. */
284
382
  const active = (p: Person | null): p is Person => !!p && hasAccess(p, deps.now());
285
383
 
384
+ // Email sign-in. An address belongs to one live person among their home's
385
+ // people (a client's, or the studio's own): the `emails` entry is the claim,
386
+ // taken before the profile names the address, so it is the one truth a code
387
+ // is sent by. A person past their access end keeps theirs (E5).
388
+
389
+ /** Whether someone at `home` still holds `address`: there, not revoked, and their profile names it. */
390
+ const holds = async (home: Home, id: string, address: string) => {
391
+ const p = await personAt(home, id);
392
+ return !!p && p.revokedAt === null && p.email === address;
393
+ };
394
+
395
+ /**
396
+ * Claims `address` for `p` among their home's people: true when it is
397
+ * theirs. An entry whose holder no longer holds it (revoked, gone, or on
398
+ * another address, after a revoke or a change that stopped part way) is
399
+ * taken over; a live holder's is refused.
400
+ */
401
+ async function claimEmail(p: Person, address: string): Promise<boolean> {
402
+ const key = keyOf(homeOf(p), 'emails');
403
+ if (await kv.hsetnx(key, address, p.id)) return true;
404
+ const holder = await kv.hget(key, address);
405
+ if (holder === p.id) return true;
406
+ if (holder !== null && (await holds(homeOf(p), holder, address))) return false;
407
+ if (holder !== null) await kv.hdel(key, address);
408
+ return kv.hsetnx(key, address, p.id);
409
+ }
410
+
411
+ /** Frees `address` when `p` holds it; an entry someone else holds stays. */
412
+ async function releaseEmail(p: Person, address: string | null): Promise<void> {
413
+ if (address === null) return;
414
+ const key = keyOf(homeOf(p), 'emails');
415
+ if ((await kv.hget(key, address)) === p.id) await kv.hdel(key, address);
416
+ }
417
+
418
+ const takenEmail = () =>
419
+ new ReviewError('invalid', 'Someone here already signs in with that address.', [
420
+ 'email: another person’s here',
421
+ ]);
422
+
423
+ /** Saves a new person, their address claimed first: one a live person here holds is refused, with nothing written. */
424
+ async function saveNew(p: Person): Promise<void> {
425
+ if (p.email !== null && !(await claimEmail(p, p.email))) throw takenEmail();
426
+ await savePerson(p);
427
+ }
428
+
429
+ /**
430
+ * Who an address signs in where `at` is: on a client's host, that client's
431
+ * people only; on the studio's own host, the studio's own. A Studio address
432
+ * on a client's host is nobody (E4), and so is another client's address.
433
+ * Null too for someone who may not sign in, or whose profile has moved on.
434
+ */
435
+ async function emailPerson(at: HostScope, address: string): Promise<Person | null> {
436
+ const home: Home = at === STUDIO_SITE ? 'studio' : { client: at.client };
437
+ const id = await kv.hget(keyOf(home, 'emails'), address);
438
+ const p = id === null ? null : await personAt(home, id);
439
+ return active(p) && p.email === address && reaches(p, at) ? p : null;
440
+ }
441
+
442
+ /** The key codes are stored under; a service given none cannot make or check one. */
443
+ function codeKey(): string {
444
+ if (!deps.codeKey) throw new Error('The review service was given no key for sign-in codes.');
445
+ return deps.codeKey;
446
+ }
447
+
448
+ /** What a code's HMAC is taken over: the person, so one code's hash says nothing of another's. */
449
+ const codeHash = (key: string, id: string, code: string) => hmacHex(key, `code\n${id}\n${code}`);
450
+
451
+ /** CODE.digits random digits, each value equally likely. */
452
+ function newCode(): string {
453
+ const space = 10 ** CODE.digits;
454
+ // The largest multiple of `space` four bytes hold: a value at or past it is drawn again, so no code is likelier.
455
+ const limit = Math.floor(2 ** 32 / space) * space;
456
+ for (;;) {
457
+ const n = deps.random(4).reduce((acc, byte) => acc * 256 + byte, 0);
458
+ if (n < limit) return String(n % space).padStart(CODE.digits, '0');
459
+ }
460
+ }
461
+
462
+ /** Removes one person's fields, `<id>:<suffix>`, from `key`, but those whose suffix `keep` says to keep. */
463
+ async function dropFields(key: string, id: string, keep: (suffix: string) => boolean): Promise<void> {
464
+ for (const field of Object.keys(await kv.hgetall(key)))
465
+ if (field.startsWith(`${id}:`) && !keep(field.slice(id.length + 1))) await kv.hdel(key, field);
466
+ }
467
+
468
+ /**
469
+ * Counts one more code made for a person this hour, before it is made: the
470
+ * count is the limit, so of two asks at once both count and neither is a
471
+ * 6th that passes. Their earlier hours' fields go. True while within CODE.perHour.
472
+ */
473
+ async function countSend(home: Home, id: string, at: number): Promise<boolean> {
474
+ const hour = String(Math.floor(at / HOUR_MS));
475
+ const key = keyOf(home, 'sends');
476
+ const n = await kv.hincrby(key, `${id}:${hour}`, 1);
477
+ await dropFields(key, id, (h) => h === hour);
478
+ return n <= CODE.perHour;
479
+ }
480
+
481
+ /**
482
+ * Claims this clock minute's code for a person: true for the ask that
483
+ * raised the count to 1. HINCRBY, so of two asks at once (a double press
484
+ * of Send code) one makes a code and the other none. Their earlier
485
+ * minutes' fields go.
486
+ */
487
+ async function claimMinute(home: Home, id: string, at: number): Promise<boolean> {
488
+ const minute = String(Math.floor(at / MINUTE_MS));
489
+ const key = keyOf(home, 'asks');
490
+ const n = await kv.hincrby(key, `${id}:${minute}`, 1);
491
+ await dropFields(key, id, (m) => m === minute);
492
+ return n === 1;
493
+ }
494
+
495
+ /**
496
+ * The field a code's wrong tries are counted in: the person and when the
497
+ * code ends. Each code counts its own, so a new code starts at none with no
498
+ * reset that a try landing at the same moment could slip past.
499
+ */
500
+ const triesField = (id: string, code: Code) => `${id}:${Date.parse(code.expiresAt)}`;
501
+
502
+ /**
503
+ * Claims `field` (a used link's or code's hash) for `p`, by the browser
504
+ * `by`: true when this call wrote it. HSETNX, so of two claims at once one
505
+ * holds, and the loser reads the winner's record (reclaim). The person's
506
+ * earlier claim goes: they keep one.
507
+ */
508
+ async function claimUse(home: Home, field: string, p: Person, by: string | null): Promise<boolean> {
509
+ const key = keyOf(home, 'used');
510
+ const record: Claim = { person: p.id, epoch: p.epoch, by, at: now() };
511
+ if (!(await kv.hsetnx(key, field, JSON.stringify(record)))) return false;
512
+ const last = await kv.hget(key, p.id);
513
+ await kv.hset(key, p.id, field);
514
+ if (last !== null && last !== field) await kv.hdel(key, last);
515
+ return true;
516
+ }
517
+
518
+ /**
519
+ * A second press: who the claim on `field` signs in again, for the same
520
+ * browser (`by`) inside CLAIM_SECONDS, read again and still able to sign in
521
+ * where `at` is, on the same epoch (and `address`, for a code). Null for
522
+ * anyone else, or later.
523
+ */
524
+ async function reclaim(
525
+ at: HostScope,
526
+ home: Home,
527
+ field: string,
528
+ by: string | null,
529
+ address: string | null = null,
530
+ ): Promise<Person | null> {
531
+ if (by === null) return null;
532
+ const c = readClaim(await kv.hget(keyOf(home, 'used'), field));
533
+ if (!c || c.by === null || !sameDigest(c.by, by)) return null;
534
+ const age = deps.now().getTime() - Date.parse(c.at);
535
+ if (!(age >= 0 && age < CLAIM_SECONDS * 1000)) return null;
536
+ const p = await personAt(home, c.person);
537
+ if (!active(p) || p.epoch !== c.epoch || !reaches(p, at)) return null;
538
+ return address === null || p.email === address ? p : null;
539
+ }
540
+
541
+ /** Takes `field` in `key` (a link or a code) after its claim: true when it was there; if not, the claim goes again. */
542
+ async function take(home: Home, key: string, field: string, claimed: string): Promise<boolean> {
543
+ if ((await kv.hdel(key, field)) === 1) return true;
544
+ await kv.hdel(keyOf(home, 'used'), claimed);
545
+ return false;
546
+ }
547
+
548
+ /**
549
+ * A code's first use: the wrong tries raised before the compare, so the
550
+ * count is the limit (past CODE.tries the code is dead, a right answer
551
+ * too, and no two requests at once get a 6th try), the compare in constant
552
+ * time, then the claim, then the code taken. True when this answer used
553
+ * it; false for a wrong, ended or dead code; 'taken' when there is no live
554
+ * code to try, or another answer claimed it first.
555
+ */
556
+ async function firstUse(
557
+ home: Home,
558
+ p: Person,
559
+ hash: string,
560
+ by: string | null,
561
+ ): Promise<boolean | 'taken'> {
562
+ const codes = keyOf(home, 'codes');
563
+ const live = readCode(await kv.hget(codes, p.id));
564
+ if (!live) return 'taken';
565
+ if (live.expiresAt <= now()) return false;
566
+ if ((await kv.hincrby(keyOf(home, 'tries'), triesField(p.id, live), 1)) > CODE.tries) return 'taken';
567
+ // The end again, after the count: a count dropped as ended (askCode) and raised again is never compared.
568
+ if (live.expiresAt <= now()) return false;
569
+ if (!sameDigest(hash, live.hash)) return false;
570
+ if (!(await claimUse(home, hash, p, by))) return 'taken';
571
+ return take(home, codes, p.id, hash);
572
+ }
573
+
286
574
  async function issueLink(p: Person): Promise<string> {
287
575
  // The link carries the token; the store keeps only its hash, so a leaked store signs nobody in.
288
576
  const token = base64url(deps.random(32));
@@ -319,6 +607,17 @@ export function createReview(kv: KV, overrides: Partial<Deps> = {}) {
319
607
  return null;
320
608
  }
321
609
 
610
+ /** A link already used, pressed again: the browser that claimed it, inside CLAIM_SECONDS (reclaim), where `at` reaches. */
611
+ async function againLink(at: HostScope, token: string, by: string | null): Promise<Person | null> {
612
+ if (by === null) return null;
613
+ const hash = await linkKey(token);
614
+ for (const home of at === STUDIO_SITE ? ['studio' as const] : [at, 'studio' as const]) {
615
+ const p = await reclaim(at, home, hash, by);
616
+ if (p) return p;
617
+ }
618
+ return null;
619
+ }
620
+
322
621
  /** The person a current link signs in, while they may sign in here. */
323
622
  async function linkPerson(at: HostScope, { home, link }: Found): Promise<Person | null> {
324
623
  if (link.expiresAt <= now()) return null;
@@ -347,13 +646,12 @@ export function createReview(kv: KV, overrides: Partial<Deps> = {}) {
347
646
  ...fields,
348
647
  team,
349
648
  client: null,
350
- email: null,
351
649
  accessEndsAt: accessEnd(access ?? 'open', deps.now()),
352
650
  createdAt: now(),
353
651
  revokedAt: null,
354
652
  epoch: 0,
355
653
  };
356
- await savePerson(p);
654
+ await saveNew(p);
357
655
  return p;
358
656
  }
359
657
 
@@ -640,7 +938,7 @@ export function createReview(kv: KV, overrides: Partial<Deps> = {}) {
640
938
  async setStudioHost(actor: Person | null, host: string): Promise<'added' | 'kept'> {
641
939
  allowStudio(actor);
642
940
  if (hostName(host) !== host)
643
- throw new ReviewError('invalid', 'Some fields are not valid.', ['host: a host name in lower case']);
941
+ throw new ReviewError('invalid', NOT_VALID, ['host: a host name in lower case']);
644
942
  const hosts = keyOf('studio', 'hosts');
645
943
  if (await kv.hsetnx(hosts, host, STUDIO_SITE)) return 'added';
646
944
  if ((await kv.hget(hosts, host)) === STUDIO_SITE) return 'kept';
@@ -938,8 +1236,7 @@ export function createReview(kv: KV, overrides: Partial<Deps> = {}) {
938
1236
  */
939
1237
  async startBuild(scope: Scope, actor: Person | null, build: unknown): Promise<void> {
940
1238
  await allow(scope, actor, 'setup', NO_PROJECT);
941
- if (!isBuildId(build))
942
- throw new ReviewError('invalid', 'Some fields are not valid.', ['build: a build id']);
1239
+ if (!isBuildId(build)) throw new ReviewError('invalid', NOT_VALID, ['build: a build id']);
943
1240
  if (!(await projectAt(scope))) throw new ReviewError('not_found', NO_PROJECT);
944
1241
  const key = keyOf(scope, 'builds');
945
1242
  const n = await kv.hincrby(key, 'next', 1);
@@ -962,8 +1259,7 @@ export function createReview(kv: KV, overrides: Partial<Deps> = {}) {
962
1259
  */
963
1260
  async setBuild(scope: Scope, actor: Person | null, build: unknown): Promise<Project> {
964
1261
  await allow(scope, actor, 'setup', NO_PROJECT);
965
- if (!isBuildId(build))
966
- throw new ReviewError('invalid', 'Some fields are not valid.', ['build: a build id']);
1262
+ if (!isBuildId(build)) throw new ReviewError('invalid', NOT_VALID, ['build: a build id']);
967
1263
  const p = await projectAt(scope);
968
1264
  if (!p) throw new ReviewError('not_found', NO_PROJECT);
969
1265
  const key = keyOf(scope, 'builds');
@@ -1023,14 +1319,16 @@ export function createReview(kv: KV, overrides: Partial<Deps> = {}) {
1023
1319
  * an access length, a Client gets the default and Studio is open-ended.
1024
1320
  * Without a team, a Studio person gets the studio's, which every Studio
1025
1321
  * person carries, so the adder's; a Client gets their client's name.
1322
+ * An email, when given, is claimed first: an address a live person of
1323
+ * the same home holds is refused, with nothing written. The service
1324
+ * never mails anyone; whoever calls it does.
1026
1325
  */
1027
1326
  async addPerson(at: HostScope, actor: Person | null, input: unknown): Promise<Issued> {
1028
1327
  const by = await allowPeople(at, actor);
1029
1328
  const { access, team, ...fields } = valid(checkPersonInput(input));
1030
1329
  // A Client belongs to one client: the studio's own host names none.
1031
1330
  const scope = fields.kind === 'studio' ? null : at;
1032
- if (scope === STUDIO_SITE)
1033
- throw new ReviewError('invalid', 'Some fields are not valid.', ['kind: studio here']);
1331
+ if (scope === STUDIO_SITE) throw new ReviewError('invalid', NOT_VALID, ['kind: studio here']);
1034
1332
  // S13: the person's own length, else (a Client) the client's default, then the studio's, then 3m.
1035
1333
  const length = access ?? (scope ? await readDefault(scope) : 'open');
1036
1334
  const p: Person = {
@@ -1038,13 +1336,12 @@ export function createReview(kv: KV, overrides: Partial<Deps> = {}) {
1038
1336
  ...fields,
1039
1337
  team: team ?? (scope ? ((await clientAt(scope.client))?.name ?? 'Client') : by.team),
1040
1338
  client: scope ? scope.client : null,
1041
- email: null,
1042
1339
  accessEndsAt: accessEnd(length, deps.now()),
1043
1340
  createdAt: now(),
1044
1341
  revokedAt: null,
1045
1342
  epoch: 0,
1046
1343
  };
1047
- await savePerson(p);
1344
+ await saveNew(p);
1048
1345
  return { person: p, token: await issueLink(p) };
1049
1346
  },
1050
1347
 
@@ -1055,12 +1352,14 @@ export function createReview(kv: KV, overrides: Partial<Deps> = {}) {
1055
1352
  return { person: p, token: await issueLink(p) };
1056
1353
  },
1057
1354
 
1058
- /** Ends every session they hold and every unused link, and gives one new link. */
1355
+ /** Ends every session they hold, every unused link and their sign-in code, and gives one new link. */
1059
1356
  async signOutEverywhere(scope: HostScope, actor: Person | null, id: string): Promise<Issued> {
1060
1357
  await allowPeople(scope, actor);
1061
1358
  const p = await needActive(scope, id);
1062
1359
  // The epoch first: a failure after it has still ended every session. Atomic, so two at once raise it twice.
1063
1360
  const next = { ...p, epoch: await kv.hincrby(keyOf(homeOf(p), 'epochs'), id, 1) };
1361
+ // An unused code is an unused way in, as a link is.
1362
+ await kv.hdel(keyOf(homeOf(p), 'codes'), id);
1064
1363
  await dropLinks(p);
1065
1364
  return { person: next, token: await issueLink(next) };
1066
1365
  },
@@ -1074,6 +1373,9 @@ export function createReview(kv: KV, overrides: Partial<Deps> = {}) {
1074
1373
  // person; a leftover link opens nothing for someone revoked.
1075
1374
  if (!p.revokedAt) await kv.hset(keyOf(homeOf(p), 'revoked'), id, revokedAt);
1076
1375
  const epoch = await kv.hincrby(keyOf(homeOf(p), 'epochs'), id, 1);
1376
+ // Revoked, they hold their address no more: someone added again may have it (E5). Their code
1377
+ // signs nobody in, since useCode reads them again.
1378
+ await releaseEmail(p, p.email);
1077
1379
  await dropLinks(p);
1078
1380
  return { ...p, revokedAt, epoch };
1079
1381
  },
@@ -1089,6 +1391,29 @@ export function createReview(kv: KV, overrides: Partial<Deps> = {}) {
1089
1391
  return (await personAt(homeOf(p), id)) as Person;
1090
1392
  },
1091
1393
 
1394
+ /**
1395
+ * Sets, changes or clears (null, or empty) the address one person signs
1396
+ * in with by code. The new address is claimed before the profile names
1397
+ * it, and refused while another live person of the same home holds it;
1398
+ * the old one is freed after. The same address saved again claims it
1399
+ * again, which mends an entry left missing or stale. Any change ends their live code, which was
1400
+ * sent to the old address. Studio only (the `people` action).
1401
+ */
1402
+ async setEmail(at: HostScope, actor: Person | null, id: string, email: unknown): Promise<Person> {
1403
+ await allowPeople(at, actor);
1404
+ const address = valid(checkEmail(email));
1405
+ const p = await needPerson(at, id);
1406
+ if (p.revokedAt) throw new ReviewError('invalid', 'That person is revoked; add them again.');
1407
+ // Claimed even when the profile names it already: saving it again mends an entry that a change at
1408
+ // the same moment, or a step that stopped part way, left missing or someone else's.
1409
+ if (address !== null && !(await claimEmail(p, address))) throw takenEmail();
1410
+ if (address === p.email) return p;
1411
+ await savePerson({ ...p, email: address });
1412
+ await releaseEmail(p, p.email);
1413
+ await kv.hdel(keyOf(homeOf(p), 'codes'), id);
1414
+ return (await personAt(homeOf(p), id)) as Person;
1415
+ },
1416
+
1092
1417
  /** How long a new Client of the scope's client keeps access unless Studio says otherwise: the client's default, else the studio's. */
1093
1418
  async defaultAccess(scope: Scope, actor: Person | null): Promise<Access> {
1094
1419
  await allow(scope, actor, 'people', NO_PERSON);
@@ -1149,25 +1474,127 @@ export function createReview(kv: KV, overrides: Partial<Deps> = {}) {
1149
1474
  },
1150
1475
 
1151
1476
  /**
1152
- * Uses a link up and returns who it signs in. The delete is the claim: of
1153
- * two requests with one token, only the one whose delete removed the link
1154
- * gets a person, so a link signs in one device at most. Who it signs in is
1155
- * read and checked first, so the delete is the last store call. Only a
1156
- * link of the scope's client, or a Studio person's, is found at all; on
1477
+ * Uses a link up and returns who it signs in. The claim (HSETNX on
1478
+ * `used`, then the link's delete) decides: of two requests with one
1479
+ * token, only the one that wrote the claim gets a person, so a link signs
1480
+ * in one device at most. The other is a second press: it signs in only
1481
+ * the same browser (`browser`, its `try` cookie) inside CLAIM_SECONDS,
1482
+ * the person read again. Who it signs in is read and checked first. Only
1483
+ * a link of the scope's client, or a Studio person's, is found at all; on
1157
1484
  * the studio's own host, only a Studio person's.
1158
1485
  */
1159
- async useLink(at: HostScope, token: string): Promise<Person | null> {
1486
+ async useLink(at: HostScope, token: string, browser: string | null = null): Promise<Person | null> {
1487
+ if (!LINK_TOKEN.test(token)) return null;
1488
+ const by = await browserOf(browser);
1160
1489
  const found = await findLink(at, token);
1161
- // Every read and check comes before the delete, so a store failure before it leaves the link usable.
1490
+ // Every read and check comes before the claim, so a store failure before it leaves the link usable.
1162
1491
  const p = found && (await linkPerson(at, found));
1163
- if (!found || !p) return null;
1164
- if ((await kv.hdel(keyOf(found.home, 'links'), found.hash)) !== 1) return null;
1492
+ if (!found) return againLink(at, token, by);
1493
+ if (!p) return null;
1494
+ if (!(await claimUse(found.home, found.hash, p, by))) return reclaim(at, found.home, found.hash, by);
1495
+ if (!(await take(found.home, keyOf(found.home, 'links'), found.hash, found.hash))) return null;
1165
1496
  // A revoke or sign out everywhere can land between the check and the claim, before its
1166
1497
  // dropLinks reaches this link: read again, and sign in only someone still active on the same epoch.
1167
1498
  const after = await personAt(found.home, p.id);
1168
1499
  return active(after) && after.epoch === p.epoch ? after : null;
1169
1500
  },
1170
1501
 
1502
+ /**
1503
+ * A new sign-in code for whoever holds `email` where `at` is (emailPerson),
1504
+ * asked by the gate with no actor, in place of their live one: the person
1505
+ * and the code, for the caller to mail, or null. Null, never a throw, for
1506
+ * an address that is malformed, unknown here, revoked, past its access
1507
+ * end, asked again inside a minute, or past CODE.perHour this hour, so
1508
+ * the gate gives one answer whatever comes back. The store keeps only the
1509
+ * code's HMAC (`hash`, which the mail's idempotency key names); the new
1510
+ * code's wrong tries are counted apart from any other's.
1511
+ */
1512
+ async askCode(
1513
+ at: HostScope,
1514
+ email: unknown,
1515
+ ): Promise<{ person: Person; code: string; hash: string } | null> {
1516
+ const key = codeKey();
1517
+ const address = emailOf(email);
1518
+ const p = address === null ? null : await emailPerson(at, address);
1519
+ if (!p) return null;
1520
+ const home = homeOf(p);
1521
+ const t = deps.now().getTime();
1522
+ const live = readCode(await kv.hget(keyOf(home, 'codes'), p.id));
1523
+ // One a minute, read from the live code; two asks at once may both pass it, and claimMinute lets one on.
1524
+ if (live && t - Date.parse(live.sentAt) < CODE.gapSeconds * 1000) return null;
1525
+ // Two asks at once both pass that read: this claim lets one of them on.
1526
+ if (!(await claimMinute(home, p.id, t))) return null;
1527
+ if (!(await countSend(home, p.id, t))) return null;
1528
+ const code = newCode();
1529
+ const stored: Code = {
1530
+ hash: await codeHash(key, p.id, code),
1531
+ expiresAt: new Date(t + CODE.minutes * MINUTE_MS).toISOString(),
1532
+ sentAt: new Date(t).toISOString(),
1533
+ };
1534
+ await kv.hset(keyOf(home, 'codes'), p.id, JSON.stringify(stored));
1535
+ // The counts of codes already past their end go; a try counted on one after this is refused
1536
+ // by useCode's second look at the end, so no code ever gets its count back.
1537
+ await dropFields(keyOf(home, 'tries'), p.id, (end) => Number(end) > t);
1538
+ return { person: p, code, hash: stored.hash };
1539
+ },
1540
+
1541
+ /**
1542
+ * Counts one request from a network address against the gate's cap
1543
+ * (CAP), in this clock minute, before anyone is looked up: true while it
1544
+ * is within. The address is kept as an HMAC under the code key, never as
1545
+ * it is; the minute two before goes, so the store holds about two.
1546
+ */
1547
+ async hit(kind: CapKind, address: string): Promise<boolean> {
1548
+ const minute = Math.floor(deps.now().getTime() / MINUTE_MS);
1549
+ const field = `${kind}:${await hmacHex(codeKey(), `hit\n${address}`)}`;
1550
+ const n = await kv.hincrby(keyOf('studio', 'hits', minute), field, 1);
1551
+ if (minute >= 2) await kv.del(keyOf('studio', 'hits', minute - 2));
1552
+ return n <= CAP[kind];
1553
+ },
1554
+
1555
+ /** Records what a mail the studio sent was answered, for Studio: the time of the last that was taken, or of the last that was not. */
1556
+ async recordMail(answer: Sent): Promise<void> {
1557
+ await kv.hset(keyOf('studio', 'mail'), answer === 'sent' ? 'okAt' : 'failedAt', now());
1558
+ },
1559
+
1560
+ /** When a mail the studio sent was last taken, and last not. */
1561
+ async mailRecord(): Promise<MailRecord> {
1562
+ const record = await kv.hgetall(keyOf('studio', 'mail'));
1563
+ return { okAt: record.okAt ?? null, failedAt: record.failedAt ?? null };
1564
+ },
1565
+
1566
+ /**
1567
+ * Signs in with a code, asked by the gate with no actor: who it signs in,
1568
+ * or null. The wrong tries are raised before the compare, so the count is
1569
+ * the limit: past CODE.tries the code is dead, a right answer too, and no
1570
+ * two requests at once get a 6th try. The compare runs in constant time.
1571
+ * The claim is useLink's: of two right answers at once, one signs in, and
1572
+ * the other only when it is the same browser pressing again (`browser`).
1573
+ * The person is read again after it, so a revoke, a sign out everywhere
1574
+ * or a changed address that landed meanwhile signs nobody in.
1575
+ */
1576
+ async useCode(
1577
+ at: HostScope,
1578
+ email: unknown,
1579
+ code: unknown,
1580
+ browser: string | null = null,
1581
+ ): Promise<Person | null> {
1582
+ const key = codeKey();
1583
+ const address = emailOf(email);
1584
+ const given = codeOf(code);
1585
+ const p = address === null || given === null ? null : await emailPerson(at, address);
1586
+ if (!p || address === null || given === null) return null;
1587
+ const home = homeOf(p);
1588
+ const hash = await codeHash(key, p.id, given);
1589
+ const first = await firstUse(home, p, hash, await browserOf(browser));
1590
+ // A code already used, or one this answer did not claim: the browser that claimed it, pressing again.
1591
+ if (first === 'taken') return reclaim(at, home, hash, await browserOf(browser), address);
1592
+ const after = first ? await personAt(home, p.id) : null;
1593
+ return active(after) && after.epoch === p.epoch && after.email === address && reaches(after, at)
1594
+ ? after
1595
+ : null;
1596
+ },
1597
+
1171
1598
  /**
1172
1599
  * A prototype's comments as the actor's view sees them. `viewAs: 'client'`
1173
1600
  * is Studio's Client view; it never widens a Client's.
@@ -1361,7 +1788,7 @@ export function createReview(kv: KV, overrides: Partial<Deps> = {}) {
1361
1788
  ): Promise<{ view: PersonKind } & Marks> {
1362
1789
  const by = await allow(scope, actor, 'read', NO_PROTOTYPE);
1363
1790
  if (!isPrototypeSlug(prototype))
1364
- throw new ReviewError('invalid', 'Some fields are not valid.', ['prototype: a prototype slug']);
1791
+ throw new ReviewError('invalid', NOT_VALID, ['prototype: a prototype slug']);
1365
1792
  const view = viewOf(by);
1366
1793
  if (!(await reachable(scope, view, prototype))) throw new ReviewError('not_found', NO_PROTOTYPE);
1367
1794
  return { view, ...readMarks(await kv.hgetall(keyOf(scope, 'controls', prototype))) };