feat(auth): add device management for learners

- Share rotated refresh tokens safely across browser tabs
- Keep learners signed in through temporary refresh failures
- Add a device picker when signing in over the device limit
- Show and remove active devices from the profile
- Notify a learner when their device is removed
This commit is contained in:
n3p-tun3 2026-11-23 18:10:00 +03:00
parent 28a1ad5228
commit 2f42f08368
10 changed files with 518 additions and 41 deletions

View File

@ -2,7 +2,7 @@
// https://api.rezina.yaltopia.com (2026-11-02): GET /catalog/courses and GET /catalog/courses/12.
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { absolute, ApiDataSource, ids, mapIssue, mapNotification, mapOutline, mapStudent, slugify, type RawOutline } from './api.ts';
import { absolute, ApiDataSource, DeviceLimitError, ids, mapIssue, mapNotification, mapOutline, mapStudent, slugify, type RawOutline } from './api.ts';
const BASE = 'https://api.rezina.yaltopia.com';
const fixture = (f: string) => JSON.parse(readFileSync(new URL(f, import.meta.url), 'utf8')).data;
@ -134,4 +134,129 @@ releaseRefresh(response({ data: { access_token: 'late-access', refresh_token: 'l
await Promise.all([viewing, signingOut]);
assert.equal(storage.get(TOKEN_KEY), undefined, 'late refresh must not recreate the signed-out session');
// device sessions and cross-tab tokens (mocked transport only)
const newTokens = { access: 'access-new', refresh: 'refresh-new', userId: 9 };
const stored = () => JSON.parse(storage.get(TOKEN_KEY) ?? 'null');
const profile = { id: 9, first_name: 'Test', status: 'ACTIVE' };
const bearer = (init?: RequestInit) => new Headers(init?.headers).get('authorization');
// two tabs: one refresh, and the second adopts the rotated pair
seedTokens();
let refreshes = 0;
globalThis.fetch = async (input, init) => {
const url = String(input);
if (url.endsWith('/auth/refresh')) { refreshes++; return response({ data: { access_token: 'access-new', refresh_token: 'refresh-new', user_id: 9 } }); }
return bearer(init) === 'Bearer access-new' ? response({ data: profile }) : response({ message: 'expired' }, 401);
};
const [tabA, tabB] = [new ApiDataSource(mockBase), new ApiDataSource(mockBase)];
const viewers = await Promise.all([tabA.viewer(), tabB.viewer()]);
assert.deepEqual(viewers.map((v) => v.id), ['9', '9']);
assert.equal(refreshes, 1, 'a rotated token is never submitted twice');
assert.deepEqual(stored(), newTokens);
// without Web Locks, a stale 401 adopts the newer stored pair and never erases it
seedTokens();
Object.defineProperty(navigator, 'locks', { configurable: true, value: undefined });
globalThis.fetch = async (input, init) => {
const url = String(input);
if (url.endsWith('/auth/refresh')) { storage.set(TOKEN_KEY, JSON.stringify(newTokens)); return response({ message: 'not found' }, 401); }
return bearer(init) === 'Bearer access-new' ? response({ data: profile }) : response({ message: 'expired' }, 401);
};
assert.equal((await new ApiDataSource(mockBase).viewer()).id, '9');
assert.deepEqual(stored(), newTokens, 'a stale refresh failure must not erase a newer session');
delete (navigator as unknown as Record<string, unknown>).locks;
// server and network failures during refresh keep the session
for (const fail of [async () => response({ message: 'down' }, 503), async () => { throw new Error('offline'); }]) {
seedTokens();
globalThis.fetch = async (input) => (String(input).endsWith('/auth/refresh') ? fail() : response({ message: 'expired' }, 401));
await new ApiDataSource(mockBase).viewer();
assert.deepEqual(stored(), oldTokens, 'only a 401 from refresh ends the session');
}
// a stable device id goes out on login, OTP and refresh
storage.delete(TOKEN_KEY);
const deviceIds = new Map<string, string | null>();
globalThis.fetch = async (input, init) => {
const path = String(input).slice(`${mockBase}/api/v1`.length);
deviceIds.set(path, new Headers(init?.headers).get('x-device-id'));
assert.equal(new Headers(init?.headers).has('x-device-platform'), false);
if (path === '/user/checkPhoneEmailExist') return response({ data: { email_exist: true, phone_number_exist: false } });
if (path === '/auth/customer-login' || path === '/user/verify-otp' || path === '/auth/refresh') return response({ data: { access_token: 'a2', refresh_token: 'r2', user_id: 9 } });
return path === '/user/user-profile' && deviceIds.has('/auth/refresh') ? response({ data: profile }) : response({ message: 'expired' }, 401);
};
const deviceSource = new ApiDataSource(mockBase);
await deviceSource.auth.start({ email: 'learner@example.test', password: 'password1' });
await deviceSource.auth.verify({ phone: '+251900000000' }, '123456');
storage.set(TOKEN_KEY, JSON.stringify(oldTokens));
await new ApiDataSource(mockBase).viewer();
const sentIds = ['/auth/customer-login', '/user/verify-otp', '/auth/refresh'].map((p) => deviceIds.get(p));
assert.ok(sentIds[0]); assert.equal(new Set(sentIds).size, 1, 'the same device id on every call');
assert.equal(storage.get('lms.deviceId'), sentIds[0]);
// a device-limit answer is typed and stores nothing
storage.delete(TOKEN_KEY);
const limit = { challenge_token: 'challenge', expires_at: '2026-11-23T12:05:00Z', devices: [{ id: 's1', label: 'Chrome on Android', platform: 'android', last_seen_at: now }] };
globalThis.fetch = async (input) => (String(input).endsWith('/user/checkPhoneEmailExist')
? response({ data: { email_exist: true, phone_number_exist: false } })
: response({ message: 'Device limit reached', code: 'DEVICE_LIMIT_REACHED', data: limit }, 409));
const limited = new ApiDataSource(mockBase);
await assert.rejects(limited.auth.start({ email: 'learner@example.test', password: 'password1' }), (e: unknown) => e instanceof DeviceLimitError && e.challengeToken === 'challenge' && e.devices.length === 1);
assert.equal(storage.get(TOKEN_KEY), undefined);
// replacing a device sends no bearer and stores the new session
calls = [];
globalThis.fetch = async (input, init) => { calls.push({ url: String(input), init }); return response({ data: { access_token: 'access-new', refresh_token: 'refresh-new', user_id: 9 } }); };
await limited.auth.replaceDevice('challenge', 's1');
assert.equal(calls[0].url, `${mockBase}/api/v1/auth/sessions/replace`);
assert.equal(bearer(calls[0].init), null);
assert.deepEqual(JSON.parse(String(calls[0].init?.body)), { challenge_token: 'challenge', session_id: 's1' });
assert.deepEqual(stored(), newTokens);
// replacement failures stay distinguishable, so a dropped connection can retry
storage.delete(TOKEN_KEY);
globalThis.fetch = async () => { throw new Error('offline'); };
await assert.rejects(limited.auth.replaceDevice('challenge', 's1'), (e: { status?: number }) => e.status === 0);
globalThis.fetch = async () => response({ message: 'Invalid session replacement' }, 401);
await assert.rejects(limited.auth.replaceDevice('challenge', 's1'), (e: { status?: number }) => e.status === 401);
// a revoked session skips refresh and notifies once across parallel calls
seedTokens();
refreshes = 0;
globalThis.fetch = async (input) => {
if (String(input).endsWith('/auth/refresh')) refreshes++;
return response({ message: 'Session revoked', code: 'SESSION_REVOKED' }, 401);
};
const revoked = new ApiDataSource(mockBase);
let revokedCount = 0;
revoked.auth.onSessionRevoked(() => { revokedCount++; });
await Promise.all([revoked.viewer(), revoked.viewer(), revoked.viewer()]);
assert.equal(refreshes, 0); assert.equal(revokedCount, 1); assert.equal(storage.get(TOKEN_KEY), undefined);
// an expired token on a removed device learns about it from refresh
seedTokens();
globalThis.fetch = async (input) => (String(input).endsWith('/auth/refresh')
? response({ message: 'Session revoked', code: 'SESSION_REVOKED' }, 401)
: response({ message: 'Access token expired' }, 401));
const expiredRevoked = new ApiDataSource(mockBase);
let expiredCount = 0;
expiredRevoked.auth.onSessionRevoked(() => { expiredCount++; });
await expiredRevoked.viewer();
assert.equal(expiredCount, 1); assert.equal(storage.get(TOKEN_KEY), undefined);
// another tab: a rotation is adopted silently, a sign-out clears this tab
seedTokens();
let tabCalls = 0;
globalThis.fetch = async (input) => { tabCalls++; return response({ data: String(input).includes('/catalog/courses') ? { courses: [], total_count: 0 } : profile }); };
const listening = new ApiDataSource(mockBase) as unknown as { onStorage(e: { key: string | null; newValue: string | null }): void; auth: { signedIn(): boolean }; tokens: unknown };
const courseWatch = (listening as unknown as ApiDataSource).watchCourses(() => {});
await new Promise((resolve) => setTimeout(resolve, 0));
tabCalls = 0;
listening.onStorage({ key: TOKEN_KEY, newValue: JSON.stringify(newTokens) });
assert.deepEqual(listening.tokens, newTokens);
assert.equal(tabCalls, 0, 'a routine rotation must not refetch the catalog');
listening.onStorage({ key: TOKEN_KEY, newValue: null });
assert.equal(listening.auth.signedIn(), false);
courseWatch();
console.log('api checks: all passed');

View File

@ -9,7 +9,7 @@
// Screens never see the API's shapes: everything is mapped onto the domain types in ./index.
import type {
Campaign, Category, Course, DataSource, InboxItem, Issue, IssueStatus, IssueType, LessonProgress, Locale, Settings,
Student, Unsub, UserStatus, Viewer, AuditEntry,
Student, Unsub, UserStatus, Viewer, AuditEntry, DeviceSession, DeviceSummary,
} from './index';
// ---------------------------------------------------------------- API shapes (the subset we read)
@ -115,15 +115,26 @@ export function mapStudent(p: RawProfile, summary: RawSummary | null, issues: Ra
export class ApiError extends Error {
readonly status: number; readonly code: string;
constructor(status: number, message: string) {
constructor(status: number, message: string, serverCode?: string) {
super(message);
this.status = status;
this.code = status === 0 ? 'network' : status === 401 ? 'unauthenticated' : status === 403 ? 'not_granted' : 'api_error';
this.code = serverCode || (status === 0 ? 'network' : status === 401 ? 'unauthenticated' : status === 403 ? 'not_granted' : 'api_error');
}
}
export class DeviceLimitError extends ApiError {
readonly challengeToken: string; readonly expiresAt: string; readonly devices: DeviceSummary[];
constructor(message: string, data: { challenge_token: string; expires_at: string; devices: DeviceSummary[] }) {
super(409, message, 'DEVICE_LIMIT_REACHED');
this.challengeToken = data.challenge_token;
this.expiresAt = data.expires_at;
this.devices = data.devices;
}
}
const notConnected = (what: string) => Object.assign(new Error(`${what} isn't connected to the API yet.`), { code: 'not_granted' });
const TOKENS_KEY = 'lms.api.tokens';
const DEVICE_KEY = 'lms.deviceId';
const REFRESH_LOCK = 'lms.api.refresh';
const REQUEST_TIMEOUT_MS = 12000;
const REQUEST_RETRIES = 2;
const PARALLEL = 3; // the catalog fans out one call per course/chapter; a smaller burst is gentler on the server
@ -136,8 +147,30 @@ async function mapLimit<T, R>(items: T[], limit: number, fn: (x: T) => Promise<R
}));
return out;
}
const readTokens = (): Tokens | null => { try { return JSON.parse(localStorage.getItem(TOKENS_KEY) ?? 'null'); } catch { return null; } };
const validTokens = (x: unknown): x is Tokens => !!x && typeof x === 'object'
&& typeof (x as Tokens).access === 'string' && !!(x as Tokens).access
&& typeof (x as Tokens).refresh === 'string' && !!(x as Tokens).refresh
&& Number.isFinite((x as Tokens).userId);
const parseTokens = (raw: string | null): Tokens | null => { try { const x = JSON.parse(raw ?? 'null'); return validTokens(x) ? x : null; } catch { return null; } };
const readTokens = (): Tokens | null => { try { return parseTokens(localStorage.getItem(TOKENS_KEY)); } catch { return null; } };
const writeTokens = (t: Tokens | null) => { try { t ? localStorage.setItem(TOKENS_KEY, JSON.stringify(t)) : localStorage.removeItem(TOKENS_KEY); } catch { /* storage blocked: session-only */ } };
let memoryDeviceId: string | null = null;
const randomDeviceId = () => {
const c = globalThis.crypto;
if (c?.randomUUID) return c.randomUUID();
const bytes = new Uint8Array(16); c?.getRandomValues?.(bytes);
bytes[6] = (bytes[6] & 0x0f) | 0x40; bytes[8] = (bytes[8] & 0x3f) | 0x80;
return [...bytes].map((b, i) => `${i === 4 || i === 6 || i === 8 || i === 10 ? '-' : ''}${b.toString(16).padStart(2, '0')}`).join('');
};
const deviceId = () => {
if (memoryDeviceId) return memoryDeviceId;
try {
const saved = localStorage.getItem(DEVICE_KEY);
if (saved) return (memoryDeviceId = saved);
memoryDeviceId = randomDeviceId(); localStorage.setItem(DEVICE_KEY, memoryDeviceId); return memoryDeviceId;
} catch { return (memoryDeviceId ??= randomDeviceId()); }
};
const samePair = (a: Tokens | null, b: Tokens | null) => !!a && !!b && a.access === b.access && a.refresh === b.refresh && a.userId === b.userId;
// ---------------------------------------------------------------- data source
@ -148,6 +181,8 @@ export class ApiDataSource implements DataSource {
private tokens: Tokens | null = readTokens();
private tokenVersion = 0;
private refreshing: { version: number; promise: Promise<boolean> } | null = null;
private revokedCbs = new Set<() => void>();
private revokedNotified = false;
private courseCbs = new Set<(c: Course[]) => void>();
private studentCbs = new Map<(s: Student | null) => void, string>();
private inboxCbs = new Set<(i: InboxItem[]) => void>();
@ -155,7 +190,21 @@ export class ApiDataSource implements DataSource {
private localProgress: Record<string, LessonProgress> = {};
readonly base: string;
constructor(base: string) { this.base = base; }
constructor(base: string) {
this.base = base;
if (typeof addEventListener === 'function') addEventListener('storage', this.onStorage);
}
private onStorage = (event: StorageEvent) => {
if (event.key !== TOKENS_KEY && event.key !== null) return; // null: storage was cleared
const next = event.key === null ? null : parseTokens(event.newValue);
if (samePair(next, this.tokens) || (!next && !this.tokens)) return;
const sameUser = !!next && next.userId === this.tokens?.userId;
this.setTokens(next, false);
if (sameUser) return; // a routine rotation in another tab: nothing on screen changed
this.localProgress = {};
this.refreshAll();
};
// ---- transport
@ -166,11 +215,19 @@ export class ApiDataSource implements DataSource {
* so a learner can't get two texts or burn a code.
*/
private async request<T>(method: string, path: string, body?: unknown, auth = true, retry = method === 'GET'): Promise<T> {
const attempt = () => fetch(`${this.base.replace(/\/+$/, '')}/api/v1${path}`, {
method, headers: { 'content-type': 'application/json', ...(auth && this.tokens ? { authorization: `Bearer ${this.tokens.access}` } : {}) },
body: body === undefined ? undefined : JSON.stringify(body),
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
});
let sent: Tokens | null = null;
const attempt = () => {
sent = this.tokens;
return fetch(`${this.base.replace(/\/+$/, '')}/api/v1${path}`, {
method, headers: {
'content-type': 'application/json',
...(auth && sent ? { authorization: `Bearer ${sent.access}` } : {}),
...(path === '/auth/customer-login' || path === '/user/verify-otp' ? { 'X-Device-Id': deviceId() } : {}),
},
body: body === undefined ? undefined : JSON.stringify(body),
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
});
};
const send = async () => {
for (let i = 0; ; i++) {
try { return await attempt(); }
@ -178,34 +235,92 @@ export class ApiDataSource implements DataSource {
}
};
let res = await send();
if (res.status === 401 && auth && this.tokens && (await this.refresh())) res = await send();
const json = await res.json().catch(() => null);
let json = await res.json().catch(() => null);
if (res.status === 401 && auth && sent) {
if (json?.code === 'SESSION_REVOKED') {
if (this.adoptNewer(sent)) { res = await send(); json = await res.json().catch(() => null); }
else this.endRevokedSession(sent);
} else if (await this.refresh(sent)) {
res = await send(); json = await res.json().catch(() => null);
}
}
// Some endpoints answer `success: false` on a 200, so the HTTP status is what counts.
if (!res.ok) throw new ApiError(res.status, json?.message || json?.error || res.statusText);
if (!res.ok) {
if (res.status === 409 && json?.code === 'DEVICE_LIMIT_REACHED' && json?.data?.challenge_token) {
throw new DeviceLimitError(json.message || 'Device limit reached', json.data);
}
throw new ApiError(res.status, json?.message || json?.error || res.statusText, json?.code);
}
return (json && 'data' in json ? json.data : json) as T;
}
private refresh(): Promise<boolean> {
if (!this.tokens) return Promise.resolve(false);
const tokens = this.tokens;
private refresh(tokens: Tokens): Promise<boolean> {
if (!samePair(this.tokens, tokens)) return Promise.resolve(this.adoptNewer(tokens));
const version = this.tokenVersion;
if (this.refreshing?.version === version) return this.refreshing.promise;
const promise = fetch(`${this.base.replace(/\/+$/, '')}/api/v1/auth/refresh`, {
method: 'POST', headers: { 'content-type': 'application/json' },
body: JSON.stringify({ access_token: tokens.access, refresh_token: tokens.refresh }),
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
}).then(async (r) => {
const j = await r.json().catch(() => null);
if (version !== this.tokenVersion || this.tokens !== tokens) return false;
if (!r.ok || !j?.data?.access_token) { this.setTokens(null); return false; }
this.setTokens({ access: j.data.access_token, refresh: j.data.refresh_token, userId: j.data.user_id });
return true;
}, () => false).finally(() => { if (this.refreshing?.promise === promise) this.refreshing = null; });
const run = async () => {
const locks = typeof navigator !== 'undefined' ? navigator.locks : undefined;
if (locks?.request) return locks.request(REFRESH_LOCK, async () => {
// Signed out or replaced while queued: never spend the old token.
if (version !== this.tokenVersion) return this.adoptNewer(tokens);
return this.adoptNewer(tokens) || this.performRefresh(tokens, version);
});
return this.performRefresh(tokens, version);
};
const promise = run().finally(() => { if (this.refreshing?.promise === promise) this.refreshing = null; });
this.refreshing = { version, promise };
return promise;
}
private setTokens(t: Tokens | null) { this.tokenVersion++; this.tokens = t; writeTokens(t); }
private async performRefresh(tokens: Tokens, version: number): Promise<boolean> {
let r: Response;
try {
r = await fetch(`${this.base.replace(/\/+$/, '')}/api/v1/auth/refresh`, {
method: 'POST', headers: { 'content-type': 'application/json', 'X-Device-Id': deviceId() },
body: JSON.stringify({ access_token: tokens.access, refresh_token: tokens.refresh }),
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
});
} catch { throw new ApiError(0, "Couldn't reach the server."); }
const j = await r.json().catch(() => null);
if (version !== this.tokenVersion || !samePair(this.tokens, tokens)) return this.adoptNewer(tokens);
if (r.status === 401) {
if (this.adoptNewer(tokens)) return true;
if (j?.code === 'SESSION_REVOKED') this.endRevokedSession(tokens); else this.clearFailedTokens(tokens);
return false;
}
if (!r.ok) throw new ApiError(r.status, j?.message || j?.error || r.statusText, j?.code);
if (!j?.data?.access_token || !j.data.refresh_token) throw new ApiError(r.status, 'The server returned an invalid session.');
this.setTokens({ access: j.data.access_token, refresh: j.data.refresh_token, userId: j.data.user_id ?? tokens.userId });
return true;
}
private adoptNewer(failed: Tokens): boolean {
if (this.tokens && this.tokens.userId === failed.userId && !samePair(this.tokens, failed)) return true;
const stored = readTokens();
if (stored?.userId !== failed.userId || samePair(stored, failed)) return false;
this.setTokens(stored, false);
return true;
}
private clearFailedTokens(failed: Tokens) {
const stored = readTokens();
if (samePair(stored, failed)) writeTokens(null);
this.setTokens(null, false);
}
private endRevokedSession(failed: Tokens) {
if (this.revokedNotified && !this.tokens) return; // parallel calls failing together end the session once
this.clearFailedTokens(failed);
this.localProgress = {};
this.refreshAll();
if (!this.revokedNotified) { this.revokedNotified = true; this.revokedCbs.forEach((cb) => cb()); }
}
private setTokens(t: Tokens | null, persist = true) {
this.tokenVersion++; this.tokens = t;
if (t) this.revokedNotified = false;
if (persist) writeTokens(t);
}
private logoutRequest(t: Tokens) {
return fetch(`${this.base.replace(/\/+$/, '')}/api/v1/auth/logout`, {
@ -220,7 +335,7 @@ export class ApiDataSource implements DataSource {
private async refreshForLogout(t: Tokens): Promise<Tokens | null> {
try {
const r = await fetch(`${this.base.replace(/\/+$/, '')}/api/v1/auth/refresh`, {
method: 'POST', headers: { 'content-type': 'application/json' },
method: 'POST', headers: { 'content-type': 'application/json', 'X-Device-Id': deviceId() },
body: JSON.stringify({ access_token: t.access, refresh_token: t.refresh }),
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
});
@ -258,6 +373,29 @@ export class ApiDataSource implements DataSource {
this.setTokens({ access: t.access_token, refresh: t.refresh_token, userId: t.user_id });
this.refreshAll();
},
replaceDevice: async (challengeToken: string, sessionId: string): Promise<void> => {
let r: Response;
try {
r = await fetch(`${this.base.replace(/\/+$/, '')}/api/v1/auth/sessions/replace`, {
method: 'POST', headers: { 'content-type': 'application/json', 'X-Device-Id': deviceId() },
body: JSON.stringify({ challenge_token: challengeToken, session_id: sessionId }),
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
});
} catch { throw new ApiError(0, "Couldn't reach the server."); } // the picker stays open so the learner can retry
const j = await r.json().catch(() => null);
if (!r.ok) throw new ApiError(r.status, j?.message || r.statusText, j?.code);
if (!j?.data?.access_token || !j.data.refresh_token) throw new ApiError(502, 'The server returned an invalid session.');
this.setTokens({ access: j.data.access_token, refresh: j.data.refresh_token, userId: j.data.user_id });
this.refreshAll();
},
listDevices: async (): Promise<DeviceSession[]> => {
const r = await this.request<DeviceSession[] | { sessions: DeviceSession[] }>('GET', '/user/me/sessions');
return Array.isArray(r) ? r : r.sessions ?? [];
},
removeDevice: async (id: string): Promise<void> => {
await this.request('DELETE', `/user/me/sessions/${encodeURIComponent(id)}`, undefined, true, false);
},
onSessionRevoked: (cb: () => void): Unsub => { this.revokedCbs.add(cb); return () => this.revokedCbs.delete(cb); },
signOut: async () => {
const t = this.tokens;
// Invalidate every refresh already in flight before doing any network work.

View File

@ -107,6 +107,14 @@ export interface AuditEntry { id: string; adminId: string; action: string; entit
export interface Viewer { id: string | null; name: string; avatarUrl: string; isOwner: boolean; canEdit: boolean }
export interface DeviceSummary {
id: string; label: string; platform: string; last_seen_at: string;
}
export interface DeviceSession extends DeviceSummary {
created_at: string; expires_at: string; is_current: boolean;
}
export type Unsub = () => void;
/** Real sign-in, present only on data sources backed by an account system (the API); the demo simulates it. */
@ -115,6 +123,10 @@ export interface AuthApi {
/** Starts sign-in or sign-up for a phone, or an email with password: 'code' means a one-time code was sent. */
start(c: { phone?: string; email?: string; password?: string }): Promise<'code' | 'done'>;
verify(c: { phone?: string; email?: string; password?: string }, code: string): Promise<void>;
replaceDevice(challengeToken: string, sessionId: string): Promise<void>;
listDevices(): Promise<DeviceSession[]>;
removeDevice(id: string): Promise<void>;
onSessionRevoked(cb: () => void): Unsub;
signOut(): Promise<void>;
}
@ -238,4 +250,4 @@ export class ClaudeDbDataSource implements DataSource {
export const newId = (prefix = '') => prefix + Date.now().toString(36) + Math.random().toString(36).slice(2, 8);
export { ApiDataSource, ApiError } from './api';
export { ApiDataSource, ApiError, DeviceLimitError } from './api';

View File

@ -112,6 +112,27 @@ export function AppProvider({ ds, children }: { ds: DataSource; children: ReactN
toastTimer.current = setTimeout(() => setToastMsg(null), 3200);
}, []);
useEffect(() => {
if (!ds.auth) return;
return ds.auth.onSessionRevoked(() => {
store.set('signedOut', '1');
setSignedOut(true);
setViewer({ id: null, name: '', avatarUrl: '', isOwner: false, canEdit: false });
toast(lookup(locale, 'auth.sessionRevoked'));
});
}, [ds, locale, toast]);
// Signing in or out in another tab updates this one too.
useEffect(() => {
const sync = (e: StorageEvent) => {
if (e.key !== 'lms.signedOut') return;
setSignedOut(e.newValue === '1');
ds.viewer().then(setViewer, () => {});
};
addEventListener('storage', sync);
return () => removeEventListener('storage', sync);
}, [ds]);
const msg = useCallback((loc: Locale, key: string, vars?: Record<string, string | number>) => lookup(loc, key, vars), []);
const write = useCallback((fn: () => Promise<void>, okMsg?: string) => {

View File

@ -1,15 +1,15 @@
'use client';
import { useCallback, useEffect, useMemo, useRef, useState, type ReactNode } from 'react';
import { useTranslations } from 'next-intl';
import type { Assessment, AssessmentResult, Course, Issue, IssueType, Lesson, Locale, Order, Student } from '@lms/data';
import { LOCALES, newId } from '@lms/data';
import type { Assessment, AssessmentResult, Course, DeviceSession, DeviceSummary, Issue, IssueType, Lesson, Locale, Order, Student } from '@lms/data';
import { DeviceLimitError, LOCALES, newId } from '@lms/data';
import { LOCALE_NAMES, DRAFT_LOCALES } from '@lms/i18n';
import { lookup, useApp } from './store';
import {
applyHeartbeat, applyPaymentEvent, clock, COUNTRIES, courseDuration, courseProgress, createOrder, DomainError, effectiveStatus,
ET_CITIES, formatDuration, formatMoney, gradeAssessment, isCompleted, isStudentVisible, lessonAccess, owns, publishedLessons, resumePoint, tr, validateLocation, validPassword,
} from './domain';
import { CAT_PHOTOS, CopyText, Cover, coursePhoto, Empty, FeedbackButton, fmtDate, Icon, KitIcon, Logo, Modal, VIMEO_ORIGIN, VIMEO_PLACEHOLDER, Ring, Skeleton, StatusPill } from './ui';
import { CAT_PHOTOS, CopyText, Cover, coursePhoto, Empty, FeedbackButton, fmtDate, fmtDateTime, Icon, KitIcon, Logo, Modal, VIMEO_ORIGIN, VIMEO_PLACEHOLDER, Ring, Skeleton, StatusPill } from './ui';
import { PAY_LOGOS } from './payLogos';
import { encodeLearnerCode } from './learnerCode';
@ -1435,13 +1435,18 @@ function SignIn() {
const [dial, setDial] = useState(() => { const r = (typeof navigator !== 'undefined' ? navigator.language : '').split('-')[1]?.toUpperCase(); return r && DIALS[r] ? r : 'ET'; });
const [email, setEmail] = useState('');
const [pw, setPw] = useState('');
const [step, setStep] = useState<'start' | 'code' | 'setup'>('start');
const [step, setStep] = useState<'start' | 'code' | 'devices' | 'setup'>('start');
const [code, setCode] = useState('');
const [entered, setEntered] = useState('');
const [tries, setTries] = useState(5);
const [wait, setWait] = useState(0);
const [err, setErr] = useState('');
const [challenge, setChallenge] = useState<{ token: string; devices: DeviceSummary[] } | null>(null);
const [removeId, setRemoveId] = useState('');
const stepHeading = useRef<HTMLHeadingElement>(null);
useEffect(() => { if (wait <= 0) return; const id = setTimeout(() => setWait((w) => w - 1), 1000); return () => clearTimeout(id); }, [wait]);
const firstStep = useRef(true);
useEffect(() => { if (firstStep.current) { firstStep.current = false; return; } stepHeading.current?.focus(); }, [step]);
if (!ready) return <Skeleton h={200} />;
const local = phone.replace(/\D/g, '').replace(/^0/, '');
const e164 = `+${DIALS[dial]}${local}`;
@ -1457,6 +1462,12 @@ function SignIn() {
const contact = () => (mode === 'phone' ? { phone: e164 } : { email, password: pw });
// The server's own message when it gave one; a plain "couldn't reach the server" when it never answered.
const apiErr = (e: unknown) => ((e as { code?: string })?.code === 'network' ? t('auth.networkError') : (e as Error)?.message || t('auth.networkError'));
const deviceLimit = (e: unknown) => {
if (!(e instanceof DeviceLimitError)) return false;
setChallenge({ token: e.challengeToken, devices: e.devices });
setRemoveId(''); setErr(''); setStep('devices');
return true;
};
// After a real sign-in: a learner without a name yet goes to profile setup, everyone else home.
const finish = async () => {
await reloadViewer(); signIn();
@ -1468,7 +1479,7 @@ function SignIn() {
try {
const next = await auth!.start(contact());
if (next === 'done') await finish(); else { setEntered(''); setWait(60); setStep('code'); }
} catch (e) { setErr(apiErr(e)); }
} catch (e) { if (!deviceLimit(e)) setErr(apiErr(e)); }
setBusy(false);
};
const verify = async (e: React.FormEvent) => {
@ -1476,7 +1487,7 @@ function SignIn() {
if (auth) {
setBusy(true);
try { await auth.verify(contact(), entered); await finish(); }
catch (x) { setErr(apiErr(x)); }
catch (x) { if (!deviceLimit(x)) setErr(apiErr(x)); }
setBusy(false);
return;
}
@ -1484,6 +1495,19 @@ function SignIn() {
if (entered !== code) { const left = tries - 1; setTries(left); setErr(left ? t('auth.wrongCode', { n: left }) : t('auth.locked')); return; }
if (me && !me.deletedAt) { signIn(); nav(`/${locale}`); } else setStep('setup');
};
const replaceDevice = async (e: React.FormEvent) => {
e.preventDefault(); setErr('');
if (!removeId) { setErr(t('auth.chooseDevice')); return; }
if (!challenge || busy) return;
setBusy(true);
try { await auth!.replaceDevice(challenge.token, removeId); setChallenge(null); await finish(); }
catch (x) {
if ((x as { status?: number })?.status === 401) {
setChallenge(null); setRemoveId(''); setStep('start'); setErr(t('auth.replaceExpired'));
} else setErr(apiErr(x));
}
setBusy(false);
};
if (step === 'setup') return <ProfileSetup phone={mode === 'phone' ? e164 : undefined} email={mode === 'email' ? email : undefined} />;
return (
<section className="auth">
@ -1496,7 +1520,7 @@ function SignIn() {
</div>
<div className="auth-main">
{!auth && !viewer?.id ? <Empty>{t('auth.noIdentity')}</Empty> : step === 'start' ? <form className="stack" onSubmit={(e) => { e.preventDefault(); send(); }}>
<div className="stack-sm"><h1>{t('auth.welcome')}</h1><p className="muted">{t('auth.welcomeLead')}</p></div>
<div className="stack-sm"><h1 ref={stepHeading} tabIndex={-1}>{t('auth.welcome')}</h1><p className="muted">{t('auth.welcomeLead')}</p></div>
{me && !me.deletedAt && <button type="button" className="btn btn-accent btn-block btn-lg" onClick={() => { signIn(); nav(`/${locale}`); }}>{t('auth.continueAs', { name: me.name.split(' ')[0] })}</button>}
{/* Google / Apple need the providers' own sign-in SDKs before they can run against the API */}
{!auth && <><SocialLogins onPick={() => { if (me && !me.deletedAt) { signIn(); nav(`/${locale}`); } else setStep('setup'); }} />
@ -1513,8 +1537,8 @@ function SignIn() {
{err && <p className="err" role="alert">{err}</p>}
<button className="btn btn-block" disabled={busy}>{t('auth.sendCode')}</button>
<button type="button" className="link" onClick={() => { setMode(mode === 'phone' ? 'email' : 'phone'); setErr(''); }}>{mode === 'phone' ? t('auth.useEmail') : t('auth.usePhone')}</button>
</form> : <form className="stack" onSubmit={verify}>
<h1>{t('auth.codeTitle')}</h1>
</form> : step === 'code' ? <form className="stack" onSubmit={verify}>
<h1 ref={stepHeading} tabIndex={-1}>{t('auth.codeTitle')}</h1>
<p>{t('auth.codeSent', { target })}</p>
{!auth && <p className="banner"><strong>{t('auth.demoCode', { code })}</strong></p>}
<label className="field"><span className="sr-only">{t('auth.codeTitle')}</span><input id="otp" className="input otp" inputMode="numeric" autoComplete="one-time-code" maxLength={6} value={entered} onChange={(e) => setEntered(e.target.value.replace(/\D/g, ''))} /></label>
@ -1522,6 +1546,21 @@ function SignIn() {
<button className="btn btn-accent btn-block" disabled={busy || entered.length < 4 || (!auth && (entered.length !== 6 || tries <= 0))}>{t('auth.verify')}</button>
<button type="button" className="btn btn-ghost btn-block" disabled={wait > 0} onClick={send}>{wait > 0 ? t('auth.resendIn', { s: wait }) : t('auth.resend')}</button>
<button type="button" className="link" onClick={() => setStep('start')}>{t('common.back')}</button>
</form> : <form className="stack device-picker" onSubmit={replaceDevice}>
<div className="stack-sm">
<h1 ref={stepHeading} tabIndex={-1}>{t('auth.deviceLimitTitle', { n: challenge?.devices.length ?? 0 })}</h1>
<p className="muted">{t('auth.deviceLimitLead')}</p>
</div>
<fieldset className="device-options">
<legend className="sr-only">{t('auth.deviceLegend')}</legend>
{challenge?.devices.map((device) => <label className="device-option" key={device.id}>
<input type="radio" name="remove-device" value={device.id} checked={removeId === device.id} onChange={() => { setRemoveId(device.id); setErr(''); }} />
<span className="device-copy"><strong>{device.label}</strong><span>{t('auth.lastActive', { date: fmtDateTime(device.last_seen_at) })}</span></span>
</label>)}
</fieldset>
{err && <p className="err" role="alert">{err}</p>}
<button className="btn btn-accent btn-block" disabled={busy}>{t('auth.removeContinue')}</button>
<button type="button" className="btn btn-ghost btn-block" disabled={busy} onClick={() => { setChallenge(null); setRemoveId(''); setErr(''); setStep('start'); }}>{t('common.cancel')}</button>
</form>}
</div>
</section>
@ -1599,6 +1638,64 @@ function ProfileSetup({ phone, email }: { phone?: string; email?: string }) {
const NOTIF_TYPES = ['PAYMENT', 'NEW_LESSON', 'ISSUE', 'ANNOUNCEMENT'] as const;
function ProfileDevices() {
const t = useTranslations();
const { ds, signOut, nav, locale, toast, settings } = useApp();
const auth = ds.auth!;
const [devices, setDevices] = useState<DeviceSession[] | null>(null);
const [failed, setFailed] = useState(false);
const [confirming, setConfirming] = useState<DeviceSession | null>(null);
const [busy, setBusy] = useState(false);
const [err, setErr] = useState('');
const load = useCallback(async () => {
setFailed(false);
try { setDevices(await auth.listDevices()); } catch { setFailed(true); }
}, [auth]);
useEffect(() => { load(); }, [load]);
const close = useCallback(() => { if (!busy) { setConfirming(null); setErr(''); } }, [busy]);
const remove = async () => {
if (!confirming || busy) return;
const target = confirming;
setBusy(true); setErr('');
try { await auth.removeDevice(target.id); }
catch (e) {
// Already gone (removed elsewhere or expired) is the outcome the learner wanted.
if ((e as { status?: number })?.status !== 404) { setErr(t('profile.deviceRemoveFailed')); setBusy(false); return; }
}
setDevices((list) => list?.filter((d) => d.id !== target.id) ?? null);
setConfirming(null); setBusy(false);
toast(t('profile.deviceRemoved'));
load();
};
if (!devices) return failed
? <div className="stack-sm"><p className="err" role="alert">{t('profile.devicesFailed')}</p><button className="btn btn-ghost btn-sm" onClick={load}>{t('profile.devicesRetry')}</button></div>
: <Skeleton h={56} />;
const ordered = [...devices].sort((a, b) => Number(b.is_current) - Number(a.is_current));
return <>
<p className="small muted">{t('profile.deviceLimit', { n: settings.sessionLimit })}</p>
<ul className="device-list">{ordered.map((d) => <li className="device-row" key={d.id}>
<span className="device-copy">
<strong>{d.label}</strong>
<span>{d.is_current ? `${t('profile.currentDevice')} · ` : ''}{t('auth.lastActive', { date: fmtDateTime(d.last_seen_at) })}</span>
</span>
{d.is_current
? <button className="btn btn-ghost btn-sm" onClick={() => { signOut(); nav(`/${locale}`); }}>{t('profile.signOutSession')}</button>
: <button className="btn btn-ghost btn-sm" aria-label={`${t('profile.deviceRemove')}: ${d.label}`} onClick={() => { setErr(''); setConfirming(d); }}>{t('profile.deviceRemove')}</button>}
</li>)}</ul>
{failed && <p className="err" role="alert">{t('profile.devicesFailed')}</p>}
{confirming && <Modal title={t('profile.deviceRemoveTitle')} onClose={close}>
<div className="stack">
<p>{t('profile.deviceRemoveBody', { device: confirming.label })}</p>
{err && <p className="err" role="alert">{err}</p>}
<div className="device-actions">
<button className="btn btn-ghost" disabled={busy} onClick={close}>{t('common.cancel')}</button>
<button className="btn btn-accent" disabled={busy} onClick={remove}>{t('profile.deviceRemove')}</button>
</div>
</div>
</Modal>}
</>;
}
function Profile() {
const t = useTranslations();
const { me, ds, write, courses, categories, locale, setLocale, signOut, nav } = useApp();
@ -1688,7 +1785,7 @@ function Profile() {
</div>
<div className="card stack-sm">
<h2 style={{ fontSize: 'var(--fs-lg)' }}>{t('profile.sessions')}</h2>
<div className="row-between"><span><Icon name="shield" size={16} /> {t('profile.thisDevice')}</span><button className="btn btn-ghost btn-sm" onClick={() => { signOut(); nav(`/${locale}`); }}>{t('profile.signOutSession')}</button></div>
{ds.auth ? <ProfileDevices /> : <div className="row-between"><span><Icon name="shield" size={16} /> {t('profile.thisDevice')}</span><button className="btn btn-ghost btn-sm" onClick={() => { signOut(); nav(`/${locale}`); }}>{t('profile.signOutSession')}</button></div>}
</div>
<div className="card stack-sm">
<h2 style={{ fontSize: 'var(--fs-lg)' }}>{t('profile.purchases')}</h2>

View File

@ -1260,3 +1260,19 @@ fieldset[disabled] .quiz-opt { cursor: default; }
.lsheet-grip { width: 40px; height: 5px; border-radius: 3px; background: var(--line); }
.lsheet-top .icon-btn { position: absolute; inset-inline-end: 0; }
@media (min-width: 640px) { .lsheet { max-width: 560px; margin-inline: auto; } }
/* Device picker and profile devices */
.auth-main h1:focus { outline: none; }
.device-options { display: grid; gap: 8px; min-width: 0; margin: 0; padding: 0; border: 0; }
.device-option { display: flex; align-items: center; gap: 12px; min-height: 56px; padding: 10px 14px; border: 1px solid var(--line); border-radius: var(--r-md); cursor: pointer; }
.device-option:has(input:checked) { border-color: var(--accent); box-shadow: inset 0 0 0 1px var(--accent); background: var(--mist); }
.device-option:has(input:focus-visible) { outline: 2px solid var(--accent); outline-offset: 2px; }
.device-option input { flex: none; width: 20px; height: 20px; margin: 0; accent-color: var(--accent); }
.device-copy { display: flex; flex-direction: column; gap: 2px; flex: 1; min-width: 0; overflow-wrap: anywhere; }
.device-copy > span { font-size: var(--fs-sm); color: var(--ink-3); font-variant-numeric: tabular-nums; }
.device-list { display: grid; list-style: none; margin: 0; padding: 0; }
.device-row { display: flex; align-items: center; justify-content: space-between; gap: 12px; padding: 10px 0; border-top: 1px solid var(--line); }
.device-row:first-child { border-top: 0; }
.device-row .btn { flex: none; min-height: 44px; }
.device-actions { display: flex; justify-content: flex-end; flex-wrap: wrap; gap: 8px; }
.device-actions .btn { min-height: 44px; }

View File

@ -65,6 +65,14 @@
"waitPill": "በቅርቡ ይከፈታል · የተጠባባቂ ዝርዝሩን ይቀላቀሉ"
},
"auth": {
"deviceLimitTitle": "በ{n} መሣሪያዎች ገብተዋል",
"deviceLimitLead": "እዚህ ለመቀጠል አንዱን ያስወግዱ። ወዲያውኑ ይወጣል።",
"deviceLegend": "የሚያስወግዱትን መሣሪያ ይምረጡ",
"lastActive": "መጨረሻ የታየው {date}",
"chooseDevice": "የሚያስወግዱትን መሣሪያ ይምረጡ።",
"removeContinue": "አስወግድና ቀጥል",
"replaceExpired": "ይህ ጥያቄ ጊዜው አልፏል። እባክዎ እንደገና ይግቡ።",
"sessionRevoked": "ይህ መሣሪያ ከመለያዎ ተወግዷል።",
"socialLabel": "በሌላ መለያ ይግቡ",
"continueWith": "በ{name} ይቀጥሉ",
"phoneTitle": "በስልክዎ ይግቡ",
@ -277,6 +285,15 @@
"required": "ርዕሱንና የተፈጠረውን ይሙሉ።"
},
"profile": {
"currentDevice": "ይህ መሣሪያ",
"deviceLimit": "እስከ {n} መሣሪያዎች መጠቀም ይችላሉ።",
"devicesFailed": "መሣሪያዎችዎን መጫን አልተቻለም።",
"devicesRetry": "እንደገና ሞክር",
"deviceRemove": "አስወግድ",
"deviceRemoveTitle": "ይህ መሣሪያ ይወገድ?",
"deviceRemoveBody": "{device} ይወገድ? ወዲያውኑ ይወጣል።",
"deviceRemoveFailed": "መሣሪያውን ማስወገድ አልተቻለም። እንደገና ይሞክሩ።",
"deviceRemoved": "መሣሪያው ተወግዷል።",
"lessonsList": "ትምህርቶችና ፈተናዎች",
"account": "የመለያ ቅንብሮች",
"statTime": "የታየ ጊዜ",

View File

@ -65,6 +65,14 @@
"waitPill": "Opening soon · Join the waitlist"
},
"auth": {
"deviceLimitTitle": "You're signed in on {n} devices",
"deviceLimitLead": "Remove one to continue here. It will be signed out right away.",
"deviceLegend": "Choose a device to remove",
"lastActive": "Last active {date}",
"chooseDevice": "Choose a device to remove.",
"removeContinue": "Remove and continue",
"replaceExpired": "This request expired. Please sign in again.",
"sessionRevoked": "This device was removed from your account.",
"socialLabel": "Sign in with another account",
"continueWith": "Continue with {name}",
"phoneTitle": "Sign in with your phone",
@ -277,6 +285,15 @@
"required": "Fill in the subject and what happened."
},
"profile": {
"currentDevice": "This device",
"deviceLimit": "You can use up to {n} devices.",
"devicesFailed": "We couldn't load your devices.",
"devicesRetry": "Try again",
"deviceRemove": "Remove",
"deviceRemoveTitle": "Remove this device?",
"deviceRemoveBody": "Remove {device}? It will be signed out right away.",
"deviceRemoveFailed": "We couldn't remove this device. Try again.",
"deviceRemoved": "Device removed.",
"lessonsList": "Lessons and quizzes",
"account": "Account settings",
"statTime": "Watch time",

View File

@ -65,6 +65,14 @@
"waitPill": "Dhiyootti banama · Tarree eegdotaatti makami"
},
"auth": {
"deviceLimitTitle": "Meeshaalee {n} irratti seentaniirtu",
"deviceLimitLead": "Asitti itti fufuuf tokko balleessaa. Battalumatti ni bahama.",
"deviceLegend": "Meeshaa balleessitan filadhaa",
"lastActive": "Yeroo dhumaa kan hojjete {date}",
"chooseDevice": "Meeshaa balleessitan filadhaa.",
"removeContinue": "Balleessii itti fufi",
"replaceExpired": "Gaaffiin kun yeroon isaa darbeera. Maaloo irra deebi'aa seenaa.",
"sessionRevoked": "Meeshaan kun herrega keessan irraa balleeffameera.",
"socialLabel": "Herrega biraatiin seeni",
"continueWith": "{name}n itti fufi",
"phoneTitle": "Bilbila keetiin seeni",
@ -277,6 +285,15 @@
"required": "Mata-duree fi waan uumame guuti."
},
"profile": {
"currentDevice": "Meeshaa kana",
"deviceLimit": "Hanga meeshaalee {n} fayyadamuu dandeessu.",
"devicesFailed": "Meeshaalee keessan fe'uun hin danda'amne.",
"devicesRetry": "Irra deebi'ii yaali",
"deviceRemove": "Balleessi",
"deviceRemoveTitle": "Meeshaan kun haa balleeffamu?",
"deviceRemoveBody": "{device} haa balleeffamu? Battalumatti ni baha.",
"deviceRemoveFailed": "Meeshaa kana balleessuun hin danda'amne. Irra deebi'aa yaalaa.",
"deviceRemoved": "Meeshaan balleeffameera.",
"lessonsList": "Barnootaa fi qormaata",
"account": "Qindaa'ina herregaa",
"statTime": "Yeroo ilaalame",

View File

@ -65,6 +65,14 @@
"waitPill": "ቀልጢፉ ይኽፈት · ናብ ዝርዝር ተጸበይቲ ተጸንበር"
},
"auth": {
"deviceLimitTitle": "ኣብ {n} መሳርሒታት ኣቲኹም ኣለኹም",
"deviceLimitLead": "ኣብዚ ንምቕጻል ሓደ ኣልግሱ። ብቕጽበት ክወጽእ እዩ።",
"deviceLegend": "እትኣልግሱዎ መሳርሒ ምረጹ",
"lastActive": "ናይ መወዳእታ ንጥፈት {date}",
"chooseDevice": "እትኣልግሱዎ መሳርሒ ምረጹ።",
"removeContinue": "ኣልግስን ቀጽልን",
"replaceExpired": "እዚ ሕቶ ግዜኡ ሓሊፉ። በጃኹም ደጊምኩም እተዉ።",
"sessionRevoked": "እዚ መሳርሒ ካብ ሕሳብኩም ተኣልዩ።",
"socialLabel": "ብካልእ ሕሳብ እቶ",
"continueWith": "ብ{name} ቀጽል",
"phoneTitle": "ብተሌፎንካ እቶ",
@ -277,6 +285,15 @@
"required": "ኣርእስትን ዘጋጠመን ምላእ።"
},
"profile": {
"currentDevice": "እዚ መሳርሒ",
"deviceLimit": "ክሳብ {n} መሳርሒታት ክትጥቀሙ ትኽእሉ።",
"devicesFailed": "መሳርሒታትኩም ክጽዓኑ ኣይከኣሉን።",
"devicesRetry": "ደጊምካ ፈትን",
"deviceRemove": "ኣልግስ",
"deviceRemoveTitle": "እዚ መሳርሒ ይለገስ?",
"deviceRemoveBody": "{device} ይለገስ? ብቕጽበት ክወጽእ እዩ።",
"deviceRemoveFailed": "ነዚ መሳርሒ ምእላይ ኣይተኻእለን። ደጊምኩም ፈትኑ።",
"deviceRemoved": "መሳርሒ ተኣልዩ።",
"lessonsList": "ትምህርትታትን ፈተናታትን",
"account": "ምድላው ሕሳብ",
"statTime": "ዝተራእየ ግዜ",