docs(production): standardiserad produktionsberedskap och gap-analys

Lägger docs/production-readiness.md och siax/production-gaps.json enligt SIAX Master Definition of Done. Underlag: git-, kod- och live-evidens 2026-11-11. Nivån är evidensbaserad, inte ett leveransgodkännande.
This commit is contained in:
2026-11-10 09:15:21 +01:00
parent 0fda8cae48
commit 2bee8eb778
6135 changed files with 4 additions and 1718997 deletions
-462
View File
@@ -1,462 +0,0 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
vi.mock('@supabase/supabase-js', () => ({
createClient: vi.fn(),
}))
const contextMocks = vi.hoisted(() => ({
getActiveCompanyId: vi.fn(),
}))
vi.mock('@/lib/company/active-company', () => ({
getActiveCompanyId: (...args: unknown[]) => contextMocks.getActiveCompanyId(...args),
}))
import {
generateApiKey,
hashApiKey,
extractBearerToken,
validateScopes,
hasScope,
validateApiKey,
findStageApproveConflict,
DEFAULT_SCOPES,
DEFAULT_OAUTH_SCOPES,
STAGING_SCOPES,
TOOL_SCOPE_MAP,
API_KEY_SCOPES,
} from '../api-keys'
import { createClient } from '@supabase/supabase-js'
const mockCreateClient = vi.mocked(createClient)
beforeEach(() => {
vi.clearAllMocks()
})
// ============================================================
// generateApiKey
// ============================================================
describe('generateApiKey', () => {
it('returns key starting with "gnubok_sk_"', () => {
const { key } = generateApiKey()
expect(key.startsWith('gnubok_sk_')).toBe(true)
})
it('returns 64-char hex SHA-256 hash', () => {
const { hash } = generateApiKey()
expect(hash).toMatch(/^[0-9a-f]{64}$/)
})
it('returns prefix of KEY_PREFIX + 8 chars', () => {
const { key, prefix } = generateApiKey()
expect(prefix).toBe(key.slice(0, 'gnubok_sk_'.length + 8))
})
it('generates unique keys on successive calls', () => {
const a = generateApiKey()
const b = generateApiKey()
expect(a.key).not.toBe(b.key)
expect(a.hash).not.toBe(b.hash)
})
it('hash matches hashApiKey(key)', () => {
const { key, hash } = generateApiKey()
expect(hashApiKey(key)).toBe(hash)
})
})
// ============================================================
// hashApiKey
// ============================================================
describe('hashApiKey', () => {
it('returns 64-char hex string', () => {
const hash = hashApiKey('gnubok_sk_test-key')
expect(hash).toMatch(/^[0-9a-f]{64}$/)
})
it('is deterministic for same input', () => {
const hash1 = hashApiKey('gnubok_sk_deterministic')
const hash2 = hashApiKey('gnubok_sk_deterministic')
expect(hash1).toBe(hash2)
})
it('produces different hashes for different inputs', () => {
const hash1 = hashApiKey('gnubok_sk_key-a')
const hash2 = hashApiKey('gnubok_sk_key-b')
expect(hash1).not.toBe(hash2)
})
})
// ============================================================
// extractBearerToken
// ============================================================
describe('extractBearerToken', () => {
it('extracts token from valid Bearer header', () => {
const request = new Request('http://localhost', {
headers: { authorization: 'Bearer my-secret-token' },
})
expect(extractBearerToken(request)).toBe('my-secret-token')
})
it('returns null when no authorization header', () => {
const request = new Request('http://localhost')
expect(extractBearerToken(request)).toBeNull()
})
it('returns null when header is not Bearer scheme', () => {
const request = new Request('http://localhost', {
headers: { authorization: 'Basic dXNlcjpwYXNz' },
})
expect(extractBearerToken(request)).toBeNull()
})
it('handles token with special characters', () => {
const request = new Request('http://localhost', {
headers: { authorization: 'Bearer gnubok_sk_abc+def/ghi=jkl' },
})
expect(extractBearerToken(request)).toBe('gnubok_sk_abc+def/ghi=jkl')
})
})
// ============================================================
// validateScopes
// ============================================================
describe('validateScopes', () => {
it('returns null for null input', () => {
expect(validateScopes(null)).toBeNull()
})
it('returns null for undefined input', () => {
expect(validateScopes(undefined)).toBeNull()
})
it('returns null for non-array input', () => {
expect(validateScopes('transactions:read')).toBeNull()
expect(validateScopes(42)).toBeNull()
expect(validateScopes({ scope: 'transactions:read' })).toBeNull()
})
it('filters to only valid API_KEY_SCOPES', () => {
const result = validateScopes(['transactions:read', 'invalid:scope', 'reports:read'])
expect(result).toEqual(['transactions:read', 'reports:read'])
})
it('returns null when no valid scopes remain after filter', () => {
expect(validateScopes(['invalid:scope', 'also:invalid'])).toBeNull()
})
it('preserves valid scopes from mixed input', () => {
const result = validateScopes(['customers:write', 'bogus', 'invoices:read'])
expect(result).toEqual(['customers:write', 'invoices:read'])
})
})
// ============================================================
// hasScope
// ============================================================
describe('hasScope', () => {
it('returns true when scope present in array', () => {
expect(hasScope(['transactions:read', 'reports:read'], 'transactions:read')).toBe(true)
})
it('returns false when scope absent', () => {
expect(hasScope(['transactions:read', 'reports:read'], 'invoices:write')).toBe(false)
})
})
// ============================================================
// findStageApproveConflict
// ============================================================
describe('findStageApproveConflict', () => {
it('returns null when approve scope is absent', () => {
expect(findStageApproveConflict(['invoices:write', 'reports:read'])).toBeNull()
})
it('returns null when approve scope present but no staging scope', () => {
expect(
findStageApproveConflict(['pending_operations:approve', 'reports:read']),
).toBeNull()
})
it('returns the offending staging scope when both are present', () => {
expect(
findStageApproveConflict(['invoices:write', 'pending_operations:approve']),
).toBe('invoices:write')
})
it('treats every STAGING_SCOPES member as a conflict alongside approve', () => {
for (const staging of STAGING_SCOPES) {
expect(findStageApproveConflict([staging, 'pending_operations:approve'])).toBe(staging)
}
})
it('does NOT treat agent:write as a staging scope', () => {
expect(STAGING_SCOPES).not.toContain('agent:write')
// agent:write + approve is not a SoD conflict: memory writes don't stage
// bookkeeping that approve would commit.
expect(
findStageApproveConflict(['agent:write', 'pending_operations:approve']),
).toBeNull()
})
})
// ============================================================
// agent:write scope wiring
// ============================================================
describe('agent:write scope', () => {
it('is a registered scope with a Swedish label and description', () => {
expect(API_KEY_SCOPES['agent:write']).toBeDefined()
expect(API_KEY_SCOPES['agent:write'].label).toBe('Agent: skriv')
expect(typeof API_KEY_SCOPES['agent:write'].description).toBe('string')
})
it('maps the memory write tools to agent:write', () => {
expect(TOOL_SCOPE_MAP.gnubok_remember_fact).toBe('agent:write')
expect(TOOL_SCOPE_MAP.gnubok_forget_fact).toBe('agent:write')
})
it('keeps gnubok_get_agent_briefing on agent:read', () => {
expect(TOOL_SCOPE_MAP.gnubok_get_agent_briefing).toBe('agent:read')
})
it('is excluded from the default scope grants', () => {
expect(DEFAULT_SCOPES).not.toContain('agent:write')
expect(DEFAULT_OAUTH_SCOPES).not.toContain('agent:write')
})
})
// ============================================================
// validateApiKey
// ============================================================
describe('validateApiKey', () => {
function setupMockRpc(response: { data: unknown; error: unknown }) {
const mockRpc = vi.fn().mockResolvedValue(response)
// eslint-disable-next-line @typescript-eslint/no-explicit-any
mockCreateClient.mockReturnValue({ rpc: mockRpc } as any)
}
it('rejects keys not starting with "gnubok_sk_"', async () => {
const result = await validateApiKey('invalid-key-format')
expect(result).toEqual({ error: 'Invalid API key format', status: 401 })
})
it('rejects a refresh token presented as Bearer with a specific message', async () => {
const result = await validateApiKey('gnubok_rt_some_refresh_token')
expect('status' in result && result.status).toBe(401)
expect('error' in result && result.error).toContain('Refresh token')
})
it('rejects when RPC returns error', async () => {
setupMockRpc({ data: null, error: { message: 'db error' } })
const result = await validateApiKey('gnubok_sk_test-key-value')
expect(result).toEqual({ error: 'Invalid API key', status: 401 })
})
it('rejects when RPC returns empty data array', async () => {
setupMockRpc({ data: [], error: null })
const result = await validateApiKey('gnubok_sk_test-key-value')
expect(result).toEqual({ error: 'Invalid API key', status: 401 })
})
it('returns rate limit error when rate_limited is true', async () => {
setupMockRpc({
data: [{ user_id: 'u1', company_id: 'c1', scopes: null, rate_limited: true }],
error: null,
})
const result = await validateApiKey('gnubok_sk_test-key-value')
expect(result).toEqual({ error: 'Rate limit exceeded', status: 429 })
})
it('returns userId, companyId, scopes on success', async () => {
setupMockRpc({
data: [{
user_id: 'user-123',
company_id: 'company-456',
scopes: ['transactions:read', 'reports:read'],
rate_limited: false,
}],
error: null,
})
const result = await validateApiKey('gnubok_sk_test-key-value')
expect(result).toEqual({
userId: 'user-123',
companyId: 'company-456',
apiKeyId: undefined,
apiKeyName: undefined,
scopes: ['transactions:read', 'reports:read'],
mode: 'live',
unattendedCommitLimit: null,
})
})
it('falls back to DEFAULT_SCOPES when row.scopes is null', async () => {
setupMockRpc({
data: [{
user_id: 'user-123',
company_id: 'company-456',
scopes: null,
rate_limited: false,
}],
error: null,
})
const result = await validateApiKey('gnubok_sk_test-key-value')
expect(result).toEqual({
userId: 'user-123',
companyId: 'company-456',
apiKeyId: undefined,
apiKeyName: undefined,
scopes: DEFAULT_SCOPES,
mode: 'live',
unattendedCommitLimit: null,
})
})
it('surfaces mode from the RPC row', async () => {
setupMockRpc({
data: [{
user_id: 'user-123',
company_id: 'company-456',
api_key_id: 'ak_1',
api_key_name: 'CI test key',
scopes: ['transactions:read'],
rate_limited: false,
mode: 'test',
}],
error: null,
})
const result = await validateApiKey('gnubok_sk_test-key-value')
expect(result).toEqual({
userId: 'user-123',
companyId: 'company-456',
apiKeyId: 'ak_1',
apiKeyName: 'CI test key',
scopes: ['transactions:read'],
mode: 'test',
unattendedCommitLimit: null,
})
})
describe('unattended commit limit', () => {
it('surfaces a positive ceiling from the RPC row', async () => {
setupMockRpc({
data: [{
user_id: 'user-123',
company_id: 'company-456',
scopes: ['transactions:read'],
rate_limited: false,
// numeric(14,2) comes back from PostgREST as a string.
unattended_commit_limit: '25000.00',
}],
error: null,
})
const result = await validateApiKey('gnubok_sk_test-key-value')
expect(result).toMatchObject({ unattendedCommitLimit: 25000 })
})
it('reads anything that is not a positive number as no ceiling', async () => {
// The whole guard is NULL-first: an unparseable or non-positive value
// must mean "unlimited", never "block every commit this key attempts".
for (const raw of [null, undefined, 0, -1, 'abc', {}]) {
setupMockRpc({
data: [{
user_id: 'user-123',
company_id: 'company-456',
scopes: ['transactions:read'],
rate_limited: false,
unattended_commit_limit: raw,
}],
error: null,
})
const result = await validateApiKey('gnubok_sk_test-key-value')
expect(result).toMatchObject({ unattendedCommitLimit: null })
}
})
})
describe('unbound keys (minted before the first company existed, issue #1814)', () => {
function setupUnboundKeyClient(rpcRow: Record<string, unknown>) {
const chain = {
update: vi.fn(),
eq: vi.fn(),
is: vi.fn().mockResolvedValue({ data: null, error: null }),
}
chain.update.mockReturnValue(chain)
chain.eq.mockReturnValue(chain)
const from = vi.fn().mockReturnValue(chain)
const rpc = vi.fn().mockResolvedValue({ data: [rpcRow], error: null })
// eslint-disable-next-line @typescript-eslint/no-explicit-any
mockCreateClient.mockReturnValue({ rpc, from } as any)
return { from, chain }
}
const unboundRow = {
user_id: 'user-123',
company_id: null,
api_key_id: 'ak_1',
api_key_name: 'MCP-klient (OAuth)',
scopes: ['transactions:read'],
rate_limited: false,
mode: 'live',
}
it('binds the key to the user\'s company once one exists and heals the row', async () => {
const { from, chain } = setupUnboundKeyClient(unboundRow)
contextMocks.getActiveCompanyId.mockResolvedValue('company-789')
const result = await validateApiKey('gnubok_sk_test-key-value')
expect('companyId' in result && result.companyId).toBe('company-789')
expect(from).toHaveBeenCalledWith('api_keys')
expect(chain.update).toHaveBeenCalledWith({ company_id: 'company-789' })
expect(chain.eq).toHaveBeenCalledWith('id', 'ak_1')
// Only an unbound row is ever rewritten: a concurrent bind must not be clobbered.
expect(chain.is).toHaveBeenCalledWith('company_id', null)
})
it('returns companyId null while the user still has no company', async () => {
const { from } = setupUnboundKeyClient(unboundRow)
contextMocks.getActiveCompanyId.mockResolvedValue(null)
const result = await validateApiKey('gnubok_sk_test-key-value')
expect('companyId' in result && result.companyId).toBeNull()
expect(from).not.toHaveBeenCalled()
})
it('treats a failed company resolution as still unbound rather than failing the key', async () => {
setupUnboundKeyClient(unboundRow)
contextMocks.getActiveCompanyId.mockRejectedValue(new Error('db blip'))
const result = await validateApiKey('gnubok_sk_test-key-value')
expect('companyId' in result && result.companyId).toBeNull()
expect('userId' in result && result.userId).toBe('user-123')
})
it('skips the heal when the RPC predates api_key_id in its return shape', async () => {
const { from } = setupUnboundKeyClient({ ...unboundRow, api_key_id: undefined })
contextMocks.getActiveCompanyId.mockResolvedValue('company-789')
const result = await validateApiKey('gnubok_sk_test-key-value')
expect('companyId' in result && result.companyId).toBe('company-789')
expect(from).not.toHaveBeenCalled()
})
})
})
-47
View File
@@ -1,47 +0,0 @@
import { describe, it, expect } from 'vitest'
import { apiPathSkipsMfaGate } from '@/lib/auth/api-mfa-gate'
describe('apiPathSkipsMfaGate', () => {
it('skips the gate only on Bearer-auth surfaces when an Authorization header is present', () => {
expect(apiPathSkipsMfaGate('/api/v1/companies/abc/invoices', true)).toBe(true)
expect(apiPathSkipsMfaGate('/api/extensions/ext/mcp-server/mcp', true)).toBe(true)
})
it('never lets an Authorization header disable the gate on cookie-authenticated routes', () => {
// A stolen-password AAL1 cookie session must not bypass MFA by attaching
// a garbage Authorization header the route ignores (Superagent P2, #878).
expect(apiPathSkipsMfaGate('/api/bookkeeping/journal-entries/123', true)).toBe(false)
expect(apiPathSkipsMfaGate('/api/reports/full-archive', true)).toBe(false)
expect(apiPathSkipsMfaGate('/api/salary/employees/1', true)).toBe(false)
// Non-MCP extension routes authenticate via cookies in the dispatcher.
expect(apiPathSkipsMfaGate('/api/extensions/ext/invoice-inbox/custom-domain', true)).toBe(false)
})
it('does not skip Bearer-auth surfaces without an Authorization header', () => {
expect(apiPathSkipsMfaGate('/api/v1/companies/abc/invoices', false)).toBe(false)
expect(apiPathSkipsMfaGate('/api/extensions/ext/mcp-server/mcp', false)).toBe(false)
})
it('skips the gate for the AAL1 escape-hatch and OAuth routes', () => {
expect(apiPathSkipsMfaGate('/api/account/password', false)).toBe(true)
expect(apiPathSkipsMfaGate('/api/account/set-password', false)).toBe(true)
expect(apiPathSkipsMfaGate('/api/company', false)).toBe(true)
expect(apiPathSkipsMfaGate('/api/company/members', false)).toBe(true)
expect(apiPathSkipsMfaGate('/api/mcp-oauth/authorize', false)).toBe(true)
expect(apiPathSkipsMfaGate('/api/mcp-oauth/token', false)).toBe(true)
})
it('gates cookie-authenticated calls to sensitive dashboard routes', () => {
expect(apiPathSkipsMfaGate('/api/bookkeeping/journal-entries/123', false)).toBe(false)
expect(apiPathSkipsMfaGate('/api/salary/employees/1', false)).toBe(false)
expect(apiPathSkipsMfaGate('/api/reports/full-archive', false)).toBe(false)
expect(apiPathSkipsMfaGate('/api/documents/1', false)).toBe(false)
})
it('does not let a lookalike prefix bypass the account/company allowlist', () => {
// "/api/accounts" (plural, a different resource) must NOT match the
// "/api/account/" escape hatch.
expect(apiPathSkipsMfaGate('/api/accounts', false)).toBe(false)
expect(apiPathSkipsMfaGate('/api/account', false)).toBe(false)
})
})
-131
View File
@@ -1,131 +0,0 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import {
isBankIdEnabled,
hashPersonalNumber,
encryptPersonalNumber,
decryptPersonalNumber,
encryptPersonalNumberForStorage,
decryptStoredPersonalNumber,
maskPersonalNumber,
} from '../bankid'
// Generate a valid 32-byte hex key for tests
const TEST_KEY = 'a'.repeat(64) // 32 bytes in hex
describe('bankid helpers', () => {
beforeEach(() => {
vi.stubEnv('BANKID_ENCRYPTION_KEY', TEST_KEY)
})
afterEach(() => {
vi.unstubAllEnvs()
})
describe('isBankIdEnabled', () => {
it('returns false when NEXT_PUBLIC_SELF_HOSTED is true', () => {
vi.stubEnv('NEXT_PUBLIC_SELF_HOSTED', 'true')
vi.stubEnv('NEXT_PUBLIC_BANKID_ENABLED', 'true')
expect(isBankIdEnabled()).toBe(false)
})
it('returns true when BANKID_ENABLED is true and not self-hosted', () => {
vi.stubEnv('NEXT_PUBLIC_SELF_HOSTED', 'false')
vi.stubEnv('NEXT_PUBLIC_BANKID_ENABLED', 'true')
expect(isBankIdEnabled()).toBe(true)
})
it('returns false when BANKID_ENABLED is not set', () => {
vi.stubEnv('NEXT_PUBLIC_SELF_HOSTED', 'false')
vi.stubEnv('NEXT_PUBLIC_BANKID_ENABLED', '')
expect(isBankIdEnabled()).toBe(false)
})
})
describe('hashPersonalNumber', () => {
it('returns a consistent SHA-256 hex hash', () => {
const hash1 = hashPersonalNumber('199001011234')
const hash2 = hashPersonalNumber('199001011234')
expect(hash1).toBe(hash2)
expect(hash1).toMatch(/^[a-f0-9]{64}$/)
})
it('returns different hashes for different numbers', () => {
const hash1 = hashPersonalNumber('199001011234')
const hash2 = hashPersonalNumber('199001015678')
expect(hash1).not.toBe(hash2)
})
})
describe('encrypt/decrypt round-trip', () => {
it('encrypts and decrypts a personnummer', () => {
const pnr = '199001011234'
const encrypted = encryptPersonalNumber(pnr)
expect(encrypted).toBeInstanceOf(Buffer)
// iv (12) + tag (16) + ciphertext (at least 1 byte)
expect(encrypted.length).toBeGreaterThan(28)
const decrypted = decryptPersonalNumber(encrypted)
expect(decrypted).toBe(pnr)
})
it('produces different ciphertext each time (random IV)', () => {
const pnr = '199001011234'
const enc1 = encryptPersonalNumber(pnr)
const enc2 = encryptPersonalNumber(pnr)
expect(enc1.equals(enc2)).toBe(false)
})
it('throws when BANKID_ENCRYPTION_KEY is missing', () => {
vi.stubEnv('BANKID_ENCRYPTION_KEY', '')
expect(() => encryptPersonalNumber('199001011234')).toThrow('BANKID_ENCRYPTION_KEY')
})
})
describe('storage codec', () => {
const pnr = '199001011234'
it('encodes for storage as a \\x-prefixed hex string and round-trips', () => {
const stored = encryptPersonalNumberForStorage(pnr)
expect(stored).toMatch(/^\\x[0-9a-f]+$/)
expect(decryptStoredPersonalNumber(stored)).toBe(pnr)
})
it('decrypts a raw Buffer', () => {
expect(decryptStoredPersonalNumber(encryptPersonalNumber(pnr))).toBe(pnr)
})
it('decrypts a legacy JSON-serialized Buffer read back as \\x-hex text', () => {
// supabase-js Buffer insert stored the JSON text of buf.toJSON();
// PostgREST returns that bytea as '\x' + hex of the UTF-8 JSON bytes.
const legacyText = JSON.stringify(encryptPersonalNumber(pnr).toJSON())
const readBack = '\\x' + Buffer.from(legacyText, 'utf8').toString('hex')
expect(decryptStoredPersonalNumber(readBack)).toBe(pnr)
})
it('decrypts a legacy JSON-serialized Buffer passed as plain text or object', () => {
const encrypted = encryptPersonalNumber(pnr)
expect(decryptStoredPersonalNumber(JSON.stringify(encrypted.toJSON()))).toBe(pnr)
expect(decryptStoredPersonalNumber(encrypted.toJSON())).toBe(pnr)
})
it('rejects tampered ciphertext (GCM auth)', () => {
const stored = encryptPersonalNumberForStorage(pnr)
const tampered = stored.slice(0, -2) + (stored.endsWith('00') ? '01' : '00')
expect(() => decryptStoredPersonalNumber(tampered)).toThrow()
})
})
describe('maskPersonalNumber', () => {
it('masks a 12-digit personnummer', () => {
expect(maskPersonalNumber('199001011234')).toBe('XXXXXXXX-1234')
})
it('masks a 10-digit personnummer', () => {
expect(maskPersonalNumber('9001011234')).toBe('XXXXXX-1234')
})
it('handles short input gracefully', () => {
expect(maskPersonalNumber('12')).toBe('****')
})
})
})
@@ -1,317 +0,0 @@
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: '[email protected]',
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: '[email protected]',
})
expect(result).toEqual({ allowed: true, brand: null, via: 'no_brand' })
})
it('allows with no host at all', async () => {
const result = await evaluateBrandSignupGate({ host: '', email: '[email protected]' })
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: '[email protected]',
})
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: ' [email protected] ',
})
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',
'[email protected]',
])
})
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: '[email protected]',
})
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: '[email protected]',
})
// 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: '[email protected]',
})
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: '[email protected]',
status: 'pending',
expires_at: new Date(Date.now() + 60_000).toISOString(),
},
},
])
const result = await evaluateBrandSignupGate({
host: 'app.testbrand.example',
email: '[email protected]',
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: '[email protected]',
status: 'pending',
expires_at: new Date(Date.now() + 60_000).toISOString(),
},
},
])
const result = await evaluateBrandSignupGate({
host: 'app.testbrand.example',
email: '[email protected]',
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: '[email protected]',
status: 'pending',
expires_at: new Date(Date.now() - 60_000).toISOString(),
},
},
])
const result = await evaluateBrandSignupGate({
host: 'app.testbrand.example',
email: '[email protected]',
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: '[email protected]',
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()
})
})
@@ -1,61 +0,0 @@
import { describe, it, expect } from 'vitest'
import { classifyAuthError } from '../classify-auth-error'
describe('classifyAuthError', () => {
it('maps GoTrue error codes', () => {
expect(classifyAuthError({ code: 'invalid_credentials', message: 'Invalid login credentials', status: 400 }))
.toBe('invalid_credentials')
expect(classifyAuthError({ code: 'email_not_confirmed', message: 'Email not confirmed', status: 400 }))
.toBe('email_not_confirmed')
expect(classifyAuthError({ code: 'over_request_rate_limit', message: 'Request rate limit reached', status: 429 }))
.toBe('rate_limited')
expect(classifyAuthError({ code: 'over_email_send_rate_limit', message: '...', status: 429 }))
.toBe('rate_limited')
expect(classifyAuthError({ code: 'user_banned', message: 'User is banned', status: 403 }))
.toBe('user_banned')
expect(classifyAuthError({ code: 'user_already_exists', message: 'User already registered', status: 422 }))
.toBe('email_exists')
expect(classifyAuthError({ code: 'weak_password', message: 'Password is too weak', status: 422 }))
.toBe('weak_password')
expect(classifyAuthError({ code: 'email_address_invalid', message: 'Email address is invalid', status: 400 }))
.toBe('email_invalid')
expect(classifyAuthError({ code: 'signup_disabled', message: 'Signups not allowed', status: 400 }))
.toBe('signup_disabled')
expect(classifyAuthError({ code: 'email_provider_disabled', message: 'Email signups are disabled', status: 400 }))
.toBe('signup_disabled')
})
it('falls back on message strings when code is missing (older self-hosted GoTrue)', () => {
expect(classifyAuthError({ message: 'Invalid login credentials', status: 400 }))
.toBe('invalid_credentials')
expect(classifyAuthError({ message: 'Email not confirmed', status: 400 }))
.toBe('email_not_confirmed')
expect(classifyAuthError({ message: 'User already registered', status: 422 }))
.toBe('email_exists')
expect(classifyAuthError({ message: 'Signups not allowed for this instance', status: 400 }))
.toBe('signup_disabled')
expect(classifyAuthError({ message: 'Email signups are disabled', status: 400 }))
.toBe('signup_disabled')
expect(classifyAuthError({ message: 'Email rate limit exceeded', status: 429 }))
.toBe('rate_limited')
})
it('falls back on HTTP 429 when neither code nor message identifies the error', () => {
expect(classifyAuthError({ message: 'something opaque', status: 429 })).toBe('rate_limited')
})
it('returns unknown for unrecognized or malformed input', () => {
expect(classifyAuthError({ code: 'mfa_totp_verify_not_enabled', message: 'x', status: 400 })).toBe('unknown')
expect(classifyAuthError({ message: 'fetch failed' })).toBe('unknown')
expect(classifyAuthError(new Error('network down'))).toBe('unknown')
expect(classifyAuthError('a string')).toBe('unknown')
expect(classifyAuthError(null)).toBe('unknown')
expect(classifyAuthError(undefined)).toBe('unknown')
})
it('never leaks which credential part failed: unknown email and wrong password share a kind', () => {
const unknownEmail = { code: 'invalid_credentials', message: 'Invalid login credentials', status: 400 }
const wrongPassword = { code: 'invalid_credentials', message: 'Invalid login credentials', status: 400 }
expect(classifyAuthError(unknownEmail)).toBe(classifyAuthError(wrongPassword))
})
})
@@ -1,316 +0,0 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
import {
consumeInviteCookie,
classifyInviteAcceptStatus,
isDefinitiveInviteDisposition,
readInviteCookie,
INVITE_COOKIE_NAME,
INVITE_PROBLEM_MESSAGE_KEYS,
} from '../consume-invite-cookie'
/**
* Minimal document.cookie stand-in. Vitest runs in the node env, so there is
* no DOM: this models the one behaviour the helper depends on, namely that
* assigning `name=; max-age=0` removes the entry.
*/
function installCookieJar(initial: Record<string, string> = {}) {
const jar = new Map(Object.entries(initial))
Object.defineProperty(globalThis, 'document', {
configurable: true,
value: {
get cookie() {
return [...jar.entries()].map(([k, v]) => `${k}=${v}`).join('; ')
},
set cookie(raw: string) {
const [pair, ...attrs] = raw.split(';').map((s) => s.trim())
const eq = pair.indexOf('=')
const name = pair.slice(0, eq)
const value = pair.slice(eq + 1)
const expiring = attrs.some((a) => /^max-age=0$/i.test(a))
if (expiring || value === '') {
jar.delete(name)
} else {
jar.set(name, value)
}
},
},
})
return jar
}
const TOKEN = 'gnubok_inv_Zm9vYmFyLXRva2Vu'
let fetchMock: ReturnType<typeof vi.fn>
beforeEach(() => {
vi.clearAllMocks()
fetchMock = vi.fn()
vi.stubGlobal('fetch', fetchMock)
vi.spyOn(console, 'error').mockImplementation(() => {})
})
afterEach(() => {
vi.unstubAllGlobals()
Reflect.deleteProperty(globalThis, 'document')
vi.restoreAllMocks()
})
function respondWith(status: number) {
fetchMock.mockResolvedValue({ status, ok: status >= 200 && status < 300 })
}
describe('classifyInviteAcceptStatus', () => {
it('treats 2xx and 409 (already a member) as accepted', () => {
expect(classifyInviteAcceptStatus(200)).toBe('accepted')
expect(classifyInviteAcceptStatus(204)).toBe('accepted')
expect(classifyInviteAcceptStatus(409)).toBe('accepted')
})
it('treats 400, 404 and 410 as a spent or invalid token', () => {
expect(classifyInviteAcceptStatus(400)).toBe('spent')
expect(classifyInviteAcceptStatus(404)).toBe('spent')
expect(classifyInviteAcceptStatus(410)).toBe('spent')
})
it('treats 403 email mismatch as its own case, not spent', () => {
expect(classifyInviteAcceptStatus(403)).toBe('wrong_email')
expect(isDefinitiveInviteDisposition('wrong_email')).toBe(false)
})
it('treats session races, rate limits and server errors as retryable', () => {
for (const status of [401, 408, 425, 429, 500, 502, 503, 504]) {
expect(classifyInviteAcceptStatus(status)).toBe('retryable')
expect(isDefinitiveInviteDisposition('retryable')).toBe(false)
}
})
it('marks only accepted and spent as definitive', () => {
expect(isDefinitiveInviteDisposition('accepted')).toBe(true)
expect(isDefinitiveInviteDisposition('spent')).toBe(true)
})
})
describe('readInviteCookie', () => {
it('reads the token out of the cookie jar', () => {
installCookieJar({ 'sb-access-token': 'x', [INVITE_COOKIE_NAME]: TOKEN })
expect(readInviteCookie()).toBe(TOKEN)
})
it('returns null when no invite cookie is present', () => {
installCookieJar({ 'sb-access-token': 'x' })
expect(readInviteCookie()).toBeNull()
})
it('does not match a differently-named cookie sharing the suffix', () => {
installCookieJar({ [`x-${INVITE_COOKIE_NAME}`]: 'not-the-invite' })
expect(readInviteCookie()).toBeNull()
})
it('returns null without a DOM (server render)', () => {
expect(readInviteCookie()).toBeNull()
})
})
describe('consumeInviteCookie', () => {
it('does nothing when there is no invite cookie', async () => {
installCookieJar({})
const result = await consumeInviteCookie()
expect(result).toEqual({
attempted: false,
disposition: null,
accepted: false,
cleared: false,
problem: null,
})
expect(fetchMock).not.toHaveBeenCalled()
})
it('happy path: posts the token, clears the cookie, reports accepted', async () => {
const jar = installCookieJar({ [INVITE_COOKIE_NAME]: TOKEN })
respondWith(200)
const result = await consumeInviteCookie()
expect(fetchMock).toHaveBeenCalledWith('/api/team/accept', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ token: TOKEN }),
})
expect(result.accepted).toBe(true)
expect(result.problem).toBeNull()
expect(result.cleared).toBe(true)
expect(jar.has(INVITE_COOKIE_NAME)).toBe(false)
})
it('already a member (409) counts as accepted and clears', async () => {
const jar = installCookieJar({ [INVITE_COOKIE_NAME]: TOKEN })
respondWith(409)
const result = await consumeInviteCookie()
expect(result.accepted).toBe(true)
expect(jar.has(INVITE_COOKIE_NAME)).toBe(false)
})
it('definitively invalid (400) clears the cookie and reports the problem', async () => {
const jar = installCookieJar({ [INVITE_COOKIE_NAME]: TOKEN })
respondWith(400)
const result = await consumeInviteCookie()
expect(result.accepted).toBe(false)
expect(result.disposition).toBe('spent')
expect(result.problem).toBe('spent')
expect(result.cleared).toBe(true)
expect(jar.has(INVITE_COOKIE_NAME)).toBe(false)
})
it('expired invitation (410) clears the cookie', async () => {
const jar = installCookieJar({ [INVITE_COOKIE_NAME]: TOKEN })
respondWith(410)
const result = await consumeInviteCookie()
expect(result.problem).toBe('spent')
expect(jar.has(INVITE_COOKIE_NAME)).toBe(false)
})
// The finding: a transient failure used to destroy the token.
it('transient 500 RETAINS the token and reports it', async () => {
const jar = installCookieJar({ [INVITE_COOKIE_NAME]: TOKEN })
respondWith(500)
const result = await consumeInviteCookie()
expect(result.accepted).toBe(false)
expect(result.disposition).toBe('retryable')
expect(result.problem).toBe('retryable')
expect(result.cleared).toBe(false)
expect(jar.get(INVITE_COOKIE_NAME)).toBe(TOKEN)
})
it('session not yet propagated (401) RETAINS the token', async () => {
const jar = installCookieJar({ [INVITE_COOKIE_NAME]: TOKEN })
respondWith(401)
const result = await consumeInviteCookie()
expect(result.problem).toBe('retryable')
expect(result.cleared).toBe(false)
expect(jar.get(INVITE_COOKIE_NAME)).toBe(TOKEN)
})
it('network throw RETAINS the token and reports it', async () => {
const jar = installCookieJar({ [INVITE_COOKIE_NAME]: TOKEN })
fetchMock.mockRejectedValue(new TypeError('Failed to fetch'))
const result = await consumeInviteCookie()
expect(result.accepted).toBe(false)
expect(result.disposition).toBe('retryable')
expect(result.problem).toBe('retryable')
expect(result.cleared).toBe(false)
expect(jar.get(INVITE_COOKIE_NAME)).toBe(TOKEN)
})
it('email mismatch (403) RETAINS the token so the right account can still use it', async () => {
const jar = installCookieJar({ [INVITE_COOKIE_NAME]: TOKEN })
respondWith(403)
const result = await consumeInviteCookie()
expect(result.accepted).toBe(false)
expect(result.disposition).toBe('wrong_email')
expect(result.problem).toBe('wrong_email')
expect(result.cleared).toBe(false)
expect(jar.get(INVITE_COOKIE_NAME)).toBe(TOKEN)
})
it('accepts an out-of-band token without reading the cookie', async () => {
installCookieJar({})
respondWith(200)
const result = await consumeInviteCookie({ token: 'gnubok_inv_from-the-url' })
expect(result.accepted).toBe(true)
expect(fetchMock).toHaveBeenCalledWith(
'/api/team/accept',
expect.objectContaining({ body: JSON.stringify({ token: 'gnubok_inv_from-the-url' }) }),
)
})
it('every problem disposition has a message key pair', async () => {
for (const problem of ['retryable', 'wrong_email', 'spent'] as const) {
expect(INVITE_PROBLEM_MESSAGE_KEYS[problem].title).toBeTruthy()
expect(INVITE_PROBLEM_MESSAGE_KEYS[problem].body).toBeTruthy()
}
})
})
/**
* Control: the pre-fix logic, copied verbatim from what login/register/mfa
* used to inline. It clears the cookie on the `!res.ok` fall-through and on
* the throw, and never tells the user anything. Running the retention
* expectations against it proves the tests above are actually load-bearing
* and not passing by construction.
*/
async function legacyInviteHandling(): Promise<{ accepted: boolean; problem: string | null }> {
const cookieMatch = document.cookie.match(/gnubok-invite-token=([^;]+)/)
const inviteToken = cookieMatch?.[1]
if (inviteToken) {
try {
const res = await fetch('/api/team/accept', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ token: inviteToken }),
})
if (res.ok) {
document.cookie = 'gnubok-invite-token=; path=/; max-age=0'
return { accepted: true, problem: null }
}
} catch {
// swallowed
}
// Clear cookie even on failure to avoid retrying stale tokens
document.cookie = 'gnubok-invite-token=; path=/; max-age=0'
}
return { accepted: false, problem: null }
}
describe('regression control: the old unconditional-clear logic', () => {
it('fails the transient-500 retention expectation', async () => {
const jar = installCookieJar({ [INVITE_COOKIE_NAME]: TOKEN })
respondWith(500)
const legacy = await legacyInviteHandling()
// What the new tests assert, and what the old code does not do:
expect(jar.get(INVITE_COOKIE_NAME)).toBeUndefined() // token destroyed
expect(legacy.problem).toBeNull() // user told nothing
})
it('fails the network-throw retention expectation', async () => {
const jar = installCookieJar({ [INVITE_COOKIE_NAME]: TOKEN })
fetchMock.mockRejectedValue(new TypeError('Failed to fetch'))
await legacyInviteHandling()
expect(jar.get(INVITE_COOKIE_NAME)).toBeUndefined() // token destroyed
})
it('fails the 403 email-mismatch retention expectation', async () => {
const jar = installCookieJar({ [INVITE_COOKIE_NAME]: TOKEN })
respondWith(403)
await legacyInviteHandling()
expect(jar.get(INVITE_COOKIE_NAME)).toBeUndefined() // token destroyed
})
})
-64
View File
@@ -1,64 +0,0 @@
import { describe, it, expect, beforeEach, vi } from 'vitest'
import { verifyCronSecret } from '../cron'
describe('verifyCronSecret', () => {
beforeEach(() => {
vi.unstubAllEnvs()
})
it('returns 401 when CRON_SECRET is not set', () => {
vi.stubEnv('CRON_SECRET', '')
const request = new Request('http://localhost/api/cron', {
headers: { authorization: 'Bearer test-secret' },
})
const result = verifyCronSecret(request)
expect(result).not.toBeNull()
expect(result!.status).toBe(401)
})
it('returns 401 when no authorization header is provided', () => {
vi.stubEnv('CRON_SECRET', 'test-secret')
const request = new Request('http://localhost/api/cron')
const result = verifyCronSecret(request)
expect(result).not.toBeNull()
expect(result!.status).toBe(401)
})
it('returns 401 when token does not match', () => {
vi.stubEnv('CRON_SECRET', 'correct-secret')
const request = new Request('http://localhost/api/cron', {
headers: { authorization: 'Bearer wrong-secret' },
})
const result = verifyCronSecret(request)
expect(result).not.toBeNull()
expect(result!.status).toBe(401)
})
it('returns null (authorized) when Bearer token matches', () => {
vi.stubEnv('CRON_SECRET', 'correct-secret')
const request = new Request('http://localhost/api/cron', {
headers: { authorization: 'Bearer correct-secret' },
})
const result = verifyCronSecret(request)
expect(result).toBeNull()
})
it('returns null (authorized) when bare token matches', () => {
vi.stubEnv('CRON_SECRET', 'correct-secret')
const request = new Request('http://localhost/api/cron', {
headers: { authorization: 'correct-secret' },
})
const result = verifyCronSecret(request)
expect(result).toBeNull()
})
it('handles tokens of different lengths safely', () => {
vi.stubEnv('CRON_SECRET', 'short')
const request = new Request('http://localhost/api/cron', {
headers: { authorization: 'Bearer a-much-longer-token-that-differs-in-length' },
})
const result = verifyCronSecret(request)
expect(result).not.toBeNull()
expect(result!.status).toBe(401)
})
})
@@ -1,176 +0,0 @@
import { describe, expect, it } from 'vitest'
import { getClient, getPool } from '@/tests/pg/setup'
import { insertAuthUser } from '@/tests/pg/fixtures'
// claim_email_change_request / release_email_change_request
// (20260903083000_email_change_request_claims.sql): the cross-instance gate
// in front of GoTrue's updateUser in POST /api/account/email. Exactly one
// caller per user, address and window may proceed; the rest must answer
// "already pending" without re-issuing confirmation tokens.
//
// withUserContext rolls its transaction back, which would hide the claim
// from the next call. These helpers commit instead, because the claim's
// whole point is what a SECOND transaction sees; the test users are fresh
// per test and their rows cascade away with them.
const WINDOW = 30 * 60
async function asUser<T>(
userId: string,
fn: (client: import('pg').PoolClient) => Promise<T>,
): Promise<T> {
const client = await getClient()
try {
await client.query('BEGIN')
await client.query(`SELECT set_config('request.jwt.claims', $1, true)`, [
JSON.stringify({ sub: userId, role: 'authenticated' }),
])
await client.query(`SELECT set_config('request.jwt.claim.sub', $1, true)`, [userId])
await client.query(`SET LOCAL ROLE authenticated`)
const result = await fn(client)
await client.query('COMMIT')
return result
} catch (err) {
await client.query('ROLLBACK').catch(() => {})
throw err
} finally {
client.release()
}
}
async function claim(userId: string, email: string, window = WINDOW): Promise<boolean> {
return asUser(userId, async (client) => {
const { rows } = await client.query<{ claim_email_change_request: boolean }>(
`SELECT public.claim_email_change_request($1, $2)`,
[email, window],
)
return rows[0]!.claim_email_change_request
})
}
async function release(userId: string): Promise<void> {
await asUser(userId, async (client) => {
await client.query(`SELECT public.release_email_change_request()`)
})
}
async function backdateClaim(userId: string, seconds: number): Promise<void> {
await getPool().query(
`UPDATE public.email_change_requests
SET claimed_at = now() - make_interval(secs => $2)
WHERE user_id = $1`,
[userId, seconds],
)
}
describe('claim_email_change_request', () => {
it('grants the first claim and refuses a repeat for the same address inside the window', async () => {
const userId = await insertAuthUser()
expect(await claim(userId, '[email protected]')).toBe(true)
expect(await claim(userId, '[email protected]')).toBe(false)
// Case and whitespace are not a different address.
expect(await claim(userId, ' [email protected] ')).toBe(false)
})
it('grants a claim for a different address while one is held', async () => {
const userId = await insertAuthUser()
expect(await claim(userId, '[email protected]')).toBe(true)
expect(await claim(userId, '[email protected]')).toBe(true)
// ... and the first address is now the "different" one again.
expect(await claim(userId, '[email protected]')).toBe(true)
})
it('grants a repeat once the held claim is older than the window', async () => {
const userId = await insertAuthUser()
expect(await claim(userId, '[email protected]')).toBe(true)
await backdateClaim(userId, WINDOW + 5)
expect(await claim(userId, '[email protected]')).toBe(true)
expect(await claim(userId, '[email protected]')).toBe(false)
})
it('lets exactly one of three concurrent claimers through', async () => {
const userId = await insertAuthUser()
const results = await Promise.all([
claim(userId, '[email protected]'),
claim(userId, '[email protected]'),
claim(userId, '[email protected]'),
])
expect(results.filter(Boolean)).toHaveLength(1)
})
it('keeps claims per user', async () => {
const a = await insertAuthUser()
const b = await insertAuthUser()
expect(await claim(a, '[email protected]')).toBe(true)
expect(await claim(b, '[email protected]')).toBe(true)
})
it('release drops the claim so the same address can be requested again', async () => {
const userId = await insertAuthUser()
expect(await claim(userId, '[email protected]')).toBe(true)
await release(userId)
expect(await claim(userId, '[email protected]')).toBe(true)
})
it('release only touches the caller', async () => {
const a = await insertAuthUser()
const b = await insertAuthUser()
expect(await claim(a, '[email protected]')).toBe(true)
expect(await claim(b, '[email protected]')).toBe(true)
await release(a)
expect(await claim(b, '[email protected]')).toBe(false)
})
it('rejects an empty address and a non-positive window', async () => {
const userId = await insertAuthUser()
await expect(claim(userId, ' ')).rejects.toThrow(/requires an address/)
await expect(claim(userId, '[email protected]', 0)).rejects.toThrow(
/positive window/,
)
})
it('refuses unauthenticated callers', async () => {
await expect(
getPool().query(`SELECT public.claim_email_change_request('[email protected]', 60)`),
).rejects.toThrow(/authenticated user/)
await expect(
getPool().query(`SELECT public.release_email_change_request()`),
).rejects.toThrow(/authenticated user/)
})
it('is not readable or writable directly by an authenticated user', async () => {
const userId = await insertAuthUser()
expect(await claim(userId, '[email protected]')).toBe(true)
const visible = await asUser(userId, async (client) => {
const { rows } = await client.query(`SELECT * FROM public.email_change_requests`)
return rows.length
})
expect(visible).toBe(0)
await expect(
asUser(userId, async (client) => {
await client.query(`DELETE FROM public.email_change_requests`)
const { rows } = await client.query(
`SELECT count(*)::int AS n FROM public.email_change_requests`,
)
return rows[0]
}),
).resolves.toBeDefined()
// RLS with no policies: the DELETE above matched nothing.
const { rows } = await getPool().query<{ n: number }>(
`SELECT count(*)::int AS n FROM public.email_change_requests WHERE user_id = $1`,
[userId],
)
expect(rows[0]!.n).toBe(1)
})
})
-267
View File
@@ -1,267 +0,0 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { fetchAuthSettings, type GoTrueSettingsResponse } from '@/lib/auth/gotrue-providers'
import { createServiceClientNoCookies } from '@/lib/auth/api-keys'
vi.mock('@/lib/auth/api-keys', () => ({
createServiceClientNoCookies: vi.fn(),
}))
const mockListProviders = vi.fn()
vi.mocked(createServiceClientNoCookies).mockReturnValue({
auth: {
admin: {
customProviders: {
listProviders: mockListProviders,
},
},
},
} as never)
function fakeSettings(overrides: Partial<GoTrueSettingsResponse> = {}): GoTrueSettingsResponse {
return {
external: {},
disable_signup: false,
mailer_autoconfirm: true,
phone_autoconfirm: true,
sms_provider: 'twilio',
saml_enabled: false,
passkeys_enabled: false,
...overrides,
}
}
function mockFetch(body: GoTrueSettingsResponse, status = 200) {
return vi.spyOn(global, 'fetch').mockResolvedValueOnce(
new Response(JSON.stringify(body), { status }),
)
}
describe('fetchAuthSettings', () => {
const savedUrl = process.env.NEXT_PUBLIC_SUPABASE_URL
const savedKey = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY
const savedServiceKey = process.env.SUPABASE_SERVICE_ROLE_KEY
afterEach(() => {
vi.restoreAllMocks()
if (savedUrl !== undefined) process.env.NEXT_PUBLIC_SUPABASE_URL = savedUrl
else delete process.env.NEXT_PUBLIC_SUPABASE_URL
if (savedKey !== undefined) process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY = savedKey
else delete process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY
if (savedServiceKey !== undefined) process.env.SUPABASE_SERVICE_ROLE_KEY = savedServiceKey
else delete process.env.SUPABASE_SERVICE_ROLE_KEY
mockListProviders.mockReset()
})
it('returns empty providers and defaults when env vars are missing', async () => {
delete process.env.NEXT_PUBLIC_SUPABASE_URL
delete process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY
const spy = vi.spyOn(global, 'fetch')
const result = await fetchAuthSettings()
expect(result).toEqual({
providers: [],
passwordLoginEnabled: true,
registrationEnabled: true,
samlEnabled: false,
})
expect(spy).not.toHaveBeenCalled()
})
it('returns safe defaults on non-200 response', async () => {
process.env.NEXT_PUBLIC_SUPABASE_URL = 'https://project.supabase.co'
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY = 'anon-key-123'
mockFetch(fakeSettings(), 500)
const result = await fetchAuthSettings()
expect(result).toEqual({
providers: [],
passwordLoginEnabled: true,
registrationEnabled: true,
samlEnabled: false,
})
})
it('returns safe defaults on fetch error', async () => {
process.env.NEXT_PUBLIC_SUPABASE_URL = 'https://project.supabase.co'
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY = 'anon-key-123'
vi.spyOn(global, 'fetch').mockRejectedValueOnce(new Error('network'))
const result = await fetchAuthSettings()
expect(result).toEqual({
providers: [],
passwordLoginEnabled: true,
registrationEnabled: true,
samlEnabled: false,
})
})
it('calls GoTrue settings endpoint with apikey header', async () => {
process.env.NEXT_PUBLIC_SUPABASE_URL = 'https://project.supabase.co'
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY = 'anon-key-123'
const spy = mockFetch(fakeSettings())
await fetchAuthSettings()
expect(spy).toHaveBeenCalledWith(
'https://project.supabase.co/auth/v1/settings',
expect.objectContaining({
headers: { apikey: 'anon-key-123' },
}),
)
})
it('returns passwordLoginEnabled=true when email is enabled', async () => {
process.env.NEXT_PUBLIC_SUPABASE_URL = 'https://project.supabase.co'
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY = 'anon-key-123'
mockFetch(fakeSettings({ external: { email: true } }))
const result = await fetchAuthSettings()
expect(result.passwordLoginEnabled).toBe(true)
})
it('returns passwordLoginEnabled=false when email is disabled', async () => {
process.env.NEXT_PUBLIC_SUPABASE_URL = 'https://project.supabase.co'
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY = 'anon-key-123'
mockFetch(fakeSettings({ external: { email: false } }))
const result = await fetchAuthSettings()
expect(result.passwordLoginEnabled).toBe(false)
})
it('returns registrationEnabled=true when disable_signup is false', async () => {
process.env.NEXT_PUBLIC_SUPABASE_URL = 'https://project.supabase.co'
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY = 'anon-key-123'
mockFetch(fakeSettings({ disable_signup: false }))
const result = await fetchAuthSettings()
expect(result.registrationEnabled).toBe(true)
})
it('returns registrationEnabled=false when disable_signup is true', async () => {
process.env.NEXT_PUBLIC_SUPABASE_URL = 'https://project.supabase.co'
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY = 'anon-key-123'
mockFetch(fakeSettings({ disable_signup: true }))
const result = await fetchAuthSettings()
expect(result.registrationEnabled).toBe(false)
})
it('resolves known providers with brand labels', async () => {
process.env.NEXT_PUBLIC_SUPABASE_URL = 'https://project.supabase.co'
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY = 'anon-key-123'
mockFetch(fakeSettings({ external: { google: true, github: true, email: true } }))
const result = await fetchAuthSettings()
expect(result.providers).toEqual([
{ id: 'google', label: 'Google', isCustom: false },
{ id: 'github', label: 'GitHub', isCustom: false },
])
})
it('excludes unknown external providers not in the allowlist', async () => {
process.env.NEXT_PUBLIC_SUPABASE_URL = 'https://project.supabase.co'
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY = 'anon-key-123'
mockFetch(fakeSettings({ external: { 'my-oidc': true } }))
const result = await fetchAuthSettings()
expect(result.providers).toEqual([])
})
it('excludes disabled providers', async () => {
process.env.NEXT_PUBLIC_SUPABASE_URL = 'https://project.supabase.co'
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY = 'anon-key-123'
mockFetch(fakeSettings({ external: { google: false, github: true } }))
const result = await fetchAuthSettings()
expect(result.providers).toEqual([
{ id: 'github', label: 'GitHub', isCustom: false },
])
})
it('excludes the email provider from the provider list', async () => {
process.env.NEXT_PUBLIC_SUPABASE_URL = 'https://project.supabase.co'
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY = 'anon-key-123'
mockFetch(fakeSettings({ external: { email: true, google: true } }))
const result = await fetchAuthSettings()
expect(result.providers).toHaveLength(1)
expect(result.providers[0].id).toBe('google')
})
it('excludes the phone provider from the provider list', async () => {
process.env.NEXT_PUBLIC_SUPABASE_URL = 'https://project.supabase.co'
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY = 'anon-key-123'
mockFetch(fakeSettings({ external: { phone: true, google: true } }))
const result = await fetchAuthSettings()
expect(result.providers).toHaveLength(1)
expect(result.providers[0].id).toBe('google')
})
it('excludes non-provider entries like anonymous_users', async () => {
process.env.NEXT_PUBLIC_SUPABASE_URL = 'https://project.supabase.co'
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY = 'anon-key-123'
mockFetch(fakeSettings({ external: { anonymous_users: true, google: true, email: true } }))
const result = await fetchAuthSettings()
expect(result.providers).toHaveLength(1)
expect(result.providers[0].id).toBe('google')
})
it('returns empty providers when no external providers are enabled', async () => {
process.env.NEXT_PUBLIC_SUPABASE_URL = 'https://project.supabase.co'
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY = 'anon-key-123'
mockFetch(fakeSettings({ external: { email: true } }))
const result = await fetchAuthSettings()
expect(result.providers).toEqual([])
})
it('merges custom providers from the admin endpoint', async () => {
process.env.NEXT_PUBLIC_SUPABASE_URL = 'https://project.supabase.co'
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY = 'anon-key-123'
process.env.SUPABASE_SERVICE_ROLE_KEY = 'service-role-key'
mockFetch(fakeSettings({ external: { google: true } }))
mockListProviders.mockResolvedValue({
data: {
providers: [
{ identifier: 'custom:mycompany', name: 'My Company SSO', enabled: true },
{ identifier: 'custom:other', name: 'Other', enabled: false },
],
},
error: null,
})
const result = await fetchAuthSettings()
expect(result.providers).toEqual([
{ id: 'google', label: 'Google', isCustom: false },
{ id: 'custom:mycompany', label: 'My Company SSO', isCustom: true },
])
})
it('falls back to built-in providers when custom endpoint throws', async () => {
process.env.NEXT_PUBLIC_SUPABASE_URL = 'https://project.supabase.co'
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY = 'anon-key-123'
process.env.SUPABASE_SERVICE_ROLE_KEY = 'service-role-key'
mockFetch(fakeSettings({ external: { github: true } }))
mockListProviders.mockRejectedValue(new Error('network'))
const result = await fetchAuthSettings()
expect(result.providers).toEqual([{ id: 'github', label: 'GitHub', isCustom: false }])
})
it('skips custom providers when service_role key is missing', async () => {
process.env.NEXT_PUBLIC_SUPABASE_URL = 'https://project.supabase.co'
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY = 'anon-key-123'
delete process.env.SUPABASE_SERVICE_ROLE_KEY
const spy = mockFetch(fakeSettings({ external: { google: true } }))
const result = await fetchAuthSettings()
expect(result.providers).toEqual([{ id: 'google', label: 'Google', isCustom: false }])
// Only one fetch call (settings), no admin call
expect(spy).toHaveBeenCalledTimes(1)
})
it('returns samlEnabled=true when SAML is enabled', async () => {
process.env.NEXT_PUBLIC_SUPABASE_URL = 'https://project.supabase.co'
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY = 'anon-key-123'
mockFetch(fakeSettings({ saml_enabled: true }))
const result = await fetchAuthSettings()
expect(result.samlEnabled).toBe(true)
})
it('returns samlEnabled=false when SAML is disabled', async () => {
process.env.NEXT_PUBLIC_SUPABASE_URL = 'https://project.supabase.co'
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY = 'anon-key-123'
mockFetch(fakeSettings({ saml_enabled: false }))
const result = await fetchAuthSettings()
expect(result.samlEnabled).toBe(false)
})
})
-31
View File
@@ -1,31 +0,0 @@
import { describe, it, expect } from 'vitest'
import { userHasPassword } from '../has-password'
describe('userHasPassword', () => {
it('returns true when has_password === true', () => {
expect(userHasPassword({ app_metadata: { has_password: true } })).toBe(true)
})
it('returns false when has_password === false', () => {
expect(userHasPassword({ app_metadata: { has_password: false } })).toBe(false)
})
it('returns false when flag is missing but bankid_linked === true', () => {
expect(userHasPassword({ app_metadata: { bankid_linked: true } })).toBe(false)
})
it('returns true when flag is missing and bankid_linked is not true (legacy email/password user)', () => {
expect(userHasPassword({ app_metadata: {} })).toBe(true)
expect(userHasPassword({ app_metadata: { bankid_linked: false } })).toBe(true)
})
it('returns true when app_metadata is missing entirely', () => {
expect(userHasPassword({ app_metadata: undefined as unknown as Record<string, unknown> })).toBe(true)
})
it('prefers explicit has_password over bankid_linked (BankID user who later set a password)', () => {
expect(
userHasPassword({ app_metadata: { bankid_linked: true, has_password: true } }),
).toBe(true)
})
})
-54
View File
@@ -1,54 +0,0 @@
import { describe, it, expect, vi, afterEach } from 'vitest'
import { generateInviteToken, hashInviteToken, getInviteExpiry } from '../invite-tokens'
describe('generateInviteToken', () => {
it('returns token starting with "gnubok_inv_"', () => {
const { token } = generateInviteToken()
expect(token.startsWith('gnubok_inv_')).toBe(true)
})
it('returns a 64-char hex SHA-256 hash', () => {
const { hash } = generateInviteToken()
expect(hash).toMatch(/^[0-9a-f]{64}$/)
})
it('hash matches hashInviteToken(token)', () => {
const { token, hash } = generateInviteToken()
expect(hashInviteToken(token)).toBe(hash)
})
it('generates unique tokens on successive calls', () => {
const a = generateInviteToken()
const b = generateInviteToken()
expect(a.token).not.toBe(b.token)
expect(a.hash).not.toBe(b.hash)
})
})
describe('hashInviteToken', () => {
it('returns 64-char hex string', () => {
const hash = hashInviteToken('gnubok_inv_test-token')
expect(hash).toMatch(/^[0-9a-f]{64}$/)
})
it('is deterministic for same input', () => {
const hash1 = hashInviteToken('gnubok_inv_deterministic')
const hash2 = hashInviteToken('gnubok_inv_deterministic')
expect(hash1).toBe(hash2)
})
})
describe('getInviteExpiry', () => {
afterEach(() => {
vi.useRealTimers()
})
it('returns a Date exactly 7 days in the future', () => {
vi.useFakeTimers()
vi.setSystemTime(new Date('2026-04-14T12:00:00Z'))
const expiry = getInviteExpiry()
expect(expiry.toISOString()).toBe('2026-04-21T12:00:00.000Z')
})
})
-36
View File
@@ -1,36 +0,0 @@
import { describe, expect, it } from 'vitest'
import {
LOGIN_METHOD_COOKIE,
isLoginMethod,
persistLoginMethodHint,
} from '@/lib/auth/login-method'
describe('isLoginMethod', () => {
it('accepts the two supported methods', () => {
expect(isLoginMethod('bankid')).toBe(true)
expect(isLoginMethod('email')).toBe(true)
})
it('rejects anything else', () => {
expect(isLoginMethod('google')).toBe(false)
expect(isLoginMethod('password')).toBe(false)
expect(isLoginMethod('')).toBe(false)
expect(isLoginMethod(undefined)).toBe(false)
expect(isLoginMethod(null)).toBe(false)
})
})
describe('persistLoginMethodHint', () => {
it('is a no-op outside the browser', () => {
expect(() => persistLoginMethodHint('email')).not.toThrow()
})
})
describe('LOGIN_METHOD_COOKIE', () => {
// New wire identifiers use the accounted name; only pre-rebrand ones keep
// the gnubok prefix. Locks the name so a rename cannot silently strand the
// stored hints of every returning user.
it('stays on the accounted name', () => {
expect(LOGIN_METHOD_COOKIE).toBe('accounted-login-method')
})
})
-78
View File
@@ -1,78 +0,0 @@
import { describe, it, expect, vi, afterEach } from 'vitest'
import { isMfaExemptionActive, isMfaRequired, shouldEnforceMfa } from '../mfa'
describe('mfa helpers', () => {
afterEach(() => {
vi.unstubAllEnvs()
})
describe('isMfaRequired', () => {
it('returns false when self-hosted', () => {
vi.stubEnv('NEXT_PUBLIC_SELF_HOSTED', 'true')
vi.stubEnv('NEXT_PUBLIC_REQUIRE_MFA', 'true')
expect(isMfaRequired()).toBe(false)
})
it('returns true when hosted and MFA required', () => {
vi.stubEnv('NEXT_PUBLIC_SELF_HOSTED', 'false')
vi.stubEnv('NEXT_PUBLIC_REQUIRE_MFA', 'true')
expect(isMfaRequired()).toBe(true)
})
})
describe('shouldEnforceMfa', () => {
it('returns false when MFA is not required', () => {
vi.stubEnv('NEXT_PUBLIC_SELF_HOSTED', 'true')
expect(shouldEnforceMfa({ app_metadata: {} })).toBe(false)
})
it('returns false when user has bankid_linked', () => {
vi.stubEnv('NEXT_PUBLIC_SELF_HOSTED', 'false')
vi.stubEnv('NEXT_PUBLIC_REQUIRE_MFA', 'true')
expect(shouldEnforceMfa({ app_metadata: { bankid_linked: true } })).toBe(false)
})
it('returns true when MFA required and no bankid', () => {
vi.stubEnv('NEXT_PUBLIC_SELF_HOSTED', 'false')
vi.stubEnv('NEXT_PUBLIC_REQUIRE_MFA', 'true')
expect(shouldEnforceMfa({ app_metadata: {} })).toBe(true)
})
it('skips MFA while a service-role exemption is still in the future', () => {
vi.stubEnv('NEXT_PUBLIC_SELF_HOSTED', 'false')
vi.stubEnv('NEXT_PUBLIC_REQUIRE_MFA', 'true')
const future = new Date(Date.now() + 60 * 60 * 1000).toISOString()
expect(shouldEnforceMfa({ app_metadata: { mfa_exempt_until: future } })).toBe(false)
})
it('enforces MFA again once the exemption has expired', () => {
vi.stubEnv('NEXT_PUBLIC_SELF_HOSTED', 'false')
vi.stubEnv('NEXT_PUBLIC_REQUIRE_MFA', 'true')
const past = new Date(Date.now() - 60 * 1000).toISOString()
expect(shouldEnforceMfa({ app_metadata: { mfa_exempt_until: past } })).toBe(true)
})
it('treats a malformed or non-string exemption as no exemption', () => {
vi.stubEnv('NEXT_PUBLIC_SELF_HOSTED', 'false')
vi.stubEnv('NEXT_PUBLIC_REQUIRE_MFA', 'true')
expect(shouldEnforceMfa({ app_metadata: { mfa_exempt_until: 'soon' } })).toBe(true)
expect(shouldEnforceMfa({ app_metadata: { mfa_exempt_until: true } })).toBe(true)
expect(shouldEnforceMfa({ app_metadata: { mfa_exempt_until: 4102444800000 } })).toBe(true)
expect(shouldEnforceMfa({ app_metadata: { mfa_exempt: true } })).toBe(true)
})
it('returns true when app_metadata is undefined', () => {
vi.stubEnv('NEXT_PUBLIC_SELF_HOSTED', 'false')
vi.stubEnv('NEXT_PUBLIC_REQUIRE_MFA', 'true')
expect(shouldEnforceMfa({})).toBe(true)
})
})
describe('isMfaExemptionActive', () => {
it('compares against the clock it is given', () => {
const user = { app_metadata: { mfa_exempt_until: '2026-10-01T00:00:00Z' } }
expect(isMfaExemptionActive(user, new Date('2026-09-30T23:59:59Z'))).toBe(true)
expect(isMfaExemptionActive(user, new Date('2026-10-01T00:00:00Z'))).toBe(false)
})
})
})
-298
View File
@@ -1,298 +0,0 @@
import { describe, it, expect, vi, afterEach } from 'vitest'
import {
builtInRedirectProvider,
capScopesForRole,
isAllowedRedirectUri,
isBuiltInRedirectUri,
lookupCompanyRole,
resolveRedirectUri,
} from '../oauth-allowlist'
import { ALL_SCOPES, type ApiKeyScope } from '../scope-catalog'
import type { SupabaseClient } from '@supabase/supabase-js'
describe('isBuiltInRedirectUri', () => {
it.each([
['https://claude.ai/api/oauth/callback', true],
['https://claude.com/api/oauth/callback', true],
['https://chatgpt.com/connector/oauth/abc123', true],
['https://chatgpt.com/connector_platform_oauth_redirect', true],
['https://chatgpt.com/connector_platform_oauth_redirect/extra', false],
['https://chatgpt.com/other/path', false],
['https://chatgpt.com.evil.com/connector/oauth/x', false],
['https://grok.com/connectors-oauth-exchange-code/', true],
['https://grok.com/connectors-oauth-exchange-code', true],
['https://grok.com/connectors-oauth-exchange-code/extra', false],
['https://grok.com/connectors-oauth-exchange-code/?next=x', false],
['https://grok.com/other/path', false],
['https://grok.com.evil.com/connectors-oauth-exchange-code/', false],
['http://grok.com/connectors-oauth-exchange-code/', false],
['cursor://anysphere.cursor-mcp/oauth/callback', true],
['cursor://anysphere.cursor-mcp/oauth/callback/', false],
['cursor://anysphere.cursor-mcp/oauth/callback?x=1', false],
['cursor://anysphere.cursor-mcp/oauth/callback/extra', false],
['cursor://evil.extension/oauth/callback', false],
['https://www.cursor.com/agents/mcp/oauth/callback', true],
['https://www.cursor.com/agents/mcp/oauth/callback/', false],
['https://www.cursor.com/agents/mcp/oauth/callback2', false],
['https://cursor.com/agents/mcp/oauth/callback', false],
['https://www.cursor.com.evil.com/agents/mcp/oauth/callback', false],
['http://www.cursor.com/agents/mcp/oauth/callback', false],
['http://localhost:8787/callback', true],
['http://localhost:3000/cb', true],
['http://localhost/cb', true],
['http://127.0.0.1:8080/cb', true],
['https://evil.com/cb', false],
['https://example.com/api/foo', false],
['ftp://localhost/cb', false],
['', false],
])('classifies %s as %s', (uri, expected) => {
expect(isBuiltInRedirectUri(uri)).toBe(expected)
})
})
describe('builtInRedirectProvider', () => {
it.each([
['https://claude.ai/api/oauth/callback', 'claude'],
['https://claude.com/api/oauth/callback', 'claude'],
['https://chatgpt.com/connector/oauth/abc123', 'chatgpt'],
['https://chatgpt.com/connector_platform_oauth_redirect', 'chatgpt'],
['https://grok.com/connectors-oauth-exchange-code/', 'grok'],
['https://grok.com/connectors-oauth-exchange-code/extra', null],
['cursor://anysphere.cursor-mcp/oauth/callback', 'cursor_deeplink'],
['https://www.cursor.com/agents/mcp/oauth/callback', 'cursor'],
['http://localhost:8787/callback', 'local'],
['http://localhost:3000/cb', 'local'],
['http://127.0.0.1:8080/cb', 'local'],
['https://claude-login.example/cb', null],
['', null],
])('maps %s to %s', (uri, expected) => {
expect(builtInRedirectProvider(uri)).toBe(expected)
})
})
type Row = Record<string, unknown>
/**
* Minimal PostgREST-shaped fake over in-memory tables: eq/is filters are
* applied, everything else is a no-op, and the chain resolves to the filtered
* rows (all rows when awaited, first row via maybeSingle). `failTable` makes
* every query against that table return a DB error.
*/
function fakeClient(tables: Record<string, Row[]>, failTable?: string) {
const from = vi.fn((table: string) => {
const filters: [string, unknown][] = []
const run = () =>
(tables[table] ?? []).filter((row) =>
filters.every(([col, val]) => (val === null ? row[col] == null : row[col] === val)),
)
const result = () =>
table === failTable
? { data: null, error: { message: 'db down' } }
: { data: run(), error: null }
const chain: Record<string, unknown> = {}
for (const method of ['select', 'order', 'range', 'limit']) chain[method] = () => chain
chain.eq = (col: string, val: unknown) => {
filters.push([col, val])
return chain
}
chain.is = (col: string, val: unknown) => {
filters.push([col, val])
return chain
}
chain.maybeSingle = async () => {
const r = result()
return { data: Array.isArray(r.data) ? (r.data[0] ?? null) : null, error: r.error }
}
chain.then = (resolve: (v: unknown) => void) => resolve(result())
return chain
})
return { from } as unknown as SupabaseClient & { from: ReturnType<typeof vi.fn> }
}
const REGISTRATIONS: Row[] = [
{ id: 'reg-1', user_id: 'user-2', client_name: 'Byråns bot', redirect_uri: 'https://app.example.com/cb', revoked_at: null },
{ id: 'reg-2', user_id: 'user-9', client_name: 'Evil', redirect_uri: 'https://evil.example/cb', revoked_at: null },
{ id: 'reg-3', user_id: 'user-1', client_name: 'Min egen app', redirect_uri: 'https://mine.example/cb', revoked_at: null },
{ id: 'reg-4', user_id: 'user-1', client_name: 'Gammal app', redirect_uri: 'https://old.example/cb', revoked_at: '2026-01-01T00:00:00Z' },
]
const MEMBERSHIPS: Row[] = [
{ id: 'm1', user_id: 'user-1', company_id: 'company-1', role: 'owner' },
{ id: 'm2', user_id: 'user-2', company_id: 'company-1', role: 'member' },
{ id: 'm3', user_id: 'user-2', company_id: 'company-2', role: 'owner' },
{ id: 'm4', user_id: 'user-9', company_id: 'company-9', role: 'owner' },
]
const DB = { oauth_client_registrations: REGISTRATIONS, company_members: MEMBERSHIPS }
describe('resolveRedirectUri', () => {
afterEach(() => {
vi.unstubAllEnvs()
})
it('short-circuits to the built-in provider without touching the DB', async () => {
const sb = {
from: vi.fn(() => {
throw new Error('should not be called')
}),
} as unknown as SupabaseClient
expect(await resolveRedirectUri('https://claude.ai/api/cb', sb, { consentingUserId: 'user-1' })).toEqual({
allowed: true,
kind: 'built_in',
provider: 'claude',
})
expect(await resolveRedirectUri('http://localhost:3000/cb', sb)).toEqual({
allowed: true,
kind: 'built_in',
provider: 'local',
})
})
it("accepts the consenting user's own registration", async () => {
const result = await resolveRedirectUri('https://mine.example/cb', fakeClient(DB), {
consentingUserId: 'user-1',
})
expect(result).toEqual({
allowed: true,
kind: 'registered',
clientName: 'Min egen app',
registeredByConsentingUser: true,
})
})
it('accepts a registration by a colleague who shares a company', async () => {
const result = await resolveRedirectUri('https://app.example.com/cb', fakeClient(DB), {
consentingUserId: 'user-1',
})
expect(result).toEqual({
allowed: true,
kind: 'registered',
clientName: 'Byråns bot',
registeredByConsentingUser: false,
})
})
it('rejects a registration by an unrelated user', async () => {
// user-9 is a real member of the instance, just not of any company user-1
// belongs to: their registration must not be a valid target for user-1.
const result = await resolveRedirectUri('https://evil.example/cb', fakeClient(DB), {
consentingUserId: 'user-1',
})
expect(result).toEqual({ allowed: false })
})
it('accepts any active registration when no consenting user is given (anonymous /register)', async () => {
const result = await resolveRedirectUri('https://evil.example/cb', fakeClient(DB))
expect(result).toEqual({
allowed: true,
kind: 'registered',
clientName: 'Evil',
registeredByConsentingUser: false,
})
})
it('rejects a revoked registration, even the user’s own', async () => {
const result = await resolveRedirectUri('https://old.example/cb', fakeClient(DB), {
consentingUserId: 'user-1',
})
expect(result).toEqual({ allowed: false })
})
it('rejects an unknown URI', async () => {
expect(await resolveRedirectUri('https://nowhere.example/cb', fakeClient(DB))).toEqual({ allowed: false })
})
it('fails closed when the registration lookup errors', async () => {
const result = await resolveRedirectUri(
'https://mine.example/cb',
fakeClient(DB, 'oauth_client_registrations'),
{ consentingUserId: 'user-1' },
)
expect(result).toEqual({ allowed: false })
})
it('fails closed when the shared-company check errors', async () => {
const result = await resolveRedirectUri('https://app.example.com/cb', fakeClient(DB, 'company_members'), {
consentingUserId: 'user-1',
})
expect(result).toEqual({ allowed: false })
})
it('fails closed when no client is given and none can be constructed', async () => {
vi.stubEnv('NEXT_PUBLIC_SUPABASE_URL', '')
vi.stubEnv('SUPABASE_SERVICE_ROLE_KEY', '')
expect(await resolveRedirectUri('https://mine.example/cb', undefined, { consentingUserId: 'user-1' })).toEqual({
allowed: false,
})
})
it('returns not allowed for empty / non-string inputs', async () => {
expect(await resolveRedirectUri('')).toEqual({ allowed: false })
expect(await resolveRedirectUri(undefined as unknown as string)).toEqual({ allowed: false })
})
})
describe('isAllowedRedirectUri', () => {
it('is the boolean view of resolveRedirectUri', async () => {
expect(await isAllowedRedirectUri('https://claude.ai/api/cb')).toBe(true)
expect(await isAllowedRedirectUri('https://mine.example/cb', fakeClient(DB), { consentingUserId: 'user-1' })).toBe(true)
expect(await isAllowedRedirectUri('https://evil.example/cb', fakeClient(DB), { consentingUserId: 'user-1' })).toBe(false)
expect(await isAllowedRedirectUri('https://evil.example/cb', fakeClient(DB))).toBe(true)
expect(await isAllowedRedirectUri('', fakeClient(DB))).toBe(false)
})
})
describe('capScopesForRole', () => {
const mixed: ApiKeyScope[] = [
'transactions:read',
'transactions:write',
'pending_operations:approve',
'webhooks:manage',
'reconciliation:signoff',
'reports:read',
]
it('keeps every scope for owner, admin and member', () => {
for (const role of ['owner', 'admin', 'member']) {
expect(capScopesForRole(mixed, role)).toEqual(mixed)
}
})
it('caps a viewer to :read scopes only', () => {
expect(capScopesForRole(mixed, 'viewer')).toEqual(['transactions:read', 'reports:read'])
})
it('caps an unknown role and a missing membership to :read scopes', () => {
expect(capScopesForRole(mixed, 'superuser')).toEqual(['transactions:read', 'reports:read'])
expect(capScopesForRole(mixed, null)).toEqual(['transactions:read', 'reports:read'])
})
it('leaves no write-kind scope in a capped set for the full catalogue', () => {
const capped = capScopesForRole(ALL_SCOPES, 'viewer')
expect(capped.length).toBeGreaterThan(0)
expect(capped.every((s) => s.endsWith(':read'))).toBe(true)
expect(capped).not.toContain('pending_operations:approve')
})
it('returns a copy, never the caller’s array', () => {
const result = capScopesForRole(mixed, 'owner')
expect(result).not.toBe(mixed)
})
})
describe('lookupCompanyRole', () => {
it('returns the role for an existing membership', async () => {
expect(await lookupCompanyRole(fakeClient(DB), 'user-2', 'company-1')).toEqual({ role: 'member', error: null })
expect(await lookupCompanyRole(fakeClient(DB), 'user-2', 'company-2')).toEqual({ role: 'owner', error: null })
})
it('returns a null role when no membership row exists', async () => {
expect(await lookupCompanyRole(fakeClient(DB), 'user-9', 'company-1')).toEqual({ role: null, error: null })
})
it('surfaces a query error instead of guessing', async () => {
const result = await lookupCompanyRole(fakeClient(DB, 'company_members'), 'user-1', 'company-1')
expect(result.role).toBeNull()
expect(result.error).toBe('db down')
})
})
-145
View File
@@ -1,145 +0,0 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import crypto from 'crypto'
import { createAuthCode, decryptAuthCode, verifyPkce, hashAuthCode } from '../oauth-codes'
beforeEach(() => {
vi.stubEnv('SUPABASE_SERVICE_ROLE_KEY', 'test-secret-for-oauth-tests')
})
afterEach(() => {
vi.unstubAllEnvs()
vi.useRealTimers()
})
// ============================================================
// createAuthCode + decryptAuthCode round-trip
// ============================================================
describe('createAuthCode + decryptAuthCode round-trip', () => {
it('encrypts and decrypts preserving userId, codeChallenge, redirectUri', () => {
const payload = {
userId: 'user-123',
codeChallenge: 'challenge-abc',
redirectUri: 'https://claude.ai/api/callback',
}
const code = createAuthCode(payload)
const decrypted = decryptAuthCode(code)
expect(decrypted).not.toBeNull()
expect(decrypted!.userId).toBe('user-123')
expect(decrypted!.codeChallenge).toBe('challenge-abc')
expect(decrypted!.redirectUri).toBe('https://claude.ai/api/callback')
})
it('sets exp approximately 5 minutes in future', () => {
vi.useFakeTimers()
vi.setSystemTime(new Date('2026-04-14T12:00:00Z'))
const code = createAuthCode({
userId: 'user-1',
codeChallenge: 'ch',
redirectUri: 'http://localhost',
})
const decrypted = decryptAuthCode(code)
expect(decrypted).not.toBeNull()
// exp should be Date.now() + 5 * 60 * 1000
const expectedExp = new Date('2026-04-14T12:00:00Z').getTime() + 5 * 60 * 1000
expect(decrypted!.exp).toBe(expectedExp)
})
it('returns null for expired code', () => {
vi.useFakeTimers()
vi.setSystemTime(new Date('2026-04-14T12:00:00Z'))
const code = createAuthCode({
userId: 'user-1',
codeChallenge: 'ch',
redirectUri: 'http://localhost',
})
// Advance past 5 minute TTL
vi.advanceTimersByTime(5 * 60 * 1000 + 1)
const decrypted = decryptAuthCode(code)
expect(decrypted).toBeNull()
})
it('returns null for tampered ciphertext', () => {
const code = createAuthCode({
userId: 'user-1',
codeChallenge: 'ch',
redirectUri: 'http://localhost',
})
// Flip a character in the middle of the encrypted string
const chars = code.split('')
const mid = Math.floor(chars.length / 2)
chars[mid] = chars[mid] === 'A' ? 'B' : 'A'
const tampered = chars.join('')
expect(decryptAuthCode(tampered)).toBeNull()
})
it('returns null for completely invalid base64url', () => {
expect(decryptAuthCode('not-a-valid-code!!!')).toBeNull()
})
it('throws when SUPABASE_SERVICE_ROLE_KEY is not set', () => {
vi.stubEnv('SUPABASE_SERVICE_ROLE_KEY', '')
expect(() =>
createAuthCode({
userId: 'user-1',
codeChallenge: 'ch',
redirectUri: 'http://localhost',
})
).toThrow('SUPABASE_SERVICE_ROLE_KEY is required')
})
})
// ============================================================
// verifyPkce
// ============================================================
describe('verifyPkce', () => {
it('returns true when SHA256(verifier) matches challenge', () => {
const verifier = 'dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk'
// Compute expected challenge using base64url(SHA-256(verifier))
const challenge = crypto.createHash('sha256').update(verifier).digest('base64url')
expect(verifyPkce(verifier, challenge)).toBe(true)
})
it('returns false when verifier does not match challenge', () => {
expect(verifyPkce('correct-verifier', 'wrong-challenge')).toBe(false)
})
})
// ============================================================
// hashAuthCode
// ============================================================
describe('hashAuthCode', () => {
it('returns 64-char hex string', () => {
const hash = hashAuthCode('some-auth-code')
expect(hash).toMatch(/^[0-9a-f]{64}$/)
})
it('is deterministic for same input', () => {
const hash1 = hashAuthCode('deterministic-code')
const hash2 = hashAuthCode('deterministic-code')
expect(hash1).toBe(hash2)
})
})
describe('verifyPkce with a missing challenge', () => {
it('never verifies when the code was minted without a code_challenge', () => {
// /authorize does not reject a missing code_challenge; it mints the code
// with an empty one. That must stay unexchangeable, otherwise a
// custom-scheme (cursor://) hijacker could skip PKCE entirely.
expect(verifyPkce('any-verifier', '')).toBe(false)
expect(verifyPkce('', '')).toBe(false)
})
})
@@ -1,216 +0,0 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
vi.mock('@/lib/supabase/server', () => ({
createClient: vi.fn(),
}))
// The trusted-origin resolver reads the brands table; books.partner.example
// is the one registered brand host in these tests.
const resolveBrandResultByHostMock = vi.hoisted(() => vi.fn())
vi.mock('@/lib/branding/resolve', () => ({
resolveBrandResultByHost: (...args: unknown[]) => resolveBrandResultByHostMock(...args),
}))
function registerBrandHost(host: string | null) {
resolveBrandResultByHostMock.mockImplementation(async (candidate: string) => ({
brand: host !== null && candidate === host ? { domain: host } : null,
lookupFailed: false,
}))
}
registerBrandHost('books.partner.example')
import { createClient } from '@/lib/supabase/server'
import {
requireFlowInitiator,
buildLoginRedirect,
redactUserId,
FLOW_INITIATOR_MISMATCH_MESSAGE,
} from '../oauth-flow-binding'
const CALLBACK_URL =
'https://app.example.se/api/extensions/stripe/callback?code=ac_123&state=state-1'
function mockSession(getUser: ReturnType<typeof vi.fn>) {
vi.mocked(createClient).mockResolvedValue({ auth: { getUser } } as never)
return getUser
}
function sessionWith(userId: string | null, error: unknown = null) {
return mockSession(
vi.fn().mockResolvedValue({
data: { user: userId ? { id: userId } : null },
error,
}),
)
}
describe('requireFlowInitiator', () => {
beforeEach(() => {
vi.clearAllMocks()
vi.stubEnv('NEXT_PUBLIC_APP_URL', 'https://app.example.se')
})
afterEach(() => {
vi.unstubAllEnvs()
})
it('passes when the cookie session belongs to the initiator', async () => {
const getUser = sessionWith('user-1')
const result = await requireFlowInitiator(new Request(CALLBACK_URL), 'user-1')
expect(result).toEqual({ ok: true, userId: 'user-1' })
expect(getUser).toHaveBeenCalledTimes(1)
})
it('refuses with a 403 envelope when a different user completes the flow', async () => {
sessionWith('user-2')
const result = await requireFlowInitiator(new Request(CALLBACK_URL), 'user-1', {
flow: 'stripe.callback',
})
expect(result.ok).toBe(false)
if (result.ok) throw new Error('unreachable')
expect(result.reason).toBe('mismatch')
if (result.reason !== 'mismatch') throw new Error('unreachable')
expect(result.sessionUserId).toBe('user-2')
expect(result.response.status).toBe(403)
const body = await result.response.json()
expect(body.error.code).toBe('OAUTH_FLOW_INITIATOR_MISMATCH')
expect(body.error.message).toBe(FLOW_INITIATOR_MISMATCH_MESSAGE)
expect(typeof body.error.message_en).toBe('string')
})
it('sends an anonymous browser to /login with the callback URL as next', async () => {
sessionWith(null)
const result = await requireFlowInitiator(new Request(CALLBACK_URL), 'user-1')
expect(result.ok).toBe(false)
if (result.ok) throw new Error('unreachable')
expect(result.reason).toBe('no_session')
expect(result.response.status).toBe(307)
const location = new URL(result.response.headers.get('location') ?? '')
expect(location.origin).toBe('https://app.example.se')
expect(location.pathname).toBe('/login')
// Same-origin relative path + query, the only shape the login page's
// safeReturnTo accepts, so signing in resumes the very same callback.
expect(location.searchParams.get('next')).toBe(
'/api/extensions/stripe/callback?code=ac_123&state=state-1',
)
})
it('sends an anonymous browser to the recorded brand origin when the caller passes one', async () => {
// Provider redirect URIs are pinned to the canonical host while sessions
// are per host: a white-label user reaches the callback signed out and
// must be sent to THEIR brand login, where the session already exists.
sessionWith(null)
const result = await requireFlowInitiator(new Request(CALLBACK_URL), 'user-1', {
returnOrigin: 'https://books.partner.example',
})
expect(result.ok).toBe(false)
if (result.ok) throw new Error('unreachable')
expect(result.reason).toBe('no_session')
const location = new URL(result.response.headers.get('location') ?? '')
expect(location.origin).toBe('https://books.partner.example')
expect(location.pathname).toBe('/login')
expect(location.searchParams.get('next')).toBe(
'/api/extensions/stripe/callback?code=ac_123&state=state-1',
)
})
it('treats a getUser error as no session (fail closed)', async () => {
sessionWith(null, { message: 'invalid JWT' })
const result = await requireFlowInitiator(new Request(CALLBACK_URL), 'user-1')
expect(result.ok).toBe(false)
if (result.ok) throw new Error('unreachable')
expect(result.reason).toBe('no_session')
})
it('treats a thrown client error as no session instead of finalizing on a guess', async () => {
vi.mocked(createClient).mockRejectedValue(new Error('cookies() outside request scope'))
const result = await requireFlowInitiator(new Request(CALLBACK_URL), 'user-1')
expect(result.ok).toBe(false)
if (result.ok) throw new Error('unreachable')
expect(result.reason).toBe('no_session')
expect(result.response.headers.get('location')).toContain('/login?next=')
})
it('never passes on an empty expected id even when someone is signed in', async () => {
sessionWith('user-2')
const result = await requireFlowInitiator(new Request(CALLBACK_URL), '')
expect(result.ok).toBe(false)
})
})
describe('buildLoginRedirect', () => {
afterEach(() => {
vi.unstubAllEnvs()
})
it('falls back to the request origin when NEXT_PUBLIC_APP_URL is unset', async () => {
vi.stubEnv('NEXT_PUBLIC_APP_URL', '')
const response = await buildLoginRedirect(
new Request('http://localhost:3000/api/extensions/woocommerce/return?success=1&user_id=abc'),
)
expect(response.headers.get('location')).toBe(
'http://localhost:3000/login?next=' +
encodeURIComponent('/api/extensions/woocommerce/return?success=1&user_id=abc'),
)
})
it('uses a recorded origin only when it is the canonical host or a registered white-label host', async () => {
vi.stubEnv('NEXT_PUBLIC_APP_URL', 'https://app.example.se')
const request = new Request('https://app.example.se/api/extensions/stripe/callback?code=1&state=2')
const brand = await buildLoginRedirect(request, 'https://books.partner.example')
expect(new URL(brand.headers.get('location') ?? '').origin).toBe('https://books.partner.example')
// A stored value that is no longer (or never was) registered must not
// become a redirect target: the allowlist is the only authority.
const unknown = await buildLoginRedirect(request, 'https://evil.example')
expect(new URL(unknown.headers.get('location') ?? '').origin).toBe('https://app.example.se')
const canonical = await buildLoginRedirect(request, 'https://app.example.se')
expect(new URL(canonical.headers.get('location') ?? '').origin).toBe('https://app.example.se')
})
it('keeps a callback that arrived on a registered brand host on that host', async () => {
// NEXT_PUBLIC_APP_URL used to win over the request origin here, dragging
// a brand-domain callback to the canonical login. The allowlisted request
// host is the fallback now; an unregistered host still collapses.
vi.stubEnv('NEXT_PUBLIC_APP_URL', 'https://app.example.se')
const onBrand = await buildLoginRedirect(
new Request('https://books.partner.example/api/extensions/stripe/callback?code=1&state=2'),
)
expect(new URL(onBrand.headers.get('location') ?? '').origin).toBe('https://books.partner.example')
const onUnknown = await buildLoginRedirect(
new Request('https://evil.example/api/extensions/stripe/callback?code=1&state=2'),
)
expect(new URL(onUnknown.headers.get('location') ?? '').origin).toBe('https://app.example.se')
})
})
describe('redactUserId', () => {
it('keeps only a correlation prefix of a uuid', () => {
expect(redactUserId('123e4567-e89b-12d3-a456-426614174000')).toBe('123e4567...')
})
it('handles short and missing ids', () => {
expect(redactUserId('user-1')).toBe('user-1')
expect(redactUserId(null)).toBe('(none)')
expect(redactUserId(undefined)).toBe('(none)')
})
})
-368
View File
@@ -1,368 +0,0 @@
/* 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\./)]],
]),
)
})
})
-155
View File
@@ -1,155 +0,0 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
const mocks = vi.hoisted(() => ({
logError: vi.fn(),
logWarn: vi.fn(),
logInfo: vi.fn(),
redisCtor: vi.fn(),
ratelimitCtor: vi.fn(),
limit: vi.fn(),
}))
vi.mock('@/lib/logger', () => ({
createLogger: () => ({
error: mocks.logError,
warn: mocks.logWarn,
info: mocks.logInfo,
child: () => ({ error: mocks.logError, warn: mocks.logWarn, info: mocks.logInfo }),
}),
}))
vi.mock('@upstash/redis', () => ({
Redis: class Redis {
constructor(cfg: unknown) {
mocks.redisCtor(cfg)
}
},
}))
vi.mock('@upstash/ratelimit', () => ({
Ratelimit: class Ratelimit {
static slidingWindow = vi.fn((max: number, window: string) => ({ max, window }))
limit = mocks.limit
constructor(cfg: unknown) {
mocks.ratelimitCtor(cfg)
}
},
}))
// The "report once per process" flag is module state, so every test gets a
// fresh module instance instead of a test-only reset export.
async function loadModule() {
vi.resetModules()
return import('@/lib/auth/rate-limit-http')
}
const OPTS = { prefix: 'test', identifier: 'ip:1', maxRequests: 5, windowMs: 60_000 }
describe('checkRateLimit', () => {
beforeEach(() => {
vi.clearAllMocks()
vi.stubEnv('UPSTASH_REDIS_REST_URL', '')
vi.stubEnv('UPSTASH_REDIS_REST_TOKEN', '')
vi.stubEnv('NEXT_PUBLIC_SELF_HOSTED', '')
vi.stubEnv('NODE_ENV', 'production')
})
afterEach(() => {
vi.unstubAllEnvs()
})
describe('Redis not configured', () => {
it('fails open on a hosted production deployment but logs one error with the alert flag', async () => {
const { checkRateLimit } = await loadModule()
expect(await checkRateLimit(OPTS)).toEqual({ ok: true })
expect(await checkRateLimit({ ...OPTS, identifier: 'ip:2' })).toEqual({ ok: true })
expect(await checkRateLimit({ ...OPTS, prefix: 'other' })).toEqual({ ok: true })
expect(mocks.logError).toHaveBeenCalledTimes(1)
const [message, ctx] = mocks.logError.mock.calls[0]
expect(message).toMatch(/UPSTASH_REDIS_REST_URL/)
expect(message).toMatch(/failing open/)
expect(ctx).toMatchObject({ alert: true })
expect(mocks.redisCtor).not.toHaveBeenCalled()
})
it('stays quiet on a self-hosted deployment (Redis is optional there)', async () => {
vi.stubEnv('NEXT_PUBLIC_SELF_HOSTED', 'true')
const { checkRateLimit } = await loadModule()
expect(await checkRateLimit(OPTS)).toEqual({ ok: true })
expect(mocks.logError).not.toHaveBeenCalled()
})
it('stays quiet outside production (local dev and tests are not deployments)', async () => {
vi.stubEnv('NODE_ENV', 'development')
const { checkRateLimit } = await loadModule()
expect(await checkRateLimit(OPTS)).toEqual({ ok: true })
expect(mocks.logError).not.toHaveBeenCalled()
})
it('reports the limiter as not configured', async () => {
const { isRateLimiterConfigured } = await loadModule()
expect(isRateLimiterConfigured()).toBe(false)
vi.stubEnv('UPSTASH_REDIS_REST_URL', 'https://redis.example')
expect(isRateLimiterConfigured()).toBe(false)
vi.stubEnv('UPSTASH_REDIS_REST_TOKEN', 'tok')
expect(isRateLimiterConfigured()).toBe(true)
})
})
describe('Redis configured', () => {
beforeEach(() => {
vi.stubEnv('UPSTASH_REDIS_REST_URL', 'https://redis.example')
vi.stubEnv('UPSTASH_REDIS_REST_TOKEN', 'tok')
})
it('allows the request when the sliding window has room and logs nothing', async () => {
mocks.limit.mockResolvedValue({ success: true, reset: Date.now() + 1000, limit: 5, remaining: 4 })
const { checkRateLimit } = await loadModule()
expect(await checkRateLimit(OPTS)).toEqual({ ok: true })
expect(mocks.limit).toHaveBeenCalledWith('ip:1')
expect(mocks.redisCtor).toHaveBeenCalledWith({ url: 'https://redis.example', token: 'tok' })
expect(mocks.ratelimitCtor).toHaveBeenCalledWith(
expect.objectContaining({ prefix: 'test', analytics: false }),
)
expect(mocks.logError).not.toHaveBeenCalled()
})
it('returns a Swedish 429 with Retry-After and X-RateLimit headers when blocked', async () => {
const reset = Date.now() + 30_000
mocks.limit.mockResolvedValue({ success: false, reset, limit: 5, remaining: 0 })
const { checkRateLimit } = await loadModule()
const result = await checkRateLimit(OPTS)
expect(result.ok).toBe(false)
expect(result.response?.status).toBe(429)
expect(await result.response?.json()).toEqual({
error: 'För många förfrågningar. Försök igen om en stund.',
})
const retryAfter = Number(result.response?.headers.get('Retry-After'))
expect(retryAfter).toBeGreaterThanOrEqual(29)
expect(retryAfter).toBeLessThanOrEqual(31)
expect(result.response?.headers.get('X-RateLimit-Limit')).toBe('5')
expect(result.response?.headers.get('X-RateLimit-Remaining')).toBe('0')
expect(result.response?.headers.get('X-RateLimit-Reset')).toBe(String(Math.ceil(reset / 1000)))
})
it('reuses one limiter per prefix/limit/window triple', async () => {
mocks.limit.mockResolvedValue({ success: true, reset: 0, limit: 5, remaining: 4 })
const { checkRateLimit } = await loadModule()
await checkRateLimit(OPTS)
await checkRateLimit({ ...OPTS, identifier: 'ip:9' })
await checkRateLimit({ ...OPTS, maxRequests: 50 })
expect(mocks.ratelimitCtor).toHaveBeenCalledTimes(2)
expect(mocks.redisCtor).toHaveBeenCalledTimes(1)
})
})
})
-341
View File
@@ -1,341 +0,0 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
vi.mock('@/lib/supabase/server', () => ({
createClient: vi.fn(),
}))
import { requireAuth } from '../require-auth'
import { createClient } from '@/lib/supabase/server'
const CLAIMS = {
iss: 'https://test.supabase.co/auth/v1',
sub: 'user-1',
aud: 'authenticated',
exp: 9999999999,
iat: 0,
role: 'authenticated',
aal: 'aal1',
session_id: 'sess-1',
email: '[email protected]',
is_anonymous: false,
app_metadata: { provider: 'email' },
user_metadata: {},
}
const MOCK_USER = {
id: 'user-1',
aud: 'authenticated',
email: '[email protected]',
app_metadata: { provider: 'email' },
user_metadata: {},
created_at: '2026-01-01T00:00:00Z',
}
const VERIFIED_TOTP = { id: 'f1', status: 'verified', factor_type: 'totp' }
const UNVERIFIED_TOTP = { id: 'f2', status: 'unverified', factor_type: 'totp' }
/** listFactors() payload: `all` carries everything, the typed arrays only verified ones. */
function factorList(...factors: Array<typeof VERIFIED_TOTP>) {
return {
data: {
all: factors,
totp: factors.filter((f) => f.status === 'verified'),
phone: [],
webauthn: [],
},
error: null,
}
}
type MockAuth = Record<string, unknown>
function useSupabase(auth: MockAuth) {
const supabase = { auth }
vi.mocked(createClient).mockResolvedValue(supabase as never)
return supabase
}
function enableMfa() {
vi.stubEnv('NEXT_PUBLIC_REQUIRE_MFA', 'true')
vi.stubEnv('NEXT_PUBLIC_SELF_HOSTED', '')
}
describe('requireAuth', () => {
beforeEach(() => {
vi.clearAllMocks()
// Deterministic baseline: MFA off unless a test stubs it on.
vi.stubEnv('NEXT_PUBLIC_REQUIRE_MFA', 'false')
// Matches CLAIMS.iss so the fast path passes the issuer pinning.
vi.stubEnv('NEXT_PUBLIC_SUPABASE_URL', 'https://test.supabase.co')
})
afterEach(() => {
vi.unstubAllEnvs()
})
it('uses locally verified claims without calling getUser (fast path)', async () => {
const getClaims = vi.fn().mockResolvedValue({ data: { claims: CLAIMS }, error: null })
const getUser = vi.fn()
useSupabase({ getClaims, getUser })
const result = await requireAuth()
expect(result.error).toBeNull()
expect(result.user?.id).toBe('user-1')
expect(result.user?.email).toBe('[email protected]')
expect(result.user?.app_metadata).toEqual({ provider: 'email' })
expect(getUser).not.toHaveBeenCalled()
})
it('falls back to getUser when the client has no getClaims (legacy mocks)', async () => {
const getUser = vi.fn().mockResolvedValue({ data: { user: MOCK_USER }, error: null })
useSupabase({ getUser })
const result = await requireAuth()
expect(result.error).toBeNull()
expect(result.user?.id).toBe('user-1')
expect(getUser).toHaveBeenCalledTimes(1)
})
it('returns 401 when neither claims nor getUser yield a user', async () => {
const getClaims = vi.fn().mockResolvedValue({ data: null, error: null })
const getUser = vi.fn().mockResolvedValue({ data: { user: null }, error: null })
useSupabase({ getClaims, getUser })
const result = await requireAuth()
expect(result.user).toBeNull()
expect(result.error?.status).toBe(401)
const body = await result.error?.json()
expect(body).toEqual({ error: 'Unauthorized' })
expect(getUser).toHaveBeenCalledTimes(1)
})
it('falls back to getUser when getClaims throws (JWKS outage)', async () => {
const getClaims = vi.fn().mockRejectedValue(new Error('jwks fetch failed'))
const getUser = vi.fn().mockResolvedValue({ data: { user: MOCK_USER }, error: null })
useSupabase({ getClaims, getUser })
const result = await requireAuth()
expect(result.error).toBeNull()
expect(result.user?.id).toBe('user-1')
expect(getUser).toHaveBeenCalledTimes(1)
})
it('falls back to getUser when the claims issuer does not match the project URL', async () => {
const claims = { ...CLAIMS, iss: 'https://evil.example.com/auth/v1' }
const getClaims = vi.fn().mockResolvedValue({ data: { claims }, error: null })
const getUser = vi.fn().mockResolvedValue({ data: { user: MOCK_USER }, error: null })
useSupabase({ getClaims, getUser })
const result = await requireAuth()
expect(result.error).toBeNull()
expect(result.user?.id).toBe('user-1')
expect(getUser).toHaveBeenCalledTimes(1)
})
it('falls back to getUser when the claims audience is not authenticated', async () => {
const claims = { ...CLAIMS, aud: 'something-else' }
const getClaims = vi.fn().mockResolvedValue({ data: { claims }, error: null })
const getUser = vi.fn().mockResolvedValue({ data: { user: MOCK_USER }, error: null })
useSupabase({ getClaims, getUser })
const result = await requireAuth()
expect(result.error).toBeNull()
expect(result.user?.id).toBe('user-1')
expect(getUser).toHaveBeenCalledTimes(1)
})
it('accepts an array audience containing authenticated', async () => {
const claims = { ...CLAIMS, aud: ['authenticated', 'other'] }
const getClaims = vi.fn().mockResolvedValue({ data: { claims }, error: null })
const getUser = vi.fn()
useSupabase({ getClaims, getUser })
const result = await requireAuth()
expect(result.error).toBeNull()
expect(result.user?.id).toBe('user-1')
expect(getUser).not.toHaveBeenCalled()
})
describe('MFA gate', () => {
beforeEach(() => {
enableMfa()
vi.spyOn(console, 'error').mockImplementation(() => {})
})
afterEach(() => {
vi.restoreAllMocks()
})
it('returns 403 for an AAL1 session when the auth server reports a verified factor', async () => {
const getClaims = vi.fn().mockResolvedValue({ data: { claims: CLAIMS }, error: null })
const listFactors = vi.fn().mockResolvedValue(factorList(VERIFIED_TOTP))
useSupabase({ getClaims, mfa: { listFactors } })
const result = await requireAuth()
expect(result.user).toBeNull()
expect(result.error?.status).toBe(403)
const body = await result.error?.json()
expect(body).toEqual({ error: 'MFA verification required' })
expect(listFactors).toHaveBeenCalledTimes(1)
})
it('never consults the cookie-derived assurance level', async () => {
// The attack: the sb-*-auth-token cookie is unsigned JSON, so the
// password holder strips `user.factors` and the local
// getAuthenticatorAssuranceLevel() reports nextLevel aal1 ("no MFA
// enrolled"). The gate must decide on the server's answer instead.
const getClaims = vi.fn().mockResolvedValue({ data: { claims: CLAIMS }, error: null })
const getAuthenticatorAssuranceLevel = vi.fn().mockResolvedValue({
data: { currentLevel: 'aal1', nextLevel: 'aal1' },
error: null,
})
const listFactors = vi.fn().mockResolvedValue(factorList(VERIFIED_TOTP))
useSupabase({ getClaims, mfa: { getAuthenticatorAssuranceLevel, listFactors } })
const result = await requireAuth()
expect(result.error?.status).toBe(403)
expect(getAuthenticatorAssuranceLevel).not.toHaveBeenCalled()
})
it('passes an AAL2 session on the verified claims alone (no listFactors round trip)', async () => {
const claims = { ...CLAIMS, aal: 'aal2' }
const getClaims = vi.fn().mockResolvedValue({ data: { claims }, error: null })
const listFactors = vi.fn()
const getAuthenticatorAssuranceLevel = vi.fn()
useSupabase({ getClaims, mfa: { listFactors, getAuthenticatorAssuranceLevel } })
const result = await requireAuth()
expect(result.error).toBeNull()
expect(result.user?.id).toBe('user-1')
expect(listFactors).not.toHaveBeenCalled()
expect(getAuthenticatorAssuranceLevel).not.toHaveBeenCalled()
})
it('passes an AAL1 session when the auth server reports no verified factor', async () => {
const getClaims = vi.fn().mockResolvedValue({ data: { claims: CLAIMS }, error: null })
const listFactors = vi.fn().mockResolvedValue(factorList())
useSupabase({ getClaims, mfa: { listFactors } })
const result = await requireAuth()
expect(result.error).toBeNull()
expect(result.user?.id).toBe('user-1')
expect(listFactors).toHaveBeenCalledTimes(1)
})
it('does not count an unverified (enrolment in progress) factor as a step-up target', async () => {
const getClaims = vi.fn().mockResolvedValue({ data: { claims: CLAIMS }, error: null })
const listFactors = vi.fn().mockResolvedValue(factorList(UNVERIFIED_TOTP))
useSupabase({ getClaims, mfa: { listFactors } })
const result = await requireAuth()
expect(result.error).toBeNull()
})
it('reads a verified phone factor from the typed array when `all` is absent', async () => {
const getClaims = vi.fn().mockResolvedValue({ data: { claims: CLAIMS }, error: null })
const listFactors = vi.fn().mockResolvedValue({
data: { phone: [{ id: 'p1', status: 'verified', factor_type: 'phone' }] },
error: null,
})
useSupabase({ getClaims, mfa: { listFactors } })
const result = await requireAuth()
expect(result.error?.status).toBe(403)
})
it('treats a session whose verified claims carry no aal as not assured', async () => {
const { aal: _aal, ...claims } = CLAIMS
const getClaims = vi.fn().mockResolvedValue({ data: { claims }, error: null })
const listFactors = vi.fn().mockResolvedValue(factorList(VERIFIED_TOTP))
useSupabase({ getClaims, mfa: { listFactors } })
const result = await requireAuth()
expect(result.error?.status).toBe(403)
})
it('fails closed when listFactors returns an error', async () => {
const getClaims = vi.fn().mockResolvedValue({ data: { claims: CLAIMS }, error: null })
const listFactors = vi.fn().mockResolvedValue({
data: null,
error: { name: 'AuthApiError', message: 'upstream unavailable' },
})
useSupabase({ getClaims, mfa: { listFactors } })
const result = await requireAuth()
expect(result.error?.status).toBe(403)
})
it('fails closed when listFactors throws', async () => {
const getClaims = vi.fn().mockResolvedValue({ data: { claims: CLAIMS }, error: null })
const listFactors = vi.fn().mockRejectedValue(new Error('network down'))
useSupabase({ getClaims, mfa: { listFactors } })
const result = await requireAuth()
expect(result.error?.status).toBe(403)
})
it('fails closed when the client exposes no mfa API at all', async () => {
const getClaims = vi.fn().mockResolvedValue({ data: { claims: CLAIMS }, error: null })
useSupabase({ getClaims })
const result = await requireAuth()
expect(result.error?.status).toBe(403)
})
it('asks listFactors on the getUser fallback path and refuses a verified factor', async () => {
// No verified claims exist here (getClaims failed), so the level is
// unknown: a verified factor means the session must be refused.
const getClaims = vi.fn().mockRejectedValue(new Error('jwks fetch failed'))
const getUser = vi.fn().mockResolvedValue({ data: { user: MOCK_USER }, error: null })
const listFactors = vi.fn().mockResolvedValue(factorList(VERIFIED_TOTP))
useSupabase({ getClaims, getUser, mfa: { listFactors } })
const result = await requireAuth()
expect(result.error?.status).toBe(403)
expect(listFactors).toHaveBeenCalledTimes(1)
})
it('passes a factor-less user on the getUser fallback path', async () => {
const getUser = vi.fn().mockResolvedValue({ data: { user: MOCK_USER }, error: null })
const listFactors = vi.fn().mockResolvedValue(factorList())
useSupabase({ getUser, mfa: { listFactors } })
const result = await requireAuth()
expect(result.error).toBeNull()
expect(result.user?.id).toBe('user-1')
expect(listFactors).toHaveBeenCalledTimes(1)
})
it('skips the MFA check for bankid_linked users', async () => {
const claims = { ...CLAIMS, app_metadata: { provider: 'email', bankid_linked: true } }
const getClaims = vi.fn().mockResolvedValue({ data: { claims }, error: null })
const listFactors = vi.fn()
useSupabase({ getClaims, mfa: { listFactors } })
const result = await requireAuth()
expect(result.error).toBeNull()
expect(result.user?.id).toBe('user-1')
expect(listFactors).not.toHaveBeenCalled()
})
})
})
-198
View File
@@ -1,198 +0,0 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { createMockSupabase } from '@/tests/helpers'
vi.mock('@/lib/company/context', () => ({
getActiveCompanyId: vi.fn(),
}))
import { requireWritePermission, getCompanyRole } from '../require-write'
import { getActiveCompanyId } from '@/lib/company/context'
describe('requireWritePermission', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('returns ok for owner', async () => {
const { supabase, mockResult } = createMockSupabase()
vi.mocked(getActiveCompanyId).mockResolvedValue('company-1')
mockResult({ data: { role: 'owner' } })
const result = await requireWritePermission(supabase, 'user-1')
expect(result.ok).toBe(true)
})
it('returns ok for admin', async () => {
const { supabase, mockResult } = createMockSupabase()
vi.mocked(getActiveCompanyId).mockResolvedValue('company-1')
mockResult({ data: { role: 'admin' } })
const result = await requireWritePermission(supabase, 'user-1')
expect(result.ok).toBe(true)
})
it('returns ok for member', async () => {
const { supabase, mockResult } = createMockSupabase()
vi.mocked(getActiveCompanyId).mockResolvedValue('company-1')
mockResult({ data: { role: 'member' } })
const result = await requireWritePermission(supabase, 'user-1')
expect(result.ok).toBe(true)
})
it('returns 403 for viewer', async () => {
const { supabase, mockResult } = createMockSupabase()
vi.mocked(getActiveCompanyId).mockResolvedValue('company-1')
mockResult({ data: { role: 'viewer' } })
const result = await requireWritePermission(supabase, 'user-1')
expect(result.ok).toBe(false)
if (!result.ok) {
expect(result.response.status).toBe(403)
const body = await result.response.json()
expect(body.error).toContain('läsbehörighet')
}
})
it('returns 403 when user has no membership', async () => {
const { supabase, mockResult } = createMockSupabase()
vi.mocked(getActiveCompanyId).mockResolvedValue('company-1')
mockResult({ data: null })
const result = await requireWritePermission(supabase, 'user-1')
expect(result.ok).toBe(false)
if (!result.ok) {
expect(result.response.status).toBe(403)
}
})
it('returns 403 when there is no active company', async () => {
const { supabase } = createMockSupabase()
vi.mocked(getActiveCompanyId).mockResolvedValue(null)
const result = await requireWritePermission(supabase, 'user-1')
expect(result.ok).toBe(false)
if (!result.ok) {
expect(result.response.status).toBe(403)
const body = await result.response.json()
expect(body.error).toContain('aktivt företag')
}
})
})
describe('requireWritePermission with a known route context', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('skips the active-company resolution when companyId is known', async () => {
const { supabase, mockResult } = createMockSupabase()
mockResult({ data: { role: 'member' } })
const result = await requireWritePermission(supabase, 'user-1', { companyId: 'company-9' })
expect(result.ok).toBe(true)
expect(getActiveCompanyId).not.toHaveBeenCalled()
expect(supabase.from).toHaveBeenCalledTimes(1)
expect(supabase.from).toHaveBeenCalledWith('company_members')
})
it('skips the membership select when the role is known too', async () => {
const { supabase } = createMockSupabase()
const result = await requireWritePermission(supabase, 'user-1', {
companyId: 'company-9',
role: 'admin',
})
expect(result.ok).toBe(true)
expect(getActiveCompanyId).not.toHaveBeenCalled()
expect(supabase.from).not.toHaveBeenCalled()
})
it('still rejects a known viewer role with 403', async () => {
const { supabase } = createMockSupabase()
const result = await requireWritePermission(supabase, 'user-1', {
companyId: 'company-9',
role: 'viewer',
})
expect(result.ok).toBe(false)
if (!result.ok) expect(result.response.status).toBe(403)
expect(supabase.from).not.toHaveBeenCalled()
})
it('a known company with no membership row is rejected, not trusted', async () => {
const { supabase, mockResult } = createMockSupabase()
mockResult({ data: null })
const result = await requireWritePermission(supabase, 'user-1', { companyId: 'company-9' })
expect(result.ok).toBe(false)
if (!result.ok) expect(result.response.status).toBe(403)
})
it('falls back to resolution when no context is passed (legacy callers)', async () => {
const { supabase, mockResult } = createMockSupabase()
vi.mocked(getActiveCompanyId).mockResolvedValue('company-1')
mockResult({ data: { role: 'owner' } })
const result = await requireWritePermission(supabase, 'user-1', undefined)
expect(result.ok).toBe(true)
expect(getActiveCompanyId).toHaveBeenCalledTimes(1)
})
})
describe('getCompanyRole', () => {
beforeEach(() => {
vi.clearAllMocks()
})
it('returns role and companyId for owner', async () => {
const { supabase, mockResult } = createMockSupabase()
vi.mocked(getActiveCompanyId).mockResolvedValue('company-1')
mockResult({ data: { role: 'owner' } })
const result = await getCompanyRole(supabase, 'user-1')
expect(result.ok).toBe(true)
if (result.ok) {
expect(result.role).toBe('owner')
expect(result.companyId).toBe('company-1')
}
})
it('returns role for viewer (does not block)', async () => {
const { supabase, mockResult } = createMockSupabase()
vi.mocked(getActiveCompanyId).mockResolvedValue('company-1')
mockResult({ data: { role: 'viewer' } })
const result = await getCompanyRole(supabase, 'user-1')
expect(result.ok).toBe(true)
if (result.ok) {
expect(result.role).toBe('viewer')
expect(result.companyId).toBe('company-1')
}
})
it('returns 403 when user has no membership', async () => {
const { supabase, mockResult } = createMockSupabase()
vi.mocked(getActiveCompanyId).mockResolvedValue('company-1')
mockResult({ data: null })
const result = await getCompanyRole(supabase, 'user-1')
expect(result.ok).toBe(false)
if (!result.ok) {
expect(result.response.status).toBe(403)
}
})
it('returns 403 when there is no active company', async () => {
const { supabase } = createMockSupabase()
vi.mocked(getActiveCompanyId).mockResolvedValue(null)
const result = await getCompanyRole(supabase, 'user-1')
expect(result.ok).toBe(false)
if (!result.ok) {
expect(result.response.status).toBe(403)
const body = await result.response.json()
expect(body.error).toContain('aktivt företag')
}
})
})
-85
View File
@@ -1,85 +0,0 @@
import { describe, it, expect } from 'vitest'
import { safeReturnTo } from '../safe-return-to'
describe('safeReturnTo', () => {
it('returns the value when it is a same-origin relative path', () => {
expect(safeReturnTo('/settings/account', '/')).toBe('/settings/account')
expect(safeReturnTo('/invoices/new', '/')).toBe('/invoices/new')
})
it('preserves search and hash', () => {
expect(safeReturnTo('/invoices?status=overdue', '/')).toBe('/invoices?status=overdue')
expect(safeReturnTo('/settings/account#mfa', '/')).toBe('/settings/account#mfa')
})
it('returns the fallback for missing or empty values', () => {
expect(safeReturnTo(null, '/home')).toBe('/home')
expect(safeReturnTo(undefined, '/home')).toBe('/home')
expect(safeReturnTo('', '/home')).toBe('/home')
})
it('rejects absolute URLs', () => {
expect(safeReturnTo('https://evil.com/path', '/')).toBe('/')
expect(safeReturnTo('http://evil.com', '/')).toBe('/')
})
it('rejects protocol-relative URLs', () => {
expect(safeReturnTo('//evil.com/path', '/')).toBe('/')
})
it('rejects the /\\evil.com browser-quirk form', () => {
expect(safeReturnTo('/\\evil.com', '/')).toBe('/')
})
it('rejects the /@user@host form some clients resolve off-origin', () => {
expect(safeReturnTo('/@evil.com', '/')).toBe('/')
})
it('rejects values that do not start with /', () => {
expect(safeReturnTo('settings', '/')).toBe('/')
expect(safeReturnTo('javascript:alert(1)', '/')).toBe('/')
})
it('rejects dot segments that normalise into a protocol-relative URL', () => {
// The raw input starts with a single '/', so the prefix guards let it
// through, and it resolves against the sentinel origin, so the origin
// check lets it through too. But URL normalisation collapses it to
// '//evil.com', which navigates off-origin the moment a caller uses it
// as a bare href (window.location.assign / router.push).
expect(safeReturnTo('/..//evil.com', '/')).toBe('/')
expect(safeReturnTo('/.//evil.com', '/')).toBe('/')
expect(safeReturnTo('/a/../..//evil.com', '/')).toBe('/')
expect(safeReturnTo('/../\\evil.com', '/')).toBe('/')
expect(safeReturnTo('/..//evil.com?x=1', '/')).toBe('/')
})
it('rejects the percent-encoded spelling of those dot segments', () => {
expect(safeReturnTo('/%2e%2e//evil.com', '/')).toBe('/')
expect(safeReturnTo('/%2E%2E//evil.com', '/')).toBe('/')
})
it('rejects dot segments that normalise into the /@ form', () => {
// The raw-input rule rejects '/@evil.com' outright, but dot-segment
// resolution can smuggle it past that guard: '/a/../@evil.com' starts
// with an innocent '/a' yet normalises to '/@evil.com'. The
// post-normalisation check must reject every prefix the raw check does.
expect(safeReturnTo('/a/../@evil.com', '/')).toBe('/')
expect(safeReturnTo('/.//@evil.com', '/')).toBe('/')
expect(safeReturnTo('/%2e%2e/@evil.com', '/')).toBe('/')
expect(safeReturnTo('/a/../@evil.com?x=1', '/')).toBe('/')
})
it('still allows ordinary dot segments that stay on-origin', () => {
expect(safeReturnTo('/settings/../invoices', '/')).toBe('/invoices')
expect(safeReturnTo('/./settings/tax', '/')).toBe('/settings/tax')
})
it('keeps percent-encoded slashes, which are path data and stay on-origin', () => {
expect(safeReturnTo('/%2F%2Fevil.com', '/')).toBe('/%2F%2Fevil.com')
})
it('rejects data: URIs', () => {
expect(safeReturnTo('data:text/html,<script>alert(1)</script>', '/')).toBe('/')
expect(safeReturnTo('data:,', '/')).toBe('/')
})
})
-99
View File
@@ -1,99 +0,0 @@
import { describe, expect, it } from 'vitest'
import {
ALL_SCOPES,
API_KEY_SCOPES,
SCOPE_GROUPS,
TOOL_COUNT_BY_SCOPE,
TOOL_SCOPE_MAP,
scopeKind,
type ApiKeyScope,
} from '../scope-catalog'
import * as apiKeys from '../api-keys'
describe('SCOPE_GROUPS', () => {
it('covers every scope in API_KEY_SCOPES exactly once', () => {
const occurrences = new Map<ApiKeyScope, number>()
for (const group of SCOPE_GROUPS) {
for (const scope of group.scopes) {
occurrences.set(scope, (occurrences.get(scope) ?? 0) + 1)
}
}
const missing = ALL_SCOPES.filter((s) => !occurrences.has(s))
const duplicated = [...occurrences].filter(([, n]) => n > 1).map(([s]) => s)
expect(missing).toEqual([])
expect(duplicated).toEqual([])
})
it('only references scopes that exist in the catalogue', () => {
for (const group of SCOPE_GROUPS) {
for (const scope of group.scopes) {
expect(scope in API_KEY_SCOPES).toBe(true)
}
}
})
it('has unique domains and lists the read scope first', () => {
const domains = SCOPE_GROUPS.map((g) => g.domain)
expect(new Set(domains).size).toBe(domains.length)
for (const group of SCOPE_GROUPS) {
const readIndex = group.scopes.findIndex((s) => scopeKind(s) === 'read')
if (readIndex !== -1) expect(readIndex).toBe(0)
}
})
})
describe('TOOL_COUNT_BY_SCOPE', () => {
it('has an entry for every scope and none for anything else', () => {
expect(Object.keys(TOOL_COUNT_BY_SCOPE).sort()).toEqual([...ALL_SCOPES].sort())
})
it('equals the number of TOOL_SCOPE_MAP entries mapped to each scope', () => {
for (const scope of ALL_SCOPES) {
const expected = Object.values(TOOL_SCOPE_MAP).filter((s) => s === scope).length
expect(TOOL_COUNT_BY_SCOPE[scope], scope).toBe(expected)
}
const total = Object.values(TOOL_COUNT_BY_SCOPE).reduce((a, b) => a + b, 0)
expect(total).toBe(Object.keys(TOOL_SCOPE_MAP).length)
})
it('only maps tools to scopes that exist', () => {
for (const [tool, scope] of Object.entries(TOOL_SCOPE_MAP)) {
expect(scope in API_KEY_SCOPES, tool).toBe(true)
}
})
})
describe('API_KEY_SCOPES labels', () => {
it('carries no hand-written tool counts (they are derived)', () => {
for (const [scope, meta] of Object.entries(API_KEY_SCOPES)) {
expect(meta.description, scope).not.toMatch(/\(\d+ verktyg\)/)
expect(meta.label, scope).not.toMatch(/\(\d+ verktyg\)/)
}
})
it('formats every label as "Område: verb"', () => {
for (const meta of Object.values(API_KEY_SCOPES)) {
expect(meta.label).toMatch(/^[^:]+: .+$/)
}
})
})
describe('scopeKind', () => {
it('treats :read as read and everything else as an elevated grant', () => {
expect(scopeKind('transactions:read')).toBe('read')
expect(scopeKind('transactions:write')).toBe('write')
expect(scopeKind('webhooks:manage')).toBe('write')
expect(scopeKind('pending_operations:approve')).toBe('write')
expect(scopeKind('reconciliation:signoff')).toBe('write')
})
})
describe('api-keys re-exports', () => {
it('exposes the same catalogue objects so server imports keep working', () => {
expect(apiKeys.API_KEY_SCOPES).toBe(API_KEY_SCOPES)
expect(apiKeys.SCOPE_GROUPS).toBe(SCOPE_GROUPS)
expect(apiKeys.TOOL_SCOPE_MAP).toBe(TOOL_SCOPE_MAP)
expect(apiKeys.TOOL_COUNT_BY_SCOPE).toBe(TOOL_COUNT_BY_SCOPE)
expect(apiKeys.ALL_SCOPES).toBe(ALL_SCOPES)
})
})
-47
View File
@@ -1,47 +0,0 @@
import { describe, expect, it } from 'vitest'
import { resolveRequiredScope } from '../scopes'
describe('resolveRequiredScope', () => {
it('returns public for the health endpoint', () => {
expect(resolveRequiredScope('GET', '/api/v1/health')).toBe('public')
})
it('returns public for openapi.json', () => {
expect(resolveRequiredScope('GET', '/api/v1/openapi.json')).toBe('public')
})
it('resolves the companies:read scope for GET /api/v1/companies', () => {
expect(resolveRequiredScope('GET', '/api/v1/companies')).toBe('companies:read')
})
it('resolves :param patterns to a single scope', () => {
expect(
resolveRequiredScope(
'GET',
'/api/v1/companies/8fd5b1f4-1111-2222-3333-444455556666/customers/0b6c7d8e-1111-2222-3333-444455556666',
),
).toBe('customers:read')
})
it('resolves the inbox-items stamp verb (previously unregistered: 404 with a valid key)', () => {
expect(
resolveRequiredScope(
'POST',
'/api/v1/companies/8fd5b1f4-1111-2222-3333-444455556666/inbox-items/0b6c7d8e-1111-2222-3333-444455556666/stamp',
),
).toBe('documents:write')
})
it('returns null for unknown paths', () => {
expect(resolveRequiredScope('GET', '/api/v1/non-existent')).toBeNull()
})
it('does not match the wrong HTTP method', () => {
expect(resolveRequiredScope('DELETE', '/api/v1/companies')).toBeNull()
})
it('does not let :param greedily consume slashes', () => {
// /companies/{companyId} should not match /companies/abc/extra
expect(resolveRequiredScope('GET', '/api/v1/companies/abc/extra')).toBeNull()
})
})
@@ -1,71 +0,0 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
import {
notifySessionExpired,
SESSION_TIMEOUT_CHANNEL,
SESSION_TIMEOUT_REASON_HEADER,
} from '../session-timeout-shared'
const posted: Array<{ name: string; message: unknown }> = []
class FakeBroadcastChannel {
constructor(public readonly name: string) {}
postMessage(message: unknown) {
posted.push({ name: this.name, message })
}
close() {}
}
function expiredResponse(reason: string, status = 401): Response {
return new Response(
JSON.stringify({ error: { code: 'SESSION_EXPIRED', message: 'Sessionen har upphört.' } }),
{ status, headers: { [SESSION_TIMEOUT_REASON_HEADER]: reason } },
)
}
describe('notifySessionExpired', () => {
beforeEach(() => {
posted.length = 0
vi.stubGlobal('BroadcastChannel', FakeBroadcastChannel)
})
afterEach(() => {
vi.unstubAllGlobals()
})
it('announces an idle timeout on the session channel', () => {
expect(notifySessionExpired(expiredResponse('idle'))).toBe(true)
expect(posted).toEqual([
{ name: SESSION_TIMEOUT_CHANNEL, message: { type: 'expired', reason: 'idle' } },
])
})
it('announces an absolute timeout on the session channel', () => {
expect(notifySessionExpired(expiredResponse('absolute'))).toBe(true)
expect(posted).toEqual([
{ name: SESSION_TIMEOUT_CHANNEL, message: { type: 'expired', reason: 'absolute' } },
])
})
// A 401 from a route's own auth check is not a timeout: signing the user out
// and redirecting on one would turn a single failed call into a logout.
it('ignores a 401 that carries no timeout reason', () => {
expect(notifySessionExpired(new Response('{}', { status: 401 }))).toBe(false)
expect(posted).toEqual([])
})
it('ignores an unknown reason', () => {
expect(notifySessionExpired(expiredResponse('whatever'))).toBe(false)
expect(posted).toEqual([])
})
it('ignores a successful response that happens to carry the header', () => {
expect(notifySessionExpired(expiredResponse('idle', 200))).toBe(false)
expect(posted).toEqual([])
})
it('still reports the timeout where BroadcastChannel is unavailable', () => {
vi.stubGlobal('BroadcastChannel', undefined)
expect(notifySessionExpired(expiredResponse('idle'))).toBe(true)
expect(posted).toEqual([])
})
})
-330
View File
@@ -1,330 +0,0 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import {
apiRequestSkipsSessionTimeout,
createSessionTimeoutState,
evaluateSessionTimeout,
fetchAutoLogoutPreference,
getSessionTimeoutConfig,
sessionStateMatchesUser,
sessionStateNeedsRemint,
signSessionTimeoutState,
toSessionTimeoutClientState,
verifySessionTimeoutState,
} from '../session-timeout'
const SIGNING_ENV = { SESSION_TIMEOUT_SECRET: 'test-session-timeout-secret' }
describe('session timeout configuration', () => {
afterEach(() => vi.unstubAllEnvs())
it('uses banking-style defaults for hosted deployments', () => {
expect(getSessionTimeoutConfig({})).toEqual({
enabled: true,
idleTimeoutMs: 30 * 60 * 1000,
absoluteTimeoutMs: 12 * 60 * 60 * 1000,
warningMs: 2 * 60 * 1000,
enforceForAll: false,
})
})
it('is disabled by default for self-hosted deployments', () => {
expect(getSessionTimeoutConfig({ NEXT_PUBLIC_SELF_HOSTED: 'true' })).toEqual({
enabled: false,
idleTimeoutMs: 0,
absoluteTimeoutMs: 0,
warningMs: 0,
enforceForAll: false,
})
})
it('allows self-hosted deployments to opt in and bounds the warning', () => {
expect(getSessionTimeoutConfig({
NEXT_PUBLIC_SELF_HOSTED: 'true',
NEXT_PUBLIC_SESSION_IDLE_TIMEOUT_MS: '60000',
NEXT_PUBLIC_SESSION_WARNING_MS: '120000',
})).toEqual({
enabled: true,
idleTimeoutMs: 60000,
absoluteTimeoutMs: 0,
warningMs: 60000,
enforceForAll: false,
})
})
it('warns when only the absolute limit is enabled', () => {
expect(getSessionTimeoutConfig({
NEXT_PUBLIC_SELF_HOSTED: 'true',
NEXT_PUBLIC_SESSION_ABSOLUTE_TIMEOUT_MS: '60000',
NEXT_PUBLIC_SESSION_WARNING_MS: '10000',
})).toEqual({
enabled: true,
idleTimeoutMs: 0,
absoluteTimeoutMs: 60000,
warningMs: 10000,
enforceForAll: false,
})
})
it('reads the force-all override', () => {
expect(getSessionTimeoutConfig({
NEXT_PUBLIC_SESSION_TIMEOUT_FORCE_ALL: 'true',
})).toMatchObject({ enforceForAll: true })
})
it('ignores negative and non-integer overrides', () => {
expect(getSessionTimeoutConfig({
NEXT_PUBLIC_SESSION_IDLE_TIMEOUT_MS: '-1',
NEXT_PUBLIC_SESSION_ABSOLUTE_TIMEOUT_MS: '12.5',
})).toMatchObject({
idleTimeoutMs: 30 * 60 * 1000,
absoluteTimeoutMs: 12 * 60 * 60 * 1000,
})
})
})
describe('signed session timeout state', () => {
it('round-trips an authentic state', async () => {
const state = createSessionTimeoutState({
userId: 'user-1',
sessionId: 'session-1',
method: 'bankid',
autoLogout: true,
now: 1000,
})
const signed = await signSessionTimeoutState(state, SIGNING_ENV)
expect(signed).not.toBeNull()
await expect(verifySessionTimeoutState(signed!, SIGNING_ENV)).resolves.toEqual(state)
})
it('returns null instead of throwing when no signing secret is configured', async () => {
const state = createSessionTimeoutState({
userId: 'user-1',
sessionId: 'session-1',
method: 'password',
autoLogout: true,
now: 1000,
})
await expect(signSessionTimeoutState(state, {})).resolves.toBeNull()
})
it('rejects payload and signature tampering', async () => {
const state = createSessionTimeoutState({
userId: 'user-1',
sessionId: 'session-1',
method: 'password',
autoLogout: true,
now: 1000,
})
const signed = await signSessionTimeoutState(state, SIGNING_ENV)
const [payload, signature] = signed!.split('.')
await expect(
verifySessionTimeoutState(`${payload}x.${signature}`, SIGNING_ENV),
).resolves.toBeNull()
await expect(
verifySessionTimeoutState(`${payload}.${signature.slice(0, -1)}x`, SIGNING_ENV),
).resolves.toBeNull()
})
it('binds state to both the user and Supabase session', () => {
const state = createSessionTimeoutState({
userId: 'user-1',
sessionId: 'session-1',
method: 'password',
autoLogout: true,
now: 1000,
})
expect(sessionStateMatchesUser(state, 'user-1', 'session-1')).toBe(true)
expect(sessionStateMatchesUser(state, 'user-2', 'session-1')).toBe(false)
expect(sessionStateMatchesUser(state, 'user-1', 'session-2')).toBe(false)
})
it('treats an unresolved current session id as a mismatch for bound state', () => {
const bound = createSessionTimeoutState({
userId: 'user-1',
sessionId: 'session-1',
method: 'password',
autoLogout: true,
now: 1000,
})
const unbound = createSessionTimeoutState({
userId: 'user-1',
sessionId: null,
method: 'password',
autoLogout: true,
now: 1000,
})
expect(sessionStateMatchesUser(bound, 'user-1', null)).toBe(false)
expect(sessionStateMatchesUser(unbound, 'user-1', null)).toBe(true)
expect(sessionStateMatchesUser(unbound, 'user-1', 'session-2')).toBe(true)
})
})
describe('session expiry', () => {
const config = {
enabled: true,
idleTimeoutMs: 30_000,
absoluteTimeoutMs: 60_000,
warningMs: 10_000,
enforceForAll: false,
}
it('uses inclusive boundaries and gives absolute expiry precedence', () => {
const state = {
...createSessionTimeoutState({
userId: 'user-1',
sessionId: 'session-1',
method: 'password' as const,
autoLogout: true,
now: 1000,
}),
lastActivityAt: 31_000,
}
expect(evaluateSessionTimeout(state, config, 60_999)).toBeNull()
expect(evaluateSessionTimeout(state, config, 61_000)).toBe('absolute')
})
it('expires an otherwise valid session after the idle limit', () => {
const state = createSessionTimeoutState({
userId: 'user-1',
sessionId: null,
method: 'password',
autoLogout: true,
now: 1000,
})
expect(evaluateSessionTimeout(state, config, 30_999)).toBeNull()
expect(evaluateSessionTimeout(state, config, 31_000)).toBe('idle')
})
})
describe('per-user opt-in gating', () => {
const config = {
enabled: true,
idleTimeoutMs: 30_000,
absoluteTimeoutMs: 60_000,
warningMs: 10_000,
enforceForAll: false,
}
function makeState(autoLogout: boolean) {
return createSessionTimeoutState({
userId: 'user-1',
sessionId: null,
method: 'password' as const,
autoLogout,
now: 1000,
})
}
it('never expires a session that has not opted in', () => {
const state = makeState(false)
// Far past both limits: still no timeout without the opt-in.
expect(evaluateSessionTimeout(state, config, 10_000_000)).toBeNull()
})
it('expires an opted-in session normally', () => {
const state = makeState(true)
expect(evaluateSessionTimeout(state, config, 61_000)).toBe('absolute')
})
it('lets enforceForAll override the opt-out', () => {
const state = makeState(false)
expect(
evaluateSessionTimeout(state, { ...config, enforceForAll: true }, 61_000),
).toBe('absolute')
})
it('treats a pre-toggle state as authentic but needing a re-mint', async () => {
const legacy = makeState(true) as { autoLogout?: boolean }
delete legacy.autoLogout
const state = legacy as ReturnType<typeof makeState>
const signed = await signSessionTimeoutState(state, SIGNING_ENV)
await expect(verifySessionTimeoutState(signed!, SIGNING_ENV)).resolves.toEqual(state)
expect(sessionStateNeedsRemint(state)).toBe(true)
expect(sessionStateNeedsRemint(makeState(false))).toBe(false)
// A legacy state is never enforced against until it has been re-minted.
expect(evaluateSessionTimeout(state, config, 10_000_000)).toBeNull()
})
it('reports the client state as enabled only when enforced', () => {
expect(toSessionTimeoutClientState(makeState(true), config, 2000).enabled).toBe(true)
expect(toSessionTimeoutClientState(makeState(false), config, 2000).enabled).toBe(false)
expect(
toSessionTimeoutClientState(
makeState(false),
{ ...config, enforceForAll: true },
2000,
).enabled,
).toBe(true)
expect(
toSessionTimeoutClientState(
makeState(true),
{ ...config, enabled: false },
2000,
).enabled,
).toBe(false)
})
})
describe('fetchAutoLogoutPreference', () => {
function client(result: { data: unknown; error: unknown } | 'throw') {
return {
from: () => ({
select: () => ({
eq: () => ({
maybeSingle: async () => {
if (result === 'throw') throw new Error('network down')
return result
},
}),
}),
}),
} as unknown as Parameters<typeof fetchAutoLogoutPreference>[0]
}
it('returns the stored opt-in', async () => {
await expect(
fetchAutoLogoutPreference(client({ data: { auto_logout: true }, error: null }), 'u1'),
).resolves.toBe(true)
await expect(
fetchAutoLogoutPreference(client({ data: { auto_logout: false }, error: null }), 'u1'),
).resolves.toBe(false)
})
it('treats a missing row as a definitive opt-out', async () => {
await expect(
fetchAutoLogoutPreference(client({ data: null, error: null }), 'u1'),
).resolves.toBe(false)
})
it('returns null (unknown) on a failed read, never a fail-open false', async () => {
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
await expect(
fetchAutoLogoutPreference(client({ data: null, error: { message: 'boom' } }), 'u1'),
).resolves.toBeNull()
await expect(fetchAutoLogoutPreference(client('throw'), 'u1')).resolves.toBeNull()
expect(errorSpy).toHaveBeenCalled()
errorSpy.mockRestore()
})
})
describe('API exclusions', () => {
it('only lets bearer-authenticated machine surfaces bypass timeouts', () => {
expect(apiRequestSkipsSessionTimeout('/api/v1/companies/c1/invoices', true)).toBe(true)
expect(apiRequestSkipsSessionTimeout('/api/v1/companies/c1/invoices', false)).toBe(false)
expect(apiRequestSkipsSessionTimeout('/api/invoices', true)).toBe(false)
expect(apiRequestSkipsSessionTimeout('/api/mcp-oauth/token', false)).toBe(true)
expect(apiRequestSkipsSessionTimeout('/api/health', false)).toBe(true)
})
})
-141
View File
@@ -1,141 +0,0 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { readFileSync } from 'node:fs'
import path from 'node:path'
import { eventBus } from '@/lib/events/bus'
import {
captchaTokenOptions,
getTurnstileRolloutState,
isTurnstileSubmissionBlocked,
resolveTurnstileSiteKey,
} from '../turnstile'
const readRepoFile = (file: string) =>
readFileSync(path.join(process.cwd(), file), 'utf8')
beforeEach(() => {
vi.clearAllMocks()
eventBus.clear()
})
afterEach(() => {
vi.unstubAllEnvs()
})
describe('Turnstile rollout state', () => {
it('keeps Auth available while the public site key is absent', () => {
expect(resolveTurnstileSiteKey(undefined)).toBeNull()
expect(resolveTurnstileSiteKey('')).toBeNull()
expect(resolveTurnstileSiteKey(' ')).toBeNull()
expect(getTurnstileRolloutState(undefined)).toBe('disabled')
expect(isTurnstileSubmissionBlocked(null, undefined)).toBe(false)
})
it('treats an unsubstituted Docker sentinel as disabled', () => {
const sentinel = '__NEXT_PUBLIC_TURNSTILE_SITE_KEY__'
expect(resolveTurnstileSiteKey(sentinel)).toBeNull()
expect(getTurnstileRolloutState(sentinel)).toBe('disabled')
expect(isTurnstileSubmissionBlocked(null, sentinel)).toBe(false)
})
it('fails closed after the client site key is configured', () => {
const siteKey = ' public-site-key '
expect(resolveTurnstileSiteKey(siteKey)).toBe('public-site-key')
expect(getTurnstileRolloutState(siteKey)).toBe('client-enabled')
expect(isTurnstileSubmissionBlocked(null, siteKey)).toBe(true)
expect(isTurnstileSubmissionBlocked('', siteKey)).toBe(true)
expect(isTurnstileSubmissionBlocked('verified-token', siteKey)).toBe(false)
})
it('reads the runtime-substituted environment value at call time', () => {
vi.stubEnv('NEXT_PUBLIC_TURNSTILE_SITE_KEY', '')
expect(getTurnstileRolloutState()).toBe('disabled')
vi.stubEnv('NEXT_PUBLIC_TURNSTILE_SITE_KEY', 'runtime-site-key')
expect(getTurnstileRolloutState()).toBe('client-enabled')
})
it('forwards only a non-empty token to Supabase Auth', () => {
expect(captchaTokenOptions(null)).toEqual({})
expect(captchaTokenOptions(undefined)).toEqual({})
expect(captchaTokenOptions(' ')).toEqual({})
expect(captchaTokenOptions(' token-value ')).toEqual({
captchaToken: 'token-value',
})
})
})
describe('Turnstile integration contract', () => {
it('protects every public Supabase Auth flow in scope', () => {
const login = readRepoFile('app/(auth)/login/login-client.tsx')
const register = readRepoFile('app/(auth)/register/register-client.tsx')
const sandbox = readRepoFile('app/sandbox/page.tsx')
expect(login).toMatch(
/signInWithPassword\([\s\S]*?options: captchaTokenOptions\(passwordCaptchaToken\)/,
)
// The reset flow moved server-side (brands-table host resolution,
// 2026-09-07): the captcha token must travel to
// POST /api/auth/password-reset, and that route must forward it into
// the GoTrue resetPasswordForEmail call.
expect(login).toMatch(
/fetch\('\/api\/auth\/password-reset'[\s\S]*?captchaTokenOptions\(resetCaptchaToken\)/,
)
const resetRoute = readRepoFile('app/api/auth/password-reset/route.ts')
expect(resetRoute).toMatch(/resetPasswordForEmail\([\s\S]*?captchaToken/)
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(
/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\)/,
)
expect(sandbox).toContain('action="accounted_sandbox"')
})
it('keeps the public key, CSP, and Docker runtime contract in sync', () => {
const envExample = readRepoFile('.env.example')
const dockerEnvExample = readRepoFile('.env.docker.example')
const dockerfile = readRepoFile('Dockerfile')
const entrypoint = readRepoFile('docker-entrypoint.sh')
const nextConfig = readRepoFile('next.config.ts')
expect(envExample).toContain('NEXT_PUBLIC_TURNSTILE_SITE_KEY=')
expect(dockerEnvExample).toContain('NEXT_PUBLIC_TURNSTILE_SITE_KEY=')
expect(dockerfile).toContain(
'NEXT_PUBLIC_TURNSTILE_SITE_KEY=__NEXT_PUBLIC_TURNSTILE_SITE_KEY__',
)
expect(entrypoint).toContain('__NEXT_PUBLIC_TURNSTILE_SITE_KEY__')
expect(nextConfig).toContain('https://challenges.cloudflare.com')
expect(nextConfig).toMatch(/script-src[\s\S]*?turnstileOrigin/)
expect(nextConfig).toMatch(/frame-src[\s\S]*?turnstileOrigin/)
expect(envExample).not.toContain('TURNSTILE_SECRET_KEY')
expect(dockerEnvExample).not.toContain('TURNSTILE_SECRET_KEY')
})
it('ships matching Swedish and English challenge messages', () => {
const swedish = JSON.parse(readRepoFile('messages/sv.json')).auth
const english = JSON.parse(readRepoFile('messages/en.json')).auth
const keys = [
'turnstile_checking',
'turnstile_required',
'turnstile_error',
]
for (const key of keys) {
expect(swedish[key]).toBeTypeOf('string')
expect(swedish[key]).not.toBe('')
expect(english[key]).toBeTypeOf('string')
expect(english[key]).not.toBe('')
}
})
})
@@ -1,266 +0,0 @@
import { randomUUID } from 'node:crypto'
import { describe, expect, it } from 'vitest'
import { getPool } from '@/tests/pg/setup'
import { insertAuthUser } from '@/tests/pg/fixtures'
// on_auth_user_email_updated_unlink_old_identities
// (20260903110000_unlink_old_address_identities_on_email_change.sql): when
// auth.users.email changes, social identities bound to the OLD address are
// removed, app_metadata.providers is recomputed, an email identity for the
// new address is guaranteed, and the removal is written to GoTrue's audit
// table. Everything else on the account (email identity, social identities
// on other addresses) stays.
async function insertIdentity(params: {
userId: string
provider: string
email: string
providerId?: string
}): Promise<string> {
const id = randomUUID()
await getPool().query(
`INSERT INTO auth.identities
(id, user_id, provider, provider_id, identity_data, created_at, updated_at, last_sign_in_at)
VALUES ($1, $2, $3, $4, $5::jsonb, now(), now(), now())`,
[
id,
params.userId,
params.provider,
params.providerId ?? (params.provider === 'email' ? params.userId : randomUUID()),
JSON.stringify({ sub: params.providerId ?? params.userId, email: params.email }),
],
)
return id
}
async function setProviders(userId: string, providers: string[]): Promise<void> {
await getPool().query(
`UPDATE auth.users
SET raw_app_meta_data = jsonb_build_object('provider', $2::text, 'providers', $3::jsonb)
WHERE id = $1`,
[userId, providers[0] ?? 'email', JSON.stringify(providers)],
)
}
// Mirrors GoTrue's ConfirmEmailChange: the pending address becomes the
// address and the pending column is cleared in the same statement.
async function confirmEmailChange(userId: string, email: string): Promise<void> {
await getPool().query(`UPDATE auth.users SET email_change = $2 WHERE id = $1`, [userId, email])
await getPool().query(
`UPDATE auth.users SET email = $2, email_change = '' WHERE id = $1`,
[userId, email],
)
}
// An admin-side or SQL change: no pending address involved.
async function adminSetEmail(userId: string, email: string): Promise<void> {
await getPool().query(`UPDATE auth.users SET email = $2 WHERE id = $1`, [userId, email])
}
async function identities(userId: string): Promise<Array<{ provider: string; email: string }>> {
const { rows } = await getPool().query<{ provider: string; email: string }>(
`SELECT provider, lower(identity_data->>'email') AS email
FROM auth.identities WHERE user_id = $1 ORDER BY provider, email`,
[userId],
)
return rows
}
async function emailIdentity(
userId: string,
): Promise<{ provider_id: string; identity_data: Record<string, unknown> } | undefined> {
const { rows } = await getPool().query<{
provider_id: string
identity_data: Record<string, unknown>
}>(`SELECT provider_id, identity_data FROM auth.identities WHERE user_id = $1 AND provider = 'email'`, [
userId,
])
return rows[0]
}
async function providers(userId: string): Promise<unknown> {
const { rows } = await getPool().query<{ providers: unknown }>(
`SELECT raw_app_meta_data->'providers' AS providers FROM auth.users WHERE id = $1`,
[userId],
)
return rows[0]!.providers
}
async function currentEmail(userId: string): Promise<string> {
const { rows } = await getPool().query<{ email: string }>(
`SELECT email FROM auth.users WHERE id = $1`,
[userId],
)
return rows[0]!.email
}
async function auditEntries(userId: string): Promise<Array<Record<string, unknown>>> {
const { rows } = await getPool().query<{ payload: Record<string, unknown> }>(
`SELECT payload FROM auth.audit_log_entries
WHERE payload->>'actor_id' = $1 AND payload->>'action' = 'identity_unlink'
ORDER BY created_at`,
[userId],
)
return rows.map((r) => r.payload)
}
describe('unlink old-address identities on auth email change', () => {
it('removes the social identity bound to the old address and keeps the rest', async () => {
const userId = await insertAuthUser()
const oldEmail = await currentEmail(userId)
const newEmail = `pg-real-new-${userId}@test.invalid`
await insertIdentity({ userId, provider: 'email', email: oldEmail })
await insertIdentity({ userId, provider: 'google', email: oldEmail })
await insertIdentity({ userId, provider: 'google', email: `other-${userId}@test.invalid` })
await setProviders(userId, ['email', 'google'])
await confirmEmailChange(userId, newEmail)
expect(await identities(userId)).toEqual([
{ provider: 'email', email: oldEmail },
{ provider: 'google', email: `other-${userId}@test.invalid` },
])
// Still has a google identity (the other address), so the list is unchanged.
expect(await providers(userId)).toEqual(['email', 'google'])
})
it('drops the provider from app_metadata when its last identity goes', async () => {
const userId = await insertAuthUser()
const oldEmail = await currentEmail(userId)
await insertIdentity({ userId, provider: 'email', email: oldEmail })
await insertIdentity({ userId, provider: 'google', email: oldEmail })
await setProviders(userId, ['email', 'google'])
await confirmEmailChange(userId, `pg-real-new-${userId}@test.invalid`)
expect(await identities(userId)).toEqual([{ provider: 'email', email: oldEmail }])
expect(await providers(userId)).toEqual(['email'])
})
it('gives a Google-only account a verified email identity after a confirmed change', async () => {
// Signed up with Google, never set a password: no 'email' identity.
// Removing the Google identity must not leave zero identities; the email
// identity is what Google with the new address links through and what
// password recovery resolves. Old address matched case-insensitively.
const userId = await insertAuthUser()
const oldEmail = await currentEmail(userId)
const newEmail = `pg-real-new-${userId}@test.invalid`
await insertIdentity({ userId, provider: 'google', email: oldEmail.toUpperCase() })
await setProviders(userId, ['google'])
await confirmEmailChange(userId, newEmail)
expect(await identities(userId)).toEqual([{ provider: 'email', email: newEmail }])
const created = await emailIdentity(userId)
expect(created?.provider_id).toBe(userId)
expect(created?.identity_data).toMatchObject({
sub: userId,
email: newEmail,
email_verified: true,
})
expect(await providers(userId)).toEqual(['email'])
})
it('creates the email identity unverified after an admin-side change', async () => {
// No pending address was confirmed by the user, so the trigger must not
// vouch for the new address.
const userId = await insertAuthUser()
const oldEmail = await currentEmail(userId)
const newEmail = `pg-real-new-${userId}@test.invalid`
await insertIdentity({ userId, provider: 'google', email: oldEmail })
await setProviders(userId, ['google'])
await adminSetEmail(userId, newEmail)
expect(await identities(userId)).toEqual([{ provider: 'email', email: newEmail }])
expect((await emailIdentity(userId))?.identity_data).toMatchObject({
email: newEmail,
email_verified: false,
})
})
it('does not create a second email identity when one already exists', async () => {
const userId = await insertAuthUser()
const oldEmail = await currentEmail(userId)
await insertIdentity({ userId, provider: 'email', email: oldEmail })
await insertIdentity({ userId, provider: 'google', email: oldEmail })
await confirmEmailChange(userId, `pg-real-new-${userId}@test.invalid`)
const { rows } = await getPool().query<{ n: number }>(
`SELECT count(*)::int AS n FROM auth.identities WHERE user_id = $1 AND provider = 'email'`,
[userId],
)
expect(rows[0]!.n).toBe(1)
})
it('never touches the email identity, even though it carries the old address', async () => {
// GoTrue moves the email identity itself as part of the change; the
// trigger must not race it by deleting the row.
const userId = await insertAuthUser()
const oldEmail = await currentEmail(userId)
await insertIdentity({ userId, provider: 'email', email: oldEmail })
await setProviders(userId, ['email'])
await confirmEmailChange(userId, `pg-real-new-${userId}@test.invalid`)
expect(await identities(userId)).toEqual([{ provider: 'email', email: oldEmail }])
expect(await providers(userId)).toEqual(['email'])
expect(await auditEntries(userId)).toEqual([])
})
it('leaves identities alone when the update does not change the email', async () => {
const userId = await insertAuthUser()
const oldEmail = await currentEmail(userId)
await insertIdentity({ userId, provider: 'google', email: oldEmail })
await setProviders(userId, ['google'])
await getPool().query(`UPDATE auth.users SET updated_at = now() WHERE id = $1`, [userId])
await adminSetEmail(userId, oldEmail)
expect(await identities(userId)).toEqual([{ provider: 'google', email: oldEmail }])
expect(await providers(userId)).toEqual(['google'])
})
it('does not touch other users with a social identity on the same address', async () => {
const a = await insertAuthUser()
const b = await insertAuthUser()
const shared = `shared-${a}@test.invalid`
await adminSetEmail(a, shared)
await insertIdentity({ userId: a, provider: 'google', email: shared })
await insertIdentity({ userId: b, provider: 'google', email: shared })
const newEmail = `pg-real-new-${a}@test.invalid`
await confirmEmailChange(a, newEmail)
// a lost its Google login and got an email identity for the new address.
expect(await identities(a)).toEqual([{ provider: 'email', email: newEmail }])
expect(await identities(b)).toEqual([{ provider: 'google', email: shared }])
})
it('writes an identity_unlink entry to the auth audit log', async () => {
const userId = await insertAuthUser()
const oldEmail = await currentEmail(userId)
const newEmail = `pg-real-new-${userId}@test.invalid`
await insertIdentity({ userId, provider: 'email', email: oldEmail })
await insertIdentity({ userId, provider: 'google', email: oldEmail })
await confirmEmailChange(userId, newEmail)
const entries = await auditEntries(userId)
expect(entries).toHaveLength(1)
expect(entries[0]).toMatchObject({
action: 'identity_unlink',
actor_id: userId,
actor_username: oldEmail,
log_type: 'user',
traits: {
reason: 'email_change',
providers: ['google'],
old_email: oldEmail,
new_email: newEmail,
confirmed: true,
},
})
})
})
-78
View File
@@ -1,78 +0,0 @@
import { describe, it, expect } from 'vitest'
import { detectWebmailHint } from '../webmail-search'
const FROM = '[email protected]'
describe('detectWebmailHint', () => {
it('returns Gmail with a pre-populated search for gmail.com', () => {
const hint = detectWebmailHint('[email protected]', FROM)
expect(hint).not.toBeNull()
expect(hint!.id).toBe('gmail')
expect(hint!.name).toBe('Gmail')
expect(hint!.hasSearch).toBe(true)
expect(hint!.url).toBe(
`https://mail.google.com/mail/u/0/#search/${encodeURIComponent('from:[email protected]')}`,
)
})
it('also handles googlemail.com as Gmail', () => {
const hint = detectWebmailHint('[email protected]', FROM)
expect(hint!.id).toBe('gmail')
expect(hint!.hasSearch).toBe(true)
})
it('detects Outlook variants (outlook.com, hotmail.com, live.com, msn.com)', () => {
for (const domain of ['outlook.com', 'hotmail.com', 'live.com', 'msn.com', 'hotmail.se']) {
const hint = detectWebmailHint(`user@${domain}`, FROM)
expect(hint?.id, domain).toBe('outlook')
expect(hint?.hasSearch, domain).toBe(false)
expect(hint?.url, domain).toBe('https://outlook.live.com/mail/0/inbox')
}
})
it('detects Yahoo variants', () => {
for (const domain of ['yahoo.com', 'yahoo.co.uk', 'yahoo.se', 'ymail.com']) {
const hint = detectWebmailHint(`user@${domain}`, FROM)
expect(hint?.id, domain).toBe('yahoo')
expect(hint?.hasSearch, domain).toBe(false)
}
})
it('detects iCloud variants (icloud.com, me.com, mac.com)', () => {
for (const domain of ['icloud.com', 'me.com', 'mac.com']) {
const hint = detectWebmailHint(`user@${domain}`, FROM)
expect(hint?.id, domain).toBe('icloud')
expect(hint?.hasSearch, domain).toBe(false)
}
})
it('detects Proton variants', () => {
for (const domain of ['proton.me', 'protonmail.com', 'pm.me']) {
const hint = detectWebmailHint(`user@${domain}`, FROM)
expect(hint?.id, domain).toBe('proton')
expect(hint?.hasSearch, domain).toBe(false)
}
})
it('is case-insensitive on the domain', () => {
const hint = detectWebmailHint('[email protected]', FROM)
expect(hint?.id).toBe('gmail')
})
it('returns null for unknown / custom domains', () => {
expect(detectWebmailHint('[email protected]', FROM)).toBeNull()
expect(detectWebmailHint('[email protected]', FROM)).toBeNull()
})
it('returns null for malformed email input', () => {
expect(detectWebmailHint('not-an-email', FROM)).toBeNull()
expect(detectWebmailHint('', FROM)).toBeNull()
expect(detectWebmailHint('@gmail.com', FROM)).not.toBeNull()
expect(detectWebmailHint('user@', FROM)).toBeNull()
})
it('URL-encodes the sender address (handles special characters)', () => {
const hint = detectWebmailHint('[email protected]', '[email protected]')
expect(hint!.url).toContain(encodeURIComponent('from:[email protected]'))
})
})
-281
View File
@@ -1,281 +0,0 @@
import crypto from 'crypto'
import type { SupabaseClient } from '@supabase/supabase-js'
import { createServiceRoleClient } from '@/lib/supabase/service-client'
// Not lib/company/context: that module imports next/headers for the legacy
// company cookie, and this file is reachable from bundles where that import
// is a build error.
import { getActiveCompanyId } from '@/lib/company/active-company'
const KEY_PREFIX = 'gnubok_sk_'
const REFRESH_TOKEN_PREFIX = 'gnubok_rt_'
// ── API Key Scopes ──────────────────────────────────────────
// The catalogue lives in scope-catalog.ts (no server imports, safe for client
// bundles) and is re-exported here so existing imports keep working.
export {
API_KEY_SCOPES,
ALL_SCOPES,
DEFAULT_SCOPES,
DEFAULT_OAUTH_SCOPES,
PUBLIC_OAUTH_METADATA_SCOPES,
STAGING_SCOPES,
findStageApproveConflict,
SCOPE_GROUPS,
scopeKind,
TOOL_SCOPE_MAP,
TOOL_COUNT_BY_SCOPE,
} from './scope-catalog'
export type { ApiKeyScope } from './scope-catalog'
import { API_KEY_SCOPES, DEFAULT_SCOPES, type ApiKeyScope } from './scope-catalog'
export function validateScopes(scopes: unknown): ApiKeyScope[] | null {
if (scopes === null || scopes === undefined) return null
if (!Array.isArray(scopes)) return null
const valid = scopes.filter((s): s is ApiKeyScope => s in API_KEY_SCOPES)
return valid.length > 0 ? valid : null
}
/**
* Create a Supabase service client that doesn't require cookies.
* Used for API key validation (MCP, webhooks) where there's no browser session.
*/
export function createServiceClientNoCookies() {
return createServiceRoleClient(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.SUPABASE_SERVICE_ROLE_KEY!
)
}
/**
* Name of every api_keys row minted by the MCP OAuth token route
* (app/api/mcp-oauth/token). It is the only marker those rows carry (there
* is no source column), so the Hem checklist's "Anslut till Claude" step
* matches on it to know a client completed its first sign-in. Renaming it
* would untick the step for every existing connection. The manual create
* route (app/api/settings/api-keys) rejects this name so a hand-minted key
* cannot fake the connection.
*/
export const OAUTH_MCP_KEY_NAME = 'MCP-klient (OAuth)'
export function generateApiKey(mode: ApiKeyMode = 'live'): { key: string; hash: string; prefix: string } {
const random = crypto.randomBytes(32).toString('base64url')
// Test keys carry an explicit `test_` infix so integrators can tell at a
// glance which environment a key targets (matches the llms.txt contract:
// `gnubok_sk_test_<random>`). The infix is purely cosmetic: the authoritative
// mode is the `mode` column on api_keys, read back by hash in validateApiKey,
// so nothing trusts the key string. Both variants keep the `gnubok_sk_`
// prefix so the `startsWith(KEY_PREFIX)` check in validateApiKey still holds.
const key = mode === 'test' ? `${KEY_PREFIX}test_${random}` : `${KEY_PREFIX}${random}`
const hash = hashApiKey(key)
// First 18 chars: 'gnubok_sk_test_xyz' for test keys, 'gnubok_sk_xxxxxxxx'
// for live: the stored prefix is what the settings UI shows, so the test_
// infix is visible in the key list without exposing the secret.
const prefix = key.slice(0, KEY_PREFIX.length + 8)
return { key, hash, prefix }
}
/**
* SHA-256, deliberately, and NOT a slow KDF like bcrypt/argon2.
*
* CodeQL flags this as js/insufficient-password-hash. That rule exists for
* user-chosen passwords, which are low-entropy and brute-forceable, so the
* defence is to make each guess expensive. This input is not a password: keys
* come from generateApiKey as 32 CSPRNG bytes (`gnubok_sk_<base64url>`), and no
* work factor moves the needle on a 256-bit random secret.
*
* A slow KDF would also be actively worse here: this runs on the hot path of
* every MCP request, where the hash is the primary-key lookup used to find the
* row, so per-request cost is real latency for zero security gain.
*
* Do NOT "fix" this by changing the algorithm. The hash IS the stored
* credential, so a different function invalidates every live `gnubok_sk_` key,
* breaking existing MCP connections with no migration path.
*/
export function hashApiKey(key: string): string {
return crypto.createHash('sha256').update(key).digest('hex')
}
export function generateRefreshToken(): { token: string; hash: string } {
const random = crypto.randomBytes(32).toString('base64url')
const token = `${REFRESH_TOKEN_PREFIX}${random}`
const hash = crypto.createHash('sha256').update(token).digest('hex')
return { token, hash }
}
export function hashRefreshToken(token: string): string {
return crypto.createHash('sha256').update(token).digest('hex')
}
export function isRefreshToken(token: string): boolean {
return token.startsWith(REFRESH_TOKEN_PREFIX)
}
export function extractBearerToken(request: Request): string | null {
const authHeader = request.headers.get('authorization')
if (!authHeader?.startsWith('Bearer ')) return null
return authHeader.slice(7)
}
/**
* Validate an API key and enforce rate limiting.
* Uses the DB RPC for atomic check + increment.
* Returns the user_id, company_id, api_key_id, name, and effective scopes on
* success, or an error with HTTP status.
* null scopes in DB → DEFAULT_SCOPES (read-only).
*
* api_key_id and api_key_name are returned so callers (e.g. the MCP server)
* can record actor attribution on pending_operations and audit_log.
* They may be undefined when the deployed DB hasn't yet run the migration
* that adds them to the RPC return shape.
*/
/**
* Operating mode of the API key. 'live' keys see real company data; 'test' keys
* are bound to deterministic sandbox companies. Keys created before the Phase 1
* migration default to 'live' for backwards compatibility.
*/
export type ApiKeyMode = 'live' | 'test'
/**
* Seconds a rate-limited caller should wait before retrying.
*
* `validate_and_increment_api_key` enforces a FIXED one-minute tumbling
* window per key row (`rate_limit_window_start`), and the limited branch
* deliberately does not slide the window, so the current window can never
* have more than 60 seconds left to run. 60 is therefore an exact upper
* bound rather than a guess, which is what `Retry-After` requires.
*
* The exact reset instant is `rate_limit_window_start + 1 minute` and is
* known inside the RPC, but its RETURNS TABLE carries no window column, so
* TypeScript cannot see it. Emitting the IETF `RateLimit` / `RateLimit-Policy`
* fields (draft-ietf-httpapi-ratelimit-headers) needs that column first.
*/
export const RATE_LIMIT_RETRY_AFTER_SECONDS = 60
export async function validateApiKey(
key: string
): Promise<
| {
userId: string
/**
* The key's default company. null only while the key's user has no
* company at all (minted from the OAuth popup before onboarding, issue
* #1814): the first validation after a company exists binds the key.
*/
companyId: string | null
apiKeyId?: string
apiKeyName?: string
scopes: ApiKeyScope[]
mode: ApiKeyMode
/**
* SEK ceiling on what this key may commit WITHOUT human approval, or
* null for no limit. Null is the only representation of "no limit": a
* stored 0 is forbidden by CHECK, because reading absence as 0 would
* block every commit for the key.
*/
unattendedCommitLimit: number | null
}
| { error: string; status: number }
> {
if (isRefreshToken(key)) {
return {
error: 'Refresh token cannot be used as access token; exchange it at /api/mcp-oauth/token',
status: 401,
}
}
if (!key.startsWith(KEY_PREFIX)) {
return { error: 'Invalid API key format', status: 401 }
}
const hash = hashApiKey(key)
const supabase = createServiceClientNoCookies()
const { data, error } = await supabase.rpc('validate_and_increment_api_key', {
p_key_hash: hash,
})
if (error || !data || data.length === 0) {
return { error: 'Invalid API key', status: 401 }
}
const row = data[0]
if (row.rate_limited) {
return { error: 'Rate limit exceeded', status: 429 }
}
const companyId: string | null =
row.company_id ?? (await bindUnboundKey(supabase, row.user_id, row.api_key_id))
return {
userId: row.user_id,
companyId,
apiKeyId: row.api_key_id,
apiKeyName: row.api_key_name,
scopes: validateScopes(row.scopes) ?? DEFAULT_SCOPES,
// `mode` may be undefined when the deployed DB hasn't yet run the Phase 1
// migration that adds it to the RPC return. Default to 'live' so existing
// keys behave unchanged.
mode: (row.mode === 'test' ? 'test' : 'live') as ApiKeyMode,
// PostgREST returns numeric as a STRING, so parse explicitly rather than
// relying on `>` coercion at the comparison site. Anything unparseable,
// absent (a DB that has not run the migration), or non-positive becomes
// null, i.e. no limit: this control must fail OPEN. Blocking a company's
// month-end because a defence-in-depth read blipped would be far worse
// than not enforcing.
unattendedCommitLimit: parseUnattendedCommitLimit(row.unattended_commit_limit),
}
}
/**
* Null unless the value is a finite number strictly greater than zero.
*
* Written NULL-first on purpose. Never `?? 0`, never `|| 0`, never
* `Number(undefined)` (which yields NaN, and NaN comparisons are false, so it
* would silently disable the control rather than loudly fail).
*/
function parseUnattendedCommitLimit(value: unknown): number | null {
if (value === null || value === undefined) return null
const parsed = typeof value === 'number' ? value : Number(value)
if (!Number.isFinite(parsed) || parsed <= 0) return null
return parsed
}
/**
* Late binding for keys minted before the user's first company existed.
*
* The OAuth token endpoint stores company_id NULL for such keys. Company
* creation happens in the web app (a Server Action) which knows nothing about
* the user's keys, so the binding is healed here, on the first validation after
* a company exists: one place, regardless of how the company was created.
* Returns null while the user still has no company. The UPDATE is best-effort:
* a failed write only means the next call resolves again.
*/
async function bindUnboundKey(
supabase: SupabaseClient,
userId: string,
apiKeyId: string | undefined
): Promise<string | null> {
let companyId: string | null
try {
companyId = await getActiveCompanyId(supabase, userId)
} catch {
return null
}
if (!companyId) return null
if (apiKeyId) {
await supabase
.from('api_keys')
.update({ company_id: companyId })
.eq('id', apiKeyId)
.is('company_id', null)
}
return companyId
}
/**
* Check if a given scope is allowed by the key's scopes.
*/
export function hasScope(keyScopes: ApiKeyScope[], required: ApiKeyScope): boolean {
return keyScopes.includes(required)
}
-49
View File
@@ -1,49 +0,0 @@
/**
* Decide whether an `/api` request should SKIP the middleware MFA (AAL2) gate.
*
* Most `/api` routes historically hand-roll `supabase.auth.getUser()` instead
* of `requireAuth()`, which means they never enforce MFA. The middleware gate
* (lib/supabase/middleware.ts) closes that gap for cookie sessions, but a few
* request classes must NOT be gated:
*
* - Bearer-authenticated SURFACES (`/api/v1/*` API keys, the MCP endpoint's
* OAuth tokens/API keys): the route validates the Authorization credential
* itself and never trusts the cookie session, so a logged-in AAL1 browser
* testing its own API key must not be blocked. This is scoped by PATH, not
* header presence: the header is attacker-controlled, and an Authorization
* header riding on a cookie-authenticated route must never disable the
* gate (the route would ignore the header and authenticate via cookies,
* i.e. a stolen-password session could bypass MFA with `Authorization: x`).
* Pure Bearer callers elsewhere (cron secret, signed webhooks) carry no
* cookie session, so the gate: which only fires for cookie users: never
* touches them and they need no exemption.
* - The AAL1 escape hatch: a user with MFA required but not yet verified (or a
* BankID-only user setting a first password) must still reach
* `/api/account/*` and `/api/company*` to COMPLETE onboarding / enroll MFA.
* - The MCP OAuth endpoints (`/api/mcp-oauth/*`) carry their own PKCE +
* single-use-code security and drive the connector authorize flow.
*
* Kept as a pure function so the allowlist is unit-testable in isolation.
*/
// Routes whose auth contract IS the Authorization header. Everything else
// under /api/extensions/ext/ authenticates via requireAuth (cookies) in the
// dispatcher and must stay behind the gate.
const BEARER_AUTH_PREFIXES = ['/api/v1/', '/api/extensions/ext/mcp-server/mcp']
export function apiPathSkipsMfaGate(
pathname: string,
hasAuthorizationHeader: boolean,
): boolean {
if (
hasAuthorizationHeader &&
BEARER_AUTH_PREFIXES.some((prefix) => pathname.startsWith(prefix))
) {
return true
}
return (
pathname.startsWith('/api/account/') ||
pathname.startsWith('/api/company') ||
pathname.startsWith('/api/mcp-oauth/')
)
}

Some files were not shown because too many files have changed in this diff Show More