From 0b69fbfc72169d416a623aaa9179223da3d50533 Mon Sep 17 00:00:00 2001 From: M1 Date: Mon, 16 Mar 2026 15:56:33 +0400 Subject: [PATCH] fix: requireAuth uses onBeforeHandle instead of error() in derive --- apps/web/src/routes/auth.ts | 42 ++++++++++++++++++++----------------- 1 file changed, 23 insertions(+), 19 deletions(-) diff --git a/apps/web/src/routes/auth.ts b/apps/web/src/routes/auth.ts index 0abd853..bf73606 100644 --- a/apps/web/src/routes/auth.ts +++ b/apps/web/src/routes/auth.ts @@ -13,28 +13,32 @@ function hashEmail(email: string): string { } export function requireAuth(app: Elysia) { - return app.derive(async ({ headers, error }) => { - const key = headers["authorization"]?.replace("Bearer ", "").trim(); - if (!key) return error(401, { error: "Missing account key. Use: Authorization: Bearer " }); + return app + .derive(async ({ headers, set }) => { + const key = headers["authorization"]?.replace("Bearer ", "").trim(); + if (!key) { + set.status = 401; + return { accountId: null as string | null, keyId: null as string | null }; + } - // Check primary account key - const [account] = await sql`SELECT id FROM accounts WHERE id = ${key}`; - if (account) { - return { accountId: account.id, keyId: null as string | null }; - } + const [account] = await sql`SELECT id FROM accounts WHERE id = ${key}`; + if (account) return { accountId: account.id as string, keyId: null as string | null }; - // Check sub-key - const [apiKey] = await sql` - SELECT id, account_id FROM api_keys WHERE id = ${key} - `; - if (apiKey) { - // Update last_used_at async (don't await) - sql`UPDATE api_keys SET last_used_at = now() WHERE id = ${key}`.catch(() => {}); - return { accountId: apiKey.account_id, keyId: apiKey.id as string }; - } + const [apiKey] = await sql`SELECT id, account_id FROM api_keys WHERE id = ${key}`; + if (apiKey) { + sql`UPDATE api_keys SET last_used_at = now() WHERE id = ${key}`.catch(() => {}); + return { accountId: apiKey.account_id as string, keyId: apiKey.id as string }; + } - return error(401, { error: "Invalid account key" }); - }); + set.status = 401; + return { accountId: null as string | null, keyId: null as string | null }; + }) + .onBeforeHandle(({ accountId, set }) => { + if (!accountId) { + set.status = 401; + return { error: "Invalid or missing account key" }; + } + }); } export const account = new Elysia({ prefix: "/account" })