@pgxsinkit/server 0.2.7 → 0.3.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.
@@ -0,0 +1,832 @@
1
+ import {
2
+ readShapeTier,
3
+ type JwtClaims,
4
+ type PredicateValue,
5
+ type SyncTableEntry,
6
+ type SyncTableRegistry,
7
+ } from "@pgxsinkit/contracts";
8
+
9
+ import {
10
+ compileShapeRequest,
11
+ fingerprintShapeRequest,
12
+ resolveEntryByShapeKey,
13
+ type CompiledShapeRequest,
14
+ } from "./compile";
15
+ import { EntitlementsUnavailableError, type EntitlementSet } from "./edge";
16
+ import { CircuitsEngineError, type CircuitsEngineClient } from "./engine-client";
17
+ import { DEFAULT_STREAM_TOKEN_TTL_SECONDS, mintStreamToken, verifyStreamToken, type StreamGrant } from "./stream-token";
18
+ import type { CircuitsShapeHandle, CreateShapeRequest } from "./wire";
19
+
20
+ /**
21
+ * One shape a client wants to follow.
22
+ *
23
+ * A shape KEY and nothing else — deliberately (ADR-0055 decision 6). A shared-tier shape fans out to
24
+ * one stream per scope the subject holds, and the control plane does that expansion because it is
25
+ * the only side that knows the answer: it holds the entitlement set. A client naming its own scopes
26
+ * could only ever restate that set redundantly or contradict it, and every contradiction is a
27
+ * denial it then has to reconcile at boot.
28
+ */
29
+ export interface SubscriptionRequest {
30
+ shapeKey: string;
31
+ }
32
+
33
+ /** A subscription the control plane granted: what to read, and where. */
34
+ export interface GrantedSubscription {
35
+ shapeKey: string;
36
+ scope?: readonly PredicateValue[];
37
+ shapeId: string;
38
+ /** The durable-streams path, which is what the client follows through the edge. */
39
+ streamPath: string;
40
+ }
41
+
42
+ /** A subscription the control plane declined, with why. */
43
+ export interface DeniedSubscription {
44
+ shapeKey: string;
45
+ scope?: readonly PredicateValue[];
46
+ reason: string;
47
+ }
48
+
49
+ export interface SubscribeResult {
50
+ /** The stream token covering every granted subscription. Absent when nothing was granted. */
51
+ token?: string;
52
+ /** Seconds since the epoch. The client re-mints before this, in one request for the whole batch. */
53
+ expiresAt?: number;
54
+ granted: GrantedSubscription[];
55
+ denied: DeniedSubscription[];
56
+ }
57
+
58
+ export interface SubscribeOptions {
59
+ registry: SyncTableRegistry;
60
+ engine: CircuitsEngineClient;
61
+ /**
62
+ * The live entitlement set backing the SHARED tier.
63
+ *
64
+ * Optional, because a registry with no shared-tier shape has nothing to ask it. Omitting it is a
65
+ * statement that this deployment has none: a shared-tier subscription is then refused with that
66
+ * reason rather than silently permitted, so adding the first shared shape fails loudly instead of
67
+ * serving one subject's rows to everyone.
68
+ */
69
+ entitlements?: EntitlementSet;
70
+ /** The stream-token signing key, shared with the edge — the same process holds both. */
71
+ key: CryptoKey;
72
+ /** Per-deployment override of ADR-0055's 5-minute default. */
73
+ ttlSeconds?: number;
74
+ /** Deployment-supplied runtime params, handed to `rowFilter.customPredicate` as its second argument. */
75
+ params?: Record<string, unknown>;
76
+ }
77
+
78
+ /**
79
+ * The engine's subscription lease is shorter than this deployment's token TTL — a **configuration**
80
+ * fault, not a request one.
81
+ *
82
+ * The control plane renews every live claim on exactly one cadence: the token re-mint, which the
83
+ * client drives at `expiresAt - skew` and which therefore lands at most `ttlSeconds` apart. The
84
+ * engine releases a claim not renewed within `leaseSeconds` (`ELECTRIC_CIRCUITS_SHAPE_IDLE_SECS`).
85
+ * So a deployment whose lease window is under two TTLs has no margin at all: one refresh delayed by a
86
+ * retry, a redeploy, or a sleeping tab, and a live session's shape goes dormant underneath it. The
87
+ * factor of two is the margin for exactly one missed refresh.
88
+ *
89
+ * Refused loudly rather than papered over, because both numbers are the operator's and neither the
90
+ * subject nor the client can do anything about either. The routes answer 503 — "this deployment, not
91
+ * you" — and never a denial: a client told it lost entitlement truncates its rows.
92
+ */
93
+ export class CircuitsLeaseConfigError extends Error {
94
+ /** The engine's `ELECTRIC_CIRCUITS_SHAPE_IDLE_SECS`, as the create response reported it. */
95
+ readonly leaseSeconds: number;
96
+ /** The stream-token TTL this control plane is configured with. */
97
+ readonly ttlSeconds: number;
98
+
99
+ constructor(leaseSeconds: number, ttlSeconds: number) {
100
+ super(
101
+ `[pgxsinkit] the sync engine's shape lease window (${leaseSeconds}s, ` +
102
+ `ELECTRIC_CIRCUITS_SHAPE_IDLE_SECS) is shorter than twice this control plane's stream-token TTL ` +
103
+ `(${ttlSeconds}s, the \`ttlSeconds\` option). Claims are renewed on the token re-mint, so a single ` +
104
+ `missed refresh would let a live session's subscription lapse and its shape go dormant underneath ` +
105
+ `it. Raise ELECTRIC_CIRCUITS_SHAPE_IDLE_SECS to at least ${2 * ttlSeconds}, lower \`ttlSeconds\` to ` +
106
+ `at most ${Math.floor(leaseSeconds / 2)}, or set ELECTRIC_CIRCUITS_SHAPE_IDLE_SECS=0 to disable ` +
107
+ `leases entirely.`,
108
+ );
109
+ this.name = "CircuitsLeaseConfigError";
110
+ this.leaseSeconds = leaseSeconds;
111
+ this.ttlSeconds = ttlSeconds;
112
+ }
113
+ }
114
+
115
+ /**
116
+ * `leaseSeconds === 0` means the engine has dormancy — and with it leases — switched off, so there is
117
+ * no window to fall out of and nothing to check. Anything else must cover two re-mints.
118
+ */
119
+ function assertLeaseCoversTtl(leaseSeconds: number, ttlSeconds: number): void {
120
+ if (leaseSeconds !== 0 && leaseSeconds < 2 * ttlSeconds) throw new CircuitsLeaseConfigError(leaseSeconds, ttlSeconds);
121
+ }
122
+
123
+ /**
124
+ * The engine must record a claim under the name it was given — on the create that TAKES it and on
125
+ * every create that RENEWS it alike.
126
+ *
127
+ * An engine that renames a claim is one this control plane can neither renew nor release by id, which
128
+ * is the whole protocol (fork ADR-0008): the renewal would take a second claim every time, and the
129
+ * release would name something the engine never held. That is the wrong engine, not a degraded one,
130
+ * so it throws rather than degrading — there is no answer this client could go on to give.
131
+ */
132
+ function assertClaimRecorded(handle: CircuitsShapeHandle, claim: string): void {
133
+ if (handle.subscription === claim) return;
134
+ throw new Error(
135
+ `[pgxsinkit] the engine recorded this shape claim under \`${handle.subscription}\` rather than the ` +
136
+ `subscription id it was sent (\`${claim}\`). Renewal and release are BY that id (fork ADR-0008), ` +
137
+ `so an engine that renames a claim is not the one this client targets.`,
138
+ );
139
+ }
140
+
141
+ /**
142
+ * Compile one shape for one scope — the single form both the subscribe and the re-mint paths use.
143
+ *
144
+ * Shared between them on purpose: the re-mint RENEWS each grant's engine claim by repeating the create
145
+ * that took it, so the request it sends has to be the request subscribe would build today. Two
146
+ * spellings of "compile this grant" would be two chances for a renew to name a different definition
147
+ * than the grant it is renewing — which the engine would answer with a different handle, and this
148
+ * route would read as a revocation.
149
+ */
150
+ function compileGrant(
151
+ options: Pick<SubscribeOptions, "registry" | "params">,
152
+ claims: JwtClaims | null,
153
+ shapeKey: string,
154
+ scope?: readonly PredicateValue[],
155
+ ): CompiledShapeRequest {
156
+ return compileShapeRequest(options.registry, {
157
+ shapeKey,
158
+ claims,
159
+ ...(scope !== undefined ? { scope } : {}),
160
+ ...(options.params ? { params: options.params } : {}),
161
+ });
162
+ }
163
+
164
+ /** What a renewal attempt came to. `renewed` is the only outcome that keeps the grant. */
165
+ type RenewalOutcome = { renewed: true } | { revoked: string };
166
+
167
+ /**
168
+ * Renew one grant's engine claim: the SAME create, repeated with the SAME subscription id.
169
+ *
170
+ * This is the whole of the lease protocol on our side (fork ADR-0008). The engine has no separate
171
+ * renew route because it needs none — a create naming a claim the shape already holds returns the same
172
+ * handle, counts nothing, and moves the lease. So the re-mint, which already re-authorizes every grant
173
+ * on the client's own refresh cadence, renews for free and renews exactly the grants that survived.
174
+ *
175
+ * The two failure outcomes are both "this is no longer the stream the client follows", and both end in
176
+ * `revoked` rather than an error, because the client's answer to a revocation — truncate and
177
+ * re-subscribe — is precisely the right one:
178
+ *
179
+ * - **A different handle.** The claim lapsed, or the shape was evicted, so this call re-subscribed
180
+ * instead of renewing (ADR-0007) and the engine handed back a fresh shape on a fresh path. The
181
+ * grant names the old one. The claim just taken is released immediately: nothing is following that
182
+ * new stream, and the client's re-subscribe will take its own.
183
+ * - **409.** The id names a different shape. Nothing was taken, so there is nothing to give back.
184
+ *
185
+ * Anything else the engine says is an OUTAGE and propagates — the route answers 503. A revocation
186
+ * would tell the client it lost the scope, and a client told that clears the rows. An engine that
187
+ * renames the claim propagates too, through {@link assertClaimRecorded}: that one is not an outage
188
+ * either, it is the wrong engine.
189
+ */
190
+ async function renewGrantClaim(
191
+ engine: CircuitsEngineClient,
192
+ request: CreateShapeRequest,
193
+ grant: StreamGrant,
194
+ ttlSeconds: number,
195
+ ): Promise<RenewalOutcome> {
196
+ let handle;
197
+ try {
198
+ handle = await engine.createShape({ ...request, subscription: grant.claim });
199
+ } catch (error) {
200
+ if (error instanceof CircuitsEngineError && error.status === 409) {
201
+ return { revoked: "subscription id is held by another shape; re-subscribe" };
202
+ }
203
+ throw error;
204
+ }
205
+ assertClaimRecorded(handle, grant.claim);
206
+ // The handle comparison and the release of a fresh claim come BEFORE the lease guard, deliberately:
207
+ // a misconfigured window is fatal to this request, and throwing it first would strand the claim
208
+ // this very call just took.
209
+ if (handle.shapeId !== grant.shapeId || handle.streamPath !== grant.path) {
210
+ await engine.releaseShape(handle.shapeId, grant.claim);
211
+ return { revoked: "shape stream changed; re-subscribe" };
212
+ }
213
+ assertLeaseCoversTtl(handle.leaseSeconds, ttlSeconds);
214
+ return { renewed: true };
215
+ }
216
+
217
+ /**
218
+ * What one requested shape expands to: the scopes to compile it at.
219
+ *
220
+ * `[undefined]` — a single scope-less compile — is the private tier, whose subject arrives in the
221
+ * claims instead. A shared-tier shape expands to one entry per entitled scope, and none is a
222
+ * refusal rather than an empty success: a subject with no scopes has nothing to read, and returning
223
+ * zero grants silently would leave the client waiting on streams that were never created.
224
+ *
225
+ * An unknown shapeKey deliberately expands to `[undefined]` and is refused downstream by
226
+ * `compileShapeRequest`, so the message for "no such shape" has exactly one author.
227
+ *
228
+ * Throws {@link EntitlementsUnavailableError} when the set exists but cannot be trusted yet — an
229
+ * outage, not a refusal, and the route turns it into a 503.
230
+ */
231
+ function expandToScopes(
232
+ options: Pick<SubscribeOptions, "registry" | "entitlements">,
233
+ subject: string,
234
+ shapeKey: string,
235
+ ): { scopes: readonly (readonly PredicateValue[] | undefined)[] } | { refusal: string } {
236
+ const entry: SyncTableEntry | undefined = resolveEntryByShapeKey(options.registry, shapeKey);
237
+ const shape = entry?.shape;
238
+ if (shape == null) return { scopes: [undefined] };
239
+ if (readShapeTier(shape) === "private") return { scopes: [undefined] };
240
+
241
+ if (options.entitlements === undefined) {
242
+ return { refusal: "shared-tier shape, but this deployment configured no entitlement set" };
243
+ }
244
+ // A refusal above, a THROW here, and the difference is permanence. "No entitlement set configured"
245
+ // is a statement about this deployment that will read the same on every future request. "Not ready"
246
+ // is a statement about this instant, and answering it with a denial would tell the client it lost
247
+ // the scope — which makes it clear those rows. See {@link EntitlementsUnavailableError}.
248
+ if (!options.entitlements.ready) throw new EntitlementsUnavailableError();
249
+ const held = options.entitlements.scopesFor(subject, shapeKey);
250
+ if (held.length === 0) return { refusal: "no entitled scopes" };
251
+ return { scopes: held };
252
+ }
253
+
254
+ /**
255
+ * Subscribe to a batch of shapes: compile each against the registry, check entitlement, register it
256
+ * with the engine, and mint ONE token covering all of them.
257
+ *
258
+ * A shared-tier shape FANS OUT: one stream per scope the subject holds, so K requested shapes yield
259
+ * however many grants their entitlements come to. Expansion happens here rather than on the client
260
+ * because this is the side holding the entitlement set — see {@link SubscriptionRequest}.
261
+ *
262
+ * A partial result rather than an all-or-nothing one. A subject holding K scopes at boot may
263
+ * legitimately have lost one of them, and failing the whole batch on that would deny them the K-1
264
+ * they still hold — so a denial is reported per subscription and the rest proceed.
265
+ *
266
+ * That partiality covers AUTHORIZATION only. An engine that cannot answer — degraded, unreachable —
267
+ * is not a denial and must never be reported as one: a client told "not entitled" truncates that
268
+ * scope and unsubscribes, so reporting an outage that way would turn a transient engine fault into
269
+ * client-side data loss. Engine failures propagate, and the route answers 503.
270
+ *
271
+ * An entitlement set that is not `ready` joins it. It is the same shape of failure — a dependency
272
+ * that cannot answer right now — and the client's response to a denial is the same clear, so it
273
+ * propagates as {@link EntitlementsUnavailableError} and the route answers 503 too. What stays a
274
+ * denial is the set being absent altogether: that is a deployment's permanent configuration.
275
+ *
276
+ * Entitlement is checked HERE as well as at the edge, and the duplication is deliberate: this is
277
+ * what stops a shape being created and a capability minted for a scope the subject never held. The
278
+ * edge's check bounds how long an already-minted one keeps working.
279
+ */
280
+ export async function subscribeToShapes(
281
+ options: SubscribeOptions,
282
+ claims: JwtClaims | null,
283
+ requests: readonly SubscriptionRequest[],
284
+ now: number,
285
+ ): Promise<SubscribeResult> {
286
+ const subject = typeof claims?.sub === "string" ? claims.sub : null;
287
+ const granted: GrantedSubscription[] = [];
288
+ const denied: DeniedSubscription[] = [];
289
+ const grants: StreamGrant[] = [];
290
+ const ttlSeconds = options.ttlSeconds ?? DEFAULT_STREAM_TOKEN_TTL_SECONDS;
291
+
292
+ for (const request of requests) {
293
+ const deny = (reason: string, scope?: readonly PredicateValue[]) =>
294
+ denied.push({ shapeKey: request.shapeKey, ...(scope !== undefined ? { scope } : {}), reason });
295
+
296
+ // Every read is bound to a subject, both tiers. The private tier fuses the subject into the
297
+ // predicate and the shared tier checks it against the entitlement set, but neither has an
298
+ // anonymous form — a token with no subject would name a bearer no revocation could reach.
299
+ if (subject === null) {
300
+ deny("no subject");
301
+ continue;
302
+ }
303
+
304
+ const expanded = expandToScopes(options, subject, request.shapeKey);
305
+ if ("refusal" in expanded) {
306
+ deny(expanded.refusal);
307
+ continue;
308
+ }
309
+
310
+ for (const scope of expanded.scopes) {
311
+ const scoped = scope !== undefined ? { scope } : {};
312
+ const compiled = compileGrant(options, claims, request.shapeKey, scope);
313
+ if (compiled.outcome === "deny") {
314
+ deny(compiled.reason, scope);
315
+ continue;
316
+ }
317
+
318
+ // Enumeration said yes; ask the predicate too. The two are required to agree, and when they do
319
+ // not it is this side that must catch it: the edge checks `permits` on EVERY read, so a scope
320
+ // only `scopesFor` believes in would mint a capability for a stream the client can never
321
+ // actually read. Better a denial it can see now than a stream that 403s forever.
322
+ if (compiled.tier === "shared" && !options.entitlements?.permits(subject, request.shapeKey, scope ?? [])) {
323
+ deny("not entitled to this scope", scope);
324
+ continue;
325
+ }
326
+
327
+ // The private tier's grant records WHAT was authorized, not merely that something was. Its
328
+ // predicate is a function of this subject's claims, and those change under the client's feet —
329
+ // a role removed mid-session — so the re-mint has to be able to ask whether the shape this
330
+ // grant points at is still the shape these claims compile to. The fingerprint is how it asks
331
+ // without storing anything (ADR-0055 decision 6). The shared tier needs none: its predicate is
332
+ // generated from the scope values, which the entitlement re-check already covers.
333
+ const fp = compiled.tier === "private" ? { fp: await fingerprintShapeRequest(compiled.request) } : {};
334
+
335
+ // The claim is NAMED before it is taken, and the name is ours (fork ADR-0008). That is what
336
+ // makes this create idempotent — a repeat with the same id renews rather than joining twice —
337
+ // and what makes the release retry-safe: `DELETE ?subscription=…` drops this claim and only
338
+ // this one. A uuid per grant, never per shape: two grants that deduplicate onto one shapeId are
339
+ // two joins, and one id could only ever release one of them.
340
+ const claim = crypto.randomUUID();
341
+
342
+ // Deliberately unguarded: see the note above on why an engine fault is not a denial.
343
+ const handle = await options.engine.createShape({ ...compiled.request, subscription: claim });
344
+ assertClaimRecorded(handle, claim);
345
+ // Checked per create rather than once at boot: the lease window is the engine's to report, and
346
+ // this is the only place it is reported. A misconfigured pairing must surface as a 503 on the
347
+ // very first subscribe, not as sessions quietly lapsing an idle window later.
348
+ //
349
+ // The claim is already taken by the time this can trip, so it is handed back before the error
350
+ // leaves — nobody will ever follow this stream. Best effort, and the failure is SWALLOWED: the
351
+ // configuration fault is what the operator has to see, and a release that also fails must not
352
+ // mask it. An unreleased claim lapses on its own.
353
+ try {
354
+ assertLeaseCoversTtl(handle.leaseSeconds, ttlSeconds);
355
+ } catch (error) {
356
+ await options.engine.releaseShape(handle.shapeId, claim).catch(() => {});
357
+ throw error;
358
+ }
359
+
360
+ granted.push({ shapeKey: request.shapeKey, ...scoped, shapeId: handle.shapeId, streamPath: handle.streamPath });
361
+ // The grant carries the shapeId this `createShape` returned AND the claim it was taken under,
362
+ // and together they are what make the renew and release routes possible at all: both are
363
+ // stateless, so the signed token is the only record of what this session holds.
364
+ grants.push({
365
+ path: handle.streamPath,
366
+ shapeKey: request.shapeKey,
367
+ shapeId: handle.shapeId,
368
+ claim,
369
+ ...scoped,
370
+ ...fp,
371
+ });
372
+ }
373
+ }
374
+
375
+ if (subject === null || grants.length === 0) return { granted, denied };
376
+
377
+ const token = await mintStreamToken(options.key, { sub: subject, grants, ttlSeconds, now });
378
+ return { token, expiresAt: now + ttlSeconds, granted, denied };
379
+ }
380
+
381
+ /**
382
+ * The subscribe route: verified claims in, a token and stream paths out.
383
+ *
384
+ * Deliberately a POST that returns paths rather than a redirect to them. The client needs the whole
385
+ * batch to open K long-polls and to know when to re-mint, and a redirect would give it one stream
386
+ * and no expiry.
387
+ */
388
+ export function createSubscribeHandler(
389
+ options: SubscribeOptions & {
390
+ resolveAuthClaims?: (request: Request) => Promise<JwtClaims | null> | JwtClaims | null;
391
+ },
392
+ ) {
393
+ return async function handleSubscribe(request: Request): Promise<Response> {
394
+ let body: { subscriptions?: SubscriptionRequest[] };
395
+ try {
396
+ body = (await request.json()) as { subscriptions?: SubscriptionRequest[] };
397
+ } catch {
398
+ return Response.json({ error: "malformed body" }, { status: 400 });
399
+ }
400
+ if (!Array.isArray(body.subscriptions)) {
401
+ return Response.json({ error: "subscriptions must be an array" }, { status: 400 });
402
+ }
403
+
404
+ const claims = options.resolveAuthClaims ? await options.resolveAuthClaims(request) : null;
405
+
406
+ // Unauthenticated is NOT a denial, for the same reason an engine outage is not: a client told
407
+ // "not entitled" truncates the scope and unsubscribes, so answering an expired JWT that way
408
+ // turns a re-login into data loss. 401 is what makes it a distinct, recoverable status the
409
+ // client can retry through (ADR-0013).
410
+ //
411
+ // The check is on the SUBJECT, not on the claims object: a verified token with no `sub` names a
412
+ // bearer no revocation could ever reach, so it is exactly as unusable as no token at all. A
413
+ // deployment with no auth adapter never reaches here — `createSyncServer` refuses that pairing
414
+ // at construction.
415
+ if (typeof claims?.sub !== "string" || claims.sub === "") {
416
+ return Response.json({ error: "unauthenticated" }, { status: 401 });
417
+ }
418
+
419
+ let result: SubscribeResult;
420
+ try {
421
+ result = await subscribeToShapes(options, claims, body.subscriptions, Math.floor(Date.now() / 1000));
422
+ } catch (error) {
423
+ // An engine that could not answer is an OUTAGE, and 503 is what keeps the client retrying.
424
+ // Relaying it as a per-subscription denial would tell the client it lost entitlement, and a
425
+ // client told that truncates the scope and unsubscribes — turning a transient fault into data
426
+ // loss.
427
+ if (error instanceof CircuitsEngineError) {
428
+ return Response.json({ error: "sync engine unavailable" }, { status: 503 });
429
+ }
430
+ // A lease window shorter than the token TTL is an operator's misconfiguration, and it joins the
431
+ // 503s for the same reason: it is a statement about this deployment, never about this subject's
432
+ // entitlements. Denying instead would make an unserviceable pairing look like lost access.
433
+ if (error instanceof CircuitsLeaseConfigError) {
434
+ return Response.json({ error: "sync engine lease window shorter than the token TTL" }, { status: 503 });
435
+ }
436
+ if (error instanceof EntitlementsUnavailableError) {
437
+ return Response.json({ error: "entitlements unavailable" }, { status: 503 });
438
+ }
439
+ throw error;
440
+ }
441
+
442
+ // 200 even when everything was denied: the per-subscription reasons ARE the response, and
443
+ // collapsing them to a status code would tell a client that lost one scope out of K nothing
444
+ // about which one.
445
+ return Response.json(result);
446
+ };
447
+ }
448
+
449
+ export interface RefreshResult {
450
+ token?: string;
451
+ expiresAt?: number;
452
+ /** Grants that survived re-authorization — see {@link refreshStreamToken} for what that is per tier. */
453
+ granted: StreamGrant[];
454
+ /**
455
+ * Grants the subject may no longer read as granted: a shared scope they have lost, or a private
456
+ * shape their current claims no longer compile to. The client truncates each and unsubscribes,
457
+ * then re-subscribes for whatever it is entitled to now.
458
+ */
459
+ revoked: DeniedSubscription[];
460
+ }
461
+
462
+ /**
463
+ * Re-mint a stream token from an existing one (ADR-0055 decision 6).
464
+ *
465
+ * The expiring token IS the request: its signature proves this control plane issued those grants, so
466
+ * nothing has to be stored server-side to know what the subject held, and the edge stays stateless on
467
+ * both halves. Expiry is deliberately not enforced here — a token is presented for re-mint precisely
468
+ * because it is at or past its TTL — but the signature is, and **every grant is re-authorized**.
469
+ * That re-check is what makes the TTL a revocation bound rather than a formality.
470
+ *
471
+ * BOTH TIERS are re-authorized, by the question each tier's authorization actually turns on.
472
+ *
473
+ * - Shared: the live entitlement set. Its predicate is generated from the scope values, so it cannot
474
+ * drift with the subject; what can change is whether the subject still holds the scope.
475
+ * - Private: **recompile the shape with the subject's CURRENT claims** and compare the fingerprint
476
+ * the grant carries. A private predicate may read ANY verified claim, not only `sub`, so a subject
477
+ * demoted mid-session — a role dropped, a tenant changed — is still the same authenticated subject
478
+ * and would sail through a check that only re-verified the JWT. Re-verifying the JWT proves the
479
+ * bearer is still who they were; it says nothing about whether the shape they hold is still the
480
+ * shape their claims compile to, and only recompiling answers that.
481
+ *
482
+ * A fingerprint mismatch is a REVOCATION by design, including when the recompiled predicate would
483
+ * still permit the subject something. The grant names one stream, that stream serves the old
484
+ * predicate, and this route may not hand out a new one — the client's re-subscribe is where a new
485
+ * shape is created, and this route is not that. So the grant is revoked, the client re-subscribes, the
486
+ * control plane creates the shape its current claims compile to, and because the handle differs the
487
+ * client re-snapshots through ADR-0056 decision 7's must-refetch.
488
+ *
489
+ * **This is also where every surviving grant's engine claim is RENEWED** (fork ADR-0008). A claim is a
490
+ * lease: the engine releases one not renewed within `leaseSeconds`, because native reads terminate on
491
+ * durable-streams and the renewal is the only liveness signal it has. Renewing here rather than on a
492
+ * timer is what makes the cadence honest — this route already runs once per subject per TTL window and
493
+ * already decides which grants are still authorized, so the renewal covers exactly the grants that
494
+ * survived and costs no extra round trip. A revoked grant is deliberately NOT renewed: its lease
495
+ * lapses and the engine reclaims the shape.
496
+ *
497
+ * The renewal is the same create, repeated with the grant's own `claim` id. Its outcomes are in
498
+ * {@link renewGrantClaim}; a renewal that comes back a different handle, or 409s, revokes the grant
499
+ * with a re-subscribe reason rather than failing the whole re-mint.
500
+ *
501
+ * `registry` is therefore REQUIRED rather than optional: a refresh route that cannot recompile cannot
502
+ * re-authorize the private tier — and now cannot renew either, since the renewal IS the compiled
503
+ * create. `engine` is required for the same reason.
504
+ *
505
+ * Throws {@link EntitlementsUnavailableError} rather than revoking when the set cannot be consulted —
506
+ * the same outage-is-not-a-denial rule {@link subscribeToShapes} follows, and it matters more here:
507
+ * `revoked` is the wire's clear-this-scope instruction, and this route runs every few minutes for
508
+ * the life of every subscription. An engine that cannot answer a renewal joins it, as does a lease
509
+ * window this deployment's TTL does not fit inside ({@link CircuitsLeaseConfigError}).
510
+ */
511
+ export async function refreshStreamToken(
512
+ options: Pick<SubscribeOptions, "registry" | "engine" | "entitlements" | "key" | "ttlSeconds" | "params">,
513
+ claims: JwtClaims | null,
514
+ expiringToken: string,
515
+ now: number,
516
+ ): Promise<RefreshResult> {
517
+ const subject = typeof claims?.sub === "string" ? claims.sub : null;
518
+ const verified = await verifyStreamToken(options.key, expiringToken, now, { allowExpired: true });
519
+ if (!verified.ok || subject === null) return { granted: [], revoked: [] };
520
+
521
+ // The token names its subject; a token presented by anyone else is not a re-mint, it is a theft.
522
+ if (verified.claims.sub !== subject) return { granted: [], revoked: [] };
523
+
524
+ const granted: StreamGrant[] = [];
525
+ const revoked: DeniedSubscription[] = [];
526
+ const ttlSeconds = options.ttlSeconds ?? DEFAULT_STREAM_TOKEN_TTL_SECONDS;
527
+
528
+ for (const grant of verified.claims.grants) {
529
+ const scoped = grant.scope !== undefined ? { scope: grant.scope } : {};
530
+ if (grant.scope === undefined) {
531
+ // Private tier: re-authorize by recompiling. See the note above on why the signed grant alone
532
+ // is not the entitlement — the predicate is a function of claims that may have changed since
533
+ // it was issued.
534
+ const compiled = compileGrant(options, claims, grant.shapeKey);
535
+ if (compiled.outcome === "deny") {
536
+ revoked.push({ shapeKey: grant.shapeKey, reason: compiled.reason });
537
+ continue;
538
+ }
539
+ if (grant.fp === undefined) {
540
+ // Nothing to compare against, so nothing that could establish this grant is still the right
541
+ // one. Fail closed rather than trust it: the recovery is a re-subscribe, which costs the
542
+ // client a re-snapshot and costs the subject nothing they are still entitled to.
543
+ revoked.push({
544
+ shapeKey: grant.shapeKey,
545
+ reason: "private grant carries no fingerprint and cannot be re-authorized",
546
+ });
547
+ continue;
548
+ }
549
+ if ((await fingerprintShapeRequest(compiled.request)) !== grant.fp) {
550
+ revoked.push({ shapeKey: grant.shapeKey, reason: "shape predicate changed for this subject" });
551
+ continue;
552
+ }
553
+ // Re-authorized, so renew the claim it holds — the recompiled request is exactly the one that
554
+ // took it, which the fingerprint just proved.
555
+ const renewal = await renewGrantClaim(options.engine, compiled.request, grant, ttlSeconds);
556
+ if ("revoked" in renewal) {
557
+ revoked.push({ shapeKey: grant.shapeKey, reason: renewal.revoked });
558
+ continue;
559
+ }
560
+ granted.push(grant);
561
+ continue;
562
+ }
563
+ if (options.entitlements === undefined) {
564
+ // Permanent, and therefore a real revocation: this deployment has no entitlement set, so a
565
+ // shared grant can never be re-minted and the scope is not coming back.
566
+ //
567
+ // Worded as the EDGE words the same condition, and deliberately not as "entitlements
568
+ // unavailable" — that string is now the 503 outage body, which means the exact opposite here:
569
+ // an outage says nothing about this subject's scopes and must never clear a row.
570
+ revoked.push({
571
+ shapeKey: grant.shapeKey,
572
+ ...scoped,
573
+ reason: "shared-tier grant, but this deployment configured no entitlement set",
574
+ });
575
+ continue;
576
+ }
577
+ // Transient, and therefore NOT a revocation. `revoked` is an instruction to clear the scope, and
578
+ // a re-mint is the most routine request on this route — an entitlement subscription that is a few
579
+ // seconds behind would otherwise empty a subject's store every time it reconnected.
580
+ if (!options.entitlements.ready) throw new EntitlementsUnavailableError();
581
+ if (!options.entitlements.permits(subject, grant.shapeKey, grant.scope)) {
582
+ revoked.push({ shapeKey: grant.shapeKey, ...scoped, reason: "not entitled to this scope" });
583
+ continue;
584
+ }
585
+ // Still entitled, so renew. The shared tier carries no fingerprint — its predicate is generated
586
+ // from the scope values, which is why the entitlement check above is the whole question — so the
587
+ // request is recompiled here, through the same {@link compileGrant} subscribe used.
588
+ const compiled = compileGrant(options, claims, grant.shapeKey, grant.scope);
589
+ if (compiled.outcome === "deny") {
590
+ revoked.push({ shapeKey: grant.shapeKey, ...scoped, reason: compiled.reason });
591
+ continue;
592
+ }
593
+ const renewal = await renewGrantClaim(options.engine, compiled.request, grant, ttlSeconds);
594
+ if ("revoked" in renewal) {
595
+ revoked.push({ shapeKey: grant.shapeKey, ...scoped, reason: renewal.revoked });
596
+ continue;
597
+ }
598
+ granted.push(grant);
599
+ }
600
+
601
+ if (granted.length === 0) return { granted, revoked };
602
+
603
+ const token = await mintStreamToken(options.key, { sub: subject, grants: granted, ttlSeconds, now });
604
+ return { token, expiresAt: now + ttlSeconds, granted, revoked };
605
+ }
606
+
607
+ /**
608
+ * The re-mint route. Takes the expiring token, answers with a fresh one and the list of grants that
609
+ * did not survive re-authorization — the shared tier's against the live entitlement set, the private
610
+ * tier's against a recompile with the subject's current claims — and **renews the engine claim of
611
+ * every grant that did survive** (fork ADR-0008).
612
+ *
613
+ * `registry` for that recompile and `engine` for that renewal, both required for the reasons
614
+ * {@link refreshStreamToken} gives.
615
+ *
616
+ * 200 even when everything was revoked, for the same reason subscribe answers 200 on a full denial:
617
+ * the per-grant reasons ARE the response, and a client that lost one scope of K needs to know which.
618
+ */
619
+ export function createRefreshHandler(
620
+ options: Pick<SubscribeOptions, "registry" | "engine" | "entitlements" | "key" | "ttlSeconds" | "params"> & {
621
+ resolveAuthClaims?: (request: Request) => Promise<JwtClaims | null> | JwtClaims | null;
622
+ },
623
+ ) {
624
+ return async function handleRefresh(request: Request): Promise<Response> {
625
+ let body: { token?: string };
626
+ try {
627
+ body = (await request.json()) as { token?: string };
628
+ } catch {
629
+ return Response.json({ error: "malformed body" }, { status: 400 });
630
+ }
631
+ if (typeof body.token !== "string") {
632
+ return Response.json({ error: "token must be a string" }, { status: 400 });
633
+ }
634
+
635
+ const claims = options.resolveAuthClaims ? await options.resolveAuthClaims(request) : null;
636
+ // Same as subscribe: an unauthenticated re-mint is a credential problem, not a revocation. The
637
+ // difference matters more here — a `revoked` answer makes the client truncate, and a token
638
+ // expiring is the single most ordinary thing that happens on this route.
639
+ if (typeof claims?.sub !== "string" || claims.sub === "") {
640
+ return Response.json({ error: "unauthenticated" }, { status: 401 });
641
+ }
642
+
643
+ let result: RefreshResult;
644
+ try {
645
+ result = await refreshStreamToken(options, claims, body.token, Math.floor(Date.now() / 1000));
646
+ } catch (error) {
647
+ // 503, never a `revoked` list: an entitlement set that cannot answer has said nothing about
648
+ // this subject's scopes, and a client that read it as a revocation would clear rows it still
649
+ // holds. The client retries with the token it already has, which the edge keeps honouring
650
+ // until its TTL lapses.
651
+ if (error instanceof EntitlementsUnavailableError) {
652
+ return Response.json({ error: "entitlements unavailable" }, { status: 503 });
653
+ }
654
+ // An engine that could not answer a RENEWAL is the same case: the claim is still held (a lease
655
+ // outlives a failed renewal by the rest of its window), the token the client holds still works,
656
+ // and a `revoked` answer would clear rows over a transient fault.
657
+ if (error instanceof CircuitsEngineError) {
658
+ return Response.json({ error: "sync engine unavailable" }, { status: 503 });
659
+ }
660
+ if (error instanceof CircuitsLeaseConfigError) {
661
+ return Response.json({ error: "sync engine lease window shorter than the token TTL" }, { status: 503 });
662
+ }
663
+ throw error;
664
+ }
665
+ return Response.json(result);
666
+ };
667
+ }
668
+
669
+ /**
670
+ * Give back the engine claims a token's grants acquired — the close half of subscribe.
671
+ *
672
+ * **Why this route exists.** A native `POST /shapes` with a definition the engine already holds does
673
+ * not create a second shape: it JOINS the existing one, under a claim of its own. Live claims are
674
+ * load-bearing rather than bookkeeping — one live claim blocks both dormancy and eviction, precisely
675
+ * because native durable-streams reads bypass the engine entirely, so a claim is the only thing that
676
+ * tells it a reader it cannot see still exists. Without a release, a shape waits out its whole lease
677
+ * window before it can go dormant, every time.
678
+ *
679
+ * **The token IS the request**, exactly as on the re-mint path: its signature proves this control
680
+ * plane minted these grants, so nothing has to be stored server-side to know what was acquired.
681
+ * Verified with `allowExpired`, and that is not a weakening — a session releases at CLOSE, which is
682
+ * routinely past a 5-minute TTL, and expiry bounds how long a grant keeps *working*, not what it
683
+ * proves was issued. A release grants its bearer nothing; the only thing it can do is give away
684
+ * claims that this token's own subject holds.
685
+ *
686
+ * **ONE release per GRANT, deliberately not deduplicated by `shapeId`.** Two grants naming one shape
687
+ * are two joins — the engine deduplicated identical definitions and counted both (ADR-0055 decision
688
+ * 6) — so collapsing them here would return one of two claims and leak the other permanently. Each
689
+ * grant releases its OWN claim (`DELETE /shapes/{id}?subscription=<claim>`), which is what makes one
690
+ * release distinguishable from the other at all.
691
+ *
692
+ * **Idempotent and retry-safe** (fork ADR-0008). A claim is named, so releasing it twice is releasing
693
+ * it once: the second `DELETE` is a no-op `200` and cannot touch another subscriber's claim. That is
694
+ * a change in kind from the anonymous refcount decrement this route was first written against, and it
695
+ * collapses the old asymmetry — a client, a proxy or an operator may repeat a release freely. A
696
+ * release that never arrives at all is not a permanent leak either: the claim is a LEASE, renewed on
697
+ * the token re-mint, so a session that crashed or was unloaded has its claims reclaimed by the engine
698
+ * within `leaseSeconds`. What this route buys is promptness, not correctness.
699
+ *
700
+ * Refusals are refusals, not no-ops: a bad signature or a mismatched subject answers an error rather
701
+ * than `{ released: 0 }`, because a token presented by anyone but its own subject is not a release,
702
+ * it is an attempt to drop the victim's claims.
703
+ */
704
+ export async function releaseStreamGrants(
705
+ options: { engine: CircuitsEngineClient; key: CryptoKey },
706
+ claims: JwtClaims | null,
707
+ token: string,
708
+ now: number,
709
+ ): Promise<{ released: number } | { refused: string }> {
710
+ const subject = typeof claims?.sub === "string" && claims.sub !== "" ? claims.sub : null;
711
+ if (subject === null) return { refused: "unauthenticated" };
712
+
713
+ const verified = await verifyStreamToken(options.key, token, now, { allowExpired: true });
714
+ if (!verified.ok) return { refused: verified.reason };
715
+ if (verified.claims.sub !== subject) return { refused: "token subject does not match the caller" };
716
+
717
+ for (const grant of verified.claims.grants) {
718
+ await options.engine.releaseShape(grant.shapeId, grant.claim);
719
+ }
720
+ return { released: verified.claims.grants.length };
721
+ }
722
+
723
+ /**
724
+ * The release route: the token a session was given, back at its close.
725
+ *
726
+ * **Safe to call more than once.** Every grant releases a NAMED claim, so a repeat is the same act
727
+ * once (fork ADR-0008) — a duplicate close, a proxy retry or an operator replaying a request all
728
+ * answer 200 and change nothing. The client still sends it at most once, but that is now a matter of
729
+ * not making a pointless request rather than of correctness.
730
+ *
731
+ * 403 rather than 200 on a refusal — see {@link releaseStreamGrants} for why a refused release must
732
+ * be visible. 401 when the caller has no subject, the same rule subscribe and re-mint follow: an
733
+ * unauthenticated call is a credential problem, and it is the one thing here a client could fix.
734
+ */
735
+ export function createReleaseHandler(
736
+ options: {
737
+ engine: CircuitsEngineClient;
738
+ key: CryptoKey;
739
+ } & {
740
+ resolveAuthClaims?: (request: Request) => Promise<JwtClaims | null> | JwtClaims | null;
741
+ },
742
+ ) {
743
+ return async function handleRelease(request: Request): Promise<Response> {
744
+ let body: { token?: string };
745
+ try {
746
+ body = (await request.json()) as { token?: string };
747
+ } catch {
748
+ return Response.json({ error: "malformed body" }, { status: 400 });
749
+ }
750
+ if (typeof body.token !== "string") {
751
+ return Response.json({ error: "token must be a string" }, { status: 400 });
752
+ }
753
+
754
+ const claims = options.resolveAuthClaims ? await options.resolveAuthClaims(request) : null;
755
+ if (typeof claims?.sub !== "string" || claims.sub === "") {
756
+ return Response.json({ error: "unauthenticated" }, { status: 401 });
757
+ }
758
+
759
+ let result: { released: number } | { refused: string };
760
+ try {
761
+ result = await releaseStreamGrants(options, claims, body.token, Math.floor(Date.now() / 1000));
762
+ } catch (error) {
763
+ // An engine that could not answer has not dropped the claims. 503 says "this deployment, not
764
+ // you", and a client is free to come back: releases are named and therefore idempotent (fork
765
+ // ADR-0008), so a retry that races a release which actually landed is a no-op rather than a
766
+ // theft. Whether it retries or not, the residue is bounded by the lease — an unreleased claim
767
+ // lapses within `leaseSeconds` of its last renewal.
768
+ if (error instanceof CircuitsEngineError) {
769
+ return Response.json({ error: "sync engine unavailable" }, { status: 503 });
770
+ }
771
+ throw error;
772
+ }
773
+
774
+ if ("refused" in result) return Response.json({ error: result.refused }, { status: 403 });
775
+ return Response.json(result);
776
+ };
777
+ }
778
+
779
+ /** The control-plane paths the native read path mounts. */
780
+ export const subscribePath = "/sync/v1/subscribe";
781
+ export const refreshPath = "/sync/v1/refresh";
782
+ export const releasePath = "/sync/v1/release";
783
+
784
+ /**
785
+ * The convergence-barrier route (ADR-0056 decision 4).
786
+ *
787
+ * Proxied rather than exposed: the engine's control plane is unauthenticated by design and is not
788
+ * client-reachable, so surfacing the barrier on our own authenticated endpoint costs nothing and
789
+ * keeps the trust boundary intact.
790
+ *
791
+ * `maxAgeSeconds` may cache the answer briefly, but only a HEALTHY one. For the `pendingFlips` term
792
+ * staleness is safe in exactly one direction — it moves the barrier backwards, so a stale reading can
793
+ * only DELAY an alignment, never satisfy one falsely. `flipFailures` inverts that: a cached
794
+ * pre-degradation zero would let a group align against an engine that has already
795
+ * lost membership effects, which is precisely the alignment the term exists to refuse. So a degraded
796
+ * reading is never cached and never served from cache, and the cache window is exactly the bound on
797
+ * how long a client may align against a freshly-degraded engine — which is why the default is 0.
798
+ */
799
+ export function createBarrierHandler(options: {
800
+ engine: CircuitsEngineClient;
801
+ resolveAuthClaims?: (request: Request) => Promise<JwtClaims | null> | JwtClaims | null;
802
+ maxAgeSeconds?: number;
803
+ }) {
804
+ let cached: { at: number; body: BarrierBody } | null = null;
805
+ const maxAge = options.maxAgeSeconds ?? 0;
806
+
807
+ return async function handleBarrier(request: Request): Promise<Response> {
808
+ const claims = options.resolveAuthClaims ? await options.resolveAuthClaims(request) : null;
809
+ // The barrier says nothing about any subject's data — only whether the engine has finished
810
+ // propagating — but it is still engine internals, so it needs a caller we recognise.
811
+ if (options.resolveAuthClaims && claims === null) {
812
+ return Response.json({ error: "unauthenticated" }, { status: 401 });
813
+ }
814
+
815
+ const now = Date.now() / 1000;
816
+ if (cached && now - cached.at < maxAge) return Response.json(cached.body);
817
+
818
+ const state = await options.engine.replicationState();
819
+ const body = { pendingFlips: state.pendingFlips, flipFailures: state.flipFailures };
820
+ cached = body.flipFailures > 0 ? null : { at: now, body };
821
+ return Response.json(body);
822
+ };
823
+ }
824
+
825
+ export const barrierPath = "/sync/v1/barrier";
826
+
827
+ /** The barrier as the client reads it — the engine's LSN is operator detail and stays server-side. */
828
+ interface BarrierBody {
829
+ pendingFlips: number;
830
+ /** Abandoned flip batches. Non-zero is terminal for a group reading it, and is never cached. */
831
+ flipFailures: number;
832
+ }