@weft-framework/server 0.0.0-stage → 0.0.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.
Files changed (175) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +4 -2
  3. package/dist/account.d.ts +124 -0
  4. package/dist/account.js +344 -0
  5. package/dist/action.d.ts +43 -0
  6. package/dist/action.js +135 -0
  7. package/dist/admin.d.ts +99 -0
  8. package/dist/admin.js +431 -0
  9. package/dist/api.d.ts +21 -0
  10. package/dist/api.js +72 -0
  11. package/dist/app.d.ts +202 -0
  12. package/dist/app.js +3692 -0
  13. package/dist/assets.d.ts +4 -0
  14. package/dist/assets.js +91 -0
  15. package/dist/auth.d.ts +150 -0
  16. package/dist/auth.js +215 -0
  17. package/dist/backup.d.ts +46 -0
  18. package/dist/backup.js +345 -0
  19. package/dist/build.d.ts +33 -0
  20. package/dist/build.js +274 -0
  21. package/dist/bun.d.ts +30 -0
  22. package/dist/bun.js +53 -0
  23. package/dist/calendar.d.ts +161 -0
  24. package/dist/calendar.js +690 -0
  25. package/dist/compiler.d.ts +13 -0
  26. package/dist/compiler.js +58 -0
  27. package/dist/compress.d.ts +6 -0
  28. package/dist/compress.js +78 -0
  29. package/dist/config.d.ts +26 -0
  30. package/dist/config.js +317 -0
  31. package/dist/context.d.ts +9 -0
  32. package/dist/context.js +1 -0
  33. package/dist/contract.d.ts +18 -0
  34. package/dist/contract.js +171 -0
  35. package/dist/datamap.d.ts +24 -0
  36. package/dist/datamap.js +365 -0
  37. package/dist/db-backup.d.ts +27 -0
  38. package/dist/db-backup.js +115 -0
  39. package/dist/dev-events.d.ts +14 -0
  40. package/dist/dev-events.js +135 -0
  41. package/dist/dev.d.ts +1 -0
  42. package/dist/dev.js +240 -0
  43. package/dist/devtools-client.d.ts +1 -0
  44. package/dist/devtools-client.js +362 -0
  45. package/dist/devtools.d.ts +87 -0
  46. package/dist/devtools.js +68 -0
  47. package/dist/edge.d.ts +3 -0
  48. package/dist/edge.js +7 -0
  49. package/dist/email-signin.d.ts +92 -0
  50. package/dist/email-signin.js +259 -0
  51. package/dist/env.d.ts +1 -0
  52. package/dist/env.js +15 -0
  53. package/dist/explain.d.ts +12 -0
  54. package/dist/explain.js +217 -0
  55. package/dist/files.d.ts +6 -0
  56. package/dist/files.js +170 -0
  57. package/dist/grants.d.ts +69 -0
  58. package/dist/grants.js +206 -0
  59. package/dist/image/bitmap.d.ts +11 -0
  60. package/dist/image/bitmap.js +172 -0
  61. package/dist/image/jpeg.d.ts +10 -0
  62. package/dist/image/jpeg.js +697 -0
  63. package/dist/image/png.d.ts +8 -0
  64. package/dist/image/png.js +282 -0
  65. package/dist/image/transform.d.ts +20 -0
  66. package/dist/image/transform.js +52 -0
  67. package/dist/image/worker.d.ts +1 -0
  68. package/dist/image/worker.js +11 -0
  69. package/dist/images.d.ts +39 -0
  70. package/dist/images.js +283 -0
  71. package/dist/index.d.ts +64 -0
  72. package/dist/index.js +31 -0
  73. package/dist/inspect-hub.d.ts +42 -0
  74. package/dist/inspect-hub.js +14 -0
  75. package/dist/inspector.d.ts +51 -0
  76. package/dist/inspector.js +193 -0
  77. package/dist/job-admin.d.ts +55 -0
  78. package/dist/job-admin.js +89 -0
  79. package/dist/jobs.d.ts +222 -0
  80. package/dist/jobs.js +789 -0
  81. package/dist/live.d.ts +72 -0
  82. package/dist/live.js +481 -0
  83. package/dist/load-config.d.ts +2 -0
  84. package/dist/load-config.js +41 -0
  85. package/dist/log.d.ts +20 -0
  86. package/dist/log.js +143 -0
  87. package/dist/mail.d.ts +189 -0
  88. package/dist/mail.js +999 -0
  89. package/dist/media.d.ts +129 -0
  90. package/dist/media.js +470 -0
  91. package/dist/meta.d.ts +54 -0
  92. package/dist/meta.js +146 -0
  93. package/dist/middleware.d.ts +20 -0
  94. package/dist/middleware.js +101 -0
  95. package/dist/migrate.d.ts +12 -0
  96. package/dist/migrate.js +88 -0
  97. package/dist/node.d.ts +26 -0
  98. package/dist/node.js +96 -0
  99. package/dist/notice.d.ts +21 -0
  100. package/dist/notice.js +48 -0
  101. package/dist/npm.d.ts +16 -0
  102. package/dist/npm.js +347 -0
  103. package/dist/oauth.d.ts +76 -0
  104. package/dist/oauth.js +408 -0
  105. package/dist/otel.d.ts +57 -0
  106. package/dist/otel.js +293 -0
  107. package/dist/passkey.d.ts +99 -0
  108. package/dist/passkey.js +572 -0
  109. package/dist/password.d.ts +8 -0
  110. package/dist/password.js +65 -0
  111. package/dist/pdf.d.ts +46 -0
  112. package/dist/pdf.js +332 -0
  113. package/dist/personal-data.d.ts +22 -0
  114. package/dist/personal-data.js +148 -0
  115. package/dist/pointers.d.ts +9 -0
  116. package/dist/pointers.js +148 -0
  117. package/dist/postcss.d.ts +3 -0
  118. package/dist/postcss.js +89 -0
  119. package/dist/presence.d.ts +27 -0
  120. package/dist/presence.js +161 -0
  121. package/dist/preview.d.ts +25 -0
  122. package/dist/preview.js +353 -0
  123. package/dist/production.d.ts +16 -0
  124. package/dist/production.js +119 -0
  125. package/dist/project.d.ts +23 -0
  126. package/dist/project.js +536 -0
  127. package/dist/regions.d.ts +47 -0
  128. package/dist/regions.js +511 -0
  129. package/dist/replay.d.ts +44 -0
  130. package/dist/replay.js +259 -0
  131. package/dist/router.d.ts +29 -0
  132. package/dist/router.js +146 -0
  133. package/dist/rules-diff.d.ts +18 -0
  134. package/dist/rules-diff.js +165 -0
  135. package/dist/rules-test.d.ts +17 -0
  136. package/dist/rules-test.js +108 -0
  137. package/dist/saml.d.ts +160 -0
  138. package/dist/saml.js +959 -0
  139. package/dist/seal.d.ts +35 -0
  140. package/dist/seal.js +107 -0
  141. package/dist/secret.d.ts +14 -0
  142. package/dist/secret.js +110 -0
  143. package/dist/security.d.ts +53 -0
  144. package/dist/security.js +250 -0
  145. package/dist/seed.d.ts +16 -0
  146. package/dist/seed.js +94 -0
  147. package/dist/seo.d.ts +42 -0
  148. package/dist/seo.js +175 -0
  149. package/dist/settings.d.ts +79 -0
  150. package/dist/settings.js +212 -0
  151. package/dist/shared.d.ts +15 -0
  152. package/dist/shared.js +283 -0
  153. package/dist/shell.d.ts +12 -0
  154. package/dist/shell.js +118 -0
  155. package/dist/storage.d.ts +13 -0
  156. package/dist/storage.js +55 -0
  157. package/dist/support.d.ts +83 -0
  158. package/dist/support.js +236 -0
  159. package/dist/sync.d.ts +35 -0
  160. package/dist/sync.js +167 -0
  161. package/dist/tailwind.d.ts +14 -0
  162. package/dist/tailwind.js +117 -0
  163. package/dist/two-factor.d.ts +103 -0
  164. package/dist/two-factor.js +435 -0
  165. package/dist/uploads.d.ts +185 -0
  166. package/dist/uploads.js +991 -0
  167. package/dist/webhooks.d.ts +169 -0
  168. package/dist/webhooks.js +758 -0
  169. package/dist/webpush.d.ts +97 -0
  170. package/dist/webpush.js +372 -0
  171. package/dist/wizard.d.ts +141 -0
  172. package/dist/wizard.js +410 -0
  173. package/dist/workflows.d.ts +134 -0
  174. package/dist/workflows.js +511 -0
  175. package/package.json +186 -4
@@ -0,0 +1,758 @@
1
+ import { defineJob, JobError } from "./jobs.js";
2
+ import { isSecret } from "./secret.js";
3
+ import { MIN_SECRET_LENGTH } from "./security.js";
4
+ const utf8 = new TextEncoder();
5
+ export class MemoryWebhookStore {
6
+ #docs = new Map();
7
+ #seq = 0;
8
+ put(kind, id, owner, ref, created, data) {
9
+ const k = `${kind}:${id}`;
10
+ const seq = this.#docs.get(k)?.seq ?? ++this.#seq;
11
+ this.#docs.set(k, { kind, id, owner, ref, created, seq, data });
12
+ }
13
+ get(kind, id) {
14
+ return this.#docs.get(`${kind}:${id}`)?.data ?? null;
15
+ }
16
+ list(kind, owner, o) {
17
+ return [...this.#docs.values()]
18
+ .filter((d) => d.kind === kind && d.owner === owner && (o.ref === undefined || d.ref === o.ref) && (o.before === undefined || d.created < o.before))
19
+ .sort((a, b) => b.created - a.created || b.seq - a.seq)
20
+ .slice(0, o.limit)
21
+ .map((d) => d.data);
22
+ }
23
+ remove(kind, id) {
24
+ this.#docs.delete(`${kind}:${id}`);
25
+ }
26
+ sweep(kind, before, owner) {
27
+ let n = 0;
28
+ for (const [k, d] of this.#docs) {
29
+ if (d.kind === kind && d.created < before && (owner === undefined || d.owner === owner)) {
30
+ this.#docs.delete(k);
31
+ n++;
32
+ }
33
+ }
34
+ return n;
35
+ }
36
+ }
37
+ export class SqlWebhookStore {
38
+ #db;
39
+ #t;
40
+ constructor(db, table = "weft_webhooks") {
41
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(table))
42
+ throw new Error(`@weft-framework/server: not a valid table name: ${table}`);
43
+ this.#db = db;
44
+ this.#t = `"${table}"`;
45
+ db.exec(`CREATE TABLE IF NOT EXISTS ${this.#t} (kind TEXT NOT NULL, id TEXT NOT NULL, owner TEXT NOT NULL, ref TEXT, ` +
46
+ `created INTEGER NOT NULL, data TEXT NOT NULL, PRIMARY KEY (kind, id))`);
47
+ db.exec(`CREATE INDEX IF NOT EXISTS "${table}_owner" ON ${this.#t} (kind, owner, created)`);
48
+ }
49
+ put(kind, id, owner, ref, created, data) {
50
+ this.#db
51
+ .prepare(`INSERT INTO ${this.#t} (kind, id, owner, ref, created, data) VALUES (?, ?, ?, ?, ?, ?) ` +
52
+ `ON CONFLICT (kind, id) DO UPDATE SET data = excluded.data`)
53
+ .run(kind, id, owner, ref, created, data);
54
+ }
55
+ get(kind, id) {
56
+ const r = this.#db.prepare(`SELECT data FROM ${this.#t} WHERE kind = ? AND id = ?`).all(kind, id)[0];
57
+ return r ? String(r.data) : null;
58
+ }
59
+ list(kind, owner, o) {
60
+ const where = ["kind = ?", "owner = ?"];
61
+ const args = [kind, owner];
62
+ if (o.ref !== undefined)
63
+ (where.push("ref = ?"), args.push(o.ref));
64
+ if (o.before !== undefined)
65
+ (where.push("created < ?"), args.push(o.before));
66
+ const rows = this.#db
67
+ .prepare(`SELECT data FROM ${this.#t} WHERE ${where.join(" AND ")} ORDER BY created DESC, rowid DESC LIMIT ?`)
68
+ .all(...args, o.limit);
69
+ return rows.map((r) => String(r.data));
70
+ }
71
+ remove(kind, id) {
72
+ this.#db.prepare(`DELETE FROM ${this.#t} WHERE kind = ? AND id = ?`).run(kind, id);
73
+ }
74
+ sweep(kind, before, owner) {
75
+ const r = owner === undefined
76
+ ? this.#db.prepare(`DELETE FROM ${this.#t} WHERE kind = ? AND created < ? RETURNING id`).all(kind, before)
77
+ : this.#db.prepare(`DELETE FROM ${this.#t} WHERE kind = ? AND created < ? AND owner = ? RETURNING id`).all(kind, before, owner);
78
+ return r.length;
79
+ }
80
+ }
81
+ function v4Parts(ip) {
82
+ const m = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(ip);
83
+ if (!m)
84
+ return null;
85
+ const p = m.slice(1).map(Number);
86
+ return p.every((x) => x <= 255) ? p : null;
87
+ }
88
+ function v4Public(p) {
89
+ const [a, b, c] = p;
90
+ if (a === 0 || a === 10 || a === 127 || a >= 224)
91
+ return false;
92
+ if (a === 100 && b >= 64 && b <= 127)
93
+ return false;
94
+ if (a === 169 && b === 254)
95
+ return false;
96
+ if (a === 172 && b >= 16 && b <= 31)
97
+ return false;
98
+ if (a === 192 && b === 168)
99
+ return false;
100
+ if (a === 192 && b === 0 && (c === 0 || c === 2))
101
+ return false;
102
+ if (a === 192 && b === 88 && c === 99)
103
+ return false;
104
+ if (a === 198 && (b === 18 || b === 19))
105
+ return false;
106
+ if (a === 198 && b === 51 && c === 100)
107
+ return false;
108
+ if (a === 203 && b === 0 && c === 113)
109
+ return false;
110
+ return true;
111
+ }
112
+ function v6Groups(ip) {
113
+ let s = ip.toLowerCase();
114
+ if (s.startsWith("[") && s.endsWith("]"))
115
+ s = s.slice(1, -1);
116
+ if (s.includes("%"))
117
+ return null;
118
+ let tail = [];
119
+ const lastColon = s.lastIndexOf(":");
120
+ if (s.slice(lastColon + 1).includes(".")) {
121
+ const v4 = v4Parts(s.slice(lastColon + 1));
122
+ if (!v4)
123
+ return null;
124
+ tail = [(v4[0] << 8) | v4[1], (v4[2] << 8) | v4[3]];
125
+ s = s.slice(0, lastColon + 1) + "0";
126
+ s = s.endsWith("::0") ? s.slice(0, -1) : s.slice(0, -2);
127
+ if (s.endsWith(":") && !s.endsWith("::"))
128
+ s = s.slice(0, -1);
129
+ }
130
+ const halves = s.split("::");
131
+ if (halves.length > 2)
132
+ return null;
133
+ const parse = (h) => (h === "" ? [] : h.split(":").map((g) => (/^[0-9a-f]{1,4}$/.test(g) ? parseInt(g, 16) : NaN)));
134
+ const head = parse(halves[0]);
135
+ const back = halves.length === 2 ? parse(halves[1]) : [];
136
+ if ([...head, ...back].some(Number.isNaN))
137
+ return null;
138
+ const want = 8 - tail.length;
139
+ if (halves.length === 1) {
140
+ if (head.length !== want)
141
+ return null;
142
+ return [...head, ...tail];
143
+ }
144
+ const fill = want - head.length - back.length;
145
+ if (fill < 1)
146
+ return null;
147
+ return [...head, ...new Array(fill).fill(0), ...back, ...tail];
148
+ }
149
+ export function isPublicAddress(ip) {
150
+ if (typeof ip !== "string")
151
+ return false;
152
+ const v4 = v4Parts(ip);
153
+ if (v4)
154
+ return v4Public(v4);
155
+ const g = v6Groups(ip);
156
+ if (!g)
157
+ return false;
158
+ const embedded = () => [g[6] >> 8, g[6] & 255, g[7] >> 8, g[7] & 255];
159
+ if (g.slice(0, 5).every((x) => x === 0) && (g[5] === 0xffff || g[5] === 0)) {
160
+ return g[5] === 0xffff ? v4Public(embedded()) : false;
161
+ }
162
+ if ((g[0] & 0xe000) !== 0x2000)
163
+ return false;
164
+ if (g[0] === 0x2001 && g[1] < 0x200)
165
+ return false;
166
+ if (g[0] === 0x2001 && g[1] === 0xdb8)
167
+ return false;
168
+ if (g[0] === 0x2002)
169
+ return false;
170
+ if (g[0] === 0x3fff && g[1] < 0x1000)
171
+ return false;
172
+ return true;
173
+ }
174
+ function isIpLiteral(host) {
175
+ return v4Parts(host) !== null || v6Groups(host) !== null;
176
+ }
177
+ export class WebhookError extends Error {
178
+ code;
179
+ constructor(code, message) {
180
+ super(message);
181
+ this.name = "WebhookError";
182
+ this.code = code;
183
+ }
184
+ }
185
+ function b64(b) {
186
+ let s = "";
187
+ for (const x of b)
188
+ s += String.fromCharCode(x);
189
+ return btoa(s);
190
+ }
191
+ function fromB64(s) {
192
+ const bin = atob(s);
193
+ const out = new Uint8Array(bin.length);
194
+ for (let i = 0; i < bin.length; i++)
195
+ out[i] = bin.charCodeAt(i);
196
+ return out;
197
+ }
198
+ function secretBytes(secret) {
199
+ if (typeof secret !== "string" || !/^whsec_[A-Za-z0-9+/]+={0,2}$/.test(secret))
200
+ throw new WebhookError("invalid", "a webhook secret starts with whsec_");
201
+ const b = fromB64(secret.slice(6));
202
+ if (b.length < 16 || b.length > 64)
203
+ throw new WebhookError("invalid", "a webhook secret is 16 to 64 bytes");
204
+ return b;
205
+ }
206
+ async function hmac(secret, content) {
207
+ const key = await crypto.subtle.importKey("raw", secretBytes(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
208
+ return new Uint8Array(await crypto.subtle.sign("HMAC", key, utf8.encode(content)));
209
+ }
210
+ export async function signWebhook(secrets, id, timestamp, body) {
211
+ const parts = [];
212
+ for (const s of secrets)
213
+ parts.push(`v1,${b64(await hmac(s, `${id}.${timestamp}.${body}`))}`);
214
+ return parts.join(" ");
215
+ }
216
+ function equal(a, b) {
217
+ if (a.length !== b.length)
218
+ return false;
219
+ let d = 0;
220
+ for (let i = 0; i < a.length; i++)
221
+ d |= a[i] ^ b[i];
222
+ return d === 0;
223
+ }
224
+ export async function verifyWebhook(secret, headers, body, o = {}) {
225
+ const h = (n) => (headers instanceof Headers ? headers.get(n) : (headers[n] ?? null)) ?? null;
226
+ const id = h("webhook-id");
227
+ const ts = h("webhook-timestamp");
228
+ const sig = h("webhook-signature");
229
+ if (!id || !ts || !sig || !/^\d{1,12}$/.test(ts))
230
+ throw new WebhookError("invalid", "missing webhook headers");
231
+ const now = Math.floor((o.now ?? Date.now()) / 1000);
232
+ if (Math.abs(now - Number(ts)) > (o.toleranceSec ?? 300))
233
+ throw new WebhookError("invalid", "webhook timestamp too far from now");
234
+ const want = await hmac(secret, `${id}.${ts}.${body}`);
235
+ let ok = false;
236
+ for (const entry of sig.split(" ")) {
237
+ const [v, s] = entry.split(",", 2);
238
+ if (v !== "v1" || !s)
239
+ continue;
240
+ let got;
241
+ try {
242
+ got = fromB64(s);
243
+ }
244
+ catch {
245
+ continue;
246
+ }
247
+ if (equal(got, want))
248
+ ok = true;
249
+ }
250
+ if (!ok)
251
+ throw new WebhookError("invalid", "webhook signature does not match");
252
+ return JSON.parse(body);
253
+ }
254
+ function newSecret() {
255
+ return `whsec_${b64(crypto.getRandomValues(new Uint8Array(24)))}`;
256
+ }
257
+ function randomId(prefix) {
258
+ const b = crypto.getRandomValues(new Uint8Array(16));
259
+ return prefix + [...b].map((x) => x.toString(16).padStart(2, "0")).join("");
260
+ }
261
+ const RESPONSE_LIMIT = 2048;
262
+ export function nodeTransport(o = {}) {
263
+ return async (req) => {
264
+ const u = new URL(req.url);
265
+ const mod = u.protocol === "https:" ? await import("node:https") : await import("node:http");
266
+ const dns = await import("node:dns");
267
+ const resolve = o.lookup ?? ((host) => dns.promises.lookup(host, { all: true, verbatim: true }));
268
+ const host = u.hostname.replace(/^\[|\]$/g, "");
269
+ if (isIpLiteral(host) && !o.allowPrivateNetworks && !isPublicAddress(host)) {
270
+ throw new WebhookError("address", `${host} is not a public address`);
271
+ }
272
+ const lookup = (hostname, opts, cb) => {
273
+ resolve(hostname).then((addrs) => {
274
+ if (addrs.length === 0)
275
+ return cb(new WebhookError("address", `${hostname} does not resolve`), "");
276
+ const bad = addrs.find((a) => !isPublicAddress(a.address));
277
+ if (bad && !o.allowPrivateNetworks) {
278
+ return cb(new WebhookError("address", `${hostname} resolves to ${bad.address}, not a public address`), "");
279
+ }
280
+ if (typeof opts === "object" && opts.all)
281
+ return cb(null, addrs);
282
+ cb(null, addrs[0].address, addrs[0].family);
283
+ }, (err) => cb(err, ""));
284
+ };
285
+ return new Promise((resolveRes, reject) => {
286
+ const r = mod.request(u, {
287
+ method: "POST",
288
+ headers: { ...req.headers, "content-length": String(Buffer.byteLength(req.body)) },
289
+ lookup: lookup,
290
+ timeout: req.timeoutMs,
291
+ agent: false,
292
+ }, (res) => {
293
+ const chunks = [];
294
+ let size = 0;
295
+ const done = () => resolveRes({ status: res.statusCode ?? 0, body: Buffer.concat(chunks).toString("utf8").slice(0, RESPONSE_LIMIT) });
296
+ res.on("data", (c) => {
297
+ if (size < RESPONSE_LIMIT)
298
+ chunks.push(c.subarray(0, RESPONSE_LIMIT - size));
299
+ size += c.length;
300
+ if (size >= RESPONSE_LIMIT) {
301
+ done();
302
+ res.destroy();
303
+ }
304
+ });
305
+ res.on("end", done);
306
+ res.on("error", () => done());
307
+ });
308
+ const timer = setTimeout(() => r.destroy(new Error(`timed out after ${req.timeoutMs} ms`)), req.timeoutMs);
309
+ r.on("timeout", () => r.destroy(new Error(`timed out after ${req.timeoutMs} ms`)));
310
+ r.on("error", (e) => (clearTimeout(timer), reject(e)));
311
+ r.on("close", () => clearTimeout(timer));
312
+ r.end(req.body);
313
+ });
314
+ };
315
+ }
316
+ const EVENT_RE = /^[a-z][a-z0-9_]*(\.[a-z0-9_]+){0,4}$/;
317
+ const CONTROL_RE = /[\x00-\x1f\x7f]/;
318
+ const DEFAULT_SCHEDULE = [5_000, 5 * 60_000, 30 * 60_000, 2 * 3600_000, 5 * 3600_000, 10 * 3600_000, 10 * 3600_000];
319
+ export class Webhooks {
320
+ job;
321
+ events;
322
+ #store;
323
+ #o;
324
+ #keyText;
325
+ #aes = null;
326
+ constructor(o) {
327
+ const fail = (m) => {
328
+ throw new Error(`defineWebhooks: ${m}`);
329
+ };
330
+ if (!Array.isArray(o.events) || o.events.length === 0)
331
+ fail("events lists the event types");
332
+ const seen = new Set();
333
+ for (const e of o.events) {
334
+ if (typeof e !== "string" || e.length > 64 || !EVENT_RE.test(e))
335
+ fail(`not an event type (a.b_c, lower case): ${JSON.stringify(e)}`);
336
+ if (seen.has(e))
337
+ fail(`event ${e} is listed twice`);
338
+ seen.add(e);
339
+ }
340
+ const key = isSecret(o.key) ? o.key.reveal() : o.key;
341
+ if (typeof key !== "string" || key.length < MIN_SECRET_LENGTH)
342
+ fail(`key must be at least ${MIN_SECRET_LENGTH} characters`);
343
+ if (typeof o.jobs !== "function")
344
+ fail("jobs is a function returning the queue");
345
+ const schedule = o.retrySchedule ?? DEFAULT_SCHEDULE;
346
+ if (!Array.isArray(schedule) || schedule.length > 30 || schedule.some((ms) => !Number.isInteger(ms) || ms < 0 || ms > 7 * 24 * 3600_000)) {
347
+ fail("retrySchedule is up to 30 waits of 0 ms to 7 days");
348
+ }
349
+ const int = (what, v, lo, hi) => (Number.isInteger(v) && v >= lo && v <= hi ? v : fail(`${what} is ${lo} to ${hi}`));
350
+ this.events = Object.freeze([...o.events]);
351
+ this.#keyText = key;
352
+ this.#store = o.store ?? new MemoryWebhookStore();
353
+ const allowPrivate = o.allowPrivateNetworks === true;
354
+ const lookup = o.lookup;
355
+ this.#o = {
356
+ jobs: o.jobs,
357
+ transport: o.transport ?? nodeTransport({ allowPrivateNetworks: allowPrivate, ...(lookup ? { lookup } : {}) }),
358
+ lookup,
359
+ timeoutMs: int("timeoutMs", o.timeoutMs ?? 15_000, 1000, 60_000),
360
+ disableAfter: int("disableAfter", o.disableAfter ?? 20, 1, 1000),
361
+ maxEndpoints: int("maxEndpoints", o.maxEndpoints ?? 20, 1, 100),
362
+ maxBytes: int("maxBytes", o.maxBytes ?? 256 * 1024, 1024, 1024 * 1024),
363
+ keepMs: int("keepMs", o.keepMs ?? 30 * 24 * 3600_000, 3600_000, 365 * 24 * 3600_000),
364
+ allowInsecure: o.allowInsecure === true,
365
+ allowPrivate,
366
+ onError: o.onError ?? ((err) => console.error("[weft] webhook:", err)),
367
+ now: o.now ?? Date.now,
368
+ };
369
+ const waits = [...schedule];
370
+ this.job = defineJob(o.jobName ?? "weftWebhook", [{ name: "delivery", type: "string" }], (ctx, delivery) => this.#attempt(delivery, ctx.job.attempt, ctx.job.maxAttempts), { attempts: waits.length + 1, backoff: (attempt) => waits[attempt - 1] ?? waits[waits.length - 1] ?? 0, timeoutMs: this.#o.timeoutMs + 30_000 });
371
+ }
372
+ async #key() {
373
+ this.#aes ??= (async () => {
374
+ const base = await crypto.subtle.importKey("raw", utf8.encode(this.#keyText), "HKDF", false, ["deriveKey"]);
375
+ return crypto.subtle.deriveKey({ name: "HKDF", hash: "SHA-256", salt: utf8.encode("weft webhooks"), info: utf8.encode("endpoint secret") }, base, { name: "AES-GCM", length: 256 }, false, ["encrypt", "decrypt"]);
376
+ })();
377
+ return this.#aes;
378
+ }
379
+ async #seal(secret, endpoint) {
380
+ const iv = crypto.getRandomValues(new Uint8Array(12));
381
+ const ct = new Uint8Array(await crypto.subtle.encrypt({ name: "AES-GCM", iv, additionalData: utf8.encode(endpoint) }, await this.#key(), utf8.encode(secret)));
382
+ return `v1.${b64(iv)}.${b64(ct)}`;
383
+ }
384
+ async #open(sealed, endpoint) {
385
+ const [v, iv, ct] = sealed.split(".");
386
+ if (v !== "v1" || !iv || !ct)
387
+ throw new Error("webhooks: unreadable stored secret");
388
+ const pt = await crypto.subtle.decrypt({ name: "AES-GCM", iv: fromB64(iv), additionalData: utf8.encode(endpoint) }, await this.#key(), fromB64(ct));
389
+ return new TextDecoder().decode(pt);
390
+ }
391
+ #owner(owner) {
392
+ if (typeof owner !== "string" || owner === "" || owner.length > 256 || CONTROL_RE.test(owner))
393
+ throw new WebhookError("invalid", "owner is a non-empty id");
394
+ return owner;
395
+ }
396
+ #events(events) {
397
+ if (!Array.isArray(events) || events.length === 0)
398
+ throw new WebhookError("invalid", 'events lists event types, or ["*"]');
399
+ if (events.includes("*")) {
400
+ if (events.length !== 1)
401
+ throw new WebhookError("invalid", '"*" stands alone');
402
+ return ["*"];
403
+ }
404
+ const out = new Set();
405
+ for (const e of events) {
406
+ if (!this.events.includes(e))
407
+ throw new WebhookError("invalid", `not an event type: ${JSON.stringify(e)}`);
408
+ out.add(e);
409
+ }
410
+ return [...out];
411
+ }
412
+ async checkUrl(url) {
413
+ if (typeof url !== "string" || url.length > 2048 || /[\x00-\x20\x7f]/.test(url))
414
+ throw new WebhookError("invalid", "url is an https URL");
415
+ let u;
416
+ try {
417
+ u = new URL(url);
418
+ }
419
+ catch {
420
+ throw new WebhookError("invalid", "url is an https URL");
421
+ }
422
+ if (u.protocol !== "https:" && !(this.#o.allowInsecure && u.protocol === "http:"))
423
+ throw new WebhookError("invalid", "url is an https URL");
424
+ if (u.username || u.password)
425
+ throw new WebhookError("invalid", "url carries no user name or password");
426
+ if (u.hash)
427
+ throw new WebhookError("invalid", "url has no #fragment");
428
+ const host = u.hostname.replace(/^\[|\]$/g, "").toLowerCase();
429
+ if (this.#o.allowPrivate)
430
+ return u.href;
431
+ if (isIpLiteral(host)) {
432
+ if (!isPublicAddress(host))
433
+ throw new WebhookError("address", `${host} is not a public address`);
434
+ return u.href;
435
+ }
436
+ if (!host.includes(".") || host.endsWith(".localhost") || host.endsWith(".local") || host.endsWith(".internal") || host === "localhost") {
437
+ throw new WebhookError("address", `${host} is not a public host name`);
438
+ }
439
+ let addrs;
440
+ try {
441
+ addrs = this.#o.lookup ? await this.#o.lookup(host) : await (await import("node:dns")).promises.lookup(host, { all: true, verbatim: true });
442
+ }
443
+ catch {
444
+ throw new WebhookError("address", `${host} does not resolve`);
445
+ }
446
+ if (addrs.length === 0)
447
+ throw new WebhookError("address", `${host} does not resolve`);
448
+ const bad = addrs.find((a) => !isPublicAddress(a.address));
449
+ if (bad)
450
+ throw new WebhookError("address", `${host} resolves to ${bad.address}, not a public address`);
451
+ return u.href;
452
+ }
453
+ async #endpoint(owner, id) {
454
+ const raw = typeof id === "string" && id.length <= 64 ? await this.#store.get("endpoint", id) : null;
455
+ const ep = raw ? JSON.parse(raw) : null;
456
+ if (!ep || ep.owner !== owner)
457
+ throw new WebhookError("not-found", "no such endpoint");
458
+ return ep;
459
+ }
460
+ async #save(ep) {
461
+ await this.#store.put("endpoint", ep.id, ep.owner, null, ep.created, JSON.stringify(ep));
462
+ }
463
+ #public(ep) {
464
+ const { secret: _s, previous: _p, ...rest } = ep;
465
+ return { ...rest, events: [...rest.events] };
466
+ }
467
+ async createEndpoint(owner, input) {
468
+ this.#owner(owner);
469
+ const url = await this.checkUrl(input?.url);
470
+ const events = this.#events(input.events);
471
+ const description = this.#description(input.description);
472
+ const mine = await this.#store.list("endpoint", owner, { limit: this.#o.maxEndpoints + 1 });
473
+ if (mine.length >= this.#o.maxEndpoints)
474
+ throw new WebhookError("limit", `at most ${this.#o.maxEndpoints} endpoints`);
475
+ const id = randomId("ep_");
476
+ const secret = newSecret();
477
+ const ep = {
478
+ id,
479
+ owner,
480
+ url,
481
+ events,
482
+ description,
483
+ enabled: true,
484
+ disabledReason: null,
485
+ created: this.#o.now(),
486
+ failures: 0,
487
+ secret: await this.#seal(secret, id),
488
+ previous: null,
489
+ };
490
+ await this.#save(ep);
491
+ return { endpoint: this.#public(ep), secret };
492
+ }
493
+ #description(d) {
494
+ if (d === undefined)
495
+ return "";
496
+ if (typeof d !== "string" || d.length > 500 || CONTROL_RE.test(d.replace(/\n/g, "")))
497
+ throw new WebhookError("invalid", "description is at most 500 characters");
498
+ return d;
499
+ }
500
+ async endpoints(owner) {
501
+ this.#owner(owner);
502
+ return (await this.#store.list("endpoint", owner, { limit: 1000 })).map((r) => this.#public(JSON.parse(r)));
503
+ }
504
+ async endpoint(owner, id) {
505
+ this.#owner(owner);
506
+ try {
507
+ return this.#public(await this.#endpoint(owner, id));
508
+ }
509
+ catch (err) {
510
+ if (err instanceof WebhookError && err.code === "not-found")
511
+ return null;
512
+ throw err;
513
+ }
514
+ }
515
+ async updateEndpoint(owner, id, patch) {
516
+ this.#owner(owner);
517
+ const ep = await this.#endpoint(owner, id);
518
+ if (patch.url !== undefined)
519
+ ep.url = await this.checkUrl(patch.url);
520
+ if (patch.events !== undefined)
521
+ ep.events = this.#events(patch.events);
522
+ if (patch.description !== undefined)
523
+ ep.description = this.#description(patch.description);
524
+ if (patch.enabled !== undefined) {
525
+ if (typeof patch.enabled !== "boolean")
526
+ throw new WebhookError("invalid", "enabled is a boolean");
527
+ ep.enabled = patch.enabled;
528
+ ep.disabledReason = null;
529
+ if (patch.enabled)
530
+ ep.failures = 0;
531
+ }
532
+ await this.#save(ep);
533
+ return this.#public(ep);
534
+ }
535
+ async revealSecret(owner, id) {
536
+ this.#owner(owner);
537
+ const ep = await this.#endpoint(owner, id);
538
+ return this.#open(ep.secret, ep.id);
539
+ }
540
+ async rotateSecret(owner, id, o = {}) {
541
+ this.#owner(owner);
542
+ const keep = o.keepOldMs ?? 24 * 3600_000;
543
+ if (!Number.isInteger(keep) || keep < 0 || keep > 7 * 24 * 3600_000)
544
+ throw new WebhookError("invalid", "keepOldMs is 0 to 7 days");
545
+ const ep = await this.#endpoint(owner, id);
546
+ const secret = newSecret();
547
+ ep.previous = keep > 0 ? { secret: ep.secret, until: this.#o.now() + keep } : null;
548
+ ep.secret = await this.#seal(secret, ep.id);
549
+ await this.#save(ep);
550
+ return secret;
551
+ }
552
+ async removeEndpoint(owner, id) {
553
+ this.#owner(owner);
554
+ try {
555
+ await this.#endpoint(owner, id);
556
+ }
557
+ catch {
558
+ return false;
559
+ }
560
+ await this.#store.remove("endpoint", id);
561
+ for (;;) {
562
+ const batch = await this.#store.list("delivery", owner, { ref: id, limit: 500 });
563
+ if (batch.length === 0)
564
+ break;
565
+ for (const r of batch)
566
+ await this.#store.remove("delivery", JSON.parse(r).id);
567
+ }
568
+ return true;
569
+ }
570
+ async emit(owner, event, data) {
571
+ this.#owner(owner);
572
+ if (!this.events.includes(event))
573
+ throw new WebhookError("invalid", `not an event type: ${JSON.stringify(event)}`);
574
+ const now = this.#o.now();
575
+ let body;
576
+ try {
577
+ body = JSON.stringify({ type: event, timestamp: new Date(now).toISOString(), data: data ?? null });
578
+ }
579
+ catch (err) {
580
+ throw new WebhookError("invalid", `event data is not JSON: ${err instanceof Error ? err.message : String(err)}`);
581
+ }
582
+ if (utf8.encode(body).length > this.#o.maxBytes)
583
+ throw new WebhookError("invalid", `event data is over ${this.#o.maxBytes} bytes`);
584
+ const targets = (await this.#store.list("endpoint", owner, { limit: 1000 }))
585
+ .map((r) => JSON.parse(r))
586
+ .filter((ep) => ep.enabled && (ep.events.includes("*") || ep.events.includes(event)));
587
+ if (targets.length === 0)
588
+ return null;
589
+ const msg = { id: randomId("msg_"), owner, event, body, created: now };
590
+ await this.#store.put("message", msg.id, owner, null, now, JSON.stringify(msg));
591
+ for (const ep of targets) {
592
+ const d = { id: randomId("dlv_"), owner, message: msg.id, endpoint: ep.id, event, status: "pending", attempts: [], created: now, updated: now };
593
+ await this.#store.put("delivery", d.id, owner, ep.id, now, JSON.stringify(d));
594
+ await this.#o.jobs().enqueue(null, this.job, { delivery: d.id }, { as: null, key: `webhook:${d.id}` });
595
+ }
596
+ return msg.id;
597
+ }
598
+ async #delivery(id) {
599
+ const raw = typeof id === "string" && id.length <= 64 ? await this.#store.get("delivery", id) : null;
600
+ return raw ? JSON.parse(raw) : null;
601
+ }
602
+ async #put(d) {
603
+ await this.#store.put("delivery", d.id, d.owner, d.endpoint, d.created, JSON.stringify(d));
604
+ }
605
+ async deliveries(owner, f = {}) {
606
+ this.#owner(owner);
607
+ const limit = Math.min(Math.max(1, Math.floor(f.limit ?? 50)), 500);
608
+ const out = [];
609
+ let before = f.before;
610
+ while (out.length < limit) {
611
+ const batch = (await this.#store.list("delivery", owner, { ...(f.endpoint !== undefined ? { ref: f.endpoint } : {}), limit: 500, ...(before !== undefined ? { before } : {}) })).map((r) => JSON.parse(r));
612
+ for (const d of batch)
613
+ if (f.status === undefined || d.status === f.status)
614
+ out.push(d);
615
+ if (batch.length < 500 || f.status === undefined)
616
+ break;
617
+ before = batch[batch.length - 1].created;
618
+ }
619
+ return out.slice(0, limit);
620
+ }
621
+ async delivery(owner, id) {
622
+ this.#owner(owner);
623
+ const d = await this.#delivery(id);
624
+ if (!d || d.owner !== owner)
625
+ return null;
626
+ const msg = await this.#store.get("message", d.message);
627
+ return { ...d, body: msg ? JSON.parse(msg).body : null };
628
+ }
629
+ async replay(owner, id) {
630
+ this.#owner(owner);
631
+ const d = await this.#delivery(id);
632
+ if (!d || d.owner !== owner || d.status === "pending")
633
+ return false;
634
+ if (!(await this.#store.get("message", d.message)))
635
+ return false;
636
+ const raw = await this.#store.get("endpoint", d.endpoint);
637
+ const ep = raw ? JSON.parse(raw) : null;
638
+ if (!ep || ep.owner !== owner || !ep.enabled)
639
+ return false;
640
+ d.status = "pending";
641
+ d.updated = this.#o.now();
642
+ await this.#put(d);
643
+ const queued = await this.#o.jobs().enqueue(null, this.job, { delivery: d.id }, { as: null, key: `webhook:${d.id}` });
644
+ return queued !== false;
645
+ }
646
+ async #attempt(id, attempt, maxAttempts) {
647
+ const d = await this.#delivery(id);
648
+ if (!d || d.status !== "pending")
649
+ return;
650
+ const final = attempt >= maxAttempts;
651
+ const rawEp = await this.#store.get("endpoint", d.endpoint);
652
+ const ep = rawEp ? JSON.parse(rawEp) : null;
653
+ const rawMsg = await this.#store.get("message", d.message);
654
+ if (!ep || ep.owner !== d.owner || !ep.enabled || !rawMsg) {
655
+ d.status = "failed";
656
+ d.attempts.push({ at: this.#o.now(), status: null, durationMs: 0, error: !ep ? "endpoint removed" : !rawMsg ? "message pruned" : "endpoint disabled", response: "" });
657
+ d.updated = this.#o.now();
658
+ await this.#put(d);
659
+ return;
660
+ }
661
+ const msg = JSON.parse(rawMsg);
662
+ const start = this.#o.now();
663
+ const ts = Math.floor(start / 1000);
664
+ let secrets;
665
+ try {
666
+ secrets = [await this.#open(ep.secret, ep.id)];
667
+ if (ep.previous && ep.previous.until > start)
668
+ secrets.push(await this.#open(ep.previous.secret, ep.id));
669
+ }
670
+ catch (err) {
671
+ this.#o.onError(err);
672
+ d.status = "failed";
673
+ d.attempts.push({ at: start, status: null, durationMs: 0, error: "the endpoint's signing secret cannot be read", response: "" });
674
+ d.updated = this.#o.now();
675
+ await this.#put(d);
676
+ return;
677
+ }
678
+ const rec = { at: start, status: null, durationMs: 0, error: null, response: "" };
679
+ try {
680
+ await this.checkUrl(ep.url);
681
+ const res = await this.#o.transport({
682
+ url: ep.url,
683
+ timeoutMs: this.#o.timeoutMs,
684
+ body: msg.body,
685
+ headers: {
686
+ "content-type": "application/json",
687
+ "user-agent": "Weft-Webhooks/1",
688
+ "webhook-id": msg.id,
689
+ "webhook-timestamp": String(ts),
690
+ "webhook-signature": await signWebhook(secrets, msg.id, ts, msg.body),
691
+ },
692
+ });
693
+ rec.status = res.status;
694
+ rec.response = String(res.body ?? "").slice(0, RESPONSE_LIMIT);
695
+ if (res.status < 200 || res.status > 299)
696
+ rec.error = `HTTP ${res.status}`;
697
+ }
698
+ catch (err) {
699
+ rec.error = err instanceof Error ? err.message : String(err);
700
+ }
701
+ rec.durationMs = Math.max(0, this.#o.now() - start);
702
+ d.attempts.push(rec);
703
+ if (d.attempts.length > 50)
704
+ d.attempts.splice(0, d.attempts.length - 50);
705
+ d.updated = this.#o.now();
706
+ const ok = rec.error === null;
707
+ if (ok || final)
708
+ d.status = ok ? "succeeded" : "failed";
709
+ await this.#put(d);
710
+ if (ok || final)
711
+ await this.#settle(ep.id, ok);
712
+ if (!ok && !final)
713
+ throw new JobError(`webhook ${d.id}: ${rec.error}`);
714
+ }
715
+ async #settle(endpoint, ok) {
716
+ const raw = await this.#store.get("endpoint", endpoint);
717
+ if (!raw)
718
+ return;
719
+ const ep = JSON.parse(raw);
720
+ if (ok) {
721
+ if (ep.failures === 0)
722
+ return;
723
+ ep.failures = 0;
724
+ }
725
+ else {
726
+ ep.failures++;
727
+ if (ep.failures >= this.#o.disableAfter && ep.enabled) {
728
+ ep.enabled = false;
729
+ ep.disabledReason = `${ep.failures} deliveries in a row failed`;
730
+ }
731
+ }
732
+ try {
733
+ await this.#save(ep);
734
+ }
735
+ catch (err) {
736
+ this.#o.onError(err);
737
+ }
738
+ }
739
+ async prune(owner) {
740
+ const before = this.#o.now() - this.#o.keepMs;
741
+ if (owner !== undefined)
742
+ this.#owner(owner);
743
+ return (await this.#store.sweep("delivery", before, owner)) + (await this.#store.sweep("message", before, owner));
744
+ }
745
+ async forget(owner) {
746
+ this.#owner(owner);
747
+ let n = 0;
748
+ for (const ep of await this.endpoints(owner))
749
+ if (await this.removeEndpoint(owner, ep.id))
750
+ n++;
751
+ await this.#store.sweep("delivery", Number.MAX_SAFE_INTEGER, owner);
752
+ await this.#store.sweep("message", Number.MAX_SAFE_INTEGER, owner);
753
+ return n;
754
+ }
755
+ }
756
+ export function defineWebhooks(o) {
757
+ return new Webhooks(o);
758
+ }