All files / src/lib firebase-auth.ts

91.66% Statements 66/72
87.5% Branches 28/32
100% Functions 6/6
91.66% Lines 66/72

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 1141x                   1x 1x 30x 30x     1x 1x                             15x 15x 9x 9x 6x     6x 6x 6x           1x 15x 15x   15x 6x 6x 6x 6x 6x 6x 6x 6x 4x 4x   6x       2x 2x 2x 2x 6x 6x 6x 15x   23x 23x 6x 6x 17x 23x     17x 17x     23x 23x 23x 23x 23x 23x 23x     21x 21x 21x 21x 21x 20x 10x 10x       11x 1x 1x 5x 5x  
import { AppError } from "@ontrack/backend-common";
import type { FastifyRequest } from "fastify";
import { createRemoteJWKSet, jwtVerify } from "jose";
import type { JWTVerifyGetKey, KeyLike } from "jose";
import type { EmailVerifiedChecker } from "./firebase-admin.js";
 
/**
 * Живая проверка email (Firebase Admin), настраивается один раз на старте.
 * Когда задана — `requireVerifiedUser` сверяет «протухший» токен с источником правды.
 */
let liveEmailCheck: EmailVerifiedChecker | null = null;
export function setLiveEmailCheck(fn: EmailVerifiedChecker | null): void {
  liveEmailCheck = fn;
}
 
/** Google's public keys for Firebase ID tokens (rotated; jose caches per Cache-Control). */
const FIREBASE_JWKS_URL =
  "https://www.googleapis.com/service_accounts/v1/jwk/[email protected]";
 
export type FirebaseUser = {
  uid: string;
  email: string;
  emailVerified: boolean;
  /** Display name from the token's `name` claim, if set. */
  name?: string;
};
 
export type IdTokenVerifier = (token: string) => Promise<FirebaseUser>;
 
type KeyInput = JWTVerifyGetKey | KeyLike | Uint8Array;
 
/** Normalize a key/JWKS/resolver into the single resolver shape jwtVerify expects. */
function toKeyResolver(keyInput?: KeyInput): JWTVerifyGetKey {
  if (keyInput === undefined) {
    return createRemoteJWKSet(new URL(FIREBASE_JWKS_URL));
  }
  if (typeof keyInput === "function") {
    return keyInput;
  }
  const key = keyInput;
  return () => key;
}
 
/**
 * Builds a verifier for Firebase ID tokens of the given project.
 * `keyInput` defaults to Google's remote JWKS; tests inject a local key.
 */
export function createIdTokenVerifier(projectId: string, keyInput?: KeyInput): IdTokenVerifier {
  const getKey = toKeyResolver(keyInput);
  const issuer = `https://securetoken.google.com/${projectId}`;
 
  return async (token: string): Promise<FirebaseUser> => {
    let payload;
    try {
      ({ payload } = await jwtVerify(token, getKey, {
        issuer,
        audience: projectId,
        algorithms: ["RS256"],
      }));
    } catch {
      throw new AppError(401, "UNAUTHORIZED", "Invalid or expired token");
    }
 
    if (!payload.sub || typeof payload.email !== "string") {
      throw new AppError(401, "UNAUTHORIZED", "Invalid token claims");
    }
 
    return {
      uid: payload.sub,
      email: payload.email,
      emailVerified: payload.email_verified === true,
      name: typeof payload.name === "string" ? payload.name : undefined,
    };
  };
}
 
function readBearerToken(header: string | undefined): string {
  if (!header) {
    throw new AppError(401, "UNAUTHORIZED", "Missing bearer token");
  }
  const [scheme, token] = header.split(" ");
  if (scheme !== "Bearer" || !token) {
    throw new AppError(401, "UNAUTHORIZED", "Missing bearer token");
  }
  return token;
}
 
/** Any authenticated (registered) user — valid Firebase ID token, verified email or not. */
export async function requireUser(
  request: FastifyRequest,
  verify: IdTokenVerifier,
): Promise<FirebaseUser> {
  const token = readBearerToken(request.headers.authorization);
  return verify(token);
}
 
/** Authenticated user with a verified email; otherwise 403. Used for writes (upload, geocode). */
export async function requireVerifiedUser(
  request: FastifyRequest,
  verify: IdTokenVerifier,
): Promise<FirebaseUser> {
  const user = await requireUser(request, verify);
  if (user.emailVerified) {
    return user;
  }
  // ID-токен лагает: `email_verified` обновляется только при ре-логине, поэтому сразу
  // после подтверждения (по письму ИЛИ админом) claim всё ещё false. Сверяемся с
  // источником правды в Firebase, чтобы не требовать перелогин для лайков/загрузки.
  if (liveEmailCheck && (await liveEmailCheck(user.uid))) {
    return { ...user, emailVerified: true };
  }
  throw new AppError(403, "EMAIL_NOT_VERIFIED", "Подтвердите email перед загрузкой.");
}