feat(invites): role-granting + usage-capped invites; audit hardening (P7)
Invites - migration 029: space_invites.role (member_role enum, default 'member' — legacy invites and the spaces.invite_code path keep granting member). schema.sql + types/database.ts mirrored - lib/invite-logic.ts (pure, tested): canAssignInviteRole — admin may grant any role; board may grant anything except admin; nobody else. Privilege-escalation guard on top of the existing admin/board gate - createInvite/updateInvite take + enforce role via that guard; createInviteSchema/updateInviteSchema validate the enum - joinSpace applies the invite's granted role (validated), default member; uses_count/max_uses/expiry already enforced - invites panel: role picker (filtered to what the creator may grant), one-click "single use", per-invite role badge - space-scoped invite link /join/<space>?code=… via a presentational app/join/[space] landing that hands off to the proven /signup?invite= flow; /join added to middleware PUBLIC_ROUTES Audit hardening (from this pass's review) - /login now honors a validated same-origin ?next= (was hardcoded to /dashboard) so the public_auth form sign-in round-trips; OAuth threads next through the callback (which already honored it) - submitForm requires formId; submitFormSchema drops the now-ambiguous slug path (form slugs are per-space after 028). Both callers already pass formId. Tests updated 337 tests; build verified (Compiled successfully, exit 0). No deploy.
This commit is contained in:
@@ -316,11 +316,11 @@ export async function submitForm(input: unknown) {
|
||||
const body = v.data
|
||||
|
||||
const admin = createAdminClient()
|
||||
let q = admin
|
||||
const { data: form } = await admin
|
||||
.from('forms')
|
||||
.select('id, space_id, slug, kind, visibility, status, schema, legal_text, version')
|
||||
q = body.formId ? q.eq('id', body.formId) : q.eq('slug', body.slug as string)
|
||||
const { data: form } = await q.single()
|
||||
.eq('id', body.formId)
|
||||
.maybeSingle()
|
||||
if (!form) return { error: 'Form not found' }
|
||||
if (form.status !== 'published') {
|
||||
return { error: 'This form is not accepting responses' }
|
||||
|
||||
@@ -4,6 +4,7 @@ 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'
|
||||
import { canAssignInviteRole } from '@/lib/invite-logic'
|
||||
|
||||
const INVITE_ADMIN_ROLES = ['admin', 'board'] as const
|
||||
|
||||
@@ -22,6 +23,7 @@ export async function createInvite(input: {
|
||||
expires_at?: string | null
|
||||
max_uses?: number | null
|
||||
is_enabled?: boolean
|
||||
role?: 'admin' | 'board' | 'treasurer' | 'member' | 'associate'
|
||||
}) {
|
||||
const v = parseInput(createInviteSchema, input)
|
||||
if (!v.ok) return { error: v.error }
|
||||
@@ -31,6 +33,10 @@ export async function createInvite(input: {
|
||||
if (!auth.ok) return { error: auth.error }
|
||||
const { member } = auth
|
||||
|
||||
if (!canAssignInviteRole(member.role, v.data.role)) {
|
||||
return { error: `You cannot create an invite that grants the "${v.data.role}" role.` }
|
||||
}
|
||||
|
||||
// Generate a unique code if not provided. Try up to 5 times in case of collision.
|
||||
let code = v.data.code
|
||||
if (!code) {
|
||||
@@ -52,6 +58,7 @@ export async function createInvite(input: {
|
||||
expires_at: v.data.expires_at ?? null,
|
||||
max_uses: v.data.max_uses ?? null,
|
||||
is_enabled: v.data.is_enabled ?? true,
|
||||
role: v.data.role,
|
||||
created_by: member.id,
|
||||
})
|
||||
.select('id, code')
|
||||
@@ -67,6 +74,7 @@ export async function updateInvite(inviteId: string, updates: {
|
||||
expires_at?: string | null
|
||||
max_uses?: number | null
|
||||
is_enabled?: boolean
|
||||
role?: 'admin' | 'board' | 'treasurer' | 'member' | 'associate'
|
||||
}) {
|
||||
const idCheck = parseInput(uuidSchema, inviteId)
|
||||
if (!idCheck.ok) return { error: 'Invalid invite ID' }
|
||||
@@ -78,11 +86,16 @@ export async function updateInvite(inviteId: string, updates: {
|
||||
if (!auth.ok) return { error: auth.error }
|
||||
const { member } = auth
|
||||
|
||||
if (v.data.role !== undefined && !canAssignInviteRole(member.role, v.data.role)) {
|
||||
return { error: `You cannot set an invite to grant the "${v.data.role}" role.` }
|
||||
}
|
||||
|
||||
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
|
||||
if (v.data.role !== undefined) patch.role = v.data.role
|
||||
|
||||
const { error } = await supabase
|
||||
.from('space_invites')
|
||||
|
||||
+11
-3
@@ -117,10 +117,10 @@ export async function joinSpace(formData: {
|
||||
|
||||
// Try the new multi-code invites table first. Falls back to the legacy
|
||||
// spaces.invite_code (a permanent default) if the code isn't found there.
|
||||
let invite: { id: string; space_id: string; max_uses: number | null; uses_count: number; expires_at: string | null; is_enabled: boolean } | null = null
|
||||
let invite: { id: string; space_id: string; max_uses: number | null; uses_count: number; expires_at: string | null; is_enabled: boolean; role: string } | null = null
|
||||
const { data: inviteRow } = await admin
|
||||
.from('space_invites')
|
||||
.select('id, space_id, max_uses, uses_count, expires_at, is_enabled')
|
||||
.select('id, space_id, max_uses, uses_count, expires_at, is_enabled, role')
|
||||
.eq('code', code)
|
||||
.maybeSingle()
|
||||
if (inviteRow) invite = inviteRow as typeof invite
|
||||
@@ -149,6 +149,14 @@ export async function joinSpace(formData: {
|
||||
|
||||
if (lookupErr || !space) return { error: 'Invalid invite code' }
|
||||
|
||||
// Honor the invite's granted role (default 'member' for the legacy
|
||||
// spaces.invite_code path or any invite created before migration 029).
|
||||
// Validated against the enum defensively even though the DB constrains it.
|
||||
const grantedRole =
|
||||
invite && ['admin', 'board', 'treasurer', 'member', 'associate'].includes(invite.role)
|
||||
? invite.role
|
||||
: 'member'
|
||||
|
||||
const { data: newMember, error: memberErr } = await admin
|
||||
.from('space_members')
|
||||
.insert({
|
||||
@@ -156,7 +164,7 @@ export async function joinSpace(formData: {
|
||||
user_id: user.id,
|
||||
display_name: formData.displayName || user.email,
|
||||
email: user.email,
|
||||
role: 'member',
|
||||
role: grantedRole,
|
||||
tier: 'basic',
|
||||
status: space.require_approval ? 'unverified' : 'current',
|
||||
approved: true,
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
// Pure invite-role policy. No deps so it is unit-testable and shared by the
|
||||
// server action, the validations, and the panel UI.
|
||||
|
||||
export const INVITE_ROLES = ['admin', 'board', 'treasurer', 'member', 'associate'] as const
|
||||
export type InviteRole = (typeof INVITE_ROLES)[number]
|
||||
|
||||
export function isInviteRole(v: string): v is InviteRole {
|
||||
return (INVITE_ROLES as readonly string[]).includes(v)
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a member with `creatorRole` may create an invite that grants
|
||||
* `target`. Invite creation is already admin/board-gated upstream; this is
|
||||
* the privilege-escalation guard on top of that:
|
||||
* - admin may grant any role
|
||||
* - board may grant anything EXCEPT admin (a board member cannot mint
|
||||
* admin access)
|
||||
* - anyone else: no (they never reach invite creation anyway)
|
||||
*/
|
||||
export function canAssignInviteRole(creatorRole: string, target: string): boolean {
|
||||
if (!isInviteRole(target)) return false
|
||||
if (creatorRole === 'admin') return true
|
||||
if (creatorRole === 'board') return target !== 'admin'
|
||||
return false
|
||||
}
|
||||
+11
-11
@@ -1,4 +1,5 @@
|
||||
import { z } from 'zod'
|
||||
import { INVITE_ROLES } from './invite-logic'
|
||||
|
||||
/**
|
||||
* Accepts every date-ish string the app produces and normalizes to a
|
||||
@@ -476,6 +477,7 @@ export const createInviteSchema = z.object({
|
||||
expires_at: flexibleDateTime(),
|
||||
max_uses: z.number().int().min(1).max(100000).optional().nullable(),
|
||||
is_enabled: z.boolean().optional(),
|
||||
role: z.enum(INVITE_ROLES).optional().default('member'),
|
||||
})
|
||||
|
||||
export const updateInviteSchema = z.object({
|
||||
@@ -483,6 +485,7 @@ export const updateInviteSchema = z.object({
|
||||
expires_at: flexibleDateTime(),
|
||||
max_uses: z.number().int().min(1).max(100000).optional().nullable(),
|
||||
is_enabled: z.boolean().optional(),
|
||||
role: z.enum(INVITE_ROLES).optional(),
|
||||
})
|
||||
|
||||
export const createChannelSchema = z.object({
|
||||
@@ -649,17 +652,14 @@ export const formIdSchema = z.object({ formId: z.string().uuid('Invalid form ID'
|
||||
|
||||
// Envelope only. The answers object is validated dynamically against the
|
||||
// form's stored field schema inside submitForm (see lib/forms-schema.ts).
|
||||
export const submitFormSchema = z
|
||||
.object({
|
||||
formId: z.string().uuid('Invalid form ID').optional(),
|
||||
slug: formSlug.optional(),
|
||||
answers: z.record(z.unknown()).default({}),
|
||||
email: emailField().optional().nullable(),
|
||||
consent: z.boolean().optional(),
|
||||
})
|
||||
.refine(d => Boolean(d.formId) || Boolean(d.slug), {
|
||||
message: 'formId or slug is required',
|
||||
})
|
||||
// formId is required: form slugs are only unique per space now, so a bare
|
||||
// slug is ambiguous. Both callers (public page + onboarding) submit by id.
|
||||
export const submitFormSchema = z.object({
|
||||
formId: z.string().uuid('Invalid form ID'),
|
||||
answers: z.record(z.unknown()).default({}),
|
||||
email: emailField().optional().nullable(),
|
||||
consent: z.boolean().optional(),
|
||||
})
|
||||
|
||||
export const linkSubmissionsSchema = z.object({
|
||||
memberId: z.string().uuid('Invalid member ID'),
|
||||
|
||||
Reference in New Issue
Block a user