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

272 lines
10 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 { Service } = require('egg');
const { Op } = require('sequelize');
const crypto = require('crypto');
/**
* 扫描器(设备)service
*
* 设备**只有一种身份**:扫码登录换来的长期 JWT ——
* `GET /api/device/login`(设备发码 → 手机确认)→ `loginByScan()` 建/取记录 + 签长期 JWT,
* 库里只存当前令牌的 `jti`(重签 → 旧令牌立即失效)。
* 不再有「sn + secret 注册 / 登录」那套入口(`secret_hash` 列作为历史字段保留,不再写入)。
*/
/** 列表/详情默认不返回历史密钥字段与令牌标识 */
const SAFE_ATTRIBUTES = { exclude: [ 'secretHash', 'tokenJti' ] };
/** 关联用户时只带这几个展示字段 */
const USER_ATTRIBUTES = [ 'id', 'username', 'nickname' ];
/**
* 输出前兜底清洗:历史密钥字段与令牌标识(jti)永不外泄
* —— 即使 attributes 过滤被绕过(如单测 mock),这里也能兜住
*/
function sanitize(row) {
if (!row) return row;
const { secretHash, tokenJti, ...rest } = row;
return rest;
}
class ScannerService extends Service {
get Scanner() {
return this.app.model.Scanner;
}
/**
* 设备扫码登录:**登录即注册**(`GET /api/device/login` 的唯一落地方法)
*
* - 按 SN 找不到记录 → 现场 `create` 一条,归属 = 扫码确认的那个用户(这就是「注册」);
* - 找到「无主」记录(`user_id` 为空)→ 由确认者**认领**(软删除的顺手复活);
* - 找到「已属于别人」的记录 → **403**,拒绝(避免扫一下就把别人的设备换绑走);
* - 设备被禁用(`status = 0`)→ 403;
* - 无论走哪条路径都换发长期 JWT(`jti` 轮换 → 旧令牌立即失效)。
*
* ⚠️ 调用方必须已经确认过登录(`userId` 来自 `POST /api/wechat/confirm` 的确认人)
*
* @param {object} params { sn? 设备自报序列号(不传则服务端生成), name?, vendor?, model?, firmware?,
* userId 确认登录的用户, ip?, expiresIn? 令牌有效期(秒数,不传用 config.jwt.deviceExpiresIn) }
* @return {Promise<object>} 扫描器信息 + token(JWT) + firstTime(本次是否新建记录)
*/
async loginByScan({ sn, name, vendor, model, firmware, userId, ip, expiresIn } = {}) {
if (!userId) this.ctx.throw(401, '缺少确认登录的用户');
const finalSn = String(sn || '').trim() || `DEV-${crypto.randomBytes(6).toString('hex').toUpperCase()}`;
const include = [{ model: this.app.model.User, as: 'user', required: false, attributes: USER_ATTRIBUTES }];
// 带上已删除的一起查:软删的行仍占着 sn 唯一键(否则下面 create 会撞键 500)
const existing = await this.Scanner.findOne({
where: { sn: finalSn },
attributes: SAFE_ATTRIBUTES,
include,
paranoid: false,
});
const payload = { userId: Number(userId), lastLoginAt: new Date(), lastSeenAt: new Date() };
if (ip) payload.ip = ip;
if (name) payload.name = name;
if (vendor) payload.vendor = vendor;
if (model) payload.model = model;
if (firmware) payload.firmware = firmware;
let scanner;
let firstTime = false;
if (existing) {
// 已属于别的账号:拒绝(设备转让得先在原账号解绑)
if (existing.userId && Number(existing.userId) !== Number(userId)) {
this.ctx.logger.warn('[scanner] %s 已被用户 %s 绑定,拒绝用户 %s 的扫码登录', finalSn, existing.userId, userId);
this.ctx.throw(403, `扫描器 ${finalSn} 已绑定到其他账号,请先在原账号里解绑`);
}
if (Number(existing.status) !== 1) this.ctx.throw(403, '扫描器已被禁用');
if (existing.deletedAt) await existing.restore(); // 曾被删除 → 复活
await existing.update(payload);
scanner = existing;
} else {
// 首次「注册」:扫码确认成功才建记录,归属就是确认登录的那个人
firstTime = true;
scanner = await this.Scanner.create(Object.assign(payload, {
sn: finalSn,
lastRegisterAt: new Date(),
}));
}
const token = await this.issueToken(scanner, { expiresIn });
this.ctx.logger.info('[scanner] %s 扫码登录成功(%s,归属用户 %s)',
finalSn, firstTime ? '首次注册' : '已存在', userId);
return Object.assign(sanitize(scanner.toJSON()), {
token,
tokenType: 'Bearer',
firstTime,
});
}
/**
* 签发长期 JWT 并把 jti 写库
* 库里不保存令牌本体,靠 jti 比对实现撤销:重签后旧令牌立即失效
* @param {object} scanner 扫描器实例
* @param {object} options { expiresIn 覆盖有效期(秒数或 '30d' 写法,不传用 config.jwt.scannerExpiresIn) }
* @return {Promise<string>} JWT
*/
async issueToken(scanner, options = {}) {
const jti = crypto.randomUUID();
const token = this.ctx.service.jwt.signScanner(scanner, { jti }, { expiresIn: options.expiresIn });
await scanner.update({
tokenJti: jti,
tokenExpiresAt: this.ctx.service.jwt.expiresAtOf(token),
});
this.ctx.logger.info('[scanner] 已签发令牌: %s (jti=%s, expiresIn=%s)',
scanner.sn, jti, options.expiresIn || this.app.config.jwt.scannerExpiresIn);
return token;
}
/** 鉴权用:取实例(含 jti,用于和令牌里的 jti 比对) */
async findByIdForAuth(id) {
return this.Scanner.findByPk(id, { attributes: { include: [ 'tokenJti' ] } });
}
/**
* 用长期 JWT 换设备实例(校验链路与 `middleware/scanner_auth.js` 完全一致,实现在这里)
*
* 1. 验签 + 过期检查;2. 回查记录存在且 `status=1`;3. 比对库里的 jti(重签后旧令牌立即失效)。
* 任何一步不过直接抛 401/403。
*
* @param {string} token 长期 JWT
* @param {object} options { sn 额外要求令牌里的 SN 与它一致(测试页模拟上报用) }
* @return {Promise<object>} 设备实例(含 tokenJti)
*/
async resolveByToken(token, { sn } = {}) {
if (!token) this.ctx.throw(401, '缺少扫描器令牌(Authorization: Bearer <token>)');
const payload = this.ctx.service.jwt.verifyScanner(token);
const scanner = await this.findByIdForAuth(payload.sub);
if (!scanner) this.ctx.throw(401, '扫描器不存在或已被删除');
if (sn && scanner.sn !== String(sn).trim()) this.ctx.throw(401, '令牌与 SN 不匹配');
if (Number(scanner.status) !== 1) this.ctx.throw(403, '扫描器已被禁用');
if (payload.jti && scanner.tokenJti && payload.jti !== scanner.tokenJti) {
this.ctx.throw(401, '扫描器令牌已失效,请重新登录');
}
return scanner;
}
/** 心跳:刷新最近心跳时间与 IP */
async heartbeat(scanner, ip) {
const fields = { lastSeenAt: new Date() };
if (ip) fields.ip = ip;
await scanner.update(fields);
return sanitize(scanner.toJSON());
}
/** 绑定扫描器到账号(管理侧用:userId / username 二选一) */
async bind({ scannerId, sn, userId, username }) {
const scanner = await this.findByKey({ scannerId, sn });
if (!scanner) this.ctx.throw(404, '扫描器不存在');
const targetUserId = await this.resolveUserId({ userId, username });
if (!targetUserId) this.ctx.throw(422, 'userId 或 username 至少提供一个');
await scanner.update({ userId: targetUserId });
this.ctx.logger.info('[scanner] %s 绑定到用户 %s', scanner.sn, targetUserId);
return sanitize(scanner.toJSON());
}
/** 解绑(仅清掉归属关系,扫描器记录保留;设备可以再扫码重新认领) */
async unbind({ scannerId, sn }) {
const scanner = await this.findByKey({ scannerId, sn });
if (!scanner) return null;
await scanner.update({ userId: null });
return sanitize(scanner.toJSON());
}
/** 按主键 / SN 查扫描器 */
async findByKey({ scannerId, sn }) {
if (scannerId) return this.Scanner.findByPk(scannerId);
if (sn) return this.Scanner.findOne({ where: { sn } });
return null;
}
async findById(id) {
const scanner = await this.Scanner.findByPk(id, {
attributes: SAFE_ATTRIBUTES,
include: [{ model: this.app.model.User, as: 'user', required: false, attributes: USER_ATTRIBUTES }],
});
return scanner ? sanitize(scanner.toJSON()) : null;
}
/** 分页列表:keyword 模糊匹配 SN / 名称 / 型号 */
async list({ page = 1, pageSize = 20, keyword, userId, status } = {}) {
const size = Math.min(Number(pageSize) || 20, 100);
const current = Math.max(Number(page) || 1, 1);
const where = {};
if (userId) where.userId = Number(userId);
if (status !== undefined && status !== '' && status !== null) where.status = Number(status);
if (keyword) {
where[Op.or] = [
{ sn: { [Op.like]: `%${keyword}%` } },
{ name: { [Op.like]: `%${keyword}%` } },
{ model: { [Op.like]: `%${keyword}%` } },
];
}
const { rows, count } = await this.Scanner.findAndCountAll({
where,
attributes: SAFE_ATTRIBUTES,
include: [{ model: this.app.model.User, as: 'user', required: false, attributes: USER_ATTRIBUTES }],
limit: size,
offset: (current - 1) * size,
order: [[ 'id', 'DESC' ]],
});
return {
list: rows.map(row => sanitize(row.toJSON())),
total: count,
page: current,
pageSize: size,
};
}
/** 软删除扫描器 */
async remove(id) {
const affected = await this.Scanner.destroy({ where: { id } });
return affected > 0;
}
/** 总数(首页统计用) */
async count(where = {}) {
return this.Scanner.count({ where });
}
/**
* 某用户名下的设备 id 列表(用户端查「我的通道 / 我的记录 / 我的统计」时用来限定范围)
* @return {Promise<number[]>}
*/
async idsOfUser(userId) {
const rows = await this.Scanner.findAll({
attributes: [ 'id' ],
where: { userId: Number(userId) },
raw: true,
});
return rows.map(row => row.id);
}
/** userId / username(或手机号) → 用户 id,找不到抛 404 */
async resolveUserId({ userId, username }) {
if (userId) return Number(userId);
if (!username) return null;
const user = await this.ctx.service.user.findOneBy({ [Op.or]: [{ username }, { phone: username }] });
if (!user) this.ctx.throw(404, `用户不存在:${username}`);
return user.id;
}
}
module.exports = ScannerService;