feat(forms): space-scoped public URL /f/[space]/[slug] (P6)

- migration 028: drop global UNIQUE(forms.slug), add
  UNIQUE(space_id, slug); schema.sql mirrored. Form slugs are now
  unique per space (fixes cross-tenant slug squatting)
- getPublicForm now takes { space, slug }: resolves the space by its
  slug then the form by space_id + slug (maybeSingle)
- route moved app/f/[slug] -> app/f/[space]/[slug]; the public client
  submits by formId (slug is no longer globally unambiguous) and the
  sign-in link round-trips the full /f/space/slug path
- forms-guard returns the space slug; the builder + forms list show
  the full /f/<space>/<slug> share URL; new/edit pass it through
- middleware /f allowlist already covers /f/<space>/<slug>
- getPublicFormSchema + tests updated (333 pass)

build verified (Compiled successfully, exit 0; new route present). No deploy.
This commit is contained in:
Moheeb Zara
2026-05-16 17:21:39 -07:00
parent 5a49ecb2cf
commit 8bbe99d34f
13 changed files with 73 additions and 26 deletions
+6 -3
View File
@@ -184,9 +184,12 @@ describe('linkSubmissionsSchema', () => {
})
describe('getPublicFormSchema', () => {
it('validates the slug', () => {
expect(getPublicFormSchema.safeParse({ slug: 'a-form' }).success).toBe(true)
expect(getPublicFormSchema.safeParse({ slug: 'Bad' }).success).toBe(false)
it('requires both a space and a valid form slug', () => {
expect(getPublicFormSchema.safeParse({ space: 'heatsynclabs', slug: 'a-form' }).success).toBe(true)
expect(getPublicFormSchema.safeParse({ slug: 'a-form' }).success).toBe(false)
expect(getPublicFormSchema.safeParse({ space: 'heatsynclabs' }).success).toBe(false)
expect(getPublicFormSchema.safeParse({ space: 'heatsynclabs', slug: 'Bad' }).success).toBe(false)
expect(getPublicFormSchema.safeParse({ space: '', slug: 'a-form' }).success).toBe(false)
})
})
+2 -1
View File
@@ -8,7 +8,7 @@ export const dynamic = 'force-dynamic'
export default async function EditFormPage({ params }: { params: Promise<{ id: string }> }) {
const { id } = await params
const { supabase, member } = await requireFormsManagerPage()
const { supabase, member, spaceSlug } = await requireFormsManagerPage()
const { data: form } = await supabase
.from('forms')
@@ -28,6 +28,7 @@ export default async function EditFormPage({ params }: { params: Promise<{ id: s
<FormBuilder
initial={{
id: form.id,
spaceSlug,
slug: form.slug,
title: form.title,
description: form.description ?? '',
+2 -2
View File
@@ -24,7 +24,7 @@ const VIS_LABEL: Record<string, string> = {
public_anon: 'Public',
}
export function FormsClient({ forms }: { forms: FormRow[] }) {
export function FormsClient({ forms, spaceSlug }: { forms: FormRow[]; spaceSlug: string }) {
return (
<>
<PageHeader>
@@ -65,7 +65,7 @@ export function FormsClient({ forms }: { forms: FormRow[] }) {
</Link>
{f.kind === 'waiver' && <Badge variant="secondary">Waiver</Badge>}
</div>
<p className="font-mono text-xs text-muted-foreground">/f/{f.slug}</p>
<p className="font-mono text-xs text-muted-foreground">/f/{spaceSlug}/{f.slug}</p>
</div>
<Badge variant="outline">{VIS_LABEL[f.visibility] ?? f.visibility}</Badge>
<Badge variant={f.status === 'published' ? 'default' : 'secondary'}>
+2 -1
View File
@@ -5,7 +5,7 @@ import { FormBuilder } from '@/components/forms/form-builder'
export const dynamic = 'force-dynamic'
export default async function NewFormPage() {
await requireFormsManagerPage()
const { spaceSlug } = await requireFormsManagerPage()
return (
<>
@@ -15,6 +15,7 @@ export default async function NewFormPage() {
<div className="p-4 md:p-6">
<FormBuilder
initial={{
spaceSlug,
slug: '',
title: '',
description: '',
+2 -2
View File
@@ -4,7 +4,7 @@ import { FormsClient } from './forms-client'
export const dynamic = 'force-dynamic'
export default async function FormsPage() {
const { supabase, member } = await requireFormsManagerPage()
const { supabase, member, spaceSlug } = await requireFormsManagerPage()
const { data: forms } = await supabase
.from('forms')
@@ -12,5 +12,5 @@ export default async function FormsPage() {
.eq('space_id', member.space_id)
.order('created_at', { ascending: false })
return <FormsClient forms={forms ?? []} />
return <FormsClient forms={forms ?? []} spaceSlug={spaceSlug} />
}
@@ -5,9 +5,13 @@ import { PublicFormClient } from './public-form-client'
export const dynamic = 'force-dynamic'
export default async function PublicFormPage({ params }: { params: Promise<{ slug: string }> }) {
const { slug } = await params
const res = await getPublicForm({ slug })
export default async function PublicFormPage({
params,
}: {
params: Promise<{ space: string; slug: string }>
}) {
const { space, slug } = await params
const res = await getPublicForm({ space, slug })
if ('error' in res && res.error) {
return (
@@ -29,7 +33,8 @@ export default async function PublicFormPage({ params }: { params: Promise<{ slu
return (
<main className="mx-auto max-w-2xl p-4 md:p-8">
<PublicFormClient
slug={form.slug}
formId={form.id}
nextPath={`/f/${space}/${slug}`}
title={form.title}
description={form.description}
kind={form.kind}
@@ -9,7 +9,8 @@ import { submitForm } from '@/lib/actions'
import type { FormField } from '@/lib/forms-schema'
export function PublicFormClient({
slug,
formId,
nextPath,
title,
description,
kind,
@@ -18,7 +19,8 @@ export function PublicFormClient({
fields,
authed,
}: {
slug: string
formId: string
nextPath: string
title: string
description: string | null
kind: string
@@ -41,8 +43,10 @@ export function PublicFormClient({
async function submit() {
setError(null)
setSubmitting(true)
// Submit by formId: form slugs are only unique per space now, so id is
// the unambiguous handle.
const res = await submitForm({
slug,
formId,
answers: values,
email: showEmail && email ? email : undefined,
consent: isWaiver ? consent : undefined,
@@ -75,7 +79,7 @@ export function PublicFormClient({
<div className="rounded-lg border bg-muted/40 p-6 text-center">
<p className="text-sm">You need to be signed in to submit this form.</p>
<Button asChild className="mt-3">
<a href={`/login?next=/f/${slug}`}>Sign in</a>
<a href={`/login?next=${encodeURIComponent(nextPath)}`}>Sign in</a>
</Button>
</div>
) : (
+4 -2
View File
@@ -29,6 +29,7 @@ type Status = 'draft' | 'published' | 'closed'
export type BuilderForm = {
id?: string
spaceSlug: string
slug: string
title: string
description: string
@@ -171,8 +172,9 @@ export function FormBuilder({ initial }: { initial: BuilderForm }) {
router.refresh()
}
const publicPath = `/f/${initial.spaceSlug}/${initial.slug}`
const publicUrl =
typeof window !== 'undefined' ? `${window.location.origin}/f/${initial.slug}` : `/f/${initial.slug}`
typeof window !== 'undefined' ? `${window.location.origin}${publicPath}` : publicPath
return (
<div className="grid gap-6 lg:grid-cols-2">
@@ -240,7 +242,7 @@ export function FormBuilder({ initial }: { initial: BuilderForm }) {
{isEdit ? (
<p className="text-xs text-muted-foreground">The slug cannot change after creation.</p>
) : (
<p className="text-xs text-muted-foreground">Public address: /f/{slug || '…'}</p>
<p className="text-xs text-muted-foreground">Public address: /f/{initial.spaceSlug}/{slug || '…'}</p>
)}
</div>
<div className="space-y-1.5">
+9 -1
View File
@@ -395,11 +395,19 @@ export async function getPublicForm(input: unknown) {
if (!v.ok) return { error: v.error }
const admin = createAdminClient()
const { data: space } = await admin
.from('spaces')
.select('id')
.eq('slug', v.data.space)
.maybeSingle()
if (!space) return { error: 'This form is not available.' }
const { data: form } = await admin
.from('forms')
.select('id, slug, title, description, kind, visibility, schema, legal_text, version, status')
.eq('space_id', space.id)
.eq('slug', v.data.slug)
.single()
.maybeSingle()
// Members-only forms are never served on the public page (that would expose
// their schema to anyone). They are filled from inside the app.
+3 -2
View File
@@ -15,7 +15,7 @@ export async function requireFormsManagerPage() {
const { data: member } = await supabase
.from('space_members')
.select('id, space_id, role, user_id, display_name')
.select('id, space_id, role, user_id, display_name, spaces(slug)')
.eq('user_id', user.id)
.in('status', ['current', 'unverified', 'late'])
.single()
@@ -28,5 +28,6 @@ export async function requireFormsManagerPage() {
})
if (!allowed) redirect('/dashboard')
return { supabase, member }
const spaceSlug = (member.spaces as { slug?: string } | null)?.slug ?? ''
return { supabase, member, spaceSlug }
}
+4 -1
View File
@@ -666,7 +666,10 @@ export const linkSubmissionsSchema = z.object({
email: emailField(),
})
export const getPublicFormSchema = z.object({ slug: formSlug })
export const getPublicFormSchema = z.object({
space: z.string().min(1).max(100),
slug: formSlug,
})
// ─── Generic ID schemas ──────────────────────────────────────────────────────
+17
View File
@@ -0,0 +1,17 @@
-- =============================================================================
-- 028: Form slug is unique PER SPACE, not globally
-- =============================================================================
-- The public form URL is moving from /f/[slug] to /f/[space]/[slug], so the
-- form slug only needs to be unique within a space (and global uniqueness was
-- a cross-tenant slug-squatting footgun). Drop the global UNIQUE(slug) and add
-- UNIQUE(space_id, slug).
--
-- `forms_slug_key` is the auto-generated name for the inline column UNIQUE in
-- migration 026 / schema.sql. Idempotent: DROP IF EXISTS the old and the new
-- constraint, then ADD.
-- =============================================================================
ALTER TABLE public.forms DROP CONSTRAINT IF EXISTS forms_slug_key;
ALTER TABLE public.forms DROP CONSTRAINT IF EXISTS forms_space_slug_key;
ALTER TABLE public.forms
ADD CONSTRAINT forms_space_slug_key UNIQUE (space_id, slug);
+5 -3
View File
@@ -1899,7 +1899,7 @@ CREATE TRIGGER trg_prevent_member_self_role_change
CREATE TABLE IF NOT EXISTS public.forms (
id uuid PRIMARY KEY DEFAULT uuid_generate_v4(),
space_id uuid NOT NULL REFERENCES public.spaces(id) ON DELETE CASCADE,
slug text NOT NULL UNIQUE
slug text NOT NULL
CHECK (slug ~ '^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$'
AND char_length(slug) BETWEEN 1 AND 80),
title text NOT NULL CHECK (char_length(title) BETWEEN 1 AND 200),
@@ -1915,9 +1915,11 @@ CREATE TABLE IF NOT EXISTS public.forms (
version integer NOT NULL DEFAULT 1 CHECK (version >= 1),
created_by uuid REFERENCES public.space_members(id) ON DELETE SET NULL,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now()
updated_at timestamptz NOT NULL DEFAULT now(),
CONSTRAINT forms_space_slug_key UNIQUE (space_id, slug)
);
-- slug already has a UNIQUE btree index from the column constraint.
-- The UNIQUE(space_id, slug) constraint above also serves slug lookups
-- scoped to a space (the /f/[space]/[slug] public route).
CREATE INDEX IF NOT EXISTS idx_forms_space ON public.forms (space_id, status);
CREATE TABLE IF NOT EXISTS public.form_submissions (