import "../../../../../base64-CmWvODNW.mjs";
import "../../../../../types-CuW0zWDA.mjs";
import { a as unwrapResult, r as handleError, t as apiError } from "../../../../../error-CkAseSqZ.mjs";
import { n as parseBody, t as isParseError } from "../../../../../parse-GmjecGct.mjs";
import { t as getTrustedProxyHeaders } from "../../../../../trusted-proxy-VTPRiX2s.mjs";
import "../../../../../api-tokens-DsvvCtdh.mjs";
import "../../../../../oauth-user-lookup-Bsc_GsX-.mjs";
import { r as handleDeviceTokenExchange } from "../../../../../device-flow-CfGP18Uw.mjs";
import { n as getClientIp, r as rateLimitResponse, t as checkRateLimit } from "../../../../../rate-limit-C_Lf63Dd.mjs";
import { z } from "zod";

//#region src/astro/routes/api/oauth/device/token.ts
const prerender = false;
const deviceTokenSchema = z.object({
	device_code: z.string().min(1),
	grant_type: z.string().min(1)
});
const POST = async ({ request, locals }) => {
	const { emdash } = locals;
	if (!emdash?.db) return apiError("NOT_CONFIGURED", "EmDash is not initialized", 500);
	try {
		const body = await parseBody(request, deviceTokenSchema);
		if (isParseError(body)) return body;
		const ip = getClientIp(request, getTrustedProxyHeaders(emdash.config));
		if (!(await checkRateLimit(emdash.db, ip, "device/token", 12, 60)).allowed) return rateLimitResponse(60);
		const result = await handleDeviceTokenExchange(emdash.db, body);
		if (!result.success && result.deviceFlowError) {
			const errorBody = { error: result.deviceFlowError };
			if (result.deviceFlowInterval !== void 0) errorBody.interval = result.deviceFlowInterval;
			return Response.json(errorBody, {
				status: 400,
				headers: {
					"Content-Type": "application/json",
					"Cache-Control": "no-store",
					Pragma: "no-cache"
				}
			});
		}
		return unwrapResult(result);
	} catch (error) {
		return handleError(error, "Failed to exchange device code", "TOKEN_EXCHANGE_ERROR");
	}
};

//#endregion
export { POST, prerender };
//# sourceMappingURL=token.mjs.map