Skip to content
Toggle navigation
Projects
Groups
Snippets
Help
ujia
/
uj-admin
This project
Loading...
Sign in
Toggle navigation
Go to a project
Project
Repository
Issues
0
Merge Requests
0
Pipelines
Wiki
Settings
Activity
Graph
Charts
Create a new issue
Jobs
Commits
Issue Boards
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Charts
Commit de1b0036
authored
Nov 20, 2026
by
liimin
Browse Files
Options
Browse Files
Tag
Download
Email Patches
Plain Diff
session 失效退出到登录页
1 parent
4454cb72
Pipeline
#570
for
de1b0036
failed
in 0 seconds
Changes
7
Pipelines
1
Hide whitespace changes
Inline
Side-by-side
Showing
7 changed files
with
183 additions
and
30 deletions
apps/web/shell/src/MicroApp.tsx
apps/web/shell/src/main.tsx
apps/web/shell/src/subapp-lifecycle.ts
apps/web/subapps/usedcar/src/api/core/client.ts
packages/api-core/src/core/facade.ts
packages/api-core/test/facade.test.mjs
packages/api-core/test/strategy.test.mjs
apps/web/shell/src/MicroApp.tsx
View file @
de1b003
...
@@ -7,7 +7,7 @@ import { busEvents } from '@uj/contracts';
...
@@ -7,7 +7,7 @@ import { busEvents } from '@uj/contracts';
import { entryOf } from './subapps';
import { entryOf } from './subapps';
import { forgetReady, isReady, markReady } from './subapp-handshake';
import { forgetReady, isReady, markReady } from './subapp-handshake';
import { createSubAppProps } from './subapp-props';
import { createSubAppProps } from './subapp-props';
import { logoutEverything } from './subapp-lifecycle';
import { logoutEverything
, reportSessionExpired
} from './subapp-lifecycle';
import { destroyAppLocked, restartAppLocked, startAppLocked } from './wujie-lifecycle';
import { destroyAppLocked, restartAppLocked, startAppLocked } from './wujie-lifecycle';
/**
/**
...
@@ -183,7 +183,7 @@ export function MicroApp({ shortName, route }: { shortName: string; route: strin
...
@@ -183,7 +183,7 @@ export function MicroApp({ shortName, route }: { shortName: string; route: strin
bus.$emit(events.navigate, subPath);
bus.$emit(events.navigate, subPath);
};
};
const onNavigateHost = (...args: unknown[]) => navigate(String(args[0] ?? '/'));
const onNavigateHost = (...args: unknown[]) => navigate(String(args[0] ?? '/'));
const onLogoutHost = () => void
logoutEverything(navigate
);
const onLogoutHost = () => void
reportSessionExpired().then(() => logoutEverything(navigate)
);
bus.$on(events.ready, onReady);
bus.$on(events.ready, onReady);
bus.$on(events.navigateHost, onNavigateHost);
bus.$on(events.navigateHost, onNavigateHost);
...
...
apps/web/shell/src/main.tsx
View file @
de1b003
...
@@ -14,14 +14,18 @@ import { DownloadCenterProvider } from '@uj/download-center';
...
@@ -14,14 +14,18 @@ import { DownloadCenterProvider } from '@uj/download-center';
import { installGlobalUnhandledRejectionHandler } from '@uj/ui';
import { installGlobalUnhandledRejectionHandler } from '@uj/ui';
import type { RemoteRequestFn } from '@uj/contracts';
import type { RemoteRequestFn } from '@uj/contracts';
import { loadRuntimeManifest } from './runtime-manifest';
import { loadRuntimeManifest } from './runtime-manifest';
import { reportSessionExpired } from './subapp-lifecycle';
import '@uj/design-tokens/tokens.css';
import '@uj/design-tokens/tokens.css';
import './index.css';
import './index.css';
import './theme/design.css';
import './theme/design.css';
import './theme/mfe.css';
import './theme/mfe.css';
// 401 / 10002 的统一处理出口。必须在任何请求发出(含下面的 initSign)之前注册:
// 401 / 10002 的统一处理出口。必须在任何请求发出(含下面的 initSign)之前注册:
// logout 会双清 uj_token 与 session 并把 loggedIn 置 false,RequireAuth 随即重定向。
// 先弹「登录已失效」提示并短暂延时,再 logout 双清 uj_token 与 session,
setUnauthorizedHandler(() => useAppStore.getState().logout());
// RequireAuth 随即重定向;不提示直接跳会让用户莫名其妙。
setUnauthorizedHandler(() => {
void reportSessionExpired().then(() => useAppStore.getState().logout());
});
// 全应用未处理 promise rejection 兜底:async 调用漏 catch 时弹红色错误 toast。
// 全应用未处理 promise rejection 兜底:async 调用漏 catch 时弹红色错误 toast。
installGlobalUnhandledRejectionHandler();
installGlobalUnhandledRejectionHandler();
...
...
apps/web/shell/src/subapp-lifecycle.ts
View file @
de1b003
import
{
bus
}
from
'wujie'
;
import
{
bus
}
from
'wujie'
;
import
{
message
}
from
'antd'
;
import
{
busEvents
}
from
'@uj/contracts'
;
import
{
busEvents
}
from
'@uj/contracts'
;
import
{
collectRouteDefs
}
from
'./dynamic-subapps'
;
import
{
collectRouteDefs
}
from
'./dynamic-subapps'
;
import
{
forgetReady
,
isReady
}
from
'./subapp-handshake'
;
import
{
forgetReady
,
isReady
}
from
'./subapp-handshake'
;
...
@@ -7,6 +8,31 @@ import { stopDownloadCenter } from '@uj/download-center';
...
@@ -7,6 +8,31 @@ import { stopDownloadCenter } from '@uj/download-center';
import
{
useAppStore
}
from
'@/store/useAppStore'
;
import
{
useAppStore
}
from
'@/store/useAppStore'
;
import
{
auth
,
menu
as
menuApi
}
from
'@/api'
;
import
{
auth
,
menu
as
menuApi
}
from
'@/api'
;
const
SESSION_NOTICE
=
'登录状态已失效,即将返回登录页,请重新登录'
;
let
lastNoticeAt
=
0
;
let
noticeWait
:
Promise
<
void
>
|
null
=
null
;
/**
* 会话失效的统一提示。
*
* 静默登出会让用户莫名其妙地回到登录页,所以先弹提示并把登出延后 1.5s。
* 同一时刻常有多条请求一起命中登出码,3s 窗口内只提示一次、共用同一个等待 Promise;
* 静态 antd message 不依赖 AntApp 上下文——setUnauthorizedHandler 在 React 挂载前就注册了。
*/
export
function
reportSessionExpired
():
Promise
<
void
>
{
const
now
=
Date
.
now
();
if
(
noticeWait
&&
now
-
lastNoticeAt
<
3000
)
return
noticeWait
;
lastNoticeAt
=
now
;
message
.
warning
(
SESSION_NOTICE
,
3
);
noticeWait
=
new
Promise
<
void
>
((
resolve
)
=>
{
window
.
setTimeout
(
resolve
,
1500
);
});
return
noticeWait
;
}
/** 并发会话失效 / 用户连点退出只做一次完整收尾。 */
let
loggingOut
=
false
;
/**
/**
* 统一登出:主壳与所有 wujie 子应用必须一起收尾。
* 统一登出:主壳与所有 wujie 子应用必须一起收尾。
*
*
...
@@ -20,30 +46,37 @@ import { auth, menu as menuApi } from '@/api';
...
@@ -20,30 +46,37 @@ import { auth, menu as menuApi } from '@/api';
* 子应用绝不自己 clearToken():令牌与会话的真源在主壳,两边各自清会留下半吊子状态。
* 子应用绝不自己 clearToken():令牌与会话的真源在主壳,两边各自清会留下半吊子状态。
*/
*/
export
async
function
logoutEverything
(
navigate
:
(
path
:
string
)
=>
void
):
Promise
<
void
>
{
export
async
function
logoutEverything
(
navigate
:
(
path
:
string
)
=>
void
):
Promise
<
void
>
{
// 必须在销毁子应用之前中止在途下载:ROP 通道的 postRop 闭包在子应用 iframe 里,
// 并发会话失效 / 用户连点退出只做一次完整收尾,避免重复 auth.logout 与重复导航。
// 销毁后失效,正在轮询的任务会失败并被误报「导出失败」。先落 canceled 再销毁。
if
(
loggingOut
)
return
;
stopDownloadCenter
({
markCanceled
:
true
});
loggingOut
=
true
;
try
{
try
{
await
auth
.
logout
();
// 必须在销毁子应用之前中止在途下载:ROP 通道的 postRop 闭包在子应用 iframe 里,
}
catch
{
// 销毁后失效,正在轮询的任务会失败并被误报「导出失败」。先落 canceled 再销毁。
/* 忽略:本地令牌清除即可 */
stopDownloadCenter
({
markCanceled
:
true
});
}
useAppStore
.
getState
().
logout
();
try
{
menuApi
.
clearCache
();
await
auth
.
logout
();
auth
.
clearCache
();
}
catch
{
/* 忽略:本地令牌清除即可 */
// 用「构建期 ∪ 运行时清单」的完整集合:只遍历 SUBAPPS 会漏掉 manifest
}
// 动态注册的子应用,它们收不到 logout 且沙箱不被销毁,重新登录时会复用
// 带着上一个账号数据的 alive iframe(串号)。
// warn:false 避免登出时重复打印清单冲突告警(建路由时已打过)。
for
(
const
s
of
collectRouteDefs
({
warn
:
false
}))
{
if
(
isReady
(
s
.
shortName
))
bus
.
$emit
(
busEvents
(
s
.
shortName
).
logout
);
forgetReady
(
s
.
shortName
);
// 不阻塞登出导航:销毁是异步的,子应用尚未启动时失败可忽略。
void
destroyAppLocked
(
s
.
shortName
).
catch
(()
=>
{});
}
navigate
(
'/login'
);
useAppStore
.
getState
().
logout
();
menuApi
.
clearCache
();
auth
.
clearCache
();
// 用「构建期 ∪ 运行时清单」的完整集合:只遍历 SUBAPPS 会漏掉 manifest
// 动态注册的子应用,它们收不到 logout 且沙箱不被销毁,重新登录时会复用
// 带着上一个账号数据的 alive iframe(串号)。
// warn:false 避免登出时重复打印清单冲突告警(建路由时已打过)。
for
(
const
s
of
collectRouteDefs
({
warn
:
false
}))
{
if
(
isReady
(
s
.
shortName
))
bus
.
$emit
(
busEvents
(
s
.
shortName
).
logout
);
forgetReady
(
s
.
shortName
);
// 不阻塞登出导航:销毁是异步的,子应用尚未启动时失败可忽略。
void
destroyAppLocked
(
s
.
shortName
).
catch
(()
=>
{});
}
navigate
(
'/login'
);
}
finally
{
loggingOut
=
false
;
}
}
}
apps/web/subapps/usedcar/src/api/core/client.ts
View file @
de1b003
...
@@ -209,7 +209,7 @@ function hostOptions(): Pick<
...
@@ -209,7 +209,7 @@ function hostOptions(): Pick<
},
},
errorHandler: (error) => { throw error.cause ?? error; },
errorHandler: (error) => { throw error.cause ?? error; },
/**
/**
* 登录态失效统一出口(GSC / ROP 信封的登出码:20 缺会话、21 登录过期)。
* 登录态失效统一出口(GSC / ROP 信封的登出码:20 缺会话、21 登录过期
、22 sessionId不存在
)。
*
*
* 门面在命中 logoutCodes 时先回调这里,再按 throwOnError 抛错。原先本域没有装配该回调,
* 门面在命中 logoutCodes 时先回调这里,再按 throwOnError 抛错。原先本域没有装配该回调,
* 于是 code=21 只被抛成一个普通 RequestError,React Query 落到 isError 分支,
* 于是 code=21 只被抛成一个普通 RequestError,React Query 落到 isError 分支,
...
@@ -236,7 +236,15 @@ function callConfig(options: UsedcarCallOptions, rop: boolean, defaultTimeout: n
...
@@ -236,7 +236,15 @@ function callConfig(options: UsedcarCallOptions, rop: boolean, defaultTimeout: n
return {
return {
timeout: typeof options.timeout === 'number' ? options.timeout : defaultTimeout,
timeout: typeof options.timeout === 'number' ? options.timeout : defaultTimeout,
...(rop ? {} : { returnAll: options.returnAll }),
...(rop ? {} : { returnAll: options.returnAll }),
...(options.response ? { response: options.response } : {}),
// GSC / ROP 信封的会话失效码:20 缺会话、21 登录过期、22 sessionId不存在。
// 不声明时 api-core 门面走兜底 [20,21],网关实测的 22 只会 toast + throw,
// 页面 React Query 落到 isError,表现为「线索列表加载失败」而停在原页。
// 声明后与 hostOptions().onLoginRequired 闭环:compat store 广播 logout-host →
// 主壳 logoutEverything 双清并 navigate('/login')。消费方显式传 logoutCodes 时优先。
response: {
logoutCodes: [20, 21, 22],
...(options.response ?? {}),
},
...(Object.keys(headers).length ? { headers } : {}),
...(Object.keys(headers).length ? { headers } : {}),
};
};
}
}
...
...
packages/api-core/src/core/facade.ts
View file @
de1b003
...
@@ -448,6 +448,15 @@ function buildError(message: string, init: Partial<RequestError> = {}): RequestE
...
@@ -448,6 +448,15 @@ function buildError(message: string, init: Partial<RequestError> = {}): RequestE
return
new
RequestError
(
message
,
init
);
return
new
RequestError
(
message
,
init
);
}
}
/**
* 已经在本层 normalize 里触发过登出的错误,catch 分支不再重复触发。
*
* 双层门面(web 子应用 transport:'host' → 主壳 http.request)下,业务码可能由主壳先判失败、
* 再由子应用 catch 接手;登出回调只应命中一次。WeakSet 只标记本 realm 抛出的错误对象,
* 不跨 realm 传播,因此不会吞掉主壳自己的登出回调。
*/
const
logoutHandledErrors
=
new
WeakSet
<
object
>
();
/** 取错误文案:跨 realm 抛来的错误不是本 realm 的 Error 实例,只能认 message 字段。 */
/** 取错误文案:跨 realm 抛来的错误不是本 realm 的 Error 实例,只能认 message 字段。 */
function
messageOf
(
error
:
unknown
):
string
{
function
messageOf
(
error
:
unknown
):
string
{
const
message
=
(
error
as
{
message
?:
unknown
}
|
undefined
)?.
message
;
const
message
=
(
error
as
{
message
?:
unknown
}
|
undefined
)?.
message
;
...
@@ -674,6 +683,28 @@ export class Request {
...
@@ -674,6 +683,28 @@ export class Request {
lastError
=
error
;
lastError
=
error
;
const
wrapped
=
wrapError
(
error
,
config
);
const
wrapped
=
wrapError
(
error
,
config
);
const
isBusiness
=
wrapped
.
code
!==
undefined
;
const
isBusiness
=
wrapped
.
code
!==
undefined
;
// 双层门面兜底:业务码不一定在本层 normalize 产生。
// web 子应用 transport:'host' 时,主壳先按自己的 response 语义判失败并 reject,
// 子应用 normalize(唯一执行 logoutCodes 判定的地方)被 catch 跳过,
// 于是子应用声明的登出码与 onLoginRequired 永远不会触发(积分 code=20 即此路径)。
// 这里对已 reject 的请求按本层 response.logoutCodes 再判一次,与 normalize 同源。
const
resp
=
config
.
response
??
{};
if
(
isBusiness
&&
!
logoutHandledErrors
.
has
(
wrapped
)
&&
looseMatch
(
resp
.
logoutCodes
??
[
20
,
21
],
wrapped
.
code
)
)
{
const
body
=
(
wrapped
.
response
??
wrapped
.
data
??
{})
as
Record
<
string
,
unknown
>
;
safeEvent
(()
=>
config
.
events
?.
logout
?.(
body
,
config
));
const
decision
=
config
.
onLoginRequired
?.(
wrapped
.
code
as
string
|
number
,
{
resource
,
config
,
body
,
});
logoutHandledErrors
.
add
(
wrapped
);
if
(
decision
&&
typeof
decision
===
'object'
&&
'resolve'
in
decision
)
return
decision
.
resolve
as
T
;
if
((
resp
.
throwOnError
??
true
)
===
false
)
return
(
wrapped
.
response
??
wrapped
.
data
)
as
T
;
}
const
shouldRetry
=
Boolean
(
retry
&&
attempt
<
maxAttempts
-
1
&&
(
retry
.
condition
?
retry
.
condition
(
wrapped
)
:
!
isBusiness
));
const
shouldRetry
=
Boolean
(
retry
&&
attempt
<
maxAttempts
-
1
&&
(
retry
.
condition
?
retry
.
condition
(
wrapped
)
:
!
isBusiness
));
if
(
!
shouldRetry
)
{
if
(
!
shouldRetry
)
{
if
(
!
isBusiness
)
{
if
(
!
isBusiness
)
{
...
@@ -809,7 +840,9 @@ export class Request {
...
@@ -809,7 +840,9 @@ export class Request {
safeUI
(()
=>
ui
.
stopPullDownRefresh
());
safeUI
(()
=>
ui
.
stopPullDownRefresh
());
return
new
Promise
(()
=>
{});
return
new
Promise
(()
=>
{});
}
}
throw
buildError
(
message
,
{
code
:
code
as
string
|
number
,
data
:
errorData
,
config
,
response
:
body
});
const
failure
=
buildError
(
message
,
{
code
:
code
as
string
|
number
,
data
:
errorData
,
config
,
response
:
body
});
logoutHandledErrors
.
add
(
failure
);
throw
failure
;
}
}
if
(
resp
.
resolveOnOther
)
{
if
(
resp
.
resolveOnOther
)
{
...
...
packages/api-core/test/facade.test.mjs
View file @
de1b003
...
@@ -459,6 +459,37 @@ test('IT-FACADE-ENVMSG-001 GSC 信封 msg 键:失败文案原样进 Error.mess
...
@@ -459,6 +459,37 @@ test('IT-FACADE-ENVMSG-001 GSC 信封 msg 键:失败文案原样进 Error.mess
);
);
});
});
test('IT-FACADE-ENVMSG-001B GSC 信封 22 声明为登出码时触发 onLoginRequired', async () => {
let required = false;
let requiredCode;
const client = createClient({
kind: 'gsc',
sender: {
async send() {
return {
status: 200,
data: { code: 22, msg: 'sessionId不存在', data: null, success: false },
headers: { 'content-type': 'application/json' },
};
},
},
baseURL: 'https://gsc.test.glsx.com.cn/gsc-vcp-web-facade',
appKey: 'Web_DJia',
appSecret: 's',
// 与 usedcar/src/api/core/client.ts callConfig 的声明保持一致:
// 不声明时兜底 [20,21] 不含 22,code=22 只会 toast + throw,页面停在原页。
response: { logoutCodes: [20, 21, 22] },
onLoginRequired: (code) => {
required = true;
requiredCode = code;
},
});
await assert.rejects(() => client.post('/dataBoard/evaluation', {}), /sessionId不存在/);
assert.ok(required, 'GSC code=22 命中 logoutCodes 后必须触发 onLoginRequired');
assert.equal(requiredCode, 22);
});
test('IT-FACADE-ENVMSG-002 messageMap:信封无文案时按码回退,信封有文案时信封优先', async () => {
test('IT-FACADE-ENVMSG-002 messageMap:信封无文案时按码回退,信封有文案时信封优先', async () => {
// 信封无 msg → 用 messageMap[22]
// 信封无 msg → 用 messageMap[22]
const withMap = createClient({
const withMap = createClient({
...
...
packages/api-core/test/strategy.test.mjs
View file @
de1b003
...
@@ -592,3 +592,47 @@ test('ST-RPC-008 网关声明的 logoutCodes 命中即触发 onLoginRequired(
...
@@ -592,3 +592,47 @@ test('ST-RPC-008 网关声明的 logoutCodes 命中即触发 onLoginRequired(
assert.ok(required, '网关登出码 21 命中后必须触发 onLoginRequired');
assert.ok(required, '网关登出码 21 命中后必须触发 onLoginRequired');
assert.equal(requiredCode, 21);
assert.equal(requiredCode, 21);
});
});
test('ST-RPC-009 双层门面:主壳按自身码判失败后,子应用仍能凭网关登出码触发 onLoginRequired', async () => {
let required = false;
let requiredCode;
// 模拟真实 web 链路:主壳用 web-host 语义(成功 200 / 登出 401、10002)归一子应用网关响应。
// code=20 在主壳不是登出码,会 throw RequestError;这正是积分明细 code=20 不跳登录页的路径。
const hostApi = new Request(
createStrategy({
kind: 'web-host',
sender: {
async send() {
return { status: 200, data: '{"code":20,"message":"Missing Session"}', headers: {} };
},
},
}),
);
// createHostSender 只透传这些字段,不把子应用的 response.logoutCodes 交给主壳。
const hostSend = (cfg) =>
hostApi.request({
url: cfg.url,
method: cfg.method,
data: cfg.data,
headers: cfg.headers,
transformResponse: cfg.transformResponse,
});
const api = new Request(
createStrategy({
transport: 'host',
hostSend,
gatewayCredential: rpcCredential,
gatewayToken: rpcToken,
timeout: 180000,
contentType: false,
onLoginRequired: (code) => {
required = true;
requiredCode = code;
},
}),
);
await assert.rejects(() => api.post('m.missing.session', {}, { gateway: 'st-rpc' }), /Missing Session/);
assert.ok(required, '主壳 reject 后,子应用门面必须按自己的 logoutCodes 再判一次');
assert.equal(requiredCode, 20);
});
Write
Preview
Markdown
is supported
Attach a file
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to post a comment