feat(security): harden gateway boundaries and usage policies

Consolidate subscription usage policy enforcement, privacy-safe persistence, and gateway security hardening into one reviewable change.

Includes bounded HTTP and execution envelopes, header and protocol guards, DNS and relay validation, authentication and secret projection hardening, secure backup/install paths, and regression coverage.
This commit is contained in:
elky
2026-09-04 03:45:52 +08:00
parent ddcbeb3ae9
commit 579f2c7cc1
1019 changed files with 190437 additions and 26080 deletions
@@ -46,6 +46,21 @@ describe('authApi turnstile payloads', () => {
})
})
it('binds verification and status requests to the verification session token', async () => {
await authApi.verifyEmail('[email protected]', '123456', 'verification-session-token')
await authApi.getVerificationStatus('[email protected]', 'verification-session-token')
expect(postMock).toHaveBeenNthCalledWith(1, '/api/auth/verify-email', {
email: '[email protected]',
code: '123456',
verification_token: 'verification-session-token',
})
expect(postMock).toHaveBeenNthCalledWith(2, '/api/auth/verification-status', {
email: '[email protected]',
verification_token: 'verification-session-token',
})
})
it('refreshes auth token without a request body', async () => {
postMock.mockResolvedValue({ data: { access_token: 'new-access-token' } })
@@ -54,4 +69,12 @@ describe('authApi turnstile payloads', () => {
expect(postMock).toHaveBeenCalledWith('/api/auth/refresh')
expect(setTokenMock).toHaveBeenCalledWith('new-access-token')
})
it('publishes login session availability without changing the token payload', async () => {
postMock.mockResolvedValue({ data: { access_token: 'login-access-token' } })
await authApi.login({ email: '[email protected]', password: 'secret123' })
expect(setTokenMock).toHaveBeenCalledWith('login-access-token', true)
})
})
+101 -4
View File
@@ -1,7 +1,11 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { AxiosAdapter, AxiosInstance, InternalAxiosRequestConfig } from 'axios'
import apiClient, { AUTH_STATE_CHANGE_EVENT } from '@/api/client'
import apiClient, {
AUTH_SESSION_SIGNAL_KEY,
AUTH_STATE_CHANGE_EVENT,
parseAuthSessionSignal,
} from '@/api/client'
import { cache, cachedRequest } from '@/utils/cache'
type TestableApiClient = typeof apiClient & {
@@ -24,17 +28,82 @@ describe('apiClient auth state change event', () => {
window.addEventListener(AUTH_STATE_CHANGE_EVENT, handler as EventListener)
apiClient.setToken('access-token')
localStorage.setItem('access_token', 'legacy-local-token')
sessionStorage.setItem('access_token', 'legacy-session-token')
apiClient.clearAuth()
expect(localStorage.getItem('access_token')).toBeNull()
expect(handler).toHaveBeenCalledTimes(1)
expect(sessionStorage.getItem('access_token')).toBeNull()
expect(handler).toHaveBeenCalledTimes(2)
const event = handler.mock.calls[0][0] as CustomEvent<{ token: string | null }>
expect(event.detail).toEqual({ token: null })
const event = handler.mock.calls[1][0] as CustomEvent<{ authenticated: boolean }>
expect(event.detail).toEqual({ authenticated: false })
window.removeEventListener(AUTH_STATE_CHANGE_EVENT, handler as EventListener)
})
it('keeps access tokens in memory and only stores token-free session metadata', () => {
apiClient.setToken('sensitive-access-token', true)
expect(apiClient.getToken()).toBe('sensitive-access-token')
expect(localStorage.getItem('access_token')).toBeNull()
expect(sessionStorage.getItem('access_token')).toBeNull()
const rawSignal = localStorage.getItem(AUTH_SESSION_SIGNAL_KEY)
expect(rawSignal).not.toContain('sensitive-access-token')
expect(parseAuthSessionSignal(rawSignal)).toMatchObject({ authenticated: true })
})
it('restores a session through the refresh cookie and stores the result in memory only', async () => {
const rawClient = apiClient as TestableApiClient
const previousAdapter = rawClient.client.defaults.adapter
rawClient.client.defaults.adapter = (async (config: InternalAxiosRequestConfig) => ({
data: { access_token: 'restored-access-token' },
status: 200,
statusText: 'OK',
headers: {},
config,
})) as AxiosAdapter
try {
await expect(apiClient.restoreSession()).resolves.toBe('restored-access-token')
expect(apiClient.getToken()).toBe('restored-access-token')
expect(localStorage.getItem('access_token')).toBeNull()
expect(sessionStorage.getItem('access_token')).toBeNull()
} finally {
rawClient.client.defaults.adapter = previousAdapter
}
})
it('does not resurrect a session when logout wins an in-flight restore', async () => {
const rawClient = apiClient as TestableApiClient
const previousAdapter = rawClient.client.defaults.adapter
let resolveRefresh!: (response: Awaited<ReturnType<AxiosAdapter>>) => void
rawClient.client.defaults.adapter = (() => new Promise((resolve) => {
resolveRefresh = resolve
})) as AxiosAdapter
try {
const restore = apiClient.restoreSession()
await vi.waitFor(() => expect(resolveRefresh).toBeTypeOf('function'))
apiClient.clearAuth()
resolveRefresh({
data: { access_token: 'stale-access-token' },
status: 200,
statusText: 'OK',
headers: {},
config: {} as InternalAxiosRequestConfig,
})
await expect(restore).rejects.toThrow('Auth state changed')
expect(apiClient.getToken()).toBeNull()
} finally {
rawClient.client.defaults.adapter = previousAdapter
}
})
it('clears cached API data whenever the authentication identity changes', () => {
apiClient.setToken('first-token')
cache.set('dashboard', { owner: 'first-user' }, 30_000)
@@ -99,4 +168,32 @@ describe('apiClient auth state change event', () => {
rawClient.client.defaults.adapter = previousAdapter
}
})
it('authenticates protected gateway operational requests', async () => {
const rawClient = apiClient as TestableApiClient
const previousAdapter = rawClient.client.defaults.adapter
const requests: InternalAxiosRequestConfig[] = []
rawClient.client.defaults.adapter = (async (config: InternalAxiosRequestConfig) => {
requests.push(config)
return {
data: '',
status: 200,
statusText: 'OK',
headers: {},
config,
}
}) as AxiosAdapter
try {
apiClient.setToken('operational-access-token')
await apiClient.get('/_gateway/metrics')
expect(requests).toHaveLength(1)
expect(requests[0].headers.Authorization).toBe('Bearer operational-access-token')
expect(requests[0].headers['X-Client-Device-Id']).toBeTruthy()
} finally {
rawClient.client.defaults.adapter = previousAdapter
}
})
})