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.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
Settings: "Add a phone or browser" shows a one-time sign-in QR code
Pixel (kwant bot)1f6020cdec55
diff --git a/frontend/package-lock.json b/frontend/package-lock.jsonindex f52bb037..44fbc303 100644--- a/frontend/package-lock.json+++ b/frontend/package-lock.json@@ -13,7 +13,8 @@"react": "^18.3.1","react-dom": "^18.3.1","react-markdown": "^10.1.0",- "remark-gfm": "^4.0.1"+ "remark-gfm": "^4.0.1",+ "uqr": "0.1.3"},"devDependencies": {"@types/react": "^18.3.12",@@ -3870,6 +3871,12 @@"browserslist": ">= 4.21.0"}},+ "node_modules/uqr": {+ "version": "0.1.3",+ "resolved": "https://registry.npmjs.org/uqr/-/uqr-0.1.3.tgz",+ "integrity": "sha512-0rjE8iEJe4YmT9TOhwsZtqCMRLc5DXZUI2UEYUUg63ikBkqqE5EYWaI0etFe/5KUcmcYwLih2RND1kq+hrUJXA==",+ "license": "MIT"+ },"node_modules/util-deprecate": {"version": "1.0.2","resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",diff --git a/frontend/package.json b/frontend/package.jsonindex 7db08cc1..470a73cb 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -15,7 +15,8 @@"react": "^18.3.1","react-dom": "^18.3.1","react-markdown": "^10.1.0",- "remark-gfm": "^4.0.1"+ "remark-gfm": "^4.0.1",+ "uqr": "0.1.3"},"devDependencies": {"@types/react": "^18.3.12",diff --git a/frontend/src/components/DeviceSignIn.tsx b/frontend/src/components/DeviceSignIn.tsxindex 033ece9b..0464319b 100644--- a/frontend/src/components/DeviceSignIn.tsx+++ b/frontend/src/components/DeviceSignIn.tsx@@ -1,15 +1,19 @@import React, { useCallback, useEffect, useRef, useState } from 'react';-import { AlertTriangle, Loader2, MonitorSmartphone, RefreshCw, ShieldCheck, X } from 'lucide-react';+import { AlertTriangle, Check, Copy, Loader2, MonitorSmartphone, QrCode, RefreshCw, ShieldCheck, X } from 'lucide-react';import {type DeviceRequest,+ type MintedLink,type PendingDevice,type SignedInSession,ago,countdown,+ createSigninLink,decideDeviceRequest,listDeviceRequests,listSessions,+ newLinkSession,pollDeviceRequest,+ qrPath,revokeSession,startDeviceRequest,viaLabel,@@ -393,6 +397,242 @@ export const SessionsList: React.FC<{);};+// ---------------------------------------------------------------- Settings: add a phone or browser++export type AddState =+ | { kind: 'idle' }+ | { kind: 'minting' }+ | { kind: 'showing'; link: MintedLink }+ | { kind: 'expired' }+ | { kind: 'signed_in'; browser: string }+ | { kind: 'error'; message: string };++/** The QR code, drawn here: the sign-in code never goes to a QR service. */+export const QrImage: React.FC<{ text: string }> = ({ text }) => {+ const { size, d } = qrPath(text);+ return (+ <svg+ viewBox={`0 0 ${size} ${size}`}+ role="img"+ aria-label="QR code for the one-time sign-in link"+ shapeRendering="crispEdges"+ className="block w-full h-auto rounded-lg bg-white"+ >+ <path d={d} fill="#000" />+ </svg>+ );+};++/** What "Add a phone or browser" shows in each state. Exported for tests. */+export const AddDeviceView: React.FC<{+ state: AddState;+ now?: number;+ copied?: 'yes' | 'failed' | null;+ onShow: () => void;+ onHide: () => void;+ onCopy: () => void;+}> = ({ state, now = Date.now(), copied = null, onShow, onHide, onCopy }) => {+ if (state.kind === 'idle' || state.kind === 'minting' || state.kind === 'error')+ return (+ <div className="space-y-2">+ <button type="button" onClick={onShow} disabled={state.kind === 'minting'} className={`${secondary} w-full sm:w-auto disabled:opacity-50`}>+ {state.kind === 'minting' ? (+ <Loader2 size={14} className="animate-spin motion-reduce:animate-none" aria-hidden="true" />+ ) : (+ <QrCode size={14} aria-hidden="true" />+ )}+ Add a phone or browser+ </button>+ {state.kind === 'error' && (+ <p className="flex items-center gap-1.5 text-[11px] text-rose-300" role="alert">+ <AlertTriangle size={12} aria-hidden="true" /> Couldn’t make a sign-in code: {state.message}+ </p>+ )}+ </div>+ );++ if (state.kind === 'signed_in')+ return (+ <div className="space-y-3 rounded-xl border border-emerald-500/30 bg-emerald-500/5 p-4" role="status" aria-live="polite">+ <p className="flex items-center gap-2 text-xs font-medium text-emerald-200">+ <Check size={14} aria-hidden="true" /> Signed in ✓+ </p>+ <p className="text-[11px] text-zinc-400 leading-relaxed">+ {state.browser || 'A new browser'} signed in with the code. It’s used up now. If that wasn’t you, sign it out below.+ </p>+ <div className="flex flex-wrap gap-2">+ <button type="button" onClick={onShow} className={secondary}>+ Add another+ </button>+ <button type="button" onClick={onHide} className={secondary}>+ Done+ </button>+ </div>+ </div>+ );++ if (state.kind === 'expired')+ return (+ <div className="space-y-3 rounded-xl border border-zinc-700 bg-zinc-900/60 p-4" role="status" aria-live="polite">+ <p className="text-xs text-zinc-300">The code expired, so it was hidden. Make a new one if you still need it.</p>+ <div className="flex flex-wrap gap-2">+ <button type="button" onClick={onShow} className={secondary}>+ <RefreshCw size={14} aria-hidden="true" /> New code+ </button>+ <button type="button" onClick={onHide} className={secondary}>+ Hide+ </button>+ </div>+ </div>+ );++ const { link } = state;+ return (+ <div className="space-y-3 rounded-xl border border-sky-500/30 bg-sky-500/5 p-4">+ <p className="text-xs text-zinc-300 leading-relaxed">+ Scan this with the phone’s camera, or open the link in the other browser. It signs that device in once.+ </p>+ <div className="mx-auto w-full max-w-[220px]">+ <QrImage text={link.url} />+ </div>+ <p className="flex items-start gap-1.5 text-[11px] text-amber-200/90 leading-relaxed">+ <AlertTriangle size={12} className="mt-0.5 shrink-0" aria-hidden="true" />+ Anyone who scans this can sign in once. Don’t share or screenshot it.+ </p>+ <div className="flex gap-2">+ <label className="sr-only" htmlFor="add-device-link">+ One-time sign-in link+ </label>+ <input+ id="add-device-link"+ readOnly+ value={link.url}+ onFocus={(e) => e.currentTarget.select()}+ className="flex-1 min-w-0 rounded-lg bg-zinc-950 border border-zinc-700 px-2.5 text-[11px] font-mono text-zinc-300"+ />+ <button type="button" onClick={onCopy} className={`${secondary} shrink-0`}>+ {copied === 'yes' ? <Check size={14} aria-hidden="true" /> : <Copy size={14} aria-hidden="true" />}+ {copied === 'yes' ? 'Copied' : 'Copy link'}+ </button>+ </div>+ {copied === 'failed' && <p className="text-[11px] text-rose-300">Couldn’t copy. Select the link and copy it yourself.</p>}+ <p className="text-[11px] text-zinc-400" role="timer" aria-live="off">+ Works once · {countdown(link.expiresAt, now)} left+ </p>+ <div className="flex flex-wrap gap-2">+ <button type="button" onClick={onShow} className={secondary}>+ <RefreshCw size={14} aria-hidden="true" /> New code+ </button>+ <button type="button" onClick={onHide} className={secondary}>+ <X size={14} aria-hidden="true" /> Hide+ </button>+ </div>+ </div>+ );+};++/** "Add a phone or browser": mints a one-time link, shows it as a QR code with a countdown, hides it+ * when it expires or the page is left, and says "Signed in ✓" once a new browser used it. */+export const AddDevice: React.FC<{ onSignedIn: () => void }> = ({ onSignedIn }) => {+ const [state, setState] = useState<AddState>({ kind: 'idle' });+ const [now, setNow] = useState(() => Date.now());+ const [copied, setCopied] = useState<'yes' | 'failed' | null>(null);+ // Sessions that existed when the code was made; null when the list couldn't be read+ const known = useRef<Set<string> | null>(null);+ const run = useRef(0);++ const show = async () => {+ const mine = ++run.current;+ setState({ kind: 'minting' });+ setCopied(null);+ try {+ known.current = await listSessions()+ .then((list) => new Set(list.map((s) => s.id)))+ .catch(() => null);+ const link = await createSigninLink(window.location.origin);+ if (mine !== run.current) return;+ setNow(Date.now());+ setState({ kind: 'showing', link });+ } catch (e) {+ if (mine !== run.current) return;+ setState({ kind: 'error', message: e instanceof Error && e.message !== 'Failed to fetch' ? e.message : 'Could not reach the server.' });+ }+ };+ const hide = useCallback(() => {+ run.current++;+ known.current = null;+ setCopied(null);+ setState({ kind: 'idle' });+ }, []);++ const showing = state.kind === 'showing' ? state.link : null;++ // The countdown; at zero the code is dropped from the page+ useEffect(() => {+ if (!showing) return;+ const tick = () => {+ const t = Date.now();+ setNow(t);+ if (t >= showing.expiresAt) {+ setCopied(null);+ setState({ kind: 'expired' });+ }+ };+ const id = window.setInterval(tick, 1000);+ return () => window.clearInterval(id);+ }, [showing]);++ // Leaving the page (another tab, the app in the background) hides the code+ useEffect(() => {+ if (!showing) return;+ const onHidden = () => {+ if (document.visibilityState === 'hidden') hide();+ };+ document.addEventListener('visibilitychange', onHidden);+ window.addEventListener('pagehide', hide);+ return () => {+ document.removeEventListener('visibilitychange', onHidden);+ window.removeEventListener('pagehide', hide);+ };+ }, [showing, hide]);++ // Watch the sessions list for the browser that used this code+ useEffect(() => {+ if (!showing || !known.current) return;+ let stop = false;+ const check = async () => {+ const ids = known.current;+ if (!ids) return;+ const list = await listSessions().catch(() => null);+ if (stop || !list) return;+ const fresh = newLinkSession(list, ids);+ if (fresh) {+ run.current++;+ setCopied(null);+ setState({ kind: 'signed_in', browser: fresh.browser });+ onSignedIn();+ }+ };+ const id = window.setInterval(check, 3000);+ return () => {+ stop = true;+ window.clearInterval(id);+ };+ }, [showing, onSignedIn]);++ const copy = async () => {+ if (!showing) return;+ try {+ await navigator.clipboard.writeText(showing.url);+ setCopied('yes');+ } catch {+ setCopied('failed');+ }+ };++ return <AddDeviceView state={state} now={now} copied={copied} onShow={show} onHide={hide} onCopy={copy} />;+};+/** 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' });@@ -415,6 +655,7 @@ export const SignedInDevices: React.FC = () => {<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>+ <AddDevice onSignedIn={load} /><SessionsListstate={state}revoking={revoking}diff --git a/frontend/src/components/SettingsModal.tsx b/frontend/src/components/SettingsModal.tsxindex bdfc826b..dd589824 100644--- a/frontend/src/components/SettingsModal.tsx+++ b/frontend/src/components/SettingsModal.tsx@@ -13,6 +13,7 @@ import {import { isSfxMuted, playSfx, toggleSfxMute } from '../audio/chiptune';import { useAuth } from './AuthGate';import { SignedInDevices } from './DeviceSignIn';+import { signedInDevicesVisible } from '../deviceSignIn';import { ComputerModeControl, useComputerMode } from './ComputerModeSwitch';import { useEngines } from '../useEngines';import { LayaStatusRow } from './LayaStatus';@@ -501,7 +502,7 @@ export const SettingsModal: React.FC<SettingsModalProps> = ({ isOpen, onClose, t</div></fieldset>- {authRequired && deviceLogin && <SignedInDevices />}+ {signedInDevicesVisible(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">diff --git a/frontend/src/deviceSignIn.ts b/frontend/src/deviceSignIn.tsindex a20ddec5..88475b03 100644--- a/frontend/src/deviceSignIn.ts+++ b/frontend/src/deviceSignIn.ts@@ -1,6 +1,9 @@// 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.+// signed-in browsers in Settings, with Sign out for each, and "Add a phone or browser": a one-time+// sign-in link and its QR code, drawn here in the browser so the code never leaves it.++import { encode } from 'uqr';/** What `POST /api/auth/device` started: the secret stays in this browser, the user code is shown. */export interface DeviceRequest {@@ -117,3 +120,51 @@ 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')}`;}++// ---------------------------------------------------------------- "Add a phone or browser"++/** Signed-in devices (and adding one) only exist where the server asks for sign-in and knows+ * device login; never on the person's own computer in local/no-token mode. */+export function signedInDevicesVisible(authRequired: boolean, deviceLogin: boolean): boolean {+ return authRequired && deviceLogin;+}++/** A one-time sign-in link minted on a signed-in device: works once, for `expires_in` seconds. */+export interface MintedLink {+ url: string;+ expiresAt: number;+}++/** Asks for a one-time link (`POST /api/signin/links`). When kwnt doesn't know its public+ * address it answers `url: null`, and the link is built from this page's own address. */+export async function createSigninLink(+ origin: string,+ now: number = Date.now(),+ send: typeof fetch = (...a) => fetch(...a),+): Promise<MintedLink> {+ const res = await send('/api/signin/links', { method: 'POST', headers: json, body: '{}', cache: 'no-store' });+ if (!res.ok) throw new Error(`The server answered ${res.status}.`);+ const body = await res.json().catch(() => null);+ if (!body || typeof body.code !== 'string' || !body.code) throw new Error('The server sent no sign-in code.');+ const url = typeof body.url === 'string' && body.url ? body.url : `${origin}/#kwnt_token=${encodeURIComponent(body.code)}`;+ const ttl = Number(body.expires_in) > 0 ? Number(body.expires_in) : 900;+ return { url, expiresAt: now + ttl * 1000 };+}++/** The browser that signed in with a link since the QR was shown: a `via: "link"` session that+ * wasn't in the list when the code was minted. Ids rather than times, so clock skew can't fool it. */+export function newLinkSession(sessions: SignedInSession[], knownIds: ReadonlySet<string>): SignedInSession | null {+ return sessions.find((s) => s.via === 'link' && !s.current && !knownIds.has(s.id)) ?? null;+}++/** The QR code for `text` as one SVG path (dark modules) inside a `size` x `size` box, quiet zone included. */+export function qrPath(text: string): { size: number; d: string } {+ const qr = encode(text, { ecc: 'M', border: 4 });+ let d = '';+ qr.data.forEach((row, y) =>+ row.forEach((dark, x) => {+ if (dark) d += `M${x} ${y}h1v1h-1z`;+ }),+ );+ return { size: qr.size, d };+}diff --git a/frontend/tests/addPhone.test.mjs b/frontend/tests/addPhone.test.mjsnew file mode 100644index 00000000..f2cacdb4--- /dev/null+++ b/frontend/tests/addPhone.test.mjs@@ -0,0 +1,139 @@+// "Add a phone or browser" in Settings → Signed-in devices: a one-time link and its QR code,+// drawn in this browser, with a countdown, Hide and New code; hidden in local/no-token mode.+import assert from 'node:assert/strict';+import test from 'node:test';+import { readFileSync } from 'node:fs';+import { loadBundled } from './bundle.mjs';++const m = await loadBundled(`+ import React from 'react';+ import { renderToStaticMarkup } from 'react-dom/server.browser';+ import { AddDeviceView } from './src/components/DeviceSignIn';+ export * from './src/deviceSignIn';+ const noop = () => {};+ export const view = (state, now, copied = null) =>+ renderToStaticMarkup(React.createElement(AddDeviceView, { state, now, copied, onShow: noop, onHide: noop, onCopy: noop }));+`);++const text = (html) => html.replace(/<[^>]+>/g, ' ').replace(/'|'|’/g, "'").replace(/&/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 URL_ = 'https://kwant.example/#kwnt_token=kl1.secretcode';+const showing = { kind: 'showing', link: { url: URL_, expiresAt: NOW + 15 * 60_000 } };++function fake(...answers) {+ const calls = [];+ const send = async (url, init = {}) => {+ calls.push({ url, init });+ const [status, body] = answers.shift() ?? [500, null];+ return new Response(body === null ? null : JSON.stringify(body), { status });+ };+ return { calls, send };+}++// ---------------------------------------------------------------- minting the link++test('a link is minted with POST /api/signin/links; url null is built from this page', async () => {+ const { calls, send } = fake([200, { code: 'kl1.abc', url: null, expires_at: '2026-10-25T12:15:00Z', expires_in: 900 }]);+ const link = await m.createSigninLink('https://box.example', NOW, send);+ assert.equal(calls[0].url, '/api/signin/links');+ assert.equal(calls[0].init.method, 'POST');+ assert.equal(link.url, 'https://box.example/#kwnt_token=kl1.abc');+ assert.equal(link.expiresAt, NOW + 900_000);+});++test('the server-given url wins when kwnt knows its public address', async () => {+ const { send } = fake([200, { code: 'kl1.abc', url: 'https://public.example/#kwnt_token=kl1.abc', expires_in: 900 }]);+ assert.equal((await m.createSigninLink('http://10.0.0.2:8899', NOW, send)).url, 'https://public.example/#kwnt_token=kl1.abc');+});++test('a refused or empty answer is an error, never a half link', async () => {+ await assert.rejects(m.createSigninLink('https://x', NOW, fake([403, { error: 'person only' }]).send), /403/);+ await assert.rejects(m.createSigninLink('https://x', NOW, fake([200, { url: null }]).send), /no sign-in code/);+});++// ---------------------------------------------------------------- the states++test('before showing: just the button, no QR and no code on the page', () => {+ const html = m.view({ kind: 'idle' }, NOW);+ assert.deepEqual(buttons(html), ['Add a phone or browser']);+ assert.ok(!html.includes('<svg role'), 'no QR');+ assert.ok(!html.includes('kwnt_token'));+});++test('showing: the QR, the copyable link, the warning, 15:00 left, New code and Hide', () => {+ const html = m.view(showing, NOW);+ const t = text(html);+ assert.match(html, /aria-label="QR code for the one-time sign-in link"/);+ assert.match(html, /<path d="M\d/);+ assert.match(html, new RegExp(`value="${URL_.replace(/[.]/g, '\\.')}"`));+ assert.match(t, /Anyone who scans this can sign in once\. Don't share or screenshot it\./);+ assert.match(t, /Works once · 15:00 left/);+ assert.deepEqual(buttons(html), ['Copy link', 'New code', 'Hide']);+});++test('the countdown runs down with the clock', () => {+ assert.match(text(m.view(showing, NOW + (14 * 60 + 1) * 1000)), /0:59 left/);+});++test('copy feedback: Copied, or a hint when the clipboard refused', () => {+ assert.ok(buttons(m.view(showing, NOW, 'yes')).includes('Copied'));+ assert.match(text(m.view(showing, NOW, 'failed')), /Couldn't copy\. Select the link and copy it yourself\./);+});++test('expired: the code and QR are gone; New code and Hide remain', () => {+ const html = m.view({ kind: 'expired' }, NOW);+ assert.ok(!html.includes('kwnt_token') && !html.includes('<svg role'));+ assert.match(text(html), /The code expired, so it was hidden/);+ assert.deepEqual(buttons(html), ['New code', 'Hide']);+});++test('signed in: "Signed in ✓" with the browser, no QR, and Add another', () => {+ const html = m.view({ kind: 'signed_in', browser: 'Safari on iPhone' }, NOW);+ assert.match(text(html), /Signed in ✓ Safari on iPhone signed in with the code/);+ assert.ok(!html.includes('kwnt_token'));+ assert.deepEqual(buttons(html), ['Add another', 'Done']);+});++test('a failed mint says so and keeps the button', () => {+ const html = m.view({ kind: 'error', message: 'The server answered 403.' }, NOW);+ assert.match(text(html), /Couldn't make a sign-in code: The server answered 403\./);+ assert.deepEqual(buttons(html), ['Add a phone or browser']);+});++// ---------------------------------------------------------------- "Signed in ✓" detection++test('only a new link session counts as the phone that scanned', () => {+ const s = (id, via, current = false) => ({ id, via, current, browser: id, ip: '', created_at: '', last_seen: '' });+ const known = new Set(['a', 'b']);+ assert.equal(m.newLinkSession([s('a', 'link', true), s('b', 'link')], known), null, 'old sessions');+ assert.equal(m.newLinkSession([s('a', 'token', true), s('c', 'device')], known), null, 'device approval is not this code');+ assert.equal(m.newLinkSession([s('a', 'token', true), s('c', 'link')], known)?.id, 'c');+});++// ---------------------------------------------------------------- the QR itself++test('the QR is drawn locally, with a quiet zone, and is the same for the same link', () => {+ const a = m.qrPath(URL_);+ assert.ok(a.size >= 29 + 8 - 4, `size ${a.size}`); // version ≥ 3 for this length, 4-module border+ assert.ok(a.d.startsWith('M4 4h1v1h-1z'), 'finder pattern starts after the border');+ assert.deepEqual(m.qrPath(URL_), a);+ assert.notEqual(m.qrPath(URL_ + 'x').d, a.d);+});++test('no QR service and nothing logged: the component never fetches an image or uses console', () => {+ const src = readFileSync(new URL('../src/components/DeviceSignIn.tsx', import.meta.url), 'utf8');+ assert.ok(!/console\./.test(src));+ assert.ok(!/<img[^>]*qr/i.test(src) && !/api\.qrserver|chart\.googleapis|quickchart/i.test(src));+ assert.ok(!/localStorage|sessionStorage/.test(src.slice(src.indexOf('Add a phone or browser'))));+});++// ---------------------------------------------------------------- local mode++test('hidden on the Mac in local/no-token mode and on servers without device login', () => {+ assert.equal(m.signedInDevicesVisible(false, true), false, 'local / no sign-in');+ assert.equal(m.signedInDevicesVisible(true, false), false, 'older server');+ assert.equal(m.signedInDevicesVisible(true, true), true);+ const settings = readFileSync(new URL('../src/components/SettingsModal.tsx', import.meta.url), 'utf8');+ assert.match(settings, /\{signedInDevicesVisible\(authRequired, deviceLogin\) && <SignedInDevices \/>\}/);+});