All files / apps / api/src / server / firebase client.ts

98.43% Statements 63/64
96.29% Branches 26/27
100% Functions 13/13
100% Lines 57/57

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200                        29x   29x   29x 29x     29x     29x 29x                 236x             29x     29x 29x 29x                         29x 29x     56x 55x   55x   55x   55x       55x       61x 61x 61x 61x 61x 57x   56x 55x   55x         41x         20x       12x     11x 11x     1x     10x 10x   9x       15x   12x 9x 9x   8x 8x               8x                             8x         8x       15x 15x   12x                             11x         4x               3x 3x   3x         56x 56x    
import { Data, Effect } from 'effect'
import { importJWK, importPKCS8, SignJWT, type CryptoKey } from 'jose'
import { proxy } from 'hono/proxy'
import { z } from 'zod'
import { fetchJson } from '../../lib/outbound'
 
// The only file that talks to Google and Firebase (design 8.2, #21): signing keys for ID tokens,
// the service-account access token, and Firebase Admin REST (Identity Toolkit v1).
 
// The JWK form of the x509 keys firebase.google.com/docs/auth/admin/verify-id-tokens lists
// (…/robot/v1/metadata/x509/securetoken@…): same kids, and one loader serves both issuers.
const FIREBASE_JWKS_URL =
  'https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com'
// The jwks_uri of accounts.google.com/.well-known/openid-configuration
const GOOGLE_JWKS_URL = 'https://www.googleapis.com/oauth2/v3/certs'
// developers.google.com/identity/protocols/oauth2/service-account
const TOKEN_URL = 'https://oauth2.googleapis.com/token'
const IDENTITY_TOOLKIT = 'https://identitytoolkit.googleapis.com/v1'
// shortcut: emulator host and its "Bearer owner" admin token are unverified (from memory); fix if
// the emulator answers 401 to an admin call.
const EMULATOR_TOOLKIT = 'http://127.0.0.1:9099/identitytoolkit.googleapis.com/v1'
// shortcut: keys cached a fixed hour (the reply's max-age is not read), refetched on an unknown kid
// at most once a minute, so a rotation is picked up and a forged kid cannot flood Google.
const KEY_TTL_MS = 60 * 60 * 1000
const KEY_REFETCH_MS = 60 * 1000
 
export class FirebaseConfigError extends Data.TaggedError('FirebaseConfigError')<{
  readonly reason: string
}> {}
 
// AUTH_EMULATOR is in no wrangler.jsonc block, only the `dev` script and vitest pass it, so no
// deploy has it. demo- is Firebase's prefix for emulator-only projects: a second lock.
export function isAuthEmulator(env: Env): boolean {
  return (
    env.AUTH_EMULATOR === 'true' &&
    env.ENVIRONMENT === 'local' &&
    env.FIREBASE_PROJECT_ID.startsWith('demo-')
  )
}
 
const JwksSchema = z.object({
  keys: z.array(z.object({ kid: z.string(), kty: z.string(), n: z.string(), e: z.string() })),
})
const AccessTokenSchema = z.object({ access_token: z.string(), expires_in: z.number() })
const AnySchema = z.unknown()
const ServiceAccountSchema = z.object({
  client_email: z.string(),
  private_key: z.string(),
})
 
type KeySet = Map<string, CryptoKey>
 
interface Cached<T> {
  value: T
  fetchedAt: number
  expiresAt: number
}
 
const keyCache = new Map<string, Cached<KeySet>>()
const tokenCache = new Map<string, { value: string; expiresAt: number }>()
 
async function loadKeys(url: string): Promise<KeySet> {
  const { keys } = await Effect.runPromise(fetchJson({ url, decoder: JwksSchema }))
  const entries = await Promise.all(
    keys.map(async (jwk) => {
      const key = await importJWK({ ...jwk, alg: 'RS256' }, 'RS256')
      // importJWK answers a Uint8Array only for a symmetric (oct) key, which RS256 never is.
      Iif (key instanceof Uint8Array) throw new FirebaseConfigError({ reason: 'symmetric jwk' })
 
      return [jwk.kid, key] as const
    }),
  )
 
  return new Map(entries)
}
 
async function findKey(url: string, kid: string): Promise<CryptoKey | undefined> {
  const now = Date.now()
  const cached = keyCache.get(url)
  const isFresh = cached !== undefined && cached.expiresAt > now
  const hit = isFresh ? cached.value.get(kid) : undefined
  if (hit) return hit
  if (isFresh && now - cached.fetchedAt < KEY_REFETCH_MS) return undefined
 
  const keys = await loadKeys(url)
  keyCache.set(url, { value: keys, fetchedAt: now, expiresAt: now + KEY_TTL_MS })
 
  return keys.get(kid)
}
 
/** The public key that signed a Firebase ID token, or undefined for an unknown kid. */
export function getFirebaseKey(kid: string): Promise<CryptoKey | undefined> {
  return findKey(FIREBASE_JWKS_URL, kid)
}
 
/** The public key that signed a Google ID token, or undefined for an unknown kid. */
export function getGoogleKey(kid: string): Promise<CryptoKey | undefined> {
  return findKey(GOOGLE_JWKS_URL, kid)
}
 
function readServiceAccount(env: Env): z.infer<typeof ServiceAccountSchema> {
  if (!env.FIREBASE_SERVICE_ACCOUNT) throw new FirebaseConfigError({ reason: 'no service account' })
 
  let json: unknown
  try {
    json = JSON.parse(env.FIREBASE_SERVICE_ACCOUNT)
  } catch {
    // The parse error would quote the secret, so it is dropped on purpose.
    throw new FirebaseConfigError({ reason: 'service account is not JSON' })
  }
 
  const parsed = ServiceAccountSchema.safeParse(json)
  if (!parsed.success) throw new FirebaseConfigError({ reason: 'bad service account' })
 
  return parsed.data
}
 
async function getAccessToken(env: Env): Promise<string> {
  if (isAuthEmulator(env)) return 'owner'
 
  const account = readServiceAccount(env)
  const cached = tokenCache.get(account.client_email)
  if (cached && cached.expiresAt > Date.now()) return cached.value
 
  const nowSec = Math.floor(Date.now() / 1000)
  const assertion = await new SignJWT({ scope: 'https://www.googleapis.com/auth/identitytoolkit' })
    .setProtectedHeader({ alg: 'RS256', typ: 'JWT' })
    .setIssuer(account.client_email)
    .setAudience(TOKEN_URL)
    .setIssuedAt(nowSec)
    .setExpirationTime(nowSec + 3600)
    .sign(await importPKCS8(account.private_key, 'RS256'))
 
  const reply = await Effect.runPromise(
    fetchJson({
      url: TOKEN_URL,
      init: {
        method: 'POST',
        headers: { 'content-type': 'application/x-www-form-urlencoded' },
        body: new URLSearchParams({
          grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer',
          assertion,
        }).toString(),
      },
      decoder: AccessTokenSchema,
    }),
  )
  // Renew a minute early so a token never expires mid-call.
  tokenCache.set(account.client_email, {
    value: reply.access_token,
    expiresAt: Date.now() + (reply.expires_in - 60) * 1000,
  })
 
  return reply.access_token
}
 
async function callAccounts(env: Env, method: 'delete' | 'update', body: object): Promise<void> {
  const base = isAuthEmulator(env) ? EMULATOR_TOOLKIT : IDENTITY_TOOLKIT
  const token = await getAccessToken(env)
 
  await Effect.runPromise(
    fetchJson({
      url: `${base}/projects/${env.FIREBASE_PROJECT_ID}/accounts:${method}`,
      init: {
        method: 'POST',
        headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' },
        body: JSON.stringify(body),
      },
      decoder: AnySchema,
    }),
  )
}
 
/** Deletes a Firebase account; used when its domain is refused (design 4.1, B3). */
export function deleteFirebaseAccount(env: Env, uid: string): Promise<void> {
  return callAccounts(env, 'delete', { localId: uid })
}
 
/** Ends every refresh token issued before `validSinceMs` (sign out everywhere, 4.2). */
export function revokeFirebaseTokens(env: Env, uid: string, validSinceMs: number): Promise<void> {
  return callAccounts(env, 'update', {
    localId: uid,
    validSince: String(Math.floor(validSinceMs / 1000)),
  })
}
 
/** Forwards /__/auth/* to the project's firebaseapp.com helper, transparently (4.1, option 3). */
export function proxyAuthHelper(env: Env, request: Request): Promise<Response> {
  const url = new URL(request.url)
  const target = `https://${env.FIREBASE_PROJECT_ID}.firebaseapp.com${url.pathname}${url.search}`
 
  return proxy(target, { raw: request })
}
 
/** Test only: forget cached keys and access tokens. */
export function resetFirebaseCaches(): void {
  keyCache.clear()
  tokenCache.clear()
}