SPB Git

Repository Public

settings.tsx 21.2 KB 283 lines tsx

1import { startRegistration } from "@simplewebauthn/browser"2import { useCallback, useEffect, useState, type ReactNode } from "react"3import { fingerprint } from "../core/crypto"4import { formatBytes } from "../core/media"5import { Avatar, dateTime, errText, I, Sheet, Switch, t, toast, useApp } from "./bits"67export type Section = "profile" | "privacy" | "appearance" | "security" | "devices" | "scheduled" | "about"89const sections = (): { id: Section; icon: ReactNode; label: string; hint: string }[] => [10  { id: "profile", icon: I.users, label: t("Profile", "Profil"), hint: t("Name, username, storage", "Nom, identifiant, stockage") },11  { id: "privacy", icon: I.eye, label: t("Privacy", "Confidentialité"), hint: t("Read receipts, presence, notifications", "Accusés de lecture, présence, notifications") },12  { id: "appearance", icon: I.sparkle, label: t("Appearance", "Apparence"), hint: t("Theme, composer", "Thème, rédaction") },13  { id: "security", icon: I.shield, label: t("Security", "Sécurité"), hint: t("Passkeys, recovery key, identity", "Clés d’accès, clé de récupération, identité") },14  { id: "devices", icon: I.device, label: t("Devices and sessions", "Appareils et sessions"), hint: t("Trusted devices, active sessions", "Appareils de confiance, sessions actives") },15  { id: "scheduled", icon: I.clock, label: t("Scheduled messages", "Messages programmés"), hint: t("Waiting on this device", "En attente sur cet appareil") },16  { id: "about", icon: I.info, label: t("About", "À propos"), hint: t("How SP Message protects you", "Comment SP Message vous protège") },17]1819export function SettingsMenu({ current, onPick }: { current: Section | null; onPick: (s: Section) => void }) {20  const { engine, signOut } = useApp()21  return (22    <>23      <div className="pane-head">24        <h1 className="h1">{t("Settings", "Réglages")}</h1>25        <div className="row"><Avatar id={engine.me.id} name={engine.me.display_name} size={52} /><div className="grow"><b className="ell" style={{ display: "block" }}>{engine.me.display_name}</b><span className="dim small">@{engine.me.handle}</span></div></div>26      </div>27      <div className="pane-body">28        {sections().map((s) => (29          <button key={s.id} className="conv" aria-current={current === s.id} onClick={() => onPick(s.id)}>30            <span className="icon-btn on" style={{ pointerEvents: "none" }}>{s.icon}</span>31            <span className="grow"><span className="name" style={{ display: "block" }}>{s.label}</span><span className="preview ell" style={{ display: "block" }}>{s.hint}</span></span>32            {s.id === "devices" && engine.pendingDevices.length > 0 && <span className="count">{engine.pendingDevices.length}</span>}33          </button>34        ))}35        <div className="divider" />36        <button className="list-row" onClick={() => signOut(false)}>{I.logout}<span>{t("Sign out", "Se déconnecter")}</span></button>37        <button className="list-row" style={{ color: "var(--danger)" }} onClick={() => confirm(t("Sign out and erase everything SP Message stored in this browser? This device will be removed from your account and its message history will be lost.", "Se déconnecter et effacer tout ce que SP Message a stocké dans ce navigateur ? Cet appareil sera retiré de votre compte et son historique sera perdu.")) && signOut(true)}>{I.trash}<span>{t("Sign out and erase this device", "Se déconnecter et effacer cet appareil")}</span></button>38      </div>39    </>40  )41}4243function Page({ title, onBack, children }: { title: string; onBack: () => void; children: ReactNode }) {44  return (45    <div className="page">46      <div className="page-inner">47        <div className="row"><button className="icon-btn back-m" onClick={onBack} aria-label={t("Back", "Retour")}>{I.back}</button><h1 className="h1">{title}</h1></div>48        {children}49      </div>50    </div>51  )52}53function Line({ title, hint, children }: { title: string; hint?: string; children: ReactNode }) {54  return (55    <div className="row" style={{ padding: "6px 0" }}>56      <span className="grow"><b>{title}</b>{hint && <><br /><span className="dim small">{hint}</span></>}</span>57      {children}58    </div>59  )60}6162export function SettingsPage({ section, onBack }: { section: Section; onBack: () => void }) {63  const title = sections().find((s) => s.id === section)!.label64  return (65    <Page title={title} onBack={onBack}>66      {section === "profile" && <Profile />}67      {section === "privacy" && <Privacy />}68      {section === "appearance" && <Appearance />}69      {section === "security" && <Security />}70      {section === "devices" && <Devices />}71      {section === "scheduled" && <Scheduled />}72      {section === "about" && <About />}73    </Page>74  )75}7677function Profile() {78  const { engine } = useApp()79  const [name, setName] = useState(engine.me.display_name)80  const [usage, setUsage] = useState<{ used: number; quota: number } | null>(null)81  useEffect(() => {82    engine.t.request<any>("GET", "/api/me").then((r) => setUsage({ used: r.user.used_bytes, quota: r.user.quota_bytes })).catch(() => {})83  }, [engine])84  return (85    <>86      <div className="card col">87        <div className="field"><label htmlFor="dn">{t("Display name", "Nom affiché")}</label><input id="dn" className="input" value={name} maxLength={64} onChange={(e) => setName(e.target.value)} /></div>88        <div className="field"><label>{t("Username", "Nom d’utilisateur")}</label><div className="input" style={{ display: "flex", alignItems: "center", opacity: 0.7 }}>@{engine.me.handle}</div></div>89        <button className="btn primary" style={{ alignSelf: "flex-start" }} disabled={!name.trim() || name === engine.me.display_name} onClick={async () => {90          try {91            await engine.t.request("PATCH", "/api/profile", { display_name: name.trim() })92            engine.me = { ...engine.me, display_name: name.trim() }93            engine.emit()94            toast(t("Saved", "Enregistré"))95          } catch (e) {96            toast(errText(e))97          }98        }}>{t("Save", "Enregistrer")}</button>99      </div>100      {usage && (101        <div className="card col">102          <b>{t("Encrypted storage", "Stockage chiffré")}</b>103          <div className="progress" style={{ height: 8 }}><i style={{ width: `${Math.min(100, (usage.used / Math.max(1, usage.quota)) * 100)}%` }} /></div>104          <span className="dim small">{formatBytes(usage.used)} {t("of", "sur")} {formatBytes(usage.quota)} · {t("attachments you sent", "pièces jointes que vous avez envoyées")}</span>105        </div>106      )}107    </>108  )109}110111function Privacy() {112  const { engine } = useApp()113  const [presence, setPresence] = useState(engine.me.presence_opt_in)114  const [perm, setPerm] = useState(typeof Notification === "undefined" ? "unsupported" : Notification.permission)115  return (116    <div className="card col">117      <Line title={t("Read receipts", "Accusés de lecture")} hint={t("Let people see when you have read their messages. Receipts are themselves encrypted.", "Indique aux autres que vous avez lu leurs messages. Les accusés sont eux-mêmes chiffrés.")}>118        <Switch checked={engine.prefs.readReceipts} onChange={(v) => engine.setPrefs({ readReceipts: v })} label={t("Read receipts", "Accusés de lecture")} />119      </Line>120      <div className="divider" />121      <Line title={t("Show when I am online", "Afficher quand je suis en ligne")} hint={t("Off by default. When on, the server tells the people you talk to that you are connected.", "Désactivé par défaut. Activé, le serveur indique à vos interlocuteurs que vous êtes connecté.")}>122        <Switch checked={presence} label={t("Presence", "Présence")} onChange={async (v) => {123          setPresence(v)124          await engine.t.request("PATCH", "/api/profile", { presence_opt_in: v }).catch((e) => toast(errText(e)))125          engine.me = { ...engine.me, presence_opt_in: v }126        }} />127      </Line>128      <div className="divider" />129      <Line title={t("Notifications", "Notifications")} hint={perm === "unsupported" ? t("Not supported by this browser.", "Non prises en charge par ce navigateur.") : t("Shown while SP Message is open in a tab or installed app. They never contain the text of a message.", "Affichées lorsque SP Message est ouvert dans un onglet ou installé. Elles ne contiennent jamais le texte d’un message.")}>130        {perm === "default" ? <button className="btn sm" onClick={async () => setPerm(await Notification.requestPermission())}>{t("Allow", "Autoriser")}</button>131          : <Switch checked={engine.prefs.notify && perm === "granted"} onChange={(v) => engine.setPrefs({ notify: v })} label={t("Notifications", "Notifications")} />}132      </Line>133    </div>134  )135}136137function Appearance() {138  const { engine } = useApp()139  const themes: [typeof engine.prefs.theme, string][] = [["system", t("Automatic", "Automatique")], ["light", t("Light", "Clair")], ["dark", t("Dark", "Sombre")]]140  return (141    <div className="card col">142      <Line title={t("Theme", "Thème")}>143        <div className="seg" role="group">{themes.map(([id, label]) => <button key={id} aria-pressed={engine.prefs.theme === id} onClick={() => engine.setPrefs({ theme: id })}>{label}</button>)}</div>144      </Line>145      <div className="divider" />146      <Line title={t("Enter sends the message", "Entrée envoie le message")} hint={t("On a keyboard. Shift + Enter always inserts a new line.", "Sur un clavier. Maj + Entrée insère toujours une nouvelle ligne.")}>147        <Switch checked={engine.prefs.enterSends} onChange={(v) => engine.setPrefs({ enterSends: v })} label={t("Enter sends", "Entrée envoie")} />148      </Line>149      <div className="divider" />150      <Line title={t("Reduce large photos before sending", "Réduire les grandes photos avant l’envoi")} hint={t("Done on this device. Turn off to always send the original file.", "Effectué sur cet appareil. Désactivez pour toujours envoyer le fichier d’origine.")}>151        <Switch checked={engine.prefs.compress} onChange={(v) => engine.setPrefs({ compress: v })} label={t("Compress photos", "Compresser les photos")} />152      </Line>153    </div>154  )155}156157function Security() {158  const { engine } = useApp()159  const [keys, setKeys] = useState<any[]>([])160  const [fp, setFp] = useState("")161  const [recovery, setRecovery] = useState("")162  const load = useCallback(() => engine.t.request<any[]>("GET", "/api/passkeys").then(setKeys).catch(() => {}), [engine])163  useEffect(() => {164    void load()165    void fingerprint(engine.dev.identityKey, engine.me.id).then(setFp)166  }, [engine, load])167  const add = async () => {168    try {169      const { challenge_id, options } = await engine.t.request<any>("POST", "/api/passkeys/options", {})170      const response = await startRegistration({ optionsJSON: options })171      const label = prompt(t("Name this passkey", "Nommez cette clé d’accès"), t("Passkey", "Clé d’accès")) || "Passkey"172      await engine.t.request("POST", "/api/passkeys/verify", { challenge_id, response, label })173      toast(t("Passkey added", "Clé d’accès ajoutée"))174      void load()175    } catch (e) {176      if ((e as Error).name !== "NotAllowedError") toast((e as Error).name === "InvalidStateError" ? t("This authenticator already holds a passkey for your account.", "Cet authentificateur possède déjà une clé d’accès pour votre compte.") : errText(e))177    }178  }179  return (180    <>181      <div className="card col">182        <div className="row"><b className="grow">{t("Passkeys", "Clés d’accès")}</b><button className="btn sm" onClick={add}>{I.plus}{t("Add", "Ajouter")}</button></div>183        <span className="dim small">{t("Passkeys prove who you are when you sign in. They are separate from your encryption keys and cannot decrypt anything.", "Les clés d’accès prouvent votre identité à la connexion. Elles sont distinctes de vos clés de chiffrement et ne déchiffrent rien.")}</span>184        {keys.map((k) => (185          <div key={k.id} className="row" style={{ padding: "6px 0" }}>186            <span className="icon-btn" style={{ pointerEvents: "none" }}>{I.key}</span>187            <span className="grow"><b>{k.label}</b><br /><span className="dim small">{k.backed_up ? t("Synced passkey", "Clé synchronisée") : t("Device-bound", "Liée à l’appareil")} · {t("added", "ajoutée le")} {dateTime(k.created_at)}{k.last_used_at ? ` · ${t("last used", "utilisée le")} ${dateTime(k.last_used_at)}` : ""}</span></span>188            {keys.length > 1 && <button className="btn sm danger" onClick={async () => confirm(t("Remove this passkey?", "Retirer cette clé d’accès ?")) && (await engine.t.request("DELETE", `/api/passkeys/${encodeURIComponent(k.id)}`).catch((e) => toast(errText(e))), void load())}>{t("Remove", "Retirer")}</button>}189          </div>190        ))}191      </div>192      <div className="card col">193        <b>{t("Recovery key", "Clé de récupération")}</b>194        <span className="dim small">{t("The only way to restore your encryption identity if you lose every device. Generating a new key makes the previous one useless.", "Le seul moyen de restaurer votre identité de chiffrement si vous perdez tous vos appareils. Générer une nouvelle clé rend la précédente inutilisable.")}</span>195        <button className="btn" style={{ alignSelf: "flex-start" }} onClick={async () => confirm(t("Generate a new recovery key? The old one will stop working.", "Générer une nouvelle clé de récupération ? L’ancienne cessera de fonctionner.")) && setRecovery(await engine.rotateRecoveryKey().catch((e) => (toast(errText(e)), "")))}>{I.key}{t("Generate a new recovery key", "Générer une nouvelle clé de récupération")}</button>196      </div>197      <div className="card col">198        <b>{t("Your identity key fingerprint", "Empreinte de votre clé d’identité")}</b>199        <div className="safety">{fp}</div>200        <span className="dim small">{t("Others see a warning if this ever changes. To compare with a contact, open the conversation details and choose the shield.", "Vos contacts sont avertis si elle change. Pour comparer avec un contact, ouvrez les détails de la conversation et choisissez le bouclier.")}</span>201      </div>202      {recovery && (203        <Sheet title={t("New recovery key", "Nouvelle clé de récupération")} onClose={() => setRecovery("")}>204          <div className="col"><div className="recovery">{recovery}</div><p className="dim small">{t("Store it now: it will not be shown again.", "Rangez-la maintenant : elle ne sera plus affichée.")}</p><button className="btn" onClick={() => navigator.clipboard?.writeText(recovery)}>{I.copy}{t("Copy", "Copier")}</button></div>205        </Sheet>206      )}207    </>208  )209}210211function Devices() {212  const { engine } = useApp()213  const [devices, setDevices] = useState<any[]>([])214  const [sessions, setSessions] = useState<any[]>([])215  const load = useCallback(() => {216    engine.t.request<any[]>("GET", "/api/devices").then(setDevices).catch(() => {})217    engine.t.request<any[]>("GET", "/api/sessions").then(setSessions).catch(() => {})218  }, [engine])219  useEffect(load, [load, engine.pendingDevices.length])220  return (221    <>222      <div className="card col">223        <b>{t("Trusted devices", "Appareils de confiance")}</b>224        <span className="dim small">{t("Each device has its own encryption key, certified by your identity. Removing a device takes it out of every conversation.", "Chaque appareil possède sa propre clé de chiffrement, certifiée par votre identité. Retirer un appareil l’exclut de toutes les conversations.")}</span>225        {devices.map((d) => (226          <div key={d.id} className="row" style={{ padding: "6px 0" }}>227            <span className="icon-btn" style={{ pointerEvents: "none" }}>{I.device}</span>228            <span className="grow"><b>{d.label}</b> {d.current && <span className="badge accent">{t("this device", "cet appareil")}</span>} {d.status === "pending" && <span className="badge warn">{t("waiting for approval", "en attente d’approbation")}</span>}<br />229              <span className="dim small">{d.enrolled_via === "first" ? t("First device", "Premier appareil") : d.enrolled_via === "recovery" ? t("Added with the recovery key", "Ajouté avec la clé de récupération") : d.enrolled_via === "approval" ? t("Approved from another device", "Approuvé depuis un autre appareil") : ""} · {dateTime(d.created_at)}</span></span>230            {!d.current && <button className="btn sm danger" onClick={async () => confirm(t("Remove this device? It will lose access to your conversations.", "Retirer cet appareil ? Il perdra l’accès à vos conversations.")) && (await engine.t.request("DELETE", `/api/devices/${d.id}`).catch((e) => toast(errText(e))), load(), void engine.sync())}>{t("Remove", "Retirer")}</button>}231          </div>232        ))}233      </div>234      <div className="card col">235        <b>{t("Active sessions", "Sessions actives")}</b>236        {sessions.map((s) => (237          <div key={s.id} className="row" style={{ padding: "6px 0" }}>238            <span className="grow"><b>{s.device_label ?? t("No device yet", "Aucun appareil")}</b> {s.current && <span className="badge accent">{t("current", "actuelle")}</span>}<br /><span className="dim small ell" style={{ display: "block", maxWidth: 520 }}>{s.ip} · {t("last active", "dernière activité")} {dateTime(s.last_seen_at)}</span></span>239            {!s.current && <button className="btn sm danger" onClick={async () => (await engine.t.request("DELETE", `/api/sessions/${s.id}`).catch((e) => toast(errText(e))), load())}>{t("Revoke", "Révoquer")}</button>}240          </div>241        ))}242      </div>243    </>244  )245}246247function Scheduled() {248  const { engine } = useApp()249  const [list, setList] = useState<Awaited<ReturnType<typeof engine.scheduled>>>([])250  useEffect(() => void engine.scheduled().then(setList), [engine, engine.version])251  return (252    <div className="card col">253      <span className="dim small">{t("Scheduled messages are kept on this device and sent from it at the chosen time, provided SP Message is open.", "Les messages programmés sont conservés sur cet appareil et envoyés depuis celui-ci à l’heure choisie, si SP Message est ouvert.")}</span>254      {list.map((s) => {255        const c = engine.convs.get(s.conv)256        return (257          <div key={s.id} className="row" style={{ padding: "6px 0" }}>258            <span className="grow"><b>{c ? engine.convTitle(c) : "?"}</b> · <span className="dim small">{dateTime(s.at)}</span><br /><span className="small ell" style={{ display: "block", maxWidth: 520 }}>{"body" in s.content ? s.content.body || t("Attachment", "Pièce jointe") : ""}</span></span>259            <button className="btn sm danger" onClick={() => engine.cancelScheduled(s.id)}>{t("Cancel", "Annuler")}</button>260          </div>261        )262      })}263      {!list.length && <p className="dim">{t("Nothing scheduled.", "Rien de programmé.")}</p>}264    </div>265  )266}267268function About() {269  const rows: [string, string][] = [270    [t("Messages", "Messages"), t("Encrypted with the Messaging Layer Security protocol (RFC 9420). Each conversation is a group in which every device holds its own key; keys are renewed whenever membership changes, so removed devices cannot read what follows.", "Chiffrés avec le protocole Messaging Layer Security (RFC 9420). Chaque conversation est un groupe où chaque appareil détient sa propre clé ; les clés sont renouvelées à chaque changement de membres, de sorte qu’un appareil retiré ne peut pas lire la suite.")],271    [t("Files", "Fichiers"), t("Encrypted in your browser with AES-256-GCM before upload. Previews are generated on your device and travel inside encrypted messages.", "Chiffrés dans votre navigateur avec AES-256-GCM avant l’envoi. Les aperçus sont générés sur votre appareil et voyagent à l’intérieur des messages chiffrés.")],272    [t("Calls", "Appels"), t("Audio and video flow directly between devices (WebRTC, DTLS-SRTP). The call setup is exchanged inside encrypted messages. Group calls connect every participant to every other one, up to six people.", "L’audio et la vidéo circulent directement entre les appareils (WebRTC, DTLS-SRTP). La mise en relation est échangée dans des messages chiffrés. Les appels de groupe relient chaque participant à tous les autres, jusqu’à six personnes.")],273    [t("What the server knows", "Ce que le serveur sait"), t("Who is a member of which conversation, when ciphertext was sent and its size, your name and username, and your public keys. It cannot read messages, file contents or file names.", "Qui est membre de quelle conversation, quand un texte chiffré a été envoyé et sa taille, votre nom et identifiant, et vos clés publiques. Il ne peut lire ni les messages, ni le contenu des fichiers, ni leurs noms.")],274    [t("Limits to know", "Limites à connaître"), t("The cryptographic library (ts-mls) has not been independently audited. A web application is delivered by the server on each visit, so a compromised server could deliver altered code. History on a new device starts when the device is added.", "La bibliothèque cryptographique (ts-mls) n’a pas fait l’objet d’un audit indépendant. Une application web est servie par le serveur à chaque visite : un serveur compromis pourrait servir un code modifié. L’historique d’un nouvel appareil commence à son ajout.")],275  ]276  return (277    <div className="card col">278      {rows.map(([k, v]) => <div key={k}><b>{k}</b><p className="muted small" style={{ margin: "4px 0 8px" }}>{v}</p></div>)}279      <span className="dim tiny">SP Message · message.spboucher.ai</span>280    </div>281  )282}283
Files main
Menu

Theme