@plitzi/sdk-kernel 0.0.0-stage → 0.39.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (142) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/README.md +80 -2
  3. package/dist/build/esbuild.d.ts +16 -0
  4. package/dist/build/index.d.ts +1 -0
  5. package/dist/build/index.mjs +35 -0
  6. package/dist/cache/CompressedFileCache.d.ts +18 -0
  7. package/dist/cache/TtlCache.d.ts +65 -0
  8. package/dist/cache/index.d.ts +3 -0
  9. package/dist/cache/index.mjs +1 -0
  10. package/dist/chunks/TtlCache-J_jG9oL9.mjs +200 -0
  11. package/dist/chunks/channel-DnVf7PJB.mjs +190 -0
  12. package/dist/chunks/csrf-BLWcaYOV.mjs +295 -0
  13. package/dist/chunks/link-C9wyDS9H.mjs +124 -0
  14. package/dist/chunks/query-DGbrN3mN.mjs +20 -0
  15. package/dist/chunks/scopes-Co6ZjhAm.mjs +46 -0
  16. package/dist/chunks/serverLog-BKaKjjc4.mjs +137 -0
  17. package/dist/chunks/session-B-dTEjeG.mjs +253 -0
  18. package/dist/chunks/sessionActivity-Ch7xuQ_o.mjs +43 -0
  19. package/dist/chunks/spaceDeployment-J2IMLfij.mjs +76 -0
  20. package/dist/chunks/stage-y6deE9LJ.mjs +345 -0
  21. package/dist/chunks/supervisor-Dh34v1vq.mjs +117 -0
  22. package/dist/chunks/tail-D-USrZIR.mjs +55 -0
  23. package/dist/chunks/tokens-BAV5YeT9.mjs +273 -0
  24. package/dist/data/index.d.ts +2 -0
  25. package/dist/data/index.mjs +68 -0
  26. package/dist/data/projectData.d.ts +21 -0
  27. package/dist/deployment/hostDeployment.d.ts +8 -0
  28. package/dist/deployment/index.d.ts +3 -0
  29. package/dist/deployment/index.mjs +19 -0
  30. package/dist/deployment/spaceDeployment.d.ts +11 -0
  31. package/dist/engine/index.d.ts +2 -0
  32. package/dist/engine/index.mjs +1 -0
  33. package/dist/engine/page.d.ts +49 -0
  34. package/dist/engine/rsc.d.ts +32 -0
  35. package/dist/files/atomicFile.d.ts +10 -0
  36. package/dist/files/index.d.ts +1 -0
  37. package/dist/files/index.mjs +32 -0
  38. package/dist/http/bearer.d.ts +5 -0
  39. package/dist/http/buildResponseHelpers.d.ts +23 -0
  40. package/dist/http/closeOnSignals.d.ts +28 -0
  41. package/dist/http/compress.d.ts +20 -0
  42. package/dist/http/dispatcher.d.ts +15 -0
  43. package/dist/http/drain.d.ts +18 -0
  44. package/dist/http/fleet/channel.d.ts +103 -0
  45. package/dist/http/fleet/link.d.ts +28 -0
  46. package/dist/http/fleet/role.d.ts +46 -0
  47. package/dist/http/fleet/supervisor.d.ts +29 -0
  48. package/dist/http/freePort.d.ts +24 -0
  49. package/dist/http/health.d.ts +21 -0
  50. package/dist/http/index.d.ts +48 -0
  51. package/dist/http/index.mjs +1313 -0
  52. package/dist/http/middlewares/auth.d.ts +2 -0
  53. package/dist/http/middlewares/basicAuth.d.ts +6 -0
  54. package/dist/http/mimeTypes.d.ts +13 -0
  55. package/dist/http/navigation.d.ts +14 -0
  56. package/dist/http/onAbort.d.ts +12 -0
  57. package/dist/http/probes.d.ts +4 -0
  58. package/dist/http/requestParser.d.ts +22 -0
  59. package/dist/http/runMiddlewares.d.ts +6 -0
  60. package/dist/http/securityHeaders.d.ts +18 -0
  61. package/dist/http/server.d.ts +39 -0
  62. package/dist/http/socketResponse.d.ts +18 -0
  63. package/dist/http/sse.d.ts +26 -0
  64. package/dist/http/stages/crossSiteWrites.d.ts +24 -0
  65. package/dist/http/stages/health.d.ts +11 -0
  66. package/dist/http/stages/middlewares.d.ts +3 -0
  67. package/dist/http/stages/static.d.ts +4 -0
  68. package/dist/http/staticFiles.d.ts +3 -0
  69. package/dist/http/stopping.d.ts +11 -0
  70. package/dist/http/transports.d.ts +31 -0
  71. package/dist/http/types.d.ts +29 -0
  72. package/dist/http/unusedPort.d.ts +10 -0
  73. package/dist/http/webExchange.d.ts +18 -0
  74. package/dist/http/wsFrame.d.ts +3 -0
  75. package/dist/identity/accounts.d.ts +278 -0
  76. package/dist/identity/authorize.d.ts +96 -0
  77. package/dist/identity/credentials.d.ts +40 -0
  78. package/dist/identity/csrf.d.ts +139 -0
  79. package/dist/identity/debugAuthorization.d.ts +24 -0
  80. package/dist/identity/domains.d.ts +41 -0
  81. package/dist/identity/identity.d.ts +119 -0
  82. package/dist/identity/index.d.ts +21 -0
  83. package/dist/identity/index.mjs +731 -0
  84. package/dist/identity/passwords.d.ts +15 -0
  85. package/dist/identity/previewToken.d.ts +21 -0
  86. package/dist/identity/requestIdentity.d.ts +14 -0
  87. package/dist/identity/scopes.d.ts +56 -0
  88. package/dist/identity/session.d.ts +185 -0
  89. package/dist/identity/sessionActivity.d.ts +11 -0
  90. package/dist/identity/spaceTokens.d.ts +174 -0
  91. package/dist/index.d.ts +17 -0
  92. package/dist/index.mjs +1 -0
  93. package/dist/log/index.d.ts +3 -0
  94. package/dist/log/index.mjs +3 -0
  95. package/dist/log/serverLog.d.ts +49 -0
  96. package/dist/log/tail.d.ts +43 -0
  97. package/dist/mysql/accounts.d.ts +4 -0
  98. package/dist/mysql/admin.d.ts +58 -0
  99. package/dist/mysql/config.d.ts +82 -0
  100. package/dist/mysql/identities.d.ts +35 -0
  101. package/dist/mysql/index.d.ts +7 -0
  102. package/dist/mysql/index.mjs +1203 -0
  103. package/dist/mysql/pool.d.ts +3 -0
  104. package/dist/mysql/query.d.ts +12 -0
  105. package/dist/mysql/schema.d.ts +43 -0
  106. package/dist/mysql/sessions.d.ts +23 -0
  107. package/dist/mysql/spaceTokens.d.ts +11 -0
  108. package/dist/mysql/store.d.ts +66 -0
  109. package/dist/outbound/index.d.ts +4 -0
  110. package/dist/outbound/index.mjs +314 -0
  111. package/dist/outbound/inside.d.ts +36 -0
  112. package/dist/outbound/outboundGuard.d.ts +69 -0
  113. package/dist/pubsub/index.d.ts +3 -0
  114. package/dist/pubsub/index.mjs +76 -0
  115. package/dist/pubsub/memoryPubSub.d.ts +10 -0
  116. package/dist/pubsub/redisPubSub.d.ts +24 -0
  117. package/dist/stats/index.d.ts +9 -0
  118. package/dist/stats/index.mjs +228 -0
  119. package/dist/stats/load.d.ts +31 -0
  120. package/dist/stats/memory.d.ts +20 -0
  121. package/dist/stats/pools.d.ts +15 -0
  122. package/dist/stats/recorder.d.ts +34 -0
  123. package/dist/stats/stage.d.ts +15 -0
  124. package/dist/stats/types.d.ts +309 -0
  125. package/dist/testing/certificates.d.ts +21 -0
  126. package/dist/testing/fleet.d.ts +28 -0
  127. package/dist/testing/goneRuns.d.ts +5 -0
  128. package/dist/testing/index.d.ts +5 -0
  129. package/dist/testing/index.mjs +270 -0
  130. package/dist/testing/keys.d.ts +2 -0
  131. package/dist/testing/runNames.d.ts +10 -0
  132. package/dist/tokens/index.d.ts +2 -0
  133. package/dist/tokens/index.mjs +1 -0
  134. package/dist/tokens/tokens.d.ts +195 -0
  135. package/dist/types/adapters.d.ts +388 -0
  136. package/dist/types/config.d.ts +240 -0
  137. package/dist/types/index.d.ts +5 -0
  138. package/dist/types/index.mjs +1 -0
  139. package/dist/types/log.d.ts +119 -0
  140. package/dist/types/oauth.d.ts +246 -0
  141. package/dist/types/pipeline.d.ts +239 -0
  142. package/package.json +67 -3
@@ -0,0 +1,295 @@
1
+ import { h as sessionCookieParams, n as appendCookies } from "./session-B-dTEjeG.mjs";
2
+ import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
3
+ // src/identity/csrf.ts
4
+ /**
5
+ * Cross-site request forgery: a page on another site causing a request here that the visitor did not mean to make.
6
+ *
7
+ * There are **two** attacks under that name, and they need different answers — conflating them is how a server
8
+ * ends up either refusing legitimate sign-ins or leaving login CSRF wide open.
9
+ *
10
+ * 1. **An action taken as somebody.** A cookie is attached by the browser to every request to its origin,
11
+ * including ones another site caused. `SameSite=Lax`, the default, keeps the cookie off another site's writes; a
12
+ * deployment that sets `None` — a space embedded in an iframe on somebody else's domain, which is exactly what `Lax`
13
+ * exists to prevent — has it on all of them. Answered by a token, demanded whenever a session cookie is present,
14
+ * whichever it is.
15
+ * 2. **Login CSRF.** Another site signs the visitor into an account IT controls, so what they do next is recorded
16
+ * against it. There is no cookie yet to look for, so the first answer does not apply at all. Answered by
17
+ * `foreign` below: where the request came from, which is what separates it from a legitimate sign-in.
18
+ *
19
+ * A request carrying `Authorization: Bearer` is at risk from neither and is never asked for a token: a
20
+ * cross-origin page cannot set that header without a preflight the server would have to allow. Requiring one
21
+ * there would break every API client to protect nobody.
22
+ *
23
+ * The token is a signed double-submit cookie: an HMAC over a nonce **and the session it belongs to**, handed to
24
+ * the page in a readable cookie and echoed back in a header. An attacker's page cannot read the cookie, so it
25
+ * cannot produce the header; and unlike plain double-submit, somebody who can merely *write* a cookie — a
26
+ * sub-domain they took over — still cannot forge one, because they do not have the secret.
27
+ */
28
+ var VERSION = "v1";
29
+ /** GET, HEAD and OPTIONS change nothing, and demanding a token for them would break every ordinary navigation. */
30
+ var SAFE_METHODS = /* @__PURE__ */ new Set([
31
+ "GET",
32
+ "HEAD",
33
+ "OPTIONS"
34
+ ]);
35
+ /** Where the echo is looked for, and the field a `<form>` may carry it in instead. */
36
+ var HEADER_NAME = "x-csrf-token";
37
+ var FIELD_NAME = "_csrf";
38
+ /** Twelve hours: long enough for a working day, short enough to bound a leak. */
39
+ var TOKEN_LIFETIME = 43200;
40
+ var csrfFailureMessage = {
41
+ missing: "A CSRF token is required",
42
+ malformed: "CSRF token malformed",
43
+ expired: "CSRF token expired",
44
+ mismatch: "CSRF token does not match this session",
45
+ foreign: "A request from another origin may not act with this session"
46
+ };
47
+ /**
48
+ * The carrier, read off whatever request a host hands over — named field by field, never spread.
49
+ *
50
+ * A spread copies OWN properties, and on Node's `IncomingMessage` (which an Express request is) `headers` is a getter on
51
+ * the prototype: `{ ...req }` arrives with no headers at all, and the first header read throws. Every guard built on a
52
+ * spread failed that way on every request.
53
+ */
54
+ var carrierOf = (req, method = req.method) => ({
55
+ method,
56
+ headers: req.headers,
57
+ hostname: req.hostname,
58
+ ...req.cookies && typeof req.cookies === "object" ? { cookies: req.cookies } : {},
59
+ body: req.body
60
+ });
61
+ var equal = (a, b) => {
62
+ const left = Buffer.from(a);
63
+ const right = Buffer.from(b);
64
+ return left.length === right.length && timingSafeEqual(left, right);
65
+ };
66
+ var header = (carrier, name) => {
67
+ const value = carrier.headers[name];
68
+ return typeof value === "string" ? value : void 0;
69
+ };
70
+ var readCookieHeader = (carrier, name) => {
71
+ if (carrier.cookies?.[name] !== void 0) return carrier.cookies[name];
72
+ const raw = header(carrier, "cookie");
73
+ if (!raw) return;
74
+ for (const part of raw.split(";")) {
75
+ const index = part.indexOf("=");
76
+ if (index !== -1 && part.slice(0, index).trim() === name) return decodeURIComponent(part.slice(index + 1).trim());
77
+ }
78
+ };
79
+ /**
80
+ * Whether `origin` is the request's own: its host AND port, as the request was addressed.
81
+ *
82
+ * The authority is the one that names the hostname the request is answered as, compared port included:
83
+ *
84
+ * - **the request's own** first — HTTP/2's `:authority` (which carries no `Host` header at all), or `Host`;
85
+ * - **`X-Forwarded-Host`** only when that does not: a host that took its hostname from the header trusts the proxy in
86
+ * front of it (Express's `trust proxy`), and that proxy wrote it. Read before the request's own, a client could send
87
+ * one naming this host on another port, and that port would count as this server's.
88
+ *
89
+ * None naming it: nothing says which port the request reached, so the origin is not taken as its own — comparing the
90
+ * name alone made every port and every scheme of this host count.
91
+ */
92
+ var isOwnOrigin = (origin, carrier) => {
93
+ let url;
94
+ try {
95
+ url = new URL(origin);
96
+ } catch {
97
+ return false;
98
+ }
99
+ const forwarded = header(carrier, "x-forwarded-host")?.split(",")[0]?.trim();
100
+ for (const authority of [
101
+ header(carrier, ":authority"),
102
+ header(carrier, "host"),
103
+ forwarded
104
+ ]) {
105
+ if (!authority) continue;
106
+ let own;
107
+ try {
108
+ own = new URL(`${url.protocol}//${authority}`);
109
+ } catch {
110
+ continue;
111
+ }
112
+ if (own.hostname === carrier.hostname) return url.host === own.host;
113
+ }
114
+ return false;
115
+ };
116
+ /**
117
+ * Did a page of another ORIGIN cause this request — `allowed` naming the origins this deployment counts as its own?
118
+ *
119
+ * This is what protects signing in, where there is no session to bind a token to and no cookie to look for, and
120
+ * every write a page server answers, cookie or none (`crossSiteWritesStage`). It rests on two headers a page CANNOT
121
+ * set — the browser attaches both, and script may not override either:
122
+ *
123
+ * - **`Sec-Fetch-Site`** is the browser's own account of where the request came from, and is believed first.
124
+ * `same-origin`, and `none` (a typed URL, a bookmark), are this server's own; `same-site` and `cross-site` are a
125
+ * page of another origin, foreign unless its origin was named.
126
+ * - **`Origin`** is the fallback, for a browser too old to send the above — Safari only did from 16.4. Matched
127
+ * **exactly** — host and port, over HTTP/1.1 and HTTP/2 alike; one port does not serve two schemes — against the
128
+ * authority the request was addressed to, or an origin the deployment named.
129
+ *
130
+ * **`same-site` is not trusted, and was once.** A site is a registrable domain, with no port in it: another port of
131
+ * this host, or a sibling sub-domain, is the same site. Both are where somebody else's code is served by design —
132
+ * `createAuthoringHost` on a port of its own, every space of a platform on a sub-domain of one domain (two spaces at
133
+ * `*.plitzi.app` are one site until that domain is on the public suffix list) — and trusting the site let any of them
134
+ * write here as if they were this server's own pages. A sibling that IS this deployment's own is named, as it always
135
+ * had to be in production, where the app and its spaces are on different sites: `createAuth` fills the list from
136
+ * `identity.platformOrigins`, a page server from `crossSiteWrites.origins`.
137
+ *
138
+ * Nor is a domain boundary guessed: this once compared *registrable domains*, last-two-labels, and with no public
139
+ * suffix list every other `.co.uk` counted as the same site as a deployment at `acme.co.uk`.
140
+ *
141
+ * **Neither header means this is not a browser**, and a client that is not a browser cannot be made to forge
142
+ * anything: there is no victim's session sitting in it. That is what keeps every API client, mobile app and
143
+ * script signing in with nothing extra to send.
144
+ */
145
+ var crossSiteRequest = (carrier, allowed = () => false) => {
146
+ const site = header(carrier, "sec-fetch-site");
147
+ const origin = header(carrier, "origin");
148
+ const vouched = origin !== void 0 && allowed(origin);
149
+ if (site !== void 0) return site !== "same-origin" && site !== "none" && !vouched;
150
+ if (!origin) return false;
151
+ return !isOwnOrigin(origin, carrier) && !vouched;
152
+ };
153
+ var createCsrf = (config) => {
154
+ const { secret, cookie, allowedOrigins = [] } = config;
155
+ const permitted = (origin) => typeof allowedOrigins === "function" ? allowedOrigins(origin) : allowedOrigins.includes(origin);
156
+ const foreign = (carrier, alsoAllowed = []) => crossSiteRequest(carrier, (origin) => permitted(origin) || alsoAllowed.includes(origin));
157
+ const nameFor = (hostname) => `${sessionCookieParams({ hostname }, cookie).name}_csrf`;
158
+ const sign = (nonce, expiry, binding) => createHmac("sha256", secret).update(`${nonce}.${expiry}.${binding}`).digest("base64url");
159
+ /**
160
+ * `binding` is what ties a token to one session. Hashed rather than used raw so the token never carries a
161
+ * credential, even indirectly: it goes in a cookie a page can read.
162
+ */
163
+ const bind = (sessionToken) => sessionToken ? createHmac("sha256", secret).update(sessionToken).digest("base64url") : "";
164
+ /**
165
+ * A token for this session, or for none.
166
+ *
167
+ * The unbound form is what protects sign-in itself: a page asks for one before anybody is authenticated, which
168
+ * is what stops another site logging a visitor into an account it controls. It is upgraded to a bound one the
169
+ * moment a session exists, and a bound token is refused for a different session.
170
+ */
171
+ const issue = (sessionToken) => {
172
+ const nonce = randomBytes(16).toString("base64url");
173
+ const expiry = Math.floor(Date.now() / 1e3) + TOKEN_LIFETIME;
174
+ return `${VERSION}.${nonce}.${expiry}.${sign(nonce, expiry, bind(sessionToken))}`;
175
+ };
176
+ /** One place the cookie's attributes are decided, so writing it and dropping it cannot disagree about them. */
177
+ const serialize = (req, value, maxAge) => {
178
+ const params = sessionCookieParams(req, cookie);
179
+ return [
180
+ `${nameFor(req.hostname)}=${value}`,
181
+ "Path=/",
182
+ `SameSite=${params.sameSite === "none" ? "None" : "Lax"}`,
183
+ `Max-Age=${maxAge}`,
184
+ ...params.domain ? [`Domain=${params.domain}`] : [],
185
+ ...params.secure ? ["Secure"] : []
186
+ ].join("; ");
187
+ };
188
+ const check = (token, sessionToken) => {
189
+ if (!token) return {
190
+ ok: false,
191
+ reason: "missing"
192
+ };
193
+ const [version, nonce, expiry, signature] = token.split(".");
194
+ if (version !== VERSION || !nonce || !expiry || !signature) return {
195
+ ok: false,
196
+ reason: "malformed"
197
+ };
198
+ const expiresAt = Number(expiry);
199
+ if (!Number.isFinite(expiresAt)) return {
200
+ ok: false,
201
+ reason: "malformed"
202
+ };
203
+ if (expiresAt < Math.floor(Date.now() / 1e3)) return {
204
+ ok: false,
205
+ reason: "expired"
206
+ };
207
+ /**
208
+ * Verified against the session the request actually carries. A token minted for nobody does NOT satisfy a
209
+ * request that has a session — otherwise an attacker could mint one from their own browser, where they are
210
+ * signed out, and replay it against a victim who is not.
211
+ */
212
+ if (!equal(signature, sign(nonce, expiresAt, bind(sessionToken)))) return {
213
+ ok: false,
214
+ reason: "mismatch"
215
+ };
216
+ return { ok: true };
217
+ };
218
+ return {
219
+ issue,
220
+ /** The name the cookie lands under, for a client that reads it by hand. */
221
+ cookieName: nameFor,
222
+ /** The header the echo is expected in, published by `GET /auth/csrf` so a client is never told it twice. */
223
+ headerName: HEADER_NAME,
224
+ /** Readable on purpose: `httpOnly` would make it impossible for a page to echo it back. It is not a credential. */
225
+ write: (req, res, token) => {
226
+ appendCookies(res, [serialize(req, encodeURIComponent(token), TOKEN_LIFETIME)]);
227
+ },
228
+ /**
229
+ * Drops the cookie, on the same attributes it was written with — anything else leaves the original in place and
230
+ * adds a second one the browser then has to choose between.
231
+ *
232
+ * Called when a session ends. Nothing depended on it going: the token is signed over the session it belongs to,
233
+ * so once that session is revoked it verifies against nothing, and a write is only ever asked for a token when a
234
+ * session cookie is present. But a logout that leaves a cookie behind is one somebody has to reason about to
235
+ * dismiss, and on a shared browser "signed out" should mean nothing of the session is still sitting there.
236
+ */
237
+ clear: (req, res) => {
238
+ appendCookies(res, [serialize(req, "", 0)]);
239
+ },
240
+ read: (carrier) => readCookieHeader(carrier, nameFor(carrier.hostname)),
241
+ /**
242
+ * Does this request need a token at all?
243
+ *
244
+ * Two requests can never be forged into, whatever they are reaching, and neither is ever asked:
245
+ *
246
+ * - a **safe method**, which changes nothing;
247
+ * - one presenting **`Authorization: Bearer`** — a cross-origin page cannot set that header without a
248
+ * preflight this server would have to allow, so requiring a token would break every API client to protect
249
+ * nobody.
250
+ *
251
+ * After that it depends on what the flow does, which is what `subject` says — an action taken as somebody is
252
+ * protected by the session cookie's presence, a sign-in by where the request came from. See {@link CsrfSubject}.
253
+ */
254
+ required: (carrier, subject = "write") => {
255
+ if (SAFE_METHODS.has((carrier.method ?? "GET").toUpperCase()) || header(carrier, "authorization")) return false;
256
+ if (subject === "delegated") return false;
257
+ if (subject === "signIn")
258
+ /**
259
+ * Not "is there a session cookie". A sign-in does not act on the session the request carries — it
260
+ * REPLACES it — so a browser still holding a stale one was being refused the very request that fixes
261
+ * that. What matters is whether another site caused this.
262
+ */
263
+ return foreign(carrier);
264
+ return readCookieHeader(carrier, sessionCookieParams({ hostname: carrier.hostname }, cookie).name) !== void 0;
265
+ },
266
+ /**
267
+ * Whether a browser sent this from a site this deployment does not recognise — its own origins, and
268
+ * `alsoAllowed` (the origins a SPACE declared, for a request that carries that space's credential).
269
+ *
270
+ * The rule `signIn` flows are guarded by, offered on its own for a router whose writes cannot all carry a token:
271
+ * a cookie-carried write that a foreign page caused is refused by where it came from — see
272
+ * `createOriginGuardMiddleware`. A request with neither Fetch Metadata nor `Origin` is not a browser's, and is
273
+ * never foreign: there is no victim's session in a script.
274
+ */
275
+ crossSite: (carrier, alsoAllowed) => foreign(carrier, alsoAllowed),
276
+ /**
277
+ * The whole check. The echoed token must verify against the session the request carries, and — when the
278
+ * cookie is also present — match it. The second half costs nothing and blocks a token that leaked somewhere
279
+ * the cookie did not.
280
+ */
281
+ verify: (carrier, sessionToken) => {
282
+ const field = carrier.body?.[FIELD_NAME];
283
+ const echoed = header(carrier, HEADER_NAME) ?? (typeof field === "string" ? field : void 0);
284
+ const result = check(echoed, sessionToken);
285
+ if (!result.ok) return result;
286
+ const fromCookie = readCookieHeader(carrier, nameFor(carrier.hostname));
287
+ if (fromCookie !== void 0 && !equal(fromCookie, echoed)) return {
288
+ ok: false,
289
+ reason: "mismatch"
290
+ };
291
+ return { ok: true };
292
+ }
293
+ };
294
+ };
295
+ export { csrfFailureMessage as i, createCsrf as n, crossSiteRequest as r, carrierOf as t };
@@ -0,0 +1,124 @@
1
+ import { i as createStoreHost, n as createFleetHub, o as isFleetMessage, r as createListeners, t as createFleetClient } from "./channel-DnVf7PJB.mjs";
2
+ import { c as serverLog } from "./serverLog-BKaKjjc4.mjs";
3
+ import cluster from "node:cluster";
4
+ import { availableParallelism } from "node:os";
5
+ // src/http/fleet/role.ts
6
+ /** What the deployment's environment says, when its code says nothing: `SDK_SERVER_WORKERS=1`, `=auto`, `=false`. */
7
+ var fromEnvironment = (raw) => {
8
+ if (raw === void 0 || raw.trim() === "") return;
9
+ const value = raw.trim().toLowerCase();
10
+ if (value === "auto" || value === "true") return "auto";
11
+ if (value === "false" || value === "off") return false;
12
+ return Number(value);
13
+ };
14
+ /**
15
+ * How many processes serve the port.
16
+ *
17
+ * On by default in production — one per core the process may use, which `availableParallelism` reads from the
18
+ * container's CPU quota too, so a quarter-core container gets one. Off by default anywhere else: a development server
19
+ * under `--watch` or a debugger, and a test runner that starts servers in its own process, must stay one process.
20
+ * The config wins over `SDK_SERVER_WORKERS`, which wins over the default.
21
+ *
22
+ * A number is a ceiling, not a demand: more processes than cores only take turns on the same cores, each with its
23
+ * own memory, so it is lowered to the cores there are and the plan says it was.
24
+ */
25
+ var resolveWorkers = (option, environment = process.env, cores = availableParallelism()) => {
26
+ const available = Math.max(1, cores);
27
+ const chosen = option ?? fromEnvironment(environment.SDK_SERVER_WORKERS) ?? (environment.NODE_ENV === "production" ? "auto" : false);
28
+ if (chosen === false) return { count: 1 };
29
+ if (chosen === true || chosen === "auto") return { count: available };
30
+ if (!Number.isInteger(chosen) || chosen < 1) throw new Error(`workers must be true, false, 'auto' or a whole number from 1 — got ${String(chosen)}`);
31
+ return chosen > available ? {
32
+ count: available,
33
+ requested: chosen
34
+ } : { count: chosen };
35
+ };
36
+ /**
37
+ * Only a worker a primary of ours forked carries this: a process that is a cluster worker of something else —
38
+ * PM2's cluster mode, a deployment's own `cluster.fork` — is a single server, with nobody to answer its calls.
39
+ */
40
+ var FLEET_ENV = "SDK_SERVER_FLEET";
41
+ var JOBS_ENV = "SDK_SERVER_FLEET_JOBS";
42
+ /** The environment the primary gives a worker it forks — and the one worker that carries the fleet's jobs. */
43
+ var fleetWorkerEnv = (runsJobs) => ({
44
+ [FLEET_ENV]: "1",
45
+ [JOBS_ENV]: runsJobs ? "1" : "0"
46
+ });
47
+ var isFleetWorker = () => cluster.isWorker && process.env[FLEET_ENV] === "1";
48
+ var fleetRole = (plan) => {
49
+ if (isFleetWorker()) return "worker";
50
+ return plan.count > 1 && cluster.isPrimary ? "primary" : "single";
51
+ };
52
+ /**
53
+ * Whether this process runs the scheduler and the job consumers.
54
+ *
55
+ * A single server, yes, as it always did. Of a fleet, one worker only: its workers are one replica, and a replica's
56
+ * `jobs` settings — how many run at once, whether it schedules at all — are for the replica, not for each of its
57
+ * processes. The primary hands the role to the replacement of the worker that carried it.
58
+ */
59
+ var runsFleetJobs = () => !isFleetWorker() || process.env[JOBS_ENV] === "1";
60
+ // src/http/fleet/link.ts
61
+ var listeners = createListeners((channel, error) => serverLog.error("fleet", `a broadcast on "${channel}" failed here`, error));
62
+ var client;
63
+ var hub;
64
+ var workerClient = () => {
65
+ if (client) return client;
66
+ const created = createFleetClient((message) => {
67
+ if (!process.send) throw new Error("this worker has no channel to its primary");
68
+ process.send(message);
69
+ }, listeners.deliver);
70
+ process.on("message", (message) => {
71
+ if (isFleetMessage(message)) created.receive(message);
72
+ });
73
+ process.once("disconnect", () => created.close());
74
+ client = created;
75
+ return created;
76
+ };
77
+ /**
78
+ * The primary's hub: it answers its workers from the stores in `catalogue`, made when first asked for, and passes
79
+ * broadcasts on. Started before the first fork, so no worker can ask before anyone is answering.
80
+ */
81
+ var startHub = (catalogue) => {
82
+ if (hub) return;
83
+ const created = createFleetHub({
84
+ host: createStoreHost(catalogue),
85
+ deliver: listeners.deliver,
86
+ peers: () => Object.values(cluster.workers ?? {}).flatMap((worker) => worker?.isConnected() ? [{
87
+ id: worker.id,
88
+ send: (message) => worker.send(message)
89
+ }] : [])
90
+ });
91
+ cluster.on("message", (worker, message) => {
92
+ if (isFleetMessage(message)) created.receive(worker.id, message);
93
+ });
94
+ hub = created;
95
+ };
96
+ /** The n-th of a name this process asked for: the same code asks in the same order in every process of a fleet, so
97
+ * the n-th one is the same one everywhere. Counted only in a fleet — a single server never asks. */
98
+ var seen = /* @__PURE__ */ new Map();
99
+ var nextKey = (name) => {
100
+ const count = seen.get(name) ?? 0;
101
+ seen.set(name, count + 1);
102
+ return `${name}#${count}`;
103
+ };
104
+ /**
105
+ * In a worker, the primary's copy of a store a single server keeps in memory, reached over the channel. Anywhere
106
+ * else, nothing — so a call site reads `deployment's ?? fleetStore(…) ?? what a single server has always made`.
107
+ */
108
+ var fleetStore = (name, methods) => isFleetWorker() ? workerClient().remote(nextKey(name), methods) : void 0;
109
+ /** A name for one server's broadcasts, the same in the primary and in each of its workers. */
110
+ var channelName = (label) => nextKey(label);
111
+ /** Tells every other process of the fleet. */
112
+ var broadcast = (channel, payload) => {
113
+ if (isFleetWorker()) {
114
+ workerClient().broadcast(channel, payload);
115
+ return;
116
+ }
117
+ hub?.broadcast(channel, payload);
118
+ };
119
+ /** Hears what another process of the fleet broadcast on `channel`. */
120
+ var onBroadcast = (channel, listener) => {
121
+ if (isFleetWorker()) workerClient();
122
+ return listeners.listen(channel, listener);
123
+ };
124
+ export { startHub as a, isFleetWorker as c, onBroadcast as i, resolveWorkers as l, channelName as n, fleetRole as o, fleetStore as r, fleetWorkerEnv as s, broadcast as t, runsFleetJobs as u };
@@ -0,0 +1,20 @@
1
+ // src/mysql/query.ts
2
+ /**
3
+ * The driver boundary, in one place.
4
+ *
5
+ * A row arrives as `RowDataPacket` — an index signature over `unknown`, which is all the driver can honestly say
6
+ * about a result set it has not been told the shape of. Naming that shape is a cast whichever way it is written, so
7
+ * it is written once, here, rather than at each of the thirty call sites that would otherwise each carry one.
8
+ */
9
+ var selectRows = async (db, sql, params = []) => {
10
+ const [rows] = await db.query(sql, params);
11
+ return rows;
12
+ };
13
+ var selectOne = async (db, sql, params = []) => {
14
+ return (await selectRows(db, sql, params))[0];
15
+ };
16
+ var execute = async (db, sql, params = []) => {
17
+ const [result] = await db.query(sql, params);
18
+ return result;
19
+ };
20
+ export { selectOne as n, selectRows as r, execute as t };
@@ -0,0 +1,46 @@
1
+ // src/identity/scopes.ts
2
+ /**
3
+ * Every credential this server mints is a JWT built from REGISTERED claims (RFC 7519) plus `scope` (RFC 6749). There
4
+ * are no bespoke `typ`/`data`/`version` claims: anyone who has read a JWT before can read one of these.
5
+ *
6
+ * iss which deployment minted it — the environment boundary
7
+ * sub who or what it is about: a user id, or a space id
8
+ * aud the API audiences it is meant for
9
+ * scope what it is and what it may do (below)
10
+ * exp / iat / nbf / jti lifetime and identity, as usual
11
+ *
12
+ * The one custom claim is `origins`, because JWT registers nothing for "the web origins this credential may be
13
+ * presented from" — it is what binds a public render token to its domains.
14
+ */
15
+ var SCOPES = {
16
+ user: "user",
17
+ refresh: "refresh",
18
+ widget: "widget",
19
+ spaceRender: "space:render",
20
+ spaceAgent: "space:agent",
21
+ /**
22
+ * A SERVER that renders this space as its own — self-hosting. Secret by construction, which is the whole reason it
23
+ * exists apart from `space:render`: see {@link SpaceScope}.
24
+ */
25
+ spaceHost: "space:host",
26
+ /** A sign-in that got the password right and still owes a second factor. Carries no authority of its own. */
27
+ mfa: "mfa"
28
+ };
29
+ /** The scopes that are safe to present with no `Origin` header, because they are not public to begin with. */
30
+ var OFF_BROWSER_SPACE_SCOPES = ["agent", "host"];
31
+ var authFailureMessage = {
32
+ missing: "Authentication required",
33
+ malformed: "Token Invalid",
34
+ expired: "Token expired",
35
+ outdated: "Token outdated",
36
+ revoked: "Token Invalid",
37
+ "wrong-type": "Token Invalid",
38
+ "scope-mismatch": "Token Invalid",
39
+ "issuer-not-allowed": "Token was issued by another environment",
40
+ "origin-not-allowed": "Access Not Authorized",
41
+ "domain-not-allowed": "This token is not allowed on this domain",
42
+ inactive: "Account is not active",
43
+ unverified: "Account is not verified",
44
+ "sso-required": "Sign in with your organization’s single sign-on"
45
+ };
46
+ export { SCOPES as n, authFailureMessage as r, OFF_BROWSER_SPACE_SCOPES as t };
@@ -0,0 +1,137 @@
1
+ import { n as keepLogEvent } from "./tail-D-USrZIR.mjs";
2
+ // src/log/serverLog.ts
3
+ var outcomeOf = (event) => event.ok ? "ok" : `ERROR ${event.error ?? ""}`.trim();
4
+ var renderRequest = (event) => {
5
+ const client = event.clientIp ? `${event.clientIp} ` : "";
6
+ const operation = event.operation ? ` ${event.operation}` : "";
7
+ const timing = `${Math.round(event.durationMs)}ms`;
8
+ return `[${event.server}] ${client}${event.method} ${event.path}${operation} ${event.status} ${timing} ${outcomeOf(event)}`;
9
+ };
10
+ var renderTool = (event) => {
11
+ const args = event.argsSummary ? ` ${event.argsSummary}` : "";
12
+ return `[MCP] tools/call ${event.name}${args} ${Math.round(event.durationMs)}ms ${outcomeOf(event)}`;
13
+ };
14
+ var renderResource = (event) => `[MCP] resources/read ${event.name} ${Math.round(event.durationMs)}ms ${outcomeOf(event)}`;
15
+ /**
16
+ * From how long a run that worked is worth a line of its own, unless the deployment says (`configureServerLog`'s
17
+ * `slowRunMs`): below it, a run that completed is `debug` — on a busy space every schedule and every call said
18
+ * `completed 40ms ok`, and buried what went wrong — and at it, `warn`.
19
+ */
20
+ var SLOW_RUN_MS = 1e3;
21
+ var slowRunMs = SLOW_RUN_MS;
22
+ var isSlowRun = (event) => event.ok && event.durationMs >= slowRunMs;
23
+ /** The steps go on the line only when the run ended badly or slowly. On a run that worked they are noise on every
24
+ * single call; on one that did not they are the answer — which step stopped, or which took the time. */
25
+ var renderRun = (event) => {
26
+ const slow = isSlowRun(event);
27
+ const steps = event.ok && !slow || event.steps.length === 0 ? "" : ` [${event.steps.join(" → ")}]`;
28
+ const outcome = slow ? `ok SLOW (${String(slowRunMs)}ms or more)` : outcomeOf(event);
29
+ return `[Action] ${event.name} via ${event.trigger} space=${event.spaceId} ${event.status} ${Math.round(event.durationMs)}ms ${outcome}${steps}`;
30
+ };
31
+ /** A refusal reads as what refused it: `[Action] checkout via webhook space=1 REFUSED invalid_signature`. The
32
+ * reason is the whole point of the line — "401" is what the request log already said. */
33
+ var renderReject = (event) => {
34
+ const caller = event.callerId ? ` from ${event.callerId}` : "";
35
+ return `[Action] ${event.name} via ${event.trigger} space=${event.spaceId} REFUSED ${event.reason}${caller} ${outcomeOf(event)}`;
36
+ };
37
+ var renderMessage = (event) => `[${event.scope}] ${event.message}${event.error ? `: ${event.error}` : ""}`;
38
+ /** One line for any {@link ServerLogEvent}: an HTTP request reads as an access-log line
39
+ * (`[SSR] 203.0.113.7 GET /pricing 200 12ms ok`), the MCP events as what happened inside one
40
+ * (`[MCP] tools/call plitzi_apply {operations:[3]} 41ms ok`), a server action as what its flow did
41
+ * (`[Action] send-invoice via call space=1 completed 12ms ok`) and a refused one as what turned it away
42
+ * (`[Action] checkout via webhook space=1 REFUSED invalid_signature`). Rendering is a pure format — the dispatcher
43
+ * already stripped query values, collected no headers, cookies or tokens, summarised tool args by shape and
44
+ * reduced a run to its steps; the client IP it does carry is personal data, so a sink that persists these lines
45
+ * must say so. */
46
+ var renderLogEvent = (event) => {
47
+ switch (event.kind) {
48
+ case "request": return renderRequest(event);
49
+ case "tool": return renderTool(event);
50
+ case "resource": return renderResource(event);
51
+ case "run": return renderRun(event);
52
+ case "reject": return renderReject(event);
53
+ case "message": return renderMessage(event);
54
+ }
55
+ };
56
+ var RANK = {
57
+ silent: 0,
58
+ error: 1,
59
+ warn: 2,
60
+ info: 3,
61
+ debug: 4
62
+ };
63
+ /**
64
+ * How severe an event is: what it says it is, or — for a request, a tool call, a run — whether it went wrong. A
65
+ * refusal is never `ok` yet never the server's failure: the caller was turned away, which is a `warn`. A run that
66
+ * worked is `debug`, unless it was slow ({@link SLOW_RUN_MS}): then `warn`.
67
+ */
68
+ var logLevelOf = (event) => {
69
+ if (event.kind === "message") return event.level;
70
+ if (event.kind === "reject") return "warn";
71
+ if (event.kind === "run" && event.ok) return isSlowRun(event) ? "warn" : "debug";
72
+ return event.ok ? "info" : "error";
73
+ };
74
+ /** Whether a server at `threshold` says something at `level`. */
75
+ var isLogged = (threshold, level) => RANK[level] <= RANK[threshold];
76
+ /** What a server says when the deployment did not choose: what went wrong in production, more while developing. */
77
+ var defaultLogLevel = (devMode = false) => devMode ? "info" : "error";
78
+ /** A drop-in `SSRServerConfig.logger` for consumers that just want the log on the console. Consumers with their
79
+ * own logging stack should pass their own sink instead and read the structured event. */
80
+ var consoleLogger = (event) => {
81
+ const line = renderLogEvent(event);
82
+ const level = logLevelOf(event);
83
+ if (level === "error") console.error(line);
84
+ else if (level === "warn") console.warn(line);
85
+ else console.log(line);
86
+ };
87
+ var errorText = (cause) => cause instanceof Error ? cause.stack ?? cause.message : typeof cause === "string" ? cause : JSON.stringify(cause);
88
+ /**
89
+ * Where everything the server says that is not a request goes — one threshold and one sink for the process.
90
+ *
91
+ * Process-wide because what speaks is often created before any server exists (an adapter, a job worker) and has no
92
+ * config to read. `createServer` sets it from its own `logLevel` and `logger`; until then it is `error` under
93
+ * `NODE_ENV=production` and `info` otherwise, to the console.
94
+ */
95
+ var state = {
96
+ level: process.env.NODE_ENV === "production" ? "error" : "info",
97
+ sink: consoleLogger
98
+ };
99
+ /**
100
+ * The process's threshold and sink — and, with `slowRunMs`, from how long a run that worked is said as slow (a
101
+ * positive number of ms; {@link SLOW_RUN_MS} by default). Refused when it is not one, saying what was given.
102
+ */
103
+ var configureServerLog = (options) => {
104
+ if (options.slowRunMs !== void 0 && !(Number.isFinite(options.slowRunMs) && options.slowRunMs > 0)) throw new Error(`slowRunMs is a number of milliseconds above 0, and ${String(options.slowRunMs)} was given`);
105
+ state.level = options.level;
106
+ state.sink = options.logger ?? consoleLogger;
107
+ slowRunMs = options.slowRunMs ?? 1e3;
108
+ };
109
+ var say = (level, scope, message, cause) => {
110
+ const event = {
111
+ kind: "message",
112
+ level,
113
+ scope,
114
+ message,
115
+ ok: level !== "error",
116
+ ...cause === void 0 ? {} : { error: errorText(cause) },
117
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
118
+ };
119
+ keepLogEvent(event, level, renderLogEvent(event));
120
+ if (isLogged(state.level, level)) state.sink(event);
121
+ };
122
+ /** The server's own voice: `serverLog.error('RSC', 'element failed to resolve', error)`. Below the threshold, nothing. */
123
+ var serverLog = {
124
+ error: (scope, message, cause) => say("error", scope, message, cause),
125
+ warn: (scope, message, cause) => say("warn", scope, message, cause),
126
+ info: (scope, message, cause) => say("info", scope, message, cause),
127
+ debug: (scope, message, cause) => say("debug", scope, message, cause),
128
+ /** Whether a level would be said — to skip building a costly message nobody will read. */
129
+ enabled: (level) => isLogged(state.level, level),
130
+ /** Hands an event to a sink the consumer wired itself (`onRun`, `onReject`) only when the process would say it. */
131
+ emit: (logger, event) => {
132
+ const level = logLevelOf(event);
133
+ keepLogEvent(event, level, renderLogEvent(event));
134
+ if (isLogged(state.level, level)) logger(event);
135
+ }
136
+ };
137
+ export { isLogged as a, serverLog as c, defaultLogLevel as i, configureServerLog as n, logLevelOf as o, consoleLogger as r, renderLogEvent as s, SLOW_RUN_MS as t };