@milesroxas/design-hub 0.6.2 → 0.8.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 (56) hide show
  1. package/README.md +16 -6
  2. package/core/review/model.ts +124 -6
  3. package/core/review/policy.test.ts +103 -24
  4. package/core/review/policy.ts +43 -7
  5. package/core/review/service.test.ts +569 -33
  6. package/core/review/service.ts +272 -76
  7. package/core/review/store.ts +24 -4
  8. package/dist/core/review/model.d.ts +59 -4
  9. package/dist/core/review/model.js +98 -4
  10. package/dist/core/review/policy.d.ts +21 -2
  11. package/dist/core/review/policy.js +34 -2
  12. package/dist/core/review/service.d.ts +39 -11
  13. package/dist/core/review/service.js +237 -77
  14. package/dist/core/review/store.d.ts +17 -4
  15. package/dist/core/review/store.js +21 -3
  16. package/dist/scripts/bootstrap.d.ts +16 -14
  17. package/dist/scripts/bootstrap.js +56 -39
  18. package/dist/scripts/comments.d.ts +10 -2
  19. package/dist/scripts/comments.js +18 -7
  20. package/dist/scripts/lib/deploy.d.ts +12 -4
  21. package/dist/scripts/lib/deploy.js +47 -13
  22. package/dist/scripts/lib/vercel.d.ts +8 -2
  23. package/dist/scripts/lib/vercel.js +23 -9
  24. package/dist/scripts/people.d.ts +13 -26
  25. package/dist/scripts/people.js +68 -35
  26. package/dist/scripts/preflight.js +2 -2
  27. package/dist/scripts/share.d.ts +2 -3
  28. package/dist/scripts/share.js +18 -10
  29. package/dist/server/api.d.ts +6 -2
  30. package/dist/server/api.js +65 -24
  31. package/dist/server/fake-upstash.js +3 -2
  32. package/dist/server/local.js +2 -0
  33. package/dist/server/session.d.ts +25 -10
  34. package/dist/server/session.js +69 -52
  35. package/dist/server/upstash.js +4 -3
  36. package/dist/vercel/proxy.d.ts +5 -3
  37. package/dist/vercel/proxy.js +183 -157
  38. package/dist/vite/plugin.js +5 -5
  39. package/kit/prefs.ts +19 -2
  40. package/package.json +2 -2
  41. package/shell/review/Bar.tsx +97 -4
  42. package/shell/review/People.tsx +178 -45
  43. package/shell/review/Pins.tsx +39 -24
  44. package/shell/review/Review.tsx +113 -29
  45. package/shell/review/ThreadCard.tsx +25 -13
  46. package/shell/review/client.ts +64 -23
  47. package/shell/review/review.css +16 -2
  48. package/shell/review/view.test.ts +73 -1
  49. package/shell/review/view.ts +49 -3
  50. package/skills/miles-deploy/SKILL.md +44 -16
  51. package/skills/miles-design-hub/SKILL.md +5 -5
  52. package/skills/miles-new-feature/SKILL.md +1 -1
  53. package/skills/miles-review/SKILL.md +10 -6
  54. package/skills/miles-worktrees/SKILL.md +1 -1
  55. package/templates/conductor/settings.toml +1 -1
  56. package/templates/guide.md +1 -1
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # design-hub
2
2
 
3
- The Design Hub product as an npm package: the hub that lists and serves a project's prototypes, the review panel and its API, the password gate, the kit, the `design-hub` command and the `miles-*` skills. A project installs it and keeps only its prototypes, kit materials and docs; `npm create @milesroxas/design-hub` makes one.
3
+ The Design Hub product as an npm package: the hub that lists and serves a project's prototypes, the review panel and its API, the sign-in gate, the kit, the `design-hub` command and the `miles-*` skills. A project installs it and keeps only its prototypes, kit materials and docs; `npm create @milesroxas/design-hub` makes one.
4
4
 
5
5
  ```bash
6
6
  design-hub dev # the hub on http://localhost:<PORT>
@@ -64,17 +64,27 @@ A speculation rule in `shell/index.html` prefetches a prototype's page when its
64
64
 
65
65
  ## The walkthrough
66
66
 
67
- `/guide/<feature>/` is `docs/sprints/<feature>/guide.md`, rendered for reviewers who have the password but not the repo; `/guide/` alone opens the only guide, or lists them. The registry plugin lists the guides, so a new feature's walkthrough appears the moment the file exists (`design-hub guide <feature>` starts one from `templates/guide.md`). The Markdown stays the one source: a Vite plugin (`vite/markdown.ts`, the `?doc` import) compiles it at build time with `marked`, so nothing is parsed in the browser. It turns the first H1 into the title, every H2 and H3 into the contents rail, each image into a figure with its pixel size (no layout shift, lazy below the first), and `> [!NOTE]` quotes into callouts. A paragraph that starts `Controls → …` renders as a click path. Links to other Markdown files lose their href, since nothing serves them. The page reads at 16px on a 680px measure; screenshots and tables take the full 960px column, because a 1440px shot at 680px is unreadable. Two raw values: a screenshot wears a 1px inset outline at 10% (black on light, white on dark) and a callout a 6% ring (8% on dark), alphas rather than tokens because they composite on any surface the page is set on. The slug `guide` is the hub's (`design-hub new guide` refuses it). The page's **Open the prototype** button goes to the feature's sprint prototype, and every prototype of the feature answers with **Open the walkthrough** as the last row of Controls, under every group, in a new tab, so a reviewer reads and clicks side by side. Above it, on every prototype, **All prototypes** goes back to `/` in the same tab. A sheet inside the product was rejected: it would be modal over the thing under review, and testing aids never sit in the product chrome.
67
+ `/guide/<feature>/` is `docs/sprints/<feature>/guide.md`, rendered for reviewers who have a sign-in link but not the repo; `/guide/` alone opens the only guide, or lists them. The registry plugin lists the guides, so a new feature's walkthrough appears the moment the file exists (`design-hub guide <feature>` starts one from `templates/guide.md`). The Markdown stays the one source: a Vite plugin (`vite/markdown.ts`, the `?doc` import) compiles it at build time with `marked`, so nothing is parsed in the browser. It turns the first H1 into the title, every H2 and H3 into the contents rail, each image into a figure with its pixel size (no layout shift, lazy below the first), and `> [!NOTE]` quotes into callouts. A paragraph that starts `Controls → …` renders as a click path. Links to other Markdown files lose their href, since nothing serves them. The page reads at 16px on a 680px measure; screenshots and tables take the full 960px column, because a 1440px shot at 680px is unreadable. Two raw values: a screenshot wears a 1px inset outline at 10% (black on light, white on dark) and a callout a 6% ring (8% on dark), alphas rather than tokens because they composite on any surface the page is set on. The slug `guide` is the hub's (`design-hub new guide` refuses it). The page's **Open the prototype** button goes to the feature's sprint prototype, and every prototype of the feature answers with **Open the walkthrough** as the last row of Controls, under every group, in a new tab, so a reviewer reads and clicks side by side. Above it, on every prototype, **All prototypes** goes back to `/` in the same tab. A sheet inside the product was rejected: it would be modal over the thing under review, and testing aids never sit in the product chrome.
68
68
 
69
- ## Deploying, and the password
69
+ ## Deploying, and signing in
70
70
 
71
- `miles-deploy` owns the steps; this is what they rest on. `design-hub signin` starts `vercel login`'s device sign-in in the background and returns its link, so the user clicks instead of typing. `design-hub bootstrap --vercel <project>` links the project, connects it to the `origin` repo when Vercel can reach it, turns Vercel Authentication off and sets the env. `design-hub share` runs the pre-flight, then deploys: a push of a clean production branch when the project is connected to the repo (following the build for that commit), else `vercel deploy --prod`; then it requests the production URL signed out and fails unless the password page answers with `noindex`. Every path on the deployed site sits behind one password, enforced on the server by Vercel Routing Middleware (`vercel/proxy.ts`, exported as `createProxy` and default-exported by the project's one-line `proxy.ts`, which `vercel.json` names as `proxy.entrypoint`): a visitor who opens a deep link, `/sample-list/#/items` included, sees the password page first and lands on that link after. A client-side gate was rejected because the bundle and the state behind it would still download.
71
+ `miles-deploy` owns the steps; this is what they rest on. `design-hub signin` starts `vercel login`'s device sign-in in the background and returns its link, so the user clicks instead of typing. `design-hub bootstrap --vercel <project>` links the project, connects it to the `origin` repo when Vercel can reach it, turns Vercel Authentication off and sets the env. `design-hub share` runs the pre-flight, then deploys: a push of a clean production branch when the project is connected to the repo (following the build for that commit), else `vercel deploy --prod`; then it requests the production URL as a signed-out browser and fails unless the sign-in page answers with `noindex` and a link no store holds answers 404, which proves the review store is wired (503 means there is none, so nobody could sign in). Every path on the deployed site sits behind the gate, enforced on the server by Vercel Routing Middleware (`vercel/proxy.ts`, exported as `createProxy` and default-exported by the project's one-line `proxy.ts`, which `vercel.json` names as `proxy.entrypoint`). A client-side gate was rejected because the bundle and the state behind it would still download.
72
72
 
73
- The middleware reads two environment variables, set in the Vercel project for Production and Preview and never committed (`.env.example` names them): `GATE_PASSWORD`, the word a reviewer types, and `GATE_SECRET`, at least 32 random characters (`openssl rand -base64 32`) that sign the session cookie. With either missing the gate answers 503 on every path, so a misconfigured deploy never serves the prototypes open. The cookie is `__Host-`-prefixed, `HttpOnly`, `Secure`, `SameSite=Lax`, lasts 30 days, and its signature covers the password, so changing `GATE_PASSWORD` signs every visitor out. A wrong password waits 800ms before answering; add a Vercel Firewall rate-limit rule on `POST` for anything stronger. The password page ships a hash-based Content Security Policy with no `unsafe-inline`, plus `font-src 'self'` and `img-src 'self'`. It wears 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 page's title is the `siteName` the project's `proxy.ts` passes to `createProxy`.
73
+ Every person is named, and signs in with a one-time link that Studio makes in the review panel's People tab or with `design-hub people add`.
74
+
75
+ - **A link works once.** `GET /invite/<token>` shows who it is for and a Continue button, and uses nothing up, since mail and chat previews open links too. Continue is a same-origin `POST` that uses the link up, sets the session cookie and goes to `/`. The use is atomic: the store's delete is the claim, so of two requests with one link only the one whose delete removed it signs in. A used, expired or unknown link answers 404, as does a link for someone revoked or past their access end. An unused link lasts 14 days. The store keeps only a hash of each token (32 random bytes), so a read of the store signs nobody in.
76
+ - **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
+ - **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
+ - **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.
80
+ - **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`.
81
+ - **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
+
83
+ 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.
74
84
 
75
85
  ## Comments and people
76
86
 
77
- The password opens the site to view. To comment, a person needs their own invite link, made by Studio in the review panel's People tab or with `design-hub people invite`. Opening it shows who it is for and asks them to continue; the continue is a POST, so a mail scanner that opens every link never uses the invite. It sets a second signed cookie naming that person and their epoch, a counter a new link or a revoke bumps, which ends every session they hold on their next page load. The store keeps only a hash of each invite token, so a read of the store signs nobody in. A link lasts 14 days.
87
+ Every signed-in person can comment as themselves. The People tab lists each person with their team, kind and when their access ends, and says how links behave where Studio shares them.
78
88
 
79
89
  The panel (`shell/review/`) mounts on every prototype page in its own React root, so a prototype that throws never takes it down. A comment carries the prototype, the URL, every dial panel's values (`snapshotDials`), and the element it was pinned to as a selector path with an offset; Show state reopens the URL and sets the dials back. Pins draw over their elements and below the Controls panel. The API is one endpoint, `/api/review` (`server/api.ts`, reached on Vercel through the project's one-line `api/review.ts`, which also bundles the project's `checks.json` so triage runs on its thresholds): queries by GET, commands by POST with a JSON body, same-origin only. The rules (who may delete, what a valid comment is) live once, in `core/review/`, behind a small storage port: Upstash Redis over REST when deployed, a file in `.design-hub/review.json` under `design-hub dev`, where whoever runs the server is a local Studio person.
80
90
 
@@ -10,12 +10,43 @@ import { SLUG } from '../feature.ts';
10
10
  export const PERSON_KINDS = ['studio', 'client'] as const;
11
11
  export type PersonKind = (typeof PERSON_KINDS)[number];
12
12
 
13
+ /**
14
+ * Who a thread is for. Internal stays inside the studio; client-facing is
15
+ * read by everyone. Fixed when the thread is made: no op changes it.
16
+ */
17
+ const AUDIENCES = ['internal', 'client'] as const;
18
+ export type Audience = (typeof AUDIENCES)[number];
19
+
13
20
  /** How a comment is triaged: something broken, a design opinion, or the words. */
14
21
  export const KINDS = ['bug', 'taste', 'copy'] as const;
15
22
  export type Kind = (typeof KINDS)[number];
16
23
 
17
- /** How long an invite link signs its person in before Studio must issue a new one. */
18
- export const INVITE_DAYS = 14;
24
+ /** How long an unused sign-in link lasts. A link signs in one device, then stops working. */
25
+ export const LINK_DAYS = 14;
26
+
27
+ /**
28
+ * How long a person keeps access: three months, six months, or open-ended.
29
+ * The project sets a default; Studio can set it for one person.
30
+ */
31
+ export const ACCESS = ['3m', '6m', 'open'] as const;
32
+ export type Access = (typeof ACCESS)[number];
33
+ /** The project default when none is set. */
34
+ export const DEFAULT_ACCESS: Access = '3m';
35
+
36
+ const ACCESS_MONTHS: Record<Exclude<Access, 'open'>, number> = { '3m': 3, '6m': 6 };
37
+
38
+ /** When access given at `from` ends, as an ISO time, or null for open-ended. */
39
+ export function accessEnd(access: Access, from: Date): string | null {
40
+ if (access === 'open') return null;
41
+ // On the same day of the month, or the target month's last day when it is shorter (30 Nov + 3m is 28 Feb).
42
+ const end = new Date(from.getTime());
43
+ const day = end.getUTCDate();
44
+ end.setUTCDate(1);
45
+ end.setUTCMonth(end.getUTCMonth() + ACCESS_MONTHS[access]);
46
+ const last = new Date(Date.UTC(end.getUTCFullYear(), end.getUTCMonth() + 1, 0)).getUTCDate();
47
+ end.setUTCDate(Math.min(day, last));
48
+ return end.toISOString();
49
+ }
19
50
 
20
51
  export const LIMITS = {
21
52
  name: 80,
@@ -34,12 +65,19 @@ export type Person = {
34
65
  /** The group a person belongs to, shown beside their name: the studio, or the client's company. */
35
66
  team: string;
36
67
  kind: PersonKind;
68
+ /** Always null until email sign-in exists. */
69
+ email: string | null;
70
+ /** When their access ends (ISO time), or null for open-ended. Their sessions end with it. */
71
+ accessEndsAt: string | null;
37
72
  createdAt: string;
38
73
  revokedAt: string | null;
39
- /** Bumped on revoke and on a new invite, which signs out every session signed with the old one. */
74
+ /** Bumped on revoke and on sign out everywhere, which ends every session signed with the old one. */
40
75
  epoch: number;
41
76
  };
42
77
 
78
+ /** A one-time sign-in link, stored under the hash of its token and deleted when used. */
79
+ export type Link = { person: string; expiresAt: string };
80
+
43
81
  /** A comment's author as it was when they wrote it, so a revoked person's comments still read. */
44
82
  export type Author = Pick<Person, 'id' | 'name' | 'team'>;
45
83
 
@@ -78,8 +116,60 @@ export type Comment = {
78
116
  status: 'open' | 'resolved';
79
117
  resolvedBy: Author | null;
80
118
  triage: Triage | null;
119
+ /** The thread's audience. Set on the root when it is made and copied onto every reply; never changed. */
120
+ audience: Audience;
121
+ /**
122
+ * The thread's number on its prototype, from 1, copied onto every reply. Never reused, so a
123
+ * deleted or hidden thread moves no other number. 0 for a thread stored before numbers existed.
124
+ */
125
+ number: number;
81
126
  };
82
127
 
128
+ /**
129
+ * A stored comment as the rules read it. A record with no audience, or one
130
+ * that is not a known value, is internal: a missing field never shows a
131
+ * Client anything. A missing or broken number reads as 0, no number.
132
+ */
133
+ export function readComment(json: string): Comment {
134
+ const c = JSON.parse(json) as Comment;
135
+ const audience: Audience = c.audience === 'client' ? 'client' : 'internal';
136
+ const number = Number.isInteger(c.number) && c.number > 0 ? c.number : 0;
137
+ return { ...c, audience, number };
138
+ }
139
+
140
+ const isText = (v: unknown) => typeof v === 'string';
141
+ const isTextOrNull = (v: unknown) => v === null || typeof v === 'string';
142
+
143
+ /** What a stored profile must hold to be a person; anything else is no person at all. */
144
+ const PROFILE_RULES: [string, (v: unknown) => boolean][] = [
145
+ ['id', (v) => isText(v) && v !== ''],
146
+ ['name', isText],
147
+ ['team', isText],
148
+ ['kind', (v) => PERSON_KINDS.includes(v as PersonKind)],
149
+ ['email', isTextOrNull],
150
+ ['accessEndsAt', isTextOrNull],
151
+ ['createdAt', isText],
152
+ ];
153
+
154
+ /** Whether a stored profile (a person without revocation and epoch) is well formed. */
155
+ export function isProfile(v: unknown): v is Omit<Person, 'revokedAt' | 'epoch'> {
156
+ if (!v || typeof v !== 'object' || Array.isArray(v)) return false;
157
+ const o = v as Record<string, unknown>;
158
+ return PROFILE_RULES.every(([key, ok]) => ok(o[key]));
159
+ }
160
+
161
+ /**
162
+ * Whether someone may sign in at `at`: not revoked, and an access end that is
163
+ * open (null) or a parseable time still ahead. An access end that does not
164
+ * parse is no access.
165
+ */
166
+ export function hasAccess(p: Pick<Person, 'revokedAt' | 'accessEndsAt'>, at: Date): boolean {
167
+ if (p.revokedAt !== null) return false;
168
+ if (p.accessEndsAt === null) return true;
169
+ const end = Date.parse(p.accessEndsAt);
170
+ return Number.isFinite(end) && end > at.getTime();
171
+ }
172
+
83
173
  export const authorOf = (p: Person): Author => ({ id: p.id, name: p.name, team: p.team });
84
174
  export const isRoot = (c: Comment) => c.thread === c.id;
85
175
 
@@ -100,17 +190,45 @@ const text = (v: unknown, path: string, max: number, problems: string[]): string
100
190
  const fraction = (v: unknown) => typeof v === 'number' && Number.isFinite(v) && v >= 0 && v <= 1;
101
191
  const size = (v: unknown) => typeof v === 'number' && Number.isFinite(v) && v >= 0 && v < 100_000;
102
192
 
103
- export function checkPersonInput(input: unknown): Checked<Pick<Person, 'name' | 'team' | 'kind'>> {
193
+ const isAccess = (v: unknown): v is Access => ACCESS.includes(v as Access);
194
+ const ACCESS_PROBLEM = `access: one of ${ACCESS.join(', ')}`;
195
+
196
+ export function checkAccess(input: unknown): Checked<Access> {
197
+ return isAccess(input) ? { ok: true, value: input } : { ok: false, problems: [ACCESS_PROBLEM] };
198
+ }
199
+
200
+ export type PersonInput = Pick<Person, 'name' | 'team' | 'kind'> & { access: Access | null };
201
+
202
+ export function checkPersonInput(input: unknown): Checked<PersonInput> {
104
203
  const i = (input ?? {}) as Record<string, unknown>;
105
204
  const problems: string[] = [];
106
205
  const name = text(i.name, 'name', LIMITS.name, problems);
107
206
  const team = text(i.team, 'team', LIMITS.team, problems);
108
- // Most people invited are on the client's side; Studio is the deliberate choice.
207
+ // Most people added are on the client's side; Studio is the deliberate choice.
109
208
  const kind = i.kind ?? 'client';
110
209
  if (!PERSON_KINDS.includes(kind as PersonKind)) problems.push(`kind: one of ${PERSON_KINDS.join(', ')}`);
210
+ // Absent, the service picks: the project default for a Client, open-ended for Studio.
211
+ const access = i.access ?? null;
212
+ if (access !== null && !isAccess(access)) problems.push(ACCESS_PROBLEM);
111
213
  return problems.length
112
214
  ? { ok: false, problems }
113
- : { ok: true, value: { name, team, kind: kind as PersonKind } };
215
+ : { ok: true, value: { name, team, kind: kind as PersonKind, access: access as Access | null } };
216
+ }
217
+
218
+ /** A new thread's audience as asked: one of AUDIENCES, or null when none is given. */
219
+ export function checkAudience(input: unknown): Checked<Audience | null> {
220
+ if (input === undefined || input === null) return { ok: true, value: null };
221
+ return AUDIENCES.includes(input as Audience)
222
+ ? { ok: true, value: input as Audience }
223
+ : { ok: false, problems: [`audience: one of ${AUDIENCES.join(', ')}`] };
224
+ }
225
+
226
+ /** Whose view of the comments is asked for: a person kind, or null for the caller's own. */
227
+ export function checkViewAs(input: unknown): Checked<PersonKind | null> {
228
+ if (input === undefined || input === null) return { ok: true, value: null };
229
+ return PERSON_KINDS.includes(input as PersonKind)
230
+ ? { ok: true, value: input as PersonKind }
231
+ : { ok: false, problems: [`viewAs: one of ${PERSON_KINDS.join(', ')}`] };
114
232
  }
115
233
 
116
234
  export function checkBody(body: unknown): Checked<string> {
@@ -1,21 +1,23 @@
1
1
  import assert from 'node:assert/strict';
2
2
  import { test } from 'node:test';
3
- import type { Comment, Person, PersonKind } from './model.ts';
4
- import { type Action, can } from './policy.ts';
3
+ import type { Audience, Comment, Person, PersonKind } from './model.ts';
4
+ import { type Action, audienceFor, can, viewOf, visibleTo } from './policy.ts';
5
5
 
6
6
  const person = (id: string, kind: PersonKind, revokedAt: string | null = null): Person => ({
7
7
  id,
8
8
  name: id,
9
9
  team: kind === 'studio' ? 'Studio' : 'Acme',
10
10
  kind,
11
+ email: null,
12
+ accessEndsAt: null,
11
13
  createdAt: '',
12
14
  revokedAt,
13
15
  epoch: 0,
14
16
  });
15
17
 
16
- const thread = (author: string): Comment => ({
17
- id: 'c',
18
- thread: 'c',
18
+ const comment = (id: string, thread: string, author: string, audience: Audience): Comment => ({
19
+ id,
20
+ thread,
19
21
  author: { id: author, name: author, team: 'Acme' },
20
22
  body: 'x',
21
23
  createdAt: '',
@@ -24,37 +26,114 @@ const thread = (author: string): Comment => ({
24
26
  status: 'open',
25
27
  resolvedBy: null,
26
28
  triage: null,
29
+ audience,
30
+ number: 1,
27
31
  });
32
+ const thread = (author: string, audience: Audience = 'client') => comment('c', 'c', author, audience);
28
33
 
29
- // The rule table, one row per action: [Studio own, Studio other's, Client own, Client other's].
30
- const TABLE: [Action, boolean, boolean, boolean, boolean][] = [
31
- ['read', true, true, true, true],
32
- ['comment', true, true, true, true],
33
- ['edit', true, false, true, false],
34
- ['resolve', true, true, true, true],
35
- ['delete', true, true, true, false],
36
- ['triage', true, true, false, false],
37
- ['people', true, true, false, false],
34
+ // The rule table, one row per action and thread audience:
35
+ // [Studio own, Studio other's, Client own, Client other's].
36
+ const TABLE: [Action, Audience, boolean, boolean, boolean, boolean][] = [
37
+ ['read', 'client', true, true, true, true],
38
+ ['read', 'internal', true, true, false, false],
39
+ ['comment', 'client', true, true, true, true],
40
+ ['comment', 'internal', true, true, false, false],
41
+ ['edit', 'client', true, false, true, false],
42
+ ['edit', 'internal', true, false, false, false],
43
+ ['resolve', 'client', true, true, true, true],
44
+ ['resolve', 'internal', true, true, false, false],
45
+ ['delete', 'client', true, true, true, false],
46
+ ['delete', 'internal', true, true, false, false],
47
+ ['triage', 'client', true, true, false, false],
48
+ ['triage', 'internal', true, true, false, false],
49
+ ['people', 'client', true, true, false, false],
50
+ ['people', 'internal', true, true, false, false],
38
51
  ];
39
52
 
40
53
  const studio = person('s', 'studio');
41
54
  const client = person('c', 'client');
42
55
 
43
- for (const [action, studioOwn, studioOther, clientOwn, clientOther] of TABLE) {
44
- test(`${action}: Studio and Client, own and another's`, () => {
45
- assert.equal(can(studio, action, thread(studio.id)), studioOwn, 'Studio, own');
46
- assert.equal(can(studio, action, thread('someone')), studioOther, "Studio, another's");
47
- assert.equal(can(client, action, thread(client.id)), clientOwn, 'Client, own');
48
- assert.equal(can(client, action, thread('someone')), clientOther, "Client, another's");
56
+ for (const [action, audience, studioOwn, studioOther, clientOwn, clientOther] of TABLE) {
57
+ test(`${action} on a ${audience} thread: Studio and Client, own and another's`, () => {
58
+ assert.equal(can(studio, action, thread(studio.id, audience)), studioOwn, 'Studio, own');
59
+ assert.equal(can(studio, action, thread('someone', audience)), studioOther, "Studio, another's");
60
+ assert.equal(can(client, action, thread(client.id, audience)), clientOwn, 'Client, own');
61
+ assert.equal(can(client, action, thread('someone', audience)), clientOther, "Client, another's");
49
62
  });
50
63
 
51
- test(`${action}: nobody signed in and a revoked person may not`, () => {
64
+ test(`${action} on a ${audience} thread: nobody signed in and a revoked person may not`, () => {
52
65
  for (const kind of ['studio', 'client'] as const) {
53
66
  const gone = person('r', kind, '2030-01-01T00:00:00Z');
54
- assert.equal(can(gone, action, thread(gone.id)), false, `revoked ${kind}, own`);
55
- assert.equal(can(gone, action, thread('someone')), false, `revoked ${kind}, another's`);
67
+ assert.equal(can(gone, action, thread(gone.id, audience)), false, `revoked ${kind}, own`);
68
+ assert.equal(can(gone, action, thread('someone', audience)), false, `revoked ${kind}, another's`);
56
69
  }
57
- assert.equal(can(null, action, thread('someone')), false, 'null');
70
+ assert.equal(can(null, action, thread('someone', audience)), false, 'null');
58
71
  assert.equal(can(null, action), false, 'null, no subject');
59
72
  });
60
73
  }
74
+
75
+ test('with no thread, both kinds read and start one; only Studio triages and manages people', () => {
76
+ for (const action of ['read', 'comment'] as const) {
77
+ assert.equal(can(studio, action), true);
78
+ assert.equal(can(client, action), true);
79
+ }
80
+ for (const action of ['triage', 'people'] as const) {
81
+ assert.equal(can(studio, action), true);
82
+ assert.equal(can(client, action), false);
83
+ }
84
+ });
85
+
86
+ test('a reply is judged by its own author, and inside its thread’s audience', () => {
87
+ const root = thread(studio.id, 'client');
88
+ const mine = comment('r', 'c', client.id, 'client');
89
+ assert.equal(can(client, 'edit', root, mine), true);
90
+ assert.equal(can(client, 'delete', root, mine), true);
91
+ assert.equal(can(studio, 'edit', root, mine), false);
92
+ assert.equal(can(studio, 'delete', root, mine), true);
93
+ // A client-facing reply in an internal thread, or an internal reply in a client-facing one: never a Client's.
94
+ assert.equal(can(client, 'edit', thread(studio.id, 'internal'), mine), false);
95
+ assert.equal(can(client, 'read', root, comment('r', 'c', client.id, 'internal')), false);
96
+ });
97
+
98
+ test('a record without an audience is internal to the rules', () => {
99
+ const legacy = { ...thread(client.id), audience: undefined } as unknown as Comment;
100
+ assert.equal(can(client, 'read', legacy), false);
101
+ assert.equal(can(studio, 'read', legacy), true);
102
+ assert.deepEqual(visibleTo('client', [legacy]), []);
103
+ });
104
+
105
+ test('visibleTo: Studio sees everything; a Client, client-facing threads and their client-facing replies', () => {
106
+ const all = [
107
+ comment('i', 'i', 's', 'internal'),
108
+ comment('i1', 'i', 's', 'internal'),
109
+ comment('k', 'k', 'c', 'client'),
110
+ comment('k1', 'k', 's', 'client'),
111
+ comment('k2', 'k', 'c', 'client'),
112
+ // Nothing writes these, but a Client still never gets them.
113
+ comment('odd', 'k', 's', 'internal'),
114
+ comment('stray', 'i', 's', 'client'),
115
+ comment('orphan', 'gone', 'c', 'client'),
116
+ ];
117
+ assert.deepEqual(visibleTo('studio', all), all);
118
+ assert.deepEqual(
119
+ visibleTo('client', all).map((c) => c.id),
120
+ ['k', 'k1', 'k2'],
121
+ );
122
+ });
123
+
124
+ test('viewOf: Studio may narrow to a Client’s view; a Client is never widened', () => {
125
+ assert.equal(viewOf(studio), 'studio');
126
+ assert.equal(viewOf(studio, 'studio'), 'studio');
127
+ assert.equal(viewOf(studio, 'client'), 'client');
128
+ assert.equal(viewOf(client), 'client');
129
+ assert.equal(viewOf(client, 'studio'), 'client');
130
+ assert.equal(viewOf(null), 'client');
131
+ });
132
+
133
+ test('audienceFor: a Client’s thread is client-facing; Studio’s is internal unless asked', () => {
134
+ assert.equal(audienceFor(client, null), 'client');
135
+ assert.equal(audienceFor(client, 'internal'), 'client');
136
+ assert.equal(audienceFor(studio, null), 'internal');
137
+ assert.equal(audienceFor(studio, 'client'), 'client');
138
+ assert.equal(audienceFor(studio, 'internal'), 'internal');
139
+ });
@@ -1,19 +1,30 @@
1
- // Who may do what. Studio runs the review: it invites and revokes people,
1
+ // Who may do what. Studio runs the review: it adds and revokes people,
2
2
  // deletes any comment and corrects triage. A Client comments, replies, edits
3
- // and deletes what they wrote, and resolves or reopens any thread, because
4
- // clients work alongside others in their own organisation. A revoked person,
5
- // or a visitor with only the shared password, may do nothing here.
6
- import type { Comment, Person } from './model.ts';
3
+ // and deletes what they wrote, and resolves or reopens any client-facing
4
+ // thread, because clients work alongside others in their own organisation.
5
+ // An internal thread does not exist for a Client: every action on one is
6
+ // refused. A revoked person, or a visitor who is not signed in, may do
7
+ // nothing here.
8
+ import type { Audience, Comment, Person, PersonKind } from './model.ts';
7
9
 
8
10
  export type Action = 'read' | 'comment' | 'edit' | 'delete' | 'resolve' | 'triage' | 'people';
9
11
 
10
12
  /** Only what the rules read, so the browser's signed-in person (no epoch) is checked by the same rules. */
11
13
  type Actor = Pick<Person, 'id' | 'kind' | 'revokedAt'>;
12
14
 
13
- export function can(actor: Actor | null, action: Action, subject?: Comment): boolean {
15
+ /** Whether a comment reaches a Client. Only the exact value counts, so a record without one stays inside. */
16
+ const clientFacing = (c: Pick<Comment, 'audience'>) => c.audience === 'client';
17
+
18
+ /**
19
+ * `root` is the thread acted on, `subject` the comment in it when that is a
20
+ * reply (edit or delete one); without `subject`, the root is the subject.
21
+ * Without a root, the action is on no thread: listing, or a new thread.
22
+ */
23
+ export function can(actor: Actor | null, action: Action, root?: Comment, subject?: Comment): boolean {
14
24
  if (!actor || actor.revokedAt) return false;
15
25
  const studio = actor.kind === 'studio';
16
- const own = subject?.author.id === actor.id;
26
+ if (!studio && [root, subject].some((c) => c && !clientFacing(c))) return false;
27
+ const own = (subject ?? root)?.author.id === actor.id;
17
28
  switch (action) {
18
29
  case 'read':
19
30
  case 'comment':
@@ -28,3 +39,28 @@ export function can(actor: Actor | null, action: Action, subject?: Comment): boo
28
39
  return studio;
29
40
  }
30
41
  }
42
+
43
+ /**
44
+ * The view a person gets: their own kind, or a narrower one they ask for.
45
+ * Studio may look as a Client does (Client view); a Client asking for
46
+ * Studio's still gets a Client's, so the view is never wider than the person.
47
+ */
48
+ export function viewOf(actor: Pick<Person, 'kind'> | null, viewAs?: PersonKind | null): PersonKind {
49
+ return actor?.kind === 'studio' && viewAs !== 'client' ? 'studio' : 'client';
50
+ }
51
+
52
+ /**
53
+ * The comments a view may see. Studio sees all. A Client sees a client-facing
54
+ * thread and its client-facing replies; a reply whose thread is not among
55
+ * them is not seen either.
56
+ */
57
+ export function visibleTo(viewAs: PersonKind, comments: Comment[]): Comment[] {
58
+ if (viewAs === 'studio') return comments;
59
+ const roots = new Set(comments.filter((c) => c.thread === c.id && clientFacing(c)).map((c) => c.id));
60
+ return comments.filter((c) => clientFacing(c) && roots.has(c.thread));
61
+ }
62
+
63
+ /** A new thread's audience: a Client's is always client-facing; Studio's is internal unless Studio asks otherwise. */
64
+ export function audienceFor(actor: Pick<Person, 'kind'>, asked: Audience | null): Audience {
65
+ return actor.kind === 'studio' ? (asked ?? 'internal') : 'client';
66
+ }