@kne/fastify-webhook 0.1.3 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/README.md +20 -10
  2. package/index.js +55 -46
  3. package/libs/constants.js +81 -0
  4. package/libs/controllers/_helper.js +16 -0
  5. package/libs/controllers/application.js +73 -0
  6. package/libs/controllers/attempt.js +49 -0
  7. package/libs/controllers/domain.js +40 -0
  8. package/libs/controllers/endpoint.js +90 -0
  9. package/libs/controllers/eventType.js +84 -0
  10. package/libs/controllers/ingest.js +83 -0
  11. package/libs/controllers/mcp.js +41 -0
  12. package/libs/controllers/message.js +56 -0
  13. package/libs/controllers/misc.js +81 -0
  14. package/libs/controllers/operational.js +26 -0
  15. package/libs/controllers/play.js +33 -0
  16. package/libs/controllers/polling.js +48 -0
  17. package/libs/controllers/portal.js +32 -0
  18. package/libs/controllers/public.js +47 -0
  19. package/libs/controllers/stream.js +74 -0
  20. package/libs/helpers/context.js +50 -0
  21. package/libs/models/appPortalSession.js +18 -0
  22. package/libs/models/application.js +21 -0
  23. package/libs/models/attempt.js +36 -0
  24. package/libs/models/channel.js +12 -0
  25. package/libs/models/customDomain.js +15 -0
  26. package/libs/models/endpoint.js +37 -0
  27. package/libs/models/environment.js +13 -0
  28. package/libs/models/eventType.js +22 -0
  29. package/libs/models/idempotency.js +14 -0
  30. package/libs/models/inbox.js +17 -0
  31. package/libs/models/ingestSource.js +17 -0
  32. package/libs/models/ingestToken.js +15 -0
  33. package/libs/models/message.js +27 -0
  34. package/libs/models/operationalSubscription.js +13 -0
  35. package/libs/models/pollingConsumer.js +15 -0
  36. package/libs/models/pollingEndpoint.js +13 -0
  37. package/libs/models/sink.js +20 -0
  38. package/libs/models/stream.js +13 -0
  39. package/libs/models/streamEvent.js +14 -0
  40. package/libs/models/transformation.js +13 -0
  41. package/libs/schema/response.js +120 -0
  42. package/libs/services/appPortal.js +87 -0
  43. package/libs/services/application.js +94 -0
  44. package/libs/services/attempt.js +151 -0
  45. package/libs/services/customDomain.js +87 -0
  46. package/libs/services/delivery.js +297 -0
  47. package/libs/services/endpoint.js +236 -0
  48. package/libs/services/eventType.js +173 -0
  49. package/libs/services/fifo.js +34 -0
  50. package/libs/services/inbound.js +108 -0
  51. package/libs/services/ingest.js +294 -0
  52. package/libs/services/mcp.js +60 -0
  53. package/libs/services/message.js +200 -0
  54. package/libs/services/operational.js +70 -0
  55. package/libs/services/play.js +87 -0
  56. package/libs/services/polling.js +162 -0
  57. package/libs/services/retention.js +66 -0
  58. package/libs/services/scheduler.js +50 -0
  59. package/libs/services/sink.js +67 -0
  60. package/libs/services/stream.js +138 -0
  61. package/libs/services/throttle.js +63 -0
  62. package/libs/services/transform.js +102 -0
  63. package/libs/sinks/index.js +105 -0
  64. package/libs/utils/common.js +184 -0
  65. package/libs/utils/index.js +10 -0
  66. package/libs/utils/outbound.js +114 -0
  67. package/libs/utils/signature.js +160 -0
  68. package/package.json +21 -11
  69. package/libs/controllers/main.js +0 -168
  70. package/libs/models/client.js +0 -58
  71. package/libs/models/example._js +0 -18
  72. package/libs/models/invocation.js +0 -40
  73. package/libs/services/example._js +0 -10
  74. package/libs/services/main.js +0 -172
@@ -0,0 +1,102 @@
1
+ 'use strict';
2
+
3
+ const fp = require('fastify-plugin');
4
+ const vm = require('node:vm');
5
+ const { DEFAULT_TIMEOUT } = { DEFAULT_TIMEOUT: 1000 };
6
+
7
+ module.exports = fp(async (fastify, options) => {
8
+ const ctx = fastify[options.name].context;
9
+ const { models, utils, tenantWhere } = ctx;
10
+
11
+ const enabled = () => options.enableTransformations !== false;
12
+
13
+ /**
14
+ * 在隔离的 vm 沙箱中执行变换脚本。
15
+ * 禁用 require / process / 网络 / 文件系统,限制 CPU 时间。
16
+ */
17
+ const run = async (code, input, variables = {}) => {
18
+ if (!code || !enabled()) {
19
+ return input;
20
+ }
21
+ const sandbox = Object.create(null);
22
+ sandbox.console = { log: () => {}, warn: () => {}, error: () => {} };
23
+ sandbox.JSON = JSON;
24
+ sandbox.Date = Date;
25
+ sandbox.Math = Math;
26
+ sandbox.String = String;
27
+ sandbox.Number = Number;
28
+ sandbox.Boolean = Boolean;
29
+ sandbox.Array = Array;
30
+ sandbox.Object = Object;
31
+ sandbox.env = variables || {};
32
+ // 不冻结对象:handler 需要修改 method/url/payload 等字段
33
+ sandbox.webhook = JSON.parse(JSON.stringify(input || {}));
34
+
35
+ const context = vm.createContext(sandbox, {
36
+ codeGeneration: { strings: false, wasm: false }
37
+ });
38
+
39
+ const wrapped = `(function () { ${code}\n if (typeof handler === 'function') { return handler(webhook); } return webhook; })()`;
40
+ const script = new vm.Script(wrapped, { filename: 'transformation.js' });
41
+ const result = script.runInContext(context, { timeout: options.transformTimeout || DEFAULT_TIMEOUT });
42
+ if (!result || typeof result !== 'object') {
43
+ return input;
44
+ }
45
+ // 禁止覆盖只读字段
46
+ const output = { ...input };
47
+ // data/events 供 Sink 批次变换改写事件列表
48
+ ['method', 'url', 'payload', 'body', 'headers', 'cancel', 'data', 'events'].forEach(key => {
49
+ if (result[key] !== undefined) {
50
+ output[key] = result[key];
51
+ }
52
+ });
53
+ return output;
54
+ };
55
+
56
+ const runForEndpoint = async (tenantId, endpointId, input) => {
57
+ if (!enabled()) {
58
+ return null;
59
+ }
60
+ const record = await models.transformation.findOne({ where: tenantWhere({ tenantId }, { endpointId }) });
61
+ if (!record || !record.enabled || !record.code) {
62
+ return null;
63
+ }
64
+ return run(record.code, input, record.variables || {});
65
+ };
66
+
67
+ const save = async (authenticatePayload, data) => {
68
+ const tenantId = utils.resolveTenantId(authenticatePayload);
69
+ const where = tenantWhere(authenticatePayload, { endpointId: data.endpointId });
70
+ const existing = await models.transformation.findOne({ where });
71
+ if (existing) {
72
+ existing.code = data.code || '';
73
+ existing.enabled = data.enabled !== false;
74
+ existing.variables = data.variables || {};
75
+ await existing.save();
76
+ return existing;
77
+ }
78
+ return models.transformation.create({
79
+ tenantId,
80
+ endpointId: data.endpointId,
81
+ code: data.code || '',
82
+ enabled: data.enabled !== false,
83
+ variables: data.variables || {}
84
+ });
85
+ };
86
+
87
+ const get = async (authenticatePayload, { endpointId }) => {
88
+ const record = await models.transformation.findOne({ where: tenantWhere(authenticatePayload, { endpointId }) });
89
+ if (!record) {
90
+ return { code: '', enabled: false, variables: {} };
91
+ }
92
+ return { code: record.code, enabled: record.enabled, variables: record.variables };
93
+ };
94
+
95
+ fastify[options.name].services.transform = {
96
+ enabled,
97
+ run,
98
+ runForEndpoint,
99
+ save,
100
+ get
101
+ };
102
+ });
@@ -0,0 +1,105 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Sink 适配器接口:
5
+ * deliver(context, events, config) -> { success, ... }
6
+ * context 提供 fetch/log 等能力,便于测试注入。
7
+ */
8
+
9
+ const formatEvents = (events, format = 'jsonl') => {
10
+ if (format === 'raw') {
11
+ return events.map(item => item.payload).join('\n');
12
+ }
13
+ if (format === 'json') {
14
+ return JSON.stringify(events.map(item => ({ eventType: item.eventType, payload: item.payload })));
15
+ }
16
+ return events
17
+ .map(item => JSON.stringify({ eventType: item.eventType, payload: item.payload }))
18
+ .join('\n');
19
+ };
20
+
21
+ const httpSink = async (context, events, config) => {
22
+ const body = formatEvents(events, config.format || 'jsonl');
23
+ const headers = Object.assign({ 'content-type': 'application/x-ndjson' }, config.headers || {});
24
+ const response = await context.fetch(config.url, {
25
+ method: 'POST',
26
+ headers,
27
+ body
28
+ });
29
+ return { success: response.status >= 200 && response.status < 300, status: response.status };
30
+ };
31
+
32
+ const adapters = {
33
+ // HTTP 通用(datadog / clickHouse / 自建收集器常走 HTTP 接口)
34
+ datadog: httpSink,
35
+ clickHouse: httpSink,
36
+ amazonS3: async (context, events, config) => {
37
+ // 通过 S3 Presigned URL 或兼容 S3 的 HTTP 端点写入
38
+ const body = formatEvents(events, config.format || 'jsonl');
39
+ const key = (config.key || 'events/{{date}}.jsonl').replace('{{date}}', new Date().toISOString().slice(0, 10));
40
+ const url = `${config.endpoint}/${config.bucket}/${key}`;
41
+ const response = await context.fetch(url, { method: 'PUT', headers: config.headers || {}, body });
42
+ return { success: response.status >= 200 && response.status < 300, key };
43
+ },
44
+ azureBlob: async (context, events, config) => {
45
+ const body = formatEvents(events, config.format || 'jsonl');
46
+ const url = `${config.endpoint}/${config.container}/${config.blob || 'events.jsonl'}`;
47
+ const response = await context.fetch(url, { method: 'PUT', headers: config.headers || {}, body });
48
+ return { success: response.status >= 200 && response.status < 300 };
49
+ },
50
+ googleCloudStorage: async (context, events, config) => {
51
+ const body = formatEvents(events, config.format || 'jsonl');
52
+ const url = `${config.endpoint || 'https://storage.googleapis.com/upload/storage/v1'}/${config.bucket}/o?uploadType=media&name=${encodeURIComponent(config.object || 'events.jsonl')}`;
53
+ const response = await context.fetch(url, { method: 'POST', headers: config.headers || {}, body });
54
+ return { success: response.status >= 200 && response.status < 300 };
55
+ },
56
+ amazonSQS: async (context, events, config) => {
57
+ const body = formatEvents(events, 'json');
58
+ const response = await context.fetch(config.endpoint, {
59
+ method: 'POST',
60
+ headers: { 'content-type': 'application/x-www-form-urlencoded' },
61
+ body: new URLSearchParams({
62
+ Action: 'SendMessage',
63
+ MessageBody: body,
64
+ QueueUrl: config.queueUrl,
65
+ Version: '2012-11-05'
66
+ }).toString()
67
+ });
68
+ return { success: response.status >= 200 && response.status < 300 };
69
+ },
70
+ snowflake: async (context, events, config) => {
71
+ // 通过 Snowflake Ingest SDK 的 HTTP API 上传
72
+ const body = formatEvents(events, 'jsonl');
73
+ const response = await context.fetch(config.endpoint, { method: 'POST', headers: config.headers || {}, body });
74
+ return { success: response.status >= 200 && response.status < 300 };
75
+ },
76
+ bigQuery: async (context, events, config) => {
77
+ const body = JSON.stringify({ rows: events.map(item => ({ json: item.payload })) });
78
+ const url = `https://bigquery.googleapis.com/bigquery/v2/projects/${config.projectId}/datasets/${config.datasetId}/tables/${config.tableId}/insertAll`;
79
+ const response = await context.fetch(url, { method: 'POST', headers: config.headers || {}, body });
80
+ return { success: response.status >= 200 && response.status < 300 };
81
+ },
82
+ rabbitMQ: async (context, events, config) => {
83
+ const body = formatEvents(events, 'jsonl');
84
+ const url = `${config.endpoint}/api/exchanges/${encodeURIComponent(config.vhost || '%2F')}/${config.exchange}/publish`;
85
+ const response = await context.fetch(url, {
86
+ method: 'POST',
87
+ headers: { 'content-type': 'application/json' },
88
+ body: JSON.stringify({ routing_key: config.routingKey || '', payload: Buffer.from(body).toString('base64'), payload_encoding: 'base64' })
89
+ });
90
+ return { success: response.status >= 200 && response.status < 300 };
91
+ },
92
+ eventBridge: async (context, events, config) => {
93
+ const body = JSON.stringify({
94
+ Entries: events.map(item => ({ Source: config.source || 'webhook', DetailType: item.eventType, Detail: JSON.stringify(item.payload) }))
95
+ });
96
+ const response = await context.fetch(config.endpoint, {
97
+ method: 'POST',
98
+ headers: { 'content-type': 'application/x-amz-json-1.1', 'x-amz-target': 'AWSEvents.PutEvents' },
99
+ body
100
+ });
101
+ return { success: response.status >= 200 && response.status < 300 };
102
+ }
103
+ };
104
+
105
+ module.exports = { formatEvents, adapters, httpSink };
@@ -0,0 +1,184 @@
1
+ 'use strict';
2
+
3
+ const crypto = require('node:crypto');
4
+ const { RETRY_SCHEDULE, MAX_RETRY_AFTER, GLOBAL_TENANT_ID } = require('../constants');
5
+
6
+ /** 生成带前缀的唯一 ID,形如 msg_01HXYZ... */
7
+ function generateId(prefix) {
8
+ const ts = Date.now().toString(36);
9
+ const rand = crypto.randomBytes(8).toString('hex');
10
+ return `${prefix}_${ts}${rand}`;
11
+ }
12
+
13
+ /** 生成随机 token(用于 magic link / ingest / polling api key) */
14
+ function generateToken(bytes = 32) {
15
+ return crypto.randomBytes(bytes).toString('base64url');
16
+ }
17
+
18
+ /** 对 token 做哈希,数据库中只存哈希 */
19
+ function hashToken(token) {
20
+ return crypto.createHash('sha256').update(String(token)).digest('hex');
21
+ }
22
+
23
+ /**
24
+ * 计算第 retryCount 次失败后的下次重试时间。
25
+ * retryCount 从 0 开始(第 0 次失败 -> 索引 0 的立即重试)。
26
+ */
27
+ function nextRetryDelay(retryCount) {
28
+ const index = Math.min(retryCount, RETRY_SCHEDULE.length - 1);
29
+ return RETRY_SCHEDULE[index];
30
+ }
31
+
32
+ /** 最大重试次数(retry 计划长度,含首次立即重试) */
33
+ const MAX_RETRY_COUNT = RETRY_SCHEDULE.length;
34
+
35
+ /**
36
+ * 解析 Retry-After 头,支持秒数、RFC 2822、RFC 3339。
37
+ * 返回毫秒数,超出上限按上限截断,非法返回 null。
38
+ */
39
+ function parseRetryAfter(value) {
40
+ if (value == null || value === '') {
41
+ return null;
42
+ }
43
+ const str = String(value).trim();
44
+ if (/^\d+$/.test(str)) {
45
+ return Math.min(Number(str) * 1000, MAX_RETRY_AFTER);
46
+ }
47
+ const ms = Date.parse(str);
48
+ if (!Number.isNaN(ms)) {
49
+ const delay = ms - Date.now();
50
+ if (delay <= 0) {
51
+ return 0;
52
+ }
53
+ return Math.min(delay, MAX_RETRY_AFTER);
54
+ }
55
+ return null;
56
+ }
57
+
58
+ /** 判断响应头要求的投递控制动作 */
59
+ function parseDeliveryControl(headers) {
60
+ const normalized = {};
61
+ Object.keys(headers || {}).forEach(key => {
62
+ normalized[key.toLowerCase()] = headers[key];
63
+ });
64
+ const value = String(normalized['webhook-delivery'] || '').toLowerCase();
65
+ if (value.includes('abort-message')) {
66
+ return 'abort-message';
67
+ }
68
+ if (value.includes('disable')) {
69
+ return 'disable';
70
+ }
71
+ return null;
72
+ }
73
+
74
+ /** 判断状态码是否表示投递成功:仅 2xx,且 3xx 也视为失败 */
75
+ function isSuccessStatus(statusCode) {
76
+ return Number(statusCode) >= 200 && Number(statusCode) < 300;
77
+ }
78
+
79
+ /** 判断 URL 是否指向内网/私网/环回/链路本地/云元数据,用于 SSRF 防护 */
80
+ function isPrivateUrl(url) {
81
+ let parsed;
82
+ try {
83
+ parsed = new URL(url);
84
+ } catch {
85
+ return true;
86
+ }
87
+ if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') {
88
+ return true;
89
+ }
90
+ const host = (parsed.hostname || '').toLowerCase();
91
+ if (host === 'localhost' || host.endsWith('.localhost') || host.endsWith('.local') || host === 'metadata.google.internal') {
92
+ return true;
93
+ }
94
+ // IPv4 私网段
95
+ const ipv4 = host.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);
96
+ if (ipv4) {
97
+ const [a, b] = [Number(ipv4[1]), Number(ipv4[2])];
98
+ if (a === 10 || a === 127 || a === 0 || (a === 169 && b === 254) || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168) || (a === 100 && b >= 64 && b <= 127)) {
99
+ return true;
100
+ }
101
+ return false;
102
+ }
103
+ // IPv6 环回 / 唯一本地 / 链路本地
104
+ if (host.includes(':') || host.startsWith('[')) {
105
+ const bare = host.replace(/^\[|\]$/g, '');
106
+ if (bare === '::1' || bare === '::' || /^f[cd]/i.test(bare) || /^fe[89ab]/i.test(bare)) {
107
+ return true;
108
+ }
109
+ }
110
+ return false;
111
+ }
112
+
113
+ /** 从 tenant payload 中提取租户 id;缺省返回空串,表示全局作用域 */
114
+ function resolveTenantId(authenticatePayload) {
115
+ if (!authenticatePayload) {
116
+ return GLOBAL_TENANT_ID;
117
+ }
118
+ const tenantId = authenticatePayload.tenantId ?? authenticatePayload.tenant?.id ?? authenticatePayload.tenant_id;
119
+ return tenantId == null || tenantId === '' ? GLOBAL_TENANT_ID : String(tenantId);
120
+ }
121
+
122
+ /** 判断两条 channels 是否有交集(大小写敏感) */
123
+ function channelsIntersect(endpointChannels, messageChannels) {
124
+ if (!Array.isArray(messageChannels) || messageChannels.length === 0) {
125
+ return false;
126
+ }
127
+ if (!Array.isArray(endpointChannels) || endpointChannels.length === 0) {
128
+ return false;
129
+ }
130
+ const set = new Set(messageChannels.map(String));
131
+ return endpointChannels.some(item => set.has(String(item)));
132
+ }
133
+
134
+ /** 判断端点是否匹配消息的事件类型与 channels */
135
+ function endpointMatches(endpoint, message) {
136
+ const eventTypes = Array.isArray(endpoint.eventTypes) ? endpoint.eventTypes : [];
137
+ if (eventTypes.length > 0 && !eventTypes.includes(message.type)) {
138
+ return false;
139
+ }
140
+ const epChannels = Array.isArray(endpoint.channels) ? endpoint.channels : [];
141
+ const msgChannels = Array.isArray(message.channels) ? message.channels : [];
142
+ // 规则 1:端点无 channels,接收全部消息
143
+ if (epChannels.length === 0) {
144
+ return true;
145
+ }
146
+ // 规则 2:双方都有 channels,有交集才投递
147
+ // 规则 3:端点有 channels、消息无 channels,不投递
148
+ return channelsIntersect(epChannels, msgChannels);
149
+ }
150
+
151
+ /** 计算平滑限流的下一个可执行时间(token bucket 简化版) */
152
+ function nextThrottleTime(ratePerSecond, recentCount, windowMs = 1000) {
153
+ if (!ratePerSecond || ratePerSecond <= 0) {
154
+ return 0;
155
+ }
156
+ if (recentCount < ratePerSecond) {
157
+ return 0;
158
+ }
159
+ return Math.ceil((windowMs / ratePerSecond) * (recentCount - ratePerSecond + 1));
160
+ }
161
+
162
+ /** 从请求头中规范化取值(大小写不敏感) */
163
+ function getHeader(headers, name) {
164
+ const target = name.toLowerCase();
165
+ const key = Object.keys(headers || {}).find(k => k.toLowerCase() === target);
166
+ return key ? headers[key] : undefined;
167
+ }
168
+
169
+ module.exports = {
170
+ generateId,
171
+ generateToken,
172
+ hashToken,
173
+ nextRetryDelay,
174
+ MAX_RETRY_COUNT,
175
+ parseRetryAfter,
176
+ parseDeliveryControl,
177
+ isSuccessStatus,
178
+ isPrivateUrl,
179
+ resolveTenantId,
180
+ channelsIntersect,
181
+ endpointMatches,
182
+ nextThrottleTime,
183
+ getHeader
184
+ };
@@ -0,0 +1,10 @@
1
+ 'use strict';
2
+
3
+ const fp = require('fastify-plugin');
4
+ const signature = require('./signature');
5
+ const common = require('./common');
6
+ const outbound = require('./outbound');
7
+
8
+ module.exports = fp(async (fastify, options) => {
9
+ fastify[options.name].utils = Object.assign({}, signature, common, outbound);
10
+ });
@@ -0,0 +1,114 @@
1
+ 'use strict';
2
+
3
+ const { DELIVERY_TIMEOUT } = require('../constants');
4
+ const { isPrivateUrl } = require('./common');
5
+
6
+ /**
7
+ * 校验出站 URL:默认禁止私网;投递前(含变换改写后)必须调用。
8
+ * @throws {Error} URL 非法或命中 SSRF 规则
9
+ */
10
+ function assertOutboundUrl(url, { allowPrivateUrl = false } = {}) {
11
+ if (!url || typeof url !== 'string') {
12
+ throw new Error('出站 URL 不能为空');
13
+ }
14
+ let parsed;
15
+ try {
16
+ parsed = new URL(url);
17
+ } catch {
18
+ throw new Error('出站 URL 非法');
19
+ }
20
+ if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:') {
21
+ throw new Error('出站 URL 仅支持 http/https');
22
+ }
23
+ if (!allowPrivateUrl && isPrivateUrl(url)) {
24
+ throw new Error('出站 URL 指向私网地址,已被 SSRF 防护拒绝');
25
+ }
26
+ return parsed;
27
+ }
28
+
29
+ /**
30
+ * 统一出站 HTTP。
31
+ * - 默认走全局 fetch,绝不回退到 fastify.inject(inject 只能打本地路由)
32
+ * - 测试可注入 httpClient:优先 request(),其次兼容旧版 inject()
33
+ * @returns {{ status: number, headers: object, body: string }}
34
+ */
35
+ async function sendHttp(
36
+ { method = 'POST', url, headers = {}, body, timeout = DELIVERY_TIMEOUT },
37
+ { httpClient, allowPrivateUrl = false, skipUrlCheck = false } = {}
38
+ ) {
39
+ if (!skipUrlCheck) {
40
+ assertOutboundUrl(url, { allowPrivateUrl });
41
+ }
42
+
43
+ if (httpClient) {
44
+ if (typeof httpClient.request === 'function') {
45
+ const response = await httpClient.request({ method, url, headers, body, timeout });
46
+ return normalizeResponse(response);
47
+ }
48
+ if (typeof httpClient.inject === 'function') {
49
+ const response = await httpClient.inject({
50
+ method,
51
+ url,
52
+ headers,
53
+ payload: body
54
+ });
55
+ return normalizeResponse({
56
+ status: response.statusCode ?? response.status,
57
+ headers: response.headers || {},
58
+ body: typeof response.body === 'string' ? response.body : JSON.stringify(response.body || {})
59
+ });
60
+ }
61
+ if (typeof httpClient.fetch === 'function') {
62
+ return fetchOnce(httpClient.fetch, { method, url, headers, body, timeout });
63
+ }
64
+ }
65
+
66
+ return fetchOnce(globalThis.fetch, { method, url, headers, body, timeout });
67
+ }
68
+
69
+ async function fetchOnce(fetchImpl, { method, url, headers, body, timeout }) {
70
+ if (typeof fetchImpl !== 'function') {
71
+ throw new Error('当前运行时无可用的 fetch,请注入 options.httpClient');
72
+ }
73
+ const controller = new AbortController();
74
+ const timer = setTimeout(() => controller.abort(), timeout);
75
+ try {
76
+ const response = await fetchImpl(url, {
77
+ method,
78
+ headers,
79
+ body,
80
+ signal: controller.signal
81
+ });
82
+ const text = typeof response.text === 'function' ? await response.text() : String(response.body || '');
83
+ return normalizeResponse({
84
+ status: response.status,
85
+ headers: response.headers || {},
86
+ body: text
87
+ });
88
+ } finally {
89
+ clearTimeout(timer);
90
+ }
91
+ }
92
+
93
+ function normalizeResponse(response) {
94
+ const headers = {};
95
+ const raw = response.headers || {};
96
+ if (typeof raw.forEach === 'function') {
97
+ raw.forEach((value, key) => {
98
+ headers[key] = value;
99
+ });
100
+ } else {
101
+ Object.assign(headers, raw);
102
+ }
103
+ return {
104
+ status: Number(response.status || response.statusCode || 0),
105
+ headers,
106
+ body: response.body == null ? '' : String(response.body)
107
+ };
108
+ }
109
+
110
+ module.exports = {
111
+ assertOutboundUrl,
112
+ sendHttp,
113
+ normalizeResponse
114
+ };
@@ -0,0 +1,160 @@
1
+ 'use strict';
2
+
3
+ const crypto = require('node:crypto');
4
+ const {
5
+ SECRET_PREFIX,
6
+ SIGNATURE_HEADER,
7
+ ID_HEADER,
8
+ TIMESTAMP_HEADER,
9
+ TIMESTAMP_TOLERANCE,
10
+ SIGNATURE_SCHEME
11
+ } = require('../constants');
12
+
13
+ /**
14
+ * 将 whsec_ 前缀的密钥解码为原始字节。
15
+ * Standard Webhooks 规定密钥内容为 base64,签名时使用解码后的字节。
16
+ */
17
+ function decodeSecret(secret) {
18
+ if (typeof secret !== 'string' || !secret) {
19
+ throw new Error('签名密钥不能为空');
20
+ }
21
+ const raw = secret.startsWith(SECRET_PREFIX) ? secret.slice(SECRET_PREFIX.length) : secret;
22
+ if (!raw) {
23
+ throw new Error('签名密钥不能为空');
24
+ }
25
+ const decoded = Buffer.from(raw, 'base64');
26
+ if (!decoded.length) {
27
+ throw new Error('签名密钥不能为空');
28
+ }
29
+ return decoded;
30
+ }
31
+
32
+ /** 生成标准 Webhooks 签名值(不含 scheme 前缀),返回 base64 字符串 */
33
+ function signValue({ id, timestamp, rawBody, secret }) {
34
+ const key = decodeSecret(secret);
35
+ const payload = `${id}.${timestamp}.${rawBody}`;
36
+ return crypto.createHmac('sha256', key).update(payload, 'utf8').digest('base64');
37
+ }
38
+
39
+ /** 生成完整的 webhook-signature 头值,形如 "v1,<base64>" */
40
+ function sign({ id, timestamp, rawBody, secret }) {
41
+ return `${SIGNATURE_SCHEME},${signValue({ id, timestamp, rawBody, secret })}`;
42
+ }
43
+
44
+ /** 生成一套完整的签名请求头 */
45
+ function signHeaders({ id, timestamp, rawBody, secret }) {
46
+ const ts = timestamp == null ? Math.floor(Date.now() / 1000) : timestamp;
47
+ return {
48
+ [ID_HEADER]: id,
49
+ [TIMESTAMP_HEADER]: String(ts),
50
+ [SIGNATURE_HEADER]: sign({ id, timestamp: ts, rawBody, secret })
51
+ };
52
+ }
53
+
54
+ /** 常量时间字符串比较,避免时序侧信道 */
55
+ function safeEqual(a, b) {
56
+ const bufA = Buffer.from(String(a));
57
+ const bufB = Buffer.from(String(b));
58
+ if (bufA.length !== bufB.length) {
59
+ // 仍执行一次比较以保持时间相近,然后返回 false
60
+ crypto.timingSafeEqual(bufA, bufA);
61
+ return false;
62
+ }
63
+ return crypto.timingSafeEqual(bufA, bufB);
64
+ }
65
+
66
+ /**
67
+ * 从 header 值中解析出所有候选签名。
68
+ * 形如 "v1,aaa v1,bbb" 或 "v1,aaa";轮换期会有多个空格分隔的签名。
69
+ */
70
+ function parseSignatures(headerValue) {
71
+ if (typeof headerValue !== 'string' || !headerValue) {
72
+ return [];
73
+ }
74
+ return headerValue
75
+ .split(/\s+/)
76
+ .map(item => {
77
+ const idx = item.indexOf(',');
78
+ if (idx === -1) {
79
+ return { scheme: item, value: '' };
80
+ }
81
+ return { scheme: item.slice(0, idx), value: item.slice(idx + 1) };
82
+ })
83
+ .filter(item => item.value);
84
+ }
85
+
86
+ /**
87
+ * 校验入站 webhook 签名。
88
+ * @param {object} params
89
+ * @param {string|Buffer} params.rawBody 原始请求体(必须是未经解析的字节/字符串)
90
+ * @param {object} params.headers 请求头对象(大小写不敏感)
91
+ * @param {string|string[]} params.secrets 一个或多个候选密钥(轮换期多个)
92
+ * @param {number} [params.tolerance] 时间戳容差毫秒,默认 5 分钟
93
+ * @param {boolean} [params.ignoreTimestamp] 跳过时间戳容差校验(仍需合法时间戳,签名仍包含时间戳)
94
+ * @returns {{id: string, timestamp: number}} 校验通过时返回消息 id 与时间戳
95
+ * @throws {Error} 校验失败
96
+ */
97
+ function verify({ rawBody, headers, secrets, tolerance = TIMESTAMP_TOLERANCE, ignoreTimestamp = false }) {
98
+ const normalized = {};
99
+ Object.keys(headers || {}).forEach(key => {
100
+ normalized[key.toLowerCase()] = headers[key];
101
+ });
102
+
103
+ const id = normalized[ID_HEADER];
104
+ const timestampRaw = normalized[TIMESTAMP_HEADER];
105
+ const signatureHeader = normalized[SIGNATURE_HEADER];
106
+
107
+ if (!id || !timestampRaw || !signatureHeader) {
108
+ throw new Error('缺少必需的签名请求头');
109
+ }
110
+
111
+ const timestamp = Number(timestampRaw);
112
+ if (!Number.isFinite(timestamp)) {
113
+ throw new Error('webhook-timestamp 不是合法时间戳');
114
+ }
115
+
116
+ if (!ignoreTimestamp) {
117
+ const nowSec = Math.floor(Date.now() / 1000);
118
+ if (Math.abs(nowSec - timestamp) * 1000 > tolerance) {
119
+ throw new Error('webhook-timestamp 超出允许的时间容差');
120
+ }
121
+ }
122
+
123
+ const signatures = parseSignatures(signatureHeader);
124
+ if (!signatures.length) {
125
+ throw new Error('webhook-signature 格式非法');
126
+ }
127
+
128
+ const raw = Buffer.isBuffer(rawBody) ? rawBody.toString('utf8') : String(rawBody);
129
+ const secretList = Array.isArray(secrets) ? secrets : [secrets];
130
+
131
+ for (const signature of signatures) {
132
+ if (signature.scheme !== SIGNATURE_SCHEME) {
133
+ continue;
134
+ }
135
+ for (const secret of secretList) {
136
+ const expected = signValue({ id, timestamp, rawBody: raw, secret });
137
+ if (safeEqual(expected, signature.value)) {
138
+ return { id, timestamp };
139
+ }
140
+ }
141
+ }
142
+
143
+ throw new Error('webhook 签名校验失败');
144
+ }
145
+
146
+ /** 生成一个随机 secret(whsec_ 前缀 + base64) */
147
+ function generateSecret(bytes = 32) {
148
+ return `${SECRET_PREFIX}${crypto.randomBytes(bytes).toString('base64')}`;
149
+ }
150
+
151
+ module.exports = {
152
+ decodeSecret,
153
+ signValue,
154
+ sign,
155
+ signHeaders,
156
+ verify,
157
+ generateSecret,
158
+ parseSignatures,
159
+ safeEqual
160
+ };