SPB Git

Repository Public

Settings.tsx 16.8 KB 199 lines tsx

1// Settings: appearance, timers, import / export / backup, recovery key, passkeys, session, security statement.2import { useEffect, useRef, useState } from "react";3import { accountFingerprint, importAny, type ImportResult, unb64u } from "../../../../packages/protocol/src/index.ts";4import type { VaultView } from "../core/engine.ts";5import { applyTheme, confirmAction, downloadBlob, engine, setPrefs, type Theme, toast, usePrefs, useTheme } from "../state.ts";6import { Btn, Callout, ErrorText, Field, Fingerprint, PageHead, Section, Segmented, useAction } from "./common.tsx";7import { KitOverlay } from "./Devices.tsx";8import { canWrite } from "./itemmeta.ts";9import { RecoveryKeyInput } from "./Onboarding.tsx";1011const FORMAT: Record<string, string> = { apple: "Apple Passwords CSV", "1password": "1Password CSV", "bitwarden-csv": "Bitwarden CSV", "bitwarden-json": "Bitwarden JSON", chrome: "Chrome / Edge CSV", generic: "Generic CSV" };12const stamp = () => new Date().toISOString().slice(0, 10);1314function ImportBox({ vaults }: { vaults: VaultView[] }) {15  const input = useRef<HTMLInputElement>(null);16  const writable = vaults.filter(canWrite);17  const [parsed, setParsed] = useState<(ImportResult & { fileName: string }) | null>(null);18  const [vaultId, setVaultId] = useState(writable[0]?.vaultId ?? "");19  const [progress, setProgress] = useState<{ done: number; total: number } | null>(null);20  const [done, setDone] = useState(0);21  const act = useAction();22  const read = (file: File) => act.run(async () => {23    setDone(0); setParsed(null);24    if (file.size > 20 * 1024 * 1024) throw new Error("This file is larger than 20 MB.");25    setParsed({ ...importAny(file.name, await file.text()), fileName: file.name });26  });27  const run = () => act.run(async () => {28    const items = parsed!.items;29    setProgress({ done: 0, total: items.length });30    try {31      for (let i = 0; i < items.length; i++) { await engine.importItems(vaultId, [items[i]!]); setProgress({ done: i + 1, total: items.length }); }32      setDone(items.length); setParsed(null);33    } finally { setProgress(null); if (input.current) input.current.value = ""; }34  });35  return (36    <div className="stack">37      <p className="muted">CSV exports from Apple Passwords, 1Password, Chrome or Bitwarden, and Bitwarden JSON. The file is read in this browser only; each entry is encrypted before it is sent.</p>38      <input ref={input} type="file" accept=".csv,.json,text/csv,application/json" className="sr-only" tabIndex={-1} aria-hidden="true" data-testid="import-input" onChange={(e) => { const f = e.target.files?.[0]; if (f) void read(f); }} />39      <div className="row wrap"><Btn icon="upload" onClick={() => input.current?.click()} disabled={act.busy}>Choose a file…</Btn></div>40      <ErrorText text={act.error} />41      {parsed && (42        <div className="card pad stack" data-testid="import-preview">43          <p><strong>{parsed.items.length}</strong> item{parsed.items.length === 1 ? "" : "s"} found in <span className="mono">{parsed.fileName}</span> · format: <strong>{FORMAT[parsed.format] ?? parsed.format}</strong>{parsed.skipped ? ` · ${parsed.skipped} row${parsed.skipped === 1 ? "" : "s"} skipped` : ""}</p>44          {parsed.warnings.length > 0 && <Callout kind="warn" title="Warnings"><ul className="plain">{parsed.warnings.map((w, i) => <li key={i}>{w}</li>)}</ul></Callout>}45          <Field label="Import into"><select className="input" value={vaultId} onChange={(e) => setVaultId(e.target.value)} data-testid="import-vault">{writable.map((v) => <option key={v.vaultId} value={v.vaultId}>{v.meta.name}</option>)}</select></Field>46          {progress ? <div className="progress-row" role="status"><span>Encrypting {progress.done} of {progress.total}…</span><progress max={progress.total || 1} value={progress.done} aria-label="Import progress" /></div>47            : <div className="row end"><Btn onClick={() => { setParsed(null); if (input.current) input.current.value = ""; }}>Discard</Btn><Btn variant="primary" onClick={run} disabled={!vaultId || parsed.items.length === 0} data-testid="import-run">Import {parsed.items.length} item{parsed.items.length === 1 ? "" : "s"}</Btn></div>}48        </div>49      )}50      {done > 0 && (51        <Callout kind="warn" title={`${done} item${done === 1 ? "" : "s"} imported`}>52          <p data-testid="import-done">The file you imported contains your passwords in clear text. Delete it and empty the trash.</p>53        </Callout>54      )}55    </div>56  );57}5859function BackupBox() {60  const exp = useAction(), res = useAction();61  const input = useRef<HTMLInputElement>(null);62  const [file, setFile] = useState<{ name: string; text: string } | null>(null);63  const [key, setKey] = useState("");64  const [restored, setRestored] = useState<number | null>(null);65  const exportBackup = () => exp.run(async () => { downloadBlob(await engine.exportBackup(), `sp-vault-backup-${stamp()}.spvault`, "application/json"); toast("Encrypted backup downloaded", "ok"); });66  const restore = () => res.run(async () => { setRestored(await engine.restoreBackup(file!.text, key.trim() || undefined)); setFile(null); setKey(""); if (input.current) input.current.value = ""; });67  return (68    <div className="stack">69      <div className="setting-row">70        <div><strong>Export encrypted backup</strong><p className="muted">A self-contained <span className="mono">.spvault</span> file holding every item you can read, encrypted under your account key. It can be restored with the recovery key that is valid today, even without this server. Attachments are not included.</p></div>71        <Btn icon="download" onClick={exportBackup} busy={exp.busy} data-testid="export-backup">Export backup</Btn>72      </div>73      <ErrorText text={exp.error} />74      <div className="setting-row">75        <div><strong>Restore a backup</strong><p className="muted">Items are restored into new vaults named “… (restored date)”. Nothing existing is overwritten.</p></div>76        <input ref={input} type="file" accept=".spvault,.json,application/json" className="sr-only" tabIndex={-1} aria-hidden="true" data-testid="restore-input" onChange={async (e) => { const f = e.target.files?.[0]; if (f) { setRestored(null); setFile({ name: f.name, text: await f.text() }); } }} />77        <Btn icon="upload" onClick={() => input.current?.click()} disabled={res.busy}>Choose backup…</Btn>78      </div>79      {file && (80        <div className="card pad stack">81          <p>Selected: <span className="mono">{file.name}</span></p>82          <RecoveryKeyInput value={key} onChange={setKey} testid="restore-key" />83          <p className="fine">Leave the recovery key empty for a backup made under the current account key. A backup made before an account rekey needs the recovery key that was valid when it was created.</p>84          <ErrorText text={res.error} />85          <div className="row end"><Btn onClick={() => setFile(null)}>Cancel</Btn><Btn variant="primary" onClick={restore} busy={res.busy} data-testid="restore-run">Restore</Btn></div>86        </div>87      )}88      {restored !== null && <Callout kind="ok" title="Backup restored"><p data-testid="restore-done">{restored} item{restored === 1 ? "" : "s"} restored into new vaults.</p></Callout>}89    </div>90  );91}9293function PlaintextExport() {94  const act = useAction();95  const run = async (format: "csv" | "json") => {96    if (!(await confirmAction({ title: "Export everything in clear text?", danger: true, confirmLabel: "Export in clear text", typeToConfirm: "EXPORT", body: [97      `A ${format.toUpperCase()} file containing every password, code seed and note you can read will be written to your downloads folder, unencrypted. Any program or person with access to that file can read it.`,98      "Your passkey is requested first, and the export is recorded in the activity log of all your devices. Prefer the encrypted backup unless you are moving to another password manager."] }))) return;99    await act.run(async () => {100      const text = await engine.exportPlaintext(format);101      downloadBlob(text, `sp-vault-export-${stamp()}.${format}`, format === "csv" ? "text/csv" : "application/json");102      toast("Plaintext export downloaded. Delete the file as soon as you are done with it.", "danger");103    });104  };105  return (106    <div className="stack">107      <div className="setting-row">108        <div><strong>Export in clear text</strong><p className="muted">Unencrypted CSV (logins) or JSON (everything). Requires a fresh passkey confirmation.</p></div>109        <div className="row"><Btn variant="danger" onClick={() => run("csv")} disabled={act.busy} data-testid="export-csv">CSV…</Btn><Btn variant="danger" onClick={() => run("json")} disabled={act.busy} data-testid="export-json">JSON…</Btn></div>110      </div>111      <ErrorText text={act.error} />112    </div>113  );114}115116export function SettingsPage({ vaults, onBack, onSignedOut }: { vaults: VaultView[]; onBack: () => void; onSignedOut: () => void }) {117  const theme = useTheme(), prefs = usePrefs();118  const [kit, setKit] = useState<string | null>(null);119  const [fp, setFp] = useState("");120  const rot = useAction(), pk = useAction(), sess = useAction();121  const info = engine.accountInfo;122  useEffect(() => { if (info) accountFingerprint(unb64u(info.sigPub), unb64u(info.encPub)).then(setFp, () => {}); }, [info?.sigPub, info?.encPub]);123124  const rotate = async () => {125    if (!(await confirmAction({ title: "Issue a new recovery key?", confirmLabel: "Issue new key", body: ["A new recovery key is generated in this browser and shown once. The current one stops working immediately, including on printed kits.", "Your passkey is requested if it was not used in the last few minutes."] }))) return;126    await rot.run(async () => { await engine.refreshAccount(); setKit(await engine.rotateRecoveryKey()); });127  };128  const addPasskey = () => pk.run(async () => { await engine.addPasskey(`Added ${stamp()}`); toast("Passkey added", "ok"); });129  const signOut = async () => {130    if (engine.syncHealth().pending > 0 && !(await confirmAction({ title: "Sign out with unsynced changes?", confirmLabel: "Sign out", body: "Some changes have not reached the server yet. They stay encrypted in this browser and are sent the next time you unlock." }))) return;131    await sess.run(async () => { await engine.signOut(); onSignedOut(); });132  };133  const forget = async () => {134    const pending = engine.syncHealth().pending;135    if (!(await confirmAction({ title: "Remove this browser?", danger: true, confirmLabel: "Remove this browser", body: ["The device key and the encrypted local copy are erased from this browser, and you are signed out. Your account and other devices are not affected.",136      pending ? `${pending} change${pending === 1 ? "" : "s"} not yet synced will be LOST.` : "To come back you will need to pair this browser again or use your recovery key.", "This browser stays listed under Devices until you revoke it from another device."] }))) return;137    await sess.run(async () => { await engine.signOut(); await engine.forget(); onSignedOut(); });138  };139140  return (141    <div className="page" data-testid="settings-page">142      <PageHead title="Settings" sub={info ? `Signed in as ${info.handle}` : undefined} onBack={onBack} />143144      <Section title="Appearance">145        <div className="setting-row"><div><strong>Theme</strong><p className="muted">Stored in this browser only.</p></div>146          <Segmented label="Theme" value={theme} onChange={(t: Theme) => applyTheme(t)} options={[{ value: "system", label: "System" }, { value: "light", label: "Light" }, { value: "dark", label: "Dark" }]} /></div>147      </Section>148149      <Section title="Locking and clipboard">150        <div className="setting-row"><div><strong>Auto-lock after inactivity</strong><p className="muted">Keys are wiped from memory; unlocking needs your passkey.</p></div>151          <select className="input auto" value={prefs.autoLockMin} onChange={(e) => setPrefs({ autoLockMin: Number(e.target.value) })} aria-label="Auto-lock delay" data-testid="pref-autolock">{[1, 2, 5, 10, 15, 30, 60].map((m) => <option key={m} value={m}>{m} minute{m === 1 ? "" : "s"}</option>)}</select></div>152        <div className="setting-row"><div><strong>Clear copied secrets</strong><p className="muted">Best effort: the clipboard is overwritten while this tab has focus. Clipboard managers and synced clipboards may already hold a copy.</p></div>153          <select className="input auto" value={prefs.clipClearSec} onChange={(e) => setPrefs({ clipClearSec: Number(e.target.value) })} aria-label="Clipboard clear delay" data-testid="pref-clip">{[10, 20, 30, 60, 120].map((s) => <option key={s} value={s}>{s} seconds</option>)}<option value={0}>Never</option></select></div>154      </Section>155156      <Section title="Import"><ImportBox vaults={vaults} /></Section>157      <Section title="Backup"><BackupBox /></Section>158159      <Section title="Account access">160        <div className="setting-row"><div><strong>Recovery key</strong><p className="muted">The only way back in when no trusted device is left. Issue a new one after using it, or if the printed kit may have been seen.</p></div>161          <Btn icon="key" onClick={rotate} busy={rot.busy} data-testid="rotate-recovery">New recovery key…</Btn></div>162        <ErrorText text={rot.error} />163        <div className="setting-row"><div><strong>Passkeys</strong><p className="muted">Add a passkey for this browser or another authenticator. Passkeys sign you in; they do not hold the vault key.</p></div>164          <Btn icon="passkey" onClick={addPasskey} busy={pk.busy} data-testid="add-passkey">Add passkey</Btn></div>165        <ErrorText text={pk.error} />166        {fp && <div className="setting-row"><div><strong>Your account fingerprint</strong><p className="muted">Read it to someone who is about to share with you, over another channel, so they can check the keys the server gave them.</p></div><Fingerprint value={fp} /></div>}167      </Section>168169      <Section title="This browser">170        <div className="setting-row"><div><strong>Sign out</strong><p className="muted">Ends the session and locks. The encrypted local copy stays for the next unlock.</p></div><Btn onClick={signOut} busy={sess.busy} data-testid="signout">Sign out</Btn></div>171        <div className="setting-row"><div><strong>Remove this browser</strong><p className="muted">Erases the device key and local data from this browser.</p></div><Btn variant="danger" onClick={forget} disabled={sess.busy} data-testid="forget">Remove…</Btn></div>172        <ErrorText text={sess.error} />173      </Section>174175      <Section title="Danger zone" danger><PlaintextExport /></Section>176177      <Section title="About security">178        <div className="prose" data-testid="about-security">179          <h3>What protects you</h3>180          <p>Items, vault names, file names and attachments are encrypted in this browser with keys the server never receives. Each device has its own key pair, certified by your account key; the server cannot enrol a device or read a vault on its own.</p>181          <h3>The limit of a web client</h3>182          <p><strong>This web app is delivered by the server each time you open it.</strong> A compromised or malicious server could serve altered JavaScript that captures your keys once you unlock. A strict content-security policy and Trusted Types reduce injection risks but cannot remove this one. The native apps are the high-assurance clients; use them for your most sensitive vaults. Browser extensions with access to this page can also read what it displays.</p>183          <h3>What the server sees</h3>184          <p>Your account handle; passkey and device public keys and platform labels; the number of vaults and who is a member of which; for each record an opaque identifier, its vault, a type tag, a revision count, the ciphertext length (rounded to 256 bytes), timestamps and which device wrote it; attachment sizes; IP addresses and timing.</p>185          <p>It never receives titles, addresses, usernames, passwords, notes, tags, one-time-code seeds, file names, vault names, device names or search terms. Search runs entirely in this browser.</p>186          <h3>What it cannot prevent</h3>187          <p>A server can refuse service, delete data or withhold recent changes from a device that has not seen them. Rollbacks of data a device already saw are detected and reported in the sync panel. Revoking a device or removing a vault member cannot erase what they already downloaded.</p>188          <h3>Managed secrets are different</h3>189          <p>Secrets placed under Connect &amp; Agents are <strong>not</strong> end-to-end encrypted: the server decrypts them to act on your behalf.</p>190          <h3>Audit status</h3>191          <p><strong>The SPV1 protocol and this implementation have not yet been independently audited.</strong> The specification (SPV1) and the threat model are published with the source so that they can be reviewed.</p>192        </div>193      </Section>194195      {kit && <KitOverlay recoveryKey={kit} reason="rotated" onDone={() => { setKit(null); toast("New recovery key active. Destroy any copy of the old one.", "ok"); }} />}196    </div>197  );198}199
Files main
Menu

Theme