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
+18
View File
@@ -3839,3 +3839,21 @@ export const FiscalYearResetSchema = z.object({
export const NoticeDismissSchema = z.object({
notice_id: z.string().min(1).max(200),
})
/**
* Brand signup access (invite-only white-label domains, 2026-08-27).
* Emails are lowercased here so they match the CHECK-enforced lowercase
* storage in brand_signup_allowlist.
*/
export const BrandSignupModeSchema = z.object({
signup_mode: z.enum(['open', 'invite_only']),
})
export const BrandAllowlistAddSchema = z.object({
email: z.string().trim().toLowerCase().max(320).pipe(z.string().email()),
note: z.string().trim().max(200).optional(),
})
export const BrandAllowlistRemoveSchema = z.object({
id: z.string().uuid(),
})
@@ -0,0 +1,317 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { createQueuedMockSupabase } from '@/tests/helpers'
import { hashInviteToken } from '@/lib/auth/invite-tokens'
import type { Brand } from '@/lib/branding/resolve'
const serviceClient = vi.hoisted(() => ({ current: null as unknown }))
vi.mock('@/lib/auth/api-keys', () => ({
createServiceClientNoCookies: vi.fn(() => serviceClient.current),
}))
// The gate resolves via resolveBrandResultByHost ({ brand, lookupFailed });
// resolveBrandDomainBounce still uses resolveBrandByHost. Mock both off one
// brand value, and let tests override lookupFailed when they need it.
const resolveBrandByHostMock = vi.hoisted(() => vi.fn())
const resolveBrandResultMock = vi.hoisted(() => vi.fn())
vi.mock('@/lib/branding/resolve', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/lib/branding/resolve')>()
return {
...actual,
resolveBrandByHost: (...args: unknown[]) => resolveBrandByHostMock(...args),
resolveBrandResultByHost: (...args: unknown[]) => resolveBrandResultMock(...args),
}
})
import {
evaluateBrandSignupGate,
isEmailOnBrandAllowlist,
readInviteTokenFromCookieHeader,
resolveBrandDomainBounce,
} from '@/lib/auth/brand-signup-gate'
function makeBrand(overrides: Partial<Brand> = {}): Brand {
return {
id: 'brand-1',
teamId: 'team-1',
domain: 'app.testbrand.example',
appName: 'Testbrand',
logoUrl: null,
faviconUrl: null,
brandColor: '#123456',
chromeColor: null,
fontKey: 'default',
supportEmail: 'support@testbrand.example',
authEmailFrom: null,
senderDomain: null,
senderDomainStatus: 'unverified',
resendDomainId: null,
signupMode: 'invite_only',
...overrides,
}
}
let mock: ReturnType<typeof createQueuedMockSupabase>
beforeEach(() => {
vi.clearAllMocks()
mock = createQueuedMockSupabase()
serviceClient.current = mock.supabase
// By default the strict resolver mirrors resolveBrandByHostMock's value
// with lookupFailed:false, so the existing tests keep configuring one mock.
// The fail-safe test overrides this to return lookupFailed:true.
resolveBrandResultMock.mockImplementation(async (host: string) => ({
brand: await resolveBrandByHostMock(host),
lookupFailed: false,
}))
})
describe('evaluateBrandSignupGate', () => {
it('allows when the host has no brand', async () => {
resolveBrandByHostMock.mockResolvedValue(null)
const result = await evaluateBrandSignupGate({
host: 'app.accounted.se',
email: 'anyone@example.com',
})
expect(result).toEqual({ allowed: true, brand: null, via: 'no_brand' })
})
it('allows with no host at all', async () => {
const result = await evaluateBrandSignupGate({ host: '', email: 'a@b.se' })
expect(result.allowed).toBe(true)
expect(resolveBrandByHostMock).not.toHaveBeenCalled()
})
it('allows on an open brand without touching the allowlist', async () => {
resolveBrandByHostMock.mockResolvedValue(makeBrand({ signupMode: 'open' }))
const result = await evaluateBrandSignupGate({
host: 'app.testbrand.example',
email: 'anyone@example.com',
})
expect(result.allowed).toBe(true)
expect(result.allowed && result.via).toBe('open')
expect(mock.supabase.from).not.toHaveBeenCalled()
})
it('allows an allowlisted email on an invite-only brand, case-insensitively', async () => {
resolveBrandByHostMock.mockResolvedValue(makeBrand())
mock.enqueue({ data: { id: 'entry-1' } })
const result = await evaluateBrandSignupGate({
host: 'app.testbrand.example',
email: ' Kund@Example.COM ',
})
expect(result.allowed).toBe(true)
expect(result.allowed && result.via).toBe('allowlist')
// The lookup used the normalized address.
expect(mock.findCalls('brand_signup_allowlist', 'eq')).toContainEqual([
'email',
'kund@example.com',
])
})
it('blocks a non-allowlisted email on an invite-only brand', async () => {
const brand = makeBrand()
resolveBrandByHostMock.mockResolvedValue(brand)
mock.enqueue({ data: null })
const result = await evaluateBrandSignupGate({
host: 'app.testbrand.example',
email: 'stranger@example.com',
})
expect(result).toEqual({ allowed: false, brand })
})
it('fails safe (lookupFailed) when the brand lookup itself errors', async () => {
resolveBrandResultMock.mockResolvedValue({ brand: null, lookupFailed: true })
const result = await evaluateBrandSignupGate({
host: 'app.testbrand.example',
email: 'anyone@example.com',
})
// Must NOT degrade to allowed no_brand: a transient DB error cannot open
// an invite-only domain.
expect(result).toEqual({ allowed: false, brand: null, lookupFailed: true })
})
it('fails closed when the allowlist lookup errors', async () => {
resolveBrandByHostMock.mockResolvedValue(makeBrand())
mock.enqueue({ data: null, error: { message: 'boom' } })
const result = await evaluateBrandSignupGate({
host: 'app.testbrand.example',
email: 'kund@example.com',
})
expect(result.allowed).toBe(false)
})
it('allows a pending unexpired invite for the same email', async () => {
resolveBrandByHostMock.mockResolvedValue(makeBrand())
// Allowlist miss, then the invite row.
mock.enqueueMany([
{ data: null },
{
data: {
email: 'Invitee@Example.com',
status: 'pending',
expires_at: new Date(Date.now() + 60_000).toISOString(),
},
},
])
const result = await evaluateBrandSignupGate({
host: 'app.testbrand.example',
email: 'invitee@example.com',
inviteToken: 'gnubok_inv_abc',
})
expect(result.allowed).toBe(true)
expect(result.allowed && result.via).toBe('invite')
// Lookup is by token hash, never the raw token.
expect(mock.findCall('company_invitations', 'eq')).toEqual([
'token_hash',
hashInviteToken('gnubok_inv_abc'),
])
})
it('blocks when the invite is for a different email', async () => {
resolveBrandByHostMock.mockResolvedValue(makeBrand())
mock.enqueueMany([
{ data: null },
{
data: {
email: 'someone-else@example.com',
status: 'pending',
expires_at: new Date(Date.now() + 60_000).toISOString(),
},
},
])
const result = await evaluateBrandSignupGate({
host: 'app.testbrand.example',
email: 'stranger@example.com',
inviteToken: 'gnubok_inv_abc',
})
expect(result.allowed).toBe(false)
})
it('blocks when the invite is expired', async () => {
resolveBrandByHostMock.mockResolvedValue(makeBrand())
mock.enqueueMany([
{ data: null },
{
data: {
email: 'invitee@example.com',
status: 'pending',
expires_at: new Date(Date.now() - 60_000).toISOString(),
},
},
])
const result = await evaluateBrandSignupGate({
host: 'app.testbrand.example',
email: 'invitee@example.com',
inviteToken: 'gnubok_inv_abc',
})
expect(result.allowed).toBe(false)
})
})
describe('isEmailOnBrandAllowlist', () => {
it('returns false for an empty email without querying', async () => {
expect(await isEmailOnBrandAllowlist('brand-1', ' ')).toBe(false)
expect(mock.supabase.from).not.toHaveBeenCalled()
})
})
describe('resolveBrandDomainBounce', () => {
const base = {
host: 'app.testbrand.example',
userEmail: 'user@example.com',
teamIds: [] as string[],
companyTeamIds: [] as Array<string | null>,
hasPendingInviteCookie: false,
canonicalAppUrl: 'https://app.accounted.se',
}
it('stays on open brands and brandless hosts', async () => {
resolveBrandByHostMock.mockResolvedValue(null)
expect(await resolveBrandDomainBounce(base)).toBeNull()
resolveBrandByHostMock.mockResolvedValue(makeBrand({ signupMode: 'open' }))
expect(await resolveBrandDomainBounce(base)).toBeNull()
})
it('stays for brand team members and brand-homed company members', async () => {
resolveBrandByHostMock.mockResolvedValue(makeBrand())
expect(
await resolveBrandDomainBounce({ ...base, teamIds: ['team-1'] }),
).toBeNull()
expect(
await resolveBrandDomainBounce({ ...base, companyTeamIds: [null, 'team-1'] }),
).toBeNull()
})
it('stays when a pending invite cookie rides along', async () => {
resolveBrandByHostMock.mockResolvedValue(makeBrand())
expect(
await resolveBrandDomainBounce({ ...base, hasPendingInviteCookie: true }),
).toBeNull()
})
it('stays for an allowlisted email', async () => {
resolveBrandByHostMock.mockResolvedValue(makeBrand())
mock.enqueue({ data: { id: 'entry-1' } })
expect(await resolveBrandDomainBounce(base)).toBeNull()
})
it('bounces a non-belonging session to the canonical URL', async () => {
resolveBrandByHostMock.mockResolvedValue(makeBrand())
mock.enqueue({ data: null })
expect(await resolveBrandDomainBounce(base)).toBe('https://app.accounted.se')
})
it('never bounces onto the same host', async () => {
resolveBrandByHostMock.mockResolvedValue(makeBrand())
mock.enqueue({ data: null })
expect(
await resolveBrandDomainBounce({
...base,
canonicalAppUrl: 'https://app.testbrand.example',
}),
).toBeNull()
})
it('never bounces on a malformed canonical URL', async () => {
resolveBrandByHostMock.mockResolvedValue(makeBrand())
mock.enqueue({ data: null })
expect(
await resolveBrandDomainBounce({ ...base, canonicalAppUrl: '' }),
).toBeNull()
})
})
describe('readInviteTokenFromCookieHeader', () => {
it('reads the invite token among other cookies', () => {
expect(
readInviteTokenFromCookieHeader(
'a=1; gnubok-invite-token=gnubok_inv_x; b=2',
),
).toBe('gnubok_inv_x')
})
it('decodes URI-encoded values and tolerates missing cookies', () => {
expect(
readInviteTokenFromCookieHeader('gnubok-invite-token=abc%3D%3D'),
).toBe('abc==')
expect(readInviteTokenFromCookieHeader(null)).toBeNull()
expect(readInviteTokenFromCookieHeader('a=1; b=2')).toBeNull()
expect(readInviteTokenFromCookieHeader('gnubok-invite-token=')).toBeNull()
})
})
+7 -1
View File
@@ -79,10 +79,16 @@ describe('Turnstile integration contract', () => {
expect(login).toContain('action="accounted_login"')
expect(login).toContain('action="accounted_password_reset"')
// The register page's email flow moved server-side (invite-only brand
// domain gate, 2026-08-27): the captcha token must travel to
// POST /api/auth/signup, and that route must forward it into the GoTrue
// signUp call, so the CAPTCHA still guards the flow end to end.
expect(register).toMatch(
/signUp\([\s\S]*?captchaTokenOptions\(captchaToken\)/,
/fetch\('\/api\/auth\/signup'[\s\S]*?captchaTokenOptions\(captchaToken\)/,
)
expect(register).toContain('action="accounted_signup"')
const signupRoute = readRepoFile('app/api/auth/signup/route.ts')
expect(signupRoute).toMatch(/signUp\(\{[\s\S]*?captchaToken/)
expect(sandbox).toMatch(
/signInAnonymously\([\s\S]*?captchaTokenOptions\(captchaToken\)/,
+224
View File
@@ -0,0 +1,224 @@
import 'server-only'
/**
* Invite-only signup gate for white-label brand domains (founder decision
* 2026-08-27): a brand domain belongs to the partner's people, so when a
* brand has signup_mode = 'invite_only', creating an account on that domain
* requires either a brand_signup_allowlist entry for the email or a valid
* pending company invite for it. Everyone else is sent to the canonical
* signup by the register page's interstitial.
*
* Enforced SERVER-SIDE at the moment an account would be created, on every
* signup path:
* - email+password: POST /api/auth/signup (the register page no longer
* calls supabase.auth.signUp from the browser on any host, because a
* client-side check would be bypassable)
* - BankID: extensions/general/tic /bankid/complete (signup mode)
* - Google OAuth: the account exists after the OAuth round-trip, so the
* dashboard layout's domain gate bounces non-belonging sessions to the
* canonical domain instead
*
* Uses the cookieless service client: the visitor is anonymous at signup
* time, so RLS cannot scope these reads. Fail-CLOSED on the allowlist and
* invite lookups: on a transient query error a gated brand refuses the
* signup rather than silently opening the door.
*/
import { createServiceClientNoCookies } from '@/lib/auth/api-keys'
import { INVITE_COOKIE_NAME } from '@/lib/auth/consume-invite-cookie'
import { hashInviteToken } from '@/lib/auth/invite-tokens'
import {
normalizeHost,
resolveBrandByHost,
resolveBrandResultByHost,
type Brand,
} from '@/lib/branding/resolve'
import { createLogger } from '@/lib/logger'
const log = createLogger('brand-signup-gate')
export type BrandSignupGateResult =
| {
allowed: true
brand: Brand | null
/** What let the signup through, for logging and tests. */
via: 'no_brand' | 'open' | 'allowlist' | 'invite'
}
| { allowed: false; brand: Brand }
// The brands lookup itself failed (transient DB error). The caller must
// fail SAFE (retry / 503), never treat this as an unbranded host, or a
// blip would open invite-only signup.
| { allowed: false; brand: null; lookupFailed: true }
/**
* Whether `email` is on the brand's signup allowlist. Case-insensitive: the
* table stores lowercase (CHECK-enforced) and the lookup lowercases too.
* Fail-closed: a query error reads as "not allowlisted".
*/
export async function isEmailOnBrandAllowlist(
brandId: string,
email: string,
): Promise<boolean> {
const normalized = email.trim().toLowerCase()
if (!normalized) return false
const supabase = createServiceClientNoCookies()
const { data, error } = await supabase
.from('brand_signup_allowlist')
.select('id')
.eq('brand_id', brandId)
.eq('email', normalized)
.limit(1)
.maybeSingle()
if (error) {
log.error('allowlist lookup failed; treating as not allowlisted', {
brandId,
message: error.message,
})
return false
}
return data !== null
}
/**
* Whether `inviteToken` is a live company invite for `email`: pending,
* unexpired, and addressed to the same email (case-insensitive). The invite
* itself is the authorization, so it bypasses the allowlist. Mirrors the
* acceptance checks in /api/team/accept and /auth/callback; acceptance
* re-validates everything, so this gate can stay a read.
*/
async function isValidInviteForEmail(
inviteToken: string,
email: string,
): Promise<boolean> {
const supabase = createServiceClientNoCookies()
const { data, error } = await supabase
.from('company_invitations')
.select('email, status, expires_at')
.eq('token_hash', hashInviteToken(inviteToken))
.maybeSingle()
if (error) {
log.error('invite lookup failed; treating as invalid', { message: error.message })
return false
}
if (!data) return false
return (
data.status === 'pending' &&
new Date(data.expires_at) > new Date() &&
data.email.toLowerCase() === email.trim().toLowerCase()
)
}
/**
* Decide whether a signup with `email` may proceed on `host`.
*
* Allowed when the host has no brand (canonical and unknown hosts, the
* additive guarantee), the brand is open, the email is allowlisted, or a
* valid invite token rides along (the gnubok-invite-token cookie set by
* /invite/[token]).
*/
export async function evaluateBrandSignupGate(opts: {
host: string | null | undefined
email: string
inviteToken?: string | null
}): Promise<BrandSignupGateResult> {
const { brand, lookupFailed } = opts.host
? await resolveBrandResultByHost(opts.host)
: { brand: null, lookupFailed: false }
if (lookupFailed) {
// Do not fall through to no_brand: a transient brands-table error must
// not open an invite-only domain. The caller turns this into a 503.
log.error('brand lookup failed; refusing to decide signup gate')
return { allowed: false, brand: null, lookupFailed: true }
}
if (!brand) return { allowed: true, brand: null, via: 'no_brand' }
if (brand.signupMode !== 'invite_only') return { allowed: true, brand, via: 'open' }
if (await isEmailOnBrandAllowlist(brand.id, opts.email)) {
return { allowed: true, brand, via: 'allowlist' }
}
if (opts.inviteToken && (await isValidInviteForEmail(opts.inviteToken, opts.email))) {
return { allowed: true, brand, via: 'invite' }
}
// Observability, not enumeration: log the brand and outcome, never the
// attempted address.
log.info('signup blocked on invite-only brand domain', { brandId: brand.id, domain: brand.domain })
return { allowed: false, brand }
}
/**
* Logged-in counterpart of the signup gate, for the dashboard layout: on an
* invite-only brand host, a session that does not belong to the brand (no
* team membership on the brand's team, no company on it, not allowlisted,
* no pending invite) is bounced to the canonical domain instead of getting
* a branded shell. Returns the absolute URL to redirect to, or null to stay.
*
* A NAVIGATION rule like the home-domain rule (WL-01), not a security
* boundary: data access is governed by membership and RLS regardless of
* host. That is why the pending-invite check is presence-only here; the
* actual invite acceptance re-validates the token server-side.
*/
export async function resolveBrandDomainBounce(opts: {
host: string
userEmail: string | null | undefined
/** teams.id of every team the user belongs to (any role). */
teamIds: string[]
/** companies.team_id of every company the user belongs to. */
companyTeamIds: Array<string | null | undefined>
hasPendingInviteCookie: boolean
/** getBranding().appUrl: where non-belonging sessions are sent. */
canonicalAppUrl: string
}): Promise<string | null> {
const brand = opts.host ? await resolveBrandByHost(opts.host) : null
if (!brand || brand.signupMode !== 'invite_only') return null
if (opts.teamIds.includes(brand.teamId)) return null
if (opts.companyTeamIds.some((teamId) => teamId === brand.teamId)) return null
if (opts.hasPendingInviteCookie) return null
if (opts.userEmail && (await isEmailOnBrandAllowlist(brand.id, opts.userEmail))) {
return null
}
// Never bounce onto the same host (misconfigured canonical URL would
// otherwise loop), and never bounce when no canonical URL is known.
let canonicalHost: string
try {
canonicalHost = new URL(opts.canonicalAppUrl).hostname
} catch {
return null
}
if (!canonicalHost || canonicalHost === normalizeHost(opts.host)) return null
log.info('bouncing non-member session off invite-only brand domain', {
brandId: brand.id,
domain: brand.domain,
})
return opts.canonicalAppUrl
}
/**
* The pending-invite token from a raw Cookie header, for server routes that
* hold a Request rather than a Next.js cookie store. The cookie is set by
* /invite/[token] (not httpOnly, so the client auth surfaces read it too).
*/
export function readInviteTokenFromCookieHeader(header: string | null): string | null {
if (!header) return null
for (const part of header.split(';')) {
const eq = part.indexOf('=')
if (eq === -1) continue
if (part.slice(0, eq).trim() !== INVITE_COOKIE_NAME) continue
const value = part.slice(eq + 1).trim()
if (!value) return null
try {
return decodeURIComponent(value)
} catch {
return value
}
}
return null
}
@@ -21,6 +21,7 @@ const fullBrand: Brand = {
senderDomain: 'mail.siffra.se',
senderDomainStatus: 'verified',
resendDomainId: 'rd_123',
signupMode: 'open',
}
describe('toPublicBrand', () => {
+2
View File
@@ -34,6 +34,7 @@ const brandRow = {
sender_domain: null,
sender_domain_status: 'unverified',
resend_domain_id: null,
signup_mode: 'open',
}
let mock: ReturnType<typeof createQueuedMockSupabase>
@@ -78,6 +79,7 @@ describe('resolveBrandByHost', () => {
senderDomain: null,
senderDomainStatus: 'unverified',
resendDomainId: null,
signupMode: 'open',
})
expect(mock.findCall('brands', 'eq')).toEqual(['domain', 'app.siffra.se'])
})
+28 -5
View File
@@ -39,6 +39,8 @@ export interface Brand {
senderDomain: string | null
senderDomainStatus: 'unverified' | 'pending' | 'verified' | 'failed'
resendDomainId: string | null
/** 'invite_only' arms the signup gate (lib/auth/brand-signup-gate.ts). */
signupMode: 'open' | 'invite_only'
}
interface BrandRow {
@@ -56,6 +58,7 @@ interface BrandRow {
sender_domain: string | null
sender_domain_status: string
resend_domain_id: string | null
signup_mode?: string | null
}
function mapRow(row: BrandRow): Brand {
@@ -74,6 +77,9 @@ function mapRow(row: BrandRow): Brand {
senderDomain: row.sender_domain,
senderDomainStatus: row.sender_domain_status as Brand['senderDomainStatus'],
resendDomainId: row.resend_domain_id,
// Anything but the explicit invite_only value reads as 'open' so the
// additive guarantee holds even against a stale schema cache.
signupMode: row.signup_mode === 'invite_only' ? 'invite_only' : 'open',
}
}
@@ -130,12 +136,28 @@ export function normalizeHost(host: string): string {
* the additive guarantee (unknown host = default Accounted, bit for bit).
*/
export async function resolveBrandByHost(host: string): Promise<Brand | null> {
return (await resolveBrandResultByHost(host)).brand
}
/**
* Brand resolution that distinguishes "this host has no brand" from "the
* lookup itself failed". Callers that only pick chrome/branding want the
* null-means-default behavior of resolveBrandByHost. A caller enforcing a
* SECURITY decision on the result (the invite-only signup gate,
* lib/auth/brand-signup-gate.ts) must NOT read a transient DB error as an
* unbranded host, which would fail open: a blip on the brands table would
* let anyone sign up on an invite-only domain. `lookupFailed` lets that
* caller fail safe (503 / retry) instead.
*/
export async function resolveBrandResultByHost(
host: string,
): Promise<{ brand: Brand | null; lookupFailed: boolean }> {
const normalized = normalizeHost(host)
if (!normalized) return null
if (!normalized) return { brand: null, lookupFailed: false }
const key = `host:${normalized}`
const hit = readCache(key)
if (hit) return hit.value
if (hit) return { brand: hit.value, lookupFailed: false }
const supabase = createServiceClientNoCookies()
const { data, error } = await supabase
@@ -146,13 +168,14 @@ export async function resolveBrandByHost(host: string): Promise<Brand | null> {
if (error) {
// Transient failure: fall back to defaults without caching, so a live
// brand is not masked for a whole TTL window by one failed query.
return null
// brand is not masked for a whole TTL window by one failed query. The
// flag lets a security caller tell this apart from a real unbranded host.
return { brand: null, lookupFailed: true }
}
const brand = data ? mapRow(data as BrandRow) : null
writeCache(key, brand)
return brand
return { brand, lookupFailed: false }
}
/**
+61 -7
View File
@@ -1,9 +1,11 @@
'use server'
import { createClient } from '@/lib/supabase/server'
import { headers } from 'next/headers'
import { createClient, createServiceClient } from '@/lib/supabase/server'
import { setActiveCompany, CompanyContextError } from '@/lib/company/context'
import { revalidatePath } from 'next/cache'
import { createCompanyCore } from '@/lib/company/create-company'
import type { SupabaseClient } from '@supabase/supabase-js'
import type { CompanyLookupResult } from '@/lib/company-lookup/types'
import { getErrorMessage } from '@/lib/errors/get-error-message'
@@ -120,6 +122,62 @@ async function createCompanyFromOnboardingImpl(params: {
}
}
// Brand-host signup homing (2026-08-27): when this wizard runs on an
// invite-only brand host and the creating user is on the brand's signup
// allowlist, the company attaches to the brand's byrå team via the
// create_company_for_brand_signup RPC (which re-checks the allowlist).
// Without this the company would get the personal team and the home-domain
// rule (WL-01) would home it on the canonical domain, invisible on the
// very brand domain the user signed up on. Only the personal-team path is
// rerouted: an explicit byrå-team creation (the cockpit's new-client flow)
// already passed the byrå team and stays under the WL-15 admin gate above.
let createCompanyRow: () => PromiseLike<{ data: unknown; error: unknown }> =
() =>
supabase.rpc('create_company_with_owner', {
p_name: companyName,
p_entity_type: entityType,
p_team_id: params.teamId,
})
// When the row is created under the service role (brand-signup path below),
// rollback must also run under the service role: `companies` has RLS and no
// FOR DELETE policy, so a cookie-session rollback of a service-created
// company deletes nothing and strands a member-less orphan on the brand's
// team. Stays null on the normal path, where the session client is correct.
// Once the rollback delete lands, user_preferences.active_company_id (which
// the RPC set) auto-clears via its ON DELETE SET NULL FK, so no dangling
// active company survives.
let rollbackClient: SupabaseClient | undefined
if ((teamRow as { kind?: string } | null)?.kind !== 'byra' && user.email) {
// Dynamic imports: this file is imported by client components (through
// switch-client.ts) for its other actions, and these two modules reach
// node:crypto; a static import would drag Node builtins into the client
// graph (client-node-builtin guard). Server actions always execute
// server-side, so the dynamic import is free here.
const [{ resolveBrandByHost }, { isEmailOnBrandAllowlist }] = await Promise.all([
import('@/lib/branding/resolve'),
import('@/lib/auth/brand-signup-gate'),
])
const requestHeaders = await headers()
const host =
requestHeaders.get('x-forwarded-host') ?? requestHeaders.get('host') ?? ''
const hostBrand = host ? await resolveBrandByHost(host) : null
if (
hostBrand?.signupMode === 'invite_only' &&
(await isEmailOnBrandAllowlist(hostBrand.id, user.email))
) {
const serviceClient = createServiceClient()
rollbackClient = serviceClient
createCompanyRow = () =>
serviceClient.rpc('create_company_for_brand_signup', {
p_user_id: user.id,
p_name: companyName,
p_entity_type: entityType,
p_brand_id: hostBrand.id,
})
}
}
// Steps 1-5 (company + owner via RPC, org number, TIC snapshot, chart,
// settings, fiscal period, tax deadlines, with rollback) are shared with
// the MCP and v1 creation paths: lib/company/create-company.ts.
@@ -133,12 +191,8 @@ async function createCompanyFromOnboardingImpl(params: {
fiscalPeriod: params.fiscalPeriod,
ticLookup: params.ticLookup,
},
() =>
supabase.rpc('create_company_with_owner', {
p_name: companyName,
p_entity_type: entityType,
p_team_id: params.teamId,
}),
createCompanyRow,
rollbackClient,
)
if (created.error !== undefined) {
return { error: created.error }
+14 -5
View File
@@ -53,6 +53,15 @@ export async function createCompanyCore(
supabase: SupabaseClient,
input: CreateCompanyInput,
createCompanyRow: () => PromiseLike<{ data: unknown; error: unknown }>,
// Client used for rollback deletes. Defaults to `supabase`, but a caller
// whose createCompanyRow ran under the SERVICE role (the brand-signup path,
// lib/company/actions.ts) MUST pass the service client here: `companies`
// has RLS enabled and no FOR DELETE policy, so a cookie-session delete of
// the companies row is a silent 0-row no-op. Rolling back a service-created
// company with the session client would strip its members but leave the
// orphaned companies row behind, attached to whichever team it was created
// on. The service client bypasses RLS, so its delete actually removes it.
rollbackClient: SupabaseClient = supabase,
): Promise<CreateCompanyResult> {
// Org-number format validation. We intentionally do NOT enforce
// uniqueness: the same org number may legitimately appear on multiple
@@ -84,11 +93,11 @@ export async function createCompanyCore(
const rollback = async (reason: string, err: unknown) => {
console.error(`[createCompany] rolling back ${newCompanyId}: ${reason}`, err)
const deletions: Array<[table: string, run: () => PromiseLike<{ error: unknown }>]> = [
['company_settings', () => supabase.from('company_settings').delete().eq('company_id', newCompanyId)],
['fiscal_periods', () => supabase.from('fiscal_periods').delete().eq('company_id', newCompanyId)],
['chart_of_accounts', () => supabase.from('chart_of_accounts').delete().eq('company_id', newCompanyId)],
['company_members', () => supabase.from('company_members').delete().eq('company_id', newCompanyId)],
['companies', () => supabase.from('companies').delete().eq('id', newCompanyId)],
['company_settings', () => rollbackClient.from('company_settings').delete().eq('company_id', newCompanyId)],
['fiscal_periods', () => rollbackClient.from('fiscal_periods').delete().eq('company_id', newCompanyId)],
['chart_of_accounts', () => rollbackClient.from('chart_of_accounts').delete().eq('company_id', newCompanyId)],
['company_members', () => rollbackClient.from('company_members').delete().eq('company_id', newCompanyId)],
['companies', () => rollbackClient.from('companies').delete().eq('id', newCompanyId)],
]
for (const [table, run] of deletions) {
const { error: deleteError } = await run()
@@ -51,6 +51,7 @@ function makeBrand(overrides: Partial<Brand> = {}): Brand {
senderDomain: 'post.siffra.se',
senderDomainStatus: 'verified',
resendDomainId: 'rd-1',
signupMode: 'open',
...overrides,
}
}
+1
View File
@@ -32,6 +32,7 @@ function makeBrand(overrides: Partial<Brand> = {}): Brand {
senderDomain: 'post.siffra.se',
senderDomainStatus: 'verified',
resendDomainId: 'rd-1',
signupMode: 'open',
...overrides,
}
}