import { g as getActiveProjectId, r as resolveProjectContext, a as resolveDefaultProjectContext } from './project-context-D0JIm5Ed.js';
import { json } from '@sveltejs/kit';
import { createHash } from 'node:crypto';
import './dist4-CiQ5cizO.js';
import 'node:module';
import './dual-scope-db-ATrwq0LH.js';
import './paths-2M_UxD_H.js';
import 'node:fs';
import 'node:path';
import 'node:os';
import 'node:events';
import 'node:diagnostics_channel';
import 'fs';
import 'events';
import 'util';
import 'path';
import 'assert';
import 'worker_threads';
import 'module';
import 'node:url';
import 'url';
import 'buffer';
import 'node:child_process';
import 'node:process';
import 'node:async_hooks';
import './indexes-aYlULWG3.js';
import './utils-BvHPJOVk.js';
import './adapters-D2gEs_5L.js';
import './registry2-BSyCTA3q.js';
import './data-accessor-CVbz8X_7.js';
import './tasks-CnwUAUXf.js';
import './conduit-Ca_OFWR_.js';
import './unique-constraint-BM-Apx1H.js';
import './chunk-DDP5xfzh.js';
import './sqlite-Dsbe0wec.js';
import './memory-schema-Bi7cChwo.js';
import './agent-registry-BtE5uhMO.js';
import './nexus-sqlite2-DgTuv9BQ.js';
import './nexus-schema2-BEd-ol6e.js';
import './logger-ChCwlV5k.js';
import 'node:sqlite';
import './lock-BoHF25mx.js';
import './index-IVoIz4D5.js';
import 'constants';
import 'stream';
import 'node:fs/promises';
import 'jsonc-parser';
import '@cleocode/cant';
import 'node:util';
import 'node:buffer';
import 'child_process';
import './branch-lock-qP1EkZ7p.js';
import './src2-DK8DKufK.js';
import 'llmtxt/identity';
import './sessions-j73dkbCI.js';
import './index-Ca4C2M45.js';
import './mvi-helpers-BNsJ8ZpQ.js';
import './session-store-OwQWMSf_.js';
import './session-manifest-ZHrj54LR.js';
import './storage-B9UA3BHR.js';
import './config-B0nEjgSh.js';
import './json-DXl7iDYg.js';
import './data-safety-central-vmfu_Y4J.js';
import './sqlite-data-accessor-C59wZ0zp.js';
import './cross-db-cleanup-C_FLyd-6.js';
import './query-ops-BDMaTdYw.js';
import 'node:net';
import './src3-CMSGYxDI.js';
import './local-model-fit2-J1xCIhC_.js';
import './credential-pool-B04qO8at.js';
import './catalog-model-resolver2-Cexk2TN0.js';
import './role-resolver-DF9BQ_U6.js';
import './identity2-DeAB5RXE.js';
import './role-executor-C4-3bmgC.js';
import 'node:stream';
import 'crypto';
import 'os';
import 'node:http2';
import 'fs/promises';
import './models-catalog-DG3aPok8.js';
import './catalog-resolver2-c0qfF34B.js';
import './providers-CmIcBfg-.js';
import './brain-maintenance-bSR6GwAG.js';
import './graph-auto-populate2-DYsUNGSL.js';
import './temporal-supersession-BZ46j30w.js';
import './typed-query-l1D_QElt.js';
import './llm-backend-resolver-BPbvttS4.js';
import '@ai-sdk/provider-utils';
import './observer-reflector2-D8nxuglX.js';
import './learnings2-2m2p7lzT.js';
import './memory-accessor2-BzlgmY-Z.js';
import './quality-scoring-CCPuRQmJ.js';
import './patterns2-DYKfsbwN.js';
import './graph-memory-bridge2-C7Y32Mk4.js';
import './sigil2-DftKm7Um.js';
import './services-Dlf3Gefq.js';
import './audit4-S87oN-BC.js';
import 'process';
import './open-cleo-db-Ba2LY1h4.js';
import './cleo-home-BCqJ5rg1.js';

//#region src/lib/server/csrf.ts
/**
* CSRF token helpers for CLEO Studio mutation endpoints.
*
* Wave 1E minimum defense (T990 · audit follow-up):
*   1. Studio binds to loopback (HOST=127.0.0.1), so the absolute threat
*      model is a local-origin attacker or a malicious page opened in
*      the same browser.
*   2. `hooks.server.ts` applies a same-origin guard on every
*      /api/project/** POST/DELETE — requests without a matching
*      `Origin` / `Referer` header are rejected.
*   3. As groundwork for future full CSRF, this module issues a
*      deterministic token bound to the active-project cookie. The
*      token is surfaced to the client via a `cleo_csrf` cookie (read
*      by the modals, re-sent in the `X-CSRF` request header). Today
*      the server does **not** validate the header — it only needs the
*      cookie machinery to exist so the eventual validator can land
*      without touching every caller.
*
* @task T990
* @wave 1E
*/
/** Cookie the client reads to attach `X-CSRF` headers on mutations. */
var CSRF_COOKIE = "cleo_csrf";
/** Server-side salt — regenerated per process start. */
var SALT = createHash("sha256").update(`${process.pid}:${Date.now()}`).digest("hex").slice(0, 16);
/**
* Derive a deterministic CSRF token from the supplied project id.
*
* Pure hash of `SALT + projectId`. Same id always produces the same
* token for the process lifetime, but the salt rotates on restart so
* stale session tokens invalidate.
*/
function deriveCsrfToken(projectId) {
	const input = `${SALT}:${projectId ?? "anon"}`;
	return createHash("sha256").update(input).digest("hex").slice(0, 24);
}
/**
* Re-derive + set the CSRF cookie so every request receives a fresh
* token bound to the active project. Called by the server hook on
* every response path so the cookie stays in sync with the project
* context.
*/
function refreshCsrfToken(cookies) {
	const token = deriveCsrfToken(cookies.get("cleo_project_id") ?? null);
	cookies.set(CSRF_COOKIE, token, {
		path: "/",
		httpOnly: false,
		sameSite: "lax",
		maxAge: 3600 * 24
	});
	return token;
}
/**
* Same-origin guard. Returns `true` when the request either:
*   - is a GET / HEAD / OPTIONS (no guard needed), or
*   - has an `Origin` / `Referer` header that matches the server's own URL.
*
* Rejects requests whose Origin is a remote site — even if Studio is
* accidentally bound to 0.0.0.0 in the future.
*/
function isSameOriginRequest(request) {
	const method = request.method.toUpperCase();
	if (method === "GET" || method === "HEAD" || method === "OPTIONS") return true;
	const selfHost = new URL(request.url).host;
	const origin = request.headers.get("origin");
	if (origin) try {
		return new URL(origin).host === selfHost;
	} catch {
		return false;
	}
	const referer = request.headers.get("referer");
	if (referer) try {
		return new URL(referer).host === selfHost;
	} catch {
		return false;
	}
	/**
	* No Origin / Referer headers — treat as cross-site (defensive
	* default). Browsers always set at least one of these on `fetch` /
	* form POST calls, so the only requests hitting this branch are
	* hand-rolled curls which already have full local access.
	*/
	return false;
}
//#endregion
//#region src/hooks.server.ts
/**
* SvelteKit server hooks for CLEO Studio.
*
* Responsibilities:
*   1. Resolve the active project context from the cookie and attach it
*      to `event.locals.projectCtx` for every page + API load.
*   2. Refresh the CSRF token cookie on every request so mutation
*      modals always have one to echo back (see
*      `$lib/server/csrf.ts`).
*   3. Enforce a same-origin guard on every mutating admin endpoint
*      (`/api/project/**` POST/DELETE). Studio binds to loopback in
*      production — the guard is belt-and-braces in case it is ever
*      bound to a LAN address.
*
* @task T990
* @wave 1E
*/
/**
* Path prefixes whose mutation verbs must pass the same-origin guard.
*
* `/api/project` — admin project mutations (T990).
* `/api/tasks`   — interactive dispatcher writes: drag→transition (T11928) and
*                  dispatch→spawn (T11930). Spawning provisions a worktree, so
*                  these state-changing endpoints get the same loopback / CSRF
*                  belt-and-braces as the admin surface.
*/
var GUARDED_PATH_PREFIXES = ["/api/project", "/api/tasks"];
/** HTTP verbs treated as state-changing by the guard. */
var GUARDED_METHODS = new Set([
	"POST",
	"PUT",
	"PATCH",
	"DELETE"
]);
/** Does this pathname fall under a guarded mutation prefix? */
function isGuardedPath(pathname) {
	return GUARDED_PATH_PREFIXES.some((prefix) => pathname.startsWith(prefix));
}
var handle = async ({ event, resolve }) => {
	const activeId = getActiveProjectId(event.cookies);
	const ctx = activeId && resolveProjectContext(activeId) || resolveDefaultProjectContext();
	event.locals.projectCtx = ctx;
	refreshCsrfToken(event.cookies);
	if (isGuardedPath(event.url.pathname) && GUARDED_METHODS.has(event.request.method.toUpperCase())) {
		if (!isSameOriginRequest(event.request)) return json({
			success: false,
			error: {
				code: "E_CROSS_ORIGIN",
				message: "Admin mutations require a same-origin request."
			}
		}, { status: 403 });
	}
	return resolve(event);
};

export { handle };
//# sourceMappingURL=hooks.server-CzT7Ys0P.js.map
