import { collection, onSnapshot, setDoc, doc, query, orderBy, limit, getFirestore, getDocFromServer, deleteDoc, } from 'firebase/firestore'; import { initializeApp } from 'firebase/app'; import { getAuth, GoogleAuthProvider, signInWithPopup, onAuthStateChanged, User, } from 'firebase/auth'; import { SystemSeed } from '../types'; import { validateSystemSeed } from '../lib/validation'; import firebaseConfig from '../../firebase-applet-config.json'; const app = initializeApp(firebaseConfig); export const db = getFirestore(app, firebaseConfig.firestoreDatabaseId); export const auth = getAuth(app); // Local Scholastic Bypass / Simulation Store let simulatedUser: any = null; try { const previouslyBypassed = localStorage.getItem('local_scholastic_bypass') === 'true'; if (previouslyBypassed) { simulatedUser = { uid: 'independent-scholar-777', email: 'chancellor@lyceum.edu', displayName: 'Independent Synthesis Scholar', emailVerified: true, _stopProactiveRefresh: () => {}, }; } } catch (e) { console.warn('[SCHOLASTIC_LOCAL_AUTH_INIT_ERROR]', e); } export const getActiveUser = () => simulatedUser || auth.currentUser; export const enableLocalScholarSimulation = (mockUser: any) => { simulatedUser = mockUser; if (mockUser) { localStorage.setItem('local_scholastic_bypass', 'true'); } else { localStorage.removeItem('local_scholastic_bypass'); } }; export const loginAsScholar = async () => { const provider = new GoogleAuthProvider(); // Ensure we request the scopes the user saw in the error provider.addScope('https://www.googleapis.com/auth/userinfo.email'); provider.addScope('https://www.googleapis.com/auth/userinfo.profile'); try { const result = await signInWithPopup(auth, provider); // Disable simulation if we signed in successfully enableLocalScholarSimulation(null); return result; } catch (err: unknown) { const error = err as Error & { code?: string }; if (error.code === 'auth/popup-closed-by-user') { console.warn('Auth: User terminated the identification sequence.'); } else if (error.message.includes('org_internal')) { console.error( "Auth: Organizational restriction detected. Ensure the Firebase Project is set to 'External' in the Google Cloud Console.", ); } throw error; } }; export const subscribeToAuth = (callback: (user: User | null) => void) => { if (simulatedUser) { callback(simulatedUser); } return onAuthStateChanged(auth, (user) => { if (!simulatedUser) { callback(user); } }); }; // Critical Connection Test async function testConnection() { try { await getDocFromServer(doc(db, 'systemSeeds', 'connection_test')); console.info('Cloud Substrate: Connection verified.'); } catch (error) { if (error instanceof Error && error.message.includes('the client is offline')) { console.error('Cloud Substrate: Offline detected. Check Firebase configuration.'); } } } testConnection(); enum OperationType { CREATE = 'create', UPDATE = 'update', DELETE = 'delete', LIST = 'list', GET = 'get', WRITE = 'write', } interface FirestoreErrorInfo { error: string; operationType: OperationType; path: string | null; authInfo: { userId?: string | null; email?: string | null; emailVerified?: boolean | null; }; } function handleFirestoreError(error: unknown, operationType: OperationType, path: string | null) { const user = getActiveUser(); const errInfo: FirestoreErrorInfo = { error: error instanceof Error ? error.message : String(error), authInfo: { userId: user?.uid, email: user?.email, emailVerified: user?.emailVerified, }, operationType, path, }; console.error('Firestore Error: ', JSON.stringify(errInfo)); throw new Error(JSON.stringify(errInfo)); } export const cloudSubstrateService = { loginAsScholar, subscribeToAuth, enableLocalScholarSimulation, isSimulated: () => !!simulatedUser, subscribeToSeeds: (callback: (seeds: SystemSeed[]) => void) => { const path = 'systemSeeds'; try { if (simulatedUser) { const stored = localStorage.getItem('simulated_cloud_system_seeds'); const seeds = stored ? JSON.parse(stored) : []; callback(seeds); return () => {}; } const q = query(collection(db, path), orderBy('affinity', 'desc'), limit(50)); return onSnapshot( q, (snapshot) => { const seeds = snapshot.docs.map( (doc) => ({ ...doc.data(), id: doc.id, isSynced: true, }) as SystemSeed, ); callback(seeds); }, (error) => { handleFirestoreError(error, OperationType.GET, path); }, ); } catch (error) { handleFirestoreError(error, OperationType.GET, path); } }, syncSeed: async (seed: SystemSeed): Promise => { const path = 'systemSeeds'; try { if (simulatedUser) { const stored = localStorage.getItem('simulated_cloud_system_seeds'); const seeds: SystemSeed[] = stored ? JSON.parse(stored) : []; const index = seeds.findIndex((s) => s.id === seed.id); const validatedSeed = { ...seed, isSynced: true, timestamp: seed.timestamp || Date.now(), }; if (index >= 0) { seeds[index] = validatedSeed; } else { seeds.push(validatedSeed); } localStorage.setItem('simulated_cloud_system_seeds', JSON.stringify(seeds)); return; } // Validate payloads client-side for early defence and prevention const validatedSeed = validateSystemSeed({ ...seed, // Close enough for most validations if rules use request.time timestamp: seed.timestamp || Date.now(), }); await setDoc(doc(db, path, validatedSeed.id), validatedSeed, { merge: true }); } catch (error) { handleFirestoreError(error, OperationType.WRITE, path); } }, subscribeToArtifacts: (callback: (artifacts: any[]) => void) => { const path = 'scholasticArtifacts'; try { if (simulatedUser) { const stored = localStorage.getItem('simulated_cloud_artifacts'); const artifacts = stored ? JSON.parse(stored) : []; callback(artifacts); return () => {}; } const q = query(collection(db, path), orderBy('updatedAt', 'desc'), limit(50)); return onSnapshot( q, (snapshot) => { const artifacts = snapshot.docs.map((doc) => ({ ...doc.data(), id: doc.id, })); callback(artifacts); }, (error) => { handleFirestoreError(error, OperationType.GET, path); }, ); } catch (error) { handleFirestoreError(error, OperationType.GET, path); } }, saveArtifact: async (artifact: any): Promise => { const path = 'scholasticArtifacts'; const activeUser = getActiveUser(); if (!activeUser) throw new Error('Not authenticated.'); try { const artifactId = artifact.id || crypto.randomUUID(); const now = Date.now(); const newArtifact = { ...artifact, id: artifactId, authorId: artifact.authorId || activeUser.uid, createdAt: artifact.createdAt || now, updatedAt: artifact.updatedAt || now, }; if (simulatedUser) { const stored = localStorage.getItem('simulated_cloud_artifacts'); const artifacts: any[] = stored ? JSON.parse(stored) : []; const index = artifacts.findIndex((a) => a.id === artifactId); if (index >= 0) { artifacts[index] = newArtifact; } else { artifacts.push(newArtifact); } localStorage.setItem('simulated_cloud_artifacts', JSON.stringify(artifacts)); return artifactId; } await setDoc(doc(db, path, artifactId), newArtifact, { merge: true }); return artifactId; } catch (error) { handleFirestoreError(error, OperationType.WRITE, path); return ''; } }, deleteArtifact: async (id: string): Promise => { const path = 'scholasticArtifacts'; try { if (simulatedUser) { const stored = localStorage.getItem('simulated_cloud_artifacts'); if (stored) { let artifacts: any[] = JSON.parse(stored); artifacts = artifacts.filter((a) => a.id !== id); localStorage.setItem('simulated_cloud_artifacts', JSON.stringify(artifacts)); } return; } await deleteDoc(doc(db, path, id)); } catch (error) { handleFirestoreError(error, OperationType.DELETE, path); } }, };