@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,273 @@
1
+ import { n as SCOPES } from "./scopes-Co6ZjhAm.mjs";
2
+ import { generateKeyPairSync, randomBytes } from "node:crypto";
3
+ import jwt from "jsonwebtoken";
4
+ // src/tokens/tokens.ts
5
+ var DAY = 86400;
6
+ /**
7
+ * How long each credential lives. One rule, applied by how much damage the credential can do and whether something
8
+ * can renew it:
9
+ *
10
+ * - The **public render token** is the only one that may live forever, and defaults to it: it is embedded in
11
+ * published sites, where an expiry is a scheduled outage. A space may still give it a date.
12
+ * - **Everything else expires**, 30 days being the baseline.
13
+ * - **The most dangerous one is the shortest.** A session access token rides on every request and is the credential
14
+ * an attacker most wants, so it lasts a day — which costs nobody anything, because the refresh token silently
15
+ * renews it. That pairing is the whole reason it can be this short.
16
+ */
17
+ var DEFAULT_LIFETIMES = {
18
+ access: DAY,
19
+ refresh: 30 * DAY,
20
+ agent: 30 * DAY,
21
+ widget: 30 * DAY,
22
+ /**
23
+ * Long enough to fetch a code out of an app, short enough that a stolen one is worthless. It authorises nothing
24
+ * on its own — only finishing the sign-in it belongs to, which still needs the code.
25
+ */
26
+ mfaChallenge: 300,
27
+ /**
28
+ * The longest a session may live no matter how often it renews, counted from when it began. `0` means no cap,
29
+ * which is the default and what most deployments want: the renewal window is already an idle timeout, since a
30
+ * session nobody refreshes dies with its refresh token. This is the other half — the one that ends a session
31
+ * that has been renewing quietly for a year.
32
+ */
33
+ session: 0
34
+ };
35
+ /**
36
+ * A new key pair for the credentials, as PEM: what a deployment generates once and keeps (its private key as a secret),
37
+ * and what a development server or a test makes for itself. `kid` names it inside every credential it signs.
38
+ */
39
+ var generateTokenKeys = (kid = randomBytes(6).toString("hex")) => {
40
+ const { privateKey, publicKey } = generateKeyPairSync("ec", {
41
+ namedCurve: "P-256",
42
+ privateKeyEncoding: {
43
+ type: "pkcs8",
44
+ format: "pem"
45
+ },
46
+ publicKeyEncoding: {
47
+ type: "spki",
48
+ format: "pem"
49
+ }
50
+ });
51
+ return {
52
+ signing: {
53
+ kid,
54
+ privateKey
55
+ },
56
+ verifying: [{
57
+ kid,
58
+ publicKey
59
+ }]
60
+ };
61
+ };
62
+ var spaceScopeToClaim = {
63
+ render: SCOPES.spaceRender,
64
+ agent: SCOPES.spaceAgent,
65
+ host: SCOPES.spaceHost
66
+ };
67
+ var claimToSpaceScope = {
68
+ [SCOPES.spaceRender]: "render",
69
+ [SCOPES.spaceAgent]: "agent",
70
+ [SCOPES.spaceHost]: "host"
71
+ };
72
+ var isLegacyShape = (payload) => "data" in payload || "version" in payload;
73
+ /** Whether a value is a JWT at all — a header and a payload that read as JSON objects — whoever signed it. */
74
+ var isJwt = (token) => {
75
+ const decoded = jwt.decode(token, { complete: true });
76
+ return decoded !== null && typeof decoded.payload === "object";
77
+ };
78
+ var subjectId = (payload) => {
79
+ if (typeof payload.sub !== "string") return;
80
+ const id = Number(payload.sub);
81
+ return Number.isInteger(id) ? id : void 0;
82
+ };
83
+ /**
84
+ * The credential mint and its verifier, bound to one deployment's signing key and issuer.
85
+ *
86
+ * A factory rather than a module of functions because the configuration is the deployment's: its secret, the issuer
87
+ * that separates its universe of credentials from every other, and how long each kind lives. A customer running this
88
+ * server issues under their own and nothing they mint is worth anything here, or the other way round.
89
+ */
90
+ var createTokens = (config) => {
91
+ const lifetimes = {
92
+ ...DEFAULT_LIFETIMES,
93
+ ...config.lifetimes
94
+ };
95
+ const allowedIssuers = [config.issuer, ...config.alsoAccept ?? []];
96
+ const publicKeys = new Map(config.keys.verifying.map(({ kid, publicKey }) => [kid, publicKey]));
97
+ if (publicKeys.size === 0) throw new Error("tokens.keys.verifying names no key: a server that cannot check a credential cannot serve anyone");
98
+ const signing = config.keys.signing;
99
+ if (signing && !publicKeys.has(signing.kid)) throw new Error(`tokens.keys.signing is key "${signing.kid}", which tokens.keys.verifying does not list: what this server signed it could not check`);
100
+ const baseClaims = (scope, ttlSeconds) => {
101
+ const now = Math.floor(Date.now() / 1e3);
102
+ return {
103
+ iss: config.issuer,
104
+ aud: config.audience ?? [config.issuer],
105
+ scope,
106
+ ...ttlSeconds === void 0 ? {} : { exp: now + ttlSeconds },
107
+ iat: now,
108
+ jti: randomBytes(8).toString("hex"),
109
+ nbf: now
110
+ };
111
+ };
112
+ const sign = (payload) => {
113
+ if (!signing) throw new Error("This server checks credentials and mints none: it holds no signing key (tokens.keys.signing). Credentials are minted where people sign in.");
114
+ return jwt.sign(payload, signing.privateKey, {
115
+ algorithm: "ES256",
116
+ keyid: signing.kid
117
+ });
118
+ };
119
+ const verify = (token) => {
120
+ if (!token) return {
121
+ ok: false,
122
+ reason: "missing"
123
+ };
124
+ const header = jwt.decode(token, { complete: true })?.header;
125
+ const publicKey = header?.kid === void 0 ? void 0 : publicKeys.get(header.kid);
126
+ if (!publicKey) return {
127
+ ok: false,
128
+ reason: "malformed"
129
+ };
130
+ let decoded;
131
+ try {
132
+ decoded = jwt.verify(token, publicKey, { algorithms: ["ES256"] });
133
+ } catch (e) {
134
+ return {
135
+ ok: false,
136
+ reason: e.name === "TokenExpiredError" ? "expired" : "malformed"
137
+ };
138
+ }
139
+ const payload = decoded;
140
+ if (isLegacyShape(payload)) return {
141
+ ok: false,
142
+ reason: "outdated"
143
+ };
144
+ if (typeof payload.scope !== "string") return {
145
+ ok: false,
146
+ reason: "malformed"
147
+ };
148
+ if (typeof payload.iss !== "string" || !allowedIssuers.includes(payload.iss)) return {
149
+ ok: false,
150
+ reason: "issuer-not-allowed"
151
+ };
152
+ return {
153
+ ok: true,
154
+ payload
155
+ };
156
+ };
157
+ const verifyScoped = (token, scopes) => {
158
+ const result = verify(token);
159
+ if (!result.ok) return result;
160
+ if (!scopes.includes(result.payload.scope)) return {
161
+ ok: false,
162
+ reason: "wrong-type"
163
+ };
164
+ return {
165
+ ok: true,
166
+ payload: result.payload
167
+ };
168
+ };
169
+ const withSubject = (result) => {
170
+ if (!result.ok) return result;
171
+ return subjectId(result.payload) === void 0 ? {
172
+ ok: false,
173
+ reason: "malformed"
174
+ } : result;
175
+ };
176
+ return {
177
+ lifetimes,
178
+ /** What this deployment mints under. Read by anything that has to name the deployment — an enrolment URI, say. */
179
+ issuer: config.issuer,
180
+ generateUserToken: (userId, { actingAs, ttlSeconds } = {}) => sign({
181
+ sub: String(userId),
182
+ ...actingAs === void 0 ? {} : { act: { sub: String(actingAs) } },
183
+ ...baseClaims(SCOPES.user, ttlSeconds ?? lifetimes.access)
184
+ }),
185
+ generateRefreshToken: (userId) => sign({
186
+ sub: String(userId),
187
+ ...baseClaims(SCOPES.refresh, lifetimes.refresh)
188
+ }),
189
+ generateWidgetToken: () => sign(baseClaims(SCOPES.widget, lifetimes.widget)),
190
+ /** Says "this person proved their password"; nothing more, and only for a few minutes. */
191
+ generateMfaChallenge: (userId) => sign({
192
+ sub: String(userId),
193
+ ...baseClaims(SCOPES.mfa, lifetimes.mfaChallenge)
194
+ }),
195
+ /**
196
+ * A `render` token may live forever, and defaults to it, because it is embedded in a published site — often a
197
+ * SPA deployed once and left alone — where an expiry is a scheduled outage: the site breaks weeks later with
198
+ * nobody having touched anything. The deadline also buys little there, since the token is public by
199
+ * construction. What limits it is what it may do (read published content), where it may be presented (its
200
+ * declared domains), and the row behind it, which the owner can rotate or delete at any moment — revocation,
201
+ * not expiry, is the control.
202
+ *
203
+ * An `agent` grant is the opposite default and always carries a lifetime: it writes, and it is held by a
204
+ * third-party host.
205
+ *
206
+ * A `host` grant follows `render`: it only reads, it is held by the space owner's own deployment, and an expiry
207
+ * there is the same scheduled outage — except the site goes quietly STALE rather than dark, because a
208
+ * self-hosted renderer keeps serving the last copy it fetched. Being secret, it is worth rotating; being
209
+ * revocable, it does not need a deadline to be withdrawn.
210
+ */
211
+ generateSpaceToken: (spaceId, origins, scope = "render", { expiresAt } = {}) => {
212
+ const defaultTtl = scope === "agent" ? lifetimes.agent : void 0;
213
+ const ttlSeconds = expiresAt == null ? defaultTtl : Math.max(0, expiresAt - Math.floor(Date.now() / 1e3));
214
+ return sign({
215
+ sub: String(spaceId),
216
+ origins,
217
+ ...baseClaims(spaceScopeToClaim[scope], ttlSeconds)
218
+ });
219
+ },
220
+ verifyUserToken: (token) => withSubject(verifyScoped(token, [SCOPES.user])),
221
+ verifyRefreshToken: (token) => withSubject(verifyScoped(token, [SCOPES.refresh])),
222
+ verifyMfaChallenge: (token) => withSubject(verifyScoped(token, [SCOPES.mfa])),
223
+ verifyWidgetToken: (token) => verifyScoped(token, [SCOPES.widget]),
224
+ verifySpaceToken: (token) => {
225
+ const result = withSubject(verifyScoped(token, [
226
+ SCOPES.spaceRender,
227
+ SCOPES.spaceAgent,
228
+ SCOPES.spaceHost
229
+ ]));
230
+ if (!result.ok) return result;
231
+ const spaceId = subjectId(result.payload);
232
+ const spaceScope = claimToSpaceScope[result.payload.scope];
233
+ if (spaceId === void 0 || !spaceScope) return {
234
+ ok: false,
235
+ reason: "malformed"
236
+ };
237
+ const origins = result.payload.origins;
238
+ return {
239
+ ok: true,
240
+ payload: {
241
+ ...result.payload,
242
+ origins: Array.isArray(origins) ? origins : [],
243
+ spaceId,
244
+ spaceScope
245
+ }
246
+ };
247
+ },
248
+ /**
249
+ * A token that no longer verifies for any reason the issuer can fix by re-minting — expiry, a pre-registered-
250
+ * claims shape, an issuer from a deployment this one is not, or a key pair this one no longer holds. Used by the
251
+ * endpoints that hand tokens back out, so a caller never has to know why.
252
+ *
253
+ * A credential signed under keys rotated away from reads as `malformed` to `verify` (a `kid` it does not list, a
254
+ * signature it cannot check) — and so did every stored one after a deployment changed its pair, none re-minted. It
255
+ * is told from garbage by being a JWT at all: what never was one is not re-minted, or storing nonsense in a row would
256
+ * be a way to be handed a working credential.
257
+ */
258
+ needsRotation: (token) => {
259
+ const result = verify(token);
260
+ if (result.ok) return false;
261
+ return result.reason !== "malformed" || isJwt(token);
262
+ },
263
+ /** Undefined for a credential that never expires, which is what a host should read as "no renewal needed". */
264
+ expiresInSeconds: (token) => {
265
+ const result = verify(token);
266
+ if (!result.ok || result.payload.exp === void 0) return;
267
+ return Math.max(0, result.payload.exp - Math.floor(Date.now() / 1e3));
268
+ }
269
+ };
270
+ };
271
+ /** The user id a session or refresh token is about. */
272
+ var userIdOf = (payload) => Number(payload.sub);
273
+ export { userIdOf as i, createTokens as n, generateTokenKeys as r, DEFAULT_LIFETIMES as t };
@@ -0,0 +1,2 @@
1
+ export { dataDirLookup, projectDataReader } from './projectData';
2
+ export type { ProjectDataLookup } from './projectData';
@@ -0,0 +1,68 @@
1
+ import { readFile, readdir, stat } from "node:fs/promises";
2
+ import path from "node:path";
3
+ // src/data/projectData.ts
4
+ /** What a project keeps in its data folder: JSON, the only files `plitzi space push` sends as the space's data. */
5
+ var DATA_EXTENSION = ".json";
6
+ /**
7
+ * A data folder as the lookup a deployment would otherwise write — what a self-hosted server derives from `dataDir`, so
8
+ * a `/data/<file>` provider and a function's `ctx.data` read the folder one way. A folder has no revisions: every
9
+ * revision is what is on disk now. A file is read again only once it changed, so a page asking per render costs the
10
+ * folder's listing and nothing more.
11
+ */
12
+ var dataDirLookup = (dataDir) => {
13
+ const root = path.resolve(dataDir);
14
+ const kept = /* @__PURE__ */ new Map();
15
+ return async () => {
16
+ let names;
17
+ try {
18
+ names = await readdir(root, { recursive: true });
19
+ } catch {
20
+ return;
21
+ }
22
+ const read = await Promise.all(names.filter((name) => name.endsWith(DATA_EXTENSION)).map(async (name) => {
23
+ const file = path.join(root, name);
24
+ const key = name.split(path.sep).join("/");
25
+ try {
26
+ const { mtimeMs, size } = await stat(file);
27
+ const known = kept.get(key);
28
+ const text = known && known.mtimeMs === mtimeMs && known.size === size ? known.text : await readFile(file, "utf8");
29
+ kept.set(key, {
30
+ mtimeMs,
31
+ size,
32
+ text
33
+ });
34
+ return [key, text];
35
+ } catch {
36
+ kept.delete(key);
37
+ return;
38
+ }
39
+ }));
40
+ const files = Object.fromEntries(read.filter((entry) => entry !== void 0));
41
+ kept.forEach((_entry, key) => {
42
+ if (!(key in files)) kept.delete(key);
43
+ });
44
+ return files;
45
+ };
46
+ };
47
+ /**
48
+ * `ctx.data` for one run: one file of the space's data, as of the run's revision, parsed.
49
+ *
50
+ * The lookup is asked once per run, whatever the code reads and however often — every read of one run sees the same
51
+ * version of the data — and each read is parsed afresh, so code that changes what it was handed changes nothing the
52
+ * next read gets.
53
+ */
54
+ var projectDataReader = (getData, spaceId, at) => {
55
+ let files;
56
+ return async (file) => {
57
+ if (!getData) throw new Error("This server keeps no data for its spaces: ctx.data reads what a deployment answers with action.lookups.getData, or the files of dataDir");
58
+ files ??= getData(spaceId, at);
59
+ const text = (await files)?.[file];
60
+ if (text === void 0) throw new Error(`"${file}" is not a file of this space's data — ctx.data takes its path under src/data/`);
61
+ try {
62
+ return JSON.parse(text);
63
+ } catch {
64
+ throw new Error(`"${file}" of this space's data is not JSON`);
65
+ }
66
+ };
67
+ };
68
+ export { dataDirLookup, projectDataReader };
@@ -0,0 +1,21 @@
1
+ import { SpaceRevision } from '@plitzi/sdk-shared';
2
+ /**
3
+ * How a server reaches a space's data: its files' text by path (`products.json`), as of a revision — what a provider
4
+ * whose `query` is `/data/<file>` reads on the page server, and a function's `ctx.data` on whatever runs it.
5
+ */
6
+ export type ProjectDataLookup = (spaceId: number, at?: SpaceRevision) => Promise<Record<string, string> | undefined>;
7
+ /**
8
+ * A data folder as the lookup a deployment would otherwise write — what a self-hosted server derives from `dataDir`, so
9
+ * a `/data/<file>` provider and a function's `ctx.data` read the folder one way. A folder has no revisions: every
10
+ * revision is what is on disk now. A file is read again only once it changed, so a page asking per render costs the
11
+ * folder's listing and nothing more.
12
+ */
13
+ export declare const dataDirLookup: (dataDir: string) => ProjectDataLookup;
14
+ /**
15
+ * `ctx.data` for one run: one file of the space's data, as of the run's revision, parsed.
16
+ *
17
+ * The lookup is asked once per run, whatever the code reads and however often — every read of one run sees the same
18
+ * version of the data — and each read is parsed afresh, so code that changes what it was handed changes nothing the
19
+ * next read gets.
20
+ */
21
+ export declare const projectDataReader: (getData: ProjectDataLookup | undefined, spaceId: number, at: SpaceRevision | undefined) => ((file: string) => Promise<unknown>);
@@ -0,0 +1,8 @@
1
+ import { BaseContext } from '../http/types';
2
+ /**
3
+ * The deployment the request's host resolves to, for a stage that writes cookies before the middlewares resolve it:
4
+ * how they are written depends on it (a domain other sites frame writes them `SameSite=None`, `sessionCookieParams`).
5
+ * Asked only by a stage about to write one — a sign-in, a renewal — and read from the resolution's cache by host.
6
+ * A host that resolves to nothing, or fails to, writes them as the server says.
7
+ */
8
+ export declare const knowHostDeployment: ({ req, config }: Pick<BaseContext, "req" | "config">) => Promise<void>;
@@ -0,0 +1,3 @@
1
+ export { knowHostDeployment } from './hostDeployment';
2
+ export { spaceDeploymentMiddleware } from './spaceDeployment';
3
+ export type { DeploymentAdapters, DeployedContext } from './spaceDeployment';
@@ -0,0 +1,19 @@
1
+ import { c as serverLog } from "../chunks/serverLog-BKaKjjc4.mjs";
2
+ import { t as spaceDeploymentMiddleware } from "../chunks/spaceDeployment-J2IMLfij.mjs";
3
+ // src/deployment/hostDeployment.ts
4
+ /**
5
+ * The deployment the request's host resolves to, for a stage that writes cookies before the middlewares resolve it:
6
+ * how they are written depends on it (a domain other sites frame writes them `SameSite=None`, `sessionCookieParams`).
7
+ * Asked only by a stage about to write one — a sign-in, a renewal — and read from the resolution's cache by host.
8
+ * A host that resolves to nothing, or fails to, writes them as the server says.
9
+ */
10
+ var knowHostDeployment = async ({ req, config }) => {
11
+ if (req.ctx.spaceDeployment || !config.adapters.getSpaceDeployment) return;
12
+ try {
13
+ const deployment = await config.adapters.getSpaceDeployment(req);
14
+ if (!deployment.error) req.ctx.spaceDeployment = deployment;
15
+ } catch (error) {
16
+ serverLog.warn("auth", `What ${req.hostname} serves could not be resolved: its cookies are written as the server says`, error);
17
+ }
18
+ };
19
+ export { knowHostDeployment, spaceDeploymentMiddleware };
@@ -0,0 +1,11 @@
1
+ import { BaseContext } from '../http/types';
2
+ import { SSRAdapters, SSRMiddleware, ServerBaseConfig } from '../types';
3
+ /** What a server answering for a space's host is handed: which deployment a request's host is. */
4
+ export type DeploymentAdapters = SSRAdapters & Required<Pick<SSRAdapters, 'getSpaceDeployment'>>;
5
+ /** The context of a server that serves spaces by their host — a page server, a worker. */
6
+ export type DeployedContext = BaseContext & {
7
+ config: ServerBaseConfig & {
8
+ adapters: DeploymentAdapters;
9
+ };
10
+ };
11
+ export declare const spaceDeploymentMiddleware: (adapters: DeploymentAdapters, config: Pick<ServerBaseConfig, "frameOptions" | "hsts">) => SSRMiddleware;
@@ -0,0 +1,2 @@
1
+ export type { PageEngine } from './page';
2
+ export type { RscResolveContext, RscElementResolver } from './rsc';
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,49 @@
1
+ import { RscElementResolver } from './rsc';
2
+ import { ProjectDataLookup } from '../data/projectData';
3
+ import { FleetStores } from '../http/fleet/link';
4
+ import { BaseContext, Stage } from '../http/types';
5
+ import { RealtimeTransport } from '@plitzi/sdk-shared';
6
+ /**
7
+ * What a page server is handed of the actions engine (RFC 0032, D11): built by the engine, never by the page server,
8
+ * which mounts it where its pipeline says and reaches it through nothing else. Absent, the server runs no actions, no
9
+ * functions and no realtime, and tells its pages so.
10
+ *
11
+ * The engine's stages read only what every server has (`BaseContext`) and what they close over: the engine's own
12
+ * configuration. So the same stages answer in a page server and in a worker of their own.
13
+ */
14
+ export type PageEngine = {
15
+ /**
16
+ * Its endpoints — `/_action` and its webhooks, `/_realtime` — after the auth chain: what a caller may do depends on
17
+ * who is asking.
18
+ */
19
+ endpoints: Stage<BaseContext>[];
20
+ /** `/fn/`: after the deployment's own data stages, so a route of its own under `/api/` stays its own. */
21
+ routes: Stage<BaseContext>[];
22
+ /** Which of its paths switch protocols (a WebSocket). */
23
+ upgrades?: (path: string) => boolean;
24
+ /**
25
+ * Resolves a server element that names an action or a connector, for the page's server-rendered data (§4.3).
26
+ * Answers `undefined` for an element that names neither: the page server reads the rest itself.
27
+ */
28
+ resolveElement?: RscElementResolver;
29
+ /** The space's data as the engine reads it (`action.lookups.getData`): what a `/data/<file>` provider reads too. */
30
+ data?: ProjectDataLookup;
31
+ /** What a page is told: where it calls its actions, and where its realtime channels are. */
32
+ published: {
33
+ actionPath?: string;
34
+ realtimePath?: string;
35
+ realtimeTransport?: RealtimeTransport;
36
+ };
37
+ /** Started once the transport is bound: the jobs, which a server nobody listened on must not be claiming. */
38
+ listening?: () => void;
39
+ /** The server has stopped taking connections: what holds them open for good — realtime sockets — lets them go. */
40
+ closing?: () => void;
41
+ /** Told to stop, before it announces it: it takes no new work from here — a job worker claims nothing more. */
42
+ stopping?: () => void;
43
+ /** Awaited before the sockets close: the jobs running here finish rather than being abandoned. */
44
+ destroy?: () => Promise<void>;
45
+ /** What the primary of a fleet keeps for its workers: each store named by the module that keeps it. */
46
+ fleetStores?: FleetStores;
47
+ /** A plugin's server half, from the plugin's package — refused, naming why, for what is not a definition. */
48
+ setPluginFunctions?: (plugin: string, definition: unknown) => void;
49
+ };
@@ -0,0 +1,32 @@
1
+ import { SSRRequest } from '../types';
2
+ import { Element, Environment, SSRUser } from '@plitzi/sdk-shared';
3
+ import { ServerTemplateData } from '@plitzi/sdk-shared/schema';
4
+ /** Everything an element resolver needs to turn one `runtime: 'server'` element into its data slice. */
5
+ export type RscResolveContext = {
6
+ element: Element;
7
+ /**
8
+ * What its input resolves to on the page server: what it was saved with, and its bound input the server reads — the
9
+ * address, the answers of the server providers before it (`serverInputOf`).
10
+ */
11
+ input?: unknown;
12
+ /** The whole element map, so a resolver can inspect the subtree that consumes its data. */
13
+ flat: Record<string, Element>;
14
+ routeParams: Record<string, string | undefined>;
15
+ queryParams: Record<string, string>;
16
+ /** What the page server knows of the visit as a template reads it — the space's variables for this host, `navigation`. */
17
+ templateData: ServerTemplateData;
18
+ req: SSRRequest;
19
+ spaceId: number;
20
+ environment: Environment;
21
+ user: SSRUser | undefined;
22
+ /**
23
+ * Aborted when this element's budget runs out, so a resolver can stop the work nobody is waiting for.
24
+ *
25
+ * The timeout below only ever decided when to STOP WAITING — the losing side of a race keeps running — so a
26
+ * provider that took longer than its budget went on holding a run slot and an outbound connection for a page
27
+ * that had already been sent. What is being cancelled is not the request, it is the work behind it.
28
+ */
29
+ signal: AbortSignal;
30
+ };
31
+ /** Produces the data slice for a single server element. Returning undefined leaves the element out of the payload. */
32
+ export type RscElementResolver = (context: RscResolveContext) => Promise<unknown>;
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Writes a file whole or not at all: to a temporary name beside it, then renamed over it.
3
+ *
4
+ * Several workers can build or download the same plugin into the same folder at once, and a reader can open a file
5
+ * while another process is writing it. A rename replaces the file in one step, so whoever reads it sees the old
6
+ * version or the new one — never half of either. Same-folder temporary, so the rename never crosses a filesystem.
7
+ */
8
+ export declare const writeFileAtomic: (file: string, data: string | Uint8Array) => Promise<void>;
9
+ /** `copyFile`, with the same whole-or-nothing guarantee. */
10
+ export declare const copyFileAtomic: (source: string, file: string) => Promise<void>;
@@ -0,0 +1 @@
1
+ export { writeFileAtomic, copyFileAtomic } from './atomicFile';
@@ -0,0 +1,32 @@
1
+ import fs from "node:fs/promises";
2
+ import { randomUUID } from "node:crypto";
3
+ // src/files/atomicFile.ts
4
+ /**
5
+ * Writes a file whole or not at all: to a temporary name beside it, then renamed over it.
6
+ *
7
+ * Several workers can build or download the same plugin into the same folder at once, and a reader can open a file
8
+ * while another process is writing it. A rename replaces the file in one step, so whoever reads it sees the old
9
+ * version or the new one — never half of either. Same-folder temporary, so the rename never crosses a filesystem.
10
+ */
11
+ var writeFileAtomic = async (file, data) => {
12
+ const temporary = `${file}.${process.pid}.${randomUUID()}.tmp`;
13
+ try {
14
+ await fs.writeFile(temporary, data);
15
+ await fs.rename(temporary, file);
16
+ } catch (error) {
17
+ await fs.rm(temporary, { force: true });
18
+ throw error;
19
+ }
20
+ };
21
+ /** `copyFile`, with the same whole-or-nothing guarantee. */
22
+ var copyFileAtomic = async (source, file) => {
23
+ const temporary = `${file}.${process.pid}.${randomUUID()}.tmp`;
24
+ try {
25
+ await fs.copyFile(source, temporary);
26
+ await fs.rename(temporary, file);
27
+ } catch (error) {
28
+ await fs.rm(temporary, { force: true });
29
+ throw error;
30
+ }
31
+ };
32
+ export { copyFileAtomic, writeFileAtomic };
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Whether an `Authorization` header carries this secret as its bearer token. Compared as digests of one length, so the
3
+ * time it takes says nothing of how much of the secret a guess got right — nor of its length.
4
+ */
5
+ export declare const bearerMatches: (header: string | undefined, secret: string) => boolean;
@@ -0,0 +1,23 @@
1
+ import { ResolvedCompression } from './compress';
2
+ import { SSRResponseHelpers } from '../types';
3
+ export type RawResponse = {
4
+ headersSent: boolean;
5
+ /** The status actually written to the wire — the access log reads it once the response is out. */
6
+ statusCode: number;
7
+ setHeader(name: string, value: string | number | readonly string[]): unknown;
8
+ getHeaders(): Record<string, string | number | readonly string[]>;
9
+ writeHead(statusCode: number, headers?: Record<string, string | number | readonly string[]>): unknown;
10
+ write(chunk: string | Buffer): unknown;
11
+ end(chunk?: string | Buffer): unknown;
12
+ /**
13
+ * Optional, because this type is the MINIMUM a host has to provide — node's own, http2's, or a fake in a test.
14
+ *
15
+ * They are how the dispatcher tells "the caller left" from "the answer was sent": a host that exposes neither
16
+ * simply never cancels early, which is the behaviour of every host that had no such notion to begin with.
17
+ */
18
+ once?(event: 'close', listener: () => void): unknown;
19
+ writableFinished?: boolean;
20
+ /** A `103 Early Hints` — node's, over HTTP/1.1 and HTTP/2 alike. Optional: a host without it sends none. */
21
+ writeEarlyHints?(hints: Record<string, string | string[]>): void;
22
+ };
23
+ export declare const buildResponseHelpers: (raw: RawResponse, acceptEncoding?: string, compression?: ResolvedCompression) => SSRResponseHelpers;
@@ -0,0 +1,28 @@
1
+ /** Anything that closes the way a server from `createServer` does. */
2
+ export type Closable = {
3
+ close: () => Promise<void>;
4
+ };
5
+ export type CloseOnSignalsOptions = {
6
+ /** Default `SIGTERM` (what an orchestrator sends before it replaces a replica) and `SIGINT` (^C). */
7
+ signals?: NodeJS.Signals[];
8
+ /** Runs once the server has closed: what the deployment opened itself — a pool, a client, a file — goes here. */
9
+ afterClose?: () => void | Promise<void>;
10
+ };
11
+ /**
12
+ * Closes the server when the process is told to stop, and only then lets the process exit.
13
+ *
14
+ * `close()` already does the waiting — the page server stops claiming jobs, finishes the ones it is running and lets
15
+ * go of its sockets — but nothing calls it when a deploy sends SIGTERM, and a process that simply exits leaves every
16
+ * running job to be retried by somebody else. This is that call, for a deployment that has no signal handling of its
17
+ * own. Opt in: a host that already manages its process's signals keeps doing so, and calls `close()` from there.
18
+ *
19
+ * ```ts
20
+ * const server = createServer(config);
21
+ * server.listen(3000);
22
+ * closeOnSignals(server, { afterClose: () => pool.end() });
23
+ * ```
24
+ *
25
+ * A second signal while it is closing exits at once — the ^C a person presses when waiting is not what they want.
26
+ * Answers a function that removes the handlers again.
27
+ */
28
+ export declare const closeOnSignals: (server: Closable, { signals, afterClose }?: CloseOnSignalsOptions) => (() => void);
@@ -0,0 +1,20 @@
1
+ import { SSRCompressionConfig } from '../types';
2
+ export type ContentEncoding = 'br' | 'gzip' | 'identity';
3
+ /** What the server does when the deployment says nothing: Brotli where the client takes it, gzip otherwise. */
4
+ export declare const DEFAULT_COMPRESSION: {
5
+ encodings: ("br" | "gzip")[];
6
+ threshold: number;
7
+ brotliQuality: number;
8
+ keptBrotliQuality: number;
9
+ gzipLevel: number;
10
+ };
11
+ export type ResolvedCompression = typeof DEFAULT_COMPRESSION;
12
+ /**
13
+ * The deployment's compression policy, with the gaps filled in. `false` means never compress, and is expressed as
14
+ * an empty encoding list so there is one shape downstream rather than a boolean to re-test at every use.
15
+ */
16
+ export declare const resolveCompression: (config?: SSRCompressionConfig | false) => ResolvedCompression;
17
+ /** The first encoding this server prefers that the client actually takes. `*` counts as taking anything. */
18
+ export declare const selectEncoding: (acceptEncoding: string | undefined, compression?: ResolvedCompression) => ContentEncoding;
19
+ /** `kept`: the result is stored and served again, so it is worth compressing harder once. */
20
+ export declare const compressBody: (body: string, encoding: ContentEncoding, compression?: ResolvedCompression, kept?: boolean) => Buffer | string;
@@ -0,0 +1,15 @@
1
+ import { RawResponse } from './buildResponseHelpers';
2
+ import { Handler } from './transports';
3
+ import { BaseContext, Stage } from './types';
4
+ import { SSRRequest, SSRResponseHelpers, ServerBaseConfig } from '../types';
5
+ import { IncomingMessage } from 'node:http';
6
+ export type BuildContext<C extends BaseContext> = (raw: IncomingMessage, rawRes: RawResponse, req: SSRRequest, res: SSRResponseHelpers) => Omit<C, 'signal'>;
7
+ export type HandlerOptions = {
8
+ compression?: ServerBaseConfig['compression'];
9
+ /**
10
+ * The paths that may switch protocols. An upgrade anywhere else is refused before the pipeline runs: a WebSocket
11
+ * opened on a page's address would otherwise render the page — and count a visit — to answer a socket.
12
+ */
13
+ upgrades?: (path: string) => boolean;
14
+ };
15
+ export declare const makeHandler: <C extends BaseContext>(label: string, buildContext: BuildContext<C>, stages: Stage<C>[], { compression: compressionConfig, upgrades }?: HandlerOptions) => Handler;