1import { For, Match, Show, Switch, createMemo, createSignal, onCleanup, onMount } from "solid-js";2import { sendMessage } from "../App";3import { LockRuneCanvas } from "../components/LockRuneCanvas";4import { PeachMark, PeachWordmark } from "../components/PeachMark";5import { RecoveryWordEntryView } from "./RecoveryWordEntry";6import { RecoveryWordDisplayView } from "./RecoveryWordDisplay";7import { RuneBackground } from "../components/RuneBackground";8import { storageGet, storageSet } from "../../shared/storage";9import { isPeachScript, decodePeachScript, normalisePeachScript } from "../../crypto/peachScript";10import { parsePayload } from "../../crypto/peachPayload";11import { parseImportSource } from "../../shared/import";12import { isNativePlatform, nativePlugin } from "../../shared/native";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}6465type RestoreSurface = "restore" | null;66type RecoverSurface = "words" | "new-password" | null;6768export function LockView(props: LockProps) {69 const [password, setPassword] = createSignal("");70 const [confirmPassword, setConfirmPassword] = createSignal("");71 const [error, setError] = createSignal("");72 const [loading, setLoading] = createSignal(false);73 const [restoreSurface, setRestoreSurface] = createSignal<RestoreSurface>(74 props.initialRestore ? "restore" : null,75 );76 const [showPassword, setShowPassword] = createSignal(false);77 const [recoverSurface, setRecoverSurface] = createSignal<RecoverSurface>(null);78 79 80 const [showRecoveryWords, setShowRecoveryWords] = createSignal(props.forceRecoveryWords ?? false);8182 const MIN_LENGTH = 12;83 const MIN_ZXCVBN_SCORE = 2;8485 const [strengthScore, setStrengthScore] = createSignal<number | null>(null);86 const [biometricAvailable, setBiometricAvailable] = createSignal(false);87 const [biometricBusy, setBiometricBusy] = createSignal(false);8889 const canCreate = createMemo(90 () =>91 password().length >= MIN_LENGTH &&92 confirmPassword().length >= MIN_LENGTH &&93 password() === confirmPassword() &&94 strengthScore() !== null &&95 strengthScore()! >= MIN_ZXCVBN_SCORE96 );9798 const passwordStrength = createMemo(() => {99 const score = strengthScore();100 if (score === null) return null;101 if (score <= 1) return "weak";102 if (score === 2) return "fair";103 if (score === 3) return "good";104 return "strong";105 });106107 const createBlockerMessage = createMemo(() => {108 if (!password()) return null;109 if (password().length < MIN_LENGTH) return `need ${MIN_LENGTH - password().length} more characters`;110 if (!confirmPassword()) return "confirm your password";111 if (password() !== confirmPassword()) return "passwords don't match";112 if (strengthScore() === null) return "checking strength…";113 if (strengthScore()! < MIN_ZXCVBN_SCORE) return "password too weak — use a longer passphrase";114 return null;115 });116117 118 createMemo(() => {119 const value = password();120 if (!value) { setStrengthScore(null); return; }121 getZxcvbn().then((zxcvbn) => {122 if (password() === value) setStrengthScore(zxcvbn(value).score);123 }).catch(() => {124 125 if (password() === value) setStrengthScore(value.length >= 16 ? 3 : value.length >= 12 ? 2 : 1);126 });127 });128129 async function handleUnlock() {130 if (!password().trim()) return;131 setLoading(true);132 setError("");133 const response = await sendMessage({134 type: "UNLOCK",135 payload: { password: password() },136 });137 const result = response as { ok: boolean; error?: string };138 if (result.ok) {139 await props.onUnlock();140 setLoading(false);141 return;142 }143 setError(getDisplayError(result.error, "incorrect password"));144 setPassword("");145 const passwordField = document.querySelector(".lock-password-input") as HTMLInputElement | undefined;146 passwordField?.classList.add("shake");147 setTimeout(() => passwordField?.classList.remove("shake"), 300);148 setLoading(false);149 }150151 async function checkBiometricAvailable(): Promise<void> {152 if (!props.hasVault || !isNativePlatform()) return;153 const keystore = nativePlugin<{ hasMasterKey: () => Promise<{ exists: boolean }> }>("KeystorePlugin");154 const biometric = nativePlugin<{ isAvailable: () => Promise<{ available: boolean }> }>("BiometricPlugin");155 if (!keystore || !biometric) return;156 try {157 const stored = await keystore.hasMasterKey();158 if (!stored.exists) return;159 const avail = await biometric.isAvailable();160 if (!avail.available) return;161 setBiometricAvailable(true);162 window.setTimeout(() => { void handleBiometricUnlock(); }, 400);163 } catch { }164 }165166 async function handleBiometricUnlock(): Promise<void> {167 if (biometricBusy()) return;168 const biometric = nativePlugin<{ authenticate: (opts: Record<string, string>) => Promise<void> }>("BiometricPlugin");169 const keystore = nativePlugin<{ retrieveMasterKey: () => Promise<{ masterKeyHex: string }> }>("KeystorePlugin");170 if (!biometric || !keystore) return;171 setBiometricBusy(true);172 setError("");173 try {174 await biometric.authenticate({175 title: "Unlock Peach",176 subtitle: "Use biometrics to access your vault",177 negativeButtonText: "Use Password",178 });179 const { masterKeyHex } = await keystore.retrieveMasterKey();180 const res = (await sendMessage({181 type: "UNLOCK_WITH_KEY",182 payload: { masterKeyHex },183 })) as { ok: boolean; error?: string };184 if (res.ok) {185 await props.onUnlock();186 return;187 }188 if (res.error === "biometric_key_invalidated") {189 await sendMessage({190 type: "UPDATE_SETTINGS",191 payload: { biometricsEnabled: false },192 });193 setBiometricAvailable(false);194 setError("biometric key expired — re-enable in settings");195 } else {196 setError("biometric unlock failed");197 }198 } catch (e) {199 const reason = e instanceof Error ? e.message : String(e);200 if (reason.includes("user_cancelled")) return;201 if (reason.includes("biometric_key_invalidated")) {202 await sendMessage({203 type: "UPDATE_SETTINGS",204 payload: { biometricsEnabled: false },205 });206 setBiometricAvailable(false);207 setError("biometric key expired — re-enable in settings");208 return;209 }210 if (reason.includes("biometric_lockout")) {211 setError("biometric locked out — use your password");212 }213 } finally {214 setBiometricBusy(false);215 }216 }217218 onMount(() => { void checkBiometricAvailable(); });219220 async function handleCreate() {221 if (!password().trim()) return;222 if (password().length < MIN_LENGTH) {223 setError(`password must be at least ${MIN_LENGTH} characters`);224 return;225 }226 if (password() !== confirmPassword()) {227 setError("passwords do not match");228 return;229 }230 const score = strengthScore();231 if (score === null || score < MIN_ZXCVBN_SCORE) {232 setError("password is too weak — use a longer passphrase");233 return;234 }235 setLoading(true);236 setError("");237 const response = await sendMessage({238 type: "CREATE_VAULT",239 payload: { password: password() },240 });241 const result = response as { ok: boolean; error?: string };242 if (result.ok) {243 244 245 246 247 248 try {249 await chrome.storage.local?.set({ peach_recovery_pending: "1" });250 } catch { }251 setShowRecoveryWords(true);252 setLoading(false);253 return;254 }255 setError(getDisplayError(result.error, "failed to create vault"));256 setLoading(false);257 }258259 260 return (261 <Switch>262 {}263 <Match when={restoreSurface() === "restore"}>264 <RestoreTabView265 hasVault={props.hasVault}266 onOpenCodexRestore={props.onOpenCodexRestore}267 onBack={() => setRestoreSurface(null)}268 onUnlock={async () => {269 setRestoreSurface(null);270 await props.onUnlock();271 }}272 />273 </Match>274275 {}276 <Match when={showRecoveryWords() && (!props.hasVault || props.forceRecoveryWords)}>277 <RecoveryWordDisplayView278 onDone={props.onUnlock}279 />280 </Match>281282 {}283 <Match when={recoverSurface() === "words"}>284 <RecoveryWordEntryView285 onCancel={() => setRecoverSurface(null)}286 onRecoveryComplete={props.onUnlock}287 />288 </Match>289290 {}291 <Match when={props.hasVault}>292 <section class="peach-screen peach-theme lock-screen lock-screen--vault-stage" data-motion-phase="enter">293 <header class="peach-screen-header lock-screen-header">294 <div class="peach-wordmark-stack">295 <PeachWordmark class="peach-wordmark-wrap" />296 <Show when={props.isPro}>297 <span class="peach-pro-mini-badge">pro</span>298 </Show>299 </div>300 </header>301302 <div class="peach-lock-hero peach-lock-hero--unlock">303 <div class="peach-lock-hero-art" aria-hidden="true">304 <PeachMark class="peach-lock-hero-mark" />305 </div>306 <span class="peach-lock-eyebrow">vault locked</span>307 <h1 class="peach-onboarding-headline peach-lock-headline--unlock">308 unlock309 <br />310 your vault.311 </h1>312 </div>313314 <LockRuneCanvas />315316 <section class="peach-lock-panel peach-lock-panel--unlock peach-glass">317 <label class="peach-label" for="unlock-password">318 master password319 </label>320 <input321 id="unlock-password"322 class="peach-underline-input peach-unlock-input lock-password-input"323 type="password"324 placeholder="••••••••••••"325 autocomplete="current-password"326 value={password()}327 disabled={!props.ready}328 ref={(el) => { if (props.ready) setTimeout(() => el.focus(), 80); }}329 onInput={(event) => setPassword((event.target as HTMLInputElement).value)}330 onKeyDown={(event) => {331 if (event.key !== "Enter" || !props.ready) return;332 void handleUnlock();333 }}334 />335336 <Show when={error()}>337 <p class="peach-hint peach-hint-error">{error()}</p>338 </Show>339340 <button341 class="peach-btn peach-btn--accent peach-btn--md peach-lock-submit"342 onClick={() => void handleUnlock()}343 disabled={!props.ready || loading()}344 >345 {loading() ? "unlocking..." : "unlock"}346 </button>347348 <Show when={biometricAvailable()}>349 <button350 class="peach-biometric-btn"351 type="button"352 onClick={() => void handleBiometricUnlock()}353 disabled={biometricBusy() || loading()}354 aria-label="Unlock with biometrics"355 >356 <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.4" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">357 <path d="M12 11c-1.7 0-3 1.3-3 3v3"/>358 <path d="M15 17v-3"/>359 <path d="M9 4.5C9.7 4.2 10.8 4 12 4s2.3.2 3 .5"/>360 <path d="M5 9c.7-1.6 2-2.9 3.6-3.6"/>361 <path d="M19 9c-.7-1.6-2-2.9-3.6-3.6"/>362 <path d="M5 15c0-1.7.3-3.3.8-4.7"/>363 <path d="M19 15c0-1.7-.3-3.3-.8-4.7"/>364 </svg>365 {biometricBusy() ? "verifying…" : "use biometrics"}366 </button>367 </Show>368369 <button370 class="peach-lock-recover-link"371 type="button"372 onClick={() => setRecoverSurface("words")}373 >374 forgot your password?375 </button>376 </section>377 </section>378 </Match>379380 {}381 <Match when={true}>382 <section383 class="peach-screen peach-theme lock-screen lock-screen--vault-stage peach-newvault"384 data-motion-phase="enter"385 >386 <header class="peach-screen-header peach-newvault-header">387 <Show when={props.onBackToOnboarding}>388 <button389 class="peach-newvault-back"390 type="button"391 onClick={() => props.onBackToOnboarding?.()}392 aria-label="Back to onboarding"393 >394 <svg width="11" height="11" viewBox="0 0 11 11" fill="none" stroke="currentColor" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round">395 <path d="M7 2L3 5.5L7 9" />396 </svg>397 back398 </button>399 </Show>400 <div class="peach-wordmark-stack">401 <PeachWordmark class="peach-wordmark-wrap" />402 <Show when={props.isPro}>403 <span class="peach-pro-mini-badge">pro</span>404 </Show>405 </div>406 </header>407408 <div class="peach-newvault-mark" aria-hidden="true">409 <PeachMark class="peach-newvault-mark-art" />410 </div>411412 <div class="peach-newvault-card">413 <h1 class="peach-newvault-headline">{"keep your\nsecrets."}</h1>414 <hr class="peach-newvault-divider" />415416 <div class="peach-newvault-field">417 <div class="peach-newvault-label-row">418 <label class="peach-label" for="master-password">419 master password420 </label>421 <button422 class="peach-lock-reveal-btn"423 type="button"424 onClick={() => setShowPassword((value) => !value)}425 aria-label={showPassword() ? "Hide password" : "Show password"}426 >427 <Show428 when={showPassword()}429 fallback={430 <svg width="15" height="10" viewBox="0 0 14 10" fill="none" stroke="currentColor" stroke-width="0.9" stroke-linecap="round">431 <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" />432 <circle cx="7" cy="5" r="1.75" />433 </svg>434 }435 >436 <svg width="15" height="10" viewBox="0 0 14 10" fill="none" stroke="currentColor" stroke-width="0.9" stroke-linecap="round">437 <path d="M1 2C3 4.5 5 6 7 6C9 6 11 4.5 13 2" />438 <path d="M3.5 5.5L2.5 7.5" />439 <path d="M7 6.5V8.5" />440 <path d="M10.5 5.5L11.5 7.5" />441 </svg>442 </Show>443 {showPassword() ? "hide" : "show"}444 </button>445 </div>446 <input447 id="master-password"448 class="peach-underline-input peach-newvault-input lock-password-input"449 type={showPassword() ? "text" : "password"}450 placeholder="••••••••••••"451 autocomplete="new-password"452 value={password()}453 disabled={!props.ready}454 onInput={(event) => setPassword((event.target as HTMLInputElement).value)}455 onKeyDown={(event) => {456 if (event.key !== "Enter" || !props.ready) return;457 void handleCreate();458 }}459 />460 <Show461 when={password().length > 0 && passwordStrength() !== null}462 fallback={463 <p class="peach-newvault-hint">464 At least 12 characters. The vault is created once both fields match and pass the strength check.465 </p>466 }467 >468 <div class="peach-password-strength">469 <div class={`peach-strength-bar peach-strength-bar--${passwordStrength()}`}>470 <div class="peach-strength-fill"></div>471 </div>472 <span class="peach-strength-label">{passwordStrength()}</span>473 </div>474 </Show>475 </div>476477 <div class="peach-newvault-field">478 <label class="peach-label" for="confirm-password">479 confirm password480 </label>481 <input482 id="confirm-password"483 class="peach-underline-input peach-newvault-input"484 type={showPassword() ? "text" : "password"}485 placeholder="••••••••••••"486 autocomplete="new-password"487 value={confirmPassword()}488 disabled={!props.ready}489 onInput={(event) => setConfirmPassword((event.target as HTMLInputElement).value)}490 onKeyDown={(event) => {491 if (event.key === "Enter" && props.ready) void handleCreate();492 }}493 />494 </div>495496 <Show when={error()}>497 <p class="peach-hint peach-hint-error">{error()}</p>498 </Show>499500 <button501 class="peach-btn peach-btn--accent peach-btn--md peach-lock-submit peach-newvault-submit"502 onClick={() => void handleCreate()}503 disabled={!props.ready || loading() || !canCreate()}504 aria-live="polite"505 >506 <Show507 when={!canCreate() && createBlockerMessage()}508 fallback={loading() ? "creating..." : "create vault"}509 >510 {createBlockerMessage()}511 </Show>512 </button>513514 <p class="peach-newvault-warning">515 <span class="peach-newvault-warning-icon" aria-hidden="true">⚠</span>516 <span>Save your 12 recovery words after creating — they're the only way back in if you forget your password.</span>517 </p>518 </div>519 </section>520 </Match>521 </Switch>522 );523}524525526527type RestoreTab = "symbols" | "codex" | "csv";528529function tabLabel(tab: RestoreTab): string {530 return (531 { symbols: "PeachScript", codex: "Codex", csv: "CSV" }[tab]532 );533}534535function RestoreTabView(props: {536 hasVault: boolean;537 onOpenCodexRestore?: () => void;538 onBack: () => void;539 onUnlock: () => void | Promise<void>;540}) {541 const [activeTab, setActiveTab] = createSignal<RestoreTab>("symbols");542 const [showIntro, setShowIntro] = createSignal(false);543 const [pendingUnlock] = createSignal(false);544545 async function handleRestoreSuccess() {546 const seen = await storageGet("peach_shown_restore_intro").catch(() => null);547 if (!seen) {548 setShowIntro(true);549 } else {550 await props.onUnlock();551 }552 }553554 async function dismissIntro() {555 await storageSet("peach_shown_restore_intro", "true").catch(() => {});556 setShowIntro(false);557 await props.onUnlock();558 }559560 return (561 <section562 class="peach-screen peach-theme lock-screen lock-screen--vault-stage peach-restore-tabview"563 data-motion-phase="enter"564 >565 <RuneBackground opacity={0.05} />566567 <header class="peach-screen-header lock-screen-header">568 <PeachWordmark class="peach-wordmark-wrap" />569 <button class="peach-lock-restore-link" onClick={props.onBack}>570 ‹ back571 </button>572 </header>573574 <div class="peach-newvault-card peach-restore-tabcard">575 <div class="peach-restore-tabs" role="tablist">576 <For each={["symbols", "codex", "csv"] as RestoreTab[]}>577 {(tab) => (578 <button579 class="peach-restore-tab"580 classList={{ "is-active": activeTab() === tab }}581 onClick={() => setActiveTab(tab)}582 role="tab"583 aria-selected={activeTab() === tab}584 >585 {tabLabel(tab)}586 </button>587 )}588 </For>589 </div>590 <div class="peach-restore-content">591 <Show when={activeTab() === "symbols"}>592 <RestoreSymbols hasVault={props.hasVault} onSuccess={handleRestoreSuccess} />593 </Show>594 <Show when={activeTab() === "codex"}>595 <RestoreCodex onOpen={() => props.onOpenCodexRestore?.()} />596 </Show>597 <Show when={activeTab() === "csv"}>598 <RestoreCSV hasVault={props.hasVault} onSuccess={handleRestoreSuccess} />599 </Show>600 </div>601 </div>602603 {}604 <Show when={showIntro()}>605 <div class="peach-restore-intro-overlay">606 <div class="peach-restore-intro-card">607 <p class="peach-restore-intro-headline">welcome to peach.</p>608 <div class="peach-restore-intro-body">609 <p>Your vault lives only on this device. No server has a copy.</p>610 <p>The inline bubble fills passwords automatically when you visit sites.</p>611 <p>Export your vault from Settings before switching devices.</p>612 </div>613 <button614 class="peach-btn peach-btn--accent peach-btn--md peach-restore-intro-btn"615 onClick={() => void dismissIntro()}616 disabled={pendingUnlock()}617 >618 got it619 </button>620 </div>621 </div>622 </Show>623 </section>624 );625}626627628629function RestoreCodex(props: { onOpen: () => void }) {630 return (631 <div class="peach-restore-codex">632 <p class="peach-restore-codex-title">Restore from Peach Codex</p>633 <p class="peach-restore-codex-copy">634 Scan printed Codex pages or import the Codex PDF. Codex restore is635 always available, even before you create a vault.636 </p>637 <button638 type="button"639 class="peach-btn peach-btn--accent peach-btn--md peach-restore-codex-button"640 onClick={props.onOpen}641 >642 open Codex restore →643 </button>644 </div>645 );646}647648649650function RestoreSymbols(props: { hasVault: boolean; onSuccess: () => void | Promise<void> }) {651 const [scriptInput, setScriptInput] = createSignal("");652 const [backupPass, setBackupPass] = createSignal("");653 const [working, setWorking] = createSignal(false);654 const [animating, setAnimating] = createSignal<"chaos" | "snap" | "bloom" | null>(null);655 const [error, setError] = createSignal<string | null>(null);656 let canvasRef: HTMLCanvasElement | undefined;657 let animFrameId = 0;658 let runes: { x: number; y: number; vx: number; vy: number; char: string; size: number; angle: number; va: number }[] = [];659660 const scriptValid = createMemo(() => isPeachScript(scriptInput()));661662 function stopAnim() {663 cancelAnimationFrame(animFrameId);664 animFrameId = 0;665 }666667 function startChaos(canvas: HTMLCanvasElement) {668 const ctx = canvas.getContext("2d")!;669 const W = canvas.width;670 const H = canvas.height;671 const RUNE_CHARS = Array.from({ length: 40 }, (_, i) =>672 String.fromCodePoint(0xe000 + i)673 );674 if (runes.length === 0) {675 runes = Array.from({ length: 60 }, () => ({676 x: Math.random() * W,677 y: Math.random() * H,678 vx: (Math.random() - 0.5) * 3,679 vy: (Math.random() - 0.5) * 3,680 char: RUNE_CHARS[Math.floor(Math.random() * RUNE_CHARS.length)]!,681 size: 14 + Math.random() * 20,682 angle: Math.random() * Math.PI * 2,683 va: (Math.random() - 0.5) * 0.1,684 }));685 }686687 function draw() {688 ctx.clearRect(0, 0, W, H);689 for (const r of runes) {690 r.x = (r.x + r.vx + W) % W;691 r.y = (r.y + r.vy + H) % H;692 r.angle += r.va;693 ctx.save();694 ctx.translate(r.x, r.y);695 ctx.rotate(r.angle);696 ctx.font = `${r.size}px PeachScript, monospace`;697 const alpha = 0.5 + 0.5 * Math.sin(Date.now() / 400 + r.x);698 ctx.fillStyle = `rgba(232, 149, 109, ${alpha})`;699 ctx.shadowColor = "rgba(232, 149, 109, 0.7)";700 ctx.shadowBlur = 8;701 ctx.fillText(r.char, 0, 0);702 ctx.restore();703 }704 animFrameId = requestAnimationFrame(draw);705 }706 draw();707 }708709 function snapToGrid(canvas: HTMLCanvasElement, onDone: () => void) {710 stopAnim();711 const ctx = canvas.getContext("2d")!;712 const W = canvas.width;713 const H = canvas.height;714 const cols = 8;715 const rows = 6;716 const cellW = W / cols;717 const cellH = H / rows;718 const targets = runes.slice(0, cols * rows).map((_, i) => ({719 x: (i % cols) * cellW + cellW / 2,720 y: Math.floor(i / cols) * cellH + cellH / 2,721 }));722 const start = performance.now();723 const DURATION = 400;724725 function drawSnap(now: number) {726 const t = Math.min((now - start) / DURATION, 1);727 const ease = t < 1 ? 1 - (1 - t) ** 3 : 1;728 ctx.clearRect(0, 0, W, H);729 runes.slice(0, targets.length).forEach((r, i) => {730 const tx = targets[i]!.x;731 const ty = targets[i]!.y;732 const cx = r.x + (tx - r.x) * ease;733 const cy = r.y + (ty - r.y) * ease;734 ctx.font = `16px PeachScript, monospace`;735 ctx.fillStyle = `rgba(232, 149, 109, ${0.8 * ease})`;736 ctx.shadowColor = "rgba(232, 149, 109, 0.6)";737 ctx.shadowBlur = 6;738 ctx.fillText(r.char, cx - 8, cy + 8);739 });740 if (t < 1) {741 animFrameId = requestAnimationFrame(drawSnap);742 } else {743 onDone();744 }745 }746 animFrameId = requestAnimationFrame(drawSnap);747 }748749 function bloom(canvas: HTMLCanvasElement, onDone: () => void) {750 stopAnim();751 const ctx = canvas.getContext("2d")!;752 const W = canvas.width;753 const H = canvas.height;754 const start = performance.now();755 const DURATION = 900;756757 function drawBloom(now: number) {758 const t = Math.min((now - start) / DURATION, 1);759 ctx.clearRect(0, 0, W, H);760 761 const runeAlpha = 1 - Math.min(t / 0.4, 1);762 if (runeAlpha > 0) {763 for (const r of runes.slice(0, 48)) {764 ctx.font = `16px PeachScript, monospace`;765 ctx.fillStyle = `rgba(232, 149, 109, ${runeAlpha * 0.8})`;766 ctx.fillText(r.char, r.x - 8, r.y + 8);767 }768 }769 770 const markT = Math.max(0, (t - 0.2) / 0.5);771 const markScale = Math.min(markT * 1.2, 1);772 const markAlpha = markT < 0.5 ? markT * 2 : 2 - markT * 2;773 if (markAlpha > 0) {774 ctx.save();775 ctx.globalAlpha = markAlpha;776 ctx.shadowColor = `rgba(217, 104, 48, ${markAlpha * 0.8})`;777 ctx.shadowBlur = 30;778 ctx.translate(W / 2, H / 2);779 ctx.scale(markScale, markScale);780 ctx.drawImage(peachMarkImg, -32, -32, 64, 64);781 ctx.restore();782 }783 if (t < 1) {784 animFrameId = requestAnimationFrame(drawBloom);785 } else {786 onDone();787 }788 }789 animFrameId = requestAnimationFrame(drawBloom);790 }791792 onCleanup(() => stopAnim());793794 async function handleRestore() {795 if (!scriptValid() || !backupPass().trim() || working()) return;796 setError(null);797 setWorking(true);798 setAnimating("chaos");799800 const canvas = canvasRef;801 if (canvas) startChaos(canvas);802803 try {804 const bytes = decodePeachScript(normalisePeachScript(scriptInput()));805 const payload = await parsePayload(bytes, backupPass());806807 if (!props.hasVault) {808 const cr = await sendMessage({ type: "CREATE_VAULT", payload: { password: backupPass() } });809 if (!(cr as { ok: boolean }).ok) throw new Error("CREATE_VAULT_FAILED");810 }811812 const rr = await sendMessage({813 type: "RESTORE_ENTRIES",814 payload: { entries: payload.entries, mode: "merge", settings: payload.settings },815 });816 if (!(rr as { ok: boolean }).ok) throw new Error((rr as { error?: string }).error ?? "RESTORE_FAILED");817818 if (payload.license?.key) {819 await sendMessage({ type: "ACTIVATE_LICENSE", payload: { key: payload.license.key } }).catch(() => {});820 }821822 setAnimating("snap");823 stopAnim();824 if (canvas) {825 snapToGrid(canvas, () => {826 setAnimating("bloom");827 bloom(canvas, async () => {828 setAnimating(null);829 await props.onSuccess();830 });831 });832 } else {833 await props.onSuccess();834 }835 } catch (err) {836 stopAnim();837 setAnimating(null);838 const code = err instanceof Error ? err.message : String(err);839 setError(840 code === "INVALID_PASSPHRASE" || code === "INVALID_EXPORT_PASSWORD"841 ? "That passphrase didn't work."842 : code === "CREATE_VAULT_FAILED"843 ? "Couldn't create a new local vault."844 : "Could not read this backup.",845 );846 } finally {847 setWorking(false);848 }849 }850851 return (852 <div class="peach-rt-symbols">853 <Show when={animating() !== null}>854 <canvas855 ref={(el) => { canvasRef = el; }}856 class="peach-rt-anim-canvas"857 width={280}858 height={200}859 />860 </Show>861 <Show when={animating() === null}>862 <textarea863 class="peach-restore-symbols-textarea"864 placeholder="paste peachscript…"865 rows={3}866 value={scriptInput()}867 onInput={(e) => setScriptInput((e.target as HTMLTextAreaElement).value)}868 />869 <div class="peach-rt-divider">— or —</div>870 <label class="peach-btn peach-btn--ghost peach-btn--sm peach-rt-file-label">871 open .peach file872 <input873 type="file"874 accept=".peach,text/plain"875 style="display:none"876 onChange={async (e) => {877 const file = (e.currentTarget as HTMLInputElement).files?.[0];878 if (!file) return;879 try {880 setScriptInput(await file.text());881 } catch {882 setError("Couldn't read file.");883 } finally {884 (e.currentTarget as HTMLInputElement).value = "";885 }886 }}887 />888 </label>889 <input890 class="peach-restore-symbols-pass"891 type="password"892 placeholder="backup password"893 value={backupPass()}894 onInput={(e) => setBackupPass((e.target as HTMLInputElement).value)}895 onKeyDown={(e) => {896 if (e.key === "Enter" && scriptValid() && backupPass().trim() && !working()) {897 e.preventDefault();898 void handleRestore();899 }900 }}901 />902 <button903 class="peach-btn peach-btn--accent peach-btn--md peach-rt-submit"904 onClick={() => void handleRestore()}905 disabled={!scriptValid() || !backupPass().trim() || working()}906 >907 restore vault →908 </button>909 <Show when={error()}>910 <p class="peach-rt-error">{error()}</p>911 </Show>912 </Show>913 </div>914 );915}916917918919function RestoreCSV(props: { hasVault: boolean; onSuccess: () => void | Promise<void> }) {920 const [importing, setImporting] = createSignal(false);921 const [error, setError] = createSignal<string | null>(null);922 923 924 925 926 const CSV_MIN_PASSWORD_LENGTH = 12;927 const [newPass, setNewPass] = createSignal("");928 const [confirmPass, setConfirmPass] = createSignal("");929 const needsPassword = () => props.hasVault === false;930 const passwordReady = () =>931 !needsPassword() ||932 (newPass().length >= CSV_MIN_PASSWORD_LENGTH && newPass() === confirmPass());933934 async function handleFile(e: Event) {935 const input = e.currentTarget as HTMLInputElement;936 const file = input.files?.[0];937 input.value = "";938 if (!file) return;939 if (needsPassword() && newPass().length < CSV_MIN_PASSWORD_LENGTH) {940 setError(`Set a master password of at least ${CSV_MIN_PASSWORD_LENGTH} characters first.`);941 return;942 }943 if (needsPassword() && newPass() !== confirmPass()) {944 setError("Passwords do not match.");945 return;946 }947 setImporting(true);948 setError(null);949 try {950 const text = await file.text();951 const parsed = await parseImportSource(text);952 if (parsed.entries.length === 0) throw new Error("NO_ENTRIES");953954 if (props.hasVault === false) {955 956 957 const cr = await sendMessage({ type: "CREATE_VAULT", payload: { password: newPass() } });958 if (!(cr as { ok: boolean }).ok) throw new Error("CREATE_VAULT_FAILED");959 }960961 const res = await sendMessage({ type: "BATCH_ADD_ENTRIES", payload: { entries: parsed.entries } });962 if (!(res as { ok: boolean }).ok) throw new Error("IMPORT_FAILED");963 if (parsed.licenseKey) {964 await sendMessage({ type: "ACTIVATE_LICENSE", payload: { key: parsed.licenseKey } }).catch(() => {});965 }966 await props.onSuccess();967 } catch (err) {968 const code = err instanceof Error ? err.message : String(err);969 setError(970 code === "NO_ENTRIES" ? "No entries found in this file." :971 code === "CREATE_VAULT_FAILED" ? "Couldn't create a new local vault." :972 "Import failed. Check the file format and try again."973 );974 } finally {975 setImporting(false);976 }977 }978979 return (980 <div class="peach-rt-csv">981 <Show when={needsPassword()}>982 <input983 class="peach-restore-symbols-pass"984 type="password"985 placeholder="new master password"986 value={newPass()}987 onInput={(e) => setNewPass((e.target as HTMLInputElement).value)}988 />989 <input990 class="peach-restore-symbols-pass"991 type="password"992 placeholder="confirm master password"993 value={confirmPass()}994 onInput={(e) => setConfirmPass((e.target as HTMLInputElement).value)}995 />996 </Show>997 <label998 class="peach-btn peach-btn--accent peach-btn--md peach-rt-csv-btn"999 classList={{ "is-busy": importing(), "is-disabled": !passwordReady() }}1000 >1001 {importing() ? "importing…" : "open csv file"}1002 <input1003 type="file"1004 accept=".csv,.json,.peach,application/x-peach"1005 style="display:none"1006 onChange={handleFile}1007 disabled={importing() || !passwordReady()}1008 />1009 </label>1010 <p class="peach-rt-csv-sources">1011 Imports from Bitwarden, 1Password, Proton Pass,<br />1012 Chrome, Safari, and Edge.1013 </p>1014 <p class="peach-rt-csv-warning">PLAIN-TEXT — DELETE THE FILE AFTER IMPORT</p>1015 <Show when={error()}>1016 <p class="peach-rt-error">{error()}</p>1017 </Show>1018 </div>1019 );1020}1021102210231024function getDisplayError(error: string | undefined, fallback: string): string {1025 if (!error) return fallback;1026 if (1027 error === "SERVICE_WORKER_UNAVAILABLE" ||1028 error.includes("Receiving end does not exist") ||1029 error.includes("message port closed")1030 ) {1031 return "background service unavailable";1032 }1033 return error;1034}