fix(skatteverket): finish the BankID consent on the initiating origin, bound to the initiating user (#2373)
* fix(skatteverket): finish the BankID consent on the initiating origin, bound to the initiating user The Skatteverket OAuth callback answered NEXT_PUBLIC_APP_URL regardless of where the flow started, so on a white-label brand domain the popup's postMessage was dropped and the fallback redirect landed on the wrong origin without a session. On hosted, the initiator check from #2155 was bypassed by design because the registered callback host carries no app cookies, so a lured victim's BankID-authorised tokens could be stored under the user who started the flow. Flow state moves from six per-company extension_data keys to one oauth_flows row per flow (migration 20260907120000), consumed atomically. Hop 1 on the registered OAuth host consumes the state, stashes the provider code or error encrypted under a separate handoff id and 302s to the recorded origin; hop 2 there claims the handoff bound to that origin, requires the initiating user's session, re-checks membership and exchanges the code. Error pages keep the tab open. The self-hosted single-hop and the connector broker branch keep working. The hosted no-session exception, the legacy cookie-user fallback and the optional PKCE verifier are gone. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01T1YDNadz81eWo94j115bhH * fix(skatteverket): decide the callback hop by host, close the tab when the flow is unknown Skeptic findings on #2373. The hop comparison and the handoff claim used the request origin including its scheme, which Next derives from x-forwarded-proto; a self-hosted proxy that forwards Host without it (or rewrites Host to the upstream address) made every connect end in a state error. Hops are now compared by host only, and the handoff is claimed for the validated origin the host resolves to, scheme from configuration. Error pages answered before the flow row is known (unknown, expired or replayed state or handoff) post to a guessed origin that a brand opener never hears; they now close the tab so the panels' closed-tab watcher resets them instead of leaving Connect disabled. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01T1YDNadz81eWo94j115bhH * test(skatteverket): mock resolveBrandResultByHost for the merged login-redirect resolver Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01T1YDNadz81eWo94j115bhH * fix(skatteverket): bind the initiator before the flow is spent Superagent P2 on #2373: hop 2 deleted the handoff before the session and membership checks, so a signed-out or wrong-user arrival burned a live consent. The finishing hop now peeks the row for its initiator, binds the completing session to it, and only then consumes atomically. A session-less arrival is sent to /login on the initiating origin and resumes into the same callback URL; a different user is refused with the row left claimable for the initiator. The handoff TTL is five minutes so a sign-in fits. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01T1YDNadz81eWo94j115bhH * fix(skatteverket): check membership before the flow is spent, answer the callback page on a failed mint Second review cycle on #2373. Superagent: the company-membership check ran after the consume, so a revoked initiator burned the provider code on the way to being refused; it now runs inside the pre-consume binding. CodeRabbit: a failed handoff mint escaped as a framework error page the opener never hears; it now answers the callback error page on the initiating origin. Co-Authored-By: Claude Fable 5.1 <[email protected]> Claude-Session: https://claude.ai/code/session_01T1YDNadz81eWo94j115bhH --------- Co-authored-by: Claude Fable 5.1 <[email protected]>
This commit is contained in:
co-authored by
Claude Fable 5.1
parent
cb962fae88
commit
f047c3d7d1
File diff suppressed because one or more lines are too long
@@ -2,8 +2,8 @@
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest'
|
||||
|
||||
// The route is exercised through the extension registration; the connector
|
||||
// seam and the paywall gate are mocked so the test pins ONLY the /authorize
|
||||
// wiring: what is stored, and where the browser is sent.
|
||||
// seam, the paywall gate and the flow store are mocked so the test pins ONLY
|
||||
// the /authorize wiring: what is recorded, and where the browser is sent.
|
||||
const { mockConnectorMode, mockStartAuth } = vi.hoisted(() => ({
|
||||
mockConnectorMode: vi.fn(),
|
||||
mockStartAuth: vi.fn(),
|
||||
@@ -27,6 +27,28 @@ vi.mock('@/lib/entitlements/has-capability', () => ({
|
||||
requireCapability: vi.fn(async () => null),
|
||||
}))
|
||||
|
||||
const { mockCreateFlow, mockPurge, mockResolveOrigin, mockNewId } = vi.hoisted(() => ({
|
||||
mockCreateFlow: vi.fn(),
|
||||
mockPurge: vi.fn(),
|
||||
mockResolveOrigin: vi.fn(),
|
||||
mockNewId: vi.fn(),
|
||||
}))
|
||||
vi.mock('@/lib/auth/oauth-flows', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import('@/lib/auth/oauth-flows')>()
|
||||
return {
|
||||
...actual,
|
||||
createOAuthFlow: mockCreateFlow,
|
||||
purgeExpiredOAuthFlows: mockPurge,
|
||||
resolveOAuthOrigin: mockResolveOrigin,
|
||||
newOAuthFlowId: mockNewId,
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('@/lib/supabase/server', () => ({
|
||||
createClient: vi.fn(),
|
||||
createServiceClient: vi.fn(() => ({ tag: 'service' })),
|
||||
}))
|
||||
|
||||
import { skatteverketExtension } from '../index'
|
||||
import { buildAuthorizeUrl } from '../lib/oauth'
|
||||
|
||||
@@ -38,33 +60,21 @@ function authorizeRoute() {
|
||||
return route!
|
||||
}
|
||||
|
||||
function makeCtx() {
|
||||
const stored: Record<string, string> = {}
|
||||
const cleared: string[] = []
|
||||
return {
|
||||
stored,
|
||||
cleared,
|
||||
ctx: {
|
||||
userId: 'user-1',
|
||||
companyId: 'company-1',
|
||||
supabase: {} as any,
|
||||
settings: {
|
||||
set: vi.fn(async (key: string, value: string) => {
|
||||
stored[key] = value
|
||||
}),
|
||||
clear: vi.fn(async (key: string) => {
|
||||
cleared.push(key)
|
||||
}),
|
||||
get: vi.fn(async () => null),
|
||||
},
|
||||
} as any,
|
||||
}
|
||||
}
|
||||
const ctx = {
|
||||
userId: 'user-1',
|
||||
companyId: 'company-1',
|
||||
supabase: {} as any,
|
||||
settings: { set: vi.fn(), clear: vi.fn(), get: vi.fn(async () => null) },
|
||||
} as any
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
process.env.NEXT_PUBLIC_APP_URL = 'https://instans.example.se'
|
||||
delete process.env.NEXT_PUBLIC_SKV_OAUTH_BASE_URL
|
||||
mockNewId.mockReturnValue('state-fixed')
|
||||
mockResolveOrigin.mockResolvedValue('https://instans.example.se')
|
||||
mockPurge.mockResolvedValue(undefined)
|
||||
mockCreateFlow.mockResolvedValue(undefined)
|
||||
})
|
||||
|
||||
describe('skatteverket /authorize: connector mode', () => {
|
||||
@@ -80,8 +90,7 @@ describe('skatteverket /authorize: connector mode', () => {
|
||||
})
|
||||
})
|
||||
|
||||
it('starts the consent through the broker and stores its redirect_uri + connector_state', async () => {
|
||||
const { ctx, stored } = makeCtx()
|
||||
it('starts the consent through the broker and records its redirect_uri + connector_state on the flow', async () => {
|
||||
const res = await authorizeRoute().handler(
|
||||
new Request('https://instans.example.se/api/extensions/ext/skatteverket/authorize'),
|
||||
ctx,
|
||||
@@ -99,23 +108,33 @@ describe('skatteverket /authorize: connector mode', () => {
|
||||
// The instance's own callback: where the hosted SKV callback bounces
|
||||
// the browser back to.
|
||||
returnUrl: 'https://instans.example.se/api/extensions/ext/skatteverket/callback',
|
||||
state: stored.oauth_state,
|
||||
state: 'state-fixed',
|
||||
codeChallenge: 'pkce-c',
|
||||
},
|
||||
)
|
||||
// The BROKER's redirect_uri (what SKV saw) is what the token exchange
|
||||
// must repeat, so it replaces the locally computed one.
|
||||
expect(stored.oauth_redirect_uri).toBe(
|
||||
'https://app.hosted.example/api/extensions/ext/skatteverket/callback',
|
||||
expect(mockCreateFlow).toHaveBeenCalledWith(
|
||||
{ tag: 'service' },
|
||||
{
|
||||
id: 'state-fixed',
|
||||
kind: 'skatteverket',
|
||||
companyId: 'company-1',
|
||||
userId: 'user-1',
|
||||
origin: 'https://instans.example.se',
|
||||
redirectUri: 'https://app.hosted.example/api/extensions/ext/skatteverket/callback',
|
||||
codeVerifier: 'pkce-v',
|
||||
connectorState: 'signed-cs',
|
||||
returnTo: null,
|
||||
},
|
||||
)
|
||||
expect(stored.oauth_connector_state).toBe('signed-cs')
|
||||
expect(stored.oauth_code_verifier).toBe('pkce-v')
|
||||
expect(buildAuthorizeUrl).not.toHaveBeenCalled()
|
||||
// Nothing goes through extension settings any more.
|
||||
expect(ctx.settings.set).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('answers 502 with operator guidance when the broker refuses, storing no flow state', async () => {
|
||||
it('answers 502 with operator guidance when the broker refuses, recording no flow', async () => {
|
||||
mockStartAuth.mockRejectedValueOnce(new Error('Connector authorize-url failed (403): quota'))
|
||||
const { ctx, stored } = makeCtx()
|
||||
const res = await authorizeRoute().handler(
|
||||
new Request('https://instans.example.se/api/extensions/ext/skatteverket/authorize'),
|
||||
ctx,
|
||||
@@ -124,27 +143,65 @@ describe('skatteverket /authorize: connector mode', () => {
|
||||
expect(res.status).toBe(502)
|
||||
const body = await (res as Response).json()
|
||||
expect(body.error).toMatch(/GNUBOK_CONNECTOR_KEY/)
|
||||
expect(Object.keys(stored)).toHaveLength(0)
|
||||
expect(mockCreateFlow).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('skatteverket /authorize: direct mode', () => {
|
||||
it('builds the authorize URL locally and clears any stale connector state', async () => {
|
||||
beforeEach(() => {
|
||||
mockConnectorMode.mockReturnValue(null)
|
||||
const { ctx, stored, cleared } = makeCtx()
|
||||
})
|
||||
|
||||
it('builds the authorize URL locally and records the validated origin, return path and PKCE verifier', async () => {
|
||||
process.env.NEXT_PUBLIC_SKV_OAUTH_BASE_URL = 'https://oauth.example'
|
||||
mockResolveOrigin.mockResolvedValue('https://brand.example')
|
||||
|
||||
const res = await authorizeRoute().handler(
|
||||
new Request('https://instans.example.se/api/extensions/ext/skatteverket/authorize'),
|
||||
new Request('https://brand.example/api/extensions/ext/skatteverket/authorize?return_to=%2Fsettings%2Ftax'),
|
||||
ctx,
|
||||
)
|
||||
|
||||
expect(res.status).toBe(307)
|
||||
expect(res.headers.get('location')).toBe('https://skv.test/authorize?direct=1')
|
||||
expect(mockStartAuth).not.toHaveBeenCalled()
|
||||
expect(stored.oauth_redirect_uri).toBe(
|
||||
'https://instans.example.se/api/extensions/ext/skatteverket/callback',
|
||||
expect(buildAuthorizeUrl).toHaveBeenCalledWith(
|
||||
'https://oauth.example/api/extensions/ext/skatteverket/callback',
|
||||
'state-fixed',
|
||||
{ codeChallenge: 'pkce-c' },
|
||||
)
|
||||
// A row surviving from a connector-era flow must not leak into a direct
|
||||
// exchange.
|
||||
expect(cleared).toContain('oauth_connector_state')
|
||||
expect(mockCreateFlow).toHaveBeenCalledWith(
|
||||
{ tag: 'service' },
|
||||
expect.objectContaining({
|
||||
id: 'state-fixed',
|
||||
origin: 'https://brand.example',
|
||||
redirectUri: 'https://oauth.example/api/extensions/ext/skatteverket/callback',
|
||||
codeVerifier: 'pkce-v',
|
||||
connectorState: null,
|
||||
returnTo: '/settings/tax',
|
||||
}),
|
||||
)
|
||||
// Expired rows are swept on the way in, best-effort.
|
||||
expect(mockPurge).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('drops a return_to that is not an in-app path', async () => {
|
||||
await authorizeRoute().handler(
|
||||
new Request('https://instans.example.se/api/extensions/ext/skatteverket/authorize?return_to=//evil.example'),
|
||||
ctx,
|
||||
)
|
||||
expect(mockCreateFlow).toHaveBeenCalledWith(
|
||||
expect.anything(),
|
||||
expect.objectContaining({ returnTo: null }),
|
||||
)
|
||||
})
|
||||
|
||||
it('still starts the flow when the purge fails', async () => {
|
||||
mockPurge.mockRejectedValueOnce(new Error('purge boom'))
|
||||
const res = await authorizeRoute().handler(
|
||||
new Request('https://instans.example.se/api/extensions/ext/skatteverket/authorize'),
|
||||
ctx,
|
||||
)
|
||||
expect(res.status).toBe(307)
|
||||
expect(mockCreateFlow).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
})
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,368 @@
|
||||
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
|
||||
const { mockResolveBrandByHost } = vi.hoisted(() => ({ mockResolveBrandByHost: vi.fn() }))
|
||||
vi.mock('@/lib/branding/resolve', () => ({ resolveBrandByHost: mockResolveBrandByHost }))
|
||||
|
||||
import {
|
||||
consumeOAuthFlowHandoff,
|
||||
consumeOAuthFlowState,
|
||||
createOAuthFlow,
|
||||
mintOAuthFlowHandoff,
|
||||
newOAuthFlowId,
|
||||
peekOAuthFlowHandoff,
|
||||
peekOAuthFlowState,
|
||||
purgeExpiredOAuthFlows,
|
||||
requestHost,
|
||||
requestMatchesOrigin,
|
||||
resolveOAuthOrigin,
|
||||
type OAuthFlow,
|
||||
} from '../oauth-flows'
|
||||
import { decryptOAuthFlowValue, encryptOAuthFlowValue } from '../oauth-flow-crypto'
|
||||
|
||||
/**
|
||||
* Chainable Supabase mock that records every builder call. Awaiting the
|
||||
* chain (insert / delete without select) resolves `terminal`; maybeSingle()
|
||||
* resolves it too.
|
||||
*/
|
||||
function makeDb(terminal: { data?: any; error?: any } = { data: null, error: null }) {
|
||||
const calls: Array<[string, unknown[]]> = []
|
||||
const chain: any = new Proxy(
|
||||
{},
|
||||
{
|
||||
get(_t, prop: string) {
|
||||
if (prop === 'then') {
|
||||
return (resolve: any, reject: any) => Promise.resolve(terminal).then(resolve, reject)
|
||||
}
|
||||
if (prop === 'maybeSingle') return vi.fn(async () => terminal)
|
||||
return (...args: unknown[]) => {
|
||||
calls.push([prop, args])
|
||||
return chain
|
||||
}
|
||||
},
|
||||
},
|
||||
)
|
||||
const db = { from: vi.fn(() => chain) }
|
||||
const call = (name: string) => calls.find(([n]) => n === name)?.[1]
|
||||
const payload = (name: string) => call(name)?.[0] as Record<string, any>
|
||||
return { db: db as any, calls, call, payload }
|
||||
}
|
||||
|
||||
const FLOW: OAuthFlow = {
|
||||
id: 'state-1',
|
||||
kind: 'skatteverket',
|
||||
companyId: 'company-1',
|
||||
userId: 'user-1',
|
||||
origin: 'https://brand.example',
|
||||
redirectUri: 'https://oauth.example/cb',
|
||||
codeVerifier: 'verifier-1',
|
||||
connectorState: null,
|
||||
returnTo: '/settings/tax',
|
||||
}
|
||||
|
||||
function rowFor(flow: OAuthFlow, extra: Record<string, unknown> = {}) {
|
||||
return {
|
||||
id: flow.id,
|
||||
kind: flow.kind,
|
||||
company_id: flow.companyId,
|
||||
user_id: flow.userId,
|
||||
origin: flow.origin,
|
||||
redirect_uri: flow.redirectUri,
|
||||
code_verifier:
|
||||
flow.codeVerifier === null
|
||||
? null
|
||||
: encryptOAuthFlowValue(
|
||||
flow.codeVerifier,
|
||||
JSON.stringify([flow.id, flow.userId, flow.origin, 'code_verifier']),
|
||||
),
|
||||
connector_state: flow.connectorState,
|
||||
return_to: flow.returnTo,
|
||||
...extra,
|
||||
}
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
vi.stubEnv('SUPABASE_SERVICE_ROLE_KEY', 'test-service-role-secret')
|
||||
vi.stubEnv('NEXT_PUBLIC_APP_URL', 'https://app.example')
|
||||
mockResolveBrandByHost.mockResolvedValue(null)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllEnvs()
|
||||
})
|
||||
|
||||
describe('oauth-flow-crypto', () => {
|
||||
it('round-trips under the same context and refuses another', () => {
|
||||
const ct = encryptOAuthFlowValue('secret', 'ctx-a')
|
||||
expect(ct.startsWith('v1:')).toBe(true)
|
||||
expect(ct).not.toContain('secret')
|
||||
expect(decryptOAuthFlowValue(ct, 'ctx-a')).toBe('secret')
|
||||
expect(() => decryptOAuthFlowValue(ct, 'ctx-b')).toThrow()
|
||||
})
|
||||
|
||||
it('never accepts a plaintext value as a decryption', () => {
|
||||
expect(() => decryptOAuthFlowValue('secret', 'ctx')).toThrow(/ciphertext/)
|
||||
})
|
||||
})
|
||||
|
||||
describe('requestHost', () => {
|
||||
it('prefers the Host header over the reconstructed URL and normalises it', () => {
|
||||
const req = new Request('https://internal.example/cb', { headers: { host: 'Brand.Example.' } })
|
||||
expect(requestHost(req)).toBe('brand.example')
|
||||
})
|
||||
|
||||
it('falls back to the URL host for a malformed Host header', () => {
|
||||
const req = new Request('https://app.example/cb', { headers: { host: 'evil.example/path' } })
|
||||
expect(requestHost(req)).toBe('app.example')
|
||||
})
|
||||
|
||||
it('matches an origin by host regardless of the scheme the proxy reported', () => {
|
||||
// A TLS-terminating proxy that drops x-forwarded-proto makes Next
|
||||
// reconstruct request.url as http://; the host is what identifies the hop.
|
||||
const req = new Request('http://app.example/cb')
|
||||
expect(requestMatchesOrigin(req, 'https://app.example')).toBe(true)
|
||||
expect(requestMatchesOrigin(req, 'https://oauth.example')).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('resolveOAuthOrigin', () => {
|
||||
it('returns the app origin for the app host without a brand lookup, whatever scheme the proxy reported', async () => {
|
||||
expect(await resolveOAuthOrigin(new Request('https://app.example/x'))).toBe('https://app.example')
|
||||
expect(await resolveOAuthOrigin(new Request('http://app.example/x'))).toBe('https://app.example')
|
||||
expect(await resolveOAuthOrigin(new Request('http://APP.example./x'))).toBe('https://app.example')
|
||||
expect(mockResolveBrandByHost).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('treats an internal proxy upstream host as the app origin', async () => {
|
||||
// nginx defaults: Host rewritten to the upstream address, no proto header.
|
||||
expect(await resolveOAuthOrigin(new Request('http://127.0.0.1:3000/x'))).toBe('https://app.example')
|
||||
expect(mockResolveBrandByHost).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('returns a brand origin only when the brands table resolves the exact host', async () => {
|
||||
mockResolveBrandByHost.mockResolvedValue({ domain: 'brand.example' })
|
||||
expect(await resolveOAuthOrigin(new Request('https://brand.example/x'))).toBe('https://brand.example')
|
||||
|
||||
mockResolveBrandByHost.mockResolvedValue({ domain: 'other.example' })
|
||||
expect(await resolveOAuthOrigin(new Request('https://brand.example/x'))).toBe('https://app.example')
|
||||
|
||||
mockResolveBrandByHost.mockResolvedValue(null)
|
||||
expect(await resolveOAuthOrigin(new Request('https://stranger.example/x'))).toBe('https://app.example')
|
||||
})
|
||||
|
||||
it('always answers a known brand as HTTPS and never a non-default port', async () => {
|
||||
mockResolveBrandByHost.mockResolvedValue({ domain: 'brand.example' })
|
||||
expect(await resolveOAuthOrigin(new Request('http://brand.example/x'))).toBe('https://brand.example')
|
||||
expect(await resolveOAuthOrigin(new Request('https://brand.example:8443/x'))).toBe('https://app.example')
|
||||
})
|
||||
})
|
||||
|
||||
describe('createOAuthFlow', () => {
|
||||
it('stores the verifier encrypted and bound to the row identity', async () => {
|
||||
const { db, payload } = makeDb({ error: null })
|
||||
await createOAuthFlow(db, {
|
||||
id: 'state-1',
|
||||
kind: 'skatteverket',
|
||||
companyId: 'company-1',
|
||||
userId: 'user-1',
|
||||
origin: 'https://brand.example',
|
||||
redirectUri: 'https://oauth.example/cb',
|
||||
codeVerifier: 'verifier-1',
|
||||
connectorState: 'cs',
|
||||
returnTo: '/settings/tax',
|
||||
})
|
||||
const row = payload('insert')
|
||||
expect(row).toMatchObject({
|
||||
id: 'state-1',
|
||||
kind: 'skatteverket',
|
||||
company_id: 'company-1',
|
||||
user_id: 'user-1',
|
||||
origin: 'https://brand.example',
|
||||
redirect_uri: 'https://oauth.example/cb',
|
||||
connector_state: 'cs',
|
||||
return_to: '/settings/tax',
|
||||
})
|
||||
expect(row.code_verifier).not.toContain('verifier-1')
|
||||
expect(
|
||||
decryptOAuthFlowValue(
|
||||
row.code_verifier,
|
||||
JSON.stringify(['state-1', 'user-1', 'https://brand.example', 'code_verifier']),
|
||||
),
|
||||
).toBe('verifier-1')
|
||||
const ttl = new Date(row.expires_at).getTime() - Date.now()
|
||||
expect(ttl).toBeGreaterThan(9 * 60 * 1000)
|
||||
expect(ttl).toBeLessThanOrEqual(10 * 60 * 1000)
|
||||
})
|
||||
|
||||
it('throws when the insert fails', async () => {
|
||||
const { db } = makeDb({ error: { message: 'boom' } })
|
||||
await expect(
|
||||
createOAuthFlow(db, {
|
||||
id: 's',
|
||||
kind: 'skatteverket',
|
||||
companyId: 'c',
|
||||
userId: 'u',
|
||||
origin: 'https://app.example',
|
||||
redirectUri: 'https://app.example/cb',
|
||||
}),
|
||||
).rejects.toThrow(/boom/)
|
||||
})
|
||||
|
||||
it('mints unguessable ids', () => {
|
||||
const a = newOAuthFlowId()
|
||||
expect(a).toHaveLength(43)
|
||||
expect(newOAuthFlowId()).not.toBe(a)
|
||||
})
|
||||
})
|
||||
|
||||
describe('consumeOAuthFlowState', () => {
|
||||
it('consumes with the whole check in the predicate and returns the decrypted flow', async () => {
|
||||
const { db, calls, call } = makeDb({ data: rowFor(FLOW), error: null })
|
||||
const flow = await consumeOAuthFlowState(db, 'state-1', 'skatteverket')
|
||||
expect(flow).toEqual(FLOW)
|
||||
expect(call('update')?.[0]).toMatchObject({ used_at: expect.any(String) })
|
||||
expect(calls).toEqual(
|
||||
expect.arrayContaining([
|
||||
['eq', ['id', 'state-1']],
|
||||
['eq', ['kind', 'skatteverket']],
|
||||
['is', ['used_at', null]],
|
||||
['gt', ['expires_at', expect.any(String)]],
|
||||
]),
|
||||
)
|
||||
})
|
||||
|
||||
it('returns null for no row, a query error, and an unreadable verifier', async () => {
|
||||
expect(await consumeOAuthFlowState(makeDb({ data: null, error: null }).db, 's', 'skatteverket')).toBeNull()
|
||||
expect(
|
||||
await consumeOAuthFlowState(makeDb({ data: null, error: { message: 'x' } }).db, 's', 'skatteverket'),
|
||||
).toBeNull()
|
||||
const tampered = rowFor(FLOW, { code_verifier: 'v1:not-really' })
|
||||
expect(await consumeOAuthFlowState(makeDb({ data: tampered, error: null }).db, 's', 'skatteverket')).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('mintOAuthFlowHandoff / consumeOAuthFlowHandoff', () => {
|
||||
it('stashes the provider code encrypted under a fresh handoff id, only onto a consumed row', async () => {
|
||||
const { db, calls, payload } = makeDb({ data: { id: 'state-1' }, error: null })
|
||||
const handoffId = await mintOAuthFlowHandoff(db, FLOW, { providerCode: 'code-1' })
|
||||
expect(handoffId).not.toBe(FLOW.id)
|
||||
const row = payload('update')
|
||||
expect(row.handoff_id).toBe(handoffId)
|
||||
expect(row.handoff_error).toBeNull()
|
||||
expect(row.handoff_code).not.toContain('code-1')
|
||||
expect(
|
||||
decryptOAuthFlowValue(
|
||||
row.handoff_code,
|
||||
JSON.stringify(['state-1', handoffId, 'user-1', 'https://brand.example', 'handoff_code']),
|
||||
),
|
||||
).toBe('code-1')
|
||||
const ttl = new Date(row.handoff_expires_at).getTime() - Date.now()
|
||||
expect(ttl).toBeGreaterThan(4 * 60 * 1000)
|
||||
expect(ttl).toBeLessThanOrEqual(5 * 60 * 1000)
|
||||
expect(calls).toEqual(
|
||||
expect.arrayContaining([
|
||||
['eq', ['id', 'state-1']],
|
||||
['is', ['handoff_id', null]],
|
||||
['not', ['used_at', 'is', null]],
|
||||
]),
|
||||
)
|
||||
})
|
||||
|
||||
it('throws when the row was already handed off', async () => {
|
||||
const { db } = makeDb({ data: null, error: null })
|
||||
await expect(mintOAuthFlowHandoff(db, FLOW, { providerError: 'nej' })).rejects.toThrow(/handed off/)
|
||||
})
|
||||
|
||||
it('claims the handoff bound to the origin and returns the decrypted result', async () => {
|
||||
const handoffId = 'handoff-1'
|
||||
const ctx = (col: string) => JSON.stringify(['state-1', handoffId, 'user-1', 'https://brand.example', col])
|
||||
const row = rowFor(FLOW, {
|
||||
handoff_code: encryptOAuthFlowValue('code-1', ctx('handoff_code')),
|
||||
handoff_error: null,
|
||||
})
|
||||
const { db, calls } = makeDb({ data: row, error: null })
|
||||
const result = await consumeOAuthFlowHandoff(db, handoffId, 'https://brand.example', 'skatteverket')
|
||||
expect(result).toEqual({ ...FLOW, providerCode: 'code-1', providerError: null })
|
||||
expect(calls[0]?.[0]).toBe('delete')
|
||||
expect(calls).toEqual(
|
||||
expect.arrayContaining([
|
||||
['eq', ['handoff_id', handoffId]],
|
||||
['eq', ['origin', 'https://brand.example']],
|
||||
['eq', ['kind', 'skatteverket']],
|
||||
['gt', ['handoff_expires_at', expect.any(String)]],
|
||||
]),
|
||||
)
|
||||
})
|
||||
|
||||
it('returns null for a missing row and for a tampered payload', async () => {
|
||||
expect(
|
||||
await consumeOAuthFlowHandoff(makeDb({ data: null, error: null }).db, 'h', 'https://brand.example', 'skatteverket'),
|
||||
).toBeNull()
|
||||
const row = rowFor(FLOW, { handoff_code: 'v1:garbage', handoff_error: null })
|
||||
expect(
|
||||
await consumeOAuthFlowHandoff(makeDb({ data: row, error: null }).db, 'h', 'https://brand.example', 'skatteverket'),
|
||||
).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('peekOAuthFlowState / peekOAuthFlowHandoff', () => {
|
||||
it('reads a live state identity without writing, with the same liveness predicate as the consume', async () => {
|
||||
const { db, calls } = makeDb({ data: { user_id: 'user-1', company_id: 'company-1', origin: 'https://brand.example' }, error: null })
|
||||
expect(await peekOAuthFlowState(db, 'state-1', 'skatteverket')).toEqual({
|
||||
userId: 'user-1',
|
||||
companyId: 'company-1',
|
||||
origin: 'https://brand.example',
|
||||
})
|
||||
expect(calls[0]?.[0]).toBe('select')
|
||||
expect(calls.map(([n]) => n)).not.toContain('update')
|
||||
expect(calls.map(([n]) => n)).not.toContain('delete')
|
||||
expect(calls).toEqual(
|
||||
expect.arrayContaining([
|
||||
['eq', ['id', 'state-1']],
|
||||
['eq', ['kind', 'skatteverket']],
|
||||
['is', ['used_at', null]],
|
||||
['gt', ['expires_at', expect.any(String)]],
|
||||
]),
|
||||
)
|
||||
})
|
||||
|
||||
it('reads a live handoff identity bound to the origin, without writing', async () => {
|
||||
const { db, calls } = makeDb({ data: { user_id: 'user-1', company_id: 'company-1', origin: 'https://brand.example' }, error: null })
|
||||
expect(await peekOAuthFlowHandoff(db, 'handoff-1', 'https://brand.example', 'skatteverket')).toEqual({
|
||||
userId: 'user-1',
|
||||
companyId: 'company-1',
|
||||
origin: 'https://brand.example',
|
||||
})
|
||||
expect(calls[0]?.[0]).toBe('select')
|
||||
expect(calls).toEqual(
|
||||
expect.arrayContaining([
|
||||
['eq', ['handoff_id', 'handoff-1']],
|
||||
['eq', ['origin', 'https://brand.example']],
|
||||
['eq', ['kind', 'skatteverket']],
|
||||
['gt', ['handoff_expires_at', expect.any(String)]],
|
||||
]),
|
||||
)
|
||||
})
|
||||
|
||||
it('returns null for no row or a query error', async () => {
|
||||
expect(await peekOAuthFlowState(makeDb({ data: null, error: null }).db, 's', 'skatteverket')).toBeNull()
|
||||
expect(
|
||||
await peekOAuthFlowHandoff(makeDb({ data: null, error: { message: 'x' } }).db, 'h', 'https://brand.example', 'skatteverket'),
|
||||
).toBeNull()
|
||||
})
|
||||
})
|
||||
|
||||
describe('purgeExpiredOAuthFlows', () => {
|
||||
it('deletes only rows nothing can consume any more', async () => {
|
||||
const { db, calls } = makeDb({ error: null })
|
||||
await purgeExpiredOAuthFlows(db)
|
||||
expect(calls[0]?.[0]).toBe('delete')
|
||||
expect(calls).toEqual(
|
||||
expect.arrayContaining([
|
||||
['lt', ['expires_at', expect.any(String)]],
|
||||
['or', [expect.stringMatching(/^handoff_expires_at\.is\.null,handoff_expires_at\.lt\./)]],
|
||||
]),
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,35 @@
|
||||
import { createCipheriv, createDecipheriv, createHash, randomBytes } from 'node:crypto'
|
||||
|
||||
/**
|
||||
* At-rest encryption for the secrets an oauth_flows row holds between
|
||||
* /authorize and /callback: the PKCE verifier, and during the two-minute
|
||||
* brand handoff the provider's authorization code or error text.
|
||||
*
|
||||
* Same construction as the provider OAuth handoff (PR #2305): AES-256-GCM
|
||||
* under a purpose-scoped derivation of the server-only service-role secret,
|
||||
* which every deployment already has, with the row identity as additional
|
||||
* authenticated data so a ciphertext cannot be moved between rows or
|
||||
* columns. Plaintext or unreadable values never decrypt successfully.
|
||||
*/
|
||||
function getKey(): Buffer {
|
||||
const secret = process.env.SUPABASE_SERVICE_ROLE_KEY
|
||||
if (!secret) throw new Error('SUPABASE_SERVICE_ROLE_KEY is required')
|
||||
return createHash('sha256').update('oauth-flows:v1:' + secret).digest()
|
||||
}
|
||||
|
||||
export function encryptOAuthFlowValue(plaintext: string, context: string): string {
|
||||
const iv = randomBytes(12)
|
||||
const cipher = createCipheriv('aes-256-gcm', getKey(), iv)
|
||||
cipher.setAAD(Buffer.from(context))
|
||||
const encrypted = Buffer.concat([cipher.update(plaintext, 'utf8'), cipher.final()])
|
||||
return 'v1:' + Buffer.concat([iv, cipher.getAuthTag(), encrypted]).toString('base64url')
|
||||
}
|
||||
|
||||
export function decryptOAuthFlowValue(ciphertext: string, context: string): string {
|
||||
if (!ciphertext.startsWith('v1:')) throw new Error('Invalid OAuth flow ciphertext')
|
||||
const combined = Buffer.from(ciphertext.slice(3), 'base64url')
|
||||
const decipher = createDecipheriv('aes-256-gcm', getKey(), combined.subarray(0, 12))
|
||||
decipher.setAAD(Buffer.from(context))
|
||||
decipher.setAuthTag(combined.subarray(12, 28))
|
||||
return Buffer.concat([decipher.update(combined.subarray(28)), decipher.final()]).toString('utf8')
|
||||
}
|
||||
@@ -0,0 +1,369 @@
|
||||
import { randomBytes } from 'node:crypto'
|
||||
import type { SupabaseClient } from '@supabase/supabase-js'
|
||||
import { resolveBrandByHost } from '@/lib/branding/resolve'
|
||||
import { decryptOAuthFlowValue, encryptOAuthFlowValue } from './oauth-flow-crypto'
|
||||
|
||||
/**
|
||||
* Server-side state for a browser-driven OAuth flow that must finish on the
|
||||
* origin it started from, for the user who started it (table oauth_flows,
|
||||
* migration 20260907120000).
|
||||
*
|
||||
* The `state` handed to the provider is the row id: a random token that
|
||||
* encodes nothing. The row records who started the flow (user + company),
|
||||
* where (the validated app or brand origin), and what the token exchange
|
||||
* must repeat (redirect URI, PKCE verifier, connector state).
|
||||
*
|
||||
* Hosted, the provider redirects to a registered callback host that carries
|
||||
* no app session cookies. The callback there consumes the state (hop 1),
|
||||
* stashes the provider's code or error encrypted on the row under a separate
|
||||
* handoff id, and redirects to the recorded origin. The callback on that
|
||||
* origin consumes the handoff (hop 2), has the initiator's cookies, and can
|
||||
* bind the completion to the initiating user before exchanging the code.
|
||||
*
|
||||
* Every consume is a single UPDATE or DELETE whose WHERE clause is the whole
|
||||
* check: a replayed or concurrent callback loses the row-lock race and gets
|
||||
* null, with no read-then-write window. Every failure mode (unknown, forged,
|
||||
* expired, consumed, wrong origin, unreadable ciphertext) is the same null:
|
||||
* the callbacks are unauthenticated and must not be an oracle.
|
||||
*/
|
||||
|
||||
export type OAuthFlowKind = 'skatteverket'
|
||||
|
||||
export interface OAuthFlow {
|
||||
id: string
|
||||
kind: OAuthFlowKind
|
||||
companyId: string
|
||||
userId: string
|
||||
origin: string
|
||||
redirectUri: string
|
||||
codeVerifier: string | null
|
||||
connectorState: string | null
|
||||
returnTo: string | null
|
||||
}
|
||||
|
||||
export interface OAuthFlowHandoff extends OAuthFlow {
|
||||
providerCode: string | null
|
||||
providerError: string | null
|
||||
}
|
||||
|
||||
/** How long an authorize URL stays completable. */
|
||||
export const OAUTH_FLOW_TTL_SECONDS = 10 * 60
|
||||
/**
|
||||
* How long hop 1's stash stays claimable by hop 2. Long enough for the
|
||||
* initiator to sign in again when hop 2 finds no session (the login page
|
||||
* forwards straight back into the callback); the provider code inside it
|
||||
* expires on the provider's side anyway.
|
||||
*/
|
||||
export const OAUTH_FLOW_HANDOFF_TTL_SECONDS = 5 * 60
|
||||
|
||||
// Column set every consume returns; decrypted into an OAuthFlow below.
|
||||
const FLOW_COLUMNS =
|
||||
'id, kind, company_id, user_id, origin, redirect_uri, code_verifier, connector_state, return_to'
|
||||
|
||||
type FlowRow = {
|
||||
id: string
|
||||
kind: string
|
||||
company_id: string
|
||||
user_id: string
|
||||
origin: string
|
||||
redirect_uri: string
|
||||
code_verifier: string | null
|
||||
connector_state: string | null
|
||||
return_to: string | null
|
||||
}
|
||||
|
||||
export function newOAuthFlowId(): string {
|
||||
return randomBytes(32).toString('base64url')
|
||||
}
|
||||
|
||||
function verifierContext(row: { id: string; user_id: string; origin: string }): string {
|
||||
return JSON.stringify([row.id, row.user_id, row.origin, 'code_verifier'])
|
||||
}
|
||||
|
||||
function handoffContext(
|
||||
row: { id: string; user_id: string; origin: string },
|
||||
handoffId: string,
|
||||
column: 'handoff_code' | 'handoff_error',
|
||||
): string {
|
||||
return JSON.stringify([row.id, handoffId, row.user_id, row.origin, column])
|
||||
}
|
||||
|
||||
function rowToFlow(row: FlowRow): OAuthFlow {
|
||||
return {
|
||||
id: row.id,
|
||||
kind: row.kind as OAuthFlowKind,
|
||||
companyId: row.company_id,
|
||||
userId: row.user_id,
|
||||
origin: row.origin,
|
||||
redirectUri: row.redirect_uri,
|
||||
codeVerifier: row.code_verifier === null ? null : decryptOAuthFlowValue(row.code_verifier, verifierContext(row)),
|
||||
connectorState: row.connector_state,
|
||||
returnTo: row.return_to,
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeHost(host: string): string {
|
||||
return host.trim().toLowerCase().replace(/\.$/, '').replace(/\.(?=:\d+$)/, '')
|
||||
}
|
||||
|
||||
/**
|
||||
* The host the browser addressed, from the Host header (what the browser
|
||||
* typed) rather than the URL Next.js reconstructed. Only the host: the
|
||||
* scheme of request.url comes from x-forwarded-proto, which a self-hoster's
|
||||
* reverse proxy may not send, and must never decide whether two hops are on
|
||||
* the same origin. Anything that is not a bare host falls back to the URL.
|
||||
*/
|
||||
export function requestHost(request: Request): string {
|
||||
const url = new URL(request.url)
|
||||
const host = request.headers.get('host') ?? url.host
|
||||
try {
|
||||
const candidate = new URL(`https://${host}`)
|
||||
if (
|
||||
candidate.host !== host.toLowerCase() ||
|
||||
candidate.pathname !== '/' ||
|
||||
candidate.search ||
|
||||
candidate.hash
|
||||
) {
|
||||
return normalizeHost(url.host)
|
||||
}
|
||||
return normalizeHost(candidate.host)
|
||||
} catch {
|
||||
return normalizeHost(url.host)
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether the request was addressed to the host of `origin`. */
|
||||
export function requestMatchesOrigin(request: Request, origin: string): boolean {
|
||||
return requestHost(request) === normalizeHost(new URL(origin).host)
|
||||
}
|
||||
|
||||
/**
|
||||
* The origin a flow started on (or, on hop 2, arrived on), validated: the
|
||||
* canonical app origin, or an HTTPS brand domain that resolves in the brands
|
||||
* table. Decided by host alone with the scheme taken from configuration, so
|
||||
* a proxy that forwards Host without x-forwarded-proto still resolves to the
|
||||
* same origin on every hop. Anything else (an unknown host, a non-default
|
||||
* port) is treated as the app origin, so a forged Host header can never make
|
||||
* the callback hand a code to a stranger.
|
||||
*/
|
||||
export async function resolveOAuthOrigin(request: Request): Promise<string> {
|
||||
const appOrigin = new URL(process.env.NEXT_PUBLIC_APP_URL || request.url).origin
|
||||
const host = requestHost(request)
|
||||
if (host === normalizeHost(new URL(appOrigin).host)) return appOrigin
|
||||
if (host.includes(':')) return appOrigin
|
||||
const brand = await resolveBrandByHost(host)
|
||||
return brand && normalizeHost(new URL(`https://${brand.domain}`).host) === host
|
||||
? `https://${host}`
|
||||
: appOrigin
|
||||
}
|
||||
|
||||
export interface CreateOAuthFlowInput {
|
||||
id: string
|
||||
kind: OAuthFlowKind
|
||||
companyId: string
|
||||
userId: string
|
||||
origin: string
|
||||
redirectUri: string
|
||||
codeVerifier?: string | null
|
||||
connectorState?: string | null
|
||||
returnTo?: string | null
|
||||
ttlSeconds?: number
|
||||
}
|
||||
|
||||
/** Insert the flow row. `id` is the state the caller sends to the provider. */
|
||||
export async function createOAuthFlow(db: SupabaseClient, input: CreateOAuthFlowInput): Promise<void> {
|
||||
const ttl = input.ttlSeconds ?? OAUTH_FLOW_TTL_SECONDS
|
||||
const identity = { id: input.id, user_id: input.userId, origin: input.origin }
|
||||
const { error } = await db.from('oauth_flows').insert({
|
||||
id: input.id,
|
||||
kind: input.kind,
|
||||
company_id: input.companyId,
|
||||
user_id: input.userId,
|
||||
origin: input.origin,
|
||||
redirect_uri: input.redirectUri,
|
||||
code_verifier:
|
||||
input.codeVerifier == null ? null : encryptOAuthFlowValue(input.codeVerifier, verifierContext(identity)),
|
||||
connector_state: input.connectorState ?? null,
|
||||
return_to: input.returnTo ?? null,
|
||||
expires_at: new Date(Date.now() + ttl * 1000).toISOString(),
|
||||
})
|
||||
if (error) throw new Error(`Failed to create OAuth flow: ${error.message}`)
|
||||
}
|
||||
|
||||
/** Who a flow belongs to and where it must finish, without consuming it. */
|
||||
export interface OAuthFlowIdentity {
|
||||
userId: string
|
||||
companyId: string
|
||||
origin: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Read a live state's identity without consuming it, so the callback can
|
||||
* bind the completing browser to the initiator BEFORE the one-shot state is
|
||||
* spent: a session-less arrival is sent to login and resumes, a wrong user
|
||||
* is refused, and the true initiator can still finish. Never trusted for
|
||||
* anything but that identity check; the consume below is the gate.
|
||||
*/
|
||||
export async function peekOAuthFlowState(
|
||||
db: SupabaseClient,
|
||||
state: string,
|
||||
kind: OAuthFlowKind,
|
||||
): Promise<OAuthFlowIdentity | null> {
|
||||
const { data, error } = await db
|
||||
.from('oauth_flows')
|
||||
.select('user_id, company_id, origin')
|
||||
.eq('id', state)
|
||||
.eq('kind', kind)
|
||||
.is('used_at', null)
|
||||
.gt('expires_at', new Date().toISOString())
|
||||
.maybeSingle()
|
||||
if (error || !data) return null
|
||||
return {
|
||||
userId: data.user_id as string,
|
||||
companyId: data.company_id as string,
|
||||
origin: data.origin as string,
|
||||
}
|
||||
}
|
||||
|
||||
/** Same as peekOAuthFlowState, for a live handoff bound to `origin`. */
|
||||
export async function peekOAuthFlowHandoff(
|
||||
db: SupabaseClient,
|
||||
handoffId: string,
|
||||
origin: string,
|
||||
kind: OAuthFlowKind,
|
||||
): Promise<OAuthFlowIdentity | null> {
|
||||
const { data, error } = await db
|
||||
.from('oauth_flows')
|
||||
.select('user_id, company_id, origin')
|
||||
.eq('handoff_id', handoffId)
|
||||
.eq('origin', origin)
|
||||
.eq('kind', kind)
|
||||
.gt('handoff_expires_at', new Date().toISOString())
|
||||
.maybeSingle()
|
||||
if (error || !data) return null
|
||||
return {
|
||||
userId: data.user_id as string,
|
||||
companyId: data.company_id as string,
|
||||
origin: data.origin as string,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Consume the state once. The UPDATE's WHERE clause is the entire check:
|
||||
* unconsumed, unexpired, of the expected kind. Null for every failure.
|
||||
*/
|
||||
export async function consumeOAuthFlowState(
|
||||
db: SupabaseClient,
|
||||
state: string,
|
||||
kind: OAuthFlowKind,
|
||||
): Promise<OAuthFlow | null> {
|
||||
const now = new Date().toISOString()
|
||||
const { data, error } = await db
|
||||
.from('oauth_flows')
|
||||
.update({ used_at: now })
|
||||
.eq('id', state)
|
||||
.eq('kind', kind)
|
||||
.is('used_at', null)
|
||||
.gt('expires_at', now)
|
||||
.select(FLOW_COLUMNS)
|
||||
.maybeSingle()
|
||||
if (error || !data) return null
|
||||
try {
|
||||
return rowToFlow(data as FlowRow)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Hop 1: stash the provider's result on the consumed row under a fresh
|
||||
* handoff id, encrypted and bound to the row, the handoff id and the
|
||||
* destination origin. Returns the handoff id to put in the hop-2 URL.
|
||||
*/
|
||||
export async function mintOAuthFlowHandoff(
|
||||
db: SupabaseClient,
|
||||
flow: OAuthFlow,
|
||||
result: { providerCode: string; providerError?: never } | { providerCode?: never; providerError: string },
|
||||
): Promise<string> {
|
||||
const handoffId = newOAuthFlowId()
|
||||
const identity = { id: flow.id, user_id: flow.userId, origin: flow.origin }
|
||||
const { data, error } = await db
|
||||
.from('oauth_flows')
|
||||
.update({
|
||||
handoff_id: handoffId,
|
||||
handoff_code:
|
||||
result.providerCode === undefined
|
||||
? null
|
||||
: encryptOAuthFlowValue(result.providerCode, handoffContext(identity, handoffId, 'handoff_code')),
|
||||
handoff_error:
|
||||
result.providerError === undefined
|
||||
? null
|
||||
: encryptOAuthFlowValue(result.providerError, handoffContext(identity, handoffId, 'handoff_error')),
|
||||
handoff_expires_at: new Date(Date.now() + OAUTH_FLOW_HANDOFF_TTL_SECONDS * 1000).toISOString(),
|
||||
})
|
||||
.eq('id', flow.id)
|
||||
.is('handoff_id', null)
|
||||
.not('used_at', 'is', null)
|
||||
.select('id')
|
||||
.maybeSingle()
|
||||
if (error) throw new Error(`Failed to mint OAuth handoff: ${error.message}`)
|
||||
if (!data) throw new Error('Failed to mint OAuth handoff: flow already handed off')
|
||||
return handoffId
|
||||
}
|
||||
|
||||
/**
|
||||
* Hop 2: claim the handoff once, only from the origin it was minted for.
|
||||
* DELETE RETURNING, so the held provider code leaves the database the moment
|
||||
* it is read. Null for every failure, including unreadable ciphertext.
|
||||
*/
|
||||
export async function consumeOAuthFlowHandoff(
|
||||
db: SupabaseClient,
|
||||
handoffId: string,
|
||||
origin: string,
|
||||
kind: OAuthFlowKind,
|
||||
): Promise<OAuthFlowHandoff | null> {
|
||||
const { data, error } = await db
|
||||
.from('oauth_flows')
|
||||
.delete()
|
||||
.eq('handoff_id', handoffId)
|
||||
.eq('origin', origin)
|
||||
.eq('kind', kind)
|
||||
.gt('handoff_expires_at', new Date().toISOString())
|
||||
.select(`${FLOW_COLUMNS}, handoff_code, handoff_error`)
|
||||
.maybeSingle()
|
||||
if (error || !data) return null
|
||||
const row = data as FlowRow & { handoff_code: string | null; handoff_error: string | null }
|
||||
try {
|
||||
const identity = { id: row.id, user_id: row.user_id, origin: row.origin }
|
||||
return {
|
||||
...rowToFlow(row),
|
||||
providerCode:
|
||||
row.handoff_code === null
|
||||
? null
|
||||
: decryptOAuthFlowValue(row.handoff_code, handoffContext(identity, handoffId, 'handoff_code')),
|
||||
providerError:
|
||||
row.handoff_error === null
|
||||
? null
|
||||
: decryptOAuthFlowValue(row.handoff_error, handoffContext(identity, handoffId, 'handoff_error')),
|
||||
}
|
||||
} catch {
|
||||
// The row is already gone. Tampered or unreadable credentials get the
|
||||
// same answer as an unknown or expired handoff.
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Drop rows nothing can consume any more: an hour past state expiry, and
|
||||
* for rows that were handed off, an hour past handoff expiry too. Called
|
||||
* best-effort from /authorize; the row set is tiny and self-limiting.
|
||||
*/
|
||||
export async function purgeExpiredOAuthFlows(db: SupabaseClient): Promise<void> {
|
||||
const cutoff = new Date(Date.now() - 60 * 60 * 1000).toISOString()
|
||||
const { error } = await db
|
||||
.from('oauth_flows')
|
||||
.delete()
|
||||
.lt('expires_at', cutoff)
|
||||
.or(`handoff_expires_at.is.null,handoff_expires_at.lt.${cutoff}`)
|
||||
if (error) throw new Error(`Failed to purge OAuth flows: ${error.message}`)
|
||||
}
|
||||
@@ -1228,6 +1228,8 @@ export const ARCHIVE_EXCLUDED_TABLES: Record<string, string> = {
|
||||
mcp_tasks: 'MCP task handles: transient tool-call state with a 1-hour TTL',
|
||||
metered_events: 'billing telemetry',
|
||||
notice_dismissals: 'per-user UI notice dismissal state, not räkenskapsinformation',
|
||||
oauth_flows:
|
||||
'in-flight browser OAuth flow state (migration 20260907120000): state, origin, encrypted PKCE verifier and handoff; consumed by the callback, not räkenskapsinformation',
|
||||
notification_log: 'notification dedup log',
|
||||
operations: 'staged-operation workflow state',
|
||||
payment_match_log: 'derived matching log',
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
/**
|
||||
* Origins the Skatteverket OAuth popup may post back from.
|
||||
*
|
||||
* The OAuth callback is served from the host pinned by
|
||||
* NEXT_PUBLIC_SKV_OAUTH_BASE_URL: the redirect_uri registered with
|
||||
* Skatteverket in Utvecklarportalen, kept on the legacy app.gnubok.se
|
||||
* domain after the user-facing app moved to app.accounted.se. The panels
|
||||
* that open the popup therefore accept postMessage events from that origin
|
||||
* in addition to their own.
|
||||
* The provider redirects to the host pinned by NEXT_PUBLIC_SKV_OAUTH_BASE_URL
|
||||
* (the redirect_uri registered with Skatteverket in Utvecklarportalen, kept
|
||||
* on the legacy app.gnubok.se domain after the user-facing app moved to
|
||||
* app.accounted.se). Since the oauth_flows handoff (lib/auth/oauth-flows.ts)
|
||||
* that host only forwards the browser to the origin the flow started on,
|
||||
* and the success/error page posts from there: the opener's own origin.
|
||||
* The pinned host stays accepted for flows in flight across the deploy.
|
||||
*
|
||||
* Origin alone is never sufficient: callers must also verify that
|
||||
* event.source is the popup window they themselves opened.
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
-- One row per browser-driven OAuth flow that must finish on the origin it
|
||||
-- started from and for the user who started it.
|
||||
--
|
||||
-- The Skatteverket consent used to live as six per-company keys in
|
||||
-- extension_data (oauth_state, oauth_user_id, oauth_redirect_uri,
|
||||
-- oauth_code_verifier, oauth_connector_state, oauth_return_to). Per-company
|
||||
-- keys meant a second connect overwrote the first mid-flight, the callback
|
||||
-- scanned every company's state row to find its own, the state was deleted
|
||||
-- only after the token exchange (two deliveries could both find it), and
|
||||
-- nothing recorded which origin (app or white-label brand) the flow started
|
||||
-- on, so the callback always answered the canonical app origin.
|
||||
--
|
||||
-- This table is the single source of truth for such a flow. The row id is
|
||||
-- the OAuth `state` sent to the provider: an unguessable random token that
|
||||
-- encodes nothing. Consuming the state and consuming the handoff are each
|
||||
-- one UPDATE / DELETE whose WHERE clause carries the whole check
|
||||
-- (unconsumed, unexpired, and for the handoff the destination origin), so a
|
||||
-- replayed or concurrent callback loses the row-lock race with no
|
||||
-- read-then-write window.
|
||||
--
|
||||
-- Two-hop flow on hosted: the provider redirects to the registered callback
|
||||
-- host (app.gnubok.se), which carries no app session. Hop 1 consumes the
|
||||
-- state, encrypts the provider code (or error) into the handoff columns and
|
||||
-- 302s to the recorded origin with the separate handoff id. Hop 2 on that
|
||||
-- origin consumes the handoff (DELETE RETURNING, bound to the origin),
|
||||
-- verifies the completing browser's session is the initiating user, and
|
||||
-- exchanges the code. Self-hosted (callback host = app host) is one hop.
|
||||
--
|
||||
-- Service-role only: written by /authorize and consumed by /callback with the
|
||||
-- service client. No user-facing role may read a code verifier or a held
|
||||
-- provider code. Not räkenskapsinformation; classified as infrastructure in
|
||||
-- lib/reports/full-archive-export.ts. Rows cascade with the company and the
|
||||
-- user; expired rows are purged opportunistically by /authorize.
|
||||
|
||||
CREATE TABLE public.oauth_flows (
|
||||
id text PRIMARY KEY,
|
||||
kind text NOT NULL,
|
||||
company_id uuid NOT NULL REFERENCES public.companies(id) ON DELETE CASCADE,
|
||||
user_id uuid NOT NULL REFERENCES auth.users(id) ON DELETE CASCADE,
|
||||
origin text NOT NULL,
|
||||
redirect_uri text NOT NULL,
|
||||
code_verifier text,
|
||||
connector_state text,
|
||||
return_to text,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
expires_at timestamptz NOT NULL,
|
||||
used_at timestamptz,
|
||||
handoff_id text UNIQUE,
|
||||
handoff_code text,
|
||||
handoff_error text,
|
||||
handoff_expires_at timestamptz,
|
||||
CONSTRAINT oauth_flows_kind_check CHECK (kind IN ('skatteverket')),
|
||||
CONSTRAINT oauth_flows_handoff_shape CHECK (
|
||||
(handoff_id IS NULL AND handoff_code IS NULL AND handoff_error IS NULL AND handoff_expires_at IS NULL)
|
||||
OR (handoff_id IS NOT NULL AND handoff_expires_at IS NOT NULL AND used_at IS NOT NULL
|
||||
AND (handoff_code IS NOT NULL OR handoff_error IS NOT NULL))
|
||||
)
|
||||
);
|
||||
|
||||
COMMENT ON TABLE public.oauth_flows IS
|
||||
'One row per browser OAuth flow (state = id). Written by /authorize, consumed atomically by /callback. code_verifier, handoff_code and handoff_error are AES-256-GCM ciphertext (lib/auth/oauth-flow-crypto.ts). Service-role only.';
|
||||
COMMENT ON COLUMN public.oauth_flows.origin IS
|
||||
'Validated app or brand origin the flow started on; the callback finishes there and the handoff may only be consumed from there.';
|
||||
COMMENT ON COLUMN public.oauth_flows.handoff_id IS
|
||||
'Separate random token for hop 2; never the state, so the provider redirect URL alone cannot claim the handoff.';
|
||||
|
||||
CREATE INDEX idx_oauth_flows_expires_at ON public.oauth_flows (expires_at);
|
||||
|
||||
-- No policies on purpose: nothing but the service client touches this table.
|
||||
ALTER TABLE public.oauth_flows ENABLE ROW LEVEL SECURITY;
|
||||
REVOKE ALL ON TABLE public.oauth_flows FROM anon, authenticated;
|
||||
|
||||
NOTIFY pgrst, 'reload schema';
|
||||
@@ -0,0 +1,165 @@
|
||||
import { randomBytes } from 'node:crypto'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { getClient, getPool } from '@/tests/pg/setup'
|
||||
import { seedCompany } from '@/tests/pg/fixtures'
|
||||
|
||||
/**
|
||||
* Migration 20260907120000_oauth_flows.sql: the one-row-per-flow table behind
|
||||
* lib/auth/oauth-flows.ts. Locks in the three things the application relies
|
||||
* on and cannot prove with mocks:
|
||||
*
|
||||
* - the table is service-role only (RLS enabled, browser roles revoked);
|
||||
* - consuming the state and consuming the handoff are single statements
|
||||
* whose WHERE clause carries the whole check, so two concurrent
|
||||
* deliveries yield exactly one winner;
|
||||
* - the handoff can only be claimed from the origin it was minted for.
|
||||
*/
|
||||
|
||||
async function insertFlow(params: {
|
||||
companyId: string
|
||||
userId: string
|
||||
origin?: string
|
||||
expiresInSeconds?: number
|
||||
}): Promise<string> {
|
||||
const id = randomBytes(32).toString('base64url')
|
||||
await getPool().query(
|
||||
`INSERT INTO public.oauth_flows
|
||||
(id, kind, company_id, user_id, origin, redirect_uri, expires_at)
|
||||
VALUES ($1, 'skatteverket', $2, $3, $4, 'https://oauth.testbrand.example/cb',
|
||||
now() + make_interval(secs => $5))`,
|
||||
[id, params.companyId, params.userId, params.origin ?? 'https://app.testbrand.example', params.expiresInSeconds ?? 600],
|
||||
)
|
||||
return id
|
||||
}
|
||||
|
||||
// Mirrors consumeOAuthFlowState's PostgREST statement.
|
||||
const CONSUME_STATE = `
|
||||
UPDATE public.oauth_flows SET used_at = now()
|
||||
WHERE id = $1 AND kind = 'skatteverket' AND used_at IS NULL AND expires_at > now()
|
||||
RETURNING id`
|
||||
|
||||
// Mirrors consumeOAuthFlowHandoff's PostgREST statement.
|
||||
const CONSUME_HANDOFF = `
|
||||
DELETE FROM public.oauth_flows
|
||||
WHERE handoff_id = $1 AND origin = $2 AND kind = 'skatteverket'
|
||||
AND handoff_expires_at > now()
|
||||
RETURNING id, handoff_code`
|
||||
|
||||
async function mintHandoff(id: string, expiresInSeconds = 120): Promise<string> {
|
||||
const handoffId = randomBytes(32).toString('base64url')
|
||||
await getPool().query(
|
||||
`UPDATE public.oauth_flows
|
||||
SET handoff_id = $2, handoff_code = 'v1:ciphertext',
|
||||
handoff_expires_at = now() + make_interval(secs => $3)
|
||||
WHERE id = $1`,
|
||||
[id, handoffId, expiresInSeconds],
|
||||
)
|
||||
return handoffId
|
||||
}
|
||||
|
||||
describe('oauth_flows (pg)', () => {
|
||||
async function expectDenied(role: 'anon' | 'authenticated', sql: string) {
|
||||
const client = await getClient()
|
||||
try {
|
||||
await client.query('BEGIN')
|
||||
await client.query(`SET LOCAL ROLE ${role}`)
|
||||
await expect(client.query(sql)).rejects.toThrow(/permission denied/i)
|
||||
} finally {
|
||||
await client.query('ROLLBACK').catch(() => {})
|
||||
client.release()
|
||||
}
|
||||
}
|
||||
|
||||
it('denies the browser-facing roles entirely', async () => {
|
||||
await expectDenied('anon', 'SELECT * FROM public.oauth_flows LIMIT 1')
|
||||
await expectDenied('authenticated', 'SELECT * FROM public.oauth_flows LIMIT 1')
|
||||
await expectDenied(
|
||||
'authenticated',
|
||||
`INSERT INTO public.oauth_flows (id, kind, company_id, user_id, origin, redirect_uri, expires_at)
|
||||
VALUES ('x', 'skatteverket', gen_random_uuid(), gen_random_uuid(), 'https://a', 'https://b', now())`,
|
||||
)
|
||||
})
|
||||
|
||||
it('lets exactly one of two concurrent deliveries consume the state', async () => {
|
||||
const { companyId, userId } = await seedCompany()
|
||||
const id = await insertFlow({ companyId, userId })
|
||||
|
||||
const a = await getClient()
|
||||
const b = await getClient()
|
||||
try {
|
||||
const [ra, rb] = await Promise.all([
|
||||
a.query(CONSUME_STATE, [id]),
|
||||
b.query(CONSUME_STATE, [id]),
|
||||
])
|
||||
expect(ra.rowCount! + rb.rowCount!).toBe(1)
|
||||
} finally {
|
||||
a.release()
|
||||
b.release()
|
||||
}
|
||||
|
||||
// And nothing after that: the state is spent.
|
||||
const again = await getPool().query(CONSUME_STATE, [id])
|
||||
expect(again.rowCount).toBe(0)
|
||||
})
|
||||
|
||||
it('refuses an expired state', async () => {
|
||||
const { companyId, userId } = await seedCompany()
|
||||
const id = await insertFlow({ companyId, userId, expiresInSeconds: -1 })
|
||||
const res = await getPool().query(CONSUME_STATE, [id])
|
||||
expect(res.rowCount).toBe(0)
|
||||
})
|
||||
|
||||
it('claims the handoff once, and only from the recorded origin', async () => {
|
||||
const { companyId, userId } = await seedCompany()
|
||||
const id = await insertFlow({ companyId, userId, origin: 'https://brand.testbrand.example' })
|
||||
await getPool().query(CONSUME_STATE, [id])
|
||||
const handoffId = await mintHandoff(id)
|
||||
|
||||
// Wrong origin: nothing, and the row is still there for the right one.
|
||||
const wrong = await getPool().query(CONSUME_HANDOFF, [handoffId, 'https://app.testbrand.example'])
|
||||
expect(wrong.rowCount).toBe(0)
|
||||
|
||||
const a = await getClient()
|
||||
const b = await getClient()
|
||||
try {
|
||||
const [ra, rb] = await Promise.all([
|
||||
a.query(CONSUME_HANDOFF, [handoffId, 'https://brand.testbrand.example']),
|
||||
b.query(CONSUME_HANDOFF, [handoffId, 'https://brand.testbrand.example']),
|
||||
])
|
||||
expect(ra.rowCount! + rb.rowCount!).toBe(1)
|
||||
const winner = ra.rowCount === 1 ? ra : rb
|
||||
expect(winner.rows[0]!.handoff_code).toBe('v1:ciphertext')
|
||||
} finally {
|
||||
a.release()
|
||||
b.release()
|
||||
}
|
||||
|
||||
// DELETE RETURNING: the held code left the database with the claim.
|
||||
const gone = await getPool().query('SELECT 1 FROM public.oauth_flows WHERE id = $1', [id])
|
||||
expect(gone.rowCount).toBe(0)
|
||||
})
|
||||
|
||||
it('refuses an expired handoff', async () => {
|
||||
const { companyId, userId } = await seedCompany()
|
||||
const id = await insertFlow({ companyId, userId, origin: 'https://brand.testbrand.example' })
|
||||
await getPool().query(CONSUME_STATE, [id])
|
||||
const handoffId = await mintHandoff(id, -1)
|
||||
const res = await getPool().query(CONSUME_HANDOFF, [handoffId, 'https://brand.testbrand.example'])
|
||||
expect(res.rowCount).toBe(0)
|
||||
})
|
||||
|
||||
it('rejects a handoff written onto an unconsumed state', async () => {
|
||||
// The shape constraint: a handoff only exists for a state hop 1 consumed,
|
||||
// so a stray write can never make an unconsumed state claimable twice.
|
||||
const { companyId, userId } = await seedCompany()
|
||||
const id = await insertFlow({ companyId, userId })
|
||||
await expect(
|
||||
getPool().query(
|
||||
`UPDATE public.oauth_flows
|
||||
SET handoff_id = 'h', handoff_code = 'v1:x', handoff_expires_at = now() + interval '2 minutes'
|
||||
WHERE id = $1`,
|
||||
[id],
|
||||
),
|
||||
).rejects.toThrow(/oauth_flows_handoff_shape/)
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user