@dplugin/core 0.0.0-stage → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,409 @@
1
- # Temporary Holding Version
1
+ # @dplugin/core
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ DPlugin 前端登录与请求 SDK。零运行时依赖(不用 axios / crypto-js / jsencrypt),浏览器原生
4
+ `fetch` + `WebCrypto`。
5
+
6
+ 两种模式**按 origin 自动选择**,业务代码几乎不用区分:
7
+
8
+ | 模式 | 触发条件 | 凭证 | 每请求形态 |
9
+ |---|---|---|---|
10
+ | **cookie** | 页面与接口**同源**(scheme + host + port 全等) | 服务端下发的 HttpOnly Cookie | 无签名参数,浏览器自动带 Cookie |
11
+ | **sign** | 页面与接口**跨源** | `access`(localStorage) | 一个 `dsign` 签名信封(query 参数) |
12
+
13
+ ```js
14
+ setup({apiBase: ''}) // 同源 → cookie 模式
15
+ setup({apiBase: 'https://api.other.com'}) // 跨源 → sign 模式
16
+ setup({apiBase: '', mode: 'sign'}) // 也可以强制指定
17
+ ```
18
+
19
+ 两条链路在服务端是同一套 sso/域会话,互不干扰。
20
+
21
+ ---
22
+
23
+ ## 安装
24
+
25
+ **npm**
26
+
27
+ ```bash
28
+ npm i @dplugin/core
29
+ ```
30
+
31
+ **CDN(UMD,挂到 `window.DPluginCore`)**
32
+
33
+ ```html
34
+ <script src="https://unpkg.com/@dplugin/core@2.0.0/dist/index.umd.js"></script>
35
+ <script>
36
+ const {setup, login, request, logout} = window.DPluginCore;
37
+ </script>
38
+ ```
39
+
40
+ **本地源码调试**(还没发版时)
41
+
42
+ ```bash
43
+ # 本目录先构建一次,dist/ 不入库
44
+ npm install && npm run build
45
+
46
+ # 页面 package.json
47
+ "@dplugin/core": "file:../dplugin-login-umdjs-core"
48
+ ```
49
+
50
+ ---
51
+
52
+ ## 快速上手
53
+
54
+ ### 1) 入口初始化(每个应用只调一次)
55
+
56
+ ```js
57
+ // main.js
58
+ import {setup} from '@dplugin/core';
59
+
60
+ setup({
61
+ apiBase: import.meta.env.VITE_API_BASE_URL, // '' = 同源
62
+ loginUrl: '/login/',
63
+ onError: ({code, message}) => {
64
+ // 业务错误统一提示(登录态的 500900 不会走到这里)
65
+ Modal.error({title: '操作失败[' + code + ']', content: message});
66
+ },
67
+ onLogout: () => router.replace('/login')
68
+ });
69
+ ```
70
+
71
+ ### 2) 登录(登录页)
72
+
73
+ ```js
74
+ import {login} from '@dplugin/core';
75
+
76
+ await login('/api/unsafe/dplugin/user/login/pwd/submit', {username, password});
77
+ location.href = '/';
78
+ ```
79
+
80
+ `login()` 收的是**登录方式的 submit 接口**,所以手机验证码登录只是换接口和参数:
81
+
82
+ ```js
83
+ await login('/api/unsafe/dplugin/user/login/phone/submit', {phone, code});
84
+ ```
85
+
86
+ 内部流程(业务不需要管):
87
+
88
+ | 模式 | 步骤 |
89
+ |---|---|
90
+ | cookie | `submit` → 种临时 token(`dp_dvt`)→ 轮询 `/c/verify` → `/c/token` 换业务凭证 |
91
+ | sign | `submit`(上报 sso 公钥)→ 轮询 `/s/verify` → `/s/token` 换 access(上报域公钥) |
92
+
93
+ ### 3) 业务请求
94
+
95
+ ```js
96
+ import {request} from '@dplugin/core';
97
+
98
+ // 返回值就是后端 data
99
+ const user = await request('/api/safe/dplugin/user/get');
100
+ await request('/api/safe/dplugin/user/update', {nickname: 'x'});
101
+
102
+ // 匿名接口:不要求登录,失效也不跳登录页
103
+ const setting = await request('/api/unsafe/dplugin/login/page/setting', {}, {auth: false});
104
+ ```
105
+
106
+ 业务错误抛 `BizError`(同时触发一次 `onError`)。
107
+
108
+ ### 4) 上传
109
+
110
+ ```js
111
+ import {upload} from '@dplugin/core';
112
+
113
+ await upload('/api/safe/dplugin/storage/upload', file, {bizType: 'avatar'}, {timeout: 60000});
114
+ ```
115
+
116
+ ### 5) 退出
117
+
118
+ ```js
119
+ import {logout} from '@dplugin/core';
120
+ await logout(); // 服务端会话 + 本地状态一起清
121
+ ```
122
+
123
+ ---
124
+
125
+ ## 判断登录态
126
+
127
+ ```js
128
+ import {isLogin, getState, verifyLogin} from '@dplugin/core';
129
+
130
+ isLogin(); // 同步、不发请求:「本地看起来是否已登录」
131
+ getState(); // {mode, loggedIn, hasAccess, sid, ds}
132
+ await verifyLogin();// 可选:向服务端确认一次,返回 true / false
133
+ ```
134
+
135
+ 两种模式下 `isLogin()` 的含义:
136
+
137
+ - **sign**:localStorage 里有 access 或 sid 就是 true(access 过期也能静默恢复)
138
+ - **cookie**:凭证在 HttpOnly Cookie 里,JS 读不到,只代表「上次登录过的标记」
139
+
140
+ **真正是否有效,以第一次 `request()` 的结果为准**:失效时 SDK 会自动续期一次,续不回来才抛 `AuthError`。
141
+
142
+ ```js
143
+ // 页面加载时的典型写法
144
+ if (!isLogin()) {
145
+ router.replace('/login');
146
+ } else {
147
+ // 可选:需要准确判断时再打一次服务端
148
+ // if (!await verifyLogin()) router.replace('/login');
149
+ }
150
+ ```
151
+
152
+ ---
153
+
154
+ ## 会话失效会自动续期
155
+
156
+ 业务请求返回 `500900` 时,SDK 自动续期一次再重发:
157
+
158
+ | 模式 | 续期 |
159
+ |---|---|
160
+ | cookie | `POST /api/unsafe/dplugin/login/c/refresh`(凭 Cookie,无参数) |
161
+ | sign | `POST /api/unsafe/dplugin/login/s/refresh?dsign=…`(`BIZ` 信封,subject = 当前 access) |
162
+
163
+ 所以业务侧不用写任何续期逻辑:
164
+
165
+ ```js
166
+ try {
167
+ const data = await request('/api/safe/xxx');
168
+ } catch (e) {
169
+ if (isAuthError(e)) {
170
+ // 续期也救不回来:让用户重新登录(onLogout 已经回调过)
171
+ }
172
+ }
173
+ ```
174
+
175
+ ---
176
+
177
+ ## 配置项(`setup`)
178
+
179
+ | 字段 | 默认 | 说明 |
180
+ |---|---|---|
181
+ | `apiBase` | `''` | 接口前缀。`''` = 同源 |
182
+ | `mode` | `'auto'` | `'auto'` / `'cookie'` / `'sign'` |
183
+ | `loginUrl` | `'/login/'` | 仅当 `enableAuth: true` 时由 SDK 跳这里 |
184
+ | `enableAuth` | `false` | 默认**不**跳转:失效只清本地 + `onLogout` + 抛 `AuthError`,提示/跳转交给业务 |
185
+ | `timeout` | `15000` | 请求超时(毫秒) |
186
+ | `pollInterval` | `2000` | 登录轮询间隔(毫秒) |
187
+ | `pollMax` | `5` | 登录轮询次数,用完报「登录超时」 |
188
+ | `nativeGuard` | `'warn'` | 原生能力指纹检查:`warn` / `error` / `off` |
189
+ | `onError` | - | `({code, message, error})` 业务错误提示 |
190
+ | `onLogin` | - | `(state)` 登录 / 静默恢复成功 |
191
+ | `onLogout` | - | `(reason)` `'logout'` 主动退出、`'expired'` 会话失效 |
192
+
193
+ ---
194
+
195
+ ## 完整 API
196
+
197
+ | 导出 | 说明 |
198
+ |---|---|
199
+ | `setup(options)` | 初始化,每个应用一次 |
200
+ | `login(submitApi, params)` | 完整登录流程,返回 `state` |
201
+ | `logout()` | 退出(凭证过期会先续期再退,保证服务端会话被删) |
202
+ | `request(api, data?, options?)` | 业务请求,返回 `data`;自动静默恢复 / 续期 / 重试一次 |
203
+ | `upload(api, file, data?, options?)` | multipart 上传;`options.timeout` 可单独放宽 |
204
+ | `isLogin()` | 本地登录态(同步,不发请求) |
205
+ | `getState()` | `{mode, loggedIn, hasAccess, sid, ds}` |
206
+ | `verifyLogin({force?})` | 服务端确认登录态;`{force:true}` 强制换一次凭证 |
207
+ | `getMode()` | `'cookie'` / `'sign'` |
208
+ | `clear()` | 只清本地(不调服务端) |
209
+ | `expire(reason?)` | 判定失效:清本地 + 回调 +(`enableAuth` 时)跳登录页 |
210
+ | `auth` | 门面:`{login, logout, isLogin, getState, restore}` |
211
+ | `store` | 存储视图(`access` / `sid` / `ds` / `cookie` / `exp`),一般不用直接碰 |
212
+ | `BizError` / `AuthError` / `CODE` / `isAuthError` | 错误类型与码值 |
213
+
214
+ > `refresh` **不导出**:后端规定凭证必须已过期才允许续期,手动调会把会话弄坏。续期由 SDK 在收到 `500900` 后自动做。
215
+
216
+ ---
217
+
218
+ ## 错误处理
219
+
220
+ 后端业务错误统一是 HTTP 200 + `{code, message, data}`;只有框架级异常才是 5xx。
221
+
222
+ | code | 含义 | SDK 行为 |
223
+ |---|---|---|
224
+ | `200` | 成功 | 返回 `data` |
225
+ | `202` | 登录中(轮询) | 继续轮询,`pollMax` 用完报超时 |
226
+ | `500900` | 会话失效 | 自动续期一次 → 重发;仍失败抛 `AuthError` + `onLogout('expired')` |
227
+ | `500` | 通用业务错误(密码错误 / 平台不支持 / 重复请求 / 时钟异常) | 抛 `BizError` + `onError`,**不续期、不登出** |
228
+ | `401001` | 没有权限 | 抛 `BizError`,会话仍有效 |
229
+ | `403` | 非法来源(CORS / 域名不符) | 环境配置问题 |
230
+ | `404` | 接口不存在 | 接口没在网关 api 表登记 |
231
+ | `NETWORK` / `TIMEOUT` | 网络异常 / 超时 | `BizError`,**不会**登出 |
232
+
233
+ ```js
234
+ import {BizError, isAuthError} from '@dplugin/core';
235
+
236
+ try {
237
+ await request('/api/safe/xxx');
238
+ } catch (e) {
239
+ if (isAuthError(e)) { /* 重新登录 */ }
240
+ else if (e instanceof BizError) { /* e.code / e.message */ }
241
+ }
242
+ ```
243
+
244
+ ---
245
+
246
+ ## 常见问题
247
+
248
+ **1. 报「crypto.subtle 不存在」**
249
+
250
+ `crypto.subtle` 只在**安全上下文**存在:`https://`、`file://`、`http://localhost`、`http://127.0.0.1`。
251
+ 用内网 IP(`http://192.168.x.x`)调试就会拿不到 —— 换 localhost 或配本地 https。
252
+ **cookie 模式不需要 WebCrypto**,不受影响。
253
+
254
+ **2. 跨源时接口变慢 / 多了一次 OPTIONS**
255
+
256
+ SDK 用 `Content-Type: text/plain` + 参数放 query,本来就是**CORS 简单请求,不触发预检**。
257
+ 业务侧不要给这些请求加自定义 header,否则预检又回来了。
258
+
259
+ **3. `a.com` 访问 `api.a.com` 走的是哪个模式**
260
+
261
+ **sign**。同源判定是 origin 全等:`https://a.com` ≠ `https://api.a.com`。
262
+
263
+ **4. `dsign` 为什么只出现在 URL 上、且只能是 `BIZ`**
264
+
265
+ 网关只放行 URL 上的 `BIZ` 信封;换 code / 换 access / 续期的信封都放请求体里。
266
+
267
+ **5. 退出后 Cookie 还在**
268
+
269
+ 不要自己清。退出接口会 `Set-Cookie` 清 `dp_sid`/`dp_token`;手动清会留下服务端孤儿会话。
270
+
271
+ **6. 登录成功但跳转后没会话**
272
+
273
+ 登录页和应用必须**同源**。放 `login.xxx.com` + `app.xxx.com` 会变成「登录成功 → 跳应用 → 没会话 → 回登录页」。
274
+
275
+ ---
276
+
277
+ ## 部署要求
278
+
279
+ 1. **https 或 localhost**(sign 模式):`crypto.subtle` 在非安全上下文不存在。
280
+ 2. **登录页与应用同源**:`localStorage` / `IndexedDB` 不跨源,且后端 `sso.domain` 取的是登录时的 Origin 主机名。
281
+ 3. **网关 CORS 白名单**要包含前端 origin(`dplugin.cors.allowed_origins`)。
282
+ 4. **接口要在网关 api 表登记**(查不到直接 404)。
283
+ 5. 反向代理**不要改写** `/api/**` 的路径和 query —— 签名原文包含路径。
284
+ 6. cookie 模式下,接口域名前面的反代要能把 `Origin` 头透传(网关用它校验 `domain`)。
285
+
286
+ ---
287
+
288
+ ## 附录:签名协议(只在需要排查时看)
289
+
290
+ 四个场景共用一张模板,后端 `com.dplugin.starter.core.sign.SignUtils` 与前端 `src/sign.js` 逐字节一致
291
+ (有跨语言比对测试):
292
+
293
+ ```
294
+ OP \n METHOD \n PATH \n ORIGIN(小写) \n DS \n TS(毫秒) \n SUBJECT \n DNA \n REDIRECT
295
+ ```
296
+
297
+ 固定 9 段,缺失的段写 `-`。
298
+
299
+ | OP | 场景 | METHOD/PATH | SUBJECT | DNA/REDIRECT | 私钥 |
300
+ |---|---|---|---|---|---|
301
+ | `BIZ` | 业务接口(网关验) | 实际值 | access | `-` | domain |
302
+ | `VERIFY` | 临时 token 轮询换 code(login 验) | 实际值 | 临时 token | 都有 | sso |
303
+ | `VERIFY_SID` | 已登录用 sid 换 code(login 验,**只在登录域**) | 实际值 | sid | 都有 | sso |
304
+ | `TOKEN` | code 换 access(login 验) | `-` | 一次性 code | dna | domain |
305
+
306
+ ### 单参数信封
307
+
308
+ ```
309
+ dsign = OP.SUBJECT.DS.TS.SIGN
310
+ ```
311
+
312
+ | 接口 | 携带位置 | 其它字段 |
313
+ |---|---|---|
314
+ | 业务 `/api/**` `/mgr/**` | URL query `dsign` | body 就是业务参数 |
315
+ | `logout` | URL query `dsign` | 无 body |
316
+ | `/s/refresh` | URL query `dsign`(OP=`BIZ`) | 无 body |
317
+ | `/s/verify` | body `dsign` | `dna`、`redirect` |
318
+ | `/s/token` | body `dsign` | `pk` |
319
+
320
+ > **硬约束**:URL 上的 `dsign` **只能是 `BIZ`**;`VERIFY`/`VERIFY_SID`/`TOKEN` 必须放请求体。
321
+ > 测试里有一条断言守着它(`URL 上的 dsign 全部是 BIZ`)。
322
+
323
+ ### 为什么 `dsign` 放 query 而不是请求头
324
+
325
+ 请求体用 `Content-Type: text/plain`(CORS 简单请求允许的类型),加上没有自定义头,
326
+ 跨域时**不会发 OPTIONS 预检**,每个接口少一次往返。框架侧 `JSONHttpMessageConverter.body()`
327
+ 不看 Content-Type,直接读流按 JSON 解析,所以 `text/plain` 里放 JSON 完全正常。
328
+
329
+ 一旦把 `dsign` 挪到 `X-Dsig` 这类自定义头,就会重新触发预检 —— 省下的往返又还回去。
330
+
331
+ ### 其它硬约束
332
+
333
+ - `ORIGIN` 两边都转小写;`TS` 一律毫秒;
334
+ - `verify` / `token` 绑定 `D-Request-IP`:登录过程中 IP 变了会 `500900`;
335
+ - `dna` = `SHA-256(SPKI DER)` 的 Base64URL 无填充;
336
+ - 时间窗 300 秒;access Redis TTL 1800 秒;临时 token 5 分钟;code 60 秒且 `GETDEL`;
337
+ - 设备只走信封的 `DS` 段,没有 `X-Device-Id` 头。
338
+
339
+ ## 附录:密钥与存储
340
+
341
+ | 内容 | 位置 | 说明 |
342
+ |---|---|---|
343
+ | `access` | localStorage `dplugin.access` | sign 模式业务信封的 SUBJECT,30 分钟 |
344
+ | `sid` | localStorage `dplugin.sid` | 静默恢复用 |
345
+ | `ds` | localStorage `dplugin.ds` | 设备凭证,服务端下发,**不要自己生成**;退出**不清**它(设备不是会话) |
346
+ | `exp` | localStorage `dplugin.exp` | 到期时间,仅用于本地展示 |
347
+ | `cookie` | localStorage `dplugin.cookie` | cookie 模式的「已登录」标记(HttpOnly 读不到,只能记标记) |
348
+ | sso 私钥 | IndexedDB `dplugin-auth/keys.sso` | 签 `VERIFY` / `VERIFY_SID` |
349
+ | 域私钥 | IndexedDB `dplugin-auth/keys.domain` | 签 `BIZ` / `TOKEN` |
350
+
351
+ - 私钥 `extractable = false`,只能以 CryptoKey 形式存在 IndexedDB,JS 导不出原始字节。
352
+ - 每次登录重新生成 sso 密钥,每次换 token 重新生成域密钥(多账号不会串)。
353
+ - 清过 IndexedDB 后:业务请求发现缺私钥 → 用 `sid` 强制换一次 token 自愈;`sid` 也没了才回登录页。
354
+
355
+ ## 附录:行为约定
356
+
357
+ 1. **同一页面内续期单飞**:N 个并发 `500900` 只发一次续期,其余复用同一结果。
358
+ 2. **跨标签页续期**:`/s/token` 有按 sso 的锁,A 抢到时 B 会拿到 `500 重复请求`;SDK 不登出,等 A 把新
359
+ access 写进 localStorage(最多 1.2 秒)后直接采用。cookie 模式因为 Cookie 天然共享,由后端锁兜住。
360
+ 3. **登录失败回滚密钥**:`login()` 失败(密码错、轮询超时)会把上一个会话的密钥写回去,
361
+ 避免「输错一次密码」把已有会话的私钥冲掉。
362
+ 4. **`isLogin()` 只是提示**:真正有效性以第一次 `request()` 为准。
363
+
364
+ ## 附录:已知取舍(有意为之)
365
+
366
+ | 取舍 | 原因 |
367
+ |---|---|
368
+ | 不做定时器 / 提前续期 | 后端规定凭证必须**已过期**才允许续期,提前续期会被判异常并吊销整个 sso |
369
+ | 默认不跳登录页(`enableAuth:false`) | 框架不该替业务决定导航 |
370
+ | `refresh` 不导出 | 同上,业务手调会把用户全端踢下线 |
371
+ | 不做跨标签页登出广播 | A 退出后 B 要等下一个请求才发现;加 `storage` 监听收益不值 |
372
+ | 不内置 loading / 重试策略 | SDK 只保证「登录态 + 签名」正确 |
373
+ | QQ / 微信扫码登录暂不支持 | 后端这两个入口还没接新协议 |
374
+
375
+ ## 附录:原生能力指纹(防 fetch / indexedDB.open 被代理)
376
+
377
+ `src/native.js` 在**模块加载那一刻**把 `fetch`、`indexedDB.open`、`crypto.subtle.*` 绑成局部引用,
378
+ 之后页面再替换全局也影响不到 SDK;顺手做源码指纹校验,`setup()` 时报告
379
+ (`nativeGuard: 'warn' | 'error' | 'off'`)。
380
+
381
+ 挡不住的是「在本模块之前就用 Proxy 冒充并伪造源码」或同源 XSS 接管 `window` ——
382
+ 这一层只是提高门槛,真正的边界是:私钥不可导出 + 签名绑路径/设备/时间 + 网关 lockSign + 30 分钟 TTL。
383
+
384
+ ---
385
+
386
+ ## 开发与发布
387
+
388
+ ```bash
389
+ npm install
390
+ npm run build # dist/index.mjs(ESM) + index.cjs(CJS) + index.umd.js(UMD/DPluginCore)
391
+ npm test # 两套自检:39 次请求(sign)+ 22 项(cookie)
392
+ node test/interop.mjs # 改了签名相关代码后跑:输出 {pk, text, sign} 供后端验签
393
+ ```
394
+
395
+ 发布:
396
+
397
+ ```bash
398
+ npm version patch # 或 minor / major
399
+ npm run build && npm test
400
+ npm publish --registry=https://registry.npmjs.org/
401
+ ```
402
+
403
+ - 安装走国内镜像没问题(`registry.npmmirror.com` 会自动同步);
404
+ - **发布/查询版本必须显式指定官方源** `--registry=https://registry.npmjs.org/`;
405
+ - 账号开了 2FA 时,token 需要勾 **Bypass 2FA**,否则 `npm publish` 会 403。
406
+
407
+ ## License
408
+
409
+ MIT
package/dist/index.cjs ADDED
@@ -0,0 +1,3 @@
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const M={apiBase:"",mode:"auto",loginUrl:"/login/",timeout:15e3,pollInterval:2e3,pollMax:5,enableAuth:!1,onError:null,onLogin:null,onLogout:null,nativeGuard:"warn"};function Ae(e){return e&&Object.keys(M).forEach(t=>{e[t]!==void 0&&(M[t]=e[t])}),M}function R(){return M}const m=_e();function Z(e,t){if(typeof e!="function")return!1;let n;try{n=Function.prototype.toString.call(e)}catch(r){return!1}const o=/^function\s+([\w$]+)\s*\(\s*\)\s*\{\s*\[native code\]\s*\}$/.exec(n);return o?o[1]===t:/\[native code\]/.test(n)&&!/^function\s*\(\s*\)\s*\{\s*\[native code\]\s*\}$/.test(n)}function Ce(e){try{const t=e();return t&&typeof t.then=="function"&&Promise.resolve(t).catch(()=>{}),!1}catch(t){const n=String(t&&t.message||"");return!!t&&t.name==="TypeError"&&/argument|required|参数/i.test(n)}}function _e(){const e=globalThis,t=typeof e.window!="undefined"&&e.window&&typeof e.window.document!="undefined",n={fetch:null,idbOpen:null,subtle:null,pristine:{fetch:!1,idbOpen:!1,subtle:!1}};typeof e.fetch=="function"&&(n.pristine.fetch=Z(e.fetch,"fetch"),n.fetch=e.fetch.bind(e)),typeof e.indexedDB!="undefined"&&e.indexedDB&&typeof e.indexedDB.open=="function"&&(n.pristine.idbOpen=Z(e.indexedDB.open,"open")&&(!t||Ce(()=>e.indexedDB.open())),n.idbOpen=e.indexedDB.open.bind(e.indexedDB));const o=e.crypto&&e.crypto.subtle?e.crypto.subtle:null;if(o){const r=["generateKey","exportKey","importKey","sign","verify","digest"],s={};let u=!0;r.forEach(c=>{typeof o[c]=="function"&&(s[c]=o[c].bind(o),u=u&&Z(o[c],c))}),n.subtle=s,n.pristine.subtle=u}return n}function ke(){if(typeof window=="undefined"||typeof window.document=="undefined")return[];const e=[];return m.fetch&&!m.pristine.fetch&&e.push("fetch"),m.idbOpen&&!m.pristine.idbOpen&&e.push("indexedDB.open"),m.subtle&&!m.pristine.subtle&&e.push("crypto.subtle"),e}const a={OK:"200",PENDING:"202",AUTH_EXPIRED:"500900",FORBIDDEN:"401001",CORS_DENIED:"403",API_NOT_FOUND:"404",NETWORK:"NETWORK",TIMEOUT:"TIMEOUT"};class E extends Error{constructor(t,n){super(n||"请求失败"),this.name="BizError",this.code=t}}class O extends E{constructor(t){super(a.AUTH_EXPIRED,t||"登录已失效"),this.name="AuthError"}}function Me(e){return e instanceof O||e&&e.code===a.AUTH_EXPIRED}const $="dplugin.access",J="dplugin.sid",we="dplugin.ds",Q="dplugin.exp",ee="dplugin.cookie";function Ue(e){try{return localStorage.getItem(e)}catch(t){return null}}function Ee(e,t){try{t==null||t===""?localStorage.removeItem(e):localStorage.setItem(e,t)}catch(n){}}const H={};function C(e){const t=Ue(e);return t===null?H[e]===void 0?null:H[e]:t}function _(e,t){H[e]=t,Ee(e,t)}const i={get access(){return C($)},set access(e){_($,e)},get sid(){return C(J)},set sid(e){_(J,e)},get ds(){return C(we)},set ds(e){_(we,e)},get exp(){const e=C(Q);return e?Number(e):0},set exp(e){_(Q,e?String(e):null)},get cookie(){return C(ee)==="1"},set cookie(e){_(ee,e?"1":null)},clear(){[$,J,Q,ee].forEach(e=>{H[e]=null,Ee(e,null)})}};function g(e,t){const n=R().apiBase||"";let o=e;return/^https?:\/\//i.test(e)||(o=(n?n.replace(/\/+$/,""):"")+(e.startsWith("/")?e:"/"+e)),t&&(o+=(o.includes("?")?"&":"?")+t),o}function j(e){const t=g(e);if(/^https?:\/\//i.test(t))try{return new URL(t).pathname}catch(n){return t.split("?")[0]}try{return new URL(t,"http://localhost").pathname}catch(n){return t.split("?")[0]}}let b=null;function ve(e){try{const t=typeof location!="undefined"?location.href:void 0;return new URL(e||"",t).origin}catch(t){return null}}function Le(){b=null}function ie(){if(b)return b;const e=R();if(e.mode==="sign"||e.mode==="cookie")return b=e.mode,b;const t=typeof location!="undefined"?location.origin:null;if(!t)return b="sign",b;const n=ve(e.apiBase||t);return b=n&&n===t?"cookie":"sign",b}function S(){return ie()==="cookie"}async function h(e,t,n){const o=R(),r=n||o.timeout,s=typeof AbortController!="undefined"?new AbortController:null,u=s?setTimeout(()=>s.abort(),r):null,c={method:"POST",credentials:S()?"same-origin":"omit",signal:s?s.signal:void 0};if(typeof FormData!="undefined"&&t instanceof FormData?c.body=t:t!=null&&(c.headers={"Content-Type":"text/plain"},c.body=JSON.stringify(t)),!m.fetch)throw new E(a.NETWORK,"当前环境不支持 fetch");let f;try{f=await m.fetch(e,c)}catch(y){throw u&&clearTimeout(u),y&&y.name==="AbortError"?new E(a.TIMEOUT,"请求超时,请重试"):new E(a.NETWORK,"网络异常,请检查网络后重试")}u&&clearTimeout(u);const d=await f.text();let l=null;if(d)try{l=JSON.parse(d)}catch(y){l=null}if(!f.ok)throw new E(String(f.status),l&&l.message||d||"请求失败");if(!l||l.code===null||l.code===void 0)throw new E("500","响应格式异常");return l.code=String(l.code),l}const Fe="dplugin-auth",Be=1,Y="keys",se="sso",ce="domain",Ge={name:"ECDSA",namedCurve:"P-256"},He={name:"ECDSA",hash:"SHA-256"},B=new Map;let L=null;function X(){if(!m.subtle){const e=typeof location!="undefined"&&location.origin?location.origin:"(未知 origin)";throw new Error("[dplugin/core] crypto.subtle 不存在:浏览器只在**安全上下文**里提供它(https、http://localhost、http://127.0.0.1、http://[::1]、file://);当前 origin="+e)}return m.subtle}function Ye(){return L||(L=new Promise(e=>{if(!m.idbOpen){e(null);return}let t;try{t=m.idbOpen(Fe,Be)}catch(n){e(null);return}t.onupgradeneeded=()=>{const n=t.result;n.objectStoreNames.contains(Y)||n.createObjectStore(Y)},t.onsuccess=()=>e(t.result),t.onerror=()=>e(null),t.onblocked=()=>e(null)}),L)}function me(e,t){return Ye().then(n=>n?new Promise(o=>{let r;try{r=n.transaction(Y,e)}catch(c){o(null);return}const s=r.objectStore(Y);let u=null;try{const c=t(s);c&&(c.onsuccess=()=>{u=c.result},c.onerror=()=>{u=null})}catch(c){u=null}r.oncomplete=()=>o(u),r.onerror=()=>o(null),r.onabort=()=>o(null)}):null)}function Oe(e){return B.has(e)?Promise.resolve(B.get(e)):me("readonly",t=>t.get(e)).then(t=>(t&&B.set(e,t),t||null))}function ye(e,t){return B.set(e,t),me("readwrite",n=>n.put(t,e)).then(()=>t)}async function ae(e){const n=await X().generateKey(Ge,!1,["sign","verify"]);return ye(e,n)}async function Se(e){return Oe(e)}async function he(e,t){return t?ye(e,t):null}async function Ve(e){return await Oe(e)||ae(e)}function je(){return ae(se)}function Xe(){return ae(ce)}function ue(){return Se(se)}function be(){return Se(ce)}async function te(e){const n=await X().exportKey("spki",e.publicKey);let o="";const r=new Uint8Array(n);for(let s=0;s<r.length;s++)o+=String.fromCharCode(r[s]);return btoa(o)}function Ie(e){const t=new Uint8Array(e);let n="";for(let o=0;o<t.length;o++)n+=String.fromCharCode(t[o]);return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function We(e,t){const o=await X().sign(He,e.privateKey,new TextEncoder().encode(t));return Ie(o)}async function Te(e){const t=X(),n=await t.exportKey("spki",e.publicKey),o=await t.digest("SHA-256",n);return Ie(o)}const ne={SSO:se,DOMAIN:ce},oe="-",qe="POST",N={BIZ:"BIZ",VERIFY:"VERIFY",VERIFY_SID:"VERIFY_SID",TOKEN:"TOKEN"};function p(e){return e==null||e===""?oe:String(e)}function ze(e,t){const n=p(t.origin);return[p(e),p(t.method),p(t.path),n===oe?oe:n.toLowerCase(),p(t.ds),p(t.ts),p(t.subject),p(t.dna),p(t.redirect)].join(`
2
+ `)}function Ze(e,t,n){return[p(e),p(t.subject),p(t.ds),p(t.ts),n].join(".")}async function x(e,t,n){const o=n==="sso"?await ue():await be();if(!o)throw Pe(n==="sso"?"缺少登录签名密钥":"缺少业务签名密钥");const r=await We(o,ze(e,t));return Ze(e,t,r)}async function fe(e,t,n){if(!t||!n)throw Pe("缺少 access 或 ds,无法签名");const o=await x(N.BIZ,{method:qe,path:j(e),origin:K(),ds:n,ts:Date.now(),subject:t},"domain");return"dsign="+encodeURIComponent(o)}function K(){if(typeof location=="undefined")return"";if(location.origin)return location.origin.toLowerCase();try{return new URL(location.href).origin.toLowerCase()}catch(e){return""}}function Pe(e){const t=new Error(e);return t.code="KEY_MISSING",t}function $e(){const e=typeof navigator!="undefined"&&navigator.userAgent||"",t={device_brand:Je(e),device_model:Qe(e),browser_name:et(e),browser_version:tt(e),os_name:nt(e),os_version:ot(e)},n=i.ds;return n&&(t.device_id=n),t}function I(e,t){const n=e.match(t);return n?n[1]:""}function Je(e){return/iPhone|iPad|iPod/.test(e)?"Apple":/Huawei|HONOR/i.test(e)?"Huawei":/Xiaomi|Redmi|POCO/i.test(e)?"Xiaomi":/OPPO|realme/i.test(e)?"OPPO":/vivo/i.test(e)?"vivo":/Samsung|SM-|SAMSUNG/i.test(e)?"Samsung":/Macintosh|Mac OS X/.test(e)?"Apple":""}function Qe(e){if(/iPhone/.test(e))return"iPhone";if(/iPad/.test(e))return"iPad";const t=e.match(/Android[^;]*;\s*([^;)]+?)(?:\s+Build[/)]|\))/i);return t?t[1].trim():/Macintosh/.test(e)?"Mac":""}function et(e){return/MicroMessenger/i.test(e)?"WeChat":/Edg[A-Za-z]*\//.test(e)?"Edge":/OPR\/|Opera/.test(e)?"Opera":/Firefox\//.test(e)?"Firefox":/Chrome\/|CriOS\//.test(e)?"Chrome":/Safari\//.test(e)?"Safari":""}function tt(e){return/MicroMessenger\/([\d.]+)/.test(e)?I(e,/MicroMessenger\/([\d.]+)/):/Edg[A-Za-z]*\/([\d.]+)/.test(e)?I(e,/Edg[A-Za-z]*\/([\d.]+)/):/OPR\/([\d.]+)/.test(e)?I(e,/OPR\/([\d.]+)/):/Firefox\/([\d.]+)/.test(e)?I(e,/Firefox\/([\d.]+)/):/CriOS\/([\d.]+)/.test(e)?I(e,/CriOS\/([\d.]+)/):/Chrome\/([\d.]+)/.test(e)?I(e,/Chrome\/([\d.]+)/):/Version\/([\d.]+).*Safari/.test(e)?I(e,/Version\/([\d.]+)/):""}function nt(e){return/Windows NT/.test(e)?"Windows":/iPhone|iPad|iPod/.test(e)?"iOS":/Android/.test(e)?"Android":/Mac OS X|Macintosh/.test(e)?"macOS":/HarmonyOS/.test(e)?"HarmonyOS":/Linux/.test(e)?"Linux":""}function ot(e){if(/Windows NT 10\.0/.test(e))return"10/11";if(/Windows NT 6\.3/.test(e))return"8.1";if(/Windows NT 6\.1/.test(e))return"7";const t=e.match(/(?:iPhone )?OS (\d+[_.]\d+(?:[_.]\d+)?)/);if(t)return t[1].replace(/_/g,".");if(/Android[ _]([\d.]+)/.test(e))return I(e,/Android[ _]([\d.]+)/);const n=e.match(/Mac OS X (\d+[_.]\d+(?:[_.]\d+)?)/);return n?n[1].replace(/_/g,"."):""}const w={SIGN:{VERIFY:"/api/unsafe/dplugin/login/s/verify",TOKEN:"/api/unsafe/dplugin/login/s/token",REFRESH:"/api/unsafe/dplugin/login/s/refresh"},COOKIE:{VERIFY:"/api/unsafe/dplugin/login/c/verify",TOKEN:"/api/unsafe/dplugin/login/c/token",REFRESH:"/api/unsafe/dplugin/login/c/refresh"},LOGOUT:"/api/safe/dplugin/login/logout"},rt="dp_dvt",de=1800*1e3;let k=null,F=null,D=null,V=!1;function W(){return typeof location!="undefined"?location.href:""}function U(e){return new Promise(t=>setTimeout(t,e))}function q(){const e=R();typeof e.onLogin=="function"&&e.onLogin(v())}function T(e,t){return new E(e.code,e.message||t)}function it(e,t,n){if(typeof document=="undefined")return;let o=e+"="+encodeURIComponent(t)+"; path=/; SameSite=Lax";o+="; max-age="+n,document.cookie=o}function v(){return{mode:ie(),loggedIn:z(),hasAccess:!!i.access,sid:i.sid,ds:i.ds}}function z(){return S()?!!i.cookie:!!(i.access||i.sid)}function le(){i.clear()}function P(e){const t=z();le();const n=R();if(t&&typeof n.onLogout=="function"&&n.onLogout(e||"expired"),V||!n.enableAuth||!n.loginUrl||typeof location=="undefined")return;V=!0;const o=n.loginUrl.includes("?")?"&":"?";location.href=n.loginUrl+o+"referer="+encodeURIComponent(location.href)}function Re(e,t){return D||(D=st(e,t).then(n=>(D=null,n),n=>{throw D=null,n}),D)}async function st(e,t){const n=R(),o=$e();if(S())return ut(e,t,o,n);const r=await ue(),s=await be();try{return await ct(e,t,o,n)}catch(u){throw await he(ne.SSO,r),await he(ne.DOMAIN,s),u}}async function ct(e,t,n,o){const r=await je(),s=await te(r),u=await h(g(e),Object.assign({},t,{device:n,pk:s}));if(u.code!==a.OK)throw T(u,"登录失败");const c=u.data&&u.data.token;if(!c)throw T(u,"登录失败");const f=await Xe(),d=await Te(f),l=await at(c,o,d),y=await h(g(w.SIGN.TOKEN),{dsign:await x(N.TOKEN,{origin:K(),ts:Date.now(),subject:l.code,dna:d},"domain"),pk:await te(f)});if(y.code!==a.OK||!y.data)throw T(y,"登录失败");return i.sid=l.sid,i.ds=y.data.ds||l.ds,i.access=y.data.token,i.exp=Date.now()+de,V=!1,q(),v()}async function at(e,t,n){const o=W(),r=Math.max(1,Number(t.pollMax)||5);for(let s=1;s<=r;s++){const u=i.ds||null,c=Date.now(),f=await x(N.VERIFY,{method:"POST",path:j(w.SIGN.VERIFY),origin:K(),ds:u,ts:c,subject:e,dna:n,redirect:o},"sso");let d;try{d=await h(g(w.SIGN.VERIFY),{dsign:f,dna:n,redirect:o})}catch(l){if((l.code===a.NETWORK||l.code===a.TIMEOUT)&&s<r){await U(t.pollInterval);continue}throw l}if(d.code===a.OK&&d.data)return d.data;if(d.code===a.PENDING){if(s<r){await U(t.pollInterval);continue}break}throw T(d,"登录失败")}throw new E(a.AUTH_EXPIRED,"登录超时,请重试")}async function ut(e,t,n,o){const r=await h(g(e),Object.assign({},t,{device:n}));if(r.code!==a.OK)throw T(r,"登录失败");const s=r.data&&r.data.token;if(!s)throw T(r,"登录失败");return it(rt,s,300),await ft(o),await De(),i.cookie=!0,V=!1,q(),v()}async function ft(e){const t=W(),n=Math.max(1,Number(e.pollMax)||5);for(let o=1;o<=n;o++){let r;try{r=await h(g(w.COOKIE.VERIFY),{redirect:t})}catch(s){if((s.code===a.NETWORK||s.code===a.TIMEOUT)&&o<n){await U(e.pollInterval);continue}throw s}if(r.code===a.OK)return r.data;if(r.code===a.PENDING){if(o<n){await U(e.pollInterval);continue}break}throw T(r,"登录失败")}throw new E(a.AUTH_EXPIRED,"登录超时,请重试")}async function De(){const e=await h(g(w.COOKIE.TOKEN));if(e.code!==a.OK)throw T(e,"登录失败");return e}async function A(e){const t=!!(e&&e.force);return F||(F=(async()=>{try{return S()?await dt(t):await gt(t)}catch(n){if(n&&(n.code===a.NETWORK||n.code===a.TIMEOUT))throw n;return!1}finally{F=null}})()),F}async function dt(e){return!e&&i.cookie?!0:(await h(g(w.COOKIE.VERIFY),{redirect:W()})).code!==a.OK||(await De()).code!==a.OK?(i.cookie=!1,!1):(i.cookie=!0,q(),!0)}async function lt(){if(!i.sid||!i.ds||!await ue())return!1;const t=i.ds,n=await Ve(ne.DOMAIN),o=await Te(n),r=W(),s=await x(N.VERIFY_SID,{method:"POST",path:j(w.SIGN.VERIFY),origin:K(),ds:t,ts:Date.now(),subject:i.sid,dna:o,redirect:r},"sso"),u=await h(g(w.SIGN.VERIFY),{dsign:s,dna:o,redirect:r});if(u.code!==a.OK||!u.data)return!1;const c=await h(g(w.SIGN.TOKEN),{dsign:await x(N.TOKEN,{origin:K(),ts:Date.now(),subject:u.data.code,dna:o},"domain"),pk:await te(n)});return c.code!==a.OK||!c.data?!1:(i.access=c.data.token,c.data.ds&&(i.ds=c.data.ds),i.exp=Date.now()+de,q(),!0)}async function gt(e){return!e&&i.access?!0:lt()}function ge(){return k||(k=(S()?wt():ht()).then(e=>(k=null,e),e=>{throw k=null,e})),k}async function wt(){const e=await h(g(w.COOKIE.REFRESH));if(e.code===a.OK)return!0;if(e.code===a.AUTH_EXPIRED)throw new O(e.message);if(e.code==="500"&&/重复/.test(e.message||""))return await U(800),!0;throw new E(e.code,e.message)}async function ht(){const e=i.access,t=i.ds;if(!e||!t)throw new O;const n=await x(N.BIZ,{method:"POST",path:j(w.SIGN.REFRESH),origin:K(),ds:t,ts:Date.now(),subject:e},"domain"),o=await h(g(w.SIGN.REFRESH,"dsign="+encodeURIComponent(n)));if(o.code===a.OK&&o.data)return i.access=o.data.token,o.data.ds&&(i.ds=o.data.ds),i.exp=Date.now()+de,i.access;const r=await pt(e,1200);if(r)return r;throw o.code===a.AUTH_EXPIRED?new O(o.message):new E(o.code,o.message)}function pt(e,t){const n=Date.now()+t;return new Promise(o=>{const r=()=>{const s=i.access;if(s&&s!==e){o(s);return}if(Date.now()>=n){o(null);return}setTimeout(r,150)};r()})}async function Ne(){try{let t=await pe();t.code===a.AUTH_EXPIRED&&(await ge(),t=await pe())}catch(t){}le();const e=R();typeof e.onLogout=="function"&&e.onLogout("logout")}async function pe(){if(S())return h(g(w.LOGOUT));const e=await fe(w.LOGOUT,i.access,i.ds);return h(g(w.LOGOUT,e))}async function Et(e,t,n){const o=n||{};return o.auth!==!1&&await xe(),G(e,t||{},o,!1)}async function xe(){if(S()){if(i.cookie||await A())return;throw P("expired"),new O}if(!i.access&&!await A())throw P("expired"),new O}async function G(e,t,n,o){const r=n.auth!==!1,s=r&&!S();let u="",c=null;if(s){c=i.access;try{u=await fe(e,c,i.ds)}catch(d){if(!o&&await A({force:!0}))return G(e,t,n,!0);throw P("expired"),new O}}const f=await h(g(e,u),t,n.timeout);if(f.code===a.OK)return f.data;if(r&&f.code===a.AUTH_EXPIRED&&!o){if(s&&c&&i.access!==c)return G(e,t,n,!0);try{await ge()}catch(d){throw d instanceof O&&P("expired"),d}return G(e,t,n,!0)}throw r&&f.code===a.AUTH_EXPIRED?(P("expired"),new O(f.message)):Ke(f)}function Ke(e){const t=new E(e.code,e.message),n=R();return n.onError&&n.onError({code:e.code,message:e.message,error:t}),t}async function mt(e,t,n,o){return(S()?!i.cookie:!i.access)&&await xe(),re(e,t,n,o||{},!1)}async function re(e,t,n,o,r){let s="";if(!S())try{s=await fe(e,i.access,i.ds)}catch(f){if(!r&&await A({force:!0}))return re(e,t,n,o,!0);throw P("expired"),new O}const u=new FormData;Object.keys(n||{}).forEach(f=>{const d=n[f];d!=null&&u.append(f,d)}),u.append("file",t);const c=await h(g(e,s),u,o.timeout);if(c.code===a.OK)return c.data;if(c.code===a.AUTH_EXPIRED&&!r){try{await ge()}catch(f){throw f instanceof O&&P("expired"),f}return re(e,t,n,o,!0)}throw Ke(c)}function Ot(e){const t=Ae(e);if(Le(),t.nativeGuard!=="off"){const n=ke();if(n.length){const o="[dplugin/core] 这些原生能力在模块加载前已被替换:"+n.join(", ")+"(签名/请求可能被中间人截获,检查是否有脚本抢跑)";if(t.nativeGuard==="error")throw new Error(o);typeof console!="undefined"&&console.warn(o)}}}const yt={login:Re,logout:Ne,isLogin:z,getState:v,restore:A};exports.AuthError=O;exports.BizError=E;exports.CODE=a;exports.auth=yt;exports.clear=le;exports.expire=P;exports.getMode=ie;exports.getState=v;exports.isAuthError=Me;exports.isLogin=z;exports.login=Re;exports.logout=Ne;exports.request=Et;exports.setup=Ot;exports.store=i;exports.upload=mt;exports.verifyLogin=A;
3
+ //# sourceMappingURL=index.cjs.map