Client half of #370. Lists every device signed in to your account, with a per-row sign-out and a "sign out all other devices" action. The card does one thing the API alone doesn't: it says "Address changed" when created_ip and last_ip differ, rather than printing two addresses and leaving you to compare them. That mismatch — same device string, different origin — is the shape of a stolen token, and it's the reason IP capture was worth a migration. Making the operator spot it by eye would have wasted the data. Placed with Password and API Token rather than at the bottom of the page: those three are the account-security group, and this is the one that tells you the other two need attention. Details worth naming: - The current session gets a "This device" badge and NO sign-out button — offering one would log you out of the page you're standing on. The server already excludes it from logout-others; this makes that visible. - Sign-out-all-others is a two-step confirm and states the count, so the button can't be a surprise. - A 404 on revoke reloads instead of erroring. It means the session is already gone — revoked elsewhere, or expired — so the list was simply stale and showing the truth is the right response. The code is `session_not_found`, not `not_found`: apierror.NotFound(what) prefixes it. - Empty and error states both handled (rule #24); the empty case is practically unreachable since listing requires an authenticated request, and is handled rather than assumed. - User-agent parsing is deliberately coarse. A real UA parser is a dependency and a maintenance burden for a string whose only job is "do you recognise this?" — the addresses carry the actual signal. Tests cover the parts that would be quiet if broken: the current-session badge suppressing its own sign-out button, the address-changed warning appearing and NOT appearing, the two-step confirm not firing on first click, and the load-failure retry. Android parity is a separate decision, not assumed.
This commit is contained in:
@@ -62,3 +62,33 @@ export async function regenerateAPIToken(): Promise<APITokenResponse> {
|
||||
export async function putMyTimezone(timezone: string): Promise<void> {
|
||||
await api.put<void>('/api/me/timezone', { timezone });
|
||||
}
|
||||
|
||||
// Active sessions (#370) ---------------------------------------------------
|
||||
|
||||
// created_ip is frozen at issue time; last_ip moves with the session. The
|
||||
// pair is the signal — the same device string arriving from an address you
|
||||
// don't recognise is what a stolen token looks like from the inside.
|
||||
export type ActiveSession = {
|
||||
id: string;
|
||||
user_agent: string;
|
||||
created_ip: string;
|
||||
last_ip: string;
|
||||
created_at: string;
|
||||
last_seen_at: string;
|
||||
current: boolean;
|
||||
};
|
||||
|
||||
export async function listSessions(): Promise<ActiveSession[]> {
|
||||
return api.get<ActiveSession[]>('/api/me/sessions');
|
||||
}
|
||||
|
||||
export async function revokeSession(id: string): Promise<void> {
|
||||
await api.del(`/api/me/sessions/${id}`);
|
||||
}
|
||||
|
||||
// Returns how many were ended. The server excludes the caller's own session,
|
||||
// so this never signs you out of the page you pressed it on.
|
||||
export async function revokeOtherSessions(): Promise<number> {
|
||||
const body = await api.post<{ revoked: number }>('/api/me/sessions/logout-others', {});
|
||||
return body.revoked;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,227 @@
|
||||
<script lang="ts">
|
||||
import { onMount } from 'svelte';
|
||||
import { MonitorSmartphone, TriangleAlert } from 'lucide-svelte';
|
||||
import {
|
||||
listSessions,
|
||||
revokeSession,
|
||||
revokeOtherSessions,
|
||||
type ActiveSession
|
||||
} from '$lib/api/me';
|
||||
import { errCode } from '$lib/api/errors';
|
||||
import { pushToast } from '$lib/stores/toast.svelte';
|
||||
|
||||
// Self-contained: nothing else in the app reads this data, so it holds its
|
||||
// own state and reloads explicitly rather than joining the query cache.
|
||||
|
||||
let sessions = $state<ActiveSession[] | null>(null);
|
||||
let loadError = $state(false);
|
||||
let busy = $state(false);
|
||||
let confirmingLogoutOthers = $state(false);
|
||||
|
||||
const others = $derived((sessions ?? []).filter((s) => !s.current).length);
|
||||
|
||||
async function load() {
|
||||
try {
|
||||
sessions = await listSessions();
|
||||
loadError = false;
|
||||
} catch {
|
||||
loadError = true;
|
||||
}
|
||||
}
|
||||
|
||||
onMount(load);
|
||||
|
||||
async function onRevoke(s: ActiveSession) {
|
||||
busy = true;
|
||||
try {
|
||||
await revokeSession(s.id);
|
||||
pushToast('Signed that device out.');
|
||||
await load();
|
||||
} catch (e: unknown) {
|
||||
// Already gone — revoked from another device, or expired. Reloading
|
||||
// shows the truth, so it isn't worth an error. The code is
|
||||
// `session_not_found`: apierror.NotFound("session") prefixes it.
|
||||
if (errCode(e) === 'session_not_found') {
|
||||
await load();
|
||||
} else {
|
||||
pushToast("Couldn't sign that device out.", 'error');
|
||||
}
|
||||
} finally {
|
||||
busy = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function onLogoutOthers() {
|
||||
busy = true;
|
||||
try {
|
||||
const n = await revokeOtherSessions();
|
||||
pushToast(n === 1 ? 'Signed out 1 other device.' : `Signed out ${n} other devices.`);
|
||||
confirmingLogoutOthers = false;
|
||||
await load();
|
||||
} catch {
|
||||
pushToast("Couldn't sign the other devices out.", 'error');
|
||||
} finally {
|
||||
busy = false;
|
||||
}
|
||||
}
|
||||
|
||||
// Deliberately coarse. A full UA parser would be a dependency and a
|
||||
// maintenance burden for a string whose only job is "do you recognise
|
||||
// this?" — the IP columns carry the actual signal.
|
||||
function describeAgent(ua: string): string {
|
||||
if (!ua) return 'Unknown device';
|
||||
if (/Minstrel/i.test(ua)) return 'Minstrel for Android';
|
||||
if (/Android/i.test(ua)) return 'Android browser';
|
||||
if (/iPhone|iPad|iOS/i.test(ua)) return 'iOS browser';
|
||||
const browser = /Edg\//.test(ua)
|
||||
? 'Edge'
|
||||
: /Firefox\//.test(ua)
|
||||
? 'Firefox'
|
||||
: /Chrome\//.test(ua)
|
||||
? 'Chrome'
|
||||
: /Safari\//.test(ua)
|
||||
? 'Safari'
|
||||
: '';
|
||||
const os = /Windows/.test(ua)
|
||||
? 'Windows'
|
||||
: /Mac OS X/.test(ua)
|
||||
? 'macOS'
|
||||
: /Linux/.test(ua)
|
||||
? 'Linux'
|
||||
: '';
|
||||
if (browser && os) return `${browser} on ${os}`;
|
||||
if (browser) return browser;
|
||||
return ua.length > 40 ? `${ua.slice(0, 40)}…` : ua;
|
||||
}
|
||||
|
||||
function when(iso: string): string {
|
||||
const then = new Date(iso).getTime();
|
||||
if (Number.isNaN(then)) return 'unknown';
|
||||
const mins = Math.round((Date.now() - then) / 60000);
|
||||
if (mins < 1) return 'just now';
|
||||
if (mins < 60) return `${mins} min ago`;
|
||||
const hours = Math.round(mins / 60);
|
||||
if (hours < 24) return hours === 1 ? '1 hour ago' : `${hours} hours ago`;
|
||||
const days = Math.round(hours / 24);
|
||||
if (days < 30) return days === 1 ? 'yesterday' : `${days} days ago`;
|
||||
return new Date(iso).toLocaleDateString();
|
||||
}
|
||||
|
||||
// The reason IP is stored at all. Rather than making someone eyeball two
|
||||
// addresses per row, say plainly when a session is being used from
|
||||
// somewhere other than where it was created.
|
||||
function hasMoved(s: ActiveSession): boolean {
|
||||
return !!s.created_ip && !!s.last_ip && s.created_ip !== s.last_ip;
|
||||
}
|
||||
|
||||
function addr(ip: string): string {
|
||||
return ip || 'unknown';
|
||||
}
|
||||
</script>
|
||||
|
||||
<section class="space-y-3 rounded border border-border bg-surface p-4">
|
||||
<h2 class="text-lg font-semibold">Active sessions</h2>
|
||||
<p class="text-sm text-text-secondary">
|
||||
Every device signed in to your account. If you see one you don't recognise — especially
|
||||
one marked as having moved — sign it out and change your password.
|
||||
</p>
|
||||
|
||||
{#if loadError}
|
||||
<p class="text-sm text-destructive">
|
||||
Couldn't load your sessions.
|
||||
<button type="button" class="underline hover:no-underline" onclick={load}>Try again</button>
|
||||
</p>
|
||||
{:else if sessions === null}
|
||||
<p class="text-sm text-text-secondary">Loading…</p>
|
||||
{:else if sessions.length === 0}
|
||||
<!-- Practically unreachable: listing requires an authenticated request,
|
||||
which means at least one session exists. Handled rather than assumed. -->
|
||||
<p class="text-sm text-text-secondary">No active sessions.</p>
|
||||
{:else}
|
||||
<ul class="divide-y divide-border">
|
||||
{#each sessions as s (s.id)}
|
||||
<li class="flex items-start gap-3 py-3">
|
||||
<MonitorSmartphone
|
||||
size={18}
|
||||
class="mt-0.5 flex-shrink-0 text-text-secondary"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<div class="min-w-0 flex-1">
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<span class="font-medium text-text-primary">{describeAgent(s.user_agent)}</span>
|
||||
{#if s.current}
|
||||
<span class="rounded bg-surface-hover px-1.5 py-0.5 text-xs text-text-secondary">
|
||||
This device
|
||||
</span>
|
||||
{/if}
|
||||
{#if hasMoved(s)}
|
||||
<span
|
||||
class="inline-flex items-center gap-1 rounded px-1.5 py-0.5 text-xs text-destructive"
|
||||
>
|
||||
<TriangleAlert size={12} aria-hidden="true" />
|
||||
Address changed
|
||||
</span>
|
||||
{/if}
|
||||
</div>
|
||||
<div class="text-xs text-text-secondary">
|
||||
Last seen {when(s.last_seen_at)} from <span class="font-mono">{addr(s.last_ip)}</span>
|
||||
</div>
|
||||
<div class="text-xs text-text-secondary">
|
||||
Signed in {when(s.created_at)} from <span class="font-mono">{addr(s.created_ip)}</span>
|
||||
</div>
|
||||
</div>
|
||||
{#if !s.current}
|
||||
<button
|
||||
type="button"
|
||||
class="flex-shrink-0 rounded border border-border px-2 py-1 text-sm
|
||||
hover:bg-surface-hover focus-visible:ring-2 focus-visible:ring-accent
|
||||
disabled:opacity-50"
|
||||
disabled={busy}
|
||||
onclick={() => onRevoke(s)}
|
||||
>
|
||||
Sign out
|
||||
</button>
|
||||
{/if}
|
||||
</li>
|
||||
{/each}
|
||||
</ul>
|
||||
|
||||
{#if others > 0}
|
||||
{#if confirmingLogoutOthers}
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<span class="text-sm text-text-secondary">
|
||||
Sign out {others === 1 ? '1 other device' : `${others} other devices`}? You'll stay
|
||||
signed in here.
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded bg-destructive px-3 py-1 text-sm text-white
|
||||
focus-visible:ring-2 focus-visible:ring-accent disabled:opacity-50"
|
||||
disabled={busy}
|
||||
onclick={onLogoutOthers}
|
||||
>
|
||||
Sign them out
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="rounded border border-border px-3 py-1 text-sm hover:bg-surface-hover
|
||||
focus-visible:ring-2 focus-visible:ring-accent"
|
||||
onclick={() => (confirmingLogoutOthers = false)}
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
</div>
|
||||
{:else}
|
||||
<button
|
||||
type="button"
|
||||
class="rounded border border-border px-3 py-1 text-sm hover:bg-surface-hover
|
||||
focus-visible:ring-2 focus-visible:ring-accent disabled:opacity-50"
|
||||
disabled={busy}
|
||||
onclick={() => (confirmingLogoutOthers = true)}
|
||||
>
|
||||
Sign out all other devices
|
||||
</button>
|
||||
{/if}
|
||||
{/if}
|
||||
{/if}
|
||||
</section>
|
||||
@@ -0,0 +1,126 @@
|
||||
import { describe, expect, test, vi, beforeEach } from 'vitest';
|
||||
import { render, screen, fireEvent, waitFor } from '@testing-library/svelte';
|
||||
import ActiveSessions from './ActiveSessions.svelte';
|
||||
|
||||
const listSessions = vi.fn();
|
||||
const revokeSession = vi.fn();
|
||||
const revokeOtherSessions = vi.fn();
|
||||
|
||||
vi.mock('$lib/api/me', () => ({
|
||||
listSessions: (...a: unknown[]) => listSessions(...a),
|
||||
revokeSession: (...a: unknown[]) => revokeSession(...a),
|
||||
revokeOtherSessions: (...a: unknown[]) => revokeOtherSessions(...a)
|
||||
}));
|
||||
|
||||
vi.mock('$lib/stores/toast.svelte', () => ({ pushToast: vi.fn() }));
|
||||
|
||||
type Row = {
|
||||
id: string;
|
||||
user_agent: string;
|
||||
created_ip: string;
|
||||
last_ip: string;
|
||||
created_at: string;
|
||||
last_seen_at: string;
|
||||
current: boolean;
|
||||
};
|
||||
|
||||
function row(over: Partial<Row> = {}): Row {
|
||||
return {
|
||||
id: 'a1',
|
||||
user_agent: 'Mozilla/5.0 (X11; Linux x86_64) Chrome/120.0',
|
||||
created_ip: '203.0.113.1',
|
||||
last_ip: '203.0.113.1',
|
||||
created_at: new Date().toISOString(),
|
||||
last_seen_at: new Date().toISOString(),
|
||||
current: false,
|
||||
...over
|
||||
};
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
describe('ActiveSessions', () => {
|
||||
test('flags the current session and gives it no sign-out button', async () => {
|
||||
listSessions.mockResolvedValue([
|
||||
row({ id: 'cur', current: true }),
|
||||
row({ id: 'other', current: false })
|
||||
]);
|
||||
render(ActiveSessions);
|
||||
|
||||
await screen.findByText('This device');
|
||||
// One sign-out button, for the non-current row. Offering one on the
|
||||
// current session would sign the user out of the page they're using.
|
||||
await waitFor(() => {
|
||||
expect(screen.getAllByRole('button', { name: 'Sign out' })).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
// The whole reason IP is stored: surfacing the mismatch rather than making
|
||||
// someone compare two addresses by eye.
|
||||
test('warns when a session is used from a different address than it was created', async () => {
|
||||
listSessions.mockResolvedValue([
|
||||
row({ id: 'moved', created_ip: '203.0.113.1', last_ip: '198.51.100.9' })
|
||||
]);
|
||||
render(ActiveSessions);
|
||||
|
||||
expect(await screen.findByText('Address changed')).toBeTruthy();
|
||||
});
|
||||
|
||||
test('does not warn when the address has not changed', async () => {
|
||||
listSessions.mockResolvedValue([
|
||||
row({ created_ip: '203.0.113.1', last_ip: '203.0.113.1' })
|
||||
]);
|
||||
render(ActiveSessions);
|
||||
|
||||
await screen.findByText(/Signed in/);
|
||||
expect(screen.queryByText('Address changed')).toBeNull();
|
||||
});
|
||||
|
||||
test('sign-out-all-others confirms before acting', async () => {
|
||||
listSessions.mockResolvedValue([
|
||||
row({ id: 'cur', current: true }),
|
||||
row({ id: 'o1' }),
|
||||
row({ id: 'o2' })
|
||||
]);
|
||||
revokeOtherSessions.mockResolvedValue(2);
|
||||
render(ActiveSessions);
|
||||
|
||||
const start = await screen.findByRole('button', { name: 'Sign out all other devices' });
|
||||
await fireEvent.click(start);
|
||||
// First click only arms the action.
|
||||
expect(revokeOtherSessions).not.toHaveBeenCalled();
|
||||
expect(screen.getByText(/Sign out 2 other devices\?/)).toBeTruthy();
|
||||
|
||||
await fireEvent.click(screen.getByRole('button', { name: 'Sign them out' }));
|
||||
await waitFor(() => expect(revokeOtherSessions).toHaveBeenCalledTimes(1));
|
||||
});
|
||||
|
||||
test('offers no bulk action when there are no other devices', async () => {
|
||||
listSessions.mockResolvedValue([row({ id: 'cur', current: true })]);
|
||||
render(ActiveSessions);
|
||||
|
||||
await screen.findByText('This device');
|
||||
expect(screen.queryByRole('button', { name: 'Sign out all other devices' })).toBeNull();
|
||||
});
|
||||
|
||||
test('surfaces a retry when loading fails', async () => {
|
||||
listSessions.mockRejectedValue(new Error('boom'));
|
||||
render(ActiveSessions);
|
||||
|
||||
const retry = await screen.findByRole('button', { name: 'Try again' });
|
||||
listSessions.mockResolvedValue([row({ id: 'cur', current: true })]);
|
||||
await fireEvent.click(retry);
|
||||
await screen.findByText('This device');
|
||||
});
|
||||
|
||||
test('renders unknown for a missing address rather than an empty cell', async () => {
|
||||
listSessions.mockResolvedValue([row({ created_ip: '', last_ip: '' })]);
|
||||
render(ActiveSessions);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getAllByText('unknown').length).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -26,6 +26,7 @@
|
||||
import { pushToast } from '$lib/stores/toast.svelte';
|
||||
import MobileAppDownload from '$lib/components/MobileAppDownload.svelte';
|
||||
import ServerVersion from '$lib/components/ServerVersion.svelte';
|
||||
import ActiveSessions from '$lib/components/ActiveSessions.svelte';
|
||||
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
@@ -526,6 +527,11 @@
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- Sits with Password and API Token rather than near the bottom: these
|
||||
three are the account-security group, and this is the one that tells
|
||||
you the other two need attention. -->
|
||||
<ActiveSessions />
|
||||
|
||||
<section class="space-y-3 rounded border border-border bg-surface p-4">
|
||||
<h2 class="text-lg font-semibold">Library</h2>
|
||||
<ul class="space-y-2 text-sm">
|
||||
|
||||
Reference in New Issue
Block a user