@milesroxas/design-hub 0.13.0 → 0.15.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 (101) hide show
  1. package/README.md +38 -33
  2. package/core/catalog.test.ts +28 -1
  3. package/core/catalog.ts +21 -4
  4. package/core/prototype.test.ts +12 -1
  5. package/core/prototype.ts +21 -2
  6. package/core/review/model.ts +71 -6
  7. package/core/review/service.test.ts +536 -1
  8. package/core/review/service.ts +452 -25
  9. package/core/review/store.ts +45 -4
  10. package/dist/core/catalog.d.ts +8 -1
  11. package/dist/core/catalog.js +12 -3
  12. package/dist/core/prototype.d.ts +20 -2
  13. package/dist/core/prototype.js +17 -2
  14. package/dist/core/review/model.d.ts +42 -3
  15. package/dist/core/review/model.js +52 -3
  16. package/dist/core/review/service.d.ts +81 -7
  17. package/dist/core/review/service.js +407 -23
  18. package/dist/core/review/store.d.ts +29 -2
  19. package/dist/core/review/store.js +4 -0
  20. package/dist/scripts/client.d.ts +1 -1
  21. package/dist/scripts/client.js +1 -1
  22. package/dist/scripts/lib/catalog.d.ts +1 -1
  23. package/dist/scripts/lib/catalog.js +3 -3
  24. package/dist/scripts/lib/dns.d.ts +16 -2
  25. package/dist/scripts/lib/dns.js +66 -3
  26. package/dist/scripts/lib/fake-host.d.ts +16 -1
  27. package/dist/scripts/lib/fake-host.js +36 -1
  28. package/dist/scripts/lib/host.d.ts +2 -0
  29. package/dist/scripts/lib/resend.d.ts +36 -0
  30. package/dist/scripts/lib/resend.js +66 -0
  31. package/dist/scripts/lib/studio-deps.d.ts +7 -0
  32. package/dist/scripts/lib/studio-deps.js +6 -1
  33. package/dist/scripts/lib/studios.d.ts +2 -2
  34. package/dist/scripts/lib/studios.js +5 -5
  35. package/dist/scripts/lib/vercel-host.js +6 -0
  36. package/dist/scripts/new.d.ts +8 -3
  37. package/dist/scripts/new.js +15 -4
  38. package/dist/scripts/people.d.ts +16 -4
  39. package/dist/scripts/people.js +67 -17
  40. package/dist/scripts/preflight.js +1 -1
  41. package/dist/scripts/share.js +3 -3
  42. package/dist/scripts/studio.d.ts +19 -3
  43. package/dist/scripts/studio.js +327 -6
  44. package/dist/server/api.d.ts +25 -2
  45. package/dist/server/api.js +77 -17
  46. package/dist/server/dev-studio.d.ts +36 -0
  47. package/dist/server/dev-studio.js +181 -0
  48. package/dist/server/dev.d.ts +16 -1
  49. package/dist/server/dev.js +23 -3
  50. package/dist/server/gate.d.ts +26 -3
  51. package/dist/server/gate.js +323 -52
  52. package/dist/server/mailer.d.ts +60 -0
  53. package/dist/server/mailer.js +104 -0
  54. package/dist/server/mailers/fake.d.ts +8 -0
  55. package/dist/server/mailers/fake.js +16 -0
  56. package/dist/server/mailers/resend.d.ts +21 -0
  57. package/dist/server/mailers/resend.js +49 -0
  58. package/dist/server/session.js +4 -1
  59. package/dist/vercel/proxy.js +10 -3
  60. package/dist/vite/plugin.js +6 -1
  61. package/kit/ViewTools.tsx +9 -0
  62. package/kit/prefs.ts +3 -4
  63. package/kit/ui/Menu.tsx +29 -18
  64. package/kit/ui/layer.ts +41 -0
  65. package/package.json +1 -1
  66. package/shell/Command.tsx +142 -0
  67. package/shell/Index.tsx +902 -400
  68. package/shell/Milestone.tsx +302 -0
  69. package/shell/Sidebar.tsx +236 -0
  70. package/shell/index.css +224 -0
  71. package/shell/milestones.test.ts +157 -0
  72. package/shell/milestones.ts +144 -0
  73. package/shell/registry.ts +4 -3
  74. package/shell/review/Bar.tsx +1 -0
  75. package/shell/review/Card.tsx +17 -7
  76. package/shell/review/People.tsx +908 -134
  77. package/shell/review/Review.tsx +2 -2
  78. package/shell/review/anchor.ts +6 -1
  79. package/shell/review/client.ts +41 -7
  80. package/shell/review/menu-place.test.ts +41 -0
  81. package/shell/review/place.test.ts +26 -1
  82. package/shell/review/place.ts +17 -0
  83. package/shell/review/review.css +97 -11
  84. package/shell/review/view.test.ts +115 -1
  85. package/shell/review/view.ts +92 -2
  86. package/shell/shell.css +8 -175
  87. package/shell/sidebar.css +86 -0
  88. package/shell/studio/ClientHub.tsx +21 -10
  89. package/shell/studio/StudioHub.tsx +121 -45
  90. package/shell/studio/hub.css +118 -27
  91. package/shell/studio/page.tsx +28 -17
  92. package/shell/system.css +12 -0
  93. package/skills/miles-deploy/SKILL.md +25 -4
  94. package/skills/miles-new-feature/SKILL.md +2 -1
  95. package/skills/miles-prototype/SKILL.md +1 -1
  96. package/templates/app/README.md +1 -1
  97. package/templates/brand/README.md +1 -1
  98. package/templates/site/README.md +1 -1
  99. package/templates/space/README.md +1 -1
  100. package/templates/studio/.env.example +6 -0
  101. package/templates/studio/package.json +1 -1
@@ -13,9 +13,11 @@ import { base64url, hex, sha256 } from '../bytes.js';
13
13
  import { controlField, readMarks } from '../controls.js';
14
14
  import { isBuildId } from '../files.js';
15
15
  import { hostName, isClientSlug, isProjectSlug, isPrototypeSlug } from '../prototype.js';
16
- import { accessEnd, authorOf, checkAccess, checkAnchor, checkAudience, checkBody, checkClientInput, checkControl, checkPersonInput, checkProjectInput, checkPrototypeAudience, checkStates, checkTriage, checkViewAs, DEFAULT_ACCESS, HANDOFF_SECONDS, HOST_SECONDS, hasAccess, isAdded, isProfile, isRoot, isStudioClient, LINK_DAYS, LOCAL_CLIENT, readClient, readComment, readProject, STUDIO_SITE, } from './model.js';
16
+ import { accessEnd, authorOf, CODE, checkAccess, checkAnchor, checkAudience, checkBody, checkClientInput, checkControl, checkEmail, checkPersonInput, checkProjectInput, checkPrototypeAudience, checkStates, checkTriage, checkViewAs, DEFAULT_ACCESS, EMAIL_PROBLEM, emailOf, HANDOFF_SECONDS, HOST_SECONDS, hasAccess, isAdded, isProfile, isRoot, isStudioClient, LINK_DAYS, LOCAL_CLIENT, NOT_AN_EMAIL, NOT_VALID, readClient, readComment, readProject, STUDIO_SITE, } from './model.js';
17
17
  import { audienceFor, can, inScope, viewOf, visibleTo } from './policy.js';
18
18
  import { keyOf, sweepPrefix } from './store.js';
19
+ /** What a refusal over fields says: a sentence when the address is the one thing wrong, else that fields are not valid. */
20
+ const notValid = (problems) => problems.length === 1 && problems[0] === EMAIL_PROBLEM ? NOT_AN_EMAIL : NOT_VALID;
19
21
  export class ReviewError extends Error {
20
22
  code;
21
23
  problems;
@@ -26,14 +28,70 @@ export class ReviewError extends Error {
26
28
  }
27
29
  }
28
30
  const DAY_MS = 86_400_000;
31
+ const MINUTE_MS = 60_000;
32
+ const HOUR_MS = 3_600_000;
29
33
  const defaults = {
30
34
  now: () => new Date(),
31
35
  random: (n) => crypto.getRandomValues(new Uint8Array(n)),
32
36
  triage: null,
37
+ codeKey: null,
33
38
  };
39
+ const encoder = new TextEncoder();
40
+ /** HMAC-SHA256 of `message` under `key`, as hex. */
41
+ async function hmacHex(key, message) {
42
+ const k = await crypto.subtle.importKey('raw', encoder.encode(key), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']);
43
+ return hex(new Uint8Array(await crypto.subtle.sign('HMAC', k, encoder.encode(message))));
44
+ }
45
+ /** Whether two hex digests are equal, looking at every character whatever differs. */
46
+ function sameDigest(a, b) {
47
+ let diff = a.length ^ b.length;
48
+ for (let i = 0; i < a.length; i++)
49
+ diff |= a.charCodeAt(i) ^ b.charCodeAt(i % (b.length || 1));
50
+ return diff === 0;
51
+ }
52
+ /** What a typed code is: its digits, spaces allowed between them, exactly CODE.digits of them; else null. */
53
+ function codeOf(input) {
54
+ if (typeof input !== 'string')
55
+ return null;
56
+ const digits = input.replace(/\s+/g, '');
57
+ return digits.length === CODE.digits && /^\d+$/.test(digits) ? digits : null;
58
+ }
59
+ /** A stored code that is well formed, or null. */
60
+ function readCode(json) {
61
+ try {
62
+ const c = json === null ? null : JSON.parse(json);
63
+ return c && typeof c.hash === 'string' && typeof c.expiresAt === 'string' && typeof c.sentAt === 'string'
64
+ ? { hash: c.hash, expiresAt: c.expiresAt, sentAt: c.sentAt }
65
+ : null;
66
+ }
67
+ catch {
68
+ return null;
69
+ }
70
+ }
34
71
  /** What a link's token looks like: 32 random bytes, base64url. Anything else is never looked up. */
35
72
  const LINK_TOKEN = /^[\w-]{20,100}$/;
36
73
  const linkKey = async (token) => hex(await sha256(token));
74
+ /** 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. */
75
+ const CLAIM_SECONDS = 60;
76
+ function readClaim(json) {
77
+ try {
78
+ const c = json === null ? null : JSON.parse(json);
79
+ return c && typeof c.person === 'string' && Number.isInteger(c.epoch) && typeof c.at === 'string'
80
+ ? { person: c.person, epoch: c.epoch, by: typeof c.by === 'string' ? c.by : null, at: c.at }
81
+ : null;
82
+ }
83
+ catch {
84
+ return null;
85
+ }
86
+ }
87
+ /** 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. */
88
+ const browserOf = async (value) => typeof value === 'string' && LINK_TOKEN.test(value) ? hex(await sha256(`try\n${value}`)) : null;
89
+ /**
90
+ * The gate's cap per network address, per clock minute (email.md, section 3):
91
+ * sign-in POSTs (a link's Continue, asking for a code, using one) and views of
92
+ * a link's page, each counted apart.
93
+ */
94
+ const CAP = { post: 10, view: 60 };
37
95
  /**
38
96
  * How long a slug or host stays out of reach after its client is archived:
39
97
  * twice the time a studio site's instance keeps a host's answer. An instance
@@ -130,14 +188,14 @@ export function createReview(kv, overrides = {}) {
130
188
  }
131
189
  function valid(checked) {
132
190
  if (!checked.ok)
133
- throw new ReviewError('invalid', 'Some fields are not valid.', checked.problems);
191
+ throw new ReviewError('invalid', notValid(checked.problems), checked.problems);
134
192
  return checked.value;
135
193
  }
136
194
  // Every field checked before any throws, so one save names every problem.
137
195
  function validAll(...checks) {
138
196
  const problems = checks.flatMap((c) => (c.ok ? [] : c.problems));
139
197
  if (problems.length)
140
- throw new ReviewError('invalid', 'Some fields are not valid.', problems);
198
+ throw new ReviewError('invalid', NOT_VALID, problems);
141
199
  return checks.map((c) => c.value);
142
200
  }
143
201
  // A person is three records. The profile (`people`) is read-modify-write, so
@@ -155,7 +213,8 @@ export function createReview(kv, overrides = {}) {
155
213
  // Any revocation record means revoked, an empty one included: it reads as the start of time.
156
214
  const revokedAt = revoked == null ? null : revoked || new Date(0).toISOString();
157
215
  const client = home === 'studio' ? null : home.client;
158
- return { ...profile, client, revokedAt, epoch: Number(epoch ?? 0) };
216
+ // A profile stored before email existed has none: links only.
217
+ return { ...profile, email: profile.email ?? null, client, revokedAt, epoch: Number(epoch ?? 0) };
159
218
  };
160
219
  const personAt = async (home, id) => {
161
220
  const [json, revoked, epoch] = await Promise.all([
@@ -182,6 +241,189 @@ export function createReview(kv, overrides = {}) {
182
241
  const savePerson = ({ revokedAt: _r, epoch: _e, client, ...profile }) => kv.hset(keyOf(homeOf({ client }), 'people'), profile.id, JSON.stringify(profile));
183
242
  /** Not revoked, and their access has not ended. */
184
243
  const active = (p) => !!p && hasAccess(p, deps.now());
244
+ // Email sign-in. An address belongs to one live person among their home's
245
+ // people (a client's, or the studio's own): the `emails` entry is the claim,
246
+ // taken before the profile names the address, so it is the one truth a code
247
+ // is sent by. A person past their access end keeps theirs (E5).
248
+ /** Whether someone at `home` still holds `address`: there, not revoked, and their profile names it. */
249
+ const holds = async (home, id, address) => {
250
+ const p = await personAt(home, id);
251
+ return !!p && p.revokedAt === null && p.email === address;
252
+ };
253
+ /**
254
+ * Claims `address` for `p` among their home's people: true when it is
255
+ * theirs. An entry whose holder no longer holds it (revoked, gone, or on
256
+ * another address, after a revoke or a change that stopped part way) is
257
+ * taken over; a live holder's is refused.
258
+ */
259
+ async function claimEmail(p, address) {
260
+ const key = keyOf(homeOf(p), 'emails');
261
+ if (await kv.hsetnx(key, address, p.id))
262
+ return true;
263
+ const holder = await kv.hget(key, address);
264
+ if (holder === p.id)
265
+ return true;
266
+ if (holder !== null && (await holds(homeOf(p), holder, address)))
267
+ return false;
268
+ if (holder !== null)
269
+ await kv.hdel(key, address);
270
+ return kv.hsetnx(key, address, p.id);
271
+ }
272
+ /** Frees `address` when `p` holds it; an entry someone else holds stays. */
273
+ async function releaseEmail(p, address) {
274
+ if (address === null)
275
+ return;
276
+ const key = keyOf(homeOf(p), 'emails');
277
+ if ((await kv.hget(key, address)) === p.id)
278
+ await kv.hdel(key, address);
279
+ }
280
+ const takenEmail = () => new ReviewError('invalid', 'Someone here already signs in with that address.', [
281
+ 'email: another person’s here',
282
+ ]);
283
+ /** Saves a new person, their address claimed first: one a live person here holds is refused, with nothing written. */
284
+ async function saveNew(p) {
285
+ if (p.email !== null && !(await claimEmail(p, p.email)))
286
+ throw takenEmail();
287
+ await savePerson(p);
288
+ }
289
+ /**
290
+ * Who an address signs in where `at` is: on a client's host, that client's
291
+ * people only; on the studio's own host, the studio's own. A Studio address
292
+ * on a client's host is nobody (E4), and so is another client's address.
293
+ * Null too for someone who may not sign in, or whose profile has moved on.
294
+ */
295
+ async function emailPerson(at, address) {
296
+ const home = at === STUDIO_SITE ? 'studio' : { client: at.client };
297
+ const id = await kv.hget(keyOf(home, 'emails'), address);
298
+ const p = id === null ? null : await personAt(home, id);
299
+ return active(p) && p.email === address && reaches(p, at) ? p : null;
300
+ }
301
+ /** The key codes are stored under; a service given none cannot make or check one. */
302
+ function codeKey() {
303
+ if (!deps.codeKey)
304
+ throw new Error('The review service was given no key for sign-in codes.');
305
+ return deps.codeKey;
306
+ }
307
+ /** What a code's HMAC is taken over: the person, so one code's hash says nothing of another's. */
308
+ const codeHash = (key, id, code) => hmacHex(key, `code\n${id}\n${code}`);
309
+ /** CODE.digits random digits, each value equally likely. */
310
+ function newCode() {
311
+ const space = 10 ** CODE.digits;
312
+ // The largest multiple of `space` four bytes hold: a value at or past it is drawn again, so no code is likelier.
313
+ const limit = Math.floor(2 ** 32 / space) * space;
314
+ for (;;) {
315
+ const n = deps.random(4).reduce((acc, byte) => acc * 256 + byte, 0);
316
+ if (n < limit)
317
+ return String(n % space).padStart(CODE.digits, '0');
318
+ }
319
+ }
320
+ /** Removes one person's fields, `<id>:<suffix>`, from `key`, but those whose suffix `keep` says to keep. */
321
+ async function dropFields(key, id, keep) {
322
+ for (const field of Object.keys(await kv.hgetall(key)))
323
+ if (field.startsWith(`${id}:`) && !keep(field.slice(id.length + 1)))
324
+ await kv.hdel(key, field);
325
+ }
326
+ /**
327
+ * Counts one more code made for a person this hour, before it is made: the
328
+ * count is the limit, so of two asks at once both count and neither is a
329
+ * 6th that passes. Their earlier hours' fields go. True while within CODE.perHour.
330
+ */
331
+ async function countSend(home, id, at) {
332
+ const hour = String(Math.floor(at / HOUR_MS));
333
+ const key = keyOf(home, 'sends');
334
+ const n = await kv.hincrby(key, `${id}:${hour}`, 1);
335
+ await dropFields(key, id, (h) => h === hour);
336
+ return n <= CODE.perHour;
337
+ }
338
+ /**
339
+ * Claims this clock minute's code for a person: true for the ask that
340
+ * raised the count to 1. HINCRBY, so of two asks at once (a double press
341
+ * of Send code) one makes a code and the other none. Their earlier
342
+ * minutes' fields go.
343
+ */
344
+ async function claimMinute(home, id, at) {
345
+ const minute = String(Math.floor(at / MINUTE_MS));
346
+ const key = keyOf(home, 'asks');
347
+ const n = await kv.hincrby(key, `${id}:${minute}`, 1);
348
+ await dropFields(key, id, (m) => m === minute);
349
+ return n === 1;
350
+ }
351
+ /**
352
+ * The field a code's wrong tries are counted in: the person and when the
353
+ * code ends. Each code counts its own, so a new code starts at none with no
354
+ * reset that a try landing at the same moment could slip past.
355
+ */
356
+ const triesField = (id, code) => `${id}:${Date.parse(code.expiresAt)}`;
357
+ /**
358
+ * Claims `field` (a used link's or code's hash) for `p`, by the browser
359
+ * `by`: true when this call wrote it. HSETNX, so of two claims at once one
360
+ * holds, and the loser reads the winner's record (reclaim). The person's
361
+ * earlier claim goes: they keep one.
362
+ */
363
+ async function claimUse(home, field, p, by) {
364
+ const key = keyOf(home, 'used');
365
+ const record = { person: p.id, epoch: p.epoch, by, at: now() };
366
+ if (!(await kv.hsetnx(key, field, JSON.stringify(record))))
367
+ return false;
368
+ const last = await kv.hget(key, p.id);
369
+ await kv.hset(key, p.id, field);
370
+ if (last !== null && last !== field)
371
+ await kv.hdel(key, last);
372
+ return true;
373
+ }
374
+ /**
375
+ * A second press: who the claim on `field` signs in again, for the same
376
+ * browser (`by`) inside CLAIM_SECONDS, read again and still able to sign in
377
+ * where `at` is, on the same epoch (and `address`, for a code). Null for
378
+ * anyone else, or later.
379
+ */
380
+ async function reclaim(at, home, field, by, address = null) {
381
+ if (by === null)
382
+ return null;
383
+ const c = readClaim(await kv.hget(keyOf(home, 'used'), field));
384
+ if (!c || c.by === null || !sameDigest(c.by, by))
385
+ return null;
386
+ const age = deps.now().getTime() - Date.parse(c.at);
387
+ if (!(age >= 0 && age < CLAIM_SECONDS * 1000))
388
+ return null;
389
+ const p = await personAt(home, c.person);
390
+ if (!active(p) || p.epoch !== c.epoch || !reaches(p, at))
391
+ return null;
392
+ return address === null || p.email === address ? p : null;
393
+ }
394
+ /** Takes `field` in `key` (a link or a code) after its claim: true when it was there; if not, the claim goes again. */
395
+ async function take(home, key, field, claimed) {
396
+ if ((await kv.hdel(key, field)) === 1)
397
+ return true;
398
+ await kv.hdel(keyOf(home, 'used'), claimed);
399
+ return false;
400
+ }
401
+ /**
402
+ * A code's first use: the wrong tries raised before the compare, so the
403
+ * count is the limit (past CODE.tries the code is dead, a right answer
404
+ * too, and no two requests at once get a 6th try), the compare in constant
405
+ * time, then the claim, then the code taken. True when this answer used
406
+ * it; false for a wrong, ended or dead code; 'taken' when there is no live
407
+ * code to try, or another answer claimed it first.
408
+ */
409
+ async function firstUse(home, p, hash, by) {
410
+ const codes = keyOf(home, 'codes');
411
+ const live = readCode(await kv.hget(codes, p.id));
412
+ if (!live)
413
+ return 'taken';
414
+ if (live.expiresAt <= now())
415
+ return false;
416
+ if ((await kv.hincrby(keyOf(home, 'tries'), triesField(p.id, live), 1)) > CODE.tries)
417
+ return 'taken';
418
+ // The end again, after the count: a count dropped as ended (askCode) and raised again is never compared.
419
+ if (live.expiresAt <= now())
420
+ return false;
421
+ if (!sameDigest(hash, live.hash))
422
+ return false;
423
+ if (!(await claimUse(home, hash, p, by)))
424
+ return 'taken';
425
+ return take(home, codes, p.id, hash);
426
+ }
185
427
  async function issueLink(p) {
186
428
  // The link carries the token; the store keeps only its hash, so a leaked store signs nobody in.
187
429
  const token = base64url(deps.random(32));
@@ -216,6 +458,18 @@ export function createReview(kv, overrides = {}) {
216
458
  }
217
459
  return null;
218
460
  }
461
+ /** A link already used, pressed again: the browser that claimed it, inside CLAIM_SECONDS (reclaim), where `at` reaches. */
462
+ async function againLink(at, token, by) {
463
+ if (by === null)
464
+ return null;
465
+ const hash = await linkKey(token);
466
+ for (const home of at === STUDIO_SITE ? ['studio'] : [at, 'studio']) {
467
+ const p = await reclaim(at, home, hash, by);
468
+ if (p)
469
+ return p;
470
+ }
471
+ return null;
472
+ }
219
473
  /** The person a current link signs in, while they may sign in here. */
220
474
  async function linkPerson(at, { home, link }) {
221
475
  if (link.expiresAt <= now())
@@ -243,13 +497,12 @@ export function createReview(kv, overrides = {}) {
243
497
  ...fields,
244
498
  team,
245
499
  client: null,
246
- email: null,
247
500
  accessEndsAt: accessEnd(access ?? 'open', deps.now()),
248
501
  createdAt: now(),
249
502
  revokedAt: null,
250
503
  epoch: 0,
251
504
  };
252
- await savePerson(p);
505
+ await saveNew(p);
253
506
  return p;
254
507
  }
255
508
  /**
@@ -498,7 +751,7 @@ export function createReview(kv, overrides = {}) {
498
751
  async setStudioHost(actor, host) {
499
752
  allowStudio(actor);
500
753
  if (hostName(host) !== host)
501
- throw new ReviewError('invalid', 'Some fields are not valid.', ['host: a host name in lower case']);
754
+ throw new ReviewError('invalid', NOT_VALID, ['host: a host name in lower case']);
502
755
  const hosts = keyOf('studio', 'hosts');
503
756
  if (await kv.hsetnx(hosts, host, STUDIO_SITE))
504
757
  return 'added';
@@ -795,7 +1048,7 @@ export function createReview(kv, overrides = {}) {
795
1048
  async startBuild(scope, actor, build) {
796
1049
  await allow(scope, actor, 'setup', NO_PROJECT);
797
1050
  if (!isBuildId(build))
798
- throw new ReviewError('invalid', 'Some fields are not valid.', ['build: a build id']);
1051
+ throw new ReviewError('invalid', NOT_VALID, ['build: a build id']);
799
1052
  if (!(await projectAt(scope)))
800
1053
  throw new ReviewError('not_found', NO_PROJECT);
801
1054
  const key = keyOf(scope, 'builds');
@@ -819,7 +1072,7 @@ export function createReview(kv, overrides = {}) {
819
1072
  async setBuild(scope, actor, build) {
820
1073
  await allow(scope, actor, 'setup', NO_PROJECT);
821
1074
  if (!isBuildId(build))
822
- throw new ReviewError('invalid', 'Some fields are not valid.', ['build: a build id']);
1075
+ throw new ReviewError('invalid', NOT_VALID, ['build: a build id']);
823
1076
  const p = await projectAt(scope);
824
1077
  if (!p)
825
1078
  throw new ReviewError('not_found', NO_PROJECT);
@@ -877,6 +1130,9 @@ export function createReview(kv, overrides = {}) {
877
1130
  * an access length, a Client gets the default and Studio is open-ended.
878
1131
  * Without a team, a Studio person gets the studio's, which every Studio
879
1132
  * person carries, so the adder's; a Client gets their client's name.
1133
+ * An email, when given, is claimed first: an address a live person of
1134
+ * the same home holds is refused, with nothing written. The service
1135
+ * never mails anyone; whoever calls it does.
880
1136
  */
881
1137
  async addPerson(at, actor, input) {
882
1138
  const by = await allowPeople(at, actor);
@@ -884,7 +1140,7 @@ export function createReview(kv, overrides = {}) {
884
1140
  // A Client belongs to one client: the studio's own host names none.
885
1141
  const scope = fields.kind === 'studio' ? null : at;
886
1142
  if (scope === STUDIO_SITE)
887
- throw new ReviewError('invalid', 'Some fields are not valid.', ['kind: studio here']);
1143
+ throw new ReviewError('invalid', NOT_VALID, ['kind: studio here']);
888
1144
  // S13: the person's own length, else (a Client) the client's default, then the studio's, then 3m.
889
1145
  const length = access ?? (scope ? await readDefault(scope) : 'open');
890
1146
  const p = {
@@ -892,13 +1148,12 @@ export function createReview(kv, overrides = {}) {
892
1148
  ...fields,
893
1149
  team: team ?? (scope ? ((await clientAt(scope.client))?.name ?? 'Client') : by.team),
894
1150
  client: scope ? scope.client : null,
895
- email: null,
896
1151
  accessEndsAt: accessEnd(length, deps.now()),
897
1152
  createdAt: now(),
898
1153
  revokedAt: null,
899
1154
  epoch: 0,
900
1155
  };
901
- await savePerson(p);
1156
+ await saveNew(p);
902
1157
  return { person: p, token: await issueLink(p) };
903
1158
  },
904
1159
  /** Another one-time link, for another device. Their sessions and other unused links stay. */
@@ -907,12 +1162,14 @@ export function createReview(kv, overrides = {}) {
907
1162
  const p = await needActive(scope, id);
908
1163
  return { person: p, token: await issueLink(p) };
909
1164
  },
910
- /** Ends every session they hold and every unused link, and gives one new link. */
1165
+ /** Ends every session they hold, every unused link and their sign-in code, and gives one new link. */
911
1166
  async signOutEverywhere(scope, actor, id) {
912
1167
  await allowPeople(scope, actor);
913
1168
  const p = await needActive(scope, id);
914
1169
  // The epoch first: a failure after it has still ended every session. Atomic, so two at once raise it twice.
915
1170
  const next = { ...p, epoch: await kv.hincrby(keyOf(homeOf(p), 'epochs'), id, 1) };
1171
+ // An unused code is an unused way in, as a link is.
1172
+ await kv.hdel(keyOf(homeOf(p), 'codes'), id);
916
1173
  await dropLinks(p);
917
1174
  return { person: next, token: await issueLink(next) };
918
1175
  },
@@ -927,6 +1184,9 @@ export function createReview(kv, overrides = {}) {
927
1184
  if (!p.revokedAt)
928
1185
  await kv.hset(keyOf(homeOf(p), 'revoked'), id, revokedAt);
929
1186
  const epoch = await kv.hincrby(keyOf(homeOf(p), 'epochs'), id, 1);
1187
+ // Revoked, they hold their address no more: someone added again may have it (E5). Their code
1188
+ // signs nobody in, since useCode reads them again.
1189
+ await releaseEmail(p, p.email);
930
1190
  await dropLinks(p);
931
1191
  return { ...p, revokedAt, epoch };
932
1192
  },
@@ -941,6 +1201,31 @@ export function createReview(kv, overrides = {}) {
941
1201
  // Read back, so the answer carries a revocation or epoch that landed meanwhile.
942
1202
  return (await personAt(homeOf(p), id));
943
1203
  },
1204
+ /**
1205
+ * Sets, changes or clears (null, or empty) the address one person signs
1206
+ * in with by code. The new address is claimed before the profile names
1207
+ * it, and refused while another live person of the same home holds it;
1208
+ * the old one is freed after. The same address saved again claims it
1209
+ * again, which mends an entry left missing or stale. Any change ends their live code, which was
1210
+ * sent to the old address. Studio only (the `people` action).
1211
+ */
1212
+ async setEmail(at, actor, id, email) {
1213
+ await allowPeople(at, actor);
1214
+ const address = valid(checkEmail(email));
1215
+ const p = await needPerson(at, id);
1216
+ if (p.revokedAt)
1217
+ throw new ReviewError('invalid', 'That person is revoked; add them again.');
1218
+ // Claimed even when the profile names it already: saving it again mends an entry that a change at
1219
+ // the same moment, or a step that stopped part way, left missing or someone else's.
1220
+ if (address !== null && !(await claimEmail(p, address)))
1221
+ throw takenEmail();
1222
+ if (address === p.email)
1223
+ return p;
1224
+ await savePerson({ ...p, email: address });
1225
+ await releaseEmail(p, p.email);
1226
+ await kv.hdel(keyOf(homeOf(p), 'codes'), id);
1227
+ return (await personAt(homeOf(p), id));
1228
+ },
944
1229
  /** How long a new Client of the scope's client keeps access unless Studio says otherwise: the client's default, else the studio's. */
945
1230
  async defaultAccess(scope, actor) {
946
1231
  await allow(scope, actor, 'people', NO_PERSON);
@@ -997,26 +1282,125 @@ export function createReview(kv, overrides = {}) {
997
1282
  return found ? linkPerson(at, found) : null;
998
1283
  },
999
1284
  /**
1000
- * Uses a link up and returns who it signs in. The delete is the claim: of
1001
- * two requests with one token, only the one whose delete removed the link
1002
- * gets a person, so a link signs in one device at most. Who it signs in is
1003
- * read and checked first, so the delete is the last store call. Only a
1004
- * link of the scope's client, or a Studio person's, is found at all; on
1285
+ * Uses a link up and returns who it signs in. The claim (HSETNX on
1286
+ * `used`, then the link's delete) decides: of two requests with one
1287
+ * token, only the one that wrote the claim gets a person, so a link signs
1288
+ * in one device at most. The other is a second press: it signs in only
1289
+ * the same browser (`browser`, its `try` cookie) inside CLAIM_SECONDS,
1290
+ * the person read again. Who it signs in is read and checked first. Only
1291
+ * a link of the scope's client, or a Studio person's, is found at all; on
1005
1292
  * the studio's own host, only a Studio person's.
1006
1293
  */
1007
- async useLink(at, token) {
1294
+ async useLink(at, token, browser = null) {
1295
+ if (!LINK_TOKEN.test(token))
1296
+ return null;
1297
+ const by = await browserOf(browser);
1008
1298
  const found = await findLink(at, token);
1009
- // Every read and check comes before the delete, so a store failure before it leaves the link usable.
1299
+ // Every read and check comes before the claim, so a store failure before it leaves the link usable.
1010
1300
  const p = found && (await linkPerson(at, found));
1011
- if (!found || !p)
1301
+ if (!found)
1302
+ return againLink(at, token, by);
1303
+ if (!p)
1012
1304
  return null;
1013
- if ((await kv.hdel(keyOf(found.home, 'links'), found.hash)) !== 1)
1305
+ if (!(await claimUse(found.home, found.hash, p, by)))
1306
+ return reclaim(at, found.home, found.hash, by);
1307
+ if (!(await take(found.home, keyOf(found.home, 'links'), found.hash, found.hash)))
1014
1308
  return null;
1015
1309
  // A revoke or sign out everywhere can land between the check and the claim, before its
1016
1310
  // dropLinks reaches this link: read again, and sign in only someone still active on the same epoch.
1017
1311
  const after = await personAt(found.home, p.id);
1018
1312
  return active(after) && after.epoch === p.epoch ? after : null;
1019
1313
  },
1314
+ /**
1315
+ * A new sign-in code for whoever holds `email` where `at` is (emailPerson),
1316
+ * asked by the gate with no actor, in place of their live one: the person
1317
+ * and the code, for the caller to mail, or null. Null, never a throw, for
1318
+ * an address that is malformed, unknown here, revoked, past its access
1319
+ * end, asked again inside a minute, or past CODE.perHour this hour, so
1320
+ * the gate gives one answer whatever comes back. The store keeps only the
1321
+ * code's HMAC (`hash`, which the mail's idempotency key names); the new
1322
+ * code's wrong tries are counted apart from any other's.
1323
+ */
1324
+ async askCode(at, email) {
1325
+ const key = codeKey();
1326
+ const address = emailOf(email);
1327
+ const p = address === null ? null : await emailPerson(at, address);
1328
+ if (!p)
1329
+ return null;
1330
+ const home = homeOf(p);
1331
+ const t = deps.now().getTime();
1332
+ const live = readCode(await kv.hget(keyOf(home, 'codes'), p.id));
1333
+ // One a minute, read from the live code; two asks at once may both pass it, and claimMinute lets one on.
1334
+ if (live && t - Date.parse(live.sentAt) < CODE.gapSeconds * 1000)
1335
+ return null;
1336
+ // Two asks at once both pass that read: this claim lets one of them on.
1337
+ if (!(await claimMinute(home, p.id, t)))
1338
+ return null;
1339
+ if (!(await countSend(home, p.id, t)))
1340
+ return null;
1341
+ const code = newCode();
1342
+ const stored = {
1343
+ hash: await codeHash(key, p.id, code),
1344
+ expiresAt: new Date(t + CODE.minutes * MINUTE_MS).toISOString(),
1345
+ sentAt: new Date(t).toISOString(),
1346
+ };
1347
+ await kv.hset(keyOf(home, 'codes'), p.id, JSON.stringify(stored));
1348
+ // The counts of codes already past their end go; a try counted on one after this is refused
1349
+ // by useCode's second look at the end, so no code ever gets its count back.
1350
+ await dropFields(keyOf(home, 'tries'), p.id, (end) => Number(end) > t);
1351
+ return { person: p, code, hash: stored.hash };
1352
+ },
1353
+ /**
1354
+ * Counts one request from a network address against the gate's cap
1355
+ * (CAP), in this clock minute, before anyone is looked up: true while it
1356
+ * is within. The address is kept as an HMAC under the code key, never as
1357
+ * it is; the minute two before goes, so the store holds about two.
1358
+ */
1359
+ async hit(kind, address) {
1360
+ const minute = Math.floor(deps.now().getTime() / MINUTE_MS);
1361
+ const field = `${kind}:${await hmacHex(codeKey(), `hit\n${address}`)}`;
1362
+ const n = await kv.hincrby(keyOf('studio', 'hits', minute), field, 1);
1363
+ if (minute >= 2)
1364
+ await kv.del(keyOf('studio', 'hits', minute - 2));
1365
+ return n <= CAP[kind];
1366
+ },
1367
+ /** 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. */
1368
+ async recordMail(answer) {
1369
+ await kv.hset(keyOf('studio', 'mail'), answer === 'sent' ? 'okAt' : 'failedAt', now());
1370
+ },
1371
+ /** When a mail the studio sent was last taken, and last not. */
1372
+ async mailRecord() {
1373
+ const record = await kv.hgetall(keyOf('studio', 'mail'));
1374
+ return { okAt: record.okAt ?? null, failedAt: record.failedAt ?? null };
1375
+ },
1376
+ /**
1377
+ * Signs in with a code, asked by the gate with no actor: who it signs in,
1378
+ * or null. The wrong tries are raised before the compare, so the count is
1379
+ * the limit: past CODE.tries the code is dead, a right answer too, and no
1380
+ * two requests at once get a 6th try. The compare runs in constant time.
1381
+ * The claim is useLink's: of two right answers at once, one signs in, and
1382
+ * the other only when it is the same browser pressing again (`browser`).
1383
+ * The person is read again after it, so a revoke, a sign out everywhere
1384
+ * or a changed address that landed meanwhile signs nobody in.
1385
+ */
1386
+ async useCode(at, email, code, browser = null) {
1387
+ const key = codeKey();
1388
+ const address = emailOf(email);
1389
+ const given = codeOf(code);
1390
+ const p = address === null || given === null ? null : await emailPerson(at, address);
1391
+ if (!p || address === null || given === null)
1392
+ return null;
1393
+ const home = homeOf(p);
1394
+ const hash = await codeHash(key, p.id, given);
1395
+ const first = await firstUse(home, p, hash, await browserOf(browser));
1396
+ // A code already used, or one this answer did not claim: the browser that claimed it, pressing again.
1397
+ if (first === 'taken')
1398
+ return reclaim(at, home, hash, await browserOf(browser), address);
1399
+ const after = first ? await personAt(home, p.id) : null;
1400
+ return active(after) && after.epoch === p.epoch && after.email === address && reaches(after, at)
1401
+ ? after
1402
+ : null;
1403
+ },
1020
1404
  /**
1021
1405
  * A prototype's comments as the actor's view sees them. `viewAs: 'client'`
1022
1406
  * is Studio's Client view; it never widens a Client's.
@@ -1161,7 +1545,7 @@ export function createReview(kv, overrides = {}) {
1161
1545
  async controlsOf(scope, actor, prototype) {
1162
1546
  const by = await allow(scope, actor, 'read', NO_PROTOTYPE);
1163
1547
  if (!isPrototypeSlug(prototype))
1164
- throw new ReviewError('invalid', 'Some fields are not valid.', ['prototype: a prototype slug']);
1548
+ throw new ReviewError('invalid', NOT_VALID, ['prototype: a prototype slug']);
1165
1549
  const view = viewOf(by);
1166
1550
  if (!(await reachable(scope, view, prototype)))
1167
1551
  throw new ReviewError('not_found', NO_PROTOTYPE);
@@ -31,8 +31,14 @@ export interface KV {
31
31
  * this database serves (its studio.json `id`), set once by `studio create`
32
32
  * and checked by every command before it acts (server/mark.ts). No other
33
33
  * key names a studio, so two studios on one database would be one studio.
34
+ * `mail`, two fields, `okAt` and `failedAt`: when a mail the studio sends was
35
+ * last taken and last not, set after every send by whoever sent it.
36
+ * `hits:<minute>` (minutes since the epoch): the gate's cap per network
37
+ * address, `<kind>:<HMAC of the address>` to the requests counted that
38
+ * minute, raised by HINCRBY, so the count is the cap; the key of two minutes
39
+ * before goes on the next count.
34
40
  */
35
- type StudioName = 'people' | 'revoked' | 'epochs' | 'links' | 'settings' | 'mark' | 'proof';
41
+ type StudioName = 'people' | 'revoked' | 'epochs' | 'links' | 'settings' | 'mark' | 'proof' | 'mail';
36
42
  /**
37
43
  * The studio's clients, outside every scope: `clients`, a client's slug to
38
44
  * its Client; `hosts`, a host name to the slug of the client it serves, or
@@ -57,8 +63,28 @@ type DirectoryName = 'clients' | 'hosts' | 'claims' | 'held';
57
63
  * the answer the gate gives for that ask (PROOF_PATH in prototype.ts).
58
64
  * `handoffs`: Studio opening this client from the studio's host,
59
65
  * hex(sha256(token)) to a Handoff, deleted when the client's host claims it.
66
+ *
67
+ * Email sign-in, kept the same way for a client's people and the studio's
68
+ * own: `emails`, an address to the id of the one live person holding it,
69
+ * claimed with HSETNX and released when the address changes or the person is
70
+ * revoked. `codes`, a person's id to their one live Code; a dead or expired
71
+ * one stays until a new code replaces it or a right answer removes it.
72
+ * `tries`, `<person id>:<code's end, ms>` to the wrong tries on that code,
73
+ * raised by HINCRBY before each compare, so each code counts its own and no
74
+ * reset is ever raced; ended codes' fields go when a new code is made. `sends`,
75
+ * `<person id>:<hour>` (hours since the epoch) to the codes made for them
76
+ * that hour, raised by HINCRBY before a code is made, so the count is the
77
+ * limit; their other hours' fields go on their next ask. `asks`,
78
+ * `<person id>:<minute>` to the asks of that clock minute, raised by HINCRBY:
79
+ * only the ask that raised it to 1 may make a code, so two at once make one;
80
+ * their other minutes' fields go on their next ask. `used` (email.md
81
+ * calls it `claims`, which the studio's directory already names), what a
82
+ * used link or code was claimed by, for a second press from the same browser:
83
+ * hex(sha256(token)) of a link, or a code's HMAC, to a Claim, written with
84
+ * HSETNX, so of two claims at once one holds; and a person's id to their one
85
+ * Claim's field, so their earlier one goes when they make a new one.
60
86
  */
61
- type ClientName = 'people' | 'revoked' | 'epochs' | 'links';
87
+ type ClientName = 'people' | 'revoked' | 'epochs' | 'links' | 'emails' | 'codes' | 'tries' | 'sends' | 'asks' | 'used';
62
88
  type ClientOnlyName = 'projects' | 'proof' | 'handoffs';
63
89
  /**
64
90
  * A project's records. `audiences`: which prototypes are client-facing,
@@ -87,6 +113,7 @@ type PrototypeName = 'comments' | 'controls';
87
113
  * no part can hold the `:` that joins them.
88
114
  */
89
115
  export declare function keyOf(scope: 'studio', name: StudioName | DirectoryName): string;
116
+ export declare function keyOf(scope: 'studio', name: 'hits', minute: number): string;
90
117
  export declare function keyOf(scope: 'studio' | Scope, name: ClientName): string;
91
118
  export declare function keyOf(scope: Scope, name: ClientOnlyName | ProjectName): string;
92
119
  export declare function keyOf(scope: Scope, name: PrototypeName, prototype: string): string;