Repository Public
1// Assistant d'une clé d'API (création ou modification des droits) : identité, portées en langage clair et profils, adresses2// permises (jamais de « toutes » implicite), envoi externe, limites et échéance, récapitulatif. L'enregistrement passe par3// `sensitive()` : si l'API exige la clé d'accès, l'invite s'ouvre puis la demande reprend seule.4import { useEffect, useId, useMemo, useRef, useState } from "react"5import {6 LIMITS, POLICIES, POWERFUL, PRESETS, SCOPE_GROUPS, STEPS, applyPreset, canSend, detectPreset, diffPayload, emptyForm, expiryToIso, formErrorKey, formFromKey, hasAdmin,7 parseDomains, presetDescKey, presetLabelKey, scopeDescKey, scopeGroupKey, scopeLabelKey, toPayload, toggleScope, validateStep, type ExpiryMode, type FormError,8 type KeyForm, type Step,9} from "../../../admin/scopes"10import { fmtDateTime, fmtNumber, t } from "../../../i18n"11import type { ApiAddress } from "../../../mail/v1"12import { toast } from "../../../state/app"13import { Dialog, Field, Icon } from "../../kit"14import { AddressPicker, isCancelled, sensitive } from "../kit"15import { errorText } from "../shared"16import { createKey, patchKey, type ApiKey, type Created } from "./api"1718const EXPIRY_MODES: readonly ExpiryMode[] = ["never", "30", "90", "365", "date"]19/** Codes d'erreur de l'API → phrases (appelé au rendu : la langue peut changer). */20export const keyErrorCodes = (): Record<string, string> => ({21 all_addresses_requires_admin: t("adm.keys.err.all_requires_admin"),22 unknown_address: t("adm.keys.api.unknownAddress"),23 invalid_scope: t("adm.keys.api.invalidScope"),24 invalid: t("adm.keys.api.invalid"),25 not_found: t("adm.keys.api.notFound"),26 key_revoked: t("adm.keys.api.revoked"),27 reauth_required: t("adm.keys.api.reauth"),28})2930export function expiryText(form: KeyForm): string {31 const e = expiryToIso(form)32 if (!e.ok) return t(formErrorKey(e.error))33 return e.iso ? fmtDateTime(e.iso) : t("adm.keys.expiry.never")34}3536export function KeyWizard({ editing, addresses, onClose, onCreated, onSaved }: { editing?: ApiKey; addresses: readonly ApiAddress[]; onClose: () => void; onCreated: (c: Created) => void; onSaved: (k: ApiKey) => void }) {37 const initial = useMemo<KeyForm>(() => {38 if (!editing) return emptyForm()39 const known = new Set(addresses.map((a) => a.id))40 const f = formFromKey(editing)41 return { ...f, addressIds: f.addressIds.filter((id) => known.has(id)) } // une adresse supprimée depuis ne reste pas cochée en silence42 }, [editing, addresses])43 const [form, setForm] = useState<KeyForm>(initial)44 const [index, setIndex] = useState(0)45 const [errors, setErrors] = useState<FormError[]>([])46 const [failure, setFailure] = useState<string | null>(null)47 const [busy, setBusy] = useState(false)48 const [leaving, setLeaving] = useState(false)49 const heading = useRef<HTMLHeadingElement>(null)50 const uid = useId()51 const step: Step = STEPS[index]52 const options = { allowEmptyAddresses: !!editing }53 const dirty = JSON.stringify(form) !== JSON.stringify(initial)54 const set = (patch: Partial<KeyForm>) => {55 setForm((f) => ({ ...f, ...patch }))56 setErrors([])57 setFailure(null)58 }59 const first = useRef(true)60 useEffect(() => {61 if (first.current) first.current = false62 else heading.current?.focus()63 }, [index])6465 // Échap, clic à côté ou « Fermer » : pendant l'enregistrement (invite de clé d'accès comprise) rien ne se ferme ;66 // une saisie commencée demande une confirmation, sur place.67 const requestClose = () => {68 if (busy) return69 if (dirty && !leaving) setLeaving(true)70 else onClose()71 }72 const goTo = (target: number) => {73 setFailure(null)74 for (let i = 0; i < target; i++) {75 const errs = validateStep(STEPS[i], form, options)76 if (errs.length) {77 setIndex(i)78 setErrors(errs)79 return80 }81 }82 setErrors([])83 setIndex(target)84 }85 const submit = async () => {86 if (busy) return87 let payload88 try {89 payload = toPayload(form, options)90 } catch {91 return goTo(STEPS.length - 1) // ramène à la première étape fautive92 }93 setBusy(true)94 setFailure(null)95 try {96 if (editing) {97 const patch = diffPayload(editing, payload)98 if (Object.keys(patch).length === 0) {99 toast({ kind: "info", text: t("adm.keys.edit.unchanged") })100 onClose()101 return102 }103 // Le corps part COMPLET, pas seulement la différence : côté serveur, un champ omis d'un PATCH retombe sur sa valeur104 // par défaut (liste d'adresses vidée, politique et limites réinitialisées). Tout dire explicitement l'évite.105 onSaved(await sensitive(() => patchKey(editing.id, payload)))106 } else {107 // la réponse (qui porte le jeton) est remise telle quelle au parent : rien n'en est gardé ici108 onCreated(await sensitive(() => createKey(payload)))109 }110 } catch (e) {111 if (!isCancelled(e)) setFailure(errorText(e, keyErrorCodes()))112 } finally {113 setBusy(false)114 }115 }116117 const preset = detectPreset(form.scopes)118 const admin = hasAdmin(form.scopes)119 const byId = useMemo(() => new Map(addresses.map((a) => [a.id, a.address])), [addresses])120 const domains = parseDomains(form.domains)121 const last = index === STEPS.length - 1122 const title = editing ? t("adm.keys.edit.title", { name: editing.name }) : t("adm.keys.create.title")123124 return (125 <Dialog126 title={title}127 onClose={requestClose}128 wide129 footer={130 <>131 <button type="button" className="btn" onClick={requestClose} disabled={busy}>132 {t("common.cancel")}133 </button>134 <span className="spacer" />135 {index > 0 ? (136 <button type="button" className="btn" onClick={() => goTo(index - 1)} disabled={busy}>137 {t("adm.keys.wizard.previous")}138 </button>139 ) : null}140 {last ? (141 <button type="button" className="btn primary" onClick={() => void submit()} disabled={busy} data-testid="key-submit">142 {busy ? <span className="spinner" aria-hidden="true" /> : <Icon name="key" />}143 <span>{editing ? t("adm.keys.edit.submit") : t("adm.keys.create.submit")}</span>144 </button>145 ) : (146 <button type="button" className="btn primary" onClick={() => goTo(index + 1)} data-testid="key-next">147 {t("adm.keys.wizard.next")}148 </button>149 )}150 </>151 }152 >153 <div className="stack adm-keys-wizard" data-testid="key-wizard" data-step={step}>154 {leaving ? (155 <div className="banner warn" role="alert">156 <Icon name="warn" />157 <span className="adm-grow">{t("adm.keys.wizard.leave")}</span>158 <button type="button" className="btn small" onClick={() => setLeaving(false)}>159 {t("adm.keys.wizard.stay")}160 </button>161 <button type="button" className="btn small danger" onClick={onClose}>162 {t("adm.keys.wizard.discard")}163 </button>164 </div>165 ) : null}166 <nav aria-label={t("adm.keys.wizard.steps")}>167 <ol className="adm-steps adm-keys-steps">168 {STEPS.map((s, i) => (169 <li key={s} aria-current={i === index ? "step" : undefined}>170 <button type="button" onClick={() => goTo(i)} disabled={busy}>171 <span aria-hidden="true">{i + 1}.</span> {t(`adm.keys.step.${s}`)}172 </button>173 </li>174 ))}175 </ol>176 </nav>177 <h3 ref={heading} tabIndex={-1} className="adm-keys-step-title" data-autofocus>178 {t("adm.keys.wizard.stepOf", { n: index + 1, total: STEPS.length })} — {t(`adm.keys.step.${step}`)}179 </h3>180181 {step === "identity" ? (182 <>183 <p className="muted small">{t("adm.keys.identity.intro")}</p>184 <Field label={t("adm.keys.field.name")} id={`${uid}n`} hint={t("adm.keys.field.nameHint")}>185 <input id={`${uid}n`} className="input" value={form.name} onChange={(e) => set({ name: e.target.value })} maxLength={LIMITS.name} autoComplete="off" spellCheck={false} required aria-invalid={errors.includes("name_required") || undefined} />186 </Field>187 <Field label={t("adm.keys.field.description")} id={`${uid}d`} hint={t("adm.keys.field.descriptionHint")}>188 <textarea id={`${uid}d`} className="textarea" value={form.description} onChange={(e) => set({ description: e.target.value })} maxLength={LIMITS.description} rows={3} />189 </Field>190 </>191 ) : null}192193 {step === "scopes" ? (194 <>195 <p className="muted small">{t("adm.keys.scopes.intro")}</p>196 <fieldset className="adm-keys-fieldset">197 <legend className="label">{t("adm.keys.scopes.presets")}</legend>198 <div className="adm-keys-choices">199 {PRESETS.map((p) => (200 <label key={p.id} className="adm-choice" data-testid={`preset-${p.id}`}>201 <input type="radio" name={`${uid}preset`} checked={preset === p.id} onChange={() => set(applyPreset(form, p.id))} />202 <span>203 <strong>{t(presetLabelKey(p.id))}</strong>204 <span className="small muted">{t(presetDescKey(p.id))}</span>205 </span>206 </label>207 ))}208 </div>209 </fieldset>210 <p className="small" role="status">211 {preset === "custom" ? t("adm.keys.scopes.custom", { n: form.scopes.length }) : t("adm.keys.scopes.matches", { preset: t(presetLabelKey(preset)) })}212 </p>213 {admin ? (214 <div className="banner warn">215 <Icon name="warn" />216 <span>{t("adm.keys.scopes.adminNote")}</span>217 </div>218 ) : null}219 <div className="adm-keys-groups">220 {SCOPE_GROUPS.map((g) => (221 <fieldset key={g.id} className="adm-keys-fieldset">222 <legend className="label">{t(scopeGroupKey(g.id))}</legend>223 {g.scopes.map((s) => (224 <label key={s} className="adm-keys-scope">225 <input type="checkbox" checked={form.scopes.includes(s)} onChange={(e) => set(toggleScope(form, s, e.target.checked))} aria-describedby={`${uid}s-${s}`} />226 <span>227 <span>228 {t(scopeLabelKey(s))} <code className="mono small muted">{s}</code>229 {POWERFUL.includes(s) ? <span className="badge warn adm-keys-inline">{t("adm.keys.scopes.powerful")}</span> : null}230 </span>231 <span className="small muted" id={`${uid}s-${s}`}>232 {t(scopeDescKey(s))}233 </span>234 </span>235 </label>236 ))}237 </fieldset>238 ))}239 </div>240 </>241 ) : null}242243 {step === "addresses" ? (244 <>245 <p className="muted small">{t("adm.keys.addresses.intro")}</p>246 {admin ? (247 <label className="adm-choice" data-testid="all-addresses">248 <input type="checkbox" checked={form.allAddresses} onChange={(e) => set({ allAddresses: e.target.checked })} />249 <span>250 <strong>{t("adm.keys.addresses.all")}</strong>251 <span className="small muted">{t("adm.keys.addresses.allHint")}</span>252 </span>253 </label>254 ) : (255 <p className="small muted">{t("adm.keys.addresses.allUnavailable")}</p>256 )}257 {form.allAddresses && admin ? (258 <div className="banner danger" role="status">259 <Icon name="warn" />260 <span>{t("adm.keys.addresses.allWarn")}</span>261 </div>262 ) : (263 <AddressPicker addresses={addresses} value={form.addressIds} onChange={(ids) => set({ addressIds: ids })} legend={t("adm.keys.addresses.legend")} hint={t("adm.keys.addresses.hint")} />264 )}265 {editing && !form.allAddresses && form.addressIds.length === 0 ? (266 <div className="banner warn" role="status">267 <Icon name="warn" />268 <span>{t("adm.keys.addresses.emptyWarn")}</span>269 </div>270 ) : null}271 </>272 ) : null}273274 {step === "policy" ? (275 <>276 <p className="muted small">{t("adm.keys.policy.intro")}</p>277 {canSend(form.scopes) ? null : (278 <div className="banner">279 <Icon name="help" />280 <span>{t("adm.keys.policy.cannotSend")}</span>281 </div>282 )}283 <fieldset className="adm-keys-fieldset">284 <legend className="label">{t("adm.keys.policy.legend")}</legend>285 <div className="adm-keys-choices">286 {POLICIES.map((p) => (287 <label key={p} className="adm-choice" data-testid={`policy-${p}`}>288 <input type="radio" name={`${uid}policy`} checked={form.policy === p} onChange={() => set({ policy: p })} />289 <span>290 <strong>{t(`adm.keys.policy.${p}`)}</strong>291 <span className="small muted">{t(`adm.keys.policyDesc.${p}`)}</span>292 </span>293 </label>294 ))}295 </div>296 </fieldset>297 {form.policy === "allow" && canSend(form.scopes) ? (298 <div className="banner warn" role="status">299 <Icon name="warn" />300 <span>{t("adm.keys.policy.allowWarn")}</span>301 </div>302 ) : null}303 <Field label={t("adm.keys.field.domains")} id={`${uid}dom`} hint={t("adm.keys.field.domainsHint")}>304 <textarea id={`${uid}dom`} className="textarea mono adm-keys-domains" value={form.domains} onChange={(e) => set({ domains: e.target.value })} rows={2} spellCheck={false} autoCapitalize="none" aria-invalid={errors.includes("domains_invalid") || undefined} />305 </Field>306 {domains.invalid.length ? <p className="small adm-error">{t("adm.keys.policy.invalidDomains", { list: domains.invalid.slice(0, 5).join(", ") })}</p> : null}307 </>308 ) : null}309310 {step === "limits" ? (311 <>312 <p className="muted small">{t("adm.keys.limits.intro")}</p>313 <div className="adm-form">314 <Field label={t("adm.keys.field.rate")} id={`${uid}r`} hint={t("adm.keys.field.rateHint", { max: fmtNumber(LIMITS.rateMax) })}>315 <input id={`${uid}r`} className="input" inputMode="numeric" value={form.rate} onChange={(e) => set({ rate: e.target.value })} autoComplete="off" aria-invalid={errors.includes("rate_invalid") || undefined} />316 </Field>317 <Field label={t("adm.keys.field.daily")} id={`${uid}q`} hint={t("adm.keys.field.dailyHint", { max: fmtNumber(LIMITS.dailyMax) })}>318 <input id={`${uid}q`} className="input" inputMode="numeric" value={form.daily} onChange={(e) => set({ daily: e.target.value })} autoComplete="off" aria-invalid={errors.includes("daily_invalid") || undefined} />319 </Field>320 <Field label={t("adm.keys.field.expiry")} id={`${uid}x`} hint={t("adm.keys.field.expiryHint")}>321 <select id={`${uid}x`} className="select" value={form.expiry} onChange={(e) => set({ expiry: e.target.value as ExpiryMode })}>322 {form.currentExpiry ? <option value="keep">{t("adm.keys.expiry.keep", { date: fmtDateTime(form.currentExpiry) })}</option> : null}323 {EXPIRY_MODES.map((m) => (324 <option key={m} value={m}>325 {t(`adm.keys.expiry.${m}`)}326 </option>327 ))}328 </select>329 </Field>330 {form.expiry === "date" ? (331 <Field label={t("adm.keys.field.expiryDate")} id={`${uid}xd`}>332 <input id={`${uid}xd`} className="input" type="date" value={form.expiryDate} onChange={(e) => set({ expiryDate: e.target.value })} aria-invalid={errors.includes("expiry_invalid") || errors.includes("expiry_past") || undefined} />333 </Field>334 ) : null}335 </div>336 </>337 ) : null}338339 {step === "review" ? (340 <>341 <p className="muted small">{editing ? t("adm.keys.review.introEdit") : t("adm.keys.review.intro")}</p>342 <dl className="adm-dl" data-testid="key-review">343 <dt>{t("adm.keys.field.name")}</dt>344 <dd>{form.name.trim()}</dd>345 {form.description.trim() ? (346 <>347 <dt>{t("adm.keys.field.description")}</dt>348 <dd>{form.description.trim()}</dd>349 </>350 ) : null}351 <dt>{t("adm.keys.col.scopes")}</dt>352 <dd>353 {preset !== "custom" ? <strong className="adm-block">{t(presetLabelKey(preset))}</strong> : null}354 <ul className="adm-keys-list">355 {form.scopes.map((s) => (356 <li key={s}>357 {t(scopeLabelKey(s))} <code className="mono small muted">{s}</code>358 </li>359 ))}360 </ul>361 </dd>362 <dt>{t("adm.keys.col.addresses")}</dt>363 <dd>364 {form.allAddresses && admin ? (365 <span className="badge danger">366 <Icon name="warn" small />367 {t("adm.keys.addresses.allBadge")}368 </span>369 ) : form.addressIds.length === 0 ? (370 <span className="badge warn">{t("adm.keys.addresses.noneBadge")}</span>371 ) : (372 <ul className="adm-keys-list mono">373 {form.addressIds.map((id) => (374 <li key={id}>{byId.get(id) ?? id}</li>375 ))}376 </ul>377 )}378 </dd>379 <dt>{t("adm.keys.col.policy")}</dt>380 <dd>381 {t(`adm.keys.policy.${form.policy}`)}382 {canSend(form.scopes) ? null : <span className="muted small adm-block">{t("adm.keys.policy.cannotSendShort")}</span>}383 </dd>384 <dt>{t("adm.keys.field.domains")}</dt>385 <dd className="mono">{domains.domains.length ? domains.domains.join(", ") : <span className="adm-sans">{t("adm.keys.domains.any")}</span>}</dd>386 <dt>{t("adm.keys.col.limits")}</dt>387 <dd>{t("adm.keys.limits.summary", { rate: form.rate.trim(), daily: form.daily.trim() })}</dd>388 <dt>{t("adm.keys.col.expiry")}</dt>389 <dd>{expiryText(form)}</dd>390 </dl>391 {editing ? null : (392 <div className="banner">393 <Icon name="key" />394 <span>{t("adm.keys.review.secretNote")}</span>395 </div>396 )}397 </>398 ) : null}399400 <div aria-live="assertive">401 {errors.length ? (402 <ul className="adm-error adm-keys-list" data-testid="key-errors">403 {errors.map((e) => (404 <li key={e}>{t(formErrorKey(e))}</li>405 ))}406 </ul>407 ) : null}408 {failure ? (409 <p className="adm-error" data-testid="key-failure">410 {failure}411 </p>412 ) : null}413 </div>414 </div>415 </Dialog>416 )417}418