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 密码,绝不入库)。
This commit is contained in:
commit
bd2363bf00
18
.gitattributes
vendored
Normal file
18
.gitattributes
vendored
Normal file
@ -0,0 +1,18 @@
|
||||
# 默认按文本处理并把行尾交给 git 归一化(仓库里存 LF)
|
||||
* text=auto
|
||||
|
||||
# 脚本按各自平台定行尾
|
||||
*.sh text eol=lf
|
||||
*.ps1 text eol=crlf
|
||||
*.bat text eol=crlf
|
||||
*.cmd text eol=crlf
|
||||
|
||||
# 二进制(别做行尾/文本转换)
|
||||
*.png binary
|
||||
*.jpg binary
|
||||
*.jpeg binary
|
||||
*.gif binary
|
||||
*.ico binary
|
||||
*.zip binary
|
||||
*.apk binary
|
||||
*.keystore binary
|
||||
50
.gitignore
vendored
Normal file
50
.gitignore
vendored
Normal file
@ -0,0 +1,50 @@
|
||||
# ============================================================
|
||||
# 仓库根忽略规则(backend / frontend / extension 通用)
|
||||
# 只在这一处维护;各子项目不必再各写一份(不带斜杠的规则对任意层级都生效)
|
||||
# ============================================================
|
||||
|
||||
# ---------- 依赖 ----------
|
||||
node_modules/
|
||||
.pnpm-store/
|
||||
|
||||
# ---------- 构建产物 ----------
|
||||
dist/
|
||||
build/
|
||||
release/
|
||||
coverage/
|
||||
.nyc_output/
|
||||
.vite/
|
||||
*.tsbuildinfo
|
||||
|
||||
# ---------- 运行期 / 日志 ----------
|
||||
# backend 的 logs/、dev:test 的 logs-test/、脚本产出的 run/
|
||||
logs/
|
||||
logs-*/
|
||||
run/
|
||||
tmp/
|
||||
*.log
|
||||
*.pid
|
||||
|
||||
# ---------- 环境变量与本地配置(含数据库/Redis 密码,绝不提交) ----------
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
config.local.js
|
||||
config.local.*.js
|
||||
|
||||
# ---------- Egg 自动生成的类型声明(typings/ 由 egg-ts-helper 生成) ----------
|
||||
typings/
|
||||
|
||||
# ---------- 编辑器 / 系统 ----------
|
||||
.vscode/*
|
||||
!.vscode/extensions.json
|
||||
!.vscode/settings.json
|
||||
.idea/
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
desktop.ini
|
||||
|
||||
# ---------- 临时文件 ----------
|
||||
*.tmp
|
||||
*.bak
|
||||
* - 副本.*
|
||||
65
README.md
Normal file
65
README.md
Normal file
@ -0,0 +1,65 @@
|
||||
# 云仓视频溯源系统
|
||||
|
||||
前后端分离 + 一个浏览器扩展,三个目录:
|
||||
|
||||
```
|
||||
packService/
|
||||
├── backend/ # Egg.js 3(纯 API;MySQL + Redis)
|
||||
├── frontend/ # Vite + Vue3 + TypeScript(用户端 SPA)
|
||||
└── extension/ # Chrome MV3 扩展:注入第三方 WMS 页面,把运单号加工成溯源入口
|
||||
```
|
||||
|
||||
## 端口约定(⚠️ 本机项目多,不要用 Vite 默认的 5173)
|
||||
|
||||
| 用途 | 端口 | 启动方式 |
|
||||
| --- | --- | --- |
|
||||
| 前端 dev(Vite) | **7301** | `cd frontend && npm run dev` |
|
||||
| 前端 preview(dist) | **7302** | `cd frontend && npm run preview` |
|
||||
| 后端 dev | **7001** | `cd backend && npm run dev` |
|
||||
| 后端 dev:test(与 7001 并存) | **7300** | `cd backend && $env:LOG_DIR='logs-test'; npm run dev:test` |
|
||||
| 扩展自测页(可选) | **7310** | `npx --yes http-server extension/test -p 7310` |
|
||||
|
||||
- 前端端口可用 `VITE_PORT=7303 npm run dev` 覆盖;`strictPort: true` → 端口被占用时**直接报错**,不会偷偷换端口(否则代理会对不上)。
|
||||
- 前端调接口走**同源代理**:Vite 把 `/api`、`/health` 反代到后端(默认 `127.0.0.1:7001`,用 `VITE_BACKEND` 覆盖)。
|
||||
- 联调更方便的做法:直接开后端 `:7001`,由后端(dev)把 `/` 反代到前端 dev server(`FRONTEND_DEV_SERVER`,默认 `http://127.0.0.1:7301`)。
|
||||
- **上线**:后端托管 `frontend/dist`(静态资源 + SPA fallback),`/` 出前端、`/api/*` 出 JSON。
|
||||
|
||||
## 身份与通讯约定
|
||||
|
||||
| 调用方 | 令牌 | 典型接口 |
|
||||
| --- | --- | --- |
|
||||
| 前端 SPA(用户端,toC:用户只管自己的设备/记录) | `Authorization: Bearer <user JWT>`(typ=user) | `/api/web/*`(登录/资料/设备/记录) |
|
||||
| 设备(扫描枪、中控) | `Authorization: Bearer <device JWT>`(typ=scanner) | `/api/device/login`、`/api/scanner/*`、`/api/scan/*` |
|
||||
| 公开 | 无 | `/api/wechat/{login,status,qrcode.svg}`、`/api/web/auth/*` |
|
||||
|
||||
前端**不用 cookie/session**:令牌存本地、放 header,所以没有跨域 cookie 与 CSRF 的问题
|
||||
(JWT 用 `typ` 声明隔离:用户令牌调设备接口一律 401)。
|
||||
|
||||
## 当前进度
|
||||
|
||||
- [x] 目录拆分为 `backend/` + `frontend/`
|
||||
- [x] 前端脚手架(Vite + Vue3 + TS)跑通,登录页走通 `/api/web/auth/*`
|
||||
- [x] 浏览器扩展 `extension/`(MV3,零构建):注入第三方 WMS 页面识别运单号 → 点击打开溯源页
|
||||
- [x] **后端去掉服务端渲染**:删除 `app/controller/page/`、`app/view/`、`app/lib/page.js`、nunjucks / session / CSRF 配置与依赖,后端只剩 JSON 接口
|
||||
- [x] 页面全部迁移到前端:登录 / 注册 / 找回密码 / 扫码 / 扫码确认 / 首页统计 / 设备管理 / 扫码记录 / 个人中心 / 测试页
|
||||
- [x] 后端 dev 反代前端(`app/middleware/frontend.js`)+ 生产托管 `frontend/dist`(SPA 深链回退)
|
||||
- [x] 运维接口加鉴权:`app/controller/admin/` → `internal/`,统一挂 `middleware.internalAuth()`
|
||||
- [x] 新增用户端接口:`/api/web/{stats,devices*,records,test/*}`(范围一律限定在令牌对应的那个用户)
|
||||
- [ ] 扩展:目标地址换成真实打包视频页(现在指向百度占位)—— 在扩展「设置」里改「目标地址模板」即可,需要真实地址
|
||||
|
||||
后端接口细节见 [`backend/README.md`](backend/README.md),扩展用法见 [`extension/README.md`](extension/README.md)。
|
||||
|
||||
## 常用环境变量
|
||||
|
||||
| 变量 | 默认值 | 作用 |
|
||||
| --- | --- | --- |
|
||||
| `PORT` | `7001` | 后端监听端口 |
|
||||
| `FRONTEND_DEV_SERVER` | `http://127.0.0.1:7301` | 开发时把页面请求反代到哪里 |
|
||||
| `FRONTEND_DIST` | `frontend/dist` | 生产托管的前端构建产物目录 |
|
||||
| `FRONTEND_ENABLE` | `true` | 关掉后后端不管页面(纯接口模式) |
|
||||
| `INTERNAL_TOKEN` | 空 | 运维接口的静态令牌(header `X-Internal-Token`);不配就只能靠白名单账号的 user JWT |
|
||||
| `INTERNAL_ADMIN_IDS` | `1` | 哪些用户 id 能调运维接口(逗号分隔) |
|
||||
| `SITE_URL` | 空 | 二维码 / 邮件里链接用的绝对域名(不配则用请求的 host) |
|
||||
| `VITE_PORT` / `VITE_BACKEND` | `7301` / `http://127.0.0.1:7001` | 前端 dev 端口 / 代理目标 |
|
||||
|
||||
> ⚠️ 运维接口的默认白名单是**内置管理员(id=1)**:上线前请配 `INTERNAL_TOKEN`,或把真正的管理员 id 写进 `INTERNAL_ADMIN_IDS`。
|
||||
713
backend/README.md
Normal file
713
backend/README.md
Normal file
@ -0,0 +1,713 @@
|
||||
# 云仓视频溯源系统(pack-service)
|
||||
|
||||
> 中文名(前端页面/邮件里显示的那个)在 **`config.siteName`** 里,默认「云仓视频溯源系统」,可用环境变量 `SITE_NAME` 覆盖 ——
|
||||
> 要改名只改这一处(邮件用 `app.config.siteName`)。
|
||||
> `pack-service` 只作为**技术标识**保留:npm 包名、JWT `issuer`、日志目录、`egg-scripts --title`。
|
||||
|
||||
基于 **Egg.js 3** 的**纯接口服务**(⚠️ **不再渲染任何页面**:模板引擎已移除,`/` 这一侧由
|
||||
`app/middleware/frontend.js` 反代给前端 dev server 或托管 `../frontend/dist`),
|
||||
数据库 **MySQL(Sequelize ORM)**,缓存与登录码用 **Redis**。
|
||||
|
||||
> 页面在隔壁 **`../frontend/`**(Vite + Vue3 + TS SPA);两个服务的端口与启动方式见仓库根目录的 `README.md`。
|
||||
|
||||
> 业务场景:**设备(扫描枪 / 中控)扫码登录** —— 设备屏幕显示二维码,已登录的手机确认一下;
|
||||
> 服务端在**确认那一刻**才把设备注册到那个账号名下,并下发**长期 JWT**(默认 1 年,库里存 `jti` 可随时撤销),
|
||||
> 之后设备调本服务的接口都靠这枚令牌鉴权。**只有这一条身份链路**(没有 sn + secret 那套)。
|
||||
|
||||
## 环境要求
|
||||
|
||||
- Node.js >= 18(Egg 3 要求 >= 14.20,建议用 18/20 LTS)
|
||||
- MySQL 5.7+ / 8.x
|
||||
- Redis 5+
|
||||
|
||||
## 目录结构
|
||||
|
||||
```
|
||||
packService/backend
|
||||
├── app
|
||||
│ ├── controller # **按「谁在调」分模块**(Egg 支持多级目录 → controller.internal.user)
|
||||
│ │ ├── home.js # GET /api/info 服务信息(公共)
|
||||
│ │ ├── health.js # GET /health 健康检查(公共)
|
||||
│ │ ├── web/ # **用户端(前端 SPA)**:user JWT(typ=user),只能动自己的数据
|
||||
│ │ │ ├── auth.js # /api/web/auth/{login,register,register/code,forgot,reset}
|
||||
│ │ │ ├── profile.js # /api/web/me [/password] 我的资料 / 改密码
|
||||
│ │ │ ├── stats.js # /api/web/stats 首页统计(按当前用户)
|
||||
│ │ │ ├── device.js # /api/web/devices* 我的设备(列表/详情/通道/解绑/删除)
|
||||
│ │ │ ├── record.js # /api/web/records 我的扫码记录(按自己设备过滤)
|
||||
│ │ │ └── test.js # /api/web/test/{device-login,scan} 前端测试页的模拟接口
|
||||
│ │ ├── internal/ # 运维/内部(❗需内部令牌,挂在 middleware.internalAuth() 后面)
|
||||
│ │ │ ├── user.js # /api/users* 用户 CRUD(含缓存)
|
||||
│ │ │ ├── wechat.js # /api/wechat/:appid/:openid、bind、tokens、解绑、用户的授权列表
|
||||
│ │ │ ├── config.js # /api/configs* 系统配置读写
|
||||
│ │ │ └── device.js # /api/scanners*、/api/scanner/{bind,unbind} 设备列表/详情/解绑/删除
|
||||
│ │ ├── auth/ # 公开的登录接口(发码 / 查码 / 微信回调,无需令牌)
|
||||
│ │ │ └── wechat.js # /api/wechat/{login,status,qrcode.svg,callback}
|
||||
│ │ ├── client/ # 小程序 / Win 客户端 / SPA(user JWT,typ=user)
|
||||
│ │ │ └── wechat.js # /api/wechat/confirm
|
||||
│ │ └── device/ # 设备(长期 JWT,typ=scanner)
|
||||
│ │ ├── auth.js # /api/device/login 扫码登录+注册(登录即注册,下发长期 JWT)
|
||||
│ │ ├── self.js # /api/scanner/{me,heartbeat} 自检 / 保活
|
||||
│ │ └── scan.js # /api/scan/* 中控上报通道 / 扫码记录(去重)
|
||||
│ ├── middleware
|
||||
│ │ ├── api_auth.js # **用户端接口鉴权(只认 header 令牌,不看 cookie/session)**
|
||||
│ │ ├── internal_auth.js # **运维/内部接口鉴权**(X-Internal-Token 或白名单账号的 user JWT)
|
||||
│ │ ├── scanner_auth.js # 扫描器 JWT 鉴权(Authorization: Bearer <token>)
|
||||
│ │ ├── frontend.js # **前端入口**:dev 反代前端 dev server / 生产托管 frontend/dist(SPA 回退)
|
||||
│ │ └── error_handler.js # 异常统一成 JSON(4xx 原消息 / 5xx 只回「服务器内部错误」)
|
||||
│ ├── model
|
||||
│ │ ├── user.js # users
|
||||
│ │ ├── wechat_oauth.js # wechat_oauth
|
||||
│ │ ├── sys_config.js # sys_config
|
||||
│ │ ├── scanner.js # scanners
|
||||
│ │ ├── scan_channel.js # scan_channels
|
||||
│ │ └── scan_record.js # scan_records(去重)
|
||||
│ ├── service
|
||||
│ │ ├── auth.js # 登录校验(bcrypt 密码比对)+ 自助注册
|
||||
│ │ ├── mail.js # 发邮件(邮箱验证码 / 重置密码链接;开发模式只写日志)
|
||||
│ │ ├── verify_code.js # 邮箱验证码:生成/发送/校验/消费(Redis 存储 + 重发节流)
|
||||
│ │ ├── wechat_login.js # 微信扫码登录:二维码本地生成 / 扫码状态机 / code 换 openid
|
||||
│ │ ├── password_reset.js # 找回密码:重置令牌生成/校验/消费(Redis 存摘要 + 旧链接失效 + 重发节流)
|
||||
│ │ ├── cache.js # Redis 封装(JSON 序列化 / 过期 / cache-aside / 降级)
|
||||
│ │ ├── config.js # 配置读写(带 Redis 缓存)
|
||||
│ │ ├── jwt.js # 令牌签发 / 校验(HS256 + typ + jti,见下文)
|
||||
│ │ ├── scanner.js # 设备记录:扫码登录即注册 + 绑定/解绑/心跳(只认长期 JWT)
|
||||
│ │ ├── scan.js # 中控通道上报 / 扫码入库去重 / 扫码查询
|
||||
│ │ ├── health.js # MySQL / Redis 连通性探测
|
||||
│ │ ├── user.js # 用户数据访问(app.model.User)
|
||||
│ │ └── wechat.js # 微信授权数据访问
|
||||
│ └── router.js
|
||||
├── config
|
||||
│ ├── config.default.js # 统一配置(连接 / 端口 / 安全 / 前端入口 / 内部鉴权)
|
||||
│ ├── config.local.js # 本机密码等(已 gitignore,仅 env=local 加载)
|
||||
│ ├── config.unittest.js # 单测用的固定内部令牌
|
||||
│ ├── plugin.js # 只开 sequelize / redis
|
||||
│ └── plugin.unittest.js # 单测环境关闭 DB 相关插件
|
||||
├── scripts
|
||||
│ ├── db-config.js # 脚本共用的连接信息解析
|
||||
│ ├── init-db.js # 执行 sql 下的 SQL 文件(npm run db:init [file])
|
||||
│ └── set-password.js # 创建用户/重置密码(npm run user:pass -- 账号 密码)
|
||||
├── sql
|
||||
│ ├── schema.sql # 建表脚本(幂等)
|
||||
│ └── migrations/ # 一次性数据迁移脚本
|
||||
├── test
|
||||
│ ├── utils/fake-redis.js # 单测用的内存版 Redis
|
||||
│ └── utils/internal.js # 内部接口鉴权 header(X-Internal-Token)
|
||||
└── package.json
|
||||
```
|
||||
|
||||
## 快速开始
|
||||
|
||||
```bash
|
||||
# 1. 安装依赖
|
||||
npm install
|
||||
|
||||
# 2. 填写本机连接信息:编辑 config/config.local.js(该文件已被 .gitignore 忽略)
|
||||
# - mysql.client.password = MySQL(127.0.0.1:3307,账号 packservice) 的密码
|
||||
# - redis.client.password / db = Redis 的密码(无密码写 null)与库序号(本机用 1)
|
||||
# 也可以改用环境变量 MYSQL_PASSWORD / REDIS_PASSWORD / REDIS_DB
|
||||
|
||||
# 3. 建表(库 packservice 需已存在,账号 packservice 仅有该库权限)
|
||||
npm run db:init
|
||||
# 如果是旧版本库,按顺序补跑迁移:
|
||||
# npm run db:init sql/migrations/20261016_rebuild_users.sql # users 表结构重建
|
||||
# npm run db:init sql/migrations/20261016_add_user_password.sql # 增加 password_hash
|
||||
# npm run db:init sql/migrations/20261016_devices_to_scanners.sql # 删掉旧的 devices 表(改用 scanners)
|
||||
# npm run db:init sql/migrations/20261016_add_user_email.sql # users 增加 email(可当登录账号)
|
||||
|
||||
# 4. 建一个登录账号(不存在会直接创建,密码 bcrypt 入库)
|
||||
npm run user:pass -- admin 123456 管理员
|
||||
|
||||
# 5. 启动(默认 http://127.0.0.1:7001)
|
||||
# 登录页:http://127.0.0.1:7001/login(用上面的账号登录)
|
||||
npm run dev
|
||||
|
||||
# 本地测试想要一个“专用端口”(默认 7300,可与 npm run dev 同时开):
|
||||
npm run dev:test
|
||||
# → http://127.0.0.1:7300 ;想换端口:egg-bin dev --port 7400,或 $env:PORT=7400; npm run dev
|
||||
# 两实例并存时给测试实例单独日志目录:$env:LOG_DIR='logs-test'; npm run dev:test
|
||||
|
||||
# 生产模式
|
||||
npm start # egg-scripts 后台启动
|
||||
npm stop
|
||||
```
|
||||
|
||||
验证:
|
||||
|
||||
```bash
|
||||
curl -I http://127.0.0.1:7001/login # 200:反代到前端 dev server(前端没起则 502 提示页)
|
||||
curl http://127.0.0.1:7001/health
|
||||
curl http://127.0.0.1:7001/api/users # 401:内部接口要令牌(X-Internal-Token 或管理员 user JWT)
|
||||
curl -H 'X-Internal-Token: <INTERNAL_TOKEN>' http://127.0.0.1:7001/api/users # 200
|
||||
```
|
||||
|
||||
> 后端只管接口:页面在 `../frontend/`(`npm run dev` 起在 7301)。
|
||||
> 联调推荐**只开后端地址** `http://127.0.0.1:7001`(dev 环境自动把页面请求反代给前端);也可以直接开前端 7301(Vite 把 `/api` 反代到 7001)。
|
||||
|
||||
## 单元测试
|
||||
|
||||
```bash
|
||||
npm test # 无需本机启动 MySQL / Redis
|
||||
npm run cov
|
||||
```
|
||||
|
||||
### 本地专用测试端口(`npm run dev:test`)
|
||||
|
||||
- `npm run dev:test` = `egg-bin dev --port 7300`(可与 7001 的 `npm run dev` 同时跑);端口也可用环境变量 `PORT` 覆盖(egg-cluster 会读 `process.env.PORT`),`config.cluster.listen.port` 的默认值是 `Number(PORT || 7001)`;
|
||||
- **登录态是共享的**:cookie(`packs_sess`)不带端口,`127.0.0.1:7001` 的登录 cookie 在 `127.0.0.1:7300` 一样有效,换端口不用重新登录;两个实例也共用同一套 MySQL / Redis(都读 `config/config.local.js`);
|
||||
- **扫码二维码地址会自动跟随端口**:二维码内容是 `ctx.origin` 拼的 `http://<当前访问的 host:port>/wechat?spm=1.0.<码>.1`,所以在 7300 打开的登录页,扫出来的就是 7300 的地址,不用改配置;邮件里的重置链接同理(`config.email.siteUrl || ctx.origin`),只有显式配了 `SITE_URL` 才需要跟着改;
|
||||
- 两个实例并存时日志默认都写 `logs/pack-service/`,想分开就 `$env:LOG_DIR='logs-test'; npm run dev:test`(PowerShell)/ `LOG_DIR=logs-test npm run dev:test`(bash);
|
||||
- `npm test` 是单测(不监听固定端口),和这两个端口不冲突;
|
||||
|
||||
- `config/plugin.unittest.js` 在测试环境关闭 `sequelize` 与 `redis` 插件(这两个插件在启动时都会连库);
|
||||
- 测试中用 `mock(app, 'model', fakeModel)` / `mock(app, 'redis', fakeRedis)` 注入假实现,因此 CI 上不依赖外部服务。
|
||||
|
||||
## 环境变量
|
||||
|
||||
不配置时使用默认值(`127.0.0.1:3307` / 账号 `packservice` / 库名 `packservice`,密码为空需在 `config/config.local.js` 填)。
|
||||
|
||||
| 变量 | 默认值 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| `MYSQL_HOST` | `127.0.0.1` | MySQL 地址 |
|
||||
| `MYSQL_PORT` | `3307` | MySQL 端口 |
|
||||
| `MYSQL_USER` | `packservice` | 用户名(**大小写敏感**) |
|
||||
| `MYSQL_PASSWORD` | 空 | 密码,本地放 `config/config.local.js` |
|
||||
| `MYSQL_DATABASE` | `packservice` | 库名 |
|
||||
| `MYSQL_POOL_SIZE` | `10` | Sequelize 连接池上限(`pool.max`) |
|
||||
| `REDIS_HOST` | `127.0.0.1` | Redis 地址 |
|
||||
| `REDIS_PORT` | `6379` | Redis 端口 |
|
||||
| `REDIS_PASSWORD` | 空(`null`) | 密码,无密码时必须为空 |
|
||||
| `REDIS_DB` | `0` | 库序号 |
|
||||
| `CACHE_PREFIX` | `packs:` | 业务缓存 key 前缀 |
|
||||
| `CACHE_TTL` | `300` | 默认缓存过期(秒) |
|
||||
| `JWT_SECRET` | 开发默认值 | 扫描器 JWT 签名密钥,**生产未设置会启动失败** |
|
||||
| `SITE_NAME` | `云仓视频溯源系统` | 站点/产品中文名(页面标题、侧边栏品牌、邮件主题与正文都用它) |
|
||||
| `SCANNER_JWT_EXPIRES` | `365d` | 扫描器长期 JWT 默认有效期(`jsonwebtoken` 语法,如 `30d` / `720h`) |
|
||||
| `DEVICE_JWT_EXPIRES` | 同 `SCANNER_JWT_EXPIRES` | `/api/device/login` 下发令牌的**默认时长 + 上限**;设备可用 `?expiresIn=30d` 申请更短的,不能更长 |
|
||||
| `REGISTER_ENABLED` | `true` | 是否允许登录页自助注册(`false`/`0`/`no`/`off` 关闭;**生产建议关掉**,用 `npm run user:pass` 建号) |
|
||||
| `SMTP_HOST` | 空 | SMTP 主机;**不配就走开发模式**(验证码只写日志 + 注册页回显,不发真邮件) |
|
||||
| `SMTP_PORT` | `465` | SMTP 端口 |
|
||||
| `SMTP_SECURE` | `true` | 是否用 TLS(465 用 true,587 用 false) |
|
||||
| `SMTP_USER` / `SMTP_PASSWORD` | 空 | SMTP 账号密码(放 `config/config.local.js` 或环境变量) |
|
||||
| `SMTP_FROM` | `云仓视频溯源系统 <no-reply@...>` | 发件人(默认取 `SITE_NAME` 作显示名) |
|
||||
| `EMAIL_CODE_TTL` | `600` | 邮箱验证码有效期(秒) |
|
||||
| `EMAIL_CODE_RESEND` | `60` | 同一邮箱重发验证码的间隔(秒) |
|
||||
| `EMAIL_CODE_ATTEMPTS` | `5` | 同一个验证码最多校验几次(超过则作废) |
|
||||
| `EMAIL_RESET_TTL` | `1800` | 重置密码链接有效期(秒,默认 30 分钟) |
|
||||
| `SITE_URL` | 空 | 邮件里重置链接的站点地址(如 `https://packs.example.com`);不配则用当前请求的 host |
|
||||
| `WECHAT_APPID` | 空 | 微信开放平台网站应用 appid;**不配时登录页二维码退化为本地演示码**(不会假装能用) |
|
||||
| `WECHAT_SECRET` | 空 | 同上对应的 appsecret |
|
||||
| `WECHAT_REDIRECT_URI` | 空 | 扫码回调地址(需与开放平台后台配置一致);不配则按当前请求 origin 拼 `/login/wechat/callback` |
|
||||
| `WECHAT_API_BASE` | `https://api.weixin.qq.com` | 微信接口域名(自建网关/联调时可改) |
|
||||
| `WECHAT_QR_CELL` / `WECHAT_QR_MARGIN` | `6` / `4` | 二维码 SVG 的单元格像素 / 静默区格数(⚠️ 库的 margin 参数单位是像素,代码里已按格×单元格换算;<4 格会影响扫码) |
|
||||
| `WECHAT_STATE_TTL` | `600` | 扫码串码(二维码)有效期(秒) |
|
||||
| `WECHAT_CODE_LENGTH` | `6` | 扫码串码长度(数字 + 大写字母,去掉了 0/O/1/I 等易混字符) |
|
||||
| `WECHAT_SPM_PATTERN` | `1.0.{code}.1` | 二维码地址里的 spm 格式(`{code}` 会被替换成串码) |
|
||||
| `USER_JWT_EXPIRES` | `7d` | 扫码登录接口下发的**用户 JWT** 有效期 |
|
||||
| `WECHAT_POLL_WAIT` | `60` | 扫码登录接口长轮询最多挂起多少秒(前端自己的超时建议再 +10s;反代注意 `proxy_read_timeout` 要大于它) |
|
||||
|
||||
Windows PowerShell 示例:
|
||||
|
||||
```powershell
|
||||
$env:MYSQL_PASSWORD = 'your-pass'; $env:REDIS_PASSWORD = 'your-pass'; npm run dev
|
||||
```
|
||||
|
||||
## 数据表
|
||||
|
||||
六张表统一约定:`BIGINT UNSIGNED` 自增主键、`created_at` / `updated_at`、`deleted_at`(软删除,Sequelize `paranoid: true`)、`status` 状态位。
|
||||
|
||||
### users 用户表
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| id | bigint unsigned | 主键 |
|
||||
| username | varchar(64) | 登录名,唯一,可空(纯微信登录可不设) |
|
||||
| nickname | varchar(64) | 昵称 |
|
||||
| email | varchar(128) | 邮箱,**唯一、可空**;注册可选填,**可当登录账号**(入库统一转小写) |
|
||||
| avatar | varchar(255) | 头像 |
|
||||
| phone | varchar(20) | 手机号,唯一 |
|
||||
| gender | tinyint unsigned | 0 未知 / 1 男 / 2 女 |
|
||||
| status | tinyint unsigned | 1 正常 / 0 禁用 |
|
||||
| remark | varchar(255) | 备注 |
|
||||
| last_login_at | datetime | 最近登录时间 |
|
||||
| created_at / updated_at / deleted_at | datetime | 时间戳与软删除 |
|
||||
|
||||
### wechat_oauth 微信授权表
|
||||
|
||||
一条记录 = 某用户在某 `appid` 下的一次授权,**一个用户可绑定多个微信**。
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| id | bigint unsigned | 主键 |
|
||||
| user_id | bigint unsigned | 关联 `users.id` |
|
||||
| appid | varchar(64) | 微信 appid,与 openid 组成唯一键 |
|
||||
| openid | varchar(64) | 用户在该 appid 下的 openid |
|
||||
| unionid | varchar(64) | 开放平台 unionid |
|
||||
| nickname / avatar | varchar | 授权时的微信资料 |
|
||||
| session_key | varchar(128) | 小程序 session_key |
|
||||
| access_token / refresh_token | varchar(512) | 网页授权令牌 |
|
||||
| scope | varchar(64) | 授权 scope |
|
||||
| token_expires_at | datetime | access_token 过期时间 |
|
||||
| last_auth_at | datetime | 最近授权时间 |
|
||||
| created_at / updated_at / deleted_at | datetime | 时间戳与软删除 |
|
||||
|
||||
### sys_config 系统配置表
|
||||
|
||||
`group_name` + `config_key` 唯一定位一条配置,`value_type` 决定 `config_value` 的解析方式(`string` / `number` / `boolean` / `json`)。
|
||||
|
||||
> 注意:本表用软删除,若建唯一索引会被已删除的记录占用,导致同 key 无法重建,因此**唯一性由 service 层保证**(先查后写),表上只建普通索引。
|
||||
|
||||
### scanners 设备表
|
||||
|
||||
设备(条码/二维码扫描枪、中控)**扫码登录时自动注册**,`user_id` 为空表示尚未绑定账号
|
||||
(设备归哪个账号由「扫码确认」的人决定,也可由管理员解绑)。
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| id | bigint unsigned | 主键 |
|
||||
| user_id | bigint unsigned | 绑定的用户 id,未绑定为 NULL |
|
||||
| sn | varchar(64) | 设备 SN,唯一(设备唯一标识;设备不传时由服务端生成 `DEV-…`) |
|
||||
| name / model / vendor / firmware | varchar | 名称、型号、厂商、固件/客户端版本 |
|
||||
| ip | varchar(45) | 最近登录 IP |
|
||||
| secret_hash | varchar(100) | **历史字段**(早期 sn+secret 登录用),现已不再写入 |
|
||||
| token_jti | varchar(64) | 当前长期 JWT 的 `jti`,唯一;**库里不存令牌本体** |
|
||||
| token_expires_at | datetime | 令牌过期时间(默认 365 天) |
|
||||
| status | tinyint unsigned | 1 正常 / 0 禁用(禁用后登录与所有带令牌的接口都 403) |
|
||||
| last_register_at / last_login_at / last_seen_at | datetime | 最近注册、最近登录、最近心跳时间 |
|
||||
| created_at / updated_at / deleted_at | datetime | 时间戳与软删除 |
|
||||
|
||||
设备接入流程(**只有一条链路**):
|
||||
|
||||
1. **拿令牌(也就是注册)**:`GET /api/device/login`(公开,无需任何凭据):
|
||||
- ① 不带参数 → 返回登录码 + 二维码地址(`qrContent` / `qrImageUrl`),**此时库里还没有任何记录**;
|
||||
- ② 手机用 `POST /api/wechat/confirm` 确认(已登录用户);
|
||||
- ③ 设备带 `?code=&wait=60` 长轮询 → **这一边才注册**:按 SN 建/取记录、绑定到确认登录的账号,并拿到长期 JWT;
|
||||
2. **用令牌**:之后所有请求带 `Authorization: Bearer <JWT>`;`GET /api/scanner/me` 自检、`POST /api/scanner/heartbeat` 保活(刷新 `last_seen_at`)、`/api/scan/*` 上报;
|
||||
3. **令牌到期 / 设备重装**:再扫一次码即可(不需要密钥:设备屏幕出码、人确认一下)—— 记录已存在时不重复建,只换发新令牌;
|
||||
4. **换人使用(设备转让)**:先由原账号在 `/scanners` 解绑(或管理侧 `POST /api/scanner/unbind`),新使用人再扫码登录即可认领;
|
||||
5. SN 曾经被**删除**过也能继续用同一个 SN:扫码登录会把那条**软删除**的记录**复活**(id 不变、`deleted_at` 清空)—— 软删行仍占着 `sn` 唯一键,不复活就会撞键。
|
||||
|
||||
> 历史变更:早期的 `POST /api/scanner/register`(自己注册拿 sn+secret)与 `POST /api/scanner/login`(sn+secret 换令牌)
|
||||
> **已下线**(跟扫码登录重复,而且会先建出一条 `user_id = NULL` 的无主记录);设备身份现在**只有长期 JWT 一种**。
|
||||
|
||||
#### 设备通讯用的长期 JWT
|
||||
|
||||
- 算法 HS256,`issuer = pack-service`、`audience = scanner`,payload 含 `sub`(设备 id)/ `sn` / `typ: 'scanner'` / `jti`;
|
||||
- 有效期:默认 **365 天**(`config.jwt.deviceExpiresIn`,env `DEVICE_JWT_EXPIRES`,不配就跟 `SCANNER_JWT_EXPIRES` 走);设备可用 `?expiresIn=30d`(或秒数)申请**更短**的,超上限 422;
|
||||
- **可撤销**:每次扫码登录都会生成新的 `jti` 写库(`scanners.token_jti`),旧令牌因 `jti` 不匹配立即 401;把 `status` 置 0 也可让令牌失效(403);
|
||||
- 令牌本体不落库(只存 `jti`);列表/详情/`me` 等响应都不返回 `token_jti`(`app/service/scanner.js` 的 `sanitize()` 兜底清洗);
|
||||
- 签名密钥取 `config.jwt.secret`(来自 `JWT_SECRET`),生产环境未设置会直接启动失败。
|
||||
|
||||
令牌取用顺序:`Authorization: Bearer <token>` → `X-Scanner-Token` → `?access_token=`(见 `app/middleware/scanner_auth.js`)。
|
||||
|
||||
### scan_channels 扫描中控通道表
|
||||
|
||||
「中控」就是绑定端(复用 `scanners`,用自己的 `sn` + 长期 JWT 上报):一台中控可接多个扫码设备,
|
||||
每个扫码设备对应一个通道,中控把 **通道 id + 通道名** 上报上来,**一个通道一行**。
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| id | bigint unsigned | 主键 |
|
||||
| scanner_id | bigint unsigned | 上报的中控(= `scanners.id`) |
|
||||
| channel_id | varchar(64) | 通道 id(中控上报,**同一中控内唯一**) |
|
||||
| channel_name | varchar(128) | 通道名(中控上报) |
|
||||
| last_report_at | datetime | 最近一次上报时间 |
|
||||
| status | tinyint unsigned | 1 正常 / 0 停用 |
|
||||
| created_at / updated_at / deleted_at | datetime | 时间戳与软删除 |
|
||||
|
||||
- 唯一键 `(scanner_id, channel_id)`:同一中控重复上报同一个通道 = 更新通道名与 `last_report_at`,不会重复建行;
|
||||
- 因为 `channel_id` 只在同一中控内唯一,所以关联/去重都必须带上 `scanner_id`;
|
||||
- 用软删除:曾被停用(`deleted_at` 非空)的通道再次上报时会自动「复活」。
|
||||
|
||||
### scan_records 扫码记录表
|
||||
|
||||
中控上报的扫码流水:**条码 + 扫描时间 + 通道 id**,需要**去重存储**。
|
||||
|
||||
| 字段 | 类型 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| id | bigint unsigned | 主键 |
|
||||
| scanner_id | bigint unsigned | 上报的中控(= `scanners.id`) |
|
||||
| channel_id | varchar(64) | 通道 id |
|
||||
| barcode | varchar(255) | 条码内容 |
|
||||
| scan_time | datetime | 扫描时间(中控上报,**精确到秒**,去重键之一) |
|
||||
| reported_at | datetime | 服务端接收时间 |
|
||||
| created_at / updated_at | datetime | 时间戳 |
|
||||
|
||||
去重规则(唯一键 `uk_scan_dedup` = `(scanner_id, channel_id, barcode, scan_time)`):
|
||||
|
||||
- **同一中控 + 同一通道 + 同一条码 + 同一扫描时间(秒)** 只入库一次,重复上报不会报错,接口返回 `duplicated` 计数;
|
||||
- 上报前先用一次查询(按中控 + 通道 + 时间范围)捞出已存在的记录做过滤,剩下的批量插入;
|
||||
真出现并发撞唯一键时会自动退化成逐条插入,撞上的计入 `duplicated`;
|
||||
- 同一批里完全相同的上报也只留一条(内存里先去重);
|
||||
- 条码相同但时间或通道不同 → 视为两条不同记录;
|
||||
- 时间精度到秒:`scan_time` 会先把毫秒截断,再做去重与入库(同一秒内的同条码算重复)。
|
||||
|
||||
> 本表**不用软删除**(paranoid 关闭):软删除会让记录占用唯一键,导致同一条扫码数据再也无法入库;
|
||||
> 需要清理请按时间物理删除:`DELETE FROM scan_records WHERE scan_time < ?`。
|
||||
|
||||
## 页面(在前端项目里)
|
||||
|
||||
⚠️ **后端不再渲染页面**:`app/view/`、nunjucks、session、CSRF 都已移除,`app/controller/page/` 也删掉了。
|
||||
登录 / 注册 / 找回密码 / 扫码确认 / 首页 / 设备管理 / 扫码记录 / 个人中心 / 测试页
|
||||
全都在 **`../frontend/`**(Vite + Vue3 + TS 的 SPA)里,通过下面的 JSON 接口通讯:
|
||||
|
||||
| 页面 | 前端路由 | 用到的接口 |
|
||||
| --- | --- | --- |
|
||||
| 登录 / 注册 / 扫码 | `/login` | `/api/web/auth/*`、`/api/wechat/{login,status,qrcode.svg}` |
|
||||
| 手机确认登录 | `/wechat?spm=…` | `/api/wechat/confirm` |
|
||||
| 忘记 / 重置密码 | `/forgot`、`/reset` | `/api/web/auth/{forgot,reset}` |
|
||||
| 首页统计 | `/` | `/api/web/stats` |
|
||||
| 设备管理 | `/devices` | `/api/web/devices*` |
|
||||
| 扫码记录 | `/records` | `/api/web/records` |
|
||||
| 个人中心 | `/profile` | `/api/web/me*` |
|
||||
| 测试页 | `/test` | `/api/web/test/*`、`/api/wechat/{status,confirm}` |
|
||||
|
||||
**后端怎么把页面交出去**(`app/middleware/frontend.js`,只接管「非 `/api`、`/health`」的 GET/HEAD 请求):
|
||||
|
||||
- **开发**(`env=local`):**反代**到 `FRONTEND_DEV_SERVER`(默认 `http://127.0.0.1:7301`,即 `frontend/ && npm run dev`),
|
||||
包含 HMR 的 WebSocket 升级 —— 所以联调只开 `http://127.0.0.1:7001` 一个地址就够(前端热更新照常生效);
|
||||
前端没起来时会回一个 502 提示页,而不是白屏;
|
||||
- **生产**:托管 `FRONTEND_DIST`(默认 `../frontend/dist`);找不到文件且请求要 HTML 时回退 `index.html`
|
||||
(SPA 深链 `/devices` 刷新不会 404);dist 不存在时回 503 并提示先 `npm run build`;
|
||||
- **单测**(`env=unittest`):整个中间件跳过(不连前端、也不要求 dist 存在)。
|
||||
|
||||
## 接口
|
||||
|
||||
|
||||
### 按调用方分模块(目录 / 鉴权 / 路径 一一对应)
|
||||
|
||||
| 调用方 | 控制器目录 | 鉴权 | 典型接口 |
|
||||
| --- | --- | --- | --- |
|
||||
| **用户端(前端 SPA)** | `app/controller/web/` | `middleware.apiAuth()`(**user JWT**,typ=user);登录/注册/找回免令牌 | `/api/web/{auth/*,me*,stats,devices*,records,test/*}` |
|
||||
| **运维 / 内部**(运维脚本、后台系统) | `app/controller/internal/` | `middleware.internalAuth()`(`X-Internal-Token` 或白名单账号的 user JWT) | `/api/users*`、`/api/configs*`、`/api/scanners*`、`/api/scanner/{bind,unbind}`、`/api/wechat/{bind,:id/tokens}` |
|
||||
| **用户态**(小程序 / Win 客户端) | `app/controller/client/` | `middleware.apiAuth()`(**user JWT**,typ=user) | `/api/wechat/confirm` |
|
||||
| **设备**(扫描枪 / 中控) | `app/controller/device/` | `middleware.scannerAuth()`(**device JWT**,typ=scanner) | `/api/device/login`、`/api/scanner/{me,heartbeat}`、`/api/scan/*` |
|
||||
| **公开登录接口** | `app/controller/auth/` | 无 | `/api/wechat/{login,status,qrcode.svg,callback}`(`/api/device/login` 的发码也无需凭据) |
|
||||
| 公共 | `home.js` / `health.js` | 无 | `/api/info`、`/health` |
|
||||
|
||||
- **小程序与 Win 客户端共用 `client/` 那一套**:它们身份相同(都是「某个登录用户」),业务接口不该复制两份;要区分用途用 header(如 `X-Client: miniapp|win`)或令牌里的自定义声明,别用路径分叉。
|
||||
- **令牌层是硬隔离**:`verifyUser()` 只认 `typ: 'user'`(默认 7d),`verifyScanner()` 只认 `typ: 'scanner'`(默认 365d)——用户令牌调设备接口、设备令牌调用户接口都直接 401。
|
||||
(⚠️ 两个 `verify*` 都必须比对 `typ`:用户令牌与设备令牌用的是同一把密钥,不比对的话用户令牌就能当设备令牌用。)
|
||||
- **前端只能碰自己的数据**:`/api/web/devices*`、`/api/web/records`、`/api/web/stats` 的过滤条件一律取令牌里的 `userId`,前端传的 `userId`/`deviceId` 越权一概 404(不泄露别人有没有这台设备)。
|
||||
- **服务层不按调用方分**:`app/service/` 按**领域**拆文件(`scanner` / `scan` / `user` / `config` / `wechat` / `wechat_login` / `jwt` / `cache` / `mail` / `verify_code` / `password_reset`),因为设备与内部接口会共用同一个领域服务(如 `service.scanner` 既被 `device/*` 也被 `internal/device.js` 调用);`app/model/` 按表拆。
|
||||
- Egg 支持多级目录:`app/controller/internal/user.js` → `controller.internal.user`(路由里就是这么引用的),`typings/` 会自动重新生成。
|
||||
|
||||
| 方法 | 路径 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| GET | `/api/info` | 服务信息(JSON) |
|
||||
| GET | `/health` | 健康检查,MySQL 或 Redis 不可用时返回 503 |
|
||||
| GET | `/api/users?page=1&pageSize=20&keyword=&status=` | 用户分页(keyword 模糊匹配昵称/登录名/手机号) |
|
||||
| GET | `/api/users/:id` | 用户详情(Redis 缓存 → 回源数据库) |
|
||||
| POST | `/api/users` | 新增,body: `{"username":"zhangsan","nickname":"张三","phone":"13800000000"}` |
|
||||
| PUT | `/api/users/:id` | 更新(清除该用户缓存) |
|
||||
| DELETE | `/api/users/:id` | 软删除(清除该用户缓存) |
|
||||
| GET | `/api/users/:id/wechats` | 某用户的全部微信授权 |
|
||||
| GET | `/api/wechat/:appid/:openid` | 按 appid + openid 反查授权与关联用户 |
|
||||
| POST | `/api/wechat/bind` | 绑定/更新授权,body: `{"userId":1,"appid":"wx123","openid":"o_abc"}` |
|
||||
| PUT | `/api/wechat/:id/tokens` | 更新 session_key / 令牌,body: `{"sessionKey":"sk","expiresIn":7200}` |
|
||||
| DELETE | `/api/wechat/:id` | 解绑(软删除) |
|
||||
| GET | `/api/configs?group=wechat` | 配置列表(管理用,含禁用项) |
|
||||
| GET | `/api/configs/:group/:key` | 取单个配置值(带 Redis 缓存) |
|
||||
| GET | `/api/configs/:group` | 取分组内所有启用配置 |
|
||||
| PUT | `/api/configs` | 新增/更新(幂等),body: `{"groupName":"wechat","configKey":"appid","configValue":"wx123"}` |
|
||||
| DELETE | `/api/configs/:group/:key` | 软删除(清缓存) |
|
||||
| GET | `/api/device/login` | **设备「扫码登录 + 注册」**(参考 `/api/wechat/login`,但下发**长期** JWT):**不需要凭据、不需要预先注册**(公开接口);`?sn=`/`name`/`vendor`/`model`/`firmware` 可选(发码时带上最省事,服务端会暂存)、`?expiresIn=30d` 可选(只能比服务端上限短);不带 `code` → 发登录码(`code` / `spm` / **`qrContent`(二维码要编的完整网址)** / `qrImageUrl`(完整地址的 SVG));带 `?code=&wait=N` → 长轮询,手机用 `POST /api/wechat/confirm` 确认后**立即**返回 `{ firstTime, sn, token, expiresIn, expiresAt, scanner, user }`,**注册/绑定就发生在这一刻**(SN 已属于别人 → 403) |
|
||||
| POST | `/api/scanner/bind` | **管理侧**:把设备绑定到账号,body: `{ sn, username }` 或 `{ sn, userId }` |
|
||||
| POST | `/api/scanner/unbind` | **管理侧**:解绑,body: `{ sn }`(设备可再扫码重新认领) |
|
||||
| GET | `/api/scanner/me` | **需 JWT**:返回当前设备信息(自检连通性) |
|
||||
| POST | `/api/scanner/heartbeat` | **需 JWT**:保活,刷新 `last_seen_at` 并返回服务端时间 |
|
||||
| GET | `/api/scanners?page=&pageSize=&keyword=&userId=&status=` | 设备列表(带绑定账号;管理侧) |
|
||||
| GET | `/api/scanners/:id` | 扫描器详情 |
|
||||
| DELETE | `/api/scanners/:id` | 软删除扫描器 |
|
||||
| POST | `/api/scan/channels` | **需扫描器 JWT**:中控上报通道,body: `{ channels: [{ channelId, channelName }] }`(单条也可)→ `{ created, updated, invalid, errors }` |
|
||||
| GET | `/api/scan/channels?page=&pageSize=&keyword=&status=` | **需扫描器 JWT**:当前中控已登记的通道 |
|
||||
| POST | `/api/scan/records` | **需扫描器 JWT**:中控上报扫码,body: `{ records: [{ barcode, scanTime, channelId }] }` → `{ received, inserted, duplicated, invalid, unknownChannels }` |
|
||||
| GET | `/api/scan/records?page=&pageSize=&channelId=&barcode=&startTime=&endTime=` | **需扫描器 JWT**:当前中控上报的扫码记录 |
|
||||
|
||||
扫码上报的两个接口都**不会因为重复而报错**(幂等):重复条数计入 `duplicated`;
|
||||
单条非法(缺条码 / 时间非法 / 超长)会被跳过并计入 `invalid` + `errors`;整体为空数组才返回 422。
|
||||
上报还支持 `records` 传 JSON 字符串(部分设备端会这么塞);上报成功会顺手刷新中控心跳与通道的 `last_report_at`,
|
||||
遇到未登记的通道会自动补建一行(`channel_name` 留空,同时记 WARN 日志)。
|
||||
|
||||
统一响应格式:成功 `{ "ok": true, "data": ... }`;失败 `{ "ok": false, "message": "..." }`(由 `app/middleware/error_handler.js` 保证 4xx/5xx 也返回 JSON);
|
||||
**接口路径写错(没匹配到路由)也是 JSON**:`404 { ok:false, message:'接口不存在' }`(不会再返 HTML 404 页把客户端的 JSON 解析弄挂)。
|
||||
|
||||
扫描器 JWT 鉴权结果:缺令牌 / 签名不对 / 已过期 / `jti` 已被轮换 / 扫描器不存在 → **401**;扫描器被禁用 → **403**。
|
||||
|
||||
## 用法速查
|
||||
|
||||
```js
|
||||
// ===== MySQL:Sequelize 模型(定义在 app/model/*.js)=====
|
||||
// 通过 app.model.User / this.app.model.User / ctx.model.User 访问
|
||||
const { User, WechatOauth, SysConfig } = this.app.model;
|
||||
|
||||
await User.findByPk(1); // 主键查询
|
||||
await User.findOne({ where: { username: 'zhangsan' } });
|
||||
await User.findAll({ where: { status: 1 }, limit: 10, offset: 0, order: [[ 'id', 'DESC' ]] });
|
||||
const { rows, count } = await User.findAndCountAll({ limit: 10 }); // 分页
|
||||
await User.create({ username: 'zhangsan', nickname: '张三' }); // 新增(自动写 created_at/updated_at)
|
||||
await User.update({ status: 0 }, { where: { id: 1 } }); // 更新
|
||||
await User.destroy({ where: { id: 1 } }); // 删除(paranoid 模型 = 软删除)
|
||||
await User.destroy({ where: { id: 1 }, force: true }); // 物理删除
|
||||
|
||||
// 关联查询:一个用户的多条微信授权
|
||||
const withWechats = await User.findOne({ where: { id: 1 }, include: [{ model: WechatOauth, as: 'wechats' }] });
|
||||
|
||||
// 原生 SQL / 事务
|
||||
const [rows2] = await this.app.model.query('SELECT 1 AS ok');
|
||||
await this.app.model.transaction(async t => {
|
||||
await User.create({ nickname: 'a' }, { transaction: t });
|
||||
await User.create({ nickname: 'b' }, { transaction: t });
|
||||
});
|
||||
|
||||
// 操作符:const { Op } = require('sequelize');
|
||||
|
||||
// ===== 系统配置:带 Redis 缓存,写入自动失效 =====
|
||||
const appid = await this.ctx.service.config.get('wechat', 'appid'); // value_type=number/json/boolean 会自动转换
|
||||
await this.ctx.service.config.set({ groupName: 'wechat', configKey: 'appid', configValue: 'wx123' });
|
||||
const groupConfig = await this.ctx.service.config.getGroup('wechat'); // { appid: 'wx123', ... }
|
||||
await this.ctx.service.config.remove('wechat', 'appid'); // 软删除 + 清缓存
|
||||
|
||||
// ===== 微信授权 =====
|
||||
await this.ctx.service.wechat.bind({ userId: 1, appid: 'wx123', openid: 'o_abc', nickname: '微信昵称' });
|
||||
const oauth = await this.ctx.service.wechat.findByOpenid('wx123', 'o_abc'); // 带关联用户
|
||||
const user = await this.ctx.service.user.findByOpenid('wx123', 'o_abc'); // 直接拿用户
|
||||
|
||||
// ===== 扫描器长期 JWT(app/service/jwt.js)=====
|
||||
const jwtToken = this.ctx.service.jwt.signScanner(scanner, { jti: 'uuid' }); // 签发
|
||||
this.ctx.service.jwt.verifyScanner(jwtToken); // 校验(失败直接 401)
|
||||
this.ctx.service.jwt.expiresAtOf(jwtToken); // 取过期时间(Date)
|
||||
|
||||
// ===== 设备业务(app/service/scanner.js)=====
|
||||
// 扫码登录(注册 + 绑定 + 发令牌,一步到位;userId = 扫码确认的那个人)
|
||||
const login = await this.ctx.service.scanner.loginByScan({
|
||||
sn: 'SN-001', // 设备自报的 SN(不传则服务端生成 DEV-…)
|
||||
name: '1 号线扫描枪',
|
||||
userId: 1, // 来自 POST /api/wechat/confirm 的确认人
|
||||
expiresIn: undefined, // 可选:秒数;不传用 config.jwt.deviceExpiresIn
|
||||
});
|
||||
login.token; // 长期 JWT(365d)
|
||||
login.firstTime; // true = 本次才注册出这条记录
|
||||
await this.ctx.service.scanner.heartbeat(scanner, this.ctx.ip); // 心跳:刷新 last_seen_at
|
||||
await this.ctx.service.scanner.unbind({ sn: 'SN-001' }); // 管理侧解绑
|
||||
|
||||
// ===== 扫码信息(app/service/scan.js,scanner = 中控实例)=====
|
||||
// 1. 中控上报通道(一个通道一行,重复上报只更新通道名)
|
||||
await this.ctx.service.scan.reportChannels(scanner, [
|
||||
{ channelId: 'CH-1', channelName: '1 号打包口' },
|
||||
]);
|
||||
// → { received, created, updated, invalid, errors, channels }
|
||||
|
||||
// 2. 中控上报扫码结果(同一中控+通道+条码+扫描时间(秒) 自动去重)
|
||||
const ingested = await this.ctx.service.scan.ingest(scanner, [
|
||||
{ barcode: '6901234567890', scanTime: '2026-10-16 10:20:30', channelId: 'CH-1' },
|
||||
{ barcode: '6901234567890', scanTime: '2026-10-16 10:20:30', channelId: 'CH-1' }, // 重复 → 只入库一次
|
||||
]);
|
||||
// → { received: 2, inserted: 1, duplicated: 1, invalid: 0, unknownChannels: [] }
|
||||
|
||||
// 3. 查询(都带分页;记录默认按 scan_time 倒序)
|
||||
await this.ctx.service.scan.listChannels({ scannerId: scanner.id, keyword: '' });
|
||||
await this.ctx.service.scan.listRecords({ scannerId: scanner.id, channelId: 'CH-1', barcode: '690' , startTime: '2026-10-16', endTime: '2026-10-17' });
|
||||
|
||||
// 时间解析:'2026-10-16 10:20:30' / '2026-10-16T10:20:30' / 10 位秒时间戳 / 13 位毫秒时间戳 都支持(毫秒会被截断)
|
||||
|
||||
// ===== Redis:app.redis 即 ioredis 实例 =====
|
||||
await this.app.redis.set('k', 'v');
|
||||
await this.app.redis.setex('k', 60, 'v');
|
||||
await this.app.redis.get('k');
|
||||
|
||||
// 项目封装(见 app/service/cache.js)
|
||||
await this.ctx.service.cache.set('user:1', { id: 1 }, 60);
|
||||
await this.ctx.service.cache.remember('user:1', 60, () => loadFromMysql());
|
||||
```
|
||||
|
||||
## 说明
|
||||
|
||||
- MySQL 通过 `egg-sequelize@6`(Sequelize 6 + mysql2)访问,模型放在 `app/model/`,表结构以 `sql/schema.sql` 为准(未开启 `sequelize.sync`,避免误改表);需要同步表结构时可在启动钩子里显式调用 `app.model.sync()`。
|
||||
- **Sequelize 是启动强依赖**:插件在 `beforeStart` 里会 `authenticate()`,连不上数据库时应用启动会失败(重试 3 次后退出);Redis 用 `egg-redis@2`(ioredis),配置了 `client.weakDependent: true`,Redis 不可用不阻塞启动。
|
||||
- 时间统一按 `timezone: '+08:00'` 处理;表名/字段名下划线映射、created_at/updated_at 命名在 `config.sequelize.define` 中配置。
|
||||
- 用户/微信授权/系统配置的 `deleted_at` 为软删除:普通查询自动过滤,需物理删除时加 `force: true`。
|
||||
- `wechat_oauth` 用 `(appid, openid)` 唯一键防重;`sys_config` 的唯一性在 service 层保证(原因见「数据表」一节的说明)。
|
||||
- 所有异常经 `app/middleware/error_handler.js` 处理:`/api/*`、`/health`(或声明了 `Accept: application/json` 的请求)统一返回 `{ ok:false, message }`(4xx 原消息、5xx 只回「服务器内部错误」);其它请求返回一行纯文本(正常情况下它们都被 `middleware/frontend.js` 接走了)。
|
||||
- **没有模板 / 会话 / CSRF**:`app/view/`、`egg-view-nunjucks`、`egg-session-redis`、`config.view`、`config.session` 全部已删除;接口一律 header 令牌鉴权,`config.security.csrf.enable = false`(没有基于 cookie 的表单了,CSRF 保护已无意义)。
|
||||
- **前端的页面与样式在 `../frontend/src/`**:公共样式 `styles/main.css`(卡片 / 表单 / 表格 / 分页 / 徽标),每个页面一个 `views/*.vue`;接口调用统一走 `api/client.ts`(自动带令牌、401 清令牌)+ `api/web.ts`(按接口分组)。
|
||||
- 登录密码用 `bcryptjs` 哈希(`app/service/auth.js`,成本因子 10);用户查询默认 `exclude: ['passwordHash']`,任何接口/模板都不会输出哈希。
|
||||
- **自助注册**(接口):前端登录页「注册」tab → `POST /api/web/auth/register/code`(发邮箱验证码)→ `POST /api/web/auth/register` → `service.auth.register()`(`user.create` + `setPassword`,用户名/邮箱/手机号重复在 service 层抛 409,接口翻成友好文案)→ 成功直接下发用户 JWT(前端存本地即登录);**邮箱必填**,格式校验后**统一小写入库**;
|
||||
- **登录账号支持 用户名 / 手机号 / 邮箱**(`service.user.findByAccount()` 的 `Op.or` 同时匹配 `username` / `phone` / `email`);邮箱也能在个人中心修改(同样格式校验 + 小写归一 + 唯一性检查);用户列表的 `keyword` 也搜邮箱;
|
||||
- 注册开关 `config.register.enable`(环境变量 `REGISTER_ENABLED`,默认开):关掉后发码与注册接口都返回 403「注册已关闭」;这是面向内部管理的服务,**上线建议关闭**并用 `npm run user:pass` 建号;
|
||||
- **注册必须验证邮箱**(邮箱必填):两步——`POST /api/web/auth/register/code` 发 6 位验证码 → `POST /api/web/auth/register` 带 `code` 校验通过才能建号。
|
||||
- 验证码存 Redis(`packs:verify:register:<email>`,TTL `EMAIL_CODE_TTL`,默认 10 分钟);重发节流(`SET NX`,默认 60 秒);错试超过 `EMAIL_CODE_ATTEMPTS`(默认 5 次)作废;**注册成功才消费验证码**(用户名/邮箱冲突时可改完重提,不用重新收码);
|
||||
- 发信走 `app/service/mail.js`:**未配 `SMTP_HOST` 时是开发模式**(验证码写服务端日志 + 在接口返回里带 `code`,前端直接提示,仅本地/测试);配上 `SMTP_HOST/PORT/USER/PASSWORD/FROM` 后自动改用 nodemailer 真发信(依赖懒加载);
|
||||
- 验证码逻辑不抛异常,统一返回 `{ ok, message }`,失败都是接口报错(Redis 不可用会提示“验证码服务暂不可用”而不是 500);
|
||||
- **邮箱找回密码(发重置链接)**:前端「忘记密码?」页 → `POST /api/web/auth/forgot` 生成带令牌的链接并**发到邮箱** → 邮件里的链接打开前端 `/reset?token=...` 设置新密码 → `POST /api/web/auth/reset` 改哈希(**不自动登录**,要求用新密码再登一次)。
|
||||
- 令牌存 Redis(`app/service/password_reset.js`):`packs:reset:token:<sha256(令牌)>` → 用户 id(TTL `EMAIL_RESET_TTL`,默认 30 分钟)、`packs:reset:user:<id>` → 当前令牌摘要、`packs:reset:sent:<id>` 重发节流(`SET NX`,默认 60 秒);**Redis 里只存摘要,不存令牌原文**(泄库也拿不到可用的链接);
|
||||
- **一次性**:重置成功后 `consume()` 删掉令牌;**重新申请会让旧链接立刻失效**(同一用户只保留最新一条);校验失败的提交(密码太短/两次不一致/令牌不对)**不会**消费令牌;
|
||||
- **防账号枚举**:邮箱格式不对才报错;邮箱未注册或账号被禁用时,提示与成功完全一致(“如果该邮箱已注册,链接已经发出”),并且不发信;
|
||||
- 邮件正文由 `service.mail.sendResetLink()` 生成(与验证码同一套开发模式/SMTP 逻辑:未配 `SMTP_HOST` 时链接写日志 + 接口返回 `url`,前端直接给个可点链接,方便本地点开);
|
||||
- 链接地址默认取当前请求的 host,正式部署建议配 `SITE_URL`(有反代/多域名时更可靠);
|
||||
- 待加固(按需):JWT 是无状态的,重置密码后**旧令牌在过期前仍然有效**(要立即失效可给 `users` 加 `password_changed_at`,鉴权中间件里比对);
|
||||
- **扫码登录**(`app/service/wechat_login.js`):前端登录页在「账号密码 / 注册 / 扫码」三个 tab 之间切(扫码 tab 里就是二维码 + 提示):
|
||||
- **串码**:服务端生成 **6 位数字 + 字母**随机串码(`WECHAT_CODE_LENGTH`,字符集去掉了 0/O/1/I 等易混字符),写进 Redis `packs:wechat:state:<code>` = `pending`(TTL `WECHAT_STATE_TTL`);
|
||||
- **二维码内容 = 本站地址**:`http://<域名>/wechat?spm=1.0.<code>.1`(spm 格式由 `WECHAT_SPM_PATTERN` 决定);二维码图片本身用零依赖的 `qrcode-generator` 现场画成 **SVG**(`GET /api/wechat/qrcode.svg?code=…`)——**不需要任何外链资源**;
|
||||
- **完整时序**(都是我们自己的接口,不需要第三方 JS/iframe):
|
||||
1. 电脑端调 `GET /api/wechat/login`(不带参数)拿 `code` + `qrUrl`,前端登录页把它画成 `<img src="/api/wechat/qrcode.svg?code=…">` → 串码登记为 `pending`;
|
||||
2. 手机扫码打开前端路由 `/wechat?spm=1.0.<code>.1`:
|
||||
- **配了微信** → 前端页重定向到公众号网页授权(`oauth2/authorize`,`scope=snsapi_base` 静默拿 openid,`state=<code>`)→ 微信回调后端 `GET /api/wechat/callback` → `code` 换 `openid`(`WECHAT_API_BASE`)→ 按 `(appid, openid)` 查 `wechat_oauth` 找账号 → 把 Redis 里串码的值改成**用户 id** → 再 302 回前端 `/wechat?ok=1`;
|
||||
- **没配微信**(本机默认)→ 前端页给「确认登录」按钮:要求手机端**已登录**(本地有占位令牌),点确认调 `POST /api/wechat/confirm`(带 `Authorization: Bearer <user JWT>`)把串码的值改成用户 id;
|
||||
3. 电脑端用 `GET /api/wechat/login?code=…&wait=60` 长轮询取结果 → `{ status:'confirmed', token, user }` 存本地即登录完成(前端登录页会自动跳首页);**取走即删(一次性)**。
|
||||
- **JWT 怎么用**:`config.jwt.userExpiresIn`(env `USER_JWT_EXPIRES`,默认 7 天);前端把令牌存 localStorage,调接口时放 `Authorization: Bearer <token>`(`app/middleware/api_auth.js` 只认这个头,不读 cookie/session)。
|
||||
- **长轮询(前端接口)**:`GET /api/wechat/login?code=<code>&wait=60` —— 服务端把请求挂起最多 `WECHAT_POLL_WAIT` 秒(默认 60):
|
||||
- 有人扫码确认 → **立即**返回 `{ status:'confirmed', token, … }`(靠 Redis 发布订阅 `packs:wechat:login:<code>` 唤醒,不是忙轮询;`confirm()` / 微信回调写完状态后 `PUBLISH` 一次);
|
||||
- 到时间还没动静 / 串码已失效 → 返回 `{ status:'refreshed', code:<新码>, spm, qrUrl, expiresIn, waited }` —— **前端直接换二维码继续轮询**,不用自己判断过期;
|
||||
- `wait=0` 或不传 → 不挂起,只回 `{ status:'pending' }`(短轮询模式);
|
||||
- **客户端断开就立即结束挂起**(2026-10-17 修):服务端会监听连接关闭(`res.on('close')`),浏览器导航离开(例如登录页点「返回账号密码登录」)、关页签或前端 `abort()` 时立刻停止等待并释放订阅连接,**不会白等满 `wait` 秒,也不会把串码换掉**(登录页的脚本在 `pagehide` 时会 `abort()` 当前请求);日志里能看到 `[wechat] 客户端已断开,停止等待串码 XXXXXX`;
|
||||
- ⚠️ **前端要自己设超时**(服务端上限 60s,客户端建议 70s):`AbortController` / `AbortSignal.timeout(70000)`,超时就重发一次请求(或退化成短轮询);重启/热更也会断掉长连接,断了重试即可。**反代/网关要把读超时调到 > 60s**(nginx `proxy_read_timeout 90s`),否则会被代理提前切断;
|
||||
```js
|
||||
let code = null;
|
||||
async function loop() {
|
||||
const url = code ? `/api/wechat/login?code=${code}&wait=60` : '/api/wechat/login';
|
||||
const ac = new AbortController();
|
||||
const timer = setTimeout(() => ac.abort(), 70000); // 前端超时 > 服务端 wait
|
||||
let r;
|
||||
try {
|
||||
r = await (await fetch(url, { signal: ac.signal })).json();
|
||||
} catch (err) { // 超时/断网 → 重试
|
||||
return setTimeout(loop, 800);
|
||||
} finally { clearTimeout(timer); }
|
||||
const d = r.data;
|
||||
if (d.status === 'confirmed') return localStorage.setItem('token', d.token);
|
||||
if (d.status === 'refreshed') { code = d.code; img.src = d.qrUrl; } // 换新码
|
||||
if (!code) { code = d.code; img.src = d.qrUrl; } // 首次拿码
|
||||
loop();
|
||||
}
|
||||
```
|
||||
- **联调/自测(三个终端就能跑通整个扫码登录)**:
|
||||
```bash
|
||||
# ① 电脑端:拿登录码
|
||||
curl -s http://127.0.0.1:7001/api/wechat/login
|
||||
# → {"ok":true,"data":{"code":"XBUBHP","spm":"1.0.XBUBHP.1","qrUrl":"/login/wechat/qrcode.svg?code=XBUBHP",...}}
|
||||
|
||||
# ② 电脑端:挂在长轮询上等(25s 内有人确认就立即返回,没人扫就换新码)
|
||||
curl -s 'http://127.0.0.1:7001/api/wechat/login?code=XBUBHP&wait=60'
|
||||
|
||||
# ③ 已登录的客户端(或用手机打开 /wechat?spm=1.0.XBUBHP.1):用登录码触发登录
|
||||
curl -s -X POST http://127.0.0.1:7001/api/wechat/confirm \
|
||||
-H 'Authorization: Bearer <用户JWT>' -H 'Content-Type: application/json' \
|
||||
-d '{"code":"XBUBHP"}'
|
||||
# → ② 的请求会立即返回 {"data":{"status":"confirmed","token":"<JWT>",...}}
|
||||
```
|
||||
`POST /api/wechat/confirm` 的 **鉴权完全走 header**(`app/middleware/api_auth.js`:`Authorization: Bearer <用户JWT>`,也认 `X-Access-Token`)——**不读 session/cookie**,所以小程序 / App / SPA 直接帯令牌就行,也不写 session;它返回 401(缺令牌)/ 403(账号被禁用)/ 422(码格式不对)/ 410(码失效、已过期或已用过);`/api/*` 不过 CSRF,所以 curl 不用带 token。
|
||||
- **不自动建号**:扫码只对已绑定微信的账号生效(绑定关系在 `wechat_oauth`,可用 `POST /api/wechat/bind` 写入),未绑定会提示先用账号密码登录;账号被禁用(`status != 1`)拒绝登录;
|
||||
- **小程序接入**(小程序里「扫码 → 直接登录电脑端」):接口都是 JSON,**鉴权只看 header 里的 `Authorization: Bearer <用户 JWT>`,不认 cookie/session**(`app/middleware/api_auth.js`);用户 JWT 用 `USER_JWT_EXPIRES`(默认 7d)控制有效期,由登录接口/扫码登录接口下发。
|
||||
```js
|
||||
// 小程序侧:扫登录页上的二维码(内容 http://<域名>/wechat?spm=1.0.<码>.1)
|
||||
wx.scanCode({
|
||||
success (scan) {
|
||||
// ① 先问一下这个码还在不在(可选,但能给出更好的提示)
|
||||
wx.request({
|
||||
url: `https://<域名>/api/wechat/status?spm=${encodeURIComponent(scan.result)}`,
|
||||
success (r) {
|
||||
// r.data.data.status: pending(待扫)/ confirmed(已被确认)/ expired(没这个码)
|
||||
}
|
||||
});
|
||||
|
||||
// ② 确认登录:把扫到的整条地址丢进来就行(接口自己抽 6 位码)
|
||||
wx.request({
|
||||
url: 'https://<域名>/api/wechat/confirm',
|
||||
method: 'POST',
|
||||
header: { 'Content-Type': 'application/json', Authorization: 'Bearer ' + userJwt },
|
||||
data: { spm: scan.result }, // 也可以传 { code: 'AB12CD' }
|
||||
success (r) {
|
||||
if (r.statusCode === 200 && r.data.data.status === 'confirmed') {
|
||||
wx.showToast({ title: '登录成功' }); // 电脑端那台浏览器已经进系统了
|
||||
} else {
|
||||
wx.showToast({ title: r.data.message, icon: 'none' }); // 401/422/410 的错误原因
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
```
|
||||
返回:成功 `HTTP 200 { ok:true, data:{ status:'confirmed', code, spm, user:{ id, username, nickname } } }`;
|
||||
失败 `HTTP 401 status=unauthorized`(没带/过期令牌)、`422 bad_format`(码格式不对)、`410 expired`(没这个码/已过期)、`410 used`(已被用过);
|
||||
- **设备专用:扫码登录 + 注册(`GET /api/device/login`,`app/controller/device.js`)**:给「设备上不好敲账号密码、甚至**出厂什么都不用配**」的场景用——
|
||||
**登录即注册**:设备插上电直接要一个登录码显示在**设备屏幕上**,用已经登录的手机(小程序/网页)扫一下确认,
|
||||
服务端**这才**把设备注册到那个账号名下(归属 = 确认登录的人),并把**长期 JWT** 发给设备
|
||||
(默认 365 天,见 `config.jwt.deviceExpiresIn` / env `DEVICE_JWT_EXPIRES`;
|
||||
设备可用 `?expiresIn=30d`(或秒数)申请**更短**的,超上限 422):
|
||||
- **不需要凭据、也不需要预先注册**(与 `GET /api/wechat/login` 一样是公开接口);
|
||||
- **不带 `code`**:发一张新登录码(此时**库里还没有任何记录**),返回
|
||||
`{ status:'pending', expiresIn, code, spm, origin, qrContent, qrImageUrl, qrUrl, device:{ sn, name } }`
|
||||
—— **域名不用设备自己拼**:`qrContent` 就是二维码里该编的**完整**网址(`http://<域名>/wechat?spm=…`),
|
||||
`qrImageUrl` 是完整地址的现成 SVG(设备不会画二维码就直接拉这张图),`qrUrl` 是它的相对路径,`origin` 是本次用的域名;
|
||||
域名取 `SITE_URL`(`config.email.siteUrl`)——有反代/多域名、或**设备走内网而扫码的手机要走公网**时建议配上;没配就用设备请求时的 origin(设备访问服务用的那个地址);
|
||||
- **设备信息(可选)**:`?sn=`(设备序列号)、`name` / `vendor` / `model` / `firmware`;**发码时带上最省事**
|
||||
(服务端暂存 `packs:device:info:<code>`,确认/换码时沿用),轮询时再带(补齐/覆盖)也行;不带 SN 时服务端注册那一步生成一个 `DEV-…` 并返回给设备保存;
|
||||
- **带 `?code=&wait=N`**:**长轮询**(与 `/api/wechat/login` 完全同一套实现与上限 `WECHAT_POLL_WAIT`,默认 60s):
|
||||
- 手机确认 → **立即**返回 `{ status:'confirmed', firstTime, sn, token, tokenType, expiresIn, expiresAt, scanner, user }`;
|
||||
- 到时间没人扫 / 码已失效 → `{ status:'refreshed', code:<新码>, spm, qrContent, qrImageUrl, … }`(设备换二维码后继续轮询);
|
||||
- 设备断开(重启/换页)→ 服务端**立刻**停止等待(`aborted`,不写响应、也不换码);
|
||||
- 不带 `wait` 就是短轮询,只查一次(`pending` 时还带 `expiresIn` 剩余秒数);
|
||||
- **确认仍走现有接口** `POST /api/wechat/confirm`(**不为设备新增确认接口**);用的也是同一套 6 位串码,
|
||||
所以设备码同样能被 `GET /api/wechat/status` 查、也能被手机上的 `/wechat?spm=…` 页面消费;
|
||||
- **确认成功(就是「注册」发生的时刻,`service/scanner.js` 的 `loginByScan()`)**:
|
||||
- 该 SN 没有记录 → **新建**:绑到确认的用户,`firstTime: true`(记录是在确认那一刻才建的);
|
||||
- 该 SN 已有记录且**无主**(历史数据里的 `user_id = NULL`)或**曾被软删** → 由确认者**认领**(软删的 `restore()` 复活),`firstTime: false`;
|
||||
- 该 SN **已绑定到别的账号** → **403**,拒绝(避免扫一下就把别人的设备换绑走);设备被禁用(`status=0`)→ 403;
|
||||
- 无论哪条路径都会换发长期 JWT(`jti` 轮换 → 设备上一次的令牌立即失效);
|
||||
- 登录码**一次性**:被设备取走即删除(同一张码不能给第二台设备用,浏览器页面长轮询与设备长轮询谁先取走算谁的);
|
||||
- 联调(**新设备不需要先注册**;第三终端是已登录的手机/小程序):
|
||||
```bash
|
||||
# ① 设备发码(拿 code / qrContent / qrImageUrl 显示二维码;带上自己的 SN 与名称)
|
||||
curl -s 'http://127.0.0.1:7001/api/device/login?sn=SN-NEW-01&name=门口扫码枪'
|
||||
|
||||
# ② 设备挂长轮询(有人确认就立即返回;参数带上也行)
|
||||
curl -s 'http://127.0.0.1:7001/api/device/login?sn=SN-NEW-01&code=<登录码>&wait=60'
|
||||
|
||||
# ③ 手机确认(现有接口,鉴权走 header,不认 cookie)
|
||||
curl -s -X POST http://127.0.0.1:7001/api/wechat/confirm \
|
||||
-H 'Authorization: Bearer <用户JWT>' -H 'Content-Type: application/json' \
|
||||
-d '{"code":"<登录码>"}'
|
||||
# → ② 立即返回 {"data":{"status":"confirmed","firstTime":true,"sn":"SN-NEW-01",
|
||||
# "token":"<长期JWT>","expiresIn":"365d","expiresAt":"...","scanner":{...},"user":{...}}}
|
||||
```
|
||||
- 设备端逻辑(伪代码,轮询到 `refreshed` 就换二维码继续):
|
||||
```js
|
||||
const sn = localStorage.getItem('sn') || 'SN-NEW-01'; // 设备自己的序列号(可固定)
|
||||
let code = null;
|
||||
for (;;) {
|
||||
const url = code
|
||||
? `/api/device/login?code=${code}&wait=60&sn=${sn}`
|
||||
: `/api/device/login?sn=${sn}&name=门口扫码枪`;
|
||||
const r = await (await fetch(url)).json();
|
||||
const d = r.data;
|
||||
if (d.status === 'confirmed') {
|
||||
saveToken(d.token); // 长期 JWT(365d),后续请求带 Authorization: Bearer
|
||||
saveSn(d.sn); // 服务端确认的 SN(没自带 SN 时以这个为准)
|
||||
break;
|
||||
}
|
||||
code = d.code; // pending / refreshed 都带回可用的码
|
||||
showQrcode(d.qrContent); // 直接编 qrContent(已是完整网址,设备无需知道域名)
|
||||
}
|
||||
```
|
||||
- 未配 `WECHAT_APPID`/`WECHAT_SECRET`(本机默认):二维码照旧本地生成(内容是本站 `/wechat?spm=…`),扫码面板**不显示任何说明文字**(只留二维码 + 「返回账号密码登录」),扫码后走「手机确认登录」降级路径;
|
||||
- 新增/重置登录账号:`npm run user:pass -- <账号> <密码> [昵称]`。
|
||||
- 设备身份**只有长期 JWT 一种**:列表/详情/`me` 接口**不会**返回 `token_jti`(`sanitize()` 兜底);`secret_hash` 是历史字段(已不再写入)。
|
||||
- **软删除的行仍占着唯一键**:`scanners.sn` 是唯一键而 `deleted_at` 的软删行还在库里,所以扫码登录(`loginByScan()`)**带上已删除的一起查**,命中就把那条记录**复活**(`restore()`,与 `scan.js` 里通道的处理一致),否则 `create` 会撞唯一键;
|
||||
- 前端「设备管理」页的解绑/删除按钮调 `POST /api/web/devices/:id/unbind` 与 `DELETE /api/web/devices/:id`;前端「测试页」提交后直接展示结果(含长期 JWT),刷新页签不会重复建设备(同 SN = 同一台,只换发令牌);
|
||||
- 扫描器接口 `/api/scanner/{me,heartbeat}` 走 `app/middleware/scanner_auth.js` 的 JWT 鉴权;接口里的“缺令牌→401 / 被禁用→403 / jti 被轮换→401”语义见上文「扫描器通讯用的长期 JWT」;
|
||||
- 设备扫码登录 `GET /api/device/login` **不需要任何凭据、也不需要设备预先注册**:发码只写 Redis(库里不建任何东西),
|
||||
确认成功那一刻(就是「注册」时刻)才按 SN 建/取记录、绑定到确认登录的用户、发长期 JWT;确认环节复用
|
||||
`POST /api/wechat/confirm` 与同一套 6 位串码(`service/wechatLogin`),**不新增确认接口、不新增 Redis key 空间**;
|
||||
`SN 已属于其他账号 → 403`(不会把别人的设备扫走),无主记录(老接口注册出来的)由本次确认者认领;
|
||||
- **没有 CSRF**:后端已关掉 CSRF(`config.security.csrf.enable = false`),页面表单/会话都没了;扫描器用 JWT 调 JSON 接口不会遇到 403;
|
||||
- 扫码去重放在**数据库唯一键 + 服务层预过滤**两层:唯一键 `(scanner_id, channel_id, barcode, scan_time)` 是最终保证,服务层先查一次再做批量插入(并发撞键时退化为逐条插入并计数),所以重复上报既不报错也不产生脏数据;
|
||||
- 扫码记录是**流水表、不用软删除**(`paranoid: false`):软删除会让记录占用唯一键,导致同一条数据无法再入库;清理请按时间物理删除;
|
||||
- 中控上报遇到未登记的通道会自动补建一行(`channel_name` 留空 + WARN 日志),避免丢数据;若希望严格模式,可在 `app/service/scan.js` 的 `touchChannels()` 里改成抛错;
|
||||
- 前端「测试页」的「模拟中控上报」卡片用**设备 SN + 长期 JWT** 校验身份(验签 + 回查 + 比对 `jti`,与 `middleware/scannerAuth()` 同一条 `service.scanner.resolveByToken()`),再走 `service.scan.*`,等价于设备的 `POST /api/scan/channels` + `POST /api/scan/records`(提交两次即可看到 `duplicated=1`);令牌就是上一张卡片发下来的那枚,重新扫码登录会换新令牌(旧令牌立即失效);
|
||||
- 前端「测试页」的「模拟扫码授权(AJAX)」卡片:一个输入框(填登录码,或直接贴 `/wechat?spm=…` 整条地址)+「查状态」「请求登录」两个按钮,**AJAX 调接口并把返回的 JSON 原样显示,不跳转**:
|
||||
- 「查状态」→ `GET /api/wechat/status?code=…`(无需登录):`pending`(待扫码)/ `confirmed`(已被确认)/ `expired`(没这个码);
|
||||
- 「请求登录」→ `POST /api/wechat/confirm`(`{ code }`):`data.status='confirmed'` 即授权成功,电脑端正在长轮询的请求会**立即**完成登录;已用过/不存在/格式错分别返回 `used` / `expired` / `bad_format`;
|
||||
- **鉴权完全模仿小程序**:AJAX 把用户 JWT 放在 `Authorization: Bearer` 头里(`fetch` 不带 `credentials`),页面上也把这枚令牌显示出来方便贴到小程序里调试;
|
||||
- **鉴权总览**:`/api/web/*`、`/api/wechat/confirm` 走 `app/middleware/api_auth.js`(**只认 header 里的用户令牌**);`/api/users*`、`/api/configs*`、`/api/scanners*` 走 `app/middleware/internal_auth.js`(`X-Internal-Token` 或白名单账号的 user JWT);`/api/scanner/*`、`/api/scan/*` 走 `app/middleware/scanner_auth.js`(设备长期 JWT);公开接口只有 `/api/info`、`/health`、`/api/wechat/{login,status,qrcode.svg,callback}`、`/api/device/login` 与 `/api/web/auth/*`;
|
||||
- 密码等敏感信息放 `config/config.local.js`(已 gitignore)或环境变量,不要写进 `config.default.js`。
|
||||
- 生产环境请修改 `config/config.default.js` 中的 `config.keys`。
|
||||
169
backend/app/controller/auth/wechat.js
Normal file
169
backend/app/controller/auth/wechat.js
Normal file
@ -0,0 +1,169 @@
|
||||
'use strict';
|
||||
|
||||
const { Controller } = require('egg');
|
||||
|
||||
/**
|
||||
* 扫码登录的**公开**接口(发码 / 查码)—— 谁来调都行,不需要令牌
|
||||
*
|
||||
* 面向:登录页(浏览器内联脚本)、Win 客户端、任何想自己画二维码显示的前端。
|
||||
* 确认环节在 `app/controller/client/wechat.js`(需要 user JWT);设备端扫码登录在 `app/controller/device/auth.js`。
|
||||
*/
|
||||
class WechatAuthController extends Controller {
|
||||
/**
|
||||
* GET /api/wechat/qrcode.svg?code=xxxxxx —— 登录码的二维码(SVG,**本地生成**,零外链)
|
||||
* 内容就是本站地址 `/wechat?spm=1.0.<码>.1`(手机扫到后打开前端路由)
|
||||
*/
|
||||
async qrcode() {
|
||||
const { ctx } = this;
|
||||
const code = String(ctx.query.code || '');
|
||||
const content = ctx.service.wechatLogin.qrContent({ code, origin: ctx.app.config.email.siteUrl || ctx.origin });
|
||||
|
||||
ctx.set('Cache-Control', 'no-store');
|
||||
ctx.type = 'image/svg+xml; charset=utf-8';
|
||||
ctx.body = ctx.service.wechatLogin.qrSvg(content);
|
||||
}
|
||||
|
||||
/**
|
||||
* GET /api/wechat/login —— 扫码登录接口(前端 JS/SPA 用,不依赖页面渲染)
|
||||
* - **不带参数**:生成一个 6 位串码(数字+字母,存 Redis)并返回二维码地址,前端拿去画二维码;
|
||||
* - **带 `?code=`**:轮询状态;手机确认后:**写入登录会话 + 返回用户 JWT**,前端存下 JWT 即完成登录。
|
||||
*/
|
||||
async login() {
|
||||
const { ctx } = this;
|
||||
const svc = ctx.service.wechatLogin;
|
||||
const raw = String(ctx.query.code || '').trim();
|
||||
|
||||
if (!raw) {
|
||||
const code = await svc.newCode();
|
||||
ctx.body = {
|
||||
ok: true,
|
||||
data: {
|
||||
code,
|
||||
spm: svc.spm(code),
|
||||
qrUrl: `/api/wechat/qrcode.svg?code=${encodeURIComponent(code)}`,
|
||||
expiresIn: svc.stateTtl,
|
||||
},
|
||||
};
|
||||
return;
|
||||
}
|
||||
|
||||
const code = raw.toUpperCase();
|
||||
const expect = Number(ctx.app.config.wechat.codeLength || 6);
|
||||
if (!new RegExp(`^[0-9A-Z]{${expect}}$`).test(code)) {
|
||||
ctx.status = 422;
|
||||
ctx.body = { ok: false, message: `code 格式不对(${expect} 位数字 + 字母)` };
|
||||
return;
|
||||
}
|
||||
|
||||
// ?wait=25 走长轮询(最多挂起到 config.wechat.pollWait):有人登录立即返回,
|
||||
// 到时间还没动静就直接给一张新码(status=refreshed),前端换二维码后继续请求
|
||||
const result = await svc.awaitLogin(code, { wait: ctx.query.wait });
|
||||
|
||||
if (result.status === 'aborted') {
|
||||
// 客户端已经断开(切回账号密码登录 / 关页签 / 前端 abort):没什么可回的,也不用写响应
|
||||
ctx.respond = false;
|
||||
return;
|
||||
}
|
||||
|
||||
if (result.status === 'refreshed') {
|
||||
ctx.body = {
|
||||
ok: true,
|
||||
data: {
|
||||
status: 'refreshed',
|
||||
code: result.code,
|
||||
spm: svc.spm(result.code),
|
||||
qrUrl: `/api/wechat/qrcode.svg?code=${encodeURIComponent(result.code)}`,
|
||||
expiresIn: svc.stateTtl,
|
||||
waited: result.waited || 0,
|
||||
},
|
||||
};
|
||||
return;
|
||||
}
|
||||
if (result.status !== 'confirmed') {
|
||||
ctx.body = { ok: true, data: { status: result.status } };
|
||||
return;
|
||||
}
|
||||
|
||||
// 手机已确认:后端只下发 JWT(前端存本地),**不写 cookie/session**
|
||||
const user = result.user;
|
||||
ctx.logger.info('[wechat] %s 扫码登录成功(API)', user.username);
|
||||
|
||||
ctx.body = {
|
||||
ok: true,
|
||||
data: {
|
||||
status: 'confirmed',
|
||||
token: result.token,
|
||||
tokenType: result.tokenType,
|
||||
expiresIn: result.expiresIn,
|
||||
user: {
|
||||
id: user.id,
|
||||
username: user.username,
|
||||
nickname: user.nickname || null,
|
||||
email: user.email || null,
|
||||
phone: user.phone || null,
|
||||
avatar: user.avatar || null,
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* GET /api/wechat/callback?code=&state= —— 微信公众号网页授权回调
|
||||
*
|
||||
* 微信把**手机浏览器**重定向到这里(回调地址可在微信平台配 `WECHAT_REDIRECT_URI`,
|
||||
* 不配就用 `<origin>/api/wechat/callback`)。这里不登录扫码设备,只把「已确认的用户 id」
|
||||
* 写进 Redis,等电脑上的登录页长轮询取走;处理完把浏览器转回**前端**的 `/wechat` 路由,
|
||||
* 由前端给出“已确认/失败”的文案。
|
||||
*/
|
||||
async callback() {
|
||||
const { ctx } = this;
|
||||
const state = String(ctx.query.state || '');
|
||||
const result = await ctx.service.wechatLogin.login(String(ctx.query.code || ''), state);
|
||||
|
||||
if (!result.ok) ctx.logger.warn('[wechat] 扫码失败: %s', result.message);
|
||||
|
||||
const spm = ctx.service.wechatLogin.parseSpm(state) ? ctx.service.wechatLogin.spm(state) : '';
|
||||
const base = String(ctx.app.config.email.siteUrl || ctx.origin || '').replace(/\/+$/, '');
|
||||
const query = new URLSearchParams({ ok: result.ok ? '1' : '0' });
|
||||
if (spm) query.set('spm', spm);
|
||||
if (!result.ok) query.set('message', result.message || '扫码失败,请重新扫码');
|
||||
|
||||
ctx.redirect(`${base}/wechat?${query.toString()}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* GET /api/wechat/status —— 查串码状态(**无需登录**,小程序/网页先问一下再决定怎么提示)
|
||||
*
|
||||
* query: `?code=` 或 `?spm=`(也可以直接把二维码里扫到的整条地址丢进来)
|
||||
* 返回 `data.status`:pending(待扫码)/ confirmed(已被确认)/ expired(不存在或已过期,即“没这个码”)
|
||||
*/
|
||||
async status() {
|
||||
const { ctx } = this;
|
||||
const svc = ctx.service.wechatLogin;
|
||||
const code = svc.parseSpm(ctx.query.code || ctx.query.spm);
|
||||
|
||||
if (!code) {
|
||||
ctx.status = 422;
|
||||
ctx.body = {
|
||||
ok: false,
|
||||
status: 'bad_format',
|
||||
message: `登录码格式不对(${Number(ctx.app.config.wechat.codeLength || 6)} 位数字 + 字母)`,
|
||||
};
|
||||
return;
|
||||
}
|
||||
|
||||
const state = await svc.statusOf(code);
|
||||
ctx.body = {
|
||||
ok: true,
|
||||
data: {
|
||||
status: state.status,
|
||||
code,
|
||||
spm: svc.spm(code),
|
||||
qrUrl: `/api/wechat/qrcode.svg?code=${encodeURIComponent(code)}`,
|
||||
expiresIn: state.expiresIn,
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = WechatAuthController;
|
||||
72
backend/app/controller/client/wechat.js
Normal file
72
backend/app/controller/client/wechat.js
Normal file
@ -0,0 +1,72 @@
|
||||
'use strict';
|
||||
|
||||
const { Controller } = require('egg');
|
||||
|
||||
/**
|
||||
* 用户态接口(小程序 / Win 客户端 / SPA 共用)
|
||||
*
|
||||
* 鉴权:`middleware.apiAuth()` —— **只认 header 里的 user JWT**(`Authorization: Bearer <token>`,
|
||||
* 也认 `X-Access-Token`),不看 cookie / session;用户令牌自带 `typ: 'user'`,
|
||||
* 与设备令牌(`typ: 'scanner'`)互不通用。
|
||||
*
|
||||
* 小程序和 Win 客户端之所以共用一套路径:它们身份相同(都是「某个登录用户」),
|
||||
* 区别只在登录入口;要区分用途请用 header(如 `X-Client: miniapp|win`),不要复制一套路径。
|
||||
*/
|
||||
class ClientWechatController extends Controller {
|
||||
/**
|
||||
* POST /api/wechat/confirm —— 把登录码断权给当前登录用户(触发电脑端/客户端登录)
|
||||
*
|
||||
* 典型用法(小程序):扫码拿到 `http://<域名>/wechat?spm=1.0.<码>.1`,把扫到的整串、
|
||||
* `spm` 或 6 位 `code` 丢过来即可(接口自己抽码);后端把码断权给当前登录用户,
|
||||
* 电脑端正在长轮询的请求会**立即**拿到 JWT 完成登录。
|
||||
*
|
||||
* 需要登录:**只看 header**(`Authorization: Bearer <user JWT>` 或 `X-Access-Token`),不认 cookie
|
||||
* body: `{ code | spm }`,也支持 `?code=` / `?spm=`(JSON / 表单 / query 都行)
|
||||
*
|
||||
* 返回:成功 `data.status=confirmed`;失败时 body.status = bad_format(422) / expired(410) /
|
||||
* used(410) / unauthorized(401) / forbidden(403)
|
||||
*/
|
||||
async confirm() {
|
||||
const { ctx } = this;
|
||||
const body = ctx.request.body || {};
|
||||
const raw = body.code || body.spm || ctx.query.code || ctx.query.spm;
|
||||
// 用户只从 header 令牌解析(middleware/api_auth.js 挂的),不从 session 取
|
||||
const user = (ctx.locals && ctx.locals.user) || (ctx.state && ctx.state.user) || null;
|
||||
const userId = user && user.id;
|
||||
|
||||
const code = ctx.service.wechatLogin.parseSpm(raw);
|
||||
if (!code) {
|
||||
ctx.status = 422;
|
||||
ctx.body = {
|
||||
ok: false,
|
||||
status: 'bad_format',
|
||||
message: `登录码格式不对(${Number(ctx.app.config.wechat.codeLength || 6)} 位数字 + 字母)`,
|
||||
};
|
||||
return;
|
||||
}
|
||||
|
||||
const result = await ctx.service.wechatLogin.confirm(code, userId);
|
||||
if (!result.ok) {
|
||||
// 码不存在/已过期/已被用过 → 410;参数不全 → 422
|
||||
ctx.status = result.reason === 'bad_param' ? 422 : 410;
|
||||
ctx.body = { ok: false, status: result.reason, message: result.message };
|
||||
return;
|
||||
}
|
||||
|
||||
ctx.body = {
|
||||
ok: true,
|
||||
data: {
|
||||
status: 'confirmed',
|
||||
code,
|
||||
spm: ctx.service.wechatLogin.spm(code),
|
||||
user: {
|
||||
id: userId,
|
||||
username: (user && user.username) || null,
|
||||
nickname: (user && user.nickname) || null,
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = ClientWechatController;
|
||||
237
backend/app/controller/device/auth.js
Normal file
237
backend/app/controller/device/auth.js
Normal file
@ -0,0 +1,237 @@
|
||||
'use strict';
|
||||
|
||||
const { Controller } = require('egg');
|
||||
|
||||
/**
|
||||
* 取设备自报信息(**全部可选**,不带也能用)
|
||||
* 设备上**不需要预先注册/预先配密钥**:发码与轮询时把自己的序列号等信息带上,
|
||||
* 服务端在「确认登录成功」那一步才用它建记录。
|
||||
*/
|
||||
function deviceInfo(ctx) {
|
||||
const q = ctx.query;
|
||||
return {
|
||||
sn: String(q.sn || '').trim() || null,
|
||||
name: q.name || '',
|
||||
vendor: q.vendor || null,
|
||||
model: q.model || null,
|
||||
firmware: q.firmware || null,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 合并设备信息:本次请求里带了就用请求的(空值不算),没带就用发码时暂存的那份
|
||||
* (建记录发生在确认/换码那一刻,设备只在发码时带过 sn/名称也能生效)
|
||||
*/
|
||||
function mergeInfo(fromQuery, stashed) {
|
||||
const info = Object.assign({}, stashed || {});
|
||||
for (const [ key, value ] of Object.entries(fromQuery)) {
|
||||
if (value !== null && value !== '' && value !== undefined) info[key] = value;
|
||||
}
|
||||
return info;
|
||||
}
|
||||
|
||||
/**
|
||||
* 令牌时长:默认 `config.jwt.deviceExpiresIn`(env `DEVICE_JWT_EXPIRES`,默认 365d),
|
||||
* 设备可以用 `?expiresIn=30d`(或 `3600` 秒)申请**更短**的;超过上限直接 422
|
||||
* (要整体放宽就改配置,不让单个设备自己把令牌拉长)
|
||||
* @return {{spec:string|number, seconds:number}} spec 用于回显,seconds 用于签发
|
||||
*/
|
||||
function resolveTokenDuration(ctx) {
|
||||
const { jwt } = ctx.app.config;
|
||||
const current = String(jwt.deviceExpiresIn || jwt.scannerExpiresIn || '365d');
|
||||
const max = ctx.service.jwt.parseDuration(current);
|
||||
const raw = String(ctx.query.expiresIn || '').trim();
|
||||
|
||||
if (!raw) return { spec: current, seconds: max };
|
||||
|
||||
const seconds = ctx.service.jwt.parseDuration(raw);
|
||||
if (!seconds) {
|
||||
ctx.throw(422, 'expiresIn 格式不对(支持 30d / 12h / 90m / 3600 这类写法)');
|
||||
}
|
||||
if (max && seconds > max) {
|
||||
ctx.throw(422, `expiresIn 不能超过服务端上限 ${current}(要放宽请改 DEVICE_JWT_EXPIRES)`);
|
||||
}
|
||||
return { spec: /^\d+$/.test(raw) ? Number(raw) : raw, seconds };
|
||||
}
|
||||
|
||||
/**
|
||||
* 设备(扫描器)专用接口
|
||||
*
|
||||
* **登录即注册**:设备出厂后什么都不用配,插上电调本接口拿到一个登录码显示出来,
|
||||
* 用已经登录的手机(小程序/网页)扫一下确认,服务端这才把设备**注册**到那个账号名下,
|
||||
* 并把**长期 JWT**(默认 365 天,见 `config.jwt.scannerExpiresIn`)发给设备。
|
||||
* 不会再出现「先注册出一条无主记录、回头再绑定」的顺序问题。
|
||||
*/
|
||||
class DeviceController extends Controller {
|
||||
/**
|
||||
* 登录码相关的响应字段(**带完整域名**)
|
||||
*
|
||||
* 设备常常**不知道本站域名**(或只知道内网 IP),所以这里直接把「二维码里该编什么」算好给它:
|
||||
* - `qrContent`:二维码要编码的**完整**网址 `http://<域名>/wechat?spm=…`,直接拿去生成二维码;
|
||||
* - `qrImageUrl`:本站现成 SVG 二维码的**完整**地址(设备不会画二维码时可直接拉这张图;内容与本接口一致);
|
||||
* - `qrUrl`:同上的相对路径(老字段,给只需要相对路径的客户端用);
|
||||
* - `origin`:本次用的域名(调试/纯文本展示用)。
|
||||
*
|
||||
* 域名优先取 `SITE_URL`(`config.email.siteUrl`,有反代/多域名/内网设备而对端要走公网时建议配上),
|
||||
* 没配就用设备请求时的 origin(也就是设备访问服务用的那个地址)。
|
||||
* @param {string} code 登录码
|
||||
*/
|
||||
qrFields(code) {
|
||||
const { ctx } = this;
|
||||
const base = String(ctx.app.config.email.siteUrl || ctx.origin || '').replace(/\/+$/, '');
|
||||
const path = `/api/wechat/qrcode.svg?code=${encodeURIComponent(code)}`;
|
||||
|
||||
return {
|
||||
code,
|
||||
spm: ctx.service.wechatLogin.spm(code),
|
||||
origin: base,
|
||||
qrContent: ctx.service.wechatLogin.qrContent({ code, origin: base }),
|
||||
qrImageUrl: `${base}${path}`,
|
||||
qrUrl: path,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* GET /api/device/login —— 设备专用「扫码登录 + 注册/绑定」(参考 `GET /api/wechat/login`,区别是下发**长期** JWT)
|
||||
*
|
||||
* 设备信息(`?sn=` 设备序列号、`name` / `vendor` / `model` / `firmware`)**都是可选的**:
|
||||
* **发码时带上最省事**(服务端会暂存,确认/换码时沿用),轮询时再带上(补齐/覆盖)也行;
|
||||
* 不带 SN 时服务端在注册那一步生成一个(`DEV-…`)并返回给设备保存。
|
||||
*
|
||||
* 三种用法(**不需要任何凭据**,与 `GET /api/wechat/login` 一样是公开接口):
|
||||
* 1. **不带 `code`**:发一张新登录码(登记为 pending)→ `{ status:'pending', expiresIn, code, spm,
|
||||
* origin, qrContent, qrImageUrl, qrUrl, device:{ sn, name } }`;**此时还没有注册任何东西**;
|
||||
* 2. **带 `code=&wait=N`**:**长轮询**(挂起最多 `WECHAT_POLL_WAIT` 秒,默认 60)——
|
||||
* 手机用 `POST /api/wechat/confirm` 确认后**立即**返回;
|
||||
* 到时间没人扫 / 码失效 → `refreshed` + 一张新码(设备换二维码后继续轮询,参数照旧带上);
|
||||
* 设备断开 → 服务端立刻停止等待(`aborted`,不写响应、也不换码);
|
||||
* 3. **带 `code` 不带 `wait`**:短轮询,只查一次。
|
||||
*
|
||||
* **确认成功后**(就是「注册」发生的时刻,归属 = 扫码确认的那个用户):
|
||||
* - 该 SN 没有记录 → **新建**:绑到该用户,`firstTime: true`;
|
||||
* - 该 SN 已有记录且**无主**(或曾被软删)→ 由确认者**认领**(复活),`firstTime: false`;
|
||||
* - 该 SN **已绑定到别的账号** → 403,拒绝(避免把别人的设备扫走);设备被禁用 → 403;
|
||||
* - 换发长期 JWT(`jti` 轮换 → 设备上一次的令牌立即失效),返回 `token` / `expiresIn` / `expiresAt`。
|
||||
*
|
||||
* **令牌时长**:默认 `config.jwt.deviceExpiresIn`(env `DEVICE_JWT_EXPIRES`,默认 365d);
|
||||
* 设备可用 `?expiresIn=30d`(或秒数,如 `3600`)申请**更短**的,超过上限返回 422
|
||||
* (要整体放宽改 `DEVICE_JWT_EXPIRES`,不允许单个设备把令牌拉长)。
|
||||
*
|
||||
* 返回 `data.status`:
|
||||
* - `pending`(已发码,等扫码)/ `confirmed`(成功:`token` + `sn` + `firstTime` + `expiresAt` + `scanner` + `user`)
|
||||
* - `refreshed`(码没了/等超时:`code`/`spm`/`qrContent`… 是新的一张,直接换二维码)
|
||||
* - 失败:403(SN 已被别人绑定 / 设备被禁用)、422(`expiresIn` 格式不对或超上限、`code` 格式不对)
|
||||
*/
|
||||
async login() {
|
||||
const { ctx } = this;
|
||||
const svc = ctx.service.wechatLogin;
|
||||
const info = deviceInfo(ctx);
|
||||
const tokenDuration = resolveTokenDuration(ctx);
|
||||
const raw = String(ctx.query.code || '').trim();
|
||||
|
||||
// ① 没带 code:发一张新码给设备显示(**公开接口,不需要先注册**)
|
||||
if (!raw) {
|
||||
const code = await svc.newCode();
|
||||
// 设备自报信息暂存一份(可选):确认成功那一刻才是建记录的时机,这样漏传也能沿用
|
||||
await svc.saveDeviceInfo(code, info);
|
||||
ctx.body = {
|
||||
ok: true,
|
||||
data: Object.assign(
|
||||
{ status: 'pending', expiresIn: svc.stateTtl },
|
||||
this.qrFields(code),
|
||||
{ device: { sn: info.sn, name: info.name || null } },
|
||||
),
|
||||
};
|
||||
return;
|
||||
}
|
||||
|
||||
// ② 带 code:校验格式后长轮询(长度/字符集与登录页的码一致)
|
||||
const code = raw.toUpperCase();
|
||||
const expect = Number(ctx.app.config.wechat.codeLength || 6);
|
||||
if (!new RegExp(`^[0-9A-Z]{${expect}}$`).test(code)) {
|
||||
ctx.status = 422;
|
||||
ctx.body = { ok: false, message: `code 格式不对(${expect} 位数字 + 字母)` };
|
||||
return;
|
||||
}
|
||||
|
||||
// 设备端不需要用户 JWT,所以只取「谁确认了」,长期令牌由这里自己签发
|
||||
const result = await svc.awaitLogin(code, { wait: ctx.query.wait, withToken: false });
|
||||
|
||||
if (result.status === 'aborted') {
|
||||
// 设备断开了(重启/换页):没什么可回的,也不用写响应
|
||||
ctx.respond = false;
|
||||
return;
|
||||
}
|
||||
|
||||
if (result.status === 'refreshed') {
|
||||
// 换码:把设备信息接着存在新码上(否则下一轮拿到新码时 sn/名称就丢了)
|
||||
const kept = mergeInfo(info, await svc.takeDeviceInfo(code));
|
||||
await svc.saveDeviceInfo(result.code, kept);
|
||||
ctx.body = {
|
||||
ok: true,
|
||||
data: Object.assign(
|
||||
{ status: 'refreshed', expiresIn: svc.stateTtl, waited: result.waited || 0 },
|
||||
this.qrFields(result.code),
|
||||
{ device: { sn: kept.sn || null, name: kept.name || null } },
|
||||
),
|
||||
};
|
||||
return;
|
||||
}
|
||||
|
||||
if (result.status !== 'confirmed') {
|
||||
// pending:码还在,继续等就行(顺带把完整二维码地址再给一次,设备可随时重画)
|
||||
ctx.body = {
|
||||
ok: true,
|
||||
data: Object.assign(
|
||||
{ status: result.status, expiresIn: await svc.ttlOf(code) },
|
||||
this.qrFields(code),
|
||||
{ device: { sn: info.sn, name: info.name || null } },
|
||||
),
|
||||
};
|
||||
return;
|
||||
}
|
||||
|
||||
// ③ 有人确认了 —— **这一步才注册/绑定**(归属就是确认登录的人),并换发长期 JWT
|
||||
const user = result.user;
|
||||
const merged = mergeInfo(info, await svc.takeDeviceInfo(code));
|
||||
const data = await ctx.service.scanner.loginByScan(Object.assign({}, merged, {
|
||||
userId: user.id,
|
||||
ip: ctx.ip,
|
||||
expiresIn: tokenDuration.seconds,
|
||||
}));
|
||||
|
||||
ctx.logger.info('[device] %s 扫码登录成功(%s),归属账号 %s',
|
||||
data.sn, data.firstTime ? '首次注册' : '已注册/认领', user.username || user.id);
|
||||
|
||||
ctx.body = {
|
||||
ok: true,
|
||||
data: {
|
||||
status: 'confirmed',
|
||||
firstTime: data.firstTime, // true = 本次扫码才注册出这条记录
|
||||
sn: data.sn,
|
||||
token: data.token,
|
||||
tokenType: data.tokenType,
|
||||
expiresIn: tokenDuration.spec, // 实际生效的时长(数字=秒;字符串=与配置同款写法)
|
||||
expiresAt: data.tokenExpiresAt || null, // 令牌到期时间(绝对时间,方便设备直接排期重扫)
|
||||
scanner: {
|
||||
id: data.id,
|
||||
sn: data.sn,
|
||||
name: data.name || null,
|
||||
userId: data.userId || null,
|
||||
status: data.status,
|
||||
lastSeenAt: data.lastSeenAt || null,
|
||||
},
|
||||
user: {
|
||||
id: user.id,
|
||||
username: user.username || null,
|
||||
nickname: user.nickname || null,
|
||||
email: user.email || null,
|
||||
phone: user.phone || null,
|
||||
avatar: user.avatar || null,
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = DeviceController;
|
||||
93
backend/app/controller/device/scan.js
Normal file
93
backend/app/controller/device/scan.js
Normal file
@ -0,0 +1,93 @@
|
||||
'use strict';
|
||||
|
||||
const { Controller } = require('egg');
|
||||
|
||||
/**
|
||||
* 把上报体里的数组字段取出来,兼容几种写法:
|
||||
* - { channels: [...] } / { records: [...] }
|
||||
* - { channelId, channelName } / { barcode, scanTime, channelId }(单条)
|
||||
* - { channels: '[{...}]' }(JSON 字符串,有些设备端会这么塞)
|
||||
*/
|
||||
function pickList(body, key, single) {
|
||||
const raw = body[key];
|
||||
if (Array.isArray(raw)) return raw;
|
||||
if (typeof raw === 'string' && raw.trim()) {
|
||||
try {
|
||||
const parsed = JSON.parse(raw);
|
||||
if (Array.isArray(parsed)) return parsed;
|
||||
if (parsed && typeof parsed === 'object') return [ parsed ];
|
||||
} catch (_) {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
if (raw && typeof raw === 'object') return [ raw ];
|
||||
if (body[single]) return [ body ];
|
||||
return [];
|
||||
}
|
||||
|
||||
class ScanController extends Controller {
|
||||
/**
|
||||
* POST /api/scan/channels —— 中控上报通道(需长期 JWT)
|
||||
* body: { channels: [{ channelId, channelName }] }
|
||||
* 同一中控 + 同一 channelId 为同一个通道,重复上报即更新通道名
|
||||
*/
|
||||
async reportChannels() {
|
||||
const { ctx } = this;
|
||||
const body = ctx.request.body || {};
|
||||
const channels = pickList(body, 'channels', 'channelId');
|
||||
if (!channels.length) ctx.throw(422, 'channels 不能为空,body 形如 { channels: [{ channelId, channelName }] }');
|
||||
|
||||
const data = await ctx.service.scan.reportChannels(ctx.state.scanner, channels);
|
||||
ctx.body = { ok: true, data };
|
||||
}
|
||||
|
||||
/** GET /api/scan/channels —— 当前中控已登记的通道(需长期 JWT) */
|
||||
async channels() {
|
||||
const { ctx } = this;
|
||||
const { page, pageSize, keyword, status } = ctx.query;
|
||||
const data = await ctx.service.scan.listChannels({
|
||||
page,
|
||||
pageSize,
|
||||
keyword,
|
||||
status,
|
||||
scannerId: ctx.state.scanner.id,
|
||||
});
|
||||
ctx.body = { ok: true, data };
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /api/scan/records —— 中控上报扫码结果(需长期 JWT)
|
||||
* body: { records: [{ barcode, scanTime, channelId }] }
|
||||
* 同一中控 + 通道 + 条码 + 扫描时间(秒) 重复上报只入库一次,不报错
|
||||
*/
|
||||
async reportRecords() {
|
||||
const { ctx } = this;
|
||||
const body = ctx.request.body || {};
|
||||
const records = pickList(body, 'records', 'barcode');
|
||||
if (!records.length) ctx.throw(422, 'records 不能为空,body 形如 { records: [{ barcode, scanTime, channelId }] }');
|
||||
|
||||
const data = await ctx.service.scan.ingest(ctx.state.scanner, records);
|
||||
ctx.body = { ok: true, data };
|
||||
}
|
||||
|
||||
/**
|
||||
* GET /api/scan/records —— 查当前中控上报的扫码记录(需长期 JWT)
|
||||
* query: page / pageSize / channelId / barcode / startTime / endTime
|
||||
*/
|
||||
async records() {
|
||||
const { ctx } = this;
|
||||
const { page, pageSize, channelId, barcode, startTime, endTime } = ctx.query;
|
||||
const data = await ctx.service.scan.listRecords({
|
||||
page,
|
||||
pageSize,
|
||||
channelId,
|
||||
barcode,
|
||||
startTime,
|
||||
endTime,
|
||||
scannerId: ctx.state.scanner.id,
|
||||
});
|
||||
ctx.body = { ok: true, data };
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = ScanController;
|
||||
41
backend/app/controller/device/self.js
Normal file
41
backend/app/controller/device/self.js
Normal file
@ -0,0 +1,41 @@
|
||||
'use strict';
|
||||
|
||||
const { Controller } = require('egg');
|
||||
|
||||
/**
|
||||
* 设备自检 / 保活(**需设备长期 JWT**)
|
||||
*
|
||||
* 鉴权:`middleware.scannerAuth()` —— `Authorization: Bearer <device JWT>`(也认 `X-Scanner-Token` /
|
||||
* `?access_token=`);令牌自带 `typ: 'scanner'`,用户令牌(`typ: 'user'`)用不了。
|
||||
* 令牌来源:`GET /api/device/login`(扫码登录,见 `app/controller/device/auth.js`)。
|
||||
*/
|
||||
class DeviceSelfController extends Controller {
|
||||
/**
|
||||
* GET /api/scanner/me —— 当前设备信息
|
||||
* 需要长期 JWT(Authorization: Bearer <token>,见 app/middleware/scanner_auth.js)
|
||||
*/
|
||||
async me() {
|
||||
const { ctx } = this;
|
||||
const data = await ctx.service.scanner.findById(ctx.state.scanner.id);
|
||||
ctx.body = { ok: true, data };
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /api/scanner/heartbeat —— 设备心跳(需 JWT)
|
||||
* 用于设备与服务之间的连通性保活,同时刷新 IP 与心跳时间
|
||||
*/
|
||||
async heartbeat() {
|
||||
const { ctx } = this;
|
||||
const data = await ctx.service.scanner.heartbeat(ctx.state.scanner, ctx.ip);
|
||||
ctx.body = {
|
||||
ok: true,
|
||||
data: {
|
||||
sn: data.sn,
|
||||
lastSeenAt: data.lastSeenAt,
|
||||
serverTime: new Date().toISOString(),
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = DeviceSelfController;
|
||||
28
backend/app/controller/health.js
Normal file
28
backend/app/controller/health.js
Normal file
@ -0,0 +1,28 @@
|
||||
'use strict';
|
||||
|
||||
const { Controller } = require('egg');
|
||||
|
||||
class HealthController extends Controller {
|
||||
/**
|
||||
* GET /health
|
||||
* 同时探测 MySQL 与 Redis,任一不可用则返回 503
|
||||
*/
|
||||
async index() {
|
||||
const { ctx, app } = this;
|
||||
const [ mysql, redis ] = await Promise.all([
|
||||
ctx.service.health.checkMysql(),
|
||||
ctx.service.health.checkRedis(),
|
||||
]);
|
||||
|
||||
const ok = mysql.ok && redis.ok;
|
||||
ctx.status = ok ? 200 : 503;
|
||||
ctx.body = {
|
||||
ok,
|
||||
env: app.config.env,
|
||||
uptime: Math.round(process.uptime()),
|
||||
dependencies: { mysql, redis },
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = HealthController;
|
||||
18
backend/app/controller/home.js
Normal file
18
backend/app/controller/home.js
Normal file
@ -0,0 +1,18 @@
|
||||
'use strict';
|
||||
|
||||
const { Controller } = require('egg');
|
||||
|
||||
class HomeController extends Controller {
|
||||
async index() {
|
||||
const { ctx, app } = this;
|
||||
ctx.body = {
|
||||
ok: true,
|
||||
name: app.config.name,
|
||||
env: app.config.env,
|
||||
uptime: Math.round(process.uptime()),
|
||||
node: process.version,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = HomeController;
|
||||
67
backend/app/controller/internal/config.js
Normal file
67
backend/app/controller/internal/config.js
Normal file
@ -0,0 +1,67 @@
|
||||
'use strict';
|
||||
|
||||
const { Controller } = require('egg');
|
||||
|
||||
/**
|
||||
* 运维/内部:系统配置(sys_config)读写
|
||||
*
|
||||
* 挂在 `middleware.internalAuth()` 后面;读接口带 Redis 缓存,写接口自动失效。
|
||||
*/
|
||||
class InternalConfigController extends Controller {
|
||||
/** GET /api/configs?group=wechat —— 列表(管理用,含禁用项) */
|
||||
async index() {
|
||||
const { ctx } = this;
|
||||
const list = await ctx.service.config.list({ groupName: ctx.query.group });
|
||||
ctx.body = { ok: true, data: { list, total: list.length } };
|
||||
}
|
||||
|
||||
/** GET /api/configs/:group/:key —— 取单个配置值(带 Redis 缓存) */
|
||||
async show() {
|
||||
const { ctx } = this;
|
||||
const { group, key } = ctx.params;
|
||||
const value = await ctx.service.config.get(group, key);
|
||||
if (value === null) {
|
||||
ctx.status = 404;
|
||||
ctx.body = { ok: false, message: '配置不存在' };
|
||||
return;
|
||||
}
|
||||
ctx.body = { ok: true, data: { group, key, value } };
|
||||
}
|
||||
|
||||
/** GET /api/configs/:group —— 取一个分组的所有启用配置 */
|
||||
async showGroup() {
|
||||
const { ctx } = this;
|
||||
const { group } = ctx.params;
|
||||
const data = await ctx.service.config.getGroup(group);
|
||||
ctx.body = { ok: true, data };
|
||||
}
|
||||
|
||||
/** PUT /api/configs —— 新增或更新(幂等) */
|
||||
async upsert() {
|
||||
const { ctx } = this;
|
||||
const { configKey } = ctx.request.body || {};
|
||||
if (!configKey) {
|
||||
ctx.status = 422;
|
||||
ctx.body = { ok: false, message: 'configKey 不能为空' };
|
||||
return;
|
||||
}
|
||||
|
||||
const data = await ctx.service.config.set(ctx.request.body);
|
||||
ctx.body = { ok: true, data };
|
||||
}
|
||||
|
||||
/** DELETE /api/configs/:group/:key —— 软删除 */
|
||||
async destroy() {
|
||||
const { ctx } = this;
|
||||
const { group, key } = ctx.params;
|
||||
const removed = await ctx.service.config.remove(group, key);
|
||||
if (!removed) {
|
||||
ctx.status = 404;
|
||||
ctx.body = { ok: false, message: '配置不存在' };
|
||||
return;
|
||||
}
|
||||
ctx.body = { ok: true, data: { group, key } };
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = InternalConfigController;
|
||||
99
backend/app/controller/internal/device.js
Normal file
99
backend/app/controller/internal/device.js
Normal file
@ -0,0 +1,99 @@
|
||||
'use strict';
|
||||
|
||||
const { Controller } = require('egg');
|
||||
|
||||
/** 路径参数转正整数,非法返回 null */
|
||||
function toId(value) {
|
||||
const id = Number(value);
|
||||
return Number.isInteger(id) && id > 0 ? id : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 运维/内部:设备(scanners)的绑定 / 解绑 / 列表 / 详情 / 删除
|
||||
*
|
||||
* 面向:运维脚本、后台系统 —— 可看/可管**所有人**的设备,所以挂在 `middleware.internalAuth()` 后面。
|
||||
* 前端 SPA 只能管自己的设备:`/api/web/devices*`(见 controller/web/device.js)。
|
||||
*
|
||||
* 设备侧的部分在 `app/controller/device/`(扫码登录 `auth.js`、自检保活 `self.js`、上报 `scan.js`)。
|
||||
*/
|
||||
class InternalDeviceController extends Controller {
|
||||
/**
|
||||
* POST /api/scanner/bind —— 把设备绑定到账号(**管理侧**接口,不是设备自己调的)
|
||||
* 设备自己的注册/登录全部走扫码登录:`GET /api/device/login`
|
||||
*/
|
||||
async bind() {
|
||||
const { ctx } = this;
|
||||
const body = ctx.request.body || {};
|
||||
const data = await ctx.service.scanner.bind({
|
||||
scannerId: toId(body.scannerId),
|
||||
sn: body.sn,
|
||||
userId: body.userId,
|
||||
username: body.username,
|
||||
});
|
||||
ctx.body = { ok: true, data };
|
||||
}
|
||||
|
||||
/** POST /api/scanner/unbind —— 解绑(设备保留,仅清掉归属;设备可再扫码重新认领) */
|
||||
async unbind() {
|
||||
const { ctx } = this;
|
||||
const body = ctx.request.body || {};
|
||||
const data = await ctx.service.scanner.unbind({
|
||||
scannerId: toId(body.scannerId),
|
||||
sn: body.sn,
|
||||
});
|
||||
if (!data) {
|
||||
ctx.status = 404;
|
||||
ctx.body = { ok: false, message: '扫描器不存在' };
|
||||
return;
|
||||
}
|
||||
ctx.body = { ok: true, data };
|
||||
}
|
||||
|
||||
/** GET /api/scanners?page=&pageSize=&keyword=&userId=&status= —— 设备列表 */
|
||||
async index() {
|
||||
const { ctx } = this;
|
||||
const { page, pageSize, keyword, userId, status } = ctx.query;
|
||||
const data = await ctx.service.scanner.list({ page, pageSize, keyword, userId, status });
|
||||
ctx.body = { ok: true, data };
|
||||
}
|
||||
|
||||
/** GET /api/scanners/:id —— 设备详情 */
|
||||
async show() {
|
||||
const { ctx } = this;
|
||||
const id = toId(ctx.params.id);
|
||||
if (!id) {
|
||||
ctx.status = 400;
|
||||
ctx.body = { ok: false, message: 'id 必须是正整数' };
|
||||
return;
|
||||
}
|
||||
|
||||
const data = await ctx.service.scanner.findById(id);
|
||||
if (!data) {
|
||||
ctx.status = 404;
|
||||
ctx.body = { ok: false, message: '扫描器不存在' };
|
||||
return;
|
||||
}
|
||||
ctx.body = { ok: true, data };
|
||||
}
|
||||
|
||||
/** DELETE /api/scanners/:id —— 软删除设备 */
|
||||
async destroy() {
|
||||
const { ctx } = this;
|
||||
const id = toId(ctx.params.id);
|
||||
if (!id) {
|
||||
ctx.status = 400;
|
||||
ctx.body = { ok: false, message: 'id 必须是正整数' };
|
||||
return;
|
||||
}
|
||||
|
||||
const removed = await ctx.service.scanner.remove(id);
|
||||
if (!removed) {
|
||||
ctx.status = 404;
|
||||
ctx.body = { ok: false, message: '扫描器不存在' };
|
||||
return;
|
||||
}
|
||||
ctx.body = { ok: true, data: { id } };
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = InternalDeviceController;
|
||||
108
backend/app/controller/internal/user.js
Normal file
108
backend/app/controller/internal/user.js
Normal file
@ -0,0 +1,108 @@
|
||||
'use strict';
|
||||
|
||||
const { Controller } = require('egg');
|
||||
|
||||
/** 路径参数转正整数,非法返回 null */
|
||||
function toId(value) {
|
||||
const id = Number(value);
|
||||
return Number.isInteger(id) && id > 0 ? id : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 运维/内部:用户 CRUD(能看/改**所有**账号,所以挂在 `middleware.internalAuth()` 后面)
|
||||
*
|
||||
* 面向:运维脚本、后台系统。前端 SPA 用的是 `/api/web/*`(只能动自己的东西)。
|
||||
*/
|
||||
class InternalUserController extends Controller {
|
||||
/** GET /api/users?page=1&pageSize=20&keyword=&status= */
|
||||
async index() {
|
||||
const { ctx } = this;
|
||||
const { page, pageSize, keyword, status } = ctx.query;
|
||||
const data = await ctx.service.user.list({ page, pageSize, keyword, status });
|
||||
ctx.body = { ok: true, data };
|
||||
}
|
||||
|
||||
/** GET /api/users/:id —— 走 Redis 缓存,未命中回源数据库 */
|
||||
async show() {
|
||||
const { ctx } = this;
|
||||
const id = toId(ctx.params.id);
|
||||
if (!id) {
|
||||
ctx.status = 400;
|
||||
ctx.body = { ok: false, message: 'id 必须是正整数' };
|
||||
return;
|
||||
}
|
||||
|
||||
const user = await ctx.service.cache.remember(
|
||||
`user:${id}`,
|
||||
ctx.app.config.cache.ttl,
|
||||
() => ctx.service.user.findById(id),
|
||||
);
|
||||
|
||||
if (!user) {
|
||||
ctx.status = 404;
|
||||
ctx.body = { ok: false, message: '用户不存在' };
|
||||
return;
|
||||
}
|
||||
ctx.body = { ok: true, data: user };
|
||||
}
|
||||
|
||||
/** POST /api/users */
|
||||
async create() {
|
||||
const { ctx } = this;
|
||||
const body = ctx.request.body || {};
|
||||
if (!body.nickname) {
|
||||
ctx.status = 422;
|
||||
ctx.body = { ok: false, message: 'nickname 不能为空' };
|
||||
return;
|
||||
}
|
||||
|
||||
const user = await ctx.service.user.create(body);
|
||||
ctx.status = 201;
|
||||
ctx.body = { ok: true, data: user };
|
||||
}
|
||||
|
||||
/** PUT /api/users/:id */
|
||||
async update() {
|
||||
const { ctx } = this;
|
||||
const id = toId(ctx.params.id);
|
||||
if (!id) {
|
||||
ctx.status = 400;
|
||||
ctx.body = { ok: false, message: 'id 必须是正整数' };
|
||||
return;
|
||||
}
|
||||
|
||||
const user = await ctx.service.user.update(id, ctx.request.body || {});
|
||||
if (!user) {
|
||||
ctx.status = 404;
|
||||
ctx.body = { ok: false, message: '用户不存在' };
|
||||
return;
|
||||
}
|
||||
|
||||
// 数据变更后让缓存失效
|
||||
await ctx.service.cache.del(`user:${id}`);
|
||||
ctx.body = { ok: true, data: user };
|
||||
}
|
||||
|
||||
/** DELETE /api/users/:id —— 软删除 */
|
||||
async destroy() {
|
||||
const { ctx } = this;
|
||||
const id = toId(ctx.params.id);
|
||||
if (!id) {
|
||||
ctx.status = 400;
|
||||
ctx.body = { ok: false, message: 'id 必须是正整数' };
|
||||
return;
|
||||
}
|
||||
|
||||
const removed = await ctx.service.user.remove(id);
|
||||
if (!removed) {
|
||||
ctx.status = 404;
|
||||
ctx.body = { ok: false, message: '用户不存在' };
|
||||
return;
|
||||
}
|
||||
|
||||
await ctx.service.cache.del(`user:${id}`);
|
||||
ctx.body = { ok: true, data: { id } };
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = InternalUserController;
|
||||
95
backend/app/controller/internal/wechat.js
Normal file
95
backend/app/controller/internal/wechat.js
Normal file
@ -0,0 +1,95 @@
|
||||
'use strict';
|
||||
|
||||
const { Controller } = require('egg');
|
||||
|
||||
/**
|
||||
* 运维/内部:微信授权(绑定关系)的读写
|
||||
*
|
||||
* 挂在 `middleware.internalAuth()` 后面(见 app/middleware/internal_auth.js)。
|
||||
*
|
||||
* 用户侧的扫码确认在 `app/controller/client/wechat.js`,公开的发码/查码在 `app/controller/auth/wechat.js`。
|
||||
*/
|
||||
class InternalWechatController extends Controller {
|
||||
/** GET /api/users/:id/wechats —— 某用户的全部微信授权 */
|
||||
async indexByUser() {
|
||||
const { ctx } = this;
|
||||
const userId = Number(ctx.params.id);
|
||||
if (!Number.isInteger(userId) || userId <= 0) {
|
||||
ctx.status = 400;
|
||||
ctx.body = { ok: false, message: 'id 必须是正整数' };
|
||||
return;
|
||||
}
|
||||
|
||||
const list = await ctx.service.wechat.listByUser(userId);
|
||||
ctx.body = { ok: true, data: { list, total: list.length } };
|
||||
}
|
||||
|
||||
/** GET /api/wechat/:appid/:openid —— 按 appid + openid 反查授权与用户 */
|
||||
async show() {
|
||||
const { ctx } = this;
|
||||
const { appid, openid } = ctx.params;
|
||||
const data = await ctx.service.wechat.findByOpenid(appid, openid);
|
||||
if (!data) {
|
||||
ctx.status = 404;
|
||||
ctx.body = { ok: false, message: '授权记录不存在' };
|
||||
return;
|
||||
}
|
||||
ctx.body = { ok: true, data };
|
||||
}
|
||||
|
||||
/** POST /api/wechat/bind —— 绑定(已存在则更新) */
|
||||
async bind() {
|
||||
const { ctx } = this;
|
||||
const { userId, appid, openid } = ctx.request.body || {};
|
||||
|
||||
if (!userId || !appid || !openid) {
|
||||
ctx.status = 422;
|
||||
ctx.body = { ok: false, message: 'userId、appid、openid 均为必填' };
|
||||
return;
|
||||
}
|
||||
|
||||
const data = await ctx.service.wechat.bind(ctx.request.body);
|
||||
ctx.status = 201;
|
||||
ctx.body = { ok: true, data };
|
||||
}
|
||||
|
||||
/** PUT /api/wechat/:id/tokens —— 更新 session_key / 令牌 */
|
||||
async updateTokens() {
|
||||
const { ctx } = this;
|
||||
const id = Number(ctx.params.id);
|
||||
if (!Number.isInteger(id) || id <= 0) {
|
||||
ctx.status = 400;
|
||||
ctx.body = { ok: false, message: 'id 必须是正整数' };
|
||||
return;
|
||||
}
|
||||
|
||||
const data = await ctx.service.wechat.updateTokens(id, ctx.request.body || {});
|
||||
if (!data) {
|
||||
ctx.status = 404;
|
||||
ctx.body = { ok: false, message: '授权记录不存在' };
|
||||
return;
|
||||
}
|
||||
ctx.body = { ok: true, data };
|
||||
}
|
||||
|
||||
/** DELETE /api/wechat/:id —— 解绑 */
|
||||
async unbind() {
|
||||
const { ctx } = this;
|
||||
const id = Number(ctx.params.id);
|
||||
if (!Number.isInteger(id) || id <= 0) {
|
||||
ctx.status = 400;
|
||||
ctx.body = { ok: false, message: 'id 必须是正整数' };
|
||||
return;
|
||||
}
|
||||
|
||||
const removed = await ctx.service.wechat.unbind(id);
|
||||
if (!removed) {
|
||||
ctx.status = 404;
|
||||
ctx.body = { ok: false, message: '授权记录不存在' };
|
||||
return;
|
||||
}
|
||||
ctx.body = { ok: true, data: { id } };
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = InternalWechatController;
|
||||
187
backend/app/controller/web/auth.js
Normal file
187
backend/app/controller/web/auth.js
Normal file
@ -0,0 +1,187 @@
|
||||
'use strict';
|
||||
|
||||
const { Controller } = require('egg');
|
||||
|
||||
/** 邮箱格式(与页面版保持一致,宽松校验) */
|
||||
const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/;
|
||||
|
||||
/**
|
||||
* web 用户端:登录 / 注册 / 找回密码 / 重置密码(**JSON 接口**,给前端 SPA 调)
|
||||
*
|
||||
* 鉴权走 **header 令牌**(`Authorization: Bearer <user JWT>`),不依赖 cookie/session:
|
||||
* 前端与后端不同源也没问题,也天然不受 CSRF 影响(`/api/*` 不过 CSRF)。
|
||||
*
|
||||
* 统一响应:成功 `{ ok:true, data }`;失败 `{ ok:false, status?, message }`。
|
||||
*/
|
||||
class WebAuthController extends Controller {
|
||||
/** 签发令牌 + 返回脱敏用户(登录 / 注册成功后都走它) */
|
||||
issue(user) {
|
||||
const { ctx } = this;
|
||||
return {
|
||||
token: ctx.service.jwt.signUser(user),
|
||||
tokenType: 'Bearer',
|
||||
expiresIn: ctx.app.config.jwt.userExpiresIn,
|
||||
user,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /api/web/auth/login
|
||||
* body: `{ account, password }`(account 支持 用户名 / 手机号 / 邮箱)
|
||||
* → `{ token, tokenType, expiresIn, user }`
|
||||
*/
|
||||
async login() {
|
||||
const { ctx } = this;
|
||||
const { account, password } = ctx.request.body || {};
|
||||
if (!account || !password) {
|
||||
ctx.status = 422;
|
||||
ctx.body = { ok: false, message: '请填写账号和密码' };
|
||||
return;
|
||||
}
|
||||
|
||||
const user = await ctx.service.auth.login(String(account).trim(), password);
|
||||
if (!user) {
|
||||
ctx.status = 401;
|
||||
ctx.body = { ok: false, status: 'unauthorized', message: '账号或密码错误' };
|
||||
return;
|
||||
}
|
||||
|
||||
ctx.logger.info('[web] %s 登录成功(API)', user.username || account);
|
||||
ctx.body = { ok: true, data: this.issue(user) };
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /api/web/auth/register/code
|
||||
* body: `{ email }` → 发 6 位邮箱验证码(开发模式直接返回 `code`)
|
||||
*/
|
||||
async sendRegisterCode() {
|
||||
const { ctx } = this;
|
||||
const email = String((ctx.request.body || {}).email || '').trim().toLowerCase();
|
||||
|
||||
if (!ctx.app.config.register.enable) {
|
||||
ctx.throw(403, '注册已关闭,请联系管理员开通账号');
|
||||
}
|
||||
if (!EMAIL_RE.test(email)) {
|
||||
ctx.throw(422, '请填写正确的邮箱');
|
||||
}
|
||||
|
||||
const exists = await ctx.service.user.findOneBy({ email });
|
||||
if (exists) ctx.throw(409, '该邮箱已被使用');
|
||||
|
||||
const result = await ctx.service.verifyCode.send('register', email);
|
||||
if (!result.ok) ctx.throw(429, result.message);
|
||||
|
||||
ctx.logger.info('[web] 注册验证码已发送到 %s', email);
|
||||
ctx.body = {
|
||||
ok: true,
|
||||
data: {
|
||||
email,
|
||||
// 开发模式(未配 SMTP)把验证码带回来,前端可直接提示;生产不返回
|
||||
devMode: Boolean(result.devMode),
|
||||
code: result.devMode ? result.code : undefined,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /api/web/auth/register
|
||||
* body: `{ username, email, code, password, nickname?, phone? }` → 建成即登录(返回令牌)
|
||||
*/
|
||||
async register() {
|
||||
const { ctx } = this;
|
||||
const body = ctx.request.body || {};
|
||||
const username = String(body.username || '').trim();
|
||||
const email = String(body.email || '').trim().toLowerCase();
|
||||
const code = String(body.code || '').trim();
|
||||
const password = String(body.password || '');
|
||||
const nickname = String(body.nickname || '').trim();
|
||||
const phone = String(body.phone || '').trim();
|
||||
|
||||
if (!ctx.app.config.register.enable) ctx.throw(403, '注册已关闭,请联系管理员开通账号');
|
||||
if (!/^[A-Za-z0-9_]{3,32}$/.test(username)) ctx.throw(422, '用户名需 3-32 位字母、数字或下划线');
|
||||
if (!EMAIL_RE.test(email)) ctx.throw(422, '邮箱格式不正确');
|
||||
if (!/^\d{6}$/.test(code)) ctx.throw(422, '请填写 6 位邮箱验证码');
|
||||
if (password.length < 6) ctx.throw(422, '密码至少 6 位');
|
||||
if (phone && !/^[0-9+\-]{6,20}$/.test(phone)) ctx.throw(422, '手机号格式不正确');
|
||||
|
||||
const checked = await ctx.service.verifyCode.check('register', email, code);
|
||||
if (!checked.ok) ctx.throw(422, checked.message);
|
||||
|
||||
try {
|
||||
const user = await ctx.service.auth.register({ username, password, nickname, email, phone: phone || null });
|
||||
// 注册成功才消费验证码(用户名/邮箱冲突时可改完重提,不用重新收码)
|
||||
await ctx.service.verifyCode.consume('register', email);
|
||||
ctx.logger.info('[web] %s 注册成功(API,id=%s)', username, user.id);
|
||||
ctx.body = { ok: true, data: this.issue(user) };
|
||||
} catch (err) {
|
||||
// 唯一键冲突(409):翻成页面能直接显示的文案
|
||||
if (err.status === 409) {
|
||||
const message = String(err.message || '');
|
||||
ctx.status = 409;
|
||||
ctx.body = {
|
||||
ok: false,
|
||||
message: message.startsWith('username') ? '该用户名已被使用'
|
||||
: message.startsWith('email') ? '该邮箱已被使用'
|
||||
: message.startsWith('phone') ? '该手机号已被注册'
|
||||
: '注册失败,请稍后重试',
|
||||
};
|
||||
return;
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /api/web/auth/forgot
|
||||
* body: `{ email }` → 发重置链接(**防账号枚举**:邮箱没注册也返回成功)
|
||||
*/
|
||||
async forgot() {
|
||||
const { ctx } = this;
|
||||
const email = String((ctx.request.body || {}).email || '').trim().toLowerCase();
|
||||
if (!EMAIL_RE.test(email)) ctx.throw(422, '请填写正确的邮箱');
|
||||
|
||||
const user = await ctx.service.user.findOneBy({ email });
|
||||
if (user && Number(user.status) === 1) {
|
||||
const origin = ctx.app.config.email.siteUrl || ctx.origin;
|
||||
const result = await ctx.service.passwordReset.send(user, origin);
|
||||
if (!result.ok) ctx.throw(500, result.message);
|
||||
|
||||
ctx.logger.info('[web] 已向 %s 发送重置密码链接', email);
|
||||
ctx.body = {
|
||||
ok: true,
|
||||
data: {
|
||||
sent: true,
|
||||
// 开发模式(未配 SMTP)把链接返回,前端可直接点开
|
||||
devMode: Boolean(result.devMode),
|
||||
url: result.devMode ? result.url : undefined,
|
||||
},
|
||||
};
|
||||
return;
|
||||
}
|
||||
|
||||
if (user) ctx.logger.warn('[web] 账号已禁用,不发送重置链接: %s', email);
|
||||
ctx.body = { ok: true, data: { sent: true } };
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /api/web/auth/reset
|
||||
* body: `{ token, password }` → 用邮件里的令牌设新密码(令牌一次性)
|
||||
*/
|
||||
async reset() {
|
||||
const { ctx } = this;
|
||||
const body = ctx.request.body || {};
|
||||
const token = String(body.token || '');
|
||||
const password = String(body.password || '');
|
||||
|
||||
const userId = await ctx.service.passwordReset.verify(token);
|
||||
if (!userId) ctx.throw(410, '重置链接无效或已过期,请重新获取');
|
||||
if (password.length < 6) ctx.throw(422, '密码至少 6 位');
|
||||
|
||||
await ctx.service.auth.setPassword(userId, password);
|
||||
await ctx.service.passwordReset.consume(token, userId);
|
||||
ctx.logger.info('[web] 用户 %s 通过邮件链接重置了密码(API)', userId);
|
||||
ctx.body = { ok: true, data: { id: userId } };
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = WebAuthController;
|
||||
82
backend/app/controller/web/device.js
Normal file
82
backend/app/controller/web/device.js
Normal file
@ -0,0 +1,82 @@
|
||||
'use strict';
|
||||
|
||||
const { Controller } = require('egg');
|
||||
|
||||
/** 路径参数转正整数,非法返回 null */
|
||||
function toId(value) {
|
||||
const id = Number(value);
|
||||
return Number.isInteger(id) && id > 0 ? id : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* web 用户端:**我自己的设备**(`/api/web/devices`)
|
||||
*
|
||||
* 鉴权:`middleware.apiAuth()`(header 里的 user JWT),用户 ID 一律取自令牌。
|
||||
* 与 `controller/internal/device.js` 的区别:那边是运维视角(可看/可管**所有人**的设备),
|
||||
* 这边只能看/动自己的 —— 不属于自己的设备直接 404(不暴露别人有哪些设备)。
|
||||
*/
|
||||
class WebDeviceController extends Controller {
|
||||
/** 取「我的设备」;不是自己的(或不存在)一律 404 */
|
||||
async own(rawId) {
|
||||
const { ctx } = this;
|
||||
const id = toId(rawId);
|
||||
if (!id) ctx.throw(400, 'id 必须是正整数');
|
||||
|
||||
const data = await ctx.service.scanner.findById(id);
|
||||
if (!data || Number(data.userId) !== Number(ctx.state.user.id)) {
|
||||
ctx.throw(404, '设备不存在或不属于当前账号');
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
/** GET /api/web/devices?page=&pageSize=&keyword=&status= —— 我的设备列表 */
|
||||
async index() {
|
||||
const { ctx } = this;
|
||||
const { page, pageSize, keyword, status } = ctx.query;
|
||||
const data = await ctx.service.scanner.list({
|
||||
page,
|
||||
pageSize,
|
||||
keyword,
|
||||
status,
|
||||
// ⚠️ 强制按当前用户过滤,忽略前端传的 userId
|
||||
userId: ctx.state.user.id,
|
||||
});
|
||||
ctx.body = { ok: true, data };
|
||||
}
|
||||
|
||||
/** GET /api/web/devices/:id —— 设备详情 */
|
||||
async show() {
|
||||
const { ctx } = this;
|
||||
ctx.body = { ok: true, data: await this.own(ctx.params.id) };
|
||||
}
|
||||
|
||||
/** GET /api/web/devices/:id/channels —— 该设备(中控)下已登记的通道 */
|
||||
async channels() {
|
||||
const { ctx } = this;
|
||||
const device = await this.own(ctx.params.id);
|
||||
const list = await ctx.service.scan.findChannelsByScanner(device.id);
|
||||
ctx.body = { ok: true, data: { deviceId: device.id, list } };
|
||||
}
|
||||
|
||||
/** POST /api/web/devices/:id/unbind —— 解绑(记录保留,设备可再扫码认领) */
|
||||
async unbind() {
|
||||
const { ctx } = this;
|
||||
const device = await this.own(ctx.params.id);
|
||||
const data = await ctx.service.scanner.unbind({ scannerId: device.id });
|
||||
|
||||
ctx.logger.info('[web] 用户 %s 解绑了设备 %s', ctx.state.user.id, device.sn);
|
||||
ctx.body = { ok: true, data };
|
||||
}
|
||||
|
||||
/** DELETE /api/web/devices/:id —— 删除(软删除)自己的设备 */
|
||||
async destroy() {
|
||||
const { ctx } = this;
|
||||
const device = await this.own(ctx.params.id);
|
||||
await ctx.service.scanner.remove(device.id);
|
||||
|
||||
ctx.logger.info('[web] 用户 %s 删除了设备 %s', ctx.state.user.id, device.sn);
|
||||
ctx.body = { ok: true, data: { id: device.id } };
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = WebDeviceController;
|
||||
65
backend/app/controller/web/profile.js
Normal file
65
backend/app/controller/web/profile.js
Normal file
@ -0,0 +1,65 @@
|
||||
'use strict';
|
||||
|
||||
const { Controller } = require('egg');
|
||||
|
||||
/** 只允许这几个字段由用户自己改(用户名、状态这类不给改) */
|
||||
const EDITABLE = [ 'nickname', 'avatar', 'phone', 'gender', 'email' ];
|
||||
|
||||
/**
|
||||
* web 用户端:当前用户自己的资料(`/api/web/me`)
|
||||
*
|
||||
* 鉴权:`middleware.apiAuth()` —— header 里的 user JWT;**用户 ID 一律取自令牌**,
|
||||
* 不接受前端传 id(不然就成越权改别人资料了)。
|
||||
*/
|
||||
class WebProfileController extends Controller {
|
||||
/** GET /api/web/me —— 当前登录用户 */
|
||||
async show() {
|
||||
const { ctx } = this;
|
||||
ctx.body = { ok: true, data: ctx.state.user };
|
||||
}
|
||||
|
||||
/**
|
||||
* PUT /api/web/me —— 改自己的资料
|
||||
* body: `{ nickname?, avatar?, phone?, gender?, email? }`
|
||||
*/
|
||||
async update() {
|
||||
const { ctx } = this;
|
||||
const body = ctx.request.body || {};
|
||||
const fields = {};
|
||||
for (const key of EDITABLE) {
|
||||
if (body[key] !== undefined) fields[key] = body[key];
|
||||
}
|
||||
if (!Object.keys(fields).length) ctx.throw(422, '没有可更新的字段');
|
||||
if (fields.email !== undefined) {
|
||||
fields.email = String(fields.email || '').trim().toLowerCase() || null;
|
||||
}
|
||||
if (fields.nickname !== undefined && !String(fields.nickname).trim()) {
|
||||
ctx.throw(422, '昵称不能为空');
|
||||
}
|
||||
|
||||
const user = await ctx.service.user.update(ctx.state.user.id, fields);
|
||||
// 用户详情接口用的是同一份缓存,顺手失效
|
||||
await ctx.service.cache.del(`user:${ctx.state.user.id}`);
|
||||
ctx.logger.info('[web] 用户 %s 更新了资料', ctx.state.user.id);
|
||||
ctx.body = { ok: true, data: user };
|
||||
}
|
||||
|
||||
/**
|
||||
* PUT /api/web/me/password —— 修改密码
|
||||
* body: `{ oldPassword, newPassword }`
|
||||
*/
|
||||
async changePassword() {
|
||||
const { ctx } = this;
|
||||
const { oldPassword, newPassword } = ctx.request.body || {};
|
||||
if (!oldPassword || !newPassword) ctx.throw(422, '请填写原密码与新密码');
|
||||
if (String(newPassword).length < 6) ctx.throw(422, '新密码至少 6 位');
|
||||
|
||||
const changed = await ctx.service.auth.changePassword(ctx.state.user.id, oldPassword, newPassword);
|
||||
if (!changed) ctx.throw(422, '原密码不正确');
|
||||
|
||||
ctx.logger.info('[web] 用户 %s 修改了密码', ctx.state.user.id);
|
||||
ctx.body = { ok: true, data: { id: ctx.state.user.id } };
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = WebProfileController;
|
||||
48
backend/app/controller/web/record.js
Normal file
48
backend/app/controller/web/record.js
Normal file
@ -0,0 +1,48 @@
|
||||
'use strict';
|
||||
|
||||
const { Controller } = require('egg');
|
||||
|
||||
/**
|
||||
* web 用户端:**我自己设备的扫码记录**(`/api/web/records`)
|
||||
*
|
||||
* 鉴权:`middleware.apiAuth()`;范围限定为「当前用户名下的设备」——
|
||||
* 先取我的设备 id 列表,再拿它去过滤记录(`service.scan.listRecords({ scannerIds })`)。
|
||||
*/
|
||||
class WebRecordController extends Controller {
|
||||
/**
|
||||
* GET /api/web/records
|
||||
* query: `?page=&pageSize=&deviceId=&channelId=&barcode=&startTime=&endTime=`
|
||||
* - `deviceId` 只能填自己名下的设备(否则 404);不填 = 所有设备
|
||||
* - `startTime` / `endTime` 支持 `2026-10-16 12:00:00`、10/13 位时间戳
|
||||
*/
|
||||
async index() {
|
||||
const { ctx } = this;
|
||||
const { page, pageSize, deviceId, channelId, barcode, startTime, endTime } = ctx.query;
|
||||
|
||||
const ids = await ctx.service.scanner.idsOfUser(ctx.state.user.id);
|
||||
let scannerIds = ids;
|
||||
if (deviceId) {
|
||||
const id = Number(deviceId);
|
||||
if (!ids.includes(id)) ctx.throw(404, '设备不存在或不属于当前账号');
|
||||
scannerIds = [ id ];
|
||||
}
|
||||
|
||||
const data = await ctx.service.scan.listRecords({
|
||||
page, pageSize, scannerIds, channelId, barcode, startTime, endTime,
|
||||
});
|
||||
|
||||
ctx.body = {
|
||||
ok: true,
|
||||
data: Object.assign({}, data, {
|
||||
// 拍平所属设备(前端表格直接显示),免得前端再查一次
|
||||
list: data.list.map(row => Object.assign({}, row, {
|
||||
deviceSn: row.scanner ? row.scanner.sn : null,
|
||||
deviceName: row.scanner ? row.scanner.name : null,
|
||||
scanner: undefined,
|
||||
})),
|
||||
}),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = WebRecordController;
|
||||
44
backend/app/controller/web/stats.js
Normal file
44
backend/app/controller/web/stats.js
Normal file
@ -0,0 +1,44 @@
|
||||
'use strict';
|
||||
|
||||
const { Controller } = require('egg');
|
||||
|
||||
/**
|
||||
* web 用户端:首页统计(`/api/web/stats`)
|
||||
*
|
||||
* 只统计**当前用户名下**的数据(设备数 / 通道数 / 扫码记录数 + 最近一条扫码记录),
|
||||
* 与运维视角的统计(`service.user.count()` 那种全站数字)区分开。
|
||||
*/
|
||||
class WebStatsController extends Controller {
|
||||
/** GET /api/web/stats */
|
||||
async index() {
|
||||
const { ctx } = this;
|
||||
const userId = ctx.state.user.id;
|
||||
const ids = await ctx.service.scanner.idsOfUser(userId);
|
||||
|
||||
const [ deviceCount, channelCount, recordCount, latest ] = await Promise.all([
|
||||
ctx.service.scanner.count({ userId }),
|
||||
ctx.service.scan.countChannels({ scannerIds: ids }),
|
||||
ctx.service.scan.countRecords({ scannerIds: ids }),
|
||||
ctx.service.scan.listRecords({ scannerIds: ids, page: 1, pageSize: 1 }),
|
||||
]);
|
||||
|
||||
const row = latest.list[0] || null;
|
||||
ctx.body = {
|
||||
ok: true,
|
||||
data: {
|
||||
deviceCount,
|
||||
channelCount,
|
||||
recordCount,
|
||||
latestRecord: row ? {
|
||||
id: row.id,
|
||||
barcode: row.barcode,
|
||||
channelId: row.channelId,
|
||||
deviceSn: row.scanner ? row.scanner.sn : null,
|
||||
scanTime: row.scanTime,
|
||||
} : null,
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = WebStatsController;
|
||||
111
backend/app/controller/web/test.js
Normal file
111
backend/app/controller/web/test.js
Normal file
@ -0,0 +1,111 @@
|
||||
'use strict';
|
||||
|
||||
const { Controller } = require('egg');
|
||||
|
||||
/**
|
||||
* web 用户端:**测试页**用的模拟接口(`/api/web/test/*`)
|
||||
*
|
||||
* 前端「测试页」把真机链路拆开跑,方便没有实物设备时联调:
|
||||
* - `POST /api/web/test/device-login`:模拟「设备发码 → 有人扫码确认」这一步。
|
||||
* 请求方(已登录用户)就是**确认人**,等价于手机上点了确认 —— 会真的建/认领设备记录并**换发长期 JWT**。
|
||||
* - `POST /api/web/test/scan`:模拟「中控上报」(拿 SN + 长期 JWT 调,等价于设备的 `/api/scan/*`)。
|
||||
*
|
||||
* 两者都不绕开校验:设备令牌仍按 `service.scanner.resolveByToken()` 完整验签 + 比对 jti。
|
||||
*/
|
||||
class WebTestController extends Controller {
|
||||
/**
|
||||
* POST /api/web/test/device-login
|
||||
* body: `{ sn?, name?, vendor?, model?, firmware?, expiresIn? }`
|
||||
* → `{ ...设备信息, token, tokenType, firstTime }`
|
||||
*/
|
||||
async deviceLogin() {
|
||||
const { ctx } = this;
|
||||
const body = ctx.request.body || {};
|
||||
const expiresIn = this.resolveDuration(body.expiresIn);
|
||||
|
||||
const created = await ctx.service.scanner.loginByScan({
|
||||
sn: body.sn,
|
||||
name: body.name,
|
||||
vendor: body.vendor,
|
||||
model: body.model,
|
||||
firmware: body.firmware,
|
||||
ip: ctx.ip,
|
||||
userId: ctx.state.user.id,
|
||||
expiresIn,
|
||||
});
|
||||
|
||||
// 再查一次,拿到带绑定用户信息的完整数据
|
||||
const detail = await ctx.service.scanner.findById(created.id);
|
||||
ctx.logger.info('[web-test] 模拟设备扫码登录: %s(确认人 %s)', created.sn, ctx.state.user.id);
|
||||
|
||||
ctx.body = {
|
||||
ok: true,
|
||||
data: Object.assign({}, detail, {
|
||||
token: created.token,
|
||||
tokenType: created.tokenType,
|
||||
firstTime: created.firstTime,
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 令牌时长(可选):只能申请比 `config.jwt.deviceExpiresIn` 更短的,超上限 422
|
||||
* @return {number|undefined} 秒数;没传返回 undefined(用默认值)
|
||||
*/
|
||||
resolveDuration(raw) {
|
||||
const { ctx } = this;
|
||||
const value = String(raw || '').trim();
|
||||
if (!value) return undefined;
|
||||
|
||||
const { jwt } = ctx.app.config;
|
||||
const maxSpec = String(jwt.deviceExpiresIn || jwt.scannerExpiresIn || '365d');
|
||||
const max = ctx.service.jwt.parseDuration(maxSpec);
|
||||
const seconds = ctx.service.jwt.parseDuration(value);
|
||||
|
||||
if (!seconds) ctx.throw(422, 'expiresIn 格式不对(支持 30d / 12h / 90m / 3600 这类写法)');
|
||||
if (max && seconds > max) ctx.throw(422, `expiresIn 不能超过服务端上限 ${maxSpec}`);
|
||||
return seconds;
|
||||
}
|
||||
|
||||
/**
|
||||
* POST /api/web/test/scan
|
||||
* body: `{ sn, token, channelId, channelName?, barcode, scanTime? }`
|
||||
* → `{ inserted, duplicated, ... }`(与设备上报同结构)
|
||||
*/
|
||||
async scan() {
|
||||
const { ctx } = this;
|
||||
const body = ctx.request.body || {};
|
||||
const sn = String(body.sn || '').trim();
|
||||
const token = String(body.token || '').trim();
|
||||
const channelId = String(body.channelId || '').trim();
|
||||
const channelName = String(body.channelName || '').trim();
|
||||
const barcode = String(body.barcode || '').trim();
|
||||
const scanTime = String(body.scanTime || '').trim();
|
||||
|
||||
if (!sn || !token) ctx.throw(422, '设备 SN 与长期 JWT 都不能为空');
|
||||
if (!channelId) ctx.throw(422, '通道 id 不能为空');
|
||||
if (!barcode) ctx.throw(422, '条码不能为空');
|
||||
|
||||
// 与设备上报走**同一套**校验(验签 + 回查 + jti 比对)
|
||||
const scanner = await ctx.service.scanner.resolveByToken(token, { sn });
|
||||
await ctx.service.scanner.heartbeat(scanner, ctx.ip);
|
||||
|
||||
const channelResult = await ctx.service.scan.reportChannels(scanner, [{ channelId, channelName }]);
|
||||
const scanResult = await ctx.service.scan.ingest(scanner, [{
|
||||
channelId,
|
||||
barcode,
|
||||
scanTime: scanTime || new Date(),
|
||||
}]);
|
||||
|
||||
ctx.logger.info('[web-test] 模拟上报完成: %s 通道=%s 条码=%s', sn, channelId, barcode);
|
||||
ctx.body = {
|
||||
ok: true,
|
||||
data: Object.assign({ sn, channelId, channelName, barcode }, scanResult, {
|
||||
channelCreated: channelResult.created,
|
||||
channelUpdated: channelResult.updated,
|
||||
}),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = WebTestController;
|
||||
56
backend/app/middleware/api_auth.js
Normal file
56
backend/app/middleware/api_auth.js
Normal file
@ -0,0 +1,56 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 接口鉴权(**只认 header 里的令牌,不看 cookie/session**)
|
||||
*
|
||||
* 用法:`router.post('/api/xxx', middleware.apiAuth(), controller.xxx.yyy)`
|
||||
*
|
||||
* - 令牌:`Authorization: Bearer <user JWT>`(也认 `X-Access-Token`,方便不爱用 Authorization 的客户端)
|
||||
* JWT 由这些地方下发:扫码登录 `GET /api/wechat/login` 的 `data.token`、页面里现场签发的同款令牌;
|
||||
* - 不加 cookie、也不写 session:小程序 / App / SPA 这类没有浏览器 cookie 的客户端直接用它;
|
||||
* - 未带或验不过 → 401 `{ ok:false, status:'unauthorized', message }`;
|
||||
* 用户不存在/被禁用 → 403 `{ ok:false, status:'forbidden', message }`;
|
||||
* - 通过后把用户放进 `ctx.locals.user` 与 `ctx.state.user`。
|
||||
*/
|
||||
module.exports = () => {
|
||||
return async function apiAuth(ctx, next) {
|
||||
const token = bearerToken(ctx);
|
||||
|
||||
const payload = token && ctx.service.jwt.verifyUser(token);
|
||||
const userId = payload && payload.sub ? Number(payload.sub) : 0;
|
||||
if (!userId) {
|
||||
ctx.status = 401;
|
||||
ctx.body = {
|
||||
ok: false,
|
||||
status: 'unauthorized',
|
||||
message: '缺少或无效的令牌(请在 header 里带 Authorization: Bearer <token>)',
|
||||
};
|
||||
return;
|
||||
}
|
||||
|
||||
const user = await ctx.service.user.findById(userId);
|
||||
if (!user) {
|
||||
ctx.status = 401;
|
||||
ctx.body = { ok: false, status: 'unauthorized', message: '令牌对应的用户不存在' };
|
||||
return;
|
||||
}
|
||||
if (Number(user.status) !== 1) {
|
||||
ctx.status = 403;
|
||||
ctx.body = { ok: false, status: 'forbidden', message: '账号已被禁用' };
|
||||
return;
|
||||
}
|
||||
|
||||
// 注意:**不碰 session/cookie**,接口鉴权完全基于这一次请求的 header
|
||||
ctx.locals = ctx.locals || {};
|
||||
ctx.locals.user = user;
|
||||
ctx.state.user = user;
|
||||
await next();
|
||||
};
|
||||
};
|
||||
|
||||
/** 取 header 里的令牌:优先 Authorization: Bearer,其次 X-Access-Token */
|
||||
function bearerToken(ctx) {
|
||||
const matched = /^Bearer\s+(.+)$/i.exec(ctx.get('authorization') || '');
|
||||
if (matched) return matched[1].trim();
|
||||
return String(ctx.get('x-access-token') || '').trim();
|
||||
}
|
||||
52
backend/app/middleware/error_handler.js
Normal file
52
backend/app/middleware/error_handler.js
Normal file
@ -0,0 +1,52 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 统一错误处理(后端不再渲染页面 → 只会返回 JSON 或纯文本)
|
||||
*
|
||||
* - 接口请求(`/api/*`、`/health` 或声明了 Accept: application/json)→ `{ ok:false, message }`
|
||||
* - 其它请求(正常都被 app/middleware/frontend.js 接走了)→ 一行纯文本
|
||||
*
|
||||
* 4xx 返回原始消息,5xx 只对外返回「服务器内部错误」并记入 common-error.log。
|
||||
*/
|
||||
module.exports = () => {
|
||||
return async function errorHandler(ctx, next) {
|
||||
try {
|
||||
await next();
|
||||
|
||||
// 没匹配到任何路由的接口请求:框架/koa 默认回 HTML 404(客户端按 JSON 解析会报
|
||||
// `Unexpected token '<'`),这里统一成 JSON —— 控制器自己给的 404(对象 body)不动
|
||||
// ⚠️ 给 ctx.body 赋值会把「默认的 404」顶成 200,所以必须显式把状态码钉回 404
|
||||
const isApiPath = ctx.path.startsWith('/api/') || ctx.path === '/health';
|
||||
if (ctx.status === 404 && isApiPath && !(ctx.body && typeof ctx.body === 'object')) {
|
||||
ctx.body = { ok: false, message: '接口不存在' };
|
||||
ctx.status = 404;
|
||||
}
|
||||
} catch (err) {
|
||||
const status = err.status >= 400 && err.status < 600 ? err.status : 500;
|
||||
|
||||
if (status >= 500) {
|
||||
// 交给框架的 onerror 记录日志(common-error.log)
|
||||
ctx.app.emit('error', err, ctx);
|
||||
} else {
|
||||
ctx.logger.warn('[http] %s %s -> %s %s', ctx.method, ctx.url, status, err.message);
|
||||
}
|
||||
|
||||
// 响应已经开始发送(例如已反代出去 / 流式输出)时不能再改 body
|
||||
if (ctx.headerSent) return;
|
||||
|
||||
const message = status >= 500 ? '服务器内部错误' : err.message;
|
||||
// 接口请求返回 JSON,其它(理论上都被 frontend 中间件接走了)返回纯文本
|
||||
const isApi = ctx.path.startsWith('/api/') || ctx.path === '/health' || ctx.acceptJSON;
|
||||
|
||||
ctx.status = status;
|
||||
|
||||
if (isApi) {
|
||||
ctx.body = { ok: false, message };
|
||||
return;
|
||||
}
|
||||
|
||||
ctx.type = 'text/plain; charset=utf-8';
|
||||
ctx.body = `${status} ${message}`;
|
||||
}
|
||||
};
|
||||
};
|
||||
108
backend/app/middleware/frontend.js
Normal file
108
backend/app/middleware/frontend.js
Normal file
@ -0,0 +1,108 @@
|
||||
'use strict';
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const httpProxy = require('http-proxy');
|
||||
const serve = require('koa-static');
|
||||
|
||||
/**
|
||||
* 前端入口:**后端不再渲染任何页面**,`/` 这一侧要么反代给前端 dev server、要么托管前端构建产物
|
||||
*
|
||||
* - **开发(`env=local`)**:把非 `/api`、`/health` 的请求反向代理到前端 dev server
|
||||
* (`config.frontend.devServer`,默认 `http://127.0.0.1:7301`,即 `frontend && npm run dev`)。
|
||||
* 这样联调只开一个地址(后端 `:7001`),前端的热更新也照常生效(含 HMR 的 WebSocket 升级)。
|
||||
* - **生产**:托管 `config.frontend.distDir`(默认 `../frontend/dist`)里的静态资源,
|
||||
* 找不到文件且浏览器要 HTML 时回退到 `index.html`(SPA 深链刷新不会 404)。
|
||||
* - **单测(`env=unittest`)**:整体跳过(不连前端、也不要求 dist 存在),
|
||||
* 于是未匹配的路径还是走框架/路由自己的 404。
|
||||
*
|
||||
* 只接管 GET/HEAD 的「非接口」请求:`/api/*`、`/health` 一律交给后面的路由。
|
||||
*/
|
||||
module.exports = (options, app) => {
|
||||
const cfg = app.config.frontend || {};
|
||||
const env = app.config.env;
|
||||
const isDev = env === 'local';
|
||||
const enabled = Boolean(cfg.enable) && env !== 'unittest';
|
||||
|
||||
const distDir = cfg.distDir;
|
||||
const indexFile = path.join(distDir, 'index.html');
|
||||
|
||||
// 静态中间件(生产用):只管真实文件,交给 koa-static 处理缓存/条件请求
|
||||
const staticMw = enabled && !isDev ? serve(distDir, { index: false, defer: false }) : null;
|
||||
|
||||
if (enabled && isDev) {
|
||||
app.logger.info('[frontend] dev 反代已启用: %s(页面请求转发给前端 dev server)', cfg.devServer);
|
||||
|
||||
// 前端 dev server 的 HMR 走 WebSocket:HTTP server 的 upgrade 事件也得转过去,
|
||||
// 否则页面能打开、但改代码不会热更新(升级请求没人管会直接断开)
|
||||
app.once('server', server => {
|
||||
server.on('upgrade', (req, socket, head) => {
|
||||
const url = String(req.url || '');
|
||||
if (url.startsWith('/api/') || url === '/health') return; // 接口侧不接管
|
||||
getProxy(cfg.devServer).ws(req, socket, head, { target: cfg.devServer });
|
||||
});
|
||||
});
|
||||
} else if (enabled && staticMw) {
|
||||
app.logger.info('[frontend] 静态托管已启用: %s(存在 index.html = %s)', distDir, fs.existsSync(indexFile));
|
||||
}
|
||||
|
||||
return async function frontend(ctx, next) {
|
||||
if (!enabled || !isFrontendRequest(ctx)) return next();
|
||||
|
||||
if (isDev) return proxyToDevServer(ctx, cfg.devServer);
|
||||
|
||||
// 生产:先当静态资源找,找不到再回退 index.html(SPA 路由)
|
||||
await staticMw(ctx, async () => {});
|
||||
if (ctx.status !== 404) return;
|
||||
|
||||
if (!fs.existsSync(indexFile)) {
|
||||
ctx.status = 503;
|
||||
ctx.type = 'html';
|
||||
ctx.body = '<h1>前端还没构建</h1><p>请在 frontend/ 执行 <code>npm run build</code>(或用 FRONTEND_DIST 指定目录)。</p>';
|
||||
return;
|
||||
}
|
||||
|
||||
ctx.type = 'html';
|
||||
ctx.body = fs.createReadStream(indexFile);
|
||||
};
|
||||
};
|
||||
|
||||
/** 只接管「页面」请求:非接口 + GET/HEAD */
|
||||
function isFrontendRequest(ctx) {
|
||||
if (ctx.method !== 'GET' && ctx.method !== 'HEAD') return false;
|
||||
return !ctx.path.startsWith('/api/') && ctx.path !== '/api' && ctx.path !== '/health';
|
||||
}
|
||||
|
||||
/** 开发:反代到前端 dev server(含 HMR 的 WebSocket 升级) */
|
||||
function proxyToDevServer(ctx, target) {
|
||||
// koa 不再自己写响应,完全交给反代
|
||||
ctx.respond = false;
|
||||
|
||||
const proxy = getProxy(target);
|
||||
proxy.web(ctx.req, ctx.res, { target }, (err) => {
|
||||
if (ctx.res.headersSent) return;
|
||||
ctx.status = 502;
|
||||
ctx.type = 'html';
|
||||
ctx.body = `<h1>前端 dev server 连不上</h1><p>${err.message}</p>`
|
||||
+ `<p>请先启动前端:<code>cd frontend; npm run dev</code>(目标 ${target})</p>`;
|
||||
});
|
||||
}
|
||||
|
||||
/** 按 target 缓存代理实例(同一个 target 复用连接池) */
|
||||
const proxies = new Map();
|
||||
function getProxy(target) {
|
||||
if (proxies.has(target)) return proxies.get(target);
|
||||
|
||||
// ws: true —— 允许 `proxy.ws()` 把 HMR 的升级请求转过去
|
||||
const proxy = httpProxy.createProxyServer({ changeOrigin: true, xfwd: true, ws: true });
|
||||
proxy.on('error', (err, req, res) => {
|
||||
// HTTP 请求的错误在 proxyToDevServer 的回调里处理;这里只兑底(避免 unhandled error 抛到进程)
|
||||
if (res && !res.headersSent && res.writeHead) {
|
||||
res.writeHead(502, { 'Content-Type': 'text/plain; charset=utf-8' });
|
||||
}
|
||||
void err;
|
||||
});
|
||||
|
||||
proxies.set(target, proxy);
|
||||
return proxy;
|
||||
}
|
||||
74
backend/app/middleware/internal_auth.js
Normal file
74
backend/app/middleware/internal_auth.js
Normal file
@ -0,0 +1,74 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 运维/内部接口鉴权(`/api/users*`、`/api/wechat/bind`、`/api/configs*`、`/api/scanners*` 这些)
|
||||
*
|
||||
* 用法:`router.get('/api/users', middleware.internalAuth(), controller.internal.user.index)`
|
||||
*
|
||||
* 两种通过方式(满足其一即可):
|
||||
* 1. **运维脚本 / 后台系统**:header 带 `X-Internal-Token: <config.internal.token>`
|
||||
* (环境变量 `INTERNAL_TOKEN`;**没配就一律不认**,避免线上忘记配还能进);
|
||||
* 2. **管理员账号**:header 带 `Authorization: Bearer <user JWT>`,且 userId 在
|
||||
* `config.internal.adminIds`(环境变量 `INTERNAL_ADMIN_IDS`,逗号分隔,默认 `1`)里。
|
||||
*
|
||||
* 通过后 `ctx.state.internal = { via, user? }`;不通过:401(没令牌/令牌无效)或 403(不是管理员、账号被禁用)。
|
||||
*
|
||||
* ⚠️ 这是**内部接口**(能看/改所有人的数据)。前端 SPA 用的是 `/api/web/*`(只能动自己的东西),
|
||||
* 不要把它暴露给普通用户。
|
||||
*/
|
||||
module.exports = () => {
|
||||
return async function internalAuth(ctx, next) {
|
||||
const cfg = ctx.app.config.internal || {};
|
||||
|
||||
// ① 静态运维令牌(给脚本/后台系统用)
|
||||
const internalToken = String(ctx.get('x-internal-token') || '').trim();
|
||||
if (cfg.token && internalToken && internalToken === cfg.token) {
|
||||
ctx.state.internal = { via: 'token' };
|
||||
return next();
|
||||
}
|
||||
|
||||
// ② 管理员账号的 user JWT
|
||||
const bearer = bearerToken(ctx);
|
||||
const payload = bearer && ctx.service.jwt.verifyUser(bearer);
|
||||
const userId = payload && payload.sub ? Number(payload.sub) : 0;
|
||||
|
||||
if (!userId) {
|
||||
ctx.status = 401;
|
||||
ctx.body = {
|
||||
ok: false,
|
||||
status: 'unauthorized',
|
||||
message: '内部接口需要管理员令牌(Authorization: Bearer <user JWT> 或 X-Internal-Token)',
|
||||
};
|
||||
return;
|
||||
}
|
||||
if (!(cfg.adminIds || []).includes(userId)) {
|
||||
ctx.status = 403;
|
||||
ctx.body = { ok: false, status: 'forbidden', message: '当前账号没有内部管理权限' };
|
||||
return;
|
||||
}
|
||||
|
||||
const user = await ctx.service.user.findById(userId);
|
||||
if (!user) {
|
||||
ctx.status = 401;
|
||||
ctx.body = { ok: false, status: 'unauthorized', message: '令牌对应的用户不存在' };
|
||||
return;
|
||||
}
|
||||
if (Number(user.status) !== 1) {
|
||||
ctx.status = 403;
|
||||
ctx.body = { ok: false, status: 'forbidden', message: '账号已被禁用' };
|
||||
return;
|
||||
}
|
||||
|
||||
ctx.state.internal = { via: 'user', user };
|
||||
ctx.locals = ctx.locals || {};
|
||||
ctx.locals.user = user;
|
||||
await next();
|
||||
};
|
||||
};
|
||||
|
||||
/** 取 header 里的用户令牌:优先 Authorization: Bearer,其次 X-Access-Token */
|
||||
function bearerToken(ctx) {
|
||||
const matched = /^Bearer\s+(.+)$/i.exec(ctx.get('authorization') || '');
|
||||
if (matched) return matched[1].trim();
|
||||
return String(ctx.get('x-access-token') || '').trim();
|
||||
}
|
||||
32
backend/app/middleware/scanner_auth.js
Normal file
32
backend/app/middleware/scanner_auth.js
Normal file
@ -0,0 +1,32 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 扫描器身份校验(长期 JWT)
|
||||
*
|
||||
* 令牌来源(按优先级):`Authorization: Bearer <jwt>` → `X-Scanner-Token` → `?access_token=`。
|
||||
*
|
||||
* 校验链路(实现在 `service/scanner.js#resolveByToken`,测试页模拟上报也用同一个方法):
|
||||
* 1. 验签 + 过期检查(app/service/jwt.js);
|
||||
* 2. 回查数据库确认扫描器存在且未被禁用(status=1);
|
||||
* 3. 比对库里保存的 jti 与令牌里的 jti —— 重新注册/登录会换 jti,旧令牌立即失效。
|
||||
*
|
||||
* 通过后:`ctx.state.scanner` 与 `ctx.locals.scanner` 都指向该扫描器。
|
||||
*/
|
||||
module.exports = () => {
|
||||
return async function scannerAuth(ctx, next) {
|
||||
const scanner = await ctx.service.scanner.resolveByToken(extractToken(ctx));
|
||||
|
||||
ctx.state.scanner = scanner;
|
||||
ctx.locals = ctx.locals || {};
|
||||
ctx.locals.scanner = scanner;
|
||||
await next();
|
||||
};
|
||||
};
|
||||
|
||||
function extractToken(ctx) {
|
||||
const header = ctx.get('authorization');
|
||||
if (header && /^Bearer\s+/i.test(header)) {
|
||||
return header.replace(/^Bearer\s+/i, '').trim();
|
||||
}
|
||||
return ctx.get('x-scanner-token') || ctx.query.access_token || null;
|
||||
}
|
||||
34
backend/app/model/scan_channel.js
Normal file
34
backend/app/model/scan_channel.js
Normal file
@ -0,0 +1,34 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 扫描中控通道表模型(scan_channels)
|
||||
*
|
||||
* 一台「中控(绑定端)」可以接多个扫码设备,每个扫码设备对应一个通道;
|
||||
* 中控通过 POST /api/scan/channels 把通道(channel_id + channel_name)上报到服务,
|
||||
* 一个通道一行,唯一键 (scanner_id, channel_id):中控再次上报同名通道就是更新。
|
||||
*
|
||||
* 注意:channel_id 只在同一中控内唯一,所以关联时要用 (scanner_id, channel_id) 两个字段。
|
||||
*/
|
||||
module.exports = (app) => {
|
||||
const { BIGINT, STRING, TINYINT, DATE } = app.Sequelize;
|
||||
|
||||
const ScanChannel = app.model.define('scanChannel', {
|
||||
id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' },
|
||||
scannerId: { type: BIGINT.UNSIGNED, allowNull: false, comment: '上报的中控(= scanners.id)' },
|
||||
channelId: { type: STRING(64), allowNull: false, comment: '通道 id(中控上报,同一中控内唯一)' },
|
||||
channelName: { type: STRING(128), allowNull: false, defaultValue: '', comment: '通道名(中控上报)' },
|
||||
lastReportAt: { type: DATE, comment: '最近一次上报时间' },
|
||||
status: { type: TINYINT.UNSIGNED, allowNull: false, defaultValue: 1, comment: '状态:1正常 0停用' },
|
||||
remark: { type: STRING(255), comment: '备注' },
|
||||
}, {
|
||||
tableName: 'scan_channels',
|
||||
paranoid: true,
|
||||
comment: '扫描中控通道表',
|
||||
});
|
||||
|
||||
ScanChannel.associate = function() {
|
||||
app.model.ScanChannel.belongsTo(app.model.Scanner, { foreignKey: 'scanner_id', as: 'scanner' });
|
||||
};
|
||||
|
||||
return ScanChannel;
|
||||
};
|
||||
34
backend/app/model/scan_record.js
Normal file
34
backend/app/model/scan_record.js
Normal file
@ -0,0 +1,34 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 扫码记录表模型(scan_records)
|
||||
*
|
||||
* 中控通过 POST /api/scan/records 上报扫码流水:条码 + 扫描时间 + 通道 id。
|
||||
* 去重靠唯一键 (scanner_id, channel_id, barcode, scan_time):完全相同的上报只入库一次。
|
||||
*
|
||||
* 本表是流水表,**不用软删除**(paranoid 关闭):
|
||||
* 软删除会让记录占用唯一键,导致同一条扫码数据再也无法入库;
|
||||
* 需要清理请按时间物理删除。
|
||||
*/
|
||||
module.exports = (app) => {
|
||||
const { BIGINT, STRING, DATE } = app.Sequelize;
|
||||
|
||||
const ScanRecord = app.model.define('scanRecord', {
|
||||
id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' },
|
||||
scannerId: { type: BIGINT.UNSIGNED, allowNull: false, comment: '上报的中控(= scanners.id)' },
|
||||
channelId: { type: STRING(64), allowNull: false, comment: '通道 id' },
|
||||
barcode: { type: STRING(255), allowNull: false, comment: '条码内容' },
|
||||
scanTime: { type: DATE, allowNull: false, comment: '扫描时间(中控上报,秒级)' },
|
||||
reportedAt: { type: DATE, allowNull: false, defaultValue: app.Sequelize.NOW, comment: '服务端接收时间' },
|
||||
}, {
|
||||
tableName: 'scan_records',
|
||||
paranoid: false,
|
||||
comment: '扫码记录表(去重)',
|
||||
});
|
||||
|
||||
ScanRecord.associate = function() {
|
||||
app.model.ScanRecord.belongsTo(app.model.Scanner, { foreignKey: 'scanner_id', as: 'scanner' });
|
||||
};
|
||||
|
||||
return ScanRecord;
|
||||
};
|
||||
42
backend/app/model/scanner.js
Normal file
42
backend/app/model/scanner.js
Normal file
@ -0,0 +1,42 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 扫描器(设备)表模型(scanners)
|
||||
*
|
||||
* 设备身份只有一种:`GET /api/device/login` 扫码登录换来的长期 JWT
|
||||
* (建记录/绑定都发生在「手机确认登录」那一刻),库里只存当前令牌的 `jti`(重签即失效)。
|
||||
* `user_id` 为空表示尚未绑定账号。
|
||||
*/
|
||||
module.exports = (app) => {
|
||||
const { BIGINT, STRING, TINYINT, DATE } = app.Sequelize;
|
||||
|
||||
const Scanner = app.model.define('scanner', {
|
||||
id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' },
|
||||
userId: { type: BIGINT.UNSIGNED, comment: '绑定的用户 id' },
|
||||
sn: { type: STRING(64), allowNull: false, comment: '扫描器 SN(唯一标识)' },
|
||||
name: { type: STRING(64), allowNull: false, defaultValue: '', comment: '名称 / 别名' },
|
||||
vendor: { type: STRING(64), comment: '厂商' },
|
||||
model: { type: STRING(64), comment: '型号' },
|
||||
firmware: { type: STRING(32), comment: '固件 / 客户端版本' },
|
||||
ip: { type: STRING(45), comment: '最近登录 IP' },
|
||||
// ⚠️ 历史字段:早期「sn + secret 注册/登录」用的密钥哈希,现在已不再写入/校验(列保留)
|
||||
secretHash: { type: STRING(100), comment: '历史字段:扫描器密钥哈希(已废弃)' },
|
||||
// 库里不存 JWT 本体,只存当前令牌的 jti:重签令牌会让旧令牌立即失效
|
||||
tokenJti: { type: STRING(64), comment: '当前 JWT 的 jti' },
|
||||
tokenExpiresAt: { type: DATE, comment: '令牌过期时间' },
|
||||
status: { type: TINYINT.UNSIGNED, allowNull: false, defaultValue: 1, comment: '状态:1正常 0禁用' },
|
||||
lastRegisterAt: { type: DATE, comment: '最近注册时间' },
|
||||
lastLoginAt: { type: DATE, comment: '最近登录时间' },
|
||||
lastSeenAt: { type: DATE, comment: '最近心跳时间' },
|
||||
}, {
|
||||
tableName: 'scanners',
|
||||
paranoid: true,
|
||||
comment: '扫描器表',
|
||||
});
|
||||
|
||||
Scanner.associate = function() {
|
||||
app.model.Scanner.belongsTo(app.model.User, { foreignKey: 'user_id', as: 'user' });
|
||||
};
|
||||
|
||||
return Scanner;
|
||||
};
|
||||
30
backend/app/model/sys_config.js
Normal file
30
backend/app/model/sys_config.js
Normal file
@ -0,0 +1,30 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 系统配置表模型(sys_config)
|
||||
*
|
||||
* 通用 key-value 配置:group_name + config_key 唯一定位一条配置,
|
||||
* value_type 决定 config_value 的解析方式(string / number / boolean / json)。
|
||||
*
|
||||
* 注意:唯一性由 service 层保证(先查后写),不建唯一索引 ——
|
||||
* 因为本表用 deleted_at 软删除,唯一索引会被已删除的记录占用,导致同 key 无法重建。
|
||||
*/
|
||||
module.exports = (app) => {
|
||||
const { BIGINT, STRING, TEXT, TINYINT } = app.Sequelize;
|
||||
|
||||
const SysConfig = app.model.define('sysConfig', {
|
||||
id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' },
|
||||
groupName: { type: STRING(64), allowNull: false, defaultValue: 'default', comment: '分组' },
|
||||
configKey: { type: STRING(128), allowNull: false, comment: '配置键' },
|
||||
configValue: { type: TEXT, comment: '配置值' },
|
||||
valueType: { type: STRING(16), allowNull: false, defaultValue: 'string', comment: 'string/number/boolean/json' },
|
||||
remark: { type: STRING(255), comment: '备注' },
|
||||
status: { type: TINYINT.UNSIGNED, allowNull: false, defaultValue: 1, comment: '状态:1启用 0禁用' },
|
||||
}, {
|
||||
tableName: 'sys_config',
|
||||
paranoid: true,
|
||||
comment: '系统配置表',
|
||||
});
|
||||
|
||||
return SysConfig;
|
||||
};
|
||||
38
backend/app/model/user.js
Normal file
38
backend/app/model/user.js
Normal file
@ -0,0 +1,38 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 用户表模型(users)
|
||||
*
|
||||
* 通用约定在 config/config.default.js 的 sequelize.define 里配置:
|
||||
* freezeTableName / underscored / created_at / updated_at,
|
||||
* 这里通过 paranoid: true 开启软删除(对应 deleted_at 字段)。
|
||||
*/
|
||||
module.exports = (app) => {
|
||||
const { BIGINT, STRING, TINYINT, DATE } = app.Sequelize;
|
||||
|
||||
const User = app.model.define('user', {
|
||||
id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' },
|
||||
username: { type: STRING(64), comment: '登录名' },
|
||||
nickname: { type: STRING(64), allowNull: false, defaultValue: '', comment: '昵称' },
|
||||
email: { type: STRING(128), comment: '邮箱(可选,可作登录账号)' },
|
||||
avatar: { type: STRING(255), allowNull: false, defaultValue: '', comment: '头像地址' },
|
||||
phone: { type: STRING(20), comment: '手机号' },
|
||||
// 密码哈希(bcrypt),接口与模板都不外泄:查询时会显式 exclude
|
||||
passwordHash: { type: STRING(100), comment: '密码哈希(bcrypt)' },
|
||||
gender: { type: TINYINT.UNSIGNED, allowNull: false, defaultValue: 0, comment: '性别:0未知 1男 2女' },
|
||||
status: { type: TINYINT.UNSIGNED, allowNull: false, defaultValue: 1, comment: '状态:1正常 0禁用' },
|
||||
remark: { type: STRING(255), comment: '备注' },
|
||||
lastLoginAt: { type: DATE, comment: '最近登录时间' },
|
||||
}, {
|
||||
tableName: 'users',
|
||||
paranoid: true,
|
||||
comment: '用户表',
|
||||
});
|
||||
|
||||
User.associate = function() {
|
||||
app.model.User.hasMany(app.model.WechatOauth, { foreignKey: 'user_id', as: 'wechats' });
|
||||
app.model.User.hasMany(app.model.Scanner, { foreignKey: 'user_id', as: 'scanners' });
|
||||
};
|
||||
|
||||
return User;
|
||||
};
|
||||
40
backend/app/model/wechat_oauth.js
Normal file
40
backend/app/model/wechat_oauth.js
Normal file
@ -0,0 +1,40 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 微信授权表模型(wechat_oauth)
|
||||
*
|
||||
* 一条记录 = 某个用户在某个 appid 下的一次微信授权,
|
||||
* 因此一个用户可绑定多个微信(公众号 / 小程序 / 开放平台)。
|
||||
* 关联:WechatOauth.belongsTo(User, { as: 'user' }),
|
||||
* 可通过 { include: [{ model: app.model.User, as: 'user' }] } 取出对应用户。
|
||||
*/
|
||||
module.exports = (app) => {
|
||||
const { BIGINT, STRING, DATE } = app.Sequelize;
|
||||
|
||||
const WechatOauth = app.model.define('wechatOauth', {
|
||||
id: { type: BIGINT.UNSIGNED, primaryKey: true, autoIncrement: true, comment: '主键' },
|
||||
// 下划线映射由 config.sequelize.define.underscored 统一处理(userId -> user_id)
|
||||
userId: { type: BIGINT.UNSIGNED, allowNull: false, comment: '关联 users.id' },
|
||||
appid: { type: STRING(64), allowNull: false, comment: '微信 appid' },
|
||||
openid: { type: STRING(64), allowNull: false, comment: '用户在该 appid 下的 openid' },
|
||||
unionid: { type: STRING(64), comment: '开放平台 unionid' },
|
||||
nickname: { type: STRING(64), allowNull: false, defaultValue: '', comment: '授权时微信昵称' },
|
||||
avatar: { type: STRING(255), allowNull: false, defaultValue: '', comment: '授权时微信头像' },
|
||||
sessionKey: { type: STRING(128), comment: '小程序 session_key' },
|
||||
accessToken: { type: STRING(512), comment: '网页授权 access_token' },
|
||||
refreshToken: { type: STRING(512), comment: '刷新令牌' },
|
||||
scope: { type: STRING(64), comment: '授权 scope' },
|
||||
tokenExpiresAt: { type: DATE, comment: 'access_token 过期时间' },
|
||||
lastAuthAt: { type: DATE, comment: '最近授权时间' },
|
||||
}, {
|
||||
tableName: 'wechat_oauth',
|
||||
paranoid: true,
|
||||
comment: '微信授权表',
|
||||
});
|
||||
|
||||
WechatOauth.associate = function() {
|
||||
app.model.WechatOauth.belongsTo(app.model.User, { foreignKey: 'user_id', as: 'user' });
|
||||
};
|
||||
|
||||
return WechatOauth;
|
||||
};
|
||||
105
backend/app/router.js
Normal file
105
backend/app/router.js
Normal file
@ -0,0 +1,105 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 路由定义
|
||||
* @param {Egg.Application} app - egg application
|
||||
*/
|
||||
module.exports = (app) => {
|
||||
const { router, controller, middleware } = app;
|
||||
const apiAuth = middleware.apiAuth();
|
||||
const internalAuth = middleware.internalAuth();
|
||||
const scannerAuth = middleware.scannerAuth();
|
||||
|
||||
// ==================== JSON 接口 ====================
|
||||
// 控制器按「谁在调」分模块(app/controller/<模块>/):
|
||||
// web/ 前端 SPA(用户端,toC:用户自己管自己的设备/记录)—— header 令牌(user JWT)
|
||||
// device/ 设备(长期 JWT,typ=scanner)
|
||||
// auth/ 公开的登录码接口(发码/查码/确认)
|
||||
// internal/ 运维/内部(用户与配置的 CRUD)—— 需内部令牌
|
||||
// home / health 放在根(公共)
|
||||
//
|
||||
// ⚠️ 后端**不再渲染任何页面**:`/` 这一侧由 app/middleware/frontend.js 处理
|
||||
// (开发时反代到前端 dev server,生产时托管 frontend/dist)。
|
||||
router.get('/api/info', controller.home.index);
|
||||
router.get('/health', controller.health.index);
|
||||
|
||||
// ---------- web 用户端(前端 SPA 调;登录/注册等公开,其余要令牌) ----------
|
||||
router.post('/api/web/auth/login', controller.web.auth.login);
|
||||
router.post('/api/web/auth/register/code', controller.web.auth.sendRegisterCode);
|
||||
router.post('/api/web/auth/register', controller.web.auth.register);
|
||||
router.post('/api/web/auth/forgot', controller.web.auth.forgot);
|
||||
router.post('/api/web/auth/reset', controller.web.auth.reset);
|
||||
|
||||
router.get('/api/web/me', apiAuth, controller.web.profile.show);
|
||||
router.put('/api/web/me', apiAuth, controller.web.profile.update);
|
||||
router.put('/api/web/me/password', apiAuth, controller.web.profile.changePassword);
|
||||
|
||||
// 首页统计(只统计当前用户名下的数据)
|
||||
router.get('/api/web/stats', apiAuth, controller.web.stats.index);
|
||||
|
||||
// 我的设备:列表 / 详情 / 通道 / 解绑 / 删除(越权访问一律 404)
|
||||
router.get('/api/web/devices', apiAuth, controller.web.device.index);
|
||||
router.get('/api/web/devices/:id', apiAuth, controller.web.device.show);
|
||||
router.get('/api/web/devices/:id/channels', apiAuth, controller.web.device.channels);
|
||||
router.post('/api/web/devices/:id/unbind', apiAuth, controller.web.device.unbind);
|
||||
router.delete('/api/web/devices/:id', apiAuth, controller.web.device.destroy);
|
||||
|
||||
// 我的扫码记录(范围限定在当前用户名下的设备)
|
||||
router.get('/api/web/records', apiAuth, controller.web.record.index);
|
||||
|
||||
// 前端「测试页」的模拟接口(模拟设备扫码登录 / 模拟中控上报),与真机走同一套 service
|
||||
router.post('/api/web/test/device-login', apiAuth, controller.web.test.deviceLogin);
|
||||
router.post('/api/web/test/scan', apiAuth, controller.web.test.scan);
|
||||
|
||||
// ---------- 运维/内部(脚本、后台系统;**需内部令牌**,见 middleware/internal_auth.js)----------
|
||||
router.get('/api/users', internalAuth, controller.internal.user.index);
|
||||
router.get('/api/users/:id', internalAuth, controller.internal.user.show);
|
||||
router.post('/api/users', internalAuth, controller.internal.user.create);
|
||||
router.put('/api/users/:id', internalAuth, controller.internal.user.update);
|
||||
router.delete('/api/users/:id', internalAuth, controller.internal.user.destroy);
|
||||
|
||||
// 微信授权(绑定关系)
|
||||
router.get('/api/users/:id/wechats', internalAuth, controller.internal.wechat.indexByUser);
|
||||
router.get('/api/wechat/:appid/:openid', internalAuth, controller.internal.wechat.show);
|
||||
router.post('/api/wechat/bind', internalAuth, controller.internal.wechat.bind);
|
||||
router.put('/api/wechat/:id/tokens', internalAuth, controller.internal.wechat.updateTokens);
|
||||
router.delete('/api/wechat/:id', internalAuth, controller.internal.wechat.unbind);
|
||||
|
||||
// 系统配置(读接口带 Redis 缓存,写接口自动失效)
|
||||
router.get('/api/configs', internalAuth, controller.internal.config.index);
|
||||
router.put('/api/configs', internalAuth, controller.internal.config.upsert);
|
||||
router.get('/api/configs/:group', internalAuth, controller.internal.config.showGroup);
|
||||
router.get('/api/configs/:group/:key', internalAuth, controller.internal.config.show);
|
||||
router.delete('/api/configs/:group/:key', internalAuth, controller.internal.config.destroy);
|
||||
|
||||
// 设备管理(运维视角:可看/可管所有人的设备):绑定 / 解绑 / 列表 / 删除
|
||||
router.post('/api/scanner/bind', internalAuth, controller.internal.device.bind);
|
||||
router.post('/api/scanner/unbind', internalAuth, controller.internal.device.unbind);
|
||||
router.get('/api/scanners', internalAuth, controller.internal.device.index);
|
||||
router.get('/api/scanners/:id', internalAuth, controller.internal.device.show);
|
||||
router.delete('/api/scanners/:id', internalAuth, controller.internal.device.destroy);
|
||||
|
||||
// ---------- 公开的登录接口(auth)----------
|
||||
// 登录码二维码(SVG,本地生成;前端登录页直接 img 引用)
|
||||
router.get('/api/wechat/qrcode.svg', controller.auth.wechat.qrcode);
|
||||
// 扫码登录(前端/客户端接口):不带参数发串码,带 ?code=&wait= 长轮询并拿用户 JWT
|
||||
router.get('/api/wechat/login', controller.auth.wechat.login);
|
||||
// 查登录码状态(无需登录)
|
||||
router.get('/api/wechat/status', controller.auth.wechat.status);
|
||||
// 微信公众号网页授权回调(微信把手机浏览器重定向到这里,处理完再转回前端 /wechat 页)
|
||||
router.get('/api/wechat/callback', controller.auth.wechat.callback);
|
||||
// 设备发码 + 长轮询:**这一步才注册/绑定**并直接拿到长期 JWT(发码不需要任何凭据)
|
||||
router.get('/api/device/login', controller.device.auth.login);
|
||||
|
||||
// ---------- 用户态(client):小程序 / Win 客户端 / SPA ----------
|
||||
// 用登录码触发登录(**不认 cookie**:header 带 Authorization: Bearer <user JWT> 就行)
|
||||
router.post('/api/wechat/confirm', apiAuth, controller.client.wechat.confirm);
|
||||
|
||||
// ---------- 设备态(device):需长期 JWT ----------
|
||||
router.get('/api/scanner/me', scannerAuth, controller.device.self.me);
|
||||
router.post('/api/scanner/heartbeat', scannerAuth, controller.device.self.heartbeat);
|
||||
router.post('/api/scan/channels', scannerAuth, controller.device.scan.reportChannels);
|
||||
router.get('/api/scan/channels', scannerAuth, controller.device.scan.channels);
|
||||
router.post('/api/scan/records', scannerAuth, controller.device.scan.reportRecords);
|
||||
router.get('/api/scan/records', scannerAuth, controller.device.scan.records);
|
||||
};
|
||||
90
backend/app/service/auth.js
Normal file
90
backend/app/service/auth.js
Normal file
@ -0,0 +1,90 @@
|
||||
'use strict';
|
||||
|
||||
const { Service } = require('egg');
|
||||
const bcrypt = require('bcryptjs');
|
||||
|
||||
/** bcrypt 成本因子,改这里等于改全站强度(与 scripts/set-password.js 保持一致) */
|
||||
const BCRYPT_ROUNDS = 10;
|
||||
|
||||
/** 账号不存在时也做一次比较,避免通过响应时间探测账号是否存在 */
|
||||
const DUMMY_HASH = bcrypt.hashSync('pack-service-dummy-password', BCRYPT_ROUNDS);
|
||||
|
||||
class AuthService extends Service {
|
||||
/** 生成密码哈希(存库用) */
|
||||
async hashPassword(plain) {
|
||||
return bcrypt.hash(String(plain), BCRYPT_ROUNDS);
|
||||
}
|
||||
|
||||
/**
|
||||
* 账号密码登录:account 支持用户名或手机号
|
||||
* @param {string} account 用户名 / 手机号
|
||||
* @param {string} password 明文密码
|
||||
* @return {Promise<object|null>} 成功返回脱敏用户信息,失败返回 null
|
||||
*/
|
||||
async login(account, password) {
|
||||
if (!account || !password) return null;
|
||||
|
||||
const user = await this.ctx.service.user.findByAccount(account);
|
||||
const hash = user && user.passwordHash ? user.passwordHash : DUMMY_HASH;
|
||||
const matched = await bcrypt.compare(String(password), hash);
|
||||
|
||||
if (!user || !matched) {
|
||||
this.ctx.logger.warn('[auth] 登录失败: %s', account);
|
||||
return null;
|
||||
}
|
||||
if (Number(user.status) !== 1) {
|
||||
this.ctx.logger.warn('[auth] 账号已被禁用: %s', account);
|
||||
return null;
|
||||
}
|
||||
|
||||
await user.update({ lastLoginAt: new Date() });
|
||||
return this.ctx.service.user.toSafeUser(user);
|
||||
}
|
||||
|
||||
/**
|
||||
* 自助注册:建用户 + 写入密码哈希
|
||||
* 用户名/手机号唯一性由 user service 的 assertUnique 保证(冲突抛 409)
|
||||
* @return {Promise<object>} 脱敏用户信息(不含密码哈希)
|
||||
*/
|
||||
async register({ username, password, nickname, phone, email }) {
|
||||
const user = await this.ctx.service.user.create({
|
||||
username,
|
||||
nickname: nickname || username,
|
||||
phone: phone || null,
|
||||
email: email || null,
|
||||
});
|
||||
await this.ctx.service.user.setPassword(user.id, await this.hashPassword(password));
|
||||
this.ctx.logger.info('[auth] 新用户注册: %s (id=%s)', username, user.id);
|
||||
return user;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置/重置密码(脚本或后续的改密接口用)
|
||||
* @return {Promise<boolean>} 用户不存在返回 false
|
||||
*/
|
||||
async setPassword(userId, plain) {
|
||||
const hash = await this.hashPassword(plain);
|
||||
return this.ctx.service.user.setPassword(userId, hash);
|
||||
}
|
||||
|
||||
/**
|
||||
* 修改密码:先校验原密码,再写入新哈希
|
||||
* @return {Promise<boolean>} 原密码不对或用户不存在返回 false
|
||||
*/
|
||||
async changePassword(userId, oldPassword, newPassword) {
|
||||
const user = await this.ctx.service.user.findByIdWithPassword(userId);
|
||||
if (!user || !user.passwordHash) return false;
|
||||
|
||||
const matched = await bcrypt.compare(String(oldPassword), user.passwordHash);
|
||||
if (!matched) {
|
||||
this.ctx.logger.warn('[auth] 修改密码失败:原密码不正确, userId=%s', userId);
|
||||
return false;
|
||||
}
|
||||
|
||||
await user.update({ passwordHash: await this.hashPassword(newPassword) });
|
||||
this.ctx.logger.info('[auth] 密码已修改, userId=%s', userId);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = AuthService;
|
||||
87
backend/app/service/cache.js
Normal file
87
backend/app/service/cache.js
Normal file
@ -0,0 +1,87 @@
|
||||
'use strict';
|
||||
|
||||
const { Service } = require('egg');
|
||||
|
||||
class CacheService extends Service {
|
||||
get redis() {
|
||||
return this.app.redis;
|
||||
}
|
||||
|
||||
get prefix() {
|
||||
return this.config.cache.prefix;
|
||||
}
|
||||
|
||||
/** 统一拼 key,避免不同业务互相覆盖 */
|
||||
key(name) {
|
||||
return this.prefix ? `${this.prefix}${name}` : name;
|
||||
}
|
||||
|
||||
/**
|
||||
* Redis 不可用时降级(返回 fallback),不阻塞主流程:
|
||||
* 缓存只是旁路,读不到就回源,写不进去也只是少一次缓存
|
||||
*/
|
||||
async _call(action, fallback) {
|
||||
if (!this.app.redis) return fallback;
|
||||
try {
|
||||
return await action();
|
||||
} catch (err) {
|
||||
this.ctx.logger.warn('[cache] redis 异常,已降级: %s', err.message);
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
|
||||
/** 读取并自动 JSON 反序列化,未命中返回 null */
|
||||
async get(name) {
|
||||
const raw = await this._call(() => this.redis.get(this.key(name)), null);
|
||||
if (raw === null || raw === undefined) return null;
|
||||
try {
|
||||
return JSON.parse(raw);
|
||||
} catch (err) {
|
||||
// 不是 JSON 就按字符串返回
|
||||
return raw;
|
||||
}
|
||||
}
|
||||
|
||||
/** 写入,ttl 单位秒;ttl <= 0 表示永不过期 */
|
||||
async set(name, value, ttl = this.config.cache.ttl) {
|
||||
const raw = typeof value === 'string' ? value : JSON.stringify(value);
|
||||
const key = this.key(name);
|
||||
if (ttl > 0) return this._call(() => this.redis.setex(key, ttl, raw), 'OK');
|
||||
return this._call(() => this.redis.set(key, raw), 'OK');
|
||||
}
|
||||
|
||||
async del(name) {
|
||||
return this._call(() => this.redis.del(this.key(name)), 0);
|
||||
}
|
||||
|
||||
async ttl(name) {
|
||||
return this._call(() => this.redis.ttl(this.key(name)), -2);
|
||||
}
|
||||
|
||||
/** 计数器,可用于限流、统计等场景(Redis 不可用时抛出,不做降级) */
|
||||
async incr(name, ttl) {
|
||||
const key = this.key(name);
|
||||
const value = await this.redis.incr(key);
|
||||
if (ttl > 0 && value === 1) {
|
||||
await this.redis.expire(key, ttl);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
/**
|
||||
* 缓存旁路(cache-aside):命中直接返回,未命中回源并写入缓存
|
||||
* loader 返回 null/undefined 时不写缓存
|
||||
*/
|
||||
async remember(name, ttl, loader) {
|
||||
const cached = await this.get(name);
|
||||
if (cached !== null) return cached;
|
||||
|
||||
const value = await loader();
|
||||
if (value === null || value === undefined) return value;
|
||||
|
||||
await this.set(name, value, ttl);
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = CacheService;
|
||||
131
backend/app/service/config.js
Normal file
131
backend/app/service/config.js
Normal file
@ -0,0 +1,131 @@
|
||||
'use strict';
|
||||
|
||||
const { Service } = require('egg');
|
||||
|
||||
/** 根据 value_type 把数据库里的字符串还原成对应类型 */
|
||||
function parseValue(configValue, valueType) {
|
||||
if (configValue === null || configValue === undefined) return null;
|
||||
switch (valueType) {
|
||||
case 'number':
|
||||
return Number(configValue);
|
||||
case 'boolean':
|
||||
return configValue === 'true' || configValue === '1';
|
||||
case 'json':
|
||||
try {
|
||||
return JSON.parse(configValue);
|
||||
} catch (err) {
|
||||
this.ctx.logger.warn('[config] %s 不是合法 JSON,按字符串返回', configValue);
|
||||
return configValue;
|
||||
}
|
||||
default:
|
||||
return configValue;
|
||||
}
|
||||
}
|
||||
|
||||
/** 写入前把值统一序列化成字符串 */
|
||||
function stringifyValue(configValue, valueType) {
|
||||
if (configValue === null || configValue === undefined) return null;
|
||||
if (valueType === 'json') {
|
||||
return typeof configValue === 'string' ? configValue : JSON.stringify(configValue);
|
||||
}
|
||||
if (typeof configValue === 'object') return JSON.stringify(configValue);
|
||||
return String(configValue);
|
||||
}
|
||||
|
||||
class ConfigService extends Service {
|
||||
get SysConfig() {
|
||||
return this.app.model.SysConfig;
|
||||
}
|
||||
|
||||
/** 缓存 key:配置读多写少,走 Redis 缓存,写入/删除时清除 */
|
||||
cacheKey(groupName, configKey) {
|
||||
return `config:${groupName}:${configKey}`;
|
||||
}
|
||||
|
||||
/** 按 group + key 查询记录(不过滤 status,内部用) */
|
||||
async findOne(groupName, configKey) {
|
||||
return this.SysConfig.findOne({ where: { groupName, configKey } });
|
||||
}
|
||||
|
||||
/**
|
||||
* 读取单个配置值,带 Redis 缓存;不存在或已禁用时返回 defaultValue
|
||||
*/
|
||||
async get(groupName, configKey, defaultValue = null) {
|
||||
const row = await this.ctx.service.cache.remember(
|
||||
this.cacheKey(groupName, configKey),
|
||||
this.config.cache.ttl,
|
||||
async () => {
|
||||
const found = await this.SysConfig.findOne({ where: { groupName, configKey, status: 1 } });
|
||||
return found ? found.toJSON() : null;
|
||||
},
|
||||
);
|
||||
|
||||
if (!row) return defaultValue;
|
||||
return parseValue.call(this, row.configValue, row.valueType);
|
||||
}
|
||||
|
||||
/** 读取一个分组下所有启用的配置,返回 { key: value } */
|
||||
async getGroup(groupName) {
|
||||
const rows = await this.SysConfig.findAll({
|
||||
where: { groupName, status: 1 },
|
||||
order: [[ 'configKey', 'ASC' ]],
|
||||
});
|
||||
|
||||
const result = {};
|
||||
for (const row of rows) {
|
||||
result[row.configKey] = parseValue.call(this, row.configValue, row.valueType);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/** 列表(管理用,含禁用项) */
|
||||
async list({ groupName } = {}) {
|
||||
const where = {};
|
||||
if (groupName) where.groupName = groupName;
|
||||
|
||||
const rows = await this.SysConfig.findAll({
|
||||
where,
|
||||
order: [[ 'groupName', 'ASC' ], [ 'configKey', 'ASC' ]],
|
||||
});
|
||||
return rows.map(row => row.toJSON());
|
||||
}
|
||||
|
||||
/** 新增或更新(幂等 upsert),返回写入后的记录 */
|
||||
async set({ groupName = 'default', configKey, configValue, valueType = 'string', remark, status = 1 }) {
|
||||
if (!configKey) {
|
||||
this.ctx.throw(422, 'configKey 不能为空');
|
||||
}
|
||||
|
||||
const value = stringifyValue(configValue, valueType);
|
||||
const existing = await this.findOne(groupName, configKey);
|
||||
|
||||
let record;
|
||||
if (existing) {
|
||||
await existing.update({ configValue: value, valueType, remark, status });
|
||||
record = existing;
|
||||
} else {
|
||||
record = await this.SysConfig.create({ groupName, configKey, configValue: value, valueType, remark, status });
|
||||
}
|
||||
|
||||
await this.clearCache(groupName, configKey);
|
||||
return record.toJSON();
|
||||
}
|
||||
|
||||
/** 软删除配置,返回是否删除成功 */
|
||||
async remove(groupName, configKey) {
|
||||
const affected = await this.SysConfig.destroy({ where: { groupName, configKey } });
|
||||
await this.clearCache(groupName, configKey);
|
||||
return affected > 0;
|
||||
}
|
||||
|
||||
async clearCache(groupName, configKey) {
|
||||
await this.ctx.service.cache.del(this.cacheKey(groupName, configKey));
|
||||
}
|
||||
|
||||
/** 总数(首页统计用) */
|
||||
async count(where = {}) {
|
||||
return this.SysConfig.count({ where });
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = ConfigService;
|
||||
31
backend/app/service/health.js
Normal file
31
backend/app/service/health.js
Normal file
@ -0,0 +1,31 @@
|
||||
'use strict';
|
||||
|
||||
const { Service } = require('egg');
|
||||
|
||||
class HealthService extends Service {
|
||||
/** MySQL 连通性探测(authenticate 会真正建立一次连接) */
|
||||
async checkMysql() {
|
||||
const start = Date.now();
|
||||
try {
|
||||
await this.app.model.authenticate();
|
||||
return { ok: true, cost: Date.now() - start };
|
||||
} catch (err) {
|
||||
this.ctx.logger.warn('[health] mysql 不可用: %s', err.message);
|
||||
return { ok: false, cost: Date.now() - start, error: err.message };
|
||||
}
|
||||
}
|
||||
|
||||
/** Redis 连通性探测 */
|
||||
async checkRedis() {
|
||||
const start = Date.now();
|
||||
try {
|
||||
const pong = await this.app.redis.ping();
|
||||
return { ok: pong === 'PONG', cost: Date.now() - start };
|
||||
} catch (err) {
|
||||
this.ctx.logger.warn('[health] redis 不可用: %s', err.message);
|
||||
return { ok: false, cost: Date.now() - start, error: err.message };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = HealthService;
|
||||
135
backend/app/service/jwt.js
Normal file
135
backend/app/service/jwt.js
Normal file
@ -0,0 +1,135 @@
|
||||
'use strict';
|
||||
|
||||
const { Service } = require('egg');
|
||||
const jwt = require('jsonwebtoken');
|
||||
|
||||
/** 时长单位换算(秒):用于把 '30d' 这类写法解析成秒数,做上限校验 */
|
||||
const DURATION_UNITS = { s: 1, m: 60, h: 3600, d: 86400, w: 604800, y: 31536000 };
|
||||
|
||||
/**
|
||||
* JWT 服务:签发 / 校验令牌
|
||||
*
|
||||
* - **扫描器长期令牌**(typ=scanner,默认 1 年,见 config.jwt.scannerExpiresIn),
|
||||
* 撤销靠库里存当前 jti + 扫描器 status 比对(见 app/middleware/scanner_auth.js):
|
||||
* 重新注册/登录会换新 jti,旧令牌立即失效;status=0 或删除扫描器,令牌立即失效。
|
||||
* - **用户令牌**(typ=user,默认 7 天,见 config.jwt.userExpiresIn):给前端(SPA / 小程序 / 扫码登录)
|
||||
* 用,接口带 `Authorization: Bearer <token>` 即可,见 app/middleware/auth.js。
|
||||
*/
|
||||
class JwtService extends Service {
|
||||
get secret() {
|
||||
return this.config.jwt.secret;
|
||||
}
|
||||
|
||||
/**
|
||||
* 时长解析:`'30d'` / `'12h'` / `'90m'` / `'30s'` / `'2w'` / `'1y'` 或纯数字(秒)
|
||||
* @param {string|number} value 时长
|
||||
* @return {number} 秒数;解析不了返回 0
|
||||
*/
|
||||
parseDuration(value) {
|
||||
if (value === undefined || value === null || value === '') return 0;
|
||||
const text = String(value).trim();
|
||||
if (/^\d+$/.test(text)) return Number(text);
|
||||
|
||||
const matched = /^(\d+)\s*([smhdwy])$/.exec(text.toLowerCase());
|
||||
if (!matched) return 0;
|
||||
return Number(matched[1]) * (DURATION_UNITS[matched[2]] || 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* 签发用户令牌
|
||||
* @param {object} user 至少含 id(可带 username)
|
||||
* @return {string} JWT
|
||||
*/
|
||||
signUser(user) {
|
||||
const payload = {
|
||||
sub: String(user.id),
|
||||
username: user.username || null,
|
||||
typ: 'user',
|
||||
};
|
||||
|
||||
return jwt.sign(payload, this.secret, {
|
||||
algorithm: 'HS256',
|
||||
expiresIn: this.config.jwt.userExpiresIn,
|
||||
issuer: this.config.jwt.issuer,
|
||||
audience: this.config.jwt.audience,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验用户令牌,失败返回 null(不抛错,调用方自己决定怎么响应)
|
||||
* @return {object|null} payload(含 sub / typ / exp)
|
||||
*/
|
||||
verifyUser(token) {
|
||||
try {
|
||||
const payload = jwt.verify(token, this.secret, {
|
||||
algorithms: [ 'HS256' ],
|
||||
issuer: this.config.jwt.issuer,
|
||||
audience: this.config.jwt.audience,
|
||||
});
|
||||
return payload && payload.typ === 'user' ? payload : null;
|
||||
} catch (err) {
|
||||
this.ctx.logger.warn('[jwt] 用户令牌校验失败(%s): %s', err.name, err.message);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 签发扫描器长期令牌
|
||||
* @param {object} scanner 至少含 id、sn
|
||||
* @param {object} extra 额外声明(如 jti)
|
||||
* @param {object} options { expiresIn 覆盖有效期(秒数或 '30d' 这种写法,不传用 config.jwt.scannerExpiresIn) }
|
||||
* @return {string} JWT
|
||||
*/
|
||||
signScanner(scanner, extra = {}, options = {}) {
|
||||
const payload = Object.assign({
|
||||
sub: String(scanner.id),
|
||||
sn: scanner.sn,
|
||||
typ: 'scanner',
|
||||
}, extra);
|
||||
|
||||
return jwt.sign(payload, this.secret, {
|
||||
algorithm: 'HS256',
|
||||
expiresIn: options.expiresIn || this.config.jwt.scannerExpiresIn,
|
||||
issuer: this.config.jwt.issuer,
|
||||
audience: this.config.jwt.audience,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验扫描器令牌,失败直接抛 401
|
||||
*
|
||||
* ⚠️ 必须检查 `typ`:用户令牌与设备令牌用的是同一把密钥、同一对 issuer/audience,
|
||||
* 不比对 `typ` 的话**用户令牌就能当设备令牌用**(用户 id 与设备 id 撞上号就出事)。
|
||||
* @return {object} payload(含 sub / sn / jti / exp)
|
||||
*/
|
||||
verifyScanner(token) {
|
||||
let payload;
|
||||
try {
|
||||
payload = jwt.verify(token, this.secret, {
|
||||
algorithms: [ 'HS256' ],
|
||||
issuer: this.config.jwt.issuer,
|
||||
audience: this.config.jwt.audience,
|
||||
});
|
||||
} catch (err) {
|
||||
const message = err.name === 'TokenExpiredError'
|
||||
? '扫描器令牌已过期,请重新注册/登录'
|
||||
: '扫描器令牌无效';
|
||||
this.ctx.logger.warn('[jwt] 校验失败(%s): %s', err.name, err.message);
|
||||
this.ctx.throw(401, message);
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!payload || payload.typ !== 'scanner') {
|
||||
this.ctx.logger.warn('[jwt] 拿到的不是设备令牌: typ=%s', payload && payload.typ);
|
||||
this.ctx.throw(401, '不是设备令牌(设备接口只认 typ=scanner 的长期 JWT)');
|
||||
}
|
||||
return payload;
|
||||
}
|
||||
|
||||
/** 取令牌的过期时间(存库/展示用) */
|
||||
expiresAtOf(token) {
|
||||
const decoded = jwt.decode(token);
|
||||
return decoded && decoded.exp ? new Date(decoded.exp * 1000) : null;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = JwtService;
|
||||
89
backend/app/service/mail.js
Normal file
89
backend/app/service/mail.js
Normal file
@ -0,0 +1,89 @@
|
||||
'use strict';
|
||||
|
||||
const { Service } = require('egg');
|
||||
|
||||
/**
|
||||
* 邮件发送(注册验证码 / 重置密码链接)
|
||||
*
|
||||
* 两种模式:
|
||||
* - **开发模式**(`config.email.devMode`,即没配 SMTP_HOST 时):不发真邮件,
|
||||
* 把验证码/重置链接写进服务端日志,并在返回值里回传,让页面能提示出来(仅本地/测试用)。
|
||||
* - **SMTP 模式**:配好 SMTP_HOST / SMTP_PORT / SMTP_USER / SMTP_PASSWORD(+ SMTP_FROM)后自动启用,
|
||||
* 用 nodemailer 真发信(依赖懒加载,开发模式不需要它)。
|
||||
*/
|
||||
class MailService extends Service {
|
||||
/**
|
||||
* 发送验证码邮件
|
||||
* @param {string} email 收件邮箱
|
||||
* @param {string} code 6 位验证码
|
||||
* @param {object} options { ttl 有效期(秒) }
|
||||
* @return {Promise<{devMode:boolean, code?:string, failed?:boolean, messageId?:string}>}
|
||||
*/
|
||||
async sendVerifyCode(email, code, { ttl } = {}) {
|
||||
const cfg = this.app.config.email;
|
||||
const site = this.app.config.siteName;
|
||||
const minutes = Math.max(Math.round((ttl || cfg.codeTtl) / 60), 1);
|
||||
const text = `你的 ${site} 注册验证码是 ${code},${minutes} 分钟内有效。\n`
|
||||
+ '如果不是你本人操作,忽略本邮件即可。';
|
||||
|
||||
if (cfg.devMode) {
|
||||
this.ctx.logger.info('[mail][dev] 未配置 SMTP,验证码不发真邮件 → %s : %s', email, code);
|
||||
return { devMode: true, code };
|
||||
}
|
||||
|
||||
const res = await this.deliver({ to: email, subject: `${site} 注册验证码`, text });
|
||||
return Object.assign({ devMode: false }, res);
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送重置密码链接邮件
|
||||
* @param {string} email 收件邮箱
|
||||
* @param {string} url 重置地址(绝对地址,带 token)
|
||||
* @param {object} options { ttl 链接有效期(秒) }
|
||||
* @return {Promise<{devMode:boolean, url?:string, failed?:boolean, messageId?:string}>}
|
||||
*/
|
||||
async sendResetLink(email, url, { ttl } = {}) {
|
||||
const cfg = this.app.config.email;
|
||||
const site = this.app.config.siteName;
|
||||
const minutes = Math.max(Math.round((ttl || cfg.resetTtl) / 60), 1);
|
||||
const text = `我们收到了重置 ${site} 密码的请求,请打开下面的链接设置新密码(${minutes} 分钟内有效):\n`
|
||||
+ `${url}\n`
|
||||
+ '如果不是你本人操作,忽略本邮件即可,你的密码不会被修改。';
|
||||
|
||||
if (cfg.devMode) {
|
||||
this.ctx.logger.info('[mail][dev] 未配置 SMTP,重置链接不发真邮件 → %s : %s', email, url);
|
||||
return { devMode: true, url };
|
||||
}
|
||||
|
||||
const res = await this.deliver({ to: email, subject: `${site} 重置密码`, text });
|
||||
return Object.assign({ devMode: false }, res);
|
||||
}
|
||||
|
||||
/**
|
||||
* 真正发信(SMTP 模式)
|
||||
* @param {object} mail { to, subject, text }
|
||||
* @return {Promise<{messageId?:string, failed?:boolean, message?:string}>}
|
||||
*/
|
||||
async deliver({ to, subject, text }) {
|
||||
const cfg = this.app.config.email;
|
||||
try {
|
||||
// 懒加载:开发模式(默认)下不依赖这个包
|
||||
const nodemailer = require('nodemailer');
|
||||
const transporter = nodemailer.createTransport({
|
||||
host: cfg.smtp.host,
|
||||
port: cfg.smtp.port,
|
||||
secure: cfg.smtp.secure,
|
||||
auth: cfg.smtp.user ? { user: cfg.smtp.user, pass: cfg.smtp.password } : undefined,
|
||||
});
|
||||
|
||||
const info = await transporter.sendMail({ from: cfg.from, to, subject, text });
|
||||
this.ctx.logger.info('[mail] 邮件已发送 %s (%s)', to, info.messageId || '');
|
||||
return { messageId: info.messageId };
|
||||
} catch (err) {
|
||||
this.ctx.logger.error('[mail] 邮件发送失败 %s : %s', to, err.message);
|
||||
return { failed: true, message: err.message };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = MailService;
|
||||
126
backend/app/service/password_reset.js
Normal file
126
backend/app/service/password_reset.js
Normal file
@ -0,0 +1,126 @@
|
||||
'use strict';
|
||||
|
||||
const { Service } = require('egg');
|
||||
const crypto = require('crypto');
|
||||
|
||||
/** 重置令牌在 Redis 里的 key 段(与验证码分开,互不影响) */
|
||||
const SEGMENT = 'reset';
|
||||
|
||||
/** 令牌原文 → 摘要(Redis 里只存摘要,泄库也拿不到可用的重置链接) */
|
||||
function digest(token) {
|
||||
return crypto.createHash('sha256').update(String(token)).digest('hex');
|
||||
}
|
||||
|
||||
/**
|
||||
* 邮箱找回密码:生成 / 校验 / 消费「重置密码链接」里的令牌
|
||||
*
|
||||
* 存 Redis(都带 TTL,过期自动失效):
|
||||
* - `packs:reset:token:<摘要>` 令牌 → 用户 id(TTL = config.email.resetTtl,默认 30 分钟)
|
||||
* - `packs:reset:user:<用户id>` 该用户**当前**最后一次发出的令牌摘要(用于让旧链接立刻失效)
|
||||
* - `packs:reset:sent:<用户id>` 重发节流标记(SET NX,TTL = config.email.resendInterval,默认 60 秒)
|
||||
*
|
||||
* 令牌是一次性的:重置成功后 `consume()` 把上面两个 key 都删掉。
|
||||
* 对外不抛异常,统一返回 `{ ok, message }`,方便页面回提示(不弹 500)。
|
||||
*/
|
||||
class PasswordResetService extends Service {
|
||||
get redis() {
|
||||
return this.app.redis;
|
||||
}
|
||||
|
||||
get cfg() {
|
||||
return this.app.config.email;
|
||||
}
|
||||
|
||||
prefix(rest) {
|
||||
return `${this.app.config.cache.prefix}${SEGMENT}:${rest}`;
|
||||
}
|
||||
|
||||
tokenKey(token) {
|
||||
return this.prefix(`token:${digest(token)}`);
|
||||
}
|
||||
|
||||
userKey(userId) {
|
||||
return this.prefix(`user:${userId}`);
|
||||
}
|
||||
|
||||
sentKey(userId) {
|
||||
return this.prefix(`sent:${userId}`);
|
||||
}
|
||||
|
||||
/** Redis 不可用时给友好提示,而不是让页面 500 */
|
||||
unavailable() {
|
||||
return { ok: false, message: '重置密码服务暂不可用(Redis 未就绪),请稍后再试' };
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成重置链接并发送邮件(同一个用户只保留最新一条链接,旧链接立即失效)
|
||||
* @param {object} user 用户实例(需要 id / email)
|
||||
* @param {string} origin 站点地址(如 http://127.0.0.1:7001)
|
||||
* @return {Promise<{ok:boolean, message?:string, devMode?:boolean, url?:string}>}
|
||||
*/
|
||||
async send(user, origin) {
|
||||
if (!this.redis) return this.unavailable();
|
||||
|
||||
const ttl = this.cfg.resetTtl;
|
||||
let locked;
|
||||
let token;
|
||||
try {
|
||||
// 重发节流:同一用户 resendInterval 秒内只发一次
|
||||
locked = await this.redis.set(this.sentKey(user.id), '1', 'EX', this.cfg.resendInterval, 'NX');
|
||||
if (locked !== 'OK') {
|
||||
return { ok: false, message: `重置链接已发送,请 ${this.cfg.resendInterval} 秒后再试` };
|
||||
}
|
||||
|
||||
// 先把旧链接作废,再写新链接
|
||||
const old = await this.redis.get(this.userKey(user.id));
|
||||
token = crypto.randomBytes(32).toString('hex');
|
||||
await this.redis.setex(this.tokenKey(token), ttl, String(user.id));
|
||||
await this.redis.setex(this.userKey(user.id), ttl, digest(token));
|
||||
if (old) await this.redis.del(this.prefix(`token:${old}`));
|
||||
} catch (err) {
|
||||
this.ctx.logger.error('[reset] 生成重置令牌失败 user=%s : %s', user.id, err.message);
|
||||
return this.unavailable();
|
||||
}
|
||||
|
||||
const url = `${String(origin || '').replace(/\/+$/, '')}/reset?token=${token}`;
|
||||
const mail = await this.ctx.service.mail.sendResetLink(user.email, url, { ttl });
|
||||
if (mail.failed) {
|
||||
// 发信失败:把令牌撤掉并放开节流位,用户改完邮箱/稍后可立即重试
|
||||
await this.redis.del(this.tokenKey(token), this.userKey(user.id), this.sentKey(user.id)).catch(() => {});
|
||||
return { ok: false, message: '邮件发送失败,请稍后再试' };
|
||||
}
|
||||
|
||||
this.ctx.logger.info('[reset] 重置链接已生成 user=%s email=%s', user.id, user.email);
|
||||
return { ok: true, devMode: mail.devMode, url: mail.devMode ? url : undefined };
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验令牌(不改动状态)
|
||||
* @param {string} token 链接里的令牌原文
|
||||
* @return {Promise<number|null>} 用户 id,无效/过期返回 null
|
||||
*/
|
||||
async verify(token) {
|
||||
if (!this.redis || !token) return null;
|
||||
try {
|
||||
const userId = await this.redis.get(this.tokenKey(token));
|
||||
return userId ? Number(userId) : null;
|
||||
} catch (err) {
|
||||
this.ctx.logger.error('[reset] 校验令牌失败 : %s', err.message);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** 消费令牌(重置成功后调用,链接随即失效) */
|
||||
async consume(token, userId) {
|
||||
if (!this.redis) return;
|
||||
try {
|
||||
await this.redis.del(this.tokenKey(token));
|
||||
await this.redis.del(this.userKey(userId));
|
||||
await this.redis.del(this.sentKey(userId));
|
||||
} catch (err) {
|
||||
this.ctx.logger.warn('[reset] 清理令牌失败 : %s', err.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = PasswordResetService;
|
||||
434
backend/app/service/scan.js
Normal file
434
backend/app/service/scan.js
Normal file
@ -0,0 +1,434 @@
|
||||
'use strict';
|
||||
|
||||
const { Service } = require('egg');
|
||||
const { Op } = require('sequelize');
|
||||
|
||||
/** 单次上报的条数上限(防止一次请求塞太多) */
|
||||
const MAX_BATCH = 500;
|
||||
/** 字段长度(与 DDL 保持一致) */
|
||||
const MAX_CHANNEL_ID = 64;
|
||||
const MAX_CHANNEL_NAME = 128;
|
||||
const MAX_BARCODE = 255;
|
||||
|
||||
/** 去掉首尾空白并把非字符串转成字符串 */
|
||||
function text(value) {
|
||||
if (value === undefined || value === null) return '';
|
||||
return String(value).trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析扫描时间,统一截断到秒(去重键的一部分)
|
||||
*
|
||||
* 支持:`2026-10-16 12:00:00` / `2026-10-16T12:00:00` / `2026/10/16 12:00:00`
|
||||
* / 10 位秒级时间戳 / 13 位毫秒级时间戳 / Date
|
||||
* 无时区的字符串按**服务器本地时区**解析(与 Sequelize 的 +08:00 一致)。
|
||||
*
|
||||
* @return {Date|null} 非法返回 null
|
||||
*/
|
||||
function parseScanTime(value) {
|
||||
if (value === undefined || value === null || value === '') return null;
|
||||
if (value instanceof Date) return Number.isNaN(value.getTime()) ? null : truncateToSecond(value);
|
||||
|
||||
const str = text(value);
|
||||
if (!str) return null;
|
||||
|
||||
let date;
|
||||
if (/^\d{10}$/.test(str)) {
|
||||
date = new Date(Number(str) * 1000); // 秒级时间戳
|
||||
} else if (/^\d{13}$/.test(str)) {
|
||||
date = new Date(Number(str)); // 毫秒级时间戳
|
||||
} else {
|
||||
date = new Date(str.replace(/\//g, '-').replace(' ', 'T'));
|
||||
}
|
||||
|
||||
if (!date || Number.isNaN(date.getTime())) return null;
|
||||
return truncateToSecond(date);
|
||||
}
|
||||
|
||||
function truncateToSecond(date) {
|
||||
const copy = new Date(date.getTime());
|
||||
copy.setMilliseconds(0);
|
||||
return copy;
|
||||
}
|
||||
|
||||
/** 唯一键冲突(重复上报)错误 */
|
||||
function isDuplicateError(err) {
|
||||
if (!err) return false;
|
||||
if (err.name === 'SequelizeUniqueConstraintError') return true;
|
||||
if (err.parent && err.parent.code === 'ER_DUP_ENTRY') return true;
|
||||
return err.code === 'ER_DUP_ENTRY';
|
||||
}
|
||||
|
||||
/** 记录去重用的内存键 */
|
||||
function dedupKey(row) {
|
||||
return [ row.scannerId, row.channelId, row.scanTime.getTime(), row.barcode ].join('\u0000');
|
||||
}
|
||||
|
||||
function toInt(value) {
|
||||
const num = Number(value);
|
||||
return Number.isFinite(num) ? num : null;
|
||||
}
|
||||
|
||||
class ScanService extends Service {
|
||||
get ScanChannel() {
|
||||
return this.app.model.ScanChannel;
|
||||
}
|
||||
|
||||
get ScanRecord() {
|
||||
return this.app.model.ScanRecord;
|
||||
}
|
||||
|
||||
/**
|
||||
* 中控上报通道(channel_id + channel_name)
|
||||
*
|
||||
* - 同一中控 + 同一 channel_id 视为同一个通道:存在则更新通道名与最近上报时间;
|
||||
* - 曾被软删除的通道会被「复活」(deleted_at 置空),避免唯一键挡住重新启用;
|
||||
* - 同一次上报里重复的 channel_id 只处理最后一次。
|
||||
*
|
||||
* @param {object} scanner 中控(扫描器实例,来自 scanner_auth)
|
||||
* @param {Array} channels 形如 [{ channelId, channelName }]
|
||||
* @return {Promise<{received:number, created:number, updated:number, invalid:number, errors:Array, channels:Array}>}
|
||||
*/
|
||||
async reportChannels(scanner, channels) {
|
||||
const list = Array.isArray(channels) ? channels : [];
|
||||
if (!list.length) this.ctx.throw(422, 'channels 不能为空');
|
||||
if (list.length > MAX_BATCH) this.ctx.throw(422, `单次最多上报 ${MAX_BATCH} 个通道`);
|
||||
|
||||
const now = new Date();
|
||||
const errors = [];
|
||||
const normalized = new Map(); // channelId -> { channelId, channelName }
|
||||
|
||||
list.forEach((raw, index) => {
|
||||
const item = raw && typeof raw === 'object' ? raw : {};
|
||||
const channelId = text(item.channelId || item.channel_id);
|
||||
const channelName = text(item.channelName || item.channel_name);
|
||||
if (!channelId) {
|
||||
errors.push({ index, message: 'channelId 不能为空' });
|
||||
return;
|
||||
}
|
||||
if (channelId.length > MAX_CHANNEL_ID) {
|
||||
errors.push({ index, message: `channelId 超长(>${MAX_CHANNEL_ID})` });
|
||||
return;
|
||||
}
|
||||
if (channelName.length > MAX_CHANNEL_NAME) {
|
||||
errors.push({ index, message: `channelName 超长(>${MAX_CHANNEL_NAME})` });
|
||||
return;
|
||||
}
|
||||
// 同一次上报里同 channelId 只保留最后一次
|
||||
normalized.set(channelId, { channelId, channelName });
|
||||
});
|
||||
|
||||
const rows = [ ...normalized.values() ];
|
||||
if (!rows.length) {
|
||||
return { received: list.length, created: 0, updated: 0, invalid: errors.length, errors, channels: [] };
|
||||
}
|
||||
|
||||
const ids = rows.map(row => row.channelId);
|
||||
const existing = await this.ScanChannel.findAll({
|
||||
where: { scannerId: scanner.id, channelId: { [Op.in]: ids } },
|
||||
paranoid: false,
|
||||
});
|
||||
const existingMap = new Map(existing.map(row => [ row.channelId, row ]));
|
||||
|
||||
let created = 0;
|
||||
let updated = 0;
|
||||
const saved = [];
|
||||
|
||||
for (const row of rows) {
|
||||
const hit = existingMap.get(row.channelId);
|
||||
if (hit) {
|
||||
if (hit.deletedAt) {
|
||||
await this.ScanChannel.restore({ where: { id: hit.id } });
|
||||
this.ctx.logger.info('[scan] 通道 %s 已重新启用 (scanner=%s)', row.channelId, scanner.sn);
|
||||
}
|
||||
await this.ScanChannel.update(
|
||||
{ channelName: row.channelName, lastReportAt: now },
|
||||
{ where: { id: hit.id }, paranoid: false },
|
||||
);
|
||||
updated++;
|
||||
saved.push(Object.assign({ id: hit.id }, row, { lastReportAt: now }));
|
||||
} else {
|
||||
const instance = await this.ScanChannel.create({
|
||||
scannerId: scanner.id,
|
||||
channelId: row.channelId,
|
||||
channelName: row.channelName,
|
||||
lastReportAt: now,
|
||||
status: 1,
|
||||
});
|
||||
created++;
|
||||
saved.push(instance.toJSON());
|
||||
}
|
||||
}
|
||||
|
||||
this.ctx.logger.info('[scan] 通道上报 %s: 新增 %d / 更新 %d / 非法 %d', scanner.sn, created, updated, errors.length);
|
||||
return {
|
||||
received: list.length,
|
||||
created,
|
||||
updated,
|
||||
invalid: errors.length,
|
||||
errors,
|
||||
channels: saved,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 中控上报扫码结果:条码 + 扫描时间 + 通道 id
|
||||
*
|
||||
* 去重:同一中控 + 同一通道 + 同一时间(秒) + 同一条码 只入库一次,
|
||||
* 重复上报不报错,返回 { inserted, duplicated }。
|
||||
* 顺带:刷新通道的最近上报时间(未知通道自动补一条,通道名留空)、刷新中控心跳。
|
||||
*
|
||||
* @param {object} scanner 中控(扫描器实例)
|
||||
* @param {Array} records 形如 [{ barcode, scanTime, channelId }]
|
||||
* @return {Promise<object>} { received, inserted, duplicated, invalid, errors, unknownChannels }
|
||||
*/
|
||||
async ingest(scanner, records) {
|
||||
const list = Array.isArray(records) ? records : [];
|
||||
if (!list.length) this.ctx.throw(422, 'records 不能为空');
|
||||
if (list.length > MAX_BATCH) this.ctx.throw(422, `单次最多上报 ${MAX_BATCH} 条`);
|
||||
|
||||
const now = new Date();
|
||||
const errors = [];
|
||||
const rows = [];
|
||||
const seen = new Set();
|
||||
|
||||
list.forEach((raw, index) => {
|
||||
const item = raw && typeof raw === 'object' ? raw : {};
|
||||
const barcode = text(item.barcode || item.code);
|
||||
const channelId = text(item.channelId || item.channel_id);
|
||||
const scanTime = parseScanTime(item.scanTime || item.scan_time || item.time);
|
||||
|
||||
if (!channelId) {
|
||||
errors.push({ index, message: 'channelId 不能为空' });
|
||||
return;
|
||||
}
|
||||
if (channelId.length > MAX_CHANNEL_ID) {
|
||||
errors.push({ index, message: `channelId 超长(>${MAX_CHANNEL_ID})` });
|
||||
return;
|
||||
}
|
||||
if (!barcode) {
|
||||
errors.push({ index, message: 'barcode 不能为空' });
|
||||
return;
|
||||
}
|
||||
if (barcode.length > MAX_BARCODE) {
|
||||
errors.push({ index, message: `barcode 超长(>${MAX_BARCODE})` });
|
||||
return;
|
||||
}
|
||||
if (!scanTime) {
|
||||
errors.push({ index, message: 'scanTime 不能为空或格式非法' });
|
||||
return;
|
||||
}
|
||||
|
||||
const row = { scannerId: scanner.id, channelId, barcode, scanTime, reportedAt: now };
|
||||
// 同一批里完全相同的上报只留一条
|
||||
const key = dedupKey(row);
|
||||
if (seen.has(key)) return;
|
||||
seen.add(key);
|
||||
rows.push(row);
|
||||
});
|
||||
|
||||
const result = {
|
||||
received: list.length,
|
||||
inserted: 0,
|
||||
duplicated: list.length - errors.length - rows.length, // 同一批内的重复条数
|
||||
invalid: errors.length,
|
||||
errors,
|
||||
unknownChannels: [],
|
||||
};
|
||||
if (!rows.length) return result;
|
||||
|
||||
const fresh = await this.filterExisting(rows);
|
||||
result.duplicated += rows.length - fresh.length;
|
||||
|
||||
if (fresh.length) {
|
||||
try {
|
||||
await this.ScanRecord.bulkCreate(fresh);
|
||||
result.inserted = fresh.length;
|
||||
} catch (err) {
|
||||
if (!isDuplicateError(err)) throw err;
|
||||
// 并发下正好撞上唯一键:退化成逐条插入,撞上的算重复
|
||||
for (const row of fresh) {
|
||||
try {
|
||||
await this.ScanRecord.create(row);
|
||||
result.inserted++;
|
||||
} catch (inner) {
|
||||
if (!isDuplicateError(inner)) throw inner;
|
||||
}
|
||||
}
|
||||
result.duplicated += fresh.length - result.inserted;
|
||||
}
|
||||
}
|
||||
|
||||
const channelIds = [ ...new Set(rows.map(row => row.channelId)) ];
|
||||
result.unknownChannels = await this.touchChannels(scanner, channelIds, now);
|
||||
// 有数据上报即视为中控在线,刷新心跳
|
||||
await this.ctx.service.scanner.heartbeat(scanner, this.ctx.ip);
|
||||
|
||||
this.ctx.logger.info(
|
||||
'[scan] 扫码上报 %s: 收到 %d / 入库 %d / 去重 %d / 非法 %d',
|
||||
scanner.sn, result.received, result.inserted, result.duplicated, result.invalid,
|
||||
);
|
||||
if (result.unknownChannels.length) {
|
||||
this.ctx.logger.warn('[scan] %s 上报了未登记的通道: %s', scanner.sn, result.unknownChannels.join(', '));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 过滤掉库里已存在的记录(一次查询,按中控 + 时间范围 + 通道)
|
||||
* @return {Promise<Array>} 需要新入库的行
|
||||
*/
|
||||
async filterExisting(rows) {
|
||||
const channelIds = [ ...new Set(rows.map(row => row.channelId)) ];
|
||||
const times = rows.map(row => row.scanTime.getTime());
|
||||
const from = new Date(Math.min(...times));
|
||||
const to = new Date(Math.max(...times));
|
||||
|
||||
const existing = await this.ScanRecord.findAll({
|
||||
attributes: [ 'scannerId', 'channelId', 'barcode', 'scanTime' ],
|
||||
where: {
|
||||
scannerId: rows[0].scannerId,
|
||||
channelId: { [Op.in]: channelIds },
|
||||
scanTime: { [Op.between]: [ from, to ] },
|
||||
},
|
||||
raw: true,
|
||||
});
|
||||
|
||||
const existingKeys = new Set(existing.map(row => dedupKey(Object.assign({}, row, {
|
||||
scanTime: new Date(row.scanTime),
|
||||
}))));
|
||||
|
||||
return rows.filter(row => !existingKeys.has(dedupKey(row)));
|
||||
}
|
||||
|
||||
/**
|
||||
* 刷新通道的最近上报时间;未登记的通道自动补一条(通道名留空)
|
||||
* @return {Promise<Array<string>>} 自动补建的通道 id
|
||||
*/
|
||||
async touchChannels(scanner, channelIds, at = new Date()) {
|
||||
if (!channelIds.length) return [];
|
||||
|
||||
const known = await this.ScanChannel.findAll({
|
||||
attributes: [ 'channelId' ],
|
||||
where: { scannerId: scanner.id, channelId: { [Op.in]: channelIds } },
|
||||
paranoid: false,
|
||||
raw: true,
|
||||
});
|
||||
const knownIds = new Set(known.map(row => row.channelId));
|
||||
const missing = channelIds.filter(id => !knownIds.has(id));
|
||||
|
||||
if (missing.length) {
|
||||
await this.ScanChannel.bulkCreate(missing.map(channelId => ({
|
||||
scannerId: scanner.id,
|
||||
channelId,
|
||||
channelName: '',
|
||||
lastReportAt: at,
|
||||
status: 1,
|
||||
})));
|
||||
}
|
||||
|
||||
await this.ScanChannel.update(
|
||||
{ lastReportAt: at },
|
||||
{ where: { scannerId: scanner.id, channelId: { [Op.in]: channelIds } }, paranoid: false },
|
||||
);
|
||||
|
||||
return missing;
|
||||
}
|
||||
|
||||
/** 通道列表(分页;可按中控 / 关键字过滤),带所属中控 */
|
||||
async listChannels({ page = 1, pageSize = 20, scannerId, keyword, status } = {}) {
|
||||
const size = Math.min(Math.max(Number(pageSize) || 20, 1), 200);
|
||||
const current = Math.max(Number(page) || 1, 1);
|
||||
|
||||
const where = {};
|
||||
if (scannerId) where.scannerId = Number(scannerId);
|
||||
if (status !== undefined && status !== '' && status !== null) where.status = Number(status);
|
||||
if (keyword) {
|
||||
where[Op.or] = [
|
||||
{ channelId: { [Op.like]: `%${keyword}%` } },
|
||||
{ channelName: { [Op.like]: `%${keyword}%` } },
|
||||
];
|
||||
}
|
||||
|
||||
const { rows, count } = await this.ScanChannel.findAndCountAll({
|
||||
where,
|
||||
include: [{ model: this.app.model.Scanner, as: 'scanner', required: false, attributes: [ 'id', 'sn', 'name' ] }],
|
||||
order: [[ 'scannerId', 'ASC' ], [ 'channelId', 'ASC' ]],
|
||||
limit: size,
|
||||
offset: (current - 1) * size,
|
||||
});
|
||||
|
||||
return {
|
||||
list: rows.map(row => row.toJSON()),
|
||||
total: count,
|
||||
page: current,
|
||||
pageSize: size,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 扫码记录列表(分页 + 通道 / 条码 / 时间范围过滤),带所属中控
|
||||
* @param {object} params { page, pageSize, scannerId 单个中控, scannerIds 多个中控(用户端按「我的设备」过滤用),
|
||||
* channelId, barcode, startTime, endTime }
|
||||
*/
|
||||
async listRecords({ page = 1, pageSize = 20, scannerId, scannerIds, channelId, barcode, startTime, endTime } = {}) {
|
||||
const size = Math.min(Math.max(Number(pageSize) || 20, 1), 200);
|
||||
const current = Math.max(Number(page) || 1, 1);
|
||||
|
||||
const where = {};
|
||||
if (scannerId) where.scannerId = Number(scannerId);
|
||||
if (scannerIds) where.scannerId = { [Op.in]: scannerIds.map(Number) };
|
||||
if (channelId) where.channelId = channelId;
|
||||
if (barcode) where.barcode = { [Op.like]: `%${barcode}%` };
|
||||
|
||||
const from = parseScanTime(startTime);
|
||||
const to = parseScanTime(endTime);
|
||||
if (from || to) {
|
||||
where.scanTime = {};
|
||||
if (from) where.scanTime[Op.gte] = from;
|
||||
if (to) where.scanTime[Op.lte] = to;
|
||||
}
|
||||
|
||||
const { rows, count } = await this.ScanRecord.findAndCountAll({
|
||||
where,
|
||||
include: [{ model: this.app.model.Scanner, as: 'scanner', required: false, attributes: [ 'id', 'sn', 'name' ] }],
|
||||
order: [[ 'scanTime', 'DESC' ], [ 'id', 'DESC' ]],
|
||||
limit: size,
|
||||
offset: (current - 1) * size,
|
||||
});
|
||||
|
||||
return {
|
||||
list: rows.map(row => row.toJSON()),
|
||||
total: count,
|
||||
page: current,
|
||||
pageSize: size,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 通道数(首页统计用)
|
||||
* @param {object} where 普通条件;或 `{ scannerIds: [1,2] }` 限定这几个中控(用户端统计用)
|
||||
*/
|
||||
async countChannels({ scannerIds, ...where } = {}) {
|
||||
if (scannerIds) where.scannerId = { [Op.in]: scannerIds.map(Number) };
|
||||
return this.ScanChannel.count({ where });
|
||||
}
|
||||
|
||||
/** 扫码记录数(首页统计用;`{ scannerIds }` 限定中控,同 countChannels) */
|
||||
async countRecords({ scannerIds, ...where } = {}) {
|
||||
if (scannerIds) where.scannerId = { [Op.in]: scannerIds.map(Number) };
|
||||
return this.ScanRecord.count({ where });
|
||||
}
|
||||
|
||||
/** 某中控的通道(上报后回显用) */
|
||||
async findChannelsByScanner(scannerId) {
|
||||
const rows = await this.ScanChannel.findAll({
|
||||
where: { scannerId },
|
||||
order: [[ 'channelId', 'ASC' ]],
|
||||
});
|
||||
return rows.map(row => row.toJSON());
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = ScanService;
|
||||
module.exports.parseScanTime = parseScanTime;
|
||||
271
backend/app/service/scanner.js
Normal file
271
backend/app/service/scanner.js
Normal file
@ -0,0 +1,271 @@
|
||||
'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;
|
||||
194
backend/app/service/user.js
Normal file
194
backend/app/service/user.js
Normal file
@ -0,0 +1,194 @@
|
||||
'use strict';
|
||||
|
||||
const { Service } = require('egg');
|
||||
const { Op } = require('sequelize');
|
||||
|
||||
const MAX_PAGE_SIZE = 100;
|
||||
/** 允许创建/更新的字段白名单 */
|
||||
const WRITABLE_FIELDS = [ 'username', 'email', 'nickname', 'avatar', 'phone', 'gender', 'status', 'remark' ];
|
||||
/** 需要校验唯一性的字段 */
|
||||
const UNIQUE_FIELDS = [ 'username', 'phone', 'email' ];
|
||||
/** 默认查询字段:排除密码哈希,避免接口/模板意外外泄 */
|
||||
const SAFE_ATTRIBUTES = { exclude: [ 'passwordHash' ] };
|
||||
|
||||
/** 从查询结果里去掉密码哈希 */
|
||||
function sanitize(row) {
|
||||
if (!row) return row;
|
||||
const { passwordHash, ...rest } = row;
|
||||
return rest;
|
||||
}
|
||||
|
||||
class UserService extends Service {
|
||||
get User() {
|
||||
return this.app.model.User;
|
||||
}
|
||||
|
||||
/** 按主键查询,返回普通对象;不存在返回 null */
|
||||
async findById(id) {
|
||||
const user = await this.User.findByPk(id, { attributes: SAFE_ATTRIBUTES });
|
||||
return user ? user.toJSON() : null;
|
||||
}
|
||||
|
||||
/** 按用户名 / 手机号查询 */
|
||||
async findOneBy(where) {
|
||||
const user = await this.User.findOne({ where, attributes: SAFE_ATTRIBUTES });
|
||||
return user ? user.toJSON() : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 登录用:按用户名 / 手机号 / 邮箱查询,包含密码哈希(仅鉴权内部使用,不要外传)
|
||||
* @return {Promise<object|null>} Sequelize 实例
|
||||
*/
|
||||
async findByAccount(account) {
|
||||
return this.User.findOne({
|
||||
where: { [Op.or]: [{ username: account }, { phone: account }, { email: account }] },
|
||||
attributes: { include: [ 'passwordHash' ] },
|
||||
});
|
||||
}
|
||||
|
||||
/** 写入密码哈希(哈希在 auth service 里生成) */
|
||||
async setPassword(id, passwordHash) {
|
||||
const user = await this.User.findByPk(id);
|
||||
if (!user) return false;
|
||||
|
||||
await user.update({ passwordHash });
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 按主键查询并带出密码哈希(仅改密码等鉴权场景内部使用,不要外传)
|
||||
* @return {Promise<object|null>} Sequelize 实例
|
||||
*/
|
||||
async findByIdWithPassword(id) {
|
||||
return this.User.findByPk(id, { attributes: { include: [ 'passwordHash' ] } });
|
||||
}
|
||||
|
||||
/** 只保留登录态需要的字段(存 session / 回给页面) */
|
||||
toSafeUser(user) {
|
||||
return {
|
||||
id: user.id,
|
||||
username: user.username,
|
||||
nickname: user.nickname,
|
||||
avatar: user.avatar,
|
||||
phone: user.phone,
|
||||
status: Number(user.status),
|
||||
};
|
||||
}
|
||||
|
||||
/** 总数(首页统计用) */
|
||||
async count(where = {}) {
|
||||
return this.User.count({ where });
|
||||
}
|
||||
|
||||
/** 通过微信授权反查用户(appid + openid) */
|
||||
async findByOpenid(appid, openid) {
|
||||
const oauth = await this.app.model.WechatOauth.findOne({
|
||||
where: { appid, openid },
|
||||
include: [{ model: this.User, as: 'user', required: true, attributes: SAFE_ATTRIBUTES }],
|
||||
});
|
||||
return oauth && oauth.user ? oauth.user.toJSON() : null;
|
||||
}
|
||||
|
||||
/** 分页查询:keyword 模糊匹配昵称 / 登录名 / 手机号 / 邮箱 */
|
||||
async list({ page = 1, pageSize = 20, keyword, status } = {}) {
|
||||
const size = Math.min(Number(pageSize) || 20, MAX_PAGE_SIZE);
|
||||
const current = Math.max(Number(page) || 1, 1);
|
||||
|
||||
const where = {};
|
||||
if (status !== undefined && status !== '' && status !== null) {
|
||||
where.status = Number(status);
|
||||
}
|
||||
if (keyword) {
|
||||
where[Op.or] = [
|
||||
{ nickname: { [Op.like]: `%${keyword}%` } },
|
||||
{ username: { [Op.like]: `%${keyword}%` } },
|
||||
{ phone: { [Op.like]: `%${keyword}%` } },
|
||||
{ email: { [Op.like]: `%${keyword}%` } },
|
||||
];
|
||||
}
|
||||
|
||||
const { rows, count } = await this.User.findAndCountAll({
|
||||
where,
|
||||
attributes: SAFE_ATTRIBUTES,
|
||||
limit: size,
|
||||
offset: (current - 1) * size,
|
||||
order: [[ 'id', 'DESC' ]],
|
||||
});
|
||||
|
||||
return {
|
||||
list: rows.map(row => row.toJSON()),
|
||||
total: count,
|
||||
page: current,
|
||||
pageSize: size,
|
||||
};
|
||||
}
|
||||
|
||||
/** 新增,返回完整记录 */
|
||||
async create(data) {
|
||||
await this.assertUnique(data);
|
||||
const user = await this.User.create(pick(data));
|
||||
return sanitize(user.toJSON());
|
||||
}
|
||||
|
||||
/** 更新,返回更新后的记录;记录不存在返回 null */
|
||||
async update(id, data) {
|
||||
const user = await this.User.findByPk(id);
|
||||
if (!user) return null;
|
||||
|
||||
await this.assertUnique(data, id);
|
||||
const fields = pick(data);
|
||||
if (Object.keys(fields).length) {
|
||||
await user.update(fields);
|
||||
}
|
||||
return sanitize(user.toJSON());
|
||||
}
|
||||
|
||||
/** 软删除,返回是否删除成功 */
|
||||
async remove(id) {
|
||||
const affected = await this.User.destroy({ where: { id } });
|
||||
return affected > 0;
|
||||
}
|
||||
|
||||
/** 记录一次登录时间 */
|
||||
async touchLogin(id) {
|
||||
const user = await this.User.findByPk(id);
|
||||
if (!user) return null;
|
||||
|
||||
await user.update({ lastLoginAt: new Date() });
|
||||
return user.toJSON();
|
||||
}
|
||||
|
||||
/** username / phone 唯一性校验,冲突抛 409 */
|
||||
async assertUnique(data, excludeId) {
|
||||
for (const field of UNIQUE_FIELDS) {
|
||||
const value = data[field];
|
||||
if (value === undefined || value === null || value === '') continue;
|
||||
|
||||
const where = { [field]: value };
|
||||
if (excludeId) where.id = { [Op.ne]: excludeId };
|
||||
|
||||
const exists = await this.User.findOne({ where });
|
||||
if (exists) this.ctx.throw(409, `${field} 已存在:${value}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 只取白名单字段,并做基础类型归一化 */
|
||||
function pick(data = {}) {
|
||||
const fields = {};
|
||||
for (const key of WRITABLE_FIELDS) {
|
||||
if (data[key] === undefined) continue;
|
||||
if (key === 'gender' || key === 'status') {
|
||||
fields[key] = Number(data[key]);
|
||||
} else if (key === 'phone' || key === 'email') {
|
||||
// 空串统一存 NULL(唯一索引允许多个 NULL);邮箱还做小写归一
|
||||
const value = String(data[key] || '').trim();
|
||||
fields[key] = value ? (key === 'email' ? value.toLowerCase() : value) : null;
|
||||
} else {
|
||||
fields[key] = data[key];
|
||||
}
|
||||
}
|
||||
return fields;
|
||||
}
|
||||
|
||||
module.exports = UserService;
|
||||
116
backend/app/service/verify_code.js
Normal file
116
backend/app/service/verify_code.js
Normal file
@ -0,0 +1,116 @@
|
||||
'use strict';
|
||||
|
||||
const { Service } = require('egg');
|
||||
|
||||
/** 场景 → Redis key 段(不同场景的验证码互不影响) */
|
||||
const SCENES = { register: 'verify:register' };
|
||||
|
||||
/** 6 位数字验证码 */
|
||||
function randomCode() {
|
||||
return String(Math.floor(Math.random() * 1000000)).padStart(6, '0');
|
||||
}
|
||||
|
||||
/**
|
||||
* 邮箱验证码:生成 / 校验 / 消费
|
||||
*
|
||||
* 存在 Redis:
|
||||
* - `packs:verify:<scene>:<email>` 验证码本身(TTL = config.email.codeTtl,默认 10 分钟)
|
||||
* - `packs:verify:<scene>:<email>:sent` 重发节流标记(SET NX,TTL = resendInterval,默认 60 秒)
|
||||
* - `packs:verify:<scene>:<email>:try` 错误次数(超过 maxAttempts 作废验证码)
|
||||
*
|
||||
* 对外不抛异常,统一返回 `{ ok, message }`,方便页面回提示(不弹 500)。
|
||||
*/
|
||||
class VerifyCodeService extends Service {
|
||||
get redis() {
|
||||
return this.app.redis;
|
||||
}
|
||||
|
||||
get cfg() {
|
||||
return this.app.config.email;
|
||||
}
|
||||
|
||||
keyOf(scene, email) {
|
||||
const segment = SCENES[scene] || scene;
|
||||
return `${this.app.config.cache.prefix}${segment}:${email}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成验证码并发邮件
|
||||
* @param {string} scene 场景(register)
|
||||
* @param {string} email 邮箱(调用方保证已小写归一)
|
||||
* @return {Promise<{ok:boolean, message?:string, code?:string, devMode?:boolean, ttl?:number, resendInterval?:number}>}
|
||||
*/
|
||||
async send(scene, email) {
|
||||
if (!this.redis) return { ok: false, message: '验证码服务不可用(Redis 未就绪)' };
|
||||
|
||||
const key = this.keyOf(scene, email);
|
||||
try {
|
||||
// 重发节流:SET NX 原子占位,间隔内只允许发一次
|
||||
const locked = await this.redis.set(`${key}:sent`, '1', 'EX', this.cfg.resendInterval, 'NX');
|
||||
if (locked !== 'OK') {
|
||||
return { ok: false, message: `验证码已发送,请 ${this.cfg.resendInterval} 秒后再试` };
|
||||
}
|
||||
|
||||
const code = randomCode();
|
||||
await this.redis.setex(key, this.cfg.codeTtl, code);
|
||||
await this.redis.del(`${key}:try`);
|
||||
|
||||
const mail = await this.ctx.service.mail.sendVerifyCode(email, code, { ttl: this.cfg.codeTtl });
|
||||
if (mail.failed) {
|
||||
await this.redis.del(`${key}:sent`); // 发失败就不要占着节流位
|
||||
return { ok: false, message: '验证码邮件发送失败,请稍后再试' };
|
||||
}
|
||||
|
||||
this.ctx.logger.info('[verify] %s 验证码已生成: %s (devMode=%s)', scene, email, !!mail.devMode);
|
||||
return {
|
||||
ok: true,
|
||||
ttl: this.cfg.codeTtl,
|
||||
resendInterval: this.cfg.resendInterval,
|
||||
devMode: !!mail.devMode,
|
||||
// 开发模式才把验证码回传给页面(生产走邮件)
|
||||
code: mail.devMode ? code : undefined,
|
||||
};
|
||||
} catch (err) {
|
||||
this.ctx.logger.error('[verify] 验证码发送失败 %s : %s', email, err.message);
|
||||
return { ok: false, message: '验证码服务暂不可用,请稍后再试' };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验验证码(不消费,注册成功后再 consume,这样用户名冲突时可以改完重提)
|
||||
* @return {Promise<{ok:boolean, message?:string}>}
|
||||
*/
|
||||
async check(scene, email, code) {
|
||||
if (!this.redis) return { ok: false, message: '验证码服务不可用(Redis 未就绪)' };
|
||||
|
||||
const key = this.keyOf(scene, email);
|
||||
try {
|
||||
const expect = await this.redis.get(key);
|
||||
if (!expect) return { ok: false, message: '验证码已过期,请重新获取' };
|
||||
|
||||
const tries = await this.redis.incr(`${key}:try`);
|
||||
await this.redis.expire(`${key}:try`, this.cfg.codeTtl);
|
||||
if (tries > this.cfg.maxAttempts) {
|
||||
await this.redis.del(key);
|
||||
return { ok: false, message: '验证码错误次数过多,请重新获取' };
|
||||
}
|
||||
if (String(code) !== String(expect)) {
|
||||
return { ok: false, message: '邮箱验证码不正确' };
|
||||
}
|
||||
return { ok: true };
|
||||
} catch (err) {
|
||||
this.ctx.logger.error('[verify] 验证码校验失败 %s : %s', email, err.message);
|
||||
return { ok: false, message: '验证码服务暂不可用,请稍后再试' };
|
||||
}
|
||||
}
|
||||
|
||||
/** 消费掉验证码(注册成功后调用) */
|
||||
async consume(scene, email) {
|
||||
if (!this.redis) return;
|
||||
const key = this.keyOf(scene, email);
|
||||
await this.redis.del(key);
|
||||
await this.redis.del(`${key}:try`);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = VerifyCodeService;
|
||||
97
backend/app/service/wechat.js
Normal file
97
backend/app/service/wechat.js
Normal file
@ -0,0 +1,97 @@
|
||||
'use strict';
|
||||
|
||||
const { Service } = require('egg');
|
||||
|
||||
/** 拼装写库的授权信息(只写入明确传入的字段,避免把旧值覆盖成空) */
|
||||
function buildPayload(data) {
|
||||
const payload = {};
|
||||
if (data.unionid !== undefined) payload.unionid = data.unionid || null;
|
||||
if (data.nickname !== undefined) payload.nickname = data.nickname || '';
|
||||
if (data.avatar !== undefined) payload.avatar = data.avatar || '';
|
||||
if (data.sessionKey !== undefined) payload.sessionKey = data.sessionKey || null;
|
||||
if (data.accessToken !== undefined) payload.accessToken = data.accessToken || null;
|
||||
if (data.refreshToken !== undefined) payload.refreshToken = data.refreshToken || null;
|
||||
if (data.scope !== undefined) payload.scope = data.scope || null;
|
||||
if (data.expiresIn !== undefined && data.expiresIn !== null) {
|
||||
payload.tokenExpiresAt = new Date(Date.now() + Number(data.expiresIn) * 1000);
|
||||
} else if (data.tokenExpiresAt !== undefined) {
|
||||
payload.tokenExpiresAt = data.tokenExpiresAt;
|
||||
}
|
||||
payload.lastAuthAt = new Date();
|
||||
return payload;
|
||||
}
|
||||
|
||||
class WechatService extends Service {
|
||||
get WechatOauth() {
|
||||
return this.app.model.WechatOauth;
|
||||
}
|
||||
|
||||
/**
|
||||
* 绑定微信授权:同一 appid + openid 已存在则更新,否则新建
|
||||
* @param {object} data userId / appid / openid 必填
|
||||
*/
|
||||
async bind(data) {
|
||||
const { userId, appid, openid } = data;
|
||||
const existing = await this.WechatOauth.findOne({ where: { appid, openid } });
|
||||
const payload = buildPayload(data);
|
||||
|
||||
if (existing) {
|
||||
// 换绑:允许把已存在的授权记录改到另一个用户
|
||||
if (userId && Number(existing.userId) !== Number(userId)) {
|
||||
payload.userId = userId;
|
||||
}
|
||||
await existing.update(payload);
|
||||
return existing.toJSON();
|
||||
}
|
||||
|
||||
const created = await this.WechatOauth.create(Object.assign({ userId, appid, openid }, payload));
|
||||
return created.toJSON();
|
||||
}
|
||||
|
||||
/** 按 appid + openid 查询授权记录,并带出关联用户 */
|
||||
async findByOpenid(appid, openid) {
|
||||
const oauth = await this.WechatOauth.findOne({
|
||||
where: { appid, openid },
|
||||
include: [{ model: this.app.model.User, as: 'user', required: false }],
|
||||
});
|
||||
if (!oauth) return null;
|
||||
|
||||
const result = oauth.toJSON();
|
||||
if (result.user) {
|
||||
// 不把用户敏感字段透出去
|
||||
delete result.user.deleted_at;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/** 查询某个用户的全部微信授权 */
|
||||
async listByUser(userId) {
|
||||
const rows = await this.WechatOauth.findAll({
|
||||
where: { userId },
|
||||
order: [[ 'id', 'DESC' ]],
|
||||
});
|
||||
return rows.map(row => row.toJSON());
|
||||
}
|
||||
|
||||
/** 更新小程序 session_key / 令牌 */
|
||||
async updateTokens(id, data) {
|
||||
const oauth = await this.WechatOauth.findByPk(id);
|
||||
if (!oauth) return null;
|
||||
|
||||
await oauth.update(buildPayload(data));
|
||||
return oauth.toJSON();
|
||||
}
|
||||
|
||||
/** 解绑(软删除) */
|
||||
async unbind(id) {
|
||||
const affected = await this.WechatOauth.destroy({ where: { id } });
|
||||
return affected > 0;
|
||||
}
|
||||
|
||||
/** 总数(首页统计用) */
|
||||
async count(where = {}) {
|
||||
return this.WechatOauth.count({ where });
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = WechatService;
|
||||
499
backend/app/service/wechat_login.js
Normal file
499
backend/app/service/wechat_login.js
Normal file
@ -0,0 +1,499 @@
|
||||
'use strict';
|
||||
|
||||
const { Service } = require('egg');
|
||||
const crypto = require('crypto');
|
||||
const qrcode = require('qrcode-generator');
|
||||
|
||||
/** 扫码串码字符集:数字 + 大写字母,去掉了 0/O/1/I 等容易看错的字符 */
|
||||
const CODE_ALPHABET = '23456789ABCDEFGHJKLMNPQRSTUVWXYZ';
|
||||
|
||||
/** 生成 6 位数字 + 字母的随机串码 */
|
||||
function randomCode(length = 6) {
|
||||
let out = '';
|
||||
for (let i = 0; i < length; i++) {
|
||||
out += CODE_ALPHABET[crypto.randomInt(CODE_ALPHABET.length)];
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* 微信公众号「网页授权」地址(在微信内置浏览器里打开时用,scope=snsapi_base 静默拿 openid)
|
||||
* 手机扫码后先落到本站 `/wechat?spm=…`,再重定向到这里。
|
||||
*/
|
||||
function webAuthorizeUrl({ appid, redirectUri, state }) {
|
||||
const query = new URLSearchParams({
|
||||
appid,
|
||||
redirect_uri: redirectUri,
|
||||
response_type: 'code',
|
||||
scope: 'snsapi_base',
|
||||
state,
|
||||
});
|
||||
return `https://open.weixin.qq.com/connect/oauth2/authorize?${query.toString()}#wechat_redirect`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 登录页的微信扫码登录
|
||||
*
|
||||
* - **二维码内容是本站地址**:`http://<域名>/wechat?spm=1.0.<code>.1`,`<code>` 是服务端生成的
|
||||
* 6 位数字 + 字母随机串码(存 Redis,TTL 内有效);二维码本身用零依赖的 qrcode-generator
|
||||
* 现场画成 SVG(`/api/wechat/qrcode.svg`),**全程不加载任何第三方图片/脚本**。
|
||||
* - **扫码后**:手机打开**前端路由** `/wechat?spm=…` → 配了微信就重定向到公众号网页授权(静默拿 openid),
|
||||
* 回到后端 `/api/wechat/callback` 后把「已确认的用户 id」写进 Redis;
|
||||
* 没配微信时退化成「手机确认登录」——扫码的人已经登录才能确认(`POST /api/wechat/confirm`)。
|
||||
* - **不自动建号**:只对「已绑定微信」的账号生效(绑定关系在 `wechat_oauth` 表里,
|
||||
* 可用 `POST /api/wechat/bind` 建立),未绑定就提示先用账号密码登录再绑定。
|
||||
* - 串码一次性:确认结果被电脑端取走后立即删除。
|
||||
*/
|
||||
class WechatLoginService extends Service {
|
||||
get cfg() {
|
||||
return this.app.config.wechat;
|
||||
}
|
||||
|
||||
get redis() {
|
||||
return this.app.redis;
|
||||
}
|
||||
|
||||
/** 是否配好了微信登录 */
|
||||
get enabled() {
|
||||
return Boolean(this.cfg.appid && this.cfg.secret);
|
||||
}
|
||||
|
||||
/** 扫码状态在 Redis 里的 key(value:'pending' = 等扫码;数字 = 已确认的用户 id) */
|
||||
stateKey(code) {
|
||||
return `${this.app.config.cache.prefix}wechat:state:${code}`;
|
||||
}
|
||||
|
||||
/** 长轮询用的广播频道 */
|
||||
channel(code) {
|
||||
return `${this.app.config.cache.prefix}wechat:login:${code}`;
|
||||
}
|
||||
|
||||
/** 设备专用登录:设备自报信息(sn / 名称等)的暂存 key(发码时写入,确认/换码时取走) */
|
||||
deviceKey(code) {
|
||||
return `${this.app.config.cache.prefix}device:info:${code}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 暂存设备自报信息(发码时调用;什么都没传就不写)
|
||||
*
|
||||
* 建记录发生在「扫码确认成功」那一刻,而设备可能只在发码时带了 sn/名称 ——
|
||||
* 存一份就能在确认/换码时沿用,不用要求设备每次都把参数补齐
|
||||
* @param {string} code 登录码
|
||||
* @param {object} info { sn, name, vendor, model, firmware }
|
||||
*/
|
||||
async saveDeviceInfo(code, info = {}) {
|
||||
if (!this.redis || !code) return;
|
||||
|
||||
const payload = {};
|
||||
for (const key of [ 'sn', 'name', 'vendor', 'model', 'firmware' ]) {
|
||||
if (info[key]) payload[key] = info[key];
|
||||
}
|
||||
if (!Object.keys(payload).length) return;
|
||||
|
||||
try {
|
||||
await this.redis.setex(this.deviceKey(code), this.stateTtl, JSON.stringify(payload));
|
||||
} catch (err) {
|
||||
this.ctx.logger.warn('[wechat] 暂存设备信息失败: %s', err.message);
|
||||
}
|
||||
}
|
||||
|
||||
/** 取走设备自报信息(确认成功 / 换码时调用,取走即删),取不到返回 null */
|
||||
async takeDeviceInfo(code) {
|
||||
if (!this.redis || !code) return null;
|
||||
try {
|
||||
const raw = await this.redis.get(this.deviceKey(code));
|
||||
await this.redis.del(this.deviceKey(code));
|
||||
return raw ? JSON.parse(raw) : null;
|
||||
} catch (err) {
|
||||
this.ctx.logger.warn('[wechat] 读取设备信息失败: %s', err.message);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 回调地址:优先用配置,否则按当前请求的 origin 拼
|
||||
* (这是**后端**地址,微信授权后会带 ?code=&state= 重定向到这里,见 controller/auth/wechat.js#callback)
|
||||
*/
|
||||
redirectUri(origin) {
|
||||
if (this.cfg.redirectUri) return this.cfg.redirectUri;
|
||||
return `${String(origin || '').replace(/\/+$/, '')}/api/wechat/callback`;
|
||||
}
|
||||
|
||||
/** 把串码拼成 spm(默认 `1.0.<code>.1`,格式可用 `WECHAT_SPM_PATTERN` 配) */
|
||||
spm(code) {
|
||||
return String(this.cfg.spmPattern || '1.0.{code}.1').replace('{code}', code);
|
||||
}
|
||||
|
||||
/** 从 spm 里把串码抠出来(`1.0.AB12CD.1` → `AB12CD`),格式不对返回空串 */
|
||||
parseSpm(spm) {
|
||||
const length = Number(this.cfg.codeLength || 6);
|
||||
const pattern = new RegExp(`^[0-9A-Za-z]{${length}}$`);
|
||||
for (const seg of String(spm || '').split('.')) {
|
||||
if (pattern.test(seg)) return seg.toUpperCase();
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
/**
|
||||
* 二维码里要编码的内容:本站 `/wechat?spm=1.0.<code>.1`(前端的 origin 由请求带)
|
||||
* @param {object} params { code, origin }
|
||||
* @return {string}
|
||||
*/
|
||||
qrContent({ code, origin } = {}) {
|
||||
if (!code) this.ctx.throw(422, '缺少登录码');
|
||||
return `${String(origin || '').replace(/\/+$/, '')}/wechat?spm=${this.spm(code)}`;
|
||||
}
|
||||
|
||||
/** 公众号网页授权地址(手机在微信里打开 `/wechat?spm=…` 时重定向过去) */
|
||||
oauthAuthorizeUrl({ origin, code }) {
|
||||
return webAuthorizeUrl({
|
||||
appid: this.cfg.appid,
|
||||
redirectUri: this.redirectUri(origin),
|
||||
state: code,
|
||||
});
|
||||
}
|
||||
|
||||
/** 这个串码还在等扫码吗(存在且是 pending) */
|
||||
async isPending(code) {
|
||||
if (!this.redis || !code) return false;
|
||||
try {
|
||||
return await this.redis.get(this.stateKey(code)) === 'pending';
|
||||
} catch (err) {
|
||||
this.ctx.logger.warn('[wechat] 查询扫码状态失败: %s', err.message);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 给前端 API 用:生成一个新串码并登记为 pending(不依赖 session)
|
||||
* @return {Promise<string>} 6 位串码
|
||||
*/
|
||||
async newCode() {
|
||||
const code = randomCode(Number(this.cfg.codeLength || 6));
|
||||
await this.openState(code);
|
||||
return code;
|
||||
}
|
||||
|
||||
/**
|
||||
* 给前端 API 用:轮询串码状态(**长轮询**)
|
||||
*
|
||||
* 行为:
|
||||
* - 已经确认过 → 立刻返回 `{ status:'confirmed', user, token, … }`(取走即删,一次性);
|
||||
* - 串码不存在/已过期 → 立刻返回 `{ status:'refreshed', code }`(附新串码,前端直接换二维码);
|
||||
* - 还在等扫码 → 挂起最多 `wait` 秒(受 `WECHAT_POLL_WAIT` 限制):
|
||||
* - 期间有人确认 → **立即**返回 `confirmed`(靠 Redis 发布订阅通知,不轮询); * - 客户端提前断开(切回账号密码登录 / 关页签 / fetch abort)→ 立即返回 `{ status:'aborted' }`,
|
||||
* **不再挂满 wait 秒**,也不把串码换掉; * - 到时间没动静 → 返回 `{ status:'refreshed', code }` 换一张新码;
|
||||
* - `wait=0`(默认)时不挂起,只返回 `{ status:'pending' }`。
|
||||
*
|
||||
* @param {string} code 串码
|
||||
* @param {object} options { wait 挂起秒数, withToken 是否顺手签发用户 JWT(设备端登录时为 false,
|
||||
* 由调用方自己签发长期令牌,见 app/controller/device.js)}
|
||||
* @return {Promise<{status:string, user?:object, token?:string, code?:string, waited?:number}>}
|
||||
*/
|
||||
async awaitLogin(code, { wait = 0, withToken = true } = {}) {
|
||||
if (!this.redis || !code) {
|
||||
return { status: 'refreshed', code: await this.newCode() };
|
||||
}
|
||||
|
||||
const maxWait = Number(this.cfg.pollWait || 25);
|
||||
const seconds = Math.min(Math.max(Number(wait) || 0, 0), maxWait);
|
||||
const channel = this.channel(code);
|
||||
|
||||
// 先订阅、再查状态:这样「查的时候还是 pending、随后立刻被确认」的那一下不会漏掉
|
||||
const subscriber = seconds > 0 ? this.subscriber() : null;
|
||||
if (subscriber) await subscriber.subscribe(channel);
|
||||
|
||||
// 客户端断开的信号:页面导航(切回账号密码登录)或前端 abort 时立刻结束等待
|
||||
const closed = seconds > 0 ? this.clientClosed() : null;
|
||||
|
||||
try {
|
||||
const login = await this.takeLogin(code, withToken);
|
||||
if (login) return Object.assign({ status: 'confirmed' }, login);
|
||||
|
||||
if (!(await this.isPending(code))) {
|
||||
return { status: 'refreshed', code: await this.newCode() };
|
||||
}
|
||||
if (!seconds) return { status: 'pending' };
|
||||
|
||||
const hit = await this.waitPublish(subscriber, seconds * 1000, closed);
|
||||
if (hit === 'closed') {
|
||||
this.ctx.logger.info('[wechat] 客户端已断开,停止等待串码 %s', code);
|
||||
return { status: 'aborted' };
|
||||
}
|
||||
if (hit) {
|
||||
const after = await this.takeLogin(code, withToken);
|
||||
if (after) return Object.assign({ status: 'confirmed' }, after);
|
||||
}
|
||||
// 到时间还没人扫 → 直接给新码,让前端换二维码
|
||||
this.ctx.logger.info('[wechat] 串码 %s 等待 %ss 无变化,换新码', code, seconds);
|
||||
return { status: 'refreshed', code: await this.newCode(), waited: seconds };
|
||||
} finally {
|
||||
if (subscriber) subscriber.disconnect();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 取走确认结果(`withToken=false` 时只给用户,不签用户 JWT)
|
||||
* 设备端扫码登录用它取用户,再自己签发**长期**扫描器令牌
|
||||
* @param {string} code 串码
|
||||
* @param {boolean} withToken 是否顺手签发用户 JWT
|
||||
* @return {Promise<{user:object, token?:string, tokenType?:string, expiresIn?:string}|null>}
|
||||
*/
|
||||
async takeLogin(code, withToken = true) {
|
||||
if (withToken) return this.takeConfirmedWithToken(code);
|
||||
|
||||
const user = await this.takeConfirmed(code);
|
||||
return user ? { user } : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 取走确认结果,顺手签发用户 JWT(写 session / 返回前端都用这一份)
|
||||
* @param {string} code 串码
|
||||
* @return {Promise<{user:object, token:string, tokenType:string, expiresIn:string}|null>}
|
||||
*/
|
||||
async takeConfirmedWithToken(code) {
|
||||
const user = await this.takeConfirmed(code);
|
||||
if (!user) return null;
|
||||
return {
|
||||
user,
|
||||
token: this.ctx.service.jwt.signUser(user),
|
||||
tokenType: 'Bearer',
|
||||
expiresIn: this.app.config.jwt.userExpiresIn,
|
||||
};
|
||||
}
|
||||
|
||||
/** 确认登录后广播一次(长轮询的请求靠它立即醒来) */
|
||||
async notify(code) {
|
||||
if (!this.redis) return;
|
||||
try {
|
||||
await this.redis.publish(this.channel(code), 'confirmed');
|
||||
} catch (err) {
|
||||
this.ctx.logger.warn('[wechat] 广播确认失败: %s', err.message);
|
||||
}
|
||||
}
|
||||
|
||||
/** 订阅用的独立连接(duplicate 出来的,用完即 disconnect) */
|
||||
subscriber() {
|
||||
const redis = this.app.redis;
|
||||
return typeof redis.duplicate === 'function' ? redis.duplicate() : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 客户端断开(页面导航 / fetch abort)时 resolve `'closed'` 的 promise,拿不到底层连接时返回 null
|
||||
* 用途:长轮询没人在等了就别再挂满 wait 秒(也避免白换一张新码)
|
||||
*/
|
||||
clientClosed() {
|
||||
const res = this.ctx && this.ctx.res;
|
||||
if (!res || typeof res.on !== 'function') return null;
|
||||
|
||||
return new Promise(resolve => {
|
||||
const onClose = () => {
|
||||
res.removeListener('close', onClose);
|
||||
// 响应正常写完后 close 也会触发,那种不算断开
|
||||
if (!res.writableEnded) resolve('closed');
|
||||
};
|
||||
res.on('close', onClose);
|
||||
});
|
||||
}
|
||||
|
||||
/** 等一条消息(或超时返回 null;`closed` 提前 resolve 就返回 'closed') */
|
||||
waitPublish(subscriber, waitMs, closed) {
|
||||
const wait = new Promise(resolve => {
|
||||
if (!subscriber) return setTimeout(() => resolve(null), waitMs);
|
||||
let done = false;
|
||||
const finish = (value) => {
|
||||
if (done) return;
|
||||
done = true;
|
||||
clearTimeout(timer);
|
||||
resolve(value);
|
||||
};
|
||||
const timer = setTimeout(() => finish(null), waitMs);
|
||||
subscriber.on('message', () => finish('confirmed'));
|
||||
});
|
||||
|
||||
return closed ? Promise.race([ wait, closed ]) : wait;
|
||||
}
|
||||
|
||||
/** 读串码当前的值:'pending' / 用户 id / null(不存在或已过期) */
|
||||
async valueOf(code) {
|
||||
if (!this.redis || !code) return null;
|
||||
try {
|
||||
return await this.redis.get(this.stateKey(code));
|
||||
} catch (err) {
|
||||
this.ctx.logger.warn('[wechat] 读取串码失败: %s', err.message);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 确认登录(把「谁登录」写进 Redis 等电脑端取走)
|
||||
* @param {string} code 串码
|
||||
* @param {number} userId 确认者的用户 id(调用方保证已登录)
|
||||
* @return {Promise<{ok:boolean, reason?:string, message?:string}>}
|
||||
* reason: no_redis(Redis 不可用)/ bad_param(参数不全)/ expired(码不存在或已过期)/ used(已经被用过)
|
||||
*/
|
||||
async confirm(code, userId) {
|
||||
if (!this.redis) return { ok: false, reason: 'no_redis', message: '服务暂时不可用,请稍后再试' };
|
||||
if (!code || !userId) return { ok: false, reason: 'bad_param', message: '参数不完整' };
|
||||
|
||||
const value = await this.valueOf(code);
|
||||
if (!value) return { ok: false, reason: 'expired', message: '登录码已失效,请刷新后重新扫码' };
|
||||
if (value !== 'pending') return { ok: false, reason: 'used', message: '该登录码已经用过了' };
|
||||
|
||||
await this.redis.setex(this.stateKey(code), this.stateTtl, String(userId));
|
||||
await this.notify(code); // 写完立刻广播:正在长轮询的请求马上就能返回
|
||||
this.ctx.logger.info('[wechat] 扫码确认登录: code=%s userId=%s', code, userId);
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
/**
|
||||
* 串码当前状态(给小程序/前端查询用,无副作用)
|
||||
* @param {string} code 串码
|
||||
* @return {Promise<{status:string, expiresIn:number}>}
|
||||
* pending(待扫码)/ confirmed(已被确认,等电脑端取走)/ expired(不存在或已过期)
|
||||
*/
|
||||
async statusOf(code) {
|
||||
const value = await this.valueOf(code);
|
||||
if (!value) return { status: 'expired', expiresIn: 0 };
|
||||
return {
|
||||
status: value === 'pending' ? 'pending' : 'confirmed',
|
||||
expiresIn: await this.ttlOf(code),
|
||||
};
|
||||
}
|
||||
|
||||
/** 串码剩余有效期(秒),取不到返回 0 */
|
||||
async ttlOf(code) {
|
||||
if (!this.redis || !code) return 0;
|
||||
try {
|
||||
const ttl = Number(await this.redis.ttl(this.stateKey(code)));
|
||||
return ttl > 0 ? ttl : 0;
|
||||
} catch (err) {
|
||||
this.ctx.logger.warn('[wechat] 读取串码有效期失败: %s', err.message);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 本地把内容画成二维码 SVG(零依赖库,不请求外部服务)
|
||||
* ⚠️ qrcode-generator 的 margin 参数单位是**像素**(不是格),所以这里把「格」换算成像素:
|
||||
* 默认 4 格静默区(QR 规范要求 ≥ 4 格,不够会影响扫码识别率)。
|
||||
* @param {string} content 编码内容
|
||||
* @return {string} SVG 源码
|
||||
*/
|
||||
qrSvg(content) {
|
||||
const cellSize = this.cfg.qrCellSize;
|
||||
const qr = qrcode(0, 'M'); // 版本自动、纠错等级 M
|
||||
qr.addData(String(content));
|
||||
qr.make();
|
||||
return qr.createSvgTag({
|
||||
cellSize,
|
||||
margin: this.cfg.qrMargin * cellSize,
|
||||
scalable: true,
|
||||
});
|
||||
}
|
||||
|
||||
/** 用 code 换 openid(只有配好 appid/secret 才会走到这里) */
|
||||
async exchangeCode(code) {
|
||||
const apiBase = String(this.cfg.apiBase || 'https://api.weixin.qq.com').replace(/\/+$/, '');
|
||||
const res = await this.ctx.curl(`${apiBase}/sns/oauth2/access_token`, {
|
||||
method: 'GET',
|
||||
data: {
|
||||
appid: this.cfg.appid,
|
||||
secret: this.cfg.secret,
|
||||
code,
|
||||
grant_type: 'authorization_code',
|
||||
},
|
||||
dataType: 'json',
|
||||
timeout: 5000,
|
||||
});
|
||||
const data = res.data || {};
|
||||
if (data.errcode) {
|
||||
this.ctx.logger.warn('[wechat] 换 openid 失败: %s %s', data.errcode, data.errmsg);
|
||||
return { ok: false, message: `微信返回错误(${data.errcode}):${data.errmsg || '未知'}` };
|
||||
}
|
||||
if (!data.openid) {
|
||||
this.ctx.logger.warn('[wechat] 微信未返回 openid: %j', data);
|
||||
return { ok: false, message: '微信未返回 openid,请重试' };
|
||||
}
|
||||
return { ok: true, openid: data.openid, unionid: data.unionid || null };
|
||||
}
|
||||
|
||||
/**
|
||||
* 扫码后微信授权回来的处理(在**扫码那台设备**上执行):串码存在 → 换 openid → 找已绑定账号 →
|
||||
* 把「已确认的用户 id」写进 Redis(key 就是串码),等电脑端登录页轮询取走。
|
||||
* @param {string} code 微信回传的 code(换 openid 用)
|
||||
* @param {string} state 微信回传的 state(= 本次扫码的 6 位串码)
|
||||
* @return {Promise<{ok:boolean, message?:string, user?:object}>}
|
||||
*/
|
||||
async login(code, state) {
|
||||
if (!this.enabled) {
|
||||
return { ok: false, message: '服务端未配置微信登录(WECHAT_APPID / WECHAT_SECRET)' };
|
||||
}
|
||||
if (!state || !this.redis) {
|
||||
return { ok: false, message: '登录状态已失效,请重新扫码' };
|
||||
}
|
||||
|
||||
let pending;
|
||||
try {
|
||||
pending = await this.redis.get(this.stateKey(state));
|
||||
} catch (err) {
|
||||
this.ctx.logger.error('[wechat] 读取扫码状态失败: %s', err.message);
|
||||
return { ok: false, message: '服务暂时不可用,请稍后再试' };
|
||||
}
|
||||
if (!pending) return { ok: false, message: '二维码已过期,请重新扫码' };
|
||||
if (!code) return { ok: false, message: '微信未回传 code,请重新扫码' };
|
||||
|
||||
const exchanged = await this.exchangeCode(code);
|
||||
if (!exchanged.ok) return exchanged;
|
||||
|
||||
const user = await this.ctx.service.user.findByOpenid(this.cfg.appid, exchanged.openid);
|
||||
if (!user) {
|
||||
this.ctx.logger.info('[wechat] openid 未绑定任何账号: %s', exchanged.openid);
|
||||
return { ok: false, message: '这个微信还没绑定账号,请先用账号密码登录,绑定微信后再扫码' };
|
||||
}
|
||||
if (Number(user.status) !== 1) {
|
||||
return { ok: false, message: '账号已被禁用,请联系管理员' };
|
||||
}
|
||||
|
||||
await this.redis.setex(this.stateKey(state), this.stateTtl, String(user.id));
|
||||
await this.notify(state); // 长轮询的请求靠这条广播立即醒来
|
||||
this.ctx.logger.info('[wechat] 扫码确认成功: %s (id=%s)', user.username, user.id);
|
||||
return { ok: true, user };
|
||||
}
|
||||
|
||||
/** state 有效期(秒):与二维码有效期一致 */
|
||||
get stateTtl() {
|
||||
return Number(this.cfg.stateTtl || 600);
|
||||
}
|
||||
|
||||
/** 登记一个待扫码的 state(桌面端渲染二维码时调用,重复调用只是刷新有效期) */
|
||||
async openState(state) {
|
||||
if (!this.redis) return;
|
||||
try {
|
||||
await this.redis.setex(this.stateKey(state), this.stateTtl, 'pending');
|
||||
} catch (err) {
|
||||
this.ctx.logger.warn('[wechat] 登记扫码状态失败: %s', err.message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 取走已确认的登录(桌面端轮询时调用)
|
||||
* @return {Promise<object|null>} 已确认的用户,未确认/已过期返回 null
|
||||
*/
|
||||
async takeConfirmed(state) {
|
||||
if (!this.redis || !state) return null;
|
||||
let value;
|
||||
try {
|
||||
value = await this.redis.get(this.stateKey(state));
|
||||
} catch (err) {
|
||||
this.ctx.logger.warn('[wechat] 查询扫码状态失败: %s', err.message);
|
||||
return null;
|
||||
}
|
||||
if (!value || value === 'pending') return null;
|
||||
|
||||
await this.redis.del(this.stateKey(state)); // 一次性,用完即失效
|
||||
return this.ctx.service.user.findById(Number(value));
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = WechatLoginService;
|
||||
206
backend/config/config.default.js
Normal file
206
backend/config/config.default.js
Normal file
@ -0,0 +1,206 @@
|
||||
'use strict';
|
||||
|
||||
const path = require('path');
|
||||
|
||||
const { env } = process;
|
||||
|
||||
/**
|
||||
* 默认配置(所有环境生效),按环境差异请放到 config.{env}.js 覆盖
|
||||
* @param {Egg.EggAppInfo} appInfo app 信息
|
||||
*/
|
||||
module.exports = (appInfo) => {
|
||||
const config = (exports = {});
|
||||
|
||||
// cookie/session 签名用的 key,生产环境请改成随机字符串
|
||||
config.keys = `${appInfo.name}_1729000000000_1971`;
|
||||
|
||||
// ==================== 站点/产品名 ====================
|
||||
// 页标题、品牌位、邮件正文都用它 —— **改名字只改这里**(或设环境变量 SITE_NAME)
|
||||
config.siteName = env.SITE_NAME || '云仓视频溯源系统';
|
||||
|
||||
// 中间件(app/middleware/xxx.js 后写 'xxx')
|
||||
// errorHandler:接口异常统一返回 JSON
|
||||
// frontend:**后端不渲染页面** —— 开发时把页面请求反代给前端 dev server,生产时托管前端构建产物
|
||||
config.middleware = [ 'errorHandler', 'frontend' ];
|
||||
|
||||
// ==================== 前端入口(页面不在后端渲染) ====================
|
||||
// 开发(env=local):页面请求(非 /api、/health)反代到前端 dev server(frontend/ 里 npm run dev)
|
||||
// 生产:直接托管前端构建产物 dist(SPA 深链回退到 index.html)
|
||||
// 联调时只开一个地址:打开 http://127.0.0.1:7001 就是前端页面
|
||||
config.frontend = {
|
||||
enable: !/^(0|false|no|off)$/i.test(String(env.FRONTEND_ENABLE || 'true')),
|
||||
devServer: env.FRONTEND_DEV_SERVER || 'http://127.0.0.1:7301',
|
||||
distDir: env.FRONTEND_DIST || path.join(appInfo.baseDir, '../frontend/dist'),
|
||||
};
|
||||
|
||||
// ==================== 运维/内部接口鉴权 ====================
|
||||
// 对应 app/middleware/internal_auth.js:
|
||||
// - token:给运维脚本 / 后台系统用(header `X-Internal-Token`);**不配则一律不认**
|
||||
// - adminIds:允许访问内部接口的账号 id(user JWT 的 sub),默认 [1](内置管理员)
|
||||
config.internal = {
|
||||
token: env.INTERNAL_TOKEN || '',
|
||||
adminIds: String(env.INTERNAL_ADMIN_IDS || '1')
|
||||
.split(',')
|
||||
.map(value => Number(value.trim()))
|
||||
.filter(id => Number.isInteger(id) && id > 0),
|
||||
};
|
||||
|
||||
// ==================== 服务端口 ====================
|
||||
// 本地默认 7001;“专用测试端口”用 `npm run dev:test`(egg-bin dev --port 7300)
|
||||
// 也可临时覆盖:PORT=7300 npm run dev(PowerShell:$env:PORT=7300; npm run dev)
|
||||
config.cluster = {
|
||||
listen: {
|
||||
port: Number(env.PORT || 7001),
|
||||
},
|
||||
};
|
||||
|
||||
// 多实例并存时用 LOG_DIR 把日志分到不同目录
|
||||
// (具体生效位置见文件末尾:这里先不设,避开下面的 config.logger 赋值)
|
||||
|
||||
// ==================== 安全 ====================
|
||||
// 前端是 SPA + **header 令牌**,后端没有任何基于 cookie/session 的表单:
|
||||
// CSRF 保护(只对 cookie 会话有意义)整个关掉,登录响应里那个多余的 csrfToken cookie 也随之消失。
|
||||
config.security = {
|
||||
csrf: {
|
||||
enable: false,
|
||||
},
|
||||
};
|
||||
|
||||
// ==================== MySQL ====================
|
||||
// ==================== MySQL(Sequelize ORM) ====================
|
||||
// 模型定义在 app/model/ 下,通过 app.model.User / ctx.model.User 访问
|
||||
config.sequelize = {
|
||||
dialect: 'mysql',
|
||||
host: env.MYSQL_HOST || '127.0.0.1',
|
||||
port: Number(env.MYSQL_PORT || 3307),
|
||||
// 注意:账号名大小写敏感,必须是 packservice
|
||||
username: env.MYSQL_USER || 'packservice',
|
||||
// 密码不要写在这里,放 config.local.js 或环境变量 MYSQL_PASSWORD
|
||||
password: env.MYSQL_PASSWORD || '',
|
||||
database: env.MYSQL_DATABASE || 'packservice',
|
||||
// 固定时区,避免服务器时区不同导致时间偏移
|
||||
timezone: '+08:00',
|
||||
charset: 'utf8mb4',
|
||||
define: {
|
||||
// 表名用单数形式(不自动加 s)
|
||||
freezeTableName: true,
|
||||
// 驼峰属性映射到下划线字段
|
||||
underscored: true,
|
||||
createdAt: 'created_at',
|
||||
updatedAt: 'updated_at',
|
||||
},
|
||||
pool: {
|
||||
max: Number(env.MYSQL_POOL_SIZE || 10),
|
||||
min: 0,
|
||||
acquire: 30000,
|
||||
idle: 10000,
|
||||
},
|
||||
// 需要打印 SQL 时改成 console.log(或自定义 logger)
|
||||
logging: false,
|
||||
// 只读从库 / 多数据源可改用 datasources 配置
|
||||
};
|
||||
|
||||
// ==================== Redis ====================
|
||||
config.redis = {
|
||||
client: {
|
||||
host: env.REDIS_HOST || '127.0.0.1',
|
||||
port: Number(env.REDIS_PORT || 6379),
|
||||
// 无密码必须显式写 null
|
||||
password: env.REDIS_PASSWORD || null,
|
||||
db: Number(env.REDIS_DB || 0),
|
||||
// 弱依赖:Redis 仅作缓存时,启动不阻塞
|
||||
weakDependent: true,
|
||||
},
|
||||
};
|
||||
|
||||
// ==================== JWT(扫描器长期令牌) ====================
|
||||
// 扫描器注册/登录时下发长期 JWT,后续调用本服务时带 Authorization: Bearer <token>
|
||||
config.jwt = {
|
||||
// 签名密钥:生产环境必须用环境变量 JWT_SECRET 注入(未设置时下面直接抛错)
|
||||
secret: env.JWT_SECRET || 'pack-service-dev-secret-please-change',
|
||||
issuer: 'pack-service',
|
||||
audience: 'scanner',
|
||||
// 扫描器令牌有效期(长期),支持 '365d' / '10y' / 秒数
|
||||
scannerExpiresIn: env.SCANNER_JWT_EXPIRES || '365d',
|
||||
// 设备扫码登录(GET /api/device/login)下发令牌的**默认时长,同时也是上限**:
|
||||
// 设备可以用 ?expiresIn=30d 申请更短的,但不能比它长(要整体放宽就改这个)
|
||||
deviceExpiresIn: env.DEVICE_JWT_EXPIRES || env.SCANNER_JWT_EXPIRES || '365d',
|
||||
// 用户令牌有效期(扫码登录 / 前端接口用的 JWT)
|
||||
userExpiresIn: env.USER_JWT_EXPIRES || '7d',
|
||||
};
|
||||
|
||||
if (!env.JWT_SECRET && appInfo.env === 'prod') {
|
||||
throw new Error('[config] 生产环境必须通过环境变量 JWT_SECRET 指定 JWT 签名密钥');
|
||||
}
|
||||
|
||||
// ==================== 业务配置 ====================
|
||||
config.cache = {
|
||||
// 缓存 key 前缀,多项目共用一个 Redis 时用来隔离
|
||||
prefix: env.CACHE_PREFIX || 'packs:',
|
||||
// 默认过期时间(秒)
|
||||
ttl: Number(env.CACHE_TTL || 300),
|
||||
};
|
||||
|
||||
// 登录页的自助注册(生产环境建议关掉:REGISTER_ENABLED=false,改用 npm run user:pass 建号)
|
||||
config.register = {
|
||||
enable: !/^(0|false|no|off)$/i.test(String(env.REGISTER_ENABLED || 'true')),
|
||||
};
|
||||
|
||||
// ==================== 邮件 / 邮箱验证码(注册时需要验证邮箱) ====================
|
||||
config.email = {
|
||||
// 未配置 SMTP_HOST 时走开发模式:验证码写日志并在注册页回显(仅本地/测试用)
|
||||
devMode: !env.SMTP_HOST,
|
||||
// 发件人显示名用站点名(邮箱域名保持 pack-service.local,技术标识不动)
|
||||
from: env.SMTP_FROM || `${config.siteName} <no-reply@pack-service.local>`,
|
||||
smtp: {
|
||||
host: env.SMTP_HOST || null,
|
||||
port: Number(env.SMTP_PORT || 465),
|
||||
secure: String(env.SMTP_SECURE || 'true') !== 'false',
|
||||
user: env.SMTP_USER || null,
|
||||
password: env.SMTP_PASSWORD || null,
|
||||
},
|
||||
// 验证码有效期(秒)/ 重发间隔(秒)/ 同一个验证码最多试几次
|
||||
codeTtl: Number(env.EMAIL_CODE_TTL || 600),
|
||||
resendInterval: Number(env.EMAIL_CODE_RESEND || 60),
|
||||
maxAttempts: Number(env.EMAIL_CODE_ATTEMPTS || 5),
|
||||
// 重置密码链接有效期(秒,默认 30 分钟)
|
||||
resetTtl: Number(env.EMAIL_RESET_TTL || 1800),
|
||||
// 邮件里链接用的站点地址(不配就用请求里的 host)
|
||||
siteUrl: env.SITE_URL || '',
|
||||
};
|
||||
|
||||
// ==================== 微信扫码登录(登录页右上角三角形切换) ====================
|
||||
config.wechat = {
|
||||
// 微信开放平台「网站应用」的 appid / secret;不配则二维码退化为本地演示码
|
||||
appid: env.WECHAT_APPID || '',
|
||||
secret: env.WECHAT_SECRET || '',
|
||||
// 扫码回调地址(不配就按当前请求的 origin 自动拼 /login/wechat/callback)
|
||||
redirectUri: env.WECHAT_REDIRECT_URI || '',
|
||||
// 微信接口地址(默认官方;自建网关/联调时可改,如 http://127.0.0.1:7099)
|
||||
apiBase: env.WECHAT_API_BASE || 'https://api.weixin.qq.com',
|
||||
// 扫码串码:长度、二维码内容里的 spm 格式(`{code}` 占位)
|
||||
codeLength: Number(env.WECHAT_CODE_LENGTH || 6),
|
||||
spmPattern: env.WECHAT_SPM_PATTERN || '1.0.{code}.1',
|
||||
// 二维码(本地生成 SVG,不引用任何第三方图片):单元格像素、静默区格数(QR 规范建议 ≥ 4)
|
||||
qrCellSize: Number(env.WECHAT_QR_CELL || 6),
|
||||
qrMargin: Number(env.WECHAT_QR_MARGIN || 4),
|
||||
// 扫码状态(二维码)有效期(秒)
|
||||
stateTtl: Number(env.WECHAT_STATE_TTL || 600),
|
||||
// 长轮询最长挂起秒数(默认 60s;前端建议再留一点自己的超时,比如 +10s)
|
||||
pollWait: Number(env.WECHAT_POLL_WAIT || 60),
|
||||
};
|
||||
|
||||
// 日志(生产建议按需调整)
|
||||
config.logger = {
|
||||
consoleLevel: 'INFO',
|
||||
};
|
||||
|
||||
// 多实例并存时用 LOG_DIR 把日志分到不同目录,免得到处翻同一个日志文件
|
||||
// 例(PowerShell):$env:LOG_DIR='logs-test'; npm run dev:test
|
||||
// ⚠️ 必须写在上面 config.logger 赋值之后,否则会被整个覆盖掉
|
||||
if (env.LOG_DIR) {
|
||||
config.logger.dir = path.resolve(appInfo.baseDir, env.LOG_DIR);
|
||||
}
|
||||
|
||||
return config;
|
||||
};
|
||||
13
backend/config/config.unittest.js
Normal file
13
backend/config/config.unittest.js
Normal file
@ -0,0 +1,13 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 单测专用配置
|
||||
*
|
||||
* 只给内部接口放一个固定的运维令牌(`X-Internal-Token`),省得每个用例都去签 JWT;
|
||||
* 真实环境请用环境变量 `INTERNAL_TOKEN` 注入,**不要用这个值**。
|
||||
*/
|
||||
module.exports = {
|
||||
internal: {
|
||||
token: 'test-internal-token',
|
||||
},
|
||||
};
|
||||
15
backend/config/plugin.js
Normal file
15
backend/config/plugin.js
Normal file
@ -0,0 +1,15 @@
|
||||
'use strict';
|
||||
|
||||
/** 插件开关 */
|
||||
module.exports = {
|
||||
// MySQL(通过 Sequelize ORM 访问)
|
||||
sequelize: {
|
||||
enable: true,
|
||||
package: 'egg-sequelize',
|
||||
},
|
||||
// Redis(缓存 / 登录码 / 长轮询发布订阅)
|
||||
redis: {
|
||||
enable: true,
|
||||
package: 'egg-redis',
|
||||
},
|
||||
};
|
||||
19
backend/config/plugin.unittest.js
Normal file
19
backend/config/plugin.unittest.js
Normal file
@ -0,0 +1,19 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 单元测试环境不加载数据库插件:
|
||||
* - sequelize 插件启用时会在 beforeStart 里 authenticate(),本机没起 MySQL 会导致启动失败
|
||||
* - redis 插件同理
|
||||
*
|
||||
* 测试里用 mock(app, 'model', fakeModel) / mock(app, 'redis', fakeRedis) 注入假实现,
|
||||
* 所以 npm test 不需要本机启动 MySQL / Redis。
|
||||
* 需要连真实数据库的集成测试时,复制一个 config/plugin.integration.js 把插件打开即可。
|
||||
*/
|
||||
module.exports = {
|
||||
sequelize: {
|
||||
enable: false,
|
||||
},
|
||||
redis: {
|
||||
enable: false,
|
||||
},
|
||||
};
|
||||
5
backend/jsconfig.json
Normal file
5
backend/jsconfig.json
Normal file
@ -0,0 +1,5 @@
|
||||
{
|
||||
"include": [
|
||||
"**/*"
|
||||
]
|
||||
}
|
||||
10162
backend/package-lock.json
generated
Normal file
10162
backend/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
41
backend/package.json
Normal file
41
backend/package.json
Normal file
@ -0,0 +1,41 @@
|
||||
{
|
||||
"name": "pack-service",
|
||||
"version": "1.0.0",
|
||||
"description": "Egg.js 接口服务(MySQL + Redis)",
|
||||
"private": true,
|
||||
"egg": {
|
||||
"declarations": true
|
||||
},
|
||||
"dependencies": {
|
||||
"bcryptjs": "^3.0.3",
|
||||
"egg": "^3.34.0",
|
||||
"egg-redis": "^2.6.1",
|
||||
"egg-scripts": "^3.1.0",
|
||||
"egg-sequelize": "^6.0.0",
|
||||
"http-proxy": "^1.18.1",
|
||||
"jsonwebtoken": "^9.0.3",
|
||||
"koa-static": "^5.0.0",
|
||||
"mysql2": "^3.24.6",
|
||||
"nodemailer": "^10.1.2",
|
||||
"qrcode-generator": "^2.0.4",
|
||||
"sequelize": "^6.37.8"
|
||||
},
|
||||
"devDependencies": {
|
||||
"egg-bin": "^6.13.0",
|
||||
"egg-mock": "^5.15.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18.0.0"
|
||||
},
|
||||
"scripts": {
|
||||
"start": "egg-scripts start --daemon --title=egg-server-pack-service",
|
||||
"stop": "egg-scripts stop --title=egg-server-pack-service",
|
||||
"dev": "egg-bin dev",
|
||||
"dev:test": "egg-bin dev --port 7300",
|
||||
"debug": "egg-bin debug",
|
||||
"test": "egg-bin test",
|
||||
"cov": "egg-bin cov",
|
||||
"db:init": "node scripts/init-db.js",
|
||||
"user:pass": "node scripts/set-password.js"
|
||||
}
|
||||
}
|
||||
33
backend/scripts/db-config.js
Normal file
33
backend/scripts/db-config.js
Normal file
@ -0,0 +1,33 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 脚本共用的数据库连接信息解析:
|
||||
* 环境变量 > config/config.local.js(已 gitignore)> 内置默认值
|
||||
*/
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
const { env } = process;
|
||||
|
||||
module.exports = function resolveDbConfig() {
|
||||
const config = {
|
||||
host: env.MYSQL_HOST || '127.0.0.1',
|
||||
port: Number(env.MYSQL_PORT || 3307),
|
||||
user: env.MYSQL_USER || 'packservice',
|
||||
password: env.MYSQL_PASSWORD || '',
|
||||
database: env.MYSQL_DATABASE || 'packservice',
|
||||
multipleStatements: true,
|
||||
};
|
||||
|
||||
const localPath = path.join(__dirname, '..', 'config', 'config.local.js');
|
||||
if (fs.existsSync(localPath)) {
|
||||
const { sequelize = {} } = require(localPath);
|
||||
if (sequelize.host) config.host = sequelize.host;
|
||||
if (sequelize.port) config.port = sequelize.port;
|
||||
if (sequelize.username) config.user = sequelize.username;
|
||||
if (sequelize.password !== undefined) config.password = sequelize.password;
|
||||
if (sequelize.database) config.database = sequelize.database;
|
||||
}
|
||||
return config;
|
||||
};
|
||||
54
backend/scripts/init-db.js
Normal file
54
backend/scripts/init-db.js
Normal file
@ -0,0 +1,54 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 执行 sql/schema.sql 建表(本机没装 mysql 客户端时用它)
|
||||
*
|
||||
* 用法:
|
||||
* npm run db:init # 执行 sql/schema.sql
|
||||
* node scripts/init-db.js sql/xxx.sql # 执行指定 SQL 文件
|
||||
*
|
||||
* 连接信息来源:环境变量 > config/config.local.js > 内置默认值
|
||||
*/
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const mysql = require('mysql2/promise');
|
||||
|
||||
// 数据库连接信息统一在 scripts/db-config.js 里解析
|
||||
// (环境变量 > config/config.local.js > 默认值)
|
||||
const resolveDbConfig = require('./db-config');
|
||||
|
||||
/** 去掉 -- 行注释,再按分号切分成可逐条执行的语句 */
|
||||
function splitStatements(sql) {
|
||||
return sql
|
||||
.split(/\r?\n/)
|
||||
.filter((line) => !line.trim().startsWith('--'))
|
||||
.join('\n')
|
||||
.split(';')
|
||||
.map((stmt) => stmt.trim())
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const file = process.argv[2] || path.join(__dirname, '..', 'sql', 'schema.sql');
|
||||
const config = resolveDbConfig();
|
||||
const statements = splitStatements(fs.readFileSync(file, 'utf8'));
|
||||
|
||||
console.log(`[db:init] 连接 ${config.host}:${config.port}/${config.database} as ${config.user}`);
|
||||
const conn = await mysql.createConnection(config);
|
||||
try {
|
||||
for (const stmt of statements) {
|
||||
console.log(`[db:init] 执行: ${stmt.split('\n')[0].slice(0, 70)} ...`);
|
||||
await conn.query(stmt);
|
||||
}
|
||||
const [tables] = await conn.query('SHOW TABLES');
|
||||
console.log('[db:init] 完成,当前表: %s', tables.map((t) => Object.values(t)[0]).join(', ') || '(空)');
|
||||
} finally {
|
||||
await conn.end();
|
||||
}
|
||||
}
|
||||
|
||||
main().catch((err) => {
|
||||
console.error(`[db:init] 失败: ${err.code || ''} ${err.message}`);
|
||||
process.exit(1);
|
||||
});
|
||||
64
backend/scripts/set-password.js
Normal file
64
backend/scripts/set-password.js
Normal file
@ -0,0 +1,64 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 创建用户 / 重置登录密码(本机没装 mysql 客户端也能用)
|
||||
*
|
||||
* 用法:
|
||||
* npm run user:pass -- <账号> <密码> [昵称]
|
||||
* node scripts/set-password.js admin 123456 管理员
|
||||
*
|
||||
* 账号不存在时自动创建(username = 账号,status = 1);
|
||||
* 账号存在时只重置密码。密码经 bcrypt 哈希后写入 users.password_hash。
|
||||
*/
|
||||
|
||||
const mysql = require('mysql2/promise');
|
||||
const bcrypt = require('bcryptjs');
|
||||
const resolveDbConfig = require('./db-config');
|
||||
|
||||
/** 与 app/service/auth.js 的 BCRYPT_ROUNDS 保持一致 */
|
||||
const BCRYPT_ROUNDS = 10;
|
||||
|
||||
function usage() {
|
||||
console.log('用法: npm run user:pass -- <账号> <密码> [昵称]');
|
||||
console.log('示例: npm run user:pass -- admin 123456 管理员');
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const [ account, password, nickname ] = process.argv.slice(2);
|
||||
if (!account || !password) {
|
||||
usage();
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const hash = await bcrypt.hash(String(password), BCRYPT_ROUNDS);
|
||||
const config = resolveDbConfig();
|
||||
const conn = await mysql.createConnection(config);
|
||||
|
||||
try {
|
||||
const [rows] = await conn.query(
|
||||
'select id, username, phone, email from users where (username = ? or phone = ? or email = ?) and deleted_at is null limit 1',
|
||||
[ account, account, account ],
|
||||
);
|
||||
|
||||
if (rows.length) {
|
||||
const user = rows[0];
|
||||
await conn.query('update users set password_hash = ?, updated_at = now() where id = ?', [ hash, user.id ]);
|
||||
console.log(`[user:pass] 已重置密码: ${user.username || user.phone || user.email} (id=${user.id})`);
|
||||
} else {
|
||||
const [result] = await conn.query(
|
||||
'insert into users (username, nickname, password_hash, status) values (?, ?, ?, 1)',
|
||||
[ account, nickname || account, hash ],
|
||||
);
|
||||
console.log(`[user:pass] 已创建用户: ${account} (id=${result.insertId}),昵称: ${nickname || account}`);
|
||||
}
|
||||
|
||||
console.log(`[user:pass] 连接: ${config.host}:${config.port}/${config.database} as ${config.user}`);
|
||||
} finally {
|
||||
await conn.end();
|
||||
}
|
||||
}
|
||||
|
||||
main().catch((err) => {
|
||||
console.error(`[user:pass] 失败: ${err.code || ''} ${err.message}`);
|
||||
process.exit(1);
|
||||
});
|
||||
10
backend/sql/migrations/20261016_add_user_email.sql
Normal file
10
backend/sql/migrations/20261016_add_user_email.sql
Normal file
@ -0,0 +1,10 @@
|
||||
-- users 表增加邮箱字段(可选,唯一;登录时邮箱可作为账号,注册时可选填)
|
||||
--
|
||||
-- ⚠️ 只需执行一次:MySQL 8 不支持 ADD COLUMN IF NOT EXISTS,重复执行会报 Duplicate column name。
|
||||
-- 执行:npm run db:init sql/migrations/20261016_add_user_email.sql
|
||||
|
||||
ALTER TABLE `users`
|
||||
ADD COLUMN `email` VARCHAR(128) DEFAULT NULL COMMENT '邮箱(可选,可作登录账号)' AFTER `nickname`;
|
||||
|
||||
ALTER TABLE `users`
|
||||
ADD UNIQUE KEY `uk_email` (`email`);
|
||||
7
backend/sql/migrations/20261016_add_user_password.sql
Normal file
7
backend/sql/migrations/20261016_add_user_password.sql
Normal file
@ -0,0 +1,7 @@
|
||||
-- users 表增加登录密码字段(bcrypt 哈希)
|
||||
--
|
||||
-- ⚠️ 只需执行一次:MySQL 8 不支持 ADD COLUMN IF NOT EXISTS,重复执行会报 Duplicate column name。
|
||||
-- 执行:npm run db:init sql/migrations/20261016_add_user_password.sql
|
||||
|
||||
ALTER TABLE `users`
|
||||
ADD COLUMN `password_hash` VARCHAR(100) DEFAULT NULL COMMENT '密码哈希(bcrypt),登录用' AFTER `phone`;
|
||||
8
backend/sql/migrations/20261016_devices_to_scanners.sql
Normal file
8
backend/sql/migrations/20261016_devices_to_scanners.sql
Normal file
@ -0,0 +1,8 @@
|
||||
-- 从「设备(devices)」重命名为「扫描器(scanners)」,
|
||||
-- 并把扫描器令牌改为长期 JWT(库里只存 jti,不存令牌本体)。
|
||||
--
|
||||
-- ⚠️ 只需执行一次:直接删掉上一版的 devices 表(当时只有演示数据)。
|
||||
-- 新表由 sql/schema.sql 的 CREATE TABLE `scanners` 建立(含 token_jti / last_seen_at)。
|
||||
-- 执行:npm run db:init sql/migrations/20261016_devices_to_scanners.sql
|
||||
|
||||
DROP TABLE IF EXISTS `devices`;
|
||||
7
backend/sql/migrations/20261016_rebuild_users.sql
Normal file
7
backend/sql/migrations/20261016_rebuild_users.sql
Normal file
@ -0,0 +1,7 @@
|
||||
-- 重建 users 表:旧的 demo 表(id/name/email/age)已废弃,
|
||||
-- 新结构见 sql/schema.sql(BIGINT 主键 + 软删除 + 状态)。
|
||||
--
|
||||
-- ⚠️ 会删除 users 表及其数据,只执行一次(当前表内只有示例数据)。
|
||||
-- 执行:npm run db:init sql/migrations/20261016_rebuild_users.sql
|
||||
|
||||
DROP TABLE IF EXISTS `users`;
|
||||
191
backend/sql/schema.sql
Normal file
191
backend/sql/schema.sql
Normal file
@ -0,0 +1,191 @@
|
||||
-- packservice 库初始化脚本(幂等,可重复执行)
|
||||
--
|
||||
-- 前提:数据库 `packservice` 已存在(账号 packservice 只有该库的权限,无法建库)。
|
||||
-- 若需新建库,请用有权限的账号执行:
|
||||
-- CREATE DATABASE IF NOT EXISTS `packservice`
|
||||
-- DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;
|
||||
--
|
||||
-- 执行方式:
|
||||
-- npm run db:init
|
||||
-- mysql -h127.0.0.1 -P3307 -upackservice -p packservice < sql/schema.sql
|
||||
--
|
||||
-- ⚠️ 历史变更(旧库需要按顺序补跑一次迁移):
|
||||
-- 1. users 表结构重建(旧的 demo 表只有 id/name/email/age)
|
||||
-- npm run db:init sql/migrations/20261016_rebuild_users.sql
|
||||
-- 2. users 表增加登录密码字段
|
||||
-- npm run db:init sql/migrations/20261016_add_user_password.sql
|
||||
--
|
||||
-- 通用约定:BIGINT UNSIGNED 自增主键 + created_at/updated_at + deleted_at(软删除) + status
|
||||
|
||||
USE `packservice`;
|
||||
|
||||
-- ---------------------------------------------------------------
|
||||
-- 用户表
|
||||
-- ---------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS `users` (
|
||||
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键',
|
||||
`username` VARCHAR(64) DEFAULT NULL COMMENT '登录名(可空,纯微信登录用户可不设)',
|
||||
`nickname` VARCHAR(64) NOT NULL DEFAULT '' COMMENT '昵称',
|
||||
`email` VARCHAR(128) DEFAULT NULL COMMENT '邮箱(可选,可作登录账号)',
|
||||
`avatar` VARCHAR(255) NOT NULL DEFAULT '' COMMENT '头像地址',
|
||||
`phone` VARCHAR(20) DEFAULT NULL COMMENT '手机号',
|
||||
`password_hash` VARCHAR(100) DEFAULT NULL COMMENT '密码哈希(bcrypt),登录用',
|
||||
`gender` TINYINT UNSIGNED NOT NULL DEFAULT 0 COMMENT '性别:0未知 1男 2女',
|
||||
`status` TINYINT UNSIGNED NOT NULL DEFAULT 1 COMMENT '状态:1正常 0禁用',
|
||||
`remark` VARCHAR(255) DEFAULT NULL COMMENT '备注',
|
||||
`last_login_at` DATETIME DEFAULT NULL COMMENT '最近登录时间',
|
||||
`created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||
`updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
`deleted_at` DATETIME DEFAULT NULL COMMENT '软删除时间',
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uk_username` (`username`),
|
||||
UNIQUE KEY `uk_phone` (`phone`),
|
||||
UNIQUE KEY `uk_email` (`email`),
|
||||
KEY `idx_status` (`status`),
|
||||
KEY `idx_created_at` (`created_at`)
|
||||
) ENGINE = InnoDB
|
||||
DEFAULT CHARSET = utf8mb4
|
||||
COMMENT = '用户表';
|
||||
|
||||
-- ---------------------------------------------------------------
|
||||
-- 微信授权表:一条记录 = 某用户在某 appid 下的一次授权
|
||||
-- 一个用户可绑定多个微信(公众号 / 小程序 / 开放平台)
|
||||
-- ---------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS `wechat_oauth` (
|
||||
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键',
|
||||
`user_id` BIGINT UNSIGNED NOT NULL COMMENT '关联 users.id',
|
||||
`appid` VARCHAR(64) NOT NULL COMMENT '微信 appid',
|
||||
`openid` VARCHAR(64) NOT NULL COMMENT '用户在该 appid 下的 openid',
|
||||
`unionid` VARCHAR(64) DEFAULT NULL COMMENT '开放平台 unionid',
|
||||
`nickname` VARCHAR(64) NOT NULL DEFAULT '' COMMENT '授权时微信昵称',
|
||||
`avatar` VARCHAR(255) NOT NULL DEFAULT '' COMMENT '授权时微信头像',
|
||||
`session_key` VARCHAR(128) DEFAULT NULL COMMENT '小程序 session_key',
|
||||
`access_token` VARCHAR(512) DEFAULT NULL COMMENT '网页授权 access_token',
|
||||
`refresh_token` VARCHAR(512) DEFAULT NULL COMMENT '刷新令牌',
|
||||
`scope` VARCHAR(64) DEFAULT NULL COMMENT '授权 scope',
|
||||
`token_expires_at` DATETIME DEFAULT NULL COMMENT 'access_token 过期时间',
|
||||
`last_auth_at` DATETIME DEFAULT NULL COMMENT '最近授权时间',
|
||||
`created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||
`updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
`deleted_at` DATETIME DEFAULT NULL COMMENT '软删除时间',
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uk_appid_openid` (`appid`, `openid`),
|
||||
KEY `idx_user_id` (`user_id`),
|
||||
KEY `idx_unionid` (`unionid`)
|
||||
) ENGINE = InnoDB
|
||||
DEFAULT CHARSET = utf8mb4
|
||||
COMMENT = '微信授权表';
|
||||
|
||||
-- ---------------------------------------------------------------
|
||||
-- 系统配置表:group_name + config_key 唯一定位一条配置
|
||||
-- 注意:唯一性由 service 层保证(先查后写),这里只建普通索引 ——
|
||||
-- 本表用 deleted_at 软删除,唯一索引会被已删除的记录占用,导致同 key 无法重建。
|
||||
-- ---------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS `sys_config` (
|
||||
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键',
|
||||
`group_name` VARCHAR(64) NOT NULL DEFAULT 'default' COMMENT '分组',
|
||||
`config_key` VARCHAR(128) NOT NULL COMMENT '配置键',
|
||||
`config_value` TEXT COMMENT '配置值',
|
||||
`value_type` VARCHAR(16) NOT NULL DEFAULT 'string' COMMENT 'string/number/boolean/json',
|
||||
`remark` VARCHAR(255) DEFAULT NULL COMMENT '备注',
|
||||
`status` TINYINT UNSIGNED NOT NULL DEFAULT 1 COMMENT '状态:1启用 0禁用',
|
||||
`created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||
`updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
`deleted_at` DATETIME DEFAULT NULL COMMENT '软删除时间',
|
||||
PRIMARY KEY (`id`),
|
||||
KEY `idx_group_key` (`group_name`, `config_key`),
|
||||
KEY `idx_group` (`group_name`)
|
||||
) ENGINE = InnoDB
|
||||
DEFAULT CHARSET = utf8mb4
|
||||
COMMENT = '系统配置表';
|
||||
|
||||
-- ---------------------------------------------------------------
|
||||
-- 扫描器表:扫描器(条码/二维码)端登录后注册到服务,并与账号绑定(user_id 为空 = 未绑定)
|
||||
-- ---------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS `scanners` (
|
||||
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键',
|
||||
`user_id` BIGINT UNSIGNED DEFAULT NULL COMMENT '绑定的用户 id,未绑定为 NULL',
|
||||
`sn` VARCHAR(64) NOT NULL COMMENT '扫描器 SN(唯一标识)',
|
||||
`name` VARCHAR(64) NOT NULL DEFAULT '' COMMENT '名称 / 别名',
|
||||
`vendor` VARCHAR(64) DEFAULT NULL COMMENT '厂商',
|
||||
`model` VARCHAR(64) DEFAULT NULL COMMENT '型号',
|
||||
`firmware` VARCHAR(32) DEFAULT NULL COMMENT '固件 / 客户端版本',
|
||||
`ip` VARCHAR(45) DEFAULT NULL COMMENT '最近登录 IP',
|
||||
`secret_hash` VARCHAR(100) DEFAULT NULL COMMENT '扫描器密钥哈希(bcrypt),扫描器端登录用',
|
||||
`token_jti` VARCHAR(64) DEFAULT NULL COMMENT '当前 JWT 的 jti(重签即失效旧令牌)',
|
||||
`token_expires_at` DATETIME DEFAULT NULL COMMENT '令牌过期时间',
|
||||
`status` TINYINT UNSIGNED NOT NULL DEFAULT 1 COMMENT '状态:1正常 0禁用',
|
||||
`last_register_at` DATETIME DEFAULT NULL COMMENT '最近注册时间',
|
||||
`last_login_at` DATETIME DEFAULT NULL COMMENT '最近登录时间',
|
||||
`last_seen_at` DATETIME DEFAULT NULL COMMENT '最近心跳时间',
|
||||
`created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||
`updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
`deleted_at` DATETIME DEFAULT NULL COMMENT '软删除时间',
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uk_sn` (`sn`),
|
||||
UNIQUE KEY `uk_token_jti` (`token_jti`),
|
||||
KEY `idx_user_id` (`user_id`),
|
||||
KEY `idx_status` (`status`)
|
||||
) ENGINE = InnoDB
|
||||
DEFAULT CHARSET = utf8mb4
|
||||
COMMENT = '扫描器表';
|
||||
|
||||
-- ---------------------------------------------------------------
|
||||
-- 扫描中控通道表:中控(绑定端)上报的通道,一个通道一行
|
||||
-- 一台中控可接多个扫码设备,每个扫码设备对应一个通道(channel_id + channel_name)
|
||||
-- channel_id 只在同一中控内唯一,所以唯一键是 (scanner_id, channel_id)
|
||||
-- ---------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS `scan_channels` (
|
||||
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键',
|
||||
`scanner_id` BIGINT UNSIGNED NOT NULL COMMENT '上报的中控(= scanners.id)',
|
||||
`channel_id` VARCHAR(64) NOT NULL COMMENT '通道 id(中控上报,同一中控内唯一)',
|
||||
`channel_name` VARCHAR(128) NOT NULL DEFAULT '' COMMENT '通道名(中控上报)',
|
||||
`last_report_at` DATETIME DEFAULT NULL COMMENT '最近一次上报时间',
|
||||
`status` TINYINT UNSIGNED NOT NULL DEFAULT 1 COMMENT '状态:1正常 0停用',
|
||||
`remark` VARCHAR(255) DEFAULT NULL COMMENT '备注',
|
||||
`created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||
`updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
`deleted_at` DATETIME DEFAULT NULL COMMENT '软删除时间',
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uk_scanner_channel` (`scanner_id`, `channel_id`),
|
||||
KEY `idx_channel_id` (`channel_id`),
|
||||
KEY `idx_status` (`status`)
|
||||
) ENGINE = InnoDB
|
||||
DEFAULT CHARSET = utf8mb4
|
||||
COMMENT = '扫描中控通道表';
|
||||
|
||||
-- ---------------------------------------------------------------
|
||||
-- 扫码记录表:中控上报的扫码流水(条码 + 扫描时间 + 通道)
|
||||
-- 去重:唯一键 (scanner_id, channel_id, barcode, scan_time) ——
|
||||
-- 同一中控 + 同一通道 + 同一时间 + 同一条码 的重复上报只入库一次(幂等重试安全)。
|
||||
-- 时间精确到秒;重复上报不会报错,接口返回 duplicated 计数。
|
||||
-- 说明:本表是流水表,不用软删除(软删除会占用唯一键,导致同一条记录无法再入库);
|
||||
-- 需要清理请按时间物理删除(DELETE ... WHERE scan_time < ?)。
|
||||
-- ---------------------------------------------------------------
|
||||
CREATE TABLE IF NOT EXISTS `scan_records` (
|
||||
`id` BIGINT UNSIGNED NOT NULL AUTO_INCREMENT COMMENT '主键',
|
||||
`scanner_id` BIGINT UNSIGNED NOT NULL COMMENT '上报的中控(= scanners.id)',
|
||||
`channel_id` VARCHAR(64) NOT NULL COMMENT '通道 id',
|
||||
`barcode` VARCHAR(255) NOT NULL COMMENT '条码内容',
|
||||
`scan_time` DATETIME NOT NULL COMMENT '扫描时间(中控上报,秒级)',
|
||||
`reported_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '服务端接收时间',
|
||||
`created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||
`updated_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||
PRIMARY KEY (`id`),
|
||||
UNIQUE KEY `uk_scan_dedup` (`scanner_id`, `channel_id`, `barcode`, `scan_time`),
|
||||
KEY `idx_scan_time` (`scan_time`),
|
||||
KEY `idx_barcode` (`barcode`),
|
||||
KEY `idx_channel_scan_time` (`channel_id`, `scan_time`)
|
||||
) ENGINE = InnoDB
|
||||
DEFAULT CHARSET = utf8mb4
|
||||
COMMENT = '扫码记录表(同 中控+通道+条码+扫描时间 去重)';
|
||||
|
||||
-- ---------------------------------------------------------------
|
||||
-- 初始化配置(可选)
|
||||
-- ---------------------------------------------------------------
|
||||
INSERT INTO `sys_config` (`group_name`, `config_key`, `config_value`, `value_type`, `remark`)
|
||||
SELECT 'wechat', 'default_appid', '', 'string', '默认微信 appid'
|
||||
FROM DUAL
|
||||
WHERE NOT EXISTS (
|
||||
SELECT 1 FROM `sys_config` WHERE `group_name` = 'wechat' AND `config_key` = 'default_appid' AND `deleted_at` IS NULL
|
||||
);
|
||||
206
backend/test/app/controller/config.test.js
Normal file
206
backend/test/app/controller/config.test.js
Normal file
@ -0,0 +1,206 @@
|
||||
'use strict';
|
||||
|
||||
const { app, mock, assert } = require('egg-mock/bootstrap');
|
||||
const createFakeRedis = require('../../utils/fake-redis');
|
||||
const { HEADER: INTERNAL } = require('../../utils/internal');
|
||||
|
||||
/** 系统配置属「内部接口」:请求都带上运维令牌 */
|
||||
const http = {
|
||||
get: url => app.httpRequest().get(url).set(INTERNAL),
|
||||
post: url => app.httpRequest().post(url).set(INTERNAL),
|
||||
put: url => app.httpRequest().put(url).set(INTERNAL),
|
||||
delete: url => app.httpRequest().delete(url).set(INTERNAL),
|
||||
};
|
||||
|
||||
const instance = (data) => Object.assign({}, data, {
|
||||
toJSON: () => data,
|
||||
update: async (fields) => Object.assign(data, fields),
|
||||
});
|
||||
|
||||
describe('test/app/controller/config.test.js', () => {
|
||||
let fakeRedis;
|
||||
|
||||
beforeEach(() => {
|
||||
fakeRedis = createFakeRedis();
|
||||
mock(app, 'redis', fakeRedis.client);
|
||||
});
|
||||
|
||||
it('GET /api/configs/:group/:key 读配置并写缓存', async () => {
|
||||
let queries = 0;
|
||||
mock(app, 'model', {
|
||||
SysConfig: {
|
||||
async findOne() {
|
||||
queries++;
|
||||
return instance({ groupName: 'wechat', configKey: 'appid', configValue: 'wx123', valueType: 'string' });
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const res = await http.get('/api/configs/wechat/appid').expect(200);
|
||||
assert(res.body.data.value === 'wx123');
|
||||
assert(queries === 1);
|
||||
assert(fakeRedis.store.get('packs:config:wechat:appid'), '应写入缓存');
|
||||
|
||||
// 第二次读命中缓存
|
||||
await http.get('/api/configs/wechat/appid').expect(200);
|
||||
assert(queries === 1);
|
||||
});
|
||||
|
||||
it('value_type 为 json / number / boolean 时自动转换类型', async () => {
|
||||
const rows = {
|
||||
json: { configValue: '{"a":1}', valueType: 'json' },
|
||||
number: { configValue: '42', valueType: 'number' },
|
||||
boolean: { configValue: 'true', valueType: 'boolean' },
|
||||
};
|
||||
mock(app, 'model', {
|
||||
SysConfig: {
|
||||
async findOne(options) {
|
||||
const key = options.where.configKey;
|
||||
return instance(Object.assign({ groupName: 'g', configKey: key }, rows[key]));
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const json = await http.get('/api/configs/g/json').expect(200);
|
||||
assert.deepStrictEqual(json.body.data.value, { a: 1 });
|
||||
|
||||
const number = await http.get('/api/configs/g/number').expect(200);
|
||||
assert.strictEqual(number.body.data.value, 42);
|
||||
|
||||
const boolean = await http.get('/api/configs/g/boolean').expect(200);
|
||||
assert.strictEqual(boolean.body.data.value, true);
|
||||
});
|
||||
|
||||
it('GET /api/configs/:group/:key 不存在(或已禁用)返回 404', async () => {
|
||||
mock(app, 'model', {
|
||||
SysConfig: {
|
||||
async findOne() {
|
||||
return null;
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
await http.get('/api/configs/wechat/none').expect(404);
|
||||
});
|
||||
|
||||
it('GET /api/configs/:group 返回分组内启用的配置', async () => {
|
||||
mock(app, 'model', {
|
||||
SysConfig: {
|
||||
async findAll() {
|
||||
return [
|
||||
instance({ configKey: 'appid', configValue: 'wx123', valueType: 'string' }),
|
||||
instance({ configKey: 'secret', configValue: 's1', valueType: 'string' }),
|
||||
];
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const res = await http.get('/api/configs/wechat').expect(200);
|
||||
assert.deepStrictEqual(res.body.data, { appid: 'wx123', secret: 's1' });
|
||||
});
|
||||
|
||||
it('PUT /api/configs 新建配置', async () => {
|
||||
mock(app, 'model', {
|
||||
SysConfig: {
|
||||
async findOne() {
|
||||
return null;
|
||||
},
|
||||
async create(data) {
|
||||
assert(data.groupName === 'wechat');
|
||||
assert(data.configKey === 'secret');
|
||||
assert(data.configValue === 's1');
|
||||
return instance(Object.assign({ id: 3 }, data));
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const res = await http
|
||||
.put('/api/configs')
|
||||
.send({ groupName: 'wechat', configKey: 'secret', configValue: 's1' })
|
||||
.expect(200);
|
||||
|
||||
assert(res.body.data.id === 3);
|
||||
});
|
||||
|
||||
it('PUT /api/configs 更新已有配置并清掉缓存', async () => {
|
||||
// 先读一次建立缓存
|
||||
mock(app, 'model', {
|
||||
SysConfig: {
|
||||
async findOne() {
|
||||
return instance({ id: 3, groupName: 'wechat', configKey: 'appid', configValue: 'old', valueType: 'string' });
|
||||
},
|
||||
},
|
||||
});
|
||||
await http.get('/api/configs/wechat/appid').expect(200);
|
||||
assert(fakeRedis.store.has('packs:config:wechat:appid'));
|
||||
|
||||
// 再更新
|
||||
mock(app, 'model', {
|
||||
SysConfig: {
|
||||
async findOne() {
|
||||
return instance({
|
||||
id: 3,
|
||||
groupName: 'wechat',
|
||||
configKey: 'appid',
|
||||
configValue: 'old',
|
||||
valueType: 'string',
|
||||
});
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const res = await http
|
||||
.put('/api/configs')
|
||||
.send({ groupName: 'wechat', configKey: 'appid', configValue: 'new' })
|
||||
.expect(200);
|
||||
|
||||
assert(res.body.data.configValue === 'new');
|
||||
assert(!fakeRedis.store.has('packs:config:wechat:appid'), '写入后应清除缓存');
|
||||
});
|
||||
|
||||
it('PUT /api/configs 缺少 configKey 返回 422', async () => {
|
||||
await http.put('/api/configs').send({ groupName: 'wechat' }).expect(422);
|
||||
});
|
||||
|
||||
it('GET /api/configs 列表(管理用)', async () => {
|
||||
mock(app, 'model', {
|
||||
SysConfig: {
|
||||
async findAll(options) {
|
||||
assert(options.where.groupName === 'wechat');
|
||||
return [ instance({ groupName: 'wechat', configKey: 'appid', configValue: 'wx123' }) ];
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const res = await http.get('/api/configs?group=wechat').expect(200);
|
||||
assert(res.body.data.total === 1);
|
||||
});
|
||||
|
||||
it('DELETE /api/configs/:group/:key 软删除并清缓存', async () => {
|
||||
fakeRedis.store.set('packs:config:wechat:appid', '{}');
|
||||
|
||||
mock(app, 'model', {
|
||||
SysConfig: {
|
||||
async destroy(options) {
|
||||
assert.deepStrictEqual(options.where, { groupName: 'wechat', configKey: 'appid' });
|
||||
return 1;
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
await http.delete('/api/configs/wechat/appid').expect(200);
|
||||
assert(!fakeRedis.store.has('packs:config:wechat:appid'));
|
||||
});
|
||||
|
||||
it('DELETE /api/configs/:group/:key 配置不存在返回 404', async () => {
|
||||
mock(app, 'model', {
|
||||
SysConfig: {
|
||||
async destroy() {
|
||||
return 0;
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
await http.delete('/api/configs/wechat/none').expect(404);
|
||||
});
|
||||
});
|
||||
389
backend/test/app/controller/device.test.js
Normal file
389
backend/test/app/controller/device.test.js
Normal file
@ -0,0 +1,389 @@
|
||||
'use strict';
|
||||
|
||||
const { app, mock, assert } = require('egg-mock/bootstrap');
|
||||
const http = require('http');
|
||||
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));
|
||||
});
|
||||
});
|
||||
51
backend/test/app/controller/health.test.js
Normal file
51
backend/test/app/controller/health.test.js
Normal file
@ -0,0 +1,51 @@
|
||||
'use strict';
|
||||
|
||||
const { app, mock } = require('egg-mock/bootstrap');
|
||||
const createFakeRedis = require('../../utils/fake-redis');
|
||||
|
||||
describe('test/app/controller/health.test.js', () => {
|
||||
beforeEach(() => {
|
||||
mock(app, 'redis', createFakeRedis().client);
|
||||
});
|
||||
|
||||
it('MySQL 与 Redis 正常时返回 200', async () => {
|
||||
mock(app, 'model', {
|
||||
async authenticate() {
|
||||
return true;
|
||||
},
|
||||
});
|
||||
|
||||
const res = await app.httpRequest().get('/health').expect(200);
|
||||
if (res.body.ok !== true) throw new Error('health 应为 ok');
|
||||
if (res.body.dependencies.mysql.ok !== true) throw new Error('mysql 应可用');
|
||||
if (res.body.dependencies.redis.ok !== true) throw new Error('redis 应可用');
|
||||
});
|
||||
|
||||
it('MySQL 不可用时返回 503', async () => {
|
||||
mock(app, 'model', {
|
||||
async authenticate() {
|
||||
throw new Error("Access denied for user 'packservice'@'localhost'");
|
||||
},
|
||||
});
|
||||
|
||||
const res = await app.httpRequest().get('/health').expect(503);
|
||||
if (res.body.dependencies.mysql.ok !== false) throw new Error('mysql 应标记为不可用');
|
||||
});
|
||||
|
||||
it('Redis 不可用时返回 503', async () => {
|
||||
mock(app, 'model', {
|
||||
async authenticate() {
|
||||
return true;
|
||||
},
|
||||
});
|
||||
mock(app, 'redis', {
|
||||
async ping() {
|
||||
throw new Error('NOAUTH Authentication required.');
|
||||
},
|
||||
});
|
||||
|
||||
const res = await app.httpRequest().get('/health').expect(503);
|
||||
if (res.body.ok !== false) throw new Error('health 应为 ok:false');
|
||||
if (res.body.dependencies.redis.ok !== false) throw new Error('redis 应标记为不可用');
|
||||
});
|
||||
});
|
||||
11
backend/test/app/controller/home.test.js
Normal file
11
backend/test/app/controller/home.test.js
Normal file
@ -0,0 +1,11 @@
|
||||
'use strict';
|
||||
|
||||
const { app, assert } = require('egg-mock/bootstrap');
|
||||
|
||||
describe('test/app/controller/home.test.js', () => {
|
||||
it('GET /api/info 返回服务信息', async () => {
|
||||
const res = await app.httpRequest().get('/api/info').expect(200);
|
||||
assert(res.body.ok === true);
|
||||
assert(typeof res.body.env === 'string');
|
||||
});
|
||||
});
|
||||
73
backend/test/app/controller/internal.test.js
Normal file
73
backend/test/app/controller/internal.test.js
Normal file
@ -0,0 +1,73 @@
|
||||
'use strict';
|
||||
|
||||
const { app, mock, assert } = require('egg-mock/bootstrap');
|
||||
const { HEADER: INTERNAL } = require('../../utils/internal');
|
||||
|
||||
const instance = (data) => Object.assign({ toJSON: () => data }, data);
|
||||
|
||||
/**
|
||||
* 内部(运维)接口的鉴权:`config.internal`
|
||||
*
|
||||
* 允许两种方式:运维令牌(`X-Internal-Token`)或**管理员账号**的 user JWT(userId 在白名单里)。
|
||||
* 用户端接口(`/api/web/*`)与这里完全隔离:普通用户令牌调内部接口一律 403,设备令牌一律 401。
|
||||
*/
|
||||
describe('test/app/controller/internal.test.js', () => {
|
||||
const user = { id: 1, username: 'admin', nickname: '管理员', status: 1 };
|
||||
|
||||
const signUser = id => `Bearer ${app.createAnonymousContext().service.jwt.signUser({ id, username: `u${id}` })}`;
|
||||
|
||||
it('运维令牌(X-Internal-Token)可直接访问内部接口', async () => {
|
||||
mock(app, 'model', {
|
||||
SysConfig: {
|
||||
async findAll() { return [ instance({ configKey: 'appid', configValue: 'wx123' }) ]; },
|
||||
},
|
||||
});
|
||||
|
||||
const res = await app.httpRequest().get('/api/configs?group=wechat').set(INTERNAL).expect(200);
|
||||
assert(res.body.data.total === 1, JSON.stringify(res.body));
|
||||
});
|
||||
|
||||
it('管理员账号的 user JWT 也能访问(白名单 INTERNAL_ADMIN_IDS,默认 [1])', async () => {
|
||||
mock(app, 'model', {
|
||||
User: {
|
||||
async findByPk() { return instance(user); },
|
||||
async findAndCountAll() { return { rows: [ instance(user) ], count: 1 }; },
|
||||
},
|
||||
});
|
||||
|
||||
const res = await app.httpRequest().get('/api/users').set('Authorization', signUser(1)).expect(200);
|
||||
assert(res.body.data.total === 1, JSON.stringify(res.body));
|
||||
});
|
||||
|
||||
it('没令牌 → 401;普通用户令牌 → 403;设备令牌 → 401', async () => {
|
||||
mock(app, 'model', {
|
||||
User: { async findByPk() { return instance({ id: 2, status: 1, username: 'other' }); } },
|
||||
});
|
||||
|
||||
const res = await app.httpRequest().get('/api/users').expect(401);
|
||||
assert(res.body.status === 'unauthorized' && res.body.ok === false, JSON.stringify(res.body));
|
||||
|
||||
await app.httpRequest().get('/api/users').set('Authorization', signUser(2)).expect(403);
|
||||
|
||||
// 设备令牌(typ=scanner)不是用户令牌 → 401
|
||||
const deviceToken = app.createAnonymousContext().service.jwt.signScanner({ id: 11, sn: 'SN-1' }, { jti: 'j-1' });
|
||||
await app.httpRequest().get('/api/users').set('Authorization', `Bearer ${deviceToken}`).expect(401);
|
||||
});
|
||||
|
||||
it('内部令牌配错 / 为空时一律不认(fail closed)', async () => {
|
||||
mock(app, 'model', {
|
||||
User: { async findByPk() { return instance(user); } },
|
||||
});
|
||||
|
||||
await app.httpRequest().get('/api/users').set('x-internal-token', 'wrong-token').expect(401);
|
||||
|
||||
// 规则:config.internal.token 为空串时,任何 token 都不通过(这里临时改配置验证)
|
||||
const original = app.config.internal.token;
|
||||
app.config.internal.token = '';
|
||||
try {
|
||||
await app.httpRequest().get('/api/users').set(INTERNAL).expect(401);
|
||||
} finally {
|
||||
app.config.internal.token = original;
|
||||
}
|
||||
});
|
||||
});
|
||||
562
backend/test/app/controller/scan.test.js
Normal file
562
backend/test/app/controller/scan.test.js
Normal file
@ -0,0 +1,562 @@
|
||||
'use strict';
|
||||
|
||||
const { app, mock, assert } = require('egg-mock/bootstrap');
|
||||
const jwt = require('jsonwebtoken');
|
||||
const { Op } = require('sequelize');
|
||||
|
||||
/** 假实例:update 时把字段合并回自身 */
|
||||
const instance = (data) => Object.assign(
|
||||
{
|
||||
toJSON: () => data,
|
||||
update: async (fields) => Object.assign(data, fields),
|
||||
},
|
||||
data,
|
||||
);
|
||||
|
||||
/** 假实例:额外回调 update 的字段(多次 update 时累积) */
|
||||
const inst = (data, onUpdate) => Object.assign(
|
||||
{
|
||||
toJSON: () => data,
|
||||
update: async fields => {
|
||||
if (onUpdate) onUpdate(fields);
|
||||
Object.assign(data, fields);
|
||||
return data;
|
||||
},
|
||||
},
|
||||
data,
|
||||
);
|
||||
|
||||
/** 与服务端一致的密钥/签发者,造一个中控(扫描器)JWT */
|
||||
function signToken(payload = {}, options = {}) {
|
||||
return jwt.sign(
|
||||
Object.assign({ sub: '1', sn: 'SN-HUB-01', typ: 'scanner', jti: 'jti-1' }, payload),
|
||||
app.config.jwt.secret,
|
||||
Object.assign({
|
||||
algorithm: 'HS256',
|
||||
expiresIn: '365d',
|
||||
issuer: app.config.jwt.issuer,
|
||||
audience: app.config.jwt.audience,
|
||||
}, options),
|
||||
);
|
||||
}
|
||||
|
||||
function authScanner(overrides = {}) {
|
||||
return Object.assign({ id: 1, sn: 'SN-HUB-01', status: 1, tokenJti: 'jti-1' }, overrides);
|
||||
}
|
||||
|
||||
describe('test/app/controller/scan.test.js', () => {
|
||||
const token = () => `Bearer ${signToken()}`;
|
||||
|
||||
it('四个扫码接口都必须带 JWT:无令牌一律 401', async () => {
|
||||
await app.httpRequest().post('/api/scan/channels').send({ channels: [] }).expect(401);
|
||||
await app.httpRequest().get('/api/scan/channels').expect(401);
|
||||
await app.httpRequest().post('/api/scan/records').send({ records: [] }).expect(401);
|
||||
await app.httpRequest().get('/api/scan/records').expect(401);
|
||||
});
|
||||
|
||||
it('POST /api/scan/channels 首次上报:按 (中控, 通道 id) 建通道', async () => {
|
||||
let created = null;
|
||||
mock(app, 'model', {
|
||||
User: {},
|
||||
Scanner: { async findByPk() { return instance(authScanner()); } },
|
||||
ScanChannel: {
|
||||
async findAll() {
|
||||
return [];
|
||||
},
|
||||
async create(data) {
|
||||
created = data;
|
||||
return instance(Object.assign({ id: 9 }, data));
|
||||
},
|
||||
async update() {
|
||||
return [ 1 ];
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const res = await app.httpRequest()
|
||||
.post('/api/scan/channels')
|
||||
.set('Authorization', token())
|
||||
.send({ channels: [{ channelId: '1', channelName: '1 号打包口' }] })
|
||||
.expect(200);
|
||||
|
||||
assert(res.body.data.created === 1 && res.body.data.updated === 0 && res.body.data.invalid === 0);
|
||||
assert(created.scannerId === 1, '通道归属当前中控');
|
||||
assert(created.channelId === '1');
|
||||
assert(created.channelName === '1 号打包口');
|
||||
assert(created.lastReportAt instanceof Date, '应记录最近上报时间');
|
||||
assert(res.body.data.channels[0].channelId === '1');
|
||||
});
|
||||
|
||||
it('POST /api/scan/channels 再次上报同通道:更新通道名(不新建)', async () => {
|
||||
let args = null;
|
||||
mock(app, 'model', {
|
||||
User: {},
|
||||
Scanner: { async findByPk() { return instance(authScanner()); } },
|
||||
ScanChannel: {
|
||||
async findAll() {
|
||||
return [ instance({ id: 7, scannerId: 1, channelId: '1', channelName: '旧名字', deletedAt: null }) ];
|
||||
},
|
||||
async update(fields, options) {
|
||||
args = { fields, options };
|
||||
return [ 1 ];
|
||||
},
|
||||
async create() {
|
||||
throw new Error('不该新建通道');
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const res = await app.httpRequest()
|
||||
.post('/api/scan/channels')
|
||||
.set('Authorization', token())
|
||||
.send({ channelId: '1', channelName: '新名字' }) // 也支持单条上报
|
||||
.expect(200);
|
||||
|
||||
assert(res.body.data.updated === 1 && res.body.data.created === 0);
|
||||
assert(args.fields.channelName === '新名字');
|
||||
assert(args.fields.lastReportAt instanceof Date);
|
||||
assert(args.options.where.id === 7);
|
||||
assert(args.options.paranoid === false, '软删除的通道也要能更新');
|
||||
});
|
||||
|
||||
it('POST /api/scan/channels 曾软删除的通道会被复活(restore)', async () => {
|
||||
let restored = null;
|
||||
mock(app, 'model', {
|
||||
User: {},
|
||||
Scanner: { async findByPk() { return instance(authScanner()); } },
|
||||
ScanChannel: {
|
||||
async findAll() {
|
||||
return [ instance({ id: 3, scannerId: 1, channelId: 'CH-2', channelName: '停用过的口', deletedAt: new Date() }) ];
|
||||
},
|
||||
async restore(options) {
|
||||
restored = options;
|
||||
return 1;
|
||||
},
|
||||
async update() {
|
||||
return [ 1 ];
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const res = await app.httpRequest()
|
||||
.post('/api/scan/channels')
|
||||
.set('Authorization', token())
|
||||
.send({ channels: [{ channelId: 'CH-2', channelName: '重新启用' }] })
|
||||
.expect(200);
|
||||
|
||||
assert(res.body.data.updated === 1);
|
||||
assert(restored && restored.where.id === 3, '应先 restore 复活通道');
|
||||
});
|
||||
|
||||
it('POST /api/scan/channels 同一批里重复通道只留最后一条;非法通道计入 invalid', async () => {
|
||||
let created = null;
|
||||
let createCount = 0;
|
||||
mock(app, 'model', {
|
||||
User: {},
|
||||
Scanner: { async findByPk() { return instance(authScanner()); } },
|
||||
ScanChannel: {
|
||||
async findAll() {
|
||||
return [];
|
||||
},
|
||||
async create(data) {
|
||||
created = data;
|
||||
createCount++;
|
||||
return instance(Object.assign({ id: 10 }, data));
|
||||
},
|
||||
async update() {
|
||||
return [ 1 ];
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const res = await app.httpRequest()
|
||||
.post('/api/scan/channels')
|
||||
.set('Authorization', token())
|
||||
.send({
|
||||
channels: [
|
||||
{ channelId: '1', channelName: '第一次' },
|
||||
{ channelId: '1', channelName: '最后一次' },
|
||||
{ channelName: '没有通道 id' },
|
||||
],
|
||||
})
|
||||
.expect(200);
|
||||
|
||||
assert(createCount === 1, '同一批里同 channelId 只处理一次');
|
||||
assert(created.channelName === '最后一次', '应保留最后一次上报的名字');
|
||||
assert(res.body.data.received === 3 && res.body.data.created === 1 && res.body.data.invalid === 1);
|
||||
assert(res.body.data.errors[0].message.includes('channelId'));
|
||||
});
|
||||
|
||||
it('POST /api/scan/channels 空数组 / 缺参 → 422', async () => {
|
||||
mock(app, 'model', {
|
||||
User: {},
|
||||
Scanner: { async findByPk() { return instance(authScanner()); } },
|
||||
ScanChannel: {},
|
||||
});
|
||||
|
||||
await app.httpRequest().post('/api/scan/channels').set('Authorization', token()).send({ channels: [] }).expect(422);
|
||||
await app.httpRequest().post('/api/scan/channels').set('Authorization', token()).send({}).expect(422);
|
||||
});
|
||||
|
||||
it('POST /api/scan/records 首次上报:入库并刷新通道/心跳', async () => {
|
||||
let rows = null;
|
||||
let scannerUpdated = null;
|
||||
const scanner = inst(authScanner(), fields => { scannerUpdated = Object.assign(scannerUpdated || {}, fields); });
|
||||
let channelBulk = null;
|
||||
|
||||
mock(app, 'model', {
|
||||
User: {},
|
||||
Scanner: { async findByPk() { return scanner; } },
|
||||
ScanChannel: {
|
||||
async findAll() {
|
||||
return [ { channelId: '1' } ]; // 通道已登记
|
||||
},
|
||||
async bulkCreate(items) {
|
||||
channelBulk = 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: '6901234567890', scanTime: '2026-10-16 10:20:30', channelId: '1' }] })
|
||||
.expect(200);
|
||||
|
||||
assert(res.body.data.received === 1 && res.body.data.inserted === 1 && res.body.data.duplicated === 0);
|
||||
assert(rows[0].scannerId === 1, '记录要归属当前中控');
|
||||
assert(rows[0].channelId === '1');
|
||||
assert(rows[0].barcode === '6901234567890');
|
||||
assert(rows[0].scanTime instanceof Date && rows[0].scanTime.getMilliseconds() === 0, '扫描时间截断到秒');
|
||||
assert(rows[0].reportedAt instanceof Date, '应记录服务端接收时间');
|
||||
assert(!channelBulk, '已登记的通道不该补建');
|
||||
assert(scannerUpdated && scannerUpdated.lastSeenAt instanceof Date, '上报即视为心跳');
|
||||
});
|
||||
|
||||
it('POST /api/scan/records 时间格式:支持 13 位 / 10 位时间戳,非法时间计入 invalid', 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() { return []; },
|
||||
async bulkCreate(items) {
|
||||
rows = items;
|
||||
return items;
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const res = await app.httpRequest()
|
||||
.post('/api/scan/records')
|
||||
.set('Authorization', token())
|
||||
.send({
|
||||
records: [
|
||||
{ barcode: 'A', scanTime: 1792137600000, channelId: '1' }, // 13 位毫秒
|
||||
{ barcode: 'B', scanTime: 1792137600, channelId: '1' }, // 10 位秒
|
||||
{ barcode: 'C', scanTime: '不是时间', channelId: '1' },
|
||||
{ barcode: 'D', scanTime: '2026-10-16T10:20:30', channelId: '1' },
|
||||
],
|
||||
})
|
||||
.expect(200);
|
||||
|
||||
assert(rows.length === 3, '合法时间入库 3 条');
|
||||
assert(res.body.data.invalid === 1 && res.body.data.errors[0].message.includes('scanTime'));
|
||||
assert(rows[0].scanTime.getTime() === 1792137600000);
|
||||
assert(rows[1].scanTime.getTime() === 1792137600000);
|
||||
});
|
||||
|
||||
it('POST /api/scan/records 库里已存在 → 不入库、duplicated +1', async () => {
|
||||
let inserted = 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() {
|
||||
return [ { scannerId: 1, channelId: '1', barcode: 'X1', scanTime: new Date('2026-10-16T10:00:00') } ];
|
||||
},
|
||||
async bulkCreate() {
|
||||
inserted = true;
|
||||
return [];
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const res = await app.httpRequest()
|
||||
.post('/api/scan/records')
|
||||
.set('Authorization', token())
|
||||
.send({ records: [{ barcode: 'X1', scanTime: '2026-10-16 10:00:00', channelId: '1' }] })
|
||||
.expect(200);
|
||||
|
||||
assert(res.body.data.inserted === 0 && res.body.data.duplicated === 1);
|
||||
assert(!inserted, '完全相同的记录不应再次入库');
|
||||
});
|
||||
|
||||
it('POST /api/scan/records 同一批内重复只入库一次', 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() { return []; },
|
||||
async bulkCreate(items) {
|
||||
rows = items;
|
||||
return items;
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const res = await app.httpRequest()
|
||||
.post('/api/scan/records')
|
||||
.set('Authorization', token())
|
||||
.send({
|
||||
records: [
|
||||
{ barcode: 'A1', scanTime: '2026-10-16 10:00:00', channelId: '1' },
|
||||
{ barcode: 'A1', scanTime: '2026-10-16 10:00:00', channelId: '1' },
|
||||
],
|
||||
})
|
||||
.expect(200);
|
||||
|
||||
assert(rows.length === 1, '同批重复只留一条');
|
||||
assert(res.body.data.received === 2 && res.body.data.inserted === 1 && res.body.data.duplicated === 1);
|
||||
});
|
||||
|
||||
it('POST /api/scan/records 未知通道自动补建(通道名留空)', async () => {
|
||||
let channelRows = null;
|
||||
mock(app, 'model', {
|
||||
User: {},
|
||||
Scanner: { async findByPk() { return instance(authScanner()); } },
|
||||
ScanChannel: {
|
||||
async findAll() { return []; }, // 通道从未登记
|
||||
async bulkCreate(items) {
|
||||
channelRows = items;
|
||||
return items;
|
||||
},
|
||||
async update() { return [ 1 ]; },
|
||||
},
|
||||
ScanRecord: {
|
||||
async findAll() { return []; },
|
||||
async bulkCreate(items) { return items; },
|
||||
},
|
||||
});
|
||||
|
||||
const res = await app.httpRequest()
|
||||
.post('/api/scan/records')
|
||||
.set('Authorization', token())
|
||||
.send({ records: [{ barcode: 'B1', scanTime: '2026-10-16 11:00:00', channelId: '9' }] })
|
||||
.expect(200);
|
||||
|
||||
assert(res.body.data.unknownChannels.length === 1 && res.body.data.unknownChannels[0] === '9');
|
||||
assert(channelRows[0].channelId === '9' && channelRows[0].channelName === '');
|
||||
assert(channelRows[0].scannerId === 1);
|
||||
});
|
||||
|
||||
it('POST /api/scan/records 唯一键冲突(并发重复)→ 退化成逐条插入,重复计数', async () => {
|
||||
let createCount = 0;
|
||||
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() { return []; },
|
||||
async bulkCreate() {
|
||||
const err = new Error('Duplicate entry');
|
||||
err.name = 'SequelizeUniqueConstraintError';
|
||||
throw err;
|
||||
},
|
||||
async create() {
|
||||
createCount++;
|
||||
if (createCount === 1) {
|
||||
const err = new Error('Duplicate entry');
|
||||
err.parent = { code: 'ER_DUP_ENTRY' };
|
||||
throw err;
|
||||
}
|
||||
return {};
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const res = await app.httpRequest()
|
||||
.post('/api/scan/records')
|
||||
.set('Authorization', token())
|
||||
.send({
|
||||
records: [
|
||||
{ barcode: 'C1', scanTime: '2026-10-16 12:00:00', channelId: '1' },
|
||||
{ barcode: 'C2', scanTime: '2026-10-16 12:00:01', channelId: '1' },
|
||||
],
|
||||
})
|
||||
.expect(200);
|
||||
|
||||
assert(res.body.data.inserted === 1 && res.body.data.duplicated === 1);
|
||||
});
|
||||
|
||||
it('POST /api/scan/records 全部非法 / 空数组 → 分别返回 invalid 与 422', async () => {
|
||||
mock(app, 'model', {
|
||||
User: {},
|
||||
Scanner: { async findByPk() { return instance(authScanner()); } },
|
||||
ScanChannel: {},
|
||||
ScanRecord: {},
|
||||
});
|
||||
|
||||
const res = await app.httpRequest()
|
||||
.post('/api/scan/records')
|
||||
.set('Authorization', token())
|
||||
.send({ records: [{ channelId: '1' }] }) // 缺条码与时间
|
||||
.expect(200);
|
||||
assert(res.body.data.inserted === 0 && res.body.data.invalid === 1);
|
||||
|
||||
await app.httpRequest().post('/api/scan/records').set('Authorization', token()).send({ records: [] }).expect(422);
|
||||
});
|
||||
|
||||
it('POST /api/scan/records 支持 JSON 字符串形式的上报体', 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() { return []; },
|
||||
async bulkCreate(items) {
|
||||
rows = items;
|
||||
return items;
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
await app.httpRequest()
|
||||
.post('/api/scan/records')
|
||||
.set('Authorization', token())
|
||||
.send({ records: JSON.stringify([{ barcode: 'S1', scanTime: '2026-10-16 13:00:00', channelId: '1' }]) })
|
||||
.expect(200);
|
||||
|
||||
assert(rows.length === 1 && rows[0].barcode === 'S1');
|
||||
});
|
||||
|
||||
it('GET /api/scan/channels 只返回当前中控的通道', async () => {
|
||||
let options = null;
|
||||
mock(app, 'model', {
|
||||
User: {},
|
||||
Scanner: {
|
||||
async findByPk() { return instance(authScanner()); },
|
||||
async findAll() { return []; },
|
||||
},
|
||||
ScanChannel: {
|
||||
async findAndCountAll(opts) {
|
||||
options = opts;
|
||||
return {
|
||||
rows: [ instance({ id: 1, scannerId: 1, channelId: '1', channelName: '1 号口', scanner: { sn: 'SN-HUB-01' } }) ],
|
||||
count: 1,
|
||||
};
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const res = await app.httpRequest().get('/api/scan/channels?pageSize=5').set('Authorization', token()).expect(200);
|
||||
assert(options.where.scannerId === 1, '必须按当前中控过滤');
|
||||
assert(options.limit === 5);
|
||||
assert(res.body.data.total === 1 && res.body.data.list[0].channelName === '1 号口');
|
||||
});
|
||||
|
||||
it('GET /api/scan/records 支持通道/条码/时间过滤且只查当前中控', async () => {
|
||||
let options = null;
|
||||
mock(app, 'model', {
|
||||
User: {},
|
||||
Scanner: {
|
||||
async findByPk() { return instance(authScanner()); },
|
||||
async findAll() { return []; },
|
||||
},
|
||||
ScanRecord: {
|
||||
async findAndCountAll(opts) {
|
||||
options = opts;
|
||||
return {
|
||||
rows: [ instance({ id: 3, scannerId: 1, channelId: '1', barcode: 'B1', scanTime: new Date() }) ],
|
||||
count: 1,
|
||||
};
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const res = await app.httpRequest()
|
||||
.get('/api/scan/records?channelId=1&barcode=B1&startTime=2026-10-16&endTime=2026-10-17')
|
||||
.set('Authorization', token())
|
||||
.expect(200);
|
||||
|
||||
assert(options.where.scannerId === 1);
|
||||
assert(options.where.channelId === '1');
|
||||
assert(String(options.where.barcode[Op.like]) === '%B1%');
|
||||
assert(options.where.scanTime[Op.gte] instanceof Date && options.where.scanTime[Op.lte] instanceof Date);
|
||||
assert(options.order[0][0] === 'scanTime' && options.order[0][1] === 'DESC');
|
||||
assert(res.body.data.total === 1 && res.body.data.list[0].barcode === 'B1');
|
||||
});
|
||||
|
||||
it('被禁用的中控调用上报接口 → 403', async () => {
|
||||
mock(app, 'model', {
|
||||
User: {},
|
||||
Scanner: { async findByPk() { return instance(authScanner({ status: 0 })); } },
|
||||
ScanChannel: {},
|
||||
ScanRecord: {},
|
||||
});
|
||||
await app.httpRequest()
|
||||
.post('/api/scan/channels')
|
||||
.set('Authorization', token())
|
||||
.send({ channels: [{ channelId: '1' }] })
|
||||
.expect(403);
|
||||
});
|
||||
|
||||
it('已被轮换的旧 JWT 调上报接口 → 401(与 scanner 接口一致)', async () => {
|
||||
mock(app, 'model', {
|
||||
User: {},
|
||||
Scanner: { async findByPk() { return instance(authScanner({ tokenJti: 'new-jti' })); } },
|
||||
ScanChannel: {},
|
||||
ScanRecord: {},
|
||||
});
|
||||
|
||||
const res = await app.httpRequest()
|
||||
.post('/api/scan/records')
|
||||
.set('Authorization', token())
|
||||
.send({ records: [{ barcode: 'A', scanTime: '2026-10-16 10:00:00', channelId: '1' }] })
|
||||
.expect(401);
|
||||
assert(res.body.message.includes('已失效'));
|
||||
});
|
||||
|
||||
it('老的 sn + secret 登录入口已下线(设备统一走扫码登录)', async () => {
|
||||
const res = await app.httpRequest().post('/api/scanner/login').send({ sn: 'SN-HUB-01', secret: 'x' }).expect(404);
|
||||
assert(res.body.ok === false && res.body.message === '接口不存在', JSON.stringify(res.body));
|
||||
});
|
||||
});
|
||||
259
backend/test/app/controller/scanner.test.js
Normal file
259
backend/test/app/controller/scanner.test.js
Normal file
@ -0,0 +1,259 @@
|
||||
'use strict';
|
||||
|
||||
const { app, mock, assert } = require('egg-mock/bootstrap');
|
||||
const jwt = require('jsonwebtoken');
|
||||
const createFakeRedis = require('../../utils/fake-redis');
|
||||
const { HEADER: INTERNAL } = require('../../utils/internal');
|
||||
|
||||
/** 管理侧接口(绑定/列表/删除)要运维令牌;设备侧接口多带这个 header 也无副作用 */
|
||||
const http = {
|
||||
get: url => app.httpRequest().get(url).set(INTERNAL),
|
||||
post: url => app.httpRequest().post(url).set(INTERNAL),
|
||||
put: url => app.httpRequest().put(url).set(INTERNAL),
|
||||
delete: url => app.httpRequest().delete(url).set(INTERNAL),
|
||||
};
|
||||
|
||||
const instance = (data) => Object.assign(
|
||||
{
|
||||
toJSON: () => data,
|
||||
update: async (fields) => Object.assign(data, fields),
|
||||
},
|
||||
data,
|
||||
);
|
||||
|
||||
/** 假实例:update 时额外回调(用于断言写入的字段) */
|
||||
const inst = (data, onUpdate) => Object.assign(
|
||||
{
|
||||
toJSON: () => data,
|
||||
update: async fields => {
|
||||
if (onUpdate) onUpdate(fields);
|
||||
Object.assign(data, fields);
|
||||
return data;
|
||||
},
|
||||
},
|
||||
data,
|
||||
);
|
||||
|
||||
/** 用与服务端一致的密钥/签发者造一个扫描器 JWT */
|
||||
function signScannerToken(payload = {}, options = {}) {
|
||||
return jwt.sign(
|
||||
Object.assign({ sub: '1', sn: 'SN-001', typ: 'scanner', jti: 'jti-1' }, payload),
|
||||
app.config.jwt.secret,
|
||||
Object.assign({
|
||||
algorithm: 'HS256',
|
||||
expiresIn: '365d',
|
||||
issuer: app.config.jwt.issuer,
|
||||
audience: app.config.jwt.audience,
|
||||
}, options),
|
||||
);
|
||||
}
|
||||
|
||||
describe('test/app/controller/scanner.test.js', () => {
|
||||
beforeEach(() => {
|
||||
mock(app, 'redis', createFakeRedis().client);
|
||||
});
|
||||
|
||||
it('老的 sn + secret 注册/登录入口已下线(设备统一走扫码登录 GET /api/device/login)', async () => {
|
||||
mock(app, 'model', { User: {}, Scanner: {} });
|
||||
const reg = await http.post('/api/scanner/register').send({ sn: 'SN-001' }).expect(404);
|
||||
const login = await http.post('/api/scanner/login').send({ sn: 'SN-001', secret: 'x' }).expect(404);
|
||||
// 接口的 404 也要是 JSON(不然客户端按 JSON 解析会报错)
|
||||
assert(reg.body.ok === false && reg.body.message === '接口不存在', JSON.stringify(reg.body));
|
||||
assert(login.body.ok === false, JSON.stringify(login.body));
|
||||
});
|
||||
|
||||
it('GET /api/scanner/me 必须带 JWT:无令牌 401 / 带令牌 200', async () => {
|
||||
await http.get('/api/scanner/me').expect(401);
|
||||
|
||||
mock(app, 'model', {
|
||||
User: {},
|
||||
Scanner: {
|
||||
async findByPk(id) {
|
||||
// 鉴权阶段用 payload.sub(字符串),控制器里又按主键(数字)取一次
|
||||
assert(String(id) === '1');
|
||||
return instance({ id: 1, sn: 'SN-001', status: 1, tokenJti: 'jti-1' });
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const res = await http
|
||||
.get('/api/scanner/me')
|
||||
.set('Authorization', `Bearer ${signScannerToken()}`)
|
||||
.expect(200);
|
||||
|
||||
assert(res.body.data.sn === 'SN-001');
|
||||
assert(res.body.data.secretHash === undefined && res.body.data.tokenJti === undefined, '不应回传密钥/jti');
|
||||
});
|
||||
|
||||
it('GET /api/scanner/me JWT 失效的各种情况', async () => {
|
||||
const baseModel = {
|
||||
User: {},
|
||||
Scanner: {
|
||||
async findByPk() {
|
||||
return instance({ id: 1, sn: 'SN-001', status: 1, tokenJti: 'jti-1' });
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
// 签名不对
|
||||
mock(app, 'model', baseModel);
|
||||
const badSign = jwt.sign({ sub: '1', sn: 'SN-001', jti: 'jti-1' }, 'wrong-secret', {
|
||||
issuer: app.config.jwt.issuer, audience: app.config.jwt.audience,
|
||||
});
|
||||
await http.get('/api/scanner/me').set('Authorization', `Bearer ${badSign}`).expect(401);
|
||||
|
||||
// 已过期
|
||||
const expired = signScannerToken({}, { expiresIn: '-1s' });
|
||||
await http.get('/api/scanner/me').set('Authorization', `Bearer ${expired}`).expect(401);
|
||||
|
||||
// jti 已被轮换
|
||||
const stale = signScannerToken({ jti: 'old-jti' });
|
||||
const staleRes = await http.get('/api/scanner/me').set('Authorization', `Bearer ${stale}`).expect(401);
|
||||
assert(staleRes.body.message.includes('已失效'));
|
||||
|
||||
// 扫描器被禁用
|
||||
mock(app, 'model', {
|
||||
User: {},
|
||||
Scanner: { async findByPk() { return instance({ id: 1, sn: 'SN-001', status: 0, tokenJti: 'jti-1' }); } },
|
||||
});
|
||||
await http.get('/api/scanner/me').set('Authorization', `Bearer ${signScannerToken()}`).expect(403);
|
||||
|
||||
// 扫描器已删除
|
||||
mock(app, 'model', { User: {}, Scanner: { async findByPk() { return null; } } });
|
||||
await http.get('/api/scanner/me').set('Authorization', `Bearer ${signScannerToken()}`).expect(401);
|
||||
});
|
||||
|
||||
it('POST /api/scanner/heartbeat 用 JWT 保活并刷新心跳时间', async () => {
|
||||
let updated = null;
|
||||
mock(app, 'model', {
|
||||
User: {},
|
||||
Scanner: {
|
||||
async findByPk() {
|
||||
return inst({ id: 1, sn: 'SN-001', status: 1, tokenJti: 'jti-1' }, fields => {
|
||||
updated = fields;
|
||||
});
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const res = await http
|
||||
.post('/api/scanner/heartbeat')
|
||||
.set('Authorization', `Bearer ${signScannerToken()}`)
|
||||
.expect(200);
|
||||
|
||||
assert(res.body.data.sn === 'SN-001');
|
||||
assert(typeof res.body.data.serverTime === 'string');
|
||||
assert(updated.lastSeenAt instanceof Date, '应刷新最近心跳时间');
|
||||
});
|
||||
|
||||
it('POST /api/scanner/bind 支持 sn + username 绑定', async () => {
|
||||
let updated = null;
|
||||
mock(app, 'model', {
|
||||
User: {
|
||||
async findOne() {
|
||||
return instance({ id: 7, username: 'admin' });
|
||||
},
|
||||
},
|
||||
Scanner: {
|
||||
async findOne() {
|
||||
return inst({ id: 1, sn: 'SN-001' }, fields => {
|
||||
updated = fields;
|
||||
});
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
await http
|
||||
.post('/api/scanner/bind')
|
||||
.send({ sn: 'SN-001', username: 'admin' })
|
||||
.expect(200);
|
||||
|
||||
assert(updated.userId === 7);
|
||||
});
|
||||
|
||||
it('POST /api/scanner/bind 扫描器不存在 → 404,用户不存在 → 404', async () => {
|
||||
mock(app, 'model', {
|
||||
User: { async findOne() { return null; } },
|
||||
Scanner: { async findOne() { return null; } },
|
||||
});
|
||||
await http.post('/api/scanner/bind').send({ sn: 'X', username: 'nobody' }).expect(404);
|
||||
|
||||
mock(app, 'model', {
|
||||
User: { async findOne() { return null; } },
|
||||
Scanner: { async findOne() { return instance({ id: 1, sn: 'SN-001' }); } },
|
||||
});
|
||||
const res = await http.post('/api/scanner/bind').send({ sn: 'SN-001', username: 'nobody' }).expect(404);
|
||||
assert(res.body.message.includes('用户不存在'));
|
||||
});
|
||||
|
||||
it('POST /api/scanner/unbind 解绑(清掉归属,保留扫描器)', async () => {
|
||||
let updated = null;
|
||||
mock(app, 'model', {
|
||||
User: {},
|
||||
Scanner: {
|
||||
async findOne() {
|
||||
return inst({ id: 1, sn: 'SN-001', userId: 7 }, fields => {
|
||||
updated = fields;
|
||||
});
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
await http.post('/api/scanner/unbind').send({ sn: 'SN-001' }).expect(200);
|
||||
assert(updated.userId === null);
|
||||
});
|
||||
|
||||
it('GET /api/scanners 分页列表(带绑定账号、不含密钥与 jti)', async () => {
|
||||
mock(app, 'model', {
|
||||
User: { name: 'User' },
|
||||
Scanner: {
|
||||
async findAndCountAll(options) {
|
||||
assert(options.limit === 5);
|
||||
assert(options.offset === 5);
|
||||
assert.deepStrictEqual(options.order, [[ 'id', 'DESC' ]]);
|
||||
return {
|
||||
rows: [ instance({ id: 1, sn: 'SN-001', name: '扫描枪', user: { id: 1, nickname: '管理员' } }) ],
|
||||
count: 1,
|
||||
};
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const res = await http.get('/api/scanners?page=2&pageSize=5').expect(200);
|
||||
assert(res.body.data.total === 1);
|
||||
assert(res.body.data.page === 2);
|
||||
assert(res.body.data.list[0].sn === 'SN-001');
|
||||
assert(res.body.data.list[0].user.nickname === '管理员');
|
||||
assert(!JSON.stringify(res.body.data).includes('tokenJti'));
|
||||
});
|
||||
|
||||
it('GET /api/scanners/:id 详情 / 不存在 404 / id 非法 400', async () => {
|
||||
mock(app, 'model', {
|
||||
User: {},
|
||||
Scanner: {
|
||||
async findByPk() {
|
||||
return instance({ id: 1, sn: 'SN-001' });
|
||||
},
|
||||
},
|
||||
});
|
||||
await http.get('/api/scanners/1').expect(200);
|
||||
|
||||
mock(app, 'model', { User: {}, Scanner: { async findByPk() { return null; } } });
|
||||
await http.get('/api/scanners/1').expect(404);
|
||||
await http.get('/api/scanners/abc').expect(400);
|
||||
});
|
||||
|
||||
it('DELETE /api/scanners/:id 软删除扫描器', async () => {
|
||||
mock(app, 'model', {
|
||||
User: {},
|
||||
Scanner: {
|
||||
async destroy(options) {
|
||||
assert.deepStrictEqual(options.where, { id: 1 });
|
||||
return 1;
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
await http.delete('/api/scanners/1').expect(200);
|
||||
});
|
||||
});
|
||||
237
backend/test/app/controller/user.test.js
Normal file
237
backend/test/app/controller/user.test.js
Normal file
@ -0,0 +1,237 @@
|
||||
'use strict';
|
||||
|
||||
const { app, mock, assert } = require('egg-mock/bootstrap');
|
||||
const { Op } = require('sequelize');
|
||||
const createFakeRedis = require('../../utils/fake-redis');
|
||||
const { HEADER: INTERNAL } = require('../../utils/internal');
|
||||
|
||||
/** 用户 CRUD 属「内部接口」:请求都带上运维令牌 */
|
||||
const http = {
|
||||
get: url => app.httpRequest().get(url).set(INTERNAL),
|
||||
post: url => app.httpRequest().post(url).set(INTERNAL),
|
||||
put: url => app.httpRequest().put(url).set(INTERNAL),
|
||||
delete: url => app.httpRequest().delete(url).set(INTERNAL),
|
||||
};
|
||||
|
||||
/** 包装成「Sequelize 实例」的样子;data 里自带的 update / toJSON 优先 */
|
||||
const instance = (data) => Object.assign(
|
||||
{
|
||||
toJSON: () => data,
|
||||
update: async (fields) => Object.assign(data, fields),
|
||||
},
|
||||
data,
|
||||
);
|
||||
|
||||
describe('test/app/controller/user.test.js', () => {
|
||||
const row = { id: 1, username: 'zhangsan', nickname: '张三', phone: '13800000000', gender: 1, status: 1 };
|
||||
let fakeRedis;
|
||||
|
||||
beforeEach(() => {
|
||||
fakeRedis = createFakeRedis();
|
||||
mock(app, 'redis', fakeRedis.client);
|
||||
});
|
||||
|
||||
it('GET /api/users/:id 未命中缓存时回源数据库,并写入缓存', async () => {
|
||||
let queries = 0;
|
||||
mock(app, 'model', {
|
||||
User: {
|
||||
async findByPk(id) {
|
||||
queries++;
|
||||
assert(id === 1);
|
||||
return instance(row);
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const res = await http.get('/api/users/1').expect(200);
|
||||
assert(res.body.data.nickname === '张三');
|
||||
assert(queries === 1);
|
||||
assert(fakeRedis.store.get('packs:user:1'), '详情应写入缓存');
|
||||
|
||||
// 第二次请求命中缓存,不再回源数据库
|
||||
await http.get('/api/users/1').expect(200);
|
||||
assert(queries === 1);
|
||||
});
|
||||
|
||||
it('Redis 不可用时详情接口降级回源数据库,不报错', async () => {
|
||||
mock(app, 'redis', {
|
||||
async get() {
|
||||
throw new Error('connect ECONNREFUSED 127.0.0.1:6379');
|
||||
},
|
||||
async setex() {
|
||||
throw new Error('connect ECONNREFUSED 127.0.0.1:6379');
|
||||
},
|
||||
});
|
||||
mock(app, 'model', {
|
||||
User: {
|
||||
async findByPk() {
|
||||
return instance(row);
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const res = await http.get('/api/users/1').expect(200);
|
||||
assert(res.body.data.nickname === '张三');
|
||||
});
|
||||
|
||||
it('GET /api/users/:id 用户不存在时返回 404', async () => {
|
||||
mock(app, 'model', {
|
||||
User: {
|
||||
async findByPk() {
|
||||
return null;
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
await http.get('/api/users/99').expect(404);
|
||||
});
|
||||
|
||||
it('GET /api/users/:id id 非法时返回 400 且不查库', async () => {
|
||||
mock(app, 'model', {
|
||||
User: {
|
||||
async findByPk() {
|
||||
assert.fail('id 非法时不应该访问数据库');
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
await http.get('/api/users/abc').expect(400);
|
||||
});
|
||||
|
||||
it('GET /api/users 支持 keyword + status 过滤与分页', async () => {
|
||||
mock(app, 'model', {
|
||||
User: {
|
||||
async findAndCountAll(options) {
|
||||
assert(options.limit === 10);
|
||||
assert(options.offset === 10);
|
||||
assert.deepStrictEqual(options.order, [[ 'id', 'DESC' ]]);
|
||||
assert.strictEqual(options.where.status, 1);
|
||||
assert.deepStrictEqual(options.where[Op.or], [
|
||||
{ nickname: { [Op.like]: '%张%' } },
|
||||
{ username: { [Op.like]: '%张%' } },
|
||||
{ phone: { [Op.like]: '%张%' } },
|
||||
{ email: { [Op.like]: '%张%' } },
|
||||
]);
|
||||
return { rows: [ instance(row) ], count: 1 };
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const res = await http
|
||||
.get(`/api/users?page=2&pageSize=10&status=1&keyword=${encodeURIComponent('张')}`)
|
||||
.expect(200);
|
||||
|
||||
assert(res.body.data.total === 1);
|
||||
assert(res.body.data.page === 2);
|
||||
assert(res.body.data.list[0].nickname === '张三');
|
||||
});
|
||||
|
||||
it('POST /api/users 缺少 nickname 时返回 422', async () => {
|
||||
await http.post('/api/users').send({ phone: '13900000000' }).expect(422);
|
||||
});
|
||||
|
||||
it('POST /api/users 创建成功返回 201', async () => {
|
||||
mock(app, 'model', {
|
||||
User: {
|
||||
async findOne() {
|
||||
return null;
|
||||
},
|
||||
async create(data) {
|
||||
assert(data.nickname === '李四');
|
||||
assert(data.gender === 2);
|
||||
return instance(Object.assign({ id: 7 }, data));
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const res = await http
|
||||
.post('/api/users')
|
||||
.send({ nickname: '李四', gender: '2' })
|
||||
.expect(201);
|
||||
|
||||
assert(res.body.data.id === 7);
|
||||
assert(res.body.data.gender === 2, 'gender 应归一化为数字');
|
||||
});
|
||||
|
||||
it('POST /api/users 用户名已存在时返回 409', async () => {
|
||||
mock(app, 'model', {
|
||||
User: {
|
||||
async findOne() {
|
||||
return instance(row);
|
||||
},
|
||||
async create() {
|
||||
assert.fail('唯一性冲突时不应该创建');
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const res = await http
|
||||
.post('/api/users')
|
||||
.send({ nickname: '张三', username: 'zhangsan' })
|
||||
.expect(409);
|
||||
|
||||
// 统一错误响应中间件:4xx 也返回 JSON
|
||||
assert(res.body.ok === false);
|
||||
assert(res.body.message.includes('username 已存在'), '应返回冲突原因');
|
||||
});
|
||||
|
||||
it('PUT /api/users/:id 更新成功后清除该用户缓存', async () => {
|
||||
fakeRedis.store.set('packs:user:1', JSON.stringify(row));
|
||||
|
||||
let updated = null;
|
||||
const data = Object.assign({}, row);
|
||||
mock(app, 'model', {
|
||||
User: {
|
||||
async findOne() {
|
||||
return null;
|
||||
},
|
||||
async findByPk() {
|
||||
return {
|
||||
update: async fields => {
|
||||
updated = fields;
|
||||
Object.assign(data, fields);
|
||||
},
|
||||
toJSON: () => data,
|
||||
};
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const res = await http
|
||||
.put('/api/users/1')
|
||||
.send({ nickname: '张三丰' })
|
||||
.expect(200);
|
||||
|
||||
assert(res.body.data.nickname === '张三丰');
|
||||
assert.deepStrictEqual(updated, { nickname: '张三丰' });
|
||||
assert(!fakeRedis.store.has('packs:user:1'), '更新后缓存应失效');
|
||||
});
|
||||
|
||||
it('DELETE /api/users/:id 软删除并清除缓存', async () => {
|
||||
fakeRedis.store.set('packs:user:1', JSON.stringify(row));
|
||||
|
||||
mock(app, 'model', {
|
||||
User: {
|
||||
async destroy(options) {
|
||||
assert.deepStrictEqual(options.where, { id: 1 });
|
||||
return 1;
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
await http.delete('/api/users/1').expect(200);
|
||||
assert(!fakeRedis.store.has('packs:user:1'));
|
||||
});
|
||||
|
||||
it('DELETE /api/users/:id 记录不存在返回 404', async () => {
|
||||
mock(app, 'model', {
|
||||
User: {
|
||||
async destroy() {
|
||||
return 0;
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
await http.delete('/api/users/1').expect(404);
|
||||
});
|
||||
});
|
||||
229
backend/test/app/controller/web.data.test.js
Normal file
229
backend/test/app/controller/web.data.test.js
Normal file
@ -0,0 +1,229 @@
|
||||
'use strict';
|
||||
|
||||
const { app, mock, assert } = require('egg-mock/bootstrap');
|
||||
const { Op } = require('sequelize');
|
||||
|
||||
/** 伪造的 sequelize 实例(toJSON + update 直接改同一份数据) */
|
||||
const instance = (data) => Object.assign(
|
||||
{
|
||||
toJSON: () => data,
|
||||
update: async (fields) => Object.assign(data, fields),
|
||||
},
|
||||
data,
|
||||
);
|
||||
|
||||
/**
|
||||
* web 用户端的数据接口:我的设备 / 我的记录 / 我的统计 / 测试页模拟接口
|
||||
*
|
||||
* 重点断言:**范围一定限定在当前用户名下**(前端传的 userId 一律忽略),
|
||||
* 别人的设备一律 404(不泄露存在性)。
|
||||
*/
|
||||
describe('test/app/controller/web.data.test.js', () => {
|
||||
const me = { id: 1, username: 'admin', nickname: '管理员', status: 1 };
|
||||
|
||||
const token = () => `Bearer ${app.createAnonymousContext().service.jwt.signUser(me)}`;
|
||||
|
||||
/** 只替换用到的模型,User 固定返回当前登录用户 */
|
||||
function mockModels(models = {}) {
|
||||
mock(app, 'model', Object.assign({
|
||||
User: { async findByPk() { return instance(me); } },
|
||||
}, models));
|
||||
}
|
||||
|
||||
it('GET /api/web/devices:只列自己的设备(忽略前端传的 userId)', async () => {
|
||||
mockModels({
|
||||
Scanner: {
|
||||
async findAndCountAll(options) {
|
||||
assert(options.where.userId === 1, '必须按当前用户过滤');
|
||||
return { rows: [ instance({ id: 7, sn: 'SN-7', userId: 1 }) ], count: 1 };
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const res = await app.httpRequest().get('/api/web/devices?userId=2').set('Authorization', token()).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);
|
||||
});
|
||||
|
||||
it('GET /api/web/devices/:id:别人的设备返回 404(不暴露存在性)', async () => {
|
||||
mockModels({
|
||||
Scanner: { async findByPk() { return instance({ id: 9, sn: 'SN-9', userId: 2 }); } },
|
||||
});
|
||||
|
||||
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);
|
||||
});
|
||||
|
||||
it('GET /api/web/devices/:id/channels:看自己设备的通道', async () => {
|
||||
let queriedId = 0;
|
||||
mockModels({
|
||||
Scanner: { async findByPk() { return instance({ id: 9, sn: 'SN-9', userId: 1 }); } },
|
||||
ScanChannel: {
|
||||
async findAll(options) {
|
||||
queriedId = options.where.scannerId;
|
||||
return [ instance({ channelId: 'CH-1', channelName: '通道一' }) ];
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const res = await app.httpRequest().get('/api/web/devices/9/channels').set('Authorization', token()).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 () => {
|
||||
let updated = null;
|
||||
mockModels({
|
||||
Scanner: {
|
||||
async findByPk() {
|
||||
return instance({
|
||||
id: 9,
|
||||
sn: 'SN-9',
|
||||
userId: 1,
|
||||
update: async fields => { updated = fields; },
|
||||
});
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
await app.httpRequest().post('/api/web/devices/9/unbind').set('Authorization', token()).expect(200);
|
||||
assert(updated && updated.userId === null, JSON.stringify(updated));
|
||||
});
|
||||
|
||||
it('DELETE /api/web/devices/:id:删除自己的设备(软删除)', async () => {
|
||||
let destroyed = 0;
|
||||
mockModels({
|
||||
Scanner: {
|
||||
async findByPk() { return instance({ id: 9, sn: 'SN-9', userId: 1 }); },
|
||||
async destroy({ where }) { destroyed = where.id; return 1; },
|
||||
},
|
||||
});
|
||||
|
||||
await app.httpRequest().delete('/api/web/devices/9').set('Authorization', token()).expect(200);
|
||||
assert(destroyed === 9);
|
||||
});
|
||||
|
||||
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) {
|
||||
seenWhere = options.where;
|
||||
return {
|
||||
rows: [ instance({ id: 5, barcode: '6901', channelId: 'CH-1', scanTime: new Date(), scanner: { sn: 'SN-1' } }) ],
|
||||
count: 1,
|
||||
};
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const res = await app.httpRequest().get('/api/web/records?barcode=6901').set('Authorization', token()).expect(200);
|
||||
assert(seenWhere.scannerId[Op.in].join(',') === '1,2', '应限定在自己的设备范围内');
|
||||
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', '指定自己名下的设备时应只查这一台');
|
||||
|
||||
// 别人的设备 id(100)→ 404
|
||||
await app.httpRequest().get('/api/web/records?deviceId=100').set('Authorization', token()).expect(404);
|
||||
});
|
||||
|
||||
it('GET /api/web/stats:设备/通道/记录数都限定在当前用户范围内', async () => {
|
||||
const wanted = [];
|
||||
mockModels({
|
||||
Scanner: {
|
||||
async findAll() { return [ { id: 3 }, { id: 4 } ]; },
|
||||
async count({ where }) {
|
||||
assert(where.userId === 1);
|
||||
return 2;
|
||||
},
|
||||
},
|
||||
ScanChannel: {
|
||||
async count({ where }) { wanted.push(where.scannerId[Op.in].join(',')); return 5; },
|
||||
},
|
||||
ScanRecord: {
|
||||
async count({ where }) { wanted.push(where.scannerId[Op.in].join(',')); return 9; },
|
||||
async findAndCountAll() { return { rows: [], count: 0 }; },
|
||||
},
|
||||
});
|
||||
|
||||
const res = await app.httpRequest().get('/api/web/stats').set('Authorization', token()).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('|')}`);
|
||||
});
|
||||
|
||||
it('POST /api/web/test/device-login:以当前用户为确认人建/取设备并发长期令牌', async () => {
|
||||
let created = null;
|
||||
mockModels({
|
||||
Scanner: {
|
||||
async findOne() { return null; },
|
||||
async create(data) {
|
||||
created = data;
|
||||
return instance(Object.assign({ id: 11 }, data));
|
||||
},
|
||||
async findByPk() {
|
||||
return instance({ id: 11, sn: 'SN-TEST-01', userId: 1, tokenJti: 'j-1', status: 1 });
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const res = await app.httpRequest()
|
||||
.post('/api/web/test/device-login')
|
||||
.set('Authorization', token())
|
||||
.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(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));
|
||||
});
|
||||
|
||||
it('POST /api/web/test/scan:用设备 SN + 长期 JWT 走完整校验(含 jti 比对)', async () => {
|
||||
const sign = (extra = {}) => app.createAnonymousContext().service.jwt.signScanner(
|
||||
{ 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',
|
||||
});
|
||||
let inserted = 0;
|
||||
mockModels({
|
||||
Scanner: { async findByPk() { return scannerRow(); } },
|
||||
ScanChannel: {
|
||||
async findAll() { return []; },
|
||||
async create({ channelId, channelName }) { return instance({ id: 3, channelId, channelName }); },
|
||||
async bulkCreate() {},
|
||||
async update() {},
|
||||
},
|
||||
ScanRecord: {
|
||||
async findAll() { return []; },
|
||||
async bulkCreate(rows) { inserted = rows.length; },
|
||||
},
|
||||
});
|
||||
|
||||
const res = await app.httpRequest()
|
||||
.post('/api/web/test/scan')
|
||||
.set('Authorization', token())
|
||||
.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())
|
||||
.send({ sn: 'SN-OTHER', token: sign(), channelId: 'CH-9', barcode: 'x' }).expect(401);
|
||||
await app.httpRequest().post('/api/web/test/scan').set('Authorization', token())
|
||||
.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())
|
||||
.send({ sn: 'SN-TEST-01', token: token().replace('Bearer ', ''), channelId: 'CH-9', barcode: 'x' }).expect(401);
|
||||
});
|
||||
});
|
||||
137
backend/test/app/controller/web.test.js
Normal file
137
backend/test/app/controller/web.test.js
Normal file
@ -0,0 +1,137 @@
|
||||
'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), '不能引用外部资源');
|
||||
});
|
||||
});
|
||||
184
backend/test/app/controller/wechat.test.js
Normal file
184
backend/test/app/controller/wechat.test.js
Normal file
@ -0,0 +1,184 @@
|
||||
'use strict';
|
||||
|
||||
const { app, mock, assert } = require('egg-mock/bootstrap');
|
||||
const createFakeRedis = require('../../utils/fake-redis');
|
||||
const { HEADER: INTERNAL } = require('../../utils/internal');
|
||||
|
||||
/** 微信绑定关系的读写属「内部接口」:请求都带上运维令牌 */
|
||||
const http = {
|
||||
get: url => app.httpRequest().get(url).set(INTERNAL),
|
||||
post: url => app.httpRequest().post(url).set(INTERNAL),
|
||||
put: url => app.httpRequest().put(url).set(INTERNAL),
|
||||
delete: url => app.httpRequest().delete(url).set(INTERNAL),
|
||||
};
|
||||
|
||||
const instance = (data) => Object.assign(
|
||||
{
|
||||
toJSON: () => data,
|
||||
update: async (fields) => Object.assign(data, fields),
|
||||
},
|
||||
data,
|
||||
);
|
||||
|
||||
describe('test/app/controller/wechat.test.js', () => {
|
||||
beforeEach(() => {
|
||||
mock(app, 'redis', createFakeRedis().client);
|
||||
});
|
||||
|
||||
it('POST /api/wechat/bind 首次绑定创建记录(201)', async () => {
|
||||
mock(app, 'model', {
|
||||
WechatOauth: {
|
||||
async findOne() {
|
||||
return null;
|
||||
},
|
||||
async create(data) {
|
||||
assert(data.userId === 1);
|
||||
assert(data.appid === 'wx123');
|
||||
assert(data.openid === 'o_abc');
|
||||
assert(data.lastAuthAt instanceof Date, '应记录最近授权时间');
|
||||
return instance(Object.assign({ id: 9 }, data));
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const res = await http
|
||||
.post('/api/wechat/bind')
|
||||
.send({ userId: 1, appid: 'wx123', openid: 'o_abc', nickname: '微信昵称' })
|
||||
.expect(201);
|
||||
|
||||
assert(res.body.data.id === 9);
|
||||
assert(res.body.data.nickname === '微信昵称');
|
||||
});
|
||||
|
||||
it('POST /api/wechat/bind 已存在时更新(含换绑用户)', async () => {
|
||||
let updated = null;
|
||||
mock(app, 'model', {
|
||||
WechatOauth: {
|
||||
async findOne() {
|
||||
return instance({
|
||||
id: 9,
|
||||
userId: 1,
|
||||
appid: 'wx123',
|
||||
openid: 'o_abc',
|
||||
update: async (fields) => {
|
||||
updated = fields;
|
||||
},
|
||||
});
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
await http
|
||||
.post('/api/wechat/bind')
|
||||
.send({ userId: 2, appid: 'wx123', openid: 'o_abc', sessionKey: 'sk-1' })
|
||||
.expect(201);
|
||||
|
||||
assert(updated.userId === 2, '应支持把授权记录换绑到另一个用户');
|
||||
assert(updated.sessionKey === 'sk-1');
|
||||
});
|
||||
|
||||
it('POST /api/wechat/bind 缺少必填参数返回 422', async () => {
|
||||
await http.post('/api/wechat/bind').send({ appid: 'wx123' }).expect(422);
|
||||
});
|
||||
|
||||
it('GET /api/wechat/:appid/:openid 返回授权与关联用户', async () => {
|
||||
mock(app, 'model', {
|
||||
User: { name: 'User' },
|
||||
WechatOauth: {
|
||||
async findOne() {
|
||||
return instance({
|
||||
id: 9,
|
||||
appid: 'wx123',
|
||||
openid: 'o_abc',
|
||||
user: { id: 1, nickname: '张三', deleted_at: null },
|
||||
});
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const res = await http.get('/api/wechat/wx123/o_abc').expect(200);
|
||||
assert(res.body.data.user.nickname === '张三');
|
||||
assert(res.body.data.user.deleted_at === undefined, '不应透出软删除字段');
|
||||
});
|
||||
|
||||
it('GET /api/wechat/:appid/:openid 不存在返回 404', async () => {
|
||||
mock(app, 'model', {
|
||||
User: {},
|
||||
WechatOauth: {
|
||||
async findOne() {
|
||||
return null;
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
await http.get('/api/wechat/wx123/o_none').expect(404);
|
||||
});
|
||||
|
||||
it('GET /api/users/:id/wechats 返回该用户的授权列表', async () => {
|
||||
mock(app, 'model', {
|
||||
WechatOauth: {
|
||||
async findAll(options) {
|
||||
assert(options.where.userId === 1);
|
||||
return [ instance({ id: 9, appid: 'wx123', openid: 'o_abc' }) ];
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const res = await http.get('/api/users/1/wechats').expect(200);
|
||||
assert(res.body.data.total === 1);
|
||||
});
|
||||
|
||||
it('PUT /api/wechat/:id/tokens 更新令牌', async () => {
|
||||
mock(app, 'model', {
|
||||
WechatOauth: {
|
||||
async findByPk(id) {
|
||||
assert(id === 9);
|
||||
return instance({
|
||||
id: 9,
|
||||
update: async fields => {
|
||||
assert(fields.accessToken === 'at-1');
|
||||
assert(fields.tokenExpiresAt instanceof Date);
|
||||
},
|
||||
});
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
await http
|
||||
.put('/api/wechat/9/tokens')
|
||||
.send({ accessToken: 'at-1', expiresIn: 7200 })
|
||||
.expect(200);
|
||||
});
|
||||
|
||||
it('PUT /api/wechat/:id/tokens 记录不存在返回 404', async () => {
|
||||
mock(app, 'model', {
|
||||
WechatOauth: {
|
||||
async findByPk() {
|
||||
return null;
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
await http.put('/api/wechat/9/tokens').send({ accessToken: 'at-1' }).expect(404);
|
||||
});
|
||||
|
||||
it('DELETE /api/wechat/:id 解绑成功 / 不存在返回 404', async () => {
|
||||
mock(app, 'model', {
|
||||
WechatOauth: {
|
||||
async destroy() {
|
||||
return 1;
|
||||
},
|
||||
},
|
||||
});
|
||||
await http.delete('/api/wechat/9').expect(200);
|
||||
|
||||
mock(app, 'model', {
|
||||
WechatOauth: {
|
||||
async destroy() {
|
||||
return 0;
|
||||
},
|
||||
},
|
||||
});
|
||||
await http.delete('/api/wechat/9').expect(404);
|
||||
});
|
||||
});
|
||||
157
backend/test/utils/fake-redis.js
Normal file
157
backend/test/utils/fake-redis.js
Normal file
@ -0,0 +1,157 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 内存版 Redis,单测用(不做 key 前缀处理,直接按完整 key 存取)
|
||||
* 用法:const { store, client } = createFakeRedis(); mock(app, 'redis', client);
|
||||
*
|
||||
* 支持本项目用到的命令:get / set(含 EX、NX)/ setex / del / exists / ttl / incr / expire / keys
|
||||
* 会按 EX/setex 的秒数做真实的过期判断(否则「重发节流」这类用例没法测)。
|
||||
*
|
||||
* 也支持长轮询用到的发布订阅:duplicate() / subscribe() / publish() / on('message') / disconnect()
|
||||
* —— duplicate 出来的 client 共享同一份 key 空间与消息总线,跟真实 Redis 行为一致;
|
||||
* 每个 client 只订阅一个频道(本项目就这个用法)。
|
||||
*/
|
||||
module.exports = function createFakeRedis() {
|
||||
const store = new Map();
|
||||
const expires = new Map();
|
||||
/** 频道 → 订阅者集合(每个订阅者 = { client, emit } ) */
|
||||
const channels = new Map();
|
||||
|
||||
/** 是否还存在(顺手清理已过期的 key) */
|
||||
function alive(key) {
|
||||
if (!store.has(key)) return false;
|
||||
const at = expires.get(key);
|
||||
if (at && at <= Date.now()) {
|
||||
store.delete(key);
|
||||
expires.delete(key);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
const noop = () => null;
|
||||
|
||||
/** 建过的所有 client(用来观察“还有几个长轮询在等”) */
|
||||
const clients = [];
|
||||
|
||||
function createClient() {
|
||||
const listeners = new Map(); // 事件名 → [fn]
|
||||
const state = { channel: null, disconnected: false };
|
||||
|
||||
const emit = (event, ...args) => {
|
||||
for (const fn of listeners.get(event) || []) fn(...args);
|
||||
};
|
||||
|
||||
const client = {
|
||||
async get(key) {
|
||||
return alive(key) ? store.get(key) : null;
|
||||
},
|
||||
async set(key, value, ...args) {
|
||||
const options = args.map(item => String(item).toUpperCase());
|
||||
if (options.includes('NX') && alive(key)) return null; // NX 且已存在 → 失败
|
||||
|
||||
const exIndex = options.indexOf('EX');
|
||||
const ttl = exIndex >= 0 ? Number(args[exIndex + 1]) : NaN;
|
||||
|
||||
store.set(key, String(value));
|
||||
if (Number.isFinite(ttl)) expires.set(key, Date.now() + ttl * 1000);
|
||||
else expires.delete(key);
|
||||
return 'OK';
|
||||
},
|
||||
async setex(key, ttl, value) {
|
||||
store.set(key, String(value));
|
||||
expires.set(key, Date.now() + Number(ttl) * 1000);
|
||||
return 'OK';
|
||||
},
|
||||
async del(key) {
|
||||
expires.delete(key);
|
||||
return store.delete(key) ? 1 : 0;
|
||||
},
|
||||
async exists(key) {
|
||||
return alive(key) ? 1 : 0;
|
||||
},
|
||||
async ttl(key) {
|
||||
if (!alive(key)) return -2;
|
||||
const at = expires.get(key);
|
||||
return at ? Math.max(Math.round((at - Date.now()) / 1000), 0) : -1;
|
||||
},
|
||||
async incr(key) {
|
||||
const next = Number(alive(key) ? store.get(key) : 0) + 1;
|
||||
store.set(key, String(next));
|
||||
return next;
|
||||
},
|
||||
async expire(key, ttl) {
|
||||
if (!alive(key)) return 0;
|
||||
expires.set(key, Date.now() + Number(ttl) * 1000);
|
||||
return 1;
|
||||
},
|
||||
async ping() {
|
||||
return 'PONG';
|
||||
},
|
||||
async keys() {
|
||||
return [ ...store.keys() ].filter(alive);
|
||||
},
|
||||
|
||||
// ---------- 发布订阅(长轮询用) ----------
|
||||
duplicate() {
|
||||
return createClient();
|
||||
},
|
||||
async subscribe(channel) {
|
||||
state.channel = String(channel);
|
||||
if (!channels.has(state.channel)) channels.set(state.channel, new Set());
|
||||
channels.get(state.channel).add(deliver);
|
||||
return 1;
|
||||
},
|
||||
async unsubscribe(channel) {
|
||||
const set = channels.get(String(channel || state.channel));
|
||||
if (set) set.delete(deliver);
|
||||
return 0;
|
||||
},
|
||||
async publish(channel, message) {
|
||||
const set = channels.get(String(channel));
|
||||
if (!set) return 0;
|
||||
for (const fn of [ ...set ]) fn(String(message));
|
||||
return set.size;
|
||||
},
|
||||
disconnect() {
|
||||
state.disconnected = true;
|
||||
for (const set of channels.values()) set.delete(deliver);
|
||||
return client;
|
||||
},
|
||||
quit() {
|
||||
return client.disconnect();
|
||||
},
|
||||
// ---------- 给测试观察用 ----------
|
||||
subscribedChannel() { return state.channel; },
|
||||
isDisconnected() { return state.disconnected; },
|
||||
|
||||
on(event, fn) {
|
||||
if (!listeners.has(event)) listeners.set(event, []);
|
||||
listeners.get(event).push(fn);
|
||||
return client;
|
||||
},
|
||||
once(event, fn) {
|
||||
return client.on(event, fn);
|
||||
},
|
||||
removeAllListeners() {
|
||||
listeners.clear();
|
||||
return client;
|
||||
},
|
||||
};
|
||||
|
||||
/** 收到本 client 订阅频道上的消息 → 冒成 'message' 事件 */
|
||||
function deliver(message) {
|
||||
emit('message', state.channel, message);
|
||||
}
|
||||
|
||||
clients.push(client);
|
||||
return client;
|
||||
}
|
||||
|
||||
return {
|
||||
store,
|
||||
client: createClient(),
|
||||
/** 还挂着的订阅连接数(长轮询断开后应该回到 0) */
|
||||
activeSubscribers: () => clients.filter(item => item.subscribedChannel() && !item.isDisconnected()).length,
|
||||
};
|
||||
};
|
||||
15
backend/test/utils/internal.js
Normal file
15
backend/test/utils/internal.js
Normal file
@ -0,0 +1,15 @@
|
||||
'use strict';
|
||||
|
||||
/**
|
||||
* 内部(运维)接口的鉴权头 —— 与 config/config.unittest.js 里的 token 对应
|
||||
*
|
||||
* 用法:
|
||||
* ```js
|
||||
* const { HEADER: INTERNAL } = require('../../utils/internal');
|
||||
* const res = await app.httpRequest().get('/api/users').set(INTERNAL);
|
||||
* ```
|
||||
* 公开接口多带这个 header 也没有副作用(只有内部路由会看它)。
|
||||
*/
|
||||
const HEADER = { 'x-internal-token': 'test-internal-token' };
|
||||
|
||||
module.exports = { HEADER };
|
||||
162
extension/README.md
Normal file
162
extension/README.md
Normal file
@ -0,0 +1,162 @@
|
||||
# 云仓视频溯源 · 单号注入扩展
|
||||
|
||||
Chrome / Edge 扩展(**Manifest V3 + 原生 JS,零构建**)。
|
||||
|
||||
它注入到**第三方 WMS / 后台页面**里,按规则把「运单号」这类字段就地**二次加工**成可点击元素;
|
||||
点击后打开溯源页面(当前先用 `https://www.baidu.com/?keyword={code}` 占位),把编号作为关键词带过去。
|
||||
|
||||
> 首个取样站点:`https://wms.wms.gztbyc.com/order/orderManagement`
|
||||
> 运单号长这样:
|
||||
> ```html
|
||||
> <span class="click-copy-link" role="button" tabindex="0"
|
||||
> title="点击复制并查看快递单号二维码">321408064481776</span>
|
||||
> ```
|
||||
> 点击它 → 小窗打开 `https://www.baidu.com/?keyword=321408064481776`
|
||||
|
||||
---
|
||||
|
||||
## 1. 安装
|
||||
|
||||
1. 打开 `chrome://extensions`(Edge 是 `edge://extensions`)。
|
||||
2. 右上角打开 **开发者模式**。
|
||||
3. 点 **加载已解压的扩展程序**,选择本目录 `extension/`。
|
||||
4. 刷新一下已经打开的 WMS 页面(扩展只对**安装之后**加载的页面生效)。
|
||||
|
||||
图标缺失时重新生成:`powershell -ExecutionPolicy Bypass -File tools\make-icons.ps1`
|
||||
|
||||
## 2. 目录结构
|
||||
|
||||
```
|
||||
extension/
|
||||
├── manifest.json # MV3 声明;权限只有 "storage"
|
||||
├── icons/ # 16/32/48/128,由 tools/make-icons.ps1 生成
|
||||
├── src/
|
||||
│ ├── lib/rules.js # ★ 规则引擎(配置归一化 / 正则编译 / DOM 加工 / 地址拼接)
|
||||
│ ├── content.js # 注入脚本:扫描 + 加工 + 点击拦截 + MutationObserver 补标
|
||||
│ ├── content.css # 注入样式(全部 .pst- 前缀 + !important)
|
||||
│ ├── background.js # service worker:只负责把算好的地址打开(小窗 / 新标签页)
|
||||
│ ├── popup.html/.css/.js # 工具栏弹窗:开关、本页命中清单、重新扫描
|
||||
│ └── options.html/.css/.js # ★ 规则配置页:基本设置 / 规则编辑 / 试跑 / 导入导出
|
||||
├── test/wms-mock.html # 自测页:按真实结构复刻的表格
|
||||
└── tools/make-icons.ps1 # 生成图标(纯 ASCII,见文件头说明)
|
||||
```
|
||||
|
||||
**没有构建步骤**:`rules.js` 挂在 `globalThis.PSTRules` 上,content script / popup / options 各自
|
||||
用 `<script src>` 或 `manifest.content_scripts.js` 按顺序加载它。改完代码在 `chrome://extensions` 点一下
|
||||
刷新即可(改 `manifest.json` 才需要重装)。
|
||||
|
||||
## 3. 两种匹配方式
|
||||
|
||||
| 方式 | 适用 | 关键字段 |
|
||||
| --- | --- | --- |
|
||||
| **文本正则** | 页面结构会变、但有稳定的编号格式(`YT1234…`) | `pattern` + `flags`(可带 `exclude` 排除) |
|
||||
| **CSS 选择器** | 元素本身很好定位(Element-Plus 表格里的 `[title*="快递单号"]`) | `selector` + `attr`(空 = 取元素文本) |
|
||||
|
||||
- **文本正则**:遍历文本节点,把**命中的子串**包成 `<span class="pst-trace-mark" data-pst-code="…">`。
|
||||
原文原样保留在 span 里,所以宿主页读 `textContent`、复制粘贴、表单校验拿到的内容**都不变**。
|
||||
- **CSS 选择器**:直接给命中元素加类名和 `data-pst-*`,不包一层(适合本来就是个 `<span>` / `<tr>` 的情况)。
|
||||
- `pattern` 的**第 1 个捕获组**会被当成编号(`{code}` 的值);没写捕获组就用整个匹配。
|
||||
|
||||
### 内置规则
|
||||
|
||||
| id | 说明 | 生效站点 | 默认 |
|
||||
| --- | --- | --- | --- |
|
||||
| `wms-waybill` | `[title*="快递单号"]`,取文本 —— **取样自 gztbyc WMS** | `wms.wms.gztbyc.com` / `*.gztbyc.com` | 开 |
|
||||
| `express` | `\b(?:YT\|SF\|JD\|ZTO\|YTO\|STO\|EMS\|DBL)\d{10,16}\b` 通用文本规则 | 全部 | 开 |
|
||||
| `numeric` | 纯数字 12~20 位 | 全部 | **关**(容易把时间戳、内部 ID 点亮,页面上到处下划线反而没人敢用) |
|
||||
| `dom-attr` | `[data-order-no]` 取属性 | 全部 | 关(示例) |
|
||||
|
||||
> ⚠️ gztbyc WMS 一行里有 4 个长得很像的 `.click-copy-link`:
|
||||
> 发货单号 `JY2026101619599`、运单号 `321408064481776`、波次号 `E2026101600069`、平台交易单号 `6930529169563286869`。
|
||||
> **只有运单号那个的 `title` 含「快递单号」**,所以规则用 `[title*="快递单号"]` 而不是 `.click-copy-link`。
|
||||
|
||||
## 4. 目标地址模板
|
||||
|
||||
在**基本设置**里改一处即可切到真实打包视频页,占位符:
|
||||
|
||||
| 占位符 | 含义 |
|
||||
| --- | --- |
|
||||
| `{code}` | 提取到的编号,**URL 编码**后填入 |
|
||||
| `{rawcode}` | 同上但不编码 |
|
||||
| `{host}` | 当前站点 host |
|
||||
|
||||
```
|
||||
默认:https://www.baidu.com/?keyword={code}
|
||||
将来:https://video.example.com/trace?keyword={code}&from=wms
|
||||
```
|
||||
|
||||
单条规则还可以设**专属地址**(留空则用全局模板)。点击后按「打开方式」呈现:
|
||||
**独立小窗**(默认)或**新标签页**。
|
||||
|
||||
## 5. 调规则:别刷页面,用「试跑」
|
||||
|
||||
配置页里的 **规则试跑** 用的是**当前表单里还没保存**的规则,所以可以边调边看:
|
||||
|
||||
- 输入类型选 `HTML 片段`,粘一段真实 DOM,点「试跑」;
|
||||
- 它会模拟一个站点(默认 `wms.wms.gztbyc.com`,用于校验规则的「生效站点」),
|
||||
列出**命中的编号 + 最终目标地址**,并给出**二次加工后的 HTML**;
|
||||
- 0 命中时会把每条启用规则的「生效站点 / 选择器 / 正则」列出来,方便判断是**站点被过滤了**还是**没匹配上**;
|
||||
- 点「填入 WMS 取样」可以一键载入内置样例。
|
||||
|
||||
工具栏弹窗则用来确认**线上是否真的生效**:显示「本页命中 N」+ 编号清单(点一条可直接打开)。
|
||||
|
||||
## 6. 自测页
|
||||
|
||||
```powershell
|
||||
# 任选一种方式打开 test/wms-mock.html
|
||||
npx --yes http-server extension/test -p 7310 # → http://127.0.0.1:7310/wms-mock.html
|
||||
```
|
||||
(也可以直接双击打开 `file://`,但要在扩展详情里额外开启「允许访问文件网址」。)
|
||||
|
||||
预期:表格里 **3 个运单号**被标记(青色虚线下划线 + ▶ 角标),其余 9 个蓝色文本不受影响。
|
||||
|
||||
## 7. 行为约定
|
||||
|
||||
- **点击拦截**在捕获阶段完成,`preventDefault + stopImmediatePropagation`,不会触发宿主页的委托逻辑,
|
||||
也不会让外层 `<a>` 跳走。
|
||||
- **修饰键放行**:按住 <kbd>Ctrl</kbd> / <kbd>⌘</kbd> / <kbd>Alt</kbd> / <kbd>Shift</kbd> 点击 = 不拦,
|
||||
交还给页面原本的行为。
|
||||
(gztbyc WMS 上那个运单号 span 原本是「点击复制二维码」,想用原功能就按住 Ctrl 点。)
|
||||
- **SPA 友好**:`MutationObserver`(默认 400ms 防抖)盯着新增节点和文本变化自动补标;
|
||||
自己也写了 DOM 会触发观察器,用 `quietUntil` 时间窗把这类回声挡掉,避免无限重扫。
|
||||
- **完整可撤销**:关掉总开关、改规则、或当前站点不在生效范围时会 `unmark()`——
|
||||
wrap 模式把 `<span>` 换回纯文本,selector 模式把类名 / `data-pst-*` / 被覆盖的 `title` / 加过的 `tabindex` 全部还原。
|
||||
- **上限保护**:单次扫描最多看 `maxNodes`(默认 5000)个文本节点、单页最多标 `maxMarks`(默认 400)处,
|
||||
超了会截断并在弹窗里显示 `N+`。
|
||||
|
||||
## 8. 权限与安全
|
||||
|
||||
| 权限 | 用途 |
|
||||
| --- | --- |
|
||||
| `storage` | 存规则配置(优先 `storage.sync`,超 8KB 单项配额自动退到 `storage.local` 并提示) |
|
||||
| content script `matches: http(s)://*/*` | 需要注入任意第三方系统,无法预先枚举域名 |
|
||||
|
||||
- 不请求 `tabs` / `scripting` / `cookies`,**不读页面 cookie,不发任何请求**:
|
||||
点击只是把算好的 URL 交给 `chrome.tabs.create` / `chrome.windows.create`。
|
||||
- 注入走隔离世界(ISOLATED),不注入页面上下文,不受宿主页 CSP 影响。
|
||||
- 想收窄范围:改 `manifest.json` 里 `content_scripts[0].matches` 为具体域名(如 `https://wms.wms.gztbyc.com/*`),
|
||||
重新加载扩展即可;规则层面的范围由「生效站点」控制。
|
||||
- 页面上不想要的可加 `data-pst-skip` 属性(能改页面时),引擎会整棵子树跳过。
|
||||
|
||||
## 9. 踩过的坑(都已修,改代码时注意)
|
||||
|
||||
- **`border-color` 不能放进 `transition`**:`border-bottom-color` 未指定时计算值是 `currentColor`
|
||||
(宿主页链接色,实测 `#409eff`),一旦参与过渡,标记出来的**第一帧**是不确定的宿主色
|
||||
——每标一处都闪一下蓝。实测 `0ms = rgb(64,158,255)` → `150ms = rgb(14,165,164)`,去掉后立即正确。
|
||||
- **`tools/make-icons.ps1` 必须保持纯 ASCII**:PowerShell 5.1 在中文机器上把**无 BOM** 的 `.ps1`
|
||||
按 GBK 读,UTF-8 中文变乱码;乱码落进 `("{0}" -f $x)` 这类格式串里会直接报
|
||||
`Input string was not in a correct format` 而中断脚本。
|
||||
- **命中数不能只看 `applyMarks` 的返回值**:它只处理「还没标过的」节点,滚动/翻页是增量补标,
|
||||
返回值只是本轮新增。所以 `status` 里的清单是**直接数 DOM 上的 `.pst-trace-mark`**(`collectItems`)。
|
||||
- **`chrome.tabs.sendMessage` 要指定 `frameId: 0`**:页面里多个 iframe 都注入过脚本,
|
||||
不定帧会拿到不确定的那个回复。
|
||||
- **`unmark` 的账要记清**:`tabindex` / `title` 可能本来就是页面自己的,只有我们记过账
|
||||
(`data-pst-tab` / `data-pst-title`)的才还原。
|
||||
- nunjucks 无关但同类教训:**新加的类名前缀统一用 `pst-`**,避免和宿主页或本项目其它样式撞名。
|
||||
|
||||
## 10. 下一步(还没做)
|
||||
|
||||
- 把目标地址换成真实的打包视频页(后端需要提供 `GET /api/.../trace?keyword=<运单号>` 之类的接口)。
|
||||
- 需要「先查有没有视频、再决定是否标记」时,把 `content.js` 的 `runScan()` 前接一次
|
||||
`fetch`(要加对应域名的 `host_permissions`),或改成点击时才查。
|
||||
- 一次报多张运单(`+1` 那个展开按钮)目前只取折叠时显示的第一个编号。
|
||||
BIN
extension/icons/icon128.png
Normal file
BIN
extension/icons/icon128.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 3.0 KiB |
BIN
extension/icons/icon16.png
Normal file
BIN
extension/icons/icon16.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 537 B |
BIN
extension/icons/icon32.png
Normal file
BIN
extension/icons/icon32.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 959 B |
BIN
extension/icons/icon48.png
Normal file
BIN
extension/icons/icon48.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 1.3 KiB |
46
extension/manifest.json
Normal file
46
extension/manifest.json
Normal file
@ -0,0 +1,46 @@
|
||||
{
|
||||
"manifest_version": 3,
|
||||
"name": "云仓视频溯源 · 单号注入",
|
||||
"version": "1.0.0",
|
||||
"description": "在第三方 WMS / 后台页面里按规则识别单号,就地加工成可点击的溯源入口;点击后打开溯源页面(默认演示地址可用 ?keyword={code} 承接)。",
|
||||
"minimum_chrome_version": "96",
|
||||
|
||||
"icons": {
|
||||
"16": "icons/icon16.png",
|
||||
"32": "icons/icon32.png",
|
||||
"48": "icons/icon48.png",
|
||||
"128": "icons/icon128.png"
|
||||
},
|
||||
|
||||
"permissions": ["storage"],
|
||||
|
||||
"action": {
|
||||
"default_title": "云仓视频溯源",
|
||||
"default_popup": "src/popup.html",
|
||||
"default_icon": {
|
||||
"16": "icons/icon16.png",
|
||||
"32": "icons/icon32.png",
|
||||
"48": "icons/icon48.png",
|
||||
"128": "icons/icon128.png"
|
||||
}
|
||||
},
|
||||
|
||||
"options_ui": {
|
||||
"page": "src/options.html",
|
||||
"open_in_tab": true
|
||||
},
|
||||
|
||||
"background": {
|
||||
"service_worker": "src/background.js"
|
||||
},
|
||||
|
||||
"content_scripts": [
|
||||
{
|
||||
"matches": ["http://*/*", "https://*/*"],
|
||||
"js": ["src/lib/rules.js", "src/content.js"],
|
||||
"css": ["src/content.css"],
|
||||
"run_at": "document_idle",
|
||||
"all_frames": true
|
||||
}
|
||||
]
|
||||
}
|
||||
50
extension/src/background.js
Normal file
50
extension/src/background.js
Normal file
@ -0,0 +1,50 @@
|
||||
'use strict';
|
||||
/**
|
||||
* 云仓视频溯源 · background(MV3 service worker)
|
||||
*
|
||||
* 只干一件事:把 content script 算好的目标地址打开。
|
||||
*
|
||||
* 为什么把「打开」放在这里而不是 content script 里?
|
||||
* - content script 调 window.open 会被宿主页的弹窗拦截器干掉;
|
||||
* - chrome.tabs.create / chrome.windows.create 不受页面策略影响;
|
||||
* - 顺带可以钉住 windowId,保证新标签页开在用户当前这个窗口里。
|
||||
*
|
||||
* 地址由 content script 算(它手里有配置和 {code}),这里只做协议白名单校验。
|
||||
*/
|
||||
|
||||
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
|
||||
if (!msg || msg.type !== 'pst:open') return;
|
||||
|
||||
openTarget(msg, sender).then(sendResponse, err => {
|
||||
sendResponse({ ok: false, message: String((err && err.message) || err) });
|
||||
});
|
||||
return true; // 异步响应
|
||||
});
|
||||
|
||||
async function openTarget(msg, sender) {
|
||||
const url = String(msg.url || '').trim();
|
||||
if (!/^https?:\/\//i.test(url)) {
|
||||
return { ok: false, message: '只允许打开 http/https 地址:' + url };
|
||||
}
|
||||
|
||||
const mode = msg.mode === 'window' ? 'window' : 'tab';
|
||||
const windowId = sender && sender.tab ? sender.tab.windowId : undefined;
|
||||
|
||||
if (mode === 'window') {
|
||||
await chrome.windows.create({
|
||||
url,
|
||||
type: 'popup',
|
||||
width: 1280,
|
||||
height: 860,
|
||||
focused: true,
|
||||
...(windowId != null ? { } : {}), // windows.create 没有 windowId 概念,忽略
|
||||
});
|
||||
} else {
|
||||
const opts = { url, active: true };
|
||||
if (windowId != null) opts.windowId = windowId;
|
||||
if (sender && sender.tab && sender.tab.id != null) opts.openerTabId = sender.tab.id;
|
||||
await chrome.tabs.create(opts);
|
||||
}
|
||||
|
||||
return { ok: true, url, mode };
|
||||
}
|
||||
92
extension/src/content.css
Normal file
92
extension/src/content.css
Normal file
@ -0,0 +1,92 @@
|
||||
/*
|
||||
* 云仓视频溯源 · 注入元素样式
|
||||
*
|
||||
* 两条铁律:
|
||||
* 1. 所有选择器都以 .pst- 开头,绝不碰宿主页自己的类名;
|
||||
* 2. 视觉属性一律 !important —— 宿主页常有 `.content span { border:0 }` 这类全局规则,
|
||||
* 不加 !important 在有些后台里会「标记生效了但看不见」。
|
||||
*
|
||||
* 另外:underline / highlight 用的是 border-bottom 与 box-shadow,
|
||||
* 都不参与布局,所以标记前后页面不会跳;chip 会撑开一点,用负 margin 抵掉。
|
||||
*/
|
||||
|
||||
.pst-trace-mark {
|
||||
cursor: pointer !important;
|
||||
border-radius: 3px;
|
||||
/*
|
||||
* 这里**故意不写 transition: border-color**:
|
||||
* border-bottom-color 不写时初始值是 currentColor(宿主页的链接色,实测 #409eff),
|
||||
* 一旦把 border-color 放进过渡里,标记出来的瞬间 computed 值是“渐变中”的宿主色 ——
|
||||
* 表现为每标记一处都闪一下蓝(实测 0ms=rgb(64,158,255) → 150ms 后=rgb(14,165,164))。
|
||||
* 去掉后边框色立即确定。
|
||||
*/
|
||||
transition: background-color .15s ease, box-shadow .15s ease;
|
||||
-webkit-box-decoration-break: clone;
|
||||
box-decoration-break: clone;
|
||||
}
|
||||
|
||||
/* ---------- 下划线:默认样式,零布局影响 ---------- */
|
||||
.pst-trace-mark.pst-style-underline {
|
||||
border-bottom: 1px dashed #0ea5a4 !important;
|
||||
padding-bottom: 1px;
|
||||
}
|
||||
.pst-trace-mark.pst-style-underline:hover,
|
||||
.pst-trace-mark.pst-style-underline.pst-open {
|
||||
border-bottom-style: solid !important;
|
||||
border-bottom-color: #0b7d7c !important;
|
||||
}
|
||||
|
||||
/* ---------- 高亮:淡青底 + 内描边(box-shadow 不占布局) ---------- */
|
||||
.pst-trace-mark.pst-style-highlight {
|
||||
background-color: rgba(14, 165, 164, .16) !important;
|
||||
box-shadow: inset 0 0 0 1px rgba(14, 165, 164, .45) !important;
|
||||
}
|
||||
.pst-trace-mark.pst-style-highlight:hover,
|
||||
.pst-trace-mark.pst-style-highlight.pst-open {
|
||||
background-color: rgba(14, 165, 164, .30) !important;
|
||||
box-shadow: inset 0 0 0 1px rgba(11, 125, 124, .85) !important;
|
||||
}
|
||||
|
||||
/* ---------- 胶囊:视觉最重,适合少量关键字段 ---------- */
|
||||
.pst-trace-mark.pst-style-chip {
|
||||
background-color: rgba(14, 165, 164, .16) !important;
|
||||
box-shadow: inset 0 0 0 1px rgba(14, 165, 164, .5) !important;
|
||||
padding: 0 4px !important;
|
||||
margin: 0 -4px !important;
|
||||
}
|
||||
.pst-trace-mark.pst-style-chip:hover,
|
||||
.pst-trace-mark.pst-style-chip.pst-open {
|
||||
background-color: rgba(14, 165, 164, .30) !important;
|
||||
}
|
||||
|
||||
/* ---------- 小播放角标:提示「点了能看视频」 ---------- */
|
||||
.pst-trace-mark.pst-has-icon::after {
|
||||
content: '\25B6'; /* ▶ */
|
||||
font-size: 9px !important;
|
||||
line-height: 1 !important;
|
||||
color: #0b7d7c !important;
|
||||
vertical-align: super;
|
||||
margin-left: 2px;
|
||||
opacity: .8;
|
||||
-webkit-user-select: none;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
/* 点了给个反馈 */
|
||||
.pst-trace-mark.pst-open {
|
||||
animation: pst-pulse .7s ease-out;
|
||||
}
|
||||
@keyframes pst-pulse {
|
||||
0% { background-color: rgba(14, 165, 164, .55); }
|
||||
100% { background-color: transparent; }
|
||||
}
|
||||
|
||||
/* selector 模式标在宿主元素(可能是 <tr> / <div>)上,不要给它加圆角变形 */
|
||||
.pst-trace-mark.pst-mode-selector {
|
||||
border-radius: 2px;
|
||||
}
|
||||
|
||||
/* 宿主页里本来就是链接的,别把下划线叠成两条 */
|
||||
a.pst-trace-mark.pst-style-underline {
|
||||
border-bottom-width: 0 !important;
|
||||
}
|
||||
303
extension/src/content.js
Normal file
303
extension/src/content.js
Normal file
@ -0,0 +1,303 @@
|
||||
'use strict';
|
||||
/**
|
||||
* 云仓视频溯源 · 页面注入(content script)
|
||||
*
|
||||
* 干三件事:
|
||||
* 1. 按配置里的规则扫描页面文本 / DOM,把命中的号「二次加工」成可点击元素;
|
||||
* 2. 拦截点击,算出目标地址后交给 background 打开(新标签页 / 独立小窗);
|
||||
* 3. 用 MutationObserver 盯着 SPA 重渲染,自动补标。
|
||||
*
|
||||
* 设计前提:这是别人的页面,不能弄坏它。
|
||||
* - 只包一层 span,**原文照抄**,宿主页读 textContent / 复制粘贴拿到的内容不变;
|
||||
* - 点击在捕获阶段拦掉并 stopImmediatePropagation,不会触发宿主页自己的点击逻辑;
|
||||
* - 关掉开关或改规则时完整撤销(unmark),页面回到原样;
|
||||
* - 自己的 DOM 写入会让 MutationObserver 触发 → 用 quietUntil 时间窗把自己造成的变动挡掉,
|
||||
* 否则会无限重扫。
|
||||
*/
|
||||
(function () {
|
||||
const R = globalThis.PSTRules;
|
||||
if (!R) return;
|
||||
|
||||
// 同一帧里可能被注入两次(比如扩展重载后又被 manifest 注入一次),只认第一次
|
||||
if (globalThis.__pstTraceInjected) return;
|
||||
globalThis.__pstTraceInjected = true;
|
||||
|
||||
const MARK_CLASS = 'pst-trace-mark';
|
||||
|
||||
const state = {
|
||||
config: R.defaultConfig(),
|
||||
compiled: { rules: [], errors: [] },
|
||||
active: false,
|
||||
observer: null,
|
||||
timer: null,
|
||||
quietUntil: 0,
|
||||
truncated: false,
|
||||
ruleErrors: [],
|
||||
};
|
||||
|
||||
boot();
|
||||
|
||||
async function boot() {
|
||||
state.config = await R.loadConfig();
|
||||
compile();
|
||||
try {
|
||||
chrome.storage.onChanged.addListener(onStorageChanged);
|
||||
chrome.runtime.onMessage.addListener(onMessage);
|
||||
} catch (_) { /* 扩展被重载后 chrome.* 会失效,忽略 */ }
|
||||
apply();
|
||||
}
|
||||
|
||||
function compile() {
|
||||
state.compiled = R.compileRules(state.config.rules);
|
||||
state.ruleErrors = state.compiled.errors;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------ 生命周期 */
|
||||
|
||||
function apply() {
|
||||
const cfg = state.config;
|
||||
const on = !!cfg.enabled && R.hostAllowed(location.hostname, location.host, cfg.hosts);
|
||||
|
||||
if (on !== state.active) {
|
||||
state.active = on;
|
||||
if (on) startObserver(); else stopObserver();
|
||||
}
|
||||
|
||||
if (!on) {
|
||||
if (R.unmark(document, MARK_CLASS)) log('已还原页面(开关关闭或当前站点不在生效范围)');
|
||||
state.truncated = false;
|
||||
return;
|
||||
}
|
||||
scheduleScan(0);
|
||||
}
|
||||
|
||||
function startObserver() {
|
||||
if (state.observer) return;
|
||||
if (!document.body) {
|
||||
document.addEventListener('DOMContentLoaded', () => startObserver(), { once: true });
|
||||
return;
|
||||
}
|
||||
state.observer = new MutationObserver(onMutations);
|
||||
state.observer.observe(document.body, {
|
||||
childList: true,
|
||||
subtree: true,
|
||||
characterData: true,
|
||||
});
|
||||
}
|
||||
|
||||
function stopObserver() {
|
||||
if (!state.observer) return;
|
||||
state.observer.disconnect();
|
||||
state.observer = null;
|
||||
}
|
||||
|
||||
function onMutations(mutations) {
|
||||
// 自己刚写过 DOM → 这批回调是自己的回声,忽略
|
||||
if (performance.now() < state.quietUntil) return;
|
||||
|
||||
for (const m of mutations) {
|
||||
if (m.type === 'characterData') {
|
||||
if (!insideMark(m.target)) { scheduleScan(); return; }
|
||||
continue;
|
||||
}
|
||||
if (m.addedNodes && m.addedNodes.length) {
|
||||
for (const n of m.addedNodes) {
|
||||
if (n.nodeType === 1 && n.classList && n.classList.contains(MARK_CLASS)) continue;
|
||||
if (insideMark(n)) continue;
|
||||
scheduleScan();
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function insideMark(node) {
|
||||
const el = node && (node.nodeType === 1 ? node : node.parentElement);
|
||||
return !!(el && el.closest && el.closest('.' + MARK_CLASS));
|
||||
}
|
||||
|
||||
function scheduleScan(delay) {
|
||||
clearTimeout(state.timer);
|
||||
const wait = delay == null ? state.config.scanDelay : delay;
|
||||
state.timer = setTimeout(() => {
|
||||
state.timer = null;
|
||||
runScan();
|
||||
}, wait);
|
||||
}
|
||||
|
||||
function runScan() {
|
||||
if (!state.active || !document.body) return;
|
||||
|
||||
state.quietUntil = performance.now() + 150;
|
||||
const res = R.applyMarks(document.body, state.compiled, {
|
||||
markClass: MARK_CLASS,
|
||||
maxNodes: state.config.maxNodes,
|
||||
maxMarks: state.config.maxMarks,
|
||||
defaultStyle: state.config.markStyle,
|
||||
showIcon: state.config.showIcon,
|
||||
urlTemplate: state.config.urlTemplate,
|
||||
hostname: location.hostname,
|
||||
host: location.host,
|
||||
});
|
||||
state.quietUntil = performance.now() + 150;
|
||||
|
||||
// ⚠️ 这里**不能**用 res.items 当“当前页命中数”:
|
||||
// applyMarks 只处理「还没标过的」节点,滚动/翻页是增量补标,res.items 只是本轮新增。
|
||||
// 真正可靠的口径是直接数 DOM 上的标记(见 collectItems)。
|
||||
state.truncated = res.truncated;
|
||||
if (res.items.length) {
|
||||
log('新增命中 ' + res.items.length + ' 处,当前页共标记 ' + markElements().length + ' 处'
|
||||
+ (res.truncated ? '(已达上限,可能有遗漏)' : ''));
|
||||
}
|
||||
if (state.ruleErrors.length) {
|
||||
for (const e of state.ruleErrors) log('规则「' + e.name + '」编译失败:' + e.message, true);
|
||||
}
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------- 交互 */
|
||||
|
||||
document.addEventListener('click', onClick, true);
|
||||
document.addEventListener('auxclick', onClick, true); // 鼠标中键
|
||||
document.addEventListener('keydown', onKeydown, true);
|
||||
|
||||
function onClick(e) {
|
||||
const el = markFrom(e.target);
|
||||
if (!el) return;
|
||||
|
||||
// 修饰键放行:宿主页的元素本来可能有自己的行为(比如 WMS 那个单号 span 是「点击复制二维码」)。
|
||||
// 按住 Ctrl / ⌘ / Alt / Shift 点击 = 不拦,交还给页面原来的处理。
|
||||
if (e.ctrlKey || e.metaKey || e.altKey || e.shiftKey) return;
|
||||
|
||||
// 拦死:不让宿主页的委托逻辑、也不让外层 <a> 跳走
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
e.stopImmediatePropagation();
|
||||
openMark(el);
|
||||
}
|
||||
|
||||
function onKeydown(e) {
|
||||
if (e.key !== 'Enter' && e.key !== ' ') return;
|
||||
const el = markFrom(e.target);
|
||||
if (!el) return;
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
openMark(el);
|
||||
}
|
||||
|
||||
function markFrom(target) {
|
||||
if (!target) return null;
|
||||
const el = target.nodeType === 1 ? target : target.parentElement;
|
||||
return el && el.closest ? el.closest('.' + MARK_CLASS) : null;
|
||||
}
|
||||
|
||||
function openMark(el) {
|
||||
const url = el.getAttribute('data-pst-url');
|
||||
if (!url) return;
|
||||
const code = el.getAttribute('data-pst-code') || '';
|
||||
|
||||
el.classList.add('pst-open');
|
||||
setTimeout(() => el.classList.remove('pst-open'), 700);
|
||||
|
||||
sendToBackground({ type: 'pst:open', url, code, mode: state.config.openMode });
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------- 消息 / 配置 */
|
||||
|
||||
function onMessage(msg, sender, sendResponse) {
|
||||
if (!msg) return;
|
||||
|
||||
if (msg.type === 'pst:status') {
|
||||
sendResponse(status());
|
||||
return; // 同步返回,不用 return true
|
||||
}
|
||||
|
||||
if (msg.type === 'pst:rescan') {
|
||||
if (!state.active) apply();
|
||||
else { R.unmark(document, MARK_CLASS); runScan(); }
|
||||
sendResponse(status());
|
||||
return;
|
||||
}
|
||||
|
||||
if (msg.type === 'pst:open') { // popup 列表里点某一条
|
||||
sendToBackground({ type: 'pst:open', url: msg.url, code: msg.code, mode: state.config.openMode });
|
||||
sendResponse({ ok: true });
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
function status() {
|
||||
const items = collectItems();
|
||||
return {
|
||||
ok: true,
|
||||
active: state.active,
|
||||
enabled: !!state.config.enabled,
|
||||
hostAllowed: R.hostAllowed(location.hostname, location.host, state.config.hosts),
|
||||
host: location.host,
|
||||
hosts: state.config.hosts,
|
||||
openMode: state.config.openMode,
|
||||
urlTemplate: state.config.urlTemplate,
|
||||
ruleCount: state.compiled.rules.length,
|
||||
ruleErrors: state.ruleErrors,
|
||||
truncated: state.truncated,
|
||||
total: items.length,
|
||||
items,
|
||||
};
|
||||
}
|
||||
|
||||
/** 页面上所有已加工过的元素(含 selector 模式标在宿主元素上的) */
|
||||
function markElements() {
|
||||
return Array.prototype.slice.call(document.querySelectorAll('.' + MARK_CLASS));
|
||||
}
|
||||
|
||||
/** 从 DOM 反推命中清单:去重、限量,up 到不再关心标记是怎么产生的 */
|
||||
function collectItems() {
|
||||
const out = [];
|
||||
const seen = new Set();
|
||||
for (const el of markElements()) {
|
||||
const code = el.getAttribute('data-pst-code') || '';
|
||||
if (!code) continue;
|
||||
const ruleId = el.getAttribute('data-pst-rule') || '';
|
||||
const key = ruleId + '\u0000' + code;
|
||||
if (seen.has(key)) continue;
|
||||
seen.add(key);
|
||||
out.push({
|
||||
ruleId,
|
||||
code,
|
||||
text: (el.textContent || '').trim(),
|
||||
url: el.getAttribute('data-pst-url') || '',
|
||||
});
|
||||
if (out.length >= 50) break;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function onStorageChanged(changes, areaName) {
|
||||
if (!changes || !changes[R.STORAGE_KEY]) return;
|
||||
const next = R.normalizeConfig(changes[R.STORAGE_KEY].newValue);
|
||||
if (JSON.stringify(next) === JSON.stringify(state.config)) return;
|
||||
|
||||
state.config = next;
|
||||
compile();
|
||||
R.unmark(document, MARK_CLASS); // 旧规则留下的标记先全部撤掉
|
||||
state.truncated = false;
|
||||
apply();
|
||||
log('配置已更新,重新扫描');
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------- 工具 */
|
||||
|
||||
function sendToBackground(msg) {
|
||||
try {
|
||||
chrome.runtime.sendMessage(msg, () => {
|
||||
// 读一下 lastError,避免 "Unchecked runtime.lastError" 噪音
|
||||
void chrome.runtime.lastError;
|
||||
});
|
||||
} catch (_) { /* 扩展已重载 */ }
|
||||
}
|
||||
|
||||
function log(message, isError) {
|
||||
const prefix = '[云仓溯源] ' + location.host + ' ';
|
||||
if (isError) console.warn(prefix + message);
|
||||
else console.debug(prefix + message);
|
||||
}
|
||||
})();
|
||||
596
extension/src/lib/rules.js
Normal file
596
extension/src/lib/rules.js
Normal file
@ -0,0 +1,596 @@
|
||||
'use strict';
|
||||
/**
|
||||
* 云仓视频溯源 · 扫码入口注入 —— 规则引擎(零构建,浏览器/扩展通用)
|
||||
*
|
||||
* 这个文件同时被三处引入:
|
||||
* - content script(manifest.content_scripts.js,跑在第三方页面里)
|
||||
* - 配置页 options.html
|
||||
* - 弹窗 popup.html
|
||||
* 所以不能写成 ES module(没有打包步骤),统一挂在 globalThis.PSTRules 上。
|
||||
*
|
||||
* 职责边界:
|
||||
* 本文件只做「纯逻辑」——配置归一化、正则编译、文本命中、DOM 标记、地址拼接。
|
||||
* 与 chrome.* 打交道的部分集中在 loadConfig / saveConfig 两个函数里。
|
||||
*/
|
||||
(function (root) {
|
||||
const STORAGE_KEY = 'pstConfig';
|
||||
const DEFAULT_URL_TEMPLATE = 'https://www.baidu.com/?keyword={code}';
|
||||
const MARK_STYLES = ['underline', 'highlight', 'chip'];
|
||||
|
||||
/** 这些元素的文本不参与匹配(避免破坏表单/脚本/媒体) */
|
||||
const SKIP_TAGS = new Set([
|
||||
'SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT', 'OPTION',
|
||||
'TITLE', 'HEAD', 'BUTTON', 'LABEL', 'IFRAME', 'CANVAS', 'VIDEO', 'AUDIO',
|
||||
'OBJECT', 'EMBED',
|
||||
]);
|
||||
|
||||
/**
|
||||
* 内置示例规则。
|
||||
* 注意:默认规则要「宁可漏、不可错」——太宽的正则(比如纯 12~20 位数字)
|
||||
* 会把时间戳、内部 ID 全部点亮,页面上到处是下划线,反而没人敢用。
|
||||
*/
|
||||
const DEFAULT_RULES = [
|
||||
{
|
||||
// ★ 取样自 https://wms.wms.gztbyc.com/order/orderManagement
|
||||
// 行内 HTML:<span data-v-7e9b424a class="click-copy-link" role="button" title="点击复制并查看快递单号二维码">321408064481776</span>
|
||||
// 同一行里还有「点击复制发货单号」「点击复制波次号」「点击复制平台交易单号」几个同类 span,
|
||||
// 所以用 title 里的「快递单号」做区分,只认真正的运单号。
|
||||
id: 'wms-waybill',
|
||||
name: '运单号(WMS 快递单号字段 · 取样自 gztbyc WMS)',
|
||||
enabled: true,
|
||||
match: 'selector',
|
||||
selector: '[title*="快递单号"]',
|
||||
attr: '', // 空 = 取元素文本
|
||||
pattern: '',
|
||||
flags: '',
|
||||
exclude: '',
|
||||
hostPatterns: ['wms.wms.gztbyc.com', '*.gztbyc.com'],
|
||||
style: 'underline',
|
||||
urlTemplate: '',
|
||||
},
|
||||
{
|
||||
id: 'express',
|
||||
name: '快递单号(YT / SF / JD / ZTO / YTO / STO / EMS… 通用文本规则)',
|
||||
enabled: true,
|
||||
match: 'text',
|
||||
pattern: '\\b(?:YT|SF|JD|ZTO|YTO|STO|EMS|DBL)\\d{10,16}\\b',
|
||||
flags: 'gi',
|
||||
exclude: '',
|
||||
selector: '',
|
||||
attr: '',
|
||||
hostPatterns: ['*'],
|
||||
style: '',
|
||||
urlTemplate: '',
|
||||
},
|
||||
{
|
||||
id: 'numeric',
|
||||
name: '纯数字单号(12~20 位,示例,默认关闭)',
|
||||
enabled: false,
|
||||
match: 'text',
|
||||
pattern: '\\b\\d{12,20}\\b',
|
||||
flags: 'g',
|
||||
// 13 位数字常是毫秒时间戳,10 位常是秒级时间戳;13 位运单号也不少见 —— 开之前先想清楚
|
||||
exclude: '\\b1[0-9]{9}(?:[0-9]{3})?\\b',
|
||||
selector: '',
|
||||
attr: '',
|
||||
hostPatterns: ['*'],
|
||||
style: '',
|
||||
urlTemplate: '',
|
||||
},
|
||||
{
|
||||
id: 'dom-attr',
|
||||
name: '按 DOM 属性取号(示例,默认关闭)',
|
||||
enabled: false,
|
||||
match: 'selector',
|
||||
pattern: '',
|
||||
flags: '',
|
||||
exclude: '',
|
||||
selector: '[data-order-no]',
|
||||
attr: 'data-order-no',
|
||||
hostPatterns: ['*'],
|
||||
style: '',
|
||||
urlTemplate: '',
|
||||
},
|
||||
];
|
||||
|
||||
/* ---------------------------------------------------------------- 配置 */
|
||||
|
||||
function defaultConfig() {
|
||||
return JSON.parse(JSON.stringify({
|
||||
version: 1,
|
||||
enabled: true,
|
||||
hosts: ['*'],
|
||||
urlTemplate: DEFAULT_URL_TEMPLATE,
|
||||
openMode: 'window', // window = 独立小窗(默认);tab = 新标签页
|
||||
markStyle: 'underline',
|
||||
showIcon: true,
|
||||
scanDelay: 400, // DOM 变动后延迟多久重扫(毫秒)
|
||||
maxNodes: 5000, // 单次扫描最多看多少个文本节点
|
||||
maxMarks: 400, // 单页最多标记多少处
|
||||
rules: DEFAULT_RULES,
|
||||
}));
|
||||
}
|
||||
|
||||
function normalizeConfig(raw) {
|
||||
const dft = defaultConfig();
|
||||
const src = raw && typeof raw === 'object' ? raw : {};
|
||||
const cfg = Object.assign(dft, src);
|
||||
|
||||
cfg.version = 1;
|
||||
cfg.enabled = cfg.enabled !== false;
|
||||
cfg.hosts = toStrArray(cfg.hosts, ['*']);
|
||||
cfg.urlTemplate = String(cfg.urlTemplate || '').trim() || DEFAULT_URL_TEMPLATE;
|
||||
cfg.openMode = cfg.openMode === 'window' ? 'window' : 'tab';
|
||||
cfg.markStyle = MARK_STYLES.indexOf(cfg.markStyle) >= 0 ? cfg.markStyle : 'underline';
|
||||
cfg.showIcon = cfg.showIcon !== false;
|
||||
cfg.scanDelay = clampInt(cfg.scanDelay, 0, 5000, 400);
|
||||
cfg.maxNodes = clampInt(cfg.maxNodes, 100, 50000, 5000);
|
||||
cfg.maxMarks = clampInt(cfg.maxMarks, 1, 5000, 400);
|
||||
|
||||
// rules 缺失(首次安装 / 数据损坏)才回落到内置规则;用户主动删空就保持空
|
||||
if (!Array.isArray(src.rules)) {
|
||||
cfg.rules = dft.rules;
|
||||
} else {
|
||||
cfg.rules = src.rules.map(normalizeRule).filter(Boolean);
|
||||
}
|
||||
return cfg;
|
||||
}
|
||||
|
||||
function normalizeRule(raw) {
|
||||
if (!raw || typeof raw !== 'object') return null;
|
||||
return {
|
||||
id: String(raw.id || '').trim() || 'r-' + Math.random().toString(36).slice(2, 8),
|
||||
name: String(raw.name == null ? '' : raw.name).trim() || '未命名规则',
|
||||
enabled: raw.enabled === true,
|
||||
match: raw.match === 'selector' ? 'selector' : 'text',
|
||||
pattern: String(raw.pattern == null ? '' : raw.pattern),
|
||||
flags: String(raw.flags == null ? '' : raw.flags),
|
||||
exclude: String(raw.exclude == null ? '' : raw.exclude),
|
||||
selector: String(raw.selector == null ? '' : raw.selector),
|
||||
attr: String(raw.attr == null ? '' : raw.attr).trim(),
|
||||
hostPatterns: toStrArray(raw.hostPatterns, ['*']),
|
||||
style: MARK_STYLES.indexOf(raw.style) >= 0 ? raw.style : '',
|
||||
urlTemplate: String(raw.urlTemplate == null ? '' : raw.urlTemplate).trim(),
|
||||
};
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------- 规则编译 */
|
||||
|
||||
/**
|
||||
* 把配置里的规则编译成「可直接跑」的形态,编译失败的规则会被跳过并收集原因
|
||||
* (而不是让整页注入挂掉)。
|
||||
* @returns {{rules: Array, errors: Array<{id:string,name:string,message:string}>}}
|
||||
*/
|
||||
function compileRules(rules) {
|
||||
const list = [];
|
||||
const errors = [];
|
||||
|
||||
for (const rule of Array.isArray(rules) ? rules : []) {
|
||||
if (!rule || rule.enabled === false) continue;
|
||||
try {
|
||||
if (rule.match === 'selector') {
|
||||
const sel = String(rule.selector || '').trim();
|
||||
if (!sel) throw new Error('CSS 选择器不能为空');
|
||||
if (typeof document !== 'undefined') {
|
||||
// 仅做语法校验:非法选择器会让 querySelector 直接抛异常
|
||||
document.createDocumentFragment().querySelector(sel);
|
||||
}
|
||||
list.push({ rule, re: null, excludeRe: null });
|
||||
} else {
|
||||
const ptn = String(rule.pattern || '').trim();
|
||||
if (!ptn) throw new Error('正则表达式不能为空');
|
||||
const re = new RegExp(ptn, normalizeFlags(rule.flags));
|
||||
const ex = String(rule.exclude || '').trim();
|
||||
list.push({ rule, re, excludeRe: ex ? new RegExp(ex, 'g') : null });
|
||||
}
|
||||
} catch (e) {
|
||||
errors.push({ id: rule.id, name: rule.name, message: shortMessage(e) });
|
||||
}
|
||||
}
|
||||
return { rules: list, errors };
|
||||
}
|
||||
|
||||
/** 只保留安全 flag,并且强制带上 g(exec 循环依赖它) */
|
||||
function normalizeFlags(flags) {
|
||||
const keep = [];
|
||||
for (const ch of String(flags || '').toLowerCase()) {
|
||||
if ('imsug'.indexOf(ch) >= 0 && keep.indexOf(ch) < 0) keep.push(ch);
|
||||
}
|
||||
if (keep.indexOf('g') < 0) keep.push('g');
|
||||
return keep.join('');
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------- 文本匹配 */
|
||||
|
||||
function extractCode(m) {
|
||||
const picked = m.length > 1 && m[1] != null ? m[1] : m[0];
|
||||
return String(picked == null ? '' : picked).trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* 在一段文本里找出所有命中(多条规则合并,按位置排序,重叠的只保留最靠前的那个)
|
||||
* @param {string} text
|
||||
* @param {{rules:Array}} compiled compileRules() 的结果
|
||||
* @param {number} [maxPerNode] 单个文本节点最多取多少条,默认 20
|
||||
*/
|
||||
function matchText(text, compiled, maxPerNode) {
|
||||
const out = [];
|
||||
if (!text) return out;
|
||||
const cap = maxPerNode || 20;
|
||||
|
||||
for (const c of (compiled && compiled.rules) || []) {
|
||||
if (!c.re) continue;
|
||||
const re = c.re;
|
||||
re.lastIndex = 0;
|
||||
let m;
|
||||
while ((m = re.exec(text)) !== null) {
|
||||
if (!m[0]) { re.lastIndex++; continue; } // 零宽匹配兜底,否则死循环
|
||||
const code = extractCode(m);
|
||||
if (!code) continue;
|
||||
if (c.excludeRe) {
|
||||
c.excludeRe.lastIndex = 0;
|
||||
if (c.excludeRe.test(m[0])) continue;
|
||||
}
|
||||
out.push({ rule: c.rule, code, text: m[0], index: m.index });
|
||||
if (out.length >= cap) break;
|
||||
}
|
||||
}
|
||||
|
||||
// 长的优先,避免短规则把长规则切碎
|
||||
out.sort((a, b) => (a.index - b.index) || (b.text.length - a.text.length));
|
||||
const kept = [];
|
||||
let end = -1;
|
||||
for (const h of out) {
|
||||
if (h.index < end) continue;
|
||||
kept.push(h);
|
||||
end = h.index + h.text.length;
|
||||
}
|
||||
return kept;
|
||||
}
|
||||
|
||||
function acceptTextNode(node, markClass) {
|
||||
const v = node.nodeValue;
|
||||
if (!v || !v.trim()) return false;
|
||||
|
||||
const p = node.parentElement;
|
||||
if (!p) return false;
|
||||
// 跳过 SVG / MathML —— 超出 HTML 命名空间,插 HTML 元素会出问题
|
||||
if (p.namespaceURI && p.namespaceURI !== 'http://www.w3.org/1999/xhtml') return false;
|
||||
if (SKIP_TAGS.has(p.tagName)) return false;
|
||||
if (p.isContentEditable) return false;
|
||||
// 已经标过的(含我们自己的 span、以及 selector 模式标过的宿主元素)不再重复处理
|
||||
if (p.closest && p.closest('.' + markClass + ', [data-pst-skip]')) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------- DOM 标记 */
|
||||
|
||||
/**
|
||||
* 扫描 rootEl 并按规则「二次加工」:
|
||||
* - text 规则:把命中的子串包成 <span class="pst-trace-mark">(原文本完整保留在 span 里,
|
||||
* 所以页面自己读 textContent / 复制粘贴拿到的内容都不变)
|
||||
* - selector 规则:直接给命中的元素打标(加类名 + data-pst-* 属性)
|
||||
* 两种方式都会带上 data-pst-code / data-pst-url,点击拦截统一按类名认。
|
||||
*
|
||||
* @param {Element|Document} rootEl
|
||||
* @param {{rules:Array}} compiled
|
||||
* @param {object} opts 见下方 o.* 读取处
|
||||
* @returns {{items:Array, marks:Array, truncated:boolean}}
|
||||
* items —— 去重后的命中清单(给 popup 展示)
|
||||
* marks —— 新建/标记的元素(配置页试跑用来取 outerHTML 预览)
|
||||
*/
|
||||
function applyMarks(rootEl, compiled, opts) {
|
||||
const o = opts || {};
|
||||
const doc = (rootEl && rootEl.ownerDocument) || (typeof document !== 'undefined' ? document : null);
|
||||
const markClass = o.markClass || 'pst-trace-mark';
|
||||
const maxNodes = clampInt(o.maxNodes, 100, 50000, 5000);
|
||||
const maxMarks = clampInt(o.maxMarks, 1, 5000, 400);
|
||||
const items = [];
|
||||
const marks = [];
|
||||
const seen = new Set();
|
||||
let truncated = false;
|
||||
|
||||
if (!rootEl || !doc) return { items, marks, truncated };
|
||||
|
||||
function urlFor(rule, code) {
|
||||
const tpl = rule.urlTemplate || o.urlTemplate || DEFAULT_URL_TEMPLATE;
|
||||
return buildUrl(tpl, code, o.host);
|
||||
}
|
||||
|
||||
function pushItem(rule, code, text, url) {
|
||||
const key = rule.id + '\u0000' + code;
|
||||
if (seen.has(key)) return;
|
||||
seen.add(key);
|
||||
if (items.length < 60) {
|
||||
items.push({ ruleId: rule.id, ruleName: rule.name, code, text, url });
|
||||
}
|
||||
}
|
||||
|
||||
const allRules = (compiled && compiled.rules) || [];
|
||||
const selRules = allRules.filter(c => c.rule.match === 'selector' && c.rule.selector);
|
||||
const txtRules = allRules.filter(c => c.re);
|
||||
|
||||
/* --- 1) selector 规则:处理宿主元素本身 --- */
|
||||
if (selRules.length && typeof rootEl.querySelectorAll === 'function') {
|
||||
for (const c of selRules) {
|
||||
let els = [];
|
||||
try {
|
||||
els = Array.prototype.slice.call(rootEl.querySelectorAll(c.rule.selector));
|
||||
} catch (_) { continue; }
|
||||
|
||||
for (const el of els) {
|
||||
if (marks.length >= maxMarks) { truncated = true; break; }
|
||||
if (el.classList.contains(markClass)) continue;
|
||||
if (el.hasAttribute('data-pst-skip')) continue;
|
||||
if (!hostAllowed(o.hostname, o.host, c.rule.hostPatterns)) continue;
|
||||
|
||||
const raw = c.rule.attr ? el.getAttribute(c.rule.attr) : el.textContent;
|
||||
const code = raw == null ? '' : String(raw).trim();
|
||||
if (!code) continue;
|
||||
|
||||
const style = c.rule.style || o.defaultStyle || 'underline';
|
||||
el.classList.add(markClass, 'pst-mode-selector', 'pst-style-' + style);
|
||||
if (o.showIcon !== false) el.classList.add('pst-has-icon');
|
||||
el.setAttribute('data-pst-code', code);
|
||||
el.setAttribute('data-pst-rule', c.rule.id);
|
||||
if (!el.hasAttribute('role')) el.setAttribute('role', 'link');
|
||||
if (!el.hasAttribute('tabindex')) {
|
||||
el.tabIndex = 0;
|
||||
el.setAttribute('data-pst-tab', '1'); // 记下来,撤销时才知道是我加的
|
||||
}
|
||||
// title 可能是页面自己的,先存原值
|
||||
if (!el.hasAttribute('data-pst-title')) {
|
||||
el.setAttribute('data-pst-title', el.hasAttribute('title') ? el.getAttribute('title') : '');
|
||||
}
|
||||
const url = urlFor(c.rule, code);
|
||||
if (url) {
|
||||
el.setAttribute('data-pst-url', url);
|
||||
el.setAttribute('title', url);
|
||||
}
|
||||
marks.push({ el, rule: c.rule, code, text: code, index: -1 });
|
||||
pushItem(c.rule, code, code, url);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* --- 2) text 规则:遍历文本节点,按命中切分后包 span --- */
|
||||
if (txtRules.length && !truncated && typeof doc.createTreeWalker === 'function') {
|
||||
const walker = doc.createTreeWalker(rootEl, NodeFilter.SHOW_TEXT, {
|
||||
acceptNode(node) {
|
||||
return acceptTextNode(node, markClass) ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT;
|
||||
},
|
||||
});
|
||||
|
||||
const targets = [];
|
||||
let node;
|
||||
while ((node = walker.nextNode())) {
|
||||
if (targets.length >= maxNodes) { truncated = true; break; }
|
||||
targets.push(node);
|
||||
}
|
||||
|
||||
const compiledText = { rules: txtRules };
|
||||
for (const tn of targets) {
|
||||
if (marks.length >= maxMarks) { truncated = true; break; }
|
||||
if (!tn.parentNode) continue;
|
||||
|
||||
const text = tn.nodeValue;
|
||||
const hits = matchText(text, compiledText, 20);
|
||||
if (!hits.length) continue;
|
||||
|
||||
const frag = doc.createDocumentFragment();
|
||||
let cursor = 0;
|
||||
for (const h of hits) {
|
||||
if (marks.length >= maxMarks) { truncated = true; break; }
|
||||
if (!hostAllowed(o.hostname, o.host, h.rule.hostPatterns)) continue;
|
||||
|
||||
if (h.index > cursor) frag.appendChild(doc.createTextNode(text.slice(cursor, h.index)));
|
||||
const span = doc.createElement('span');
|
||||
const style = h.rule.style || o.defaultStyle || 'underline';
|
||||
span.className = markClass + ' pst-wrap pst-style-' + style + (o.showIcon !== false ? ' pst-has-icon' : '');
|
||||
span.setAttribute('data-pst-code', h.code);
|
||||
span.setAttribute('data-pst-rule', h.rule.id);
|
||||
span.setAttribute('role', 'link');
|
||||
span.tabIndex = 0;
|
||||
span.setAttribute('data-pst-tab', '1');
|
||||
const url = urlFor(h.rule, h.code);
|
||||
if (url) {
|
||||
span.setAttribute('data-pst-url', url);
|
||||
span.setAttribute('title', url);
|
||||
}
|
||||
span.textContent = h.text; // 原文照抄,页面 textContent 不变
|
||||
frag.appendChild(span);
|
||||
|
||||
marks.push({ el: span, rule: h.rule, code: h.code, text: h.text, index: h.index });
|
||||
pushItem(h.rule, h.code, h.text, url);
|
||||
cursor = h.index + h.text.length;
|
||||
}
|
||||
if (cursor < text.length) frag.appendChild(doc.createTextNode(text.slice(cursor)));
|
||||
tn.parentNode.replaceChild(frag, tn);
|
||||
}
|
||||
}
|
||||
|
||||
return { items, marks, truncated };
|
||||
}
|
||||
|
||||
/** 撤销所有加工,把页面还原成原样(关掉开关 / 改规则时调用) */
|
||||
function unmark(rootEl, markClass) {
|
||||
const sel = '.' + (markClass || 'pst-trace-mark');
|
||||
const el = rootEl || (typeof document !== 'undefined' ? document : null);
|
||||
if (!el || typeof el.querySelectorAll !== 'function') return 0;
|
||||
|
||||
const doc = el.ownerDocument || (typeof document !== 'undefined' ? document : null);
|
||||
let n = 0;
|
||||
|
||||
// text 模式:span 换回纯文本
|
||||
for (const w of Array.prototype.slice.call(el.querySelectorAll(sel + '.pst-wrap'))) {
|
||||
if (w.parentNode && doc) {
|
||||
w.parentNode.replaceChild(doc.createTextNode(w.textContent), w);
|
||||
n++;
|
||||
}
|
||||
}
|
||||
// selector 模式:把加在宿主元素上的痕迹抹掉
|
||||
const classes = ['pst-mode-selector', 'pst-has-icon', 'pst-open',
|
||||
'pst-style-underline', 'pst-style-highlight', 'pst-style-chip'];
|
||||
for (const host of Array.prototype.slice.call(el.querySelectorAll(sel + ':not(.pst-wrap)'))) {
|
||||
host.classList.remove(sel.slice(1));
|
||||
for (const c of classes) host.classList.remove(c);
|
||||
host.removeAttribute('data-pst-code');
|
||||
host.removeAttribute('data-pst-rule');
|
||||
host.removeAttribute('data-pst-url');
|
||||
// tabindex 只有我们能确定是自己加的时候才删(用 data-pst-tab 记过账)
|
||||
if (host.hasAttribute('data-pst-tab')) {
|
||||
host.removeAttribute('tabindex');
|
||||
host.removeAttribute('data-pst-tab');
|
||||
}
|
||||
if (host.getAttribute('role') === 'link') host.removeAttribute('role');
|
||||
if (host.hasAttribute('data-pst-title')) {
|
||||
const prev = host.getAttribute('data-pst-title');
|
||||
host.removeAttribute('data-pst-title');
|
||||
if (prev) host.setAttribute('title', prev); else host.removeAttribute('title');
|
||||
}
|
||||
n++;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------ 站点/地址 */
|
||||
|
||||
function hostAllowed(hostname, host, patterns) {
|
||||
const list = toStrArray(patterns, ['*']);
|
||||
if (list.indexOf('*') >= 0) return true;
|
||||
const targets = [String(hostname || ''), String(host || '')].filter(Boolean);
|
||||
if (!targets.length) return true; // 拿不到 host(比如配置页试跑)就不拦
|
||||
return list.some(p => targets.some(t => globMatch(p, t)));
|
||||
}
|
||||
|
||||
function globMatch(pattern, value) {
|
||||
const p = String(pattern || '').trim();
|
||||
if (!p) return false;
|
||||
if (p === '*') return true;
|
||||
const body = p.split('*').map(escapeRe).join('[^\\s]*');
|
||||
try {
|
||||
return new RegExp('^' + body + '$', 'i').test(String(value));
|
||||
} catch (_) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** 把 {code} 换成编号、{host} 换成当前站点;URL 模板里可以重复出现 */
|
||||
function buildUrl(template, code, host) {
|
||||
const tpl = String(template || '').trim() || DEFAULT_URL_TEMPLATE;
|
||||
const c = code == null ? '' : String(code);
|
||||
return tpl
|
||||
.replace(/\{code\}/gi, encodeURIComponent(c))
|
||||
.replace(/\{host\}/gi, encodeURIComponent(String(host || '')))
|
||||
.replace(/\{rawcode\}/gi, c);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------- 存储(chrome) */
|
||||
|
||||
function hasChromeStorage() {
|
||||
try {
|
||||
return typeof chrome !== 'undefined' && chrome.storage && chrome.storage.local;
|
||||
} catch (_) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async function loadConfig() {
|
||||
if (!hasChromeStorage()) return defaultConfig();
|
||||
let raw = null;
|
||||
try {
|
||||
if (chrome.storage.sync) {
|
||||
const r = await chrome.storage.sync.get(STORAGE_KEY);
|
||||
raw = r && r[STORAGE_KEY];
|
||||
}
|
||||
} catch (_) { /* sync 不可用(企业策略)时退到 local */ }
|
||||
if (raw == null) {
|
||||
try {
|
||||
const r = await chrome.storage.local.get(STORAGE_KEY);
|
||||
raw = r && r[STORAGE_KEY];
|
||||
} catch (_) { /* ignore */ }
|
||||
}
|
||||
return normalizeConfig(raw);
|
||||
}
|
||||
|
||||
/**
|
||||
* 存配置。chrome.storage.sync 单个条目上限 8KB,规则多了会超 —— 超了就落到 local,
|
||||
* 并把警告返回给调用方展示(而不是静默丢配置)。
|
||||
*/
|
||||
async function saveConfig(cfg) {
|
||||
const value = normalizeConfig(cfg);
|
||||
if (!hasChromeStorage()) return { ok: true, area: 'none' };
|
||||
if (chrome.storage.sync) {
|
||||
try {
|
||||
await chrome.storage.sync.set({ [STORAGE_KEY]: value });
|
||||
return { ok: true, area: 'sync' };
|
||||
} catch (e) {
|
||||
try {
|
||||
await chrome.storage.local.set({ [STORAGE_KEY]: value });
|
||||
} catch (e2) {
|
||||
return { ok: false, message: shortMessage(e2) };
|
||||
}
|
||||
return {
|
||||
ok: true,
|
||||
area: 'local',
|
||||
warning: '配置超出同步配额(sync 单项 8KB),已存到本机:换设备不会自动同步。原因:' + shortMessage(e),
|
||||
};
|
||||
}
|
||||
}
|
||||
try {
|
||||
await chrome.storage.local.set({ [STORAGE_KEY]: value });
|
||||
return { ok: true, area: 'local' };
|
||||
} catch (e) {
|
||||
return { ok: false, message: shortMessage(e) };
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------ 小工具 */
|
||||
|
||||
function toStrArray(v, fallback) {
|
||||
const arr = Array.isArray(v) ? v : (typeof v === 'string' ? v.split(/[\s,;]+/) : []);
|
||||
const out = arr.map(x => String(x == null ? '' : x).trim()).filter(Boolean);
|
||||
return out.length ? out : fallback.slice();
|
||||
}
|
||||
|
||||
function clampInt(v, min, max, dft) {
|
||||
const n = Number.parseInt(v, 10);
|
||||
if (!Number.isFinite(n)) return dft;
|
||||
return Math.min(max, Math.max(min, n));
|
||||
}
|
||||
|
||||
function escapeRe(s) {
|
||||
return String(s).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||
}
|
||||
|
||||
function escapeHtml(s) {
|
||||
return String(s == null ? '' : s)
|
||||
.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')
|
||||
.replace(/"/g, '"').replace(/'/g, ''');
|
||||
}
|
||||
|
||||
function shortMessage(e) {
|
||||
const m = e && e.message ? String(e.message) : String(e || '');
|
||||
return m.length > 160 ? m.slice(0, 160) + '…' : m;
|
||||
}
|
||||
|
||||
root.PSTRules = {
|
||||
STORAGE_KEY,
|
||||
DEFAULT_URL_TEMPLATE,
|
||||
MARK_STYLES,
|
||||
defaultConfig,
|
||||
normalizeConfig,
|
||||
normalizeRule,
|
||||
compileRules,
|
||||
matchText,
|
||||
applyMarks,
|
||||
unmark,
|
||||
extractCode,
|
||||
hostAllowed,
|
||||
globMatch,
|
||||
buildUrl,
|
||||
loadConfig,
|
||||
saveConfig,
|
||||
escapeHtml,
|
||||
};
|
||||
})(typeof globalThis !== 'undefined' ? globalThis : this);
|
||||
208
extension/src/options.css
Normal file
208
extension/src/options.css
Normal file
@ -0,0 +1,208 @@
|
||||
:root {
|
||||
--bg: #f2f5f7;
|
||||
--card: #fff;
|
||||
--fg: #1f2328;
|
||||
--muted: #6b7280;
|
||||
--border: #d9dee5;
|
||||
--brand: #0b7d7c;
|
||||
--brand-2: #0ea5a4;
|
||||
--danger: #b42318;
|
||||
}
|
||||
|
||||
* { box-sizing: border-box; }
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
background: var(--bg);
|
||||
color: var(--fg);
|
||||
font: 13px/1.6 "Microsoft YaHei", "Segoe UI", system-ui, sans-serif;
|
||||
}
|
||||
|
||||
.wrap { max-width: 1080px; margin: 0 auto; padding: 20px 20px 90px; }
|
||||
|
||||
code, .mono {
|
||||
font-family: Consolas, "Courier New", monospace;
|
||||
font-size: 12px;
|
||||
}
|
||||
code { background: #eef1f4; padding: 0 4px; border-radius: 3px; }
|
||||
.muted { color: var(--muted); }
|
||||
|
||||
.page-head { display: flex; gap: 12px; align-items: flex-start; margin-bottom: 14px; }
|
||||
.page-head .logo { width: 40px; height: 40px; flex: none; }
|
||||
h1 { margin: 0 0 4px; font-size: 17px; }
|
||||
.page-head p { margin: 0; max-width: 78ch; font-size: 12.5px; }
|
||||
|
||||
.card {
|
||||
background: var(--card);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 10px;
|
||||
padding: 14px 16px;
|
||||
margin-bottom: 14px;
|
||||
}
|
||||
.card h2 {
|
||||
margin: 0 0 12px;
|
||||
font-size: 14px;
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
gap: 8px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.card h2 small { font-weight: 400; font-size: 12px; }
|
||||
|
||||
/* ---------- 表单 ---------- */
|
||||
.grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
|
||||
gap: 10px 14px;
|
||||
}
|
||||
.f { display: flex; flex-direction: column; gap: 4px; min-width: 0; }
|
||||
.f.wide { grid-column: 1 / -1; }
|
||||
.f > span { font-size: 12px; color: var(--muted); }
|
||||
.f .hint { font-size: 11.5px; color: var(--brand); font-style: normal; word-break: break-all; }
|
||||
|
||||
input[type="text"], input:not([type]), select, textarea, .rule input, .rule select {
|
||||
width: 100%;
|
||||
padding: 6px 8px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 6px;
|
||||
background: #fff;
|
||||
color: var(--fg);
|
||||
font-size: 12.5px;
|
||||
font-family: inherit;
|
||||
}
|
||||
input.mono, textarea.mono, .rid { font-family: Consolas, "Courier New", monospace; }
|
||||
textarea { resize: vertical; }
|
||||
input:focus, select:focus, textarea:focus {
|
||||
outline: none;
|
||||
border-color: var(--brand-2);
|
||||
box-shadow: 0 0 0 3px rgba(14, 165, 164, .15);
|
||||
}
|
||||
|
||||
.row-actions { display: flex; gap: 8px; margin-top: 12px; flex-wrap: wrap; }
|
||||
|
||||
button {
|
||||
padding: 6px 12px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 6px;
|
||||
background: #fff;
|
||||
color: var(--fg);
|
||||
font-size: 12.5px;
|
||||
font-family: inherit;
|
||||
cursor: pointer;
|
||||
}
|
||||
button:hover { border-color: var(--brand-2); color: var(--brand); }
|
||||
button.primary { background: var(--brand); border-color: var(--brand); color: #fff; }
|
||||
button.primary:hover { background: var(--brand-2); border-color: var(--brand-2); color: #fff; }
|
||||
button.danger { color: var(--danger); }
|
||||
button.danger:hover { border-color: var(--danger); color: var(--danger); }
|
||||
button.big { padding: 9px 26px; font-size: 13.5px; }
|
||||
|
||||
/* ---------- 规则卡片 ---------- */
|
||||
.rules { display: flex; flex-direction: column; gap: 10px; }
|
||||
.rule {
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
padding: 10px 12px;
|
||||
background: #fbfcfd;
|
||||
}
|
||||
.rule-head { display: flex; align-items: center; gap: 8px; margin-bottom: 8px; }
|
||||
.rule-head .rname { flex: 1 1 auto; font-weight: 600; }
|
||||
.rule-head .rid { flex: none; color: var(--muted); font-size: 11px; background: none; padding: 0; }
|
||||
.rule-actions { display: flex; gap: 4px; flex: none; }
|
||||
.rule-actions button {
|
||||
padding: 2px 8px;
|
||||
line-height: 1.5;
|
||||
font-size: 12px;
|
||||
border-color: transparent;
|
||||
background: transparent;
|
||||
}
|
||||
.rule-actions button:hover { background: #eef6f6; }
|
||||
.rule.is-off { opacity: .62; }
|
||||
.rule.is-off .grid { opacity: .9; }
|
||||
|
||||
/* 开关(小号) */
|
||||
.sw { position: relative; display: inline-block; width: 36px; height: 20px; flex: none; }
|
||||
.sw.small { width: 32px; height: 18px; }
|
||||
.sw input { position: absolute; opacity: 0; width: 0; height: 0; }
|
||||
.sw span {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
background: #cbd5e1;
|
||||
border-radius: 999px;
|
||||
transition: background .15s ease;
|
||||
}
|
||||
.sw span::after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
top: 2px; left: 2px;
|
||||
width: 16px; height: 16px;
|
||||
background: #fff;
|
||||
border-radius: 50%;
|
||||
transition: transform .15s ease;
|
||||
}
|
||||
.sw.small span::after { width: 14px; height: 14px; }
|
||||
.sw input:checked + span { background: var(--brand-2); }
|
||||
.sw input:checked + span::after { transform: translateX(16px); }
|
||||
.sw.small input:checked + span::after { transform: translateX(14px); }
|
||||
|
||||
.note { margin: 12px 0 0; font-size: 12px; }
|
||||
|
||||
/* ---------- 试跑 ---------- */
|
||||
.test-result { margin-top: 12px; }
|
||||
.test-result table { width: 100%; border-collapse: collapse; font-size: 12.5px; }
|
||||
.test-result th, .test-result td {
|
||||
border-bottom: 1px solid var(--border);
|
||||
padding: 5px 8px;
|
||||
text-align: left;
|
||||
vertical-align: top;
|
||||
word-break: break-all;
|
||||
}
|
||||
.test-result th { color: var(--muted); font-weight: 500; }
|
||||
.test-result td.mono { font-family: Consolas, "Courier New", monospace; }
|
||||
.test-result .snippet {
|
||||
margin-top: 10px;
|
||||
padding: 8px 10px;
|
||||
background: #f6f8fa;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 6px;
|
||||
font-family: Consolas, "Courier New", monospace;
|
||||
font-size: 11.5px;
|
||||
white-space: pre-wrap;
|
||||
word-break: break-all;
|
||||
max-height: 220px;
|
||||
overflow: auto;
|
||||
}
|
||||
.test-result .bad { color: var(--danger); }
|
||||
.test-result .good { color: var(--brand); }
|
||||
|
||||
.steps { margin: 0; padding-left: 20px; font-size: 12.5px; }
|
||||
.steps li { margin-bottom: 5px; }
|
||||
|
||||
/* ---------- 底部条 / 提示 ---------- */
|
||||
.page-foot {
|
||||
position: fixed;
|
||||
left: 0; right: 0; bottom: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
padding: 10px 24px;
|
||||
background: rgba(255, 255, 255, .96);
|
||||
border-top: 1px solid var(--border);
|
||||
backdrop-filter: blur(4px);
|
||||
}
|
||||
|
||||
.toast {
|
||||
position: fixed;
|
||||
top: 14px;
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
z-index: 20;
|
||||
padding: 8px 16px;
|
||||
border-radius: 8px;
|
||||
background: #1f2328;
|
||||
color: #fff;
|
||||
font-size: 12.5px;
|
||||
box-shadow: 0 6px 20px rgba(0, 0, 0, .18);
|
||||
max-width: 76ch;
|
||||
}
|
||||
.toast.bad { background: var(--danger); }
|
||||
242
extension/src/options.html
Normal file
242
extension/src/options.html
Normal file
@ -0,0 +1,242 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>云仓视频溯源 · 规则配置</title>
|
||||
<link rel="stylesheet" href="options.css">
|
||||
</head>
|
||||
<body>
|
||||
<div class="wrap">
|
||||
|
||||
<header class="page-head">
|
||||
<img class="logo" src="../icons/icon48.png" alt="">
|
||||
<div>
|
||||
<h1>云仓视频溯源 · 页面注入配置</h1>
|
||||
<p class="muted">
|
||||
在第三方 WMS / 后台页面里按规则识别单号,就地加工成可点击元素;
|
||||
点击后打开「目标地址」并把编号塞进 <code>{code}</code> 占位符。
|
||||
改完保存即生效,已打开的页面会自动重新扫描,<b>不需要刷新</b>。
|
||||
</p>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div id="toast" class="toast" hidden></div>
|
||||
|
||||
<!-- ============================ 基本设置 ============================ -->
|
||||
<section class="card">
|
||||
<h2>基本设置</h2>
|
||||
|
||||
<div class="grid">
|
||||
<label class="f">
|
||||
<span>总开关</span>
|
||||
<select id="enabled">
|
||||
<option value="true">开启</option>
|
||||
<option value="false">关闭</option>
|
||||
</select>
|
||||
</label>
|
||||
|
||||
<label class="f">
|
||||
<span>点击后打开方式</span>
|
||||
<select id="openMode">
|
||||
<option value="window">独立小窗</option>
|
||||
<option value="tab">新标签页</option>
|
||||
</select>
|
||||
</label>
|
||||
|
||||
<label class="f">
|
||||
<span>标记样式</span>
|
||||
<select id="markStyle">
|
||||
<option value="underline">下划线(不改变布局)</option>
|
||||
<option value="highlight">淡青高亮</option>
|
||||
<option value="chip">胶囊</option>
|
||||
</select>
|
||||
</label>
|
||||
|
||||
<label class="f">
|
||||
<span>显示播放角标</span>
|
||||
<select id="showIcon">
|
||||
<option value="true">显示</option>
|
||||
<option value="false">不显示</option>
|
||||
</select>
|
||||
</label>
|
||||
|
||||
<label class="f wide">
|
||||
<span>生效站点(glob,一行/逗号分隔,<code>*</code> = 全部站点)</span>
|
||||
<textarea id="hosts" rows="2" class="mono" placeholder="wms.wms.gztbyc.com *.gztbyc.com"></textarea>
|
||||
</label>
|
||||
|
||||
<label class="f wide">
|
||||
<span>
|
||||
目标地址模板 占位符:<code>{code}</code>=编号(URL 编码)、<code>{rawcode}</code>=编号原样、<code>{host}</code>=当前站点
|
||||
</span>
|
||||
<input id="urlTemplate" class="mono" placeholder="https://www.baidu.com/?keyword={code}">
|
||||
<em class="hint" id="urlPreview">预览:—</em>
|
||||
</label>
|
||||
|
||||
<label class="f">
|
||||
<span>DOM 变动后延迟重扫(毫秒)</span>
|
||||
<input id="scanDelay" type="number" min="0" max="5000" step="50">
|
||||
</label>
|
||||
|
||||
<label class="f">
|
||||
<span>单页最多标记多少处</span>
|
||||
<input id="maxMarks" type="number" min="1" max="5000" step="10">
|
||||
</label>
|
||||
|
||||
<label class="f">
|
||||
<span>单次扫描最多看多少个文本节点</span>
|
||||
<input id="maxNodes" type="number" min="100" max="50000" step="100">
|
||||
</label>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- ============================== 规则 ============================== -->
|
||||
<section class="card">
|
||||
<h2>
|
||||
识别规则
|
||||
<small class="muted">默认规则已按 <code>https://wms.wms.gztbyc.com/order/orderManagement</code> 的真实结构取样</small>
|
||||
</h2>
|
||||
|
||||
<div id="rules" class="rules"></div>
|
||||
|
||||
<div class="row-actions">
|
||||
<button type="button" id="add-rule">+ 添加规则</button>
|
||||
</div>
|
||||
|
||||
<p class="note muted">
|
||||
两种匹配方式:<br>
|
||||
· <b>文本正则</b>:遍历页面文本,把命中的子串包成 <code><span></code>(原文照抄,页面读 textContent / 复制粘贴不受影响)。<br>
|
||||
· <b>CSS 选择器</b>:直接命中元素本身(例如 Element-Plus 表格里的
|
||||
<code>[title*="快递单号"]</code>),取它的文本或某个属性当编号。
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<!-- ============================= 试跑 ============================= -->
|
||||
<section class="card">
|
||||
<h2>规则试跑 <small class="muted">用当前<b>还没保存</b>的规则试,方便调正则</small></h2>
|
||||
|
||||
<div class="grid">
|
||||
<label class="f">
|
||||
<span>模拟站点(用于校验规则的「生效站点」)</span>
|
||||
<input id="testHost" class="mono" placeholder="wms.wms.gztbyc.com">
|
||||
</label>
|
||||
<label class="f">
|
||||
<span>输入类型</span>
|
||||
<select id="testMode">
|
||||
<option value="html">HTML 片段</option>
|
||||
<option value="text">纯文本</option>
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<textarea id="testInput" rows="5" class="mono"></textarea>
|
||||
|
||||
<div class="row-actions">
|
||||
<button type="button" id="run-test" class="primary">试跑</button>
|
||||
<button type="button" id="fill-sample">填入 WMS 取样</button>
|
||||
</div>
|
||||
|
||||
<div id="testResult" class="test-result"></div>
|
||||
</section>
|
||||
|
||||
<!-- ========================== 导入导出/重置 ========================== -->
|
||||
<section class="card">
|
||||
<h2>导入 / 导出</h2>
|
||||
<textarea id="json" rows="4" class="mono" placeholder="点「导出」把当前配置贴到这里,或粘贴一段配置后点「导入」"></textarea>
|
||||
<div class="row-actions">
|
||||
<button type="button" id="export">导出</button>
|
||||
<button type="button" id="import">导入</button>
|
||||
<button type="button" id="reset" class="danger">恢复默认</button>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- ============================ 使用说明 ============================ -->
|
||||
<section class="card">
|
||||
<h2>使用说明</h2>
|
||||
<ol class="steps">
|
||||
<li>打开 <code>chrome://extensions</code> → 右上角打开「开发者模式」→「加载已解压的扩展程序」→ 选择本项目的 <code>extension/</code> 目录。</li>
|
||||
<li>进入 WMS 页面(<code>https://wms.wms.gztbyc.com/order/orderManagement</code>),运单号会被自动标记。</li>
|
||||
<li>点一下运单号 → 小窗打开 <code>https://www.baidu.com/?keyword=<运单号></code>。换成真实的打包视频页,只改上面那个「目标地址模板」即可。</li>
|
||||
<li>调规则时优先用下面的「规则试跑」,不要反复刷页面。工具栏图标上的弹窗能看到「本页命中」清单,用来确认注入是否生效。</li>
|
||||
</ol>
|
||||
</section>
|
||||
|
||||
<footer class="page-foot">
|
||||
<button type="button" id="save" class="primary big">保存配置</button>
|
||||
<span id="savedAt" class="muted"></span>
|
||||
</footer>
|
||||
</div>
|
||||
|
||||
<template id="rule-tpl">
|
||||
<div class="rule" data-rule>
|
||||
<div class="rule-head">
|
||||
<label class="sw small" title="启用这条规则">
|
||||
<input type="checkbox" data-field="enabled">
|
||||
<span></span>
|
||||
</label>
|
||||
<input class="rname" data-field="name" placeholder="规则名称">
|
||||
<code class="rid" data-id></code>
|
||||
<div class="rule-actions">
|
||||
<button type="button" data-act="up" title="上移">↑</button>
|
||||
<button type="button" data-act="down" title="下移">↓</button>
|
||||
<button type="button" data-act="dup" title="复制">⧉</button>
|
||||
<button type="button" data-act="del" title="删除" class="danger">✕</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="grid">
|
||||
<label class="f">
|
||||
<span>匹配方式</span>
|
||||
<select data-field="match">
|
||||
<option value="text">文本正则</option>
|
||||
<option value="selector">CSS 选择器</option>
|
||||
</select>
|
||||
</label>
|
||||
<label class="f">
|
||||
<span>标记样式</span>
|
||||
<select data-field="style">
|
||||
<option value="">跟随全局</option>
|
||||
<option value="underline">下划线</option>
|
||||
<option value="highlight">淡青高亮</option>
|
||||
<option value="chip">胶囊</option>
|
||||
</select>
|
||||
</label>
|
||||
|
||||
<label class="f wide" data-when="text">
|
||||
<span>正则表达式(第 1 个捕获组 = 编号,没写捕获组就用整个匹配)</span>
|
||||
<input data-field="pattern" class="mono" placeholder="\b(?:YT|SF|JD)\d{10,16}\b">
|
||||
</label>
|
||||
<label class="f" data-when="text">
|
||||
<span>flags</span>
|
||||
<input data-field="flags" class="mono" placeholder="gi">
|
||||
</label>
|
||||
<label class="f wide" data-when="text">
|
||||
<span>排除正则(命中即跳过整条匹配,可留空)</span>
|
||||
<input data-field="exclude" class="mono">
|
||||
</label>
|
||||
|
||||
<label class="f wide" data-when="selector">
|
||||
<span>CSS 选择器</span>
|
||||
<input data-field="selector" class="mono" placeholder="[title*="快递单号"]">
|
||||
</label>
|
||||
<label class="f" data-when="selector">
|
||||
<span>取哪个属性(留空 = 取元素文本)</span>
|
||||
<input data-field="attr" class="mono" placeholder="data-order-no">
|
||||
</label>
|
||||
|
||||
<label class="f wide">
|
||||
<span>生效站点(glob,一行/逗号分隔,<code>*</code> = 全部)</span>
|
||||
<input data-field="hostPatterns" class="mono" placeholder="*">
|
||||
</label>
|
||||
<label class="f wide">
|
||||
<span>专属目标地址(留空 = 用全局模板)</span>
|
||||
<input data-field="urlTemplate" class="mono" placeholder="https://video.example.com/play?keyword={code}">
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script src="lib/rules.js"></script>
|
||||
<script src="options.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
383
extension/src/options.js
Normal file
383
extension/src/options.js
Normal file
@ -0,0 +1,383 @@
|
||||
'use strict';
|
||||
/**
|
||||
* 云仓视频溯源 · 规则配置页
|
||||
*
|
||||
* 说明:
|
||||
* - 页面上所有读写都围绕「配置对象」,最终由 PSTRules.normalizeConfig 兜底(缺字段/非法值都不会写坏)。
|
||||
* - 「试跑」用的是**当前表单里还没保存**的规则,方便边调正则边看结果。
|
||||
* - 试跑里渲染 HTML 一律走 PSTRules.escapeHtml,不把外来 HTML 直接 innerHTML 进本页(杜绝 onerror 之类)。
|
||||
*/
|
||||
(function () {
|
||||
const R = globalThis.PSTRules;
|
||||
const $ = id => document.getElementById(id);
|
||||
|
||||
/** 取样自 https://wms.wms.gztbyc.com/order/orderManagement 的一整行(已精简掉无关列) */
|
||||
const SAMPLE_HTML = [
|
||||
'<table><tbody><tr>',
|
||||
' <td><span class="click-copy-link" role="button" tabindex="0" title="点击复制发货单号">JY2026101619599</span></td>',
|
||||
' <td><span class="click-copy-link" role="button" tabindex="0" title="点击复制并查看快递单号二维码">321408064481776</span>',
|
||||
' <button type="button" class="click-copy-toggle" title="展开查看全部">+1</button></td>',
|
||||
' <td><span class="click-copy-link" role="button" tabindex="0" title="点击复制波次号">E2026101600069</span></td>',
|
||||
' <td><span class="click-copy-link" role="button" tabindex="0" title="点击复制平台交易单号">6930529169563286869</span></td>',
|
||||
' <td><span class="ut-status-text ut-status-text--success">已打包</span></td>',
|
||||
' <td><span>2026-10-16 13:26:22</span></td>',
|
||||
'</tr></tbody></table>',
|
||||
].join('\n');
|
||||
|
||||
let cfg = R.defaultConfig();
|
||||
|
||||
boot();
|
||||
|
||||
async function boot() {
|
||||
cfg = await R.loadConfig();
|
||||
fillBase(cfg);
|
||||
renderRules(cfg.rules);
|
||||
|
||||
$('testHost').value = 'wms.wms.gztbyc.com';
|
||||
$('testInput').value = SAMPLE_HTML;
|
||||
|
||||
bind();
|
||||
updateUrlPreview();
|
||||
runTest();
|
||||
}
|
||||
|
||||
/* ============================== 基本设置 ============================== */
|
||||
|
||||
function fillBase(c) {
|
||||
$('enabled').value = String(c.enabled);
|
||||
$('openMode').value = c.openMode;
|
||||
$('markStyle').value = c.markStyle;
|
||||
$('showIcon').value = String(c.showIcon);
|
||||
$('hosts').value = (c.hosts || []).join('\n');
|
||||
$('urlTemplate').value = c.urlTemplate;
|
||||
$('scanDelay').value = c.scanDelay;
|
||||
$('maxMarks').value = c.maxMarks;
|
||||
$('maxNodes').value = c.maxNodes;
|
||||
}
|
||||
|
||||
function readBase() {
|
||||
return {
|
||||
enabled: $('enabled').value === 'true',
|
||||
openMode: $('openMode').value,
|
||||
markStyle: $('markStyle').value,
|
||||
showIcon: $('showIcon').value === 'true',
|
||||
hosts: $('hosts').value,
|
||||
urlTemplate: $('urlTemplate').value,
|
||||
scanDelay: $('scanDelay').value,
|
||||
maxMarks: $('maxMarks').value,
|
||||
maxNodes: $('maxNodes').value,
|
||||
};
|
||||
}
|
||||
|
||||
/** 表单 → 合法配置对象(同时用于保存和试跑) */
|
||||
function readForm() {
|
||||
return R.normalizeConfig(Object.assign(readBase(), { rules: readRules() }));
|
||||
}
|
||||
|
||||
/* ================================ 规则 ================================ */
|
||||
|
||||
const field = (card, name) => card.querySelector('[data-field="' + name + '"]');
|
||||
|
||||
function renderRules(rules) {
|
||||
const box = $('rules');
|
||||
box.textContent = '';
|
||||
for (const rule of rules) box.appendChild(ruleCard(rule));
|
||||
}
|
||||
|
||||
function ruleCard(rule) {
|
||||
const card = $('rule-tpl').content.firstElementChild.cloneNode(true);
|
||||
card.dataset.id = rule.id;
|
||||
field(card, 'enabled').checked = !!rule.enabled;
|
||||
field(card, 'name').value = rule.name;
|
||||
field(card, 'match').value = rule.match;
|
||||
field(card, 'style').value = rule.style || '';
|
||||
field(card, 'pattern').value = rule.pattern;
|
||||
field(card, 'flags').value = rule.flags;
|
||||
field(card, 'exclude').value = rule.exclude;
|
||||
field(card, 'selector').value = rule.selector;
|
||||
field(card, 'attr').value = rule.attr;
|
||||
field(card, 'hostPatterns').value = (rule.hostPatterns || []).join(' ');
|
||||
field(card, 'urlTemplate').value = rule.urlTemplate;
|
||||
card.querySelector('[data-id]').textContent = rule.id;
|
||||
updateWhen(card);
|
||||
updateOff(card);
|
||||
return card;
|
||||
}
|
||||
|
||||
function readRules() {
|
||||
return Array.prototype.slice.call($('rules').querySelectorAll('.rule')).map(card => ({
|
||||
id: card.dataset.id,
|
||||
enabled: field(card, 'enabled').checked,
|
||||
name: field(card, 'name').value.trim(),
|
||||
match: field(card, 'match').value,
|
||||
style: field(card, 'style').value,
|
||||
pattern: field(card, 'pattern').value,
|
||||
flags: field(card, 'flags').value,
|
||||
exclude: field(card, 'exclude').value,
|
||||
selector: field(card, 'selector').value,
|
||||
attr: field(card, 'attr').value.trim(),
|
||||
hostPatterns: field(card, 'hostPatterns').value,
|
||||
urlTemplate: field(card, 'urlTemplate').value.trim(),
|
||||
}));
|
||||
}
|
||||
|
||||
function updateWhen(card) {
|
||||
const mode = field(card, 'match').value;
|
||||
for (const el of card.querySelectorAll('[data-when]')) {
|
||||
el.style.display = el.getAttribute('data-when') === mode ? '' : 'none';
|
||||
}
|
||||
}
|
||||
|
||||
function updateOff(card) {
|
||||
card.classList.toggle('is-off', !field(card, 'enabled').checked);
|
||||
}
|
||||
|
||||
function newRule() {
|
||||
// 借 normalizeRule 生成一个不重复的 id,顺便把字段补齐
|
||||
return R.normalizeRule({
|
||||
name: '新规则',
|
||||
enabled: true,
|
||||
match: 'text',
|
||||
pattern: '\\b[A-Z]{2}\\d{10,16}\\b',
|
||||
flags: 'gi',
|
||||
hostPatterns: ['*'],
|
||||
});
|
||||
}
|
||||
|
||||
function onRulesClick(e) {
|
||||
const btn = e.target.closest('button[data-act]');
|
||||
if (!btn) return;
|
||||
const card = btn.closest('.rule');
|
||||
const rules = $('rules');
|
||||
const act = btn.dataset.act;
|
||||
|
||||
if (act === 'del') {
|
||||
if (!confirm('删除规则「' + field(card, 'name').value + '」?(记得点保存才会生效)')) return;
|
||||
card.remove();
|
||||
} else if (act === 'up' && card.previousElementSibling) {
|
||||
rules.insertBefore(card, card.previousElementSibling);
|
||||
} else if (act === 'down' && card.nextElementSibling) {
|
||||
rules.insertBefore(card.nextElementSibling, card);
|
||||
} else if (act === 'dup') {
|
||||
const src = readRules().find(r => r.id === card.dataset.id);
|
||||
if (!src) return;
|
||||
const copy = R.normalizeRule(Object.assign({}, src, {
|
||||
id: newRule().id,
|
||||
name: (src.name || '规则') + ' 副本',
|
||||
}));
|
||||
rules.insertBefore(ruleCard(copy), card.nextElementSibling);
|
||||
}
|
||||
}
|
||||
|
||||
/* ================================ 试跑 ================================ */
|
||||
|
||||
function runTest() {
|
||||
const form = readForm();
|
||||
const compiled = R.compileRules(form.rules);
|
||||
const simHost = $('testHost').value.trim();
|
||||
const mode = $('testMode').value;
|
||||
const raw = $('testInput').value;
|
||||
const box = $('testResult');
|
||||
box.textContent = '';
|
||||
|
||||
if (!raw.trim()) {
|
||||
box.appendChild(el('p', 'muted', '先粘一段 HTML / 文本再试跑。'));
|
||||
return;
|
||||
}
|
||||
|
||||
let items = [];
|
||||
let marks = [];
|
||||
let truncated = false;
|
||||
|
||||
if (mode === 'html') {
|
||||
const doc = new DOMParser().parseFromString(raw, 'text/html');
|
||||
const res = R.applyMarks(doc.body, compiled, {
|
||||
markClass: 'pst-trace-mark',
|
||||
maxNodes: 3000,
|
||||
maxMarks: 200,
|
||||
defaultStyle: form.markStyle,
|
||||
showIcon: form.showIcon,
|
||||
urlTemplate: form.urlTemplate,
|
||||
hostname: simHost,
|
||||
host: simHost,
|
||||
});
|
||||
items = res.items;
|
||||
marks = res.marks;
|
||||
truncated = res.truncated;
|
||||
} else {
|
||||
for (const line of raw.split(/\r?\n/)) {
|
||||
for (const m of R.matchText(line, compiled, 20)) {
|
||||
items.push({
|
||||
ruleId: m.rule.id,
|
||||
ruleName: m.rule.name,
|
||||
code: m.code,
|
||||
url: R.buildUrl(m.rule.urlTemplate || form.urlTemplate, m.code, simHost),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- 概览 ----
|
||||
const head = el('p', 'muted');
|
||||
head.innerHTML = '启用规则 <b>' + compiled.rules.length + '</b> 条'
|
||||
+ ' · 命中 <b class="' + (items.length ? 'good' : 'bad') + '">' + items.length + '</b> 条'
|
||||
+ (truncated ? ' · <span class="bad">已达上限,可能有遗漏</span>' : '')
|
||||
+ ' · 模拟站点 <code>' + R.escapeHtml(simHost || '(空)') + '</code>';
|
||||
box.appendChild(head);
|
||||
|
||||
for (const err of compiled.errors) {
|
||||
box.appendChild(el('p', 'bad', '规则「' + err.name + '」无效:' + err.message));
|
||||
}
|
||||
|
||||
// ---- 命中表 ----
|
||||
if (items.length) {
|
||||
const table = document.createElement('table');
|
||||
table.innerHTML = '<thead><tr><th>规则</th><th>提取的编号</th><th>目标地址</th></tr></thead>';
|
||||
const tbody = document.createElement('tbody');
|
||||
for (const it of items) {
|
||||
const tr = document.createElement('tr');
|
||||
tr.innerHTML = '<td>' + R.escapeHtml(it.ruleName || it.ruleId) + '</td>'
|
||||
+ '<td class="mono">' + R.escapeHtml(it.code) + '</td>'
|
||||
+ '<td class="mono">' + R.escapeHtml(it.url) + '</td>';
|
||||
tbody.appendChild(tr);
|
||||
}
|
||||
table.appendChild(tbody);
|
||||
box.appendChild(table);
|
||||
} else {
|
||||
// 0 命中时把「为什么没命中」说清楚:多半是生效站点把规则挡住了
|
||||
const enabled = form.rules.filter(r => r.enabled);
|
||||
if (enabled.length) {
|
||||
const box2 = el('div', 'snippet');
|
||||
box2.textContent = enabled.map(r => '· ' + r.name + ' 生效站点:' + r.hostPatterns.join(' / ')
|
||||
+ (r.match === 'selector' ? ' 选择器:' + r.selector : ' 正则:' + r.pattern)).join('\n')
|
||||
+ '\n(模拟站点不在「生效站点」里、或选择器/正则没命中,都会是 0 条)';
|
||||
box.appendChild(box2);
|
||||
}
|
||||
}
|
||||
|
||||
// ---- 二次加工后的源码片段(转义显示,不执行)----
|
||||
if (marks.length) {
|
||||
const snippet = el('div', 'snippet');
|
||||
snippet.textContent = marks.slice(0, 3)
|
||||
.map(m => trim(m.el.outerHTML, 240))
|
||||
.join('\n\n');
|
||||
box.appendChild(el('p', 'muted', '二次加工后的 HTML(最多 3 段):'));
|
||||
box.appendChild(snippet);
|
||||
}
|
||||
}
|
||||
|
||||
/* ============================ 导入导出/重置 ============================ */
|
||||
|
||||
async function reset() {
|
||||
if (!confirm('恢复为内置默认规则?当前配置会被覆盖。')) return;
|
||||
await save(R.defaultConfig());
|
||||
}
|
||||
|
||||
/* ================================ 保存 ================================ */
|
||||
|
||||
async function save(value) {
|
||||
const res = await R.saveConfig(value || readForm());
|
||||
if (!res.ok) {
|
||||
toast('保存失败:' + (res.message || ''), true);
|
||||
return;
|
||||
}
|
||||
cfg = await R.loadConfig();
|
||||
fillBase(cfg);
|
||||
renderRules(cfg.rules);
|
||||
updateUrlPreview();
|
||||
$('savedAt').textContent = '最后保存 ' + new Date().toLocaleTimeString();
|
||||
toast(res.warning ? '已保存(' + res.warning + ')' : '已保存 —— 已打开的页面会自动重新扫描');
|
||||
}
|
||||
|
||||
function updateUrlPreview() {
|
||||
const host = $('testHost').value.trim() || 'wms.wms.gztbyc.com';
|
||||
$('urlPreview').textContent = '预览:' + R.buildUrl($('urlTemplate').value, '321408064481776', host);
|
||||
}
|
||||
|
||||
/* ================================ 绑定 ================================ */
|
||||
|
||||
function bind() {
|
||||
$('save').addEventListener('click', () => save());
|
||||
$('add-rule').addEventListener('click', () => {
|
||||
$('rules').appendChild(ruleCard(newRule()));
|
||||
});
|
||||
|
||||
const rulesBox = $('rules');
|
||||
rulesBox.addEventListener('click', onRulesClick);
|
||||
rulesBox.addEventListener('change', e => {
|
||||
const card = e.target.closest('.rule');
|
||||
if (!card) return;
|
||||
const name = e.target.getAttribute('data-field');
|
||||
if (name === 'match') updateWhen(card);
|
||||
if (name === 'enabled') updateOff(card);
|
||||
// 规则改了就顺手重跑一遍试跑,$('testInput') 里没东西时不会报错
|
||||
if (name) runTest();
|
||||
});
|
||||
|
||||
$('run-test').addEventListener('click', runTest);
|
||||
$('fill-sample').addEventListener('click', () => {
|
||||
$('testMode').value = 'html';
|
||||
$('testInput').value = SAMPLE_HTML;
|
||||
runTest();
|
||||
});
|
||||
|
||||
$('urlTemplate').addEventListener('input', updateUrlPreview);
|
||||
$('testHost').addEventListener('input', updateUrlPreview);
|
||||
$('testInput').addEventListener('input', debounce(runTest, 350));
|
||||
|
||||
$('export').addEventListener('click', () => {
|
||||
$('json').value = JSON.stringify(readForm(), null, 2);
|
||||
toast('已导出到下面的文本框,复制走即可');
|
||||
});
|
||||
$('import').addEventListener('click', async () => {
|
||||
let parsed;
|
||||
try {
|
||||
parsed = JSON.parse($('json').value);
|
||||
} catch (e) {
|
||||
toast('JSON 解析失败:' + e.message, true);
|
||||
return;
|
||||
}
|
||||
await save(parsed);
|
||||
});
|
||||
$('reset').addEventListener('click', reset);
|
||||
|
||||
window.addEventListener('keydown', e => {
|
||||
if ((e.ctrlKey || e.metaKey) && e.key === 's') {
|
||||
e.preventDefault();
|
||||
save();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/* ================================ 小工具 ================================ */
|
||||
|
||||
function el(tag, cls, text) {
|
||||
const node = document.createElement(tag);
|
||||
if (cls) node.className = cls;
|
||||
if (text != null) node.textContent = text;
|
||||
return node;
|
||||
}
|
||||
|
||||
let toastTimer = null;
|
||||
function toast(message, bad) {
|
||||
const box = $('toast');
|
||||
box.textContent = message;
|
||||
box.className = 'toast' + (bad ? ' bad' : '');
|
||||
box.hidden = false;
|
||||
clearTimeout(toastTimer);
|
||||
toastTimer = setTimeout(() => { box.hidden = true; }, bad ? 6000 : 2600);
|
||||
}
|
||||
|
||||
function trim(s, max) {
|
||||
const t = String(s || '');
|
||||
return t.length > max ? t.slice(0, max) + ' …(' + t.length + ' 字符)' : t;
|
||||
}
|
||||
|
||||
function debounce(fn, ms) {
|
||||
let t = null;
|
||||
return function () {
|
||||
clearTimeout(t);
|
||||
t = setTimeout(fn, ms);
|
||||
};
|
||||
}
|
||||
})();
|
||||
131
extension/src/popup.css
Normal file
131
extension/src/popup.css
Normal file
@ -0,0 +1,131 @@
|
||||
:root {
|
||||
--bg: #f6f8fa;
|
||||
--fg: #1f2328;
|
||||
--muted: #6b7280;
|
||||
--border: #d9dee5;
|
||||
--brand: #0b7d7c;
|
||||
--brand-2: #0ea5a4;
|
||||
}
|
||||
|
||||
* { box-sizing: border-box; }
|
||||
|
||||
body {
|
||||
width: 336px;
|
||||
margin: 0;
|
||||
padding: 10px 10px 12px;
|
||||
background: var(--bg);
|
||||
color: var(--fg);
|
||||
font: 13px/1.5 "Microsoft YaHei", "Segoe UI", system-ui, sans-serif;
|
||||
}
|
||||
|
||||
header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 2px 2px 10px;
|
||||
}
|
||||
.logo { width: 24px; height: 24px; flex: none; }
|
||||
.title { flex: 1 1 auto; min-width: 0; }
|
||||
h1 { margin: 0; font-size: 13px; font-weight: 600; }
|
||||
.muted { color: var(--muted); }
|
||||
#host {
|
||||
margin: 0;
|
||||
font-size: 11px;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.card {
|
||||
background: #fff;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 8px;
|
||||
padding: 8px 10px;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
.card .row { display: flex; align-items: center; gap: 6px; font-size: 12px; }
|
||||
.card .row.head { justify-content: space-between; color: var(--muted); }
|
||||
.card .row.head b { color: var(--fg); font-size: 13px; }
|
||||
.card .row + .row { margin-top: 4px; }
|
||||
|
||||
.badge {
|
||||
display: inline-block;
|
||||
padding: 0 6px;
|
||||
border-radius: 999px;
|
||||
font-size: 11px;
|
||||
line-height: 18px;
|
||||
}
|
||||
.badge.ok { background: #e6f7f6; color: var(--brand); }
|
||||
.badge.warn { background: #fff4e5; color: #b45309; }
|
||||
.badge.off { background: #eef0f3; color: var(--muted); }
|
||||
|
||||
.list {
|
||||
list-style: none;
|
||||
margin: 6px 0 0;
|
||||
padding: 0;
|
||||
max-height: 190px;
|
||||
overflow-y: auto;
|
||||
}
|
||||
.list li {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding: 4px 6px;
|
||||
border-radius: 5px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.list li:hover { background: #eef6f6; }
|
||||
.list li .code {
|
||||
font-family: Consolas, "Courier New", monospace;
|
||||
font-size: 12px;
|
||||
flex: 1 1 auto;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.list li .rule { color: var(--muted); font-size: 10px; flex: none; }
|
||||
|
||||
.empty { margin: 6px 0 0; font-size: 12px; }
|
||||
|
||||
.actions { display: flex; gap: 8px; }
|
||||
button {
|
||||
flex: 1 1 0;
|
||||
padding: 7px 8px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 6px;
|
||||
background: #fff;
|
||||
color: var(--fg);
|
||||
font-size: 12px;
|
||||
cursor: pointer;
|
||||
}
|
||||
button:hover { border-color: var(--brand-2); color: var(--brand); }
|
||||
button.primary {
|
||||
background: var(--brand);
|
||||
border-color: var(--brand);
|
||||
color: #fff;
|
||||
}
|
||||
button.primary:hover { background: var(--brand-2); border-color: var(--brand-2); color: #fff; }
|
||||
|
||||
/* 开关 */
|
||||
.sw { position: relative; display: inline-block; width: 36px; height: 20px; flex: none; }
|
||||
.sw input { position: absolute; opacity: 0; width: 0; height: 0; }
|
||||
.sw span {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
background: #cbd5e1;
|
||||
border-radius: 999px;
|
||||
transition: background .15s ease;
|
||||
}
|
||||
.sw span::after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
top: 2px; left: 2px;
|
||||
width: 16px; height: 16px;
|
||||
background: #fff;
|
||||
border-radius: 50%;
|
||||
transition: transform .15s ease;
|
||||
}
|
||||
.sw input:checked + span { background: var(--brand-2); }
|
||||
.sw input:checked + span::after { transform: translateX(16px); }
|
||||
.sw input:focus-visible + span { box-shadow: 0 0 0 2px rgba(14,165,164,.4); }
|
||||
42
extension/src/popup.html
Normal file
42
extension/src/popup.html
Normal file
@ -0,0 +1,42 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>云仓视频溯源</title>
|
||||
<link rel="stylesheet" href="popup.css">
|
||||
</head>
|
||||
<body>
|
||||
<header>
|
||||
<img class="logo" src="../icons/icon32.png" alt="">
|
||||
<div class="title">
|
||||
<h1>云仓视频溯源</h1>
|
||||
<p id="host" class="muted">—</p>
|
||||
</div>
|
||||
<label class="sw" title="总开关">
|
||||
<input type="checkbox" id="enabled">
|
||||
<span></span>
|
||||
</label>
|
||||
</header>
|
||||
|
||||
<section class="card" id="state">
|
||||
<div class="row"><span class="muted">正在读取当前页面…</span></div>
|
||||
</section>
|
||||
|
||||
<section class="card">
|
||||
<div class="row head">
|
||||
<span>本页命中</span>
|
||||
<b id="total">0</b>
|
||||
</div>
|
||||
<ul id="list" class="list"></ul>
|
||||
<p id="empty" class="empty muted">还没有命中项。</p>
|
||||
</section>
|
||||
|
||||
<div class="actions">
|
||||
<button id="rescan" type="button">重新扫描</button>
|
||||
<button id="open-options" type="button" class="primary">规则配置</button>
|
||||
</div>
|
||||
|
||||
<script src="lib/rules.js"></script>
|
||||
<script src="popup.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
155
extension/src/popup.js
Normal file
155
extension/src/popup.js
Normal file
@ -0,0 +1,155 @@
|
||||
'use strict';
|
||||
/**
|
||||
* 云仓视频溯源 · 工具栏弹窗
|
||||
*
|
||||
* 只做展示 + 少量开关,真正的注入逻辑在 content.js 里。
|
||||
* 和 content script 的通信都走 chrome.tabs.sendMessage(tabId, msg, { frameId: 0 }) ——
|
||||
* 指定 frameId 很重要:页面里可能有多个 iframe 都注入了脚本,不定帧会拿到不确定的那个回复。
|
||||
*/
|
||||
(function () {
|
||||
const R = globalThis.PSTRules;
|
||||
const $ = id => document.getElementById(id);
|
||||
|
||||
let tab = null;
|
||||
let cfg = R.defaultConfig();
|
||||
let status = null;
|
||||
|
||||
init();
|
||||
|
||||
async function init() {
|
||||
try {
|
||||
cfg = await R.loadConfig();
|
||||
} catch (_) {
|
||||
cfg = R.defaultConfig();
|
||||
}
|
||||
$('enabled').checked = !!cfg.enabled;
|
||||
|
||||
$('enabled').addEventListener('change', onToggle);
|
||||
$('rescan').addEventListener('click', onRescan);
|
||||
$('open-options').addEventListener('click', () => chrome.runtime.openOptionsPage());
|
||||
|
||||
try {
|
||||
tab = await activeTab();
|
||||
if (!tab || !/^https?:/i.test(tab.url || '')) {
|
||||
renderUnsupported();
|
||||
} else {
|
||||
$('host').textContent = safeHost(tab.url);
|
||||
status = await send(tab.id, { type: 'pst:status' });
|
||||
render();
|
||||
}
|
||||
} catch (e) {
|
||||
// 兜底:宁可显示一行错误,也不要弹窗一片空白
|
||||
$('state').innerHTML = '<div class="row"><span class="badge warn">出错</span>'
|
||||
+ '<span class="muted">' + R.escapeHtml(String((e && e.message) || e)) + '</span></div>';
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------ 渲染 */
|
||||
|
||||
function render() {
|
||||
const stateBox = $('state');
|
||||
|
||||
if (!status || !status.ok) {
|
||||
stateBox.innerHTML = '<div class="row"><span class="badge warn">未注入</span>'
|
||||
+ '<span class="muted">这个页面还没有脚本,刷新一下即可</span></div>';
|
||||
} else if (!status.enabled) {
|
||||
stateBox.innerHTML = '<div class="row"><span class="badge off">已关闭</span>'
|
||||
+ '<span class="muted">总开关处于关闭状态</span></div>';
|
||||
} else if (!status.hostAllowed && !status.active) {
|
||||
stateBox.innerHTML = '<div class="row"><span class="badge off">不在生效范围</span></div>'
|
||||
+ '<div class="row"><span class="muted">生效站点:' + R.escapeHtml((status.hosts || []).join(' / ')) + '</span></div>';
|
||||
} else {
|
||||
stateBox.innerHTML = '<div class="row"><span class="badge ok">注入中</span>'
|
||||
+ '<span class="muted">启用规则 ' + status.ruleCount + ' 条 · '
|
||||
+ (status.openMode === 'window' ? '小窗打开' : '新标签页打开') + '</span></div>'
|
||||
+ (status.ruleErrors && status.ruleErrors.length
|
||||
? '<div class="row"><span class="badge warn">' + status.ruleErrors.length + ' 条规则无效</span></div>'
|
||||
: '');
|
||||
}
|
||||
|
||||
const items = (status && status.items) || [];
|
||||
$('total').textContent = String(items.length) + (status && status.truncated ? '+' : '');
|
||||
$('empty').style.display = items.length ? 'none' : 'block';
|
||||
|
||||
const list = $('list');
|
||||
list.textContent = '';
|
||||
for (const it of items) {
|
||||
const li = document.createElement('li');
|
||||
li.title = it.url || '';
|
||||
const code = document.createElement('span');
|
||||
code.className = 'code';
|
||||
code.textContent = it.code;
|
||||
const rule = document.createElement('span');
|
||||
rule.className = 'rule';
|
||||
rule.textContent = it.ruleId || '';
|
||||
li.append(code, rule);
|
||||
li.addEventListener('click', () => openUrl(it.url));
|
||||
list.appendChild(li);
|
||||
}
|
||||
}
|
||||
|
||||
function renderUnsupported() {
|
||||
$('host').textContent = '当前页面';
|
||||
$('state').innerHTML = '<div class="row"><span class="badge off">不支持</span>'
|
||||
+ '<span class="muted">本扩展只在 http / https 页面上工作</span></div>';
|
||||
$('empty').style.display = 'none';
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------ 交互 */
|
||||
|
||||
async function onToggle() {
|
||||
const next = $('enabled').checked;
|
||||
cfg.enabled = next;
|
||||
const res = await R.saveConfig(cfg);
|
||||
if (!res.ok) {
|
||||
$('enabled').checked = !next;
|
||||
$('state').innerHTML = '<div class="row"><span class="badge warn">保存失败</span>'
|
||||
+ '<span class="muted">' + R.escapeHtml(res.message || '') + '</span></div>';
|
||||
return;
|
||||
}
|
||||
cfg = await R.loadConfig();
|
||||
// content script 收到 storage 变更会自己重新扫描,这里刷一下展示
|
||||
status = tab ? await send(tab.id, { type: 'pst:status' }) : null;
|
||||
render();
|
||||
}
|
||||
|
||||
async function onRescan() {
|
||||
if (!tab) return;
|
||||
status = await send(tab.id, { type: 'pst:rescan' });
|
||||
render();
|
||||
}
|
||||
|
||||
function openUrl(url) {
|
||||
if (!url) return;
|
||||
chrome.runtime.sendMessage({ type: 'pst:open', url, mode: cfg.openMode }, () => {
|
||||
void chrome.runtime.lastError;
|
||||
});
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------ 工具 */
|
||||
|
||||
function activeTab() {
|
||||
return new Promise(resolve => {
|
||||
chrome.tabs.query({ active: true, currentWindow: true }, tabs => {
|
||||
resolve((tabs && tabs[0]) || null);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function send(tabId, msg) {
|
||||
return new Promise(resolve => {
|
||||
try {
|
||||
chrome.tabs.sendMessage(tabId, msg, { frameId: 0 }, res => {
|
||||
const err = chrome.runtime.lastError;
|
||||
resolve(err ? { ok: false, message: err.message } : res);
|
||||
});
|
||||
} catch (e) {
|
||||
resolve({ ok: false, message: String((e && e.message) || e) });
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function safeHost(url) {
|
||||
try { return new URL(url).host; } catch (_) { return url || ''; }
|
||||
}
|
||||
})();
|
||||
77
extension/test/wms-mock.html
Normal file
77
extension/test/wms-mock.html
Normal file
@ -0,0 +1,77 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>WMS 取样页 · 云仓视频溯源注入自测</title>
|
||||
<style>
|
||||
body { font: 13px/1.6 "Microsoft YaHei", system-ui, sans-serif; margin: 24px; color: #1f2328; }
|
||||
h1 { font-size: 16px; margin: 0 0 4px; }
|
||||
p.note { color: #6b7280; font-size: 12.5px; margin: 0 0 16px; }
|
||||
table { border-collapse: collapse; width: 900px; }
|
||||
th, td { border: 1px solid #dcdfe6; padding: 6px 8px; text-align: center; }
|
||||
th { background: #fafafa; color: #606266; font-weight: 500; }
|
||||
.click-copy-list { display: flex; align-items: center; justify-content: center; gap: 4px; }
|
||||
.click-copy-link {
|
||||
color: #409eff;
|
||||
cursor: pointer;
|
||||
font-family: Consolas, monospace;
|
||||
}
|
||||
.click-copy-toggle {
|
||||
border: 0; background: #f0f2f5; color: #606266;
|
||||
border-radius: 3px; padding: 0 4px; font-size: 11px; cursor: pointer;
|
||||
}
|
||||
.ut-status-text--success { color: #67c23a; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<h1>WMS 取样页(自测用)</h1>
|
||||
<p class="note">
|
||||
结构与 <code>https://wms.wms.gztbyc.com/order/orderManagement</code> 的一行一致:<b>只有「运单号」那个 span 带
|
||||
<code>title="点击复制并查看快递单号二维码"</code></b>,同行的发货单号 / 波次号 / 平台交易单号都不该被标记。<br>
|
||||
加载扩展后打开本页:运单号应出现青色虚线下划线 + ▶ 角标,点击会打开小窗。
|
||||
</p>
|
||||
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th>发货单号</th>
|
||||
<th>运单号(快递单号)</th>
|
||||
<th>波次号</th>
|
||||
<th>平台交易单号</th>
|
||||
<th>状态</th>
|
||||
<th>下单时间</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr>
|
||||
<td><div class="click-copy-list"><span class="click-copy-link" role="button" tabindex="0" title="点击复制发货单号">JY2026101619599</span></div></td>
|
||||
<td><div class="click-copy-list"><span class="click-copy-link" role="button" tabindex="0" title="点击复制并查看快递单号二维码">321408064481776</span><button type="button" class="click-copy-toggle" title="展开查看全部">+1</button></div></td>
|
||||
<td><div class="click-copy-list"><span class="click-copy-link" role="button" tabindex="0" title="点击复制波次号">E2026101600069</span></div></td>
|
||||
<td><div class="click-copy-list"><span class="click-copy-link" role="button" tabindex="0" title="点击复制平台交易单号">6930529169563286869</span></div></td>
|
||||
<td><span class="ut-status-text--success">已打包</span></td>
|
||||
<td>2026-10-16 13:26:22</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><div class="click-copy-list"><span class="click-copy-link" role="button" tabindex="0" title="点击复制发货单号">JY2026101615872</span></div></td>
|
||||
<td><div class="click-copy-list"><span class="click-copy-link" role="button" tabindex="0" title="点击复制并查看快递单号二维码">321408064481576</span><button type="button" class="click-copy-toggle" title="展开查看全部">+1</button></div></td>
|
||||
<td><div class="click-copy-list"><span class="click-copy-link" role="button" tabindex="0" title="点击复制波次号">E2026101600069</span></div></td>
|
||||
<td><div class="click-copy-list"><span class="click-copy-link" role="button" tabindex="0" title="点击复制平台交易单号">6930516355859054381</span></div></td>
|
||||
<td><span class="ut-status-text--success">已打包</span></td>
|
||||
<td>2026-10-16 13:46:54</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><div class="click-copy-list"><span class="click-copy-link" role="button" tabindex="0" title="点击复制发货单号">JY2026101416270</span></div></td>
|
||||
<td><div class="click-copy-list"><span class="click-copy-link" role="button" tabindex="0" title="点击复制并查看快递单号二维码">321407672814174</span></div></td>
|
||||
<td><div class="click-copy-list"><span class="click-copy-link" role="button" tabindex="0" title="点击复制波次号">B2026101600532</span></div></td>
|
||||
<td><div class="click-copy-list"><span class="click-copy-link" role="button" tabindex="0" title="点击复制平台交易单号">6918483774881410405</span></div></td>
|
||||
<td><span class="ut-status-text--success">已打包</span></td>
|
||||
<td>2026-10-13 08:36:42</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
<p class="note" style="margin-top:16px">
|
||||
预期:表格里 <b>3 个运单号</b> 被标记,其余 9 个蓝色文本不受影响。
|
||||
</p>
|
||||
</body>
|
||||
</html>
|
||||
70
extension/tools/make-icons.ps1
Normal file
70
extension/tools/make-icons.ps1
Normal file
@ -0,0 +1,70 @@
|
||||
# Generate extension icons (16 / 32 / 48 / 128). Zero dependency: System.Drawing only.
|
||||
#
|
||||
# Usage (PowerShell 5.1):
|
||||
# powershell -ExecutionPolicy Bypass -File tools\make-icons.ps1
|
||||
#
|
||||
# IMPORTANT - keep this file pure ASCII.
|
||||
# PowerShell 5.1 on a zh-CN machine reads .ps1 files WITHOUT a BOM as GBK, so any UTF-8
|
||||
# Chinese in here becomes mojibake; and mojibake inside a format string such as
|
||||
# ("done: {0}" -f $x) can even break parsing: "Input string was not in a correct format".
|
||||
#
|
||||
# Artwork: rounded gradient tile (deep blue -> teal) + white barcode bars.
|
||||
|
||||
Add-Type -AssemblyName System.Drawing
|
||||
|
||||
$root = Split-Path -Parent $PSScriptRoot # extension/
|
||||
$outDir = Join-Path $root 'icons'
|
||||
New-Item -ItemType Directory -Force -Path $outDir | Out-Null
|
||||
|
||||
function New-Icon([int]$size) {
|
||||
$bmp = New-Object System.Drawing.Bitmap($size, $size, [System.Drawing.Imaging.PixelFormat]::Format32bppArgb)
|
||||
$g = [System.Drawing.Graphics]::FromImage($bmp)
|
||||
$g.SmoothingMode = [System.Drawing.Drawing2D.SmoothingMode]::AntiAlias
|
||||
$g.Clear([System.Drawing.Color]::Transparent)
|
||||
|
||||
# ---- rounded rectangle background ----
|
||||
$r = [Math]::Max(2, [int]($size * 0.22))
|
||||
$d = $r * 2
|
||||
$rect = New-Object System.Drawing.Rectangle(0, 0, $size, $size)
|
||||
$path = New-Object System.Drawing.Drawing2D.GraphicsPath
|
||||
$path.AddArc($rect.X, $rect.Y, $d, $d, 180, 90)
|
||||
$path.AddArc($rect.Right - $d, $rect.Y, $d, $d, 270, 90)
|
||||
$path.AddArc($rect.Right - $d, $rect.Bottom - $d, $d, $d, 0, 90)
|
||||
$path.AddArc($rect.X, $rect.Bottom - $d, $d, $d, 90, 90)
|
||||
$path.CloseAllFigures()
|
||||
|
||||
$c1 = [System.Drawing.Color]::FromArgb(255, 12, 74, 110)
|
||||
$c2 = [System.Drawing.Color]::FromArgb(255, 14, 165, 164)
|
||||
$brush = [System.Drawing.Drawing2D.LinearGradientBrush]::new($rect, $c1, $c2, [single]45)
|
||||
$g.FillPath($brush, $path)
|
||||
|
||||
# ---- white barcode bars, alternating heights ----
|
||||
$white = [System.Drawing.SolidBrush]::new([System.Drawing.Color]::FromArgb(255, 255, 255, 255))
|
||||
$barW = [Math]::Max(1, [int]($size * 0.075))
|
||||
$gap = [Math]::Max(1, [int]($size * 0.055))
|
||||
$x = [int]($size * 0.20)
|
||||
$top = [int]($size * 0.28)
|
||||
$bot = [int]($size * 0.72)
|
||||
$limit = $size * 0.82
|
||||
$ratios = @(0.55, 1.0, 0.72, 1.0, 0.6, 0.88, 1.0, 0.66)
|
||||
foreach ($ratio in $ratios) {
|
||||
if ($x + $barW -gt $limit) { break }
|
||||
$h = [int](($bot - $top) * $ratio)
|
||||
$g.FillRectangle($white, $x, ($bot - $h), $barW, $h)
|
||||
$x += $barW + $gap
|
||||
}
|
||||
|
||||
$g.Dispose()
|
||||
$brush.Dispose()
|
||||
$white.Dispose()
|
||||
$path.Dispose()
|
||||
|
||||
$file = Join-Path $outDir ("icon{0}.png" -f $size)
|
||||
$bmp.Save($file, [System.Drawing.Imaging.ImageFormat]::Png)
|
||||
$bmp.Dispose()
|
||||
Write-Host (" {0,-16} {1}x{1}" -f (Split-Path -Leaf $file), $size)
|
||||
}
|
||||
|
||||
Write-Host 'Building icons ->'
|
||||
foreach ($s in 16, 32, 48, 128) { New-Icon $s }
|
||||
Write-Host ('Done. Output: {0}' -f $outDir)
|
||||
12
frontend/index.html
Normal file
12
frontend/index.html
Normal file
@ -0,0 +1,12 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>云仓视频溯源系统</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
<script type="module" src="/src/main.ts"></script>
|
||||
</body>
|
||||
</html>
|
||||
1639
frontend/package-lock.json
generated
Normal file
1639
frontend/package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
24
frontend/package.json
Normal file
24
frontend/package.json
Normal file
@ -0,0 +1,24 @@
|
||||
{
|
||||
"name": "pack-service-frontend",
|
||||
"version": "1.0.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vue-tsc --noEmit && vite build",
|
||||
"build:only": "vite build",
|
||||
"preview": "vite preview",
|
||||
"typecheck": "vue-tsc --noEmit"
|
||||
},
|
||||
"dependencies": {
|
||||
"vue": "^3.5.44",
|
||||
"vue-router": "^5.4.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^26.6.5",
|
||||
"@vitejs/plugin-vue": "^6.0.10",
|
||||
"typescript": "^5.9.3",
|
||||
"vite": "^8.3.4",
|
||||
"vue-tsc": "^3.3.13"
|
||||
}
|
||||
}
|
||||
7
frontend/src/App.vue
Normal file
7
frontend/src/App.vue
Normal file
@ -0,0 +1,7 @@
|
||||
<script setup lang="ts">
|
||||
// 根组件:只负责给路由出口(布局由各页面自己决定:登录页是全屏卡片,业务页是侧边栏布局)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<RouterView />
|
||||
</template>
|
||||
75
frontend/src/api/client.ts
Normal file
75
frontend/src/api/client.ts
Normal file
@ -0,0 +1,75 @@
|
||||
/**
|
||||
* 接口客户端:统一带上 `Authorization: Bearer <user JWT>`,统一处理 `{ ok, data, message }` 结构
|
||||
*
|
||||
* 后端约定(见 backend/README):
|
||||
* - 成功 `{ ok: true, data }`;失败 `{ ok: false, message, status? }`
|
||||
* - 401 = 令牌缺失/过期/无效 → 清掉本地令牌并跳登录页
|
||||
*/
|
||||
import { clearToken, getToken } from '@/composables/useAuth';
|
||||
|
||||
/** 开发时走 Vite 代理(同源 /api),生产时后端同源托管,所以默认空字符串即可 */
|
||||
const BASE = (import.meta.env.VITE_API_BASE as string | undefined) || '';
|
||||
|
||||
export interface ApiResult<T> {
|
||||
ok: boolean;
|
||||
data?: T;
|
||||
message?: string;
|
||||
status?: string;
|
||||
}
|
||||
|
||||
export class ApiError extends Error {
|
||||
status: number;
|
||||
code?: string;
|
||||
|
||||
constructor(message: string, status: number, code?: string) {
|
||||
super(message);
|
||||
this.status = status;
|
||||
this.code = code;
|
||||
}
|
||||
}
|
||||
|
||||
interface RequestOptions {
|
||||
method?: 'GET' | 'POST' | 'PUT' | 'DELETE';
|
||||
body?: unknown;
|
||||
/** 带上令牌(默认带;登录等公开接口可传 false) */
|
||||
auth?: boolean;
|
||||
}
|
||||
|
||||
async function request<T>(path: string, options: RequestOptions = {}): Promise<T> {
|
||||
const { method = 'GET', body, auth = true } = options;
|
||||
const headers: Record<string, string> = {};
|
||||
if (body !== undefined) headers['Content-Type'] = 'application/json';
|
||||
if (auth) {
|
||||
const token = getToken();
|
||||
if (token) headers.Authorization = `Bearer ${token}`;
|
||||
}
|
||||
|
||||
const res = await fetch(`${BASE}${path}`, {
|
||||
method,
|
||||
headers,
|
||||
body: body === undefined ? undefined : JSON.stringify(body),
|
||||
});
|
||||
|
||||
let payload: ApiResult<T> | null = null;
|
||||
try {
|
||||
payload = (await res.json()) as ApiResult<T>;
|
||||
} catch {
|
||||
payload = null;
|
||||
}
|
||||
|
||||
if (res.status === 401) {
|
||||
clearToken();
|
||||
throw new ApiError(payload?.message || '登录已过期,请重新登录', 401, payload?.status);
|
||||
}
|
||||
if (!res.ok || !payload || payload.ok === false) {
|
||||
throw new ApiError(payload?.message || `请求失败(${res.status})`, res.status, payload?.status);
|
||||
}
|
||||
return payload.data as T;
|
||||
}
|
||||
|
||||
export const api = {
|
||||
get: <T>(path: string, options?: Omit<RequestOptions, 'method' | 'body'>) => request<T>(path, { ...options, method: 'GET' }),
|
||||
post: <T>(path: string, body?: unknown, options?: Omit<RequestOptions, 'method' | 'body'>) => request<T>(path, { ...options, method: 'POST', body }),
|
||||
put: <T>(path: string, body?: unknown, options?: Omit<RequestOptions, 'method' | 'body'>) => request<T>(path, { ...options, method: 'PUT', body }),
|
||||
del: <T>(path: string, body?: unknown, options?: Omit<RequestOptions, 'method' | 'body'>) => request<T>(path, { ...options, method: 'DELETE', body }),
|
||||
};
|
||||
101
frontend/src/api/types.ts
Normal file
101
frontend/src/api/types.ts
Normal file
@ -0,0 +1,101 @@
|
||||
/**
|
||||
* 接口数据模型(与后端 `backend/app/controller/web/*` 的返回一一对应)
|
||||
*
|
||||
* 时间字段后端返回的是 ISO 字符串(JSON 序列化后的 Date),这里统一按 `string` 处理,
|
||||
* 展示时用 `formatTime()`(`src/utils/format.ts`)格式化。
|
||||
*/
|
||||
|
||||
/** 分页返回(后端 service 层的 { list, total, page, pageSize } 结构) */
|
||||
export interface Paged<T> {
|
||||
list: T[];
|
||||
total: number;
|
||||
page: number;
|
||||
pageSize: number;
|
||||
}
|
||||
|
||||
/** 设备(中控) */
|
||||
export interface Device {
|
||||
id: number;
|
||||
sn: string;
|
||||
name?: string | null;
|
||||
vendor?: string | null;
|
||||
model?: string | null;
|
||||
firmware?: string | null;
|
||||
ip?: string | null;
|
||||
userId?: number | null;
|
||||
status: number;
|
||||
lastRegisterAt?: string | null;
|
||||
lastLoginAt?: string | null;
|
||||
lastSeenAt?: string | null;
|
||||
createdAt?: string;
|
||||
updatedAt?: string;
|
||||
/** 绑定的账号(只带展示字段) */
|
||||
user?: { id: number; username?: string | null; nickname?: string | null } | null;
|
||||
}
|
||||
|
||||
/** 中控通道 */
|
||||
export interface Channel {
|
||||
id: number;
|
||||
scannerId: number;
|
||||
channelId: string;
|
||||
channelName?: string | null;
|
||||
lastReportAt?: string | null;
|
||||
status: number;
|
||||
}
|
||||
|
||||
/** 扫码记录 */
|
||||
export interface ScanRecord {
|
||||
id: number;
|
||||
scannerId: number;
|
||||
channelId: string;
|
||||
barcode: string;
|
||||
scanTime: string;
|
||||
reportedAt?: string | null;
|
||||
/** 后端拍平出来的所属设备(records 接口) */
|
||||
deviceSn?: string | null;
|
||||
deviceName?: string | null;
|
||||
}
|
||||
|
||||
/** 首页统计 */
|
||||
export interface Stats {
|
||||
deviceCount: number;
|
||||
channelCount: number;
|
||||
recordCount: number;
|
||||
latestRecord: {
|
||||
id: number;
|
||||
barcode: string;
|
||||
channelId: string;
|
||||
deviceSn?: string | null;
|
||||
scanTime: string;
|
||||
} | null;
|
||||
}
|
||||
|
||||
/** 测试页:模拟设备扫码登录的返回(设备信息 + 长期 JWT) */
|
||||
export interface DeviceLoginResult extends Device {
|
||||
token: string;
|
||||
tokenType: string;
|
||||
firstTime: boolean;
|
||||
}
|
||||
|
||||
/** 测试页:模拟中控上报的返回 */
|
||||
export interface ScanReportResult {
|
||||
sn: string;
|
||||
channelId: string;
|
||||
channelName?: string;
|
||||
barcode: string;
|
||||
received: number;
|
||||
inserted: number;
|
||||
duplicated: number;
|
||||
invalid: number;
|
||||
channelCreated: number;
|
||||
channelUpdated: number;
|
||||
}
|
||||
|
||||
/** 扫码登录码状态 */
|
||||
export interface WechatCodeStatus {
|
||||
status: 'pending' | 'confirmed' | 'expired';
|
||||
code: string;
|
||||
spm: string;
|
||||
qrUrl: string;
|
||||
expiresIn?: number;
|
||||
}
|
||||
114
frontend/src/api/web.ts
Normal file
114
frontend/src/api/web.ts
Normal file
@ -0,0 +1,114 @@
|
||||
/**
|
||||
* web 用户端接口(`/api/web/*`)—— 只碰「自己的」数据,令牌由 `api/client.ts` 统一带上
|
||||
*
|
||||
* 后端返回 `{ ok:true, data }`,失败会抛 `ApiError`(401 会自动清令牌)。
|
||||
*/
|
||||
import { api } from '@/api/client';
|
||||
import type {
|
||||
Channel,
|
||||
Device,
|
||||
DeviceLoginResult,
|
||||
Paged,
|
||||
ScanRecord,
|
||||
ScanReportResult,
|
||||
Stats,
|
||||
WechatCodeStatus,
|
||||
} from '@/api/types';
|
||||
|
||||
/** 首页统计 */
|
||||
export function fetchStats(): Promise<Stats> {
|
||||
return api.get<Stats>('/api/web/stats');
|
||||
}
|
||||
|
||||
/** 我的设备列表 */
|
||||
export function fetchDevices(params: {
|
||||
page?: number;
|
||||
pageSize?: number;
|
||||
keyword?: string;
|
||||
status?: number | '';
|
||||
} = {}): Promise<Paged<Device>> {
|
||||
const query = new URLSearchParams();
|
||||
if (params.page) query.set('page', String(params.page));
|
||||
if (params.pageSize) query.set('pageSize', String(params.pageSize));
|
||||
if (params.keyword) query.set('keyword', params.keyword);
|
||||
if (params.status !== undefined && params.status !== '') query.set('status', String(params.status));
|
||||
const qs = query.toString();
|
||||
return api.get<Paged<Device>>(`/api/web/devices${qs ? `?${qs}` : ''}`);
|
||||
}
|
||||
|
||||
/** 某台设备下已登记的通道 */
|
||||
export function fetchDeviceChannels(id: number): Promise<{ deviceId: number; list: Channel[] }> {
|
||||
return api.get<{ deviceId: number; list: Channel[] }>(`/api/web/devices/${id}/channels`);
|
||||
}
|
||||
|
||||
/** 解绑设备(记录保留,设备可再扫码认领) */
|
||||
export function unbindDevice(id: number): Promise<Device> {
|
||||
return api.post<Device>(`/api/web/devices/${id}/unbind`);
|
||||
}
|
||||
|
||||
/** 删除设备(软删除) */
|
||||
export function deleteDevice(id: number): Promise<{ id: number }> {
|
||||
return api.del<{ id: number }>(`/api/web/devices/${id}`);
|
||||
}
|
||||
|
||||
/** 我的扫码记录 */
|
||||
export function fetchRecords(params: {
|
||||
page?: number;
|
||||
pageSize?: number;
|
||||
deviceId?: number | '';
|
||||
channelId?: string;
|
||||
barcode?: string;
|
||||
startTime?: string;
|
||||
endTime?: string;
|
||||
} = {}): Promise<Paged<ScanRecord>> {
|
||||
const query = new URLSearchParams();
|
||||
if (params.page) query.set('page', String(params.page));
|
||||
if (params.pageSize) query.set('pageSize', String(params.pageSize));
|
||||
if (params.deviceId !== undefined && params.deviceId !== '') query.set('deviceId', String(params.deviceId));
|
||||
if (params.channelId) query.set('channelId', params.channelId);
|
||||
if (params.barcode) query.set('barcode', params.barcode);
|
||||
if (params.startTime) query.set('startTime', params.startTime);
|
||||
if (params.endTime) query.set('endTime', params.endTime);
|
||||
const qs = query.toString();
|
||||
return api.get<Paged<ScanRecord>>(`/api/web/records${qs ? `?${qs}` : ''}`);
|
||||
}
|
||||
|
||||
// ---------------- 测试页:模拟真机链路 ----------------
|
||||
|
||||
/** 模拟「设备发码 → 有人扫码确认」:以当前登录账号为确认人建/取设备并换发长期 JWT */
|
||||
export function testDeviceLogin(body: {
|
||||
sn?: string;
|
||||
name?: string;
|
||||
vendor?: string;
|
||||
model?: string;
|
||||
firmware?: string;
|
||||
expiresIn?: string;
|
||||
}): Promise<DeviceLoginResult> {
|
||||
return api.post<DeviceLoginResult>('/api/web/test/device-login', body);
|
||||
}
|
||||
|
||||
/** 模拟「中控上报」(拿 SN + 长期 JWT,与真机同一套校验) */
|
||||
export function testScanReport(body: {
|
||||
sn: string;
|
||||
token: string;
|
||||
channelId: string;
|
||||
channelName?: string;
|
||||
barcode: string;
|
||||
scanTime?: string;
|
||||
}): Promise<ScanReportResult> {
|
||||
return api.post<ScanReportResult>('/api/web/test/scan', body);
|
||||
}
|
||||
|
||||
/** 查扫码登录码状态(公开接口,不需要登录) */
|
||||
export function fetchWechatStatus(codeOrSpm: string): Promise<WechatCodeStatus> {
|
||||
const query = new URLSearchParams(
|
||||
codeOrSpm.includes('.') ? { spm: codeOrSpm } : { code: codeOrSpm },
|
||||
);
|
||||
return api.get<WechatCodeStatus>(`/api/wechat/status?${query}`, { auth: false });
|
||||
}
|
||||
|
||||
/** 模拟扫码授权:用当前登录账号确认某个登录码(小程序里就是这一步) */
|
||||
export function confirmWechatLogin(codeOrSpm: string): Promise<{ status: string; code: string; user: { id: number } }> {
|
||||
const body = codeOrSpm.includes('.') ? { spm: codeOrSpm } : { code: codeOrSpm };
|
||||
return api.post<{ status: string; code: string; user: { id: number } }>('/api/wechat/confirm', body);
|
||||
}
|
||||
45
frontend/src/components/AppLayout.vue
Normal file
45
frontend/src/components/AppLayout.vue
Normal file
@ -0,0 +1,45 @@
|
||||
<script setup lang="ts">
|
||||
/** 业务页公用布局:左侧菜单 + 顶栏 + 内容区 */
|
||||
import { useRouter } from 'vue-router';
|
||||
import { clearToken, currentUser, displayName } from '@/composables/useAuth';
|
||||
|
||||
const router = useRouter();
|
||||
|
||||
const menus = [
|
||||
{ to: '/', label: '首页' },
|
||||
{ to: '/devices', label: '设备管理' },
|
||||
{ to: '/records', label: '扫码记录' },
|
||||
{ to: '/profile', label: '个人中心' },
|
||||
{ to: '/test', label: '测试页' },
|
||||
];
|
||||
|
||||
function logout() {
|
||||
// 令牌在本地,退出即清掉并回登录页(服务端无需回调)
|
||||
clearToken();
|
||||
router.replace({ name: 'login' });
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="layout">
|
||||
<aside class="sidebar">
|
||||
<div class="brand">云仓视频溯源系统</div>
|
||||
<nav>
|
||||
<RouterLink v-for="item in menus" :key="item.to" :to="item.to">{{ item.label }}</RouterLink>
|
||||
</nav>
|
||||
<div class="me">
|
||||
<div>{{ displayName(currentUser) }}</div>
|
||||
<a href="#" @click.prevent="logout">退出登录</a>
|
||||
</div>
|
||||
</aside>
|
||||
<div class="main">
|
||||
<header class="topbar">
|
||||
<slot name="title">控制台</slot>
|
||||
<span class="muted">云仓视频溯源系统</span>
|
||||
</header>
|
||||
<section class="content">
|
||||
<slot />
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user