Skip to content

armgit / kwant

Public Imported from GitHub
0

Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.

Sign in from another device: waiting code, approve prompt, signed-in devices

Pixel (kwant bot)df12ff54f8b9
diff --git a/frontend/src/auth.ts b/frontend/src/auth.ts
index bbd0e226..e3c40099 100644
--- a/frontend/src/auth.ts
+++ b/frontend/src/auth.ts
@@ -59,6 +59,8 @@ export interface AuthStatus {
/** Person-only actions need the token even where the rest of the API doesn't (newer servers). */
person_auth_required?: boolean;
person_authenticated?: boolean;
+ /** This server can let a new browser in from a signed-in device (newer servers). */
+ device_login?: boolean;
}
/** Asks for the token for a person-only action, as if one had answered 401. */
diff --git a/frontend/src/components/AuthGate.tsx b/frontend/src/components/AuthGate.tsx
index d879f3d8..a1633826 100644
--- a/frontend/src/components/AuthGate.tsx
+++ b/frontend/src/components/AuthGate.tsx
@@ -1,6 +1,7 @@
import React, { createContext, useCallback, useContext, useEffect, useRef, useState } from 'react';
import { Check, ChevronRight, Copy, KeyRound, Loader2, RefreshCw, Terminal, X } from 'lucide-react';
import { ModernAvatar } from './ModernAvatar';
+import { DeviceRequestPrompt, DeviceWait } from './DeviceSignIn';
import {
PERSON_PROMPT_CLOSED_EVENT,
PERSON_SIGNED_IN_EVENT,
@@ -18,17 +19,19 @@ import {
interface AuthContextValue {
/** True when this browser needs the API token (Docker, a VPS reached directly). */
authRequired: boolean;
+ /** This server lets new browsers in from a signed-in one, and lists signed-in browsers. */
+ deviceLogin: boolean;
signOut: () => Promise<void>;
}
-const AuthContext = createContext<AuthContextValue>({ authRequired: false, signOut: async () => undefined });
+const AuthContext = createContext<AuthContextValue>({ authRequired: false, deviceLogin: false, signOut: async () => undefined });
export const useAuth = () => useContext(AuthContext);
type GateState =
| { kind: 'checking' }
- | { kind: 'ready'; authRequired: boolean }
- | { kind: 'locked'; notice: string | null }
+ | { kind: 'ready'; authRequired: boolean; deviceLogin: boolean }
+ | { kind: 'locked'; notice: string | null; deviceLogin: boolean }
| { kind: 'offline'; message: string };
installUnauthorizedListener();
@@ -58,7 +61,12 @@ export const AuthGate: React.FC<{ children: React.ReactNode }> = ({ children })
checking.current = true;
try {
const s = await fetchAuthStatus();
- setState(s.auth_required && !s.authenticated ? { kind: 'locked', notice } : { kind: 'ready', authRequired: s.auth_required });
+ const deviceLogin = s.device_login === true;
+ setState(
+ s.auth_required && !s.authenticated
+ ? { kind: 'locked', notice, deviceLogin }
+ : { kind: 'ready', authRequired: s.auth_required, deviceLogin },
+ );
} catch (e) {
setState({ kind: 'offline', message: offlineMessage(e, navigator.onLine) });
} finally {
@@ -93,16 +101,19 @@ export const AuthGate: React.FC<{ children: React.ReactNode }> = ({ children })
try {
await endSession();
} finally {
- setState({ kind: 'locked', notice: 'Signed out.' });
+ setState((prev) => ({ kind: 'locked', notice: 'Signed out.', deviceLogin: prev.kind === 'ready' && prev.deviceLogin }));
}
}, []);
if (state.kind === 'ready') {
return (
- <AuthContext.Provider value={{ authRequired: state.authRequired, signOut }}>
+ <AuthContext.Provider value={{ authRequired: state.authRequired, deviceLogin: state.deviceLogin, signOut }}>
{children}
+ {/* Only where browsers sign in: a Mac in local mode has no other devices to let in */}
+ {state.authRequired && state.deviceLogin && <DeviceRequestPrompt />}
{personPrompt && (
<PersonTokenDialog
+ deviceLogin={state.deviceLogin}
onClose={() => {
setPersonPrompt(false);
window.dispatchEvent(new Event(PERSON_PROMPT_CLOSED_EVENT));
@@ -147,14 +158,18 @@ export const AuthGate: React.FC<{ children: React.ReactNode }> = ({ children })
</button>
</div>
)}
- {state.kind === 'locked' && <TokenForm notice={state.notice} onSignedIn={() => check()} />}
+ {state.kind === 'locked' && <TokenForm notice={state.notice} deviceLogin={state.deviceLogin} onSignedIn={() => check()} />}
</div>
</div>
);
};
/** The token screen as a dialog, for an action only the person may take. The app stays open under it. */
-export const PersonTokenDialog: React.FC<{ onClose: () => void; onSignedIn: () => void }> = ({ onClose, onSignedIn }) => {
+export const PersonTokenDialog: React.FC<{ onClose: () => void; onSignedIn: () => void; deviceLogin?: boolean }> = ({
+ onClose,
+ onSignedIn,
+ deviceLogin = false,
+}) => {
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
if (e.key === 'Escape') onClose();
@@ -179,7 +194,7 @@ export const PersonTokenDialog: React.FC<{ onClose: () => void; onSignedIn: () =
>
<X size={14} />
</button>
- <TokenForm notice={null} onSignedIn={onSignedIn} personOnly onCancel={onClose} />
+ <TokenForm notice={null} onSignedIn={onSignedIn} personOnly onCancel={onClose} deviceLogin={deviceLogin} />
</div>
</div>
);
@@ -309,12 +324,14 @@ export const WRONG_TOKEN = "That token isn't right. It has to come from the mach
/** Only shown with the wrong-token error, not up front. */
export const OWN_TOKEN_HINT = "Each install has its own token, so one copied from another computer won't work here.";
-export const TokenForm: React.FC<{ notice: string | null; onSignedIn: () => void; personOnly?: boolean; onCancel?: () => void }> = ({
- notice,
- onSignedIn,
- personOnly = false,
- onCancel,
-}) => {
+export const TokenForm: React.FC<{
+ notice: string | null;
+ onSignedIn: () => void;
+ personOnly?: boolean;
+ onCancel?: () => void;
+ /** The server can let this browser in from a signed-in device: that comes first. */
+ deviceLogin?: boolean;
+}> = ({ notice, onSignedIn, personOnly = false, onCancel, deviceLogin = false }) => {
const [token, setToken] = useState('');
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
@@ -369,10 +386,11 @@ export const TokenForm: React.FC<{ notice: string | null; onSignedIn: () => void
{notice}
</p>
)}
+ {deviceLogin && <DeviceWait onSignedIn={onSignedIn} />}
<div className="space-y-1.5">
<p className="text-xs text-zinc-400 leading-relaxed">
- Open the one-time sign-in link kwant bots printed when it started, or scan its QR code with your phone. Used or lost it? Make a new one on the
- machine running kwant bots:
+ {deviceLogin ? 'Or open' : 'Open'} the one-time sign-in link kwant bots printed when it started, or scan its QR code with your phone. Used or lost
+ it? Make a new one on the machine running kwant bots:
</p>
<Command>{docker ? DOCKER_LINK_COMMAND : LINK_COMMAND}</Command>
</div>
diff --git a/frontend/src/components/DeviceSignIn.tsx b/frontend/src/components/DeviceSignIn.tsx
new file mode 100644
index 00000000..033ece9b
--- /dev/null
+++ b/frontend/src/components/DeviceSignIn.tsx
@@ -0,0 +1,439 @@
+import React, { useCallback, useEffect, useRef, useState } from 'react';
+import { AlertTriangle, Loader2, MonitorSmartphone, RefreshCw, ShieldCheck, X } from 'lucide-react';
+import {
+ type DeviceRequest,
+ type PendingDevice,
+ type SignedInSession,
+ ago,
+ countdown,
+ decideDeviceRequest,
+ listDeviceRequests,
+ listSessions,
+ pollDeviceRequest,
+ revokeSession,
+ startDeviceRequest,
+ viaLabel,
+} from '../deviceSignIn';
+
+// ---------------------------------------------------------------- the new browser: show a code, wait
+
+export type WaitState =
+ | { kind: 'idle' }
+ | { kind: 'starting' }
+ | { kind: 'waiting'; request: DeviceRequest; expiresAt: number }
+ | { kind: 'approved' }
+ | { kind: 'denied' }
+ | { kind: 'expired' }
+ | { kind: 'too_many'; retryAfter: number }
+ | { kind: 'error'; message: string };
+
+const primary =
+ 'w-full flex items-center justify-center gap-1.5 min-h-[44px] px-4 rounded-lg text-xs font-medium text-white bg-sky-600 hover:bg-sky-500 transition-colors disabled:opacity-50';
+const secondary =
+ 'flex items-center justify-center gap-1.5 min-h-[44px] px-4 rounded-lg text-xs font-medium text-zinc-200 bg-zinc-800 hover:bg-zinc-700 border border-zinc-700 transition-colors';
+
+/** What the "Sign in from another device" part of the card shows in each state. Exported for tests. */
+export const DeviceWaitView: React.FC<{ state: WaitState; now?: number; onStart: () => void; onCancel: () => void }> = ({
+ state,
+ now = Date.now(),
+ onStart,
+ onCancel,
+}) => {
+ if (state.kind === 'waiting' || state.kind === 'approved') {
+ const code = state.kind === 'waiting' ? state.request.user_code : null;
+ return (
+ <div className="space-y-3 rounded-xl border border-sky-500/30 bg-sky-500/5 p-4" role="status" aria-live="polite">
+ {code ? (
+ <>
+ <p className="text-xs text-zinc-300 leading-relaxed">
+ On a phone or computer where you’re already signed in to kwant bots, open it and approve this code:
+ </p>
+ <p className="text-center font-mono text-2xl font-semibold tracking-[0.15em] text-zinc-50 select-all" aria-label={`Code ${code.split('').join(' ')}`}>
+ {code}
+ </p>
+ <p className="flex items-center justify-center gap-2 text-[11px] text-zinc-400">
+ <Loader2 size={12} className="animate-spin motion-reduce:animate-none" aria-hidden="true" />
+ Waiting for approval · {state.kind === 'waiting' ? countdown(state.expiresAt, now) : ''} left
+ </p>
+ <button type="button" onClick={onCancel} className={`${secondary} w-full`}>
+ Cancel
+ </button>
+ </>
+ ) : (
+ <p className="flex items-center justify-center gap-2 text-xs text-emerald-300">
+ <ShieldCheck size={14} aria-hidden="true" /> Approved. Signing you in…
+ </p>
+ )}
+ </div>
+ );
+ }
+ const problem =
+ state.kind === 'denied'
+ ? 'The request was denied on your other device. If that wasn’t you, nothing happened: this browser is still signed out.'
+ : state.kind === 'expired'
+ ? 'The code expired before it was approved. Codes work for 10 minutes.'
+ : state.kind === 'too_many'
+ ? `Too many sign-in requests right now. Try again in ${Math.max(1, Math.ceil(state.retryAfter / 60))} min.`
+ : state.kind === 'error'
+ ? state.message
+ : null;
+ return (
+ <div className="space-y-2">
+ {problem && (
+ <p className="flex items-start gap-1.5 text-xs text-rose-300 leading-relaxed" role="alert">
+ <AlertTriangle size={13} className="shrink-0 mt-0.5" aria-hidden="true" /> {problem}
+ </p>
+ )}
+ <button type="button" onClick={onStart} disabled={state.kind === 'starting'} className={primary}>
+ {state.kind === 'starting' ? (
+ <Loader2 size={14} className="animate-spin motion-reduce:animate-none" aria-hidden="true" />
+ ) : problem ? (
+ <RefreshCw size={14} aria-hidden="true" />
+ ) : (
+ <MonitorSmartphone size={14} aria-hidden="true" />
+ )}
+ {problem ? 'Get a new code' : 'Sign in from another device'}
+ </button>
+ </div>
+ );
+};
+
+/** "Sign in from another device": asks for a code, waits for approval and signs in by itself. */
+export const DeviceWait: React.FC<{ onSignedIn: () => void }> = ({ onSignedIn }) => {
+ const [state, setState] = useState<WaitState>({ kind: 'idle' });
+ const [now, setNow] = useState(Date.now());
+ // Bumped to stop the current poll loop (cancel, unmount, a new code)
+ const run = useRef(0);
+
+ useEffect(() => () => void (run.current += 1), []);
+
+ const start = useCallback(async () => {
+ const mine = ++run.current;
+ setState({ kind: 'starting' });
+ try {
+ const started = await startDeviceRequest();
+ if (mine !== run.current) return;
+ if (started.kind === 'too_many') {
+ setState({ kind: 'too_many', retryAfter: started.retryAfter });
+ return;
+ }
+ const { request } = started;
+ const expiresAt = Date.now() + request.expires_in * 1000;
+ setState({ kind: 'waiting', request, expiresAt });
+ const every = Math.max(1, request.interval) * 1000;
+ let failures = 0;
+ while (mine === run.current) {
+ await new Promise((r) => setTimeout(r, every));
+ if (mine !== run.current) return;
+ setNow(Date.now());
+ let result;
+ try {
+ result = await pollDeviceRequest(request.device_code);
+ failures = 0;
+ } catch {
+ // A blip (phone switching networks): keep waiting, give up after a minute of failures
+ if (++failures * every >= 60_000) {
+ setState({ kind: 'error', message: 'Lost the connection to the server while waiting. Get a new code to try again.' });
+ return;
+ }
+ continue;
+ }
+ if (mine !== run.current) return;
+ if (result === 'approved') {
+ setState({ kind: 'approved' });
+ onSignedIn();
+ return;
+ }
+ if (result === 'denied' || result === 'expired') {
+ setState({ kind: result });
+ return;
+ }
+ if (Date.now() >= expiresAt) {
+ setState({ kind: 'expired' });
+ return;
+ }
+ }
+ } catch (e) {
+ if (mine === run.current)
+ setState({ kind: 'error', message: e instanceof Error && e.message !== 'Failed to fetch' ? e.message : 'Could not reach the server.' });
+ }
+ }, [onSignedIn]);
+
+ // The countdown ticks between polls too
+ useEffect(() => {
+ if (state.kind !== 'waiting') return;
+ const t = setInterval(() => setNow(Date.now()), 1000);
+ return () => clearInterval(t);
+ }, [state.kind]);
+
+ return (
+ <DeviceWaitView
+ state={state}
+ now={now}
+ onStart={start}
+ onCancel={() => {
+ run.current += 1;
+ setState({ kind: 'idle' });
+ }}
+ />
+ );
+};
+
+// ---------------------------------------------------------------- a signed-in device: approve or deny
+
+/** The approval card for one waiting device. Exported for tests. */
+export const DeviceRequestCard: React.FC<{
+ request: PendingDevice;
+ more: number;
+ busy: 'approve' | 'deny' | null;
+ error: string | null;
+ now?: number;
+ onApprove: () => void;
+ onDeny: () => void;
+ onLater: () => void;
+}> = ({ request, more, busy, error, now = Date.now(), onApprove, onDeny, onLater }) => {
+ const [matches, setMatches] = useState(false);
+ useEffect(() => setMatches(false), [request.user_code]);
+ return (
+ <div className="fixed inset-0 z-[90] flex items-center justify-center bg-black/70 p-4 font-sans">
+ <div
+ role="alertdialog"
+ aria-modal="true"
+ aria-labelledby="kwnt-device-request-title"
+ aria-describedby="kwnt-device-request-warning"
+ className="relative w-full max-w-sm bg-zinc-900 border border-zinc-800 rounded-2xl p-5 shadow-2xl text-zinc-100 space-y-4"
+ >
+ <button
+ type="button"
+ onClick={onLater}
+ aria-label="Decide later"
+ title="Decide later"
+ className="absolute top-3 right-3 p-1.5 rounded-lg text-zinc-500 hover:text-zinc-200 hover:bg-zinc-800 transition-colors"
+ >
+ <X size={14} />
+ </button>
+ <h2 id="kwnt-device-request-title" className="flex items-center gap-2 pr-8 text-sm font-semibold">
+ <MonitorSmartphone size={16} className="text-sky-400" aria-hidden="true" /> New device wants access
+ </h2>
+ <div className="rounded-xl bg-zinc-950 border border-zinc-800 p-3 space-y-1.5 text-center">
+ <p className="text-[11px] text-zinc-500">Code</p>
+ <p className="font-mono text-2xl font-semibold tracking-[0.15em] text-zinc-50" aria-label={`Code ${request.user_code.split('').join(' ')}`}>
+ {request.user_code}
+ </p>
+ <p className="text-xs text-zinc-300">{request.browser || 'Unknown browser'}</p>
+ <p className="text-[11px] text-zinc-500 break-words">
+ IP {request.ip || 'unknown'} · asked {ago(request.created_at, now)}
+ </p>
+ </div>
+ <p id="kwnt-device-request-warning" className="text-xs text-amber-200/90 leading-relaxed">
+ Approve only if this exact code is on a screen you’re holding right now. That device gets full control of kwant bots, as you. If someone asked you to
+ approve a code, deny it.
+ </p>
+ <label className="flex items-start gap-2 text-xs text-zinc-200 cursor-pointer min-h-[32px]">
+ <input
+ type="checkbox"
+ className="mt-0.5 h-4 w-4 accent-sky-500"
+ checked={matches}
+ onChange={(e) => setMatches(e.target.checked)}
+ />
+ <span>The code matches the one on my other device</span>
+ </label>
+ {error && (
+ <p className="text-[11px] text-rose-400 leading-snug" role="alert">
+ {error}
+ </p>
+ )}
+ <div className="flex gap-2">
+ <button type="button" onClick={onDeny} disabled={!!busy} className={`${secondary} flex-1 hover:text-rose-200 disabled:opacity-50`}>
+ {busy === 'deny' && <Loader2 size={13} className="animate-spin motion-reduce:animate-none" aria-hidden="true" />} Deny
+ </button>
+ <button
+ type="button"
+ onClick={onApprove}
+ disabled={!matches || !!busy}
+ className="flex-1 flex items-center justify-center gap-1.5 min-h-[44px] px-4 rounded-lg text-xs font-medium text-white bg-sky-600 hover:bg-sky-500 transition-colors disabled:opacity-50"
+ >
+ {busy === 'approve' && <Loader2 size={13} className="animate-spin motion-reduce:animate-none" aria-hidden="true" />} Approve
+ </button>
+ </div>
+ {more > 0 && <p className="text-[11px] text-zinc-500 text-center">{more === 1 ? '1 more request is waiting.' : `${more} more requests are waiting.`}</p>}
+ </div>
+ </div>
+ );
+};
+
+/** How often a signed-in tab checks for devices waiting to be let in. */
+export const REQUEST_CHECK_MS = 4000;
+
+/** Watches for devices waiting to be let in and asks this signed-in person to approve or deny each. */
+export const DeviceRequestPrompt: React.FC = () => {
+ const [requests, setRequests] = useState<PendingDevice[]>([]);
+ // Codes put off with "Decide later", until they expire
+ const [later, setLater] = useState<string[]>([]);
+ const [busy, setBusy] = useState<'approve' | 'deny' | null>(null);
+ const [error, setError] = useState<string | null>(null);
+
+ const refresh = useCallback(async () => {
+ try {
+ const list = await listDeviceRequests();
+ if (list) setRequests(list);
+ } catch {
+ // Offline for a moment; the next check tries again
+ }
+ }, []);
+
+ useEffect(() => {
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ let stopped = false;
+ const tick = async () => {
+ if (document.visibilityState === 'visible') await refresh();
+ if (!stopped) timer = setTimeout(tick, REQUEST_CHECK_MS);
+ };
+ tick();
+ const onVisible = () => {
+ if (document.visibilityState === 'visible') refresh();
+ };
+ document.addEventListener('visibilitychange', onVisible);
+ return () => {
+ stopped = true;
+ clearTimeout(timer);
+ document.removeEventListener('visibilitychange', onVisible);
+ };
+ }, [refresh]);
+
+ const open = requests.filter((r) => !later.includes(r.user_code));
+ const current = open[0];
+ useEffect(() => setError(null), [current?.user_code]);
+ if (!current) return null;
+
+ const decide = async (approve: boolean) => {
+ setBusy(approve ? 'approve' : 'deny');
+ setError(null);
+ try {
+ // "gone": it expired or was answered on another device; either way it's off this one
+ await decideDeviceRequest(current.user_code, approve);
+ setRequests((list) => list.filter((r) => r.user_code !== current.user_code));
+ } catch (e) {
+ setError(e instanceof Error && e.message !== 'Failed to fetch' ? e.message : 'Could not reach the server.');
+ } finally {
+ setBusy(null);
+ }
+ };
+
+ return (
+ <DeviceRequestCard
+ request={current}
+ more={open.length - 1}
+ busy={busy}
+ error={error}
+ onApprove={() => decide(true)}
+ onDeny={() => decide(false)}
+ onLater={() => setLater((l) => [...l, current.user_code])}
+ />
+ );
+};
+
+// ---------------------------------------------------------------- Settings: signed-in devices
+
+export type SessionsState = { kind: 'loading' } | { kind: 'error'; message: string } | { kind: 'ready'; sessions: SignedInSession[] };
+
+/** The list of signed-in browsers. Exported for tests. */
+export const SessionsList: React.FC<{
+ state: SessionsState;
+ revoking: string | null;
+ now?: number;
+ onRevoke: (id: string) => void;
+ onRetry: () => void;
+}> = ({ state, revoking, now = Date.now(), onRevoke, onRetry }) => {
+ if (state.kind === 'loading')
+ return (
+ <p className="flex items-center gap-2 text-[11px] text-zinc-500" role="status">
+ <Loader2 size={12} className="animate-spin motion-reduce:animate-none" aria-hidden="true" /> Loading signed-in devices…
+ </p>
+ );
+ if (state.kind === 'error')
+ return (
+ <div className="flex flex-wrap items-center gap-2 text-[11px] text-rose-300" role="alert">
+ <span>Couldn’t load signed-in devices: {state.message}</span>
+ <button type="button" onClick={onRetry} className="px-2 py-1 rounded-md text-zinc-300 bg-zinc-800 hover:bg-zinc-700 border border-zinc-700">
+ Try again
+ </button>
+ </div>
+ );
+ if (state.sessions.length === 0) return <p className="text-[11px] text-zinc-500">No browsers are signed in with a session yet.</p>;
+ return (
+ <ul className="divide-y divide-zinc-800 rounded-lg border border-zinc-800">
+ {state.sessions.map((s) => (
+ <li key={s.id} className="flex items-center gap-3 px-3 py-2">
+ <div className="flex-1 min-w-0">
+ <p className="flex flex-wrap items-center gap-1.5 text-xs text-zinc-200">
+ <span className="truncate">{s.browser || 'Unknown browser'}</span>
+ {s.current && (
+ <span className="px-1.5 py-0.5 rounded bg-sky-500/15 text-sky-300 text-[10px] font-medium">This device</span>
+ )}
+ </p>
+ <p className="text-[11px] text-zinc-500 break-words">
+ {viaLabel(s.via)} · IP {s.ip || 'unknown'} · active {ago(s.last_seen, now)}
+ </p>
+ </div>
+ {!s.current && (
+ <button
+ type="button"
+ onClick={() => onRevoke(s.id)}
+ disabled={revoking === s.id}
+ aria-label={`Sign out ${s.browser || 'this browser'}`}
+ className="shrink-0 flex items-center gap-1 min-h-[32px] px-2.5 rounded-md text-[11px] font-medium text-zinc-300 bg-zinc-800 hover:bg-zinc-700 hover:text-rose-200 border border-zinc-700 transition-colors disabled:opacity-50"
+ >
+ {revoking === s.id && <Loader2 size={11} className="animate-spin motion-reduce:animate-none" aria-hidden="true" />} Sign out
+ </button>
+ )}
+ </li>
+ ))}
+ </ul>
+ );
+};
+
+/** Settings section: who is signed in, with Sign out for each other browser. */
+export const SignedInDevices: React.FC = () => {
+ const [state, setState] = useState<SessionsState>({ kind: 'loading' });
+ const [revoking, setRevoking] = useState<string | null>(null);
+ const load = useCallback(async () => {
+ try {
+ setState({ kind: 'ready', sessions: await listSessions() });
+ } catch (e) {
+ setState({ kind: 'error', message: e instanceof Error && e.message !== 'Failed to fetch' ? e.message : 'Could not reach the server.' });
+ }
+ }, []);
+ useEffect(() => {
+ load();
+ }, [load]);
+ return (
+ <fieldset className="space-y-3 pt-2 border-t border-zinc-800">
+ <legend className="flex items-center gap-2 text-xs font-medium text-zinc-300 pt-3">
+ <MonitorSmartphone size={14} aria-hidden="true" /> Signed-in devices
+ </legend>
+ <p className="text-[11px] text-zinc-500 leading-relaxed">
+ Browsers that can use kwant bots as you. Sign out any you don’t recognise; signing out here doesn’t change the access token.
+ </p>
+ <SessionsList
+ state={state}
+ revoking={revoking}
+ onRetry={() => {
+ setState({ kind: 'loading' });
+ load();
+ }}
+ onRevoke={async (id) => {
+ setRevoking(id);
+ try {
+ await revokeSession(id);
+ await load();
+ } catch (e) {
+ setState({ kind: 'error', message: e instanceof Error ? e.message : 'Could not reach the server.' });
+ } finally {
+ setRevoking(null);
+ }
+ }}
+ />
+ </fieldset>
+ );
+};
diff --git a/frontend/src/components/SettingsModal.tsx b/frontend/src/components/SettingsModal.tsx
index 1dbcfff7..bdfc826b 100644
--- a/frontend/src/components/SettingsModal.tsx
+++ b/frontend/src/components/SettingsModal.tsx
@@ -12,6 +12,7 @@ import {
} from '../continuity';
import { isSfxMuted, playSfx, toggleSfxMute } from '../audio/chiptune';
import { useAuth } from './AuthGate';
+import { SignedInDevices } from './DeviceSignIn';
import { ComputerModeControl, useComputerMode } from './ComputerModeSwitch';
import { useEngines } from '../useEngines';
import { LayaStatusRow } from './LayaStatus';
@@ -53,7 +54,7 @@ interface SettingsModalProps {
/** App settings: shared by every space (keys, Laya, limits, notifications, sounds). Accounts,
* bots and tools are per space, in Space settings. */
export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, tokensUsed = 0 }) => {
- const { authRequired, signOut } = useAuth();
+ const { authRequired, deviceLogin, signOut } = useAuth();
const computer = useComputerMode(isOpen);
const engines = useEngines(isOpen);
const [sfxMuted, setSfxMuted] = useState(isSfxMuted);
@@ -500,6 +501,8 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, t
</div>
</fieldset>
+ {authRequired && deviceLogin && <SignedInDevices />}
+
{saveError && (
<div className="bg-rose-500/10 border border-rose-500/20 text-rose-300 px-3 py-2 rounded-lg text-xs flex items-center gap-2" role="alert">
<AlertTriangle size={14} />
diff --git a/frontend/src/deviceSignIn.ts b/frontend/src/deviceSignIn.ts
new file mode 100644
index 00000000..a20ddec5
--- /dev/null
+++ b/frontend/src/deviceSignIn.ts
@@ -0,0 +1,119 @@
+// Signing a new browser in from a signed-in device: the new browser shows a short code and waits;
+// a signed-in device sees "New device wants access" and approves or denies it. Also the list of
+// signed-in browsers in Settings, with Sign out for each.
+
+/** What `POST /api/auth/device` started: the secret stays in this browser, the user code is shown. */
+export interface DeviceRequest {
+ device_code: string;
+ user_code: string;
+ expires_in: number;
+ interval: number;
+}
+
+export type DeviceStart = { kind: 'started'; request: DeviceRequest } | { kind: 'too_many'; retryAfter: number };
+
+export type DevicePoll = 'pending' | 'approved' | 'denied' | 'expired';
+
+/** A device waiting to be let in, as a signed-in device sees it. */
+export interface PendingDevice {
+ user_code: string;
+ browser: string;
+ ip: string;
+ created_at: string;
+ expires_at: string;
+}
+
+/** A signed-in browser. */
+export interface SignedInSession {
+ id: string;
+ browser: string;
+ ip: string;
+ via: 'token' | 'link' | 'device';
+ created_at: string;
+ last_seen: string;
+ current: boolean;
+}
+
+const json = { 'Content-Type': 'application/json' };
+
+/** Asks to be let in. */
+export async function startDeviceRequest(send: typeof fetch = (...a) => fetch(...a)): Promise<DeviceStart> {
+ const res = await send('/api/auth/device', { method: 'POST', headers: json, body: '{}' });
+ if (res.status === 429) {
+ const body = await res.json().catch(() => null);
+ const retryAfter = Number(body?.retry_after ?? res.headers.get('Retry-After')) || 60;
+ return { kind: 'too_many', retryAfter };
+ }
+ if (!res.ok) throw new Error(`The server answered ${res.status}.`);
+ return { kind: 'started', request: await res.json() };
+}
+
+/** Whether the request was decided. "approved" comes with the session cookie, once. */
+export async function pollDeviceRequest(deviceCode: string, send: typeof fetch = (...a) => fetch(...a)): Promise<DevicePoll> {
+ const res = await send('/api/auth/device/poll', { method: 'POST', headers: json, body: JSON.stringify({ device_code: deviceCode }) });
+ if (res.status === 403) return 'denied';
+ if (res.status === 410) return 'expired';
+ if (!res.ok) throw new Error(`The server answered ${res.status}.`);
+ const body = await res.json().catch(() => null);
+ return body?.status === 'approved' ? 'approved' : 'pending';
+}
+
+/** Devices waiting to be let in, or null when this browser may not see them (or the server is older). */
+export async function listDeviceRequests(send: typeof fetch = (...a) => fetch(...a)): Promise<PendingDevice[] | null> {
+ // Quiet: a background check never opens the sign-in screen by itself
+ const res = await send('/api/signin/requests', { cache: 'no-store', kwntQuiet: true } as RequestInit);
+ if (!res.ok) return null;
+ const body = await res.json().catch(() => null);
+ return Array.isArray(body) ? body : null;
+}
+
+/** Approves or denies a waiting device. "gone" when it expired or was decided elsewhere. */
+export async function decideDeviceRequest(userCode: string, approve: boolean, send: typeof fetch = (...a) => fetch(...a)): Promise<'ok' | 'gone'> {
+ const res = await send(`/api/signin/requests/${approve ? 'approve' : 'deny'}`, {
+ method: 'POST',
+ headers: json,
+ body: JSON.stringify({ user_code: userCode }),
+ });
+ if (res.status === 404) return 'gone';
+ if (!res.ok) throw new Error(`The server answered ${res.status}.`);
+ return 'ok';
+}
+
+export async function listSessions(send: typeof fetch = (...a) => fetch(...a)): Promise<SignedInSession[]> {
+ const res = await send('/api/signin/sessions', { cache: 'no-store' });
+ if (!res.ok) throw new Error(`The server answered ${res.status}.`);
+ return res.json();
+}
+
+/** Signs that browser out. A session that is already gone counts as done. */
+export async function revokeSession(id: string, send: typeof fetch = (...a) => fetch(...a)): Promise<void> {
+ const res = await send(`/api/signin/sessions/${encodeURIComponent(id)}`, { method: 'DELETE' });
+ if (!res.ok && res.status !== 404) throw new Error(`The server answered ${res.status}.`);
+}
+
+/** How a session was made, in words. */
+export function viaLabel(via: SignedInSession['via']): string {
+ if (via === 'link') return 'Signed in with a link';
+ if (via === 'device') return 'Approved from another device';
+ return 'Signed in with the token';
+}
+
+/** "just now", "5 min ago", "3 h ago", "2 days ago". */
+export function ago(iso: string, now: number = Date.now()): string {
+ const t = Date.parse(iso);
+ if (Number.isNaN(t)) return '';
+ const s = Math.max(0, Math.round((now - t) / 1000));
+ if (s < 60) return 'just now';
+ const min = Math.floor(s / 60);
+ if (min < 60) return `${min} min ago`;
+ const h = Math.floor(min / 60);
+ if (h < 24) return `${h} h ago`;
+ const d = Math.floor(h / 24);
+ return d === 1 ? '1 day ago' : `${d} days ago`;
+}
+
+/** "9:41" left until `expiresAt` (ms), never negative. */
+export function countdown(expiresAt: number, now: number = Date.now()): string {
+ const s = Math.max(0, Math.ceil((expiresAt - now) / 1000));
+ return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`;
+}
diff --git a/frontend/tests/deviceSignIn.test.mjs b/frontend/tests/deviceSignIn.test.mjs
new file mode 100644
index 00000000..bb7a9c20
--- /dev/null
+++ b/frontend/tests/deviceSignIn.test.mjs
@@ -0,0 +1,216 @@
+// Signing in from another device: the new browser shows a short code and waits; a signed-in
+// device approves or denies it; Settings lists signed-in browsers with Sign out.
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { loadBundled } from './bundle.mjs';
+
+const m = await loadBundled(`
+ import React from 'react';
+ import { renderToStaticMarkup } from 'react-dom/server.browser';
+ import { DeviceRequestCard, DeviceWaitView, SessionsList } from './src/components/DeviceSignIn';
+ import { TokenForm } from './src/components/AuthGate';
+ export * from './src/deviceSignIn';
+ const noop = () => {};
+ export const wait = (state, now) => renderToStaticMarkup(React.createElement(DeviceWaitView, { state, now, onStart: noop, onCancel: noop }));
+ export const card = (props) => renderToStaticMarkup(React.createElement(DeviceRequestCard, { more: 0, busy: null, error: null, onApprove: noop, onDeny: noop, onLater: noop, ...props }));
+ export const sessions = (state, now, revoking = null) => renderToStaticMarkup(React.createElement(SessionsList, { state, now, revoking, onRevoke: noop, onRetry: noop }));
+ export const form = (deviceLogin) => renderToStaticMarkup(React.createElement(TokenForm, { notice: null, onSignedIn: noop, deviceLogin }));
+`);
+
+const text = (html) => html.replace(/<[^>]+>/g, ' ').replace(/&#x27;|&#39;|’/g, "'").replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&amp;/g, '&').replace(/\s+/g, ' ');
+const buttons = (html) => [...html.matchAll(/<button[^>]*>(.*?)<\/button>/g)].map((b) => text(b[1]).trim());
+const NOW = Date.parse('2026-10-25T12:00:00Z');
+const request = { device_code: 'kd1.secret', user_code: 'BCDF-2345', expires_in: 600, interval: 2 };
+
+/** A fetch that answers each call from `answers` in turn ([status, body]) and records the calls. */
+function fake(...answers) {
+ const calls = [];
+ const send = async (url, init = {}) => {
+ calls.push({ url, init });
+ const [status, body, headers] = answers.shift() ?? [500, null];
+ return new Response(body === null ? null : JSON.stringify(body), { status, headers });
+ };
+ return { calls, send };
+}
+
+// ---------------------------------------------------------------- the sign-in card
+
+test('with device login, "Sign in from another device" leads the card; the link and the token follow', () => {
+ const html = m.form(true);
+ const t = text(html);
+ assert.equal(buttons(html)[0], 'Sign in from another device');
+ assert.ok(t.indexOf('Sign in from another device') < t.indexOf('Or open the one-time sign-in link'));
+ assert.ok(t.indexOf('kwnt signin-link') < t.indexOf('Other setups'));
+ assert.match(html.slice(html.indexOf('<details')), /Paste a sign-in link or the access token/);
+});
+
+test('an older server without device login: no device button, the link leads', () => {
+ const t = text(m.form(false));
+ assert.ok(!t.includes('Sign in from another device'));
+ assert.match(t, /Open the one-time sign-in link/);
+});
+
+// ---------------------------------------------------------------- the new browser's states
+
+test('waiting: the code, what to do with it, the time left and Cancel', () => {
+ const html = m.wait({ kind: 'waiting', request, expiresAt: NOW + 9 * 60_000 + 41_000 }, NOW);
+ const t = text(html);
+ assert.match(t, /where you're already signed in to kwant bots, open it and approve this code/);
+ assert.match(t, /BCDF-2345/);
+ assert.match(t, /Waiting for approval · 9:41 left/);
+ assert.match(html, /role="status"/);
+ assert.match(html, /aria-live="polite"/);
+ assert.deepEqual(buttons(html), ['Cancel']);
+ assert.ok(!html.includes('kd1.secret'), 'the device secret is never shown');
+});
+
+test('approved: signing in', () => {
+ assert.match(text(m.wait({ kind: 'approved' }, NOW)), /Approved\. Signing you in/);
+});
+
+test('denied, expired, too many and errors say what happened and offer a new code', () => {
+ const cases = [
+ [{ kind: 'denied' }, /denied on your other device.*still signed out/],
+ [{ kind: 'expired' }, /expired before it was approved\. Codes work for 10 minutes/],
+ [{ kind: 'too_many', retryAfter: 45 }, /Too many sign-in requests right now\. Try again in 1 min/],
+ [{ kind: 'error', message: 'Could not reach the server.' }, /Could not reach the server/],
+ ];
+ for (const [state, re] of cases) {
+ const html = m.wait(state, NOW);
+ assert.match(text(html), re, state.kind);
+ assert.match(html, /role="alert"/, state.kind);
+ assert.deepEqual(buttons(html), ['Get a new code'], state.kind);
+ }
+});
+
+test('idle and starting', () => {
+ assert.deepEqual(buttons(m.wait({ kind: 'idle' }, NOW)), ['Sign in from another device']);
+ assert.match(m.wait({ kind: 'starting' }, NOW), /disabled=""/);
+});
+
+test('countdown never goes below zero', () => {
+ assert.equal(m.countdown(NOW + 61_000, NOW), '1:01');
+ assert.equal(m.countdown(NOW - 5000, NOW), '0:00');
+});
+
+// ---------------------------------------------------------------- the API, new browser side
+
+test('start: POST /api/auth/device; 429 gives a wait', async () => {
+ const ok = fake([200, request]);
+ assert.deepEqual(await m.startDeviceRequest(ok.send), { kind: 'started', request });
+ assert.equal(ok.calls[0].url, '/api/auth/device');
+ assert.equal(ok.calls[0].init.method, 'POST');
+ const busy = fake([429, { error: 'too many', retry_after: 30 }]);
+ assert.deepEqual(await m.startDeviceRequest(busy.send), { kind: 'too_many', retryAfter: 30 });
+ await assert.rejects(m.startDeviceRequest(fake([500, {}]).send), /500/);
+});
+
+test('poll: pending, approved (once), denied (403) and expired (410)', async () => {
+ const f = fake([200, { status: 'pending' }], [200, { status: 'approved' }], [403, { status: 'denied' }], [410, { status: 'expired' }]);
+ assert.equal(await m.pollDeviceRequest('kd1.secret', f.send), 'pending');
+ assert.equal(await m.pollDeviceRequest('kd1.secret', f.send), 'approved');
+ assert.equal(await m.pollDeviceRequest('kd1.secret', f.send), 'denied');
+ assert.equal(await m.pollDeviceRequest('kd1.secret', f.send), 'expired');
+ assert.equal(f.calls[0].url, '/api/auth/device/poll');
+ assert.deepEqual(JSON.parse(f.calls[0].init.body), { device_code: 'kd1.secret' });
+});
+
+// ---------------------------------------------------------------- the signed-in device
+
+const pending = { user_code: 'BCDF-2345', browser: 'Safari on iPhone', ip: '203.0.113.7', created_at: '2026-10-25T11:58:00Z', expires_at: '2026-10-25T12:08:00Z' };
+
+test('the approval card: code, browser, IP, when, the warning, and Approve held until the code matches', () => {
+ const html = m.card({ request: pending, now: NOW });
+ const t = text(html);
+ assert.match(html, /role="alertdialog"/);
+ assert.match(html, /aria-modal="true"/);
+ assert.match(t, /New device wants access/);
+ assert.match(t, /BCDF-2345/);
+ assert.match(t, /Safari on iPhone/);
+ assert.match(t, /IP 203\.0\.113\.7 · asked 2 min ago/);
+ assert.match(t, /Approve only if this exact code is on a screen you're holding right now/);
+ assert.match(t, /If someone asked you to approve a code, deny it/);
+ assert.match(t, /The code matches the one on my other device/);
+ assert.match(html, /type="checkbox"/);
+ const approve = html.match(/<button[^>]*>(?:(?!<\/button>).)*Approve<\/button>/)[0];
+ assert.match(approve, /disabled=""/, 'Approve waits for the checkbox');
+ const deny = html.match(/<button[^>]*>(?:(?!<\/button>).)*Deny<\/button>/)[0];
+ assert.ok(!/disabled=""/.test(deny), 'Deny is always available');
+ assert.match(html, /aria-label="Decide later"/);
+});
+
+test('the approval card: more waiting, busy and errors', () => {
+ assert.match(text(m.card({ request: pending, now: NOW, more: 2 })), /2 more requests are waiting/);
+ assert.match(text(m.card({ request: pending, now: NOW, more: 1 })), /1 more request is waiting/);
+ const busy = m.card({ request: pending, now: NOW, busy: 'deny' });
+ assert.deepEqual(buttons(busy).filter(Boolean), ['Deny', 'Approve'], 'labels stay while busy');
+ assert.match(busy.match(/<button[^>]*>(?:(?!<\/button>).)*Deny<\/button>/)[0], /disabled=""/);
+ assert.match(text(m.card({ request: pending, now: NOW, error: 'Could not reach the server.' })), /Could not reach the server/);
+});
+
+test('the signed-in side: list quietly, approve and deny by user code, 404 is "gone"', async () => {
+ const f = fake([200, [pending]], [204, null], [204, null], [404, { error: 'no waiting sign-in request' }]);
+ assert.deepEqual(await m.listDeviceRequests(f.send), [pending]);
+ assert.equal(f.calls[0].url, '/api/signin/requests');
+ assert.equal(f.calls[0].init.kwntQuiet, true, 'a background check never opens the sign-in screen');
+ assert.equal(await m.decideDeviceRequest('BCDF-2345', true, f.send), 'ok');
+ assert.equal(f.calls[1].url, '/api/signin/requests/approve');
+ assert.deepEqual(JSON.parse(f.calls[1].init.body), { user_code: 'BCDF-2345' });
+ assert.equal(await m.decideDeviceRequest('BCDF-2345', false, f.send), 'ok');
+ assert.equal(f.calls[2].url, '/api/signin/requests/deny');
+ assert.equal(await m.decideDeviceRequest('BCDF-2345', true, f.send), 'gone');
+});
+
+test('a browser that may not see requests (401/403) or an older server (404) gets null, not an error', async () => {
+ for (const status of [401, 403, 404]) assert.equal(await m.listDeviceRequests(fake([status, {}]).send), null, String(status));
+});
+
+// ---------------------------------------------------------------- Settings: signed-in devices
+
+const sessionRows = [
+ { id: 's1', browser: 'Chrome on Mac', ip: '198.51.100.2', via: 'link', created_at: '2026-10-20T10:00:00Z', last_seen: '2026-10-25T11:59:30Z', current: true },
+ { id: 's2', browser: 'Safari on iPhone', ip: '203.0.113.7', via: 'device', created_at: '2026-10-24T10:00:00Z', last_seen: '2026-10-24T09:00:00Z', current: false },
+ { id: 's3', browser: 'Firefox on Linux', ip: '192.0.2.9', via: 'token', created_at: '2026-10-01T10:00:00Z', last_seen: '2026-10-25T09:00:00Z', current: false },
+];
+
+test('sessions: each browser with how it signed in, IP and last activity; this device has no Sign out', () => {
+ const html = m.sessions({ kind: 'ready', sessions: sessionRows }, NOW);
+ const t = text(html);
+ assert.match(t, /Chrome on Mac This device Signed in with a link · IP 198\.51\.100\.2 · active just now/);
+ assert.match(t, /Safari on iPhone Approved from another device · IP 203\.0\.113\.7 · active 1 day ago/);
+ assert.match(t, /Firefox on Linux Signed in with the token · IP 192\.0\.2\.9 · active 3 h ago/);
+ assert.deepEqual(buttons(html), ['Sign out', 'Sign out']);
+ assert.match(html, /aria-label="Sign out Safari on iPhone"/);
+});
+
+test('sessions: loading, empty, error with Try again, and a revoke in progress', () => {
+ assert.match(m.sessions({ kind: 'loading' }, NOW), /role="status"/);
+ assert.match(text(m.sessions({ kind: 'ready', sessions: [] }, NOW)), /No browsers are signed in with a session yet/);
+ const err = m.sessions({ kind: 'error', message: 'The server answered 500.' }, NOW);
+ assert.match(text(err), /Couldn't load signed-in devices: The server answered 500\./);
+ assert.deepEqual(buttons(err), ['Try again']);
+ const revoking = m.sessions({ kind: 'ready', sessions: sessionRows }, NOW, 's2');
+ assert.match(revoking.match(/<button[^>]*aria-label="Sign out Safari on iPhone"[^>]*>/)[0], /disabled=""/);
+});
+
+test('sessions API: list uncached, revoke by id, an already-gone session is fine', async () => {
+ const f = fake([200, sessionRows], [204, null], [404, {}], [500, {}]);
+ assert.deepEqual(await m.listSessions(f.send), sessionRows);
+ assert.equal(f.calls[0].url, '/api/signin/sessions');
+ assert.equal(f.calls[0].init.cache, 'no-store');
+ await m.revokeSession('s2', f.send);
+ assert.equal(f.calls[1].url, '/api/signin/sessions/s2');
+ assert.equal(f.calls[1].init.method, 'DELETE');
+ await m.revokeSession('s2', f.send);
+ await assert.rejects(m.revokeSession('s2', f.send), /500/);
+});
+
+test('words for how a session was made, and how long ago', () => {
+ assert.equal(m.viaLabel('link'), 'Signed in with a link');
+ assert.equal(m.viaLabel('device'), 'Approved from another device');
+ assert.equal(m.viaLabel('token'), 'Signed in with the token');
+ assert.equal(m.ago('2026-10-25T11:59:50Z', NOW), 'just now');
+ assert.equal(m.ago('2026-10-25T11:55:00Z', NOW), '5 min ago');
+ assert.equal(m.ago('2026-10-22T12:00:00Z', NOW), '3 days ago');
+ assert.equal(m.ago('nonsense', NOW), '');
+});