@niscorp/moss 0.3.0 → 0.3.3

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 (48) hide show
  1. package/CHANGELOG.md +160 -0
  2. package/DESIGN.md +92 -21
  3. package/DOCS.md +190 -40
  4. package/README.md +7 -2
  5. package/dist/{chunk-J72N3EMJ.js → chunk-4T6KAXBP.js} +45 -27
  6. package/dist/chunk-4T6KAXBP.js.map +1 -0
  7. package/dist/{chunk-3CJCJKKY.js → chunk-AUZMT3GL.js} +742 -654
  8. package/dist/chunk-AUZMT3GL.js.map +1 -0
  9. package/dist/{chunk-ZOEUEMDX.js → chunk-HOZID4EM.js} +131 -16
  10. package/dist/chunk-HOZID4EM.js.map +1 -0
  11. package/dist/chunk-NE2EXMTO.js +103 -0
  12. package/dist/chunk-NE2EXMTO.js.map +1 -0
  13. package/dist/client/node.cjs +1 -1
  14. package/dist/client/node.cjs.map +1 -1
  15. package/dist/client/node.js +1 -1
  16. package/dist/client/node.js.map +1 -1
  17. package/dist/client.cjs +60 -26
  18. package/dist/client.cjs.map +1 -1
  19. package/dist/client.d.cts +6 -1
  20. package/dist/client.d.ts +6 -1
  21. package/dist/client.js +2 -2
  22. package/dist/{document-Jhfii6kd.d.cts → document-DhWxieUc.d.cts} +24 -4
  23. package/dist/{document-Jhfii6kd.d.ts → document-DhWxieUc.d.ts} +24 -4
  24. package/dist/index.cjs +780 -572
  25. package/dist/index.cjs.map +1 -1
  26. package/dist/index.d.cts +19 -3
  27. package/dist/index.d.ts +19 -3
  28. package/dist/index.js +2 -2
  29. package/dist/node.cjs +373 -219
  30. package/dist/node.cjs.map +1 -1
  31. package/dist/node.d.cts +2 -1
  32. package/dist/node.d.ts +2 -1
  33. package/dist/node.js +3 -3
  34. package/dist/terminal/index.cjs +60 -26
  35. package/dist/terminal/index.cjs.map +1 -1
  36. package/dist/terminal/index.js +2 -2
  37. package/dist/vite.cjs +103 -28
  38. package/dist/vite.cjs.map +1 -1
  39. package/dist/vite.d.cts +1 -1
  40. package/dist/vite.d.ts +1 -1
  41. package/dist/vite.js +14 -9
  42. package/dist/vite.js.map +1 -1
  43. package/package.json +15 -14
  44. package/dist/chunk-3CJCJKKY.js.map +0 -1
  45. package/dist/chunk-DPFWL7BS.js +0 -64
  46. package/dist/chunk-DPFWL7BS.js.map +0 -1
  47. package/dist/chunk-J72N3EMJ.js.map +0 -1
  48. package/dist/chunk-ZOEUEMDX.js.map +0 -1
package/DOCS.md CHANGED
@@ -222,8 +222,10 @@ type NiscRuntime = {
222
222
  pool: PgPool; // SQL
223
223
  db: MutationClient; // writes
224
224
  cache?: CacheBackend; // defaults to vex's postgres cache on `pool`
225
+ vexConfig?: QueryEngineConfig['config']; // the query engine's settings (limits, read timeout); default vex's own
225
226
  session: SessionVerifier | 'sessions' | 'dev-open'; // REQUIRED — no default
226
227
  migrations?: 'apply' | 'verify'; // the boot's ledgered run; default 'apply'
228
+ tables?: readonly Sequence[]; // the app's own table sequences, in that same run
227
229
  shellIdleMs?: number; // idle shell eviction; default 30 min, `0` disables
228
230
  endpointTimeoutMs?: number; // a server shell's endpoint call; default nova's, 30s
229
231
  sessionRevalidateMs?: number; // live-socket re-verify; default 60s, `0` disables
@@ -271,6 +273,38 @@ refuses to boot if anything is, for a deployment that migrates as a deploy step.
271
273
  `initIntegrations` and `initSessions` remain for hosts that are not moss's
272
274
  server, and go through the same ledger.
273
275
 
276
+ `tables` on the runtime hands over the app's own table sequences. They join
277
+ that run after moss's — one transaction, one lock, one posture, so `'verify'`
278
+ covers them. Absent, the app migrates its own tables itself, as before. Another
279
+ owner's tables the app keeps go in the same list (`TIDE_SEQUENCE`), and a
280
+ runtime that hands tables over does not also migrate them itself.
281
+
282
+ #### `migrateTables(runtime, app, { dryRun? }): Promise<TablesReport>`
283
+
284
+ The step that changes tables, for a deployment that migrates before it starts
285
+ (`nisc migrate` calls it). It applies everything pending in the one run,
286
+ whatever `runtime.migrations` says, and before the run may commit it asks
287
+ whether `app`'s entries fit what it leaves: every read is resolved against the
288
+ schema as the transaction sees it, every write is put to the gate vex puts it
289
+ to before it runs (`mutationMisfits`: its table, the columns it writes, its
290
+ WHERE, its lookups, its conflict target, what it reads from an earlier
291
+ statement). An entry that does not fit refuses the run — strata's
292
+ `DOES_NOT_FIT`, each
293
+ reason as `fingerprint: why` — and nothing was applied. It asks on every run,
294
+ so a release that changes an entry and no table is checked too.
295
+
296
+ One kind of entry is said and not refused: one that already did not fit before
297
+ the run and that the database already holds seeded exactly as it is. That is an
298
+ old fault, not this run's. A new or changed entry gets no such pass.
299
+
300
+ `TablesReport` is strata's `{ applied, plan }` plus `removed` (tables and
301
+ columns the run takes away), `retyped` (columns whose type it changes, as
302
+ `table.column (was → now)`) and `alreadyBroken`. `dryRun` does all of it and
303
+ rolls it back.
304
+
305
+ It sees entries and nothing else: not SQL written by hand, not a column a scope
306
+ rule stamps, not what a value means.
307
+
274
308
  **Documents are read in this code's grammars.** Stored integration actions
275
309
  carry a `grammar` stamp (`INTEGRATION_ACTIONS_STORE`). At boot, after the
276
310
  tables, moss upgrades every stored action that is behind — through nova's and
@@ -301,12 +335,14 @@ harness wants and a deployment must opt into out loud.
301
335
  #### `createServer(app, runtime): Promise<MossServer>`
302
336
 
303
337
  Stands up the data layer, **refuses to boot** on an incoherent charter
304
- (`verifyCharter` + nova's closure audit), memoizes per-principal policy,
338
+ (`verifyCharter`'s errors), memoizes per-principal policy,
305
339
  catalogs, and ring-2 variant bindings, mounts the vex surfaces and `/catalog`, and — when the manifest
306
340
  declares a shell — the shell host behind the socket. Also refused at boot: an
307
341
  entry whose `reach` names no profile the behaviors declare, and two pages that
308
- could answer one path. Returns a Hono app extended with the `MossServer`
309
- members below.
342
+ could answer one path. A broken closure is not among them: the closure audit's
343
+ findings land in the report's `perRole[].issues`, which boot does not read. A
344
+ role granted an action that pushes one it is not granted boots, and the press
345
+ does nothing. Returns a Hono app extended with the `MossServer` members below.
310
346
 
311
347
  What the server answers over HTTP:
312
348
 
@@ -330,7 +366,7 @@ is the anonymous principal. There is no `/fns` surface.
330
366
  #### `MossServer`
331
367
 
332
368
  `Hono<Env> & { socket: SocketAccept; shells?: ShellHost; principalOf; page; pages;
333
- refresh; invalidateIdentity; invalidateTenant; identity; executeAs;
369
+ refresh; charterReport; invalidateIdentity; invalidateTenant; identity; executeAs;
334
370
  callIntegration; nudge; generation; close; identities? }`.
335
371
  It's a Hono app — mount it, extend it, or hand it to a listener.
336
372
 
@@ -351,6 +387,15 @@ It's a Hono app — mount it, extend it, or hand it to a listener.
351
387
  on an incoherent charter or variant set, and the old resolution keeps
352
388
  serving. It also moves the generation pointer, so every other process on the
353
389
  same database does the same within one poll.
390
+ - `charterReport(): VerifyReport` — the report `verifyCharter` gave this server:
391
+ boot's, then that of each `refresh` that passed. `{ errors, warnings,
392
+ perRole }`, over the universes boot resolved against. Boot and `refresh` read
393
+ `errors` alone and print nothing of the rest, so this is where a host reads
394
+ it, to draw, log or hold a deploy on: `warnings` (an action no role grants, an
395
+ `allow` that matches nothing) and each role's closure `issues`. `errors` is
396
+ always empty here. A push whose target is a binding (`@event.payload`,
397
+ `$.target`) is listed among the `issues` as "not in the catalog", though it is
398
+ resolved when the step runs; a `{{…}}` target is not listed.
354
399
  - `generation(): number` — the generation this process last observed (`-1`
355
400
  before the first read).
356
401
  - `invalidateIdentity(principal): boolean` — forget one principal's identity
@@ -459,11 +504,15 @@ const page = await renderDocument({
459
504
  ```
460
505
 
461
506
  - **Which shell**: the page `server.page(path)` names, else the app's.
462
- - **For whom**: the principal behind the cookie named by the wire's token key
463
- (`tokenKey`, default `nisc.token`), or nobody. A cookie that no longer
464
- resolves is nobody, and the response takes it back (`Set-Cookie`, `Max-Age=0`).
465
- A verifier that *throws* is a fault, not a sign-out: the page goes out
466
- undrawn and the cookie stays.
507
+ - **For whom**: the principal behind the browser's session cookie for the
508
+ wire's token key (`tokenKey`, default `nisc.token`), or nobody. The cookie's
509
+ name ends with the port a page is on, so `request.host` (the `Host` header)
510
+ is how a page on a port finds it; `mountSite` and the vite plugin pass it.
511
+ Behind a proxy that rewrites `Host` to its upstream, the port `site` names
512
+ is tried too.
513
+ A cookie that no longer resolves is nobody. Nothing is written here — the
514
+ upgrade is where the cookie is set and taken back. A verifier that *throws*
515
+ is a fault, not a sign-out: the page goes out undrawn.
467
516
  - **`draw`** is a terminal that draws to a string — the app's kit bound to
468
517
  `renderSnapshot` from `terminal/react/server`, `terminal/vue/server` or
469
518
  `terminal/dom/server`. It may be async.
@@ -529,6 +578,28 @@ page. `embedSnapshot` writes the snapshot as a
529
578
  (and U+2028/2029) escaped: a tree carries what people typed, and nothing in it
530
579
  can close the element or open another.
531
580
 
581
+ #### `sessionCookies(page, token, options?)`
582
+
583
+ The `Set-Cookie` values that keep `token` in the browser of the page at this
584
+ origin — or, for `null`, take it back. For a sign-in the app answers over HTTP
585
+ (a link redeemed, a provider's callback): set them on the response, and the
586
+ page that follows is signed in having never held the token.
587
+
588
+ ```typescript
589
+ server.get('/login', async (c) => {
590
+ const token = await mintSession(pool, principal, TTL_MS);
591
+ for (const cookie of sessionCookies(c.req.raw, token, { lastsMs: TTL_MS })) c.header('set-cookie', cookie, { append: true });
592
+ return c.redirect('/');
593
+ });
594
+ ```
595
+
596
+ `page` is the request (its `Origin`, else where it was addressed and the
597
+ `X-Forwarded-Proto` it arrived with) or the page's origin as a string.
598
+ `options.key` is the seat (the terminal's `tokenKey`; default `nisc.token`);
599
+ `options.lastsMs` is how long the browser keeps it — left out, until the
600
+ browser closes. A sign-in made over the socket (`session.grant`) needs none of
601
+ this: the answer to the terminal's next upgrade writes the same cookie.
602
+
532
603
  #### `createPageRouter(pages): PageRouter`
533
604
 
534
605
  `{ match(path): { name, params } | undefined }` — the matching rule above, for a
@@ -684,7 +755,11 @@ measures the end.
684
755
  ### Resolution (exposed for tools)
685
756
 
686
757
  - `resolveRoles(app, principal): readonly string[]` — assignment rows; anonymous/
687
- unassigned wears `['public']`.
758
+ unassigned wears `['public']`. The name is fixed, and the charter has to
759
+ define it (`public: []` grants nothing). Where it does not, the server still
760
+ boots and nothing is said; then every request with no session, and every
761
+ signed-in principal with no assignment, fails with `Unknown role "public"` —
762
+ a 500, a socket closed `4500`, a page served undrawn.
688
763
  - `resolvePolicy(app, grants, principal): ScopePolicy` — the compiled vex policy
689
764
  this principal reads and writes under. **One policy per role, merged** — a
690
765
  person may wear several (an instructor who also trains here), and reach belongs
@@ -762,6 +837,18 @@ measures the end.
762
837
  - `Connection` — the transport seam: `{ send, close, onMessage, onClose }`.
763
838
  - `ServerMessage` — `hello | catalog | frame | render | render-delta | session | error`.
764
839
  - `ClientMessage` — `event | publish | resync | reset | back | popTo`.
840
+ - **A message a terminal sends is at most 256 KB**, counted as it is once
841
+ inflated. One over that closes the connection with `1009` — the transport's
842
+ own close, not one of moss's — and what it carried did not arrive: the
843
+ terminal reconnects as after any other close, and a signed-in person's shell
844
+ is as it was. The limit is the Node transport's (`attachSocket`'s
845
+ `maxMessageBytes`, below), and it is a bound on memory, not on speed: the
846
+ server keeps what a message carried — the value in the shell, and again in
847
+ the last frame it sent — and sends it back down in every later frame of that
848
+ canvas. An event is a press, a typed value, a row handed back. A file never
849
+ goes over the socket (AGENTS.md rule 9a): the picker sends it to a route the
850
+ app mounts, or to a system the app already has, and the event carries what
851
+ came back.
765
852
  - `render-delta` is only ever sent to a connection that advertised `?delta=1`
766
853
  on the upgrade, and only when the server is configured for it. Everything
767
854
  else is served whole frames, unchanged. See [Wire size](#wire-size).
@@ -792,18 +879,59 @@ measures the end.
792
879
  failing definitions, then the close. The refusal is that terminal's alone,
793
880
  and reconnecting later is reasonable.
794
881
  - `error` codes: `invalid_token`, `session_failed`, `client_too_old`,
795
- `server_too_old`, `no_shell` (the app serves no shell), `invalid_message`.
882
+ `server_too_old`, `no_shell` (the app serves no shell), `invalid_message`,
883
+ `seal_not_kept` (a sealed sign-in came back with no seal to open it).
884
+ - **Who a terminal is** is decided on the upgrade request, from a header of
885
+ it — never from its address, which is what every proxy on the way writes
886
+ into its log. A terminal offers the subprotocol `nisc`, and beside it its
887
+ token when it holds one: `offerToken(token | null)` returns the list to
888
+ construct the socket with (`new WebSocket(url, offerToken(token))`), and the
889
+ server answers `nisc`. A token in the address (`?token=`) is not read. A
890
+ transport hands the offer over as `connection.upgrade.offered`
891
+ (`Sec-WebSocket-Protocol`, split); one that leaves it out serves every
892
+ terminal as nobody. `attachSocket` does it.
893
+ - **A browser on the app's own page** is who its session cookie says
894
+ ([`sessionCookies`](#sessioncookiespage-token-options)). The cookie is read
895
+ only when the upgrade's `Origin` is the host it was addressed to, or one
896
+ `runtime.origins` lists. (Behind a proxy that rewrites `Host` and with
897
+ nothing listed, no page is the app's own: terminals hold their own tokens,
898
+ as before, and moss says so once in the log.) A token such a page offers is who it is and is
899
+ moved into the cookie by the answer to the upgrade; one that no longer
900
+ resolves is nobody (served, not refused) and is taken back. `?key=` names
901
+ which of the browser's sessions the terminal is — a seat; the cookie is named
902
+ by it. `?leave=1` is a terminal that was signed out: it is nobody whatever
903
+ its browser holds, and the cookie is taken back. A transport passes what the
904
+ request carried as `connection.upgrade` — `{ offered, origin, host, cookie }`
905
+ — and, when it has not answered the request yet, `answer(cookies)`: moss
906
+ calls it once who is asking is decided, with the `Set-Cookie` values to
907
+ answer with. A transport without `answer` reads cookies and writes none.
908
+ - **A sign-in is handed to such a page sealed.** A terminal whose browser can
909
+ keep a session says so (`?sealed=1`; `browserEnv` does), and the answer to
910
+ its first upgrade gives the browser a *seal*: a key in a second cookie no
911
+ script can read — or, over https, set (`__Http-nisc.seal`; `nisc.seal` over
912
+ plain http) — sent only with the socket's path. `session.grant(token)`
913
+ then reaches that terminal as `{ type: 'session', sealed }` — the token,
914
+ encrypted with the seal and good for a minute — which it offers back on its
915
+ next upgrade (`offerToken(null, sealed)`); the browser's seal opens it there
916
+ and the session cookie is written. Offered with another seal, altered, or
917
+ late, it opens nothing and the terminal is nobody. A browser that sent no
918
+ seal to open it with does not keep cookies: the terminal is told
919
+ (`seal_not_kept`), stops asking, and is handed the next sign-in as a token.
920
+ Any other terminal — a process, a page on another origin — is handed
921
+ `{ type: 'session', token }`, as before.
796
922
  - **Protocol version.** `PROTOCOL` is the wire protocol this server speaks and
797
923
  `PROTOCOL_MIN` the oldest it still serves. A terminal names its protocol on
798
- the upgrade (`?protocol=N`, beside the token); one that names none speaks `1`,
799
- which is every terminal built before the question existed. Outside the range
800
- the connection is refused before anything is served: an `error` frame
801
- (`client_too_old` or `server_too_old`) and a `4426` close. `hello` carries
802
- `protocol`, so a terminal can refuse a server older than it can speak to.
803
- Bump `PROTOCOL` when a message changes shape; raise `PROTOCOL_MIN` only when
804
- the server stops speaking an old one. Both are `1` today. `PROTOCOL`,
805
- `PROTOCOL_MIN` and `CLOSE_PROTOCOL_MISMATCH` are defined in `src/socket.ts`
806
- and are not re-exported from the package root.
924
+ the upgrade (`?protocol=N`); one that names none speaks `1`, which is every
925
+ terminal built before the question existed. Outside the range the connection
926
+ is refused before anything is served: an `error` frame (`client_too_old` or
927
+ `server_too_old`) and a `4426` close. `hello` carries `protocol`, so a
928
+ terminal can refuse a server older than it can speak to. Bump `PROTOCOL` when
929
+ a message changes shape; raise `PROTOCOL_MIN` only when the server stops
930
+ speaking an old one. Both are `2` today: at `1` the token rode the address,
931
+ and a server that went on reading it there would keep that open. `PROTOCOL`
932
+ and `offerToken` are exported from the package root, for a terminal written
933
+ by hand; `PROTOCOL_MIN` and `CLOSE_PROTOCOL_MISMATCH` are defined in
934
+ `src/socket.ts` and are not.
807
935
  - **`?path=`** — the path the terminal is on. A path that leads to a page is
808
936
  served that page's shell, built for this connection alone and seeded with the
809
937
  path's parameters; any other path (and no path) is the app's shell. A
@@ -863,6 +991,12 @@ at most 60% of the whole frame. A terminal that never advertises — including
863
991
  every terminal built before this existed — receives whole frames forever, from
864
992
  the same shell, in the same pass. The two kinds of connection coexist.
865
993
 
994
+ **A canvas whose frame is over 64 KB is always sent whole.** Comparing two
995
+ frames costs the server in proportion to their size, not to what changed, and
996
+ it does that work on the thread every session shares — about 7 ms at 64 KB, a
997
+ second at 2.7 MB. So when the frame a terminal holds, or the one replacing it,
998
+ is longer than 64 KB, the server does not compare them. It is not a setting.
999
+
866
1000
  What it buys, measured on Lyra:
867
1001
 
868
1002
  | change | delta, as a share of the whole frame |
@@ -891,10 +1025,19 @@ Correctness, which matters more than the saving:
891
1025
  in one process. `port` defaults to 8787.
892
1026
  - `attachSocket(httpServer, accept, path?, options?)` — embed the socket on an
893
1027
  existing server (raw `ws`, `noServer`, path-matched — coexists with vite
894
- HMR). `path` defaults to `/socket`. `options = { compression? }` is the same
895
- value as `runtime.socketCompression` and defaults to `true`; `serve()` passes
896
- the runtime's through for you, so only a host running its own listener (a
897
- vite plugin, a dev check) ever needs it.
1028
+ HMR). `path` defaults to `/socket`. `options = { compression?,
1029
+ maxMessageBytes? }`. `compression` is the same value as
1030
+ `runtime.socketCompression` and defaults to `true`; `serve()` passes the
1031
+ runtime's through for you, so only a host running its own listener (a vite
1032
+ plugin, a dev check) ever needs it. `maxMessageBytes` is the largest message
1033
+ a connection may send, in bytes, and defaults to 256 KB (`256 * 1024`); a
1034
+ message over it closes that connection with `1009`. It is handed to `ws` as
1035
+ `maxPayload`, whose own default was 100 MiB. Only a host that calls
1036
+ `attachSocket` itself can raise it: `serve()`, `nisc start` and the dev
1037
+ plugin take the default.
1038
+ - A frame the transport refuses — malformed, not UTF-8, over the limit — ends
1039
+ that connection (`1002`, `1007`, `1009`) and logs one line; no other
1040
+ connection is touched.
898
1041
 
899
1042
  - `mountSite(server, { dist, draw, htmlAttributes?, site?, tokenKey?, waitMs?, owned? })`
900
1043
  — the built terminal, served by the same process as the app. Every GET that
@@ -931,8 +1074,8 @@ Requires the optional `vite` peer.
931
1074
  - `options.app(load): Promise<DevApp>` — stand the app up. `load` is vite's
932
1075
  `ssrLoadModule`. `DevApp = { server, close?, draw?, htmlAttributes?,
933
1076
  site?, tokenKey?, signIn? }`; absent `draw`, pages go out undrawn.
934
- - `signIn(who)` enables `/dev/as/<who>`: it stores the returned token (and
935
- its cookie copy) and goes to `/`. `null` is nobody of that name.
1077
+ - `signIn(who)` enables `/dev/as/<who>`: it puts the returned token in the
1078
+ browser's session cookie and goes to `/`. `null` is nobody of that name.
936
1079
  - `watch?: RegExp` (default: `src/app`, `src/server`, `src/db`, `src/ui` and
937
1080
  the nisc config), `index?` (default `index.html`), `owned?` (default
938
1081
  `MOSS_PATHS`), `label?` (default `moss`).
@@ -944,19 +1087,26 @@ Requires the optional `vite` peer.
944
1087
  host-shaped comes in as a `WireEnv`. `delta` (default `false`) advertises
945
1088
  that this terminal can rebuild frame deltas; the snapshot it produces is
946
1089
  identical either way. See [Wire size](#wire-size).
947
- - `WireEnv` — the host seam: `{ tokens: { load, save, clear }, socket(url),
948
- defaultUrl() }`. The socket API is WHATWG-standard in every host (browser,
949
- Node ≥22, Bun); an env only constructs it.
950
- - `browserEnv({ tokenKey?, cookie? }?): WireEnv` — the default host: token in
951
- localStorage (`nisc.token`), url derived from `window.location`, the
952
- page's WebSocket. `cookie: true` keeps a **copy** of the token in a cookie of
953
- the same name (`Path=/; SameSite=Lax`, `Secure` on https), written and
954
- cleared with the stored one and levelled with it on every load — so a token
955
- put in localStorage by something else (a sign-in handoff page) reaches the
956
- cookie on the first load after it. A page request carries cookies and nothing
957
- else; this is what lets a server draw the page for whoever is asking. The
958
- cookie is only ever read to draw a page — every other surface still wants the
959
- token itself — so it adds no way in.
1090
+ - `WireEnv` — the host seam: `{ tokens: { load, save, clear, held?, key? },
1091
+ socket({ url, offered }), defaultUrl() }`. The socket API is WHATWG-standard
1092
+ in every host (browser, Node ≥22, Bun); an env only constructs it —
1093
+ `new WebSocket(url, offered)`. What is offered is who the terminal is, so an
1094
+ env that drops it connects as nobody. `held()` is for a host whose browser
1095
+ may keep the session itself: asked after an upgrade is answered, `true`
1096
+ makes the wire let go of the token it offered, `false` makes it store it. A
1097
+ host with `held` also asks to be handed sign-ins sealed. A host without it
1098
+ stores a token as soon as it is handed one. `key` names the terminal's seat
1099
+ in the socket's address.
1100
+ - `browserEnv({ tokenKey?, cookie? }?): WireEnv` — the default host: url
1101
+ derived from `window.location`, the page's WebSocket, and the session
1102
+ wherever the page can have it kept. Served by the app it talks to, the page
1103
+ does not keep it: the browser does, in a cookie the page cannot read, and
1104
+ `held` reads the flag beside it. Anywhere else — another origin, a browser
1105
+ that refuses cookies — the token is in localStorage under `tokenKey`
1106
+ (default `nisc.token`). `tokenKey` is also the seat, and the cookie's name.
1107
+ `cookie` is accepted and does nothing: it kept a script-readable copy of the
1108
+ token for the server to draw the page from, and the page is now drawn from
1109
+ the browser's own cookie.
960
1110
  - `readDocumentSnapshot(doc?): DocumentSnapshot | undefined` — the snapshot a
961
1111
  server-drawn page carries (`{ frame, trees, principal, seed?, path?, live? }`),
962
1112
  or `undefined` for a page that carries none. Never throws. `principal` is a
@@ -1014,7 +1164,7 @@ outage ago.
1014
1164
 
1015
1165
  ```typescript
1016
1166
  import { createWire } from '@niscorp/moss/client';
1017
- const wire = createWire(); // browser host; token from localStorage
1167
+ const wire = createWire(); // browser host; the session is the browser's to keep
1018
1168
  wire.subscribe(() => render(wire.snapshot()));
1019
1169
  wire.dispatch('main', { type: 'ui:click', ref: 'save' });
1020
1170
  ```
package/README.md CHANGED
@@ -51,6 +51,11 @@ const server = await serve(app, { pool, db, session: 'sessions', port: 3000 });
51
51
  // boot refusal here (createServer runs inside serve); HTTP + ws in one
52
52
  ```
53
53
 
54
+ The charter defines a role named `public`. It is what a request with no session
55
+ resolves to, and a signed-in principal with no assignment. `public: []` grants
56
+ nothing. A charter without the role still boots, and those requests then fail
57
+ with `Unknown role "public"`.
58
+
54
59
  ## The first screen can arrive with the page
55
60
 
56
61
  A page request can be answered with the screen itself: the caller's shell is
@@ -78,7 +83,7 @@ server.get('*', async (c) => {
78
83
  ```typescript
79
84
  // the browser's entry
80
85
  const drawn = readDocumentSnapshot();
81
- createWire({ env: browserEnv({ cookie: true }), ...(drawn ? { initial: drawn } : {}) });
86
+ createWire({ env: browserEnv(), ...(drawn ? { initial: drawn } : {}) });
82
87
  ```
83
88
 
84
89
  Who may keep the page follows from who asked: drawn for nobody it is the same
@@ -153,7 +158,7 @@ never in moss core.
153
158
 
154
159
  - **`/catalog`** — the application, resolved for you (granted action ids + a version token).
155
160
  - **`/api/vex`, `/api/<resource>/vex`** — reads and writes, locked (replay-only), scoped per principal. The model never writes SQL; the policy it can't see enforces access.
156
- - **the socket** — the authority channel: the served frame and per-canvas `RenderNode` trees down, `NovaEvent`s up. Session lifecycle (sign-in grant, sign-out revoke) rides it. Two optional reductions sit under it, both invisible to an app: `permessage-deflate` (on by default) and frame deltas (`shellFrameDelta`, off) — a changed canvas sent as a checksummed delta against the frame the terminal already holds, 1–4% of the frame on an in-place change. See [DOCS.md § Wire size](DOCS.md#wire-size).
161
+ - **the socket** — the authority channel: the served frame and per-canvas `RenderNode` trees down, `NovaEvent`s up (a message a terminal sends is at most 256 KB). Session lifecycle (sign-in grant, sign-out revoke) rides it. Two optional reductions sit under it, both invisible to an app: `permessage-deflate` (on by default) and frame deltas (`shellFrameDelta`, off) — a changed canvas sent as a checksummed delta against the frame the terminal already holds, 1–4% of the frame on an in-place change. See [DOCS.md § Wire size](DOCS.md#wire-size).
157
162
 
158
163
  ## Tables and documents, versioned
159
164
 
@@ -1,4 +1,4 @@
1
- import { applyDelta, frameHash, PROTOCOL_MIN, PROTOCOL, CLOSE_PROTOCOL_MISMATCH, CLOSE_SIGNED_OUT, CLOSE_INVALID_TOKEN } from './chunk-ZOEUEMDX.js';
1
+ import { heldCookieName, PROTOCOL, offerToken, applyDelta, frameHash, PROTOCOL_MIN, CLOSE_PROTOCOL_MISMATCH, CLOSE_SIGNED_OUT, CLOSE_INVALID_TOKEN } from './chunk-HOZID4EM.js';
2
2
 
3
3
  // src/client/index.ts
4
4
  var SNAPSHOT_ELEMENT_ID = "nisc-snapshot";
@@ -25,21 +25,11 @@ var readDocumentSnapshot = (doc = document) => {
25
25
  var EMPTY = { frame: [], trees: /* @__PURE__ */ new Map() };
26
26
  var browserEnv = (config = {}) => {
27
27
  const tokenKey = config.tokenKey ?? "nisc.token";
28
- const mirror = (token) => {
29
- if (config.cookie !== true) return;
30
- try {
31
- const secure = window.location.protocol === "https:" ? "; Secure" : "";
32
- document.cookie = token === null ? `${encodeURIComponent(tokenKey)}=; Path=/; Max-Age=0; SameSite=Lax${secure}` : `${encodeURIComponent(tokenKey)}=${encodeURIComponent(token)}; Path=/; SameSite=Lax${secure}`;
33
- } catch {
34
- }
35
- };
36
28
  return {
37
29
  tokens: {
38
30
  load: () => {
39
31
  try {
40
- const token = window.localStorage.getItem(tokenKey);
41
- mirror(token);
42
- return token;
32
+ return window.localStorage.getItem(tokenKey);
43
33
  } catch {
44
34
  return null;
45
35
  }
@@ -49,17 +39,27 @@ var browserEnv = (config = {}) => {
49
39
  window.localStorage.setItem(tokenKey, token);
50
40
  } catch {
51
41
  }
52
- mirror(token);
53
42
  },
54
43
  clear: () => {
55
44
  try {
56
45
  window.localStorage.removeItem(tokenKey);
57
46
  } catch {
58
47
  }
59
- mirror(null);
60
- }
48
+ try {
49
+ document.cookie = `${encodeURIComponent(tokenKey)}=; Path=/; Max-Age=0; SameSite=Lax${window.location.protocol === "https:" ? "; Secure" : ""}`;
50
+ } catch {
51
+ }
52
+ },
53
+ held: () => {
54
+ try {
55
+ return document.cookie.split("; ").includes(`${heldCookieName(tokenKey, window.location.port)}=1`);
56
+ } catch {
57
+ return false;
58
+ }
59
+ },
60
+ ...config.tokenKey !== void 0 ? { key: tokenKey } : {}
61
61
  },
62
- socket: (url) => new WebSocket(url),
62
+ socket: ({ url, offered }) => new WebSocket(url, offered),
63
63
  defaultUrl: () => {
64
64
  const scheme = window.location.protocol === "https:" ? "wss" : "ws";
65
65
  return `${scheme}://${window.location.host}/socket`;
@@ -69,12 +69,15 @@ var browserEnv = (config = {}) => {
69
69
  var createWire = (config = {}) => {
70
70
  const env = config.env ?? browserEnv();
71
71
  let token = env.tokens.load();
72
- const initial = config.initial !== void 0 && config.initial.principal === (token !== null) ? config.initial : void 0;
72
+ const initial = config.initial !== void 0 && config.initial.principal === (token !== null || env.tokens.held?.() === true) ? config.initial : void 0;
73
73
  let snapshot = initial === void 0 ? EMPTY : { frame: initial.frame, trees: new Map(Object.entries(initial.trees)) };
74
74
  let seed = initial?.seed;
75
75
  const path = config.path ?? config.initial?.path;
76
76
  let status = "connecting";
77
77
  let incompatible = false;
78
+ let leaving = false;
79
+ let sealed = null;
80
+ let unsealed = false;
78
81
  let socket = null;
79
82
  let retry;
80
83
  let attempts = 0;
@@ -99,14 +102,15 @@ var createWire = (config = {}) => {
99
102
  if (disposed) return;
100
103
  setStatus("connecting");
101
104
  bases.clear();
102
- const params = [];
103
- if (token !== null) params.push(`token=${encodeURIComponent(token)}`);
104
- params.push(`protocol=${PROTOCOL}`);
105
+ const params = [`protocol=${PROTOCOL}`];
106
+ if (env.tokens.key !== void 0) params.push(`key=${encodeURIComponent(env.tokens.key)}`);
107
+ if (leaving) params.push("leave=1");
108
+ if (env.tokens.held !== void 0 && !unsealed) params.push("sealed=1");
105
109
  if (config.delta === true) params.push("delta=1");
106
110
  if (seed !== void 0) params.push(`seed=${encodeURIComponent(seed)}`);
107
111
  seed = void 0;
108
112
  if (path !== void 0) params.push(`path=${encodeURIComponent(path)}`);
109
- const ws = env.socket(`${url()}${params.length > 0 ? `?${params.join("&")}` : ""}`);
113
+ const ws = env.socket({ url: `${url()}?${params.join("&")}`, offered: offerToken(token, sealed) });
110
114
  socket = ws;
111
115
  ws.onopen = () => {
112
116
  attempts = 0;
@@ -142,13 +146,25 @@ var createWire = (config = {}) => {
142
146
  publishSnapshot({ ...snapshot, frame: data.tree });
143
147
  } else if (data.type === "session" && typeof data.token === "string") {
144
148
  become(data.token);
149
+ } else if (data.type === "session" && typeof data.sealed === "string") {
150
+ become(null, data.sealed);
145
151
  } else if (data.type === "error") {
152
+ if (data.code === "seal_not_kept") unsealed = true;
146
153
  console.warn(`[moss/wire] server error${data.code !== void 0 ? ` (${data.code})` : ""}: ${data.message ?? ""}`);
147
154
  } else if (data.type === "hello" && (data.protocol ?? 1) < PROTOCOL_MIN) {
148
155
  console.error(`[moss/wire] the server speaks protocol ${data.protocol ?? 1}; this terminal needs ${PROTOCOL_MIN}\u2013${PROTOCOL}. The server has not been updated yet.`);
149
156
  incompatible = true;
150
157
  ws.close();
151
- } else if (data.type !== "hello" && data.type !== "catalog") {
158
+ } else if (data.type === "hello") {
159
+ leaving = false;
160
+ sealed = null;
161
+ if (token !== null && env.tokens.held !== void 0) {
162
+ if (env.tokens.held()) {
163
+ env.tokens.clear();
164
+ token = null;
165
+ } else env.tokens.save(token);
166
+ }
167
+ } else if (data.type !== "catalog") {
152
168
  console.warn(`[moss/wire] unhandled server message: ${data.type}`);
153
169
  }
154
170
  };
@@ -160,6 +176,7 @@ var createWire = (config = {}) => {
160
176
  }
161
177
  setStatus("closed");
162
178
  if (e.code === CLOSE_SIGNED_OUT || e.code === CLOSE_INVALID_TOKEN) {
179
+ leaving = e.code === CLOSE_SIGNED_OUT;
163
180
  become(null);
164
181
  return;
165
182
  }
@@ -173,9 +190,10 @@ var createWire = (config = {}) => {
173
190
  const delay = ceiling / 2 + Math.random() * (ceiling / 2);
174
191
  retry = setTimeout(connect, delay);
175
192
  };
176
- const become = (next) => {
177
- if (next === null) env.tokens.clear();
178
- else env.tokens.save(next);
193
+ const become = (next, handedSealed = null) => {
194
+ sealed = handedSealed;
195
+ if (handedSealed !== null) ; else if (next === null) env.tokens.clear();
196
+ else if (env.tokens.held === void 0) env.tokens.save(next);
179
197
  token = next;
180
198
  clearTimeout(retry);
181
199
  attempts = 0;
@@ -234,5 +252,5 @@ var createWire = (config = {}) => {
234
252
  };
235
253
 
236
254
  export { SNAPSHOT_ELEMENT_ID, browserEnv, createWire, readDocumentSnapshot };
237
- //# sourceMappingURL=chunk-J72N3EMJ.js.map
238
- //# sourceMappingURL=chunk-J72N3EMJ.js.map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AA,QAAA,GAAW,CAAA;AACX,MAAA,OAAA,EAAQ;AAAA,IACV,CAAA;AAAA,IACA,SAAS,MAAM;AACb,MAAA,QAAA,GAAW,IAAA;AACX,MAAA,MAAA,GAAS,QAAA;AACT,MAAA,YAAA,CAAa,KAAK,CAAA;AAClB,MAAA,MAAA,EAAQ,KAAA,EAAM;AAAA,IAChB;AAAA,GACF;AACF","file":"chunk-4T6KAXBP.js","sourcesContent":["import type { NovaEvent, RenderNode } from '@niscorp/nova';\nimport { CLOSE_INVALID_TOKEN, CLOSE_PROTOCOL_MISMATCH, CLOSE_SIGNED_OUT, PROTOCOL, PROTOCOL_MIN, offerToken } from '../socket';\nimport { applyDelta, frameHash } from '../delta';\nimport type { DeltaOp } from '../delta';\nimport { heldCookieName } from '../session-cookie';\n\n// ═══════════════════════════════════════════════════════════════\n// The wire — moss's protocol client, the other end of ../socket. Plain\n// code: a token slot, a websocket with reconnect, and session lifecycle —\n// a `session` message (login redeemed server-side) stores the token and\n// reconnects authenticated; a 4403 close clears it and reconnects\n// anonymous (the lock screen is the anonymous principal's application,\n// served like everything else). Rendering the snapshot is the app's\n// (framework's) business; nothing framework-shaped lives here.\n//\n// The wire never reaches for globals: everything host-shaped — where the\n// token lives, how a socket is constructed, what url \"here\" means — comes\n// in as a `WireEnv`. `browserEnv` (the default) is localStorage + location;\n// `./node` ships `nodeEnv` (a token file, an explicit url). The socket API\n// itself is WHATWG-standard in every host (browser, Node ≥22, Bun), so an\n// env only constructs it.\n// ═══════════════════════════════════════════════════════════════\n\n// Where the session token lives between connects.\nexport type WireTokenStore = {\n load: () => string | null;\n save: (token: string) => void;\n clear: () => void;\n // A host whose BROWSER may keep the session itself, in a cookie the page\n // cannot read (../session-cookie.ts): whether it does, right now. Asked\n // after an upgrade is answered — if it does, the wire lets go of the token\n // it offered and nothing is stored; if not, the token is stored as ever. A\n // host without this (a process) always keeps its own.\n held?: () => boolean;\n // Which of the browser's sessions this terminal is, when not the default one\n // — a seat. Named in the socket's address; it is the cookie's name.\n key?: string;\n};\n\n// The host seam: what the wire would otherwise take from globals.\nexport type WireEnv = {\n tokens: WireTokenStore;\n // Construct a socket for this url, offering these subprotocols —\n // `new WebSocket(url, offered)` in every host. What is offered is who the\n // terminal is (socket.ts): a host that drops it connects as nobody.\n socket: (upgrade: { url: string; offered: string[] }) => WebSocket;\n // the socket url when `config.url` is absent\n defaultUrl: () => string;\n};\n\nexport type WireConfig = {\n // The socket url; default: `env.defaultUrl()`.\n url?: string;\n // The host environment; default: `browserEnv()`.\n env?: WireEnv;\n // Accept canvas frames as DELTAS against the last frame received (default:\n // off). Both ends have to want it: this tells the server the terminal can\n // rebuild them, and the server sends them only if `runtime.shellFrameDelta`\n // is on and the delta is decisively smaller. Nothing else about the terminal\n // changes — the snapshot it renders is identical either way. See DOCS.md\n // § Frame deltas.\n delta?: boolean;\n // The screen the page already shows — the snapshot a server-rendered\n // document carries (`readDocumentSnapshot`). The wire starts from it instead\n // of from nothing, so the first render matches the HTML and the first frames\n // off the socket confirm it rather than paint it. Absent, or made for\n // somebody else (see `DocumentSnapshot.principal`): the wire starts empty, as\n // it always has.\n initial?: DocumentSnapshot;\n // The path this terminal is on, named on the socket so the server can tell a\n // page's terminal from the app's (a page is served a shell of its own, for\n // this connection alone). Default: the path the page's snapshot was drawn\n // for; a page that was not drawn on the server passes `location.pathname`.\n path?: string;\n};\n\n// What a server-rendered document carries beside its HTML.\nexport type DocumentSnapshot = {\n frame: RenderNode[];\n trees: Record<string, RenderNode[]>;\n // The id seed an anonymous page's shell was built under; named on the first\n // connect so the socket's shell mints the same instance ids.\n seed?: string;\n // Whether the page was rendered for a signed-in principal. A page rendered\n // for nobody is not this terminal's screen if it holds a token, and the other\n // way round — the wire then starts empty rather than from the wrong screen.\n principal: boolean;\n // The path it was drawn for.\n path?: string;\n // False when nothing on the drawn screen can still happen: the trees are the\n // whole of it, and the wire opens no socket at all (status `static`). Absent\n // is live — a page that does not say is not concluded finished.\n live?: boolean;\n};\n\n// The id of the element a document carries its snapshot in.\nexport const SNAPSHOT_ELEMENT_ID = 'nisc-snapshot';\n\n// Read the snapshot out of the page, if it has one. Never throws: a page\n// without one, or with one that does not parse, is a page that was not\n// server-rendered, and the terminal starts the way it always has.\nexport const readDocumentSnapshot = (doc: Pick<Document, 'getElementById'> = document): DocumentSnapshot | undefined => {\n try {\n const text = doc.getElementById(SNAPSHOT_ELEMENT_ID)?.textContent;\n if (text === undefined || text === null || text === '') return undefined;\n const parsed: unknown = JSON.parse(text);\n if (parsed === null || typeof parsed !== 'object') return undefined;\n const { frame, trees, seed, principal, path, live } = parsed as Record<string, unknown>;\n if (!Array.isArray(frame) || trees === null || typeof trees !== 'object' || typeof principal !== 'boolean') return undefined;\n return {\n frame: frame as RenderNode[],\n trees: trees as Record<string, RenderNode[]>,\n principal,\n ...(typeof seed === 'string' ? { seed } : {}),\n ...(typeof path === 'string' ? { path } : {}),\n ...(typeof live === 'boolean' ? { live } : {}),\n };\n } catch {\n return undefined;\n }\n};\n\nexport type WireSnapshot = {\n // the frame: the canvas ARRANGEMENT — a served layout whose CanvasSlot\n // markers resolve against `trees`\n frame: RenderNode[];\n // the current tree per canvas id\n trees: ReadonlyMap<string, RenderNode[]>;\n};\n\n// The socket's health, as a renderer needs it: `connecting` (a connect is in\n// flight or scheduled), `open`, `closed` (lost; a retry will flip it back to\n// connecting). Status changes notify subscribers like snapshot changes do —\n// a terminal that renders nothing on a dead socket is indistinguishable from\n// a working terminal rendering an empty app, so the state must be readable.\n// `incompatible`: this terminal and the server speak protocols the other\n// cannot (see PROTOCOL in ../socket). Terminal state — the wire stops retrying,\n// because every retry would speak the same protocol again.\n// `static`: the page was drawn on the server and nothing on it can still\n// happen, so no socket was opened. Not a fault and not a wait — `reset` (or a\n// token arriving) connects after all.\nexport type WireStatus = 'connecting' | 'open' | 'closed' | 'incompatible' | 'static';\n\nexport type Wire = {\n subscribe: (listener: () => void) => () => void;\n snapshot: () => WireSnapshot;\n status: () => WireStatus;\n // an event from inside a canvas, tagged with the canvas it came from\n dispatch: (canvasId: string, event: NovaEvent) => void;\n publish: (channel: string, payload?: unknown) => void;\n // Ask the server to throw this session's shell away and serve a fresh one —\n // the escape from a wedged shell, and the only one that can work. The shell\n // is SERVER state keyed by principal: dropping the token here would just\n // hand us a throwaway anonymous shell, and signing back in would reattach\n // to the same wreck. On a dead socket this reconnects instead, which is the\n // same recovery one layer down.\n reset: () => void;\n // Undo the shell's last navigation. Fire-and-forget by design: what comes\n // back is whatever canvases moved, over the same stream every other change\n // arrives on — the terminal never holds a location to keep in step.\n back: () => void;\n // Jump to an ancestor already on a canvas's stack — one message the shell\n // executes atomically, rather than N back gestures racing each other.\n popTo: (canvas: string, instance: string) => void;\n dispose: () => void;\n};\n\ntype ClientMessage =\n | { type: 'event'; canvas: string; event: Record<string, unknown> }\n | { type: 'publish'; channel: string; payload?: unknown }\n | { type: 'resync' }\n | { type: 'reset' }\n | { type: 'back' }\n | { type: 'popTo'; canvas: string; instance: string };\n\nconst EMPTY: WireSnapshot = { frame: [], trees: new Map() };\n\n// The browser host: url derived from location, the page's WebSocket, and the\n// session wherever this page can have it kept.\n//\n// SERVED BY THE APP IT TALKS TO, the page does not keep it: the browser does,\n// in a cookie the page cannot read, which the server writes in its answer to\n// the upgrade (../session-cookie.ts). `held` is all the page sees of it. A\n// token this page is handed is offered once and let go of; nothing is stored.\n//\n// ANYWHERE ELSE — another origin, a browser that refuses cookies — the token\n// is in localStorage, as it always was. The try/catches keep a storage-less\n// context (private mode, sandboxed iframe) alive: the session then lives for\n// this page only.\n//\n// `cookie` did one thing — keep a script-readable copy of the token for the\n// server to draw the page from — and is no longer needed: the page is drawn\n// from the browser's own cookie. It is accepted and does nothing.\nexport const browserEnv = (config: { tokenKey?: string; cookie?: boolean } = {}): WireEnv => {\n const tokenKey = config.tokenKey ?? 'nisc.token';\n return {\n tokens: {\n load: () => {\n try {\n return window.localStorage.getItem(tokenKey);\n } catch {\n return null;\n }\n },\n save: (token) => {\n try {\n window.localStorage.setItem(tokenKey, token);\n } catch {\n /* storage unavailable — the session lives for this page only */\n }\n },\n clear: () => {\n try {\n window.localStorage.removeItem(tokenKey);\n } catch {\n /* nothing stored, nothing to clear */\n }\n // the copy an earlier build kept beside it, where script could read it\n try {\n document.cookie = `${encodeURIComponent(tokenKey)}=; Path=/; Max-Age=0; SameSite=Lax${window.location.protocol === 'https:' ? '; Secure' : ''}`;\n } catch {\n /* no document, or cookies refused */\n }\n },\n held: () => {\n try {\n return document.cookie.split('; ').includes(`${heldCookieName(tokenKey, window.location.port)}=1`);\n } catch {\n return false;\n }\n },\n ...(config.tokenKey !== undefined ? { key: tokenKey } : {}),\n },\n socket: ({ url, offered }) => new WebSocket(url, offered),\n defaultUrl: () => {\n const scheme = window.location.protocol === 'https:' ? 'wss' : 'ws';\n return `${scheme}://${window.location.host}/socket`;\n },\n };\n};\n\nexport const createWire = (config: WireConfig = {}): Wire => {\n const env = config.env ?? browserEnv();\n\n let token = env.tokens.load();\n // The page's own snapshot, when it was rendered for who this terminal is —\n // signed in (holding a token, or its browser a session), or neither.\n // Anything else is somebody else's screen and is not started from.\n const initial = config.initial !== undefined && config.initial.principal === (token !== null || env.tokens.held?.() === true) ? config.initial : undefined;\n let snapshot: WireSnapshot = initial === undefined ? EMPTY : { frame: initial.frame, trees: new Map(Object.entries(initial.trees)) };\n // Named on the FIRST connect only: it belongs to the page's own shell, and a\n // later connect (a retry, another principal) is not that shell.\n let seed = initial?.seed;\n const path = config.path ?? config.initial?.path;\n let status: WireStatus = 'connecting';\n // Set by a protocol mismatch in either direction; ends the reconnect loop.\n let incompatible = false;\n // Signed out, and not yet heard by the server: the next upgrade says so,\n // because what the browser holds may be a token that still resolves.\n let leaving = false;\n // A sign-in handed to this terminal SEALED: its browser keeps the session,\n // so the page is given something it can carry to the next upgrade and cannot\n // open. Offered until an upgrade is answered. `unsealed`: this browser turned\n // out not to keep the cookie that opens one, so the terminal stops asking.\n let sealed: string | null = null;\n let unsealed = false;\n let socket: WebSocket | null = null;\n let retry: ReturnType<typeof setTimeout> | undefined;\n // Consecutive failed connects — resets to 0 the moment one opens. Drives the\n // reconnect backoff so a dead server is polled ever more slowly, not every\n // second forever.\n let attempts = 0;\n let disposed = false;\n const listeners = new Set<() => void>();\n const publishSnapshot = (next: WireSnapshot): void => {\n snapshot = next;\n for (const listener of listeners) listener();\n };\n const setStatus = (next: WireStatus): void => {\n if (status === next) return;\n status = next;\n for (const listener of listeners) listener();\n };\n\n const url = (): string => config.url ?? env.defaultUrl();\n\n // Only on an OPEN socket, and never queued — the posture `back` and `popTo`\n // always had, now everybody's. A page rendered server-side is on screen\n // before the socket is, so there is a moment in which something can be\n // pressed with nothing to send it over: that press is dropped, not held. An\n // intention replayed against a screen that may have moved is worse than one\n // lost, and a browser socket that is still connecting throws on `send`.\n const send = (message: ClientMessage): void => {\n if (socket === null || status !== 'open') return;\n socket.send(JSON.stringify(message));\n };\n\n // The last `render` message TEXT per canvas — the base a delta is written\n // against, byte for byte as the server holds it. Only populated when deltas\n // are on; cleared on every connect, because attaching serves whole frames and\n // a base carried across a reconnect is a base the server never assumed.\n const bases = new Map<string, string>();\n\n const connect = (): void => {\n if (disposed) return;\n setStatus('connecting');\n bases.clear();\n // The address says nothing about who this is — it is what every proxy on\n // the way writes down. The token is offered with the socket, below.\n const params: string[] = [`protocol=${PROTOCOL}`];\n if (env.tokens.key !== undefined) params.push(`key=${encodeURIComponent(env.tokens.key)}`);\n if (leaving) params.push('leave=1');\n if (env.tokens.held !== undefined && !unsealed) params.push('sealed=1');\n if (config.delta === true) params.push('delta=1');\n if (seed !== undefined) params.push(`seed=${encodeURIComponent(seed)}`);\n seed = undefined;\n if (path !== undefined) params.push(`path=${encodeURIComponent(path)}`);\n const ws = env.socket({ url: `${url()}?${params.join('&')}`, offered: offerToken(token, sealed) });\n socket = ws;\n // A connection that opens is a healthy connection: forget the backoff.\n ws.onopen = () => {\n attempts = 0;\n setStatus('open');\n };\n ws.onmessage = (e) => {\n const text = String(e.data);\n const data = JSON.parse(text) as {\n type: string;\n canvas?: string;\n tree?: RenderNode[];\n ops?: DeltaOp[];\n hash?: number;\n protocol?: number;\n token?: string;\n sealed?: string;\n code?: string;\n message?: string;\n };\n if (data.type === 'render' && data.canvas !== undefined && data.tree !== undefined) {\n if (config.delta === true) bases.set(data.canvas, text);\n publishSnapshot({ ...snapshot, trees: new Map(snapshot.trees).set(data.canvas, data.tree) });\n } else if (data.type === 'render-delta' && data.canvas !== undefined && data.ops !== undefined && data.hash !== undefined) {\n // Rebuild, then PROVE it. Anything short of the server's own checksum\n // and we would be rendering a frame nobody authored — so every failure\n // here takes the one exit that always works: ask for whole frames.\n // Never a thrown error and never a partial apply; a terminal that goes\n // blank on a bad delta is worse than one that costs a round trip.\n const base = bases.get(data.canvas);\n let rebuilt: string | null = null;\n if (base !== undefined) {\n try {\n const candidate = applyDelta(base, data.ops);\n rebuilt = frameHash(candidate) === data.hash ? candidate : null;\n } catch {\n rebuilt = null;\n }\n }\n if (rebuilt === null) {\n console.warn(`[moss/wire] canvas \"${data.canvas}\": delta did not rebuild the server's frame — resyncing.`);\n bases.delete(data.canvas);\n send({ type: 'resync' });\n return;\n }\n const frame = JSON.parse(rebuilt) as { canvas: string; tree: RenderNode[] };\n bases.set(data.canvas, rebuilt);\n publishSnapshot({ ...snapshot, trees: new Map(snapshot.trees).set(data.canvas, frame.tree) });\n } else if (data.type === 'frame' && data.tree !== undefined) {\n publishSnapshot({ ...snapshot, frame: data.tree });\n } else if (data.type === 'session' && typeof data.token === 'string') {\n // Login redeemed server-side: become that principal.\n become(data.token);\n } else if (data.type === 'session' && typeof data.sealed === 'string') {\n // The same, for a terminal whose browser keeps the session: nothing\n // this page can read — it is carried to the next upgrade as it is.\n become(null, data.sealed);\n } else if (data.type === 'error') {\n if (data.code === 'seal_not_kept') unsealed = true;\n // Diagnostics, not authority — surfaced, never swallowed: a wire that\n // silently stops updating is the worst thing to debug. `invalid_token`\n // arrives here too, from the server's revalidation pass, and it is\n // worth the line: the AUTHORITY is the 4401 close that follows (see\n // onclose), and this is the breadcrumb saying the session expired\n // rather than the network dropping.\n console.warn(`[moss/wire] server error${data.code !== undefined ? ` (${data.code})` : ''}: ${data.message ?? ''}`);\n } else if (data.type === 'hello' && (data.protocol ?? 1) < PROTOCOL_MIN) {\n // The other half of the handshake: the server checked this terminal on\n // the upgrade; this checks the server. One that predates the question\n // sends no `protocol` and speaks 1.\n console.error(`[moss/wire] the server speaks protocol ${data.protocol ?? 1}; this terminal needs ${PROTOCOL_MIN}–${PROTOCOL}. The server has not been updated yet.`);\n incompatible = true;\n ws.close();\n } else if (data.type === 'hello') {\n // The upgrade has been answered, so a browser that keeps the session\n // itself now does: the token this terminal offered is let go of, and\n // the page holds it no longer. One that does not (another origin,\n // cookies refused) leaves it with the terminal, stored as it always was.\n leaving = false;\n sealed = null;\n if (token !== null && env.tokens.held !== undefined) {\n if (env.tokens.held()) {\n env.tokens.clear();\n token = null;\n } else env.tokens.save(token);\n }\n } else if (data.type !== 'catalog') {\n // catalog is known and deliberately ignored (the terminal is\n // grant-blind — it renders what it is served, never what it may do);\n // anything else is protocol drift worth a shout.\n console.warn(`[moss/wire] unhandled server message: ${data.type}`);\n }\n };\n // The socket is ephemeral, the shell is durable: reconnect re-sends\n // current state. Two application close codes are recoveries, not retries —\n // SIGNED_OUT (a deliberate revoke) and INVALID_TOKEN (the stored token went\n // stale; retrying WITH it would loop forever) both drop the token and\n // reconnect anonymous (the served lock screen). Every other close backs off\n // and retries carrying the current token.\n ws.onclose = (e) => {\n if (incompatible || e.code === CLOSE_PROTOCOL_MISMATCH) {\n incompatible = true;\n setStatus('incompatible');\n return;\n }\n setStatus('closed');\n if (e.code === CLOSE_SIGNED_OUT || e.code === CLOSE_INVALID_TOKEN) {\n leaving = e.code === CLOSE_SIGNED_OUT;\n become(null);\n return;\n }\n if (!disposed) scheduleReconnect();\n };\n };\n\n // Exponential backoff with jitter, capped: a dead server is polled ever more\n // slowly (never faster than ~½s, never slower than the cap), and the jitter\n // spreads a thundering herd of terminals reconnecting on the same outage.\n const RECONNECT_CAP_MS = 30_000;\n const scheduleReconnect = (): void => {\n const ceiling = Math.min(RECONNECT_CAP_MS, 1000 * 2 ** attempts);\n attempts += 1;\n const delay = ceiling / 2 + Math.random() * (ceiling / 2);\n retry = setTimeout(connect, delay);\n };\n\n // A different principal — possibly none — is a different application:\n // store the token, blank the screen, reconnect. A host whose browser may\n // keep the session stores nothing yet: the token is offered, and what\n // becomes of it is settled when the upgrade is answered (`hello`, above).\n const become = (next: string | null, handedSealed: string | null = null): void => {\n // whatever was being offered sealed is over: taken, or refused\n sealed = handedSealed;\n if (handedSealed !== null) {\n /* nothing this page can read, so nothing to store */\n } else if (next === null) env.tokens.clear();\n else if (env.tokens.held === undefined) env.tokens.save(next);\n token = next;\n clearTimeout(retry);\n attempts = 0; // a new principal is a fresh session — start backoff clean\n publishSnapshot(EMPTY);\n const old = socket;\n socket = null;\n if (old !== null) {\n old.onclose = null;\n old.close();\n }\n connect();\n };\n\n // A drawn page with nothing left to happen needs no socket. Everything that\n // would later need one — `reset`, a token arriving — connects by itself.\n if (initial?.live === false) status = 'static';\n else connect();\n\n return {\n subscribe: (listener) => {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n snapshot: () => snapshot,\n status: () => status,\n dispatch: (canvasId, event) => send({ type: 'event', canvas: canvasId, event: event as unknown as Record<string, unknown> }),\n publish: (channel, payload) => send(payload === undefined ? { type: 'publish', channel } : { type: 'publish', channel, payload }),\n // Only on an open socket, and deliberately not queued: a back pressed while\n // the connection is down is a gesture about a screen the person is no\n // longer being served, and replaying it on reconnect would move them\n // somewhere they asked to go some seconds and one outage ago.\n back: () => {\n if (socket === null || status !== 'open') return;\n send({ type: 'back' });\n },\n // Same posture as `back`: only on an open socket, never queued. A jump\n // replayed on reconnect would move somebody to where they wanted to be\n // one outage ago.\n popTo: (canvas: string, instance: string) => {\n if (socket === null || status !== 'open') return;\n send({ type: 'popTo', canvas, instance });\n },\n reset: () => {\n if (disposed) return;\n // Open: ask the server, and the fresh frame arrives on this same socket.\n // Asked of our OWN status rather than `readyState`, because the socket\n // is whatever the host env constructed and the status is ours.\n if (socket !== null && status === 'open') {\n send({ type: 'reset' });\n return;\n }\n // Not open: the backoff may have us waiting half a minute for a retry,\n // and somebody pressing reset is telling us they are waiting NOW. Jump\n // the queue — reattaching re-sends the current trees anyway.\n clearTimeout(retry);\n attempts = 0;\n connect();\n },\n dispose: () => {\n disposed = true;\n status = 'closed'; // sync truth for late readers; no notification after dispose\n clearTimeout(retry);\n socket?.close();\n },\n };\n};\n"]}