@selvajs/selva 4.21.0-beta.21 → 4.21.0-beta.23

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 (228) hide show
  1. package/build/adapter-node.js +1 -1
  2. package/build/client/_app/immutable/chunks/B58dPMPq.js +1 -0
  3. package/build/client/_app/immutable/chunks/B58dPMPq.js.br +1 -0
  4. package/build/client/_app/immutable/chunks/B58dPMPq.js.gz +0 -0
  5. package/build/client/_app/immutable/chunks/{C6zhj8Tc.js → DtmN00GS.js} +3 -3
  6. package/build/client/_app/immutable/chunks/DtmN00GS.js.br +0 -0
  7. package/build/client/_app/immutable/chunks/{C6zhj8Tc.js.gz → DtmN00GS.js.gz} +0 -0
  8. package/build/client/_app/immutable/entry/{app.C2KpbBu3.js → app.Dl3HM1mx.js} +2 -2
  9. package/build/client/_app/immutable/entry/app.Dl3HM1mx.js.br +0 -0
  10. package/build/client/_app/immutable/entry/app.Dl3HM1mx.js.gz +0 -0
  11. package/build/client/_app/immutable/nodes/21.BZJQikE5.js +1 -0
  12. package/build/client/_app/immutable/nodes/21.BZJQikE5.js.br +0 -0
  13. package/build/client/_app/immutable/nodes/21.BZJQikE5.js.gz +0 -0
  14. package/build/client/_app/version.json +1 -1
  15. package/build/client/_app/version.json.br +0 -0
  16. package/build/client/_app/version.json.gz +0 -0
  17. package/build/server/.vite/manifest.json +228 -187
  18. package/build/server/chunks/AppHeader.js +1 -1
  19. package/build/server/chunks/Callout.js +1 -1
  20. package/build/server/chunks/ConfirmDialog.js +1 -1
  21. package/build/server/chunks/DataTable.js +1 -1
  22. package/build/server/chunks/DefinitionCard.js +2 -2
  23. package/build/server/chunks/EmptyState.js +1 -1
  24. package/build/server/chunks/ErrorScreen.js +1 -1
  25. package/build/server/chunks/FilterableDropdown.js +1 -1
  26. package/build/server/chunks/PageContent.js +1 -1
  27. package/build/server/chunks/SectionHeader.js +1 -1
  28. package/build/server/chunks/SettingsMenu.js +1 -1
  29. package/build/server/chunks/SideNav.js +1 -1
  30. package/build/server/chunks/StatCard.js +1 -1
  31. package/build/server/chunks/UserAvatar.js +1 -1
  32. package/build/server/chunks/UserRowIdentity.js +1 -1
  33. package/build/server/chunks/activity.js +1 -1
  34. package/build/server/chunks/alert-dialog.js +1 -1
  35. package/build/server/chunks/arrow-left.js +1 -1
  36. package/build/server/chunks/arrow-right.js +1 -1
  37. package/build/server/chunks/{keepalive-DbmLH4v1.js → async-solve-Doflh4BJ.js} +5 -3
  38. package/build/server/chunks/async-solve-Doflh4BJ.js.map +1 -0
  39. package/build/server/chunks/asyncSolves.server.js +22 -0
  40. package/build/server/chunks/asyncSolves.server.js.map +1 -0
  41. package/build/server/chunks/auth-bootstrap.server.js +1 -1
  42. package/build/server/chunks/badge.js +1 -1
  43. package/build/server/chunks/boot.server.js +1 -1
  44. package/build/server/chunks/building-complex.js +1 -1
  45. package/build/server/chunks/button.js +1 -1
  46. package/build/server/chunks/capture.js +1 -1
  47. package/build/server/chunks/card-content.js +1 -1
  48. package/build/server/chunks/card-description.js +1 -1
  49. package/build/server/chunks/card-header.js +1 -1
  50. package/build/server/chunks/card-title.js +1 -1
  51. package/build/server/chunks/chevron-down.js +1 -1
  52. package/build/server/chunks/chevron-left.js +1 -1
  53. package/build/server/chunks/chevron-right.js +1 -1
  54. package/build/server/chunks/chevron-up.js +1 -1
  55. package/build/server/chunks/circle.js +1 -1
  56. package/build/server/chunks/computeRateLimit.server.js +1 -1
  57. package/build/server/chunks/copy.js +1 -1
  58. package/build/server/chunks/create-id.js +1 -1
  59. package/build/server/chunks/delete-with-blobs.js +1 -1
  60. package/build/server/chunks/dialog-description.js +1 -1
  61. package/build/server/chunks/dialog.js +1 -1
  62. package/build/server/chunks/dom-typeahead.svelte.js +1 -1
  63. package/build/server/chunks/dynamic-value-list.js +301 -0
  64. package/build/server/chunks/dynamic-value-list.js.map +1 -0
  65. package/build/server/chunks/engine.server.js +2 -1
  66. package/build/server/chunks/engine.server.js.map +1 -1
  67. package/build/server/chunks/events.js +1 -1
  68. package/build/server/chunks/external-link.js +1 -1
  69. package/build/server/chunks/folder-kanban.js +1 -1
  70. package/build/server/chunks/folder-open.js +1 -1
  71. package/build/server/chunks/folders.js +1 -1
  72. package/build/server/chunks/footerContext.svelte.js +1 -1
  73. package/build/server/chunks/gauge.js +1 -1
  74. package/build/server/chunks/handlers.js +1 -1
  75. package/build/server/chunks/index-server2.js +1 -1
  76. package/build/server/chunks/input-group.js +1 -1
  77. package/build/server/chunks/input.js +1 -1
  78. package/build/server/chunks/instance.js +4 -4
  79. package/build/server/chunks/instanceAdmins.server.js +1 -1
  80. package/build/server/chunks/internal.js +1 -1
  81. package/build/server/chunks/key-round.js +1 -1
  82. package/build/server/chunks/label.js +1 -1
  83. package/build/server/chunks/link-2.js +1 -1
  84. package/build/server/chunks/localeContext.svelte.js +1 -1
  85. package/build/server/chunks/mail.js +1 -1
  86. package/build/server/chunks/minus.js +1 -1
  87. package/build/server/chunks/package.js +2 -2
  88. package/build/server/chunks/package.js.map +1 -1
  89. package/build/server/chunks/permissions.server.js +1 -1
  90. package/build/server/chunks/plus.js +1 -1
  91. package/build/server/chunks/popper-layer-force-mount.js +1 -1
  92. package/build/server/chunks/providers.server.js +3 -28134
  93. package/build/server/chunks/providers.server.js.map +1 -1
  94. package/build/server/chunks/refresh-cw.js +1 -1
  95. package/build/server/chunks/registry.js +22 -0
  96. package/build/server/chunks/registry.js.map +1 -1
  97. package/build/server/chunks/rotate-ccw.js +1 -1
  98. package/build/server/chunks/roving-focus-group.js +1 -1
  99. package/build/server/chunks/scroll-lock.js +1 -1
  100. package/build/server/chunks/scroll-text.js +1 -1
  101. package/build/server/chunks/search.js +1 -1
  102. package/build/server/chunks/search2.js +1 -1
  103. package/build/server/chunks/select.js +1 -1
  104. package/build/server/chunks/separator.js +1 -1
  105. package/build/server/chunks/server-config-write.js +1 -1
  106. package/build/server/chunks/server.js +28298 -5
  107. package/build/server/chunks/server.js.map +1 -1
  108. package/build/server/chunks/server2.js +5 -107
  109. package/build/server/chunks/server2.js.map +1 -1
  110. package/build/server/chunks/server3.js +101 -3911
  111. package/build/server/chunks/server3.js.map +1 -1
  112. package/build/server/chunks/server4.js +3916 -41
  113. package/build/server/chunks/server4.js.map +1 -1
  114. package/build/server/chunks/server5.js +45 -0
  115. package/build/server/chunks/server5.js.map +1 -0
  116. package/build/server/chunks/settings.js +1 -1
  117. package/build/server/chunks/severity.js +1 -1
  118. package/build/server/chunks/shield-check.js +1 -1
  119. package/build/server/chunks/shield.js +1 -1
  120. package/build/server/chunks/signInMaxAge.server.js +1 -1
  121. package/build/server/chunks/solve.server.js +4 -3
  122. package/build/server/chunks/solve.server.js.map +1 -1
  123. package/build/server/chunks/star.js +1 -1
  124. package/build/server/chunks/state.js +1 -1
  125. package/build/server/chunks/sveltekit.js +1 -1
  126. package/build/server/chunks/tabs-trigger.js +1 -1
  127. package/build/server/chunks/textarea.js +1 -1
  128. package/build/server/chunks/toast-state.svelte.js +1 -1
  129. package/build/server/chunks/toggle-group-item.js +1 -1
  130. package/build/server/chunks/trash.js +1 -1
  131. package/build/server/chunks/user-plus.js +1 -1
  132. package/build/server/chunks/users.js +1 -1
  133. package/build/server/chunks/utils.js +1 -1
  134. package/build/server/chunks/x.js +1 -1
  135. package/build/server/entries/endpoints/.well-known/oauth-authorization-server/_server.ts.js +1 -1
  136. package/build/server/entries/endpoints/.well-known/oauth-protected-resource/_server.ts.js +1 -1
  137. package/build/server/entries/endpoints/.well-known/oauth-protected-resource/mcp/_server.ts.js +1 -1
  138. package/build/server/entries/endpoints/api/admin/compute/_server.ts.js +1 -1
  139. package/build/server/entries/endpoints/api/admin/compute/actions/_server.ts.js +1 -1
  140. package/build/server/entries/endpoints/api/admin/compute/status/_server.ts.js +1 -1
  141. package/build/server/entries/endpoints/api/admin/orgs/_id_/_server.ts.js +1 -1
  142. package/build/server/entries/endpoints/api/admin/orgs/_server.ts.js +1 -1
  143. package/build/server/entries/endpoints/api/admin/projects/_id_/_server.ts.js +1 -1
  144. package/build/server/entries/endpoints/api/admin/projects/_id_/grants/_grantId_/_server.ts.js +1 -1
  145. package/build/server/entries/endpoints/api/admin/projects/_id_/grants/_server.ts.js +1 -1
  146. package/build/server/entries/endpoints/api/admin/projects/_server.ts.js +1 -1
  147. package/build/server/entries/endpoints/api/admin/system/health/_server.ts.js +1 -1
  148. package/build/server/entries/endpoints/api/admin/system/update/_server.ts.js +1 -1
  149. package/build/server/entries/endpoints/api/admin/users/_id_/_server.ts.js +1 -1
  150. package/build/server/entries/endpoints/api/admin/users/_id_/disable/_server.ts.js +1 -1
  151. package/build/server/entries/endpoints/api/admin/users/_server.ts.js +1 -1
  152. package/build/server/entries/endpoints/api/files/_...path_/_server.ts.js +1 -1
  153. package/build/server/entries/endpoints/api/v1/compute/_server.ts.js +8 -4
  154. package/build/server/entries/endpoints/api/v1/compute/_server.ts.js.map +1 -1
  155. package/build/server/entries/endpoints/api/v1/definitions/_guid_/solve/_server.ts.js +12 -3
  156. package/build/server/entries/endpoints/api/v1/definitions/_guid_/solve/_server.ts.js.map +1 -1
  157. package/build/server/entries/endpoints/api/v1/solves/_solveId_/_server.ts.js +32 -0
  158. package/build/server/entries/endpoints/api/v1/solves/_solveId_/_server.ts.js.map +1 -0
  159. package/build/server/entries/endpoints/auth/email/callback/_server.ts.js +1 -1
  160. package/build/server/entries/endpoints/auth/supabase/callback/_server.ts.js +1 -1
  161. package/build/server/entries/endpoints/auth/supabase/start/_server.ts.js +1 -1
  162. package/build/server/entries/endpoints/docs/api/openapi.yaml/_server.ts.js +1 -1
  163. package/build/server/entries/endpoints/mcp/_server.ts.js +244 -41
  164. package/build/server/entries/endpoints/mcp/_server.ts.js.map +1 -1
  165. package/build/server/entries/endpoints/oauth/register/_server.ts.js +1 -1
  166. package/build/server/entries/endpoints/oauth/token/_server.ts.js +1 -1
  167. package/build/server/entries/hooks.server.js +2 -1
  168. package/build/server/entries/hooks.server.js.map +1 -1
  169. package/build/server/entries/pages/_error.svelte.js +1 -1
  170. package/build/server/entries/pages/_layout.svelte.js +1 -1
  171. package/build/server/entries/pages/_page.svelte.js +1 -1
  172. package/build/server/entries/pages/accept-invite/_page.svelte.js +1 -1
  173. package/build/server/entries/pages/admin/_error.svelte.js +1 -1
  174. package/build/server/entries/pages/admin/_layout.svelte.js +2 -2
  175. package/build/server/entries/pages/admin/_page.svelte.js +2 -2
  176. package/build/server/entries/pages/admin/audit/_page.svelte.js +1 -1
  177. package/build/server/entries/pages/admin/compute/_page.svelte.js +2 -2
  178. package/build/server/entries/pages/admin/organizations/_page.svelte.js +1 -1
  179. package/build/server/entries/pages/admin/projects/_id_/_page.svelte.js +1 -1
  180. package/build/server/entries/pages/admin/projects/_page.svelte.js +1 -1
  181. package/build/server/entries/pages/admin/system/_page.server.ts.js +1 -1
  182. package/build/server/entries/pages/admin/system/_page.svelte.js +1 -1
  183. package/build/server/entries/pages/admin/users/_page.svelte.js +1 -1
  184. package/build/server/entries/pages/auth/email/sent/_page.svelte.js +1 -1
  185. package/build/server/entries/pages/auth/email/start/_page.svelte.js +1 -1
  186. package/build/server/entries/pages/docs/api/_page.svelte.js +1 -1
  187. package/build/server/entries/pages/library/_guid_/_page.server.ts.js +1 -1
  188. package/build/server/entries/pages/library/_guid_/_page.svelte.js +71 -305
  189. package/build/server/entries/pages/library/_guid_/_page.svelte.js.map +1 -1
  190. package/build/server/entries/pages/library/_layout.svelte.js +1 -1
  191. package/build/server/entries/pages/library/_page.svelte.js +1 -1
  192. package/build/server/entries/pages/login/_page.svelte.js +1 -1
  193. package/build/server/entries/pages/oauth/authorize/_page.server.ts.js +1 -1
  194. package/build/server/entries/pages/oauth/authorize/_page.svelte.js +1 -1
  195. package/build/server/entries/pages/projects/_layout.svelte.js +1 -1
  196. package/build/server/entries/pages/projects/_page.server.ts.js +1 -1
  197. package/build/server/entries/pages/projects/_page.svelte.js +1 -1
  198. package/build/server/entries/pages/setup/_page.server.ts.js +1 -1
  199. package/build/server/entries/pages/setup/_page.svelte.js +1 -1
  200. package/build/server/entries/pages/team/_layout.svelte.js +2 -2
  201. package/build/server/entries/pages/team/_page.svelte.js +1 -1
  202. package/build/server/entries/pages/team/activity/_page.svelte.js +1 -1
  203. package/build/server/entries/pages/team/compute/_page.svelte.js +2 -2
  204. package/build/server/entries/pages/team/members/_page.svelte.js +1 -1
  205. package/build/server/entries/pages/team/projects/_page.server.ts.js +1 -1
  206. package/build/server/entries/pages/team/projects/_page.svelte.js +1 -1
  207. package/build/server/entries/pages/team/reclaim/_page.svelte.js +1 -1
  208. package/build/server/entries/pages/team/settings/_page.svelte.js +1 -1
  209. package/build/server/entries/pages/team/shares/_page.svelte.js +1 -1
  210. package/build/server/entries/pages/team/tokens/_page.svelte.js +1 -1
  211. package/build/server/index.js +1 -1
  212. package/build/server/manifest-full.js +8 -1
  213. package/build/server/manifest.js +8 -1
  214. package/build/server/nodes/21.js +1 -1
  215. package/build/server/remote-entry.js +1 -1
  216. package/build/server/server.js +8 -1
  217. package/package.json +8 -8
  218. package/templates/.env.example +5 -3
  219. package/build/client/_app/immutable/chunks/C36Kxzt3.js +0 -1
  220. package/build/client/_app/immutable/chunks/C36Kxzt3.js.br +0 -1
  221. package/build/client/_app/immutable/chunks/C36Kxzt3.js.gz +0 -0
  222. package/build/client/_app/immutable/chunks/C6zhj8Tc.js.br +0 -0
  223. package/build/client/_app/immutable/entry/app.C2KpbBu3.js.br +0 -0
  224. package/build/client/_app/immutable/entry/app.C2KpbBu3.js.gz +0 -0
  225. package/build/client/_app/immutable/nodes/21.C3YDbmsU.js +0 -1
  226. package/build/client/_app/immutable/nodes/21.C3YDbmsU.js.br +0 -0
  227. package/build/client/_app/immutable/nodes/21.C3YDbmsU.js.gz +0 -0
  228. package/build/server/chunks/keepalive-DbmLH4v1.js.map +0 -1
@@ -1,4 +1,4 @@
1
- import { a as oauthUnavailable, i as oauthServer, r as oauthRateLimited } from "../../../../chunks/server2.js";
1
+ import { a as oauthUnavailable, i as oauthServer, r as oauthRateLimited } from "../../../../chunks/server3.js";
2
2
  import { t as publicUrl } from "../../../../chunks/origin.js";
3
3
  import { json } from "@sveltejs/kit";
4
4
  // src/routes/oauth/register/+server.ts
@@ -1,4 +1,4 @@
1
- import { a as oauthUnavailable, i as oauthServer, r as oauthRateLimited } from "../../../../chunks/server2.js";
1
+ import { a as oauthUnavailable, i as oauthServer, r as oauthRateLimited } from "../../../../chunks/server3.js";
2
2
  import { t as publicUrl } from "../../../../chunks/origin.js";
3
3
  import { json } from "@sveltejs/kit";
4
4
  // src/routes/oauth/token/+server.ts
@@ -1,6 +1,6 @@
1
- import { H as emptyProfile, T as providers, b as getSolveMetricSink, f as getLogger, l as getErrorReporter, t as flag, u as getEventSink, w as lazyLogger } from "../chunks/providers.server.js";
2
1
  import { n as env } from "../chunks/previous-key.js";
3
2
  import { j as isApiError } from "../chunks/access.js";
3
+ import { P as emptyProfile, T as providers, b as getSolveMetricSink, f as getLogger, l as getErrorReporter, t as flag, u as getEventSink, w as lazyLogger } from "../chunks/providers.server.js";
4
4
  import { a as wireHeaderAuthBootstrap, n as hasSetupProof, r as identifyWithSetupProof, t as bootstrapUserSession } from "../chunks/auth-bootstrap.server.js";
5
5
  import { t as SYSTEM_CONTEXT } from "../chunks/context.js";
6
6
  import "../chunks/api.js";
@@ -550,6 +550,7 @@ var { isStaticAsset, isSelfGatingApiRoute, isPublicRoute } = createRouteClassifi
550
550
  selfGatingPrefixes: [
551
551
  "/api/files/",
552
552
  "/api/v1/solve-events",
553
+ "/api/v1/solves/",
553
554
  MCP_FILES_PREFIX
554
555
  ],
555
556
  staticPrefixes: ["/_app/", "/favicon/"],
@@ -1 +1 @@
1
- {"version":3,"file":"hooks.server.js","names":[],"sources":["../../../../providers/supabase/src/upstream.ts","../../../../server/src/http/security-headers.ts","../../../../server/src/http/route-classifier.ts","../../../../server/src/http/session-resolver.ts","../../../../server/src/http/request-timing.ts","../../../src/lib/server/requestTiming.server.ts","../../../src/lib/server/framing.ts","../../../src/hooks.server.ts"],"sourcesContent":["/**\n * Supabase serves every API under one origin; the path prefix names the service. For a\n * request-timing classifier (`createRequestTiming` in `@selvajs/server/http`): `db`, `auth` or\n * `storage`, and for the database the table or RPC a call reached (`db jobs`, `db rpc/x`).\n */\n\nconst SERVICES: [prefix: string, name: string][] = [\n\t['/rest/v1/', 'db'],\n\t['/auth/v1/', 'auth'],\n\t['/storage/v1/', 'storage']\n];\n\nexport function supabaseUpstream(url: URL): { key: string; target: string } | undefined {\n\tconst service = SERVICES.find(([prefix]) => url.pathname.startsWith(prefix));\n\tif (!service) return undefined;\n\tconst [first = '', second = ''] = url.pathname.slice(service[0].length).split('/');\n\treturn { key: service[1], target: `${service[1]} ${first === 'rpc' ? `rpc/${second}` : first}` };\n}\n","export interface SecurityHeaderOptions {\n\t/**\n\t * Set `Strict-Transport-Security`. Production only — pinning\n\t * http://localhost to HTTPS bricks local development. The caller decides\n\t * what \"production\" means (e.g. `NODE_ENV`).\n\t */\n\thsts: boolean;\n\t/**\n\t * Forbid framing this response. Off by default — Selva-engine app routes are\n\t * built to be embedded. Turn it on for operator surfaces (`/admin/*`,\n\t * `/setup`), where an authenticated session plus a framable page is a\n\t * UI-redress attack. `SameSite=Lax` blunts cross-site POST, not same-origin\n\t * redress, so the cookie flag is not a substitute.\n\t */\n\tdenyFraming?: boolean;\n}\n\n/**\n * Apply baseline browser-hardening headers to a response and return it for\n * chaining. Each is a cheap win that needs no UI verification:\n *\n * - X-Content-Type-Options: nosniff — disables MIME sniffing.\n * - Referrer-Policy: strict-origin-when-cross-origin — strips path and query\n * from cross-origin Referer headers. Matches modern browser defaults, but\n * pins the behavior in case a default drifts.\n * - Permissions-Policy: opts out of browser APIs Selva-engine apps don't use,\n * so XSS can't enable them.\n * - HSTS when `opts.hsts`.\n * - X-Frame-Options + `frame-ancestors 'none'` when `opts.denyFraming` — the\n * caller opts in per route, since embeddable app routes must stay framable.\n *\n * **Intentionally NOT set here:**\n * - A full Content-Security-Policy. Selva-engine apps are built for iframe\n * embedding, so a strict CSP needs validating against real consumer sites\n * before it can ship. `denyFraming` sets only the `frame-ancestors`\n * directive, which constrains nothing else the page loads.\n * - Cache-Control. Asset-path layout is app policy; set it in the caller.\n */\nexport function applySecurityHeaders(response: Response, opts: SecurityHeaderOptions): Response {\n\tresponse.headers.set('X-Content-Type-Options', 'nosniff');\n\tresponse.headers.set('Referrer-Policy', 'strict-origin-when-cross-origin');\n\tresponse.headers.set(\n\t\t'Permissions-Policy',\n\t\t'accelerometer=(), camera=(), geolocation=(), gyroscope=(), magnetometer=(), microphone=(), payment=(), usb=()'\n\t);\n\tif (opts.hsts) {\n\t\tresponse.headers.set('Strict-Transport-Security', 'max-age=31536000; includeSubDomains');\n\t}\n\tif (opts.denyFraming) {\n\t\tresponse.headers.set('X-Frame-Options', 'DENY');\n\t\tresponse.headers.set('Content-Security-Policy', \"frame-ancestors 'none'\");\n\t}\n\treturn response;\n}\n","/**\n * Deny-by-default route classification. A request is gated unless its path\n * matches one of the allowlists supplied here, so forgetting to list a new\n * route makes it gated — a loud 401/redirect, not silently public.\n *\n * The pattern is reusable; the values are app policy, supplied by the consuming\n * app. Matching is plain exact/prefix string comparison: cheap enough for the\n * hooks hot path, and no regex to get wrong.\n */\n\nexport interface RouteClassifierConfig {\n\t/** Exact-match pages needing no session (e.g. `/`, `/login`). */\n\tpublicPages?: Iterable<string>;\n\t/** Public path prefixes (e.g. `/auth/` — OAuth start and callback precede any session). */\n\tpublicPrefixes?: readonly string[];\n\t/**\n\t * Exact-match API endpoints that answer without a session (e.g. a\n\t * load-balancer health probe). Anything listed here is exposed to anonymous\n\t * callers.\n\t */\n\tpublicApis?: Iterable<string>;\n\t/**\n\t * Prefixes whose routes authorize each request themselves (e.g. a blob\n\t * proxy classifying per asset path, or a callback authenticated by a\n\t * per-request bearer). These classify as public so the hook attaches a\n\t * session best-effort and does not deny up front; the route makes the real\n\t * decision. Keep the list short — every other API route stays deny-by-default.\n\t */\n\tselfGatingPrefixes?: readonly string[];\n\t/** Single-prefix form of `selfGatingPrefixes`. */\n\tselfGatingPrefix?: string;\n\t/** Static-asset prefixes the adapter serves directly (e.g. `/_app/`). */\n\tstaticPrefixes?: readonly string[];\n\t/** Exact static-asset paths (e.g. `/favicon.svg`, `/robots.txt`). */\n\tstaticPaths?: Iterable<string>;\n}\n\nexport interface RouteClassifier {\n\t/** Matches `staticPaths`/`staticPrefixes`. These bypass auth gating entirely. */\n\tisStaticAsset(pathname: string): boolean;\n\t/** Matches `selfGatingPrefix`. The hook must not deny these — the route gates itself. */\n\tisSelfGatingApiRoute(pathname: string): boolean;\n\t/** Needs no session: a public page, API, prefix, or a self-gating route. */\n\tisPublicRoute(pathname: string): boolean;\n}\n\nexport function createRouteClassifier(config: RouteClassifierConfig): RouteClassifier {\n\tconst publicPages = new Set(config.publicPages ?? []);\n\tconst publicPrefixes = config.publicPrefixes ?? [];\n\tconst publicApis = new Set(config.publicApis ?? []);\n\tconst selfGatingPrefixes = [\n\t\t...(config.selfGatingPrefixes ?? []),\n\t\t...(config.selfGatingPrefix !== undefined ? [config.selfGatingPrefix] : [])\n\t];\n\tconst staticPrefixes = config.staticPrefixes ?? [];\n\tconst staticPaths = new Set(config.staticPaths ?? []);\n\n\tfunction isStaticAsset(pathname: string): boolean {\n\t\tif (staticPaths.has(pathname)) return true;\n\t\treturn staticPrefixes.some((p) => pathname.startsWith(p));\n\t}\n\n\tfunction isSelfGatingApiRoute(pathname: string): boolean {\n\t\treturn selfGatingPrefixes.some((p) => pathname.startsWith(p));\n\t}\n\n\tfunction isPublicRoute(pathname: string): boolean {\n\t\tif (publicPages.has(pathname)) return true;\n\t\tif (publicApis.has(pathname)) return true;\n\t\tif (isSelfGatingApiRoute(pathname)) return true;\n\t\treturn publicPrefixes.some((p) => pathname.startsWith(p));\n\t}\n\n\treturn { isStaticAsset, isSelfGatingApiRoute, isPublicRoute };\n}\n","/**\n * Turns a session token into whatever a host attaches to a request, with the round trips that\n * cost cut to what the token needs.\n *\n * - The user's rows are read beside `verify`, keyed by the token's unverified subject, and kept\n * only when `verify` confirms that same user. `read` must be a read: it runs before the token\n * is checked, so it must not write anything for the subject it is handed.\n * - Requests carrying one token share one resolution while it runs.\n * - With `freshForMs`, a resolved session is reused for that long. Past it the session is still\n * answered, and resolved again behind the request; a re-check that refuses the token drops it,\n * so after a sign-out or disable the requests already in flight are the last to get through.\n * A session is never answered past its token's expiry, so row security never sees an expired\n * token mid-request.\n */\n\nimport type { AuthUser } from '@selvajs/platform';\n\nexport interface SessionResolverConfig<Rows, Session> {\n\t/** The token's user, or null for a token it refuses. */\n\tverify(token: string): Promise<AuthUser | null>;\n\t/** Everything the session needs that is keyed by the user id alone. Never a write. */\n\tread(userId: string): Promise<Rows>;\n\t/** The session from the verified user and its rows. Writes for the user belong here. */\n\tbuild(user: AuthUser, rows: Rows, token: string): Promise<Session> | Session;\n\t/**\n\t * How long a resolved session is reused before a request re-checks it behind its answer.\n\t * 0 (the default) keeps nothing between requests: every request resolves.\n\t */\n\tfreshForMs?: number;\n\t/** The cap on remembered sessions; the oldest go first. Default 5,000. */\n\tmaxEntries?: number;\n\t/** The token's subject, unverified: which rows to read ahead. Default: a JWT's `sub`. */\n\tsubjectOf?: (token: string) => string | null;\n\t/** The token's expiry in ms epoch, unverified. Default: a JWT's `exp`. Null: unknown. */\n\texpiresAtOf?: (token: string) => number | null;\n\t/** A background re-check that threw rather than refused. The session is kept. */\n\tonRefreshError?: (err: unknown) => void;\n\tnow?: () => number;\n}\n\nexport interface SessionResolver<Session> {\n\t/** The token's session, or null when `verify` refuses it. */\n\tresolve(token: string): Promise<Session | null>;\n\t/** Forget one token's session: after a sign-out, or a change to what it holds. */\n\tinvalidate(token: string): void;\n\t/** Forget every session of `userId`: after a change to their permissions or memberships. */\n\tinvalidateUser(userId: string): void;\n\tclear(): void;\n}\n\ninterface Entry<Session> {\n\tsession: Session;\n\tuserId: string;\n\tresolvedAt: number;\n\t/** Never answered at or past this: the token's expiry, else the end of the fresh window. */\n\tuntil: number;\n}\n\nconst DEFAULT_MAX_ENTRIES = 5_000;\n\nexport function createSessionResolver<Rows, Session>(\n\tconfig: SessionResolverConfig<Rows, Session>\n): SessionResolver<Session> {\n\tconst freshForMs = Math.max(0, config.freshForMs ?? 0);\n\tconst maxEntries = Math.max(1, config.maxEntries ?? DEFAULT_MAX_ENTRIES);\n\tconst subjectOf = config.subjectOf ?? jwtSubject;\n\tconst expiresAtOf = config.expiresAtOf ?? jwtExpiresAt;\n\tconst now = config.now ?? Date.now;\n\tconst entries = new Map<string, Entry<Session>>();\n\tconst inFlight = new Map<string, Promise<Entry<Session> | null>>();\n\n\tasync function build(token: string): Promise<Entry<Session> | null> {\n\t\tconst subject = subjectOf(token);\n\t\tconst ahead = subject ? config.read(subject) : null;\n\t\t// A token that fails verification never awaits its read-ahead.\n\t\tahead?.catch(() => {});\n\t\tconst user = await config.verify(token);\n\t\tif (!user) return null;\n\t\tconst rows = ahead && user.id === subject ? await ahead : await config.read(user.id);\n\t\tconst session = await config.build(user, rows, token);\n\t\tconst resolvedAt = now();\n\t\tconst expiresAt = expiresAtOf(token);\n\t\treturn {\n\t\t\tsession,\n\t\t\tuserId: user.id,\n\t\t\tresolvedAt,\n\t\t\tuntil: expiresAt ?? resolvedAt + freshForMs\n\t\t};\n\t}\n\n\tfunction remember(token: string, entry: Entry<Session>): void {\n\t\tif (freshForMs === 0 || entry.until <= now()) return;\n\t\tif (entries.size >= maxEntries) {\n\t\t\tconst at = now();\n\t\t\tfor (const [key, e] of entries) if (e.until <= at) entries.delete(key);\n\t\t\t// Map keeps insertion order, so the first key is the oldest.\n\t\t\twhile (entries.size >= maxEntries) entries.delete(entries.keys().next().value!);\n\t\t}\n\t\tentries.delete(token);\n\t\tentries.set(token, entry);\n\t}\n\n\tfunction start(token: string): Promise<Entry<Session> | null> {\n\t\tconst resolution = build(token).then((entry) => {\n\t\t\t// An invalidation while it ran dropped this resolution: what it read may be stale.\n\t\t\tif (inFlight.get(token) === resolution) {\n\t\t\t\tif (entry) remember(token, entry);\n\t\t\t\telse entries.delete(token);\n\t\t\t}\n\t\t\treturn entry;\n\t\t});\n\t\tinFlight.set(token, resolution);\n\t\tconst settle = () => {\n\t\t\tif (inFlight.get(token) === resolution) inFlight.delete(token);\n\t\t};\n\t\tresolution.then(settle, settle);\n\t\treturn resolution;\n\t}\n\n\treturn {\n\t\tasync resolve(token) {\n\t\t\tif (!token) return null;\n\t\t\tconst entry = entries.get(token);\n\t\t\tif (entry) {\n\t\t\t\tconst at = now();\n\t\t\t\tif (entry.until <= at) {\n\t\t\t\t\tentries.delete(token);\n\t\t\t\t} else {\n\t\t\t\t\tif (at - entry.resolvedAt >= freshForMs && !inFlight.has(token)) {\n\t\t\t\t\t\tstart(token).catch((err) => config.onRefreshError?.(err));\n\t\t\t\t\t}\n\t\t\t\t\treturn entry.session;\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst resolved = await (inFlight.get(token) ?? start(token));\n\t\t\treturn resolved?.session ?? null;\n\t\t},\n\t\tinvalidate(token) {\n\t\t\tentries.delete(token);\n\t\t\tinFlight.delete(token);\n\t\t},\n\t\tinvalidateUser(userId) {\n\t\t\tfor (const [token, entry] of entries) if (entry.userId === userId) entries.delete(token);\n\t\t\t// A resolution under way may hold the user's old rows; none of them is kept.\n\t\t\tinFlight.clear();\n\t\t},\n\t\tclear() {\n\t\t\tentries.clear();\n\t\t\tinFlight.clear();\n\t\t}\n\t};\n}\n\n// ============================================================================\n// Unverified JWT claims\n// ============================================================================\n\nfunction jwtClaims(token: string): Record<string, unknown> | null {\n\tconst parts = token.split('.');\n\tif (parts.length !== 3 || !parts[1]) return null;\n\ttry {\n\t\tconst claims = JSON.parse(Buffer.from(parts[1], 'base64url').toString('utf8'));\n\t\treturn claims && typeof claims === 'object' ? claims : null;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nfunction jwtSubject(token: string): string | null {\n\tconst sub = jwtClaims(token)?.sub;\n\treturn typeof sub === 'string' && sub ? sub : null;\n}\n\nfunction jwtExpiresAt(token: string): number | null {\n\tconst exp = jwtClaims(token)?.exp;\n\treturn typeof exp === 'number' ? exp * 1000 : null;\n}\n","/**\n * Per-request timing: where a request's wall time went, as named spans plus every outbound\n * fetch grouped by upstream. One AsyncLocalStorage store per request, opened by `timeRequest`\n * in the host's handle hook. The result goes out twice: a `Server-Timing` header on the\n * response, and one structured record through `log` for a request that is slow, sampled, or the\n * first the process served.\n *\n * Fetch time is time to response headers, not body: round-trip latency, which a chain of\n * sequential awaits multiplies. Parallel fetches overlap, so a bucket's `ms` is a sum and can\n * exceed the request's wall time.\n */\n\nimport { AsyncLocalStorage } from 'node:async_hooks';\nimport { randomUUID } from 'node:crypto';\n\n/** Which upstream a fetch reached, and optionally the table or endpoint within it. */\nexport interface Upstream {\n\tkey: string;\n\ttarget?: string;\n}\n\nexport interface TimedRequest {\n\tmethod: string;\n\t/** The route id (`/s/[token]`), so records aggregate across ids; the path when unrouted. */\n\troute: string;\n\tisDataRequest?: boolean;\n}\n\nexport interface RequestTimingOptions {\n\t/** Writes one record. Fields are typed JSON; never put payload values in them. */\n\tlog: (message: string, fields: Record<string, unknown>) => void;\n\t/** Names the upstream of a fetch; unnamed ones bucket by host. */\n\tupstream?: (url: URL) => Upstream | undefined;\n\t/** A request at or over this is logged. Default 200 ms. */\n\tslowMs?: number;\n\t/**\n\t * This share of requests is logged whatever its time, marked `sampled`: slow-only records\n\t * lean toward whatever got slower, the sampled ones compare across a change. Default 0.1.\n\t */\n\tsampleRate?: number;\n\t/** Stamped on every record, e.g. the revision; `instance` is added per process. */\n\tlabels?: Record<string, string>;\n}\n\nexport interface RequestTiming {\n\t/**\n\t * Runs one request inside a timing store, stamps `Server-Timing` on its response and logs it\n\t * when due. A throw (a framework redirect included) is logged and rethrown.\n\t */\n\ttimeRequest(req: TimedRequest, fn: () => Promise<Response>): Promise<Response>;\n\t/** Times `fn` as a named span of the current request; outside a request it just runs. */\n\tspan<T>(name: string, fn: () => Promise<T> | T): Promise<T>;\n\t/** Attaches facts to the current request's record; a no-op outside a request. */\n\tfact(facts: Record<string, unknown>): void;\n\t/** Whether the current request is the first this process served. */\n\tisCold(): boolean;\n\t/** Called once the server can take requests: the cold-start record's `bootMs`. */\n\tmarkBooted(): void;\n\t/** Wraps the global `fetch` once; clients that look it up at call time are then timed. */\n\tinstrumentFetch(): void;\n}\n\n/** `calls` holds each call's ms, for the record's per-call median and max. */\ntype Bucket = { count: number; ms: number; calls: number[] };\n\ninterface Store {\n\tspans: { name: string; ms: number }[];\n\tupstream: Map<string, Bucket>;\n\ttargets: Map<string, number>;\n\t/** Attempts a client re-sent after a failed one (`X-Retry-Count`). */\n\tretries: number;\n\tfacts: Record<string, unknown>;\n\tcold: boolean;\n}\n\nconst round = (ms: number) => Math.round(ms);\n\nfunction median(values: number[]): number {\n\tconst sorted = [...values].sort((a, b) => a - b);\n\tconst mid = sorted.length >> 1;\n\treturn sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2;\n}\n\nfunction urlOf(input: Parameters<typeof fetch>[0]): URL | undefined {\n\ttry {\n\t\treturn new URL(input instanceof Request ? input.url : String(input));\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction isRetry(init: Parameters<typeof fetch>[1]): boolean {\n\tconst headers = init?.headers;\n\tif (!headers) return false;\n\tif (headers instanceof Headers) return headers.has('x-retry-count');\n\tif (Array.isArray(headers)) return headers.some(([k]) => k.toLowerCase() === 'x-retry-count');\n\treturn Object.keys(headers).some((k) => k.toLowerCase() === 'x-retry-count');\n}\n\n/** Parses a `Server-Timing` value into `{ name: ms }`, a desc-only entry into `{ name: desc }`. */\nexport function parseServerTimingHeader(\n\theader: string | null | undefined\n): Record<string, number | string> {\n\tconst out: Record<string, number | string> = {};\n\tfor (const entry of header?.split(',') ?? []) {\n\t\tconst [name, ...params] = entry.trim().split(';');\n\t\tif (!name) continue;\n\t\tfor (const p of params) {\n\t\t\tconst [k, v = ''] = p.trim().split('=');\n\t\t\tif (k === 'dur') out[name] = round(Number(v));\n\t\t\telse if (k === 'desc' && !(name in out)) out[name] = v.replace(/^\"|\"$/g, '');\n\t\t}\n\t}\n\treturn out;\n}\n\nexport function createRequestTiming(options: RequestTimingOptions): RequestTiming {\n\tconst slowMs = options.slowMs ?? 200;\n\tconst sampleRate = options.sampleRate ?? 0.1;\n\tconst labels = { instance: randomUUID().slice(0, 8), ...options.labels };\n\tconst als = new AsyncLocalStorage<Store>();\n\tlet bootMs: number | null = null;\n\tlet served = false;\n\tlet installed = false;\n\n\tconst log = (message: string, fields: Record<string, unknown>) => {\n\t\ttry {\n\t\t\toptions.log(message, { ...labels, ...fields });\n\t\t} catch {\n\t\t\t// Telemetry never fails a request.\n\t\t}\n\t};\n\n\tfunction upstreamOf(url: URL | undefined): Upstream {\n\t\tif (!url) return { key: 'other' };\n\t\treturn options.upstream?.(url) ?? { key: url.host };\n\t}\n\n\t/** An upstream that times itself (`Server-Timing`) lands on the record by path. */\n\tfunction recordUpstreamTiming(store: Store, url: URL | undefined, response: Response): void {\n\t\tconst timing = response.headers.get('server-timing');\n\t\tif (!timing || !url) return;\n\t\tconst byPath = (store.facts.upstreamTiming as Record<string, unknown> | undefined) ?? {};\n\t\tbyPath[url.pathname] = parseServerTimingHeader(timing);\n\t\tstore.facts.upstreamTiming = byPath;\n\t}\n\n\tfunction serverTiming(store: Store, totalMs: number): string {\n\t\tconst parts = store.spans.map(\n\t\t\t(s) => `app_${s.name.replace(/[^\\w-]/g, '_')};dur=${s.ms.toFixed(1)}`\n\t\t);\n\t\tfor (const [key, b] of store.upstream) {\n\t\t\tparts.push(`up;desc=\"${key} x${b.count}\";dur=${b.ms.toFixed(1)}`);\n\t\t}\n\t\tif (store.retries > 0) parts.push(`retries;desc=\"${store.retries}\"`);\n\t\tparts.push(`app_total;dur=${totalMs.toFixed(1)}`);\n\t\treturn parts.join(', ');\n\t}\n\n\tfunction logTiming(\n\t\treq: TimedRequest,\n\t\tstatus: number | 'thrown',\n\t\ttotalMs: number,\n\t\tstore: Store,\n\t\tsampled: boolean\n\t): void {\n\t\tconst upstream = Object.fromEntries(\n\t\t\t[...store.upstream].map(([k, b]) => [\n\t\t\t\tk,\n\t\t\t\t{\n\t\t\t\t\tcount: b.count,\n\t\t\t\t\tms: round(b.ms),\n\t\t\t\t\tp50: round(median(b.calls)),\n\t\t\t\t\tmax: round(Math.max(...b.calls))\n\t\t\t\t}\n\t\t\t])\n\t\t);\n\t\t// A span name that ran more than once sums.\n\t\tconst spans: Record<string, number> = {};\n\t\tfor (const s of store.spans) spans[s.name] = round((spans[s.name] ?? 0) + s.ms);\n\t\tlog(\n\t\t\t`[timing] ${req.method} ${req.route}${req.isDataRequest ? ' (data)' : ''} ${status} ${round(totalMs)}ms`,\n\t\t\t{\n\t\t\t\ttiming: {\n\t\t\t\t\troute: req.route,\n\t\t\t\t\tmethod: req.method,\n\t\t\t\t\tdata: req.isDataRequest ?? false,\n\t\t\t\t\tstatus,\n\t\t\t\t\ttotalMs: round(totalMs),\n\t\t\t\t\t...(store.cold && { cold: true }),\n\t\t\t\t\t...(sampled && { sampled: true }),\n\t\t\t\t\tspans,\n\t\t\t\t\tupstream,\n\t\t\t\t\tcalls: Object.fromEntries(store.targets),\n\t\t\t\t\t...(store.retries > 0 && { retries: store.retries }),\n\t\t\t\t\t...store.facts\n\t\t\t\t}\n\t\t\t}\n\t\t);\n\t}\n\n\treturn {\n\t\tasync timeRequest(req, fn) {\n\t\t\tconst cold = !served;\n\t\t\tserved = true;\n\t\t\tconst store: Store = {\n\t\t\t\tspans: [],\n\t\t\t\tupstream: new Map(),\n\t\t\t\ttargets: new Map(),\n\t\t\t\tretries: 0,\n\t\t\t\tfacts: {},\n\t\t\t\tcold\n\t\t\t};\n\t\t\tconst start = performance.now();\n\t\t\tif (cold) {\n\t\t\t\t// Process start to `markBooted`, and to this request: their gap is idle time.\n\t\t\t\tlog(`[coldstart] ${req.method} ${req.route}`, {\n\t\t\t\t\tcoldstart: { bootMs, firstRequestMs: round(start), route: req.route }\n\t\t\t\t});\n\t\t\t}\n\t\t\tlet status: number | 'thrown' = 'thrown';\n\t\t\ttry {\n\t\t\t\tconst response = await als.run(store, fn);\n\t\t\t\tstatus = response.status;\n\t\t\t\ttry {\n\t\t\t\t\tresponse.headers.append('Server-Timing', serverTiming(store, performance.now() - start));\n\t\t\t\t} catch {\n\t\t\t\t\t// Immutable headers (a fetched Response passed through): the record still has it.\n\t\t\t\t}\n\t\t\t\treturn response;\n\t\t\t} finally {\n\t\t\t\tconst totalMs = performance.now() - start;\n\t\t\t\tconst sampled = Math.random() < sampleRate;\n\t\t\t\t// The cold request always: a comparison across a change must be able to drop it.\n\t\t\t\tif (cold || sampled || totalMs >= slowMs) logTiming(req, status, totalMs, store, sampled);\n\t\t\t}\n\t\t},\n\n\t\tasync span(name, fn) {\n\t\t\tconst store = als.getStore();\n\t\t\tif (!store) return fn();\n\t\t\tconst start = performance.now();\n\t\t\ttry {\n\t\t\t\treturn await fn();\n\t\t\t} finally {\n\t\t\t\tstore.spans.push({ name, ms: performance.now() - start });\n\t\t\t}\n\t\t},\n\n\t\tfact(facts) {\n\t\t\tconst store = als.getStore();\n\t\t\tif (store) Object.assign(store.facts, facts);\n\t\t},\n\n\t\tisCold: () => als.getStore()?.cold ?? false,\n\n\t\tmarkBooted() {\n\t\t\tbootMs ??= round(performance.now());\n\t\t},\n\n\t\tinstrumentFetch() {\n\t\t\tif (installed) return;\n\t\t\tinstalled = true;\n\t\t\tconst original = globalThis.fetch;\n\t\t\tglobalThis.fetch = async (input, init) => {\n\t\t\t\tconst store = als.getStore();\n\t\t\t\tif (!store) return original(input, init);\n\t\t\t\tconst start = performance.now();\n\t\t\t\tconst url = urlOf(input);\n\t\t\t\tconst { key, target } = upstreamOf(url);\n\t\t\t\tif (target) store.targets.set(target, (store.targets.get(target) ?? 0) + 1);\n\t\t\t\tif (isRetry(init)) store.retries += 1;\n\t\t\t\ttry {\n\t\t\t\t\tconst response = await original(input, init);\n\t\t\t\t\trecordUpstreamTiming(store, url, response);\n\t\t\t\t\treturn response;\n\t\t\t\t} finally {\n\t\t\t\t\tconst bucket = store.upstream.get(key) ?? { count: 0, ms: 0, calls: [] };\n\t\t\t\t\tconst ms = performance.now() - start;\n\t\t\t\t\tbucket.count += 1;\n\t\t\t\t\tbucket.ms += ms;\n\t\t\t\t\tbucket.calls.push(ms);\n\t\t\t\t\tstore.upstream.set(key, bucket);\n\t\t\t\t}\n\t\t\t};\n\t\t}\n\t};\n}\n","// Opened per request in hooks.server.ts: `Server-Timing` on every response, and a `[timing]`\n// record for a slow, sampled or cold request, with each upstream's calls.\nimport { createRequestTiming } from '@selvajs/server/http';\nimport { supabaseUpstream } from '@selvajs/supabase-provider';\nimport { env } from '#lib/server/env.js';\nimport { getLogger } from '#lib/server/providers.server.js';\n\nexport const requestTiming = createRequestTiming({\n\tlog: (message, fields) => getLogger().info(message, fields),\n\tupstream: supabaseUpstream,\n\tlabels: env.SELVA_RELEASE ? { release: env.SELVA_RELEASE } : {}\n});\nrequestTiming.instrumentFetch();\n","// App routes stay framable (embedding is what Selva-engine apps are for), but the operator\n// surfaces hold an authenticated admin session, where a framable page is a UI-redress attack.\nconst FRAME_DENIED_PREFIXES = ['/admin', '/setup', '/login', '/oauth'];\n\n/**\n * Whether a response to `pathname` must refuse framing. Kit routes on the decoded path, so\n * `/%61dmin` renders /admin: this matches what Kit matches, and a path that does not decode is\n * refused too.\n */\nexport function deniesFraming(pathname: string): boolean {\n\tlet path: string;\n\ttry {\n\t\tpath = pathname.split('%25').map(decodeURI).join('%25');\n\t} catch {\n\t\treturn true;\n\t}\n\treturn FRAME_DENIED_PREFIXES.some((p) => path === p || path.startsWith(`${p}/`));\n}\n","import { redirect, type RequestEvent } from '@sveltejs/kit';\nimport type { ServerInit } from '@sveltejs/kit/hooks';\nimport { dev } from '$app/env';\nimport { isApiError } from '@selvajs/server/api';\nimport type { AuthUser } from '@selvajs/platform';\nimport { SYSTEM_CONTEXT, emptyProfile } from '@selvajs/platform';\nimport {\n\tapplySecurityHeaders,\n\tbuildRequestContext,\n\tcreateHolderVerdictCache,\n\tcreateRouteClassifier,\n\tcreateSessionRefresher,\n\tcreateSessionResolver,\n\tisCrossSiteFormSubmission,\n\tresolveApiToken\n} from '@selvajs/server/http';\nimport { renderThrown, resolveRequestId, REQUEST_ID_HEADER } from '@selvajs/server/logging';\nimport { resolveRetentionPolicy, startRetentionJanitor } from '@selvajs/server/ops';\nimport {\n\tproviders,\n\tflag,\n\tgetErrorReporter,\n\tgetEventSink,\n\tgetLogger,\n\tgetSolveMetricSink,\n\tlazyLogger\n} from '#lib/server/providers.server.js';\nimport { signInMaxAgeMs } from '#lib/server/signInMaxAge.server.js';\nimport { apiTokenCodec, apiTokenResolutions } from '#lib/server/apiTokens/token.server.js';\nimport { MCP_FILES_PREFIX, MCP_PATH } from '#lib/server/mcp/path.js';\nimport { startStashJanitor } from '#lib/server/mcp/stash-instance.js';\nimport { readShareToken } from '#lib/server/shareLinks/resolve.server.js';\nimport { looksLikeShareToken } from '#lib/server/shareLinks/token.server.js';\nimport { requestMemo } from '#lib/server/requestMemo.server.js';\nimport { requestTiming } from '#lib/server/requestTiming.server.js';\n\nconst OAUTH_TOKEN_PATH = '/oauth/token';\nconst holderVerdicts = createHolderVerdictCache();\nlazyLogger.info('Sign-in max age', { component: 'auth', maxAgeMs: signInMaxAgeMs ?? 'off' });\nconst refreshSession = createSessionRefresher(() => providers.auth.sessionRefresh, {\n\tsignInMaxAgeMs,\n\tauth: () => providers.auth\n});\nimport { getBootHealth } from '#lib/server/bootHealth.server.js';\nimport { checkConfigAtBoot } from '#lib/server/config/boot.server.js';\nimport { env } from '#lib/server/env.js';\nimport { deniesFraming } from '#lib/server/framing.js';\nimport { publicUrl } from '#lib/server/origin.js';\nimport { closeAllSolveEventStreams } from '#lib/server/solveEvents/sse.server.js';\nimport { findDeploymentDir, startUpdateOutcomeReconciler } from '#lib/server/selfUpdate.server.js';\nimport {\n\tbootstrapUserSession,\n\thasSetupProof,\n\tidentifyWithSetupProof,\n\twireHeaderAuthBootstrap\n} from '#lib/server/auth-bootstrap.server.js';\nimport {\n\tgetRefreshToken,\n\tsetSessionCookie,\n\tsetRefreshCookie,\n\tclearRefreshCookie\n} from '#lib/server/admin-auth.server.js';\n\n// Wired lazily on first real request, not at module import, so test files\n// that import helpers from this module don't trigger provider lookups\n// before their fake providers are installed.\nlet headerAuthBootstrapWired = false;\n\n// Same lazy-on-first-request reasoning as headerAuthBootstrapWired above.\n// Result is cached in bootHealth.server.ts; `/api/health` awaits that promise.\nlet bootHealthKicked = false;\n\n// One-shot per process: a user landing on /login under forward-auth with no\n// resolved identity is the clearest \"headers didn't arrive\" signal, worth a\n// single log line rather than one per anonymous request.\nlet proxyAuthLoginMissWarned = false;\n\n// Once at server start, never in tests that import this module for `handle`.\nexport const init: ServerInit = () => {\n\tcheckConfigAtBoot();\n\trequestTiming.markBooted();\n\tstartStashJanitor();\n\t// Not in dev: Vite owns the signals there, and HMR would stack a listener per reload.\n\tif (!dev) {\n\t\tprocess.once('SIGINT', closeAllSolveEventStreams);\n\t\tprocess.once('SIGTERM', closeAllSolveEventStreams);\n\t\tprocess.once('sveltekit:shutdown', () => void exitAfterShutdown());\n\t}\n};\n\nconst SHUTDOWN_FLUSH_MS = 3000;\n\n/**\n * adapter-node closes the HTTP server on SIGINT or SIGTERM, emits this event and\n * then waits for the event loop to empty. Here it never does (limiter sweeps,\n * caches, the solve-event bus), so the process sat until pm2's kill timeout and\n * was SIGKILLed: ten seconds on every stop, restart and update, and the metric\n * sink's last batch lost. Bounded, so a dead database cannot hold the exit.\n */\nasync function exitAfterShutdown(): Promise<void> {\n\tconst sink = getSolveMetricSink() as { close?: () => Promise<void> };\n\ttry {\n\t\tawait Promise.race([\n\t\t\tsink.close?.(),\n\t\t\tnew Promise((resolve) => setTimeout(resolve, SHUTDOWN_FLUSH_MS))\n\t\t]);\n\t} catch {\n\t\t// Exiting anyway: a failed flush is not a reason to wait for the SIGKILL.\n\t} finally {\n\t\tprocess.exit(0);\n\t}\n}\n\n// One-way transition (zero users → at least one). Once true, permanent —\n// caching it skips a per-request listUsers DB read after the first user exists.\nlet firstRunResolved = false;\n\nasync function isFirstRun(): Promise<boolean> {\n\tif (firstRunResolved) return false;\n\tconst usersPage = await providers.auth.listUsers({ limit: 1 });\n\tif (usersPage === null) {\n\t\t// OIDC-only provider, no listUsers support — the setup page falls back\n\t\t// to `permissions.hasInstanceAdmin` and first-run gating doesn't apply.\n\t\tfirstRunResolved = true;\n\t\treturn false;\n\t}\n\tif (usersPage.items.length === 0) return true;\n\tfirstRunResolved = true;\n\treturn false;\n}\n\n// `ensureUser` is idempotent and rows don't disappear mid-process, so once a\n// user is ensured, subsequent requests skip the data-layer round-trip (local:\n// a full `user-data.json` read+parse) for a `Set.has` check. Per-process only —\n// a second instance just ensures the same user once itself; safe since the\n// call is idempotent.\nconst ensuredUserIds = new Set<string>();\n\nasync function ensureUserOnce(userId: string): Promise<void> {\n\tif (ensuredUserIds.has(userId)) return;\n\tawait providers.data.ensureUser(SYSTEM_CONTEXT, userId);\n\tensuredUserIds.add(userId);\n}\n\ntype SessionRows = Awaited<ReturnType<typeof readSessionRows>>;\n\ninterface Session {\n\tuser: AuthUser;\n\tprofile: App.Locals['profile'];\n\tctx: App.Locals['ctx'];\n}\n\n/**\n * Profile, platform permissions and membership: independent and keyed only by the user id, so\n * they run together as SYSTEM_CONTEXT (`ctx` isn't built yet), and for a JWT session beside\n * `verifyToken`. Reads only: they run before the token is checked.\n */\nfunction readSessionRows(userId: string) {\n\treturn Promise.all([\n\t\tproviders.data.userProfile.getProfile(SYSTEM_CONTEXT, userId),\n\t\tproviders.data.permissions.getFor(SYSTEM_CONTEXT, userId),\n\t\tproviders.data.orgs.findUserMembership(SYSTEM_CONTEXT, userId)\n\t]);\n}\n\n/**\n * The acting org is the user's first membership, or an instance admin's fallback. `ensureUser`\n * is the local equivalent of Supabase's `handle_new_auth_user` trigger, memoized per process.\n * The rows may have been read before it seeded a brand-new user's row: each fails soft to\n * empty, the correct state for a user with nothing yet.\n */\nasync function buildSession(\n\tuser: AuthUser,\n\t[profile, platformPermissions, membership]: SessionRows,\n\t// Forwarded so adapters scoping by the upstream token (Supabase RLS) get it.\n\tsessionToken: string | undefined\n): Promise<Session> {\n\tawait ensureUserOnce(user.id);\n\treturn {\n\t\tuser,\n\t\tprofile: profile ?? emptyProfile(user.id),\n\t\tctx: await buildRequestContext(\n\t\t\t{ user, sessionToken, platformPermissions, membership: membership?.member ?? null },\n\t\t\t{ orgs: providers.data.orgs }\n\t\t)\n\t};\n}\n\n// No window: every request resolves its own session, since what it holds (stars, recent\n// runs, memberships) changes under many writes that don't invalidate. Requests carrying one\n// token at once still share one resolution, and a JWT's rows are read beside its check.\nconst sessions = createSessionResolver({\n\tverify: (token) => providers.auth.verifyToken(token),\n\tread: readSessionRows,\n\tbuild: buildSession\n});\n\n/** For a user identified without a session token (forward-auth headers). */\nasync function sessionFor(user: AuthUser, sessionToken: string | undefined): Promise<Session> {\n\treturn buildSession(user, await readSessionRows(user.id), sessionToken);\n}\n\nfunction attachSession(event: RequestEvent, session: Session): void {\n\tevent.locals.user = session.user;\n\tevent.locals.profile = session.profile;\n\tevent.locals.ctx = session.ctx;\n}\n\n// ============================================================================\n// Route classification\n// ============================================================================\n//\n// Auth gating is **deny-by-default**: the classifier (mechanics in\n// `@selvajs/server/http`) gates every request unless its path matches one of\n// the allowlists below. Adding a route is safe by default — forgetting to\n// list it makes it gated (401/redirect), not silently public. Named (not\n// inlined into the classifier config) because the best-effort session attach\n// below also needs it: public *pages* get locals populated for a signed-in\n// user, public prefixes/APIs don't.\nconst PUBLIC_PAGE_ROUTES: ReadonlySet<string> = new Set([\n\t'/', // guests see the landing page; authed users get redirected by +page.server.ts\n\t'/login',\n\t'/setup',\n\t'/accept-invite'\n]);\n\nconst routeClassifier = createRouteClassifier({\n\tpublicPages: PUBLIC_PAGE_ROUTES,\n\t// `/auth/` is the OAuth start + callback flow (no session yet by\n\t// definition). `/logout` is a form action that destroys the session then\n\t// redirects. `/docs/` is the API reference — reads no tenant data, and\n\t// gating it would hide it from callers deciding whether to integrate.\n\tpublicPrefixes: ['/auth/', '/logout', '/docs/'],\n\t// Must answer without a session: load-balancer liveness probe, and the\n\t// readiness probe the post-update poller waits on across a restart. The v1\n\t// spec is public for the same reason `/docs/` is. `/mcp` gates itself: it needs a\n\t// key and passes it through to `/api/v1`, which authenticates every call.\n\t// OAuth discovery, registration and token exchange are called server-to-server\n\t// by MCP clients, with no session.\n\tpublicApis: [\n\t\t'/api/health',\n\t\t'/api/health/ready',\n\t\t'/api/v1/openapi.json',\n\t\tMCP_PATH,\n\t\t'/.well-known/oauth-protected-resource',\n\t\t'/.well-known/oauth-protected-resource/mcp',\n\t\t'/.well-known/oauth-authorization-server',\n\t\t'/oauth/register',\n\t\tOAUTH_TOKEN_PATH\n\t],\n\t// Self-gating routes authorize each request themselves; the hook must not\n\t// deny them up front. `/api/files/[...path]` classifies each path against\n\t// the asset-class registry (public branding serves to anyone, org/project\n\t// assets 401 without a session). `/api/v1/solve-events` holds the SSE stream\n\t// (requires a session, checked in the route) and the Compute callback (no\n\t// session by nature — a per-solve bearer instead). The only other route that\n\t// authorizes a request itself is `/api/v1/compute` with a share token: see\n\t// `carriesShareToken`.\n\t//\n\t// No trailing slash on solve-events: the SSE route IS that path, with the\n\t// stream in a query param, so a trailing slash would deny the stream while\n\t// letting the callback (which has a solveId segment) through.\n\t//\n\t// `/mcp/files/` serves an MCP solve's output files by an unguessable token\n\t// that expires within the hour, so a link works where the model hands it on.\n\tselfGatingPrefixes: ['/api/files/', '/api/v1/solve-events', MCP_FILES_PREFIX],\n\t// Static-asset paths SvelteKit/adapter-node serves directly.\n\tstaticPrefixes: ['/_app/', '/favicon/'],\n\tstaticPaths: ['/favicon.svg', '/robots.txt']\n});\n\n// Exported for tests: these predicates are the deny-by-default policy, and a\n// bug in either is security-relevant.\nexport const { isStaticAsset, isSelfGatingApiRoute, isPublicRoute } = routeClassifier;\n\n// The only two routes that honour a share token. A share link is meant to work\n// without an account, so a request that carries one and has no session still\n// reaches the route, which accepts or refuses the token itself. The page serves\n// only the live pointer by token: a draft or version pick still needs a session.\nconst SHARE_TOKEN_API = '/api/v1/compute';\nconst SHARE_TOKEN_PAGE = /^\\/library\\/[^/]+$/;\n\nfunction carriesShareToken(request: Request, url: URL): boolean {\n\tconst onShareRoute =\n\t\turl.pathname === SHARE_TOKEN_API ||\n\t\t(SHARE_TOKEN_PAGE.test(url.pathname) &&\n\t\t\turl.searchParams.get('channel') !== 'draft' &&\n\t\t\t!url.searchParams.has('version'));\n\treturn onShareRoute && readShareToken(request, url) !== null;\n}\n\n// Kept out of `redirectTo`: the login URL lands in access logs and browser history.\nfunction withoutShareToken(url: URL): string {\n\tconst query = new URLSearchParams(\n\t\t[...url.searchParams].filter(([key, value]) => !(key === 'token' && looksLikeShareToken(value)))\n\t).toString();\n\treturn url.pathname + (query ? `?${query}` : '');\n}\n\n// Every request runs inside its read memo, so a layout and its page share repeated reads, and\n// inside its timing store; static assets skip the timing.\nexport const handle: import('@sveltejs/kit/hooks').Handle = (input) => {\n\tconst { event } = input;\n\tconst run = () =>\n\t\trequestMemo.run(event.request.method, async () =>\n\t\t\twithRequestIdInErrorBody(await gate(input), event.url.pathname)\n\t\t);\n\tif (isStaticAsset(event.url.pathname)) return run();\n\treturn requestTiming.timeRequest(\n\t\t{\n\t\t\tmethod: event.request.method,\n\t\t\troute: event.route.id ?? event.url.pathname,\n\t\t\tisDataRequest: event.isDataRequest\n\t\t},\n\t\tasync () => run()\n\t);\n};\n\nconst gate: import('@sveltejs/kit/hooks').Handle = async ({ event, resolve }) => {\n\tevent.locals.providers = providers;\n\n\t// Bound once per request; every downstream `locals.log` record inherits\n\t// these fields. `event.url.pathname`, never `.search` — query strings carry\n\t// share tokens, and a log record outlives the token's usefulness to an attacker.\n\tconst requestId = resolveRequestId(event.request.headers);\n\tevent.locals.requestId = requestId;\n\tevent.locals.log = getLogger().child({\n\t\trequestId,\n\t\tmethod: event.request.method,\n\t\troute: event.url.pathname\n\t});\n\n\tif (!headerAuthBootstrapWired) {\n\t\twireHeaderAuthBootstrap();\n\t\theaderAuthBootstrapWired = true;\n\t}\n\n\tif (!bootHealthKicked) {\n\t\tbootHealthKicked = true;\n\t\tvoid getBootHealth();\n\t\tstartRetentionJanitor({\n\t\t\tdata: providers.data,\n\t\t\tpolicy: resolveRetentionPolicy(env),\n\t\t\tlogger: getLogger()\n\t\t});\n\t\t// Reconciles a self-update that was in flight when this process came up\n\t\t// into the audit log. No-op when no pending-update state file exists —\n\t\t// see selfUpdate.server.ts for the full lifecycle.\n\t\tconst deploymentDir = findDeploymentDir(env);\n\t\tif (deploymentDir) {\n\t\t\tstartUpdateOutcomeReconciler({\n\t\t\t\tdeploymentDir,\n\t\t\t\temit: (e) => getEventSink().emit(e),\n\t\t\t\treport: (err) => getErrorReporter().capture(err, { tags: { origin: 'selfUpdate' } })\n\t\t\t});\n\t\t}\n\t}\n\n\tconst { pathname } = event.url;\n\n\t// SvelteKit's own check is off (vite.config.ts) because it can't exempt the\n\t// token endpoint or bearer requests; this is the same check with those exemptions.\n\tif (\n\t\t!dev &&\n\t\tisCrossSiteFormSubmission(event.request, {\n\t\t\texemptPaths: [OAUTH_TOKEN_PATH],\n\t\t\torigin: publicUrl(event.url).origin\n\t\t})\n\t) {\n\t\treturn applyResponseHeaders(\n\t\t\tnew Response(`Cross-site ${event.request.method} form submissions are forbidden`, {\n\t\t\t\tstatus: 403\n\t\t\t}),\n\t\t\tpathname,\n\t\t\trequestId\n\t\t);\n\t}\n\n\t// Static assets bypass every gate below — no auth, no first-run check.\n\tif (isStaticAsset(pathname)) {\n\t\treturn applyResponseHeaders(await resolve(event), pathname, requestId);\n\t}\n\n\t// Probes answer before any gate runs — a fresh deployment with no users yet\n\t// is still live and ready, and the first-run 503 below would tell a load\n\t// balancer (or the post-update poller) the opposite.\n\tif (pathname === '/api/health' || pathname === '/api/health/ready') {\n\t\treturn applyResponseHeaders(await resolve(event), pathname, requestId);\n\t}\n\n\t// A `selva_` key decides the request on its own: it never falls back to the\n\t// cookie, so a broken key can't quietly run as whoever is signed in.\n\t// `/mcp` carries a key but isn't under `/api/v1`, so the resolver would refuse it.\n\tconst tokenResult =\n\t\tpathname === MCP_PATH\n\t\t\t? ({ kind: 'none' } as const)\n\t\t\t: await resolveApiToken(event.request, {\n\t\t\t\t\tcodec: apiTokenCodec(),\n\t\t\t\t\tauth: providers.auth,\n\t\t\t\t\tdata: providers.data,\n\t\t\t\t\tflag,\n\t\t\t\t\tholderVerdicts,\n\t\t\t\t\tsignInMaxAgeMs,\n\t\t\t\t\tresolutionCache: apiTokenResolutions,\n\t\t\t\t\tlog: event.locals.log\n\t\t\t\t});\n\tif (tokenResult.kind === 'rejected') {\n\t\tconst { status, code, message } = tokenResult;\n\t\tconst headers: Record<string, string> = { 'Content-Type': 'application/json' };\n\t\tif (status === 401) headers['WWW-Authenticate'] = 'Bearer error=\"invalid_token\"';\n\t\treturn applyResponseHeaders(\n\t\t\tnew Response(JSON.stringify({ message, code }), { status, headers }),\n\t\t\tpathname,\n\t\t\trequestId\n\t\t);\n\t}\n\tif (tokenResult.kind === 'ok') {\n\t\tconst { user, ctx, token } = tokenResult;\n\t\tevent.locals.log = event.locals.log.child({ tokenId: token.id });\n\t\tevent.locals.user = user;\n\t\tevent.locals.ctx = ctx;\n\t\tevent.locals.profile =\n\t\t\t(await providers.data.userProfile.getProfile(SYSTEM_CONTEXT, user.id)) ??\n\t\t\temptyProfile(user.id);\n\n\t\treturn applyResponseHeaders(await resolve(event), pathname, requestId);\n\t}\n\n\tconst publicRoute = isPublicRoute(pathname);\n\t// All HTTP endpoints live under `/api/*` — distinguishes 401 JSON from a\n\t// 303 redirect.\n\tconst isJsonApiRoute = pathname.startsWith('/api/');\n\n\t// On first run (no users yet), redirect non-public traffic to /setup so a\n\t// fresh deployment lands on the bootstrap flow instead of a dead login\n\t// page. Public routes pass through unchanged.\n\tif (!publicRoute) {\n\t\tif (await isFirstRun()) {\n\t\t\tif (isJsonApiRoute) {\n\t\t\t\treturn applyResponseHeaders(\n\t\t\t\t\tnew Response(JSON.stringify({ message: 'Setup required', code: 'SETUP_REQUIRED' }), {\n\t\t\t\t\t\tstatus: 503,\n\t\t\t\t\t\theaders: { 'Content-Type': 'application/json' }\n\t\t\t\t\t}),\n\t\t\t\t\tpathname,\n\t\t\t\t\trequestId\n\t\t\t\t);\n\t\t\t}\n\t\t\tredirect(303, '/setup');\n\t\t}\n\t}\n\n\t// Deny-by-default: any non-public, non-static path requires a valid session,\n\t// unless it carries a share token the route checks itself.\n\tconst needsAuth = !publicRoute;\n\tif (needsAuth) {\n\t\tlet token = event.cookies.get('admin_session') ?? '';\n\t\tlet session = await sessions.resolve(token);\n\n\t\t// When the access token expired but a refresh token is present (Supabase\n\t\t// OAuth flow), swap silently for a fresh pair and rotate the cookies.\n\t\t// Local/HMAC sessions never set a refresh cookie, so this is a no-op there.\n\t\tif (!session) {\n\t\t\tconst refreshToken = getRefreshToken(event.cookies);\n\t\t\tif (refreshToken && providers.auth.sessionRefresh) {\n\t\t\t\tconst refreshed = await refreshSession(refreshToken);\n\t\t\t\tif (refreshed) {\n\t\t\t\t\tsetSessionCookie(event.cookies, refreshed.sessionToken);\n\t\t\t\t\tsetRefreshCookie(event.cookies, refreshed.refreshToken);\n\t\t\t\t\ttoken = refreshed.sessionToken;\n\t\t\t\t\tsession = await sessions.resolve(token);\n\t\t\t\t} else {\n\t\t\t\t\t// Refresh failed — clear the stale cookie so the next request\n\t\t\t\t\t// goes through the login flow cleanly.\n\t\t\t\t\tclearRefreshCookie(event.cookies);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Forward-proxy fallback: providers that derive identity from trusted\n\t\t// upstream-proxy signals (Caddy forward_auth, oauth2-proxy, etc.) get a\n\t\t// chance to identify the request. See IProxyAuth for the trust contract.\n\t\tlet user = session?.user ?? null;\n\t\tconst proxyAuth = providers.auth.proxyAuth;\n\t\tif (!user && proxyAuth) {\n\t\t\tconst setupProven = hasSetupProof(event.cookies);\n\t\t\tuser = await identifyWithSetupProof(setupProven, () =>\n\t\t\t\tproxyAuth.identifyFromHeaders(event.request.headers)\n\t\t\t);\n\t\t\t// First-admin bootstrap for forward-auth deployments: OAuth and\n\t\t\t// email-link callbacks call `bootstrapUserSession` themselves, but the\n\t\t\t// proxy-auth path has no callback. Internally gated by `hasInstanceAdmin`\n\t\t\t// and a no-op once an admin exists, so safe on every authed request.\n\t\t\tif (user) await bootstrapUserSession(user, setupProven);\n\t\t}\n\n\t\tif (!user && carriesShareToken(event.request, event.url)) {\n\t\t\treturn applyResponseHeaders(await resolve(event), pathname, requestId);\n\t\t}\n\n\t\tif (!user) {\n\t\t\tif (isJsonApiRoute) {\n\t\t\t\treturn applyResponseHeaders(\n\t\t\t\t\tnew Response(\n\t\t\t\t\t\tJSON.stringify({\n\t\t\t\t\t\t\tmessage: 'Your session has expired. Sign in again to continue.',\n\t\t\t\t\t\t\tcode: 'UNAUTHORIZED'\n\t\t\t\t\t\t}),\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tstatus: 401,\n\t\t\t\t\t\t\theaders: { 'Content-Type': 'application/json' }\n\t\t\t\t\t\t}\n\t\t\t\t\t),\n\t\t\t\t\tpathname,\n\t\t\t\t\trequestId\n\t\t\t\t);\n\t\t\t}\n\t\t\t// With the query: an OAuth authorize request is nothing without it.\n\t\t\tredirect(303, `/login?redirectTo=${encodeURIComponent(withoutShareToken(event.url))}`);\n\t\t}\n\n\t\tattachSession(event, session ?? (await sessionFor(user, token)));\n\t} else {\n\t\t// Public page route (e.g. `/`): best-effort session attach. If a valid\n\t\t// session cookie is present, populate locals so the UI reflects authed\n\t\t// state (nav, user chip). Failure is silent — public pages keep\n\t\t// rendering for guests. Also applies to the self-gating files proxy,\n\t\t// which needs `locals.ctx` when a session is present so org/project\n\t\t// assets resolve, while still rendering guests' public branding.\n\t\tconst isPublicPage = PUBLIC_PAGE_ROUTES.has(pathname);\n\t\tconst wantsSessionAttach = isPublicPage || isSelfGatingApiRoute(pathname);\n\t\tconst token = wantsSessionAttach ? (event.cookies.get('admin_session') ?? '') : '';\n\t\tconst session = token ? await sessions.resolve(token) : null;\n\t\tlet user = session?.user ?? null;\n\t\tif (!user && wantsSessionAttach && providers.auth.proxyAuth) {\n\t\t\tuser = await providers.auth.proxyAuth.identifyFromHeaders(event.request.headers);\n\n\t\t\tif (!user && pathname === '/login' && !proxyAuthLoginMissWarned) {\n\t\t\t\tproxyAuthLoginMissWarned = true;\n\t\t\t\tconst proxyAuth = providers.auth.proxyAuth;\n\t\t\t\tconst noHeaders = proxyAuth.hasNoIdentityHeaders(event.request.headers);\n\t\t\t\tconst configured = proxyAuth.configuredHeaderNames.join(', ');\n\t\t\t\tif (noHeaders) {\n\t\t\t\t\tevent.locals.log.warn(\n\t\t\t\t\t\t'/login was hit and NONE of the configured identity headers arrived. The ' +\n\t\t\t\t\t\t\t'forward-auth proxy is not reaching this process, or is not forwarding the ' +\n\t\t\t\t\t\t\t'configured headers. See the @selvajs/header-auth-provider README ' +\n\t\t\t\t\t\t\t'\"Verification\" section.',\n\t\t\t\t\t\t{ component: 'HeaderAuth', configuredHeaders: configured }\n\t\t\t\t\t);\n\t\t\t\t} else {\n\t\t\t\t\tevent.locals.log.warn(\n\t\t\t\t\t\t'/login was hit but the UPN header was missing or the user is not allowlisted. ' +\n\t\t\t\t\t\t\t'Some headers arrived but identification still failed — check that the UPN ' +\n\t\t\t\t\t\t\t'header is populated and that the user has been added to header-allowlist.json.',\n\t\t\t\t\t\t{ component: 'HeaderAuth', configuredHeaders: configured }\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (user) attachSession(event, session ?? (await sessionFor(user, token)));\n\t}\n\n\treturn applyResponseHeaders(await resolve(event), pathname, requestId);\n};\n\n// ============================================================================\n// Response headers\n// ============================================================================\n//\n// Applied to every response — successful resolves and the 401/503\n// short-circuits above. The browser-hardening set (nosniff, Referrer-Policy,\n// Permissions-Policy, HSTS in production) lives in `@selvajs/server/http` —\n// see `applySecurityHeaders` there. Cache-control stays here: it encodes this\n// app's asset layout.\n//\n// Frame headers are the one route-dependent piece (`deniesFraming`).\n\nfunction applyResponseHeaders(response: Response, pathname: string, requestId: string): Response {\n\tapplySecurityHeaders(response, {\n\t\thsts: process.env.NODE_ENV === 'production',\n\t\tdenyFraming: deniesFraming(pathname)\n\t});\n\n\t// Echoed so a user reporting \"request X failed\" gives an operator the\n\t// exact key to grep logs with.\n\tresponse.headers.set(REQUEST_ID_HEADER, requestId);\n\n\t// Cache-control: hashed build assets are immutable; other static assets\n\t// get a short TTL.\n\tif (pathname.startsWith('/_app/')) {\n\t\tresponse.headers.set('Cache-Control', 'public, max-age=31536000, immutable');\n\t} else if (pathname.startsWith('/api/v1/') && !response.headers.has('Cache-Control')) {\n\t\t// Authenticated JSON: no intermediary may keep a copy.\n\t\tresponse.headers.set('Cache-Control', 'private, no-store');\n\t} else if (\n\t\tpathname.startsWith('/favicon/') ||\n\t\tpathname === '/favicon.svg' ||\n\t\tpathname === '/robots.txt'\n\t) {\n\t\tresponse.headers.set('Cache-Control', 'public, max-age=604800');\n\t}\n\n\treturn response;\n}\n\n/**\n * Copies the request id into an API error's JSON body, so a client that logs only the body still\n * has the id an operator greps for. The header alone is lost by most HTTP client error paths.\n */\nasync function withRequestIdInErrorBody(response: Response, pathname: string): Promise<Response> {\n\tif (response.status < 400 || !pathname.startsWith('/api/')) return response;\n\tif (!response.headers.get('Content-Type')?.includes('application/json')) return response;\n\tconst requestId = response.headers.get(REQUEST_ID_HEADER);\n\tif (!requestId) return response;\n\tlet body: unknown;\n\ttry {\n\t\tbody = await response.clone().json();\n\t} catch {\n\t\treturn response;\n\t}\n\tif (!body || typeof body !== 'object' || Array.isArray(body) || 'requestId' in body) {\n\t\treturn response;\n\t}\n\tconst headers = new Headers(response.headers);\n\theaders.delete('Content-Length');\n\treturn new Response(JSON.stringify({ ...body, requestId }), {\n\t\tstatus: response.status,\n\t\tstatusText: response.statusText,\n\t\theaders\n\t});\n}\n\nexport const handleError: import('@sveltejs/kit/hooks').HandleServerError = ({\n\tkind,\n\terror,\n\tevent\n}) => {\n\t// `error(...)` bodies already carry `code`/`fields`, so they reach the client as thrown.\n\tif (kind === 'app') return error;\n\tif (kind !== 'unknown') {\n\t\treturn error.status === 404 ? { message: 'Page not found.', code: 'NOT_FOUND' } : error;\n\t}\n\t// Backstop only. `ApiError` reaching here means a page load called a guard\n\t// without going through `asHttpError()`.\n\tif (isApiError(error)) {\n\t\treturn {\n\t\t\tstatus: error.status,\n\t\t\tmessage: error.message,\n\t\t\tcode: error.code,\n\t\t\tfields: error.fields,\n\t\t\tdetails: error.details\n\t\t};\n\t}\n\t// SvelteKit's default logging drops `cause`, which is where provider\n\t// adapters tend to stash the real reason (Supabase network error, fs\n\t// EACCES, etc.) — kept as a separate field so the message still groups\n\t// cleanly while the stack stays searchable.\n\t//\n\t// `locals.log` already carries requestId/method/route, but handleError can\n\t// fire before `handle` populates locals (a throw in an earlier hook), so\n\t// fall back to the root logger and re-state the fields.\n\tconst log =\n\t\tevent.locals.log ??\n\t\tgetLogger().child({ method: event.request.method, route: event.url.pathname });\n\tlog.error('Unhandled error', {\n\t\tcomponent: 'handleError',\n\t\terr: renderThrown(error),\n\t\tcause: error instanceof Error && error.cause ? String(error.cause) : undefined\n\t});\n\t// Only reached for genuinely unexpected errors — intentional HTTP outcomes\n\t// (incl. the compute route's `apiError(500)` on a failed solve) are\n\t// `HttpError`s handled above. No-op unless SENTRY_DSN is configured.\n\tgetErrorReporter().capture(error, {\n\t\tmethod: event.request.method,\n\t\troute: event.url.pathname,\n\t\tuserId: event.locals.ctx?.userId || undefined,\n\t\torgId: event.locals.ctx?.actingOrgId\n\t});\n\treturn { message: 'An unexpected error occurred.', code: 'INTERNAL' };\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAMA,IAAM,WAA6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../../../../server/src/http/security-headers.ts","../../../../server/src/http/route-classifier.ts","../../../../server/src/http/session-resolver.ts","../../../../server/src/http/request-timing.ts","../../../src/lib/server/requestTiming.server.ts","../../../src/lib/server/framing.ts","../../../src/hooks.server.ts"],"sourcesContent":["/**\n * Supabase serves every API under one origin; the path prefix names the service. For a\n * request-timing classifier (`createRequestTiming` in `@selvajs/server/http`): `db`, `auth` or\n * `storage`, and for the database the table or RPC a call reached (`db jobs`, `db rpc/x`).\n */\n\nconst SERVICES: [prefix: string, name: string][] = [\n\t['/rest/v1/', 'db'],\n\t['/auth/v1/', 'auth'],\n\t['/storage/v1/', 'storage']\n];\n\nexport function supabaseUpstream(url: URL): { key: string; target: string } | undefined {\n\tconst service = SERVICES.find(([prefix]) => url.pathname.startsWith(prefix));\n\tif (!service) return undefined;\n\tconst [first = '', second = ''] = url.pathname.slice(service[0].length).split('/');\n\treturn { key: service[1], target: `${service[1]} ${first === 'rpc' ? `rpc/${second}` : first}` };\n}\n","export interface SecurityHeaderOptions {\n\t/**\n\t * Set `Strict-Transport-Security`. Production only — pinning\n\t * http://localhost to HTTPS bricks local development. The caller decides\n\t * what \"production\" means (e.g. `NODE_ENV`).\n\t */\n\thsts: boolean;\n\t/**\n\t * Forbid framing this response. Off by default — Selva-engine app routes are\n\t * built to be embedded. Turn it on for operator surfaces (`/admin/*`,\n\t * `/setup`), where an authenticated session plus a framable page is a\n\t * UI-redress attack. `SameSite=Lax` blunts cross-site POST, not same-origin\n\t * redress, so the cookie flag is not a substitute.\n\t */\n\tdenyFraming?: boolean;\n}\n\n/**\n * Apply baseline browser-hardening headers to a response and return it for\n * chaining. Each is a cheap win that needs no UI verification:\n *\n * - X-Content-Type-Options: nosniff — disables MIME sniffing.\n * - Referrer-Policy: strict-origin-when-cross-origin — strips path and query\n * from cross-origin Referer headers. Matches modern browser defaults, but\n * pins the behavior in case a default drifts.\n * - Permissions-Policy: opts out of browser APIs Selva-engine apps don't use,\n * so XSS can't enable them.\n * - HSTS when `opts.hsts`.\n * - X-Frame-Options + `frame-ancestors 'none'` when `opts.denyFraming` — the\n * caller opts in per route, since embeddable app routes must stay framable.\n *\n * **Intentionally NOT set here:**\n * - A full Content-Security-Policy. Selva-engine apps are built for iframe\n * embedding, so a strict CSP needs validating against real consumer sites\n * before it can ship. `denyFraming` sets only the `frame-ancestors`\n * directive, which constrains nothing else the page loads.\n * - Cache-Control. Asset-path layout is app policy; set it in the caller.\n */\nexport function applySecurityHeaders(response: Response, opts: SecurityHeaderOptions): Response {\n\tresponse.headers.set('X-Content-Type-Options', 'nosniff');\n\tresponse.headers.set('Referrer-Policy', 'strict-origin-when-cross-origin');\n\tresponse.headers.set(\n\t\t'Permissions-Policy',\n\t\t'accelerometer=(), camera=(), geolocation=(), gyroscope=(), magnetometer=(), microphone=(), payment=(), usb=()'\n\t);\n\tif (opts.hsts) {\n\t\tresponse.headers.set('Strict-Transport-Security', 'max-age=31536000; includeSubDomains');\n\t}\n\tif (opts.denyFraming) {\n\t\tresponse.headers.set('X-Frame-Options', 'DENY');\n\t\tresponse.headers.set('Content-Security-Policy', \"frame-ancestors 'none'\");\n\t}\n\treturn response;\n}\n","/**\n * Deny-by-default route classification. A request is gated unless its path\n * matches one of the allowlists supplied here, so forgetting to list a new\n * route makes it gated — a loud 401/redirect, not silently public.\n *\n * The pattern is reusable; the values are app policy, supplied by the consuming\n * app. Matching is plain exact/prefix string comparison: cheap enough for the\n * hooks hot path, and no regex to get wrong.\n */\n\nexport interface RouteClassifierConfig {\n\t/** Exact-match pages needing no session (e.g. `/`, `/login`). */\n\tpublicPages?: Iterable<string>;\n\t/** Public path prefixes (e.g. `/auth/` — OAuth start and callback precede any session). */\n\tpublicPrefixes?: readonly string[];\n\t/**\n\t * Exact-match API endpoints that answer without a session (e.g. a\n\t * load-balancer health probe). Anything listed here is exposed to anonymous\n\t * callers.\n\t */\n\tpublicApis?: Iterable<string>;\n\t/**\n\t * Prefixes whose routes authorize each request themselves (e.g. a blob\n\t * proxy classifying per asset path, or a callback authenticated by a\n\t * per-request bearer). These classify as public so the hook attaches a\n\t * session best-effort and does not deny up front; the route makes the real\n\t * decision. Keep the list short — every other API route stays deny-by-default.\n\t */\n\tselfGatingPrefixes?: readonly string[];\n\t/** Single-prefix form of `selfGatingPrefixes`. */\n\tselfGatingPrefix?: string;\n\t/** Static-asset prefixes the adapter serves directly (e.g. `/_app/`). */\n\tstaticPrefixes?: readonly string[];\n\t/** Exact static-asset paths (e.g. `/favicon.svg`, `/robots.txt`). */\n\tstaticPaths?: Iterable<string>;\n}\n\nexport interface RouteClassifier {\n\t/** Matches `staticPaths`/`staticPrefixes`. These bypass auth gating entirely. */\n\tisStaticAsset(pathname: string): boolean;\n\t/** Matches `selfGatingPrefix`. The hook must not deny these — the route gates itself. */\n\tisSelfGatingApiRoute(pathname: string): boolean;\n\t/** Needs no session: a public page, API, prefix, or a self-gating route. */\n\tisPublicRoute(pathname: string): boolean;\n}\n\nexport function createRouteClassifier(config: RouteClassifierConfig): RouteClassifier {\n\tconst publicPages = new Set(config.publicPages ?? []);\n\tconst publicPrefixes = config.publicPrefixes ?? [];\n\tconst publicApis = new Set(config.publicApis ?? []);\n\tconst selfGatingPrefixes = [\n\t\t...(config.selfGatingPrefixes ?? []),\n\t\t...(config.selfGatingPrefix !== undefined ? [config.selfGatingPrefix] : [])\n\t];\n\tconst staticPrefixes = config.staticPrefixes ?? [];\n\tconst staticPaths = new Set(config.staticPaths ?? []);\n\n\tfunction isStaticAsset(pathname: string): boolean {\n\t\tif (staticPaths.has(pathname)) return true;\n\t\treturn staticPrefixes.some((p) => pathname.startsWith(p));\n\t}\n\n\tfunction isSelfGatingApiRoute(pathname: string): boolean {\n\t\treturn selfGatingPrefixes.some((p) => pathname.startsWith(p));\n\t}\n\n\tfunction isPublicRoute(pathname: string): boolean {\n\t\tif (publicPages.has(pathname)) return true;\n\t\tif (publicApis.has(pathname)) return true;\n\t\tif (isSelfGatingApiRoute(pathname)) return true;\n\t\treturn publicPrefixes.some((p) => pathname.startsWith(p));\n\t}\n\n\treturn { isStaticAsset, isSelfGatingApiRoute, isPublicRoute };\n}\n","/**\n * Turns a session token into whatever a host attaches to a request, with the round trips that\n * cost cut to what the token needs.\n *\n * - The user's rows are read beside `verify`, keyed by the token's unverified subject, and kept\n * only when `verify` confirms that same user. `read` must be a read: it runs before the token\n * is checked, so it must not write anything for the subject it is handed.\n * - Requests carrying one token share one resolution while it runs.\n * - With `freshForMs`, a resolved session is reused for that long. Past it the session is still\n * answered, and resolved again behind the request; a re-check that refuses the token drops it,\n * so after a sign-out or disable the requests already in flight are the last to get through.\n * A session is never answered past its token's expiry, so row security never sees an expired\n * token mid-request.\n */\n\nimport type { AuthUser } from '@selvajs/platform';\n\nexport interface SessionResolverConfig<Rows, Session> {\n\t/** The token's user, or null for a token it refuses. */\n\tverify(token: string): Promise<AuthUser | null>;\n\t/** Everything the session needs that is keyed by the user id alone. Never a write. */\n\tread(userId: string): Promise<Rows>;\n\t/** The session from the verified user and its rows. Writes for the user belong here. */\n\tbuild(user: AuthUser, rows: Rows, token: string): Promise<Session> | Session;\n\t/**\n\t * How long a resolved session is reused before a request re-checks it behind its answer.\n\t * 0 (the default) keeps nothing between requests: every request resolves.\n\t */\n\tfreshForMs?: number;\n\t/** The cap on remembered sessions; the oldest go first. Default 5,000. */\n\tmaxEntries?: number;\n\t/** The token's subject, unverified: which rows to read ahead. Default: a JWT's `sub`. */\n\tsubjectOf?: (token: string) => string | null;\n\t/** The token's expiry in ms epoch, unverified. Default: a JWT's `exp`. Null: unknown. */\n\texpiresAtOf?: (token: string) => number | null;\n\t/** A background re-check that threw rather than refused. The session is kept. */\n\tonRefreshError?: (err: unknown) => void;\n\tnow?: () => number;\n}\n\nexport interface SessionResolver<Session> {\n\t/** The token's session, or null when `verify` refuses it. */\n\tresolve(token: string): Promise<Session | null>;\n\t/** Forget one token's session: after a sign-out, or a change to what it holds. */\n\tinvalidate(token: string): void;\n\t/** Forget every session of `userId`: after a change to their permissions or memberships. */\n\tinvalidateUser(userId: string): void;\n\tclear(): void;\n}\n\ninterface Entry<Session> {\n\tsession: Session;\n\tuserId: string;\n\tresolvedAt: number;\n\t/** Never answered at or past this: the token's expiry, else the end of the fresh window. */\n\tuntil: number;\n}\n\nconst DEFAULT_MAX_ENTRIES = 5_000;\n\nexport function createSessionResolver<Rows, Session>(\n\tconfig: SessionResolverConfig<Rows, Session>\n): SessionResolver<Session> {\n\tconst freshForMs = Math.max(0, config.freshForMs ?? 0);\n\tconst maxEntries = Math.max(1, config.maxEntries ?? DEFAULT_MAX_ENTRIES);\n\tconst subjectOf = config.subjectOf ?? jwtSubject;\n\tconst expiresAtOf = config.expiresAtOf ?? jwtExpiresAt;\n\tconst now = config.now ?? Date.now;\n\tconst entries = new Map<string, Entry<Session>>();\n\tconst inFlight = new Map<string, Promise<Entry<Session> | null>>();\n\n\tasync function build(token: string): Promise<Entry<Session> | null> {\n\t\tconst subject = subjectOf(token);\n\t\tconst ahead = subject ? config.read(subject) : null;\n\t\t// A token that fails verification never awaits its read-ahead.\n\t\tahead?.catch(() => {});\n\t\tconst user = await config.verify(token);\n\t\tif (!user) return null;\n\t\tconst rows = ahead && user.id === subject ? await ahead : await config.read(user.id);\n\t\tconst session = await config.build(user, rows, token);\n\t\tconst resolvedAt = now();\n\t\tconst expiresAt = expiresAtOf(token);\n\t\treturn {\n\t\t\tsession,\n\t\t\tuserId: user.id,\n\t\t\tresolvedAt,\n\t\t\tuntil: expiresAt ?? resolvedAt + freshForMs\n\t\t};\n\t}\n\n\tfunction remember(token: string, entry: Entry<Session>): void {\n\t\tif (freshForMs === 0 || entry.until <= now()) return;\n\t\tif (entries.size >= maxEntries) {\n\t\t\tconst at = now();\n\t\t\tfor (const [key, e] of entries) if (e.until <= at) entries.delete(key);\n\t\t\t// Map keeps insertion order, so the first key is the oldest.\n\t\t\twhile (entries.size >= maxEntries) entries.delete(entries.keys().next().value!);\n\t\t}\n\t\tentries.delete(token);\n\t\tentries.set(token, entry);\n\t}\n\n\tfunction start(token: string): Promise<Entry<Session> | null> {\n\t\tconst resolution = build(token).then((entry) => {\n\t\t\t// An invalidation while it ran dropped this resolution: what it read may be stale.\n\t\t\tif (inFlight.get(token) === resolution) {\n\t\t\t\tif (entry) remember(token, entry);\n\t\t\t\telse entries.delete(token);\n\t\t\t}\n\t\t\treturn entry;\n\t\t});\n\t\tinFlight.set(token, resolution);\n\t\tconst settle = () => {\n\t\t\tif (inFlight.get(token) === resolution) inFlight.delete(token);\n\t\t};\n\t\tresolution.then(settle, settle);\n\t\treturn resolution;\n\t}\n\n\treturn {\n\t\tasync resolve(token) {\n\t\t\tif (!token) return null;\n\t\t\tconst entry = entries.get(token);\n\t\t\tif (entry) {\n\t\t\t\tconst at = now();\n\t\t\t\tif (entry.until <= at) {\n\t\t\t\t\tentries.delete(token);\n\t\t\t\t} else {\n\t\t\t\t\tif (at - entry.resolvedAt >= freshForMs && !inFlight.has(token)) {\n\t\t\t\t\t\tstart(token).catch((err) => config.onRefreshError?.(err));\n\t\t\t\t\t}\n\t\t\t\t\treturn entry.session;\n\t\t\t\t}\n\t\t\t}\n\t\t\tconst resolved = await (inFlight.get(token) ?? start(token));\n\t\t\treturn resolved?.session ?? null;\n\t\t},\n\t\tinvalidate(token) {\n\t\t\tentries.delete(token);\n\t\t\tinFlight.delete(token);\n\t\t},\n\t\tinvalidateUser(userId) {\n\t\t\tfor (const [token, entry] of entries) if (entry.userId === userId) entries.delete(token);\n\t\t\t// A resolution under way may hold the user's old rows; none of them is kept.\n\t\t\tinFlight.clear();\n\t\t},\n\t\tclear() {\n\t\t\tentries.clear();\n\t\t\tinFlight.clear();\n\t\t}\n\t};\n}\n\n// ============================================================================\n// Unverified JWT claims\n// ============================================================================\n\nfunction jwtClaims(token: string): Record<string, unknown> | null {\n\tconst parts = token.split('.');\n\tif (parts.length !== 3 || !parts[1]) return null;\n\ttry {\n\t\tconst claims = JSON.parse(Buffer.from(parts[1], 'base64url').toString('utf8'));\n\t\treturn claims && typeof claims === 'object' ? claims : null;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nfunction jwtSubject(token: string): string | null {\n\tconst sub = jwtClaims(token)?.sub;\n\treturn typeof sub === 'string' && sub ? sub : null;\n}\n\nfunction jwtExpiresAt(token: string): number | null {\n\tconst exp = jwtClaims(token)?.exp;\n\treturn typeof exp === 'number' ? exp * 1000 : null;\n}\n","/**\n * Per-request timing: where a request's wall time went, as named spans plus every outbound\n * fetch grouped by upstream. One AsyncLocalStorage store per request, opened by `timeRequest`\n * in the host's handle hook. The result goes out twice: a `Server-Timing` header on the\n * response, and one structured record through `log` for a request that is slow, sampled, or the\n * first the process served.\n *\n * Fetch time is time to response headers, not body: round-trip latency, which a chain of\n * sequential awaits multiplies. Parallel fetches overlap, so a bucket's `ms` is a sum and can\n * exceed the request's wall time.\n */\n\nimport { AsyncLocalStorage } from 'node:async_hooks';\nimport { randomUUID } from 'node:crypto';\n\n/** Which upstream a fetch reached, and optionally the table or endpoint within it. */\nexport interface Upstream {\n\tkey: string;\n\ttarget?: string;\n}\n\nexport interface TimedRequest {\n\tmethod: string;\n\t/** The route id (`/s/[token]`), so records aggregate across ids; the path when unrouted. */\n\troute: string;\n\tisDataRequest?: boolean;\n}\n\nexport interface RequestTimingOptions {\n\t/** Writes one record. Fields are typed JSON; never put payload values in them. */\n\tlog: (message: string, fields: Record<string, unknown>) => void;\n\t/** Names the upstream of a fetch; unnamed ones bucket by host. */\n\tupstream?: (url: URL) => Upstream | undefined;\n\t/** A request at or over this is logged. Default 200 ms. */\n\tslowMs?: number;\n\t/**\n\t * This share of requests is logged whatever its time, marked `sampled`: slow-only records\n\t * lean toward whatever got slower, the sampled ones compare across a change. Default 0.1.\n\t */\n\tsampleRate?: number;\n\t/** Stamped on every record, e.g. the revision; `instance` is added per process. */\n\tlabels?: Record<string, string>;\n}\n\nexport interface RequestTiming {\n\t/**\n\t * Runs one request inside a timing store, stamps `Server-Timing` on its response and logs it\n\t * when due. A throw (a framework redirect included) is logged and rethrown.\n\t */\n\ttimeRequest(req: TimedRequest, fn: () => Promise<Response>): Promise<Response>;\n\t/** Times `fn` as a named span of the current request; outside a request it just runs. */\n\tspan<T>(name: string, fn: () => Promise<T> | T): Promise<T>;\n\t/** Attaches facts to the current request's record; a no-op outside a request. */\n\tfact(facts: Record<string, unknown>): void;\n\t/** Whether the current request is the first this process served. */\n\tisCold(): boolean;\n\t/** Called once the server can take requests: the cold-start record's `bootMs`. */\n\tmarkBooted(): void;\n\t/** Wraps the global `fetch` once; clients that look it up at call time are then timed. */\n\tinstrumentFetch(): void;\n}\n\n/** `calls` holds each call's ms, for the record's per-call median and max. */\ntype Bucket = { count: number; ms: number; calls: number[] };\n\ninterface Store {\n\tspans: { name: string; ms: number }[];\n\tupstream: Map<string, Bucket>;\n\ttargets: Map<string, number>;\n\t/** Attempts a client re-sent after a failed one (`X-Retry-Count`). */\n\tretries: number;\n\tfacts: Record<string, unknown>;\n\tcold: boolean;\n}\n\nconst round = (ms: number) => Math.round(ms);\n\nfunction median(values: number[]): number {\n\tconst sorted = [...values].sort((a, b) => a - b);\n\tconst mid = sorted.length >> 1;\n\treturn sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2;\n}\n\nfunction urlOf(input: Parameters<typeof fetch>[0]): URL | undefined {\n\ttry {\n\t\treturn new URL(input instanceof Request ? input.url : String(input));\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\nfunction isRetry(init: Parameters<typeof fetch>[1]): boolean {\n\tconst headers = init?.headers;\n\tif (!headers) return false;\n\tif (headers instanceof Headers) return headers.has('x-retry-count');\n\tif (Array.isArray(headers)) return headers.some(([k]) => k.toLowerCase() === 'x-retry-count');\n\treturn Object.keys(headers).some((k) => k.toLowerCase() === 'x-retry-count');\n}\n\n/** Parses a `Server-Timing` value into `{ name: ms }`, a desc-only entry into `{ name: desc }`. */\nexport function parseServerTimingHeader(\n\theader: string | null | undefined\n): Record<string, number | string> {\n\tconst out: Record<string, number | string> = {};\n\tfor (const entry of header?.split(',') ?? []) {\n\t\tconst [name, ...params] = entry.trim().split(';');\n\t\tif (!name) continue;\n\t\tfor (const p of params) {\n\t\t\tconst [k, v = ''] = p.trim().split('=');\n\t\t\tif (k === 'dur') out[name] = round(Number(v));\n\t\t\telse if (k === 'desc' && !(name in out)) out[name] = v.replace(/^\"|\"$/g, '');\n\t\t}\n\t}\n\treturn out;\n}\n\nexport function createRequestTiming(options: RequestTimingOptions): RequestTiming {\n\tconst slowMs = options.slowMs ?? 200;\n\tconst sampleRate = options.sampleRate ?? 0.1;\n\tconst labels = { instance: randomUUID().slice(0, 8), ...options.labels };\n\tconst als = new AsyncLocalStorage<Store>();\n\tlet bootMs: number | null = null;\n\tlet served = false;\n\tlet installed = false;\n\n\tconst log = (message: string, fields: Record<string, unknown>) => {\n\t\ttry {\n\t\t\toptions.log(message, { ...labels, ...fields });\n\t\t} catch {\n\t\t\t// Telemetry never fails a request.\n\t\t}\n\t};\n\n\tfunction upstreamOf(url: URL | undefined): Upstream {\n\t\tif (!url) return { key: 'other' };\n\t\treturn options.upstream?.(url) ?? { key: url.host };\n\t}\n\n\t/** An upstream that times itself (`Server-Timing`) lands on the record by path. */\n\tfunction recordUpstreamTiming(store: Store, url: URL | undefined, response: Response): void {\n\t\tconst timing = response.headers.get('server-timing');\n\t\tif (!timing || !url) return;\n\t\tconst byPath = (store.facts.upstreamTiming as Record<string, unknown> | undefined) ?? {};\n\t\tbyPath[url.pathname] = parseServerTimingHeader(timing);\n\t\tstore.facts.upstreamTiming = byPath;\n\t}\n\n\tfunction serverTiming(store: Store, totalMs: number): string {\n\t\tconst parts = store.spans.map(\n\t\t\t(s) => `app_${s.name.replace(/[^\\w-]/g, '_')};dur=${s.ms.toFixed(1)}`\n\t\t);\n\t\tfor (const [key, b] of store.upstream) {\n\t\t\tparts.push(`up;desc=\"${key} x${b.count}\";dur=${b.ms.toFixed(1)}`);\n\t\t}\n\t\tif (store.retries > 0) parts.push(`retries;desc=\"${store.retries}\"`);\n\t\tparts.push(`app_total;dur=${totalMs.toFixed(1)}`);\n\t\treturn parts.join(', ');\n\t}\n\n\tfunction logTiming(\n\t\treq: TimedRequest,\n\t\tstatus: number | 'thrown',\n\t\ttotalMs: number,\n\t\tstore: Store,\n\t\tsampled: boolean\n\t): void {\n\t\tconst upstream = Object.fromEntries(\n\t\t\t[...store.upstream].map(([k, b]) => [\n\t\t\t\tk,\n\t\t\t\t{\n\t\t\t\t\tcount: b.count,\n\t\t\t\t\tms: round(b.ms),\n\t\t\t\t\tp50: round(median(b.calls)),\n\t\t\t\t\tmax: round(Math.max(...b.calls))\n\t\t\t\t}\n\t\t\t])\n\t\t);\n\t\t// A span name that ran more than once sums.\n\t\tconst spans: Record<string, number> = {};\n\t\tfor (const s of store.spans) spans[s.name] = round((spans[s.name] ?? 0) + s.ms);\n\t\tlog(\n\t\t\t`[timing] ${req.method} ${req.route}${req.isDataRequest ? ' (data)' : ''} ${status} ${round(totalMs)}ms`,\n\t\t\t{\n\t\t\t\ttiming: {\n\t\t\t\t\troute: req.route,\n\t\t\t\t\tmethod: req.method,\n\t\t\t\t\tdata: req.isDataRequest ?? false,\n\t\t\t\t\tstatus,\n\t\t\t\t\ttotalMs: round(totalMs),\n\t\t\t\t\t...(store.cold && { cold: true }),\n\t\t\t\t\t...(sampled && { sampled: true }),\n\t\t\t\t\tspans,\n\t\t\t\t\tupstream,\n\t\t\t\t\tcalls: Object.fromEntries(store.targets),\n\t\t\t\t\t...(store.retries > 0 && { retries: store.retries }),\n\t\t\t\t\t...store.facts\n\t\t\t\t}\n\t\t\t}\n\t\t);\n\t}\n\n\treturn {\n\t\tasync timeRequest(req, fn) {\n\t\t\tconst cold = !served;\n\t\t\tserved = true;\n\t\t\tconst store: Store = {\n\t\t\t\tspans: [],\n\t\t\t\tupstream: new Map(),\n\t\t\t\ttargets: new Map(),\n\t\t\t\tretries: 0,\n\t\t\t\tfacts: {},\n\t\t\t\tcold\n\t\t\t};\n\t\t\tconst start = performance.now();\n\t\t\tif (cold) {\n\t\t\t\t// Process start to `markBooted`, and to this request: their gap is idle time.\n\t\t\t\tlog(`[coldstart] ${req.method} ${req.route}`, {\n\t\t\t\t\tcoldstart: { bootMs, firstRequestMs: round(start), route: req.route }\n\t\t\t\t});\n\t\t\t}\n\t\t\tlet status: number | 'thrown' = 'thrown';\n\t\t\ttry {\n\t\t\t\tconst response = await als.run(store, fn);\n\t\t\t\tstatus = response.status;\n\t\t\t\ttry {\n\t\t\t\t\tresponse.headers.append('Server-Timing', serverTiming(store, performance.now() - start));\n\t\t\t\t} catch {\n\t\t\t\t\t// Immutable headers (a fetched Response passed through): the record still has it.\n\t\t\t\t}\n\t\t\t\treturn response;\n\t\t\t} finally {\n\t\t\t\tconst totalMs = performance.now() - start;\n\t\t\t\tconst sampled = Math.random() < sampleRate;\n\t\t\t\t// The cold request always: a comparison across a change must be able to drop it.\n\t\t\t\tif (cold || sampled || totalMs >= slowMs) logTiming(req, status, totalMs, store, sampled);\n\t\t\t}\n\t\t},\n\n\t\tasync span(name, fn) {\n\t\t\tconst store = als.getStore();\n\t\t\tif (!store) return fn();\n\t\t\tconst start = performance.now();\n\t\t\ttry {\n\t\t\t\treturn await fn();\n\t\t\t} finally {\n\t\t\t\tstore.spans.push({ name, ms: performance.now() - start });\n\t\t\t}\n\t\t},\n\n\t\tfact(facts) {\n\t\t\tconst store = als.getStore();\n\t\t\tif (store) Object.assign(store.facts, facts);\n\t\t},\n\n\t\tisCold: () => als.getStore()?.cold ?? false,\n\n\t\tmarkBooted() {\n\t\t\tbootMs ??= round(performance.now());\n\t\t},\n\n\t\tinstrumentFetch() {\n\t\t\tif (installed) return;\n\t\t\tinstalled = true;\n\t\t\tconst original = globalThis.fetch;\n\t\t\tglobalThis.fetch = async (input, init) => {\n\t\t\t\tconst store = als.getStore();\n\t\t\t\tif (!store) return original(input, init);\n\t\t\t\tconst start = performance.now();\n\t\t\t\tconst url = urlOf(input);\n\t\t\t\tconst { key, target } = upstreamOf(url);\n\t\t\t\tif (target) store.targets.set(target, (store.targets.get(target) ?? 0) + 1);\n\t\t\t\tif (isRetry(init)) store.retries += 1;\n\t\t\t\ttry {\n\t\t\t\t\tconst response = await original(input, init);\n\t\t\t\t\trecordUpstreamTiming(store, url, response);\n\t\t\t\t\treturn response;\n\t\t\t\t} finally {\n\t\t\t\t\tconst bucket = store.upstream.get(key) ?? { count: 0, ms: 0, calls: [] };\n\t\t\t\t\tconst ms = performance.now() - start;\n\t\t\t\t\tbucket.count += 1;\n\t\t\t\t\tbucket.ms += ms;\n\t\t\t\t\tbucket.calls.push(ms);\n\t\t\t\t\tstore.upstream.set(key, bucket);\n\t\t\t\t}\n\t\t\t};\n\t\t}\n\t};\n}\n","// Opened per request in hooks.server.ts: `Server-Timing` on every response, and a `[timing]`\n// record for a slow, sampled or cold request, with each upstream's calls.\nimport { createRequestTiming } from '@selvajs/server/http';\nimport { supabaseUpstream } from '@selvajs/supabase-provider';\nimport { env } from '#lib/server/env.js';\nimport { getLogger } from '#lib/server/providers.server.js';\n\nexport const requestTiming = createRequestTiming({\n\tlog: (message, fields) => getLogger().info(message, fields),\n\tupstream: supabaseUpstream,\n\tlabels: env.SELVA_RELEASE ? { release: env.SELVA_RELEASE } : {}\n});\nrequestTiming.instrumentFetch();\n","// App routes stay framable (embedding is what Selva-engine apps are for), but the operator\n// surfaces hold an authenticated admin session, where a framable page is a UI-redress attack.\nconst FRAME_DENIED_PREFIXES = ['/admin', '/setup', '/login', '/oauth'];\n\n/**\n * Whether a response to `pathname` must refuse framing. Kit routes on the decoded path, so\n * `/%61dmin` renders /admin: this matches what Kit matches, and a path that does not decode is\n * refused too.\n */\nexport function deniesFraming(pathname: string): boolean {\n\tlet path: string;\n\ttry {\n\t\tpath = pathname.split('%25').map(decodeURI).join('%25');\n\t} catch {\n\t\treturn true;\n\t}\n\treturn FRAME_DENIED_PREFIXES.some((p) => path === p || path.startsWith(`${p}/`));\n}\n","import { redirect, type RequestEvent } from '@sveltejs/kit';\nimport type { ServerInit } from '@sveltejs/kit/hooks';\nimport { dev } from '$app/env';\nimport { isApiError } from '@selvajs/server/api';\nimport type { AuthUser } from '@selvajs/platform';\nimport { SYSTEM_CONTEXT, emptyProfile } from '@selvajs/platform';\nimport {\n\tapplySecurityHeaders,\n\tbuildRequestContext,\n\tcreateHolderVerdictCache,\n\tcreateRouteClassifier,\n\tcreateSessionRefresher,\n\tcreateSessionResolver,\n\tisCrossSiteFormSubmission,\n\tresolveApiToken\n} from '@selvajs/server/http';\nimport { renderThrown, resolveRequestId, REQUEST_ID_HEADER } from '@selvajs/server/logging';\nimport { resolveRetentionPolicy, startRetentionJanitor } from '@selvajs/server/ops';\nimport {\n\tproviders,\n\tflag,\n\tgetErrorReporter,\n\tgetEventSink,\n\tgetLogger,\n\tgetSolveMetricSink,\n\tlazyLogger\n} from '#lib/server/providers.server.js';\nimport { signInMaxAgeMs } from '#lib/server/signInMaxAge.server.js';\nimport { apiTokenCodec, apiTokenResolutions } from '#lib/server/apiTokens/token.server.js';\nimport { MCP_FILES_PREFIX, MCP_PATH } from '#lib/server/mcp/path.js';\nimport { startStashJanitor } from '#lib/server/mcp/stash-instance.js';\nimport { readShareToken } from '#lib/server/shareLinks/resolve.server.js';\nimport { looksLikeShareToken } from '#lib/server/shareLinks/token.server.js';\nimport { requestMemo } from '#lib/server/requestMemo.server.js';\nimport { requestTiming } from '#lib/server/requestTiming.server.js';\n\nconst OAUTH_TOKEN_PATH = '/oauth/token';\nconst holderVerdicts = createHolderVerdictCache();\nlazyLogger.info('Sign-in max age', { component: 'auth', maxAgeMs: signInMaxAgeMs ?? 'off' });\nconst refreshSession = createSessionRefresher(() => providers.auth.sessionRefresh, {\n\tsignInMaxAgeMs,\n\tauth: () => providers.auth\n});\nimport { getBootHealth } from '#lib/server/bootHealth.server.js';\nimport { checkConfigAtBoot } from '#lib/server/config/boot.server.js';\nimport { env } from '#lib/server/env.js';\nimport { deniesFraming } from '#lib/server/framing.js';\nimport { publicUrl } from '#lib/server/origin.js';\nimport { closeAllSolveEventStreams } from '#lib/server/solveEvents/sse.server.js';\nimport { findDeploymentDir, startUpdateOutcomeReconciler } from '#lib/server/selfUpdate.server.js';\nimport {\n\tbootstrapUserSession,\n\thasSetupProof,\n\tidentifyWithSetupProof,\n\twireHeaderAuthBootstrap\n} from '#lib/server/auth-bootstrap.server.js';\nimport {\n\tgetRefreshToken,\n\tsetSessionCookie,\n\tsetRefreshCookie,\n\tclearRefreshCookie\n} from '#lib/server/admin-auth.server.js';\n\n// Wired lazily on first real request, not at module import, so test files\n// that import helpers from this module don't trigger provider lookups\n// before their fake providers are installed.\nlet headerAuthBootstrapWired = false;\n\n// Same lazy-on-first-request reasoning as headerAuthBootstrapWired above.\n// Result is cached in bootHealth.server.ts; `/api/health` awaits that promise.\nlet bootHealthKicked = false;\n\n// One-shot per process: a user landing on /login under forward-auth with no\n// resolved identity is the clearest \"headers didn't arrive\" signal, worth a\n// single log line rather than one per anonymous request.\nlet proxyAuthLoginMissWarned = false;\n\n// Once at server start, never in tests that import this module for `handle`.\nexport const init: ServerInit = () => {\n\tcheckConfigAtBoot();\n\trequestTiming.markBooted();\n\tstartStashJanitor();\n\t// Not in dev: Vite owns the signals there, and HMR would stack a listener per reload.\n\tif (!dev) {\n\t\tprocess.once('SIGINT', closeAllSolveEventStreams);\n\t\tprocess.once('SIGTERM', closeAllSolveEventStreams);\n\t\tprocess.once('sveltekit:shutdown', () => void exitAfterShutdown());\n\t}\n};\n\nconst SHUTDOWN_FLUSH_MS = 3000;\n\n/**\n * adapter-node closes the HTTP server on SIGINT or SIGTERM, emits this event and\n * then waits for the event loop to empty. Here it never does (limiter sweeps,\n * caches, the solve-event bus), so the process sat until pm2's kill timeout and\n * was SIGKILLed: ten seconds on every stop, restart and update, and the metric\n * sink's last batch lost. Bounded, so a dead database cannot hold the exit.\n */\nasync function exitAfterShutdown(): Promise<void> {\n\tconst sink = getSolveMetricSink() as { close?: () => Promise<void> };\n\ttry {\n\t\tawait Promise.race([\n\t\t\tsink.close?.(),\n\t\t\tnew Promise((resolve) => setTimeout(resolve, SHUTDOWN_FLUSH_MS))\n\t\t]);\n\t} catch {\n\t\t// Exiting anyway: a failed flush is not a reason to wait for the SIGKILL.\n\t} finally {\n\t\tprocess.exit(0);\n\t}\n}\n\n// One-way transition (zero users → at least one). Once true, permanent —\n// caching it skips a per-request listUsers DB read after the first user exists.\nlet firstRunResolved = false;\n\nasync function isFirstRun(): Promise<boolean> {\n\tif (firstRunResolved) return false;\n\tconst usersPage = await providers.auth.listUsers({ limit: 1 });\n\tif (usersPage === null) {\n\t\t// OIDC-only provider, no listUsers support — the setup page falls back\n\t\t// to `permissions.hasInstanceAdmin` and first-run gating doesn't apply.\n\t\tfirstRunResolved = true;\n\t\treturn false;\n\t}\n\tif (usersPage.items.length === 0) return true;\n\tfirstRunResolved = true;\n\treturn false;\n}\n\n// `ensureUser` is idempotent and rows don't disappear mid-process, so once a\n// user is ensured, subsequent requests skip the data-layer round-trip (local:\n// a full `user-data.json` read+parse) for a `Set.has` check. Per-process only —\n// a second instance just ensures the same user once itself; safe since the\n// call is idempotent.\nconst ensuredUserIds = new Set<string>();\n\nasync function ensureUserOnce(userId: string): Promise<void> {\n\tif (ensuredUserIds.has(userId)) return;\n\tawait providers.data.ensureUser(SYSTEM_CONTEXT, userId);\n\tensuredUserIds.add(userId);\n}\n\ntype SessionRows = Awaited<ReturnType<typeof readSessionRows>>;\n\ninterface Session {\n\tuser: AuthUser;\n\tprofile: App.Locals['profile'];\n\tctx: App.Locals['ctx'];\n}\n\n/**\n * Profile, platform permissions and membership: independent and keyed only by the user id, so\n * they run together as SYSTEM_CONTEXT (`ctx` isn't built yet), and for a JWT session beside\n * `verifyToken`. Reads only: they run before the token is checked.\n */\nfunction readSessionRows(userId: string) {\n\treturn Promise.all([\n\t\tproviders.data.userProfile.getProfile(SYSTEM_CONTEXT, userId),\n\t\tproviders.data.permissions.getFor(SYSTEM_CONTEXT, userId),\n\t\tproviders.data.orgs.findUserMembership(SYSTEM_CONTEXT, userId)\n\t]);\n}\n\n/**\n * The acting org is the user's first membership, or an instance admin's fallback. `ensureUser`\n * is the local equivalent of Supabase's `handle_new_auth_user` trigger, memoized per process.\n * The rows may have been read before it seeded a brand-new user's row: each fails soft to\n * empty, the correct state for a user with nothing yet.\n */\nasync function buildSession(\n\tuser: AuthUser,\n\t[profile, platformPermissions, membership]: SessionRows,\n\t// Forwarded so adapters scoping by the upstream token (Supabase RLS) get it.\n\tsessionToken: string | undefined\n): Promise<Session> {\n\tawait ensureUserOnce(user.id);\n\treturn {\n\t\tuser,\n\t\tprofile: profile ?? emptyProfile(user.id),\n\t\tctx: await buildRequestContext(\n\t\t\t{ user, sessionToken, platformPermissions, membership: membership?.member ?? null },\n\t\t\t{ orgs: providers.data.orgs }\n\t\t)\n\t};\n}\n\n// No window: every request resolves its own session, since what it holds (stars, recent\n// runs, memberships) changes under many writes that don't invalidate. Requests carrying one\n// token at once still share one resolution, and a JWT's rows are read beside its check.\nconst sessions = createSessionResolver({\n\tverify: (token) => providers.auth.verifyToken(token),\n\tread: readSessionRows,\n\tbuild: buildSession\n});\n\n/** For a user identified without a session token (forward-auth headers). */\nasync function sessionFor(user: AuthUser, sessionToken: string | undefined): Promise<Session> {\n\treturn buildSession(user, await readSessionRows(user.id), sessionToken);\n}\n\nfunction attachSession(event: RequestEvent, session: Session): void {\n\tevent.locals.user = session.user;\n\tevent.locals.profile = session.profile;\n\tevent.locals.ctx = session.ctx;\n}\n\n// ============================================================================\n// Route classification\n// ============================================================================\n//\n// Auth gating is **deny-by-default**: the classifier (mechanics in\n// `@selvajs/server/http`) gates every request unless its path matches one of\n// the allowlists below. Adding a route is safe by default — forgetting to\n// list it makes it gated (401/redirect), not silently public. Named (not\n// inlined into the classifier config) because the best-effort session attach\n// below also needs it: public *pages* get locals populated for a signed-in\n// user, public prefixes/APIs don't.\nconst PUBLIC_PAGE_ROUTES: ReadonlySet<string> = new Set([\n\t'/', // guests see the landing page; authed users get redirected by +page.server.ts\n\t'/login',\n\t'/setup',\n\t'/accept-invite'\n]);\n\nconst routeClassifier = createRouteClassifier({\n\tpublicPages: PUBLIC_PAGE_ROUTES,\n\t// `/auth/` is the OAuth start + callback flow (no session yet by\n\t// definition). `/logout` is a form action that destroys the session then\n\t// redirects. `/docs/` is the API reference — reads no tenant data, and\n\t// gating it would hide it from callers deciding whether to integrate.\n\tpublicPrefixes: ['/auth/', '/logout', '/docs/'],\n\t// Must answer without a session: load-balancer liveness probe, and the\n\t// readiness probe the post-update poller waits on across a restart. The v1\n\t// spec is public for the same reason `/docs/` is. `/mcp` gates itself: it needs a\n\t// key and passes it through to `/api/v1`, which authenticates every call.\n\t// OAuth discovery, registration and token exchange are called server-to-server\n\t// by MCP clients, with no session.\n\tpublicApis: [\n\t\t'/api/health',\n\t\t'/api/health/ready',\n\t\t'/api/v1/openapi.json',\n\t\tMCP_PATH,\n\t\t'/.well-known/oauth-protected-resource',\n\t\t'/.well-known/oauth-protected-resource/mcp',\n\t\t'/.well-known/oauth-authorization-server',\n\t\t'/oauth/register',\n\t\tOAUTH_TOKEN_PATH\n\t],\n\t// Self-gating routes authorize each request themselves; the hook must not\n\t// deny them up front. `/api/files/[...path]` classifies each path against\n\t// the asset-class registry (public branding serves to anyone, org/project\n\t// assets 401 without a session). `/api/v1/solve-events` holds the SSE stream\n\t// (requires a session, checked in the route) and the Compute callback (no\n\t// session by nature — a per-solve bearer instead). The only other route that\n\t// authorizes a request itself is `/api/v1/compute` with a share token: see\n\t// `carriesShareToken`.\n\t//\n\t// No trailing slash on solve-events: the SSE route IS that path, with the\n\t// stream in a query param, so a trailing slash would deny the stream while\n\t// letting the callback (which has a solveId segment) through.\n\t//\n\t// `/mcp/files/` serves an MCP solve's output files by an unguessable token\n\t// that expires within the hour, so a link works where the model hands it on.\n\t//\n\t// `/api/v1/solves/` reads a detached solve. One a share-link viewer started has\n\t// no session behind it, so its unguessable id is the capability; one a user\n\t// started is readable by that user only, checked in the route.\n\tselfGatingPrefixes: ['/api/files/', '/api/v1/solve-events', '/api/v1/solves/', MCP_FILES_PREFIX],\n\t// Static-asset paths SvelteKit/adapter-node serves directly.\n\tstaticPrefixes: ['/_app/', '/favicon/'],\n\tstaticPaths: ['/favicon.svg', '/robots.txt']\n});\n\n// Exported for tests: these predicates are the deny-by-default policy, and a\n// bug in either is security-relevant.\nexport const { isStaticAsset, isSelfGatingApiRoute, isPublicRoute } = routeClassifier;\n\n// The only two routes that honour a share token. A share link is meant to work\n// without an account, so a request that carries one and has no session still\n// reaches the route, which accepts or refuses the token itself. The page serves\n// only the live pointer by token: a draft or version pick still needs a session.\nconst SHARE_TOKEN_API = '/api/v1/compute';\nconst SHARE_TOKEN_PAGE = /^\\/library\\/[^/]+$/;\n\nfunction carriesShareToken(request: Request, url: URL): boolean {\n\tconst onShareRoute =\n\t\turl.pathname === SHARE_TOKEN_API ||\n\t\t(SHARE_TOKEN_PAGE.test(url.pathname) &&\n\t\t\turl.searchParams.get('channel') !== 'draft' &&\n\t\t\t!url.searchParams.has('version'));\n\treturn onShareRoute && readShareToken(request, url) !== null;\n}\n\n// Kept out of `redirectTo`: the login URL lands in access logs and browser history.\nfunction withoutShareToken(url: URL): string {\n\tconst query = new URLSearchParams(\n\t\t[...url.searchParams].filter(([key, value]) => !(key === 'token' && looksLikeShareToken(value)))\n\t).toString();\n\treturn url.pathname + (query ? `?${query}` : '');\n}\n\n// Every request runs inside its read memo, so a layout and its page share repeated reads, and\n// inside its timing store; static assets skip the timing.\nexport const handle: import('@sveltejs/kit/hooks').Handle = (input) => {\n\tconst { event } = input;\n\tconst run = () =>\n\t\trequestMemo.run(event.request.method, async () =>\n\t\t\twithRequestIdInErrorBody(await gate(input), event.url.pathname)\n\t\t);\n\tif (isStaticAsset(event.url.pathname)) return run();\n\treturn requestTiming.timeRequest(\n\t\t{\n\t\t\tmethod: event.request.method,\n\t\t\troute: event.route.id ?? event.url.pathname,\n\t\t\tisDataRequest: event.isDataRequest\n\t\t},\n\t\tasync () => run()\n\t);\n};\n\nconst gate: import('@sveltejs/kit/hooks').Handle = async ({ event, resolve }) => {\n\tevent.locals.providers = providers;\n\n\t// Bound once per request; every downstream `locals.log` record inherits\n\t// these fields. `event.url.pathname`, never `.search` — query strings carry\n\t// share tokens, and a log record outlives the token's usefulness to an attacker.\n\tconst requestId = resolveRequestId(event.request.headers);\n\tevent.locals.requestId = requestId;\n\tevent.locals.log = getLogger().child({\n\t\trequestId,\n\t\tmethod: event.request.method,\n\t\troute: event.url.pathname\n\t});\n\n\tif (!headerAuthBootstrapWired) {\n\t\twireHeaderAuthBootstrap();\n\t\theaderAuthBootstrapWired = true;\n\t}\n\n\tif (!bootHealthKicked) {\n\t\tbootHealthKicked = true;\n\t\tvoid getBootHealth();\n\t\tstartRetentionJanitor({\n\t\t\tdata: providers.data,\n\t\t\tpolicy: resolveRetentionPolicy(env),\n\t\t\tlogger: getLogger()\n\t\t});\n\t\t// Reconciles a self-update that was in flight when this process came up\n\t\t// into the audit log. No-op when no pending-update state file exists —\n\t\t// see selfUpdate.server.ts for the full lifecycle.\n\t\tconst deploymentDir = findDeploymentDir(env);\n\t\tif (deploymentDir) {\n\t\t\tstartUpdateOutcomeReconciler({\n\t\t\t\tdeploymentDir,\n\t\t\t\temit: (e) => getEventSink().emit(e),\n\t\t\t\treport: (err) => getErrorReporter().capture(err, { tags: { origin: 'selfUpdate' } })\n\t\t\t});\n\t\t}\n\t}\n\n\tconst { pathname } = event.url;\n\n\t// SvelteKit's own check is off (vite.config.ts) because it can't exempt the\n\t// token endpoint or bearer requests; this is the same check with those exemptions.\n\tif (\n\t\t!dev &&\n\t\tisCrossSiteFormSubmission(event.request, {\n\t\t\texemptPaths: [OAUTH_TOKEN_PATH],\n\t\t\torigin: publicUrl(event.url).origin\n\t\t})\n\t) {\n\t\treturn applyResponseHeaders(\n\t\t\tnew Response(`Cross-site ${event.request.method} form submissions are forbidden`, {\n\t\t\t\tstatus: 403\n\t\t\t}),\n\t\t\tpathname,\n\t\t\trequestId\n\t\t);\n\t}\n\n\t// Static assets bypass every gate below — no auth, no first-run check.\n\tif (isStaticAsset(pathname)) {\n\t\treturn applyResponseHeaders(await resolve(event), pathname, requestId);\n\t}\n\n\t// Probes answer before any gate runs — a fresh deployment with no users yet\n\t// is still live and ready, and the first-run 503 below would tell a load\n\t// balancer (or the post-update poller) the opposite.\n\tif (pathname === '/api/health' || pathname === '/api/health/ready') {\n\t\treturn applyResponseHeaders(await resolve(event), pathname, requestId);\n\t}\n\n\t// A `selva_` key decides the request on its own: it never falls back to the\n\t// cookie, so a broken key can't quietly run as whoever is signed in.\n\t// `/mcp` carries a key but isn't under `/api/v1`, so the resolver would refuse it.\n\tconst tokenResult =\n\t\tpathname === MCP_PATH\n\t\t\t? ({ kind: 'none' } as const)\n\t\t\t: await resolveApiToken(event.request, {\n\t\t\t\t\tcodec: apiTokenCodec(),\n\t\t\t\t\tauth: providers.auth,\n\t\t\t\t\tdata: providers.data,\n\t\t\t\t\tflag,\n\t\t\t\t\tholderVerdicts,\n\t\t\t\t\tsignInMaxAgeMs,\n\t\t\t\t\tresolutionCache: apiTokenResolutions,\n\t\t\t\t\tlog: event.locals.log\n\t\t\t\t});\n\tif (tokenResult.kind === 'rejected') {\n\t\tconst { status, code, message } = tokenResult;\n\t\tconst headers: Record<string, string> = { 'Content-Type': 'application/json' };\n\t\tif (status === 401) headers['WWW-Authenticate'] = 'Bearer error=\"invalid_token\"';\n\t\treturn applyResponseHeaders(\n\t\t\tnew Response(JSON.stringify({ message, code }), { status, headers }),\n\t\t\tpathname,\n\t\t\trequestId\n\t\t);\n\t}\n\tif (tokenResult.kind === 'ok') {\n\t\tconst { user, ctx, token } = tokenResult;\n\t\tevent.locals.log = event.locals.log.child({ tokenId: token.id });\n\t\tevent.locals.user = user;\n\t\tevent.locals.ctx = ctx;\n\t\tevent.locals.profile =\n\t\t\t(await providers.data.userProfile.getProfile(SYSTEM_CONTEXT, user.id)) ??\n\t\t\temptyProfile(user.id);\n\n\t\treturn applyResponseHeaders(await resolve(event), pathname, requestId);\n\t}\n\n\tconst publicRoute = isPublicRoute(pathname);\n\t// All HTTP endpoints live under `/api/*` — distinguishes 401 JSON from a\n\t// 303 redirect.\n\tconst isJsonApiRoute = pathname.startsWith('/api/');\n\n\t// On first run (no users yet), redirect non-public traffic to /setup so a\n\t// fresh deployment lands on the bootstrap flow instead of a dead login\n\t// page. Public routes pass through unchanged.\n\tif (!publicRoute) {\n\t\tif (await isFirstRun()) {\n\t\t\tif (isJsonApiRoute) {\n\t\t\t\treturn applyResponseHeaders(\n\t\t\t\t\tnew Response(JSON.stringify({ message: 'Setup required', code: 'SETUP_REQUIRED' }), {\n\t\t\t\t\t\tstatus: 503,\n\t\t\t\t\t\theaders: { 'Content-Type': 'application/json' }\n\t\t\t\t\t}),\n\t\t\t\t\tpathname,\n\t\t\t\t\trequestId\n\t\t\t\t);\n\t\t\t}\n\t\t\tredirect(303, '/setup');\n\t\t}\n\t}\n\n\t// Deny-by-default: any non-public, non-static path requires a valid session,\n\t// unless it carries a share token the route checks itself.\n\tconst needsAuth = !publicRoute;\n\tif (needsAuth) {\n\t\tlet token = event.cookies.get('admin_session') ?? '';\n\t\tlet session = await sessions.resolve(token);\n\n\t\t// When the access token expired but a refresh token is present (Supabase\n\t\t// OAuth flow), swap silently for a fresh pair and rotate the cookies.\n\t\t// Local/HMAC sessions never set a refresh cookie, so this is a no-op there.\n\t\tif (!session) {\n\t\t\tconst refreshToken = getRefreshToken(event.cookies);\n\t\t\tif (refreshToken && providers.auth.sessionRefresh) {\n\t\t\t\tconst refreshed = await refreshSession(refreshToken);\n\t\t\t\tif (refreshed) {\n\t\t\t\t\tsetSessionCookie(event.cookies, refreshed.sessionToken);\n\t\t\t\t\tsetRefreshCookie(event.cookies, refreshed.refreshToken);\n\t\t\t\t\ttoken = refreshed.sessionToken;\n\t\t\t\t\tsession = await sessions.resolve(token);\n\t\t\t\t} else {\n\t\t\t\t\t// Refresh failed — clear the stale cookie so the next request\n\t\t\t\t\t// goes through the login flow cleanly.\n\t\t\t\t\tclearRefreshCookie(event.cookies);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Forward-proxy fallback: providers that derive identity from trusted\n\t\t// upstream-proxy signals (Caddy forward_auth, oauth2-proxy, etc.) get a\n\t\t// chance to identify the request. See IProxyAuth for the trust contract.\n\t\tlet user = session?.user ?? null;\n\t\tconst proxyAuth = providers.auth.proxyAuth;\n\t\tif (!user && proxyAuth) {\n\t\t\tconst setupProven = hasSetupProof(event.cookies);\n\t\t\tuser = await identifyWithSetupProof(setupProven, () =>\n\t\t\t\tproxyAuth.identifyFromHeaders(event.request.headers)\n\t\t\t);\n\t\t\t// First-admin bootstrap for forward-auth deployments: OAuth and\n\t\t\t// email-link callbacks call `bootstrapUserSession` themselves, but the\n\t\t\t// proxy-auth path has no callback. Internally gated by `hasInstanceAdmin`\n\t\t\t// and a no-op once an admin exists, so safe on every authed request.\n\t\t\tif (user) await bootstrapUserSession(user, setupProven);\n\t\t}\n\n\t\tif (!user && carriesShareToken(event.request, event.url)) {\n\t\t\treturn applyResponseHeaders(await resolve(event), pathname, requestId);\n\t\t}\n\n\t\tif (!user) {\n\t\t\tif (isJsonApiRoute) {\n\t\t\t\treturn applyResponseHeaders(\n\t\t\t\t\tnew Response(\n\t\t\t\t\t\tJSON.stringify({\n\t\t\t\t\t\t\tmessage: 'Your session has expired. Sign in again to continue.',\n\t\t\t\t\t\t\tcode: 'UNAUTHORIZED'\n\t\t\t\t\t\t}),\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tstatus: 401,\n\t\t\t\t\t\t\theaders: { 'Content-Type': 'application/json' }\n\t\t\t\t\t\t}\n\t\t\t\t\t),\n\t\t\t\t\tpathname,\n\t\t\t\t\trequestId\n\t\t\t\t);\n\t\t\t}\n\t\t\t// With the query: an OAuth authorize request is nothing without it.\n\t\t\tredirect(303, `/login?redirectTo=${encodeURIComponent(withoutShareToken(event.url))}`);\n\t\t}\n\n\t\tattachSession(event, session ?? (await sessionFor(user, token)));\n\t} else {\n\t\t// Public page route (e.g. `/`): best-effort session attach. If a valid\n\t\t// session cookie is present, populate locals so the UI reflects authed\n\t\t// state (nav, user chip). Failure is silent — public pages keep\n\t\t// rendering for guests. Also applies to the self-gating files proxy,\n\t\t// which needs `locals.ctx` when a session is present so org/project\n\t\t// assets resolve, while still rendering guests' public branding.\n\t\tconst isPublicPage = PUBLIC_PAGE_ROUTES.has(pathname);\n\t\tconst wantsSessionAttach = isPublicPage || isSelfGatingApiRoute(pathname);\n\t\tconst token = wantsSessionAttach ? (event.cookies.get('admin_session') ?? '') : '';\n\t\tconst session = token ? await sessions.resolve(token) : null;\n\t\tlet user = session?.user ?? null;\n\t\tif (!user && wantsSessionAttach && providers.auth.proxyAuth) {\n\t\t\tuser = await providers.auth.proxyAuth.identifyFromHeaders(event.request.headers);\n\n\t\t\tif (!user && pathname === '/login' && !proxyAuthLoginMissWarned) {\n\t\t\t\tproxyAuthLoginMissWarned = true;\n\t\t\t\tconst proxyAuth = providers.auth.proxyAuth;\n\t\t\t\tconst noHeaders = proxyAuth.hasNoIdentityHeaders(event.request.headers);\n\t\t\t\tconst configured = proxyAuth.configuredHeaderNames.join(', ');\n\t\t\t\tif (noHeaders) {\n\t\t\t\t\tevent.locals.log.warn(\n\t\t\t\t\t\t'/login was hit and NONE of the configured identity headers arrived. The ' +\n\t\t\t\t\t\t\t'forward-auth proxy is not reaching this process, or is not forwarding the ' +\n\t\t\t\t\t\t\t'configured headers. See the @selvajs/header-auth-provider README ' +\n\t\t\t\t\t\t\t'\"Verification\" section.',\n\t\t\t\t\t\t{ component: 'HeaderAuth', configuredHeaders: configured }\n\t\t\t\t\t);\n\t\t\t\t} else {\n\t\t\t\t\tevent.locals.log.warn(\n\t\t\t\t\t\t'/login was hit but the UPN header was missing or the user is not allowlisted. ' +\n\t\t\t\t\t\t\t'Some headers arrived but identification still failed — check that the UPN ' +\n\t\t\t\t\t\t\t'header is populated and that the user has been added to header-allowlist.json.',\n\t\t\t\t\t\t{ component: 'HeaderAuth', configuredHeaders: configured }\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (user) attachSession(event, session ?? (await sessionFor(user, token)));\n\t}\n\n\treturn applyResponseHeaders(await resolve(event), pathname, requestId);\n};\n\n// ============================================================================\n// Response headers\n// ============================================================================\n//\n// Applied to every response — successful resolves and the 401/503\n// short-circuits above. The browser-hardening set (nosniff, Referrer-Policy,\n// Permissions-Policy, HSTS in production) lives in `@selvajs/server/http` —\n// see `applySecurityHeaders` there. Cache-control stays here: it encodes this\n// app's asset layout.\n//\n// Frame headers are the one route-dependent piece (`deniesFraming`).\n\nfunction applyResponseHeaders(response: Response, pathname: string, requestId: string): Response {\n\tapplySecurityHeaders(response, {\n\t\thsts: process.env.NODE_ENV === 'production',\n\t\tdenyFraming: deniesFraming(pathname)\n\t});\n\n\t// Echoed so a user reporting \"request X failed\" gives an operator the\n\t// exact key to grep logs with.\n\tresponse.headers.set(REQUEST_ID_HEADER, requestId);\n\n\t// Cache-control: hashed build assets are immutable; other static assets\n\t// get a short TTL.\n\tif (pathname.startsWith('/_app/')) {\n\t\tresponse.headers.set('Cache-Control', 'public, max-age=31536000, immutable');\n\t} else if (pathname.startsWith('/api/v1/') && !response.headers.has('Cache-Control')) {\n\t\t// Authenticated JSON: no intermediary may keep a copy.\n\t\tresponse.headers.set('Cache-Control', 'private, no-store');\n\t} else if (\n\t\tpathname.startsWith('/favicon/') ||\n\t\tpathname === '/favicon.svg' ||\n\t\tpathname === '/robots.txt'\n\t) {\n\t\tresponse.headers.set('Cache-Control', 'public, max-age=604800');\n\t}\n\n\treturn response;\n}\n\n/**\n * Copies the request id into an API error's JSON body, so a client that logs only the body still\n * has the id an operator greps for. The header alone is lost by most HTTP client error paths.\n */\nasync function withRequestIdInErrorBody(response: Response, pathname: string): Promise<Response> {\n\tif (response.status < 400 || !pathname.startsWith('/api/')) return response;\n\tif (!response.headers.get('Content-Type')?.includes('application/json')) return response;\n\tconst requestId = response.headers.get(REQUEST_ID_HEADER);\n\tif (!requestId) return response;\n\tlet body: unknown;\n\ttry {\n\t\tbody = await response.clone().json();\n\t} catch {\n\t\treturn response;\n\t}\n\tif (!body || typeof body !== 'object' || Array.isArray(body) || 'requestId' in body) {\n\t\treturn response;\n\t}\n\tconst headers = new Headers(response.headers);\n\theaders.delete('Content-Length');\n\treturn new Response(JSON.stringify({ ...body, requestId }), {\n\t\tstatus: response.status,\n\t\tstatusText: response.statusText,\n\t\theaders\n\t});\n}\n\nexport const handleError: import('@sveltejs/kit/hooks').HandleServerError = ({\n\tkind,\n\terror,\n\tevent\n}) => {\n\t// `error(...)` bodies already carry `code`/`fields`, so they reach the client as thrown.\n\tif (kind === 'app') return error;\n\tif (kind !== 'unknown') {\n\t\treturn error.status === 404 ? { message: 'Page not found.', code: 'NOT_FOUND' } : error;\n\t}\n\t// Backstop only. `ApiError` reaching here means a page load called a guard\n\t// without going through `asHttpError()`.\n\tif (isApiError(error)) {\n\t\treturn {\n\t\t\tstatus: error.status,\n\t\t\tmessage: error.message,\n\t\t\tcode: error.code,\n\t\t\tfields: error.fields,\n\t\t\tdetails: error.details\n\t\t};\n\t}\n\t// SvelteKit's default logging drops `cause`, which is where provider\n\t// adapters tend to stash the real reason (Supabase network error, fs\n\t// EACCES, etc.) — kept as a separate field so the message still groups\n\t// cleanly while the stack stays searchable.\n\t//\n\t// `locals.log` already carries requestId/method/route, but handleError can\n\t// fire before `handle` populates locals (a throw in an earlier hook), so\n\t// fall back to the root logger and re-state the fields.\n\tconst log =\n\t\tevent.locals.log ??\n\t\tgetLogger().child({ method: event.request.method, route: event.url.pathname });\n\tlog.error('Unhandled error', {\n\t\tcomponent: 'handleError',\n\t\terr: renderThrown(error),\n\t\tcause: error instanceof Error && error.cause ? String(error.cause) : undefined\n\t});\n\t// Only reached for genuinely unexpected errors — intentional HTTP outcomes\n\t// (incl. the compute route's `apiError(500)` on a failed solve) are\n\t// `HttpError`s handled above. No-op unless SENTRY_DSN is configured.\n\tgetErrorReporter().capture(error, {\n\t\tmethod: event.request.method,\n\t\troute: event.url.pathname,\n\t\tuserId: event.locals.ctx?.userId || undefined,\n\t\torgId: event.locals.ctx?.actingOrgId\n\t});\n\treturn { message: 'An unexpected error occurred.', code: 'INTERNAL' };\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAMA,IAAM,WAA6C;CAClD,CAAC,aAAa,IAAI;CAClB,CAAC,aAAa,MAAM;CACpB,CAAC,gBAAgB,SAAS;AAC3B;AAEA,SAAgB,iBAAiB,KAAuD;CACvF,MAAM,UAAU,SAAS,MAAM,CAAC,YAAY,IAAI,SAAS,WAAW,MAAM,CAAC;CAC3E,IAAI,CAAC,SAAS,OAAO,KAAA;CACrB,MAAM,CAAC,QAAQ,IAAI,SAAS,MAAM,IAAI,SAAS,MAAM,QAAQ,EAAE,CAAC,MAAM,CAAC,CAAC,MAAM,GAAG;CACjF,OAAO;EAAE,KAAK,QAAQ;EAAI,QAAQ,GAAG,QAAQ,GAAG,GAAG,UAAU,QAAQ,OAAO,WAAW;CAAQ;AAChG;;;;;;;;;;;;;;;;;;;;;;;ACqBA,SAAgB,qBAAqB,UAAoB,MAAuC;CAC/F,SAAS,QAAQ,IAAI,0BAA0B,SAAS;CACxD,SAAS,QAAQ,IAAI,mBAAmB,iCAAiC;CACzE,SAAS,QAAQ,IAChB,sBACA,+GACD;CACA,IAAI,KAAK,MACR,SAAS,QAAQ,IAAI,6BAA6B,qCAAqC;CAExF,IAAI,KAAK,aAAa;EACrB,SAAS,QAAQ,IAAI,mBAAmB,MAAM;EAC9C,SAAS,QAAQ,IAAI,2BAA2B,wBAAwB;CACzE;CACA,OAAO;AACR;;ACPA,SAAgB,sBAAsB,QAAgD;CACrF,MAAM,cAAc,IAAI,IAAI,OAAO,eAAe,CAAC,CAAC;CACpD,MAAM,iBAAiB,OAAO,kBAAkB,CAAC;CACjD,MAAM,aAAa,IAAI,IAAI,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AC,CAAC,QAAQ,OAAO;EACjC,QAAQ,MAAM,QAAQ;EACtB,OAAO,MAAM,IAAI;EACjB,QAAQ,MAAM,OAAO,KAAK,UAAU,KAAA;EACpC,OAAO,MAAM,OAAO,KAAK;CAC1B,CAAC;CACD,OAAO;EAAE,SAAS;EAAiC,MAAM;CAAW;AACrE"}
@@ -1,4 +1,4 @@
1
- import "../../chunks/server3.js";
1
+ import "../../chunks/server4.js";
2
2
  import { t as page } from "../../chunks/state.js";
3
3
  import { t as ErrorScreen } from "../../chunks/ErrorScreen.js";
4
4
  // src/routes/+error.svelte
@@ -1,4 +1,4 @@
1
- import { Ft as run, Lt as escape_html, Ot as attr, _ as setContext, a as derived, c as head, d as spread_props, f as stringify, g as hasContext, h as getContext, kt as clsx, n as attr_style, r as attributes, s as ensure_array_like, t as attr_class } from "../../chunks/server3.js";
1
+ import { Ft as run, Lt as escape_html, Ot as attr, _ as setContext, a as derived, c as head, d as spread_props, f as stringify, g as hasContext, h as getContext, kt as clsx, n as attr_style, r as attributes, s as ensure_array_like, t as attr_class } from "../../chunks/server4.js";
2
2
  import { i as Mode_watcher, n as initializeFooterContext, o as derivedMode } from "../../chunks/footerContext.svelte.js";
3
3
  import { r as on } from "../../chunks/events.js";
4
4
  import { a as createSubscriber } from "../../chunks/index-server.js";
@@ -1,4 +1,4 @@
1
- import { Lt as escape_html, Ot as attr, a as derived, c as head, f as stringify, n as attr_style, s as ensure_array_like, t as attr_class } from "../../chunks/server3.js";
1
+ import { Lt as escape_html, Ot as attr, a as derived, c as head, f as stringify, n as attr_style, s as ensure_array_like, t as attr_class } from "../../chunks/server4.js";
2
2
  import { t as page } from "../../chunks/state.js";
3
3
  import { t as Button } from "../../chunks/button.js";
4
4
  import { t as Arrow_right } from "../../chunks/arrow-right.js";
@@ -1,4 +1,4 @@
1
- import { Lt as escape_html, Ot as attr, c as head } from "../../../chunks/server3.js";
1
+ import { Lt as escape_html, Ot as attr, c as head } from "../../../chunks/server4.js";
2
2
  import { t as page } from "../../../chunks/state.js";
3
3
  import { t as Button } from "../../../chunks/button.js";
4
4
  import { t as Label } from "../../../chunks/label.js";
@@ -1,4 +1,4 @@
1
- import "../../../chunks/server3.js";
1
+ import "../../../chunks/server4.js";
2
2
  import { t as page } from "../../../chunks/state.js";
3
3
  import { t as ErrorScreen } from "../../../chunks/ErrorScreen.js";
4
4
  // src/routes/admin/+error.svelte
@@ -1,11 +1,11 @@
1
- import { a as derived } from "../../../chunks/server3.js";
1
+ import { a as derived } from "../../../chunks/server4.js";
2
2
  import { t as Building_complex } from "../../../chunks/building-complex.js";
3
3
  import { t as SideNav } from "../../../chunks/SideNav.js";
4
4
  import { t as Folders } from "../../../chunks/folders.js";
5
5
  import { t as Gauge } from "../../../chunks/gauge.js";
6
6
  import { t as AppHeader } from "../../../chunks/AppHeader.js";
7
7
  import { t as Scroll_text } from "../../../chunks/scroll-text.js";
8
- import { t as Server } from "../../../chunks/server4.js";
8
+ import { t as Server } from "../../../chunks/server5.js";
9
9
  import { t as Settings } from "../../../chunks/settings.js";
10
10
  import { t as Users } from "../../../chunks/users.js";
11
11
  import { t as PageContent } from "../../../chunks/PageContent.js";
@@ -1,9 +1,9 @@
1
- import { Lt as escape_html, Ot as attr, a as derived, c as head, d as spread_props, f as stringify, s as ensure_array_like } from "../../../chunks/server3.js";
1
+ import { Lt as escape_html, Ot as attr, a as derived, c as head, d as spread_props, f as stringify, s as ensure_array_like } from "../../../chunks/server4.js";
2
2
  import { t as page } from "../../../chunks/state.js";
3
3
  import { n as Icon } from "../../../chunks/utils.js";
4
4
  import { t as Button } from "../../../chunks/button.js";
5
5
  import { t as Building_complex } from "../../../chunks/building-complex.js";
6
- import { t as Server } from "../../../chunks/server4.js";
6
+ import { t as Server } from "../../../chunks/server5.js";
7
7
  import { t as Trash } from "../../../chunks/trash.js";
8
8
  import { t as Users } from "../../../chunks/users.js";
9
9
  import { t as SectionHeader } from "../../../chunks/SectionHeader.js";
@@ -1,4 +1,4 @@
1
- import { Lt as escape_html, Ot as attr, a as derived, c as head, s as ensure_array_like } from "../../../../chunks/server3.js";
1
+ import { Lt as escape_html, Ot as attr, a as derived, c as head, s as ensure_array_like } from "../../../../chunks/server4.js";
2
2
  import { t as Button } from "../../../../chunks/button.js";
3
3
  import { t as Chevron_down } from "../../../../chunks/chevron-down.js";
4
4
  import { t as Chevron_right } from "../../../../chunks/chevron-right.js";
@@ -1,4 +1,4 @@
1
- import { Lt as escape_html, Ot as attr, a as derived, c as head, d as spread_props, f as stringify, n as attr_style, s as ensure_array_like, t as attr_class } from "../../../../chunks/server3.js";
1
+ import { Lt as escape_html, Ot as attr, a as derived, c as head, d as spread_props, f as stringify, n as attr_style, s as ensure_array_like, t as attr_class } from "../../../../chunks/server4.js";
2
2
  import { r as SvelteSet } from "../../../../chunks/index-server.js";
3
3
  import { n as onDestroy } from "../../../../chunks/index-server2.js";
4
4
  import { n as Icon } from "../../../../chunks/utils.js";
@@ -8,7 +8,7 @@ import { t as Chevron_up } from "../../../../chunks/chevron-up.js";
8
8
  import { t as Circle } from "../../../../chunks/circle.js";
9
9
  import { t as Plus } from "../../../../chunks/plus.js";
10
10
  import { t as Refresh_cw } from "../../../../chunks/refresh-cw.js";
11
- import { t as Server } from "../../../../chunks/server4.js";
11
+ import { t as Server } from "../../../../chunks/server5.js";
12
12
  import { t as Star } from "../../../../chunks/star.js";
13
13
  import { t as Trash } from "../../../../chunks/trash.js";
14
14
  import { t as SectionHeader } from "../../../../chunks/SectionHeader.js";
@@ -1,4 +1,4 @@
1
- import { Lt as escape_html, c as head } from "../../../../chunks/server3.js";
1
+ import { Lt as escape_html, c as head } from "../../../../chunks/server4.js";
2
2
  import { t as Building_complex } from "../../../../chunks/building-complex.js";
3
3
  import { t as SectionHeader } from "../../../../chunks/SectionHeader.js";
4
4
  import { t as EmptyState } from "../../../../chunks/EmptyState.js";
@@ -1,4 +1,4 @@
1
- import { Lt as escape_html, Ot as attr, a as derived, c as head, d as spread_props } from "../../../../../chunks/server3.js";
1
+ import { Lt as escape_html, Ot as attr, a as derived, c as head, d as spread_props } from "../../../../../chunks/server4.js";
2
2
  import { n as Icon } from "../../../../../chunks/utils.js";
3
3
  import { t as Button } from "../../../../../chunks/button.js";
4
4
  import { t as Arrow_left } from "../../../../../chunks/arrow-left.js";
@@ -1,4 +1,4 @@
1
- import { Lt as escape_html, Ot as attr, c as head } from "../../../../chunks/server3.js";
1
+ import { Lt as escape_html, Ot as attr, c as head } from "../../../../chunks/server4.js";
2
2
  import { t as Button } from "../../../../chunks/button.js";
3
3
  import { t as Folders } from "../../../../chunks/folders.js";
4
4
  import { t as Plus } from "../../../../chunks/plus.js";
@@ -1,5 +1,5 @@
1
- import { t as flag } from "../../../../chunks/providers.server.js";
2
1
  import { C as requirePermission } from "../../../../chunks/access.js";
2
+ import { t as flag } from "../../../../chunks/providers.server.js";
3
3
  import { r as hasPermission } from "../../../../chunks/context.js";
4
4
  import { t as asHttpError } from "../../../../chunks/access2.server.js";
5
5
  import { S as REMOTE_DEFINITION_MAX_BYTES, _ as MAX_IMAGE_FILE_SIZE, a as computeRequestCap, b as REMOTE_DEFINITION_CACHE_TTL_MS, f as COMPUTE_DEFINITION_CACHE_BYTES, g as MAX_DEFINITION_FILE_SIZE, h as COMPUTE_SOLVE_CACHE_BYTES, m as COMPUTE_RESPONSE_MAX_BYTES, v as RATE_LIMIT_MAX_REQUESTS, x as REMOTE_DEFINITION_FETCH_TIMEOUT_MS, y as RATE_LIMIT_WINDOW_MS } from "../../../../chunks/engine.server.js";
@@ -1,5 +1,5 @@
1
1
  import { t as deriveOutcome } from "../../../../chunks/update-outcome.js";
2
- import { Ft as run, Lt as escape_html, Ot as attr, a as derived, c as head, d as spread_props, f as stringify, s as ensure_array_like, t as attr_class } from "../../../../chunks/server3.js";
2
+ import { Ft as run, Lt as escape_html, Ot as attr, a as derived, c as head, d as spread_props, f as stringify, s as ensure_array_like, t as attr_class } from "../../../../chunks/server4.js";
3
3
  import "../../../../chunks/index-server2.js";
4
4
  import { t as page } from "../../../../chunks/state.js";
5
5
  import { n as Icon } from "../../../../chunks/utils.js";
@@ -1,5 +1,5 @@
1
1
  import { t as ALL_PLATFORM_PERMISSIONS } from "../../../../chunks/types3.js";
2
- import { Lt as escape_html, Ot as attr, a as derived, c as head, d as spread_props, s as ensure_array_like, t as attr_class } from "../../../../chunks/server3.js";
2
+ import { Lt as escape_html, Ot as attr, a as derived, c as head, d as spread_props, s as ensure_array_like, t as attr_class } from "../../../../chunks/server4.js";
3
3
  import { n as Icon } from "../../../../chunks/utils.js";
4
4
  import { t as Button } from "../../../../chunks/button.js";
5
5
  import { t as Chevron_down } from "../../../../chunks/chevron-down.js";
@@ -1,4 +1,4 @@
1
- import { Lt as escape_html, c as head } from "../../../../../chunks/server3.js";
1
+ import { Lt as escape_html, c as head } from "../../../../../chunks/server4.js";
2
2
  import { t as page } from "../../../../../chunks/state.js";
3
3
  import { t as Mail } from "../../../../../chunks/mail.js";
4
4
  import { t as Callout } from "../../../../../chunks/Callout.js";
@@ -1,4 +1,4 @@
1
- import { c as head } from "../../../../../chunks/server3.js";
1
+ import { c as head } from "../../../../../chunks/server4.js";
2
2
  // src/routes/auth/email/start/+page.svelte
3
3
  function _page($$renderer) {
4
4
  head("1j44d23", $$renderer, ($$renderer) => {
@@ -1,5 +1,5 @@
1
1
  import { vt as resolve } from "../../../../chunks/internal.js";
2
- import { Lt as escape_html, Ot as attr, c as head, f as stringify, s as ensure_array_like, t as attr_class } from "../../../../chunks/server3.js";
2
+ import { Lt as escape_html, Ot as attr, c as head, f as stringify, s as ensure_array_like, t as attr_class } from "../../../../chunks/server4.js";
3
3
  import { t as PageContent } from "../../../../chunks/PageContent.js";
4
4
  // src/routes/docs/api/+page.svelte
5
5
  function _page($$renderer, $$props) {
@@ -1,5 +1,5 @@
1
- import { a as getComputeServerConfigStore, h as getOrganizationProvider, s as getDefinitionMeta, v as getProjectProvider, x as getStorageProvider } from "../../../../chunks/providers.server.js";
2
1
  import { E as scoped, V as NoopLogger, h as requireCanSolve, j as isApiError } from "../../../../chunks/access.js";
2
+ import { a as getComputeServerConfigStore, h as getOrganizationProvider, s as getDefinitionMeta, v as getProjectProvider, x as getStorageProvider } from "../../../../chunks/providers.server.js";
3
3
  import "../../../../chunks/api.js";
4
4
  import { n as renderThrown } from "../../../../chunks/logging.js";
5
5
  import { t as UI_SCHEMA_VERSION } from "../../../../chunks/schema.js";