@bigworm/bigworm-boot
v8.3.1
Published
BigWorm Bootstrap 前端框架
Readme
@bigworm/bigworm-boot
前端 HTTP 通信框架。提供 EnvelopeAxios(Envelope 协议)和 OpenAxios(常规 JSON)双客户端,内置数字签名(HMAC/RSA/SM2)、JWT 认证、requestId/timestamp 防重放校验、文件上传/下载、HTTP 调试日志等功能。
安装
npm install @bigworm/bigworm-boot对等依赖(按需安装):
npm install crypto-js@^4.2.0 # HMAC 签名必需
npm install jsencrypt@^3.5.4 # RSA 签名可选
npm install sm-crypto@^0.3.13 # SM2 国密可选模块结构
src/
├── core/
│ ├── EnvelopeAxios.ts # Envelope 协议 HTTP 客户端
│ └── OpenAxios.ts # 常规 JSON HTTP 客户端
├── config/
│ ├── SecurityConfig.ts # 统一安全配置接口及默认值
│ ├── EnvelopeAxiosConfig.ts
│ ├── OpenAxiosConfig.ts
│ ├── RequestConfig.ts
│ ├── UploadConfig.ts
│ ├── DownloadConfig.ts
│ └── StreamConfig.ts
├── crypto/
│ ├── CryptoAdapterFactory.ts
│ ├── HmacAdapter.ts
│ ├── RSAAdapter.ts
│ └── SM2Adapter.ts
├── tools/
│ ├── JwtUtil.ts # JWT Token 管理
│ ├── HmacUtil.ts # HMAC 用户专属密钥管理
│ ├── SignatureUtil.ts
│ ├── SecurityUtil.ts
│ └── DebugUtil.ts # HTTP 调试日志
└── error/
└── CheckedError.ts核心:EnvelopeAxios
用于与 bigworm 后端 Envelope 协议接口通信。
初始化
import { EnvelopeAxios } from '@bigworm/bigworm-boot'
const http = EnvelopeAxios.getInstance({
baseURL: 'http://localhost:8080',
timeout: 30000,
onError: (error) => ElMessage.error(error.message), // 全局错误回调
security: {
// 所有选项均有默认值,下方为默认值说明
envelopeEnabled: true, // 启用 Envelope 报文验证
validateRequestId: true, // 校验响应 requestId 与请求一致
validateTimestamp: true, // 校验响应时间戳防重放
maxTimeDiff: 300000, // 最大时间差(毫秒,默认 5 分钟)
signatureEnabled: true, // 启用数字签名
requestAlgorithm: 'hmac', // 请求签名算法:'hmac' | 'rsa' | 'sm2'
responseAlgorithm: 'rsa', // 响应验签算法:'rsa' | 'sm2' | 'hmac'
signRequest: true, // 对请求签名
verifyResponse: true, // 验证响应签名
useUserHmacKey: true, // 启用用户专属 HMAC 密钥
publicKey: undefined, // 后端公钥(未配置则用内置默认公钥)
hmacKey: undefined, // 自定义默认 HMAC 密钥
authType: 'jwt', // 认证类型:'jwt' | 'session'
jwtHeaderName: 'Authorization',
jwtTokenPrefix: 'Bearer ',
jwtStorageType: 'localStorage'
}
})配置优先级:
getInstance(config)>globalThis.CONFIG.security> 默认值
请求方法
// POST
const response = await http.post('/api/user/login', requestEnvelope)
// GET(params 可以是 Record 或 Envelope)
const response = await http.get('/api/user/info', { userId: '123' })
// 文件上传
const response = await http.upload('/api/file/upload', formData, {
onUploadProgress: (e) => console.log(`${Math.round(e.loaded * 100 / e.total!)}%`)
})
// 文件下载
const result = await http.download('/api/file/download', requestEnvelope, {
onDownloadProgress: (e) => console.log(`${Math.round(e.loaded * 100 / e.total!)}%`)
})
// result.blob: Blob, result.filename: string
const url = URL.createObjectURL(result.blob)拦截器
// 请求拦截(添加业务字段)
const reqId = http.addRequestInterceptor((envelope) => {
envelope.header().entity().data().setStringItem('sessionId', getSessionId())
return envelope
})
// 响应拦截(统一错误处理)
const resId = http.addResponseInterceptor((envelope) => {
const success = envelope.header().entity().data().getStringItem('success')
if (success === 'false') {
const msg = envelope.header().entity().data().getStringItem('message')
if (msg?.includes('未登录')) window.location.href = '/login'
}
return envelope
})
// 移除拦截器
http.removeRequestInterceptor(reqId)
http.removeResponseInterceptor(resId)核心:OpenAxios
与 EnvelopeAxios API 完全一致,区别是不强制 Envelope 协议,接收和返回任意 JSON。
import { OpenAxios } from '@bigworm/bigworm-boot'
const http = OpenAxios.getInstance({
baseURL: 'https://api.example.com',
security: { signRequest: true, verifyResponse: true, requestAlgorithm: 'rsa' }
})
const data = await http.post('/api/login', { username: 'admin', password: '123' })
const info = await http.get('/api/user/info', { userId: '123' })安全配置详解
签名算法
| 方向 | 配置项 | 可选值 | 说明 |
|------|--------|--------|------|
| 请求签名(前端→后端) | requestAlgorithm | hmac(默认)/ rsa / sm2 | HMAC 性能最优,推荐 |
| 响应验签(后端→前端) | responseAlgorithm | rsa(默认)/ sm2 / hmac | 需与后端 response-algorithm 一致 |
签名内容放入 HTTP Header X-Signature;requestId 和 timestamp 同时放入 X-Request-ID、X-Timestamp Header 以及 envelope.header 双通道传输(兼容防火墙过滤 Header 的场景)。
用户专属 HMAC(useUserHmacKey)
登录后通过 HmacUtil.deriveKey(password, account) 派生用户专属密钥,再通过 HmacUtil.saveKey(key) 保存。框架在初始化时自动从 storage 恢复并注入签名器,实现每个用户使用独立的 HMAC 密钥。需与后端 server.security.signature.use-user-hmac-key 保持一致。
全局配置(globalThis.CONFIG)
框架从 globalThis.CONFIG.security 读取配置,支持在运行时注入(Vite 环境变量、Webpack process.env、或运行时配置文件均可):
// 在 main.ts / index.ts 中提前设置
;(globalThis as any).CONFIG = {
security: {
publicKey: import.meta.env.VITE_PUBLIC_KEY,
requestAlgorithm: 'hmac',
responseAlgorithm: 'rsa'
}
}JwtUtil — JWT Token 管理
import { JwtUtil } from '@bigworm/bigworm-boot'
// 登录成功后保存 token
JwtUtil.saveToken('eyJhbGci...')
// 获取 token
const token = JwtUtil.getToken() // 返回 string | null
// 解析 payload(仅客户端解码,不验证签名)
const payload = JwtUtil.parseToken(token)
console.log(payload?.sub, payload?.exp)
// 检查是否过期
const expired = JwtUtil.isTokenExpired() // true | false | null
// 获取剩余有效时间(毫秒)
const remaining = JwtUtil.getTokenRemainingTime()
// 登出时清除
JwtUtil.clearToken()
// 切换存储类型(默认 localStorage)
JwtUtil.setStorageType('sessionStorage')HmacUtil — 用户专属 HMAC 密钥管理
import { HmacUtil } from '@bigworm/bigworm-boot'
// 登录成功后:派生 + 保存用户专属密钥(PBKDF2,与后端算法参数一致)
const key = HmacUtil.deriveKey(password, account)
HmacUtil.saveKey(key)
// 获取当前用户密钥
const key = HmacUtil.getKey() // string | null
// 登出时清除
HmacUtil.clearKey()
// 切换存储类型(默认 localStorage)
HmacUtil.setStorageType('sessionStorage')HTTP 调试日志
开发环境(DEBUG 日志级别)下自动输出请求/响应详情,生产环境零开销:
═══════════════════════════════════════════
📥 HTTP 请求信息
═══════════════════════════════════════════
📍 请求路径: POST /api/user/login
📋 HTTP 请求头:
X-Request-ID: req-abc123...
X-Timestamp: 1736604123456
X-Signature: MIIBIjAN...
📦 请求体:
{
"header": { "default": { "requestid": "req-abc123...", "timestamp": "..." } },
"body": { "default": { "username": "admin" } }
}
═══════════════════════════════════════════构建
npm run build # ESM + CJS + UMD
npm run build:esm # ES Module
npm run build:cjs # CommonJS
npm run build:umd # UMD(浏览器直接使用)
npm run build:all # 构建并压缩(发布前使用)输出格式:
dist/esm/— ES Module(含.d.ts类型声明)dist/cjs/— CommonJSdist/umd/— UMD
测试
npm test # 运行所有测试
npm run test:watch # 监听模式
npm run test:coverage # 覆盖率报告