Replace the ALLOWED_USER_IDS sub-allowlist with a Zitadel project role check: tokens must carry the role from REQUIRED_ROLE (default "user") in the urn:zitadel:iam:org:project[:id]:roles claim. Roles are granted per account in Zitadel (project ClaudeDo), where access is now managed. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
45 lines
1.8 KiB
TypeScript
45 lines
1.8 KiB
TypeScript
import { decodeJwt } from "jose";
|
|
|
|
// Gates every /api/** route. Static SPA assets stay public.
|
|
export default defineEventHandler(async (event) => {
|
|
const path = getRequestURL(event).pathname;
|
|
if (!path.startsWith("/api/")) return;
|
|
|
|
// Dev-only bypass for local smoke tests. `import.meta.dev` is false in production
|
|
// builds, so this branch is dead-code-eliminated and can never run when deployed.
|
|
if (import.meta.dev && process.env.AUTH_DEV_BYPASS === "1") {
|
|
event.context.user = { sub: "dev" };
|
|
return;
|
|
}
|
|
|
|
// CORS preflight is answered (and short-circuited) by 0.cors.ts before this runs.
|
|
const header = getHeader(event, "authorization") || "";
|
|
const token = header.startsWith("Bearer ") ? header.slice(7).trim() : "";
|
|
if (!token) {
|
|
if (process.env.AUTH_DEBUG === "1") console.error("[auth] no bearer token on", path);
|
|
throw createError({ statusCode: 401, statusMessage: "Unauthorized" });
|
|
}
|
|
|
|
try {
|
|
event.context.user = await getVerifier()(token);
|
|
} catch (e) {
|
|
if (process.env.AUTH_DEBUG === "1") {
|
|
let claims: Record<string, unknown> = {};
|
|
try {
|
|
const c = decodeJwt(token);
|
|
const roleClaims = Object.keys(c).filter((k) => k.includes(":project:") && k.endsWith(":roles"));
|
|
claims = { iss: c.iss, sub: c.sub, aud: c.aud, azp: c.azp, exp: c.exp, roleClaims, alg_present: true };
|
|
} catch (de) {
|
|
claims = { not_a_jwt: String(de).slice(0, 80) };
|
|
}
|
|
console.error(
|
|
"[auth] verify failed:", (e as Error).message,
|
|
"| claims:", JSON.stringify(claims),
|
|
"| REQUIRED_ROLE:", process.env.REQUIRED_ROLE || "user",
|
|
"| ZITADEL_AUDIENCE:", process.env.ZITADEL_AUDIENCE,
|
|
);
|
|
}
|
|
throw createError({ statusCode: 401, statusMessage: "Unauthorized" });
|
|
}
|
|
});
|