SPB Git

Repository Public

Keys.tsx 14.8 KB 339 lines tsx

1// Onglet « Clés d'API » : liste (tableau, fiches sur téléphone), assistant de création, modification des droits, rotation,2// révocation. Le jeton d'une clé n'existe que le temps du dialogue qui le montre une fois (état local de ce composant) :3// jamais dans un magasin, le stockage du navigateur, l'adresse ou un journal.4import { useId, useMemo, useState } from "react"5import { GRACE_CHOICES, detectPreset, hasAdmin, presetLabelKey, scopeLabelKey, isScope } from "../../../admin/scopes"6import { addMessages, fmtDateTime, fmtNumber, t } from "../../../i18n"7import { enAdmKeys } from "../../../i18n/en.adm.keys"8import { frAdmKeys } from "../../../i18n/fr.adm.keys"9import type { ApiAddress } from "../../../mail/v1"10import { toast } from "../../../state/app"11import { linkProps } from "../../../state/session"12import { ConfirmDialog, Dialog, Field, Icon } from "../../kit"13import { SecretDialog, isCancelled, sensitive, toastFail } from "../kit"14import { Loadable, errorText, useLoad } from "../shared"15import { loadKeysData, pendingRevocation, revokeKey, rotateKey, type ApiKey } from "./api"16import { KeyWizard, keyErrorCodes } from "./KeyWizard"17import "./keys.css"1819addMessages("fr", frAdmKeys)20addMessages("en", enAdmKeys)2122/** Secret à montrer une fois : seule trace du jeton côté navigateur, effacée à la fermeture du dialogue. */23interface Shown {24  title: string25  description: string26  token: string27}2829function StateBadge({ k }: { k: ApiKey }) {30  const later = pendingRevocation(k)31  if (later) {32    return (33      <span className="badge warn" title={fmtDateTime(later)}>34        <Icon name="clock" small />35        {t("adm.keys.state.revoking", { date: fmtDateTime(later) })}36      </span>37    )38  }39  return (40    <span className={`badge ${k.state === "active" ? "ok" : k.state === "expired" ? "warn" : "danger"}`}>41      <Icon name={k.state === "active" ? "check" : k.state === "expired" ? "clock" : "close"} small />42      {t(`adm.keys.state.${k.state}`)}43    </span>44  )45}4647function PolicyBadge({ policy }: { policy: ApiKey["external_send_policy"] }) {48  return (49    <span className={`badge ${policy === "allow" ? "warn" : policy === "deny" ? "" : "ok"}`}>50      <Icon name={policy === "allow" ? "send" : policy === "deny" ? "close" : "shieldOk"} small />51      {t(`adm.keys.policyShort.${policy}`)}52    </span>53  )54}5556function ScopesCell({ k }: { k: ApiKey }) {57  const preset = detectPreset(k.scopes)58  return (59    <>60      {preset !== "custom" ? <strong className="adm-block adm-keys-preset">{t(presetLabelKey(preset))}</strong> : null}61      <span className="adm-keys-scopes">62        {k.scopes.map((s) => (63          <span key={s} className={`badge${s === "mail.admin" ? " danger" : ""}`} title={s}>64            {isScope(s) ? t(scopeLabelKey(s)) : s}65          </span>66        ))}67      </span>68    </>69  )70}7172function AddressesCell({ k, byId }: { k: ApiKey; byId: Map<string, string> }) {73  if (k.all_addresses && hasAdmin(k.scopes)) {74    return (75      <span className="badge danger">76        <Icon name="warn" small />77        {t("adm.keys.addresses.allBadge")}78      </span>79    )80  }81  if (k.address_ids.length === 0) return <span className="badge warn">{t("adm.keys.addresses.noneBadge")}</span>82  const names = k.address_ids.map((id) => byId.get(id) ?? t("adm.keys.addresses.unknown"))83  return (84    <span className="adm-keys-addresses">85      {names.slice(0, 3).map((a, i) => (86        <span key={i} className="mono adm-break">87          {a}88        </span>89      ))}90      {names.length > 3 ? (91        <details>92          <summary>{t("adm.keys.addresses.more", { n: names.length - 3 })}</summary>93          {names.slice(3).map((a, i) => (94            <span key={i} className="mono adm-break adm-block">95              {a}96            </span>97          ))}98        </details>99      ) : null}100    </span>101  )102}103104// ---------------------------------------------------------------- rotation105function RotateDialog({ k, onClose, onRotated }: { k: ApiKey; onClose: () => void; onRotated: (token: string, grace: number) => void }) {106  const [grace, setGrace] = useState<number>(0)107  const [busy, setBusy] = useState(false)108  const [failure, setFailure] = useState<string | null>(null)109  const id = useId()110  const rotate = async () => {111    if (busy) return112    setBusy(true)113    setFailure(null)114    try {115      const r = await sensitive(() => rotateKey(k.id, grace))116      onRotated(r.token, grace)117    } catch (e) {118      if (!isCancelled(e)) setFailure(errorText(e, keyErrorCodes()))119    } finally {120      setBusy(false)121    }122  }123  return (124    <Dialog125      title={t("adm.keys.rotate.title", { name: k.name })}126      onClose={() => (busy ? undefined : onClose())}127      footer={128        <>129          <button type="button" className="btn" onClick={onClose} disabled={busy}>130            {t("common.cancel")}131          </button>132          <button type="button" className="btn primary" onClick={() => void rotate()} disabled={busy} data-testid="rotate-submit">133            {busy ? <span className="spinner" aria-hidden="true" /> : <Icon name="refresh" />}134            <span>{t("adm.keys.rotate.submit")}</span>135          </button>136        </>137      }138    >139      <div className="stack" data-testid="rotate-dialog">140        <p>{t("adm.keys.rotate.body")}</p>141        <Field label={t("adm.keys.rotate.grace")} id={id} hint={t("adm.keys.rotate.graceHint")}>142          <select id={id} className="select" value={grace} onChange={(e) => setGrace(Number(e.target.value))} data-autofocus>143            {GRACE_CHOICES.map((g) => (144              <option key={g} value={g}>145                {t(`adm.keys.rotate.grace.${g}`)}146              </option>147            ))}148          </select>149        </Field>150        <p className="muted small">{t("adm.keys.rotate.webhooks")}</p>151        <div aria-live="assertive">{failure ? <p className="adm-error">{failure}</p> : null}</div>152      </div>153    </Dialog>154  )155}156157// ---------------------------------------------------------------- onglet158type Open = { kind: "create" } | { kind: "edit"; key: ApiKey } | { kind: "rotate"; key: ApiKey } | { kind: "revoke"; key: ApiKey } | null159160export default function KeysTab() {161  const load = useLoad(loadKeysData)162  const [open, setOpen] = useState<Open>(null)163  const [shown, setShown] = useState<Shown | null>(null)164  const [inactive, setInactive] = useState(false)165  const id = useId()166  const addresses: readonly ApiAddress[] = load.data?.addresses ?? []167  const byId = useMemo(() => new Map(addresses.map((a) => [a.id, a.address])), [addresses])168169  const revoke = async (k: ApiKey) => {170    try {171      await revokeKey(k.id)172      toast({ kind: "success", text: t("adm.keys.revoke.done", { name: k.name }) })173    } catch (e) {174      toastFail(e, keyErrorCodes())175    }176    load.reload()177  }178179  return (180    <>181      <Loadable182        load={load}183        toolbar={184          <>185            <button type="button" className="btn primary" onClick={() => setOpen({ kind: "create" })} disabled={load.data === null} data-testid="key-new">186              <Icon name="plus" />187              <span>{t("adm.keys.new")}</span>188            </button>189            <label className="check" htmlFor={id}>190              <input id={id} type="checkbox" checked={inactive} onChange={(e) => setInactive(e.target.checked)} />191              <span>{t("adm.keys.showInactive")}</span>192            </label>193          </>194        }195      >196        {({ keys }) => {197          const active = keys.filter((k) => k.state === "active")198          const list = inactive ? keys : active199          return (200            <>201              <p className="muted small" role="status">202                {t("adm.keys.count", { n: active.length })}203                {keys.length > active.length ? ` · ${t("adm.keys.countInactive", { n: keys.length - active.length })}` : ""}204              </p>205              {list.length === 0 ? (206                <div className="empty card">207                  <Icon name="key" />208                  <p>{keys.length === 0 ? t("adm.keys.empty") : t("adm.keys.emptyActive")}</p>209                </div>210              ) : (211                <div className="table-wrap">212                  <table className="table cards-sm adm-keys-table" data-testid="keys-table">213                    <caption className="sr-only">{t("adm.tab.keys")}</caption>214                    <thead>215                      <tr>216                        <th scope="col">{t("adm.keys.col.name")}</th>217                        <th scope="col">{t("adm.keys.col.scopes")}</th>218                        <th scope="col">{t("adm.keys.col.addresses")}</th>219                        <th scope="col">{t("adm.keys.col.policy")}</th>220                        <th scope="col">{t("adm.keys.col.limits")}</th>221                        <th scope="col">{t("adm.keys.col.lastUsed")}</th>222                        <th scope="col">{t("adm.keys.col.expiry")}</th>223                        <th scope="col">{t("adm.keys.col.state")}</th>224                        <th scope="col">225                          <span className="sr-only">{t("admin.col.actions")}</span>226                        </th>227                      </tr>228                    </thead>229                    <tbody>230                      {list.map((k) => {231                        const live = k.state === "active"232                        return (233                          <tr key={k.id} data-key-id={k.id} data-key-name={k.name} data-state={k.state}>234                            <th scope="row" className="adm-rowhead">235                              <span className="adm-break">{k.name}</span>236                              <span className="mono small muted adm-block" data-testid="key-prefix">237                                {k.prefix}…238                              </span>239                              {k.description ? <span className="small muted adm-block adm-sans adm-keys-desc">{k.description}</span> : null}240                              {k.rotated_from ? <span className="badge adm-keys-inline">{t("adm.keys.rotated")}</span> : null}241                            </th>242                            <td data-label={t("adm.keys.col.scopes")}>243                              <ScopesCell k={k} />244                            </td>245                            <td data-label={t("adm.keys.col.addresses")}>246                              <AddressesCell k={k} byId={byId} />247                            </td>248                            <td data-label={t("adm.keys.col.policy")}>249                              <PolicyBadge policy={k.external_send_policy} />250                              {k.allowed_recipient_domains.length ? <span className="small muted adm-block">{t("adm.keys.domains.only", { list: k.allowed_recipient_domains.join(", ") })}</span> : null}251                            </td>252                            <td data-label={t("adm.keys.col.limits")}>{t("adm.keys.limits.summary", { rate: fmtNumber(k.rate_per_minute), daily: fmtNumber(k.daily_send_limit) })}</td>253                            <td data-label={t("adm.keys.col.lastUsed")}>{k.last_used_at ? fmtDateTime(k.last_used_at) : t("adm.never")}</td>254                            <td data-label={t("adm.keys.col.expiry")}>{k.expires_at ? fmtDateTime(k.expires_at) : t("adm.keys.expiry.never")}</td>255                            <td data-label={t("adm.keys.col.state")}>256                              <StateBadge k={k} />257                            </td>258                            <td>259                              <div className="row wrap adm-actions adm-keys-actions">260                                <a className="btn small" {...linkProps(`/admin/usage?key=${encodeURIComponent(k.id)}`)} aria-label={t("adm.keys.action.usageOf", { name: k.name })}>261                                  {t("adm.keys.action.usage")}262                                </a>263                                {live ? (264                                  <>265                                    <button type="button" className="btn small" onClick={() => setOpen({ kind: "edit", key: k })} aria-label={t("adm.keys.action.editOf", { name: k.name })}>266                                      {t("common.edit")}267                                    </button>268                                    <button type="button" className="btn small" onClick={() => setOpen({ kind: "rotate", key: k })} aria-label={t("adm.keys.action.rotateOf", { name: k.name })}>269                                      {t("adm.keys.action.rotate")}270                                    </button>271                                    <button type="button" className="btn small danger" onClick={() => setOpen({ kind: "revoke", key: k })} aria-label={t("adm.keys.action.revokeOf", { name: k.name })}>272                                      {t("adm.keys.action.revoke")}273                                    </button>274                                  </>275                                ) : null}276                              </div>277                            </td>278                          </tr>279                        )280                      })}281                    </tbody>282                  </table>283                </div>284              )}285            </>286          )287        }}288      </Loadable>289290      {open?.kind === "create" || open?.kind === "edit" ? (291        <KeyWizard292          editing={open.kind === "edit" ? open.key : undefined}293          addresses={addresses}294          onClose={() => setOpen(null)}295          onCreated={(c) => {296            setOpen(null)297            setShown({ title: t("adm.keys.secret.createdTitle", { name: c.key.name }), description: t("adm.keys.secret.body"), token: c.token })298            load.reload()299          }}300          onSaved={(k) => {301            setOpen(null)302            toast({ kind: "success", text: t("adm.keys.edit.done", { name: k.name }) })303            load.reload()304          }}305        />306      ) : null}307      {open?.kind === "rotate" ? (308        <RotateDialog309          k={open.key}310          onClose={() => setOpen(null)}311          onRotated={(token, grace) => {312            const name = open.key.name313            setOpen(null)314            setShown({ title: t("adm.keys.secret.rotatedTitle", { name }), description: `${t("adm.keys.secret.body")} ${t(grace ? "adm.keys.secret.rotatedGrace" : "adm.keys.secret.rotatedNow")}`, token })315            load.reload()316          }}317        />318      ) : null}319      {open?.kind === "revoke" ? (320        <ConfirmDialog321          title={t("adm.keys.revoke.title", { name: open.key.name })}322          body={323            <div className="stack">324              <p>{t("adm.keys.revoke.body")}</p>325              {pendingRevocation(open.key) ? <p className="muted small">{t("adm.keys.revoke.pending")}</p> : null}326            </div>327          }328          confirmLabel={t("adm.keys.revoke.confirm")}329          danger330          requireText={open.key.name}331          onConfirm={() => revoke(open.key)}332          onClose={() => setOpen(null)}333        />334      ) : null}335      {shown ? <SecretDialog title={shown.title} description={shown.description} secret={shown.token} onDone={() => setShown(null)} /> : null}336    </>337  )338}339
Files main
Menu

Theme