diff --git a/packages/data/src/api.check.ts b/packages/data/src/api.check.ts index 08f02e1..a9d7829 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, ids, mapIssue, mapNotification, mapOutline, mapStudent, slugify, type RawOutline } from './api.ts'; +import { absolute, ApiDataSource, 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; @@ -70,4 +70,68 @@ assert.equal(s.progress.l39?.positionSec, 40, 'this session’s resume point sur assert.equal(s.issues['1']?.type, 'PAYMENT'); assert.equal(mapStudent({ id: 1, preferred_language: 'fr' }, null, [], {}, now).locale, 'en', 'unknown language falls back to English'); +// sign-out revocation (mocked transport only: these checks never contact the production API) +const TOKEN_KEY = 'lms.api.tokens'; +const storage = new Map(); +Object.defineProperty(globalThis, 'localStorage', { configurable: true, value: { + getItem: (key: string) => storage.get(key) ?? null, + setItem: (key: string, value: string) => storage.set(key, value), + removeItem: (key: string) => storage.delete(key), +} }); +const oldTokens = { access: 'access-old', refresh: 'refresh-old', userId: 9 }; +const seedTokens = () => storage.set(TOKEN_KEY, JSON.stringify(oldTokens)); +const mockBase = 'https://mock.invalid'; +const response = (body: unknown, status = 200) => new Response(body == null ? null : JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } }); + +// normal logout carries both credentials, then removes the local session +seedTokens(); +let calls: { url: string; init?: RequestInit }[] = []; +globalThis.fetch = async (input, init) => { calls.push({ url: String(input), init }); return response(null, 204); }; +await new ApiDataSource(mockBase).auth.signOut(); +assert.equal(calls.length, 1); +assert.equal(calls[0].url, `${mockBase}/api/v1/auth/logout`); +assert.equal(new Headers(calls[0].init?.headers).get('authorization'), 'Bearer access-old'); +assert.deepEqual(JSON.parse(String(calls[0].init?.body)), { refresh_token: 'refresh-old' }); +assert.equal(storage.get(TOKEN_KEY), undefined); + +// an expired access token refreshes once, then revokes with the rotated pair +seedTokens(); calls = []; +globalThis.fetch = async (input, init) => { + const url = String(input); calls.push({ url, init }); + if (url.endsWith('/auth/logout') && calls.filter((x) => x.url.endsWith('/auth/logout')).length === 1) return response({ message: 'expired' }, 401); + if (url.endsWith('/auth/refresh')) return response({ data: { access_token: 'access-new', refresh_token: 'refresh-new', user_id: 9 } }); + return response(null, 204); +}; +await new ApiDataSource(mockBase).auth.signOut(); +assert.deepEqual(calls.map((x) => x.url.slice(mockBase.length)), ['/api/v1/auth/logout', '/api/v1/auth/refresh', '/api/v1/auth/logout']); +assert.equal(new Headers(calls[2].init?.headers).get('authorization'), 'Bearer access-new'); +assert.deepEqual(JSON.parse(String(calls[2].init?.body)), { refresh_token: 'refresh-new' }); +assert.equal(storage.get(TOKEN_KEY), undefined); + +// network failure never prevents local sign-out +seedTokens(); +globalThis.fetch = async () => { throw new Error('offline'); }; +await new ApiDataSource(mockBase).auth.signOut(); +assert.equal(storage.get(TOKEN_KEY), undefined); + +// a refresh that started before sign-out cannot restore its result afterward +seedTokens(); +let releaseRefresh!: (value: Response) => void; +let refreshStarted!: () => void; +const started = new Promise((resolve) => { refreshStarted = resolve; }); +globalThis.fetch = async (input) => { + const url = String(input); + if (url.endsWith('/user/user-profile')) return response({ message: 'expired' }, 401); + if (url.endsWith('/auth/refresh')) { refreshStarted(); return new Promise((resolve) => { releaseRefresh = resolve; }); } + if (url.endsWith('/auth/logout')) return response(null, 204); + throw new Error(`unexpected mocked request: ${url}`); +}; +const racing = new ApiDataSource(mockBase); +const viewing = racing.viewer(); +await started; +const signingOut = racing.auth.signOut(); +releaseRefresh(response({ data: { access_token: 'late-access', refresh_token: 'late-refresh', user_id: 9 } })); +await Promise.all([viewing, signingOut]); +assert.equal(storage.get(TOKEN_KEY), undefined, 'late refresh must not recreate the signed-out session'); + console.log('api checks: all passed'); diff --git a/packages/data/src/api.ts b/packages/data/src/api.ts index 55ffca0..0e7ef24 100644 --- a/packages/data/src/api.ts +++ b/packages/data/src/api.ts @@ -146,7 +146,8 @@ type Contact = { phone?: string; email?: string; password?: string }; export class ApiDataSource implements DataSource { readonly kind = 'api' as const; private tokens: Tokens | null = readTokens(); - private refreshing: Promise | null = null; + private tokenVersion = 0; + private refreshing: { version: number; promise: Promise } | null = null; private courseCbs = new Set<(c: Course[]) => void>(); private studentCbs = new Map<(s: Student | null) => void, string>(); private inboxCbs = new Set<(i: InboxItem[]) => void>(); @@ -186,20 +187,48 @@ export class ApiDataSource implements DataSource { private refresh(): Promise { if (!this.tokens) return Promise.resolve(false); - this.refreshing ??= fetch(`${this.base.replace(/\/+$/, '')}/api/v1/auth/refresh`, { + const tokens = this.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: this.tokens.access, refresh_token: this.tokens.refresh }), + 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(() => { this.refreshing = null; }); - return this.refreshing; + }, () => false).finally(() => { if (this.refreshing?.promise === promise) this.refreshing = null; }); + this.refreshing = { version, promise }; + return promise; } - private setTokens(t: Tokens | null) { this.tokens = t; writeTokens(t); } + private setTokens(t: Tokens | null) { this.tokenVersion++; this.tokens = t; writeTokens(t); } + + private logoutRequest(t: Tokens) { + return fetch(`${this.base.replace(/\/+$/, '')}/api/v1/auth/logout`, { + method: 'POST', + headers: { 'content-type': 'application/json', authorization: `Bearer ${t.access}` }, + body: JSON.stringify({ refresh_token: t.refresh }), + signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS), + }); + } + + /** Refresh only for a final revoke attempt. These tokens are never installed into the signed-out client. */ + 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' }, + body: JSON.stringify({ access_token: t.access, refresh_token: t.refresh }), + signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS), + }); + const j = await r.json().catch(() => null); + if (!r.ok || !j?.data?.access_token || !j.data.refresh_token) return null; + return { access: j.data.access_token, refresh: j.data.refresh_token, userId: j.data.user_id ?? t.userId }; + } catch { return null; } + } // ---- auth (the screens reach this through `ds.auth` when it exists; the demo has none) @@ -231,10 +260,20 @@ export class ApiDataSource implements DataSource { }, signOut: async () => { const t = this.tokens; + // Invalidate every refresh already in flight before doing any network work. this.setTokens(null); - if (t) await this.request('POST', '/auth/logout', { refresh_token: t.refresh }, false).catch(() => { /* already gone server-side */ }); this.localProgress = {}; - this.refreshAll(); + try { + if (t) { + const first = await this.logoutRequest(t); + if (first.status === 401) { + const fresh = await this.refreshForLogout(t); + if (fresh) await this.logoutRequest(fresh); + } + } + } catch { /* local sign-out still wins on timeout, network failure, or API failure */ } + // Tokens were cleared above; clearing again here would erase a sign-in made while logout was pending. + finally { this.refreshAll(); } }, }; diff --git a/packages/features/src/domain.check.ts b/packages/features/src/domain.check.ts index d751212..5fd2f1a 100644 --- a/packages/features/src/domain.check.ts +++ b/packages/features/src/domain.check.ts @@ -2,6 +2,7 @@ import assert from 'node:assert/strict'; import type { Course, Student } from '@lms/data'; import { applyHeartbeat, DomainError, gradeAssessment, applyPaymentEvent, createOrder, dashboardMetrics, effectiveStatus, isStudentVisible, lessonAccess, publishProblems, validateLocation, validPassword } from './domain.ts'; +import { decodeLearnerCode, encodeLearnerCode } from './learnerCode.ts'; const lesson = (id: string, extra = {}) => ({ id, sortOrder: Number(id.slice(-1)), isPreview: false, isPublished: true, durationSec: 100, videoStatus: 'READY' as const, translations: { en: { title: id } }, ...extra }); const course = (id: string, extra: Partial = {}): Course => ({ @@ -88,4 +89,13 @@ assert.deepEqual([g2.score, g2.bestPct, g2.passed, g2.attempts], [1, 100, true, assert.equal(gradeAssessment(A, quiz, [1, 1, 1], undefined, now).passed, false); assert.throws(() => gradeAssessment(A, quiz, [0, 1], undefined, now), DomainError); +// Traceable player watermark: numeric learner ids round-trip without ambiguous characters. +for (const id of [0, 1, 31, 32, 9_847_231, Number.MAX_SAFE_INTEGER]) { + const code = encodeLearnerCode(id); + assert.match(code, /^RZ-[2-9A-HJ-NP-Z]+$/); + assert.equal(decodeLearnerCode(code), id); +} +assert.equal(decodeLearnerCode('RZ-O01I'), null); +assert.throws(() => encodeLearnerCode(-1), RangeError); + console.log('domain checks: all passed'); diff --git a/packages/features/src/learnerCode.ts b/packages/features/src/learnerCode.ts new file mode 100644 index 0000000..f775dfa --- /dev/null +++ b/packages/features/src/learnerCode.ts @@ -0,0 +1,29 @@ +// A compact support identifier, not a secret. The alphabet omits 0/O and 1/I. +const ALPHABET = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ'; +const PREFIX = 'RZ-'; + +export function encodeLearnerCode(id: number): string { + if (!Number.isSafeInteger(id) || id < 0) throw new RangeError('Learner id must be a non-negative safe integer'); + let n = id; + let body = ''; + do { + body = ALPHABET[n % ALPHABET.length] + body; + n = Math.floor(n / ALPHABET.length); + } while (n > 0); + return PREFIX + body.padStart(4, ALPHABET[0]); +} + +export function decodeLearnerCode(code: string): number | null { + const value = code.trim().toUpperCase(); + if (!value.startsWith(PREFIX)) return null; + const body = value.slice(PREFIX.length); + if (!body) return null; + let id = 0; + for (const char of body) { + const digit = ALPHABET.indexOf(char); + if (digit < 0) return null; + id = id * ALPHABET.length + digit; + if (!Number.isSafeInteger(id)) return null; + } + return id; +} diff --git a/packages/features/src/student.tsx b/packages/features/src/student.tsx index 383f530..71df7c0 100644 --- a/packages/features/src/student.tsx +++ b/packages/features/src/student.tsx @@ -11,6 +11,7 @@ import { } 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 { PAY_LOGOS } from './payLogos'; +import { encodeLearnerCode } from './learnerCode'; const ISSUE_TYPES: IssueType[] = ['BUG', 'PAYMENT', 'VIDEO', 'ACCOUNT', 'CONTENT', 'OTHER']; // Demo checkout lists every method we plan to accept; all of them run through the same simulated ETB order. @@ -955,7 +956,7 @@ export function vimeoPlayerUrl(url: string): string | null { function VideoPanel({ c, lesson, next, head }: { c: Course; lesson: Lesson; next?: Lesson; head?: ReactNode }) { const t = useTranslations(); - const { me, locale, nav, ds, write, signedIn, viewer } = useApp(); + const { me, locale, nav, ds, write, signedIn } = useApp(); // A Vimeo link (what the API's lessons carry) plays in Vimeo's player; no video yet plays the sample clip. const placeholder = !lesson.videoAssetId; const vimeoSrc = placeholder ? VIMEO_PLACEHOLDER : vimeoPlayerUrl(lesson.videoAssetId!); @@ -963,7 +964,9 @@ function VideoPanel({ c, lesson, next, head }: { c: Course; lesson: Lesson; next const [vdur, setVdur] = useState(0); const dur = (vimeo && vdur) || lesson.durationSec || 1; const saved = me?.progress?.[lesson.id]; - const [pos, setPos] = useState(() => (saved && !saved.completedAt ? Math.min(saved.positionSec, dur - 5) : 0)); + const [pos, setPos] = useState(() => (saved && !saved.completedAt + ? Math.max(0, lesson.durationSec ? Math.min(saved.positionSec, lesson.durationSec - 5) : saved.positionSec) + : 0)); const [playing, setPlaying] = useState(false); const [rate, setRate] = useState(1); const conn = typeof navigator !== 'undefined' ? (navigator as any).connection : undefined; @@ -973,6 +976,8 @@ function VideoPanel({ c, lesson, next, head }: { c: Course; lesson: Lesson; next // L4: when a lesson ends, "up next" appears over the video and plays it after a short count the student can cancel const [ended, setEnded] = useState(false); const [auto, setAuto] = useState(null); + const [fillViewport, setFillViewport] = useState(false); + const [nativeFullscreen, setNativeFullscreen] = useState(false); const videoRef = useRef(null); const frameRef = useRef(null); const screenRef = useRef(null); @@ -1023,6 +1028,26 @@ function VideoPanel({ c, lesson, next, head }: { c: Course; lesson: Lesson; next }, [heartbeat]); useEffect(() => { const v = videoRef.current; if (v) v.playbackRate = rate; }, [rate]); useEffect(() => { if (vimeo && rate !== 1) vcall('setPlaybackRate', rate); }, [rate]); + useEffect(() => { + const changed = () => setNativeFullscreen(document.fullscreenElement === screenRef.current); + document.addEventListener('fullscreenchange', changed); + return () => document.removeEventListener('fullscreenchange', changed); + }, []); + useEffect(() => { + if (!fillViewport) return; + const root = document.documentElement; + const body = document.body; + const scrollY = window.scrollY; + const before = { rootOverflow: root.style.overflow, bodyOverflow: body.style.overflow, position: body.style.position, top: body.style.top, width: body.style.width }; + root.style.overflow = 'hidden'; body.style.overflow = 'hidden'; body.style.position = 'fixed'; body.style.top = `-${scrollY}px`; body.style.width = '100%'; + const escape = (e: KeyboardEvent) => { if (e.key === 'Escape') setFillViewport(false); }; + addEventListener('keydown', escape, true); + return () => { + removeEventListener('keydown', escape, true); + root.style.overflow = before.rootOverflow; body.style.overflow = before.bodyOverflow; body.style.position = before.position; body.style.top = before.top; body.style.width = before.width; + window.scrollTo(0, scrollY); + }; + }, [fillViewport]); const goNext = () => { if (next) nav(`/${locale}/learn/${c.slug}/${next.id}`); }; useEffect(() => { if (ended && next) setAuto(AUTO_NEXT_SEC); }, [ended, next]); useEffect(() => { @@ -1038,26 +1063,39 @@ function VideoPanel({ c, lesson, next, head }: { c: Course; lesson: Lesson; next vcall(playing ? 'pause' : 'play'); }; const seek = (to: number) => { const n = Math.max(0, Math.min(dur, to)); setPos(n); if (videoRef.current) videoRef.current.currentTime = n; else vcall('setCurrentTime', n); }; - const full = () => { screenRef.current?.requestFullscreen?.().catch(() => { /* not allowed in this frame */ }); }; - const onKey = (e: React.KeyboardEvent) => { - if ((e.target as HTMLElement).tagName === 'SELECT' || (e.target as HTMLElement).tagName === 'INPUT') return; - if (e.key === 'Escape' && auto != null) { setAuto(null); return; } - if (e.key === ' ') { e.preventDefault(); toggle(); } else if (e.key === 'ArrowLeft') seek(pos - 10); else if (e.key === 'ArrowRight') seek(pos + 10); else if (e.key === 'f') full(); else if (e.key === 'm' && videoRef.current) videoRef.current.muted = !videoRef.current.muted; + const full = () => { + const screen = screenRef.current; + if (!screen) return; + if (fillViewport) { setFillViewport(false); return; } + if (document.fullscreenElement === screen) { document.exitFullscreen().catch(() => {}); return; } + if (!screen.requestFullscreen) { setFillViewport(true); return; } + screen.requestFullscreen().catch(() => setFillViewport(true)); }; - const mark = (me?.phone || me?.email || viewer?.name || 'student').replace(/^(.{3}).*(.{2})$/, '$1•••$2'); + const onKey = (e: React.KeyboardEvent) => { + const el = e.target as HTMLElement; + if (el.tagName === 'SELECT' || el.tagName === 'INPUT' || (el.tagName === 'BUTTON' && (e.key === ' ' || e.key === 'Enter'))) return; + if (e.key === 'Escape' && auto != null) { setAuto(null); return; } + if (e.key === ' ') { e.preventDefault(); toggle(); } else if (e.key === 'ArrowLeft') seek(pos - 10); else if (e.key === 'ArrowRight') seek(pos + 10); else if (e.key.toLowerCase() === 'f') full(); else if (e.key.toLowerCase() === 'm' && videoRef.current) videoRef.current.muted = !videoRef.current.muted; + }; + const numericLearnerId = me && /^(0|[1-9]\d*)$/.test(me.id) ? Number(me.id) : NaN; + const mark = signedIn && Number.isSafeInteger(numericLearnerId) ? encodeLearnerCode(numericLearnerId) : null; + const isFullscreen = fillViewport || nativeFullscreen; const done = isCompleted(me, lesson.id) || justDone; const pct = courseProgress(c, me).pct; return (
-
- {lesson.videoAssetId ? ( -