@pgxsinkit/server 0.2.6 → 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.
package/README.md CHANGED
@@ -1,12 +1,15 @@
1
1
  # @pgxsinkit/server
2
2
 
3
3
  The [pgxsinkit](https://pgxsinkit.github.io) write API and secured read ingress:
4
- `createSyncServer` owns the single mutation route and the registry-governed Electric
5
- shape proxy, both behind one verified-claims adapter, plus the in-database
6
- apply-function builder.
4
+ `createSyncServer` owns the single mutation route and the read path's control plane
5
+ (`/sync/v1/subscribe`, `/sync/v1/refresh`, `/sync/v1/barrier`), both behind one
6
+ verified-claims adapter, plus `createStreamGate` — the stream edge that verifies a
7
+ stream token and proxies durable-streams bytes — and the in-database apply-function
8
+ builder.
7
9
 
8
10
  ```bash
9
11
  bun add @pgxsinkit/server @pgxsinkit/contracts
10
12
  ```
11
13
 
12
- See the [documentation](https://pgxsinkit.github.io) for the write path and proxy.
14
+ See the [documentation](https://pgxsinkit.github.io) for the write path, the control
15
+ plane, and the edge.
@@ -0,0 +1,66 @@
1
+ import { type JwtClaims, type PredicateValue, type SyncTableEntry, type SyncTableRegistry } from "@pgxsinkit/contracts";
2
+ import type { CreateShapeRequest } from "./wire";
3
+ /** What a client asks the control plane for: a declared shape, plus the inputs its tier consumes. */
4
+ export interface ShapeRequest {
5
+ /** The shape's unique identity, exactly as declared. Never a table name the client chose. */
6
+ shapeKey: string;
7
+ /** Verified claims. The private tier's only subject input; the shared tier never sees them. */
8
+ claims: JwtClaims | null;
9
+ /**
10
+ * SHARED TIER — the scope values, positionally matching the shape's declared `scope` columns.
11
+ * `null` is a legal value and compiles to `IS NULL`, so an absent element and a null one are
12
+ * different things: arity is checked strictly rather than padded.
13
+ */
14
+ scope?: readonly PredicateValue[];
15
+ /** Deployment-supplied runtime params, handed to `rowFilter.customPredicate` as its second argument. */
16
+ params?: Record<string, unknown>;
17
+ }
18
+ /**
19
+ * The outcome of compiling a request. A denial is a first-class result rather than an exception
20
+ * because it is an ordinary, expected outcome — an anonymous caller, a subject with no membership —
21
+ * and because the caller's response to it (no handle, no shape, 403) is the same for every reason.
22
+ */
23
+ export type CompiledShapeRequest = {
24
+ outcome: "create";
25
+ tier: "shared" | "private";
26
+ request: CreateShapeRequest;
27
+ } | {
28
+ outcome: "deny";
29
+ reason: string;
30
+ };
31
+ /**
32
+ * Resolve the entry a request selects by its **`shapeKey`** — not by table name, since several
33
+ * shapes (a read projection and its owner) legitimately read one physical table under distinct keys.
34
+ * Schema qualification is significant. Returns undefined when nothing declares that key, and the
35
+ * caller fails closed.
36
+ */
37
+ export declare function resolveEntryByShapeKey(registry: SyncTableRegistry, shapeKey: string): SyncTableEntry | undefined;
38
+ /**
39
+ * Compile a shape request into the engine's `POST /shapes` body, or a denial.
40
+ *
41
+ * The whole predicate is built here, in the control plane, from the registry — nothing predicate
42
+ * shaped arrives on the wire. That is strictly stronger than the proxy's "discard the client's
43
+ * `where`": there is no `where` on the wire to discard, so no parameter parsing to get right and no
44
+ * grammar for a client to probe.
45
+ */
46
+ export declare function compileShapeRequest(registry: SyncTableRegistry, request: ShapeRequest): CompiledShapeRequest;
47
+ /**
48
+ * A content fingerprint of a compiled shape request — SHA-256 over its canonical JSON, lowercase hex.
49
+ *
50
+ * CANONICAL because the input is not a literal an author wrote: a predicate reaches here through
51
+ * `rowFilter.customPredicate`, whose closure may assemble `{ col, op, value }` in whatever order its
52
+ * branches happen to take, and `p.and(a, b)` on one path may nest where another flattens. Two
53
+ * compiles that MEAN the same thing must fingerprint the same, or the equality below degrades into a
54
+ * test of how the author's code was written on the day.
55
+ *
56
+ * This is an AUTHORIZATION equality check, not a cache key. Two requests fingerprinting the same are
57
+ * the same shape to the engine — same table, same predicate, same projection — so a subject whose
58
+ * recompiled shape still fingerprints as the one their grant names is still authorized for exactly
59
+ * the stream that grant points at. A collision is therefore not a performance regression, it is an
60
+ * authorization one, which is why this is a cryptographic digest and not a cheap hash.
61
+ *
62
+ * Used by the re-mint path (ADR-0055 decision 6) to re-authorize a private-tier grant against the
63
+ * subject's current claims. Never sent to the engine, which knows nothing about it.
64
+ */
65
+ export declare function fingerprintShapeRequest(request: CreateShapeRequest): Promise<string>;
66
+ //# sourceMappingURL=compile.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"compile.d.ts","sourceRoot":"","sources":["../../src/circuits/compile.ts"],"names":[],"mappings":"AAEA,OAAO,EAOL,KAAK,SAAS,EAEd,KAAK,cAAc,EAEnB,KAAK,cAAc,EACnB,KAAK,iBAAiB,EACvB,MAAM,sBAAsB,CAAC;AAE9B,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,QAAQ,CAAC;AAEjD,qGAAqG;AACrG,MAAM,WAAW,YAAY;IAC3B,6FAA6F;IAC7F,QAAQ,EAAE,MAAM,CAAC;IACjB,+FAA+F;IAC/F,MAAM,EAAE,SAAS,GAAG,IAAI,CAAC;IACzB;;;;OAIG;IACH,KAAK,CAAC,EAAE,SAAS,cAAc,EAAE,CAAC;IAClC,wGAAwG;IACxG,MAAM,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CAClC;AAED;;;;GAIG;AACH,MAAM,MAAM,oBAAoB,GAC5B;IAAE,OAAO,EAAE,QAAQ,CAAC;IAAC,IAAI,EAAE,QAAQ,GAAG,SAAS,CAAC;IAAC,OAAO,EAAE,kBAAkB,CAAA;CAAE,GAC9E;IAAE,OAAO,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,CAAC;AAExC;;;;;GAKG;AACH,wBAAgB,sBAAsB,CAAC,QAAQ,EAAE,iBAAiB,EAAE,QAAQ,EAAE,MAAM,GAAG,cAAc,GAAG,SAAS,CAEhH;AA6CD;;;;;;;GAOG;AACH,wBAAgB,mBAAmB,CAAC,QAAQ,EAAE,iBAAiB,EAAE,OAAO,EAAE,YAAY,GAAG,oBAAoB,CA+B5G;AAyID;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAsB,uBAAuB,CAAC,OAAO,EAAE,kBAAkB,GAAG,OAAO,CAAC,MAAM,CAAC,CAS1F"}
@@ -0,0 +1,188 @@
1
+ import type { PredicateValue, SyncTableRegistry } from "@pgxsinkit/contracts";
2
+ import { type StreamGrant } from "./stream-token";
3
+ /**
4
+ * The live entitlement set the edge checks a shared-tier read against (ADR-0055 decision 7).
5
+ *
6
+ * An interface, not an implementation, because the source is a Circuits subscription over the
7
+ * membership relations themselves — freshness is engine propagation, not a cache TTL, and there is
8
+ * no database on the read path.
9
+ */
10
+ export interface EntitlementSet {
11
+ /**
12
+ * Whether the entitlement set can be trusted right now. False while the subscription is catching
13
+ * up, degraded, or stale.
14
+ *
15
+ * The edge denies when this is false. An unavailable entitlement set is never a permit — the
16
+ * failure mode of the alternative is a disclosure, and the failure mode of this one is a subject
17
+ * retrying a read.
18
+ */
19
+ readonly ready: boolean;
20
+ /** Whether `subject` may read `shapeKey` at `scope`. */
21
+ permits(subject: string, shapeKey: string, scope: readonly PredicateValue[]): boolean;
22
+ /**
23
+ * Every scope of `shapeKey` that `subject` holds, each an ordered tuple matching the shape's
24
+ * declared scope columns.
25
+ *
26
+ * This is what lets a client subscribe by shape alone (ADR-0055 decision 6): it names
27
+ * `offering_content`, and the control plane answers with one stream per offering the subject can
28
+ * actually read. The alternative — the client naming scopes — makes it restate something only this
29
+ * set knows, so its every answer is either redundant or wrong.
30
+ *
31
+ * Enumeration and `permits` must agree: a scope returned here that `permits` would refuse is a
32
+ * grant the edge then rejects on every read.
33
+ */
34
+ scopesFor(subject: string, shapeKey: string): readonly (readonly PredicateValue[])[];
35
+ }
36
+ /**
37
+ * The entitlement set cannot be consulted right now — it is catching up, degraded, or stale.
38
+ *
39
+ * An OUTAGE, and thrown rather than reported per subscription for exactly the reason an engine fault
40
+ * is: a client told "not entitled" clears that scope and unsubscribes (ADR-0055 decision 6), so
41
+ * relaying an unavailable set as a denial would turn a transient control-plane condition into
42
+ * client-side data loss. The routes map it to 503, which is a status a client retries through.
43
+ *
44
+ * The EDGE does not throw this. A read arriving while the set is unavailable is denied (see
45
+ * {@link EntitlementSet.ready}) and a denied read is not a revocation — it is a request the client
46
+ * makes again.
47
+ */
48
+ export declare class EntitlementsUnavailableError extends Error {
49
+ constructor();
50
+ }
51
+ export interface StreamGateOptions {
52
+ /** Verifies the stream token. Minted by the control plane in the same process. */
53
+ key: CryptoKey;
54
+ /**
55
+ * The registry the granted shapes are declared in — REQUIRED, unlike every other option here.
56
+ *
57
+ * The gate needs it to answer one question per read: does this shape declare a
58
+ * `serverProjection.rowTransform`, and must its bytes therefore be rewritten before they reach the
59
+ * client (ADR-0055 decision 5)? A gate that cannot see the registry cannot know, so it would proxy
60
+ * a transform shape's raw rows — including the `serverOnlyColumns` fetched solely for the transform
61
+ * — with nothing anywhere reporting a discrepancy. Making it required is what makes that mount
62
+ * impossible to write, which is why it is not optional "for deployments with no transform shape":
63
+ * the leak arrives on the day someone adds the first one, in a file nobody was editing.
64
+ */
65
+ registry: SyncTableRegistry;
66
+ /**
67
+ * The live entitlement set backing the shared tier. Optional for the same reason it is optional on
68
+ * the control plane: a deployment whose registry declares no shared shape has nothing to ask it.
69
+ * Absent, a shared-tier grant is DENIED rather than waved through — the two sides then agree that
70
+ * an unconfigured entitlement set can never permit.
71
+ */
72
+ entitlements?: EntitlementSet;
73
+ /**
74
+ * Base URL of the durable-streams server, with whatever stream prefix it is mounted under — the
75
+ * same value the engine is given as `ELECTRIC_CIRCUITS_DS_URL`, since both address the same paths.
76
+ */
77
+ durableStreamsUrl: string;
78
+ /**
79
+ * Deployment-supplied runtime params, handed to an egress `rowTransform` as its context's `params`
80
+ * — the same values `SubscribeOptions.params` hands to `rowFilter.customPredicate`. A deployment
81
+ * that configures them on one side and not the other gives its registry two different runtime
82
+ * environments for one shape, so mount both from the same source.
83
+ */
84
+ params?: Record<string, unknown>;
85
+ /** Injected for tests; defaults to the ambient `fetch`. */
86
+ fetch?: typeof fetch;
87
+ }
88
+ /**
89
+ * What DECIDING one read needs: the signing key, plus the entitlement set the shared tier is checked
90
+ * against.
91
+ *
92
+ * Spelled as the gate's options with everything else relaxed to optional, rather than as
93
+ * {@link StreamGateOptions} itself, because a caller that wants only the decision — a mount that
94
+ * proxies for itself, a test pinning the authorization rules — has no gate to configure, and
95
+ * requiring it to invent a `registry` and a `durableStreamsUrl` would demand values the answer
96
+ * provably does not depend on.
97
+ */
98
+ export type StreamAuthorizationOptions = Pick<StreamGateOptions, "key" | "entitlements"> & Partial<Omit<StreamGateOptions, "key" | "entitlements">>;
99
+ export type GateDecision = {
100
+ allow: true;
101
+ grant: StreamGrant;
102
+ /**
103
+ * The token's subject. Carried on the decision because the egress transform stage needs it and
104
+ * re-verifying the token to recover it would pay for a second HMAC on every rewritten read —
105
+ * the verification that established it already happened here.
106
+ */
107
+ subject: string;
108
+ } | {
109
+ allow: false;
110
+ reason: string;
111
+ };
112
+ /**
113
+ * Authorize one read of one stream path.
114
+ *
115
+ * Two checks, and they are not redundant. The token is a capability bounded by its TTL, which is the
116
+ * only bound available when a hit-serving CDN sits in front and the request never reaches us. The
117
+ * entitlement lookup is live, and bounds revocation by propagation latency instead whenever the
118
+ * request does reach us. Which one binds is a property of the deployment, not of this code.
119
+ *
120
+ * A private-tier grant has no scope to check, so the token is the whole authorization and its TTL is
121
+ * the whole revocation bound. That is the same bound a CDN-fronted shared read has, and it is worth
122
+ * stating rather than leaving to be inferred.
123
+ */
124
+ export declare function authorizeStreamRead(options: StreamAuthorizationOptions, token: string | null, path: string, now: number): Promise<GateDecision>;
125
+ /**
126
+ * Read the stream token off a request.
127
+ *
128
+ * `Authorization`, never a query parameter, and this is a correctness condition rather than a
129
+ * convention: the cache key is the URL, so a token in the URL gives every subscriber a distinct key
130
+ * and destroys precisely the sharing the shared tier exists for. A cache must also be configured not
131
+ * to vary on this header — which it can only do if the header is where the token is.
132
+ */
133
+ export declare function readStreamToken(request: Request): string | null;
134
+ /**
135
+ * The response headers a browser must be allowed to READ off a stream-edge response.
136
+ *
137
+ * CORS lets script see only a short safelist of response headers (`cache-control`, `content-language`,
138
+ * `content-length`, `content-type`, `expires`, `last-modified`, `pragma`). Every header the
139
+ * durable-streams protocol answers with is outside it, so a CROSS-ORIGIN reader sees NONE of them
140
+ * unless the mount names them on `Access-Control-Expose-Headers`.
141
+ *
142
+ * The failure that follows is silent and expensive rather than loud. `@durable-streams/client` drives
143
+ * its entire read loop off these headers — verified by grepping the installed 0.2.6 dist
144
+ * (`@durable-streams/client/dist/index.js`, mirrored in its shipped `src/`): `Stream-Next-Offset`,
145
+ * `Stream-Cursor` and `Stream-Closed` are read per response, `Stream-Up-To-Date` is a presence check
146
+ * (`headers.has`, which is why it is easy to miss), `stream-sse-data-encoding` decides SSE payload
147
+ * decoding, and `etag` is read on the stream-metadata path. Stripped of them, the client never learns
148
+ * an offset: it re-requests `offset=-1` forever and never switches to a live long poll, which presents
149
+ * as a hot loop of hundreds of requests per second per shape with no error raised anywhere.
150
+ *
151
+ * `Stream-Seq`, `Stream-TTL` and `Stream-Expires-At` are request headers in that client version. They
152
+ * are named here anyway because this list is a statement about the ds protocol's response namespace
153
+ * rather than about which subset one client version happens to read today — exposing a header a
154
+ * response never carries is inert, while omitting one that it does carry wedges the reader. The
155
+ * `Producer-*` headers are deliberately absent: they belong to the write path, which does not come
156
+ * through this gate.
157
+ *
158
+ * EVERY mount of `createStreamGate` must put these on `Access-Control-Expose-Headers` of the ACTUAL
159
+ * (non-preflight) response. The gate cannot do it itself — it forwards the upstream response's
160
+ * headers (verbatim for an ordinary shape, minus the caching ones for a rewritten one), and an
161
+ * exposure list is meaningless without the `Access-Control-Allow-Origin` decision that only the mount
162
+ * owns.
163
+ */
164
+ export declare const STREAM_READ_EXPOSED_HEADERS: readonly string[];
165
+ /**
166
+ * The edge: gate, then proxy bytes — rewriting them only for the shapes that declare a rewrite.
167
+ *
168
+ * There is no per-read FILTERING here at all, and no per-read rewriting for shapes that declare none.
169
+ * Predicates were resolved at shape creation, so what remains for almost every read is a decision and
170
+ * a copy — which is why this can sit in the TypeScript control-plane process without CPU being the
171
+ * axis that decides where it belongs.
172
+ *
173
+ * A shape that declares `serverProjection.rowTransform` is the one exception: it is rewritten HERE,
174
+ * per request, with the subject taken from the stream token, and answered `private, no-store`. This
175
+ * is the rewriting origin ADR-0055 decision 5 names, confined to the shapes that incur it — a
176
+ * transform shape gives up CDN shareability and SSE framing, and every other shape gives up nothing.
177
+ * The transform's `serverOnlyColumns` are fetched by the engine so the transform can read them and
178
+ * are stripped here, after it runs, to the columns the client's local table declares.
179
+ *
180
+ * The claims a transform sees at the edge are `{ sub }` and nothing else: a stream token carries the
181
+ * subject, not the JWT it was minted from, and re-deriving richer claims per read would put an auth
182
+ * provider call on the read path this whole topology exists to keep off it. A transform that needs
183
+ * more than the subject is therefore NOT expressible at egress — put the subject-dependent part in
184
+ * the shape's private `rowFilter.customPredicate`, which is compiled at subscribe time from the full
185
+ * verified claims.
186
+ */
187
+ export declare function createStreamGate(options: StreamGateOptions): (request: Request, path: string, now: number) => Promise<Response>;
188
+ //# sourceMappingURL=edge.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"edge.d.ts","sourceRoot":"","sources":["../../src/circuits/edge.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,cAAc,EAAqC,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AAGjH,OAAO,EAAgC,KAAK,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAEhF;;;;;;GAMG;AACH,MAAM,WAAW,cAAc;IAC7B;;;;;;;OAOG;IACH,QAAQ,CAAC,KAAK,EAAE,OAAO,CAAC;IACxB,wDAAwD;IACxD,OAAO,CAAC,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,KAAK,EAAE,SAAS,cAAc,EAAE,GAAG,OAAO,CAAC;IACtF;;;;;;;;;;;OAWG;IACH,SAAS,CAAC,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG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ACH,eAAO,MAAM,2BAA2B,EAAE,SAAS,MAAM,EAUxD,CAAC;AA+CF;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,iBAAiB,aAIT,OAAO,QAAQ,MAAM,OAAO,MAAM,KAAG,OAAO,CAAC,QAAQ,CAAC,CA0FvG"}
@@ -0,0 +1,111 @@
1
+ import type { CircuitsShapeHandle, CreateShapeRequest } from "./wire";
2
+ export interface CircuitsEngineOptions {
3
+ /** Base URL of the Circuits engine's control API, e.g. `http://circuits-engine:4000`. */
4
+ baseUrl: string;
5
+ /** Injected for tests; defaults to the ambient `fetch`. */
6
+ fetch?: typeof fetch;
7
+ }
8
+ /**
9
+ * An engine call that did not return 2xx, carrying the status so a caller can map it to its own.
10
+ *
11
+ * The one status with a MEANING rather than a severity is **409**: a create whose `subscription` id
12
+ * is already held by a different shape (fork ADR-0008 — one name, one shape). It is the caller's
13
+ * conflict, not an outage, and no retry changes it; match it as `error.status === 409` and re-subscribe
14
+ * under a fresh id. Everything else is either a request this client built wrong (4xx) or an engine
15
+ * that could not answer (5xx), and both propagate as a 503 to the client.
16
+ */
17
+ export declare class CircuitsEngineError extends Error {
18
+ readonly status: number;
19
+ readonly body: string;
20
+ constructor(status: number, body: string, message: string);
21
+ }
22
+ /**
23
+ * The control plane's client for the Circuits engine.
24
+ *
25
+ * Only the shape LIFECYCLE goes through here. Reads never do: they terminate on durable-streams,
26
+ * which is the whole point of the native topology — the engine is asked once, at subscribe time,
27
+ * for a stream to follow, and is then out of the read path entirely.
28
+ */
29
+ export declare function createCircuitsEngineClient(options: CircuitsEngineOptions): {
30
+ /**
31
+ * Register a shape and get the stream to follow — **and renew that registration**.
32
+ *
33
+ * There is deliberately no `renewShape`: a renewal IS this call, repeated with the same
34
+ * `request.subscription` on the same definition (fork ADR-0008). The engine answers the same
35
+ * handle, counts nothing extra, and moves the lease forward. That is also why a create whose
36
+ * response was lost can simply be sent again, and why the control plane's token re-mint can renew
37
+ * every live claim without a second route.
38
+ *
39
+ * Two outcomes a caller must distinguish:
40
+ * - **409** ({@link CircuitsEngineError.status}) — the id names a DIFFERENT shape already. One
41
+ * name, one shape; nothing was taken, and a retry will not change it.
42
+ * - a **different handle** — the claim had lapsed or the shape was evicted, so this call
43
+ * re-subscribed rather than renewed. The stream the old grant named is not this one (ADR-0007).
44
+ *
45
+ * The engine shares by definition: two identical bodies collapse onto one maintained stream and
46
+ * return the same handle. Nothing here has to check for that or cache against it — which is
47
+ * exactly why the shared tier's predicate must be GENERATED. Two subscribers in one scope produce
48
+ * identical bodies only because neither's identity reached the predicate; they are still two
49
+ * distinct subscriptions, because each names its own claim.
50
+ *
51
+ * The answer is VALIDATED, not cast, for the same reason {@link replicationState} validates the
52
+ * barrier: an engine that acknowledges a create without saying which subscription it recorded or
53
+ * how long that subscription lives cannot be renewed or released by id at all, and defaulting
54
+ * either field would invent a lease this control plane was never promised.
55
+ */
56
+ createShape(request: CreateShapeRequest): Promise<CircuitsShapeHandle>;
57
+ /**
58
+ * Release ONE named subscription's claim on a shape (`DELETE /shapes/{id}?subscription=…`).
59
+ *
60
+ * **Idempotent**, and that is the whole point of naming the claim: releasing one that is already
61
+ * gone is a no-op `200` rather than a decrement that steals another subscriber's. A caller whose
62
+ * response was lost may simply send it again.
63
+ *
64
+ * There is no anonymous form here. The engine still accepts a bare `DELETE /shapes/{id}` as a
65
+ * legacy refcount decrement, but it carries no claim identity and is not retry-safe, so this
66
+ * client never issues one.
67
+ *
68
+ * The shape itself survives its other subscribers and then follows the engine's retention
69
+ * lifecycle (idle → dormant → evicted); this is a release, not a delete.
70
+ */
71
+ releaseShape(shapeId: string, subscription: string): Promise<void>;
72
+ /**
73
+ * The engine's convergence barrier (ADR-0056): where replication is, how many
74
+ * computed-but-undelivered subquery flips remain, and how many flip batches the engine gave up
75
+ * on.
76
+ *
77
+ * The engine answers a `sync` field beside these and it is deliberately NOT read: it is the
78
+ * `__el_sync` sentinel watermark — an i64 the engine's conformance harness bumps and waits on as
79
+ * a global quiescence fence — which no pgxsinkit database ever writes, so it is 0 everywhere and
80
+ * says nothing about convergence.
81
+ *
82
+ * `pendingFlips > 0` means a revocation has been computed and not yet written to any stream,
83
+ * which no wire-format watermark can see. That is the term the Electric wire could not express
84
+ * at all, and the reason the barrier is read out of band rather than inferred from a position.
85
+ *
86
+ * `flipFailures > 0` means a batch was **abandoned** after exhausting its propagation retries:
87
+ * those membership effects are gone rather than late. The engine keeps the abandoned batch's
88
+ * `pendingFlips` count held — so the waiting terms never falsely read converged — and latches
89
+ * itself degraded: `/v1/health` answers 503, so do its membership-bearing routes, and a reaper
90
+ * deletes every subquery shape stream. Recovery is an operator restart.
91
+ *
92
+ * The answer is VALIDATED, not cast. An engine that does not report both counters cannot answer
93
+ * the question this barrier asks, and defaulting a missing term to zero would manufacture a
94
+ * converged reading out of an engine that never claimed one.
95
+ */
96
+ replicationState(): Promise<CircuitsReplicationState>;
97
+ };
98
+ export type CircuitsEngineClient = ReturnType<typeof createCircuitsEngineClient>;
99
+ /** What `GET /replication/lsn` answers that this client reads — these fields exactly, no more. */
100
+ export interface CircuitsReplicationState {
101
+ /** The ingest head — where the replication tailer has read to. */
102
+ lsn: string | null;
103
+ pendingFlips: number;
104
+ /**
105
+ * Flip batches the engine abandoned after exhausting their retries. Non-zero means membership
106
+ * effects were **lost**, not delayed: the batch's pending count stays held, the engine is latched
107
+ * degraded, and only a restart clears it.
108
+ */
109
+ flipFailures: number;
110
+ }
111
+ //# sourceMappingURL=engine-client.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"engine-client.d.ts","sourceRoot":"","sources":["../../src/circuits/engine-client.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,mBAAmB,EAAE,kBAAkB,EAAE,MAAM,QAAQ,CAAC;AAEtE,MAAM,WAAW,qBAAqB;IACpC,yFAAyF;IACzF,OAAO,EAAE,MAAM,CAAC;IAChB,2DAA2D;IAC3D,KAAK,CAAC,EAAE,OAAO,KAAK,CAAC;CACtB;AAED;;;;;;;;GAQG;AACH,qBAAa,mBAAoB,SAAQ,KAAK;IAC5C,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IAEtB,YAAY,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAKxD;CACF;AAED;;;;;;GAMG;AACH,wBAAgB,0BAA0B,CAAC,OAAO,EAAE,qBAAqB;IAoBrE;;;;;;;;;;;;;;;;;;;;;;;;;OAyBG;IACG,WAAW,UAAU,kBAAkB,GAAG,OAAO,CAAC,mBAAmB,CAAC;IAe5E;;;;;;;;;;;;;OAaG;IACG,YAAY,UAAU,MAAM,gBAAgB,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAKxE;;;;;;;;;;;;;;;;;;;;;;;OAuBG;IACG,gBAAgB,IAAI,OAAO,CAAC,wBAAwB,CAAC;EAS9D;AA+BD,MAAM,MAAM,oBAAoB,GAAG,UAAU,CAAC,OAAO,0BAA0B,CAAC,CAAC;AAEjF,kGAAkG;AAClG,MAAM,WAAW,wBAAwB;IACvC,kEAAkE;IAClE,GAAG,EAAE,MAAM,GAAG,IAAI,CAAC;IACnB,YAAY,EAAE,MAAM,CAAC;IACrB;;;;OAIG;IACH,YAAY,EAAE,MAAM,CAAC;CACtB"}
@@ -0,0 +1,7 @@
1
+ export * from "./compile";
2
+ export * from "./engine-client";
3
+ export * from "./wire";
4
+ export * from "./edge";
5
+ export * from "./stream-token";
6
+ export * from "./subscribe";
7
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/circuits/index.ts"],"names":[],"mappings":"AAAA,cAAc,WAAW,CAAC;AAC1B,cAAc,iBAAiB,CAAC;AAChC,cAAc,QAAQ,CAAC;AACvB,cAAc,QAAQ,CAAC;AACvB,cAAc,gBAAgB,CAAC;AAC/B,cAAc,aAAa,CAAC"}
@@ -0,0 +1,138 @@
1
+ import type { PredicateValue } from "@pgxsinkit/contracts";
2
+ /**
3
+ * One stream a token admits its bearer to.
4
+ *
5
+ * The grant is **self-describing**: it carries the durable-streams path together with the shape and
6
+ * scope that path serves. That is what keeps the edge stateless. Shape creation happened on whichever
7
+ * replica the client reached, and the edge is replica-scaled, so a path→scope map held in memory
8
+ * would have to be shared between replicas — a second piece of distributed state on the read path,
9
+ * to answer a question the token can simply carry.
10
+ */
11
+ export interface StreamGrant {
12
+ /** The durable-streams path, e.g. `shape/s1`. */
13
+ path: string;
14
+ /** The shape this path serves — the entitlement rule's binding key. */
15
+ shapeKey: string;
16
+ /**
17
+ * The engine claim this grant acquired — one `POST /shapes` join — so the session that holds it can
18
+ * release exactly what it acquired.
19
+ *
20
+ * Carried rather than looked up, for the same reason the path and scope are: the release route is
21
+ * stateless, and the signed token is the only proof of what the control plane handed out. It is not
22
+ * the same thing as {@link StreamGrant.path}: the engine's own id is what `DELETE /shapes/{id}`
23
+ * takes, and two grants can legitimately name ONE shapeId when the engine deduplicated two
24
+ * identical definitions (ADR-0055 decision 6) — which is precisely why release counts grants, not
25
+ * distinct ids.
26
+ */
27
+ shapeId: string;
28
+ /**
29
+ * The **subscription id** this grant's claim was taken under — the name the control plane gave it
30
+ * on `POST /shapes` (fork ADR-0008).
31
+ *
32
+ * Carried for the same reason {@link StreamGrant.shapeId} is: renewal and release are stateless.
33
+ * The re-mint renews this exact claim (the same create, repeated with this id) and the release
34
+ * route drops this exact claim (`DELETE /shapes/{id}?subscription=…`) — both of them from the
35
+ * signed token alone, with nothing remembered server-side. It is also what makes a release
36
+ * idempotent: a claim named is a claim that can only be given back once, however many times the
37
+ * request arrives.
38
+ *
39
+ * Distinct per grant even when two grants share a `shapeId`: two joins onto one deduplicated shape
40
+ * are two claims, and one id could only ever release one of them.
41
+ */
42
+ claim: string;
43
+ /**
44
+ * Scope values, positionally matching the shape's declared scope columns. Shared tier only; a
45
+ * private-tier grant has none, and its authorization is the token itself.
46
+ */
47
+ scope?: readonly PredicateValue[];
48
+ /**
49
+ * PRIVATE TIER ONLY: the fingerprint of the compiled shape request this grant authorized.
50
+ *
51
+ * A re-mint recompiles the shape with the subject's CURRENT claims and admits the grant only if the
52
+ * result fingerprints the same; a grant without one cannot be re-authorized and is revoked. That is
53
+ * what keeps the re-mint stateless — the token carries the thing that was authorized, so nothing
54
+ * server-side has to remember it.
55
+ *
56
+ * Shared-tier grants carry none, and deliberately: their predicate is generated from the scope
57
+ * values alone, so it cannot drift with the subject's claims and the live entitlement re-check is
58
+ * the whole question.
59
+ */
60
+ fp?: string;
61
+ }
62
+ /** The verified body of a stream token. */
63
+ export interface StreamTokenClaims {
64
+ /** The subject the token was minted for. */
65
+ sub: string;
66
+ grants: StreamGrant[];
67
+ /** Issued-at and expiry, seconds since the epoch. */
68
+ iat: number;
69
+ exp: number;
70
+ }
71
+ export interface MintStreamTokenOptions {
72
+ sub: string;
73
+ grants: readonly StreamGrant[];
74
+ /**
75
+ * Lifetime in seconds. The ADR-0055 default is 5 minutes, which is also the revocation bound when
76
+ * a hit-serving third-party CDN sits in front: shorten it where that bound matters more than the
77
+ * re-mint traffic, lengthen it where it does not.
78
+ */
79
+ ttlSeconds?: number;
80
+ /** Seconds since the epoch. Injected so minting is testable and so a batch shares one issue time. */
81
+ now: number;
82
+ }
83
+ export declare const DEFAULT_STREAM_TOKEN_TTL_SECONDS = 300;
84
+ export type StreamTokenVerification = {
85
+ ok: true;
86
+ claims: StreamTokenClaims;
87
+ } | {
88
+ ok: false;
89
+ reason: string;
90
+ };
91
+ /**
92
+ * The signing key. HMAC-SHA256 over a compact JWS: the same process mints and verifies, so there is
93
+ * one trust domain and no reason to pay for asymmetric keys — and no reason to take a JWT dependency
94
+ * into a published library for what Web Crypto already does.
95
+ *
96
+ * The token still IS a JWT, so it stays readable by ordinary tooling when someone has to debug one.
97
+ */
98
+ export declare function importStreamTokenKey(secret: string): Promise<CryptoKey>;
99
+ /**
100
+ * Mint one token for a whole batch of grants.
101
+ *
102
+ * Batched by design, not as an optimisation: a subject in K scopes holds K subscriptions, and
103
+ * re-minting per subscription would put K requests on every TTL boundary for every subject. One
104
+ * token covering all K collapses that to one request per subject per window.
105
+ */
106
+ export declare function mintStreamToken(key: CryptoKey, options: MintStreamTokenOptions): Promise<string>;
107
+ /**
108
+ * Verify a token and read its grants back.
109
+ *
110
+ * `now` is the request-start time, and is passed rather than read here so that a long-poll held open
111
+ * across the expiry is judged by when it started — the alternative silently kills connections
112
+ * mid-flight at the TTL boundary, which presents as a stall rather than as the re-auth it is.
113
+ *
114
+ * Signature verification goes through `crypto.subtle.verify`, so the comparison is the platform's
115
+ * constant-time one rather than a string equality that leaks by how early it diverges.
116
+ */
117
+ export interface VerifyStreamTokenOptions {
118
+ /**
119
+ * Accept a token past its expiry, for the **re-mint path only**.
120
+ *
121
+ * The signature is still verified, so the grants are still ones this control plane issued — that is
122
+ * the whole claim being relied on. Expiry bounds how long a grant keeps *working*, and the re-mint
123
+ * re-authorizes every grant before re-signing — the shared tier against the live entitlement set,
124
+ * the private tier by recompiling its shape against the subject's current claims — so an expired
125
+ * token buys its bearer nothing on its own. Never set this on a read.
126
+ */
127
+ allowExpired?: boolean;
128
+ }
129
+ export declare function verifyStreamToken(key: CryptoKey, token: string, now: number, options?: VerifyStreamTokenOptions): Promise<StreamTokenVerification>;
130
+ /**
131
+ * The grant covering a requested stream path, if the token carries one.
132
+ *
133
+ * Exact path match, deliberately: durable-streams paths are a monotonic counter (`shape/s1`,
134
+ * `shape/s2`, …), so they are enumerable rather than capability-bearing, and any prefix or pattern
135
+ * match over them would hand the bearer streams the control plane never granted.
136
+ */
137
+ export declare function findGrant(claims: StreamTokenClaims, path: string): StreamGrant | undefined;
138
+ //# sourceMappingURL=stream-token.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"stream-token.d.ts","sourceRoot":"","sources":["../../src/circuits/stream-token.ts"],"names":[],"mappings":"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