@milesroxas/design-hub 0.12.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 (92) hide show
  1. package/README.md +5 -5
  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 +575 -39
  6. package/core/review/service.ts +452 -25
  7. package/core/review/store.ts +47 -6
  8. package/core/review/suite-kv.ts +17 -0
  9. package/dist/core/prototype.d.ts +20 -2
  10. package/dist/core/prototype.js +17 -2
  11. package/dist/core/review/model.d.ts +42 -3
  12. package/dist/core/review/model.js +52 -3
  13. package/dist/core/review/service.d.ts +81 -7
  14. package/dist/core/review/service.js +407 -23
  15. package/dist/core/review/store.d.ts +29 -2
  16. package/dist/core/review/store.js +6 -2
  17. package/dist/core/review/suite-kv.d.ts +7 -0
  18. package/dist/core/review/suite-kv.js +12 -0
  19. package/dist/scripts/client.d.ts +1 -1
  20. package/dist/scripts/client.js +4 -4
  21. package/dist/scripts/lib/cli.js +5 -0
  22. package/dist/scripts/lib/dns.d.ts +16 -2
  23. package/dist/scripts/lib/dns.js +66 -3
  24. package/dist/scripts/lib/fake-host.d.ts +17 -3
  25. package/dist/scripts/lib/fake-host.js +56 -10
  26. package/dist/scripts/lib/host.d.ts +15 -25
  27. package/dist/scripts/lib/host.js +15 -324
  28. package/dist/scripts/lib/resend.d.ts +36 -0
  29. package/dist/scripts/lib/resend.js +66 -0
  30. package/dist/scripts/lib/studio-deps.d.ts +23 -0
  31. package/dist/scripts/lib/studio-deps.js +46 -16
  32. package/dist/scripts/lib/studios.d.ts +16 -6
  33. package/dist/scripts/lib/studios.js +28 -10
  34. package/dist/scripts/lib/vercel-host.d.ts +17 -0
  35. package/dist/scripts/lib/vercel-host.js +416 -0
  36. package/dist/scripts/people.d.ts +16 -4
  37. package/dist/scripts/people.js +67 -17
  38. package/dist/scripts/share.js +3 -2
  39. package/dist/scripts/studio.d.ts +26 -4
  40. package/dist/scripts/studio.js +364 -19
  41. package/dist/server/api.d.ts +20 -7
  42. package/dist/server/api.js +83 -27
  43. package/dist/server/dev.js +21 -1
  44. package/dist/server/gate.d.ts +120 -0
  45. package/dist/server/gate.js +808 -0
  46. package/dist/server/mailer.d.ts +60 -0
  47. package/dist/server/mailer.js +104 -0
  48. package/dist/server/mailers/fake.d.ts +8 -0
  49. package/dist/server/mailers/fake.js +16 -0
  50. package/dist/server/mailers/resend.d.ts +21 -0
  51. package/dist/server/mailers/resend.js +49 -0
  52. package/dist/server/mark.d.ts +17 -0
  53. package/dist/server/mark.js +46 -1
  54. package/dist/server/session.d.ts +2 -1
  55. package/dist/server/session.js +6 -3
  56. package/dist/server/stores/backends.d.ts +22 -0
  57. package/dist/server/stores/backends.js +96 -0
  58. package/dist/server/{fake-upstash.js → stores/fake-upstash.js} +1 -1
  59. package/dist/server/stores/index.d.ts +41 -0
  60. package/dist/server/stores/index.js +63 -0
  61. package/dist/server/stores/pglite.d.ts +16 -0
  62. package/dist/server/stores/pglite.js +98 -0
  63. package/dist/server/stores/postgres.d.ts +63 -0
  64. package/dist/server/stores/postgres.js +153 -0
  65. package/dist/server/{upstash.d.ts → stores/upstash.d.ts} +1 -1
  66. package/dist/vercel/files.js +1 -1
  67. package/dist/vercel/proxy.d.ts +6 -82
  68. package/dist/vercel/proxy.js +24 -524
  69. package/dist/vite/plugin.js +4 -2
  70. package/kit/ui/Menu.tsx +29 -18
  71. package/kit/ui/layer.ts +41 -0
  72. package/package.json +3 -1
  73. package/shell/review/Bar.tsx +1 -0
  74. package/shell/review/Card.tsx +17 -7
  75. package/shell/review/People.tsx +908 -134
  76. package/shell/review/Review.tsx +2 -2
  77. package/shell/review/anchor.ts +6 -1
  78. package/shell/review/client.ts +41 -7
  79. package/shell/review/menu-place.test.ts +41 -0
  80. package/shell/review/place.test.ts +26 -1
  81. package/shell/review/place.ts +17 -0
  82. package/shell/review/review.css +97 -11
  83. package/shell/review/view.test.ts +115 -1
  84. package/shell/review/view.ts +92 -2
  85. package/shell/studio/StudioHub.tsx +1 -0
  86. package/shell/studio/hub.css +99 -13
  87. package/skills/miles-deploy/SKILL.md +26 -4
  88. package/templates/studio/.env.example +9 -0
  89. package/templates/studio/README.md +13 -0
  90. package/templates/studio/package.json +1 -1
  91. /package/dist/server/{fake-upstash.d.ts → stores/fake-upstash.d.ts} +0 -0
  92. /package/dist/server/{upstash.js → stores/upstash.js} +0 -0
@@ -1,8 +1,9 @@
1
1
  import assert from 'node:assert/strict';
2
2
  import { beforeEach, test } from 'node:test';
3
- import { type Anchor, accessEnd, type Comment, type Person, type Scope, threadLabel } from './model.ts';
3
+ import { type Anchor, accessEnd, CODE, type Comment, type Person, type Scope, threadLabel } from './model.ts';
4
4
  import { createReview, REUSE_SECONDS, type Review, ReviewError } from './service.ts';
5
- import { type KV, keyOf, memoryKV, type Snapshot } from './store.ts';
5
+ import { type KV, keyOf, type Snapshot } from './store.ts';
6
+ import { suiteKV } from './suite-kv.ts';
6
7
 
7
8
  const anchor: Anchor = {
8
9
  prototype: 'sample-list',
@@ -55,7 +56,7 @@ const LIVE = live('acme', 'bravo');
55
56
 
56
57
  beforeEach(async () => {
57
58
  clock = Date.parse('2030-01-01T00:00:00Z');
58
- review = createReview(memoryKV(LIVE), {
59
+ review = createReview(suiteKV(LIVE), {
59
60
  now: () => {
60
61
  clock += 1000;
61
62
  return new Date(clock);
@@ -144,7 +145,7 @@ test('a revoke ends every session and link, and a revoked person gets no new lin
144
145
  });
145
146
 
146
147
  test('a store failure before the claim leaves the link usable', async () => {
147
- const kv = memoryKV(LIVE);
148
+ const kv = suiteKV(LIVE);
148
149
  let failPeople = false;
149
150
  const flaky: KV = {
150
151
  ...kv,
@@ -165,7 +166,7 @@ test('a store failure before the claim leaves the link usable', async () => {
165
166
  test('the store never holds a link token in clear', async () => {
166
167
  let seen: Snapshot = { hashes: {}, sets: {} };
167
168
  const r = createReview(
168
- memoryKV(LIVE, (snapshot) => {
169
+ suiteKV(LIVE, (snapshot) => {
169
170
  seen = snapshot;
170
171
  }),
171
172
  );
@@ -183,7 +184,7 @@ test('the store never holds a link token in clear', async () => {
183
184
 
184
185
  test('a revoke writes revocation and epoch, never the profile, before it drops their links', async () => {
185
186
  const writes: string[] = [];
186
- const kv = memoryKV(LIVE);
187
+ const kv = suiteKV(LIVE);
187
188
  const watched: KV = {
188
189
  ...kv,
189
190
  hset: async (key, field, value) => {
@@ -216,7 +217,7 @@ test('a revoke writes revocation and epoch, never the profile, before it drops t
216
217
  * until the test releases it: a real interleaving, not two calls in a row.
217
218
  */
218
219
  function pausingKV() {
219
- const kv = memoryKV(LIVE);
220
+ const kv = suiteKV(LIVE);
220
221
  let arm = false;
221
222
  let reached = () => {};
222
223
  let release = () => {};
@@ -330,7 +331,7 @@ for (const [what, run] of [
330
331
  ['a sign out everywhere', (r: Review, root: Person, id: string) => r.signOutEverywhere(A, root, id)],
331
332
  ] as const)
332
333
  test(`a link used while ${what} lands signs nobody in`, async () => {
333
- const { store, arm, pauses } = pausing(memoryKV(LIVE), {
334
+ const { store, arm, pauses } = pausing(suiteKV(LIVE), {
334
335
  claim: { method: 'hdel', key: keyOf(A, 'links') },
335
336
  drop: { method: 'hgetall', key: keyOf(A, 'links') },
336
337
  });
@@ -353,7 +354,7 @@ for (const [what, run] of [
353
354
  });
354
355
 
355
356
  test('any revocation record means revoked, and an access end that does not parse means no access', async () => {
356
- const kv = memoryKV(LIVE);
357
+ const kv = suiteKV(LIVE);
357
358
  const r = createReview(kv);
358
359
  const root = { ...studio, id: 'cli' };
359
360
  const a = (await r.addPerson(A, root, { name: 'Rae', team: 'Acme' })).person;
@@ -369,7 +370,7 @@ test('any revocation record means revoked, and an access end that does not parse
369
370
  });
370
371
 
371
372
  test('a profile that is not a well-formed person is no person, and listPeople skips it', async () => {
372
- const kv = memoryKV(LIVE);
373
+ const kv = suiteKV(LIVE);
373
374
  const r = createReview(kv);
374
375
  const root = { ...studio, id: 'cli' };
375
376
  const { person } = await r.addPerson(A, root, { name: 'Rae', team: 'Acme' });
@@ -411,7 +412,7 @@ test('two sign outs everywhere at once both end the earlier sessions', async ()
411
412
  });
412
413
 
413
414
  test('a profile write never carries revocation or epoch', async () => {
414
- const kv = memoryKV(LIVE);
415
+ const kv = suiteKV(LIVE);
415
416
  const r = createReview(kv);
416
417
  const root = { ...studio, id: 'cli' };
417
418
  const { person } = await r.addPerson(A, root, { name: 'Rae', team: 'Acme' });
@@ -543,7 +544,7 @@ test('records under an older key prefix are never read: the unscoped hub3 store
543
544
  );
544
545
  const link = JSON.stringify({ person: 'old', expiresAt: '2999-01-01T00:00:00Z' });
545
546
  const comment = JSON.stringify({ id: 'x', thread: 'x', audience: 'client', anchor });
546
- const kv = memoryKV({
547
+ const kv = suiteKV({
547
548
  hashes: {
548
549
  ...LIVE.hashes,
549
550
  'hub3:people': { old: JSON.stringify(profile) },
@@ -613,9 +614,30 @@ test('bad input names every problem', async () => {
613
614
  );
614
615
  });
615
616
 
617
+ test('an anchor URL that a browser would read as another site is refused', async () => {
618
+ for (const url of [
619
+ '//other.example/x',
620
+ '/\\other.example/x',
621
+ '/\t/other.example/x',
622
+ 'https://other.example/',
623
+ ]) {
624
+ await assert.rejects(review.add(A, client, { body: 'x', anchor: { ...anchor, url } }), (e: unknown) => {
625
+ assert.ok(e instanceof ReviewError);
626
+ assert.deepEqual(
627
+ e.problems.map((p) => p.split(':')[0]),
628
+ ['anchor.url'],
629
+ JSON.stringify(url),
630
+ );
631
+ return true;
632
+ });
633
+ }
634
+ const ok = await review.add(A, client, { body: 'x', anchor: { ...anchor, url: '/p/?a=//b#/c' } });
635
+ assert.equal(ok.anchor?.url, '/p/?a=//b#/c');
636
+ });
637
+
616
638
  test('triage runs on add, and a failing triager never loses the comment', async () => {
617
639
  const seen: string[][] = [];
618
- const triaged = createReview(memoryKV(LIVE), {
640
+ const triaged = createReview(suiteKV(LIVE), {
619
641
  triage: async ({ states }) => {
620
642
  seen.push(states);
621
643
  return { kind: 'bug', state: states[0] ?? null, by: 'jev', confidence: 0.9 };
@@ -629,7 +651,7 @@ test('triage runs on add, and a failing triager never loses the comment', async
629
651
  });
630
652
  assert.deepEqual(seen, [['Empty', 'Real list']]);
631
653
  assert.equal(c.triage?.kind, 'bug');
632
- const failing = createReview(memoryKV(LIVE), { triage: async () => Promise.reject(new Error('down')) });
654
+ const failing = createReview(suiteKV(LIVE), { triage: async () => Promise.reject(new Error('down')) });
633
655
  await failing.setAudience(A, studio, anchor.prototype, 'client');
634
656
  assert.equal((await failing.add(A, client, { body: 'Still saved', anchor })).triage, null);
635
657
  });
@@ -795,7 +817,7 @@ test('numbers count per prototype', async () => {
795
817
  });
796
818
 
797
819
  test('the internal count starts past internal threads numbered while the two shared one count', async () => {
798
- const kv = memoryKV(LIVE);
820
+ const kv = suiteKV(LIVE);
799
821
  const r = createReview(kv);
800
822
  const root = { ...studio, id: 'cli' };
801
823
  // Under one shared count: internal 1, client-facing 2, internal 3.
@@ -830,7 +852,7 @@ test('the internal count starts past internal threads numbered while the two sha
830
852
  });
831
853
 
832
854
  test('a stored comment without an audience is internal, and one without a number has none', async () => {
833
- const kv = memoryKV(LIVE);
855
+ const kv = suiteKV(LIVE);
834
856
  const r = createReview(kv);
835
857
  const root = { ...studio, id: 'cli' };
836
858
  const rae = (await r.addPerson(A, root, { name: 'Rae', team: 'Acme' })).person;
@@ -878,7 +900,7 @@ test('a prototype is internal until Studio marks it client-facing, and internal
878
900
  });
879
901
 
880
902
  test('only client-facing is stored: internal deletes the field, and absent or garbage reads as internal', async () => {
881
- const kv = memoryKV(LIVE);
903
+ const kv = suiteKV(LIVE);
882
904
  const own = createReview(kv);
883
905
  await own.setAudience(A, studio, 'secret-plan', 'client');
884
906
  assert.deepEqual(await kv.hgetall(keyOf(A, 'audiences')), { 'secret-plan': 'client' });
@@ -1011,7 +1033,7 @@ test('a Client acting on a client-facing thread of an internal prototype is told
1011
1033
 
1012
1034
  // Slice 6: what Studio marks on a prototype's dials and variants.
1013
1035
  test('controls: Studio marks a dial either way and a variant on or off, one field each', async () => {
1014
- const kv = memoryKV(LIVE);
1036
+ const kv = suiteKV(LIVE);
1015
1037
  const own = createReview(kv);
1016
1038
  const mark = (kind: string, id: string, audience: string) =>
1017
1039
  own.setControl(A, studio, { prototype: 'sample-list', kind, id, audience });
@@ -1144,6 +1166,7 @@ const OPS: [string, (s: Scope, actor: Person, ids: Ids) => Promise<unknown>][] =
1144
1166
  ['signOutEverywhere', (s, a, ids) => review.signOutEverywhere(s, a, ids.person)],
1145
1167
  ['revoke', (s, a, ids) => review.revoke(s, a, ids.person)],
1146
1168
  ['setAccess', (s, a, ids) => review.setAccess(s, a, ids.person, 'open')],
1169
+ ['setEmail', (s, a, ids) => review.setEmail(s, a, ids.person, 'bea@bravo.test')],
1147
1170
  ['defaultAccess', (s, a) => review.defaultAccess(s, a)],
1148
1171
  ['setDefaultAccess', (s, a) => review.setDefaultAccess(s, a, 'open')],
1149
1172
  ['listComments', (s, a) => review.listComments(s, a, anchor.prototype)],
@@ -1209,6 +1232,7 @@ const BY_ID = new Set([
1209
1232
  'signOutEverywhere',
1210
1233
  'revoke',
1211
1234
  'setAccess',
1235
+ 'setEmail',
1212
1236
  'reply',
1213
1237
  'edit',
1214
1238
  'remove',
@@ -1223,6 +1247,12 @@ const ACTORLESS = [
1223
1247
  'sessionPerson',
1224
1248
  'peekLink',
1225
1249
  'useLink',
1250
+ 'askCode',
1251
+ 'useCode',
1252
+ // The gate's cap and the record of what the mail provider answered: studio-wide, by no person.
1253
+ 'hit',
1254
+ 'recordMail',
1255
+ 'mailRecord',
1226
1256
  'audienceOf',
1227
1257
  'clientOfHost',
1228
1258
  'siteOfHost',
@@ -1234,13 +1264,13 @@ const ACTORLESS = [
1234
1264
 
1235
1265
  test('every op of the review service is in the cross-client test or named as having no actor', () => {
1236
1266
  const listed = [...OPS.map(([name]) => name), ...STUDIO_WIDE.map(([name]) => name), ...ACTORLESS].sort();
1237
- assert.deepEqual(Object.keys(createReview(memoryKV())).sort(), listed);
1267
+ assert.deepEqual(Object.keys(createReview(suiteKV())).sort(), listed);
1238
1268
  });
1239
1269
 
1240
1270
  test('every op from client A’s person on client B’s scope answers as an unknown id does, and changes nothing', async () => {
1241
1271
  let snapshot = '';
1242
1272
  review = createReview(
1243
- memoryKV(live('acme'), (s) => {
1273
+ suiteKV(live('acme'), (s) => {
1244
1274
  snapshot = JSON.stringify(s);
1245
1275
  }),
1246
1276
  );
@@ -1274,7 +1304,7 @@ const ON_RECORD = new Set(['addClient', 'clientRecord', 'archiveClient', 'forget
1274
1304
  test('every op in a client archived, forgotten or never added answers as an unknown id, and writes nothing', async () => {
1275
1305
  let snapshot = '';
1276
1306
  review = createReview(
1277
- memoryKV(undefined, (s) => {
1307
+ suiteKV(undefined, (s) => {
1278
1308
  snapshot = JSON.stringify(s);
1279
1309
  }),
1280
1310
  );
@@ -1301,7 +1331,7 @@ test('every op in a client archived, forgotten or never added answers as an unkn
1301
1331
 
1302
1332
  test('a client added over keys an earlier client of its slug left starts clean, every kind of key', async () => {
1303
1333
  let seen: Snapshot = { hashes: {}, sets: {} };
1304
- const kv = memoryKV(undefined, (s) => {
1334
+ const kv = suiteKV(undefined, (s) => {
1305
1335
  seen = s;
1306
1336
  });
1307
1337
  const r = createReview(kv);
@@ -1373,7 +1403,7 @@ test('a client added over keys an earlier client of its slug left starts clean,
1373
1403
  });
1374
1404
 
1375
1405
  test('the local store’s client, which has no record, runs every op as before, and no studio may add a client by its name', async () => {
1376
- const kv = memoryKV();
1406
+ const kv = suiteKV();
1377
1407
  const r = createReview(kv);
1378
1408
  const SITE: Scope = { client: 'site', project: 'site' };
1379
1409
  const ed = (
@@ -1454,7 +1484,7 @@ test('a project’s comments, numbers, marks and audiences are its own, the same
1454
1484
  test('every record lives under its own scope’s keys, and Studio’s under the studio’s', async () => {
1455
1485
  let seen: Snapshot = { hashes: {}, sets: {} };
1456
1486
  review = createReview(
1457
- memoryKV(undefined, (s) => {
1487
+ suiteKV(undefined, (s) => {
1458
1488
  seen = s;
1459
1489
  }),
1460
1490
  );
@@ -1498,7 +1528,7 @@ test('every record lives under its own scope’s keys, and Studio’s under the
1498
1528
  });
1499
1529
 
1500
1530
  test('a profile stored at the wrong home is no person: a Client with the studio, Studio with a client', async () => {
1501
- const kv = memoryKV(LIVE);
1531
+ const kv = suiteKV(LIVE);
1502
1532
  const r = createReview(kv);
1503
1533
  const rae = (await r.addPerson(A, studio, { name: 'Rae', team: 'Acme' })).person;
1504
1534
  const profile = JSON.parse((await kv.hget(keyOf(A, 'people'), rae.id)) ?? '{}');
@@ -1515,7 +1545,7 @@ test('a profile stored at the wrong home is no person: a Client with the studio,
1515
1545
  });
1516
1546
 
1517
1547
  test('a host names its client while the client is live and its records agree; anything else is no client', async () => {
1518
- review = createReview(memoryKV());
1548
+ review = createReview(suiteKV());
1519
1549
  const acme = await review.addClient(studio, { slug: 'acme', host: 'acme.studio.test', name: 'Acme' });
1520
1550
  assert.deepEqual(acme, {
1521
1551
  slug: 'acme',
@@ -1531,7 +1561,7 @@ test('a host names its client while the client is live and its records agree; an
1531
1561
  for (const host of ['', 'nope.studio.test', 'studio.test', 'acme.studio.test.evil', 'a b'])
1532
1562
  assert.equal(await review.clientOfHost(host), null, host);
1533
1563
  // A host table entry the client's own record does not agree with, or an archived client, is no client.
1534
- const kv = memoryKV();
1564
+ const kv = suiteKV();
1535
1565
  const r = createReview(kv);
1536
1566
  await r.addClient(studio, { slug: 'acme', host: 'acme.studio.test', name: 'Acme' });
1537
1567
  await kv.hset(keyOf('studio', 'hosts'), 'alias.studio.test', 'acme');
@@ -1546,7 +1576,7 @@ test('a host names its client while the client is live and its records agree; an
1546
1576
  });
1547
1577
 
1548
1578
  test('a client is Studio’s to add, with a slug and a host nobody has, and never a name the studio keeps', async () => {
1549
- review = createReview(memoryKV());
1579
+ review = createReview(suiteKV());
1550
1580
  await review.addClient(studio, { slug: 'acme', host: 'acme.studio.test', name: 'Acme' });
1551
1581
  await rejects(review.addClient(studio, { slug: 'acme', host: 'other.studio.test', name: 'A' }), 'invalid');
1552
1582
  await rejects(review.addClient(studio, { slug: 'other', host: 'acme.studio.test', name: 'A' }), 'invalid');
@@ -1562,7 +1592,7 @@ test('a client is Studio’s to add, with a slug and a host nobody has, and neve
1562
1592
  });
1563
1593
 
1564
1594
  test('a project is its client’s: listed with a build, opened only from its own client', async () => {
1565
- review = createReview(memoryKV());
1595
+ review = createReview(suiteKV());
1566
1596
  const acme = { client: 'acme' };
1567
1597
  await rejects(review.addProject(acme, studio, { slug: 'rebrand', name: 'Rebrand' }), 'not_found');
1568
1598
  await review.addClient(studio, { slug: 'acme', host: 'acme.studio.test', name: 'Acme' });
@@ -1613,7 +1643,7 @@ test('a project is its client’s: listed with a build, opened only from its own
1613
1643
  test('a Client is refused every studio-wide op, and a signed-out caller is unauthorized, with nothing written', async () => {
1614
1644
  let snapshot = '';
1615
1645
  review = createReview(
1616
- memoryKV(LIVE, (x) => {
1646
+ suiteKV(LIVE, (x) => {
1617
1647
  snapshot = JSON.stringify(x);
1618
1648
  }),
1619
1649
  );
@@ -1698,7 +1728,7 @@ test('the People tab’s default access reads and sets the same value: the clien
1698
1728
  });
1699
1729
 
1700
1730
  test('of two adds at once, one gets the slug and one the host; the other is refused and holds nothing', async () => {
1701
- review = createReview(memoryKV());
1731
+ review = createReview(suiteKV());
1702
1732
  const make = (slug: string, host: string) => outcome(review.addClient(studio, { slug, host, name: slug }));
1703
1733
  const sameSlug = await Promise.all([make('acme', 'one.studio.test'), make('acme', 'two.studio.test')]);
1704
1734
  assert.equal(sameSlug.filter((o) => 'value' in o).length, 1);
@@ -1720,7 +1750,7 @@ test('of two adds at once, one gets the slug and one the host; the other is refu
1720
1750
  });
1721
1751
 
1722
1752
  test('archiving a client removes every key it has, so the slug and host start clean when added again', async () => {
1723
- const kv = memoryKV();
1753
+ const kv = suiteKV();
1724
1754
  const tick = () => {
1725
1755
  clock += 1000;
1726
1756
  return new Date(clock);
@@ -1811,7 +1841,7 @@ test('archiving a client removes every key it has, so the slug and host start cl
1811
1841
  });
1812
1842
 
1813
1843
  test('an archive keeps a host another client has, and frees a slug or host whose add stopped part way', async () => {
1814
- const kv = memoryKV();
1844
+ const kv = suiteKV();
1815
1845
  let now = Date.parse('2030-01-01T00:00:00Z');
1816
1846
  const r = createReview(kv, { now: () => new Date(now) });
1817
1847
  const record = (slug: string, host: string) =>
@@ -1871,7 +1901,7 @@ test('an archive keeps a host another client has, and frees a slug or host whose
1871
1901
  });
1872
1902
 
1873
1903
  test('a host proof is Studio’s to start and end, answers only its own ask in its own client, and keeps no ask', async () => {
1874
- const kv = memoryKV();
1904
+ const kv = suiteKV();
1875
1905
  const r = createReview(kv);
1876
1906
  await r.addClient(studio, { slug: 'acme', host: 'acme.studio.test', name: 'Acme' });
1877
1907
  await r.addClient(studio, { slug: 'bravo', host: 'bravo.studio.test', name: 'Bravo' });
@@ -1949,7 +1979,7 @@ for (const lands of ['during the archive', 'after the forget'] as const)
1949
1979
  return new Date(at);
1950
1980
  },
1951
1981
  };
1952
- const kv = memoryKV();
1982
+ const kv = suiteKV();
1953
1983
  const held = holdingKV(kv);
1954
1984
  const site = createReview(held.kv, deps);
1955
1985
  const cli = createReview(kv, deps);
@@ -1993,7 +2023,7 @@ for (const lands of ['during the archive', 'after the forget'] as const)
1993
2023
  test('a sweep reaches its own scope’s keys only: never acme-two’s, a sibling project’s, the studio’s or the directory’s', async () => {
1994
2024
  let at = Date.parse('2030-01-01T00:00:00Z');
1995
2025
  let seen: Snapshot = { hashes: {}, sets: {} };
1996
- const kv = memoryKV(undefined, (s) => {
2026
+ const kv = suiteKV(undefined, (s) => {
1997
2027
  seen = s;
1998
2028
  });
1999
2029
  const r = createReview(kv, {
@@ -2078,7 +2108,7 @@ test('a sweep reaches its own scope’s keys only: never acme-two’s, a sibling
2078
2108
 
2079
2109
  test('the local store is never swept: archive and forget of its client change nothing, and a project added in it deletes nothing', async () => {
2080
2110
  let snapshot = '';
2081
- const kv = memoryKV(undefined, (s) => {
2111
+ const kv = suiteKV(undefined, (s) => {
2082
2112
  snapshot = JSON.stringify(s);
2083
2113
  });
2084
2114
  const r = createReview(kv);
@@ -2104,7 +2134,7 @@ test('the local store is never swept: archive and forget of its client change no
2104
2134
  });
2105
2135
 
2106
2136
  test('a client default set while the client’s record goes is refused, and never lands as the studio’s', async () => {
2107
- const kv = memoryKV();
2137
+ const kv = suiteKV();
2108
2138
  const r = createReview(kv);
2109
2139
  await r.addClient(studio, { slug: 'acme', host: 'acme.studio.test', name: 'Acme' });
2110
2140
  // The record is there for the live check, and gone by the time the default is written: a forget landed between.
@@ -2155,7 +2185,7 @@ test('a project points only at a build started for it, never one started before
2155
2185
 
2156
2186
  /** A store with acme added (its host proven) and bravo still waiting for its host, on a clock a test moves. */
2157
2187
  async function handoffStudio() {
2158
- const kv = memoryKV();
2188
+ const kv = suiteKV();
2159
2189
  let t = Date.parse('2030-01-01T00:00:00Z');
2160
2190
  const r = createReview(kv, { now: () => new Date(t) });
2161
2191
  const ed = await r.addStudioPerson({ ...studio, id: 'cli' }, { name: 'Ed', team: 'Studio' });
@@ -2364,3 +2394,509 @@ test('the studio host’s proof is Studio’s to start and end, answers only its
2364
2394
  await r.endStudioProof(ed);
2365
2395
  assert.equal(await kv.hget(keyOf('studio', 'settings'), 'hostProvenAt'), at);
2366
2396
  });
2397
+
2398
+ // ── Email sign-in: an address on a person, and the code rules (email.md, E4 to E8) ──
2399
+
2400
+ /** The key codes are kept under in these tests, as a studio site's gate secret would be. */
2401
+ const CODE_KEY = 'c'.repeat(32);
2402
+ const ACME: Scope = { client: 'acme' };
2403
+ const BRAVO: Scope = { client: 'bravo' };
2404
+ const MINUTE = 60_000;
2405
+ /** useCode, by a name no lint reads as a React hook, for the loops that call it. */
2406
+ const tryCode = (r: Review, ...args: Parameters<Review['useCode']>) => r.useCode.apply(r, args);
2407
+
2408
+ /** Clients acme and bravo, live; Studio's Ed; a service given a code key, on a clock a test moves. */
2409
+ async function mailStudio() {
2410
+ let snapshot = '';
2411
+ const kv = suiteKV(LIVE, (s) => {
2412
+ snapshot = JSON.stringify(s);
2413
+ });
2414
+ let t = Date.parse('2030-01-01T00:00:00Z');
2415
+ const r = createReview(kv, { now: () => new Date(t), codeKey: CODE_KEY });
2416
+ const ed = await r.addStudioPerson({ ...studio, id: 'cli' }, { name: 'Ed', team: 'Studio' });
2417
+ const add = async (at: Scope | 'studio', name: string, email: string | null, access?: string) =>
2418
+ (
2419
+ await r.addPerson(at, ed, {
2420
+ name,
2421
+ kind: at === 'studio' ? 'studio' : 'client',
2422
+ email,
2423
+ ...(access ? { access } : {}),
2424
+ })
2425
+ ).person;
2426
+ return { kv, r, ed, add, move: (ms: number) => (t += ms), written: () => snapshot };
2427
+ }
2428
+
2429
+ test('an email is optional on a person, kept trimmed and lower case; a profile stored without one reads as null', async () => {
2430
+ const { kv, r, ed, add } = await mailStudio();
2431
+ assert.equal((await add(ACME, 'Rae', ' Rae@Acme.TEST ')).email, 'rae@acme.test');
2432
+ assert.equal((await add(ACME, 'Kim', null)).email, null);
2433
+ assert.equal((await add(ACME, 'Lu', '')).email, null);
2434
+ assert.equal((await r.addPerson(ACME, ed, { name: 'Mo' })).person.email, null);
2435
+ // A profile written before email existed has no field at all: a person with no address.
2436
+ const old = { id: 'old1', name: 'Old', team: 'Acme', kind: 'client', accessEndsAt: null, createdAt: '' };
2437
+ await kv.hset(keyOf(ACME, 'people'), 'old1', JSON.stringify(old));
2438
+ assert.equal((await r.person(ACME, 'old1'))?.email, null);
2439
+ assert.ok((await r.listPeople(ACME, ed)).some((p) => p.id === 'old1' && p.email === null));
2440
+ // Something that is not an address is refused, with the field named, and no one is added.
2441
+ const before = (await r.listPeople(ACME, ed)).length;
2442
+ for (const email of ['nope', 'a@b', 'a b@acme.test', 'a@acme.test, b@acme.test', '<a@acme.test>', 42, {}])
2443
+ await assert.rejects(
2444
+ r.addPerson(ACME, ed, { name: 'Oz', email }),
2445
+ (e: unknown) => e instanceof ReviewError && e.problems.some((p) => p.startsWith('email:')),
2446
+ String(email),
2447
+ );
2448
+ await rejects(r.addPerson(ACME, ed, { name: 'Oz', email: `${'a'.repeat(250)}@acme.test` }), 'invalid');
2449
+ assert.equal((await r.listPeople(ACME, ed)).length, before);
2450
+ });
2451
+
2452
+ test('E5: within one client, or the studio’s own people, an address belongs to one live person; another client’s may hold it too', async () => {
2453
+ const { kv, r, ed, add } = await mailStudio();
2454
+ const rae = await add(ACME, 'Rae', 'same@mail.test');
2455
+ const kim = await add(ACME, 'Kim', null);
2456
+ // A second Acme person with Rae's address, in any case: refused, and nothing written.
2457
+ const people = JSON.stringify(await kv.hgetall(keyOf(ACME, 'people')));
2458
+ await rejects(r.addPerson(ACME, ed, { name: 'Oz', email: 'SAME@mail.test' }), 'invalid');
2459
+ assert.equal(JSON.stringify(await kv.hgetall(keyOf(ACME, 'people'))), people);
2460
+ await rejects(r.setEmail(ACME, ed, kim.id, 'same@mail.test'), 'invalid');
2461
+ assert.equal((await r.person(ACME, kim.id))?.email, null);
2462
+ // Bravo's people and the studio's own are other lists: each may hold it once.
2463
+ const bea = await add(BRAVO, 'Bea', 'same@mail.test');
2464
+ const sam = await add('studio', 'Sam', 'same@mail.test');
2465
+ assert.deepEqual([bea.email, sam.email], ['same@mail.test', 'same@mail.test']);
2466
+ await rejects(
2467
+ r.addPerson('studio', ed, { name: 'Jo', kind: 'studio', email: 'same@mail.test' }),
2468
+ 'invalid',
2469
+ );
2470
+ await rejects(r.addStudioPerson(ed, { name: 'Jo', team: 'Studio', email: 'same@mail.test' }), 'invalid');
2471
+ assert.deepEqual(await kv.hgetall(keyOf(ACME, 'emails')), { 'same@mail.test': rae.id });
2472
+ assert.deepEqual(await kv.hgetall(keyOf(BRAVO, 'emails')), { 'same@mail.test': bea.id });
2473
+ assert.deepEqual(await kv.hgetall(keyOf('studio', 'emails')), { 'same@mail.test': sam.id });
2474
+ });
2475
+
2476
+ test('E5: a revoked person frees their address; a person past their access end keeps it, and longer access brings their sign-in back', async () => {
2477
+ const { r, ed, add, move } = await mailStudio();
2478
+ const rae = await add(ACME, 'Rae', 'rae@acme.test');
2479
+ await r.revoke(ACME, ed, rae.id);
2480
+ const again = await add(ACME, 'Rae', 'rae@acme.test');
2481
+ assert.equal((await r.askCode(ACME, 'rae@acme.test'))?.person.id, again.id);
2482
+ // Kim's access runs out: she keeps her address, so nobody else may take it, and no code goes to her.
2483
+ const kim = await add(ACME, 'Kim', 'kim@acme.test', '3m');
2484
+ move(100 * DAY);
2485
+ await rejects(r.addPerson(ACME, ed, { name: 'Oz', email: 'kim@acme.test' }), 'invalid');
2486
+ assert.equal(await r.askCode(ACME, 'kim@acme.test'), null);
2487
+ await r.setAccess(ACME, ed, kim.id, '6m');
2488
+ assert.equal((await r.askCode(ACME, 'kim@acme.test'))?.person.id, kim.id);
2489
+ });
2490
+
2491
+ test('setting, changing and clearing an address: Studio only, the old one freed, and the live code ended', async () => {
2492
+ const { kv, r, ed, add, move } = await mailStudio();
2493
+ const rae = await add(ACME, 'Rae', null);
2494
+ assert.equal((await r.setEmail(ACME, ed, rae.id, ' Rae@Acme.test')).email, 'rae@acme.test');
2495
+ // The same address again changes nothing.
2496
+ assert.equal((await r.setEmail(ACME, ed, rae.id, 'rae@acme.test')).email, 'rae@acme.test');
2497
+ const sent = await r.askCode(ACME, 'rae@acme.test');
2498
+ assert.ok(sent);
2499
+ assert.equal((await r.setEmail(ACME, ed, rae.id, 'rae@new.test')).email, 'rae@new.test');
2500
+ // The code went to the old address: it signs in on neither.
2501
+ assert.equal(await r.useCode(ACME, 'rae@acme.test', sent.code), null);
2502
+ assert.equal(await r.useCode(ACME, 'rae@new.test', sent.code), null);
2503
+ // The old address is free for someone else; the new one is Rae's.
2504
+ assert.equal((await add(ACME, 'Kim', 'rae@acme.test')).email, 'rae@acme.test');
2505
+ assert.deepEqual(await kv.hgetall(keyOf(ACME, 'emails')), {
2506
+ 'rae@new.test': rae.id,
2507
+ 'rae@acme.test': (await r.listPeople(ACME, ed)).find((p) => p.name === 'Kim')?.id,
2508
+ });
2509
+ // Cleared, by null or empty: links only again, and the address is free.
2510
+ move(MINUTE);
2511
+ assert.ok(await r.askCode(ACME, 'rae@new.test'));
2512
+ assert.equal((await r.setEmail(ACME, ed, rae.id, '')).email, null);
2513
+ assert.deepEqual(await kv.hget(keyOf(ACME, 'codes'), rae.id), null);
2514
+ assert.equal(await kv.hget(keyOf(ACME, 'emails'), 'rae@new.test'), null);
2515
+ assert.equal((await r.setEmail(ACME, ed, rae.id, 'rae@new.test')).email, 'rae@new.test');
2516
+ assert.equal((await r.setEmail(ACME, ed, rae.id, null)).email, null);
2517
+ // Refused: no address given, a malformed one, a revoked person, a Client, someone signed out, an unknown id.
2518
+ await rejects(r.setEmail(ACME, ed, rae.id, undefined), 'invalid');
2519
+ await rejects(r.setEmail(ACME, ed, rae.id, 'nope'), 'invalid');
2520
+ const client = (await r.addPerson(ACME, ed, { name: 'Bo' })).person;
2521
+ await rejects(r.setEmail(ACME, client, rae.id, 'x@acme.test'), 'forbidden');
2522
+ await rejects(r.setEmail(ACME, null, rae.id, 'x@acme.test'), 'unauthorized');
2523
+ await rejects(r.setEmail(ACME, ed, 'nobody', 'x@acme.test'), 'not_found');
2524
+ await r.revoke(ACME, ed, rae.id);
2525
+ await rejects(r.setEmail(ACME, ed, rae.id, 'x@acme.test'), 'invalid');
2526
+ // On the studio's own host, the studio's own people only.
2527
+ const sam = await add('studio', 'Sam', null);
2528
+ assert.equal((await r.setEmail('studio', ed, sam.id, 'sam@studio.test')).email, 'sam@studio.test');
2529
+ await rejects(r.setEmail('studio', ed, client.id, 'bo@acme.test'), 'not_found');
2530
+ await rejects(r.setEmail('studio', client, sam.id, 'x@studio.test'), 'forbidden');
2531
+ });
2532
+
2533
+ test('an entry left by a change or a revoke that stopped part way locks nobody out', async () => {
2534
+ const { kv, r, ed, add } = await mailStudio();
2535
+ const rae = await add(ACME, 'Rae', 'rae@acme.test');
2536
+ // Rae moved on to a new address, but the old entry stayed, as if the release never ran.
2537
+ await r.setEmail(ACME, ed, rae.id, 'rae@new.test');
2538
+ await kv.hset(keyOf(ACME, 'emails'), 'rae@acme.test', rae.id);
2539
+ const kim = await add(ACME, 'Kim', 'rae@acme.test');
2540
+ assert.equal(await kv.hget(keyOf(ACME, 'emails'), 'rae@acme.test'), kim.id);
2541
+ // A revoke that stopped before it freed the address: the entry names someone revoked, so it is free.
2542
+ const lu = await add(ACME, 'Lu', 'lu@acme.test');
2543
+ await r.revoke(ACME, ed, lu.id);
2544
+ await kv.hset(keyOf(ACME, 'emails'), 'lu@acme.test', lu.id);
2545
+ assert.equal((await add(ACME, 'Lu', 'lu@acme.test')).email, 'lu@acme.test');
2546
+ // An entry naming nobody at all is free as well.
2547
+ await kv.hset(keyOf(ACME, 'emails'), 'ghost@acme.test', 'nobody');
2548
+ assert.equal((await add(ACME, 'Lu', 'ghost@acme.test')).email, 'ghost@acme.test');
2549
+ // A Studio entry is never a client's, and the other way: each list is its own.
2550
+ assert.equal(await kv.hget(keyOf('studio', 'emails'), 'rae@acme.test'), null);
2551
+ });
2552
+
2553
+ test('E6: a code is 8 digits, signs in once, and the store keeps only its HMAC under the key the service was given', async () => {
2554
+ const { kv, r, add, written } = await mailStudio();
2555
+ const rae = await add(ACME, 'Rae', 'rae@acme.test');
2556
+ const sent = await r.askCode(ACME, ' RAE@acme.test ');
2557
+ assert.ok(sent);
2558
+ assert.match(sent.code, /^\d{8}$/);
2559
+ assert.equal(sent.person.id, rae.id);
2560
+ assert.equal(written().includes(sent.code), false);
2561
+ const stored = JSON.parse((await kv.hget(keyOf(ACME, 'codes'), rae.id)) ?? '{}');
2562
+ assert.match(stored.hash, /^[0-9a-f]{64}$/);
2563
+ assert.equal(stored.expiresAt, '2030-01-01T00:10:00.000Z');
2564
+ // A service with another key cannot check it, nor one with none at all.
2565
+ const other = createReview(kv, { now: () => new Date('2030-01-01T00:01:00Z'), codeKey: 'x'.repeat(32) });
2566
+ assert.equal(await other.useCode(ACME, 'rae@acme.test', sent.code), null);
2567
+ await assert.rejects(createReview(kv).useCode(ACME, 'rae@acme.test', sent.code), /no key/);
2568
+ await assert.rejects(createReview(kv).askCode(ACME, 'rae@acme.test'), /no key/);
2569
+ // Typed with a space between the halves, it signs Rae in, once.
2570
+ const typed = `${sent.code.slice(0, 4)} ${sent.code.slice(4)}`;
2571
+ assert.equal((await r.useCode(ACME, 'rae@acme.test', typed))?.id, rae.id);
2572
+ assert.equal(await r.useCode(ACME, 'rae@acme.test', sent.code), null);
2573
+ assert.equal(await kv.hget(keyOf(ACME, 'codes'), rae.id), null);
2574
+ });
2575
+
2576
+ test('E6: the 6th wrong try kills the code, a right answer included; 5 tries are counted, never got past by many at once', async () => {
2577
+ const { r, add, move } = await mailStudio();
2578
+ await add(ACME, 'Rae', 'rae@acme.test');
2579
+ const wrong = (code: string) => String((Number(code) + 1) % 1e8).padStart(8, '0');
2580
+ // Four wrong, then right on the 5th: signed in.
2581
+ const first = await r.askCode(ACME, 'rae@acme.test');
2582
+ assert.ok(first);
2583
+ for (let i = 0; i < 4; i++) assert.equal(await tryCode(r, ACME, 'rae@acme.test', wrong(first.code)), null);
2584
+ assert.ok(await r.useCode(ACME, 'rae@acme.test', first.code));
2585
+ // Five wrong, then right on the 6th: dead. A new code starts the tries again.
2586
+ move(MINUTE);
2587
+ const second = await r.askCode(ACME, 'rae@acme.test');
2588
+ assert.ok(second);
2589
+ for (let i = 0; i < 5; i++) assert.equal(await tryCode(r, ACME, 'rae@acme.test', wrong(second.code)), null);
2590
+ assert.equal(await r.useCode(ACME, 'rae@acme.test', second.code), null);
2591
+ move(MINUTE);
2592
+ const third = await r.askCode(ACME, 'rae@acme.test');
2593
+ assert.ok(third);
2594
+ // Ten wrong tries at once: the count is the limit, so the right one after them is the 11th, and dead.
2595
+ await Promise.all(Array.from({ length: 10 }, () => r.useCode(ACME, 'rae@acme.test', wrong(third.code))));
2596
+ assert.equal(await r.useCode(ACME, 'rae@acme.test', third.code), null);
2597
+ });
2598
+
2599
+ test('E6: a code lasts 10 minutes: in its 11th minute it is dead', async () => {
2600
+ const { r, add, move } = await mailStudio();
2601
+ const rae = await add(ACME, 'Rae', 'rae@acme.test');
2602
+ const early = await r.askCode(ACME, 'rae@acme.test');
2603
+ assert.ok(early);
2604
+ move(10 * MINUTE - 1000);
2605
+ assert.equal((await r.useCode(ACME, 'rae@acme.test', early.code))?.id, rae.id);
2606
+ const late = await r.askCode(ACME, 'rae@acme.test');
2607
+ assert.ok(late);
2608
+ move(10 * MINUTE);
2609
+ assert.equal(await r.useCode(ACME, 'rae@acme.test', late.code), null);
2610
+ });
2611
+
2612
+ test('E6: one code a minute, a new one replaces the old, and 5 an hour; the next hour gives one again', async () => {
2613
+ const { kv, r, add, move } = await mailStudio();
2614
+ const rae = await add(ACME, 'Rae', 'rae@acme.test');
2615
+ const one = await r.askCode(ACME, 'rae@acme.test');
2616
+ assert.ok(one);
2617
+ // A second ask inside the minute: nothing made, nothing counted.
2618
+ move(MINUTE - 1000);
2619
+ assert.equal(await r.askCode(ACME, 'rae@acme.test'), null);
2620
+ move(1000);
2621
+ const two = await r.askCode(ACME, 'rae@acme.test');
2622
+ assert.ok(two);
2623
+ assert.equal(await r.useCode(ACME, 'rae@acme.test', one.code), null);
2624
+ // Three more, a minute apart, make five this hour; the 6th is refused.
2625
+ for (let i = 0; i < 3; i++) {
2626
+ move(MINUTE);
2627
+ assert.ok(await r.askCode(ACME, 'rae@acme.test'), `code ${i + 3}`);
2628
+ }
2629
+ move(MINUTE);
2630
+ assert.equal(await r.askCode(ACME, 'rae@acme.test'), null);
2631
+ // The next hour gives one again, and the earlier hour's count goes.
2632
+ move(60 * MINUTE);
2633
+ assert.ok(await r.askCode(ACME, 'rae@acme.test'));
2634
+ // The try counted earlier went once its code had ended.
2635
+ assert.deepEqual(await kv.hgetall(keyOf(ACME, 'tries')), {});
2636
+ assert.deepEqual(Object.keys(await kv.hgetall(keyOf(ACME, 'sends'))), [
2637
+ `${rae.id}:${Math.floor(Date.parse('2030-01-01T01:05:00Z') / 3_600_000)}`,
2638
+ ]);
2639
+ });
2640
+
2641
+ test('E6: asks at once make one code: one a minute holds between them, so a double press sends one mail', async () => {
2642
+ const { r, add, move } = await mailStudio();
2643
+ await add(ACME, 'Rae', 'rae@acme.test');
2644
+ const two = await Promise.all([r.askCode(ACME, 'rae@acme.test'), r.askCode(ACME, 'rae@acme.test')]);
2645
+ const made = two.filter((c) => c !== null);
2646
+ assert.equal(made.length, 1);
2647
+ // The one code made is the live one: it signs in.
2648
+ const [only] = made;
2649
+ assert.ok(only);
2650
+ assert.ok(await r.useCode(ACME, 'rae@acme.test', only.code));
2651
+ move(MINUTE);
2652
+ const eight = await Promise.all(Array.from({ length: 8 }, () => r.askCode(ACME, 'rae@acme.test')));
2653
+ assert.equal(eight.filter(Boolean).length, 1);
2654
+ });
2655
+
2656
+ test('E6: of two right answers at once, one signs in', async () => {
2657
+ const { r, add } = await mailStudio();
2658
+ const rae = await add(ACME, 'Rae', 'rae@acme.test');
2659
+ const sent = await r.askCode(ACME, 'rae@acme.test');
2660
+ assert.ok(sent);
2661
+ const both = await Promise.all([
2662
+ r.useCode(ACME, 'rae@acme.test', sent.code),
2663
+ r.useCode(ACME, 'rae@acme.test', sent.code),
2664
+ ]);
2665
+ assert.deepEqual(both.map((p) => p?.id ?? null).sort(), [rae.id, null].sort());
2666
+ });
2667
+
2668
+ test('every askCode refusal is null, and those before any limit write nothing: malformed, unknown, revoked, past access end', async () => {
2669
+ const { r, ed, add, move, written } = await mailStudio();
2670
+ const rae = await add(ACME, 'Rae', 'rae@acme.test');
2671
+ await add(ACME, 'Kim', 'kim@acme.test', '3m');
2672
+ const lu = await add(ACME, 'Lu', 'lu@acme.test');
2673
+ await r.revoke(ACME, ed, lu.id);
2674
+ move(100 * DAY);
2675
+ await r.setAccess(ACME, ed, rae.id, 'open');
2676
+ const before = written();
2677
+ const asks: unknown[] = [
2678
+ undefined,
2679
+ null,
2680
+ 42,
2681
+ '',
2682
+ 'rae',
2683
+ 'rae@acme',
2684
+ 'rae @acme.test',
2685
+ ['rae@acme.test'],
2686
+ { email: 'rae@acme.test' },
2687
+ `${'r'.repeat(300)}@acme.test`,
2688
+ 'nobody@acme.test',
2689
+ 'lu@acme.test',
2690
+ 'kim@acme.test',
2691
+ ];
2692
+ for (const email of asks) assert.equal(await r.askCode(ACME, email), null, String(email));
2693
+ assert.equal(written(), before);
2694
+ // useCode answers null the same way, for each of those and for a code that is not 8 digits.
2695
+ const sent = await r.askCode(ACME, 'rae@acme.test');
2696
+ assert.ok(sent);
2697
+ for (const email of asks) assert.equal(await tryCode(r, ACME, email, sent.code), null, String(email));
2698
+ for (const code of [undefined, null, 12345678, '1234567', '123456789', 'abcdefgh', `${sent.code}x`])
2699
+ assert.equal(await tryCode(r, ACME, 'rae@acme.test', code), null, String(code));
2700
+ // None of them raised a try: the right code still signs Rae in.
2701
+ assert.equal((await r.useCode(ACME, 'rae@acme.test', sent.code))?.id, rae.id);
2702
+ // With no live code, a try finds nothing to count.
2703
+ assert.equal(await r.useCode(ACME, 'rae@acme.test', sent.code), null);
2704
+ });
2705
+
2706
+ test('E4: an address answers only where its person signs in; anywhere else it is an unknown address, and nothing is written', async () => {
2707
+ const { r, ed, add, written } = await mailStudio();
2708
+ const rae = await add(ACME, 'Rae', 'rae@acme.test');
2709
+ const sam = await add('studio', 'Sam', 'sam@studio.test');
2710
+ await r.setEmail('studio', ed, ed.id, 'ed@studio.test');
2711
+ const before = written();
2712
+ // A Studio address on a client's host, a Client's on the studio's host or another client's host: nobody.
2713
+ for (const [at, email] of [
2714
+ [ACME, 'sam@studio.test'],
2715
+ [ACME, 'ed@studio.test'],
2716
+ ['studio', 'rae@acme.test'],
2717
+ [BRAVO, 'rae@acme.test'],
2718
+ ] as const)
2719
+ assert.equal(await r.askCode(at, email), null, `${JSON.stringify(at)} ${email}`);
2720
+ assert.equal(written(), before);
2721
+ // Each signs in where it belongs, and its code is nobody's anywhere else.
2722
+ const forRae = await r.askCode(ACME, 'rae@acme.test');
2723
+ const forSam = await r.askCode('studio', 'sam@studio.test');
2724
+ assert.ok(forRae && forSam);
2725
+ assert.equal(await r.useCode(BRAVO, 'rae@acme.test', forRae.code), null);
2726
+ assert.equal(await r.useCode('studio', 'rae@acme.test', forRae.code), null);
2727
+ assert.equal(await r.useCode(ACME, 'sam@studio.test', forSam.code), null);
2728
+ assert.equal((await r.useCode(ACME, 'rae@acme.test', forRae.code))?.id, rae.id);
2729
+ assert.equal((await r.useCode('studio', 'sam@studio.test', forSam.code))?.id, sam.id);
2730
+ // Bravo's person with the same address is Bravo's alone.
2731
+ const bea = await add(BRAVO, 'Bea', 'rae@acme.test');
2732
+ assert.equal((await r.askCode(BRAVO, 'rae@acme.test'))?.person.id, bea.id);
2733
+ });
2734
+
2735
+ test('a sign out everywhere ends the live code, and a revoke between the compare and the claim signs nobody in', async () => {
2736
+ const kv = suiteKV(LIVE);
2737
+ let between: (() => Promise<unknown>) | null = null;
2738
+ const watched: KV = {
2739
+ ...kv,
2740
+ hdel: async (key, field) => {
2741
+ const run = key === keyOf(ACME, 'codes') ? between : null;
2742
+ between = null;
2743
+ await run?.();
2744
+ return kv.hdel(key, field);
2745
+ },
2746
+ };
2747
+ let t = Date.parse('2030-01-01T00:00:00Z');
2748
+ const r = createReview(watched, { now: () => new Date(t), codeKey: CODE_KEY });
2749
+ const ed = await r.addStudioPerson({ ...studio, id: 'cli' }, { name: 'Ed', team: 'Studio' });
2750
+ const rae = (await r.addPerson(ACME, ed, { name: 'Rae', email: 'rae@acme.test' })).person;
2751
+ const sent = await r.askCode(ACME, 'rae@acme.test');
2752
+ assert.ok(sent);
2753
+ await r.signOutEverywhere(ACME, ed, rae.id);
2754
+ assert.equal(await r.useCode(ACME, 'rae@acme.test', sent.code), null);
2755
+ t += MINUTE;
2756
+ const next = await r.askCode(ACME, 'rae@acme.test');
2757
+ assert.ok(next);
2758
+ // The revoke lands after the code was checked, before it is claimed.
2759
+ between = () => r.revoke(ACME, ed, rae.id);
2760
+ assert.equal(await r.useCode(ACME, 'rae@acme.test', next.code), null);
2761
+ assert.ok((await r.person(ACME, rae.id))?.revokedAt);
2762
+ });
2763
+
2764
+ // ── Fix pass: the tries are a code's own ──
2765
+
2766
+ /** A store in which a test can hold one call back until it lets go. */
2767
+ function gatedKV(kv: KV) {
2768
+ let hold: ((op: string, key: string) => Promise<void> | undefined) | null = null;
2769
+ const wrapped = Object.fromEntries(
2770
+ Object.entries(kv).map(([name, op]) => [
2771
+ name,
2772
+ async (...args: string[]) => {
2773
+ await hold?.(name, args[0]);
2774
+ return (op as (...a: string[]) => Promise<unknown>)(...args);
2775
+ },
2776
+ ]),
2777
+ ) as unknown as KV;
2778
+ return { kv: wrapped, onCall: (h: typeof hold) => (hold = h) };
2779
+ }
2780
+
2781
+ /** A store whose every call first waits a few ticks, chosen by `seed`, so calls at once interleave in many orders. */
2782
+ function jitterKV(kv: KV, seed: number): KV {
2783
+ let s = seed;
2784
+ const ticks = () => {
2785
+ s = (s * 1103515245 + 12345) & 0x7fffffff;
2786
+ return (s >>> 16) % 4;
2787
+ };
2788
+ return Object.fromEntries(
2789
+ Object.entries(kv).map(([name, op]) => [
2790
+ name,
2791
+ async (...args: string[]) => {
2792
+ for (let i = ticks(); i > 0; i--) await new Promise((r) => setImmediate(r));
2793
+ return (op as (...a: string[]) => Promise<unknown>)(...args);
2794
+ },
2795
+ ]),
2796
+ ) as unknown as KV;
2797
+ }
2798
+
2799
+ test('E6: wrong tries that land while a new code is being written still count: the 10th try, right, is dead', async () => {
2800
+ const g = gatedKV(suiteKV(LIVE));
2801
+ const r = createReview(g.kv, { now: () => new Date('2030-01-01T00:00:00Z'), codeKey: CODE_KEY });
2802
+ const ed = await r.addStudioPerson({ ...studio, id: 'cli' }, { name: 'Ed', team: 'Studio' });
2803
+ await r.addPerson(ACME, ed, { name: 'Rae', email: 'rae@acme.test' });
2804
+ let release = () => {};
2805
+ let reached = () => {};
2806
+ const held = new Promise<void>((resolve) => {
2807
+ release = resolve;
2808
+ });
2809
+ const there = new Promise<void>((resolve) => {
2810
+ reached = resolve;
2811
+ });
2812
+ // askCode has written the new code; whatever it does to the tries after that (a try counts by HINCRBY, so
2813
+ // anything else is askCode's) waits here, and the test goes on only once it has got there.
2814
+ g.onCall((op, key) => {
2815
+ if (op === 'hincrby' || key !== keyOf(ACME, 'tries')) return undefined;
2816
+ reached();
2817
+ return held;
2818
+ });
2819
+ const asking = r.askCode(ACME, 'rae@acme.test');
2820
+ await there;
2821
+ for (let i = 0; i < 5; i++) assert.equal(await tryCode(r, ACME, 'rae@acme.test', '00000000'), null);
2822
+ release();
2823
+ const sent = await asking;
2824
+ g.onCall(null);
2825
+ assert.ok(sent && sent.code !== '00000000');
2826
+ for (let i = 0; i < 4; i++) assert.equal(await tryCode(r, ACME, 'rae@acme.test', '00000000'), null);
2827
+ assert.equal(await r.useCode(ACME, 'rae@acme.test', sent.code), null);
2828
+ });
2829
+
2830
+ test('E6: new codes and guesses at once never compare more than 5 guesses a code, 25 an hour, in any order tried', async () => {
2831
+ for (let seed = 1; seed <= 6; seed++) {
2832
+ let compared = 0;
2833
+ const base = suiteKV(LIVE);
2834
+ const counting: KV = {
2835
+ ...base,
2836
+ hincrby: async (key, field, by) => {
2837
+ const n = await base.hincrby(key, field, by);
2838
+ if (key === keyOf(ACME, 'tries') && n <= CODE.tries) compared++;
2839
+ return n;
2840
+ },
2841
+ };
2842
+ let t = Date.parse('2030-01-01T00:00:00Z');
2843
+ const r = createReview(jitterKV(counting, seed), { now: () => new Date(t), codeKey: CODE_KEY });
2844
+ const ed = await r.addStudioPerson({ ...studio, id: 'cli' }, { name: 'Ed', team: 'Studio' });
2845
+ await r.addPerson(ACME, ed, { name: 'Rae', email: 'rae@acme.test' });
2846
+ for (let minute = 0; minute < 8; minute++) {
2847
+ const work: Promise<unknown>[] = [r.askCode(ACME, 'rae@acme.test')];
2848
+ for (let i = 0; i < 12; i++) work.push(tryCode(r, ACME, 'rae@acme.test', '00000000'));
2849
+ await Promise.all(work);
2850
+ t += MINUTE + 1;
2851
+ }
2852
+ assert.ok(compared <= 5 * CODE.tries, `seed ${seed}: ${compared} guesses compared in one hour`);
2853
+ }
2854
+ });
2855
+
2856
+ test('saving the same address again mends a person whose entry is missing or names someone no longer holding it', async () => {
2857
+ const { kv, r, ed, add } = await mailStudio();
2858
+ const rae = await add(ACME, 'Rae', 'rae@acme.test');
2859
+ // The entry is gone, as a change at the same moment can leave it: no code goes to Rae.
2860
+ await kv.hdel(keyOf(ACME, 'emails'), 'rae@acme.test');
2861
+ assert.equal(await r.askCode(ACME, 'rae@acme.test'), null);
2862
+ assert.equal((await r.setEmail(ACME, ed, rae.id, 'rae@acme.test')).email, 'rae@acme.test');
2863
+ assert.equal((await r.askCode(ACME, 'rae@acme.test'))?.person.id, rae.id);
2864
+ // The entry names a person since revoked: saving it again takes it back.
2865
+ const kim = await add(ACME, 'Kim', 'kim@acme.test');
2866
+ const gone = await add(ACME, 'Gone', null);
2867
+ await r.revoke(ACME, ed, gone.id);
2868
+ await kv.hset(keyOf(ACME, 'emails'), 'kim@acme.test', gone.id);
2869
+ assert.equal(await r.askCode(ACME, 'kim@acme.test'), null);
2870
+ await r.setEmail(ACME, ed, kim.id, 'kim@acme.test');
2871
+ assert.equal((await r.askCode(ACME, 'kim@acme.test'))?.person.id, kim.id);
2872
+ // While a live person holds it, saving it on someone else is still refused, the address named.
2873
+ const lu = await add(ACME, 'Lu', null);
2874
+ await assert.rejects(r.setEmail(ACME, ed, lu.id, 'kim@acme.test'), /already signs in with that address/);
2875
+ });
2876
+
2877
+ test('a refused address is said in a sentence, taken or malformed, by add and by setEmail; other refusals still name their fields', async () => {
2878
+ const { r, ed, add } = await mailStudio();
2879
+ const rae = await add(ACME, 'Rae', 'rae@acme.test');
2880
+ const kim = await add(ACME, 'Kim', null);
2881
+ const said = (p: Promise<unknown>, message: string, problems: string[]) =>
2882
+ assert.rejects(p, (e: unknown) => {
2883
+ assert.ok(e instanceof ReviewError);
2884
+ assert.deepEqual([e.message, e.problems], [message, problems]);
2885
+ return true;
2886
+ });
2887
+ const TAKEN = 'Someone here already signs in with that address.';
2888
+ const MALFORMED = 'That is not an email address. Use one such as name@example.com, or leave it empty.';
2889
+ const PROBLEM = 'email: an address such as name@example.com, or empty for links only';
2890
+ await said(r.setEmail(ACME, ed, kim.id, 'rae@acme.test'), TAKEN, ['email: another person’s here']);
2891
+ await said(r.addPerson(ACME, ed, { name: 'Oz', email: 'rae@acme.test' }), TAKEN, [
2892
+ 'email: another person’s here',
2893
+ ]);
2894
+ await said(r.setEmail(ACME, ed, kim.id, 'rae@acme'), MALFORMED, [PROBLEM]);
2895
+ await said(r.addPerson(ACME, ed, { name: 'Oz', email: 'rae@acme' }), MALFORMED, [PROBLEM]);
2896
+ // With another field wrong too, every problem is named, as before.
2897
+ await said(r.addPerson(ACME, ed, { name: '', email: 'rae@acme' }), 'Some fields are not valid.', [
2898
+ 'name: required',
2899
+ PROBLEM,
2900
+ ]);
2901
+ assert.equal((await r.person(ACME, rae.id))?.email, 'rae@acme.test');
2902
+ });