@@ -3,22 +3,35 @@ import fs from 'node:fs';
33import path from 'node:path' ;
44import { getEnvConfig , nonEmpty } from '../app/utils/config' ;
55
6- /**
7- * Centralized Firebase Admin initialization.
8- * Prefers explicit service account credentials via env.
9- * Fallback to ADC only when GOOGLE_APPLICATION_CREDENTIALS is set.
10- */
6+ let adminApp : App | undefined ;
117
128/**
13- * Server-only Firebase Admin SDK initialization.
14- * Uses Application Default Credentials (ADC) which works automatically on Cloud Run.
15- * For local development, you can either:
16- * 1. Run `gcloud auth application-default login`
17- * 2. Set GOOGLE_APPLICATION_CREDENTIALS env var to a service account JSON path
9+ * ensureAdminInitialized
10+ * Creates or reuses a singleton Firebase Admin App.
11+ *
12+ * Selection order:
13+ * 1) Reuse an existing Admin app from `getApps()`, preferring the one whose
14+ * `options.projectId` matches `NEXT_PUBLIC_FIREBASE_PROJECT_ID`; falls back
15+ * to the first app if no match.
16+ * 2) If `GOOGLE_SA_JSON` is set (server-only inline JSON), parse and initialize
17+ * with `cert(serviceAccount)`.
18+ * 3) If `GOOGLE_SA_JSON_PATH` is set, read and parse the JSON file and
19+ * initialize with `cert(serviceAccount)`.
20+ * 4) If none of the above are provided, throws an error to avoid implicit ADC
21+ * behavior (metadata server lookups) in serverless environments.
22+ *
23+ * Environment variables accessed:
24+ * - NEXT_PUBLIC_FIREBASE_PROJECT_ID: Used to match existing apps and as fallback
25+ * when the service account JSON lacks `project_id`.
26+ * - GOOGLE_SA_JSON: Server-only inline service account JSON string
27+ * (must include `project_id`, `client_email`, and `private_key`).
28+ * - GOOGLE_SA_JSON_PATH: Path to a service account JSON file containing the
29+ * same required fields.
30+ *
31+ * Notes:
32+ * - Uses `getEnvConfig` and `nonEmpty` to read configuration consistently.
33+ * - Keep credentials server-only; do not expose inline JSON to client code.
1834 */
19-
20- let adminApp : App | undefined ;
21-
2235function ensureAdminInitialized ( ) : App {
2336 // Reuse already initialized app
2437 const existingApps = getApps ( ) ;
0 commit comments