@vite-hub/webhooks 0.4.1 → 0.5.1
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 +36 -6
- package/dist/database-C5cwO1an.d.ts +1517 -0
- package/dist/database.d.ts +2 -2
- package/dist/database.js +196 -14
- package/dist/{errors-1y5fWGlX.js → errors-DT8uyCh7.js} +39 -4
- package/dist/index.d.ts +128 -4
- package/dist/index.js +246 -4
- package/dist/members-BjDcAAhY.d.ts +343 -0
- package/dist/members-Cr_Nlyg4.js +308 -0
- package/dist/object-CAK6UYR5.js +10 -0
- package/dist/{operations-7ycAhDCw.d.ts → operations-8hqTi0DH.d.ts} +8 -4
- package/dist/operations.d.ts +13 -4
- package/dist/operations.js +189 -99
- package/dist/{queue-name-CGeTSHId.d.ts → queue-name-CLdaJFPZ.d.ts} +0 -2
- package/dist/{queue-name-RURp9SQf.js → queue-name-jmgeppja.js} +1 -2
- package/dist/runtime-BFiCJOMB.js +914 -0
- package/dist/{runtime-mqwMGfyX.d.ts → runtime-BdILDcW1.d.ts} +94 -17
- package/dist/runtime.d.ts +3 -3
- package/dist/runtime.js +3 -3
- package/dist/table-names-DAUip4v2.js +12 -0
- package/dist/vite.d.ts +91 -16
- package/dist/vite.js +192 -55
- package/package.json +9 -9
- package/dist/database-COdjz9Vi.d.ts +0 -608
- package/dist/object-BJb1W_q5.js +0 -7
- package/dist/runtime-DVBMk9vu.js +0 -486
- package/dist/table-names-DVvicXhh.js +0 -8
|
@@ -0,0 +1,914 @@
|
|
|
1
|
+
import { t as webhooksErrors } from "./errors-DT8uyCh7.js";
|
|
2
|
+
import { signWebhook } from "@vite-hub/env";
|
|
3
|
+
import { onRunFailed, runFailedEventNames } from "@vite-hub/runtime/internal/run-failed";
|
|
4
|
+
import { parseDuration } from "@vite-hub/runtime";
|
|
5
|
+
import { importSealKey, sealWithKey, unsealWithKey } from "@vite-hub/env/seal";
|
|
6
|
+
import { getViteHubTestMode } from "@vite-hub/runtime/internal/test-mode";
|
|
7
|
+
// src/define.ts
|
|
8
|
+
const definitionBrand = Symbol.for("vitehub.webhooks.definition");
|
|
9
|
+
const variableName = /^[A-Z_][A-Z0-9_]*$/i;
|
|
10
|
+
function isWebhookEvent(value) {
|
|
11
|
+
return runFailedEventNames.some((name) => name === value);
|
|
12
|
+
}
|
|
13
|
+
function invalid(message) {
|
|
14
|
+
return webhooksErrors.WEBHOOKS_DEFINITION_INVALID({ message: `[vitehub] ${message}` });
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Defines a webhook: where ViteHub sends events, how it signs them, and how long it waits to collapse them. Default-export
|
|
18
|
+
* it from `server/webhooks/<name>.ts`, then call `sendWebhook("<name>", body)` from server code, or list `events` that
|
|
19
|
+
* ViteHub sends by itself.
|
|
20
|
+
*
|
|
21
|
+
* ```ts [server/webhooks/t3.ts]
|
|
22
|
+
* import { defineWebhook } from "@vite-hub/webhooks"
|
|
23
|
+
*
|
|
24
|
+
* export default defineWebhook({
|
|
25
|
+
* url: "T3_WEBHOOK_URL",
|
|
26
|
+
* secret: "T3_WEBHOOK_SECRET",
|
|
27
|
+
* debounce: "30m",
|
|
28
|
+
* })
|
|
29
|
+
* ```
|
|
30
|
+
*/
|
|
31
|
+
function defineWebhook(options) {
|
|
32
|
+
for (const key of ["url", "secret"]) {
|
|
33
|
+
const value = options?.[key];
|
|
34
|
+
if (typeof value !== "string" || !variableName.test(value)) throw invalid(`\`${key}\` must be the name of a server variable, such as ${key === "url" ? "\"T3_WEBHOOK_URL\"" : "\"T3_WEBHOOK_SECRET\""}, not ${JSON.stringify(value)}.`);
|
|
35
|
+
}
|
|
36
|
+
const signature = options.signature ?? "github";
|
|
37
|
+
if (signature !== "github" && signature !== "stripe") throw invalid(`\`signature\` must be "github" or "stripe", not ${JSON.stringify(signature)}.`);
|
|
38
|
+
const debounceMs = options.debounce === void 0 ? 0 : parseDuration(options.debounce, "debounce");
|
|
39
|
+
if (debounceMs > 864e5) throw webhooksErrors.WEBHOOKS_DEBOUNCE_TOO_LONG({ debounce: JSON.stringify(options.debounce) });
|
|
40
|
+
const listed = options.events ?? [];
|
|
41
|
+
if (!Array.isArray(listed)) throw invalid(`\`events\` must be a list such as ["workflow.failed"], not ${JSON.stringify(listed)}.`);
|
|
42
|
+
const items = listed;
|
|
43
|
+
const events = /* @__PURE__ */ new Set();
|
|
44
|
+
for (const event of items) {
|
|
45
|
+
if (!isWebhookEvent(event)) throw invalid(`\`events\` lists ${JSON.stringify(event)}. Use ${runFailedEventNames.map((name) => JSON.stringify(name)).join(", ")}.`);
|
|
46
|
+
events.add(event);
|
|
47
|
+
}
|
|
48
|
+
return Object.defineProperty({
|
|
49
|
+
url: options.url,
|
|
50
|
+
secret: options.secret,
|
|
51
|
+
signature,
|
|
52
|
+
debounceMs,
|
|
53
|
+
events: [...events]
|
|
54
|
+
}, definitionBrand, { value: true });
|
|
55
|
+
}
|
|
56
|
+
function isWebhookDefinition(value) {
|
|
57
|
+
return typeof value === "object" && value !== null && Reflect.get(value, definitionBrand) === true;
|
|
58
|
+
}
|
|
59
|
+
// ../internal/src/runtime/cloudflare-env-lookup.ts
|
|
60
|
+
/** The key of the AsyncLocalStorage store on `globalThis`. Every bundled copy of this module shares the store. */
|
|
61
|
+
const activeEnvStorageKey = Symbol.for("vitehub.cloudflare.env-storage");
|
|
62
|
+
let activeEnv;
|
|
63
|
+
/** The store of the current `runWithActiveCloudflareEnv()` call, or undefined outside one. */
|
|
64
|
+
function getScopedCloudflareEnv() {
|
|
65
|
+
return globalThis[activeEnvStorageKey]?.getStore();
|
|
66
|
+
}
|
|
67
|
+
function getActiveCloudflareEnv() {
|
|
68
|
+
const scoped = getScopedCloudflareEnv();
|
|
69
|
+
if (scoped) return scoped.env;
|
|
70
|
+
const host = globalThis;
|
|
71
|
+
return Object.hasOwn(host, "__env__") && host.__env__ !== void 0 ? host.__env__ : activeEnv;
|
|
72
|
+
}
|
|
73
|
+
new TextEncoder();
|
|
74
|
+
Object.freeze({ prefix: "sha256=" });
|
|
75
|
+
/** Decodes a canonical base64 key. Returns `undefined` for malformed or empty input, so verification fails closed. */
|
|
76
|
+
function decodeViteHubBase64Key(value) {
|
|
77
|
+
if (!/^[A-Za-z0-9+/]+={0,2}$/.test(value) || value.length % 4 === 1) return void 0;
|
|
78
|
+
let binary;
|
|
79
|
+
try {
|
|
80
|
+
binary = atob(value);
|
|
81
|
+
} catch {
|
|
82
|
+
return;
|
|
83
|
+
}
|
|
84
|
+
if (!binary.length || btoa(binary).replace(/=+$/, "") !== value.replace(/=+$/, "")) return void 0;
|
|
85
|
+
return Uint8Array.from(binary, (character) => character.charCodeAt(0));
|
|
86
|
+
}
|
|
87
|
+
/** The server variables: Node's `process.env`, the Cloudflare bindings, and the values of `setEnv()` in app tests. */
|
|
88
|
+
function serverEnv() {
|
|
89
|
+
return {
|
|
90
|
+
...typeof process === "object" && process?.env ? process.env : {},
|
|
91
|
+
...getActiveCloudflareEnv(),
|
|
92
|
+
...getViteHubTestMode()?.env
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
function readString(env, name) {
|
|
96
|
+
const value = env[name];
|
|
97
|
+
return typeof value === "string" && value.trim() ? value.trim() : void 0;
|
|
98
|
+
}
|
|
99
|
+
let cached;
|
|
100
|
+
function testKey() {
|
|
101
|
+
return getViteHubTestMode()?.backend("webhooks:key", () => btoa(String.fromCharCode(...crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(32)))));
|
|
102
|
+
}
|
|
103
|
+
async function endpointKey(developmentKey) {
|
|
104
|
+
const value = readString(serverEnv(), "VITEHUB_WEBHOOKS_KEY") ?? testKey() ?? developmentKey;
|
|
105
|
+
if (!value) return [webhooksErrors.WEBHOOKS_KEY_UNSET(), void 0];
|
|
106
|
+
if (cached?.value !== value) {
|
|
107
|
+
const raw = decodeViteHubBase64Key(value);
|
|
108
|
+
if (raw?.byteLength !== 32) return [webhooksErrors.WEBHOOKS_KEY_INVALID({ problem: "the value is not 32 bytes in base64" }), void 0];
|
|
109
|
+
cached = {
|
|
110
|
+
value,
|
|
111
|
+
key: importSealKey(raw)
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
return [void 0, await cached.key];
|
|
115
|
+
}
|
|
116
|
+
function additionalData(endpoint) {
|
|
117
|
+
return new TextEncoder().encode(`vitehub:webhooks:endpoint:${JSON.stringify([endpoint.id, endpoint.owner])}`);
|
|
118
|
+
}
|
|
119
|
+
async function sealEndpoint(endpoint, target, developmentKey) {
|
|
120
|
+
const [error, key] = await endpointKey(developmentKey);
|
|
121
|
+
if (error) return [error, void 0];
|
|
122
|
+
return [void 0, await sealWithKey(key, additionalData(endpoint), JSON.stringify({
|
|
123
|
+
url: target.url,
|
|
124
|
+
secret: target.secret
|
|
125
|
+
}))];
|
|
126
|
+
}
|
|
127
|
+
async function unsealEndpoint(endpoint, developmentKey) {
|
|
128
|
+
const [error, key] = await endpointKey(developmentKey);
|
|
129
|
+
if (error) return [error, void 0];
|
|
130
|
+
let text;
|
|
131
|
+
try {
|
|
132
|
+
text = await unsealWithKey(key, additionalData(endpoint), endpoint.sealed);
|
|
133
|
+
} catch {
|
|
134
|
+
return [webhooksErrors.WEBHOOKS_KEY_INVALID({ problem: "it is not the key that sealed this endpoint" }), void 0];
|
|
135
|
+
}
|
|
136
|
+
const value = JSON.parse(text);
|
|
137
|
+
const url = typeof value === "object" && value !== null ? Reflect.get(value, "url") : void 0;
|
|
138
|
+
const secret = typeof value === "object" && value !== null ? Reflect.get(value, "secret") : void 0;
|
|
139
|
+
if (typeof url !== "string" || typeof secret !== "string") return [webhooksErrors.WEBHOOKS_KEY_INVALID({ problem: "the sealed endpoint has no URL or secret" }), void 0];
|
|
140
|
+
return [void 0, {
|
|
141
|
+
url,
|
|
142
|
+
secret
|
|
143
|
+
}];
|
|
144
|
+
}
|
|
145
|
+
/**
|
|
146
|
+
* Seals `text` with `VITEHUB_WEBHOOKS_KEY` for another package that keeps a receiver's secret before it becomes a member
|
|
147
|
+
* endpoint, such as the setup code of Comments Send. `label` binds the sealed text to one row: open it with the same one.
|
|
148
|
+
*/
|
|
149
|
+
async function sealWebhooksText(label, text, developmentKey) {
|
|
150
|
+
const [error, key] = await endpointKey(developmentKey);
|
|
151
|
+
if (error) return [error, void 0];
|
|
152
|
+
return [void 0, await sealWithKey(key, new TextEncoder().encode(`vitehub:webhooks:text:${label}`), text)];
|
|
153
|
+
}
|
|
154
|
+
/** Opens the text that `sealWebhooksText()` sealed with the same `label`. */
|
|
155
|
+
async function unsealWebhooksText(label, sealed, developmentKey) {
|
|
156
|
+
const [error, key] = await endpointKey(developmentKey);
|
|
157
|
+
if (error) return [error, void 0];
|
|
158
|
+
try {
|
|
159
|
+
return [void 0, await unsealWithKey(key, new TextEncoder().encode(`vitehub:webhooks:text:${label}`), sealed)];
|
|
160
|
+
} catch {
|
|
161
|
+
return [webhooksErrors.WEBHOOKS_KEY_INVALID({ problem: "it is not the key that sealed this text" }), void 0];
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
const sealedMemberBodyPrefix = "vitehub:sealed-member-body:";
|
|
165
|
+
function memberBodyLabel(webhook, event) {
|
|
166
|
+
return `delivery:${JSON.stringify([webhook, event])}`;
|
|
167
|
+
}
|
|
168
|
+
// src/url-guard.ts
|
|
169
|
+
function refuse(reason) {
|
|
170
|
+
return [webhooksErrors.WEBHOOKS_URL_REFUSED({ reason }), void 0];
|
|
171
|
+
}
|
|
172
|
+
/** Why the host of `url` is outside `hosts`, or `undefined` when `hosts` lists it. A host does not match its subdomains. */
|
|
173
|
+
function outsideHosts(url, hosts) {
|
|
174
|
+
const host = url.hostname.toLowerCase().replace(/\.$/, "");
|
|
175
|
+
return hosts.some((allowed) => allowed.toLowerCase() === host) ? void 0 : `its host is not ${hosts.join(" or ") || "allowed"}`;
|
|
176
|
+
}
|
|
177
|
+
function parseIPv4(host) {
|
|
178
|
+
const match = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(host);
|
|
179
|
+
if (!match) return void 0;
|
|
180
|
+
const bytes = [
|
|
181
|
+
Number(match[1]),
|
|
182
|
+
Number(match[2]),
|
|
183
|
+
Number(match[3]),
|
|
184
|
+
Number(match[4])
|
|
185
|
+
];
|
|
186
|
+
return bytes.every((byte) => byte <= 255) ? bytes : void 0;
|
|
187
|
+
}
|
|
188
|
+
function parseIPv6(input) {
|
|
189
|
+
let text = input.toLowerCase();
|
|
190
|
+
const dotted = /^(?<head>.*:)(?<tail>\d+\.\d+\.\d+\.\d+)$/.exec(text)?.groups;
|
|
191
|
+
if (dotted?.head !== void 0 && dotted.tail !== void 0) {
|
|
192
|
+
const v4 = parseIPv4(dotted.tail);
|
|
193
|
+
if (!v4) return void 0;
|
|
194
|
+
text = `${dotted.head}${(v4[0] << 8 | v4[1]).toString(16)}:${(v4[2] << 8 | v4[3]).toString(16)}`;
|
|
195
|
+
}
|
|
196
|
+
const [before = "", after, ...more] = text.split("::");
|
|
197
|
+
if (more.length) return void 0;
|
|
198
|
+
const read = (part) => part === "" ? [] : part.split(":");
|
|
199
|
+
const head = read(before);
|
|
200
|
+
const rest = after === void 0 ? [] : read(after);
|
|
201
|
+
if (![...head, ...rest].every((group) => /^[0-9a-f]{1,4}$/.test(group))) return void 0;
|
|
202
|
+
const missing = 8 - head.length - rest.length;
|
|
203
|
+
if (after === void 0 ? missing !== 0 : missing < 1) return void 0;
|
|
204
|
+
const zeros = Array.from({ length: after === void 0 ? 0 : missing }, () => "0");
|
|
205
|
+
return [
|
|
206
|
+
...head,
|
|
207
|
+
...zeros,
|
|
208
|
+
...rest
|
|
209
|
+
].map((group) => Number.parseInt(group, 16));
|
|
210
|
+
}
|
|
211
|
+
function privateIPv4([a, b, c]) {
|
|
212
|
+
if (a === 127) return "a loopback address";
|
|
213
|
+
if (a === 10 || a === 172 && b >= 16 && b <= 31 || a === 192 && b === 168) return "a private address";
|
|
214
|
+
if (a === 169 && b === 254) return "a link-local or cloud metadata address";
|
|
215
|
+
if (a === 100 && b >= 64 && b <= 127) return "a shared or cloud metadata address";
|
|
216
|
+
if (a === 0) return "an unspecified address";
|
|
217
|
+
if (a === 192 && b === 0 && c === 0) return "a reserved address";
|
|
218
|
+
if (a === 198 && (b === 18 || b === 19)) return "a reserved address";
|
|
219
|
+
if (a >= 224) return "a multicast or reserved address";
|
|
220
|
+
}
|
|
221
|
+
const embeddedIPv4 = (high, low) => [
|
|
222
|
+
high >> 8,
|
|
223
|
+
high & 255,
|
|
224
|
+
low >> 8,
|
|
225
|
+
low & 255
|
|
226
|
+
];
|
|
227
|
+
function privateIPv6(groups) {
|
|
228
|
+
const [first = 0, second = 0, third = 0, , , sixth = 0, seventh = 0, eighth = 0] = groups;
|
|
229
|
+
const zeroUntil = (end) => groups.slice(0, end).every((group) => group === 0);
|
|
230
|
+
if (zeroUntil(8)) return "an unspecified address";
|
|
231
|
+
if (zeroUntil(7) && eighth === 1) return "a loopback address";
|
|
232
|
+
const mapped = zeroUntil(5) && sixth === 65535;
|
|
233
|
+
const compatible = zeroUntil(6);
|
|
234
|
+
const nat64 = first === 100 && second === 65435 && groups.slice(2, 6).every((group) => group === 0);
|
|
235
|
+
if (mapped || nat64) return privateIPv4(embeddedIPv4(seventh, eighth));
|
|
236
|
+
if (compatible) return privateIPv4(embeddedIPv4(seventh, eighth)) ?? "a deprecated IPv4-compatible address";
|
|
237
|
+
if (first === 100 && second === 65435 && third === 1) return "a local-use NAT64 address";
|
|
238
|
+
if (first === 8194) {
|
|
239
|
+
const reason = privateIPv4(embeddedIPv4(second, third));
|
|
240
|
+
if (reason) return `a 6to4 address of ${reason}`;
|
|
241
|
+
}
|
|
242
|
+
if ((first & 65024) === 64512) return "a private address";
|
|
243
|
+
if ((first & 65472) === 65152) return "a link-local address";
|
|
244
|
+
if ((first & 65280) === 65280) return "a multicast address";
|
|
245
|
+
}
|
|
246
|
+
function privateAddress(address) {
|
|
247
|
+
const v4 = parseIPv4(address);
|
|
248
|
+
if (v4) return privateIPv4(v4);
|
|
249
|
+
const v6 = parseIPv6(address.replace(/^\[|\]$/g, ""));
|
|
250
|
+
return v6 ? privateIPv6(v6) : void 0;
|
|
251
|
+
}
|
|
252
|
+
/**
|
|
253
|
+
* Checks that `url` is safe to post a signed body to, and returns it parsed as `[error, url]`. It refuses a URL that:
|
|
254
|
+
*
|
|
255
|
+
* - is not `https`, or holds a user name or a password;
|
|
256
|
+
* - uses a host outside `hosts`, when you pass `hosts`;
|
|
257
|
+
* - names a loopback, private, link-local, or cloud metadata address, such as `127.0.0.1`, `10.0.0.1`,
|
|
258
|
+
* `169.254.169.254`, or `[::1]`;
|
|
259
|
+
* - on Node, Bun, and Deno, has a name that resolves to such an address, or does not resolve.
|
|
260
|
+
*
|
|
261
|
+
* Cloudflare Workers cannot resolve names, so there a name passes on the host allowlist alone. Webhooks checks the URL
|
|
262
|
+
* again before each delivery.
|
|
263
|
+
*
|
|
264
|
+
* ```ts
|
|
265
|
+
* import { checkWebhookUrl } from "@vite-hub/webhooks"
|
|
266
|
+
*
|
|
267
|
+
* const [error] = await checkWebhookUrl("https://relay.t3.codes/hooks/abc", { hosts: ["relay.t3.codes"] })
|
|
268
|
+
* ```
|
|
269
|
+
*/
|
|
270
|
+
async function checkWebhookUrl(url, options = {}) {
|
|
271
|
+
const [error, resolved] = await resolveWebhookUrl(url, options);
|
|
272
|
+
return error ? [error, void 0] : [void 0, resolved.url];
|
|
273
|
+
}
|
|
274
|
+
async function resolveWebhookUrl(url, options = {}) {
|
|
275
|
+
if (typeof url !== "string" || !URL.canParse(url)) return refuse("it is not a URL");
|
|
276
|
+
const parsed = new URL(url);
|
|
277
|
+
if (parsed.protocol !== "https:") return refuse("it does not use https");
|
|
278
|
+
if (parsed.username || parsed.password) return refuse("it holds a user name or a password");
|
|
279
|
+
const host = parsed.hostname.toLowerCase().replace(/\.$/, "");
|
|
280
|
+
const outside = options.hosts && outsideHosts(parsed, options.hosts);
|
|
281
|
+
if (outside) return refuse(outside);
|
|
282
|
+
if (host === "localhost" || host.endsWith(".localhost")) return refuse("it names a loopback address");
|
|
283
|
+
const literal = privateAddress(host);
|
|
284
|
+
if (literal) return refuse(`it names ${literal}`);
|
|
285
|
+
if (parseIPv4(host) || host.startsWith("[")) return [void 0, { url: parsed }];
|
|
286
|
+
if (globalThis.navigator?.userAgent === "Cloudflare-Workers" || typeof process !== "object" || !process?.versions?.node) return [void 0, { url: parsed }];
|
|
287
|
+
let addresses;
|
|
288
|
+
try {
|
|
289
|
+
const { lookup } = await import("node:dns/promises");
|
|
290
|
+
addresses = await lookup(host, {
|
|
291
|
+
all: true,
|
|
292
|
+
verbatim: true
|
|
293
|
+
});
|
|
294
|
+
} catch {
|
|
295
|
+
return refuse("its host does not resolve");
|
|
296
|
+
}
|
|
297
|
+
if (!addresses.length) return refuse("its host does not resolve");
|
|
298
|
+
for (const { address } of addresses) {
|
|
299
|
+
const reason = privateAddress(address);
|
|
300
|
+
if (reason) return refuse(`its host resolves to ${reason}`);
|
|
301
|
+
}
|
|
302
|
+
return [void 0, {
|
|
303
|
+
url: parsed,
|
|
304
|
+
addresses
|
|
305
|
+
}];
|
|
306
|
+
}
|
|
307
|
+
// src/runtime.ts
|
|
308
|
+
/** Attempts of one delivery before it is `dead`: one delivery and three retries, as Cloudflare Queues does by default. */
|
|
309
|
+
const webhookMaxAttempts = 4;
|
|
310
|
+
/** How long a receiver has to answer. */
|
|
311
|
+
const webhookTimeoutMs = 1e4;
|
|
312
|
+
const claimLeaseMs = 7e4;
|
|
313
|
+
const installedKey = Symbol.for("vitehub.webhooks.installed");
|
|
314
|
+
/** The webhooks that `installWebhooks()` installed in this process. */
|
|
315
|
+
function installedWebhooks() {
|
|
316
|
+
const value = Reflect.get(globalThis, installedKey);
|
|
317
|
+
return value === void 0 ? void 0 : value;
|
|
318
|
+
}
|
|
319
|
+
/**
|
|
320
|
+
* Installs the webhooks of the app for `sendWebhook()`, the Queue handler, and the delivery functions. The generated
|
|
321
|
+
* server code of a ViteHub app calls it when the server starts. A test calls it with its own store and wake sender.
|
|
322
|
+
*/
|
|
323
|
+
function installWebhooks(options) {
|
|
324
|
+
const webhooks = /* @__PURE__ */ new Map();
|
|
325
|
+
for (const [name, definition] of Object.entries(options.webhooks)) {
|
|
326
|
+
if (!isWebhookDefinition(definition)) throw webhooksErrors.WEBHOOKS_DEFINITION_INVALID({ message: `[vitehub] server/webhooks/${name} must default-export defineWebhook({ url, secret }).` });
|
|
327
|
+
webhooks.set(name, definition);
|
|
328
|
+
}
|
|
329
|
+
const installed = {
|
|
330
|
+
webhooks,
|
|
331
|
+
store: options.store,
|
|
332
|
+
wake: options.wake,
|
|
333
|
+
endpoints: options.endpoints,
|
|
334
|
+
developmentKey: options.developmentKey,
|
|
335
|
+
resolveVerifiedOwner: options.resolveVerifiedOwner
|
|
336
|
+
};
|
|
337
|
+
Reflect.set(globalThis, installedKey, installed);
|
|
338
|
+
if (!Reflect.get(globalThis, listenerKey)) Reflect.set(globalThis, listenerKey, onRunFailed(sendRunFailed));
|
|
339
|
+
return installed;
|
|
340
|
+
}
|
|
341
|
+
const listenerKey = Symbol.for("vitehub.webhooks.runFailedListener");
|
|
342
|
+
function failedSubject(event) {
|
|
343
|
+
if (event.event === "invocation.failed") return event.agent ?? event.invocationId;
|
|
344
|
+
return event.event === "workflow.failed" ? event.workflow : event.schedule;
|
|
345
|
+
}
|
|
346
|
+
function toWebhookEventBody(event) {
|
|
347
|
+
const subject = event.event === "invocation.failed" ? `The Agent Invocation ${event.invocationId}${event.agent ? ` of ${JSON.stringify(event.agent)}` : ""}` : event.event === "workflow.failed" ? `The Workflow run ${event.runId} of ${JSON.stringify(event.workflow)}` : `The Schedule run ${event.runId} of ${JSON.stringify(event.schedule)}`;
|
|
348
|
+
return {
|
|
349
|
+
...event,
|
|
350
|
+
text: `${subject} failed: ${event.error.message}`
|
|
351
|
+
};
|
|
352
|
+
}
|
|
353
|
+
async function sendRunFailed(event) {
|
|
354
|
+
const installed = installedWebhooks();
|
|
355
|
+
if (!installed) return;
|
|
356
|
+
const body = toWebhookEventBody(event);
|
|
357
|
+
for (const [name, definition] of installed.webhooks) {
|
|
358
|
+
if (!definition.events.includes(event.event)) continue;
|
|
359
|
+
const key = definition.debounceMs > 0 ? `${event.event}:${failedSubject(event)}` : null;
|
|
360
|
+
const [error] = await enqueue(name, body, {
|
|
361
|
+
event: event.event,
|
|
362
|
+
key,
|
|
363
|
+
delayMs: definition.debounceMs
|
|
364
|
+
});
|
|
365
|
+
if (error) console.error(`[vitehub] The webhook ${name} did not store the ${event.event} event.`, error);
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
function requireInstalled() {
|
|
369
|
+
const installed = installedWebhooks();
|
|
370
|
+
if (!installed) throw webhooksErrors.WEBHOOKS_NOT_INSTALLED();
|
|
371
|
+
return installed;
|
|
372
|
+
}
|
|
373
|
+
/** The installed webhooks with member endpoints on. */
|
|
374
|
+
function requireMemberEndpoints() {
|
|
375
|
+
const installed = installedWebhooks();
|
|
376
|
+
if (!installed?.endpoints) throw webhooksErrors.WEBHOOKS_ENDPOINTS_OFF();
|
|
377
|
+
return {
|
|
378
|
+
...installed,
|
|
379
|
+
endpoints: installed.endpoints
|
|
380
|
+
};
|
|
381
|
+
}
|
|
382
|
+
/**
|
|
383
|
+
* The Database that keeps the deliveries: the one that `useDatabase()` of `@vite-hub/database/runtime/registry` returns
|
|
384
|
+
* without a name. That is the Database that `vitehub database generate` adds the table to: `default`, else the only one.
|
|
385
|
+
* The registry also holds a placeholder `default` that throws, so code must not pick from it by name.
|
|
386
|
+
*/
|
|
387
|
+
function selectDefaultDatabase(useDatabase) {
|
|
388
|
+
try {
|
|
389
|
+
return useDatabase().db;
|
|
390
|
+
} catch (cause) {
|
|
391
|
+
throw webhooksErrors.WEBHOOKS_DATABASE_MISSING({ cause });
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
function resolveTarget(name, definition) {
|
|
395
|
+
const env = serverEnv();
|
|
396
|
+
const url = readString(env, definition.url);
|
|
397
|
+
if (!url) return [webhooksErrors.WEBHOOKS_URL_UNSET({
|
|
398
|
+
name: definition.url,
|
|
399
|
+
webhook: name
|
|
400
|
+
}), void 0];
|
|
401
|
+
if (!URL.canParse(url) || !/^https?:$/.test(new URL(url).protocol)) return [webhooksErrors.WEBHOOKS_URL_INVALID({
|
|
402
|
+
name: definition.url,
|
|
403
|
+
webhook: name
|
|
404
|
+
}), void 0];
|
|
405
|
+
const secret = readString(env, definition.secret);
|
|
406
|
+
if (!secret) return [webhooksErrors.WEBHOOKS_SECRET_UNSET({
|
|
407
|
+
name: definition.secret,
|
|
408
|
+
webhook: name
|
|
409
|
+
}), void 0];
|
|
410
|
+
return [void 0, {
|
|
411
|
+
url,
|
|
412
|
+
secret,
|
|
413
|
+
signature: definition.signature
|
|
414
|
+
}];
|
|
415
|
+
}
|
|
416
|
+
/** A member delivery names its endpoint as `@<endpoint id>` in the `webhook` column. */
|
|
417
|
+
const memberWebhookPrefix = "@";
|
|
418
|
+
async function resolveMemberTarget(installed, id) {
|
|
419
|
+
const endpoint = await installed.endpoints?.find(id);
|
|
420
|
+
if (!endpoint) return [`No member endpoint has the id ${JSON.stringify(id)}.`, void 0];
|
|
421
|
+
if (endpoint.disabledAt !== null) return [`The member endpoint ${id} is disabled.`, void 0];
|
|
422
|
+
if (endpoint.sealed === null) return [`The member endpoint ${id} is an inbox, so it takes no posts.`, void 0];
|
|
423
|
+
const [error, target] = await unsealEndpoint({
|
|
424
|
+
...endpoint,
|
|
425
|
+
sealed: endpoint.sealed
|
|
426
|
+
}, installed.developmentKey);
|
|
427
|
+
if (error) return [error.message, void 0];
|
|
428
|
+
return [void 0, {
|
|
429
|
+
...target,
|
|
430
|
+
signature: "github",
|
|
431
|
+
guard: true
|
|
432
|
+
}];
|
|
433
|
+
}
|
|
434
|
+
/**
|
|
435
|
+
* Whether `caller` has the app user id of the owner. Console callers must also match the email set at connect time.
|
|
436
|
+
*/
|
|
437
|
+
function ownsMemberEndpoint(endpoint, caller) {
|
|
438
|
+
return caller?.id === endpoint.owner && (caller.verifiedConsoleEmail === void 0 || caller.verifiedConsoleEmail === endpoint.ownerEmail);
|
|
439
|
+
}
|
|
440
|
+
/**
|
|
441
|
+
* Posts a claimed member delivery now, or keeps it for the inbox when `target` is `undefined`. A failed post is tried
|
|
442
|
+
* again through the Queue when the app has one, so its status is `"pending"`; without Queue it is `"failed"`.
|
|
443
|
+
*/
|
|
444
|
+
async function deliverMemberClaim(installed, claim, target) {
|
|
445
|
+
const { store } = installed;
|
|
446
|
+
if (!target) {
|
|
447
|
+
await store.sent(claim, {
|
|
448
|
+
status: null,
|
|
449
|
+
error: null
|
|
450
|
+
}, Date.now());
|
|
451
|
+
return [void 0, {
|
|
452
|
+
id: claim.id,
|
|
453
|
+
status: "inbox"
|
|
454
|
+
}];
|
|
455
|
+
}
|
|
456
|
+
const result = await postDelivery(claim, {
|
|
457
|
+
...target,
|
|
458
|
+
signature: "github",
|
|
459
|
+
guard: true
|
|
460
|
+
}, installed.developmentKey);
|
|
461
|
+
if (result.ok) {
|
|
462
|
+
await store.sent(claim, {
|
|
463
|
+
status: result.status,
|
|
464
|
+
error: null
|
|
465
|
+
}, Date.now());
|
|
466
|
+
return [void 0, {
|
|
467
|
+
id: claim.id,
|
|
468
|
+
status: "sent"
|
|
469
|
+
}];
|
|
470
|
+
}
|
|
471
|
+
const retry = installed.wake !== void 0 && !result.final;
|
|
472
|
+
const wakeError = retry ? await wake(installed, claim, webhookTimeoutMs) : void 0;
|
|
473
|
+
const state = await store.failed(claim, {
|
|
474
|
+
status: result.status,
|
|
475
|
+
error: result.failure
|
|
476
|
+
}, Date.now(), !retry || wakeError !== void 0);
|
|
477
|
+
if (wakeError) return [wakeError, void 0];
|
|
478
|
+
return [void 0, {
|
|
479
|
+
id: claim.id,
|
|
480
|
+
status: state === "pending" ? "pending" : "failed"
|
|
481
|
+
}];
|
|
482
|
+
}
|
|
483
|
+
function createDeliveryId() {
|
|
484
|
+
return `whd_${crypto.randomUUID()}`;
|
|
485
|
+
}
|
|
486
|
+
async function wake(installed, delivery, delayMs) {
|
|
487
|
+
if (!installed.wake) return webhooksErrors.WEBHOOKS_WAKE_FAILED({
|
|
488
|
+
webhook: delivery.webhook,
|
|
489
|
+
cause: /* @__PURE__ */ new Error("The app has no Queue.")
|
|
490
|
+
});
|
|
491
|
+
try {
|
|
492
|
+
const [error] = await installed.wake({
|
|
493
|
+
id: delivery.id,
|
|
494
|
+
revision: delivery.revision
|
|
495
|
+
}, { delay: `${Math.ceil(Math.max(0, delayMs) / 1e3)}s` });
|
|
496
|
+
return error === void 0 ? void 0 : webhooksErrors.WEBHOOKS_WAKE_FAILED({
|
|
497
|
+
webhook: delivery.webhook,
|
|
498
|
+
cause: error
|
|
499
|
+
});
|
|
500
|
+
} catch (cause) {
|
|
501
|
+
return webhooksErrors.WEBHOOKS_WAKE_FAILED({
|
|
502
|
+
webhook: delivery.webhook,
|
|
503
|
+
cause
|
|
504
|
+
});
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
async function enqueue(name, body, options) {
|
|
508
|
+
const installed = requireInstalled();
|
|
509
|
+
const definition = installed.webhooks.get(name);
|
|
510
|
+
if (!definition) throw webhooksErrors.WEBHOOKS_NOT_FOUND({ name: JSON.stringify(name) });
|
|
511
|
+
const [targetError] = resolveTarget(name, definition);
|
|
512
|
+
if (targetError) return [targetError, void 0];
|
|
513
|
+
let text;
|
|
514
|
+
try {
|
|
515
|
+
text = JSON.stringify(body);
|
|
516
|
+
} catch {
|
|
517
|
+
text = void 0;
|
|
518
|
+
}
|
|
519
|
+
if (text === void 0) return [webhooksErrors.WEBHOOKS_BODY_INVALID({ webhook: name }), void 0];
|
|
520
|
+
const now = Date.now();
|
|
521
|
+
let recorded;
|
|
522
|
+
try {
|
|
523
|
+
recorded = await installed.store.record({
|
|
524
|
+
id: createDeliveryId(),
|
|
525
|
+
webhook: name,
|
|
526
|
+
key: options.key,
|
|
527
|
+
event: options.event,
|
|
528
|
+
body: text,
|
|
529
|
+
dueAt: now + options.delayMs,
|
|
530
|
+
now
|
|
531
|
+
});
|
|
532
|
+
} catch (error) {
|
|
533
|
+
if (webhooksErrors.WEBHOOKS_STORE_FAILED.is(error) || webhooksErrors.WEBHOOKS_DATABASE_MISSING.is(error)) return [error, void 0];
|
|
534
|
+
throw error;
|
|
535
|
+
}
|
|
536
|
+
const wakeError = await wake(installed, {
|
|
537
|
+
...recorded,
|
|
538
|
+
webhook: name
|
|
539
|
+
}, options.delayMs);
|
|
540
|
+
if (wakeError) return [wakeError, void 0];
|
|
541
|
+
return [void 0, {
|
|
542
|
+
id: recorded.id,
|
|
543
|
+
status: "pending"
|
|
544
|
+
}];
|
|
545
|
+
}
|
|
546
|
+
/** Sends a body to a webhook. `sendWebhook()` of `@vite-hub/webhooks` calls it with a typed name. */
|
|
547
|
+
async function sendDynamicWebhook(name, body, options) {
|
|
548
|
+
const debounceMs = requireInstalled().webhooks.get(name)?.debounceMs ?? 0;
|
|
549
|
+
return enqueue(name, body, {
|
|
550
|
+
event: options.event,
|
|
551
|
+
key: debounceMs > 0 ? options.key ?? name : null,
|
|
552
|
+
delayMs: debounceMs
|
|
553
|
+
});
|
|
554
|
+
}
|
|
555
|
+
/** The event of a test delivery. */
|
|
556
|
+
const webhookTestEvent = "webhooks.test";
|
|
557
|
+
/**
|
|
558
|
+
* Sends a test delivery to a webhook now, without its debounce and apart from the pending sends, with the event
|
|
559
|
+
* `webhooks.test`. Use it to check the URL, the secret, and the receiver. The default body is
|
|
560
|
+
* `{ test: true, webhook: name }`. An unknown name throws.
|
|
561
|
+
*/
|
|
562
|
+
async function testWebhook(name, options = {}) {
|
|
563
|
+
return enqueue(name, options.body === void 0 ? {
|
|
564
|
+
test: true,
|
|
565
|
+
webhook: name
|
|
566
|
+
} : options.body, {
|
|
567
|
+
event: webhookTestEvent,
|
|
568
|
+
key: null,
|
|
569
|
+
delayMs: 0
|
|
570
|
+
});
|
|
571
|
+
}
|
|
572
|
+
function isWake(value) {
|
|
573
|
+
return typeof value === "object" && value !== null && typeof Reflect.get(value, "id") === "string" && Number.isInteger(Reflect.get(value, "revision"));
|
|
574
|
+
}
|
|
575
|
+
function describeFailure(error) {
|
|
576
|
+
if (error instanceof Error && (error.name === "TimeoutError" || error.name === "AbortError")) return `no answer within ${webhookTimeoutMs / 1e3} seconds`;
|
|
577
|
+
const cause = error instanceof Error ? error.cause : void 0;
|
|
578
|
+
const code = typeof cause === "object" && cause !== null ? Reflect.get(cause, "code") : void 0;
|
|
579
|
+
return typeof code === "string" ? `network error ${code}` : "network error";
|
|
580
|
+
}
|
|
581
|
+
/**
|
|
582
|
+
* The Queue handler of `vitehub-webhooks`. It posts the delivery of a wake when the wake carries the latest revision and
|
|
583
|
+
* the delivery is pending. A 2xx answer marks it `sent`. Any other answer throws, so the Queue tries again, until the
|
|
584
|
+
* last attempt marks it `dead`. A wake that is out of date does nothing.
|
|
585
|
+
*/
|
|
586
|
+
async function deliverWebhookWake(payload) {
|
|
587
|
+
if (!isWake(payload)) {
|
|
588
|
+
console.error("[vitehub] The webhooks Queue got a job that is not a delivery wake. It skips the job.");
|
|
589
|
+
return;
|
|
590
|
+
}
|
|
591
|
+
const installed = requireInstalled();
|
|
592
|
+
const { store } = installed;
|
|
593
|
+
const now = Date.now();
|
|
594
|
+
const claim = await store.claim(payload.id, payload.revision, now, now - claimLeaseMs);
|
|
595
|
+
if (!claim) {
|
|
596
|
+
const current = await store.get(payload.id);
|
|
597
|
+
if (current?.revision === payload.revision && current.state === "sending") {
|
|
598
|
+
const error = await wake(installed, current, current.updatedAt + claimLeaseMs + 1 - Date.now());
|
|
599
|
+
if (error) throw error;
|
|
600
|
+
}
|
|
601
|
+
return;
|
|
602
|
+
}
|
|
603
|
+
const [targetError, target] = claim.webhook.startsWith("@") ? await resolveMemberTarget(installed, claim.webhook.slice(1)) : resolveFileTarget(installed, claim.webhook);
|
|
604
|
+
if (targetError !== void 0) {
|
|
605
|
+
await store.failed(claim, {
|
|
606
|
+
status: null,
|
|
607
|
+
error: targetError
|
|
608
|
+
}, Date.now(), true);
|
|
609
|
+
return;
|
|
610
|
+
}
|
|
611
|
+
const result = await postDelivery(claim, target, installed.developmentKey);
|
|
612
|
+
if (result.ok) {
|
|
613
|
+
await store.sent(claim, {
|
|
614
|
+
status: result.status,
|
|
615
|
+
error: null
|
|
616
|
+
}, Date.now());
|
|
617
|
+
return;
|
|
618
|
+
}
|
|
619
|
+
const dead = result.final || claim.attempts >= 4;
|
|
620
|
+
if (await store.failed(claim, {
|
|
621
|
+
status: result.status,
|
|
622
|
+
error: result.failure
|
|
623
|
+
}, Date.now(), dead) === "pending") throw webhooksErrors.WEBHOOKS_DELIVERY_FAILED({
|
|
624
|
+
reason: result.failure,
|
|
625
|
+
webhook: claim.webhook
|
|
626
|
+
});
|
|
627
|
+
}
|
|
628
|
+
function resolveFileTarget(installed, name) {
|
|
629
|
+
const definition = installed.webhooks.get(name);
|
|
630
|
+
if (!definition) return [`No webhook is named ${JSON.stringify(name)} in this build.`, void 0];
|
|
631
|
+
const [error, target] = resolveTarget(name, definition);
|
|
632
|
+
return error ? [error.message, void 0] : [void 0, target];
|
|
633
|
+
}
|
|
634
|
+
async function postWithCheckedAddresses(url, addresses, body, headers, signal) {
|
|
635
|
+
const { request } = await import("node:https");
|
|
636
|
+
return new Promise((resolve, reject) => {
|
|
637
|
+
const outgoing = request(url, {
|
|
638
|
+
agent: false,
|
|
639
|
+
method: "POST",
|
|
640
|
+
headers: {
|
|
641
|
+
...headers,
|
|
642
|
+
"content-length": String(Buffer.byteLength(body))
|
|
643
|
+
},
|
|
644
|
+
signal,
|
|
645
|
+
lookup(_hostname, options, callback) {
|
|
646
|
+
const candidates = addresses.filter((address) => !options.family || address.family === options.family);
|
|
647
|
+
const first = candidates[0];
|
|
648
|
+
if (!first) callback(/* @__PURE__ */ new Error("No checked address matches the requested family."), "", 0);
|
|
649
|
+
else if (options.all) callback(null, candidates);
|
|
650
|
+
else callback(null, first.address, first.family);
|
|
651
|
+
}
|
|
652
|
+
}, (response) => {
|
|
653
|
+
const status = response.statusCode ?? 0;
|
|
654
|
+
response.destroy();
|
|
655
|
+
resolve(status);
|
|
656
|
+
});
|
|
657
|
+
outgoing.on("error", reject);
|
|
658
|
+
outgoing.end(body);
|
|
659
|
+
});
|
|
660
|
+
}
|
|
661
|
+
/** Posts a claimed delivery once, signed, with a 10 second timeout and no redirects. */
|
|
662
|
+
async function postDelivery(claim, target, developmentKey) {
|
|
663
|
+
let checked;
|
|
664
|
+
if (target.guard) {
|
|
665
|
+
const [refused, resolved] = await resolveWebhookUrl(target.url);
|
|
666
|
+
if (refused) return {
|
|
667
|
+
ok: false,
|
|
668
|
+
status: null,
|
|
669
|
+
failure: refused.message,
|
|
670
|
+
final: true
|
|
671
|
+
};
|
|
672
|
+
checked = resolved;
|
|
673
|
+
}
|
|
674
|
+
const sealed = sealedMemberBody(claim);
|
|
675
|
+
let body = JSON.stringify(claim.body);
|
|
676
|
+
if (sealed !== void 0) {
|
|
677
|
+
const [error, opened] = await unsealWebhooksText(memberBodyLabel(claim.webhook, claim.event), sealed, developmentKey);
|
|
678
|
+
if (error) return {
|
|
679
|
+
ok: false,
|
|
680
|
+
status: null,
|
|
681
|
+
failure: error.message,
|
|
682
|
+
final: true
|
|
683
|
+
};
|
|
684
|
+
body = opened;
|
|
685
|
+
}
|
|
686
|
+
try {
|
|
687
|
+
const headers = {
|
|
688
|
+
...await signWebhook(body, {
|
|
689
|
+
provider: target.signature,
|
|
690
|
+
secret: target.secret
|
|
691
|
+
}),
|
|
692
|
+
"content-type": "application/json",
|
|
693
|
+
"user-agent": "ViteHub-Webhooks",
|
|
694
|
+
"x-vitehub-delivery": claim.id,
|
|
695
|
+
"x-vitehub-event": claim.event,
|
|
696
|
+
"x-vitehub-events": String(claim.count)
|
|
697
|
+
};
|
|
698
|
+
const signal = AbortSignal.timeout(webhookTimeoutMs);
|
|
699
|
+
let status;
|
|
700
|
+
if (checked?.addresses) status = await postWithCheckedAddresses(checked.url, checked.addresses, body, headers, signal);
|
|
701
|
+
else {
|
|
702
|
+
const response = await fetch(checked?.url ?? target.url, {
|
|
703
|
+
method: "POST",
|
|
704
|
+
body,
|
|
705
|
+
headers,
|
|
706
|
+
redirect: "manual",
|
|
707
|
+
signal
|
|
708
|
+
});
|
|
709
|
+
await response.body?.cancel().catch(() => {});
|
|
710
|
+
status = response.status;
|
|
711
|
+
}
|
|
712
|
+
return status >= 200 && status < 300 ? {
|
|
713
|
+
ok: true,
|
|
714
|
+
status
|
|
715
|
+
} : {
|
|
716
|
+
ok: false,
|
|
717
|
+
status,
|
|
718
|
+
failure: `HTTP ${status}`,
|
|
719
|
+
final: false
|
|
720
|
+
};
|
|
721
|
+
} catch (error) {
|
|
722
|
+
return {
|
|
723
|
+
ok: false,
|
|
724
|
+
status: null,
|
|
725
|
+
failure: describeFailure(error),
|
|
726
|
+
final: false
|
|
727
|
+
};
|
|
728
|
+
}
|
|
729
|
+
}
|
|
730
|
+
const deliveryErrorCodes = [
|
|
731
|
+
"WEBHOOKS_DATABASE_MISSING",
|
|
732
|
+
"WEBHOOKS_DELIVERY_ACTIVE",
|
|
733
|
+
"WEBHOOKS_DELIVERY_NOT_FOUND",
|
|
734
|
+
"WEBHOOKS_DELIVERY_NOT_OWNER",
|
|
735
|
+
"WEBHOOKS_DELIVERY_NOT_PENDING",
|
|
736
|
+
"WEBHOOKS_ENDPOINT_DISABLED",
|
|
737
|
+
"WEBHOOKS_ENDPOINT_NOT_FOUND",
|
|
738
|
+
"WEBHOOKS_KEY_INVALID",
|
|
739
|
+
"WEBHOOKS_KEY_UNSET",
|
|
740
|
+
"WEBHOOKS_STORE_FAILED",
|
|
741
|
+
"WEBHOOKS_WAKE_FAILED"
|
|
742
|
+
];
|
|
743
|
+
function isDeliveryError(error) {
|
|
744
|
+
return webhooksErrors.is(error) && deliveryErrorCodes.includes(error.code);
|
|
745
|
+
}
|
|
746
|
+
async function attempt(run) {
|
|
747
|
+
const installed = requireInstalled();
|
|
748
|
+
try {
|
|
749
|
+
return [void 0, await run(installed)];
|
|
750
|
+
} catch (error) {
|
|
751
|
+
if (isDeliveryError(error)) return [error, void 0];
|
|
752
|
+
throw error;
|
|
753
|
+
}
|
|
754
|
+
}
|
|
755
|
+
/** Every webhook of the app, with the names of its variables and whether they are set. */
|
|
756
|
+
function listWebhooks() {
|
|
757
|
+
const installed = requireInstalled();
|
|
758
|
+
const env = serverEnv();
|
|
759
|
+
return [...installed.webhooks].sort(([left], [right]) => left.localeCompare(right)).map(([name, definition]) => {
|
|
760
|
+
const url = readString(env, definition.url);
|
|
761
|
+
return {
|
|
762
|
+
name,
|
|
763
|
+
url: definition.url,
|
|
764
|
+
secret: definition.secret,
|
|
765
|
+
signature: definition.signature,
|
|
766
|
+
debounceMs: definition.debounceMs,
|
|
767
|
+
events: definition.events,
|
|
768
|
+
urlSet: url !== void 0,
|
|
769
|
+
secretSet: readString(env, definition.secret) !== void 0,
|
|
770
|
+
host: url !== void 0 && URL.canParse(url) ? new URL(url).host || null : null
|
|
771
|
+
};
|
|
772
|
+
});
|
|
773
|
+
}
|
|
774
|
+
/** Deliveries, newest first. */
|
|
775
|
+
function listWebhookDeliveries(options) {
|
|
776
|
+
return attempt(async (installed) => (await installed.store.list(options)).map(inspectDelivery));
|
|
777
|
+
}
|
|
778
|
+
/** Pending deliveries, the soonest due first: the debounce timers that run now. */
|
|
779
|
+
function listPendingWebhookDeliveries(options) {
|
|
780
|
+
return attempt(async (installed) => (await installed.store.pending(options)).map(inspectDelivery));
|
|
781
|
+
}
|
|
782
|
+
async function findDelivery(installed, id) {
|
|
783
|
+
const delivery = await installed.store.get(id);
|
|
784
|
+
if (!delivery) throw webhooksErrors.WEBHOOKS_DELIVERY_NOT_FOUND({ id: JSON.stringify(id) });
|
|
785
|
+
return delivery;
|
|
786
|
+
}
|
|
787
|
+
function getWebhookDelivery(id) {
|
|
788
|
+
return attempt(async (installed) => inspectDelivery(await findDelivery(installed, id)));
|
|
789
|
+
}
|
|
790
|
+
function sealedMemberBody(delivery) {
|
|
791
|
+
if (delivery.webhook.startsWith("@") && typeof delivery.body === "string" && delivery.body.startsWith("vitehub:sealed-member-body:")) return delivery.body.slice(27);
|
|
792
|
+
}
|
|
793
|
+
function inspectDelivery(delivery) {
|
|
794
|
+
return sealedMemberBody(delivery) === void 0 ? delivery : {
|
|
795
|
+
...delivery,
|
|
796
|
+
body: null
|
|
797
|
+
};
|
|
798
|
+
}
|
|
799
|
+
/** The member endpoint of a member delivery, when `caller` owns it. Throws the error that the action returns. */
|
|
800
|
+
async function ownedMemberEndpoint(installed, delivery, options) {
|
|
801
|
+
const id = delivery.webhook.slice(1);
|
|
802
|
+
const endpoint = await installed.endpoints?.find(id);
|
|
803
|
+
if (!endpoint) throw webhooksErrors.WEBHOOKS_ENDPOINT_NOT_FOUND({ match: `the id ${JSON.stringify(id)}` });
|
|
804
|
+
if (!ownsMemberEndpoint(endpoint, options.resolveCaller ? await options.resolveCaller() : options.caller)) throw webhooksErrors.WEBHOOKS_DELIVERY_NOT_OWNER({ id: JSON.stringify(delivery.id) });
|
|
805
|
+
return endpoint;
|
|
806
|
+
}
|
|
807
|
+
/**
|
|
808
|
+
* Delivers a pending delivery now, without the rest of its debounce. A pending member delivery, which waits for a
|
|
809
|
+
* Queue retry, goes out only for its owner, so pass `caller`.
|
|
810
|
+
*/
|
|
811
|
+
function flushWebhookDelivery(id, options = {}) {
|
|
812
|
+
return attempt(async (installed) => {
|
|
813
|
+
const current = await findDelivery(installed, id);
|
|
814
|
+
if (current.webhook.startsWith("@")) {
|
|
815
|
+
const endpoint = await ownedMemberEndpoint(installed, current, options);
|
|
816
|
+
if (endpoint.disabledAt !== null) throw webhooksErrors.WEBHOOKS_ENDPOINT_DISABLED({ id: endpoint.id });
|
|
817
|
+
}
|
|
818
|
+
const delivery = await installed.store.due(id, Date.now());
|
|
819
|
+
if (!delivery) {
|
|
820
|
+
const current = await findDelivery(installed, id);
|
|
821
|
+
throw webhooksErrors.WEBHOOKS_DELIVERY_NOT_PENDING({
|
|
822
|
+
id: JSON.stringify(id),
|
|
823
|
+
state: current.state
|
|
824
|
+
});
|
|
825
|
+
}
|
|
826
|
+
const error = await wake(installed, delivery, 0);
|
|
827
|
+
if (error) throw error;
|
|
828
|
+
return inspectDelivery(delivery);
|
|
829
|
+
});
|
|
830
|
+
}
|
|
831
|
+
/** Cancels a pending delivery. Its wake then does nothing. */
|
|
832
|
+
function cancelWebhookDelivery(id) {
|
|
833
|
+
return attempt(async (installed) => {
|
|
834
|
+
const delivery = await installed.store.cancel(id, Date.now());
|
|
835
|
+
if (delivery) return inspectDelivery(delivery);
|
|
836
|
+
const current = await findDelivery(installed, id);
|
|
837
|
+
throw webhooksErrors.WEBHOOKS_DELIVERY_NOT_PENDING({
|
|
838
|
+
id: JSON.stringify(id),
|
|
839
|
+
state: current.state
|
|
840
|
+
});
|
|
841
|
+
});
|
|
842
|
+
}
|
|
843
|
+
/**
|
|
844
|
+
* Sends a sent, dead, or cancelled delivery again, now, as a new delivery with a new id. It keeps the body, the event,
|
|
845
|
+
* and the count. The webhook must still exist.
|
|
846
|
+
*
|
|
847
|
+
* A delivery to a member endpoint goes out again only for the owner of the endpoint, so pass `caller`. Anyone else gets
|
|
848
|
+
* `WEBHOOKS_DELIVERY_NOT_OWNER`. It posts in the request, as `sendToMemberEndpoint()` does, and returns its status.
|
|
849
|
+
*/
|
|
850
|
+
function redeliverWebhookDelivery(id, options = {}) {
|
|
851
|
+
return attempt(async (installed) => {
|
|
852
|
+
const source = await findDelivery(installed, id);
|
|
853
|
+
const endpoint = source.webhook.startsWith("@") ? await ownedMemberEndpoint(installed, source, options) : void 0;
|
|
854
|
+
if (source.state === "pending" || source.state === "sending") throw webhooksErrors.WEBHOOKS_DELIVERY_ACTIVE({
|
|
855
|
+
id: JSON.stringify(id),
|
|
856
|
+
state: source.state
|
|
857
|
+
});
|
|
858
|
+
if (endpoint) return await redeliverToMember(installed, source, endpoint);
|
|
859
|
+
if (!installed.webhooks.has(source.webhook)) throw webhooksErrors.WEBHOOKS_NOT_FOUND({ name: JSON.stringify(source.webhook) });
|
|
860
|
+
const now = Date.now();
|
|
861
|
+
const recorded = await installed.store.record({
|
|
862
|
+
id: createDeliveryId(),
|
|
863
|
+
webhook: source.webhook,
|
|
864
|
+
key: null,
|
|
865
|
+
event: source.event,
|
|
866
|
+
body: JSON.stringify(source.body),
|
|
867
|
+
count: source.count,
|
|
868
|
+
dueAt: now,
|
|
869
|
+
now
|
|
870
|
+
});
|
|
871
|
+
const error = await wake(installed, {
|
|
872
|
+
...recorded,
|
|
873
|
+
webhook: source.webhook
|
|
874
|
+
}, 0);
|
|
875
|
+
if (error) throw error;
|
|
876
|
+
return {
|
|
877
|
+
id: recorded.id,
|
|
878
|
+
status: "pending"
|
|
879
|
+
};
|
|
880
|
+
});
|
|
881
|
+
}
|
|
882
|
+
async function redeliverToMember(installed, source, endpoint) {
|
|
883
|
+
if (endpoint.disabledAt !== null) throw webhooksErrors.WEBHOOKS_ENDPOINT_DISABLED({ id: endpoint.id });
|
|
884
|
+
let target;
|
|
885
|
+
if (endpoint.sealed !== null) {
|
|
886
|
+
const [keyError, opened] = await unsealEndpoint({
|
|
887
|
+
...endpoint,
|
|
888
|
+
sealed: endpoint.sealed
|
|
889
|
+
}, installed.developmentKey);
|
|
890
|
+
if (keyError) throw keyError;
|
|
891
|
+
target = opened;
|
|
892
|
+
}
|
|
893
|
+
const now = Date.now();
|
|
894
|
+
const recorded = await installed.store.record({
|
|
895
|
+
id: createDeliveryId(),
|
|
896
|
+
webhook: source.webhook,
|
|
897
|
+
owner: endpoint.owner,
|
|
898
|
+
key: null,
|
|
899
|
+
event: source.event,
|
|
900
|
+
body: JSON.stringify(source.body),
|
|
901
|
+
count: source.count,
|
|
902
|
+
dueAt: now,
|
|
903
|
+
now
|
|
904
|
+
});
|
|
905
|
+
const claim = await installed.store.claim(recorded.id, recorded.revision, now, 0);
|
|
906
|
+
if (!claim) return {
|
|
907
|
+
id: recorded.id,
|
|
908
|
+
status: "pending"
|
|
909
|
+
};
|
|
910
|
+
const [wakeError, result] = await deliverMemberClaim(installed, claim, target);
|
|
911
|
+
if (wakeError) throw wakeError;
|
|
912
|
+
return result;
|
|
913
|
+
}
|
|
914
|
+
export { sealedMemberBodyPrefix as A, webhookTestEvent as C, memberBodyLabel as D, outsideHosts as E, unsealWebhooksText as M, defineWebhook as N, sealEndpoint as O, webhookMaxAttempts as S, checkWebhookUrl as T, requireMemberEndpoints as _, flushWebhookDelivery as a, testWebhook as b, installWebhooks as c, listWebhookDeliveries as d, listWebhooks as f, redeliverWebhookDelivery as g, postDelivery as h, deliverWebhookWake as i, unsealEndpoint as j, sealWebhooksText as k, installedWebhooks as l, ownsMemberEndpoint as m, createDeliveryId as n, getWebhookDelivery as o, memberWebhookPrefix as p, deliverMemberClaim as r, inspectDelivery as s, cancelWebhookDelivery as t, listPendingWebhookDeliveries as u, selectDefaultDatabase as v, webhookTimeoutMs as w, wake as x, sendDynamicWebhook as y };
|