@midsummer-ai/sdk 0.1.0-staging.4459 → 0.1.0-staging.4465
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/apps.d.mts +6 -1
- package/apps.mjs +13 -6
- package/here-C2jhTheQ.mjs +1 -1
- package/kv/contract.d.mts +14 -0
- package/kv/contract.mjs +309 -0
- package/kv/index.d.mts +205 -0
- package/kv/index.mjs +232 -0
- package/kv/stand-in.d.mts +14 -0
- package/kv/stand-in.mjs +148 -0
- package/kv/wire.d.mts +24 -0
- package/kv/wire.mjs +277 -0
- package/package.json +50 -1
- package/webhooks/contract.d.mts +17 -0
- package/webhooks/contract.mjs +163 -0
- package/webhooks/index.d.mts +224 -0
- package/webhooks/index.mjs +355 -0
- package/webhooks/stand-in.d.mts +12 -0
- package/webhooks/stand-in.mjs +305 -0
|
@@ -0,0 +1,355 @@
|
|
|
1
|
+
import { a as processEnv, i as platformApi, n as here, r as late, t as clientHeaders } from "../here-C2jhTheQ.mjs";
|
|
2
|
+
import { verifyEvent } from "../apps.mjs";
|
|
3
|
+
//#region src/webhooks/index.ts
|
|
4
|
+
/**
|
|
5
|
+
* Webhooks from a Project's code: tell your own customers what happened, signed as Standard Webhooks says, tried again
|
|
6
|
+
* for about a day when their server is down, and kept so you and they can see and replay what was sent.
|
|
7
|
+
*
|
|
8
|
+
* import { webhooks, verifyWebhook } from "@midsummer-ai/sdk/webhooks"
|
|
9
|
+
*
|
|
10
|
+
* await webhooks.send({ customer: user.id, type: "order.paid", data: { order: 1043, total: 40 }, key: "order-1043-paid" })
|
|
11
|
+
*
|
|
12
|
+
* // On your customer's settings page, from your server, always for the customer signed in:
|
|
13
|
+
* const { endpoint, secret } = await webhooks.endpoints.create({ customer: user.id, url, types: ["order.paid"] })
|
|
14
|
+
* const failed = await webhooks.deliveries.list({ customer: user.id, status: "failed" })
|
|
15
|
+
* await webhooks.deliveries.replay(failed[0].id)
|
|
16
|
+
*
|
|
17
|
+
* Nothing is made first: a customer is your app's own id for them, and a type any `noun.verb` name. A message sent to a
|
|
18
|
+
* customer with no endpoint is kept and sent nowhere. Sending the same `key` again within 30 days returns the first
|
|
19
|
+
* message and sends nothing, so a retry is safe.
|
|
20
|
+
*
|
|
21
|
+
* In a deployment, in any framework, `webhooks` sends for the deployment's project, needing no key: production's
|
|
22
|
+
* endpoints from production, the ones every preview shares from a preview. Anywhere else (an app on another host, a
|
|
23
|
+
* job, a script), give it the project and a token: `webhooks(client({ project: "acme/shop", token }))` from
|
|
24
|
+
* `@midsummer-ai/sdk/webhooks`. Under `midsummer dev` it runs on the Stand-in (`@midsummer-ai/sdk/webhooks/stand-in`),
|
|
25
|
+
* which posts each message, signed, to the endpoints you add there, this computer's included, once. Every engine is
|
|
26
|
+
* held to the cases in `@midsummer-ai/sdk/webhooks/contract`. Every failure is a `WebhooksError`, whose `code` shows
|
|
27
|
+
* which kind.
|
|
28
|
+
*
|
|
29
|
+
* Your customers check each delivery with `verifyWebhook`, or any Standard Webhooks library, against the body exactly
|
|
30
|
+
* as it arrived.
|
|
31
|
+
*/
|
|
32
|
+
var WebhooksError = class extends Error {
|
|
33
|
+
code;
|
|
34
|
+
constructor(code, message) {
|
|
35
|
+
super(message);
|
|
36
|
+
this.code = code;
|
|
37
|
+
this.name = "WebhooksError";
|
|
38
|
+
}
|
|
39
|
+
};
|
|
40
|
+
/** At most this many bytes a message's type and data, as JSON. */
|
|
41
|
+
const MAX_MESSAGE_BYTES = 65536;
|
|
42
|
+
const CUSTOMER = /^[A-Za-z0-9_.:@-]{1,128}$/;
|
|
43
|
+
const TYPE = /^[a-z][a-z0-9_]*(\.[a-z0-9_]+){1,4}$/;
|
|
44
|
+
const ID = /^[\w:.-]{1,128}$/;
|
|
45
|
+
const customerOf = (value) => {
|
|
46
|
+
if (typeof value !== "string" || !CUSTOMER.test(value)) throw new WebhooksError("invalid", "a customer is your app's own id for them, such as cus_42: letters, digits and _ - . : @, at most 128");
|
|
47
|
+
return value;
|
|
48
|
+
};
|
|
49
|
+
const typeOf = (value) => {
|
|
50
|
+
if (typeof value !== "string" || value.length > 100 || !TYPE.test(value)) throw new WebhooksError("invalid", `${String(value)} is not a type: name one as noun.verb in lower case, such as order.paid`);
|
|
51
|
+
return value;
|
|
52
|
+
};
|
|
53
|
+
const idOf = (value, what) => {
|
|
54
|
+
if (typeof value !== "string" || !ID.test(value)) throw new WebhooksError("invalid", `name the ${what} by its id`);
|
|
55
|
+
return value;
|
|
56
|
+
};
|
|
57
|
+
const optional = (value, check) => value === void 0 ? void 0 : check(value);
|
|
58
|
+
const defined = (input) => Object.fromEntries(Object.entries(input).filter(([, value]) => value !== void 0));
|
|
59
|
+
/**
|
|
60
|
+
* A call checked as every engine takes it, the same on the caller's side and the platform's: throws
|
|
61
|
+
* `WebhooksError("invalid")` saying what is wrong.
|
|
62
|
+
*/
|
|
63
|
+
function checkCall(op, given) {
|
|
64
|
+
switch (op) {
|
|
65
|
+
case "send": {
|
|
66
|
+
let size = 0;
|
|
67
|
+
try {
|
|
68
|
+
size = new TextEncoder().encode(JSON.stringify({
|
|
69
|
+
type: given.type,
|
|
70
|
+
data: given.data ?? null
|
|
71
|
+
})).length;
|
|
72
|
+
} catch {
|
|
73
|
+
throw new WebhooksError("invalid", "a message's data is JSON");
|
|
74
|
+
}
|
|
75
|
+
if (size > 65536) throw new WebhooksError("invalid", "a message is at most 64 KB with its type");
|
|
76
|
+
return defined({
|
|
77
|
+
customer: customerOf(given.customer),
|
|
78
|
+
type: typeOf(given.type),
|
|
79
|
+
data: given.data ?? null,
|
|
80
|
+
key: optional(given.key, (key) => idOf(key, "message's key"))
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
case "endpoint.create": {
|
|
84
|
+
if (typeof given.url !== "string" || !given.url) throw new WebhooksError("invalid", "give the endpoint's address, such as https://example.com/hooks");
|
|
85
|
+
const types = given.types === void 0 ? void 0 : Array.isArray(given.types) && given.types.length ? given.types.map(typeOf) : (() => {
|
|
86
|
+
throw new WebhooksError("invalid", "name at least one type, or leave types out for every type");
|
|
87
|
+
})();
|
|
88
|
+
return defined({
|
|
89
|
+
customer: customerOf(given.customer),
|
|
90
|
+
url: given.url,
|
|
91
|
+
types,
|
|
92
|
+
description: optional(given.description, (text) => String(text).slice(0, 200)),
|
|
93
|
+
key: optional(given.key, (key) => idOf(key, "endpoint's key"))
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
case "endpoint.edit": return defined({
|
|
97
|
+
endpoint: idOf(given.endpoint, "endpoint"),
|
|
98
|
+
url: optional(given.url, String),
|
|
99
|
+
types: given.types === null ? null : optional(given.types, (types) => Array.isArray(types) ? types.map(typeOf) : (() => {
|
|
100
|
+
throw new WebhooksError("invalid", "types is a list");
|
|
101
|
+
})()),
|
|
102
|
+
description: given.description === null ? null : optional(given.description, String),
|
|
103
|
+
enabled: optional(given.enabled, Boolean)
|
|
104
|
+
});
|
|
105
|
+
case "endpoint.replay": {
|
|
106
|
+
const since = given.since instanceof Date ? given.since.getTime() : given.since;
|
|
107
|
+
if (typeof since !== "number" || !Number.isFinite(since) || since < 0) throw new WebhooksError("invalid", "since is a time");
|
|
108
|
+
return {
|
|
109
|
+
endpoint: idOf(given.endpoint, "endpoint"),
|
|
110
|
+
since: Math.floor(since)
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
case "endpoint.test": return defined({
|
|
114
|
+
endpoint: idOf(given.endpoint, "endpoint"),
|
|
115
|
+
key: optional(given.key, (key) => idOf(key, "test's key"))
|
|
116
|
+
});
|
|
117
|
+
case "endpoint.show":
|
|
118
|
+
case "endpoint.rotate":
|
|
119
|
+
case "endpoint.delete": return { endpoint: idOf(given.endpoint, "endpoint") };
|
|
120
|
+
case "message.show": return { message: idOf(given.message, "message") };
|
|
121
|
+
case "delivery.show":
|
|
122
|
+
case "delivery.replay": return { delivery: idOf(given.delivery, "delivery") };
|
|
123
|
+
case "endpoint.list":
|
|
124
|
+
case "message.list": return defined({
|
|
125
|
+
customer: optional(given.customer, customerOf),
|
|
126
|
+
limit: optional(given.limit, Number),
|
|
127
|
+
before: optional(given.before, (before) => idOf(before, "page's last item"))
|
|
128
|
+
});
|
|
129
|
+
case "delivery.list": return defined({
|
|
130
|
+
endpoint: optional(given.endpoint, (id) => idOf(id, "endpoint")),
|
|
131
|
+
customer: optional(given.customer, customerOf),
|
|
132
|
+
status: optional(given.status, (status) => {
|
|
133
|
+
if (status !== "pending" && status !== "delivered" && status !== "failed") throw new WebhooksError("invalid", "status is pending, delivered or failed");
|
|
134
|
+
return status;
|
|
135
|
+
}),
|
|
136
|
+
limit: optional(given.limit, Number)
|
|
137
|
+
});
|
|
138
|
+
case "type.list": return {};
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
/** Webhooks over `engine`, each call checked before it leaves. */
|
|
142
|
+
function webhooksOver(engine) {
|
|
143
|
+
const call = async (op, input) => await engine.call(op, checkCall(op, input));
|
|
144
|
+
return {
|
|
145
|
+
send: (message) => call("send", { ...message }),
|
|
146
|
+
endpoints: {
|
|
147
|
+
create: (input) => call("endpoint.create", { ...input }),
|
|
148
|
+
list: (options = {}) => call("endpoint.list", { ...options }),
|
|
149
|
+
show: (id) => call("endpoint.show", { endpoint: id }),
|
|
150
|
+
edit: (id, change) => call("endpoint.edit", {
|
|
151
|
+
endpoint: id,
|
|
152
|
+
...change
|
|
153
|
+
}),
|
|
154
|
+
rotate: (id) => call("endpoint.rotate", { endpoint: id }),
|
|
155
|
+
remove: async (id) => {
|
|
156
|
+
await call("endpoint.delete", { endpoint: id });
|
|
157
|
+
},
|
|
158
|
+
test: (id, options = {}) => call("endpoint.test", {
|
|
159
|
+
endpoint: id,
|
|
160
|
+
...options
|
|
161
|
+
}),
|
|
162
|
+
replay: (id, options) => call("endpoint.replay", {
|
|
163
|
+
endpoint: id,
|
|
164
|
+
since: options.since
|
|
165
|
+
})
|
|
166
|
+
},
|
|
167
|
+
messages: {
|
|
168
|
+
list: (options = {}) => call("message.list", { ...options }),
|
|
169
|
+
show: (id) => call("message.show", { message: id })
|
|
170
|
+
},
|
|
171
|
+
deliveries: {
|
|
172
|
+
list: (options = {}) => call("delivery.list", { ...options }),
|
|
173
|
+
show: (id) => call("delivery.show", { delivery: id }),
|
|
174
|
+
replay: (id) => call("delivery.replay", { delivery: id })
|
|
175
|
+
},
|
|
176
|
+
types: () => call("type.list", {})
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
/** `midsummer dev`'s webhooks: one Stand-in for the process, posting to the endpoints added there, this computer's too. */
|
|
180
|
+
let devEngine;
|
|
181
|
+
/** The engine of the environment this code runs in, made when each call is: the deployment's handle, or under `midsummer dev` the Stand-in. */
|
|
182
|
+
function hereEngine() {
|
|
183
|
+
return late(() => {
|
|
184
|
+
const handle = here()?.webhooks;
|
|
185
|
+
if (handle) return boundWebhooks(handle);
|
|
186
|
+
if (processEnv().MIDSUMMER_DEV === "1") return devEngine ??= import("./stand-in.mjs").then((found) => found.standIn({
|
|
187
|
+
local: true,
|
|
188
|
+
say: (line) => console.log(`webhooks: ${line}`)
|
|
189
|
+
}));
|
|
190
|
+
throw new WebhooksError("forbidden", "This code runs outside a deployment, so it sends with a token: webhooks(client({ project: \"<team>/<project>\", token })). In tests, give webhooks the Stand-in from @midsummer-ai/sdk/webhooks/stand-in.");
|
|
191
|
+
});
|
|
192
|
+
}
|
|
193
|
+
/**
|
|
194
|
+
* Webhooks: `webhooks.send(…)` in a deployment, or `webhooks(engine).send(…)` over an engine you give: `client(…)`
|
|
195
|
+
* outside one, or the Stand-in in tests.
|
|
196
|
+
*/
|
|
197
|
+
const webhooks = Object.assign((engine) => webhooksOver(engine ?? hereEngine()), webhooksOver(hereEngine()));
|
|
198
|
+
/** The Actions each call is, by its method and its path under `/v1/webhook/<team>/<project>`; what is left of its input goes in the query or the body. */
|
|
199
|
+
const ROUTES = {
|
|
200
|
+
send: ["POST", () => "/messages"],
|
|
201
|
+
"message.list": ["GET", () => "/messages"],
|
|
202
|
+
"message.show": [
|
|
203
|
+
"GET",
|
|
204
|
+
(input) => `/messages/${input.message}`,
|
|
205
|
+
"message"
|
|
206
|
+
],
|
|
207
|
+
"type.list": ["GET", () => "/types"],
|
|
208
|
+
"endpoint.create": ["POST", () => "/endpoints"],
|
|
209
|
+
"endpoint.list": ["GET", () => "/endpoints"],
|
|
210
|
+
"endpoint.show": [
|
|
211
|
+
"GET",
|
|
212
|
+
(input) => `/endpoints/${input.endpoint}`,
|
|
213
|
+
"endpoint"
|
|
214
|
+
],
|
|
215
|
+
"endpoint.edit": [
|
|
216
|
+
"PATCH",
|
|
217
|
+
(input) => `/endpoints/${input.endpoint}`,
|
|
218
|
+
"endpoint"
|
|
219
|
+
],
|
|
220
|
+
"endpoint.rotate": [
|
|
221
|
+
"POST",
|
|
222
|
+
(input) => `/endpoints/${input.endpoint}/rotate`,
|
|
223
|
+
"endpoint"
|
|
224
|
+
],
|
|
225
|
+
"endpoint.delete": [
|
|
226
|
+
"DELETE",
|
|
227
|
+
(input) => `/endpoints/${input.endpoint}`,
|
|
228
|
+
"endpoint"
|
|
229
|
+
],
|
|
230
|
+
"endpoint.test": [
|
|
231
|
+
"POST",
|
|
232
|
+
(input) => `/endpoints/${input.endpoint}/test`,
|
|
233
|
+
"endpoint"
|
|
234
|
+
],
|
|
235
|
+
"endpoint.replay": [
|
|
236
|
+
"POST",
|
|
237
|
+
(input) => `/endpoints/${input.endpoint}/replay`,
|
|
238
|
+
"endpoint"
|
|
239
|
+
],
|
|
240
|
+
"delivery.list": ["GET", () => "/deliveries"],
|
|
241
|
+
"delivery.show": [
|
|
242
|
+
"GET",
|
|
243
|
+
(input) => `/deliveries/${input.delivery}`,
|
|
244
|
+
"delivery"
|
|
245
|
+
],
|
|
246
|
+
"delivery.replay": [
|
|
247
|
+
"POST",
|
|
248
|
+
(input) => `/deliveries/${input.delivery}/replay`,
|
|
249
|
+
"delivery"
|
|
250
|
+
]
|
|
251
|
+
};
|
|
252
|
+
/** The calls that take the environment they act in: what lists and sends read. The rest name one thing by its id. */
|
|
253
|
+
const SCOPED = /* @__PURE__ */ new Set([
|
|
254
|
+
"send",
|
|
255
|
+
"message.list",
|
|
256
|
+
"type.list",
|
|
257
|
+
"endpoint.create",
|
|
258
|
+
"endpoint.list",
|
|
259
|
+
"delivery.list"
|
|
260
|
+
]);
|
|
261
|
+
const CODES = {
|
|
262
|
+
400: "invalid",
|
|
263
|
+
401: "forbidden",
|
|
264
|
+
403: "forbidden",
|
|
265
|
+
404: "not-found",
|
|
266
|
+
429: "held"
|
|
267
|
+
};
|
|
268
|
+
/**
|
|
269
|
+
* Webhooks through Midsummer's API, for code outside a deployment: `project` is `<team>/<project>`, `token` a token
|
|
270
|
+
* whose person or agent may deploy it (`midsummer token create`). `environment` is production unless given; `api` the
|
|
271
|
+
* site's API, `MIDSUMMER_API` or the one this package was published for when left out.
|
|
272
|
+
*
|
|
273
|
+
* const hooks = webhooks(client({ project: "acme/shop", token: process.env.MIDSUMMER_TOKEN! }))
|
|
274
|
+
*/
|
|
275
|
+
function client(options) {
|
|
276
|
+
const [team, project, ...rest] = options.project.split("/");
|
|
277
|
+
if (!team || !project || rest.length) throw new WebhooksError("invalid", "name the project as <team>/<project>, such as acme/shop");
|
|
278
|
+
const base = `${(options.api ?? platformApi()).replace(/\/+$/, "")}/v1/webhook/${encodeURIComponent(team)}/${encodeURIComponent(project)}`;
|
|
279
|
+
const send = options.fetch ?? fetch;
|
|
280
|
+
return { async call(op, input) {
|
|
281
|
+
const [method, path, param] = ROUTES[op];
|
|
282
|
+
const { [param ?? ""]: _named, ...rest } = input;
|
|
283
|
+
const fields = {
|
|
284
|
+
...rest,
|
|
285
|
+
...SCOPED.has(op) && options.environment ? { environment: options.environment } : {}
|
|
286
|
+
};
|
|
287
|
+
const query = method === "GET" ? `?${new URLSearchParams(Object.entries(fields).map(([key, value]) => [key, String(value)]))}` : "";
|
|
288
|
+
let response;
|
|
289
|
+
try {
|
|
290
|
+
response = await send(`${base}${path(input)}${query === "?" ? "" : query}`, {
|
|
291
|
+
method,
|
|
292
|
+
headers: {
|
|
293
|
+
authorization: `Bearer ${options.token}`,
|
|
294
|
+
...clientHeaders("webhooks"),
|
|
295
|
+
...method === "GET" || method === "DELETE" ? {} : { "content-type": "application/json" }
|
|
296
|
+
},
|
|
297
|
+
...method === "GET" || method === "DELETE" ? {} : { body: JSON.stringify(fields) }
|
|
298
|
+
});
|
|
299
|
+
} catch {
|
|
300
|
+
throw new WebhooksError("unavailable", "Midsummer couldn't be reached");
|
|
301
|
+
}
|
|
302
|
+
if (response.status === 204) return void 0;
|
|
303
|
+
const answer = await response.json().catch(() => void 0);
|
|
304
|
+
if (response.ok) return answer;
|
|
305
|
+
const message = typeof answer?.error === "string" ? answer.error : answer?.error?.message;
|
|
306
|
+
throw new WebhooksError(CODES[response.status] ?? "unavailable", message ?? `Midsummer returned ${response.status}`);
|
|
307
|
+
} };
|
|
308
|
+
}
|
|
309
|
+
/** What Midsummer hands a deployment as `context.webhooks`: each call carries its op, and the platform knows the project and environment. */
|
|
310
|
+
function boundWebhooks(handle) {
|
|
311
|
+
return { async call(op, input) {
|
|
312
|
+
let answer;
|
|
313
|
+
try {
|
|
314
|
+
answer = await handle.call(op, input);
|
|
315
|
+
} catch {
|
|
316
|
+
throw new WebhooksError("unavailable", "Webhooks could not be reached");
|
|
317
|
+
}
|
|
318
|
+
if ("value" in answer) return answer.value;
|
|
319
|
+
throw new WebhooksError(answer.error.code, answer.error.message);
|
|
320
|
+
} };
|
|
321
|
+
}
|
|
322
|
+
/**
|
|
323
|
+
* The platform's side of a bound handle: checks each call again, as it comes from another Worker's code, and hands it
|
|
324
|
+
* to `engine`, the deployment's project's webhooks. A refusal is returned as data.
|
|
325
|
+
*/
|
|
326
|
+
function serveWebhooks(engine) {
|
|
327
|
+
return async (op, input) => {
|
|
328
|
+
try {
|
|
329
|
+
if (typeof op !== "string" || !(op in ROUTES)) throw new WebhooksError("invalid", `webhooks takes ${Object.keys(ROUTES).join(", ")}`);
|
|
330
|
+
const given = typeof input === "object" && input !== null && !Array.isArray(input) ? input : {};
|
|
331
|
+
return { value: await (await engine()).call(op, checkCall(op, given)) };
|
|
332
|
+
} catch (error) {
|
|
333
|
+
if (error instanceof WebhooksError) return { error: {
|
|
334
|
+
code: error.code,
|
|
335
|
+
message: error.message
|
|
336
|
+
} };
|
|
337
|
+
throw error;
|
|
338
|
+
}
|
|
339
|
+
};
|
|
340
|
+
}
|
|
341
|
+
/**
|
|
342
|
+
* Whether a delivery your app sent is genuine: signed as Standard Webhooks says with the endpoint's secret
|
|
343
|
+
* (`whsec_…`, shown when it was added or rotated). Give the request's headers (`webhook-id`, `webhook-timestamp`,
|
|
344
|
+
* `webhook-signature`) and the body exactly as it arrived, before any parsing. One older than five minutes, or ahead
|
|
345
|
+
* of the clock by as much, is refused. After a rotation both secrets sign for a day, and either passing is enough.
|
|
346
|
+
* Deliveries are at least once: drop a repeat by its `webhook-id`.
|
|
347
|
+
*
|
|
348
|
+
* const body = await request.text()
|
|
349
|
+
* if (!(await verifyWebhook(request.headers, body, process.env.WEBHOOK_SECRET!))) return new Response(null, { status: 401 })
|
|
350
|
+
*/
|
|
351
|
+
function verifyWebhook(headers, body, secret, options = {}) {
|
|
352
|
+
return verifyEvent(headers, body, secret, options.now ?? Date.now());
|
|
353
|
+
}
|
|
354
|
+
//#endregion
|
|
355
|
+
export { MAX_MESSAGE_BYTES, WebhooksError, boundWebhooks, checkCall, client, serveWebhooks, verifyWebhook, webhooks, webhooksOver };
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { Message, WebhooksEngine } from "./index.mjs";
|
|
2
|
+
//#region src/webhooks/stand-in.d.ts
|
|
3
|
+
declare function standIn(options?: {
|
|
4
|
+
readonly fetch?: typeof fetch;
|
|
5
|
+
readonly clock?: () => number;
|
|
6
|
+
readonly local?: boolean;
|
|
7
|
+
readonly say?: (line: string) => void;
|
|
8
|
+
}): WebhooksEngine & {
|
|
9
|
+
readonly messages: ReadonlyArray<Message>;
|
|
10
|
+
};
|
|
11
|
+
//#endregion
|
|
12
|
+
export { standIn };
|
|
@@ -0,0 +1,305 @@
|
|
|
1
|
+
import { signEvent } from "../apps.mjs";
|
|
2
|
+
import { WebhooksError } from "./index.mjs";
|
|
3
|
+
//#region src/webhooks/stand-in.ts
|
|
4
|
+
/**
|
|
5
|
+
* Webhooks' Stand-in: the Capability's behaviour in memory, for `midsummer dev` and tests. It really posts each message,
|
|
6
|
+
* signed as Standard Webhooks says with each endpoint's own secret, to the endpoints added to it, once, at once: a
|
|
7
|
+
* receiver on this computer gets what production's would. It passes the contract (`@midsummer-ai/sdk/webhooks/contract`)
|
|
8
|
+
* except durability and the retry schedule: a try that fails stays failed until it is replayed.
|
|
9
|
+
*
|
|
10
|
+
* const engine = standIn({ fetch: myFetch })
|
|
11
|
+
* const hooks = webhooks(engine)
|
|
12
|
+
* await hooks.endpoints.create({ customer: "cus_42", url: "https://hooks.example.com/in" })
|
|
13
|
+
* await hooks.send({ customer: "cus_42", type: "order.paid", data: { order: 1 } })
|
|
14
|
+
*
|
|
15
|
+
* `local` lets endpoints be on this computer and over http, as under `midsummer dev`; `say` is told of each send.
|
|
16
|
+
*/
|
|
17
|
+
function standIn(options = {}) {
|
|
18
|
+
const send = options.fetch ?? fetch;
|
|
19
|
+
const clock = options.clock ?? Date.now;
|
|
20
|
+
const endpoints = /* @__PURE__ */ new Map();
|
|
21
|
+
const messages = /* @__PURE__ */ new Map();
|
|
22
|
+
const byKey = /* @__PURE__ */ new Map();
|
|
23
|
+
const deliveries = /* @__PURE__ */ new Map();
|
|
24
|
+
const types = /* @__PURE__ */ new Map();
|
|
25
|
+
let count = 0;
|
|
26
|
+
const id = (prefix) => `${prefix}${(++count).toString(36).padStart(6, "0")}`;
|
|
27
|
+
const secret = () => `whsec_${btoa(String.fromCharCode(...crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(24))))}`;
|
|
28
|
+
const takes = (endpoint, type) => endpoint.types === void 0 || endpoint.types.includes(type);
|
|
29
|
+
function checkedUrl(given) {
|
|
30
|
+
const url = URL.parse(given);
|
|
31
|
+
if (!url) throw new WebhooksError("invalid", "give the endpoint's address in full, such as https://example.com/hooks");
|
|
32
|
+
const here = [
|
|
33
|
+
"localhost",
|
|
34
|
+
"127.0.0.1",
|
|
35
|
+
"[::1]"
|
|
36
|
+
].includes(url.hostname) || url.hostname.endsWith(".localhost");
|
|
37
|
+
if (url.protocol === "https:" && !here) return url.toString();
|
|
38
|
+
if (options.local && (url.protocol === "http:" || url.protocol === "https:")) return url.toString();
|
|
39
|
+
throw new WebhooksError("invalid", "an endpoint's address is https on the public internet");
|
|
40
|
+
}
|
|
41
|
+
function endpointOf(endpointId) {
|
|
42
|
+
const kept = endpoints.get(String(endpointId));
|
|
43
|
+
if (!kept) throw new WebhooksError("not-found", `No endpoint ${String(endpointId)} here.`);
|
|
44
|
+
return kept;
|
|
45
|
+
}
|
|
46
|
+
function deliveryOf(deliveryId) {
|
|
47
|
+
const kept = deliveries.get(String(deliveryId));
|
|
48
|
+
if (!kept) throw new WebhooksError("not-found", `No delivery ${String(deliveryId)} here.`);
|
|
49
|
+
return kept;
|
|
50
|
+
}
|
|
51
|
+
/** One try of a delivery, signed with the endpoint's secrets: delivered on a 2xx, failed otherwise. */
|
|
52
|
+
async function attempt(kept) {
|
|
53
|
+
const { endpoint, secret: current, previous } = endpointOf(kept.delivery.endpointId);
|
|
54
|
+
const at = clock(), timestamp = Math.floor(at / 1e3);
|
|
55
|
+
const signatures = await Promise.all([current, ...previous ? [previous] : []].map((one) => signEvent(one, kept.delivery.id, timestamp, kept.payload)));
|
|
56
|
+
let status, body, error;
|
|
57
|
+
try {
|
|
58
|
+
const answer = await send(endpoint.url, {
|
|
59
|
+
method: "POST",
|
|
60
|
+
redirect: "manual",
|
|
61
|
+
headers: {
|
|
62
|
+
"content-type": "application/json",
|
|
63
|
+
"webhook-id": kept.delivery.id,
|
|
64
|
+
"webhook-timestamp": String(timestamp),
|
|
65
|
+
"webhook-signature": signatures.join(" ")
|
|
66
|
+
},
|
|
67
|
+
body: kept.payload
|
|
68
|
+
});
|
|
69
|
+
status = answer.status;
|
|
70
|
+
body = (await answer.text().catch(() => "")).slice(0, 1024) || void 0;
|
|
71
|
+
} catch (thrown) {
|
|
72
|
+
error = thrown instanceof Error ? thrown.message : String(thrown);
|
|
73
|
+
}
|
|
74
|
+
const delivered = status !== void 0 && status >= 200 && status < 300;
|
|
75
|
+
const attempts = kept.delivery.attempts + 1;
|
|
76
|
+
kept.tries.unshift({
|
|
77
|
+
at,
|
|
78
|
+
ms: clock() - at,
|
|
79
|
+
attempt: attempts,
|
|
80
|
+
...status !== void 0 ? { status } : {},
|
|
81
|
+
...body ? { body } : {},
|
|
82
|
+
...error ? { error } : {}
|
|
83
|
+
});
|
|
84
|
+
const { lastStatus: _status, lastError: _error, nextAt: _next, ...rest } = kept.delivery;
|
|
85
|
+
kept.delivery = {
|
|
86
|
+
...rest,
|
|
87
|
+
status: delivered ? "delivered" : "failed",
|
|
88
|
+
attempts,
|
|
89
|
+
lastAttemptAt: clock(),
|
|
90
|
+
...status !== void 0 ? { lastStatus: status } : {},
|
|
91
|
+
...error ? { lastError: error } : {},
|
|
92
|
+
...delivered ? { deliveredAt: clock() } : {}
|
|
93
|
+
};
|
|
94
|
+
return kept.delivery;
|
|
95
|
+
}
|
|
96
|
+
function deliver(endpoint, message, payload) {
|
|
97
|
+
const kept = {
|
|
98
|
+
delivery: {
|
|
99
|
+
id: `msg_${endpoint.id}_${message.id}`,
|
|
100
|
+
endpointId: endpoint.id,
|
|
101
|
+
messageId: message.id,
|
|
102
|
+
customer: message.customer,
|
|
103
|
+
type: message.type,
|
|
104
|
+
status: "pending",
|
|
105
|
+
attempts: 0,
|
|
106
|
+
createdAt: clock()
|
|
107
|
+
},
|
|
108
|
+
payload,
|
|
109
|
+
tries: []
|
|
110
|
+
};
|
|
111
|
+
deliveries.set(kept.delivery.id, kept);
|
|
112
|
+
return kept;
|
|
113
|
+
}
|
|
114
|
+
const shown = ({ deliveries: _d, ...message }) => message;
|
|
115
|
+
const ops = {
|
|
116
|
+
async send(input) {
|
|
117
|
+
const key = input.key;
|
|
118
|
+
const earlier = key === void 0 ? void 0 : messages.get(byKey.get(key) ?? "");
|
|
119
|
+
if (earlier) return shown(earlier);
|
|
120
|
+
const customer = input.customer, type = input.type;
|
|
121
|
+
const payload = JSON.stringify({
|
|
122
|
+
type,
|
|
123
|
+
timestamp: new Date(clock()).toISOString(),
|
|
124
|
+
data: input.data
|
|
125
|
+
});
|
|
126
|
+
const listening = [...endpoints.values()].filter(({ endpoint }) => endpoint.customer === customer && endpoint.enabled && takes(endpoint, type));
|
|
127
|
+
const message = {
|
|
128
|
+
id: id("msg_"),
|
|
129
|
+
environment: "production",
|
|
130
|
+
customer,
|
|
131
|
+
type,
|
|
132
|
+
...key === void 0 ? {} : { key },
|
|
133
|
+
data: input.data,
|
|
134
|
+
createdAt: clock(),
|
|
135
|
+
endpoints: listening.length,
|
|
136
|
+
deliveries: []
|
|
137
|
+
};
|
|
138
|
+
messages.set(message.id, message);
|
|
139
|
+
if (key !== void 0) byKey.set(key, message.id);
|
|
140
|
+
if (!types.has(type)) types.set(type, {
|
|
141
|
+
type,
|
|
142
|
+
firstAt: message.createdAt,
|
|
143
|
+
example: input.data
|
|
144
|
+
});
|
|
145
|
+
const made = listening.map(({ endpoint }) => deliver(endpoint, message, payload));
|
|
146
|
+
message.deliveries = made.map((kept) => kept.delivery.id);
|
|
147
|
+
await Promise.all(made.map(attempt));
|
|
148
|
+
options.say?.(`${type} to ${customer}: ${listening.length ? `${made.filter((kept) => kept.delivery.status === "delivered").length} of ${listening.length} endpoints took it` : "no endpoint takes it, so it was kept and sent nowhere"}`);
|
|
149
|
+
return shown(message);
|
|
150
|
+
},
|
|
151
|
+
async "message.list"(input) {
|
|
152
|
+
return [...messages.values()].filter((message) => input.customer === void 0 || message.customer === input.customer).reverse().slice(0, Number(input.limit ?? 50)).map(shown);
|
|
153
|
+
},
|
|
154
|
+
async "message.show"(input) {
|
|
155
|
+
const message = messages.get(String(input.message));
|
|
156
|
+
if (!message) throw new WebhooksError("not-found", `No message ${String(input.message)} here.`);
|
|
157
|
+
return {
|
|
158
|
+
...shown(message),
|
|
159
|
+
deliveries: message.deliveries.map((one) => deliveries.get(one).delivery)
|
|
160
|
+
};
|
|
161
|
+
},
|
|
162
|
+
async "type.list"() {
|
|
163
|
+
return [...types.values()];
|
|
164
|
+
},
|
|
165
|
+
async "endpoint.create"(input) {
|
|
166
|
+
const url = checkedUrl(String(input.url));
|
|
167
|
+
const customer = input.customer;
|
|
168
|
+
const theirs = [...endpoints.values()].filter(({ endpoint }) => endpoint.customer === customer);
|
|
169
|
+
if (theirs.some(({ endpoint }) => endpoint.url === url)) throw new WebhooksError("invalid", `${url} gets ${customer}'s messages already`);
|
|
170
|
+
if (theirs.length >= 20) throw new WebhooksError("invalid", "A customer has at most 20 endpoints.");
|
|
171
|
+
const typesNamed = input.types;
|
|
172
|
+
const endpoint = {
|
|
173
|
+
id: id("wae_"),
|
|
174
|
+
environment: "production",
|
|
175
|
+
customer,
|
|
176
|
+
url,
|
|
177
|
+
...typeof input.description === "string" ? { description: input.description } : {},
|
|
178
|
+
...typesNamed ? { types: typesNamed } : {},
|
|
179
|
+
enabled: true,
|
|
180
|
+
failing: 0,
|
|
181
|
+
createdAt: clock(),
|
|
182
|
+
secretAt: clock()
|
|
183
|
+
};
|
|
184
|
+
const made = secret();
|
|
185
|
+
endpoints.set(endpoint.id, {
|
|
186
|
+
endpoint,
|
|
187
|
+
secret: made
|
|
188
|
+
});
|
|
189
|
+
return {
|
|
190
|
+
endpoint,
|
|
191
|
+
secret: made,
|
|
192
|
+
unsent: (typesNamed ?? []).filter((type) => !types.has(type))
|
|
193
|
+
};
|
|
194
|
+
},
|
|
195
|
+
async "endpoint.list"(input) {
|
|
196
|
+
return [...endpoints.values()].map(({ endpoint }) => endpoint).filter((endpoint) => input.customer === void 0 || endpoint.customer === input.customer).reverse();
|
|
197
|
+
},
|
|
198
|
+
async "endpoint.show"(input) {
|
|
199
|
+
return endpointOf(input.endpoint).endpoint;
|
|
200
|
+
},
|
|
201
|
+
async "endpoint.edit"(input) {
|
|
202
|
+
const kept = endpointOf(input.endpoint);
|
|
203
|
+
const { types: _types, disabled: _off, description: _description, ...rest } = kept.endpoint;
|
|
204
|
+
const typesNamed = input.types === void 0 ? kept.endpoint.types : input.types === null ? void 0 : input.types;
|
|
205
|
+
const description = input.description === void 0 ? kept.endpoint.description : input.description === null ? void 0 : String(input.description);
|
|
206
|
+
const enabled = input.enabled === void 0 ? kept.endpoint.enabled : Boolean(input.enabled);
|
|
207
|
+
kept.endpoint = {
|
|
208
|
+
...rest,
|
|
209
|
+
...input.url === void 0 ? {} : { url: checkedUrl(String(input.url)) },
|
|
210
|
+
...typesNamed ? { types: typesNamed } : {},
|
|
211
|
+
...description ? { description } : {},
|
|
212
|
+
enabled,
|
|
213
|
+
...enabled ? { failing: 0 } : { disabled: "by-request" }
|
|
214
|
+
};
|
|
215
|
+
return kept.endpoint;
|
|
216
|
+
},
|
|
217
|
+
async "endpoint.rotate"(input) {
|
|
218
|
+
const kept = endpointOf(input.endpoint);
|
|
219
|
+
kept.previous = kept.secret;
|
|
220
|
+
kept.secret = secret();
|
|
221
|
+
kept.endpoint = {
|
|
222
|
+
...kept.endpoint,
|
|
223
|
+
secretAt: clock()
|
|
224
|
+
};
|
|
225
|
+
return {
|
|
226
|
+
endpoint: kept.endpoint,
|
|
227
|
+
secret: kept.secret
|
|
228
|
+
};
|
|
229
|
+
},
|
|
230
|
+
async "endpoint.delete"(input) {
|
|
231
|
+
endpointOf(input.endpoint);
|
|
232
|
+
endpoints.delete(String(input.endpoint));
|
|
233
|
+
},
|
|
234
|
+
async "endpoint.test"(input) {
|
|
235
|
+
const { endpoint } = endpointOf(input.endpoint);
|
|
236
|
+
return attempt(deliver(endpoint, {
|
|
237
|
+
id: id("ping_"),
|
|
238
|
+
customer: endpoint.customer,
|
|
239
|
+
type: "webhook.ping"
|
|
240
|
+
}, JSON.stringify({
|
|
241
|
+
type: "webhook.ping",
|
|
242
|
+
timestamp: new Date(clock()).toISOString(),
|
|
243
|
+
data: {
|
|
244
|
+
endpoint: endpoint.id,
|
|
245
|
+
customer: endpoint.customer
|
|
246
|
+
}
|
|
247
|
+
})));
|
|
248
|
+
},
|
|
249
|
+
async "endpoint.replay"(input) {
|
|
250
|
+
const { endpoint } = endpointOf(input.endpoint);
|
|
251
|
+
if (!endpoint.enabled) throw new WebhooksError("invalid", `${endpoint.id} is off. Turn it on first.`);
|
|
252
|
+
const since = Number(input.since);
|
|
253
|
+
const theirs = [...messages.values()].filter((message) => message.customer === endpoint.customer && message.createdAt >= since && takes(endpoint, message.type));
|
|
254
|
+
let replayed = 0;
|
|
255
|
+
for (const message of theirs) {
|
|
256
|
+
const existing = deliveries.get(`msg_${endpoint.id}_${message.id}`);
|
|
257
|
+
if (existing?.delivery.status === "delivered") continue;
|
|
258
|
+
const kept = existing ?? deliver(endpoint, message, JSON.stringify({
|
|
259
|
+
type: message.type,
|
|
260
|
+
timestamp: new Date(message.createdAt).toISOString(),
|
|
261
|
+
data: message.data
|
|
262
|
+
}));
|
|
263
|
+
if (!existing) message.deliveries.push(kept.delivery.id);
|
|
264
|
+
kept.delivery = {
|
|
265
|
+
...kept.delivery,
|
|
266
|
+
attempts: 0
|
|
267
|
+
};
|
|
268
|
+
await attempt(kept);
|
|
269
|
+
replayed++;
|
|
270
|
+
}
|
|
271
|
+
return {
|
|
272
|
+
replayed,
|
|
273
|
+
checked: theirs.length,
|
|
274
|
+
more: false
|
|
275
|
+
};
|
|
276
|
+
},
|
|
277
|
+
async "delivery.list"(input) {
|
|
278
|
+
return [...deliveries.values()].map((kept) => kept.delivery).filter((delivery) => (input.endpoint === void 0 || delivery.endpointId === input.endpoint) && (input.customer === void 0 || delivery.customer === input.customer) && (input.status === void 0 || delivery.status === input.status)).reverse().slice(0, Number(input.limit ?? 50));
|
|
279
|
+
},
|
|
280
|
+
async "delivery.show"(input) {
|
|
281
|
+
const kept = deliveryOf(input.delivery);
|
|
282
|
+
return {
|
|
283
|
+
...kept.delivery,
|
|
284
|
+
tries: [...kept.tries]
|
|
285
|
+
};
|
|
286
|
+
},
|
|
287
|
+
async "delivery.replay"(input) {
|
|
288
|
+
const kept = deliveryOf(input.delivery);
|
|
289
|
+
if (!endpointOf(kept.delivery.endpointId).endpoint.enabled) throw new WebhooksError("invalid", `${kept.delivery.endpointId} is off. Turn it on first.`);
|
|
290
|
+
kept.delivery = {
|
|
291
|
+
...kept.delivery,
|
|
292
|
+
attempts: 0
|
|
293
|
+
};
|
|
294
|
+
return attempt(kept);
|
|
295
|
+
}
|
|
296
|
+
};
|
|
297
|
+
return {
|
|
298
|
+
get messages() {
|
|
299
|
+
return [...messages.values()].map(shown);
|
|
300
|
+
},
|
|
301
|
+
call: (op, input) => ops[op](input)
|
|
302
|
+
};
|
|
303
|
+
}
|
|
304
|
+
//#endregion
|
|
305
|
+
export { standIn };
|