Import.tsx

32.8 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} from "../../crypto/peachScript";15import { parsePayload } from "../../crypto/peachPayload";16import { IMPORT_LIMITS } from "../../shared/import-limits";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 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      // PB-26-208: decodePeachScript skips whitespace internally — no257      // separate normalise pass.258      const bytes = decodePeachScript(scriptInput());259      const payload = await parsePayload(bytes, scriptPass());260261      if (isOnboarding) {262        if (!masterPasswordReady()) {263          throw new Error("MASTER_PASSWORD_REQUIRED");264        }265        const createRes = await sendMessage({266          type: "CREATE_VAULT",267          payload: { password: masterPassword(), ...(isOnboarding && props.replacesExistingVault === true ? { replacement: "warned-import" } : {}) },268        });269        if (!(createRes as { ok: boolean }).ok) throw new Error("CREATE_VAULT_FAILED");270        if ((createRes.data as { unlocked?: boolean } | undefined)?.unlocked === false) throw new Error("VAULT_CREATED_LOCKED");271      }272273      const restoreRes = await sendMessage({274        type: "RESTORE_ENTRIES",275        payload: {276          entries: payload.entries,277          mode: "merge",278          settings: payload.settings,279        },280      });281      const restoreEnvelope = restoreRes as { ok: boolean; error?: string };282      if (!restoreEnvelope.ok) {283        throw new Error(restoreEnvelope.error ?? "RESTORE_FAILED");284      }285286      if (payload.license?.key) {287        await sendMessage({288          type: "ACTIVATE_LICENSE",289          payload: { key: payload.license.key },290        }).catch(() => {});291      }292293      setResult({ entryCount: payload.entries.length });294      await props.onImport();295    } catch (err) {296      const code = err instanceof Error ? err.message : String(err);297      setError(getImportErrorCopy(code));298    } finally {299      setWorking(false);300    }301  }302303  return (304    <>305      <SubviewHeader title="peachscript" onBack={props.onBack} mode={props.mode} />306      <div class="peach-settings-body">307        <Show when={isOnboarding && props.replacesExistingVault}>308          <div class="peach-settings-group">309            <div class="peach-restore-warning">310              Restoring now replaces the locked local vault on this device with311              a fresh one from your backup.312            </div>313          </div>314        </Show>315        <div class="peach-settings-group peach-export-card peach-export-card--primary peach-export-pass-group">316          <p class="peach-settings-label">paste peachscript</p>317          <p class="peach-export-card-copy">318            {isOnboarding319              ? "Paste a PeachScript backup from another Peach device to restore your vault — or load a .peach file from disk."320              : "We'll merge the entries into your existing vault. You can paste PeachScript or load a .peach file."}321          </p>322          <textarea323            class="peach-script-input"324            placeholder="paste peachscript…"325            value={scriptInput()}326            onInput={(e) => setScriptInput((e.target as HTMLTextAreaElement).value)}327          />328          <label329            class="peach-btn peach-btn--ghost peach-btn--sm"330            style="display:inline-flex;align-items:center;justify-content:center;cursor:pointer;"331          >332            Load .peach file333            <input334              type="file"335              accept=".peach,application/x-peach,text/plain"336              style="display:none;"337              onChange={async (event) => {338                const input = event.currentTarget;339                const file = input.files?.[0];340                if (!file) return;341                try {342                  // PB-26-010: bound before reading the file into a string.343                  if (file.size > IMPORT_LIMITS.MAX_JSON_BYTES) {344                    setError("That file is too large.");345                    return;346                  }347                  const text = await file.text();348                  setScriptInput(text);349                } catch (err) {350                  setError(err instanceof Error ? err.message : "Couldn't read file.");351                } finally {352                  input.value = "";353                }354              }}355            />356          </label>357          <div class="peach-settings-stack peach-export-password-stack">358            <input359              class="peach-settings-input"360              type="password"361              placeholder="PeachScript password"362              value={scriptPass()}363              onInput={(e) => setScriptPass((e.target as HTMLInputElement).value)}364            />365          </div>366          <Show when={isOnboarding}>367            <OnboardingMasterPasswordFields368              idPrefix="peachscript"369              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."370              masterPlaceholder="new master password"371              password={masterPassword()}372              confirm={masterConfirm()}373              onPasswordInput={setMasterPassword}374              onConfirmInput={setMasterConfirm}375            />376          </Show>377          <button378            class="peach-btn peach-btn--subtle peach-btn--sm"379            onClick={() => void handleImport()}380            disabled={381              working() ||382              !scriptLooksValid() ||383              !scriptPass().trim() ||384              (isOnboarding && !masterPasswordReady())385            }386          >387            {working() ? "decoding…" : "Restore from PeachScript"}388          </button>389          <Show when={error()}>390            <div class="peach-restore-error">{error()}</div>391          </Show>392          <Show when={result()}>393            <div class="peach-export-success">394              <span class="peach-export-success-check">✓</span>395              <span>396                Restored {result()!.entryCount} entr397                {result()!.entryCount === 1 ? "y" : "ies"}.398              </span>399            </div>400          </Show>401        </div>402      </div>403    </>404  );405}406407// ---------------------------------------------------------------------------408// File flow (Bitwarden / 1Password / etc.)409// ---------------------------------------------------------------------------410411function FileImport(props: {412  mode: "existing" | "onboarding";413  replacesExistingVault?: boolean;414  onBack: () => void;415  onImport: () => void | Promise<void>;416  /** Called when the user picks a .peach file from this picker — the parent417   *  routes them to the PeachScript subview with the contents prefilled. */418  onLoadPeachFile?: (content: string) => void;419}) {420  const isOnboarding = props.mode === "onboarding";421  const needsMasterPassword = () => isOnboarding;422423  const [preview, setPreview] = createSignal<ImportParseResult | null>(null);424  const [masterPassword, setMasterPassword] = createSignal("");425  const [masterConfirm, setMasterConfirm] = createSignal("");426  const [importing, setImporting] = createSignal(false);427  const [error, setError] = createSignal<string | null>(null);428  const [mergeMode, setMergeMode] = createSignal<ImportMergeMode>("add");429  const [awaitingReplaceConfirm, setAwaitingReplaceConfirm] = createSignal(false);430  const [importProgress, setImportProgress] = createSignal<{ current: number; total: number } | null>(null);431  const [duplicateWarning, setDuplicateWarning] = createSignal<number>(0);432  const [existingCount, setExistingCount] = createSignal<number>(0);433434  const masterPasswordReady = createMemo(435    () => masterPassword().length >= 8 && masterPassword() === masterConfirm()436  );437438  async function refreshExistingCount() {439    if (isOnboarding) return;440    const res = await sendMessage({ type: "GET_ENTRIES" });441    const list = (res as { ok: boolean; data?: VaultEntry[] }).data ?? [];442    setExistingCount(list.length);443  }444  void refreshExistingCount();445446  async function parseSource(text: string) {447    try {448      const result = await parseImportSource(text);449      setPreview(result);450      setError(null);451      if (result.format === "unknown") {452        setError(453          "We couldn't recognise this file format. Peach supports: Bitwarden JSON/CSV, Proton Pass JSON/CSV, 1Password JSON, and generic browser CSV exports."454        );455      }456      return result;457    } catch (err) {458      const message = err instanceof Error ? err.message : String(err);459      setPreview(null);460      setError(getImportErrorCopy(message));461      return null;462    }463  }464465  async function handleFileSelect(event: Event) {466    const input = event.target as HTMLInputElement;467    const file = input.files?.[0];468    if (!file) return;469470    setPreview(null);471    setError(null);472    setAwaitingReplaceConfirm(false);473474    if (file.size > IMPORT_LIMITS.MAX_JSON_BYTES) {475      setError("That file is too large.");476      input.value = "";477      return;478    }479    const text = await file.text();480481    // Route .peach files to the PeachScript subview. Detection is two-pronged:482    // either the filename ends in .peach, or the body is entirely PUA chars483    // (the canonical PeachScript shape). The two-pronged check protects484    // against renamed-extension imports and against text editors that485    // accidentally save with a different extension.486    const looksLikePeach =487      file.name.toLowerCase().endsWith(".peach") || isPeachScript(text);488    if (looksLikePeach) {489      if (props.onLoadPeachFile) {490        props.onLoadPeachFile(text);491        input.value = "";492        return;493      }494      setError("This is a .peach file. Open the PeachScript card to import it.");495      return;496    }497498    await parseSource(text);499  }500501  async function countDuplicates(incoming: ImportParseResult["entries"]): Promise<number> {502    if (incoming.length === 0) return 0;503    const res = await sendMessage({ type: "GET_ENTRIES" });504    const existing = ((res as { ok: boolean; data?: VaultEntry[] }).data ?? []).filter((e) => !e.deletedAt);505    const keyOf = (title?: string, url?: string, username?: string) =>506      `${(title ?? "").toLowerCase()}|${(url ?? "").toLowerCase()}|${(username ?? "").toLowerCase()}`;507    const existingKeys = new Set(existing.map((e) => keyOf(e.title, e.url, e.username)));508    let dupes = 0;509    for (const entry of incoming) {510      const u = "username" in entry ? entry.username : undefined;511      const url = "url" in entry ? entry.url : undefined;512      if (existingKeys.has(keyOf(entry.title, url, u))) dupes += 1;513    }514    return dupes;515  }516517  async function handleImport() {518    const currentPreview = preview();519    if (!currentPreview) return;520521    if (needsMasterPassword()) {522      if (masterPassword().length < 8) {523        setError("Master password must be at least 8 characters.");524        return;525      }526      if (!masterPasswordReady()) {527        setError("Master passwords do not match.");528        return;529      }530    }531532    if (!isOnboarding && mergeMode() === "replace" && !awaitingReplaceConfirm()) {533      setAwaitingReplaceConfirm(true);534      return;535    }536537    setImporting(true);538    setError(null);539    setDuplicateWarning(0);540    setImportProgress(null);541542    try {543      if (currentPreview.entries.length === 0) {544        throw new Error("NO_ENTRIES_IMPORTED");545      }546547      if (needsMasterPassword()) {548        const createResponse = await sendMessage({549          type: "CREATE_VAULT",550          payload: { password: masterPassword(), ...(isOnboarding && props.replacesExistingVault === true ? { replacement: "warned-import" } : {}) },551        });552        if (!(createResponse as { ok: boolean }).ok) {553          throw new Error("CREATE_VAULT_FAILED");554        }555        if ((createResponse.data as { unlocked?: boolean } | undefined)?.unlocked === false) throw new Error("VAULT_CREATED_LOCKED");556      }557558      if (!isOnboarding && mergeMode() === "replace") {559        const clearRes = await sendMessage({ type: "CLEAR_VAULT_ENTRIES" });560        if (!(clearRes as { ok: boolean }).ok) {561          throw new Error("CLEAR_VAULT_FAILED");562        }563      }564565      let dupes = 0;566      if (!isOnboarding && mergeMode() === "add") {567        dupes = await countDuplicates(currentPreview.entries);568      }569570      let imported = 0;571      setImportProgress({ current: 0, total: currentPreview.entries.length });572573      const batchRes = await sendMessage({574        type: "BATCH_ADD_ENTRIES",575        payload: { entries: currentPreview.entries },576      });577578      if ((batchRes as { ok: boolean }).ok) {579        imported = ((batchRes as { ok: boolean; data?: VaultEntry[] }).data ?? []).length;580        setImportProgress({ current: imported, total: currentPreview.entries.length });581      } else {582        for (const entry of currentPreview.entries) {583          const response = await sendMessage({584            type: "ADD_ENTRY",585            payload: entry,586          });587          if ((response as { ok: boolean }).ok) imported += 1;588          setImportProgress({ current: imported, total: currentPreview.entries.length });589        }590      }591592      if (imported === 0) {593        throw new Error("NO_ENTRIES_IMPORTED");594      }595596      setDuplicateWarning(dupes);597      await props.onImport();598    } catch (err) {599      const message = err instanceof Error ? err.message : String(err);600      setError(getImportErrorCopy(message));601      setImporting(false);602      setImportProgress(null);603      return;604    }605606    setImporting(false);607    setImportProgress(null);608  }609610  return (611    <>612      <SubviewHeader title="backup file" onBack={props.onBack} mode={props.mode} />613      <div class="peach-settings-body">614        <Show when={isOnboarding && props.replacesExistingVault}>615          <div class="peach-settings-group">616            <div class="peach-restore-warning">617              Restoring now replaces the locked local vault on this device with618              a fresh one from your backup.619            </div>620          </div>621        </Show>622        <div class="peach-settings-group peach-export-card peach-export-card--primary">623          <p class="peach-settings-label">choose a file</p>624          <p class="peach-export-card-copy">625            Bitwarden, 1Password, Proton Pass, Chrome / Edge / Safari CSV, FIDO626              credential-exchange passkeys.627          </p>628629          <div class="peach-provider-chips">630            <span class="peach-provider-chip">FIDO passkeys</span>631            <span class="peach-provider-chip">Proton Pass</span>632            <span class="peach-provider-chip">Bitwarden</span>633            <span class="peach-provider-chip">1Password</span>634            <span class="peach-provider-chip">Browser CSV</span>635          </div>636637          <input638            class="peach-restore-file"639            type="file"640            accept=".csv,.json,.peach,application/x-peach"641            onChange={(event) => void handleFileSelect(event)}642          />643        </div>644645        <Show when={preview() && preview()!.format !== "unknown"}>646          <div class="peach-settings-group">647            <p class="peach-settings-label">{preview()!.label}</p>648            <div class="peach-import-summary">649              Found <strong>{preview()!.entries.length}</strong>{" "}650              entr{preview()!.entries.length === 1 ? "y" : "ies"}651              {preview()!.skippedItems > 0652                ? `. ${preview()!.skippedItems} skipped because no password was present.`653                : "."}654            </div>655656            <div class="peach-import-preview">657              {preview()!.entries.slice(0, 8).map((entry) => (658                <div class="peach-import-preview-row">659                  <span class="peach-import-preview-title">{entry.title}</span>660                  <span class="peach-import-preview-meta">661                    {entry.passkey662                      ? `${entry.passkey.userName} • ${entry.passkey.rpId} (passkey)`663                      : entry.type === "note"664                        ? "secure note"665                        : entry.username || entry.url || "password item"}666                  </span>667                </div>668              ))}669              <Show when={preview()!.entries.length > 8}>670                <div class="peach-import-preview-more">671                  ...and {preview()!.entries.length - 8} more672                </div>673              </Show>674            </div>675          </div>676        </Show>677678        <Show when={!isOnboarding && preview() && preview()!.format !== "unknown" && preview()!.entries.length > 0}>679          <div class="peach-settings-group">680            <p class="peach-settings-label">merge or replace</p>681            <label class="peach-import-choice">682              <input683                type="radio"684                name="merge-mode"685                value="add"686                checked={mergeMode() === "add"}687                onChange={() => { setMergeMode("add"); setAwaitingReplaceConfirm(false); }}688              />689              <span class="peach-import-choice-main">690                <span class="peach-import-choice-label">Add to existing vault</span>691                <span class="peach-import-choice-sub">692                  This will add {preview()!.entries.length} entries to your existing {existingCount()}.693                </span>694              </span>695            </label>696            <label class="peach-import-choice">697              <input698                type="radio"699                name="merge-mode"700                value="replace"701                checked={mergeMode() === "replace"}702                onChange={() => setMergeMode("replace")}703              />704              <span class="peach-import-choice-main">705                <span class="peach-import-choice-label">Replace vault</span>706                <span class="peach-import-choice-sub">707                  This will replace your {existingCount()} entries with {preview()!.entries.length} imported ones.708                </span>709              </span>710            </label>711            <Show when={awaitingReplaceConfirm()}>712              <div class="peach-restore-warning" style="margin-top:6px">713                Replace forever? This cannot be undone.714              </div>715            </Show>716          </div>717        </Show>718719        <Show when={needsMasterPassword() && preview() && preview()!.format !== "unknown"}>720          <div class="peach-settings-group">721            <OnboardingMasterPasswordFields722              idPrefix="backup"723              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."724              masterPlaceholder="new master password"725              password={masterPassword()}726              confirm={masterConfirm()}727              onPasswordInput={setMasterPassword}728              onConfirmInput={setMasterConfirm}729            />730          </div>731        </Show>732733        <Show when={error()}>734          <div class="peach-settings-group">735            <div class="peach-restore-error">{error()}</div>736          </div>737        </Show>738739        <Show when={importing() && importProgress()}>740          <div class="peach-settings-group">741            <div class="peach-import-summary">742              Importing... [{importProgress()!.current} / {importProgress()!.total}]743            </div>744          </div>745        </Show>746747        <Show when={duplicateWarning() > 0 && !importing()}>748          <div class="peach-settings-group">749            <div class="peach-export-card-copy">750              {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.751            </div>752          </div>753        </Show>754755        <Show when={preview() && preview()!.format !== "unknown"}>756          <div class="peach-settings-group">757            <div class="peach-settings-actions">758              <button759                class="peach-btn peach-btn--subtle peach-btn--sm"760                onClick={() => void handleImport()}761                disabled={762                  importing() ||763                  preview()!.entries.length === 0 ||764                  (needsMasterPassword() && !masterPasswordReady())765                }766              >767                {importing()768                  ? "importing..."769                  : isOnboarding770                    ? `Create vault + import ${preview()!.entries.length}`771                    : mergeMode() === "replace"772                      ? awaitingReplaceConfirm()773                        ? "Yes, replace forever"774                        : `Replace vault with ${preview()!.entries.length}`775                      : `Import ${preview()!.entries.length}`}776              </button>777            </div>778          </div>779        </Show>780      </div>781    </>782  );783}784785// ---------------------------------------------------------------------------786// Shared headers787// ---------------------------------------------------------------------------788789function OverlayHeader(props: { title: string; onBack: () => void }) {790  return (791    <div class="peach-overlay-header">792      <button793        class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"794        onClick={props.onBack}795        aria-label="Back"796      >797        <svg width="7" height="12" viewBox="0 0 7 12" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">798          <path d="M6 1L1 6L6 11" />799        </svg>800      </button>801      <span class="peach-overlay-title">{props.title}</span>802      <div class="peach-overlay-spacer"></div>803    </div>804  );805}806807function SubviewHeader(props: {808  title: string;809  onBack: () => void;810  mode: "existing" | "onboarding";811}) {812  // Onboarding sub-flows reuse the lock-screen header; existing-vault flows813  // use the standard overlay back-arrow header.814  return (815    <Show816      when={props.mode === "onboarding"}817      fallback={<OverlayHeader title={props.title} onBack={props.onBack} />}818    >819      <div class="peach-lock-view-header">820        <PeachWordmark class="peach-wordmark-wrap" />821        <button class="peach-lock-restore-link" onClick={props.onBack}>822          ‹ back823        </button>824      </div>825    </Show>826  );827}828829function getImportErrorCopy(error: string): string {830  // UI-7 / MV-5: oversized-import errors carry a variable detail after the831  // code, so match the prefix and never surface the raw string.832  if (error.startsWith("IMPORT_TOO_LARGE")) {833    return "This file is too large to import (limit: 10 MiB for backups, 25 MiB for Codex PDFs). If this is a real PeachScript backup, please report it — backups never approach this size.";834  }835  switch (error) {836    case "UNSUPPORTED_IMPORT_FORMAT":837      return "Unrecognised file format. Use CSV, Bitwarden JSON, Proton Pass JSON/CSV, or a PeachScript backup.";838    case "INVALID_PASSPHRASE":839      return "Wrong backup password. This is the password you chose when you created the backup.";840    case "INVALID_PEACHSCRIPT_CHARACTER":841      return "This doesn't look like PeachScript. Make sure you copied the entire backup string.";842    case "PAYLOAD_TOO_SHORT":843      return "PeachScript looks truncated. Copy the full backup string and try again.";844    case "BAD_MAGIC":845    case "UNSUPPORTED_VERSION":846      return "This PeachScript was created by a different version of Peach.";847    case "CHECKSUM_FAILED":848      return "PeachScript appears corrupted. Re-copy from the source device.";849    case "VAULT_CREATED_LOCKED":850      return "Your new vault and password were saved. Unlock Peach, then import your backup.";851    case "CREATE_VAULT_FAILED":852      return "Peach couldn't create a new local vault before importing.";853    case "CLEAR_VAULT_FAILED":854      return "Peach couldn't clear the existing vault before replacing it.";855    case "MASTER_PASSWORD_REQUIRED":856      return "Choose a master password for your new vault first.";857    case "RESTORE_FAILED":858      return "Restore failed. Your existing vault is unchanged.";859    case "vault_locked":860      return "Peach is locked. Open Peach with your master password and try again.";861    case "refuse to replace with empty entry set":862      return "This PeachScript decoded to zero entries — refusing to wipe the vault.";863    case "NO_ENTRIES_IMPORTED":864      return "No importable password entries were found in that file.";865    case "PEACHSCRIPT_TOO_LARGE":866      return "That backup is too large.";867    default:868      // Never echo raw error strings — internal messages must not reach the UI.869      return "Import failed. Please try again.";870  }871}