From 10b675c2b71e362986fd03984a881ffdc88bdded Mon Sep 17 00:00:00 2001 From: tobias Date: Tue, 17 Mar 2026 02:55:48 +0700 Subject: [PATCH] refactor: enhance JWT verification key handling in Privy client - Introduced a new function to resolve the JWT verification key from environment variables, supporting both raw PEM and base64 formats. - Updated the PrivyClient instantiation to conditionally include the jwtVerificationKey based on the resolved value. --- lib/privy/client.ts | 27 +++++++++++++++++++++------ 1 file changed, 21 insertions(+), 6 deletions(-) diff --git a/lib/privy/client.ts b/lib/privy/client.ts index ed3354c7..4147ff72 100644 --- a/lib/privy/client.ts +++ b/lib/privy/client.ts @@ -1,15 +1,30 @@ import { PrivyClient } from "@privy-io/node"; -// Decode JWT verification key from base64 -const decodedJwtVerificationKey = Buffer.from( - process.env.PRIVY_JWT_VERIFICATION_KEY!, - "base64", -).toString("utf8"); +/** + * Privy "Verify with key instead" value may be: + * - Raw PEM (-----BEGIN ...-----) — paste as-is + * - Base64 of that PEM — legacy / docs format + * If unset, @privy-io/node fetches JWKS from Privy (works locally; slightly slower first verify). + */ +function resolveJwtVerificationKey(): string | undefined { + const raw = process.env.PRIVY_JWT_VERIFICATION_KEY?.trim(); + if (!raw) return undefined; + if (raw.includes("BEGIN")) return raw; + try { + const decoded = Buffer.from(raw, "base64").toString("utf8"); + if (decoded.includes("BEGIN")) return decoded; + } catch { + /* ignore */ + } + return raw; +} + +const jwtVerificationKey = resolveJwtVerificationKey(); const privyClient = new PrivyClient({ appId: process.env.PRIVY_APP_ID!, appSecret: process.env.PRIVY_PROJECT_SECRET!, - jwtVerificationKey: decodedJwtVerificationKey, + ...(jwtVerificationKey ? { jwtVerificationKey } : {}), }); export default privyClient;