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:
@@ -16,6 +16,13 @@ export async function upsertAreaLead(formData: {
|
||||
const v = parseInput(upsertAreaLeadSchema, formData)
|
||||
if (!v.ok) return { error: v.error }
|
||||
|
||||
// area_code is the (space_id, area_code) upsert conflict target. Postgres
|
||||
// treats NULLs as distinct in unique constraints, so a null/empty code
|
||||
// would let duplicate area-lead rows accumulate. Require it.
|
||||
if (!v.data.area_code || !v.data.area_code.trim()) {
|
||||
return { error: 'An area code is required.' }
|
||||
}
|
||||
|
||||
const supabase = await createClient()
|
||||
const auth = await requireMemberWithRole(supabase, ADMIN_ROLES, 'Admin access required')
|
||||
if (!auth.ok) return { error: auth.error }
|
||||
|
||||
@@ -41,3 +41,6 @@ export * from './invites'
|
||||
|
||||
// Configurable member onboarding
|
||||
export * from './onboarding'
|
||||
|
||||
// Customizable permissions, per-item Ops ACLs, area-lead roles
|
||||
export * from './permissions'
|
||||
|
||||
@@ -0,0 +1,197 @@
|
||||
'use server'
|
||||
|
||||
import { revalidatePath } from 'next/cache'
|
||||
import { createClient } from '@/lib/supabase/server'
|
||||
import { requireMemberWithRole, parseInput } from '@/lib/auth-helpers'
|
||||
import {
|
||||
setRolePermissionsSchema,
|
||||
setOpsAclSchema,
|
||||
createAreaLeadRoleSchema,
|
||||
assignAreaLeadSchema,
|
||||
uuidSchema,
|
||||
} from '@/lib/validations'
|
||||
import { isValidPermission } from '@/lib/permissions-catalog'
|
||||
|
||||
const PERM_ADMIN_ROLES = ['admin', 'board'] as const
|
||||
|
||||
// Replace the full permission set for one role/custom-role subject.
|
||||
export async function setRolePermissions(input: { subject: string; permissions: string[] }) {
|
||||
const v = parseInput(setRolePermissionsSchema, input)
|
||||
if (!v.ok) return { error: v.error }
|
||||
|
||||
const perms = v.data.permissions.filter(isValidPermission)
|
||||
|
||||
const supabase = await createClient()
|
||||
const auth = await requireMemberWithRole(supabase, PERM_ADMIN_ROLES, 'Admin or board access required')
|
||||
if (!auth.ok) return { error: auth.error }
|
||||
const { member } = auth
|
||||
|
||||
const del = await supabase
|
||||
.from('space_role_permissions')
|
||||
.delete()
|
||||
.eq('space_id', member.space_id)
|
||||
.eq('subject', v.data.subject)
|
||||
if (del.error) return { error: del.error.message }
|
||||
|
||||
if (perms.length > 0) {
|
||||
const ins = await supabase
|
||||
.from('space_role_permissions')
|
||||
.insert(perms.map(permission => ({ space_id: member.space_id, subject: v.data.subject, permission })))
|
||||
if (ins.error) return { error: ins.error.message }
|
||||
}
|
||||
|
||||
revalidatePath('/customize')
|
||||
return { success: true as const }
|
||||
}
|
||||
|
||||
// Replace the full ACL role list for one Ops item. Empty list => the item
|
||||
// falls back to its existing visibility rule (no ACL rows).
|
||||
export async function setOpsAcl(input: {
|
||||
entity_type: 'secret' | 'kb' | 'process' | 'area_lead'
|
||||
entity_id: string
|
||||
roles: string[]
|
||||
}) {
|
||||
const v = parseInput(setOpsAclSchema, input)
|
||||
if (!v.ok) return { error: v.error }
|
||||
|
||||
const supabase = await createClient()
|
||||
const auth = await requireMemberWithRole(supabase, PERM_ADMIN_ROLES, 'Admin or board access required')
|
||||
if (!auth.ok) return { error: auth.error }
|
||||
const { member } = auth
|
||||
|
||||
const del = await supabase
|
||||
.from('ops_acl')
|
||||
.delete()
|
||||
.eq('space_id', member.space_id)
|
||||
.eq('entity_type', v.data.entity_type)
|
||||
.eq('entity_id', v.data.entity_id)
|
||||
if (del.error) return { error: del.error.message }
|
||||
|
||||
const roles = Array.from(new Set(v.data.roles.map(r => r.trim()).filter(Boolean)))
|
||||
if (roles.length > 0) {
|
||||
const ins = await supabase.from('ops_acl').insert(
|
||||
roles.map(role => ({
|
||||
space_id: member.space_id,
|
||||
entity_type: v.data.entity_type,
|
||||
entity_id: v.data.entity_id,
|
||||
role,
|
||||
})),
|
||||
)
|
||||
if (ins.error) return { error: ins.error.message }
|
||||
}
|
||||
|
||||
revalidatePath('/ops')
|
||||
return { success: true as const }
|
||||
}
|
||||
|
||||
// An area-lead role is an area_leads row. lead_id NULL renders as "Vacant".
|
||||
export async function createAreaLeadRole(input: { area_code: string; name: string }) {
|
||||
const v = parseInput(createAreaLeadRoleSchema, input)
|
||||
if (!v.ok) return { error: v.error }
|
||||
|
||||
const supabase = await createClient()
|
||||
const auth = await requireMemberWithRole(supabase, PERM_ADMIN_ROLES, 'Admin or board access required')
|
||||
if (!auth.ok) return { error: auth.error }
|
||||
const { member } = auth
|
||||
|
||||
const { data, error } = await supabase
|
||||
.from('area_leads')
|
||||
.insert({
|
||||
space_id: member.space_id,
|
||||
area_code: v.data.area_code,
|
||||
area_name: v.data.name,
|
||||
status: 'vacant',
|
||||
})
|
||||
.select('id, area_code, area_name, lead_id, lead_handle, status')
|
||||
.single()
|
||||
|
||||
if (error) return { error: error.message }
|
||||
revalidatePath('/customize')
|
||||
revalidatePath('/ops')
|
||||
return { data }
|
||||
}
|
||||
|
||||
export async function assignAreaLead(input: { area_lead_role_id: string; member_id: string }) {
|
||||
const v = parseInput(assignAreaLeadSchema, input)
|
||||
if (!v.ok) return { error: v.error }
|
||||
|
||||
const supabase = await createClient()
|
||||
const auth = await requireMemberWithRole(supabase, PERM_ADMIN_ROLES, 'Admin or board access required')
|
||||
if (!auth.ok) return { error: auth.error }
|
||||
const { member } = auth
|
||||
|
||||
const { data: target } = await supabase
|
||||
.from('space_members')
|
||||
.select('id, display_name, handle')
|
||||
.eq('id', v.data.member_id)
|
||||
.eq('space_id', member.space_id)
|
||||
.single()
|
||||
if (!target) return { error: 'Member not found in this space' }
|
||||
|
||||
const { error } = await supabase
|
||||
.from('area_leads')
|
||||
.update({
|
||||
lead_id: target.id,
|
||||
lead_handle: target.handle ?? target.display_name ?? null,
|
||||
status: 'active',
|
||||
updated_at: new Date().toISOString(),
|
||||
})
|
||||
.eq('id', v.data.area_lead_role_id)
|
||||
.eq('space_id', member.space_id)
|
||||
|
||||
if (error) return { error: error.message }
|
||||
revalidatePath('/customize')
|
||||
revalidatePath('/members')
|
||||
revalidatePath('/ops')
|
||||
return { success: true as const }
|
||||
}
|
||||
|
||||
export async function unassignAreaLead(areaLeadRoleId: string) {
|
||||
const idCheck = parseInput(uuidSchema, areaLeadRoleId)
|
||||
if (!idCheck.ok) return { error: 'Invalid role ID' }
|
||||
|
||||
const supabase = await createClient()
|
||||
const auth = await requireMemberWithRole(supabase, PERM_ADMIN_ROLES, 'Admin or board access required')
|
||||
if (!auth.ok) return { error: auth.error }
|
||||
const { member } = auth
|
||||
|
||||
const { error } = await supabase
|
||||
.from('area_leads')
|
||||
.update({ lead_id: null, lead_handle: null, status: 'vacant', updated_at: new Date().toISOString() })
|
||||
.eq('id', idCheck.data)
|
||||
.eq('space_id', member.space_id)
|
||||
|
||||
if (error) return { error: error.message }
|
||||
revalidatePath('/customize')
|
||||
revalidatePath('/members')
|
||||
revalidatePath('/ops')
|
||||
return { success: true as const }
|
||||
}
|
||||
|
||||
export async function deleteAreaLeadRole(areaLeadRoleId: string) {
|
||||
const idCheck = parseInput(uuidSchema, areaLeadRoleId)
|
||||
if (!idCheck.ok) return { error: 'Invalid role ID' }
|
||||
|
||||
const supabase = await createClient()
|
||||
const auth = await requireMemberWithRole(supabase, ['admin'], 'Admin access required')
|
||||
if (!auth.ok) return { error: auth.error }
|
||||
const { member } = auth
|
||||
|
||||
// Clear any ACL rows that referenced this area-lead sentinel first.
|
||||
await supabase
|
||||
.from('ops_acl')
|
||||
.delete()
|
||||
.eq('space_id', member.space_id)
|
||||
.eq('role', `area_lead:${idCheck.data}`)
|
||||
|
||||
const { error } = await supabase
|
||||
.from('area_leads')
|
||||
.delete()
|
||||
.eq('id', idCheck.data)
|
||||
.eq('space_id', member.space_id)
|
||||
|
||||
if (error) return { error: error.message }
|
||||
revalidatePath('/customize')
|
||||
revalidatePath('/ops')
|
||||
return { success: true as const }
|
||||
}
|
||||
@@ -124,6 +124,14 @@ export async function revealSecret(secretId: string) {
|
||||
|
||||
if (error || !data) return { error: error?.message ?? 'Not found' }
|
||||
|
||||
// A row marked encrypted (version > 0) MUST have ciphertext. If it does
|
||||
// not, the row is corrupt: do not silently fall back to the (empty/stale)
|
||||
// plaintext column, which would either leak nothing useful or mask data
|
||||
// loss. Surface it instead.
|
||||
if ((data.encryption_version ?? 0) > 0 && !data.encrypted_value) {
|
||||
return { error: 'This secret is marked encrypted but has no ciphertext. It may be corrupted; re-enter it.' }
|
||||
}
|
||||
|
||||
let plaintext: string
|
||||
try {
|
||||
if (data.encryption_version === 1 && data.encrypted_value) {
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
// Fixed catalog of permission codes. This is app-owned data, not a table:
|
||||
// the set of capabilities is part of the product, while which roles hold
|
||||
// which permissions is per-space (space_role_permissions).
|
||||
//
|
||||
// Important: this layer is ADDITIVE. Existing role-based RLS and server-action
|
||||
// role checks stay in force. A permission grant can only widen what a role can
|
||||
// do through the surfaces that consult it (the Ops ACL and the Customize
|
||||
// permissions UI); it never overrides the database RLS that protects tenant
|
||||
// isolation. `admin` implicitly holds every permission and can never be
|
||||
// locked out.
|
||||
|
||||
export const PERMISSIONS = [
|
||||
{ code: 'ops.kb.read', group: 'Ops', label: 'Read knowledge base' },
|
||||
{ code: 'ops.kb.write', group: 'Ops', label: 'Write knowledge base' },
|
||||
{ code: 'ops.process.read', group: 'Ops', label: 'Read processes' },
|
||||
{ code: 'ops.process.write', group: 'Ops', label: 'Write processes' },
|
||||
{ code: 'ops.secrets.read', group: 'Ops', label: 'Reveal secrets' },
|
||||
{ code: 'ops.secrets.write', group: 'Ops', label: 'Manage secrets' },
|
||||
{ code: 'ops.arealeads.manage', group: 'Ops', label: 'Manage area leads' },
|
||||
{ code: 'members.manage', group: 'People', label: 'Manage members' },
|
||||
{ code: 'payments.manage', group: 'Finance', label: 'Manage payments' },
|
||||
{ code: 'governance.manage', group: 'Governance', label: 'Manage proposals, incidents, policies' },
|
||||
{ code: 'forum.moderate', group: 'Community', label: 'Moderate forum and comments' },
|
||||
{ code: 'customize.manage', group: 'Admin', label: 'Customize roles, tiers, areas, invites, onboarding' },
|
||||
{ code: 'settings.manage', group: 'Admin', label: 'Space settings, integrations, webhooks' },
|
||||
] as const
|
||||
|
||||
export type PermissionCode = (typeof PERMISSIONS)[number]['code']
|
||||
|
||||
export const PERMISSION_CODES: readonly string[] = PERMISSIONS.map(p => p.code)
|
||||
|
||||
export const PERMISSION_GROUPS: string[] = Array.from(new Set(PERMISSIONS.map(p => p.group)))
|
||||
|
||||
// Built-in role defaults seeded per space. `admin` is intentionally absent:
|
||||
// it holds everything implicitly and is never stored, so it cannot be
|
||||
// accidentally revoked.
|
||||
export const DEFAULT_ROLE_PERMISSIONS: Record<string, PermissionCode[]> = {
|
||||
board: [
|
||||
'ops.kb.read', 'ops.kb.write', 'ops.process.read', 'ops.process.write',
|
||||
'ops.secrets.read', 'ops.secrets.write', 'ops.arealeads.manage',
|
||||
'members.manage', 'payments.manage', 'governance.manage',
|
||||
'forum.moderate', 'customize.manage', 'settings.manage',
|
||||
],
|
||||
treasurer: ['payments.manage', 'ops.kb.read', 'ops.process.read'],
|
||||
member: ['ops.kb.read', 'ops.process.read'],
|
||||
associate: ['ops.kb.read'],
|
||||
}
|
||||
|
||||
export function isValidPermission(code: string): code is PermissionCode {
|
||||
return PERMISSION_CODES.includes(code)
|
||||
}
|
||||
@@ -486,6 +486,42 @@ export const createChannelSchema = z.object({
|
||||
channel_type: z.enum(['general', 'area', 'ops', 'project']).default('general'),
|
||||
})
|
||||
|
||||
// ─── Permissions, Ops ACLs, area-lead roles ──────────────────────────────────
|
||||
|
||||
// A grant subject is a built-in role or a custom-role slug.
|
||||
const roleSubject = z.string().min(1).max(50).regex(/^[a-z0-9][a-z0-9_:-]{0,49}$/, 'Invalid role')
|
||||
|
||||
export const setRolePermissionsSchema = z.object({
|
||||
subject: roleSubject,
|
||||
permissions: z.array(z.string().min(1).max(60)).max(64),
|
||||
})
|
||||
|
||||
export const opsEntityTypeSchema = z.enum(['secret', 'kb', 'process', 'area_lead'])
|
||||
|
||||
// The UI sends the full desired role list for one item; the server replaces.
|
||||
// An empty list means "fall back to the item's existing visibility rule".
|
||||
export const setOpsAclSchema = z.object({
|
||||
entity_type: opsEntityTypeSchema,
|
||||
entity_id: z.string().uuid('Invalid entity ID'),
|
||||
roles: z.array(z.string().min(1).max(64)).max(64),
|
||||
})
|
||||
|
||||
export const createAreaLeadRoleSchema = z.object({
|
||||
area_code: z.string().min(1).max(60).regex(/^[a-z0-9][a-z0-9_-]{0,59}$/, 'Invalid area code'),
|
||||
name: z.string().min(1).max(100),
|
||||
color: z.string().max(20).optional().nullable(),
|
||||
})
|
||||
|
||||
export const updateAreaLeadRoleSchema = z.object({
|
||||
name: z.string().min(1).max(100).optional(),
|
||||
color: z.string().max(20).optional().nullable(),
|
||||
})
|
||||
|
||||
export const assignAreaLeadSchema = z.object({
|
||||
area_lead_role_id: z.string().uuid('Invalid role ID'),
|
||||
member_id: z.string().uuid('Invalid member ID'),
|
||||
})
|
||||
|
||||
// ─── Generic ID schemas ──────────────────────────────────────────────────────
|
||||
|
||||
export const uuidSchema = z.string().uuid('Invalid ID format')
|
||||
|
||||
Reference in New Issue
Block a user