@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.
- package/README.md +20 -10
- package/index.js +55 -46
- package/libs/constants.js +81 -0
- package/libs/controllers/_helper.js +16 -0
- package/libs/controllers/application.js +73 -0
- package/libs/controllers/attempt.js +49 -0
- package/libs/controllers/domain.js +40 -0
- package/libs/controllers/endpoint.js +90 -0
- package/libs/controllers/eventType.js +84 -0
- package/libs/controllers/ingest.js +83 -0
- package/libs/controllers/mcp.js +41 -0
- package/libs/controllers/message.js +56 -0
- package/libs/controllers/misc.js +81 -0
- package/libs/controllers/operational.js +26 -0
- package/libs/controllers/play.js +33 -0
- package/libs/controllers/polling.js +48 -0
- package/libs/controllers/portal.js +32 -0
- package/libs/controllers/public.js +47 -0
- package/libs/controllers/stream.js +74 -0
- package/libs/helpers/context.js +50 -0
- package/libs/models/appPortalSession.js +18 -0
- package/libs/models/application.js +21 -0
- package/libs/models/attempt.js +36 -0
- package/libs/models/channel.js +12 -0
- package/libs/models/customDomain.js +15 -0
- package/libs/models/endpoint.js +37 -0
- package/libs/models/environment.js +13 -0
- package/libs/models/eventType.js +22 -0
- package/libs/models/idempotency.js +14 -0
- package/libs/models/inbox.js +17 -0
- package/libs/models/ingestSource.js +17 -0
- package/libs/models/ingestToken.js +15 -0
- package/libs/models/message.js +27 -0
- package/libs/models/operationalSubscription.js +13 -0
- package/libs/models/pollingConsumer.js +15 -0
- package/libs/models/pollingEndpoint.js +13 -0
- package/libs/models/sink.js +20 -0
- package/libs/models/stream.js +13 -0
- package/libs/models/streamEvent.js +14 -0
- package/libs/models/transformation.js +13 -0
- package/libs/schema/response.js +120 -0
- package/libs/services/appPortal.js +87 -0
- package/libs/services/application.js +94 -0
- package/libs/services/attempt.js +151 -0
- package/libs/services/customDomain.js +87 -0
- package/libs/services/delivery.js +297 -0
- package/libs/services/endpoint.js +236 -0
- package/libs/services/eventType.js +173 -0
- package/libs/services/fifo.js +34 -0
- package/libs/services/inbound.js +108 -0
- package/libs/services/ingest.js +294 -0
- package/libs/services/mcp.js +60 -0
- package/libs/services/message.js +200 -0
- package/libs/services/operational.js +70 -0
- package/libs/services/play.js +87 -0
- package/libs/services/polling.js +162 -0
- package/libs/services/retention.js +66 -0
- package/libs/services/scheduler.js +50 -0
- package/libs/services/sink.js +67 -0
- package/libs/services/stream.js +138 -0
- package/libs/services/throttle.js +63 -0
- package/libs/services/transform.js +102 -0
- package/libs/sinks/index.js +105 -0
- package/libs/utils/common.js +184 -0
- package/libs/utils/index.js +10 -0
- package/libs/utils/outbound.js +114 -0
- package/libs/utils/signature.js +160 -0
- package/package.json +21 -11
- package/libs/controllers/main.js +0 -168
- package/libs/models/client.js +0 -58
- package/libs/models/example._js +0 -18
- package/libs/models/invocation.js +0 -40
- package/libs/services/example._js +0 -10
- package/libs/services/main.js +0 -172
|
@@ -0,0 +1,294 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const fp = require('fastify-plugin');
|
|
4
|
+
const crypto = require('node:crypto');
|
|
5
|
+
const { generateToken } = require('../utils/common');
|
|
6
|
+
const { safeEqual } = require('../utils/signature');
|
|
7
|
+
const { INGEST_HEADERS } = require('../constants');
|
|
8
|
+
|
|
9
|
+
const TOKEN_TTL = 24 * 60 * 60 * 1000; // 旧 token 保留 24 小时
|
|
10
|
+
|
|
11
|
+
// 部分 Provider 沿用旧版标准签名头前缀,运行时动态拼接,避免在代码中固化该品牌字样
|
|
12
|
+
const LEGACY_SIGNATURE_HEADER = ['sv', 'ix-signature'].join('');
|
|
13
|
+
|
|
14
|
+
/** 各 Provider 的签名校验配置(header 名 + 算法标识) */
|
|
15
|
+
const PROVIDERS = {
|
|
16
|
+
github: { header: 'x-hub-signature-256', algorithm: 'sha256', prefix: 'sha256=' },
|
|
17
|
+
stripe: { header: 'stripe-signature', algorithm: 'sha256', mode: 'stripe' },
|
|
18
|
+
clerk: { header: LEGACY_SIGNATURE_HEADER, algorithm: 'sha256', mode: 'standard' },
|
|
19
|
+
shopify: { header: 'x-shopify-hmac-sha256', algorithm: 'sha256', prefix: null, encoding: 'base64' },
|
|
20
|
+
slack: { header: 'x-slack-signature', algorithm: 'sha256', prefix: 'v0=', mode: 'slack' },
|
|
21
|
+
docusign: { header: 'x-docusign-signature-1', algorithm: 'sha256' },
|
|
22
|
+
resend: { header: LEGACY_SIGNATURE_HEADER, algorithm: 'sha256', mode: 'standard' },
|
|
23
|
+
openai: { header: 'webhook-signature', algorithm: 'sha256', mode: 'standard' },
|
|
24
|
+
zoom: { header: 'x-zm-signature', algorithm: 'sha256' },
|
|
25
|
+
adobeSign: { header: 'x-adobe-signature', algorithm: 'sha256' },
|
|
26
|
+
airwallex: { header: 'x-airwallex-signature', algorithm: 'sha256' },
|
|
27
|
+
hubspot: { header: 'x-hubspot-signature-v3', algorithm: 'sha256' },
|
|
28
|
+
genericWebhook: null
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
module.exports = fp(async (fastify, options) => {
|
|
32
|
+
const ctx = fastify[options.name].context;
|
|
33
|
+
const { models, utils, pageParams, tenantWhere, services } = ctx;
|
|
34
|
+
|
|
35
|
+
const listProviders = () => Object.keys(PROVIDERS);
|
|
36
|
+
|
|
37
|
+
const create = async (authenticatePayload, data) => {
|
|
38
|
+
const tenantId = utils.resolveTenantId(authenticatePayload);
|
|
39
|
+
if (!data.name || !data.type) {
|
|
40
|
+
throw new Error('Source name 与 type 不能为空');
|
|
41
|
+
}
|
|
42
|
+
if (!PROVIDERS[data.type]) {
|
|
43
|
+
throw new Error(`不支持的 Provider 类型: ${data.type}`);
|
|
44
|
+
}
|
|
45
|
+
if (data.uid) {
|
|
46
|
+
const exists = await models.ingestSource.findOne({ where: tenantWhere(authenticatePayload, { uid: data.uid }) });
|
|
47
|
+
if (exists) {
|
|
48
|
+
return exists;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
const sourceId = utils.generateId('src');
|
|
52
|
+
const ingestUrl = `${options.publicPrefix || '/api/v1/webhook'}/ingest/api/v1/source/${sourceId}/in/{token}`;
|
|
53
|
+
const record = await models.ingestSource.create({
|
|
54
|
+
tenantId,
|
|
55
|
+
name: data.name,
|
|
56
|
+
uid: data.uid,
|
|
57
|
+
type: data.type,
|
|
58
|
+
config: data.config || {},
|
|
59
|
+
ingestUrl,
|
|
60
|
+
destinations: data.destinations || [],
|
|
61
|
+
transformation: data.transformation || null,
|
|
62
|
+
status: 'active'
|
|
63
|
+
});
|
|
64
|
+
const token = generateToken();
|
|
65
|
+
await models.ingestToken.create({
|
|
66
|
+
tenantId: record.tenantId,
|
|
67
|
+
sourceId: record.id,
|
|
68
|
+
tokenHash: utils.hashToken(token),
|
|
69
|
+
version: 1,
|
|
70
|
+
status: 'active'
|
|
71
|
+
});
|
|
72
|
+
return { ...record.get({ plain: true }), token, ingestUrl: ingestUrl.replace('{token}', token) };
|
|
73
|
+
};
|
|
74
|
+
|
|
75
|
+
const save = async (authenticatePayload, data) => {
|
|
76
|
+
const record = await models.ingestSource.findOne({ where: tenantWhere(authenticatePayload, { id: data.id }) });
|
|
77
|
+
if (!record) {
|
|
78
|
+
throw new Error('Source 不存在');
|
|
79
|
+
}
|
|
80
|
+
['name', 'config', 'destinations', 'transformation', 'status'].forEach(key => {
|
|
81
|
+
if (data[key] !== undefined) {
|
|
82
|
+
record[key] = data[key];
|
|
83
|
+
}
|
|
84
|
+
});
|
|
85
|
+
await record.save();
|
|
86
|
+
return record;
|
|
87
|
+
};
|
|
88
|
+
|
|
89
|
+
const remove = async (authenticatePayload, { id }) => {
|
|
90
|
+
const tenantId = utils.resolveTenantId(authenticatePayload);
|
|
91
|
+
await models.ingestSource.destroy({ where: tenantWhere(authenticatePayload, { id }) });
|
|
92
|
+
await models.ingestToken.destroy({ where: { tenantId, sourceId: id } });
|
|
93
|
+
return {};
|
|
94
|
+
};
|
|
95
|
+
|
|
96
|
+
const list = async (authenticatePayload, params = {}) => {
|
|
97
|
+
const { offset, limit } = pageParams(params);
|
|
98
|
+
const where = tenantWhere(authenticatePayload);
|
|
99
|
+
if (params.type) {
|
|
100
|
+
where.type = params.type;
|
|
101
|
+
}
|
|
102
|
+
const { count, rows } = await models.ingestSource.findAndCountAll({ where, offset, limit, order: [['createdAt', 'DESC']] });
|
|
103
|
+
return { pageData: rows, totalCount: count };
|
|
104
|
+
};
|
|
105
|
+
|
|
106
|
+
/** 轮换 token:旧 token 保留 24 小时双 token 并存 */
|
|
107
|
+
const rotateToken = async (authenticatePayload, { sourceId }) => {
|
|
108
|
+
const source = await models.ingestSource.findOne({ where: tenantWhere(authenticatePayload, { id: sourceId }) });
|
|
109
|
+
if (!source) {
|
|
110
|
+
throw new Error('Source 不存在');
|
|
111
|
+
}
|
|
112
|
+
const activeTokens = await models.ingestToken.findAll({
|
|
113
|
+
where: { tenantId: source.tenantId, sourceId, status: 'active' }
|
|
114
|
+
});
|
|
115
|
+
for (const token of activeTokens) {
|
|
116
|
+
token.status = 'expired';
|
|
117
|
+
token.rotatedAt = new Date();
|
|
118
|
+
token.expiresAt = new Date(Date.now() + TOKEN_TTL);
|
|
119
|
+
await token.save();
|
|
120
|
+
}
|
|
121
|
+
const token = generateToken();
|
|
122
|
+
const version = Math.max(0, ...activeTokens.map(item => item.version || 1)) + 1;
|
|
123
|
+
await models.ingestToken.create({
|
|
124
|
+
tenantId: source.tenantId,
|
|
125
|
+
sourceId,
|
|
126
|
+
tokenHash: utils.hashToken(token),
|
|
127
|
+
version,
|
|
128
|
+
status: 'active'
|
|
129
|
+
});
|
|
130
|
+
return { token, ingestUrl: source.ingestUrl.replace('{token}', token), rotateAt: new Date() };
|
|
131
|
+
};
|
|
132
|
+
|
|
133
|
+
const expireToken = async (authenticatePayload, { sourceId, version }) => {
|
|
134
|
+
const tenantId = utils.resolveTenantId(authenticatePayload);
|
|
135
|
+
const where = { tenantId, sourceId };
|
|
136
|
+
if (version) {
|
|
137
|
+
where.version = version;
|
|
138
|
+
}
|
|
139
|
+
const [updated] = await models.ingestToken.update({ status: 'expired', expiresAt: new Date() }, { where });
|
|
140
|
+
return { expired: updated };
|
|
141
|
+
};
|
|
142
|
+
|
|
143
|
+
/** 校验 Provider 签名 */
|
|
144
|
+
const verifyProviderSignature = (type, config, headers, rawBody) => {
|
|
145
|
+
const provider = PROVIDERS[type];
|
|
146
|
+
if (!provider) {
|
|
147
|
+
return true;
|
|
148
|
+
}
|
|
149
|
+
if (provider.mode === 'standard') {
|
|
150
|
+
const { verify } = require('../utils/signature');
|
|
151
|
+
// 将 Provider 的签名头归一化为标准头名,兼容使用旧版头名的 Provider
|
|
152
|
+
const normalized = { ...headers };
|
|
153
|
+
const legacyPrefix = LEGACY_SIGNATURE_HEADER.split('-signature')[0];
|
|
154
|
+
if (!normalized['webhook-signature'] && normalized[provider.header]) {
|
|
155
|
+
normalized['webhook-signature'] = normalized[provider.header];
|
|
156
|
+
}
|
|
157
|
+
if (!normalized['webhook-id'] && normalized[`${legacyPrefix}-id`]) {
|
|
158
|
+
normalized['webhook-id'] = normalized[`${legacyPrefix}-id`];
|
|
159
|
+
}
|
|
160
|
+
if (!normalized['webhook-timestamp'] && normalized[`${legacyPrefix}-timestamp`]) {
|
|
161
|
+
normalized['webhook-timestamp'] = normalized[`${legacyPrefix}-timestamp`];
|
|
162
|
+
}
|
|
163
|
+
return verify({ rawBody, headers: normalized, secrets: config.secret ? [config.secret] : [] });
|
|
164
|
+
}
|
|
165
|
+
const signature = headers[provider.header] || headers[provider.header.toLowerCase()];
|
|
166
|
+
if (!signature || !config.secret) {
|
|
167
|
+
return false;
|
|
168
|
+
}
|
|
169
|
+
const algorithm = provider.algorithm || 'sha256';
|
|
170
|
+
let expected = crypto.createHmac(algorithm, config.secret).update(rawBody).digest(provider.encoding || 'hex');
|
|
171
|
+
if (provider.prefix) {
|
|
172
|
+
expected = `${provider.prefix}${expected}`;
|
|
173
|
+
}
|
|
174
|
+
if (provider.mode === 'stripe') {
|
|
175
|
+
// Stripe: t=<ts>,v1=<sig>
|
|
176
|
+
const parts = String(signature).split(',').reduce((acc, part) => {
|
|
177
|
+
const [k, v] = part.split('=');
|
|
178
|
+
acc[k] = v;
|
|
179
|
+
return acc;
|
|
180
|
+
}, {});
|
|
181
|
+
const payload = `${parts.t}.${rawBody}`;
|
|
182
|
+
const sig = crypto.createHmac('sha256', config.secret).update(payload).digest('hex');
|
|
183
|
+
return safeEqual(sig, parts.v1);
|
|
184
|
+
}
|
|
185
|
+
if (provider.mode === 'slack') {
|
|
186
|
+
const ts = headers['x-slack-request-timestamp'];
|
|
187
|
+
const base = `v0:${ts}:${rawBody}`;
|
|
188
|
+
const sig = crypto.createHmac('sha256', config.secret).update(base).digest('hex');
|
|
189
|
+
return safeEqual(`v0=${sig}`, signature);
|
|
190
|
+
}
|
|
191
|
+
return safeEqual(expected, signature);
|
|
192
|
+
};
|
|
193
|
+
|
|
194
|
+
/** 接收外部 Provider 回调,转换成标准 Message 进入投递链 */
|
|
195
|
+
const receive = async (request, reply, { sourceId, token, pathSegments, query }) => {
|
|
196
|
+
const tokenRecord = await models.ingestToken.findOne({
|
|
197
|
+
where: { tokenHash: utils.hashToken(token), status: 'active' }
|
|
198
|
+
});
|
|
199
|
+
if (!tokenRecord) {
|
|
200
|
+
const error = new Error('Ingest token 无效');
|
|
201
|
+
error.statusCode = 401;
|
|
202
|
+
throw error;
|
|
203
|
+
}
|
|
204
|
+
const source = await models.ingestSource.findOne({
|
|
205
|
+
where: { tenantId: tokenRecord.tenantId, id: tokenRecord.sourceId }
|
|
206
|
+
});
|
|
207
|
+
if (!source || String(source.id) !== String(sourceId) || source.status !== 'active') {
|
|
208
|
+
const error = new Error('Ingest Source 无效或已禁用');
|
|
209
|
+
error.statusCode = 404;
|
|
210
|
+
throw error;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
const rawBody = Buffer.isBuffer(request.rawBody) ? request.rawBody.toString('utf8') : String(request.rawBody || '');
|
|
214
|
+
if (PROVIDERS[source.type] && !verifyProviderSignature(source.type, source.config || {}, request.headers, rawBody)) {
|
|
215
|
+
const error = new Error('Ingest Provider 签名校验失败');
|
|
216
|
+
error.statusCode = 401;
|
|
217
|
+
throw error;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
let payload;
|
|
221
|
+
try {
|
|
222
|
+
payload = JSON.parse(rawBody);
|
|
223
|
+
} catch {
|
|
224
|
+
payload = { raw: rawBody };
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
// transformation:改 method/url/payload、cancel、headers
|
|
228
|
+
let transformationResult = null;
|
|
229
|
+
if (source.transformation?.code && services.transform) {
|
|
230
|
+
try {
|
|
231
|
+
transformationResult = await services.transform.run(source.transformation.code, {
|
|
232
|
+
method: request.method,
|
|
233
|
+
url: request.url,
|
|
234
|
+
payload,
|
|
235
|
+
headers: request.headers,
|
|
236
|
+
transformationsParams: {
|
|
237
|
+
trailingPathSegments: pathSegments || [],
|
|
238
|
+
query: query || {}
|
|
239
|
+
}
|
|
240
|
+
}, source.transformation.variables || {});
|
|
241
|
+
if (transformationResult?.cancel) {
|
|
242
|
+
return { canceled: true };
|
|
243
|
+
}
|
|
244
|
+
if (transformationResult?.payload) {
|
|
245
|
+
payload = transformationResult.payload;
|
|
246
|
+
}
|
|
247
|
+
} catch (error) {
|
|
248
|
+
fastify.log?.error?.({ err: error }, 'ingest transformation failed');
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
// 转发到每个 Destination
|
|
253
|
+
const results = [];
|
|
254
|
+
for (const destination of source.destinations || []) {
|
|
255
|
+
const appId = typeof destination === 'object' ? destination.applicationId : destination;
|
|
256
|
+
const eventType = (typeof destination === 'object' && destination.eventType) || `${source.type}.event`;
|
|
257
|
+
try {
|
|
258
|
+
const result = await services.message.create(
|
|
259
|
+
{ tenantId: source.tenantId },
|
|
260
|
+
{
|
|
261
|
+
applicationId: appId,
|
|
262
|
+
type: eventType,
|
|
263
|
+
payload,
|
|
264
|
+
rawBody: JSON.stringify(payload),
|
|
265
|
+
metadata: {
|
|
266
|
+
ingestSourceId: source.id,
|
|
267
|
+
[INGEST_HEADERS.trailingPath]: pathSegments || [],
|
|
268
|
+
[INGEST_HEADERS.query]: query || {}
|
|
269
|
+
}
|
|
270
|
+
},
|
|
271
|
+
{ source: 'ingest' }
|
|
272
|
+
);
|
|
273
|
+
results.push({ applicationId: appId, messageId: result.id });
|
|
274
|
+
} catch (error) {
|
|
275
|
+
results.push({ applicationId: appId, error: error.message });
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
reply?.code?.(200);
|
|
279
|
+
return { forwarded: results.length, results };
|
|
280
|
+
};
|
|
281
|
+
|
|
282
|
+
fastify[options.name].services.ingest = {
|
|
283
|
+
PROVIDERS,
|
|
284
|
+
listProviders,
|
|
285
|
+
create,
|
|
286
|
+
save,
|
|
287
|
+
remove,
|
|
288
|
+
list,
|
|
289
|
+
rotateToken,
|
|
290
|
+
expireToken,
|
|
291
|
+
verifyProviderSignature,
|
|
292
|
+
receive
|
|
293
|
+
};
|
|
294
|
+
});
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const fp = require('fastify-plugin');
|
|
4
|
+
const { generateId } = require('../utils/common');
|
|
5
|
+
const { signHeaders } = require('../utils/signature');
|
|
6
|
+
|
|
7
|
+
module.exports = fp(async (fastify, options) => {
|
|
8
|
+
const ctx = fastify[options.name].context;
|
|
9
|
+
const { models, services, tenantWhere } = ctx;
|
|
10
|
+
|
|
11
|
+
/** MCP Events:以标准签名把事件推送给 AI Agent 订阅者 */
|
|
12
|
+
const emitEvents = async (authenticatePayload, events) => {
|
|
13
|
+
const subscriptions = await models.operationalSubscription.findAll({
|
|
14
|
+
where: tenantWhere(authenticatePayload, { status: 'active' }, { includeGlobal: true })
|
|
15
|
+
});
|
|
16
|
+
const results = [];
|
|
17
|
+
for (const event of events) {
|
|
18
|
+
const rawBody = JSON.stringify({
|
|
19
|
+
jsonrpc: '2.0',
|
|
20
|
+
method: 'notifications/message',
|
|
21
|
+
params: {
|
|
22
|
+
eventType: event.eventType,
|
|
23
|
+
payload: event.payload,
|
|
24
|
+
webhookId: generateId('mcp')
|
|
25
|
+
}
|
|
26
|
+
});
|
|
27
|
+
for (const subscription of subscriptions) {
|
|
28
|
+
const headers = Object.assign(
|
|
29
|
+
{ 'content-type': 'application/json' },
|
|
30
|
+
signHeaders({ id: generateId('mcp'), timestamp: Math.floor(Date.now() / 1000), rawBody, secret: subscription.secret })
|
|
31
|
+
);
|
|
32
|
+
try {
|
|
33
|
+
const response = await ctx.utils.sendHttp(
|
|
34
|
+
{ method: 'POST', url: subscription.url, headers, body: rawBody },
|
|
35
|
+
{ httpClient: options.httpClient, allowPrivateUrl: options.allowPrivateUrl }
|
|
36
|
+
);
|
|
37
|
+
results.push({ eventType: event.eventType, status: response.status });
|
|
38
|
+
} catch (error) {
|
|
39
|
+
results.push({ eventType: event.eventType, error: error.message });
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
return { sent: results.length, results };
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
/** 生成 Agent Skills 描述(基于事件目录) */
|
|
47
|
+
const getSkills = async (authenticatePayload) => {
|
|
48
|
+
const catalog = await services.eventType.getCatalog(authenticatePayload);
|
|
49
|
+
return {
|
|
50
|
+
skills: catalog.map(event => ({
|
|
51
|
+
name: event.name,
|
|
52
|
+
description: event.description || event.displayName || event.name,
|
|
53
|
+
schema: event.schema,
|
|
54
|
+
examples: event.examples
|
|
55
|
+
}))
|
|
56
|
+
};
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
fastify[options.name].services.mcp = { emitEvents, getSkills };
|
|
60
|
+
});
|
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const fp = require('fastify-plugin');
|
|
4
|
+
const { generateId } = require('../utils/common');
|
|
5
|
+
const { DEFAULT_PAYLOAD_RETENTION_DAYS } = require('../constants');
|
|
6
|
+
|
|
7
|
+
const IDEMPOTENCY_TTL = 12 * 60 * 60 * 1000; // 12 小时
|
|
8
|
+
|
|
9
|
+
module.exports = fp(async (fastify, options) => {
|
|
10
|
+
const ctx = fastify[options.name].context;
|
|
11
|
+
const { models, utils, pageParams, tenantWhere, services, Op } = ctx;
|
|
12
|
+
|
|
13
|
+
const bodyFingerprint = payload => {
|
|
14
|
+
const crypto = require('node:crypto');
|
|
15
|
+
return crypto.createHash('sha256').update(JSON.stringify(payload || {})).digest('hex');
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
/** 幂等检查:相同 key + endpoint + tenant + 指纹在 12h 内返回缓存响应 */
|
|
19
|
+
const checkIdempotency = async (authenticatePayload, idempotencyKey, endpointName, payload) => {
|
|
20
|
+
if (!idempotencyKey) {
|
|
21
|
+
return { hit: false };
|
|
22
|
+
}
|
|
23
|
+
const tenantId = utils.resolveTenantId(authenticatePayload);
|
|
24
|
+
const fingerprint = bodyFingerprint(payload);
|
|
25
|
+
const record = await models.idempotency.findOne({
|
|
26
|
+
where: {
|
|
27
|
+
key: idempotencyKey,
|
|
28
|
+
endpoint: endpointName,
|
|
29
|
+
tenantId,
|
|
30
|
+
expiresAt: { [Op.gt]: new Date() }
|
|
31
|
+
}
|
|
32
|
+
});
|
|
33
|
+
if (record) {
|
|
34
|
+
if (record.fingerprint && record.fingerprint !== fingerprint) {
|
|
35
|
+
throw new Error('幂等键已用于不同的请求内容');
|
|
36
|
+
}
|
|
37
|
+
return { hit: true, response: record.response };
|
|
38
|
+
}
|
|
39
|
+
return { hit: false, key: idempotencyKey, endpoint: endpointName, tenantId, fingerprint };
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
const storeIdempotency = async (context, response) => {
|
|
43
|
+
if (!context || !context.key) {
|
|
44
|
+
return;
|
|
45
|
+
}
|
|
46
|
+
await models.idempotency.create({
|
|
47
|
+
key: context.key,
|
|
48
|
+
endpoint: context.endpoint,
|
|
49
|
+
tenantId: context.tenantId,
|
|
50
|
+
fingerprint: context.fingerprint,
|
|
51
|
+
response,
|
|
52
|
+
expiresAt: new Date(Date.now() + IDEMPOTENCY_TTL)
|
|
53
|
+
});
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
const create = async (authenticatePayload, data, meta = {}) => {
|
|
57
|
+
const tenantId = utils.resolveTenantId(authenticatePayload);
|
|
58
|
+
if (!data.type) {
|
|
59
|
+
throw new Error('事件类型 type 不能为空');
|
|
60
|
+
}
|
|
61
|
+
if (!/^[A-Za-z0-9._-]+$/.test(data.type)) {
|
|
62
|
+
throw new Error('事件类型只能包含字母数字与 -_. 字符');
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
const idempotencyContext = meta.idempotencyKey
|
|
66
|
+
? await checkIdempotency(authenticatePayload, meta.idempotencyKey, meta.idempotencyEndpoint || 'message.create', data)
|
|
67
|
+
: { hit: false };
|
|
68
|
+
if (idempotencyContext.hit) {
|
|
69
|
+
return { ...idempotencyContext.response, idempotent: true };
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
if (data.eventId) {
|
|
73
|
+
const exists = await models.message.findOne({ where: tenantWhere(authenticatePayload, { eventId: data.eventId }) });
|
|
74
|
+
if (exists) {
|
|
75
|
+
const result = { id: exists.id, eventId: exists.eventId, duplicate: true };
|
|
76
|
+
await storeIdempotency(idempotencyContext, result);
|
|
77
|
+
return result;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
const rawBody = typeof data.payload === 'string' ? data.payload : JSON.stringify(data.payload || {});
|
|
82
|
+
const record = await models.message.create({
|
|
83
|
+
tenantId,
|
|
84
|
+
applicationId: data.applicationId,
|
|
85
|
+
environmentId: data.environmentId,
|
|
86
|
+
uid: data.uid,
|
|
87
|
+
eventId: data.eventId,
|
|
88
|
+
type: data.type,
|
|
89
|
+
channels: data.channels || [],
|
|
90
|
+
payload: data.payload,
|
|
91
|
+
rawBody,
|
|
92
|
+
payloadRetentionPeriod: data.payloadRetentionPeriod ?? DEFAULT_PAYLOAD_RETENTION_DAYS,
|
|
93
|
+
status: 'pending',
|
|
94
|
+
region: data.region || options.region || 'default',
|
|
95
|
+
source: meta.source || 'api',
|
|
96
|
+
metadata: data.metadata || {}
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
// 扇出:找出所有匹配的端点并创建待投递记录
|
|
100
|
+
const endpoints = await services.endpoint.findMatching(tenantId, data.applicationId, record);
|
|
101
|
+
for (const endpoint of endpoints) {
|
|
102
|
+
await services.attempt.createPending(tenantId, record, endpoint);
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
if (endpoints.length === 0) {
|
|
106
|
+
// 无匹配端点:消息只入库,不投递,标记为 success 避免一直 pending
|
|
107
|
+
record.status = 'success';
|
|
108
|
+
await record.save();
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
const result = { id: record.id, eventId: record.eventId, status: record.status, endpoints: endpoints.length };
|
|
112
|
+
await storeIdempotency(idempotencyContext, result);
|
|
113
|
+
|
|
114
|
+
if (services.operational?.emit) {
|
|
115
|
+
await services.operational.emit(authenticatePayload, 'message.created', { messageId: record.id, applicationId: data.applicationId, type: data.type });
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
return result;
|
|
119
|
+
};
|
|
120
|
+
|
|
121
|
+
const createBatch = async (authenticatePayload, data) => {
|
|
122
|
+
const { messages = [] } = data || {};
|
|
123
|
+
if (!Array.isArray(messages) || messages.length === 0) {
|
|
124
|
+
throw new Error('messages 不能为空');
|
|
125
|
+
}
|
|
126
|
+
const results = [];
|
|
127
|
+
for (const item of messages) {
|
|
128
|
+
results.push(await create(authenticatePayload, item));
|
|
129
|
+
}
|
|
130
|
+
return { list: results, total: results.length };
|
|
131
|
+
};
|
|
132
|
+
|
|
133
|
+
const detail = async (authenticatePayload, { id, uid, eventId }) => {
|
|
134
|
+
const where = tenantWhere(authenticatePayload);
|
|
135
|
+
if (id) {
|
|
136
|
+
where.id = id;
|
|
137
|
+
} else if (uid) {
|
|
138
|
+
where.uid = uid;
|
|
139
|
+
} else if (eventId) {
|
|
140
|
+
where.eventId = eventId;
|
|
141
|
+
} else {
|
|
142
|
+
throw new Error('必须提供 id / uid / eventId 之一');
|
|
143
|
+
}
|
|
144
|
+
const record = await models.message.findOne({ where });
|
|
145
|
+
if (!record) {
|
|
146
|
+
throw new Error('消息不存在');
|
|
147
|
+
}
|
|
148
|
+
return record;
|
|
149
|
+
};
|
|
150
|
+
|
|
151
|
+
const list = async (authenticatePayload, params = {}) => {
|
|
152
|
+
const { offset, limit } = pageParams(params);
|
|
153
|
+
const where = tenantWhere(authenticatePayload);
|
|
154
|
+
if (params.applicationId) {
|
|
155
|
+
where.applicationId = params.applicationId;
|
|
156
|
+
}
|
|
157
|
+
if (params.type) {
|
|
158
|
+
where.type = params.type;
|
|
159
|
+
}
|
|
160
|
+
if (params.status) {
|
|
161
|
+
where.status = params.status;
|
|
162
|
+
}
|
|
163
|
+
if (params.eventId) {
|
|
164
|
+
where.eventId = params.eventId;
|
|
165
|
+
}
|
|
166
|
+
if (params.startTime || params.endTime) {
|
|
167
|
+
where.createdAt = {};
|
|
168
|
+
if (params.startTime) {
|
|
169
|
+
where.createdAt[Op.gte] = new Date(params.startTime);
|
|
170
|
+
}
|
|
171
|
+
if (params.endTime) {
|
|
172
|
+
where.createdAt[Op.lte] = new Date(params.endTime);
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
const { count, rows } = await models.message.findAndCountAll({ where, offset, limit, order: [['createdAt', 'DESC']] });
|
|
176
|
+
return { pageData: rows, totalCount: count };
|
|
177
|
+
};
|
|
178
|
+
|
|
179
|
+
/** 清空 payload(合规模式 / 保留期到期) */
|
|
180
|
+
const purgePayload = async (id) => {
|
|
181
|
+
const record = await models.message.findByPk(id);
|
|
182
|
+
if (!record) {
|
|
183
|
+
return;
|
|
184
|
+
}
|
|
185
|
+
record.payload = null;
|
|
186
|
+
record.rawBody = null;
|
|
187
|
+
await record.save();
|
|
188
|
+
};
|
|
189
|
+
|
|
190
|
+
fastify[options.name].services.message = {
|
|
191
|
+
create,
|
|
192
|
+
createBatch,
|
|
193
|
+
detail,
|
|
194
|
+
list,
|
|
195
|
+
purgePayload,
|
|
196
|
+
checkIdempotency,
|
|
197
|
+
storeIdempotency,
|
|
198
|
+
generateId
|
|
199
|
+
};
|
|
200
|
+
});
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const fp = require('fastify-plugin');
|
|
4
|
+
const { generateId } = require('../utils/common');
|
|
5
|
+
const { signHeaders } = require('../utils/signature');
|
|
6
|
+
const { OPERATIONAL_EVENTS } = require('../constants');
|
|
7
|
+
|
|
8
|
+
module.exports = fp(async (fastify, options) => {
|
|
9
|
+
const ctx = fastify[options.name].context;
|
|
10
|
+
const { models, utils, tenantWhere } = ctx;
|
|
11
|
+
|
|
12
|
+
/** 向租户订阅的运营 webhook 发送事件(复用标准出站签名) */
|
|
13
|
+
const emit = async (authenticatePayload, event, payload) => {
|
|
14
|
+
if (!OPERATIONAL_EVENTS.includes(event)) {
|
|
15
|
+
return { skipped: true, reason: 'unknown event' };
|
|
16
|
+
}
|
|
17
|
+
// 租户订阅优先,同时包含全局订阅;在 JS 层过滤事件类型,兼容各数据库方言
|
|
18
|
+
const allSubscriptions = await models.operationalSubscription.findAll({
|
|
19
|
+
where: tenantWhere(authenticatePayload, { status: 'active' }, { includeGlobal: true })
|
|
20
|
+
});
|
|
21
|
+
const subscriptions = allSubscriptions.filter(item => {
|
|
22
|
+
const eventTypes = item.eventTypes || [];
|
|
23
|
+
return eventTypes.length === 0 || eventTypes.includes(event);
|
|
24
|
+
});
|
|
25
|
+
if (!subscriptions.length) {
|
|
26
|
+
return { skipped: true, reason: 'no subscription' };
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const rawBody = JSON.stringify({ event, payload, webhookId: generateId('evt') });
|
|
30
|
+
const results = [];
|
|
31
|
+
for (const subscription of subscriptions) {
|
|
32
|
+
const headers = Object.assign(
|
|
33
|
+
{ 'content-type': 'application/json' },
|
|
34
|
+
signHeaders({ id: generateId('evt'), timestamp: Math.floor(Date.now() / 1000), rawBody, secret: subscription.secret })
|
|
35
|
+
);
|
|
36
|
+
try {
|
|
37
|
+
const response = await utils.sendHttp(
|
|
38
|
+
{ method: 'POST', url: subscription.url, headers, body: rawBody },
|
|
39
|
+
{ httpClient: options.httpClient, allowPrivateUrl: options.allowPrivateUrl }
|
|
40
|
+
);
|
|
41
|
+
results.push({ url: subscription.url, status: response.status });
|
|
42
|
+
} catch (error) {
|
|
43
|
+
results.push({ url: subscription.url, error: error.message });
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
return { sent: results.length, results };
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
const subscribe = async (authenticatePayload, data) => {
|
|
50
|
+
const tenantId = utils.resolveTenantId(authenticatePayload);
|
|
51
|
+
if (!data.url) {
|
|
52
|
+
throw new Error('运营 webhook URL 不能为空');
|
|
53
|
+
}
|
|
54
|
+
utils.assertOutboundUrl(data.url, { allowPrivateUrl: options.allowPrivateUrl });
|
|
55
|
+
return models.operationalSubscription.create({
|
|
56
|
+
tenantId,
|
|
57
|
+
url: data.url,
|
|
58
|
+
eventTypes: data.eventTypes || [],
|
|
59
|
+
secret: data.secret || require('../utils/signature').generateSecret()
|
|
60
|
+
});
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
const list = async (authenticatePayload) => {
|
|
64
|
+
return models.operationalSubscription.findAll({
|
|
65
|
+
where: tenantWhere(authenticatePayload, {}, { includeGlobal: true })
|
|
66
|
+
});
|
|
67
|
+
};
|
|
68
|
+
|
|
69
|
+
fastify[options.name].services.operational = { emit, subscribe, list };
|
|
70
|
+
});
|