SPB Git

Repository Public

session.ts 21.0 KB 446 lines typescript

1// Session : démarrage, connexion par clé d'accès, enrôlement, déconnexion, expiration, préférences, navigation.2import { startAuthentication, startRegistration, type PublicKeyCredentialCreationOptionsJSON, type PublicKeyCredentialRequestOptionsJSON } from "@simplewebauthn/browser"3import { detectLang, setLang, t } from "../i18n"4import { bindUnauthorized } from "../jmap/client"5import { HttpError, NetworkError } from "../jmap/errors"6import { api, apiPost } from "../jmap/http"7import { S, defaultPrefs, emptyList, normalizePrefs, parseRoute, resolveMailboxIndex, routeHref, toast, type Me, type Prefs, type ResolvedTheme, type Route, type Theme } from "./app"8import { cacheClear, cacheGet, cachePut } from "./cache"9import { clearLocalDraft, composeNew, restoreLocalDraft } from "./composer"10import { clampPane, pushRecentSearch, readDevice, writeDevice, type DevicePrefs, type PaneKey } from "./device"11import { applyMailRoute, initAccount, startAccounts, stopAccounts, teardownAccount } from "./mail"12import { loadAddresses } from "./senders"13import { startOffline, stopOffline } from "./offline"14import { purgeShell, registerShell, takeShortcut } from "../sw/register"1516const UI_KEY = "spmail.ui"17const THEME_COLOR: Record<ResolvedTheme, string> = { light: "#f6f5f1", dark: "#141513", midnight: "#000000" }1819// ---------------------------------------------------------------- apparence et langue20const systemDark = () => typeof matchMedia === "function" && matchMedia("(prefers-color-scheme: dark)").matches21export const resolveTheme = (theme: Theme, dark = systemDark()): ResolvedTheme => (theme === "system" ? (dark ? "dark" : "light") : theme)2223/**24 * Applique les préférences au document. `data-theme` porte toujours le thème résolu (light | dark | midnight) : les feuilles de25 * style n'ont ainsi qu'un bloc par thème ; `data-theme-pref="system"` signale que le choix suit l'appareil.26 */27function applyUi(prefs: Prefs) {28  const root = document.documentElement29  const resolved = resolveTheme(prefs.theme)30  if (root.getAttribute("data-theme") !== resolved) {31    // changement de thème : toutes les couleurs basculent d'un coup, sans transitions (ni teintes intermédiaires illisibles)32    root.classList.add("theme-switching")33    requestAnimationFrame(() => requestAnimationFrame(() => root.classList.remove("theme-switching")))34  }35  root.setAttribute("data-theme", resolved)36  root.setAttribute("data-theme-pref", prefs.theme)37  root.setAttribute("data-density", prefs.density)38  root.setAttribute("data-preview", String(prefs.previewLines))39  root.setAttribute("data-text", prefs.textSize)40  root.setAttribute("data-reading-font", prefs.readingFont)41  root.setAttribute("data-avatars", prefs.avatars ? "on" : "off")42  for (const meta of document.querySelectorAll<HTMLMetaElement>('meta[name="theme-color"]')) meta.content = THEME_COLOR[resolved]43  const lang = prefs.lang ?? detectLang()44  setLang(lang)45  if (S.get().lang !== lang || S.get().resolvedTheme !== resolved) S.set({ lang, resolvedTheme: resolved })46  try {47    localStorage.setItem(UI_KEY, JSON.stringify({ theme: prefs.theme, density: prefs.density, lang: prefs.lang, textSize: prefs.textSize, readingFont: prefs.readingFont, previewLines: prefs.previewLines, avatars: prefs.avatars }))48  } catch {49    /* stockage indisponible */50  }51}5253function storedUi(): Record<string, unknown> {54  try {55    return JSON.parse(localStorage.getItem(UI_KEY) ?? "{}") as Record<string, unknown>56  } catch {57    return {}58  }59}6061/** Préférences de l'appareil → attributs et variables du document (disposition, volets, barre réduite, transparence). */62function applyDevice(d: DevicePrefs) {63  const root = document.documentElement64  root.setAttribute("data-layout", d.layout)65  root.setAttribute("data-sidebar", d.sidebarCollapsed ? "rail" : "full")66  if (d.reduceTransparency === null) root.removeAttribute("data-transparency")67  else root.setAttribute("data-transparency", d.reduceTransparency ? "reduce" : "allow")68  root.style.setProperty("--sidebar-w", `${d.paneWidths.sidebar}px`)69  root.style.setProperty("--list-w", `${d.paneWidths.list}px`)70  root.style.setProperty("--list-h", `${d.paneWidths.listHeight}px`)71}72export function updateDevice(patch: Partial<DevicePrefs>) {73  const device = { ...S.get().device, ...patch }74  S.set({ device })75  applyDevice(device)76  writeDevice(device)77}78/** Largeur (ou hauteur) d'un volet, bornée ; `persist` faux pendant un glissement (la valeur finale seule est enregistrée). */79export function setPaneSize(key: PaneKey, value: number, persist = true): number {80  const v = clampPane(key, value)81  if (persist) updateDevice({ paneWidths: { ...S.get().device.paneWidths, [key]: v } })82  else document.documentElement.style.setProperty(key === "sidebar" ? "--sidebar-w" : key === "list" ? "--list-w" : "--list-h", `${v}px`)83  return v84}85export function toggleFolderCollapsed(id: string) {86  const cur = S.get().device.foldersCollapsed87  updateDevice({ foldersCollapsed: cur.includes(id) ? cur.filter((x) => x !== id) : [...cur, id] })88}89export function rememberSearch(q: string) {90  updateDevice({ recentSearches: pushRecentSearch(S.get().device.recentSearches, q) })91}9293/** Avant la connexion : thème, langue et disposition du dernier passage sur cet appareil. */94export function applyStoredUi() {95  const prefs = { ...defaultPrefs(), ...normalizePrefs(storedUi()) }96  const device = readDevice()97  S.set({ prefs, device })98  applyUi(prefs)99  applyDevice(device)100}101102/**103 * Le thème est propre à l'appareil (préférences d'appareil) ; celui du compte ne sert qu'à amorcer un appareil où l'on n'a104 * jamais choisi. Les enregistrements de préférences renvoient donc au serveur le thème DU COMPTE, pas celui de l'appareil :105 * changer la densité ici ne doit pas modifier le thème par défaut des autres appareils.106 */107let accountTheme: Theme = "system"108109let prefsSaving = false110let prefsPending = false111async function pushPrefs() {112  if (prefsSaving) {113    prefsPending = true114    return115  }116  prefsSaving = true117  try {118    do {119      prefsPending = false120      // keepalive : un changement suivi d'un rechargement immédiat n'est pas perdu121      await api("/api/prefs", { method: "PUT", json: { ...S.get().prefs, theme: accountTheme }, keepalive: true })122    } while (prefsPending)123  } catch {124    toast({ kind: "error", text: t("prefs.saveFailed") })125  } finally {126    prefsSaving = false127  }128}129export function updatePrefs(patch: Partial<Prefs>) {130  const prefs = { ...S.get().prefs, ...patch }131  if (patch.theme) {132    // choix explicite : retenu pour cet appareil, et proposé comme thème de départ aux appareils qui n'ont rien choisi133    accountTheme = patch.theme134    const device = { ...S.get().device, theme: patch.theme }135    S.set({ device })136    writeDevice(device)137  }138  S.set({ prefs })139  applyUi(prefs)140  if (S.get().phase === "ready") void pushPrefs()141}142143// ---------------------------------------------------------------- navigation144export function currentRoute(): Route {145  return parseRoute(location.pathname, location.search)146}147/**148 * Garde de navigation (modifications non enregistrées, génération en cours) : appelée avant tout changement de route.149 * Elle rend `true` pour laisser passer ; sinon elle retient la navigation et peut appeler `proceed` plus tard150 * (après confirmation). Une seule garde à la fois ; `null` la retire.151 */152export type NavigationGuard = (href: string, proceed: () => void) => boolean153let navGuard: NavigationGuard | null = null154let shownHref = typeof location === "undefined" ? "/" : location.pathname + location.search155export function setNavigationGuard(guard: NavigationGuard | null) {156  navGuard = guard157}158159/** Identifiant stable de la boîte visée par une adresse (voir `resolveMailboxIndex`). */160function mailboxStateFor(href: string): { mb: string } | null {161  const q = href.indexOf("?")162  const r = parseRoute(q < 0 ? href : href.slice(0, q), q < 0 ? "" : href.slice(q))163  if (r.name !== "mail" || (r.all && !r.threadId)) return null164  const id = S.get().me?.mailboxes[r.mbIndex]?.id165  return id ? { mb: id } : null166}167168export function navigate(to: Route | string, opts: { replace?: boolean; force?: boolean } = {}) {169  const href = typeof to === "string" ? to : routeHref(to)170  if (!opts.force && navGuard && href !== shownHref && !navGuard(href, () => navigate(href, { ...opts, force: true }))) return171  if (href !== location.pathname + location.search) {172    if (opts.replace) history.replaceState(mailboxStateFor(href), "", href)173    else history.pushState(mailboxStateFor(href), "", href)174  }175  onRouteChange()176}177178/**179 * Le rang d'une boîte dans l'adresse (`/m/<rang>/…`) peut ne plus désigner la même boîte (liste modifiée côté serveur) :180 * l'identifiant mémorisé avec l'entrée d'historique fait foi et l'adresse est corrigée sur place.181 */182function reconcileRoute(route: Route): Route {183  const me = S.get().me184  if (route.name !== "mail" || !me || (route.all && !route.threadId)) return route185  const stable = (history.state as { mb?: unknown } | null)?.mb186  const r = resolveMailboxIndex(me.mailboxes, route.mbIndex, typeof stable === "string" ? stable : null)187  const id = me.mailboxes[r.index]?.id188  if (!r.redirect) {189    // signet ou lien direct : l'entrée d'historique apprend l'identifiant stable de sa boîte190    if (id && stable !== id) history.replaceState({ mb: id }, "", location.pathname + location.search)191    return route192  }193  // la boîte visée a disparu : sa conversation et sa recherche n'ont plus de sens194  const next: Route = r.gone || !id ? { name: "mail", mbIndex: r.index, view: "inbox", threadId: null, q: "" } : { ...route, mbIndex: r.index }195  history.replaceState(id ? { mb: id } : null, "", routeHref(next))196  return next197}198let lastMail = "/"199/** Dernière vue du courrier affichée : c'est là que ramène « Courrier » depuis les réglages ou l'administration. */200export const lastMailHref = () => lastMail201/** Bouton Précédent/Suivant du navigateur : l'adresse a déjà changé ; si la garde retient, on la rétablit. */202function onPopState() {203  const href = location.pathname + location.search204  if (navGuard && href !== shownHref && !navGuard(href, () => navigate(href, { force: true }))) {205    history.pushState(null, "", shownHref)206    return207  }208  onRouteChange()209}210export function onRouteChange() {211  const route = reconcileRoute(currentRoute())212  shownHref = location.pathname + location.search213  // retour au courrier depuis les réglages ou l'administration : les adresses (alias, signatures) ont pu y changer214  if (route.name === "mail" && S.get().route.name !== "mail" && S.get().phase === "ready") void loadAddresses()215  if (route.name === "mail") lastMail = routeHref({ ...route, threadId: null })216  S.set({ route, navOpen: false })217  if (route.name === "mail" && S.get().phase === "ready") applyMailRoute(route)218  // écran « Next » ouvert directement : la barre latérale a besoin d'une boîte courante219  else if (route.name === "next" && S.get().phase === "ready" && !S.get().mb) applyMailRoute({ name: "mail", mbIndex: 0, view: "inbox", threadId: null, q: "" })220}221/** Lien interne : même onglet sans rechargement, sauf clic modifié (nouvel onglet). */222export function linkProps(to: Route | string) {223  const href = typeof to === "string" ? to : routeHref(to)224  return {225    href,226    onClick: (e: { defaultPrevented: boolean; button: number; metaKey: boolean; ctrlKey: boolean; shiftKey: boolean; altKey: boolean; preventDefault(): void }) => {227      if (e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return228      e.preventDefault()229      navigate(href)230    },231  }232}233234// ---------------------------------------------------------------- démarrage et authentification235function enter(me: Me, offlineShell = false) {236  // le thème est propre à l'appareil : celui choisi ici l'emporte ; celui du compte n'amorce qu'un appareil où rien n'a été choisi237  const account = normalizePrefs(me.user.prefs)238  accountTheme = account.theme239  const prefs = { ...account, theme: S.get().device.theme ?? account.theme }240  S.set({ me, prefs, phase: "ready", expired: false, offlineShell })241  applyUi(prefs)242  void cachePut("me", me)243  startAccounts()244  onRouteChange()245  restoreLocalDraft()246  void loadAddresses()247  void refreshApprovalCount()248  // hors ligne : file durable des actions de CET utilisateur, coque applicative (service worker), raccourcis du manifeste249  void startOffline(me.user.id)250  registerShell()251  if (takeShortcut() === "compose") composeNew()252}253254/** Administrateurs : nombre d'envois externes en attente d'approbation (pastille discrète de la barre latérale). */255export async function refreshApprovalCount(): Promise<void> {256  const s = S.get()257  if (s.phase !== "ready" || s.me?.user.role !== "admin") return258  try {259    const list = await api<unknown[]>("/api/admin/approvals?status=pending", { quiet401: true })260    S.set({ pendingApprovals: Array.isArray(list) ? list.length : 0 })261  } catch {262    // hors ligne ou API indisponible : la pastille garde sa dernière valeur263  }264}265266/** La liste des boîtes peut changer côté serveur (boîte ajoutée ou retirée par l'administration) : on la relit au retour sur l'onglet et périodiquement. */267let refreshingMe = false268export async function refreshMe(): Promise<void> {269  const cur = S.get().me270  if (!cur || S.get().phase !== "ready" || refreshingMe || document.visibilityState !== "visible") return271  refreshingMe = true272  try {273    const me = await api<Me>("/api/me", { quiet401: true })274    const sig = (m: Me) => m.mailboxes.map((b) => `${b.id}:${b.address}:${b.display_name}`).join("|") + "|" + m.user.role275    if (sig(me) !== sig(cur)) applyMe(me)276  } catch {277    // hors ligne ou session expirée : traité ailleurs278  } finally {279    refreshingMe = false280  }281}282283/**284 * Prend en compte une liste de boîtes modifiée côté serveur : les boîtes retirées sont démontées (client, connexion de285 * notification, cache), les nouvelles démarrées, et l'adresse affichée suit la boîte courante si son rang a changé.286 */287export function applyMe(me: Me) {288  const cur = S.get().me289  if (!cur) return290  const before = S.get()291  const shown = before.mb292  const next = new Set(me.mailboxes.map((b) => b.id))293  const known = new Set(cur.mailboxes.map((b) => b.id))294  S.set({ me })295  void cachePut("me", me)296  for (const b of cur.mailboxes) if (!next.has(b.id)) teardownAccount(b.id)297  for (const b of me.mailboxes) if (!known.has(b.id)) void initAccount(b.id)298  const draft = S.get().draft299  if (draft && !next.has(draft.mb)) toast({ kind: "error", text: t("mailbox.removedDraft") })300  if (shown && !next.has(shown)) toast({ kind: "info", text: t("mailbox.removed", { address: cur.mailboxes.find((b) => b.id === shown)?.address ?? "" }) })301  const route = S.get().route302  if (route.name !== "mail") return303  if (shown && next.has(shown) && !route.all) {304    // même boîte, rang peut-être différent : l'adresse est corrigée sans rien recharger305    const index = me.mailboxes.findIndex((b) => b.id === shown)306    if (index !== route.mbIndex) {307      const fixed = { ...route, mbIndex: index }308      history.replaceState({ mb: shown }, "", routeHref(fixed))309      shownHref = location.pathname + location.search310      S.set({ route: fixed })311    }312    return313  }314  onRouteChange()315}316317export async function boot() {318  document.addEventListener("visibilitychange", () => void refreshMe())319  setInterval(() => void refreshMe(), 5 * 60_000)320  setInterval(() => document.visibilityState === "visible" && void refreshApprovalCount(), 2 * 60_000)321  bindUnauthorized(sessionExpired)322  applyStoredUi()323  // « Système » : le thème suit l'appareil en direct324  if (typeof matchMedia === "function") matchMedia("(prefers-color-scheme: dark)").addEventListener("change", () => applyUi(S.get().prefs))325  S.set({ route: currentRoute() })326  window.addEventListener("popstate", onPopState)327  window.addEventListener("online", () => S.set({ online: true }))328  window.addEventListener("offline", () => S.set({ online: false }))329  if (currentRoute().name === "enroll") {330    S.set({ phase: "signedOut" })331    return332  }333  try {334    enter(await api<Me>("/api/me", { quiet401: true }))335  } catch (e) {336    if (e instanceof NetworkError) {337      // serveur injoignable : on montre la dernière interface connue, en lecture seule de fait338      const cached = await cacheGet<Me>("me")339      if (cached) return enter(cached, true)340    } else if (e instanceof HttpError && e.status === 401) {341      void cacheClear() // session terminée ailleurs : plus de copie locale du courrier, ni file d'actions, ni coque342      void purgeShell()343    }344    S.set({ phase: "signedOut" })345  }346}347348const clientInfo = () => ({ kind: "web" as const, deviceName: navigator.platform?.slice(0, 80) || "Web", platform: (navigator.userAgent.match(/\(([^;)]+)/)?.[1] ?? "web").slice(0, 40) })349350export async function signIn(): Promise<void> {351  const { challenge_id, options } = await apiPost<{ challenge_id: string; options: PublicKeyCredentialRequestOptionsJSON }>("/api/login/options")352  const response = await startAuthentication({ optionsJSON: options })353  await apiPost("/api/login/verify", { challenge_id, response, client: clientInfo() })354  const me = await api<Me>("/api/me")355  if (location.pathname.startsWith("/enroll")) history.replaceState(null, "", "/")356  enter(me)357}358359export interface EnrollInfo {360  purpose: "bootstrap" | "recover" | "invite"361  user: { handle: string; display_name: string } | null362}363export const enrollCheck = (token: string) => apiPost<EnrollInfo>("/api/enroll/check", { token })364365export async function enroll(token: string, handle?: string, displayName?: string, label?: string): Promise<void> {366  const { challenge_id, options } = await apiPost<{ challenge_id: string; options: PublicKeyCredentialCreationOptionsJSON }>("/api/enroll/options", { token, handle, display_name: displayName })367  const response = await startRegistration({ optionsJSON: options })368  await apiPost("/api/enroll/verify", { challenge_id, response, label: label || undefined, client: clientInfo() })369  const me = await api<Me>("/api/me")370  history.replaceState(null, "", "/") // le jeton à usage unique quitte la barre d'adresse371  enter(me)372}373374export async function addPasskey(label: string): Promise<void> {375  const { challenge_id, options } = await apiPost<{ challenge_id: string; options: PublicKeyCredentialCreationOptionsJSON }>("/api/passkeys/options")376  const response = await startRegistration({ optionsJSON: options })377  await apiPost("/api/passkeys/verify", { challenge_id, response, label })378}379380function resetState(extra: Partial<ReturnType<typeof S.get>> = {}) {381  stopOffline() // plus aucun rejeu : la file est effacée avec le cache local382  stopAccounts()383  S.set({ phase: "signedOut", me: null, accounts: {}, mb: null, list: emptyList(), emails: {}, threads: {}, threadShown: {}, selected: new Set(), cursor: null, open: null, deliveries: [], contacts: {}, offlineShell: false, all: false, addresses: null, pendingApprovals: 0, paletteOpen: false, sync: { pendingOps: 0, busy: false, error: null }, ...extra })384}385386/** Déconnexion volontaire : la session est révoquée, le cache local et le brouillon en cours sont effacés. */387export async function signOut() {388  try {389    await apiPost("/api/logout")390  } catch (e) {391    if (!(e instanceof HttpError && e.status === 401)) {392      toast({ kind: "error", text: t("auth.signOutFailed") })393      return394    }395  }396  clearLocalDraft()397  stopOffline()398  await cacheClear()399  await purgeShell() // service worker désenregistré, caches de la coque effacés400  resetState({ draft: null, expired: false })401  history.replaceState(null, "", "/")402  S.set({ route: currentRoute() })403}404405/**406 * 401 en cours d'utilisation (session expirée ou révoquée) : retour à la connexion SANS perdre le brouillon en cours (il reste en407 * mémoire et en local). Le courrier mis en cache, lui, est effacé comme à la déconnexion : sans session, plus rien de lisible408 * ne doit rester sur l'appareil. L'état en mémoire est vidé lui aussi et rechargé à la reconnexion.409 */410export function sessionExpired() {411  if (S.get().phase !== "ready") return412  resetState({ expired: true, helpOpen: false })413  void cacheClear()414  void purgeShell()415}416417/** Message d'erreur lisible pour un échec WebAuthn ou d'API pendant la connexion. */418export function authErrorMessage(e: unknown): string {419  if (e instanceof NetworkError) return t("error.offline")420  if (e instanceof HttpError) {421    switch (e.code) {422      case "unknown_passkey":423        return t("auth.unknownPasskey")424      case "passkey_verification_failed":425        return t("auth.verificationFailed")426      case "account_disabled":427        return t("auth.accountDisabled")428      case "invalid_token":429        return t("auth.invalidToken")430      case "handle_taken":431        return t("auth.handleTaken")432      case "challenge_expired":433        return t("auth.challengeExpired")434      case "invalid_request":435        return t("auth.invalidRequest")436      default:437        return e.status === 429 ? t("error.rateLimited") : t("auth.failed")438    }439  }440  const name = (e as { name?: string } | null)?.name441  if (name === "NotAllowedError" || name === "AbortError") return t("auth.cancelled")442  if (name === "InvalidStateError") return t("auth.alreadyRegistered")443  if (name === "NotSupportedError" || name === "SecurityError") return t("auth.unsupported")444  return t("auth.failed")445}446
Files main
Menu

Theme