@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,236 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const fp = require('fastify-plugin');
|
|
4
|
+
const { generateSecret } = require('../utils/signature');
|
|
5
|
+
const { generateToken } = require('../utils/common');
|
|
6
|
+
|
|
7
|
+
module.exports = fp(async (fastify, options) => {
|
|
8
|
+
const ctx = fastify[options.name].context;
|
|
9
|
+
const { models, utils, pageParams, tenantWhere, services, Op } = ctx;
|
|
10
|
+
|
|
11
|
+
const maskSecret = secret => (secret ? `${secret.slice(0, 9)}***` : secret);
|
|
12
|
+
|
|
13
|
+
const decorate = record => {
|
|
14
|
+
if (!record) {
|
|
15
|
+
return record;
|
|
16
|
+
}
|
|
17
|
+
const plain = record.get ? record.get({ plain: true }) : { ...record };
|
|
18
|
+
plain.secret = maskSecret(plain.secret);
|
|
19
|
+
return plain;
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
const create = async (authenticatePayload, data) => {
|
|
23
|
+
const payload = { ...data, tenantId: utils.resolveTenantId(authenticatePayload) };
|
|
24
|
+
if (!payload.applicationId) {
|
|
25
|
+
throw new Error('缺少应用 ID');
|
|
26
|
+
}
|
|
27
|
+
if (!payload.url && payload.kind !== 'polling' && payload.kind !== 'sink') {
|
|
28
|
+
throw new Error('端点 URL 不能为空');
|
|
29
|
+
}
|
|
30
|
+
if (payload.url && !options.allowPrivateUrl && utils.isPrivateUrl(payload.url)) {
|
|
31
|
+
throw new Error('不允许使用私网地址作为端点 URL');
|
|
32
|
+
}
|
|
33
|
+
if (!payload.secret) {
|
|
34
|
+
payload.secret = generateSecret();
|
|
35
|
+
}
|
|
36
|
+
if (payload.uid) {
|
|
37
|
+
const exists = await models.endpoint.findOne({ where: tenantWhere(authenticatePayload, { uid: payload.uid }) });
|
|
38
|
+
if (exists) {
|
|
39
|
+
return decorate(exists);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
const record = await models.endpoint.create(payload);
|
|
43
|
+
if (record.kind === 'polling') {
|
|
44
|
+
await models.pollingEndpoint.create({
|
|
45
|
+
tenantId: payload.tenantId,
|
|
46
|
+
endpointId: record.id,
|
|
47
|
+
tokenHash: utils.hashToken(generateToken()),
|
|
48
|
+
apiKeyHash: utils.hashToken(generateToken())
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
return decorate(record);
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
const save = async (authenticatePayload, data) => {
|
|
55
|
+
if (!data.id) {
|
|
56
|
+
throw new Error('缺少端点 ID');
|
|
57
|
+
}
|
|
58
|
+
const record = await models.endpoint.findOne({ where: tenantWhere(authenticatePayload, { id: data.id }) });
|
|
59
|
+
if (!record) {
|
|
60
|
+
throw new Error('端点不存在');
|
|
61
|
+
}
|
|
62
|
+
const allowed = [
|
|
63
|
+
'name', 'url', 'direction', 'type', 'kind', 'eventTypes', 'channels', 'headers',
|
|
64
|
+
'throttleRate', 'status', 'rate', 'expireAt', 'options', 'description', 'metadata'
|
|
65
|
+
];
|
|
66
|
+
allowed.forEach(key => {
|
|
67
|
+
if (data[key] !== undefined) {
|
|
68
|
+
record[key] = data[key];
|
|
69
|
+
}
|
|
70
|
+
});
|
|
71
|
+
if (data.url && !options.allowPrivateUrl && utils.isPrivateUrl(data.url)) {
|
|
72
|
+
throw new Error('不允许使用私网地址作为端点 URL');
|
|
73
|
+
}
|
|
74
|
+
await record.save();
|
|
75
|
+
return decorate(record);
|
|
76
|
+
};
|
|
77
|
+
|
|
78
|
+
/** 轮换签名密钥,返回明文密钥(仅此一次) */
|
|
79
|
+
const rotateSecret = async (authenticatePayload, { id }) => {
|
|
80
|
+
const record = await models.endpoint.findOne({ where: tenantWhere(authenticatePayload, { id }) });
|
|
81
|
+
if (!record) {
|
|
82
|
+
throw new Error('端点不存在');
|
|
83
|
+
}
|
|
84
|
+
const secret = generateSecret();
|
|
85
|
+
record.secret = secret;
|
|
86
|
+
record.version = (record.version || 1) + 1;
|
|
87
|
+
await record.save();
|
|
88
|
+
return { secret };
|
|
89
|
+
};
|
|
90
|
+
|
|
91
|
+
const setStatus = async (authenticatePayload, { id, status, reason }) => {
|
|
92
|
+
const record = await models.endpoint.findOne({ where: tenantWhere(authenticatePayload, { id }) });
|
|
93
|
+
if (!record) {
|
|
94
|
+
throw new Error('端点不存在');
|
|
95
|
+
}
|
|
96
|
+
record.status = status;
|
|
97
|
+
if (status === 'active') {
|
|
98
|
+
record.disabledReason = null;
|
|
99
|
+
record.failureCount = 0;
|
|
100
|
+
record.firstFailureAt = null;
|
|
101
|
+
record.lastFailureAt = null;
|
|
102
|
+
if (services.operational?.emit) {
|
|
103
|
+
await services.operational.emit(authenticatePayload, 'endpoint.enabled', { endpointId: id });
|
|
104
|
+
}
|
|
105
|
+
} else {
|
|
106
|
+
record.disabledReason = reason || null;
|
|
107
|
+
}
|
|
108
|
+
await record.save();
|
|
109
|
+
return decorate(record);
|
|
110
|
+
};
|
|
111
|
+
|
|
112
|
+
const remove = async (authenticatePayload, { id }) => {
|
|
113
|
+
await models.endpoint.destroy({ where: tenantWhere(authenticatePayload, { id }) });
|
|
114
|
+
await models.transformation.destroy({ where: tenantWhere(authenticatePayload, { endpointId: id }) });
|
|
115
|
+
await models.pollingEndpoint.destroy({ where: tenantWhere(authenticatePayload, { endpointId: id }) });
|
|
116
|
+
await models.pollingConsumer.destroy({ where: tenantWhere(authenticatePayload, { endpointId: id }) });
|
|
117
|
+
return {};
|
|
118
|
+
};
|
|
119
|
+
|
|
120
|
+
const detail = async (authenticatePayload, { id, uid }) => {
|
|
121
|
+
const where = tenantWhere(authenticatePayload);
|
|
122
|
+
if (id) {
|
|
123
|
+
where.id = id;
|
|
124
|
+
} else if (uid) {
|
|
125
|
+
where.uid = uid;
|
|
126
|
+
} else {
|
|
127
|
+
throw new Error('必须提供 id 或 uid');
|
|
128
|
+
}
|
|
129
|
+
const record = await models.endpoint.findOne({ where });
|
|
130
|
+
return decorate(record);
|
|
131
|
+
};
|
|
132
|
+
|
|
133
|
+
const list = async (authenticatePayload, params = {}) => {
|
|
134
|
+
const { offset, limit } = pageParams(params);
|
|
135
|
+
const where = tenantWhere(authenticatePayload);
|
|
136
|
+
if (params.applicationId) {
|
|
137
|
+
where.applicationId = params.applicationId;
|
|
138
|
+
}
|
|
139
|
+
if (params.status) {
|
|
140
|
+
where.status = params.status;
|
|
141
|
+
}
|
|
142
|
+
if (params.kind) {
|
|
143
|
+
where.kind = params.kind;
|
|
144
|
+
}
|
|
145
|
+
if (params.direction) {
|
|
146
|
+
where.direction = params.direction;
|
|
147
|
+
}
|
|
148
|
+
if (params.name) {
|
|
149
|
+
where.name = { [Op.like]: `%${params.name}%` };
|
|
150
|
+
}
|
|
151
|
+
const { count, rows } = await models.endpoint.findAndCountAll({ where, offset, limit, order: [['createdAt', 'DESC']] });
|
|
152
|
+
return { pageData: rows.map(decorate), totalCount: count };
|
|
153
|
+
};
|
|
154
|
+
|
|
155
|
+
/** 找出匹配某条消息的所有活跃出站端点 */
|
|
156
|
+
const findMatching = async (tenantId, applicationId, message) => {
|
|
157
|
+
const endpoints = await models.endpoint.findAll({
|
|
158
|
+
where: {
|
|
159
|
+
tenantId,
|
|
160
|
+
applicationId,
|
|
161
|
+
direction: 'outbound',
|
|
162
|
+
status: 'active',
|
|
163
|
+
kind: { [Op.in]: ['http', 'fifo'] }
|
|
164
|
+
}
|
|
165
|
+
});
|
|
166
|
+
return endpoints.filter(endpoint => utils.endpointMatches(endpoint, message));
|
|
167
|
+
};
|
|
168
|
+
|
|
169
|
+
/** 记录一次投递失败,判断是否达到自动禁用条件 */
|
|
170
|
+
const recordFailure = async (tenantId, endpointId, environment) => {
|
|
171
|
+
const settings = environment?.settings || {};
|
|
172
|
+
if (settings.autoDisable === false) {
|
|
173
|
+
return false;
|
|
174
|
+
}
|
|
175
|
+
const record = await models.endpoint.findOne({ where: { tenantId, id: endpointId } });
|
|
176
|
+
if (!record || record.status !== 'active') {
|
|
177
|
+
return false;
|
|
178
|
+
}
|
|
179
|
+
const now = new Date();
|
|
180
|
+
const first = record.firstFailureAt ? new Date(record.firstFailureAt) : now;
|
|
181
|
+
const failureCount = (record.failureCount || 0) + 1;
|
|
182
|
+
const withinFiveDays = now.getTime() - first.getTime() <= 5 * 24 * 60 * 60 * 1000;
|
|
183
|
+
const within24hMultiple = failureCount >= 2 && now.getTime() - first.getTime() <= 24 * 60 * 60 * 1000;
|
|
184
|
+
const spanOver12h = now.getTime() - first.getTime() >= 12 * 60 * 60 * 1000;
|
|
185
|
+
|
|
186
|
+
if (!record.firstFailureAt) {
|
|
187
|
+
record.firstFailureAt = now;
|
|
188
|
+
}
|
|
189
|
+
record.lastFailureAt = now;
|
|
190
|
+
record.failureCount = failureCount;
|
|
191
|
+
await record.save();
|
|
192
|
+
|
|
193
|
+
if (withinFiveDays && within24hMultiple && spanOver12h) {
|
|
194
|
+
record.status = 'disabled';
|
|
195
|
+
record.disabledReason = '连续 5 天投递全部失败,自动禁用';
|
|
196
|
+
await record.save();
|
|
197
|
+
if (services.operational?.emit) {
|
|
198
|
+
await services.operational.emit({ tenantId }, 'endpoint.disabled', { endpointId, reason: record.disabledReason });
|
|
199
|
+
}
|
|
200
|
+
return true;
|
|
201
|
+
}
|
|
202
|
+
return false;
|
|
203
|
+
};
|
|
204
|
+
|
|
205
|
+
/** 重置失败计数(投递成功时) */
|
|
206
|
+
// 兼容旧调用 resetFailure(endpointId):旧签名按全局租户处理
|
|
207
|
+
const resetFailure = async (tenantIdOrEndpointId, endpointId) => {
|
|
208
|
+
const tenantId = endpointId === undefined ? '' : tenantIdOrEndpointId;
|
|
209
|
+
const id = endpointId === undefined ? tenantIdOrEndpointId : endpointId;
|
|
210
|
+
const record = endpointId === undefined
|
|
211
|
+
? await models.endpoint.findByPk(tenantIdOrEndpointId)
|
|
212
|
+
: await models.endpoint.findOne({ where: { tenantId, id } });
|
|
213
|
+
if (!record) {
|
|
214
|
+
return;
|
|
215
|
+
}
|
|
216
|
+
record.failureCount = 0;
|
|
217
|
+
record.firstFailureAt = null;
|
|
218
|
+
record.lastFailureAt = null;
|
|
219
|
+
await record.save();
|
|
220
|
+
};
|
|
221
|
+
|
|
222
|
+
fastify[options.name].services.endpoint = {
|
|
223
|
+
create,
|
|
224
|
+
save,
|
|
225
|
+
remove,
|
|
226
|
+
detail,
|
|
227
|
+
list,
|
|
228
|
+
setStatus,
|
|
229
|
+
rotateSecret,
|
|
230
|
+
findMatching,
|
|
231
|
+
recordFailure,
|
|
232
|
+
resetFailure,
|
|
233
|
+
decorate,
|
|
234
|
+
maskSecret
|
|
235
|
+
};
|
|
236
|
+
});
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const fp = require('fastify-plugin');
|
|
4
|
+
|
|
5
|
+
module.exports = fp(async (fastify, options) => {
|
|
6
|
+
const ctx = fastify[options.name].context;
|
|
7
|
+
const { models, utils, pageParams, tenantWhere, Op } = ctx;
|
|
8
|
+
|
|
9
|
+
const create = async (authenticatePayload, data) => {
|
|
10
|
+
if (!data.name) {
|
|
11
|
+
throw new Error('事件类型名称不能为空');
|
|
12
|
+
}
|
|
13
|
+
const tenantId = utils.resolveTenantId(authenticatePayload);
|
|
14
|
+
const where = tenantWhere(authenticatePayload, { name: data.name });
|
|
15
|
+
const existing = await models.eventType.findOne({ where });
|
|
16
|
+
if (existing) {
|
|
17
|
+
return existing;
|
|
18
|
+
}
|
|
19
|
+
return models.eventType.create({ ...data, tenantId, name: data.name });
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
const save = async (authenticatePayload, data) => {
|
|
23
|
+
if (!data.id) {
|
|
24
|
+
throw new Error('缺少事件类型 ID');
|
|
25
|
+
}
|
|
26
|
+
const record = await models.eventType.findOne({ where: tenantWhere(authenticatePayload, { id: data.id }) });
|
|
27
|
+
if (!record) {
|
|
28
|
+
throw new Error('事件类型不存在');
|
|
29
|
+
}
|
|
30
|
+
['displayName', 'description', 'descriptionTranslations', 'schema', 'examples', 'featureFlags', 'groupName', 'status'].forEach(key => {
|
|
31
|
+
if (data[key] !== undefined) {
|
|
32
|
+
record[key] = data[key];
|
|
33
|
+
}
|
|
34
|
+
});
|
|
35
|
+
await record.save();
|
|
36
|
+
return record;
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
const remove = async (authenticatePayload, { id }) => {
|
|
40
|
+
await models.eventType.destroy({ where: tenantWhere(authenticatePayload, { id }) });
|
|
41
|
+
return {};
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
const list = async (authenticatePayload, params = {}) => {
|
|
45
|
+
const { offset, limit } = pageParams(params);
|
|
46
|
+
const where = tenantWhere(authenticatePayload, {}, { includeGlobal: true });
|
|
47
|
+
if (params.name) {
|
|
48
|
+
where.name = { [Op.like]: `%${params.name}%` };
|
|
49
|
+
}
|
|
50
|
+
if (params.status) {
|
|
51
|
+
where.status = params.status;
|
|
52
|
+
}
|
|
53
|
+
const { count, rows } = await models.eventType.findAndCountAll({ where, offset, limit, order: [['name', 'ASC']] });
|
|
54
|
+
return { pageData: rows, totalCount: count };
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
/** 把全局事件目录复制到当前租户,供租户定制 */
|
|
58
|
+
const copyToTenant = async (authenticatePayload, { id } = {}) => {
|
|
59
|
+
if (!id) {
|
|
60
|
+
throw new Error('缺少事件类型 ID');
|
|
61
|
+
}
|
|
62
|
+
const tenantId = utils.resolveTenantId(authenticatePayload);
|
|
63
|
+
const source = await models.eventType.findOne({
|
|
64
|
+
where: tenantWhere(authenticatePayload, { id }, { includeGlobal: true })
|
|
65
|
+
});
|
|
66
|
+
if (!source) {
|
|
67
|
+
throw new Error('事件类型不存在');
|
|
68
|
+
}
|
|
69
|
+
const existing = await models.eventType.findOne({
|
|
70
|
+
where: tenantWhere(authenticatePayload, { name: source.name })
|
|
71
|
+
});
|
|
72
|
+
if (existing) {
|
|
73
|
+
return existing;
|
|
74
|
+
}
|
|
75
|
+
const plain = source.get ? source.get({ plain: true }) : { ...source };
|
|
76
|
+
const { id: ignoredId, tenantId: ignoredTenantId, createdAt, updatedAt, ...rest } = plain;
|
|
77
|
+
return models.eventType.create({ ...rest, tenantId, status: 'active' });
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
const getCatalog = async (authenticatePayload, { lang, featureFlags = [] } = {}) => {
|
|
81
|
+
const listResult = await list(authenticatePayload, { perPage: 500 });
|
|
82
|
+
const tenantId = utils.resolveTenantId(authenticatePayload);
|
|
83
|
+
const resolved = new Map();
|
|
84
|
+
listResult.pageData.forEach(item => {
|
|
85
|
+
const current = resolved.get(item.name);
|
|
86
|
+
if (!current || (item.tenantId === tenantId && current.tenantId !== tenantId)) {
|
|
87
|
+
resolved.set(item.name, item);
|
|
88
|
+
}
|
|
89
|
+
});
|
|
90
|
+
return [...resolved.values()]
|
|
91
|
+
.filter(item => item.status === 'active')
|
|
92
|
+
.filter(item => {
|
|
93
|
+
if (!item.featureFlags || item.featureFlags.length === 0) {
|
|
94
|
+
return true;
|
|
95
|
+
}
|
|
96
|
+
return item.featureFlags.some(flag => featureFlags.includes(flag));
|
|
97
|
+
})
|
|
98
|
+
.map(item => {
|
|
99
|
+
const description = item.descriptionTranslations?.[lang] || item.description;
|
|
100
|
+
return {
|
|
101
|
+
name: item.name,
|
|
102
|
+
displayName: item.displayName,
|
|
103
|
+
description,
|
|
104
|
+
schema: item.schema,
|
|
105
|
+
examples: item.examples,
|
|
106
|
+
groupName: item.groupName
|
|
107
|
+
};
|
|
108
|
+
});
|
|
109
|
+
};
|
|
110
|
+
|
|
111
|
+
/** 从 OpenAPI 3.1 文档的 webhooks / x-webhooks 段导入事件类型 */
|
|
112
|
+
const importOpenApi = async (authenticatePayload, { document }) => {
|
|
113
|
+
if (!document || typeof document !== 'object') {
|
|
114
|
+
throw new Error('document 必须是 OpenAPI 对象');
|
|
115
|
+
}
|
|
116
|
+
const webhooks = document.webhooks || document['x-webhooks'] || {};
|
|
117
|
+
const imported = [];
|
|
118
|
+
for (const [name, definition] of Object.entries(webhooks)) {
|
|
119
|
+
const post = definition?.post || {};
|
|
120
|
+
const schema = post.requestBody?.content?.['application/json']?.schema || null;
|
|
121
|
+
const description = post.description || post.summary || '';
|
|
122
|
+
const extensions = Object.fromEntries(
|
|
123
|
+
Object.entries(definition || {}).filter(([key]) => key.startsWith('x-webhook-'))
|
|
124
|
+
);
|
|
125
|
+
imported.push(
|
|
126
|
+
await create(authenticatePayload, {
|
|
127
|
+
name,
|
|
128
|
+
displayName: name,
|
|
129
|
+
description,
|
|
130
|
+
descriptionTranslations: {},
|
|
131
|
+
schema,
|
|
132
|
+
examples: (post.requestBody?.content?.['application/json']?.examples &&
|
|
133
|
+
Object.values(post.requestBody.content['application/json'].examples).map(item => item.value)) || [],
|
|
134
|
+
featureFlags: extensions['x-webhook-feature-flags'] || [],
|
|
135
|
+
groupName: extensions['x-webhook-group-name'] || null
|
|
136
|
+
})
|
|
137
|
+
);
|
|
138
|
+
}
|
|
139
|
+
return { imported: imported.length, events: imported.map(item => item.name) };
|
|
140
|
+
};
|
|
141
|
+
|
|
142
|
+
/** 按事件 Schema 生成 TS 类型定义字符串 */
|
|
143
|
+
const generateTypes = async (authenticatePayload, { lang } = {}) => {
|
|
144
|
+
const catalog = await getCatalog(authenticatePayload, { lang });
|
|
145
|
+
const lines = ['// 自动生成的 Webhook 事件类型定义', ''];
|
|
146
|
+
lines.push('export interface WebhookEventMap {');
|
|
147
|
+
catalog.forEach(item => {
|
|
148
|
+
const typeName = item.name.replace(/[^A-Za-z0-9_]/g, '_');
|
|
149
|
+
lines.push(` '${item.name}': ${typeName}Payload;`);
|
|
150
|
+
});
|
|
151
|
+
lines.push('}');
|
|
152
|
+
lines.push('');
|
|
153
|
+
catalog.forEach(item => {
|
|
154
|
+
const typeName = item.name.replace(/[^A-Za-z0-9_]/g, '_');
|
|
155
|
+
lines.push(`export interface ${typeName}Payload {`);
|
|
156
|
+
lines.push(' [key: string]: unknown;');
|
|
157
|
+
lines.push('}');
|
|
158
|
+
lines.push('');
|
|
159
|
+
});
|
|
160
|
+
return { code: lines.join('\n'), typescript: lines.join('\n') };
|
|
161
|
+
};
|
|
162
|
+
|
|
163
|
+
fastify[options.name].services.eventType = {
|
|
164
|
+
create,
|
|
165
|
+
save,
|
|
166
|
+
remove,
|
|
167
|
+
list,
|
|
168
|
+
copyToTenant,
|
|
169
|
+
getCatalog,
|
|
170
|
+
importOpenApi,
|
|
171
|
+
generateTypes
|
|
172
|
+
};
|
|
173
|
+
});
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const fp = require('fastify-plugin');
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* FIFO 端点严格顺序:同一 endpoint 内,按 message 创建顺序(attempt id)串行投递。
|
|
7
|
+
* 只有当前最小的未完成 attempt 才能投递,其余返回 false 等待下一轮调度。
|
|
8
|
+
*/
|
|
9
|
+
module.exports = fp(async (fastify, options) => {
|
|
10
|
+
const { models, Op } = fastify[options.name].context;
|
|
11
|
+
|
|
12
|
+
/** 判断该 attempt 是否是端点上最早的未完成项 */
|
|
13
|
+
const acquire = async (attempt) => {
|
|
14
|
+
const head = await models.attempt.findOne({
|
|
15
|
+
where: {
|
|
16
|
+
endpointId: attempt.endpointId,
|
|
17
|
+
status: { [Op.in]: ['pending', 'retrying', 'sending'] },
|
|
18
|
+
id: { [Op.lt]: attempt.id }
|
|
19
|
+
},
|
|
20
|
+
order: [['id', 'ASC']]
|
|
21
|
+
});
|
|
22
|
+
return !head;
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
/** attempt 进入终态后无需显式释放:下一轮调度会重新计算 head */
|
|
26
|
+
const release = async () => {};
|
|
27
|
+
|
|
28
|
+
/** 批量变换输入:FIFO 每次投递一批事件 */
|
|
29
|
+
const batchTransformInput = (messages) => ({
|
|
30
|
+
events: messages.map(message => ({ payload: message.payload, eventType: message.type }))
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
fastify[options.name].services.fifo = { acquire, release, batchTransformInput };
|
|
34
|
+
});
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const fp = require('fastify-plugin');
|
|
4
|
+
const { verify } = require('../utils/signature');
|
|
5
|
+
const { ID_HEADER } = require('../constants');
|
|
6
|
+
const { getHeader } = require('../utils/common');
|
|
7
|
+
|
|
8
|
+
module.exports = fp(async (fastify, options) => {
|
|
9
|
+
const ctx = fastify[options.name].context;
|
|
10
|
+
const { models, utils, services, pageParams } = ctx;
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* 处理入站 webhook:验签 -> 去重 -> 记录 -> 调用业务 handler。
|
|
14
|
+
* 业务 handler 通过 options.onInbound(request, context) 注入。
|
|
15
|
+
*/
|
|
16
|
+
const receive = async (request, reply, pathToken) => {
|
|
17
|
+
const endpoints = await models.endpoint.findAll({
|
|
18
|
+
where: {
|
|
19
|
+
uid: pathToken,
|
|
20
|
+
direction: 'inbound',
|
|
21
|
+
status: 'active'
|
|
22
|
+
}
|
|
23
|
+
});
|
|
24
|
+
if (!endpoints.length) {
|
|
25
|
+
// 也尝试把 pathToken 当作 endpoint id
|
|
26
|
+
const byId = await models.endpoint.findByPk(pathToken);
|
|
27
|
+
if (byId && byId.direction === 'inbound' && byId.status === 'active') {
|
|
28
|
+
endpoints.push(byId);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
if (!endpoints.length) {
|
|
32
|
+
const error = new Error('未找到匹配的入站端点');
|
|
33
|
+
error.statusCode = 404;
|
|
34
|
+
throw error;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const endpoint = endpoints[0];
|
|
38
|
+
const tenantId = endpoint.tenantId;
|
|
39
|
+
const rawBody = typeof request.rawBody === 'string' || Buffer.isBuffer(request.rawBody)
|
|
40
|
+
? request.rawBody
|
|
41
|
+
: (request.body ? JSON.stringify(request.body) : '');
|
|
42
|
+
|
|
43
|
+
let verified;
|
|
44
|
+
try {
|
|
45
|
+
const secrets = [endpoint.secret, ...(endpoint.options?.previousSecrets || [])].filter(Boolean);
|
|
46
|
+
verified = verify({ rawBody, headers: request.headers, secrets, tolerance: options.timestampTolerance });
|
|
47
|
+
} catch (error) {
|
|
48
|
+
const err = new Error(`入站签名校验失败: ${error.message}`);
|
|
49
|
+
err.statusCode = 401;
|
|
50
|
+
throw err;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const webhookId = verified.id || getHeader(request.headers, ID_HEADER);
|
|
54
|
+
// 去重:webhook-id + source 唯一
|
|
55
|
+
const existing = await models.inbox.findOne({ where: { tenantId, webhookId, source: 'inbound' } });
|
|
56
|
+
if (existing) {
|
|
57
|
+
return { duplicate: true, id: existing.id, webhookId };
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
const inboxRecord = await models.inbox.create({
|
|
61
|
+
tenantId,
|
|
62
|
+
webhookId,
|
|
63
|
+
source: 'inbound',
|
|
64
|
+
type: getHeader(request.headers, 'webhook-event-type') || endpoint.options?.defaultEventType || 'inbound.event',
|
|
65
|
+
requestBody: Buffer.isBuffer(rawBody) ? rawBody.toString('utf8') : String(rawBody),
|
|
66
|
+
requestHeaders: request.headers,
|
|
67
|
+
status: 'received',
|
|
68
|
+
receivedAt: new Date()
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
// 调用业务 handler(若注入)
|
|
72
|
+
if (typeof options.onInbound === 'function') {
|
|
73
|
+
try {
|
|
74
|
+
await options.onInbound(request, {
|
|
75
|
+
tenantId,
|
|
76
|
+
endpoint,
|
|
77
|
+
webhookId,
|
|
78
|
+
rawBody,
|
|
79
|
+
inboxId: inboxRecord.id,
|
|
80
|
+
fastify
|
|
81
|
+
});
|
|
82
|
+
inboxRecord.status = 'processed';
|
|
83
|
+
} catch (error) {
|
|
84
|
+
inboxRecord.status = 'failed';
|
|
85
|
+
inboxRecord.error = error.message;
|
|
86
|
+
}
|
|
87
|
+
await inboxRecord.save();
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// 立即返回 2xx,业务处理由 handler 决定
|
|
91
|
+
reply?.code?.(200);
|
|
92
|
+
return { id: inboxRecord.id, webhookId, status: inboxRecord.status };
|
|
93
|
+
};
|
|
94
|
+
|
|
95
|
+
const listInbox = async (authenticatePayload, params = {}) => {
|
|
96
|
+
const { offset, limit } = pageParams(params);
|
|
97
|
+
const where = utils.resolveTenantId(authenticatePayload) != null
|
|
98
|
+
? { tenantId: utils.resolveTenantId(authenticatePayload) }
|
|
99
|
+
: {};
|
|
100
|
+
if (params.status) {
|
|
101
|
+
where.status = params.status;
|
|
102
|
+
}
|
|
103
|
+
const { count, rows } = await models.inbox.findAndCountAll({ where, offset, limit, order: [['receivedAt', 'DESC']] });
|
|
104
|
+
return { pageData: rows, totalCount: count };
|
|
105
|
+
};
|
|
106
|
+
|
|
107
|
+
fastify[options.name].services.inbound = { receive, listInbox };
|
|
108
|
+
});
|