UNPKG

next-firebase-auth-edge

Version:

Next.js Firebase Authentication for Edge and server runtimes. Compatible with latest Next.js features.

45 lines (44 loc) 1.87 kB
import { base64url, errors } from 'jose'; import { InvalidTokenError, InvalidTokenReason } from '../../../auth/error.js'; import { RotatingCredential } from '../../../auth/rotating-credential.js'; const textDecoder = new TextDecoder(); export class MultipleCookiesParser { cookies; cookieName; signatureKeys; constructor(cookies, cookieName, signatureKeys) { this.cookies = cookies; this.cookieName = cookieName; this.signatureKeys = signatureKeys; } async parseCookies() { const idTokenCookie = this.cookies.get(`${this.cookieName}.id`); const refreshTokenCookie = this.cookies.get(`${this.cookieName}.refresh`); const customTokenCookie = this.cookies.get(`${this.cookieName}.custom`); const metadataCookie = this.cookies.get(`${this.cookieName}.metadata`); const signatureCookie = this.cookies.get(`${this.cookieName}.sig`); if (![idTokenCookie, refreshTokenCookie, signatureCookie].every(Boolean)) { throw new InvalidTokenError(InvalidTokenReason.MISSING_CREDENTIALS); } const signature = signatureCookie; const customTokens = { idToken: idTokenCookie, refreshToken: refreshTokenCookie, customToken: customTokenCookie, metadata: metadataCookie ? JSON.parse(textDecoder.decode(base64url.decode(metadataCookie))) : {} }; const credential = new RotatingCredential(this.signatureKeys); try { await credential.verifySignature(customTokens, signature); return customTokens; } catch (e) { if (e instanceof errors.JWSSignatureVerificationFailed) { throw new InvalidTokenError(InvalidTokenReason.INVALID_SIGNATURE); } throw e; } } }