protocol.ts
7.32 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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
/**
* 请求 / 签名协议 → api-core 内部策略的桥接。
*
* 边界
* ────
* URL 怎么拼、签什么、信封长什么样,全部由 @venus/contracts 的 RequestProtocol /
* SignProtocol 决定;「什么时候签」由本层控制(协议 prepare 产出 wire 之后、
* 交给传输层之前),发送、防重复提交、超时取消、重试、拦截器与响应管线留在门面。
* 显式传入的 signature / sign / signBody 优先于协议签名,老项目可平滑过渡。
*
* 为什么只做 type-only import
* ──────────────────────────
* api-core 会被小程序「构建 npm」打成单文件 CJS,运行时不能 require 工作区包。
* 因此调用方传入的是 defineProtocols() **已解析**的 ResolvedProtocols:
* 默认 prepare 与 deps 已由契约层补齐,这里不复制第二份默认值,也不 import 运行时。
*/
import type { ResolvedProtocols, VenusRequestSpec, VenusWireRequest } from '@venus/contracts';
import type { BodySignFn, RequestConfig } from '../core/facade';
import type { HeaderSignInput, RawRequest } from '../core/types';
import type {
PreparedRequest,
RequestStrategy,
SessionValue,
SignatureSpec,
SignatureStrategy,
} from './strategies';
import {
defineRequestStrategy,
defineSignatureStrategy,
resolveSignatureStrategy,
} from './strategies';
/** 协议产物 → 门面认识的策略返回结构;signal 由门面在 prepare 之后统一并入。 */
function toPrepared(wire: VenusWireRequest): PreparedRequest {
return {
url: wire.url,
method: wire.method as RawRequest['method'],
data: wire.data,
headers: wire.headers,
timeout: wire.timeout,
responseType: wire.responseType,
withCredentials: wire.withCredentials,
resource: wire.resource,
normalize: wire.normalize,
response: wire.response as PreparedRequest['response'],
};
}
/** RequestConfig → 协议入参。业务自定义字段(gateway / appKey / hosts ...)原样透传。 */
function toSpec(config: RequestConfig, session?: SessionValue): VenusRequestSpec {
const { protocols: _protocols, session: _sessionOptions, ...rest } = config;
return {
...rest,
resource: String(config.url ?? ''),
method: String(config.method ?? 'GET'),
headers: config.headers ?? {},
session,
} as VenusRequestSpec;
}
/**
* 从协议拼出的最终 wire 反推签名原文上下文。
* 关键点:query / bodyString / mediaType 必须来自「实际要发出去的字节」,
* 否则会出现「签的是 A、发的是 B」这种最难查的网关错误。
*/
function signContext(config: RequestConfig, prepared: PreparedRequest) {
const url = prepared.url;
const qIdx = url.indexOf('?');
const withoutQuery = qIdx < 0 ? url : url.slice(0, qIdx);
const query = qIdx < 0 ? '' : url.slice(qIdx + 1);
let path = withoutQuery;
if (config.baseURL && path.startsWith(config.baseURL)) path = path.slice(config.baseURL.length);
if (!path.startsWith('/')) path = `/${path}`;
const contentType = String(
prepared.headers['Content-Type'] ?? prepared.headers['content-type'] ?? '',
);
const data = prepared.data;
const hasBody = data !== undefined && data !== null;
const mediaType =
contentType.split(';')[0].trim().toLowerCase() || (hasBody ? 'application/json' : '');
const bodyString =
typeof data === 'string'
? data
: data && typeof data === 'object'
? JSON.stringify(data)
: hasBody
? String(data)
: '';
return { path, query, mediaType, bodyString };
}
/** 签名协议 → 签名策略。两个方法都不实现时返回 undefined(= 不签名,零副作用)。 */
export function signatureProtocolStrategy(
protocols: ResolvedProtocols,
): SignatureStrategy | undefined {
const sign = protocols.sign;
if (!sign.body && !sign.headers) return undefined;
return defineSignatureStrategy('protocol', {
...(sign.body ? { bodySign: sign.body as BodySignFn } : {}),
...(sign.headers
? {
headerSigner: {
id: 'protocol',
headers(input: HeaderSignInput) {
return sign.headers!({
method: input.method,
path: input.path ?? '',
query: input.query ?? '',
params: input.params ?? {},
data: input.data,
bodyString: input.bodyString ?? '',
mediaType: input.mediaType ?? '',
appKey: input.appKey,
secret: input.secret,
exclude: input.exclude,
// 时间戳由内核在真正签名时生成,保证与实际发送同源。
timestamp: Date.now(),
});
},
},
}
: {}),
});
}
/**
* 在 prepare 之后、发送之前执行签名。
* 显式配置优先于协议签名:已注入 signature / signBody 时不会双重签名。
*/
async function applySignature(
config: RequestConfig,
protocolSign: SignatureStrategy | undefined,
prepared: PreparedRequest,
): Promise<void> {
const explicit = config.signature ?? config.signBody;
const spec = (explicit !== undefined ? explicit : protocolSign) as SignatureSpec | undefined;
if (spec === undefined) return;
const strategy = resolveSignatureStrategy(spec);
if (!strategy) return;
const appKey = String(config.appKey ?? '');
const secret = String(config.appSecret ?? '');
if (strategy.bodySign && prepared.data && typeof prepared.data === 'object') {
prepared.data = await strategy.bodySign(
{ ...(prepared.data as Record<string, unknown>), appKey },
secret,
config.noSignAttr,
);
}
if (strategy.headerSigner) {
Object.assign(
prepared.headers,
await strategy.headerSigner.headers({
method: prepared.method,
params: (config.params ?? {}) as Record<string, unknown>,
data: prepared.data,
appKey,
secret,
exclude: config.noSignAttr,
url: prepared.url,
...signContext(config, prepared),
}),
);
}
}
/** 请求协议 → 方案策略。协议没实现 prepare 时,契约层的默认实现就是简单 REST。 */
export function requestProtocolStrategy(protocols: ResolvedProtocols): RequestStrategy {
const request = protocols.request;
const protocolSign = signatureProtocolStrategy(protocols);
return defineRequestStrategy({
id: request.id ?? 'rest-fetch',
defaults: request.defaults as Partial<RequestConfig> | undefined,
async prepare(config, session) {
const wire = await request.prepare(toSpec(config, session), protocols.deps);
// 协议 normalize 只在业务显式实现时才有意义;契约默认恒等,对响应管线无害。
const prepared = toPrepared({
...wire,
normalize: wire.normalize ?? ((raw: unknown) => request.normalize(raw, wire, protocols.deps)),
});
await applySignature(config, protocolSign, prepared);
return prepared;
},
});
}
/**
* 协议模式的一站式预设:只注入 strategy,签名在 prepare 之后由本层统一执行。
* 未传 protocols 时调用方不应进入本分支——由 createStrategy 决定何时启用。
*/
export function protocolPreset(protocols: ResolvedProtocols, env: RequestConfig = {}): RequestConfig {
return { strategy: requestProtocolStrategy(protocols), ...env };
}