Files
accounted/app/api/auth/email-hook/__tests__/route.test.ts
T
MattssonandClaude Fable 5 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

242 lines
8.3 KiB
TypeScript

/**
* Tests for POST /api/auth/email-hook (Supabase Send Email hook).
*
* Unauthenticated by design: the guard is the Standard Webhooks signature.
* Signature material is computed with node:crypto exactly like Supabase does.
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import { createHmac, randomBytes } from 'node:crypto'
import type { Brand } from '@/lib/branding/resolve'
vi.mock('@/lib/init', () => ({ ensureInitialized: vi.fn() }))
const resolveBrandByHostMock = vi.hoisted(() => vi.fn())
vi.mock('@/lib/branding/resolve', () => ({
resolveBrandByHost: resolveBrandByHostMock,
// Imported by lib/email/brand-sender (not called on the hook path).
resolveBrandForCompany: vi.fn(),
}))
vi.mock('@/lib/branding/service', () => ({
getBranding: () => ({ appName: 'Accounted', appUrl: 'https://app.gnubok.se' }),
}))
const sendEmailMock = vi.hoisted(() => vi.fn())
vi.mock('@/lib/email/service', () => ({
getEmailService: () => ({ sendEmail: sendEmailMock, isConfigured: () => true }),
}))
import { POST } from '../route'
const KEY = randomBytes(24)
const SECRET = `v1,whsec_${KEY.toString('base64')}`
function makeBrand(overrides: Partial<Brand> = {}): Brand {
return {
id: 'brand-1',
teamId: 'team-1',
domain: 'app.siffra.se',
appName: 'Siffra',
logoUrl: null,
brandColor: '#123456',
chromeColor: null,
fontKey: 'default',
supportEmail: 'support@siffra.se',
authEmailFrom: 'noreply@post.siffra.se',
senderDomain: 'post.siffra.se',
senderDomainStatus: 'verified',
resendDomainId: 'rd-1',
signupMode: 'open',
...overrides,
}
}
function signedRequest(rawBody: string, opts?: { badSignature?: boolean; headers?: Record<string, string> }): Request {
const id = 'msg_1'
const timestamp = String(Math.floor(Date.now() / 1000))
const signature = createHmac('sha256', KEY)
.update(`${id}.${timestamp}.${rawBody}`)
.digest('base64')
return new Request('http://localhost:3000/api/auth/email-hook', {
method: 'POST',
body: rawBody,
headers: {
'content-type': 'application/json',
'webhook-id': id,
'webhook-timestamp': timestamp,
'webhook-signature': opts?.badSignature ? 'v1,AAAA' : `v1,${signature}`,
...opts?.headers,
},
})
}
function hookPayload(overrides?: {
user?: Record<string, unknown>
email_data?: Record<string, unknown>
}): string {
return JSON.stringify({
user: { email: 'user@example.se', ...overrides?.user },
email_data: {
token: '123456',
token_hash: 'hash-1',
redirect_to: 'https://app.gnubok.se/auth/callback?next=/reset-password',
email_action_type: 'recovery',
site_url: 'https://app.gnubok.se',
...overrides?.email_data,
},
})
}
beforeEach(() => {
vi.clearAllMocks()
process.env.SUPABASE_SEND_EMAIL_HOOK_SECRET = SECRET
resolveBrandByHostMock.mockResolvedValue(null)
sendEmailMock.mockResolvedValue({ success: true, messageId: 'msg-1' })
})
afterEach(() => {
delete process.env.SUPABASE_SEND_EMAIL_HOOK_SECRET
})
describe('POST /api/auth/email-hook', () => {
it('returns 500 when the hook secret is not configured', async () => {
delete process.env.SUPABASE_SEND_EMAIL_HOOK_SECRET
const res = await POST(signedRequest(hookPayload()))
expect(res.status).toBe(500)
expect(sendEmailMock).not.toHaveBeenCalled()
})
it('returns 401 for an invalid signature', async () => {
const res = await POST(signedRequest(hookPayload(), { badSignature: true }))
expect(res.status).toBe(401)
expect(sendEmailMock).not.toHaveBeenCalled()
})
it('returns 400 for a signed but malformed payload', async () => {
const res = await POST(signedRequest('not-json'))
expect(res.status).toBe(400)
expect(sendEmailMock).not.toHaveBeenCalled()
})
it('sends canonical recovery mail linking to the originating host (no brand)', async () => {
const res = await POST(signedRequest(hookPayload()))
expect(res.status).toBe(200)
await expect(res.json()).resolves.toEqual({})
expect(sendEmailMock).toHaveBeenCalledTimes(1)
const options = sendEmailMock.mock.calls[0][0]
expect(options.to).toBe('user@example.se')
expect(options.subject).toBe('Återställ ditt lösenord')
expect(options.fromName).toBeUndefined()
expect(options.fromAddress).toBeUndefined()
expect(options.replyTo).toBeUndefined()
// token_hash + verifyOtp pattern on the originating host, preserving the
// existing next=/reset-password query.
expect(options.text).toContain('https://app.gnubok.se/auth/callback?next=%2Freset-password')
expect(options.text).toContain('token_hash=hash-1')
expect(options.text).toContain('type=recovery')
})
it('brands the mail from the redirect_to host and rides the verified brand sender', async () => {
resolveBrandByHostMock.mockResolvedValue(makeBrand())
const res = await POST(
signedRequest(
hookPayload({
email_data: {
email_action_type: 'signup',
redirect_to: 'https://app.siffra.se/auth/callback',
},
}),
),
)
expect(res.status).toBe(200)
expect(resolveBrandByHostMock).toHaveBeenCalledWith('app.siffra.se')
const options = sendEmailMock.mock.calls[0][0]
expect(options.fromName).toBe('Siffra')
expect(options.fromAddress).toBe('noreply@post.siffra.se')
expect(options.replyTo).toBe('support@siffra.se')
expect(options.html).toContain('Siffra')
expect(options.html).not.toMatch(/accounted/i)
expect(options.text).toContain('https://app.siffra.se/auth/callback?token_hash=hash-1')
expect(options.text).toContain('type=signup')
})
it('uses the via-fallback for a brand without a verified sender domain', async () => {
resolveBrandByHostMock.mockResolvedValue(makeBrand({ senderDomainStatus: 'pending' }))
await POST(
signedRequest(
hookPayload({
email_data: {
email_action_type: 'magiclink',
redirect_to: 'https://app.siffra.se/auth/callback',
},
}),
),
)
const options = sendEmailMock.mock.calls[0][0]
expect(options.fromName).toBe('Siffra')
expect(options.fromAddress).toBeUndefined()
})
it('sends two mails for a secure email change', async () => {
await POST(
signedRequest(
hookPayload({
user: { email: 'current@example.se', new_email: 'new@example.se' },
email_data: {
email_action_type: 'email_change',
token_hash: 'hash-new-address',
token_hash_new: 'hash-current-address',
redirect_to: 'https://app.gnubok.se/auth/callback',
},
}),
),
)
expect(sendEmailMock).toHaveBeenCalledTimes(2)
const first = sendEmailMock.mock.calls[0][0]
const second = sendEmailMock.mock.calls[1][0]
// token_hash confirms at the NEW address, token_hash_new at the current.
expect(first.to).toBe('new@example.se')
expect(first.text).toContain('token_hash=hash-new-address')
expect(second.to).toBe('current@example.se')
expect(second.text).toContain('token_hash=hash-current-address')
})
it('sends the OTP code for reauthentication without a link', async () => {
await POST(
signedRequest(
hookPayload({
email_data: { email_action_type: 'reauthentication', token: '424242' },
}),
),
)
const options = sendEmailMock.mock.calls[0][0]
expect(options.subject).toBe('Din verifieringskod')
expect(options.text).toContain('424242')
expect(options.text).not.toContain('token_hash=')
})
it('builds the callback URL when redirect_to points at a plain path', async () => {
await POST(
signedRequest(
hookPayload({
email_data: {
email_action_type: 'magiclink',
redirect_to: 'https://app.gnubok.se/settings/account',
},
}),
),
)
const options = sendEmailMock.mock.calls[0][0]
expect(options.text).toContain('https://app.gnubok.se/auth/callback?next=%2Fsettings%2Faccount')
expect(options.text).toContain('type=magiclink')
})
it('returns 500 when the email provider fails, so Supabase retries', async () => {
sendEmailMock.mockResolvedValue({ success: false, error: 'provider down' })
const res = await POST(signedRequest(hookPayload()))
expect(res.status).toBe(500)
})
})