Import.tsx

34.0 KB · raw

1// Signal-conditioned views in this file must use <Show>, never a2// signal-conditioned early return — see Projects.md §4.1.3import { createMemo, createSignal, Show } from "solid-js";45import { sendMessage } from "../App";6import { PeachWordmark } from "../components/PeachMark";7import {8  parseImportSource,9  type ImportParseResult,10} from "../../shared/import";11import {12  decodePeachScript,13  isPeachScript,14  normalisePeachScript,15} from "../../crypto/peachScript";16import { parsePayload } from "../../crypto/peachPayload";17import type { VaultEntry } from "../../shared/types";1819type ImportSubview = "menu" | "peachscript" | "file";20type ImportMergeMode = "add" | "replace";2122interface ImportProps {23  mode?: "existing" | "onboarding";24  replacesExistingVault?: boolean;25  /** Skip the menu and open straight into a specific subview. */26  initialView?: ImportSubview;27  onBack: () => void;28  onImport: () => void | Promise<void>;29}3031function OnboardingMasterPasswordFields(props: {32  idPrefix: string;33  copy: string;34  masterPlaceholder: string;35  password: string;36  confirm: string;37  onPasswordInput: (value: string) => void;38  onConfirmInput: (value: string) => void;39}) {40  const [showPassword, setShowPassword] = createSignal(false);4142  return (43    <>44      <div class="peach-newvault-label-row">45        <label class="peach-label" for={`${props.idPrefix}-master-password`}>46          new master password47        </label>48        <button49          class="peach-lock-reveal-btn"50          type="button"51          onClick={() => setShowPassword((value) => !value)}52          aria-label={showPassword() ? "Hide passwords" : "Show passwords"}53        >54          <Show55            when={showPassword()}56            fallback={57              <svg width="15" height="10" viewBox="0 0 14 10" fill="none" stroke="currentColor" stroke-width="0.9" stroke-linecap="round">58                <path d="M1 5C1 5 2.8 1 7 1C11.2 1 13 5 13 5C13 5 11.2 9 7 9C2.8 9 1 5 1 5Z" />59                <circle cx="7" cy="5" r="1.75" />60              </svg>61            }62          >63            <svg width="15" height="10" viewBox="0 0 14 10" fill="none" stroke="currentColor" stroke-width="0.9" stroke-linecap="round">64              <path d="M1 2C3 4.5 5 6 7 6C9 6 11 4.5 13 2" />65              <path d="M3.5 5.5L2.5 7.5" />66              <path d="M7 6.5V8.5" />67              <path d="M10.5 5.5L11.5 7.5" />68            </svg>69          </Show>70          {showPassword() ? "hide" : "show"}71        </button>72      </div>73      <p class="peach-export-card-copy">{props.copy}</p>74      <div class="peach-settings-stack peach-export-password-stack">75        <input76          id={`${props.idPrefix}-master-password`}77          class="peach-settings-input"78          type={showPassword() ? "text" : "password"}79          placeholder={props.masterPlaceholder}80          value={props.password}81          onInput={(event) => props.onPasswordInput((event.target as HTMLInputElement).value)}82        />83        <input84          id={`${props.idPrefix}-confirm-password`}85          class="peach-settings-input"86          type={showPassword() ? "text" : "password"}87          placeholder="confirm master password"88          value={props.confirm}89          onInput={(event) => props.onConfirmInput((event.target as HTMLInputElement).value)}90        />91        <Show when={props.confirm.length > 0 && props.password !== props.confirm}>92          <p class="peach-export-note" style="color:var(--peach-t2)">93            Passwords don't match94          </p>95        </Show>96      </div>97    </>98  );99}100101export function ImportView(props: ImportProps) {102  const [view, setView] = createSignal<ImportSubview>(props.initialView ?? "menu");103  // When FileImport detects a .peach file, it stashes the contents here and104  // routes the view to "peachscript" so the existing decode flow handles it.105  const [peachScriptPrefill, setPeachScriptPrefill] = createSignal<string>("");106  const mode = () => props.mode ?? "existing";107  const isOnboarding = () => mode() === "onboarding";108  // When the caller deep-links into a subview, the back arrow exits the109  // ImportView entirely. Otherwise it returns to the import menu.110  const subviewBack = () => (props.initialView ? props.onBack() : setView("menu"));111112  return (113    <div class={isOnboarding() ? "peach-lock-view" : "peach-overlay-view ov-enter-right"} style="display:flex">114      <Show when={view() === "menu"}>115        <ImportMenu116          mode={mode()}117          replacesExistingVault={props.replacesExistingVault}118          onBack={props.onBack}119          onPick={(v) => setView(v)}120        />121      </Show>122      <Show when={view() === "peachscript"}>123        <PeachScriptImport124          mode={mode()}125          replacesExistingVault={props.replacesExistingVault}126          initialScript={peachScriptPrefill()}127          onBack={() => {128            setPeachScriptPrefill("");129            subviewBack();130          }}131          onImport={props.onImport}132        />133      </Show>134      <Show when={view() === "file"}>135        <FileImport136          mode={mode()}137          replacesExistingVault={props.replacesExistingVault}138          onBack={subviewBack}139          onImport={props.onImport}140          onLoadPeachFile={(content) => {141            setPeachScriptPrefill(content);142            setView("peachscript");143          }}144        />145      </Show>146    </div>147  );148}149150// ---------------------------------------------------------------------------151// Menu152// ---------------------------------------------------------------------------153154function ImportMenu(props: {155  mode: "existing" | "onboarding";156  replacesExistingVault?: boolean;157  onBack: () => void;158  onPick: (view: ImportSubview) => void;159}) {160  const isOnboarding = props.mode === "onboarding";161  return (162    <>163      <Show164        when={isOnboarding}165        fallback={<OverlayHeader title="import" onBack={props.onBack} />}166      >167        <div class="peach-lock-view-header">168          <PeachWordmark class="peach-wordmark-wrap" />169          <button class="peach-lock-restore-link" onClick={props.onBack}>170            ‹ back171          </button>172        </div>173      </Show>174      <div class="peach-settings-body peach-export-menu">175        <Show when={isOnboarding && props.replacesExistingVault}>176          <div class="peach-settings-group">177            <div class="peach-restore-warning">178              Restoring now replaces the locked local vault on this device with179              a fresh one from your backup or export file.180            </div>181          </div>182        </Show>183184        <div class="peach-settings-group peach-export-card peach-export-card--primary">185          <p class="peach-settings-label">peachscript</p>186          <p class="peach-export-card-copy">187            Paste a PeachScript backup from another Peach device.188            {props.mode === "existing" ? " We'll merge it into your vault." : ""}189          </p>190          <button191            class="peach-btn peach-btn--subtle peach-btn--sm"192            onClick={() => props.onPick("peachscript")}193          >194            Paste PeachScript →195          </button>196        </div>197198        <div class="peach-settings-group peach-export-card">199          <p class="peach-settings-label">backup file</p>200          <p class="peach-export-card-copy">201            A Peach JSON export, or a file from Bitwarden, Proton Pass,202            1Password, or a browser CSV (Chrome, Safari, Edge).203          </p>204          <button205            class="peach-btn peach-btn--subtle peach-btn--sm"206            onClick={() => props.onPick("file")}207          >208            Choose file →209          </button>210        </div>211      </div>212    </>213  );214}215216// ---------------------------------------------------------------------------217// PeachScript paste flow218// ---------------------------------------------------------------------------219220function PeachScriptImport(props: {221  mode: "existing" | "onboarding";222  replacesExistingVault?: boolean;223  /** Optional initial PeachScript content — set when the user loaded a224   *  .peach file from the CSV/file card and was routed here. */225  initialScript?: string;226  onBack: () => void;227  onImport: () => void | Promise<void>;228}) {229  const [scriptInput, setScriptInput] = createSignal(props.initialScript ?? "");230  const [scriptPass, setScriptPass] = createSignal("");231  const [masterPassword, setMasterPassword] = createSignal("");232  const [masterConfirm, setMasterConfirm] = createSignal("");233  const [working, setWorking] = createSignal(false);234  const [error, setError] = createSignal<string | null>(null);235  const [result, setResult] = createSignal<{ entryCount: number } | null>(null);236237  const scriptLooksValid = createMemo(() => isPeachScript(scriptInput()));238  const isOnboarding = props.mode === "onboarding";239  const masterPasswordReady = createMemo(240    () => masterPassword().length >= 8 && masterPassword() === masterConfirm()241  );242243  async function handleImport() {244    setError(null);245    setResult(null);246    if (!scriptLooksValid()) {247      setError("Paste your PeachScript first.");248      return;249    }250    if (!scriptPass().trim()) {251      setError("Enter the backup password.");252      return;253    }254    setWorking(true);255    try {256      const bytes = decodePeachScript(normalisePeachScript(scriptInput()));257      const payload = await parsePayload(bytes, scriptPass());258259      if (isOnboarding) {260        if (!masterPasswordReady()) {261          throw new Error("MASTER_PASSWORD_REQUIRED");262        }263        const createRes = await sendMessage({264          type: "CREATE_VAULT",265          payload: { password: masterPassword() },266        });267        if (!(createRes as { ok: boolean }).ok) throw new Error("CREATE_VAULT_FAILED");268      }269270      const restoreRes = await sendMessage({271        type: "RESTORE_ENTRIES",272        payload: {273          entries: payload.entries,274          mode: "merge",275          settings: payload.settings,276        },277      });278      const restoreEnvelope = restoreRes as { ok: boolean; error?: string };279      if (!restoreEnvelope.ok) {280        throw new Error(restoreEnvelope.error ?? "RESTORE_FAILED");281      }282283      if (payload.license?.key) {284        await sendMessage({285          type: "ACTIVATE_LICENSE",286          payload: { key: payload.license.key },287        }).catch(() => {});288      }289290      setResult({ entryCount: payload.entries.length });291      await props.onImport();292    } catch (err) {293      const code = err instanceof Error ? err.message : String(err);294      setError(getImportErrorCopy(code));295    } finally {296      setWorking(false);297    }298  }299300  return (301    <>302      <SubviewHeader title="peachscript" onBack={props.onBack} mode={props.mode} />303      <div class="peach-settings-body">304        <Show when={isOnboarding && props.replacesExistingVault}>305          <div class="peach-settings-group">306            <div class="peach-restore-warning">307              Restoring now replaces the locked local vault on this device with308              a fresh one from your backup.309            </div>310          </div>311        </Show>312        <div class="peach-settings-group peach-export-card peach-export-card--primary peach-export-pass-group">313          <p class="peach-settings-label">paste peachscript</p>314          <p class="peach-export-card-copy">315            {isOnboarding316              ? "Paste a PeachScript backup from another Peach device to restore your vault — or load a .peach file from disk."317              : "We'll merge the entries into your existing vault. You can paste PeachScript or load a .peach file."}318          </p>319          <textarea320            class="peach-script-input"321            placeholder="paste peachscript…"322            value={scriptInput()}323            onInput={(e) => setScriptInput((e.target as HTMLTextAreaElement).value)}324          />325          <label326            class="peach-btn peach-btn--ghost peach-btn--sm"327            style="display:inline-flex;align-items:center;justify-content:center;cursor:pointer;"328          >329            Load .peach file330            <input331              type="file"332              accept=".peach,application/x-peach,text/plain"333              style="display:none;"334              onChange={async (event) => {335                const input = event.currentTarget;336                const file = input.files?.[0];337                if (!file) return;338                try {339                  const text = await file.text();340                  setScriptInput(text);341                } catch (err) {342                  setError(err instanceof Error ? err.message : "Couldn't read file.");343                } finally {344                  input.value = "";345                }346              }}347            />348          </label>349          <div class="peach-settings-stack peach-export-password-stack">350            <input351              class="peach-settings-input"352              type="password"353              placeholder="PeachScript password"354              value={scriptPass()}355              onInput={(e) => setScriptPass((e.target as HTMLInputElement).value)}356            />357          </div>358          <Show when={isOnboarding}>359            <OnboardingMasterPasswordFields360              idPrefix="peachscript"361              copy="Use at least 8 characters. This password unlocks Peach on this device after the restore, and both fields must match before Peach can create it."362              masterPlaceholder="new master password"363              password={masterPassword()}364              confirm={masterConfirm()}365              onPasswordInput={setMasterPassword}366              onConfirmInput={setMasterConfirm}367            />368          </Show>369          <button370            class="peach-btn peach-btn--subtle peach-btn--sm"371            onClick={() => void handleImport()}372            disabled={373              working() ||374              !scriptLooksValid() ||375              !scriptPass().trim() ||376              (isOnboarding && !masterPasswordReady())377            }378          >379            {working() ? "decoding…" : "Restore from PeachScript"}380          </button>381          <Show when={error()}>382            <div class="peach-restore-error">{error()}</div>383          </Show>384          <Show when={result()}>385            <div class="peach-export-success">386              <span class="peach-export-success-check">✓</span>387              <span>388                Restored {result()!.entryCount} entr389                {result()!.entryCount === 1 ? "y" : "ies"}.390              </span>391            </div>392          </Show>393        </div>394      </div>395    </>396  );397}398399// ---------------------------------------------------------------------------400// File flow (Bitwarden / 1Password / Peach JSON / etc.)401// ---------------------------------------------------------------------------402403function FileImport(props: {404  mode: "existing" | "onboarding";405  replacesExistingVault?: boolean;406  onBack: () => void;407  onImport: () => void | Promise<void>;408  /** Called when the user picks a .peach file from this picker — the parent409   *  routes them to the PeachScript subview with the contents prefilled. */410  onLoadPeachFile?: (content: string) => void;411}) {412  const isOnboarding = props.mode === "onboarding";413  const needsMasterPassword = () => isOnboarding;414415  const [preview, setPreview] = createSignal<ImportParseResult | null>(null);416  const [rawImport, setRawImport] = createSignal<string | null>(null);417  const [backupPassword, setBackupPassword] = createSignal("");418  const [masterPassword, setMasterPassword] = createSignal("");419  const [masterConfirm, setMasterConfirm] = createSignal("");420  const [importing, setImporting] = createSignal(false);421  const [error, setError] = createSignal<string | null>(null);422  const [mergeMode, setMergeMode] = createSignal<ImportMergeMode>("add");423  const [awaitingReplaceConfirm, setAwaitingReplaceConfirm] = createSignal(false);424  const [importProgress, setImportProgress] = createSignal<{ current: number; total: number } | null>(null);425  const [duplicateWarning, setDuplicateWarning] = createSignal<number>(0);426  const [existingCount, setExistingCount] = createSignal<number>(0);427428  const needsBackupPassword = createMemo(() => preview()?.requiresPassword ?? false);429  const masterPasswordReady = createMemo(430    () => masterPassword().length >= 8 && masterPassword() === masterConfirm()431  );432433  async function refreshExistingCount() {434    if (isOnboarding) return;435    const res = await sendMessage({ type: "GET_ENTRIES" });436    const list = (res as { ok: boolean; data?: VaultEntry[] }).data ?? [];437    setExistingCount(list.length);438  }439  void refreshExistingCount();440441  async function parseSource(text: string, password?: string) {442    try {443      const result = await parseImportSource(text, password);444      setPreview(result);445      setError(null);446      if (result.format === "unknown") {447        setError(448          "We couldn't recognise this file format. Peach supports: Peach JSON backups, Bitwarden JSON/CSV, Proton Pass JSON/CSV, 1Password JSON, and generic browser CSV exports."449        );450      }451      return result;452    } catch (err) {453      const message = err instanceof Error ? err.message : String(err);454      setPreview(null);455      setError(getImportErrorCopy(message));456      return null;457    }458  }459460  async function handleFileSelect(event: Event) {461    const input = event.target as HTMLInputElement;462    const file = input.files?.[0];463    if (!file) return;464465    setPreview(null);466    setRawImport(null);467    setBackupPassword("");468    setError(null);469    setAwaitingReplaceConfirm(false);470471    const text = await file.text();472473    // Route .peach files to the PeachScript subview. Detection is two-pronged:474    // either the filename ends in .peach, or the body is entirely PUA chars475    // (the canonical PeachScript shape). The two-pronged check protects476    // against renamed-extension imports and against text editors that477    // accidentally save with a different extension.478    const looksLikePeach =479      file.name.toLowerCase().endsWith(".peach") || isPeachScript(text);480    if (looksLikePeach) {481      if (props.onLoadPeachFile) {482        props.onLoadPeachFile(text);483        input.value = "";484        return;485      }486      setError("This is a .peach file. Open the PeachScript card to import it.");487      return;488    }489490    setRawImport(text);491    await parseSource(text);492  }493494  async function handleUnlockBackup() {495    const raw = rawImport();496    if (!raw || !backupPassword().trim()) return;497    await parseSource(raw, backupPassword());498  }499500  async function countDuplicates(incoming: ImportParseResult["entries"]): Promise<number> {501    if (incoming.length === 0) return 0;502    const res = await sendMessage({ type: "GET_ENTRIES" });503    const existing = ((res as { ok: boolean; data?: VaultEntry[] }).data ?? []).filter((e) => !e.deletedAt);504    const keyOf = (title?: string, url?: string, username?: string) =>505      `${(title ?? "").toLowerCase()}|${(url ?? "").toLowerCase()}|${(username ?? "").toLowerCase()}`;506    const existingKeys = new Set(existing.map((e) => keyOf(e.title, e.url, e.username)));507    let dupes = 0;508    for (const entry of incoming) {509      const u = "username" in entry ? entry.username : undefined;510      const url = "url" in entry ? entry.url : undefined;511      if (existingKeys.has(keyOf(entry.title, url, u))) dupes += 1;512    }513    return dupes;514  }515516  async function handleImport() {517    const currentPreview = preview();518    if (!currentPreview) return;519520    if (needsBackupPassword() && !backupPassword().trim()) {521      setError("Enter the backup password used for this export.");522      return;523    }524525    if (needsMasterPassword()) {526      if (masterPassword().length < 8) {527        setError("Master password must be at least 8 characters.");528        return;529      }530      if (!masterPasswordReady()) {531        setError("Master passwords do not match.");532        return;533      }534    }535536    if (!isOnboarding && mergeMode() === "replace" && !awaitingReplaceConfirm()) {537      setAwaitingReplaceConfirm(true);538      return;539    }540541    setImporting(true);542    setError(null);543    setDuplicateWarning(0);544    setImportProgress(null);545546    try {547      if (currentPreview.entries.length === 0) {548        throw new Error("NO_ENTRIES_IMPORTED");549      }550551      if (needsMasterPassword()) {552        const createResponse = await sendMessage({553          type: "CREATE_VAULT",554          payload: { password: masterPassword() },555        });556        if (!(createResponse as { ok: boolean }).ok) {557          throw new Error("CREATE_VAULT_FAILED");558        }559      }560561      if (!isOnboarding && mergeMode() === "replace") {562        const clearRes = await sendMessage({ type: "CLEAR_VAULT_ENTRIES" });563        if (!(clearRes as { ok: boolean }).ok) {564          throw new Error("CLEAR_VAULT_FAILED");565        }566      }567568      let dupes = 0;569      if (!isOnboarding && mergeMode() === "add") {570        dupes = await countDuplicates(currentPreview.entries);571      }572573      let imported = 0;574      setImportProgress({ current: 0, total: currentPreview.entries.length });575576      const batchRes = await sendMessage({577        type: "BATCH_ADD_ENTRIES",578        payload: { entries: currentPreview.entries },579      });580581      if ((batchRes as { ok: boolean }).ok) {582        imported = ((batchRes as { ok: boolean; data?: VaultEntry[] }).data ?? []).length;583        setImportProgress({ current: imported, total: currentPreview.entries.length });584      } else {585        for (const entry of currentPreview.entries) {586          const response = await sendMessage({587            type: "ADD_ENTRY",588            payload: entry,589          });590          if ((response as { ok: boolean }).ok) imported += 1;591          setImportProgress({ current: imported, total: currentPreview.entries.length });592        }593      }594595      if (imported === 0) {596        throw new Error("NO_ENTRIES_IMPORTED");597      }598599      if (currentPreview.licenseKey) {600        await sendMessage({ type: "ACTIVATE_LICENSE", payload: { key: currentPreview.licenseKey } }).catch(() => {});601      }602603      setDuplicateWarning(dupes);604      await props.onImport();605    } catch (err) {606      const message = err instanceof Error ? err.message : String(err);607      setError(getImportErrorCopy(message));608      setImporting(false);609      setImportProgress(null);610      return;611    }612613    setImporting(false);614    setImportProgress(null);615  }616617  return (618    <>619      <SubviewHeader title="backup file" onBack={props.onBack} mode={props.mode} />620      <div class="peach-settings-body">621        <Show when={isOnboarding && props.replacesExistingVault}>622          <div class="peach-settings-group">623            <div class="peach-restore-warning">624              Restoring now replaces the locked local vault on this device with625              a fresh one from your backup.626            </div>627          </div>628        </Show>629        <div class="peach-settings-group peach-export-card peach-export-card--primary">630          <p class="peach-settings-label">choose a file</p>631          <p class="peach-export-card-copy">632            Bitwarden, 1Password, Proton Pass, Chrome / Edge / Safari CSV, FIDO633            credential-exchange passkeys, or a Peach JSON backup.634          </p>635636          <div class="peach-provider-chips">637            <span class="peach-provider-chip">Peach JSON</span>638            <span class="peach-provider-chip">FIDO passkeys</span>639            <span class="peach-provider-chip">Proton Pass</span>640            <span class="peach-provider-chip">Bitwarden</span>641            <span class="peach-provider-chip">1Password</span>642            <span class="peach-provider-chip">Browser CSV</span>643          </div>644645          <input646            class="peach-restore-file"647            type="file"648            accept=".csv,.json,.peach,application/x-peach"649            onChange={(event) => void handleFileSelect(event)}650          />651        </div>652653        <Show when={needsBackupPassword()}>654          <div class="peach-settings-group">655            <p class="peach-settings-label">unlock backup</p>656            <p class="peach-export-card-copy">657              Enter the password used when you created this encrypted Peach JSON658              backup.659            </p>660            <input661              class="peach-restore-input"662              type="password"663              placeholder="backup password"664              value={backupPassword()}665              onInput={(event) =>666                setBackupPassword((event.target as HTMLInputElement).value)667              }668              onBlur={() => { if (backupPassword().trim()) void handleUnlockBackup(); }}669              onKeyDown={(event) => {670                if (event.key === "Enter") {671                  event.preventDefault();672                  void handleUnlockBackup();673                }674              }}675            />676            <div class="peach-settings-actions">677              <button678                class="peach-btn peach-btn--subtle peach-btn--sm"679                onClick={() => void handleUnlockBackup()}680                disabled={!backupPassword().trim()}681              >682                Decrypt →683              </button>684            </div>685          </div>686        </Show>687688        <Show when={preview() && !needsBackupPassword() && preview()!.format !== "unknown"}>689          <div class="peach-settings-group">690            <p class="peach-settings-label">{preview()!.label}</p>691            <div class="peach-import-summary">692              Found <strong>{preview()!.entries.length}</strong>{" "}693              entr{preview()!.entries.length === 1 ? "y" : "ies"}694              {preview()!.skippedItems > 0695                ? `. ${preview()!.skippedItems} skipped because no password was present.`696                : "."}697            </div>698699            <div class="peach-import-preview">700              {preview()!.entries.slice(0, 8).map((entry) => (701                <div class="peach-import-preview-row">702                  <span class="peach-import-preview-title">{entry.title}</span>703                  <span class="peach-import-preview-meta">704                    {entry.passkey705                      ? `${entry.passkey.userName} • ${entry.passkey.rpId} (passkey)`706                      : entry.type === "note"707                        ? "secure note"708                        : entry.username || entry.url || "password item"}709                  </span>710                </div>711              ))}712              <Show when={preview()!.entries.length > 8}>713                <div class="peach-import-preview-more">714                  ...and {preview()!.entries.length - 8} more715                </div>716              </Show>717            </div>718          </div>719        </Show>720721        <Show when={!isOnboarding && preview() && !needsBackupPassword() && preview()!.format !== "unknown" && preview()!.entries.length > 0}>722          <div class="peach-settings-group">723            <p class="peach-settings-label">merge or replace</p>724            <label class="peach-import-choice">725              <input726                type="radio"727                name="merge-mode"728                value="add"729                checked={mergeMode() === "add"}730                onChange={() => { setMergeMode("add"); setAwaitingReplaceConfirm(false); }}731              />732              <span class="peach-import-choice-main">733                <span class="peach-import-choice-label">Add to existing vault</span>734                <span class="peach-import-choice-sub">735                  This will add {preview()!.entries.length} entries to your existing {existingCount()}.736                </span>737              </span>738            </label>739            <label class="peach-import-choice">740              <input741                type="radio"742                name="merge-mode"743                value="replace"744                checked={mergeMode() === "replace"}745                onChange={() => setMergeMode("replace")}746              />747              <span class="peach-import-choice-main">748                <span class="peach-import-choice-label">Replace vault</span>749                <span class="peach-import-choice-sub">750                  This will replace your {existingCount()} entries with {preview()!.entries.length} imported ones.751                </span>752              </span>753            </label>754            <Show when={awaitingReplaceConfirm()}>755              <div class="peach-restore-warning" style="margin-top:6px">756                Replace forever? This cannot be undone.757              </div>758            </Show>759          </div>760        </Show>761762        <Show when={needsMasterPassword() && preview() && !needsBackupPassword() && preview()!.format !== "unknown"}>763          <div class="peach-settings-group">764            <OnboardingMasterPasswordFields765              idPrefix="backup"766              copy="Use at least 8 characters. This password unlocks the Peach vault created on this device after import, and both fields must match before Peach can create it."767              masterPlaceholder="new master password"768              password={masterPassword()}769              confirm={masterConfirm()}770              onPasswordInput={setMasterPassword}771              onConfirmInput={setMasterConfirm}772            />773          </div>774        </Show>775776        <Show when={error()}>777          <div class="peach-settings-group">778            <div class="peach-restore-error">{error()}</div>779          </div>780        </Show>781782        <Show when={importing() && importProgress()}>783          <div class="peach-settings-group">784            <div class="peach-import-summary">785              Importing... [{importProgress()!.current} / {importProgress()!.total}]786            </div>787          </div>788        </Show>789790        <Show when={duplicateWarning() > 0 && !importing()}>791          <div class="peach-settings-group">792            <div class="peach-export-card-copy">793              {duplicateWarning()} {duplicateWarning() === 1 ? "entry appears" : "entries appear"} to be duplicates of existing ones. They were still imported — you can review and delete them in your vault.794            </div>795          </div>796        </Show>797798        <Show when={preview() && !needsBackupPassword() && preview()!.format !== "unknown"}>799          <div class="peach-settings-group">800            <div class="peach-settings-actions">801              <button802                class="peach-btn peach-btn--subtle peach-btn--sm"803                onClick={() => void handleImport()}804                disabled={805                  importing() ||806                  preview()!.entries.length === 0 ||807                  (needsMasterPassword() && !masterPasswordReady())808                }809              >810                {importing()811                  ? "importing..."812                  : isOnboarding813                    ? `Create vault + import ${preview()!.entries.length}`814                    : mergeMode() === "replace"815                      ? awaitingReplaceConfirm()816                        ? "Yes, replace forever"817                        : `Replace vault with ${preview()!.entries.length}`818                      : `Import ${preview()!.entries.length}`}819              </button>820            </div>821          </div>822        </Show>823      </div>824    </>825  );826}827828// ---------------------------------------------------------------------------829// Shared headers830// ---------------------------------------------------------------------------831832function OverlayHeader(props: { title: string; onBack: () => void }) {833  return (834    <div class="peach-overlay-header">835      <button836        class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"837        onClick={props.onBack}838        aria-label="Back"839      >840        <svg width="7" height="12" viewBox="0 0 7 12" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">841          <path d="M6 1L1 6L6 11" />842        </svg>843      </button>844      <span class="peach-overlay-title">{props.title}</span>845      <div class="peach-overlay-spacer"></div>846    </div>847  );848}849850function SubviewHeader(props: {851  title: string;852  onBack: () => void;853  mode: "existing" | "onboarding";854}) {855  // Onboarding sub-flows reuse the lock-screen header; existing-vault flows856  // use the standard overlay back-arrow header.857  return (858    <Show859      when={props.mode === "onboarding"}860      fallback={<OverlayHeader title={props.title} onBack={props.onBack} />}861    >862      <div class="peach-lock-view-header">863        <PeachWordmark class="peach-wordmark-wrap" />864        <button class="peach-lock-restore-link" onClick={props.onBack}>865          ‹ back866        </button>867      </div>868    </Show>869  );870}871872function getImportErrorCopy(error: string): string {873  // UI-7 / MV-5: oversized-import errors carry a variable detail after the874  // code, so match the prefix and never surface the raw string.875  if (error.startsWith("IMPORT_TOO_LARGE")) {876    return "This file is too large to import (limit: 10 MiB for backups, 25 MiB for Codex PDFs). If this is a real Peach backup, please report it — backups never approach this size.";877  }878  switch (error) {879    case "UNSUPPORTED_IMPORT_FORMAT":880      return "Unrecognised file format. Use CSV, Bitwarden JSON, Proton Pass JSON/CSV, or a Peach encrypted backup.";881    case "INVALID_EXPORT_PASSWORD":882    case "INVALID_PASSPHRASE":883      return "Wrong backup password. This is the password you chose when you created the backup.";884    case "INVALID_PEACH_EXPORT":885      return "This Peach backup file looks corrupted or incomplete.";886    case "INVALID_PEACHSCRIPT_CHARACTER":887      return "This doesn't look like PeachScript. Make sure you copied the entire backup string.";888    case "PAYLOAD_TOO_SHORT":889      return "PeachScript looks truncated. Copy the full backup string and try again.";890    case "BAD_MAGIC":891    case "UNSUPPORTED_VERSION":892      return "This PeachScript was created by a different version of Peach.";893    case "CHECKSUM_FAILED":894      return "PeachScript appears corrupted. Re-copy from the source device.";895    case "CREATE_VAULT_FAILED":896      return "Peach couldn't create a new local vault before importing.";897    case "CLEAR_VAULT_FAILED":898      return "Peach couldn't clear the existing vault before replacing it.";899    case "MASTER_PASSWORD_REQUIRED":900      return "Choose a master password for your new vault first.";901    case "RESTORE_FAILED":902      return "Restore failed. Your existing vault is unchanged.";903    case "vault_locked":904      return "Peach is locked. Open Peach with your master password and try again.";905    case "refuse to replace with empty entry set":906      return "This PeachScript decoded to zero entries — refusing to wipe the vault.";907    case "NO_ENTRIES_IMPORTED":908      return "No importable password entries were found in that file.";909    default:910      return error;911  }912}