{"_id":"@bigworm/bigworm-boot","name":"@bigworm/bigworm-boot","dist-tags":{"latest":"8.3.1"},"versions":{"8.3.1":{"name":"@bigworm/bigworm-boot","version":"8.3.1","description":"BigWorm Bootstrap 前端框架","main":"dist/cjs/index.js","module":"dist/esm/index.js","browser":"dist/umd/index.js","types":"dist/esm/index.d.ts","sideEffects":false,"exports":{".":{"types":"./dist/esm/index.d.ts","import":"./dist/esm/index.js","require":"./dist/cjs/index.js","browser":"./dist/umd/index.js","default":"./dist/cjs/index.js"}},"engines":{"node":">=14.0.0"},"scripts":{"clean":"rm -rf dist","build:esm":"tsc -p tsconfig.esm.json","build:cjs":"tsc -p tsconfig.cjs.json","build:umd":"NODE_OPTIONS= npx webpack --config webpack.config.js","build":"npm run clean && npm run build:esm && npm run build:cjs && npm run build:umd","minify":"NODE_OPTIONS= node scripts/minify.js","build:all":"npm run build && npm run minify","verify:pack":"node ../scripts/verify-pack.js","test":"jest","test:watch":"jest --watch","test:coverage":"jest --coverage","prepublishOnly":"npm run verify:pack && npm run build:all"},"keywords":["bigworm","bigworm-boot"],"author":{"name":"郑淑卿","email":"xunfeng@bigworm.com.cn"},"license":"BSL-1.1","devDependencies":{"@bigworm/bigworm-envelope":"workspace:*","@types/axios-mock-adapter":"^1.9.0","@types/jest":"^29.5.0","@types/node":"^18.19.111","axios":"^1.13.2","axios-mock-adapter":"^2.1.0","formdata-polyfill":"^4.0.10","glob":"^10.3.10","jest":"^29.5.0","terser":"^5.44.1","terser-webpack-plugin":"^5.3.10","ts-jest":"^29.1.0","ts-loader":"^9.5.1","typescript":"^5.0.4","undici":"^7.18.2","webpack":"^5.89.0","webpack-cli":"^5.1.4"},"peerDependencies":{"@bigworm/bigworm-envelope":"^8.3.1","crypto-js":"^4.2.0","jsencrypt":"^3.5.4","sm-crypto":"^0.3.13"},"publishConfig":{"access":"public"},"repository":{"type":"git","url":""},"_id":"@bigworm/bigworm-boot@8.3.1","gitHead":"a0b830c2684ebfdb33e05f7c596f18afc52a43c2","_nodeVersion":"20.19.4","_npmVersion":"10.8.2","dist":{"integrity":"sha512-apdDShE+IPFihTNL2PHk6fVlh+HZaS/JqurFr0pK/MLhPbbPd7NNOAcVcuRuYLF/9wR0UH8ghNHShEV7VK2B9Q==","shasum":"2a220788bfbb6a5c1e739b19f257704660ed59e7","tarball":"https://registry.npmjs.org/@bigworm/bigworm-boot/-/bigworm-boot-8.3.1.tgz","fileCount":85,"unpackedSize":568462,"signatures":[{"keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U","sig":"MEUCIEGj6s0O3kPd5WBMDj266DsSXoMdx/p9rs0I6C7rkI9UAiEA/M/778eeHao5PFaBWfl5wB3Dkr6d4BJ4P5e7gddNcBA="}]},"_npmUser":{"name":"mybigworm","email":"xunfeng@bigworm.com.cn"},"directories":{},"maintainers":[{"name":"mybigworm","email":"xunfeng@bigworm.com.cn"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages-npm-production","tmp":"tmp/bigworm-boot_8.3.1_1782287690103_0.1753365056908176"},"_hasShrinkwrap":false}},"time":{"created":"2026-06-24T07:54:49.924Z","8.3.1":"2026-06-24T07:54:50.264Z","modified":"2026-06-24T07:54:50.520Z"},"maintainers":[{"name":"mybigworm","email":"xunfeng@bigworm.com.cn"}],"description":"BigWorm Bootstrap 前端框架","keywords":["bigworm","bigworm-boot"],"repository":{"type":"git","url":""},"author":{"name":"郑淑卿","email":"xunfeng@bigworm.com.cn"},"license":"BSL-1.1","readme":"# @bigworm/bigworm-boot\n\n[![Version](https://img.shields.io/badge/version-8.3.1-green.svg)](package.json)\n[![Node](https://img.shields.io/badge/node-%3E%3D14.0.0-brightgreen.svg)](package.json)\n\n前端 HTTP 通信框架。提供 `EnvelopeAxios`（Envelope 协议）和 `OpenAxios`（常规 JSON）双客户端，内置数字签名（HMAC/RSA/SM2）、JWT 认证、requestId/timestamp 防重放校验、文件上传/下载、HTTP 调试日志等功能。\n\n## 安装\n\n```bash\nnpm install @bigworm/bigworm-boot\n```\n\n**对等依赖（按需安装）：**\n\n```bash\nnpm install crypto-js@^4.2.0   # HMAC 签名必需\nnpm install jsencrypt@^3.5.4   # RSA 签名可选\nnpm install sm-crypto@^0.3.13  # SM2 国密可选\n```\n\n## 模块结构\n\n```\nsrc/\n├── core/\n│   ├── EnvelopeAxios.ts      # Envelope 协议 HTTP 客户端\n│   └── OpenAxios.ts          # 常规 JSON HTTP 客户端\n├── config/\n│   ├── SecurityConfig.ts     # 统一安全配置接口及默认值\n│   ├── EnvelopeAxiosConfig.ts\n│   ├── OpenAxiosConfig.ts\n│   ├── RequestConfig.ts\n│   ├── UploadConfig.ts\n│   ├── DownloadConfig.ts\n│   └── StreamConfig.ts\n├── crypto/\n│   ├── CryptoAdapterFactory.ts\n│   ├── HmacAdapter.ts\n│   ├── RSAAdapter.ts\n│   └── SM2Adapter.ts\n├── tools/\n│   ├── JwtUtil.ts            # JWT Token 管理\n│   ├── HmacUtil.ts           # HMAC 用户专属密钥管理\n│   ├── SignatureUtil.ts\n│   ├── SecurityUtil.ts\n│   └── DebugUtil.ts          # HTTP 调试日志\n└── error/\n    └── CheckedError.ts\n```\n\n---\n\n## 核心：EnvelopeAxios\n\n用于与 bigworm 后端 Envelope 协议接口通信。\n\n### 初始化\n\n```typescript\nimport { EnvelopeAxios } from '@bigworm/bigworm-boot'\n\nconst http = EnvelopeAxios.getInstance({\n  baseURL: 'http://localhost:8080',\n  timeout: 30000,\n  onError: (error) => ElMessage.error(error.message), // 全局错误回调\n  security: {\n    // 所有选项均有默认值，下方为默认值说明\n    envelopeEnabled: true,       // 启用 Envelope 报文验证\n    validateRequestId: true,     // 校验响应 requestId 与请求一致\n    validateTimestamp: true,     // 校验响应时间戳防重放\n    maxTimeDiff: 300000,         // 最大时间差（毫秒，默认 5 分钟）\n    signatureEnabled: true,      // 启用数字签名\n    requestAlgorithm: 'hmac',    // 请求签名算法：'hmac' | 'rsa' | 'sm2'\n    responseAlgorithm: 'rsa',    // 响应验签算法：'rsa' | 'sm2' | 'hmac'\n    signRequest: true,           // 对请求签名\n    verifyResponse: true,        // 验证响应签名\n    useUserHmacKey: true,        // 启用用户专属 HMAC 密钥\n    publicKey: undefined,        // 后端公钥（未配置则用内置默认公钥）\n    hmacKey: undefined,          // 自定义默认 HMAC 密钥\n    authType: 'jwt',             // 认证类型：'jwt' | 'session'\n    jwtHeaderName: 'Authorization',\n    jwtTokenPrefix: 'Bearer ',\n    jwtStorageType: 'localStorage'\n  }\n})\n```\n\n> 配置优先级：`getInstance(config)` > `globalThis.CONFIG.security` > 默认值\n\n### 请求方法\n\n```typescript\n// POST\nconst response = await http.post('/api/user/login', requestEnvelope)\n\n// GET（params 可以是 Record 或 Envelope）\nconst response = await http.get('/api/user/info', { userId: '123' })\n\n// 文件上传\nconst response = await http.upload('/api/file/upload', formData, {\n  onUploadProgress: (e) => console.log(`${Math.round(e.loaded * 100 / e.total!)}%`)\n})\n\n// 文件下载\nconst result = await http.download('/api/file/download', requestEnvelope, {\n  onDownloadProgress: (e) => console.log(`${Math.round(e.loaded * 100 / e.total!)}%`)\n})\n// result.blob: Blob, result.filename: string\nconst url = URL.createObjectURL(result.blob)\n```\n\n### 拦截器\n\n```typescript\n// 请求拦截（添加业务字段）\nconst reqId = http.addRequestInterceptor((envelope) => {\n  envelope.header().entity().data().setStringItem('sessionId', getSessionId())\n  return envelope\n})\n\n// 响应拦截（统一错误处理）\nconst resId = http.addResponseInterceptor((envelope) => {\n  const success = envelope.header().entity().data().getStringItem('success')\n  if (success === 'false') {\n    const msg = envelope.header().entity().data().getStringItem('message')\n    if (msg?.includes('未登录')) window.location.href = '/login'\n  }\n  return envelope\n})\n\n// 移除拦截器\nhttp.removeRequestInterceptor(reqId)\nhttp.removeResponseInterceptor(resId)\n```\n\n---\n\n## 核心：OpenAxios\n\n与 `EnvelopeAxios` API 完全一致，区别是不强制 Envelope 协议，接收和返回任意 JSON。\n\n```typescript\nimport { OpenAxios } from '@bigworm/bigworm-boot'\n\nconst http = OpenAxios.getInstance({\n  baseURL: 'https://api.example.com',\n  security: { signRequest: true, verifyResponse: true, requestAlgorithm: 'rsa' }\n})\n\nconst data = await http.post('/api/login', { username: 'admin', password: '123' })\nconst info = await http.get('/api/user/info', { userId: '123' })\n```\n\n---\n\n## 安全配置详解\n\n### 签名算法\n\n| 方向 | 配置项 | 可选值 | 说明 |\n|------|--------|--------|------|\n| 请求签名（前端→后端） | `requestAlgorithm` | `hmac`（默认）/ `rsa` / `sm2` | HMAC 性能最优，推荐 |\n| 响应验签（后端→前端） | `responseAlgorithm` | `rsa`（默认）/ `sm2` / `hmac` | 需与后端 `response-algorithm` 一致 |\n\n签名内容放入 HTTP Header `X-Signature`；requestId 和 timestamp 同时放入 `X-Request-ID`、`X-Timestamp` Header 以及 `envelope.header` 双通道传输（兼容防火墙过滤 Header 的场景）。\n\n### 用户专属 HMAC（`useUserHmacKey`）\n\n登录后通过 `HmacUtil.deriveKey(password, account)` 派生用户专属密钥，再通过 `HmacUtil.saveKey(key)` 保存。框架在初始化时自动从 storage 恢复并注入签名器，实现每个用户使用独立的 HMAC 密钥。需与后端 `server.security.signature.use-user-hmac-key` 保持一致。\n\n### 全局配置（`globalThis.CONFIG`）\n\n框架从 `globalThis.CONFIG.security` 读取配置，支持在运行时注入（Vite 环境变量、Webpack process.env、或运行时配置文件均可）：\n\n```typescript\n// 在 main.ts / index.ts 中提前设置\n;(globalThis as any).CONFIG = {\n  security: {\n    publicKey: import.meta.env.VITE_PUBLIC_KEY,\n    requestAlgorithm: 'hmac',\n    responseAlgorithm: 'rsa'\n  }\n}\n```\n\n---\n\n## JwtUtil — JWT Token 管理\n\n```typescript\nimport { JwtUtil } from '@bigworm/bigworm-boot'\n\n// 登录成功后保存 token\nJwtUtil.saveToken('eyJhbGci...')\n\n// 获取 token\nconst token = JwtUtil.getToken()  // 返回 string | null\n\n// 解析 payload（仅客户端解码，不验证签名）\nconst payload = JwtUtil.parseToken(token)\nconsole.log(payload?.sub, payload?.exp)\n\n// 检查是否过期\nconst expired = JwtUtil.isTokenExpired()  // true | false | null\n\n// 获取剩余有效时间（毫秒）\nconst remaining = JwtUtil.getTokenRemainingTime()\n\n// 登出时清除\nJwtUtil.clearToken()\n\n// 切换存储类型（默认 localStorage）\nJwtUtil.setStorageType('sessionStorage')\n```\n\n---\n\n## HmacUtil — 用户专属 HMAC 密钥管理\n\n```typescript\nimport { HmacUtil } from '@bigworm/bigworm-boot'\n\n// 登录成功后：派生 + 保存用户专属密钥（PBKDF2，与后端算法参数一致）\nconst key = HmacUtil.deriveKey(password, account)\nHmacUtil.saveKey(key)\n\n// 获取当前用户密钥\nconst key = HmacUtil.getKey()  // string | null\n\n// 登出时清除\nHmacUtil.clearKey()\n\n// 切换存储类型（默认 localStorage）\nHmacUtil.setStorageType('sessionStorage')\n```\n\n---\n\n## HTTP 调试日志\n\n开发环境（`DEBUG` 日志级别）下自动输出请求/响应详情，生产环境零开销：\n\n```\n═══════════════════════════════════════════\n📥 HTTP 请求信息\n═══════════════════════════════════════════\n📍 请求路径: POST /api/user/login\n📋 HTTP 请求头:\n   X-Request-ID: req-abc123...\n   X-Timestamp: 1736604123456\n   X-Signature: MIIBIjAN...\n📦 请求体:\n{\n  \"header\": { \"default\": { \"requestid\": \"req-abc123...\", \"timestamp\": \"...\" } },\n  \"body\":   { \"default\": { \"username\": \"admin\" } }\n}\n═══════════════════════════════════════════\n```\n\n---\n\n## 构建\n\n```bash\nnpm run build        # ESM + CJS + UMD\nnpm run build:esm    # ES Module\nnpm run build:cjs    # CommonJS\nnpm run build:umd    # UMD（浏览器直接使用）\nnpm run build:all    # 构建并压缩（发布前使用）\n```\n\n**输出格式：**\n- `dist/esm/` — ES Module（含 `.d.ts` 类型声明）\n- `dist/cjs/` — CommonJS\n- `dist/umd/` — UMD\n\n## 测试\n\n```bash\nnpm test              # 运行所有测试\nnpm run test:watch    # 监听模式\nnpm run test:coverage # 覆盖率报告\n```\n","readmeFilename":"README.md","_rev":"1-ec7a6abd7a93d5014792d6a494717986"}