@ultimat3/realtime 31.51.0 → 31.53.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CLAUDE.md CHANGED
@@ -1,7 +1,7 @@
1
1
  # @ultimat3/realtime — agent notes
2
2
 
3
3
  Tier 3 package. Channels, live queries, local-first sync. One protocol for all three.
4
- A rule marked `†` has its full text in [`docs/history/realtime-rules.md`](../../docs/history/realtime-rules.md).
4
+ `†`: full text in [`docs/history/realtime-rules.md`](../../docs/history/realtime-rules.md).
5
5
 
6
6
  ## Boundary
7
7
 
@@ -95,6 +95,8 @@ A rule marked `†` has its full text in [`docs/history/realtime-rules.md`](../.
95
95
  a non-positive or non-finite value takes the default (`query-window.test.ts`).
96
96
  - The retained change window stores **pre-policy** patches; resume re-filters them per subscriber,
97
97
  outside the lane, against the live window.
98
+ - **`cursor.ids` is trusted only under the node's `sig`** (`cursor-sign.ts`, SERVER-only):
99
+ mismatch = cold start; none = legacy, counted.
98
100
  - **`desynced` is a mark with a reader**: the next delivery re-snapshots out of the shared window,
99
101
  then clears it; `result.refill` is checked BEFORE the mark. A quiet query's three other readers
100
102
  (drain, a landed read, `repairMarked`): `docs/history/realtime.md` (2026-11-09). A bus
@@ -276,7 +278,7 @@ A rule marked `†` has its full text in [`docs/history/realtime-rules.md`](../.
276
278
  per socket; the engine reaps ports on the longer of its own and the node's.
277
279
  - **There is ONE `backoffDelay`, `@ultimat3/core`'s, counted from 1** — `policyDelay()` passes a
278
280
  `ReconnectBackoff` (core's `RetryPolicy` minus `attempts`/`timeBudgetMs`) to it; `bun run flight-copies` refuses a second curve.
279
- - Never a bare `Error`. Never `any`. Never `Date.now()` — take a `Clock` (`monotonic()` for durations).
281
+ - Never `Date.now()` — take a `Clock` (`monotonic()` for durations).
280
282
 
281
283
  ## The page boot
282
284
 
@@ -300,15 +302,13 @@ side: `client*.ts`, `socket-*.ts`, `sync-worker.ts`, `record-*.ts`, `page-*.ts`,
300
302
  ## Commands
301
303
 
302
304
  ```
303
- bun test ./packages/realtime/ # from the REPO ROOT; the ./ keeps examples/dummy out
304
- bun run typecheck
305
+ bun test ./packages/realtime/ # REPO ROOT; ./ keeps examples/dummy out
305
306
  ```
306
307
 
307
-
308
- Changing a frame shape means a fixture in `sync-protocol.test.ts` (the round-trip test fails
308
+ Changing a frame shape means a fixture in `sync-protocol.test.ts` (the round trip fails
309
309
  without one) and bumping `PROTOCOL_VERSION` **when an old frame becomes unreadable in either
310
310
  direction**. `decode` is a whitelist: an additive optional field, or removing a field read through
311
311
  `list()`, is free; removing a field read through `str()`/`num()` (which throw) is a bump.
312
312
 
313
- Why each rule is shaped so, and browser bytes per hook (re-measure before quoting):
313
+ Why, and bytes per hook (re-measure):
314
314
  [`docs/history/realtime.md`](../../docs/history/realtime.md).
package/README.md CHANGED
@@ -100,7 +100,7 @@ class — stay on `.`.
100
100
  |---|---|---|
101
101
  | tier 1 | `./server` | `ChannelHub`, `PresenceRegistry`, `SyncSocket`, `SocketRegistry`; `publishChannelEvent` — a channel event from a job or an action, on the bus the boot installed |
102
102
  | a bus driver | `./adapter` | `Transport` and its parts (`TransportHandler`, `TransportSet`, `TransportSetEntry`, `TransportSubscription`), the errors a driver throws (`TransportUnavailableError`, also on `.`; `TransportProtocolError`, only on this entry), and `installChannelTransport` — the boot's installer and `@ultimat3/testing`'s seam, on no other entry. The offline stores (`LocalStore` / `openLocalStore` / `pageLocalStore` / `memoryLocalStore()`, `QueueStore` / `memoryQueueStore()`, `RecordStoreOptions`, `SignalFactory`) are on `.`: no `runtime.ts` field takes one. An app hands its bus to `transport` in `apps/<app>/runtime.ts`, never to the installer |
103
- | tier 2 | `./server` | `LiveQueryRegistry`, `memoryChangeFeed()`, `postgresChangeFeed()`, `selectChangeFeed`, `changeFeedReplicator`, `postgresAdvisoryLock()`, `matcherFor` |
103
+ | tier 2 | `./server` | `LiveQueryRegistry`, its resume-cursor events `CursorDistrusted` / `CursorTrustOptions` (`onUnsignedCursor`, `onCursorRefused`), `memoryChangeFeed()`, `postgresChangeFeed()`, `selectChangeFeed`, `changeFeedReplicator`, `postgresAdvisoryLock()`, `matcherFor` |
104
104
  | replication | `./server` | `parsePgUrl`, `bunPgStream`, `entityRow`, `changeLsn`, `commitPositionOf` |
105
105
  | the in-process change source | `./server` | `startLiveReplicator` — a repository's own writes (core's `entity.row` / `entity.bulk` bus events, subscribed) as `ChangeEvent`s, for the embedded database `x dev` runs on (PGlite has no walsender). `ChangeEvent.table` is the entity's TABLE on it as on the WAL decoder and `recordPublisher`, so an `entity(name, { table })` reaches channels and live windows (25.0.0). Moved from `@ultimat3/testing`, which no longer re-exports it |
106
106
  | fanout | `./server` | `Transport`, `InProcessTransport`, `NatsTransport`, `selectTransport`, `subjectMatches` |
@@ -413,6 +413,7 @@ answer nothing, and the entry would be born reading no table.
413
413
  | the source names ANOTHER org | `X_TENANCY_ACTOR_MISMATCH`, as over HTTP — it was answered, until 2026-10 |
414
414
  | a subscriber with no org reads a tenant-scoped table | `X_TENANCY_ACTOR_ORG_REQUIRED`, as over HTTP |
415
415
  | a reconnect presents a cursor minted in another org's window | a cold start: one snapshot, never a replay of that window's patches |
416
+ | a reconnect presents a cursor whose `sig` is not its own | a cold start, for the same reason: `holds` is the node's word ([below](#limits-stated-plainly)) |
416
417
  | the actor changes org mid-connection | `reauthorize` re-seats the subscription on its new tenant's window and sends that snapshot |
417
418
 
418
419
  The read's actor is `serviceActor({ id: 'live-window', orgId })` — the shape a job run gets. Never
@@ -789,6 +790,26 @@ made it — a key already queued collapses as always, and nothing queued is ever
789
790
  every subscriber learned the id and the instant of every *other* tenant's row as it was deleted,
790
791
  on a query whose `visible` rule had never let them see one. A subscriber that holds the row is
791
792
  told it is gone; one that does not gets nothing, counted as `rowsDenied`.
793
+ - **`holds` is the node's word, not the client's: a live cursor is signed** (`As of 2026-11`,
794
+ #1280). `holds` is read off `cursor.ids`, and on a resume the cursor is client data — a forged id
795
+ was handed that row's `delete`, which says the row exists and when it went. Every cursor the node
796
+ hands out carries `sig` (`cursor-sign.ts`, server-only): a keyed fingerprint, under the app's
797
+ signing secret, of the window, the lsn, the ids and the subscriber's actor and tenant. It rides
798
+ down in `snapshot.cursor.sig` and on each `patch.sig`; the client stores the last one and echoes
799
+ it on `subscribe`, and never computes one. On a resume:
800
+
801
+ | The cursor's `sig` | The resume | Counted as |
802
+ |---|---|---|
803
+ | this cursor's, for this subscriber | decided from the cursor, ids trusted — so a row really held and revoked while away is still withdrawn | — |
804
+ | present, and not this cursor's — edited ids or lsn, another subscriber's, another window's, a rotated secret, or a value that is no sig at all (kept by the decoder as a marker, never read as absent) | a **cold start**: one snapshot, nothing replayed | `registry.cursorsRefused`, `onCursorRefused` |
805
+ | absent — no `sig` key: a client built before the signature, or one that stripped its own | as before 2026-11, ids trusted | `registry.unsignedCursors`, `onUnsignedCursor` |
806
+
807
+ The absent row is the gap that stays open on `main` and closes on `next`, where an unsigned
808
+ cursor cold-starts too; `unsignedCursors` counts resumes sending no `sig` (old builds, or tampering); at zero, none is left. The ids
809
+ are never intersected with what the policy admits now — that is the fix that loses the withdraw.
810
+ A subscriber's own OLDER cursor still verifies: it is a position it really held. Signing costs
811
+ one keyed fingerprint per subscriber per patch frame (≈ 11 µs, measured 2026-11-27); the id
812
+ digest is cached per ids array, so an update re-signs only the lsn.
792
813
  - **`postgresChangeFeed()` decodes `pgoutput` off a real slot** — its own Postgres v3 client
793
814
  (SCRAM-SHA-256, in-band TLS, CopyBoth), no driver dependency. It preflights `wal_level`, the
794
815
  publication, every entity's replica identity and the slot — in that order, because the identity
@@ -975,7 +996,7 @@ onRequest })` is the Bun client. Every rule (credential, caps, frame limit, beat
975
996
  | `device-hooks.ts` | `onOpen` / `onClose`, beside the socket path, one lane per socket |
976
997
  | `device-ledger.ts` | the open sockets in the bus's shared set, so a dead node's still close |
977
998
  | `device-bus.ts` | where a device is and how a request reaches it and comes back |
978
- | `device-wire.ts` | both hops' frames and the frame limit |
999
+ | `device-wire.ts` | both hops' frames, the frame limit and `DEVICE_WIRE_VERSION` — the node's `hello` carries it as `v`, and an agent older than the node refuses with `X_DEVICE_WIRE_VERSION` (`DeviceWireVersionError`) rather than misread a frame |
979
1000
  | `device-agent.ts` | the device's half, on Bun |
980
1001
  | `device-errors.ts` | its refusals |
981
1002
  | `device-declarer.ts` | the file that called `deviceSocket()`, so `x dev` refuses another module taking a path |
@@ -990,7 +1011,7 @@ onRequest })` is the Bun client. Every rule (credential, caps, frame limit, beat
990
1011
  `X_LIVE_SERVER_RENDER` · `X_LIVE_QUERY_UNKNOWN` ·
991
1012
  `X_LIVE_REPLICA_IDENTITY` ·
992
1013
  `X_SOCKET_UNAUTHENTICATED` · `X_SOCKET_AUTH_UNAVAILABLE` ·
993
- `X_DEVICE_OFFLINE` · `X_DEVICE_REQUEST_TIMEOUT` · `X_DEVICE_FRAME_TOO_LARGE` · `X_NOT_IMPLEMENTED` ·
1014
+ `X_DEVICE_OFFLINE` · `X_DEVICE_REQUEST_TIMEOUT` · `X_DEVICE_FRAME_TOO_LARGE` · `X_DEVICE_WIRE_VERSION` · `X_NOT_IMPLEMENTED` ·
994
1015
  `X_TIMEOUT`
995
1016
 
996
1017
  `X_NOT_IMPLEMENTED` and `X_TIMEOUT` are **borrowed** from `@ultimat3/core`, which owns and titles
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ultimat3/realtime",
3
- "version": "31.51.0",
3
+ "version": "31.53.0",
4
4
  "description": "Three-tier realtime: channels, live queries, local-first sync — one protocol, one mutator shape",
5
5
  "keywords": [
6
6
  "ultimate",
@@ -34,10 +34,13 @@
34
34
  "./page-runtime": "./src/page-runtime.ts",
35
35
  "./page-runtime-wait": "./src/page-runtime-wait.ts",
36
36
  "./server": "./src/server.ts",
37
- "./sync-worker": "./src/sync-worker.ts"
37
+ "./sync-worker": "./src/sync-worker.ts",
38
+ "./device-wire-frames": "./src/device-wire-frames.ts",
39
+ "./wire/device-v1.json": "./wire/device-v1.json"
38
40
  },
39
41
  "files": [
40
42
  "src",
43
+ "wire",
41
44
  "!src/**/*.test.ts",
42
45
  "!src/**/*-fixture.ts",
43
46
  "CLAUDE.md",
@@ -52,10 +55,10 @@
52
55
  "test": "bun test"
53
56
  },
54
57
  "dependencies": {
55
- "@ultimat3/core": "31.51.0",
56
- "@ultimat3/entity": "31.51.0",
57
- "@ultimat3/policy": "31.51.0",
58
- "@ultimat3/query": "31.51.0",
58
+ "@ultimat3/core": "31.53.0",
59
+ "@ultimat3/entity": "31.53.0",
60
+ "@ultimat3/policy": "31.53.0",
61
+ "@ultimat3/query": "31.53.0",
59
62
  "nats": "2.29.3"
60
63
  }
61
64
  }
@@ -93,7 +93,10 @@ export function applyFrame(frame: Frame, target: ClientFrameTarget): void {
93
93
  // is a tier-1 channel frame's, so it never rewinds one.
94
94
  if (registration.cursor && frame.lsn !== '') {
95
95
  const next = advance(registration.cursor, frame.patches, frame.lsn, target.now());
96
- registration.cursor = next;
96
+ // The node's sig for the cursor this patch leaves it on, stored as sent and never
97
+ // computed here. `advance` carries none over, so a patch without one clears it: the
98
+ // old sig covered the old position, and echoed beside the new one it reads as forged.
99
+ registration.cursor = frame.sig === undefined ? next : { ...next, sig: frame.sig };
97
100
  }
98
101
  registration.state = 'live';
99
102
  // The writes the frame names settle in the window's own batch, as a `records` frame's do.
@@ -0,0 +1,134 @@
1
+ // The node's signature on a live cursor (#1280): `cursor.ids` is client data the gate reads as
2
+ // "rows this subscriber holds", so a forged id is handed that row's `delete`. SERVER-ONLY — it
3
+ // reads the app's signing secret, and no page module may import it.
4
+ //
5
+ // Why a signature and not a filter: intersecting the ids with what the policy admits NOW loses the
6
+ // designed case — a row really held, revoked while away, must still be withdrawn — and client data
7
+ // cannot tell the two apart. A cursor the node signed can.
8
+
9
+ import { compareFingerprint, keyedFingerprint } from '@ultimat3/core';
10
+ import type { LiveCursor } from './cursor';
11
+ import { liveTenantOf } from './live-tenant';
12
+ import type { Subscriber } from './subscriber-gate';
13
+
14
+ /** The key purpose: a cursor sig is a MAC under a key no other keyed fingerprint shares. */
15
+ const PURPOSE = 'realtime-live-cursor';
16
+
17
+ /**
18
+ * `signed`: the node minted this sig over exactly this cursor, for this subscriber. `unsigned`: no
19
+ * sig — a client older than the signature. `refused`: a sig is present and is not this cursor's —
20
+ * tampered ids or lsn, another subscriber's or another window's, a rotated secret, or no sig format
21
+ * at all (the decoder keeps one as `CURSOR_SIG_MALFORMED`, never as absent). Only the node mints
22
+ * one, so no honest client ever sends the third.
23
+ */
24
+ export type CursorVerdict = 'signed' | 'unsigned' | 'refused';
25
+
26
+ /**
27
+ * SHA-256 over the SORTED ids as JSON, per ids ARRAY. Sorted, so the same set signs the same in any
28
+ * order; JSON, so two lists that only concatenate alike do not. `advance` hands an update's cursor
29
+ * the array it had, so the common change re-signs a new lsn over a digest already taken — and a
30
+ * copy is another array, so tampered ids are never answered from the cache of the honest ones.
31
+ */
32
+ const digests = new WeakMap<readonly string[], string>();
33
+
34
+ function idsDigest(ids: readonly string[]): string {
35
+ const cached = digests.get(ids);
36
+ if (cached !== undefined) return cached;
37
+ const digest = new Bun.CryptoHasher('sha256')
38
+ .update(JSON.stringify([...ids].sort()))
39
+ .digest('hex');
40
+ digests.set(ids, digest);
41
+ return digest;
42
+ }
43
+
44
+ /**
45
+ * What a sig covers, as one JSON array — fixed positions, so no field can be read as another, and
46
+ * `null` is never the string a client could name an actor. A string and not an object on purpose:
47
+ * this runs per subscriber per change, and `keyedFingerprint` canonicalises an object key by key
48
+ * (18.9 µs against 10.7 µs for this, measured 2026-11-27).
49
+ *
50
+ * `at` is absent on purpose — the client rewrites it on every patch. The subscriber is its actor
51
+ * and tenant, never its `sid`: a reconnect subscribes under a new one. Every anonymous subscriber
52
+ * is one subject, which is what a row policy sees them as too.
53
+ */
54
+ function signedFields(cursor: LiveCursor, who: Subscriber): string {
55
+ return JSON.stringify([
56
+ cursor.qid,
57
+ cursor.lsn,
58
+ idsDigest(cursor.ids),
59
+ who.actor === null ? null : who.actor.id,
60
+ liveTenantOf(who.actor),
61
+ ]);
62
+ }
63
+
64
+ /** The cursor as the node hands it out: the same position, signed for the subscriber it is for. */
65
+ export function signCursor(cursor: LiveCursor, who: Subscriber): LiveCursor & { sig: string } {
66
+ return { ...cursor, sig: keyedFingerprint(signedFields(cursor, who), PURPOSE) };
67
+ }
68
+
69
+ /** What a cursor a client SENT is worth. Compared in constant time (`compareFingerprint`). */
70
+ export function cursorVerdict(cursor: LiveCursor, who: Subscriber): CursorVerdict {
71
+ if (cursor.sig === undefined) return 'unsigned';
72
+ const match = compareFingerprint(cursor.sig, signedFields(cursor, who), PURPOSE);
73
+ // `unverifiable` — another key, or no format this build reads — is refused with a mismatch: the
74
+ // cost is one snapshot after a secret rotation, and trusting it would be the forgery's way in.
75
+ return match === 'match' ? 'signed' : 'refused';
76
+ }
77
+
78
+ /** One cursor a resume was not decided from as signed. Carries no ids: they are the forgery. */
79
+ export interface CursorDistrusted {
80
+ readonly qid: string;
81
+ readonly sid: string;
82
+ readonly actorId: string | null;
83
+ }
84
+
85
+ export interface CursorTrustOptions {
86
+ /**
87
+ * `live.cursors_unsigned`. A resume from a cursor with NO sig key: a client built before the
88
+ * signature — or one that stripped its own, which reads the same. Served as it always was, ids
89
+ * trusted; the count is how many such resumes are left for `next` to cold-start.
90
+ */
91
+ readonly onUnsignedCursor?: (event: CursorDistrusted) => void;
92
+ /**
93
+ * `live.cursors_refused`. A cursor whose sig is not its own, answered with a cold start. No
94
+ * honest client produces one except across a signing-secret rotation, so a steady rate is
95
+ * somebody editing cursors.
96
+ */
97
+ readonly onCursorRefused?: (event: CursorDistrusted) => void;
98
+ }
99
+
100
+ /** Both counters and the one decision behind them. Owned per registry, as `SubscriberGate` is. */
101
+ export class CursorTrust {
102
+ readonly #options: CursorTrustOptions;
103
+ #unsigned = 0;
104
+ #refused = 0;
105
+
106
+ constructor(options: CursorTrustOptions) {
107
+ this.#options = options;
108
+ }
109
+
110
+ /** Resumes from an unsigned cursor since boot. */
111
+ get unsignedCursors(): number {
112
+ return this.#unsigned;
113
+ }
114
+
115
+ /** Cursors whose sig did not match since boot, each answered with a cold start. */
116
+ get cursorsRefused(): number {
117
+ return this.#refused;
118
+ }
119
+
120
+ /** Whether a resume may be decided from this cursor. `false` is a cold start, never an error. */
121
+ admits(cursor: LiveCursor, who: Subscriber): boolean {
122
+ const verdict = cursorVerdict(cursor, who);
123
+ if (verdict === 'signed') return true;
124
+ const event = { qid: cursor.qid, sid: who.sid, actorId: who.actor?.id ?? null };
125
+ if (verdict === 'unsigned') {
126
+ this.#unsigned += 1;
127
+ this.#options.onUnsignedCursor?.(event);
128
+ return true;
129
+ }
130
+ this.#refused += 1;
131
+ this.#options.onCursorRefused?.(event);
132
+ return false;
133
+ }
134
+ }
package/src/cursor.ts CHANGED
@@ -10,6 +10,34 @@ import { CursorStaleError } from './page-errors';
10
10
  /** Ids are bounded so a cursor stays small enough to ship on every `subscribe` frame. */
11
11
  export const CURSOR_ID_LIMIT = 512;
12
12
 
13
+ /**
14
+ * The longest `sig` the wire reads. The node mints 44 characters (`cursor-sign.ts`); the ceiling is
15
+ * here, not there, because the decoder is a page module and the signer must never be one.
16
+ */
17
+ export const CURSOR_SIG_MAX = 64;
18
+
19
+ /** What a `sig` may be spelled with. */
20
+ const CURSOR_SIG = /^[a-z0-9:]+$/;
21
+
22
+ /**
23
+ * What the decoder keeps of a `sig` that was SENT and is no sig: one character outside the sig
24
+ * alphabet, so it is no node's signature and verifies for nobody (`cursor-sign.ts` refuses it).
25
+ */
26
+ export const CURSOR_SIG_MALFORMED = '!';
27
+
28
+ /**
29
+ * A wire value as a `sig`. Only an ABSENT key is no sig — a client older than the signature. A
30
+ * present value that is no sig (wrong type, `null`, too long, another alphabet) is never read as
31
+ * absent: only the node mints one, so no honest client sends it, and dropping it would let a
32
+ * tampered cursor pass as a legacy one with its ids trusted. It becomes `CURSOR_SIG_MALFORMED` —
33
+ * bounded, and a cold start rather than a refused frame.
34
+ */
35
+ export function wireSig(value: unknown): string | undefined {
36
+ if (value === undefined) return undefined;
37
+ if (typeof value !== 'string' || value.length > CURSOR_SIG_MAX) return CURSOR_SIG_MALFORMED;
38
+ return CURSOR_SIG.test(value) ? value : CURSOR_SIG_MALFORMED;
39
+ }
40
+
13
41
  /**
14
42
  * What a resume decides from, and nothing else. `digest` and `count` were here until 2026-08-24
15
43
  * and were written by every snapshot, encoded and validated on every `subscribe` frame, and read
@@ -26,6 +54,14 @@ export interface LiveCursor {
26
54
  /** Last-seen row ids, truncated at `CURSOR_ID_LIMIT`. */
27
55
  readonly ids: readonly string[];
28
56
  readonly at: number;
57
+ /**
58
+ * The node's signature over `{ qid, lsn, ids, subscriber }` — never `at`, which is the client's
59
+ * clock. Minted and verified by the sync node alone (`cursor-sign.ts`, server-only); a client
60
+ * stores the one its last frame carried and echoes it, and never computes one. `makeCursor` and
61
+ * `advance` build a cursor WITHOUT it, so a sig cannot outlive the ids it was taken over.
62
+ * Optional and additive, no `PROTOCOL_VERSION` bump: a node that mints none is resumed as before.
63
+ */
64
+ readonly sig?: string;
29
65
  }
30
66
 
31
67
  export interface ReconnectBudget {
@@ -3,7 +3,14 @@
3
3
  // jittered backoff — or at the slot a draining node's `reconnect` frame assigns.
4
4
 
5
5
  import { reportError } from '@ultimat3/core';
6
- import { bytesOverLimit, type DeviceInbound, decodeNodeFrame } from './device-wire';
6
+ import { CLOSE } from './close-codes';
7
+ import { DeviceWireVersionError } from './device-errors';
8
+ import {
9
+ bytesOverLimit,
10
+ DEVICE_WIRE_VERSION,
11
+ type DeviceInbound,
12
+ decodeNodeFrame,
13
+ } from './device-wire';
7
14
  import type { JsonValue } from './json';
8
15
  import {
9
16
  defaultBackoff,
@@ -109,8 +116,20 @@ export function deviceAgent(options: DeviceAgentOptions): DeviceAgent {
109
116
  if (current !== socket || typeof data !== 'string') return;
110
117
  const frame = decodeNodeFrame(data);
111
118
  if (frame === undefined) return;
112
- if (frame.type === 'hello') beat(frame.heartbeatMs);
113
- else if (frame.type === 'request') void answer(frame.id, frame.frame);
119
+ if (frame.type === 'hello') {
120
+ if (frame.v > DEVICE_WIRE_VERSION) {
121
+ // A newer node's frames are read by guessing: close instead, and let the backoff redial —
122
+ // a rolling deploy may land the next dial on a node that still speaks this version.
123
+ reportError(new DeviceWireVersionError({ spoken: DEVICE_WIRE_VERSION, node: frame.v }), {
124
+ source: 'realtime',
125
+ scope: { operation: 'device.agent_wire_version' },
126
+ });
127
+ current.close(CLOSE.versionSkew, 'X_DEVICE_WIRE_VERSION');
128
+ return;
129
+ }
130
+ attempt = 0;
131
+ beat(frame.heartbeatMs);
132
+ } else if (frame.type === 'request') void answer(frame.id, frame.frame);
114
133
  else if (frame.type === 'frame') options.onFrame?.(frame.frame);
115
134
  else if (frame.type === 'reconnect') {
116
135
  // The node's slot, not the backoff: the spread is what keeps a fleet restart off one node.
@@ -118,7 +137,7 @@ export function deviceAgent(options: DeviceAgentOptions): DeviceAgent {
118
137
  cancelRedial?.();
119
138
  cancelRedial = null;
120
139
  redialIn(frame.afterMs);
121
- current.close(4002, 'reconnect');
140
+ current.close(CLOSE.drain, 'reconnect');
122
141
  }
123
142
  };
124
143
 
@@ -140,8 +159,9 @@ export function deviceAgent(options: DeviceAgentOptions): DeviceAgent {
140
159
  socket = current;
141
160
  current.onopen = () => {
142
161
  if (current !== socket) return;
162
+ // Not `attempt = 0`: an open socket is not a healthy one. A node that answers with a wire this
163
+ // agent cannot read closes it at once, and only an accepted `hello` earns a fresh backoff.
143
164
  open = true;
144
- attempt = 0;
145
165
  };
146
166
  current.onmessage = (event) => receive(current, event.data);
147
167
  current.onclose = () => {
@@ -102,3 +102,14 @@ export function deviceAuthUnavailable(detail: string): RealtimeError {
102
102
  fix: 'x doctor --json',
103
103
  });
104
104
  }
105
+
106
+ /** The node's `hello` named a wire version newer than this agent speaks. */
107
+ export class DeviceWireVersionError extends RealtimeError {
108
+ constructor(args: { spoken: number; node: number }) {
109
+ super({
110
+ code: 'X_DEVICE_WIRE_VERSION',
111
+ cause: `the node's hello carries device wire v${args.node}, and this agent speaks up to v${args.spoken}, so it cannot read the node's frames`,
112
+ fix: 'bun update @ultimat3/realtime # on the agent side, then restart it — or pin the node to the version the device firmware speaks',
113
+ });
114
+ }
115
+ }
@@ -15,6 +15,7 @@ import {
15
15
  type BusRequest,
16
16
  bytesOverLimit,
17
17
  DEVICE_FRAME_MAX_BYTES,
18
+ DEVICE_WIRE_VERSION,
18
19
  type DeviceOutbound,
19
20
  decodeDeviceFrame,
20
21
  } from './device-wire';
@@ -107,6 +108,7 @@ export class DeviceHost implements DeviceBusHandlers {
107
108
  this.#byDevice.set(key, socketId);
108
109
  this.#send(ws, {
109
110
  type: 'hello',
111
+ v: DEVICE_WIRE_VERSION,
110
112
  heartbeatMs: this.#options.heartbeatMs,
111
113
  maxFrameBytes: DEVICE_FRAME_MAX_BYTES,
112
114
  });
@@ -0,0 +1,69 @@
1
+ // The device wire as data: every frame a non-JS client (a firmware, a Go or Rust agent) must read
2
+ // or refuse the same way this package does. `scripts/device-wire.ts` generates
3
+ // `wire/device-v1.json` from this table; `device-wire-conformance.test.ts` runs it through both
4
+ // decoders. Named `-frames`, not `-fixture`: a `*-fixture.ts` is not published, and this is.
5
+
6
+ import { DEVICE_FRAME_MAX_BYTES, DEVICE_WIRE_VERSION } from './device-wire';
7
+
8
+ /** `device-to-node` is what `decodeDeviceFrame` reads; `node-to-device` is `decodeNodeFrame`'s. */
9
+ export type DeviceWireDirection = 'device-to-node' | 'node-to-device';
10
+
11
+ export interface DeviceWireFixture {
12
+ readonly name: string;
13
+ readonly direction: DeviceWireDirection;
14
+ /** The exact websocket text frame. */
15
+ readonly text: string;
16
+ /** `false`: a reader must drop the frame, never act on a guess. */
17
+ readonly valid: boolean;
18
+ }
19
+
20
+ const up = (name: string, text: string, valid = true): DeviceWireFixture => ({
21
+ name,
22
+ direction: 'device-to-node',
23
+ text,
24
+ valid,
25
+ });
26
+ const down = (name: string, text: string, valid = true): DeviceWireFixture => ({
27
+ name,
28
+ direction: 'node-to-device',
29
+ text,
30
+ valid,
31
+ });
32
+
33
+ export const DEVICE_WIRE_FIXTURES: readonly DeviceWireFixture[] = [
34
+ up('beat', '{"type":"beat"}'),
35
+ up('frame', '{"type":"frame","frame":{"temp":21}}'),
36
+ up('frame-null-payload', '{"type":"frame","frame":null}'),
37
+ up('response', '{"type":"response","id":"r_1-A","frame":{"ok":true}}'),
38
+ up('not-json', 'beat', false),
39
+ up('not-an-object', '[1,2]', false),
40
+ up('unknown-type', '{"type":"hello"}', false),
41
+ up('frame-without-payload', '{"type":"frame"}', false),
42
+ up('response-without-id', '{"type":"response","frame":1}', false),
43
+ up('response-id-not-token-safe', '{"type":"response","id":"a b","frame":1}', false),
44
+ up('response-id-too-long', `{"type":"response","id":"${'a'.repeat(65)}","frame":1}`, false),
45
+ down(
46
+ 'hello',
47
+ `{"type":"hello","v":1,"heartbeatMs":10000,"maxFrameBytes":${DEVICE_FRAME_MAX_BYTES}}`,
48
+ ),
49
+ down('hello-without-v-reads-as-1', '{"type":"hello","heartbeatMs":10000,"maxFrameBytes":262144}'),
50
+ down(
51
+ 'hello-newer-version-decodes',
52
+ `{"type":"hello","v":${DEVICE_WIRE_VERSION + 1},"heartbeatMs":10000,"maxFrameBytes":262144}`,
53
+ ),
54
+ down('hello-v-not-a-number', '{"type":"hello","v":"1","heartbeatMs":1,"maxFrameBytes":1}', false),
55
+ down('hello-v-zero', '{"type":"hello","v":0,"heartbeatMs":1,"maxFrameBytes":1}', false),
56
+ down('hello-v-fractional', '{"type":"hello","v":1.5,"heartbeatMs":1,"maxFrameBytes":1}', false),
57
+ down('hello-without-heartbeat', '{"type":"hello","v":1,"maxFrameBytes":1}', false),
58
+ down('request', '{"type":"request","id":"q-7","frame":{"cmd":"status"}}'),
59
+ down('request-without-id', '{"type":"request","frame":1}', false),
60
+ down('frame', '{"type":"frame","frame":"ack"}'),
61
+ down('frame-without-payload', '{"type":"frame"}', false),
62
+ down('error', '{"type":"error","code":"X_FRAME_RATE_LIMIT"}'),
63
+ down('error-code-not-a-string', '{"type":"error","code":7}', false),
64
+ down('reconnect', '{"type":"reconnect","v":3,"afterMs":2500,"reason":"drain"}'),
65
+ down('reconnect-unknown-reason', '{"type":"reconnect","v":3,"afterMs":1,"reason":"nap"}', false),
66
+ down('reconnect-without-delay', '{"type":"reconnect","v":3,"reason":"drain"}', false),
67
+ down('unknown-type', '{"type":"mutate"}', false),
68
+ down('not-json', '{', false),
69
+ ];
@@ -13,6 +13,14 @@ import type { ReconnectFrame } from './sync-protocol';
13
13
  */
14
14
  export const DEVICE_FRAME_MAX_BYTES = 256 * 1024;
15
15
 
16
+ /**
17
+ * The device wire's version, spoken in the node's `hello` (`v`). A node newer than an agent says so
18
+ * there, and the agent refuses with `X_DEVICE_WIRE_VERSION` instead of misreading a frame. An
19
+ * additive optional field never bumps it; a changed or removed one does. A hello with no `v` is a
20
+ * node from before the field existed and reads as 1.
21
+ */
22
+ export const DEVICE_WIRE_VERSION = 1;
23
+
16
24
  /** What a device sends: a beat, a frame for `onFrame`, or the answer to a `request` by its id. */
17
25
  export type DeviceInbound =
18
26
  | { readonly type: 'beat' }
@@ -21,7 +29,12 @@ export type DeviceInbound =
21
29
 
22
30
  /** What a node sends a device. `reconnect` is the sync protocol's own frame, unchanged. */
23
31
  export type DeviceOutbound =
24
- | { readonly type: 'hello'; readonly heartbeatMs: number; readonly maxFrameBytes: number }
32
+ | {
33
+ readonly type: 'hello';
34
+ readonly v: number;
35
+ readonly heartbeatMs: number;
36
+ readonly maxFrameBytes: number;
37
+ }
25
38
  | { readonly type: 'request'; readonly id: string; readonly frame: JsonValue }
26
39
  | { readonly type: 'frame'; readonly frame: JsonValue }
27
40
  | { readonly type: 'error'; readonly code: string }
@@ -73,7 +86,9 @@ export function decodeNodeFrame(text: string): DeviceOutbound | undefined {
73
86
  case 'hello': {
74
87
  const { heartbeatMs, maxFrameBytes } = raw;
75
88
  if (typeof heartbeatMs !== 'number' || typeof maxFrameBytes !== 'number') return undefined;
76
- return { type: 'hello', heartbeatMs, maxFrameBytes };
89
+ const v = Object.hasOwn(raw, 'v') ? raw['v'] : 1;
90
+ if (typeof v !== 'number' || !Number.isInteger(v) || v < 1) return undefined;
91
+ return { type: 'hello', v, heartbeatMs, maxFrameBytes };
77
92
  }
78
93
  case 'request':
79
94
  return isId(raw['id']) && Object.hasOwn(raw, 'frame')
@@ -16,6 +16,7 @@ export const REALTIME_SERVER_OWNED_ERROR_CODES = [
16
16
  'X_REALTIME_PRODUCER_CONFLICT',
17
17
  'X_REPLICATION_SLOT_INVALIDATED',
18
18
  'X_REPLICATION_SLOT_RECREATED',
19
+ 'X_DEVICE_WIRE_VERSION',
19
20
  ] as const;
20
21
 
21
22
  export type RealtimeServerErrorCode = (typeof REALTIME_SERVER_OWNED_ERROR_CODES)[number];
@@ -30,6 +31,7 @@ export const REALTIME_SERVER_ERROR_TITLES: Readonly<Record<RealtimeServerErrorCo
30
31
  X_REALTIME_PRODUCER_CONFLICT: 'two kinds of producer carry one table on the change bus',
31
32
  X_REPLICATION_SLOT_INVALIDATED: 'the replication slot was invalidated',
32
33
  X_REPLICATION_SLOT_RECREATED: 'the replication slot was recreated',
34
+ X_DEVICE_WIRE_VERSION: 'a device spoke a wire version this agent does not',
33
35
  };
34
36
 
35
37
  // One unconditional call, as in `error-titles.ts`: a second claimant throws X_ERROR_CODE_DUPLICATE.
@@ -6,6 +6,7 @@
6
6
  import { type Clock, isWriteDigest } from '@ultimat3/core';
7
7
  import type { ChangeEvent } from './changefeed';
8
8
  import { advance, type LiveCursor, makeCursor, type ResumeSource } from './cursor';
9
+ import { signCursor } from './cursor-sign';
9
10
  import type { LiveRow, RowPatch } from './json';
10
11
  import type { LiveSubscription } from './live-contract';
11
12
  import { encodePatchFrame, samePatches } from './live-patch-encode';
@@ -155,15 +156,18 @@ export async function fanoutChange(
155
156
  continue;
156
157
  }
157
158
  if (allowed.length === 0) continue;
159
+ // Signed BEFORE the send, because the frame carries the sig of the cursor it leaves this
160
+ // subscriber on — and seated only once the frame left, as the unsigned cursor always was.
161
+ const next = signCursor(advance(subscription.cursor, allowed, change.lsn, change.at), who);
158
162
  let text: string;
159
163
  if (samePatches(allowed, result.patches)) {
160
164
  shared ??= JSON.stringify(result.patches);
161
- text = encodePatchFrame(subscription.sid, shared, change.lsn, writes);
165
+ text = encodePatchFrame(subscription.sid, shared, change.lsn, writes, next.sig);
162
166
  } else {
163
- text = encode(patchFrame(subscription.sid, allowed, change.lsn, writes));
167
+ text = encode(patchFrame(subscription.sid, allowed, change.lsn, writes, next.sig));
164
168
  }
165
169
  if (subscription.socket.sendEncoded(text)) {
166
- subscription.cursor = advance(subscription.cursor, allowed, change.lsn, change.at);
170
+ subscription.cursor = next;
167
171
  sent += 1;
168
172
  } else {
169
173
  subscription.socket.markDesynced(subscription.sid);
@@ -270,7 +274,10 @@ async function resnapshot(
270
274
  // cannot decide is not one to serve rows to, and the next change tries again.
271
275
  return false;
272
276
  }
273
- const cursor = makeCursor(entry.qid, entry.lsn, rows, deps.clock.now().getTime());
277
+ const cursor = signCursor(
278
+ makeCursor(entry.qid, entry.lsn, rows, deps.clock.now().getTime()),
279
+ who,
280
+ );
274
281
  const frame = snapshotFrame(entry, subscription.sid, rows, cursor, named);
275
282
  if (!subscription.socket.send(frame)) return false;
276
283
  subscription.cursor = cursor;
@@ -386,14 +393,17 @@ function retain(patch: RowPatch, write: string | null): RowPatch {
386
393
  /**
387
394
  * The one place a patch frame is built, so a live fanout and a delta resume cannot spell it two
388
395
  * ways. `writes` rides only when some keyed write made a patch here: an unkeyed change sends the
389
- * frame it always sent.
396
+ * frame it always sent. `sig` is the signature of the cursor these patches leave the subscriber on
397
+ * (`cursor-sign.ts`), last on the frame — `encodePatchFrame` spells the same order.
390
398
  */
391
399
  export function patchFrame(
392
400
  sid: string,
393
401
  patches: readonly RowPatch[],
394
402
  lsn: string,
395
403
  writes: readonly string[],
404
+ sig?: string,
396
405
  ): Frame {
397
406
  const base = { type: 'patch', v: PROTOCOL_VERSION, sid, patches, lsn } as const;
398
- return writes.length === 0 ? base : { ...base, writes };
407
+ const named = writes.length === 0 ? base : { ...base, writes };
408
+ return sig === undefined ? named : { ...named, sig };
399
409
  }
@@ -6,7 +6,7 @@ import type { RowPatch } from './json';
6
6
  import { PROTOCOL_VERSION } from './sync-protocol';
7
7
 
8
8
  /**
9
- * Byte-for-byte `encode(patchFrame(sid, patches, lsn, writes))` with `patches` already encoded:
9
+ * Byte-for-byte `encode(patchFrame(sid, patches, lsn, writes, sig))` with `patches` already encoded:
10
10
  * the same keys in the same order, and `JSON.stringify` is compositional with no indentation.
11
11
  * Pinned against the unshared spelling by `live-fanout.test.ts`.
12
12
  */
@@ -15,10 +15,12 @@ export function encodePatchFrame(
15
15
  patchesJson: string,
16
16
  lsn: string,
17
17
  writes: readonly string[],
18
+ sig?: string,
18
19
  ): string {
19
20
  const head = `{"type":"patch","v":${JSON.stringify(PROTOCOL_VERSION)},"sid":${JSON.stringify(sid)}`;
20
21
  const tail = writes.length === 0 ? '' : `,"writes":${JSON.stringify(writes)}`;
21
- return `${head},"patches":${patchesJson},"lsn":${JSON.stringify(lsn)}${tail}}`;
22
+ const signed = sig === undefined ? '' : `,"sig":${JSON.stringify(sig)}`;
23
+ return `${head},"patches":${patchesJson},"lsn":${JSON.stringify(lsn)}${tail}${signed}}`;
22
24
  }
23
25
 
24
26
  /** The gate let every patch through untouched: the shared encoding is this subscriber's too. */
@@ -3,10 +3,15 @@
3
3
 
4
4
  import type { Actor, Clock } from '@ultimat3/core';
5
5
  import type { ReconnectBudget, ResumeSource } from './cursor';
6
+ import type { CursorTrustOptions } from './cursor-sign';
6
7
  import type { SubscriberGateOptions } from './subscriber-gate';
7
8
  import type { Scheduler } from './thundering-herd';
8
9
 
10
+ // The cursor-trust hooks are members read off `CursorTrustOptions`, not a second `extends`: the
11
+ // heading is part of this interface's 31.x public API, and an added optional member is not.
9
12
  export interface LiveQueryRegistryOptions extends SubscriberGateOptions {
13
+ readonly onUnsignedCursor?: NonNullable<CursorTrustOptions['onUnsignedCursor']>;
14
+ readonly onCursorRefused?: NonNullable<CursorTrustOptions['onCursorRefused']>;
10
15
  readonly source: ResumeSource;
11
16
  readonly budget?: ReconnectBudget;
12
17
  readonly clock?: Clock;
package/src/live-query.ts CHANGED
@@ -10,6 +10,7 @@ import { type Clock, systemClock, uuidV7 } from '@ultimat3/core';
10
10
  import { queryHash } from '@ultimat3/query';
11
11
  import type { ChangeEvent } from './changefeed';
12
12
  import { type LiveCursor, makeCursor } from './cursor';
13
+ import { CursorTrust, signCursor } from './cursor-sign';
13
14
  import { LiveQueryUnknownError } from './errors';
14
15
  import type { JsonValue } from './json';
15
16
  import type { LiveQueryDefinition, LiveSubscription, SnapshotResult } from './live-contract';
@@ -44,6 +45,8 @@ export class LiveQueryRegistry {
44
45
  readonly #options: LiveQueryRegistryOptions;
45
46
  readonly #clock: Clock;
46
47
  readonly #gate: SubscriberGate;
48
+ /** Whether a resume may be decided from the cursor a client sent (`cursor-sign.ts`). */
49
+ readonly #trust: CursorTrust;
47
50
  /** What one lane needs, and nothing this class holds beyond it. */
48
51
  readonly #fanout: FanoutDeps;
49
52
  #lastLsn = '';
@@ -58,6 +61,7 @@ export class LiveQueryRegistry {
58
61
  this.#options = options;
59
62
  this.#clock = options.clock ?? systemClock;
60
63
  this.#gate = new SubscriberGate(options);
64
+ this.#trust = new CursorTrust(options);
61
65
  this.#entries = new LiveEntries(options);
62
66
  // The book owns the caps because it is the only thing that can answer them in O(1).
63
67
  this.#book = new SubscriptionBook(options);
@@ -75,6 +79,16 @@ export class LiveQueryRegistry {
75
79
  return this.#gate.gateFailures;
76
80
  }
77
81
 
82
+ /** `live.cursors_unsigned`: resumes from a cursor with no sig — a client older than #1280. */
83
+ get unsignedCursors(): number {
84
+ return this.#trust.unsignedCursors;
85
+ }
86
+
87
+ /** `live.cursors_refused`: cursors whose sig was not their own, each answered a cold start. */
88
+ get cursorsRefused(): number {
89
+ return this.#trust.cursorsRefused;
90
+ }
91
+
78
92
  /** `live.changes_stale`: changes at or below a window's own lsn, refused rather than folded. */
79
93
  get staleChanges(): number {
80
94
  return this.#counts.staleChanges;
@@ -232,8 +246,17 @@ export class LiveQueryRegistry {
232
246
  //
233
247
  // Nor is ANY cursor a position in a window known to have missed a change: the ring still
234
248
  // answers a delta for it, and that delta is the hole. A stale entry serves cold starts only.
235
- if (args.cursor && args.cursor.qid === qid && !entry.stale) {
236
- const who = { sid, actor: args.socket.actor };
249
+ //
250
+ // Nor is a cursor whose `sig` is not its own: its ids are read as rows this subscriber HOLDS,
251
+ // and a forged one is handed that row's `delete`. Asked last, so only a cursor that would
252
+ // otherwise resume is counted. One with no sig is a client older than the signature: resumed.
253
+ const who: Subscriber = { sid, actor: args.socket.actor };
254
+ if (
255
+ args.cursor &&
256
+ args.cursor.qid === qid &&
257
+ !entry.stale &&
258
+ this.#trust.admits(args.cursor, who)
259
+ ) {
237
260
  const resumed = await resumeOnto(
238
261
  {
239
262
  source: this.#options.source,
@@ -256,8 +279,8 @@ export class LiveQueryRegistry {
256
279
  }
257
280
 
258
281
  await pay();
259
- const fresh = await this.#read(entry, { sid, actor: args.socket.actor });
260
- const cursor = makeCursor(qid, fresh.lsn, fresh.rows, now);
282
+ const fresh = await this.#read(entry, who);
283
+ const cursor = signCursor(makeCursor(qid, fresh.lsn, fresh.rows, now), who);
261
284
  const subscription = this.#attachUnlessGone(entry, args.socket, sid, cursor);
262
285
  return { subscription, frame: snapshotFrame(entry, sid, fresh.rows, cursor) };
263
286
  }
@@ -11,6 +11,7 @@ import {
11
11
  type ResumeSource,
12
12
  resumeFrom,
13
13
  } from './cursor';
14
+ import { signCursor } from './cursor-sign';
14
15
  import type { RowPatch } from './json';
15
16
  import type { SnapshotResult } from './live-contract';
16
17
  import { type NamedWrite, patchFrame, snapshotFrame } from './live-fanout';
@@ -31,8 +32,9 @@ export interface ResumeOntoDeps {
31
32
 
32
33
  /**
33
34
  * The frame a resuming subscriber needs and the cursor it is seated under. The caller has already
34
- * established that `cursor` names THIS window: a cursor is client data, and one minted for another
35
- * window is a cold start, never a replay of a ring this window does not own.
35
+ * established that `cursor` names THIS window — a cursor is client data, and one minted for another
36
+ * window is a cold start, never a replay of a ring this window does not own — and that its `sig`,
37
+ * when it carries one, is this cursor's and this subscriber's (`CursorTrust.admits`).
36
38
  */
37
39
  export async function resumeOnto(
38
40
  deps: ResumeOntoDeps,
@@ -52,10 +54,8 @@ export async function resumeOnto(
52
54
  // behind a row this subscriber was given. Out of the ring's window there is nothing to name,
53
55
  // and a write left unnamed settles on its own HTTP answer.
54
56
  const named = retainedWrites(deps.source.since(entry.qid, cursor.lsn) ?? []);
55
- return {
56
- cursor: resumed.cursor,
57
- frame: snapshotFrame(entry, who.sid, resumed.rows, resumed.cursor, named),
58
- };
57
+ const fresh = signCursor(resumed.cursor, who);
58
+ return { cursor: fresh, frame: snapshotFrame(entry, who.sid, resumed.rows, fresh, named) };
59
59
  }
60
60
  // The gate decides about whole rows out of the shared window, and an entry nothing has read
61
61
  // yet has none — every patch would meet an empty window and be withheld. Filling is
@@ -76,9 +76,10 @@ export async function resumeOnto(
76
76
  // takes the "the subscriber holds this row" branch, and delivers a `delete` frame carrying
77
77
  // another tenant's row id and the instant it went. The leak that branch closes, re-opened
78
78
  // one layer up. `live-fanout.ts` advances over `allowed` for exactly this reason.
79
- const seated = advance(cursor, patches, resumed.cursor.lsn, now);
79
+ // Signed where it is seated: the sig the client sent covered the cursor it sent, not this one.
80
+ const seated = signCursor(advance(cursor, patches, resumed.cursor.lsn, now), who);
80
81
  const { bare, writes } = namedWrites(patches);
81
- return { cursor: seated, frame: patchFrame(who.sid, bare, seated.lsn, writes) };
82
+ return { cursor: seated, frame: patchFrame(who.sid, bare, seated.lsn, writes, seated.sig) };
82
83
  }
83
84
 
84
85
  /**
package/src/server.ts CHANGED
@@ -53,6 +53,8 @@ export { type ChannelDescription, describeChannels } from './channel-describe';
53
53
  // What a job or an action publishes an event with: the process's own bus, no hub needed.
54
54
  // Its installer is the boot's, on `./adapter` (`adapter.ts`), never here.
55
55
  export { publishChannelEvent } from './channel-publish';
56
+ // A resume's cursor as the node judged it; the signer itself is the registry's, never an export.
57
+ export type { CursorDistrusted, CursorTrustOptions } from './cursor-sign';
56
58
  export {
57
59
  type AgentDial,
58
60
  type AgentSocket,
@@ -64,6 +66,7 @@ export {
64
66
  DeviceFrameTooLargeError,
65
67
  DeviceOfflineError,
66
68
  DeviceRequestTimeoutError,
69
+ DeviceWireVersionError,
67
70
  } from './device-errors';
68
71
  export {
69
72
  DEVICE_NODE_LOST,
@@ -101,7 +104,11 @@ export type {
101
104
  DeviceUpgradeTarget,
102
105
  DeviceWsData,
103
106
  } from './device-upgrade';
104
- export { DEVICE_CLOSE_REASON_MAX_BYTES, DEVICE_FRAME_MAX_BYTES } from './device-wire';
107
+ export {
108
+ DEVICE_CLOSE_REASON_MAX_BYTES,
109
+ DEVICE_FRAME_MAX_BYTES,
110
+ DEVICE_WIRE_VERSION,
111
+ } from './device-wire';
105
112
  export { RealtimeTopologyError } from './errors';
106
113
  export {
107
114
  InProcessTransport,
@@ -14,7 +14,7 @@ import type {
14
14
  ChannelSubscribeTarget,
15
15
  ReplayGapFrame,
16
16
  } from './channel-wire';
17
- import type { LiveCursor } from './cursor';
17
+ import { type LiveCursor, wireSig } from './cursor';
18
18
  import {
19
19
  isParsedJsonObject,
20
20
  isRow,
@@ -153,6 +153,13 @@ export interface PatchFrame {
153
153
  * it always was — so no `PROTOCOL_VERSION` bump.
154
154
  */
155
155
  readonly writes?: readonly string[];
156
+ /**
157
+ * The node's signature over the cursor this subscriber holds AFTER folding these patches
158
+ * (`LiveCursor.sig`). The client stores it on its advanced cursor and echoes it on resume; a
159
+ * patch without one leaves that cursor unsigned. Additive and optional, for the reason `writes`
160
+ * is. A PRESENT value that is no sig is kept as `CURSOR_SIG_MALFORMED`, never read as absent.
161
+ */
162
+ readonly sig?: string;
156
163
  }
157
164
 
158
165
  export interface AckFrame {
@@ -285,7 +292,9 @@ export function decode(raw: string | Uint8Array): Frame {
285
292
  lsn: str(parsed, 'lsn'),
286
293
  } as const;
287
294
  const writes = writesOf(parsed, 'patch.writes');
288
- return writes.length === 0 ? base : { ...base, writes };
295
+ const named = writes.length === 0 ? base : { ...base, writes };
296
+ const sig = wireSig(parsed['sig']);
297
+ return sig === undefined ? named : { ...named, sig };
289
298
  }
290
299
  case 'ack':
291
300
  return {
@@ -388,7 +397,7 @@ function row(value: unknown): LiveRow {
388
397
 
389
398
  function cursor(value: unknown): LiveCursor {
390
399
  if (!isParsedJsonObject(value)) throw fail('cursor must be an object');
391
- return {
400
+ const base = {
392
401
  qid: str(value, 'qid'),
393
402
  lsn: str(value, 'lsn'),
394
403
  ids: list(value, 'ids', FRAME_LIMITS.cursorIds, 'cursor.ids').map((id) => {
@@ -397,6 +406,11 @@ function cursor(value: unknown): LiveCursor {
397
406
  }),
398
407
  at: num(value, 'at'),
399
408
  };
409
+ // Absent stays absent — a client older than the signature. Present and no sig is KEPT, as the
410
+ // marker that verifies for nobody: dropped, a tampered cursor read as a legacy one. Never a
411
+ // refused frame either way — the subscriber is served, from a cold start.
412
+ const sig = wireSig(value['sig']);
413
+ return sig === undefined ? base : { ...base, sig };
400
414
  }
401
415
 
402
416
  function patch(value: unknown): RowPatch {
package/src/type-pins.ts CHANGED
@@ -5,6 +5,8 @@
5
5
 
6
6
  import type { AsyncState, Row } from '@ultimat3/core';
7
7
  import type { LiveHandle, Unsubscribe } from './client-contract';
8
+ import type { CursorTrustOptions } from './cursor-sign';
9
+ import type { LiveQueryRegistryOptions } from './live-query-options';
8
10
  import type { QueryAccessor, QueryRef } from './use-query';
9
11
  import type { RecordAccessor, useRecords } from './use-record';
10
12
 
@@ -58,3 +60,18 @@ export type _RecordAccessorIsDisposable = Assert<
58
60
  [RecordAccessor<Row>] extends [Disposable] ? true : false
59
61
  >;
60
62
  export type _UnsubscribeIsDisposable = Assert<[Unsubscribe] extends [Disposable] ? true : false>;
63
+
64
+ /**
65
+ * `LiveQueryRegistryOptions` restates the two cursor-trust hooks as members rather than extending
66
+ * `CursorTrustOptions` (its heading is 31.51.0's public API): the registry hands its options to
67
+ * `CursorTrust`, so the two stay one shape or this is a build error.
68
+ */
69
+ export type _RegistryOptionsAreCursorTrustOptions = Assert<
70
+ LiveQueryRegistryOptions extends CursorTrustOptions ? true : false
71
+ >;
72
+ export type _RegistryHooksAreTheTrustHooks = Assert<
73
+ Equals<
74
+ Pick<LiveQueryRegistryOptions, keyof CursorTrustOptions>,
75
+ Pick<CursorTrustOptions, keyof CursorTrustOptions>
76
+ >
77
+ >;
@@ -0,0 +1,180 @@
1
+ {
2
+ "version": 1,
3
+ "maxFrameBytes": 262144,
4
+ "fixtures": [
5
+ {
6
+ "name": "beat",
7
+ "direction": "device-to-node",
8
+ "text": "{\"type\":\"beat\"}",
9
+ "valid": true
10
+ },
11
+ {
12
+ "name": "frame",
13
+ "direction": "device-to-node",
14
+ "text": "{\"type\":\"frame\",\"frame\":{\"temp\":21}}",
15
+ "valid": true
16
+ },
17
+ {
18
+ "name": "frame-null-payload",
19
+ "direction": "device-to-node",
20
+ "text": "{\"type\":\"frame\",\"frame\":null}",
21
+ "valid": true
22
+ },
23
+ {
24
+ "name": "response",
25
+ "direction": "device-to-node",
26
+ "text": "{\"type\":\"response\",\"id\":\"r_1-A\",\"frame\":{\"ok\":true}}",
27
+ "valid": true
28
+ },
29
+ {
30
+ "name": "not-json",
31
+ "direction": "device-to-node",
32
+ "text": "beat",
33
+ "valid": false
34
+ },
35
+ {
36
+ "name": "not-an-object",
37
+ "direction": "device-to-node",
38
+ "text": "[1,2]",
39
+ "valid": false
40
+ },
41
+ {
42
+ "name": "unknown-type",
43
+ "direction": "device-to-node",
44
+ "text": "{\"type\":\"hello\"}",
45
+ "valid": false
46
+ },
47
+ {
48
+ "name": "frame-without-payload",
49
+ "direction": "device-to-node",
50
+ "text": "{\"type\":\"frame\"}",
51
+ "valid": false
52
+ },
53
+ {
54
+ "name": "response-without-id",
55
+ "direction": "device-to-node",
56
+ "text": "{\"type\":\"response\",\"frame\":1}",
57
+ "valid": false
58
+ },
59
+ {
60
+ "name": "response-id-not-token-safe",
61
+ "direction": "device-to-node",
62
+ "text": "{\"type\":\"response\",\"id\":\"a b\",\"frame\":1}",
63
+ "valid": false
64
+ },
65
+ {
66
+ "name": "response-id-too-long",
67
+ "direction": "device-to-node",
68
+ "text": "{\"type\":\"response\",\"id\":\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"frame\":1}",
69
+ "valid": false
70
+ },
71
+ {
72
+ "name": "hello",
73
+ "direction": "node-to-device",
74
+ "text": "{\"type\":\"hello\",\"v\":1,\"heartbeatMs\":10000,\"maxFrameBytes\":262144}",
75
+ "valid": true
76
+ },
77
+ {
78
+ "name": "hello-without-v-reads-as-1",
79
+ "direction": "node-to-device",
80
+ "text": "{\"type\":\"hello\",\"heartbeatMs\":10000,\"maxFrameBytes\":262144}",
81
+ "valid": true
82
+ },
83
+ {
84
+ "name": "hello-newer-version-decodes",
85
+ "direction": "node-to-device",
86
+ "text": "{\"type\":\"hello\",\"v\":2,\"heartbeatMs\":10000,\"maxFrameBytes\":262144}",
87
+ "valid": true
88
+ },
89
+ {
90
+ "name": "hello-v-not-a-number",
91
+ "direction": "node-to-device",
92
+ "text": "{\"type\":\"hello\",\"v\":\"1\",\"heartbeatMs\":1,\"maxFrameBytes\":1}",
93
+ "valid": false
94
+ },
95
+ {
96
+ "name": "hello-v-zero",
97
+ "direction": "node-to-device",
98
+ "text": "{\"type\":\"hello\",\"v\":0,\"heartbeatMs\":1,\"maxFrameBytes\":1}",
99
+ "valid": false
100
+ },
101
+ {
102
+ "name": "hello-v-fractional",
103
+ "direction": "node-to-device",
104
+ "text": "{\"type\":\"hello\",\"v\":1.5,\"heartbeatMs\":1,\"maxFrameBytes\":1}",
105
+ "valid": false
106
+ },
107
+ {
108
+ "name": "hello-without-heartbeat",
109
+ "direction": "node-to-device",
110
+ "text": "{\"type\":\"hello\",\"v\":1,\"maxFrameBytes\":1}",
111
+ "valid": false
112
+ },
113
+ {
114
+ "name": "request",
115
+ "direction": "node-to-device",
116
+ "text": "{\"type\":\"request\",\"id\":\"q-7\",\"frame\":{\"cmd\":\"status\"}}",
117
+ "valid": true
118
+ },
119
+ {
120
+ "name": "request-without-id",
121
+ "direction": "node-to-device",
122
+ "text": "{\"type\":\"request\",\"frame\":1}",
123
+ "valid": false
124
+ },
125
+ {
126
+ "name": "frame",
127
+ "direction": "node-to-device",
128
+ "text": "{\"type\":\"frame\",\"frame\":\"ack\"}",
129
+ "valid": true
130
+ },
131
+ {
132
+ "name": "frame-without-payload",
133
+ "direction": "node-to-device",
134
+ "text": "{\"type\":\"frame\"}",
135
+ "valid": false
136
+ },
137
+ {
138
+ "name": "error",
139
+ "direction": "node-to-device",
140
+ "text": "{\"type\":\"error\",\"code\":\"X_FRAME_RATE_LIMIT\"}",
141
+ "valid": true
142
+ },
143
+ {
144
+ "name": "error-code-not-a-string",
145
+ "direction": "node-to-device",
146
+ "text": "{\"type\":\"error\",\"code\":7}",
147
+ "valid": false
148
+ },
149
+ {
150
+ "name": "reconnect",
151
+ "direction": "node-to-device",
152
+ "text": "{\"type\":\"reconnect\",\"v\":3,\"afterMs\":2500,\"reason\":\"drain\"}",
153
+ "valid": true
154
+ },
155
+ {
156
+ "name": "reconnect-unknown-reason",
157
+ "direction": "node-to-device",
158
+ "text": "{\"type\":\"reconnect\",\"v\":3,\"afterMs\":1,\"reason\":\"nap\"}",
159
+ "valid": false
160
+ },
161
+ {
162
+ "name": "reconnect-without-delay",
163
+ "direction": "node-to-device",
164
+ "text": "{\"type\":\"reconnect\",\"v\":3,\"reason\":\"drain\"}",
165
+ "valid": false
166
+ },
167
+ {
168
+ "name": "unknown-type",
169
+ "direction": "node-to-device",
170
+ "text": "{\"type\":\"mutate\"}",
171
+ "valid": false
172
+ },
173
+ {
174
+ "name": "not-json",
175
+ "direction": "node-to-device",
176
+ "text": "{",
177
+ "valid": false
178
+ }
179
+ ]
180
+ }