472 lines
22 KiB
JavaScript
472 lines
22 KiB
JavaScript
'use strict';
|
||
|
||
const { app, mock, assert } = require('egg-mock/bootstrap');
|
||
const http = require('http');
|
||
const crypto = require('crypto');
|
||
const createFakeRedis = require('../../utils/fake-redis');
|
||
|
||
/** 等一会儿(用来模拟「挂上长轮询之后,手机才确认」) */
|
||
const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));
|
||
|
||
/** Sequelize 实例的最小替身:update 的字段收集到 updates 里,同时并进 data(toJSON 会看到新值) */
|
||
const instance = (data, updates) => Object.assign(
|
||
{
|
||
toJSON: () => data,
|
||
update: async (fields) => {
|
||
if (updates) updates.push(fields);
|
||
Object.assign(data, fields);
|
||
},
|
||
},
|
||
data,
|
||
);
|
||
|
||
describe('test/app/controller/device.test.js', () => {
|
||
const userRow = { id: 7, username: 'admin', nickname: '管理员', email: 'admin@example.com', phone: null, status: 1 };
|
||
|
||
/** 用户模型固定桩 + 用例自己的扫描器模型 */
|
||
function mockModels(scannerModel) {
|
||
mock(app, 'model', {
|
||
User: {
|
||
async findByPk(id) {
|
||
return instance(Object.assign({}, userRow, { id }));
|
||
},
|
||
},
|
||
Scanner: scannerModel,
|
||
});
|
||
}
|
||
|
||
/** 已登录用户的 JWT(手机端 /api/wechat/confirm 就是用它) */
|
||
const userJwt = () => app.createAnonymousContext().service.jwt.signUser(userRow);
|
||
|
||
/** 发码 → 挂长轮询 → 手机确认 → 等设备拿到结果 */
|
||
async function scanFlow({ sn = null, wait = 10, expectPoll = 200 } = {}) {
|
||
const query = sn ? `?sn=${encodeURIComponent(sn)}` : '';
|
||
const issued = await app.httpRequest().get(`/api/device/login${query}`).expect(200);
|
||
const code = issued.body.data.code;
|
||
|
||
// 长轮询先挂着,150ms 后手机确认(走真实的 POST /api/wechat/confirm)
|
||
const polled = app.httpRequest()
|
||
.get(`/api/device/login${sn ? `?sn=${encodeURIComponent(sn)}&` : '?'}code=${code}&wait=${wait}`)
|
||
.expect(expectPoll);
|
||
await sleep(150);
|
||
|
||
const confirmed = await app.httpRequest()
|
||
.post('/api/wechat/confirm')
|
||
.set('Authorization', `Bearer ${userJwt()}`)
|
||
.send({ code })
|
||
.expect(200);
|
||
assert(confirmed.body.data.status === 'confirmed', JSON.stringify(confirmed.body));
|
||
|
||
return { code, res: await polled, issued: issued.body.data };
|
||
}
|
||
|
||
it('GET /api/device/login 发码:不需要任何凭据、也不建任何记录', async () => {
|
||
const fake = createFakeRedis();
|
||
mock(app, 'redis', fake.client);
|
||
// 扫描器模型一个方法都不给:这一步要是碰了库,用例直接报错
|
||
mockModels({});
|
||
|
||
let res = await app.httpRequest().get('/api/device/login').expect(200);
|
||
let d = res.body.data;
|
||
assert(d.status === 'pending', JSON.stringify(d));
|
||
assert(/^[0-9A-Z]{6}$/.test(d.code), `应是 6 位数字+字母:${d.code}`);
|
||
assert(d.spm === `1.0.${d.code}.1`, d.spm);
|
||
assert(d.device.sn === null && d.device.name === null, `没报就是 null:${JSON.stringify(d.device)}`);
|
||
assert(d.expiresIn === app.config.wechat.stateTtl, '应返回登录码有效期');
|
||
assert(await fake.client.get(`packs:wechat:state:${d.code}`) === 'pending', '登录码应登记为 pending');
|
||
|
||
// 设备不知道域名也能画二维码:接口把**完整网址**算好给它
|
||
assert(/^https?:\/\/[^/]+$/.test(d.origin), `origin 应是「协议 + 主机」:${d.origin}`);
|
||
assert(d.qrContent === `${d.origin}/wechat?spm=1.0.${d.code}.1`, d.qrContent);
|
||
assert(d.qrImageUrl === `${d.origin}/api/wechat/qrcode.svg?code=${d.code}`, d.qrImageUrl);
|
||
assert(d.qrUrl === `/api/wechat/qrcode.svg?code=${d.code}`, d.qrUrl);
|
||
|
||
// 带上设备自报信息:原样回显(此时同样不建记录)
|
||
// ⚠️ URL 里的中文必须 encodeURIComponent(supertest 会报 ERR_UNESCAPED_CHARACTERS)
|
||
res = await app.httpRequest()
|
||
.get(`/api/device/login?sn=SN-SCAN-01&name=${encodeURIComponent('门口扫码枪')}&vendor=acme`)
|
||
.expect(200);
|
||
d = res.body.data;
|
||
assert(d.device.sn === 'SN-SCAN-01' && d.device.name === '门口扫码枪', JSON.stringify(d.device));
|
||
});
|
||
|
||
it('设备扫码登录:**确认成功这一步才注册**并绑定到确认的账号,下发长期 JWT', async () => {
|
||
const fake = createFakeRedis();
|
||
mock(app, 'redis', fake.client);
|
||
const updates = [];
|
||
let created = null;
|
||
mockModels({
|
||
// 库里没有这个 SN —— 设备是全新的,还没注册
|
||
async findOne() {
|
||
return null;
|
||
},
|
||
async create(data) {
|
||
created = Object.assign({ id: 21, status: 1 }, data);
|
||
return instance(created, updates);
|
||
},
|
||
});
|
||
|
||
const { code, res } = await scanFlow({ sn: 'SN-SCAN-01' });
|
||
const d = res.body.data;
|
||
|
||
assert(d.status === 'confirmed', JSON.stringify(d));
|
||
assert(d.firstTime === true, '首次应是「本次才注册」');
|
||
assert(d.sn === 'SN-SCAN-01', `应回显设备自报的 SN:${d.sn}`);
|
||
assert(d.secret === undefined, '设备身份只看长期 JWT,不再下发密钥');
|
||
assert(d.tokenType === 'Bearer' && d.expiresIn === app.config.jwt.deviceExpiresIn, JSON.stringify(d));
|
||
assert(d.expiresAt && Math.abs(new Date(d.expiresAt) - Date.now() - 365 * 86400 * 1000) < 60000, `应给出到期时间:${d.expiresAt}`);
|
||
|
||
// 记录是在「确认成功」之后才建的,而且**归属就是确认登录的人**
|
||
assert(created, '确认后应创建扫描器记录');
|
||
assert(created.sn === 'SN-SCAN-01' && created.userId === userRow.id, JSON.stringify(created));
|
||
assert(!('secretHash' in created), '不再写密钥字段(已不用 sn+secret 那套)');
|
||
assert(created.lastRegisterAt instanceof Date && created.lastSeenAt instanceof Date, JSON.stringify(created));
|
||
assert(created.tokenJti, '创建后要写 jti(可用于撤销)');
|
||
|
||
// 下发的是**长期**扫描器 JWT(不是 7 天的用户令牌)
|
||
const ctx = app.createAnonymousContext();
|
||
const payload = ctx.service.jwt.verifyScanner(d.token);
|
||
assert(payload.typ === 'scanner' && payload.sn === 'SN-SCAN-01' && payload.jti, JSON.stringify(payload));
|
||
assert(Math.round((payload.exp - payload.iat) / 86400) === 365, `应为 365 天:${payload}`);
|
||
assert(ctx.service.jwt.verifyUser(d.token) === null, '长期令牌不能被当成用户令牌用');
|
||
|
||
// 同时返回设备信息与用户信息
|
||
assert(d.scanner.userId === userRow.id && d.scanner.sn === 'SN-SCAN-01', JSON.stringify(d.scanner));
|
||
assert(d.user.id === userRow.id && d.user.username === 'admin', JSON.stringify(d.user));
|
||
|
||
// 没带 SN 的设备也能用:服务端生成一个 SN 返回(设备存下来)
|
||
const auto = await scanFlow({});
|
||
assert(/^DEV-[0-9A-F]{12}$/.test(auto.res.body.data.sn), `应生成 SN:${auto.res.body.data.sn}`);
|
||
|
||
// 登录码一次性
|
||
assert(!(await fake.client.get(`packs:wechat:state:${code}`)), '确认结果取走后应删除登录码');
|
||
});
|
||
|
||
it('SN 已存在但无主(或曾被软删):由确认者认领/复活', async () => {
|
||
const fake = createFakeRedis();
|
||
mock(app, 'redis', fake.client);
|
||
const updates = [];
|
||
let restored = false;
|
||
const row = {
|
||
id: 5,
|
||
sn: 'SN-OLD-01',
|
||
name: '旧名字',
|
||
status: 1,
|
||
userId: null, // 无主:等一个账号来认领
|
||
deletedAt: new Date(), // 而且曾被删除
|
||
restore: async () => {
|
||
restored = true;
|
||
row.deletedAt = null;
|
||
},
|
||
};
|
||
mockModels({
|
||
async findOne(options) {
|
||
assert(options.paranoid === false, '要带上已删除的一起查(软删行仍占 sn 唯一键)');
|
||
return instance(row, updates);
|
||
},
|
||
});
|
||
|
||
const d = (await scanFlow({ sn: 'SN-OLD-01' })).res.body.data;
|
||
assert(d.status === 'confirmed', JSON.stringify(d));
|
||
assert(d.firstTime === false, '已存在的记录不算首次注册');
|
||
assert(d.secret === undefined, '不是首次注册,不应再返回密钥');
|
||
assert(restored, '软删过的记录要复活');
|
||
assert(updates[0].userId === userRow.id, `应认领给确认者:${JSON.stringify(updates)}`);
|
||
assert(d.scanner.id === 5 && d.scanner.userId === userRow.id, JSON.stringify(d.scanner));
|
||
assert(d.token.split('.').length === 3, '照样换发长期令牌');
|
||
});
|
||
|
||
it('SN 已绑定到别的账号:拒绝(403),不注册也不发令牌', async () => {
|
||
const fake = createFakeRedis();
|
||
mock(app, 'redis', fake.client);
|
||
mockModels({
|
||
async findOne() {
|
||
return instance({ id: 9, sn: 'SN-TAKEN-01', status: 1, userId: 999, secretHash: 'x' });
|
||
},
|
||
});
|
||
|
||
const { res } = await scanFlow({ sn: 'SN-TAKEN-01', expectPoll: 403 });
|
||
assert(res.body.ok === false, JSON.stringify(res.body));
|
||
assert(res.body.message.includes('其他账号'), JSON.stringify(res.body));
|
||
assert(res.body.data === undefined, '不能把令牌发出去');
|
||
});
|
||
|
||
it('设备被禁用(status=0):拒绝(403)', async () => {
|
||
const fake = createFakeRedis();
|
||
mock(app, 'redis', fake.client);
|
||
mockModels({
|
||
async findOne() {
|
||
return instance({ id: 9, sn: 'SN-OFF-01', status: 0, userId: null, secretHash: 'x' });
|
||
},
|
||
});
|
||
|
||
const { res } = await scanFlow({ sn: 'SN-OFF-01', expectPoll: 403 });
|
||
assert(res.body.message.includes('已被禁用'), JSON.stringify(res.body));
|
||
});
|
||
|
||
it('GET /api/device/login 码失效 → refreshed 换新码;wait 被 pollWait 封顶', async () => {
|
||
const fake = createFakeRedis();
|
||
mock(app, 'redis', fake.client);
|
||
mockModels({});
|
||
mock(app.config.wechat, 'pollWait', 1); // 把上限压到 1s,免得用例等 60s
|
||
|
||
// 不存在的码 → 立即给一张新码(设备直接换二维码继续轮询)
|
||
let res = await app.httpRequest().get('/api/device/login?sn=SN-SCAN-01&code=ZZZZZZ').expect(200);
|
||
const fresh = res.body.data.code;
|
||
assert(res.body.data.status === 'refreshed', JSON.stringify(res.body));
|
||
assert(/^[0-9A-Z]{6}$/.test(fresh) && fresh !== 'ZZZZZZ', `应换一张新码:${fresh}`);
|
||
assert(res.body.data.qrContent.endsWith(`/wechat?spm=1.0.${fresh}.1`), res.body.data.qrContent);
|
||
assert(res.body.data.device.sn === 'SN-SCAN-01', '换码时也要回显设备信息');
|
||
assert(await fake.client.get(`packs:wechat:state:${fresh}`) === 'pending', '新码应已登记');
|
||
|
||
// 挂着没人扫 → 等满上限后同样换新码
|
||
const started = Date.now();
|
||
res = await app.httpRequest().get(`/api/device/login?code=${fresh}&wait=999`).expect(200);
|
||
const cost = Date.now() - started;
|
||
assert(res.body.data.status === 'refreshed' && res.body.data.waited === 1, JSON.stringify(res.body.data));
|
||
assert(cost >= 900 && cost < 5000, `应等满 1s 上限(实测 ${cost}ms)`);
|
||
assert(res.body.data.code !== fresh, '应换一张新码');
|
||
|
||
// 码格式不对 → 422
|
||
res = await app.httpRequest().get('/api/device/login?code=abc').expect(422);
|
||
assert(res.body.message.includes('6 位'), JSON.stringify(res.body));
|
||
});
|
||
|
||
it('设备信息暂存:发码时带上、轮询时不用补齐,确认/换码都会沿用', async () => {
|
||
const fake = createFakeRedis();
|
||
mock(app, 'redis', fake.client);
|
||
const updates = [];
|
||
let created = null;
|
||
mockModels({
|
||
async findOne() {
|
||
return null;
|
||
},
|
||
async create(data) {
|
||
created = Object.assign({ id: 31, status: 1 }, data);
|
||
return instance(created, updates);
|
||
},
|
||
});
|
||
|
||
// ① 只在发码时带 sn + name
|
||
const issued = await app.httpRequest()
|
||
.get(`/api/device/login?sn=SN-STASH-01&name=${encodeURIComponent('暂存名字')}`)
|
||
.expect(200);
|
||
const code = issued.body.data.code;
|
||
assert(await fake.client.get(`packs:device:info:${code}`), '发码时应暂存设备信息');
|
||
|
||
// ② 换码(refreshed)时信息要跟着走到新码上(把 pollWait 压到 1s 触发换码)
|
||
mock(app.config.wechat, 'pollWait', 1);
|
||
const refreshed = await app.httpRequest().get(`/api/device/login?code=${code}&wait=1`).expect(200);
|
||
const newCode = refreshed.body.data.code;
|
||
assert(refreshed.body.data.status === 'refreshed', JSON.stringify(refreshed.body.data));
|
||
assert(refreshed.body.data.device.sn === 'SN-STASH-01' && refreshed.body.data.device.name === '暂存名字', JSON.stringify(refreshed.body.data.device));
|
||
assert(await fake.client.get(`packs:device:info:${newCode}`), '换码后信息应存到新码上');
|
||
|
||
// ③ 轮询**什么都不带**,确认后建出来的记录仍然带 sn 与名字
|
||
const polled = app.httpRequest().get(`/api/device/login?code=${newCode}&wait=10`).expect(200);
|
||
await sleep(150);
|
||
await app.httpRequest()
|
||
.post('/api/wechat/confirm')
|
||
.set('Authorization', `Bearer ${userJwt()}`)
|
||
.send({ code: newCode })
|
||
.expect(200);
|
||
|
||
const d = (await polled).body.data;
|
||
assert(d.status === 'confirmed' && d.firstTime === true, JSON.stringify(d));
|
||
assert(created.sn === 'SN-STASH-01' && created.name === '暂存名字', `应沿用暂存信息:${JSON.stringify(created)}`);
|
||
assert(!(await fake.client.get(`packs:device:info:${newCode}`)), '取走后应删除暂存');
|
||
});
|
||
|
||
it('二维码地址:没配 SITE_URL 用请求的 origin,配了就优先用配置的域名', async () => {
|
||
const fake = createFakeRedis();
|
||
mock(app, 'redis', fake.client);
|
||
mockModels({});
|
||
|
||
let d = (await app.httpRequest().get('/api/device/login').expect(200)).body.data;
|
||
assert(/^https?:\/\//.test(d.origin) && d.qrContent === `${d.origin}/wechat?spm=1.0.${d.code}.1`, JSON.stringify(d));
|
||
|
||
mock(app.config.email, 'siteUrl', 'https://pack.example.com/');
|
||
d = (await app.httpRequest().get('/api/device/login').expect(200)).body.data;
|
||
assert(d.origin === 'https://pack.example.com', `尾部斜杠应被去掉:${d.origin}`);
|
||
assert(d.qrContent === `https://pack.example.com/wechat?spm=1.0.${d.code}.1`, d.qrContent);
|
||
assert(d.qrImageUrl === `https://pack.example.com/api/wechat/qrcode.svg?code=${d.code}`, d.qrImageUrl);
|
||
});
|
||
|
||
it('令牌时长可调:?expiresIn=30d 按该时长下发;超上限 / 格式错返回 422', async () => {
|
||
const fake = createFakeRedis();
|
||
mock(app, 'redis', fake.client);
|
||
mockModels({
|
||
async findOne() {
|
||
return null;
|
||
},
|
||
async create(data) {
|
||
return instance(Object.assign({ id: 31, status: 1 }, data));
|
||
},
|
||
});
|
||
const ctx = app.createAnonymousContext();
|
||
const spanDays = (token) => {
|
||
const p = ctx.service.jwt.verifyScanner(token);
|
||
return Math.round((p.exp - p.iat) / 86400);
|
||
};
|
||
const run = async (sn, extra) => {
|
||
const issued = await app.httpRequest().get(`/api/device/login?sn=${sn}${extra}`).expect(200);
|
||
const code = issued.body.data.code;
|
||
const polled = app.httpRequest().get(`/api/device/login?sn=${sn}${extra}&code=${code}&wait=10`).expect(200);
|
||
await sleep(150);
|
||
await app.httpRequest()
|
||
.post('/api/wechat/confirm')
|
||
.set('Authorization', `Bearer ${userJwt()}`)
|
||
.send({ code })
|
||
.expect(200);
|
||
return (await polled).body.data;
|
||
};
|
||
|
||
// ① 不传 → 用服务端配置(默认 365d)
|
||
const base = await run('SN-DUR-01', '');
|
||
assert(base.expiresIn === app.config.jwt.deviceExpiresIn && spanDays(base.token) === 365, JSON.stringify(base));
|
||
assert(Math.abs(new Date(base.expiresAt) - Date.now() - 365 * 86400 * 1000) < 60000, base.expiresAt);
|
||
|
||
// ② 申请更短的 30d → 下发的 JWT 就按 30 天
|
||
const shorter = await run('SN-DUR-02', '&expiresIn=30d');
|
||
assert(shorter.expiresIn === '30d' && spanDays(shorter.token) === 30, JSON.stringify(shorter));
|
||
assert(Math.abs(new Date(shorter.expiresAt) - Date.now() - 30 * 86400 * 1000) < 60000, shorter.expiresAt);
|
||
|
||
// ③ 秒数写法 3600
|
||
const seconds = await run('SN-DUR-03', '&expiresIn=3600');
|
||
assert(seconds.expiresIn === 3600, JSON.stringify(seconds));
|
||
const payload = ctx.service.jwt.verifyScanner(seconds.token);
|
||
assert(payload.exp - payload.iat === 3600, `应按 3600s 签发:${payload.exp - payload.iat}`);
|
||
|
||
// ④ 超过服务端上限 → 422(连码都不发):不允许单个设备自己把令牌拉长
|
||
let res = await app.httpRequest().get('/api/device/login?sn=SN-DUR-04&expiresIn=999d').expect(422);
|
||
assert(res.body.message.includes('不能超过服务端上限'), JSON.stringify(res.body));
|
||
|
||
// ⑤ 格式不对 → 422
|
||
res = await app.httpRequest().get('/api/device/login?sn=SN-DUR-05&expiresIn=abc').expect(422);
|
||
assert(res.body.message.includes('格式不对'), JSON.stringify(res.body));
|
||
|
||
// ⑥ 服务端配置改小(DEVICE_JWT_EXPIRES=10d):默认值与上限一起变
|
||
mock(app.config.jwt, 'deviceExpiresIn', '10d');
|
||
const ten = await run('SN-DUR-06', '');
|
||
assert(ten.expiresIn === '10d' && spanDays(ten.token) === 10, JSON.stringify(ten));
|
||
await app.httpRequest().get('/api/device/login?sn=SN-DUR-07&expiresIn=30d').expect(422);
|
||
});
|
||
|
||
it('设备长轮询:客户端断开后立刻停止等待(不换码、释放订阅连接)', async () => {
|
||
const fake = createFakeRedis();
|
||
mock(app, 'redis', fake.client);
|
||
mockModels({});
|
||
|
||
const issued = await app.httpRequest().get('/api/device/login?sn=SN-SCAN-01').expect(200);
|
||
const code = issued.body.data.code;
|
||
assert(await fake.client.get(`packs:wechat:state:${code}`) === 'pending');
|
||
|
||
// 自己起一个真实监听端口,手动发请求再 destroy(设备重启/切页就是这样)
|
||
const server = http.createServer(app.callback()).listen(0);
|
||
await new Promise(resolve => server.once('listening', resolve));
|
||
const port = server.address().port;
|
||
|
||
const request = http.request({
|
||
host: '127.0.0.1',
|
||
port,
|
||
method: 'GET',
|
||
path: `/api/device/login?sn=SN-SCAN-01&code=${code}&wait=60`,
|
||
});
|
||
request.on('error', () => {}); // abort 后本地也会报错,忽略
|
||
request.end();
|
||
await sleep(300);
|
||
assert(fake.activeSubscribers() === 1, '长轮询应该还挂着(1 个订阅连接)');
|
||
|
||
const started = Date.now();
|
||
request.destroy(); // 设备断开
|
||
await sleep(300);
|
||
|
||
assert(fake.activeSubscribers() === 0, '断开后应立刻释放订阅连接(说明没等满 60s)');
|
||
assert(Date.now() - started < 5000, '不应等满 wait');
|
||
assert(await fake.client.get(`packs:wechat:state:${code}`) === 'pending', '断开时不应把登录码换掉');
|
||
|
||
await new Promise(resolve => server.close(resolve));
|
||
});
|
||
|
||
it('POST /api/device/refresh:刷新令牌换新访问令牌,并轮换刷新令牌', async () => {
|
||
const refresh = 'r1-' + crypto.randomBytes(16).toString('hex');
|
||
const hash = crypto.createHash('sha256').update(refresh).digest('hex');
|
||
const updates = [];
|
||
|
||
const row = {
|
||
id: 31,
|
||
sn: 'SN-REFRESH-01',
|
||
status: 1,
|
||
deletedAt: null,
|
||
refreshTokenHash: hash,
|
||
refreshExpiresAt: new Date(Date.now() + 24 * 3600 * 1000),
|
||
};
|
||
const scanner = instance(row, updates);
|
||
|
||
mockModels({
|
||
async findOne({ where }) {
|
||
return where.refreshTokenHash === hash ? scanner : null;
|
||
},
|
||
});
|
||
|
||
const res = await app.httpRequest()
|
||
.post('/api/device/refresh')
|
||
.send({ refreshToken: refresh, sn: 'SN-REFRESH-01' })
|
||
.expect(200);
|
||
|
||
const d = res.body.data;
|
||
assert(d.sn === 'SN-REFRESH-01', JSON.stringify(d));
|
||
assert(d.token && d.token.split('.').length === 3, '应返回新的访问令牌');
|
||
assert(d.tokenType === 'Bearer', d.tokenType);
|
||
assert(d.refreshToken && d.refreshToken !== refresh, '刷新令牌应轮换');
|
||
assert(d.refreshExpiresIn === app.config.jwt.deviceRefreshExpiresIn, `应返回刷新令牌时长:${d.refreshExpiresIn}`);
|
||
|
||
// 新访问令牌是合法的设备令牌(不可预知旧 jti)
|
||
const ctx = app.createAnonymousContext();
|
||
const payload = ctx.service.jwt.verifyScanner(d.token);
|
||
assert(payload.typ === 'scanner' && payload.sn === 'SN-REFRESH-01', JSON.stringify(payload));
|
||
|
||
// 库里存的是新刷新令牌的 sha256,不是原文
|
||
const newHash = crypto.createHash('sha256').update(d.refreshToken).digest('hex');
|
||
const stored = updates.find(item => item.refreshTokenHash);
|
||
assert(stored && stored.refreshTokenHash === newHash, '应只存新刷新令牌的 sha256');
|
||
assert(!JSON.stringify(updates).includes(d.refreshToken), '库里不能出现刷新令牌原文');
|
||
});
|
||
|
||
it('POST /api/device/refresh:无效 / 过期 / 禁用 / SN 不匹配都拒绝', async () => {
|
||
const refresh = 'r2-' + crypto.randomBytes(16).toString('hex');
|
||
const hash = crypto.createHash('sha256').update(refresh).digest('hex');
|
||
|
||
const makeRow = (patch = {}) => instance(Object.assign({
|
||
id: 32,
|
||
sn: 'SN-REFRESH-02',
|
||
status: 1,
|
||
deletedAt: null,
|
||
refreshTokenHash: hash,
|
||
refreshExpiresAt: new Date(Date.now() + 24 * 3600 * 1000),
|
||
}, patch));
|
||
|
||
// ① 查不到 → 401
|
||
mockModels({ async findOne() { return null; } });
|
||
await app.httpRequest().post('/api/device/refresh').send({ refreshToken: 'nope' }).expect(401);
|
||
|
||
// ② 已过期 → 401
|
||
mockModels({ async findOne() { return makeRow({ refreshExpiresAt: new Date(Date.now() - 1000) }); } });
|
||
await app.httpRequest().post('/api/device/refresh').send({ refreshToken: refresh }).expect(401);
|
||
|
||
// ③ 被禁用 → 403
|
||
mockModels({ async findOne() { return makeRow({ status: 0 }); } });
|
||
await app.httpRequest().post('/api/device/refresh').send({ refreshToken: refresh }).expect(403);
|
||
|
||
// ④ SN 不匹配 → 401
|
||
mockModels({ async findOne() { return makeRow(); } });
|
||
await app.httpRequest()
|
||
.post('/api/device/refresh')
|
||
.send({ refreshToken: refresh, sn: 'SN-OTHER' })
|
||
.expect(401);
|
||
|
||
// ⑤ 缺 refreshToken → 400
|
||
await app.httpRequest().post('/api/device/refresh').send({}).expect(400);
|
||
});
|
||
});
|