headerSigner.test.mjs
5.18 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
/**
* @file 头签名器落点测试:createHeaderSigner 的产物必须进请求头,不能进请求体。
*
* 这里钉住的是「契约边界」而非某个业务的 canonical:Signer.fields 产请求体字段,
* HeaderSigner.headers 产请求头。两条路都留在内核,但入口不同,混用会把 X-* 头写进 body。
* RSA 那套 8 行 canonical 是本域后端事实,仍在 platform-core 业务层,不在本文件范围。
*/
import assert from 'node:assert/strict';
import { createRequire } from 'node:module';
import { createHmac } from 'node:crypto';
import test from 'node:test';
const require = createRequire(import.meta.url);
const {
createHeaderSigner,
createSigner,
createClient,
Request,
} = require('../dist/index.cjs');
const SECRET = 'header-sign-secret';
const APP_KEY = 'mini-app';
const okBody = { data: { id: 7 } };
function makeSender() {
const calls = [];
return {
calls,
sender: {
async send(req) {
calls.push(req);
return { status: 200, data: okBody };
},
},
};
}
/** 用输出的 timestamp/nonce 复算原文,确认签名与头同源(没有第二套时间源)。 */
function recompute(input, headers, appendMethod = true) {
const all = {
'X-App-Id': headers['X-App-Id'],
'X-Nonce': headers['X-Nonce'],
'X-Timestamp': headers['X-Timestamp'],
};
if (appendMethod) all.method = input.method;
for (const [key, value] of Object.entries(input.params ?? {})) {
if (!input.exclude?.includes(key)) all[key] = value;
}
const canonical = Object.keys(all)
.sort()
.map((key) => `${key}=${typeof all[key] === 'string' ? all[key] : JSON.stringify(all[key])}`)
.join('&');
return createHmac('sha256', SECRET).update(`${canonical}&secret=${SECRET}`).digest('hex');
}
test('HS-001 createHeaderSigner 默认产出四个头,签名与 timestamp/nonce 同源', async () => {
const signer = createHeaderSigner();
assert.equal(signer.id, 'hmac-sha256');
assert.equal(typeof signer.headers, 'function');
assert.equal(signer.fields, undefined, '头签名器不得有 fields,防止被当 bodySign 使用');
const input = {
method: 'GET',
params: { page: 1, name: 'a b', ignored: 'x' },
appKey: APP_KEY,
secret: SECRET,
exclude: ['ignored'],
};
const headers = await signer.headers(input);
assert.equal(headers['X-App-Id'], APP_KEY);
assert.match(headers['X-Nonce'], /\S+/);
assert.match(headers['X-Timestamp'], /^\d+$/);
assert.match(headers['X-Sign'], /^[0-9a-f]{64}$/);
assert.equal(
headers['X-Sign'],
recompute(input, headers),
'timestamp / nonce / exclude 必须与签名原文同源',
);
});
test('HS-002 头名可覆盖,appendMethod:false 时方法名不进原文', async () => {
const signer = createHeaderSigner({
headerNames: { appId: 'App-Id', nonce: 'Nonce', timestamp: 'Ts', sign: 'Sig' },
appendMethod: false,
});
const input = { method: 'POST', params: { a: 1 }, appKey: APP_KEY, secret: SECRET };
const headers = await signer.headers(input);
assert.ok(headers['App-Id'] && headers['Nonce'] && headers['Ts'] && headers['Sig']);
assert.equal(headers['X-Sign'], undefined);
const all = {
'App-Id': headers['App-Id'],
Nonce: headers['Nonce'],
Ts: headers['Ts'],
a: 1,
};
const canonical = Object.keys(all)
.sort()
.map((key) => `${key}=${typeof all[key] === 'string' ? all[key] : JSON.stringify(all[key])}`)
.join('&');
const expected = createHmac('sha256', SECRET).update(`${canonical}&secret=${SECRET}`).digest('hex');
assert.equal(headers['Sig'], expected);
});
test('HS-003 经 signature.headerSigner 注入门面:头进 headers、body 不被污染', async () => {
const { calls, sender } = makeSender();
const signer = createHeaderSigner();
const request = new Request({
sender,
appKey: APP_KEY,
appSecret: SECRET,
signature: { id: 'hmac-header', headerSigner: signer },
});
await request.post('/api/orders', { productId: 1 });
const req = calls[0];
assert.ok(req.headers['X-Sign'], '签名头应进 headers');
assert.ok(req.headers['X-Timestamp']);
assert.deepEqual(req.data, { productId: 1 }, '请求体不得被塞入 X-* 头字段');
});
test('HS-004 经 sign 协议接入 createClient:头进 headers,仍是同一份签名器', async () => {
const { calls, sender } = makeSender();
const signer = createHeaderSigner();
const client = createClient({
protocols: {
request: {
prepare: (spec) => ({
url: spec.resource,
method: spec.method,
data: spec.data,
headers: spec.headers,
resource: spec.resource,
}),
normalize: (raw) => raw,
},
sign: { headers: (input) => signer.headers(input) },
},
sender,
appKey: APP_KEY,
appSecret: SECRET,
});
await client.post('/api/orders', { productId: 2 });
const req = calls[0];
assert.ok(req.headers['X-Sign']);
assert.deepEqual(req.data, { productId: 2 });
});
test('HS-005 createSigner 不再接受 hmac:body 与头签名入口必须分开', () => {
assert.throws(
() => createSigner({ kind: 'hmac' }),
/createHeaderSigner/,
'误把 hmac 当 body 签名时应给出明确迁移提示',
);
});