@plitzi/sdk-server 0.38.14 → 0.38.15

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 (41) hide show
  1. package/CHANGELOG.md +106 -0
  2. package/README.md +64 -2
  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/createServer.js +4 -0
  8. package/dist/core/http/stages/authRoutes.js +3 -0
  9. package/dist/core/http/stages/crossSiteWrites.d.ts +23 -0
  10. package/dist/core/http/stages/crossSiteWrites.js +44 -0
  11. package/dist/core/http/stages/crossSiteWrites.test.d.ts +1 -0
  12. package/dist/core/http/stages/exchangeRoute.js +2 -0
  13. package/dist/core/server/fleet/link.d.ts +1 -1
  14. package/dist/core/server/fleet/stores.js +1 -1
  15. package/dist/core/services/registry.js +2 -0
  16. package/dist/functions-api.d.ts +5 -2
  17. package/dist/index.d.ts +2 -0
  18. package/dist/index.js +2 -1
  19. package/dist/modules/actions/tasks/realtime.js +1 -1
  20. package/dist/modules/authoringHost/index.d.ts +49 -0
  21. package/dist/modules/authoringHost/index.js +113 -0
  22. package/dist/modules/authoringHost/index.test.d.ts +1 -0
  23. package/dist/modules/functions/contract.d.ts +5 -2
  24. package/dist/modules/project/serveProject.js +4 -1
  25. package/dist/modules/realtime/hub.d.ts +7 -2
  26. package/dist/modules/realtime/hub.js +8 -4
  27. package/dist/modules/realtime/index.js +14 -7
  28. package/dist/modules/realtime/message.d.ts +3 -0
  29. package/dist/modules/realtime/message.js +5 -0
  30. package/dist/modules/realtime/retained.d.ts +24 -0
  31. package/dist/modules/realtime/retained.js +47 -0
  32. package/dist/modules/realtime/retained.test.d.ts +1 -0
  33. package/dist/modules/runtime/stages.d.ts +4 -1
  34. package/dist/modules/ssr/spaceDocument.js +5 -1
  35. package/package.json +3 -3
  36. package/skills/plitzi-authoring/SKILL.md +1 -1
  37. package/skills/plitzi-authoring/reference/index.md +3 -2
  38. package/skills/plitzi-authoring/reference/plugin-reach.md +91 -0
  39. package/skills/plitzi-authoring/reference/plugins.md +15 -31
  40. package/skills/plitzi-authoring/reference/realtime.md +11 -0
  41. package/skills/plitzi-authoring/reference/testing.md +3 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,111 @@
1
1
  # @plitzi/sdk-server
2
2
 
3
+ ## 0.38.15
4
+
5
+ ### Patch Changes
6
+
7
+ - 6cdd5cf: ## Security
8
+
9
+ - **A write another site caused is refused, cookie or none** (`@plitzi/sdk-server`, `@plitzi/sdk-shared`): the page
10
+ server guarded nothing it answers past `/auth` — a server action (`/_action`), a realtime publish, a space's `/fn/`
11
+ route, its runtime's endpoints, the deployment's own `data` stages, the adapter-only `loginPath`, `logoutPath` and
12
+ `exchangePath`. A plain `text/plain` POST from any page open in the same browser ran them, with the visitor's session
13
+ cookie when there was one (`SameSite=None` off this machine) and, in a project nobody signs in to, as whoever holds
14
+ the server's own credentials. Every unsafe request a browser says another site caused (`Sec-Fetch-Site: cross-site`,
15
+ or a foreign `Origin`) is now refused `403 reason: 'foreign'`, saying how to allow it: `crossSiteWrites.origins`
16
+ (with `auth`, `identity.platformOrigins` too) and `crossSiteWrites.paths` for a form other sites post to by design.
17
+ `Authorization`, and callers that are not browsers — webhooks, scripts — pass as before. One rule for this and the
18
+ sign-in check (`crossSiteRequest`, `csrf.ts`). A self-hosted runtime's endpoints now sit where the platform forwards a
19
+ space's — after the auth chain and this guard (`data`, was `preAuth`).
20
+
21
+ ## Testing
22
+ - **`page check` and `page shot` anywhere the project is served** (`@plitzi/cli`): `--url <origin>` for a second server
23
+ of it, staging or a deploy, instead of `npm start`'s port; `page check --space <module>` holds the pages to that space
24
+ instead of the project's — an agent's page — authored with `authorIsolated`.
25
+ - **A route with a query is checked as its page** (`@plitzi/cli`): `page check "/?v=2"` matched the query as part of
26
+ the path, found no page, and checked the space's "not found" page in its place.
27
+
28
+ - **What an element that chooses its children draws is checked** (`@plitzi/sdk-authoring`, `@plitzi/cli`): with
29
+ `choosesChildren`, the page checks owed none of its children — and checked none of them either: a dashboard drawing
30
+ three panels reported `checked: 1`. Each child it may draw, and what is inside one under no condition of its own,
31
+ now carries `shownWith` (the child it comes with) on its handle: once that child is on screen it and everything
32
+ named in it are owed like the rest of the page, and `checked` counts them. `onScreenIfChosen(handles, page)` lists
33
+ them.
34
+ - **A page that met a server error is looked at once more** (`@plitzi/cli`): `page check` and `verify` failed a page
35
+ for a `500` from somebody else's service having a bad second (`/fn/<space>/weather`), and passed on the next run with
36
+ nothing changed. A page whose requests got a `5xx` is checked again once; its report is the second look, and says
37
+ what failed the first time (`retriedAfter`). A `4xx` fails the same way twice, and is never retried.
38
+
39
+ ## Plugins
40
+ - **`useNotify`** (`@plitzi/plitzi-sdk`): a plugin shows the page's notifications — `notify('Deleted 79 recordings', {
41
+ appearance: 'danger' })` — the same toasts an `addNotification` step shows, in the space's theme and `notifications`
42
+ look, with no trigger, flow or `window` event of the space's to wire. The step's vocabulary (`NOTIFICATION_PLACEMENTS`,
43
+ `NOTIFICATION_APPEARANCES`, `NOTIFICATION_DEFAULTS`) is one list in `@plitzi/sdk-shared`, read by both.
44
+ - **`appearance: 'danger'` looks like one** (`@plitzi/plitzi-sdk`): it reached the toast library as a type it does not
45
+ know, so a danger notification showed neither the error icon nor the colour `notifications.danger` sets.
46
+ A value a notification does not take — from a flow, or a plugin in plain JavaScript — is set aside by name and said
47
+ in the console, rather than shown as the default in silence (`readNotificationOptions`, `@plitzi/sdk-shared`).
48
+ - **`useServerAction`** (`@plitzi/plitzi-sdk`, `@plitzi/sdk-authoring`, `@plitzi/sdk-interactions`,
49
+ `@plitzi/sdk-server`): a plugin runs one of the space's server actions, awaited —
50
+ `useServerAction<typeof habitDone>('habits-done')({ id })` answers `{ ok, output }` or `{ ok: false, reason, error }`
51
+ — through the `runServerAction` step itself: the same access, refusals, session handling and dev-tools entry.
52
+ `defineAction` keeps the literal types of its `call` way in, so the input is typed by the fields it declares (the
53
+ required ones required); `taskAction` types both ends from the task's `run`, and `FunctionTask<T, R>` takes what
54
+ `run` answers. `CallInputOf` / `CallOutputOf` read them. One operation is one action, never a `case` in one route.
55
+ What a run answers is typed (`ServerActionStatus`): a status the server never uses reads as a run that did not
56
+ complete, never as one that did.
57
+ The key those types ride under (`CALL_TYPES`) is exported, by `@plitzi/sdk-shared` and `@plitzi/sdk-authoring` with
58
+ `TypedActionEntry`, `CallInputOf` and `CallOutputOf`: a package that emits declarations could not write the type of an
59
+ action it exports (`TS4023` on every `export const actions = [defineAction(…)]`).
60
+ - **A plugin is drawn on the server first** (docs): a preference per device belongs in kept state (`keepState`,
61
+ `paintedState`) as a bound prop, never read from `localStorage` while rendering — React discards the whole tree on the
62
+ mismatch, and only in the browser of whoever saved something. `@plitzi/plitzi-ui` is not the page's: a plugin
63
+ importing it bundles its own copy, with its own contexts and its own look. The authoring skill's `plugin-reach.md`
64
+ says what a plugin says and to whom: a notification, another element (an event and the space's flow), a server
65
+ action, shared state, other pages.
66
+
67
+ ## Realtime
68
+ - **A channel that retains** (`@plitzi/sdk-shared`, `@plitzi/sdk-server`, `@plitzi/sdk-elements`): declared
69
+ `retain: true` (with `publish: 'server'`, which authoring requires), the server keeps the latest message of each type
70
+ on a topic — said by `ctx.publish` or a flow's `realtime.publish` — and hands them to every page that joins, marked
71
+ `retained`. A page reads them as `<channel>.retained.<type>`, a plugin as `useChannel(topic).retained`, the newest of
72
+ a type holding whichever order they arrive in; `null` forgets a type. Kept in the store the actions' `kv` uses (beside
73
+ the grants, by compare-and-swap), so every replica hands out the same; a topic keeps at most 64 types and 512 KB, and
74
+ a publish past that is refused before anything is sent. State every screen shares is one publish and one binding —
75
+ no kv key, initial read or copy in `state` of the project's own. The fleet store `realtime.grants` is now
76
+ `realtime.kv`.
77
+ - **The MCP writes every field a channel takes** (`@plitzi/sdk-mcp`): `patchSettings`'s channel had no `grant` — which
78
+ the guide taught — nor `retain` or the limits, so an agent could not declare a private channel at all. All are there
79
+ now, and the guide says what `retain` is for and that `channel_<id>.retained` holds it.
80
+
81
+ ## Authoring
82
+ - **`plitzi explain` knows every `@plitzi` package installed** (`@plitzi/cli`): a name that was not
83
+ `@plitzi/sdk-authoring`'s (`createServer`, `createJsonAdapters`, `useChannel`) was answered as the project's own code,
84
+ to `grep` in `src/`. It is read from the published types of every one installed, through their re-exports and entry
85
+ points (`@plitzi/sdk-server/handlers`), and a name two packages export — `createServer` is sdk-server's and sdk-mcp's
86
+ — is answered with both.
87
+
88
+ - **A space module somebody else wrote, authored where it reaches nothing** (`@plitzi/sdk-authoring`):
89
+ `authorIsolated(file, { timeoutMs })` of `@plitzi/sdk-authoring/node` runs `authorSpace` on it in a process Node's
90
+ permission model holds to reading the module's folder and its packages — no file written, no process started, no
91
+ variable of the caller's environment — kills one that runs too long, and validates what it answers again, so a forged
92
+ answer gains nothing. A refusal comes back as `authorSpace` says it, with the problems as data.
93
+ - **Pages an agent writes, served** (`@plitzi/sdk-server`): `createAuthoringHost({ dir, frameAncestors })` serves each
94
+ space it is handed at an address of its own (`put(space, { id }) → /?__pt=<id>`) as a draft of its one space, kept in
95
+ `dir` across restarts; `drop(id)` forgets one, and anything else answers `404` saying where the pages are.
96
+ - **A space is chosen by host or credential** (`@plitzi/sdk-server`, docs): `getSpaceDeployment` is asked on every
97
+ request, and what a page fetches after it carries nothing of its address but the host — a space chosen by the page's
98
+ query or path lost everything it asked for, and `/_plitzi/space/<hash>.json` answered a bare `404`. The contract and
99
+ the README say so (the README offered "by path prefix"), and that `404` says why.
100
+
101
+ - **`plitzi explain on` says how to read what a trigger carries** (`@plitzi/sdk-authoring`): its doc sat above a
102
+ helper, so `explain` printed only the signature. It now leads with `[named('picked', on('onPick')), …('{{ picked.seat
103
+ }}')]`, and the CLI skill's plugin section says the same.
104
+
105
+ - Updated dependencies [6cdd5cf]
106
+ - @plitzi/plitzi-sdk@0.38.15
107
+ - @plitzi/sdk-shared@0.38.15
108
+
3
109
  ## 0.38.14
4
110
 
5
111
  ### 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.
@@ -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 };
@@ -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,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)
@@ -5,6 +5,7 @@ import { rscStage } from "./rsc.js";
5
5
  import { spaceDocumentStage } from "./spaceDocument.js";
6
6
  import { imagesStage } from "../http/stages/images.js";
7
7
  import { notFoundStage, ssrStage } from "./ssr.js";
8
+ import { crossSiteWritesStage } from "../http/stages/crossSiteWrites.js";
8
9
  import { authRoutesStages } from "../http/stages/authRoutes.js";
9
10
  import { fontAssetsStage } from "../http/stages/fontAssets.js";
10
11
  import { healthStage } from "../http/stages/health.js";
@@ -25,6 +26,7 @@ var buildPagePipeline = (services, extensions = {}) => {
25
26
  sdkAssetsStage
26
27
  ];
27
28
  stages.push(...extensions.preAuth ?? []);
29
+ stages.push(crossSiteWritesStage);
28
30
  stages.push(createMiddlewaresStage());
29
31
  if (services.rsc) stages.push(rscStage);
30
32
  stages.push(actionStage);
@@ -160,8 +160,11 @@ export declare type FunctionsDefinition = {
160
160
  * One step a server action can take, written by the space. The shape of the platform's own tasks — addressed as
161
161
  * `<namespace>.<action>`, drawn in the builder from `params` — run with a {@link FunctionContext} rather than the
162
162
  * platform's full one.
163
+ *
164
+ * `R` is what `run` answers: `taskAction(task, …)` hands it, with `T`, to a page that runs the action
165
+ * (`useServerAction`), so `FunctionTask<{ id: string }, Habit>` is typed at both ends.
163
166
  */
164
- export declare type FunctionTask<T extends Record<string, unknown> = Record<string, unknown>> = {
167
+ export declare type FunctionTask<T extends Record<string, unknown> = Record<string, unknown>, R = unknown> = {
165
168
  namespace: string;
166
169
  action: string;
167
170
  title: string;
@@ -172,7 +175,7 @@ export declare type FunctionTask<T extends Record<string, unknown> = Record<stri
172
175
  * what the server allows. Over the functions' own `limits`, for this task.
173
176
  */
174
177
  limits?: FunctionTimeLimits;
175
- run: (params: T, ctx: FunctionContext) => unknown;
178
+ run: (params: T, ctx: FunctionContext) => R | Promise<R>;
176
179
  };
177
180
 
178
181
  /**
package/dist/index.d.ts CHANGED
@@ -12,6 +12,7 @@ export { createAuthAdapters } from './adapters/authAdapters';
12
12
  export { authoringPreview, createMemoryCache, createSpaceAdapters, fixedSpace, presentsCredential, refuse, verifiedDomain, wildcardSubdomain } from './adapters/space';
13
13
  export { createLocalFontStore, hostedPathsOf } from './core/fontStore';
14
14
  export { createMemoryDraftStore, takeDraftOverride } from './modules/ssr/preview';
15
+ export { createAuthoringHost } from './modules/authoringHost';
15
16
  export { createMemoryPubSub } from './modules/realtime/memoryPubSub';
16
17
  export { createRedisPubSub } from './modules/realtime/redisPubSub';
17
18
  export { PREVIEW_TOKEN_PARAM } from './core/previewToken';
@@ -27,5 +28,6 @@ export type { FontStore, StoredFont } from './core/fontStore';
27
28
  export type { PubSubAdapter, SSRRealtimeConfig } from '@plitzi/sdk-shared';
28
29
  export type { RedisPubSubClients } from './modules/realtime/redisPubSub';
29
30
  export type { ResolvedServices, ServerConfig } from './core/createServer';
31
+ export type { AuthoringHost, AuthoringHostConfig } from './modules/authoringHost';
30
32
  export type { Closable, CloseOnSignalsOptions } from './core/server/closeOnSignals';
31
33
  export type { BaseContext, PipelineExtensions, SSRContext, Stage } from './core/http/types';
package/dist/index.js CHANGED
@@ -19,5 +19,6 @@ import { createMemoryCache, refuse } from "./adapters/space/types.js";
19
19
  import { authoringPreview, fixedSpace, presentsCredential, verifiedDomain, wildcardSubdomain } from "./adapters/space/resolvers.js";
20
20
  import { createSpaceAdapters } from "./adapters/space/index.js";
21
21
  import { createLocalFontStore, hostedPathsOf } from "./core/fontStore.js";
22
+ import { createAuthoringHost } from "./modules/authoringHost/index.js";
22
23
  import { createRedisPubSub } from "./modules/realtime/redisPubSub.js";
23
- export { PREVIEW_TOKEN_PARAM, authoringPreview, buildHealthPayload, closeOnSignals, consoleLogger, createAuthAdapters, createCloudAdapters, createConnectorResolver, createJsonAdapters, createLocalFontStore, createMemoryCache, createMemoryDraftStore, createMemoryPubSub, createRedisPubSub, createServer, createSpaceAdapters, fetchConnectorRecords, fixedSpace, freePort, hostedPathsOf, isLogged, loadFunctions, loadFunctionsSource, logLevelOf, presentsCredential, readFunctionsDir, rebaseMedia, refuse, registerHealthCheck, renderLogEvent, resolveRscData, resolveServices, serverLog, takeDraftOverride, unusedPort, verifiedDomain, wildcardSubdomain, writeConnectorRecord };
24
+ export { PREVIEW_TOKEN_PARAM, authoringPreview, buildHealthPayload, closeOnSignals, consoleLogger, createAuthAdapters, createAuthoringHost, createCloudAdapters, createConnectorResolver, createJsonAdapters, createLocalFontStore, createMemoryCache, createMemoryDraftStore, createMemoryPubSub, createRedisPubSub, createServer, createSpaceAdapters, fetchConnectorRecords, fixedSpace, freePort, hostedPathsOf, isLogged, loadFunctions, loadFunctionsSource, logLevelOf, presentsCredential, readFunctionsDir, rebaseMedia, refuse, registerHealthCheck, renderLogEvent, resolveRscData, resolveServices, serverLog, takeDraftOverride, unusedPort, verifiedDomain, wildcardSubdomain, writeConnectorRecord };
@@ -13,7 +13,7 @@ var realtimeTasks = [
13
13
  namespace: "realtime",
14
14
  action: "publish",
15
15
  title: "Publish On Channel",
16
- description: "Sends a message to every page subscribed to a topic of one of the space’s channels.",
16
+ description: "Sends a message to every page subscribed to a topic of one of the space’s channels. On a `retain: true` channel it is also kept, the latest of its type, for every page that joins later; `null` data forgets it.",
17
17
  params: {
18
18
  topic: {
19
19
  type: "text",
@@ -0,0 +1,49 @@
1
+ import { ServerConfig } from '../../core/createServer';
2
+ import { AuthoredDocuments } from '../project/watchSpace';
3
+ import { SSRServer } from '@plitzi/sdk-shared';
4
+ /**
5
+ * Pages somebody else authored — an agent designing a screen, a visitor's own page — served as a project's pages are,
6
+ * each at an address of its own, from one server.
7
+ *
8
+ * Each page is a space kept as a draft of the host's one space (`?__pt=<id>`), which is how a page server tells many
9
+ * apart on one host: the page arrives with its whole space in it, every page after it is the browser's, and a reload
10
+ * that lost the address finds it again in the draft's cookie. So a page here is drawn in the browser alone — no server
11
+ * provider, action, function or channel of its own: it is data and its look.
12
+ *
13
+ * Author them where they cannot reach anything (`authorIsolated` of `@plitzi/sdk-authoring/node`) and serve them here,
14
+ * on an origin of their own — never the app's, whose cookies a page somebody else wrote would then run beside.
15
+ *
16
+ * ```ts
17
+ * const host = createAuthoringHost({ dir: 'tmp/pages', port: 8091, frameAncestors: ['https://localhost:8080'] });
18
+ * await host.server.listen(8091, '0.0.0.0');
19
+ *
20
+ * const result = await authorIsolated('tmp/pages/weather.ts');
21
+ * if (result.ok) {
22
+ * const { path } = host.put(result.space, { id: 'weather' }); // `/?__pt=weather`
23
+ * }
24
+ * ```
25
+ */
26
+ export type AuthoringHostConfig = Omit<ServerConfig, 'adapters' | 'auth' | 'draftStore'> & {
27
+ /** Where the pages are kept, `<id>.json` each — read back when the host starts, so a restart serves them still. */
28
+ dir: string;
29
+ /** Who may show the pages in an iframe, as CSP `frame-ancestors` sources: the app that shows them. */
30
+ frameAncestors?: string[];
31
+ };
32
+ export type AuthoringHost = {
33
+ server: SSRServer;
34
+ /**
35
+ * Keeps a space under `id` — a new one when left out, which nobody can guess — replacing what it held, and answers
36
+ * the address its pages are at: its home is `path`, any other page that path with the page's own in front of `?`.
37
+ */
38
+ put: (documents: AuthoredDocuments, options?: {
39
+ id?: string;
40
+ }) => {
41
+ id: string;
42
+ path: string;
43
+ };
44
+ /** Forgets a page: its address answers 404 from then on. Whether there was one. */
45
+ drop: (id: string) => boolean;
46
+ /** The ids it serves. */
47
+ ids: () => string[];
48
+ };
49
+ export declare const createAuthoringHost: ({ dir, frameAncestors, ...config }: AuthoringHostConfig) => AuthoringHost;