SPB Git

Repository Public

Explorer.tsx 35.9 KB 773 lines tsx

1// Onglet « Explorateur » : essayer l'API /api/v1 depuis la console, avec les droits d'une clé (jeton d'exploration de 10 minutes,2// gardé en mémoire du composant, jamais affiché ni stocké) ou de la session. Formulaire généré depuis la spécification OpenAPI3// servie par l'API, pré-vérification locale des permissions, confirmations avant toute écriture, exemples de code sans jeton.4import { Fragment, useEffect, useId, useMemo, useRef, useState } from "react"5import {6  blocking, buildRequest, callerFromKey, callerFromMe, checkPermission, groupByTag, initialValue, jsonToField, parseOperations, searchOperations,7  type AddressBook, type BuiltRequest, type Caller, type FormValue, type FormValues, type Json, type OpenApiDoc, type Operation, type PermissionCheck, type Problem,8} from "../../../admin/openapi"9import { snippet, type SnippetLang } from "../../../admin/snippets"10import { addMessages, getLang, t } from "../../../i18n"11import { enAdmExplorer } from "../../../i18n/en.adm.explorer"12import { frAdmExplorer } from "../../../i18n/fr.adm.explorer"13import { HttpError, NetworkError } from "../../../jmap/errors"14import { apiGet, apiPost, request } from "../../../jmap/http"15import { v1 } from "../../../mail/v1"16import { Section } from "../../Page"17import { Dialog, Icon, Spinner } from "../../kit"18import { CodeBlock, CopyButton, isCancelled, loadAddresses, sensitive } from "../kit"19import { Loadable, asArray, asString, errorText, fmtBytes, isRecord, useLoad } from "../shared"20import { JsonTree } from "./JsonTree"21import { FieldInput } from "./RequestForm"22import "./explorer.css"2324addMessages("fr", frAdmExplorer)25addMessages("en", enAdmExplorer)2627// ---------------------------------------------------------------- données28interface KeyInfo {29  id: string30  name: string31  prefix: string32  scopes: string[]33  address_ids: string[]34  all_addresses: boolean35}36interface MeInfo {37  scopes: string[]38  all_addresses: boolean39  addresses: { id: string; address: string }[]40}41interface Loaded {42  ops: Operation[]43  keys: KeyInfo[]44  book: AddressBook45  me: MeInfo | null46}47const strings = (v: unknown): string[] => asArray(v).filter((x): x is string => typeof x === "string")48/** Clés actives seulement (une clé révoquée ou expirée ne peut pas recevoir de jeton d'exploration). */49function parseKeys(raw: unknown): KeyInfo[] {50  return asArray(raw).filter(isRecord).flatMap((k) => {51    const id = asString(k.id)52    if (!id || k.state !== "active") return []53    return [{ id, name: asString(k.name) ?? id, prefix: asString(k.prefix) ?? "", scopes: strings(k.scopes), address_ids: strings(k.address_ids), all_addresses: k.all_addresses === true }]54  })55}56function parseMe(raw: unknown): MeInfo | null {57  if (!isRecord(raw)) return null58  return { scopes: strings(raw.scopes), all_addresses: raw.all_addresses === true, addresses: asArray(raw.addresses).filter(isRecord).flatMap((a) => (typeof a.id === "string" && typeof a.address === "string" ? [{ id: a.id, address: a.address }] : [])) }59}60const rethrowAbort = (e: unknown) => {61  if (e instanceof DOMException && e.name === "AbortError") throw e62}63async function loadExplorer(signal: AbortSignal): Promise<Loaded> {64  const [doc, keys, book, me] = await Promise.all([65    apiGet<OpenApiDoc>("/api/v1/openapi.json", signal),66    apiGet<unknown>("/api/admin/api-keys", signal).then(parseKeys),67    // annuaire et identité : utiles à la pré-vérification seulement — leur absence ne bloque pas l'explorateur68    loadAddresses(signal).then((list) => list.map((a) => ({ id: a.id, address: a.address })), (e) => (rethrowAbort(e), [])),69    v1<unknown>("/me", { signal }).then(parseMe, (e) => (rethrowAbort(e), null)),70  ])71  return { ops: parseOperations(doc), keys, book, me }72}7374// ---------------------------------------------------------------- réponse75const SHOWN_HEADERS = ["X-Request-Id", "X-RateLimit-Limit", "X-RateLimit-Remaining", "X-RateLimit-Reset", "Retry-After", "Idempotency-Replayed"]76const TEXT_LIMIT = 200_00077type Body = { kind: "json"; value: Json } | { kind: "text"; text: string; truncated: boolean } | { kind: "binary"; size: number; type: string } | { kind: "empty" }78interface CallResult {79  status: number80  ok: boolean81  durationMs: number82  headers: [string, string][]83  body: Body84  /** code d'erreur de l'enveloppe /api/v1 */85  code: string | null86  message: string | null87  /** réponse d'erreur reçue par le transport de la session : le corps est reconstitué, les en-têtes ne sont pas disponibles */88  rebuilt: boolean89}90interface HistoryItem {91  n: number92  method: string93  path: string94  status: number95  durationMs: number96  caller: string97}9899async function readResponse(r: Response, binaryExpected: boolean, started: number): Promise<CallResult> {100  const type = r.headers.get("content-type") ?? ""101  const headers = SHOWN_HEADERS.flatMap((h): [string, string][] => {102    const v = r.headers.get(h)103    return v === null ? [] : [[h, v]]104  })105  let body: Body106  if (r.ok && binaryExpected) {107    // téléchargement : jamais rendu, seulement mesuré108    const blob = await r.blob()109    body = { kind: "binary", size: blob.size, type: type || blob.type || "application/octet-stream" }110  } else if (/json/i.test(type)) {111    const text = await r.text()112    try {113      body = text ? { kind: "json", value: JSON.parse(text) as Json } : { kind: "empty" }114    } catch {115      body = { kind: "text", text: text.slice(0, TEXT_LIMIT), truncated: text.length > TEXT_LIMIT }116    }117  } else if (/^text\/|yaml|xml/i.test(type)) {118    const text = await r.text()119    body = text ? { kind: "text", text: text.slice(0, TEXT_LIMIT), truncated: text.length > TEXT_LIMIT } : { kind: "empty" }120  } else {121    const blob = await r.blob()122    body = blob.size ? { kind: "binary", size: blob.size, type: type || "application/octet-stream" } : { kind: "empty" }123  }124  const durationMs = Math.round(performance.now() - started)125  const err = body.kind === "json" && isRecord(body.value) && isRecord(body.value.error) ? body.value.error : null126  return { status: r.status, ok: r.ok, durationMs, headers, body, code: err ? asString(err.code) : null, message: err ? asString(err.message) : null, rebuilt: false }127}128129/** Phrase claire pour les codes d'erreur que l'explorateur provoque le plus souvent. */130function codeSentence(code: string | null): string | null {131  switch (code) {132    case "insufficient_scope":133      return t("adm.explorer.code.insufficient_scope")134    case "from_not_allowed":135    case "address_not_allowed":136      return t("adm.explorer.code.address_not_allowed")137    case "invalid_request":138      return t("adm.explorer.code.invalid_request")139    case "invalid_api_key":140    case "key_revoked":141    case "key_expired":142      return t("adm.explorer.code.invalid_api_key")143    case "rate_limited":144      return t("adm.explorer.code.rate_limited")145    case "not_found":146      return t("adm.explorer.code.not_found")147    case "reauth_required":148      return t("adm.explorer.code.reauth_required")149    default:150      return null151  }152}153154// ---------------------------------------------------------------- petites briques155function MethodBadge({ method }: { method: string }) {156  return <span className={`badge adm-explorer-method m-${method.toLowerCase()}`}>{method}</span>157}158159function EndpointList({ ops, current, onPick, idBase }: { ops: Operation[]; current: string; onPick: (id: string) => void; idBase: string }) {160  const [q, setQ] = useState("")161  const shown = useMemo(() => searchOperations(ops, q), [ops, q])162  const groups = useMemo(() => groupByTag(shown), [shown])163  return (164    <div className="adm-explorer-list" data-testid="explorer-endpoints">165      <div className="field">166        <label htmlFor={`${idBase}-q`}>{t("adm.explorer.search")}</label>167        <input id={`${idBase}-q`} className="input" type="search" value={q} onChange={(e) => setQ(e.target.value)} placeholder={t("adm.explorer.searchHint")} autoComplete="off" spellCheck={false} data-testid="explorer-search" />168      </div>169      <p className="small muted" aria-live="polite" data-testid="explorer-count">170        {t("adm.explorer.count", { n: shown.length })}171      </p>172      {shown.length === 0 ? <p className="muted">{t("adm.explorer.noMatch")}</p> : null}173      <div className="adm-explorer-groups">174        {groups.map((g) => (175          <div key={g.tag}>176            <h4 className="adm-explorer-tag">{g.tag || t("adm.explorer.untagged")}</h4>177            <ul>178              {g.operations.map((op) => (179                <li key={op.id}>180                  <button type="button" className="adm-explorer-op" aria-current={op.id === current ? "true" : undefined} onClick={() => onPick(op.id)} data-testid="explorer-op" data-op={op.id}>181                    <MethodBadge method={op.method} />182                    <span className="adm-explorer-op-text">183                      <span className="mono adm-break">{op.path}</span>184                      {op.summary ? <span className="small muted">{op.summary}</span> : null}185                    </span>186                  </button>187                </li>188              ))}189            </ul>190          </div>191        ))}192      </div>193    </div>194  )195}196197function Precheck({ check, session }: { check: PermissionCheck; session: boolean }) {198  const icon = check.verdict === "allowed" ? "check" : check.verdict === "denied" ? "close" : "help"199  const cls = check.verdict === "allowed" ? "ok" : check.verdict === "denied" ? "danger" : "warn"200  return (201    <div className="adm-explorer-precheck" data-testid="explorer-precheck" data-verdict={check.verdict}>202      <div className="row wrap">203        <h4>{t("adm.explorer.precheck.title")}</h4>204        <span className={`badge ${cls}`}>205          <Icon name={icon} small />206          {t(`adm.explorer.precheck.${check.verdict}`)}207        </span>208      </div>209      <ul aria-live="polite">210        {check.public ? (211          <li>{t("adm.explorer.precheck.public")}</li>212        ) : check.verdict === "unknown" && !check.scope.ok && !check.scope.missing.length ? (213          <li>{t("adm.explorer.precheck.noCaller")}</li>214        ) : check.scope.required.length === 0 ? (215          <li>{t("adm.explorer.precheck.scopeNone")}</li>216        ) : (217          <li>218            {t(check.scope.ok ? "adm.explorer.precheck.scopeOk" : "adm.explorer.precheck.scopeMissing")} <code>{check.scope.required.join(t("adm.explorer.or"))}</code>219          </li>220        )}221        {check.addresses.map((a) => (222          <li key={a.address}>223            <code className="adm-break">224              {a.where} = {a.address}225            </code>{" "}226            — {t(`adm.explorer.precheck.addr.${a.verdict}`)}227          </li>228        ))}229        {check.resource && check.verdict !== "denied" ? <li>{t("adm.explorer.precheck.resource")}</li> : null}230      </ul>231      <p className="small muted">{t(session ? "adm.explorer.precheck.noteSession" : "adm.explorer.precheck.note")}</p>232    </div>233  )234}235236/** Confirmation avant toute requête autre que GET ; envoi de courrier ou suppression : avertissement et case à cocher. */237function GuardDialog({ op, path, denied, onConfirm, onClose }: { op: Operation; path: string; denied: boolean; onConfirm: () => void; onClose: () => void }) {238  const [sure, setSure] = useState(false)239  const id = useId()240  const strong = op.danger === "send" || op.danger === "delete"241  return (242    <Dialog243      title={t(op.danger === "send" ? "adm.explorer.guard.sendTitle" : op.danger === "delete" ? "adm.explorer.guard.deleteTitle" : "adm.explorer.guard.writeTitle")}244      onClose={onClose}245      alert246      footer={247        <>248          <button type="button" className="btn" onClick={onClose} data-autofocus>249            {t("common.cancel")}250          </button>251          <button252            type="button"253            className={`btn ${strong ? "danger solid" : "primary"}`}254            disabled={strong && !sure}255            onClick={() => {256              onClose()257              onConfirm()258            }}259            data-testid="explorer-guard-confirm"260          >261            {t(op.danger === "send" ? "adm.explorer.guard.sendConfirm" : op.danger === "delete" ? "adm.explorer.guard.deleteConfirm" : "adm.explorer.guard.writeConfirm")}262          </button>263        </>264      }265    >266      <div className="stack" data-testid="explorer-guard" data-danger={op.danger}>267        <p className="row wrap">268          <MethodBadge method={op.method} />269          <code className="adm-break">{path}</code>270        </p>271        {strong ? (272          <div className="banner danger" role="alert">273            <Icon name="warn" />274            <span>{t(op.danger === "send" ? "adm.explorer.guard.sendWarn" : "adm.explorer.guard.deleteWarn")}</span>275          </div>276        ) : (277          <p>{t("adm.explorer.guard.writeBody")}</p>278        )}279        {denied ? <p className="small muted">{t("adm.explorer.guard.denied")}</p> : null}280        {strong ? (281          <label className="check" htmlFor={`${id}-sure`}>282            <input id={`${id}-sure`} type="checkbox" checked={sure} onChange={(e) => setSure(e.target.checked)} data-testid="explorer-guard-check" />283            <span>{t(op.danger === "send" ? "adm.explorer.guard.sendCheck" : "adm.explorer.guard.deleteCheck")}</span>284          </label>285        ) : null}286      </div>287    </Dialog>288  )289}290291function ResponseView({ result }: { result: CallResult }) {292  const sentence = codeSentence(result.code)293  const pretty = result.body.kind === "json" ? JSON.stringify(result.body.value, null, 2) : result.body.kind === "text" ? result.body.text : ""294  return (295    <div className="stack" data-testid="explorer-response">296      <div className="row wrap">297        <span className={`badge ${result.ok ? "ok" : "danger"}`} data-testid="explorer-status">298          <Icon name={result.ok ? "check" : "close"} small />299          {t("adm.explorer.response.status", { status: result.status })}300        </span>301        <span className="small muted">{t("adm.explorer.response.duration", { ms: result.durationMs })}</span>302        {result.code ? (303          <code className="adm-break" data-testid="explorer-code">304            {result.code}305          </code>306        ) : null}307        <span className="spacer" />308        {pretty ? <CopyButton text={pretty} label={t("adm.explorer.response.copy")} /> : null}309      </div>310      {sentence || result.message ? (311        <p className={result.ok ? "small" : "adm-error small"}>312          {sentence}313          {sentence && result.message ? " " : ""}314          {result.message ? <span className="muted">{result.message}</span> : null}315        </p>316      ) : null}317      {result.headers.length ? (318        <dl className="adm-dl adm-explorer-headers" data-testid="explorer-headers">319          {result.headers.map(([k, v]) => (320            <Fragment key={k}>321              <dt>{k}</dt>322              <dd className="mono">{v}</dd>323            </Fragment>324          ))}325        </dl>326      ) : result.rebuilt ? (327        <p className="small muted">{t("adm.explorer.response.rebuilt")}</p>328      ) : null}329      {result.body.kind === "json" ? (330        <JsonTree value={result.body.value} label={t("adm.explorer.response.body")} />331      ) : result.body.kind === "text" ? (332        <>333          <pre className="adm-pre mono" tabIndex={0} aria-label={t("adm.explorer.response.body")} data-testid="explorer-body">334            {result.body.text}335          </pre>336          {result.body.truncated ? <p className="small muted">{t("adm.explorer.response.truncated")}</p> : null}337        </>338      ) : result.body.kind === "binary" ? (339        <p data-testid="explorer-binary">340          <Icon name="file" small className="adm-explorer-inline" /> {t("adm.explorer.response.binary", { size: fmtBytes(result.body.size), type: result.body.type })}341        </p>342      ) : (343        <p className="muted">{t("adm.explorer.response.empty")}</p>344      )}345    </div>346  )347}348349// ---------------------------------------------------------------- requête d'une opération350interface PanelProps {351  op: Operation352  caller: Caller | null353  callerLabel: string354  keyId: string | null355  book: AddressBook356  obtainToken: (keyId: string) => Promise<string>357  dropToken: () => void358  onCall: (h: Omit<HistoryItem, "n">) => void359}360361function RequestPanel({ op, caller, callerLabel, keyId, book, obtainToken, dropToken, onCall }: PanelProps) {362  const idBase = useId()363  const bodyField = op.body.kind === "json" ? op.body.field : null364  /** formulaire par champs possible (corps objet) ; sinon seul le JSON brut existe */365  const formable = bodyField?.kind === "object"366  const [params, setParams] = useState<{ path: FormValues; query: FormValues; header: FormValues }>(() => {367    const init = { path: {} as FormValues, query: {} as FormValues, header: {} as FormValues }368    for (const p of op.params) init[p.in][p.name] = initialValue(p.field)369    return init370  })371  const [body, setBody] = useState<FormValue>(() => (bodyField ? initialValue(bodyField) : undefined))372  const [mode, setMode] = useState<"form" | "raw">(formable || !bodyField ? "form" : "raw")373  const [raw, setRaw] = useState(() => (bodyField && !formable ? (typeof body === "string" ? body : "") : ""))374  const [file, setFile] = useState<File | null>(null)375  const [modeNote, setModeNote] = useState<string | null>(null)376  const [problems, setProblems] = useState<Problem[]>([])377  const [notice, setNotice] = useState<string | null>(null)378  const [guard, setGuard] = useState<BuiltRequest | null>(null)379  const [busy, setBusy] = useState(false)380  const [result, setResult] = useState<CallResult | null>(null)381  const [lang, setLang] = useState<SnippetLang>("curl")382383  const built = useMemo(() => buildRequest(op, { ...params, ...(mode === "raw" ? { raw } : { body }) }), [op, params, body, raw, mode])384  const check = useMemo(() => checkPermission(caller, op, built, book), [caller, op, built, book])385  const rawInvalid = mode === "raw" && built.problems.some((p) => p.path === "body" && p.kind === "json")386387  const toRaw = () => {388    if (mode === "raw") return389    // le JSON brut part de ce que le formulaire enverrait390    setRaw(built.body === undefined ? "" : JSON.stringify(built.body, null, 2))391    setMode("raw")392    setModeNote(null)393  }394  const toForm = () => {395    if (mode === "form" || !bodyField) return396    if (!raw.trim()) {397      setBody(jsonToField(bodyField, undefined).value)398    } else {399      let parsed: Json400      try {401        parsed = JSON.parse(raw) as Json402      } catch {403        return setModeNote(t("adm.explorer.mode.invalid"))404      }405      const r = jsonToField(bodyField, parsed)406      if (r.lossy) return setModeNote(t("adm.explorer.mode.lossy"))407      setBody(r.value)408    }409    setMode("form")410    setModeNote(null)411  }412413  const run = async (req: BuiltRequest) => {414    setBusy(true)415    setNotice(null)416    try {417      const extra: Record<string, string> = { ...req.headers }418      if (req.binary && file) extra["content-type"] = file.type || "application/octet-stream"419      let res: CallResult420      if (keyId) {421        // avec une clé : jeton d'exploration en en-tête, cookie de session jamais joint422        const headers: Record<string, string> = { accept: "application/json", ...extra }423        if (!op.public) headers.authorization = `Bearer ${await obtainToken(keyId)}`424        if (!req.binary && req.body !== undefined) headers["content-type"] = "application/json"425        const started = performance.now()426        const r = await fetch(req.url, { method: req.method, headers, body: req.binary ? (file ?? undefined) : req.body === undefined ? undefined : JSON.stringify(req.body), credentials: "omit", cache: "no-store" })427        res = await readResponse(r, op.binaryResponse, started)428        if (r.status === 401) dropToken()429      } else {430        const started = performance.now()431        try {432          const r = await sensitive(() => request(req.url, { method: req.method, headers: extra, quiet401: true, ...(req.binary ? { body: file ?? undefined } : req.body === undefined ? {} : { json: req.body }) }))433          res = await readResponse(r, op.binaryResponse, started)434        } catch (e) {435          if (!(e instanceof HttpError)) throw e436          // le transport de la session ne rend pas la réponse d'erreur : enveloppe reconstituée à partir de ce qu'il en a lu437          const error: { [k: string]: Json } = { code: e.code, message: e.message }438          if (e.details !== undefined) error.details = e.details as Json439          res = { status: e.status, ok: false, durationMs: Math.round(performance.now() - started), headers: [], body: { kind: "json", value: { error } }, code: e.code, message: e.message, rebuilt: true }440        }441      }442      setResult(res)443      onCall({ method: req.method, path: req.path, status: res.status, durationMs: res.durationMs, caller: callerLabel })444    } catch (e) {445      if (!isCancelled(e)) setNotice(e instanceof NetworkError || e instanceof TypeError ? t("adm.explorer.error.network") : errorText(e, { key_inactive: t("adm.explorer.error.keyInactive"), not_found: t("adm.explorer.error.keyGone") }))446    } finally {447      setBusy(false)448    }449  }450451  const execute = () => {452    const bad = blocking(built.problems)453    setProblems(bad)454    setNotice(null)455    if (bad.length) return setNotice(t(rawInvalid ? "adm.explorer.error.rawInvalid" : "adm.explorer.error.fields"))456    if (built.binary && !file) return setNotice(t("adm.explorer.error.noFile"))457    if (op.danger === "none") void run(built)458    else setGuard(built)459  }460461  const groups = (["path", "query", "header"] as const).map((where) => ({ where, list: op.params.filter((p) => p.in === where) })).filter((g) => g.list.length)462  const snippetText = useMemo(463    () => snippet(lang, { method: built.method, url: `${location.origin}${built.url}`, headers: built.headers, body: built.binary ? undefined : built.body, file: built.binary ? { name: file?.name ?? "file.bin", type: file?.type ?? "" } : undefined, auth: !op.public }),464    [lang, built, file, op.public],465  )466467  return (468    <>469      <Section title={t("adm.explorer.request")}>470        <div className="adm-explorer-title" data-testid="explorer-current" data-op={op.id}>471          <MethodBadge method={op.method} />472          <code className="adm-break">{op.path}</code>473          {op.danger === "send" ? <span className="badge danger">{t("adm.explorer.danger.send")}</span> : op.danger === "delete" ? <span className="badge danger">{t("adm.explorer.danger.delete")}</span> : op.danger === "write" ? <span className="badge warn">{t("adm.explorer.danger.write")}</span> : null}474        </div>475        <div className="adm-explorer-doc" data-testid="explorer-doc">476          {op.summary ? <p>{op.summary}</p> : null}477          {op.description ? <p className="small muted adm-break">{op.description}</p> : null}478          <dl className="adm-dl">479            <dt>{t("adm.explorer.doc.scopes")}</dt>480            <dd>481              {op.public ? (482                t("adm.explorer.doc.public")483              ) : op.scopes.length ? (484                <span className="row wrap">485                  {op.scopes.map((s, i) => (486                    <span key={s} className="row">487                      {i ? <span className="small muted">{t("adm.explorer.or").trim()}</span> : null}488                      <code>{s}</code>489                    </span>490                  ))}491                </span>492              ) : (493                t("adm.explorer.doc.anyCaller")494              )}495            </dd>496            <dt>{t("adm.explorer.doc.errors")}</dt>497            <dd>498              {op.errors.length ? (499                <ul className="adm-explorer-errors">500                  {op.errors.map((e) => (501                    <li key={e.status}>502                      <code>{e.status}</code> {e.description}503                    </li>504                  ))}505                </ul>506              ) : null}507              {op.errorEnvelope ? (508                <span className="small muted">509                  {t("adm.explorer.doc.envelope")} <code>{'{"error": {"code", "message", "details"}}'}</code>510                </span>511              ) : op.errors.length ? null : (512                t("adm.none")513              )}514            </dd>515          </dl>516        </div>517518        <Precheck check={check} session={!keyId} />519520        {groups.map((g) => (521          <fieldset key={g.where} className="adm-explorer-group">522            <legend>{t(`adm.explorer.params.${g.where}`)}</legend>523            <div className="adm-explorer-fields">524              {g.list.map((p) => (525                <FieldInput key={p.name} field={p.field} value={params[g.where][p.name]} onChange={(v) => setParams((cur) => ({ ...cur, [g.where]: { ...cur[g.where], [p.name]: v } }))} path={`${g.where}.${p.name}`} idBase={idBase} problems={problems} />526              ))}527            </div>528          </fieldset>529        ))}530531        {op.body.kind === "binary" ? (532          <div className="field">533            <label htmlFor={`${idBase}-file`}>{t("adm.explorer.file.label")}</label>534            <input id={`${idBase}-file`} className="input" type="file" onChange={(e) => setFile(e.target.files?.[0] ?? null)} data-testid="explorer-file" aria-describedby={`${idBase}-fileh`} />535            <span className="hint" id={`${idBase}-fileh`}>536              {file ? t("adm.explorer.file.chosen", { name: file.name, size: fmtBytes(file.size), type: file.type || "application/octet-stream" }) : t("adm.explorer.file.hint")}537            </span>538          </div>539        ) : null}540541        {bodyField ? (542          <fieldset className="adm-explorer-group">543            <legend>{t("adm.explorer.body")}</legend>544            <div className="row wrap">545              <div className="segmented" role="group" aria-label={t("adm.explorer.mode.label")}>546                <button type="button" aria-pressed={mode === "form"} onClick={toForm} disabled={!formable} data-testid="explorer-mode-form">547                  {t("adm.explorer.mode.form")}548                </button>549                <button type="button" aria-pressed={mode === "raw"} onClick={toRaw} data-testid="explorer-mode-raw">550                  {t("adm.explorer.mode.raw")}551                </button>552              </div>553              {modeNote ? (554                <span className="adm-error small" role="alert" data-testid="explorer-mode-note">555                  {modeNote}556                </span>557              ) : null}558            </div>559            {mode === "form" && formable ? (560              <FieldInput field={bodyField} value={body} onChange={setBody} path="body" idBase={idBase} problems={problems} root />561            ) : (562              <div className="field">563                <label htmlFor={`${idBase}-raw`}>{t("adm.explorer.raw.label")}</label>564                <textarea id={`${idBase}-raw`} className="textarea mono adm-explorer-raw" rows={10} value={raw} onChange={(e) => setRaw(e.target.value)} spellCheck={false} autoComplete="off" autoCapitalize="off" aria-invalid={rawInvalid || undefined} aria-describedby={`${idBase}-rawh`} data-testid="explorer-raw" />565                <span className={rawInvalid ? "adm-error small" : "hint"} id={`${idBase}-rawh`} data-testid="explorer-raw-state">566                  {rawInvalid ? t("adm.explorer.raw.invalid") : t("adm.explorer.raw.hint")}567                </span>568              </div>569            )}570          </fieldset>571        ) : null}572573        <div className="row wrap">574          <button type="button" className="btn primary" onClick={execute} disabled={busy} data-testid="explorer-run">575            {busy ? <span className="spinner" aria-hidden="true" /> : <Icon name="send" />}576            <span>{t("adm.explorer.run")}</span>577          </button>578          <code className="small adm-break adm-grow" data-testid="explorer-url">579            {built.method} {built.url}580          </code>581        </div>582        {notice ? (583          <p className="adm-error" role="alert" data-testid="explorer-notice">584            {notice}585          </p>586        ) : null}587      </Section>588589      <Section title={t("adm.explorer.response.title")}>590        <div aria-live="polite" aria-busy={busy}>591          {busy ? <Spinner label={t("adm.explorer.running")} /> : result ? <ResponseView result={result} /> : <p className="muted">{t("adm.explorer.response.none")}</p>}592        </div>593      </Section>594595      <Section title={t("adm.explorer.snippet.title")} description={t("adm.explorer.snippet.note")}>596        <div className="segmented adm-tabs" role="group" aria-label={t("adm.explorer.snippet.lang")}>597          {(["curl", "ts", "python"] as const).map((l) => (598            <button key={l} type="button" aria-pressed={lang === l} onClick={() => setLang(l)} data-testid={`explorer-lang-${l}`}>599              {l === "curl" ? "cURL" : l === "ts" ? "TypeScript" : "Python"}600            </button>601          ))}602        </div>603        <CodeBlock code={snippetText} label={t("adm.explorer.snippet.label", { lang: lang === "curl" ? "cURL" : lang === "ts" ? "TypeScript" : "Python" })} testId="explorer-snippet" />604      </Section>605606      {guard ? <GuardDialog op={op} path={guard.url} denied={check.verdict === "denied"} onConfirm={() => void run(guard)} onClose={() => setGuard(null)} /> : null}607    </>608  )609}610611// ---------------------------------------------------------------- atelier612const SESSION = "session"613const fmtClock = (iso: string) => new Date(iso).toLocaleTimeString(getLang() === "fr" ? "fr-CA" : "en-CA", { hour: "2-digit", minute: "2-digit" })614615function Workspace({ data }: { data: Loaded }) {616  const idBase = useId()617  const [callerId, setCallerId] = useState(SESSION)618  const [opId, setOpId] = useState(() => (data.ops.find((o) => o.id === "GET /me") ?? data.ops[0])?.id ?? "")619  const [picker, setPicker] = useState(false)620  const [history, setHistory] = useState<HistoryItem[]>([])621  const counter = useRef(0)622  // Jeton d'exploration : dans cette référence seulement. Jamais dans l'état, un magasin, l'URL ni le stockage ; jamais rendu.623  const token = useRef<{ keyId: string; value: string; expiresAt: number } | null>(null)624  /** ce qui s'affiche du jeton : la clé concernée et l'heure d'expiration — pas sa valeur */625  const [tokenInfo, setTokenInfo] = useState<{ keyId: string; expiresAt: string } | null>(null)626627  const dropToken = () => {628    token.current = null629    setTokenInfo(null)630  }631  useEffect(() => () => void (token.current = null), [])632  useEffect(() => {633    if (!tokenInfo) return634    const timer = setTimeout(dropToken, Math.max(0, new Date(tokenInfo.expiresAt).getTime() - Date.now()))635    return () => clearTimeout(timer)636  }, [tokenInfo])637638  const obtainToken = async (keyId: string): Promise<string> => {639    const cur = token.current640    if (cur && cur.keyId === keyId && cur.expiresAt - Date.now() > 20_000) return cur.value641    const r = await sensitive(() => apiPost<{ token: string; expires_at: string }>(`/api/admin/api-keys/${encodeURIComponent(keyId)}/explorer-token`))642    token.current = { keyId, value: r.token, expiresAt: new Date(r.expires_at).getTime() }643    setTokenInfo({ keyId, expiresAt: r.expires_at })644    return r.token645  }646647  const key = data.keys.find((k) => k.id === callerId) ?? null648  const caller = useMemo<Caller | null>(() => (key ? callerFromKey(key) : data.me ? callerFromMe(data.me) : null), [key, data.me])649  const op = data.ops.find((o) => o.id === opId) ?? null650  const callerLabel = key ? key.name : t("adm.explorer.caller.session")651  const pick = (id: string) => {652    setOpId(id)653    setPicker(false)654  }655656  if (!op) {657    return (658      <div className="empty card">659        <Icon name="code" />660        <p>{t("adm.explorer.emptySpec")}</p>661      </div>662    )663  }664  return (665    <>666      <Section>667        <div className="adm-form">668          <div className="field">669            <label htmlFor={`${idBase}-caller`}>{t("adm.explorer.caller.label")}</label>670            <select671              id={`${idBase}-caller`}672              className="select"673              value={callerId}674              onChange={(e) => {675                dropToken()676                setCallerId(e.target.value)677              }}678              data-testid="explorer-caller"679            >680              <option value={SESSION}>{t("adm.explorer.caller.session")}</option>681              {data.keys.map((k) => (682                <option key={k.id} value={k.id}>683                  {k.prefix ? `${k.name} (${k.prefix}…)` : k.name}684                </option>685              ))}686            </select>687            <span className="hint">{data.keys.length ? t("adm.explorer.caller.hint") : t("adm.explorer.caller.noKeys")}</span>688          </div>689          <p className="small adm-explorer-token" aria-live="polite" data-testid="explorer-token-state">690            <Icon name={key ? "key" : "user"} small className="adm-explorer-inline" />{" "}691            {!key ? t("adm.explorer.token.session") : tokenInfo && tokenInfo.keyId === key.id ? t("adm.explorer.token.valid", { time: fmtClock(tokenInfo.expiresAt) }) : t("adm.explorer.token.lazy")}692          </p>693        </div>694      </Section>695696      <div className="adm-explorer-cols">697        <div className="adm-explorer-side">698          <Section title={t("adm.explorer.endpoints")}>699            <EndpointList ops={data.ops} current={op.id} onPick={pick} idBase={`${idBase}-side`} />700          </Section>701        </div>702        <div className="adm-explorer-main">703          <button type="button" className="btn adm-explorer-pick" onClick={() => setPicker(true)} data-testid="explorer-pick">704            <Icon name="list" />705            <span>{t("adm.explorer.pick")}</span>706          </button>707          <RequestPanel key={op.id} op={op} caller={caller} callerLabel={callerLabel} keyId={key?.id ?? null} book={data.book} obtainToken={obtainToken} dropToken={dropToken} onCall={(h) => setHistory((cur) => [{ ...h, n: ++counter.current }, ...cur].slice(0, 12))} />708709          <Section title={t("adm.explorer.history.title")} description={t("adm.explorer.history.note")}>710            {history.length === 0 ? (711              <p className="muted">{t("adm.explorer.history.empty")}</p>712            ) : (713              <div className="table-wrap">714                <table className="table cards-sm" data-testid="explorer-history">715                  <caption className="sr-only">{t("adm.explorer.history.title")}</caption>716                  <thead>717                    <tr>718                      <th scope="col">{t("adm.explorer.history.method")}</th>719                      <th scope="col">{t("adm.explorer.history.path")}</th>720                      <th scope="col">{t("adm.explorer.history.status")}</th>721                      <th scope="col">{t("adm.explorer.history.duration")}</th>722                      <th scope="col">{t("adm.explorer.history.caller")}</th>723                    </tr>724                  </thead>725                  <tbody>726                    {history.map((h) => (727                      <tr key={h.n}>728                        <td data-label={t("adm.explorer.history.method")}>729                          <MethodBadge method={h.method} />730                        </td>731                        <td data-label={t("adm.explorer.history.path")} className="mono adm-break">732                          {h.path}733                        </td>734                        <td data-label={t("adm.explorer.history.status")}>735                          <span className={`badge ${h.status < 400 ? "ok" : "danger"}`}>736                            <Icon name={h.status < 400 ? "check" : "close"} small />737                            {h.status}738                          </span>739                        </td>740                        <td data-label={t("adm.explorer.history.duration")} className="adm-nowrap">741                          {t("adm.explorer.response.duration", { ms: h.durationMs })}742                        </td>743                        <td data-label={t("adm.explorer.history.caller")} className="adm-break">744                          {h.caller}745                        </td>746                      </tr>747                    ))}748                  </tbody>749                </table>750              </div>751            )}752          </Section>753        </div>754      </div>755756      {picker ? (757        <Dialog title={t("adm.explorer.endpoints")} onClose={() => setPicker(false)} wide>758          <EndpointList ops={data.ops} current={op.id} onPick={pick} idBase={`${idBase}-dlg`} />759        </Dialog>760      ) : null}761    </>762  )763}764765export default function ExplorerTab() {766  const load = useLoad(loadExplorer)767  return (768    <Loadable load={load} toolbar={<p className="muted small adm-grow">{t("adm.explorer.intro")}</p>}>769      {(data) => <Workspace data={data} />}770    </Loadable>771  )772}773
Files main
Menu

Theme