SPB Git

Repository Public

Security.tsx 8.4 KB 214 lines tsx

1// Réglages › Sécurité : clés d'accès (passkeys) et sessions ouvertes.2import { useState } from "react"3import { fmtDateTime, t } from "../../i18n"4import { HttpError } from "../../jmap/errors"5import { apiDelete, apiGet } from "../../jmap/http"6import { toast } from "../../state/app"7import { addPasskey, authErrorMessage, signOut } from "../../state/session"8import { ConfirmDialog, Icon, PromptDialog, Spinner } from "../kit"9import { Section } from "../Page"10import { LoadError, toastError, useLoad } from "./shared"1112interface Passkey {13  id: string14  label: string | null15  device_type: string | null16  backed_up: boolean17  created_at: string18  last_used_at: string | null19}20interface SessionRow {21  id: string22  kind: "web" | "native"23  device_name: string | null24  platform: string | null25  ip: string | null26  user_agent: string | null27  created_at: string28  last_seen_at: string | null29  current: boolean30}3132export function SecuritySection() {33  return (34    <>35      <Passkeys />36      <Sessions />37    </>38  )39}4041function Passkeys() {42  const { state, reload } = useLoad((signal) => apiGet<Passkey[]>("/api/passkeys", signal), "passkeys")43  const [adding, setAdding] = useState(false)44  const [removing, setRemoving] = useState<Passkey | null>(null)45  const nameOf = (p: Passkey) => p.label?.trim() || t("settings.security.passkeyUnnamed")4647  const add = async (label: string) => {48    try {49      await addPasskey(label)50      toast({ kind: "success", text: t("settings.security.passkeyAdded") })51      reload()52    } catch (e) {53      toast({ kind: "error", text: authErrorMessage(e) })54    }55  }56  const remove = async (p: Passkey) => {57    try {58      await apiDelete<unknown>(`/api/passkeys/${encodeURIComponent(p.id)}`)59      toast({ kind: "success", text: t("settings.security.passkeyRemoved") })60      reload()61    } catch (e) {62      if (e instanceof HttpError && e.status === 409 && e.code === "last_passkey") toast({ kind: "error", text: t("settings.security.lastPasskey") })63      else toastError(e)64    }65  }6667  return (68    <Section69      title={t("settings.security.passkeys")}70      description={t("settings.security.passkeysDesc")}71      actions={72        <button type="button" className="btn small" onClick={() => setAdding(true)}>73          <Icon name="plus" small />74          <span>{t("settings.security.addPasskey")}</span>75        </button>76      }77    >78      {state.status === "loading" ? (79        <Spinner label={t("common.loading")} />80      ) : state.status === "error" ? (81        <LoadError error={state.error} onRetry={reload} />82      ) : state.data.length === 0 ? (83        <p className="muted">{t("settings.security.noPasskeys")}</p>84      ) : (85        <div className="table-wrap">86          <table className="table" data-table="passkeys">87            <caption className="sr-only">{t("settings.security.passkeys")}</caption>88            <thead>89              <tr>90                <th scope="col">{t("settings.security.colLabel")}</th>91                <th scope="col">{t("settings.security.colSync")}</th>92                <th scope="col">{t("settings.security.colCreated")}</th>93                <th scope="col">{t("settings.security.colLastUsed")}</th>94                <th scope="col">95                  <span className="sr-only">{t("settings.security.colActions")}</span>96                </th>97              </tr>98            </thead>99            <tbody>100              {state.data.map((p) => (101                <tr key={p.id} data-passkey-id={p.id}>102                  <th scope="row" className="set-cell-main">103                    {nameOf(p)}104                  </th>105                  <td>106                    <span className={`badge ${p.backed_up ? "ok" : ""}`}>{p.backed_up ? t("settings.security.synced") : t("settings.security.deviceOnly")}</span>107                  </td>108                  <td>{fmtDateTime(p.created_at)}</td>109                  <td>{p.last_used_at ? fmtDateTime(p.last_used_at) : t("settings.security.never")}</td>110                  <td className="set-cell-action">111                    <button type="button" className="btn small danger" aria-label={t("settings.security.removePasskeyLabel", { label: nameOf(p) })} onClick={() => setRemoving(p)}>112                      {t("common.remove")}113                    </button>114                  </td>115                </tr>116              ))}117            </tbody>118          </table>119        </div>120      )}121      {adding ? <PromptDialog title={t("settings.security.addPasskey")} label={t("settings.security.passkeyLabel")} confirmLabel={t("common.add")} onSubmit={add} onClose={() => setAdding(false)} /> : null}122      {removing ? (123        <ConfirmDialog124          title={t("settings.security.removePasskeyTitle")}125          body={t("settings.security.removePasskeyBody", { label: nameOf(removing) })}126          confirmLabel={t("common.remove")}127          danger128          onConfirm={() => remove(removing)}129          onClose={() => setRemoving(null)}130        />131      ) : null}132    </Section>133  )134}135136function Sessions() {137  const { state, reload } = useLoad((signal) => apiGet<SessionRow[]>("/api/sessions", signal), "sessions")138  const [revoking, setRevoking] = useState<SessionRow | null>(null)139  const deviceOf = (s: SessionRow) => [s.device_name, s.platform].filter((x) => x && x.trim()).join(" · ") || t("settings.security.unknownDevice")140141  const revoke = async (s: SessionRow) => {142    if (s.current) return signOut()143    try {144      await apiDelete<unknown>(`/api/sessions/${encodeURIComponent(s.id)}`)145      toast({ kind: "success", text: t("settings.security.sessionRevoked") })146      reload()147    } catch (e) {148      toastError(e)149    }150  }151152  return (153    <Section title={t("settings.security.sessions")} description={t("settings.security.sessionsDesc")}>154      {state.status === "loading" ? (155        <Spinner label={t("common.loading")} />156      ) : state.status === "error" ? (157        <LoadError error={state.error} onRetry={reload} />158      ) : state.data.length === 0 ? (159        <p className="muted">{t("settings.security.noSessions")}</p>160      ) : (161        <div className="table-wrap">162          <table className="table" data-table="sessions">163            <caption className="sr-only">{t("settings.security.sessions")}</caption>164            <thead>165              <tr>166                <th scope="col">{t("settings.security.colDevice")}</th>167                <th scope="col">{t("settings.security.colKind")}</th>168                <th scope="col">{t("settings.security.colIp")}</th>169                <th scope="col">{t("settings.security.colLastSeen")}</th>170                <th scope="col">171                  <span className="sr-only">{t("settings.security.colActions")}</span>172                </th>173              </tr>174            </thead>175            <tbody>176              {state.data.map((s) => (177                <tr key={s.id} data-session-id={s.id} data-current={String(s.current)}>178                  <th scope="row" className="set-cell-main">179                    <div>{deviceOf(s)}</div>180                    {s.current ? <span className="badge accent">{t("settings.security.thisSession")}</span> : null}181                    {s.user_agent ? (182                      <div className="muted small set-ua" title={s.user_agent}>183                        {s.user_agent}184                      </div>185                    ) : null}186                  </th>187                  <td>{s.kind === "native" ? t("settings.security.kindApp") : t("settings.security.kindWeb")}</td>188                  <td className="mono">{s.ip || "—"}</td>189                  <td>{fmtDateTime(s.last_seen_at ?? s.created_at)}</td>190                  <td className="set-cell-action">191                    <button type="button" className={`btn small${s.current ? "" : " danger"}`} onClick={() => setRevoking(s)}>192                      {s.current ? t("settings.signOut") : t("settings.security.revoke")}193                    </button>194                  </td>195                </tr>196              ))}197            </tbody>198          </table>199        </div>200      )}201      {revoking ? (202        <ConfirmDialog203          title={revoking.current ? t("settings.security.signOutTitle") : t("settings.security.revokeTitle")}204          body={revoking.current ? t("settings.security.signOutBody") : t("settings.security.revokeBody", { device: deviceOf(revoking) })}205          confirmLabel={revoking.current ? t("settings.signOut") : t("settings.security.revoke")}206          danger={!revoking.current}207          onConfirm={() => revoke(revoking)}208          onClose={() => setRevoking(null)}209        />210      ) : null}211    </Section>212  )213}214
Files main
Menu

Theme