@selvajs/selva 4.20.0-beta.27 → 4.20.0-beta.28
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/adapter-node.js +1 -1
- package/build/client/_app/immutable/assets/0.EoCnujqq.css +2 -0
- package/build/client/_app/immutable/assets/0.EoCnujqq.css.br +0 -0
- package/build/client/_app/immutable/assets/0.EoCnujqq.css.gz +0 -0
- package/build/client/_app/immutable/assets/21.Dy4MSSQ0.css +1 -0
- package/build/client/_app/immutable/assets/21.Dy4MSSQ0.css.br +0 -0
- package/build/client/_app/immutable/assets/21.Dy4MSSQ0.css.gz +0 -0
- package/build/client/_app/immutable/chunks/B54S3nTL.js +1 -0
- package/build/client/_app/immutable/chunks/B54S3nTL.js.br +0 -0
- package/build/client/_app/immutable/chunks/B54S3nTL.js.gz +0 -0
- package/build/client/_app/immutable/chunks/{sg4CWDsx.js → DNn0nzek.js} +1 -1
- package/build/client/_app/immutable/chunks/DNn0nzek.js.br +0 -0
- package/build/client/_app/immutable/chunks/DNn0nzek.js.gz +0 -0
- package/build/client/_app/immutable/chunks/DkJKKB94.js +1 -0
- package/build/client/_app/immutable/chunks/DkJKKB94.js.br +1 -0
- package/build/client/_app/immutable/chunks/DkJKKB94.js.gz +0 -0
- package/build/client/_app/immutable/chunks/XiGvLmZI.js +5906 -0
- package/build/client/_app/immutable/chunks/XiGvLmZI.js.br +0 -0
- package/build/client/_app/immutable/chunks/XiGvLmZI.js.gz +0 -0
- package/build/client/_app/immutable/chunks/{CaBqDK26.js → jZMNULqI.js} +1 -1
- package/build/client/_app/immutable/chunks/jZMNULqI.js.br +0 -0
- package/build/client/_app/immutable/chunks/jZMNULqI.js.gz +0 -0
- package/build/client/_app/immutable/entry/app.C4Xhz1j-.js +2 -0
- package/build/client/_app/immutable/entry/app.C4Xhz1j-.js.br +0 -0
- package/build/client/_app/immutable/entry/app.C4Xhz1j-.js.gz +0 -0
- package/build/client/_app/immutable/nodes/0.DTKs7-tx.js +1 -0
- package/build/client/_app/immutable/nodes/0.DTKs7-tx.js.br +0 -0
- package/build/client/_app/immutable/nodes/0.DTKs7-tx.js.gz +0 -0
- package/build/client/_app/immutable/nodes/11.DS0azG6Y.js +5 -0
- package/build/client/_app/immutable/nodes/11.DS0azG6Y.js.br +0 -0
- package/build/client/_app/immutable/nodes/11.DS0azG6Y.js.gz +0 -0
- package/build/client/_app/immutable/nodes/{13.JNEl4w7x.js → 13.BQ0cOim-.js} +2 -2
- package/build/client/_app/immutable/nodes/13.BQ0cOim-.js.br +0 -0
- package/build/client/_app/immutable/nodes/13.BQ0cOim-.js.gz +0 -0
- package/build/client/_app/immutable/nodes/{14.CiK46T_1.js → 14.BsbXlPTK.js} +2 -2
- package/build/client/_app/immutable/nodes/14.BsbXlPTK.js.br +0 -0
- package/build/client/_app/immutable/nodes/14.BsbXlPTK.js.gz +0 -0
- package/build/client/_app/immutable/nodes/15.Cuq4zfye.js +32 -0
- package/build/client/_app/immutable/nodes/15.Cuq4zfye.js.br +0 -0
- package/build/client/_app/immutable/nodes/15.Cuq4zfye.js.gz +0 -0
- package/build/client/_app/immutable/nodes/{16.CIy8Me4f.js → 16.D7-QOesS.js} +2 -2
- package/build/client/_app/immutable/nodes/16.D7-QOesS.js.br +0 -0
- package/build/client/_app/immutable/nodes/16.D7-QOesS.js.gz +0 -0
- package/build/client/_app/immutable/nodes/{17.DVNUmPUk.js → 17.0cv7e5IP.js} +1 -1
- package/build/client/_app/immutable/nodes/17.0cv7e5IP.js.br +0 -0
- package/build/client/_app/immutable/nodes/17.0cv7e5IP.js.gz +0 -0
- package/build/client/_app/immutable/nodes/{19.qbUJ-ZrA.js → 19.DRxrJE9N.js} +3 -3
- package/build/client/_app/immutable/nodes/19.DRxrJE9N.js.br +0 -0
- package/build/client/_app/immutable/nodes/19.DRxrJE9N.js.gz +0 -0
- package/build/client/_app/immutable/nodes/{2.Db9e6NkL.js → 2.CkTe-0F-.js} +1 -1
- package/build/client/_app/immutable/nodes/2.CkTe-0F-.js.br +0 -0
- package/build/client/_app/immutable/nodes/2.CkTe-0F-.js.gz +0 -0
- package/build/client/_app/immutable/nodes/20.ClCOkXtk.js +2 -0
- package/build/client/_app/immutable/nodes/20.ClCOkXtk.js.br +0 -0
- package/build/client/_app/immutable/nodes/20.ClCOkXtk.js.gz +0 -0
- package/build/client/_app/immutable/nodes/21.j2ZNmKE0.js +1 -0
- package/build/client/_app/immutable/nodes/21.j2ZNmKE0.js.br +1 -0
- package/build/client/_app/immutable/nodes/21.j2ZNmKE0.js.gz +0 -0
- package/build/client/_app/immutable/nodes/{22.AhwAEf2A.js → 22.3c2Ar-_L.js} +2 -2
- package/build/client/_app/immutable/nodes/22.3c2Ar-_L.js.br +0 -0
- package/build/client/_app/immutable/nodes/22.3c2Ar-_L.js.gz +0 -0
- package/build/client/_app/immutable/nodes/24.CPSunfJJ.js +3 -0
- package/build/client/_app/immutable/nodes/24.CPSunfJJ.js.br +0 -0
- package/build/client/_app/immutable/nodes/24.CPSunfJJ.js.gz +0 -0
- package/build/client/_app/immutable/nodes/{25.Cqalaz7Y.js → 25.C-dvoLm5.js} +12 -12
- package/build/client/_app/immutable/nodes/25.C-dvoLm5.js.br +0 -0
- package/build/client/_app/immutable/nodes/25.C-dvoLm5.js.gz +0 -0
- package/build/client/_app/immutable/nodes/{26.CnBEBmQb.js → 26.CqaMEm_t.js} +2 -2
- package/build/client/_app/immutable/nodes/26.CqaMEm_t.js.br +0 -0
- package/build/client/_app/immutable/nodes/26.CqaMEm_t.js.gz +0 -0
- package/build/client/_app/immutable/nodes/29.PsrL6xdd.js +4 -0
- package/build/client/_app/immutable/nodes/29.PsrL6xdd.js.br +0 -0
- package/build/client/_app/immutable/nodes/29.PsrL6xdd.js.gz +0 -0
- package/build/client/_app/immutable/nodes/30.Bz0cB9UL.js +6 -0
- package/build/client/_app/immutable/nodes/30.Bz0cB9UL.js.br +0 -0
- package/build/client/_app/immutable/nodes/30.Bz0cB9UL.js.gz +0 -0
- package/build/client/_app/immutable/nodes/31.CFCkC-P2.js +2 -0
- package/build/client/_app/immutable/nodes/31.CFCkC-P2.js.br +0 -0
- package/build/client/_app/immutable/nodes/31.CFCkC-P2.js.gz +0 -0
- package/build/client/_app/immutable/nodes/{32.Csmqk0LJ.js → 32.DWY9hRHg.js} +2 -2
- package/build/client/_app/immutable/nodes/32.DWY9hRHg.js.br +0 -0
- package/build/client/_app/immutable/nodes/32.DWY9hRHg.js.gz +0 -0
- package/build/client/_app/immutable/nodes/{34.KdJfmmfc.js → 34.ZQaLUUXZ.js} +1 -1
- package/build/client/_app/immutable/nodes/34.ZQaLUUXZ.js.br +0 -0
- package/build/client/_app/immutable/nodes/34.ZQaLUUXZ.js.gz +0 -0
- package/build/client/_app/immutable/nodes/35.DFkalFgm.js +5 -0
- package/build/client/_app/immutable/nodes/35.DFkalFgm.js.br +0 -0
- package/build/client/_app/immutable/nodes/35.DFkalFgm.js.gz +0 -0
- package/build/client/_app/immutable/nodes/{5.CAzzdmQi.js → 5.Ce6v0yql.js} +1 -1
- package/build/client/_app/immutable/nodes/5.Ce6v0yql.js.br +0 -0
- package/build/client/_app/immutable/nodes/5.Ce6v0yql.js.gz +0 -0
- package/build/client/_app/immutable/nodes/6.TFeDtO3j.js +1 -0
- package/build/client/_app/immutable/nodes/6.TFeDtO3j.js.br +0 -0
- package/build/client/_app/immutable/nodes/6.TFeDtO3j.js.gz +0 -0
- package/build/client/_app/immutable/nodes/{7.CjIXEVDA.js → 7.CTdUnooR.js} +1 -1
- package/build/client/_app/immutable/nodes/7.CTdUnooR.js.br +0 -0
- package/build/client/_app/immutable/nodes/7.CTdUnooR.js.gz +0 -0
- package/build/client/_app/immutable/nodes/{8.CZTZwY1d.js → 8.CeF7Yj23.js} +2 -2
- package/build/client/_app/immutable/nodes/8.CeF7Yj23.js.br +0 -0
- package/build/client/_app/immutable/nodes/8.CeF7Yj23.js.gz +0 -0
- package/build/client/_app/immutable/nodes/9.Bxpo8jgd.js +1 -0
- package/build/client/_app/immutable/nodes/9.Bxpo8jgd.js.br +0 -0
- package/build/client/_app/immutable/nodes/9.Bxpo8jgd.js.gz +0 -0
- package/build/client/_app/version.json +1 -1
- package/build/client/_app/version.json.br +0 -0
- package/build/client/_app/version.json.gz +0 -0
- package/build/server/.vite/manifest.json +29 -22
- package/build/server/_app/immutable/assets/_layout.EoCnujqq.css +2 -0
- package/build/server/_app/immutable/assets/_page.BD9df-LS.css +1 -0
- package/build/server/chunks/AppHeader.js +1 -1
- package/build/server/chunks/SettingsMenu.js +1 -1
- package/build/server/chunks/SideNav.js +1 -1
- package/build/server/chunks/instance.js +3 -3
- package/build/server/chunks/internal.js +1 -1
- package/build/server/chunks/package.js +1 -1
- package/build/server/chunks/package.js.map +1 -1
- package/build/server/chunks/sse.server.js +65 -0
- package/build/server/chunks/sse.server.js.map +1 -0
- package/build/server/entries/endpoints/api/v1/solve-events/_server.ts.js +1 -51
- package/build/server/entries/endpoints/api/v1/solve-events/_server.ts.js.map +1 -1
- package/build/server/entries/hooks.server.js +3 -0
- package/build/server/entries/hooks.server.js.map +1 -1
- package/build/server/entries/pages/_layout.svelte.js +1 -0
- package/build/server/entries/pages/_layout.svelte.js.map +1 -1
- package/build/server/entries/pages/_page.svelte.js +1 -1
- package/build/server/entries/pages/accept-invite/_page.svelte.js +1 -1
- package/build/server/entries/pages/admin/_page.svelte.js +1 -1
- package/build/server/entries/pages/admin/system/_page.svelte.js +1 -1
- package/build/server/entries/pages/auth/email/sent/_page.svelte.js +1 -1
- package/build/server/entries/pages/library/_guid_/_page.svelte.js +47 -38
- package/build/server/entries/pages/library/_guid_/_page.svelte.js.map +1 -1
- package/build/server/entries/pages/login/_page.svelte.js +1 -1
- package/build/server/entries/pages/oauth/authorize/_page.svelte.js +1 -1
- package/build/server/entries/pages/projects/_page.svelte.js +1 -1
- package/build/server/entries/pages/setup/_page.svelte.js +1 -1
- package/build/server/entries/pages/team/_layout.svelte.js +1 -1
- package/build/server/entries/pages/team/compute/_page.svelte.js +1 -1
- package/build/server/entries/pages/team/tokens/_page.svelte.js +1 -1
- package/build/server/manifest-full.js +1 -1
- package/build/server/manifest.js +1 -1
- package/build/server/nodes/0.js +2 -2
- package/build/server/nodes/11.js +1 -1
- package/build/server/nodes/13.js +1 -1
- package/build/server/nodes/14.js +1 -1
- package/build/server/nodes/15.js +1 -1
- package/build/server/nodes/16.js +1 -1
- package/build/server/nodes/17.js +1 -1
- package/build/server/nodes/19.js +1 -1
- package/build/server/nodes/2.js +1 -1
- package/build/server/nodes/20.js +1 -1
- package/build/server/nodes/21.js +2 -2
- package/build/server/nodes/22.js +1 -1
- package/build/server/nodes/24.js +1 -1
- package/build/server/nodes/25.js +1 -1
- package/build/server/nodes/26.js +1 -1
- package/build/server/nodes/29.js +1 -1
- package/build/server/nodes/30.js +1 -1
- package/build/server/nodes/31.js +1 -1
- package/build/server/nodes/32.js +1 -1
- package/build/server/nodes/34.js +1 -1
- package/build/server/nodes/35.js +1 -1
- package/build/server/nodes/5.js +1 -1
- package/build/server/nodes/6.js +1 -1
- package/build/server/nodes/7.js +1 -1
- package/build/server/nodes/8.js +1 -1
- package/build/server/nodes/9.js +1 -1
- package/build/server/server.js +1 -1
- package/package.json +7 -7
- package/build/client/_app/immutable/assets/0.Cn456UtT.css +0 -2
- package/build/client/_app/immutable/assets/0.Cn456UtT.css.br +0 -0
- package/build/client/_app/immutable/assets/0.Cn456UtT.css.gz +0 -0
- package/build/client/_app/immutable/assets/21.BL3a_Clt.css +0 -1
- package/build/client/_app/immutable/assets/21.BL3a_Clt.css.br +0 -0
- package/build/client/_app/immutable/assets/21.BL3a_Clt.css.gz +0 -0
- package/build/client/_app/immutable/chunks/BD_1lGYg.js +0 -1
- package/build/client/_app/immutable/chunks/BD_1lGYg.js.br +0 -0
- package/build/client/_app/immutable/chunks/BD_1lGYg.js.gz +0 -0
- package/build/client/_app/immutable/chunks/CaBqDK26.js.br +0 -0
- package/build/client/_app/immutable/chunks/CaBqDK26.js.gz +0 -0
- package/build/client/_app/immutable/chunks/DnyaMNr8.js +0 -1
- package/build/client/_app/immutable/chunks/DnyaMNr8.js.br +0 -1
- package/build/client/_app/immutable/chunks/DnyaMNr8.js.gz +0 -0
- package/build/client/_app/immutable/chunks/JYV4ULDs.js +0 -5906
- package/build/client/_app/immutable/chunks/JYV4ULDs.js.br +0 -0
- package/build/client/_app/immutable/chunks/JYV4ULDs.js.gz +0 -0
- package/build/client/_app/immutable/chunks/sg4CWDsx.js.br +0 -0
- package/build/client/_app/immutable/chunks/sg4CWDsx.js.gz +0 -0
- package/build/client/_app/immutable/entry/app.4vLx5YtD.js +0 -2
- package/build/client/_app/immutable/entry/app.4vLx5YtD.js.br +0 -0
- package/build/client/_app/immutable/entry/app.4vLx5YtD.js.gz +0 -0
- package/build/client/_app/immutable/nodes/0.CV6qhxW5.js +0 -1
- package/build/client/_app/immutable/nodes/0.CV6qhxW5.js.br +0 -0
- package/build/client/_app/immutable/nodes/0.CV6qhxW5.js.gz +0 -0
- package/build/client/_app/immutable/nodes/11.C7QVYNzD.js +0 -5
- package/build/client/_app/immutable/nodes/11.C7QVYNzD.js.br +0 -0
- package/build/client/_app/immutable/nodes/11.C7QVYNzD.js.gz +0 -0
- package/build/client/_app/immutable/nodes/13.JNEl4w7x.js.br +0 -0
- package/build/client/_app/immutable/nodes/13.JNEl4w7x.js.gz +0 -0
- package/build/client/_app/immutable/nodes/14.CiK46T_1.js.br +0 -0
- package/build/client/_app/immutable/nodes/14.CiK46T_1.js.gz +0 -0
- package/build/client/_app/immutable/nodes/15.BfxP3BK1.js +0 -32
- package/build/client/_app/immutable/nodes/15.BfxP3BK1.js.br +0 -0
- package/build/client/_app/immutable/nodes/15.BfxP3BK1.js.gz +0 -0
- package/build/client/_app/immutable/nodes/16.CIy8Me4f.js.br +0 -0
- package/build/client/_app/immutable/nodes/16.CIy8Me4f.js.gz +0 -0
- package/build/client/_app/immutable/nodes/17.DVNUmPUk.js.br +0 -0
- package/build/client/_app/immutable/nodes/17.DVNUmPUk.js.gz +0 -0
- package/build/client/_app/immutable/nodes/19.qbUJ-ZrA.js.br +0 -0
- package/build/client/_app/immutable/nodes/19.qbUJ-ZrA.js.gz +0 -0
- package/build/client/_app/immutable/nodes/2.Db9e6NkL.js.br +0 -0
- package/build/client/_app/immutable/nodes/2.Db9e6NkL.js.gz +0 -0
- package/build/client/_app/immutable/nodes/20.a80Xph9J.js +0 -2
- package/build/client/_app/immutable/nodes/20.a80Xph9J.js.br +0 -0
- package/build/client/_app/immutable/nodes/20.a80Xph9J.js.gz +0 -0
- package/build/client/_app/immutable/nodes/21.BUIhwaFc.js +0 -1
- package/build/client/_app/immutable/nodes/21.BUIhwaFc.js.br +0 -0
- package/build/client/_app/immutable/nodes/21.BUIhwaFc.js.gz +0 -0
- package/build/client/_app/immutable/nodes/22.AhwAEf2A.js.br +0 -0
- package/build/client/_app/immutable/nodes/22.AhwAEf2A.js.gz +0 -0
- package/build/client/_app/immutable/nodes/24.C8JSt6Pa.js +0 -3
- package/build/client/_app/immutable/nodes/24.C8JSt6Pa.js.br +0 -0
- package/build/client/_app/immutable/nodes/24.C8JSt6Pa.js.gz +0 -0
- package/build/client/_app/immutable/nodes/25.Cqalaz7Y.js.br +0 -0
- package/build/client/_app/immutable/nodes/25.Cqalaz7Y.js.gz +0 -0
- package/build/client/_app/immutable/nodes/26.CnBEBmQb.js.br +0 -0
- package/build/client/_app/immutable/nodes/26.CnBEBmQb.js.gz +0 -0
- package/build/client/_app/immutable/nodes/29.DUg4JvmM.js +0 -4
- package/build/client/_app/immutable/nodes/29.DUg4JvmM.js.br +0 -0
- package/build/client/_app/immutable/nodes/29.DUg4JvmM.js.gz +0 -0
- package/build/client/_app/immutable/nodes/30.DsE9EPUe.js +0 -6
- package/build/client/_app/immutable/nodes/30.DsE9EPUe.js.br +0 -0
- package/build/client/_app/immutable/nodes/30.DsE9EPUe.js.gz +0 -0
- package/build/client/_app/immutable/nodes/31.HMdYYOC6.js +0 -2
- package/build/client/_app/immutable/nodes/31.HMdYYOC6.js.br +0 -0
- package/build/client/_app/immutable/nodes/31.HMdYYOC6.js.gz +0 -0
- package/build/client/_app/immutable/nodes/32.Csmqk0LJ.js.br +0 -0
- package/build/client/_app/immutable/nodes/32.Csmqk0LJ.js.gz +0 -0
- package/build/client/_app/immutable/nodes/34.KdJfmmfc.js.br +0 -0
- package/build/client/_app/immutable/nodes/34.KdJfmmfc.js.gz +0 -0
- package/build/client/_app/immutable/nodes/35.CiAaE31k.js +0 -5
- package/build/client/_app/immutable/nodes/35.CiAaE31k.js.br +0 -0
- package/build/client/_app/immutable/nodes/35.CiAaE31k.js.gz +0 -0
- package/build/client/_app/immutable/nodes/5.CAzzdmQi.js.br +0 -0
- package/build/client/_app/immutable/nodes/5.CAzzdmQi.js.gz +0 -0
- package/build/client/_app/immutable/nodes/6.f6QtDg9y.js +0 -1
- package/build/client/_app/immutable/nodes/6.f6QtDg9y.js.br +0 -0
- package/build/client/_app/immutable/nodes/6.f6QtDg9y.js.gz +0 -0
- package/build/client/_app/immutable/nodes/7.CjIXEVDA.js.br +0 -0
- package/build/client/_app/immutable/nodes/7.CjIXEVDA.js.gz +0 -0
- package/build/client/_app/immutable/nodes/8.CZTZwY1d.js.br +0 -0
- package/build/client/_app/immutable/nodes/8.CZTZwY1d.js.gz +0 -0
- package/build/client/_app/immutable/nodes/9.DxhpY6Zo.js +0 -1
- package/build/client/_app/immutable/nodes/9.DxhpY6Zo.js.br +0 -0
- package/build/client/_app/immutable/nodes/9.DxhpY6Zo.js.gz +0 -0
- package/build/server/_app/immutable/assets/_layout.Cn456UtT.css +0 -2
- package/build/server/_app/immutable/assets/_page.CnHXQXAS.css +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"_server.ts.js","names":[],"sources":["../../../../../../../src/
|
|
1
|
+
{"version":3,"file":"_server.ts.js","names":[],"sources":["../../../../../../../src/routes/api/v1/solve-events/+server.ts"],"sourcesContent":["import type { RequestHandler } from './$types';\nimport { withApiRateLimit } from '#lib/server/api/sveltekit.js';\nimport { apiError, ApiErrorCode } from '#lib/server/api-errors.js';\nimport { getSolveEventBus } from '#lib/server/solveEvents/bus.server.js';\nimport { liveOwnerKey } from '#lib/server/solveEvents/liveSolve.server.js';\nimport { openSolveEventStream } from '#lib/server/solveEvents/sse.server.js';\nimport { asHttpError } from '#lib/server/access.server.js';\nimport { assertScopeAnywhere } from '@selvajs/server/api';\n\n// One SSE stream per browser tab. The tab mints `streamId` and sends it with every\n// solve request; the server routes that solve's events here. Self-gating (the hook\n// does not deny it) because the sibling callback route under the same prefix has no\n// session at all — this route still requires one.\n\nconst STREAM_ID = /^[A-Za-z0-9_-]{16,64}$/;\n\nexport const GET: RequestHandler = withApiRateLimit(async ({ url, locals, request }) => {\n\tconst ownerKey = liveOwnerKey(locals.user?.id);\n\tif (!ownerKey) apiError(401, ApiErrorCode.UNAUTHORIZED, 'Unauthorized');\n\tawait asHttpError(() => assertScopeAnywhere(locals.ctx, 'read'));\n\n\tconst streamId = url.searchParams.get('streamId') ?? '';\n\tif (!STREAM_ID.test(streamId)) {\n\t\tapiError(400, ApiErrorCode.VALIDATION_FAILED, 'streamId must be 16-64 URL-safe characters');\n\t}\n\n\tconst response = openSolveEventStream({\n\t\tbus: getSolveEventBus(),\n\t\tstreamId,\n\t\townerKey,\n\t\tsignal: request.signal\n\t});\n\tif (!response) apiError(409, ApiErrorCode.CONFLICT, 'streamId is in use');\n\treturn response;\n});\n"],"mappings":";;;;;;;;;AAcA,IAAM,YAAY;AAElB,IAAa,MAAsB,iBAAiB,OAAO,EAAE,KAAK,QAAQ,cAAc;CACvF,MAAM,WAAW,aAAa,OAAO,MAAM,EAAE;CAC7C,IAAI,CAAC,UAAU,SAAS,KAAK,aAAa,cAAc,cAAc;CACtE,MAAM,kBAAkB,oBAAoB,OAAO,KAAK,MAAM,CAAC;CAE/D,MAAM,WAAW,IAAI,aAAa,IAAI,UAAU,KAAK;CACrD,IAAI,CAAC,UAAU,KAAK,QAAQ,GAC3B,SAAS,KAAK,aAAa,mBAAmB,4CAA4C;CAG3F,MAAM,WAAW,qBAAqB;EACrC,KAAK,iBAAiB;EACtB;EACA;EACA,QAAQ,QAAQ;CACjB,CAAC;CACD,IAAI,CAAC,UAAU,SAAS,KAAK,aAAa,UAAU,oBAAoB;CACxE,OAAO;AACR,CAAC"}
|
|
@@ -13,6 +13,7 @@ import { t as requestMemo } from "../chunks/requestMemo.server.js";
|
|
|
13
13
|
import { n as apiTokenResolutions, t as apiTokenCodec } from "../chunks/token2.server.js";
|
|
14
14
|
import { t as getBootHealth } from "../chunks/bootHealth.server.js";
|
|
15
15
|
import { r as signInMaxAgeMs } from "../chunks/signInMaxAge.server.js";
|
|
16
|
+
import { t as closeAllSolveEventStreams } from "../chunks/sse.server.js";
|
|
16
17
|
import { n as wireHeaderAuthBootstrap, t as bootstrapUserSession } from "../chunks/auth-bootstrap.server.js";
|
|
17
18
|
import { redirect } from "@sveltejs/kit";
|
|
18
19
|
import { randomUUID } from "node:crypto";
|
|
@@ -503,6 +504,8 @@ var proxyAuthLoginMissWarned = false;
|
|
|
503
504
|
var init = () => {
|
|
504
505
|
checkConfigAtBoot();
|
|
505
506
|
requestTiming.markBooted();
|
|
507
|
+
process.once("SIGINT", closeAllSolveEventStreams);
|
|
508
|
+
process.once("SIGTERM", closeAllSolveEventStreams);
|
|
506
509
|
};
|
|
507
510
|
var firstRunResolved = false;
|
|
508
511
|
async function isFirstRun() {
|
|
@@ -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/bounded-ttl-cache.ts","../../../../server/src/http/session-refresher.ts","../../../../server/src/http/session-resolver.ts","../../../../server/src/http/request-timing.ts","../../../src/lib/server/mcp/path.ts","../../../src/lib/server/requestTiming.server.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","// Process-local TTL cache with a hard entry cap.\n//\n// Sweeping is amortized onto `set` rather than driven by a timer: a timer would\n// keep the event loop alive and give this module a lifecycle its callers — plain\n// module-level singletons — do not have.\n//\n// Values are stored as-is. A caller that caches failures alongside successes\n// encodes both in ONE value type and gives each its own TTL at the `set` call,\n// rather than this holding a success/error union it would have to interpret.\n\nexport interface BoundedTtlCacheConfig {\n\t/** Max retained entries. Once full, expired entries go first, then oldest-inserted. */\n\tmaxEntries: number;\n}\n\nexport interface BoundedTtlCache<T> {\n\t/** The live value, or `undefined` when absent or expired. Expired entries are dropped on read. */\n\tget(key: string): T | undefined;\n\t/** Store `value` under `key`, expiring `ttlMs` from now. Re-inserting a key refreshes its insertion order. */\n\tset(key: string, value: T, ttlMs: number): void;\n\tdelete(key: string): void;\n\t/** Test seam and force-refresh gestures. */\n\tclear(): void;\n\t/** Retained entries, including any expired but not yet swept. For tests/observability. */\n\tsize(): number;\n}\n\ninterface Entry<T> {\n\tvalue: T;\n\texpiresAt: number;\n}\n\nexport function createBoundedTtlCache<T>(config: BoundedTtlCacheConfig): BoundedTtlCache<T> {\n\tconst maxEntries = Math.max(1, Math.floor(config.maxEntries));\n\tconst entries = new Map<string, Entry<T>>();\n\n\tfunction evictIfFull(now: number): void {\n\t\tif (entries.size < maxEntries) return;\n\t\tfor (const [key, entry] of entries) {\n\t\t\tif (entry.expiresAt <= now) entries.delete(key);\n\t\t}\n\t\t// Map preserves insertion order, so the first key is the oldest-inserted.\n\t\twhile (entries.size >= maxEntries) {\n\t\t\tconst oldest = entries.keys().next().value;\n\t\t\tif (oldest === undefined) break;\n\t\t\tentries.delete(oldest);\n\t\t}\n\t}\n\n\treturn {\n\t\tget(key) {\n\t\t\tconst entry = entries.get(key);\n\t\t\tif (!entry) return undefined;\n\t\t\tif (entry.expiresAt <= Date.now()) {\n\t\t\t\tentries.delete(key);\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t\treturn entry.value;\n\t\t},\n\t\tset(key, value, ttlMs) {\n\t\t\t// Delete first so a re-insert moves the key to the end of the insertion\n\t\t\t// order — otherwise a hot key keeps its original position and is evicted\n\t\t\t// while colder, newer keys survive.\n\t\t\tentries.delete(key);\n\t\t\tevictIfFull(Date.now());\n\t\t\tentries.set(key, { value, expiresAt: Date.now() + ttlMs });\n\t\t},\n\t\tdelete(key) {\n\t\t\tentries.delete(key);\n\t\t},\n\t\tclear() {\n\t\t\tentries.clear();\n\t\t},\n\t\tsize() {\n\t\t\treturn entries.size;\n\t\t}\n\t};\n}\n","import type { IAuthProvider, ISessionRefresh } from '@selvajs/platform';\nimport { createBoundedTtlCache } from './bounded-ttl-cache.js';\nimport { signInIsStale } from './sign-in-age.js';\n\ntype SessionPair = NonNullable<Awaited<ReturnType<ISessionRefresh['refreshSession']>>>;\n\n/** Long enough for the requests of one page load that left before the new cookie landed. */\nconst RECENT_PAIR_TTL_MS = 10_000;\nconst RECENT_PAIR_MAX = 1_000;\n\nexport type SessionRefresher = (refreshToken: string) => Promise<SessionPair | null>;\n\nexport interface SessionRefresherOptions {\n\t/**\n\t * Refuse a refresh once the user's last real sign-in is older than this\n\t * (see `resolveSignInMaxAgeMs`). A provider's refresh never asks the\n\t * identity provider again, so without it a session outlives the account.\n\t */\n\tsignInMaxAgeMs?: number;\n\tauth?: () => Pick<IAuthProvider, 'verifyToken' | 'getUser'>;\n\tnow?: () => number;\n}\n\n/**\n * A page's parallel requests all arrive with the same expired session and the same refresh token,\n * and a provider may rotate that token on first use. Each request exchanging it alone would see\n * every one after the first refused, read that as a dead session, and clear the cookie: a signed-in\n * user logged out by loading a page. So they share one exchange and its answer.\n *\n * `getRefresh` is read per exchange so a host can swap providers. One per process.\n */\nexport function createSessionRefresher(\n\tgetRefresh: () => ISessionRefresh | undefined,\n\t{ signInMaxAgeMs, auth, now = Date.now }: SessionRefresherOptions = {}\n): SessionRefresher {\n\tconst inflight = new Map<string, Promise<SessionPair | null>>();\n\tconst recent = createBoundedTtlCache<SessionPair>({ maxEntries: RECENT_PAIR_MAX });\n\n\t// Only a user we could read counts as lapsed: a failed lookup must not sign\n\t// someone out on every device. API tokens are checked on their own path.\n\tasync function signInLapsed(pair: SessionPair): Promise<boolean> {\n\t\tif (!signInMaxAgeMs || !auth) return false;\n\t\ttry {\n\t\t\tconst provider = auth();\n\t\t\tconst session = await provider.verifyToken(pair.sessionToken);\n\t\t\tconst user = session && (await provider.getUser(session.id));\n\t\t\treturn !!user && signInIsStale(user.lastLoginAt, signInMaxAgeMs, now());\n\t\t} catch {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tasync function exchange(refreshToken: string) {\n\t\tconst refresh = getRefresh();\n\t\tconst pair = (await refresh?.refreshSession(refreshToken)) ?? null;\n\t\tif (pair && (await signInLapsed(pair))) {\n\t\t\tawait refresh?.revokeSession(pair.sessionToken).catch(() => false);\n\t\t\treturn null;\n\t\t}\n\t\tif (pair) recent.set(refreshToken, pair, RECENT_PAIR_TTL_MS);\n\t\treturn pair;\n\t}\n\n\treturn (refreshToken) => {\n\t\tconst done = recent.get(refreshToken);\n\t\tif (done) return Promise.resolve(done);\n\t\tlet pending = inflight.get(refreshToken);\n\t\tif (!pending) {\n\t\t\tpending = exchange(refreshToken).finally(() => inflight.delete(refreshToken));\n\t\t\tinflight.set(refreshToken, pending);\n\t\t}\n\t\treturn pending;\n\t};\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","// Its own module: the hook needs the path on every request, and importing it from `server.ts`\n// would load the MCP SDK and the OpenAPI builder at boot.\nexport const MCP_PATH = '/mcp';\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","import { redirect, type RequestEvent } from '@sveltejs/kit';\nimport type { ServerInit } from '@sveltejs/kit/hooks';\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 {\n\tproviders,\n\tflag,\n\tgetErrorReporter,\n\tgetEventSink,\n\tgetLogger,\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_PATH } from '#lib/server/mcp/path.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 { publicUrl } from '#lib/server/origin.js';\nimport { findDeploymentDir, startUpdateOutcomeReconciler } from '#lib/server/selfUpdate.server.js';\nimport {\n\tbootstrapUserSession,\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};\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). Nothing else under\n\t// `/api/*` carries its own authorization.\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\tselfGatingPrefixes: ['/api/files/', '/api/v1/solve-events'],\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// 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 = () => requestMemo.run(event.request.method, () => gate(input));\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\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!import.meta.env.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\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\tif (!user && providers.auth.proxyAuth) {\n\t\t\tuser = await providers.auth.proxyAuth.identifyFromHeaders(event.request.headers);\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);\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(pathname + event.url.search)}`);\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. App routes must stay\n// framable (embedding is what Selva-engine apps are for), but the operator\n// surfaces below hold an authenticated admin session, where a framable page is\n// a UI-redress attack.\nconst FRAME_DENIED_PREFIXES = ['/admin', '/setup', '/login', '/oauth'];\n\nfunction deniesFraming(pathname: string): boolean {\n\treturn FRAME_DENIED_PREFIXES.some((p) => pathname === p || pathname.startsWith(`${p}/`));\n}\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 (\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\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,QAA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,OAAO,iBAAiB,SAAS,MAAM,QAAQ,OAAO,MAAM,KAAK,IAAI,KAAA;CACtE,CAAC;CAID,iBAAiB,CAAC,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
|
+
{"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/bounded-ttl-cache.ts","../../../../server/src/http/session-refresher.ts","../../../../server/src/http/session-resolver.ts","../../../../server/src/http/request-timing.ts","../../../src/lib/server/mcp/path.ts","../../../src/lib/server/requestTiming.server.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","// Process-local TTL cache with a hard entry cap.\n//\n// Sweeping is amortized onto `set` rather than driven by a timer: a timer would\n// keep the event loop alive and give this module a lifecycle its callers — plain\n// module-level singletons — do not have.\n//\n// Values are stored as-is. A caller that caches failures alongside successes\n// encodes both in ONE value type and gives each its own TTL at the `set` call,\n// rather than this holding a success/error union it would have to interpret.\n\nexport interface BoundedTtlCacheConfig {\n\t/** Max retained entries. Once full, expired entries go first, then oldest-inserted. */\n\tmaxEntries: number;\n}\n\nexport interface BoundedTtlCache<T> {\n\t/** The live value, or `undefined` when absent or expired. Expired entries are dropped on read. */\n\tget(key: string): T | undefined;\n\t/** Store `value` under `key`, expiring `ttlMs` from now. Re-inserting a key refreshes its insertion order. */\n\tset(key: string, value: T, ttlMs: number): void;\n\tdelete(key: string): void;\n\t/** Test seam and force-refresh gestures. */\n\tclear(): void;\n\t/** Retained entries, including any expired but not yet swept. For tests/observability. */\n\tsize(): number;\n}\n\ninterface Entry<T> {\n\tvalue: T;\n\texpiresAt: number;\n}\n\nexport function createBoundedTtlCache<T>(config: BoundedTtlCacheConfig): BoundedTtlCache<T> {\n\tconst maxEntries = Math.max(1, Math.floor(config.maxEntries));\n\tconst entries = new Map<string, Entry<T>>();\n\n\tfunction evictIfFull(now: number): void {\n\t\tif (entries.size < maxEntries) return;\n\t\tfor (const [key, entry] of entries) {\n\t\t\tif (entry.expiresAt <= now) entries.delete(key);\n\t\t}\n\t\t// Map preserves insertion order, so the first key is the oldest-inserted.\n\t\twhile (entries.size >= maxEntries) {\n\t\t\tconst oldest = entries.keys().next().value;\n\t\t\tif (oldest === undefined) break;\n\t\t\tentries.delete(oldest);\n\t\t}\n\t}\n\n\treturn {\n\t\tget(key) {\n\t\t\tconst entry = entries.get(key);\n\t\t\tif (!entry) return undefined;\n\t\t\tif (entry.expiresAt <= Date.now()) {\n\t\t\t\tentries.delete(key);\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t\treturn entry.value;\n\t\t},\n\t\tset(key, value, ttlMs) {\n\t\t\t// Delete first so a re-insert moves the key to the end of the insertion\n\t\t\t// order — otherwise a hot key keeps its original position and is evicted\n\t\t\t// while colder, newer keys survive.\n\t\t\tentries.delete(key);\n\t\t\tevictIfFull(Date.now());\n\t\t\tentries.set(key, { value, expiresAt: Date.now() + ttlMs });\n\t\t},\n\t\tdelete(key) {\n\t\t\tentries.delete(key);\n\t\t},\n\t\tclear() {\n\t\t\tentries.clear();\n\t\t},\n\t\tsize() {\n\t\t\treturn entries.size;\n\t\t}\n\t};\n}\n","import type { IAuthProvider, ISessionRefresh } from '@selvajs/platform';\nimport { createBoundedTtlCache } from './bounded-ttl-cache.js';\nimport { signInIsStale } from './sign-in-age.js';\n\ntype SessionPair = NonNullable<Awaited<ReturnType<ISessionRefresh['refreshSession']>>>;\n\n/** Long enough for the requests of one page load that left before the new cookie landed. */\nconst RECENT_PAIR_TTL_MS = 10_000;\nconst RECENT_PAIR_MAX = 1_000;\n\nexport type SessionRefresher = (refreshToken: string) => Promise<SessionPair | null>;\n\nexport interface SessionRefresherOptions {\n\t/**\n\t * Refuse a refresh once the user's last real sign-in is older than this\n\t * (see `resolveSignInMaxAgeMs`). A provider's refresh never asks the\n\t * identity provider again, so without it a session outlives the account.\n\t */\n\tsignInMaxAgeMs?: number;\n\tauth?: () => Pick<IAuthProvider, 'verifyToken' | 'getUser'>;\n\tnow?: () => number;\n}\n\n/**\n * A page's parallel requests all arrive with the same expired session and the same refresh token,\n * and a provider may rotate that token on first use. Each request exchanging it alone would see\n * every one after the first refused, read that as a dead session, and clear the cookie: a signed-in\n * user logged out by loading a page. So they share one exchange and its answer.\n *\n * `getRefresh` is read per exchange so a host can swap providers. One per process.\n */\nexport function createSessionRefresher(\n\tgetRefresh: () => ISessionRefresh | undefined,\n\t{ signInMaxAgeMs, auth, now = Date.now }: SessionRefresherOptions = {}\n): SessionRefresher {\n\tconst inflight = new Map<string, Promise<SessionPair | null>>();\n\tconst recent = createBoundedTtlCache<SessionPair>({ maxEntries: RECENT_PAIR_MAX });\n\n\t// Only a user we could read counts as lapsed: a failed lookup must not sign\n\t// someone out on every device. API tokens are checked on their own path.\n\tasync function signInLapsed(pair: SessionPair): Promise<boolean> {\n\t\tif (!signInMaxAgeMs || !auth) return false;\n\t\ttry {\n\t\t\tconst provider = auth();\n\t\t\tconst session = await provider.verifyToken(pair.sessionToken);\n\t\t\tconst user = session && (await provider.getUser(session.id));\n\t\t\treturn !!user && signInIsStale(user.lastLoginAt, signInMaxAgeMs, now());\n\t\t} catch {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tasync function exchange(refreshToken: string) {\n\t\tconst refresh = getRefresh();\n\t\tconst pair = (await refresh?.refreshSession(refreshToken)) ?? null;\n\t\tif (pair && (await signInLapsed(pair))) {\n\t\t\tawait refresh?.revokeSession(pair.sessionToken).catch(() => false);\n\t\t\treturn null;\n\t\t}\n\t\tif (pair) recent.set(refreshToken, pair, RECENT_PAIR_TTL_MS);\n\t\treturn pair;\n\t}\n\n\treturn (refreshToken) => {\n\t\tconst done = recent.get(refreshToken);\n\t\tif (done) return Promise.resolve(done);\n\t\tlet pending = inflight.get(refreshToken);\n\t\tif (!pending) {\n\t\t\tpending = exchange(refreshToken).finally(() => inflight.delete(refreshToken));\n\t\t\tinflight.set(refreshToken, pending);\n\t\t}\n\t\treturn pending;\n\t};\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","// Its own module: the hook needs the path on every request, and importing it from `server.ts`\n// would load the MCP SDK and the OpenAPI builder at boot.\nexport const MCP_PATH = '/mcp';\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","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 {\n\tproviders,\n\tflag,\n\tgetErrorReporter,\n\tgetEventSink,\n\tgetLogger,\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_PATH } from '#lib/server/mcp/path.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 { 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\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\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}\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). Nothing else under\n\t// `/api/*` carries its own authorization.\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\tselfGatingPrefixes: ['/api/files/', '/api/v1/solve-events'],\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// 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 = () => requestMemo.run(event.request.method, () => gate(input));\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\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!import.meta.env.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\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\tif (!user && providers.auth.proxyAuth) {\n\t\t\tuser = await providers.auth.proxyAuth.identifyFromHeaders(event.request.headers);\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);\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(pathname + event.url.search)}`);\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. App routes must stay\n// framable (embedding is what Selva-engine apps are for), but the operator\n// surfaces below hold an authenticated admin session, where a framable page is\n// a UI-redress attack.\nconst FRAME_DENIED_PREFIXES = ['/admin', '/setup', '/login', '/oauth'];\n\nfunction deniesFraming(pathname: string): boolean {\n\treturn FRAME_DENIED_PREFIXES.some((p) => pathname === p || pathname.startsWith(`${p}/`));\n}\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 (\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\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;CACl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o as derivedMode } fro
|
|
|
3
3
|
import { r as on } from "../../chunks/events.js";
|
|
4
4
|
import { a as createSubscriber } from "../../chunks/index-server.js";
|
|
5
5
|
import "../../chunks/index-server2.js";
|
|
6
|
+
import "../../chunks/state.js";
|
|
6
7
|
import { i as cn, r as toastState, t as SonnerState } from "../../chunks/toast-state.svelte.js";
|
|
7
8
|
// ../../node_modules/.pnpm/svelte-sonner@1.2.2_svelte@5.57.3_@typescript-eslint+types@8.72.1_/node_modules/svelte-sonner/dist/Loader.svelte
|
|
8
9
|
var bars = Array(12).fill(0);
|