Repository Public
1import { startAuthentication, startRegistration } from "@simplewebauthn/browser"2import { useCallback, useEffect, useRef, useState, type ReactNode } from "react"3import { CallManager } from "../core/calls"4import { Engine } from "../core/engine"5import { IdbStore } from "../core/store"6import { BrowserTransport } from "../core/transport"7import { ApiError, type Me } from "../core/types"8import { EngineCtx, errText, I, t, Toasts } from "./bits"9import { Shell } from "./shell"1011const transport = new BrowserTransport()1213export function deviceLabel() {14 const ua = navigator.userAgent15 const os = /iPhone/.test(ua) ? "iPhone" : /iPad/.test(ua) ? "iPad" : /Android/.test(ua) ? "Android" : /Mac/.test(ua) ? "Mac" : /Windows/.test(ua) ? "Windows" : /Linux/.test(ua) ? "Linux" : "Device"16 const br = /Edg\//.test(ua) ? "Edge" : /Chrome\//.test(ua) ? "Chrome" : /Firefox\//.test(ua) ? "Firefox" : /Safari\//.test(ua) ? "Safari" : "Browser"17 return `${br} · ${os}`18}1920type MeResponse = { user: Me; session: { id: string; device_id: string | null }; devices: unknown[]; has_backup: boolean }21type Phase =22 | { k: "loading" }23 | { k: "anon" }24 | { k: "join"; token: string; bootstrap: boolean }25 | { k: "first-device"; me: MeResponse; store: IdbStore }26 | { k: "link-device"; me: MeResponse; store: IdbStore }27 | { k: "recovery-key"; key: string; next: () => void }28 | { k: "pending"; me: MeResponse }29 | { k: "ready"; engine: Engine; calls: CallManager }30 | { k: "error"; message: string }3132export function App() {33 const [phase, setPhase] = useState<Phase>({ k: "loading" })34 const engineRef = useRef<Engine | null>(null)3536 const boot = useCallback(async () => {37 const hashToken = location.hash.slice(1)38 const path = location.pathname39 let me: MeResponse40 try {41 me = await transport.request<MeResponse>("GET", "/api/me")42 } catch (e) {43 if (e instanceof ApiError && e.status === 401) {44 if ((path === "/invite" || path === "/bootstrap") && hashToken.length >= 20) return setPhase({ k: "join", token: hashToken, bootstrap: path === "/bootstrap" })45 return setPhase({ k: "anon" })46 }47 return setPhase({ k: "error", message: errText(e) })48 }49 if (path === "/invite" || path === "/bootstrap") history.replaceState(null, "", "/")50 const store = await new IdbStore(`spm-${me.user.id}`).open()51 let dev = await Engine.loadDevice(store, me.user)52 if (dev && me.session.device_id !== dev.deviceId) {53 try {54 await Engine.bindSession(transport, dev, me.session.id)55 } catch (e) {56 if (e instanceof ApiError && (e.code === "unknown_device" || e.code === "invalid_signature")) {57 await store.clear() // this browser's device was revoked: nothing stored here is usable any more58 dev = null59 } else return setPhase({ k: "error", message: errText(e) })60 }61 }62 if (dev && me.user.identity_key && btoa(String.fromCharCode(...dev.identityKey)) !== me.user.identity_key) {63 await store.clear() // the account identity was reset by an administrator64 dev = null65 }66 if (!dev) return setPhase(me.user.identity_key ? { k: "link-device", me, store } : { k: "first-device", me, store })67 if (me.user.status !== "active") return setPhase({ k: "pending", me })68 const engine = new Engine(transport, store, me.user, dev)69 engineRef.current = engine70 const calls = new CallManager(engine)71 await engine.start()72 setPhase({ k: "ready", engine, calls })73 }, [])7475 useEffect(() => {76 void boot().catch((e) => setPhase({ k: "error", message: errText(e) }))77 return () => engineRef.current?.stop()78 }, [boot])7980 const signOut = useCallback(async (wipe: boolean) => {81 const e = engineRef.current82 if (e && wipe) {83 await transport.request("DELETE", `/api/devices/${e.deviceId}`).catch(() => {})84 await e.wipe()85 } else e?.stop()86 await transport.request("POST", "/api/logout").catch(() => {})87 location.href = "/"88 }, [])8990 let body: ReactNode91 switch (phase.k) {92 case "loading":93 body = <Stage><div className="row" style={{ justifyContent: "center" }}><span className="spinner" /></div></Stage>94 break95 case "error":96 body = (97 <Stage>98 <h1 className="h1">{t("Something went wrong", "Un problème est survenu")}</h1>99 <p className="muted">{phase.message}</p>100 <button className="btn primary lg" onClick={() => location.reload()}>{t("Try again", "Réessayer")}</button>101 </Stage>102 )103 break104 case "anon":105 body = <SignIn onDone={boot} />106 break107 case "join":108 body = <Join token={phase.token} bootstrap={phase.bootstrap} onDone={boot} />109 break110 case "first-device":111 body = <FirstDevice me={phase.me} store={phase.store} onKey={(key) => setPhase({ k: "recovery-key", key, next: boot })} />112 break113 case "recovery-key":114 body = <RecoveryKey value={phase.key} onDone={phase.next} />115 break116 case "link-device":117 body = <LinkDevice me={phase.me} store={phase.store} onDone={boot} onSignOut={() => signOut(false)} />118 break119 case "pending":120 body = <Pending onRetry={boot} onSignOut={() => signOut(false)} />121 break122 case "ready":123 body = (124 <EngineCtx.Provider value={{ engine: phase.engine, calls: phase.calls, signOut }}>125 <Shell />126 </EngineCtx.Provider>127 )128 }129 return (130 <>131 {body}132 <Toasts />133 </>134 )135}136137function Stage({ children, step, steps }: { children: ReactNode; step?: number; steps?: number }) {138 return (139 <main className="stage">140 <div className="stage-card">141 <div className="brand"><img src="/icon.svg" alt="" />SP Message</div>142 {steps ? <div className="steps" aria-hidden="true">{Array.from({ length: steps }, (_, i) => <i key={i} className={i <= (step ?? 0) ? "on" : ""} />)}</div> : null}143 {children}144 </div>145 </main>146 )147}148149function Points() {150 return (151 <div className="points">152 <div className="point"><span className="ic">{I.lock}</span><div><b>{t("Encrypted on your devices", "Chiffré sur vos appareils")}</b><span className="muted small">{t("Messages, files and calls are encrypted before they leave your device. The server stores only ciphertext.", "Messages, fichiers et appels sont chiffrés avant de quitter votre appareil. Le serveur ne conserve que du texte chiffré.")}</span></div></div>153 <div className="point"><span className="ic">{I.key}</span><div><b>{t("No password", "Aucun mot de passe")}</b><span className="muted small">{t("You sign in with a passkey: Face ID, Touch ID or your device lock.", "Vous vous connectez avec une clé d’accès : Face ID, Touch ID ou le verrou de votre appareil.")}</span></div></div>154 <div className="point"><span className="ic">{I.users}</span><div><b>{t("By invitation only", "Sur invitation seulement")}</b><span className="muted small">{t("A private network: only invited people can join and find you.", "Un réseau privé : seules les personnes invitées peuvent s’inscrire et vous trouver.")}</span></div></div>155 </div>156 )157}158159function SignIn({ onDone }: { onDone: () => void }) {160 const [busy, setBusy] = useState(false)161 const [err, setErr] = useState("")162 const go = async () => {163 setBusy(true)164 setErr("")165 try {166 const { challenge_id, options } = await transport.request<any>("POST", "/api/login/options", {})167 const response = await startAuthentication({ optionsJSON: options })168 await transport.request("POST", "/api/login/verify", { challenge_id, response })169 onDone()170 } catch (e) {171 setErr((e as Error).name === "NotAllowedError" ? t("Sign-in was cancelled.", "Connexion annulée.") : errText(e))172 setBusy(false)173 }174 }175 return (176 <Stage>177 <h1 className="h1">{t("Private conversations,", "Des conversations privées,")}<br /><span className="grad-text">{t("truly yours.", "vraiment à vous.")}</span></h1>178 <Points />179 <button className="btn primary lg block" onClick={go} disabled={busy}>{busy ? <span className="spinner" /> : I.key}{t("Sign in with a passkey", "Se connecter avec une clé d’accès")}</button>180 {err && <p className="err" role="alert">{err}</p>}181 <p className="dim small">{t("New here? SP Message is invitation-only: open the link you received.", "Nouveau ? SP Message fonctionne sur invitation : ouvrez le lien que vous avez reçu.")}</p>182 </Stage>183 )184}185186function Join({ token, bootstrap, onDone }: { token: string; bootstrap: boolean; onDone: () => void }) {187 const [info, setInfo] = useState<any>(null)188 const [step, setStep] = useState(0)189 const [name, setName] = useState("")190 const [handle, setHandle] = useState("")191 const [err, setErr] = useState("")192 const [busy, setBusy] = useState(false)193 useEffect(() => {194 transport.request("POST", "/api/invitations/check", { token, bootstrap }).then(setInfo).catch(() => setInfo({ invalid: true }))195 }, [token, bootstrap])196 if (!info) return <Stage><div className="row" style={{ justifyContent: "center" }}><span className="spinner" /></div></Stage>197 if (info.invalid)198 return (199 <Stage>200 <h1 className="h1">{t("This link is no longer valid", "Ce lien n’est plus valide")}</h1>201 <p className="muted">{t("It has expired, was revoked, or has already been used. Ask the person who invited you for a new one.", "Il a expiré, a été révoqué ou a déjà été utilisé. Demandez un nouveau lien à la personne qui vous a invité.")}</p>202 <a className="btn" href="/">{t("Go to sign-in", "Aller à la connexion")}</a>203 </Stage>204 )205 const create = async () => {206 setBusy(true)207 setErr("")208 try {209 const { challenge_id, options } = await transport.request<any>("POST", "/api/register/options", { token, bootstrap, handle, display_name: name })210 const response = await startRegistration({ optionsJSON: options })211 await transport.request("POST", "/api/register/verify", { challenge_id, response, label: deviceLabel() })212 history.replaceState(null, "", "/")213 onDone()214 } catch (e) {215 const code = e instanceof ApiError ? e.code : ""216 setErr(217 code === "handle_taken" ? t("This username is already taken.", "Ce nom d’utilisateur est déjà pris.")218 : (e as Error).name === "NotAllowedError" ? t("Passkey creation was cancelled.", "Création de la clé d’accès annulée.")219 : (e as Error).name === "InvalidStateError" ? t("This device already has a passkey for SP Message.", "Cet appareil possède déjà une clé d’accès pour SP Message.")220 : errText(e),221 )222 setBusy(false)223 }224 }225 if (step === 0)226 return (227 <Stage step={0} steps={3}>228 <h1 className="h1">229 {bootstrap ? t("Set up the administrator", "Créer l’administrateur") : <>{info.inviter ? `${info.inviter.display_name} ${t("invites you to", "vous invite sur")}` : t("You are invited to", "Vous êtes invité sur")}<br /><span className="grad-text">SP Message</span></>}230 </h1>231 {bootstrap && <p className="muted">{t("This one-time link creates the first administrator account of this server.", "Ce lien à usage unique crée le premier compte administrateur de ce serveur.")}</p>}232 <Points />233 <button className="btn primary lg block" onClick={() => setStep(1)}>{t("Continue", "Continuer")}</button>234 {info.require_approval && <p className="dim small">{t("An administrator will confirm your account before you can start.", "Un administrateur confirmera votre compte avant que vous puissiez commencer.")}</p>}235 </Stage>236 )237 const validHandle = /^[a-z0-9_.-]{2,32}$/.test(handle)238 return (239 <Stage step={1} steps={3}>240 <h1 className="h1">{t("Your profile", "Votre profil")}</h1>241 <div className="field">242 <label htmlFor="name">{t("Name shown to your contacts", "Nom affiché à vos contacts")}</label>243 <input id="name" className="input" value={name} maxLength={64} autoComplete="name" autoFocus onChange={(e) => {244 setName(e.target.value)245 if (!handle || handle === slug(name)) setHandle(slug(e.target.value))246 }} />247 </div>248 <div className="field">249 <label htmlFor="handle">{t("Username", "Nom d’utilisateur")}</label>250 <input id="handle" className="input" value={handle} maxLength={32} autoCapitalize="none" autoCorrect="off" spellCheck={false} onChange={(e) => setHandle(e.target.value.toLowerCase())} />251 <span className="dim tiny">{t("Lowercase letters, digits, dot, dash, underscore.", "Minuscules, chiffres, point, tiret, tiret bas.")}</span>252 </div>253 <div className="banner info">{I.key}<span>{t("Next, your device will offer to create a passkey. It stays in your keychain; nothing secret is sent to the server.", "Votre appareil va ensuite proposer de créer une clé d’accès. Elle reste dans votre trousseau ; rien de secret n’est envoyé au serveur.")}</span></div>254 {err && <p className="err" role="alert">{err}</p>}255 <button className="btn primary lg block" disabled={busy || !name.trim() || !validHandle} onClick={create}>{busy ? <span className="spinner" /> : I.key}{t("Create my passkey", "Créer ma clé d’accès")}</button>256 </Stage>257 )258}259const slug = (s: string) => s.normalize("NFD").replace(/[̀-ͯ]/g, "").toLowerCase().replace(/[^a-z0-9]+/g, ".").replace(/^\.+|\.+$/g, "").slice(0, 32)260261function FirstDevice({ me, store, onKey }: { me: MeResponse; store: IdbStore; onKey: (key: string) => void }) {262 const [err, setErr] = useState("")263 const started = useRef(false)264 useEffect(() => {265 if (started.current) return266 started.current = true267 Engine.createIdentity(transport, store, me.user, deviceLabel()).then((r) => onKey(r.recoveryKey)).catch((e) => setErr(errText(e)))268 }, [me, store, onKey])269 return (270 <Stage step={2} steps={3}>271 <h1 className="h1">{t("Creating your encryption keys", "Création de vos clés de chiffrement")}</h1>272 <p className="muted">{t("They are generated on this device and never leave it unencrypted.", "Elles sont générées sur cet appareil et ne le quittent jamais en clair.")}</p>273 {err ? <p className="err" role="alert">{err}</p> : <div className="row"><span className="spinner" /></div>}274 </Stage>275 )276}277278export function RecoveryKey({ value, onDone }: { value: string; onDone: () => void }) {279 const [ok, setOk] = useState(false)280 return (281 <Stage step={2} steps={3}>282 <h1 className="h1">{t("Your recovery key", "Votre clé de récupération")}</h1>283 <p className="muted">{t("If you lose all your devices, this key is the only way to recover your encryption identity. Write it down or store it in a password manager. It is shown only once and the server cannot read it.", "Si vous perdez tous vos appareils, cette clé est le seul moyen de retrouver votre identité de chiffrement. Notez-la ou rangez-la dans un gestionnaire de mots de passe. Elle n’est affichée qu’une fois et le serveur ne peut pas la lire.")}</p>284 <div className="recovery" data-testid="recovery-key">{value}</div>285 <button className="btn" onClick={() => navigator.clipboard?.writeText(value)}>{I.copy}{t("Copy", "Copier")}</button>286 <label className="row small"><input type="checkbox" checked={ok} onChange={(e) => setOk(e.target.checked)} />{t("I have stored my recovery key somewhere safe.", "J’ai rangé ma clé de récupération en lieu sûr.")}</label>287 <button className="btn primary lg block" disabled={!ok} onClick={onDone}>{t("Open SP Message", "Ouvrir SP Message")}</button>288 </Stage>289 )290}291292function LinkDevice({ me, store, onDone, onSignOut }: { me: MeResponse; store: IdbStore; onDone: () => void; onSignOut: () => void }) {293 const [mode, setMode] = useState<"choose" | "approve" | "recovery">("choose")294 const [code, setCode] = useState("")295 const [key, setKey] = useState("")296 const [err, setErr] = useState("")297 const [busy, setBusy] = useState(false)298 useEffect(() => {299 if (mode !== "approve") return300 let stop = false301 Engine.requestLink(transport, store, me.user, deviceLabel()).then((r) => !stop && setCode(r.code)).catch((e) => setErr(errText(e)))302 const timer = setInterval(async () => {303 try {304 const fresh = await transport.request<MeResponse>("GET", "/api/me")305 if (await Engine.completeLink(transport, store, fresh.user)) {306 clearInterval(timer)307 onDone()308 }309 } catch (e) {310 setErr(errText(e))311 clearInterval(timer)312 }313 }, 2000)314 return () => {315 stop = true316 clearInterval(timer)317 }318 }, [mode, me, store, onDone])319 const recover = async () => {320 setBusy(true)321 setErr("")322 try {323 await Engine.recover(transport, store, me.user, key, deviceLabel())324 onDone()325 } catch (e) {326 setErr(errText(e))327 setBusy(false)328 }329 }330 if (mode === "approve")331 return (332 <Stage>333 <h1 className="h1">{t("Approve this device", "Approuvez cet appareil")}</h1>334 <p className="muted">{t("Open SP Message on a device where you are already signed in. A request appears there: check that it shows the same code, then approve.", "Ouvrez SP Message sur un appareil déjà connecté. Une demande y apparaît : vérifiez qu’elle affiche le même code, puis approuvez.")}</p>335 <div className="code" data-testid="link-code">{code ? `${code.slice(0, 3)} ${code.slice(3)}` : "··· ···"}</div>336 <div className="row muted small"><span className="spinner" />{t("Waiting for approval…", "En attente d’approbation…")}</div>337 {err && <p className="err" role="alert">{err}</p>}338 <button className="btn ghost" onClick={() => (void Engine.cancelLink(transport, store), setMode("choose"), setErr(""))}>{t("Cancel", "Annuler")}</button>339 </Stage>340 )341 if (mode === "recovery")342 return (343 <Stage>344 <h1 className="h1">{t("Enter your recovery key", "Saisissez votre clé de récupération")}</h1>345 <textarea className="textarea mono" value={key} onChange={(e) => setKey(e.target.value)} placeholder="XXXX-XXXX-XXXX-XXXX-XXXX-XXXX-XXXX-XXXX" autoCapitalize="characters" spellCheck={false} aria-label={t("Recovery key", "Clé de récupération")} />346 {err && <p className="err" role="alert">{err}</p>}347 <button className="btn primary lg block" disabled={busy || key.replace(/[^A-Za-z0-9]/g, "").length < 32} onClick={recover}>{busy && <span className="spinner" />}{t("Restore my identity", "Restaurer mon identité")}</button>348 <button className="btn ghost" onClick={() => (setMode("choose"), setErr(""))}>{t("Back", "Retour")}</button>349 </Stage>350 )351 return (352 <Stage>353 <h1 className="h1">{t("Add this device", "Ajouter cet appareil")}</h1>354 <p className="muted">{t("Your passkey proved who you are. To read encrypted conversations, this device also needs your encryption identity, which the server does not hold.", "Votre clé d’accès a prouvé votre identité. Pour lire les conversations chiffrées, cet appareil a aussi besoin de votre identité de chiffrement, que le serveur ne détient pas.")}</p>355 <button className="btn primary lg block" onClick={() => setMode("approve")}>{I.device}{t("Approve from another device", "Approuver depuis un autre appareil")}</button>356 <button className="btn lg block" onClick={() => setMode("recovery")}>{I.key}{t("Use my recovery key", "Utiliser ma clé de récupération")}</button>357 <p className="dim small">{t("Messages sent before this device was added stay on your other devices: they cannot be decrypted here.", "Les messages envoyés avant l’ajout de cet appareil restent sur vos autres appareils : ils ne peuvent pas être déchiffrés ici.")}</p>358 <button className="btn ghost" onClick={onSignOut}>{I.logout}{t("Sign out", "Se déconnecter")}</button>359 </Stage>360 )361}362363function Pending({ onRetry, onSignOut }: { onRetry: () => void; onSignOut: () => void }) {364 useEffect(() => {365 const timer = setInterval(onRetry, 8000)366 return () => clearInterval(timer)367 }, [onRetry])368 return (369 <Stage>370 <h1 className="h1">{t("Waiting for approval", "En attente d’approbation")}</h1>371 <p className="muted">{t("Your account and your keys are ready. An administrator must confirm your registration before you can start a conversation. This page updates by itself.", "Votre compte et vos clés sont prêts. Un administrateur doit confirmer votre inscription avant que vous puissiez commencer une conversation. Cette page se met à jour seule.")}</p>372 <div className="row muted small"><span className="spinner" />{t("Checking…", "Vérification…")}</div>373 <button className="btn ghost" onClick={onSignOut}>{I.logout}{t("Sign out", "Se déconnecter")}</button>374 </Stage>375 )376}377