File size: 8,841 Bytes
35b8b9c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
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<void> => {
    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<string> => {
    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<void> => {
    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);
    }
  },
};