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.

Saved passwords UI: masked list, Reveal, confirm-save of captures, person token screen

Lin (kwant bot)1748d16e709f
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index bcf4ce8b..6d357bc7 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -1153,6 +1153,9 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
dropApproval(ticketId);
if (!res.ok) pushToast('This request expired', 'The bot is no longer waiting for this answer.');
refreshAwayCount(300);
+ } else if (res.status === 401) {
+ // Person-only: the token dialog is open; the card stays so the person can answer again.
+ pushToast('Enter your access token', 'Answering approval cards needs your token. Then answer the card again.');
} else {
pushToast("Couldn't send your answer", `Request failed (HTTP ${res.status}). Try again.`);
}
@@ -2599,6 +2602,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
setNewAgentTeam(null);
}}
joinTeamName={newAgentTeam?.name}
+ approvalsOff={space.approvals === 'off'}
takenNames={kwants.map((k) => k.name)}
profiles={profiles}
onManageProfiles={openSettings}
@@ -2628,6 +2632,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
onSubmit={(data) => (editingKwant ? handleUpdateAgent(editingKwant, data) : undefined)}
onRequestDelete={editingKwant ? () => setDeletingKwant(editingKwant) : undefined}
onApprovalsChanged={refreshRoster}
+ approvalsOff={approvalsOff(editingKwant)}
/>
{deletingKwant && (
diff --git a/frontend/src/auth.ts b/frontend/src/auth.ts
index 9c5e1f0f..0e02fd00 100644
--- a/frontend/src/auth.ts
+++ b/frontend/src/auth.ts
@@ -4,10 +4,28 @@ import { getCurrentSpace, withSpace } from './spaces';
/** Fired on `window` when an `/api` call answers 401 (the token is missing or no longer valid). */
export const UNAUTHORIZED_EVENT = 'kwnt:unauthorized';
+/** Fired when a person-only route (saved passwords, answering approvals, the approvals switch)
+ * answers 401 `{person_only:true}`: the rest of the app works, only this action needs the token. */
+export const PERSON_TOKEN_EVENT = 'kwnt:person-token';
+/** Fired after the person signed in from that prompt, so open panels can load again. */
+export const PERSON_SIGNED_IN_EVENT = 'kwnt:person-signed-in';
export interface AuthStatus {
auth_required: boolean;
authenticated: boolean;
+ /** Person-only actions need the token even where the rest of the API doesn't (newer servers). */
+ person_auth_required?: boolean;
+ person_authenticated?: boolean;
+}
+
+/** Asks for the token for a person-only action, as if one had answered 401. */
+export function requestPersonToken(): void {
+ if (typeof window !== 'undefined') window.dispatchEvent(new Event(PERSON_TOKEN_EVENT));
+}
+
+/** Whether a 401 body is the person-only answer, not "the whole API needs the token". */
+export function isPersonOnlyBody(body: unknown): boolean {
+ return !!body && typeof body === 'object' && (body as { person_only?: unknown }).person_only === true;
}
/** Splits `#kwnt_token=<t>` off a location hash, keeping any other fragment parameters. */
@@ -44,9 +62,13 @@ export function installUnauthorizedListener(): void {
window.fetch = async (input: RequestInfo | URL, init?: RequestInit) => {
if (typeof input === 'string') input = withSpace(input, window.location.origin, getCurrentSpace());
const res = await original(input, init);
- if (res.status === 401) {
+ // `kwntQuiet`: a background load that shows its own "needs the token" state instead.
+ if (res.status === 401 && !(init as { kwntQuiet?: boolean } | undefined)?.kwntQuiet) {
const url = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;
- if (isGuardedApiUrl(url, window.location.origin)) window.dispatchEvent(new Event(UNAUTHORIZED_EVENT));
+ if (isGuardedApiUrl(url, window.location.origin)) {
+ const body = await res.clone().json().catch(() => null);
+ window.dispatchEvent(new Event(isPersonOnlyBody(body) ? PERSON_TOKEN_EVENT : UNAUTHORIZED_EVENT));
+ }
}
return res;
};
diff --git a/frontend/src/components/AuthGate.tsx b/frontend/src/components/AuthGate.tsx
index 665babd3..afb9fc15 100644
--- a/frontend/src/components/AuthGate.tsx
+++ b/frontend/src/components/AuthGate.tsx
@@ -1,7 +1,9 @@
import React, { createContext, useCallback, useContext, useEffect, useRef, useState } from 'react';
-import { KeyRound, Loader2, RefreshCw, Terminal } from 'lucide-react';
+import { KeyRound, Loader2, RefreshCw, Terminal, X } from 'lucide-react';
import { ModernAvatar } from './ModernAvatar';
import {
+ PERSON_SIGNED_IN_EVENT,
+ PERSON_TOKEN_EVENT,
UNAUTHORIZED_EVENT,
consumeTokenLink,
endSession,
@@ -31,8 +33,16 @@ installUnauthorizedListener();
/** Shows its children once the API answers, and the token screen while it needs a token. */
export const AuthGate: React.FC<{ children: React.ReactNode }> = ({ children }) => {
const [state, setState] = useState<GateState>({ kind: 'checking' });
+ // A person-only action (passwords, approvals) answered 401: ask for the token over the app.
+ const [personPrompt, setPersonPrompt] = useState(false);
const checking = useRef(false);
+ useEffect(() => {
+ const onPerson = () => setPersonPrompt(true);
+ window.addEventListener(PERSON_TOKEN_EVENT, onPerson);
+ return () => window.removeEventListener(PERSON_TOKEN_EVENT, onPerson);
+ }, []);
+
const check = useCallback(async (notice: string | null = null) => {
if (checking.current) return;
checking.current = true;
@@ -74,7 +84,20 @@ export const AuthGate: React.FC<{ children: React.ReactNode }> = ({ children })
}, []);
if (state.kind === 'ready') {
- return <AuthContext.Provider value={{ authRequired: state.authRequired, signOut }}>{children}</AuthContext.Provider>;
+ return (
+ <AuthContext.Provider value={{ authRequired: state.authRequired, signOut }}>
+ {children}
+ {personPrompt && (
+ <PersonTokenDialog
+ onClose={() => setPersonPrompt(false)}
+ onSignedIn={() => {
+ setPersonPrompt(false);
+ window.dispatchEvent(new Event(PERSON_SIGNED_IN_EVENT));
+ }}
+ />
+ )}
+ </AuthContext.Provider>
+ );
}
return (
@@ -113,7 +136,44 @@ export const AuthGate: React.FC<{ children: React.ReactNode }> = ({ children })
);
};
-const TokenForm: React.FC<{ notice: string | null; onSignedIn: () => void }> = ({ notice, onSignedIn }) => {
+/** 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 }) => {
+ useEffect(() => {
+ const onKey = (e: KeyboardEvent) => {
+ if (e.key === 'Escape') onClose();
+ };
+ window.addEventListener('keydown', onKey);
+ return () => window.removeEventListener('keydown', onKey);
+ }, [onClose]);
+ return (
+ <div className="fixed inset-0 z-[100] flex items-center justify-center bg-black/70 p-4 font-sans" onClick={onClose}>
+ <div
+ role="dialog"
+ aria-modal="true"
+ aria-labelledby="kwnt-person-token-title"
+ className="relative w-full max-w-md bg-zinc-900 border border-zinc-800 rounded-2xl p-6 shadow-2xl text-zinc-100"
+ onClick={(e) => e.stopPropagation()}
+ >
+ <button
+ type="button"
+ onClick={onClose}
+ aria-label="Close"
+ 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>
+ <TokenForm notice={null} onSignedIn={onSignedIn} personOnly onCancel={onClose} />
+ </div>
+ </div>
+ );
+};
+
+const TokenForm: React.FC<{ notice: string | null; onSignedIn: () => void; personOnly?: boolean; onCancel?: () => void }> = ({
+ notice,
+ onSignedIn,
+ personOnly = false,
+ onCancel,
+}) => {
const [token, setToken] = useState('');
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
@@ -141,11 +201,13 @@ const TokenForm: React.FC<{ notice: string | null; onSignedIn: () => void }> = (
return (
<form onSubmit={submit} className="space-y-4">
<div className="space-y-1.5">
- <h2 className="flex items-center gap-2 text-sm font-medium">
- <KeyRound size={15} className="text-sky-400" /> Enter your access token
+ <h2 id={personOnly ? 'kwnt-person-token-title' : undefined} className="flex items-center gap-2 text-sm font-medium">
+ <KeyRound size={15} className="text-sky-400" /> {personOnly ? 'Confirm it’s you' : 'Enter your access token'}
</h2>
<p className="text-xs text-zinc-400 leading-relaxed">
- This server is reachable from other machines, so it needs its token once per browser. Get it on the server:
+ {personOnly
+ ? 'Saved passwords and answers to approval cards need your access token, even on this computer, so a bot can’t reach them. You need it once per browser. Get it on the server:'
+ : 'This server is reachable from other machines, so it needs its token once per browser. Get it on the server:'}
</p>
<div className="space-y-1 text-[11px] font-mono text-zinc-300">
<p className="flex items-center gap-1.5 bg-zinc-950 border border-zinc-800 rounded-md px-2 py-1">
@@ -180,13 +242,24 @@ const TokenForm: React.FC<{ notice: string | null; onSignedIn: () => void }> = (
</p>
)}
</div>
- <button
- type="submit"
- disabled={busy || !token.trim()}
- className="w-full flex items-center justify-center gap-1.5 px-4 py-2 rounded-lg text-xs font-medium text-white bg-sky-600 hover:bg-sky-500 transition-colors disabled:opacity-50"
- >
- {busy && <Loader2 size={13} className="animate-spin motion-reduce:animate-none" />} Continue
- </button>
+ <div className="flex gap-2">
+ {onCancel && (
+ <button
+ type="button"
+ onClick={onCancel}
+ className="flex-1 px-4 py-2 rounded-lg text-xs font-medium text-zinc-200 bg-zinc-800 hover:bg-zinc-700 border border-zinc-700 transition-colors"
+ >
+ Not now
+ </button>
+ )}
+ <button
+ type="submit"
+ disabled={busy || !token.trim()}
+ className="flex-1 w-full flex items-center justify-center gap-1.5 px-4 py-2 rounded-lg text-xs font-medium text-white bg-sky-600 hover:bg-sky-500 transition-colors disabled:opacity-50"
+ >
+ {busy && <Loader2 size={13} className="animate-spin motion-reduce:animate-none" />} Continue
+ </button>
+ </div>
<p className="text-[11px] text-zinc-500">The browser keeps you signed in for a year. Anyone with the token controls this server.</p>
</form>
);
diff --git a/frontend/src/components/KwantToolsPicker.tsx b/frontend/src/components/KwantToolsPicker.tsx
index 97e12460..ad5fce36 100644
--- a/frontend/src/components/KwantToolsPicker.tsx
+++ b/frontend/src/components/KwantToolsPicker.tsx
@@ -8,6 +8,8 @@ interface KwantToolsPickerProps {
selected: string[];
onChange: (ids: string[]) => void;
onManageServers?: () => void;
+ /** The bot's approvals are off: its tools run without a card. */
+ approvalsOff?: boolean;
}
/**
@@ -15,7 +17,7 @@ interface KwantToolsPickerProps {
* kwant unless switched off here. A server paused in Tools shows greyed and keeps this kwant's
* choice, so turning it back on there restores it.
*/
-export const KwantToolsPicker: React.FC<KwantToolsPickerProps> = ({ model, selected, onChange, onManageServers }) => {
+export const KwantToolsPicker: React.FC<KwantToolsPickerProps> = ({ model, selected, onChange, onManageServers, approvalsOff = false }) => {
const [servers, setServers] = useState<McpServer[] | null>(null);
const [keys, setKeys] = useState<EngineKeys>({ anthropic: false, openai: false, xai: false });
@@ -47,7 +49,10 @@ export const KwantToolsPicker: React.FC<KwantToolsPickerProps> = ({ model, selec
<div>
<div className="flex items-center justify-between mb-1">
<label className="text-xs font-medium text-zinc-400">
- Tools this bot can use <span className="text-zinc-600 font-normal">· asks you before each use</span>
+ Tools this bot can use{' '}
+ <span className={`font-normal ${approvalsOff ? 'text-amber-300/90' : 'text-zinc-600'}`}>
+ {approvalsOff ? '· runs them without asking (approvals off)' : '· asks you before each use'}
+ </span>
</label>
{onManageServers && servers && servers.length > 0 && (
<button type="button" onClick={onManageServers} className="text-[11px] text-sky-300 hover:text-sky-200">
diff --git a/frontend/src/components/NewAgentModal.tsx b/frontend/src/components/NewAgentModal.tsx
index 609591c9..d8801568 100644
--- a/frontend/src/components/NewAgentModal.tsx
+++ b/frontend/src/components/NewAgentModal.tsx
@@ -72,6 +72,8 @@ interface NewAgentModalProps {
onRequestDelete?: () => void;
/** Editing only: the approvals override saved; load bots again for the markers. */
onApprovalsChanged?: () => void;
+ /** Whether this bot runs tools without asking: the bot's effective value, or the space's for a new bot. */
+ approvalsOff?: boolean;
}
export const NewAgentModal: React.FC<NewAgentModalProps> = ({
@@ -94,6 +96,7 @@ export const NewAgentModal: React.FC<NewAgentModalProps> = ({
pendingSkills = 0,
onRequestDelete,
onApprovalsChanged,
+ approvalsOff = false,
}) => {
const [tab, setTab] = useState<EditTab>('profile');
const [name, setName] = useState('');
@@ -109,6 +112,9 @@ export const NewAgentModal: React.FC<NewAgentModalProps> = ({
const [mcpIds, setMcpIds] = useState<string[] | undefined>(undefined);
const [profileId, setProfileId] = useState<string | null>(null);
const [failover, setFailover] = useState(true);
+ // Follows the prop until the person changes this bot's approvals here.
+ const [toolsRunFree, setToolsRunFree] = useState(approvalsOff);
+ useEffect(() => setToolsRunFree(approvalsOff), [approvalsOff, isOpen]);
const isEdit = !!initial;
const engines = useEngines(isOpen);
const { reload: reloadEngines } = engines;
@@ -431,10 +437,19 @@ export const NewAgentModal: React.FC<NewAgentModalProps> = ({
</div>
)}
- {isEdit && kwantId && <BotApprovalsSetting kwantId={kwantId} kwantName={initial?.name ?? name} onChanged={() => onApprovalsChanged?.()} />}
+ {isEdit && kwantId && (
+ <BotApprovalsSetting
+ kwantId={kwantId}
+ kwantName={initial?.name ?? name}
+ onChanged={(s) => {
+ setToolsRunFree(s.approvals_effective === 'off');
+ onApprovalsChanged?.();
+ }}
+ />
+ )}
{mcpIds !== undefined && (
- <KwantToolsPicker model={model} selected={mcpIds} onChange={setMcpIds} onManageServers={onManageServers} />
+ <KwantToolsPicker model={model} selected={mcpIds} onChange={setMcpIds} onManageServers={onManageServers} approvalsOff={toolsRunFree} />
)}
<div>
diff --git a/frontend/src/components/SavedPasswordsPanel.tsx b/frontend/src/components/SavedPasswordsPanel.tsx
new file mode 100644
index 00000000..744c06d3
--- /dev/null
+++ b/frontend/src/components/SavedPasswordsPanel.tsx
@@ -0,0 +1,486 @@
+import React, { useCallback, useEffect, useRef, useState } from 'react';
+import { AlertTriangle, Check, Copy, ExternalLink, Eye, EyeOff, Key, KeyRound, Loader2, Lock, Plus, Search, ShieldCheck, Trash2 } from 'lucide-react';
+import { PERSON_SIGNED_IN_EVENT, requestPersonToken } from '../auth';
+import { playSfx } from '../audio/chiptune';
+import {
+ PROBLEM_TEXT,
+ PasswordsError,
+ PasswordsProblem,
+ PendingLogin,
+ REVEAL_MS,
+ SavedLogin,
+ filterLogins,
+ loginMatchesPage,
+ originFromInput,
+ originLabel,
+ passwordsApi,
+} from '../savedPasswords';
+
+export interface SavedPasswordsState {
+ logins: SavedLogin[];
+ pending: PendingLogin | null;
+ /** True until the first answer. */
+ loading: boolean;
+ problem: PasswordsProblem | null;
+ reload: () => void;
+}
+
+/**
+ * Loads the saved logins for a team, channel or bot. No event fires when the browser catches a
+ * login, so `refreshKey` (a new screenshot or page) loads again, at most every 1.5s.
+ */
+export function useSavedPasswords(sandboxId: string | undefined, refreshKey: unknown): SavedPasswordsState {
+ const [logins, setLogins] = useState<SavedLogin[]>([]);
+ const [pending, setPending] = useState<PendingLogin | null>(null);
+ const [loading, setLoading] = useState(true);
+ const [problem, setProblem] = useState<PasswordsProblem | null>(null);
+ const seq = useRef(0);
+ const usable = !!sandboxId && sandboxId !== 'default';
+
+ const reload = useCallback(() => {
+ if (!usable) return;
+ const mine = ++seq.current;
+ passwordsApi
+ .list(sandboxId!)
+ .then((l) => {
+ if (mine !== seq.current) return;
+ setLogins(l.passwords);
+ setPending(l.pending);
+ setProblem(null);
+ })
+ .catch((e: unknown) => {
+ if (mine !== seq.current) return;
+ setProblem(e instanceof PasswordsError ? e.problem : 'error');
+ setLogins([]);
+ setPending(null);
+ })
+ .finally(() => mine === seq.current && setLoading(false));
+ }, [sandboxId, usable]);
+
+ useEffect(() => {
+ setLogins([]);
+ setPending(null);
+ setProblem(null);
+ setLoading(usable);
+ reload();
+ }, [reload, usable]);
+
+ const first = useRef(true);
+ useEffect(() => {
+ if (first.current) {
+ first.current = false;
+ return;
+ }
+ const t = setTimeout(reload, 1500);
+ return () => clearTimeout(t);
+ }, [refreshKey, reload]);
+
+ useEffect(() => {
+ window.addEventListener(PERSON_SIGNED_IN_EVENT, reload);
+ return () => window.removeEventListener(PERSON_SIGNED_IN_EVENT, reload);
+ }, [reload]);
+
+ return { logins, pending, loading, problem, reload };
+}
+
+const errorText = (e: unknown, fallback: string) => (e instanceof PasswordsError || e instanceof Error ? e.message : fallback);
+
+/** "Save password for <site> as <user>?" for a login the browser caught. Nothing is saved until Save. */
+export const PendingLoginPrompt: React.FC<{
+ sandboxId: string;
+ pending: PendingLogin;
+ onDone: () => void;
+}> = ({ sandboxId, pending, onDone }) => {
+ const [busy, setBusy] = useState<'save' | 'discard' | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const act = async (kind: 'save' | 'discard') => {
+ setBusy(kind);
+ setError(null);
+ try {
+ if (kind === 'save') await passwordsApi.savePending(sandboxId);
+ else await passwordsApi.discardPending(sandboxId);
+ playSfx(kind === 'save' ? 'coin' : 'click');
+ onDone();
+ } catch (e) {
+ setError(errorText(e, 'Couldn’t do that. Try again.'));
+ // 404: nothing is waiting any more (saved or discarded elsewhere).
+ if (e instanceof PasswordsError && e.status === 404) onDone();
+ } finally {
+ setBusy(null);
+ }
+ };
+ return (
+ <div role="region" aria-label="Save password?" data-pending-login className="mx-3 mt-2 p-2.5 rounded-xl border border-sky-500/30 bg-sky-500/5 text-xs space-y-2">
+ <p className="flex items-start gap-2 text-zinc-200 leading-snug">
+ <KeyRound size={14} className="text-sky-400 flex-shrink-0 mt-px" aria-hidden="true" />
+ <span>
+ Save password for <span className="font-semibold break-all">{originLabel(pending.origin)}</span>
+ {pending.username ? (
+ <>
+ {' '}as <span className="font-mono break-all">{pending.username}</span>
+ </>
+ ) : null}
+ ?
+ </span>
+ </p>
+ <p className="text-[11px] text-zinc-500 pl-[22px]">It’s filled in only on this exact address. Nothing is saved until you choose Save.</p>
+ {error && (
+ <p role="alert" className="flex items-center gap-1.5 text-[11px] text-rose-300 pl-[22px]">
+ <AlertTriangle size={12} aria-hidden="true" /> {error}
+ </p>
+ )}
+ <div className="flex justify-end gap-1.5">
+ <button
+ type="button"
+ disabled={!!busy}
+ onClick={() => act('discard')}
+ className="px-2.5 py-1.5 rounded-lg text-[11px] font-medium bg-zinc-800 hover:bg-zinc-700 text-zinc-200 disabled:opacity-50"
+ >
+ {busy === 'discard' ? 'Discarding…' : 'Don’t save'}
+ </button>
+ <button
+ type="button"
+ disabled={!!busy}
+ onClick={() => act('save')}
+ className="px-2.5 py-1.5 rounded-lg text-[11px] font-semibold bg-sky-500 hover:bg-sky-400 text-zinc-950 disabled:opacity-50"
+ >
+ {busy === 'save' ? 'Saving…' : 'Save'}
+ </button>
+ </div>
+ </div>
+ );
+};
+
+/** The panel's own message when the list can't be shown. `locked` is ready for a store that unlocks. */
+export const PasswordsProblemNotice: React.FC<{ problem: PasswordsProblem; onRetry: () => void }> = ({ problem, onRetry }) => (
+ <div className="text-center py-10 px-4 text-xs" data-passwords-problem={problem}>
+ <Lock size={28} className="mx-auto mb-2 opacity-40 text-zinc-400" aria-hidden="true" />
+ <p className="text-zinc-300 leading-relaxed">{PROBLEM_TEXT[problem]}</p>
+ <div className="mt-3 flex justify-center">
+ {problem === 'needs-token' ? (
+ <button
+ type="button"
+ onClick={requestPersonToken}
+ className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-[11px] font-medium text-white bg-sky-600 hover:bg-sky-500"
+ >
+ <KeyRound size={12} aria-hidden="true" /> Enter access token
+ </button>
+ ) : (
+ <button type="button" onClick={onRetry} className="px-3 py-1.5 rounded-lg text-[11px] font-medium bg-zinc-800 hover:bg-zinc-700 text-zinc-200">
+ Try again
+ </button>
+ )}
+ </div>
+ </div>
+);
+
+interface RowProps {
+ sandboxId: string;
+ login: SavedLogin;
+ onThisPage: boolean;
+ onOpen?: (origin: string) => void;
+ onDeleted: () => void;
+ /** Tests start a row revealed or asking to delete. */
+ initialRevealed?: string | null;
+ initialConfirmDelete?: boolean;
+}
+
+/** One saved login: site and username; the password only after Reveal, for REVEAL_MS. */
+export const SavedLoginRow: React.FC<RowProps> = ({ sandboxId, login, onThisPage, onOpen, onDeleted, initialRevealed = null, initialConfirmDelete = false }) => {
+ const [revealed, setRevealed] = useState<string | null>(initialRevealed);
+ const [revealing, setRevealing] = useState(false);
+ const [confirmDelete, setConfirmDelete] = useState(initialConfirmDelete);
+ const [deleting, setDeleting] = useState(false);
+ const [copied, setCopied] = useState<'user' | 'pass' | null>(null);
+ const [error, setError] = useState<string | null>(null);
+
+ // A revealed password disappears on its own; it's never kept anywhere else.
+ useEffect(() => {
+ if (revealed === null) return;
+ const t = setTimeout(() => setRevealed(null), REVEAL_MS);
+ return () => clearTimeout(t);
+ }, [revealed]);
+
+ const reveal = async () => {
+ if (revealed !== null) {
+ setRevealed(null);
+ return;
+ }
+ setRevealing(true);
+ setError(null);
+ try {
+ setRevealed(await passwordsApi.reveal(sandboxId, login.id));
+ playSfx('click');
+ } catch (e) {
+ setError(errorText(e, 'Couldn’t show this password.'));
+ } finally {
+ setRevealing(false);
+ }
+ };
+
+ const remove = async () => {
+ setDeleting(true);
+ setError(null);
+ try {
+ await passwordsApi.remove(sandboxId, login.id);
+ playSfx('click');
+ onDeleted();
+ } catch (e) {
+ setError(errorText(e, 'Couldn’t delete this login.'));
+ setDeleting(false);
+ }
+ };
+
+ const copy = (text: string, which: 'user' | 'pass') => {
+ navigator.clipboard?.writeText(text).catch(() => undefined);
+ setCopied(which);
+ setTimeout(() => setCopied((c) => (c === which ? null : c)), 2000);
+ };
+
+ const site = originLabel(login.origin || `https://${login.domain}`);
+ return (
+ <li
+ data-login-row={login.id}
+ className={`p-2.5 rounded-xl border text-xs bg-zinc-900/60 ${onThisPage ? 'border-emerald-500/40' : 'border-zinc-800/80 hover:border-zinc-700'}`}
+ >
+ <div className="flex items-center justify-between gap-2 mb-1.5">
+ <div className="flex items-center gap-1.5 min-w-0">
+ <span className="font-semibold text-zinc-200 truncate" title={login.origin}>
+ {site}
+ </span>
+ {onThisPage && (
+ <span className="px-1.5 rounded bg-emerald-500/10 text-emerald-300 border border-emerald-500/20 text-[9px] font-mono flex-shrink-0">This page</span>
+ )}
+ </div>
+ <div className="flex items-center gap-0.5 flex-shrink-0">
+ {onOpen && login.origin && (
+ <button
+ type="button"
+ onClick={() => onOpen(login.origin)}
+ aria-label={`Open ${site}`}
+ title="Open this site in the browser"
+ className="text-zinc-400 hover:text-sky-400 p-1.5 rounded hover:bg-zinc-800/60"
+ >
+ <ExternalLink size={12} />
+ </button>
+ )}
+ <button
+ type="button"
+ onClick={() => setConfirmDelete(true)}
+ aria-label={`Delete login for ${site}`}
+ title="Delete"
+ className="text-zinc-500 hover:text-rose-400 p-1.5 rounded hover:bg-zinc-800/60"
+ >
+ <Trash2 size={12} />
+ </button>
+ </div>
+ </div>
+
+ <div className="flex items-center justify-between py-1 px-2 rounded bg-zinc-950/70 border border-zinc-800/50 mb-1">
+ <span className="text-[11px] font-mono text-zinc-300 truncate">{login.username || <span className="text-zinc-500 font-sans">No username</span>}</span>
+ {login.username && (
+ <button type="button" onClick={() => copy(login.username, 'user')} aria-label="Copy username" className="text-zinc-500 hover:text-zinc-200 p-1 ml-1">
+ {copied === 'user' ? <Check size={11} className="text-emerald-400" /> : <Copy size={11} />}
+ </button>
+ )}
+ </div>
+
+ <div className="flex items-center justify-between py-1 px-2 rounded bg-zinc-950/70 border border-zinc-800/50">
+ <span className="text-[11px] font-mono text-zinc-400 truncate" aria-live="polite">
+ {revealed !== null ? <span data-revealed className="text-zinc-100">{revealed}</span> : <span aria-label="Password hidden">••••••••••••</span>}
+ </span>
+ <div className="flex items-center gap-0.5 ml-1 flex-shrink-0">
+ {revealed !== null && (
+ <button type="button" onClick={() => copy(revealed, 'pass')} aria-label="Copy password" className="text-zinc-500 hover:text-zinc-200 p-1">
+ {copied === 'pass' ? <Check size={11} className="text-emerald-400" /> : <Copy size={11} />}
+ </button>
+ )}
+ <button
+ type="button"
+ onClick={reveal}
+ disabled={revealing}
+ className="flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] text-zinc-400 hover:text-zinc-100 hover:bg-zinc-800/60 disabled:opacity-50"
+ >
+ {revealing ? <Loader2 size={11} className="animate-spin motion-reduce:animate-none" /> : revealed !== null ? <EyeOff size={11} /> : <Eye size={11} />}
+ {revealed !== null ? 'Hide' : 'Reveal'}
+ </button>
+ </div>
+ </div>
+ {revealed !== null && <p className="mt-1 text-[10px] text-zinc-500">Hides again in 30 seconds.</p>}
+
+ {confirmDelete && (
+ <div role="alertdialog" aria-label={`Delete login for ${site}?`} className="mt-2 p-2 rounded-lg border border-rose-500/30 bg-rose-500/5 space-y-1.5">
+ <p className="text-[11px] text-zinc-200">Delete this login? The bots can’t sign in to {site} with it any more.</p>
+ <div className="flex justify-end gap-1.5">
+ <button type="button" autoFocus onClick={() => setConfirmDelete(false)} className="px-2.5 py-1 rounded text-[11px] bg-zinc-800 hover:bg-zinc-700 text-zinc-200">
+ Keep
+ </button>
+ <button type="button" disabled={deleting} onClick={remove} className="px-2.5 py-1 rounded text-[11px] font-semibold bg-rose-500 hover:bg-rose-400 text-zinc-950 disabled:opacity-50">
+ {deleting ? 'Deleting…' : 'Delete'}
+ </button>
+ </div>
+ </div>
+ )}
+ {error && (
+ <p role="alert" className="mt-1.5 flex items-center gap-1.5 text-[11px] text-rose-300">
+ <AlertTriangle size={12} aria-hidden="true" /> {error}
+ </p>
+ )}
+ {login.last_used && <p className="mt-1 text-[9px] text-zinc-500 text-right">Last used {new Date(login.last_used).toLocaleDateString()}</p>}
+ </li>
+ );
+};
+
+const AddLoginForm: React.FC<{ sandboxId: string; onSaved: () => void; onCancel: () => void }> = ({ sandboxId, onSaved, onCancel }) => {
+ const [site, setSite] = useState('');
+ const [username, setUsername] = useState('');
+ const [password, setPassword] = useState('');
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+ const origin = originFromInput(site);
+
+ const submit = async (e: React.FormEvent) => {
+ e.preventDefault();
+ if (!origin) {
+ setError('Enter an address like example.com or https://example.com.');
+ return;
+ }
+ if (!password) return;
+ setBusy(true);
+ setError(null);
+ try {
+ await passwordsApi.add(sandboxId, origin, username.trim(), password);
+ setPassword('');
+ playSfx('coin');
+ onSaved();
+ } catch (err) {
+ setError(errorText(err, 'Couldn’t save this login.'));
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ const field = 'w-full px-2 py-1.5 bg-zinc-950 border border-zinc-800 rounded text-[11px] text-zinc-200 focus:outline-none focus:border-sky-500 font-mono';
+ return (
+ <form onSubmit={submit} className="p-3 bg-zinc-900/90 border border-sky-500/30 rounded-xl space-y-2 text-xs">
+ <div className="text-[11px] font-semibold text-sky-400 flex items-center gap-1">
+ <Key size={12} aria-hidden="true" /> Add a login
+ </div>
+ <label className="block">
+ <span className="text-[10px] text-zinc-400 block mb-0.5">Site</span>
+ <input type="text" required value={site} onChange={(e) => setSite(e.target.value)} placeholder="example.com" className={field} autoComplete="off" spellCheck={false} />
+ {origin && <span className="text-[10px] text-zinc-500 block mt-0.5">Filled in only on {origin}</span>}
+ </label>
+ <label className="block">
+ <span className="text-[10px] text-zinc-400 block mb-0.5">Username or email</span>
+ <input type="text" value={username} onChange={(e) => setUsername(e.target.value)} placeholder="[email protected]" className={field} autoComplete="off" spellCheck={false} />
+ </label>
+ <label className="block">
+ <span className="text-[10px] text-zinc-400 block mb-0.5">Password</span>
+ <input type="password" required value={password} onChange={(e) => setPassword(e.target.value)} className={field} autoComplete="new-password" />
+ </label>
+ {error && (
+ <p role="alert" className="flex items-center gap-1.5 text-[11px] text-rose-300">
+ <AlertTriangle size={12} aria-hidden="true" /> {error}
+ </p>
+ )}
+ <div className="flex justify-end gap-1.5 pt-1">
+ <button type="button" onClick={onCancel} className="px-2.5 py-1 text-[11px] rounded bg-zinc-800 hover:bg-zinc-700 text-zinc-300">
+ Cancel
+ </button>
+ <button type="submit" disabled={busy || !password} className="px-2.5 py-1 text-[11px] rounded bg-sky-500 hover:bg-sky-400 text-zinc-950 font-semibold disabled:opacity-50">
+ {busy ? 'Saving…' : 'Save login'}
+ </button>
+ </div>
+ </form>
+ );
+};
+
+/** The Saved logins tab: site and username only, Reveal per row, Delete with a confirm. */
+export const SavedPasswordsPanel: React.FC<{
+ sandboxId: string;
+ state: SavedPasswordsState;
+ pageUrl: string;
+ onOpen?: (origin: string) => void;
+ /** Tests open the add form. */
+ initialAdding?: boolean;
+}> = ({ sandboxId, state, pageUrl, onOpen, initialAdding = false }) => {
+ const [query, setQuery] = useState('');
+ const [adding, setAdding] = useState(initialAdding);
+ const shown = filterLogins(state.logins, query);
+ const blocked = state.problem !== null;
+
+ return (
+ <div className="flex-1 flex flex-col p-3 gap-2 overflow-hidden bg-zinc-950" data-saved-passwords>
+ {!blocked && (
+ <div className="flex items-center gap-1.5">
+ <label className="flex-1 flex items-center gap-1.5 px-2 py-1.5 bg-zinc-900 border border-zinc-800 rounded-lg text-xs focus-within:border-sky-500">
+ <Search size={12} className="text-zinc-500 flex-shrink-0" aria-hidden="true" />
+ <span className="sr-only">Search saved logins</span>
+ <input
+ type="search"
+ value={query}
+ onChange={(e) => setQuery(e.target.value)}
+ placeholder="Search sites or usernames"
+ className="w-full bg-transparent text-zinc-200 text-[11px] focus:outline-none placeholder:text-zinc-600"
+ />
+ </label>
+ <button
+ type="button"
+ aria-expanded={adding}
+ onClick={() => setAdding((a) => !a)}
+ className={`flex items-center gap-1 px-2.5 py-1.5 rounded-lg text-[11px] font-medium transition-colors ${
+ adding ? 'bg-zinc-800 text-zinc-200' : 'bg-sky-500/10 text-sky-400 border border-sky-500/20 hover:bg-sky-500/20'
+ }`}
+ >
+ <Plus size={12} aria-hidden="true" /> {adding ? 'Close' : 'Add'}
+ </button>
+ </div>
+ )}
+
+ {adding && !blocked && (
+ <AddLoginForm
+ sandboxId={sandboxId}
+ onCancel={() => setAdding(false)}
+ onSaved={() => {
+ setAdding(false);
+ state.reload();
+ }}
+ />
+ )}
+
+ <div className="flex-1 overflow-y-auto pr-0.5">
+ {state.problem ? (
+ <PasswordsProblemNotice problem={state.problem} onRetry={state.reload} />
+ ) : state.loading ? (
+ <p className="flex items-center justify-center gap-2 py-10 text-xs text-zinc-500" role="status">
+ <Loader2 size={14} className="animate-spin motion-reduce:animate-none" /> Loading saved logins…
+ </p>
+ ) : shown.length === 0 ? (
+ <div className="text-center py-10 px-4 text-zinc-500 text-xs">
+ <Lock size={28} className="mx-auto mb-2 opacity-30 text-zinc-400" aria-hidden="true" />
+ <p className="font-medium text-zinc-400">{state.logins.length === 0 ? 'No saved logins yet' : 'No logins match'}</p>
+ {state.logins.length === 0 && (
+ <p className="text-[11px] text-zinc-500 mt-1 leading-relaxed">
+ When a bot signs in on a site, you’re asked whether to save that login. You can also add one here.
+ </p>
+ )}
+ </div>
+ ) : (
+ <ul className="space-y-2" aria-label="Saved logins">
+ {shown.map((l) => (
+ <SavedLoginRow key={l.id} sandboxId={sandboxId} login={l} onThisPage={loginMatchesPage(l, pageUrl)} onOpen={onOpen} onDeleted={state.reload} />
+ ))}
+ </ul>
+ )}
+ </div>
+
+ <div className="p-2 rounded-lg bg-zinc-900/40 border border-zinc-800/60 flex items-start gap-2 text-[10px] text-zinc-400">
+ <ShieldCheck size={14} className="text-emerald-400 flex-shrink-0 mt-0.5" aria-hidden="true" />
+ <p className="leading-snug">
+ <span className="text-zinc-300 font-medium">Encrypted on the server, out of the bots’ folders.</span> A login is filled in only on the exact address it was saved for.
+ </p>
+ </div>
+ </div>
+ );
+};
diff --git a/frontend/src/components/VirtualMachinePane.tsx b/frontend/src/components/VirtualMachinePane.tsx
index b675c933..8d8afcd6 100644
--- a/frontend/src/components/VirtualMachinePane.tsx
+++ b/frontend/src/components/VirtualMachinePane.tsx
@@ -7,15 +7,6 @@ import {
ExternalLink,
Cpu,
Key,
- Eye,
- EyeOff,
- Copy,
- Check,
- Trash2,
- Plus,
- ShieldCheck,
- Search,
- Lock,
MousePointerClick,
Keyboard,
Loader2,
@@ -26,6 +17,8 @@ import { mapBrowserPoint } from '../browserViewport';
import { useBrowserStream } from '../useBrowserStream';
import { ComputerModeChip, ComputerModeError, LocalBrowserNote, OpenWindowButton, useComputerMode } from './ComputerModeSwitch';
import { browserFooterLabel, isBlankPage, showsLocalWindow } from '../computerMode';
+import { loginMatchesPage } from '../savedPasswords';
+import { PendingLoginPrompt, SavedPasswordsPanel, useSavedPasswords } from './SavedPasswordsPanel';
export interface TerminalLogEntry {
command: string;
@@ -33,15 +26,6 @@ export interface TerminalLogEntry {
timestamp?: string;
}
-export interface SavedCredential {
- id: string;
- domain: string;
- origin: string;
- username: string;
- password: string;
- last_used?: string;
-}
-
export interface VirtualMachinePaneProps {
isOpen: boolean;
onClose: () => void;
@@ -75,16 +59,9 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({
}) => {
const [activeTab, setActiveTab] = useState<'browser' | 'terminal' | 'vault'>('browser');
const [inputUrl, setInputUrl] = useState(activeUrl);
- const [savedPasswords, setSavedPasswords] = useState<SavedCredential[]>([]);
- const [, setIsLoadingPasswords] = useState(false);
- const [revealedPasswords, setRevealedPasswords] = useState<Record<string, boolean>>({});
- const [copiedKey, setCopiedKey] = useState<string | null>(null);
- const [searchQuery, setSearchQuery] = useState('');
- const [isAdding, setIsAdding] = useState(false);
- const [newDomain, setNewDomain] = useState('');
- const [newUsername, setNewUsername] = useState('');
- const [newPassword, setNewPassword] = useState('');
- const [isSubmitting, setIsSubmitting] = useState(false);
+ // No event fires when the browser catches a login, so a new screenshot or page loads the list again.
+ const passwords = useSavedPasswords(teamId, `${activeUrl}|${screenshotBase64?.length ?? 0}|${screenshotBase64?.slice(-32) ?? ''}`);
+ const savedCount = passwords.logins.length;
// Local Chrome streams here like the VM, unless the person opened it as a window: then there's
// nothing to show. Unknown counts as vm.
@@ -118,132 +95,11 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({
if (stream.location?.url) setInputUrl(stream.location.url);
}, [stream.location]);
- const loadPasswords = useCallback(async () => {
- if (!teamId || teamId === 'default') return;
- try {
- setIsLoadingPasswords(true);
- const res = await fetch(`/api/sandbox/${teamId}/passwords`);
- if (res.ok) {
- const data = await res.json();
- setSavedPasswords(data.passwords || []);
- }
- } catch (err) {
- console.error('Failed to load saved passwords:', err);
- } finally {
- setIsLoadingPasswords(false);
- }
- }, [teamId]);
-
- useEffect(() => {
- loadPasswords();
- }, [loadPasswords]);
-
useEffect(() => {
setInputUrl(activeUrl);
}, [activeUrl]);
- // Extract hostname from active URL
- const activeDomain = useMemo(() => {
- if (!activeUrl || activeUrl === 'about:blank') return '';
- try {
- return new URL(activeUrl).hostname.toLowerCase();
- } catch {
- return '';
- }
- }, [activeUrl]);
-
- // Credentials matching active domain
- const matchingCreds = useMemo(() => {
- if (!activeDomain) return [];
- return savedPasswords.filter((p) => {
- const d = p.domain.toLowerCase();
- return activeDomain === d || activeDomain.endsWith(`.${d}`) || d.endsWith(`.${activeDomain}`);
- });
- }, [activeDomain, savedPasswords]);
-
- // Filtered credentials in vault
- const filteredPasswords = useMemo(() => {
- if (!searchQuery.trim()) return savedPasswords;
- const q = searchQuery.toLowerCase().trim();
- return savedPasswords.filter(
- (p) =>
- p.domain.toLowerCase().includes(q) ||
- p.username.toLowerCase().includes(q) ||
- p.origin.toLowerCase().includes(q)
- );
- }, [savedPasswords, searchQuery]);
-
- const handleCopy = (text: string, key: string) => {
- playSfx('click');
- navigator.clipboard.writeText(text);
- setCopiedKey(key);
- setTimeout(() => {
- setCopiedKey((curr) => (curr === key ? null : curr));
- }, 2000);
- };
-
- const toggleReveal = (id: string) => {
- playSfx('click');
- setRevealedPasswords((prev) => ({
- ...prev,
- [id]: !prev[id],
- }));
- };
-
- const handleAddCredential = async (e: React.FormEvent) => {
- e.preventDefault();
- if (!teamId || !newDomain.trim() || !newUsername.trim() || !newPassword.trim()) return;
- try {
- setIsSubmitting(true);
- let origin = newDomain.trim();
- if (!origin.startsWith('http://') && !origin.startsWith('https://')) {
- origin = `https://${origin}`;
- }
- let domain = origin.replace(/^https?:\/\//i, '').split('/')[0];
- if (domain.includes(':')) {
- domain = domain.split(':')[0];
- }
-
- const res = await fetch(`/api/sandbox/${teamId}/passwords`, {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- domain,
- origin,
- username: newUsername.trim(),
- password: newPassword.trim(),
- }),
- });
-
- if (res.ok) {
- playSfx('coin');
- setNewDomain('');
- setNewUsername('');
- setNewPassword('');
- setIsAdding(false);
- await loadPasswords();
- }
- } catch (err) {
- console.error('Failed to save password:', err);
- } finally {
- setIsSubmitting(false);
- }
- };
-
- const handleDeleteCredential = async (id: string) => {
- if (!teamId) return;
- try {
- playSfx('click');
- const res = await fetch(`/api/sandbox/${teamId}/passwords/${id}`, {
- method: 'DELETE',
- });
- if (res.ok) {
- setSavedPasswords((prev) => prev.filter((p) => p.id !== id));
- }
- } catch (err) {
- console.error('Failed to delete password:', err);
- }
- };
+ const loginsOnThisPage = useMemo(() => passwords.logins.filter((l) => loginMatchesPage(l, pageUrl)).length, [passwords.logins, pageUrl]);
// Dispatch interactive action to backend
const sendInteraction = useCallback(
@@ -369,7 +225,8 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({
playSfx('click');
setActiveTab((curr) => (curr === 'vault' ? 'browser' : 'vault'));
}}
- title={`Saved Logins & Passwords (${savedPasswords.length})`}
+ title={`Saved logins (${savedCount})`}
+ aria-label={`Saved logins (${savedCount})`}
className={`p-1.5 rounded-md transition-colors cursor-pointer relative ${
activeTab === 'vault'
? 'text-sky-400 bg-sky-500/10'
@@ -377,9 +234,9 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({
}`}
>
<Key size={13} />
- {savedPasswords.length > 0 && (
+ {savedCount > 0 && (
<span className="absolute -top-1 -right-1 min-w-3.5 h-3.5 px-0.5 bg-sky-500 text-[9px] font-bold text-zinc-950 rounded-full flex items-center justify-center">
- {savedPasswords.length}
+ {savedCount}
</span>
)}
</button>
@@ -390,7 +247,7 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({
onClick={() => {
playSfx('click');
onRefresh();
- loadPasswords();
+ passwords.reload();
}}
title="Refresh Screenshot & Passwords"
className="p-1.5 rounded-md text-zinc-400 hover:text-zinc-100 hover:bg-zinc-800 transition-colors cursor-pointer"
@@ -465,14 +322,16 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({
>
<Key size={13} />
<span>Logins</span>
- {savedPasswords.length > 0 && (
+ {savedCount > 0 && (
<span className="text-[10px] px-1 py-0.2 rounded-full bg-zinc-800 text-zinc-300 font-mono">
- {savedPasswords.length}
+ {savedCount}
</span>
)}
</button>
</div>
+ {teamId && passwords.pending && <PendingLoginPrompt sandboxId={teamId} pending={passwords.pending} onDone={passwords.reload} />}
+
{/* Content Area */}
<div className="flex-1 overflow-hidden flex flex-col">
{activeTab === 'browser' && isWindow ? (
@@ -503,19 +362,18 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({
className="flex-1 bg-transparent text-zinc-200 font-mono text-[11px] truncate focus:outline-none"
/>
- {matchingCreds.length > 0 && (
+ {loginsOnThisPage > 0 && (
<button
type="button"
onClick={() => {
playSfx('click');
setActiveTab('vault');
- setSearchQuery(activeDomain);
}}
className="flex items-center gap-1 px-1.5 py-0.5 rounded bg-emerald-500/15 text-emerald-400 border border-emerald-500/25 text-[10px] hover:bg-emerald-500/25 transition-colors cursor-pointer flex-shrink-0"
- title={`${matchingCreds.length} login saved for this site. Click to view credentials.`}
+ title={`${loginsOnThisPage} saved login${loginsOnThisPage === 1 ? '' : 's'} for this address`}
>
<Key size={10} />
- <span className="font-mono">{matchingCreds.length} saved</span>
+ <span className="font-mono">{loginsOnThisPage} saved</span>
</button>
)}
@@ -657,242 +515,25 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({
)}
</div>
) : (
- /* Saved Logins / Password Vault Tab */
- <div className="flex-1 flex flex-col p-3 gap-2 overflow-hidden bg-zinc-950">
- {/* Vault Controls */}
- <div className="flex items-center gap-1.5">
- <div className="flex-1 flex items-center gap-1.5 px-2 py-1 bg-zinc-900 border border-zinc-800 rounded-lg text-xs">
- <Search size={12} className="text-zinc-500 flex-shrink-0" />
- <input
- type="text"
- value={searchQuery}
- onChange={(e) => setSearchQuery(e.target.value)}
- placeholder="Search domains or users..."
- className="w-full bg-transparent text-zinc-200 text-[11px] focus:outline-none placeholder:text-zinc-600"
- />
- {searchQuery && (
- <button
- type="button"
- onClick={() => setSearchQuery('')}
- className="text-zinc-500 hover:text-zinc-300 text-[10px]"
- >
- ×
- </button>
- )}
- </div>
- <button
- type="button"
- onClick={() => {
- playSfx('click');
- setIsAdding((prev) => !prev);
- }}
- className={`flex items-center gap-1 px-2.5 py-1.5 rounded-lg text-[11px] font-medium transition-colors cursor-pointer ${
- isAdding
- ? 'bg-zinc-800 text-zinc-200'
- : 'bg-sky-500/10 text-sky-400 border border-sky-500/20 hover:bg-sky-500/20'
- }`}
- >
- <Plus size={12} />
- <span>{isAdding ? 'Cancel' : 'Add'}</span>
- </button>
- </div>
-
- {/* Manual Entry Form */}
- {isAdding && (
- <form
- onSubmit={handleAddCredential}
- className="p-3 bg-zinc-900/90 border border-sky-500/30 rounded-xl space-y-2 text-xs animate-in fade-in duration-150"
- >
- <div className="text-[11px] font-semibold text-sky-400 flex items-center gap-1">
- <Key size={12} />
- <span>Save New Credential</span>
- </div>
- <div>
- <label className="text-[10px] text-zinc-400 block mb-0.5">Domain or URL</label>
- <input
- type="text"
- required
- value={newDomain}
- onChange={(e) => setNewDomain(e.target.value)}
- placeholder="e.g. github.com or https://..."
- className="w-full px-2 py-1 bg-zinc-950 border border-zinc-800 rounded text-[11px] text-zinc-200 focus:outline-none focus:border-sky-500 font-mono"
- />
- </div>
- <div>
- <label className="text-[10px] text-zinc-400 block mb-0.5">Username or Email</label>
- <input
- type="text"
- required
- value={newUsername}
- onChange={(e) => setNewUsername(e.target.value)}
- placeholder="[email protected]"
- className="w-full px-2 py-1 bg-zinc-950 border border-zinc-800 rounded text-[11px] text-zinc-200 focus:outline-none focus:border-sky-500 font-mono"
- />
- </div>
- <div>
- <label className="text-[10px] text-zinc-400 block mb-0.5">Password</label>
- <input
- type="password"
- required
- value={newPassword}
- onChange={(e) => setNewPassword(e.target.value)}
- placeholder="••••••••••••"
- className="w-full px-2 py-1 bg-zinc-950 border border-zinc-800 rounded text-[11px] text-zinc-200 focus:outline-none focus:border-sky-500 font-mono"
- />
- </div>
- <div className="flex justify-end gap-1.5 pt-1">
- <button
- type="button"
- onClick={() => setIsAdding(false)}
- className="px-2.5 py-1 text-[11px] rounded bg-zinc-800 hover:bg-zinc-700 text-zinc-300 cursor-pointer"
- >
- Cancel
- </button>
- <button
- type="submit"
- disabled={isSubmitting}
- className="px-2.5 py-1 text-[11px] rounded bg-sky-500 hover:bg-sky-400 text-zinc-950 font-semibold cursor-pointer disabled:opacity-50"
- >
- {isSubmitting ? 'Saving...' : 'Save Credential'}
- </button>
- </div>
- </form>
- )}
-
- {/* Credential List */}
- <div className="flex-1 overflow-y-auto space-y-2 pr-0.5">
- {filteredPasswords.length === 0 ? (
- <div className="text-center py-10 px-4 text-zinc-500 text-xs">
- <Lock size={28} className="mx-auto mb-2 opacity-30 text-zinc-400" />
- <p className="font-medium text-zinc-400">No saved logins yet</p>
- <p className="text-[10px] text-zinc-500 mt-1 leading-relaxed">
- Credentials entered into website forms within the sandbox browser are automatically captured and saved here, or you can add them manually.
- </p>
- </div>
- ) : (
- filteredPasswords.map((cred) => {
- const isMatchingActive =
- activeDomain &&
- (activeDomain === cred.domain.toLowerCase() ||
- activeDomain.endsWith(`.${cred.domain.toLowerCase()}`));
- const isRevealed = !!revealedPasswords[cred.id];
-
- return (
- <div
- key={cred.id}
- className={`p-2.5 rounded-xl border transition-all text-xs bg-zinc-900/60 ${
- isMatchingActive
- ? 'border-emerald-500/40 shadow-sm shadow-emerald-500/5'
- : 'border-zinc-800/80 hover:border-zinc-700'
- }`}
- >
- {/* Card Header */}
- <div className="flex items-center justify-between mb-1.5">
- <div className="flex items-center gap-1.5 truncate">
- <span className="font-semibold text-zinc-200 truncate">{cred.domain}</span>
- {isMatchingActive && (
- <span className="px-1.5 py-0.2 rounded bg-emerald-500/10 text-emerald-400 border border-emerald-500/20 text-[9px] font-mono flex-shrink-0">
- Active Site
- </span>
- )}
- </div>
- <div className="flex items-center gap-1">
- {onNavigate && (
- <button
- type="button"
- onClick={() => {
- playSfx('click');
- onNavigate(cred.origin);
- setActiveTab('browser');
- }}
- title="Open & Autofill in Browser"
- className="text-zinc-400 hover:text-sky-400 p-1 rounded hover:bg-zinc-800/60 cursor-pointer"
- >
- <ExternalLink size={11} />
- </button>
- )}
- <button
- type="button"
- onClick={() => handleDeleteCredential(cred.id)}
- title="Delete credential"
- className="text-zinc-500 hover:text-rose-400 p-1 rounded hover:bg-zinc-800/60 cursor-pointer"
- >
- <Trash2 size={11} />
- </button>
- </div>
- </div>
-
- {/* Username Row */}
- <div className="flex items-center justify-between py-1 px-2 rounded bg-zinc-950/70 border border-zinc-800/50 mb-1">
- <span className="text-[11px] font-mono text-zinc-300 truncate max-w-[200px]">
- {cred.username}
- </span>
- <button
- type="button"
- onClick={() => handleCopy(cred.username, `user-${cred.id}`)}
- title="Copy username"
- className="text-zinc-500 hover:text-zinc-200 p-0.5 cursor-pointer ml-1"
- >
- {copiedKey === `user-${cred.id}` ? (
- <Check size={11} className="text-emerald-400" />
- ) : (
- <Copy size={11} />
- )}
- </button>
- </div>
-
- {/* Password Row */}
- <div className="flex items-center justify-between py-1 px-2 rounded bg-zinc-950/70 border border-zinc-800/50">
- <span className="text-[11px] font-mono text-zinc-400 truncate max-w-[180px]">
- {isRevealed ? cred.password : '••••••••••••'}
- </span>
- <div className="flex items-center gap-1 ml-1">
- <button
- type="button"
- onClick={() => toggleReveal(cred.id)}
- title={isRevealed ? 'Hide password' : 'Show password'}
- className="text-zinc-500 hover:text-zinc-200 p-0.5 cursor-pointer"
- >
- {isRevealed ? <EyeOff size={11} /> : <Eye size={11} />}
- </button>
- <button
- type="button"
- onClick={() => handleCopy(cred.password, `pass-${cred.id}`)}
- title="Copy password"
- className="text-zinc-500 hover:text-zinc-200 p-0.5 cursor-pointer"
- >
- {copiedKey === `pass-${cred.id}` ? (
- <Check size={11} className="text-emerald-400" />
- ) : (
- <Copy size={11} />
- )}
- </button>
- </div>
- </div>
-
- {/* Card Footer */}
- {cred.last_used && (
- <div className="mt-1 text-[9px] text-zinc-500 text-right">
- Last used {new Date(cred.last_used).toLocaleDateString()}
- </div>
- )}
- </div>
- );
- })
- )}
- </div>
-
- {/* Vault Security Note */}
- <div className="p-2 rounded-lg bg-zinc-900/40 border border-zinc-800/60 flex items-start gap-2 text-[10px] text-zinc-400">
- <ShieldCheck size={14} className="text-emerald-400 flex-shrink-0 mt-0.5" />
- <div className="leading-tight">
- <span className="text-zinc-300 font-medium">Automatic Autofill & Persistence</span>
- <p className="text-zinc-500 mt-0.5">
- Saved logins and session cookies persist in the workspace vault across container restarts.
- </p>
- </div>
- </div>
- </div>
+ /* Saved logins */
+ teamId && teamId !== 'default' ? (
+ <SavedPasswordsPanel
+ sandboxId={teamId}
+ state={passwords}
+ pageUrl={pageUrl}
+ onOpen={
+ onNavigate
+ ? (origin) => {
+ playSfx('click');
+ onNavigate(origin);
+ setActiveTab('browser');
+ }
+ : undefined
+ }
+ />
+ ) : (
+ <p className="flex-1 p-6 text-center text-xs text-zinc-500">Open a bot, team or channel to see its saved logins.</p>
+ )
)}
</div>
diff --git a/frontend/src/savedPasswords.ts b/frontend/src/savedPasswords.ts
new file mode 100644
index 00000000..0d1e444a
--- /dev/null
+++ b/frontend/src/savedPasswords.ts
@@ -0,0 +1,173 @@
+// Saved passwords for a team's, channel's or bot's browser. The list carries no passwords: one is
+// fetched only when the person presses Reveal, shown for a short while and never kept. A login the
+// browser caught on a form waits as `pending` until the person saves or discards it. Every route
+// is person-only: without the API token the server answers 401 `{person_only:true}`, and the auth
+// layer then asks for the token (see auth.ts).
+
+/** GET /api/sandbox/:id/passwords → passwords[] */
+export interface SavedLogin {
+ id: string;
+ origin: string;
+ domain: string;
+ username: string;
+ created_at: string | null;
+ last_used: string | null;
+}
+
+/** A login caught on a page, waiting for the person's yes or no. */
+export interface PendingLogin {
+ origin: string;
+ username: string;
+ captured_at: string | null;
+}
+
+export interface PasswordsList {
+ passwords: SavedLogin[];
+ pending: PendingLogin | null;
+}
+
+/** Why the list can't be shown. `locked` is for a store that must be unlocked first (Bitwarden). */
+export type PasswordsProblem = 'needs-token' | 'locked' | 'unavailable' | 'error';
+
+/** How long a revealed password stays on screen. */
+export const REVEAL_MS = 30_000;
+
+const str = (v: unknown): string | null => (typeof v === 'string' ? v : null);
+
+function parseLogin(raw: unknown): SavedLogin | null {
+ if (!raw || typeof raw !== 'object') return null;
+ const o = raw as Record<string, unknown>;
+ const id = str(o.id);
+ const origin = str(o.origin) ?? '';
+ const domain = str(o.domain) ?? hostOf(origin);
+ if (!id || (!origin && !domain)) return null;
+ // Whatever else the server sends (an older one sent `password`) is dropped here.
+ return { id, origin, domain, username: str(o.username) ?? '', created_at: str(o.created_at), last_used: str(o.last_used) };
+}
+
+function parsePending(raw: unknown): PendingLogin | null {
+ if (!raw || typeof raw !== 'object') return null;
+ const o = raw as Record<string, unknown>;
+ const origin = str(o.origin);
+ if (!origin) return null;
+ return { origin, username: str(o.username) ?? '', captured_at: str(o.captured_at) };
+}
+
+export function parsePasswordsList(raw: unknown): PasswordsList {
+ const o = raw && typeof raw === 'object' ? (raw as Record<string, unknown>) : {};
+ const list = Array.isArray(o.passwords) ? o.passwords : [];
+ return {
+ passwords: list.map(parseLogin).filter((l): l is SavedLogin => l !== null),
+ pending: parsePending(o.pending),
+ };
+}
+
+export function hostOf(origin: string): string {
+ try {
+ return new URL(origin).hostname.toLowerCase();
+ } catch {
+ return '';
+ }
+}
+
+/** The origin (scheme, host and port) of a page, or '' for a blank or unparsable one. */
+export function pageOrigin(url: string | null | undefined): string {
+ if (!url || url === 'about:blank') return '';
+ try {
+ const u = new URL(url);
+ return u.protocol === 'http:' || u.protocol === 'https:' ? u.origin : '';
+ } catch {
+ return '';
+ }
+}
+
+/** Autofill only fills on the exact origin it was saved for, so "for this site" means the same. */
+export function loginMatchesPage(login: Pick<SavedLogin, 'origin'>, pageUrl: string | null | undefined): boolean {
+ const page = pageOrigin(pageUrl);
+ return !!page && pageOrigin(login.origin) === page;
+}
+
+/** What the person typed in "Site" → the origin to save under. A bare host means https. */
+export function originFromInput(input: string): string | null {
+ const v = input.trim();
+ if (!v) return null;
+ const withScheme = /^[a-z][a-z0-9+.-]*:\/\//i.test(v) ? v : `https://${v}`;
+ try {
+ const u = new URL(withScheme);
+ if ((u.protocol !== 'https:' && u.protocol !== 'http:') || !u.hostname) return null;
+ return u.origin;
+ } catch {
+ return null;
+ }
+}
+
+/** A short label for an origin: the host, plus the scheme when it isn't https and any port. */
+export function originLabel(origin: string): string {
+ try {
+ const u = new URL(origin);
+ return u.protocol === 'https:' ? u.host : `${u.protocol}//${u.host}`;
+ } catch {
+ return origin;
+ }
+}
+
+export function filterLogins(list: SavedLogin[], query: string): SavedLogin[] {
+ const q = query.trim().toLowerCase();
+ if (!q) return list;
+ return list.filter((l) => l.origin.toLowerCase().includes(q) || l.domain.toLowerCase().includes(q) || l.username.toLowerCase().includes(q));
+}
+
+export function problemFor(status: number, body: unknown): PasswordsProblem {
+ const o = body && typeof body === 'object' ? (body as Record<string, unknown>) : {};
+ if (status === 401) return 'needs-token';
+ if (status === 423 || o.locked === true) return 'locked';
+ if (status === 503) return 'unavailable';
+ return 'error';
+}
+
+export const PROBLEM_TEXT: Record<PasswordsProblem, string> = {
+ 'needs-token': 'Saved passwords need your access token, even on this computer, so a bot can’t reach them.',
+ locked: 'The password store is locked. Unlock it to see or use saved passwords.',
+ unavailable: 'The password store isn’t available right now. Try again in a moment.',
+ error: 'Couldn’t load saved passwords.',
+};
+
+export class PasswordsError extends Error {
+ constructor(public problem: PasswordsProblem, public status: number, message: string) {
+ super(message);
+ }
+}
+
+async function call(url: string, init?: RequestInit): Promise<unknown> {
+ const res = await fetch(url, { cache: 'no-store', ...init });
+ const body = await res.json().catch(() => null);
+ if (!res.ok) {
+ const problem = problemFor(res.status, body);
+ const msg = body && typeof body === 'object' && typeof (body as { error?: unknown }).error === 'string' ? (body as { error: string }).error : null;
+ throw new PasswordsError(problem, res.status, problem === 'error' && msg ? msg : PROBLEM_TEXT[problem]);
+ }
+ return body;
+}
+
+const json = (method: string, body?: unknown): RequestInit => ({
+ method,
+ headers: body === undefined ? undefined : { 'Content-Type': 'application/json' },
+ body: body === undefined ? undefined : JSON.stringify(body),
+});
+
+const base = (sandboxId: string) => `/api/sandbox/${encodeURIComponent(sandboxId)}/passwords`;
+
+export const passwordsApi = {
+ /** Quiet: a missing token shows as the panel's own state, not the token dialog. */
+ list: async (sandboxId: string) => parsePasswordsList(await call(base(sandboxId), { kwntQuiet: true } as RequestInit)),
+ /** The one call that returns a password. Callers show it briefly and drop it. */
+ reveal: async (sandboxId: string, id: string): Promise<string> => {
+ const body = (await call(`${base(sandboxId)}/${encodeURIComponent(id)}/reveal`, json('POST'))) as { password?: unknown } | null;
+ if (typeof body?.password !== 'string') throw new PasswordsError('error', 200, 'The server sent no password.');
+ return body.password;
+ },
+ add: (sandboxId: string, origin: string, username: string, password: string) => call(base(sandboxId), json('POST', { origin, username, password })),
+ remove: (sandboxId: string, id: string) => call(`${base(sandboxId)}/${encodeURIComponent(id)}`, json('DELETE')),
+ savePending: (sandboxId: string) => call(`${base(sandboxId)}/pending`, json('POST')),
+ discardPending: (sandboxId: string) => call(`${base(sandboxId)}/pending`, json('DELETE')),
+};
diff --git a/frontend/tests/savedPasswords.test.mjs b/frontend/tests/savedPasswords.test.mjs
new file mode 100644
index 00000000..274d4337
--- /dev/null
+++ b/frontend/tests/savedPasswords.test.mjs
@@ -0,0 +1,233 @@
+// Saved passwords after the audit (2026-10-20): the list carries no passwords, Reveal fetches one
+// for 30 seconds, a caught login waits for Save / Don't save, person-only 401s ask for the token,
+// and bot settings say so when tools run without asking.
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { loadBundled } from './bundle.mjs';
+
+globalThis.localStorage ??= { getItem: () => null, setItem: () => {} };
+
+const m = await loadBundled(`
+ import React from 'react';
+ import { renderToStaticMarkup } from 'react-dom/server.browser';
+ import { SavedPasswordsPanel, SavedLoginRow, PendingLoginPrompt, PasswordsProblemNotice } from './src/components/SavedPasswordsPanel';
+ import { PersonTokenDialog } from './src/components/AuthGate';
+ import { KwantToolsPicker } from './src/components/KwantToolsPicker';
+ export * from './src/savedPasswords';
+ export * as auth from './src/auth';
+ const r = (C, p) => renderToStaticMarkup(React.createElement(C, p));
+ const state = (p) => ({ logins: [], pending: null, loading: false, problem: null, reload() {}, ...p });
+ export const panel = (s, p) => r(SavedPasswordsPanel, { sandboxId: 'k1', state: state(s), pageUrl: '', ...p });
+ export const row = (p) => r(SavedLoginRow, { sandboxId: 'k1', onThisPage: false, onDeleted() {}, ...p });
+ export const pendingPrompt = (pending) => r(PendingLoginPrompt, { sandboxId: 'k1', pending, onDone() {} });
+ export const problem = (problem) => r(PasswordsProblemNotice, { problem, onRetry() {} });
+ export const tokenDialog = () => r(PersonTokenDialog, { onClose() {}, onSignedIn() {} });
+ export const tools = (p) => r(KwantToolsPicker, { model: 'claude:sonnet', selected: [], onChange() {}, ...p });
+`);
+
+const text = (html) => html.replace(/<[^>]+>/g, ' ').replace(/’/g, "'").replace(/&#x27;|&#39;/g, "'").replace(/&quot;/g, '"').replace(/&amp;/g, '&').replace(/\s+/g, ' ').trim();
+const buttons = (html) => [...html.matchAll(/<button[^>]*>([\s\S]*?)<\/button>/g)].map((x) => text(x[1]));
+const login = (p) => ({ id: 'c1', origin: 'https://example.com', domain: 'example.com', username: 'alice', created_at: '2026-10-20T07:00:00Z', last_used: null, ...p });
+
+// ---------------------------------------------------------------- the model
+
+test('the list keeps only metadata, even if a server still sends a password', () => {
+ const l = m.parsePasswordsList({
+ passwords: [{ id: 'c1', origin: 'https://example.com', domain: 'example.com', username: 'alice', password: 'DUMMY-SECRET', created_at: 'x' }, { nope: 1 }],
+ pending: { origin: 'https://example.com', username: 'alice', captured_at: 't', password: 'DUMMY-SECRET' },
+ });
+ assert.equal(l.passwords.length, 1);
+ assert.equal(JSON.stringify(l).includes('DUMMY-SECRET'), false);
+ assert.deepEqual(l.pending, { origin: 'https://example.com', username: 'alice', captured_at: 't' });
+ assert.deepEqual(m.parsePasswordsList({ passwords: [] , pending: null }), { passwords: [], pending: null });
+ assert.deepEqual(m.parsePasswordsList(null), { passwords: [], pending: null });
+});
+
+test('"this page" means the exact origin: scheme, host and port', () => {
+ const l = { origin: 'https://example.com' };
+ assert.equal(m.loginMatchesPage(l, 'https://example.com/login?x=1'), true);
+ assert.equal(m.loginMatchesPage(l, 'http://example.com/login'), false, 'http is another origin');
+ assert.equal(m.loginMatchesPage(l, 'https://evil.example.com/'), false, 'subdomains are other origins');
+ assert.equal(m.loginMatchesPage(l, 'https://example.com:8443/'), false, 'another port');
+ assert.equal(m.loginMatchesPage(l, 'https://example.com.evil.test/'), false);
+ assert.equal(m.loginMatchesPage(l, 'about:blank'), false);
+ assert.equal(m.loginMatchesPage(l, ''), false);
+});
+
+test('the Site field becomes an origin; a bare host means https', () => {
+ assert.equal(m.originFromInput('example.com'), 'https://example.com');
+ assert.equal(m.originFromInput(' https://example.com/login '), 'https://example.com');
+ assert.equal(m.originFromInput('http://localhost:3000/x'), 'http://localhost:3000');
+ assert.equal(m.originFromInput('ftp://example.com'), null);
+ assert.equal(m.originFromInput('javascript://alert(1)'), null);
+ assert.equal(m.originFromInput(' '), null);
+ assert.equal(m.originLabel('https://example.com'), 'example.com');
+ assert.equal(m.originLabel('http://example.com:8080'), 'http://example.com:8080');
+});
+
+test('server answers map to the panel states, including locked for a store that unlocks', () => {
+ assert.equal(m.problemFor(401, { person_only: true }), 'needs-token');
+ assert.equal(m.problemFor(423, { locked: true }), 'locked');
+ assert.equal(m.problemFor(503, {}), 'unavailable');
+ assert.equal(m.problemFor(500, {}), 'error');
+ assert.equal(m.REVEAL_MS, 30_000);
+});
+
+test('the API: list is quiet and uncached, reveal is a POST, save sends the origin', async () => {
+ const calls = [];
+ const prev = globalThis.fetch;
+ globalThis.fetch = async (url, init = {}) => {
+ calls.push({ url, ...init });
+ if (url.endsWith('/reveal')) return new Response(JSON.stringify({ password: 'DUMMY-1' }), { status: 200 });
+ if (url.endsWith('/passwords') && (init.method ?? 'GET') === 'GET') return new Response(JSON.stringify({ passwords: [login()], pending: null }), { status: 200 });
+ return new Response(JSON.stringify({ status: 'saved' }), { status: 200 });
+ };
+ try {
+ await m.passwordsApi.list('k 1');
+ assert.equal(calls[0].url, '/api/sandbox/k%201/passwords');
+ assert.equal(calls[0].kwntQuiet, true, 'a background load shows its own token state');
+ assert.equal(calls[0].cache, 'no-store');
+ assert.equal(await m.passwordsApi.reveal('k1', 'c1'), 'DUMMY-1');
+ assert.equal(calls[1].method, 'POST');
+ assert.equal(calls[1].url, '/api/sandbox/k1/passwords/c1/reveal');
+ assert.notEqual(calls[1].kwntQuiet, true, 'an explicit action asks for the token');
+ await m.passwordsApi.add('k1', 'https://example.com', 'alice', 'DUMMY-2');
+ assert.deepEqual(JSON.parse(calls[2].body), { origin: 'https://example.com', username: 'alice', password: 'DUMMY-2' });
+ await m.passwordsApi.savePending('k1');
+ await m.passwordsApi.discardPending('k1');
+ await m.passwordsApi.remove('k1', 'c1');
+ assert.deepEqual(calls.slice(3).map((c) => `${c.method} ${c.url}`), [
+ 'POST /api/sandbox/k1/passwords/pending',
+ 'DELETE /api/sandbox/k1/passwords/pending',
+ 'DELETE /api/sandbox/k1/passwords/c1',
+ ]);
+ globalThis.fetch = async () => new Response(JSON.stringify({ error: 'x', person_only: true }), { status: 401 });
+ await assert.rejects(m.passwordsApi.reveal('k1', 'c1'), (e) => e.problem === 'needs-token');
+ globalThis.fetch = async () => new Response(JSON.stringify({ locked: true }), { status: 423 });
+ await assert.rejects(m.passwordsApi.list('k1'), (e) => e.problem === 'locked');
+ } finally {
+ globalThis.fetch = prev;
+ }
+});
+
+// ---------------------------------------------------------------- the list
+
+test('a row shows site and username, the password only as dots with a Reveal button', () => {
+ const html = m.row({ login: login() });
+ const t = text(html);
+ assert.match(t, /example\.com/);
+ assert.match(t, /alice/);
+ assert.match(html, /••••/);
+ assert.ok(buttons(html).includes('Reveal'));
+ assert.ok(!html.includes('Copy password'), 'nothing to copy before Reveal');
+ assert.ok(!html.includes('data-revealed'));
+});
+
+test('a revealed row shows the password, a Hide button and when it hides again', () => {
+ const html = m.row({ login: login(), initialRevealed: 'DUMMY-3' });
+ assert.match(html, /data-revealed[^>]*>DUMMY-3</);
+ assert.ok(buttons(html).includes('Hide'));
+ assert.match(text(html), /Hides again in 30 seconds/);
+ assert.match(html, /aria-label="Copy password"/);
+});
+
+test('Delete asks first, with Keep focused', () => {
+ const html = m.row({ login: login(), initialConfirmDelete: true });
+ assert.match(text(html), /Delete this login\? The bots can't sign in to example\.com/);
+ const b = buttons(html);
+ assert.ok(b.includes('Keep') && b.includes('Delete'));
+ assert.match(html, /<button[^>]*autofocus=""[^>]*>Keep/i);
+ assert.ok(!text(m.row({ login: login() })).includes('Delete this login'));
+});
+
+test('the exact-origin row is marked "This page" in words, not colour alone', () => {
+ assert.match(text(m.row({ login: login(), onThisPage: true })), /This page/);
+ assert.ok(!text(m.row({ login: login(), onThisPage: false })).includes('This page'));
+});
+
+test('the panel lists logins and marks only the exact origin', () => {
+ const html = m.panel({ logins: [login(), login({ id: 'c2', origin: 'http://example.com', username: 'bob' })] }, { pageUrl: 'https://example.com/login' });
+ assert.equal((html.match(/data-login-row=/g) || []).length, 2);
+ assert.equal((text(html).match(/This page/g) || []).length, 1);
+ assert.match(text(html), /http:\/\/example\.com/);
+});
+
+test('empty, loading and problem states', () => {
+ assert.match(text(m.panel({})), /No saved logins yet/);
+ assert.match(text(m.panel({ loading: true })), /Loading saved logins/);
+ const tok = m.panel({ problem: 'needs-token' });
+ assert.match(text(tok), /need your access token/);
+ assert.ok(buttons(tok).includes('Enter access token'));
+ assert.ok(!buttons(tok).some((b) => b.includes('Add')), 'no add form while the list is unreachable');
+ assert.match(text(m.problem('locked')), /locked/i);
+ assert.ok(buttons(m.problem('locked')).includes('Try again'));
+});
+
+test('the add form takes a site and says the exact origin it fills on', () => {
+ const html = m.panel({}, { initialAdding: true });
+ assert.match(text(html), /Site/);
+ assert.match(html, /type="password"/);
+ assert.match(html, /autoComplete="new-password"|autocomplete="new-password"/);
+ assert.ok(buttons(html).includes('Save login'));
+});
+
+// ---------------------------------------------------------------- the waiting capture
+
+test('a caught login asks "Save password for <site> as <user>?" with Save and Don\'t save', () => {
+ const html = m.pendingPrompt({ origin: 'https://example.com', username: 'alice', captured_at: null });
+ assert.match(text(html), /Save password for example\.com as alice \?|Save password for example\.com as alice\?/);
+ assert.deepEqual(buttons(html), ["Don't save", 'Save']);
+ assert.match(text(html), /Nothing is saved until you choose Save/);
+ assert.match(text(m.pendingPrompt({ origin: 'http://example.com:8080', username: '', captured_at: null })), /Save password for http:\/\/example\.com:8080 \?|Save password for http:\/\/example\.com:8080\?/);
+});
+
+// ---------------------------------------------------------------- the token screen
+
+test('a person-only 401 asks for the token; any other 401 goes to the gate; quiet loads ask nothing', async () => {
+ assert.equal(m.auth.isPersonOnlyBody({ person_only: true }), true);
+ assert.equal(m.auth.isPersonOnlyBody({ error: 'API token required' }), false);
+ assert.equal(m.auth.isPersonOnlyBody(null), false);
+
+ const seen = [];
+ const win = new EventTarget();
+ win.location = { origin: 'http://127.0.0.1:18982', hash: '', pathname: '/', search: '' };
+ let answer = { status: 401, body: { person_only: true } };
+ win.fetch = async () => new Response(JSON.stringify(answer.body), { status: answer.status });
+ for (const e of [m.auth.PERSON_TOKEN_EVENT, m.auth.UNAUTHORIZED_EVENT]) win.addEventListener(e, () => seen.push(e));
+ const prevWindow = globalThis.window;
+ globalThis.window = win;
+ try {
+ m.auth.installUnauthorizedListener();
+ const res = await win.fetch('/api/sandbox/k1/passwords/c1/reveal', { method: 'POST' });
+ assert.deepEqual(await res.json(), { person_only: true }, 'the caller still reads the body');
+ assert.deepEqual(seen, [m.auth.PERSON_TOKEN_EVENT]);
+ await win.fetch('/api/sandbox/k1/passwords', { kwntQuiet: true });
+ assert.equal(seen.length, 1, 'quiet: no prompt');
+ answer = { status: 401, body: { error: 'API token required' } };
+ await win.fetch('/api/kwants');
+ assert.deepEqual(seen, [m.auth.PERSON_TOKEN_EVENT, m.auth.UNAUTHORIZED_EVENT]);
+ } finally {
+ globalThis.window = prevWindow;
+ }
+});
+
+test('the token dialog says why it is asked on this computer and can be dismissed', () => {
+ const html = m.tokenDialog();
+ assert.match(html, /role="dialog"/);
+ assert.match(html, /aria-modal="true"/);
+ const t = text(html);
+ assert.match(t, /Confirm it's you/);
+ assert.match(t, /even on this computer, so a bot can't reach them/);
+ assert.match(t, /kwnt token/);
+ assert.ok(buttons(html).includes('Not now'));
+ assert.ok(buttons(html).includes('Continue'));
+});
+
+// ---------------------------------------------------------------- the hint
+
+test('bot settings: the tools hint says "runs without asking" when approvals are off', () => {
+ assert.match(text(m.tools({})), /asks you before each use/);
+ const off = text(m.tools({ approvalsOff: true }));
+ assert.match(off, /runs them without asking \(approvals off\)/);
+ assert.ok(!off.includes('asks you before each use'));
+});