feat(white-label): invite-only signup for brand domains (#1995)

* feat(white-label): invite-only signup for brand domains

A brand domain belongs to the partner's people (founder decision
2026-08-27): only allowlisted or invited users may create an account on
an invite-only brand domain; everyone else is shown an interstitial that
sends them to the canonical Accounted signup.

- brands.signup_mode ('open' default / 'invite_only') +
  brand_signup_allowlist (lowercase emails, team-scoped RLS, owner/admin
  writes) + create_company_for_brand_signup RPC, with pg-real coverage
- server-side gate (lib/auth/brand-signup-gate.ts) enforced on every
  signup path: email signup moved to POST /api/auth/signup (the browser
  used to call GoTrue directly, so a client-side check would be
  bypassable), BankID gated in /bankid/complete, Google covered by the
  dashboard layout's brand-domain bounce
- company invites bypass the allowlist: the invite is the authorization
- register page interstitial on gated brands (no email in the outbound
  URL), sv+en strings
- dashboard layout bounces non-belonging sessions off gated brand hosts
  to the canonical domain (navigation rule like WL-01, not a security
  boundary)
- allowlisted signups' onboarding-created companies attach to the
  brand's byra team via the new RPC, so WL-01 homes them on the brand
  domain; the allowlist entry recorded by an owner/admin stands in for
  the WL-15 admin gate
- byra cockpit page /clients/access + /api/clients/signup-access to
  manage the mode and the allowlist

All existing brands default to 'open': behavior is byte-identical until
a brand is flipped to invite_only.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ByL5dQXG8gGLtNBPj8g2C4

* fix(white-label): rollback brand-signup company with the service client

Skeptic (correctness) found that a brand-signup company created under the
service role rolled back with the cookie-session client: `companies` has
RLS and no FOR DELETE policy, so the delete was a silent 0-row no-op,
stranding a member-less ghost company on the partner's byra team. Pass an
optional rollbackClient to createCompanyCore and hand it the service
client on that path; user_preferences.active_company_id then clears itself
via its ON DELETE SET NULL FK once the company row is actually deleted.

Also map a validateBody 400 (flat envelope, no code) on the register page
to the specific email-invalid field message instead of the generic one,
since the client already pre-gates password strength.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ByL5dQXG8gGLtNBPj8g2C4

* fix(white-label): fail-safe brand lookup, pg-test seed, anonymize fixtures

Second resolve-pr cycle: skeptic + CodeRabbit findings and a green-up.

- Fail safe on a brands-table error (CodeRabbit CWE-285): the gate treated a
  failed resolveBrandByHost as an unbranded host, opening invite-only signup
  during a transient DB blip. resolveBrandResultByHost now distinguishes
  "no brand" from "lookup failed"; the gate returns lookupFailed and the
  email + BankID routes answer 503 (retry), never creating an account.
- pg-real: the RLS delete test seeded its row inside withUserContext, which
  always rolls back, so the owner DELETE saw zero rows. Seed on the superuser
  pool instead.
- Anonymize every test/fixture brand to the repo's existing synthetic
  placeholder (Siffra / app.siffra.se): no real partner names in code.
- SignupAccessManager: functional setData updates so a concurrent mode
  toggle and an add/remove do not clobber each other's snapshot (CodeRabbit).
- Route a transient-error message through i18n instead of the raw envelope
  (raw-user-error guard); new register.error_temporary sv+en.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ByL5dQXG8gGLtNBPj8g2C4

* test(white-label): anonymize new signup-gate fixtures; log oracle residual

Rename the placeholder brand in the four new brand-signup test files to a
clearly-fake, partner-unrelated name (Testbrand / app.testbrand.example);
the previous placeholder echoed a real partner. Scoped to files this PR
creates; the repo-wide legacy placeholder is left for a separate cleanup.

Also record in DECISIONS.md that the feature ships accepting the
low-severity allowlist-enumeration residual (captcha-free 403 vs 200 on
the signup endpoint), with rate-limiting as the follow-up option.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ByL5dQXG8gGLtNBPj8g2C4

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Mattsson
2026-08-27 18:32:52 +02:00
committed by GitHub
co-authored by Claude Fable 5
parent 325c827322
commit 4f6ecad549
28 changed files with 2495 additions and 44 deletions
+107 -17
View File
@@ -77,6 +77,9 @@ function RegisterPageContent() {
const [isCancelling, setIsCancelling] = useState(false)
const [isRegistered, setIsRegistered] = useState(false)
const [duplicateEmail, setDuplicateEmail] = useState<string | null>(null)
// Invite-only brand domain (signup gate said no): the form is replaced by
// an interstitial pointing at the canonical Accounted signup.
const [inviteOnlyBlocked, setInviteOnlyBlocked] = useState(false)
const [inviteEmail, setInviteEmail] = useState<string | null>(null)
const [bankIdUser, setBankIdUser] = useState<{ givenName?: string; surname?: string } | null>(null)
const [bankIdFlowId, setBankIdFlowId] = useState<string | null>(null)
@@ -220,6 +223,11 @@ function RegisterPageContent() {
const json = await res.json()
if (!res.ok) {
if (json.error === 'signup_not_allowed') {
// Invite-only brand domain: same interstitial as the email path.
setInviteOnlyBlocked(true)
return
}
if (json.error === 'already_linked') {
// email_exists kind: the alert renders a sign-in link, which is the
// recovery path for both "BankID taken" and "email taken".
@@ -335,20 +343,51 @@ function RegisterPageContent() {
setIsLoading(true)
try {
// The confirmation link lands on /auth/callback; carry the consent
// destination along so the confirmed session resumes it.
const confirmationCallback = new URL('/auth/callback', window.location.origin)
if (nextPath !== '/') confirmationCallback.searchParams.set('next', nextPath)
const { data, error } = await supabase.auth.signUp({
email: emailValue,
password: passwordValue,
options: {
emailRedirectTo: confirmationCallback.toString(),
...captchaTokenOptions(captchaToken),
},
// Server-side signup (POST /api/auth/signup): the route performs the
// GoTrue signUp and enforces the invite-only brand-domain gate, which
// a direct browser call to Supabase would bypass. It builds the
// /auth/callback confirmation URL from the request host and carries
// `next` along, so the mail flow is unchanged.
const res = await fetch('/api/auth/signup', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
email: emailValue,
password: passwordValue,
captchaToken: captchaTokenOptions(captchaToken).captchaToken ?? null,
next: nextPath !== '/' ? nextPath : null,
}),
})
const json = await res.json().catch(() => ({}))
if (error) {
if (!res.ok) {
const error = {
code: json?.error?.code,
message: json?.error?.message ?? t('register_failed_default'),
status: res.status,
}
if (error.code === 'signup_not_allowed') {
// Invite-only brand domain: swap the form for the interstitial
// that sends the visitor to the canonical Accounted signup.
setInviteOnlyBlocked(true)
return
}
if (error.code === 'brand_lookup_failed') {
// Transient brand-lookup error (the gate failed safe rather than
// guess). Ask the user to retry instead of implying they were
// turned away. Localized here, not from the raw response envelope.
setFormError({ kind: 'unknown', message: t('error_temporary') })
return
}
// The route's validateBody rejection is a flat envelope with no
// `code`; the client already gates password strength and presence
// before this fetch, so a 400 without a code is an email Zod
// rejected (e.g. user@localhost, which passes the browser's
// type=email). Surface the specific field message, not the generic.
if (!error.code && res.status === 400) {
setFormError({ kind: 'email_invalid', message: t('error_email_invalid') })
return
}
console.error('[register] signUp error', error.message)
const kind = classifyAuthError(error)
if (kind === 'weak_password') {
@@ -375,7 +414,7 @@ function RegisterPageContent() {
persistLoginMethodHint('email')
// If auto-confirmed (local dev), process invite immediately and redirect
if (data.session) {
if (json?.data?.status === 'session') {
const cookieMatch = document.cookie.match(/gnubok-invite-token=([^;]+)/)
const inviteToken = cookieMatch?.[1]
@@ -405,10 +444,10 @@ function RegisterPageContent() {
}
// Supabase obfuscates duplicate signups (to prevent user enumeration):
// when the email already belongs to a confirmed account, it returns
// data.user with identities: [] and no error, and sends no email.
// Detect that case so we don't show a misleading "check your email" screen.
if (data.user && (data.user.identities?.length ?? 0) === 0) {
// when the email already belongs to a confirmed account, no mail is
// sent. The route surfaces that as 'duplicate' so we don't show a
// misleading "check your email" screen.
if (json?.data?.status === 'duplicate') {
setDuplicateEmail(emailValue)
return
}
@@ -427,6 +466,57 @@ function RegisterPageContent() {
}
}
if (inviteOnlyBlocked) {
// Deliberately no email in the outbound URL: the canonical register page
// never reads one, and an address in a URL lands in browser history,
// Referer headers and proxy logs. The visitor retypes it.
const canonicalRegisterHref = `${branding.appUrl.replace(/\/+$/, '')}/register`
return (
<div className="min-h-dvh flex flex-col items-center justify-center bg-frame p-4">
<div className="w-full max-w-sm animate-slide-up space-y-8">
<div className="flex justify-center">
<div className="h-14 w-14 rounded-xl bg-primary/8 flex items-center justify-center">
<Mail className="h-7 w-7 text-primary" />
</div>
</div>
<div className="text-center space-y-2">
<h1 className="text-2xl tracking-tight">
{t('invite_only_title', { appName: branding.appName })}
</h1>
<p className="text-muted-foreground text-sm leading-relaxed">
{t('invite_only_body', { appName: branding.appName })}
</p>
</div>
<div className="rounded-xl border border-border bg-background p-4">
<p className="text-sm text-muted-foreground text-center leading-relaxed">
{t('invite_only_hint')}
</p>
</div>
<div className="space-y-2">
<Button className="w-full" asChild>
<a href={canonicalRegisterHref}>
{t('invite_only_cta')}
<ExternalLink className="ml-2 h-4 w-4" />
</a>
</Button>
<Button
variant="ghost"
className="w-full text-muted-foreground"
onClick={() => setInviteOnlyBlocked(false)}
>
<ArrowLeft className="mr-2 h-4 w-4" />
{t('back')}
</Button>
</div>
</div>
</div>
)
}
if (duplicateEmail) {
return (
<div className="min-h-dvh flex flex-col items-center justify-center bg-frame p-4">
@@ -0,0 +1,290 @@
'use client'
import { useCallback, useEffect, useState } from 'react'
import { useTranslations } from 'next-intl'
import { Loader2, Plus, X } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Switch } from '@/components/ui/switch'
import { Skeleton } from '@/components/ui/skeleton'
import { TD_CLASS, TH_CLASS } from '@/components/ui/dry-table'
import { useToast } from '@/components/ui/use-toast'
import { formatDate } from '@/lib/utils'
interface AllowlistEntry {
id: string
email: string
note: string | null
created_at: string
}
interface AccessData {
brand: { domain: string; appName: string; signupMode: 'open' | 'invite_only' }
role: 'owner' | 'admin' | 'member'
entries: AllowlistEntry[]
}
/**
* Invite-only signup management (2026-08-27): the mode switch and the email
* allowlist for the byrå's brand domain. Company invites bypass the list, so
* this list only governs who can create an account cold on the domain.
*/
export default function SignupAccessManager({ canEdit }: { canEdit: boolean }) {
const t = useTranslations('clients')
const { toast } = useToast()
const [data, setData] = useState<AccessData | null>(null)
const [loadError, setLoadError] = useState<'no_brand' | 'failed' | null>(null)
const [savingMode, setSavingMode] = useState(false)
const [adding, setAdding] = useState(false)
const [removingId, setRemovingId] = useState<string | null>(null)
const [email, setEmail] = useState('')
const [note, setNote] = useState('')
const load = useCallback(async () => {
try {
const res = await fetch('/api/clients/signup-access', { cache: 'no-store' })
if (res.status === 404) {
setLoadError('no_brand')
return
}
if (!res.ok) {
setLoadError('failed')
return
}
const json = (await res.json()) as { data: AccessData }
setData(json.data)
setLoadError(null)
} catch {
setLoadError('failed')
}
}, [])
useEffect(() => {
void load()
}, [load])
const toggleMode = async (inviteOnly: boolean) => {
if (!data) return
setSavingMode(true)
const previous = data.brand.signupMode
setData({
...data,
brand: { ...data.brand, signupMode: inviteOnly ? 'invite_only' : 'open' },
})
try {
const res = await fetch('/api/clients/signup-access', {
method: 'PATCH',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ signup_mode: inviteOnly ? 'invite_only' : 'open' }),
})
if (!res.ok) throw new Error(`PATCH failed: ${res.status}`)
} catch {
setData((current) =>
current
? { ...current, brand: { ...current.brand, signupMode: previous } }
: current,
)
toast({ title: t('access_save_failed'), variant: 'destructive' })
} finally {
setSavingMode(false)
}
}
const addEntry = async (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault()
if (!email.trim() || !data) return
setAdding(true)
try {
const res = await fetch('/api/clients/signup-access', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
email: email.trim(),
note: note.trim() || undefined,
}),
})
const json = await res.json().catch(() => ({}))
if (!res.ok) {
toast({
title:
res.status === 409
? t('access_duplicate')
: t('access_save_failed'),
variant: 'destructive',
})
return
}
// Functional update: a concurrent mode toggle or remove must not be
// clobbered by the `data` snapshot captured when this request started.
setData((current) =>
current
? { ...current, entries: [json.data as AllowlistEntry, ...current.entries] }
: current,
)
setEmail('')
setNote('')
} catch {
toast({ title: t('access_save_failed'), variant: 'destructive' })
} finally {
setAdding(false)
}
}
const removeEntry = async (id: string) => {
if (!data) return
setRemovingId(id)
try {
const res = await fetch('/api/clients/signup-access', {
method: 'DELETE',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ id }),
})
if (!res.ok) throw new Error(`DELETE failed: ${res.status}`)
// Functional update: see addEntry. Avoids clobbering a concurrent
// mode toggle or add with a stale snapshot.
setData((current) =>
current
? { ...current, entries: current.entries.filter((entry) => entry.id !== id) }
: current,
)
} catch {
toast({ title: t('access_save_failed'), variant: 'destructive' })
} finally {
setRemovingId(null)
}
}
if (loadError === 'no_brand') {
return <p className="text-sm text-muted-foreground">{t('access_no_brand')}</p>
}
if (loadError === 'failed') {
return <p className="text-sm text-muted-foreground">{t('access_load_failed')}</p>
}
if (!data) {
return (
<div className="space-y-4">
<Skeleton className="h-10 w-full" />
<Skeleton className="h-10 w-2/3" />
<Skeleton className="h-24 w-full" />
</div>
)
}
const inviteOnly = data.brand.signupMode === 'invite_only'
return (
<div className="space-y-8">
<div className="rounded-lg border border-border p-6 space-y-1">
<div className="flex items-center justify-between gap-4">
<div>
<p className="text-sm font-medium">
{t('access_mode_label', { domain: data.brand.domain })}
</p>
<p className="text-[13px] text-muted-foreground leading-relaxed mt-1">
{t('access_mode_hint')}
</p>
</div>
<Switch
checked={inviteOnly}
disabled={!canEdit || savingMode}
onCheckedChange={(checked) => void toggleMode(checked)}
aria-label={t('access_mode_label', { domain: data.brand.domain })}
/>
</div>
{!canEdit && (
<p className="text-xs text-muted-foreground">{t('access_readonly_hint')}</p>
)}
</div>
<section className="space-y-4">
<h2 className="text-sm font-medium uppercase tracking-wider text-muted-foreground">
{t('access_list_heading')}
</h2>
{canEdit && (
<form onSubmit={addEntry} className="flex flex-wrap items-end gap-3">
<div className="space-y-2">
<Label htmlFor="allowlist-email">{t('access_col_email')}</Label>
<Input
id="allowlist-email"
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
placeholder={t('access_add_placeholder')}
required
disabled={adding}
className="w-64"
/>
</div>
<div className="space-y-2">
<Label htmlFor="allowlist-note">{t('access_col_note')}</Label>
<Input
id="allowlist-note"
value={note}
onChange={(e) => setNote(e.target.value)}
placeholder={t('access_add_note_placeholder')}
disabled={adding}
className="w-56"
/>
</div>
<Button type="submit" disabled={adding || !email.trim()}>
{adding ? (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
) : (
<Plus className="mr-2 h-4 w-4" />
)}
{t('access_add')}
</Button>
</form>
)}
{data.entries.length === 0 ? (
<p className="text-sm text-muted-foreground">{t('access_empty')}</p>
) : (
<table className="w-full border-collapse text-[13px]">
<thead>
<tr>
<th className={TH_CLASS}>{t('access_col_email')}</th>
<th className={TH_CLASS}>{t('access_col_note')}</th>
<th className={TH_CLASS}>{t('access_col_added')}</th>
{canEdit && <th className={TH_CLASS} aria-hidden />}
</tr>
</thead>
<tbody>
{data.entries.map((entry) => (
<tr key={entry.id} className="hover:bg-secondary/35">
<td className={TD_CLASS}>{entry.email}</td>
<td className={`${TD_CLASS} text-muted-foreground`}>
{entry.note || ''}
</td>
<td className={`${TD_CLASS} tabular-nums text-muted-foreground`}>
{formatDate(entry.created_at)}
</td>
{canEdit && (
<td className={`${TD_CLASS} text-right`}>
<Button
type="button"
variant="ghost"
size="icon"
aria-label={t('access_remove')}
disabled={removingId === entry.id}
onClick={() => void removeEntry(entry.id)}
>
{removingId === entry.id ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
<X className="h-4 w-4" />
)}
</Button>
</td>
)}
</tr>
))}
</tbody>
</table>
)}
</section>
</div>
)
}
+37
View File
@@ -0,0 +1,37 @@
import { redirect } from 'next/navigation'
import { getTranslations } from 'next-intl/server'
import { PageHeader } from '@/components/ui/page-header'
import { getByraMembership } from '@/lib/clients/fetch-client-overview'
import { getDashboardAuthContext } from '../../request-context'
import SignupAccessManager from './SignupAccessManager'
export const dynamic = 'force-dynamic'
/**
* Byrå cockpit: invite-only signup management for the team's brand domain
* (2026-08-27). Any byrå team member may look; owner/admin may change the
* mode and the allowlist (the API and RLS both enforce that). Non-byrå
* users are redirected like the rest of the cockpit.
*/
export default async function SignupAccessPage() {
const { supabase, user } = await getDashboardAuthContext()
if (!user) {
redirect('/login')
}
const membership = await getByraMembership(supabase, user.id)
if (!membership) {
redirect('/')
}
const t = await getTranslations('clients')
return (
<div className="space-y-8">
<PageHeader title={t('access_title')} />
<SignupAccessManager
canEdit={membership.role === 'owner' || membership.role === 'admin'}
/>
</div>
)
}
+10 -1
View File
@@ -1,5 +1,7 @@
import { redirect } from 'next/navigation'
import Link from 'next/link'
import { getTranslations } from 'next-intl/server'
import { Button } from '@/components/ui/button'
import { PageHeader } from '@/components/ui/page-header'
import { fetchClientOverview } from '@/lib/clients/fetch-client-overview'
import { getDashboardAuthContext } from '../request-context'
@@ -34,7 +36,14 @@ export default async function ClientsPage() {
<div className="space-y-8">
<PageHeader
title={t('title')}
action={canCreate ? <NewClientCompanyButton /> : undefined}
action={
<div className="flex items-center gap-2">
<Button variant="ghost" className="text-muted-foreground" asChild>
<Link href="/clients/access">{t('access_link')}</Link>
</Button>
{canCreate && <NewClientCompanyButton />}
</div>
}
/>
<ClientsTable clients={overview.clients} />
</div>
+31 -6
View File
@@ -1,5 +1,5 @@
import { redirect } from 'next/navigation'
import { headers } from 'next/headers'
import { cookies, headers } from 'next/headers'
import DashboardNav from '@/components/dashboard/DashboardNav'
import { MainContainer } from '@/components/dashboard/MainContainer'
import CompanyTabSync from '@/components/dashboard/CompanyTabSync'
@@ -19,6 +19,8 @@ import { getCompanyEntitlements } from '@/lib/entitlements/has-capability'
import { getDashboardNavFlags } from '@/lib/dashboard/nav-flags'
import { getBranding } from '@/lib/branding/service'
import { resolveBrandByHost } from '@/lib/branding/resolve'
import { resolveBrandDomainBounce } from '@/lib/auth/brand-signup-gate'
import { INVITE_COOKIE_NAME } from '@/lib/auth/consume-invite-cookie'
import { resolveBrandsForTeams } from '@/lib/branding/team-brands'
import {
partitionCompaniesByHomeDomain,
@@ -133,6 +135,31 @@ export default async function DashboardLayout({
null
const isTeamMember = membershipRows.length > 0
// Invite-only brand-domain gate (2026-08-27): on a gated brand host, a
// session with no tie to the brand (team, company, allowlist entry, or
// pending invite) is sent to the canonical domain instead of getting a
// branded shell. Runs before the zero-company branch below, because that
// branch would otherwise walk a stranger into /onboarding under the
// partner's brand. Navigation-level like WL-01; RLS is the data boundary.
const hostHeader =
headerStore.get('x-forwarded-host') ?? headerStore.get('host') ?? ''
const bounceUrl = await resolveBrandDomainBounce({
host: hostHeader,
userEmail: user.email,
teamIds: membershipRows
.map((m) => m.teams?.id)
.filter((id): id is string => typeof id === 'string'),
companyTeamIds: (allMemberships || []).map(
(m) => (m.companies as { team_id?: string | null } | null)?.team_id,
),
hasPendingInviteCookie:
(await cookies()).get(INVITE_COOKIE_NAME)?.value != null,
canonicalAppUrl: getBranding().appUrl,
})
if (bounceUrl) {
redirect(bounceUrl)
}
// No companies: redirect to onboarding, except for allowed escape-hatch
// routes (so the user can still reach /settings/account to delete their
// account after archiving their last company) and byrå team members (any
@@ -206,11 +233,9 @@ export default async function DashboardLayout({
// Home-domain rule (WL-01): which brand serves this host, and which brand
// (if any) each membership company's team owns. Both resolvers are ~60s
// cached; unknown hosts and brandless teams resolve to null/absent, so the
// canonical no-brands hot path stays byte-identical. Both only depend on
// wave-1 data, so they ride in the wave-2 batch below.
const hostHeader =
headerStore.get('x-forwarded-host') ?? headerStore.get('host') ?? ''
// cached (the domain-gate lookup above already warmed the host entry);
// unknown hosts and brandless teams resolve to null/absent, so the
// canonical no-brands hot path stays byte-identical.
// Wave 2: everything keyed on the company. Nav badge counts are NOT fetched
// here: DashboardNav loads them client-side after mount
@@ -46,6 +46,7 @@ function makeBrand(overrides: Partial<Brand> = {}): Brand {
senderDomain: 'post.siffra.se',
senderDomainStatus: 'verified',
resendDomainId: 'rd-1',
signupMode: 'open',
...overrides,
}
}
+179
View File
@@ -0,0 +1,179 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { parseJsonResponse } from '@/tests/helpers'
const signUpMock = vi.hoisted(() => vi.fn())
vi.mock('@/lib/supabase/server', () => ({
createClient: vi.fn(async () => ({ auth: { signUp: signUpMock } })),
}))
const gateMock = vi.hoisted(() => vi.fn())
vi.mock('@/lib/auth/brand-signup-gate', async (importOriginal) => {
const actual =
await importOriginal<typeof import('@/lib/auth/brand-signup-gate')>()
return {
...actual,
evaluateBrandSignupGate: (...args: unknown[]) => gateMock(...args),
}
})
import { POST } from '../route'
function makeRequest(
body: unknown,
headers: Record<string, string> = {},
): Request {
return new Request('https://internal/api/auth/signup', {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...headers },
body: JSON.stringify(body),
})
}
const validBody = { email: 'kund@example.com', password: 'Str0ng!Pass' }
beforeEach(() => {
vi.clearAllMocks()
gateMock.mockResolvedValue({ allowed: true, brand: null, via: 'no_brand' })
signUpMock.mockResolvedValue({
data: { user: { identities: [{ id: 'i1' }] }, session: null },
error: null,
})
})
describe('POST /api/auth/signup', () => {
it('400s on invalid body', async () => {
const res = await POST(makeRequest({ email: 'not-an-email', password: 'x' }))
expect(res.status).toBe(400)
expect(signUpMock).not.toHaveBeenCalled()
})
it('403s with signup_not_allowed when the gate blocks', async () => {
gateMock.mockResolvedValue({ allowed: false, brand: { id: 'brand-1' } })
const res = await POST(
makeRequest(validBody, { host: 'app.testbrand.example' }),
)
const { body: json } = await parseJsonResponse<{ error: { code: string } }>(res)
expect(res.status).toBe(403)
expect(json.error.code).toBe('signup_not_allowed')
expect(signUpMock).not.toHaveBeenCalled()
})
it('503s (fail safe) when the brand lookup errors, without creating an account', async () => {
gateMock.mockResolvedValue({ allowed: false, brand: null, lookupFailed: true })
const res = await POST(
makeRequest(validBody, { host: 'app.testbrand.example' }),
)
const { body: json } = await parseJsonResponse<{ error: { code: string } }>(res)
expect(res.status).toBe(503)
expect(json.error.code).toBe('brand_lookup_failed')
expect(signUpMock).not.toHaveBeenCalled()
})
it('feeds the gate the forwarded host, normalized email and invite cookie', async () => {
await POST(
makeRequest(
{ ...validBody, email: ' Kund@Example.COM ' },
{
host: 'internal',
'x-forwarded-host': 'app.testbrand.example',
cookie: 'gnubok-invite-token=gnubok_inv_x',
},
),
)
expect(gateMock).toHaveBeenCalledWith({
host: 'app.testbrand.example',
email: 'kund@example.com',
inviteToken: 'gnubok_inv_x',
})
})
it('signs up with a confirmation callback on the originating host', async () => {
const res = await POST(
makeRequest(validBody, {
'x-forwarded-host': 'app.testbrand.example',
'x-forwarded-proto': 'https',
}),
)
const { body: json } = await parseJsonResponse<{ data: { status: string } }>(res)
expect(res.status).toBe(200)
expect(json.data.status).toBe('confirmation_sent')
expect(signUpMock).toHaveBeenCalledWith({
email: 'kund@example.com',
password: 'Str0ng!Pass',
options: {
emailRedirectTo: 'https://app.testbrand.example/auth/callback',
},
})
})
it('forwards the captcha token and a safe next path', async () => {
await POST(
makeRequest(
{ ...validBody, captchaToken: 'tok', next: '/api/mcp-oauth/authorize?x=1' },
{ host: 'app.accounted.se' },
),
)
const call = signUpMock.mock.calls[0][0]
expect(call.options.captchaToken).toBe('tok')
expect(call.options.emailRedirectTo).toBe(
'https://app.accounted.se/auth/callback?next=%2Fapi%2Fmcp-oauth%2Fauthorize%3Fx%3D1',
)
})
it('drops an unsafe next path instead of forwarding it', async () => {
await POST(
makeRequest(
{ ...validBody, next: 'https://evil.example.com/phish' },
{ host: 'app.accounted.se' },
),
)
const call = signUpMock.mock.calls[0][0]
expect(call.options.emailRedirectTo).toBe(
'https://app.accounted.se/auth/callback',
)
})
it('maps a GoTrue error to the canonical envelope', async () => {
signUpMock.mockResolvedValue({
data: { user: null, session: null },
error: { code: 'weak_password', message: 'Password is too weak', status: 422 },
})
const res = await POST(makeRequest(validBody, { host: 'app.accounted.se' }))
const { body: json } = await parseJsonResponse<{ error: { code: string; message: string } }>(res)
expect(res.status).toBe(422)
expect(json.error.code).toBe('weak_password')
})
it('reports duplicate for the obfuscated existing-account response', async () => {
signUpMock.mockResolvedValue({
data: { user: { identities: [] }, session: null },
error: null,
})
const res = await POST(makeRequest(validBody, { host: 'app.accounted.se' }))
const { body: json } = await parseJsonResponse<{ data: { status: string } }>(res)
expect(json.data.status).toBe('duplicate')
})
it('reports session for auto-confirmed signups', async () => {
signUpMock.mockResolvedValue({
data: { user: { identities: [{ id: 'i1' }] }, session: { access_token: 'x' } },
error: null,
})
const res = await POST(makeRequest(validBody, { host: 'app.accounted.se' }))
const { body: json } = await parseJsonResponse<{ data: { status: string } }>(res)
expect(json.data.status).toBe('session')
})
})
+131
View File
@@ -0,0 +1,131 @@
import { NextResponse } from 'next/server'
import { z } from 'zod'
import { createClient } from '@/lib/supabase/server'
import { validateBody } from '@/lib/api/validate'
import {
evaluateBrandSignupGate,
readInviteTokenFromCookieHeader,
} from '@/lib/auth/brand-signup-gate'
import { safeReturnTo } from '@/lib/auth/safe-return-to'
import { getErrorMessage } from '@/lib/errors/get-error-message'
import { createLogger } from '@/lib/logger'
const log = createLogger('auth-signup')
/**
* POST /api/auth/signup: email+password signup, moved server-side so the
* invite-only brand-domain gate (lib/auth/brand-signup-gate.ts) cannot be
* bypassed. The register page used to call supabase.auth.signUp straight
* from the browser; that call never touched Next.js, so any host-based
* gating there would have been cosmetic. This route is now the only
* email-signup path on every host: on canonical and open-brand hosts the
* behavior is byte-identical to the old direct call (same GoTrue request,
* same captcha, same emailRedirectTo shape), on invite-only brand hosts it
* refuses with signup_not_allowed unless the email is allowlisted or a
* valid invite cookie rides along.
*
* Anonymous by design: there is no session to authenticate at signup time,
* so no withRouteContext / requireAuth. Abuse is bounded the same way the
* direct GoTrue call was: the forwarded Turnstile token (verified by
* GoTrue) plus GoTrue's own signup rate limits.
*/
const SignupSchema = z.object({
email: z.string().trim().toLowerCase().max(320).pipe(z.string().email()),
password: z.string().min(8).max(256),
captchaToken: z.string().max(4096).nullish(),
/** Post-signup resume path (MCP OAuth consent); same-origin enforced. */
next: z.string().max(2048).nullish(),
})
export async function POST(request: Request) {
const validation = await validateBody(request, SignupSchema)
if (!validation.success) return validation.response
const { email, password, captchaToken } = validation.data
const host =
request.headers.get('x-forwarded-host') ?? request.headers.get('host') ?? ''
// The invite cookie is set by /invite/[token] before it redirects to
// /register, so an invitee's signup carries it automatically.
const inviteToken = readInviteTokenFromCookieHeader(request.headers.get('cookie'))
const gate = await evaluateBrandSignupGate({ host, email, inviteToken })
if (!gate.allowed && 'lookupFailed' in gate) {
// Transient brands-table error: fail safe, do not create the account.
// 503 tells the client to retry rather than the misleading "not allowed".
return NextResponse.json(
{
error: {
code: 'brand_lookup_failed',
message: 'Tillfälligt fel. Försök igen om en stund.',
message_en: 'Temporary error. Please try again shortly.',
},
},
{ status: 503 },
)
}
if (!gate.allowed) {
return NextResponse.json(
{
error: {
code: 'signup_not_allowed',
// Brand-neutral copy: the interstitial on the register page owns
// the user-facing story; this message is the API-level fallback.
message: 'Registrering på den här domänen kräver inbjudan.',
message_en: 'Signing up on this domain requires an invitation.',
},
},
{ status: 403 },
)
}
// Confirmation links must land back on the ORIGINATING host (WL-05 brand
// mail resolves its brand from this URL), so build the callback from the
// forwarded host rather than request.url, which can be an internal origin
// behind the proxy.
const proto = request.headers.get('x-forwarded-proto') ?? 'https'
const confirmationCallback = new URL(`${proto}://${host}/auth/callback`)
const nextPath = safeReturnTo(validation.data.next ?? null, '/')
if (nextPath !== '/') confirmationCallback.searchParams.set('next', nextPath)
const supabase = await createClient()
const { data, error } = await supabase.auth.signUp({
email,
password,
options: {
emailRedirectTo: confirmationCallback.toString(),
...(captchaToken ? { captchaToken } : {}),
},
})
if (error) {
log.warn('signUp rejected', { status: error.status, code: error.code })
// The register page feeds this envelope to classifyAuthError, which
// keys on the GoTrue code (and the HTTP status); the display message is
// localized through getErrorMessage like every other auth surface.
return NextResponse.json(
{
error: {
code: error.code ?? 'auth_error',
message: getErrorMessage(error, { context: 'auth', locale: 'sv' }),
message_en: getErrorMessage(error, { context: 'auth', locale: 'en' }),
},
},
{ status: error.status && error.status >= 400 ? error.status : 400 },
)
}
// Supabase obfuscates duplicate signups (anti-enumeration): a confirmed
// existing email returns a user with identities: [] and sends no mail.
// Surface that as a distinct status so the page can skip the misleading
// "check your email" screen; the information is the same the browser call
// exposed, so nothing new leaks.
const status = data.session
? 'session'
: data.user && (data.user.identities?.length ?? 0) === 0
? 'duplicate'
: 'confirmation_sent'
return NextResponse.json({ data: { status } })
}
@@ -0,0 +1,171 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { NextResponse } from 'next/server'
import { createQueuedMockSupabase, parseJsonResponse } from '@/tests/helpers'
const { supabase, enqueue, reset } = createQueuedMockSupabase()
const service = createQueuedMockSupabase()
const requireAuthMock = vi.hoisted(() => vi.fn())
vi.mock('@/lib/auth/require-auth', () => ({
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
}))
const byraMembershipMock = vi.hoisted(() => vi.fn())
vi.mock('@/lib/clients/fetch-client-overview', () => ({
getByraMembership: (...args: unknown[]) => byraMembershipMock(...args),
}))
const brandForTeamMock = vi.hoisted(() => vi.fn())
vi.mock('@/lib/branding/resolve', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/lib/branding/resolve')>()
return {
...actual,
resolveBrandForTeam: (...args: unknown[]) => brandForTeamMock(...args),
clearBrandCache: vi.fn(),
}
})
vi.mock('@/lib/auth/api-keys', () => ({
createServiceClientNoCookies: vi.fn(() => service.supabase),
}))
import { GET, PATCH, POST, DELETE } from '../route'
const BRAND = {
id: 'brand-1',
teamId: 'team-1',
domain: 'app.testbrand.example',
appName: 'Testbrand',
signupMode: 'invite_only',
}
function makeRequest(method: string, body?: unknown): Request {
return new Request('https://app.test/api/clients/signup-access', {
method,
headers: { 'Content-Type': 'application/json' },
body: body === undefined ? undefined : JSON.stringify(body),
})
}
function authed() {
requireAuthMock.mockResolvedValue({
user: { id: 'user-1', email: 'byra@example.com' },
supabase,
error: null,
})
}
beforeEach(() => {
vi.clearAllMocks()
reset()
service.reset()
authed()
byraMembershipMock.mockResolvedValue({
teamId: 'team-1',
teamName: 'Byrån',
role: 'owner',
})
brandForTeamMock.mockResolvedValue(BRAND)
})
describe('/api/clients/signup-access', () => {
it('401s when unauthenticated', async () => {
requireAuthMock.mockResolvedValue({
user: null,
supabase,
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
})
const res = await GET()
expect(res.status).toBe(401)
})
it('403s for non-byrå users', async () => {
byraMembershipMock.mockResolvedValue(null)
const res = await GET()
expect(res.status).toBe(403)
})
it('404s when the team has no brand', async () => {
brandForTeamMock.mockResolvedValue(null)
const res = await GET()
expect(res.status).toBe(404)
})
it('returns mode, role and entries', async () => {
enqueue({
data: [{ id: 'e1', email: 'kund@example.com', note: null, created_at: '2026-08-27' }],
})
const res = await GET()
const { body } = await parseJsonResponse<{
data: {
brand: { domain: string; signupMode: string }
role: string
entries: unknown[]
}
}>(res)
expect(res.status).toBe(200)
expect(body.data.brand.signupMode).toBe('invite_only')
expect(body.data.role).toBe('owner')
expect(body.data.entries).toHaveLength(1)
})
it('PATCH 403s for plain members', async () => {
byraMembershipMock.mockResolvedValue({
teamId: 'team-1',
teamName: 'Byrån',
role: 'member',
})
const res = await PATCH(makeRequest('PATCH', { signup_mode: 'invite_only' }))
expect(res.status).toBe(403)
expect(service.supabase.from).not.toHaveBeenCalled()
})
it('PATCH 400s on an unknown mode', async () => {
const res = await PATCH(makeRequest('PATCH', { signup_mode: 'wide_open' }))
expect(res.status).toBe(400)
})
it('PATCH flips the mode through the service client', async () => {
service.enqueue({ data: null, error: null })
const res = await PATCH(makeRequest('PATCH', { signup_mode: 'invite_only' }))
expect(res.status).toBe(200)
expect(service.findCall('brands', 'update')).toEqual([
{ signup_mode: 'invite_only' },
])
expect(service.findCall('brands', 'eq')).toEqual(['id', 'brand-1'])
})
it('POST adds a lowercased entry', async () => {
enqueue({
data: { id: 'e1', email: 'ny@example.com', note: 'VD', created_at: '2026-08-27' },
})
const res = await POST(
makeRequest('POST', { email: ' NY@Example.com ', note: 'VD' }),
)
expect(res.status).toBe(200)
const insert = supabase.from as unknown as ReturnType<typeof vi.fn>
expect(insert).toHaveBeenCalledWith('brand_signup_allowlist')
})
it('POST 409s on a duplicate email', async () => {
enqueue({ data: null, error: { code: '23505', message: 'duplicate' } })
const res = await POST(makeRequest('POST', { email: 'kund@example.com' }))
expect(res.status).toBe(409)
})
it('POST 400s on an invalid email', async () => {
const res = await POST(makeRequest('POST', { email: 'not-an-email' }))
expect(res.status).toBe(400)
})
it('DELETE removes scoped to the brand', async () => {
enqueue({ data: null, error: null })
const res = await DELETE(
makeRequest('DELETE', { id: '11111111-1111-4111-8111-111111111111' }),
)
expect(res.status).toBe(200)
})
})
+220
View File
@@ -0,0 +1,220 @@
import { NextResponse } from 'next/server'
import { requireAuth } from '@/lib/auth/require-auth'
import { createServiceClientNoCookies } from '@/lib/auth/api-keys'
import { getByraMembership } from '@/lib/clients/fetch-client-overview'
import { clearBrandCache, resolveBrandForTeam, type Brand } from '@/lib/branding/resolve'
import type { SupabaseClient } from '@supabase/supabase-js'
import { validateBody } from '@/lib/api/validate'
import {
BrandAllowlistAddSchema,
BrandAllowlistRemoveSchema,
BrandSignupModeSchema,
} from '@/lib/api/schemas'
/**
* /api/clients/signup-access: the byrå cockpit's management surface for
* invite-only signup on the team's brand domain (2026-08-27).
*
* GET signup mode + allowlist entries (any byrå team member)
* PATCH { signup_mode } flip open/invite_only (owner/admin)
* POST { email, note? } add an allowlist entry (owner/admin)
* DELETE { id } remove an allowlist entry (owner/admin)
*
* Uses requireAuth() directly (the sanctioned withRouteContext opt-out, MFA
* still enforced): byrå staff without a company of their own are the
* cockpit's primary persona, and this surface needs no active company.
*
* Allowlist reads/writes go through the caller's client so RLS enforces the
* same team/role rules a second time. The signup_mode flip uses the service
* client because brands rows are ops-managed (no user write policies); the
* owner/admin check here is the authorization for that single column.
*/
type Access =
| {
ok: true
supabase: SupabaseClient
userId: string
role: 'owner' | 'admin' | 'member'
brand: Brand
}
| { ok: false; response: NextResponse }
async function resolveAccess(opts: { write: boolean }): Promise<Access> {
const auth = await requireAuth()
if (auth.error) return { ok: false, response: auth.error }
const { user, supabase } = auth
const membership = await getByraMembership(supabase, user.id)
if (!membership) {
return {
ok: false,
response: NextResponse.json(
{
error: {
code: 'FORBIDDEN',
message: 'Endast byråteam har åtkomst till registreringsinställningarna.',
message_en: 'Signup access settings are only available to byrå teams.',
},
},
{ status: 403 },
),
}
}
if (opts.write && membership.role !== 'owner' && membership.role !== 'admin') {
return {
ok: false,
response: NextResponse.json(
{
error: {
code: 'FORBIDDEN',
message: 'Endast byråns ägare och administratörer kan ändra registreringsåtkomst.',
message_en: 'Only byrå owners and admins can change signup access.',
},
},
{ status: 403 },
),
}
}
const brand = await resolveBrandForTeam(membership.teamId)
if (!brand) {
return {
ok: false,
response: NextResponse.json(
{
error: {
code: 'NOT_FOUND',
message: 'Byrån har ingen egen domän ännu.',
message_en: 'The byrå has no white-label domain yet.',
},
},
{ status: 404 },
),
}
}
return { ok: true, supabase, userId: user.id, role: membership.role, brand }
}
export async function GET() {
const access = await resolveAccess({ write: false })
if (!access.ok) return access.response
const { data: entries, error } = await access.supabase
.from('brand_signup_allowlist')
.select('id, email, note, created_at')
.eq('brand_id', access.brand.id)
.order('created_at', { ascending: false })
if (error) {
return NextResponse.json(
{ error: { code: 'INTERNAL', message: 'Kunde inte hämta listan.', message_en: 'Could not load the list.' } },
{ status: 500 },
)
}
return NextResponse.json({
data: {
brand: {
domain: access.brand.domain,
appName: access.brand.appName,
signupMode: access.brand.signupMode,
},
role: access.role,
entries: entries ?? [],
},
})
}
export async function PATCH(request: Request) {
const access = await resolveAccess({ write: true })
if (!access.ok) return access.response
const validation = await validateBody(request, BrandSignupModeSchema)
if (!validation.success) return validation.response
const service = createServiceClientNoCookies()
const { error } = await service
.from('brands')
.update({ signup_mode: validation.data.signup_mode })
.eq('id', access.brand.id)
if (error) {
return NextResponse.json(
{ error: { code: 'INTERNAL', message: 'Kunde inte spara.', message_en: 'Could not save.' } },
{ status: 500 },
)
}
// The host-resolution cache holds the old mode for up to ~60s; drop it so
// the gate on this server instance flips immediately. Other instances
// converge within the TTL, same as every other brand edit.
clearBrandCache()
return NextResponse.json({ data: { signupMode: validation.data.signup_mode } })
}
export async function POST(request: Request) {
const access = await resolveAccess({ write: true })
if (!access.ok) return access.response
const validation = await validateBody(request, BrandAllowlistAddSchema)
if (!validation.success) return validation.response
const { data: entry, error } = await access.supabase
.from('brand_signup_allowlist')
.insert({
brand_id: access.brand.id,
email: validation.data.email,
note: validation.data.note ?? null,
created_by: access.userId,
})
.select('id, email, note, created_at')
.single()
if (error) {
if (error.code === '23505') {
return NextResponse.json(
{
error: {
code: 'CONFLICT',
message: 'E-postadressen finns redan i listan.',
message_en: 'That email is already on the list.',
},
},
{ status: 409 },
)
}
return NextResponse.json(
{ error: { code: 'INTERNAL', message: 'Kunde inte lägga till.', message_en: 'Could not add the email.' } },
{ status: 500 },
)
}
return NextResponse.json({ data: entry })
}
export async function DELETE(request: Request) {
const access = await resolveAccess({ write: true })
if (!access.ok) return access.response
const validation = await validateBody(request, BrandAllowlistRemoveSchema)
if (!validation.success) return validation.response
const { error } = await access.supabase
.from('brand_signup_allowlist')
.delete()
.eq('id', validation.data.id)
.eq('brand_id', access.brand.id)
if (error) {
return NextResponse.json(
{ error: { code: 'INTERNAL', message: 'Kunde inte ta bort.', message_en: 'Could not remove the email.' } },
{ status: 500 },
)
}
return NextResponse.json({ data: { removed: validation.data.id } })
}
@@ -57,6 +57,7 @@ const SIFFRA_BRAND = {
senderDomain: 'post.siffra.se',
senderDomainStatus: 'verified',
resendDomainId: 'rd-1',
signupMode: 'open',
}
const mockUser = { id: 'user-1', email: 'admin@byra.se' }