@milesroxas/design-hub 0.10.0 → 0.11.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 (131) hide show
  1. package/README.md +13 -11
  2. package/core/files.test.ts +76 -0
  3. package/core/files.ts +131 -0
  4. package/core/prototype.test.ts +124 -7
  5. package/core/prototype.ts +133 -24
  6. package/core/review/model.ts +119 -2
  7. package/core/review/policy.test.ts +79 -22
  8. package/core/review/policy.ts +36 -8
  9. package/core/review/service.test.ts +1464 -340
  10. package/core/review/service.ts +777 -191
  11. package/core/review/store.test.ts +91 -0
  12. package/core/review/store.ts +143 -33
  13. package/dist/core/files.d.ts +39 -0
  14. package/dist/core/files.js +107 -0
  15. package/dist/core/prototype.d.ts +61 -12
  16. package/dist/core/prototype.js +105 -26
  17. package/dist/core/review/model.d.ts +76 -2
  18. package/dist/core/review/model.js +76 -1
  19. package/dist/core/review/policy.d.ts +11 -4
  20. package/dist/core/review/policy.js +14 -2
  21. package/dist/core/review/service.d.ts +197 -45
  22. package/dist/core/review/service.js +702 -192
  23. package/dist/core/review/store.d.ts +84 -31
  24. package/dist/core/review/store.js +66 -33
  25. package/dist/scripts/bootstrap.d.ts +4 -34
  26. package/dist/scripts/bootstrap.js +9 -244
  27. package/dist/scripts/cli.js +6 -0
  28. package/dist/scripts/client.d.ts +45 -0
  29. package/dist/scripts/client.js +320 -0
  30. package/dist/scripts/commands.js +6 -0
  31. package/dist/scripts/comments.d.ts +8 -26
  32. package/dist/scripts/comments.js +27 -14
  33. package/dist/scripts/lib/builds.d.ts +40 -0
  34. package/dist/scripts/lib/builds.js +198 -0
  35. package/dist/scripts/lib/cli.js +3 -1
  36. package/dist/scripts/lib/deploy.d.ts +6 -90
  37. package/dist/scripts/lib/deploy.js +24 -137
  38. package/dist/scripts/lib/dns.d.ts +49 -0
  39. package/dist/scripts/lib/dns.js +141 -0
  40. package/dist/scripts/lib/fake-host.d.ts +168 -0
  41. package/dist/scripts/lib/fake-host.js +244 -0
  42. package/dist/scripts/lib/host.d.ts +87 -0
  43. package/dist/scripts/lib/host.js +362 -0
  44. package/dist/scripts/lib/linked.d.ts +51 -0
  45. package/dist/scripts/lib/linked.js +124 -0
  46. package/dist/scripts/lib/names.d.ts +35 -0
  47. package/dist/scripts/lib/names.js +77 -0
  48. package/dist/scripts/lib/review.d.ts +23 -2
  49. package/dist/scripts/lib/review.js +32 -15
  50. package/dist/scripts/lib/studio-deps.d.ts +35 -0
  51. package/dist/scripts/lib/studio-deps.js +79 -0
  52. package/dist/scripts/lib/studios.d.ts +70 -0
  53. package/dist/scripts/lib/studios.js +187 -0
  54. package/dist/scripts/lib/update.d.ts +33 -0
  55. package/dist/scripts/lib/update.js +40 -0
  56. package/dist/scripts/lib/vercel.d.ts +1 -23
  57. package/dist/scripts/lib/vercel.js +6 -81
  58. package/dist/scripts/people.d.ts +7 -11
  59. package/dist/scripts/people.js +51 -46
  60. package/dist/scripts/preflight.d.ts +8 -1
  61. package/dist/scripts/preflight.js +36 -19
  62. package/dist/scripts/project.d.ts +86 -0
  63. package/dist/scripts/project.js +141 -0
  64. package/dist/scripts/share.d.ts +105 -30
  65. package/dist/scripts/share.js +82 -154
  66. package/dist/scripts/skills.d.ts +18 -2
  67. package/dist/scripts/skills.js +22 -3
  68. package/dist/scripts/studio.d.ts +75 -0
  69. package/dist/scripts/studio.js +401 -0
  70. package/dist/scripts/upgrade.d.ts +10 -2
  71. package/dist/scripts/upgrade.js +44 -14
  72. package/dist/server/api.d.ts +22 -11
  73. package/dist/server/api.js +114 -46
  74. package/dist/server/blob.d.ts +10 -0
  75. package/dist/server/blob.js +53 -0
  76. package/dist/server/checks.js +2 -2
  77. package/dist/server/dev.js +4 -4
  78. package/dist/server/env.d.ts +2 -0
  79. package/dist/server/env.js +9 -0
  80. package/dist/server/fake-upstash.js +52 -3
  81. package/dist/server/hosts.d.ts +11 -0
  82. package/dist/server/hosts.js +31 -0
  83. package/dist/server/local.d.ts +7 -1
  84. package/dist/server/local.js +10 -1
  85. package/dist/server/mark.d.ts +41 -0
  86. package/dist/server/mark.js +111 -0
  87. package/dist/server/session.d.ts +17 -9
  88. package/dist/server/session.js +22 -45
  89. package/dist/server/upstash.js +20 -0
  90. package/dist/vercel/files.d.ts +11 -0
  91. package/dist/vercel/files.js +68 -0
  92. package/dist/vercel/index.d.ts +4 -3
  93. package/dist/vercel/index.js +12 -8
  94. package/dist/vercel/proxy.d.ts +69 -4
  95. package/dist/vercel/proxy.js +171 -107
  96. package/dist/vite/plugin.d.ts +24 -1
  97. package/dist/vite/plugin.js +46 -2
  98. package/kit/dials.tsx +2 -2
  99. package/package.json +2 -1
  100. package/shell/Guide.tsx +11 -5
  101. package/shell/Index.tsx +32 -10
  102. package/shell/Notice.tsx +1 -1
  103. package/shell/controls.ts +1 -1
  104. package/shell/hub.ts +5 -1
  105. package/shell/main.tsx +18 -3
  106. package/shell/review/Review.tsx +2 -2
  107. package/shell/review/ThreadCard.tsx +5 -5
  108. package/shell/review/client.ts +28 -11
  109. package/shell/review/view.test.ts +19 -0
  110. package/shell/review/view.ts +25 -0
  111. package/shell/shell.css +4 -0
  112. package/shell/studio/ClientHub.tsx +98 -0
  113. package/shell/studio/hub.css +48 -0
  114. package/shell/studio/index.html +14 -0
  115. package/shell/studio/main.tsx +17 -0
  116. package/skills/miles-deploy/SKILL.md +120 -65
  117. package/skills/miles-design-hub/SKILL.md +11 -9
  118. package/skills/miles-review/SKILL.md +5 -7
  119. package/skills/miles-worktrees/SKILL.md +3 -3
  120. package/templates/conductor/settings.toml +1 -1
  121. package/templates/studio/.env.example +9 -0
  122. package/templates/studio/.vercelignore +5 -0
  123. package/templates/studio/README.md +84 -0
  124. package/templates/studio/_gitignore +7 -0
  125. package/templates/studio/api/files.ts +4 -0
  126. package/templates/studio/api/review.ts +4 -0
  127. package/templates/studio/build.mjs +4 -0
  128. package/templates/studio/package.json +16 -0
  129. package/templates/studio/proxy.ts +4 -0
  130. package/templates/studio/studio.json +9 -0
  131. package/templates/studio/vercel.json +27 -0
@@ -4,9 +4,15 @@
4
4
  // policy.ts hold everywhere. Writes are per record (one hash field per
5
5
  // person, per comment), so two people commenting at once never collide;
6
6
  // two edits of the same comment at once keep the last.
7
+ //
8
+ // Every method takes the Scope it runs in first, and every key it reads or
9
+ // writes is built from that scope (keyOf in store.ts). A person outside the
10
+ // scope gets the answer an unknown id gets, never forbidden, so no answer
11
+ // says what another client holds.
7
12
  import { base64url, hex, sha256 } from '../bytes.ts';
8
13
  import { type ControlKind, controlField, type Marks, readMarks } from '../controls.ts';
9
- import { isPrototypeSlug } from '../prototype.ts';
14
+ import { isBuildId } from '../files.ts';
15
+ import { hostName, isClientSlug, isProjectSlug, isPrototypeSlug } from '../prototype.ts';
10
16
  import {
11
17
  type Access,
12
18
  type Anchor,
@@ -14,30 +20,41 @@ import {
14
20
  accessEnd,
15
21
  authorOf,
16
22
  type Checked,
23
+ type Client,
17
24
  type Comment,
18
25
  checkAccess,
19
26
  checkAnchor,
20
27
  checkAudience,
21
28
  checkBody,
29
+ checkClientInput,
22
30
  checkControl,
23
31
  checkPersonInput,
32
+ checkProjectInput,
24
33
  checkPrototypeAudience,
25
34
  checkStates,
26
35
  checkTriage,
27
36
  checkViewAs,
28
37
  DEFAULT_ACCESS,
38
+ HOST_SECONDS,
29
39
  hasAccess,
30
40
  isProfile,
31
41
  isRoot,
42
+ isStudioClient,
32
43
  LINK_DAYS,
33
44
  type Link,
45
+ LOCAL_CLIENT,
34
46
  type Person,
35
47
  type PersonKind,
48
+ type Profile,
49
+ type Project,
50
+ readClient,
36
51
  readComment,
52
+ readProject,
53
+ type Scope,
37
54
  type Triage,
38
55
  } from './model.ts';
39
- import { type Action, audienceFor, can, viewOf, visibleTo } from './policy.ts';
40
- import { KEY, type KV } from './store.ts';
56
+ import { type Action, audienceFor, can, inScope, viewOf, visibleTo } from './policy.ts';
57
+ import { type KV, keyOf, sweepPrefix } from './store.ts';
41
58
 
42
59
  export type ErrorCode = 'unauthorized' | 'forbidden' | 'not_found' | 'invalid';
43
60
 
@@ -73,6 +90,55 @@ const defaults: Deps = {
73
90
  const LINK_TOKEN = /^[\w-]{20,100}$/;
74
91
  const linkKey = async (token: string) => hex(await sha256(token));
75
92
 
93
+ /**
94
+ * How long a slug or host stays out of reach after its client is archived:
95
+ * twice the time a studio site's instance keeps a host's answer. An instance
96
+ * that cached the archived client's record keeps accepting that client's
97
+ * fresh tokens until its answer runs out; if the slug came back sooner, it
98
+ * would show them the new client's projects.
99
+ */
100
+ export const REUSE_SECONDS = 2 * HOST_SECONDS;
101
+
102
+ /** A started build of a project: the order it was started in, and whether the project ever pointed at it. */
103
+ type BuildEntry = { n: number; live: boolean };
104
+ export type Build = BuildEntry & { build: string };
105
+
106
+ function readBuildEntry(json: string | null): BuildEntry | null {
107
+ try {
108
+ const v = json === null ? null : JSON.parse(json);
109
+ return v && Number.isSafeInteger(v.n) && typeof v.live === 'boolean' ? { n: v.n, live: v.live } : null;
110
+ } catch {
111
+ return null;
112
+ }
113
+ }
114
+
115
+ /** What an archive answers: the archived record, and whether its host is the client's own to take off the site. */
116
+ export type Archived = { client: Client; ownHost: boolean };
117
+
118
+ const tooSoon = (seconds: number) =>
119
+ new ReviewError(
120
+ 'invalid',
121
+ `That client or host was archived moments ago: add it again in ${seconds} seconds.`,
122
+ [`wait: ${seconds} seconds`],
123
+ );
124
+
125
+ /** What an op answers when what it names is not there, or is outside the actor's scope. */
126
+ const NO_COMMENT = 'No such comment.';
127
+ const NO_PERSON = 'No such person.';
128
+ const NO_PROTOTYPE = 'No such prototype.';
129
+ const NO_CLIENT = 'No such client.';
130
+ export const NO_PROJECT = 'No such project.';
131
+
132
+ /**
133
+ * Where a person's records live: Studio's with the studio, a Client's with
134
+ * their client. A scope reaches its own client's people and the studio's.
135
+ */
136
+ type Home = 'studio' | Scope;
137
+ const homeOf = ({ client }: Pick<Person, 'client'>): Home => (client === null ? 'studio' : { client });
138
+
139
+ /** A person and a new one-time link's token for them. */
140
+ type Issued = { person: Person; token: string };
141
+
76
142
  export function createReview(kv: KV, overrides: Partial<Deps> = {}) {
77
143
  const deps = { ...defaults, ...overrides };
78
144
  const now = () => deps.now().toISOString();
@@ -89,14 +155,58 @@ export function createReview(kv: KV, overrides: Partial<Deps> = {}) {
89
155
  }
90
156
  };
91
157
 
92
- function allow(
93
- actor: Person | null,
94
- action: Action,
95
- root?: Comment,
96
- subject?: Comment,
97
- ): asserts actor is Person {
158
+ /** Signed in, then in scope. Out of scope answers `missing`, what the op answers an unknown id. */
159
+ function admit(scope: Scope, actor: Person | null, missing: string): asserts actor is Person {
98
160
  if (!actor) throw new ReviewError('unauthorized', 'Sign in with your link to do that.');
99
- if (!can(actor, action, root, subject)) throw new ReviewError('forbidden', 'You cannot do that.');
161
+ if (!inScope(actor, scope)) throw new ReviewError('not_found', missing);
162
+ }
163
+
164
+ /**
165
+ * Whether ops may run in a client: its record is there and not archived,
166
+ * or it is the local store's, which never has one (LOCAL_CLIENT).
167
+ */
168
+ const isLive = async (client: string) =>
169
+ client === LOCAL_CLIENT || (await clientAt(client))?.archivedAt === null;
170
+
171
+ /**
172
+ * The first check of every op with an actor that runs in a client: signed
173
+ * in, in scope, the scope's client live, then allowed. Out of scope, or a
174
+ * client archived or gone, answers `missing`, what the op answers an
175
+ * unknown id, so it never tells a Client whether another client holds
176
+ * anything. The client is read here, from the store, on every op: a host's
177
+ * answer cached by an instance can name a client archived since, and
178
+ * nothing may write into the keys its archive swept.
179
+ */
180
+ async function allow(scope: Scope, actor: Person | null, action: Action, missing: string): Promise<Person> {
181
+ admit(scope, actor, missing);
182
+ if (!(await isLive(scope.client))) throw new ReviewError('not_found', missing);
183
+ permit(scope, actor, action);
184
+ return actor;
185
+ }
186
+
187
+ /**
188
+ * The first check of an op on a client's record itself (add, read,
189
+ * archive, forget), which runs while the record is absent or archived:
190
+ * signed in, in scope, then Studio. Nothing it does writes in the client.
191
+ */
192
+ function allowRecord(scope: Scope, actor: Person | null): asserts actor is Person {
193
+ admit(scope, actor, NO_CLIENT);
194
+ permit(scope, actor, 'setup');
195
+ }
196
+
197
+ /**
198
+ * The first check of an op on the studio as a whole, which names no client:
199
+ * signed in, then Studio. A Client is refused; no answer names a client.
200
+ */
201
+ function allowStudio(actor: Person | null): asserts actor is Person {
202
+ if (!actor) throw new ReviewError('unauthorized', 'Sign in with your link to do that.');
203
+ if (actor.kind !== 'studio' || actor.client !== null || actor.revokedAt)
204
+ throw new ReviewError('forbidden', 'You cannot do that.');
205
+ }
206
+
207
+ /** Whether the actor may act on this thread, or on `subject`, a reply in it. */
208
+ function permit(scope: Scope, actor: Person, action: Action, root?: Comment, subject?: Comment): void {
209
+ if (!can(actor, scope, action, root, subject)) throw new ReviewError('forbidden', 'You cannot do that.');
100
210
  }
101
211
 
102
212
  function valid<T>(checked: Checked<T>): T {
@@ -111,32 +221,51 @@ export function createReview(kv: KV, overrides: Partial<Deps> = {}) {
111
221
  return checks.map((c) => (c as { value: unknown }).value) as T;
112
222
  }
113
223
 
114
- // A person is three records. The profile (KEY.people) is read-modify-write, so
224
+ // A person is three records. The profile (`people`) is read-modify-write, so
115
225
  // a stale write of it can land after anything. Revocation and the epoch live
116
226
  // outside it: revocation is written once and never cleared, the epoch only
117
227
  // rises (HINCRBY), so no profile write, however stale, can revive a session.
228
+ // A person's client is where the three live, never a field anyone writes.
118
229
  const compose = (
230
+ home: Home,
119
231
  json: string | null,
120
232
  revoked: string | null | undefined,
121
233
  epoch: string | null | undefined,
122
- ) => {
234
+ ): Person | null => {
123
235
  const profile = safeParse(json);
124
236
  if (!isProfile(profile)) return null;
237
+ // Studio lives with the studio and a Client with their client: a profile anywhere else is no person.
238
+ if ((profile.kind === 'studio') !== (home === 'studio')) return null;
125
239
  // Any revocation record means revoked, an empty one included: it reads as the start of time.
126
240
  const revokedAt = revoked == null ? null : revoked || new Date(0).toISOString();
127
- return { ...profile, revokedAt, epoch: Number(epoch ?? 0) };
241
+ const client = home === 'studio' ? null : home.client;
242
+ return { ...profile, client, revokedAt, epoch: Number(epoch ?? 0) };
128
243
  };
129
- const person = async (id: string): Promise<Person | null> => {
244
+ const personAt = async (home: Home, id: string): Promise<Person | null> => {
130
245
  const [json, revoked, epoch] = await Promise.all([
131
- kv.hget(KEY.people, id),
132
- kv.hget(KEY.revoked, id),
133
- kv.hget(KEY.epochs, id),
246
+ kv.hget(keyOf(home, 'people'), id),
247
+ kv.hget(keyOf(home, 'revoked'), id),
248
+ kv.hget(keyOf(home, 'epochs'), id),
249
+ ]);
250
+ return compose(home, json, revoked, epoch);
251
+ };
252
+ /** Someone the scope reaches: a Client of its client, else a Studio person. */
253
+ const person = async (scope: Scope, id: string): Promise<Person | null> =>
254
+ (await personAt(scope, id)) ?? personAt('studio', id);
255
+ /** Every person at one home, skipping any profile that is not a well-formed person. */
256
+ const peopleAt = async (home: Home): Promise<Person[]> => {
257
+ const [profiles, revoked, epochs] = await Promise.all([
258
+ kv.hgetall(keyOf(home, 'people')),
259
+ kv.hgetall(keyOf(home, 'revoked')),
260
+ kv.hgetall(keyOf(home, 'epochs')),
134
261
  ]);
135
- return compose(json, revoked, epoch);
262
+ return Object.entries(profiles)
263
+ .map(([id, json]) => compose(home, json, revoked[id], epochs[id]))
264
+ .filter((p): p is Person => p !== null);
136
265
  };
137
- /** Writes the profile alone: revocation and epoch are never part of what it saves. */
138
- const savePerson = ({ revokedAt: _r, epoch: _e, ...profile }: Person) =>
139
- kv.hset(KEY.people, profile.id, JSON.stringify(profile));
266
+ /** Writes the profile alone, at the person's home: revocation, epoch and client are never part of it. */
267
+ const savePerson = ({ revokedAt: _r, epoch: _e, client, ...profile }: Person) =>
268
+ kv.hset(keyOf(homeOf({ client }), 'people'), profile.id, JSON.stringify(profile satisfies Profile));
140
269
  /** Not revoked, and their access has not ended. */
141
270
  const active = (p: Person | null): p is Person => !!p && hasAccess(p, deps.now());
142
271
 
@@ -147,47 +276,121 @@ export function createReview(kv: KV, overrides: Partial<Deps> = {}) {
147
276
  person: p.id,
148
277
  expiresAt: new Date(deps.now().getTime() + LINK_DAYS * DAY_MS).toISOString(),
149
278
  };
150
- await kv.hset(KEY.links, await linkKey(token), JSON.stringify(link));
279
+ // A link lives with its person, so it signs in only where that person's scope reaches.
280
+ await kv.hset(keyOf(homeOf(p), 'links'), await linkKey(token), JSON.stringify(link));
151
281
  return token;
152
282
  }
153
283
 
154
- async function dropLinks(personId: string): Promise<void> {
155
- const all = await kv.hgetall(KEY.links);
156
- for (const [hash, json] of Object.entries(all))
157
- if ((JSON.parse(json) as Link).person === personId) await kv.hdel(KEY.links, hash);
284
+ async function dropLinks(p: Person): Promise<void> {
285
+ const links = keyOf(homeOf(p), 'links');
286
+ for (const [hash, json] of Object.entries(await kv.hgetall(links)))
287
+ if ((JSON.parse(json) as Link).person === p.id) await kv.hdel(links, hash);
158
288
  }
159
289
 
160
- /** The link a token names, or null for a malformed or unknown token. */
161
- async function findLink(token: string): Promise<{ key: string; link: Link } | null> {
290
+ type Found = { home: Home; hash: string; link: Link };
291
+
292
+ /** The link a token names in the scope's client or the studio, or null for a malformed or unknown token. */
293
+ async function findLink(scope: Scope, token: string): Promise<Found | null> {
162
294
  if (!LINK_TOKEN.test(token)) return null;
163
- const key = await linkKey(token);
164
- const link = parse<Link>(await kv.hget(KEY.links, key));
165
- return link ? { key, link } : null;
295
+ const hash = await linkKey(token);
296
+ for (const home of [scope, 'studio'] as const) {
297
+ const link = parse<Link>(await kv.hget(keyOf(home, 'links'), hash));
298
+ if (link) return { home, hash, link };
299
+ }
300
+ return null;
166
301
  }
167
302
 
168
- /** The person a current link signs in, while they may sign in. */
169
- async function linkPerson(link: Link): Promise<Person | null> {
303
+ /** The person a current link signs in, while they may sign in here. */
304
+ async function linkPerson(scope: Scope, { home, link }: Found): Promise<Person | null> {
170
305
  if (link.expiresAt <= now()) return null;
171
- const p = await person(link.person);
172
- return active(p) ? p : null;
306
+ const p = await personAt(home, link.person);
307
+ return active(p) && inScope(p, scope) ? p : null;
173
308
  }
174
309
 
175
- async function readDefault(): Promise<Access> {
176
- const stored = await kv.hget(KEY.settings, 'access');
310
+ async function studioDefault(): Promise<Access> {
311
+ const stored = await kv.hget(keyOf('studio', 'settings'), 'access');
177
312
  return checkAccess(stored).ok ? (stored as Access) : DEFAULT_ACCESS;
178
313
  }
179
314
 
315
+ /** How long a new Client of the scope's client keeps access: the client's default, else the studio's, else 3m. */
316
+ async function readDefault(scope: Scope): Promise<Access> {
317
+ const own = isClientSlug(scope.client) ? (await clientAt(scope.client))?.access : null;
318
+ return own && checkAccess(own).ok ? own : studioDefault();
319
+ }
320
+
321
+ /** A new Studio person, with no link yet; their records live with the studio. */
322
+ async function newStudioPerson(input: unknown): Promise<Person> {
323
+ const { access, ...fields } = valid(checkPersonInput({ ...(input as object), kind: 'studio' }));
324
+ const p: Person = {
325
+ id: newId(),
326
+ ...fields,
327
+ client: null,
328
+ email: null,
329
+ accessEndsAt: accessEnd(access ?? 'open', deps.now()),
330
+ createdAt: now(),
331
+ revokedAt: null,
332
+ epoch: 0,
333
+ };
334
+ await savePerson(p);
335
+ return p;
336
+ }
337
+
338
+ /**
339
+ * Seconds until a slug or host archived lately (`held`) may be added
340
+ * again; 0 when it was not, or long enough ago.
341
+ */
342
+ async function heldFor(field: string): Promise<number> {
343
+ const at = Date.parse((await kv.hget(keyOf('studio', 'held'), field)) ?? '');
344
+ if (Number.isNaN(at)) return 0;
345
+ return Math.max(0, Math.ceil((at + REUSE_SECONDS * 1000 - deps.now().getTime()) / 1000));
346
+ }
347
+
348
+ /**
349
+ * Whether no client but `client` has the host: none serves it and no live
350
+ * client's record names it. Only then is its claim this client's to free.
351
+ */
352
+ async function hostIsFree(client: string, host: string): Promise<boolean> {
353
+ const served = await kv.hget(keyOf('studio', 'hosts'), host);
354
+ if (served !== null && served !== client) return false;
355
+ const records = Object.values(await kv.hgetall(keyOf('studio', 'clients'))).map(readClient);
356
+ return !records.some((o) => o && o.slug !== client && o.host === host && o.archivedAt === null);
357
+ }
358
+
359
+ /** Raises a claim counter; true when this call raised it to 1 and so holds it. */
360
+ const claim = async (field: string) => (await kv.hincrby(keyOf('studio', 'claims'), field, 1)) === 1;
361
+ const release = (field: string) => kv.hdel(keyOf('studio', 'claims'), field);
362
+
363
+ /**
364
+ * Removes everything stored under a client's keys, or one project's, by
365
+ * their prefix: whatever an index names and whatever none does, such as a
366
+ * write that passed the live check before an archive and landed after it.
367
+ * Never the local store's (sweepPrefix refuses it). Run only on a client
368
+ * that is not live: one being added, once its slug is claimed, or one
369
+ * archived; or on a project not yet added.
370
+ */
371
+ const sweep = (scope: Scope) => kv.delPrefix(sweepPrefix(scope));
372
+
373
+ /**
374
+ * The client an op on a client's record names (archive, forget): a slug a
375
+ * studio client can have. Never the local store's, which has no record and
376
+ * is never archived; it answers as a client that is not there.
377
+ */
378
+ function recordSlug(scope: Scope): string {
379
+ if (!isStudioClient(scope.client)) throw new ReviewError('not_found', NO_CLIENT);
380
+ return scope.client;
381
+ }
382
+
180
383
  /** Someone Studio can still give a link to. */
181
- async function needActive(id: string): Promise<Person> {
182
- const p = await needPerson(id);
384
+ async function needActive(scope: Scope, id: string): Promise<Person> {
385
+ const p = await needPerson(scope, id);
183
386
  if (p.revokedAt) throw new ReviewError('invalid', 'That person is revoked; add them again.');
184
387
  if (!active(p)) throw new ReviewError('invalid', 'Their access has ended; change their access first.');
185
388
  return p;
186
389
  }
187
390
 
188
- async function needPerson(id: string): Promise<Person> {
189
- const p = await person(id);
190
- if (!p) throw new ReviewError('not_found', 'No such person.');
391
+ async function needPerson(scope: Scope, id: string): Promise<Person> {
392
+ const p = await person(scope, id);
393
+ if (!p) throw new ReviewError('not_found', NO_PERSON);
191
394
  return p;
192
395
  }
193
396
 
@@ -199,56 +402,58 @@ export function createReview(kv: KV, overrides: Partial<Deps> = {}) {
199
402
  * numbers always had. Internal threads count in their own, which starts past any internal
200
403
  * thread numbered before the two counted apart, so no internal number is given twice.
201
404
  */
202
- const nextNumber = async (prototype: string, audience: Audience): Promise<number> => {
203
- if (audience === 'client') return kv.hincrby(KEY.counters, prototype, 1);
405
+ const nextNumber = async (scope: Scope, prototype: string, audience: Audience): Promise<number> => {
406
+ const counters = keyOf(scope, 'counters');
407
+ if (audience === 'client') return kv.hincrby(counters, prototype, 1);
204
408
  const field = `${prototype}:internal`;
205
- const n = await kv.hincrby(KEY.counters, field, 1);
409
+ const n = await kv.hincrby(counters, field, 1);
206
410
  if (n !== 1) return n;
207
411
  const before = Math.max(
208
412
  0,
209
- ...(await commentsOf(prototype)).filter((c) => c.audience === 'internal').map((c) => c.number),
413
+ ...(await commentsOf(scope, prototype)).filter((c) => c.audience === 'internal').map((c) => c.number),
210
414
  );
211
- return before ? kv.hincrby(KEY.counters, field, before) : n;
415
+ return before ? kv.hincrby(counters, field, before) : n;
212
416
  };
213
417
 
214
- const commentsOf = async (prototype: string) =>
215
- Object.values(await kv.hgetall(KEY.comments(prototype)))
418
+ const commentsOf = async (scope: Scope, prototype: string) =>
419
+ Object.values(await kv.hgetall(keyOf(scope, 'comments', prototype)))
216
420
  .map(readComment)
217
421
  .sort((a, b) => a.createdAt.localeCompare(b.createdAt) || a.id.localeCompare(b.id));
218
422
 
219
- const commentAt = async (prototype: string, id: string): Promise<Comment | null> => {
220
- const json = await kv.hget(KEY.comments(prototype), id);
423
+ const commentAt = async (scope: Scope, prototype: string, id: string): Promise<Comment | null> => {
424
+ const json = await kv.hget(keyOf(scope, 'comments', prototype), id);
221
425
  return json === null ? null : readComment(json);
222
426
  };
223
427
 
224
- const saveComment = (prototype: string, c: Comment) =>
225
- kv.hset(KEY.comments(prototype), c.id, JSON.stringify(c));
428
+ const saveComment = (scope: Scope, prototype: string, c: Comment) =>
429
+ kv.hset(keyOf(scope, 'comments', prototype), c.id, JSON.stringify(c));
226
430
 
227
- const isClientFacing = async (prototype: string) =>
228
- isPrototypeSlug(prototype) && (await kv.hget(KEY.audiences, prototype)) === 'client';
431
+ const isClientFacing = async (scope: Scope, prototype: string) =>
432
+ isPrototypeSlug(prototype) && (await kv.hget(keyOf(scope, 'audiences'), prototype)) === 'client';
229
433
 
230
434
  /**
231
435
  * Whether a view reaches a prototype's comments at all. A Client's view
232
436
  * reaches only a client-facing prototype: on any other, every op answers
233
437
  * as if it had no comments, so no answer confirms an internal slug.
234
438
  */
235
- const reachable = async (view: PersonKind, prototype: string) =>
236
- view === 'studio' || (await isClientFacing(prototype));
439
+ const reachable = async (scope: Scope, view: PersonKind, prototype: string) =>
440
+ view === 'studio' || (await isClientFacing(scope, prototype));
237
441
 
238
442
  /**
239
443
  * A comment and its thread's root, if `actor` may see both; else null. A
240
444
  * reply whose root is gone is not there either.
241
445
  */
242
446
  async function seen(
447
+ scope: Scope,
243
448
  actor: Person,
244
449
  prototype: string,
245
450
  id: string,
246
451
  ): Promise<{ comment: Comment; root: Comment } | null> {
247
- if (!(await reachable(viewOf(actor), prototype))) return null;
248
- const comment = await commentAt(prototype, id);
452
+ if (!(await reachable(scope, viewOf(actor), prototype))) return null;
453
+ const comment = await commentAt(scope, prototype, id);
249
454
  if (!comment) return null;
250
- const root = isRoot(comment) ? comment : await commentAt(prototype, comment.thread);
251
- return root && can(actor, 'read', root, comment) ? { comment, root } : null;
455
+ const root = isRoot(comment) ? comment : await commentAt(scope, prototype, comment.thread);
456
+ return root && can(actor, scope, 'read', root, comment) ? { comment, root } : null;
252
457
  }
253
458
 
254
459
  /**
@@ -257,53 +462,352 @@ export function createReview(kv: KV, overrides: Partial<Deps> = {}) {
257
462
  * an internal thread is there.
258
463
  */
259
464
  async function needThread(
465
+ scope: Scope,
260
466
  actor: Person | null,
261
467
  prototype: string,
262
468
  id: string,
263
- ): Promise<{ comment: Comment; root: Comment }> {
264
- allow(actor, 'read');
265
- const found = await seen(actor, prototype, id);
266
- if (!found) throw new ReviewError('not_found', 'No such comment.');
267
- return found;
469
+ ): Promise<{ actor: Person; comment: Comment; root: Comment }> {
470
+ const by = await allow(scope, actor, 'read', NO_COMMENT);
471
+ const found = await seen(scope, by, prototype, id);
472
+ if (!found) throw new ReviewError('not_found', NO_COMMENT);
473
+ return { actor: by, ...found };
268
474
  }
269
475
 
270
- async function needRoot(actor: Person | null, prototype: string, id: string): Promise<Comment> {
271
- const { comment } = await needThread(actor, prototype, id);
272
- if (!isRoot(comment)) throw new ReviewError('invalid', 'That is a reply; act on its thread.');
273
- return comment;
476
+ async function needRoot(
477
+ scope: Scope,
478
+ actor: Person | null,
479
+ prototype: string,
480
+ id: string,
481
+ ): Promise<{ actor: Person; root: Comment }> {
482
+ const found = await needThread(scope, actor, prototype, id);
483
+ if (!isRoot(found.comment)) throw new ReviewError('invalid', 'That is a reply; act on its thread.');
484
+ return { actor: found.actor, root: found.comment };
274
485
  }
275
486
 
487
+ const clientAt = async (slug: string): Promise<Client | null> => {
488
+ const c = readClient(await kv.hget(keyOf('studio', 'clients'), slug));
489
+ return c?.slug === slug ? c : null;
490
+ };
491
+ /** The scope's project, when its record is well formed and its own. */
492
+ const projectAt = async ({ client, project }: Scope): Promise<Project | null> => {
493
+ if (!isClientSlug(client) || !isProjectSlug(project)) return null;
494
+ const p = readProject(await kv.hget(keyOf({ client }, 'projects'), project));
495
+ return p?.client === client && p.slug === project ? p : null;
496
+ };
497
+ const saveProject = (p: Project) =>
498
+ kv.hset(keyOf({ client: p.client }, 'projects'), p.slug, JSON.stringify(p));
499
+
276
500
  return {
277
501
  person,
278
502
 
279
- /** The person a signed session names, if they still may sign in with it. */
280
- async sessionPerson(id: string, epoch: number): Promise<Person | null> {
281
- const p = await person(id);
282
- return active(p) && p.epoch === epoch ? p : null;
283
- },
284
-
285
- async listPeople(actor: Person | null): Promise<Person[]> {
286
- allow(actor, 'people');
287
- const [profiles, revoked, epochs] = await Promise.all([
288
- kv.hgetall(KEY.people),
289
- kv.hgetall(KEY.revoked),
290
- kv.hgetall(KEY.epochs),
291
- ]);
292
- // A profile that is not a well-formed person is skipped, never a throw.
293
- const all = Object.entries(profiles)
294
- .map(([id, json]) => compose(json, revoked[id], epochs[id]))
295
- .filter((p): p is Person => p !== null);
503
+ /**
504
+ * The client a host serves, asked by the gate and the studio's functions
505
+ * with no actor: null for a host no client has, an archived client, or
506
+ * records that disagree, so an unknown host is never a scope.
507
+ */
508
+ async clientOfHost(host: string): Promise<Client | null> {
509
+ const name = hostName(host);
510
+ if (!name) return null;
511
+ const slug = await kv.hget(keyOf('studio', 'hosts'), name);
512
+ const c = isClientSlug(slug) ? await clientAt(slug) : null;
513
+ return c && c.host === name && c.archivedAt === null ? c : null;
514
+ },
515
+
516
+ /** One project of the scope's client, asked with no actor: null when the client has none by that name. */
517
+ projectOf: projectAt,
518
+
519
+ /** Every project of the scope's client that has a build to open, by name. */
520
+ async listProjects(scope: Scope, actor: Person | null): Promise<Project[]> {
521
+ await allow(scope, actor, 'read', NO_PROJECT);
522
+ const stored = Object.values(await kv.hgetall(keyOf({ client: scope.client }, 'projects')));
523
+ return stored
524
+ .map(readProject)
525
+ .filter((p): p is Project => p?.client === scope.client && p.build !== null)
526
+ .sort((a, b) => a.name.localeCompare(b.name) || a.slug.localeCompare(b.slug));
527
+ },
528
+
529
+ /**
530
+ * A new client and its host. Studio only. The slug and the host are each
531
+ * claimed (`claims` in store.ts), so of two adds at once only one gets
532
+ * either, and a slug or a host already taken is refused. The record goes
533
+ * in between the two claims, so a host's claim is only ever held while a
534
+ * record names the host: an add that stops part way leaves a record that
535
+ * `archiveClient` and `forgetClient` find, and so free. A slug or host
536
+ * archived less than REUSE_SECONDS ago is refused, with how long to wait.
537
+ * Once the slug is claimed, everything stored under the slug's prefix is
538
+ * removed before the record goes in, so the client starts clean whatever
539
+ * was written under the slug before, and whether or not a record named it.
540
+ */
541
+ async addClient(actor: Person | null, input: unknown): Promise<Client> {
542
+ const fields = valid(checkClientInput(input));
543
+ allowRecord({ client: fields.slug }, actor);
544
+ const slug = `client:${fields.slug}`;
545
+ const host = `host:${fields.host}`;
546
+ const slugHeld = await claim(slug);
547
+ if (!slugHeld || (await clientAt(fields.slug))) {
548
+ if (slugHeld) await release(slug);
549
+ throw new ReviewError('invalid', 'That client exists, or an add or archive of it stopped part way.', [
550
+ 'slug: archive the client to free it',
551
+ ]);
552
+ }
553
+ const slugWait = await heldFor(slug);
554
+ if (slugWait) {
555
+ await release(slug);
556
+ throw tooSoon(slugWait);
557
+ }
558
+ // A new client starts clean: whatever an earlier client of the slug left, or a write that landed
559
+ // after its archive swept, goes before the record makes the client live.
560
+ await sweep({ client: fields.slug });
561
+ const c: Client = { ...fields, access: null, createdAt: now(), archivedAt: null, provenAt: null };
562
+ const clients = keyOf('studio', 'clients');
563
+ await kv.hset(clients, c.slug, JSON.stringify(c));
564
+ const hostHeld = await claim(host);
565
+ const hostWait = hostHeld ? await heldFor(host) : 0;
566
+ if (!hostHeld || hostWait || (await kv.hget(keyOf('studio', 'hosts'), fields.host))) {
567
+ if (hostHeld) await release(host);
568
+ await kv.hdel(clients, c.slug);
569
+ await release(slug);
570
+ if (hostWait) throw tooSoon(hostWait);
571
+ throw new ReviewError('invalid', 'That host already serves a client.', ['host: another host']);
572
+ }
573
+ await kv.hset(keyOf('studio', 'hosts'), c.host, c.slug);
574
+ await kv.hdel(keyOf('studio', 'held'), slug);
575
+ await kv.hdel(keyOf('studio', 'held'), host);
576
+ return c;
577
+ },
578
+
579
+ /**
580
+ * How many seconds until this slug and host may be added again: 0 when
581
+ * neither was archived in the last REUSE_SECONDS. `client add` asks
582
+ * before it changes any DNS or domain. Studio only.
583
+ */
584
+ async clientWait(actor: Person | null, input: { slug: string; host: string }): Promise<number> {
585
+ allowStudio(actor);
586
+ return Math.max(await heldFor(`client:${input.slug}`), await heldFor(`host:${input.host}`));
587
+ },
588
+
589
+ /**
590
+ * A new host proof for the scope's client, in place of any before it:
591
+ * `ask` goes to the client's host and `answer` must come back, which only
592
+ * the gate with this store can give (PROOF_PATH). The store keeps the ask
593
+ * as its hash, so a leaked store answers nothing. Studio only.
594
+ */
595
+ async startProof(scope: Scope, actor: Person | null): Promise<{ ask: string; answer: string }> {
596
+ await allow(scope, actor, 'setup', NO_CLIENT);
597
+ const ask = base64url(deps.random(32));
598
+ const answer = base64url(deps.random(32));
599
+ const key = keyOf({ client: scope.client }, 'proof');
600
+ await kv.del(key);
601
+ await kv.hset(key, await linkKey(ask), answer);
602
+ return { ask, answer };
603
+ },
604
+
605
+ /**
606
+ * Ends the scope's client's host proof, once its host has answered it,
607
+ * and marks the client proven: it has finished being added (isAdded).
608
+ * The mark goes on first, so a run stopped between the two leaves a
609
+ * proven client with a stale proof, which answers nothing anyone holds.
610
+ * Studio only.
611
+ */
612
+ async endProof(scope: Scope, actor: Person | null): Promise<Client> {
613
+ await allow(scope, actor, 'setup', NO_CLIENT);
614
+ const c = await clientAt(scope.client);
615
+ if (!c) throw new ReviewError('not_found', NO_CLIENT);
616
+ const proven = c.provenAt ? c : { ...c, provenAt: now() };
617
+ if (proven !== c) await kv.hset(keyOf('studio', 'clients'), c.slug, JSON.stringify(proven));
618
+ await kv.del(keyOf({ client: scope.client }, 'proof'));
619
+ return proven;
620
+ },
621
+
622
+ /** The answer to a host proof's ask in the scope's client, asked by the gate with no actor: null for any other ask. */
623
+ async proofAnswer(scope: Scope, ask: string): Promise<string | null> {
624
+ if (!isClientSlug(scope.client) || typeof ask !== 'string' || !LINK_TOKEN.test(ask)) return null;
625
+ return kv.hget(keyOf({ client: scope.client }, 'proof'), await linkKey(ask));
626
+ },
627
+
628
+ /** The scope's client record. Studio only. */
629
+ async clientRecord(scope: Scope, actor: Person | null): Promise<Client> {
630
+ allowRecord(scope, actor);
631
+ const c = await clientAt(scope.client);
632
+ if (!c) throw new ReviewError('not_found', NO_CLIENT);
633
+ return c;
634
+ },
635
+
636
+ /** Sets how long the scope's client's new people keep access by default; null leaves it to the studio's. Studio only. */
637
+ async setClientAccess(scope: Scope, actor: Person | null, access: unknown): Promise<Client> {
638
+ await allow(scope, actor, 'setup', NO_CLIENT);
639
+ const length = access === null ? null : valid(checkAccess(access));
640
+ const c = await clientAt(scope.client);
641
+ if (!c) throw new ReviewError('not_found', NO_CLIENT);
642
+ const next = { ...c, access: length };
643
+ await kv.hset(keyOf('studio', 'clients'), c.slug, JSON.stringify(next));
644
+ return next;
645
+ },
646
+
647
+ /**
648
+ * Archives the scope's client, the first of two steps: its record is
649
+ * marked archived, so its host stops serving at once (clientOfHost), then
650
+ * its host entry, then everything under its prefix (people, links,
651
+ * projects, each project's records, and any key no record names). The record stays, naming the host, until
652
+ * forgetClient, so `client archive` stopped part way and run again still
653
+ * knows the host to take off the site. Answers the record, and whether
654
+ * the host is the client's own to take off: not when another client
655
+ * serves it or a live client's record names it. null when there is no
656
+ * record. Safe to run again. The client's files are the caller's to
657
+ * remove (the files port). Studio only.
658
+ */
659
+ async archiveClient(scope: Scope, actor: Person | null): Promise<Archived | null> {
660
+ allowRecord(scope, actor);
661
+ const client = recordSlug(scope);
662
+ const found = await clientAt(client);
663
+ const c = found && found.archivedAt === null ? { ...found, archivedAt: now() } : found;
664
+ if (c && c !== found) await kv.hset(keyOf('studio', 'clients'), client, JSON.stringify(c));
665
+ const hosts = keyOf('studio', 'hosts');
666
+ if (c && (await kv.hget(hosts, c.host)) === client) await kv.hdel(hosts, c.host);
667
+ await sweep({ client });
668
+ return c ? { client: c, ownHost: await hostIsFree(client, c.host) } : null;
669
+ },
670
+
671
+ /**
672
+ * The second step, once the caller has removed the client's files, DNS
673
+ * record and domain: its keys once more (anything written meanwhile),
674
+ * then the time on its slug and host (`held`), then the host's claim
675
+ * unless another client holds it, then its record, then the slug's claim.
676
+ * With no record, it frees the slug alone: an add that stopped before its
677
+ * record held no host. Refused while the client is not archived. Studio only.
678
+ */
679
+ async forgetClient(scope: Scope, actor: Person | null): Promise<void> {
680
+ allowRecord(scope, actor);
681
+ const client = recordSlug(scope);
682
+ const c = await clientAt(client);
683
+ if (c && c.archivedAt === null) throw new ReviewError('invalid', 'Archive the client first.');
684
+ if (c) {
685
+ await sweep({ client });
686
+ const at = now();
687
+ await kv.hset(keyOf('studio', 'held'), `client:${client}`, at);
688
+ await kv.hset(keyOf('studio', 'held'), `host:${c.host}`, at);
689
+ if (await hostIsFree(client, c.host)) await release(`host:${c.host}`);
690
+ await kv.hdel(keyOf('studio', 'clients'), client);
691
+ }
692
+ await release(`client:${client}`);
693
+ },
694
+
695
+ /** A new project of the scope's client, with no build yet. Studio only. */
696
+ async addProject(scope: Scope, actor: Person | null, input: unknown): Promise<Project> {
697
+ await allow(scope, actor, 'setup', NO_CLIENT);
698
+ const fields = valid(checkProjectInput(input));
699
+ if (await projectAt({ client: scope.client, project: fields.slug }))
700
+ throw new ReviewError('invalid', 'That project exists.');
701
+ const p: Project = { ...fields, client: scope.client, build: null, createdAt: now() };
702
+ // A new project starts clean too: whatever a write left under its slug, outside any record, goes first.
703
+ await sweep({ client: p.client, project: p.slug });
704
+ await saveProject(p);
705
+ return p;
706
+ },
707
+
708
+ /**
709
+ * Starts a build of the scope's project, before any of its files go up:
710
+ * it takes the next number in the project's own order of builds, from
711
+ * the store, never a clock. Only a started build can go live, and setBuild
712
+ * refuses one while a build started after it is live. A build started for
713
+ * a project that was archived and made again was started for none of
714
+ * the new one's. Studio only.
715
+ */
716
+ async startBuild(scope: Scope, actor: Person | null, build: unknown): Promise<void> {
717
+ await allow(scope, actor, 'setup', NO_PROJECT);
718
+ if (!isBuildId(build))
719
+ throw new ReviewError('invalid', 'Some fields are not valid.', ['build: a build id']);
720
+ if (!(await projectAt(scope))) throw new ReviewError('not_found', NO_PROJECT);
721
+ const key = keyOf(scope, 'builds');
722
+ const n = await kv.hincrby(key, 'next', 1);
723
+ if (!(await kv.hsetnx(key, build, JSON.stringify({ n, live: false } satisfies BuildEntry))))
724
+ throw new ReviewError('invalid', 'That build was started already.', ['build: a new build id']);
725
+ },
726
+
727
+ /**
728
+ * Points the scope's project at a build. The caller has checked that
729
+ * every file of it is in the file store. Refused for a build never
730
+ * started for this project, or one started before the build the pointer
731
+ * names when this call reads it: a share overtaken by a newer one does
732
+ * not take the project back, which is what lets pruning remove the
733
+ * builds before the live one. The check reads and then writes, with no
734
+ * lock, so of two calls for one project within the same few store calls
735
+ * both can pass and the older build's write can land last; and a build
736
+ * pruned meanwhile, not yet marked live, is still pointed at, with no
737
+ * files. The next share's call puts either right. The build is marked
738
+ * live before the pointer moves. Studio only.
739
+ */
740
+ async setBuild(scope: Scope, actor: Person | null, build: unknown): Promise<Project> {
741
+ await allow(scope, actor, 'setup', NO_PROJECT);
742
+ if (!isBuildId(build))
743
+ throw new ReviewError('invalid', 'Some fields are not valid.', ['build: a build id']);
744
+ const p = await projectAt(scope);
745
+ if (!p) throw new ReviewError('not_found', NO_PROJECT);
746
+ const key = keyOf(scope, 'builds');
747
+ const entry = readBuildEntry(await kv.hget(key, build));
748
+ if (!entry)
749
+ throw new ReviewError('invalid', 'That build was never started for this project.', [
750
+ 'build: one started for this project',
751
+ ]);
752
+ const live = p.build && p.build !== build ? readBuildEntry(await kv.hget(key, p.build)) : null;
753
+ if (live && live.n > entry.n)
754
+ throw new ReviewError('invalid', 'A build started after this one is live.', [
755
+ 'build: started after the live one',
756
+ ]);
757
+ await kv.hset(key, build, JSON.stringify({ ...entry, live: true } satisfies BuildEntry));
758
+ const next = { ...p, build };
759
+ await saveProject(next);
760
+ return next;
761
+ },
762
+
763
+ /** The scope's project's live build and every build started for it, in the order they were started. Studio only. */
764
+ async buildsOf(scope: Scope, actor: Person | null): Promise<{ live: string | null; builds: Build[] }> {
765
+ await allow(scope, actor, 'setup', NO_PROJECT);
766
+ const p = await projectAt(scope);
767
+ if (!p) throw new ReviewError('not_found', NO_PROJECT);
768
+ const builds = Object.entries(await kv.hgetall(keyOf(scope, 'builds')))
769
+ .map(([build, json]) => ({ build, entry: readBuildEntry(json) }))
770
+ .filter((b): b is { build: string; entry: BuildEntry } => isBuildId(b.build) && b.entry !== null)
771
+ .map(({ build, entry }) => ({ build, ...entry }))
772
+ .sort((a, b) => a.n - b.n);
773
+ return { live: p.build, builds };
774
+ },
775
+
776
+ /** Forgets builds of the scope's project, once their files are gone; never the live one. Studio only. */
777
+ async forgetBuilds(scope: Scope, actor: Person | null, builds: string[]): Promise<void> {
778
+ await allow(scope, actor, 'setup', NO_PROJECT);
779
+ const live = (await projectAt(scope))?.build;
780
+ for (const build of builds)
781
+ if (isBuildId(build) && build !== live) await kv.hdel(keyOf(scope, 'builds'), build);
782
+ },
783
+
784
+ /** The person a signed session names, if they still may sign in with it, here. */
785
+ async sessionPerson(scope: Scope, id: string, epoch: number): Promise<Person | null> {
786
+ const p = await person(scope, id);
787
+ return active(p) && p.epoch === epoch && inScope(p, scope) ? p : null;
788
+ },
789
+
790
+ /** The scope's Clients and every Studio person. */
791
+ async listPeople(scope: Scope, actor: Person | null): Promise<Person[]> {
792
+ await allow(scope, actor, 'people', NO_PERSON);
793
+ const all = [...(await peopleAt('studio')), ...(await peopleAt(scope))];
296
794
  return all.sort((a, b) => a.team.localeCompare(b.team) || a.name.localeCompare(b.name));
297
795
  },
298
796
 
299
- /** A new person and their first link. Without an access length, a Client gets the project default and Studio is open-ended. */
300
- async addPerson(actor: Person | null, input: unknown): Promise<{ person: Person; token: string }> {
301
- allow(actor, 'people');
797
+ /**
798
+ * A new person and their first link: a Client of the scope's client, or a
799
+ * Studio person. Without an access length, a Client gets the default and
800
+ * Studio is open-ended.
801
+ */
802
+ async addPerson(scope: Scope, actor: Person | null, input: unknown): Promise<Issued> {
803
+ await allow(scope, actor, 'people', NO_PERSON);
302
804
  const { access, ...fields } = valid(checkPersonInput(input));
303
- const length = access ?? (fields.kind === 'studio' ? 'open' : await readDefault());
805
+ // S13: the person's own length, else (a Client) the client's default, then the studio's, then 3m.
806
+ const length = access ?? (fields.kind === 'studio' ? 'open' : await readDefault(scope));
304
807
  const p: Person = {
305
808
  id: newId(),
306
809
  ...fields,
810
+ client: fields.kind === 'studio' ? null : scope.client,
307
811
  email: null,
308
812
  accessEndsAt: accessEnd(length, deps.now()),
309
813
  createdAt: now(),
@@ -315,80 +819,121 @@ export function createReview(kv: KV, overrides: Partial<Deps> = {}) {
315
819
  },
316
820
 
317
821
  /** Another one-time link, for another device. Their sessions and other unused links stay. */
318
- async newLink(actor: Person | null, id: string): Promise<{ person: Person; token: string }> {
319
- allow(actor, 'people');
320
- const p = await needActive(id);
822
+ async newLink(scope: Scope, actor: Person | null, id: string): Promise<Issued> {
823
+ await allow(scope, actor, 'people', NO_PERSON);
824
+ const p = await needActive(scope, id);
321
825
  return { person: p, token: await issueLink(p) };
322
826
  },
323
827
 
324
828
  /** Ends every session they hold and every unused link, and gives one new link. */
325
- async signOutEverywhere(actor: Person | null, id: string): Promise<{ person: Person; token: string }> {
326
- allow(actor, 'people');
327
- const p = await needActive(id);
829
+ async signOutEverywhere(scope: Scope, actor: Person | null, id: string): Promise<Issued> {
830
+ await allow(scope, actor, 'people', NO_PERSON);
831
+ const p = await needActive(scope, id);
328
832
  // The epoch first: a failure after it has still ended every session. Atomic, so two at once raise it twice.
329
- const next = { ...p, epoch: await kv.hincrby(KEY.epochs, id, 1) };
330
- await dropLinks(id);
833
+ const next = { ...p, epoch: await kv.hincrby(keyOf(homeOf(p), 'epochs'), id, 1) };
834
+ await dropLinks(p);
331
835
  return { person: next, token: await issueLink(next) };
332
836
  },
333
837
 
334
- async revoke(actor: Person | null, id: string): Promise<Person> {
335
- allow(actor, 'people');
336
- if (actor.id === id) throw new ReviewError('invalid', 'You cannot revoke yourself.');
337
- const p = await needPerson(id);
838
+ async revoke(scope: Scope, actor: Person | null, id: string): Promise<Person> {
839
+ const by = await allow(scope, actor, 'people', NO_PERSON);
840
+ if (by.id === id) throw new ReviewError('invalid', 'You cannot revoke yourself.');
841
+ const p = await needPerson(scope, id);
338
842
  const revokedAt = p.revokedAt ?? now();
339
843
  // Revocation and the epoch before the links go, so a failure part-way never leaves an active
340
844
  // person; a leftover link opens nothing for someone revoked.
341
- if (!p.revokedAt) await kv.hset(KEY.revoked, id, revokedAt);
342
- const epoch = await kv.hincrby(KEY.epochs, id, 1);
343
- await dropLinks(id);
845
+ if (!p.revokedAt) await kv.hset(keyOf(homeOf(p), 'revoked'), id, revokedAt);
846
+ const epoch = await kv.hincrby(keyOf(homeOf(p), 'epochs'), id, 1);
847
+ await dropLinks(p);
344
848
  return { ...p, revokedAt, epoch };
345
849
  },
346
850
 
347
851
  /** Sets one person's access length, counted from now. Their sessions follow at the gate's next check, within five minutes. */
348
- async setAccess(actor: Person | null, id: string, access: unknown): Promise<Person> {
349
- allow(actor, 'people');
852
+ async setAccess(scope: Scope, actor: Person | null, id: string, access: unknown): Promise<Person> {
853
+ await allow(scope, actor, 'people', NO_PERSON);
350
854
  const length = valid(checkAccess(access));
351
- const p = await needPerson(id);
855
+ const p = await needPerson(scope, id);
352
856
  if (p.revokedAt) throw new ReviewError('invalid', 'That person is revoked; add them again.');
353
857
  await savePerson({ ...p, accessEndsAt: accessEnd(length, deps.now()) });
354
858
  // Read back, so the answer carries a revocation or epoch that landed meanwhile.
355
- return (await person(id)) as Person;
859
+ return (await personAt(homeOf(p), id)) as Person;
860
+ },
861
+
862
+ /** How long a new Client of the scope's client keeps access unless Studio says otherwise: the client's default, else the studio's. */
863
+ async defaultAccess(scope: Scope, actor: Person | null): Promise<Access> {
864
+ await allow(scope, actor, 'people', NO_PERSON);
865
+ return readDefault(scope);
866
+ },
867
+
868
+ /**
869
+ * Sets what defaultAccess reads for the scope: the client's own default
870
+ * on a studio site's client host, the studio's in the local store, whose
871
+ * client has no record. Never the studio's for a client whose record is
872
+ * gone. Studio only.
873
+ */
874
+ async setDefaultAccess(scope: Scope, actor: Person | null, access: unknown): Promise<Access> {
875
+ await allow(scope, actor, 'people', NO_PERSON);
876
+ const length = valid(checkAccess(access));
877
+ if (scope.client === LOCAL_CLIENT) {
878
+ await kv.hset(keyOf('studio', 'settings'), 'access', length);
879
+ return length;
880
+ }
881
+ const c = await clientAt(scope.client);
882
+ if (!c) throw new ReviewError('not_found', NO_PERSON);
883
+ await kv.hset(keyOf('studio', 'clients'), c.slug, JSON.stringify({ ...c, access: length }));
884
+ return length;
885
+ },
886
+
887
+ /** A new Studio person, who works in every client. No link: each comes from newStudioLink, for one host. Studio only. */
888
+ async addStudioPerson(actor: Person | null, input: unknown): Promise<Person> {
889
+ allowStudio(actor);
890
+ return newStudioPerson(input);
891
+ },
892
+
893
+ /** Another one-time link for a Studio person: it signs in one device, on whichever client host it is opened. Studio only. */
894
+ async newStudioLink(actor: Person | null, id: string): Promise<Issued> {
895
+ allowStudio(actor);
896
+ const p = await personAt('studio', id);
897
+ if (!p) throw new ReviewError('not_found', NO_PERSON);
898
+ if (!active(p)) throw new ReviewError('invalid', 'That person is revoked or their access has ended.');
899
+ return { person: p, token: await issueLink(p) };
356
900
  },
357
901
 
358
- /** How long a new Client keeps access unless Studio says otherwise. */
359
- async defaultAccess(actor: Person | null): Promise<Access> {
360
- allow(actor, 'people');
361
- return readDefault();
902
+ /** The studio's default access length, what a client without its own gives. Studio only. */
903
+ async studioAccess(actor: Person | null): Promise<Access> {
904
+ allowStudio(actor);
905
+ return studioDefault();
362
906
  },
363
907
 
364
- async setDefaultAccess(actor: Person | null, access: unknown): Promise<Access> {
365
- allow(actor, 'people');
908
+ async setStudioAccess(actor: Person | null, access: unknown): Promise<Access> {
909
+ allowStudio(actor);
366
910
  const length = valid(checkAccess(access));
367
- await kv.hset(KEY.settings, 'access', length);
911
+ await kv.hset(keyOf('studio', 'settings'), 'access', length);
368
912
  return length;
369
913
  },
370
914
 
371
- /** Who a link signs in, without using it: mail and chat previews open links too. */
372
- async peekLink(token: string): Promise<Person | null> {
373
- const found = await findLink(token);
374
- return found ? linkPerson(found.link) : null;
915
+ /** Who a link signs in here, without using it: mail and chat previews open links too. */
916
+ async peekLink(scope: Scope, token: string): Promise<Person | null> {
917
+ const found = await findLink(scope, token);
918
+ return found ? linkPerson(scope, found) : null;
375
919
  },
376
920
 
377
921
  /**
378
922
  * Uses a link up and returns who it signs in. The delete is the claim: of
379
923
  * two requests with one token, only the one whose delete removed the link
380
924
  * gets a person, so a link signs in one device at most. Who it signs in is
381
- * read and checked first, so the delete is the last store call.
925
+ * read and checked first, so the delete is the last store call. Only a
926
+ * link of the scope's client, or a Studio person's, is found at all.
382
927
  */
383
- async useLink(token: string): Promise<Person | null> {
384
- const found = await findLink(token);
928
+ async useLink(scope: Scope, token: string): Promise<Person | null> {
929
+ const found = await findLink(scope, token);
385
930
  // Every read and check comes before the delete, so a store failure before it leaves the link usable.
386
- const p = found && (await linkPerson(found.link));
931
+ const p = found && (await linkPerson(scope, found));
387
932
  if (!found || !p) return null;
388
- if ((await kv.hdel(KEY.links, found.key)) !== 1) return null;
933
+ if ((await kv.hdel(keyOf(found.home, 'links'), found.hash)) !== 1) return null;
389
934
  // A revoke or sign out everywhere can land between the check and the claim, before its
390
935
  // dropLinks reaches this link: read again, and sign in only someone still active on the same epoch.
391
- const after = await person(p.id);
936
+ const after = await personAt(found.home, p.id);
392
937
  return active(after) && after.epoch === p.epoch ? after : null;
393
938
  },
394
939
 
@@ -396,20 +941,26 @@ export function createReview(kv: KV, overrides: Partial<Deps> = {}) {
396
941
  * A prototype's comments as the actor's view sees them. `viewAs: 'client'`
397
942
  * is Studio's Client view; it never widens a Client's.
398
943
  */
399
- async listComments(actor: Person | null, prototype: string, viewAs?: unknown): Promise<Comment[]> {
400
- allow(actor, 'read');
401
- const view = viewOf(actor, valid(checkViewAs(viewAs)));
402
- if (!(await reachable(view, prototype))) return [];
403
- return visibleTo(view, await commentsOf(prototype));
944
+ async listComments(
945
+ scope: Scope,
946
+ actor: Person | null,
947
+ prototype: string,
948
+ viewAs?: unknown,
949
+ ): Promise<Comment[]> {
950
+ const by = await allow(scope, actor, 'read', NO_COMMENT);
951
+ const view = viewOf(by, valid(checkViewAs(viewAs)));
952
+ if (!(await reachable(scope, view, prototype))) return [];
953
+ return visibleTo(view, await commentsOf(scope, prototype));
404
954
  },
405
955
 
406
- /** Every comment on every prototype the actor may see, for the CLI (which acts as Studio). */
407
- async allComments(actor: Person | null): Promise<Comment[]> {
408
- allow(actor, 'read');
409
- const view = viewOf(actor);
956
+ /** Every comment on every prototype of the scope's project the actor may see, for the CLI (which acts as Studio). */
957
+ async allComments(scope: Scope, actor: Person | null): Promise<Comment[]> {
958
+ const by = await allow(scope, actor, 'read', NO_COMMENT);
959
+ const view = viewOf(by);
410
960
  const prototypes = [];
411
- for (const p of await kv.smembers(KEY.prototypes)) if (await reachable(view, p)) prototypes.push(p);
412
- return visibleTo(view, (await Promise.all(prototypes.map(commentsOf))).flat());
961
+ for (const p of await kv.smembers(keyOf(scope, 'prototypes')))
962
+ if (await reachable(scope, view, p)) prototypes.push(p);
963
+ return visibleTo(view, (await Promise.all(prototypes.map((p) => commentsOf(scope, p)))).flat());
413
964
  },
414
965
 
415
966
  /**
@@ -418,18 +969,19 @@ export function createReview(kv: KV, overrides: Partial<Deps> = {}) {
418
969
  * next of its audience on the prototype, never one used before.
419
970
  */
420
971
  async add(
972
+ scope: Scope,
421
973
  actor: Person | null,
422
974
  input: { body?: unknown; anchor?: unknown; states?: unknown; audience?: unknown },
423
975
  ): Promise<Comment> {
424
- allow(actor, 'comment');
976
+ const by = await allow(scope, actor, 'comment', NO_COMMENT);
425
977
  const [body, anchor, asked] = validAll<[string, Anchor, Audience | null]>(
426
978
  checkBody(input.body),
427
979
  checkAnchor(input.anchor),
428
980
  checkAudience(input.audience),
429
981
  );
430
982
  // A Client's thread on a prototype that is not client-facing: the answer an unknown id gets.
431
- if (!(await reachable(viewOf(actor), anchor.prototype)))
432
- throw new ReviewError('not_found', 'No such comment.');
983
+ if (!(await reachable(scope, viewOf(by), anchor.prototype)))
984
+ throw new ReviewError('not_found', NO_COMMENT);
433
985
  const id = newId();
434
986
  const triage = deps.triage
435
987
  ? await deps
@@ -440,7 +992,7 @@ export function createReview(kv: KV, overrides: Partial<Deps> = {}) {
440
992
  const c: Comment = {
441
993
  id,
442
994
  thread: id,
443
- author: authorOf(actor),
995
+ author: authorOf(by),
444
996
  body,
445
997
  createdAt: now(),
446
998
  editedAt: null,
@@ -448,26 +1000,27 @@ export function createReview(kv: KV, overrides: Partial<Deps> = {}) {
448
1000
  status: 'open',
449
1001
  resolvedBy: null,
450
1002
  triage,
451
- audience: audienceFor(actor, asked),
1003
+ audience: audienceFor(by, asked),
452
1004
  number: 0,
453
1005
  };
454
- c.number = await nextNumber(anchor.prototype, c.audience);
455
- await kv.sadd(KEY.prototypes, anchor.prototype);
456
- await saveComment(anchor.prototype, c);
1006
+ c.number = await nextNumber(scope, anchor.prototype, c.audience);
1007
+ await kv.sadd(keyOf(scope, 'prototypes'), anchor.prototype);
1008
+ await saveComment(scope, anchor.prototype, c);
457
1009
  return c;
458
1010
  },
459
1011
 
460
1012
  async reply(
1013
+ scope: Scope,
461
1014
  actor: Person | null,
462
1015
  input: { prototype: string; thread: string; body?: unknown },
463
1016
  ): Promise<Comment> {
464
- const root = await needRoot(actor, input.prototype, input.thread);
465
- allow(actor, 'comment', root);
1017
+ const { actor: by, root } = await needRoot(scope, actor, input.prototype, input.thread);
1018
+ permit(scope, by, 'comment', root);
466
1019
  const id = newId();
467
1020
  const c: Comment = {
468
1021
  id,
469
1022
  thread: root.id,
470
- author: authorOf(actor),
1023
+ author: authorOf(by),
471
1024
  body: valid(checkBody(input.body)),
472
1025
  createdAt: now(),
473
1026
  editedAt: null,
@@ -479,55 +1032,64 @@ export function createReview(kv: KV, overrides: Partial<Deps> = {}) {
479
1032
  audience: root.audience,
480
1033
  number: root.number,
481
1034
  };
482
- await saveComment(input.prototype, c);
1035
+ await saveComment(scope, input.prototype, c);
483
1036
  return c;
484
1037
  },
485
1038
 
486
1039
  async edit(
1040
+ scope: Scope,
487
1041
  actor: Person | null,
488
1042
  input: { prototype: string; id: string; body?: unknown },
489
1043
  ): Promise<Comment> {
490
- const { comment: c, root } = await needThread(actor, input.prototype, input.id);
491
- allow(actor, 'edit', root, c);
1044
+ const { actor: by, comment: c, root } = await needThread(scope, actor, input.prototype, input.id);
1045
+ permit(scope, by, 'edit', root, c);
492
1046
  const next = { ...c, body: valid(checkBody(input.body)), editedAt: now() };
493
- await saveComment(input.prototype, next);
1047
+ await saveComment(scope, input.prototype, next);
494
1048
  return next;
495
1049
  },
496
1050
 
497
1051
  /** Deletes a comment; deleting a thread's root deletes its replies with it. */
498
- async remove(actor: Person | null, input: { prototype: string; id: string }): Promise<string[]> {
499
- const { comment: c, root } = await needThread(actor, input.prototype, input.id);
500
- allow(actor, 'delete', root, c);
501
- const gone = isRoot(c) ? (await commentsOf(input.prototype)).filter((x) => x.thread === c.id) : [c];
502
- for (const x of gone) await kv.hdel(KEY.comments(input.prototype), x.id);
1052
+ async remove(
1053
+ scope: Scope,
1054
+ actor: Person | null,
1055
+ input: { prototype: string; id: string },
1056
+ ): Promise<string[]> {
1057
+ const { actor: by, comment: c, root } = await needThread(scope, actor, input.prototype, input.id);
1058
+ permit(scope, by, 'delete', root, c);
1059
+ const gone = isRoot(c)
1060
+ ? (await commentsOf(scope, input.prototype)).filter((x) => x.thread === c.id)
1061
+ : [c];
1062
+ for (const x of gone) await kv.hdel(keyOf(scope, 'comments', input.prototype), x.id);
503
1063
  // The answer names only what the actor may see, judged with the thread's root beside it.
504
- const shown = new Set(visibleTo(viewOf(actor), [root, ...gone]).map((x) => x.id));
1064
+ const shown = new Set(visibleTo(viewOf(by), [root, ...gone]).map((x) => x.id));
505
1065
  return gone.filter((x) => shown.has(x.id)).map((x) => x.id);
506
1066
  },
507
1067
 
508
1068
  async resolve(
1069
+ scope: Scope,
509
1070
  actor: Person | null,
510
1071
  input: { prototype: string; id: string; resolved: boolean },
511
1072
  ): Promise<Comment> {
512
- const c = await needRoot(actor, input.prototype, input.id);
513
- allow(actor, 'resolve', c);
1073
+ const { actor: by, root: c } = await needRoot(scope, actor, input.prototype, input.id);
1074
+ permit(scope, by, 'resolve', c);
514
1075
  const next: Comment = input.resolved
515
- ? { ...c, status: 'resolved', resolvedBy: authorOf(actor) }
1076
+ ? { ...c, status: 'resolved', resolvedBy: authorOf(by) }
516
1077
  : { ...c, status: 'open', resolvedBy: null };
517
- await saveComment(input.prototype, next);
1078
+ await saveComment(scope, input.prototype, next);
518
1079
  return next;
519
1080
  },
520
1081
 
521
1082
  async retriage(
1083
+ scope: Scope,
522
1084
  actor: Person | null,
523
1085
  input: { prototype: string; id: string; triage?: unknown; states?: unknown },
524
1086
  ): Promise<Comment> {
525
- allow(actor, 'triage');
526
- const c = await needRoot(actor, input.prototype, input.id);
1087
+ await allow(scope, actor, 'triage', NO_COMMENT);
1088
+ const { root: c } = await needRoot(scope, actor, input.prototype, input.id);
527
1089
  const states = checkStates(input.states);
528
1090
  const { kind, state } = valid(checkTriage(input.triage, states.length ? states : null));
529
1091
  const next: Comment = { ...c, triage: { kind, state, by: 'person', confidence: null } };
530
- await saveComment(input.prototype, next);
1092
+ await saveComment(scope, input.prototype, next);
531
1093
  return next;
532
1094
  },
533
1095
 
@@ -536,16 +1098,21 @@ export function createReview(kv: KV, overrides: Partial<Deps> = {}) {
536
1098
  * stored, so internal deletes the field and a prototype nobody marked is
537
1099
  * internal. Studio only.
538
1100
  */
539
- async setAudience(actor: Person | null, prototype: unknown, audience: unknown): Promise<Audience> {
540
- allow(actor, 'audience');
1101
+ async setAudience(
1102
+ scope: Scope,
1103
+ actor: Person | null,
1104
+ prototype: unknown,
1105
+ audience: unknown,
1106
+ ): Promise<Audience> {
1107
+ await allow(scope, actor, 'audience', NO_PROTOTYPE);
541
1108
  const [slug, value] = validAll<[string, Audience]>(
542
1109
  isPrototypeSlug(prototype)
543
1110
  ? { ok: true, value: prototype }
544
1111
  : { ok: false, problems: ['prototype: a prototype slug'] },
545
1112
  checkPrototypeAudience(audience),
546
1113
  );
547
- if (value === 'client') await kv.hset(KEY.audiences, slug, 'client');
548
- else await kv.hdel(KEY.audiences, slug);
1114
+ if (value === 'client') await kv.hset(keyOf(scope, 'audiences'), slug, 'client');
1115
+ else await kv.hdel(keyOf(scope, 'audiences'), slug);
549
1116
  return value;
550
1117
  },
551
1118
 
@@ -556,13 +1123,17 @@ export function createReview(kv: KV, overrides: Partial<Deps> = {}) {
556
1123
  * names are in the prototype's own code already. An internal prototype
557
1124
  * has none for a Client, as it has no comments.
558
1125
  */
559
- async controlsOf(actor: Person | null, prototype: unknown): Promise<{ view: PersonKind } & Marks> {
560
- allow(actor, 'read');
1126
+ async controlsOf(
1127
+ scope: Scope,
1128
+ actor: Person | null,
1129
+ prototype: unknown,
1130
+ ): Promise<{ view: PersonKind } & Marks> {
1131
+ const by = await allow(scope, actor, 'read', NO_PROTOTYPE);
561
1132
  if (!isPrototypeSlug(prototype))
562
1133
  throw new ReviewError('invalid', 'Some fields are not valid.', ['prototype: a prototype slug']);
563
- const view = viewOf(actor);
564
- if (!(await reachable(view, prototype))) throw new ReviewError('not_found', 'No such prototype.');
565
- return { view, ...readMarks(await kv.hgetall(KEY.controls(prototype))) };
1134
+ const view = viewOf(by);
1135
+ if (!(await reachable(scope, view, prototype))) throw new ReviewError('not_found', NO_PROTOTYPE);
1136
+ return { view, ...readMarks(await kv.hgetall(keyOf(scope, 'controls', prototype))) };
566
1137
  },
567
1138
 
568
1139
  /**
@@ -572,29 +1143,31 @@ export function createReview(kv: KV, overrides: Partial<Deps> = {}) {
572
1143
  * keeps no list of a prototype's controls, so any well-formed id is taken.
573
1144
  */
574
1145
  async setControl(
1146
+ scope: Scope,
575
1147
  actor: Person | null,
576
1148
  input: { prototype: unknown; kind: unknown; id: unknown; audience: unknown },
577
1149
  ): Promise<{ kind: ControlKind; id: string; audience: Audience }> {
578
- allow(actor, 'audience');
1150
+ await allow(scope, actor, 'audience', NO_PROTOTYPE);
579
1151
  const [slug, mark] = validAll<[string, { kind: ControlKind; id: string; audience: Audience }]>(
580
1152
  isPrototypeSlug(input.prototype)
581
1153
  ? { ok: true, value: input.prototype }
582
1154
  : { ok: false, problems: ['prototype: a prototype slug'] },
583
1155
  checkControl(input),
584
1156
  );
1157
+ const controls = keyOf(scope, 'controls', slug);
585
1158
  const field = controlField(mark.kind, mark.id);
586
- if (mark.kind === 'variant' && mark.audience === 'internal') await kv.hdel(KEY.controls(slug), field);
587
- else await kv.hset(KEY.controls(slug), field, mark.audience);
1159
+ if (mark.kind === 'variant' && mark.audience === 'internal') await kv.hdel(controls, field);
1160
+ else await kv.hset(controls, field, mark.audience);
588
1161
  return mark;
589
1162
  },
590
1163
 
591
1164
  /**
592
- * Who a prototype is for, asked by the gate with no actor. Absent, or any
593
- * value but `client`, is internal; a name that cannot be a prototype is
594
- * internal without asking the store.
1165
+ * Who a prototype of the scope's project is for, asked by the gate with no
1166
+ * actor. Absent, or any value but `client`, is internal; a name that
1167
+ * cannot be a prototype is internal without asking the store.
595
1168
  */
596
- async audienceOf(prototype: string): Promise<Audience> {
597
- return (await isClientFacing(prototype)) ? 'client' : 'internal';
1169
+ async audienceOf(scope: Scope, prototype: string): Promise<Audience> {
1170
+ return (await isClientFacing(scope, prototype)) ? 'client' : 'internal';
598
1171
  },
599
1172
 
600
1173
  /**
@@ -604,12 +1177,13 @@ export function createReview(kv: KV, overrides: Partial<Deps> = {}) {
604
1177
  * own list, which the gate refuses to a Client.
605
1178
  */
606
1179
  async visiblePrototypes(
1180
+ scope: Scope,
607
1181
  actor: Person | null,
608
1182
  viewAs?: unknown,
609
1183
  ): Promise<{ view: PersonKind; clientFacing: string[] }> {
610
- allow(actor, 'read');
611
- const view = viewOf(actor, valid(checkViewAs(viewAs)));
612
- const all = await kv.hgetall(KEY.audiences);
1184
+ const by = await allow(scope, actor, 'read', NO_PROTOTYPE);
1185
+ const view = viewOf(by, valid(checkViewAs(viewAs)));
1186
+ const all = await kv.hgetall(keyOf(scope, 'audiences'));
613
1187
  const clientFacing = Object.entries(all)
614
1188
  .filter(([slug, value]) => value === 'client' && isPrototypeSlug(slug))
615
1189
  .map(([slug]) => slug)
@@ -617,11 +1191,23 @@ export function createReview(kv: KV, overrides: Partial<Deps> = {}) {
617
1191
  return { view, clientFacing };
618
1192
  },
619
1193
 
620
- /** Where a comment lives, for the CLI, which has an id and no prototype; null when the actor may not see it. */
621
- async locate(actor: Person | null, id: string): Promise<{ prototype: string; comment: Comment } | null> {
622
- allow(actor, 'read');
623
- for (const prototype of await kv.smembers(KEY.prototypes)) {
624
- const found = await seen(actor, prototype, id);
1194
+ /**
1195
+ * Where a comment lives, for the CLI, which has an id and no prototype;
1196
+ * null when the actor may not see it, and outside the actor's scope or in
1197
+ * a client that is not live, as for an id that is not there.
1198
+ */
1199
+ async locate(
1200
+ scope: Scope,
1201
+ actor: Person | null,
1202
+ id: string,
1203
+ ): Promise<{ prototype: string; comment: Comment } | null> {
1204
+ const by = await allow(scope, actor, 'read', NO_COMMENT).catch((error: unknown) => {
1205
+ if (error instanceof ReviewError && error.code === 'not_found') return null;
1206
+ throw error;
1207
+ });
1208
+ if (!by) return null;
1209
+ for (const prototype of await kv.smembers(keyOf(scope, 'prototypes'))) {
1210
+ const found = await seen(scope, by, prototype, id);
625
1211
  if (found) return { prototype, comment: found.comment };
626
1212
  }
627
1213
  return null;