SPB Git

Repository Public

kit.tsx 11.5 KB 277 lines tsx

1// Briques communes de la console d'administration : réauthentification par clé d'accès (avec nouvel essai transparent),2// secret affiché une seule fois, cadre isolé pour le HTML venu de l'API, sélecteur d'adresses, copie, blocs de code.3import { startAuthentication, type PublicKeyCredentialRequestOptionsJSON } from "@simplewebauthn/browser"4import { useEffect, useId, useMemo, useState, type ReactNode } from "react"5import { ReauthCancelled, retryWithReauth } from "../../admin/reauth"6import { getLang, t } from "../../i18n"7import { apiPost } from "../../jmap/http"8import { buildReaderDocument, sanitizeEmailHtml } from "../../mail/sanitize"9import { v1, type ApiAddress } from "../../mail/v1"10import { toast } from "../../state/app"11import { authErrorMessage } from "../../state/session"12import { Dialog, Icon, useModal } from "../kit"13import { errorText } from "./shared"1415// ---------------------------------------------------------------- réauthentification16interface ReauthAsk {17  resolve: () => void18  reject: (e: unknown) => void19}20let openReauth: ((a: ReauthAsk | null) => void) | null = null2122function promptReauth(): Promise<void> {23  return new Promise((resolve, reject) => {24    if (!openReauth) return reject(new ReauthCancelled())25    openReauth({ resolve, reject })26  })27}2829/**30 * Exécute une opération sensible. Si l'API répond `403 reauth_required`, l'invite de clé d'accès s'ouvre ;31 * une fois la clé présentée, l'opération est rejouée une fois, sans autre intervention.32 */33export const sensitive = <T,>(action: () => Promise<T>): Promise<T> => retryWithReauth(action, promptReauth)34export const isCancelled = (e: unknown): boolean => e instanceof ReauthCancelled3536/** Notification d'échec d'une action d'administration (rien si l'invite de clé a simplement été refermée). */37export function toastFail(e: unknown, codes: Record<string, string> = {}) {38  if (isCancelled(e)) return39  toast({ kind: "error", text: errorText(e, codes) })40}4142/** À monter une fois dans la console : dialogue « Confirmez avec votre clé d'accès ». */43export function ReauthHost() {44  const [ask, setAsk] = useState<ReauthAsk | null>(null)45  const [busy, setBusy] = useState(false)46  const [error, setError] = useState<string | null>(null)47  useEffect(() => {48    openReauth = (a) => {49      setError(null)50      setAsk(a)51    }52    return () => {53      openReauth = null54    }55  }, [])56  if (!ask) return null57  const cancel = () => {58    ask.reject(new ReauthCancelled())59    setAsk(null)60  }61  const confirm = async () => {62    setBusy(true)63    setError(null)64    try {65      const { challenge_id, options } = await apiPost<{ challenge_id: string; options: PublicKeyCredentialRequestOptionsJSON }>("/api/reauth/options")66      const response = await startAuthentication({ optionsJSON: options })67      await apiPost("/api/reauth/verify", { challenge_id, response })68      ask.resolve()69      setAsk(null)70    } catch (e) {71      setError(authErrorMessage(e))72    } finally {73      setBusy(false)74    }75  }76  return (77    <Dialog78      title={t("adm.reauth.title")}79      onClose={cancel}80      alert81      footer={82        <>83          <button type="button" className="btn" onClick={cancel}>84            {t("common.cancel")}85          </button>86          <button type="button" className="btn primary" onClick={() => void confirm()} disabled={busy} data-autofocus data-testid="reauth-confirm">87            {busy ? <span className="spinner" aria-hidden="true" /> : <Icon name="key" />}88            <span>{t("adm.reauth.confirm")}</span>89          </button>90        </>91      }92    >93      <div className="stack" data-testid="reauth-dialog">94        <p>{t("adm.reauth.body")}</p>95        <p className="muted small">{t("adm.reauth.hint")}</p>96        {error ? (97          <p className="adm-error" role="alert">98            {error}99          </p>100        ) : null}101      </div>102    </Dialog>103  )104}105106// ---------------------------------------------------------------- copie107export async function copyToClipboard(text: string, okMessage?: string): Promise<boolean> {108  try {109    await navigator.clipboard.writeText(text)110    if (okMessage) toast({ kind: "success", text: okMessage })111    return true112  } catch {113    toast({ kind: "error", text: t("adm.copy.failed") })114    return false115  }116}117118export function CopyButton({ text, label, small = true }: { text: string; label?: string; small?: boolean }) {119  return (120    <button type="button" className={`btn${small ? " small" : ""}`} onClick={() => void copyToClipboard(text, t("adm.copy.done"))}>121      <Icon name="copy" small />122      <span>{label ?? t("adm.copy.action")}</span>123    </button>124  )125}126127/** Bloc de code (texte seul) avec bouton de copie. */128export function CodeBlock({ code, label, testId }: { code: string; label: string; testId?: string }) {129  return (130    <div className="adm-code">131      <div className="row adm-code-head">132        <span className="small muted">{label}</span>133        <span className="spacer" />134        <CopyButton text={code} />135      </div>136      <pre className="adm-pre mono" tabIndex={0} aria-label={label} data-testid={testId}>137        {code}138      </pre>139    </div>140  )141}142143// ---------------------------------------------------------------- secret affiché une seule fois144/**145 * Jeton d'une clé d'API ou secret d'un webhook : montré une fois, ici, puis oublié. Le dialogue ne se ferme ni par146 * Échap ni par un clic à côté : il faut cocher « J'ai enregistré ce secret ». La valeur ne vit que dans les props147 * de ce composant (jamais dans un magasin, le stockage local ou un journal).148 */149export function SecretDialog({ title, secret, description, onDone }: { title: string; secret: string; description: ReactNode; onDone: () => void }) {150  const ref = useModal(() => {})151  const [saved, setSaved] = useState(false)152  const [copied, setCopied] = useState(false)153  const id = useId()154  return (155    <div className="overlay">156      <div ref={ref} className="dialog" role="alertdialog" aria-modal="true" aria-labelledby={`${id}-t`} aria-describedby={`${id}-d`} tabIndex={-1} data-testid="secret-dialog">157        <div className="dialog-head">158          <h2 id={`${id}-t`}>{title}</h2>159        </div>160        <div className="dialog-body stack">161          <div className="banner warn" id={`${id}-d`}>162            <Icon name="warn" />163            <span>{description}</span>164          </div>165          <div className="field">166            <label htmlFor={`${id}-s`}>{t("adm.secret.label")}</label>167            <input id={`${id}-s`} className="input mono" readOnly value={secret} onFocus={(e) => e.currentTarget.select()} spellCheck={false} autoComplete="off" data-testid="secret-value" data-autofocus />168          </div>169          <div className="row wrap">170            <button171              type="button"172              className="btn"173              onClick={async () => {174                if (await copyToClipboard(secret)) setCopied(true)175              }}176            >177              <Icon name={copied ? "check" : "copy"} small />178              <span>{copied ? t("adm.copy.done") : t("adm.copy.action")}</span>179            </button>180          </div>181          <label className="check" htmlFor={`${id}-c`}>182            <input id={`${id}-c`} type="checkbox" checked={saved} onChange={(e) => setSaved(e.target.checked)} />183            <span>{t("adm.secret.saved")}</span>184          </label>185        </div>186        <div className="dialog-foot">187          <button type="button" className="btn primary" disabled={!saved} onClick={onDone}>188            {t("adm.secret.close")}189          </button>190        </div>191      </div>192    </div>193  )194}195196// ---------------------------------------------------------------- HTML venu de l'API ou d'un message197/**198 * Affiche du HTML non fiable (aperçu d'un envoi en attente, signature) : assaini comme un message reçu, puis rendu dans un199 * <iframe sandbox> sans scripts ni même origine, CSP interne `default-src 'none'`. Jamais de dangerouslySetInnerHTML.200 */201export function SafeHtmlFrame({ html, title, height = 180 }: { html: string; title: string; height?: number }) {202  const doc = useMemo(() => buildReaderDocument(sanitizeEmailHtml(html, { mode: "quote" }), {}, getLang()), [html])203  return <iframe className="adm-frame" sandbox="" title={title} srcDoc={doc} style={{ height }} />204}205206// ---------------------------------------------------------------- adresses207export const loadAddresses = async (signal?: AbortSignal): Promise<ApiAddress[]> => (await v1<{ data: ApiAddress[] }>("/addresses", { signal })).data208209/** Adresses regroupées par boîte, la principale en tête. */210export function groupByMailbox(list: readonly ApiAddress[]): { mailbox: string; items: ApiAddress[] }[] {211  const groups = new Map<string, ApiAddress[]>()212  for (const a of list) groups.set(a.mailbox, [...(groups.get(a.mailbox) ?? []), a])213  return [...groups.entries()]214    .sort(([x], [y]) => x.localeCompare(y))215    .map(([mailbox, items]) => ({ mailbox, items: items.sort((x, y) => Number(y.address === mailbox) - Number(x.address === mailbox) || x.address.localeCompare(y.address)) }))216}217218/**219 * Choix explicite d'adresses (liste d'autorisation d'une clé, filtre d'un webhook). Rien n'est coché par défaut :220 * il n'existe pas de « toutes » implicite.221 */222export function AddressPicker({ addresses, value, onChange, legend, hint }: { addresses: readonly ApiAddress[]; value: readonly string[]; onChange: (ids: string[]) => void; legend: string; hint?: string }) {223  const [q, setQ] = useState("")224  const id = useId()225  const shown = useMemo(() => groupByMailbox(addresses.filter((a) => !q.trim() || a.address.toLowerCase().includes(q.trim().toLowerCase()))), [addresses, q])226  const set = new Set(value)227  const toggle = (aid: string, on: boolean) => {228    const next = new Set(value)229    if (on) next.add(aid)230    else next.delete(aid)231    onChange([...next])232  }233  return (234    <fieldset className="adm-picker" data-testid="address-picker">235      <legend className="label">{legend}</legend>236      {hint ? <p className="muted small">{hint}</p> : null}237      {addresses.length > 8 ? (238        <>239          <label className="sr-only" htmlFor={`${id}-q`}>240            {t("adm.picker.filter")}241          </label>242          <input id={`${id}-q`} className="input" type="search" value={q} onChange={(e) => setQ(e.target.value)} placeholder={t("adm.picker.filter")} />243        </>244      ) : null}245      <p className="small muted" aria-live="polite">246        {t("adm.picker.count", { n: value.length })}247      </p>248      <div className="adm-picker-list">249        {shown.length === 0 ? <p className="muted small">{t("adm.picker.none")}</p> : null}250        {shown.map((g) => (251          <div key={g.mailbox} className="adm-picker-group" role="group" aria-label={g.mailbox}>252            <div className="small muted adm-picker-box">{g.mailbox}</div>253            {g.items.map((a) => (254              <label key={a.id} className="check adm-picker-item">255                <input type="checkbox" checked={set.has(a.id)} onChange={(e) => toggle(a.id, e.target.checked)} />256                <span className="adm-break">{a.address}</span>257                <span className="badge">{t(`adm.kind.${a.kind}`)}</span>258                {a.status !== "active" || a.expired ? <span className="badge warn">{t("adm.status.suspended")}</span> : null}259              </label>260            ))}261          </div>262        ))}263      </div>264    </fieldset>265  )266}267268/** Petit titre de champ + contenu, pour les fiches (cartes) de la console. */269export function Meta({ label, children }: { label: string; children: ReactNode }) {270  return (271    <div className="adm-meta-item">272      <dt>{label}</dt>273      <dd>{children}</dd>274    </div>275  )276}277
Files main
Menu

Theme