mirror of
https://github.com/thegeneralist01/archivr
synced 2026-12-04 18:56:44 +01:00
feat(frontend): sessions tab, token scope and expiry, admin user delete
Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
094f9ceab1
commit
6be3fe33bc
7 changed files with 302 additions and 8 deletions
|
|
@ -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',
|
||||
|
|
|
|||
71
frontend/src/api.test.js
Normal file
71
frontend/src/api.test.js
Normal file
|
|
@ -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')
|
||||
})
|
||||
})
|
||||
|
|
@ -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 }) {
|
|||
<button className="admin-action-btn" onClick={() => handleToggleStatus(u)}>
|
||||
{u.status === 'active' ? 'Ban' : 'Unban'}
|
||||
</button>
|
||||
{u.user_uid !== currentUser?.user_uid && (
|
||||
<button className="admin-action-btn admin-action-btn--danger" onClick={() => handleDeleteUser(u)}>
|
||||
Delete
|
||||
</button>
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
|
|
|
|||
|
|
@ -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 (
|
||||
<section className="admin-view">
|
||||
|
|
@ -36,6 +38,7 @@ export default function SettingsView({ tab, onTabChange, archiveId }) {
|
|||
|
||||
{tab === 'profile' && <ProfileTab currentUser={currentUser} setCurrentUser={setCurrentUser} />}
|
||||
{tab === 'tokens' && <TokensTab />}
|
||||
{tab === 'sessions' && <SessionsTab />}
|
||||
{tab === 'instance' && isAdmin && (
|
||||
<>
|
||||
<InstanceTab isOwner={isOwner} setCurrentUser={setCurrentUser} />
|
||||
|
|
@ -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() {
|
|||
<form className="token-create-row" onSubmit={handleCreate}>
|
||||
<input className="field-input field-input--flex" placeholder="Token name"
|
||||
value={newName} onChange={e => setNewName(e.target.value)} required />
|
||||
<select className="field-input" aria-label="Token scope"
|
||||
value={newScope} onChange={e => setNewScope(e.target.value)}>
|
||||
<option value="full">Full access</option>
|
||||
<option value="read">Read-only</option>
|
||||
</select>
|
||||
<select className="field-input" aria-label="Token expiry"
|
||||
value={newExpiry} onChange={e => setNewExpiry(e.target.value)}>
|
||||
<option value="">Never</option>
|
||||
<option value="30">30 days</option>
|
||||
<option value="90">90 days</option>
|
||||
<option value="365">1 year</option>
|
||||
</select>
|
||||
<button className="btn-primary" type="submit" disabled={creating}>
|
||||
{creating ? 'Creating\u2026' : 'Create token'}
|
||||
</button>
|
||||
|
|
@ -226,20 +248,111 @@ function TokensTab() {
|
|||
) : (
|
||||
<div>
|
||||
{tokens.length === 0 && <div className="muted">No tokens yet.</div>}
|
||||
{tokens.map(tok => (
|
||||
{tokens.map(tok => {
|
||||
const expiry = describeExpiry(tok.expires_at)
|
||||
return (
|
||||
<div key={tok.token_uid} className="token-row">
|
||||
<div className="token-row-info">
|
||||
<strong>{tok.name}</strong>
|
||||
<div className="token-row-title">
|
||||
<strong>{tok.name}</strong>
|
||||
{tok.scope === 'read' && <span className="token-badge">read-only</span>}
|
||||
</div>
|
||||
<div className="muted">
|
||||
Created {tok.created_at.slice(0, 10)}
|
||||
{tok.last_used_at && ` \u00b7 Last used ${tok.last_used_at.slice(0, 10)}`}
|
||||
</div>
|
||||
<div className={`token-expiry${expiry.expired ? ' token-expiry--expired' : ''}`}>
|
||||
{expiry.text}
|
||||
</div>
|
||||
</div>
|
||||
<button className="btn-danger" style={{ fontSize: 12, padding: '4px 10px' }}
|
||||
onClick={() => handleDelete(tok.token_uid)}>
|
||||
Revoke
|
||||
</button>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
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 (
|
||||
<div style={{ maxWidth: 600 }}>
|
||||
<div className="form-section">
|
||||
<h2>Sessions</h2>
|
||||
<p className="muted">Devices currently signed in to your account.</p>
|
||||
<button className="btn-danger" type="button" style={{ fontSize: 12, padding: '4px 10px' }}
|
||||
disabled={busy || loading || others.length === 0}
|
||||
onClick={handleRevokeOthers}>
|
||||
Sign out other devices
|
||||
</button>
|
||||
{error && <div className="form-msg form-msg--err">{error}</div>}
|
||||
{loading ? (
|
||||
<div className="muted">Loading…</div>
|
||||
) : (
|
||||
<div>
|
||||
{sessions.length === 0 && <div className="muted">No active sessions.</div>}
|
||||
{sessions.map(s => (
|
||||
<div key={s.session_handle} className="session-row">
|
||||
<div className="token-row-info">
|
||||
<div className="token-row-title">
|
||||
<strong>{s.user_agent || 'Unknown device'}</strong>
|
||||
{s.current && <span className="session-badge">This device</span>}
|
||||
</div>
|
||||
<div className="muted">Signed in {formatTimestamp(s.created_at)}</div>
|
||||
<div className="muted">Last seen {formatTimestamp(s.last_seen_at)}</div>
|
||||
<div className="muted">Expires {formatTimestamp(s.expires_at)}</div>
|
||||
</div>
|
||||
{!s.current && (
|
||||
<button className="btn-danger" style={{ fontSize: 12, padding: '4px 10px' }}
|
||||
onClick={() => handleRevoke(s)}>
|
||||
Revoke
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
|
|
|||
|
|
@ -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 {
|
||||
|
|
|
|||
|
|
@ -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: `<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path fill="#FF0000" d="M23.5 6.2a3 3 0 0 0-2.1-2.1C19.5 3.6 12 3.6 12 3.6s-7.5 0-9.4.5A3 3 0 0 0 .5 6.2C0 8.1 0 12 0 12s0 3.9.5 5.8a3 3 0 0 0 2.1 2.1c1.9.5 9.4.5 9.4.5s7.5 0 9.4-.5a3 3 0 0 0 2.1-2.1C24 15.9 24 12 24 12s0-3.9-.5-5.8z"/><polygon fill="#fff" points="9.6,15.6 15.8,12 9.6,8.4"/></svg>`,
|
||||
youtube_music: `<svg viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><circle cx="12" cy="12" r="12" fill="#FF0000"/><polygon fill="#fff" points="9.6,15.6 15.8,12 9.6,8.4"/></svg>`,
|
||||
|
|
|
|||
26
frontend/src/utils.test.js
Normal file
26
frontend/src/utils.test.js
Normal file
|
|
@ -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' })
|
||||
})
|
||||
})
|
||||
Loading…
Add table
Add a link
Reference in a new issue