diff --git a/index.html b/index.html index d423224..a96a597 100644 --- a/index.html +++ b/index.html @@ -4,7 +4,8 @@ - envbao-admin + + EnvBao Admin
diff --git a/public/favicon.svg b/public/favicon.svg index 6893eb1..79d0f68 100644 --- a/public/favicon.svg +++ b/public/favicon.svg @@ -1 +1,5 @@ - \ No newline at end of file + + + + + diff --git a/src/App.tsx b/src/App.tsx index c5d2605..06748ea 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -2,6 +2,7 @@ import { QueryClient, QueryClientProvider } from '@tanstack/react-query' import { createBrowserRouter, RouterProvider } from 'react-router' import { SessionGuard } from './api/SessionGuard' import { SessionProvider } from './api/session' +import { ConfirmProvider } from './features/shared/ConfirmProvider' import { routes } from './routes' const queryClient = new QueryClient() @@ -11,8 +12,10 @@ function App() { return ( - - + + + + ) diff --git a/src/features/access/AccessEditor.test.tsx b/src/features/access/AccessEditor.test.tsx index a6a9aa1..55076dd 100644 --- a/src/features/access/AccessEditor.test.tsx +++ b/src/features/access/AccessEditor.test.tsx @@ -53,7 +53,7 @@ function setup() { test('shows managed grants and read-only other policies', async () => { const user = setup() - expect(await screen.findByText('secret/data/app/*')).toBeInTheDocument() + expect(await screen.findByText('secret/app/*')).toBeInTheDocument() const other = screen.getByText('default').closest('li')! await user.click(within(other).getByRole('button', { name: 'View default' })) expect(await within(other).findByText(/capabilities/)).toBeInTheDocument() @@ -118,9 +118,9 @@ test('revoke asks for confirmation', async () => { vi.mocked(grants.revokeAccess).mockResolvedValue() const user = setup() const confirm = vi.spyOn(window, 'confirm').mockReturnValueOnce(false).mockReturnValueOnce(true) - await user.click(await screen.findByRole('button', { name: 'Revoke secret/data/app/*' })) + await user.click(await screen.findByRole('button', { name: 'Revoke secret/app/*' })) expect(grants.revokeAccess).not.toHaveBeenCalled() - await user.click(screen.getByRole('button', { name: 'Revoke secret/data/app/*' })) + await user.click(screen.getByRole('button', { name: 'Revoke secret/app/*' })) expect(grants.revokeAccess).toHaveBeenCalledWith(client, target, ['secret/data/app/*']) confirm.mockRestore() }) diff --git a/src/features/access/AccessEditor.tsx b/src/features/access/AccessEditor.tsx index 7f5c1f8..26dcbd5 100644 --- a/src/features/access/AccessEditor.tsx +++ b/src/features/access/AccessEditor.tsx @@ -4,7 +4,10 @@ import type { BaoClient } from '../../api/bao' import { getGrantState, grantAccess, revokeAccess, type Target } from '../../api/grants' import { listKvMounts, readPolicyHcl } from '../../api/secrets' import { KV_CAPABILITIES, kvGrantRules, validateGrantPath, type KvCapability } from '../../model/managed' +import { groupGrants } from '../../model/grantRows' +import { CapabilityChips } from '../shared/CapabilityChips' import { PathPicker } from './PathPicker' +import { useConfirm } from '../shared/useConfirm' interface Props { client: BaoClient @@ -28,6 +31,7 @@ function PolicyView({ client, name }: { client: BaoClient; name: string }) { export function AccessEditor({ client, target, onClose }: Props) { const qc = useQueryClient() + const confirm = useConfirm() const stateKey = ['grant-state', target.kind, target.name] const state = useQuery({ queryKey: stateKey, queryFn: () => getGrantState(client, target) }) const mounts = useQuery({ queryKey: ['kv-mounts'], queryFn: () => listKvMounts(client) }) @@ -53,7 +57,7 @@ export function AccessEditor({ client, target, onClose }: Props) { return done() }, }) - const revoke = useMutation({ mutationFn: (path: string) => revokeAccess(client, target, [path]), onSuccess: done }) + const revoke = useMutation({ mutationFn: (paths: string[]) => revokeAccess(client, target, paths), onSuccess: done }) function submit(e: FormEvent) { e.preventDefault() @@ -63,6 +67,7 @@ export function AccessEditor({ client, target, onClose }: Props) { } const s = state.data + const rows = groupGrants(s?.managed?.grants ?? [], mounts.data?.map((m) => m.path) ?? []) const editable = !s?.managed || s.managed.editable return ( @@ -93,28 +98,38 @@ export function AccessEditor({ client, target, onClose }: Props) {

)} {showRaw &&
{s.hcl}
} - {s.managed?.grants.length ? ( + {rows.length ? ( - - + + - {s.managed.grants.map((g) => ( - + {rows.map((row) => ( + + - - - + + - - + + @@ -88,7 +97,7 @@ export function GroupsTab({ client }: { client: BaoClient }) { Name setDraft({ ...draft, name: e.target.value })} required /> -
+
Member entities {entities.data?.map((e) => (
setDraft({ ...draft, policies })} /> {save.error &&

{save.error.message}

} -
+
{' '} + diff --git a/src/features/identities/TokensTab.tsx b/src/features/identities/TokensTab.tsx index 5878af8..ea8ce04 100644 --- a/src/features/identities/TokensTab.tsx +++ b/src/features/identities/TokensTab.tsx @@ -5,6 +5,8 @@ import { createToken, listTokens, revokeToken, type CreatedToken } from '../../a import { useSession } from '../../api/useSession' import { ListState } from '../shared/ListState' import { PolicyPicker } from '../shared/PolicyPicker' +import { useConfirm } from '../shared/useConfirm' +import { PolicyChips } from '../shared/PolicyChips' interface Draft { displayName: string @@ -25,6 +27,7 @@ function formatTtl(seconds: number): string { export function TokensTab({ client }: { client: BaoClient }) { const qc = useQueryClient() + const confirm = useConfirm() const { tokenInfo } = useSession() const tokens = useQuery({ queryKey: ['tokens'], queryFn: () => listTokens(client) }) const [draft, setDraft] = useState(null) @@ -68,13 +71,15 @@ export function TokensTab({ client }: { client: BaoClient }) {

Copy this token now. It will not be shown again.

- {created.token}{' '} - {' '} - + {created.token} +
+ + +
)} @@ -98,7 +103,9 @@ export function TokensTab({ client }: { client: BaoClient }) { {t.display_name || '—'} {isSelf ? ' (you)' : ''} -
+ - +
PathCapabilitiesSecretCan
- {g.path} + {row.display} + {row.wildcard && everything inside} + + {g.capabilities.join(', ')} diff --git a/src/features/graph/Details.tsx b/src/features/graph/Details.tsx index bf6ccd3..381cd5e 100644 --- a/src/features/graph/Details.tsx +++ b/src/features/graph/Details.tsx @@ -4,6 +4,7 @@ import { revokeAccess } from '../../api/grants' import type { AccessGraph, GraphEdge, GraphNode, PolicyInput } from '../../model/graph' import { parseManagedPolicy, type GrantTarget } from '../../model/managed' import { CapabilityChips } from '../shared/CapabilityChips' +import { useConfirm } from '../shared/useConfirm' export type Selection = { kind: 'node'; id: string } | { kind: 'edge'; id: string } @@ -147,6 +148,7 @@ function NodeDetails({ node, full, policies }: { node: GraphNode; full: AccessGr function EdgeDetails({ client, edge, full, policies, onRevoked }: { client: BaoClient; edge: GraphEdge; full: AccessGraph } & Pick) { const qc = useQueryClient() + const confirm = useConfirm() const from = nodeById(full, edge.source) const to = nodeById(full, edge.target) const isGrant = from?.type === 'policy' && to?.type === 'path' @@ -186,10 +188,14 @@ function EdgeDetails({ client, edge, full, policies, onRevoked }: { client: BaoC
{e.name}{e.aliases.map((a) => a.name).join(', ') || '—'}{e.policies.join(', ') || '—'} + a.name)} /> + + + {' '} + {' '} + @@ -107,10 +117,10 @@ export function EntitiesTab({ client }: { client: BaoClient }) { setDraft({ ...draft, policies })} /> {save.error &&

{save.error.message}

} -
+
{' '} + @@ -121,7 +131,13 @@ export function EntitiesTab({ client }: { client: BaoClient }) { {draft.entity.aliases.map((a) => (
{a.name}{' '} -
diff --git a/src/features/identities/GroupsTab.tsx b/src/features/identities/GroupsTab.tsx index 8852d28..fe6028c 100644 --- a/src/features/identities/GroupsTab.tsx +++ b/src/features/identities/GroupsTab.tsx @@ -5,6 +5,8 @@ import { deleteGroup, listEntities, listGroups, saveGroup } from '../../api/iden import { AccessEditor } from '../access/AccessEditor' import { ListState } from '../shared/ListState' import { PolicyPicker } from '../shared/PolicyPicker' +import { useConfirm } from '../shared/useConfirm' +import { NameChips, PolicyChips } from '../shared/PolicyChips' interface Draft { name: string @@ -15,6 +17,7 @@ interface Draft { export function GroupsTab({ client }: { client: BaoClient }) { const qc = useQueryClient() + const confirm = useConfirm() const groups = useQuery({ queryKey: ['groups'], queryFn: () => listGroups(client) }) const entities = useQuery({ queryKey: ['entities'], queryFn: () => listEntities(client) }) const [draft, setDraft] = useState(null) @@ -54,20 +57,26 @@ export function GroupsTab({ client }: { client: BaoClient }) { {groups.data?.map((g) => (
{g.name}{g.member_entity_ids.map(nameOf).join(', ') || '—'}{g.policies.join(', ') || '—'} + + + + {' '} + {' '} - + {t.policies.join(', ') || '—'} + + {formatTtl(t.ttl)} {t.accessor.slice(0, 8)}… @@ -109,10 +116,14 @@ export function TokensTab({ client }: { client: BaoClient }) { aria-label={`Revoke ${t.display_name || t.accessor}`} disabled={isSelf} title={isSelf ? 'This is the token you are signed in with' : undefined} - onClick={() => - window.confirm(`Revoke token "${t.display_name || t.accessor}"? Tokens created from it are revoked too.`) && - revoke.mutate(t.accessor) - } + onClick={async () => { + const ok = await confirm({ + title: `Revoke token “${t.display_name || t.accessor}”?`, + message: 'Tokens created from it are revoked too.', + confirmLabel: 'Revoke', + }) + if (ok) revoke.mutate(t.accessor) + }} > Revoke @@ -130,7 +141,8 @@ export function TokensTab({ client }: { client: BaoClient }) { )} {draft && ( -
+ +

New token

setDraft({ ...draft, policies })} /> + {draft.policies.length === 0 && ( +

+ No policies selected: OpenBao gives the new token the same policies as yours + {tokenInfo?.policies.length ? ` (${tokenInfo.policies.join(', ')})` : ''}. +

+ )} {create.error &&

{create.error.message}

} -
+
{' '} + diff --git a/src/features/identities/UsersTab.tsx b/src/features/identities/UsersTab.tsx index a666d7f..b8aabfd 100644 --- a/src/features/identities/UsersTab.tsx +++ b/src/features/identities/UsersTab.tsx @@ -5,6 +5,8 @@ import { deleteUser, listUsers, saveUser } from '../../api/identities' import { AccessEditor } from '../access/AccessEditor' import { ListState } from '../shared/ListState' import { PolicyPicker } from '../shared/PolicyPicker' +import { useConfirm } from '../shared/useConfirm' +import { PolicyChips } from '../shared/PolicyChips' interface Draft { name: string @@ -18,6 +20,7 @@ const empty: Draft = { name: '', password: '', policies: [], ttl: '', isNew: tru export function UsersTab({ client }: { client: BaoClient }) { const qc = useQueryClient() + const confirm = useConfirm() const users = useQuery({ queryKey: ['users'], queryFn: () => listUsers(client) }) const [draft, setDraft] = useState(null) const [accessFor, setAccessFor] = useState(null) @@ -55,18 +58,22 @@ export function UsersTab({ client }: { client: BaoClient }) { {users.data?.map((u) => (
{u.name}{u.policies.join(', ') || '—'} + + {' '} + {' '} + @@ -105,10 +112,10 @@ export function UsersTab({ client }: { client: BaoClient }) { setDraft({ ...draft, policies })} /> {save.error &&

{save.error.message}

} -
+
{' '} + diff --git a/src/features/shared/ConfirmProvider.test.tsx b/src/features/shared/ConfirmProvider.test.tsx new file mode 100644 index 0000000..a634ac9 --- /dev/null +++ b/src/features/shared/ConfirmProvider.test.tsx @@ -0,0 +1,61 @@ +import { fireEvent, render, screen } from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import { useState } from 'react' +import { expect, test } from 'vitest' +import { ConfirmProvider } from './ConfirmProvider' +import { useConfirm } from './useConfirm' + +function Trigger() { + const confirm = useConfirm() + const [answer, setAnswer] = useState('none') + return ( + <> + + {answer} + + ) +} + +function setup() { + render( + + + , + ) + return userEvent.setup() +} + +test('shows the question and resolves true on confirm', async () => { + const user = setup() + await user.click(screen.getByRole('button', { name: 'ask' })) + const dialog = await screen.findByRole('dialog', { name: 'Delete user “alice”?' }) + expect(dialog).toHaveTextContent('This cannot be undone.') + await user.click(screen.getByRole('button', { name: 'Delete' })) + expect(await screen.findByText('yes')).toBeInTheDocument() + expect(screen.queryByRole('dialog')).not.toBeInTheDocument() +}) + +test('resolves false on cancel, and Cancel has focus first', async () => { + const user = setup() + await user.click(screen.getByRole('button', { name: 'ask' })) + expect(await screen.findByRole('button', { name: 'Cancel' })).toHaveFocus() + await user.click(screen.getByRole('button', { name: 'Cancel' })) + expect(await screen.findByText('no')).toBeInTheDocument() +}) + +test('resolves false when the dialog is cancelled', async () => { + const user = setup() + await user.click(screen.getByRole('button', { name: 'ask' })) + // Browsers fire "cancel" on a modal dialog for Escape; jsdom does not, so send it directly. + fireEvent(await screen.findByRole('dialog'), new Event('cancel', { cancelable: true })) + expect(await screen.findByText('no')).toBeInTheDocument() +}) diff --git a/src/features/shared/ConfirmProvider.tsx b/src/features/shared/ConfirmProvider.tsx new file mode 100644 index 0000000..ffd1329 --- /dev/null +++ b/src/features/shared/ConfirmProvider.tsx @@ -0,0 +1,59 @@ +import { useCallback, useEffect, useRef, useState, type MouseEvent, type ReactNode } from 'react' +import { ConfirmContext, type Confirm, type ConfirmOptions } from './useConfirm' + +interface Pending { + options: ConfirmOptions + resolve: (ok: boolean) => void +} + +/** Renders one modal confirmation dialog for the whole app; open it with useConfirm(). */ +export function ConfirmProvider({ children }: { children: ReactNode }) { + const [pending, setPending] = useState(null) + const dialog = useRef(null) + + const confirm = useCallback((options) => new Promise((resolve) => setPending({ options, resolve })), []) + + useEffect(() => { + const el = dialog.current + if (!pending || !el) return + // showModal gives focus trapping, Escape and an inert page; fall back to a plain open dialog without it. + if (typeof el.showModal === 'function') el.showModal() + else el.setAttribute('open', '') + }, [pending]) + + function settle(ok: boolean) { + pending?.resolve(ok) + setPending(null) + } + + return ( + + {children} + {pending && ( + { + e.preventDefault() + settle(false) + }} + // A click on the backdrop lands on the dialog element itself, not on its content. + onClick={(e: MouseEvent) => e.target === e.currentTarget && settle(false)} + > +

{pending.options.title}

+ {pending.options.message &&

{pending.options.message}

} +
+ + +
+
+ )} +
+ ) +} diff --git a/src/features/shared/PolicyChips.tsx b/src/features/shared/PolicyChips.tsx new file mode 100644 index 0000000..56ee6ee --- /dev/null +++ b/src/features/shared/PolicyChips.tsx @@ -0,0 +1,31 @@ +import { isManagedPolicy } from '../../model/graph' + +function Empty() { + return None +} + +/** Policy names as chips; the ones EnvBao manages are tinted. */ +export function PolicyChips({ policies }: { policies: readonly string[] }) { + if (policies.length === 0) return + return ( +
    + {policies.map((p) => ( +
  • + {p} +
  • + ))} +
+ ) +} + +/** Plain names (aliases, members) as neutral chips. */ +export function NameChips({ names }: { names: readonly string[] }) { + if (names.length === 0) return + return ( +
    + {names.map((n) => ( +
  • {n}
  • + ))} +
+ ) +} diff --git a/src/features/shared/PolicyPicker.tsx b/src/features/shared/PolicyPicker.tsx index cc882bd..62ef087 100644 --- a/src/features/shared/PolicyPicker.tsx +++ b/src/features/shared/PolicyPicker.tsx @@ -13,7 +13,7 @@ export function PolicyPicker({ client, value, onChange }: Props) { // Keep policies that are attached but no longer exist selectable, so editing doesn't drop them silently. const names = [...new Set([...(data ?? []), ...value])].filter((n) => n !== 'root').sort() return ( -
+
Policies {error &&

Could not load policies: {error.message}

} {names.map((n) => ( diff --git a/src/features/shared/useConfirm.ts b/src/features/shared/useConfirm.ts new file mode 100644 index 0000000..2f8dea9 --- /dev/null +++ b/src/features/shared/useConfirm.ts @@ -0,0 +1,18 @@ +import { createContext, useContext } from 'react' + +export interface ConfirmOptions { + title: string + message?: string + /** Label of the confirming button, e.g. "Delete". */ + confirmLabel: string +} + +export type Confirm = (options: ConfirmOptions) => Promise + +export const ConfirmContext = createContext(null) + +/** Ask before a destructive action. Falls back to the browser's confirm() when no provider is mounted. */ +export function useConfirm(): Confirm { + const confirm = useContext(ConfirmContext) + return confirm ?? (async (o) => window.confirm(o.message ? `${o.title}\n${o.message}` : o.title)) +} diff --git a/src/index.css b/src/index.css index 9ac9da8..0a2327f 100644 --- a/src/index.css +++ b/src/index.css @@ -20,6 +20,7 @@ --accent-soft: light-dark(#e2f3f0, #12302c); --danger: light-dark(#b42318, #ff8a7a); --danger-soft: light-dark(#fdecea, #3a1815); + --danger-ink: light-dark(#ffffff, #2a0b07); --warn: light-dark(#8a5a00, #f2c14e); --warn-soft: light-dark(#fff4d6, #3a2d0c); @@ -898,7 +899,7 @@ td:last-child button + button { } @media (max-width: 48rem) { - .shell nav { + .shell > nav { flex-wrap: wrap; padding: 0 var(--s4); } @@ -906,10 +907,6 @@ td:last-child button + button { .shell main { padding: var(--s5) var(--s4); } - - .graph-layout { - grid-template-columns: 1fr; - } } @media (prefers-reduced-motion: reduce) { @@ -1158,3 +1155,164 @@ button.link:hover:not(:disabled) { grid-template-columns: minmax(0, 1fr); } } + +/* ---------- Identity forms ---------- */ + +form.wide { + max-width: 36rem; +} + +form > h3 { + margin: 0; +} + +.form-actions { + display: flex; + gap: var(--s2); +} + +/* Checkbox lists (policies, members) run in columns instead of one long stack. */ +.pick-grid { + grid-template-columns: repeat(auto-fill, minmax(11rem, 1fr)); +} + +.pick-grid legend, +.pick-grid > p { + grid-column: 1 / -1; +} + +form .note-warn { + margin: 0; +} + +button.primary { + background: var(--accent); + border-color: var(--accent); + color: var(--accent-ink); +} + +button.primary:hover:not(:disabled) { + background: var(--accent); + border-color: var(--accent); + filter: brightness(1.08); +} + +/* The one-time token: large, selectable, impossible to mistake for table content. */ +.secret-once p { + margin: 0 0 var(--s3); +} + +.token-value { + display: block; + margin-bottom: var(--s3); + padding: var(--s3) var(--s4); + background: var(--surface); + border: 1px solid var(--warn); + border-radius: var(--radius); + font-size: var(--text); + overflow-wrap: anywhere; + user-select: all; +} + +/* ---------- Narrow screens ---------- */ + +@media (max-width: 60rem) { + .graph-layout { + grid-template-columns: minmax(0, 1fr); + } + + .graph-canvas { + height: 60vh; + } + + .graph-details { + max-height: none; + } +} + +@media (max-width: 40rem) { + /* Wide tables scroll sideways inside themselves rather than widening the page. */ + table { + display: block; + overflow-x: auto; + } + + .shell > nav .whoami { + display: none; + } + + .graph-toolbar label:not(.check), + .graph-toolbar input:not([type='checkbox']) { + width: 100%; + } + + .graph-toolbar button { + margin-left: 0; + } + + .graph-legend .grow { + margin-left: 0; + } + + .access-head, + .connection-head { + flex-wrap: wrap; + } +} + +/* ---------- Confirm dialog ---------- */ + +.confirm-dialog { + width: min(28rem, calc(100% - 2rem)); + padding: var(--s5); + background: var(--surface); + color: var(--ink); + border: 1px solid var(--line-strong); + border-radius: var(--radius); + box-shadow: 0 12px 40px rgb(0 0 0 / 0.35); +} + +.confirm-dialog::backdrop { + background: rgb(0 0 0 / 0.55); +} + +.confirm-dialog h2 { + margin: 0 0 var(--s2); + font-size: var(--text-lg); +} + +.confirm-dialog p { + margin: 0 0 var(--s5); + color: var(--ink-soft); +} + +.confirm-actions { + display: flex; + justify-content: flex-end; + gap: var(--s2); +} + +button.danger-solid { + background: var(--danger); + border-color: var(--danger); + color: var(--danger-ink); +} + +button.danger-solid:hover:not(:disabled) { + background: var(--danger); + border-color: var(--danger); + filter: brightness(1.08); +} + +/* Policy and name chips in tables: neutral, with EnvBao-managed policies tinted. */ +.chips.plain li { + background: var(--surface-sunken); + border: 1px solid var(--line); + color: var(--ink-soft); +} + +.chips.plain li.managed { + background: var(--accent-soft); + border-color: transparent; + color: var(--accent); +} diff --git a/src/model/grantRows.test.ts b/src/model/grantRows.test.ts new file mode 100644 index 0000000..aac8e5e --- /dev/null +++ b/src/model/grantRows.test.ts @@ -0,0 +1,41 @@ +import { expect, test } from 'vitest' +import { groupGrants } from './grantRows' + +test('folds a KV data rule and its metadata rule into one row', () => { + const rows = groupGrants( + [ + { path: 'secret/data/team-a/*', capabilities: ['read', 'update'] }, + { path: 'secret/metadata/team-a/*', capabilities: ['list'] }, + ], + ['secret/'], + ) + expect(rows).toEqual([ + { + display: 'secret/team-a/*', + wildcard: true, + capabilities: ['read', 'update', 'list'], + paths: ['secret/data/team-a/*', 'secret/metadata/team-a/*'], + }, + ]) +}) + +test('a secret with only a data rule is one row', () => { + const [row] = groupGrants([{ path: 'secret/data/app/db', capabilities: ['read'] }], ['secret/']) + expect(row).toMatchObject({ display: 'secret/app/db', wildcard: false, paths: ['secret/data/app/db'] }) +}) + +test('paths outside a known KV mount keep their raw path', () => { + const [row] = groupGrants([{ path: 'sys/health', capabilities: ['read'] }], ['secret/']) + expect(row).toMatchObject({ display: 'sys/health', paths: ['sys/health'] }) +}) + +test('keeps different secrets and mounts apart', () => { + const rows = groupGrants( + [ + { path: 'secret/data/a', capabilities: ['read'] }, + { path: 'kv/data/a', capabilities: ['read'] }, + ], + ['secret/', 'kv/'], + ) + expect(rows.map((r) => r.display)).toEqual(['secret/a', 'kv/a']) +}) diff --git a/src/model/grantRows.ts b/src/model/grantRows.ts new file mode 100644 index 0000000..7a569dd --- /dev/null +++ b/src/model/grantRows.ts @@ -0,0 +1,35 @@ +import type { Grant } from './managed' +import { CAPABILITIES, type Capability } from './policy' + +/** One line in the "granted by EnvBao" list: a secret path with everything granted on it. */ +export interface GrantRow { + /** Where the grant applies as a user thinks of it, e.g. "secret/app/*" (not "secret/data/app/*"). */ + display: string + wildcard: boolean + capabilities: Capability[] + /** The policy paths behind this row; revoking the row removes all of them. */ + paths: string[] +} + +/** + * KV v2 grants are stored as a `data/` rule and a `metadata/` rule per secret. Fold each pair into one row + * keyed by the secret's own path; grants outside a known KV mount keep their raw path. + */ +export function groupGrants(grants: Grant[], mounts: string[]): GrantRow[] { + const rows = new Map() + for (const g of grants) { + let display = g.path + for (const m of mounts) { + const mount = m.endsWith('/') ? m : `${m}/` + for (const kind of ['data', 'metadata']) { + const prefix = `${mount}${kind}/` + if (g.path.startsWith(prefix)) display = mount + g.path.slice(prefix.length) + } + } + const row = rows.get(display) ?? { display, wildcard: display.endsWith('*'), capabilities: [], paths: [] } + row.capabilities = CAPABILITIES.filter((c) => row.capabilities.includes(c) || g.capabilities.includes(c)) + row.paths.push(g.path) + rows.set(display, row) + } + return [...rows.values()] +}