All files / apps / web/src / features / auth / lib session.ts

100% Statements 92/92
95.55% Branches 43/45
100% Functions 18/18
100% Lines 85/85

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 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237                                                            11x   11x 11x           2x 2x   2x                     43x   43x                   4x 4x   3x 3x   2x 1x           27x 25x 25x 25x   25x     27x         2x         1x         32x 32x       2x 2x   2x         2x 2x 1x 1x 1x 1x     1x     1x         4x 4x   2x 2x                     10x 10x 10x 10x       10x 4x 2x     2x 2x 2x 1x     6x 6x   3x 10x 1x   2x 1x             11x 11x 10x 11x 7x     3x       5x 5x 5x 5x 3x 3x   3x               15x         6x 1x   1x               6x 6x 6x   5x 5x     5x 2x 6x 1x   1x 1x    
import { AUTH_ERROR_CODE, HTTP_STATUS, type PublicConfig } from '@chattra/shared'
import {
  getRedirectResult,
  GoogleAuthProvider,
  signInWithCredential,
  signInWithRedirect,
  signOut,
  type Auth,
  type User,
} from 'firebase/auth'
import { fetchPublicConfig } from '@/features/shell'
import { ApiRequestError, setTokenGetter } from '@/lib/api'
import { initFirebaseAuth } from '@/lib/firebase'
import { createSession } from '../api'
import {
  createBrokerState,
  getBrokerUrl,
  getReturnUrl,
  isAllowedReturn,
  setLocation,
  takeBrokerHandoff,
} from './broker'
 
// Google sign-in through Firebase (design 4.1, 4.2). Redirect, not popup: the Google page runs
// through /__/auth/* on our own domain, and the desktop app cannot open popups (G21). Firebase
// keeps the person signed in and refreshes the short-lived ID token; apiFetch sends it as Bearer.
 
/** Why the dev site refused to sign in for a preview. */
export class BrokerError extends Error {
  constructor(
    readonly code: 'broker_unavailable' | 'broker_return_refused' | 'broker_state_mismatch',
  ) {
    super(code)
    this.name = 'BrokerError'
  }
}
 
// Both survive a trip away and back in this tab only: the preview's state while it waits for the
// broker, and on the dev site the preview's way back while Google signs in.
const BROKER_STATE_KEY = 'chattra.broker-state'
const BROKER_RETURN_KEY = 'chattra.broker-return'
 
const STATE_PATTERN = /^[A-Za-z0-9-]{1,64}$/
 
interface BrokerReturn {
  returnUrl: string
  state: string
}
 
let configReady: Promise<PublicConfig> | undefined
let authReady: Promise<Auth> | undefined
 
function getConfig(): Promise<PublicConfig> {
  configReady ??= fetchPublicConfig()
 
  return configReady
}
 
/**
 * The cached ID token, or a fresh one once it is about to expire. A refresh Firebase refuses
 * (token revoked, account disabled) signs the person out first (_logoutIfInvalidated in
 * @firebase/auth); then no token is sent, so the API's 401 runs the sign-out flow instead of
 * reading as "could not be reached".
 */
async function getCurrentToken(auth: Auth): Promise<string | null> {
  const user = auth.currentUser
  if (!user) return null
 
  try {
    return await user.getIdToken()
  } catch (error) {
    if (auth.currentUser === null) return null
    throw error
  }
}
 
/** Firebase Auth with the signed-in person restored; one config fetch per page load. */
export function getReadyAuth(): Promise<Auth> {
  authReady ??= getConfig().then(async (config) => {
    const auth = initFirebaseAuth(config)
    await auth.authStateReady()
    setTokenGetter(() => getCurrentToken(auth))
 
    return auth
  })
 
  return authReady
}
 
/** True while Firebase has a signed-in person in this browser (the guard of every shell route). */
export async function isSignedIn(): Promise<boolean> {
  return (await getReadyAuth()).currentUser !== null
}
 
/** Forgets the Firebase sign-in of this browser only; other devices stay signed in (AUTH-3). */
export async function signOutHere(): Promise<void> {
  await signOut(await getReadyAuth())
}
 
/** Test only. */
export function resetReadyAuth(): void {
  configReady = undefined
  authReady = undefined
}
 
function createGoogleProvider(): GoogleAuthProvider {
  const provider = new GoogleAuthProvider()
  provider.setCustomParameters({ prompt: 'select_account' })
 
  return provider
}
 
/** Google, or on a branch preview the dev site that signs in for it. */
export async function startSignIn(): Promise<void> {
  const brokerUrl = (await getConfig()).signIn?.brokerUrl
  if (brokerUrl) {
    const { origin, pathname, search } = window.location
    const state = createBrokerState()
    window.sessionStorage.setItem(BROKER_STATE_KEY, state)
    setLocation(getBrokerUrl(brokerUrl, `${origin}${pathname}${search}`, state), {
      shouldReplace: false,
    })
    return
  }
 
  await signInWithRedirect(await getReadyAuth(), createGoogleProvider())
}
 
// A refused sign-in must not leave a Firebase session behind that the app or /api/docs would use.
async function openSession(auth: Auth, user: User, googleIdToken: string): Promise<void> {
  try {
    await createSession(await user.getIdToken(), googleIdToken)
  } catch (error) {
    await signOut(auth)
    throw error
  }
}
 
/**
 * After Google (or the dev site, on a preview) sends the browser back: opens the session with
 * Google's ID token, which carries the Workspace domain (hd). When this load is neither, true if
 * the person is already signed in, so /signin sends them on instead of asking again.
 */
export async function completeSignIn(): Promise<boolean> {
  // Before any await, so the token leaves the address bar at once.
  const handoff = takeBrokerHandoff()
  const expectedState = window.sessionStorage.getItem(BROKER_STATE_KEY)
  window.sessionStorage.removeItem(BROKER_STATE_KEY)
  const auth = await getReadyAuth()
 
  // Only a preview takes a hand-off, and only the one it asked for: a link carrying someone
  // else's token would otherwise sign this browser in as them.
  if (handoff && (await getConfig()).signIn?.brokerUrl) {
    if (!expectedState || handoff.state !== expectedState) {
      throw new BrokerError('broker_state_mismatch')
    }
    // requestUri is http://localhost here, so the preview's host needs no Firebase setup.
    const credential = GoogleAuthProvider.credential(handoff.googleIdToken)
    const result = await signInWithCredential(auth, credential)
    await openSession(auth, result.user, handoff.googleIdToken)
    return true
  }
 
  const result = await getRedirectResult(auth)
  if (!result) return auth.currentUser !== null
 
  const googleIdToken = GoogleAuthProvider.credentialFromResult(result)?.idToken
  if (!googleIdToken)
    throw new ApiRequestError(HTTP_STATUS.unauthorized, AUTH_ERROR_CODE.invalidToken, null)
 
  await openSession(auth, result.user, googleIdToken)
  return true
}
 
async function getAllowedReturn(
  returnUrl: string | null,
  state: string | null,
): Promise<BrokerReturn> {
  const pattern = (await getConfig()).signIn?.brokerReturnPattern
  if (!pattern) throw new BrokerError('broker_unavailable')
  const isAllowed = returnUrl !== null && isAllowedReturn(returnUrl, pattern)
  if (!isAllowed || state === null || !STATE_PATTERN.test(state)) {
    throw new BrokerError('broker_return_refused')
  }
 
  return { returnUrl, state }
}
 
function readStoredReturn(): { returnUrl: string | null; state: string | null } {
  const stored = window.sessionStorage.getItem(BROKER_RETURN_KEY)
  window.sessionStorage.removeItem(BROKER_RETURN_KEY)
  const value: unknown = stored ? JSON.parse(stored) : null
  if (typeof value !== 'object' || value === null) return { returnUrl: null, state: null }
  const returnUrl: unknown = Reflect.get(value, 'returnUrl')
  const state: unknown = Reflect.get(value, 'state')
 
  return {
    returnUrl: typeof returnUrl === 'string' ? returnUrl : null,
    state: typeof state === 'string' ? state : null,
  }
}
 
/** The preview host the dev site would sign in for, shown before anyone goes to Google. */
export function getBrokerTarget(returnUrl: string | null): string | null {
  return returnUrl && URL.canParse(returnUrl) ? new URL(returnUrl).host : null
}
 
/** On the dev site: signs in with Google for the preview page `returnUrl`. */
export async function startBroker(returnUrl: string | null, state: string | null): Promise<void> {
  const allowed = await getAllowedReturn(returnUrl, state)
  window.sessionStorage.setItem(BROKER_RETURN_KEY, JSON.stringify(allowed))
 
  await signInWithRedirect(await getReadyAuth(), createGoogleProvider())
}
 
/**
 * On the dev site, back from Google: hands Google's ID token to the preview and keeps no session
 * here. False when this load is not a return from Google.
 */
export async function completeBroker(): Promise<boolean> {
  const auth = await getReadyAuth()
  const result = await getRedirectResult(auth)
  if (!result) return false
 
  const stored = readStoredReturn()
  await signOut(auth)
 
  // Checked again: sessionStorage is this origin's, but the pattern is the only authority.
  const { returnUrl, state } = await getAllowedReturn(stored.returnUrl, stored.state)
  const googleIdToken = GoogleAuthProvider.credentialFromResult(result)?.idToken
  if (!googleIdToken)
    throw new ApiRequestError(HTTP_STATUS.unauthorized, AUTH_ERROR_CODE.invalidToken, null)
 
  setLocation(getReturnUrl(returnUrl, { googleIdToken, state }), { shouldReplace: true })
  return true
}