Import.tsx

31.6 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 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 / 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 [masterPassword, setMasterPassword] = createSignal("");417  const [masterConfirm, setMasterConfirm] = createSignal("");418  const [importing, setImporting] = createSignal(false);419  const [error, setError] = createSignal<string | null>(null);420  const [mergeMode, setMergeMode] = createSignal<ImportMergeMode>("add");421  const [awaitingReplaceConfirm, setAwaitingReplaceConfirm] = createSignal(false);422  const [importProgress, setImportProgress] = createSignal<{ current: number; total: number } | null>(null);423  const [duplicateWarning, setDuplicateWarning] = createSignal<number>(0);424  const [existingCount, setExistingCount] = createSignal<number>(0);425426  const masterPasswordReady = createMemo(427    () => masterPassword().length >= 8 && masterPassword() === masterConfirm()428  );429430  async function refreshExistingCount() {431    if (isOnboarding) return;432    const res = await sendMessage({ type: "GET_ENTRIES" });433    const list = (res as { ok: boolean; data?: VaultEntry[] }).data ?? [];434    setExistingCount(list.length);435  }436  void refreshExistingCount();437438  async function parseSource(text: string) {439    try {440      const result = await parseImportSource(text);441      setPreview(result);442      setError(null);443      if (result.format === "unknown") {444        setError(445          "We couldn't recognise this file format. Peach supports: Bitwarden JSON/CSV, Proton Pass JSON/CSV, 1Password JSON, and generic browser CSV exports."446        );447      }448      return result;449    } catch (err) {450      const message = err instanceof Error ? err.message : String(err);451      setPreview(null);452      setError(getImportErrorCopy(message));453      return null;454    }455  }456457  async function handleFileSelect(event: Event) {458    const input = event.target as HTMLInputElement;459    const file = input.files?.[0];460    if (!file) return;461462    setPreview(null);463    setError(null);464    setAwaitingReplaceConfirm(false);465466    const text = await file.text();467468    // Route .peach files to the PeachScript subview. Detection is two-pronged:469    // either the filename ends in .peach, or the body is entirely PUA chars470    // (the canonical PeachScript shape). The two-pronged check protects471    // against renamed-extension imports and against text editors that472    // accidentally save with a different extension.473    const looksLikePeach =474      file.name.toLowerCase().endsWith(".peach") || isPeachScript(text);475    if (looksLikePeach) {476      if (props.onLoadPeachFile) {477        props.onLoadPeachFile(text);478        input.value = "";479        return;480      }481      setError("This is a .peach file. Open the PeachScript card to import it.");482      return;483    }484485    await parseSource(text);486  }487488  async function countDuplicates(incoming: ImportParseResult["entries"]): Promise<number> {489    if (incoming.length === 0) return 0;490    const res = await sendMessage({ type: "GET_ENTRIES" });491    const existing = ((res as { ok: boolean; data?: VaultEntry[] }).data ?? []).filter((e) => !e.deletedAt);492    const keyOf = (title?: string, url?: string, username?: string) =>493      `${(title ?? "").toLowerCase()}|${(url ?? "").toLowerCase()}|${(username ?? "").toLowerCase()}`;494    const existingKeys = new Set(existing.map((e) => keyOf(e.title, e.url, e.username)));495    let dupes = 0;496    for (const entry of incoming) {497      const u = "username" in entry ? entry.username : undefined;498      const url = "url" in entry ? entry.url : undefined;499      if (existingKeys.has(keyOf(entry.title, url, u))) dupes += 1;500    }501    return dupes;502  }503504  async function handleImport() {505    const currentPreview = preview();506    if (!currentPreview) return;507508    if (needsMasterPassword()) {509      if (masterPassword().length < 8) {510        setError("Master password must be at least 8 characters.");511        return;512      }513      if (!masterPasswordReady()) {514        setError("Master passwords do not match.");515        return;516      }517    }518519    if (!isOnboarding && mergeMode() === "replace" && !awaitingReplaceConfirm()) {520      setAwaitingReplaceConfirm(true);521      return;522    }523524    setImporting(true);525    setError(null);526    setDuplicateWarning(0);527    setImportProgress(null);528529    try {530      if (currentPreview.entries.length === 0) {531        throw new Error("NO_ENTRIES_IMPORTED");532      }533534      if (needsMasterPassword()) {535        const createResponse = await sendMessage({536          type: "CREATE_VAULT",537          payload: { password: masterPassword() },538        });539        if (!(createResponse as { ok: boolean }).ok) {540          throw new Error("CREATE_VAULT_FAILED");541        }542      }543544      if (!isOnboarding && mergeMode() === "replace") {545        const clearRes = await sendMessage({ type: "CLEAR_VAULT_ENTRIES" });546        if (!(clearRes as { ok: boolean }).ok) {547          throw new Error("CLEAR_VAULT_FAILED");548        }549      }550551      let dupes = 0;552      if (!isOnboarding && mergeMode() === "add") {553        dupes = await countDuplicates(currentPreview.entries);554      }555556      let imported = 0;557      setImportProgress({ current: 0, total: currentPreview.entries.length });558559      const batchRes = await sendMessage({560        type: "BATCH_ADD_ENTRIES",561        payload: { entries: currentPreview.entries },562      });563564      if ((batchRes as { ok: boolean }).ok) {565        imported = ((batchRes as { ok: boolean; data?: VaultEntry[] }).data ?? []).length;566        setImportProgress({ current: imported, total: currentPreview.entries.length });567      } else {568        for (const entry of currentPreview.entries) {569          const response = await sendMessage({570            type: "ADD_ENTRY",571            payload: entry,572          });573          if ((response as { ok: boolean }).ok) imported += 1;574          setImportProgress({ current: imported, total: currentPreview.entries.length });575        }576      }577578      if (imported === 0) {579        throw new Error("NO_ENTRIES_IMPORTED");580      }581582      setDuplicateWarning(dupes);583      await props.onImport();584    } catch (err) {585      const message = err instanceof Error ? err.message : String(err);586      setError(getImportErrorCopy(message));587      setImporting(false);588      setImportProgress(null);589      return;590    }591592    setImporting(false);593    setImportProgress(null);594  }595596  return (597    <>598      <SubviewHeader title="backup file" onBack={props.onBack} mode={props.mode} />599      <div class="peach-settings-body">600        <Show when={isOnboarding && props.replacesExistingVault}>601          <div class="peach-settings-group">602            <div class="peach-restore-warning">603              Restoring now replaces the locked local vault on this device with604              a fresh one from your backup.605            </div>606          </div>607        </Show>608        <div class="peach-settings-group peach-export-card peach-export-card--primary">609          <p class="peach-settings-label">choose a file</p>610          <p class="peach-export-card-copy">611            Bitwarden, 1Password, Proton Pass, Chrome / Edge / Safari CSV, FIDO612              credential-exchange passkeys.613          </p>614615          <div class="peach-provider-chips">616            <span class="peach-provider-chip">FIDO passkeys</span>617            <span class="peach-provider-chip">Proton Pass</span>618            <span class="peach-provider-chip">Bitwarden</span>619            <span class="peach-provider-chip">1Password</span>620            <span class="peach-provider-chip">Browser CSV</span>621          </div>622623          <input624            class="peach-restore-file"625            type="file"626            accept=".csv,.json,.peach,application/x-peach"627            onChange={(event) => void handleFileSelect(event)}628          />629        </div>630631        <Show when={preview() && preview()!.format !== "unknown"}>632          <div class="peach-settings-group">633            <p class="peach-settings-label">{preview()!.label}</p>634            <div class="peach-import-summary">635              Found <strong>{preview()!.entries.length}</strong>{" "}636              entr{preview()!.entries.length === 1 ? "y" : "ies"}637              {preview()!.skippedItems > 0638                ? `. ${preview()!.skippedItems} skipped because no password was present.`639                : "."}640            </div>641642            <div class="peach-import-preview">643              {preview()!.entries.slice(0, 8).map((entry) => (644                <div class="peach-import-preview-row">645                  <span class="peach-import-preview-title">{entry.title}</span>646                  <span class="peach-import-preview-meta">647                    {entry.passkey648                      ? `${entry.passkey.userName} • ${entry.passkey.rpId} (passkey)`649                      : entry.type === "note"650                        ? "secure note"651                        : entry.username || entry.url || "password item"}652                  </span>653                </div>654              ))}655              <Show when={preview()!.entries.length > 8}>656                <div class="peach-import-preview-more">657                  ...and {preview()!.entries.length - 8} more658                </div>659              </Show>660            </div>661          </div>662        </Show>663664        <Show when={!isOnboarding && preview() && preview()!.format !== "unknown" && preview()!.entries.length > 0}>665          <div class="peach-settings-group">666            <p class="peach-settings-label">merge or replace</p>667            <label class="peach-import-choice">668              <input669                type="radio"670                name="merge-mode"671                value="add"672                checked={mergeMode() === "add"}673                onChange={() => { setMergeMode("add"); setAwaitingReplaceConfirm(false); }}674              />675              <span class="peach-import-choice-main">676                <span class="peach-import-choice-label">Add to existing vault</span>677                <span class="peach-import-choice-sub">678                  This will add {preview()!.entries.length} entries to your existing {existingCount()}.679                </span>680              </span>681            </label>682            <label class="peach-import-choice">683              <input684                type="radio"685                name="merge-mode"686                value="replace"687                checked={mergeMode() === "replace"}688                onChange={() => setMergeMode("replace")}689              />690              <span class="peach-import-choice-main">691                <span class="peach-import-choice-label">Replace vault</span>692                <span class="peach-import-choice-sub">693                  This will replace your {existingCount()} entries with {preview()!.entries.length} imported ones.694                </span>695              </span>696            </label>697            <Show when={awaitingReplaceConfirm()}>698              <div class="peach-restore-warning" style="margin-top:6px">699                Replace forever? This cannot be undone.700              </div>701            </Show>702          </div>703        </Show>704705        <Show when={needsMasterPassword() && preview() && preview()!.format !== "unknown"}>706          <div class="peach-settings-group">707            <OnboardingMasterPasswordFields708              idPrefix="backup"709              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."710              masterPlaceholder="new master password"711              password={masterPassword()}712              confirm={masterConfirm()}713              onPasswordInput={setMasterPassword}714              onConfirmInput={setMasterConfirm}715            />716          </div>717        </Show>718719        <Show when={error()}>720          <div class="peach-settings-group">721            <div class="peach-restore-error">{error()}</div>722          </div>723        </Show>724725        <Show when={importing() && importProgress()}>726          <div class="peach-settings-group">727            <div class="peach-import-summary">728              Importing... [{importProgress()!.current} / {importProgress()!.total}]729            </div>730          </div>731        </Show>732733        <Show when={duplicateWarning() > 0 && !importing()}>734          <div class="peach-settings-group">735            <div class="peach-export-card-copy">736              {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.737            </div>738          </div>739        </Show>740741        <Show when={preview() && preview()!.format !== "unknown"}>742          <div class="peach-settings-group">743            <div class="peach-settings-actions">744              <button745                class="peach-btn peach-btn--subtle peach-btn--sm"746                onClick={() => void handleImport()}747                disabled={748                  importing() ||749                  preview()!.entries.length === 0 ||750                  (needsMasterPassword() && !masterPasswordReady())751                }752              >753                {importing()754                  ? "importing..."755                  : isOnboarding756                    ? `Create vault + import ${preview()!.entries.length}`757                    : mergeMode() === "replace"758                      ? awaitingReplaceConfirm()759                        ? "Yes, replace forever"760                        : `Replace vault with ${preview()!.entries.length}`761                      : `Import ${preview()!.entries.length}`}762              </button>763            </div>764          </div>765        </Show>766      </div>767    </>768  );769}770771// ---------------------------------------------------------------------------772// Shared headers773// ---------------------------------------------------------------------------774775function OverlayHeader(props: { title: string; onBack: () => void }) {776  return (777    <div class="peach-overlay-header">778      <button779        class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"780        onClick={props.onBack}781        aria-label="Back"782      >783        <svg width="7" height="12" viewBox="0 0 7 12" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">784          <path d="M6 1L1 6L6 11" />785        </svg>786      </button>787      <span class="peach-overlay-title">{props.title}</span>788      <div class="peach-overlay-spacer"></div>789    </div>790  );791}792793function SubviewHeader(props: {794  title: string;795  onBack: () => void;796  mode: "existing" | "onboarding";797}) {798  // Onboarding sub-flows reuse the lock-screen header; existing-vault flows799  // use the standard overlay back-arrow header.800  return (801    <Show802      when={props.mode === "onboarding"}803      fallback={<OverlayHeader title={props.title} onBack={props.onBack} />}804    >805      <div class="peach-lock-view-header">806        <PeachWordmark class="peach-wordmark-wrap" />807        <button class="peach-lock-restore-link" onClick={props.onBack}>808          ‹ back809        </button>810      </div>811    </Show>812  );813}814815function getImportErrorCopy(error: string): string {816  // UI-7 / MV-5: oversized-import errors carry a variable detail after the817  // code, so match the prefix and never surface the raw string.818  if (error.startsWith("IMPORT_TOO_LARGE")) {819    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.";820  }821  switch (error) {822    case "UNSUPPORTED_IMPORT_FORMAT":823      return "Unrecognised file format. Use CSV, Bitwarden JSON, Proton Pass JSON/CSV, or a PeachScript backup.";824    case "INVALID_PASSPHRASE":825      return "Wrong backup password. This is the password you chose when you created the backup.";826    case "INVALID_PEACHSCRIPT_CHARACTER":827      return "This doesn't look like PeachScript. Make sure you copied the entire backup string.";828    case "PAYLOAD_TOO_SHORT":829      return "PeachScript looks truncated. Copy the full backup string and try again.";830    case "BAD_MAGIC":831    case "UNSUPPORTED_VERSION":832      return "This PeachScript was created by a different version of Peach.";833    case "CHECKSUM_FAILED":834      return "PeachScript appears corrupted. Re-copy from the source device.";835    case "CREATE_VAULT_FAILED":836      return "Peach couldn't create a new local vault before importing.";837    case "CLEAR_VAULT_FAILED":838      return "Peach couldn't clear the existing vault before replacing it.";839    case "MASTER_PASSWORD_REQUIRED":840      return "Choose a master password for your new vault first.";841    case "RESTORE_FAILED":842      return "Restore failed. Your existing vault is unchanged.";843    case "vault_locked":844      return "Peach is locked. Open Peach with your master password and try again.";845    case "refuse to replace with empty entry set":846      return "This PeachScript decoded to zero entries — refusing to wipe the vault.";847    case "NO_ENTRIES_IMPORTED":848      return "No importable password entries were found in that file.";849    default:850      return error;851  }852}