@milesroxas/design-hub 0.8.1 → 0.9.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 (59) hide show
  1. package/README.md +7 -2
  2. package/core/prototype.test.ts +83 -0
  3. package/core/prototype.ts +84 -0
  4. package/core/review/model.ts +7 -0
  5. package/core/review/policy.test.ts +4 -2
  6. package/core/review/policy.ts +4 -2
  7. package/core/review/service.test.ts +144 -4
  8. package/core/review/service.ts +70 -2
  9. package/core/review/store.ts +6 -0
  10. package/dist/core/prototype.d.ts +35 -0
  11. package/dist/core/prototype.js +84 -0
  12. package/dist/core/review/model.d.ts +2 -0
  13. package/dist/core/review/model.js +6 -0
  14. package/dist/core/review/policy.d.ts +1 -1
  15. package/dist/core/review/policy.js +1 -0
  16. package/dist/core/review/service.d.ts +23 -1
  17. package/dist/core/review/service.js +62 -3
  18. package/dist/core/review/store.d.ts +6 -0
  19. package/dist/core/review/store.js +6 -0
  20. package/dist/scripts/lib/cdp.js +6 -1
  21. package/dist/scripts/lib/export-smoke.d.ts +18 -0
  22. package/dist/scripts/lib/export-smoke.js +73 -0
  23. package/dist/scripts/new.js +5 -2
  24. package/dist/scripts/release-check.d.ts +5 -3
  25. package/dist/scripts/release-check.js +17 -4
  26. package/dist/scripts/share.d.ts +2 -2
  27. package/dist/server/api.js +8 -0
  28. package/dist/server/session.d.ts +5 -1
  29. package/dist/server/session.js +39 -21
  30. package/dist/vercel/proxy.js +44 -8
  31. package/dist/vite/boundary.d.ts +93 -0
  32. package/dist/vite/boundary.js +218 -0
  33. package/dist/vite/css-boundary.d.ts +39 -0
  34. package/dist/vite/css-boundary.js +167 -0
  35. package/dist/vite/kit.js +15 -6
  36. package/dist/vite/leaks.d.ts +37 -0
  37. package/dist/vite/leaks.js +331 -0
  38. package/dist/vite/plugin.js +2 -1
  39. package/dist/vite/registry.d.ts +15 -4
  40. package/dist/vite/registry.js +531 -27
  41. package/dist/vite/settle.d.ts +27 -0
  42. package/dist/vite/settle.js +185 -0
  43. package/package.json +4 -3
  44. package/shell/ClientViewNote.tsx +18 -0
  45. package/shell/Guide.tsx +17 -2
  46. package/shell/Index.tsx +257 -25
  47. package/shell/audience.test.ts +63 -0
  48. package/shell/audience.ts +47 -0
  49. package/shell/hub.ts +36 -0
  50. package/shell/main.tsx +39 -5
  51. package/shell/registry.ts +28 -7
  52. package/shell/registry.virtual.d.ts +12 -4
  53. package/shell/review/client.ts +16 -4
  54. package/shell/review/review.css +2 -2
  55. package/shell/shell.css +50 -3
  56. package/shell/system.css +5 -0
  57. package/skills/miles-deploy/SKILL.md +17 -0
  58. package/skills/miles-new-feature/SKILL.md +1 -1
  59. package/skills/miles-prototype/SKILL.md +14 -1
package/README.md CHANGED
@@ -35,7 +35,7 @@ A feature group, top to bottom:
35
35
  1. **Heading.** The feature's name. `Walkthrough →` ends the line when `docs/sprints/<feature>/guide.md` exists.
36
36
  2. **Primary.** The one `sprint` row, its title 16px against 14px for every other row. Size alone marks it; no badge, no new shape.
37
37
  3. **Alternates.** Under an `Alternates` caption (12px, 500, quaternary text), indented 20px and joined to the primary by a 1px rail in `--border-secondary` on the primary's text edge. The rail makes them children of that one row; a heading of their own would make them peers of the feature. A stray second `sprint` renders here too.
38
- 4. **Internal explorations.** A toggle (`Internal explorations`, the count, a chevron), collapsed by default because explorations are working material, not the feature. The open state persists per group in `localStorage` (`index-explorations-open`). Typing in the filter opens every fold, so a match is never hidden. Open, the explorations are cards on a grid (`minmax(208px, 1fr)`, 8px gap). Every exploration lives here, never in the row list.
38
+ 4. **Explorations.** A toggle (`Explorations`, the count, a chevron), collapsed by default because explorations are working material, not the feature. The open state persists per group in `localStorage` (`index-explorations-open`). Typing in the filter opens every fold, so a match is never hidden. Open, the explorations are cards on a grid (`minmax(208px, 1fr)`, 8px gap). Every exploration lives here, never in the row list.
39
39
 
40
40
  Within any list: exploring above decided, then newest first.
41
41
 
@@ -49,6 +49,10 @@ Surfaces:
49
49
  - **Foot.** The count alone, in body type over a hairline (the Ledger Foot Rule).
50
50
  - **Lede.** 18px/28px Geist at 400, secondary text. `--font-voice` resolves to Geist inside the hub's `.sys` scope (`shell/system.css`), so the index never borrows the project's faces.
51
51
 
52
+ ### Audience
53
+
54
+ Every prototype is Internal until Studio marks it Client-facing; a Client's index lists only the client-facing ones, and the gate refuses an internal prototype's page and files to a Client. Studio, outside Client view, sees each prototype's audience in a fifth column beside its row (under a card), never inside the link: `Internal` on the internal comments' amber (`--sys-internal`), `Client-facing` in quaternary text, then a switch (`role="switch"`, a 28px track, its hit area grown to 40px). A switch shows at once and is undone, with a toast, when the save fails. **Client view** in the head shows the index as a client gets it, with the comment layer's note at the bottom and **Leave**; in it no switch and no audience word shows. A Client with nothing shared sees `Nothing shared yet`.
55
+
52
56
  ### Motion
53
57
 
54
58
  Nothing animates on a keyboard action.
@@ -76,8 +80,9 @@ Every person is named, and signs in with a one-time link that Studio makes in th
76
80
  - **A second device gets a second link** (`design-hub people link <id>`), and the first stays signed in. **Sign out everywhere** (`people sign-out <id>`) bumps the person's epoch, drops their unused links and returns one new link. **Revoke** ends their access everywhere.
77
81
  - **What a stale write cannot undo.** A person is a profile (name, team, kind, access end), written read-modify-write, plus two records only revoke and sign out everywhere touch: the revocation, written once and never cleared, and the epoch, raised only by `HINCRBY`. So a profile change that started before a revoke or a sign out everywhere and lands after it never clears the revocation or lowers the epoch, and two sign outs everywhere at once raise it twice.
78
82
  - **Access lasts the engagement.** Each person has an access end: 3 months, 6 months, or open-ended. The project default (`people access --access <length>`, or `bootstrap --review --access`) applies to a new Client and is 3 months when unset; a new Studio person is open-ended, and Studio can set one person's length from the People tab or `people access <id>`.
79
- - **The session** is one cookie, `__Host-hub_person`: `HttpOnly`, `Secure`, `SameSite=Lax`, signed with HMAC-SHA256 over the person, their epoch, an expiry, `checkedAt` (when the store last said yes) and the review store's URL, which is signed but never written into the token, so two projects that share a `GATE_SECRET` never accept each other's cookies, and versioned (`p3`), so a cookie from an older release never verifies. It lasts to the access end, at most 400 days, the longest a browser keeps one. For `CHECK_SECONDS` (5 minutes) after `checkedAt` any request passes on the signature. After that the next request, of any kind, asks the store: a current person passes with a fresh cookie whose expiry follows their current access end; a revoked, signed-out-everywhere or ended person gets 401 and the cookie cleared. The request's own headers never decide whether the store is asked, since the client chooses them. A store that fails answers 503 with `Retry-After`, and leaves the cookie, so an outage signs nobody out; the review panel reads `Retry-After` as try again, and a 503 without it as a site with no store. The API function answers the same way in JSON. The sign-in POST also refuses a store failure with 503, and a link is checked before it is used up, so a failure never burns one.
83
+ - **The session** is one cookie, `__Host-hub_person`: `HttpOnly`, `Secure`, `SameSite=Lax`, signed with HMAC-SHA256 over the person, their epoch, their kind (Studio or Client), an expiry, `checkedAt` (when the store last said yes) and the review store's URL, which is signed but never written into the token, so two projects that share a `GATE_SECRET` never accept each other's cookies, and versioned (`p4`), so a cookie from an older release never verifies. The one exception is `p3`, the version before the kind: a valid one still passes, read as stale, so the next request asks the store and re-issues it as `p4`, and nobody is signed out by the upgrade. It lasts to the access end, at most 400 days, the longest a browser keeps one. For `CHECK_SECONDS` (5 minutes) after `checkedAt` any request passes on the signature. After that the next request, of any kind, asks the store: a current person passes with a fresh cookie whose expiry follows their current access end; a revoked, signed-out-everywhere or ended person gets 401 and the cookie cleared. The request's own headers never decide whether the store is asked, since the client chooses them. A store that fails answers 503 with `Retry-After`, and leaves the cookie, so an outage signs nobody out; the review panel reads `Retry-After` as try again, and a 503 without it as a site with no store. The API function answers the same way in JSON. The sign-in POST also refuses a store failure with 503, and a link is checked before it is used up, so a failure never burns one.
80
84
  - **The link page** sends `Referrer-Policy: same-origin`, so Continue's POST carries a real `Origin` (with `no-referrer` a browser sends `Origin: null`, trusted only beside `Sec-Fetch-Site`, which older Safari does not send). Every other gate response sends `no-referrer`.
85
+ - **Internal prototypes.** Everything built from `prototypes/<slug>/` (its README, code, CSS, fixtures, lazy chunks and images) lands under `/_p/<slug>/`, its entry at `/_p/<slug>/entry.js`, and Studio's list of every slug at `/_p/all.js`; the shared bundle in `/assets/` names no prototype's folder (`vite/registry.ts`, `vite/boundary.ts`, `vite/settle.ts`; the build fails if a file breaks that). The exception is the walkthroughs: their compiled text and every feature's name sit in `/assets/` and reach every signed-in person, so a walkthrough must not name or describe internal work until that is built. A built file is owned by where its content comes from, never by who reads it, and each source is recorded as the file is written (`vite/settle.ts`): a stylesheet's CSS modules, an asset's original files, a worker's output; a file with no record and no fixed name fails the build. Nothing a prototype owns is inlined by the size limit, and nothing under `prototypes/` is ever the hub's: a file directly there, or in a folder without a README, is refused (shared code belongs in `kit/`). Any import or `new URL` (`?inline` included) into a prototype its importer does not own is refused in dev and in a build. Every stylesheet is read for reaches inside Vite's postcss run (`vite/css-boundary.ts`), each reference followed as a path and through Vite's own resolvers (aliases and package paths included); Sass, Less and Stylus are refused in prototypes and the project's `kit/`, since their imports resolve inside the preprocessor; and every worker bundle refuses a module under `prototypes/` and resolves `@kit/*`. After the bundle is settled the build reads what it wrote (`vite/leaks.ts`): a file outside `/_p/<slug>/` that holds a whole file of `prototypes/<slug>/` (its bytes, a base64 or SVG data URI of it anywhere in the file, or, for a file the build read, its whole text as a string in a script; 40 bytes or more) fails the build, unless the reader's owner has a source with the same content. It is a backstop for whole-file inlining: no part of a file (a line, a rule) is looked for. Vite is pinned to 8.3 (`~8.3.5`) because the boundary leans on its internals; `vite/build.test.ts` is what to run on a Vite upgrade. A file a prototype owns lives in its folder; the hub's and the kit's live in `/assets/` and are never copied into a prototype's folder; the same bytes from several owners become one copy per owner, each named from its owner's source. A file that reads what another prototype owns, or a hub or kit file that reads what a prototype owns, fails the build, naming both. A prototype that reaches into another (an import, a CSS `@import` or `url()`, a `new URL`) or starts a web worker fails the build. A Client asking for a prototype's page (`/<slug>/`) or anything under `/_p/<slug>/` gets 404 unless that prototype is client-facing, asked of the store on every such request; `/_p/all.js` is always 404 to a Client, and an internal prototype and one that does not exist answer byte for byte the same. A path that could mean more than one file (a `.` or `..` segment, a backslash, an empty segment, a `%` left after decoding, or one that does not decode) gets the same 404, as does any first segment that is not `/`, the hub's own (`assets`, `api`, `guide`, `_gate`, `index.html`, `favicon.svg`), `_p` or a prototype slug. A Client's comments on a prototype that is not client-facing answer as if it had none. Studio passes on the cookie's kind with no store read. `/`, `/assets/*`, `/guide/*` and `/api/*` pass as before. `guide`, `api` and `assets` are never a prototype's slug (`core/prototype.ts`).
81
86
  - **Signed out**, a page gets the sign-in page (401). It has no form: it says to open the link the studio sent, that each link signs in one device and then stops working, and to ask the studio for a new one for another device. Anything else gets a plain-text 401, an anonymous `POST` included.
82
87
 
83
88
  The middleware reads one environment variable, set in the Vercel project for Production and Preview and never committed (`.env.example` names it): `GATE_SECRET`, at least 32 random characters that sign the session cookie. With it missing the gate answers 503 on every path, so a misconfigured deploy never serves the prototypes open. People and links live in the review store, so a site without it has a gate nobody can pass. The gate pages ship a hash-based Content Security Policy with no `unsafe-inline` and no script, plus `font-src 'self'` and `img-src 'self'`, and send no referrer. They wear the hub's neutral look in Geist, so two files pass the gate without a session: `/_gate/geist.woff2` (the latin subset, emitted by `vite/plugin.ts` at that fixed path) and `/favicon.svg`. Nothing else does. Every response carries `X-Robots-Tag: noindex`, so no search engine lists the site. The pages' title is the `siteName` the project's `proxy.ts` passes to `createProxy`. Under `design-hub dev` there is no gate; `/_gate/` previews the sign-in page, `?page=link` a link's page and `?page=used` a used one.
@@ -0,0 +1,83 @@
1
+ import assert from 'node:assert/strict';
2
+ import { test } from 'node:test';
3
+ import { ALL_FILE, entryFile, isPrototypeSlug, probeEntry, prototypeOfPath, RESERVED } from './prototype.ts';
4
+
5
+ test('a prototype slug is kebab-case and never one of the hub’s own paths', () => {
6
+ assert.deepEqual([...RESERVED], ['guide', 'api', 'assets']);
7
+ for (const reserved of RESERVED) assert.equal(isPrototypeSlug(reserved), false);
8
+ assert.equal(isPrototypeSlug('sample-list'), true);
9
+ for (const bad of ['_p', 'Sample', 'a_b', '', 'a.js', 'a/b', null, 3])
10
+ assert.equal(isPrototypeSlug(bad), false);
11
+ assert.equal(entryFile('sample-list'), '_p/sample-list/entry.js');
12
+ assert.equal(ALL_FILE, '_p/all.js');
13
+ });
14
+
15
+ test('a path names its prototype, or none for the hub’s own', () => {
16
+ const cases: [string, string | null][] = [
17
+ ['/', null],
18
+ ['/assets/index-abc.js', null],
19
+ ['/guide/sample/', null],
20
+ ['/api/review', null],
21
+ ['/favicon.svg', null],
22
+ ['/_gate/geist.woff2', null],
23
+ ['/index.html', null],
24
+ ['/robots.txt', ''],
25
+ ['/invite/short', 'invite'],
26
+ ['/Sample-List/', ''],
27
+ ['/_p;x/secret/entry.js', ''],
28
+ ['/_p./secret/entry.js', ''],
29
+ ['/_p%20/secret/entry.js', ''],
30
+ ['/_p%00/secret/entry.js', ''],
31
+ ['/%EF%BC%BFp/secret/entry.js', ''],
32
+ ['/_p/secret/entry.js', ''],
33
+ ['/assets;x/y.js', ''],
34
+ ['/sample-list/', 'sample-list'],
35
+ ['/sample-list', 'sample-list'],
36
+ ['/sample-list/deep/path', 'sample-list'],
37
+ ['/_p/sample-list/entry.js', 'sample-list'],
38
+ ['/_p/sample-list', 'sample-list'],
39
+ ['/_p/all.js', 'all.js'],
40
+ ['/_p/', ''],
41
+ ['/_p', ''],
42
+ ['//_p//sample-list/x.js', ''],
43
+ ['/assets/..%2f_p/secret/entry.js', ''],
44
+ ['/api/..%2f_p/secret/entry.js', ''],
45
+ ['/_p/open/..%2fsecret/entry.js', ''],
46
+ ['/_p/open/.%2fentry.js', ''],
47
+ ['/assets//x.js', ''],
48
+ ['/_P/secret/entry.js', ''],
49
+ ['/_P/all.js', ''],
50
+ ['/%255Fp/secret/entry.js', ''],
51
+ ['/_p%5csecret%5centry.js', ''],
52
+ ['/assets%5cx.js', ''],
53
+ ['/assets/a%20b.png', null],
54
+ ['/assets/caf%C3%A9.png', null],
55
+ ['/_p/secret/caf%C3%A9%20x.png', 'secret'],
56
+ ['/guide/', null],
57
+ ['/%5Fp/sample-list/entry.js', 'sample-list'],
58
+ ['/_p/sample%2Dlist/entry.js', 'sample-list'],
59
+ ['/_p%2Fsample-list%2Fentry.js', 'sample-list'],
60
+ ['/%73ample-list/', 'sample-list'],
61
+ ['/%E0%A4%A/', ''],
62
+ ];
63
+ for (const [path, owner] of cases) assert.equal(prototypeOfPath(path), owner, path);
64
+ });
65
+
66
+ test('an entry is there on a JavaScript 200, not there on a 404 or the host’s page, and an error otherwise', async () => {
67
+ const asked: [string, RequestInit | undefined][] = [];
68
+ const answer = (status: number, type = 'text/javascript') =>
69
+ (async (url: string, init?: RequestInit) => {
70
+ asked.push([url, init]);
71
+ return new Response(null, { status, headers: { 'content-type': type } });
72
+ }) as unknown as typeof fetch;
73
+ assert.equal(await probeEntry('/_p/a/entry.js', answer(200)), true);
74
+ assert.equal(
75
+ await probeEntry('/_p/a/entry.js', answer(200, 'application/javascript; charset=utf-8')),
76
+ true,
77
+ );
78
+ assert.equal(await probeEntry('/_p/a/entry.js', answer(404)), false);
79
+ assert.equal(await probeEntry('/_p/a/entry.js', answer(200, 'text/html; charset=utf-8')), false);
80
+ for (const status of [401, 403, 500, 503])
81
+ await assert.rejects(probeEntry('/_p/a/entry.js', answer(status)), new RegExp(`answered ${status}`));
82
+ assert.deepEqual(asked[0], ['/_p/a/entry.js', { method: 'HEAD', credentials: 'same-origin' }]);
83
+ });
@@ -0,0 +1,84 @@
1
+ // What a prototype's slug may be, and where the files built from it live.
2
+ // One rule for the registry's scan, `design-hub new` and the gate, so a
3
+ // folder the hub lists is always a path the gate knows how to refuse.
4
+ import { SLUG } from './feature.ts';
5
+
6
+ /**
7
+ * First path segments the hub owns, never a prototype: the walkthroughs,
8
+ * the review API, and the shared bundle.
9
+ */
10
+ export const RESERVED = ['guide', 'api', 'assets'] as const;
11
+
12
+ /**
13
+ * Everything built from `prototypes/<slug>/` lands under `/_p/<slug>/`, and
14
+ * Studio's list of every slug at `/_p/all.js`. `_p` can never be a slug: SLUG
15
+ * has no underscore.
16
+ */
17
+ export const PROTOTYPE_DIR = '_p';
18
+ export const ALL_FILE = `${PROTOTYPE_DIR}/all.js`;
19
+ export const entryFile = (slug: string) => `${PROTOTYPE_DIR}/${slug}/entry.js`;
20
+
21
+ /** Whether `name` can be a prototype's folder: kebab-case and not one of the hub's own paths. */
22
+ export const isPrototypeSlug = (name: unknown): name is string =>
23
+ typeof name === 'string' && SLUG.test(name) && !(RESERVED as readonly string[]).includes(name);
24
+
25
+ /**
26
+ * A path's segments as a file server might read them, or null when the path
27
+ * could mean more than one file: it does not decode, still holds a `%` after
28
+ * decoding (`%255F`), holds a backslash, a `.` or `..` segment, or an empty
29
+ * segment other than the last. The gate refuses those to a Client rather than
30
+ * guess how the server resolves them. An encoded space or letter decodes and passes.
31
+ */
32
+ function segments(pathname: string): string[] | null {
33
+ let decoded: string;
34
+ try {
35
+ decoded = decodeURIComponent(pathname);
36
+ } catch {
37
+ return null;
38
+ }
39
+ if (/[%\\]/.test(decoded)) return null;
40
+ const parts = decoded.split('/').slice(1);
41
+ if (parts.at(-1) === '') parts.pop();
42
+ return parts.some((p) => p === '' || p === '.' || p === '..') ? null : parts;
43
+ }
44
+
45
+ /**
46
+ * The first path segments that are the hub's own, for anyone signed in: the
47
+ * reserved routes, the gate's font folder, and the files the hub serves at
48
+ * the top (shell/index.html, shell/public/favicon.svg).
49
+ */
50
+ const HUB_ROOT: readonly string[] = [...RESERVED, '_gate', 'index.html', 'favicon.svg'];
51
+
52
+ /**
53
+ * Which prototype a request path belongs to, for the gate: the name a
54
+ * prototype path carries, or null for a hub path (`/`, or a first segment in
55
+ * HUB_ROOT). The first segment, decoded, must be one of those, `_p`, or a
56
+ * prototype slug; anything else (`_P`, `_p;x`, `_p.`, a full-width `_p`)
57
+ * belongs to `''`, refused like an internal prototype. A path under `/_p/`
58
+ * always belongs to one, so its name may be no slug at all (`all.js`), which
59
+ * no audience makes client-facing. A path that could mean more than one file
60
+ * belongs to `''` too.
61
+ */
62
+ export function prototypeOfPath(pathname: string): string | null {
63
+ const parts = segments(pathname);
64
+ if (!parts) return '';
65
+ const [first, second] = parts;
66
+ if (first === undefined || HUB_ROOT.includes(first)) return null;
67
+ if (first === PROTOTYPE_DIR) return second ?? '';
68
+ return isPrototypeSlug(first) ? first : '';
69
+ }
70
+
71
+ /**
72
+ * Whether a built prototype's entry is there for this person, asked with a
73
+ * HEAD before it is imported. Not there: a 404 (the gate's answer for a
74
+ * prototype this person may not open, or none at all), or a 200 that is not
75
+ * JavaScript (the host's page for an entry that was never built). Any other
76
+ * answer (401, 500, 503) is an error, never "not there", so an outage never
77
+ * reads as nothing shared.
78
+ */
79
+ export async function probeEntry(path: string, fetcher: typeof fetch): Promise<boolean> {
80
+ const head = await fetcher(path, { method: 'HEAD', credentials: 'same-origin' });
81
+ if (head.status === 404) return false;
82
+ if (head.status !== 200) throw new Error(`${path} answered ${head.status}.`);
83
+ return /javascript/.test(head.headers.get('content-type') ?? '');
84
+ }
@@ -234,6 +234,13 @@ export function checkAudience(input: unknown): Checked<Audience | null> {
234
234
  : { ok: false, problems: [`audience: one of ${AUDIENCES.join(', ')}`] };
235
235
  }
236
236
 
237
+ /** A prototype's audience as Studio sets it: one of AUDIENCES, required. */
238
+ export function checkPrototypeAudience(input: unknown): Checked<Audience> {
239
+ return AUDIENCES.includes(input as Audience)
240
+ ? { ok: true, value: input as Audience }
241
+ : { ok: false, problems: [`audience: one of ${AUDIENCES.join(', ')}`] };
242
+ }
243
+
237
244
  /** Whose view of the comments is asked for: a person kind, or null for the caller's own. */
238
245
  export function checkViewAs(input: unknown): Checked<PersonKind | null> {
239
246
  if (input === undefined || input === null) return { ok: true, value: null };
@@ -48,6 +48,8 @@ const TABLE: [Action, Audience, boolean, boolean, boolean, boolean][] = [
48
48
  ['triage', 'internal', true, true, false, false],
49
49
  ['people', 'client', true, true, false, false],
50
50
  ['people', 'internal', true, true, false, false],
51
+ ['audience', 'client', true, true, false, false],
52
+ ['audience', 'internal', true, true, false, false],
51
53
  ];
52
54
 
53
55
  const studio = person('s', 'studio');
@@ -72,12 +74,12 @@ for (const [action, audience, studioOwn, studioOther, clientOwn, clientOther] of
72
74
  });
73
75
  }
74
76
 
75
- test('with no thread, both kinds read and start one; only Studio triages and manages people', () => {
77
+ test('with no thread, both kinds read and start one; only Studio triages, manages people and sets a prototype’s audience', () => {
76
78
  for (const action of ['read', 'comment'] as const) {
77
79
  assert.equal(can(studio, action), true);
78
80
  assert.equal(can(client, action), true);
79
81
  }
80
- for (const action of ['triage', 'people'] as const) {
82
+ for (const action of ['triage', 'people', 'audience'] as const) {
81
83
  assert.equal(can(studio, action), true);
82
84
  assert.equal(can(client, action), false);
83
85
  }
@@ -1,5 +1,6 @@
1
1
  // Who may do what. Studio runs the review: it adds and revokes people,
2
- // deletes any comment and corrects triage. A Client comments, replies, edits
2
+ // deletes any comment, corrects triage and sets which prototypes are
3
+ // client-facing. A Client comments, replies, edits
3
4
  // and deletes what they wrote, and resolves or reopens any client-facing
4
5
  // thread, because clients work alongside others in their own organisation.
5
6
  // An internal thread does not exist for a Client: every action on one is
@@ -7,7 +8,7 @@
7
8
  // nothing here.
8
9
  import type { Audience, Comment, Person, PersonKind } from './model.ts';
9
10
 
10
- export type Action = 'read' | 'comment' | 'edit' | 'delete' | 'resolve' | 'triage' | 'people';
11
+ export type Action = 'read' | 'comment' | 'edit' | 'delete' | 'resolve' | 'triage' | 'people' | 'audience';
11
12
 
12
13
  /** Only what the rules read, so the browser's signed-in person (no epoch) is checked by the same rules. */
13
14
  type Actor = Pick<Person, 'id' | 'kind' | 'revokedAt'>;
@@ -36,6 +37,7 @@ export function can(actor: Actor | null, action: Action, root?: Comment, subject
36
37
  return own || studio;
37
38
  case 'triage':
38
39
  case 'people':
40
+ case 'audience':
39
41
  return studio;
40
42
  }
41
43
  }
@@ -47,6 +47,8 @@ beforeEach(async () => {
47
47
  const r = await review.addPerson(studio, { name: 'Rae', team: 'Acme' });
48
48
  client = r.person;
49
49
  clientToken = r.token;
50
+ // The prototype these tests comment on is client-facing, so a Client reaches its comments.
51
+ await review.setAudience(studio, anchor.prototype, 'client');
50
52
  });
51
53
 
52
54
  test('a link works once, and looking at it uses nothing up', async () => {
@@ -60,10 +62,8 @@ test('a link works once, and looking at it uses nothing up', async () => {
60
62
 
61
63
  test('two requests with one link at once sign in one device', async () => {
62
64
  const both = await Promise.all([review.useLink(clientToken), review.useLink(clientToken)]);
63
- assert.deepEqual(
64
- both.map((p) => p?.id ?? null),
65
- [client.id, null],
66
- );
65
+ // Either request may win the claim; exactly one does.
66
+ assert.deepEqual(both.map((p) => p?.id ?? null).sort(), [client.id, null].sort());
67
67
  });
68
68
 
69
69
  test('a new link is for another device: sessions and other links stay', async () => {
@@ -555,6 +555,7 @@ test('triage runs on add, and a failing triager never loses the comment', async
555
555
  return { kind: 'bug', state: states[0] ?? null, by: 'jev', confidence: 0.9 };
556
556
  },
557
557
  });
558
+ await triaged.setAudience(studio, anchor.prototype, 'client');
558
559
  const c = await triaged.add(client, {
559
560
  body: 'Broken',
560
561
  anchor,
@@ -563,6 +564,7 @@ test('triage runs on add, and a failing triager never loses the comment', async
563
564
  assert.deepEqual(seen, [['Empty', 'Real list']]);
564
565
  assert.equal(c.triage?.kind, 'bug');
565
566
  const failing = createReview(memoryKV(), { triage: async () => Promise.reject(new Error('down')) });
567
+ await failing.setAudience(studio, anchor.prototype, 'client');
566
568
  assert.equal((await failing.add(client, { body: 'Still saved', anchor })).triage, null);
567
569
  });
568
570
 
@@ -704,6 +706,7 @@ test('numbers are fixed: internal and client-facing threads count apart, and non
704
706
  });
705
707
 
706
708
  test('numbers count per prototype', async () => {
709
+ await review.setAudience(studio, 'other', 'client');
707
710
  const a = await review.add(client, { body: 'A1', anchor });
708
711
  const b = await review.add(client, { body: 'B1', anchor: { ...anchor, prototype: 'other' } });
709
712
  const a2 = await review.add(studio, { body: 'A2', anchor, audience: 'client' });
@@ -781,3 +784,140 @@ test('a stored comment without an audience is internal, and one without a number
781
784
  assert.equal(await r.locate(rae, 'old'), null);
782
785
  await rejects(r.edit(rae, { prototype: 'sample-list', id: 'old', body: 'x' }), 'not_found');
783
786
  });
787
+
788
+ test('a prototype is internal until Studio marks it client-facing, and internal again when unmarked', async () => {
789
+ assert.equal(await review.audienceOf('secret-plan'), 'internal');
790
+ assert.equal(await review.setAudience(studio, 'secret-plan', 'client'), 'client');
791
+ assert.equal(await review.audienceOf('secret-plan'), 'client');
792
+ assert.equal(await review.audienceOf('sample-page'), 'internal');
793
+ assert.equal(await review.setAudience(studio, 'secret-plan', 'internal'), 'internal');
794
+ assert.equal(await review.audienceOf('secret-plan'), 'internal');
795
+ // Marking internal twice, or one never marked, is no error.
796
+ assert.equal(await review.setAudience(studio, 'sample-page', 'internal'), 'internal');
797
+ });
798
+
799
+ test('only client-facing is stored: internal deletes the field, and absent or garbage reads as internal', async () => {
800
+ const kv = memoryKV();
801
+ const own = createReview(kv);
802
+ await own.setAudience(studio, 'secret-plan', 'client');
803
+ assert.deepEqual(await kv.hgetall(KEY.audiences), { 'secret-plan': 'client' });
804
+ await own.setAudience(studio, 'secret-plan', 'internal');
805
+ assert.deepEqual(await kv.hgetall(KEY.audiences), {});
806
+ for (const garbage of ['Client', 'internal', '', '"client"', 'true', ' client']) {
807
+ await kv.hset(KEY.audiences, 'secret-plan', garbage);
808
+ assert.equal(await own.audienceOf('secret-plan'), 'internal', garbage);
809
+ }
810
+ await kv.hset(KEY.audiences, 'sample-page', 'yes');
811
+ await kv.hset(KEY.audiences, 'guide', 'client');
812
+ await kv.hset(KEY.audiences, 'Not_A_Slug', 'client');
813
+ await kv.hset(KEY.audiences, 'sample-social', 'client');
814
+ assert.deepEqual(await own.visiblePrototypes(studio), { view: 'studio', clientFacing: ['sample-social'] });
815
+ // A name that can never be a prototype is internal without a store read.
816
+ assert.equal(await own.audienceOf('guide'), 'internal');
817
+ assert.equal(await own.audienceOf('all.js'), 'internal');
818
+ });
819
+
820
+ test('only Studio sets an audience: a Client is forbidden, a signed-out caller unauthorized, whatever the input', async () => {
821
+ await rejects(review.setAudience(client, 'secret-plan', 'client'), 'forbidden');
822
+ await rejects(review.setAudience(client, 'nope!', 'garbage'), 'forbidden');
823
+ await rejects(review.setAudience(null, 'secret-plan', 'client'), 'unauthorized');
824
+ const revoked = await review.revoke(studio, client.id);
825
+ await rejects(review.setAudience({ ...revoked, kind: 'studio' }, 'secret-plan', 'client'), 'forbidden');
826
+ assert.equal(await review.audienceOf('secret-plan'), 'internal');
827
+ });
828
+
829
+ test('a prototype’s audience is checked: the slug and the value, every problem named', async () => {
830
+ await assert.rejects(
831
+ review.setAudience(studio, 'Bad Slug', 'everyone'),
832
+ (e: unknown) =>
833
+ e instanceof ReviewError &&
834
+ e.code === 'invalid' &&
835
+ e.problems.join('|') === 'prototype: a prototype slug|audience: one of internal, client',
836
+ );
837
+ for (const reserved of ['guide', 'api', 'assets'])
838
+ await rejects(review.setAudience(studio, reserved, 'client'), 'invalid');
839
+ await rejects(review.setAudience(studio, 'sample-list', null), 'invalid');
840
+ await rejects(review.setAudience(studio, 'sample-list', undefined), 'invalid');
841
+ });
842
+
843
+ test('the index read: Studio’s view, Client view, and a Client’s, each with the client-facing slugs', async () => {
844
+ await review.setAudience(studio, 'sample-page', 'client');
845
+ await review.setAudience(studio, 'sample-list', 'client');
846
+ const facing = ['sample-list', 'sample-page'];
847
+ assert.deepEqual(await review.visiblePrototypes(studio), { view: 'studio', clientFacing: facing });
848
+ assert.deepEqual(await review.visiblePrototypes(studio, 'studio'), {
849
+ view: 'studio',
850
+ clientFacing: facing,
851
+ });
852
+ assert.deepEqual(await review.visiblePrototypes(studio, 'client'), {
853
+ view: 'client',
854
+ clientFacing: facing,
855
+ });
856
+ // A Client asking for Studio's view still gets a Client's.
857
+ assert.deepEqual(await review.visiblePrototypes(client), { view: 'client', clientFacing: facing });
858
+ assert.deepEqual(await review.visiblePrototypes(client, 'studio'), {
859
+ view: 'client',
860
+ clientFacing: facing,
861
+ });
862
+ await rejects(review.visiblePrototypes(studio, 'everyone'), 'invalid');
863
+ await rejects(review.visiblePrototypes(null), 'unauthorized');
864
+ await rejects(review.visiblePrototypes(null, 'client'), 'unauthorized');
865
+ });
866
+
867
+ /** A client-facing thread with a Client's reply on it, then the prototype switched back to internal. */
868
+ async function onInternalPrototype() {
869
+ const root = await review.add(studio, { body: 'For the client', anchor, audience: 'client' });
870
+ const reply = await review.reply(client, { prototype: anchor.prototype, thread: root.id, body: 'Seen' });
871
+ await review.setAudience(studio, anchor.prototype, 'internal');
872
+ return { root, reply };
873
+ }
874
+
875
+ test('a Client’s list of an internal prototype is empty, as if it had no comments, and so is Studio’s Client view', async () => {
876
+ await onInternalPrototype();
877
+ assert.deepEqual(await review.listComments(client, anchor.prototype), []);
878
+ assert.deepEqual(await review.listComments(client, anchor.prototype, 'studio'), []);
879
+ assert.deepEqual(await review.listComments(studio, anchor.prototype, 'client'), []);
880
+ // The same answer as a prototype nobody made.
881
+ assert.deepEqual(await review.listComments(client, 'no-such-thing'), []);
882
+ assert.equal((await review.listComments(studio, anchor.prototype)).length, 2);
883
+ assert.deepEqual(await review.allComments(client), []);
884
+ assert.equal((await review.allComments(studio)).length, 2);
885
+ // Client-facing again: the thread is back for them, with its reply.
886
+ await review.setAudience(studio, anchor.prototype, 'client');
887
+ assert.equal((await review.listComments(client, anchor.prototype)).length, 2);
888
+ });
889
+
890
+ test('a Client acting on a client-facing thread of an internal prototype is told it does not exist, by every op', async () => {
891
+ const { root, reply } = await onInternalPrototype();
892
+ const at = { prototype: anchor.prototype };
893
+ for (const id of [root.id, reply.id]) {
894
+ await rejects(review.reply(client, { ...at, thread: id, body: 'x' }), 'not_found');
895
+ await rejects(review.edit(client, { ...at, id, body: 'x' }), 'not_found');
896
+ await rejects(review.remove(client, { ...at, id }), 'not_found');
897
+ await rejects(review.resolve(client, { ...at, id, resolved: true }), 'not_found');
898
+ await rejects(review.resolve(client, { ...at, id, resolved: false }), 'not_found');
899
+ await rejects(review.retriage(client, { ...at, id, triage: { kind: 'bug' } }), 'forbidden');
900
+ assert.equal(await review.locate(client, id), null);
901
+ assert.ok(await review.locate(studio, id));
902
+ }
903
+ // The same answers as an id, and a prototype, that are not there at all.
904
+ await rejects(review.edit(client, { ...at, id: 'nope', body: 'x' }), 'not_found');
905
+ await rejects(review.edit(client, { prototype: 'no-such-thing', id: 'nope', body: 'x' }), 'not_found');
906
+ // A new thread there is refused the same way, and nothing is written or counted.
907
+ await rejects(review.add(client, { body: 'Hello?', anchor }), 'not_found');
908
+ await rejects(
909
+ review.add(client, { body: 'Hello?', anchor: { ...anchor, prototype: 'no-such-thing' } }),
910
+ 'not_found',
911
+ );
912
+ const after = await review.listComments(studio, anchor.prototype);
913
+ assert.deepEqual(
914
+ after.map((c) => [c.body, c.status]),
915
+ [
916
+ ['For the client', 'open'],
917
+ ['Seen', 'open'],
918
+ ],
919
+ );
920
+ // Studio, writing as Studio from Client view, still works there.
921
+ assert.ok(await review.add(studio, { body: 'Internal note', anchor }));
922
+ assert.ok(await review.reply(studio, { ...at, thread: root.id, body: 'Studio reply' }));
923
+ });
@@ -5,6 +5,7 @@
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
7
  import { base64url, hex, sha256 } from '../bytes.ts';
8
+ import { isPrototypeSlug } from '../prototype.ts';
8
9
  import {
9
10
  type Access,
10
11
  type Anchor,
@@ -18,6 +19,7 @@ import {
18
19
  checkAudience,
19
20
  checkBody,
20
21
  checkPersonInput,
22
+ checkPrototypeAudience,
21
23
  checkStates,
22
24
  checkTriage,
23
25
  checkViewAs,
@@ -28,6 +30,7 @@ import {
28
30
  LINK_DAYS,
29
31
  type Link,
30
32
  type Person,
33
+ type PersonKind,
31
34
  readComment,
32
35
  type Triage,
33
36
  } from './model.ts';
@@ -219,6 +222,17 @@ export function createReview(kv: KV, overrides: Partial<Deps> = {}) {
219
222
  const saveComment = (prototype: string, c: Comment) =>
220
223
  kv.hset(KEY.comments(prototype), c.id, JSON.stringify(c));
221
224
 
225
+ const isClientFacing = async (prototype: string) =>
226
+ isPrototypeSlug(prototype) && (await kv.hget(KEY.audiences, prototype)) === 'client';
227
+
228
+ /**
229
+ * Whether a view reaches a prototype's comments at all. A Client's view
230
+ * reaches only a client-facing prototype: on any other, every op answers
231
+ * as if it had no comments, so no answer confirms an internal slug.
232
+ */
233
+ const reachable = async (view: PersonKind, prototype: string) =>
234
+ view === 'studio' || (await isClientFacing(prototype));
235
+
222
236
  /**
223
237
  * A comment and its thread's root, if `actor` may see both; else null. A
224
238
  * reply whose root is gone is not there either.
@@ -228,6 +242,7 @@ export function createReview(kv: KV, overrides: Partial<Deps> = {}) {
228
242
  prototype: string,
229
243
  id: string,
230
244
  ): Promise<{ comment: Comment; root: Comment } | null> {
245
+ if (!(await reachable(viewOf(actor), prototype))) return null;
231
246
  const comment = await commentAt(prototype, id);
232
247
  if (!comment) return null;
233
248
  const root = isRoot(comment) ? comment : await commentAt(prototype, comment.thread);
@@ -382,14 +397,17 @@ export function createReview(kv: KV, overrides: Partial<Deps> = {}) {
382
397
  async listComments(actor: Person | null, prototype: string, viewAs?: unknown): Promise<Comment[]> {
383
398
  allow(actor, 'read');
384
399
  const view = viewOf(actor, valid(checkViewAs(viewAs)));
400
+ if (!(await reachable(view, prototype))) return [];
385
401
  return visibleTo(view, await commentsOf(prototype));
386
402
  },
387
403
 
388
404
  /** Every comment on every prototype the actor may see, for the CLI (which acts as Studio). */
389
405
  async allComments(actor: Person | null): Promise<Comment[]> {
390
406
  allow(actor, 'read');
391
- const prototypes = await kv.smembers(KEY.prototypes);
392
- return visibleTo(viewOf(actor), (await Promise.all(prototypes.map(commentsOf))).flat());
407
+ const view = viewOf(actor);
408
+ const prototypes = [];
409
+ for (const p of await kv.smembers(KEY.prototypes)) if (await reachable(view, p)) prototypes.push(p);
410
+ return visibleTo(view, (await Promise.all(prototypes.map(commentsOf))).flat());
393
411
  },
394
412
 
395
413
  /**
@@ -407,6 +425,9 @@ export function createReview(kv: KV, overrides: Partial<Deps> = {}) {
407
425
  checkAnchor(input.anchor),
408
426
  checkAudience(input.audience),
409
427
  );
428
+ // A Client's thread on a prototype that is not client-facing: the answer an unknown id gets.
429
+ if (!(await reachable(viewOf(actor), anchor.prototype)))
430
+ throw new ReviewError('not_found', 'No such comment.');
410
431
  const id = newId();
411
432
  const triage = deps.triage
412
433
  ? await deps
@@ -508,6 +529,53 @@ export function createReview(kv: KV, overrides: Partial<Deps> = {}) {
508
529
  return next;
509
530
  },
510
531
 
532
+ /**
533
+ * Marks a prototype client-facing or internal. Only client-facing is
534
+ * stored, so internal deletes the field and a prototype nobody marked is
535
+ * internal. Studio only.
536
+ */
537
+ async setAudience(actor: Person | null, prototype: unknown, audience: unknown): Promise<Audience> {
538
+ allow(actor, 'audience');
539
+ const [slug, value] = validAll<[string, Audience]>(
540
+ isPrototypeSlug(prototype)
541
+ ? { ok: true, value: prototype }
542
+ : { ok: false, problems: ['prototype: a prototype slug'] },
543
+ checkPrototypeAudience(audience),
544
+ );
545
+ if (value === 'client') await kv.hset(KEY.audiences, slug, 'client');
546
+ else await kv.hdel(KEY.audiences, slug);
547
+ return value;
548
+ },
549
+
550
+ /**
551
+ * Who a prototype is for, asked by the gate with no actor. Absent, or any
552
+ * value but `client`, is internal; a name that cannot be a prototype is
553
+ * internal without asking the store.
554
+ */
555
+ async audienceOf(prototype: string): Promise<Audience> {
556
+ return (await isClientFacing(prototype)) ? 'client' : 'internal';
557
+ },
558
+
559
+ /**
560
+ * What the index is built from: the view the actor gets (Client view for
561
+ * Studio with `viewAs: 'client'`) and every client-facing slug. The
562
+ * server keeps no list of internal ones: Studio's view reads the build's
563
+ * own list, which the gate refuses to a Client.
564
+ */
565
+ async visiblePrototypes(
566
+ actor: Person | null,
567
+ viewAs?: unknown,
568
+ ): Promise<{ view: PersonKind; clientFacing: string[] }> {
569
+ allow(actor, 'read');
570
+ const view = viewOf(actor, valid(checkViewAs(viewAs)));
571
+ const all = await kv.hgetall(KEY.audiences);
572
+ const clientFacing = Object.entries(all)
573
+ .filter(([slug, value]) => value === 'client' && isPrototypeSlug(slug))
574
+ .map(([slug]) => slug)
575
+ .sort();
576
+ return { view, clientFacing };
577
+ },
578
+
511
579
  /** Where a comment lives, for the CLI, which has an id and no prototype; null when the actor may not see it. */
512
580
  async locate(actor: Person | null, id: string): Promise<{ prototype: string; comment: Comment } | null> {
513
581
  allow(actor, 'read');
@@ -34,6 +34,12 @@ export const KEY = {
34
34
  /** Project settings, one field each: `access` is the default access length. */
35
35
  settings: `${PREFIX}settings`,
36
36
  prototypes: `${PREFIX}prototypes`,
37
+ /**
38
+ * Which prototypes are client-facing: field `<slug>`, value `client`. Only
39
+ * client-facing is stored; internal is the field's absence, and any other
40
+ * value reads as internal too.
41
+ */
42
+ audiences: `${PREFIX}audiences`,
37
43
  /**
38
44
  * The last thread number given on each prototype, only ever raised by HINCRBY: field
39
45
  * `<prototype>` counts client-facing threads, `<prototype>:internal` internal ones.
@@ -0,0 +1,35 @@
1
+ /**
2
+ * First path segments the hub owns, never a prototype: the walkthroughs,
3
+ * the review API, and the shared bundle.
4
+ */
5
+ export declare const RESERVED: readonly ['guide', 'api', 'assets'];
6
+ /**
7
+ * Everything built from `prototypes/<slug>/` lands under `/_p/<slug>/`, and
8
+ * Studio's list of every slug at `/_p/all.js`. `_p` can never be a slug: SLUG
9
+ * has no underscore.
10
+ */
11
+ export declare const PROTOTYPE_DIR = "_p";
12
+ export declare const ALL_FILE = "_p/all.js";
13
+ export declare const entryFile: (slug: string) => string;
14
+ /** Whether `name` can be a prototype's folder: kebab-case and not one of the hub's own paths. */
15
+ export declare const isPrototypeSlug: (name: unknown) => name is string;
16
+ /**
17
+ * Which prototype a request path belongs to, for the gate: the name a
18
+ * prototype path carries, or null for a hub path (`/`, or a first segment in
19
+ * HUB_ROOT). The first segment, decoded, must be one of those, `_p`, or a
20
+ * prototype slug; anything else (`_P`, `_p;x`, `_p.`, a full-width `_p`)
21
+ * belongs to `''`, refused like an internal prototype. A path under `/_p/`
22
+ * always belongs to one, so its name may be no slug at all (`all.js`), which
23
+ * no audience makes client-facing. A path that could mean more than one file
24
+ * belongs to `''` too.
25
+ */
26
+ export declare function prototypeOfPath(pathname: string): string | null;
27
+ /**
28
+ * Whether a built prototype's entry is there for this person, asked with a
29
+ * HEAD before it is imported. Not there: a 404 (the gate's answer for a
30
+ * prototype this person may not open, or none at all), or a 200 that is not
31
+ * JavaScript (the host's page for an entry that was never built). Any other
32
+ * answer (401, 500, 503) is an error, never "not there", so an outage never
33
+ * reads as nothing shared.
34
+ */
35
+ export declare function probeEntry(path: string, fetcher: typeof fetch): Promise<boolean>;