Import.tsx

32.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 { IMPORT_LIMITS } from "../../shared/import-limits";18import type { VaultEntry } from "../../shared/types";1920type ImportSubview = "menu" | "peachscript" | "file";21type ImportMergeMode = "add" | "replace";2223interface ImportProps {24  mode?: "existing" | "onboarding";25  replacesExistingVault?: boolean;26  /** Skip the menu and open straight into a specific subview. */27  initialView?: ImportSubview;28  onBack: () => void;29  onImport: () => void | Promise<void>;30}3132function OnboardingMasterPasswordFields(props: {33  idPrefix: string;34  copy: string;35  masterPlaceholder: string;36  password: string;37  confirm: string;38  onPasswordInput: (value: string) => void;39  onConfirmInput: (value: string) => void;40}) {41  const [showPassword, setShowPassword] = createSignal(false);4243  return (44    <>45      <div class="peach-newvault-label-row">46        <label class="peach-label" for={`${props.idPrefix}-master-password`}>47          new master password48        </label>49        <button50          class="peach-lock-reveal-btn"51          type="button"52          onClick={() => setShowPassword((value) => !value)}53          aria-label={showPassword() ? "Hide passwords" : "Show passwords"}54        >55          <Show56            when={showPassword()}57            fallback={58              <svg width="15" height="10" viewBox="0 0 14 10" fill="none" stroke="currentColor" stroke-width="0.9" stroke-linecap="round">59                <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" />60                <circle cx="7" cy="5" r="1.75" />61              </svg>62            }63          >64            <svg width="15" height="10" viewBox="0 0 14 10" fill="none" stroke="currentColor" stroke-width="0.9" stroke-linecap="round">65              <path d="M1 2C3 4.5 5 6 7 6C9 6 11 4.5 13 2" />66              <path d="M3.5 5.5L2.5 7.5" />67              <path d="M7 6.5V8.5" />68              <path d="M10.5 5.5L11.5 7.5" />69            </svg>70          </Show>71          {showPassword() ? "hide" : "show"}72        </button>73      </div>74      <p class="peach-export-card-copy">{props.copy}</p>75      <div class="peach-settings-stack peach-export-password-stack">76        <input77          id={`${props.idPrefix}-master-password`}78          class="peach-settings-input"79          type={showPassword() ? "text" : "password"}80          placeholder={props.masterPlaceholder}81          value={props.password}82          onInput={(event) => props.onPasswordInput((event.target as HTMLInputElement).value)}83        />84        <input85          id={`${props.idPrefix}-confirm-password`}86          class="peach-settings-input"87          type={showPassword() ? "text" : "password"}88          placeholder="confirm master password"89          value={props.confirm}90          onInput={(event) => props.onConfirmInput((event.target as HTMLInputElement).value)}91        />92        <Show when={props.confirm.length > 0 && props.password !== props.confirm}>93          <p class="peach-export-note" style="color:var(--peach-t2)">94            Passwords don't match95          </p>96        </Show>97      </div>98    </>99  );100}101102export function ImportView(props: ImportProps) {103  const [view, setView] = createSignal<ImportSubview>(props.initialView ?? "menu");104  // When FileImport detects a .peach file, it stashes the contents here and105  // routes the view to "peachscript" so the existing decode flow handles it.106  const [peachScriptPrefill, setPeachScriptPrefill] = createSignal<string>("");107  const mode = () => props.mode ?? "existing";108  const isOnboarding = () => mode() === "onboarding";109  // When the caller deep-links into a subview, the back arrow exits the110  // ImportView entirely. Otherwise it returns to the import menu.111  const subviewBack = () => (props.initialView ? props.onBack() : setView("menu"));112113  return (114    <div class={isOnboarding() ? "peach-lock-view" : "peach-overlay-view ov-enter-right"} style="display:flex">115      <Show when={view() === "menu"}>116        <ImportMenu117          mode={mode()}118          replacesExistingVault={props.replacesExistingVault}119          onBack={props.onBack}120          onPick={(v) => setView(v)}121        />122      </Show>123      <Show when={view() === "peachscript"}>124        <PeachScriptImport125          mode={mode()}126          replacesExistingVault={props.replacesExistingVault}127          initialScript={peachScriptPrefill()}128          onBack={() => {129            setPeachScriptPrefill("");130            subviewBack();131          }}132          onImport={props.onImport}133        />134      </Show>135      <Show when={view() === "file"}>136        <FileImport137          mode={mode()}138          replacesExistingVault={props.replacesExistingVault}139          onBack={subviewBack}140          onImport={props.onImport}141          onLoadPeachFile={(content) => {142            setPeachScriptPrefill(content);143            setView("peachscript");144          }}145        />146      </Show>147    </div>148  );149}150151// ---------------------------------------------------------------------------152// Menu153// ---------------------------------------------------------------------------154155function ImportMenu(props: {156  mode: "existing" | "onboarding";157  replacesExistingVault?: boolean;158  onBack: () => void;159  onPick: (view: ImportSubview) => void;160}) {161  const isOnboarding = props.mode === "onboarding";162  return (163    <>164      <Show165        when={isOnboarding}166        fallback={<OverlayHeader title="import" onBack={props.onBack} />}167      >168        <div class="peach-lock-view-header">169          <PeachWordmark class="peach-wordmark-wrap" />170          <button class="peach-lock-restore-link" onClick={props.onBack}>171            ‹ back172          </button>173        </div>174      </Show>175      <div class="peach-settings-body peach-export-menu">176        <Show when={isOnboarding && props.replacesExistingVault}>177          <div class="peach-settings-group">178            <div class="peach-restore-warning">179              Restoring now replaces the locked local vault on this device with180              a fresh one from your backup or export file.181            </div>182          </div>183        </Show>184185        <div class="peach-settings-group peach-export-card peach-export-card--primary">186          <p class="peach-settings-label">peachscript</p>187          <p class="peach-export-card-copy">188            Paste a PeachScript backup from another Peach device.189            {props.mode === "existing" ? " We'll merge it into your vault." : ""}190          </p>191          <button192            class="peach-btn peach-btn--subtle peach-btn--sm"193            onClick={() => props.onPick("peachscript")}194          >195            Paste PeachScript →196          </button>197        </div>198199        <div class="peach-settings-group peach-export-card">200          <p class="peach-settings-label">backup file</p>201          <p class="peach-export-card-copy">202            A file from Bitwarden, Proton Pass,203            1Password, or a browser CSV (Chrome, Safari, Edge).204          </p>205          <button206            class="peach-btn peach-btn--subtle peach-btn--sm"207            onClick={() => props.onPick("file")}208          >209            Choose file →210          </button>211        </div>212      </div>213    </>214  );215}216217// ---------------------------------------------------------------------------218// PeachScript paste flow219// ---------------------------------------------------------------------------220221function PeachScriptImport(props: {222  mode: "existing" | "onboarding";223  replacesExistingVault?: boolean;224  /** Optional initial PeachScript content — set when the user loaded a225   *  .peach file from the CSV/file card and was routed here. */226  initialScript?: string;227  onBack: () => void;228  onImport: () => void | Promise<void>;229}) {230  const [scriptInput, setScriptInput] = createSignal(props.initialScript ?? "");231  const [scriptPass, setScriptPass] = createSignal("");232  const [masterPassword, setMasterPassword] = createSignal("");233  const [masterConfirm, setMasterConfirm] = createSignal("");234  const [working, setWorking] = createSignal(false);235  const [error, setError] = createSignal<string | null>(null);236  const [result, setResult] = createSignal<{ entryCount: number } | null>(null);237238  const scriptLooksValid = createMemo(() => isPeachScript(scriptInput()));239  const isOnboarding = props.mode === "onboarding";240  const masterPasswordReady = createMemo(241    () => masterPassword().length >= 8 && masterPassword() === masterConfirm()242  );243244  async function handleImport() {245    setError(null);246    setResult(null);247    if (!scriptLooksValid()) {248      setError("Paste your PeachScript first.");249      return;250    }251    if (!scriptPass().trim()) {252      setError("Enter the backup password.");253      return;254    }255    setWorking(true);256    try {257      const bytes = decodePeachScript(normalisePeachScript(scriptInput()));258      const payload = await parsePayload(bytes, scriptPass());259260      if (isOnboarding) {261        if (!masterPasswordReady()) {262          throw new Error("MASTER_PASSWORD_REQUIRED");263        }264        const createRes = await sendMessage({265          type: "CREATE_VAULT",266          payload: { password: masterPassword() },267        });268        if (!(createRes as { ok: boolean }).ok) throw new Error("CREATE_VAULT_FAILED");269      }270271      const restoreRes = await sendMessage({272        type: "RESTORE_ENTRIES",273        payload: {274          entries: payload.entries,275          mode: "merge",276          settings: payload.settings,277        },278      });279      const restoreEnvelope = restoreRes as { ok: boolean; error?: string };280      if (!restoreEnvelope.ok) {281        throw new Error(restoreEnvelope.error ?? "RESTORE_FAILED");282      }283284      if (payload.license?.key) {285        await sendMessage({286          type: "ACTIVATE_LICENSE",287          payload: { key: payload.license.key },288        }).catch(() => {});289      }290291      setResult({ entryCount: payload.entries.length });292      await props.onImport();293    } catch (err) {294      const code = err instanceof Error ? err.message : String(err);295      setError(getImportErrorCopy(code));296    } finally {297      setWorking(false);298    }299  }300301  return (302    <>303      <SubviewHeader title="peachscript" onBack={props.onBack} mode={props.mode} />304      <div class="peach-settings-body">305        <Show when={isOnboarding && props.replacesExistingVault}>306          <div class="peach-settings-group">307            <div class="peach-restore-warning">308              Restoring now replaces the locked local vault on this device with309              a fresh one from your backup.310            </div>311          </div>312        </Show>313        <div class="peach-settings-group peach-export-card peach-export-card--primary peach-export-pass-group">314          <p class="peach-settings-label">paste peachscript</p>315          <p class="peach-export-card-copy">316            {isOnboarding317              ? "Paste a PeachScript backup from another Peach device to restore your vault — or load a .peach file from disk."318              : "We'll merge the entries into your existing vault. You can paste PeachScript or load a .peach file."}319          </p>320          <textarea321            class="peach-script-input"322            placeholder="paste peachscript…"323            value={scriptInput()}324            onInput={(e) => setScriptInput((e.target as HTMLTextAreaElement).value)}325          />326          <label327            class="peach-btn peach-btn--ghost peach-btn--sm"328            style="display:inline-flex;align-items:center;justify-content:center;cursor:pointer;"329          >330            Load .peach file331            <input332              type="file"333              accept=".peach,application/x-peach,text/plain"334              style="display:none;"335              onChange={async (event) => {336                const input = event.currentTarget;337                const file = input.files?.[0];338                if (!file) return;339                try {340                  // PB-26-010: bound before reading the file into a string.341                  if (file.size > IMPORT_LIMITS.MAX_JSON_BYTES) {342                    setError("That file is too large.");343                    return;344                  }345                  const text = await file.text();346                  setScriptInput(text);347                } catch (err) {348                  setError(err instanceof Error ? err.message : "Couldn't read file.");349                } finally {350                  input.value = "";351                }352              }}353            />354          </label>355          <div class="peach-settings-stack peach-export-password-stack">356            <input357              class="peach-settings-input"358              type="password"359              placeholder="PeachScript password"360              value={scriptPass()}361              onInput={(e) => setScriptPass((e.target as HTMLInputElement).value)}362            />363          </div>364          <Show when={isOnboarding}>365            <OnboardingMasterPasswordFields366              idPrefix="peachscript"367              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."368              masterPlaceholder="new master password"369              password={masterPassword()}370              confirm={masterConfirm()}371              onPasswordInput={setMasterPassword}372              onConfirmInput={setMasterConfirm}373            />374          </Show>375          <button376            class="peach-btn peach-btn--subtle peach-btn--sm"377            onClick={() => void handleImport()}378            disabled={379              working() ||380              !scriptLooksValid() ||381              !scriptPass().trim() ||382              (isOnboarding && !masterPasswordReady())383            }384          >385            {working() ? "decoding…" : "Restore from PeachScript"}386          </button>387          <Show when={error()}>388            <div class="peach-restore-error">{error()}</div>389          </Show>390          <Show when={result()}>391            <div class="peach-export-success">392              <span class="peach-export-success-check">✓</span>393              <span>394                Restored {result()!.entryCount} entr395                {result()!.entryCount === 1 ? "y" : "ies"}.396              </span>397            </div>398          </Show>399        </div>400      </div>401    </>402  );403}404405// ---------------------------------------------------------------------------406// File flow (Bitwarden / 1Password / etc.)407// ---------------------------------------------------------------------------408409function FileImport(props: {410  mode: "existing" | "onboarding";411  replacesExistingVault?: boolean;412  onBack: () => void;413  onImport: () => void | Promise<void>;414  /** Called when the user picks a .peach file from this picker — the parent415   *  routes them to the PeachScript subview with the contents prefilled. */416  onLoadPeachFile?: (content: string) => void;417}) {418  const isOnboarding = props.mode === "onboarding";419  const needsMasterPassword = () => isOnboarding;420421  const [preview, setPreview] = createSignal<ImportParseResult | null>(null);422  const [masterPassword, setMasterPassword] = createSignal("");423  const [masterConfirm, setMasterConfirm] = createSignal("");424  const [importing, setImporting] = createSignal(false);425  const [error, setError] = createSignal<string | null>(null);426  const [mergeMode, setMergeMode] = createSignal<ImportMergeMode>("add");427  const [awaitingReplaceConfirm, setAwaitingReplaceConfirm] = createSignal(false);428  const [importProgress, setImportProgress] = createSignal<{ current: number; total: number } | null>(null);429  const [duplicateWarning, setDuplicateWarning] = createSignal<number>(0);430  const [existingCount, setExistingCount] = createSignal<number>(0);431432  const masterPasswordReady = createMemo(433    () => masterPassword().length >= 8 && masterPassword() === masterConfirm()434  );435436  async function refreshExistingCount() {437    if (isOnboarding) return;438    const res = await sendMessage({ type: "GET_ENTRIES" });439    const list = (res as { ok: boolean; data?: VaultEntry[] }).data ?? [];440    setExistingCount(list.length);441  }442  void refreshExistingCount();443444  async function parseSource(text: string) {445    try {446      const result = await parseImportSource(text);447      setPreview(result);448      setError(null);449      if (result.format === "unknown") {450        setError(451          "We couldn't recognise this file format. Peach supports: Bitwarden JSON/CSV, Proton Pass JSON/CSV, 1Password JSON, and generic browser CSV exports."452        );453      }454      return result;455    } catch (err) {456      const message = err instanceof Error ? err.message : String(err);457      setPreview(null);458      setError(getImportErrorCopy(message));459      return null;460    }461  }462463  async function handleFileSelect(event: Event) {464    const input = event.target as HTMLInputElement;465    const file = input.files?.[0];466    if (!file) return;467468    setPreview(null);469    setError(null);470    setAwaitingReplaceConfirm(false);471472    const text = await file.text();473474    // Route .peach files to the PeachScript subview. Detection is two-pronged:475    // either the filename ends in .peach, or the body is entirely PUA chars476    // (the canonical PeachScript shape). The two-pronged check protects477    // against renamed-extension imports and against text editors that478    // accidentally save with a different extension.479    const looksLikePeach =480      file.name.toLowerCase().endsWith(".peach") || isPeachScript(text);481    if (looksLikePeach) {482      if (props.onLoadPeachFile) {483        props.onLoadPeachFile(text);484        input.value = "";485        return;486      }487      setError("This is a .peach file. Open the PeachScript card to import it.");488      return;489    }490491    await parseSource(text);492  }493494  async function countDuplicates(incoming: ImportParseResult["entries"]): Promise<number> {495    if (incoming.length === 0) return 0;496    const res = await sendMessage({ type: "GET_ENTRIES" });497    const existing = ((res as { ok: boolean; data?: VaultEntry[] }).data ?? []).filter((e) => !e.deletedAt);498    const keyOf = (title?: string, url?: string, username?: string) =>499      `${(title ?? "").toLowerCase()}|${(url ?? "").toLowerCase()}|${(username ?? "").toLowerCase()}`;500    const existingKeys = new Set(existing.map((e) => keyOf(e.title, e.url, e.username)));501    let dupes = 0;502    for (const entry of incoming) {503      const u = "username" in entry ? entry.username : undefined;504      const url = "url" in entry ? entry.url : undefined;505      if (existingKeys.has(keyOf(entry.title, url, u))) dupes += 1;506    }507    return dupes;508  }509510  async function handleImport() {511    const currentPreview = preview();512    if (!currentPreview) return;513514    if (needsMasterPassword()) {515      if (masterPassword().length < 8) {516        setError("Master password must be at least 8 characters.");517        return;518      }519      if (!masterPasswordReady()) {520        setError("Master passwords do not match.");521        return;522      }523    }524525    if (!isOnboarding && mergeMode() === "replace" && !awaitingReplaceConfirm()) {526      setAwaitingReplaceConfirm(true);527      return;528    }529530    setImporting(true);531    setError(null);532    setDuplicateWarning(0);533    setImportProgress(null);534535    try {536      if (currentPreview.entries.length === 0) {537        throw new Error("NO_ENTRIES_IMPORTED");538      }539540      if (needsMasterPassword()) {541        const createResponse = await sendMessage({542          type: "CREATE_VAULT",543          payload: { password: masterPassword() },544        });545        if (!(createResponse as { ok: boolean }).ok) {546          throw new Error("CREATE_VAULT_FAILED");547        }548      }549550      if (!isOnboarding && mergeMode() === "replace") {551        const clearRes = await sendMessage({ type: "CLEAR_VAULT_ENTRIES" });552        if (!(clearRes as { ok: boolean }).ok) {553          throw new Error("CLEAR_VAULT_FAILED");554        }555      }556557      let dupes = 0;558      if (!isOnboarding && mergeMode() === "add") {559        dupes = await countDuplicates(currentPreview.entries);560      }561562      let imported = 0;563      setImportProgress({ current: 0, total: currentPreview.entries.length });564565      const batchRes = await sendMessage({566        type: "BATCH_ADD_ENTRIES",567        payload: { entries: currentPreview.entries },568      });569570      if ((batchRes as { ok: boolean }).ok) {571        imported = ((batchRes as { ok: boolean; data?: VaultEntry[] }).data ?? []).length;572        setImportProgress({ current: imported, total: currentPreview.entries.length });573      } else {574        for (const entry of currentPreview.entries) {575          const response = await sendMessage({576            type: "ADD_ENTRY",577            payload: entry,578          });579          if ((response as { ok: boolean }).ok) imported += 1;580          setImportProgress({ current: imported, total: currentPreview.entries.length });581        }582      }583584      if (imported === 0) {585        throw new Error("NO_ENTRIES_IMPORTED");586      }587588      setDuplicateWarning(dupes);589      await props.onImport();590    } catch (err) {591      const message = err instanceof Error ? err.message : String(err);592      setError(getImportErrorCopy(message));593      setImporting(false);594      setImportProgress(null);595      return;596    }597598    setImporting(false);599    setImportProgress(null);600  }601602  return (603    <>604      <SubviewHeader title="backup file" onBack={props.onBack} mode={props.mode} />605      <div class="peach-settings-body">606        <Show when={isOnboarding && props.replacesExistingVault}>607          <div class="peach-settings-group">608            <div class="peach-restore-warning">609              Restoring now replaces the locked local vault on this device with610              a fresh one from your backup.611            </div>612          </div>613        </Show>614        <div class="peach-settings-group peach-export-card peach-export-card--primary">615          <p class="peach-settings-label">choose a file</p>616          <p class="peach-export-card-copy">617            Bitwarden, 1Password, Proton Pass, Chrome / Edge / Safari CSV, FIDO618              credential-exchange passkeys.619          </p>620621          <div class="peach-provider-chips">622            <span class="peach-provider-chip">FIDO passkeys</span>623            <span class="peach-provider-chip">Proton Pass</span>624            <span class="peach-provider-chip">Bitwarden</span>625            <span class="peach-provider-chip">1Password</span>626            <span class="peach-provider-chip">Browser CSV</span>627          </div>628629          <input630            class="peach-restore-file"631            type="file"632            accept=".csv,.json,.peach,application/x-peach"633            onChange={(event) => void handleFileSelect(event)}634          />635        </div>636637        <Show when={preview() && preview()!.format !== "unknown"}>638          <div class="peach-settings-group">639            <p class="peach-settings-label">{preview()!.label}</p>640            <div class="peach-import-summary">641              Found <strong>{preview()!.entries.length}</strong>{" "}642              entr{preview()!.entries.length === 1 ? "y" : "ies"}643              {preview()!.skippedItems > 0644                ? `. ${preview()!.skippedItems} skipped because no password was present.`645                : "."}646            </div>647648            <div class="peach-import-preview">649              {preview()!.entries.slice(0, 8).map((entry) => (650                <div class="peach-import-preview-row">651                  <span class="peach-import-preview-title">{entry.title}</span>652                  <span class="peach-import-preview-meta">653                    {entry.passkey654                      ? `${entry.passkey.userName} • ${entry.passkey.rpId} (passkey)`655                      : entry.type === "note"656                        ? "secure note"657                        : entry.username || entry.url || "password item"}658                  </span>659                </div>660              ))}661              <Show when={preview()!.entries.length > 8}>662                <div class="peach-import-preview-more">663                  ...and {preview()!.entries.length - 8} more664                </div>665              </Show>666            </div>667          </div>668        </Show>669670        <Show when={!isOnboarding && preview() && preview()!.format !== "unknown" && preview()!.entries.length > 0}>671          <div class="peach-settings-group">672            <p class="peach-settings-label">merge or replace</p>673            <label class="peach-import-choice">674              <input675                type="radio"676                name="merge-mode"677                value="add"678                checked={mergeMode() === "add"}679                onChange={() => { setMergeMode("add"); setAwaitingReplaceConfirm(false); }}680              />681              <span class="peach-import-choice-main">682                <span class="peach-import-choice-label">Add to existing vault</span>683                <span class="peach-import-choice-sub">684                  This will add {preview()!.entries.length} entries to your existing {existingCount()}.685                </span>686              </span>687            </label>688            <label class="peach-import-choice">689              <input690                type="radio"691                name="merge-mode"692                value="replace"693                checked={mergeMode() === "replace"}694                onChange={() => setMergeMode("replace")}695              />696              <span class="peach-import-choice-main">697                <span class="peach-import-choice-label">Replace vault</span>698                <span class="peach-import-choice-sub">699                  This will replace your {existingCount()} entries with {preview()!.entries.length} imported ones.700                </span>701              </span>702            </label>703            <Show when={awaitingReplaceConfirm()}>704              <div class="peach-restore-warning" style="margin-top:6px">705                Replace forever? This cannot be undone.706              </div>707            </Show>708          </div>709        </Show>710711        <Show when={needsMasterPassword() && preview() && preview()!.format !== "unknown"}>712          <div class="peach-settings-group">713            <OnboardingMasterPasswordFields714              idPrefix="backup"715              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."716              masterPlaceholder="new master password"717              password={masterPassword()}718              confirm={masterConfirm()}719              onPasswordInput={setMasterPassword}720              onConfirmInput={setMasterConfirm}721            />722          </div>723        </Show>724725        <Show when={error()}>726          <div class="peach-settings-group">727            <div class="peach-restore-error">{error()}</div>728          </div>729        </Show>730731        <Show when={importing() && importProgress()}>732          <div class="peach-settings-group">733            <div class="peach-import-summary">734              Importing... [{importProgress()!.current} / {importProgress()!.total}]735            </div>736          </div>737        </Show>738739        <Show when={duplicateWarning() > 0 && !importing()}>740          <div class="peach-settings-group">741            <div class="peach-export-card-copy">742              {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.743            </div>744          </div>745        </Show>746747        <Show when={preview() && preview()!.format !== "unknown"}>748          <div class="peach-settings-group">749            <div class="peach-settings-actions">750              <button751                class="peach-btn peach-btn--subtle peach-btn--sm"752                onClick={() => void handleImport()}753                disabled={754                  importing() ||755                  preview()!.entries.length === 0 ||756                  (needsMasterPassword() && !masterPasswordReady())757                }758              >759                {importing()760                  ? "importing..."761                  : isOnboarding762                    ? `Create vault + import ${preview()!.entries.length}`763                    : mergeMode() === "replace"764                      ? awaitingReplaceConfirm()765                        ? "Yes, replace forever"766                        : `Replace vault with ${preview()!.entries.length}`767                      : `Import ${preview()!.entries.length}`}768              </button>769            </div>770          </div>771        </Show>772      </div>773    </>774  );775}776777// ---------------------------------------------------------------------------778// Shared headers779// ---------------------------------------------------------------------------780781function OverlayHeader(props: { title: string; onBack: () => void }) {782  return (783    <div class="peach-overlay-header">784      <button785        class="peach-btn peach-btn--ghost peach-btn--sm peach-icon-btn"786        onClick={props.onBack}787        aria-label="Back"788      >789        <svg width="7" height="12" viewBox="0 0 7 12" fill="none" stroke="currentColor" stroke-width="1.1" stroke-linecap="round" stroke-linejoin="round">790          <path d="M6 1L1 6L6 11" />791        </svg>792      </button>793      <span class="peach-overlay-title">{props.title}</span>794      <div class="peach-overlay-spacer"></div>795    </div>796  );797}798799function SubviewHeader(props: {800  title: string;801  onBack: () => void;802  mode: "existing" | "onboarding";803}) {804  // Onboarding sub-flows reuse the lock-screen header; existing-vault flows805  // use the standard overlay back-arrow header.806  return (807    <Show808      when={props.mode === "onboarding"}809      fallback={<OverlayHeader title={props.title} onBack={props.onBack} />}810    >811      <div class="peach-lock-view-header">812        <PeachWordmark class="peach-wordmark-wrap" />813        <button class="peach-lock-restore-link" onClick={props.onBack}>814          ‹ back815        </button>816      </div>817    </Show>818  );819}820821function getImportErrorCopy(error: string): string {822  // UI-7 / MV-5: oversized-import errors carry a variable detail after the823  // code, so match the prefix and never surface the raw string.824  if (error.startsWith("IMPORT_TOO_LARGE")) {825    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.";826  }827  switch (error) {828    case "UNSUPPORTED_IMPORT_FORMAT":829      return "Unrecognised file format. Use CSV, Bitwarden JSON, Proton Pass JSON/CSV, or a PeachScript backup.";830    case "INVALID_PASSPHRASE":831      return "Wrong backup password. This is the password you chose when you created the backup.";832    case "INVALID_PEACHSCRIPT_CHARACTER":833      return "This doesn't look like PeachScript. Make sure you copied the entire backup string.";834    case "PAYLOAD_TOO_SHORT":835      return "PeachScript looks truncated. Copy the full backup string and try again.";836    case "BAD_MAGIC":837    case "UNSUPPORTED_VERSION":838      return "This PeachScript was created by a different version of Peach.";839    case "CHECKSUM_FAILED":840      return "PeachScript appears corrupted. Re-copy from the source device.";841    case "CREATE_VAULT_FAILED":842      return "Peach couldn't create a new local vault before importing.";843    case "CLEAR_VAULT_FAILED":844      return "Peach couldn't clear the existing vault before replacing it.";845    case "MASTER_PASSWORD_REQUIRED":846      return "Choose a master password for your new vault first.";847    case "RESTORE_FAILED":848      return "Restore failed. Your existing vault is unchanged.";849    case "vault_locked":850      return "Peach is locked. Open Peach with your master password and try again.";851    case "refuse to replace with empty entry set":852      return "This PeachScript decoded to zero entries — refusing to wipe the vault.";853    case "NO_ENTRIES_IMPORTED":854      return "No importable password entries were found in that file.";855    case "PEACHSCRIPT_TOO_LARGE":856      return "That backup is too large.";857    default:858      // Never echo raw error strings — internal messages must not reach the UI.859      return "Import failed. Please try again.";860  }861}