fix(auth): resolve BankID confirmation and email-hook link hosts through the trusted-origin registry (#2380)

* fix(auth): resolve BankID confirmation and email-hook link hosts through the trusted-origin registry

The BankID confirmation mail built its /auth/callback link from the raw
forwarded host and protocol; it is the one auth link GoTrue's redirect
allowlist never sees, since the link is minted here and sent through
Resend. The Send Email hook followed GoTrue's redirect_to verbatim: the
webhook signature proves who sent the payload, not that every destination
in it should be followed, and the GoTrue allowlist is a hand-configured
glob.

Both now resolve the destination through lib/domains/trusted-app-origin
like every other auth link (canonical, this deployment's own Vercel hosts,
or a registered brands.domain). Unknown, lookalike, credential-bearing,
non-default-port and malformed destinations collapse to the canonical
/auth/callback with no next path; a registered brand host over http is
upgraded to https. Brand sender identity is taken from the RESOLVED host,
so mail branding and link destination always agree. A brands-table read
failure refuses instead of mailing a wrong-host link: the BankID helper
returns step resolve_origin (signup rolls back, login re-send logs), the
hook answers 500 so Supabase retries.

Drops the proto parameter from the BankID helper; the resolver owns the
scheme.

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

* fix(auth): read the sender brand once, failure-aware, before minting or sending auth mail

CodeRabbit: resolveTrustedAppOrigin could classify a brand host, then the
separate resolveBrandByHost read for the sender could fail and return null,
so a brand link went out with the platform sender; the BankID helper had
already minted the magic link by then. Both sites now read the brand with
resolveBrandResultByHost on the resolved host and refuse on a failed read
for any non-canonical origin (BankID: step resolve_origin before
generateLink; hook: 500 so Supabase retries). On the canonical origin a
failed read is the platform sender either way, so mail still goes out.

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

* fix(auth): treat a credential-bearing redirect_to as untrusted in the email hook

Superagent P2: URL.origin drops userinfo, so a redirect_to with credentials
on a served host passed the origin comparison and was cloned into the auth
link with the credentials still in it. No flow of ours sends one; the hook
now rejects any redirect_to carrying username or password outright and
links to the canonical /auth/callback with no next path.

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

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
Mattsson
2026-09-07 16:29:29 +02:00
committed by GitHub
co-authored by Claude Fable 5.1
parent e0244b95a7
commit cb962fae88
7 changed files with 376 additions and 74 deletions
@@ -13,6 +13,13 @@
* pending identity tries to log in, which includes accounts created by the
* old flow (confirmed by admin, address never proven). Verifying a magic link
* confirms an unconfirmed address as a side effect, so both cases converge.
*
* This is the one auth mail GoTrue's redirect allowlist never sees: the link
* is built here and sent through the platform email service, so the host it
* points at is resolved through lib/domains/trusted-app-origin like every
* other auth link (canonical, this deployment's own Vercel hosts, or a
* registered brand domain). The raw Host header is an input, never the
* destination.
*/
import type { SupabaseClient } from '@supabase/supabase-js'
@@ -20,7 +27,12 @@ import { getEmailService } from '@/lib/email/service'
import { buildAuthEmail } from '@/lib/email/auth-templates'
import { getSenderForBrand } from '@/lib/email/brand-sender'
import { getBranding } from '@/lib/branding/service'
import { resolveBrandByHost } from '@/lib/branding/resolve'
import { resolveBrandResultByHost } from '@/lib/branding/resolve'
import {
BrandLookupFailedError,
getCanonicalAppOrigin,
resolveTrustedAppOrigin,
} from '@/lib/domains/trusted-app-origin'
import { createLogger } from '@/lib/logger'
const log = createLogger('tic/bankid-confirmation-mail')
@@ -32,26 +44,18 @@ export interface SendBankIdConfirmationInput {
email: string
/** Forwarded host of the request, '' when unknown. */
host: string
/** Forwarded protocol of the request; defaults to https. */
proto?: string | null
}
export type SendBankIdConfirmationResult =
| { ok: true }
| { ok: false; step: 'generate_link' | 'send'; message?: string }
| { ok: false; step: 'resolve_origin' | 'generate_link' | 'send'; message?: string }
/**
* Confirmation links must land on the ORIGINATING host (the brand mail
* resolves its brand from it), mirroring POST /api/auth/signup. With no host
* (direct invocation, tests) the canonical app URL is used.
* The verify link on an already-trusted application origin. Callers resolve
* the origin first (resolveTrustedAppOrigin), so this never sees a raw host.
*/
export function buildConfirmationUrl(
host: string,
proto: string | null | undefined,
tokenHash: string,
): string {
const base = host ? `${proto || 'https'}://${host}` : getBranding().appUrl
const url = new URL('/auth/callback', base)
export function buildConfirmationUrl(origin: string, tokenHash: string): string {
const url = new URL('/auth/callback', origin)
url.searchParams.set('token_hash', tokenHash)
url.searchParams.set('type', 'magiclink')
return url.toString()
@@ -60,6 +64,31 @@ export function buildConfirmationUrl(
export async function sendBankIdSignupConfirmation(
input: SendBankIdConfirmationInput,
): Promise<SendBankIdConfirmationResult> {
// Resolve the destination BEFORE minting a link: a token is only ever
// generated for a host this deployment is known to serve. An unknown host
// falls back to the canonical origin; an unreadable brands table refuses
// (a wrong-brand link whose session lands on a foreign domain is the
// failure this registry exists to prevent), and the caller rolls the
// signup back so the person can simply retry.
let origin: string
try {
origin = await resolveTrustedAppOrigin(input.host)
} catch (err) {
if (!(err instanceof BrandLookupFailedError)) throw err
return { ok: false, step: 'resolve_origin', message: err.message }
}
// Sender identity from the RESOLVED host, read before the link is minted:
// a brand host whose brand row cannot be read right now must not get
// platform-branded mail carrying a brand link (a second registry read can
// fail after the first succeeded). On the canonical origin a failed read
// is the platform sender either way, so it does not block the mail.
const brandResult = await resolveBrandResultByHost(new URL(origin).hostname)
if (brandResult.lookupFailed && origin !== getCanonicalAppOrigin()) {
return { ok: false, step: 'resolve_origin', message: `brand lookup failed for ${origin}` }
}
const brand = brandResult.brand
const { data: link, error: linkError } = await input.supabase.auth.admin.generateLink({
type: 'magiclink',
email: input.email,
@@ -72,14 +101,13 @@ export async function sendBankIdSignupConfirmation(
return { ok: false, step: 'generate_link', message: linkError?.message }
}
const brand = input.host ? await resolveBrandByHost(input.host) : null
const sender = getSenderForBrand(brand)
const appName = brand?.appName ?? getBranding().appName
const mail = buildAuthEmail({
actionType: 'bankid_signup',
appName,
actionUrl: buildConfirmationUrl(input.host, input.proto, link.properties.hashed_token),
actionUrl: buildConfirmationUrl(origin, link.properties.hashed_token),
})
const result = await getEmailService().sendEmail({