@plitzi/sdk-kernel 0.0.0-stage → 0.39.2

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 +10 -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-CBd5tXut.mjs +262 -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 +190 -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,253 @@
1
+ import { BlockList, isIP } from "node:net";
2
+ // src/identity/session.ts
3
+ var LOCAL_HOSTS = [
4
+ "localhost",
5
+ "127.0.0.1",
6
+ "::1"
7
+ ];
8
+ /**
9
+ * Whether the host is a loopback name or a `.localhost` sibling. Local hosts get no Domain on their cookies (browsers
10
+ * refuse one on a single-label host) and no Secure over plain http.
11
+ */
12
+ var isLocalHost = (hostname) => LOCAL_HOSTS.includes(hostname) || hostname.endsWith(".localhost");
13
+ /**
14
+ * The addresses a home or office network hands out — RFC 1918, link-local, the shared range a mesh VPN (Tailscale)
15
+ * gives each device, IPv6 unique- and link-local — which a phone on the same Wi-Fi opens a development server on.
16
+ */
17
+ var PRIVATE_NETWORK = new BlockList();
18
+ PRIVATE_NETWORK.addSubnet("10.0.0.0", 8);
19
+ PRIVATE_NETWORK.addSubnet("172.16.0.0", 12);
20
+ PRIVATE_NETWORK.addSubnet("192.168.0.0", 16);
21
+ PRIVATE_NETWORK.addSubnet("169.254.0.0", 16);
22
+ PRIVATE_NETWORK.addSubnet("100.64.0.0", 10);
23
+ PRIVATE_NETWORK.addSubnet("fc00::", 7, "ipv6");
24
+ PRIVATE_NETWORK.addSubnet("fe80::", 10, "ipv6");
25
+ /**
26
+ * Whether the host is this machine as another device on its network reaches it: a private address, or the name
27
+ * mDNS gives it (`studio.local` — one label before `.local`, so a deployment's own `app.example.local` sub-domains,
28
+ * which share cookies across siblings over https, are not taken for one). Such a server is opened over plain http
29
+ * from a tablet, and gets the local cookie profile: a Secure cookie written over http is dropped.
30
+ */
31
+ var isPrivateNetworkHost = (hostname) => {
32
+ const address = hostname.replace(/^\[(.*)\]$/, "$1");
33
+ const family = isIP(address);
34
+ if (family === 0) return /^[^.]+\.local$/.test(hostname);
35
+ return PRIVATE_NETWORK.check(address, family === 4 ? "ipv4" : "ipv6");
36
+ };
37
+ var isIpAddress = (hostname) => isIP(hostname) !== 0;
38
+ /**
39
+ * The last two labels of the host, so a session established on one sub-domain is carried by its siblings — an app
40
+ * and the API it talks to are rarely the same host. Local and IP hosts get no domain at all: browsers refuse a
41
+ * Domain on a single-label host, and one written for an address would never be sent back to it.
42
+ *
43
+ * A domain whose sub-domains belong to different people — the one a deployment serves its spaces on, like
44
+ * `*.plitzi.app` — is not one to share a cookie across: a session of one space's visitor would reach every other's.
45
+ * Such a deployment says so with `authCookie.domain`, answering this for its own hosts and nothing for the rest.
46
+ */
47
+ var registrableDomain = (hostname) => {
48
+ if (isLocalHost(hostname) || isIpAddress(hostname) || isPrivateNetworkHost(hostname)) return;
49
+ const match = /([^.]+\.[^.]+)$/.exec(hostname);
50
+ return match ? `.${match[1]}` : void 0;
51
+ };
52
+ var resolve = (value, hostname, fallback) => {
53
+ if (typeof value === "function") return value(hostname);
54
+ return value ?? fallback;
55
+ };
56
+ /** A domain whose owner lets other sites frame its pages (`security.frameAncestors`). */
57
+ var embeddedElsewhere = (req) => (req.ctx?.spaceDeployment?.security?.frameAncestors?.length ?? 0) > 0;
58
+ /**
59
+ * Everything about how a session cookie is written, derived from the request host unless the deployment says
60
+ * otherwise. The defaults are the ones a server on a real domain needs: a cookie shared across sub-domains — an app and
61
+ * the API it talks to are rarely the same host — Secure, and `SameSite=Lax`. Sub-domains of one site are the same site,
62
+ * so `Lax` reaches all of them; what it keeps the cookie from is a request another site's page makes, which carried it
63
+ * as a third-party cookie (Lighthouse: "Uses third-party cookies"), to the API and to every other host of the domain,
64
+ * a CDN's included. A deployment whose pages need the session inside another site's page — a space in an iframe there,
65
+ * an app on another site than its API — says `sameSite: 'none'`; a domain that lets other sites frame its pages
66
+ * (`security.frameAncestors` of its deployment) gets it on that host alone. A local server — this machine, or this machine as its
67
+ * network reaches it — is not Secure, which plain http would drop.
68
+ */
69
+ var sessionCookieParams = (req, config = {}) => {
70
+ const { hostname } = req;
71
+ const local = isLocalHost(hostname) || isPrivateNetworkHost(hostname);
72
+ const secure = config.secure ?? !local;
73
+ return {
74
+ name: resolve(config.name, hostname, "plitzi_session"),
75
+ domain: resolve(config.domain, hostname, registrableDomain(hostname)),
76
+ secure,
77
+ sameSite: embeddedElsewhere(req) && secure ? "none" : config.sameSite ?? "lax",
78
+ refreshPath: config.refreshPath ?? "/auth",
79
+ hintSuffix: config.hintSuffix ?? "_hint"
80
+ };
81
+ };
82
+ /** The readable companion cookie's name — the one a page is told to look for (`server.auth.sessionHintCookie`). */
83
+ var sessionHintCookieName = (params) => `${params.name}${params.hintSuffix}`;
84
+ /**
85
+ * The value of the readable companion cookie: `<access expiry>.<refresh expiry>`, unix seconds, refresh optional.
86
+ *
87
+ * It exists because the session cookie is httpOnly — correctly — which leaves a page unable to tell whether the
88
+ * browser holds a session at all. Answering that costs a request per page load otherwise, and the answer is usually
89
+ * "nobody is signed in". This carries no credential: any script that can read it could have asked the backend the
90
+ * same question with `credentials: 'include'`.
91
+ */
92
+ var sessionHintValue = (expiresAt, refreshExpiresAt) => `${Math.floor(expiresAt)}.${refreshExpiresAt === void 0 ? "" : Math.floor(refreshExpiresAt)}`;
93
+ /** {@link sessionHintValue} read back — the same reading `@plitzi/sdk-auth` gives it in the browser. */
94
+ var parseSessionHint = (value) => {
95
+ if (!value) return;
96
+ const [expiresAt, refreshExpiresAt] = value.split(".");
97
+ const expiry = Number(expiresAt);
98
+ if (!Number.isFinite(expiry) || expiry <= 0) return;
99
+ const refreshExpiry = Number(refreshExpiresAt);
100
+ return {
101
+ expiresAt: expiry,
102
+ refreshExpiresAt: Number.isFinite(refreshExpiry) && refreshExpiry > 0 ? refreshExpiry : void 0
103
+ };
104
+ };
105
+ var serializeCookie = (name, value, maxAgeSeconds, params, { httpOnly = true, path = "/" } = {}) => {
106
+ const parts = [
107
+ `${name}=${encodeURIComponent(value)}`,
108
+ `Path=${path}`,
109
+ ...httpOnly ? ["HttpOnly"] : [],
110
+ `SameSite=${params.sameSite === "none" ? "None" : "Lax"}`,
111
+ `Max-Age=${Math.max(0, Math.floor(maxAgeSeconds))}`
112
+ ];
113
+ if (params.domain) parts.push(`Domain=${params.domain}`);
114
+ if (params.secure) parts.push("Secure");
115
+ return parts.join("; ");
116
+ };
117
+ var nowInSeconds = () => Math.floor(Date.now() / 1e3);
118
+ /**
119
+ * Adds to `Set-Cookie` rather than replacing it. A handler may already have written one — clearing an OAuth flow
120
+ * before granting the session it produced is exactly that — and replacing the header would silently drop it.
121
+ */
122
+ var appendCookies = (res, cookies) => {
123
+ const existing = res.getHeader?.("set-cookie") ?? res.headers?.["set-cookie"];
124
+ const previous = Array.isArray(existing) ? existing : typeof existing === "string" ? [existing] : [];
125
+ res.setHeader("Set-Cookie", [...previous, ...cookies]);
126
+ };
127
+ /**
128
+ * Writes a granted session onto the response: the credential itself, the refresh half confined to its own path, and
129
+ * the readable hint. One call, because the three only make sense together — a hint that outlives its session sends
130
+ * clients to renew something that is gone, and one that dies early signs out a live session.
131
+ */
132
+ var writeSessionCookies = (req, res, session, config) => {
133
+ const params = sessionCookieParams(req, config);
134
+ const now = nowInSeconds();
135
+ const cookies = [serializeCookie(params.name, session.token, session.expiresAt - now, params)];
136
+ if (session.refreshToken) cookies.push(serializeCookie(`${params.name}_refresh`, session.refreshToken, (session.refreshExpiresAt ?? session.expiresAt) - now, params, { path: params.refreshPath }));
137
+ cookies.push(serializeCookie(sessionHintCookieName(params), sessionHintValue(session.expiresAt, session.refreshExpiresAt), (session.refreshExpiresAt ?? session.expiresAt) - now, params, { httpOnly: false }));
138
+ appendCookies(res, cookies);
139
+ };
140
+ /** Ends the session in this browser. Every cookie the grant wrote is cleared, the readable one included. */
141
+ var clearSessionCookies = (req, res, config) => {
142
+ const params = sessionCookieParams(req, config);
143
+ appendCookies(res, [
144
+ serializeCookie(params.name, "", 0, params),
145
+ serializeCookie(`${params.name}_refresh`, "", 0, params, { path: params.refreshPath }),
146
+ serializeCookie(sessionHintCookieName(params), "", 0, params, { httpOnly: false })
147
+ ]);
148
+ };
149
+ /**
150
+ * The cookie a social sign-in leaves behind while the browser is away at the provider. Same family, same policy, so
151
+ * it is written here rather than by whoever happens to be driving the flow. Path `/` because a deployment may serve
152
+ * its API under a prefix, and the callback would then miss a cookie scoped to `/auth`.
153
+ */
154
+ var writeFlowCookie = (req, res, value, ttlSeconds, config) => {
155
+ const params = sessionCookieParams(req, config);
156
+ appendCookies(res, [serializeCookie(`${params.name}_oauth`, value, ttlSeconds, params)]);
157
+ };
158
+ var clearFlowCookie = (req, res, config) => {
159
+ const params = sessionCookieParams(req, config);
160
+ appendCookies(res, [serializeCookie(`${params.name}_oauth`, "", 0, params)]);
161
+ };
162
+ /** The value that flow cookie carries, for the callback leg. */
163
+ var readFlowCookie = (req, config) => readCookie(req, `${sessionCookieParams(req, config).name}_oauth`);
164
+ var parseCookieHeader = (header) => {
165
+ const cookies = {};
166
+ for (const part of header.split(";")) {
167
+ const separator = part.indexOf("=");
168
+ if (separator === -1) continue;
169
+ cookies[part.slice(0, separator).trim()] = decodeURIComponent(part.slice(separator + 1).trim());
170
+ }
171
+ return cookies;
172
+ };
173
+ var readCookie = (req, name) => {
174
+ const header = req.headers.cookie;
175
+ return header ? parseCookieHeader(header)[name] || void 0 : void 0;
176
+ };
177
+ /** The session credential this request carries, for an adapter that resolves identity from it. */
178
+ var readSessionToken = (req, config) => readCookie(req, sessionCookieParams(req, config).name);
179
+ /** The renewal credential, which rides in its own cookie confined to the refresh path. */
180
+ var readRefreshToken = (req, config) => readCookie(req, `${sessionCookieParams(req, config).name}_refresh`);
181
+ /** What the readable companion cookie says about this browser's session, without presenting any credential. */
182
+ var readSessionHint = (req, config) => {
183
+ return parseSessionHint(readCookie(req, sessionHintCookieName(sessionCookieParams(req, config))));
184
+ };
185
+ /**
186
+ * How long a page server holds off sending a browser to renew again. Long enough to cover the round trip there and
187
+ * back, short enough that a renewal which failed for a passing reason is retried on a later visit.
188
+ */
189
+ var RENEWAL_GUARD_SECONDS = 30;
190
+ /**
191
+ * Marks a browser as having just been sent to renew its session, so the page it comes back to is rendered rather
192
+ * than bounced again. Every renewal that can fail without ending the session — the refresh cookie not reaching the
193
+ * endpoint, the store being down — would otherwise send the visitor round in a loop.
194
+ */
195
+ var writeRenewalGuard = (req, res, config) => {
196
+ const params = sessionCookieParams(req, config);
197
+ appendCookies(res, [serializeCookie(`${params.name}_renewing`, "1", 30, params)]);
198
+ };
199
+ /**
200
+ * Where a renewal sends the browser back to: a path on this host, or a page on any host this session's cookies are
201
+ * scoped to — the only hosts that could have sent a browser here to renew, since the hint that triggers it rides on
202
+ * the same cookie domain. Anything else is an open redirect, and goes to `/` instead.
203
+ */
204
+ var sessionReturnTarget = (req, target, config) => {
205
+ if (typeof target !== "string" || target === "") return "/";
206
+ if (target.startsWith("/") && !target.startsWith("//") && !target.startsWith("/\\")) return target;
207
+ let url;
208
+ try {
209
+ url = new URL(target);
210
+ } catch {
211
+ return "/";
212
+ }
213
+ if (url.protocol !== "https:" && url.protocol !== "http:") return "/";
214
+ const { domain } = sessionCookieParams(req, config);
215
+ return url.hostname === req.hostname || domain !== void 0 && (url.hostname === domain.slice(1) || url.hostname.endsWith(domain)) ? url.toString() : "/";
216
+ };
217
+ var readRenewalGuard = (req, config) => readCookie(req, `${sessionCookieParams(req, config).name}_renewing`) !== void 0;
218
+ /**
219
+ * The cookie side of a session with this deployment's naming already bound in.
220
+ *
221
+ * The functions above take the naming on every call, which is right for the server's own internals and tedious for a
222
+ * host that answers dozens of requests with the same configuration. Nothing here knows about any framework: it takes
223
+ * a request that can be read and something that can carry `Set-Cookie`, which is as true of `node:http` as it is of
224
+ * Express — a self-hoster running neither still gets the whole cycle.
225
+ */
226
+ var createSessionCookies = (config) => ({
227
+ write: (req, res, session) => writeSessionCookies(req, res, session, config),
228
+ clear: (req, res) => clearSessionCookies(req, res, config),
229
+ /** Holds a social sign-in between its two legs: the CSRF nonce and the PKCE verifier. */
230
+ writeFlow: (req, res, value, ttlSeconds) => writeFlowCookie(req, res, value, ttlSeconds, config),
231
+ clearFlow: (req, res) => clearFlowCookie(req, res, config),
232
+ readFlow: (req) => readFlowCookie(req, config),
233
+ returnTarget: (req, target) => sessionReturnTarget(req, target, config),
234
+ /**
235
+ * The session credential from `Authorization: Bearer` or the cookie, so one endpoint serves a bearer client and a
236
+ * browser. The header wins: a caller that went to the trouble of presenting one means it.
237
+ */
238
+ resolveSessionToken: (req) => {
239
+ const header = req.headers.authorization;
240
+ return (header?.startsWith("Bearer ") ? header.slice(7).trim() : "") || readSessionToken(req, config);
241
+ },
242
+ /**
243
+ * The renewal credential from the request body (`refresh_token`, for API clients) or its cookie (for browsers).
244
+ * The body wins when both are present, mirroring how the session credential is resolved. `body` is whatever the
245
+ * host parsed — this only reads one field off it, so a host that parses JSON its own way still fits.
246
+ */
247
+ resolveRefreshToken: (req, body) => {
248
+ const presented = body?.refresh_token;
249
+ if (typeof presented === "string" && presented.trim() !== "") return presented.trim();
250
+ return readRefreshToken(req, config);
251
+ }
252
+ });
253
+ export { sessionHintValue as _, createSessionCookies as a, writeRenewalGuard as b, parseSessionHint as c, readRenewalGuard as d, readSessionHint as f, sessionHintCookieName as g, sessionCookieParams as h, clearSessionCookies as i, readFlowCookie as l, registrableDomain as m, appendCookies as n, isLocalHost as o, readSessionToken as p, clearFlowCookie as r, isPrivateNetworkHost as s, RENEWAL_GUARD_SECONDS as t, readRefreshToken as u, sessionReturnTarget as v, writeSessionCookies as x, writeFlowCookie as y };
@@ -0,0 +1,43 @@
1
+ import { randomBytes, randomUUID, scrypt, timingSafeEqual } from "node:crypto";
2
+ import { promisify } from "node:util";
3
+ // src/identity/passwords.ts
4
+ var scrypt$1 = promisify(scrypt);
5
+ var KEY_LENGTH = 64;
6
+ /**
7
+ * Password hashing that a deployment does not have to choose, and by default does not even have to know about:
8
+ * this is what `createAuthApi` uses when nobody says otherwise.
9
+ *
10
+ * `scrypt` from the standard library, so this costs no dependency and nothing has to be compiled. It is a memory-hard
11
+ * KDF and an entirely respectable answer; argon2 or bcrypt are better ones, and a deployment that wants either passes
12
+ * its own `verifyPassword`/`hashPassword` to `createAuth` — nothing here assumes an algorithm.
13
+ *
14
+ * The format is `scrypt$<salt>$<hash>`, tagged so a later change of algorithm can recognise what it is looking at
15
+ * instead of guessing from the shape.
16
+ */
17
+ var hashPassword = async (plain) => {
18
+ const salt = randomBytes(16).toString("hex");
19
+ return `scrypt$${salt}$${(await scrypt$1(plain, salt, KEY_LENGTH)).toString("hex")}`;
20
+ };
21
+ var verifyPassword = async (plain, stored) => {
22
+ const [algorithm, salt, digest] = stored.split("$");
23
+ if (algorithm !== "scrypt" || !salt || !digest) return false;
24
+ const expected = Buffer.from(digest, "hex");
25
+ if (expected.length !== KEY_LENGTH) return false;
26
+ const actual = await scrypt$1(plain, salt, KEY_LENGTH);
27
+ return timingSafeEqual(expected, actual);
28
+ };
29
+ /** Opaque single-use strings, for validation and password-reset links. */
30
+ var generateToken = () => randomUUID().replace(/-/g, "");
31
+ // src/identity/sessionActivity.ts
32
+ /**
33
+ * When a session was last used, to the resolution a device list needs.
34
+ *
35
+ * "Active 3 minutes ago" against "active last March" is what tells somebody which of their devices is the one they do
36
+ * not recognise — and the time a session was CREATED says neither: a laptop signed in a month ago and used this morning
37
+ * reads as a month-old session. Recording every request would be a write per request on the hottest read in the
38
+ * system, so a store records it at most once per this many seconds, on the lookup it already makes.
39
+ */
40
+ var SESSION_ACTIVITY_RESOLUTION_SECONDS = 300;
41
+ /** Whether a session last seen at `lastActiveAt` (unix seconds, absent when never) is due a new record at `now`. */
42
+ var activityDue = (lastActiveAt, now) => lastActiveAt === null || lastActiveAt === void 0 || now - lastActiveAt >= 300;
43
+ export { verifyPassword as a, hashPassword as i, activityDue as n, generateToken as r, SESSION_ACTIVITY_RESOLUTION_SECONDS as t };
@@ -0,0 +1,76 @@
1
+ import { o as isLocalHost, s as isPrivateNetworkHost } from "./session-B-dTEjeG.mjs";
2
+ // src/http/securityHeaders.ts
3
+ /** A year: what the browsers' preload list asks of a site, and what Lighthouse takes as a strong policy. */
4
+ var HSTS_MAX_AGE = 31536e3;
5
+ /** Domains no public certificate authority signs for: a development certificate is all they ever have. */
6
+ var UNCERTIFIED = /\.(local|test|localhost|internal)$/;
7
+ /**
8
+ * The `Strict-Transport-Security` a response over https carries, or none — see `ServerBaseConfig.hsts` — and on a host
9
+ * whose deployment says (`SSRDeploymentSecurity.hsts`): `'host'` keeps to that host alone, `'subdomains'` reaches every
10
+ * sub-domain of it, `'off'` asks nothing.
11
+ */
12
+ var hstsFor = (req, config, chosen) => {
13
+ const { hsts } = config;
14
+ const { hostname } = req;
15
+ if (hsts === false || chosen === "off" || req.protocol !== "https" || isLocalHost(hostname) || isPrivateNetworkHost(hostname) || UNCERTIFIED.test(hostname)) return;
16
+ const { maxAge = HSTS_MAX_AGE, includeSubDomains = true, preload = false } = hsts ?? {};
17
+ const subDomains = chosen === void 0 ? includeSubDomains : chosen === "subdomains";
18
+ return [
19
+ `max-age=${String(maxAge)}`,
20
+ ...subDomains ? ["includeSubDomains"] : [],
21
+ ...preload && subDomains ? ["preload"] : []
22
+ ].join("; ");
23
+ };
24
+ /**
25
+ * Who may put the page in a frame, as CSP `frame-ancestors`: the space's own list when its deployment names one — only
26
+ * it knows the sites its owner allowed — and the sites its domain adds (`security.frameAncestors`), else the server's
27
+ * `frameOptions`. One place, because the page's script policy is sent in the same header (`pagePolicies`) and a second
28
+ * header would replace this one.
29
+ */
30
+ var frameAncestorsOf = (config, deployment) => {
31
+ const ofSpace = deployment?.frameAncestors ?? [];
32
+ const ofDomain = deployment?.security?.frameAncestors ?? [];
33
+ if (ofSpace.length > 0 || ofDomain.length > 0) {
34
+ const sources = [...ofSpace.length > 0 ? ofSpace : ["'self'"], ...ofDomain];
35
+ return `frame-ancestors ${[...new Set(sources)].join(" ")}`;
36
+ }
37
+ const frameOptions = config.frameOptions === void 0 ? "DENY" : config.frameOptions;
38
+ if (!frameOptions) return;
39
+ return Array.isArray(frameOptions) ? `frame-ancestors ${frameOptions.join(" ")}` : `frame-ancestors '${frameOptions === "DENY" ? "none" : "self"}'`;
40
+ };
41
+ var applySecurityHeaders = (req, res, config, port) => {
42
+ res.setHeader("X-Content-Type-Options", "nosniff");
43
+ res.setHeader("Referrer-Policy", "strict-origin-when-cross-origin");
44
+ res.setHeader("X-DNS-Prefetch-Control", "off");
45
+ const frameAncestors = frameAncestorsOf(config);
46
+ if (frameAncestors) res.setHeader("Content-Security-Policy", frameAncestors);
47
+ const frameOptions = config.frameOptions === void 0 ? "DENY" : config.frameOptions;
48
+ if (typeof frameOptions === "string") res.setHeader("X-Frame-Options", frameOptions);
49
+ const hsts = hstsFor(req, config);
50
+ if (hsts) res.setHeader("Strict-Transport-Security", hsts);
51
+ const opener = config.crossOriginOpenerPolicy ?? "same-origin-allow-popups";
52
+ if (opener) res.setHeader("Cross-Origin-Opener-Policy", opener);
53
+ if ((config.httpVersion ?? 2) >= 3) res.setHeader("Alt-Svc", `h3=":${port}"; ma=86400`);
54
+ };
55
+ // src/deployment/spaceDeployment.ts
56
+ var spaceDeploymentMiddleware = (adapters, config) => {
57
+ return async (req, res, next) => {
58
+ const deployment = await adapters.getSpaceDeployment(req);
59
+ req.ctx.spaceDeployment = deployment;
60
+ const { spaceId, error, frameAncestors, security } = deployment;
61
+ if (spaceId == null || error) {
62
+ res.setStatus(error?.code ?? 404);
63
+ res.send(error?.message ?? "Space not found");
64
+ return;
65
+ }
66
+ if ((frameAncestors?.length ?? 0) > 0 || (security?.frameAncestors?.length ?? 0) > 0) res.setHeader("Content-Security-Policy", frameAncestorsOf(config, deployment) ?? "");
67
+ const chosen = security?.hsts;
68
+ if (chosen !== void 0) {
69
+ const hsts = hstsFor(req, config, chosen);
70
+ if (hsts) res.setHeader("Strict-Transport-Security", hsts);
71
+ else Reflect.deleteProperty(res.headers, "Strict-Transport-Security");
72
+ }
73
+ await next();
74
+ };
75
+ };
76
+ export { hstsFor as i, applySecurityHeaders as n, frameAncestorsOf as r, spaceDeploymentMiddleware as t };