fix(fastify-auth): support getter functions for jwtSecret/jwksUrl

Allows dynamic config resolution (e.g. test mocks that change config between calls).
Options can now be string | (() => string) for both jwtSecret and jwksUrl.
This commit is contained in:
saravanakumardb1 2026-03-20 07:38:26 -07:00
parent f61a1f0b04
commit ea2cb4c0e6
2 changed files with 14 additions and 6 deletions

View File

@ -14,8 +14,16 @@ export function createAuthMiddleware(opts: FastifyAuthOptions) {
let jwks: ReturnType<typeof createRemoteJWKSet> | null = null; let jwks: ReturnType<typeof createRemoteJWKSet> | null = null;
let cachedJwksUrl: string | undefined; let cachedJwksUrl: string | undefined;
function resolveJwksUrl(): string | undefined {
return typeof opts.jwksUrl === 'function' ? opts.jwksUrl() : opts.jwksUrl;
}
function resolveJwtSecret(): string {
return typeof opts.jwtSecret === 'function' ? opts.jwtSecret() : opts.jwtSecret;
}
function getJWKS(): ReturnType<typeof createRemoteJWKSet> | null { function getJWKS(): ReturnType<typeof createRemoteJWKSet> | null {
const url = opts.jwksUrl; const url = resolveJwksUrl();
if (!url) return null; if (!url) return null;
if (jwks && cachedJwksUrl === url) return jwks; if (jwks && cachedJwksUrl === url) return jwks;
jwks = createRemoteJWKSet(new URL(url)); jwks = createRemoteJWKSet(new URL(url));
@ -24,7 +32,7 @@ export function createAuthMiddleware(opts: FastifyAuthOptions) {
} }
function getHmacSecret(): Uint8Array { function getHmacSecret(): Uint8Array {
return new TextEncoder().encode(opts.jwtSecret); return new TextEncoder().encode(resolveJwtSecret());
} }
/** /**

View File

@ -24,10 +24,10 @@ export interface JwtPayload {
/** Options for creating the auth middleware. */ /** Options for creating the auth middleware. */
export interface FastifyAuthOptions { export interface FastifyAuthOptions {
/** HS256 symmetric secret for JWT verification. */ /** HS256 symmetric secret for JWT verification. May be a getter for dynamic config. */
jwtSecret: string; jwtSecret: string | (() => string);
/** Optional RS256 JWKS endpoint URL (tried first, falls back to HS256). */ /** Optional RS256 JWKS endpoint URL (tried first, falls back to HS256). May be a getter. */
jwksUrl?: string; jwksUrl?: string | (() => string | undefined);
} }
/** Options for creating the request context helpers. */ /** Options for creating the request context helpers. */