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 { storageGet, storageRemove, storageSet } from "../../shared/storage";8import { isPeachScript, decodePeachScript, normalisePeachScript } from "../../crypto/peachScript";9import { parsePayload } from "../../crypto/peachPayload";10import { parseImportSource } from "../../shared/import";11import { isNativePlatform, nativePlugin } from "../../shared/native";1213const peachMarkImg = new Image();14peachMarkImg.src = `data:image/svg+xml,${encodeURIComponent(15 '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 240 240" fill="none">' +16 '<path d="M 124 64 C 134 32 168 16 200 22 C 198 56 168 72 130 66 Z" fill="#92AC65"/>' +17 '<path d="M 130 64 C 152 46 178 30 196 24" stroke="#5E7A42" stroke-width="2.6" fill="none" stroke-linecap="round"/>' +18 '<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"/>' +19 '<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"/>' +20 '<ellipse cx="178" cy="108" rx="20" ry="11" fill="#FFD0A8" opacity="0.7" transform="rotate(-26 178 108)"/>' +21 '</svg>'22)}`;2324252627let _zxcvbn: ((password: string) => { score: number }) | null = null;28async function getZxcvbn() {29 if (_zxcvbn) return _zxcvbn;30 const [{ zxcvbn, zxcvbnOptions }, common, en] = await Promise.all([31 import("@zxcvbn-ts/core"),32 import("@zxcvbn-ts/language-common"),33 import("@zxcvbn-ts/language-en"),34 ]);35 zxcvbnOptions.setOptions({36 translations: en.translations,37 graphs: common.adjacencyGraphs,38 dictionary: { ...common.dictionary, ...en.dictionary },39 });40 _zxcvbn = (password: string) => zxcvbn(password);41 return _zxcvbn;42}4344interface LockProps {45 hasVault: boolean;46 ready: boolean;47 isPro?: boolean;48 495051 forceRecoveryWords?: boolean;52 onUnlock: () => void | Promise<void>;53 545556 onBackToOnboarding?: () => void;57 5859 onOpenCodexRestore?: () => void;60 61 initialRestore?: boolean;62 636465 initialRestoreSource?: RestoreSource;66}6768697071export const RESTORE_SOURCE_STORAGE_KEY = "peach_onboarding_restore_source";7273type RestoreSurface = "restore" | null;74type RecoverSurface = "words" | "new-password" | null;7576export function LockView(props: LockProps) {77 const [password, setPassword] = createSignal("");78 const [confirmPassword, setConfirmPassword] = createSignal("");79 const [error, setError] = createSignal("");80 const [loading, setLoading] = createSignal(false);81 const [restoreSurface, setRestoreSurface] = createSignal<RestoreSurface>(82 props.initialRestore ? "restore" : null,83 );84 const [showPassword, setShowPassword] = createSignal(false);85 const [recoverSurface, setRecoverSurface] = createSignal<RecoverSurface>(null);86 87 88 const [showRecoveryWords, setShowRecoveryWords] = createSignal(props.forceRecoveryWords ?? false);8990 const MIN_LENGTH = 12;91 const MIN_ZXCVBN_SCORE = 2;9293 const [strengthScore, setStrengthScore] = createSignal<number | null>(null);94 const [biometricAvailable, setBiometricAvailable] = createSignal(false);95 const [biometricBusy, setBiometricBusy] = createSignal(false);96 const [pinAvailable, setPinAvailable] = createSignal(false);97 const [usingPin, setUsingPin] = createSignal(false);98 const [pin, setPin] = createSignal("");99100 const canCreate = createMemo(101 () =>102 password().length >= MIN_LENGTH &&103 confirmPassword().length >= MIN_LENGTH &&104 password() === confirmPassword() &&105 strengthScore() !== null &&106 strengthScore()! >= MIN_ZXCVBN_SCORE107 );108109 const passwordStrength = createMemo(() => {110 const score = strengthScore();111 if (score === null) return null;112 if (score <= 1) return "weak";113 if (score === 2) return "fair";114 if (score === 3) return "good";115 return "strong";116 });117118 const createBlockerMessage = createMemo(() => {119 if (!password()) return null;120 if (password().length < MIN_LENGTH) return `need ${MIN_LENGTH - password().length} more characters`;121 if (!confirmPassword()) return "confirm your password";122 if (password() !== confirmPassword()) return "passwords don't match";123 if (strengthScore() === null) return "checking strength…";124 if (strengthScore()! < MIN_ZXCVBN_SCORE) return "password too weak — use a longer passphrase";125 return null;126 });127128 129 createMemo(() => {130 const value = password();131 if (!value) { setStrengthScore(null); return; }132 getZxcvbn().then((zxcvbn) => {133 if (password() === value) setStrengthScore(zxcvbn(value).score);134 }).catch(() => {135 136 if (password() === value) setStrengthScore(value.length >= 16 ? 3 : value.length >= 12 ? 2 : 1);137 });138 });139140 async function handleUnlock() {141 if (!password().trim()) return;142 setLoading(true);143 setError("");144 const response = await sendMessage({145 type: "UNLOCK",146 payload: { password: password() },147 });148 const result = response as { ok: boolean; error?: string };149 if (result.ok) {150 await props.onUnlock();151 setLoading(false);152 return;153 }154 setError(getDisplayError(result.error, "incorrect password"));155 setPassword("");156 const passwordField = document.querySelector(".lock-password-input") as HTMLInputElement | undefined;157 passwordField?.classList.add("shake");158 setTimeout(() => passwordField?.classList.remove("shake"), 300);159 setLoading(false);160 }161162 async function handlePinUnlock() {163 if (!/^\d{4,12}$/.test(pin())) return;164 setLoading(true);165 setError("");166 const response = await sendMessage({167 type: "UNLOCK_WITH_PIN",168 payload: { pin: pin() },169 });170 const result = response as { ok: boolean; error?: string };171 if (result.ok) {172 await props.onUnlock();173 setLoading(false);174 return;175 }176 setError(getDisplayError(result.error, "incorrect PIN"));177 setPin("");178 const pinField = document.querySelector(".lock-pin-input") as HTMLInputElement | undefined;179 pinField?.classList.add("shake");180 setTimeout(() => pinField?.classList.remove("shake"), 300);181 setLoading(false);182 }183184 async function checkPinAvailable(): Promise<void> {185 if (!props.hasVault) return;186 try {187 const response = await sendMessage({ type: "GET_SETTINGS" });188 const settings = (response as { ok: boolean; data?: { pinEnabled?: boolean; pinPreferred?: boolean } }).data;189 const enabled = settings?.pinEnabled === true;190 setPinAvailable(enabled);191 if (enabled && settings?.pinPreferred === true) setUsingPin(true);192 } catch { }193 }194195 async function checkBiometricAvailable(): Promise<void> {196 if (!props.hasVault || !isNativePlatform()) return;197 const keystore = nativePlugin<{ hasMasterKey: () => Promise<{ exists: boolean }> }>("KeystorePlugin");198 const biometric = nativePlugin<{ isAvailable: () => Promise<{ available: boolean }> }>("BiometricPlugin");199 if (!keystore || !biometric) return;200 try {201 const stored = await keystore.hasMasterKey();202 if (!stored.exists) return;203 const avail = await biometric.isAvailable();204 if (!avail.available) return;205 setBiometricAvailable(true);206 window.setTimeout(() => { void handleBiometricUnlock(); }, 400);207 } catch { }208 }209210 async function handleBiometricUnlock(): Promise<void> {211 if (biometricBusy()) return;212 const biometric = nativePlugin<{ authenticate: (opts: Record<string, string>) => Promise<void> }>("BiometricPlugin");213 const keystore = nativePlugin<{ retrieveMasterKey: () => Promise<{ masterKeyHex: string }> }>("KeystorePlugin");214 if (!biometric || !keystore) return;215 setBiometricBusy(true);216 setError("");217 try {218 await biometric.authenticate({219 title: "Unlock Peach",220 subtitle: "Use biometrics to access your vault",221 negativeButtonText: "Use Password",222 });223 const { masterKeyHex } = await keystore.retrieveMasterKey();224 const res = (await sendMessage({225 type: "UNLOCK_WITH_KEY",226 payload: { masterKeyHex },227 })) as { ok: boolean; error?: string };228 if (res.ok) {229 await props.onUnlock();230 return;231 }232 if (res.error === "biometric_key_invalidated") {233 await sendMessage({234 type: "UPDATE_SETTINGS",235 payload: { biometricsEnabled: false },236 });237 setBiometricAvailable(false);238 setError("biometric key expired — re-enable in settings");239 } else {240 setError("biometric unlock failed");241 }242 } catch (e) {243 const reason = e instanceof Error ? e.message : String(e);244 if (reason.includes("user_cancelled")) return;245 if (reason.includes("biometric_key_invalidated")) {246 await sendMessage({247 type: "UPDATE_SETTINGS",248 payload: { biometricsEnabled: false },249 });250 setBiometricAvailable(false);251 setError("biometric key expired — re-enable in settings");252 return;253 }254 if (reason.includes("biometric_lockout")) {255 setError("biometric locked out — use your password");256 }257 } finally {258 setBiometricBusy(false);259 }260 }261262 onMount(() => {263 void checkBiometricAvailable();264 void checkPinAvailable();265 });266267 async function handleCreate() {268 if (!password().trim()) return;269 if (password().length < MIN_LENGTH) {270 setError(`password must be at least ${MIN_LENGTH} characters`);271 return;272 }273 if (password() !== confirmPassword()) {274 setError("passwords do not match");275 return;276 }277 const score = strengthScore();278 if (score === null || score < MIN_ZXCVBN_SCORE) {279 setError("password is too weak — use a longer passphrase");280 return;281 }282 setLoading(true);283 setError("");284 const response = await sendMessage({285 type: "CREATE_VAULT",286 payload: { password: password() },287 });288 const result = response as { ok: boolean; error?: string };289 if (result.ok) {290 291 292 293 294 295 try {296 await chrome.storage.local?.set({ peach_recovery_pending: "1" });297 } catch { }298 setShowRecoveryWords(true);299 setLoading(false);300 return;301 }302 setError(getDisplayError(result.error, "failed to create vault"));303 setLoading(false);304 }305306 307 return (308 <Switch>309 {}310 <Match when={restoreSurface() === "restore"}>311 <RestoreView312 hasVault={props.hasVault}313 onOpenCodexRestore={props.onOpenCodexRestore}314 initialSource={props.initialRestoreSource}315 onBack={() => {316 317 318 if (props.onBackToOnboarding) props.onBackToOnboarding();319 else setRestoreSurface(null);320 }}321 onUnlock={async () => {322 setRestoreSurface(null);323 await props.onUnlock();324 }}325 />326 </Match>327328 {}329 {330331}332 <Match333 when={334 (showRecoveryWords() || props.forceRecoveryWords) &&335 (!props.hasVault || props.forceRecoveryWords)336 }337 >338 <RecoveryWordDisplayView339 onDone={props.onUnlock}340 />341 </Match>342343 {}344 <Match when={recoverSurface() === "words"}>345 <RecoveryWordEntryView346 onCancel={() => setRecoverSurface(null)}347 onRecoveryComplete={props.onUnlock}348 />349 </Match>350351 {}352 <Match when={props.hasVault}>353 <section class="peach-screen peach-theme lock-screen lock-screen--vault-stage" data-motion-phase="enter">354 <RuneBackground opacity={0.07} />355356 <header class="peach-screen-header lock-screen-header">357 <div class="peach-wordmark-stack">358 <PeachWordmark class="peach-wordmark-wrap" />359 <Show when={props.isPro}>360 <span class="peach-pro-mini-badge">pro</span>361 </Show>362 </div>363 </header>364365 <div class="peach-lock-hero peach-lock-hero--unlock">366 <PeachMark class="peach-lock-mark" />367 <span class="peach-lock-eyebrow">vault locked</span>368 <h1 class="peach-onboarding-headline peach-lock-headline--unlock">369 unlock370 <br />371 your vault.372 </h1>373 </div>374375 <section class="peach-lock-panel peach-lock-panel--unlock peach-glass">376 <Show when={usingPin()} fallback={377 <>378 <label class="peach-label" for="unlock-password">379 master password380 </label>381 <input382 id="unlock-password"383 class="peach-underline-input peach-unlock-input lock-password-input"384 type="password"385 placeholder="••••••••••••"386 autocomplete="current-password"387 value={password()}388 disabled={!props.ready}389 ref={(el) => { if (props.ready) setTimeout(() => el.focus(), 80); }}390 onInput={(event) => setPassword((event.target as HTMLInputElement).value)}391 onKeyDown={(event) => {392 if (event.key !== "Enter" || !props.ready) return;393 void handleUnlock();394 }}395 />396 </>397 }>398 <label class="peach-label" for="unlock-pin">399 PIN400 </label>401 <input402 id="unlock-pin"403 class="peach-underline-input peach-unlock-input lock-pin-input"404 type="password"405 inputmode="numeric"406 maxlength="12"407 placeholder="••••••••••••"408 autocomplete="off"409 value={pin()}410 disabled={!props.ready}411 ref={(el) => { if (props.ready) setTimeout(() => el.focus(), 80); }}412 onInput={(event) => setPin((event.target as HTMLInputElement).value.replace(/\D/g, "").slice(0, 12))}413 onKeyDown={(event) => {414 if (event.key !== "Enter" || !props.ready) return;415 void handlePinUnlock();416 }}417 />418 <button419 class="peach-lock-recover-link"420 type="button"421 onClick={() => { setUsingPin(false); setError(""); }}422 >423 use master password424 </button>425 </Show>426427 <Show when={error()}>428 <p class="peach-hint peach-hint-error">{error()}</p>429 </Show>430431 <button432 class="peach-btn peach-btn--accent peach-btn--md peach-lock-submit"433 onClick={() => void (usingPin() ? handlePinUnlock() : handleUnlock())}434 disabled={!props.ready || loading()}435 >436 {loading() ? "unlocking..." : usingPin() ? "unlock with PIN" : "unlock"}437 </button>438439 <Show when={!usingPin() && pinAvailable()}>440 <button441 class="peach-lock-recover-link"442 type="button"443 onClick={() => { setUsingPin(true); setError(""); }}444 >445 use PIN446 </button>447 </Show>448449 <Show when={biometricAvailable()}>450 <button451 class="peach-biometric-btn"452 type="button"453 onClick={() => void handleBiometricUnlock()}454 disabled={biometricBusy() || loading()}455 aria-label="Unlock with biometrics"456 >457 <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">458 <path d="M12 11c-1.7 0-3 1.3-3 3v3"/>459 <path d="M15 17v-3"/>460 <path d="M9 4.5C9.7 4.2 10.8 4 12 4s2.3.2 3 .5"/>461 <path d="M5 9c.7-1.6 2-2.9 3.6-3.6"/>462 <path d="M19 9c-.7-1.6-2-2.9-3.6-3.6"/>463 <path d="M5 15c0-1.7.3-3.3.8-4.7"/>464 <path d="M19 15c0-1.7-.3-3.3-.8-4.7"/>465 </svg>466 {biometricBusy() ? "verifying…" : "use biometrics"}467 </button>468 </Show>469470 <button471 class="peach-lock-recover-link"472 type="button"473 onClick={() => setRecoverSurface("words")}474 >475 forgot your password?476 </button>477 </section>478 </section>479 </Match>480481 {}482 <Match when={true}>483 <section484 class="peach-screen peach-theme lock-screen lock-screen--vault-stage peach-newvault"485 data-motion-phase="enter"486 >487 <header class="peach-screen-header peach-newvault-header">488 <div class="peach-wordmark-stack">489 <PeachWordmark class="peach-wordmark-wrap" />490 <Show when={props.isPro}>491 <span class="peach-pro-mini-badge">pro</span>492 </Show>493 </div>494 <Show when={props.onBackToOnboarding}>495 <button496 class="peach-newvault-back"497 type="button"498 onClick={() => props.onBackToOnboarding?.()}499 aria-label="Back to onboarding"500 >501 <svg width="11" height="11" viewBox="0 0 11 11" fill="none" stroke="currentColor" stroke-width="1.2" stroke-linecap="round" stroke-linejoin="round">502 <path d="M7 2L3 5.5L7 9" />503 </svg>504 back505 </button>506 </Show>507 </header>508509 <div class="peach-newvault-mark" aria-hidden="true">510 <PeachMark class="peach-newvault-mark-art" />511 </div>512513 <div class="peach-newvault-card">514 <h1 class="peach-newvault-headline">{"keep your\nsecrets."}</h1>515 <hr class="peach-newvault-divider" />516517 <div class="peach-newvault-field">518 <div class="peach-newvault-label-row">519 <label class="peach-label" for="master-password">520 master password521 </label>522 <button523 class="peach-lock-reveal-btn"524 type="button"525 onClick={() => setShowPassword((value) => !value)}526 aria-label={showPassword() ? "Hide password" : "Show password"}527 >528 <Show529 when={showPassword()}530 fallback={531 <svg width="15" height="10" viewBox="0 0 14 10" fill="none" stroke="currentColor" stroke-width="0.9" stroke-linecap="round">532 <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" />533 <circle cx="7" cy="5" r="1.75" />534 </svg>535 }536 >537 <svg width="15" height="10" viewBox="0 0 14 10" fill="none" stroke="currentColor" stroke-width="0.9" stroke-linecap="round">538 <path d="M1 2C3 4.5 5 6 7 6C9 6 11 4.5 13 2" />539 <path d="M3.5 5.5L2.5 7.5" />540 <path d="M7 6.5V8.5" />541 <path d="M10.5 5.5L11.5 7.5" />542 </svg>543 </Show>544 {showPassword() ? "hide" : "show"}545 </button>546 </div>547 <input548 id="master-password"549 class="peach-underline-input peach-newvault-input lock-password-input"550 type={showPassword() ? "text" : "password"}551 placeholder="••••••••••••"552 autocomplete="new-password"553 value={password()}554 disabled={!props.ready}555 onInput={(event) => setPassword((event.target as HTMLInputElement).value)}556 onKeyDown={(event) => {557 if (event.key !== "Enter" || !props.ready) return;558 void handleCreate();559 }}560 />561 <Show562 when={password().length > 0 && passwordStrength() !== null}563 fallback={564 <p class="peach-newvault-hint">565 At least 12 characters.566 </p>567 }568 >569 <div class="peach-password-strength">570 <div class={`peach-strength-bar peach-strength-bar--${passwordStrength()}`}>571 <div class="peach-strength-fill"></div>572 </div>573 <span class="peach-strength-label">{passwordStrength()}</span>574 </div>575 </Show>576 </div>577578 <div class="peach-newvault-field">579 <label class="peach-label" for="confirm-password">580 confirm password581 </label>582 <input583 id="confirm-password"584 class="peach-underline-input peach-newvault-input"585 type={showPassword() ? "text" : "password"}586 placeholder="••••••••••••"587 autocomplete="new-password"588 value={confirmPassword()}589 disabled={!props.ready}590 onInput={(event) => setConfirmPassword((event.target as HTMLInputElement).value)}591 onKeyDown={(event) => {592 if (event.key === "Enter" && props.ready) void handleCreate();593 }}594 />595 </div>596597 <Show when={error()}>598 <p class="peach-hint peach-hint-error">{error()}</p>599 </Show>600601 <button602 class="peach-btn peach-btn--accent peach-btn--md peach-lock-submit peach-newvault-submit"603 onClick={() => void handleCreate()}604 disabled={!props.ready || loading() || !canCreate()}605 aria-live="polite"606 >607 <Show608 when={!canCreate() && createBlockerMessage()}609 fallback={loading() ? "creating..." : "create vault"}610 >611 {createBlockerMessage()}612 </Show>613 </button>614615 <p class="peach-newvault-warning">616 <span class="peach-newvault-warning-icon" aria-hidden="true">⚠</span>617 <span>Save your 12 recovery words after creating — they're the only way back in if you forget your password.</span>618 </p>619 </div>620 </section>621 </Match>622 </Switch>623 );624}625626627628export type RestoreSource = "symbols" | "codex" | "csv";629630const RESTORE_SOURCES: { id: RestoreSource; name: string; detail: string }[] = [631 { id: "symbols", name: "PeachScript", detail: "Paste the rune string, or open a .peach file." },632 { id: "codex", name: "Codex", detail: "Scan printed pages, or import the PDF." },633 { id: "csv", name: "CSV", detail: "A .csv or .json file from another password manager." },634];635636function RestoreView(props: {637 hasVault: boolean;638 onOpenCodexRestore?: () => void;639 onBack: () => void;640 onUnlock: () => void | Promise<void>;641 initialSource?: RestoreSource;642}) {643 const [source, setSource] = createSignal<RestoreSource | null>(props.initialSource ?? null);644 const [showIntro, setShowIntro] = createSignal(false);645 const [pendingUnlock] = createSignal(false);646647 648 649 650 651 function chooseSource(next: RestoreSource | null) {652 setSource(next);653 if (next) void storageSet(RESTORE_SOURCE_STORAGE_KEY, next).catch(() => {});654 else void storageRemove(RESTORE_SOURCE_STORAGE_KEY).catch(() => {});655 }656657 async function handleRestoreSuccess() {658 const seen = await storageGet("peach_shown_restore_intro").catch(() => null);659 if (!seen) {660 setShowIntro(true);661 } else {662 await props.onUnlock();663 }664 }665666 async function dismissIntro() {667 await storageSet("peach_shown_restore_intro", "true").catch(() => {});668 setShowIntro(false);669 await props.onUnlock();670 }671672 return (673 <section674 class="peach-screen peach-theme lock-screen lock-screen--vault-stage peach-newvault peach-restore"675 data-motion-phase="enter"676 >677 <RuneBackground opacity={0.05} />678679 <header class="peach-screen-header peach-newvault-header">680 <PeachWordmark class="peach-wordmark-wrap" />681 <button682 class="peach-newvault-back peach-restore-back"683 type="button"684 onClick={props.onBack}685 aria-label="Back to onboarding"686 >687 <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">688 <path d="M7 2L3 5.5L7 9" />689 </svg>690 back691 </button>692 </header>693694 <div class="peach-newvault-card peach-restore-card">695 <Show696 when={source()}697 keyed698 fallback={699 <>700 <h1 class="peach-newvault-headline">{"welcome\nback."}</h1>701 <hr class="peach-newvault-divider" />702 <div class="peach-restore-sources">703 <For each={RESTORE_SOURCES}>704 {(entry) => (705 <button706 type="button"707 class="peach-onboarding-choice peach-restore-source"708 onClick={() => chooseSource(entry.id)}709 >710 <span class="peach-onboarding-choice-label">{entry.name}</span>711 <span class="peach-onboarding-choice-detail">{entry.detail}</span>712 </button>713 )}714 </For>715 </div>716 </>717 }718 >719 {(active) => (720 <>721 <div class="peach-restore-source-head">722 <h2 class="peach-restore-source-title">723 {RESTORE_SOURCES.find((entry) => entry.id === active)?.name}724 </h2>725 <button726 type="button"727 class="peach-restore-picker-back"728 onClick={() => chooseSource(null)}729 >730 ‹ sources731 </button>732 </div>733 <hr class="peach-newvault-divider" />734 <Show when={active === "symbols"}>735 <RestoreSymbols hasVault={props.hasVault} onSuccess={handleRestoreSuccess} />736 </Show>737 <Show when={active === "codex"}>738 <RestoreCodex onOpen={() => props.onOpenCodexRestore?.()} />739 </Show>740 <Show when={active === "csv"}>741 <RestoreCSV hasVault={props.hasVault} onSuccess={handleRestoreSuccess} />742 </Show>743 </>744 )}745 </Show>746 </div>747748 {}749 <Show when={showIntro()}>750 <div class="peach-restore-intro-overlay">751 <div class="peach-restore-intro-card">752 <p class="peach-restore-intro-headline">welcome to peach.</p>753 <div class="peach-restore-intro-body">754 <p>Your vault lives only on this device. No server has a copy.</p>755 <p>The inline bubble fills passwords automatically when you visit sites.</p>756 <p>Export your vault from Settings before switching devices.</p>757 </div>758 <button759 class="peach-btn peach-btn--accent peach-btn--md peach-restore-intro-btn"760 onClick={() => void dismissIntro()}761 disabled={pendingUnlock()}762 >763 got it764 </button>765 </div>766 </div>767 </Show>768 </section>769 );770}771772773774function RestoreCodex(props: { onOpen: () => void }) {775 return (776 <div class="peach-restore-form">777 <p class="peach-restore-codex-copy">778 Scan printed Codex pages or import the Codex PDF. Codex restore is779 always available, even before you create a vault.780 </p>781 <button782 type="button"783 class="peach-btn peach-btn--accent peach-btn--md peach-restore-submit"784 onClick={props.onOpen}785 >786 open Codex restore787 </button>788 </div>789 );790}791792793794function RestoreSymbols(props: {795 hasVault: boolean;796 onSuccess: () => void | Promise<void>;797}) {798 const [scriptInput, setScriptInput] = createSignal("");799 const [backupPass, setBackupPass] = createSignal("");800 const [working, setWorking] = createSignal(false);801 const [animating, setAnimating] = createSignal<"chaos" | "snap" | "bloom" | null>(null);802 const [error, setError] = createSignal<string | null>(null);803 let canvasRef: HTMLCanvasElement | undefined;804 let animFrameId = 0;805 let runes: { x: number; y: number; vx: number; vy: number; char: string; size: number; angle: number; va: number }[] = [];806807 const scriptValid = createMemo(() => isPeachScript(scriptInput()));808809 function stopAnim() {810 cancelAnimationFrame(animFrameId);811 animFrameId = 0;812 }813814 function startChaos(canvas: HTMLCanvasElement) {815 const ctx = canvas.getContext("2d")!;816 const W = canvas.width;817 const H = canvas.height;818 const RUNE_CHARS = Array.from({ length: 40 }, (_, i) =>819 String.fromCodePoint(0xe000 + i)820 );821 if (runes.length === 0) {822 runes = Array.from({ length: 60 }, () => ({823 x: Math.random() * W,824 y: Math.random() * H,825 vx: (Math.random() - 0.5) * 3,826 vy: (Math.random() - 0.5) * 3,827 char: RUNE_CHARS[Math.floor(Math.random() * RUNE_CHARS.length)]!,828 size: 14 + Math.random() * 20,829 angle: Math.random() * Math.PI * 2,830 va: (Math.random() - 0.5) * 0.1,831 }));832 }833834 function draw() {835 ctx.clearRect(0, 0, W, H);836 for (const r of runes) {837 r.x = (r.x + r.vx + W) % W;838 r.y = (r.y + r.vy + H) % H;839 r.angle += r.va;840 ctx.save();841 ctx.translate(r.x, r.y);842 ctx.rotate(r.angle);843 ctx.font = `${r.size}px PeachScript, monospace`;844 const alpha = 0.5 + 0.5 * Math.sin(Date.now() / 400 + r.x);845 ctx.fillStyle = `rgba(232, 149, 109, ${alpha})`;846 ctx.shadowColor = "rgba(232, 149, 109, 0.7)";847 ctx.shadowBlur = 8;848 ctx.fillText(r.char, 0, 0);849 ctx.restore();850 }851 animFrameId = requestAnimationFrame(draw);852 }853 draw();854 }855856 function snapToGrid(canvas: HTMLCanvasElement, onDone: () => void) {857 stopAnim();858 const ctx = canvas.getContext("2d")!;859 const W = canvas.width;860 const H = canvas.height;861 const cols = 8;862 const rows = 6;863 const cellW = W / cols;864 const cellH = H / rows;865 const targets = runes.slice(0, cols * rows).map((_, i) => ({866 x: (i % cols) * cellW + cellW / 2,867 y: Math.floor(i / cols) * cellH + cellH / 2,868 }));869 const start = performance.now();870 const DURATION = 400;871872 function drawSnap(now: number) {873 const t = Math.min((now - start) / DURATION, 1);874 const ease = t < 1 ? 1 - (1 - t) ** 3 : 1;875 ctx.clearRect(0, 0, W, H);876 runes.slice(0, targets.length).forEach((r, i) => {877 const tx = targets[i]!.x;878 const ty = targets[i]!.y;879 const cx = r.x + (tx - r.x) * ease;880 const cy = r.y + (ty - r.y) * ease;881 ctx.font = `16px PeachScript, monospace`;882 ctx.fillStyle = `rgba(232, 149, 109, ${0.8 * ease})`;883 ctx.shadowColor = "rgba(232, 149, 109, 0.6)";884 ctx.shadowBlur = 6;885 ctx.fillText(r.char, cx - 8, cy + 8);886 });887 if (t < 1) {888 animFrameId = requestAnimationFrame(drawSnap);889 } else {890 onDone();891 }892 }893 animFrameId = requestAnimationFrame(drawSnap);894 }895896 function bloom(canvas: HTMLCanvasElement, onDone: () => void) {897 stopAnim();898 const ctx = canvas.getContext("2d")!;899 const W = canvas.width;900 const H = canvas.height;901 const start = performance.now();902 const DURATION = 900;903904 function drawBloom(now: number) {905 const t = Math.min((now - start) / DURATION, 1);906 ctx.clearRect(0, 0, W, H);907 908 const runeAlpha = 1 - Math.min(t / 0.4, 1);909 if (runeAlpha > 0) {910 for (const r of runes.slice(0, 48)) {911 ctx.font = `16px PeachScript, monospace`;912 ctx.fillStyle = `rgba(232, 149, 109, ${runeAlpha * 0.8})`;913 ctx.fillText(r.char, r.x - 8, r.y + 8);914 }915 }916 917 const markT = Math.max(0, (t - 0.2) / 0.5);918 const markScale = Math.min(markT * 1.2, 1);919 const markAlpha = markT < 0.5 ? markT * 2 : 2 - markT * 2;920 if (markAlpha > 0) {921 ctx.save();922 ctx.globalAlpha = markAlpha;923 ctx.shadowColor = `rgba(217, 104, 48, ${markAlpha * 0.8})`;924 ctx.shadowBlur = 30;925 ctx.translate(W / 2, H / 2);926 ctx.scale(markScale, markScale);927 ctx.drawImage(peachMarkImg, -32, -32, 64, 64);928 ctx.restore();929 }930 if (t < 1) {931 animFrameId = requestAnimationFrame(drawBloom);932 } else {933 onDone();934 }935 }936 animFrameId = requestAnimationFrame(drawBloom);937 }938939 onCleanup(() => stopAnim());940941 942 943 944 const [dragDepth, setDragDepth] = createSignal(0);945946 async function handleDrop(e: DragEvent) {947 e.preventDefault();948 setDragDepth(0);949 if (working() || animating() !== null) return;950 const file = e.dataTransfer?.files?.[0];951 if (!file) return;952 try {953 setScriptInput(await file.text());954 setError(null);955 } catch {956 setError("Couldn't read file.");957 }958 }959960 async function handleRestore() {961 if (!scriptValid() || !backupPass().trim() || working()) return;962 setError(null);963 setWorking(true);964 setAnimating("chaos");965966 const canvas = canvasRef;967 if (canvas) startChaos(canvas);968969 try {970 const bytes = decodePeachScript(normalisePeachScript(scriptInput()));971 const payload = await parsePayload(bytes, backupPass());972973 if (!props.hasVault) {974 const cr = await sendMessage({ type: "CREATE_VAULT", payload: { password: backupPass() } });975 if (!(cr as { ok: boolean }).ok) throw new Error("CREATE_VAULT_FAILED");976 }977978 const rr = await sendMessage({979 type: "RESTORE_ENTRIES",980 payload: { entries: payload.entries, mode: "merge", settings: payload.settings },981 });982 if (!(rr as { ok: boolean }).ok) throw new Error((rr as { error?: string }).error ?? "RESTORE_FAILED");983984 if (payload.license?.key) {985 await sendMessage({ type: "ACTIVATE_LICENSE", payload: { key: payload.license.key } }).catch(() => {});986 }987988 setAnimating("snap");989 stopAnim();990 if (canvas) {991 snapToGrid(canvas, () => {992 setAnimating("bloom");993 bloom(canvas, async () => {994 setAnimating(null);995 await props.onSuccess();996 });997 });998 } else {999 await props.onSuccess();1000 }1001 } catch (err) {1002 stopAnim();1003 setAnimating(null);1004 const code = err instanceof Error ? err.message : String(err);1005 setError(1006 code === "INVALID_PASSPHRASE" || code === "INVALID_EXPORT_PASSWORD"1007 ? "That passphrase didn't work."1008 : code === "CREATE_VAULT_FAILED"1009 ? "Couldn't create a new local vault."1010 : "Could not read this backup.",1011 );1012 } finally {1013 setWorking(false);1014 }1015 }10161017 return (1018 <div1019 class="peach-restore-form"1020 classList={{ "is-dragover": dragDepth() > 0 }}1021 onDragEnter={(e) => { e.preventDefault(); setDragDepth((d) => d + 1); }}1022 onDragOver={(e) => e.preventDefault()}1023 onDragLeave={() => setDragDepth((d) => Math.max(0, d - 1))}1024 onDrop={(e) => void handleDrop(e)}1025 >1026 <Show when={animating() !== null}>1027 <canvas1028 ref={(el) => { canvasRef = el; }}1029 class="peach-restore-anim-canvas"1030 width={280}1031 height={200}1032 />1033 </Show>1034 <Show when={animating() === null}>1035 <textarea1036 class="peach-restore-script"1037 placeholder="paste peachscript…"1038 rows={3}1039 aria-label="Paste your PeachScript backup"1040 value={scriptInput()}1041 onInput={(e) => setScriptInput((e.target as HTMLTextAreaElement).value)}1042 />1043 <div class="peach-restore-or" aria-hidden="true">or</div>1044 <label class="peach-btn peach-btn--ghost peach-btn--sm peach-restore-file-btn">1045 open .peach file1046 <input1047 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 try {1054 setScriptInput(await file.text());1055 } catch {1056 setError("Couldn't read file.");1057 } finally {1058 (e.currentTarget as HTMLInputElement).value = "";1059 }1060 }}1061 />1062 </label>1063 <p class="peach-restore-drop-hint">or drop the file anywhere here</p>1064 <div class="peach-newvault-field">1065 <label class="peach-label" for="restore-backup-pass">1066 backup password1067 </label>1068 <input1069 id="restore-backup-pass"1070 class="peach-underline-input peach-newvault-input"1071 type="password"1072 placeholder="••••••••••••"1073 autocomplete="current-password"1074 value={backupPass()}1075 onInput={(e) => setBackupPass((e.target as HTMLInputElement).value)}1076 onKeyDown={(e) => {1077 if (e.key === "Enter" && scriptValid() && backupPass().trim() && !working()) {1078 e.preventDefault();1079 void handleRestore();1080 }1081 }}1082 />1083 </div>1084 <button1085 class="peach-btn peach-btn--accent peach-btn--md peach-restore-submit"1086 onClick={() => void handleRestore()}1087 disabled={!scriptValid() || !backupPass().trim() || working()}1088 >1089 restore vault1090 </button>1091 <Show when={error()}>1092 <p class="peach-hint peach-hint-error">{error()}</p>1093 </Show>1094 </Show>1095 </div>1096 );1097}1098109911001101function RestoreCSV(props: {1102 hasVault: boolean;1103 onSuccess: () => void | Promise<void>;1104}) {1105 const [importing, setImporting] = createSignal(false);1106 const [error, setError] = createSignal<string | null>(null);1107 1108 1109 1110 1111 const CSV_MIN_PASSWORD_LENGTH = 12;1112 const [newPass, setNewPass] = createSignal("");1113 const [confirmPass, setConfirmPass] = createSignal("");1114 const needsPassword = () => props.hasVault === false;1115 const passwordReady = () =>1116 !needsPassword() ||1117 (newPass().length >= CSV_MIN_PASSWORD_LENGTH && newPass() === confirmPass());1118 1119 1120 const [dragDepth, setDragDepth] = createSignal(0);11211122 1123 1124 1125 async function processFile(file: File) {1126 setImporting(true);1127 setError(null);1128 try {1129 const text = await file.text();1130 const parsed = await parseImportSource(text);1131 if (parsed.entries.length === 0) throw new Error("NO_ENTRIES");11321133 if (props.hasVault === false) {1134 1135 1136 const cr = await sendMessage({ type: "CREATE_VAULT", payload: { password: newPass() } });1137 if (!(cr as { ok: boolean }).ok) throw new Error("CREATE_VAULT_FAILED");1138 }11391140 const res = await sendMessage({ type: "BATCH_ADD_ENTRIES", payload: { entries: parsed.entries } });1141 if (!(res as { ok: boolean }).ok) throw new Error("IMPORT_FAILED");1142 if (parsed.licenseKey) {1143 await sendMessage({ type: "ACTIVATE_LICENSE", payload: { key: parsed.licenseKey } }).catch(() => {});1144 }1145 await props.onSuccess();1146 } catch (err) {1147 const code = err instanceof Error ? err.message : String(err);1148 setError(1149 code === "NO_ENTRIES" ? "No entries found in this file." :1150 code === "CREATE_VAULT_FAILED" ? "Couldn't create a new local vault." :1151 "Import failed. Check the file format and try again."1152 );1153 } finally {1154 setImporting(false);1155 }1156 }11571158 let csvFileRef: HTMLInputElement | undefined;11591160 function gatePassword(): boolean {1161 if (importing()) return false;1162 if (needsPassword() && newPass().length < CSV_MIN_PASSWORD_LENGTH) {1163 setError(`Set a master password of at least ${CSV_MIN_PASSWORD_LENGTH} characters first.`);1164 return false;1165 }1166 if (needsPassword() && newPass() !== confirmPass()) {1167 setError("Passwords do not match.");1168 return false;1169 }1170 return true;1171 }11721173 async function handleFile(e: Event) {1174 const input = e.currentTarget as HTMLInputElement;1175 const file = input.files?.[0];1176 input.value = "";1177 if (!file) return;1178 await processFile(file);1179 }11801181 async function handleDrop(e: DragEvent) {1182 e.preventDefault();1183 setDragDepth(0);1184 if (!gatePassword()) return;1185 const file = e.dataTransfer?.files?.[0];1186 if (!file) return;1187 await processFile(file);1188 }11891190 return (1191 <div1192 class="peach-restore-form"1193 classList={{ "is-dragover": dragDepth() > 0 }}1194 onDragEnter={(e) => { e.preventDefault(); setDragDepth((d) => d + 1); }}1195 onDragOver={(e) => e.preventDefault()}1196 onDragLeave={() => setDragDepth((d) => Math.max(0, d - 1))}1197 onDrop={(e) => void handleDrop(e)}1198 >1199 <Show when={needsPassword()}>1200 <div class="peach-newvault-field">1201 <label class="peach-label" for="restore-csv-pass">1202 new master password1203 </label>1204 <input1205 id="restore-csv-pass"1206 class="peach-underline-input peach-newvault-input"1207 type="password"1208 placeholder="••••••••••••"1209 autocomplete="new-password"1210 value={newPass()}1211 onInput={(e) => setNewPass((e.target as HTMLInputElement).value)}1212 />1213 </div>1214 <div class="peach-newvault-field">1215 <label class="peach-label" for="restore-csv-confirm">1216 confirm master password1217 </label>1218 <input1219 id="restore-csv-confirm"1220 class="peach-underline-input peach-newvault-input"1221 type="password"1222 placeholder="••••••••••••"1223 autocomplete="new-password"1224 value={confirmPass()}1225 onInput={(e) => setConfirmPass((e.target as HTMLInputElement).value)}1226 />1227 </div>1228 </Show>1229 <label1230 class="peach-btn peach-btn--accent peach-btn--md peach-restore-file-btn"1231 onClick={(e) => {1232 1233 1234 e.preventDefault();1235 if (!gatePassword()) return;1236 csvFileRef?.click();1237 }}1238 >1239 {importing() ? "importing…" : "open csv file"}1240 <input1241 ref={(el) => { csvFileRef = el; }}1242 type="file"1243 accept=".csv,.json,.peach,application/x-peach"1244 style="display:none"1245 onChange={handleFile}1246 disabled={importing() || !passwordReady()}1247 />1248 </label>1249 <p class="peach-restore-drop-hint">or drop the file anywhere here</p>1250 <p class="peach-hint peach-restore-csv-sources">1251 Imports from Bitwarden, 1Password, Proton Pass,1252 <br />1253 Chrome, Safari, and Edge.1254 </p>1255 <p class="peach-newvault-warning">1256 <span class="peach-newvault-warning-icon" aria-hidden="true">⚠</span>1257 <span>Plain-text file — delete it after the import.</span>1258 </p>1259 <Show when={error()}>1260 <p class="peach-hint peach-hint-error">{error()}</p>1261 </Show>1262 </div>1263 );1264}1265126612671268function getDisplayError(error: string | undefined, fallback: string): string {1269 if (!error) return fallback;1270 if (1271 error === "SERVICE_WORKER_UNAVAILABLE" ||1272 error.includes("Receiving end does not exist") ||1273 error.includes("message port closed")1274 ) {1275 return "background service unavailable";1276 }1277 return error;1278}