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', () => { describe('getPublicFormSchema', () => {
it('validates the slug', () => { it('requires both a space and a valid form slug', () => {
expect(getPublicFormSchema.safeParse({ slug: 'a-form' }).success).toBe(true) expect(getPublicFormSchema.safeParse({ space: 'heatsynclabs', slug: 'a-form' }).success).toBe(true)
expect(getPublicFormSchema.safeParse({ slug: 'Bad' }).success).toBe(false) 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 }> }) { export default async function EditFormPage({ params }: { params: Promise<{ id: string }> }) {
const { id } = await params const { id } = await params
const { supabase, member } = await requireFormsManagerPage() const { supabase, member, spaceSlug } = await requireFormsManagerPage()
const { data: form } = await supabase const { data: form } = await supabase
.from('forms') .from('forms')
@@ -28,6 +28,7 @@ export default async function EditFormPage({ params }: { params: Promise<{ id: s
<FormBuilder <FormBuilder
initial={{ initial={{
id: form.id, id: form.id,
spaceSlug,
slug: form.slug, slug: form.slug,
title: form.title, title: form.title,
description: form.description ?? '', description: form.description ?? '',
+2 -2
View File
@@ -24,7 +24,7 @@ const VIS_LABEL: Record<string, string> = {
public_anon: 'Public', public_anon: 'Public',
} }
export function FormsClient({ forms }: { forms: FormRow[] }) { export function FormsClient({ forms, spaceSlug }: { forms: FormRow[]; spaceSlug: string }) {
return ( return (
<> <>
<PageHeader> <PageHeader>
@@ -65,7 +65,7 @@ export function FormsClient({ forms }: { forms: FormRow[] }) {
</Link> </Link>
{f.kind === 'waiver' && <Badge variant="secondary">Waiver</Badge>} {f.kind === 'waiver' && <Badge variant="secondary">Waiver</Badge>}
</div> </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> </div>
<Badge variant="outline">{VIS_LABEL[f.visibility] ?? f.visibility}</Badge> <Badge variant="outline">{VIS_LABEL[f.visibility] ?? f.visibility}</Badge>
<Badge variant={f.status === 'published' ? 'default' : 'secondary'}> <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 const dynamic = 'force-dynamic'
export default async function NewFormPage() { export default async function NewFormPage() {
await requireFormsManagerPage() const { spaceSlug } = await requireFormsManagerPage()
return ( return (
<> <>
@@ -15,6 +15,7 @@ export default async function NewFormPage() {
<div className="p-4 md:p-6"> <div className="p-4 md:p-6">
<FormBuilder <FormBuilder
initial={{ initial={{
spaceSlug,
slug: '', slug: '',
title: '', title: '',
description: '', description: '',
+2 -2
View File
@@ -4,7 +4,7 @@ import { FormsClient } from './forms-client'
export const dynamic = 'force-dynamic' export const dynamic = 'force-dynamic'
export default async function FormsPage() { export default async function FormsPage() {
const { supabase, member } = await requireFormsManagerPage() const { supabase, member, spaceSlug } = await requireFormsManagerPage()
const { data: forms } = await supabase const { data: forms } = await supabase
.from('forms') .from('forms')
@@ -12,5 +12,5 @@ export default async function FormsPage() {
.eq('space_id', member.space_id) .eq('space_id', member.space_id)
.order('created_at', { ascending: false }) .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 const dynamic = 'force-dynamic'
export default async function PublicFormPage({ params }: { params: Promise<{ slug: string }> }) { export default async function PublicFormPage({
const { slug } = await params params,
const res = await getPublicForm({ slug }) }: {
params: Promise<{ space: string; slug: string }>
}) {
const { space, slug } = await params
const res = await getPublicForm({ space, slug })
if ('error' in res && res.error) { if ('error' in res && res.error) {
return ( return (
@@ -29,7 +33,8 @@ export default async function PublicFormPage({ params }: { params: Promise<{ slu
return ( return (
<main className="mx-auto max-w-2xl p-4 md:p-8"> <main className="mx-auto max-w-2xl p-4 md:p-8">
<PublicFormClient <PublicFormClient
slug={form.slug} formId={form.id}
nextPath={`/f/${space}/${slug}`}
title={form.title} title={form.title}
description={form.description} description={form.description}
kind={form.kind} kind={form.kind}
@@ -9,7 +9,8 @@ import { submitForm } from '@/lib/actions'
import type { FormField } from '@/lib/forms-schema' import type { FormField } from '@/lib/forms-schema'
export function PublicFormClient({ export function PublicFormClient({
slug, formId,
nextPath,
title, title,
description, description,
kind, kind,
@@ -18,7 +19,8 @@ export function PublicFormClient({
fields, fields,
authed, authed,
}: { }: {
slug: string formId: string
nextPath: string
title: string title: string
description: string | null description: string | null
kind: string kind: string
@@ -41,8 +43,10 @@ export function PublicFormClient({
async function submit() { async function submit() {
setError(null) setError(null)
setSubmitting(true) setSubmitting(true)
// Submit by formId: form slugs are only unique per space now, so id is
// the unambiguous handle.
const res = await submitForm({ const res = await submitForm({
slug, formId,
answers: values, answers: values,
email: showEmail && email ? email : undefined, email: showEmail && email ? email : undefined,
consent: isWaiver ? consent : undefined, consent: isWaiver ? consent : undefined,
@@ -75,7 +79,7 @@ export function PublicFormClient({
<div className="rounded-lg border bg-muted/40 p-6 text-center"> <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> <p className="text-sm">You need to be signed in to submit this form.</p>
<Button asChild className="mt-3"> <Button asChild className="mt-3">
<a href={`/login?next=/f/${slug}`}>Sign in</a> <a href={`/login?next=${encodeURIComponent(nextPath)}`}>Sign in</a>
</Button> </Button>
</div> </div>
) : ( ) : (
+4 -2
View File
@@ -29,6 +29,7 @@ type Status = 'draft' | 'published' | 'closed'
export type BuilderForm = { export type BuilderForm = {
id?: string id?: string
spaceSlug: string
slug: string slug: string
title: string title: string
description: string description: string
@@ -171,8 +172,9 @@ export function FormBuilder({ initial }: { initial: BuilderForm }) {
router.refresh() router.refresh()
} }
const publicPath = `/f/${initial.spaceSlug}/${initial.slug}`
const publicUrl = const publicUrl =
typeof window !== 'undefined' ? `${window.location.origin}/f/${initial.slug}` : `/f/${initial.slug}` typeof window !== 'undefined' ? `${window.location.origin}${publicPath}` : publicPath
return ( return (
<div className="grid gap-6 lg:grid-cols-2"> <div className="grid gap-6 lg:grid-cols-2">
@@ -240,7 +242,7 @@ export function FormBuilder({ initial }: { initial: BuilderForm }) {
{isEdit ? ( {isEdit ? (
<p className="text-xs text-muted-foreground">The slug cannot change after creation.</p> <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>
<div className="space-y-1.5"> <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 } if (!v.ok) return { error: v.error }
const admin = createAdminClient() 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 const { data: form } = await admin
.from('forms') .from('forms')
.select('id, slug, title, description, kind, visibility, schema, legal_text, version, status') .select('id, slug, title, description, kind, visibility, schema, legal_text, version, status')
.eq('space_id', space.id)
.eq('slug', v.data.slug) .eq('slug', v.data.slug)
.single() .maybeSingle()
// Members-only forms are never served on the public page (that would expose // Members-only forms are never served on the public page (that would expose
// their schema to anyone). They are filled from inside the app. // 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 const { data: member } = await supabase
.from('space_members') .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) .eq('user_id', user.id)
.in('status', ['current', 'unverified', 'late']) .in('status', ['current', 'unverified', 'late'])
.single() .single()
@@ -28,5 +28,6 @@ export async function requireFormsManagerPage() {
}) })
if (!allowed) redirect('/dashboard') 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(), 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 ────────────────────────────────────────────────────── // ─── 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 ( CREATE TABLE IF NOT EXISTS public.forms (
id uuid PRIMARY KEY DEFAULT uuid_generate_v4(), id uuid PRIMARY KEY DEFAULT uuid_generate_v4(),
space_id uuid NOT NULL REFERENCES public.spaces(id) ON DELETE CASCADE, 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])?$' CHECK (slug ~ '^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$'
AND char_length(slug) BETWEEN 1 AND 80), AND char_length(slug) BETWEEN 1 AND 80),
title text NOT NULL CHECK (char_length(title) BETWEEN 1 AND 200), 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), version integer NOT NULL DEFAULT 1 CHECK (version >= 1),
created_by uuid REFERENCES public.space_members(id) ON DELETE SET NULL, created_by uuid REFERENCES public.space_members(id) ON DELETE SET NULL,
created_at timestamptz NOT NULL DEFAULT now(), 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 INDEX IF NOT EXISTS idx_forms_space ON public.forms (space_id, status);
CREATE TABLE IF NOT EXISTS public.form_submissions ( CREATE TABLE IF NOT EXISTS public.form_submissions (