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
Bitwarden password screens: store picker, connect, unlock, reveal, migrate
Lin (kwant bot)39f268bd461b
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsxindex 6d357bc7..d88384d3 100644--- a/frontend/src/App.tsx+++ b/frontend/src/App.tsx@@ -2469,6 +2469,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({onRefreshVm={handleRefreshVm}onRestartVm={handleRestartVm}onNavigateVm={handleNavigateVm}+ vmApprovalsOff={space.approvals === 'off' || kwants.some(approvalsOff)}pinned={pinned}onEditInstructions={isChannel && currentChanneldiff --git a/frontend/src/approvalMode.ts b/frontend/src/approvalMode.tsindex ac81c62c..dcf12531 100644--- a/frontend/src/approvalMode.ts+++ b/frontend/src/approvalMode.ts@@ -2,6 +2,8 @@// recorded). Set per space, with a per-bot override. Only the person changes it; a bot's token// gets 403. No event fires on a change, so callers load bots and spaces again after a save.+import { AUTOFILL_GAP_NOTE } from './passwordStore';+export type SpaceApprovals = 'ask' | 'off';export type BotApprovals = 'inherit' | 'ask' | 'off';@@ -56,6 +58,7 @@ export const OFF_CONSEQUENCES = ['Files can be written or deleted anywhere the computer allows, not just in the bot’s folder.','Tools (MCP servers, browser, web) run without asking.','No approval cards appear. Everything that runs is still recorded.',+ AUTOFILL_GAP_NOTE,];export function offConfirmTitle(who: { space: string } | { bot: string }): string {diff --git a/frontend/src/components/ChatView.tsx b/frontend/src/components/ChatView.tsxindex 968a96d2..8a51a4f2 100644--- a/frontend/src/components/ChatView.tsx+++ b/frontend/src/components/ChatView.tsx@@ -136,6 +136,8 @@ export interface ChatViewProps {onRefreshVm?: () => void;onRestartVm?: () => void;onNavigateVm?: (url: string) => void;+ /** Some bot in the space runs without asking (the saved-passwords note). */+ vmApprovalsOff?: boolean;/** Pinned team/channel instructions, shown collapsed above the messages. */pinned?: PinnedItem[];/** Opens the channel's instructions editor; only for channels. */@@ -303,6 +305,7 @@ export const ChatView: React.FC<ChatViewProps> = ({onRefreshVm,onRestartVm,onNavigateVm,+ vmApprovalsOff,pinned = [],onEditInstructions,highlightMessageId,@@ -1314,6 +1317,7 @@ export const ChatView: React.FC<ChatViewProps> = ({onRefresh={onRefreshVm}onRestartVm={onRestartVm}onNavigate={onNavigateVm}+ approvalsOff={vmApprovalsOff}/></div></div>diff --git a/frontend/src/components/PasswordStorePanel.tsx b/frontend/src/components/PasswordStorePanel.tsxnew file mode 100644index 00000000..887b40d1--- /dev/null+++ b/frontend/src/components/PasswordStorePanel.tsx@@ -0,0 +1,624 @@+import React, { useCallback, useEffect, useId, useRef, useState } from 'react';+import { AlertTriangle, ArrowRight, Check, ChevronDown, Info, KeyRound, Loader2, Lock, LockOpen, Server, ShieldCheck, X } from 'lucide-react';+import { PERSON_SIGNED_IN_EVENT, requestPersonToken } from '../auth';+import { playSfx } from '../audio/chiptune';+import {+ AUTOFILL_GAP_NOTE,+ BITWARDEN_CLOUDS,+ DEFAULT_BITWARDEN_SERVER,+ StoreError,+ StoreStatus,+ UnlockProblem,+ checkServerUrl,+ migrateText,+ serverLabel,+ storeApi,+ unlockProblemText,+} from '../passwordStore';++export interface PasswordStoreState {+ status: StoreStatus | null;+ /** 'needs-token' shows the panel's own token state; the list says the same. */+ problem: 'needs-token' | 'error' | null;+ reload: () => void;+ /** After unlock, lock, connect or disconnect: the server's new status, no extra round trip. */+ set: (s: StoreStatus) => void;+}++/** Where passwords are kept, loaded quietly (a missing token is the list's own state). */+export function usePasswordStore(enabled: boolean): PasswordStoreState {+ const [status, setStatus] = useState<StoreStatus | null>(null);+ const [problem, setProblem] = useState<PasswordStoreState['problem']>(null);+ const seq = useRef(0);+ const reload = useCallback(() => {+ if (!enabled) return;+ const mine = ++seq.current;+ storeApi+ .status()+ .then((s) => {+ if (mine !== seq.current) return;+ setStatus(s);+ setProblem(null);+ })+ .catch((e: unknown) => {+ if (mine !== seq.current) return;+ setProblem(e instanceof StoreError && e.problem.kind === 'needs-token' ? 'needs-token' : 'error');+ });+ }, [enabled]);+ useEffect(reload, [reload]);+ useEffect(() => {+ window.addEventListener(PERSON_SIGNED_IN_EVENT, reload);+ return () => window.removeEventListener(PERSON_SIGNED_IN_EVENT, reload);+ }, [reload]);+ const set = useCallback((s: StoreStatus) => {+ seq.current++;+ setStatus(s);+ setProblem(null);+ }, []);+ return { status, problem, reload, set };+}++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';+const btnQuiet = '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';+const btnMain = 'flex items-center gap-1.5 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';++const ProblemLine: React.FC<{ text: string }> = ({ text }) => (+ <p role="alert" className="flex items-start gap-1.5 text-[11px] text-rose-300 leading-snug">+ <AlertTriangle size={12} className="flex-shrink-0 mt-px" aria-hidden="true" /> <span>{text}</span>+ </p>+);++/** Clears a secret input and returns what it held. The value lives only in the DOM field. */+function takeSecret(ref: React.RefObject<HTMLInputElement>, clear: boolean): string {+ const v = ref.current?.value ?? '';+ if (clear && ref.current) ref.current.value = '';+ return v;+}++type Step = { kind: 'two-factor'; providers: Array<{ id: number; name: string; usable: boolean }> } | { kind: 'new-device-code' } | null;++/**+ * Connect (first time: server, email, password or API key) or unlock (after a restart).+ * The master password and client secret are uncontrolled inputs: read at submit, never in state.+ * A two-step code or new-device code is asked for in the same form when Bitwarden wants one.+ */+export const BitwardenLoginForm: React.FC<{+ mode: 'connect' | 'unlock';+ status: StoreStatus | null;+ onDone: (s: StoreStatus) => void;+ onCancel: () => void;+ /** Tests start on a step or with a problem showing. */+ initialStep?: Step;+ initialProblem?: UnlockProblem | null;+ initialApiKey?: boolean;+ initialServer?: string;+}> = ({ mode, status, onDone, onCancel, initialStep = null, initialProblem = null, initialApiKey, initialServer = DEFAULT_BITWARDEN_SERVER }) => {+ const id = useId();+ const bw = status?.bitwarden ?? null;+ const [server, setServer] = useState(initialServer);+ const [selfHosted, setSelfHosted] = useState('');+ const [email, setEmail] = useState('');+ const [apiKey, setApiKey] = useState(initialApiKey ?? (mode === 'unlock' && bw?.login === 'api_key'));+ const [clientId, setClientId] = useState('');+ const [step, setStep] = useState<Step>(initialStep);+ const [provider, setProvider] = useState<number | null>(initialStep?.kind === 'two-factor' ? initialStep.providers.find((p) => p.usable)?.id ?? null : null);+ const [code, setCode] = useState('');+ const [busy, setBusy] = useState(false);+ const [problem, setProblem] = useState<UnlockProblem | null>(initialProblem);+ const [formError, setFormError] = useState<string | null>(null);+ const masterRef = useRef<HTMLInputElement>(null);+ const secretRef = useRef<HTMLInputElement>(null);+ const codeRef = useRef<HTMLInputElement>(null);++ useEffect(() => {+ if (step) codeRef.current?.focus();+ }, [step]);++ // Leaving the form drops whatever was typed in the secret fields.+ useEffect(+ () => () => {+ takeSecret(masterRef, true);+ takeSecret(secretRef, true);+ },+ [],+ );++ const submit = async (e: React.FormEvent) => {+ e.preventDefault();+ setFormError(null);+ let serverUrl: string | undefined;+ if (mode === 'connect') {+ if (server === 'self') {+ const checked = checkServerUrl(selfHosted);+ if ('error' in checked) return setFormError(checked.error);+ serverUrl = checked.url;+ } else serverUrl = server;+ if (!email.includes('@')) return setFormError('Enter the email of your Bitwarden account.');+ if (apiKey && !clientId.trim()) return setFormError('Enter the API key’s client_id.');+ }+ if (!masterRef.current?.value) return setFormError('Enter your master password.');+ if (apiKey && !secretRef.current?.value) return setFormError('Enter the API key’s client_secret.');+ if (step && !code.trim()) return setFormError(step.kind === 'two-factor' ? 'Enter the two-step login code.' : 'Enter the code from the email.');+ setBusy(true);+ setProblem(null);+ try {+ const s = await storeApi.unlock({+ master_password: takeSecret(masterRef, false),+ server_url: serverUrl,+ email: mode === 'connect' ? email : undefined,+ client_id: apiKey && mode === 'connect' ? clientId : undefined,+ client_secret: apiKey ? takeSecret(secretRef, false) : undefined,+ two_factor_provider: step?.kind === 'two-factor' ? provider ?? undefined : undefined,+ two_factor_token: step?.kind === 'two-factor' ? code : undefined,+ new_device_otp: step?.kind === 'new-device-code' ? code : undefined,+ });+ takeSecret(masterRef, true);+ takeSecret(secretRef, true);+ playSfx('coin');+ onDone(s);+ } catch (err) {+ const p = err instanceof StoreError ? err.problem : ({ kind: 'error', message: 'Couldn’t reach the server.' } as UnlockProblem);+ setProblem(p);+ if (p.kind === 'two-factor') {+ setStep(p);+ setProvider(p.providers.find((x) => x.usable)?.id ?? null);+ setCode('');+ } else if (p.kind === 'new-device-code') {+ setStep(p);+ setCode('');+ } else if (p.kind === 'wrong-password') {+ takeSecret(masterRef, true);+ masterRef.current?.focus();+ }+ } finally {+ setBusy(false);+ }+ };++ const noUsableTwoFactor = step?.kind === 'two-factor' && !step.providers.some((p) => p.usable);+ // The hint describes the field rather than naming it, so screen readers hear the label alone first.+ const label = (text: string, input: React.ReactElement, hint?: React.ReactNode) => {+ const hintId = `${id}-${text.replace(/\W+/g, '-').toLowerCase()}-hint`;+ return (+ <div>+ <label className="block">+ <span className="text-[10px] text-zinc-400 block mb-0.5">{text}</span>+ {hint ? React.cloneElement(input as React.ReactElement<{ 'aria-describedby'?: string }>, { 'aria-describedby': hintId }) : input}+ </label>+ {hint && <span id={hintId} className="text-[10px] text-zinc-500 block mt-0.5 leading-snug">{hint}</span>}+ </div>+ );+ };++ return (+ <form onSubmit={submit} className="space-y-2 text-xs" aria-labelledby={`${id}-t`} data-bitwarden-form={mode} noValidate>+ <p id={`${id}-t`} className="text-[11px] font-semibold text-sky-400 flex items-center gap-1.5">+ {mode === 'connect' ? <KeyRound size={12} aria-hidden="true" /> : <LockOpen size={12} aria-hidden="true" />}+ {mode === 'connect' ? 'Connect Bitwarden' : 'Unlock Bitwarden'}+ </p>+ {mode === 'unlock' && bw && (+ <p className="text-[11px] text-zinc-400 break-all">+ {bw.email} on {serverLabel(bw.server_url)}+ </p>+ )}++ {mode === 'connect' && (+ <>+ {label(+ 'Server',+ <select value={server} onChange={(e) => setServer(e.target.value)} className={field} disabled={!!step}>+ {BITWARDEN_CLOUDS.map((c) => (+ <option key={c.value} value={c.value}>+ {c.label}+ </option>+ ))}+ <option value="self">Self-hosted (Vaultwarden too)</option>+ </select>,+ )}+ {server === 'self' &&+ label(+ 'Server address',+ <input type="url" value={selfHosted} onChange={(e) => setSelfHosted(e.target.value)} placeholder="https://vault.example.com" className={`${field} font-mono`} autoComplete="off" spellCheck={false} disabled={!!step} />,+ )}+ {label(+ 'Account email',+ <input type="email" value={email} onChange={(e) => setEmail(e.target.value)} placeholder="[email protected]" className={field} autoComplete="off" spellCheck={false} disabled={!!step} />,+ )}+ <fieldset className="space-y-1">+ <legend className="text-[10px] text-zinc-400 mb-0.5">Sign in with</legend>+ <div className="flex flex-wrap gap-x-3 gap-y-1">+ {[+ { v: false, l: 'Master password' },+ { v: true, l: 'API key + master password' },+ ].map((o) => (+ <label key={String(o.v)} className="flex items-center gap-1.5 text-[11px] text-zinc-300 cursor-pointer">+ <input type="radio" name={`${id}-method`} checked={apiKey === o.v} onChange={() => setApiKey(o.v)} disabled={!!step} className="accent-sky-500" />+ {o.l}+ </label>+ ))}+ </div>+ {apiKey && <p className="text-[10px] text-zinc-500 leading-snug">For accounts whose two-step login can’t be typed here. Find it in Bitwarden under Account settings → Security → Keys.</p>}+ </fieldset>+ {apiKey &&+ label('client_id', <input type="text" value={clientId} onChange={(e) => setClientId(e.target.value)} placeholder="user.…" className={`${field} font-mono`} autoComplete="off" spellCheck={false} />)}+ </>+ )}+ {apiKey &&+ label(+ 'client_secret',+ <input ref={secretRef} type="password" className={`${field} font-mono`} autoComplete="off" spellCheck={false} />,+ mode === 'unlock' ? 'Asked for at every unlock, and never kept.' : undefined,+ )}+ {label(+ 'Master password',+ <input ref={masterRef} type="password" className={field} autoComplete="off" autoFocus={mode === 'unlock'} />,+ 'Used to unlock, then forgotten. It’s never saved.',+ )}++ {step?.kind === 'two-factor' && !noUsableTwoFactor && (+ <div className="p-2 rounded-lg border border-sky-500/30 bg-sky-500/5 space-y-1.5" data-step="two-factor">+ {step.providers.filter((p) => p.usable).length > 1 &&+ label(+ 'Method',+ <select value={provider ?? ''} onChange={(e) => setProvider(Number(e.target.value))} className={field}>+ {step.providers+ .filter((p) => p.usable)+ .map((p) => (+ <option key={p.id} value={p.id}>+ {p.name}+ </option>+ ))}+ </select>,+ )}+ {label(+ step.providers.find((p) => p.id === provider)?.name === 'Email' ? 'Code from the email' : 'Two-step login code',+ <input ref={codeRef} type="text" inputMode="numeric" value={code} onChange={(e) => setCode(e.target.value)} className={`${field} font-mono tracking-widest`} autoComplete="one-time-code" />,+ )}+ </div>+ )}+ {step?.kind === 'new-device-code' && (+ <div className="p-2 rounded-lg border border-sky-500/30 bg-sky-500/5" data-step="new-device-code">+ {label(+ 'Code from Bitwarden’s email',+ <input ref={codeRef} type="text" inputMode="numeric" value={code} onChange={(e) => setCode(e.target.value)} className={`${field} font-mono tracking-widest`} autoComplete="one-time-code" />,+ )}+ </div>+ )}++ {formError && <ProblemLine text={formError} />}+ {problem && !formError && problem.kind !== 'needs-token' && <ProblemLine text={unlockProblemText(problem)} />}+ {problem?.kind === 'needs-token' && (+ <p role="alert" className="flex items-center gap-2 text-[11px] text-zinc-300">+ {unlockProblemText(problem)}+ <button type="button" onClick={requestPersonToken} className="text-sky-400 underline underline-offset-2">+ Enter access token+ </button>+ </p>+ )}++ <div className="flex justify-end gap-1.5 pt-1">+ <button type="button" onClick={onCancel} className={btnQuiet}>+ Cancel+ </button>+ <button type="submit" disabled={busy || noUsableTwoFactor} className={btnMain}>+ {busy && <Loader2 size={12} className="animate-spin motion-reduce:animate-none" aria-hidden="true" />}+ {busy ? (mode === 'connect' ? 'Connecting…' : 'Unlocking…') : step ? 'Continue' : mode === 'connect' ? 'Connect' : 'Unlock'}+ </button>+ </div>+ </form>+ );+};++/** The unlock form in a dialog, from the "Locked" state of the list or the store bar. */+export const UnlockDialog: React.FC<{ status: StoreStatus | null; onClose: () => void; onUnlocked: (s: StoreStatus) => void }> = ({ status, onClose, onUnlocked }) => {+ const id = useId();+ useEffect(() => {+ const onKey = (e: KeyboardEvent) => e.key === 'Escape' && onClose();+ window.addEventListener('keydown', onKey);+ return () => window.removeEventListener('keydown', onKey);+ }, [onClose]);+ return (+ <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-3" onMouseDown={(e) => e.target === e.currentTarget && onClose()}>+ <div role="dialog" aria-modal="true" aria-labelledby={`${id}-h`} className="relative w-full max-w-sm rounded-2xl border border-zinc-800 bg-zinc-900 p-4 shadow-2xl" data-unlock-dialog>+ <h2 id={`${id}-h`} className="sr-only">+ Unlock Bitwarden+ </h2>+ <button type="button" onClick={onClose} aria-label="Close" className="absolute right-2 top-2 p-1.5 rounded text-zinc-500 hover:text-zinc-200 hover:bg-zinc-800">+ <X size={14} />+ </button>+ <BitwardenLoginForm+ mode="unlock"+ status={status}+ onCancel={onClose}+ onDone={(s) => {+ onUnlocked(s);+ onClose();+ }}+ />+ </div>+ </div>+ );+};++/** "Move N saved passwords to Bitwarden": only when the person presses it; shows moved/failed. */+export const MigrateButton: React.FC<{ count: number; onDone: () => void; initialResult?: string | null }> = ({ count, onDone, initialResult = null }) => {+ const [busy, setBusy] = useState(false);+ const [result, setResult] = useState<string | null>(initialResult);+ const [error, setError] = useState<string | null>(null);+ const run = async () => {+ setBusy(true);+ setError(null);+ try {+ const r = await storeApi.migrate();+ setResult(migrateText(r));+ playSfx(r.failed ? 'click' : 'coin');+ onDone();+ } catch (e) {+ setError(e instanceof Error ? e.message : 'Couldn’t move the passwords.');+ } finally {+ setBusy(false);+ }+ };+ return (+ <div className="space-y-1" data-migrate>+ {count > 0 && (+ <>+ <button type="button" onClick={run} disabled={busy} className="flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg text-[11px] font-medium bg-sky-500/10 text-sky-300 border border-sky-500/30 hover:bg-sky-500/20 disabled:opacity-50">+ {busy ? <Loader2 size={12} className="animate-spin motion-reduce:animate-none" aria-hidden="true" /> : <ArrowRight size={12} aria-hidden="true" />}+ {busy ? 'Moving…' : `Move ${count} saved ${count === 1 ? 'password' : 'passwords'} to Bitwarden`}+ </button>+ <p className="text-[10px] text-zinc-500 leading-snug">Each one is deleted here only after Bitwarden has it.</p>+ </>+ )}+ {result && (+ <p role="status" className="flex items-start gap-1.5 text-[11px] text-emerald-300 leading-snug">+ <Check size={12} className="flex-shrink-0 mt-px" aria-hidden="true" /> {result}+ </p>+ )}+ {error && <ProblemLine text={error} />}+ </div>+ );+};++/** Disconnect asks for the master password; the items stay in Bitwarden. */+const DisconnectConfirm: React.FC<{ onCancel: () => void; onDone: (s: StoreStatus) => void }> = ({ onCancel, onDone }) => {+ const ref = useRef<HTMLInputElement>(null);+ const [busy, setBusy] = useState(false);+ const [error, setError] = useState<string | null>(null);+ useEffect(() => () => void takeSecret(ref, true), []);+ const submit = async (e: React.FormEvent) => {+ e.preventDefault();+ if (!ref.current?.value) return setError('Enter your master password.');+ setBusy(true);+ setError(null);+ try {+ const s = await storeApi.disconnect(takeSecret(ref, false));+ takeSecret(ref, true);+ playSfx('click');+ onDone(s);+ } catch (err) {+ setError(err instanceof Error ? err.message : 'Couldn’t disconnect.');+ if (err instanceof StoreError && err.problem.kind === 'wrong-password') takeSecret(ref, true);+ } finally {+ setBusy(false);+ }+ };+ return (+ <form onSubmit={submit} role="alertdialog" aria-label="Disconnect Bitwarden?" className="p-2 rounded-lg border border-rose-500/30 bg-rose-500/5 space-y-1.5" data-disconnect noValidate>+ <p className="text-[11px] text-zinc-200 leading-snug">Disconnect Bitwarden? New logins are saved on this server again. Your items stay in Bitwarden.</p>+ <label className="block">+ <span className="text-[10px] text-zinc-400 block mb-0.5">Master password</span>+ <input ref={ref} type="password" className={field} autoComplete="off" autoFocus />+ </label>+ {error && <ProblemLine text={error} />}+ <div className="flex justify-end gap-1.5">+ <button type="button" onClick={onCancel} className={btnQuiet}>+ Keep Bitwarden+ </button>+ <button type="submit" disabled={busy} className="px-2.5 py-1.5 rounded-lg text-[11px] font-semibold bg-rose-500 hover:bg-rose-400 text-zinc-950 disabled:opacity-50">+ {busy ? 'Disconnecting…' : 'Disconnect'}+ </button>+ </div>+ </form>+ );+};++/** One line about where passwords are kept, opening the picker and Bitwarden's account settings. */+export const PasswordStoreBar: React.FC<{+ store: PasswordStoreState;+ onUnlock: () => void;+ /** The list changed (moved, store switched): load it again. */+ onChanged: () => void;+ /** Tests open it. */+ initialOpen?: boolean;+ initialConnecting?: boolean;+ initialDisconnecting?: boolean;+}> = ({ store, onUnlock, onChanged, initialOpen = false, initialConnecting = false, initialDisconnecting = false }) => {+ const id = useId();+ const [open, setOpen] = useState(initialOpen);+ const [connecting, setConnecting] = useState(initialConnecting);+ const [disconnecting, setDisconnecting] = useState(initialDisconnecting);+ const [locking, setLocking] = useState(false);+ // Keeps the "Moved N" result on screen after the count drops to 0.+ const [migrated, setMigrated] = useState(false);+ const s = store.status;+ if (!s) return null;+ const bw = s.bitwarden;+ const onBitwarden = s.store === 'bitwarden' && !!bw;++ const changed = (next: StoreStatus) => {+ store.set(next);+ onChanged();+ };+ const lock = async () => {+ setLocking(true);+ try {+ changed(await storeApi.lock());+ playSfx('click');+ } catch {+ store.reload();+ } finally {+ setLocking(false);+ }+ };++ const summary = onBitwarden ? (+ <>+ {s.locked ? <Lock size={13} className="text-amber-300 flex-shrink-0" aria-hidden="true" /> : <ShieldCheck size={13} className="text-emerald-400 flex-shrink-0" aria-hidden="true" />}+ <span className="min-w-0 truncate">+ <span className="text-zinc-200 font-medium">Bitwarden</span>+ <span className="text-zinc-500"> · {bw!.email}</span>+ </span>+ <span className={`px-1.5 rounded text-[9px] font-mono border flex-shrink-0 ${s.locked ? 'bg-amber-500/10 text-amber-200 border-amber-500/30' : 'bg-emerald-500/10 text-emerald-300 border-emerald-500/20'}`}>+ {s.locked ? 'Locked' : 'Unlocked'}+ </span>+ </>+ ) : (+ <>+ <Server size={13} className="text-zinc-400 flex-shrink-0" aria-hidden="true" />+ <span className="min-w-0 truncate text-zinc-200 font-medium">Saved on this server</span>+ </>+ );++ return (+ <section className="rounded-xl border border-zinc-800/80 bg-zinc-900/50 text-xs" data-store-bar={onBitwarden ? (s.locked ? 'locked' : 'unlocked') : 'local'}>+ <div className="flex items-center gap-1.5 px-2.5 py-1.5">+ <button+ type="button"+ aria-expanded={open}+ aria-controls={`${id}-p`}+ onClick={() => setOpen((o) => !o)}+ className="flex-1 min-w-0 flex items-center gap-1.5 text-left text-[11px] rounded focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-500"+ >+ <span className="sr-only">Where passwords are kept: </span>+ {summary}+ <ChevronDown size={12} className={`ml-auto flex-shrink-0 text-zinc-500 transition-transform ${open ? 'rotate-180' : ''}`} aria-hidden="true" />+ </button>+ {onBitwarden && s.locked && (+ <button type="button" onClick={onUnlock} className="flex items-center gap-1 px-2 py-1 rounded-lg text-[11px] font-semibold bg-amber-400 hover:bg-amber-300 text-zinc-950 flex-shrink-0">+ <LockOpen size={11} aria-hidden="true" /> Unlock+ </button>+ )}+ {onBitwarden && !s.locked && (+ <button type="button" onClick={lock} disabled={locking} className="flex items-center gap-1 px-2 py-1 rounded-lg text-[11px] text-zinc-300 bg-zinc-800 hover:bg-zinc-700 flex-shrink-0 disabled:opacity-50">+ <Lock size={11} aria-hidden="true" /> Lock+ </button>+ )}+ </div>++ {open && (+ <div id={`${id}-p`} className="px-2.5 pb-2.5 pt-1 space-y-2 border-t border-zinc-800/80">+ <fieldset className="space-y-1.5">+ <legend className="text-[10px] text-zinc-400 mb-1">Where passwords are kept, for every bot</legend>+ <label className={`flex items-start gap-2 p-2 rounded-lg border cursor-pointer ${!onBitwarden && !connecting ? 'border-sky-500/60 bg-sky-500/10' : 'border-zinc-800 hover:border-zinc-700'}`}>+ <input+ type="radio"+ name={`${id}-store`}+ checked={!onBitwarden && !connecting}+ onChange={() => {+ setConnecting(false);+ if (onBitwarden) setDisconnecting(true);+ }}+ className="mt-0.5 accent-sky-500"+ />+ <span>+ <span className="block text-[11px] text-zinc-200 font-medium">Saved on this server</span>+ <span className="block text-[10px] text-zinc-500 leading-snug">Encrypted here. A bot with approvals off can read them, so use Bitwarden then.</span>+ </span>+ </label>+ <label className={`flex items-start gap-2 p-2 rounded-lg border cursor-pointer ${onBitwarden || connecting ? 'border-sky-500/60 bg-sky-500/10' : 'border-zinc-800 hover:border-zinc-700'}`}>+ <input+ type="radio"+ name={`${id}-store`}+ checked={onBitwarden || connecting}+ onChange={() => {+ setDisconnecting(false);+ if (!onBitwarden) setConnecting(true);+ }}+ className="mt-0.5 accent-sky-500"+ />+ <span>+ <span className="block text-[11px] text-zinc-200 font-medium">Bitwarden</span>+ <span className="block text-[10px] text-zinc-500 leading-snug">In your own Bitwarden account, in a folder of their own. Locked after every restart until you unlock it.</span>+ </span>+ </label>+ </fieldset>++ {connecting && !onBitwarden && (+ <div className="p-2.5 rounded-xl border border-sky-500/30 bg-zinc-900/90">+ <BitwardenLoginForm+ mode="connect"+ status={s}+ onCancel={() => setConnecting(false)}+ onDone={(next) => {+ setConnecting(false);+ changed(next);+ }}+ />+ </div>+ )}++ {onBitwarden && (+ <div className="space-y-2" data-bitwarden-account>+ <dl className="grid grid-cols-[auto_1fr] gap-x-2 gap-y-0.5 text-[10px]">+ <dt className="text-zinc-500">Account</dt>+ <dd className="text-zinc-300 break-all">{bw!.email}</dd>+ <dt className="text-zinc-500">Server</dt>+ <dd className="text-zinc-300 break-all">{serverLabel(bw!.server_url)}</dd>+ <dt className="text-zinc-500">Sign-in</dt>+ <dd className="text-zinc-300">{bw!.login === 'api_key' ? 'API key + master password' : 'Master password'}</dd>+ {!s.locked && bw!.item_count !== null && (+ <>+ <dt className="text-zinc-500">Logins</dt>+ <dd className="text-zinc-300">{bw!.item_count}</dd>+ </>+ )}+ </dl>+ {s.locked ? (+ s.local_count > 0 && <p className="text-[10px] text-zinc-500">{s.local_count} {s.local_count === 1 ? 'password is' : 'passwords are'} still saved on this server. Unlock to move them.</p>+ ) : (+ (s.local_count > 0 || migrated) && (+ <MigrateButton+ count={s.local_count}+ onDone={() => {+ setMigrated(true);+ store.reload();+ onChanged();+ }}+ />+ )+ )}+ {disconnecting ? (+ s.locked ? (+ <p className="text-[10px] text-zinc-400">Unlock Bitwarden first, then you can disconnect it.</p>+ ) : (+ <DisconnectConfirm+ onCancel={() => setDisconnecting(false)}+ onDone={(next) => {+ setDisconnecting(false);+ changed(next);+ }}+ />+ )+ ) : (+ <button type="button" onClick={() => setDisconnecting(true)} className="text-[10px] text-zinc-500 hover:text-rose-300 underline underline-offset-2">+ Disconnect Bitwarden+ </button>+ )}+ </div>+ )}+ </div>+ )}+ </section>+ );+};++/** The accepted autofill gap, said once, plainly, where approvals are off. */+export const AutofillGapNote: React.FC = () => (+ <p className="flex items-start gap-2 text-[10px] text-zinc-400 leading-snug" data-autofill-gap>+ <Info size={12} className="text-zinc-500 flex-shrink-0 mt-px" aria-hidden="true" />+ <span>+ <span className="text-zinc-300">Approvals are off.</span> {AUTOFILL_GAP_NOTE}+ </span>+ </p>+);diff --git a/frontend/src/components/SavedPasswordsPanel.tsx b/frontend/src/components/SavedPasswordsPanel.tsxindex 744c06d3..202d4d80 100644--- a/frontend/src/components/SavedPasswordsPanel.tsx+++ b/frontend/src/components/SavedPasswordsPanel.tsx@@ -1,5 +1,5 @@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 { AlertTriangle, Check, Copy, ExternalLink, Eye, EyeOff, Key, KeyRound, Loader2, Lock, LockOpen, Plus, Search, ShieldCheck, Trash2 } from 'lucide-react';import { PERSON_SIGNED_IN_EVENT, requestPersonToken } from '../auth';import { playSfx } from '../audio/chiptune';import {@@ -15,6 +15,7 @@ import {originLabel,passwordsApi,} from '../savedPasswords';+import { AutofillGapNote, PasswordStoreBar, PasswordStoreState, UnlockDialog } from './PasswordStorePanel';export interface SavedPasswordsState {logins: SavedLogin[];@@ -152,7 +153,7 @@ export const PendingLoginPrompt: React.FC<{};/** 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 }) => (+export const PasswordsProblemNotice: React.FC<{ problem: PasswordsProblem; onRetry: () => void; onUnlock?: () => void }> = ({ problem, onRetry, onUnlock }) => (<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>@@ -165,6 +166,14 @@ export const PasswordsProblemNotice: React.FC<{ problem: PasswordsProblem; onRet><KeyRound size={12} aria-hidden="true" /> Enter access token</button>+ ) : problem === 'locked' && onUnlock ? (+ <button+ type="button"+ onClick={onUnlock}+ className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-[11px] font-semibold text-zinc-950 bg-amber-400 hover:bg-amber-300"+ >+ <LockOpen size={12} aria-hidden="true" /> Unlock Bitwarden+ </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@@ -180,14 +189,30 @@ interface RowProps {onThisPage: boolean;onOpen?: (origin: string) => void;onDeleted: () => void;- /** Tests start a row revealed or asking to delete. */+ /** Bitwarden: Reveal asks for the master password first. */+ askMasterPassword?: boolean;+ /** Tests start a row revealed, asking to delete or asking for the master password. */initialRevealed?: string | null;initialConfirmDelete?: boolean;+ initialAsking?: 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 }) => {+export const SavedLoginRow: React.FC<RowProps> = ({+ sandboxId,+ login,+ onThisPage,+ onOpen,+ onDeleted,+ askMasterPassword = false,+ initialRevealed = null,+ initialConfirmDelete = false,+ initialAsking = false,+}) => {const [revealed, setRevealed] = useState<string | null>(initialRevealed);+ // The master password stays in its input (never in state) and is cleared once it's been sent.+ const [asking, setAsking] = useState(initialAsking);+ const masterRef = useRef<HTMLInputElement>(null);const [revealing, setRevealing] = useState(false);const [confirmDelete, setConfirmDelete] = useState(initialConfirmDelete);const [deleting, setDeleting] = useState(false);@@ -206,14 +231,34 @@ export const SavedLoginRow: React.FC<RowProps> = ({ sandboxId, login, onThisPagesetRevealed(null);return;}+ if (askMasterPassword && !asking) {+ setError(null);+ setAsking(true);+ return;+ }+ let master: string | undefined;+ if (askMasterPassword) {+ master = masterRef.current?.value ?? '';+ if (!master) {+ setError('Enter your Bitwarden master password.');+ masterRef.current?.focus();+ return;+ }+ }setRevealing(true);setError(null);try {- setRevealed(await passwordsApi.reveal(sandboxId, login.id));+ const pw = await passwordsApi.reveal(sandboxId, login.id, master);+ if (masterRef.current) masterRef.current.value = '';+ setAsking(false);+ setRevealed(pw);playSfx('click');} catch (e) {+ if (masterRef.current) masterRef.current.value = '';+ masterRef.current?.focus();setError(errorText(e, 'Couldn’t show this password.'));} finally {+ master = undefined;setRevealing(false);}};@@ -307,6 +352,42 @@ export const SavedLoginRow: React.FC<RowProps> = ({ sandboxId, login, onThisPage</div></div>{revealed !== null && <p className="mt-1 text-[10px] text-zinc-500">Hides again in 30 seconds.</p>}+ {asking && revealed === null && (+ <form+ onSubmit={(e) => {+ e.preventDefault();+ reveal();+ }}+ className="mt-1.5 flex items-end gap-1.5"+ data-ask-master+ noValidate+ >+ <label className="flex-1 min-w-0">+ <span className="text-[10px] text-zinc-400 block mb-0.5">Bitwarden master password, to show it</span>+ <input+ ref={masterRef}+ type="password"+ autoFocus+ autoComplete="off"+ 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"+ />+ </label>+ <button+ type="button"+ onClick={() => {+ if (masterRef.current) masterRef.current.value = '';+ setAsking(false);+ setError(null);+ }}+ className="px-2 py-1 rounded text-[11px] bg-zinc-800 hover:bg-zinc-700 text-zinc-200"+ >+ Cancel+ </button>+ <button type="submit" disabled={revealing} className="px-2 py-1 rounded text-[11px] font-semibold bg-sky-500 hover:bg-sky-400 text-zinc-950 disabled:opacity-50">+ Show+ </button>+ </form>+ )}{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">@@ -402,16 +483,32 @@ export const SavedPasswordsPanel: React.FC<{state: SavedPasswordsState;pageUrl: string;onOpen?: (origin: string) => void;- /** Tests open the add form. */+ /** Where passwords are kept (Bitwarden or this server); missing on older servers. */+ store?: PasswordStoreState;+ /** Some bot runs without asking: say plainly what autofill then exposes. */+ approvalsOff?: boolean;+ /** Tests open the add form or the unlock dialog. */initialAdding?: boolean;-}> = ({ sandboxId, state, pageUrl, onOpen, initialAdding = false }) => {+ initialUnlocking?: boolean;+}> = ({ sandboxId, state, pageUrl, onOpen, store, approvalsOff = false, initialAdding = false, initialUnlocking = false }) => {const [query, setQuery] = useState('');const [adding, setAdding] = useState(initialAdding);+ const [unlocking, setUnlocking] = useState(initialUnlocking);const shown = filterLogins(state.logins, query);const blocked = state.problem !== null;+ const bitwarden = store?.status?.store === 'bitwarden';+ const openUnlock = useCallback(() => setUnlocking(true), []);+ const closeUnlock = useCallback(() => setUnlocking(false), []);+ // The list says locked but the bar still shows unlocked (Bitwarden locked elsewhere): catch up.+ const storeReload = store?.reload;+ const staleUnlocked = state.problem === 'locked' && store?.status?.locked === false;+ useEffect(() => {+ if (staleUnlocked) storeReload?.();+ }, [staleUnlocked, storeReload]);return (<div className="flex-1 flex flex-col p-3 gap-2 overflow-hidden bg-zinc-950" data-saved-passwords>+ {store && state.problem !== 'needs-token' && <PasswordStoreBar store={store} onUnlock={openUnlock} onChanged={state.reload} />}{!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">@@ -451,7 +548,7 @@ export const SavedPasswordsPanel: React.FC<{<div className="flex-1 overflow-y-auto pr-0.5">{state.problem ? (- <PasswordsProblemNotice problem={state.problem} onRetry={state.reload} />+ <PasswordsProblemNotice problem={state.problem} onRetry={state.reload} onUnlock={store ? openUnlock : undefined} />) : 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…@@ -469,18 +566,39 @@ export const SavedPasswordsPanel: React.FC<{) : (<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} />+ <SavedLoginRow+ key={l.id}+ sandboxId={sandboxId}+ login={l}+ onThisPage={loginMatchesPage(l, pageUrl)}+ onOpen={onOpen}+ onDeleted={state.reload}+ askMasterPassword={bitwarden}+ />))}</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 className="p-2 rounded-lg bg-zinc-900/40 border border-zinc-800/60 space-y-1.5 text-[10px] text-zinc-400">+ <div className="flex items-start gap-2">+ <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">{bitwarden ? 'Kept in your Bitwarden, locked after every restart.' : '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>+ {approvalsOff && <AutofillGapNote />}</div>+ {unlocking && store && (+ <UnlockDialog+ status={store.status}+ onClose={closeUnlock}+ onUnlocked={(next) => {+ store.set(next);+ state.reload();+ }}+ />+ )}</div>);};diff --git a/frontend/src/components/VirtualMachinePane.tsx b/frontend/src/components/VirtualMachinePane.tsxindex 8d8afcd6..1cb6f113 100644--- a/frontend/src/components/VirtualMachinePane.tsx+++ b/frontend/src/components/VirtualMachinePane.tsx@@ -19,6 +19,7 @@ import { ComputerModeChip, ComputerModeError, LocalBrowserNote, OpenWindowButtonimport { browserFooterLabel, isBlankPage, showsLocalWindow } from '../computerMode';import { loginMatchesPage } from '../savedPasswords';import { PendingLoginPrompt, SavedPasswordsPanel, useSavedPasswords } from './SavedPasswordsPanel';+import { usePasswordStore } from './PasswordStorePanel';export interface TerminalLogEntry {command: string;@@ -40,6 +41,8 @@ export interface VirtualMachinePaneProps {onRefresh?: () => void;onRestartVm?: () => void;onNavigate?: (url: string) => void;+ /** Some bot in the space runs without asking (shown next to saved passwords). */+ approvalsOff?: boolean;}export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({@@ -56,12 +59,14 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({onRefresh,onRestartVm,onNavigate,+ approvalsOff = false,}) => {const [activeTab, setActiveTab] = useState<'browser' | 'terminal' | 'vault'>('browser');const [inputUrl, setInputUrl] = useState(activeUrl);// 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;+ const passwordStore = usePasswordStore(!!teamId && teamId !== 'default');// 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.@@ -520,6 +525,8 @@ export const VirtualMachinePane: React.FC<VirtualMachinePaneProps> = ({<SavedPasswordsPanelsandboxId={teamId}state={passwords}+ store={passwordStore}+ approvalsOff={approvalsOff}pageUrl={pageUrl}onOpen={onNavigatediff --git a/frontend/src/passwordStore.ts b/frontend/src/passwordStore.tsnew file mode 100644index 00000000..5bfa7356--- /dev/null+++ b/frontend/src/passwordStore.ts@@ -0,0 +1,237 @@+// Where saved passwords live: on this server (default) or in the person's Bitwarden. Bitwarden is+// locked after every restart; unlocking, revealing and disconnecting take the master password.+// The master password and an API key's client secret are read from their input at submit, sent in+// one request and never kept in React state, storage or logs. Every route is person-only.++import { isPersonOnlyBody, requestPersonToken } from './auth';++export interface BitwardenInfo {+ server_url: string;+ email: string;+ login: 'password' | 'api_key';+ client_id: string | null;+ unlocked: boolean;+ unlocked_at: string | null;+ item_count: number | null;+ last_sync: string | null;+}++/** GET /api/passwords/store */+export interface StoreStatus {+ store: 'local' | 'bitwarden';+ /** Bitwarden is the store and isn't unlocked: nothing is filled, the lists answer 423. */+ locked: boolean;+ /** Passwords still in the built-in store (what "Move to Bitwarden" would move). */+ local_count: number;+ bitwarden: BitwardenInfo | null;+}++const str = (v: unknown): string | null => (typeof v === 'string' ? v : null);+const num = (v: unknown): number | null => (typeof v === 'number' && Number.isFinite(v) ? v : null);++export function parseStoreStatus(raw: unknown): StoreStatus {+ const o = raw && typeof raw === 'object' ? (raw as Record<string, unknown>) : {};+ const b = o.bitwarden && typeof o.bitwarden === 'object' ? (o.bitwarden as Record<string, unknown>) : null;+ const bitwarden: BitwardenInfo | null = b+ ? {+ server_url: str(b.server_url) ?? '',+ email: str(b.email) ?? '',+ login: b.login === 'api_key' ? 'api_key' : 'password',+ client_id: str(b.client_id),+ unlocked: b.unlocked === true,+ unlocked_at: str(b.unlocked_at),+ item_count: num(b.item_count),+ last_sync: str(b.last_sync),+ }+ : null;+ const store = o.store === 'bitwarden' ? 'bitwarden' : 'local';+ return { store, locked: o.locked === true || (store === 'bitwarden' && !bitwarden?.unlocked), local_count: num(o.local_count) ?? 0, bitwarden };+}++/** The Bitwarden cloud servers; anything else is self-hosted (Vaultwarden too). */+export const BITWARDEN_CLOUDS = [+ { value: 'https://vault.bitwarden.com', label: 'bitwarden.com' },+ { value: 'https://vault.bitwarden.eu', label: 'bitwarden.eu' },+] as const;+export const DEFAULT_BITWARDEN_SERVER = BITWARDEN_CLOUDS[0].value;++/** A short name for the account's server: "bitwarden.com", or the self-hosted host. */+export function serverLabel(serverUrl: string): string {+ const cloud = BITWARDEN_CLOUDS.find((c) => c.value === serverUrl.replace(/\/+$/, ''));+ if (cloud) return cloud.label;+ try {+ return new URL(serverUrl).host || serverUrl;+ } catch {+ return serverUrl;+ }+}++/** What the person typed as a self-hosted server → an address the server accepts, or why not. */+export function checkServerUrl(input: string): { url: string } | { error: string } {+ const v = input.trim().replace(/\/+$/, '');+ if (!v) return { error: 'Enter your Bitwarden server’s address.' };+ const withScheme = v.includes('://') ? v : `https://${v}`;+ let u: URL;+ try {+ u = new URL(withScheme);+ } catch {+ return { error: 'That isn’t a web address.' };+ }+ const host = u.hostname.replace(/^\[|\]$/g, '');+ const loopback = host === 'localhost' || /^127\./.test(host) || host === '::1';+ if (u.protocol !== 'https:' && !(u.protocol === 'http:' && loopback)) return { error: 'The address must start with https:// (http works only on this computer).' };+ if (u.search || u.hash || u.username || u.password) return { error: 'Leave out anything after the address, and any name or password in it.' };+ return { url: `${u.origin}${u.pathname.replace(/\/+$/, '')}` };+}++/** Bitwarden's two-step login methods. Only the ones with a code to type can be done here. */+export const TWO_FACTOR_NAMES: Record<number, string> = {+ 0: 'Authenticator app',+ 1: 'Email',+ 2: 'Duo',+ 3: 'YubiKey',+ 4: 'FIDO U2F',+ 6: 'Duo (organisation)',+ 7: 'Passkey or security key',+};+const TYPED_CODE = new Set([0, 1, 3]);++/** The methods the account offers, usable ones (a code to type) first. */+export function twoFactorChoices(providers: unknown): Array<{ id: number; name: string; usable: boolean }> {+ const ids = (Array.isArray(providers) ? providers : [])+ .map((p) => (typeof p === 'number' ? p : typeof p === 'string' && /^\d+$/.test(p) ? Number(p) : NaN))+ .filter((n) => Number.isInteger(n) && n !== 5);+ const unique = [...new Set(ids)];+ return unique+ .map((id) => ({ id, name: TWO_FACTOR_NAMES[id] ?? `Method ${id}`, usable: TYPED_CODE.has(id) }))+ .sort((a, b) => Number(b.usable) - Number(a.usable));+}++/** Why an unlock (or a check of the master password) didn't go through. */+export type UnlockProblem =+ | { kind: 'needs-token' }+ | { kind: 'wrong-password' }+ | { kind: 'two-factor'; providers: Array<{ id: number; name: string; usable: boolean }> }+ | { kind: 'new-device-code' }+ | { kind: 'other-account' }+ | { kind: 'invalid'; message: string }+ | { kind: 'unreachable' }+ | { kind: 'locked' }+ | { kind: 'error'; message: string };++export function unlockProblemFor(status: number, body: unknown): UnlockProblem {+ const o = body && typeof body === 'object' ? (body as Record<string, unknown>) : {};+ const message = str(o.error) ?? '';+ if (status === 401 && isPersonOnlyBody(body)) return { kind: 'needs-token' };+ if (o.wrong_password === true) return { kind: 'wrong-password' };+ if (o.needs === 'two_factor') return { kind: 'two-factor', providers: twoFactorChoices(o.providers) };+ if (o.needs === 'new_device_otp') return { kind: 'new-device-code' };+ if (status === 409) return { kind: 'other-account' };+ if (status === 400) return { kind: 'invalid', message };+ if (status === 502) return { kind: 'unreachable' };+ if (status === 423 || o.locked === true) return { kind: 'locked' };+ if (status === 401) return { kind: 'invalid', message };+ return { kind: 'error', message: message || `The server answered ${status}.` };+}++export function unlockProblemText(p: UnlockProblem): string {+ switch (p.kind) {+ case 'needs-token':+ return 'This needs your access token first.';+ case 'wrong-password':+ return 'That master password isn’t right. After five wrong tries in a row Bitwarden stays locked.';+ case 'two-factor':+ return p.providers.some((x) => x.usable)+ ? 'Your account uses two-step login. Enter the code to continue.'+ : `Your account’s two-step login (${p.providers.map((x) => x.name).join(', ') || 'unknown'}) can’t be done here. Use an API key instead.`;+ case 'new-device-code':+ return 'Bitwarden emailed you a code to confirm this new device. Enter it to continue.';+ case 'other-account':+ return 'Another Bitwarden account is connected. Disconnect it first.';+ case 'invalid':+ return p.message ? capitalise(p.message) + '.' : 'Something in the form isn’t right.';+ case 'unreachable':+ return 'Bitwarden couldn’t be reached, or it refused. Check the server address and try again.';+ case 'locked':+ return 'Bitwarden is locked. Unlock it first.';+ case 'error':+ return p.message || 'Something went wrong.';+ }+}++const capitalise = (s: string) => (s ? s[0].toUpperCase() + s.slice(1) : s);++export class StoreError extends Error {+ constructor(public problem: UnlockProblem, public status: number) {+ super(unlockProblemText(problem));+ }+}++/** One person-only call. Quiet: a 401 here is often a wrong master password, not a missing+ * token, so the app-wide gate must not open. The person-only 401 asks for the token itself. */+async function call(url: string, method = 'GET', body?: unknown): Promise<unknown> {+ const init = {+ method,+ cache: 'no-store',+ kwntQuiet: true,+ headers: body === undefined ? undefined : { 'Content-Type': 'application/json' },+ body: body === undefined ? undefined : JSON.stringify(body),+ } as RequestInit;+ const res = await fetch(url, init);+ const answer = await res.json().catch(() => null);+ if (!res.ok) {+ const problem = unlockProblemFor(res.status, answer);+ if (problem.kind === 'needs-token') requestPersonToken();+ throw new StoreError(problem, res.status);+ }+ return answer;+}++export interface UnlockFields {+ master_password: string;+ /** First connect only (later the saved ones are used). */+ server_url?: string;+ email?: string;+ /** API-key login: the id is saved; the secret is asked for at every unlock. */+ client_id?: string;+ client_secret?: string;+ two_factor_provider?: number;+ two_factor_token?: string;+ new_device_otp?: string;+}++/** Drops empty optional fields so the server falls back to the saved settings. */+export function unlockBody(f: UnlockFields): UnlockFields {+ const out: UnlockFields = { master_password: f.master_password };+ for (const k of ['server_url', 'email', 'client_id', 'client_secret', 'two_factor_token', 'new_device_otp'] as const) {+ const v = f[k]?.trim();+ if (v) out[k] = k === 'client_secret' ? f[k] : v;+ }+ if (f.two_factor_token?.trim() && typeof f.two_factor_provider === 'number') out.two_factor_provider = f.two_factor_provider;+ return out;+}++export interface MigrateResult {+ moved: number;+ failed: number;+}++export function migrateText(r: MigrateResult): string {+ const moved = `Moved ${r.moved} ${r.moved === 1 ? 'password' : 'passwords'} to Bitwarden.`;+ return r.failed ? `${moved} ${r.failed} couldn’t be moved and ${r.failed === 1 ? 'stays' : 'stay'} on this server; try again.` : moved;+}++export const storeApi = {+ status: async () => parseStoreStatus(await call('/api/passwords/store')),+ unlock: async (f: UnlockFields) => parseStoreStatus(await call('/api/passwords/bitwarden/unlock', 'POST', unlockBody(f))),+ lock: async () => parseStoreStatus(await call('/api/passwords/bitwarden/lock', 'POST')),+ /** Back to the built-in store. The items stay in Bitwarden. */+ disconnect: async (master_password: string) => parseStoreStatus(await call('/api/passwords/bitwarden', 'DELETE', { master_password })),+ migrate: async (): Promise<MigrateResult> => {+ const o = (await call('/api/passwords/migrate', 'POST')) as Record<string, unknown> | null;+ return { moved: num(o?.moved) ?? 0, failed: num(o?.failed) ?? 0 };+ },+};++/** The one-line note shown where autofill meets approvals off (accepted gap, 2026-10-20). */+export const AUTOFILL_GAP_NOTE = 'While a password is being filled into a page, a bot that can run commands can read it.';diff --git a/frontend/src/savedPasswords.ts b/frontend/src/savedPasswords.tsindex 0d1e444a..fa351657 100644--- a/frontend/src/savedPasswords.ts+++ b/frontend/src/savedPasswords.ts@@ -2,7 +2,9 @@// 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).+// layer then asks for the token (see auth.ts). Where they're kept (Bitwarden or here) is passwordStore.ts.++import { isPersonOnlyBody, requestPersonToken } from './auth';/** GET /api/sandbox/:id/passwords → passwords[] */export interface SavedLogin {@@ -27,7 +29,7 @@ export interface PasswordsList {}/** 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';+export type PasswordsProblem = 'needs-token' | 'locked' | 'unavailable' | 'wrong-password' | 'error';/** How long a revealed password stays on screen. */export const REVEAL_MS = 30_000;@@ -119,6 +121,7 @@ export function filterLogins(list: SavedLogin[], query: string): SavedLogin[] {export function problemFor(status: number, body: unknown): PasswordsProblem {const o = body && typeof body === 'object' ? (body as Record<string, unknown>) : {};+ if (o.wrong_password === true) return 'wrong-password';if (status === 401) return 'needs-token';if (status === 423 || o.locked === true) return 'locked';if (status === 503) return 'unavailable';@@ -127,8 +130,9 @@ export function problemFor(status: number, body: unknown): PasswordsProblem {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.',+ locked: 'Bitwarden is locked. Unlock it to see saved passwords and fill them in.',unavailable: 'The password store isn’t available right now. Try again in a moment.',+ 'wrong-password': 'That master password isn’t right. After five wrong tries in a row Bitwarden stays locked.',error: 'Couldn’t load saved passwords.',};@@ -143,6 +147,8 @@ async function call(url: string, init?: RequestInit): Promise<unknown> {const body = await res.json().catch(() => null);if (!res.ok) {const problem = problemFor(res.status, body);+ // A quiet call that isn't the background list still asks for the token on a person-only 401.+ if (problem === 'needs-token' && (init as { kwntAskToken?: boolean } | undefined)?.kwntAskToken && isPersonOnlyBody(body)) requestPersonToken();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]);}@@ -160,9 +166,11 @@ const base = (sandboxId: string) => `/api/sandbox/${encodeURIComponent(sandboxIdexport 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;+ /** The one call that returns a password. Callers show it briefly and drop it. With Bitwarden it+ * takes the master password; quiet, because a wrong one answers 401 and that isn't the token. */+ reveal: async (sandboxId: string, id: string, masterPassword?: string): Promise<string> => {+ const init = { ...json('POST', masterPassword === undefined ? undefined : { master_password: masterPassword }), kwntQuiet: true, kwntAskToken: true } as RequestInit;+ const body = (await call(`${base(sandboxId)}/${encodeURIComponent(id)}/reveal`, init)) as { password?: unknown } | null;if (typeof body?.password !== 'string') throw new PasswordsError('error', 200, 'The server sent no password.');return body.password;},diff --git a/frontend/tests/bitwardenStore.test.mjs b/frontend/tests/bitwardenStore.test.mjsnew file mode 100644index 00000000..a27198b8--- /dev/null+++ b/frontend/tests/bitwardenStore.test.mjs@@ -0,0 +1,309 @@+// Saved passwords in Bitwarden (2026-10-20): the store picker and connect form, Locked → Unlock,+// Reveal with the master password, "Move N to Bitwarden", and the plain note about autofill with+// approvals off. The master password is read from its input at submit and never kept.+import assert from 'node:assert/strict';+import test from 'node:test';+import { readFileSync } from 'node:fs';+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, PasswordsProblemNotice } from './src/components/SavedPasswordsPanel';+ import { PasswordStoreBar, BitwardenLoginForm, MigrateButton, AutofillGapNote } from './src/components/PasswordStorePanel';+ import { OffConfirm } from './src/components/ApprovalsSetting';+ export * from './src/passwordStore';+ export { passwordsApi, problemFor } from './src/savedPasswords';+ export { OFF_CONSEQUENCES } from './src/approvalMode';+ export * as auth from './src/auth';+ const r = (C, p) => renderToStaticMarkup(React.createElement(C, p));+ const lists = (p) => ({ logins: [], pending: null, loading: false, problem: null, reload() {}, ...p });+ export const storeState = (status) => ({ status, problem: null, reload() {}, set() {} });+ export const panel = (s, p) => r(SavedPasswordsPanel, { sandboxId: 'k1', state: lists(s), pageUrl: '', ...p });+ export const row = (p) => r(SavedLoginRow, { sandboxId: 'k1', onThisPage: false, onDeleted() {}, ...p });+ export const problem = (problem, p) => r(PasswordsProblemNotice, { problem, onRetry() {}, ...p });+ export const bar = (status, p) => r(PasswordStoreBar, { store: storeState(status), onUnlock() {}, onChanged() {}, ...p });+ export const form = (p) => r(BitwardenLoginForm, { mode: 'connect', status: null, onDone() {}, onCancel() {}, ...p });+ export const migrate = (p) => r(MigrateButton, { count: 0, onDone() {}, ...p });+ export const gap = () => r(AutofillGapNote, {});+ export const offConfirm = () => r(OffConfirm, { title: 'Turn off?', busy: false, onCancel() {}, onConfirm() {} });+`);++const text = (html) => html.replace(/<[^>]+>/g, ' ').replace(/’/g, "'").replace(/'|'/g, "'").replace(/"/g, '"').replace(/&/g, '&').replace(/\s+/g, ' ').trim();+const buttons = (html) => [...html.matchAll(/<button[^>]*>([\s\S]*?)<\/button>/g)].map((x) => text(x[1]));+const inputs = (html) => [...html.matchAll(/<input[^>]*>/g)].map((x) => x[0]);+const login = (p) => ({ id: 'c1', origin: 'https://example.com', domain: 'example.com', username: 'alice', created_at: null, last_used: null, ...p });+const bw = (p) => ({ server_url: 'https://vault.bitwarden.com', email: '[email protected]', login: 'password', client_id: null, unlocked: true, unlocked_at: 't', item_count: 4, last_sync: 't', ...p });+const LOCAL = { store: 'local', locked: false, local_count: 3, bitwarden: null };+const UNLOCKED = { store: 'bitwarden', locked: false, local_count: 0, bitwarden: bw() };+const LOCKED = { store: 'bitwarden', locked: true, local_count: 0, bitwarden: bw({ unlocked: false, unlocked_at: null, item_count: null }) };++// ---------------------------------------------------------------- the model++test('store status: local, Bitwarden unlocked, Bitwarden locked (also when only "unlocked" says so)', () => {+ assert.deepEqual(m.parseStoreStatus({ store: 'local', locked: false, local_count: 3, bitwarden: null }), LOCAL);+ const u = m.parseStoreStatus({ store: 'bitwarden', locked: false, local_count: 0, bitwarden: { ...bw(), extra: 'x' } });+ assert.equal(u.locked, false);+ assert.equal(u.bitwarden.email, '[email protected]');+ assert.equal(m.parseStoreStatus({ store: 'bitwarden', locked: false, bitwarden: bw({ unlocked: false }) }).locked, true);+ assert.equal(m.parseStoreStatus({ store: 'bitwarden', locked: true, bitwarden: bw() }).locked, true);+ assert.deepEqual(m.parseStoreStatus(null), { store: 'local', locked: false, local_count: 0, bitwarden: null });+ assert.equal(m.parseStoreStatus({ store: 'local', bitwarden: bw({ login: 'api_key', client_id: 'user.x' }) }).bitwarden.login, 'api_key');+});++test('self-hosted address: https, or http only on this computer; nothing after the address', () => {+ assert.deepEqual(m.checkServerUrl('vault.example.com'), { url: 'https://vault.example.com' });+ assert.deepEqual(m.checkServerUrl(' https://vault.example.com/bw/ '), { url: 'https://vault.example.com/bw' });+ assert.deepEqual(m.checkServerUrl('http://127.0.0.1:18990'), { url: 'http://127.0.0.1:18990' });+ assert.deepEqual(m.checkServerUrl('http://localhost:8080'), { url: 'http://localhost:8080' });+ assert.ok('error' in m.checkServerUrl('http://vault.example.com'), 'plain http off this computer');+ assert.ok('error' in m.checkServerUrl('https://vault.example.com/?x=1'));+ assert.ok('error' in m.checkServerUrl('https://u:[email protected]'));+ assert.ok('error' in m.checkServerUrl(''));+ assert.equal(m.serverLabel('https://vault.bitwarden.eu'), 'bitwarden.eu');+ assert.equal(m.serverLabel('http://127.0.0.1:18990'), '127.0.0.1:18990');+});++test('two-step methods: the ones with a code to type come first; "remember" is dropped', () => {+ assert.deepEqual(m.twoFactorChoices(['7', '0', '5', 1]), [+ { id: 0, name: 'Authenticator app', usable: true },+ { id: 1, name: 'Email', usable: true },+ { id: 7, name: 'Passkey or security key', usable: false },+ ]);+ assert.deepEqual(m.twoFactorChoices(null), []);+});++test('unlock answers: token, wrong password, two-step, new device, other account, bad input, unreachable', () => {+ assert.deepEqual(m.unlockProblemFor(401, { person_only: true }), { kind: 'needs-token' });+ assert.deepEqual(m.unlockProblemFor(401, { wrong_password: true, error: 'x' }), { kind: 'wrong-password' });+ assert.equal(m.unlockProblemFor(401, { needs: 'two_factor', providers: ['0'] }).kind, 'two-factor');+ assert.deepEqual(m.unlockProblemFor(401, { needs: 'new_device_otp' }), { kind: 'new-device-code' });+ assert.deepEqual(m.unlockProblemFor(409, {}), { kind: 'other-account' });+ assert.deepEqual(m.unlockProblemFor(400, { error: 'the Bitwarden server must be an https address' }), { kind: 'invalid', message: 'the Bitwarden server must be an https address' });+ assert.equal(m.unlockProblemText(m.unlockProblemFor(400, { error: 'the master password is missing' })), 'The master password is missing.');+ assert.deepEqual(m.unlockProblemFor(502, {}), { kind: 'unreachable' });+ assert.deepEqual(m.unlockProblemFor(423, { locked: true }), { kind: 'locked' });+ assert.match(m.unlockProblemText({ kind: 'wrong-password' }), /five wrong tries/);+ assert.match(m.unlockProblemText({ kind: 'two-factor', providers: m.twoFactorChoices(['7']) }), /can't|can’t/);+ // The saved-passwords side: a wrong master password on Reveal is not "needs the token".+ assert.equal(m.problemFor(401, { wrong_password: true }), 'wrong-password');+ assert.equal(m.problemFor(401, { person_only: true }), 'needs-token');+});++test('the unlock body leaves out empty fields, and the two-step method only with a code', () => {+ assert.deepEqual(m.unlockBody({ master_password: 'DUMMY-MP', server_url: '', email: ' [email protected] ', client_id: ' ', two_factor_provider: 0 }), { master_password: 'DUMMY-MP', email: '[email protected]' });+ assert.deepEqual(m.unlockBody({ master_password: 'DUMMY-MP', two_factor_provider: 0, two_factor_token: ' 123456 ' }), { master_password: 'DUMMY-MP', two_factor_token: '123456', two_factor_provider: 0 });+ assert.deepEqual(m.unlockBody({ master_password: ' DUMMY ', client_secret: ' s ' }), { master_password: ' DUMMY ', client_secret: ' s ' }, 'secrets are sent as typed');+});++test('the API: quiet, uncached, the documented routes; a person-only 401 asks for the token, a wrong password doesn\'t', async () => {+ const calls = [];+ const events = [];+ const prevFetch = globalThis.fetch;+ const prevWindow = globalThis.window;+ globalThis.window = new EventTarget();+ window.addEventListener(m.auth.PERSON_TOKEN_EVENT, () => events.push('person'));+ let next = null;+ globalThis.fetch = async (url, init = {}) => {+ calls.push({ url, ...init });+ if (next) return next;+ if (url.endsWith('/migrate')) return new Response(JSON.stringify({ moved: 2, failed: 1 }), { status: 200 });+ return new Response(JSON.stringify(UNLOCKED), { status: 200 });+ };+ try {+ assert.deepEqual(await m.storeApi.status(), UNLOCKED);+ await m.storeApi.unlock({ master_password: 'DUMMY-MP', server_url: 'http://127.0.0.1:18990', email: '[email protected]' });+ await m.storeApi.lock();+ await m.storeApi.disconnect('DUMMY-MP');+ assert.deepEqual(await m.storeApi.migrate(), { moved: 2, failed: 1 });+ assert.deepEqual(calls.map((c) => `${c.method} ${c.url}`), [+ 'GET /api/passwords/store',+ 'POST /api/passwords/bitwarden/unlock',+ 'POST /api/passwords/bitwarden/lock',+ 'DELETE /api/passwords/bitwarden',+ 'POST /api/passwords/migrate',+ ]);+ assert.ok(calls.every((c) => c.kwntQuiet === true && c.cache === 'no-store'), 'quiet: a 401 here is often a wrong master password');+ assert.deepEqual(JSON.parse(calls[1].body), { master_password: 'DUMMY-MP', server_url: 'http://127.0.0.1:18990', email: '[email protected]' });+ assert.deepEqual(JSON.parse(calls[3].body), { master_password: 'DUMMY-MP' });++ next = new Response(JSON.stringify({ error: 'wrong master password', wrong_password: true }), { status: 401 });+ await assert.rejects(m.storeApi.unlock({ master_password: 'nope' }), (e) => e.problem.kind === 'wrong-password');+ assert.deepEqual(events, [], 'a wrong password is not a missing token');+ next = new Response(JSON.stringify({ error: 'x', person_only: true }), { status: 401 });+ await assert.rejects(m.storeApi.status(), (e) => e.problem.kind === 'needs-token');+ assert.deepEqual(events, ['person']);++ // Reveal in Bitwarden mode sends the master password, quietly.+ next = new Response(JSON.stringify({ password: 'DUMMY-PW' }), { status: 200 });+ assert.equal(await m.passwordsApi.reveal('k1', 'c1', 'DUMMY-MP'), 'DUMMY-PW');+ assert.deepEqual(JSON.parse(calls.at(-1).body), { master_password: 'DUMMY-MP' });+ next = new Response(JSON.stringify({ error: 'wrong master password', wrong_password: true }), { status: 401 });+ await assert.rejects(m.passwordsApi.reveal('k1', 'c1', 'nope'), (e) => e.problem === 'wrong-password' && /isn't right|isn’t right/.test(e.message));+ assert.deepEqual(events, ['person'], 'still no token prompt');+ } finally {+ globalThis.fetch = prevFetch;+ globalThis.window = prevWindow;+ }+});++test('migrate wording: moved, and what failed stays here', () => {+ assert.equal(m.migrateText({ moved: 3, failed: 0 }), 'Moved 3 passwords to Bitwarden.');+ assert.equal(m.migrateText({ moved: 1, failed: 2 }), 'Moved 1 password to Bitwarden. 2 couldn’t be moved and stay on this server; try again.');+});++// ---------------------------------------------------------------- the picker and the forms++test('the store bar: this server, Bitwarden unlocked with Lock, Bitwarden locked with Unlock', () => {+ const local = m.bar(LOCAL);+ assert.match(local, /data-store-bar="local"/);+ assert.match(text(local), /Saved on this server/);+ assert.deepEqual(buttons(local).length, 1, 'just the toggle');+ const open = m.bar(UNLOCKED);+ assert.match(text(open), /Bitwarden · [email protected] Unlocked/);+ assert.ok(buttons(open).includes('Lock'));+ const locked = m.bar(LOCKED);+ assert.match(locked, /data-store-bar="locked"/);+ assert.match(text(locked), /Locked/);+ assert.ok(buttons(locked).includes('Unlock'));+ assert.equal(m.bar(null), '', 'nothing until the status is known');+});++test('the picker: two choices, said plainly; Bitwarden opens the connect form', () => {+ const html = m.bar(LOCAL, { initialOpen: true });+ assert.match(text(html), /Where passwords are kept, for every bot/);+ assert.match(text(html), /Saved on this server Encrypted here\. A bot with approvals off can read them, so use Bitwarden then\./);+ assert.match(text(html), /Bitwarden In your own Bitwarden account/);+ assert.equal(inputs(html).filter((i) => /type="radio"/.test(i)).length, 2);+ const connecting = m.bar(LOCAL, { initialOpen: true, initialConnecting: true });+ assert.match(connecting, /data-bitwarden-form="connect"/);+ const storeRadios = (h) => inputs(h).filter((i) => /type="radio"/.test(i) && /-store"/.test(i));+ assert.deepEqual(storeRadios(html).map((i) => /checked/.test(i)), [true, false], 'on this server by default');+ assert.deepEqual(storeRadios(connecting).map((i) => /checked/.test(i)), [false, true], 'one choice at a time: Bitwarden while connecting');+});++test('connect form: server (cloud or self-hosted), email, password or API key; secrets are uncontrolled', () => {+ const html = m.form({});+ assert.match(text(html), /Connect Bitwarden/);+ assert.match(html, /<option value="https:\/\/vault.bitwarden.com"[^>]*>bitwarden.com/);+ assert.match(html, /<option value="https:\/\/vault.bitwarden.eu"[^>]*>bitwarden.eu/);+ assert.match(html, /<option value="self"[^>]*>Self-hosted/);+ assert.match(text(html), /Account email/);+ assert.match(text(html), /Sign in with Master password API key \+ master password/);+ const pw = inputs(html).filter((i) => /type="password"/.test(i));+ assert.equal(pw.length, 1, 'just the master password without an API key');+ assert.doesNotMatch(pw[0], /value=/, 'never a controlled value');+ assert.match(pw[0], /autoComplete="off"|autocomplete="off"/);+ assert.match(text(html), /never saved/);+ assert.deepEqual(buttons(html), ['Cancel', 'Connect']);++ const key = m.form({ initialApiKey: true });+ assert.match(text(key), /client_id/);+ assert.equal(inputs(key).filter((i) => /type="password"/.test(i)).length, 2, 'client_secret is a password field too');+ assert.ok(inputs(key).filter((i) => /type="password"/.test(i)).every((i) => !/value=/.test(i)));++ const self = m.form({ initialServer: 'self' });+ assert.match(self, /placeholder="https:\/\/vault.example.com"/);+});++test('unlock form: says which account, asks for the master password (and the client secret for an API key)', () => {+ const html = m.form({ mode: 'unlock', status: LOCKED });+ assert.match(text(html), /Unlock Bitwarden [email protected] on bitwarden.com/);+ assert.doesNotMatch(text(html), /Account email|Server/, 'server and email are already set up');+ assert.deepEqual(buttons(html), ['Cancel', 'Unlock']);+ const apiKey = m.form({ mode: 'unlock', status: { ...LOCKED, bitwarden: bw({ login: 'api_key', client_id: 'user.x', unlocked: false }) } });+ assert.match(text(apiKey), /client_secret Asked for at every unlock, and never kept\./);+ assert.equal(inputs(apiKey).filter((i) => /type="password"/.test(i)).length, 2);+});++test('two-step login and new-device code are asked for in the same form', () => {+ const tf = m.form({ mode: 'unlock', status: LOCKED, initialStep: { kind: 'two-factor', providers: m.twoFactorChoices(['0', '1']) } });+ assert.match(tf, /data-step="two-factor"/);+ assert.match(text(tf), /Method/);+ assert.match(tf, /autoComplete="one-time-code"|autocomplete="one-time-code"/);+ assert.deepEqual(buttons(tf), ['Cancel', 'Continue']);+ const only = m.form({ mode: 'unlock', status: LOCKED, initialStep: { kind: 'two-factor', providers: m.twoFactorChoices(['0']) } });+ assert.doesNotMatch(text(only), /Method/, 'no picker for one method');+ const passkey = m.form({ mode: 'unlock', status: LOCKED, initialStep: { kind: 'two-factor', providers: m.twoFactorChoices(['7']) }, initialProblem: { kind: 'two-factor', providers: m.twoFactorChoices(['7']) } });+ assert.match(text(passkey), /Use an API key instead/);+ assert.match(passkey, /<button type="submit" disabled=""/);+ const device = m.form({ mode: 'unlock', status: LOCKED, initialStep: { kind: 'new-device-code' } });+ assert.match(text(device), /Code from Bitwarden's email/);+ const wrong = m.form({ mode: 'unlock', status: LOCKED, initialProblem: { kind: 'wrong-password' } });+ assert.match(wrong, /role="alert"/);+ assert.match(text(wrong), /isn't right/);+});++// ---------------------------------------------------------------- locked, reveal, migrate, disconnect++test('locked: the list says so and offers Unlock Bitwarden', () => {+ const html = m.problem('locked', { onUnlock() {} });+ assert.match(text(html), /Bitwarden is locked\. Unlock it to see saved passwords and fill them in\./);+ assert.deepEqual(buttons(html), ['Unlock Bitwarden']);+ assert.deepEqual(buttons(m.problem('locked')), ['Try again'], 'an older server without a store keeps Try again');+ const p = m.panel({ problem: 'locked' }, { store: m.storeState(LOCKED) });+ assert.match(p, /data-store-bar="locked"/);+ assert.ok(buttons(p).includes('Unlock Bitwarden'));+ assert.doesNotMatch(m.panel({ problem: 'needs-token' }, { store: m.storeState(LOCKED) }), /data-store-bar/, 'no bar until the token is in');+});++test('Reveal with Bitwarden asks for the master password in the row', () => {+ const plain = m.row({ login: login(), askMasterPassword: true });+ assert.doesNotMatch(plain, /data-ask-master/, 'asked only after Reveal');+ const asking = m.row({ login: login(), askMasterPassword: true, initialAsking: true });+ assert.match(asking, /data-ask-master/);+ assert.match(text(asking), /Bitwarden master password, to show it/);+ const field = inputs(asking).find((i) => /type="password"/.test(i));+ assert.ok(field && !/value=/.test(field), 'uncontrolled');+ assert.ok(buttons(asking).includes('Show') && buttons(asking).includes('Cancel'));+ const panel = m.panel({ logins: [login()] }, { store: m.storeState(UNLOCKED) });+ assert.match(text(panel), /Kept in your Bitwarden, locked after every restart\./);+ assert.match(text(m.panel({ logins: [login()] }, { store: m.storeState(LOCAL) })), /Encrypted on the server/);+});++test('"Move N saved passwords to Bitwarden" only when unlocked with some left here; shows the result', () => {+ assert.deepEqual(buttons(m.migrate({ count: 3 })), ['Move 3 saved passwords to Bitwarden']);+ assert.deepEqual(buttons(m.migrate({ count: 1 })), ['Move 1 saved password to Bitwarden']);+ assert.deepEqual(buttons(m.migrate({ count: 0, initialResult: 'Moved 3 passwords to Bitwarden.' })), []);+ assert.match(m.migrate({ count: 0, initialResult: 'Moved 3 passwords to Bitwarden.' }), /role="status"/);+ const open = m.bar({ ...UNLOCKED, local_count: 2 }, { initialOpen: true });+ assert.ok(buttons(open).includes('Move 2 saved passwords to Bitwarden'));+ const locked = m.bar({ ...LOCKED, local_count: 2 }, { initialOpen: true });+ assert.ok(!buttons(locked).some((b) => b.startsWith('Move')));+ assert.match(text(locked), /2 passwords are still saved on this server\. Unlock to move them\./);+});++test('Disconnect asks for the master password and says the items stay in Bitwarden', () => {+ const html = m.bar(UNLOCKED, { initialOpen: true, initialDisconnecting: true });+ assert.match(html, /data-disconnect/);+ assert.match(text(html), /Your items stay in Bitwarden\./);+ assert.ok(buttons(html).includes('Keep Bitwarden') && buttons(html).includes('Disconnect'));+ assert.ok(inputs(html).some((i) => /type="password"/.test(i) && !/value=/.test(i)));+ assert.match(text(m.bar(LOCKED, { initialOpen: true, initialDisconnecting: true })), /Unlock Bitwarden first/);+ assert.match(text(m.bar(UNLOCKED, { initialOpen: true })), /Account [email protected] Server bitwarden.com Sign-in Master password Logins 4/);+});++// ---------------------------------------------------------------- the honest note++test('approvals off: one plain sentence about autofill, in the confirm and next to saved passwords', () => {+ const note = 'While a password is being filled into a page, a bot that can run commands can read it.';+ assert.equal(m.AUTOFILL_GAP_NOTE, note);+ assert.ok(m.OFF_CONSEQUENCES.includes(note));+ assert.ok(text(m.offConfirm()).includes(note));+ assert.ok(text(m.panel({ logins: [login()] }, { approvalsOff: true })).includes(note));+ assert.ok(!text(m.panel({ logins: [login()] }, { approvalsOff: false })).includes(note));+ assert.doesNotMatch(m.gap(), /rose|red-|amber/, 'no scare styling');+});++test('no master password in storage, logs or React state', () => {+ for (const f of ['src/passwordStore.ts', 'src/components/PasswordStorePanel.tsx', 'src/components/SavedPasswordsPanel.tsx']) {+ const src = readFileSync(new URL(`../${f}`, import.meta.url), 'utf8');+ assert.doesNotMatch(src, /localStorage|sessionStorage|console\./, f);+ assert.doesNotMatch(src, /const \[\s*\w*(master|secret)\w*\s*,/i, `${f}: no secret in state`);+ assert.doesNotMatch(src, /useState[^;\n]*(master|secret)/i, `${f}: no secret in state`);+ }+ // The check itself catches what it's for.+ assert.match('const [masterPassword, setMasterPassword] = useState(\'\');', /const \[\s*\w*(master|secret)\w*\s*,/i);+});diff --git a/frontend/tests/savedPasswords.test.mjs b/frontend/tests/savedPasswords.test.mjsindex 274d4337..5c046cbe 100644--- a/frontend/tests/savedPasswords.test.mjs+++ b/frontend/tests/savedPasswords.test.mjs@@ -90,7 +90,9 @@ test('the API: list is quiet and uncached, reveal is a POST, save sends the origassert.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');+ // Quiet, because with Bitwarden a wrong master password is also a 401; a person-only 401 asks for the token itself.+ assert.equal(calls[1].kwntQuiet, true, 'a wrong master password must not open the app-wide gate');+ assert.equal(calls[1].kwntAskToken, true, 'an explicit action still 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');