import { readTailscaleWhoisIdentity } from "../infra/tailscale.js";
import { isLoopbackHost } from "./host.js";
//#region src/gateway/tailscale-auth.ts
function parseTailscaleAuthHeaders(headers) {
	return {
		forwardedFor: headers["x-forwarded-for"]?.split(",")[0]?.trim(),
		forwardedProto: headers["x-forwarded-proto"]?.trim(),
		forwardedHost: headers["x-forwarded-host"]?.trim(),
		tailscaleUserLogin: headers["tailscale-user-login"]?.trim()
	};
}
function isTailscaleServeRequest(params) {
	if (!params.remoteAddress || !isLoopbackHost(params.remoteAddress)) return false;
	const { forwardedFor, forwardedProto, forwardedHost, tailscaleUserLogin } = params.headers;
	return Boolean(forwardedFor && forwardedProto && forwardedHost && tailscaleUserLogin);
}
function shouldAllowTailscaleIdentityAuth(cfg) {
	if ((cfg.gateway?.tailscale?.mode ?? "off") !== "serve") return false;
	if (cfg.gateway?.auth?.allowTailscale === false) return false;
	if (cfg.gateway?.auth?.mode === "password" || cfg.gateway?.auth?.mode === "trusted-proxy") return false;
	return true;
}
async function verifyTailscaleIdentity(params) {
	if (!shouldAllowTailscaleIdentityAuth(params.cfg)) return { ok: false };
	if (!isTailscaleServeRequest({
		remoteAddress: params.remoteAddress,
		headers: params.headers
	})) return { ok: false };
	const login = params.headers.tailscaleUserLogin;
	const clientIp = params.headers.forwardedFor;
	if (!login || !clientIp) return { ok: false };
	const identity = await readTailscaleWhoisIdentity(clientIp);
	if (!identity || identity.login !== login) return { ok: false };
	return {
		ok: true,
		login: identity.login
	};
}
/** Static gateway console routes that may skip token when Tailscale identity is verified. */
function isTailscaleUiBypassPath(path) {
	if (path === "/" || path === "/index.html") return true;
	if (path.startsWith("/assets/")) return true;
	return false;
}
//#endregion
export { isTailscaleServeRequest, isTailscaleUiBypassPath, parseTailscaleAuthHeaders, shouldAllowTailscaleIdentityAuth, verifyTailscaleIdentity };

//# sourceMappingURL=tailscale-auth.js.map