SPB Git

Repository Public

Webhooks.tsx 10.7 KB 257 lines tsx

1// Onglet « Webhooks » : liste, création et modification, secret montré une seule fois, journal des livraisons avec rejeu,2// événement d'essai, destinations internes permises (garde SSRF) et exemple de vérification de signature pour le récepteur.3import { useState } from "react"4import { eventKey, isEventType, type AllowEntry, type TestResult, type Webhook } from "../../../admin/webhooks"5import { addMessages, t } from "../../../i18n"6import { enAdmWebhooks } from "../../../i18n/en.adm.webhooks"7import { frAdmWebhooks } from "../../../i18n/fr.adm.webhooks"8import { apiGet } from "../../../jmap/http"9import { v1, type ApiAddress } from "../../../mail/v1"10import { toast } from "../../../state/app"11import { ConfirmDialog, Icon } from "../../kit"12import { Meta, SecretDialog, loadAddresses, sensitive, toastFail } from "../kit"13import { Loadable, fmtWhen, useLoad } from "../shared"14import { Allowlist } from "./Allowlist"15import { Deliveries } from "./Deliveries"16import { Editor } from "./Editor"17import { Snippet } from "./Snippet"18import { TestOutcome, hookCodes, type TestState } from "./common"19import "./webhooks.css"2021addMessages("fr", frAdmWebhooks)22addMessages("en", enAdmWebhooks)2324interface Data {25  hooks: Webhook[]26  addresses: ApiAddress[]27  allow: AllowEntry[]28}29type View = { name: "list" } | { name: "new" } | { name: "edit"; id: string } | { name: "deliveries"; id: string }3031/** Le secret ne doit vivre que dans le dialogue qui le montre : il est retiré de l'objet gardé en mémoire. */32function withoutSecret(w: Webhook): Webhook {33  const { secret: _secret, ...rest } = w34  return rest35}3637export default function WebhooksTab() {38  const load = useLoad<Data>(async (signal) => {39    const [hooks, addresses, allow] = await Promise.all([v1<{ data: Webhook[] }>("/webhooks", { signal }), loadAddresses(signal), apiGet<AllowEntry[]>("/api/admin/webhook-allowlist", signal)])40    return { hooks: hooks.data.map(withoutSecret), addresses, allow: Array.isArray(allow) ? allow : [] }41  })42  const [view, setView] = useState<View>({ name: "list" })43  const [secret, setSecret] = useState<{ title: string; value: string } | null>(null)44  const [tests, setTests] = useState<Record<string, TestState>>({})45  const [confirm, setConfirm] = useState<{ kind: "delete" | "rotate"; hook: Webhook } | null>(null)46  const [busy, setBusy] = useState<string | null>(null)4748  const sendTest = async (w: Webhook) => {49    setTests((s) => ({ ...s, [w.id]: { pending: true } }))50    try {51      const result = await v1<TestResult>(`/webhooks/${w.id}/test`, { method: "POST", json: {} })52      setTests((s) => ({ ...s, [w.id]: { pending: false, result, at: Date.now() } }))53    } catch (e) {54      setTests((s) => ({ ...s, [w.id]: { pending: false, failure: e, at: Date.now() } }))55    }56  }57  const rotate = async (w: Webhook) => {58    setBusy(w.id)59    try {60      const r = await sensitive(() => v1<Webhook>(`/webhooks/${w.id}`, { method: "PATCH", json: { rotate_secret: true } }))61      if (r.secret) setSecret({ title: t("adm.webhooks.secret.rotatedTitle", { name: w.name }), value: r.secret })62      load.reload()63    } catch (e) {64      toastFail(e, hookCodes())65    } finally {66      setBusy(null)67    }68  }69  const remove = async (w: Webhook) => {70    setBusy(w.id)71    try {72      await v1(`/webhooks/${w.id}`, { method: "DELETE" })73      toast({ kind: "success", text: t("adm.webhooks.deleted", { name: w.name }) })74      setView({ name: "list" })75      load.reload()76    } catch (e) {77      toastFail(e, hookCodes())78    } finally {79      setBusy(null)80    }81  }8283  const dialogs = (84    <>85      {secret ? <SecretDialog title={secret.title} secret={secret.value} description={t("adm.webhooks.secret.body")} onDone={() => setSecret(null)} /> : null}86      {confirm?.kind === "delete" ? (87        <ConfirmDialog88          title={t("adm.webhooks.delete.title")}89          body={<p>{t("adm.webhooks.delete.body", { name: confirm.hook.name })}</p>}90          confirmLabel={t("adm.webhooks.delete.confirm")}91          danger92          requireText={confirm.hook.name}93          onConfirm={() => void remove(confirm.hook)}94          onClose={() => setConfirm(null)}95        />96      ) : null}97      {confirm?.kind === "rotate" ? (98        <ConfirmDialog99          title={t("adm.webhooks.rotate.title")}100          body={<p>{t("adm.webhooks.rotate.body", { name: confirm.hook.name })}</p>}101          confirmLabel={t("adm.webhooks.rotate.confirm")}102          // l'invite de clé d'accès s'ouvre après la fermeture de ce dialogue (jamais deux dialogues empilés)103          onConfirm={() => void rotate(confirm.hook)}104          onClose={() => setConfirm(null)}105        />106      ) : null}107    </>108  )109110  return (111    <>112      <Loadable113        load={load}114        toolbar={115          view.name === "list" ? (116            <>117              <p className="muted small adm-grow">{t("adm.webhooks.intro")}</p>118              <button type="button" className="btn primary" onClick={() => setView({ name: "new" })} data-testid="webhook-new">119                <Icon name="plus" small />120                <span>{t("adm.webhooks.new")}</span>121              </button>122            </>123          ) : (124            <button type="button" className="btn" onClick={() => setView({ name: "list" })} data-testid="webhook-back">125              <Icon name="back" small />126              <span>{t("adm.webhooks.back")}</span>127            </button>128          )129        }130      >131        {(d) => {132          const current = view.name === "edit" || view.name === "deliveries" ? d.hooks.find((h) => h.id === view.id) : undefined133          if (view.name === "new" || (view.name === "edit" && current)) {134            return (135              <Editor136                key={current?.id ?? "new"}137                hook={current ?? null}138                addresses={d.addresses}139                allow={d.allow.map((a) => a.host_port)}140                onCancel={() => setView({ name: "list" })}141                onSaved={(w, created) => {142                  if (created && w.secret) setSecret({ title: t("adm.webhooks.secret.createdTitle", { name: w.name }), value: w.secret })143                  else toast({ kind: "success", text: t("adm.webhooks.saved", { name: w.name }) })144                  setView({ name: "list" })145                  load.reload()146                }}147              />148            )149          }150          if (view.name === "deliveries" && current) {151            return <Deliveries key={current.id} hook={current} test={tests[current.id]} onTest={() => sendTest(current)} />152          }153          return (154            <>155              {d.hooks.length === 0 ? (156                <div className="empty card">157                  <Icon name="send" />158                  <p>{t("adm.webhooks.empty")}</p>159                </div>160              ) : (161                <div className="adm-cards" data-testid="webhook-list">162                  {d.hooks.map((w) => (163                    <HookCard164                      key={w.id}165                      hook={w}166                      addresses={d.addresses}167                      test={tests[w.id]}168                      busy={busy === w.id}169                      onEdit={() => setView({ name: "edit", id: w.id })}170                      onDeliveries={() => setView({ name: "deliveries", id: w.id })}171                      onTest={() => void sendTest(w)}172                      onRotate={() => setConfirm({ kind: "rotate", hook: w })}173                      onDelete={() => setConfirm({ kind: "delete", hook: w })}174                    />175                  ))}176                </div>177              )}178              <Allowlist entries={d.allow} onChanged={load.reload} />179              <Snippet />180            </>181          )182        }}183      </Loadable>184      {dialogs}185    </>186  )187}188189function HookCard({ hook: w, addresses, test, busy, onEdit, onDeliveries, onTest, onRotate, onDelete }: { hook: Webhook; addresses: readonly ApiAddress[]; test: TestState | undefined; busy: boolean; onEdit: () => void; onDeliveries: () => void; onTest: () => void; onRotate: () => void; onDelete: () => void }) {190  const byId = new Map(addresses.map((a) => [a.id, a.address]))191  const titleId = `wh-${w.id}`192  return (193    <article className="card stack" aria-labelledby={titleId} data-testid="webhook-card" data-webhook-id={w.id}>194      <div className="adm-card-head">195        <h3 id={titleId}>{w.name}</h3>196        <span className={`badge ${w.active ? "ok" : "warn"}`}>197          <Icon name={w.active ? "check" : "close"} small />198          {t(w.active ? "adm.webhooks.active" : "adm.webhooks.inactive")}199        </span>200        <span className="badge">{t(w.owner === "key" ? "adm.webhooks.owner.key" : "adm.webhooks.owner.admin")}</span>201        {w.include_content ? (202          <span className="badge warn">203            <Icon name="eye" small />204            {t("adm.webhooks.content.badge")}205          </span>206        ) : null}207      </div>208      <dl className="adm-metas">209        <Meta label={t("adm.webhooks.field.url")}>210          <span className="mono adm-break">{w.url}</span>211        </Meta>212        <Meta label={t("adm.webhooks.field.events")}>213          <ul className="adm-wh-events">214            {w.events.map((e) => (215              <li key={e} className="badge mono" title={isEventType(e) ? t(eventKey(e)) : undefined}>216                {e}217              </li>218            ))}219          </ul>220        </Meta>221        <Meta label={t("adm.webhooks.field.addresses")}>222          {w.address_ids.length === 0 ? (223            t("adm.webhooks.addresses.all")224          ) : (225            <span className="adm-break">{w.address_ids.map((id) => byId.get(id) ?? t("adm.webhooks.addresses.unknown")).join(", ")}</span>226          )}227        </Meta>228        <Meta label={t("adm.webhooks.field.updated")}>{fmtWhen(w.updated_at)}</Meta>229      </dl>230      <div className="row wrap">231        <button type="button" className="btn small" onClick={onEdit}>232          <Icon name="edit" small />233          <span>{t("common.edit")}</span>234        </button>235        <button type="button" className="btn small" onClick={onDeliveries}>236          <Icon name="list" small />237          <span>{t("adm.webhooks.deliveries")}</span>238        </button>239        <button type="button" className="btn small" onClick={onTest} disabled={test?.pending === true}>240          <Icon name="send" small />241          <span>{t("adm.webhooks.test.send")}</span>242        </button>243        <button type="button" className="btn small" onClick={onRotate} disabled={busy}>244          <Icon name="key" small />245          <span>{t("adm.webhooks.rotate.action")}</span>246        </button>247        <span className="spacer" />248        <button type="button" className="btn small danger" onClick={onDelete} disabled={busy}>249          <Icon name="trash" small />250          <span>{t("common.delete")}</span>251        </button>252      </div>253      <TestOutcome test={test} />254    </article>255  )256}257
Files main
Menu

Theme