algospaced-dsa / algospaced-ui /tests /offlineAuth.test.mjs
iamfebin's picture
feat: offline auth session persistence, token caching, and taskbar connectivity indicator
e937b05
Raw History Blame Contribute Delete
8.45 kB
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');
});