@autional/shared 0.1.0-rc.65 → 0.1.0-rc.67
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/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@autional/shared",
|
|
3
|
-
"version": "0.1.0-rc.
|
|
3
|
+
"version": "0.1.0-rc.67",
|
|
4
4
|
"description": "Autional shared layer — API client, auth, types, hooks, utils",
|
|
5
5
|
"license": "AGPL-3.0",
|
|
6
6
|
"main": "./src/index.ts",
|
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
"./fetch": "./src/api/fetch-client.ts",
|
|
15
15
|
"./jwt": "./src/auth/jwt-payload.ts",
|
|
16
16
|
"./pkce": "./src/auth/pkce.ts",
|
|
17
|
-
"./console-auth": "./src/console-auth/
|
|
17
|
+
"./console-auth": "./src/console-auth/index.ts",
|
|
18
18
|
"./generated/api": "./src/generated/api.ts",
|
|
19
19
|
"./generated/types": "./src/generated/types.ts",
|
|
20
20
|
"./generated/queries": "./src/generated/queries.ts",
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { describe, expect, it } from 'vitest';
|
|
2
2
|
import {
|
|
3
3
|
expiresAtFromToken,
|
|
4
|
+
mergeTokenClaims,
|
|
4
5
|
pickClaimRoles,
|
|
5
6
|
pickClaimString,
|
|
6
7
|
sessionExpiryAt,
|
|
@@ -136,3 +137,36 @@ describe('sessionExpiryAt', () => {
|
|
|
136
137
|
expect(sessionExpiryAt(jwt({ sub: 'u' }), 12345)).toBe(12345);
|
|
137
138
|
});
|
|
138
139
|
});
|
|
140
|
+
|
|
141
|
+
describe('mergeTokenClaims', () => {
|
|
142
|
+
it('id_token 优先,access_token 补缺(tenant_id 只在 access 里也拿得到)', () => {
|
|
143
|
+
const access = jwt({ sub: 'u1', tenant_id: 't-1', roles: ['admin'] });
|
|
144
|
+
const id = jwt({ sub: 'u1', name: '张三', nonce: 'n-1' });
|
|
145
|
+
expect(mergeTokenClaims(access, id)).toMatchObject({
|
|
146
|
+
name: '张三',
|
|
147
|
+
tenant_id: 't-1',
|
|
148
|
+
nonce: 'n-1',
|
|
149
|
+
roles: ['admin'],
|
|
150
|
+
});
|
|
151
|
+
});
|
|
152
|
+
|
|
153
|
+
it('同名字段以 id_token 为准', () => {
|
|
154
|
+
const access = jwt({ sub: 'u1', name: '来自 access' });
|
|
155
|
+
const id = jwt({ sub: 'u1', name: '来自 id' });
|
|
156
|
+
expect(mergeTokenClaims(access, id)?.name).toBe('来自 id');
|
|
157
|
+
});
|
|
158
|
+
|
|
159
|
+
it('只有一份令牌时用它', () => {
|
|
160
|
+
const access = jwt({ sub: 'u1', tenant_id: 't-1' });
|
|
161
|
+
expect(mergeTokenClaims(access, undefined)?.tenant_id).toBe('t-1');
|
|
162
|
+
expect(mergeTokenClaims(undefined, access)?.tenant_id).toBe('t-1');
|
|
163
|
+
});
|
|
164
|
+
|
|
165
|
+
it('两份都缺 → null', () => {
|
|
166
|
+
expect(mergeTokenClaims(undefined, undefined)).toBeNull();
|
|
167
|
+
});
|
|
168
|
+
|
|
169
|
+
it('坏令牌不抛错', () => {
|
|
170
|
+
expect(() => mergeTokenClaims('bad', 'also-bad')).not.toThrow();
|
|
171
|
+
});
|
|
172
|
+
});
|
|
@@ -0,0 +1,400 @@
|
|
|
1
|
+
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
|
2
|
+
import type { ConsoleAuthOptions, ConsoleSession } from '@autional/shared/console-auth';
|
|
3
|
+
import { createConsoleAuth } from '@autional/shared/console-auth';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* 引擎测试:两站流程合并成一份后,这里的行为就是**两站的行为**。
|
|
7
|
+
* 用假 window(storage / location)+ 假 fetch,覆盖:
|
|
8
|
+
* mock 演示会话、PKCE 跳转、state/nonce 校验、续期单飞、4xx 清会话 / 5xx 保活、
|
|
9
|
+
* 过期判定、storage 策略参数、旧 key 迁移、登出吊销。
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
type MemStorage = {
|
|
13
|
+
getItem: (key: string) => string | null;
|
|
14
|
+
setItem: (key: string, value: string) => void;
|
|
15
|
+
removeItem: (key: string) => void;
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
function memoryStorage(): MemStorage {
|
|
19
|
+
const map = new Map<string, string>();
|
|
20
|
+
return {
|
|
21
|
+
getItem: (key: string) => map.get(key) ?? null,
|
|
22
|
+
setItem: (key: string, value: string) => void map.set(key, String(value)),
|
|
23
|
+
removeItem: (key: string) => void map.delete(key),
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** 造一个 payload 可解的最小 JWT。 */
|
|
28
|
+
function jwt(payload: Record<string, unknown>): string {
|
|
29
|
+
const b64 = (obj: unknown) =>
|
|
30
|
+
Buffer.from(JSON.stringify(obj))
|
|
31
|
+
.toString('base64')
|
|
32
|
+
.replace(/\+/g, '-')
|
|
33
|
+
.replace(/\//g, '_')
|
|
34
|
+
.replace(/=+$/, '');
|
|
35
|
+
return `${b64({ alg: 'none' })}.${b64(payload)}.sig`;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const KEYS = { session: 'test:auth', pkce: 'test:pkce', mockSignedOut: 'test:signed-out' };
|
|
39
|
+
|
|
40
|
+
let local: MemStorage;
|
|
41
|
+
let session: MemStorage;
|
|
42
|
+
let assigned: string[];
|
|
43
|
+
|
|
44
|
+
function installWindow() {
|
|
45
|
+
local = memoryStorage();
|
|
46
|
+
session = memoryStorage();
|
|
47
|
+
assigned = [];
|
|
48
|
+
vi.stubGlobal('window', {
|
|
49
|
+
localStorage: local,
|
|
50
|
+
sessionStorage: session,
|
|
51
|
+
location: { origin: 'https://test.local', search: '', assign: (url: string) => assigned.push(url) },
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function options(overrides: Partial<ConsoleAuthOptions> = {}): ConsoleAuthOptions {
|
|
56
|
+
return {
|
|
57
|
+
authMode: 'oidc',
|
|
58
|
+
storage: 'local',
|
|
59
|
+
keys: KEYS,
|
|
60
|
+
oidc: {
|
|
61
|
+
authorizeUrl: 'https://idp.test/authorize',
|
|
62
|
+
tokenUrl: 'https://idp.test/token',
|
|
63
|
+
clientId: 'client-1',
|
|
64
|
+
scope: 'openid profile',
|
|
65
|
+
redirectUri: 'https://test.local/oauth/callback',
|
|
66
|
+
},
|
|
67
|
+
mockSession: () => ({
|
|
68
|
+
mode: 'mock',
|
|
69
|
+
accessToken: '',
|
|
70
|
+
expiresAt: 0,
|
|
71
|
+
user: { sub: 'demo', name: '演示', email: '', tenantId: 't-demo', appId: '', roles: ['super_admin'] },
|
|
72
|
+
}),
|
|
73
|
+
assign: (url: string) => assigned.push(url),
|
|
74
|
+
...overrides,
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function tokenResponse(extra: Record<string, unknown> = {}) {
|
|
79
|
+
return new Response(
|
|
80
|
+
JSON.stringify({
|
|
81
|
+
access_token: jwt({ sub: 'u1', exp: 1_900_000_000, tenant_id: 't-1', roles: ['admin'] }),
|
|
82
|
+
refresh_token: 'r-2',
|
|
83
|
+
id_token: jwt({ sub: 'u1', name: '张三', nonce: 'n-1', exp: 1_900_000_000 }),
|
|
84
|
+
expires_in: 3600,
|
|
85
|
+
...extra,
|
|
86
|
+
}),
|
|
87
|
+
{ status: 200, headers: { 'content-type': 'application/json' } },
|
|
88
|
+
);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function seedSession(overrides: Record<string, unknown> = {}) {
|
|
92
|
+
const target = local;
|
|
93
|
+
target.setItem(
|
|
94
|
+
KEYS.session,
|
|
95
|
+
JSON.stringify({
|
|
96
|
+
mode: 'oidc',
|
|
97
|
+
accessToken: 'access-token',
|
|
98
|
+
refreshToken: 'r-1',
|
|
99
|
+
expiresAt: Date.now() + 3_600_000,
|
|
100
|
+
user: { sub: 'u1', name: 'QA', email: 'q@e.test', tenantId: 't-1', appId: 'a-1', roles: ['admin'] },
|
|
101
|
+
...overrides,
|
|
102
|
+
}),
|
|
103
|
+
);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
beforeEach(() => {
|
|
107
|
+
vi.unstubAllGlobals();
|
|
108
|
+
vi.unstubAllEnvs();
|
|
109
|
+
installWindow();
|
|
110
|
+
});
|
|
111
|
+
|
|
112
|
+
describe('mock 模式', () => {
|
|
113
|
+
it('未退出 → 演示会话;退出后 → null(不自动回填)', async () => {
|
|
114
|
+
const auth = createConsoleAuth(options({ authMode: 'mock' }));
|
|
115
|
+
expect(auth.currentSession()?.mode).toBe('mock');
|
|
116
|
+
await auth.signOut();
|
|
117
|
+
expect(auth.currentSession()).toBeNull();
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
it('signOut 不发网络请求(mock 没有可吊销的令牌)', async () => {
|
|
121
|
+
const fetchMock = vi.fn();
|
|
122
|
+
vi.stubGlobal('fetch', fetchMock);
|
|
123
|
+
const auth = createConsoleAuth(options({ authMode: 'mock' }));
|
|
124
|
+
await auth.signOut();
|
|
125
|
+
expect(fetchMock).not.toHaveBeenCalled();
|
|
126
|
+
});
|
|
127
|
+
});
|
|
128
|
+
|
|
129
|
+
describe('startLogin(授权跳转)', () => {
|
|
130
|
+
it('生成 PKCE 并跳转,参数齐全', async () => {
|
|
131
|
+
const auth = createConsoleAuth(options());
|
|
132
|
+
expect(await auth.startLogin()).toBeNull();
|
|
133
|
+
|
|
134
|
+
expect(assigned).toHaveLength(1);
|
|
135
|
+
const url = new URL(assigned[0]);
|
|
136
|
+
expect(url.origin + url.pathname).toBe('https://idp.test/authorize');
|
|
137
|
+
expect(url.searchParams.get('response_type')).toBe('code');
|
|
138
|
+
expect(url.searchParams.get('client_id')).toBe('client-1');
|
|
139
|
+
expect(url.searchParams.get('code_challenge_method')).toBe('S256');
|
|
140
|
+
expect(url.searchParams.get('code_challenge')).toMatch(/^[A-Za-z0-9_-]{43}$/);
|
|
141
|
+
expect(url.searchParams.get('state')).toBeTruthy();
|
|
142
|
+
expect(url.searchParams.get('nonce')).toBeTruthy();
|
|
143
|
+
expect(url.searchParams.get('redirect_uri')).toBe('https://test.local/oauth/callback');
|
|
144
|
+
|
|
145
|
+
// PKCE 上下文落盘(含 verifier,供回调时换取令牌)
|
|
146
|
+
const pkce = JSON.parse(local.getItem(KEYS.pkce) as string);
|
|
147
|
+
expect(pkce.verifier).toMatch(/^[A-Za-z0-9\-._~]{43,128}$/);
|
|
148
|
+
expect(pkce.redirectUri).toBe('https://test.local/oauth/callback');
|
|
149
|
+
});
|
|
150
|
+
|
|
151
|
+
it('缺 clientId → 抛错且不跳转', async () => {
|
|
152
|
+
const auth = createConsoleAuth(options({ oidc: { ...options().oidc, clientId: '' } }));
|
|
153
|
+
await expect(auth.startLogin()).rejects.toThrow(/VITE_OIDC_CLIENT_ID/);
|
|
154
|
+
expect(assigned).toEqual([]);
|
|
155
|
+
});
|
|
156
|
+
});
|
|
157
|
+
|
|
158
|
+
describe('completeLogin(回调换票)', () => {
|
|
159
|
+
function seedPkce(state = 's-1', nonce = 'n-1') {
|
|
160
|
+
local.setItem(KEYS.pkce, JSON.stringify({ verifier: 'v', state, nonce, redirectUri: 'https://test.local/cb', at: Date.now() }));
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
it('正常换票 → 会话落盘;tenant_id 来自 access_token(声明合并)', async () => {
|
|
164
|
+
seedPkce();
|
|
165
|
+
vi.stubGlobal('fetch', vi.fn(async () => tokenResponse()));
|
|
166
|
+
const auth = createConsoleAuth(options());
|
|
167
|
+
|
|
168
|
+
const session = await auth.completeLogin('?code=c&state=s-1');
|
|
169
|
+
expect(session.mode).toBe('oidc');
|
|
170
|
+
expect(session.user.name).toBe('张三'); // 来自 id_token
|
|
171
|
+
expect(session.user.tenantId).toBe('t-1'); // 只在 access_token 里,靠合并拿到
|
|
172
|
+
expect(session.user.roles).toEqual(['admin']);
|
|
173
|
+
expect(session.expiresAt).toBe(1_900_000_000 * 1000);
|
|
174
|
+
expect(local.getItem(KEYS.session)).not.toBeNull();
|
|
175
|
+
expect(local.getItem(KEYS.pkce)).toBeNull();
|
|
176
|
+
});
|
|
177
|
+
|
|
178
|
+
it('state 不匹配 → 抛错且不落会话', async () => {
|
|
179
|
+
seedPkce('expected');
|
|
180
|
+
vi.stubGlobal('fetch', vi.fn(async () => tokenResponse()));
|
|
181
|
+
const auth = createConsoleAuth(options());
|
|
182
|
+
await expect(auth.completeLogin('?code=c&state=other')).rejects.toThrow(/state/);
|
|
183
|
+
expect(local.getItem(KEYS.session)).toBeNull();
|
|
184
|
+
});
|
|
185
|
+
|
|
186
|
+
it('nonce 不匹配 → 抛错且清 PKCE(防重放)', async () => {
|
|
187
|
+
seedPkce('s-1', 'expected-nonce');
|
|
188
|
+
vi.stubGlobal('fetch', vi.fn(async () => tokenResponse()));
|
|
189
|
+
const auth = createConsoleAuth(options());
|
|
190
|
+
await expect(auth.completeLogin('?code=c&state=s-1')).rejects.toThrow(/nonce/);
|
|
191
|
+
expect(local.getItem(KEYS.pkce)).toBeNull();
|
|
192
|
+
});
|
|
193
|
+
|
|
194
|
+
it('授权端点回 error → 抛错带错误码', async () => {
|
|
195
|
+
const auth = createConsoleAuth(options());
|
|
196
|
+
await expect(auth.completeLogin('?error=access_denied')).rejects.toThrow(/access_denied/);
|
|
197
|
+
});
|
|
198
|
+
|
|
199
|
+
it('缺 code → 抛错', async () => {
|
|
200
|
+
const auth = createConsoleAuth(options());
|
|
201
|
+
await expect(auth.completeLogin('?state=s')).rejects.toThrow(/code/);
|
|
202
|
+
});
|
|
203
|
+
|
|
204
|
+
it('缺 PKCE 上下文 → 抛错', async () => {
|
|
205
|
+
const auth = createConsoleAuth(options());
|
|
206
|
+
await expect(auth.completeLogin('?code=c&state=s')).rejects.toThrow(/PKCE/);
|
|
207
|
+
});
|
|
208
|
+
});
|
|
209
|
+
|
|
210
|
+
describe('refreshSession(续期)', () => {
|
|
211
|
+
it('并发只发一次令牌请求(单飞)', async () => {
|
|
212
|
+
seedSession();
|
|
213
|
+
const fetchMock = vi.fn(async () => tokenResponse());
|
|
214
|
+
vi.stubGlobal('fetch', fetchMock);
|
|
215
|
+
const auth = createConsoleAuth(options());
|
|
216
|
+
|
|
217
|
+
const [a, b] = await Promise.all([auth.refreshSession(), auth.refreshSession()]);
|
|
218
|
+
expect(fetchMock).toHaveBeenCalledTimes(1);
|
|
219
|
+
expect(a?.refreshToken).toBe('r-2');
|
|
220
|
+
expect(b?.refreshToken).toBe('r-2');
|
|
221
|
+
});
|
|
222
|
+
|
|
223
|
+
it('4xx(invalid_grant)→ 返回 null 并清会话', async () => {
|
|
224
|
+
seedSession();
|
|
225
|
+
vi.stubGlobal('fetch', vi.fn(async () => new Response(JSON.stringify({ error: 'invalid_grant' }), { status: 400 })));
|
|
226
|
+
const auth = createConsoleAuth(options());
|
|
227
|
+
await expect(auth.refreshSession()).resolves.toBeNull();
|
|
228
|
+
expect(local.getItem(KEYS.session)).toBeNull();
|
|
229
|
+
});
|
|
230
|
+
|
|
231
|
+
it('5xx → 不清会话,并把有效期延长约 transientGraceMs', async () => {
|
|
232
|
+
seedSession();
|
|
233
|
+
vi.stubGlobal('fetch', vi.fn(async () => new Response('{}', { status: 502 })));
|
|
234
|
+
const auth = createConsoleAuth(options({ transientGraceMs: 30_000 }));
|
|
235
|
+
|
|
236
|
+
const before = Date.now();
|
|
237
|
+
const kept = await auth.refreshSession();
|
|
238
|
+
expect(kept).not.toBeNull();
|
|
239
|
+
expect(local.getItem(KEYS.session)).not.toBeNull();
|
|
240
|
+
expect(kept?.expiresAt).toBeGreaterThanOrEqual(before + 29_000);
|
|
241
|
+
});
|
|
242
|
+
|
|
243
|
+
it('网络异常 → 同样不清会话(瞬时)', async () => {
|
|
244
|
+
seedSession();
|
|
245
|
+
vi.stubGlobal('fetch', vi.fn(async () => Promise.reject(new Error('ECONNRESET'))));
|
|
246
|
+
const auth = createConsoleAuth(options());
|
|
247
|
+
await expect(auth.refreshSession()).resolves.not.toBeNull();
|
|
248
|
+
expect(local.getItem(KEYS.session)).not.toBeNull();
|
|
249
|
+
});
|
|
250
|
+
|
|
251
|
+
it('没有 refresh_token → null 并清会话', async () => {
|
|
252
|
+
seedSession({ refreshToken: undefined });
|
|
253
|
+
vi.stubGlobal('fetch', vi.fn());
|
|
254
|
+
const auth = createConsoleAuth(options());
|
|
255
|
+
await expect(auth.refreshSession()).resolves.toBeNull();
|
|
256
|
+
expect(local.getItem(KEYS.session)).toBeNull();
|
|
257
|
+
});
|
|
258
|
+
|
|
259
|
+
it('续期保留上一轮的租户/应用与补全过的展示名', async () => {
|
|
260
|
+
seedSession({
|
|
261
|
+
user: { sub: 'u1', name: '平台管理员', email: 'p@e.test', tenantId: 't-keep', appId: 'a-keep', roles: ['admin'] },
|
|
262
|
+
});
|
|
263
|
+
// 令牌里既没有 tenant/app,也没有 name → 展示名会落到「…<sub 尾段>」
|
|
264
|
+
vi.stubGlobal(
|
|
265
|
+
'fetch',
|
|
266
|
+
vi.fn(
|
|
267
|
+
async () =>
|
|
268
|
+
new Response(
|
|
269
|
+
JSON.stringify({
|
|
270
|
+
access_token: jwt({ sub: 'u1', exp: 1_900_000_000 }),
|
|
271
|
+
id_token: jwt({ sub: 'u1', exp: 1_900_000_000 }),
|
|
272
|
+
expires_in: 3600,
|
|
273
|
+
}),
|
|
274
|
+
{ status: 200, headers: { 'content-type': 'application/json' } },
|
|
275
|
+
),
|
|
276
|
+
),
|
|
277
|
+
);
|
|
278
|
+
const auth = createConsoleAuth(options());
|
|
279
|
+
const next = await auth.refreshSession();
|
|
280
|
+
expect(next?.user.name).toBe('平台管理员');
|
|
281
|
+
expect(next?.user.tenantId).toBe('t-keep');
|
|
282
|
+
expect(next?.user.appId).toBe('a-keep');
|
|
283
|
+
});
|
|
284
|
+
});
|
|
285
|
+
|
|
286
|
+
describe('currentSession(过期判定)', () => {
|
|
287
|
+
it('无会话 → null', () => {
|
|
288
|
+
expect(createConsoleAuth(options()).currentSession()).toBeNull();
|
|
289
|
+
});
|
|
290
|
+
|
|
291
|
+
it('以 JWT exp 为准:exp 已过(即使记录值未过)→ null', () => {
|
|
292
|
+
seedSession({ accessToken: jwt({ sub: 'u1', exp: Math.floor((Date.now() + 30_000) / 1000) }) });
|
|
293
|
+
expect(createConsoleAuth(options()).currentSession()).toBeNull();
|
|
294
|
+
});
|
|
295
|
+
|
|
296
|
+
it('未过期 → 返回会话', () => {
|
|
297
|
+
seedSession();
|
|
298
|
+
expect(createConsoleAuth(options()).currentSession()?.refreshToken).toBe('r-1');
|
|
299
|
+
});
|
|
300
|
+
|
|
301
|
+
it('存储内容损坏 → 清掉并返回 null', () => {
|
|
302
|
+
local.setItem(KEYS.session, '{not json');
|
|
303
|
+
const auth = createConsoleAuth(options());
|
|
304
|
+
expect(auth.currentSession()).toBeNull();
|
|
305
|
+
});
|
|
306
|
+
});
|
|
307
|
+
|
|
308
|
+
describe('storage 策略参数(唯一参数)', () => {
|
|
309
|
+
it("storage='session' → 只写 sessionStorage,localStorage 干净", async () => {
|
|
310
|
+
session.setItem(KEYS.pkce, JSON.stringify({ verifier: 'v', state: 's', nonce: 'n-1', redirectUri: 'u', at: Date.now() }));
|
|
311
|
+
vi.stubGlobal('fetch', vi.fn(async () => tokenResponse()));
|
|
312
|
+
const auth = createConsoleAuth(options({ storage: 'session' }));
|
|
313
|
+
await auth.completeLogin('?code=c&state=s');
|
|
314
|
+
|
|
315
|
+
expect(session.getItem(KEYS.session)).not.toBeNull();
|
|
316
|
+
expect(local.getItem(KEYS.session)).toBeNull();
|
|
317
|
+
});
|
|
318
|
+
|
|
319
|
+
it("storage='local' → 写 localStorage", async () => {
|
|
320
|
+
local.setItem(KEYS.pkce, JSON.stringify({ verifier: 'v', state: 's', nonce: 'n-1', redirectUri: 'u', at: Date.now() }));
|
|
321
|
+
vi.stubGlobal('fetch', vi.fn(async () => tokenResponse()));
|
|
322
|
+
const auth = createConsoleAuth(options({ storage: 'local' }));
|
|
323
|
+
await auth.completeLogin('?code=c&state=s');
|
|
324
|
+
|
|
325
|
+
expect(local.getItem(KEYS.session)).not.toBeNull();
|
|
326
|
+
expect(session.getItem(KEYS.session)).toBeNull();
|
|
327
|
+
});
|
|
328
|
+
});
|
|
329
|
+
|
|
330
|
+
describe('旧 key 迁移', () => {
|
|
331
|
+
it('新 key 为空时把旧值搬过来,并删掉旧 key', () => {
|
|
332
|
+
session.setItem('old:auth', JSON.stringify({ mode: 'oidc', accessToken: 'x', expiresAt: Date.now() + 600_000, user: { sub: 'u' } }));
|
|
333
|
+
const auth = createConsoleAuth(options({ legacy: { key: 'old:auth', from: 'session' } }));
|
|
334
|
+
expect(auth.currentSession()).not.toBeNull();
|
|
335
|
+
expect(local.getItem(KEYS.session)).not.toBeNull();
|
|
336
|
+
expect(session.getItem('old:auth')).toBeNull();
|
|
337
|
+
});
|
|
338
|
+
|
|
339
|
+
it('新 key 已有值时不覆盖', () => {
|
|
340
|
+
seedSession({ accessToken: 'current' });
|
|
341
|
+
session.setItem('old:auth', JSON.stringify({ mode: 'oidc', accessToken: 'legacy', expiresAt: 0, user: { sub: 'u' } }));
|
|
342
|
+
const auth = createConsoleAuth(options({ legacy: { key: 'old:auth', from: 'session' } }));
|
|
343
|
+
expect(auth.currentSession()?.accessToken).toBe('current');
|
|
344
|
+
expect(JSON.parse(local.getItem(KEYS.session) as string).accessToken).toBe('current');
|
|
345
|
+
});
|
|
346
|
+
});
|
|
347
|
+
|
|
348
|
+
describe('signOut(登出)', () => {
|
|
349
|
+
it('默认吊销 refresh + access,并清本地会话', async () => {
|
|
350
|
+
seedSession();
|
|
351
|
+
const fetchMock = vi.fn(async (_url: string, _init?: RequestInit) => new Response('{}', { status: 200 }));
|
|
352
|
+
vi.stubGlobal('fetch', fetchMock);
|
|
353
|
+
const auth = createConsoleAuth(options());
|
|
354
|
+
|
|
355
|
+
await auth.signOut();
|
|
356
|
+
expect(fetchMock).toHaveBeenCalledTimes(2);
|
|
357
|
+
const urls = fetchMock.mock.calls.map((c) => String(c[0]));
|
|
358
|
+
expect(urls.every((u) => u.endsWith('/revoke'))).toBe(true);
|
|
359
|
+
expect(local.getItem(KEYS.session)).toBeNull();
|
|
360
|
+
});
|
|
361
|
+
|
|
362
|
+
it('revoke:false(401 强制登出)→ 不发请求', async () => {
|
|
363
|
+
seedSession();
|
|
364
|
+
const fetchMock = vi.fn();
|
|
365
|
+
vi.stubGlobal('fetch', fetchMock);
|
|
366
|
+
const auth = createConsoleAuth(options());
|
|
367
|
+
await auth.signOut({ revoke: false });
|
|
368
|
+
expect(fetchMock).not.toHaveBeenCalled();
|
|
369
|
+
expect(local.getItem(KEYS.session)).toBeNull();
|
|
370
|
+
});
|
|
371
|
+
|
|
372
|
+
it('revoke 网络失败不阻塞本地登出', async () => {
|
|
373
|
+
seedSession();
|
|
374
|
+
vi.stubGlobal('fetch', vi.fn(async () => Promise.reject(new Error('down'))));
|
|
375
|
+
const auth = createConsoleAuth(options());
|
|
376
|
+
await expect(auth.signOut()).resolves.toBeUndefined();
|
|
377
|
+
expect(local.getItem(KEYS.session)).toBeNull();
|
|
378
|
+
});
|
|
379
|
+
});
|
|
380
|
+
|
|
381
|
+
describe('ensureFreshSession(主动续期)', () => {
|
|
382
|
+
it('剩余 > 阈值 → 不请求', async () => {
|
|
383
|
+
seedSession({ accessToken: jwt({ sub: 'u1', exp: Math.floor((Date.now() + 3_600_000) / 1000) }) });
|
|
384
|
+
const fetchMock = vi.fn();
|
|
385
|
+
vi.stubGlobal('fetch', fetchMock);
|
|
386
|
+
const auth = createConsoleAuth(options());
|
|
387
|
+
expect(await auth.ensureFreshSession()).not.toBeNull();
|
|
388
|
+
expect(fetchMock).not.toHaveBeenCalled();
|
|
389
|
+
});
|
|
390
|
+
|
|
391
|
+
it('剩余 < 阈值 → 续期', async () => {
|
|
392
|
+
seedSession({ accessToken: jwt({ sub: 'u1', exp: Math.floor((Date.now() + 120_000) / 1000) }) });
|
|
393
|
+
const fetchMock = vi.fn(async () => tokenResponse());
|
|
394
|
+
vi.stubGlobal('fetch', fetchMock);
|
|
395
|
+
const auth = createConsoleAuth(options());
|
|
396
|
+
const next = (await auth.ensureFreshSession()) as ConsoleSession;
|
|
397
|
+
expect(fetchMock).toHaveBeenCalledTimes(1);
|
|
398
|
+
expect(next.refreshToken).toBe('r-2');
|
|
399
|
+
});
|
|
400
|
+
});
|
|
@@ -75,6 +75,25 @@ export function userFromClaims(
|
|
|
75
75
|
};
|
|
76
76
|
}
|
|
77
77
|
|
|
78
|
+
/**
|
|
79
|
+
* 合并 access_token 与 id_token 的声明:**id_token 优先,access_token 补缺**。
|
|
80
|
+
*
|
|
81
|
+
* 为什么需要:登录换票时若只取 id_token,一旦签发方的 id_token 是精简版
|
|
82
|
+
* (只有 sub/name/email,没有 tenant_id / roles),`X-Tenant-ID` 就会丢,
|
|
83
|
+
* 后续请求直接 403——而同样的信息在 access_token 里明明有。
|
|
84
|
+
* 反过来只取 access_token 又会丢掉 id_token 的 nonce、更完整的展示名。
|
|
85
|
+
* 所以按字段合并,而不是二选一。
|
|
86
|
+
*/
|
|
87
|
+
export function mergeTokenClaims(
|
|
88
|
+
accessToken?: string,
|
|
89
|
+
idToken?: string,
|
|
90
|
+
): Record<string, unknown> | null {
|
|
91
|
+
const access = accessToken ? decodeJwtPayload(accessToken) : null;
|
|
92
|
+
const id = idToken ? decodeJwtPayload(idToken) : null;
|
|
93
|
+
if (!access && !id) return null;
|
|
94
|
+
return { ...(access ?? {}), ...(id ?? {}) };
|
|
95
|
+
}
|
|
96
|
+
|
|
78
97
|
/**
|
|
79
98
|
* 过期时刻(epoch ms)。
|
|
80
99
|
*
|
|
@@ -0,0 +1,502 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 控制台认证引擎(唯一实现)。
|
|
3
|
+
*
|
|
4
|
+
* 背景:配置中心与密钥中心原本各写一份 ~450/540 行的 OIDC PKCE 流程,逐段相同。
|
|
5
|
+
* 差异只有一处是**策略**(令牌存 sessionStorage 还是 localStorage),其余差异都是
|
|
6
|
+
* 事故修复,不该做成开关:
|
|
7
|
+
* 1. 5xx / 网络故障 → 会话延长 30s 再试(否则网关抖一下就把人踢下线);
|
|
8
|
+
* 2. 登出时吊销 refresh + access(否则登出后 refresh_token 还能换新票);
|
|
9
|
+
* 3. 兜底有效期 30 分钟(`exp` 与 `expires_in` 都缺时才用);
|
|
10
|
+
* 4. identity 补全过的展示名不被令牌里的 sub 尾段覆盖(否则每 5 分钟顶栏闪一次);
|
|
11
|
+
* 5. 令牌里没有 tenant/app 声明时保留上一轮已知值(否则 X-Tenant-ID 丢 → 403)。
|
|
12
|
+
*
|
|
13
|
+
* 设计约束:
|
|
14
|
+
* - **不改安全姿态**:`storage` 是唯一参数,由各站自己决定;
|
|
15
|
+
* - 纯副作用集中在此(storage / fetch / location),便于用假 window 测试;
|
|
16
|
+
* - 对外 API 与原两站的 `lib/auth.ts` 一一对应,站点侧只做薄绑定。
|
|
17
|
+
*/
|
|
18
|
+
import { decodeJwtPayload } from '../auth/jwt-payload';
|
|
19
|
+
import { generatePKCE } from '../auth/pkce';
|
|
20
|
+
import {
|
|
21
|
+
expiresAtFromToken,
|
|
22
|
+
mergeTokenClaims,
|
|
23
|
+
pickClaimString,
|
|
24
|
+
sessionExpiryAt,
|
|
25
|
+
userFromClaims,
|
|
26
|
+
type ConsoleSessionUser,
|
|
27
|
+
} from './claims';
|
|
28
|
+
|
|
29
|
+
export interface ConsoleSession {
|
|
30
|
+
mode: 'mock' | 'oidc';
|
|
31
|
+
accessToken: string;
|
|
32
|
+
refreshToken?: string;
|
|
33
|
+
idToken?: string;
|
|
34
|
+
/** epoch ms;0 = 不过期(mock) */
|
|
35
|
+
expiresAt: number;
|
|
36
|
+
user: ConsoleSessionUser;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export interface ConsoleAuthOptions {
|
|
40
|
+
authMode: 'mock' | 'oidc';
|
|
41
|
+
/** **唯一策略参数**:令牌放 localStorage(跨标签页/刷新保持)还是 sessionStorage(关标签页失效)。 */
|
|
42
|
+
storage: 'local' | 'session';
|
|
43
|
+
keys: {
|
|
44
|
+
/** 会话落盘 key */
|
|
45
|
+
session: string;
|
|
46
|
+
/** PKCE 上下文 key(state/nonce/verifier) */
|
|
47
|
+
pkce: string;
|
|
48
|
+
/** mock 模式下点过「退出」的标记 key */
|
|
49
|
+
mockSignedOut: string;
|
|
50
|
+
};
|
|
51
|
+
oidc: {
|
|
52
|
+
authorizeUrl: string;
|
|
53
|
+
tokenUrl: string;
|
|
54
|
+
clientId: string;
|
|
55
|
+
scope: string;
|
|
56
|
+
redirectUri: string;
|
|
57
|
+
};
|
|
58
|
+
/** 演示会话工厂(`authMode === 'mock'` 时使用) */
|
|
59
|
+
mockSession: () => ConsoleSession;
|
|
60
|
+
/** 旧会话迁移:仅当新 key 为空时,把旧 storage 里的值搬过来(只做一次)。 */
|
|
61
|
+
legacy?: { key: string; from: 'local' | 'session' };
|
|
62
|
+
/** `exp` 与 `expires_in` 都缺时的兜底有效期,默认 30 分钟。 */
|
|
63
|
+
expiryFallbackMs?: number;
|
|
64
|
+
/** 瞬时故障(5xx / 网络)时把会话延长多久,默认 30s。 */
|
|
65
|
+
transientGraceMs?: number;
|
|
66
|
+
/** 登出时是否调服务端 revoke,默认 true。 */
|
|
67
|
+
revokeOnSignOut?: boolean;
|
|
68
|
+
/** 跳转实现(默认 `window.location.assign`),测试可注入。 */
|
|
69
|
+
assign?: (url: string) => void;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export interface ConsoleAuth {
|
|
73
|
+
sessionKey: string;
|
|
74
|
+
mockSession: () => ConsoleSession;
|
|
75
|
+
currentSession: () => ConsoleSession | null;
|
|
76
|
+
restoreSession: () => Promise<ConsoleSession | null>;
|
|
77
|
+
startLogin: () => Promise<ConsoleSession | null>;
|
|
78
|
+
completeLogin: (search?: string) => Promise<ConsoleSession>;
|
|
79
|
+
refreshSession: (stored?: ConsoleSession | null) => Promise<ConsoleSession | null>;
|
|
80
|
+
/** 剩余有效期 < 阈值时主动续期(App 定时器 / 页面重新可见时调用)。 */
|
|
81
|
+
ensureFreshSession: (thresholdMs?: number) => Promise<ConsoleSession | null>;
|
|
82
|
+
signOut: (options?: { revoke?: boolean }) => Promise<void>;
|
|
83
|
+
renewAfterUnauthorized: () => Promise<ConsoleSession | null>;
|
|
84
|
+
patchUser: (patch: Partial<ConsoleSessionUser>) => ConsoleSession | null;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** 提前 60s 视为过期,避免请求途中失效。 */
|
|
88
|
+
const EXPIRY_SKEW_MS = 60_000;
|
|
89
|
+
|
|
90
|
+
type PkceState = {
|
|
91
|
+
verifier: string;
|
|
92
|
+
state: string;
|
|
93
|
+
nonce: string;
|
|
94
|
+
redirectUri: string;
|
|
95
|
+
at: number;
|
|
96
|
+
};
|
|
97
|
+
|
|
98
|
+
type TokenResponse = {
|
|
99
|
+
access_token?: string;
|
|
100
|
+
refresh_token?: string;
|
|
101
|
+
id_token?: string;
|
|
102
|
+
expires_in?: number;
|
|
103
|
+
token_type?: string;
|
|
104
|
+
scope?: string;
|
|
105
|
+
error?: string;
|
|
106
|
+
error_description?: string;
|
|
107
|
+
};
|
|
108
|
+
|
|
109
|
+
/** 令牌端点错误:区分「瞬时(网络/5xx)」与「确定失败(4xx invalid_grant 等)」。 */
|
|
110
|
+
class TokenError extends Error {
|
|
111
|
+
constructor(
|
|
112
|
+
message: string,
|
|
113
|
+
readonly transient: boolean,
|
|
114
|
+
) {
|
|
115
|
+
super(message);
|
|
116
|
+
this.name = 'TokenError';
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
function safeStorage(kind: 'local' | 'session'): Storage | null {
|
|
121
|
+
try {
|
|
122
|
+
const win = (globalThis as unknown as { window?: Window & typeof globalThis }).window;
|
|
123
|
+
return (win?.[kind === 'local' ? 'localStorage' : 'sessionStorage'] ?? null) as Storage | null;
|
|
124
|
+
} catch {
|
|
125
|
+
// 隐私模式/被禁用:降级为「无存储」,绝不抛到 UI
|
|
126
|
+
return null;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
export function createConsoleAuth(options: ConsoleAuthOptions): ConsoleAuth {
|
|
131
|
+
const {
|
|
132
|
+
authMode,
|
|
133
|
+
storage: storageKind,
|
|
134
|
+
keys,
|
|
135
|
+
oidc,
|
|
136
|
+
mockSession,
|
|
137
|
+
legacy,
|
|
138
|
+
expiryFallbackMs = 30 * 60_000,
|
|
139
|
+
transientGraceMs = 30_000,
|
|
140
|
+
revokeOnSignOut = true,
|
|
141
|
+
assign = (url: string) => window.location.assign(url),
|
|
142
|
+
} = options;
|
|
143
|
+
|
|
144
|
+
const store = () => safeStorage(storageKind);
|
|
145
|
+
|
|
146
|
+
function read(key: string): string | null {
|
|
147
|
+
try {
|
|
148
|
+
return store()?.getItem(key) ?? null;
|
|
149
|
+
} catch {
|
|
150
|
+
return null;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
function write(key: string, value: string): void {
|
|
155
|
+
try {
|
|
156
|
+
store()?.setItem(key, value);
|
|
157
|
+
} catch {
|
|
158
|
+
/* 忽略:无存储时退化为「每次刷新都要重新登录」 */
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
function remove(key: string): void {
|
|
163
|
+
try {
|
|
164
|
+
store()?.removeItem(key);
|
|
165
|
+
} catch {
|
|
166
|
+
/* 忽略 */
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** 旧 key 迁移(只做一次,避免升级后强制重登)。 */
|
|
171
|
+
function migrateLegacy(): void {
|
|
172
|
+
if (!legacy) return;
|
|
173
|
+
try {
|
|
174
|
+
const current = store();
|
|
175
|
+
if (!current || current.getItem(keys.session)) return;
|
|
176
|
+
const old = safeStorage(legacy.from);
|
|
177
|
+
const value = old?.getItem(legacy.key);
|
|
178
|
+
if (!value) return;
|
|
179
|
+
current.setItem(keys.session, value);
|
|
180
|
+
old?.removeItem(legacy.key);
|
|
181
|
+
} catch {
|
|
182
|
+
/* 忽略 */
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
function saveSession(session: ConsoleSession): void {
|
|
187
|
+
write(keys.session, JSON.stringify(session));
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
function clearSession(): void {
|
|
191
|
+
remove(keys.session);
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
function readStored(): ConsoleSession | null {
|
|
195
|
+
const raw = read(keys.session);
|
|
196
|
+
if (!raw) return null;
|
|
197
|
+
try {
|
|
198
|
+
const parsed = JSON.parse(raw) as ConsoleSession;
|
|
199
|
+
return parsed?.accessToken !== undefined ? parsed : null;
|
|
200
|
+
} catch {
|
|
201
|
+
clearSession();
|
|
202
|
+
return null;
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
function isFresh(session: ConsoleSession): boolean {
|
|
207
|
+
const expiry = sessionExpiryAt(session.accessToken, session.expiresAt);
|
|
208
|
+
return expiry === 0 || Date.now() <= expiry - EXPIRY_SKEW_MS;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
function readPkce(): PkceState | null {
|
|
212
|
+
const raw = read(keys.pkce);
|
|
213
|
+
if (!raw) return null;
|
|
214
|
+
try {
|
|
215
|
+
const parsed = JSON.parse(raw) as PkceState;
|
|
216
|
+
return parsed?.verifier && parsed?.state ? parsed : null;
|
|
217
|
+
} catch {
|
|
218
|
+
return null;
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
async function postToken(body: URLSearchParams): Promise<TokenResponse> {
|
|
223
|
+
let res: Response;
|
|
224
|
+
try {
|
|
225
|
+
res = await fetch(oidc.tokenUrl, {
|
|
226
|
+
method: 'POST',
|
|
227
|
+
headers: { 'Content-Type': 'application/x-www-form-urlencoded', Accept: 'application/json' },
|
|
228
|
+
body: body.toString(),
|
|
229
|
+
});
|
|
230
|
+
} catch (cause) {
|
|
231
|
+
throw new TokenError(`无法连接令牌端点(${oidc.tokenUrl}):${(cause as Error).message}`, true);
|
|
232
|
+
}
|
|
233
|
+
const data = (await res.json().catch(() => null)) as TokenResponse | null;
|
|
234
|
+
if (!res.ok || !data?.access_token) {
|
|
235
|
+
const reason = data?.error_description || data?.error || `HTTP ${res.status}`;
|
|
236
|
+
// 5xx / 0 = 瞬时;4xx(invalid_grant 等)= 确定失败
|
|
237
|
+
throw new TokenError(`换取令牌失败:${reason}`, res.status >= 500 || res.status === 0);
|
|
238
|
+
}
|
|
239
|
+
return data;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
function toSession(
|
|
243
|
+
data: TokenResponse,
|
|
244
|
+
base?: ConsoleSession | null,
|
|
245
|
+
): ConsoleSession {
|
|
246
|
+
const claims = mergeTokenClaims(data.access_token, data.id_token);
|
|
247
|
+
const session: ConsoleSession = {
|
|
248
|
+
mode: 'oidc',
|
|
249
|
+
accessToken: data.access_token as string,
|
|
250
|
+
refreshToken: data.refresh_token ?? base?.refreshToken,
|
|
251
|
+
idToken: data.id_token ?? base?.idToken,
|
|
252
|
+
expiresAt: expiresAtFromToken(data.access_token as string, data.expires_in, expiryFallbackMs),
|
|
253
|
+
user: userFromClaims(claims, base?.user?.name || '已登录用户'),
|
|
254
|
+
};
|
|
255
|
+
if (base) {
|
|
256
|
+
// identity 补全过的展示名(如 platform_admin)不要被令牌里的 sub 尾段覆盖,
|
|
257
|
+
// 否则每 5 分钟续期一次,顶栏就闪回「…XXXXXX」并重复查一次资料。
|
|
258
|
+
if (session.user.name.startsWith('…') && base.user?.name && !base.user.name.startsWith('…')) {
|
|
259
|
+
session.user = { ...session.user, name: base.user.name, email: session.user.email || base.user.email };
|
|
260
|
+
}
|
|
261
|
+
// 令牌内没有租户/应用声明时,保留上一轮已知值,避免 X-Tenant-ID 丢失。
|
|
262
|
+
if (!session.user.tenantId) session.user.tenantId = base.user?.tenantId ?? '';
|
|
263
|
+
if (!session.user.appId) session.user.appId = base.user?.appId ?? '';
|
|
264
|
+
}
|
|
265
|
+
return session;
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
// ── 对外 API ────────────────────────────────────────────────────────────
|
|
269
|
+
|
|
270
|
+
function currentSession(): ConsoleSession | null {
|
|
271
|
+
if (authMode === 'mock') {
|
|
272
|
+
migrateLegacy();
|
|
273
|
+
return read(keys.mockSignedOut) === '1' ? null : mockSession();
|
|
274
|
+
}
|
|
275
|
+
migrateLegacy();
|
|
276
|
+
const session = readStored();
|
|
277
|
+
if (!session?.accessToken) return null;
|
|
278
|
+
return isFresh(session) ? session : null;
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
async function restoreSession(): Promise<ConsoleSession | null> {
|
|
282
|
+
if (authMode === 'mock') return currentSession();
|
|
283
|
+
migrateLegacy();
|
|
284
|
+
const stored = readStored();
|
|
285
|
+
if (!stored) return null;
|
|
286
|
+
if (stored.accessToken && isFresh(stored)) return stored;
|
|
287
|
+
return refreshSession(stored);
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
async function startLogin(): Promise<ConsoleSession | null> {
|
|
291
|
+
if (authMode === 'mock') {
|
|
292
|
+
remove(keys.mockSignedOut);
|
|
293
|
+
const session = mockSession();
|
|
294
|
+
saveSession(session);
|
|
295
|
+
return session;
|
|
296
|
+
}
|
|
297
|
+
if (!oidc.clientId) {
|
|
298
|
+
throw new Error('缺少 VITE_OIDC_CLIENT_ID:请先在 OAuth 客户端登记回调地址并配置客户端 ID');
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
// PKCE(RFC 7636):verifier 43–128 字符,challenge = base64url(sha256(verifier))
|
|
302
|
+
const { verifier, challenge } = await generatePKCE();
|
|
303
|
+
const state = randomToken(16);
|
|
304
|
+
const nonce = randomToken(16);
|
|
305
|
+
|
|
306
|
+
write(
|
|
307
|
+
keys.pkce,
|
|
308
|
+
JSON.stringify({ verifier, state, nonce, redirectUri: oidc.redirectUri, at: Date.now() } satisfies PkceState),
|
|
309
|
+
);
|
|
310
|
+
|
|
311
|
+
const url = new URL(oidc.authorizeUrl);
|
|
312
|
+
url.searchParams.set('response_type', 'code');
|
|
313
|
+
url.searchParams.set('client_id', oidc.clientId);
|
|
314
|
+
url.searchParams.set('redirect_uri', oidc.redirectUri);
|
|
315
|
+
url.searchParams.set('scope', oidc.scope);
|
|
316
|
+
url.searchParams.set('state', state);
|
|
317
|
+
url.searchParams.set('nonce', nonce);
|
|
318
|
+
url.searchParams.set('code_challenge', challenge);
|
|
319
|
+
url.searchParams.set('code_challenge_method', 'S256');
|
|
320
|
+
|
|
321
|
+
assign(url.toString());
|
|
322
|
+
return null;
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
async function completeLogin(search: string = window.location.search): Promise<ConsoleSession> {
|
|
326
|
+
const query = new URLSearchParams(search);
|
|
327
|
+
const error = query.get('error');
|
|
328
|
+
if (error) {
|
|
329
|
+
const desc = query.get('error_description');
|
|
330
|
+
throw new Error(`授权被拒绝:${error}${desc ? ` · ${desc}` : ''}`);
|
|
331
|
+
}
|
|
332
|
+
const code = query.get('code');
|
|
333
|
+
const state = query.get('state');
|
|
334
|
+
if (!code) throw new Error('回调缺少 code 参数');
|
|
335
|
+
|
|
336
|
+
const pkce = readPkce();
|
|
337
|
+
if (!pkce) throw new Error('登录会话已失效(缺少 PKCE 上下文),请重新登录');
|
|
338
|
+
if (!state || state !== pkce.state) throw new Error('state 校验失败(可能的 CSRF),请重新登录');
|
|
339
|
+
if (Date.now() - pkce.at > 10 * 60_000) {
|
|
340
|
+
remove(keys.pkce);
|
|
341
|
+
throw new Error('登录超时,请重新登录');
|
|
342
|
+
}
|
|
343
|
+
if (!oidc.clientId) throw new Error('缺少 VITE_OIDC_CLIENT_ID');
|
|
344
|
+
|
|
345
|
+
const data = await postToken(
|
|
346
|
+
new URLSearchParams({
|
|
347
|
+
grant_type: 'authorization_code',
|
|
348
|
+
code,
|
|
349
|
+
redirect_uri: pkce.redirectUri,
|
|
350
|
+
client_id: oidc.clientId,
|
|
351
|
+
code_verifier: pkce.verifier,
|
|
352
|
+
}),
|
|
353
|
+
);
|
|
354
|
+
|
|
355
|
+
const nonceClaim = pickClaimString(mergeTokenClaims(data.access_token, data.id_token), 'nonce');
|
|
356
|
+
if (nonceClaim && nonceClaim !== pkce.nonce) {
|
|
357
|
+
remove(keys.pkce);
|
|
358
|
+
throw new Error('nonce 校验失败(令牌可能被重放),请重新登录');
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
remove(keys.pkce);
|
|
362
|
+
|
|
363
|
+
const session = toSession(data);
|
|
364
|
+
saveSession(session);
|
|
365
|
+
return session;
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
let refreshInFlight: Promise<ConsoleSession | null> | null = null;
|
|
369
|
+
|
|
370
|
+
function refreshSession(stored?: ConsoleSession | null): Promise<ConsoleSession | null> {
|
|
371
|
+
if (authMode === 'mock') return Promise.resolve(currentSession());
|
|
372
|
+
if (refreshInFlight) return refreshInFlight;
|
|
373
|
+
refreshInFlight = doRefresh(stored).finally(() => {
|
|
374
|
+
refreshInFlight = null;
|
|
375
|
+
});
|
|
376
|
+
return refreshInFlight;
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
async function doRefresh(stored?: ConsoleSession | null): Promise<ConsoleSession | null> {
|
|
380
|
+
const base = stored ?? readStored();
|
|
381
|
+
if (!base) return null;
|
|
382
|
+
if (!base.refreshToken || !oidc.clientId) {
|
|
383
|
+
clearSession();
|
|
384
|
+
return null;
|
|
385
|
+
}
|
|
386
|
+
try {
|
|
387
|
+
const data = await postToken(
|
|
388
|
+
new URLSearchParams({
|
|
389
|
+
grant_type: 'refresh_token',
|
|
390
|
+
refresh_token: base.refreshToken,
|
|
391
|
+
client_id: oidc.clientId,
|
|
392
|
+
}),
|
|
393
|
+
);
|
|
394
|
+
const session = toSession(data, base);
|
|
395
|
+
saveSession(session);
|
|
396
|
+
return session;
|
|
397
|
+
} catch (err) {
|
|
398
|
+
if (err instanceof TokenError && err.transient) {
|
|
399
|
+
// 网络/网关瞬时故障:不清会话,延长一小段让 UI 不立刻掉登录,下次再续。
|
|
400
|
+
if (transientGraceMs > 0) {
|
|
401
|
+
const keep: ConsoleSession = {
|
|
402
|
+
...base,
|
|
403
|
+
expiresAt: Math.max(base.expiresAt, Date.now() + transientGraceMs),
|
|
404
|
+
};
|
|
405
|
+
saveSession(keep);
|
|
406
|
+
return keep;
|
|
407
|
+
}
|
|
408
|
+
return currentSession();
|
|
409
|
+
}
|
|
410
|
+
clearSession();
|
|
411
|
+
return null;
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
async function ensureFreshSession(thresholdMs: number = 5 * 60_000): Promise<ConsoleSession | null> {
|
|
416
|
+
if (authMode === 'mock') return currentSession();
|
|
417
|
+
migrateLegacy();
|
|
418
|
+
const stored = readStored();
|
|
419
|
+
if (!stored?.accessToken) return null;
|
|
420
|
+
const expiry = sessionExpiryAt(stored.accessToken, stored.expiresAt);
|
|
421
|
+
if (expiry === 0 || expiry - Date.now() > thresholdMs) return stored;
|
|
422
|
+
return refreshSession(stored);
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
function revokeUrl(): string {
|
|
426
|
+
// 与 token 同源:把 `/token` 换成 `/revoke`
|
|
427
|
+
return oidc.tokenUrl.replace(/\/token(\?.*)?$/, '/revoke');
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
async function revokeToken(token: string, hint: 'access_token' | 'refresh_token'): Promise<void> {
|
|
431
|
+
if (!oidc.clientId) return;
|
|
432
|
+
const controller = new AbortController();
|
|
433
|
+
const timer = setTimeout(() => controller.abort(), 3000);
|
|
434
|
+
try {
|
|
435
|
+
await fetch(revokeUrl(), {
|
|
436
|
+
method: 'POST',
|
|
437
|
+
headers: { 'Content-Type': 'application/x-www-form-urlencoded', Accept: 'application/json' },
|
|
438
|
+
body: new URLSearchParams({ token, token_type_hint: hint, client_id: oidc.clientId }).toString(),
|
|
439
|
+
signal: controller.signal,
|
|
440
|
+
credentials: 'omit',
|
|
441
|
+
keepalive: true,
|
|
442
|
+
});
|
|
443
|
+
} catch {
|
|
444
|
+
/* 网络/超时忽略:本地会话仍会清除 */
|
|
445
|
+
} finally {
|
|
446
|
+
clearTimeout(timer);
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
async function signOut(signOutOptions: { revoke?: boolean } = {}): Promise<void> {
|
|
451
|
+
const shouldRevoke = revokeOnSignOut && authMode === 'oidc' && signOutOptions.revoke !== false;
|
|
452
|
+
if (shouldRevoke) {
|
|
453
|
+
const stored = readStored();
|
|
454
|
+
if (stored) {
|
|
455
|
+
const tasks: Promise<void>[] = [];
|
|
456
|
+
if (stored.refreshToken) tasks.push(revokeToken(stored.refreshToken, 'refresh_token'));
|
|
457
|
+
if (stored.accessToken) tasks.push(revokeToken(stored.accessToken, 'access_token'));
|
|
458
|
+
if (tasks.length) await Promise.allSettled(tasks);
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
clearSession();
|
|
462
|
+
remove(keys.pkce);
|
|
463
|
+
if (authMode === 'mock') write(keys.mockSignedOut, '1');
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
function patchUser(patch: Partial<ConsoleSessionUser>): ConsoleSession | null {
|
|
467
|
+
const current = currentSession();
|
|
468
|
+
if (!current) return null;
|
|
469
|
+
const next: ConsoleSession = { ...current, user: { ...current.user, ...patch } };
|
|
470
|
+
saveSession(next);
|
|
471
|
+
return next;
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
return {
|
|
475
|
+
sessionKey: keys.session,
|
|
476
|
+
mockSession,
|
|
477
|
+
currentSession,
|
|
478
|
+
restoreSession,
|
|
479
|
+
startLogin,
|
|
480
|
+
completeLogin,
|
|
481
|
+
refreshSession,
|
|
482
|
+
ensureFreshSession,
|
|
483
|
+
signOut,
|
|
484
|
+
renewAfterUnauthorized: () => refreshSession(),
|
|
485
|
+
patchUser,
|
|
486
|
+
};
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
function b64url(bytes: Uint8Array): string {
|
|
490
|
+
let binary = '';
|
|
491
|
+
for (const b of bytes) binary += String.fromCharCode(b);
|
|
492
|
+
return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
function randomToken(byteLength = 32): string {
|
|
496
|
+
const buf = new Uint8Array(byteLength);
|
|
497
|
+
crypto.getRandomValues(buf);
|
|
498
|
+
return b64url(buf);
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
/** 供站点复用的 JWT 解码(不验签:签名在后端,前端只取展示用声明)。 */
|
|
502
|
+
export { decodeJwtPayload };
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 控制台认证公共层(配置中心 / 密钥中心共用)。
|
|
3
|
+
*
|
|
4
|
+
* - `claims`:JWT 声明 → 会话用户 / 过期时刻的纯映射;
|
|
5
|
+
* - `createConsoleAuth`:完整 OIDC PKCE 流程(登录 / 换票 / 续期 / 登出),
|
|
6
|
+
* 「令牌存哪」是唯一策略参数,其余行为统一。
|
|
7
|
+
*/
|
|
8
|
+
export {
|
|
9
|
+
expiresAtFromToken,
|
|
10
|
+
mergeTokenClaims,
|
|
11
|
+
pickClaimRoles,
|
|
12
|
+
pickClaimString,
|
|
13
|
+
sessionExpiryAt,
|
|
14
|
+
userFromClaims,
|
|
15
|
+
type ConsoleSessionUser,
|
|
16
|
+
} from './claims';
|
|
17
|
+
export {
|
|
18
|
+
createConsoleAuth,
|
|
19
|
+
decodeJwtPayload,
|
|
20
|
+
type ConsoleAuth,
|
|
21
|
+
type ConsoleAuthOptions,
|
|
22
|
+
type ConsoleSession,
|
|
23
|
+
} from './create-console-auth';
|