1import { For, Match, Show, Switch, createMemo, createSignal, onCleanup, onMount } from "solid-js";2import { sendMessage } from "../App";3import { PeachMark, PeachWordmark } from "../components/PeachMark";4import { RecoveryWordEntryView } from "./RecoveryWordEntry";5import { RecoveryWordDisplayView } from "./RecoveryWordDisplay";6import { RuneBackground } from "../components/RuneBackground";7import { RuneCanvas } from "../components/RuneCanvas";8import { storageGet, storageRemove, storageSet } from "../../shared/storage";9import { isPeachScript, decodePeachScript } from "../../crypto/peachScript";10import { parsePayload } from "../../crypto/peachPayload";11import { parseImportSource } from "../../shared/import";12import { IMPORT_LIMITS } from "../../shared/import-limits";1314const peachMarkImg = new Image();15peachMarkImg.src = `data:image/svg+xml,${encodeURIComponent(16 '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 240 240" fill="none">' +17 '<path d="M 124 64 C 134 32 168 16 200 22 C 198 56 168 72 130 66 Z" fill="#92AC65"/>' +18 '<path d="M 130 64 C 152 46 178 30 196 24" stroke="#5E7A42" stroke-width="2.6" fill="none" stroke-linecap="round"/>' +19 '<path d="M 120 60 C 75 45 28 75 22 130 C 18 185 65 222 125 222 C 185 222 222 185 220 130 C 218 78 170 45 120 60 Z" fill="#FFB082"/>' +20 '<path d="M 120 60 C 75 45 28 75 22 130 C 18 185 65 222 125 222 C 105 195 75 150 100 90 C 105 75 112 65 120 60 Z" fill="#E5805C"/>' +21 '<ellipse cx="178" cy="108" rx="20" ry="11" fill="#FFD0A8" opacity="0.7" transform="rotate(-26 178 108)"/>' +22 '</svg>'23)}`;2425262728let _zxcvbn: ((password: string) => { score: number }) | null = null;29async function getZxcvbn() {30 if (_zxcvbn) return _zxcvbn;31 const [{ zxcvbn, zxcvbnOptions }, common, en] = await Promise.all([32 import("@zxcvbn-ts/core"),33 import("@zxcvbn-ts/language-common"),34 import("@zxcvbn-ts/language-en"),35 ]);36 zxcvbnOptions.setOptions({37 translations: en.translations,38 graphs: common.adjacencyGraphs,39 dictionary: { ...common.dictionary, ...en.dictionary },40 });41 _zxcvbn = (password: string) => zxcvbn(password);42 return _zxcvbn;43}4445interface LockProps {46 hasVault: boolean;47 ready: boolean;48 isPro?: boolean;49 505152 forceRecoveryWords?: boolean;53 onUnlock: () => void | Promise<void>;54 555657 onBackToOnboarding?: () => void;58 5960 onOpenCodexRestore?: () => void;61 62 initialRestore?: boolean;63 646566 initialRestoreSource?: RestoreSource;67}6869707172export const RESTORE_SOURCE_STORAGE_KEY = "peach_onboarding_restore_source";7374type RestoreSurface = "restore" | null;75type RecoverSurface = "words" | "new-password" | null;7677export function LockView(props: LockProps) {78 const [password, setPassword] = createSignal("");79 const [confirmPassword, setConfirmPassword] = createSignal("");80 const [error, setError] = createSignal("");81 const [loading, setLoading] = createSignal(false);82 const [restoreSurface, setRestoreSurface] = createSignal<RestoreSurface>(83 props.initialRestore ? "restore" : null,84 );85 const [showPassword, setShowPassword] = createSignal(false);86 const [recoverSurface, setRecoverSurface] = createSignal<RecoverSurface>(null);87 88 89 const [showRecoveryWords, setShowRecoveryWords] = createSignal(props.forceRecoveryWords ?? false);9091 const MIN_LENGTH = 12;92 const MIN_ZXCVBN_SCORE = 2;9394 const [strengthScore, setStrengthScore] = createSignal<number | null>(null);95 const [pinAvailable, setPinAvailable] = createSignal(false);96 const [usingPin, setUsingPin] = createSignal(false);97 const [pin, setPin] = createSignal("");9899 const canCreate = createMemo(100 () =>101 password().length >= MIN_LENGTH &&102 confirmPassword().length >= MIN_LENGTH &&103 password() === confirmPassword() &&104 strengthScore() !== null &&105 strengthScore()! >= MIN_ZXCVBN_SCORE106 );107108 const passwordStrength = createMemo(() => {109 const score = strengthScore();110 if (score === null) return null;111 if (score <= 1) return "weak";112 if (score === 2) return "fair";113 if (score === 3) return "good";114 return "strong";115 });116117 const createBlockerMessage = createMemo(() => {118 if (!password()) return null;119 if (password().length < MIN_LENGTH) return `need ${MIN_LENGTH - password().length} more characters`;120 if (!confirmPassword()) return "confirm your password";121 if (password() !== confirmPassword()) return "passwords don't match";122 if (strengthScore() === null) return "checking strength…";123 if (strengthScore()! < MIN_ZXCVBN_SCORE) return "password too weak — use a longer passphrase";124 return null;125 });126127 128 createMemo(() => {129 const value = password();130 if (!value) { setStrengthScore(null); return; }131 getZxcvbn().then((zxcvbn) => {132 if (password() === value) setStrengthScore(zxcvbn(value).score);133 }).catch(() => {134 135 if (password() === value) setStrengthScore(value.length >= 16 ? 3 : value.length >= 12 ? 2 : 1);136 });137 });138139 async function handleUnlock() {140 if (!password().trim()) return;141 setLoading(true);142 setError("");143 const response = await sendMessage({144 type: "UNLOCK",145 payload: { password: password() },146 });147 const result = response as { ok: boolean; error?: string };148 if (result.ok) {149 await props.onUnlock();150 setLoading(false);151 return;152 }153 setError(getDisplayError(result.error, "incorrect password"));154 setPassword("");155 const passwordField = document.querySelector(".lock-password-input") as HTMLInputElement | undefined;156 passwordField?.classList.add("shake");157 setTimeout(() => passwordField?.classList.remove("shake"), 300);158 setLoading(false);159 }160161 async function handlePinUnlock() {162 if (!/^\d{4,12}$/.test(pin())) return;163 setLoading(true);164 setError("");165 const response = await sendMessage({166 type: "UNLOCK_WITH_PIN",167 payload: { pin: pin() },168 });169 const result = response as { ok: boolean; error?: string };170 if (result.ok) {171 await props.onUnlock();172 setLoading(false);173 return;174 }175 if (result.error === "pin_attempts_exceeded") {176 setUsingPin(false);177 setError("too many incorrect PIN attempts — use your master password");178 } else if (result.error === "pin_session_expired") {179 setUsingPin(false);180 setError("PIN is unavailable until you unlock with your master password");181 } else {182 setError(getDisplayError(result.error, "incorrect PIN"));183 }184 setPin("");185 const pinField = document.querySelector(".lock-pin-input") as HTMLInputElement | undefined;186 pinField?.classList.add("shake");187 setTimeout(() => pinField?.classList.remove("shake"), 300);188 setLoading(false);189 }190191 async function checkPinAvailable(): Promise<void> {192 if (!props.hasVault) return;193 try {194 const response = await sendMessage({ type: "GET_PIN_STATUS" });195 const status = (response as {196 ok: boolean;197 data?: { configured?: boolean; available?: boolean; attemptsRemaining?: number; pinPreferred?: boolean };198 }).data;199 const enabled = status?.configured === true && status.available === true;200 setPinAvailable(enabled);201 if (enabled) {202 const settingsResponse = await sendMessage({ type: "GET_SETTINGS" });203 const settings = (settingsResponse as { ok: boolean; data?: { pinPreferred?: boolean } }).data;204 if (settings?.pinPreferred === true) setUsingPin(true);205 }206 } catch { }207 }208209 onMount(() => {210 void checkPinAvailable();211 });212213 async function handleCreate() {214 if (!password().trim()) return;215 if (password().length < MIN_LENGTH) {216 setError(`password must be at least ${MIN_LENGTH} characters`);217 return;218 }219 if (password() !== confirmPassword()) {220 setError("passwords do not match");221 return;222 }223 const score = strengthScore();224 if (score === null || score < MIN_ZXCVBN_SCORE) {225 setError("password is too weak — use a longer passphrase");226 return;227 }228 setLoading(true);229 setError("");230 const response = await sendMessage({231 type: "CREATE_VAULT",232 payload: { password: password() },233 });234 const result = response as { ok: boolean; error?: string; data?: { unlocked?: boolean } };235 if (result.ok && result.data?.unlocked === false) {236 setError(getDisplayError("vault_created_locked", ""));237 setLoading(false);238 return;239 }240 if (result.ok) {241 242 243 244 await sendMessage({ type: "SET_RECOVERY_CONFIRM_PENDING" });245 setShowRecoveryWords(true);246 setLoading(false);247 return;248 }249 setError(getDisplayError(result.error, "failed to create vault"));250 setLoading(false);251 }252253 254 return (255 <Switch>256 {}257 <Match when={restoreSurface() === "restore"}>258 <RestoreView259 hasVault={props.hasVault}260 onOpenCodexRestore={props.onOpenCodexRestore}261 initialSource={props.initialRestoreSource}262 onBack={() => {263 264 265 if (props.onBackToOnboarding) props.onBackToOnboarding();266 else setRestoreSurface(null);267 }}268 onUnlock={async () => {269 setRestoreSurface(null);270 await props.onUnlock();271 }}272 />273 </Match>274275 {}276 {277278}279 <Match280 when={281 (showRecoveryWords() || props.forceRecoveryWords) &&282 (!props.hasVault || props.forceRecoveryWords)283 }284 >285 <RecoveryWordDisplayView286 onDone={props.onUnlock}287 />288 </Match>289290 {}291 <Match when={recoverSurface() === "words"}>292 <RecoveryWordEntryView293 onCancel={() => setRecoverSurface(null)}294 onRecoveryComplete={props.onUnlock}295 />296 </Match>297298 {}299 <Match when={props.hasVault}>300 <section class="peach-screen peach-theme lock-screen lock-screen--vault-stage" data-motion-phase="enter">301 <RuneBackground opacity={0.07} />302303 <header class="peach-screen-header lock-screen-header">304 <div class="peach-wordmark-stack">305 <PeachWordmark class="peach-wordmark-wrap" />306 <Show when={props.isPro}>307 <span class="peach-pro-mini-badge">pro</span>308 </Show>309 </div>310 </header>311312 <div class="peach-lock-hero peach-lock-hero--unlock">313 <PeachMark class="peach-lock-mark" />314 <span class="peach-lock-eyebrow">vault locked</span>315 <h1 class="peach-onboarding-headline peach-lock-headline--unlock">316 unlock317 <br />318 your vault.319 </h1>320 </div>321322 <section class="peach-lock-panel peach-lock-panel--unlock peach-glass">323 <Show when={usingPin()} fallback={324 <>325 <label class="peach-label" for="unlock-password">326 master password327 </label>328 <input329 id="unlock-password"330 class="peach-underline-input peach-unlock-input lock-password-input"331 type="password"332 placeholder="••••••••••••"333 autocomplete="current-password"334 value={password()}335 disabled={!props.ready}336 ref={(el) => { if (props.ready) setTimeout(() => el.focus(), 80); }}337 onInput={(event) => setPassword((event.target as HTMLInputElement).value)}338 onKeyDown={(event) => {339 if (event.key !== "Enter" || !props.ready) return;340 void handleUnlock();341 }}342 />343 </>344 }>345 <label class="peach-label" for="unlock-pin">346 PIN347 </label>348 <input349 id="unlock-pin"350 class="peach-underline-input peach-unlock-input lock-pin-input"351 type="password"352 inputmode="numeric"353 maxlength="12"354 placeholder="••••••••••••"355 autocomplete="off"356 value={pin()}357 disabled={!props.ready}358 ref={(el) => { if (props.ready) setTimeout(() => el.focus(), 80); }}359 onInput={(event) => setPin((event.target as HTMLInputElement).value.replace(/\D/g, "").slice(0, 12))}360 onKeyDown={(event) => {361 if (event.key !== "Enter" || !props.ready) return;362 void handlePinUnlock();363 }}364 />365 <button366 class="peach-lock-recover-link"367 type="button"368 onClick={() => { setUsingPin(false); setError(""); }}369 >370 use master password371 </button>372 </Show>373374 <Show when={error()}>375 <p class="peach-hint peach-hint-error">{error()}</p>376 </Show>377378 <button379 class="peach-btn peach-btn--accent peach-btn--md peach-lock-submit"380 onClick={() => void (usingPin() ? handlePinUnlock() : handleUnlock())}381 disabled={!props.ready || loading()}382 >383 {loading() ? "unlocking..." : usingPin() ? "unlock with PIN" : "unlock"}384 </button>385386 <Show when={!usingPin() && pinAvailable()}>387 <button388 class="peach-lock-recover-link"389 type="button"390 onClick={() => { setUsingPin(true); setError(""); }}391 >392 use PIN393 </button>394 </Show>395396 <button397 class="peach-lock-recover-link"398 type="button"399 onClick={() => setRecoverSurface("words")}400 >401 forgot your password?402 </button>403 </section>404 </section>405 </Match>406407 {}408 <Match when={true}>409 <section410 class="peach-screen peach-theme lock-screen lock-screen--vault-stage peach-newvault"411 data-motion-phase="enter"412 >413 <header class="peach-screen-header peach-newvault-header">414 <div class="peach-wordmark-stack">415 <PeachWordmark class="peach-wordmark-wrap" />416 <Show when={props.isPro}>417 <span class="peach-pro-mini-badge">pro</span>418 </Show>419 </div>420 <Show when={props.onBackToOnboarding}>421 <button422 class="peach-newvault-back"423 type="button"424 onClick={() => props.onBackToOnboarding?.()}425 aria-label="Back to onboarding"426 >427 <svg width="11" height="11" viewBox="0 0 11 11" fill="none" stroke="currentColor" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round">428 <path d="M7 2L3 5.5L7 9" />429 </svg>430 back431 </button>432 </Show>433 </header>434435 <div class="peach-newvault-mark" aria-hidden="true">436 <PeachMark class="peach-newvault-mark-art" />437 </div>438439 <div class="peach-newvault-card">440 <h1 class="peach-newvault-headline">{"keep your\nsecrets."}</h1>441 <hr class="peach-newvault-divider" />442443 <div class="peach-newvault-field">444 <div class="peach-newvault-label-row">445 <label class="peach-label" for="master-password">446 master password447 </label>448 <button449 class="peach-lock-reveal-btn"450 type="button"451 onClick={() => setShowPassword((value) => !value)}452 aria-label={showPassword() ? "Hide password" : "Show password"}453 >454 <Show455 when={showPassword()}456 fallback={457 <svg width="15" height="10" viewBox="0 0 14 10" fill="none" stroke="currentColor" stroke-width="0.9" stroke-linecap="round">458 <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" />459 <circle cx="7" cy="5" r="1.75" />460 </svg>461 }462 >463 <svg width="15" height="10" viewBox="0 0 14 10" fill="none" stroke="currentColor" stroke-width="0.9" stroke-linecap="round">464 <path d="M1 2C3 4.5 5 6 7 6C9 6 11 4.5 13 2" />465 <path d="M3.5 5.5L2.5 7.5" />466 <path d="M7 6.5V8.5" />467 <path d="M10.5 5.5L11.5 7.5" />468 </svg>469 </Show>470 {showPassword() ? "hide" : "show"}471 </button>472 </div>473 <input474 id="master-password"475 class="peach-underline-input peach-newvault-input lock-password-input"476 type={showPassword() ? "text" : "password"}477 placeholder="••••••••••••"478 autocomplete="new-password"479 value={password()}480 disabled={!props.ready}481 onInput={(event) => setPassword((event.target as HTMLInputElement).value)}482 onKeyDown={(event) => {483 if (event.key !== "Enter" || !props.ready) return;484 void handleCreate();485 }}486 />487 <Show488 when={password().length > 0 && passwordStrength() !== null}489 fallback={490 <p class="peach-newvault-hint">491 At least 12 characters.492 </p>493 }494 >495 <div class="peach-password-strength">496 <div class={`peach-strength-bar peach-strength-bar--${passwordStrength()}`}>497 <div class="peach-strength-fill"></div>498 </div>499 <span class="peach-strength-label">{passwordStrength()}</span>500 </div>501 </Show>502 </div>503504 <div class="peach-newvault-field">505 <label class="peach-label" for="confirm-password">506 confirm password507 </label>508 <input509 id="confirm-password"510 class="peach-underline-input peach-newvault-input"511 type={showPassword() ? "text" : "password"}512 placeholder="••••••••••••"513 autocomplete="new-password"514 value={confirmPassword()}515 disabled={!props.ready}516 onInput={(event) => setConfirmPassword((event.target as HTMLInputElement).value)}517 onKeyDown={(event) => {518 if (event.key === "Enter" && props.ready) void handleCreate();519 }}520 />521 </div>522523 <Show when={error()}>524 <p class="peach-hint peach-hint-error">{error()}</p>525 </Show>526527 <button528 class="peach-btn peach-btn--accent peach-btn--md peach-lock-submit peach-newvault-submit"529 onClick={() => void handleCreate()}530 disabled={!props.ready || loading() || !canCreate()}531 aria-live="polite"532 >533 <Show534 when={!canCreate() && createBlockerMessage()}535 fallback={loading() ? "creating..." : "create vault"}536 >537 {createBlockerMessage()}538 </Show>539 </button>540541 <p class="peach-newvault-warning">542 <span class="peach-newvault-warning-icon" aria-hidden="true">⚠</span>543 <span>Save your 12 recovery words after creating — they're the only way back in if you forget your password.</span>544 </p>545 </div>546 </section>547 </Match>548 </Switch>549 );550}551552553554export type RestoreSource = "symbols" | "codex" | "csv";555556const RESTORE_SOURCES: { id: RestoreSource; name: string; detail: string }[] = [557 { id: "symbols", name: "PeachScript", detail: "Paste the rune string, or open a .peach file." },558 { id: "codex", name: "Codex", detail: "Scan printed pages, or import the PDF." },559 { id: "csv", name: "CSV", detail: "A .csv or .json file from another password manager." },560];561562const RESTORE_DEEP_LINKS: Record<"symbols" | "csv", "peachscript" | "csv"> = {563 symbols: "peachscript",564 csv: "csv",565};566567568569570571572573574575async function detachForFilePicker(route: "peachscript" | "csv"): Promise<boolean> {576 try {577 578 if (new URLSearchParams(window.location.search).get("restore")) return false;579 } catch { }580 if (typeof chrome === "undefined" || typeof chrome.runtime?.sendMessage !== "function") {581 return false;582 }583 try {584 const res = (await sendMessage({585 type: "OPEN_DETACHED_POPUP",586 payload: { route },587 })) as { ok: boolean; data?: { detached?: boolean } };588 if (!res?.data?.detached) return false;589 590 591 return true;592 } catch {593 return false;594 }595}596597598599function restoreDeepLinkActive(link: "peachscript" | "csv"): boolean {600 try {601 return new URLSearchParams(window.location.search).get("restore") === link;602 } catch {603 return false;604 }605}606607function RestoreView(props: {608 hasVault: boolean;609 onOpenCodexRestore?: () => void;610 onBack: () => void;611 onUnlock: () => void | Promise<void>;612 initialSource?: RestoreSource;613}) {614 const [source, setSource] = createSignal<RestoreSource | null>(props.initialSource ?? null);615 const [showIntro, setShowIntro] = createSignal(false);616 const [pendingUnlock] = createSignal(false);617618 619 620 621 622 function chooseSource(next: RestoreSource | null) {623 setSource(next);624 if (next) void storageSet(RESTORE_SOURCE_STORAGE_KEY, next).catch(() => {});625 else void storageRemove(RESTORE_SOURCE_STORAGE_KEY).catch(() => {});626 }627628 async function handleRestoreSuccess() {629 const seen = await storageGet("peach_shown_restore_intro").catch(() => null);630 if (!seen) {631 setShowIntro(true);632 } else {633 await props.onUnlock();634 }635 }636637 async function dismissIntro() {638 await storageSet("peach_shown_restore_intro", "true").catch(() => {});639 setShowIntro(false);640 await props.onUnlock();641 }642643 return (644 <section645 class="peach-screen peach-theme lock-screen lock-screen--vault-stage peach-newvault peach-restore"646 data-motion-phase="enter"647 >648 <RuneBackground opacity={0.05} />649650 <header class="peach-screen-header peach-newvault-header">651 <PeachWordmark class="peach-wordmark-wrap" />652 <button653 class="peach-newvault-back peach-restore-back"654 type="button"655 onClick={props.onBack}656 aria-label="Back to onboarding"657 >658 <svg width="11" height="11" viewBox="0 0 11 11" fill="none" stroke="currentColor" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">659 <path d="M7 2L3 5.5L7 9" />660 </svg>661 back662 </button>663 </header>664665 <div class="peach-newvault-card peach-restore-card">666 <Show667 when={source()}668 keyed669 fallback={670 <>671 <h1 class="peach-newvault-headline">{"welcome\nback."}</h1>672 <hr class="peach-newvault-divider" />673 <div class="peach-restore-sources">674 <For each={RESTORE_SOURCES}>675 {(entry) => (676 <button677 type="button"678 class="peach-onboarding-choice peach-restore-source"679 onClick={() => chooseSource(entry.id)}680 >681 <span class="peach-onboarding-choice-label">{entry.name}</span>682 <span class="peach-onboarding-choice-detail">{entry.detail}</span>683 </button>684 )}685 </For>686 </div>687 </>688 }689 >690 {(active) => (691 <>692 <div class="peach-restore-source-head">693 <h2 class="peach-restore-source-title">694 {RESTORE_SOURCES.find((entry) => entry.id === active)?.name}695 </h2>696 <button697 type="button"698 class="peach-restore-picker-back"699 onClick={() => chooseSource(null)}700 >701 ‹ sources702 </button>703 </div>704 <hr class="peach-newvault-divider" />705 <Show when={active === "symbols"}>706 <RestoreSymbols hasVault={props.hasVault} onSuccess={handleRestoreSuccess} />707 </Show>708 <Show when={active === "codex"}>709 <RestoreCodex onOpen={() => props.onOpenCodexRestore?.()} />710 </Show>711 <Show when={active === "csv"}>712 <RestoreCSV hasVault={props.hasVault} onSuccess={handleRestoreSuccess} />713 </Show>714 </>715 )}716 </Show>717 </div>718719 {}720 <Show when={showIntro()}>721 <div class="peach-restore-intro-overlay">722 <div class="peach-restore-intro-card">723 <p class="peach-restore-intro-headline">welcome to peach.</p>724 <div class="peach-restore-intro-body">725 <p>Your vault lives only on this device. No server has a copy.</p>726 <p>The inline bubble fills passwords automatically when you visit sites.</p>727 <p>Export your vault from Settings before switching devices.</p>728 </div>729 <button730 class="peach-btn peach-btn--accent peach-btn--md peach-restore-intro-btn"731 onClick={() => void dismissIntro()}732 disabled={pendingUnlock()}733 >734 got it735 </button>736 </div>737 </div>738 </Show>739 </section>740 );741}742743744745function RestoreCodex(props: { onOpen: () => void }) {746 return (747 <div class="peach-restore-form">748 <p class="peach-restore-codex-copy">749 Scan printed Codex pages or import the Codex PDF. Codex restore is750 always available, even before you create a vault.751 </p>752 <button753 type="button"754 class="peach-btn peach-btn--accent peach-btn--md peach-restore-submit"755 onClick={props.onOpen}756 >757 open Codex restore758 </button>759 </div>760 );761}762763764765function RestoreSymbols(props: {766 hasVault: boolean;767 onSuccess: () => void | Promise<void>;768}) {769 const [scriptInput, setScriptInput] = createSignal("");770 const [backupPass, setBackupPass] = createSignal("");771 const [working, setWorking] = createSignal(false);772 const [animating, setAnimating] = createSignal<"chaos" | "snap" | "bloom" | null>(null);773 const [error, setError] = createSignal<string | null>(null);774 let canvasRef: HTMLCanvasElement | undefined;775 let peachFileRef: HTMLInputElement | undefined;776 let animFrameId = 0;777 let runes: { x: number; y: number; vx: number; vy: number; char: string; size: number; angle: number; va: number }[] = [];778779 const scriptValid = createMemo(() => isPeachScript(scriptInput()));780781 function stopAnim() {782 cancelAnimationFrame(animFrameId);783 animFrameId = 0;784 }785786 function startChaos(canvas: HTMLCanvasElement) {787 const ctx = canvas.getContext("2d")!;788 const W = canvas.width;789 const H = canvas.height;790 const RUNE_CHARS = Array.from({ length: 40 }, (_, i) =>791 String.fromCodePoint(0xe000 + i)792 );793 if (runes.length === 0) {794 runes = Array.from({ length: 60 }, () => ({795 x: Math.random() * W,796 y: Math.random() * H,797 vx: (Math.random() - 0.5) * 3,798 vy: (Math.random() - 0.5) * 3,799 char: RUNE_CHARS[Math.floor(Math.random() * RUNE_CHARS.length)]!,800 size: 14 + Math.random() * 20,801 angle: Math.random() * Math.PI * 2,802 va: (Math.random() - 0.5) * 0.1,803 }));804 }805806 function draw() {807 ctx.clearRect(0, 0, W, H);808 for (const r of runes) {809 r.x = (r.x + r.vx + W) % W;810 r.y = (r.y + r.vy + H) % H;811 r.angle += r.va;812 ctx.save();813 ctx.translate(r.x, r.y);814 ctx.rotate(r.angle);815 ctx.font = `${r.size}px PeachScript, monospace`;816 const alpha = 0.5 + 0.5 * Math.sin(Date.now() / 400 + r.x);817 ctx.fillStyle = `rgba(232, 149, 109, ${alpha})`;818 ctx.shadowColor = "rgba(232, 149, 109, 0.7)";819 ctx.shadowBlur = 8;820 ctx.fillText(r.char, 0, 0);821 ctx.restore();822 }823 animFrameId = requestAnimationFrame(draw);824 }825 draw();826 }827828 function snapToGrid(canvas: HTMLCanvasElement, onDone: () => void) {829 stopAnim();830 const ctx = canvas.getContext("2d")!;831 const W = canvas.width;832 const H = canvas.height;833 const cols = 8;834 const rows = 6;835 const cellW = W / cols;836 const cellH = H / rows;837 const targets = runes.slice(0, cols * rows).map((_, i) => ({838 x: (i % cols) * cellW + cellW / 2,839 y: Math.floor(i / cols) * cellH + cellH / 2,840 }));841 const start = performance.now();842 const DURATION = 400;843844 function drawSnap(now: number) {845 const t = Math.min((now - start) / DURATION, 1);846 const ease = t < 1 ? 1 - (1 - t) ** 3 : 1;847 ctx.clearRect(0, 0, W, H);848 runes.slice(0, targets.length).forEach((r, i) => {849 const tx = targets[i]!.x;850 const ty = targets[i]!.y;851 const cx = r.x + (tx - r.x) * ease;852 const cy = r.y + (ty - r.y) * ease;853 ctx.font = `16px PeachScript, monospace`;854 ctx.fillStyle = `rgba(232, 149, 109, ${0.8 * ease})`;855 ctx.shadowColor = "rgba(232, 149, 109, 0.6)";856 ctx.shadowBlur = 6;857 ctx.fillText(r.char, cx - 8, cy + 8);858 });859 if (t < 1) {860 animFrameId = requestAnimationFrame(drawSnap);861 } else {862 onDone();863 }864 }865 animFrameId = requestAnimationFrame(drawSnap);866 }867868 function bloom(canvas: HTMLCanvasElement, onDone: () => void) {869 stopAnim();870 const ctx = canvas.getContext("2d")!;871 const W = canvas.width;872 const H = canvas.height;873 const start = performance.now();874 const DURATION = 900;875876 function drawBloom(now: number) {877 const t = Math.min((now - start) / DURATION, 1);878 ctx.clearRect(0, 0, W, H);879 880 const runeAlpha = 1 - Math.min(t / 0.4, 1);881 if (runeAlpha > 0) {882 for (const r of runes.slice(0, 48)) {883 ctx.font = `16px PeachScript, monospace`;884 ctx.fillStyle = `rgba(232, 149, 109, ${runeAlpha * 0.8})`;885 ctx.fillText(r.char, r.x - 8, r.y + 8);886 }887 }888 889 const markT = Math.max(0, (t - 0.2) / 0.5);890 const markScale = Math.min(markT * 1.2, 1);891 const markAlpha = markT < 0.5 ? markT * 2 : 2 - markT * 2;892 if (markAlpha > 0) {893 ctx.save();894 ctx.globalAlpha = markAlpha;895 ctx.shadowColor = `rgba(217, 104, 48, ${markAlpha * 0.8})`;896 ctx.shadowBlur = 30;897 ctx.translate(W / 2, H / 2);898 ctx.scale(markScale, markScale);899 ctx.drawImage(peachMarkImg, -32, -32, 64, 64);900 ctx.restore();901 }902 if (t < 1) {903 animFrameId = requestAnimationFrame(drawBloom);904 } else {905 onDone();906 }907 }908 animFrameId = requestAnimationFrame(drawBloom);909 }910911 onCleanup(() => stopAnim());912913 914 915 onMount(() => {916 if (restoreDeepLinkActive(RESTORE_DEEP_LINKS.symbols)) {917 setTimeout(() => peachFileRef?.click(), 50);918 }919 });920921 922 923 const [dragDepth, setDragDepth] = createSignal(0);924925 async function handleDrop(e: DragEvent) {926 e.preventDefault();927 setDragDepth(0);928 if (working() || animating() !== null) return;929 const file = e.dataTransfer?.files?.[0];930 if (!file) return;931 932 933 if (file.size > IMPORT_LIMITS.MAX_JSON_BYTES) {934 setError("That file is too large.");935 return;936 }937 try {938 setScriptInput(await file.text());939 setError(null);940 } catch {941 setError("Couldn't read file.");942 }943 }944945 async function handleRestore() {946 if (!scriptValid() || !backupPass().trim() || working()) return;947 setError(null);948 setWorking(true);949 setAnimating("chaos");950951 const canvas = canvasRef;952 if (canvas) startChaos(canvas);953954 try {955 956 957 const bytes = decodePeachScript(scriptInput());958 const payload = await parsePayload(bytes, backupPass());959960 if (!props.hasVault) {961 const cr = await sendMessage({ type: "CREATE_VAULT", payload: { password: backupPass() } });962 if (!(cr as { ok: boolean }).ok) throw new Error("CREATE_VAULT_FAILED");963 if ((cr.data as { unlocked?: boolean } | undefined)?.unlocked === false) throw new Error("vault_created_locked");964 }965966 const rr = await sendMessage({967 type: "RESTORE_ENTRIES",968 payload: { entries: payload.entries, mode: "merge", settings: payload.settings },969 });970 if (!(rr as { ok: boolean }).ok) throw new Error((rr as { error?: string }).error ?? "RESTORE_FAILED");971972 if (payload.license?.key) {973 await sendMessage({ type: "ACTIVATE_LICENSE", payload: { key: payload.license.key } }).catch(() => {});974 }975976 setAnimating("snap");977 stopAnim();978 if (canvas) {979 snapToGrid(canvas, () => {980 setAnimating("bloom");981 bloom(canvas, async () => {982 setAnimating(null);983 await props.onSuccess();984 });985 });986 } else {987 await props.onSuccess();988 }989 } catch (err) {990 stopAnim();991 setAnimating(null);992 const code = err instanceof Error ? err.message : String(err);993 setError(994 code === "INVALID_PASSPHRASE"995 ? "That passphrase didn't work."996 : code === "vault_created_locked"997 ? getDisplayError(code, "")998 : code === "CREATE_VAULT_FAILED"999 ? "Couldn't create a new local vault."1000 : "Could not read this backup.",1001 );1002 } finally {1003 setWorking(false);1004 }1005 }10061007 return (1008 <div1009 class="peach-restore-form"1010 classList={{ "is-dragover": dragDepth() > 0 }}1011 onDragEnter={(e) => { e.preventDefault(); setDragDepth((d) => d + 1); }}1012 onDragOver={(e) => e.preventDefault()}1013 onDragLeave={() => setDragDepth((d) => Math.max(0, d - 1))}1014 onDrop={(e) => void handleDrop(e)}1015 >1016 <Show when={animating() !== null}>1017 <canvas1018 ref={(el) => { canvasRef = el; }}1019 class="peach-restore-anim-canvas"1020 width={280}1021 height={200}1022 />1023 </Show>1024 <Show when={animating() === null}>1025 <Show1026 when={scriptValid()}1027 fallback={1028 <>1029 <textarea1030 class="peach-restore-script"1031 placeholder="paste peachscript…"1032 rows={3}1033 aria-label="Paste your PeachScript backup"1034 value={scriptInput()}1035 onInput={(e) => setScriptInput((e.target as HTMLTextAreaElement).value)}1036 />1037 <div class="peach-restore-or" aria-hidden="true">or</div>1038 <label1039 class="peach-btn peach-btn--ghost peach-btn--sm peach-restore-file-btn"1040 onClick={(e) => {1041 if (restoreDeepLinkActive(RESTORE_DEEP_LINKS.symbols)) return;1042 e.preventDefault();1043 void detachForFilePicker(RESTORE_DEEP_LINKS.symbols).then((detached) => {1044 if (!detached) peachFileRef?.click();1045 });1046 }}1047 >1048 open .peach file1049 <input1050 ref={(el) => { peachFileRef = el; }}1051 type="file"1052 accept=".peach,text/plain"1053 style="display:none"1054 onChange={async (e) => {1055 const file = (e.currentTarget as HTMLInputElement).files?.[0];1056 if (!file) return;1057 1058 if (file.size > IMPORT_LIMITS.MAX_JSON_BYTES) {1059 setError("That file is too large.");1060 (e.currentTarget as HTMLInputElement).value = "";1061 return;1062 }1063 try {1064 setScriptInput(await file.text());1065 } catch {1066 setError("Couldn't read file.");1067 } finally {1068 (e.currentTarget as HTMLInputElement).value = "";1069 }1070 }}1071 />1072 </label>1073 <p class="peach-restore-drop-hint">or drop the file anywhere here</p>1074 </>1075 }1076 >1077 <div class="peach-restore-rune-preview">1078 <RuneCanvas runeString={scriptInput()} width={256} height={120} />1079 </div>1080 <button1081 type="button"1082 class="peach-restore-picker-back"1083 onClick={() => { setScriptInput(""); setError(null); }}1084 >1085 ‹ paste again1086 </button>1087 </Show>1088 <div class="peach-newvault-field">1089 <label class="peach-label" for="restore-backup-pass">1090 backup password1091 </label>1092 <input1093 id="restore-backup-pass"1094 class="peach-underline-input peach-newvault-input"1095 type="password"1096 placeholder="••••••••••••"1097 autocomplete="current-password"1098 value={backupPass()}1099 onInput={(e) => setBackupPass((e.target as HTMLInputElement).value)}1100 onKeyDown={(e) => {1101 if (e.key === "Enter" && scriptValid() && backupPass().trim() && !working()) {1102 e.preventDefault();1103 void handleRestore();1104 }1105 }}1106 />1107 </div>1108 <button1109 class="peach-btn peach-btn--accent peach-btn--md peach-restore-submit"1110 onClick={() => void handleRestore()}1111 disabled={!scriptValid() || !backupPass().trim() || working()}1112 >1113 restore vault1114 </button>1115 <Show when={error()}>1116 <p class="peach-hint peach-hint-error">{error()}</p>1117 </Show>1118 </Show>1119 </div>1120 );1121}1122112311241125function RestoreCSV(props: {1126 hasVault: boolean;1127 onSuccess: () => void | Promise<void>;1128}) {1129 const [importing, setImporting] = createSignal(false);1130 const [error, setError] = createSignal<string | null>(null);1131 1132 1133 1134 1135 const CSV_MIN_PASSWORD_LENGTH = 12;1136 const [newPass, setNewPass] = createSignal("");1137 const [confirmPass, setConfirmPass] = createSignal("");1138 const needsPassword = () => props.hasVault === false;1139 const passwordReady = () =>1140 !needsPassword() ||1141 (newPass().length >= CSV_MIN_PASSWORD_LENGTH && newPass() === confirmPass());1142 1143 1144 const [dragDepth, setDragDepth] = createSignal(0);11451146 1147 1148 1149 async function processFile(file: File) {1150 if (file.size > IMPORT_LIMITS.MAX_JSON_BYTES) {1151 setError("That file is too large.");1152 return;1153 }1154 setImporting(true);1155 setError(null);1156 try {1157 const text = await file.text();1158 const parsed = await parseImportSource(text);1159 if (parsed.entries.length === 0) throw new Error("NO_ENTRIES");11601161 if (props.hasVault === false) {1162 1163 1164 const cr = await sendMessage({ type: "CREATE_VAULT", payload: { password: newPass() } });1165 if (!(cr as { ok: boolean }).ok) throw new Error("CREATE_VAULT_FAILED");1166 if ((cr.data as { unlocked?: boolean } | undefined)?.unlocked === false) throw new Error("vault_created_locked");1167 }11681169 const res = await sendMessage({ type: "BATCH_ADD_ENTRIES", payload: { entries: parsed.entries } });1170 if (!(res as { ok: boolean }).ok) throw new Error("IMPORT_FAILED");1171 await props.onSuccess();1172 } catch (err) {1173 const code = err instanceof Error ? err.message : String(err);1174 setError(1175 code === "NO_ENTRIES" ? "No entries found in this file." :1176 code === "vault_created_locked" ? getDisplayError(code, "") :1177 code === "CREATE_VAULT_FAILED" ? "Couldn't create a new local vault." :1178 "Import failed. Check the file format and try again."1179 );1180 } finally {1181 setImporting(false);1182 }1183 }11841185 let csvFileRef: HTMLInputElement | undefined;11861187 onMount(() => {1188 1189 1190 1191 if (restoreDeepLinkActive(RESTORE_DEEP_LINKS.csv) && !needsPassword()) {1192 setTimeout(() => csvFileRef?.click(), 50);1193 }1194 });11951196 function gatePassword(): boolean {1197 if (importing()) return false;1198 if (needsPassword() && newPass().length < CSV_MIN_PASSWORD_LENGTH) {1199 setError(`Set a master password of at least ${CSV_MIN_PASSWORD_LENGTH} characters first.`);1200 return false;1201 }1202 if (needsPassword() && newPass() !== confirmPass()) {1203 setError("Passwords do not match.");1204 return false;1205 }1206 return true;1207 }12081209 async function handleFile(e: Event) {1210 const input = e.currentTarget as HTMLInputElement;1211 const file = input.files?.[0];1212 input.value = "";1213 if (!file) return;1214 await processFile(file);1215 }12161217 async function handleDrop(e: DragEvent) {1218 e.preventDefault();1219 setDragDepth(0);1220 if (!gatePassword()) return;1221 const file = e.dataTransfer?.files?.[0];1222 if (!file) return;1223 await processFile(file);1224 }12251226 return (1227 <div1228 class="peach-restore-form"1229 classList={{ "is-dragover": dragDepth() > 0 }}1230 onDragEnter={(e) => { e.preventDefault(); setDragDepth((d) => d + 1); }}1231 onDragOver={(e) => e.preventDefault()}1232 onDragLeave={() => setDragDepth((d) => Math.max(0, d - 1))}1233 onDrop={(e) => void handleDrop(e)}1234 >1235 <Show when={needsPassword()}>1236 <div class="peach-newvault-field">1237 <label class="peach-label" for="restore-csv-pass">1238 new master password1239 </label>1240 <input1241 id="restore-csv-pass"1242 class="peach-underline-input peach-newvault-input"1243 type="password"1244 placeholder="••••••••••••"1245 autocomplete="new-password"1246 value={newPass()}1247 onInput={(e) => setNewPass((e.target as HTMLInputElement).value)}1248 />1249 </div>1250 <div class="peach-newvault-field">1251 <label class="peach-label" for="restore-csv-confirm">1252 confirm master password1253 </label>1254 <input1255 id="restore-csv-confirm"1256 class="peach-underline-input peach-newvault-input"1257 type="password"1258 placeholder="••••••••••••"1259 autocomplete="new-password"1260 value={confirmPass()}1261 onInput={(e) => setConfirmPass((e.target as HTMLInputElement).value)}1262 />1263 </div>1264 </Show>1265 <label1266 class="peach-btn peach-btn--accent peach-btn--md peach-restore-file-btn"1267 onClick={(e) => {1268 1269 1270 1271 if (restoreDeepLinkActive(RESTORE_DEEP_LINKS.csv)) return;1272 1273 1274 e.preventDefault();1275 if (!gatePassword()) return;1276 void detachForFilePicker(RESTORE_DEEP_LINKS.csv).then((detached) => {1277 if (!detached) csvFileRef?.click();1278 });1279 }}1280 >1281 {importing() ? "importing…" : "open csv file"}1282 <input1283 ref={(el) => { csvFileRef = el; }}1284 type="file"1285 accept=".csv,.json,.peach,application/x-peach"1286 style="display:none"1287 onChange={handleFile}1288 disabled={importing() || !passwordReady()}1289 />1290 </label>1291 <p class="peach-restore-drop-hint">or drop the file anywhere here</p>1292 <p class="peach-hint peach-restore-csv-sources">1293 Imports from Bitwarden, 1Password, Proton Pass,1294 <br />1295 Chrome, Safari, and Edge.1296 </p>1297 <p class="peach-newvault-warning">1298 <span class="peach-newvault-warning-icon" aria-hidden="true">⚠</span>1299 <span>Plain-text file — delete it after the import.</span>1300 </p>1301 <Show when={error()}>1302 <p class="peach-hint peach-hint-error">{error()}</p>1303 </Show>1304 </div>1305 );1306}1307130813091310function getDisplayError(error: string | undefined, fallback: string): string {1311 if (!error) return fallback;1312 if (error === "vault_created_locked") return "Your new vault and password were saved. Reopen Peach and unlock it with your new password.";1313 if (1314 error === "SERVICE_WORKER_UNAVAILABLE" ||1315 error.includes("Receiving end does not exist") ||1316 error.includes("message port closed")1317 ) {1318 return "background service unavailable";1319 }1320 1321 return fallback;1322}