feat: forum, polymorphic comments, custom tiers, multi-invite, secrets encryption

Big feature batch driven by the super-audit findings and the user's
follow-up requests.

Schema migration 021 (folded into schema.sql Section 13):
- forum_threads + polymorphic comments table keyed on (entity_type,
  entity_id). Entity types: forum_thread, proposal, incident, policy.
  Trigger maintains forum_threads.comment_count and last_comment_at.
- space_tiers per-space with monthly_price_cents, billing_cadence,
  is_system, sort_order. Trigger seeds plus/basic/associate on every
  space INSERT and backfills existing spaces. space_members.tier_id FK
  added and backfilled from the legacy enum value.
- space_role_labels (rename/recolor built-in roles per space).
  space_custom_roles + space_member_custom_roles for non-privileged
  extra labels. RLS gates by admin/board.
- space_invites: multi-code invites with expires_at, max_uses,
  uses_count, is_enabled. Legacy spaces.invite_code backfilled as a
  permanent enabled invite.
- secrets.encrypted_value bytea + encryption_version. Secrets RLS
  tightened. New comms_channels INSERT policy: any member can create;
  default channels are protected from deletion.
- knowledge_base.render_markdown boolean (default true).

Secrets encryption-at-rest:
- AES-256-GCM in lib/secrets/crypto.ts. Master key from
  SECRETS_ENCRYPTION_KEY env (64 hex chars).
- New revealSecret(id) server action: only path to plaintext, writes
  secret.revealed to activity_log.
- /ops/page.tsx no longer selects value or encrypted_value on the list
  endpoint - the original screenshot bug where ciphertext was already
  in the page bundle before "Reveal" is fixed.

UI:
- /forum index, /forum/new, /forum/[id]. Pin/lock/delete actions for
  admin/board.
- CommentThread component embedded on /proposals/[id], /incidents/[id],
  /policies/[slug]. Markdown rendering via react-markdown + remark-gfm.
- /comms sidebar: inline "+ New channel" form.
- /ops KB: row click opens markdown-rendering viewer modal.
- /settings: new Tiers tab and Invites tab. Inline price edit and
  archive/delete on tiers; copy/enable/disable/delete on invites.
- AtlasLogo replaces the terminal icon on the landing nav and footer.
  public/logo.svg wired as the favicon in app/layout.tsx metadata.
- Sidebar has a Forum nav link.

Server actions added:
- lib/actions/forum.ts, comms.ts, tiers.ts, roles.ts, invites.ts.
- lib/actions/secrets.ts rewritten with updateSecret + revealSecret.

Auth flow:
- joinSpace honors codes from space_invites first (enabled, expiry,
  use cap), falls back to legacy spaces.invite_code, increments
  uses_count on success.

Env:
- SECRETS_ENCRYPTION_KEY documented in .env.example and set on the
  Droplet's /opt/hackerspace-ops/.env.production.

README: live site link added (https://hackerspace.sh).

266/266 unit tests pass. Production build clean. Migration 021 will be
applied on the next deploy via /opt/hackerspace-ops/deploy.sh's
idempotent migration runner.
This commit is contained in:
Moheeb Zara
2026-05-14 17:47:52 -07:00
parent 8ad1ca44b7
commit de51000584
35 changed files with 2981 additions and 93 deletions
+89
View File
@@ -0,0 +1,89 @@
'use server'
import { revalidatePath } from 'next/cache'
import { createClient } from '@/lib/supabase/server'
import { requireMember, requireMemberWithRole, parseInput } from '@/lib/auth-helpers'
import { createChannelSchema, uuidSchema } from '@/lib/validations'
export async function createChannel(input: {
name: string
description?: string | null
channel_type?: 'general' | 'area' | 'ops' | 'project'
}) {
const v = parseInput(createChannelSchema, input)
if (!v.ok) return { error: v.error }
const supabase = await createClient()
const auth = await requireMember(supabase)
if (!auth.ok) return { error: auth.error }
const { member } = auth
const { data: { user } } = await supabase.auth.getUser()
if (!user) return { error: 'Not authenticated' }
// Uniqueness check: channel names must be unique within a space.
const { data: existing } = await supabase
.from('comms_channels')
.select('id')
.eq('space_id', member.space_id)
.eq('name', v.data.name)
.maybeSingle()
if (existing) return { error: `A channel named "${v.data.name}" already exists.` }
const { data, error } = await supabase
.from('comms_channels')
.insert({
space_id: member.space_id,
name: v.data.name,
description: v.data.description ?? null,
channel_type: v.data.channel_type ?? 'general',
created_by: user.id,
is_default: false,
})
.select('id')
.single()
if (error) return { error: error.message }
revalidatePath('/comms')
return { id: data.id }
}
export async function deleteChannel(channelId: string) {
const v = parseInput(uuidSchema, channelId)
if (!v.ok) return { error: 'Invalid channel ID' }
const supabase = await createClient()
const auth = await requireMember(supabase)
if (!auth.ok) return { error: auth.error }
// Default channels are protected at the RLS layer too.
const { error, count } = await supabase
.from('comms_channels')
.delete({ count: 'exact' })
.eq('id', v.data)
if (error) return { error: error.message }
if (count === 0) return { error: 'Cannot delete this channel' }
revalidatePath('/comms')
return { success: true as const }
}
export async function renameChannel(channelId: string, name: string, description?: string | null) {
const idCheck = parseInput(uuidSchema, channelId)
if (!idCheck.ok) return { error: 'Invalid channel ID' }
const v = parseInput(createChannelSchema, { name, description })
if (!v.ok) return { error: v.error }
const supabase = await createClient()
const auth = await requireMember(supabase)
if (!auth.ok) return { error: auth.error }
const { error } = await supabase
.from('comms_channels')
.update({ name: v.data.name, description: v.data.description ?? null })
.eq('id', idCheck.data)
if (error) return { error: error.message }
revalidatePath('/comms')
return { success: true as const }
}
+193
View File
@@ -0,0 +1,193 @@
'use server'
import { revalidatePath } from 'next/cache'
import { createClient } from '@/lib/supabase/server'
import { requireMember, requireMemberWithRole, parseInput } from '@/lib/auth-helpers'
import {
createForumThreadSchema,
updateForumThreadSchema,
createCommentSchema,
updateCommentSchema,
uuidSchema,
} from '@/lib/validations'
export async function createForumThread(input: {
title: string
body?: string
category?: string
}) {
const v = parseInput(createForumThreadSchema, input)
if (!v.ok) return { error: v.error }
const supabase = await createClient()
const auth = await requireMember(supabase)
if (!auth.ok) return { error: auth.error }
const { member } = auth
const { data, error } = await supabase
.from('forum_threads')
.insert({
space_id: member.space_id,
author_id: member.id,
title: v.data.title,
body: v.data.body ?? null,
category: v.data.category ?? 'general',
})
.select('id')
.single()
if (error) return { error: error.message }
revalidatePath('/forum')
return { id: data.id }
}
export async function updateForumThread(threadId: string, updates: {
title?: string
body?: string | null
category?: string
pinned?: boolean
locked?: boolean
}) {
const idCheck = parseInput(uuidSchema, threadId)
if (!idCheck.ok) return { error: 'Invalid thread ID' }
const v = parseInput(updateForumThreadSchema, updates)
if (!v.ok) return { error: v.error }
const supabase = await createClient()
const auth = await requireMember(supabase)
if (!auth.ok) return { error: auth.error }
// Pinning/locking is moderator-only (admin/board). The RLS UPDATE policy
// additionally requires the actor to be the author or admin/board, so a
// non-author cannot edit a thread regardless of this guard.
const wantsMod = v.data.pinned !== undefined || v.data.locked !== undefined
if (wantsMod) {
const modAuth = await requireMemberWithRole(supabase, ['admin', 'board'], 'Admin or board access required')
if (!modAuth.ok) return { error: modAuth.error }
}
const patch: Record<string, unknown> = {}
if (v.data.title !== undefined) patch.title = v.data.title
if (v.data.body !== undefined) patch.body = v.data.body
if (v.data.category !== undefined) patch.category = v.data.category
if (v.data.pinned !== undefined) patch.pinned = v.data.pinned
if (v.data.locked !== undefined) patch.locked = v.data.locked
const { error } = await supabase.from('forum_threads').update(patch).eq('id', idCheck.data)
if (error) return { error: error.message }
revalidatePath('/forum')
revalidatePath(`/forum/${idCheck.data}`)
return { success: true as const }
}
export async function deleteForumThread(threadId: string) {
const v = parseInput(uuidSchema, threadId)
if (!v.ok) return { error: 'Invalid thread ID' }
const supabase = await createClient()
const auth = await requireMember(supabase)
if (!auth.ok) return { error: auth.error }
// RLS DELETE allows the author or admin; non-authors get a row-not-found
// error which we translate to a clearer message.
const { error, count } = await supabase
.from('forum_threads')
.delete({ count: 'exact' })
.eq('id', v.data)
if (error) return { error: error.message }
if (count === 0) return { error: 'Not allowed to delete this thread' }
revalidatePath('/forum')
return { success: true as const }
}
export async function addComment(input: {
entity_type: 'forum_thread' | 'proposal' | 'incident' | 'policy'
entity_id: string
body: string
parent_id?: string | null
}) {
const v = parseInput(createCommentSchema, input)
if (!v.ok) return { error: v.error }
const supabase = await createClient()
const auth = await requireMember(supabase)
if (!auth.ok) return { error: auth.error }
const { member } = auth
// Reject comments on locked forum threads up front.
if (v.data.entity_type === 'forum_thread') {
const { data: thread } = await supabase
.from('forum_threads')
.select('locked')
.eq('id', v.data.entity_id)
.single()
if (thread?.locked) return { error: 'Thread is locked' }
}
const { data, error } = await supabase
.from('comments')
.insert({
space_id: member.space_id,
entity_type: v.data.entity_type,
entity_id: v.data.entity_id,
author_id: member.id,
parent_id: v.data.parent_id ?? null,
body: v.data.body,
})
.select('id')
.single()
if (error) return { error: error.message }
if (v.data.entity_type === 'forum_thread') {
revalidatePath(`/forum/${v.data.entity_id}`)
} else if (v.data.entity_type === 'proposal') {
revalidatePath(`/proposals/${v.data.entity_id}`)
} else if (v.data.entity_type === 'incident') {
revalidatePath(`/incidents/${v.data.entity_id}`)
}
return { id: data.id }
}
export async function editComment(commentId: string, body: string) {
const idCheck = parseInput(uuidSchema, commentId)
if (!idCheck.ok) return { error: 'Invalid comment ID' }
const v = parseInput(updateCommentSchema, { body })
if (!v.ok) return { error: v.error }
const supabase = await createClient()
const auth = await requireMember(supabase)
if (!auth.ok) return { error: auth.error }
const { data, error } = await supabase
.from('comments')
.update({ body: v.data.body, edited_at: new Date().toISOString() })
.eq('id', idCheck.data)
.select('entity_type, entity_id')
.single()
if (error) return { error: error.message }
if (data?.entity_type === 'forum_thread') revalidatePath(`/forum/${data.entity_id}`)
return { success: true as const }
}
export async function deleteComment(commentId: string) {
const v = parseInput(uuidSchema, commentId)
if (!v.ok) return { error: 'Invalid comment ID' }
const supabase = await createClient()
const auth = await requireMember(supabase)
if (!auth.ok) return { error: auth.error }
const { data, error } = await supabase
.from('comments')
.delete()
.eq('id', v.data)
.select('entity_type, entity_id')
.single()
if (error) return { error: error.message }
if (data?.entity_type === 'forum_thread') revalidatePath(`/forum/${data.entity_id}`)
return { success: true as const }
}
+11
View File
@@ -27,3 +27,14 @@ export * from './policies'
// Per-space configurable taxonomies
export * from './areas'
// Forum and polymorphic comments
export * from './forum'
// User-creatable chat channels
export * from './comms'
// Custom tiers, custom roles, multi-code invites
export * from './tiers'
export * from './roles'
export * from './invites'
+116
View File
@@ -0,0 +1,116 @@
'use server'
import { revalidatePath } from 'next/cache'
import { createClient } from '@/lib/supabase/server'
import { requireMemberWithRole, parseInput } from '@/lib/auth-helpers'
import { createInviteSchema, updateInviteSchema, uuidSchema } from '@/lib/validations'
const INVITE_ADMIN_ROLES = ['admin', 'board'] as const
function generateInviteCode(length = 8): string {
const alphabet = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'
let out = ''
const bytes = new Uint8Array(length)
crypto.getRandomValues(bytes)
for (let i = 0; i < length; i++) out += alphabet[bytes[i] % alphabet.length]
return out
}
export async function createInvite(input: {
code?: string
label?: string | null
expires_at?: string | null
max_uses?: number | null
is_enabled?: boolean
}) {
const v = parseInput(createInviteSchema, input)
if (!v.ok) return { error: v.error }
const supabase = await createClient()
const auth = await requireMemberWithRole(supabase, INVITE_ADMIN_ROLES, 'Admin or board access required')
if (!auth.ok) return { error: auth.error }
const { member } = auth
// Generate a unique code if not provided. Try up to 5 times in case of collision.
let code = v.data.code
if (!code) {
for (let attempt = 0; attempt < 5; attempt++) {
code = generateInviteCode()
const { data: existing } = await supabase.from('space_invites').select('id').eq('code', code).maybeSingle()
if (!existing) break
code = undefined
}
if (!code) return { error: 'Could not generate a unique invite code; try again.' }
}
const { data, error } = await supabase
.from('space_invites')
.insert({
space_id: member.space_id,
code,
label: v.data.label ?? null,
expires_at: v.data.expires_at ?? null,
max_uses: v.data.max_uses ?? null,
is_enabled: v.data.is_enabled ?? true,
created_by: member.id,
})
.select('id, code')
.single()
if (error) return { error: error.message }
revalidatePath('/settings')
return { id: data.id, code: data.code }
}
export async function updateInvite(inviteId: string, updates: {
label?: string | null
expires_at?: string | null
max_uses?: number | null
is_enabled?: boolean
}) {
const idCheck = parseInput(uuidSchema, inviteId)
if (!idCheck.ok) return { error: 'Invalid invite ID' }
const v = parseInput(updateInviteSchema, updates)
if (!v.ok) return { error: v.error }
const supabase = await createClient()
const auth = await requireMemberWithRole(supabase, INVITE_ADMIN_ROLES, 'Admin or board access required')
if (!auth.ok) return { error: auth.error }
const { member } = auth
const patch: Record<string, unknown> = {}
if (v.data.label !== undefined) patch.label = v.data.label
if (v.data.expires_at !== undefined) patch.expires_at = v.data.expires_at
if (v.data.max_uses !== undefined) patch.max_uses = v.data.max_uses
if (v.data.is_enabled !== undefined) patch.is_enabled = v.data.is_enabled
const { error } = await supabase
.from('space_invites')
.update(patch)
.eq('id', idCheck.data)
.eq('space_id', member.space_id)
if (error) return { error: error.message }
revalidatePath('/settings')
return { success: true as const }
}
export async function deleteInvite(inviteId: string) {
const v = parseInput(uuidSchema, inviteId)
if (!v.ok) return { error: 'Invalid invite ID' }
const supabase = await createClient()
const auth = await requireMemberWithRole(supabase, ['admin'], 'Admin access required')
if (!auth.ok) return { error: auth.error }
const { member } = auth
const { error } = await supabase
.from('space_invites')
.delete()
.eq('id', v.data)
.eq('space_id', member.space_id)
if (error) return { error: error.message }
revalidatePath('/settings')
return { success: true as const }
}
+170
View File
@@ -0,0 +1,170 @@
'use server'
import { revalidatePath } from 'next/cache'
import { createClient } from '@/lib/supabase/server'
import { requireMemberWithRole, parseInput } from '@/lib/auth-helpers'
import {
upsertRoleLabelSchema,
createCustomRoleSchema,
updateCustomRoleSchema,
uuidSchema,
} from '@/lib/validations'
const ROLE_ADMIN_ROLES = ['admin', 'board'] as const
export async function upsertRoleLabel(input: {
role: 'admin' | 'board' | 'treasurer' | 'member' | 'associate'
display_name?: string | null
description?: string | null
color?: string | null
sort_order?: number
}) {
const v = parseInput(upsertRoleLabelSchema, input)
if (!v.ok) return { error: v.error }
const supabase = await createClient()
const auth = await requireMemberWithRole(supabase, ROLE_ADMIN_ROLES, 'Admin or board access required')
if (!auth.ok) return { error: auth.error }
const { member } = auth
const { error } = await supabase
.from('space_role_labels')
.upsert({
space_id: member.space_id,
role: v.data.role,
display_name: v.data.display_name ?? null,
description: v.data.description ?? null,
color: v.data.color ?? null,
sort_order: v.data.sort_order ?? 0,
}, { onConflict: 'space_id,role' })
if (error) return { error: error.message }
revalidatePath('/settings')
return { success: true as const }
}
export async function createCustomRole(input: {
slug: string
name: string
description?: string | null
color?: string | null
sort_order?: number
}) {
const v = parseInput(createCustomRoleSchema, input)
if (!v.ok) return { error: v.error }
const supabase = await createClient()
const auth = await requireMemberWithRole(supabase, ROLE_ADMIN_ROLES, 'Admin or board access required')
if (!auth.ok) return { error: auth.error }
const { member } = auth
const { data, error } = await supabase
.from('space_custom_roles')
.insert({
space_id: member.space_id,
slug: v.data.slug,
name: v.data.name,
description: v.data.description ?? null,
color: v.data.color ?? null,
sort_order: v.data.sort_order ?? 100,
})
.select('id')
.single()
if (error) return { error: error.message }
revalidatePath('/settings')
return { id: data.id }
}
export async function updateCustomRole(roleId: string, updates: {
name?: string
description?: string | null
color?: string | null
sort_order?: number
}) {
const idCheck = parseInput(uuidSchema, roleId)
if (!idCheck.ok) return { error: 'Invalid role ID' }
const v = parseInput(updateCustomRoleSchema, updates)
if (!v.ok) return { error: v.error }
const supabase = await createClient()
const auth = await requireMemberWithRole(supabase, ROLE_ADMIN_ROLES, 'Admin or board access required')
if (!auth.ok) return { error: auth.error }
const { member } = auth
const patch: Record<string, unknown> = {}
if (v.data.name !== undefined) patch.name = v.data.name
if (v.data.description !== undefined) patch.description = v.data.description
if (v.data.color !== undefined) patch.color = v.data.color
if (v.data.sort_order !== undefined) patch.sort_order = v.data.sort_order
const { error } = await supabase
.from('space_custom_roles')
.update(patch)
.eq('id', idCheck.data)
.eq('space_id', member.space_id)
if (error) return { error: error.message }
revalidatePath('/settings')
return { success: true as const }
}
export async function deleteCustomRole(roleId: string) {
const v = parseInput(uuidSchema, roleId)
if (!v.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
const { error } = await supabase
.from('space_custom_roles')
.delete()
.eq('id', v.data)
.eq('space_id', member.space_id)
if (error) return { error: error.message }
revalidatePath('/settings')
return { success: true as const }
}
export async function assignCustomRole(memberId: string, customRoleId: string) {
const a = parseInput(uuidSchema, memberId)
const b = parseInput(uuidSchema, customRoleId)
if (!a.ok || !b.ok) return { error: 'Invalid ID' }
const supabase = await createClient()
const auth = await requireMemberWithRole(supabase, ROLE_ADMIN_ROLES, 'Admin or board access required')
if (!auth.ok) return { error: auth.error }
const { error } = await supabase
.from('space_member_custom_roles')
.insert({ member_id: a.data, custom_role_id: b.data })
if (error) return { error: error.message }
revalidatePath('/members')
revalidatePath('/settings')
return { success: true as const }
}
export async function unassignCustomRole(memberId: string, customRoleId: string) {
const a = parseInput(uuidSchema, memberId)
const b = parseInput(uuidSchema, customRoleId)
if (!a.ok || !b.ok) return { error: 'Invalid ID' }
const supabase = await createClient()
const auth = await requireMemberWithRole(supabase, ROLE_ADMIN_ROLES, 'Admin or board access required')
if (!auth.ok) return { error: auth.error }
const { error } = await supabase
.from('space_member_custom_roles')
.delete()
.eq('member_id', a.data)
.eq('custom_role_id', b.data)
if (error) return { error: error.message }
revalidatePath('/members')
revalidatePath('/settings')
return { success: true as const }
}
+124 -12
View File
@@ -4,7 +4,10 @@ import { revalidatePath } from 'next/cache'
import { createClient } from '@/lib/supabase/server'
import { requireMemberWithRole, parseInput } from '@/lib/auth-helpers'
import { ADMIN_ROLES } from '@/lib/permissions'
import { createSecretSchema, uuidSchema } from '@/lib/validations'
import { createSecretSchema, updateSecretSchema, uuidSchema } from '@/lib/validations'
import { encryptSecret, decryptSecret, encryptionAvailable } from '@/lib/secrets/crypto'
const SECRETS_RW_ROLES = ['admin', 'board'] as const
export async function createSecret(formData: {
title: string
@@ -21,18 +24,29 @@ export async function createSecret(formData: {
if (!auth.ok) return { error: auth.error }
const { member } = auth
const row: Record<string, unknown> = {
space_id: member.space_id,
title: v.data.title,
label: v.data.title,
description: v.data.description ?? null,
area: v.data.area ?? null,
icon: v.data.icon ?? null,
}
if (encryptionAvailable()) {
const { ciphertext, version } = encryptSecret(v.data.value)
row.encrypted_value = ciphertext
row.encryption_version = version
row.value = ''
} else {
row.value = v.data.value
row.encryption_version = 0
}
const { data, error } = await supabase
.from('secrets')
.insert({
space_id: member.space_id,
title: v.data.title,
label: v.data.title,
value: v.data.value,
description: v.data.description ?? null,
area: v.data.area ?? null,
icon: v.data.icon ?? null,
})
.select()
.insert(row)
.select('id, title, label, area, description, icon, encryption_version, created_at, updated_at, space_id, created_by')
.single()
if (error) return { error: error.message }
@@ -40,12 +54,110 @@ export async function createSecret(formData: {
return { data }
}
export async function updateSecret(secretId: string, updates: {
title?: string
value?: string
description?: string | null
area?: string | null
icon?: string | null
}) {
const idCheck = parseInput(uuidSchema, secretId)
if (!idCheck.ok) return { error: 'Invalid secret ID' }
const v = parseInput(updateSecretSchema, updates)
if (!v.ok) return { error: v.error }
const supabase = await createClient()
const auth = await requireMemberWithRole(supabase, SECRETS_RW_ROLES, 'Board or admin access required')
if (!auth.ok) return { error: auth.error }
const { member } = auth
const patch: Record<string, unknown> = {}
if (v.data.title !== undefined) {
patch.title = v.data.title
patch.label = v.data.title
}
if (v.data.description !== undefined) patch.description = v.data.description
if (v.data.area !== undefined) patch.area = v.data.area
if (v.data.icon !== undefined) patch.icon = v.data.icon
if (v.data.value !== undefined) {
if (encryptionAvailable()) {
const { ciphertext, version } = encryptSecret(v.data.value)
patch.encrypted_value = ciphertext
patch.encryption_version = version
patch.value = ''
} else {
patch.value = v.data.value
patch.encryption_version = 0
}
}
const { error } = await supabase
.from('secrets')
.update(patch)
.eq('id', idCheck.data)
.eq('space_id', member.space_id)
if (error) return { error: error.message }
revalidatePath('/ops')
return { success: true as const }
}
// Reveal returns the plaintext for a single secret. The list endpoint must
// NEVER send the plaintext or ciphertext to the client; only this action does,
// and only when the caller is board/admin in the owning space.
export async function revealSecret(secretId: string) {
const idCheck = parseInput(uuidSchema, secretId)
if (!idCheck.ok) return { error: 'Invalid secret ID' }
const supabase = await createClient()
const auth = await requireMemberWithRole(supabase, SECRETS_RW_ROLES, 'Board or admin access required')
if (!auth.ok) return { error: auth.error }
const { member } = auth
const { data: { user } } = await supabase.auth.getUser()
const { data, error } = await supabase
.from('secrets')
.select('id, encryption_version, encrypted_value, value, title')
.eq('id', idCheck.data)
.eq('space_id', member.space_id)
.single()
if (error || !data) return { error: error?.message ?? 'Not found' }
let plaintext: string
try {
if (data.encryption_version === 1 && data.encrypted_value) {
const raw = data.encrypted_value as unknown
const buf = typeof raw === 'string'
? Buffer.from((raw as string).replace(/^\\x/, ''), 'hex')
: Buffer.from(raw as Uint8Array)
plaintext = decryptSecret(buf, 1)
} else {
plaintext = (data.value ?? '') as string
}
} catch (e) {
return { error: e instanceof Error ? e.message : 'Decryption failed' }
}
if (user?.id) {
await supabase.from('activity_log').insert({
space_id: member.space_id,
user_id: user.id,
action: 'secret.revealed',
entity_type: 'secret',
entity_id: data.id,
details: `Revealed secret "${data.title}"`,
})
}
return { value: plaintext }
}
export async function deleteSecret(secretId: string) {
const v = parseInput(uuidSchema, secretId)
if (!v.ok) return { error: 'Invalid secret ID' }
const supabase = await createClient()
// Admin-only per RLS secrets_delete.
const auth = await requireMemberWithRole(supabase, ['admin'], 'Admin access required')
if (!auth.ok) return { error: auth.error }
const { member } = auth
+103
View File
@@ -0,0 +1,103 @@
'use server'
import { revalidatePath } from 'next/cache'
import { createClient } from '@/lib/supabase/server'
import { requireMemberWithRole, parseInput } from '@/lib/auth-helpers'
import { createTierSchema, updateTierSchema, uuidSchema } from '@/lib/validations'
const TIER_RW_ROLES = ['admin', 'board', 'treasurer'] as const
export async function createTier(input: {
slug: string
name: string
description?: string | null
monthly_price_cents: number
billing_cadence?: 'monthly' | 'quarterly' | 'annual' | 'one_time' | 'custom'
sort_order?: number
}) {
const v = parseInput(createTierSchema, input)
if (!v.ok) return { error: v.error }
const supabase = await createClient()
const auth = await requireMemberWithRole(supabase, TIER_RW_ROLES, 'Treasurer, board, or admin access required')
if (!auth.ok) return { error: auth.error }
const { member } = auth
const { data, error } = await supabase
.from('space_tiers')
.insert({
space_id: member.space_id,
slug: v.data.slug,
name: v.data.name,
description: v.data.description ?? null,
monthly_price_cents: v.data.monthly_price_cents,
billing_cadence: v.data.billing_cadence ?? 'monthly',
sort_order: v.data.sort_order ?? 100,
is_system: false,
})
.select('id')
.single()
if (error) return { error: error.message }
revalidatePath('/settings')
return { id: data.id }
}
export async function updateTier(tierId: string, updates: {
name?: string
description?: string | null
monthly_price_cents?: number
billing_cadence?: 'monthly' | 'quarterly' | 'annual' | 'one_time' | 'custom'
sort_order?: number
is_archived?: boolean
}) {
const idCheck = parseInput(uuidSchema, tierId)
if (!idCheck.ok) return { error: 'Invalid tier ID' }
const v = parseInput(updateTierSchema, updates)
if (!v.ok) return { error: v.error }
const supabase = await createClient()
const auth = await requireMemberWithRole(supabase, TIER_RW_ROLES, 'Treasurer, board, or admin access required')
if (!auth.ok) return { error: auth.error }
const { member } = auth
const patch: Record<string, unknown> = {}
if (v.data.name !== undefined) patch.name = v.data.name
if (v.data.description !== undefined) patch.description = v.data.description
if (v.data.monthly_price_cents !== undefined) patch.monthly_price_cents = v.data.monthly_price_cents
if (v.data.billing_cadence !== undefined) patch.billing_cadence = v.data.billing_cadence
if (v.data.sort_order !== undefined) patch.sort_order = v.data.sort_order
if (v.data.is_archived !== undefined) patch.is_archived = v.data.is_archived
const { error } = await supabase
.from('space_tiers')
.update(patch)
.eq('id', idCheck.data)
.eq('space_id', member.space_id)
if (error) return { error: error.message }
revalidatePath('/settings')
return { success: true as const }
}
export async function deleteTier(tierId: string) {
const v = parseInput(uuidSchema, tierId)
if (!v.ok) return { error: 'Invalid tier ID' }
const supabase = await createClient()
// RLS blocks deletion of system tiers; admin-only.
const auth = await requireMemberWithRole(supabase, ['admin'], 'Admin access required')
if (!auth.ok) return { error: auth.error }
const { member } = auth
const { error, count } = await supabase
.from('space_tiers')
.delete({ count: 'exact' })
.eq('id', v.data)
.eq('space_id', member.space_id)
if (error) return { error: error.message }
if (count === 0) return { error: 'Cannot delete a built-in tier. Archive it instead.' }
revalidatePath('/settings')
return { success: true as const }
}