Spaces:
Running
Running
File size: 8,447 Bytes
e937b05 | 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 | import test from 'node:test';
import assert from 'node:assert/strict';
// Setup Mock Browser Environment for Node.js
class LocalStorageMock {
constructor() {
this.store = {};
}
getItem(key) {
return this.store[key] || null;
}
setItem(key, val) {
this.store[key] = String(val);
}
removeItem(key) {
delete this.store[key];
}
clear() {
this.store = {};
}
}
const mockStorage = new LocalStorageMock();
globalThis.localStorage = mockStorage;
globalThis.window = {
addEventListener: () => {},
location: { reload: () => {} }
};
Object.defineProperty(globalThis.navigator, 'onLine', {
value: false,
configurable: true,
writable: true
});
// Import source client directly via Node's native TypeScript support
import {
authService,
getStoredFirebaseConfig,
initializeFirebase,
setRuntimeConfigOffline,
isOfflineOrUnreachable,
resolveUserToken,
CONFIG_STORAGE_KEY,
SESSION_STORAGE_KEY,
TOKEN_STORAGE_PREFIX
} from '../src/firebaseClient.ts';
test('1. Unauthenticated offline user receives null session', async () => {
mockStorage.clear();
navigator.onLine = false;
setRuntimeConfigOffline(true);
const initialUser = authService.getInitialUser();
assert.strictEqual(initialUser, null, 'Unauthenticated user should have null initialUser');
const { data: { session }, error } = await authService.getSession();
assert.strictEqual(session, null, 'Session should be null when unauthenticated');
assert.strictEqual(error, null, 'Error should be null');
});
test('2. initializeFirebase caches config to localStorage for offline reload', () => {
mockStorage.clear();
const sampleConfig = {
apiKey: 'AIzaSyTestApiKey12345',
authDomain: 'algospaced-test.firebaseapp.com',
projectId: 'algospaced-test-project',
};
initializeFirebase(sampleConfig);
const stored = getStoredFirebaseConfig();
assert.notStrictEqual(stored, null, 'Stored config should not be null');
assert.strictEqual(stored.apiKey, sampleConfig.apiKey);
assert.strictEqual(stored.projectId, sampleConfig.projectId);
});
test('3. Logged-in user reloading offline preserves session and avoids sign-in screen', async () => {
mockStorage.clear();
navigator.onLine = false;
setRuntimeConfigOffline(true);
// Simulate previously authenticated state saved in storage
const activeSession = {
access_token: 'valid-jwt-token-xyz',
user: {
id: 'usr-12345',
uid: 'usr-12345',
email: 'algohero@example.com',
displayName: 'Algo Hero',
emailVerified: true
}
};
mockStorage.setItem(SESSION_STORAGE_KEY, JSON.stringify(activeSession));
mockStorage.setItem(`${TOKEN_STORAGE_PREFIX}usr-12345`, activeSession.access_token);
// 1st offline reload
const initialUser = authService.getInitialUser();
assert.notStrictEqual(initialUser, null, 'Initial user should be restored immediately from cache');
assert.strictEqual(initialUser.id, 'usr-12345');
assert.strictEqual(initialUser.email, 'algohero@example.com');
const { data: { session }, error } = await authService.getSession();
assert.notStrictEqual(session, null, 'Session must not be null when reloading offline');
assert.strictEqual(session.user.id, 'usr-12345');
assert.strictEqual(session.access_token, 'valid-jwt-token-xyz');
assert.strictEqual(error, null);
});
test('4. Reloading offline repeatedly keeps showing the restored workspace session', async () => {
// 2nd offline reload simulation
navigator.onLine = false;
setRuntimeConfigOffline(true);
const initialUser = authService.getInitialUser();
assert.strictEqual(initialUser.id, 'usr-12345');
const { data: { session } } = await authService.getSession();
assert.strictEqual(session?.user?.id, 'usr-12345');
// Verify onAuthStateChange also keeps session alive offline
await new Promise((resolve) => {
const { data: { subscription } } = authService.onAuthStateChange((event, listenerSession) => {
assert.strictEqual(event, 'SIGNED_IN', 'Event must remain SIGNED_IN while offline');
assert.strictEqual(listenerSession?.user?.id, 'usr-12345');
subscription.unsubscribe();
resolve();
});
});
});
test('5. Reloading offline a third time continues to preserve session', async () => {
// 3rd offline reload simulation
navigator.onLine = false;
setRuntimeConfigOffline(true);
const initialUser = authService.getInitialUser();
assert.strictEqual(initialUser.id, 'usr-12345');
const { data: { session } } = await authService.getSession();
assert.strictEqual(session?.user?.id, 'usr-12345');
});
test('6. Explicit signOut cleans up cached session and tokens even if currentUser is null', async () => {
// User explicitly logs out
await authService.signOut();
assert.strictEqual(mockStorage.getItem(SESSION_STORAGE_KEY), null, 'Session must be removed from storage on sign out');
assert.strictEqual(mockStorage.getItem(`${TOKEN_STORAGE_PREFIX}usr-12345`), null, 'User token must be removed from storage on sign out');
assert.strictEqual(authService.getInitialUser(), null, 'getInitialUser must return null after signOut');
// Reloading offline after explicit signOut shows sign-in screen (null session)
navigator.onLine = false;
setRuntimeConfigOffline(true);
const { data: { session } } = await authService.getSession();
assert.strictEqual(session, null, 'User should remain signed out on reload after signOut');
});
test('7. Sandbox Guest Mode functions offline without cloud credentials', async () => {
mockStorage.clear();
mockStorage.setItem('algospaced_sandbox_mode', 'true');
navigator.onLine = false;
setRuntimeConfigOffline(true);
const guest = authService.getInitialUser();
assert.strictEqual(guest?.id, 'sandbox-user-id');
assert.strictEqual(guest?.displayName, 'Sandbox Guest');
const { data: { session } } = await authService.getSession();
assert.strictEqual(session?.access_token, 'sandbox');
assert.strictEqual(session?.user?.id, 'sandbox-user-id');
});
test('8. Network unreachable while navigator.onLine is true preserves session via runtime offline flag', async () => {
mockStorage.clear();
// Connected to local Wi-Fi with no internet
navigator.onLine = true;
setRuntimeConfigOffline(true);
const activeSession = {
access_token: 'lan-offline-jwt-token',
user: {
id: 'usr-lan-999',
uid: 'usr-lan-999',
email: 'lanuser@example.com',
displayName: 'LAN User',
emailVerified: true
}
};
mockStorage.setItem(SESSION_STORAGE_KEY, JSON.stringify(activeSession));
mockStorage.setItem(`${TOKEN_STORAGE_PREFIX}usr-lan-999`, activeSession.access_token);
assert.strictEqual(isOfflineOrUnreachable(), true, 'isOfflineOrUnreachable must be true when runtime config is offline');
const { data: { session } } = await authService.getSession();
assert.notStrictEqual(session, null, 'Session must not be cleared when backend is unreachable even if navigator.onLine is true');
assert.strictEqual(session?.user?.id, 'usr-lan-999');
assert.strictEqual(mockStorage.getItem(SESSION_STORAGE_KEY) !== null, true, 'Stored session must remain preserved in storage');
});
test('9. resolveUserToken returns cached token immediately when offline without network call', async () => {
navigator.onLine = false;
setRuntimeConfigOffline(true);
mockStorage.setItem(`${TOKEN_STORAGE_PREFIX}test-user`, 'offline-cached-token-123');
const mockUser = {
uid: 'test-user',
getIdToken: async () => {
throw new Error('Should not attempt network getIdToken when offline with cached token');
}
};
const start = Date.now();
const token = await resolveUserToken(mockUser);
const elapsed = Date.now() - start;
assert.strictEqual(token, 'offline-cached-token-123');
assert.strictEqual(elapsed < 100, true, 'Must return cached token immediately without delay');
});
test('10. resolveUserToken times out slow token refresh and falls back to cached token', async () => {
navigator.onLine = true;
setRuntimeConfigOffline(false);
mockStorage.setItem(`${TOKEN_STORAGE_PREFIX}hanging-user`, 'fallback-token-abc');
const hangingUser = {
uid: 'hanging-user',
getIdToken: () => new Promise((resolve) => setTimeout(() => resolve('delayed-token'), 5000))
};
const token = await resolveUserToken(hangingUser);
assert.strictEqual(token, 'fallback-token-abc', 'Must fall back to cached token on timeout');
});
|