Repository Public
1// Device pairing (SPV1 §5): the new-browser side (QR + code + fingerprint) and the trusted-device approval dialog.2import { useEffect, useRef, useState } from "react";3import QRCode from "qrcode";4import { decodePairingCode } from "../../../../packages/protocol/src/index.ts";5import { copyText, engine, errText, toast } from "../state.ts";6import { Btn, Callout, Dialog, ErrorText, Field, Icon, useAction } from "./common.tsx";78export function QrCanvas({ text, label }: { text: string; label: string }) {9 const ref = useRef<HTMLCanvasElement>(null);10 const [failed, setFailed] = useState(false);11 useEffect(() => {12 if (!ref.current) return;13 // Rendered to a canvas (no markup injection); always dark-on-white so that cameras read it in both themes.14 QRCode.toCanvas(ref.current, text, { margin: 2, width: 208, errorCorrectionLevel: "M", color: { dark: "#0c1113", light: "#ffffff" } }).catch(() => setFailed(true));15 }, [text]);16 return failed ? <p className="muted">The QR code could not be drawn. Use the text code instead.</p> : <canvas ref={ref} className="qr" role="img" aria-label={label} width={208} height={208} />;17}1819export function Sas({ value }: { value: string }) {20 return <span className="sas mono" data-testid="sas" aria-label={`Fingerprint ${value.split("").join(" ")}`}><span>{value.slice(0, 3)}</span><span>{value.slice(3)}</span></span>;21}2223/** Shown in a browser that is signed in (pending session) but not yet enrolled. */24export function EnrolBrowser({ handle, onDone, onUseRecovery, onCancel }: { handle: string; onDone: () => void; onUseRecovery: () => void; onCancel: () => void }) {25 const [pairing, setPairing] = useState<{ code: string; sas: string; until: number } | null>(null);26 const [status, setStatus] = useState<"starting" | "waiting" | "expired" | "rejected" | "error">("starting");27 const [error, setError] = useState("");28 const [left, setLeft] = useState(0);29 const started = useRef(false);3031 const start = async () => {32 setStatus("starting"); setError(""); setPairing(null);33 try { const p = await engine.startPairing(); setPairing({ code: p.code, sas: p.sas, until: Date.now() + p.expiresInSec * 1000 }); setLeft(p.expiresInSec); setStatus("waiting"); }34 catch (e) { setError(errText(e)); setStatus("error"); }35 };36 useEffect(() => { if (started.current) return; started.current = true; void start(); }, []);37 useEffect(() => {38 if (status !== "waiting" || !pairing) return;39 let stop = false, busy = false;40 const tick = setInterval(() => { const s = Math.max(0, Math.round((pairing.until - Date.now()) / 1000)); setLeft(s); if (s === 0) setStatus("expired"); }, 1000);41 const poll = setInterval(async () => {42 if (busy) return; busy = true;43 try { const r = await engine.checkPairing(); if (stop) return; if (r === "done") onDone(); else if (r === "rejected") setStatus("rejected"); }44 catch (e) { if (!stop) { setError(errText(e)); setStatus("error"); } }45 finally { busy = false; }46 }, 2000);47 return () => { stop = true; clearInterval(tick); clearInterval(poll); };48 }, [status, pairing]);4950 return (51 <div className="stack" data-testid="enrol">52 <h2 className="serif">Enrol this browser</h2>53 <p className="muted">You are signed in as <strong>{handle || "your account"}</strong>, but this browser holds no key yet. Approve it from a device that is already unlocked: <em>Devices → Approve a new device</em>.</p>54 {status === "starting" && <div className="pair-box"><span className="spinner big" aria-label="Preparing" /></div>}55 {status === "waiting" && pairing && (56 <>57 <div className="pair-box">58 <QrCanvas text={pairing.code} label="Pairing code as a QR code" />59 <div className="pair-side">60 <div><span className="eyebrow">Fingerprint — compare on both screens</span><Sas value={pairing.sas} /></div>61 <div className="pair-timer" aria-live="off"><Icon name="clock" size={15} /><span>Expires in {Math.floor(left / 60)}:{String(left % 60).padStart(2, "0")}</span></div>62 </div>63 </div>64 <Field label="Pairing code (if you cannot scan)" hint="The code never passes through the server in a usable form: it proves to your other device that the keys really come from this browser.">65 <div className="input-row">66 <input className="input mono" readOnly value={pairing.code} data-testid="pairing-code" onFocus={(e) => e.target.select()} />67 <Btn icon="copy" onClick={() => copyText(pairing.code, "Pairing code", false)}>Copy</Btn>68 </div>69 </Field>70 <p className="muted row"><span className="spinner" aria-hidden="true" /> Waiting for approval…</p>71 </>72 )}73 {status === "expired" && <Callout kind="warn" title="The code expired"><p>Pairing codes are valid for five minutes and can be used once.</p></Callout>}74 {status === "rejected" && <Callout kind="danger" title="The request was rejected"><p>The other device refused this pairing. If that was not you, someone else may hold your passkey.</p></Callout>}75 <ErrorText text={error} />76 {(status === "expired" || status === "rejected" || status === "error") && <Btn variant="primary" icon="refresh" onClick={start}>Generate a new code</Btn>}77 <div className="row between wrap">78 <Btn variant="ghost" onClick={onCancel}>Cancel</Btn>79 <Btn variant="ghost" icon="key" onClick={onUseRecovery} data-testid="use-recovery">Use recovery key instead</Btn>80 </div>81 </div>82 );83}8485type Inspect = Awaited<ReturnType<typeof engine.inspectPairing>>;8687/** Trusted side: paste or scan the code, compare the fingerprint, approve or reject. */88export function ApproveDeviceDialog({ onClose, onApproved }: { onClose: () => void; onApproved: () => void }) {89 const [code, setCode] = useState("");90 const [req, setReq] = useState<Inspect | null>(null);91 const [scanning, setScanning] = useState(false);92 const act = useAction();93 const canScan = typeof (window as any).BarcodeDetector === "function" && !!navigator.mediaDevices?.getUserMedia;94 const valid = (() => { try { decodePairingCode(code); return true; } catch { return false; } })();9596 const inspect = (c = code) => act.run(async () => { setReq(await engine.inspectPairing(c)); });97 const approve = () => act.run(async () => { await req!.approve(); toast("Device approved. It can now decrypt the vault.", "ok"); onApproved(); onClose(); });98 const reject = () => act.run(async () => { await req!.reject(); toast("Pairing request rejected."); onClose(); });99100 return (101 <Dialog title="Approve a new device" onClose={onClose}>102 {!req ? (103 <form className="stack" onSubmit={(e) => { e.preventDefault(); if (valid) void inspect(); }}>104 <p className="muted">On the new device, sign in with your passkey. It shows a QR code and a text code. Enter that code here.</p>105 {scanning ? <Scanner onCode={(c) => { setScanning(false); setCode(c); void inspect(c); }} onStop={() => setScanning(false)} /> : (106 <>107 <Field label="Pairing code" error={code && !valid ? "This is not an SP Vault pairing code" : undefined}>108 <textarea className="input mono" rows={3} value={code} onChange={(e) => setCode(e.target.value.trim())} spellCheck={false} autoComplete="off" placeholder="spvault-pair:…" data-autofocus data-testid="approve-code" />109 </Field>110 {canScan && <Btn icon="qr" onClick={() => setScanning(true)}>Scan QR code with the camera</Btn>}111 </>112 )}113 <ErrorText text={act.error} />114 <div className="row end"><Btn onClick={onClose}>Cancel</Btn><Btn variant="primary" type="submit" disabled={!valid} busy={act.busy} data-testid="approve-inspect">Continue</Btn></div>115 </form>116 ) : (117 <div className="stack">118 <Callout kind="ok" title="The code matches the keys relayed by the server"><p>The request really comes from the device that displayed this code.</p></Callout>119 <dl className="kv">120 <dt>Device</dt><dd>{req.platform}</dd>121 <dt>Fingerprint</dt><dd><Sas value={req.sas} /></dd>122 </dl>123 <p>Compare these six digits with the other screen. Approve <strong>only if they are identical</strong> and you started this yourself: the new device will be able to decrypt everything in your vault.</p>124 <p className="muted">Approving asks for your passkey if it was not used in the last few minutes.</p>125 <ErrorText text={act.error} />126 <div className="row end"><Btn variant="danger" onClick={reject} disabled={act.busy}>Reject</Btn><Btn variant="primary" onClick={approve} busy={act.busy} data-testid="approve-ok">The digits match — approve</Btn></div>127 </div>128 )}129 </Dialog>130 );131}132133function Scanner({ onCode, onStop }: { onCode: (code: string) => void; onStop: () => void }) {134 const ref = useRef<HTMLVideoElement>(null);135 const [error, setError] = useState("");136 useEffect(() => {137 let stream: MediaStream | undefined, stop = false, timer: ReturnType<typeof setInterval> | undefined;138 (async () => {139 try {140 stream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: "environment" }, audio: false });141 if (stop) { stream.getTracks().forEach((t) => t.stop()); return; }142 const video = ref.current!; video.srcObject = stream; await video.play();143 const detector = new (window as any).BarcodeDetector({ formats: ["qr_code"] });144 timer = setInterval(async () => {145 try { for (const c of await detector.detect(video)) { const v = String(c.rawValue ?? ""); if (v.startsWith("spvault-pair:")) { onCode(v); return; } } } catch { /* frame not ready */ }146 }, 350);147 } catch { setError("The camera could not be used. Paste the text code instead."); }148 })();149 return () => { stop = true; clearInterval(timer); stream?.getTracks().forEach((t) => t.stop()); };150 }, []);151 return (152 <div className="stack">153 <video ref={ref} className="scanner" muted playsInline aria-label="Camera preview" />154 <ErrorText text={error} />155 <Btn onClick={onStop}>Enter the code by hand</Btn>156 </div>157 );158}159