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(), purpose: "onboarding" },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 setShowRecoveryWords(true);242 setLoading(false);243 return;244 }245 setError(getDisplayError(result.error, "failed to create vault"));246 setLoading(false);247 }248249 250 return (251 <Switch>252 {}253 <Match when={restoreSurface() === "restore"}>254 <RestoreView255 hasVault={props.hasVault}256 onOpenCodexRestore={props.onOpenCodexRestore}257 initialSource={props.initialRestoreSource}258 onBack={() => {259 260 261 if (props.onBackToOnboarding) props.onBackToOnboarding();262 else setRestoreSurface(null);263 }}264 onUnlock={async () => {265 setRestoreSurface(null);266 await props.onUnlock();267 }}268 />269 </Match>270271 {}272 {273274}275 <Match276 when={277 (showRecoveryWords() || props.forceRecoveryWords) &&278 (!props.hasVault || props.forceRecoveryWords)279 }280 >281 <RecoveryWordDisplayView282 onDone={props.onUnlock}283 />284 </Match>285286 {}287 <Match when={recoverSurface() === "words"}>288 <RecoveryWordEntryView289 onCancel={() => setRecoverSurface(null)}290 onRecoveryComplete={props.onUnlock}291 />292 </Match>293294 {}295 <Match when={props.hasVault}>296 <section class="peach-screen peach-theme lock-screen lock-screen--vault-stage" data-motion-phase="enter">297 <RuneBackground opacity={0.07} />298299 <header class="peach-screen-header lock-screen-header">300 <div class="peach-wordmark-stack">301 <PeachWordmark class="peach-wordmark-wrap" />302 <Show when={props.isPro}>303 <span class="peach-pro-mini-badge">pro</span>304 </Show>305 </div>306 </header>307308 <div class="peach-lock-hero peach-lock-hero--unlock">309 <PeachMark class="peach-lock-mark" />310 <span class="peach-lock-eyebrow">vault locked</span>311 <h1 class="peach-onboarding-headline peach-lock-headline--unlock">312 unlock313 <br />314 your vault.315 </h1>316 </div>317318 <section class="peach-lock-panel peach-lock-panel--unlock peach-glass">319 <Show when={usingPin()} fallback={320 <>321 <label class="peach-label" for="unlock-password">322 master password323 </label>324 <input325 id="unlock-password"326 class="peach-underline-input peach-unlock-input lock-password-input"327 type="password"328 placeholder="••••••••••••"329 autocomplete="current-password"330 value={password()}331 disabled={!props.ready}332 ref={(el) => { if (props.ready) setTimeout(() => el.focus(), 80); }}333 onInput={(event) => setPassword((event.target as HTMLInputElement).value)}334 onKeyDown={(event) => {335 if (event.key !== "Enter" || !props.ready) return;336 void handleUnlock();337 }}338 />339 </>340 }>341 <label class="peach-label" for="unlock-pin">342 PIN343 </label>344 <input345 id="unlock-pin"346 class="peach-underline-input peach-unlock-input lock-pin-input"347 type="password"348 inputmode="numeric"349 maxlength="12"350 placeholder="••••••••••••"351 autocomplete="off"352 value={pin()}353 disabled={!props.ready}354 ref={(el) => { if (props.ready) setTimeout(() => el.focus(), 80); }}355 onInput={(event) => setPin((event.target as HTMLInputElement).value.replace(/\D/g, "").slice(0, 12))}356 onKeyDown={(event) => {357 if (event.key !== "Enter" || !props.ready) return;358 void handlePinUnlock();359 }}360 />361 <button362 class="peach-lock-recover-link"363 type="button"364 onClick={() => { setUsingPin(false); setError(""); }}365 >366 use master password367 </button>368 </Show>369370 <Show when={error()}>371 <p class="peach-hint peach-hint-error">{error()}</p>372 </Show>373374 <button375 class="peach-btn peach-btn--accent peach-btn--md peach-lock-submit"376 onClick={() => void (usingPin() ? handlePinUnlock() : handleUnlock())}377 disabled={!props.ready || loading()}378 >379 {loading() ? "unlocking..." : usingPin() ? "unlock with PIN" : "unlock"}380 </button>381382 <Show when={!usingPin() && pinAvailable()}>383 <button384 class="peach-lock-recover-link"385 type="button"386 onClick={() => { setUsingPin(true); setError(""); }}387 >388 use PIN389 </button>390 </Show>391392 <button393 class="peach-lock-recover-link"394 type="button"395 onClick={() => setRecoverSurface("words")}396 >397 forgot your password?398 </button>399 </section>400 </section>401 </Match>402403 {}404 <Match when={true}>405 <section406 class="peach-screen peach-theme lock-screen lock-screen--vault-stage peach-newvault"407 data-motion-phase="enter"408 >409 <header class="peach-screen-header peach-newvault-header">410 <div class="peach-wordmark-stack">411 <PeachWordmark class="peach-wordmark-wrap" />412 <Show when={props.isPro}>413 <span class="peach-pro-mini-badge">pro</span>414 </Show>415 </div>416 <Show when={props.onBackToOnboarding}>417 <button418 class="peach-newvault-back"419 type="button"420 onClick={() => props.onBackToOnboarding?.()}421 aria-label="Back to onboarding"422 >423 <svg width="11" height="11" viewBox="0 0 11 11" fill="none" stroke="currentColor" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round">424 <path d="M7 2L3 5.5L7 9" />425 </svg>426 back427 </button>428 </Show>429 </header>430431 <div class="peach-newvault-mark" aria-hidden="true">432 <PeachMark class="peach-newvault-mark-art" />433 </div>434435 <div class="peach-newvault-card">436 <h1 class="peach-newvault-headline">{"keep your\nsecrets."}</h1>437 <hr class="peach-newvault-divider" />438439 <div class="peach-newvault-field">440 <div class="peach-newvault-label-row">441 <label class="peach-label" for="master-password">442 master password443 </label>444 <button445 class="peach-lock-reveal-btn"446 type="button"447 onClick={() => setShowPassword((value) => !value)}448 aria-label={showPassword() ? "Hide password" : "Show password"}449 >450 <Show451 when={showPassword()}452 fallback={453 <svg width="15" height="10" viewBox="0 0 14 10" fill="none" stroke="currentColor" stroke-width="0.9" stroke-linecap="round">454 <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" />455 <circle cx="7" cy="5" r="1.75" />456 </svg>457 }458 >459 <svg width="15" height="10" viewBox="0 0 14 10" fill="none" stroke="currentColor" stroke-width="0.9" stroke-linecap="round">460 <path d="M1 2C3 4.5 5 6 7 6C9 6 11 4.5 13 2" />461 <path d="M3.5 5.5L2.5 7.5" />462 <path d="M7 6.5V8.5" />463 <path d="M10.5 5.5L11.5 7.5" />464 </svg>465 </Show>466 {showPassword() ? "hide" : "show"}467 </button>468 </div>469 <input470 id="master-password"471 class="peach-underline-input peach-newvault-input lock-password-input"472 type={showPassword() ? "text" : "password"}473 placeholder="••••••••••••"474 autocomplete="new-password"475 value={password()}476 disabled={!props.ready}477 onInput={(event) => setPassword((event.target as HTMLInputElement).value)}478 onKeyDown={(event) => {479 if (event.key !== "Enter" || !props.ready) return;480 void handleCreate();481 }}482 />483 <Show484 when={password().length > 0 && passwordStrength() !== null}485 fallback={486 <p class="peach-newvault-hint">487 At least 12 characters.488 </p>489 }490 >491 <div class="peach-password-strength">492 <div class={`peach-strength-bar peach-strength-bar--${passwordStrength()}`}>493 <div class="peach-strength-fill"></div>494 </div>495 <span class="peach-strength-label">{passwordStrength()}</span>496 </div>497 </Show>498 </div>499500 <div class="peach-newvault-field">501 <label class="peach-label" for="confirm-password">502 confirm password503 </label>504 <input505 id="confirm-password"506 class="peach-underline-input peach-newvault-input"507 type={showPassword() ? "text" : "password"}508 placeholder="••••••••••••"509 autocomplete="new-password"510 value={confirmPassword()}511 disabled={!props.ready}512 onInput={(event) => setConfirmPassword((event.target as HTMLInputElement).value)}513 onKeyDown={(event) => {514 if (event.key === "Enter" && props.ready) void handleCreate();515 }}516 />517 </div>518519 <Show when={error()}>520 <p class="peach-hint peach-hint-error">{error()}</p>521 </Show>522523 <button524 class="peach-btn peach-btn--accent peach-btn--md peach-lock-submit peach-newvault-submit"525 onClick={() => void handleCreate()}526 disabled={!props.ready || loading() || !canCreate()}527 aria-live="polite"528 >529 <Show530 when={!canCreate() && createBlockerMessage()}531 fallback={loading() ? "creating..." : "create vault"}532 >533 {createBlockerMessage()}534 </Show>535 </button>536537 <p class="peach-newvault-warning">538 <span class="peach-newvault-warning-icon" aria-hidden="true">⚠</span>539 <span>Save your 12 recovery words after creating — they're the only way back in if you forget your password.</span>540 </p>541 </div>542 </section>543 </Match>544 </Switch>545 );546}547548549550export type RestoreSource = "symbols" | "codex" | "csv";551552const RESTORE_SOURCES: { id: RestoreSource; name: string; detail: string }[] = [553 { id: "symbols", name: "PeachScript", detail: "Paste the rune string, or open a .peach file." },554 { id: "codex", name: "Codex", detail: "Scan printed pages, or import the PDF." },555 { id: "csv", name: "CSV", detail: "A .csv or .json file from another password manager." },556];557558const RESTORE_DEEP_LINKS: Record<"symbols" | "csv", "peachscript" | "csv"> = {559 symbols: "peachscript",560 csv: "csv",561};562563564565566567568569570571async function detachForFilePicker(route: "peachscript" | "csv"): Promise<boolean> {572 try {573 574 if (new URLSearchParams(window.location.search).get("restore")) return false;575 } catch { }576 if (typeof chrome === "undefined" || typeof chrome.runtime?.sendMessage !== "function") {577 return false;578 }579 try {580 const res = (await sendMessage({581 type: "OPEN_DETACHED_POPUP",582 payload: { route },583 })) as { ok: boolean; data?: { detached?: boolean } };584 if (!res?.data?.detached) return false;585 586 587 return true;588 } catch {589 return false;590 }591}592593594595function restoreDeepLinkActive(link: "peachscript" | "csv"): boolean {596 try {597 return new URLSearchParams(window.location.search).get("restore") === link;598 } catch {599 return false;600 }601}602603function RestoreView(props: {604 hasVault: boolean;605 onOpenCodexRestore?: () => void;606 onBack: () => void;607 onUnlock: () => void | Promise<void>;608 initialSource?: RestoreSource;609}) {610 const [source, setSource] = createSignal<RestoreSource | null>(props.initialSource ?? null);611 const [showIntro, setShowIntro] = createSignal(false);612 const [pendingUnlock] = createSignal(false);613614 615 616 617 618 function chooseSource(next: RestoreSource | null) {619 setSource(next);620 if (next) void storageSet(RESTORE_SOURCE_STORAGE_KEY, next).catch(() => {});621 else void storageRemove(RESTORE_SOURCE_STORAGE_KEY).catch(() => {});622 }623624 async function handleRestoreSuccess() {625 const seen = await storageGet("peach_shown_restore_intro").catch(() => null);626 if (!seen) {627 setShowIntro(true);628 } else {629 await props.onUnlock();630 }631 }632633 async function dismissIntro() {634 await storageSet("peach_shown_restore_intro", "true").catch(() => {});635 setShowIntro(false);636 await props.onUnlock();637 }638639 return (640 <section641 class="peach-screen peach-theme lock-screen lock-screen--vault-stage peach-newvault peach-restore"642 data-motion-phase="enter"643 >644 <RuneBackground opacity={0.05} />645646 <header class="peach-screen-header peach-newvault-header">647 <PeachWordmark class="peach-wordmark-wrap" />648 <button649 class="peach-newvault-back peach-restore-back"650 type="button"651 onClick={props.onBack}652 aria-label="Back to onboarding"653 >654 <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">655 <path d="M7 2L3 5.5L7 9" />656 </svg>657 back658 </button>659 </header>660661 <div class="peach-newvault-card peach-restore-card">662 <Show663 when={source()}664 keyed665 fallback={666 <>667 <h1 class="peach-newvault-headline">{"welcome\nback."}</h1>668 <hr class="peach-newvault-divider" />669 <div class="peach-restore-sources">670 <For each={RESTORE_SOURCES}>671 {(entry) => (672 <button673 type="button"674 class="peach-onboarding-choice peach-restore-source"675 onClick={() => chooseSource(entry.id)}676 >677 <span class="peach-onboarding-choice-label">{entry.name}</span>678 <span class="peach-onboarding-choice-detail">{entry.detail}</span>679 </button>680 )}681 </For>682 </div>683 </>684 }685 >686 {(active) => (687 <>688 <div class="peach-restore-source-head">689 <h2 class="peach-restore-source-title">690 {RESTORE_SOURCES.find((entry) => entry.id === active)?.name}691 </h2>692 <button693 type="button"694 class="peach-restore-picker-back"695 onClick={() => chooseSource(null)}696 >697 ‹ sources698 </button>699 </div>700 <hr class="peach-newvault-divider" />701 <Show when={active === "symbols"}>702 <RestoreSymbols hasVault={props.hasVault} onSuccess={handleRestoreSuccess} />703 </Show>704 <Show when={active === "codex"}>705 <RestoreCodex onOpen={() => props.onOpenCodexRestore?.()} />706 </Show>707 <Show when={active === "csv"}>708 <RestoreCSV hasVault={props.hasVault} onSuccess={handleRestoreSuccess} />709 </Show>710 </>711 )}712 </Show>713 </div>714715 {}716 <Show when={showIntro()}>717 <div class="peach-restore-intro-overlay">718 <div class="peach-restore-intro-card">719 <p class="peach-restore-intro-headline">welcome to peach.</p>720 <div class="peach-restore-intro-body">721 <p>Your vault lives only on this device. No server has a copy.</p>722 <p>The inline bubble fills passwords automatically when you visit sites.</p>723 <p>Export your vault from Settings before switching devices.</p>724 </div>725 <button726 class="peach-btn peach-btn--accent peach-btn--md peach-restore-intro-btn"727 onClick={() => void dismissIntro()}728 disabled={pendingUnlock()}729 >730 got it731 </button>732 </div>733 </div>734 </Show>735 </section>736 );737}738739740741function RestoreCodex(props: { onOpen: () => void }) {742 return (743 <div class="peach-restore-form">744 <p class="peach-restore-codex-copy">745 Scan printed Codex pages or import the Codex PDF. Codex restore is746 always available, even before you create a vault.747 </p>748 <button749 type="button"750 class="peach-btn peach-btn--accent peach-btn--md peach-restore-submit"751 onClick={props.onOpen}752 >753 open Codex restore754 </button>755 </div>756 );757}758759760761function RestoreSymbols(props: {762 hasVault: boolean;763 onSuccess: () => void | Promise<void>;764}) {765 const [scriptInput, setScriptInput] = createSignal("");766 const [backupPass, setBackupPass] = createSignal("");767 const [working, setWorking] = createSignal(false);768 const [animating, setAnimating] = createSignal<"chaos" | "snap" | "bloom" | null>(null);769 const [error, setError] = createSignal<string | null>(null);770 let canvasRef: HTMLCanvasElement | undefined;771 let peachFileRef: HTMLInputElement | undefined;772 let animFrameId = 0;773 let runes: { x: number; y: number; vx: number; vy: number; char: string; size: number; angle: number; va: number }[] = [];774775 const scriptValid = createMemo(() => isPeachScript(scriptInput()));776777 function stopAnim() {778 cancelAnimationFrame(animFrameId);779 animFrameId = 0;780 }781782 function startChaos(canvas: HTMLCanvasElement) {783 const ctx = canvas.getContext("2d")!;784 const W = canvas.width;785 const H = canvas.height;786 const RUNE_CHARS = Array.from({ length: 40 }, (_, i) =>787 String.fromCodePoint(0xe000 + i)788 );789 if (runes.length === 0) {790 runes = Array.from({ length: 60 }, () => ({791 x: Math.random() * W,792 y: Math.random() * H,793 vx: (Math.random() - 0.5) * 3,794 vy: (Math.random() - 0.5) * 3,795 char: RUNE_CHARS[Math.floor(Math.random() * RUNE_CHARS.length)]!,796 size: 14 + Math.random() * 20,797 angle: Math.random() * Math.PI * 2,798 va: (Math.random() - 0.5) * 0.1,799 }));800 }801802 function draw() {803 ctx.clearRect(0, 0, W, H);804 for (const r of runes) {805 r.x = (r.x + r.vx + W) % W;806 r.y = (r.y + r.vy + H) % H;807 r.angle += r.va;808 ctx.save();809 ctx.translate(r.x, r.y);810 ctx.rotate(r.angle);811 ctx.font = `${r.size}px PeachScript, monospace`;812 const alpha = 0.5 + 0.5 * Math.sin(Date.now() / 400 + r.x);813 ctx.fillStyle = `rgba(232, 149, 109, ${alpha})`;814 ctx.shadowColor = "rgba(232, 149, 109, 0.7)";815 ctx.shadowBlur = 8;816 ctx.fillText(r.char, 0, 0);817 ctx.restore();818 }819 animFrameId = requestAnimationFrame(draw);820 }821 draw();822 }823824 function snapToGrid(canvas: HTMLCanvasElement, onDone: () => void) {825 stopAnim();826 const ctx = canvas.getContext("2d")!;827 const W = canvas.width;828 const H = canvas.height;829 const cols = 8;830 const rows = 6;831 const cellW = W / cols;832 const cellH = H / rows;833 const targets = runes.slice(0, cols * rows).map((_, i) => ({834 x: (i % cols) * cellW + cellW / 2,835 y: Math.floor(i / cols) * cellH + cellH / 2,836 }));837 const start = performance.now();838 const DURATION = 400;839840 function drawSnap(now: number) {841 const t = Math.min((now - start) / DURATION, 1);842 const ease = t < 1 ? 1 - (1 - t) ** 3 : 1;843 ctx.clearRect(0, 0, W, H);844 runes.slice(0, targets.length).forEach((r, i) => {845 const tx = targets[i]!.x;846 const ty = targets[i]!.y;847 const cx = r.x + (tx - r.x) * ease;848 const cy = r.y + (ty - r.y) * ease;849 ctx.font = `16px PeachScript, monospace`;850 ctx.fillStyle = `rgba(232, 149, 109, ${0.8 * ease})`;851 ctx.shadowColor = "rgba(232, 149, 109, 0.6)";852 ctx.shadowBlur = 6;853 ctx.fillText(r.char, cx - 8, cy + 8);854 });855 if (t < 1) {856 animFrameId = requestAnimationFrame(drawSnap);857 } else {858 onDone();859 }860 }861 animFrameId = requestAnimationFrame(drawSnap);862 }863864 function bloom(canvas: HTMLCanvasElement, onDone: () => void) {865 stopAnim();866 const ctx = canvas.getContext("2d")!;867 const W = canvas.width;868 const H = canvas.height;869 const start = performance.now();870 const DURATION = 900;871872 function drawBloom(now: number) {873 const t = Math.min((now - start) / DURATION, 1);874 ctx.clearRect(0, 0, W, H);875 876 const runeAlpha = 1 - Math.min(t / 0.4, 1);877 if (runeAlpha > 0) {878 for (const r of runes.slice(0, 48)) {879 ctx.font = `16px PeachScript, monospace`;880 ctx.fillStyle = `rgba(232, 149, 109, ${runeAlpha * 0.8})`;881 ctx.fillText(r.char, r.x - 8, r.y + 8);882 }883 }884 885 const markT = Math.max(0, (t - 0.2) / 0.5);886 const markScale = Math.min(markT * 1.2, 1);887 const markAlpha = markT < 0.5 ? markT * 2 : 2 - markT * 2;888 if (markAlpha > 0) {889 ctx.save();890 ctx.globalAlpha = markAlpha;891 ctx.shadowColor = `rgba(217, 104, 48, ${markAlpha * 0.8})`;892 ctx.shadowBlur = 30;893 ctx.translate(W / 2, H / 2);894 ctx.scale(markScale, markScale);895 ctx.drawImage(peachMarkImg, -32, -32, 64, 64);896 ctx.restore();897 }898 if (t < 1) {899 animFrameId = requestAnimationFrame(drawBloom);900 } else {901 onDone();902 }903 }904 animFrameId = requestAnimationFrame(drawBloom);905 }906907 onCleanup(() => stopAnim());908909 910 911 onMount(() => {912 if (restoreDeepLinkActive(RESTORE_DEEP_LINKS.symbols)) {913 setTimeout(() => peachFileRef?.click(), 50);914 }915 });916917 918 919 const [dragDepth, setDragDepth] = createSignal(0);920921 async function handleDrop(e: DragEvent) {922 e.preventDefault();923 setDragDepth(0);924 if (working() || animating() !== null) return;925 const file = e.dataTransfer?.files?.[0];926 if (!file) return;927 928 929 if (file.size > IMPORT_LIMITS.MAX_JSON_BYTES) {930 setError("That file is too large.");931 return;932 }933 try {934 setScriptInput(await file.text());935 setError(null);936 } catch {937 setError("Couldn't read file.");938 }939 }940941 async function handleRestore() {942 if (!scriptValid() || !backupPass().trim() || working()) return;943 setError(null);944 setWorking(true);945 setAnimating("chaos");946947 const canvas = canvasRef;948 if (canvas) startChaos(canvas);949950 try {951 952 953 const bytes = decodePeachScript(scriptInput());954 const payload = await parsePayload(bytes, backupPass());955956 if (!props.hasVault) {957 const cr = await sendMessage({ type: "CREATE_VAULT", payload: { password: backupPass() } });958 if (!(cr as { ok: boolean }).ok) throw new Error("CREATE_VAULT_FAILED");959 if ((cr.data as { unlocked?: boolean } | undefined)?.unlocked === false) throw new Error("vault_created_locked");960 }961962 const rr = await sendMessage({963 type: "RESTORE_ENTRIES",964 payload: { entries: payload.entries, mode: "merge", settings: payload.settings },965 });966 if (!(rr as { ok: boolean }).ok) throw new Error((rr as { error?: string }).error ?? "RESTORE_FAILED");967968 if (payload.license?.key) {969 await sendMessage({ type: "ACTIVATE_LICENSE", payload: { key: payload.license.key } }).catch(() => {});970 }971972 setAnimating("snap");973 stopAnim();974 if (canvas) {975 snapToGrid(canvas, () => {976 setAnimating("bloom");977 bloom(canvas, async () => {978 setAnimating(null);979 await props.onSuccess();980 });981 });982 } else {983 await props.onSuccess();984 }985 } catch (err) {986 stopAnim();987 setAnimating(null);988 const code = err instanceof Error ? err.message : String(err);989 setError(990 code === "INVALID_PASSPHRASE"991 ? "That passphrase didn't work."992 : code === "vault_created_locked"993 ? getDisplayError(code, "")994 : code === "CREATE_VAULT_FAILED"995 ? "Couldn't create a new local vault."996 : "Could not read this backup.",997 );998 } finally {999 setWorking(false);1000 }1001 }10021003 return (1004 <div1005 class="peach-restore-form"1006 classList={{ "is-dragover": dragDepth() > 0 }}1007 onDragEnter={(e) => { e.preventDefault(); setDragDepth((d) => d + 1); }}1008 onDragOver={(e) => e.preventDefault()}1009 onDragLeave={() => setDragDepth((d) => Math.max(0, d - 1))}1010 onDrop={(e) => void handleDrop(e)}1011 >1012 <Show when={animating() !== null}>1013 <canvas1014 ref={(el) => { canvasRef = el; }}1015 class="peach-restore-anim-canvas"1016 width={280}1017 height={200}1018 />1019 </Show>1020 <Show when={animating() === null}>1021 <Show1022 when={scriptValid()}1023 fallback={1024 <>1025 <textarea1026 class="peach-restore-script"1027 placeholder="paste peachscript…"1028 rows={3}1029 aria-label="Paste your PeachScript backup"1030 value={scriptInput()}1031 onInput={(e) => setScriptInput((e.target as HTMLTextAreaElement).value)}1032 />1033 <div class="peach-restore-or" aria-hidden="true">or</div>1034 <label1035 class="peach-btn peach-btn--ghost peach-btn--sm peach-restore-file-btn"1036 onClick={(e) => {1037 if (restoreDeepLinkActive(RESTORE_DEEP_LINKS.symbols)) return;1038 e.preventDefault();1039 void detachForFilePicker(RESTORE_DEEP_LINKS.symbols).then((detached) => {1040 if (!detached) peachFileRef?.click();1041 });1042 }}1043 >1044 open .peach file1045 <input1046 ref={(el) => { peachFileRef = el; }}1047 type="file"1048 accept=".peach,text/plain"1049 style="display:none"1050 onChange={async (e) => {1051 const file = (e.currentTarget as HTMLInputElement).files?.[0];1052 if (!file) return;1053 1054 if (file.size > IMPORT_LIMITS.MAX_JSON_BYTES) {1055 setError("That file is too large.");1056 (e.currentTarget as HTMLInputElement).value = "";1057 return;1058 }1059 try {1060 setScriptInput(await file.text());1061 } catch {1062 setError("Couldn't read file.");1063 } finally {1064 (e.currentTarget as HTMLInputElement).value = "";1065 }1066 }}1067 />1068 </label>1069 <p class="peach-restore-drop-hint">or drop the file anywhere here</p>1070 </>1071 }1072 >1073 <div class="peach-restore-rune-preview">1074 <RuneCanvas runeString={scriptInput()} width={256} height={120} />1075 </div>1076 <button1077 type="button"1078 class="peach-restore-picker-back"1079 onClick={() => { setScriptInput(""); setError(null); }}1080 >1081 ‹ paste again1082 </button>1083 </Show>1084 <div class="peach-newvault-field">1085 <label class="peach-label" for="restore-backup-pass">1086 backup password1087 </label>1088 <input1089 id="restore-backup-pass"1090 class="peach-underline-input peach-newvault-input"1091 type="password"1092 placeholder="••••••••••••"1093 autocomplete="current-password"1094 value={backupPass()}1095 onInput={(e) => setBackupPass((e.target as HTMLInputElement).value)}1096 onKeyDown={(e) => {1097 if (e.key === "Enter" && scriptValid() && backupPass().trim() && !working()) {1098 e.preventDefault();1099 void handleRestore();1100 }1101 }}1102 />1103 </div>1104 <button1105 class="peach-btn peach-btn--accent peach-btn--md peach-restore-submit"1106 onClick={() => void handleRestore()}1107 disabled={!scriptValid() || !backupPass().trim() || working()}1108 >1109 restore vault1110 </button>1111 <Show when={error()}>1112 <p class="peach-hint peach-hint-error">{error()}</p>1113 </Show>1114 </Show>1115 </div>1116 );1117}1118111911201121function RestoreCSV(props: {1122 hasVault: boolean;1123 onSuccess: () => void | Promise<void>;1124}) {1125 const [importing, setImporting] = createSignal(false);1126 const [error, setError] = createSignal<string | null>(null);1127 1128 1129 1130 1131 const CSV_MIN_PASSWORD_LENGTH = 12;1132 const [newPass, setNewPass] = createSignal("");1133 const [confirmPass, setConfirmPass] = createSignal("");1134 const needsPassword = () => props.hasVault === false;1135 const passwordReady = () =>1136 !needsPassword() ||1137 (newPass().length >= CSV_MIN_PASSWORD_LENGTH && newPass() === confirmPass());1138 1139 1140 const [dragDepth, setDragDepth] = createSignal(0);11411142 1143 1144 1145 async function processFile(file: File) {1146 if (file.size > IMPORT_LIMITS.MAX_JSON_BYTES) {1147 setError("That file is too large.");1148 return;1149 }1150 setImporting(true);1151 setError(null);1152 try {1153 const text = await file.text();1154 const parsed = await parseImportSource(text);1155 if (parsed.entries.length === 0) throw new Error("NO_ENTRIES");11561157 if (props.hasVault === false) {1158 1159 1160 const cr = await sendMessage({ type: "CREATE_VAULT", payload: { password: newPass() } });1161 if (!(cr as { ok: boolean }).ok) throw new Error("CREATE_VAULT_FAILED");1162 if ((cr.data as { unlocked?: boolean } | undefined)?.unlocked === false) throw new Error("vault_created_locked");1163 }11641165 const res = await sendMessage({ type: "BATCH_ADD_ENTRIES", payload: { entries: parsed.entries } });1166 if (!(res as { ok: boolean }).ok) throw new Error("IMPORT_FAILED");1167 await props.onSuccess();1168 } catch (err) {1169 const code = err instanceof Error ? err.message : String(err);1170 setError(1171 code === "NO_ENTRIES" ? "No entries found in this file." :1172 code === "vault_created_locked" ? getDisplayError(code, "") :1173 code === "CREATE_VAULT_FAILED" ? "Couldn't create a new local vault." :1174 "Import failed. Check the file format and try again."1175 );1176 } finally {1177 setImporting(false);1178 }1179 }11801181 let csvFileRef: HTMLInputElement | undefined;11821183 onMount(() => {1184 1185 1186 1187 if (restoreDeepLinkActive(RESTORE_DEEP_LINKS.csv) && !needsPassword()) {1188 setTimeout(() => csvFileRef?.click(), 50);1189 }1190 });11911192 function gatePassword(): boolean {1193 if (importing()) return false;1194 if (needsPassword() && newPass().length < CSV_MIN_PASSWORD_LENGTH) {1195 setError(`Set a master password of at least ${CSV_MIN_PASSWORD_LENGTH} characters first.`);1196 return false;1197 }1198 if (needsPassword() && newPass() !== confirmPass()) {1199 setError("Passwords do not match.");1200 return false;1201 }1202 return true;1203 }12041205 async function handleFile(e: Event) {1206 const input = e.currentTarget as HTMLInputElement;1207 const file = input.files?.[0];1208 input.value = "";1209 if (!file) return;1210 await processFile(file);1211 }12121213 async function handleDrop(e: DragEvent) {1214 e.preventDefault();1215 setDragDepth(0);1216 if (!gatePassword()) return;1217 const file = e.dataTransfer?.files?.[0];1218 if (!file) return;1219 await processFile(file);1220 }12211222 return (1223 <div1224 class="peach-restore-form"1225 classList={{ "is-dragover": dragDepth() > 0 }}1226 onDragEnter={(e) => { e.preventDefault(); setDragDepth((d) => d + 1); }}1227 onDragOver={(e) => e.preventDefault()}1228 onDragLeave={() => setDragDepth((d) => Math.max(0, d - 1))}1229 onDrop={(e) => void handleDrop(e)}1230 >1231 <Show when={needsPassword()}>1232 <div class="peach-newvault-field">1233 <label class="peach-label" for="restore-csv-pass">1234 new master password1235 </label>1236 <input1237 id="restore-csv-pass"1238 class="peach-underline-input peach-newvault-input"1239 type="password"1240 placeholder="••••••••••••"1241 autocomplete="new-password"1242 value={newPass()}1243 onInput={(e) => setNewPass((e.target as HTMLInputElement).value)}1244 />1245 </div>1246 <div class="peach-newvault-field">1247 <label class="peach-label" for="restore-csv-confirm">1248 confirm master password1249 </label>1250 <input1251 id="restore-csv-confirm"1252 class="peach-underline-input peach-newvault-input"1253 type="password"1254 placeholder="••••••••••••"1255 autocomplete="new-password"1256 value={confirmPass()}1257 onInput={(e) => setConfirmPass((e.target as HTMLInputElement).value)}1258 />1259 </div>1260 </Show>1261 <label1262 class="peach-btn peach-btn--accent peach-btn--md peach-restore-file-btn"1263 onClick={(e) => {1264 1265 1266 1267 if (restoreDeepLinkActive(RESTORE_DEEP_LINKS.csv)) return;1268 1269 1270 e.preventDefault();1271 if (!gatePassword()) return;1272 void detachForFilePicker(RESTORE_DEEP_LINKS.csv).then((detached) => {1273 if (!detached) csvFileRef?.click();1274 });1275 }}1276 >1277 {importing() ? "importing…" : "open csv file"}1278 <input1279 ref={(el) => { csvFileRef = el; }}1280 type="file"1281 accept=".csv,.json,.peach,application/x-peach"1282 style="display:none"1283 onChange={handleFile}1284 disabled={importing() || !passwordReady()}1285 />1286 </label>1287 <p class="peach-restore-drop-hint">or drop the file anywhere here</p>1288 <p class="peach-hint peach-restore-csv-sources">1289 Imports from Bitwarden, 1Password, Proton Pass,1290 <br />1291 Chrome, Safari, and Edge.1292 </p>1293 <p class="peach-newvault-warning">1294 <span class="peach-newvault-warning-icon" aria-hidden="true">⚠</span>1295 <span>Plain-text file — delete it after the import.</span>1296 </p>1297 <Show when={error()}>1298 <p class="peach-hint peach-hint-error">{error()}</p>1299 </Show>1300 </div>1301 );1302}1303130413051306function getDisplayError(error: string | undefined, fallback: string): string {1307 if (!error) return fallback;1308 if (error === "vault_created_locked") return "Your new vault and password were saved. Reopen Peach and unlock it with your new password.";1309 if (1310 error === "SERVICE_WORKER_UNAVAILABLE" ||1311 error.includes("Receiving end does not exist") ||1312 error.includes("message port closed")1313 ) {1314 return "background service unavailable";1315 }1316 1317 return fallback;1318}