@plitzi/sdk-server 0.38.14 → 0.38.16

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 (47) hide show
  1. package/CHANGELOG.md +171 -0
  2. package/README.md +68 -6
  3. package/dist/core/auth/createAuth.d.ts +5 -0
  4. package/dist/core/auth/createAuth.js +5 -0
  5. package/dist/core/auth/csrf.d.ts +25 -0
  6. package/dist/core/auth/csrf.js +34 -32
  7. package/dist/core/auth/identity.d.ts +4 -0
  8. package/dist/core/auth/identity.js +1 -0
  9. package/dist/core/createServer.js +4 -0
  10. package/dist/core/freePort.d.ts +4 -0
  11. package/dist/core/freePort.js +4 -4
  12. package/dist/core/http/stages/authRoutes.js +3 -0
  13. package/dist/core/http/stages/crossSiteWrites.d.ts +23 -0
  14. package/dist/core/http/stages/crossSiteWrites.js +44 -0
  15. package/dist/core/http/stages/crossSiteWrites.test.d.ts +1 -0
  16. package/dist/core/http/stages/exchangeRoute.js +2 -0
  17. package/dist/core/server/fleet/link.d.ts +1 -1
  18. package/dist/core/server/fleet/stores.js +1 -1
  19. package/dist/core/services/registry.js +2 -0
  20. package/dist/core/unusedPort.d.ts +7 -3
  21. package/dist/core/unusedPort.js +33 -15
  22. package/dist/functions-api.d.ts +5 -2
  23. package/dist/index.d.ts +2 -0
  24. package/dist/index.js +2 -1
  25. package/dist/modules/actions/tasks/realtime.js +1 -1
  26. package/dist/modules/authoringHost/index.d.ts +49 -0
  27. package/dist/modules/authoringHost/index.js +113 -0
  28. package/dist/modules/authoringHost/index.test.d.ts +1 -0
  29. package/dist/modules/functions/contract.d.ts +5 -2
  30. package/dist/modules/project/serveProject.js +4 -1
  31. package/dist/modules/realtime/hub.d.ts +7 -2
  32. package/dist/modules/realtime/hub.js +8 -4
  33. package/dist/modules/realtime/index.js +14 -7
  34. package/dist/modules/realtime/message.d.ts +3 -0
  35. package/dist/modules/realtime/message.js +5 -0
  36. package/dist/modules/realtime/retained.d.ts +24 -0
  37. package/dist/modules/realtime/retained.js +47 -0
  38. package/dist/modules/realtime/retained.test.d.ts +1 -0
  39. package/dist/modules/runtime/stages.d.ts +4 -1
  40. package/dist/modules/ssr/spaceDocument.js +5 -1
  41. package/package.json +3 -3
  42. package/skills/plitzi-authoring/SKILL.md +1 -1
  43. package/skills/plitzi-authoring/reference/index.md +3 -2
  44. package/skills/plitzi-authoring/reference/plugin-reach.md +91 -0
  45. package/skills/plitzi-authoring/reference/plugins.md +15 -31
  46. package/skills/plitzi-authoring/reference/realtime.md +11 -0
  47. package/skills/plitzi-authoring/reference/testing.md +3 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,176 @@
1
1
  # @plitzi/sdk-server
2
2
 
3
+ ## 0.38.16
4
+
5
+ ### Patch Changes
6
+
7
+ - 9cfdccb: ## Security
8
+
9
+ - **A site's credential reads nothing of the space over MCP** (`@plitzi/sdk-mcp`): the `render` token every published
10
+ page embeds — and a self-hosting `host` key — resolved to a grant naming the space, and the MCP served every read
11
+ under it: the unpublished draft, the change history with who made each change and every value before and after, the
12
+ functions' source, the space's private data, its action documents and connectors. Only an `agent` grant attaches a
13
+ space now; any other is a connection with no space (`plitzi_render` and the public guides), told so in the words
14
+ `NO_SPACE_ATTACHED` already uses. A deployment whose `getGrant` answered other scopes for reading must issue agent
15
+ grants for them.
16
+
17
+ ## Agents
18
+ - **`plitzi space watch`** (`@plitzi/cli`): the space read again on every save of `src/space/`, `src/plugins/`,
19
+ `src/data/` or `public/data/`, and only what changed said — what the save did to the space element by element, the
20
+ findings and warnings it brought and fixed (one that only moved down its file is the same one), a save that changed
21
+ nothing, or that the space stopped authoring and why. `--json` is one event a line (`ready`, `pass`, `refused`,
22
+ `error`), for an agent to run in the background instead of `author` and `space lint` after every edit. Each pass reads
23
+ the space in a process of its own (`space watch-pass`, hidden). `space lint`'s reading is `spaceFindings`, shared.
24
+ - **A space's activity, followed** (`@plitzi/sdk-shared`, `@plitzi/sdk-mcp`, `@plitzi/cli`): what happened on a space
25
+ after a cursor — its draft changed (a person in the builder, an agent, the autofix), a version went out, a server
26
+ action failed or was refused — and, with nothing yet, waited for, up to 50 s. One vocabulary,
27
+ `@plitzi/sdk-shared/activity` (`SpaceActivity`, `SpaceActivityPage`, `activityLine`, `isSpaceActivityPage`, the
28
+ limits); the reader's own writes left out and counted (`skippedMine`), `mine` keeps them.
29
+ - **`plitzi_activity { after, wait, limit, mine }`** (`@plitzi/sdk-mcp`), on the new `getActivity` adapter
30
+ (`SSRAdapters`). The listing budget is 78k (was 77k) for it.
31
+ - **`plitzi space activity [--follow] [--after <cursor>] [--mine] [--limit <n>] [--json]`** (`@plitzi/cli`), over
32
+ the platform's `GET /spaces/:spaceId/activity`; `--follow` stays, one page a line with `--json`, and asks again
33
+ when the platform does not answer.
34
+ - **The people in the builder see the agent work** (`@plitzi/sdk-server`, `@plitzi/sdk-shared`, `@plitzi/sdk-mcp`,
35
+ `@plitzi/plitzi-builder`): an agent grant carries the application the member connected (`Grant.client`,
36
+ `StoredSpaceToken.client`, `SSRGrant.client`), and every MCP write `SSRWriteContext.client` — the history's
37
+ `client` for an agent, which was never set. A collaborator may be an agent (`SubscriptionCollaborator.agent`): the
38
+ builder draws it as a robot, names it `Claude · for ana` (`collaboratorTitle`) in the header, on the canvas and in
39
+ its notices. The deployment announces it — Plitzi's joins it on a write, selects what it changed, and lets it go
40
+ after a minute of nothing. `activityLine` names it the same way (`Claude for ana over the MCP, …`), so
41
+ `plitzi space activity` says which application wrote.
42
+ - A tool may declare `documents: false` (`ToolSpec`): the host loads none of the space for it, and passes the call's
43
+ abort signal through `ToolContext.activity`.
44
+
45
+ ## Authoring
46
+ - **A file that does not parse is said at its line under any loader** (`@plitzi/sdk-authoring`): `moduleProblem` read
47
+ the first line of the error, and an esbuild transform (tsx, vitest) puts only `Transform failed with 1 error:` there
48
+ — the file, line and what is wrong are on the next. A line of the message that points at a file of the project is
49
+ now the problem (`src/space/hero.ts:139: Expected "}" but found ";"`), the project's root matched as given and as it
50
+ is on disk (`/var/…` and `/private/var/…` on macOS).
51
+
52
+ ## Testing
53
+ - **`unusedPort` is chosen where the system never hands one out** (`@plitzi/sdk-server`): it answered a port the system
54
+ had just handed out (`listen(0)`), from the ephemeral range every outgoing connection takes its local port from — so
55
+ another worker's request could take it before the test listened, and CI failed `runtime.test.ts` with `EADDRINUSE`
56
+ (the page server then ends the process). It is a free port below that range now, at random, checked first.
57
+
58
+ ## Docs
59
+ - **A self-hosted runtime's endpoints go in `data`**, as 0.38.15 moved them: `docs/en/runtimes.md`, the
60
+ `10-runtime` example and the website still put `served.stage` in `preAuth`, before the cross-site guard.
61
+ - New: `docs/en/activity.md`; `space watch` in `docs/en/agent-tooling.md`'s loop; the CLI README, the CLI skill, the
62
+ generated project's `AGENTS.md`, the MCP guide and README.
63
+
64
+ - Updated dependencies [9cfdccb]
65
+ - @plitzi/plitzi-sdk@0.38.16
66
+ - @plitzi/sdk-shared@0.38.16
67
+
68
+ ## 0.38.15
69
+
70
+ ### Patch Changes
71
+
72
+ - 6cdd5cf: ## Security
73
+
74
+ - **A write another site caused is refused, cookie or none** (`@plitzi/sdk-server`, `@plitzi/sdk-shared`): the page
75
+ server guarded nothing it answers past `/auth` — a server action (`/_action`), a realtime publish, a space's `/fn/`
76
+ route, its runtime's endpoints, the deployment's own `data` stages, the adapter-only `loginPath`, `logoutPath` and
77
+ `exchangePath`. A plain `text/plain` POST from any page open in the same browser ran them, with the visitor's session
78
+ cookie when there was one (`SameSite=None` off this machine) and, in a project nobody signs in to, as whoever holds
79
+ the server's own credentials. Every unsafe request a browser says another site caused (`Sec-Fetch-Site: cross-site`,
80
+ or a foreign `Origin`) is now refused `403 reason: 'foreign'`, saying how to allow it: `crossSiteWrites.origins`
81
+ (with `auth`, `identity.platformOrigins` too) and `crossSiteWrites.paths` for a form other sites post to by design.
82
+ `Authorization`, and callers that are not browsers — webhooks, scripts — pass as before. One rule for this and the
83
+ sign-in check (`crossSiteRequest`, `csrf.ts`). A self-hosted runtime's endpoints now sit where the platform forwards a
84
+ space's — after the auth chain and this guard (`data`, was `preAuth`).
85
+
86
+ ## Testing
87
+ - **`page check` and `page shot` anywhere the project is served** (`@plitzi/cli`): `--url <origin>` for a second server
88
+ of it, staging or a deploy, instead of `npm start`'s port; `page check --space <module>` holds the pages to that space
89
+ instead of the project's — an agent's page — authored with `authorIsolated`.
90
+ - **A route with a query is checked as its page** (`@plitzi/cli`): `page check "/?v=2"` matched the query as part of
91
+ the path, found no page, and checked the space's "not found" page in its place.
92
+
93
+ - **What an element that chooses its children draws is checked** (`@plitzi/sdk-authoring`, `@plitzi/cli`): with
94
+ `choosesChildren`, the page checks owed none of its children — and checked none of them either: a dashboard drawing
95
+ three panels reported `checked: 1`. Each child it may draw, and what is inside one under no condition of its own,
96
+ now carries `shownWith` (the child it comes with) on its handle: once that child is on screen it and everything
97
+ named in it are owed like the rest of the page, and `checked` counts them. `onScreenIfChosen(handles, page)` lists
98
+ them.
99
+ - **A page that met a server error is looked at once more** (`@plitzi/cli`): `page check` and `verify` failed a page
100
+ for a `500` from somebody else's service having a bad second (`/fn/<space>/weather`), and passed on the next run with
101
+ nothing changed. A page whose requests got a `5xx` is checked again once; its report is the second look, and says
102
+ what failed the first time (`retriedAfter`). A `4xx` fails the same way twice, and is never retried.
103
+
104
+ ## Plugins
105
+ - **`useNotify`** (`@plitzi/plitzi-sdk`): a plugin shows the page's notifications — `notify('Deleted 79 recordings', {
106
+ appearance: 'danger' })` — the same toasts an `addNotification` step shows, in the space's theme and `notifications`
107
+ look, with no trigger, flow or `window` event of the space's to wire. The step's vocabulary (`NOTIFICATION_PLACEMENTS`,
108
+ `NOTIFICATION_APPEARANCES`, `NOTIFICATION_DEFAULTS`) is one list in `@plitzi/sdk-shared`, read by both.
109
+ - **`appearance: 'danger'` looks like one** (`@plitzi/plitzi-sdk`): it reached the toast library as a type it does not
110
+ know, so a danger notification showed neither the error icon nor the colour `notifications.danger` sets.
111
+ A value a notification does not take — from a flow, or a plugin in plain JavaScript — is set aside by name and said
112
+ in the console, rather than shown as the default in silence (`readNotificationOptions`, `@plitzi/sdk-shared`).
113
+ - **`useServerAction`** (`@plitzi/plitzi-sdk`, `@plitzi/sdk-authoring`, `@plitzi/sdk-interactions`,
114
+ `@plitzi/sdk-server`): a plugin runs one of the space's server actions, awaited —
115
+ `useServerAction<typeof habitDone>('habits-done')({ id })` answers `{ ok, output }` or `{ ok: false, reason, error }`
116
+ — through the `runServerAction` step itself: the same access, refusals, session handling and dev-tools entry.
117
+ `defineAction` keeps the literal types of its `call` way in, so the input is typed by the fields it declares (the
118
+ required ones required); `taskAction` types both ends from the task's `run`, and `FunctionTask<T, R>` takes what
119
+ `run` answers. `CallInputOf` / `CallOutputOf` read them. One operation is one action, never a `case` in one route.
120
+ What a run answers is typed (`ServerActionStatus`): a status the server never uses reads as a run that did not
121
+ complete, never as one that did.
122
+ The key those types ride under (`CALL_TYPES`) is exported, by `@plitzi/sdk-shared` and `@plitzi/sdk-authoring` with
123
+ `TypedActionEntry`, `CallInputOf` and `CallOutputOf`: a package that emits declarations could not write the type of an
124
+ action it exports (`TS4023` on every `export const actions = [defineAction(…)]`).
125
+ - **A plugin is drawn on the server first** (docs): a preference per device belongs in kept state (`keepState`,
126
+ `paintedState`) as a bound prop, never read from `localStorage` while rendering — React discards the whole tree on the
127
+ mismatch, and only in the browser of whoever saved something. `@plitzi/plitzi-ui` is not the page's: a plugin
128
+ importing it bundles its own copy, with its own contexts and its own look. The authoring skill's `plugin-reach.md`
129
+ says what a plugin says and to whom: a notification, another element (an event and the space's flow), a server
130
+ action, shared state, other pages.
131
+
132
+ ## Realtime
133
+ - **A channel that retains** (`@plitzi/sdk-shared`, `@plitzi/sdk-server`, `@plitzi/sdk-elements`): declared
134
+ `retain: true` (with `publish: 'server'`, which authoring requires), the server keeps the latest message of each type
135
+ on a topic — said by `ctx.publish` or a flow's `realtime.publish` — and hands them to every page that joins, marked
136
+ `retained`. A page reads them as `<channel>.retained.<type>`, a plugin as `useChannel(topic).retained`, the newest of
137
+ a type holding whichever order they arrive in; `null` forgets a type. Kept in the store the actions' `kv` uses (beside
138
+ the grants, by compare-and-swap), so every replica hands out the same; a topic keeps at most 64 types and 512 KB, and
139
+ a publish past that is refused before anything is sent. State every screen shares is one publish and one binding —
140
+ no kv key, initial read or copy in `state` of the project's own. The fleet store `realtime.grants` is now
141
+ `realtime.kv`.
142
+ - **The MCP writes every field a channel takes** (`@plitzi/sdk-mcp`): `patchSettings`'s channel had no `grant` — which
143
+ the guide taught — nor `retain` or the limits, so an agent could not declare a private channel at all. All are there
144
+ now, and the guide says what `retain` is for and that `channel_<id>.retained` holds it.
145
+
146
+ ## Authoring
147
+ - **`plitzi explain` knows every `@plitzi` package installed** (`@plitzi/cli`): a name that was not
148
+ `@plitzi/sdk-authoring`'s (`createServer`, `createJsonAdapters`, `useChannel`) was answered as the project's own code,
149
+ to `grep` in `src/`. It is read from the published types of every one installed, through their re-exports and entry
150
+ points (`@plitzi/sdk-server/handlers`), and a name two packages export — `createServer` is sdk-server's and sdk-mcp's
151
+ — is answered with both.
152
+
153
+ - **A space module somebody else wrote, authored where it reaches nothing** (`@plitzi/sdk-authoring`):
154
+ `authorIsolated(file, { timeoutMs })` of `@plitzi/sdk-authoring/node` runs `authorSpace` on it in a process Node's
155
+ permission model holds to reading the module's folder and its packages — no file written, no process started, no
156
+ variable of the caller's environment — kills one that runs too long, and validates what it answers again, so a forged
157
+ answer gains nothing. A refusal comes back as `authorSpace` says it, with the problems as data.
158
+ - **Pages an agent writes, served** (`@plitzi/sdk-server`): `createAuthoringHost({ dir, frameAncestors })` serves each
159
+ space it is handed at an address of its own (`put(space, { id }) → /?__pt=<id>`) as a draft of its one space, kept in
160
+ `dir` across restarts; `drop(id)` forgets one, and anything else answers `404` saying where the pages are.
161
+ - **A space is chosen by host or credential** (`@plitzi/sdk-server`, docs): `getSpaceDeployment` is asked on every
162
+ request, and what a page fetches after it carries nothing of its address but the host — a space chosen by the page's
163
+ query or path lost everything it asked for, and `/_plitzi/space/<hash>.json` answered a bare `404`. The contract and
164
+ the README say so (the README offered "by path prefix"), and that `404` says why.
165
+
166
+ - **`plitzi explain on` says how to read what a trigger carries** (`@plitzi/sdk-authoring`): its doc sat above a
167
+ helper, so `explain` printed only the signature. It now leads with `[named('picked', on('onPick')), …('{{ picked.seat
168
+ }}')]`, and the CLI skill's plugin section says the same.
169
+
170
+ - Updated dependencies [6cdd5cf]
171
+ - @plitzi/plitzi-sdk@0.38.15
172
+ - @plitzi/sdk-shared@0.38.15
173
+
3
174
  ## 0.38.14
4
175
 
5
176
  ### Patch Changes
package/README.md CHANGED
@@ -366,8 +366,13 @@ createServer({ adapters: { ...spaces.adapters, getOfflineData } });
366
366
  **Resolvers are an ordered list**, and the order is the policy. Each returns a resolution, a refusal, or nothing —
367
367
  and the difference between the last two is the point: a refusal ENDS the chain, so a request that tried to act for
368
368
  a space and failed is never quietly served as an anonymous visitor of whatever else that host resolves to. Three
369
- are built in and a fourth is `(req) => …` of your own, which is how a deployment that identifies tenants by header,
370
- by path prefix or by a table nobody else has still gets everything below.
369
+ are built in and a fourth is `(req) => …` of your own, which is how a deployment that identifies tenants by a header
370
+ its proxy sets or by a table nobody else has still gets everything below.
371
+
372
+ **A space is chosen by host or credential, never by the page's path or query.** `getSpaceDeployment` is asked on every
373
+ request, and what a page fetches after it — `/_plitzi/space/<hash>.json`, `/_action`, `/fn/…`, `/_realtime` — carries
374
+ nothing of the page's address but its host: a space chosen by `?space=` or `/s/<id>/` renders its first page and then
375
+ loses everything it asks for. Many spaces on one server are a sub-domain each (`wildcardSubdomain`).
371
376
 
372
377
  | Built in | What it is |
373
378
  |---|---|
@@ -391,6 +396,39 @@ a single-process deployment. `invalidate.resolution(host)` and `invalidate.domai
391
396
  untrue, which matters the moment an owner edits a domain list: until then the old framing policy stands, and a TTL
392
397
  is not a security boundary.
393
398
 
399
+ ## Pages an agent writes (`createAuthoringHost`)
400
+
401
+ A product where an agent designs the screen — a dashboard's panel, a page a visitor asks for — authors a space module
402
+ per page and needs it served with the quality of a project's, without trusting what the module does. Two pieces:
403
+
404
+ ```ts
405
+ import { authorIsolated } from '@plitzi/sdk-authoring/node';
406
+ import { createAuthoringHost } from '@plitzi/sdk-server';
407
+
408
+ const host = createAuthoringHost({ dir: 'state/pages', port: 8091, tls, frameAncestors: ['https://localhost:8080'] });
409
+ await host.server.listen(8091, '0.0.0.0');
410
+
411
+ const result = await authorIsolated('tmp/pages/weather.ts'); // its own process: reads the module and its packages, nothing else
412
+ if (result.ok) {
413
+ const { path } = host.put(result.space, { id: 'weather' }); // `/?__pt=weather`, kept in state/pages/weather.json
414
+ } else {
415
+ reply(result.message); // a refusal reads as authorSpace's: every problem, located
416
+ }
417
+ ```
418
+
419
+ - **`authorIsolated`** authors the module in a process Node's permission model holds to reading the module's folder and
420
+ the packages it imports: no file written, no process or worker started, no variable of the caller's environment. A
421
+ module that runs too long is killed (`timeoutMs`), and what it answers is validated again in the caller, so one that
422
+ forges its answer gains nothing. Before Node 25 the permission model leaves the network open: serve the result on an
423
+ origin of its own, never the app's.
424
+ - **`createAuthoringHost`** serves each page as a draft of its one space, at the address `put` answers — the way a page
425
+ server tells many spaces apart on one host (a space is chosen by host or credential, never by path). The page
426
+ arrives with its whole space, navigation is the browser's, and a reload that lost the address finds it in the draft's
427
+ cookie. So a page here is data and its look: no server provider, action, function or channel of its own. Anything
428
+ but a page it holds answers `404`, saying where they are.
429
+ - **Checked like a project's page:** `plitzi page check "/?__pt=weather" --url https://localhost:8091 --space
430
+ tmp/pages/weather.ts` — the CLI's whole check (elements on screen, hydration, console, contrast) against that module.
431
+
394
432
  ## JSON adapters (offline mode)
395
433
 
396
434
  `createJsonAdapters` provides a ready-made adapter set that reads a space from local JSON files, useful for offline mode, integration tests, and static deployments.
@@ -412,10 +450,10 @@ Beside the page adapters it offers `getSchema` and `getStyle`, read from the sam
412
450
  path, or a function that may answer one — `saveSchema` and `saveStyle`, each writing its document back into the file. So an MCP server
413
451
  ([`@plitzi/sdk-mcp`](../mcp/README.md#adapters)) can run over it, with a `getGrant` of yours beside it.
414
452
 
415
- In a test, listen on `await unusedPort()`: a port the system has just handed out, never a fixed number — one in the
416
- system's ephemeral range can be taken by any outgoing connection of a test running beside it, and the listen fails with
417
- `EADDRINUSE` on a run with nothing wrong. (`freePort(8080)` is the development server's: the next free one from a port
418
- people expect.)
453
+ In a test, listen on `await unusedPort()`: a free port below the system's ephemeral range, never a fixed number nor
454
+ one the system hands out (`listen(0)`) — a port of that range can be taken by any outgoing connection of a test running
455
+ beside it between the moment it is chosen and the listen, which fails with `EADDRINUSE` on a run with nothing wrong.
456
+ (`freePort(8080)` is the development server's: the next free one from a port people expect.)
419
457
 
420
458
  ### `JsonAdaptersConfig`
421
459
 
@@ -1251,6 +1289,30 @@ There is nothing to configure: the secret, the cookie scope and the origins all
1251
1289
  `createAuth`. Turn it off entirely with `csrf: false`. Outside this package, `createCsrfMiddleware` from
1252
1290
  `@plitzi/sdk-server/handlers` applies the same check to your own routes.
1253
1291
 
1292
+ #### The page server's own writes
1293
+
1294
+ Everything a page server answers past its self-gating flows — server actions (`/_action`), realtime publishes, a
1295
+ space's `/fn/` routes, its runtime's endpoints, your own `data` stages, and the adapter-only `loginPath`, `logoutPath`
1296
+ and `exchangePath` — refuses a write that a browser says **another site caused**, with `403` and `reason: 'foreign'`.
1297
+ **Whether or not a session cookie came with it**: a server holding credentials of its own (a token for somebody's
1298
+ calendar, an API key) or a tool nobody signs in to acts for whoever reaches it, and a plain `text/plain` POST from any
1299
+ page open in the same browser reaches it without a preflight.
1300
+
1301
+ The same two headers decide, under the same rules: what passes is a safe method, anything with `Authorization`, a
1302
+ caller that is not a browser (a webhook, `curl`), a page of this site (`same-origin`, `same-site`), and what you name:
1303
+
1304
+ ```ts
1305
+ createServer({
1306
+ adapters,
1307
+ crossSiteWrites: {
1308
+ // Exactly as a browser sends them. With `auth`, `identity.platformOrigins` are added for you.
1309
+ origins: ['https://app.example.com'],
1310
+ // A form other sites post to by design.
1311
+ paths: path => path === '/fn/newsletter'
1312
+ }
1313
+ });
1314
+ ```
1315
+
1254
1316
  ### `SSRUser`
1255
1317
 
1256
1318
  What a rendered page sees, so a schema can restrict pages to signed-in visitors — the SDK reads `authenticated` and
@@ -195,6 +195,11 @@ export declare const createAuth: (config: AuthConfig) => {
195
195
  pageAuth: Omit<ServerAuth, "sessionHintCookie">;
196
196
  /** The naming this was built with, so a page server takes it from here instead of being told a second time. */
197
197
  cookieConfig: SSRAuthCookie | undefined;
198
+ /**
199
+ * The sites this deployment's own pages are served from (`identity.platformOrigins`): a page server counts their
200
+ * writes as its own (`crossSiteWrites`), as the sign-in check here does.
201
+ */
202
+ platformOrigins: string[];
198
203
  /**
199
204
  * Cross-site request forgery: issuing tokens, writing the readable cookie, and the check. `undefined` when the
200
205
  * deployment turned it off. The `/auth` routes below already enforce it.
@@ -134,6 +134,11 @@ var createAuth = (config) => {
134
134
  /** The naming this was built with, so a page server takes it from here instead of being told a second time. */
135
135
  cookieConfig: config.cookie,
136
136
  /**
137
+ * The sites this deployment's own pages are served from (`identity.platformOrigins`): a page server counts their
138
+ * writes as its own (`crossSiteWrites`), as the sign-in check here does.
139
+ */
140
+ platformOrigins: config.identity?.platformOrigins ?? [],
141
+ /**
137
142
  * Cross-site request forgery: issuing tokens, writing the readable cookie, and the check. `undefined` when the
138
143
  * deployment turned it off. The `/auth` routes below already enforce it.
139
144
  */
@@ -56,6 +56,31 @@ export declare const carrierOf: (req: {
56
56
  cookies?: unknown;
57
57
  body?: unknown;
58
58
  }, method?: string | undefined) => CsrfCarrier;
59
+ /**
60
+ * Did this request come from a site this deployment does not recognise — `allowed` naming the origins it does?
61
+ *
62
+ * This is what protects signing in, where there is no session to bind a token to and no cookie to look for, and
63
+ * every write a page server answers, cookie or none (`crossSiteWritesStage`). It rests on two headers a page CANNOT
64
+ * set — the browser attaches both, and script may not override either:
65
+ *
66
+ * - **`Sec-Fetch-Site`** is the browser's own account of where the request came from, and is believed first.
67
+ * Anything but `cross-site` (`same-origin`, `same-site`, or `none` for a typed URL) is this deployment's own.
68
+ * The browser works that out with the real public suffix list, which is why it is worth more than anything
69
+ * derivable here.
70
+ * - **`Origin`** is the fallback, for a browser too old to send the above — Safari only did from 16.4. Matched
71
+ * **exactly**, against this host or an origin the deployment named.
72
+ *
73
+ * That exactness is deliberate and was a bug once: this compared *registrable domains*, last-two-labels, the
74
+ * same helper that scopes the session cookie. It has no public suffix list, so on a deployment at `acme.co.uk`
75
+ * every other `.co.uk` in the world counted as the same site and could sign a visitor in. Guessing where a
76
+ * domain boundary falls is not something to do in a security decision — a sibling sub-domain that needs to be
77
+ * trusted is one line in `allowedOrigins`, which `createAuth` already fills from `identity.platformOrigins`.
78
+ *
79
+ * **Neither header means this is not a browser**, and a client that is not a browser cannot be made to forge
80
+ * anything: there is no victim's session sitting in it. That is what keeps every API client, mobile app and
81
+ * script signing in with nothing extra to send.
82
+ */
83
+ export declare const crossSiteRequest: (carrier: CsrfCarrier, allowed?: (origin: string) => boolean) => boolean;
59
84
  export declare const createCsrf: (config: CsrfConfig) => {
60
85
  issue: (sessionToken?: string) => string;
61
86
  /** The name the cookie lands under, for a client that reads it by hand. */
@@ -83,40 +83,42 @@ var originHost = (origin) => {
83
83
  return;
84
84
  }
85
85
  };
86
+ /**
87
+ * Did this request come from a site this deployment does not recognise — `allowed` naming the origins it does?
88
+ *
89
+ * This is what protects signing in, where there is no session to bind a token to and no cookie to look for, and
90
+ * every write a page server answers, cookie or none (`crossSiteWritesStage`). It rests on two headers a page CANNOT
91
+ * set — the browser attaches both, and script may not override either:
92
+ *
93
+ * - **`Sec-Fetch-Site`** is the browser's own account of where the request came from, and is believed first.
94
+ * Anything but `cross-site` (`same-origin`, `same-site`, or `none` for a typed URL) is this deployment's own.
95
+ * The browser works that out with the real public suffix list, which is why it is worth more than anything
96
+ * derivable here.
97
+ * - **`Origin`** is the fallback, for a browser too old to send the above — Safari only did from 16.4. Matched
98
+ * **exactly**, against this host or an origin the deployment named.
99
+ *
100
+ * That exactness is deliberate and was a bug once: this compared *registrable domains*, last-two-labels, the
101
+ * same helper that scopes the session cookie. It has no public suffix list, so on a deployment at `acme.co.uk`
102
+ * every other `.co.uk` in the world counted as the same site and could sign a visitor in. Guessing where a
103
+ * domain boundary falls is not something to do in a security decision — a sibling sub-domain that needs to be
104
+ * trusted is one line in `allowedOrigins`, which `createAuth` already fills from `identity.platformOrigins`.
105
+ *
106
+ * **Neither header means this is not a browser**, and a client that is not a browser cannot be made to forge
107
+ * anything: there is no victim's session sitting in it. That is what keeps every API client, mobile app and
108
+ * script signing in with nothing extra to send.
109
+ */
110
+ var crossSiteRequest = (carrier, allowed = () => false) => {
111
+ const site = header(carrier, "sec-fetch-site");
112
+ const origin = header(carrier, "origin");
113
+ const vouched = origin !== void 0 && allowed(origin);
114
+ if (site !== void 0) return site === "cross-site" && !vouched;
115
+ if (!origin) return false;
116
+ return originHost(origin) !== carrier.hostname && !vouched;
117
+ };
86
118
  var createCsrf = (config) => {
87
119
  const { secret, cookie, allowedOrigins = [] } = config;
88
120
  const permitted = (origin) => typeof allowedOrigins === "function" ? allowedOrigins(origin) : allowedOrigins.includes(origin);
89
- /**
90
- * Did this request come from a site this deployment does not recognise?
91
- *
92
- * This is what protects signing in, where there is no session to bind a token to and no cookie to look for. It
93
- * rests on two headers a page CANNOT set — the browser attaches both, and script may not override either:
94
- *
95
- * - **`Sec-Fetch-Site`** is the browser's own account of where the request came from, and is believed first.
96
- * Anything but `cross-site` (`same-origin`, `same-site`, or `none` for a typed URL) is this deployment's own.
97
- * The browser works that out with the real public suffix list, which is why it is worth more than anything
98
- * derivable here.
99
- * - **`Origin`** is the fallback, for a browser too old to send the above — Safari only did from 16.4. Matched
100
- * **exactly**, against this host or an origin the deployment named.
101
- *
102
- * That exactness is deliberate and was a bug once: this compared *registrable domains*, last-two-labels, the
103
- * same helper that scopes the session cookie. It has no public suffix list, so on a deployment at `acme.co.uk`
104
- * every other `.co.uk` in the world counted as the same site and could sign a visitor in. Guessing where a
105
- * domain boundary falls is not something to do in a security decision — a sibling sub-domain that needs to be
106
- * trusted is one line in `allowedOrigins`, which `createAuth` already fills from `identity.platformOrigins`.
107
- *
108
- * **Neither header means this is not a browser**, and a client that is not a browser cannot be made to forge
109
- * anything: there is no victim's session sitting in it. That is what keeps every API client, mobile app and
110
- * script signing in with nothing extra to send.
111
- */
112
- const foreign = (carrier, alsoAllowed = []) => {
113
- const site = header(carrier, "sec-fetch-site");
114
- const origin = header(carrier, "origin");
115
- const allowed = origin !== void 0 && (permitted(origin) || alsoAllowed.includes(origin));
116
- if (site !== void 0) return site === "cross-site" && !allowed;
117
- if (!origin) return false;
118
- return originHost(origin) !== carrier.hostname && !allowed;
119
- };
121
+ const foreign = (carrier, alsoAllowed = []) => crossSiteRequest(carrier, (origin) => permitted(origin) || alsoAllowed.includes(origin));
120
122
  const nameFor = (hostname) => `${sessionCookieParams(hostname, cookie).name}_csrf`;
121
123
  const sign = (nonce, expiry, binding) => createHmac("sha256", secret).update(`${nonce}.${expiry}.${binding}`).digest("base64url");
122
124
  /**
@@ -256,4 +258,4 @@ var createCsrf = (config) => {
256
258
  };
257
259
  };
258
260
  //#endregion
259
- export { carrierOf, createCsrf, csrfFailureMessage };
261
+ export { carrierOf, createCsrf, crossSiteRequest, csrfFailureMessage };
@@ -23,6 +23,8 @@ export interface Grant {
23
23
  spaceId: number;
24
24
  scope: SpaceScope;
25
25
  userId?: number;
26
+ /** For an `agent` grant, the application the member connected, as it registered (`Claude`): who writes for them. */
27
+ client?: string;
26
28
  origins: string[];
27
29
  }
28
30
  /** What an account may do inside ONE space. */
@@ -37,6 +39,8 @@ export interface StoredSpaceToken {
37
39
  spaceId: number;
38
40
  scope: SpaceScope;
39
41
  userId?: number;
42
+ /** For an `agent` grant, the application the member connected (`Claude`). */
43
+ client?: string;
40
44
  }
41
45
  /**
42
46
  * What identity resolution cannot work out on its own: where accounts, space tokens and memberships are kept. This
@@ -63,6 +63,7 @@ var createIdentity = ({ tokens, carriers, adapters, config = {}, presentedOrigin
63
63
  spaceId,
64
64
  scope,
65
65
  userId: stored.userId,
66
+ ...stored.client === void 0 ? {} : { client: stored.client },
66
67
  origins
67
68
  };
68
69
  if (scope === "render" && host !== void 0 && !domainAllowed(host, origins, platformHosts)) {
@@ -82,6 +82,10 @@ var createServer = ({ auth, sessionRenewal, ...config }, extensions) => {
82
82
  exchangePath: false,
83
83
  ...config,
84
84
  authCookie: config.authCookie ?? auth.cookieConfig,
85
+ crossSiteWrites: {
86
+ ...config.crossSiteWrites,
87
+ origins: [...config.crossSiteWrites?.origins ?? [], ...auth.platformOrigins]
88
+ },
85
89
  pageAuth: config.pageAuth ?? auth.pageAuth,
86
90
  adapters: {
87
91
  ...auth.ssrAdapters,
@@ -1,3 +1,7 @@
1
+ /** Whether something already answers at `port` — the one test that sees a listener on every address, not just `host`. */
2
+ export declare const portAnswers: (port: number, host: string) => Promise<boolean>;
3
+ /** Whether this process could listen at `port` on `host`. */
4
+ export declare const portBindable: (port: number, host: string) => Promise<boolean>;
1
5
  /**
2
6
  * The first port from `preferred` up that nothing uses — for a development server, which should start beside
3
7
  * whatever else is running rather than refuse to.
@@ -1,7 +1,7 @@
1
1
  import { connect, createServer } from "node:net";
2
2
  //#region src/core/freePort.ts
3
3
  /** Whether something already answers at `port` — the one test that sees a listener on every address, not just `host`. */
4
- var answers = (port, host) => new Promise((resolve) => {
4
+ var portAnswers = (port, host) => new Promise((resolve) => {
5
5
  const socket = connect({
6
6
  port,
7
7
  host
@@ -13,7 +13,7 @@ var answers = (port, host) => new Promise((resolve) => {
13
13
  socket.once("error", () => resolve(false));
14
14
  });
15
15
  /** Whether this process could listen at `port` on `host`. */
16
- var bindable = (port, host) => new Promise((resolve) => {
16
+ var portBindable = (port, host) => new Promise((resolve) => {
17
17
  const probe = createServer();
18
18
  probe.once("error", () => resolve(false));
19
19
  probe.once("listening", () => probe.close(() => resolve(true)));
@@ -29,8 +29,8 @@ var bindable = (port, host) => new Promise((resolve) => {
29
29
  * this: a fixed port that is taken is an error worth stopping for.
30
30
  */
31
31
  var freePort = async (preferred, host = "127.0.0.1", attempts = 20) => {
32
- for (let port = preferred; port < preferred + attempts; port += 1) if (!await answers(port, host) && await bindable(port, host)) return port;
32
+ for (let port = preferred; port < preferred + attempts; port += 1) if (!await portAnswers(port, host) && await portBindable(port, host)) return port;
33
33
  throw new Error(`No free port between ${preferred} and ${preferred + attempts - 1} on ${host}. Set PORT to one.`);
34
34
  };
35
35
  //#endregion
36
- export { freePort };
36
+ export { freePort, portAnswers, portBindable };
@@ -1,6 +1,7 @@
1
1
  import { readRawBody } from "../../requestParser.js";
2
2
  import { isNavigation, safeRedirectTarget } from "../navigation.js";
3
3
  import { clearSessionCookies, writeSessionCookies } from "../../auth/session.js";
4
+ import { refusedCrossSite } from "./crossSiteWrites.js";
4
5
  import { exchangeStage } from "./exchangeRoute.js";
5
6
  import { signInStage } from "./signInRoute.js";
6
7
  //#region src/core/http/stages/authRoutes.ts
@@ -24,6 +25,7 @@ var loginStage = async (ctx) => {
24
25
  const { config, raw, req, res } = ctx;
25
26
  const loginPath = config.loginPath === false ? null : config.loginPath ?? "/auth/login";
26
27
  if (!loginPath || req.method !== "POST" || req.path !== loginPath) return false;
28
+ if (refusedCrossSite(ctx)) return true;
27
29
  req.body = await readRawBody(raw);
28
30
  const session = await config.adapters.authenticate?.(parseCredentials(req), req);
29
31
  if (session) writeSessionCookies(req, res, session, config.authCookie);
@@ -49,6 +51,7 @@ var logoutStage = async (ctx) => {
49
51
  const { config, raw, req, res } = ctx;
50
52
  const logoutPath = config.logoutPath === false ? null : config.logoutPath ?? "/auth/logout";
51
53
  if (!logoutPath || req.method !== "POST" || req.path !== logoutPath) return false;
54
+ if (refusedCrossSite(ctx)) return true;
52
55
  req.body = await readRawBody(raw);
53
56
  await config.adapters.endSession?.(req);
54
57
  clearSessionCookies(req, res, config.authCookie);
@@ -0,0 +1,23 @@
1
+ import { BaseContext, Stage } from '../types';
2
+ /**
3
+ * Whether this request is a write a page on another site caused, and so is refused — answered here, 403
4
+ * `reason: 'foreign'`, when it is.
5
+ *
6
+ * Not only a write a session cookie could authenticate: a server holding credentials of its own (a token for somebody's
7
+ * calendar, an API key) or a tool with no sign-in at all acts for whoever reaches it, and a plain form POST from any
8
+ * page open in the same browser reaches it without a preflight. Passes:
9
+ *
10
+ * - a safe method;
11
+ * - `Authorization` — a page on another site cannot set it without a preflight this server never allows;
12
+ * - a request that is not a browser's (no `Sec-Fetch-Site`, no `Origin`): a webhook, `curl`, another server;
13
+ * - a page of this site (`same-origin`, `same-site`), or of an origin in `crossSiteWrites.origins`;
14
+ * - a path in `crossSiteWrites.paths` — a form other sites post to by design.
15
+ */
16
+ export declare const refusedCrossSite: (ctx: BaseContext) => boolean;
17
+ /**
18
+ * Every write the page server answers after it — server actions, realtime publishes, a space's `/fn/` routes and its
19
+ * runtime's endpoints, the deployment's own data stages — refused when another site caused it (see
20
+ * {@link refusedCrossSite}). After the stages that gate themselves (`preAuth`: the `/auth` flows with their own CSRF,
21
+ * MCP and its OAuth, the preview's shared secret), before everything else.
22
+ */
23
+ export declare const crossSiteWritesStage: Stage;
@@ -0,0 +1,44 @@
1
+ import { carrierOf, crossSiteRequest } from "../../auth/csrf.js";
2
+ //#region src/core/http/stages/crossSiteWrites.ts
3
+ /** GET, HEAD and OPTIONS change nothing: a link or an `<img>` from anywhere is how the web works. */
4
+ var SAFE_METHODS = /* @__PURE__ */ new Set([
5
+ "GET",
6
+ "HEAD",
7
+ "OPTIONS"
8
+ ]);
9
+ /**
10
+ * Whether this request is a write a page on another site caused, and so is refused — answered here, 403
11
+ * `reason: 'foreign'`, when it is.
12
+ *
13
+ * Not only a write a session cookie could authenticate: a server holding credentials of its own (a token for somebody's
14
+ * calendar, an API key) or a tool with no sign-in at all acts for whoever reaches it, and a plain form POST from any
15
+ * page open in the same browser reaches it without a preflight. Passes:
16
+ *
17
+ * - a safe method;
18
+ * - `Authorization` — a page on another site cannot set it without a preflight this server never allows;
19
+ * - a request that is not a browser's (no `Sec-Fetch-Site`, no `Origin`): a webhook, `curl`, another server;
20
+ * - a page of this site (`same-origin`, `same-site`), or of an origin in `crossSiteWrites.origins`;
21
+ * - a path in `crossSiteWrites.paths` — a form other sites post to by design.
22
+ */
23
+ var refusedCrossSite = (ctx) => {
24
+ const { req, res, config } = ctx;
25
+ const allowed = config.crossSiteWrites;
26
+ if (SAFE_METHODS.has(req.method.toUpperCase()) || req.headers.authorization !== void 0 || allowed?.paths?.(req.path) === true || !crossSiteRequest(carrierOf(req), (origin) => allowed?.origins?.includes(origin) === true)) return false;
27
+ ctx.operation = "refused:cross-site";
28
+ res.setStatus(403);
29
+ res.setHeader("Content-Type", "application/json; charset=utf-8");
30
+ res.send(JSON.stringify({
31
+ error: `A page on another site may not ${req.method} ${req.path} here: name its origin in the server's \`crossSiteWrites.origins\`, or the path in \`crossSiteWrites.paths\``,
32
+ reason: "foreign"
33
+ }));
34
+ return true;
35
+ };
36
+ /**
37
+ * Every write the page server answers after it — server actions, realtime publishes, a space's `/fn/` routes and its
38
+ * runtime's endpoints, the deployment's own data stages — refused when another site caused it (see
39
+ * {@link refusedCrossSite}). After the stages that gate themselves (`preAuth`: the `/auth` flows with their own CSRF,
40
+ * MCP and its OAuth, the preview's shared secret), before everything else.
41
+ */
42
+ var crossSiteWritesStage = refusedCrossSite;
43
+ //#endregion
44
+ export { crossSiteWritesStage, refusedCrossSite };
@@ -0,0 +1 @@
1
+ export {};
@@ -1,5 +1,6 @@
1
1
  import { readRawBody } from "../../requestParser.js";
2
2
  import { writeSessionCookies } from "../../auth/session.js";
3
+ import { refusedCrossSite } from "./crossSiteWrites.js";
3
4
  //#region src/core/http/stages/exchangeRoute.ts
4
5
  var parseBody = (req) => {
5
6
  if (!req.body) return {};
@@ -30,6 +31,7 @@ var exchangeStage = async (ctx) => {
30
31
  const { config, raw, req, res } = ctx;
31
32
  const exchangePath = config.exchangePath === false ? null : config.exchangePath ?? "/auth/exchange";
32
33
  if (!exchangePath || req.method !== "POST" || req.path !== exchangePath) return false;
34
+ if (refusedCrossSite(ctx)) return true;
33
35
  if (!config.adapters.exchangeCredential) {
34
36
  res.setStatus(404);
35
37
  res.end();
@@ -4,7 +4,7 @@ import { HostedStore, Remote, StoreMethods } from './channel';
4
4
  * (`role.ts`). A single server never reaches past `fleetStore`, which answers it nothing.
5
5
  */
6
6
  /** The stores a single process keeps in memory by default, which the workers of a fleet share (see `stores.ts`). */
7
- export type FleetStoreName = 'actions.kv' | 'realtime.grants' | 'actions.jobs' | 'ssr.drafts' | 'auth.rateLimit';
7
+ export type FleetStoreName = 'actions.kv' | 'realtime.kv' | 'actions.jobs' | 'ssr.drafts' | 'auth.rateLimit';
8
8
  /**
9
9
  * The primary's hub: it answers its workers from the stores in `catalogue`, made when first asked for, and passes
10
10
  * broadcasts on. Started before the first fork, so no worker can ask before anyone is answering.
@@ -24,7 +24,7 @@ var fleetKv = (make) => {
24
24
  */
25
25
  var FLEET_STORES = {
26
26
  "actions.kv": hostable(() => deploymentKv ?? createMemoryKv(), KV_METHODS),
27
- "realtime.grants": hostable(createMemoryKv, KV_METHODS),
27
+ "realtime.kv": hostable(createMemoryKv, KV_METHODS),
28
28
  "actions.jobs": hostable(() => createMemoryJobQueue(), JOB_QUEUE_METHODS),
29
29
  "ssr.drafts": hostable(createMemoryDraftStore, DRAFT_STORE_METHODS),
30
30
  "auth.rateLimit": hostable(() => ({ check: createMemoryRateLimit() }), RATE_LIMIT_METHODS)