credentials.ts
2.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import { getLoginSession } from '@/access';
import type { GatewayCredential } from '@uj/api-core';
import type { GatewayId } from './types';
/**
* 外部网关的运行时凭据注入点。
*
* 适配层不写死任何 appKey/secret:值来自主壳下发的 .env(构建期替换),
* 与老系统把 sign 配置放配置中心下发是同一件事,只是换了投递方式。
* 取不到值时不做静默兜底——请求会带着一句人话失败,而不是「接口没反应」。
*
* 凭据的通用形状(origin/appKey/secret/version/format)由 @uj/api-core 定义,
* 本域只负责从 VITE_POINTS_GATEWAY_* 注入具体取值。
*/
const env = import.meta.env as Record<string, string | undefined>;
const SHARED = {
origin: (env.VITE_POINTS_GATEWAY_ORIGIN ?? '').trim(),
appKey: (env.VITE_POINTS_GATEWAY_APP_KEY ?? '').trim(),
secret: (env.VITE_POINTS_GATEWAY_SECRET ?? '').trim(),
version: (env.VITE_POINTS_GATEWAY_VERSION ?? '1.0.0').trim(),
format: (env.VITE_POINTS_GATEWAY_FORMAT ?? 'json').trim(),
};
/** 个别网关(dj)在老系统里挂在另一个域名上,允许单独覆盖。 */
const OVERRIDES: Partial<Record<GatewayId, string>> = {
'dj-smartcarlife': (env.VITE_POINTS_DJ_GATEWAY_ORIGIN ?? '').trim(),
};
const injected = new Map<GatewayId, GatewayCredential>();
/** 运行时注入(联调脚本、灰度环境或后端下发的配置中心)。 */
export function setGatewayCredential(id: GatewayId, credential: Partial<GatewayCredential>): void {
const previous = injected.get(id);
injected.set(id, {
origin: credential.origin ?? previous?.origin ?? SHARED.origin,
appKey: credential.appKey ?? previous?.appKey ?? SHARED.appKey,
secret: credential.secret ?? previous?.secret ?? SHARED.secret,
version: credential.version ?? previous?.version ?? SHARED.version,
format: credential.format ?? previous?.format ?? SHARED.format,
});
}
export function getGatewayCredential(id: GatewayId): GatewayCredential {
const credential = injected.get(id) ?? {
...SHARED,
origin: OVERRIDES[id] || SHARED.origin,
};
if (!credential.origin) {
throw new Error(
`未配置 ${id} 网关地址:请在 .env 设置 VITE_POINTS_GATEWAY_ORIGIN(或该网关的独立 origin),` +
'积分域的接口不会自动改走主壳后端。',
);
}
return credential;
}
/**
* 会话令牌提供器。老系统把主应用的 session token 放在 token/TGT 头,
* 现系统的主壳登录后已有同一份令牌;若接入时需要换成网关侧签发的令牌,
* 在此注入即可,业务模块与策略都不用动。
*/
let tokenProvider: () => string = () => getLoginSession()?.token ?? '';
export function setGatewayTokenProvider(provider: () => string): void {
tokenProvider = provider;
}
export function getGatewayToken(): string {
return tokenProvider();
}