import { AUTH_SESSION_KEY, assertAuthSessionLockHeld, createAuthNonce, formatToken, getAccessToken, getAuthSession, getRefreshToken, getTenantId, getVisitTenantId, isAuthSessionCurrent, isPageSessionCurrent, removeToken, setTenantId, setToken, setVisitTenantId, withAuthSessionLock } from '@/utils/auth' import { appUrl, assertSsoFlowCurrent, beginSsoFlow, completeSsoFlow, consumeSsoFlow, currentAppPath, isIdentityCenterPage, safeRedirect } from '@/utils/ssoFlow' import type { TokenType } from '@/api/login/types' const token = (access: string, refresh: string, binding?: string): TokenType => ({ id: 1, accessToken: access, refreshToken: refresh, userId: 1, userType: 2, clientId: 'ckcloud', expiresTime: 0, ssoSessionBinding: binding }) describe('utils/auth 登录会话', () => { it('无会话或存储损坏时返回空会话', () => { expect(getAuthSession()).toEqual({ accessToken: '', refreshToken: '', sessionId: '', ssoSessionBinding: '' }) localStorage.setItem(AUTH_SESSION_KEY, '{broken') expect(getAccessToken()).toBe('') localStorage.setItem(AUTH_SESSION_KEY, JSON.stringify({ accessToken: 1 })) expect(getRefreshToken()).toBe('') }) it('令牌只能在跨标签页锁内写入', () => { expect(() => setToken(token('a', 'r'))).toThrow('登录状态必须在跨标签页锁内更新') expect(() => assertAuthSessionLockHeld()).toThrow() }) it('锁内一次写入完整令牌对,同会话续期保留 SSO 绑定', async () => { await withAuthSessionLock(() => setToken(token('a1', 'r1', 'bind-1'), 'sid')) expect(getAuthSession()).toEqual({ accessToken: 'a1', refreshToken: 'r1', sessionId: 'sid', ssoSessionBinding: 'bind-1' }) expect(isPageSessionCurrent()).toBe(true) await withAuthSessionLock(() => setToken(token('a2', 'r1'), 'sid')) expect(getAuthSession().ssoSessionBinding).toBe('bind-1') const snapshot = getAuthSession() expect(isAuthSessionCurrent(snapshot)).toBe(true) await withAuthSessionLock(() => setToken(token('a3', 'r1'), 'sid')) expect(isAuthSessionCurrent(snapshot)).toBe(false) }) it('不完整的登录响应被拒绝', async () => { await expect(withAuthSessionLock(() => setToken(token('', 'r')))).rejects.toThrow( '登录响应不完整' ) }) it('removeToken 清除会话', async () => { await withAuthSessionLock(() => setToken(token('a', 'r'), 'sid')) await withAuthSessionLock(() => removeToken()) expect(getAccessToken()).toBe('') }) it('锁按顺序串行执行', async () => { const order: number[] = [] await Promise.all([ withAuthSessionLock(async () => { await new Promise((r) => setTimeout(r, 10)) order.push(1) }), withAuthSessionLock(() => { order.push(2) }) ]) expect(order).toEqual([1, 2]) }) it('随机数、令牌格式与租户缓存', () => { expect(createAuthNonce()).toMatch(/^[0-9a-f]{64}$/) expect(formatToken('x')).toBe('Bearer x') setTenantId(1) setVisitTenantId(2) expect(getTenantId()).toBe(1) expect(getVisitTenantId()).toBe(2) }) }) describe('utils/ssoFlow 单点登录流程', () => { it('appUrl / currentAppPath / isIdentityCenterPage', () => { expect(appUrl('/sso/login')).toBe(`${location.origin}/sso/login`) expect(currentAppPath()).toBe(location.pathname + location.search + location.hash) expect(isIdentityCenterPage()).toBe(false) }) it('safeRedirect 只允许站内业务路径,拦截外链与登录页', () => { expect(safeRedirect('/system/user?id=1#x')).toBe('/system/user?id=1#x') expect(safeRedirect('//evil.com/a')).toBe('/') expect(safeRedirect('https://evil.com')).toBe('/') expect(safeRedirect('/a\\b')).toBe('/') expect(safeRedirect('/sso/callback')).toBe('/') expect(safeRedirect('/zcy/login')).toBe('/') expect(safeRedirect('/auth-status')).toBe('/') expect(safeRedirect('/403')).toBe('/') expect(safeRedirect(123)).toBe('/') }) it('发起的流程只能被同一 requestId 与类型消费一次', async () => { const flow = await beginSsoFlow('login', '/system/user', 'org-1') expect(flow.redirect).toBe('/system/user') expect(flow.organizationKey).toBe('org-1') expect(() => consumeSsoFlow('other', 'login')).toThrow('登录请求不匹配') expect(() => consumeSsoFlow(flow.requestId, 'logout')).toThrow('登录请求不匹配') const consumed = consumeSsoFlow(flow.requestId, 'login') expect(consumed.requestId).toBe(flow.requestId) expect(() => consumeSsoFlow(flow.requestId, 'login')).toThrow('登录请求已失效') }) it('新流程覆盖旧流程,过期流程失效', async () => { const first = await beginSsoFlow('login') await beginSsoFlow('logout') expect(() => assertSsoFlowCurrent(first)).toThrow('登录状态已变更') const second = await beginSsoFlow('login') expect(() => assertSsoFlowCurrent({ ...second, createdAt: Date.now() - 9 * 3600_000 })).toThrow() await withAuthSessionLock(() => completeSsoFlow(second)) expect(() => assertSsoFlowCurrent(second)).toThrow() }) })