From 2f42f083685cc8510d7d83828f56ebaf05c4dbc8 Mon Sep 17 00:00:00 2001 From: n3p-tun3 Date: Mon, 23 Nov 2026 18:10:00 +0300 Subject: [PATCH] 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 --- packages/data/src/api.check.ts | 127 ++++++++++++++++++- packages/data/src/api.ts | 196 +++++++++++++++++++++++++----- packages/data/src/index.ts | 14 ++- packages/features/src/store.tsx | 21 ++++ packages/features/src/student.tsx | 117 ++++++++++++++++-- packages/features/src/styles.css | 16 +++ packages/i18n/messages/am.json | 17 +++ packages/i18n/messages/en.json | 17 +++ packages/i18n/messages/om.json | 17 +++ packages/i18n/messages/ti.json | 17 +++ 10 files changed, 518 insertions(+), 41 deletions(-) diff --git a/packages/data/src/api.check.ts b/packages/data/src/api.check.ts index a9d7829..05189e6 100644 --- a/packages/data/src/api.check.ts +++ b/packages/data/src/api.check.ts @@ -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).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(); +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'); diff --git a/packages/data/src/api.ts b/packages/data/src/api.ts index 0e7ef24..434864e 100644 --- a/packages/data/src/api.ts +++ b/packages/data/src/api.ts @@ -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(items: T[], limit: number, fn: (x: T) => Promise { 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 } | 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 = {}; 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(method: string, path: string, body?: unknown, auth = true, retry = method === 'GET'): Promise { - 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 { - if (!this.tokens) return Promise.resolve(false); - const tokens = this.tokens; + private refresh(tokens: Tokens): Promise { + 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 { + 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 { 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 => { + 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 => { + const r = await this.request('GET', '/user/me/sessions'); + return Array.isArray(r) ? r : r.sessions ?? []; + }, + removeDevice: async (id: string): Promise => { + 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. diff --git a/packages/data/src/index.ts b/packages/data/src/index.ts index 202d665..493646f 100644 --- a/packages/data/src/index.ts +++ b/packages/data/src/index.ts @@ -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; + replaceDevice(challengeToken: string, sessionId: string): Promise; + listDevices(): Promise; + removeDevice(id: string): Promise; + onSessionRevoked(cb: () => void): Unsub; signOut(): Promise; } @@ -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'; diff --git a/packages/features/src/store.tsx b/packages/features/src/store.tsx index 6a18e85..00c517a 100644 --- a/packages/features/src/store.tsx +++ b/packages/features/src/store.tsx @@ -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) => lookup(loc, key, vars), []); const write = useCallback((fn: () => Promise, okMsg?: string) => { diff --git a/packages/features/src/student.tsx b/packages/features/src/student.tsx index 71df7c0..1e63f6e 100644 --- a/packages/features/src/student.tsx +++ b/packages/features/src/student.tsx @@ -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(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 ; 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 ; return (
@@ -1496,7 +1520,7 @@ function SignIn() {
{!auth && !viewer?.id ? {t('auth.noIdentity')} : step === 'start' ?
{ e.preventDefault(); send(); }}> -

{t('auth.welcome')}

{t('auth.welcomeLead')}

+

{t('auth.welcome')}

{t('auth.welcomeLead')}

{me && !me.deletedAt && } {/* Google / Apple need the providers' own sign-in SDKs before they can run against the API */} {!auth && <> { if (me && !me.deletedAt) { signIn(); nav(`/${locale}`); } else setStep('setup'); }} /> @@ -1513,8 +1537,8 @@ function SignIn() { {err &&

{err}

} - :
-

{t('auth.codeTitle')}

+
: step === 'code' ?
+

{t('auth.codeTitle')}

{t('auth.codeSent', { target })}

{!auth &&

{t('auth.demoCode', { code })}

} @@ -1522,6 +1546,21 @@ function SignIn() { +
:
+
+

{t('auth.deviceLimitTitle', { n: challenge?.devices.length ?? 0 })}

+

{t('auth.deviceLimitLead')}

+
+
+ {t('auth.deviceLegend')} + {challenge?.devices.map((device) => )} +
+ {err &&

{err}

} + +
}
@@ -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(null); + const [failed, setFailed] = useState(false); + const [confirming, setConfirming] = useState(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 + ?

{t('profile.devicesFailed')}

+ : ; + const ordered = [...devices].sort((a, b) => Number(b.is_current) - Number(a.is_current)); + return <> +

{t('profile.deviceLimit', { n: settings.sessionLimit })}

+
    {ordered.map((d) =>
  • + + {d.label} + {d.is_current ? `${t('profile.currentDevice')} · ` : ''}{t('auth.lastActive', { date: fmtDateTime(d.last_seen_at) })} + + {d.is_current + ? + : } +
  • )}
+ {failed &&

{t('profile.devicesFailed')}

} + {confirming && +
+

{t('profile.deviceRemoveBody', { device: confirming.label })}

+ {err &&

{err}

} +
+ + +
+
+
} + ; +} + function Profile() { const t = useTranslations(); const { me, ds, write, courses, categories, locale, setLocale, signOut, nav } = useApp(); @@ -1688,7 +1785,7 @@ function Profile() {

{t('profile.sessions')}

-
{t('profile.thisDevice')}
+ {ds.auth ? :
{t('profile.thisDevice')}
}

{t('profile.purchases')}

diff --git a/packages/features/src/styles.css b/packages/features/src/styles.css index 681b606..c15e630 100644 --- a/packages/features/src/styles.css +++ b/packages/features/src/styles.css @@ -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; } diff --git a/packages/i18n/messages/am.json b/packages/i18n/messages/am.json index 6888bd0..132def6 100644 --- a/packages/i18n/messages/am.json +++ b/packages/i18n/messages/am.json @@ -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": "የታየ ጊዜ", diff --git a/packages/i18n/messages/en.json b/packages/i18n/messages/en.json index 49f9e91..00250a9 100644 --- a/packages/i18n/messages/en.json +++ b/packages/i18n/messages/en.json @@ -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", diff --git a/packages/i18n/messages/om.json b/packages/i18n/messages/om.json index ac12187..5213886 100644 --- a/packages/i18n/messages/om.json +++ b/packages/i18n/messages/om.json @@ -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", diff --git a/packages/i18n/messages/ti.json b/packages/i18n/messages/ti.json index a11bb61..9fbe2f1 100644 --- a/packages/i18n/messages/ti.json +++ b/packages/i18n/messages/ti.json @@ -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": "ዝተራእየ ግዜ", -- 2.43.0