SPB Git

Repository Public

Onboarding.tsx 11.2 KB 191 lines tsx

1// Signed-out screens: welcome, join by invitation, recovery with the recovery key, locked.2import { type ReactNode, useEffect, useState } from "react";3import { decodeRecoveryKey } from "../../../../packages/protocol/src/index.ts";4import { ApiError } from "../core/engine.ts";5import { confirmAction, engine, errText, notice, useNotice } from "../state.ts";6import { Brand, Btn, Callout, ErrorText, Field, Icon, useAction } from "./common.tsx";7import { RecoveryKit } from "./RecoveryKit.tsx";89export function AuthLayout({ children, wide }: { children: ReactNode; wide?: boolean }) {10  return (11    <div className="auth">12      <div className="auth-glow" aria-hidden="true" />13      <header className="auth-brand"><Brand size={34} /></header>14      <main className={`auth-card${wide ? " wide" : ""}`}>{children}</main>15      <footer className="auth-foot">16        <span><Icon name="lock" size={13} /> End-to-end encrypted · keys never leave your devices</span>17      </footer>18    </div>19  );20}2122function NoticeLine() {23  const n = useNotice();24  if (!n) return null;25  return <Callout kind="info"><p data-testid="notice">{n}</p></Callout>;26}2728const HANDLE = /^[a-z0-9][a-z0-9._-]{1,31}$/;2930export function Welcome({ onPending, onRecover }: { onPending: () => void; onRecover: () => void }) {31  const act = useAction();32  const signIn = () => act.run(async () => { notice.set(""); if ((await engine.signIn()) === "pending") onPending(); });33  return (34    <AuthLayout>35      <div className="stack" data-testid="welcome">36        <h1 className="serif auth-title">Open your vault</h1>37        <p className="muted">Passwords, passkeys, cards and secrets — encrypted on your device before anything is sent. The server stores ciphertext it cannot read.</p>38        <NoticeLine />39        <ErrorText text={act.error} />40        <Btn variant="primary" icon="passkey" className="block" onClick={signIn} busy={act.busy} data-testid="signin">Sign in with passkey</Btn>41        <Btn icon="key" className="block" onClick={onRecover} data-testid="goto-recover">Recover with recovery key</Btn>42        <p className="fine">New here? Accounts are created by invitation link only. Ask the vault owner for one and open it in this browser.</p>43      </div>44    </AuthLayout>45  );46}4748export function Locked({ onPending, onForgotten }: { onPending: () => void; onForgotten: () => void }) {49  const act = useAction();50  const handle = engine.identity?.handle ?? "";51  const unlock = () => act.run(async () => {52    notice.set("");53    try { if ((await engine.signIn()) === "pending") onPending(); }54    catch (e) {55      if (e instanceof ApiError && e.code === "device_revoked") { notice.set(errText(e)); onForgotten(); return; }56      throw e;57    }58  });59  const remove = async () => {60    if (!(await confirmAction({ title: "Remove this browser?", danger: true, confirmLabel: "Remove this browser",61      body: ["Everything SP Vault stored in this browser is erased: the device key and the encrypted local copy.", "Your account and your other devices are not affected. To come back you will need to pair this browser again or use your recovery key."] }))) return;62    await act.run(async () => { await engine.signOut(); await engine.forget(); onForgotten(); });63  };64  return (65    <AuthLayout>66      <div className="stack center" data-testid="locked">67        <span className="lock-mark"><Icon name="lock" size={30} /></span>68        <h1 className="serif auth-title">Vault locked</h1>69        <p className="muted">Signed in on this browser as <strong data-testid="locked-handle">{handle}</strong></p>70        <NoticeLine />71        <ErrorText text={act.error} />72        <Btn variant="primary" icon="passkey" className="block" onClick={unlock} busy={act.busy} data-testid="unlock" autoFocus>Unlock with passkey</Btn>73        <Btn variant="ghost" className="block" onClick={remove} disabled={act.busy} data-testid="remove-browser">Remove this browser</Btn>74        <p className="fine">Unlocking contacts the server: the key that opens your vault is released to this browser only after a passkey check.</p>75      </div>76    </AuthLayout>77  );78}7980export function Join({ invite, onDone, onExisting }: { invite: string; onDone: () => void; onExisting: () => void }) {81  const [handle, setHandle] = useState("");82  const [kit, setKit] = useState<string | null>(null);83  const act = useAction();84  const valid = HANDLE.test(handle);85  useEffect(() => {86    if (!kit) return;87    const guard = (e: BeforeUnloadEvent) => { e.preventDefault(); };88    window.addEventListener("beforeunload", guard);89    return () => window.removeEventListener("beforeunload", guard);90  }, [kit]);9192  if (kit) return <AuthLayout wide><RecoveryKit recoveryKey={kit} handle={handle} reason="new" onDone={onDone} /></AuthLayout>;93  if (engine.identity) {94    return (95      <AuthLayout>96        <div className="stack">97          <h1 className="serif auth-title">This browser already has a vault</h1>98          <p className="muted">It is enrolled for <strong>{engine.identity.handle}</strong>. To create another account here, first remove this browser from the locked screen.</p>99          <Btn variant="primary" onClick={onExisting}>Go to my vault</Btn>100        </div>101      </AuthLayout>102    );103  }104  const create = () => act.run(async () => { setKit(await engine.register(invite, handle)); });105  return (106    <AuthLayout>107      <form className="stack" data-testid="join" onSubmit={(e) => { e.preventDefault(); if (valid) void create(); }}>108        <span className="eyebrow">Invitation accepted</span>109        <h1 className="serif auth-title">Create your vault</h1>110        <p className="muted">Choose a handle, then create a passkey. There is no master password: your passkey signs you in and your devices hold the keys.</p>111        <Field label="Handle" hint="2–32 characters: lowercase letters, digits, dot, dash or underscore. Other members use it to share with you." error={handle && !valid ? "Use lowercase letters, digits, . _ - and start with a letter or digit" : undefined}>112          <input className="input" value={handle} onChange={(e) => setHandle(e.target.value.toLowerCase().trim())} autoComplete="username webauthn" autoCapitalize="none" spellCheck={false} maxLength={32} autoFocus data-testid="join-handle" aria-invalid={!!handle && !valid} />113        </Field>114        <ErrorText text={act.error} />115        <Btn variant="primary" icon="passkey" className="block" type="submit" disabled={!valid} busy={act.busy} data-testid="join-create">Create passkey and vault</Btn>116        <ol className="steps-list">117          <li><strong>Passkey</strong> — your browser or device asks to create one.</li>118          <li><strong>Recovery key</strong> — shown once; you print or write it down.</li>119          <li><strong>Verification</strong> — you type three groups back to prove the copy works.</li>120        </ol>121      </form>122    </AuthLayout>123  );124}125126/** Live checksum validation: the key is decoded locally; nothing is sent while typing. */127export function useRecoveryKeyCheck(text: string): "empty" | "incomplete" | "bad" | "ok" {128  const [state, setState] = useState<"empty" | "incomplete" | "bad" | "ok">("empty");129  useEffect(() => {130    let live = true;131    const compact = text.toUpperCase().replace(/[\s-]/g, "").replace(/^SPV1/, "");132    if (!compact) { setState("empty"); return; }133    if (compact.length < 56) { setState("incomplete"); return; }134    decodeRecoveryKey(text).then((rk) => { rk.fill(0); if (live) setState("ok"); }, () => { if (live) setState("bad"); });135    return () => { live = false; };136  }, [text]);137  return state;138}139export function RecoveryKeyInput({ value, onChange, testid }: { value: string; onChange: (v: string) => void; testid?: string }) {140  const check = useRecoveryKeyCheck(value);141  const compact = value.toUpperCase().replace(/[\s-]/g, "").replace(/^SPV1/, "");142  return (143    <Field label="Recovery key" error={check === "bad" ? "The checksum does not match — check for a typo (0/O and 1/I/L are treated as the same)" : undefined}144      hint={check === "ok" ? <span className="ok-text"><Icon name="check" size={13} /> Checksum valid</span> : check === "incomplete" ? `${compact.length} of 56 characters` : "Starts with SPV1 — 14 groups of 4 characters. Dashes and case do not matter."}>145      <textarea className="input mono recovery-input" rows={3} value={value} onChange={(e) => onChange(e.target.value)} autoComplete="off" autoCapitalize="characters" spellCheck={false} placeholder="SPV1-XXXX-XXXX-…" data-testid={testid ?? "recovery-input"} aria-invalid={check === "bad"} />146    </Field>147  );148}149150export function Recover({ initialHandle, onDone, onBack }: { initialHandle?: string; onDone: () => void; onBack: () => void }) {151  const [handle, setHandle] = useState(initialHandle ?? "");152  const [key, setKey] = useState("");153  const [step, setStep] = useState<"form" | "passkey">("form");154  const check = useRecoveryKeyCheck(key);155  const act = useAction(), pk = useAction();156  const ready = HANDLE.test(handle) && check === "ok";157  const recover = () => act.run(async () => { await engine.recover(handle, key); setKey(""); setStep("passkey"); });158  const addPasskey = () => pk.run(async () => { await engine.addPasskey("Added after recovery"); onDone(); });159160  if (step === "passkey") {161    return (162      <AuthLayout>163        <div className="stack" data-testid="recovered">164          <span className="lock-mark ok"><Icon name="check" size={30} /></span>165          <h1 className="serif auth-title">Vault recovered</h1>166          <p className="muted">This browser is now a trusted device. If the passkey you used before is lost, create a new one now — without a passkey you cannot unlock this browser again after it locks.</p>167          <ErrorText text={pk.error} />168          <Btn variant="primary" icon="passkey" className="block" onClick={addPasskey} busy={pk.busy} data-testid="recover-add-passkey">Create a passkey for this browser</Btn>169          <Btn variant="ghost" className="block" onClick={onDone} disabled={pk.busy} data-testid="recover-skip">I still have my passkey — continue</Btn>170          <p className="fine">The recovery key you just typed has been used on this device. Issue a new one from Settings → Recovery key once you are in.</p>171        </div>172      </AuthLayout>173    );174  }175  return (176    <AuthLayout>177      <form className="stack" data-testid="recover" onSubmit={(e) => { e.preventDefault(); if (ready) void recover(); }}>178        <h1 className="serif auth-title">Recover your vault</h1>179        <p className="muted">Use the recovery key from your printed kit. It is checked in this browser first, then proves to the server that you may download the encrypted key envelope. The key itself is never sent.</p>180        <Field label="Handle">181          <input className="input" value={handle} onChange={(e) => setHandle(e.target.value.toLowerCase().trim())} autoComplete="username" autoCapitalize="none" spellCheck={false} maxLength={32} autoFocus={!initialHandle} data-testid="recover-handle" />182        </Field>183        <RecoveryKeyInput value={key} onChange={setKey} />184        <ErrorText text={act.error} />185        <Btn variant="primary" className="block" type="submit" disabled={!ready} busy={act.busy} data-testid="recover-submit">Recover</Btn>186        <Btn variant="ghost" icon="back" onClick={onBack} disabled={act.busy}>Back</Btn>187      </form>188    </AuthLayout>189  );190}191
Files main
Menu

Theme