|
| 1 | +import { createRemoteJWKSet, jwtVerify } from "jose"; |
| 2 | +import { db } from "@onecli/db"; |
| 3 | +import { OAUTH_ISSUER, OAUTH_AUDIENCE, OAUTH_JWKS_URL } from "@/lib/env"; |
| 4 | +import { logger } from "@/lib/logger"; |
| 5 | + |
| 6 | +export interface JwtAuth { |
| 7 | + userId: string; |
| 8 | + accountId: string; |
| 9 | +} |
| 10 | + |
| 11 | +const log = logger.child({ module: "validate-jwt" }); |
| 12 | + |
| 13 | +// Module-level singletons — persist across requests in the Node.js process. |
| 14 | +let cachedJwksUri: string | null = null; |
| 15 | +let cachedGetKey: ReturnType<typeof createRemoteJWKSet> | null = null; |
| 16 | + |
| 17 | +const resolveJwksUri = async (): Promise<string | null> => { |
| 18 | + if (cachedJwksUri) return cachedJwksUri; |
| 19 | + |
| 20 | + if (OAUTH_JWKS_URL) { |
| 21 | + cachedJwksUri = OAUTH_JWKS_URL; |
| 22 | + return cachedJwksUri; |
| 23 | + } |
| 24 | + |
| 25 | + try { |
| 26 | + const res = await fetch(`${OAUTH_ISSUER}/.well-known/openid-configuration`); |
| 27 | + const doc = (await res.json()) as { jwks_uri?: string }; |
| 28 | + if (!doc.jwks_uri) { |
| 29 | + log.warn("OIDC discovery response missing jwks_uri"); |
| 30 | + return null; |
| 31 | + } |
| 32 | + cachedJwksUri = doc.jwks_uri; |
| 33 | + return cachedJwksUri; |
| 34 | + } catch (err) { |
| 35 | + log.warn({ err }, "OIDC discovery failed"); |
| 36 | + return null; |
| 37 | + } |
| 38 | +}; |
| 39 | + |
| 40 | +const getKeyFunction = async (): Promise<ReturnType< |
| 41 | + typeof createRemoteJWKSet |
| 42 | +> | null> => { |
| 43 | + if (cachedGetKey) return cachedGetKey; |
| 44 | + |
| 45 | + const jwksUri = await resolveJwksUri(); |
| 46 | + if (!jwksUri) return null; |
| 47 | + |
| 48 | + cachedGetKey = createRemoteJWKSet(new URL(jwksUri)); |
| 49 | + return cachedGetKey; |
| 50 | +}; |
| 51 | + |
| 52 | +const extractBearerToken = (request: Request): string | null => { |
| 53 | + const header = request.headers.get("authorization"); |
| 54 | + if (!header) return null; |
| 55 | + const token = header.startsWith("Bearer ") ? header.slice(7).trim() : null; |
| 56 | + if (!token || token.startsWith("oc_")) return null; |
| 57 | + return token; |
| 58 | +}; |
| 59 | + |
| 60 | +const lookupUser = async (externalAuthId: string): Promise<JwtAuth | null> => { |
| 61 | + const user = await db.user.findUnique({ |
| 62 | + where: { externalAuthId }, |
| 63 | + select: { |
| 64 | + id: true, |
| 65 | + memberships: { select: { accountId: true }, take: 1 }, |
| 66 | + }, |
| 67 | + }); |
| 68 | + |
| 69 | + if (!user || user.memberships.length === 0) { |
| 70 | + log.warn({ sub: externalAuthId }, "JWT auth: user or account not found"); |
| 71 | + return null; |
| 72 | + } |
| 73 | + |
| 74 | + return { userId: user.id, accountId: user.memberships[0]!.accountId }; |
| 75 | +}; |
| 76 | + |
| 77 | +/** |
| 78 | + * Validate an OAuth access token (JWT) from a request's `Authorization: Bearer ...` header. |
| 79 | + * Verifies signature via JWKS, checks issuer + audience + expiration, then resolves the user. |
| 80 | + * Returns null (and logs a warning) on any failure, allowing fallthrough to session auth. |
| 81 | + */ |
| 82 | +export const validateJwt = async ( |
| 83 | + request: Request, |
| 84 | +): Promise<JwtAuth | null> => { |
| 85 | + if (!OAUTH_ISSUER) return null; |
| 86 | + |
| 87 | + const token = extractBearerToken(request); |
| 88 | + if (!token) return null; |
| 89 | + |
| 90 | + const getKey = await getKeyFunction(); |
| 91 | + if (!getKey) return null; |
| 92 | + |
| 93 | + try { |
| 94 | + const { payload } = await jwtVerify(token, getKey, { |
| 95 | + issuer: OAUTH_ISSUER, |
| 96 | + audience: OAUTH_AUDIENCE || undefined, |
| 97 | + algorithms: ["RS256", "RS384", "RS512"], |
| 98 | + }); |
| 99 | + |
| 100 | + const sub = payload.sub; |
| 101 | + if (!sub) { |
| 102 | + log.warn("JWT missing sub claim"); |
| 103 | + return null; |
| 104 | + } |
| 105 | + |
| 106 | + return await lookupUser(sub); |
| 107 | + } catch (err) { |
| 108 | + log.warn({ err }, "JWT validation failed"); |
| 109 | + return null; |
| 110 | + } |
| 111 | +}; |
0 commit comments