SPB Git

Repository Public

Grants.tsx 9.9 KB 128 lines tsx

1"use client";2import { useState } from "react";3import { apiDelete, apiPost, type Schemas } from "@/api/client";4import { useApiList, useApiQuery } from "@/api/query";5import { useI18n } from "@/i18n";6import { Badge, Banner, Button, Combobox, ConfirmDialog, DataStamp, DataTable, Dialog, ErrorState, Icon, LoadMore, QueryBoundary, SelectField, SkeletonRows, TextField, type Column } from "@/ui";7import { Gate } from "./SettingsFrame";8import { useAct } from "./useAct";910type Grant = Schemas["PolicyGrant"];11type Role = Schemas["UserRole"];12const ROLES: Role[] = ["owner", "admin", "operator", "viewer"];13type ResourceKind = "" | "node" | "service" | "site" | "tag";1415export function GrantsSection() {16  return <Gate permission="users.manage"><Grants /></Gate>;17}1819function Grants() {20  const { t, fmt } = useI18n();21  const catalog = useApiQuery("/permissions", undefined, { staleTime: 5 * 60_000 });22  const grants = useApiList("/policy-grants", { query: { limit: 100 } });23  const users = useApiList("/users", { query: { limit: 200 } });24  const { busy, act } = useAct();25  const [creating, setCreating] = useState(false);26  const [remove, setRemove] = useState<Grant | null>(null);27  const userName = (id: string) => { const u = users.items.find((x) => x.id === id); return u ? `${u.display_name} (@${u.handle})` : id; };2829  const columns: Column<Grant>[] = [30    { id: "effect", header: t("settings.grants.effect"), cell: (g) => <Badge tone={g.effect === "deny" ? "critical" : "ok"} icon={g.effect === "deny" ? "denied" : "check"}>{t(`settings.grants.effects.${g.effect}`)}</Badge>, sortValue: (g) => g.effect },31    { id: "perm", header: t("settings.grants.permission"), mono: true, cell: (g) => g.permission, sortValue: (g) => g.permission },32    { id: "subject", header: t("settings.grants.subject"), cell: (g) => (g.subject_kind === "role" ? <span>{t("settings.grants.kinds.role")} · {ROLES.includes(g.subject as Role) ? t(`states.role.${g.subject as Role}`) : g.subject}</span> : <span>{t("settings.grants.kinds.user")} · {userName(g.subject)}</span>), sortValue: (g) => g.subject },33    { id: "res", header: t("settings.grants.resource"), hide: "sm", cell: (g) => (g.resource_kind ? <span className="mono">{g.resource_kind}{g.resource_id ? `:${g.resource_id}` : ""}</span> : <span className="muted">{t("settings.grants.allResources")}</span>) },34    { id: "created", header: t("common.created"), hide: "md", cell: (g) => <time dateTime={g.created_at} className="num">{fmt.dateTime(g.created_at)}</time>, sortValue: (g) => Date.parse(g.created_at) },35    { id: "act", header: t("common.actions"), srOnlyHeader: true, shrink: true, cell: (g) => <Button size="sm" variant="danger" icon="trash" onClick={() => setRemove(g)} data-testid="grant-delete">{t("common.delete")}</Button> },36  ];3738  return (39    <div className="stack-lg" data-testid="screen-settings-grants">40      <section className="section" aria-labelledby="set-grants">41        <div className="section-head">42          <h2 id="set-grants">{t("settings.grants.title")}</h2>43          <div className="row"><DataStamp at={grants.ready ? grants.updatedAt : undefined} /><Button variant="primary" icon="plus" onClick={() => setCreating(true)} disabled={!catalog.data} data-testid="grant-create">{t("settings.grants.create")}</Button></div>44        </div>45        <p className="muted">{t("settings.grants.intro")}</p>46        <Banner tone="info" icon="denied">{t("settings.grants.denyWins")}</Banner>47        {grants.error && !grants.ready ? <ErrorState error={grants.error} onRetry={grants.refetch} /> : !grants.ready ? <SkeletonRows rows={3} /> : (48          <DataTable caption={t("settings.grants.title")} columns={columns} rows={grants.items} rowKey={(g) => g.id} empty={<span className="muted">{t("settings.grants.empty")}</span>} />49        )}50        <LoadMore hasMore={grants.hasMore} loading={grants.loadingMore} onMore={grants.loadMore} />51      </section>52      <section className="section" aria-labelledby="set-catalog">53        <div className="section-head"><h2 id="set-catalog">{t("settings.grants.catalog")}</h2><DataStamp at={catalog.data ? catalog.dataUpdatedAt : undefined} /></div>54        <p className="muted">{t("settings.grants.catalogIntro")}</p>55        <QueryBoundary query={catalog}>56          {(c) => {57            const defaults = new Map(c.role_defaults.map((r) => [r.role, new Set(r.permissions)]));58            return (59              <div className="mcc-table-wrap" data-testid="permission-catalog">60                <table className="mcc-table compact">61                  <caption className="sr-only">{t("settings.grants.catalog")}</caption>62                  <thead><tr><th scope="col">{t("settings.grants.permission")}</th><th scope="col" className="hide-md">{t("common.description")}</th><th scope="col">{t("settings.grants.stepUp")}</th>{ROLES.map((r) => <th key={r} scope="col">{t(`states.role.${r}`)}</th>)}</tr></thead>63                  <tbody>64                    {c.permissions.map((p) => (65                      <tr key={p.name}>66                        <th scope="row" className="mono set-rowhead">{p.name}</th>67                        <td className="hide-md muted">{p.description}</td>68                        <td>{p.step_up ? <span className="row"><Icon name="passkey" size={14} /><span>{t("common.yes")}</span></span> : <span className="faint">{t("common.no")}</span>}</td>69                        {ROLES.map((r) => <td key={r}>{defaults.get(r)?.has(p.name) ? <span className="row tone-ok set-yes"><Icon name="check" size={14} /><span className="sr-only">{t("common.yes")}</span></span> : <span className="faint"><span aria-hidden="true">·</span><span className="sr-only">{t("common.no")}</span></span>}</td>)}70                      </tr>71                    ))}72                  </tbody>73                </table>74              </div>75            );76          }}77        </QueryBoundary>78      </section>79      {creating && catalog.data ? <GrantDialog permissions={catalog.data.permissions.map((p) => p.name)} users={users.items} onClose={() => setCreating(false)} /> : null}80      <ConfirmDialog open={remove !== null} onClose={() => setRemove(null)} danger busy={busy} title={t("settings.grants.deleteTitle")} body={remove ? `${t(`settings.grants.effects.${remove.effect}`)} · ${remove.permission}` : ""} confirmLabel={t("common.delete")}81        onConfirm={() => { if (remove) void act(() => apiDelete("/policy-grants/{id}", { path: { id: remove.id } }), { ok: t("settings.grants.deleted"), invalidate: ["/policy-grants"] }).then(() => setRemove(null)); }} />82    </div>83  );84}8586function GrantDialog({ permissions, users, onClose }: { permissions: string[]; users: Schemas["User"][]; onClose: () => void }) {87  const { t } = useI18n();88  const { busy, act } = useAct();89  const [effect, setEffect] = useState<Schemas["GrantEffect"]>("allow");90  const [permission, setPermission] = useState<string | null>(null);91  const [kind, setKind] = useState<Schemas["GrantSubjectKind"]>("role");92  const [role, setRole] = useState<Role>("operator");93  const [user, setUser] = useState<string | null>(null);94  const [resKind, setResKind] = useState<ResourceKind>("");95  const [resId, setResId] = useState("");96  const [tried, setTried] = useState(false);97  const subject = kind === "role" ? role : user;98  const submit = async () => {99    setTried(true);100    if (!permission || !subject || (resKind && !resId.trim())) return;101    const body: Schemas["CreatePolicyGrantRequest"] = { effect, permission, subject_kind: kind, subject, ...(resKind ? { resource_kind: resKind, resource_id: resId.trim() } : {}) };102    const r = await act(() => apiPost("/policy-grants", { body }), { ok: t("settings.grants.created"), invalidate: ["/policy-grants"] });103    if (r.ok) onClose();104  };105  const required = t("ui.schema.required", { limit: "" });106  return (107    <Dialog open onClose={onClose} title={t("settings.grants.createTitle")} description={t("settings.grants.denyWins")} size="wide" dismissable={!busy}108      footer={<><Button onClick={onClose} disabled={busy}>{t("common.cancel")}</Button><Button variant="primary" loading={busy} onClick={() => void submit()} data-testid="grant-submit">{t("common.create")}</Button></>}>109      <div className="mcc-form">110        <div className="mcc-form-row">111          <SelectField label={t("settings.grants.effect")} value={effect} onChange={setEffect} options={[{ value: "allow", label: t("settings.grants.effects.allow") }, { value: "deny", label: t("settings.grants.effects.deny") }]} />112          <Combobox label={t("settings.grants.permission")} required options={permissions.map((p) => ({ value: p, label: p }))} value={permission} onChange={setPermission} error={tried && !permission ? required : undefined} />113        </div>114        <div className="mcc-form-row">115          <SelectField label={t("settings.grants.subjectKind")} value={kind} onChange={setKind} options={[{ value: "role", label: t("settings.grants.kinds.role") }, { value: "user", label: t("settings.grants.kinds.user") }]} />116          {kind === "role"117            ? <SelectField label={t("settings.role")} value={role} onChange={setRole} options={ROLES.map((r) => ({ value: r, label: t(`states.role.${r}`) }))} />118            : <Combobox label={t("settings.grants.user")} required options={users.map((u) => ({ value: u.id, label: `${u.display_name} (@${u.handle})` }))} value={user} onChange={setUser} error={tried && !user ? required : undefined} />}119        </div>120        <div className="mcc-form-row">121          <SelectField<ResourceKind> label={t("settings.grants.resourceKind")} hint={t("settings.grants.resourceHint")} value={resKind} onChange={setResKind} options={[{ value: "", label: t("settings.grants.allResources") }, ...(["node", "service", "site", "tag"] as const).map((k) => ({ value: k, label: t(`settings.grants.resources.${k}`) }))]} />122          {resKind ? <TextField label={t("settings.grants.resourceId")} required mono value={resId} onChange={setResId} spellCheck={false} error={tried && !resId.trim() ? required : undefined} /> : null}123        </div>124      </div>125    </Dialog>126  );127}128
Files main
Menu

Theme