Auth providers

Firebase Authentication

firebase-adminverifySessionCookieverifyIdToken
Session Cookies for the browser, ID tokens for apps, and error codes mapped to 401 or 503.

The Firebase Admin SDK verifies a session Cookie with verifySessionCookie and an ID token with verifyIdToken. Its errors carry codes such as auth/id-token-expired. Map credential errors to 401 and let infrastructure errors through as 503.

server/auth/firebase-admin.ts
import { getApps, initializeApp } from 'firebase-admin/app'
import { getAuth } from 'firebase-admin/auth'

export const auth = getAuth(getApps()[0] ?? initializeApp())
server/auth/verify-user.ts
import { createError, getCookie, getHeader } from 'h3'
import type { VerifyUser } from '@kurashina-design/nuxt-bff-guard'
import { auth } from './firebase-admin'

// Errors that mean the backend or the configuration failed, not the user's credentials.
const infrastructure = new Set(['auth/internal-error', 'auth/invalid-credential', 'auth/project-not-found'])

export default (async (event) => {
  const authorization = getHeader(event, 'authorization')
  const bearer = /^Bearer[ \t]+([^\s,]+)$/i.exec(authorization ?? '')?.[1]
  const session = getCookie(event, '__session')

  if (!bearer && (authorization !== undefined || !session)) {
    throw createError({ statusCode: 401 })
  }

  try {
    const decoded = bearer
      ? await auth.verifyIdToken(bearer, true)
      : await auth.verifySessionCookie(session!, true)
    event.context.user = { uid: decoded.uid }
  }
  catch (error) {
    const code = (error as { code?: string }).code ?? ''
    if (code.startsWith('auth/') && !infrastructure.has(code)) {
      throw createError({ statusCode: 401 }) // expired, revoked, disabled, malformed…
    }
    throw error // app/network-error and friends → 503
  }

  return { viaBearer: Boolean(bearer) }
}) satisfies VerifyUser

The second argument true checks for revoked sessions, which makes a request to Firebase. Network failures there arrive as app/network-error and become 503.

When Firebase cannot download Google's public keys, the SDK reports auth/argument-error, the same code as a malformed token. That rare case answers 401. Keys are cached, so it only happens when they are refreshed.

The route that turns an ID token into a session Cookie runs before the Cookie exists, so it is public. It still needs your origin, because it is a POST.

server/api/session.post.ts
import { defineBffHandler } from '#bff-guard'
import { auth } from '../auth/firebase-admin'

const expiresIn = 1000 * 60 * 60 * 24 * 5 // 5 days

export default defineBffHandler(async (event) => {
  const { idToken } = await readBody<{ idToken: string }>(event)
  const decoded = await auth.verifyIdToken(idToken).catch(() => null)
  if (!decoded || Date.now() / 1000 - decoded.auth_time > 5 * 60) {
    throw createError({ statusCode: 401 }) // only recent sign-ins
  }
  const cookie = await auth.createSessionCookie(idToken, { expiresIn })
  setCookie(event, '__session', cookie, { maxAge: expiresIn / 1000, httpOnly: true, secure: true, sameSite: 'lax', path: '/' })
  return { ok: true }
}, { access: 'public' })