@vueboot/http 0.1.0 → 0.2.0
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/LICENSE +21 -21
- package/README.md +479 -434
- package/dist/index.d.ts +31 -2
- package/dist/index.js +358 -161
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -4,6 +4,176 @@ var __defProp = Object.defineProperty;
|
|
|
4
4
|
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
5
5
|
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
|
|
6
6
|
|
|
7
|
+
// src/errors.ts
|
|
8
|
+
function createErrorNormalizer() {
|
|
9
|
+
return async (error) => {
|
|
10
|
+
const normalized = await normalize(error);
|
|
11
|
+
return Promise.reject(hideConfig(normalized));
|
|
12
|
+
};
|
|
13
|
+
}
|
|
14
|
+
function hideConfig(error) {
|
|
15
|
+
if (!error.config) return error;
|
|
16
|
+
try {
|
|
17
|
+
Object.defineProperty(error, "config", {
|
|
18
|
+
value: error.config,
|
|
19
|
+
enumerable: false,
|
|
20
|
+
configurable: true,
|
|
21
|
+
writable: true
|
|
22
|
+
});
|
|
23
|
+
} catch {
|
|
24
|
+
}
|
|
25
|
+
return error;
|
|
26
|
+
}
|
|
27
|
+
function safeAxiosRaw(error) {
|
|
28
|
+
const raw = {
|
|
29
|
+
isAxiosError: true,
|
|
30
|
+
name: error.name,
|
|
31
|
+
message: error.message
|
|
32
|
+
};
|
|
33
|
+
if (error.code !== void 0) raw.code = error.code;
|
|
34
|
+
if (error.status !== void 0) raw.status = error.status;
|
|
35
|
+
if (error.response) {
|
|
36
|
+
raw.response = {
|
|
37
|
+
status: error.response.status,
|
|
38
|
+
statusText: error.response.statusText,
|
|
39
|
+
data: error.response.data
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
return raw;
|
|
43
|
+
}
|
|
44
|
+
function sanitizeErrorForPayload(error) {
|
|
45
|
+
if (error && typeof error === "object" && error.isAxiosError === true) {
|
|
46
|
+
return safeAxiosRaw(error);
|
|
47
|
+
}
|
|
48
|
+
return error;
|
|
49
|
+
}
|
|
50
|
+
var KINDS = /* @__PURE__ */ new Set([
|
|
51
|
+
"network",
|
|
52
|
+
"timeout",
|
|
53
|
+
"http",
|
|
54
|
+
"business",
|
|
55
|
+
"canceled",
|
|
56
|
+
"unknown"
|
|
57
|
+
]);
|
|
58
|
+
function isNormalized(error) {
|
|
59
|
+
if (!error || typeof error !== "object") return false;
|
|
60
|
+
const candidate = error;
|
|
61
|
+
return typeof candidate.message === "string" && KINDS.has(candidate.kind);
|
|
62
|
+
}
|
|
63
|
+
function readableMessage(error) {
|
|
64
|
+
if (error instanceof Error && error.message.trim()) return error.message;
|
|
65
|
+
if (typeof error === "string" && error.trim()) return error.trim();
|
|
66
|
+
return "\u672A\u77E5\u9519\u8BEF";
|
|
67
|
+
}
|
|
68
|
+
async function normalize(error) {
|
|
69
|
+
if (isNormalized(error)) return error;
|
|
70
|
+
if (error instanceof Error && "__business__" in error && error.__business__) {
|
|
71
|
+
const business = error;
|
|
72
|
+
return {
|
|
73
|
+
kind: "business",
|
|
74
|
+
code: business.code,
|
|
75
|
+
message: business.message?.trim() ? business.message : "\u4E1A\u52A1\u5904\u7406\u5931\u8D25",
|
|
76
|
+
config: business.config,
|
|
77
|
+
raw: business.raw ?? business
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
const axiosError = error;
|
|
81
|
+
if (!axiosError?.isAxiosError) {
|
|
82
|
+
return {
|
|
83
|
+
kind: "unknown",
|
|
84
|
+
message: readableMessage(error),
|
|
85
|
+
config: error?.config,
|
|
86
|
+
raw: error
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
if (axiosError.code === "ERR_CANCELED") {
|
|
90
|
+
return {
|
|
91
|
+
kind: "canceled",
|
|
92
|
+
message: "\u8BF7\u6C42\u5DF2\u53D6\u6D88",
|
|
93
|
+
config: axiosError.config,
|
|
94
|
+
raw: safeAxiosRaw(axiosError)
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
if (axiosError.code === "ECONNABORTED" || axiosError.code === "ETIMEDOUT" || axiosError.message?.includes("timeout")) {
|
|
98
|
+
return {
|
|
99
|
+
kind: "timeout",
|
|
100
|
+
message: "\u8BF7\u6C42\u8D85\u65F6\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5",
|
|
101
|
+
config: axiosError.config,
|
|
102
|
+
raw: safeAxiosRaw(axiosError)
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
if (!axiosError.response) {
|
|
106
|
+
return {
|
|
107
|
+
kind: "network",
|
|
108
|
+
message: "\u7F51\u7EDC\u5F02\u5E38\uFF0C\u8BF7\u68C0\u67E5\u8FDE\u63A5",
|
|
109
|
+
config: axiosError.config,
|
|
110
|
+
raw: safeAxiosRaw(axiosError)
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
const { status, data } = axiosError.response;
|
|
114
|
+
const body = await readMessageBody(data);
|
|
115
|
+
return {
|
|
116
|
+
kind: "http",
|
|
117
|
+
status,
|
|
118
|
+
message: pickServerMessage(body) ?? `\u8BF7\u6C42\u5931\u8D25\uFF08${status}\uFF09`,
|
|
119
|
+
config: axiosError.config,
|
|
120
|
+
raw: safeAxiosRaw(axiosError)
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
async function readMessageBody(data) {
|
|
124
|
+
if (typeof Blob !== "undefined" && data instanceof Blob) {
|
|
125
|
+
const type = data.type ?? "";
|
|
126
|
+
const textual = !type || type.includes("json") || type.startsWith("text/");
|
|
127
|
+
if (!textual) return data;
|
|
128
|
+
try {
|
|
129
|
+
const text = await data.text();
|
|
130
|
+
return parseJsonText(text) ?? text;
|
|
131
|
+
} catch {
|
|
132
|
+
return data;
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
if (typeof ArrayBuffer !== "undefined") {
|
|
136
|
+
if (data instanceof ArrayBuffer || ArrayBuffer.isView(data)) {
|
|
137
|
+
try {
|
|
138
|
+
return parseJsonText(new TextDecoder().decode(data)) ?? data;
|
|
139
|
+
} catch {
|
|
140
|
+
return data;
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
return data;
|
|
145
|
+
}
|
|
146
|
+
function parseJsonText(text) {
|
|
147
|
+
const trimmed = text.trim();
|
|
148
|
+
if (!trimmed) return void 0;
|
|
149
|
+
try {
|
|
150
|
+
return JSON.parse(trimmed);
|
|
151
|
+
} catch {
|
|
152
|
+
return void 0;
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
function pickServerMessage(data) {
|
|
156
|
+
if (typeof data === "string") {
|
|
157
|
+
const text = data.trim();
|
|
158
|
+
return text || void 0;
|
|
159
|
+
}
|
|
160
|
+
if (data && typeof data === "object") {
|
|
161
|
+
const body = data;
|
|
162
|
+
for (const value of [body.message, body.msg, body.MSG]) {
|
|
163
|
+
if (typeof value === "string" && value.trim()) return value.trim();
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
return void 0;
|
|
167
|
+
}
|
|
168
|
+
function toErrorText(error) {
|
|
169
|
+
const normalized = error;
|
|
170
|
+
if (normalized && typeof normalized === "object" && typeof normalized.message === "string" && normalized.message.trim()) {
|
|
171
|
+
return normalized.message;
|
|
172
|
+
}
|
|
173
|
+
if (error instanceof Error && error.message.trim()) return error.message;
|
|
174
|
+
return "\u64CD\u4F5C\u5931\u8D25\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5";
|
|
175
|
+
}
|
|
176
|
+
|
|
7
177
|
// src/session.ts
|
|
8
178
|
var EMPTY = { tokenType: "Bearer", version: 0 };
|
|
9
179
|
var DEFAULT_REFRESH_COOLDOWN_MS = 1e4;
|
|
@@ -16,6 +186,13 @@ function normalizeExpiresAt(value) {
|
|
|
16
186
|
function normalizeToken(value) {
|
|
17
187
|
return typeof value === "string" && value ? value : void 0;
|
|
18
188
|
}
|
|
189
|
+
function createSessionId() {
|
|
190
|
+
const cryptoRef = globalThis.crypto;
|
|
191
|
+
if (typeof cryptoRef?.randomUUID === "function") {
|
|
192
|
+
return cryptoRef.randomUUID();
|
|
193
|
+
}
|
|
194
|
+
return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
|
|
195
|
+
}
|
|
19
196
|
function normalizeVersion(value) {
|
|
20
197
|
return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : 0;
|
|
21
198
|
}
|
|
@@ -31,6 +208,7 @@ function normalizeSnapshot(raw) {
|
|
|
31
208
|
tokenType: typeof snapshot.tokenType === "string" && snapshot.tokenType ? snapshot.tokenType : "Bearer",
|
|
32
209
|
expiresAt: normalizeExpiresAt(snapshot.expiresAt),
|
|
33
210
|
refreshExpiresAt: normalizeExpiresAt(snapshot.refreshExpiresAt),
|
|
211
|
+
sessionId: typeof snapshot.sessionId === "string" && snapshot.sessionId ? snapshot.sessionId : void 0,
|
|
34
212
|
version: normalizeVersion(snapshot.version)
|
|
35
213
|
};
|
|
36
214
|
}
|
|
@@ -50,6 +228,11 @@ var Session = class {
|
|
|
50
228
|
__publicField(this, "lastProactiveFailedAt", 0);
|
|
51
229
|
__publicField(this, "lastAuthFailedAt", 0);
|
|
52
230
|
__publicField(this, "expirationTimer", null);
|
|
231
|
+
__publicField(this, "refreshController", null);
|
|
232
|
+
__publicField(this, "refreshTimer", null);
|
|
233
|
+
/** dispose 时主动结算 inflight,避免刷新实现忽略 abort 后请求永久挂起 */
|
|
234
|
+
__publicField(this, "rejectInflightOnDispose", null);
|
|
235
|
+
__publicField(this, "disposed", false);
|
|
53
236
|
__publicField(this, "expiredEmitted", false);
|
|
54
237
|
__publicField(this, "sideEffectsInstalled", false);
|
|
55
238
|
__publicField(this, "unsubscribers", []);
|
|
@@ -79,6 +262,15 @@ var Session = class {
|
|
|
79
262
|
* 判断能否访问受保护页面请用 `authenticated`(或 isAuthenticated())。
|
|
80
263
|
*/
|
|
81
264
|
async restore(options = {}) {
|
|
265
|
+
if (this.disposed) {
|
|
266
|
+
const tokenStatus2 = this.getStatus();
|
|
267
|
+
return {
|
|
268
|
+
status: tokenStatus2 === "anonymous" ? "anonymous" : this.isAuthenticated() ? "authenticated" : "expired",
|
|
269
|
+
tokenStatus: tokenStatus2,
|
|
270
|
+
refresh: "not-needed",
|
|
271
|
+
authenticated: this.isAuthenticated()
|
|
272
|
+
};
|
|
273
|
+
}
|
|
82
274
|
try {
|
|
83
275
|
await this.hydrate();
|
|
84
276
|
} catch {
|
|
@@ -129,7 +321,8 @@ var Session = class {
|
|
|
129
321
|
tokenStatus,
|
|
130
322
|
refresh: unavailable ?? "failed",
|
|
131
323
|
authenticated,
|
|
132
|
-
|
|
324
|
+
// 失败原因同样脱敏,避免业务记录 RestoreResult 时泄露认证头
|
|
325
|
+
error: sanitizeErrorForPayload(error)
|
|
133
326
|
};
|
|
134
327
|
}
|
|
135
328
|
}
|
|
@@ -154,6 +347,7 @@ var Session = class {
|
|
|
154
347
|
async hydrateOnce() {
|
|
155
348
|
const versionAtStart = this.state.version;
|
|
156
349
|
const raw = await Promise.resolve(this.storage?.read() ?? null);
|
|
350
|
+
if (this.disposed) return false;
|
|
157
351
|
this.hydrated = true;
|
|
158
352
|
const normalized = normalizeSnapshot(raw);
|
|
159
353
|
if (!normalized) return false;
|
|
@@ -163,6 +357,8 @@ var Session = class {
|
|
|
163
357
|
}
|
|
164
358
|
this.state = {
|
|
165
359
|
...normalized,
|
|
360
|
+
// 旧版本快照可能没有 sessionId:水合时补发,后续请求才能绑定会话
|
|
361
|
+
sessionId: normalized.sessionId ?? createSessionId(),
|
|
166
362
|
version: Math.max(normalized.version, previous.version + 1)
|
|
167
363
|
};
|
|
168
364
|
this.expiredEmitted = false;
|
|
@@ -171,7 +367,7 @@ var Session = class {
|
|
|
171
367
|
return true;
|
|
172
368
|
}
|
|
173
369
|
installSideEffects() {
|
|
174
|
-
if (this.sideEffectsInstalled) return;
|
|
370
|
+
if (this.disposed || this.sideEffectsInstalled) return;
|
|
175
371
|
this.sideEffectsInstalled = true;
|
|
176
372
|
const unsubscribe = this.storage?.subscribe?.((snapshot) => {
|
|
177
373
|
this.hydrateFromExternal(snapshot);
|
|
@@ -196,7 +392,11 @@ var Session = class {
|
|
|
196
392
|
const normalized = normalizeSnapshot(snapshot);
|
|
197
393
|
if (!normalized || normalized.version <= this.state.version) return;
|
|
198
394
|
const previous = this.getSnapshot();
|
|
199
|
-
this.state =
|
|
395
|
+
this.state = {
|
|
396
|
+
...normalized,
|
|
397
|
+
// 旧版本写出的快照可能没有 sessionId,本 tab 补发一个
|
|
398
|
+
sessionId: normalized.sessionId ?? createSessionId()
|
|
399
|
+
};
|
|
200
400
|
this.expiredEmitted = false;
|
|
201
401
|
this.resetCooldown();
|
|
202
402
|
this.scheduleExpiration();
|
|
@@ -213,6 +413,7 @@ var Session = class {
|
|
|
213
413
|
this.clear(reason);
|
|
214
414
|
}
|
|
215
415
|
setTokens(tokens, options = {}) {
|
|
416
|
+
if (this.disposed) throw new Error("[session] disposed");
|
|
216
417
|
if (typeof tokens?.accessToken !== "string" || !tokens.accessToken) {
|
|
217
418
|
throw new Error("[session] accessToken is required");
|
|
218
419
|
}
|
|
@@ -231,6 +432,7 @@ var Session = class {
|
|
|
231
432
|
} else if (tokens.refreshToken !== void 0) {
|
|
232
433
|
refreshExpiresAt = void 0;
|
|
233
434
|
}
|
|
435
|
+
const type = options.event ?? (previous.accessToken ? "refresh" : "login");
|
|
234
436
|
this.state = {
|
|
235
437
|
accessToken: tokens.accessToken,
|
|
236
438
|
// 显式传入空字符串表示「移除 refreshToken」,缺省则沿用旧值
|
|
@@ -238,10 +440,12 @@ var Session = class {
|
|
|
238
440
|
tokenType: typeof tokens.tokenType === "string" && tokens.tokenType || this.state.tokenType || "Bearer",
|
|
239
441
|
expiresAt,
|
|
240
442
|
refreshExpiresAt,
|
|
443
|
+
// 新的登录换会话标识;刷新沿用,避免把旧请求重放到新会话上
|
|
444
|
+
// cookieMode 可能从不调用 login:任何首次拿到 token 的写入都补发会话标识
|
|
445
|
+
sessionId: type === "login" || !this.state.sessionId ? createSessionId() : this.state.sessionId,
|
|
241
446
|
version: this.nextVersion()
|
|
242
447
|
};
|
|
243
448
|
this.expiredEmitted = false;
|
|
244
|
-
const type = options.event ?? (previous.accessToken ? "refresh" : "login");
|
|
245
449
|
if (type === "login") this.resetCooldown();
|
|
246
450
|
this.persist();
|
|
247
451
|
this.scheduleExpiration();
|
|
@@ -297,6 +501,9 @@ var Session = class {
|
|
|
297
501
|
* 与调试面板共用。并发调用共享同一个 inflight。
|
|
298
502
|
*/
|
|
299
503
|
async refresh(reason = "proactive") {
|
|
504
|
+
if (this.disposed) {
|
|
505
|
+
throw refreshError("unknown", "[session] disposed");
|
|
506
|
+
}
|
|
300
507
|
if (this.inflight) {
|
|
301
508
|
this.inflightReasons?.add(reason);
|
|
302
509
|
return this.inflight;
|
|
@@ -312,7 +519,7 @@ var Session = class {
|
|
|
312
519
|
const versionBefore = this.state.version;
|
|
313
520
|
const reasons = /* @__PURE__ */ new Set([reason]);
|
|
314
521
|
this.inflightReasons = reasons;
|
|
315
|
-
|
|
522
|
+
const core = (async () => {
|
|
316
523
|
try {
|
|
317
524
|
if (!this.cookieMode && this.isRefreshTokenExpired()) {
|
|
318
525
|
throw refreshError("unknown", "\u767B\u5F55\u51ED\u8BC1\u5DF2\u8FC7\u671F\uFF0C\u8BF7\u91CD\u65B0\u767B\u5F55");
|
|
@@ -326,7 +533,10 @@ var Session = class {
|
|
|
326
533
|
if (this.state.version !== versionBefore) {
|
|
327
534
|
return this.getSnapshot();
|
|
328
535
|
}
|
|
329
|
-
const
|
|
536
|
+
const hasExpiry = typeof tokens.expiresAt === "number" && Number.isFinite(tokens.expiresAt) || typeof tokens.expiresIn === "number" && Number.isFinite(tokens.expiresIn);
|
|
537
|
+
const reusableExpiry = this.state.expiresAt !== void 0 && this.state.expiresAt * 1e3 > Date.now();
|
|
538
|
+
const nextTokens = !hasExpiry && reusableExpiry ? { ...tokens, expiresAt: this.state.expiresAt } : tokens;
|
|
539
|
+
const snapshot = this.setTokens(nextTokens, { event: "refresh" });
|
|
330
540
|
this.lastProactiveFailedAt = 0;
|
|
331
541
|
this.lastAuthFailedAt = 0;
|
|
332
542
|
return snapshot;
|
|
@@ -335,11 +545,18 @@ var Session = class {
|
|
|
335
545
|
throw error;
|
|
336
546
|
}
|
|
337
547
|
})();
|
|
548
|
+
const disposal = new Promise((_, reject) => {
|
|
549
|
+
this.rejectInflightOnDispose = reject;
|
|
550
|
+
});
|
|
551
|
+
this.inflight = Promise.race([core, disposal]);
|
|
338
552
|
try {
|
|
339
553
|
return await this.inflight;
|
|
340
554
|
} finally {
|
|
341
555
|
this.inflight = null;
|
|
342
556
|
this.inflightReasons = null;
|
|
557
|
+
this.refreshController = null;
|
|
558
|
+
this.refreshTimer = null;
|
|
559
|
+
this.rejectInflightOnDispose = null;
|
|
343
560
|
}
|
|
344
561
|
}
|
|
345
562
|
isCoolingDown(reason = "proactive") {
|
|
@@ -352,6 +569,7 @@ var Session = class {
|
|
|
352
569
|
this.lastAuthFailedAt = 0;
|
|
353
570
|
}
|
|
354
571
|
recordFailure(error, reasons) {
|
|
572
|
+
if (this.disposed) return;
|
|
355
573
|
const now = Date.now();
|
|
356
574
|
if (reasons.has("proactive")) this.lastProactiveFailedAt = now;
|
|
357
575
|
if (reasons.has("unauthorized") || reasons.has("bootstrap")) {
|
|
@@ -370,26 +588,31 @@ var Session = class {
|
|
|
370
588
|
previous: null,
|
|
371
589
|
// 并发刷新可能同时服务多个原因,例如 "proactive+unauthorized"
|
|
372
590
|
reason: reasonLabel,
|
|
373
|
-
error
|
|
591
|
+
error: sanitizeErrorForPayload(error)
|
|
374
592
|
});
|
|
375
593
|
}
|
|
376
594
|
withTimeout(run) {
|
|
377
595
|
const controller = new AbortController();
|
|
596
|
+
this.refreshController = controller;
|
|
378
597
|
const promise = run(controller.signal);
|
|
379
598
|
if (!this.refreshTimeoutMs) return promise;
|
|
380
599
|
return new Promise((resolve, reject) => {
|
|
381
600
|
const timer = setTimeout(() => {
|
|
601
|
+
this.refreshTimer = null;
|
|
382
602
|
controller.abort();
|
|
383
603
|
reject(refreshError("timeout", "\u5237\u65B0\u767B\u5F55\u72B6\u6001\u8D85\u65F6\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5"));
|
|
384
604
|
}, this.refreshTimeoutMs);
|
|
605
|
+
this.refreshTimer = timer;
|
|
385
606
|
timer.unref?.();
|
|
386
607
|
promise.then(
|
|
387
608
|
(value) => {
|
|
388
609
|
clearTimeout(timer);
|
|
610
|
+
if (this.refreshTimer === timer) this.refreshTimer = null;
|
|
389
611
|
resolve(value);
|
|
390
612
|
},
|
|
391
613
|
(error) => {
|
|
392
614
|
clearTimeout(timer);
|
|
615
|
+
if (this.refreshTimer === timer) this.refreshTimer = null;
|
|
393
616
|
reject(error);
|
|
394
617
|
}
|
|
395
618
|
);
|
|
@@ -408,6 +631,10 @@ var Session = class {
|
|
|
408
631
|
getVersion() {
|
|
409
632
|
return this.state.version;
|
|
410
633
|
}
|
|
634
|
+
/** 当前登录会话标识;未登录时为 undefined */
|
|
635
|
+
getSessionId() {
|
|
636
|
+
return this.state.sessionId;
|
|
637
|
+
}
|
|
411
638
|
getSnapshot() {
|
|
412
639
|
return { ...this.state };
|
|
413
640
|
}
|
|
@@ -477,8 +704,19 @@ var Session = class {
|
|
|
477
704
|
this.listeners.get(type)?.delete(listener);
|
|
478
705
|
}
|
|
479
706
|
// ───────────────────────── 生命周期 ─────────────────────────
|
|
480
|
-
/**
|
|
707
|
+
/** 停止过期调度、注销存储订阅;在途刷新会被中止且不再写回存储 */
|
|
481
708
|
dispose() {
|
|
709
|
+
if (this.disposed) return;
|
|
710
|
+
this.disposed = true;
|
|
711
|
+
const rejectInflight = this.rejectInflightOnDispose;
|
|
712
|
+
this.rejectInflightOnDispose = null;
|
|
713
|
+
this.refreshController?.abort();
|
|
714
|
+
this.refreshController = null;
|
|
715
|
+
if (this.refreshTimer) {
|
|
716
|
+
clearTimeout(this.refreshTimer);
|
|
717
|
+
this.refreshTimer = null;
|
|
718
|
+
}
|
|
719
|
+
rejectInflight?.(refreshError("unknown", "[session] disposed"));
|
|
482
720
|
this.cancelExpiration();
|
|
483
721
|
for (const unsubscribe of this.unsubscribers.splice(0)) {
|
|
484
722
|
try {
|
|
@@ -493,6 +731,7 @@ var Session = class {
|
|
|
493
731
|
return Math.max(this.state.version + 1, Date.now());
|
|
494
732
|
}
|
|
495
733
|
persist(snapshot = this.state) {
|
|
734
|
+
if (this.disposed) return;
|
|
496
735
|
try {
|
|
497
736
|
const result = this.storage?.write(snapshot);
|
|
498
737
|
void Promise.resolve(result).catch(() => {
|
|
@@ -524,6 +763,7 @@ var Session = class {
|
|
|
524
763
|
}
|
|
525
764
|
/** 按 expiresAt 精确调度一次过期事件;token 变化时重排 */
|
|
526
765
|
scheduleExpiration() {
|
|
766
|
+
if (this.disposed) return;
|
|
527
767
|
this.cancelExpiration();
|
|
528
768
|
const { accessToken, expiresAt } = this.state;
|
|
529
769
|
if (!accessToken || expiresAt === void 0) return;
|
|
@@ -553,6 +793,7 @@ var jsonTokenSerializer = {
|
|
|
553
793
|
deserialize: (raw) => JSON.parse(raw)
|
|
554
794
|
};
|
|
555
795
|
var DEFAULT_MAX_AGE_MS = 30 * 24 * 3600 * 1e3;
|
|
796
|
+
var FUTURE_SKEW_MS = 6e4;
|
|
556
797
|
function createSessionStorage(options = {}) {
|
|
557
798
|
const key = options.key ?? "app.auth";
|
|
558
799
|
const refreshKey = options.refreshKey ?? `${key}.rt`;
|
|
@@ -571,7 +812,9 @@ function createSessionStorage(options = {}) {
|
|
|
571
812
|
const isFresh = (savedAt) => {
|
|
572
813
|
if (maxAgeMs <= 0) return true;
|
|
573
814
|
if (typeof savedAt !== "number" || !Number.isFinite(savedAt)) return false;
|
|
574
|
-
|
|
815
|
+
const now = Date.now();
|
|
816
|
+
if (savedAt > now + FUTURE_SKEW_MS) return false;
|
|
817
|
+
return now - savedAt <= maxAgeMs;
|
|
575
818
|
};
|
|
576
819
|
const parse = (raw) => {
|
|
577
820
|
if (!raw) return null;
|
|
@@ -683,155 +926,63 @@ function createSessionStorage(options = {}) {
|
|
|
683
926
|
};
|
|
684
927
|
}
|
|
685
928
|
|
|
686
|
-
// src/
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
929
|
+
// src/request-origin.ts
|
|
930
|
+
var ABSOLUTE_URL = /^([a-z][a-z\d+\-.]*:)?\/\//i;
|
|
931
|
+
var NETWORK_PATH = /^[\\/]{2}/;
|
|
932
|
+
var SCHEME = /^[a-z][a-z\d+\-.]*:/i;
|
|
933
|
+
function normalizeUrl(value) {
|
|
934
|
+
if (typeof value !== "string") return void 0;
|
|
935
|
+
return value.replace(/[\u0000-\u001F\u007F]/g, "").trim();
|
|
692
936
|
}
|
|
693
|
-
function
|
|
694
|
-
if (!error.config) return error;
|
|
937
|
+
function parseUrl(url, base) {
|
|
695
938
|
try {
|
|
696
|
-
|
|
697
|
-
value: error.config,
|
|
698
|
-
enumerable: false,
|
|
699
|
-
configurable: true,
|
|
700
|
-
writable: true
|
|
701
|
-
});
|
|
939
|
+
return base ? new URL(url, base) : new URL(url);
|
|
702
940
|
} catch {
|
|
941
|
+
return null;
|
|
703
942
|
}
|
|
704
|
-
return error;
|
|
705
943
|
}
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
"
|
|
709
|
-
"http",
|
|
710
|
-
"business",
|
|
711
|
-
"canceled",
|
|
712
|
-
"unknown"
|
|
713
|
-
]);
|
|
714
|
-
function isNormalized(error) {
|
|
715
|
-
if (!error || typeof error !== "object") return false;
|
|
716
|
-
const candidate = error;
|
|
717
|
-
return typeof candidate.message === "string" && KINDS.has(candidate.kind);
|
|
718
|
-
}
|
|
719
|
-
function readableMessage(error) {
|
|
720
|
-
if (error instanceof Error && error.message.trim()) return error.message;
|
|
721
|
-
if (typeof error === "string" && error.trim()) return error.trim();
|
|
722
|
-
return "\u672A\u77E5\u9519\u8BEF";
|
|
944
|
+
function originOf(url, base) {
|
|
945
|
+
const parsed = parseUrl(url, base);
|
|
946
|
+
return parsed && parsed.origin !== "null" ? parsed.origin : void 0;
|
|
723
947
|
}
|
|
724
|
-
|
|
725
|
-
if (isNormalized(error)) return error;
|
|
726
|
-
if (error instanceof Error && "__business__" in error && error.__business__) {
|
|
727
|
-
const business = error;
|
|
728
|
-
return {
|
|
729
|
-
kind: "business",
|
|
730
|
-
code: business.code,
|
|
731
|
-
message: business.message?.trim() ? business.message : "\u4E1A\u52A1\u5904\u7406\u5931\u8D25",
|
|
732
|
-
config: business.config,
|
|
733
|
-
raw: business.raw ?? business
|
|
734
|
-
};
|
|
735
|
-
}
|
|
736
|
-
const axiosError = error;
|
|
737
|
-
if (!axiosError?.isAxiosError) {
|
|
738
|
-
return {
|
|
739
|
-
kind: "unknown",
|
|
740
|
-
message: readableMessage(error),
|
|
741
|
-
config: error?.config,
|
|
742
|
-
raw: error
|
|
743
|
-
};
|
|
744
|
-
}
|
|
745
|
-
if (axiosError.code === "ERR_CANCELED") {
|
|
746
|
-
return {
|
|
747
|
-
kind: "canceled",
|
|
748
|
-
message: "\u8BF7\u6C42\u5DF2\u53D6\u6D88",
|
|
749
|
-
config: axiosError.config,
|
|
750
|
-
raw: error
|
|
751
|
-
};
|
|
752
|
-
}
|
|
753
|
-
if (axiosError.code === "ECONNABORTED" || axiosError.code === "ETIMEDOUT" || axiosError.message?.includes("timeout")) {
|
|
754
|
-
return {
|
|
755
|
-
kind: "timeout",
|
|
756
|
-
message: "\u8BF7\u6C42\u8D85\u65F6\uFF0C\u8BF7\u7A0D\u540E\u91CD\u8BD5",
|
|
757
|
-
config: axiosError.config,
|
|
758
|
-
raw: error
|
|
759
|
-
};
|
|
760
|
-
}
|
|
761
|
-
if (!axiosError.response) {
|
|
762
|
-
return {
|
|
763
|
-
kind: "network",
|
|
764
|
-
message: "\u7F51\u7EDC\u5F02\u5E38\uFF0C\u8BF7\u68C0\u67E5\u8FDE\u63A5",
|
|
765
|
-
config: axiosError.config,
|
|
766
|
-
raw: error
|
|
767
|
-
};
|
|
768
|
-
}
|
|
769
|
-
const { status, data } = axiosError.response;
|
|
770
|
-
const body = await readMessageBody(data);
|
|
771
|
-
return {
|
|
772
|
-
kind: "http",
|
|
773
|
-
status,
|
|
774
|
-
message: pickServerMessage(body) ?? `\u8BF7\u6C42\u5931\u8D25\uFF08${status}\uFF09`,
|
|
775
|
-
config: axiosError.config,
|
|
776
|
-
raw: error
|
|
777
|
-
};
|
|
778
|
-
}
|
|
779
|
-
async function readMessageBody(data) {
|
|
780
|
-
if (typeof Blob !== "undefined" && data instanceof Blob) {
|
|
781
|
-
const type = data.type ?? "";
|
|
782
|
-
const textual = !type || type.includes("json") || type.startsWith("text/");
|
|
783
|
-
if (!textual) return data;
|
|
784
|
-
try {
|
|
785
|
-
const text = await data.text();
|
|
786
|
-
return parseJsonText(text) ?? text;
|
|
787
|
-
} catch {
|
|
788
|
-
return data;
|
|
789
|
-
}
|
|
790
|
-
}
|
|
791
|
-
if (typeof ArrayBuffer !== "undefined") {
|
|
792
|
-
if (data instanceof ArrayBuffer || ArrayBuffer.isView(data)) {
|
|
793
|
-
try {
|
|
794
|
-
return parseJsonText(new TextDecoder().decode(data)) ?? data;
|
|
795
|
-
} catch {
|
|
796
|
-
return data;
|
|
797
|
-
}
|
|
798
|
-
}
|
|
799
|
-
}
|
|
800
|
-
return data;
|
|
801
|
-
}
|
|
802
|
-
function parseJsonText(text) {
|
|
803
|
-
const trimmed = text.trim();
|
|
804
|
-
if (!trimmed) return void 0;
|
|
948
|
+
function currentOrigin() {
|
|
805
949
|
try {
|
|
806
|
-
return
|
|
950
|
+
return typeof location !== "undefined" && location.origin ? location.origin : void 0;
|
|
807
951
|
} catch {
|
|
808
952
|
return void 0;
|
|
809
953
|
}
|
|
810
954
|
}
|
|
811
|
-
function
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
const body = data;
|
|
818
|
-
for (const value of [body.message, body.msg, body.MSG]) {
|
|
819
|
-
if (typeof value === "string" && value.trim()) return value.trim();
|
|
820
|
-
}
|
|
821
|
-
}
|
|
822
|
-
return void 0;
|
|
955
|
+
function referenceOrigin(baseURL) {
|
|
956
|
+
const base = normalizeUrl(baseURL);
|
|
957
|
+
const current = currentOrigin();
|
|
958
|
+
if (!base) return current;
|
|
959
|
+
if (!ABSOLUTE_URL.test(base) && !NETWORK_PATH.test(base)) return current;
|
|
960
|
+
return originOf(base, current);
|
|
823
961
|
}
|
|
824
|
-
function
|
|
825
|
-
const
|
|
826
|
-
if (
|
|
827
|
-
|
|
962
|
+
function isSameOriginRequest(config) {
|
|
963
|
+
const url = normalizeUrl(config.url);
|
|
964
|
+
if (!url) return true;
|
|
965
|
+
const networkPath = NETWORK_PATH.test(url);
|
|
966
|
+
const hasScheme = SCHEME.test(url);
|
|
967
|
+
if (!networkPath && !hasScheme) return true;
|
|
968
|
+
const axiosAbsolute = ABSOLUTE_URL.test(url);
|
|
969
|
+
const reference = referenceOrigin(config.baseURL);
|
|
970
|
+
if (hasScheme && !axiosAbsolute && !networkPath) {
|
|
971
|
+
const standalone = originOf(url);
|
|
972
|
+
if (standalone === void 0) {
|
|
973
|
+
return true;
|
|
974
|
+
}
|
|
975
|
+
if (!reference) return false;
|
|
976
|
+
if (standalone !== reference) return false;
|
|
977
|
+
return originOf(url, reference) === reference;
|
|
828
978
|
}
|
|
829
|
-
if (
|
|
830
|
-
|
|
979
|
+
if (!reference) return false;
|
|
980
|
+
const target = originOf(url, reference);
|
|
981
|
+
return target !== void 0 && target === reference;
|
|
831
982
|
}
|
|
832
983
|
|
|
833
984
|
// src/plugins/api-key.ts
|
|
834
|
-
function createApiKeyInterceptor(options) {
|
|
985
|
+
function createApiKeyInterceptor(options, allowCrossOriginAuth = false) {
|
|
835
986
|
const {
|
|
836
987
|
getApiKey,
|
|
837
988
|
transport = "header",
|
|
@@ -840,6 +991,7 @@ function createApiKeyInterceptor(options) {
|
|
|
840
991
|
} = options;
|
|
841
992
|
return async (config) => {
|
|
842
993
|
if (config.skipApiKey) return config;
|
|
994
|
+
if (!allowCrossOriginAuth && !isSameOriginRequest(config)) return config;
|
|
843
995
|
const key = await getApiKey();
|
|
844
996
|
if (!key) return config;
|
|
845
997
|
if (transport === "authorization") {
|
|
@@ -960,6 +1112,19 @@ function createUnwrapInterceptor(options = {}) {
|
|
|
960
1112
|
// src/plugins/jwt.ts
|
|
961
1113
|
var DEFAULT_STATUSES = [401];
|
|
962
1114
|
var DEFAULT_CODES = [401];
|
|
1115
|
+
var IDEMPOTENT_METHODS = /* @__PURE__ */ new Set([
|
|
1116
|
+
"get",
|
|
1117
|
+
"head",
|
|
1118
|
+
"options"
|
|
1119
|
+
]);
|
|
1120
|
+
function isReplayableData(data) {
|
|
1121
|
+
if (data === void 0 || data === null) return true;
|
|
1122
|
+
if (typeof ReadableStream !== "undefined" && data instanceof ReadableStream) {
|
|
1123
|
+
return false;
|
|
1124
|
+
}
|
|
1125
|
+
const nodeStream = data;
|
|
1126
|
+
return !(typeof nodeStream.pipe === "function" && typeof nodeStream.read === "function");
|
|
1127
|
+
}
|
|
963
1128
|
function isBusinessFailure(error) {
|
|
964
1129
|
return error !== null && typeof error === "object" && error.__business__ === true;
|
|
965
1130
|
}
|
|
@@ -982,9 +1147,10 @@ function defaultRefreshWhen(failure) {
|
|
|
982
1147
|
const matches = (value, candidates) => value !== void 0 && candidates.some((candidate) => String(candidate) === String(value));
|
|
983
1148
|
return matches(failure.status, DEFAULT_STATUSES) || matches(failure.code, DEFAULT_CODES);
|
|
984
1149
|
}
|
|
985
|
-
function createJwtRequestInterceptor(session, refreshBeforeExpirationMs = 6e4) {
|
|
1150
|
+
function createJwtRequestInterceptor(session, refreshBeforeExpirationMs = 6e4, allowCrossOriginAuth = false) {
|
|
986
1151
|
return async (config) => {
|
|
987
1152
|
if (config.skipAuth) return config;
|
|
1153
|
+
if (!allowCrossOriginAuth && !isSameOriginRequest(config)) return config;
|
|
988
1154
|
let token = session.getAccessToken();
|
|
989
1155
|
if (token && session.isExpiringSoon(refreshBeforeExpirationMs) && !session.isCoolingDown("proactive")) {
|
|
990
1156
|
try {
|
|
@@ -1000,6 +1166,8 @@ function createJwtRequestInterceptor(session, refreshBeforeExpirationMs = 6e4) {
|
|
|
1000
1166
|
);
|
|
1001
1167
|
}
|
|
1002
1168
|
config._tokenVersion = session.getVersion();
|
|
1169
|
+
config._sessionId = session.getSessionId();
|
|
1170
|
+
config._authedAtSend = Boolean(config.headers.get("Authorization"));
|
|
1003
1171
|
return config;
|
|
1004
1172
|
};
|
|
1005
1173
|
}
|
|
@@ -1011,6 +1179,9 @@ function createJwtResponseInterceptor(instance, session, options = {}) {
|
|
|
1011
1179
|
if (!config || config.skipAuth || config.skipRefresh || config._retry) {
|
|
1012
1180
|
return Promise.reject(rawError);
|
|
1013
1181
|
}
|
|
1182
|
+
if (!(options.allowCrossOriginAuth ?? false) && !isSameOriginRequest(config)) {
|
|
1183
|
+
return Promise.reject(rawError);
|
|
1184
|
+
}
|
|
1014
1185
|
if (!isBusinessFailure(rawError) && !error.response) {
|
|
1015
1186
|
return Promise.reject(rawError);
|
|
1016
1187
|
}
|
|
@@ -1023,18 +1194,40 @@ function createJwtResponseInterceptor(instance, session, options = {}) {
|
|
|
1023
1194
|
}
|
|
1024
1195
|
if (!shouldRefresh) return Promise.reject(rawError);
|
|
1025
1196
|
config._retry = true;
|
|
1197
|
+
const method = (config.method ?? "get").toLowerCase();
|
|
1198
|
+
const canReplay = IDEMPOTENT_METHODS.has(method) || (config.retryUnauthorized ?? options.retryOnUnauthorized ?? false);
|
|
1199
|
+
const bodyReplayable = isReplayableData(config.data) && !config.signal?.aborted;
|
|
1200
|
+
const sameSession = () => {
|
|
1201
|
+
if (config._sessionId !== void 0) {
|
|
1202
|
+
return session.getSessionId() === config._sessionId;
|
|
1203
|
+
}
|
|
1204
|
+
return !config._authedAtSend;
|
|
1205
|
+
};
|
|
1026
1206
|
if (config._tokenVersion !== void 0 && config._tokenVersion !== session.getVersion()) {
|
|
1207
|
+
if (!canReplay) return Promise.reject(rawError);
|
|
1027
1208
|
const latest = session.getAccessToken();
|
|
1028
|
-
if (!latest
|
|
1209
|
+
if (!latest || !sameSession() || !bodyReplayable) {
|
|
1210
|
+
return Promise.reject(rawError);
|
|
1211
|
+
}
|
|
1029
1212
|
config.headers.set(
|
|
1030
1213
|
"Authorization",
|
|
1031
1214
|
`${session.getTokenType()} ${latest}`
|
|
1032
1215
|
);
|
|
1033
1216
|
return instance(config);
|
|
1034
1217
|
}
|
|
1218
|
+
if (!canReplay) {
|
|
1219
|
+
if (!isBusinessFailure(rawError) || options.refreshWhen !== void 0) {
|
|
1220
|
+
try {
|
|
1221
|
+
await session.refresh("unauthorized");
|
|
1222
|
+
} catch {
|
|
1223
|
+
}
|
|
1224
|
+
}
|
|
1225
|
+
return Promise.reject(rawError);
|
|
1226
|
+
}
|
|
1035
1227
|
try {
|
|
1036
1228
|
const snapshot = await session.refresh("unauthorized");
|
|
1037
1229
|
if (!snapshot.accessToken) return Promise.reject(rawError);
|
|
1230
|
+
if (!sameSession() || !bodyReplayable) return Promise.reject(rawError);
|
|
1038
1231
|
config.headers.set(
|
|
1039
1232
|
"Authorization",
|
|
1040
1233
|
`${snapshot.tokenType} ${snapshot.accessToken}`
|
|
@@ -1234,8 +1427,18 @@ function createHttp(options) {
|
|
|
1234
1427
|
baseURL,
|
|
1235
1428
|
timeout,
|
|
1236
1429
|
withCredentials,
|
|
1430
|
+
...options.headers ? { headers: options.headers } : {},
|
|
1237
1431
|
...adapter ? { adapter } : {}
|
|
1238
1432
|
});
|
|
1433
|
+
if (options.instance) {
|
|
1434
|
+
if (options.adapter) options.instance.defaults.adapter = options.adapter;
|
|
1435
|
+
if (options.headers) {
|
|
1436
|
+
Object.assign(
|
|
1437
|
+
options.instance.defaults.headers.common,
|
|
1438
|
+
options.headers
|
|
1439
|
+
);
|
|
1440
|
+
}
|
|
1441
|
+
}
|
|
1239
1442
|
const requestSteps = [];
|
|
1240
1443
|
const responseSteps = [];
|
|
1241
1444
|
const loggerInterceptors = options.logger ? createLoggerInterceptors(options.logger) : null;
|
|
@@ -1247,24 +1450,15 @@ function createHttp(options) {
|
|
|
1247
1450
|
)) {
|
|
1248
1451
|
requestSteps.push({ name: "business:beforeAuth", spec });
|
|
1249
1452
|
}
|
|
1250
|
-
if (options.headers && Object.keys(options.headers).length > 0) {
|
|
1251
|
-
const headers = options.headers;
|
|
1252
|
-
requestSteps.push({
|
|
1253
|
-
name: "headers",
|
|
1254
|
-
spec: {
|
|
1255
|
-
onFulfilled: (config) => {
|
|
1256
|
-
for (const [key, value] of Object.entries(headers)) {
|
|
1257
|
-
config.headers.set(key, value);
|
|
1258
|
-
}
|
|
1259
|
-
return config;
|
|
1260
|
-
}
|
|
1261
|
-
}
|
|
1262
|
-
});
|
|
1263
|
-
}
|
|
1264
1453
|
if (options.apiKey) {
|
|
1265
1454
|
requestSteps.push({
|
|
1266
1455
|
name: "api-key",
|
|
1267
|
-
spec: {
|
|
1456
|
+
spec: {
|
|
1457
|
+
onFulfilled: createApiKeyInterceptor(
|
|
1458
|
+
options.apiKey,
|
|
1459
|
+
options.allowCrossOriginAuth
|
|
1460
|
+
)
|
|
1461
|
+
}
|
|
1268
1462
|
});
|
|
1269
1463
|
}
|
|
1270
1464
|
if (options.jwt !== false) {
|
|
@@ -1273,7 +1467,8 @@ function createHttp(options) {
|
|
|
1273
1467
|
spec: {
|
|
1274
1468
|
onFulfilled: createJwtRequestInterceptor(
|
|
1275
1469
|
session,
|
|
1276
|
-
options.refreshBeforeExpirationMs
|
|
1470
|
+
options.refreshBeforeExpirationMs,
|
|
1471
|
+
options.allowCrossOriginAuth
|
|
1277
1472
|
)
|
|
1278
1473
|
}
|
|
1279
1474
|
});
|
|
@@ -1297,7 +1492,9 @@ function createHttp(options) {
|
|
|
1297
1492
|
name: "jwt",
|
|
1298
1493
|
spec: {
|
|
1299
1494
|
onRejected: createJwtResponseInterceptor(http, session, {
|
|
1300
|
-
refreshWhen: options.refreshWhen
|
|
1495
|
+
refreshWhen: options.refreshWhen,
|
|
1496
|
+
allowCrossOriginAuth: options.allowCrossOriginAuth,
|
|
1497
|
+
retryOnUnauthorized: options.retryOnUnauthorized
|
|
1301
1498
|
})
|
|
1302
1499
|
}
|
|
1303
1500
|
});
|