import "../../../../../base64-CmWvODNW.mjs";
import "../../../../../types-CuW0zWDA.mjs";
import { t as OptionsRepository } from "../../../../../options-DTTML-Tx.mjs";
import { n as apiSuccess, r as handleError, t as apiError } from "../../../../../error-CkAseSqZ.mjs";
import { r as parseOptionalBody, t as isParseError } from "../../../../../parse-GmjecGct.mjs";
import "../../../../../redirects-DXEXBAII.mjs";
import { C as passkeyOptionsBody } from "../../../../../byline-fields-2Lp5Hbgf.mjs";
import "../../../../../status-CqJQX1QN.mjs";
import "../../../../../api/schemas/index.mjs";
import { t as getTrustedProxyHeaders } from "../../../../../trusted-proxy-VTPRiX2s.mjs";
import { n as getPublicOrigin } from "../../../../../public-url-Danv47cS.mjs";
import { n as createChallengeStore, t as cleanupExpiredChallenges } from "../../../../../challenge-store-anhwVER0.mjs";
import { t as getPasskeyConfig } from "../../../../../passkey-config-De0ahnRg.mjs";
import { n as getClientIp, r as rateLimitResponse, t as checkRateLimit } from "../../../../../rate-limit-C_Lf63Dd.mjs";
import { createKyselyAdapter } from "@emdash-cms/auth/adapters/kysely";
import { generateAuthenticationOptions } from "@emdash-cms/auth/passkey";

//#region src/astro/routes/api/auth/passkey/options.ts
const prerender = false;
const POST = async ({ request, locals }) => {
	const { emdash } = locals;
	if (!emdash?.db) return apiError("NOT_CONFIGURED", "EmDash is not initialized", 500);
	try {
		cleanupExpiredChallenges(emdash.db).catch(() => {});
		const body = await parseOptionalBody(request, passkeyOptionsBody, {});
		if (isParseError(body)) return body;
		const ip = getClientIp(request, getTrustedProxyHeaders(emdash.config));
		if (!(await checkRateLimit(emdash.db, ip, "passkey/options", 10, 60)).allowed) return rateLimitResponse(60);
		const adapter = createKyselyAdapter(emdash.db);
		let credentials = [];
		if (body.email) {
			const user = await adapter.getUserByEmail(body.email);
			if (user) credentials = await adapter.getCredentialsByUserId(user.id);
		}
		const url = new URL(request.url);
		const passkeyConfig = getPasskeyConfig(url, await new OptionsRepository(emdash.db).get("emdash:site_title") ?? void 0, getPublicOrigin(url, emdash?.config));
		const challengeStore = createChallengeStore(emdash.db);
		return apiSuccess({
			success: true,
			options: await generateAuthenticationOptions(passkeyConfig, credentials, challengeStore)
		});
	} catch (error) {
		return handleError(error, "Failed to generate passkey options", "PASSKEY_OPTIONS_ERROR");
	}
};

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