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
+94
View File
@@ -0,0 +1,94 @@
import Link from 'next/link'
import { notFound } from 'next/navigation'
import ReactMarkdown from 'react-markdown'
import remarkGfm from 'remark-gfm'
import { Pin, Lock } from 'lucide-react'
import { createClient } from '@/lib/supabase/server'
import { CommentThread } from '@/components/comments/comment-thread'
import { loadComments } from '@/components/comments/load-comments'
import { ThreadActions } from './thread-actions'
export default async function ForumThreadPage({ params }: { params: Promise<{ id: string }> }) {
const { id } = await params
const supabase = await createClient()
const { data: { user } } = await supabase.auth.getUser()
if (!user) return null
const { data: self } = await supabase
.from('space_members')
.select('id, space_id, role, display_name')
.eq('user_id', user.id)
.in('status', ['current', 'unverified', 'late'])
.single()
if (!self) return null
const { data: thread } = await supabase
.from('forum_threads')
.select('id, title, body, category, pinned, locked, comment_count, created_at, author_id, space_id')
.eq('id', id)
.single()
if (!thread) notFound()
if (thread.space_id !== self.space_id) notFound()
let authorName = 'Member'
if (thread.author_id) {
const { data: a } = await supabase
.from('space_members')
.select('display_name')
.eq('id', thread.author_id)
.single()
if (a?.display_name) authorName = a.display_name
}
const comments = await loadComments(supabase, 'forum_thread', thread.id)
const isAuthor = self.id === thread.author_id
const canModerate = self.role === 'admin' || self.role === 'board'
const canEditThread = isAuthor || canModerate
return (
<div className="p-4 md:p-6 max-w-4xl space-y-5">
<div>
<Link href="/forum" className="font-mono text-[11px] tracking-widest text-muted-foreground hover:text-foreground uppercase">
← Forum
</Link>
</div>
<header className="bg-card border border-border rounded p-5">
<div className="flex items-start justify-between gap-4 mb-2">
<div className="flex items-center gap-2 flex-wrap min-w-0">
{thread.pinned && <Pin className="w-4 h-4 text-amber-500 shrink-0" />}
{thread.locked && <Lock className="w-4 h-4 text-muted-foreground shrink-0" />}
<h1 className="font-sans text-xl font-semibold text-foreground">{thread.title}</h1>
<span className="font-mono text-[10px] px-1.5 py-0.5 rounded bg-muted text-muted-foreground uppercase tracking-widest">{thread.category}</span>
</div>
{canEditThread && (
<ThreadActions
threadId={thread.id}
pinned={thread.pinned}
locked={thread.locked}
canModerate={canModerate}
isAuthor={isAuthor}
/>
)}
</div>
<p className="font-mono text-[11px] text-muted-foreground">
{authorName} · {new Date(thread.created_at).toLocaleString()}
</p>
{thread.body && (
<div className="prose prose-sm prose-neutral dark:prose-invert max-w-none mt-4 break-words">
<ReactMarkdown remarkPlugins={[remarkGfm]}>{thread.body}</ReactMarkdown>
</div>
)}
</header>
<CommentThread
entityType="forum_thread"
entityId={thread.id}
comments={comments}
currentMemberId={self.id}
canModerate={canModerate}
locked={thread.locked}
/>
</div>
)
}
+72
View File
@@ -0,0 +1,72 @@
'use client'
import { useRouter } from 'next/navigation'
import { toast } from 'sonner'
import { Pin, Lock, Trash2 } from 'lucide-react'
import { updateForumThread, deleteForumThread } from '@/lib/actions'
interface Props {
threadId: string
pinned: boolean
locked: boolean
canModerate: boolean
isAuthor: boolean
}
export function ThreadActions({ threadId, pinned, locked, canModerate, isAuthor }: Props) {
const router = useRouter()
async function togglePinned() {
const result = await updateForumThread(threadId, { pinned: !pinned })
if (result.error) { toast.error(result.error); return }
router.refresh()
}
async function toggleLocked() {
const result = await updateForumThread(threadId, { locked: !locked })
if (result.error) { toast.error(result.error); return }
router.refresh()
}
async function handleDelete() {
if (!confirm('Delete this thread? All comments are deleted too.')) return
const result = await deleteForumThread(threadId)
if (result.error) { toast.error(result.error); return }
toast.success('Thread deleted')
router.push('/forum')
}
return (
<div className="flex items-center gap-1 shrink-0">
{canModerate && (
<>
<button
onClick={togglePinned}
className={`font-mono text-[10px] border border-border px-2 py-1 rounded transition flex items-center gap-1 ${pinned ? 'text-amber-600 bg-amber-50' : 'hover:border-amber-500 hover:text-amber-600'}`}
title={pinned ? 'Unpin' : 'Pin'}
>
<Pin className="w-3 h-3" />
{pinned ? 'Pinned' : 'Pin'}
</button>
<button
onClick={toggleLocked}
className={`font-mono text-[10px] border border-border px-2 py-1 rounded transition flex items-center gap-1 ${locked ? 'text-muted-foreground bg-muted' : 'hover:border-primary hover:text-primary'}`}
title={locked ? 'Unlock' : 'Lock'}
>
<Lock className="w-3 h-3" />
{locked ? 'Locked' : 'Lock'}
</button>
</>
)}
{(isAuthor || canModerate) && (
<button
onClick={handleDelete}
className="text-muted-foreground hover:text-red-500 transition p-1.5"
title="Delete"
>
<Trash2 className="w-3.5 h-3.5" />
</button>
)}
</div>
)
}
+83
View File
@@ -0,0 +1,83 @@
'use client'
import { useState } from 'react'
import { useRouter } from 'next/navigation'
import { toast } from 'sonner'
import { createForumThread } from '@/lib/actions'
const CATEGORIES = [
{ value: 'general', label: 'General' },
{ value: 'announcements', label: 'Announcements' },
{ value: 'projects', label: 'Projects' },
{ value: 'help', label: 'Help' },
{ value: 'feedback', label: 'Feedback' },
{ value: 'off-topic', label: 'Off topic' },
]
export function NewThreadForm() {
const router = useRouter()
const [title, setTitle] = useState('')
const [body, setBody] = useState('')
const [category, setCategory] = useState('general')
const [saving, setSaving] = useState(false)
async function handleSubmit(e: React.FormEvent) {
e.preventDefault()
if (!title.trim()) return
setSaving(true)
const result = await createForumThread({ title: title.trim(), body: body.trim() || undefined, category })
setSaving(false)
if ('error' in result && result.error) { toast.error(result.error); return }
if ('id' in result && result.id) {
toast.success('Thread created')
router.push(`/forum/${result.id}`)
}
}
return (
<form onSubmit={handleSubmit} className="bg-card border border-border rounded p-5 space-y-4">
<div>
<label className="font-mono text-[10px] tracking-widest text-muted-foreground uppercase block mb-1">Title</label>
<input
type="text"
value={title}
onChange={e => setTitle(e.target.value)}
maxLength={200}
required
autoFocus
className="w-full bg-background border border-border text-foreground font-sans text-sm rounded px-3 py-2 focus:outline-none focus:border-primary"
/>
</div>
<div>
<label className="font-mono text-[10px] tracking-widest text-muted-foreground uppercase block mb-1">Category</label>
<select
value={category}
onChange={e => setCategory(e.target.value)}
className="w-full bg-background border border-border text-foreground font-sans text-sm rounded px-3 py-2 focus:outline-none focus:border-primary"
>
{CATEGORIES.map(c => <option key={c.value} value={c.value}>{c.label}</option>)}
</select>
</div>
<div>
<label className="font-mono text-[10px] tracking-widest text-muted-foreground uppercase block mb-1">Body (markdown)</label>
<textarea
value={body}
onChange={e => setBody(e.target.value)}
rows={8}
maxLength={20000}
placeholder="Markdown supported. Headings, lists, code blocks, links."
className="w-full bg-background border border-border text-foreground font-sans text-sm rounded px-3 py-2 focus:outline-none focus:border-primary"
/>
</div>
<div className="flex items-center gap-2 justify-end">
<button
type="submit"
disabled={saving || !title.trim()}
className="bg-primary text-white text-xs font-sans px-3 py-1.5 rounded hover:bg-primary/90 transition disabled:opacity-50"
>
{saving ? 'Posting...' : 'Post thread'}
</button>
</div>
</form>
)
}
+16
View File
@@ -0,0 +1,16 @@
import Link from 'next/link'
import { NewThreadForm } from './new-thread-form'
export default function NewThreadPage() {
return (
<div className="p-4 md:p-6 max-w-3xl">
<div className="mb-6">
<Link href="/forum" className="font-mono text-[11px] tracking-widest text-muted-foreground hover:text-foreground uppercase">
← Forum
</Link>
<h1 className="font-mono text-sm tracking-widest uppercase text-muted-foreground mt-2">New thread</h1>
</div>
<NewThreadForm />
</div>
)
}
+93
View File
@@ -0,0 +1,93 @@
import Link from 'next/link'
import { createClient } from '@/lib/supabase/server'
import { Pin, Lock, MessagesSquare, Plus } from 'lucide-react'
export default async function ForumIndexPage() {
const supabase = await createClient()
const { data: { user } } = await supabase.auth.getUser()
if (!user) return null
const { data: self } = await supabase
.from('space_members')
.select('space_id, role, display_name, id')
.eq('user_id', user.id)
.in('status', ['current', 'unverified', 'late'])
.single()
if (!self) return null
const { data: threads } = await supabase
.from('forum_threads')
.select('id, title, category, pinned, locked, comment_count, last_comment_at, created_at, author_id')
.eq('space_id', self.space_id)
.order('pinned', { ascending: false })
.order('last_comment_at', { ascending: false, nullsFirst: false })
.order('created_at', { ascending: false })
.limit(200)
const authorIds = Array.from(new Set((threads ?? []).map(t => t.author_id).filter(Boolean) as string[]))
const authorMap: Record<string, string> = {}
if (authorIds.length > 0) {
const { data: authors } = await supabase
.from('space_members')
.select('id, display_name')
.in('id', authorIds)
for (const a of authors ?? []) authorMap[a.id] = a.display_name ?? 'Member'
}
return (
<div className="p-4 md:p-6 max-w-5xl">
<div className="flex items-center justify-between mb-6 gap-4">
<div>
<h1 className="font-mono text-sm tracking-widest uppercase text-muted-foreground mb-1">Forum</h1>
<p className="font-sans text-sm text-muted-foreground">Long-form discussion, announcements, and proposals before they become proposals.</p>
</div>
<Link
href="/forum/new"
className="flex items-center gap-1.5 bg-primary text-white text-xs font-sans px-3 py-1.5 rounded hover:bg-primary/90 transition shrink-0"
>
<Plus className="w-3.5 h-3.5" /> New thread
</Link>
</div>
{threads && threads.length > 0 ? (
<div className="bg-card border border-border rounded divide-y divide-border">
{threads.map(t => (
<Link
key={t.id}
href={`/forum/${t.id}`}
className="flex items-center gap-3 px-4 py-3 hover:bg-muted/30 transition"
>
<MessagesSquare className="w-4 h-4 text-muted-foreground shrink-0" />
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2 flex-wrap">
{t.pinned && <Pin className="w-3 h-3 text-amber-500" aria-label="Pinned" />}
{t.locked && <Lock className="w-3 h-3 text-muted-foreground" aria-label="Locked" />}
<span className="font-sans text-sm font-medium text-foreground truncate">{t.title}</span>
<span className="font-mono text-[10px] px-1.5 py-0.5 rounded bg-muted text-muted-foreground uppercase tracking-widest">{t.category}</span>
</div>
<p className="font-mono text-[11px] text-muted-foreground mt-0.5">
{(t.author_id && authorMap[t.author_id]) ?? 'Member'}
{' · '}
{t.comment_count} {t.comment_count === 1 ? 'reply' : 'replies'}
{t.last_comment_at && <> · last activity {new Date(t.last_comment_at).toLocaleString()}</>}
</p>
</div>
</Link>
))}
</div>
) : (
<div className="bg-card border border-border rounded p-10 text-center">
<MessagesSquare className="w-8 h-8 text-muted-foreground mx-auto mb-3" />
<p className="font-sans text-sm text-foreground mb-1">No threads yet.</p>
<p className="font-sans text-sm text-muted-foreground mb-4">Start the conversation.</p>
<Link
href="/forum/new"
className="inline-flex items-center gap-1.5 bg-primary text-white text-xs font-sans px-3 py-1.5 rounded hover:bg-primary/90 transition"
>
<Plus className="w-3.5 h-3.5" /> Start a thread
</Link>
</div>
)}
</div>
)
}