From 6be3fe33bcf26483393684fce8b3ff7a8bf0955c Mon Sep 17 00:00:00 2001 From: TheGeneralist <180094941+thegeneralist01@users.noreply.github.com> Date: Fri, 9 Oct 2026 22:37:26 +0200 Subject: [PATCH] feat(frontend): sessions tab, token scope and expiry, admin user delete Co-Authored-By: Claude Haiku 5.5 --- frontend/src/api.js | 31 +++++- frontend/src/api.test.js | 71 +++++++++++++ frontend/src/components/AdminView.jsx | 17 +++- frontend/src/components/SettingsView.jsx | 123 ++++++++++++++++++++++- frontend/src/styles.css | 30 ++++++ frontend/src/utils.js | 12 +++ frontend/src/utils.test.js | 26 +++++ 7 files changed, 302 insertions(+), 8 deletions(-) create mode 100644 frontend/src/api.test.js create mode 100644 frontend/src/utils.test.js diff --git a/frontend/src/api.js b/frontend/src/api.js index c91fa95..c26115a 100644 --- a/frontend/src/api.js +++ b/frontend/src/api.js @@ -409,11 +409,13 @@ export async function listTokens() { return getJson('/api/auth/tokens'); } -export async function createToken(name) { +// `expiresInDays` null means the token never expires; `scope` is 'full' or 'read'. +// Omitting both sends the same behaviour as before (full access, no expiry). +export async function createToken(name, { expiresInDays = null, scope = 'full' } = {}) { const res = await fetch('/api/auth/tokens', { method: 'POST', headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ name }), + body: JSON.stringify({ name, expires_in_days: expiresInDays, scope }), }); if (!res.ok) throw new Error(await res.text()); return res.json(); @@ -424,6 +426,25 @@ export async function deleteToken(tokenUid) { if (!res.ok) throw new Error(await res.text()); } +// ── Sessions ────────────────────────────────────────────────────────────────── +// Rows: { session_handle, created_at, last_seen_at, expires_at, user_agent|null, current }. + +export async function listSessions() { + return getJson('/api/auth/sessions'); +} + +export async function revokeSession(sessionHandle) { + const res = await fetch(`/api/auth/sessions/${encodeURIComponent(sessionHandle)}`, { method: 'DELETE' }); + if (!res.ok) { const b = await res.json().catch(() => ({})); throw new Error(b.error || `HTTP ${res.status}`); } +} + +// Revokes every session except the caller's own. Resolves to { revoked: n }. +export async function revokeOtherSessions() { + const res = await fetch('/api/auth/sessions', { method: 'DELETE' }); + if (!res.ok) { const b = await res.json().catch(() => ({})); throw new Error(b.error || `HTTP ${res.status}`); } + return res.json(); +} + export async function getInstanceSettings() { return getJson('/api/admin/instance-settings'); } @@ -480,6 +501,12 @@ export async function setUserStatus(userUid, status) { return res.json(); } +// Server removes the user with their sessions, API tokens and role rows. 204, no body. +export async function deleteAdminUser(userUid) { + const res = await fetch(`/api/admin/users/${userUid}`, { method: 'DELETE' }); + if (!res.ok) { const b = await res.json().catch(() => ({})); throw new Error(b.error || `HTTP ${res.status}`); } +} + export async function assignRole(userUid, roleSlug) { const res = await fetch(`/api/admin/users/${userUid}/roles`, { method: 'POST', diff --git a/frontend/src/api.test.js b/frontend/src/api.test.js new file mode 100644 index 0000000..e889ebb --- /dev/null +++ b/frontend/src/api.test.js @@ -0,0 +1,71 @@ +import { afterEach, describe, expect, test } from 'bun:test' + +// api.js reads window.fetch at load time to install its 401 interceptor. Shim +// window only for the import; the calls below use the global fetch, which is +// the one api.js reaches at call time. +const originalWindow = globalThis.window +globalThis.window = { fetch: globalThis.fetch } +const api = await import('./api.js') +globalThis.window = originalWindow + +const originalFetch = globalThis.fetch +afterEach(() => { globalThis.fetch = originalFetch }) + +function mockFetch(response) { + const calls = [] + globalThis.fetch = async (url, options = {}) => { + calls.push({ url, method: options.method ?? 'GET', body: options.body }) + return response + } + return calls +} + +describe('token and session API calls', () => { + test('createToken defaults to full access with no expiry', async () => { + const calls = mockFetch(new Response(JSON.stringify({ raw_token: 'x' }), { status: 200 })) + await api.createToken('cli') + expect(calls).toHaveLength(1) + expect(calls[0].url).toBe('/api/auth/tokens') + expect(calls[0].method).toBe('POST') + expect(JSON.parse(calls[0].body)).toEqual({ name: 'cli', expires_in_days: null, scope: 'full' }) + }) + + test('createToken forwards expiry and read-only scope', async () => { + const calls = mockFetch(new Response('{}', { status: 200 })) + await api.createToken('ci', { expiresInDays: 30, scope: 'read' }) + expect(JSON.parse(calls[0].body)).toEqual({ name: 'ci', expires_in_days: 30, scope: 'read' }) + }) + + test('listSessions issues a GET to the sessions route', async () => { + const calls = mockFetch(new Response('[]', { status: 200 })) + expect(await api.listSessions()).toEqual([]) + expect(calls[0].url).toBe('/api/auth/sessions') + expect(calls[0].method).toBe('GET') + }) + + test('revokeSession encodes the handle as a single path segment', async () => { + const calls = mockFetch(new Response(null, { status: 204 })) + await api.revokeSession('a/b c') + expect(calls[0].url).toBe('/api/auth/sessions/a%2Fb%20c') + expect(calls[0].method).toBe('DELETE') + }) + + test('revokeOtherSessions resolves to the revoked count', async () => { + const calls = mockFetch(new Response(JSON.stringify({ revoked: 2 }), { status: 200 })) + expect(await api.revokeOtherSessions()).toEqual({ revoked: 2 }) + expect(calls[0].url).toBe('/api/auth/sessions') + expect(calls[0].method).toBe('DELETE') + }) + + test('server error messages reach the caller', async () => { + mockFetch(new Response(JSON.stringify({ error: 'cannot revoke current session' }), { status: 400 })) + await expect(api.revokeSession('h')).rejects.toThrow('cannot revoke current session') + }) + + test('deleteAdminUser issues a DELETE for the user uid', async () => { + const calls = mockFetch(new Response(null, { status: 204 })) + await api.deleteAdminUser('user-1') + expect(calls[0].url).toBe('/api/admin/users/user-1') + expect(calls[0].method).toBe('DELETE') + }) +}) diff --git a/frontend/src/components/AdminView.jsx b/frontend/src/components/AdminView.jsx index 760f365..feb4a75 100644 --- a/frontend/src/components/AdminView.jsx +++ b/frontend/src/components/AdminView.jsx @@ -1,7 +1,7 @@ import { useState, useEffect, useContext, useCallback } from 'react' import { AuthContext } from '../App.jsx' import { - listAdminUsers, createAdminUser, setUserStatus, assignRole, removeRole, + listAdminUsers, createAdminUser, setUserStatus, deleteAdminUser, assignRole, removeRole, listRoles, createRole, fetchArchives } from '../api.js' @@ -65,6 +65,16 @@ export default function AdminView({ archives }) { } } + async function handleDeleteUser(user) { + if (!window.confirm(`Delete user ${user.username}? This removes their sessions and API tokens and cannot be undone.`)) return + try { + await deleteAdminUser(user.user_uid) + setUsers(us => us.filter(u => u.user_uid !== user.user_uid)) + } catch (e) { + setError(e.message) + } + } + async function handleCreateUser(e) { e.preventDefault() if (!newUsername.trim() || !newPassword) { setCreateError('Username and password required'); return } @@ -148,6 +158,11 @@ export default function AdminView({ archives }) { + {u.user_uid !== currentUser?.user_uid && ( + + )} ))} diff --git a/frontend/src/components/SettingsView.jsx b/frontend/src/components/SettingsView.jsx index 400943d..560733c 100644 --- a/frontend/src/components/SettingsView.jsx +++ b/frontend/src/components/SettingsView.jsx @@ -3,12 +3,14 @@ import { AuthContext } from '../App.jsx' import { updateProfile, changePassword, patchMe, listTokens, createToken, deleteToken, + listSessions, revokeSession, revokeOtherSessions, getInstanceSettings, updateInstanceSettings, scanOrphanBlobs, deleteOrphanBlobs, listCookieRules, createCookieRule, updateCookieRule, deleteCookieRule, listRoles, fetchMe, getYtDlpStatus, updateYtDlp, } from '../api.js' +import { describeExpiry, formatTimestamp } from '../utils.js' const ROLE_ADMIN = 4 const ROLE_OWNER = 8 @@ -18,8 +20,8 @@ export default function SettingsView({ tab, onTabChange, archiveId }) { const isAdmin = currentUser && ((currentUser.role_bits & ROLE_ADMIN) !== 0) const isOwner = !!currentUser && (currentUser.role_bits & ROLE_OWNER) !== 0 - const tabs = ['profile', 'tokens', ...(isAdmin ? ['instance', 'cookies', 'extensions', 'storage'] : [])] - const tabLabels = { profile: 'Profile', tokens: 'API Tokens', instance: 'Instance', cookies: 'Cookies', extensions: 'Extensions', storage: 'Storage' } + const tabs = ['profile', 'tokens', 'sessions', ...(isAdmin ? ['instance', 'cookies', 'extensions', 'storage'] : [])] + const tabLabels = { profile: 'Profile', tokens: 'API Tokens', sessions: 'Sessions', instance: 'Instance', cookies: 'Cookies', extensions: 'Extensions', storage: 'Storage' } return (
@@ -36,6 +38,7 @@ export default function SettingsView({ tab, onTabChange, archiveId }) { {tab === 'profile' && } {tab === 'tokens' && } + {tab === 'sessions' && } {tab === 'instance' && isAdmin && ( <> @@ -165,6 +168,8 @@ function TokensTab() { const [loading, setLoading] = useState(true) const [error, setError] = useState(null) const [newName, setNewName] = useState('') + const [newScope, setNewScope] = useState('full') + const [newExpiry, setNewExpiry] = useState('') const [creating, setCreating] = useState(false) const [newToken, setNewToken] = useState(null) @@ -182,9 +187,14 @@ function TokensTab() { if (!newName.trim()) return setCreating(true) try { - const tok = await createToken(newName.trim()) + const tok = await createToken(newName.trim(), { + expiresInDays: newExpiry ? Number(newExpiry) : null, + scope: newScope, + }) setNewToken(tok) setNewName('') + setNewScope('full') + setNewExpiry('') refresh() } catch (err) { setError(err.message) @@ -216,6 +226,18 @@ function TokensTab() {
setNewName(e.target.value)} required /> + + @@ -226,20 +248,111 @@ function TokensTab() { ) : (
{tokens.length === 0 &&
No tokens yet.
} - {tokens.map(tok => ( + {tokens.map(tok => { + const expiry = describeExpiry(tok.expires_at) + return (
- {tok.name} +
+ {tok.name} + {tok.scope === 'read' && read-only} +
Created {tok.created_at.slice(0, 10)} {tok.last_used_at && ` \u00b7 Last used ${tok.last_used_at.slice(0, 10)}`}
+
+ {expiry.text} +
+ ) + })} +
+ )} + + + ) +} + +function SessionsTab() { + const [sessions, setSessions] = useState([]) + const [loading, setLoading] = useState(true) + const [error, setError] = useState(null) + const [busy, setBusy] = useState(false) + + const refresh = useCallback(async () => { + setLoading(true); setError(null) + try { setSessions(await listSessions()) } + catch (e) { setError(e.message) } + finally { setLoading(false) } + }, []) + + useEffect(() => { refresh() }, [refresh]) + + const others = sessions.filter(s => !s.current) + + async function handleRevoke(session) { + if (!window.confirm('Sign out this device?')) return + try { + await revokeSession(session.session_handle) + setSessions(ss => ss.filter(s => s.session_handle !== session.session_handle)) + } catch (e) { + setError(e.message) + } + } + + async function handleRevokeOthers() { + if (!window.confirm('Sign out all other devices? Your current session stays signed in.')) return + setBusy(true); setError(null) + try { + await revokeOtherSessions() + setSessions(ss => ss.filter(s => s.current)) + } catch (e) { + setError(e.message) + } finally { + setBusy(false) + } + } + + return ( +
+
+

Sessions

+

Devices currently signed in to your account.

+ + {error &&
{error}
} + {loading ? ( +
Loading…
+ ) : ( +
+ {sessions.length === 0 &&
No active sessions.
} + {sessions.map(s => ( +
+
+
+ {s.user_agent || 'Unknown device'} + {s.current && This device} +
+
Signed in {formatTimestamp(s.created_at)}
+
Last seen {formatTimestamp(s.last_seen_at)}
+
Expires {formatTimestamp(s.expires_at)}
+
+ {!s.current && ( + + )} +
))}
)} diff --git a/frontend/src/styles.css b/frontend/src/styles.css index 785719f..dd95407 100644 --- a/frontend/src/styles.css +++ b/frontend/src/styles.css @@ -2262,6 +2262,36 @@ select { .token-row-info strong { font-size: 14px; display: block; } .token-row-info .muted { font-size: 12px; margin-top: 2px; } .token-create-row { display: flex; gap: 8px; margin-bottom: 16px; } +.token-row-title { display: flex; align-items: center; gap: 8px; } +.token-badge, +.session-badge { + display: inline-block; + padding: 1px 7px; + border-radius: var(--r); + font-size: 11px; + font-weight: 600; + text-transform: uppercase; + letter-spacing: 0.04em; + border: 1px solid var(--line); + color: var(--muted); + background: var(--paper-2); +} +.session-badge { background: #d8eddf; color: #235c35; border-color: #b4d9be; } +.token-expiry { font-size: 12px; color: var(--muted); margin-top: 2px; } +.token-expiry--expired { color: var(--accent); } +.session-row { + display: flex; + align-items: center; + justify-content: space-between; + border: 1px solid var(--line); + background: var(--paper-3); + padding: 10px 12px; + border-radius: var(--r); + margin-bottom: 6px; +} +.session-row .muted { font-size: 12px; margin-top: 2px; } +.admin-action-btn--danger { color: var(--accent); border-color: var(--accent); } +.admin-action-btn--danger:hover { background: #f5ddd8; } /* ── Instance settings checkboxes ───────────────────────────────────────── */ .checkbox-row { diff --git a/frontend/src/utils.js b/frontend/src/utils.js index 6463665..f325dd5 100644 --- a/frontend/src/utils.js +++ b/frontend/src/utils.js @@ -33,6 +33,18 @@ export function formatTimestamp(value) { return `${d.getUTCFullYear()}-${pad(d.getUTCMonth() + 1)}-${pad(d.getUTCDate())} ${pad(d.getUTCHours())}:${pad(d.getUTCMinutes())}`; } +// Describes a token's expiry for display. `expiresAt` is an RFC 3339 string or +// null (never expires). Returns { expired, text } where text is the date-only +// UTC form, e.g. "Expires 2026-11-01" or "Expired 2026-10-01". +export function describeExpiry(expiresAt, now = new Date()) { + if (!expiresAt) return { expired: false, text: "Never expires" }; + const d = new Date(expiresAt); + if (isNaN(d)) return { expired: false, text: `Expires ${expiresAt}` }; + const date = d.toISOString().slice(0, 10); + const expired = d.getTime() <= now.getTime(); + return { expired, text: `${expired ? "Expired" : "Expires"} ${date}` }; +} + export const SOURCE_ICONS = { youtube: ``, youtube_music: ``, diff --git a/frontend/src/utils.test.js b/frontend/src/utils.test.js new file mode 100644 index 0000000..f5623ce --- /dev/null +++ b/frontend/src/utils.test.js @@ -0,0 +1,26 @@ +import { describe, expect, test } from 'bun:test' +import { describeExpiry } from './utils.js' + +const now = new Date('2026-10-09T00:00:00Z') + +describe('describeExpiry', () => { + test('null expiry means the token never expires', () => { + expect(describeExpiry(null, now)).toEqual({ expired: false, text: 'Never expires' }) + }) + + test('a future expiry shows the UTC date', () => { + expect(describeExpiry('2026-11-01T12:00:00Z', now)).toEqual({ expired: false, text: 'Expires 2026-11-01' }) + }) + + test('a past expiry is marked expired', () => { + expect(describeExpiry('2026-10-01T12:00:00Z', now)).toEqual({ expired: true, text: 'Expired 2026-10-01' }) + }) + + test('an expiry exactly at now counts as expired', () => { + expect(describeExpiry('2026-10-09T00:00:00Z', now).expired).toBe(true) + }) + + test('an unparseable value is shown verbatim and not marked expired', () => { + expect(describeExpiry('not-a-date', now)).toEqual({ expired: false, text: 'Expires not-a-date' }) + }) +})