@selvajs/selva 4.20.1-beta.2 → 4.20.1-beta.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/adapter-node.js +1 -1
- package/build/client/_app/immutable/chunks/{D-SwRD80.js → D-uUm_OB.js} +43 -43
- package/build/client/_app/immutable/chunks/D-uUm_OB.js.br +0 -0
- package/build/client/_app/immutable/chunks/{D-SwRD80.js.gz → D-uUm_OB.js.gz} +0 -0
- package/build/client/_app/immutable/chunks/D84F7w9g.js +1 -0
- package/build/client/_app/immutable/chunks/D84F7w9g.js.br +1 -0
- package/build/client/_app/immutable/chunks/D84F7w9g.js.gz +0 -0
- package/build/client/_app/immutable/entry/{app.hg2qyLJU.js → app.BpT6WkO1.js} +2 -2
- package/build/client/_app/immutable/entry/app.BpT6WkO1.js.br +0 -0
- package/build/client/_app/immutable/entry/app.BpT6WkO1.js.gz +0 -0
- package/build/client/_app/immutable/nodes/21.BkNlRItr.js +1 -0
- package/build/client/_app/immutable/nodes/21.BkNlRItr.js.br +0 -0
- package/build/client/_app/immutable/nodes/21.BkNlRItr.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 +9 -2
- package/build/server/chunks/access.js +0 -3
- package/build/server/chunks/access.js.map +1 -1
- package/build/server/chunks/definitions.js +178 -1
- package/build/server/chunks/definitions.js.map +1 -1
- package/build/server/chunks/handlers.js +4 -5
- package/build/server/chunks/handlers.js.map +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/providers.server.js +89 -188
- package/build/server/chunks/providers.server.js.map +1 -1
- package/build/server/chunks/registry.js +3 -3
- package/build/server/chunks/registry.js.map +1 -1
- package/build/server/chunks/resolve.server.js +1 -1
- package/build/server/chunks/server-config-write.js +13 -1
- package/build/server/chunks/server-config-write.js.map +1 -1
- package/build/server/entries/endpoints/api/admin/compute/_server.ts.js +30 -48
- package/build/server/entries/endpoints/api/admin/compute/_server.ts.js.map +1 -1
- package/build/server/entries/endpoints/api/admin/compute/actions/_server.ts.js +3 -2
- package/build/server/entries/endpoints/api/admin/compute/actions/_server.ts.js.map +1 -1
- package/build/server/entries/endpoints/api/admin/compute/status/_server.ts.js +3 -2
- package/build/server/entries/endpoints/api/admin/compute/status/_server.ts.js.map +1 -1
- package/build/server/entries/endpoints/api/admin/projects/_id_/_server.ts.js +3 -2
- package/build/server/entries/endpoints/api/admin/projects/_id_/_server.ts.js.map +1 -1
- package/build/server/entries/endpoints/api/admin/users/_server.ts.js +6 -2
- package/build/server/entries/endpoints/api/admin/users/_server.ts.js.map +1 -1
- package/build/server/entries/endpoints/api/files/_...path_/_server.ts.js +8 -8
- package/build/server/entries/endpoints/api/files/_...path_/_server.ts.js.map +1 -1
- package/build/server/entries/endpoints/api/v1/compute/_server.ts.js +1 -1
- package/build/server/entries/endpoints/api/v1/definitions/_guid_/solve/_server.ts.js +1 -1
- package/build/server/entries/endpoints/docs/api/openapi.yaml/_server.ts.js +1 -1
- package/build/server/entries/hooks.server.js +13 -1
- package/build/server/entries/hooks.server.js.map +1 -1
- package/build/server/entries/pages/library/_guid_/_page.server.ts.js +16 -3
- package/build/server/entries/pages/library/_guid_/_page.server.ts.js.map +1 -1
- package/build/server/entries/pages/library/_guid_/_page.svelte.js +132 -89
- package/build/server/entries/pages/library/_guid_/_page.svelte.js.map +1 -1
- package/build/server/manifest-full.js +1 -1
- package/build/server/manifest.js +1 -1
- package/build/server/nodes/21.js +1 -1
- package/build/server/server.js +1 -1
- package/package.json +11 -11
- package/build/client/_app/immutable/chunks/D-SwRD80.js.br +0 -0
- package/build/client/_app/immutable/chunks/Dvq2vJj6.js +0 -1
- package/build/client/_app/immutable/chunks/Dvq2vJj6.js.br +0 -1
- package/build/client/_app/immutable/chunks/Dvq2vJj6.js.gz +0 -0
- package/build/client/_app/immutable/entry/app.hg2qyLJU.js.br +0 -0
- package/build/client/_app/immutable/entry/app.hg2qyLJU.js.gz +0 -0
- package/build/client/_app/immutable/nodes/21.gGT7QEb1.js +0 -1
- package/build/client/_app/immutable/nodes/21.gGT7QEb1.js.br +0 -1
- package/build/client/_app/immutable/nodes/21.gGT7QEb1.js.gz +0 -0
|
@@ -11,6 +11,8 @@ import { d as setSessionCookie, o as getRefreshToken, r as clearRefreshCookie, u
|
|
|
11
11
|
import { t as requestMemo } from "../chunks/requestMemo.server.js";
|
|
12
12
|
import { n as apiTokenResolutions, t as apiTokenCodec } from "../chunks/token2.server.js";
|
|
13
13
|
import { t as getBootHealth } from "../chunks/bootHealth.server.js";
|
|
14
|
+
import { n as looksLikeShareToken } from "../chunks/token3.server.js";
|
|
15
|
+
import { t as readShareToken } from "../chunks/resolve.server.js";
|
|
14
16
|
import { r as signInMaxAgeMs } from "../chunks/signInMaxAge.server.js";
|
|
15
17
|
import { t as closeAllSolveEventStreams } from "../chunks/sse.server.js";
|
|
16
18
|
import { n as wireHeaderAuthBootstrap, t as bootstrapUserSession } from "../chunks/auth-bootstrap.server.js";
|
|
@@ -509,6 +511,15 @@ var { isStaticAsset, isSelfGatingApiRoute, isPublicRoute } = createRouteClassifi
|
|
|
509
511
|
staticPrefixes: ["/_app/", "/favicon/"],
|
|
510
512
|
staticPaths: ["/favicon.svg", "/robots.txt"]
|
|
511
513
|
});
|
|
514
|
+
var SHARE_TOKEN_API = "/api/v1/compute";
|
|
515
|
+
var SHARE_TOKEN_PAGE = /^\/library\/[^/]+$/;
|
|
516
|
+
function carriesShareToken(request, url) {
|
|
517
|
+
return (url.pathname === SHARE_TOKEN_API || SHARE_TOKEN_PAGE.test(url.pathname) && url.searchParams.get("channel") !== "draft" && !url.searchParams.has("version")) && readShareToken(request, url) !== null;
|
|
518
|
+
}
|
|
519
|
+
function withoutShareToken(url) {
|
|
520
|
+
const query = new URLSearchParams([...url.searchParams].filter(([key, value]) => !(key === "token" && looksLikeShareToken(value)))).toString();
|
|
521
|
+
return url.pathname + (query ? `?${query}` : "");
|
|
522
|
+
}
|
|
512
523
|
var handle = (input) => {
|
|
513
524
|
const { event } = input;
|
|
514
525
|
const run = () => requestMemo.run(event.request.method, () => gate(input));
|
|
@@ -613,6 +624,7 @@ var gate = async ({ event, resolve }) => {
|
|
|
613
624
|
user = await providers.auth.proxyAuth.identifyFromHeaders(event.request.headers);
|
|
614
625
|
if (user) await bootstrapUserSession(user);
|
|
615
626
|
}
|
|
627
|
+
if (!user && carriesShareToken(event.request, event.url)) return applyResponseHeaders(await resolve(event), pathname, requestId);
|
|
616
628
|
if (!user) {
|
|
617
629
|
if (isJsonApiRoute) return applyResponseHeaders(new Response(JSON.stringify({
|
|
618
630
|
message: "Your session has expired. Sign in again to continue.",
|
|
@@ -621,7 +633,7 @@ var gate = async ({ event, resolve }) => {
|
|
|
621
633
|
status: 401,
|
|
622
634
|
headers: { "Content-Type": "application/json" }
|
|
623
635
|
}), pathname, requestId);
|
|
624
|
-
redirect(303, `/login?redirectTo=${encodeURIComponent(
|
|
636
|
+
redirect(303, `/login?redirectTo=${encodeURIComponent(withoutShareToken(event.url))}`);
|
|
625
637
|
}
|
|
626
638
|
attachSession(event, session ?? await sessionFor(user, token));
|
|
627
639
|
} else {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"hooks.server.js","names":[],"sources":["../../../../providers/supabase/src/upstream.ts","../../../../server/src/http/security-headers.ts","../../../../server/src/http/route-classifier.ts","../../../../server/src/http/session-resolver.ts","../../../../server/src/http/request-timing.ts","../../../src/lib/server/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","/**\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;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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;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/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","/**\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 { readShareToken } from '#lib/server/shareLinks/resolve.server.js';\nimport { looksLikeShareToken } from '#lib/server/shareLinks/token.server.js';\nimport { requestMemo } from '#lib/server/requestMemo.server.js';\nimport { requestTiming } from '#lib/server/requestTiming.server.js';\n\nconst OAUTH_TOKEN_PATH = '/oauth/token';\nconst holderVerdicts = createHolderVerdictCache();\nlazyLogger.info('Sign-in max age', { component: 'auth', maxAgeMs: signInMaxAgeMs ?? 'off' });\nconst refreshSession = createSessionRefresher(() => providers.auth.sessionRefresh, {\n\tsignInMaxAgeMs,\n\tauth: () => providers.auth\n});\nimport { getBootHealth } from '#lib/server/bootHealth.server.js';\nimport { checkConfigAtBoot } from '#lib/server/config/boot.server.js';\nimport { env } from '#lib/server/env.js';\nimport { 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). The only other route that\n\t// authorizes a request itself is `/api/v1/compute` with a share token: see\n\t// `carriesShareToken`.\n\t//\n\t// No trailing slash on solve-events: the SSE route IS that path, with the\n\t// stream in a query param, so a trailing slash would deny the stream while\n\t// letting the callback (which has a solveId segment) through.\n\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// The only two routes that honour a share token. A share link is meant to work\n// without an account, so a request that carries one and has no session still\n// reaches the route, which accepts or refuses the token itself. The page serves\n// only the live pointer by token: a draft or version pick still needs a session.\nconst SHARE_TOKEN_API = '/api/v1/compute';\nconst SHARE_TOKEN_PAGE = /^\\/library\\/[^/]+$/;\n\nfunction carriesShareToken(request: Request, url: URL): boolean {\n\tconst onShareRoute =\n\t\turl.pathname === SHARE_TOKEN_API ||\n\t\t(SHARE_TOKEN_PAGE.test(url.pathname) &&\n\t\t\turl.searchParams.get('channel') !== 'draft' &&\n\t\t\t!url.searchParams.has('version'));\n\treturn onShareRoute && readShareToken(request, url) !== null;\n}\n\n// Kept out of `redirectTo`: the login URL lands in access logs and browser history.\nfunction withoutShareToken(url: URL): string {\n\tconst query = new URLSearchParams(\n\t\t[...url.searchParams].filter(([key, value]) => !(key === 'token' && looksLikeShareToken(value)))\n\t).toString();\n\treturn url.pathname + (query ? `?${query}` : '');\n}\n\n// Every request runs inside its read memo, so a layout and its page share repeated reads, and\n// inside its timing store; static assets skip the timing.\nexport const handle: import('@sveltejs/kit/hooks').Handle = (input) => {\n\tconst { event } = input;\n\tconst run = () => 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!dev &&\n\t\tisCrossSiteFormSubmission(event.request, {\n\t\t\texemptPaths: [OAUTH_TOKEN_PATH],\n\t\t\torigin: publicUrl(event.url).origin\n\t\t})\n\t) {\n\t\treturn applyResponseHeaders(\n\t\t\tnew Response(`Cross-site ${event.request.method} form submissions are forbidden`, {\n\t\t\t\tstatus: 403\n\t\t\t}),\n\t\t\tpathname,\n\t\t\trequestId\n\t\t);\n\t}\n\n\t// Static assets bypass every gate below — no auth, no first-run check.\n\tif (isStaticAsset(pathname)) {\n\t\treturn applyResponseHeaders(await resolve(event), pathname, requestId);\n\t}\n\n\t// Probes answer before any gate runs — a fresh deployment with no users yet\n\t// is still live and ready, and the first-run 503 below would tell a load\n\t// balancer (or the post-update poller) the opposite.\n\tif (pathname === '/api/health' || pathname === '/api/health/ready') {\n\t\treturn applyResponseHeaders(await resolve(event), pathname, requestId);\n\t}\n\n\t// A `selva_` key decides the request on its own: it never falls back to the\n\t// cookie, so a broken key can't quietly run as whoever is signed in.\n\t// `/mcp` carries a key but isn't under `/api/v1`, so the resolver would refuse it.\n\tconst tokenResult =\n\t\tpathname === MCP_PATH\n\t\t\t? ({ kind: 'none' } as const)\n\t\t\t: await resolveApiToken(event.request, {\n\t\t\t\t\tcodec: apiTokenCodec(),\n\t\t\t\t\tauth: providers.auth,\n\t\t\t\t\tdata: providers.data,\n\t\t\t\t\tflag,\n\t\t\t\t\tholderVerdicts,\n\t\t\t\t\tsignInMaxAgeMs,\n\t\t\t\t\tresolutionCache: apiTokenResolutions,\n\t\t\t\t\tlog: event.locals.log\n\t\t\t\t});\n\tif (tokenResult.kind === 'rejected') {\n\t\tconst { status, code, message } = tokenResult;\n\t\tconst headers: Record<string, string> = { 'Content-Type': 'application/json' };\n\t\tif (status === 401) headers['WWW-Authenticate'] = 'Bearer error=\"invalid_token\"';\n\t\treturn applyResponseHeaders(\n\t\t\tnew Response(JSON.stringify({ message, code }), { status, headers }),\n\t\t\tpathname,\n\t\t\trequestId\n\t\t);\n\t}\n\tif (tokenResult.kind === 'ok') {\n\t\tconst { user, ctx, token } = tokenResult;\n\t\tevent.locals.log = event.locals.log.child({ tokenId: token.id });\n\t\tevent.locals.user = user;\n\t\tevent.locals.ctx = ctx;\n\t\tevent.locals.profile =\n\t\t\t(await providers.data.userProfile.getProfile(SYSTEM_CONTEXT, user.id)) ??\n\t\t\temptyProfile(user.id);\n\n\t\treturn applyResponseHeaders(await resolve(event), pathname, requestId);\n\t}\n\n\tconst publicRoute = isPublicRoute(pathname);\n\t// All HTTP endpoints live under `/api/*` — distinguishes 401 JSON from a\n\t// 303 redirect.\n\tconst isJsonApiRoute = pathname.startsWith('/api/');\n\n\t// On first run (no users yet), redirect non-public traffic to /setup so a\n\t// fresh deployment lands on the bootstrap flow instead of a dead login\n\t// page. Public routes pass through unchanged.\n\tif (!publicRoute) {\n\t\tif (await isFirstRun()) {\n\t\t\tif (isJsonApiRoute) {\n\t\t\t\treturn applyResponseHeaders(\n\t\t\t\t\tnew Response(JSON.stringify({ message: 'Setup required', code: 'SETUP_REQUIRED' }), {\n\t\t\t\t\t\tstatus: 503,\n\t\t\t\t\t\theaders: { 'Content-Type': 'application/json' }\n\t\t\t\t\t}),\n\t\t\t\t\tpathname,\n\t\t\t\t\trequestId\n\t\t\t\t);\n\t\t\t}\n\t\t\tredirect(303, '/setup');\n\t\t}\n\t}\n\n\t// Deny-by-default: any non-public, non-static path requires a valid session,\n\t// unless it carries a share token the route checks itself.\n\tconst needsAuth = !publicRoute;\n\tif (needsAuth) {\n\t\tlet token = event.cookies.get('admin_session') ?? '';\n\t\tlet session = await sessions.resolve(token);\n\n\t\t// When the access token expired but a refresh token is present (Supabase\n\t\t// OAuth flow), swap silently for a fresh pair and rotate the cookies.\n\t\t// Local/HMAC sessions never set a refresh cookie, so this is a no-op there.\n\t\tif (!session) {\n\t\t\tconst refreshToken = getRefreshToken(event.cookies);\n\t\t\tif (refreshToken && providers.auth.sessionRefresh) {\n\t\t\t\tconst refreshed = await refreshSession(refreshToken);\n\t\t\t\tif (refreshed) {\n\t\t\t\t\tsetSessionCookie(event.cookies, refreshed.sessionToken);\n\t\t\t\t\tsetRefreshCookie(event.cookies, refreshed.refreshToken);\n\t\t\t\t\ttoken = refreshed.sessionToken;\n\t\t\t\t\tsession = await sessions.resolve(token);\n\t\t\t\t} else {\n\t\t\t\t\t// Refresh failed — clear the stale cookie so the next request\n\t\t\t\t\t// goes through the login flow cleanly.\n\t\t\t\t\tclearRefreshCookie(event.cookies);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Forward-proxy fallback: providers that derive identity from trusted\n\t\t// upstream-proxy signals (Caddy forward_auth, oauth2-proxy, etc.) get a\n\t\t// chance to identify the request. See IProxyAuth for the trust contract.\n\t\tlet user = session?.user ?? null;\n\t\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 && carriesShareToken(event.request, event.url)) {\n\t\t\treturn applyResponseHeaders(await resolve(event), pathname, requestId);\n\t\t}\n\n\t\tif (!user) {\n\t\t\tif (isJsonApiRoute) {\n\t\t\t\treturn applyResponseHeaders(\n\t\t\t\t\tnew Response(\n\t\t\t\t\t\tJSON.stringify({\n\t\t\t\t\t\t\tmessage: 'Your session has expired. Sign in again to continue.',\n\t\t\t\t\t\t\tcode: 'UNAUTHORIZED'\n\t\t\t\t\t\t}),\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tstatus: 401,\n\t\t\t\t\t\t\theaders: { 'Content-Type': 'application/json' }\n\t\t\t\t\t\t}\n\t\t\t\t\t),\n\t\t\t\t\tpathname,\n\t\t\t\t\trequestId\n\t\t\t\t);\n\t\t\t}\n\t\t\t// With the query: an OAuth authorize request is nothing without it.\n\t\t\tredirect(303, `/login?redirectTo=${encodeURIComponent(withoutShareToken(event.url))}`);\n\t\t}\n\n\t\tattachSession(event, session ?? (await sessionFor(user, token)));\n\t} else {\n\t\t// Public page route (e.g. `/`): best-effort session attach. If a valid\n\t\t// session cookie is present, populate locals so the UI reflects authed\n\t\t// state (nav, user chip). Failure is silent — public pages keep\n\t\t// rendering for guests. Also applies to the self-gating files proxy,\n\t\t// which needs `locals.ctx` when a session is present so org/project\n\t\t// assets resolve, while still rendering guests' public branding.\n\t\tconst isPublicPage = PUBLIC_PAGE_ROUTES.has(pathname);\n\t\tconst wantsSessionAttach = isPublicPage || isSelfGatingApiRoute(pathname);\n\t\tconst token = wantsSessionAttach ? (event.cookies.get('admin_session') ?? '') : '';\n\t\tconst session = token ? await sessions.resolve(token) : null;\n\t\tlet user = session?.user ?? null;\n\t\tif (!user && wantsSessionAttach && providers.auth.proxyAuth) {\n\t\t\tuser = await providers.auth.proxyAuth.identifyFromHeaders(event.request.headers);\n\n\t\t\tif (!user && pathname === '/login' && !proxyAuthLoginMissWarned) {\n\t\t\t\tproxyAuthLoginMissWarned = true;\n\t\t\t\tconst proxyAuth = providers.auth.proxyAuth;\n\t\t\t\tconst noHeaders = proxyAuth.hasNoIdentityHeaders(event.request.headers);\n\t\t\t\tconst configured = proxyAuth.configuredHeaderNames.join(', ');\n\t\t\t\tif (noHeaders) {\n\t\t\t\t\tevent.locals.log.warn(\n\t\t\t\t\t\t'/login was hit and NONE of the configured identity headers arrived. The ' +\n\t\t\t\t\t\t\t'forward-auth proxy is not reaching this process, or is not forwarding the ' +\n\t\t\t\t\t\t\t'configured headers. See the @selvajs/header-auth-provider README ' +\n\t\t\t\t\t\t\t'\"Verification\" section.',\n\t\t\t\t\t\t{ component: 'HeaderAuth', configuredHeaders: configured }\n\t\t\t\t\t);\n\t\t\t\t} else {\n\t\t\t\t\tevent.locals.log.warn(\n\t\t\t\t\t\t'/login was hit but the UPN header was missing or the user is not allowlisted. ' +\n\t\t\t\t\t\t\t'Some headers arrived but identification still failed — check that the UPN ' +\n\t\t\t\t\t\t\t'header is populated and that the user has been added to header-allowlist.json.',\n\t\t\t\t\t\t{ component: 'HeaderAuth', configuredHeaders: configured }\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tif (user) attachSession(event, session ?? (await sessionFor(user, token)));\n\t}\n\n\treturn applyResponseHeaders(await resolve(event), pathname, requestId);\n};\n\n// ============================================================================\n// Response headers\n// ============================================================================\n//\n// Applied to every response — successful resolves and the 401/503\n// short-circuits above. The browser-hardening set (nosniff, Referrer-Policy,\n// Permissions-Policy, HSTS in production) lives in `@selvajs/server/http` —\n// see `applySecurityHeaders` there. Cache-control stays here: it encodes this\n// app's asset layout.\n//\n// Frame headers are the one route-dependent piece. 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,KAA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AAmB,MAAM;CAAY,IAAI;CAInF,IAAI,WAAW,KAAK,GACnB,OAAO;EACN,QAAQ,MAAM;EACd,SAAS,MAAM;EACf,MAAM,MAAM;EACZ,QAAQ,MAAM;EACd,SAAS,MAAM;CAChB;CAaD,CAFC,MAAM,OAAO,OACb,UAAU,CAAC,CAAC,MAAM;EAAE,QAAQ,MAAM,QAAQ;EAAQ,OAAO,MAAM,IAAI;CAAS,CAAC,EAAA,CAC1E,MAAM,mBAAmB;EAC5B,WAAW;EACX,KAAK,aAAa,KAAK;EACvB,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,12 +1,13 @@
|
|
|
1
1
|
import { a as getComputeServerConfigStore, h as getOrganizationProvider, s as getDefinitionMeta, v as getProjectProvider, x as getStorageProvider } from "../../../../chunks/providers.server.js";
|
|
2
|
-
import { B as NoopLogger, E as scoped, h as requireCanSolve } from "../../../../chunks/access.js";
|
|
2
|
+
import { B as NoopLogger, E as scoped, M as isApiError, h as requireCanSolve } from "../../../../chunks/access.js";
|
|
3
|
+
import "../../../../chunks/api.js";
|
|
3
4
|
import { r as fetchSchemaFromCompute } from "../../../../chunks/schema-extraction.js";
|
|
4
5
|
import { n as renderThrown } from "../../../../chunks/definitions.js";
|
|
5
6
|
import "../../../../chunks/schema.js";
|
|
6
7
|
import { t as asHttpError } from "../../../../chunks/access2.server.js";
|
|
7
8
|
import { c as getClient, t as COMPUTE_DEBUG } from "../../../../chunks/engine.server.js";
|
|
8
9
|
import { t as serverResolver } from "../../../../chunks/serverResolver.server.js";
|
|
9
|
-
import {
|
|
10
|
+
import { n as tryResolveShareToken, t as readShareToken } from "../../../../chunks/resolve.server.js";
|
|
10
11
|
import { error } from "@sveltejs/kit";
|
|
11
12
|
// ../server/src/definitions/load-for-render.ts
|
|
12
13
|
var DefinitionLoadError = class extends Error {
|
|
@@ -166,7 +167,7 @@ var load = (async ({ params, locals, request, url }) => {
|
|
|
166
167
|
const clientDefUrl = `local:${guid}`;
|
|
167
168
|
let shareToken = null;
|
|
168
169
|
try {
|
|
169
|
-
const sharedAccess = channel === "live" && !explicitVersionId ? await tryResolveShareToken(request, url, guid, "live", { requireSolve: false }) : null;
|
|
170
|
+
const sharedAccess = channel === "live" && !explicitVersionId && readShareToken(request, url) !== null && !await sessionCanSolve(locals, guid) ? await tryResolveShareToken(request, url, guid, "live", { requireSolve: false }) : null;
|
|
170
171
|
if (sharedAccess) shareToken = url.searchParams.get("token");
|
|
171
172
|
else if (!locals.ctx || !locals.user) throw error(401, "Unauthorized: You must be logged in to access definitions");
|
|
172
173
|
const ctx = sharedAccess?.ctx ?? locals.ctx;
|
|
@@ -228,6 +229,18 @@ Troubleshooting:
|
|
|
228
229
|
throw err;
|
|
229
230
|
}
|
|
230
231
|
});
|
|
232
|
+
async function sessionCanSolve(locals, guid) {
|
|
233
|
+
if (!locals.ctx || !locals.user) return false;
|
|
234
|
+
const record = await getDefinitionMeta().get(locals.ctx, guid);
|
|
235
|
+
if (!record) return false;
|
|
236
|
+
try {
|
|
237
|
+
await requireCanSolve(scoped(locals), record.projectId);
|
|
238
|
+
return true;
|
|
239
|
+
} catch (err) {
|
|
240
|
+
if (isApiError(err)) return false;
|
|
241
|
+
throw err;
|
|
242
|
+
}
|
|
243
|
+
}
|
|
231
244
|
/**
|
|
232
245
|
* Resolve the owning org's logo URL for viewer branding. definition → project →
|
|
233
246
|
* org. Best-effort and self-contained: any miss or read error returns null so a
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"_page.server.ts.js","names":[],"sources":["../../../../../../../server/src/definitions/load-for-render.ts","../../../../../../src/lib/server/definitions/loadForRender.server.ts","../../../../../../src/routes/library/[guid]/+page.server.ts"],"sourcesContent":["// Given a definition record, produces everything the client needs to render its\n// form and solve it.\n//\n// Access gating is deliberately NOT done here — the calling route decides\n// whether `ctx` may load this definition, since gates differ across routes\n// (project membership, segment ownership, share-token, admin override).\n//\n// Everything stateful is injected, so any app on the engine can wire its own\n// composition root.\n\nimport type { GrasshopperClient } from '@selvajs/compute/grasshopper';\nimport { UI_SCHEMA_VERSION, type UISchema } from '@selvajs/schemas';\nimport type {\n\tComputeServerConfig,\n\tDefinitionRecord,\n\tDefinitionVersion,\n\tIDefinitionStore,\n\tIProjectStore,\n\tIStorageProvider,\n\tRequestContext\n} from '@selvajs/platform';\nimport { NoopLogger, type ILogger } from '@selvajs/platform';\nimport { fetchSchemaFromCompute } from './schema-extraction.js';\n\nexport type DefinitionChannel = 'live' | 'draft';\n\nexport interface LoadedDefinition {\n\tversion: DefinitionVersion;\n\tdefinitionSource: Uint8Array;\n\tcomputeServer: ComputeServerConfig;\n\tschema: UISchema;\n}\n\n/**\n * Classified failure modes so callers can map to appropriate HTTP status:\n * - 'data': record references a version/blob that isn't there. (400)\n * - 'missing-config': no compute server resolvable for this org/definition. (503)\n * - 'connect': compute server is configured but unreachable. (503)\n * - 'schema': compute responded but IO/schema phase failed. (500)\n */\nexport type DefinitionLoadErrorKind = 'data' | 'missing-config' | 'connect' | 'schema';\n\nexport class DefinitionLoadError extends Error {\n\tconstructor(\n\t\tpublic readonly kind: DefinitionLoadErrorKind,\n\t\tmessage: string,\n\t\tpublic readonly cause?: unknown\n\t) {\n\t\tsuper(message);\n\t\tthis.name = 'DefinitionLoadError';\n\t}\n}\n\nexport interface DefinitionLoaderDeps {\n\tstorage: Pick<IStorageProvider, 'get'>;\n\tdefinitions: Pick<IDefinitionStore, 'getVersion' | 'setVersionSchema'>;\n\tprojects: Pick<IProjectStore, 'getProject'>;\n\t/** Resolution order: definition pin → org default override → global default. */\n\tresolveServer: (\n\t\tctx: RequestContext,\n\t\torgId: string | null,\n\t\topts: { definitionPin: string | null }\n\t) => Promise<ComputeServerConfig>;\n\t/** Shared warm-client cache, keyed by server id with a definition-guid affinity header. */\n\tgetClient: (\n\t\tserver: ComputeServerConfig,\n\t\topts: { definitionGuid: string }\n\t) => Promise<{ client: GrasshopperClient }>;\n\t/** Schema extraction; defaults to `fetchSchemaFromCompute`. Injectable for tests. */\n\tfetchSchema?: (bytes: Uint8Array, server: ComputeServerConfig) => Promise<UISchema>;\n\t/**\n\t * When set, an unhealthy IO result also dumps the raw /io wire shape, making\n\t * casing/serialization mismatches visible.\n\t */\n\tcomputeDebug?: boolean;\n\t/** Legacy diagnostic sink. When set it takes the warnings below instead of `logger`. */\n\tonWarn?: (message: string, detail?: string) => void;\n\t/**\n\t * Defaults to `NoopLogger`, so a consumer that wires nothing gets silence\n\t * rather than unsolicited stdout.\n\t */\n\tlogger?: ILogger;\n}\n\nexport interface DefinitionLoadOptions {\n\t/**\n\t * For callers that read only schema STRUCTURE (input ids, `source.key`,\n\t * widget types — anything persisted at upload). A fresh cached schema then\n\t * returns without touching compute, whose multi-second connect otherwise\n\t * dominates a page resolving several definitions.\n\t *\n\t * Leave unset (the default) for anything that RENDERS a form — without\n\t * compute defaults the form shows the wrong initial values.\n\t */\n\tskipComputeDefaults?: boolean;\n}\n\nexport type DefinitionLoader = (\n\tctx: RequestContext,\n\trecord: DefinitionRecord,\n\tchannel: DefinitionChannel,\n\texplicitVersionId?: string | null,\n\toptions?: DefinitionLoadOptions\n) => Promise<LoadedDefinition>;\n\n/**\n * The returned loader resolves the `channel` pointer (live/draft) by default.\n * `explicitVersionId` renders an arbitrary historical version instead — the\n * caller MUST gate that behind edit permission, as with the draft channel.\n */\nexport function createDefinitionLoader(deps: DefinitionLoaderDeps): DefinitionLoader {\n\tconst {\n\t\tstorage,\n\t\tdefinitions,\n\t\tprojects,\n\t\tresolveServer,\n\t\tgetClient,\n\t\tfetchSchema = fetchSchemaFromCompute,\n\t\tcomputeDebug = false,\n\t\tonWarn,\n\t\tlogger = new NoopLogger()\n\t} = deps;\n\n\treturn async function loadDefinitionForRender(ctx, record, channel, explicitVersionId, options) {\n\t\tconst versionId =\n\t\t\texplicitVersionId ?? (channel === 'draft' ? record.draftVersionId : record.liveVersionId);\n\t\tif (!versionId)\n\t\t\tthrow new DefinitionLoadError(\n\t\t\t\t'data',\n\t\t\t\t`Definition '${record.guid}' has no ${channel} version`\n\t\t\t);\n\n\t\t// The server needs only the record, so it resolves while the version and file are read.\n\t\t// It is awaited after them, so a definition missing its data still fails as 'data'.\n\t\tconst pendingServer = (async (): Promise<ComputeServerConfig> => {\n\t\t\tconst project = await projects.getProject(ctx, record.projectId);\n\t\t\ttry {\n\t\t\t\treturn await resolveServer(ctx, project?.orgId ?? null, {\n\t\t\t\t\tdefinitionPin: record.computeServerId ?? null\n\t\t\t\t});\n\t\t\t} catch (err) {\n\t\t\t\tthrow new DefinitionLoadError(\n\t\t\t\t\t'missing-config',\n\t\t\t\t\t'No compute server configured for this definition',\n\t\t\t\t\terr\n\t\t\t\t);\n\t\t\t}\n\t\t})();\n\t\tpendingServer.catch(() => {});\n\n\t\tconst version = await definitions.getVersion(ctx, versionId);\n\t\tif (!version) throw new DefinitionLoadError('data', `version missing for '${record.guid}'`);\n\t\t// An explicitly requested version must belong to this definition.\n\t\tif (version.definitionId !== record.guid)\n\t\t\tthrow new DefinitionLoadError('data', `version does not belong to '${record.guid}'`);\n\n\t\tconst definitionSource = await storage.get(version.fileKey);\n\t\tif (!definitionSource)\n\t\t\tthrow new DefinitionLoadError(\n\t\t\t\t'data',\n\t\t\t\t`Definition file for '${record.guid}' not found on disk`\n\t\t\t);\n\n\t\tconst computeServer = await pendingServer;\n\n\t\t// Returning before `getClient` is the point — the connect is the cost, not\n\t\t// the `getIO` it carries. A missing or stale-format cache falls through to\n\t\t// the full path below, so the result is always a valid schema.\n\t\tif (options?.skipComputeDefaults) {\n\t\t\tconst cachedSchema = version.schema as UISchema | undefined;\n\t\t\tif (cachedSchema && isUsableCachedSchema(cachedSchema)) {\n\t\t\t\treturn { version, definitionSource, computeServer, schema: cachedSchema };\n\t\t\t}\n\t\t}\n\n\t\t// Only the client is used here (getIO); the entry's solve scheduler rides\n\t\t// along unused.\n\t\tlet client: GrasshopperClient;\n\t\ttry {\n\t\t\tclient = (await getClient(computeServer, { definitionGuid: record.guid })).client;\n\t\t} catch (err) {\n\t\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\t\tthrow new DefinitionLoadError(\n\t\t\t\t'connect',\n\t\t\t\t`Failed to connect to Rhino Compute server: ${message}`,\n\t\t\t\terr\n\t\t\t);\n\t\t}\n\n\t\ttry {\n\t\t\t// The stored schema is a disposable cache, used ONLY when its format\n\t\t\t// version matches the app's. On a mismatch (or a pre-caching row with no\n\t\t\t// schema) re-extract from compute, whose C# SchemaMigrator emits the\n\t\t\t// current format — the web side never migrates schemas itself. `getIO`\n\t\t\t// runs either way, to merge compute default values in.\n\t\t\tconst cachedSchema = version.schema as UISchema | undefined;\n\t\t\tconst freshCache = cachedSchema && isUsableCachedSchema(cachedSchema) ? cachedSchema : null;\n\t\t\tconst [definition, fetchedSchema] = await Promise.all([\n\t\t\t\tclient.getIO(definitionSource),\n\t\t\t\tfreshCache ? Promise.resolve(freshCache) : fetchSchema(definitionSource, computeServer)\n\t\t\t]);\n\n\t\t\t// Best-effort — a viewer context may lack write access, and the next\n\t\t\t// editor render or the solve-time backfill will land it. Guarded on the\n\t\t\t// current version because persisting an older format (compute plugin\n\t\t\t// behind the app) would just go stale again next render.\n\t\t\tif (!freshCache && fetchedSchema.schemaVersion === UI_SCHEMA_VERSION) {\n\t\t\t\tdefinitions.setVersionSchema(ctx, version.id, fetchedSchema).catch((err) => {\n\t\t\t\t\tif (onWarn) {\n\t\t\t\t\t\tonWarn(\n\t\t\t\t\t\t\t`[loadForRender] schema cache refresh failed for version ${version.id}: ` +\n\t\t\t\t\t\t\t\t`${err instanceof Error ? err.message : String(err)}`\n\t\t\t\t\t\t);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tlogger.warn('Schema cache refresh failed', {\n\t\t\t\t\t\tcomponent: 'loadForRender',\n\t\t\t\t\t\tversionId: version.id,\n\t\t\t\t\t\terr: err instanceof Error ? (err.stack ?? err.message) : String(err)\n\t\t\t\t\t});\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tif (!definition) {\n\t\t\t\tthrow new Error(`Failed to get definition IO — server returned undefined`);\n\t\t\t}\n\n\t\t\t// Zero inputs or reported parse/load problems mean a definition that will\n\t\t\t// render wrong without saying why: an empty ValueList whose backing GH\n\t\t\t// component didn't resolve (\"Missing Definition Objects\"), or a PascalCase\n\t\t\t// /io response the parser silently dropped to []. Warning is always on —\n\t\t\t// it only fires on the unhappy path — while the raw wire dump costs an\n\t\t\t// extra round-trip and stays behind `computeDebug`.\n\t\t\tconst ioParseErrors = (definition as { parseErrors?: unknown[] }).parseErrors ?? [];\n\t\t\tconst ioLoadErrors = (definition as { loadErrors?: unknown[] }).loadErrors ?? [];\n\t\t\tconst ioLooksBroken =\n\t\t\t\tdefinition.inputs.length === 0 || ioParseErrors.length > 0 || ioLoadErrors.length > 0;\n\t\t\tif (ioLooksBroken) {\n\t\t\t\tconst health = {\n\t\t\t\t\tinputCount: definition.inputs.length,\n\t\t\t\t\toutputCount: definition.outputs?.length,\n\t\t\t\t\tparseErrors: ioParseErrors,\n\t\t\t\t\tloadErrors: ioLoadErrors,\n\t\t\t\t\tloadWarnings: (definition as { loadWarnings?: unknown }).loadWarnings\n\t\t\t\t};\n\t\t\t\tif (onWarn) {\n\t\t\t\t\tonWarn(`[loadForRender] IO health for '${record.guid}':`, JSON.stringify(health));\n\t\t\t\t} else {\n\t\t\t\t\tlogger.warn('Definition IO looks unhealthy', {\n\t\t\t\t\t\tcomponent: 'loadForRender',\n\t\t\t\t\t\tdefinitionGuid: record.guid,\n\t\t\t\t\t\t...health\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tif (computeDebug) {\n\t\t\t\t\tconst rawIO = await client\n\t\t\t\t\t\t.getRawIO(definitionSource)\n\t\t\t\t\t\t.catch((e) => ({ error: String(e) }));\n\t\t\t\t\tconst rendered = JSON.stringify(rawIO).slice(0, 3000);\n\t\t\t\t\tif (onWarn) onWarn('[loadForRender] raw /io:', rendered);\n\t\t\t\t\telse\n\t\t\t\t\t\tlogger.debug('Raw /io wire shape', {\n\t\t\t\t\t\t\tcomponent: 'loadForRender',\n\t\t\t\t\t\t\tdefinitionGuid: record.guid,\n\t\t\t\t\t\t\trawIO: rendered\n\t\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\tversion,\n\t\t\t\tdefinitionSource,\n\t\t\t\tcomputeServer,\n\t\t\t\tschema: mergeComputeDefaults(fetchedSchema, definition.inputs)\n\t\t\t};\n\t\t} catch (err) {\n\t\t\tif (err instanceof DefinitionLoadError) throw err;\n\t\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\t\tthrow new DefinitionLoadError('schema', message, err);\n\t\t}\n\t};\n}\n\n/**\n * A cached schema is usable only if it is BOTH the current format version and\n * structurally sound. The version check alone is not enough: a compute server\n * that serialized the schema with the wrong Newtonsoft emits PascalCase keys, so\n * `schemaVersion` reads as undefined while `SchemaVersion` holds the value —\n * and a row cached during that window would otherwise be served forever, long\n * after the server was fixed. See `assertCamelCaseSchema`.\n */\nexport function isUsableCachedSchema(schema: UISchema): boolean {\n\treturn schema.schemaVersion === UI_SCHEMA_VERSION && Array.isArray(schema.inputs);\n}\n\n// Colors come back from Compute as \"r,g,b\" or \"a,r,g,b\" strings — converted to\n// hex here so the color picker can consume them directly.\nfunction mergeComputeDefaults(\n\tschema: UISchema,\n\tcomputeInputs: Array<{ id?: string; paramType?: string; default?: unknown }>\n): UISchema {\n\tif (!Array.isArray(schema.inputs)) {\n\t\tthrow new DefinitionLoadError(\n\t\t\t'schema',\n\t\t\t`Schema has no 'inputs' array (keys: ${Object.keys(schema as object)\n\t\t\t\t.slice(0, 12)\n\t\t\t\t.join(', ')}). A PascalCase shape here means compute serialized it with the wrong ` +\n\t\t\t\t`Newtonsoft — see assertCamelCaseSchema.`\n\t\t);\n\t}\n\n\tconst byParamId = new Map(computeInputs.map((input) => [input.id, input]));\n\n\treturn {\n\t\t...schema,\n\t\tinputs: schema.inputs.map((schemaInput) => {\n\t\t\tconst computeInput = byParamId.get(schemaInput.id);\n\n\t\t\tif (computeInput?.paramType === 'Color' && computeInput.default !== undefined) {\n\t\t\t\tconst toHex = (value: number) => value.toString(16).padStart(2, '0');\n\t\t\t\tconst parts = String(computeInput.default)\n\t\t\t\t\t.split(',')\n\t\t\t\t\t.map((s) => parseInt(s.trim(), 10));\n\n\t\t\t\tif (parts.length === 3) {\n\t\t\t\t\tcomputeInput.default = `#${toHex(parts[0])}${toHex(parts[1])}${toHex(parts[2])}`;\n\t\t\t\t} else if (parts.length === 4) {\n\t\t\t\t\tcomputeInput.default = `#${toHex(parts[1])}${toHex(parts[2])}${toHex(parts[3])}`;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (computeInput && computeInput.default !== undefined) {\n\t\t\t\treturn { ...schemaInput, default: computeInput.default };\n\t\t\t}\n\t\t\treturn schemaInput;\n\t\t})\n\t};\n}\n","// `@selvajs/server/definitions` owns the loading pipeline (version resolution,\n// blob fetch, schema staleness check, default merging); this wires in the\n// app's providers, compute-server resolution, and warm-client cache. Access\n// gating stays with the calling route.\n\nimport {\n\tcreateDefinitionLoader,\n\tDefinitionLoadError,\n\ttype DefinitionChannel,\n\ttype DefinitionLoadErrorKind,\n\ttype LoadedDefinition\n} from '@selvajs/server/definitions';\nimport type { DefinitionRecord, RequestContext } from '@selvajs/platform';\nimport {\n\tgetStorageProvider,\n\tgetDefinitionMeta,\n\tgetProjectProvider,\n\tgetComputeServerConfigStore\n} from '../providers.server';\nimport { serverResolver } from '../compute/serverResolver.server';\nimport { getClient, COMPUTE_DEBUG } from '../compute/engine.server';\n\nexport { DefinitionLoadError };\nexport type { DefinitionChannel, DefinitionLoadErrorKind, LoadedDefinition };\n\nexport async function loadDefinitionForRender(\n\tctx: RequestContext,\n\trecord: DefinitionRecord,\n\tchannel: DefinitionChannel,\n\texplicitVersionId?: string | null\n): Promise<LoadedDefinition> {\n\tconst load = createDefinitionLoader({\n\t\tstorage: getStorageProvider(),\n\t\tdefinitions: getDefinitionMeta(),\n\t\tprojects: getProjectProvider(),\n\t\tresolveServer: (ctx, orgId, opts) =>\n\t\t\tserverResolver.resolve(ctx, orgId, getComputeServerConfigStore(), opts),\n\t\tgetClient,\n\t\tcomputeDebug: COMPUTE_DEBUG\n\t});\n\treturn load(ctx, record, channel, explicitVersionId);\n}\n","import type { PageServerLoad } from './$types';\nimport { error } from '@sveltejs/kit';\nimport type { ILogger, RequestContext } from '@selvajs/platform';\nimport { renderThrown } from '@selvajs/server/logging';\nimport {\n\tgetDefinitionMeta,\n\tgetProjectProvider,\n\tgetOrganizationProvider\n} from '#lib/server/providers.server.js';\nimport { asHttpError, requireCanSolve, scoped } from '#lib/server/access.server.js';\nimport { tryResolveShareToken } from '#lib/server/shareLinks/resolve.server.js';\nimport { getClient } from '#lib/server/compute/engine.server.js';\nimport {\n\tloadDefinitionForRender,\n\tDefinitionLoadError\n} from '#lib/server/definitions/loadForRender.server.js';\n\nexport const load = (async ({ params, locals, request, url }) => {\n\tconst meta = getDefinitionMeta();\n\n\tconst guid = params.guid;\n\tconst channel = url.searchParams.get('channel') === 'draft' ? 'draft' : 'live';\n\t// Explicit version pick (versioning tab \"Run\"): render an arbitrary version,\n\t// not just the live/draft pointer. Editor-only, never share-token accessible.\n\tconst explicitVersionId = url.searchParams.get('version');\n\tconst clientDefUrl = `local:${guid}`;\n\t// `shareToken` is forwarded to the page so the client can include it on\n\t// subsequent /api/compute/solve calls. null = user-authenticated session.\n\tlet shareToken: string | null = null;\n\n\ttry {\n\t\t// Draft channel and explicit-version picks are editor-only — share tokens\n\t\t// are always live channel on the pointer.\n\t\tconst sharedAccess =\n\t\t\tchannel === 'live' && !explicitVersionId\n\t\t\t\t? await tryResolveShareToken(request, url, guid, 'live', { requireSolve: false })\n\t\t\t\t: null;\n\t\tif (sharedAccess) {\n\t\t\tshareToken = url.searchParams.get('token');\n\t\t} else if (!locals.ctx || !locals.user) {\n\t\t\tthrow error(401, 'Unauthorized: You must be logged in to access definitions');\n\t\t}\n\n\t\tconst ctx: RequestContext = sharedAccess?.ctx ?? locals.ctx!;\n\n\t\tconst record = await meta.get(ctx, guid);\n\t\tif (!record) throw new Error(`Definition '${guid}' not found`);\n\n\t\t// User-auth path needs the canSolve gate; token-auth was already gated.\n\t\tif (!sharedAccess) await asHttpError(() => requireCanSolve(scoped(locals), record.projectId));\n\n\t\t// Draft channel and explicit-version picks require edit permission on top\n\t\t// of solve.\n\t\tif (channel === 'draft' || explicitVersionId) {\n\t\t\tconst { requireEditableDefinition } = await import('#lib/server/access.server.js');\n\t\t\tawait asHttpError(() => requireEditableDefinition(scoped(locals), guid));\n\t\t}\n\n\t\t// Owning org's logo, for viewer branding, read beside the definition load. Same\n\t\t// `ctx` already authorized to load this definition (user session or share-token\n\t\t// ctx, which carries actingOrgId). Best-effort: a missing project/org or read\n\t\t// failure just yields no logo — branding is non-essential and must never break a solve.\n\t\tconst [loaded, orgLogoUrl] = await Promise.all([\n\t\t\tloadDefinitionForRender(ctx, record, channel, explicitVersionId),\n\t\t\tresolveOrgLogo(ctx, record.projectId, locals.log)\n\t\t]);\n\n\t\t// Warm already: loading the definition read its inputs through this client.\n\t\tconst { limits } = await getClient(loaded.computeServer, { definitionGuid: guid });\n\n\t\treturn {\n\t\t\tschema: loaded.schema,\n\t\t\tghDefinition: clientDefUrl,\n\t\t\tcurrentDefinition: guid,\n\t\t\tserverLabel: loaded.computeServer.label,\n\t\t\torgLogoUrl,\n\t\t\tchannel,\n\t\t\t// When rendering an explicit version, forward its id (so solve calls\n\t\t\t// target the same version) and number (for the preview badge).\n\t\t\tversionId: explicitVersionId,\n\t\t\tversionNumber: loaded.version.versionNumber,\n\t\t\t// Forward to the client so /api/compute/solve calls can include it.\n\t\t\t// Null when the request was user-authenticated (session cookie carries auth).\n\t\t\tshareToken,\n\t\t\t// The deadline this definition's compute server sets, so the browser's\n\t\t\t// AbortController doesn't stop a solve the server would still finish.\n\t\t\tsolveDeadlineMs: limits.solveDeadlineMs\n\t\t};\n\t} catch (err) {\n\t\t// Let HttpError (from error() calls) bubble up.\n\t\tif (err instanceof Error && 'status' in err) throw err;\n\n\t\t// Translate classified load errors to the same HTTP statuses the route\n\t\t// used pre-extraction:\n\t\t// missing-config | connect → 503 (operator action needed)\n\t\t// schema → 500 (compute responded but IO/schema failed)\n\t\t// data → 400 (definition references missing version/blob)\n\t\tif (err instanceof DefinitionLoadError) {\n\t\t\tif (err.kind === 'missing-config') {\n\t\t\t\tthrow error(\n\t\t\t\t\t503,\n\t\t\t\t\t'No compute server configured. Ask an admin to add one in /admin/compute.'\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (err.kind === 'connect') {\n\t\t\t\tlocals.log.error('Compute server connection failed', {\n\t\t\t\t\tcomponent: 'PageLoad',\n\t\t\t\t\tguid,\n\t\t\t\t\terr: renderThrown(err)\n\t\t\t\t});\n\t\t\t\tthrow error(503, err.message);\n\t\t\t}\n\t\t\tif (err.kind === 'schema') {\n\t\t\t\tlocals.log.error('Definition loading failed', {\n\t\t\t\t\tcomponent: 'PageLoad',\n\t\t\t\t\tguid,\n\t\t\t\t\terr: renderThrown(err)\n\t\t\t\t});\n\n\t\t\t\tif (process.env.NODE_ENV === 'development') {\n\t\t\t\t\tconst hint = `\\n\\nTroubleshooting:\\n1. Check /api/health/compute to diagnose server connectivity\\n2. Check the browser console for more details`;\n\t\t\t\t\tthrow error(500, `Failed to load definition from ${clientDefUrl}: ${err.message}${hint}`);\n\t\t\t\t}\n\t\t\t\tthrow error(500, `Failed to load definition: ${err.message}`);\n\t\t\t}\n\t\t\t// kind === 'data' falls through to the 400 wrap below.\n\t\t}\n\n\t\tif (err instanceof Error) {\n\t\t\tlocals.log.warn('Failed to load definition', {\n\t\t\t\tcomponent: 'App Load',\n\t\t\t\tguid,\n\t\t\t\terr: renderThrown(err)\n\t\t\t});\n\t\t\tthrow error(400, `Failed to load definition '${guid}': ${err.message}`);\n\t\t}\n\t\tthrow err;\n\t}\n}) satisfies PageServerLoad;\n\n/**\n * Resolve the owning org's logo URL for viewer branding. definition → project →\n * org. Best-effort and self-contained: any miss or read error returns null so a\n * branding lookup can never fail the render path.\n */\nasync function resolveOrgLogo(\n\tctx: RequestContext,\n\tprojectId: string,\n\tlog: ILogger\n): Promise<string | null> {\n\ttry {\n\t\tconst project = await getProjectProvider().getProject(ctx, projectId);\n\t\tif (!project?.orgId) return null;\n\t\tconst org = await getOrganizationProvider().getOrg(ctx, project.orgId);\n\t\treturn org?.assets?.logo ?? null;\n\t} catch (err) {\n\t\tlog.warn('Failed to resolve org logo', {\n\t\t\tcomponent: 'App Load',\n\t\t\tprojectId,\n\t\t\terr: renderThrown(err)\n\t\t});\n\t\treturn null;\n\t}\n}\n"],"mappings":";;;;;;;;;;;AA0CA,IAAa,sBAAb,cAAyC,MAAM;CAE7B;CAEA;CAHjB,YACC,MACA,SACA,OACC;EACD,MAAM,OAAO;EAJG,KAAA,OAAA;EAEA,KAAA,QAAA;EAGhB,KAAK,OAAO;CACb;AACD;;;;;;AA2DA,SAAgB,uBAAuB,MAA8C;CACpF,MAAM,EACL,SACA,aACA,UACA,eACA,WACA,cAAc,wBACd,eAAe,OACf,QACA,SAAS,IAAI,WAAW,MACrB;CAEJ,OAAO,eAAe,wBAAwB,KAAK,QAAQ,SAAS,mBAAmB,SAAS;EAC/F,MAAM,YACL,sBAAsB,YAAY,UAAU,OAAO,iBAAiB,OAAO;EAC5E,IAAI,CAAC,WACJ,MAAM,IAAI,oBACT,QACA,eAAe,OAAO,KAAK,WAAW,QAAQ,SAC/C;EAID,MAAM,iBAAiB,Y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AO,OAAO;EAE5B,QAAO,MADW,wBAAwB,CAAC,CAAC,OAAO,KAAK,QAAQ,KAAK,EAAA,EACzD,QAAQ,QAAQ;CAC7B,SAAS,KAAK;EACb,IAAI,KAAK,8BAA8B;GACtC,WAAW;GACX;GACA,KAAK,aAAa,GAAG;EACtB,CAAC;EACD,OAAO;CACR;AACD"}
|
|
1
|
+
{"version":3,"file":"_page.server.ts.js","names":[],"sources":["../../../../../../../server/src/definitions/load-for-render.ts","../../../../../../src/lib/server/definitions/loadForRender.server.ts","../../../../../../src/routes/library/[guid]/+page.server.ts"],"sourcesContent":["// Given a definition record, produces everything the client needs to render its\n// form and solve it.\n//\n// Access gating is deliberately NOT done here — the calling route decides\n// whether `ctx` may load this definition, since gates differ across routes\n// (project membership, segment ownership, share-token, admin override).\n//\n// Everything stateful is injected, so any app on the engine can wire its own\n// composition root.\n\nimport type { GrasshopperClient } from '@selvajs/compute/grasshopper';\nimport { UI_SCHEMA_VERSION, type UISchema } from '@selvajs/schemas';\nimport type {\n\tComputeServerConfig,\n\tDefinitionRecord,\n\tDefinitionVersion,\n\tIDefinitionStore,\n\tIProjectStore,\n\tIStorageProvider,\n\tRequestContext\n} from '@selvajs/platform';\nimport { NoopLogger, type ILogger } from '@selvajs/platform';\nimport { fetchSchemaFromCompute } from './schema-extraction.js';\n\nexport type DefinitionChannel = 'live' | 'draft';\n\nexport interface LoadedDefinition {\n\tversion: DefinitionVersion;\n\tdefinitionSource: Uint8Array;\n\tcomputeServer: ComputeServerConfig;\n\tschema: UISchema;\n}\n\n/**\n * Classified failure modes so callers can map to appropriate HTTP status:\n * - 'data': record references a version/blob that isn't there. (400)\n * - 'missing-config': no compute server resolvable for this org/definition. (503)\n * - 'connect': compute server is configured but unreachable. (503)\n * - 'schema': compute responded but IO/schema phase failed. (500)\n */\nexport type DefinitionLoadErrorKind = 'data' | 'missing-config' | 'connect' | 'schema';\n\nexport class DefinitionLoadError extends Error {\n\tconstructor(\n\t\tpublic readonly kind: DefinitionLoadErrorKind,\n\t\tmessage: string,\n\t\tpublic readonly cause?: unknown\n\t) {\n\t\tsuper(message);\n\t\tthis.name = 'DefinitionLoadError';\n\t}\n}\n\nexport interface DefinitionLoaderDeps {\n\tstorage: Pick<IStorageProvider, 'get'>;\n\tdefinitions: Pick<IDefinitionStore, 'getVersion' | 'setVersionSchema'>;\n\tprojects: Pick<IProjectStore, 'getProject'>;\n\t/** Resolution order: definition pin → org default override → global default. */\n\tresolveServer: (\n\t\tctx: RequestContext,\n\t\torgId: string | null,\n\t\topts: { definitionPin: string | null }\n\t) => Promise<ComputeServerConfig>;\n\t/** Shared warm-client cache, keyed by server id with a definition-guid affinity header. */\n\tgetClient: (\n\t\tserver: ComputeServerConfig,\n\t\topts: { definitionGuid: string }\n\t) => Promise<{ client: GrasshopperClient }>;\n\t/** Schema extraction; defaults to `fetchSchemaFromCompute`. Injectable for tests. */\n\tfetchSchema?: (bytes: Uint8Array, server: ComputeServerConfig) => Promise<UISchema>;\n\t/**\n\t * When set, an unhealthy IO result also dumps the raw /io wire shape, making\n\t * casing/serialization mismatches visible.\n\t */\n\tcomputeDebug?: boolean;\n\t/** Legacy diagnostic sink. When set it takes the warnings below instead of `logger`. */\n\tonWarn?: (message: string, detail?: string) => void;\n\t/**\n\t * Defaults to `NoopLogger`, so a consumer that wires nothing gets silence\n\t * rather than unsolicited stdout.\n\t */\n\tlogger?: ILogger;\n}\n\nexport interface DefinitionLoadOptions {\n\t/**\n\t * For callers that read only schema STRUCTURE (input ids, `source.key`,\n\t * widget types — anything persisted at upload). A fresh cached schema then\n\t * returns without touching compute, whose multi-second connect otherwise\n\t * dominates a page resolving several definitions.\n\t *\n\t * Leave unset (the default) for anything that RENDERS a form — without\n\t * compute defaults the form shows the wrong initial values.\n\t */\n\tskipComputeDefaults?: boolean;\n}\n\nexport type DefinitionLoader = (\n\tctx: RequestContext,\n\trecord: DefinitionRecord,\n\tchannel: DefinitionChannel,\n\texplicitVersionId?: string | null,\n\toptions?: DefinitionLoadOptions\n) => Promise<LoadedDefinition>;\n\n/**\n * The returned loader resolves the `channel` pointer (live/draft) by default.\n * `explicitVersionId` renders an arbitrary historical version instead — the\n * caller MUST gate that behind edit permission, as with the draft channel.\n */\nexport function createDefinitionLoader(deps: DefinitionLoaderDeps): DefinitionLoader {\n\tconst {\n\t\tstorage,\n\t\tdefinitions,\n\t\tprojects,\n\t\tresolveServer,\n\t\tgetClient,\n\t\tfetchSchema = fetchSchemaFromCompute,\n\t\tcomputeDebug = false,\n\t\tonWarn,\n\t\tlogger = new NoopLogger()\n\t} = deps;\n\n\treturn async function loadDefinitionForRender(ctx, record, channel, explicitVersionId, options) {\n\t\tconst versionId =\n\t\t\texplicitVersionId ?? (channel === 'draft' ? record.draftVersionId : record.liveVersionId);\n\t\tif (!versionId)\n\t\t\tthrow new DefinitionLoadError(\n\t\t\t\t'data',\n\t\t\t\t`Definition '${record.guid}' has no ${channel} version`\n\t\t\t);\n\n\t\t// The server needs only the record, so it resolves while the version and file are read.\n\t\t// It is awaited after them, so a definition missing its data still fails as 'data'.\n\t\tconst pendingServer = (async (): Promise<ComputeServerConfig> => {\n\t\t\tconst project = await projects.getProject(ctx, record.projectId);\n\t\t\ttry {\n\t\t\t\treturn await resolveServer(ctx, project?.orgId ?? null, {\n\t\t\t\t\tdefinitionPin: record.computeServerId ?? null\n\t\t\t\t});\n\t\t\t} catch (err) {\n\t\t\t\tthrow new DefinitionLoadError(\n\t\t\t\t\t'missing-config',\n\t\t\t\t\t'No compute server configured for this definition',\n\t\t\t\t\terr\n\t\t\t\t);\n\t\t\t}\n\t\t})();\n\t\tpendingServer.catch(() => {});\n\n\t\tconst version = await definitions.getVersion(ctx, versionId);\n\t\tif (!version) throw new DefinitionLoadError('data', `version missing for '${record.guid}'`);\n\t\t// An explicitly requested version must belong to this definition.\n\t\tif (version.definitionId !== record.guid)\n\t\t\tthrow new DefinitionLoadError('data', `version does not belong to '${record.guid}'`);\n\n\t\tconst definitionSource = await storage.get(version.fileKey);\n\t\tif (!definitionSource)\n\t\t\tthrow new DefinitionLoadError(\n\t\t\t\t'data',\n\t\t\t\t`Definition file for '${record.guid}' not found on disk`\n\t\t\t);\n\n\t\tconst computeServer = await pendingServer;\n\n\t\t// Returning before `getClient` is the point — the connect is the cost, not\n\t\t// the `getIO` it carries. A missing or stale-format cache falls through to\n\t\t// the full path below, so the result is always a valid schema.\n\t\tif (options?.skipComputeDefaults) {\n\t\t\tconst cachedSchema = version.schema as UISchema | undefined;\n\t\t\tif (cachedSchema && isUsableCachedSchema(cachedSchema)) {\n\t\t\t\treturn { version, definitionSource, computeServer, schema: cachedSchema };\n\t\t\t}\n\t\t}\n\n\t\t// Only the client is used here (getIO); the entry's solve scheduler rides\n\t\t// along unused.\n\t\tlet client: GrasshopperClient;\n\t\ttry {\n\t\t\tclient = (await getClient(computeServer, { definitionGuid: record.guid })).client;\n\t\t} catch (err) {\n\t\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\t\tthrow new DefinitionLoadError(\n\t\t\t\t'connect',\n\t\t\t\t`Failed to connect to Rhino Compute server: ${message}`,\n\t\t\t\terr\n\t\t\t);\n\t\t}\n\n\t\ttry {\n\t\t\t// The stored schema is a disposable cache, used ONLY when its format\n\t\t\t// version matches the app's. On a mismatch (or a pre-caching row with no\n\t\t\t// schema) re-extract from compute, whose C# SchemaMigrator emits the\n\t\t\t// current format — the web side never migrates schemas itself. `getIO`\n\t\t\t// runs either way, to merge compute default values in.\n\t\t\tconst cachedSchema = version.schema as UISchema | undefined;\n\t\t\tconst freshCache = cachedSchema && isUsableCachedSchema(cachedSchema) ? cachedSchema : null;\n\t\t\tconst [definition, fetchedSchema] = await Promise.all([\n\t\t\t\tclient.getIO(definitionSource),\n\t\t\t\tfreshCache ? Promise.resolve(freshCache) : fetchSchema(definitionSource, computeServer)\n\t\t\t]);\n\n\t\t\t// Best-effort — a viewer context may lack write access, and the next\n\t\t\t// editor render or the solve-time backfill will land it. Guarded on the\n\t\t\t// current version because persisting an older format (compute plugin\n\t\t\t// behind the app) would just go stale again next render.\n\t\t\tif (!freshCache && fetchedSchema.schemaVersion === UI_SCHEMA_VERSION) {\n\t\t\t\tdefinitions.setVersionSchema(ctx, version.id, fetchedSchema).catch((err) => {\n\t\t\t\t\tif (onWarn) {\n\t\t\t\t\t\tonWarn(\n\t\t\t\t\t\t\t`[loadForRender] schema cache refresh failed for version ${version.id}: ` +\n\t\t\t\t\t\t\t\t`${err instanceof Error ? err.message : String(err)}`\n\t\t\t\t\t\t);\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tlogger.warn('Schema cache refresh failed', {\n\t\t\t\t\t\tcomponent: 'loadForRender',\n\t\t\t\t\t\tversionId: version.id,\n\t\t\t\t\t\terr: err instanceof Error ? (err.stack ?? err.message) : String(err)\n\t\t\t\t\t});\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tif (!definition) {\n\t\t\t\tthrow new Error(`Failed to get definition IO — server returned undefined`);\n\t\t\t}\n\n\t\t\t// Zero inputs or reported parse/load problems mean a definition that will\n\t\t\t// render wrong without saying why: an empty ValueList whose backing GH\n\t\t\t// component didn't resolve (\"Missing Definition Objects\"), or a PascalCase\n\t\t\t// /io response the parser silently dropped to []. Warning is always on —\n\t\t\t// it only fires on the unhappy path — while the raw wire dump costs an\n\t\t\t// extra round-trip and stays behind `computeDebug`.\n\t\t\tconst ioParseErrors = (definition as { parseErrors?: unknown[] }).parseErrors ?? [];\n\t\t\tconst ioLoadErrors = (definition as { loadErrors?: unknown[] }).loadErrors ?? [];\n\t\t\tconst ioLooksBroken =\n\t\t\t\tdefinition.inputs.length === 0 || ioParseErrors.length > 0 || ioLoadErrors.length > 0;\n\t\t\tif (ioLooksBroken) {\n\t\t\t\tconst health = {\n\t\t\t\t\tinputCount: definition.inputs.length,\n\t\t\t\t\toutputCount: definition.outputs?.length,\n\t\t\t\t\tparseErrors: ioParseErrors,\n\t\t\t\t\tloadErrors: ioLoadErrors,\n\t\t\t\t\tloadWarnings: (definition as { loadWarnings?: unknown }).loadWarnings\n\t\t\t\t};\n\t\t\t\tif (onWarn) {\n\t\t\t\t\tonWarn(`[loadForRender] IO health for '${record.guid}':`, JSON.stringify(health));\n\t\t\t\t} else {\n\t\t\t\t\tlogger.warn('Definition IO looks unhealthy', {\n\t\t\t\t\t\tcomponent: 'loadForRender',\n\t\t\t\t\t\tdefinitionGuid: record.guid,\n\t\t\t\t\t\t...health\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tif (computeDebug) {\n\t\t\t\t\tconst rawIO = await client\n\t\t\t\t\t\t.getRawIO(definitionSource)\n\t\t\t\t\t\t.catch((e) => ({ error: String(e) }));\n\t\t\t\t\tconst rendered = JSON.stringify(rawIO).slice(0, 3000);\n\t\t\t\t\tif (onWarn) onWarn('[loadForRender] raw /io:', rendered);\n\t\t\t\t\telse\n\t\t\t\t\t\tlogger.debug('Raw /io wire shape', {\n\t\t\t\t\t\t\tcomponent: 'loadForRender',\n\t\t\t\t\t\t\tdefinitionGuid: record.guid,\n\t\t\t\t\t\t\trawIO: rendered\n\t\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn {\n\t\t\t\tversion,\n\t\t\t\tdefinitionSource,\n\t\t\t\tcomputeServer,\n\t\t\t\tschema: mergeComputeDefaults(fetchedSchema, definition.inputs)\n\t\t\t};\n\t\t} catch (err) {\n\t\t\tif (err instanceof DefinitionLoadError) throw err;\n\t\t\tconst message = err instanceof Error ? err.message : String(err);\n\t\t\tthrow new DefinitionLoadError('schema', message, err);\n\t\t}\n\t};\n}\n\n/**\n * A cached schema is usable only if it is BOTH the current format version and\n * structurally sound. The version check alone is not enough: a compute server\n * that serialized the schema with the wrong Newtonsoft emits PascalCase keys, so\n * `schemaVersion` reads as undefined while `SchemaVersion` holds the value —\n * and a row cached during that window would otherwise be served forever, long\n * after the server was fixed. See `assertCamelCaseSchema`.\n */\nexport function isUsableCachedSchema(schema: UISchema): boolean {\n\treturn schema.schemaVersion === UI_SCHEMA_VERSION && Array.isArray(schema.inputs);\n}\n\n// Colors come back from Compute as \"r,g,b\" or \"a,r,g,b\" strings — converted to\n// hex here so the color picker can consume them directly.\nfunction mergeComputeDefaults(\n\tschema: UISchema,\n\tcomputeInputs: Array<{ id?: string; paramType?: string; default?: unknown }>\n): UISchema {\n\tif (!Array.isArray(schema.inputs)) {\n\t\tthrow new DefinitionLoadError(\n\t\t\t'schema',\n\t\t\t`Schema has no 'inputs' array (keys: ${Object.keys(schema as object)\n\t\t\t\t.slice(0, 12)\n\t\t\t\t.join(', ')}). A PascalCase shape here means compute serialized it with the wrong ` +\n\t\t\t\t`Newtonsoft — see assertCamelCaseSchema.`\n\t\t);\n\t}\n\n\tconst byParamId = new Map(computeInputs.map((input) => [input.id, input]));\n\n\treturn {\n\t\t...schema,\n\t\tinputs: schema.inputs.map((schemaInput) => {\n\t\t\tconst computeInput = byParamId.get(schemaInput.id);\n\n\t\t\tif (computeInput?.paramType === 'Color' && computeInput.default !== undefined) {\n\t\t\t\tconst toHex = (value: number) => value.toString(16).padStart(2, '0');\n\t\t\t\tconst parts = String(computeInput.default)\n\t\t\t\t\t.split(',')\n\t\t\t\t\t.map((s) => parseInt(s.trim(), 10));\n\n\t\t\t\tif (parts.length === 3) {\n\t\t\t\t\tcomputeInput.default = `#${toHex(parts[0])}${toHex(parts[1])}${toHex(parts[2])}`;\n\t\t\t\t} else if (parts.length === 4) {\n\t\t\t\t\tcomputeInput.default = `#${toHex(parts[1])}${toHex(parts[2])}${toHex(parts[3])}`;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (computeInput && computeInput.default !== undefined) {\n\t\t\t\treturn { ...schemaInput, default: computeInput.default };\n\t\t\t}\n\t\t\treturn schemaInput;\n\t\t})\n\t};\n}\n","// `@selvajs/server/definitions` owns the loading pipeline (version resolution,\n// blob fetch, schema staleness check, default merging); this wires in the\n// app's providers, compute-server resolution, and warm-client cache. Access\n// gating stays with the calling route.\n\nimport {\n\tcreateDefinitionLoader,\n\tDefinitionLoadError,\n\ttype DefinitionChannel,\n\ttype DefinitionLoadErrorKind,\n\ttype LoadedDefinition\n} from '@selvajs/server/definitions';\nimport type { DefinitionRecord, RequestContext } from '@selvajs/platform';\nimport {\n\tgetStorageProvider,\n\tgetDefinitionMeta,\n\tgetProjectProvider,\n\tgetComputeServerConfigStore\n} from '../providers.server';\nimport { serverResolver } from '../compute/serverResolver.server';\nimport { getClient, COMPUTE_DEBUG } from '../compute/engine.server';\n\nexport { DefinitionLoadError };\nexport type { DefinitionChannel, DefinitionLoadErrorKind, LoadedDefinition };\n\nexport async function loadDefinitionForRender(\n\tctx: RequestContext,\n\trecord: DefinitionRecord,\n\tchannel: DefinitionChannel,\n\texplicitVersionId?: string | null\n): Promise<LoadedDefinition> {\n\tconst load = createDefinitionLoader({\n\t\tstorage: getStorageProvider(),\n\t\tdefinitions: getDefinitionMeta(),\n\t\tprojects: getProjectProvider(),\n\t\tresolveServer: (ctx, orgId, opts) =>\n\t\t\tserverResolver.resolve(ctx, orgId, getComputeServerConfigStore(), opts),\n\t\tgetClient,\n\t\tcomputeDebug: COMPUTE_DEBUG\n\t});\n\treturn load(ctx, record, channel, explicitVersionId);\n}\n","import type { PageServerLoad } from './$types';\nimport { error } from '@sveltejs/kit';\nimport type { ILogger, RequestContext } from '@selvajs/platform';\nimport { renderThrown } from '@selvajs/server/logging';\nimport {\n\tgetDefinitionMeta,\n\tgetProjectProvider,\n\tgetOrganizationProvider\n} from '#lib/server/providers.server.js';\nimport { isApiError } from '@selvajs/server/api';\nimport { asHttpError, requireCanSolve, scoped } from '#lib/server/access.server.js';\nimport { readShareToken, tryResolveShareToken } from '#lib/server/shareLinks/resolve.server.js';\nimport { getClient } from '#lib/server/compute/engine.server.js';\nimport {\n\tloadDefinitionForRender,\n\tDefinitionLoadError\n} from '#lib/server/definitions/loadForRender.server.js';\n\nexport const load = (async ({ params, locals, request, url }) => {\n\tconst meta = getDefinitionMeta();\n\n\tconst guid = params.guid;\n\tconst channel = url.searchParams.get('channel') === 'draft' ? 'draft' : 'live';\n\t// Explicit version pick (versioning tab \"Run\"): render an arbitrary version,\n\t// not just the live/draft pointer. Editor-only, never share-token accessible.\n\tconst explicitVersionId = url.searchParams.get('version');\n\tconst clientDefUrl = `local:${guid}`;\n\t// `shareToken` is forwarded to the page so the client can include it on\n\t// subsequent /api/compute/solve calls. null = user-authenticated session.\n\tlet shareToken: string | null = null;\n\n\ttry {\n\t\t// Draft channel and explicit-version picks are editor-only — share tokens\n\t\t// are always live channel on the pointer. A signed-in viewer who can solve\n\t\t// anyway ignores the token: a share-token solve gets no live events and\n\t\t// counts against the link's solve cap.\n\t\tconst sharedAccess =\n\t\t\tchannel === 'live' &&\n\t\t\t!explicitVersionId &&\n\t\t\treadShareToken(request, url) !== null &&\n\t\t\t!(await sessionCanSolve(locals, guid))\n\t\t\t\t? await tryResolveShareToken(request, url, guid, 'live', { requireSolve: false })\n\t\t\t\t: null;\n\t\tif (sharedAccess) {\n\t\t\tshareToken = url.searchParams.get('token');\n\t\t} else if (!locals.ctx || !locals.user) {\n\t\t\tthrow error(401, 'Unauthorized: You must be logged in to access definitions');\n\t\t}\n\n\t\tconst ctx: RequestContext = sharedAccess?.ctx ?? locals.ctx!;\n\n\t\tconst record = await meta.get(ctx, guid);\n\t\tif (!record) throw new Error(`Definition '${guid}' not found`);\n\n\t\t// User-auth path needs the canSolve gate; token-auth was already gated.\n\t\tif (!sharedAccess) await asHttpError(() => requireCanSolve(scoped(locals), record.projectId));\n\n\t\t// Draft channel and explicit-version picks require edit permission on top\n\t\t// of solve.\n\t\tif (channel === 'draft' || explicitVersionId) {\n\t\t\tconst { requireEditableDefinition } = await import('#lib/server/access.server.js');\n\t\t\tawait asHttpError(() => requireEditableDefinition(scoped(locals), guid));\n\t\t}\n\n\t\t// Owning org's logo, for viewer branding, read beside the definition load. Same\n\t\t// `ctx` already authorized to load this definition (user session or share-token\n\t\t// ctx, which carries actingOrgId). Best-effort: a missing project/org or read\n\t\t// failure just yields no logo — branding is non-essential and must never break a solve.\n\t\tconst [loaded, orgLogoUrl] = await Promise.all([\n\t\t\tloadDefinitionForRender(ctx, record, channel, explicitVersionId),\n\t\t\tresolveOrgLogo(ctx, record.projectId, locals.log)\n\t\t]);\n\n\t\t// Warm already: loading the definition read its inputs through this client.\n\t\tconst { limits } = await getClient(loaded.computeServer, { definitionGuid: guid });\n\n\t\treturn {\n\t\t\tschema: loaded.schema,\n\t\t\tghDefinition: clientDefUrl,\n\t\t\tcurrentDefinition: guid,\n\t\t\tserverLabel: loaded.computeServer.label,\n\t\t\torgLogoUrl,\n\t\t\tchannel,\n\t\t\t// When rendering an explicit version, forward its id (so solve calls\n\t\t\t// target the same version) and number (for the preview badge).\n\t\t\tversionId: explicitVersionId,\n\t\t\tversionNumber: loaded.version.versionNumber,\n\t\t\t// Forward to the client so /api/compute/solve calls can include it.\n\t\t\t// Null when the request was user-authenticated (session cookie carries auth).\n\t\t\tshareToken,\n\t\t\t// The deadline this definition's compute server sets, so the browser's\n\t\t\t// AbortController doesn't stop a solve the server would still finish.\n\t\t\tsolveDeadlineMs: limits.solveDeadlineMs\n\t\t};\n\t} catch (err) {\n\t\t// Let HttpError (from error() calls) bubble up.\n\t\tif (err instanceof Error && 'status' in err) throw err;\n\n\t\t// Translate classified load errors to the same HTTP statuses the route\n\t\t// used pre-extraction:\n\t\t// missing-config | connect → 503 (operator action needed)\n\t\t// schema → 500 (compute responded but IO/schema failed)\n\t\t// data → 400 (definition references missing version/blob)\n\t\tif (err instanceof DefinitionLoadError) {\n\t\t\tif (err.kind === 'missing-config') {\n\t\t\t\tthrow error(\n\t\t\t\t\t503,\n\t\t\t\t\t'No compute server configured. Ask an admin to add one in /admin/compute.'\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (err.kind === 'connect') {\n\t\t\t\tlocals.log.error('Compute server connection failed', {\n\t\t\t\t\tcomponent: 'PageLoad',\n\t\t\t\t\tguid,\n\t\t\t\t\terr: renderThrown(err)\n\t\t\t\t});\n\t\t\t\tthrow error(503, err.message);\n\t\t\t}\n\t\t\tif (err.kind === 'schema') {\n\t\t\t\tlocals.log.error('Definition loading failed', {\n\t\t\t\t\tcomponent: 'PageLoad',\n\t\t\t\t\tguid,\n\t\t\t\t\terr: renderThrown(err)\n\t\t\t\t});\n\n\t\t\t\tif (process.env.NODE_ENV === 'development') {\n\t\t\t\t\tconst hint = `\\n\\nTroubleshooting:\\n1. Check /api/health/compute to diagnose server connectivity\\n2. Check the browser console for more details`;\n\t\t\t\t\tthrow error(500, `Failed to load definition from ${clientDefUrl}: ${err.message}${hint}`);\n\t\t\t\t}\n\t\t\t\tthrow error(500, `Failed to load definition: ${err.message}`);\n\t\t\t}\n\t\t\t// kind === 'data' falls through to the 400 wrap below.\n\t\t}\n\n\t\tif (err instanceof Error) {\n\t\t\tlocals.log.warn('Failed to load definition', {\n\t\t\t\tcomponent: 'App Load',\n\t\t\t\tguid,\n\t\t\t\terr: renderThrown(err)\n\t\t\t});\n\t\t\tthrow error(400, `Failed to load definition '${guid}': ${err.message}`);\n\t\t}\n\t\tthrow err;\n\t}\n}) satisfies PageServerLoad;\n\nasync function sessionCanSolve(locals: App.Locals, guid: string): Promise<boolean> {\n\tif (!locals.ctx || !locals.user) return false;\n\tconst record = await getDefinitionMeta().get(locals.ctx, guid);\n\tif (!record) return false;\n\ttry {\n\t\tawait requireCanSolve(scoped(locals), record.projectId);\n\t\treturn true;\n\t} catch (err) {\n\t\tif (isApiError(err)) return false;\n\t\tthrow err;\n\t}\n}\n\n/**\n * Resolve the owning org's logo URL for viewer branding. definition → project →\n * org. Best-effort and self-contained: any miss or read error returns null so a\n * branding lookup can never fail the render path.\n */\nasync function resolveOrgLogo(\n\tctx: RequestContext,\n\tprojectId: string,\n\tlog: ILogger\n): Promise<string | null> {\n\ttry {\n\t\tconst project = await getProjectProvider().getProject(ctx, projectId);\n\t\tif (!project?.orgId) return null;\n\t\tconst org = await getOrganizationProvider().getOrg(ctx, project.orgId);\n\t\treturn org?.assets?.logo ?? null;\n\t} catch (err) {\n\t\tlog.warn('Failed to resolve org logo', {\n\t\t\tcomponent: 'App Load',\n\t\t\tprojectId,\n\t\t\terr: renderThrown(err)\n\t\t});\n\t\treturn null;\n\t}\n}\n"],"mappings":";;;;;;;;;;;;AA0CA,IAAa,sBAAb,cAAyC,MAAM;CAE7B;CAEA;CAHjB,YACC,MACA,SACA,OACC;EACD,MAAM,OAAO;EAJG,KAAA,OAAA;EAEA,KAAA,QAAA;EAGhB,KAAK,OAAO;CACb;AACD;;;;;;AA2DA,SAAgB,uBAAuB,MAA8C;CACpF,MAAM,EACL,SACA,aACA,UACA,eACA,WACA,cAAc,wBACd,eAAe,OACf,QACA,SAAS,IAAI,WAAW,MACrB;CAEJ,OAAO,eAAe,wBAAwB,KAAK,QAAQ,SAAS,mBAAmB,SAAS;EAC/F,MAAM,YACL,sBAAsB,YAAY,UAAU,OAAO,iBAAiB,OAAO;EAC5E,IAAI,CAAC,WACJ,MAAM,IAAI,oBACT,QACA,eAAe,OAAO,KAAK,WAAW,QAAQ,SAC/C;EAID,MAAM,iBAAiB,YAA0C;GAChE,MAAM,UAAU,MAAM,SAAS,WAAW,KAAK,OAAO,SAAS;GAC/D,IAAI;IACH,OAAO,MAAM,cAAc,KAAK,SAAS,SAAS,MAAM,EACvD,eAAe,OAAO,mBAAmB,KAC1C,CAAC;GACF,SAAS,KAAK;IACb,MAAM,IAAI,oBACT,kBACA,oDACA,GACD;GACD;EACD,EAAA,CAAG;EACH,cAAc,YAAY,CAAC,CAAC;EAE5B,MAAM,UAAU,MAAM,YAAY,WAAW,KAAK,SAAS;EAC3D,IAAI,CAAC,SAAS,MAAM,IAAI,oBAAoB,QAAQ,wBAAwB,OAAO,KAAK,EAAE;EAE1F,IAAI,QAAQ,iBAAiB,OAAO,MACnC,MAAM,IAAI,oBAAoB,QAAQ,+BAA+B,OAAO,KAAK,EAAE;EAEpF,MAAM,mBAAmB,MAAM,QAAQ,IAAI,QAAQ,O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