credentials.ts
3.26 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
73
74
75
76
77
78
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 = {
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 路由不在 scrm 域名上(那里对 dj 的 POST 直接 405 Not Allowed),老系统与二手车小程序
* 的环境表里 dj 与 scrm 从来是两个域名,所以不给「读不到就退回 scrm」的兜底:
* 兜底的后果是接口静默无数据,排查成本远高于少配一个变量时当场报错。
*/
const GATEWAY_ORIGIN_ENV: Record<GatewayId, string> = {
'scrm-shopmall': 'VITE_POINTS_GATEWAY_ORIGIN',
'scrm-carlife': 'VITE_POINTS_GATEWAY_ORIGIN',
'dj-smartcarlife': 'VITE_POINTS_DJ_GATEWAY_ORIGIN',
};
const envOrigin = (id: GatewayId): string => (env[GATEWAY_ORIGIN_ENV[id]] ?? '').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 ?? envOrigin(id),
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: envOrigin(id) };
if (!credential.origin) {
throw new Error(
`未配置 ${id} 网关地址:请在 .env 设置 ${GATEWAY_ORIGIN_ENV[id]}。` +
'积分域的接口不会自动改走主壳后端,也不会退回其它网关的域名。',
);
}
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();
}