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}6263type RestoreSurface = "restore" | null;64type RecoverSurface = "words" | "new-password" | null;6566export function LockView(props: LockProps) {67 const [password, setPassword] = createSignal("");68 const [confirmPassword, setConfirmPassword] = createSignal("");69 const [error, setError] = createSignal("");70 const [loading, setLoading] = createSignal(false);71 const [restoreSurface, setRestoreSurface] = createSignal<RestoreSurface>(null);72 const [showPassword, setShowPassword] = createSignal(false);73 const [recoverSurface, setRecoverSurface] = createSignal<RecoverSurface>(null);74 75 76 const [showRecoveryWords, setShowRecoveryWords] = createSignal(props.forceRecoveryWords ?? false);7778 const MIN_LENGTH = 12;79 const MIN_ZXCVBN_SCORE = 2;8081 const [strengthScore, setStrengthScore] = createSignal<number | null>(null);82 const [biometricAvailable, setBiometricAvailable] = createSignal(false);83 const [biometricBusy, setBiometricBusy] = createSignal(false);8485 const canCreate = createMemo(86 () =>87 password().length >= MIN_LENGTH &&88 confirmPassword().length >= MIN_LENGTH &&89 password() === confirmPassword() &&90 strengthScore() !== null &&91 strengthScore()! >= MIN_ZXCVBN_SCORE92 );9394 const passwordStrength = createMemo(() => {95 const score = strengthScore();96 if (score === null) return null;97 if (score <= 1) return "weak";98 if (score === 2) return "fair";99 if (score === 3) return "good";100 return "strong";101 });102103 const createBlockerMessage = createMemo(() => {104 if (!password()) return null;105 if (password().length < MIN_LENGTH) return `need ${MIN_LENGTH - password().length} more characters`;106 if (!confirmPassword()) return "confirm your password";107 if (password() !== confirmPassword()) return "passwords don't match";108 if (strengthScore() === null) return "checking strength…";109 if (strengthScore()! < MIN_ZXCVBN_SCORE) return "password too weak — add words or length";110 return null;111 });112113 114 createMemo(() => {115 const value = password();116 if (!value) { setStrengthScore(null); return; }117 getZxcvbn().then((zxcvbn) => {118 if (password() === value) setStrengthScore(zxcvbn(value).score);119 }).catch(() => {120 121 if (password() === value) setStrengthScore(value.length >= 16 ? 3 : value.length >= 12 ? 2 : 1);122 });123 });124125 async function handleUnlock() {126 if (!password().trim()) return;127 setLoading(true);128 setError("");129 const response = await sendMessage({130 type: "UNLOCK",131 payload: { password: password() },132 });133 const result = response as { ok: boolean; error?: string };134 if (result.ok) {135 await props.onUnlock();136 setLoading(false);137 return;138 }139 setError(getDisplayError(result.error, "incorrect password"));140 setPassword("");141 const passwordField = document.querySelector(".lock-password-input") as HTMLInputElement | undefined;142 passwordField?.classList.add("shake");143 setTimeout(() => passwordField?.classList.remove("shake"), 300);144 setLoading(false);145 }146147 async function checkBiometricAvailable(): Promise<void> {148 if (!props.hasVault || !isNativePlatform()) return;149 const keystore = nativePlugin<{ hasMasterKey: () => Promise<{ exists: boolean }> }>("KeystorePlugin");150 const biometric = nativePlugin<{ isAvailable: () => Promise<{ available: boolean }> }>("BiometricPlugin");151 if (!keystore || !biometric) return;152 try {153 const stored = await keystore.hasMasterKey();154 if (!stored.exists) return;155 const avail = await biometric.isAvailable();156 if (!avail.available) return;157 setBiometricAvailable(true);158 window.setTimeout(() => { void handleBiometricUnlock(); }, 400);159 } catch { }160 }161162 async function handleBiometricUnlock(): Promise<void> {163 if (biometricBusy()) return;164 const biometric = nativePlugin<{ authenticate: (opts: Record<string, string>) => Promise<void> }>("BiometricPlugin");165 const keystore = nativePlugin<{ retrieveMasterKey: () => Promise<{ masterKeyHex: string }> }>("KeystorePlugin");166 if (!biometric || !keystore) return;167 setBiometricBusy(true);168 setError("");169 try {170 await biometric.authenticate({171 title: "Unlock Peach",172 subtitle: "Use biometrics to access your vault",173 negativeButtonText: "Use Password",174 });175 const { masterKeyHex } = await keystore.retrieveMasterKey();176 const res = (await sendMessage({177 type: "UNLOCK_WITH_KEY",178 payload: { masterKeyHex },179 })) as { ok: boolean; error?: string };180 if (res.ok) {181 await props.onUnlock();182 return;183 }184 if (res.error === "biometric_key_invalidated") {185 await sendMessage({186 type: "UPDATE_SETTINGS",187 payload: { biometricsEnabled: false },188 });189 setBiometricAvailable(false);190 setError("biometric key expired — re-enable in settings");191 } else {192 setError("biometric unlock failed");193 }194 } catch (e) {195 const reason = e instanceof Error ? e.message : String(e);196 if (reason.includes("user_cancelled")) return;197 if (reason.includes("biometric_key_invalidated")) {198 await sendMessage({199 type: "UPDATE_SETTINGS",200 payload: { biometricsEnabled: false },201 });202 setBiometricAvailable(false);203 setError("biometric key expired — re-enable in settings");204 return;205 }206 if (reason.includes("biometric_lockout")) {207 setError("biometric locked out — use your password");208 }209 } finally {210 setBiometricBusy(false);211 }212 }213214 onMount(() => { void checkBiometricAvailable(); });215216 async function handleCreate() {217 if (!password().trim()) return;218 if (password().length < MIN_LENGTH) {219 setError(`password must be at least ${MIN_LENGTH} characters`);220 return;221 }222 if (password() !== confirmPassword()) {223 setError("passwords do not match");224 return;225 }226 const score = strengthScore();227 if (score === null || score < MIN_ZXCVBN_SCORE) {228 setError("password is too weak — try a longer or more varied passphrase");229 return;230 }231 setLoading(true);232 setError("");233 const response = await sendMessage({234 type: "CREATE_VAULT",235 payload: { password: password() },236 });237 const result = response as { ok: boolean; error?: string };238 if (result.ok) {239 240 241 242 243 244 try {245 await chrome.storage.local?.set({ peach_recovery_pending: "1" });246 } catch { }247 setShowRecoveryWords(true);248 setLoading(false);249 return;250 }251 setError(getDisplayError(result.error, "failed to create vault"));252 setLoading(false);253 }254255 function openRestore(surface: Exclude<RestoreSurface, null>) {256 if (!props.ready || loading()) return;257 setPassword("");258 setConfirmPassword("");259 setError("");260 setRestoreSurface(surface);261 }262263 264 return (265 <Switch>266 {}267 <Match when={restoreSurface() === "restore"}>268 <RestoreTabView269 hasVault={props.hasVault}270 onOpenCodexRestore={props.onOpenCodexRestore}271 onBack={() => setRestoreSurface(null)}272 onUnlock={async () => {273 setRestoreSurface(null);274 await props.onUnlock();275 }}276 />277 </Match>278279 {}280 <Match when={showRecoveryWords() && (!props.hasVault || props.forceRecoveryWords)}>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 <header class="peach-screen-header lock-screen-header">298 <div class="peach-wordmark-stack">299 <PeachWordmark class="peach-wordmark-wrap" />300 <Show when={props.isPro}>301 <span class="peach-pro-mini-badge">pro</span>302 </Show>303 </div>304 </header>305306 <div class="peach-lock-hero peach-lock-hero--unlock">307 <div class="peach-lock-hero-art" aria-hidden="true">308 <PeachMark class="peach-lock-hero-mark" />309 </div>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 <LockRuneCanvas />319320 <section class="peach-lock-panel peach-lock-panel--unlock peach-glass">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 />339340 <Show when={error()}>341 <p class="peach-hint peach-hint-error">{error()}</p>342 </Show>343344 <button345 class="peach-btn peach-btn--accent peach-btn--md peach-lock-submit"346 onClick={() => void handleUnlock()}347 disabled={!props.ready || loading()}348 >349 {loading() ? "unlocking..." : "unlock"}350 </button>351352 <Show when={biometricAvailable()}>353 <button354 class="peach-biometric-btn"355 type="button"356 onClick={() => void handleBiometricUnlock()}357 disabled={biometricBusy() || loading()}358 aria-label="Unlock with biometrics"359 >360 <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">361 <path d="M12 11c-1.7 0-3 1.3-3 3v3"/>362 <path d="M15 17v-3"/>363 <path d="M9 4.5C9.7 4.2 10.8 4 12 4s2.3.2 3 .5"/>364 <path d="M5 9c.7-1.6 2-2.9 3.6-3.6"/>365 <path d="M19 9c-.7-1.6-2-2.9-3.6-3.6"/>366 <path d="M5 15c0-1.7.3-3.3.8-4.7"/>367 <path d="M19 15c0-1.7-.3-3.3-.8-4.7"/>368 </svg>369 {biometricBusy() ? "verifying…" : "use biometrics"}370 </button>371 </Show>372373 <button374 class="peach-lock-recover-link"375 type="button"376 onClick={() => setRecoverSurface("words")}377 >378 forgot your password?379 </button>380 </section>381 </section>382 </Match>383384 {}385 <Match when={true}>386 <section387 class="peach-screen peach-theme lock-screen lock-screen--vault-stage peach-newvault"388 data-motion-phase="enter"389 >390 <header class="peach-screen-header peach-newvault-header">391 <Show when={props.onBackToOnboarding}>392 <button393 class="peach-newvault-back"394 type="button"395 onClick={() => props.onBackToOnboarding?.()}396 aria-label="Back to onboarding"397 >398 <svg width="11" height="11" viewBox="0 0 11 11" fill="none" stroke="currentColor" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round">399 <path d="M7 2L3 5.5L7 9" />400 </svg>401 back402 </button>403 </Show>404 <div class="peach-wordmark-stack">405 <PeachWordmark class="peach-wordmark-wrap" />406 <Show when={props.isPro}>407 <span class="peach-pro-mini-badge">pro</span>408 </Show>409 </div>410 </header>411412 <div class="peach-newvault-mark" aria-hidden="true">413 <PeachMark class="peach-newvault-mark-art" />414 </div>415416 <div class="peach-newvault-card">417 <h1 class="peach-newvault-headline">{"keep your\nsecrets."}</h1>418 <hr class="peach-newvault-divider" />419420 <div class="peach-newvault-field">421 <div class="peach-newvault-label-row">422 <label class="peach-label" for="master-password">423 master password424 </label>425 <button426 class="peach-lock-reveal-btn"427 type="button"428 onClick={() => setShowPassword((value) => !value)}429 aria-label={showPassword() ? "Hide password" : "Show password"}430 >431 <Show432 when={showPassword()}433 fallback={434 <svg width="15" height="10" viewBox="0 0 14 10" fill="none" stroke="currentColor" stroke-width="0.9" stroke-linecap="round">435 <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" />436 <circle cx="7" cy="5" r="1.75" />437 </svg>438 }439 >440 <svg width="15" height="10" viewBox="0 0 14 10" fill="none" stroke="currentColor" stroke-width="0.9" stroke-linecap="round">441 <path d="M1 2C3 4.5 5 6 7 6C9 6 11 4.5 13 2" />442 <path d="M3.5 5.5L2.5 7.5" />443 <path d="M7 6.5V8.5" />444 <path d="M10.5 5.5L11.5 7.5" />445 </svg>446 </Show>447 {showPassword() ? "hide" : "show"}448 </button>449 </div>450 <input451 id="master-password"452 class="peach-underline-input peach-newvault-input lock-password-input"453 type={showPassword() ? "text" : "password"}454 placeholder="••••••••••••"455 autocomplete="new-password"456 value={password()}457 disabled={!props.ready}458 onInput={(event) => setPassword((event.target as HTMLInputElement).value)}459 onKeyDown={(event) => {460 if (event.key !== "Enter" || !props.ready) return;461 void handleCreate();462 }}463 />464 <Show465 when={password().length > 0 && passwordStrength() !== null}466 fallback={467 <p class="peach-newvault-hint">at least 12 characters</p>468 }469 >470 <div class="peach-password-strength">471 <div class={`peach-strength-bar peach-strength-bar--${passwordStrength()}`}>472 <div class="peach-strength-fill"></div>473 </div>474 <span class="peach-strength-label">{passwordStrength()}</span>475 </div>476 </Show>477 </div>478479 <div class="peach-newvault-field">480 <label class="peach-label" for="confirm-password">481 confirm password482 </label>483 <input484 id="confirm-password"485 class="peach-underline-input peach-newvault-input"486 type={showPassword() ? "text" : "password"}487 placeholder="••••••••••••"488 autocomplete="new-password"489 value={confirmPassword()}490 disabled={!props.ready}491 onInput={(event) => setConfirmPassword((event.target as HTMLInputElement).value)}492 onKeyDown={(event) => {493 if (event.key === "Enter" && props.ready) void handleCreate();494 }}495 />496 </div>497498 <Show when={error()}>499 <p class="peach-hint peach-hint-error">{error()}</p>500 </Show>501502 <button503 class="peach-btn peach-btn--accent peach-btn--md peach-lock-submit peach-newvault-submit"504 onClick={() => void handleCreate()}505 disabled={!props.ready || loading() || !canCreate()}506 aria-live="polite"507 >508 <Show509 when={!canCreate() && createBlockerMessage()}510 fallback={loading() ? "creating..." : "create vault"}511 >512 {createBlockerMessage()}513 </Show>514 </button>515516 <p class="peach-newvault-warning">517 <span class="peach-newvault-warning-icon" aria-hidden="true">⚠</span>518 <span>Save your 12 recovery words right after you create the vault — they're the only way in if you forget your password.</span>519 </p>520 </div>521522 <div class="peach-newvault-footer">523 <p class="peach-hint">Already have a backup?</p>524 <button525 class="peach-lock-restore-link"526 onClick={() => void openRestore("restore")}527 disabled={!props.ready}528 >529 › restore from backup530 </button>531 <Show when={props.onOpenCodexRestore}>532 <button533 class="peach-lock-restore-link"534 onClick={() => props.onOpenCodexRestore?.()}535 disabled={!props.ready}536 >537 › restore from peach codex538 </button>539 </Show>540 </div>541 </section>542 </Match>543 </Switch>544 );545}546547548549type RestoreTab = "symbols" | "codex" | "csv";550551function tabLabel(tab: RestoreTab): string {552 return (553 { symbols: "PeachScript", codex: "Codex", csv: "CSV" }[tab]554 );555}556557function RestoreTabView(props: {558 hasVault: boolean;559 onOpenCodexRestore?: () => void;560 onBack: () => void;561 onUnlock: () => void | Promise<void>;562}) {563 const [activeTab, setActiveTab] = createSignal<RestoreTab>("symbols");564 const [showIntro, setShowIntro] = createSignal(false);565 const [pendingUnlock] = createSignal(false);566567 async function handleRestoreSuccess() {568 const seen = await storageGet("peach_shown_restore_intro").catch(() => null);569 if (!seen) {570 setShowIntro(true);571 } else {572 await props.onUnlock();573 }574 }575576 async function dismissIntro() {577 await storageSet("peach_shown_restore_intro", "true").catch(() => {});578 setShowIntro(false);579 await props.onUnlock();580 }581582 return (583 <section584 class="peach-screen peach-theme lock-screen lock-screen--vault-stage peach-restore-tabview"585 data-motion-phase="enter"586 >587 <RuneBackground opacity={0.05} />588589 <header class="peach-screen-header lock-screen-header">590 <PeachWordmark class="peach-wordmark-wrap" />591 <button class="peach-lock-restore-link" onClick={props.onBack}>592 ‹ back593 </button>594 </header>595596 <div class="peach-newvault-card peach-restore-tabcard">597 <div class="peach-restore-tabs" role="tablist">598 <For each={["symbols", "codex", "csv"] as RestoreTab[]}>599 {(tab) => (600 <button601 class="peach-restore-tab"602 classList={{ "is-active": activeTab() === tab }}603 onClick={() => setActiveTab(tab)}604 role="tab"605 aria-selected={activeTab() === tab}606 >607 {tabLabel(tab)}608 </button>609 )}610 </For>611 </div>612 <div class="peach-restore-content">613 <Show when={activeTab() === "symbols"}>614 <RestoreSymbols hasVault={props.hasVault} onSuccess={handleRestoreSuccess} />615 </Show>616 <Show when={activeTab() === "codex"}>617 <RestoreCodex onOpen={() => props.onOpenCodexRestore?.()} />618 </Show>619 <Show when={activeTab() === "csv"}>620 <RestoreCSV hasVault={props.hasVault} onSuccess={handleRestoreSuccess} />621 </Show>622 </div>623 </div>624625 {}626 <Show when={showIntro()}>627 <div class="peach-restore-intro-overlay">628 <div class="peach-restore-intro-card">629 <p class="peach-restore-intro-headline">welcome to peach.</p>630 <div class="peach-restore-intro-body">631 <p>Your vault lives only on this device. No server has a copy.</p>632 <p>The inline bubble fills passwords automatically when you visit sites.</p>633 <p>Export your vault from Settings before switching devices.</p>634 </div>635 <button636 class="peach-btn peach-btn--accent peach-btn--md peach-restore-intro-btn"637 onClick={() => void dismissIntro()}638 disabled={pendingUnlock()}639 >640 got it641 </button>642 </div>643 </div>644 </Show>645 </section>646 );647}648649650651function RestoreCodex(props: { onOpen: () => void }) {652 return (653 <div class="peach-restore-codex">654 <p class="peach-restore-codex-title">Restore from Peach Codex</p>655 <p class="peach-restore-codex-copy">656 Scan printed Codex pages or import the Codex PDF. Codex restore is657 always available, even before you create a vault.658 </p>659 <button660 type="button"661 class="peach-btn peach-btn--accent peach-btn--md peach-restore-codex-button"662 onClick={props.onOpen}663 >664 open Codex restore →665 </button>666 </div>667 );668}669670671672function RestoreSymbols(props: { hasVault: boolean; onSuccess: () => void | Promise<void> }) {673 const [scriptInput, setScriptInput] = createSignal("");674 const [backupPass, setBackupPass] = createSignal("");675 const [working, setWorking] = createSignal(false);676 const [animating, setAnimating] = createSignal<"chaos" | "snap" | "bloom" | null>(null);677 const [error, setError] = createSignal<string | null>(null);678 let canvasRef: HTMLCanvasElement | undefined;679 let animFrameId = 0;680 let runes: { x: number; y: number; vx: number; vy: number; char: string; size: number; angle: number; va: number }[] = [];681682 const scriptValid = createMemo(() => isPeachScript(scriptInput()));683684 function stopAnim() {685 cancelAnimationFrame(animFrameId);686 animFrameId = 0;687 }688689 function startChaos(canvas: HTMLCanvasElement) {690 const ctx = canvas.getContext("2d")!;691 const W = canvas.width;692 const H = canvas.height;693 const RUNE_CHARS = Array.from({ length: 40 }, (_, i) =>694 String.fromCodePoint(0xe000 + i)695 );696 if (runes.length === 0) {697 runes = Array.from({ length: 60 }, () => ({698 x: Math.random() * W,699 y: Math.random() * H,700 vx: (Math.random() - 0.5) * 3,701 vy: (Math.random() - 0.5) * 3,702 char: RUNE_CHARS[Math.floor(Math.random() * RUNE_CHARS.length)]!,703 size: 14 + Math.random() * 20,704 angle: Math.random() * Math.PI * 2,705 va: (Math.random() - 0.5) * 0.1,706 }));707 }708709 function draw() {710 ctx.clearRect(0, 0, W, H);711 for (const r of runes) {712 r.x = (r.x + r.vx + W) % W;713 r.y = (r.y + r.vy + H) % H;714 r.angle += r.va;715 ctx.save();716 ctx.translate(r.x, r.y);717 ctx.rotate(r.angle);718 ctx.font = `${r.size}px PeachScript, monospace`;719 const alpha = 0.5 + 0.5 * Math.sin(Date.now() / 400 + r.x);720 ctx.fillStyle = `rgba(232, 149, 109, ${alpha})`;721 ctx.shadowColor = "rgba(232, 149, 109, 0.7)";722 ctx.shadowBlur = 8;723 ctx.fillText(r.char, 0, 0);724 ctx.restore();725 }726 animFrameId = requestAnimationFrame(draw);727 }728 draw();729 }730731 function snapToGrid(canvas: HTMLCanvasElement, onDone: () => void) {732 stopAnim();733 const ctx = canvas.getContext("2d")!;734 const W = canvas.width;735 const H = canvas.height;736 const cols = 8;737 const rows = 6;738 const cellW = W / cols;739 const cellH = H / rows;740 const targets = runes.slice(0, cols * rows).map((_, i) => ({741 x: (i % cols) * cellW + cellW / 2,742 y: Math.floor(i / cols) * cellH + cellH / 2,743 }));744 const start = performance.now();745 const DURATION = 400;746747 function drawSnap(now: number) {748 const t = Math.min((now - start) / DURATION, 1);749 const ease = t < 1 ? 1 - Math.pow(1 - t, 3) : 1;750 ctx.clearRect(0, 0, W, H);751 runes.slice(0, targets.length).forEach((r, i) => {752 const tx = targets[i]!.x;753 const ty = targets[i]!.y;754 const cx = r.x + (tx - r.x) * ease;755 const cy = r.y + (ty - r.y) * ease;756 ctx.font = `16px PeachScript, monospace`;757 ctx.fillStyle = `rgba(232, 149, 109, ${0.8 * ease})`;758 ctx.shadowColor = "rgba(232, 149, 109, 0.6)";759 ctx.shadowBlur = 6;760 ctx.fillText(r.char, cx - 8, cy + 8);761 });762 if (t < 1) {763 animFrameId = requestAnimationFrame(drawSnap);764 } else {765 onDone();766 }767 }768 animFrameId = requestAnimationFrame(drawSnap);769 }770771 function bloom(canvas: HTMLCanvasElement, onDone: () => void) {772 stopAnim();773 const ctx = canvas.getContext("2d")!;774 const W = canvas.width;775 const H = canvas.height;776 const start = performance.now();777 const DURATION = 900;778779 function drawBloom(now: number) {780 const t = Math.min((now - start) / DURATION, 1);781 ctx.clearRect(0, 0, W, H);782 783 const runeAlpha = 1 - Math.min(t / 0.4, 1);784 if (runeAlpha > 0) {785 for (const r of runes.slice(0, 48)) {786 ctx.font = `16px PeachScript, monospace`;787 ctx.fillStyle = `rgba(232, 149, 109, ${runeAlpha * 0.8})`;788 ctx.fillText(r.char, r.x - 8, r.y + 8);789 }790 }791 792 const markT = Math.max(0, (t - 0.2) / 0.5);793 const markScale = Math.min(markT * 1.2, 1);794 const markAlpha = markT < 0.5 ? markT * 2 : 2 - markT * 2;795 if (markAlpha > 0) {796 ctx.save();797 ctx.globalAlpha = markAlpha;798 ctx.shadowColor = `rgba(217, 104, 48, ${markAlpha * 0.8})`;799 ctx.shadowBlur = 30;800 ctx.translate(W / 2, H / 2);801 ctx.scale(markScale, markScale);802 ctx.drawImage(peachMarkImg, -32, -32, 64, 64);803 ctx.restore();804 }805 if (t < 1) {806 animFrameId = requestAnimationFrame(drawBloom);807 } else {808 onDone();809 }810 }811 animFrameId = requestAnimationFrame(drawBloom);812 }813814 onCleanup(() => stopAnim());815816 async function handleRestore() {817 if (!scriptValid() || !backupPass().trim() || working()) return;818 setError(null);819 setWorking(true);820 setAnimating("chaos");821822 const canvas = canvasRef;823 if (canvas) startChaos(canvas);824825 try {826 const bytes = decodePeachScript(normalisePeachScript(scriptInput()));827 const payload = await parsePayload(bytes, backupPass());828829 if (!props.hasVault) {830 const cr = await sendMessage({ type: "CREATE_VAULT", payload: { password: backupPass() } });831 if (!(cr as { ok: boolean }).ok) throw new Error("CREATE_VAULT_FAILED");832 }833834 const rr = await sendMessage({835 type: "RESTORE_ENTRIES",836 payload: { entries: payload.entries, mode: "merge", settings: payload.settings },837 });838 if (!(rr as { ok: boolean }).ok) throw new Error((rr as { error?: string }).error ?? "RESTORE_FAILED");839840 if (payload.license?.key) {841 await sendMessage({ type: "ACTIVATE_LICENSE", payload: { key: payload.license.key } }).catch(() => {});842 }843844 setAnimating("snap");845 stopAnim();846 if (canvas) {847 snapToGrid(canvas, () => {848 setAnimating("bloom");849 bloom(canvas, async () => {850 setAnimating(null);851 await props.onSuccess();852 });853 });854 } else {855 await props.onSuccess();856 }857 } catch (err) {858 stopAnim();859 setAnimating(null);860 const code = err instanceof Error ? err.message : String(err);861 setError(862 code === "INVALID_PASSPHRASE" || code === "INVALID_EXPORT_PASSWORD"863 ? "That passphrase didn't work."864 : code === "CREATE_VAULT_FAILED"865 ? "Couldn't create a new local vault."866 : "Could not read this backup.",867 );868 } finally {869 setWorking(false);870 }871 }872873 return (874 <div class="peach-rt-symbols">875 <Show when={animating() !== null}>876 <canvas877 ref={(el) => { canvasRef = el; }}878 class="peach-rt-anim-canvas"879 width={280}880 height={200}881 />882 </Show>883 <Show when={animating() === null}>884 <textarea885 class="peach-restore-symbols-textarea"886 placeholder="paste peachscript…"887 rows={3}888 value={scriptInput()}889 onInput={(e) => setScriptInput((e.target as HTMLTextAreaElement).value)}890 />891 <div class="peach-rt-divider">— or —</div>892 <label class="peach-btn peach-btn--ghost peach-btn--sm peach-rt-file-label">893 open .peach file894 <input895 type="file"896 accept=".peach,text/plain"897 style="display:none"898 onChange={async (e) => {899 const file = (e.currentTarget as HTMLInputElement).files?.[0];900 if (!file) return;901 try {902 setScriptInput(await file.text());903 } catch {904 setError("Couldn't read file.");905 } finally {906 (e.currentTarget as HTMLInputElement).value = "";907 }908 }}909 />910 </label>911 <input912 class="peach-restore-symbols-pass"913 type="password"914 placeholder="backup password"915 value={backupPass()}916 onInput={(e) => setBackupPass((e.target as HTMLInputElement).value)}917 onKeyDown={(e) => {918 if (e.key === "Enter" && scriptValid() && backupPass().trim() && !working()) {919 e.preventDefault();920 void handleRestore();921 }922 }}923 />924 <button925 class="peach-btn peach-btn--accent peach-btn--md peach-rt-submit"926 onClick={() => void handleRestore()}927 disabled={!scriptValid() || !backupPass().trim() || working()}928 >929 restore vault →930 </button>931 <Show when={error()}>932 <p class="peach-rt-error">{error()}</p>933 </Show>934 </Show>935 </div>936 );937}938939940941function RestoreCSV(props: { hasVault: boolean; onSuccess: () => void | Promise<void> }) {942 const [importing, setImporting] = createSignal(false);943 const [error, setError] = createSignal<string | null>(null);944 945 946 947 948 const CSV_MIN_PASSWORD_LENGTH = 12;949 const [newPass, setNewPass] = createSignal("");950 const [confirmPass, setConfirmPass] = createSignal("");951 const needsPassword = () => props.hasVault === false;952 const passwordReady = () =>953 !needsPassword() ||954 (newPass().length >= CSV_MIN_PASSWORD_LENGTH && newPass() === confirmPass());955956 async function handleFile(e: Event) {957 const input = e.currentTarget as HTMLInputElement;958 const file = input.files?.[0];959 input.value = "";960 if (!file) return;961 if (needsPassword() && newPass().length < CSV_MIN_PASSWORD_LENGTH) {962 setError(`Set a master password of at least ${CSV_MIN_PASSWORD_LENGTH} characters first.`);963 return;964 }965 if (needsPassword() && newPass() !== confirmPass()) {966 setError("Passwords do not match.");967 return;968 }969 setImporting(true);970 setError(null);971 try {972 const text = await file.text();973 const parsed = await parseImportSource(text);974 if (parsed.entries.length === 0) throw new Error("NO_ENTRIES");975976 if (props.hasVault === false) {977 978 979 const cr = await sendMessage({ type: "CREATE_VAULT", payload: { password: newPass() } });980 if (!(cr as { ok: boolean }).ok) throw new Error("CREATE_VAULT_FAILED");981 }982983 const res = await sendMessage({ type: "BATCH_ADD_ENTRIES", payload: { entries: parsed.entries } });984 if (!(res as { ok: boolean }).ok) throw new Error("IMPORT_FAILED");985 if (parsed.licenseKey) {986 await sendMessage({ type: "ACTIVATE_LICENSE", payload: { key: parsed.licenseKey } }).catch(() => {});987 }988 await props.onSuccess();989 } catch (err) {990 const code = err instanceof Error ? err.message : String(err);991 setError(992 code === "NO_ENTRIES" ? "No entries found in this file." :993 code === "CREATE_VAULT_FAILED" ? "Couldn't create a new local vault." :994 "Import failed. Check the file format and try again."995 );996 } finally {997 setImporting(false);998 }999 }10001001 return (1002 <div class="peach-rt-csv">1003 <Show when={needsPassword()}>1004 <input1005 class="peach-restore-symbols-pass"1006 type="password"1007 placeholder="new master password"1008 value={newPass()}1009 onInput={(e) => setNewPass((e.target as HTMLInputElement).value)}1010 />1011 <input1012 class="peach-restore-symbols-pass"1013 type="password"1014 placeholder="confirm master password"1015 value={confirmPass()}1016 onInput={(e) => setConfirmPass((e.target as HTMLInputElement).value)}1017 />1018 </Show>1019 <label1020 class="peach-btn peach-btn--accent peach-btn--md peach-rt-csv-btn"1021 classList={{ "is-busy": importing(), "is-disabled": !passwordReady() }}1022 >1023 {importing() ? "importing…" : "open csv file"}1024 <input1025 type="file"1026 accept=".csv,.json,.peach,application/x-peach"1027 style="display:none"1028 onChange={handleFile}1029 disabled={importing() || !passwordReady()}1030 />1031 </label>1032 <p class="peach-rt-csv-sources">1033 Imports from Bitwarden, 1Password, Proton Pass,<br />1034 Chrome, Safari, and Edge.1035 </p>1036 <p class="peach-rt-csv-warning">PLAIN-TEXT — DELETE THE FILE AFTER IMPORT</p>1037 <Show when={error()}>1038 <p class="peach-rt-error">{error()}</p>1039 </Show>1040 </div>1041 );1042}1043104410451046function getDisplayError(error: string | undefined, fallback: string): string {1047 if (!error) return fallback;1048 if (1049 error === "SERVICE_WORKER_UNAVAILABLE" ||1050 error.includes("Receiving end does not exist") ||1051 error.includes("message port closed")1052 ) {1053 return "background service unavailable";1054 }1055 return error;1056}