Files
accounted/app/api/auth/signup/route.ts
T
Mattsson 4f6ecad549 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>
2026-08-27 18:32:52 +02:00

132 lines
5.3 KiB
TypeScript

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 } })
}