- 主体状态缓存(Redis 优先、进程内兜底):设备心跳与上报判断不再查库,续期/停用后主动失效 - 上报写接口按缓存校验期限:过期 403 subject_expired、停用 subject_disabled、主体缺失 subject_missing - 心跳与 /api/scanner/me 返回 subject 状态,桌面端据此暂停推送并在续期后自动补传积压 - 新增续期订单(subject_orders)与接口,支付回调 POST /api/pay/notify 幂等、支持 HMAC 签名, 另提供内部令牌模拟支付用于联调 - 顺带提交工作区中已完成的「登录协议」后端改动(agreement):与本次改动共用 router.js / config.default.js Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
248 lines
11 KiB
JavaScript
248 lines
11 KiB
JavaScript
'use strict';
|
||
|
||
const { app, mock, assert } = require('egg-mock/bootstrap');
|
||
const bcrypt = require('bcryptjs');
|
||
const jwt = require('jsonwebtoken');
|
||
const createFakeRedis = require('../../utils/fake-redis');
|
||
|
||
const instance = (data) => Object.assign(
|
||
{
|
||
toJSON: () => data,
|
||
update: async (fields) => Object.assign(data, fields),
|
||
},
|
||
data,
|
||
);
|
||
|
||
describe('test/app/controller/web.test.js', () => {
|
||
const passwordHash = bcrypt.hashSync('secret-pass', 4);
|
||
const userRow = {
|
||
id: 1,
|
||
username: 'admin',
|
||
nickname: '管理员',
|
||
email: 'admin@example.com',
|
||
phone: '13800000001',
|
||
status: 1,
|
||
passwordHash,
|
||
};
|
||
|
||
/** 用户模型:按账号查 / 按主键查 */
|
||
function mockUser(user = userRow) {
|
||
mock(app, 'model', {
|
||
User: {
|
||
async findOne() {
|
||
return instance(Object.assign({}, user, { update: async fields => Object.assign(user, fields) }));
|
||
},
|
||
async findByPk(id) {
|
||
return instance(Object.assign({}, user, { id }));
|
||
},
|
||
},
|
||
});
|
||
}
|
||
|
||
it('POST /api/web/auth/login:账号密码换取 user JWT(不依赖 cookie/CSRF)', async () => {
|
||
mock(app, 'redis', createFakeRedis().client);
|
||
mockUser();
|
||
|
||
const res = await app.httpRequest()
|
||
.post('/api/web/auth/login')
|
||
.send({ account: 'admin', password: 'secret-pass' })
|
||
.expect(200);
|
||
|
||
assert(res.body.ok === true, JSON.stringify(res.body));
|
||
const { token, tokenType, expiresIn, user } = res.body.data;
|
||
assert(tokenType === 'Bearer' && expiresIn === app.config.jwt.userExpiresIn, JSON.stringify(res.body.data));
|
||
assert(user.id === 1 && user.username === 'admin' && user.passwordHash === undefined, JSON.stringify(user));
|
||
|
||
const payload = jwt.decode(token);
|
||
assert(payload.typ === 'user' && Number(payload.sub) === 1, JSON.stringify(payload));
|
||
assert(!(res.headers['set-cookie'] || []).some(item => item.startsWith('packs_sess')), '不应下发登录态 cookie');
|
||
});
|
||
|
||
it('POST /api/web/auth/login:密码错 / 缺参', async () => {
|
||
mock(app, 'redis', createFakeRedis().client);
|
||
mockUser();
|
||
|
||
let res = await app.httpRequest().post('/api/web/auth/login').send({ account: 'admin', password: 'wrong' }).expect(401);
|
||
assert(res.body.status === 'unauthorized' && res.body.message.includes('账号或密码错误'), JSON.stringify(res.body));
|
||
|
||
res = await app.httpRequest().post('/api/web/auth/login').send({ account: 'admin' }).expect(422);
|
||
assert(res.body.ok === false, JSON.stringify(res.body));
|
||
});
|
||
|
||
const requiredAgreement = {
|
||
id: 9,
|
||
code: 'user_agreement',
|
||
name: '用户协议',
|
||
required: true,
|
||
version: { id: 11, version: '1.0.0', title: '用户协议', content: '正文' },
|
||
};
|
||
|
||
it('POST /api/web/auth/login:小程序未同意协议 → 428 agreement_required', async () => {
|
||
mock(app, 'redis', createFakeRedis().client);
|
||
mockUser();
|
||
app.mockService('agreement', 'requiredVersions', async () => [ requiredAgreement ]);
|
||
|
||
const res = await app.httpRequest()
|
||
.post('/api/web/auth/login')
|
||
.send({ account: 'admin', password: 'secret-pass', client: 'mini_program' })
|
||
.expect(428);
|
||
|
||
assert(res.body.status === 'agreement_required', JSON.stringify(res.body));
|
||
assert(res.body.data.agreements[0].code === 'user_agreement', JSON.stringify(res.body));
|
||
});
|
||
|
||
it('POST /api/web/auth/login:小程序同意当前版本 → 记录版本并登录成功', async () => {
|
||
mock(app, 'redis', createFakeRedis().client);
|
||
mockUser();
|
||
|
||
let recorded = null;
|
||
app.mockService('agreement', 'requiredVersions', async () => [ requiredAgreement ]);
|
||
app.mockService('agreement', 'record', async (userId, accepted) => {
|
||
recorded = { userId, accepted };
|
||
return accepted.map(item => ({
|
||
code: item.code,
|
||
versionId: item.versionId,
|
||
version: item.version,
|
||
agreedAt: new Date().toISOString(),
|
||
}));
|
||
});
|
||
|
||
const res = await app.httpRequest()
|
||
.post('/api/web/auth/login')
|
||
.send({
|
||
account: 'admin',
|
||
password: 'secret-pass',
|
||
client: 'mini_program',
|
||
agreements: [{ code: 'user_agreement', versionId: 11 }],
|
||
})
|
||
.expect(200);
|
||
|
||
assert(res.body.ok === true, JSON.stringify(res.body));
|
||
assert(recorded && recorded.userId === 1, JSON.stringify(recorded));
|
||
assert(recorded.accepted[0].versionId === 11 && recorded.accepted[0].version === '1.0.0', JSON.stringify(recorded));
|
||
assert(res.body.data.agreements[0].version === '1.0.0', JSON.stringify(res.body.data));
|
||
});
|
||
|
||
it('GET /api/web/me / PUT /api/web/me / PUT /api/web/me/password:都按令牌里的用户操作', async () => {
|
||
mock(app, 'redis', createFakeRedis().client);
|
||
let updated = null;
|
||
/** ⚠️ mock 会忽略 attributes.exclude,这里手动模拟 service 的 SAFE_ATTRIBUTES(不吐密码哈希) */
|
||
const safeRow = () => {
|
||
const { passwordHash: _omit, ...safe } = userRow;
|
||
return safe;
|
||
};
|
||
mock(app, 'model', {
|
||
User: {
|
||
// 真 service 的行为:默认不返回密码哈希,只有显式 include('passwordHash') 时才带
|
||
async findByPk(id, options) {
|
||
assert(String(id) === '1');
|
||
const wantHash = Boolean(options?.attributes?.include?.includes('passwordHash'));
|
||
const data = wantHash ? Object.assign({}, userRow) : safeRow();
|
||
const row = instance(data);
|
||
// update 要同时写进实例的 toJSON 数据,否则控制器回显还是旧值
|
||
row.update = async fields => {
|
||
updated = Object.assign(updated || {}, fields);
|
||
Object.assign(data, fields);
|
||
Object.assign(userRow, fields);
|
||
};
|
||
return row;
|
||
},
|
||
},
|
||
});
|
||
|
||
const token = app.createAnonymousContext().service.jwt.signUser(userRow);
|
||
const auth = { Authorization: `Bearer ${token}` };
|
||
|
||
let res = await app.httpRequest().get('/api/web/me').set(auth).expect(200);
|
||
assert(res.body.data.username === 'admin' && res.body.data.passwordHash === undefined, JSON.stringify(res.body.data));
|
||
await app.httpRequest().get('/api/web/me').expect(401);
|
||
|
||
res = await app.httpRequest().put('/api/web/me').set(auth).send({ nickname: '新昵称' }).expect(200);
|
||
assert(res.body.data.nickname === '新昵称' && updated.nickname === '新昵称', JSON.stringify(updated));
|
||
|
||
// 改密码:原密码错 → 422;正确 → 200
|
||
await app.httpRequest().put('/api/web/me/password').set(auth).send({ oldPassword: 'nope', newPassword: 'new-pass' }).expect(422);
|
||
await app.httpRequest().put('/api/web/me/password').set(auth).send({ oldPassword: 'secret-pass', newPassword: 'new-pass' }).expect(200);
|
||
assert(await bcrypt.compare('new-pass', userRow.passwordHash), '应写入新密码哈希');
|
||
});
|
||
|
||
it('POST /api/web/auth/forgot:邮箱未注册也返回成功(防账号枚举)', async () => {
|
||
mock(app, 'redis', createFakeRedis().client);
|
||
mock(app, 'model', {
|
||
User: { async findOne() { return null; } },
|
||
});
|
||
|
||
const res = await app.httpRequest().post('/api/web/auth/forgot').send({ email: 'nobody@example.com' }).expect(200);
|
||
assert(res.body.data.sent === true && res.body.data.url === undefined, JSON.stringify(res.body));
|
||
|
||
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);
|
||
|
||
const res = await app.httpRequest().get('/api/wechat/qrcode.svg?code=AB12CD').expect(200);
|
||
assert(String(res.headers['content-type']).includes('image/svg+xml'), res.headers['content-type']);
|
||
// SVG 是二进制类响应,supertest 可能只给 res.body(Buffer)
|
||
const svg = res.text || String(res.body);
|
||
assert(svg.includes('<svg'), '应返回 SVG 源码');
|
||
assert(!/<image|xlink:href/i.test(svg), '不能引用外部资源');
|
||
});
|
||
});
|