All files / apps / api/src / server / auth tokens.ts

100% Statements 44/44
100% Branches 26/26
100% Functions 11/11
100% Lines 38/38

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                    29x   29x   29x               29x                                                   17x       196x 196x   3x                       56x 56x     56x 55x   53x                   48x   8x 1x                   137x   134x 134x   1x             60x   2x 2x   1x             4x       182x 182x   181x         138x       138x     126x     125x   124x                   60x             56x   56x                       106x   106x    
import { AUTH_ERROR_CODE } from '@chattra/shared'
import { decodeProtectedHeader, errors, jwtVerify, UnsecuredJWT, type JWTPayload } from 'jose'
import { z } from 'zod'
import { getFirebaseKey, getGoogleKey, isAuthEmulator } from '../firebase/client'
import { ApiHttpError } from '../http'
 
// ID token checks (design 4.1, 4.2), with jose because the Firebase Admin SDK needs Node.
// Claim rules: firebase.google.com/docs/auth/admin/verify-id-tokens and
// developers.google.com/identity/openid-connect/openid-connect (iss, aud, hd, key by sub).
 
const GOOGLE_ISSUERS = ['https://accounts.google.com', 'accounts.google.com']
// Clock skew allowed on iat, exp and auth_time.
const SKEW_SEC = 30
 
const FirebaseClaimsSchema = z.object({
  sub: z.string().min(1),
  auth_time: z.number().int(),
  firebase: z.object({
    identities: z.object({ 'google.com': z.tuple([z.string()]).rest(z.string()) }),
  }),
})
 
const GoogleClaimsSchema = z.object({
  sub: z.string().min(1),
  email: z.string().min(3),
  email_verified: z.boolean(),
  hd: z.string().optional(),
  name: z.string().optional(),
  picture: z.string().optional(),
})
 
export interface FirebaseIdentity {
  uid: string
  /** Seconds, as Firebase gives it; one session per (user, auth_time). */
  authTime: number
  googleSub: string
}
 
export interface GoogleIdentity {
  sub: string
  email: string
  emailVerified: boolean
  hd: string | undefined
  name: string | undefined
  picture: string | undefined
}
 
function invalidToken(): ApiHttpError {
  return new ApiHttpError(AUTH_ERROR_CODE.invalidToken, 'Invalid or expired token')
}
 
function isUnsigned(token: string): boolean {
  try {
    return decodeProtectedHeader(token).alg === 'none'
  } catch {
    throw invalidToken()
  }
}
 
type KeyLookup = (kid: string) => Promise<CryptoKey | undefined>
 
// jose's own errors mean a bad token (401); anything else, such as Google not answering, is ours.
async function verifySigned(
  token: string,
  lookup: KeyLookup,
  options: { issuer: string | string[]; audience: string },
): Promise<JWTPayload> {
  try {
    const { payload } = await jwtVerify(
      token,
      async (header) => {
        const key = header.kid ? await lookup(header.kid) : undefined
        if (!key) throw new errors.JWKSNoMatchingKey()
 
        return key
      },
      {
        ...options,
        algorithms: ['RS256'],
        clockTolerance: SKEW_SEC,
        requiredClaims: ['iat', 'exp', 'sub'],
      },
    )
 
    return payload
  } catch (error) {
    if (error instanceof errors.JOSEError) throw invalidToken()
    throw error
  }
}
 
// The Auth emulator signs nothing: accepted only when isAuthEmulator (local flag, env, demo- project).
function decodeUnsigned(
  env: Env,
  token: string,
  options: { issuer?: string; audience?: string },
): JWTPayload {
  if (!isAuthEmulator(env)) throw invalidToken()
 
  try {
    return UnsecuredJWT.decode(token, { ...options, clockTolerance: SKEW_SEC }).payload
  } catch {
    throw invalidToken()
  }
}
 
// The emulator's sign-in page hands over Google's claims as plain JSON, not a JWT, and has no
// field for hd (firebase-tools lib/emulator/auth/widget_ui.js createFakeClaims).
function decodeEmulatorJson(env: Env, token: string): unknown {
  if (!isAuthEmulator(env) || !token.startsWith('{')) return undefined
 
  try {
    return JSON.parse(token)
  } catch {
    throw invalidToken()
  }
}
 
// Emulator only: hd from the email, so a local account can reach a workspace. Real tokens never
// get here; their hd comes from Google alone (design 4.1).
function emulatorHd(env: Env, email: string): string | undefined {
  return isAuthEmulator(env) ? email.slice(email.lastIndexOf('@') + 1).toLowerCase() : undefined
}
 
function parseClaims<T>(schema: z.ZodType<T>, payload: unknown): T {
  const parsed = schema.safeParse(payload)
  if (!parsed.success) throw invalidToken()
 
  return parsed.data
}
 
/** Verifies a Firebase ID token; throws 401 invalid_token. */
export async function verifyFirebaseToken(env: Env, token: string): Promise<FirebaseIdentity> {
  const options = {
    issuer: `https://securetoken.google.com/${env.FIREBASE_PROJECT_ID}`,
    audience: env.FIREBASE_PROJECT_ID,
  }
  const payload = isUnsigned(token)
    ? decodeUnsigned(env, token, options)
    : await verifySigned(token, getFirebaseKey, options)
  const claims = parseClaims(FirebaseClaimsSchema, payload)
 
  // "auth_time: Must be in the past."
  if (claims.auth_time > Math.floor(Date.now() / 1000) + SKEW_SEC) throw invalidToken()
 
  return {
    uid: claims.sub,
    authTime: claims.auth_time,
    googleSub: claims.firebase.identities['google.com'][0],
  }
}
 
/** Verifies Google's own ID token, the one that carries `hd`; throws 401 invalid_token. */
export async function verifyGoogleToken(env: Env, token: string): Promise<GoogleIdentity> {
  const payload =
    decodeEmulatorJson(env, token) ??
    (isUnsigned(token)
      ? decodeUnsigned(env, token, {})
      : await verifySigned(token, getGoogleKey, {
          issuer: GOOGLE_ISSUERS,
          audience: env.GOOGLE_OAUTH_CLIENT_ID,
        }))
  const claims = parseClaims(GoogleClaimsSchema, payload)
 
  return {
    sub: claims.sub,
    email: claims.email,
    emailVerified: claims.email_verified,
    hd: claims.hd ?? emulatorHd(env, claims.email),
    name: claims.name,
    picture: claims.picture,
  }
}
 
/** The token from `Authorization: Bearer <token>`, or undefined. */
export function readBearer(header: string | undefined): string | undefined {
  const match = header?.match(/^Bearer ([\w.-]+)$/)
 
  return match?.[1]
}