diff --git a/backend/test/app/controller/device.test.js b/backend/test/app/controller/device.test.js index bc7fb95..4814b8a 100644 --- a/backend/test/app/controller/device.test.js +++ b/backend/test/app/controller/device.test.js @@ -2,6 +2,7 @@ const { app, mock, assert } = require('egg-mock/bootstrap'); const http = require('http'); +const crypto = require('crypto'); const createFakeRedis = require('../../utils/fake-redis'); /** 等一会儿(用来模拟「挂上长轮询之后,手机才确认」) */ @@ -386,4 +387,85 @@ describe('test/app/controller/device.test.js', () => { 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); + }); }); diff --git a/backend/test/app/controller/scan.test.js b/backend/test/app/controller/scan.test.js index a90f9a4..92a3f2c 100644 --- a/backend/test/app/controller/scan.test.js +++ b/backend/test/app/controller/scan.test.js @@ -349,6 +349,164 @@ describe('test/app/controller/scan.test.js', () => { assert(res.body.data.received === 2 && res.body.data.inserted === 1 && res.body.data.duplicated === 1); }); + it('POST /api/scan/records 同一运单 24 小时内重复扫描:只入库最新一条(跨通道也算)', async () => { + let rows = null; + mock(app, 'model', { + User: {}, + Scanner: { async findByPk() { return instance(authScanner()); } }, + ScanChannel: { + async findAll() { return [ { channelId: '1' }, { channelId: '2' } ]; }, + async bulkCreate(items) { return items; }, + async update() { return [ 1 ]; }, + }, + ScanRecord: { + async findAll() { return []; }, + async bulkCreate(items) { + rows = items; + return items; + }, + }, + }); + + const res = await app.httpRequest() + .post('/api/scan/records') + .set('Authorization', token()) + .send({ + records: [ + { barcode: 'R1', scanTime: '2026-10-19 16:30:52', channelId: '1' }, + { barcode: 'R1', scanTime: '2026-10-19 16:31:04', channelId: '1' }, + { barcode: 'R1', scanTime: '2026-10-19 17:12:37', channelId: '2' }, + ], + }) + .expect(200); + + assert(rows.length === 1, '同一运单只入库一条'); + assert(rows[0].scanTime.getTime() === new Date('2026-10-19T17:12:37').getTime(), '取最后一次扫描时间'); + assert(res.body.data.inserted === 1 && res.body.data.updated === 0 && res.body.data.suppressed === 2); + assert(res.body.data.duplicated === 0); + }); + + it('POST /api/scan/records 库里 24 小时内已有同一运单、本次更新 → 覆盖时间与工作台配置', async () => { + let inserted = false; + let updateArgs = null; + mock(app, 'model', { + User: {}, + Scanner: { async findByPk() { return instance(authScanner()); } }, + ScanChannel: { + async findAll() { return [ { channelId: '1' } ]; }, + async bulkCreate(items) { return items; }, + async update() { return [ 1 ]; }, + }, + ScanRecord: { + async findAll(options) { + // 第二次查询(24 小时合并)返回库里的历史记录 + if (options && options.where && options.where.barcode) { + return [ { id: 5, barcode: 'R2', scanTime: new Date('2026-10-19T08:00:00') } ]; + } + return []; + }, + async update(fields, options) { + updateArgs = { fields, options }; + return [ 1 ]; + }, + async bulkCreate() { + inserted = true; + return []; + }, + }, + }); + + const res = await app.httpRequest() + .post('/api/scan/records') + .set('Authorization', token()) + .send({ records: [{ barcode: 'R2', scanTime: '2026-10-19 20:00:00', channelId: '1' }] }) + .expect(200); + + assert(!inserted, '已有记录时不应再入库'); + assert(res.body.data.inserted === 0 && res.body.data.updated === 1 && res.body.data.suppressed === 0); + assert(updateArgs && updateArgs.options.where.id === 5, '覆盖的是库里那条记录'); + assert(updateArgs.fields.scanTime.getTime() === new Date('2026-10-19T20:00:00').getTime(), '时间覆盖为最新'); + assert(updateArgs.fields.reportedAt instanceof Date); + }); + + it('POST /api/scan/records 库里已有更晚的同一运单 → 旧上报不回退时间', async () => { + let inserted = false; + let updated = false; + mock(app, 'model', { + User: {}, + Scanner: { async findByPk() { return instance(authScanner()); } }, + ScanChannel: { + async findAll() { return [ { channelId: '1' } ]; }, + async bulkCreate(items) { return items; }, + async update() { return [ 1 ]; }, + }, + ScanRecord: { + async findAll(options) { + if (options && options.where && options.where.barcode) { + return [ { id: 6, barcode: 'R4', scanTime: new Date('2026-10-19T21:00:00') } ]; + } + return []; + }, + async update() { + updated = true; + return [ 1 ]; + }, + async bulkCreate() { + inserted = true; + return []; + }, + }, + }); + + const res = await app.httpRequest() + .post('/api/scan/records') + .set('Authorization', token()) + .send({ records: [{ barcode: 'R4', scanTime: '2026-10-19 20:00:00', channelId: '1' }] }) + .expect(200); + + assert(!inserted && !updated, '更旧的上报既不入库也不覆盖'); + assert(res.body.data.inserted === 0 && res.body.data.updated === 0 && res.body.data.suppressed === 1); + }); + + it('POST /api/scan/records 距上一条超过 24 小时 → 算新的上报,正常入库', async () => { + let rows = null; + mock(app, 'model', { + User: {}, + Scanner: { async findByPk() { return instance(authScanner()); } }, + ScanChannel: { + async findAll() { return [ { channelId: '1' } ]; }, + async bulkCreate(items) { return items; }, + async update() { return [ 1 ]; }, + }, + ScanRecord: { + async findAll(options) { + if (options && options.where && options.where.barcode) { + // 假装数据库按 scanTime 范围过滤:24 小时外的老记录查不到 + const old = new Date('2026-10-18T09:00:00'); + const range = options.where.scanTime && options.where.scanTime[Op.between]; + if (range && (old < range[0] || old > range[1])) return []; + return [ { id: 7, barcode: 'R3', scanTime: old } ]; + } + return []; + }, + async update() { return [ 1 ]; }, + async bulkCreate(items) { + rows = items; + return items; + }, + }, + }); + + const res = await app.httpRequest() + .post('/api/scan/records') + .set('Authorization', token()) + .send({ records: [{ barcode: 'R3', scanTime: '2026-10-19 10:00:00', channelId: '1' }] }) + .expect(200); + + assert(rows.length === 1 && rows[0].barcode === 'R3'); + assert(res.body.data.inserted === 1 && res.body.data.updated === 0 && res.body.data.suppressed === 0); + }); + it('POST /api/scan/records 未知通道自动补建(通道名留空)', async () => { let channelRows = null; mock(app, 'model', { diff --git a/backend/test/app/controller/web.data.test.js b/backend/test/app/controller/web.data.test.js index 43588c4..19c0bcd 100644 --- a/backend/test/app/controller/web.data.test.js +++ b/backend/test/app/controller/web.data.test.js @@ -13,54 +13,79 @@ const instance = (data) => Object.assign( ); /** - * web 用户端的数据接口:我的设备 / 我的记录 / 我的统计 / 测试页模拟接口 + * web 主体端的数据接口:设备 / 扫码记录 / 首页统计 / 测试页模拟接口 * - * 重点断言:**范围一定限定在当前用户名下**(前端传的 userId 一律忽略), - * 别人的设备一律 404(不泄露存在性)。 + * 重点断言:**范围一定限定在当前主体下**(前端传的 userId / subjectId 一律忽略), + * 别的数据一律 404(不泄露存在性)。 + * + * 主体上下文由 `middleware/subject_auth.js` 解析 `X-Subject-Id`, + * 它要查 `SubjectMember.findOne` + `Subject.findByPk`,所以 mockModels 默认把这两个也备上。 */ describe('test/app/controller/web.data.test.js', () => { const me = { id: 1, username: 'admin', nickname: '管理员', status: 1 }; + const SUBJECT_ID = 5; const token = () => `Bearer ${app.createAnonymousContext().service.jwt.signUser(me)}`; + /** 带上令牌 + 主体 header */ + const setAuth = (req) => req.set('Authorization', token()).set('X-Subject-Id', String(SUBJECT_ID)); - /** 只替换用到的模型,User 固定返回当前登录用户 */ + /** 只替换用到的模型,User / 主体相关的固定返回当前用户与当前主体 */ function mockModels(models = {}) { mock(app, 'model', Object.assign({ User: { async findByPk() { return instance(me); } }, + SubjectMember: { + async findOne() { + return instance({ id: 11, subjectId: SUBJECT_ID, userId: 1, name: '管理员', role: 1, status: 1 }); + }, + }, + Subject: { + async findByPk() { + return instance({ + id: SUBJECT_ID, + name: '测试主体', + adminUserId: 1, + status: 1, + expireAt: new Date(Date.now() + 86400000), + }); + }, + }, }, models)); } - it('GET /api/web/devices:只列自己的设备(忽略前端传的 userId)', async () => { + it('GET /api/web/devices:只列本主体的设备(忽略前端传的 userId / subjectId)', async () => { mockModels({ Scanner: { async findAndCountAll(options) { - assert(options.where.userId === 1, '必须按当前用户过滤'); - return { rows: [ instance({ id: 7, sn: 'SN-7', userId: 1 }) ], count: 1 }; + assert(options.where.subjectId === SUBJECT_ID, '必须按当前主体过滤'); + return { rows: [ instance({ id: 7, sn: 'SN-7', subjectId: SUBJECT_ID }) ], count: 1 }; }, }, }); - const res = await app.httpRequest().get('/api/web/devices?userId=2').set('Authorization', token()).expect(200); + const res = await setAuth(app.httpRequest().get('/api/web/devices?userId=2&subjectId=99')).expect(200); assert(res.body.data.total === 1 && res.body.data.list[0].sn === 'SN-7', JSON.stringify(res.body)); // 没令牌 → 401 await app.httpRequest().get('/api/web/devices').expect(401); + // 有令牌没主体 → 400 subject_required + const missing = await app.httpRequest().get('/api/web/devices').set('Authorization', token()).expect(400); + assert(missing.body.status === 'subject_required', JSON.stringify(missing.body)); }); - it('GET /api/web/devices/:id:别人的设备返回 404(不暴露存在性)', async () => { + it('GET /api/web/devices/:id:别的主体的设备返回 404(不暴露存在性)', async () => { mockModels({ - Scanner: { async findByPk() { return instance({ id: 9, sn: 'SN-9', userId: 2 }); } }, + Scanner: { async findByPk() { return instance({ id: 9, sn: 'SN-9', subjectId: 999 }); } }, }); - await app.httpRequest().get('/api/web/devices/9').set('Authorization', token()).expect(404); - await app.httpRequest().delete('/api/web/devices/9').set('Authorization', token()).expect(404); - await app.httpRequest().post('/api/web/devices/9/unbind').set('Authorization', token()).expect(404); + await setAuth(app.httpRequest().get('/api/web/devices/9')).expect(404); + await setAuth(app.httpRequest().delete('/api/web/devices/9')).expect(404); + await setAuth(app.httpRequest().post('/api/web/devices/9/unbind')).expect(404); }); - it('GET /api/web/devices/:id/channels:看自己设备的通道', async () => { + it('GET /api/web/devices/:id/channels:看本主体设备的通道', async () => { let queriedId = 0; mockModels({ - Scanner: { async findByPk() { return instance({ id: 9, sn: 'SN-9', userId: 1 }); } }, + Scanner: { async findByPk() { return instance({ id: 9, sn: 'SN-9', subjectId: SUBJECT_ID }); } }, ScanChannel: { async findAll(options) { queriedId = options.where.scannerId; @@ -69,11 +94,11 @@ describe('test/app/controller/web.data.test.js', () => { }, }); - const res = await app.httpRequest().get('/api/web/devices/9/channels').set('Authorization', token()).expect(200); + const res = await setAuth(app.httpRequest().get('/api/web/devices/9/channels')).expect(200); assert(queriedId === 9 && res.body.data.list[0].channelId === 'CH-1', JSON.stringify(res.body)); }); - it('POST /api/web/devices/:id/unbind:解绑自己的设备(清掉归属)', async () => { + it('POST /api/web/devices/:id/unbind:解绑本主体的设备(清掉归属)', async () => { let updated = null; mockModels({ Scanner: { @@ -81,36 +106,35 @@ describe('test/app/controller/web.data.test.js', () => { return instance({ id: 9, sn: 'SN-9', - userId: 1, + subjectId: SUBJECT_ID, update: async fields => { updated = fields; }, }); }, }, }); - await app.httpRequest().post('/api/web/devices/9/unbind').set('Authorization', token()).expect(200); + await setAuth(app.httpRequest().post('/api/web/devices/9/unbind')).expect(200); assert(updated && updated.userId === null, JSON.stringify(updated)); }); - it('DELETE /api/web/devices/:id:删除自己的设备(软删除)', async () => { + it('DELETE /api/web/devices/:id:删除本主体的设备(软删除)', async () => { let destroyed = 0; mockModels({ Scanner: { - async findByPk() { return instance({ id: 9, sn: 'SN-9', userId: 1 }); }, + async findByPk() { return instance({ id: 9, sn: 'SN-9', subjectId: SUBJECT_ID }); }, async destroy({ where }) { destroyed = where.id; return 1; }, }, }); - await app.httpRequest().delete('/api/web/devices/9').set('Authorization', token()).expect(200); + await setAuth(app.httpRequest().delete('/api/web/devices/9')).expect(200); assert(destroyed === 9); }); - it('GET /api/web/records:只查自己设备的记录(deviceId 越权 404)', async () => { + it('GET /api/web/records:只查本主体设备的记录(deviceId 越权 404)', async () => { let seenWhere = null; mockModels({ Scanner: { async findAll() { return [ { id: 1 }, { id: 2 } ]; }, - async findByPk() { return instance({ id: 1, sn: 'SN-1', userId: 1 }); }, }, ScanRecord: { async findAndCountAll(options) { @@ -123,40 +147,39 @@ describe('test/app/controller/web.data.test.js', () => { }, }); - const res = await app.httpRequest().get('/api/web/records?barcode=6901').set('Authorization', token()).expect(200); - assert(seenWhere.scannerId[Op.in].join(',') === '1,2', '应限定在自己的设备范围内'); + const res = await setAuth(app.httpRequest().get('/api/web/records?barcode=6901')).expect(200); + assert(seenWhere.subjectId === SUBJECT_ID, '应限定在当前主体范围内'); assert(res.body.data.list[0].deviceSn === 'SN-1', JSON.stringify(res.body.data.list[0])); - // 只查其中一台(自己名下)→ 范围收窄成那一台 - await app.httpRequest().get('/api/web/records?deviceId=2').set('Authorization', token()).expect(200); - assert(seenWhere.scannerId[Op.in].join(',') === '2', '指定自己名下的设备时应只查这一台'); + // 只查其中一台(本主体的)→ 范围收窄成那一台 + await setAuth(app.httpRequest().get('/api/web/records?deviceId=2')).expect(200); + assert(seenWhere.scannerId[Op.in].join(',') === '2', '指定本主体设备时应只查这一台'); - // 别人的设备 id(100)→ 404 - await app.httpRequest().get('/api/web/records?deviceId=100').set('Authorization', token()).expect(404); + // 不属于本主体的设备 id(100)→ 404 + await setAuth(app.httpRequest().get('/api/web/records?deviceId=100')).expect(404); }); - it('GET /api/web/stats:设备/通道/记录数都限定在当前用户范围内', async () => { + it('GET /api/web/stats:设备/通道/记录数都限定在当前主体范围内', async () => { const wanted = []; mockModels({ Scanner: { - async findAll() { return [ { id: 3 }, { id: 4 } ]; }, async count({ where }) { - assert(where.userId === 1); + assert(where.subjectId === SUBJECT_ID); return 2; }, }, ScanChannel: { - async count({ where }) { wanted.push(where.scannerId[Op.in].join(',')); return 5; }, + async count({ where }) { wanted.push(where.subjectId); return 5; }, }, ScanRecord: { - async count({ where }) { wanted.push(where.scannerId[Op.in].join(',')); return 9; }, + async count({ where }) { wanted.push(where.subjectId); return 9; }, async findAndCountAll() { return { rows: [], count: 0 }; }, }, }); - const res = await app.httpRequest().get('/api/web/stats').set('Authorization', token()).expect(200); + const res = await setAuth(app.httpRequest().get('/api/web/stats')).expect(200); assert(res.body.data.deviceCount === 2 && res.body.data.channelCount === 5 && res.body.data.recordCount === 9, JSON.stringify(res.body)); - assert(wanted.every(item => item === '3,4'), `统计范围应限定在自己的设备: ${wanted.join('|')}`); + assert(wanted.every(item => item === SUBJECT_ID), `统计范围应限定在当前主体: ${wanted.join('|')}`); }); it('POST /api/web/test/device-login:以当前用户为确认人建/取设备并发长期令牌', async () => { @@ -169,18 +192,17 @@ describe('test/app/controller/web.data.test.js', () => { return instance(Object.assign({ id: 11 }, data)); }, async findByPk() { - return instance({ id: 11, sn: 'SN-TEST-01', userId: 1, tokenJti: 'j-1', status: 1 }); + return instance({ id: 11, sn: 'SN-TEST-01', userId: 1, subjectId: SUBJECT_ID, tokenJti: 'j-1', status: 1 }); }, }, }); - const res = await app.httpRequest() - .post('/api/web/test/device-login') - .set('Authorization', token()) + const res = await setAuth(app.httpRequest().post('/api/web/test/device-login')) .send({ sn: 'SN-TEST-01', name: '测试中控', vendor: 'ACME' }) .expect(200); - assert(created.userId === 1 && created.sn === 'SN-TEST-01' && created.vendor === 'ACME', JSON.stringify(created)); + assert(created.userId === 1 && created.subjectId === SUBJECT_ID, '设备要挂到当前主体'); + assert(created.sn === 'SN-TEST-01' && created.vendor === 'ACME', JSON.stringify(created)); assert(res.body.data.firstTime === true && res.body.data.tokenType === 'Bearer' && res.body.data.token, JSON.stringify(res.body.data)); const payload = app.createAnonymousContext().service.jwt.verifyScanner(res.body.data.token); assert(payload.typ === 'scanner' && Number(payload.sub) === 11, JSON.stringify(payload)); @@ -191,7 +213,7 @@ describe('test/app/controller/web.data.test.js', () => { { id: 11, sn: 'SN-TEST-01' }, Object.assign({ jti: 'j-1' }, extra), ); const scannerRow = () => instance({ - id: 11, sn: 'SN-TEST-01', userId: 1, status: 1, tokenJti: 'j-1', + id: 11, sn: 'SN-TEST-01', userId: 1, subjectId: SUBJECT_ID, status: 1, tokenJti: 'j-1', }); let inserted = 0; mockModels({ @@ -208,22 +230,20 @@ describe('test/app/controller/web.data.test.js', () => { }, }); - const res = await app.httpRequest() - .post('/api/web/test/scan') - .set('Authorization', token()) + const res = await setAuth(app.httpRequest().post('/api/web/test/scan')) .send({ sn: 'SN-TEST-01', token: sign(), channelId: 'CH-9', barcode: '6901234567892' }) .expect(200); assert(inserted === 1 && res.body.data.inserted === 1, JSON.stringify(res.body)); // SN 对不上 → 401;jti 过期(重新登录过)→ 401 - await app.httpRequest().post('/api/web/test/scan').set('Authorization', token()) + await setAuth(app.httpRequest().post('/api/web/test/scan')) .send({ sn: 'SN-OTHER', token: sign(), channelId: 'CH-9', barcode: 'x' }).expect(401); - await app.httpRequest().post('/api/web/test/scan').set('Authorization', token()) + await setAuth(app.httpRequest().post('/api/web/test/scan')) .send({ sn: 'SN-TEST-01', token: sign({ jti: 'j-old' }), channelId: 'CH-9', barcode: 'x' }).expect(401); // 用户令牌不能当设备令牌用 - await app.httpRequest().post('/api/web/test/scan').set('Authorization', token()) + await setAuth(app.httpRequest().post('/api/web/test/scan')) .send({ sn: 'SN-TEST-01', token: token().replace('Bearer ', ''), channelId: 'CH-9', barcode: 'x' }).expect(401); }); }); diff --git a/backend/test/app/controller/web.test.js b/backend/test/app/controller/web.test.js index 4ada1c9..65809e3 100644 --- a/backend/test/app/controller/web.test.js +++ b/backend/test/app/controller/web.test.js @@ -124,6 +124,62 @@ describe('test/app/controller/web.test.js', () => { await app.httpRequest().post('/api/web/auth/forgot').send({ email: 'bad' }).expect(422); }); + it('POST /api/web/auth/forgot:重发节流返回 429 + 友好文案(不是 500)', async () => { + const fake = createFakeRedis(); + mock(app, 'redis', fake.client); + mockUser(); + + // 第一次:正常发出(devMode 会把链接带回来) + const first = await app.httpRequest().post('/api/web/auth/forgot').send({ email: userRow.email }).expect(200); + assert(first.body.data.sent === true, JSON.stringify(first.body)); + assert((first.body.data.url || '').includes('/reset?token='), 'devMode 应回带令牌的链接'); + + // 立刻再发:命中 resendInterval 节流 → 429(之前是 500「服务器内部错误」,用户看不懂) + const again = await app.httpRequest().post('/api/web/auth/forgot').send({ email: userRow.email }).expect(429); + assert(again.body.status === 'throttled', JSON.stringify(again.body)); + assert(/秒后再试/.test(again.body.message), JSON.stringify(again.body)); + }); + + it('改密 / 重置密码后,旧 user JWT 立即失效(password_changed_at)', async () => { + const user = Object.assign({}, userRow, { passwordChangedAt: null }); + mock(app, 'redis', createFakeRedis().client); + mock(app, 'model', { + User: { + async findOne() { return instance(user); }, + async findByPk(id) { return instance(Object.assign(user, { id })); }, + }, + }); + + const cfgJwt = app.config.jwt; + const iat = Math.floor(Date.now() / 1000) - 600; // 10 分钟前签发 + const oldToken = jwt.sign( + { sub: String(userRow.id), username: 'admin', typ: 'user', iat }, + cfgJwt.secret, + { issuer: cfgJwt.issuer, audience: cfgJwt.audience, expiresIn: '1h' }, + ); + const oldAuth = { Authorization: `Bearer ${oldToken}` }; + + // 没改过密码:旧令牌正常可用 + await app.httpRequest().get('/api/web/me').set(oldAuth).expect(200); + + // 刚改过密码(改密时间晚于旧令牌的 iat)→ 旧令牌 401,且带明确原因 + user.passwordChangedAt = new Date((iat + 300) * 1000); + const stale = await app.httpRequest().get('/api/web/me').set(oldAuth).expect(401); + assert(stale.body.status === 'password_changed', JSON.stringify(stale.body)); + assert(/重新登录/.test(stale.body.message), JSON.stringify(stale.body)); + + // 改密之后重新签发的令牌(iat 更晚)照常可用 + const fresh = app.createAnonymousContext().service.jwt.signUser(Object.assign({}, userRow)); + await app.httpRequest().get('/api/web/me').set({ Authorization: `Bearer ${fresh}` }).expect(200); + + // 且 passwordChangedAt 不会漏给前端 + const me = await app.httpRequest().get('/api/web/me').set({ Authorization: `Bearer ${fresh}` }).expect(200); + assert(me.body.data.passwordChangedAt === undefined, JSON.stringify(me.body.data)); + + // 运维接口(internal_auth)同样拦旧令牌 + await app.httpRequest().get('/api/users').set(oldAuth).expect(401); + }); + it('GET /api/wechat/qrcode.svg:本地生成二维码(可直接给前端 img 用)', async () => { mock(app, 'redis', createFakeRedis().client); diff --git a/backend/test/app/service/pack.test.js b/backend/test/app/service/pack.test.js new file mode 100644 index 0000000..dcbfe12 --- /dev/null +++ b/backend/test/app/service/pack.test.js @@ -0,0 +1,134 @@ +'use strict'; + +const { app, assert } = require('egg-mock/bootstrap'); + +/** + * 运单回放查询(`service/pack`) + * + * 这块最容易错的不是查库,而是**时间区间怎么算**: + * - 团购:以扫码时间为基准,前后各留余量; + * - 散单:扫码 = 本次任务开始,**下一次扫码** = 本次任务结束, + * 两者之差超过最大录制时长要截断,再各扩前后余量; + * - 没有工作台快照 → 明确回 `kind = unknown`,别瞎拉流。 + * + * 所以这里只测纯函数 `buildPlan`,不碰数据库(快照/落库在 scan.test.js 里覆盖)。 + */ +describe('test/app/service/pack.test.js', () => { + let pack; + const scanTime = new Date('2026-10-18T10:00:00+08:00'); + + const snapshotOf = (overrides = {}) => ({ + v: 1, + channelId: '1', + channelName: '一号口', + workstation: { + id: 1, + code: 'WS-01', + name: '1号工作台', + wsType: 1, + recordBeforeSec: 60, + recordAfterSec: 60, + recordMaxSec: 240, + canvasWidth: 1920, + canvasHeight: 1080, + ...overrides, + }, + cameras: [ + { + cameraId: 2, + cameraName: '打包台1', + channelNo: 34, + streamType: 0, + nvrId: 1, + nvrName: '测试NVR', + nvrHost: '192.168.8.241', + nvrPort: 8000, + nvrUsername: 'admin', + layout: { x: 0, y: 0, width: 1920, height: 1080, zIndex: 0, sortNo: 1 }, + }, + ], + }); + + before(() => { + pack = app.createAnonymousContext().service.pack; + }); + + it('团购:以扫码时间为基准,前后各留配置的秒数', () => { + const plan = pack.buildPlan({ scanTime, snapshot: snapshotOf({ wsType: 2 }) }); + + assert(plan.kind === 'group'); + assert(plan.startTime.getTime() === scanTime.getTime() - 60 * 1000); + assert(plan.endTime.getTime() === scanTime.getTime() + 60 * 1000); + assert(plan.durationSec === 120, '时长应为 60 + 60 = 120 秒'); + }); + + it('散单:扫码 = 开始,下一次扫码 = 结束(并前后扩余量)', () => { + const next = new Date(scanTime.getTime() + 100 * 1000); // 下一次打包开始 +100s + const plan = pack.buildPlan({ scanTime, nextScanTime: next, snapshot: snapshotOf() }); + + assert(plan.kind === 'scatter'); + assert(plan.startTime.getTime() === scanTime.getTime() - 60 * 1000); + assert(plan.endTime.getTime() === next.getTime() + 60 * 1000); + assert(plan.durationSec === 220, '100 秒任务 + 前后各 60 = 220 秒'); + assert(plan.nextScanTime.getTime() === next.getTime()); + }); + + it('散单:两次扫码间隔超过最大录制时长时截断', () => { + const next = new Date(scanTime.getTime() + 400 * 1000); // 400s > maxSec 240 + const plan = pack.buildPlan({ scanTime, nextScanTime: next, snapshot: snapshotOf() }); + + assert(plan.kind === 'scatter'); + assert(plan.endTime.getTime() === scanTime.getTime() + (240 + 60) * 1000); + assert(plan.durationSec === 360, '240 秒截断 + 前后各 60 = 360 秒'); + }); + + it('散单:没有下一次扫码时按最大录制时长兜底', () => { + const plan = pack.buildPlan({ scanTime, nextScanTime: null, snapshot: snapshotOf() }); + + assert(plan.kind === 'scatter'); + assert(plan.durationSec === 360); + assert(plan.nextScanTime === null); + }); + + it('没有工作台快照:回 unknown,不给流(避免瞎拉视频)', () => { + const plan = pack.buildPlan({ scanTime, snapshot: null }); + + assert(plan.kind === 'unknown'); + assert(plan.startTime === null && plan.endTime === null); + assert(plan.streams.length === 0); + assert(plan.reason.includes('没有关联工作台')); + }); + + it('工作台绑了多个摄像头:每个摄像头一路流,带布局与画布尺寸', () => { + const snapshot = snapshotOf({ wsType: 2 }); + snapshot.cameras.push({ + cameraId: 13, + cameraName: 'Camera', + channelNo: 45, + streamType: 0, + nvrId: 1, + nvrName: '测试NVR', + nvrHost: '192.168.8.241', + nvrPort: 8000, + nvrUsername: 'admin', + layout: { x: 1200, y: 0, width: 720, height: 405, zIndex: 1, sortNo: 2 }, + }); + + const plan = pack.buildPlan({ scanTime, snapshot }); + + assert(plan.streams.length === 2); + assert(plan.streams[0].channelNo === 34 && plan.streams[1].channelNo === 45); + assert(plan.streams[1].layout.x === 1200); + assert(plan.streams[0].canvasWidth === 1920 && plan.streams[0].canvasHeight === 1080); + }); + + it('同一路流(录像机 + 通道 + 时段)只保留一份', () => { + const start = new Date('2026-10-18T02:00:00.000Z'); + const end = new Date('2026-10-18T02:02:00.000Z'); + const stream = { nvrId: 1, channelNo: 34, streamType: 0, startTime: start, endTime: end }; + + const deduped = pack.dedupStreams([ stream, { ...stream }, { ...stream, channelNo: 45 } ]); + + assert(deduped.length === 2); + }); +});