gongxiangp2/lib/__tests__/desktop-client-session.test.ts

82 lines
3.8 KiB
TypeScript

/** @jest-environment node */
import { createHash } from 'node:crypto'
import { DESKTOP_CLIENT_ID } from '@/lib/desktop-client/contract.mjs'
import { exchangeDesktop, requireDesktop } from '@/lib/desktop-client/service'
import { prisma } from '@/lib/prisma'
jest.mock('@/lib/prisma', () => ({ prisma: {
user: { findUnique: jest.fn() }, $queryRawUnsafe: jest.fn(), $executeRawUnsafe: jest.fn(), $transaction: jest.fn(),
} }))
jest.mock('@/lib/detail-generator/repository', () => ({}))
jest.mock('@/lib/detail-generator/storage', () => ({}))
const now = Date.parse('2026-12-02T00:00:00Z')
const day = 86400000
const request = new Request('https://example.test/api/desktop/session', {
headers: { authorization: `Bearer dcs_${'x'.repeat(64)}` },
})
const query = jest.mocked(prisma.$queryRawUnsafe)
const execute = jest.mocked(prisma.$executeRawUnsafe)
const enabled = process.env.DETAIL_GENERATOR_ENABLED
beforeEach(() => {
jest.resetAllMocks()
jest.spyOn(Date, 'now').mockReturnValue(now)
process.env.DETAIL_GENERATOR_ENABLED = 'true'
jest.mocked(prisma.user.findUnique).mockResolvedValue({
username: 'tester', realName: '试用同事', status: 'active', isActive: true, archivedAt: null,
} as Awaited<ReturnType<typeof prisma.user.findUnique>>)
execute.mockResolvedValue(1)
})
afterEach(() => {
jest.restoreAllMocks()
if (enabled === undefined) delete process.env.DETAIL_GENERATOR_ENABLED
else process.env.DETAIL_GENERATOR_ENABLED = enabled
})
test('issues a desktop session with a 30-day expiry', async () => {
const verifier = 'v'.repeat(43)
const redirectUri = 'http://127.0.0.1:18433/oauth/callback'
const challenge = createHash('sha256').update(verifier).digest('base64url')
query.mockResolvedValue([{ id: 'grant', ownerId: 'owner', redirectUri, challenge }])
;(prisma.$transaction as jest.Mock).mockImplementation(async action => action(prisma))
const session = await exchangeDesktop({ client_id: DESKTOP_CLIENT_ID, grant_type: 'authorization_code',
code: 'dca_' + 'x'.repeat(43), code_verifier: verifier, redirect_uri: redirectUri })
const expiry = new Date(now + 30 * day)
expect(session.expires_at).toBe(expiry.toISOString())
expect(execute).toHaveBeenCalledWith(expect.stringContaining('INSERT INTO desktop_client_sessions'),
expect.any(String), expect.any(String), 'owner', '详情页工作台', expiry)
})
test('extends a session with under 15 days remaining and returns the new expiry', async () => {
query.mockResolvedValue([{ id: 'session', ownerId: 'owner', expiresAt: new Date(now + 15 * day - 1) }])
const expiresAt = new Date(now + 30 * day)
await expect(requireDesktop(request)).resolves.toMatchObject({ id: 'session', expiresAt })
expect(execute).toHaveBeenCalledWith(
'UPDATE desktop_client_sessions SET expires_at=$2 WHERE id=$1 AND revoked_at IS NULL AND expires_at>NOW()',
'session', expiresAt,
)
})
test.each([15, 16])('leaves a session with %i days remaining untouched', async days => {
const expiresAt = new Date(now + days * day)
query.mockResolvedValue([{ id: 'session', ownerId: 'owner', expiresAt }])
await expect(requireDesktop(request)).resolves.toMatchObject({ expiresAt })
expect(execute).not.toHaveBeenCalled()
})
test('rejects expired or revoked sessions excluded by the lookup', async () => {
query.mockResolvedValue([])
await expect(requireDesktop(request)).rejects.toMatchObject({ status: 401, code: 'session_expired' })
expect(query).toHaveBeenCalledWith(expect.stringContaining('revoked_at IS NULL AND expires_at>NOW()'), expect.any(String))
expect(execute).not.toHaveBeenCalled()
})
test('rejects the session if revocation or expiry races the renewal', async () => {
query.mockResolvedValue([{ id: 'session', ownerId: 'owner', expiresAt: new Date(now + day) }])
execute.mockResolvedValue(0)
await expect(requireDesktop(request)).rejects.toMatchObject({ status: 401, code: 'session_expired' })
})