@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.
- package/README.md +7 -4
- package/dist/circuits/compile.d.ts +66 -0
- package/dist/circuits/compile.d.ts.map +1 -0
- package/dist/circuits/edge.d.ts +188 -0
- package/dist/circuits/edge.d.ts.map +1 -0
- package/dist/circuits/engine-client.d.ts +111 -0
- package/dist/circuits/engine-client.d.ts.map +1 -0
- package/dist/circuits/index.d.ts +7 -0
- package/dist/circuits/index.d.ts.map +1 -0
- package/dist/circuits/stream-token.d.ts +138 -0
- package/dist/circuits/stream-token.d.ts.map +1 -0
- package/dist/circuits/subscribe.d.ts +280 -0
- package/dist/circuits/subscribe.d.ts.map +1 -0
- package/dist/circuits/wire.d.ts +70 -0
- package/dist/circuits/wire.d.ts.map +1 -0
- package/dist/index.d.ts +36 -10
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +801 -286
- package/dist/index.js.map +12 -8
- package/dist/mutations/plpgsql-apply.d.ts +1 -1
- package/package.json +2 -2
- package/skills/deploying/SKILL.md +74 -38
- package/src/circuits/compile.ts +301 -0
- package/src/circuits/edge.ts +386 -0
- package/src/circuits/engine-client.ts +195 -0
- package/src/circuits/index.ts +6 -0
- package/src/circuits/stream-token.ts +224 -0
- package/src/circuits/subscribe.ts +832 -0
- package/src/circuits/wire.ts +71 -0
- package/src/index.ts +136 -31
- package/src/mutations/plpgsql-apply.ts +1 -1
- package/src/router.ts +2 -2
- package/dist/electric-proxy.d.ts +0 -48
- package/dist/electric-proxy.d.ts.map +0 -1
- package/src/electric-proxy.ts +0 -474
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
import type { PredicateValue } from "@pgxsinkit/contracts";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* One stream a token admits its bearer to.
|
|
5
|
+
*
|
|
6
|
+
* The grant is **self-describing**: it carries the durable-streams path together with the shape and
|
|
7
|
+
* scope that path serves. That is what keeps the edge stateless. Shape creation happened on whichever
|
|
8
|
+
* replica the client reached, and the edge is replica-scaled, so a path→scope map held in memory
|
|
9
|
+
* would have to be shared between replicas — a second piece of distributed state on the read path,
|
|
10
|
+
* to answer a question the token can simply carry.
|
|
11
|
+
*/
|
|
12
|
+
export interface StreamGrant {
|
|
13
|
+
/** The durable-streams path, e.g. `shape/s1`. */
|
|
14
|
+
path: string;
|
|
15
|
+
/** The shape this path serves — the entitlement rule's binding key. */
|
|
16
|
+
shapeKey: string;
|
|
17
|
+
/**
|
|
18
|
+
* The engine claim this grant acquired — one `POST /shapes` join — so the session that holds it can
|
|
19
|
+
* release exactly what it acquired.
|
|
20
|
+
*
|
|
21
|
+
* Carried rather than looked up, for the same reason the path and scope are: the release route is
|
|
22
|
+
* stateless, and the signed token is the only proof of what the control plane handed out. It is not
|
|
23
|
+
* the same thing as {@link StreamGrant.path}: the engine's own id is what `DELETE /shapes/{id}`
|
|
24
|
+
* takes, and two grants can legitimately name ONE shapeId when the engine deduplicated two
|
|
25
|
+
* identical definitions (ADR-0055 decision 6) — which is precisely why release counts grants, not
|
|
26
|
+
* distinct ids.
|
|
27
|
+
*/
|
|
28
|
+
shapeId: string;
|
|
29
|
+
/**
|
|
30
|
+
* The **subscription id** this grant's claim was taken under — the name the control plane gave it
|
|
31
|
+
* on `POST /shapes` (fork ADR-0008).
|
|
32
|
+
*
|
|
33
|
+
* Carried for the same reason {@link StreamGrant.shapeId} is: renewal and release are stateless.
|
|
34
|
+
* The re-mint renews this exact claim (the same create, repeated with this id) and the release
|
|
35
|
+
* route drops this exact claim (`DELETE /shapes/{id}?subscription=…`) — both of them from the
|
|
36
|
+
* signed token alone, with nothing remembered server-side. It is also what makes a release
|
|
37
|
+
* idempotent: a claim named is a claim that can only be given back once, however many times the
|
|
38
|
+
* request arrives.
|
|
39
|
+
*
|
|
40
|
+
* Distinct per grant even when two grants share a `shapeId`: two joins onto one deduplicated shape
|
|
41
|
+
* are two claims, and one id could only ever release one of them.
|
|
42
|
+
*/
|
|
43
|
+
claim: string;
|
|
44
|
+
/**
|
|
45
|
+
* Scope values, positionally matching the shape's declared scope columns. Shared tier only; a
|
|
46
|
+
* private-tier grant has none, and its authorization is the token itself.
|
|
47
|
+
*/
|
|
48
|
+
scope?: readonly PredicateValue[];
|
|
49
|
+
/**
|
|
50
|
+
* PRIVATE TIER ONLY: the fingerprint of the compiled shape request this grant authorized.
|
|
51
|
+
*
|
|
52
|
+
* A re-mint recompiles the shape with the subject's CURRENT claims and admits the grant only if the
|
|
53
|
+
* result fingerprints the same; a grant without one cannot be re-authorized and is revoked. That is
|
|
54
|
+
* what keeps the re-mint stateless — the token carries the thing that was authorized, so nothing
|
|
55
|
+
* server-side has to remember it.
|
|
56
|
+
*
|
|
57
|
+
* Shared-tier grants carry none, and deliberately: their predicate is generated from the scope
|
|
58
|
+
* values alone, so it cannot drift with the subject's claims and the live entitlement re-check is
|
|
59
|
+
* the whole question.
|
|
60
|
+
*/
|
|
61
|
+
fp?: string;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** The verified body of a stream token. */
|
|
65
|
+
export interface StreamTokenClaims {
|
|
66
|
+
/** The subject the token was minted for. */
|
|
67
|
+
sub: string;
|
|
68
|
+
grants: StreamGrant[];
|
|
69
|
+
/** Issued-at and expiry, seconds since the epoch. */
|
|
70
|
+
iat: number;
|
|
71
|
+
exp: number;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export interface MintStreamTokenOptions {
|
|
75
|
+
sub: string;
|
|
76
|
+
grants: readonly StreamGrant[];
|
|
77
|
+
/**
|
|
78
|
+
* Lifetime in seconds. The ADR-0055 default is 5 minutes, which is also the revocation bound when
|
|
79
|
+
* a hit-serving third-party CDN sits in front: shorten it where that bound matters more than the
|
|
80
|
+
* re-mint traffic, lengthen it where it does not.
|
|
81
|
+
*/
|
|
82
|
+
ttlSeconds?: number;
|
|
83
|
+
/** Seconds since the epoch. Injected so minting is testable and so a batch shares one issue time. */
|
|
84
|
+
now: number;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export const DEFAULT_STREAM_TOKEN_TTL_SECONDS = 300;
|
|
88
|
+
|
|
89
|
+
export type StreamTokenVerification = { ok: true; claims: StreamTokenClaims } | { ok: false; 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 async function importStreamTokenKey(secret: string): Promise<CryptoKey> {
|
|
99
|
+
return crypto.subtle.importKey("raw", new TextEncoder().encode(secret), { name: "HMAC", hash: "SHA-256" }, false, [
|
|
100
|
+
"sign",
|
|
101
|
+
"verify",
|
|
102
|
+
]);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function base64UrlEncode(bytes: Uint8Array): string {
|
|
106
|
+
return btoa(String.fromCharCode(...bytes))
|
|
107
|
+
.replaceAll("+", "-")
|
|
108
|
+
.replaceAll("/", "_")
|
|
109
|
+
.replaceAll("=", "");
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function base64UrlDecode(value: string): Uint8Array<ArrayBuffer> {
|
|
113
|
+
const padded = value
|
|
114
|
+
.replaceAll("-", "+")
|
|
115
|
+
.replaceAll("_", "/")
|
|
116
|
+
.padEnd(Math.ceil(value.length / 4) * 4, "=");
|
|
117
|
+
const binary = atob(padded);
|
|
118
|
+
const bytes = new Uint8Array(new ArrayBuffer(binary.length));
|
|
119
|
+
for (let index = 0; index < binary.length; index += 1) bytes[index] = binary.charCodeAt(index);
|
|
120
|
+
return bytes;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
const HEADER = base64UrlEncode(new TextEncoder().encode(JSON.stringify({ alg: "HS256", typ: "JWT" })));
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* Mint one token for a whole batch of grants.
|
|
127
|
+
*
|
|
128
|
+
* Batched by design, not as an optimisation: a subject in K scopes holds K subscriptions, and
|
|
129
|
+
* re-minting per subscription would put K requests on every TTL boundary for every subject. One
|
|
130
|
+
* token covering all K collapses that to one request per subject per window.
|
|
131
|
+
*/
|
|
132
|
+
export async function mintStreamToken(key: CryptoKey, options: MintStreamTokenOptions): Promise<string> {
|
|
133
|
+
const ttl = options.ttlSeconds ?? DEFAULT_STREAM_TOKEN_TTL_SECONDS;
|
|
134
|
+
const claims: StreamTokenClaims = {
|
|
135
|
+
sub: options.sub,
|
|
136
|
+
grants: options.grants.map((grant) => ({
|
|
137
|
+
path: grant.path,
|
|
138
|
+
shapeKey: grant.shapeKey,
|
|
139
|
+
shapeId: grant.shapeId,
|
|
140
|
+
claim: grant.claim,
|
|
141
|
+
...(grant.scope !== undefined ? { scope: [...grant.scope] } : {}),
|
|
142
|
+
...(grant.fp !== undefined ? { fp: grant.fp } : {}),
|
|
143
|
+
})),
|
|
144
|
+
iat: options.now,
|
|
145
|
+
exp: options.now + ttl,
|
|
146
|
+
};
|
|
147
|
+
|
|
148
|
+
const body = base64UrlEncode(new TextEncoder().encode(JSON.stringify(claims)));
|
|
149
|
+
const signingInput = `${HEADER}.${body}`;
|
|
150
|
+
const signature = await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(signingInput));
|
|
151
|
+
return `${signingInput}.${base64UrlEncode(new Uint8Array(signature))}`;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* Verify a token and read its grants back.
|
|
156
|
+
*
|
|
157
|
+
* `now` is the request-start time, and is passed rather than read here so that a long-poll held open
|
|
158
|
+
* across the expiry is judged by when it started — the alternative silently kills connections
|
|
159
|
+
* mid-flight at the TTL boundary, which presents as a stall rather than as the re-auth it is.
|
|
160
|
+
*
|
|
161
|
+
* Signature verification goes through `crypto.subtle.verify`, so the comparison is the platform's
|
|
162
|
+
* constant-time one rather than a string equality that leaks by how early it diverges.
|
|
163
|
+
*/
|
|
164
|
+
export interface VerifyStreamTokenOptions {
|
|
165
|
+
/**
|
|
166
|
+
* Accept a token past its expiry, for the **re-mint path only**.
|
|
167
|
+
*
|
|
168
|
+
* The signature is still verified, so the grants are still ones this control plane issued — that is
|
|
169
|
+
* the whole claim being relied on. Expiry bounds how long a grant keeps *working*, and the re-mint
|
|
170
|
+
* re-authorizes every grant before re-signing — the shared tier against the live entitlement set,
|
|
171
|
+
* the private tier by recompiling its shape against the subject's current claims — so an expired
|
|
172
|
+
* token buys its bearer nothing on its own. Never set this on a read.
|
|
173
|
+
*/
|
|
174
|
+
allowExpired?: boolean;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
export async function verifyStreamToken(
|
|
178
|
+
key: CryptoKey,
|
|
179
|
+
token: string,
|
|
180
|
+
now: number,
|
|
181
|
+
options?: VerifyStreamTokenOptions,
|
|
182
|
+
): Promise<StreamTokenVerification> {
|
|
183
|
+
const parts = token.split(".");
|
|
184
|
+
if (parts.length !== 3) return { ok: false, reason: "malformed token" };
|
|
185
|
+
const [header, body, signature] = parts as [string, string, string];
|
|
186
|
+
if (header !== HEADER) return { ok: false, reason: "unexpected token header" };
|
|
187
|
+
|
|
188
|
+
let valid: boolean;
|
|
189
|
+
try {
|
|
190
|
+
valid = await crypto.subtle.verify(
|
|
191
|
+
"HMAC",
|
|
192
|
+
key,
|
|
193
|
+
base64UrlDecode(signature),
|
|
194
|
+
new TextEncoder().encode(`${header}.${body}`),
|
|
195
|
+
);
|
|
196
|
+
} catch {
|
|
197
|
+
return { ok: false, reason: "malformed signature" };
|
|
198
|
+
}
|
|
199
|
+
if (!valid) return { ok: false, reason: "bad signature" };
|
|
200
|
+
|
|
201
|
+
let claims: StreamTokenClaims;
|
|
202
|
+
try {
|
|
203
|
+
claims = JSON.parse(new TextDecoder().decode(base64UrlDecode(body))) as StreamTokenClaims;
|
|
204
|
+
} catch {
|
|
205
|
+
return { ok: false, reason: "malformed payload" };
|
|
206
|
+
}
|
|
207
|
+
if (typeof claims.sub !== "string" || !Array.isArray(claims.grants) || typeof claims.exp !== "number") {
|
|
208
|
+
return { ok: false, reason: "malformed payload" };
|
|
209
|
+
}
|
|
210
|
+
if (claims.exp <= now && options?.allowExpired !== true) return { ok: false, reason: "expired" };
|
|
211
|
+
|
|
212
|
+
return { ok: true, claims };
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
/**
|
|
216
|
+
* The grant covering a requested stream path, if the token carries one.
|
|
217
|
+
*
|
|
218
|
+
* Exact path match, deliberately: durable-streams paths are a monotonic counter (`shape/s1`,
|
|
219
|
+
* `shape/s2`, …), so they are enumerable rather than capability-bearing, and any prefix or pattern
|
|
220
|
+
* match over them would hand the bearer streams the control plane never granted.
|
|
221
|
+
*/
|
|
222
|
+
export function findGrant(claims: StreamTokenClaims, path: string): StreamGrant | undefined {
|
|
223
|
+
return claims.grants.find((grant) => grant.path === path);
|
|
224
|
+
}
|