Files
crawler-plugin/admin-frontend-vue/tests/live/expiry-notice-live.test.ts
T
huangzd1997 3724e1e4cd test(到期提醒): 补生产 E2E——daysToExpire 生命周期、续费解除与到期拦截
弹窗的唯一判据是 /api/admin/current-user 的 daysToExpire,之前只有前端渲染层的桩用例,
"临期→续费→过期"这条真链路在产线上从没跑过。这支用例走完整生命周期并在 finally 删号:
建临期号(+2 天) → 登录取 current-user 断言天数落在 [0,5) → 续费到 10 天断言 >=5(弹窗消失的
判据)→ 手工置为过去时间 → 登录应 403 且文案指向续费 → 既有会话应 401。

两处刻意的设计,别当成随手写的:
1) 临时号口令用 randomBytes 现场生成,不落盘不进仓库——写死一个弱口令等于在产线上留后门;
2) 超管那半支先按 role 门控再断言(凭据角色不是 super_admin 就 skip)。
   上一版直接断言 daysToExpire===null,用 ceshi001(normal)跑出来是红的,看着像功能坏了,
   其实是环境缺后台凭据——缺凭据不等于有 bug,尺子要能把这两件事分开说。

只在带 AIIMAGE_LIVE_USER/PASS 时运行;tests/live 不在 node --test 的 glob 分母里,
所以它既不进全量例数,也不会被 CI 顺手跑掉(跑它=在产线建删真实管理员,必须显式授权)。
2026-10-05 13:53:03 +08:00

163 lines
8.3 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import test, { type TestContext } from 'node:test'
import assert from 'node:assert/strict'
import { randomBytes } from 'node:crypto'
/**
* 到期续费提醒的端到端用例(V146,2026-10-05 需求)。
*
* 验的是弹窗唯一的判据来源——`/api/admin/current-user` 的 `daysToExpire`,以及
* 到期后登录被拦这条出口;弹窗本身是纯前端渲染,由 tests/expiry-notice.test.ts 钉。
*
* 生命周期:建号(临期) → 登录取 current-user 断言 <5 → 续费到 10 天 → 断言 ≥5
* → 手工置为过去时间 → 登录应被拒 → 删号清理。
* 只在带**后台角色**凭据时跑(AIIMAGE_LIVE_USER/PASS):角色不足会带诊断跳过,
* 因为"缺凭据"和"功能坏了"混成一条红,下一轮就没人信这支了。
* 创建的账号带 acc_expiry_live_ 前缀、当场删除,口令每次随机生成且不落盘。
*/
const BASE = process.env.AIIMAGE_LIVE_BASE || 'http://127.0.0.1:18080'
const USER = process.env.AIIMAGE_LIVE_USER || ''
const PASS = process.env.AIIMAGE_LIVE_PASS || ''
const HAS_CREDS = Boolean(USER && PASS)
/** 临时号的口令:随机、只在本次进程内存里,绝不写进仓库(写死一个弱口令=在产线留后门)。 */
const ADMIN_PASS = randomBytes(18).toString('base64url')
function authHeader(token: string): Record<string, string> {
return { Authorization: `Bearer ${token}` }
}
async function login(username: string, password: string, deviceId: string) {
const res = await fetch(`${BASE}/login`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username, password, deviceId }),
})
const body = (await res.json()) as {
success?: boolean
code?: number
message?: string
data?: { token?: string; role?: string }
}
return { res, body }
}
/** yyyy-MM-dd HH:mm,与后端 CREATED_AT_FORMATTER/expiresAt 入参同形。 */
function fmt(dt: Date): string {
const p = (n: number) => String(n).padStart(2, '0')
return `${dt.getFullYear()}-${p(dt.getMonth() + 1)}-${p(dt.getDate())} ${p(dt.getHours())}:${p(dt.getMinutes())}`
}
function daysFromNow(days: number): string {
return fmt(new Date(Date.now() + days * 86_400_000))
}
type Operator = { token: string; role: string }
let operatorCache: Operator | null = null
async function operator(): Promise<Operator> {
if (operatorCache) return operatorCache
const { res, body } = await login(USER, PASS, 'claude-expiry-live-operator')
assert.equal(body.success, true, `操作账号登录应成功: ${body.message || res.status}`)
const token = body.data?.token
assert.ok(token, '登录应下发 token')
operatorCache = { token: token as string, role: String(body.data?.role || '') }
return operatorCache
}
/**
* 角色闸门:普通账号(role=normal)拿不到 /api/admin/*,那类 403 是权限不是缺陷。
* 返回 null 表示"本用例在缺后台凭据的环境里跑不了",调用方必须立刻 return——
* t.skip() 之后 body 仍会继续执行,留着断言就会把环境问题报成功能红。
*/
async function requireRole(t: TestContext, need: string[]): Promise<Operator | null> {
const op = await operator()
if (!need.includes(op.role)) {
t.skip(`凭据角色=${op.role || '<空>'},本用例需要 ${need.join('/')};缺后台凭据不等于功能坏了`)
return null
}
return op
}
test('test_expiry_live_super_admin_has_no_notice', { skip: !HAS_CREDS }, async (t) => {
// 超管自身不设到期 ⇒ daysToExpire 为 null ⇒ 弹窗不该出现(需求只针对"快过期的管理员")。
const op = await requireRole(t, ['super_admin'])
if (!op) return
const res = await fetch(`${BASE}/api/admin/current-user`, { headers: authHeader(op.token) })
const body = (await res.json()) as { success?: boolean; data?: Record<string, unknown> }
assert.equal(body.success, true)
assert.ok(body.data && 'daysToExpire' in body.data, 'current-user 必须带 daysToExpire 字段(弹窗的数据源)')
assert.equal(body.data?.daysToExpire, null, `超管不该有到期天数: ${JSON.stringify(body.data?.daysToExpire)}`)
})
test('test_expiry_live_notice_then_renew_then_expire', { skip: !HAS_CREDS }, async (t) => {
const op = await requireRole(t, ['super_admin'])
if (!op) return
const token = op.token
const username = `acc_expiry_live_${Date.now()}`
let createdId: number | null = null
try {
// 1) 建一个"剩余不足 5 天"的管理员(临期 +2 天)
const create = await fetch(`${BASE}/api/admin/user`, {
method: 'POST',
headers: { ...authHeader(token), 'Content-Type': 'application/json' },
body: JSON.stringify({ username, password: ADMIN_PASS, role: 'admin', expiresAt: daysFromNow(2) }),
})
const created = (await create.json()) as { success?: boolean; message?: string; data?: number }
assert.equal(created.success, true, `建号应成功: ${created.message || create.status}`)
createdId = created.data as number
assert.equal(typeof createdId, 'number')
// 2) 以该账号登录取 current-user:daysToExpire 必须落进弹窗触发区间 [0,5)
const near = await login(username, ADMIN_PASS, 'claude-expiry-live-self')
assert.equal(near.body.success, true, `临期账号此刻仍可登录: ${near.body.message || ''}`)
const nearToken = near.body.data?.token as string
const cu = (await (await fetch(`${BASE}/api/admin/current-user`, { headers: authHeader(nearToken) })).json()) as {
data?: { daysToExpire?: number | null; expiresAt?: string | null }
}
assert.equal(typeof cu.data?.daysToExpire, 'number', `临期应给出天数: ${JSON.stringify(cu.data)}`)
assert.ok((cu.data?.daysToExpire as number) >= 0 && (cu.data?.daysToExpire as number) < 5,
`daysToExpire 应落在弹窗触发区间 [0,5),实际 ${cu.data?.daysToExpire}`)
// 3) 续费到 10 天 ⇒ 超过阈值,弹窗消失(需求:"直到续费超过5天才消失")
const renew = await fetch(`${BASE}/api/admin/user/${createdId}`, {
method: 'PUT',
headers: { ...authHeader(token), 'Content-Type': 'application/json' },
body: JSON.stringify({ expiresAt: daysFromNow(10) }),
})
const renewed = (await renew.json()) as { success?: boolean; message?: string }
assert.equal(renewed.success, true, `续费应成功: ${renewed.message || renew.status}`)
const cu2 = (await (await fetch(`${BASE}/api/admin/current-user`, { headers: authHeader(nearToken) })).json()) as {
data?: { daysToExpire?: number | null }
}
assert.ok(typeof cu2.data?.daysToExpire === 'number' && (cu2.data?.daysToExpire as number) >= 5,
`续费后应 ≥5 天(弹窗不再出现),实际 ${cu2.data?.daysToExpire}`)
// 4) 置为过去时间 = 手工停用 ⇒ 登录被拦、给出续费文案(403 走响应体 biz code)
const expire = await fetch(`${BASE}/api/admin/user/${createdId}`, {
method: 'PUT',
headers: { ...authHeader(token), 'Content-Type': 'application/json' },
body: JSON.stringify({ expiresAt: fmt(new Date(Date.now() - 86_400_000)) }),
})
assert.equal(((await expire.json()) as { success?: boolean }).success, true, '置为过去时间应成功')
const blocked = await login(username, ADMIN_PASS, 'claude-expiry-live-blocked')
assert.notEqual(blocked.body.success, true, '已过期账号不该登录成功')
assert.equal(blocked.body.code, 403, `到期拦截应是 403,实际 code=${blocked.body.code}`)
assert.ok(/续费|过期/.test(blocked.body.message || ''), `文案应指向续费,实际 "${blocked.body.message}"`)
// 5) 老会话也要被拦(每请求鉴权走 401,前端按下线处理)
const stale = await fetch(`${BASE}/api/admin/current-user`, { headers: authHeader(nearToken) })
const staleBody = (await stale.json()) as { success?: boolean; code?: number }
assert.notEqual(staleBody.success, true, '过期账号的既有会话不该继续可用')
assert.equal(staleBody.code, 401, `会话拦截应是 401,实际 code=${staleBody.code}`)
} finally {
if (createdId !== null) {
const del = await fetch(`${BASE}/api/admin/user/${createdId}`, {
method: 'DELETE',
headers: authHeader(token),
})
const gone = (await del.json()) as { success?: boolean; message?: string }
assert.equal(gone.success, true, `清理账号应成功: ${gone.message || del.status}`)
}
}
})