import { r as redirect } from './exports-D1quPX8S.js';
import { am as isSetupComplete, aZ as resolveStackDir, r as classifyLocalInstall, w as composePs, n as buildComposeOptions, N as deriveLaunchStatus, T as detectRuntime, O as deriveLocalStackState, s as collectBindAddressWarnings, Y as ensureHomeDirs, a1 as ensureSecrets, aF as readSecret, aJ as readStackRuntimeEnv, _ as ensureOpenCodeConfig, $ as ensureOpenCodeSystemConfig, aY as resolveRuntimeFiles, b9 as writeRuntimeFiles, H as createLogger } from './src-CidJbygh.js';
import { g as getState } from './state-fxN45gBp.js';
import { b as listRemoteStatuses } from './endpoints-UdQGgKsR.js';
import { c as checkHostHeader, a as checkOriginHeader, i as identifyCallerByToken, t as touchSession, U as UI_PORT } from './helpers-kzwksNq1.js';
import { S as SESSION_COOKIE_NAME, s as sessionCookieHeader } from './session-cookie-CHgIES2p.js';
import { i as isMigrationBlocking } from './migration-status-a9KsTKSo.js';
import './utils-BSRjJDrZ.js';
import './chunk-CLZ62Ad-.js';
import 'node:module';
import './provider-constants-DPrj3yBX.js';
import './dist-DOFcG0Zp.js';
import 'node:fs';
import 'node:path';
import 'buffer';
import 'fs';
import 'path';
import 'node:child_process';
import 'node:url';
import 'node:crypto';
import 'events';
import 'node:events';
import 'node:stream';
import 'node:string_decoder';
import 'assert';
import 'zlib';
import 'node:assert';
import 'node:fs/promises';
import 'node:os';

//#region src/hooks.server.ts
var logger = createLogger("admin");
var startupApplyDone = false;
var setupCompleteMemo = false;
var localStatusCache = null;
/** Test-only: clear the 5s launch-routing cache so each test resolves fresh. */
function _resetLaunchCache() {
	localStatusCache = null;
}
function runStartupApply() {
	if (startupApplyDone) return;
	startupApplyDone = true;
	for (const line of collectBindAddressWarnings(process.env)) logger.warn(line);
	try {
		ensureHomeDirs();
		const state = getState();
		ensureSecrets(state);
		if (!process.env.OP_UI_LOGIN_PASSWORD) {
			const pw = readSecret(state.stackDir, "op_ui_login_password");
			if (pw) process.env.OP_UI_LOGIN_PASSWORD = pw.trimEnd();
		}
		const stackVars = readStackRuntimeEnv(state.stackDir);
		for (const [k, v] of Object.entries(stackVars)) if (v && !process.env[k]) process.env[k] = v;
		ensureOpenCodeConfig();
		ensureOpenCodeSystemConfig();
		state.artifacts = resolveRuntimeFiles();
		writeRuntimeFiles(state);
		logger.info("startup auto-apply completed successfully", { artifactMeta: state.artifactMeta });
	} catch (err) {
		logger.error("startup auto-apply failed", { error: String(err) });
	}
}
runStartupApply();
var SETUP_PATHS = [
	"/setup",
	"/api/setup",
	"/health",
	"/guardian/health"
];
function isLocalhostAddress(ip) {
	return ip === "127.0.0.1" || ip === "::1" || ip === "::ffff:127.0.0.1";
}
function parseComposePsServices(stdout) {
	const services = [];
	for (const line of stdout.split("\n")) {
		const trimmed = line.trim();
		if (!trimmed) continue;
		try {
			const parsed = JSON.parse(trimmed);
			services.push({
				service: String(parsed.Service ?? parsed.Name ?? ""),
				state: String(parsed.State ?? ""),
				health: String(parsed.Health ?? "")
			});
		} catch {
			continue;
		}
	}
	return services;
}
async function resolveLaunchRouting() {
	if (localStatusCache && localStatusCache.expiresAt > Date.now()) return localStatusCache.value;
	const state = getState();
	const installState = classifyLocalInstall(state.stackDir);
	const composeResult = await composePs(buildComposeOptions(state));
	const value = {
		installState,
		launch: deriveLaunchStatus({
			local: {
				state: deriveLocalStackState(installState, composeResult.ok ? parseComposePsServices(composeResult.stdout) : []),
				runtime: installState === "not_installed" ? await detectRuntime() : void 0,
				detail: { installState }
			},
			remotes: await listRemoteStatuses()
		}),
		migrationBlocking: isMigrationBlocking(state.homeDir)
	};
	localStatusCache = {
		value,
		expiresAt: Date.now() + 5e3
	};
	return value;
}
var handle = async ({ event, resolve }) => {
	const hostError = checkHostHeader(event.request, UI_PORT);
	if (hostError) return hostError;
	const originError = checkOriginHeader(event.request, UI_PORT);
	if (originError) return originError;
	const path = event.url.pathname;
	const isSetupPath = SETUP_PATHS.some((p) => path === p || path.startsWith(p + "/"));
	const setupComplete = setupCompleteMemo || isSetupComplete(resolveStackDir());
	if (setupComplete) setupCompleteMemo = true;
	if (isSetupPath && !setupComplete) {
		if (!isLocalhostAddress(event.getClientAddress())) return new Response(JSON.stringify({
			error: "setup_localhost_only",
			message: "Setup is only accessible from the host machine until installation is complete."
		}), {
			status: 403,
			headers: { "content-type": "application/json" }
		});
	}
	if (!isSetupPath) {
		const { installState, launch, migrationBlocking } = await resolveLaunchRouting();
		const desiredPath = migrationBlocking ? "/splash" : installState === "setup_incomplete" && launch.local.state === "running" ? "/splash" : launch.recommendedRoute === "chat" ? "/chat" : "/splash";
		const usageRoute = path.startsWith("/chat") || path.startsWith("/advanced");
		const exempt = path.startsWith("/api/") || path.startsWith("/proxy/") || path.startsWith("/login") || path.startsWith("/health") || path.startsWith("/guardian/health") || path.startsWith("/admin") || path.startsWith("/splash") || !migrationBlocking && usageRoute;
		if (path === "/" || path !== desiredPath && !exempt) redirect(302, desiredPath);
	}
	event.locals.role = identifyCallerByToken(event);
	let renewedCookie = null;
	if (event.locals.role === "admin") {
		const match = (event.request.headers.get("cookie") ?? "").match(new RegExp(`(?:^|;\\s*)${SESSION_COOKIE_NAME}=([^;]+)`));
		const renewed = match ? touchSession(match[1]) : false;
		if (renewed) renewedCookie = sessionCookieHeader(renewed, event.request);
	}
	const isAuthPath = path === "/login" || path.startsWith("/login/");
	if (event.request.method === "GET" && (event.request.headers.get("accept") ?? "").includes("text/html") && !event.locals.role && !isSetupPath && !isAuthPath) {
		const redirectTo = path + event.url.search;
		redirect(302, `/login?redirectTo=${encodeURIComponent(redirectTo)}`);
	}
	const response = await resolve(event);
	if (renewedCookie) {
		if (!(response.headers.get("set-cookie") ?? "").includes(`op_session=`)) response.headers.append("set-cookie", renewedCookie);
	}
	response.headers.set("X-Frame-Options", path === "/admin/akm/health-report" ? "SAMEORIGIN" : "DENY");
	response.headers.set("X-Content-Type-Options", "nosniff");
	response.headers.set("Referrer-Policy", "no-referrer");
	return response;
};

export { _resetLaunchCache, handle };
//# sourceMappingURL=hooks.server-BjQOtOyj.js.map
