gongxiangp2/lib/__tests__/auth-cookie.test.ts
2026-07-07 13:31:01 +08:00

79 lines
2.1 KiB
TypeScript

import {
getAuthSessionCookieCandidates,
getAuthSessionCookieName,
PLAIN_AUTH_SESSION_COOKIE_NAME,
resolveSecureAuthCookieFromRequest,
SECURE_AUTH_SESSION_COOKIE_NAME,
} from '@/lib/auth-cookie'
describe('auth cookie protocol resolution', () => {
function restoreEnv(name: string, value: string | undefined) {
if (value === undefined) {
delete process.env[name]
} else {
process.env[name] = value
}
}
it('HTTPS 请求使用 secure cookie', () => {
expect(
resolveSecureAuthCookieFromRequest({
headers: {
'x-forwarded-proto': 'https',
},
})
).toBe(true)
})
it('HTTP 请求使用普通 cookie', () => {
expect(
resolveSecureAuthCookieFromRequest({
headers: {
'x-forwarded-proto': 'http',
},
nextUrl: {
protocol: 'http:',
},
})
).toBe(false)
})
it('公网域名经过内网 HTTP 反代时仍使用 secure cookie', () => {
const originalAppPublicUrl = process.env.APP_PUBLIC_URL
const originalNextAuthUrl = process.env.NEXTAUTH_URL
process.env.APP_PUBLIC_URL = 'https://sc.jiansun.vip'
process.env.NEXTAUTH_URL = 'https://sc.jiansun.vip'
jest.isolateModules(() => {
const {
resolveSecureAuthCookieFromRequest: resolveWithPublicHost,
} = require('@/lib/auth-cookie')
expect(
resolveWithPublicHost({
headers: {
host: 'sc.jiansun.vip',
'x-forwarded-proto': 'http',
},
})
).toBe(true)
})
restoreEnv('APP_PUBLIC_URL', originalAppPublicUrl)
restoreEnv('NEXTAUTH_URL', originalNextAuthUrl)
})
it('优先和兜底 cookie 名称都可返回', () => {
expect(getAuthSessionCookieName(true)).toBe(SECURE_AUTH_SESSION_COOKIE_NAME)
expect(getAuthSessionCookieName(false)).toBe(PLAIN_AUTH_SESSION_COOKIE_NAME)
expect(getAuthSessionCookieCandidates(true)).toEqual([
SECURE_AUTH_SESSION_COOKIE_NAME,
PLAIN_AUTH_SESSION_COOKIE_NAME,
])
expect(getAuthSessionCookieCandidates(false)).toEqual([
PLAIN_AUTH_SESSION_COOKIE_NAME,
SECURE_AUTH_SESSION_COOKIE_NAME,
])
})
})