import { H as createLogger } from './src-CidJbygh.js';
import { d as getRequestId, r as requireAdmin, e as errorResponse, g as getOpenCodeClient, k as jsonResponse, p as parseJsonBody, j as jsonBodyError } from './helpers-kzwksNq1.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';
import './endpoints-UdQGgKsR.js';
import './state-fxN45gBp.js';

//#region src/routes/admin/opencode/providers/[id]/auth/+server.ts
var logger = createLogger("opencode.auth");
var MAX_API_KEY_LENGTH = 512;
var API_KEY_PATTERN = /^[\x20-\x7E]+$/;
var OAUTH_SESSION_TTL_MS = 6e5;
var MAX_PROVIDER_ID_LENGTH = 128;
var PROVIDER_ID_PATTERN = /^[a-zA-Z0-9_.-]+$/;
function validateApiKey(key) {
	if (key.length > MAX_API_KEY_LENGTH) return "API key exceeds maximum length";
	if (!API_KEY_PATTERN.test(key)) return "API key contains invalid characters";
	return null;
}
var oauthSessions = /* @__PURE__ */ new Map();
function purgeExpiredSessions() {
	const now = Date.now();
	for (const [token, session] of oauthSessions) if (now - session.createdAt > OAUTH_SESSION_TTL_MS) oauthSessions.delete(token);
}
var GET = async (event) => {
	const requestId = getRequestId(event);
	const authError = requireAdmin(event, requestId);
	if (authError) return authError;
	const pollToken = event.url.searchParams.get("pollToken");
	if (!pollToken) return errorResponse(400, "bad_request", "pollToken query parameter is required", {}, requestId);
	purgeExpiredSessions();
	const session = oauthSessions.get(pollToken);
	if (!session) return errorResponse(404, "not_found", "Poll session not found or expired", {}, requestId);
	if (event.params.id !== session.providerId) return errorResponse(400, "bad_request", "Provider ID does not match poll session", {}, requestId);
	if ((await getOpenCodeClient().completeProviderOAuth(session.providerId, session.methodIndex)).ok) {
		oauthSessions.delete(pollToken);
		logger.info("oauth authorization completed", {
			providerId: session.providerId,
			requestId
		});
		return jsonResponse(200, {
			status: "complete",
			message: "Authorization successful"
		}, requestId);
	}
	if (Date.now() - session.createdAt > OAUTH_SESSION_TTL_MS) {
		oauthSessions.delete(pollToken);
		return jsonResponse(200, {
			status: "error",
			message: "Authorization session expired"
		}, requestId);
	}
	return jsonResponse(200, {
		status: "pending",
		message: "Waiting for authorization..."
	}, requestId);
};
var POST = async (event) => {
	const requestId = getRequestId(event);
	const authError = requireAdmin(event, requestId);
	if (authError) return authError;
	const result = await parseJsonBody(event.request);
	if ("error" in result) return jsonBodyError(result, requestId);
	const body = result.data;
	const providerId = event.params.id;
	const mode = typeof body.mode === "string" ? body.mode : "";
	if (!providerId || providerId.length > MAX_PROVIDER_ID_LENGTH || !PROVIDER_ID_PATTERN.test(providerId)) return errorResponse(400, "bad_request", "Invalid provider ID", {}, requestId);
	purgeExpiredSessions();
	if (mode === "api_key") {
		const apiKey = typeof body.apiKey === "string" ? body.apiKey.trim() : "";
		if (!apiKey) return errorResponse(400, "bad_request", "apiKey is required for api_key mode", {}, requestId);
		const keyError = validateApiKey(apiKey);
		if (keyError) return errorResponse(400, "bad_request", keyError, {}, requestId);
		const result = await getOpenCodeClient().setProviderApiKey(providerId, apiKey);
		if (!result.ok) {
			logger.warn("provider api key save failed", {
				providerId,
				requestId,
				error: result.code
			});
			return errorResponse(result.status, result.code, result.message, {}, requestId);
		}
		logger.info("provider API key saved to OpenCode auth.json", {
			providerId,
			requestId
		});
		return jsonResponse(200, {
			ok: true,
			mode: "api_key"
		}, requestId);
	}
	if (mode === "oauth") {
		if (typeof body.methodIndex !== "undefined" && (typeof body.methodIndex !== "number" || !Number.isInteger(body.methodIndex) || body.methodIndex < 0)) return errorResponse(400, "bad_request", "methodIndex must be a non-negative integer", {}, requestId);
		const methodIndex = typeof body.methodIndex === "number" ? body.methodIndex : 0;
		const result = await getOpenCodeClient().startProviderOAuth(providerId, methodIndex);
		if (!result.ok) return errorResponse(result.status, result.code, result.message, {}, requestId);
		const data = result.data;
		const pollToken = crypto.randomUUID();
		oauthSessions.set(pollToken, {
			providerId,
			methodIndex,
			createdAt: Date.now()
		});
		logger.info("oauth authorization started", {
			providerId,
			methodIndex,
			requestId
		});
		return jsonResponse(200, {
			ok: true,
			mode: "oauth",
			pollToken,
			url: data.url,
			method: data.method,
			instructions: data.instructions
		}, requestId);
	}
	return errorResponse(400, "bad_request", "mode must be api_key or oauth", {}, requestId);
};
/**
* DELETE /admin/opencode/providers/:id/auth — Disconnect a provider by
* removing its credential from OpenCode's auth.json.
*/
var DELETE = async (event) => {
	const requestId = getRequestId(event);
	const authError = requireAdmin(event, requestId);
	if (authError) return authError;
	const providerId = event.params.id ?? "";
	if (!providerId || providerId.length > MAX_PROVIDER_ID_LENGTH || !PROVIDER_ID_PATTERN.test(providerId)) return errorResponse(400, "bad_request", "Invalid provider ID", {}, requestId);
	const result = await getOpenCodeClient().proxy(`/auth/${encodeURIComponent(providerId)}`, { method: "DELETE" });
	if (!result.ok) {
		logger.warn("provider disconnect failed", {
			providerId,
			requestId,
			error: result.code
		});
		return errorResponse(result.status, result.code, result.message, {}, requestId);
	}
	logger.info("provider credential removed via OpenCode /auth DELETE", {
		providerId,
		requestId
	});
	return jsonResponse(200, { ok: true }, requestId);
};

export { DELETE, GET, POST };
//# sourceMappingURL=_server.ts-JejNP4uV.js.map
