1import {2 Match,3 Show,4 Switch,5 createEffect,6 createMemo,7 createSignal,8 onCleanup,9} from "solid-js";10import { sendMessage } from "../App";11import { DesktopBird, MobileBird } from "../components/PairingBirds";12import { RuneBackground } from "../components/RuneBackground";13import { PairingQrCode } from "../components/PairingQrCode";14import { PairingProRequired } from "../components/PairingProRequired";15import { RELAY_DISCLOSURE } from "../components/SyncModeSelector";1617type AdoptPhase = "password" | "pair" | "error";1819export interface AdoptVaultViewProps {20 onCancel(): void;21 onDone(): void | Promise<void>;22}23242526272829function describeAdoptionError(error: string | undefined, fallback: string): string {30 return error === "ADOPT_PRO_REQUIRED" ? error : fallback;31}3233const MIN_LENGTH = 12;34const MIN_ZXCVBN_SCORE = 2;35const PAIRING_CELEBRATION_MS = 5_000;3637let zxcvbnLoader: ((password: string) => { score: number }) | null = null;38async function getZxcvbn() {39 if (zxcvbnLoader) return zxcvbnLoader;40 const [{ zxcvbn, zxcvbnOptions }, common, en] = await Promise.all([41 import("@zxcvbn-ts/core"),42 import("@zxcvbn-ts/language-common"),43 import("@zxcvbn-ts/language-en"),44 ]);45 zxcvbnOptions.setOptions({46 translations: en.translations,47 graphs: common.adjacencyGraphs,48 dictionary: { ...common.dictionary, ...en.dictionary },49 });50 zxcvbnLoader = (password: string) => zxcvbn(password);51 return zxcvbnLoader;52}5354export function AdoptVaultView(props: AdoptVaultViewProps) {55 const [phase, setPhase] = createSignal<AdoptPhase>("password");56 const [password, setPassword] = createSignal("");57 const [confirmPassword, setConfirmPassword] = createSignal("");58 const [strengthScore, setStrengthScore] = createSignal<number | null>(null);59 const [receiverInvitation, setReceiverInvitation] = createSignal("");60 const [receiverSas, setReceiverSas] = createSignal("");61 const [receiverError, setReceiverError] = createSignal("");62 const [receiverComplete, setReceiverComplete] = createSignal(false);63 let completionTimer: number | undefined;6465 onCleanup(() => {66 if (completionTimer !== undefined) window.clearTimeout(completionTimer);67 68 void sendMessage({ type: "CANCEL_ADOPTION_SOURCE" }).catch(() => undefined);69 });7071 72 73 74 75 76 createEffect(() => {77 if (phase() !== "pair") return;78 if (receiverInvitation() || receiverError()) return;79 void (async () => {80 const response = (await sendMessage({81 type: "START_ADOPTION_RECEIVER",82 payload: { password: password() },83 })) as { ok: boolean; data?: { invitation?: string }; error?: string };84 if (response.ok && response.data?.invitation) {85 setReceiverInvitation(response.data.invitation);86 } else {87 setReceiverError(88 describeAdoptionError(89 response.error,90 "could not start joining this vault. please try again.",91 ),92 );93 }94 })();95 });9697 const [receiverSasId, setReceiverSasId] = createSignal("");98 const [receiverSasDecision, setReceiverSasDecision] = createSignal(false);99100 function confirmReceiverSas(): void {101 if (!receiverSas() || !receiverSasId()) return;102 void sendMessage({103 type: "RECEIVER_SAS_DECISION",104 payload: { id: receiverSasId(), sas: receiverSas(), ok: true },105 });106 setReceiverSasDecision(true);107 }108109 110111 if (typeof chrome !== "undefined" && chrome.runtime?.onMessage) {112 const handler = (msg: { type?: string; payload?: unknown }) => {113 if (msg?.type === "ADOPTION_SOURCE_SAS") {114 const p = msg.payload as { id?: string; sas?: string; displayOnly?: boolean } | undefined;115 if (p?.displayOnly === false && typeof p.sas === "string" && typeof (p as { id?: unknown }).id === "string") {116 setReceiverSas(p.sas);117 setReceiverSasId((p as { id: string }).id);118 setReceiverSasDecision(false);119 }120 } else if (msg?.type === "ADOPTION_SOURCE_RESULT") {121 const p = msg.payload as {122 status?: "complete" | "error";123 error?: string;124 } | undefined;125 if (p?.status === "complete") {126 if (receiverComplete()) return;127 setReceiverComplete(true);128 completionTimer = window.setTimeout(() => {129 completionTimer = undefined;130 void props.onDone();131 }, PAIRING_CELEBRATION_MS);132 } else if (p?.status === "error") {133 setReceiverError(134 describeAdoptionError(135 p.error,136 "the other device could not finish the transfer. please try again.",137 ),138 );139 setPhase("error");140 }141 }142 };143 chrome.runtime.onMessage.addListener(handler);144 onCleanup(() => chrome.runtime.onMessage.removeListener(handler));145 }146147 createMemo(() => {148 const value = password();149 if (!value) {150 setStrengthScore(null);151 return;152 }153 getZxcvbn().then((zxcvbn) => {154 if (password() === value) setStrengthScore(zxcvbn(value).score);155 }).catch(() => {156 if (password() === value) setStrengthScore(value.length >= 16 ? 2 : 1);157 });158 });159160 const canContinue = createMemo(() =>161 password().length >= MIN_LENGTH &&162 confirmPassword().length >= MIN_LENGTH &&163 password() === confirmPassword() &&164 strengthScore() !== null &&165 strengthScore()! >= MIN_ZXCVBN_SCORE166 );167168 const createBlocker = createMemo(() => {169 if (!password()) return null;170 if (password().length < MIN_LENGTH) return `need ${MIN_LENGTH - password().length} more characters`;171 if (!confirmPassword()) return "confirm your password";172 if (password() !== confirmPassword()) return "passwords don't match";173 if (strengthScore() === null) return "checking strength...";174 if (strengthScore()! < MIN_ZXCVBN_SCORE) return "password too weak - use a longer passphrase";175 return null;176 });177178 function tryAgain(): void {179 setReceiverError("");180 setReceiverInvitation("");181 setReceiverSas("");182 setPhase("pair");183 }184185 return (186 <section187 class="peach-screen peach-theme peach-adopt-vault"188 classList={{ "peach-adopt-vault--pair": phase() === "pair" }}189 >190 <RuneBackground opacity={0.07} />191 <div192 class="peach-adopt-card"193 classList={{ "peach-adopt-card--pair": phase() === "pair" }}194 >195 <Switch>196 <Match when={phase() === "password"}>197 <h1>Set a password for this device.</h1>198 <p>This protects your vault on this device only. It can be different from your other devices.</p>199 <label class="peach-label" for="adopt-password">password</label>200 <input201 id="adopt-password"202 class="peach-underline-input peach-adopt-input"203 type="password"204 autocomplete="new-password"205 value={password()}206 onInput={(event) => setPassword((event.target as HTMLInputElement).value)}207 onKeyDown={(event) => {208 if (event.key === "Enter" && canContinue()) setPhase("pair");209 }}210 />211 <label class="peach-label" for="adopt-confirm-password">confirm password</label>212 <input213 id="adopt-confirm-password"214 class="peach-underline-input peach-adopt-input"215 type="password"216 autocomplete="new-password"217 value={confirmPassword()}218 onInput={(event) => setConfirmPassword((event.target as HTMLInputElement).value)}219 onKeyDown={(event) => {220 if (event.key === "Enter" && canContinue()) setPhase("pair");221 }}222 />223 <Show when={createBlocker()}>224 <p class="peach-hint">{createBlocker()}</p>225 </Show>226 <div class="peach-adopt-actions">227 <button class="peach-btn peach-btn--accent peach-btn--md" disabled={!canContinue()} onClick={() => setPhase("pair")}>228 Continue229 </button>230 <button class="peach-btn peach-btn--ghost peach-btn--md" onClick={props.onCancel}>Cancel</button>231 </div>232 </Match>233234 <Match when={phase() === "pair"}>235 <div236 class="peach-adopt-pairing"237 classList={{238 "has-sas": Boolean(receiverSas()),239 "is-complete": receiverComplete(),240 }}241 >242 <div243 class={`peach-pair-stage peach-adopt-bird-stage ${244 receiverComplete()245 ? "act-paired"246 : receiverSas()247 ? "act-handshake"248 : "act-listening"249 }`}250 aria-hidden="true"251 >252 <div class="peach-pair-bird-slot peach-pair-bird-slot-desktop">253 <DesktopBird pose={receiverComplete() ? "happy" : "chirping"} />254 </div>255 <Show when={receiverComplete()}>256 <span class="peach-adopt-connection" />257 </Show>258 <div class="peach-pair-bird-slot peach-pair-bird-slot-mobile">259 <MobileBird pose={receiverComplete() ? "happy" : "attentive"} />260 </div>261 </div>262263 <h1>{receiverComplete() ? "Paired" : "Pair a device"}</h1>264 <p class="peach-adopt-pair-lede" aria-live="polite">265 {receiverComplete()266 ? "Your devices are connected. Getting your vault ready…"267 : receiverSas()268 ? "Make sure this code matches the one on your phone."269 : "Scan this QR in Peach on the device that already has your vault."}270 </p>271272 <Show273 when={!receiverComplete()}274 fallback={275 <div class="peach-adopt-paired-status" role="status">276 <span />277 Secure connection established278 </div>279 }280 >281 <Show282 when={receiverSas()}283 fallback={284 <div class="peach-adopt-qr-wrap" aria-live="polite">285 <Show286 when={receiverInvitation()}287 fallback={288 <Show289 when={receiverError()}290 fallback={<p class="peach-adopt-pair-status">Preparing your secure pairing code…</p>}291 >292 <p class="peach-hint peach-hint-error">{receiverError()}</p>293 </Show>294 }295 >296 <PairingQrCode value={receiverInvitation()} size={144} />297 </Show>298 </div>299 }300 >301 <div class="peach-adopt-confirmation">302 <p class="peach-adopt-confirmation-label">8-DIGIT SAFETY CODE</p>303 <div class="peach-adoption-sas" aria-label="Pairing confirmation code">304 <strong>{receiverSas()}</strong>305 </div>306 <p class="peach-adopt-confirmation-help">307 Confirm this code matches the one on your phone.308 </p>309 <button310 class="peach-btn peach-btn--accent peach-btn--md"311 disabled={receiverSasDecision()}312 onClick={confirmReceiverSas}313 >314 {receiverSasDecision() ? "Code confirmed" : "Confirm code"}315 </button>316 </div>317 </Show>318319 <div class="peach-adopt-privacy">320 <svg viewBox="0 0 24 24" aria-hidden="true">321 <path d="M7 10V8a5 5 0 0 1 10 0v2" />322 <rect x="5" y="10" width="14" height="10" rx="3" />323 <path d="M12 14v2" />324 </svg>325 <p><strong>Private by design.</strong> {RELAY_DISCLOSURE}</p>326 </div>327328 <div class="peach-adopt-actions peach-adopt-pair-actions">329 <button class="peach-btn peach-btn--ghost peach-btn--md" onClick={props.onCancel}>Cancel</button>330 </div>331 </Show>332 </div>333 </Match>334335 <Match when={phase() === "error"}>336 <Show337 when={receiverError() === "ADOPT_PRO_REQUIRED"}338 fallback={339 <>340 <h1>Could not join the vault.</h1>341 <p class="peach-hint peach-hint-error">{receiverError()}</p>342 <div class="peach-adopt-actions">343 <button class="peach-btn peach-btn--accent peach-btn--md" onClick={tryAgain}>344 Try again345 </button>346 <button class="peach-btn peach-btn--ghost peach-btn--md" onClick={props.onCancel}>Cancel</button>347 </div>348 </>349 }350 >351 <PairingProRequired onRetry={tryAgain} />352 </Show>353 </Match>354 </Switch>355 </div>356 </section>357 );358}