Spaces:
Running
Running
Download tools/test-session-guard.cjs from tkadkghdlf/CD: direct link, hf CLI and curl.
- Browser
- Download file 11.9 kB
-
https://huggingface.co/spaces/tkadkghdlf/CD/resolve/main/tools/test-session-guard.cjs
- Command line
-
hf download hf://spaces/tkadkghdlf/CD/tools/test-session-guard.cjs
-
curl -L -o test-session-guard.cjs https://huggingface.co/spaces/tkadkghdlf/CD/resolve/main/tools/test-session-guard.cjs
11.9 kB
| // Session regressions use mocked tokens/APIs and a fake clock, never real accounts. | |
| const assert = require('node:assert/strict'); | |
| const fs = require('node:fs'); | |
| const path = require('node:path'); | |
| const vm = require('node:vm'); | |
| const ts = require('../main/node_modules/typescript'); | |
| const root = path.resolve(__dirname, '../main/app'); | |
| const jwt = (exp, sub = 'fixture') => `fixture.${Buffer.from(JSON.stringify({ exp, sub })).toString('base64url')}.fixture`; | |
| const flush = async () => { for (let i = 0; i < 25; i++) await Promise.resolve(); }; | |
| function findElement(tree, predicate) { | |
| if (!tree || typeof tree !== 'object') return undefined; | |
| if (predicate(tree)) return tree; | |
| for (const child of [tree.props?.children].flat()) { | |
| const match = findElement(child, predicate); | |
| if (match) return match; | |
| } | |
| } | |
| function fixture(pathname = '/lobby') { | |
| let now = Date.now(); | |
| class ClockDate extends Date { static now() { return now; } } | |
| const values = new Map(); | |
| const localStorage = { | |
| getItem: key => values.get(key) ?? null, | |
| setItem: (key, value) => values.set(key, value), | |
| removeItem: key => values.delete(key), | |
| }; | |
| const location = { origin: 'http://localhost:3000', protocol: 'http:' }; | |
| const document = new EventTarget(); | |
| let cookie = ''; | |
| Object.defineProperty(document, 'cookie', { | |
| get: () => cookie, | |
| set: value => { cookie = value.includes('Max-Age=0') ? '' : value.split(';')[0]; }, | |
| }); | |
| document.visibilityState = 'visible'; | |
| const window = new EventTarget(); | |
| const timers = new Map(); | |
| const intervals = new Map(); | |
| let id = 0; | |
| const setTimeout = (callback, delay) => { const key = ++id; timers.set(key, { callback, delay }); return key; }; | |
| const clearTimeout = key => timers.delete(key); | |
| window.setInterval = callback => { const key = ++id; intervals.set(key, callback); return key; }; | |
| window.clearInterval = key => intervals.delete(key); | |
| const states = []; | |
| const effects = []; | |
| const refs = []; | |
| let cursor = 0; | |
| let refCursor = 0; | |
| const react = { | |
| useState(initial) { | |
| const key = cursor++; | |
| if (!(key in states)) states[key] = initial; | |
| return [states[key], next => { states[key] = typeof next === 'function' ? next(states[key]) : next; }]; | |
| }, | |
| useRef(initial) { const key = refCursor++; return refs[key] ??= { current: initial }; }, | |
| useEffect: effect => effects.push(effect), | |
| }; | |
| const modules = new Map(); | |
| const context = vm.createContext({ | |
| console, URL, Headers, Request, Response, AbortController, Event, Date: ClockDate, | |
| window, document, localStorage, location, atob, setTimeout, clearTimeout, | |
| process: { env: { NEXT_PUBLIC_API_BASE_URL: 'http://localhost:8000' } }, | |
| fetch: (...args) => window.fetch(...args), | |
| }); | |
| function load(filename) { | |
| const absolute = path.resolve(root, filename); | |
| if (modules.has(absolute)) return modules.get(absolute); | |
| const exports = {}; | |
| modules.set(absolute, exports); | |
| const code = ts.transpileModule(fs.readFileSync(absolute, 'utf8'), { | |
| compilerOptions: { module: ts.ModuleKind.CommonJS, jsx: ts.JsxEmit.ReactJSX, target: ts.ScriptTarget.ES2020 }, | |
| }).outputText; | |
| const requireFixture = name => { | |
| if (name === 'react') return react; | |
| if (name === 'react/jsx-runtime') return { jsx: (type, props) => ({ type, props }), jsxs: (type, props) => ({ type, props }), Fragment: 'Fragment' }; | |
| if (name === 'next/navigation') return { usePathname: () => pathname, useRouter: () => ({ replace: value => { result.redirect = value; } }) }; | |
| if (name.endsWith('nativeWearBridge')) return { syncNativeWearRelayAuth() {}, clearNativeWearRelayAuth() {} }; | |
| if (name.endsWith('nativeLocation')) return { getAppPosition: () => result.position() }; | |
| if (name === './LoginRequiredDialog') return { default: 'LoginRequiredDialog' }; | |
| const target = path.resolve(path.dirname(absolute), name); | |
| const extension = fs.existsSync(target + '.ts') ? '.ts' : '.tsx'; | |
| return load(path.relative(root, target + extension)); | |
| }; | |
| vm.runInContext(`(function(require, exports) { ${code}\n})`, context, { filename: absolute })(requireFixture, exports); | |
| return exports; | |
| } | |
| const result = { window, localStorage, timers, intervals, states, effects, load, | |
| advance(milliseconds) { now += milliseconds; }, | |
| position: async () => { throw { code: 1 }; }, | |
| render(component) { cursor = 0; refCursor = 0; return component({ children: null }); }, | |
| mount() { return effects.splice(0).map(effect => effect()); }, | |
| seed(token = jwt(Date.now() / 1000 + 3600)) { | |
| localStorage.setItem('access_token', token); localStorage.setItem('refresh_token', 'refresh-fixture'); | |
| }, | |
| }; | |
| return result; | |
| } | |
| (async () => { | |
| { | |
| const f = fixture(); | |
| const guard = f.load('_components/SessionGuard.tsx').default; | |
| f.window.fetch = async () => { throw Error('no API for missing session'); }; | |
| f.render(guard); const cleanup = f.mount(); await flush(); | |
| assert.equal(f.states[0], 'missing', 'unauthenticated lobby opens immediately'); | |
| const tree = f.render(guard); | |
| tree.props.children[1].props.onDismiss(); await flush(); | |
| assert.equal(f.states[0], null, 'later dismisses without reopening on the lobby'); | |
| f.load('_utils/sessionRestore.ts').requestLogin(); | |
| assert.equal(f.states[0], 'missing', 'protected actions reuse the same global dialog'); | |
| cleanup.forEach(fn => fn?.()); | |
| console.log('PASS unauthenticated lobby and dismiss'); | |
| } | |
| { | |
| const f = fixture('/signup'); | |
| f.window.fetch = async () => Response.json({}); | |
| f.render(f.load('_components/SessionGuard.tsx').default); const cleanup = f.mount(); await flush(); | |
| assert.equal(f.states[0], null, 'signup does not require login'); | |
| cleanup.forEach(fn => fn?.()); | |
| console.log('PASS public signup remains accessible'); | |
| } | |
| { | |
| const f = fixture(); f.seed(); | |
| let rejected = false; | |
| const renewed = jwt(Date.now() / 1000 + 120); | |
| f.window.fetch = async () => rejected ? new Response(null, { status: 401 }) : Response.json({ access_token: renewed, refresh_token: 'new-refresh' }); | |
| f.render(f.load('_components/SessionGuard.tsx').default); const cleanup = f.mount(); await flush(); | |
| assert.equal(f.states[0], null); | |
| const expiryTimer = [...f.timers.values()].find(timer => timer.delay < 65_000); | |
| assert.ok(expiryTimer, 'expiry check is scheduled before the token expires, not five minutes later'); | |
| rejected = true; f.advance(61_000); expiryTimer.callback(); await flush(); | |
| assert.equal(f.states[0], 'expired'); | |
| assert.equal(f.localStorage.getItem('access_token'), null); | |
| cleanup.forEach(fn => fn?.()); | |
| console.log('PASS idle expiry and rejected refresh open re-login'); | |
| } | |
| { | |
| const f = fixture(); f.seed(); | |
| let expired = 0; | |
| f.window.addEventListener('rts:session-expired', () => expired++); | |
| f.window.fetch = async () => new Response(null, { status: 401 }); | |
| f.load('_utils/sessionFetch.ts').installSessionFetchObserver(); | |
| await f.window.fetch('http://localhost:8000/api/v1/auth/me', { headers: { Authorization: `Bearer ${f.localStorage.getItem('access_token')}` } }); | |
| assert.equal(expired, 1); assert.equal(f.localStorage.getItem('access_token'), null); | |
| console.log('PASS API 401 immediately invalidates an unrecoverable session'); | |
| } | |
| { | |
| const f = fixture(); f.seed(); | |
| const old = f.localStorage.getItem('access_token'); | |
| const renewed = jwt(Date.now() / 1000 + 7200); | |
| const calls = []; | |
| f.window.fetch = async (input, init) => { | |
| const url = String(input); calls.push({ url, auth: new Headers(init?.headers).get('Authorization') }); | |
| if (url.endsWith('/refresh')) return Response.json({ access_token: renewed, refresh_token: 'renewed' }); | |
| return new Headers(init?.headers).get('Authorization') === `Bearer ${old}` ? new Response(null, { status: 401 }) : Response.json({ ok: true }); | |
| }; | |
| f.load('_utils/sessionFetch.ts').installSessionFetchObserver(); | |
| const response = await f.window.fetch('http://localhost:8000/api/v1/auth/me', { headers: { Authorization: `Bearer ${old}` } }); | |
| assert.equal(response.status, 200); assert.equal(calls.length, 3); assert.equal(calls[2].auth, `Bearer ${renewed}`); | |
| console.log('PASS successful refresh retries the API with the new token'); | |
| } | |
| { | |
| const f = fixture(); f.seed(); const token = f.localStorage.getItem('access_token'); | |
| let expired = 0; f.window.addEventListener('rts:session-expired', () => expired++); | |
| f.window.fetch = async input => { | |
| if (String(input).endsWith('/refresh')) throw Error('offline'); | |
| return new Response(null, { status: 401 }); | |
| }; | |
| f.load('_utils/sessionFetch.ts').installSessionFetchObserver(); | |
| await f.window.fetch('http://localhost:8000/api/v1/auth/me', { headers: { Authorization: `Bearer ${token}` } }); | |
| await f.window.fetch('http://localhost:8000/api/v1/auth/login'); | |
| assert.equal(expired, 0); assert.equal(f.localStorage.getItem('access_token'), token); | |
| console.log('PASS connection errors and failed public login do not clear sessions'); | |
| } | |
| { | |
| const f = fixture(); f.seed(); const old = f.localStorage.getItem('access_token'); | |
| const current = jwt(Date.now() / 1000 + 3600, 'other-account'); | |
| f.window.fetch = async () => { f.localStorage.setItem('access_token', current); return new Response(null, { status: 401 }); }; | |
| f.load('_utils/sessionFetch.ts').installSessionFetchObserver(); | |
| await f.window.fetch('http://localhost:8000/api/v1/auth/me', { headers: { Authorization: `Bearer ${old}` } }); | |
| assert.equal(f.localStorage.getItem('access_token'), current); | |
| console.log('PASS stale requests cannot clear a new account session'); | |
| } | |
| { | |
| const f = fixture('/signup'); const component = f.load('_components/SignupLocationPermission.tsx').default; | |
| const choose = (tree, value, checked = true) => findElement(tree, node => node.type === 'input' && node.props.value === value).props.onChange({ target: { checked } }); | |
| let tree = f.render(component); | |
| let locationCalls = 0; | |
| f.position = async () => { locationCalls++; throw { code: 1 }; }; | |
| choose(tree, 'declined'); await flush(); | |
| assert.equal(locationCalls, 0, 'declining must not trigger a platform permission request'); | |
| assert.equal(f.localStorage.getItem('rts:location-consent'), 'declined'); | |
| tree = f.render(component); choose(tree, 'allowed'); await flush(); | |
| assert.equal(f.states[0], 'declined'); assert.equal(f.states[1], 'error'); assert.match(f.states[2], /๊ฐ์ ์ ๊ณ์/); | |
| f.position = async () => ({ coords: { latitude: 0, longitude: 0 } }); | |
| tree = f.render(component); choose(tree, 'allowed'); await flush(); | |
| assert.equal(f.states[0], 'allowed'); assert.equal(f.states[1], 'granted'); assert.match(f.states[2], /๋ก๋น/); | |
| let finish; | |
| f.position = () => new Promise(resolve => { finish = resolve; }); | |
| tree = f.render(component); choose(tree, 'allowed'); | |
| tree = f.render(component); choose(tree, 'declined'); | |
| finish({ coords: { latitude: 0, longitude: 0 } }); await flush(); | |
| assert.equal(f.states[0], 'declined'); assert.equal(f.states[1], 'idle'); | |
| assert.equal(f.localStorage.getItem('rts:location-consent'), 'declined', 'a late permission result must not override opting out'); | |
| tree = f.render(component); | |
| assert.equal(findElement(tree, node => node.type === 'input' && node.props.value === 'allowed').props.checked, false); | |
| assert.equal(findElement(tree, node => node.type === 'input' && node.props.value === 'declined').props.checked, true); | |
| choose(tree, 'declined', false); await flush(); | |
| assert.equal(f.states[0], null, 'unchecking an option clears the choice without granting permission'); | |
| console.log('PASS signup allow/decline, system denial, retry and opting out during a request'); | |
| } | |
| })().catch(error => { console.error(error); process.exitCode = 1; }); | |