@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
package/package.json CHANGED
@@ -1,17 +1,19 @@
1
1
  {
2
2
  "name": "@kne/fastify-webhook",
3
- "version": "0.1.3",
4
- "description": "实现一个webhook功能.",
3
+ "version": "1.0.0",
4
+ "description": "Fastify Webhook 引擎:应用/端点/消息/投递/重试/Ingest/Stream/Polling/Portal/Play 调试器的全量实现",
5
5
  "main": "index.js",
6
6
  "scripts": {
7
7
  "init": "husky",
8
8
  "build:md": "npx @kne/md-doc",
9
9
  "start:md": "npx @kne/md-doc --watch",
10
- "prettier": "prettier --config .prettierrc --write '{libs/**/*,index}.{js,jsx,ts,tsx,json,css,scss}'",
11
- "lint-staged": "npx lint-staged"
10
+ "prettier": "prettier --config .prettierrc --write '{libs/**/*,index,test/**/*}.{js,jsx,ts,tsx,json,css,scss}'",
11
+ "lint-staged": "npx lint-staged",
12
+ "test": "mocha --exit 'test/**/*.test.js'",
13
+ "test:coverage": "nyc --reporter=html --reporter=text mocha --exit 'test/**/*.test.js'"
12
14
  },
13
15
  "lint-staged": {
14
- "{libs/**/*,index}.{js,jsx,ts,tsx,json,css,scss}": [
16
+ "{libs/**/*,index,test/**/*}.{js,jsx,ts,tsx,json,css,scss}": [
15
17
  "prettier --config .prettierrc --write",
16
18
  "git add"
17
19
  ]
@@ -24,7 +26,11 @@
24
26
  "type": "git",
25
27
  "url": "git+https://github.com/kne-union/fastify-webhook.git"
26
28
  },
27
- "keywords": [],
29
+ "keywords": [
30
+ "fastify",
31
+ "webhook",
32
+ "standard-webhooks"
33
+ ],
28
34
  "author": "linzp",
29
35
  "license": "ISC",
30
36
  "bugs": {
@@ -36,17 +42,21 @@
36
42
  "@kne/fastify-sequelize": "*",
37
43
  "fastify-plugin": ">=5"
38
44
  },
45
+ "dependencies": {
46
+ "dayjs": "^1.11.20",
47
+ "lodash": "^4.17.21"
48
+ },
39
49
  "devDependencies": {
40
- "@fastify/env": "^5.0.2",
50
+ "@kne/fastify-namespace": "*",
41
51
  "@kne/fastify-sequelize": "^3.0.6",
52
+ "chai": "^6.2.2",
42
53
  "fastify": "^5.4.0",
43
54
  "fastify-plugin": "^5.0.1",
44
55
  "husky": "^9.0.11",
45
- "nodemon": "^3.1.3",
56
+ "mocha": "^11.7.5",
57
+ "nyc": "^17.1.0",
46
58
  "prettier": "^3.2.5",
59
+ "sinon": "^21.0.0",
47
60
  "sqlite3": "^5.1.7"
48
- },
49
- "dependencies": {
50
- "lodash": "^4.17.21"
51
61
  }
52
62
  }
@@ -1,168 +0,0 @@
1
- const fp = require('fastify-plugin');
2
-
3
- module.exports = fp(async (fastify, options) => {
4
- const { services } = fastify[options.name];
5
- const userAuthenticate = options.getUserAuthenticate(),
6
- adminAuthenticate = options.getAdminAuthenticate();
7
- fastify.post(
8
- `${options.prefix}/create`,
9
- {
10
- onRequest: [userAuthenticate, adminAuthenticate],
11
- schema: {
12
- summary: '添加webhooks',
13
- body: {
14
- type: 'object',
15
- properties: {
16
- name: { type: 'string' },
17
- type: { type: 'string' },
18
- expire: { type: 'string', format: 'date-time' },
19
- signatureLocation: { type: 'string' },
20
- inputLocation: { type: 'string' },
21
- shouldEncryptVerify: { type: 'boolean', default: false }
22
- },
23
- required: ['name', 'type']
24
- }
25
- }
26
- },
27
- async request => {
28
- return services.create({ ...request.body, userId: request.userInfo.id });
29
- }
30
- );
31
-
32
- fastify.get(
33
- `${options.prefix}/list`,
34
- {
35
- onRequest: [userAuthenticate, adminAuthenticate]
36
- },
37
- async () => {
38
- return services.list();
39
- }
40
- );
41
-
42
- fastify.post(
43
- `${options.prefix}/set-status`,
44
- {
45
- onRequest: [userAuthenticate, adminAuthenticate],
46
- schema: {
47
- summary: '设置webhook状态',
48
- body: {
49
- type: 'object',
50
- properties: {
51
- id: { type: 'number' },
52
- status: { type: 'string', enum: ['open', 'close'] }
53
- },
54
- required: ['id', 'status']
55
- }
56
- }
57
- },
58
- async request => {
59
- return services.setStatus(request.body);
60
- }
61
- );
62
-
63
- fastify.post(
64
- `${options.prefix}/invoke/:type`,
65
- {
66
- config: {
67
- rawBody: true
68
- },
69
- schema: {
70
- summary: '调用webhook post请求',
71
- params: {
72
- type: 'object',
73
- properties: {
74
- type: { type: 'string' }
75
- },
76
- required: ['type']
77
- }
78
- }
79
- },
80
- async request => {
81
- const { type } = request.params;
82
-
83
- return services.invoke(
84
- Object.assign(
85
- {},
86
- { type },
87
- {
88
- body: request.body,
89
- rawBody: request[options.rawBodyField || 'rawBody'],
90
- headers: request.headers,
91
- query: request.query
92
- }
93
- )
94
- );
95
- }
96
- );
97
-
98
- fastify.get(
99
- `${options.prefix}/invoke/:type`,
100
- {
101
- schema: {
102
- summary: '调用webhook get请求',
103
- params: {
104
- type: 'object',
105
- properties: {
106
- type: { type: 'string' }
107
- },
108
- required: ['type']
109
- }
110
- }
111
- },
112
- async request => {
113
- const { type } = request.params;
114
- return services.invoke(
115
- Object.assign(
116
- {},
117
- { type },
118
- {
119
- headers: request.headers,
120
- query: request.query
121
- }
122
- )
123
- );
124
- }
125
- );
126
-
127
- fastify.get(
128
- `${options.prefix}/invoke-record`,
129
- {
130
- onRequest: [userAuthenticate, adminAuthenticate],
131
- schema: {
132
- summary: '获取webhook调用记录',
133
- query: {
134
- type: 'object',
135
- properties: {
136
- id: { type: 'string' },
137
- type: { type: 'string' },
138
- currentPage: { type: 'number', default: 1 },
139
- perPage: { type: 'number', default: 10 }
140
- }
141
- }
142
- }
143
- },
144
- async request => {
145
- return services.invokeRecord(request.query);
146
- }
147
- );
148
-
149
- fastify.post(
150
- `${options.prefix}/remove`,
151
- {
152
- onRequest: [userAuthenticate, adminAuthenticate],
153
- schema: {
154
- summary: '删除webhook',
155
- body: {
156
- type: 'object',
157
- properties: {
158
- id: { type: 'string' }
159
- },
160
- required: ['id']
161
- }
162
- }
163
- },
164
- async request => {
165
- return services.remove(request.body);
166
- }
167
- );
168
- });
@@ -1,58 +0,0 @@
1
- module.exports = ({ DataTypes, options }) => {
2
- return {
3
- model: {
4
- name: {
5
- type: DataTypes.STRING,
6
- comment: '名称,需说明调用webhook的端口的身份',
7
- allowNull: false
8
- },
9
- type: {
10
- type: DataTypes.STRING,
11
- comment: '在hooks中定义的webhook类型',
12
- allowNull: false
13
- },
14
- signatureLocation: {
15
- type: DataTypes.STRING,
16
- comment: '签名所在位置',
17
- allowNull: false,
18
- defaultValue: 'headers["x-signature"]'
19
- },
20
- inputLocation: {
21
- type: DataTypes.STRING,
22
- comment: '输入参数所在位置',
23
- allowNull: false,
24
- defaultValue: 'body'
25
- },
26
- expire: {
27
- type: DataTypes.DATE,
28
- comment: '过期时间,默认为null,不过期',
29
- defaultValue: null
30
- },
31
- shouldEncryptVerify: {
32
- type: DataTypes.BOOLEAN,
33
- comment: '是否加密验证',
34
- defaultValue: false
35
- },
36
- status: {
37
- type: DataTypes.ENUM('open', 'close'),
38
- comment: '状态',
39
- defaultValue: 'open'
40
- }
41
- },
42
- associate: ({ client }) => {
43
- client.belongsTo(options.getUserModel(), {
44
- foreignKey: 'userId',
45
- comment: '创建人'
46
- });
47
- },
48
- options: {
49
- comment: 'webhook调用客户端',
50
- indexes: [
51
- {
52
- fields: ['name', 'type', 'deleted_at'],
53
- unique: true
54
- }
55
- ]
56
- }
57
- };
58
- };
@@ -1,18 +0,0 @@
1
- module.exports = ({DataTypes, options}) => {
2
- return {
3
- //name: 'modelName',//此处定义modelName,默认根据文件名转驼峰命名,可以缺省
4
- model: {
5
- name: {
6
- type: DataTypes.STRING,
7
- comment: '名称'
8
- }
9
- }, associate: ({/*这里可以获取models*/}, fastify) => {
10
- //可以这样获取某个namespace的models fastify.account.models
11
- // options.getUserModel() 可以获取 user model
12
- }, options: {
13
- comment: '',
14
- indexes: []
15
- }
16
- };
17
- };
18
-
@@ -1,40 +0,0 @@
1
- module.exports = ({ DataTypes, options }) => {
2
- return {
3
- model: {
4
- startTime: {
5
- type: DataTypes.DATE,
6
- comment: '调用时间',
7
- allowNull: false
8
- },
9
- endTime: {
10
- type: DataTypes.DATE,
11
- comment: '调用结束时间',
12
- allowNull: false
13
- },
14
- input: {
15
- type: DataTypes.JSON,
16
- comment: '调用参数'
17
- },
18
- type: {
19
- type: DataTypes.STRING,
20
- comment: '调用类型'
21
- },
22
- status: {
23
- type: DataTypes.ENUM('success', 'failed'),
24
- comment: '调用返回状态'
25
- },
26
- result: {
27
- type: DataTypes.JSON,
28
- comment: '调用结果'
29
- }
30
- },
31
- associate: ({ invocation, client }) => {
32
- invocation.belongsTo(client, {
33
- comment: 'webhook调用端'
34
- });
35
- },
36
- options: {
37
- comment: '调用记录'
38
- }
39
- };
40
- };
@@ -1,10 +0,0 @@
1
- const fp = require('fastify-plugin');
2
-
3
- module.exports = fp(async (fastify, options) => {
4
- const { models, services } = fastify[options.name];
5
- const { Op } = fastify.sequelize.Sequelize;
6
-
7
- Object.assign(fastify[options.name].services, {
8
-
9
- });
10
- });
@@ -1,172 +0,0 @@
1
- const fp = require('fastify-plugin');
2
- const crypto = require('crypto');
3
- const transform = require('lodash/transform');
4
- const groupBy = require('lodash/groupBy');
5
- const get = require('lodash/get');
6
-
7
- function generateSignature(key, body) {
8
- // 创建 HMAC-SHA256 哈希对象
9
- const hmac = crypto.createHmac('sha256', key);
10
- // 更新哈希内容(支持字符串或 Buffer)
11
- hmac.update(body);
12
- // 生成 Base64 编码的签名
13
- return hmac.digest('base64');
14
- }
15
-
16
- module.exports = fp(async (fastify, options) => {
17
- const { models } = fastify[options.name];
18
- const { Op } = fastify.sequelize.Sequelize;
19
-
20
- const create = async ({ name, type, expire, userId, signatureLocation, inputLocation, shouldEncryptVerify }) => {
21
- if (!options.hooks[type]) {
22
- throw new Error(`Hook ${type} not allowed`);
23
- }
24
- return await models.client.create({
25
- name,
26
- type,
27
- expire,
28
- userId,
29
- signatureLocation,
30
- inputLocation,
31
- shouldEncryptVerify
32
- });
33
- };
34
-
35
- const detail = async ({ id }) => {
36
- const webhook = await models.client.findByPk(id);
37
- if (!webhook) {
38
- throw new Error('Webhook not found');
39
- }
40
- return webhook;
41
- };
42
-
43
- const list = async () => {
44
- const list = await models.client.findAll();
45
- const mapping = groupBy(
46
- list.map(webhook => {
47
- const signature = crypto
48
- .createHash('md5')
49
- .update(`${webhook.name}|${webhook.expire ? webhook.expire.getTime() : 0}`)
50
- .digest('hex');
51
- return Object.assign({}, webhook.get({ plain: true }), {
52
- signature
53
- });
54
- }),
55
- 'type'
56
- );
57
- return transform(
58
- Object.keys(options.hooks),
59
- (result, type) => {
60
- result[type] = mapping[type] || [];
61
- },
62
- {}
63
- );
64
- };
65
-
66
- const invokeRecord = async ({ id, type, currentPage, perPage }) => {
67
- const { rows, count } = await models.invocation.findAndCountAll({
68
- where: id
69
- ? { webhookClientId: id }
70
- : {
71
- webhookClientId: { [Op.is]: null },
72
- type
73
- },
74
- limit: perPage,
75
- offset: (currentPage - 1) * perPage
76
- });
77
-
78
- return {
79
- pageData: rows,
80
- totalCount: count
81
- };
82
- };
83
-
84
- const setStatus = async ({ id, status }) => {
85
- const webhook = await detail({ id });
86
- webhook.status = status;
87
- return webhook.save();
88
- };
89
-
90
- const remove = async ({ id }) => {
91
- const webhook = await detail({ id });
92
- await webhook.destroy();
93
- };
94
-
95
- const invoke = async ({ type, headers, body, rawBody, query }) => {
96
- //signature, input
97
- const list = await models.client.findAll({ where: { type } });
98
-
99
- if (list.length === 0) {
100
- throw new Error('Webhook not found');
101
- }
102
-
103
- let currentWebhook = null;
104
- for (const webhook of list) {
105
- const signature = get({ headers, body, query }, webhook.signatureLocation);
106
- if (webhook.expire && webhook.expire < new Date()) {
107
- continue;
108
- }
109
- const md5 = crypto
110
- .createHash('md5')
111
- .update(`${webhook.name}|${webhook.expire ? webhook.expire.getTime() : 0}`)
112
- .digest('hex');
113
-
114
- const shouldEncryptVerify = webhook.inputLocation === 'body' && webhook.shouldEncryptVerify;
115
-
116
- if (shouldEncryptVerify && generateSignature(md5, rawBody) === signature) {
117
- currentWebhook = webhook;
118
- break;
119
- }
120
- if (!shouldEncryptVerify) {
121
- if (md5 === signature) {
122
- currentWebhook = webhook;
123
- break;
124
- }
125
- }
126
- }
127
-
128
- const startTime = new Date();
129
- if (!currentWebhook) {
130
- await models.invocation.create({
131
- input: {
132
- headers,
133
- body,
134
- rawBody,
135
- query
136
- },
137
- type,
138
- status: 'failed',
139
- startTime,
140
- endTime: new Date()
141
- });
142
- throw new Error('Webhook not registered');
143
- }
144
- const input = { headers, body, query }[currentWebhook.inputLocation];
145
- try {
146
- const result = await options.hooks[currentWebhook.type]({ input });
147
- await models.invocation.create({
148
- input,
149
- type,
150
- result,
151
- webhookClientId: currentWebhook.id,
152
- status: 'success',
153
- startTime,
154
- endTime: new Date()
155
- });
156
- return {};
157
- } catch (e) {
158
- await models.invocation.create({
159
- input,
160
- type,
161
- result: e.toString(),
162
- webhookClientId: currentWebhook.id,
163
- status: 'failed',
164
- startTime,
165
- endTime: new Date()
166
- });
167
- throw e;
168
- }
169
- };
170
-
171
- Object.assign(fastify[options.name].services, { create, list, setStatus, remove, invoke, invokeRecord });
172
- });