liufumingren bd2363bf00 chore: 初始化仓库(backend / frontend / extension 三块)
- backend/:Egg 3 纯 JSON 接口服务(MySQL 8 + Redis),全部走 header 令牌鉴权;
  已彻底去掉服务端渲染(删除 page 控制器 / app/view / nunjucks / session / CSRF),
  开发时把页面请求反代到前端 dev server,生产托管 frontend/dist(SPA 回退)。
  单测 91 个通过(不需要本机数据库)。
- frontend/:Vite + Vue3 + TypeScript 的 SPA(登录 / 注册 / 找回密码 / 扫码登录与确认 /
  首页统计 / 设备管理 / 扫码记录 / 个人中心 / 测试页),vue-tsc 类型检查与构建通过。
- extension/:MV3 浏览器扩展(零构建),注入第三方 WMS 页面识别运单号并打开溯源页。
- 忽略规则统一放根 .gitignore:node_modules、dist、logs / logs-*、run、typings、
  .env*、config.local.js(含本机数据库与 Redis 密码,绝不入库)。
2026-10-17 08:50:32 +08:00

138 lines
5.8 KiB
JavaScript
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.

'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));
});
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('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), '不能引用外部资源');
});
});