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
Saved passwords: approvals-off UI needs Bitwarden first (audit F-10)
Lin (kwant bot)9823b78397b5
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsxindex d88384d3..83e20273 100644--- a/frontend/src/App.tsx+++ b/frontend/src/App.tsx@@ -6,7 +6,7 @@ import { ChatView, ChatMessage, DiscussionState, RoutingState, QueuedState } froimport { ThreadBar, ThreadHeader } from './components/ThreadBar';import { DelegationCard } from './components/DelegationCard';import { ApprovalsOffBadge } from './components/ApprovalsSetting';-import { approvalsOff } from './approvalMode';+import { APPROVALS_CHANGED_EVENT, approvalsOff } from './approvalMode';import { QuestionCard } from './components/QuestionCard';import { McpSuggestionCard } from './components/McpSuggestionCard';import { Suggestion, SuggestionMeta, applySuggestion, suggestionsApi } from './mcpSuggestions';@@ -359,6 +359,11 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({useEffect(() => () => {if (rosterTimerRef.current) clearTimeout(rosterTimerRef.current);}, []);+ // "Turn approvals back on" from a password screen: the markers and space header catch up.+ useEffect(() => {+ window.addEventListener(APPROVALS_CHANGED_EVENT, refreshRoster);+ return () => window.removeEventListener(APPROVALS_CHANGED_EVENT, refreshRoster);+ }, [refreshRoster]);const markLive = (ctx: string | null | undefined, speaker?: string) => {if (!ctx) return;const name = speaker ?? liveRef.current[ctx] ?? '';diff --git a/frontend/src/approvalMode.ts b/frontend/src/approvalMode.tsindex dcf12531..e72377bc 100644--- a/frontend/src/approvalMode.ts+++ b/frontend/src/approvalMode.ts@@ -2,7 +2,7 @@// 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';+import { StoreStatus, autofillGapNote, needsBitwardenFrom } from './passwordStore';export type SpaceApprovals = 'ask' | 'off';export type BotApprovals = 'inherit' | 'ask' | 'off';@@ -58,9 +58,21 @@ 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,];+/** The same, with the saved-passwords sentence for where passwords are kept. */+export const offConsequences = (store: StoreStatus | null | undefined): string[] => [...OFF_CONSEQUENCES, autofillGapNote(store)];++/** The server refused "off" because passwords are still saved on it (audit F-10). */+export class NeedsBitwardenError extends Error {+ constructor(message: string, public localCount: number | null) {+ super(message);+ }+}++/** Fired after approvals change outside a settings screen, so lists and markers load again. */+export const APPROVALS_CHANGED_EVENT = 'kwnt:approvals-changed';+export function offConfirmTitle(who: { space: string } | { bot: string }): string {return 'space' in who ? `Turn off approvals for every bot in ${who.space}?` : `Let ${who.bot} run everything without approval?`;}@@ -75,9 +87,11 @@ export function spaceOffLine(space: SpaceApprovals | undefined, bots: Array<{ apreturn off ? `Approvals off for ${off} ${off === 1 ? 'bot' : 'bots'}` : null;}-async function errorText(res: Response, fallback: string): Promise<string> {+async function errorText(res: Response, fallback: string): Promise<string | NeedsBitwardenError> {try {const body = await res.json();+ const needs = needsBitwardenFrom(res.status, body);+ if (needs) return new NeedsBitwardenError(needs.message, needs.local_count);if (typeof body?.error === 'string' && body.error) {if (res.status === 403) return 'Only you can change approvals, from the app.';if (res.status === 409) return 'This space is archived. Restore it to change its approvals.';@@ -97,7 +111,10 @@ async function put(url: string, approvals: string, fallback: string): Promise<un} catch {throw new Error('Couldn’t reach the server. Check your connection and try again.');}- if (!res.ok) throw new Error(await errorText(res, fallback));+ if (!res.ok) {+ const e = await errorText(res, fallback);+ throw e instanceof Error ? e : new Error(e);+ }return res.json();}@@ -118,9 +135,59 @@ export const approvalModeApi = {return null;}},- setBot: async (kwantId: string, approvals: BotApprovals): Promise<BotApprovalsState> => {- const state = parseBotApprovals(await put(`/api/kwants/${enc(kwantId)}/approvals`, approvals, 'Couldn’t change this bot’s approvals'));+ setBot: async (kwantId: string, approvals: BotApprovals, spaceId?: string): Promise<BotApprovalsState> => {+ const url = `/api/kwants/${enc(kwantId)}/approvals${spaceId ? `?space=${enc(spaceId)}` : ''}`;+ const state = parseBotApprovals(await put(url, approvals, 'Couldn’t change this bot’s approvals'));if (!state) throw new Error('The server sent an answer the app can’t read. Reload and check the setting.');return state;},+ /**+ * "Turn approvals back on" everywhere: every active space that's off, and every bot set to off,+ * goes back to ask. Archived spaces can't be changed until they're restored; they count as failed.+ */+ turnAllOn: async (): Promise<{ changed: number; failed: number }> => {+ let changed = 0;+ let failed = 0;+ const list = async (url: string): Promise<Array<Record<string, unknown>>> => {+ const res = await fetch(url, { cache: 'no-store' });+ if (!res.ok) throw new Error('Couldn’t load your spaces. Try again.');+ const body = await res.json();+ return Array.isArray(body) ? body : [];+ };+ // `/api/spaces` lists the active spaces only; `?archived=1` lists only the archived ones.+ let spaces: Array<Record<string, unknown>>;+ try {+ const [active, archived] = await Promise.all([list('/api/spaces'), list('/api/spaces?archived=1').catch(() => [])]);+ spaces = [...active, ...archived];+ } catch {+ throw new Error('Couldn’t reach the server. Check your connection and try again.');+ }+ const attempt = async (f: () => Promise<unknown>) => {+ try {+ await f();+ changed++;+ } catch {+ failed++;+ }+ };+ for (const sp of spaces) {+ const id = typeof sp.id === 'string' ? sp.id : null;+ if (!id) continue;+ if (sp.approvals === 'off') {+ if (sp.archived_at) failed++;+ else await attempt(() => approvalModeApi.setSpace(id, 'ask'));+ }+ if (sp.archived_at) continue;+ const bots = await list(`/api/kwants?space=${enc(id)}`).catch(() => null);+ if (!bots) {+ failed++;+ continue;+ }+ for (const b of bots) {+ if (b.approvals === 'off' && typeof b.id === 'string') await attempt(() => approvalModeApi.setBot(b.id as string, 'ask', id));+ }+ }+ if (changed) window.dispatchEvent(new Event(APPROVALS_CHANGED_EVENT));+ return { changed, failed };+ },};diff --git a/frontend/src/components/ApprovalsSetting.tsx b/frontend/src/components/ApprovalsSetting.tsxindex 5a332e6d..dd0c9f3e 100644--- a/frontend/src/components/ApprovalsSetting.tsx+++ b/frontend/src/components/ApprovalsSetting.tsx@@ -6,14 +6,18 @@ import { AlertTriangle, Loader2, ShieldCheck, ShieldOff } from 'lucide-react';import {BotApprovals,BotApprovalsState,- OFF_CONSEQUENCES,+ NeedsBitwardenError,SPACE_OPTIONS,SpaceApprovals,approvalModeApi,botOptions,effectiveApprovals,offConfirmTitle,+ OFF_CONSEQUENCES,+ offConsequences,} from '../approvalMode';+import { StoreStatus, moveFirstLabel, moveFirstText } from '../passwordStore';+import { ExposedBanner, MoveToBitwardenFirst, PasswordStoreState, usePasswordStore } from './PasswordStorePanel';/** "Approvals off": in a chat header (full) or a sidebar row (icon, with the words for screen readers). */export const ApprovalsOffBadge: React.FC<{ compact?: boolean; onClick?: () => void; title?: string }> = ({ compact, onClick, title }) => {@@ -45,20 +49,42 @@ export const ApprovalsOffBadge: React.FC<{ compact?: boolean; onClick?: () => vo);};-/** The plain-words confirm before anything runs without asking. */-export const OffConfirm: React.FC<{ title: string; busy: boolean; onCancel: () => void; onConfirm: () => void }> = ({ title, busy, onCancel, onConfirm }) => {+/**+ * The plain-words confirm before anything runs without asking. With passwords still saved on this+ * server, "off" isn't offered: they move to Bitwarden first (the server refuses otherwise, F-10).+ */+export const OffConfirm: React.FC<{+ title: string;+ busy: boolean;+ onCancel: () => void;+ onConfirm: () => void;+ /** Where passwords are kept; missing on screens (and older servers) that don't know. */+ passwords?: PasswordStoreState;+}> = ({ title, busy, onCancel, onConfirm, passwords }) => {const id = useId();+ const status = passwords?.status ?? null;+ const mustMove = !!status && status.local_count > 0;+ // Still finding out: don't offer "off" for the moment it takes.+ const checking = !!passwords && !status && !passwords.problem;return (<div role="alertdialog" aria-labelledby={`${id}-t`} aria-describedby={`${id}-d`} className="rounded-lg border border-amber-500/40 bg-amber-500/10 p-3 space-y-2.5"><p id={`${id}-t`} className="flex items-center gap-2 text-xs font-semibold text-amber-100"><AlertTriangle size={14} aria-hidden="true" /> {title}</p><ul id={`${id}-d`} className="list-disc pl-5 space-y-1 text-[11px] text-amber-100/90">- {OFF_CONSEQUENCES.map((l) => (+ {/* With a move needed, the paragraph below says it; the note would repeat it. */}+ {(mustMove ? OFF_CONSEQUENCES : offConsequences(status)).map((l) => (<li key={l}>{l}</li>))}</ul>- <p className="text-[11px] text-amber-100/80">Bots can’t change this. You can turn approvals back on here at any time.</p>+ {mustMove ? (+ <div className="space-y-1.5 pt-0.5" data-off-needs-bitwarden>+ <p className="text-[11px] text-amber-100 leading-snug">{moveFirstText(status!.local_count)}</p>+ <MoveToBitwardenFirst store={passwords!} label={moveFirstLabel(status!.local_count)} />+ </div>+ ) : (+ <p className="text-[11px] text-amber-100/80">Bots can’t change this. You can turn approvals back on here at any time.</p>+ )}<div className="flex flex-wrap gap-2"><buttontype="button"@@ -68,20 +94,31 @@ export const OffConfirm: React.FC<{ title: string; busy: boolean; onCancel: () =>Keep asking</button>- <button- type="button"- onClick={onConfirm}- disabled={busy}- className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium text-white bg-rose-600 hover:bg-rose-500 disabled:opacity-50"- >- {busy && <Loader2 size={12} className="animate-spin motion-reduce:animate-none" aria-hidden="true" />}- Turn approvals off- </button>+ {!mustMove && (+ <button+ type="button"+ onClick={onConfirm}+ disabled={busy || checking}+ className="flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-medium text-white bg-rose-600 hover:bg-rose-500 disabled:opacity-50"+ >+ {(busy || checking) && <Loader2 size={12} className="animate-spin motion-reduce:animate-none" aria-hidden="true" />}+ {checking ? 'Checking saved passwords…' : 'Turn approvals off'}+ </button>+ )}</div></div>);};+/** A refused "off": show the move step when the store is known, else the server's sentence. */+function refusedOff(err: unknown, passwords: PasswordStoreState): string | null {+ if (!(err instanceof NeedsBitwardenError)) return err instanceof Error ? err.message : null;+ const known = passwords.status;+ if (known) passwords.set({ ...known, local_count: Math.max(err.localCount ?? 1, 1) });+ passwords.reload();+ return known ? null : err.message;+}+const radioCls = (on: boolean) =>`flex items-start gap-2.5 p-2.5 rounded-lg border cursor-pointer transition-colors ${on ? 'border-sky-500/60 bg-sky-500/10' : 'border-zinc-800 hover:border-zinc-700'}`;@@ -93,14 +130,21 @@ export const SpaceApprovalsSetting: React.FC<{/** Bots in the space that override it, so the person knows who won't follow. */overrides?: { ask: string[]; off: string[] };onChanged: (v: SpaceApprovals) => void;- /** Tests open it with the confirm showing. */+ /** Tests open it with the confirm showing, and say where passwords are kept. */initialConfirm?: boolean;-}> = ({ spaceId, spaceName, value, overrides, onChanged, initialConfirm = false }) => {+ initialPasswords?: StoreStatus | null;+}> = ({ spaceId, spaceName, value, overrides, onChanged, initialConfirm = false, initialPasswords = null }) => {const [current, setCurrent] = useState<SpaceApprovals>(value);const [confirming, setConfirming] = useState(initialConfirm);const [busy, setBusy] = useState(false);const [error, setError] = useState<string | null>(null);+ const passwords = usePasswordStore(true, true, initialPasswords);+ const storeReload = passwords.reload;useEffect(() => setCurrent(value), [value]);+ // Fresh numbers each time the confirm opens (a password may have been saved since).+ useEffect(() => {+ if (confirming) storeReload();+ }, [confirming, storeReload]);const save = async (v: SpaceApprovals) => {setBusy(true);@@ -110,8 +154,9 @@ export const SpaceApprovalsSetting: React.FC<{setCurrent(next);setConfirming(false);onChanged(next);+ storeReload();} catch (err) {- setError(err instanceof Error ? err.message : 'Couldn’t change approvals.');+ setError(v === 'off' ? refusedOff(err, passwords) : err instanceof Error ? err.message : 'Couldn’t change approvals.');} finally {setBusy(false);}@@ -130,6 +175,13 @@ export const SpaceApprovalsSetting: React.FC<{Approvals{current === 'off' && <ApprovalsOffBadge title={`Approvals are off in ${spaceName}.`} />}</p>+ <ExposedBanner+ store={passwords}+ onApprovalsOn={() => {+ setCurrent('ask');+ onChanged('ask');+ }}+ /><div role="radiogroup" aria-label={`Approvals in ${spaceName}`} className="space-y-1.5">{SPACE_OPTIONS.map((o) => (<label key={o.value} className={radioCls(current === o.value)}>@@ -152,7 +204,9 @@ export const SpaceApprovalsSetting: React.FC<{</label>))}</div>- {confirming && <OffConfirm title={offConfirmTitle({ space: spaceName })} busy={busy} onCancel={() => setConfirming(false)} onConfirm={() => save('off')} />}+ {confirming && (+ <OffConfirm title={offConfirmTitle({ space: spaceName })} busy={busy} passwords={passwords} onCancel={() => setConfirming(false)} onConfirm={() => save('off')} />+ )}{exceptions.length > 0 && !confirming && (<p className="text-[11px] text-zinc-500">{current === 'off' ? 'Still asks, set on the bot: ' : 'Runs without asking, set on the bot: '}@@ -178,14 +232,21 @@ export const BotApprovalsSetting: React.FC<{kwantId: string;kwantName: string;onChanged?: (s: BotApprovalsState) => void;- /** Tests pass the loaded state instead of fetching it. */+ /** Tests pass the loaded state instead of fetching it, a choice waiting on the confirm, and the store. */initial?: BotApprovalsState | null;-}> = ({ kwantId, kwantName, onChanged, initial }) => {+ initialPending?: BotApprovals | null;+ initialPasswords?: StoreStatus | null;+}> = ({ kwantId, kwantName, onChanged, initial, initialPending = null, initialPasswords = null }) => {const [state, setState] = useState<BotApprovalsState | null | undefined>(initial === undefined ? undefined : initial);- const [pending, setPending] = useState<BotApprovals | null>(null);+ const [pending, setPending] = useState<BotApprovals | null>(initialPending);const [busy, setBusy] = useState(false);const [error, setError] = useState<string | null>(null);const selectId = useId();+ const passwords = usePasswordStore(true, true, initialPasswords);+ const storeReload = passwords.reload;+ useEffect(() => {+ if (pending) storeReload();+ }, [pending, storeReload]);useEffect(() => {if (initial !== undefined) return;@@ -209,8 +270,9 @@ export const BotApprovalsSetting: React.FC<{setState(next);setPending(null);onChanged?.(next);+ storeReload();} catch (err) {- setError(err instanceof Error ? err.message : 'Couldn’t change this bot’s approvals.');+ setError(pending ? refusedOff(err, passwords) : err instanceof Error ? err.message : 'Couldn’t change this bot’s approvals.');} finally {setBusy(false);}@@ -243,7 +305,19 @@ export const BotApprovalsSetting: React.FC<{))}</select><p className="text-[11px] text-zinc-500">Saved as soon as you change it.</p>- {pending && <OffConfirm title={offConfirmTitle({ bot: kwantName })} busy={busy} onCancel={() => setPending(null)} onConfirm={() => save(pending)} />}+ <ExposedBanner+ store={passwords}+ onApprovalsOn={() =>+ approvalModeApi.bot(kwantId).then((s) => {+ if (!s) return;+ setState(s);+ onChanged?.(s);+ })+ }+ />+ {pending && (+ <OffConfirm title={offConfirmTitle({ bot: kwantName })} busy={busy} passwords={passwords} onCancel={() => setPending(null)} onConfirm={() => save(pending)} />+ )}{error && (<p role="alert" className="flex items-center gap-2 text-[11px] text-rose-300"><AlertTriangle size={12} aria-hidden="true" /> {error}diff --git a/frontend/src/components/PasswordStorePanel.tsx b/frontend/src/components/PasswordStorePanel.tsxindex 887b40d1..d18b02bc 100644--- a/frontend/src/components/PasswordStorePanel.tsx+++ b/frontend/src/components/PasswordStorePanel.tsx@@ -2,14 +2,16 @@ 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 { approvalModeApi } from '../approvalMode';import {- AUTOFILL_GAP_NOTE,BITWARDEN_CLOUDS,DEFAULT_BITWARDEN_SERVER,StoreError,StoreStatus,UnlockProblem,+ autofillGapNote,checkServerUrl,+ exposedText,migrateText,serverLabel,storeApi,@@ -25,16 +27,16 @@ export interface PasswordStoreState {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);+/** Where passwords are kept, loaded quietly (a missing token is the list's own state). `peek`+ * never opens the token dialog: for screens where the store is a side note (approvals settings). */+export function usePasswordStore(enabled: boolean, peek = false, initial: StoreStatus | null = null): PasswordStoreState {+ const [status, setStatus] = useState<StoreStatus | null>(initial);const [problem, setProblem] = useState<PasswordStoreState['problem']>(null);const seq = useRef(0);const reload = useCallback(() => {if (!enabled) return;const mine = ++seq.current;- storeApi- .status()+ (peek ? storeApi.peek() : storeApi.status()).then((s) => {if (mine !== seq.current) return;setStatus(s);@@ -44,7 +46,7 @@ export function usePasswordStore(enabled: boolean): PasswordStoreState {if (mine !== seq.current) return;setProblem(e instanceof StoreError && e.problem.kind === 'needs-token' ? 'needs-token' : 'error');});- }, [enabled]);+ }, [enabled, peek]);useEffect(reload, [reload]);useEffect(() => {window.addEventListener(PERSON_SIGNED_IN_EVENT, reload);@@ -613,12 +615,151 @@ export const PasswordStoreBar: React.FC<{);};-/** 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>-);+/** What approvals off means for saved passwords, said once, plainly, for where they're kept. */+export const AutofillGapNote: React.FC<{ status?: StoreStatus | null }> = ({ status }) => {+ const kind = status?.store === 'bitwarden' && status.local_count === 0 ? 'bitwarden' : 'local';+ return (+ <p className="flex items-start gap-2 text-[10px] text-zinc-400 leading-snug" data-autofill-gap={kind}>+ <Info size={12} className="text-zinc-500 flex-shrink-0 mt-px" aria-hidden="true" />+ <span>+ {/* The local sentence already starts with "With approvals off". */}+ {kind === 'bitwarden' && <span className="text-zinc-300">Approvals are off. </span>}+ {autofillGapNote(status)}+ </span>+ </p>+ );+};++/**+ * One button that gets the passwords on this server into Bitwarden: connect (first time) or+ * unlock (after a restart) in place, then move them. Pressing it is the person's go-ahead, so the+ * move runs as soon as Bitwarden is ready. Nothing moves until it's pressed.+ */+export const MoveToBitwardenFirst: React.FC<{+ store: PasswordStoreState;+ label: string;+ /** After the move, with what it says ("Moved 3 passwords to Bitwarden."). */+ onMoved?: (result: string) => void;+ /** Tests open a step. */+ initialStep?: 'connect' | 'unlock' | null;+}> = ({ store, label, onMoved, initialStep = null }) => {+ const [step, setStep] = useState<'connect' | 'unlock' | null>(initialStep);+ const [busy, setBusy] = useState(false);+ const [result, setResult] = useState<string | null>(null);+ const [error, setError] = useState<string | null>(null);+ const s = store.status;+ if (!s) return null;+ const ready = s.store === 'bitwarden' && !!s.bitwarden && !s.locked;++ const move = async () => {+ setBusy(true);+ setError(null);+ try {+ const r = await storeApi.migrate();+ const text = migrateText(r);+ setResult(text);+ playSfx(r.failed ? 'click' : 'coin');+ store.reload();+ onMoved?.(text);+ } catch (e) {+ setError(e instanceof Error ? e.message : 'Couldn’t move the passwords.');+ } finally {+ setBusy(false);+ }+ };+ const press = () => {+ setError(null);+ if (ready) move();+ else setStep(s.store === 'bitwarden' && s.bitwarden ? 'unlock' : 'connect');+ };++ return (+ <div className="space-y-1.5" data-move-first>+ {s.local_count > 0 && !step && (+ <button type="button" onClick={press} disabled={busy} className={btnMain}>+ {busy ? <Loader2 size={12} className="animate-spin motion-reduce:animate-none" aria-hidden="true" /> : <ArrowRight size={12} aria-hidden="true" />}+ {busy ? 'Moving…' : label}+ </button>+ )}+ {step && (+ <div className="p-2.5 rounded-xl border border-sky-500/30 bg-zinc-900/90 space-y-1.5" data-move-step={step}>+ <p className="text-[10px] text-zinc-400 leading-snug">+ {step === 'connect' ? 'Connect your Bitwarden account; the passwords move as soon as it’s connected.' : 'Unlock Bitwarden; the passwords move as soon as it’s unlocked.'}+ </p>+ <BitwardenLoginForm+ mode={step}+ status={s}+ onCancel={() => setStep(null)}+ onDone={(next) => {+ store.set(next);+ setStep(null);+ move();+ }}+ />+ </div>+ )}+ {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>+ );+};++/**+ * Approvals off with passwords still on this server (set up before that was blocked): said plainly+ * next to saved passwords and in approvals settings, with the two ways out. Nothing changes on its own.+ */+export const ExposedBanner: React.FC<{+ store: PasswordStoreState;+ /** After "Turn approvals back on", so the screen loads its approvals again. */+ onApprovalsOn?: () => void;+}> = ({ store, onApprovalsOn }) => {+ const id = useId();+ const [busy, setBusy] = useState(false);+ const [done, setDone] = useState<string | null>(null);+ const [error, setError] = useState<string | null>(null);+ const s = store.status;+ if (!s?.exposed)+ return done ? (+ <p role="status" className="flex items-start gap-1.5 text-[11px] text-emerald-300 leading-snug" data-exposed-done>+ <Check size={12} className="flex-shrink-0 mt-px" aria-hidden="true" /> {done}+ </p>+ ) : null;++ const turnOn = async () => {+ setBusy(true);+ setError(null);+ try {+ const r = await approvalModeApi.turnAllOn();+ playSfx('click');+ store.reload();+ onApprovalsOn?.();+ if (r.failed) setError(`${r.failed} ${r.failed === 1 ? 'setting' : 'settings'} couldn’t be changed. An archived space keeps its approvals until you restore it.`);+ else setDone('Approvals are back on. Bots ask before running commands again.');+ } catch (e) {+ setError(e instanceof Error ? e.message : 'Couldn’t turn approvals back on.');+ } finally {+ setBusy(false);+ }+ };++ return (+ <section role="region" aria-labelledby={`${id}-t`} className="p-2.5 rounded-xl border border-amber-500/40 bg-amber-500/10 space-y-2 text-xs" data-exposed>+ <p id={`${id}-t`} className="flex items-start gap-2 text-[11px] text-amber-100 leading-snug">+ <AlertTriangle size={13} className="flex-shrink-0 mt-px" aria-hidden="true" />+ <span>{exposedText(s.local_count)}</span>+ </p>+ <div className="flex flex-wrap items-start gap-1.5">+ <MoveToBitwardenFirst store={store} label="Move to Bitwarden" onMoved={setDone} />+ <button type="button" onClick={turnOn} disabled={busy} className={`${btnQuiet} flex items-center gap-1.5`}>+ {busy ? <Loader2 size={12} className="animate-spin motion-reduce:animate-none" aria-hidden="true" /> : <ShieldCheck size={12} aria-hidden="true" />}+ {busy ? 'Turning on…' : 'Turn approvals back on'}+ </button>+ </div>+ {error && <ProblemLine text={error} />}+ </section>+ );+};diff --git a/frontend/src/components/SavedPasswordsPanel.tsx b/frontend/src/components/SavedPasswordsPanel.tsxindex 202d4d80..4c75d556 100644--- a/frontend/src/components/SavedPasswordsPanel.tsx+++ b/frontend/src/components/SavedPasswordsPanel.tsx@@ -15,7 +15,7 @@ import {originLabel,passwordsApi,} from '../savedPasswords';-import { AutofillGapNote, PasswordStoreBar, PasswordStoreState, UnlockDialog } from './PasswordStorePanel';+import { AutofillGapNote, ExposedBanner, PasswordStoreBar, PasswordStoreState, UnlockDialog } from './PasswordStorePanel';export interface SavedPasswordsState {logins: SavedLogin[];@@ -436,6 +436,8 @@ const AddLoginForm: React.FC<{ sandboxId: string; onSaved: () => void; onCancel:onSaved();} catch (err) {setError(errorText(err, 'Couldn’t save this login.'));+ // It can't be saved here until Bitwarden is in use or approvals are back on: don't keep it typed.+ if (err instanceof PasswordsError && err.needsBitwarden) setPassword('');} finally {setBusy(false);}@@ -509,6 +511,7 @@ export const SavedPasswordsPanel: React.FC<{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} />}+ {store && state.problem !== 'needs-token' && <ExposedBanner store={store} onApprovalsOn={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">@@ -587,7 +590,8 @@ export const SavedPasswordsPanel: React.FC<{<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 />}+ {/* The exposed banner above already says it. */}+ {(approvalsOff || store?.status?.approvals_off) && !store?.status?.exposed && <AutofillGapNote status={store?.status} />}</div>{unlocking && store && (<UnlockDialogdiff --git a/frontend/src/passwordStore.ts b/frontend/src/passwordStore.tsindex 5bfa7356..053df2aa 100644--- a/frontend/src/passwordStore.ts+++ b/frontend/src/passwordStore.ts@@ -24,6 +24,11 @@ export interface StoreStatus {/** Passwords still in the built-in store (what "Move to Bitwarden" would move). */local_count: number;bitwarden: BitwardenInfo | null;+ /** Some space or bot runs without asking. */+ approvals_off: boolean;+ /** Approvals off while passwords are still saved here (an install from before the block): any+ * bot that can run commands can read them. Nothing changes it on its own. */+ exposed: boolean;}const str = (v: unknown): string | null => (typeof v === 'string' ? v : null);@@ -45,7 +50,16 @@ export function parseStoreStatus(raw: unknown): StoreStatus {}: 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 };+ const local_count = num(o.local_count) ?? 0;+ const approvals_off = o.approvals_off === true;+ return {+ store,+ locked: o.locked === true || (store === 'bitwarden' && !bitwarden?.unlocked),+ local_count,+ bitwarden,+ approvals_off,+ exposed: o.exposed === true,+ };}/** The Bitwarden cloud servers; anything else is self-hosted (Vaultwarden too). */@@ -169,7 +183,7 @@ export class StoreError extends Error {/** 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> {+async function call(url: string, method = 'GET', body?: unknown, askToken = true): Promise<unknown> {const init = {method,cache: 'no-store',@@ -181,7 +195,7 @@ async function call(url: string, method = 'GET', body?: unknown): Promise<unknowconst answer = await res.json().catch(() => null);if (!res.ok) {const problem = unlockProblemFor(res.status, answer);- if (problem.kind === 'needs-token') requestPersonToken();+ if (problem.kind === 'needs-token' && askToken) requestPersonToken();throw new StoreError(problem, res.status);}return answer;@@ -223,6 +237,8 @@ export function migrateText(r: MigrateResult): string {export const storeApi = {status: async () => parseStoreStatus(await call('/api/passwords/store')),+ /** The same, without asking for the token: for screens where the store is a side note. */+ peek: async () => parseStoreStatus(await call('/api/passwords/store', 'GET', undefined, false)),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. */@@ -233,5 +249,35 @@ export const storeApi = {},};-/** 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.';+/** One sentence per store for wherever approvals are off. Bitwarden: the accepted gap (2026-10-20).+ * This server: approvals off can't sit next to passwords here (audit F-10), so it's blocked. */+export const AUTOFILL_GAP_NOTE = {+ bitwarden: 'While a password is being filled into a page, a bot that can run commands can read it.',+ local: 'With approvals off, any bot that can run commands could read passwords saved on this server, so that’s blocked: use Bitwarden.',+} as const;++/** The note for a store; unknown counts as this server, the stricter one. */+export const autofillGapNote = (store: StoreStatus | null | undefined): string =>+ store?.store === 'bitwarden' && store.local_count === 0 ? AUTOFILL_GAP_NOTE.bitwarden : AUTOFILL_GAP_NOTE.local;++const passwords = (n: number) => `${n} saved ${n === 1 ? 'password' : 'passwords'}`;++/** Approvals can't go off while this server holds passwords: what the confirm says instead. */+export const moveFirstText = (n: number) =>+ `${capitalise(passwords(n))} ${n === 1 ? 'is' : 'are'} kept on this server. With approvals off, any bot that can run commands could read ${n === 1 ? 'it' : 'them'}, so move ${n === 1 ? 'it' : 'them'} to Bitwarden first.`;+export const moveFirstLabel = (n: number) => `Move ${passwords(n)} to Bitwarden first`;++/** An install already in that state (approvals off before the block). */+export const exposedText = (n: number) =>+ `Approvals are off and ${passwords(n)} ${n === 1 ? 'is' : 'are'} still on this server, so any bot that can run commands can read ${n === 1 ? 'it' : 'them'}.`;++/** A 409 that says the server wants Bitwarden first: its sentence, and how many passwords are here. */+export function needsBitwardenFrom(status: number, body: unknown): { message: string; local_count: number | null } | null {+ const o = body && typeof body === 'object' ? (body as Record<string, unknown>) : {};+ if (status !== 409 || o.needs_bitwarden !== true) return null;+ const msg = str(o.error)?.trim();+ return {+ message: msg ? capitalise(msg.endsWith('.') ? msg : `${msg}.`) : 'Move the passwords on this server to Bitwarden first.',+ local_count: num(o.local_count),+ };+}diff --git a/frontend/src/savedPasswords.ts b/frontend/src/savedPasswords.tsindex fa351657..a73b8db5 100644--- a/frontend/src/savedPasswords.ts+++ b/frontend/src/savedPasswords.ts@@ -5,6 +5,7 @@// layer then asks for the token (see auth.ts). Where they're kept (Bitwarden or here) is passwordStore.ts.import { isPersonOnlyBody, requestPersonToken } from './auth';+import { needsBitwardenFrom } from './passwordStore';/** GET /api/sandbox/:id/passwords → passwords[] */export interface SavedLogin {@@ -137,7 +138,7 @@ export const PROBLEM_TEXT: Record<PasswordsProblem, string> = {};export class PasswordsError extends Error {- constructor(public problem: PasswordsProblem, public status: number, message: string) {+ constructor(public problem: PasswordsProblem, public status: number, message: string, public needsBitwarden = false) {super(message);}}@@ -146,6 +147,9 @@ 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) {+ // Saving here while approvals are off (F-10): the server's own sentence says why and what to do.+ const needs = needsBitwardenFrom(res.status, body);+ if (needs) throw new PasswordsError('error', res.status, needs.message, true);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();diff --git a/frontend/tests/approvalsNeedBitwarden.test.mjs b/frontend/tests/approvalsNeedBitwarden.test.mjsnew file mode 100644index 00000000..d14ae13b--- /dev/null+++ b/frontend/tests/approvalsNeedBitwarden.test.mjs@@ -0,0 +1,268 @@+// Audit F-10 (2026-10-20): with approvals off, a bot that can run commands can read every password+// saved on this server. The server refuses that combination; these screens say so plainly and offer+// the way through: move the passwords to Bitwarden first, or turn approvals back on.+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 { SpaceApprovalsSetting, BotApprovalsSetting, OffConfirm } from './src/components/ApprovalsSetting';+ import { ExposedBanner, MoveToBitwardenFirst, AutofillGapNote } from './src/components/PasswordStorePanel';+ import { SavedPasswordsPanel } from './src/components/SavedPasswordsPanel';+ export * from './src/passwordStore';+ export { approvalModeApi, NeedsBitwardenError, APPROVALS_CHANGED_EVENT, offConsequences } from './src/approvalMode';+ export { passwordsApi, PasswordsError } from './src/savedPasswords';+ const r = (C, p) => renderToStaticMarkup(React.createElement(C, p));+ export const storeState = (status) => ({ status, problem: null, reload() {}, set() {} });+ export const confirm = (status, p) => r(OffConfirm, { title: 'Turn off approvals for every bot in Work?', busy: false, onCancel() {}, onConfirm() {}, passwords: status === undefined ? undefined : storeState(status), ...p });+ export const spaceSetting = (p) => r(SpaceApprovalsSetting, { spaceId: 'spc_1', spaceName: 'Work', value: 'ask', onChanged() {}, ...p });+ export const botSetting = (p) => r(BotApprovalsSetting, { kwantId: 'k1', kwantName: 'Dev', ...p });+ export const banner = (status) => r(ExposedBanner, { store: storeState(status) });+ export const moveFirst = (status, p) => r(MoveToBitwardenFirst, { store: storeState(status), label: 'Move 3 saved passwords to Bitwarden first', ...p });+ export const gap = (status) => r(AutofillGapNote, { status });+ export const panel = (status, p) =>+ r(SavedPasswordsPanel, { sandboxId: 'k1', state: { logins: [], pending: null, loading: false, problem: null, reload() {} }, pageUrl: '', store: storeState(status), ...p });+`);++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 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 st = (p) => ({ store: 'local', locked: false, local_count: 0, bitwarden: null, approvals_off: false, exposed: false, ...p });+const LOCAL3 = st({ local_count: 3 });+const LOCAL0 = st();+const BW = st({ store: 'bitwarden', bitwarden: bw() });+const BW_LEFTOVER = st({ store: 'bitwarden', bitwarden: bw(), local_count: 2 });+const BW_LOCKED = st({ store: 'bitwarden', locked: true, bitwarden: bw({ unlocked: false }), local_count: 3 });+const EXPOSED = st({ local_count: 3, approvals_off: true, exposed: true });+const LOCAL_NOTE = "With approvals off, any bot that can run commands could read passwords saved on this server, so that's blocked: use Bitwarden.";+const BW_NOTE = 'While a password is being filled into a page, a bot that can run commands can read it.';++// ---------------------------------------------------------------- the model++test('store status reads approvals_off and exposed; older servers mean neither', () => {+ const s = m.parseStoreStatus({ store: 'local', locked: false, local_count: 3, bitwarden: null, approvals_off: true, exposed: true });+ assert.equal(s.approvals_off, true);+ assert.equal(s.exposed, true);+ const old = m.parseStoreStatus({ store: 'local', local_count: 3 });+ assert.equal(old.approvals_off, false);+ assert.equal(old.exposed, false);+ assert.equal(m.parseStoreStatus({ exposed: 'yes' }).exposed, false, 'only true counts');+});++test('the note fits the store: Bitwarden (empty here) gets the fill gap, anything else the block', () => {+ assert.equal(text(m.autofillGapNote(BW)), BW_NOTE);+ assert.equal(text(m.autofillGapNote(LOCAL0)), LOCAL_NOTE);+ assert.equal(text(m.autofillGapNote(LOCAL3)), LOCAL_NOTE);+ assert.equal(text(m.autofillGapNote(BW_LEFTOVER)), LOCAL_NOTE, 'leftovers here open with the built-in key');+ assert.equal(text(m.autofillGapNote(null)), LOCAL_NOTE, 'unknown: the stricter one');+ for (const n of Object.values(m.AUTOFILL_GAP_NOTE)) assert.equal(n.split(/[.!?](\s|$)/).filter((x) => x && x.trim()).length, 1, `one sentence: ${n}`);+ assert.deepEqual(m.offConsequences(BW).at(-1), m.AUTOFILL_GAP_NOTE.bitwarden);+ assert.deepEqual(m.offConsequences(LOCAL0).at(-1), m.AUTOFILL_GAP_NOTE.local);+});++test('move-first and exposed wording, one and many', () => {+ assert.equal(m.moveFirstLabel(1), 'Move 1 saved password to Bitwarden first');+ assert.equal(m.moveFirstLabel(3), 'Move 3 saved passwords to Bitwarden first');+ assert.equal(+ text(m.moveFirstText(3)),+ "3 saved passwords are kept on this server. With approvals off, any bot that can run commands could read them, so move them to Bitwarden first.",+ );+ assert.match(text(m.moveFirstText(1)), /^1 saved password is kept .* read it, so move it to Bitwarden first\.$/);+ assert.equal(text(m.exposedText(3)), 'Approvals are off and 3 saved passwords are still on this server, so any bot that can run commands can read them.');+ assert.match(text(m.exposedText(1)), /1 saved password is still on this server, .* read it\.$/);+});++test('a 409 with needs_bitwarden: the server\'s sentence, capitalised, and the count; anything else is not it', () => {+ const body = { error: "approvals can't be switched off while passwords are saved on this server: a bot that can run commands could read them. Move them to Bitwarden first.", needs_bitwarden: true, local_count: 2 };+ const n = m.needsBitwardenFrom(409, body);+ assert.equal(n.local_count, 2);+ assert.match(n.message, /^Approvals can't be switched off/);+ assert.equal(m.needsBitwardenFrom(409, { error: 'x', needs_bitwarden: true }).local_count, null);+ assert.match(m.needsBitwardenFrom(409, { needs_bitwarden: true }).message, /Bitwarden/);+ assert.equal(m.needsBitwardenFrom(409, { error: 'this space is archived; restore it first' }), null);+ assert.equal(m.needsBitwardenFrom(400, body), null);+});++// ---------------------------------------------------------------- the API++async function withFetch(handler, fn) {+ const prevFetch = globalThis.fetch;+ const prevWindow = globalThis.window;+ globalThis.window = new EventTarget();+ const calls = [];+ globalThis.fetch = async (url, init = {}) => {+ calls.push({ url, method: init.method ?? 'GET', body: init.body });+ return handler(url, init);+ };+ try {+ return await fn(calls);+ } finally {+ globalThis.fetch = prevFetch;+ globalThis.window = prevWindow;+ }+}+const json = (b, status = 200) => new Response(JSON.stringify(b), { status });++test('approvals PUT refused for passwords here → NeedsBitwardenError with the count; archived 409 stays as before', async () => {+ const refusal = { error: "approvals can't be switched off while passwords are saved on this server: a bot that can run commands could read them. Move them to Bitwarden first.", needs_bitwarden: true, local_count: 3 };+ await withFetch(+ () => json(refusal, 409),+ async () => {+ await assert.rejects(m.approvalModeApi.setSpace('spc_1', 'off'), (e) => e instanceof m.NeedsBitwardenError && e.localCount === 3 && /^Approvals can't be switched off/.test(e.message));+ await assert.rejects(m.approvalModeApi.setBot('k1', 'inherit'), (e) => e instanceof m.NeedsBitwardenError && e.localCount === 3);+ },+ );+ await withFetch(+ () => json({ error: 'this space is archived; restore it first' }, 409),+ async () => {+ await assert.rejects(m.approvalModeApi.setSpace('spc_1', 'off'), (e) => !(e instanceof m.NeedsBitwardenError) && /archived/.test(e.message));+ },+ );+});++test('saving here while approvals are off: the 409 reason, not a generic error (Add and a caught login)', async () => {+ const refusal = { error: "passwords can't be saved on this server while approvals are off: a bot that can run commands could read them. Use Bitwarden, or turn approvals back on.", needs_bitwarden: true };+ await withFetch(+ () => json(refusal, 409),+ async (calls) => {+ for (const p of [m.passwordsApi.add('k1', 'https://example.com', 'alice', 'DUMMY-PW'), m.passwordsApi.savePending('k1')]) {+ await assert.rejects(p, (e) => e instanceof m.PasswordsError && e.needsBitwarden === true && e.status === 409 && /^Passwords can't be saved on this server while approvals are off/.test(e.message) && /Use Bitwarden, or turn approvals back on\.$/.test(e.message));+ }+ assert.deepEqual(calls.map((c) => `${c.method} ${c.url}`), ['POST /api/sandbox/k1/passwords', 'POST /api/sandbox/k1/passwords/pending']);+ },+ );+ // An ordinary failure is unchanged.+ await withFetch(+ () => json({ error: 'bad origin' }, 400),+ async () => {+ await assert.rejects(m.passwordsApi.add('k1', 'x', 'a', 'b'), (e) => e.needsBitwarden === false && e.message === 'bad origin');+ },+ );+ // The typed password isn't kept around after that refusal.+ const src = readFileSync(new URL('../src/components/SavedPasswordsPanel.tsx', import.meta.url), 'utf8');+ assert.match(src, /err\.needsBitwarden\) setPassword\(''\)/);+});++test('"Turn approvals back on": every active space that is off and every bot set to off → ask; archived counts as not changed', async () => {+ let changedEvents = 0;+ await withFetch(+ (url, init) => {+ // Like the server: the plain list is active spaces only, ?archived=1 only archived ones.+ if (url === '/api/spaces')+ return json([+ { id: 'spc_1', approvals: 'off', archived_at: null },+ { id: 'spc_2', approvals: 'ask', archived_at: null },+ ]);+ if (url === '/api/spaces?archived=1') return json([{ id: 'spc_old', approvals: 'off', archived_at: '2026-01-01' }]);+ if (url === '/api/kwants?space=spc_1') return json([{ id: 'k1', approvals: 'inherit' }, { id: 'k2', approvals: 'off' }]);+ if (url === '/api/kwants?space=spc_2') return json([{ id: 'k3', approvals: 'off' }, { id: 'k4', approvals: 'ask' }]);+ if (init.method === 'PUT' && url.startsWith('/api/spaces/')) return json({ approvals: 'ask' });+ if (init.method === 'PUT') return json({ kwant_id: url.split('/')[3], approvals: 'ask', approvals_effective: 'ask', space_approvals: 'ask' });+ return json({}, 404);+ },+ async (calls) => {+ window.addEventListener(m.APPROVALS_CHANGED_EVENT, () => changedEvents++);+ assert.deepEqual(await m.approvalModeApi.turnAllOn(), { changed: 3, failed: 1 });+ const puts = calls.filter((c) => c.method === 'PUT');+ assert.deepEqual(+ puts.map((c) => `${c.url} ${c.body}`),+ ['/api/spaces/spc_1/approvals {"approvals":"ask"}', '/api/kwants/k2/approvals?space=spc_1 {"approvals":"ask"}', '/api/kwants/k3/approvals?space=spc_2 {"approvals":"ask"}'],+ );+ assert.ok(!calls.some((c) => c.url.includes('spc_old')), 'an archived space is not touched');+ },+ );+ assert.equal(changedEvents, 1, 'the roster and markers load again');+});++// ---------------------------------------------------------------- the confirm++test('confirm with passwords here: "off" isn\'t offered; it says why and offers to move them first', () => {+ const html = m.confirm(LOCAL3);+ const t = text(html);+ assert.match(html, /data-off-needs-bitwarden/);+ assert.match(t, /3 saved passwords are kept on this server\. With approvals off, any bot that can run commands could read them, so move them to Bitwarden first\./);+ assert.deepEqual(buttons(html), ['Move 3 saved passwords to Bitwarden first', 'Keep asking']);+ assert.doesNotMatch(t, /Turn approvals off/);+ // The paragraph says it; the note isn't repeated above it.+ assert.ok(!t.includes(LOCAL_NOTE));+ // Bitwarden with leftovers here, and Bitwarden locked with some here: the same.+ assert.deepEqual(buttons(m.confirm(BW_LEFTOVER)), ['Move 2 saved passwords to Bitwarden first', 'Keep asking']);+ assert.deepEqual(buttons(m.confirm(BW_LOCKED)), ['Move 3 saved passwords to Bitwarden first', 'Keep asking']);+});++test('confirm with nothing here: "off" is offered, with the sentence for that store', () => {+ const b = m.confirm(BW);+ assert.deepEqual(buttons(b), ['Keep asking', 'Turn approvals off']);+ assert.ok(text(b).includes(BW_NOTE));+ assert.ok(!text(b).includes(LOCAL_NOTE));+ const l = m.confirm(LOCAL0);+ assert.deepEqual(buttons(l), ['Keep asking', 'Turn approvals off']);+ assert.ok(text(l).includes(LOCAL_NOTE), 'nothing saved yet, and saving here will be refused');+});++test('confirm while the store is still loading: "off" waits; with no store info (older screens) it is offered and the server decides', () => {+ const html = m.confirm(null);+ assert.match(text(html), /Checking saved passwords…|Checking saved passwords\.\.\./);+ assert.match(html, /<button[^>]*disabled=""[^>]*>[\s\S]*Checking saved passwords/);+ assert.deepEqual(buttons(m.confirm(undefined)), ['Keep asking', 'Turn approvals off']);+ const failed = m.confirm(undefined, { passwords: { status: null, problem: 'error', reload() {}, set() {} } });+ assert.deepEqual(buttons(failed), ['Keep asking', 'Turn approvals off'], 'store unreadable: the server\'s 409 is the backstop');+});++test('space and bot settings use it: move first with passwords here, off with none', () => {+ assert.match(text(m.spaceSetting({ initialConfirm: true, initialPasswords: LOCAL3 })), /Move 3 saved passwords to Bitwarden first/);+ assert.doesNotMatch(text(m.spaceSetting({ initialConfirm: true, initialPasswords: LOCAL3 })), /Turn approvals off/);+ const state = { kwant_id: 'k1', approvals: 'inherit', approvals_effective: 'ask', space_approvals: 'ask' };+ const bot = m.botSetting({ initial: state, initialPending: 'off', initialPasswords: LOCAL3 });+ assert.match(text(bot), /Let Dev run everything without approval\?/);+ assert.match(text(bot), /Move 3 saved passwords to Bitwarden first/);+ assert.doesNotMatch(text(bot), /Turn approvals off/);+ assert.match(text(m.botSetting({ initial: state, initialPending: 'off', initialPasswords: BW })), /Turn approvals off/);+});++test('move first: connect when there is no Bitwarden, unlock when it is locked, both in place', () => {+ assert.match(m.moveFirst(LOCAL3, { initialStep: 'connect' }), /data-bitwarden-form="connect"/);+ assert.match(text(m.moveFirst(LOCAL3, { initialStep: 'connect' })), /the passwords move as soon as it's connected/);+ assert.match(m.moveFirst(BW_LOCKED, { initialStep: 'unlock' }), /data-bitwarden-form="unlock"/);+ assert.match(text(m.moveFirst(BW_LOCKED, { initialStep: 'unlock' })), /dummy@example\.com/);+ assert.deepEqual(buttons(m.moveFirst(LOCAL3)), ['Move 3 saved passwords to Bitwarden first']);+ assert.equal(m.moveFirst(null), '', 'no store, nothing');+ // The master password stays in its input, never in state (same rule as the Bitwarden screens).+ const src = readFileSync(new URL('../src/components/PasswordStorePanel.tsx', import.meta.url), 'utf8');+ assert.doesNotMatch(src, /useState[^;\n]*(master|secret)/i);+});++// ---------------------------------------------------------------- old installs++test('exposed: a plain banner with both ways out, next to saved passwords and in approvals settings', () => {+ const html = m.banner(EXPOSED);+ assert.match(html, /data-exposed/);+ assert.match(html, /role="region"/);+ assert.equal(text(html).split(' Move to Bitwarden')[0], 'Approvals are off and 3 saved passwords are still on this server, so any bot that can run commands can read them.');+ assert.deepEqual(buttons(html), ['Move to Bitwarden', 'Turn approvals back on']);+ assert.equal(m.banner({ ...EXPOSED, exposed: false }), '', 'nothing when not exposed');+ assert.equal(m.banner(null), '');++ assert.match(m.panel(EXPOSED, { approvalsOff: true }), /data-exposed/);+ assert.doesNotMatch(m.panel(EXPOSED, { approvalsOff: true }), /data-autofill-gap/, 'the banner says it; no note repeating it');+ assert.doesNotMatch(m.panel(LOCAL3), /data-exposed/);+ assert.match(m.spaceSetting({ value: 'off', initialPasswords: EXPOSED }), /data-exposed/);+ assert.match(m.botSetting({ initial: { kwant_id: 'k1', approvals: 'off', approvals_effective: 'off', space_approvals: 'ask' }, initialPasswords: EXPOSED }), /data-exposed/);+ assert.doesNotMatch(m.spaceSetting({ value: 'ask', initialPasswords: LOCAL3 }), /data-exposed/);+});++test('next to saved passwords: the note follows the store, and shows when any bot runs without asking', () => {+ assert.ok(text(m.panel(st({ store: 'bitwarden', bitwarden: bw(), approvals_off: true }))).includes(BW_NOTE), 'the server says approvals are off somewhere');+ assert.ok(text(m.panel(st({ approvals_off: true }))).includes(LOCAL_NOTE));+ assert.ok(!text(m.panel(BW)).includes(BW_NOTE));+ assert.match(m.gap(BW), /data-autofill-gap="bitwarden"/);+ assert.match(m.gap(LOCAL0), /data-autofill-gap="local"/);+ for (const s of [BW, LOCAL0]) assert.doesNotMatch(m.gap(s), /rose|red-|amber/, 'no scare styling');+ assert.equal(text(m.gap(BW)), `Approvals are off. ${BW_NOTE}`);+ assert.equal(text(m.gap(LOCAL0)), LOCAL_NOTE, 'no "Approvals are off." before "With approvals off"');+});diff --git a/frontend/tests/approvalsOff.test.mjs b/frontend/tests/approvalsOff.test.mjsindex 85f40fe1..be2e533e 100644--- a/frontend/tests/approvalsOff.test.mjs+++ b/frontend/tests/approvalsOff.test.mjs@@ -129,7 +129,7 @@ test('space control: Ask is the default and checked, Don\'t ask explains itself,});test('space control: the confirm says plainly what off means, and Keep asking is the safe default focus', () => {- const html = m.spaceSetting({ initialConfirm: true });+ const html = m.spaceSetting({ initialConfirm: true, initialPasswords: { store: 'local', locked: false, local_count: 0, bitwarden: null, approvals_off: false, exposed: false } });const t = text(html);assert.match(html, /role="alertdialog"/);assert.match(t, /Turn off approvals for every bot in Work\?/);diff --git a/frontend/tests/bitwardenStore.test.mjs b/frontend/tests/bitwardenStore.test.mjsindex a27198b8..7d233307 100644--- a/frontend/tests/bitwardenStore.test.mjs+++ b/frontend/tests/bitwardenStore.test.mjs@@ -27,7 +27,7 @@ const m = await loadBundled(`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 gap = (status) => r(AutofillGapNote, { status });export const offConfirm = () => r(OffConfirm, { title: 'Turn off?', busy: false, onCancel() {}, onConfirm() {} });`);@@ -36,9 +36,9 @@ const buttons = (html) => [...html.matchAll(/<button[^>]*>([\s\S]*?)<\/button>/gconst 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 }) };+const LOCAL = { store: 'local', locked: false, local_count: 3, bitwarden: null, approvals_off: false, exposed: false };+const UNLOCKED = { store: 'bitwarden', locked: false, local_count: 0, bitwarden: bw(), approvals_off: false, exposed: false };+const LOCKED = { store: 'bitwarden', locked: true, local_count: 0, bitwarden: bw({ unlocked: false, unlocked_at: null, item_count: null }), approvals_off: false, exposed: false };// ---------------------------------------------------------------- the model@@ -49,7 +49,7 @@ test('store status: local, Bitwarden unlocked, Bitwarden locked (also when onlyassert.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.deepEqual(m.parseStoreStatus(null), { store: 'local', locked: false, local_count: 0, bitwarden: null, approvals_off: false, exposed: false });assert.equal(m.parseStoreStatus({ store: 'local', bitwarden: bw({ login: 'api_key', client_id: 'user.x' }) }).bitwarden.login, 'api_key');});@@ -287,14 +287,15 @@ test('Disconnect asks for the master password and says the items stay in Bitward// ---------------------------------------------------------------- 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('approvals off: one plain sentence per store, in the confirm and next to saved passwords', () => {+ // Bitwarden: the accepted gap. This server: blocked (audit F-10), so the sentence says so.+ const bwNote = 'While a password is being filled into a page, a bot that can run commands can read it.';+ assert.equal(m.AUTOFILL_GAP_NOTE.bitwarden, bwNote);+ assert.match(m.AUTOFILL_GAP_NOTE.local, /^With approvals off, any bot that can run commands could read passwords saved on this server, so that's blocked|^With approvals off, any bot that can run commands could read passwords saved on this server, so that’s blocked/);+ assert.ok(text(m.offConfirm()).includes(text(m.AUTOFILL_GAP_NOTE.local)), 'unknown store: the stricter sentence');+ assert.ok(text(m.panel({ logins: [login()] }, { approvalsOff: true, store: m.storeState(UNLOCKED) })).includes(bwNote));+ assert.ok(!text(m.panel({ logins: [login()] }, { approvalsOff: false, store: m.storeState(UNLOCKED) })).includes(bwNote));+ for (const st of [undefined, UNLOCKED, { ...LOCAL, local_count: 0 }]) assert.doesNotMatch(m.gap(st), /rose|red-|amber/, 'no scare styling');});test('no master password in storage, logs or React state', () => {