feat: customizable permissions, per-item Ops ACLs, area-lead roles

Migration 023 (folded into schema.sql section 15). ADDITIVE and
backward compatible: with no permission/ACL rows the app behaves
exactly as before.

Schema:
- space_role_permissions (space_id, subject, permission); ops_acl
  (space_id, entity_type secret|kb|process|area_lead, entity_id,
  role). Full RLS, writes admin/board.
- user_effective_roles(uid,sid): built-in role + custom-role slugs +
  area_lead:<id> for areas the member leads. SECURITY DEFINER.
- user_has_permission(uid,sid,perm): admin implicit-all else a grant
  via an effective role. SECURITY DEFINER.
- secrets/knowledge_base SELECT rewritten as
  `exact existing rule OR ops_acl match` (only widens; zero change
  with no ACL rows). Seed + backfill default role permissions.

Area-lead roles reuse the existing area_leads table rather than
duplicating the concept: a row is a role, lead_id NULL = Vacant,
assigning sets lead_id, the member then holds area_lead:<id>.

App:
- lib/permissions-catalog.ts (codes + per-role defaults + guardrails),
  Zod schemas, lib/actions/permissions.ts (setRolePermissions,
  setOpsAcl, createAreaLeadRole, assign/unassign/delete).
- Customize gains Permissions (role x permission matrix, admin shown
  implicit-all/locked) and Area leads (create/Vacant/assign) panels,
  modular under customize/panels/. Reusable
  components/ops/ops-acl-editor.tsx wired into the Secrets list.

Audit-found latent fixes:
- revealSecret errors on encrypted-but-no-ciphertext corruption
  instead of silently returning the stale plaintext column.
- upsertAreaLead rejects null/empty area_code (NULLs are distinct in
  unique constraints; allowed duplicate rows).

types/database.ts: added the two new tables. 271/271 tests pass,
build clean. KB-modal ACL wiring + members-row shortcut deferred and
tracked in HANDOFF.
This commit is contained in:
Moheeb Zara
2026-05-15 17:15:14 -07:00
parent 109947552f
commit 9447b5ee80
19 changed files with 1192 additions and 29 deletions
+64 -27
View File
@@ -7,6 +7,7 @@ import ReactMarkdown from 'react-markdown'
import remarkGfm from 'remark-gfm'
import { createKbEntry, updateKbEntry, deleteKbEntry } from '@/lib/actions'
import { revealSecret, deleteSecret } from '@/lib/actions/secrets'
import { OpsAclEditor } from '@/components/ops/ops-acl-editor'
import { createClient } from '@/lib/supabase/client'
import { toast } from 'sonner'
import type { Tables, TablesInsert } from '@/types/database'
@@ -22,6 +23,9 @@ interface Props {
areaLeads: AreaLead[]
secrets: Secret[]
canSeeSecrets: boolean
canManageAcl?: boolean
aclRoleOptions?: { value: string; label: string }[]
aclByEntity?: Record<string, string[]>
}
type Tab = 'kb' | 'processes' | 'secrets' | 'area-leads'
@@ -342,10 +346,17 @@ function AreaLeadModal({
}
// ─── Secret Row (reveal on click) ─────────────────────────────────────────────
function SecretRow({ secret, onDelete }: { secret: Secret; onDelete: (id: string) => void }) {
function SecretRow({ secret, onDelete, canManageAcl, aclRoleOptions, aclInitial }: {
secret: Secret
onDelete: (id: string) => void
canManageAcl?: boolean
aclRoleOptions?: { value: string; label: string }[]
aclInitial?: string[]
}) {
const [revealed, setRevealed] = useState(false)
const [value, setValue] = useState<string | null>(null)
const [loading, setLoading] = useState(false)
const [showAcl, setShowAcl] = useState(false)
async function reveal() {
if (revealed) { setRevealed(false); setValue(null); return }
@@ -366,31 +377,50 @@ function SecretRow({ secret, onDelete }: { secret: Secret; onDelete: (id: string
}
return (
<div className="flex items-center gap-3 px-4 py-3">
<div className="w-8 h-8 rounded bg-amber-50 border border-amber-200 flex items-center justify-center flex-shrink-0">
<Lock className="w-4 h-4 text-amber-500" />
</div>
<div className="flex-1 min-w-0">
<p className="font-sans text-sm font-medium text-foreground">{secret.title}</p>
{secret.area && <p className="font-mono text-[10px] text-muted-foreground">{secret.area}</p>}
{revealed && value && (
<p className="font-mono text-xs text-foreground bg-muted px-2 py-1 rounded mt-1 break-all">{value}</p>
)}
</div>
<div className="flex items-center gap-1.5 flex-shrink-0">
<button
onClick={reveal}
disabled={loading}
className="flex items-center gap-1 font-mono text-[10px] border border-border px-2 py-0.5 rounded hover:border-primary hover:text-primary transition"
title={revealed ? 'Hide' : 'Reveal'}
>
{loading ? '...' : revealed ? <EyeOff className="w-3 h-3" /> : <Eye className="w-3 h-3" />}
{revealed ? 'Hide' : 'Reveal'}
</button>
<button onClick={handleDelete} className="text-muted-foreground hover:text-red-500 transition p-1" title="Delete">
<Trash2 className="w-3.5 h-3.5" />
</button>
<div className="px-4 py-3">
<div className="flex items-center gap-3">
<div className="w-8 h-8 rounded bg-amber-50 border border-amber-200 flex items-center justify-center flex-shrink-0">
<Lock className="w-4 h-4 text-amber-500" />
</div>
<div className="flex-1 min-w-0">
<p className="font-sans text-sm font-medium text-foreground">{secret.title}</p>
{secret.area && <p className="font-mono text-[10px] text-muted-foreground">{secret.area}</p>}
{revealed && value && (
<p className="font-mono text-xs text-foreground bg-muted px-2 py-1 rounded mt-1 break-all">{value}</p>
)}
</div>
<div className="flex items-center gap-1.5 flex-shrink-0">
{canManageAcl && (
<button
onClick={() => setShowAcl(v => !v)}
className="font-mono text-[10px] border border-border px-2 py-0.5 rounded hover:border-primary hover:text-primary transition"
title="Who can access this secret"
>
Access
</button>
)}
<button
onClick={reveal}
disabled={loading}
className="flex items-center gap-1 font-mono text-[10px] border border-border px-2 py-0.5 rounded hover:border-primary hover:text-primary transition"
title={revealed ? 'Hide' : 'Reveal'}
>
{loading ? '...' : revealed ? <EyeOff className="w-3 h-3" /> : <Eye className="w-3 h-3" />}
{revealed ? 'Hide' : 'Reveal'}
</button>
<button onClick={handleDelete} className="text-muted-foreground hover:text-red-500 transition p-1" title="Delete">
<Trash2 className="w-3.5 h-3.5" />
</button>
</div>
</div>
{showAcl && canManageAcl && (
<OpsAclEditor
entityType="secret"
entityId={secret.id}
options={aclRoleOptions ?? []}
initial={aclInitial ?? []}
/>
)}
</div>
)
}
@@ -504,7 +534,7 @@ function KbEntryRow({
}
// ─── Main Component ────────────────────────────────────────────────────────────
export function OpsClient({ member, spaceId, kbEntries: initial, areaLeads: initialLeads, secrets: initialSecrets, canSeeSecrets }: Props) {
export function OpsClient({ member, spaceId, kbEntries: initial, areaLeads: initialLeads, secrets: initialSecrets, canSeeSecrets, canManageAcl = false, aclRoleOptions = [], aclByEntity = {} }: Props) {
const router = useRouter()
const [activeTab, setActiveTab] = useState<Tab>('kb')
const [search, setSearch] = useState('')
@@ -722,7 +752,14 @@ export function OpsClient({ member, spaceId, kbEntries: initial, areaLeads: init
) : filteredSecrets.length > 0 ? (
<div className="bg-card rounded border border-border divide-y divide-border">
{filteredSecrets.map(s => (
<SecretRow key={s.id} secret={s} onDelete={id => setSecrets(prev => prev.filter(x => x.id !== id))} />
<SecretRow
key={s.id}
secret={s}
onDelete={id => setSecrets(prev => prev.filter(x => x.id !== id))}
canManageAcl={canManageAcl}
aclRoleOptions={aclRoleOptions}
aclInitial={aclByEntity[`secret:${s.id}`] ?? []}
/>
))}
</div>
) : (
+23 -1
View File
@@ -12,8 +12,9 @@ export default async function OpsPage() {
if (!member) return null
const canSeeSecrets = member.role === 'admin' || member.role === 'board'
const canManageAcl = member.role === 'admin' || member.role === 'board'
const [{ data: kbEntries }, { data: areaLeads }, secretsResult] = await Promise.all([
const [{ data: kbEntries }, { data: areaLeads }, secretsResult, { data: customRoles }, { data: acl }] = await Promise.all([
supabase.from('knowledge_base').select('*').eq('space_id', member.space_id).order('is_pinned', { ascending: false }).order('created_at', { ascending: false }),
supabase.from('area_leads').select('*').eq('space_id', member.space_id).order('area_name'),
canSeeSecrets
@@ -22,8 +23,26 @@ export default async function OpsPage() {
// through the revealSecret() server action.
? supabase.from('secrets').select('id, title, area, created_at, label, description, icon, space_id, created_by, updated_at, category, notes, encryption_version').eq('space_id', member.space_id)
: Promise.resolve({ data: [] as Tables<'secrets'>[] }),
supabase.from('space_custom_roles').select('slug, name').eq('space_id', member.space_id),
supabase.from('ops_acl').select('entity_type, entity_id, role').eq('space_id', member.space_id),
])
// Selectable ACL roles: built-in roles, custom-role slugs, and area-lead
// sentinels labelled by area name.
const aclRoleOptions = [
{ value: 'treasurer', label: 'treasurer' },
{ value: 'member', label: 'member' },
{ value: 'associate', label: 'associate' },
...((customRoles ?? []).map(c => ({ value: c.slug, label: c.name }))),
...((areaLeads ?? []).map(al => ({ value: `area_lead:${al.id}`, label: `${al.area_name} lead` }))),
]
const aclByEntity: Record<string, string[]> = {}
for (const row of acl ?? []) {
const k = `${row.entity_type}:${row.entity_id}`
;(aclByEntity[k] ??= []).push(row.role)
}
return (
<OpsClient
member={member as Tables<'space_members'>}
@@ -32,6 +51,9 @@ export default async function OpsPage() {
areaLeads={areaLeads ?? []}
secrets={secretsResult.data ?? []}
canSeeSecrets={canSeeSecrets}
canManageAcl={canManageAcl}
aclRoleOptions={aclRoleOptions}
aclByEntity={aclByEntity}
/>
)
}