@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.
@@ -1,2 +1,2 @@
1
- import { a as WebhookDeliveryStore, c as createDrizzleWebhookStore, d as webhooksTables, f as webhooksTableNames, i as WebhookDeliveryState, l as webhookDeliveries, n as WebhookAttemptResult, o as WebhookSendRecord, r as WebhookDelivery, s as WebhooksDatabase, t as ListWebhookDeliveriesOptions, u as webhooksSchema } from "./database-COdjz9Vi.js";
2
- export { ListWebhookDeliveriesOptions, WebhookAttemptResult, WebhookDelivery, WebhookDeliveryState, WebhookDeliveryStore, WebhookSendRecord, WebhooksDatabase, createDrizzleWebhookStore, webhookDeliveries, webhooksSchema, webhooksTableNames, webhooksTables };
1
+ import { C as webhooksSchema, E as webhooksTableNames, S as webhookPairings, T as webhookEndpointsTableNames, _ as createDrizzleWebhookEndpointStore, a as MemberLastDelivery, b as webhookEndpoints, c as StoredMemberPairing, d as WebhookDeliveryState, f as WebhookDeliveryStore, g as WebhooksDatabase, h as WebhookSendRecord, i as MemberEndpointKind, l as WebhookAttemptResult, m as WebhookRecordOnceResult, n as ListWebhookDeliveriesOptions, o as MemberPairingState, p as WebhookEndpointStore, r as MemberEndpoint, s as StoredMemberEndpoint, t as ListMemberEndpointsOptions, u as WebhookDelivery, v as createDrizzleWebhookStore, w as webhooksTables, x as webhookEndpointsSchema, y as webhookDeliveries } from "./database-C5cwO1an.js";
2
+ export { ListMemberEndpointsOptions, ListWebhookDeliveriesOptions, MemberEndpoint, MemberEndpointKind, MemberLastDelivery, MemberPairingState, StoredMemberEndpoint, StoredMemberPairing, WebhookAttemptResult, WebhookDelivery, WebhookDeliveryState, WebhookDeliveryStore, WebhookEndpointStore, WebhookRecordOnceResult, WebhookSendRecord, WebhooksDatabase, createDrizzleWebhookEndpointStore, createDrizzleWebhookStore, webhookDeliveries, webhookEndpoints, webhookEndpointsSchema, webhookEndpointsTableNames, webhookPairings, webhooksSchema, webhooksTableNames, webhooksTables };
package/dist/database.js CHANGED
@@ -1,6 +1,6 @@
1
- import { t as webhooksErrors } from "./errors-1y5fWGlX.js";
2
- import { t as webhooksTableNames } from "./table-names-DVvicXhh.js";
3
- import { and, asc, desc, eq, lt, or, sql } from "drizzle-orm";
1
+ import { t as webhooksErrors } from "./errors-DT8uyCh7.js";
2
+ import { n as webhooksTableNames, t as webhookEndpointsTableNames } from "./table-names-DAUip4v2.js";
3
+ import { and, asc, desc, eq, gt, gte, inArray, lt, or, sql } from "drizzle-orm";
4
4
  import { index, integer, sqliteTable, text, uniqueIndex } from "drizzle-orm/sqlite-core";
5
5
  /**
6
6
  * One row for each delivery. A debounced webhook keeps one `pending` row for each `(webhook, key)`: each send replaces
@@ -9,13 +9,11 @@ import { index, integer, sqliteTable, text, uniqueIndex } from "drizzle-orm/sqli
9
9
  const webhookDeliveries = sqliteTable("vitehub_webhook_deliveries", {
10
10
  id: text("id").primaryKey(),
11
11
  webhook: text("webhook").notNull(),
12
- /** The debounce key. `null` for a webhook without a debounce and for a redelivery: those rows never collapse. */
12
+ owner: text("owner"),
13
13
  key: text("key"),
14
14
  event: text("event").notNull(),
15
- /** The JSON text that the receiver gets, byte for byte. */
16
15
  body: text("body").notNull(),
17
16
  revision: integer("revision").notNull(),
18
- /** How many sends this delivery collapses. The receiver gets it in `x-vitehub-events`. */
19
17
  count: integer("count").notNull(),
20
18
  state: text("state", { enum: [
21
19
  "pending",
@@ -34,20 +32,79 @@ const webhookDeliveries = sqliteTable("vitehub_webhook_deliveries", {
34
32
  }, (table) => [
35
33
  uniqueIndex("vitehub_webhook_deliveries_pending").on(table.webhook, table.key).where(sql`state = 'pending'`),
36
34
  index("vitehub_webhook_deliveries_webhook").on(table.webhook, table.createdAt),
37
- index("vitehub_webhook_deliveries_state").on(table.state, table.dueAt)
35
+ index("vitehub_webhook_deliveries_state").on(table.state, table.dueAt),
36
+ index("vitehub_webhook_deliveries_owner").on(table.owner, table.createdAt, table.id).where(sql`owner IS NOT NULL`)
38
37
  ]);
38
+ /**
39
+ * One row per owner and address. `sealed` holds the URL and secret, encrypted with
40
+ * `VITEHUB_WEBHOOKS_KEY`, and `null` for an inbox. `host` is the only part of the URL in plain text.
41
+ */
42
+ const webhookEndpoints = sqliteTable("vitehub_webhook_endpoints", {
43
+ id: text("id").primaryKey(),
44
+ owner: text("owner").notNull(),
45
+ /** The name of the owner that people read, such as `Ana Ruiz`. */
46
+ ownerName: text("owner_name"),
47
+ /** The verified email of the owner at connect time, not proof of their current identity. */
48
+ ownerEmail: text("owner_email"),
49
+ name: text("name").notNull(),
50
+ address: text("address").notNull().default(""),
51
+ kind: text("kind", { enum: ["url", "inbox"] }).notNull(),
52
+ agent: text("agent"),
53
+ host: text("host"),
54
+ sealed: text("sealed"),
55
+ disabledAt: integer("disabled_at"),
56
+ /** Who disabled it, such as the name of an admin. */
57
+ disabledBy: text("disabled_by"),
58
+ createdAt: integer("created_at").notNull(),
59
+ updatedAt: integer("updated_at").notNull()
60
+ }, (table) => [uniqueIndex("vitehub_webhook_endpoints_owner").on(table.owner, table.address), index("vitehub_webhook_endpoints_created").on(table.createdAt, table.id)]);
39
61
  /** The table of Webhooks, for `defineDatabase({ schema })` or a Database contribution. */
40
62
  const webhooksSchema = { webhookDeliveries };
41
- /** `webhooksSchema` as SQLite statements that are safe to run on every start. */
63
+ /**
64
+ * One row for each pairing code, for 10 minutes. `id` is the SHA-256 hash of the code. `sealed` holds the signing secret
65
+ * that the member's agent gets with the code, and after pairing the agent's URL too, encrypted with `VITEHUB_WEBHOOKS_KEY`.
66
+ */
67
+ const webhookPairings = sqliteTable("vitehub_webhook_pairings", {
68
+ id: text("id").primaryKey(),
69
+ owner: text("owner").notNull(),
70
+ state: text("state", { enum: [
71
+ "waiting",
72
+ "paired",
73
+ "used",
74
+ "refused"
75
+ ] }).notNull(),
76
+ agent: text("agent"),
77
+ host: text("host"),
78
+ address: text("address"),
79
+ sealed: text("sealed").notNull(),
80
+ expiresAt: integer("expires_at").notNull(),
81
+ createdAt: integer("created_at").notNull()
82
+ }, (table) => [index("vitehub_webhook_pairings_owner").on(table.owner)]);
83
+ /** The tables of member endpoints and their pairing codes. Webhooks adds them only when a feature of the app uses member endpoints. */
84
+ const webhookEndpointsSchema = {
85
+ webhookEndpoints,
86
+ webhookPairings
87
+ };
88
+ /** The tables of `webhooksSchema` and `webhookEndpointsSchema` as SQLite statements that are safe to run on every start. */
42
89
  const webhooksTables = [
43
- "CREATE TABLE IF NOT EXISTS `vitehub_webhook_deliveries` (`id` text PRIMARY KEY NOT NULL, `webhook` text NOT NULL, `key` text, `event` text NOT NULL, `body` text NOT NULL, `revision` integer NOT NULL, `count` integer NOT NULL, `state` text NOT NULL, `attempts` integer NOT NULL, `last_status` integer, `last_error` text, `due_at` integer NOT NULL, `created_at` integer NOT NULL, `updated_at` integer NOT NULL, `sent_at` integer)",
90
+ "CREATE TABLE IF NOT EXISTS `vitehub_webhook_deliveries` (`id` text PRIMARY KEY NOT NULL, `webhook` text NOT NULL, `owner` text, `key` text, `event` text NOT NULL, `body` text NOT NULL, `revision` integer NOT NULL, `count` integer NOT NULL, `state` text NOT NULL, `attempts` integer NOT NULL, `last_status` integer, `last_error` text, `due_at` integer NOT NULL, `created_at` integer NOT NULL, `updated_at` integer NOT NULL, `sent_at` integer)",
44
91
  "CREATE UNIQUE INDEX IF NOT EXISTS `vitehub_webhook_deliveries_pending` ON `vitehub_webhook_deliveries` (`webhook`,`key`) WHERE state = 'pending'",
45
92
  "CREATE INDEX IF NOT EXISTS `vitehub_webhook_deliveries_webhook` ON `vitehub_webhook_deliveries` (`webhook`,`created_at`)",
46
- "CREATE INDEX IF NOT EXISTS `vitehub_webhook_deliveries_state` ON `vitehub_webhook_deliveries` (`state`,`due_at`)"
93
+ "CREATE INDEX IF NOT EXISTS `vitehub_webhook_deliveries_state` ON `vitehub_webhook_deliveries` (`state`,`due_at`)",
94
+ "CREATE INDEX IF NOT EXISTS `vitehub_webhook_deliveries_owner` ON `vitehub_webhook_deliveries` (`owner`,`created_at`,`id`) WHERE owner IS NOT NULL",
95
+ "CREATE TABLE IF NOT EXISTS `vitehub_webhook_endpoints` (`id` text PRIMARY KEY NOT NULL, `owner` text NOT NULL, `owner_name` text, `owner_email` text, `name` text NOT NULL, `address` text DEFAULT '' NOT NULL, `kind` text NOT NULL, `agent` text, `host` text, `sealed` text, `disabled_at` integer, `disabled_by` text, `created_at` integer NOT NULL, `updated_at` integer NOT NULL)",
96
+ "CREATE UNIQUE INDEX IF NOT EXISTS `vitehub_webhook_endpoints_owner` ON `vitehub_webhook_endpoints` (`owner`,`address`)",
97
+ "CREATE INDEX IF NOT EXISTS `vitehub_webhook_endpoints_created` ON `vitehub_webhook_endpoints` (`created_at`,`id`)",
98
+ "CREATE TABLE IF NOT EXISTS `vitehub_webhook_pairings` (`id` text PRIMARY KEY NOT NULL, `owner` text NOT NULL, `state` text NOT NULL, `agent` text, `host` text, `address` text, `sealed` text NOT NULL, `expires_at` integer NOT NULL, `created_at` integer NOT NULL)",
99
+ "CREATE INDEX IF NOT EXISTS `vitehub_webhook_pairings_owner` ON `vitehub_webhook_pairings` (`owner`)"
47
100
  ];
101
+ function hasBatch(database) {
102
+ return "batch" in database && typeof database.batch === "function";
103
+ }
48
104
  function toDelivery(row) {
105
+ const { owner: _owner, ...delivery } = row;
49
106
  return {
50
- ...row,
107
+ ...delivery,
51
108
  body: JSON.parse(row.body)
52
109
  };
53
110
  }
@@ -74,6 +131,7 @@ function createDrizzleWebhookStore(database) {
74
131
  const insert = db().insert(t).values({
75
132
  id: send.id,
76
133
  webhook: send.webhook,
134
+ owner: send.owner,
77
135
  key: send.key,
78
136
  event: send.event,
79
137
  body: send.body,
@@ -109,6 +167,37 @@ function createDrizzleWebhookStore(database) {
109
167
  if (!row) throw webhooksErrors.WEBHOOKS_STORE_FAILED({ action: "store a delivery" });
110
168
  return row;
111
169
  }),
170
+ recordOnce: (send) => guarded("store a delivery", async () => {
171
+ const connection = db();
172
+ const columns = {
173
+ id: t.id,
174
+ revision: t.revision,
175
+ state: t.state
176
+ };
177
+ const live = and(eq(t.webhook, send.webhook), eq(t.key, send.key), inArray(t.state, [
178
+ "pending",
179
+ "sending",
180
+ "sent"
181
+ ]));
182
+ const insert = (target) => target.insert(t).select(sql`
183
+ SELECT ${send.id}, ${send.webhook}, ${send.owner ?? null}, ${send.key}, ${send.event}, ${send.body},
184
+ 1, ${send.count ?? 1}, 'pending', 0, NULL, NULL, ${send.dueAt}, ${send.now}, ${send.now}, NULL
185
+ WHERE NOT EXISTS (SELECT 1 FROM ${t} WHERE ${live})
186
+ `).returning(columns);
187
+ const existing = (target) => target.select(columns).from(t).where(live).orderBy(desc(t.createdAt)).limit(1);
188
+ const [[inserted], [retained]] = hasBatch(connection) ? await connection.batch([insert(connection), existing(connection)]) : await connection.transaction(async (tx) => {
189
+ return [await insert(tx), await existing(tx)];
190
+ }, { behavior: "immediate" });
191
+ if (inserted) return {
192
+ ...inserted,
193
+ created: true
194
+ };
195
+ if (retained) return {
196
+ ...retained,
197
+ created: false
198
+ };
199
+ throw webhooksErrors.WEBHOOKS_STORE_FAILED({ action: "store a delivery" });
200
+ }),
112
201
  get: (id) => guarded("read a delivery", async () => {
113
202
  const [row] = await db().select().from(t).where(eq(t.id, id)).limit(1);
114
203
  return row ? toDelivery(row) : void 0;
@@ -116,7 +205,7 @@ function createDrizzleWebhookStore(database) {
116
205
  list: (options = {}) => guarded("list deliveries", async () => {
117
206
  const limit = Math.min(Math.max(options.limit ?? 100, 1), 500);
118
207
  const { before } = options;
119
- const where = and(options.webhook ? eq(t.webhook, options.webhook) : void 0, options.state ? eq(t.state, options.state) : void 0, before ? or(lt(t.createdAt, before.createdAt), and(eq(t.createdAt, before.createdAt), lt(t.id, before.id))) : void 0);
208
+ const where = and(options.webhook ? eq(t.webhook, options.webhook) : void 0, options.owner !== void 0 ? eq(t.owner, options.owner) : void 0, options.state ? eq(t.state, options.state) : void 0, before ? or(lt(t.createdAt, before.createdAt), and(eq(t.createdAt, before.createdAt), lt(t.id, before.id))) : void 0);
120
209
  return (await db().select().from(t).where(where).orderBy(desc(t.createdAt), desc(t.id)).limit(limit)).map(toDelivery);
121
210
  }),
122
211
  pending: (options = {}) => guarded("list pending deliveries", async () => {
@@ -164,8 +253,101 @@ function createDrizzleWebhookStore(database) {
164
253
  updatedAt: now
165
254
  }).where(and(eq(t.id, id), eq(t.state, "pending"))).returning();
166
255
  return row ? toDelivery(row) : void 0;
256
+ }),
257
+ memberResults: (webhooks) => guarded("read the member deliveries", async () => {
258
+ if (!webhooks.length) return /* @__PURE__ */ new Map();
259
+ const rows = await db().all(sql`
260
+ SELECT d.webhook AS webhook, d.state AS state, d.last_status AS status, d.last_error AS error, d.updated_at AS at,
261
+ (SELECT count(*) FROM vitehub_webhook_deliveries AS f WHERE f.webhook = d.webhook AND f.state = 'dead'
262
+ AND f.created_at > coalesce((SELECT max(s.created_at) FROM vitehub_webhook_deliveries AS s WHERE s.webhook = d.webhook AND s.state <> 'dead'), -1)) AS failures
263
+ FROM vitehub_webhook_deliveries AS d
264
+ WHERE d.webhook IN (SELECT value FROM json_each(${JSON.stringify(webhooks)}))
265
+ AND NOT EXISTS (SELECT 1 FROM vitehub_webhook_deliveries AS n WHERE n.webhook = d.webhook AND (n.created_at > d.created_at OR (n.created_at = d.created_at AND n.id > d.id)))`);
266
+ return new Map(rows.map(({ webhook, ...result }) => [webhook, {
267
+ ...result,
268
+ failures: Number(result.failures)
269
+ }]));
270
+ })
271
+ };
272
+ }
273
+ /** Member endpoints in a Drizzle SQLite Database. Pass a function when the Database connects per request. */
274
+ function createDrizzleWebhookEndpointStore(database) {
275
+ const db = typeof database === "function" ? database : () => database;
276
+ const t = webhookEndpoints;
277
+ const p = webhookPairings;
278
+ return {
279
+ put: (endpoint) => guarded("store a member endpoint", async () => {
280
+ await db().insert(t).values(endpoint).onConflictDoUpdate({
281
+ target: [t.owner, t.address],
282
+ set: {
283
+ id: endpoint.id,
284
+ ownerName: endpoint.ownerName,
285
+ ownerEmail: endpoint.ownerEmail,
286
+ name: endpoint.name,
287
+ kind: endpoint.kind,
288
+ agent: endpoint.agent,
289
+ host: endpoint.host,
290
+ sealed: endpoint.sealed,
291
+ disabledAt: null,
292
+ disabledBy: null,
293
+ createdAt: endpoint.createdAt,
294
+ updatedAt: endpoint.updatedAt
295
+ }
296
+ });
297
+ }),
298
+ get: (owner, address) => guarded("read a member endpoint", async () => {
299
+ const normalized = address?.trim();
300
+ const [row] = await db().select().from(t).where(eq(t.owner, owner)).orderBy(...normalized === void 0 ? [] : [desc(sql`${t.address} = ${normalized}`)], desc(t.createdAt), desc(t.id)).limit(1);
301
+ return row;
302
+ }),
303
+ find: (id) => guarded("read a member endpoint", async () => {
304
+ const [row] = await db().select().from(t).where(eq(t.id, id)).limit(1);
305
+ return row;
306
+ }),
307
+ remove: (owner, id) => guarded("remove a member endpoint", async () => {
308
+ const [row] = await db().delete(t).where(and(eq(t.owner, owner), eq(t.id, id))).returning();
309
+ return row;
310
+ }),
311
+ removeAll: (owner) => guarded("remove the member endpoints of an owner", async () => await db().delete(t).where(eq(t.owner, owner)).returning()),
312
+ list: (options = {}) => guarded("list the member endpoints", async () => {
313
+ const { after } = options;
314
+ const where = after && or(gt(t.createdAt, after.createdAt), and(eq(t.createdAt, after.createdAt), gt(t.id, after.id)));
315
+ return await db().select().from(t).where(where).orderBy(asc(t.createdAt), asc(t.id)).limit(Math.min(Math.max(options.limit ?? 500, 1), 500));
316
+ }),
317
+ disable: (id, now, by) => guarded("disable a member endpoint", async () => {
318
+ const [row] = await db().update(t).set({
319
+ disabledAt: sql`coalesce(${t.disabledAt}, ${now})`,
320
+ disabledBy: sql`CASE WHEN ${t.disabledAt} IS NULL THEN ${by} ELSE ${t.disabledBy} END`,
321
+ updatedAt: now
322
+ }).where(eq(t.id, id)).returning();
323
+ return row;
324
+ }),
325
+ enable: (id, now) => guarded("enable a member endpoint", async () => {
326
+ const [row] = await db().update(t).set({
327
+ disabledAt: null,
328
+ disabledBy: null,
329
+ updatedAt: now
330
+ }).where(eq(t.id, id)).returning();
331
+ return row;
332
+ }),
333
+ insertPairing: (row) => guarded("store a pairing code", async () => {
334
+ await db().delete(p).where(or(lt(p.expiresAt, row.createdAt), and(eq(p.owner, row.owner), inArray(p.state, ["used", "refused"]))));
335
+ await db().insert(p).values(row);
336
+ }),
337
+ pairing: (id) => guarded("read a pairing code", async () => {
338
+ const [row] = await db().select().from(p).where(eq(p.id, id)).limit(1);
339
+ return row;
340
+ }),
341
+ movePairing: (id, from, to, now, set = {}) => guarded("update a pairing code", async () => {
342
+ const [row] = await db().update(p).set({
343
+ ...set,
344
+ state: to
345
+ }).where(and(eq(p.id, id), eq(p.state, from), gte(p.expiresAt, now))).returning();
346
+ return row;
347
+ }),
348
+ removePairing: (id, owner) => guarded("remove a pairing code", async () => {
349
+ await db().delete(p).where(and(eq(p.id, id), eq(p.owner, owner)));
167
350
  })
168
351
  };
169
352
  }
170
- //#endregion
171
- export { createDrizzleWebhookStore, webhookDeliveries, webhooksSchema, webhooksTableNames, webhooksTables };
353
+ export { createDrizzleWebhookEndpointStore, createDrizzleWebhookStore, webhookDeliveries, webhookEndpoints, webhookEndpointsSchema, webhookEndpointsTableNames, webhookPairings, webhooksSchema, webhooksTableNames, webhooksTables };
@@ -1,11 +1,15 @@
1
1
  import { defineErrors } from "@vite-hub/runtime";
2
- //#region src/errors.ts
2
+ // src/errors.ts
3
3
  const webhooksErrors = /*#__PURE__*/ defineErrors({
4
4
  docs: "https://vitehub.dev/docs/webhooks/diagnostics",
5
5
  codes: {
6
+ WEBHOOKS_CONTRIBUTION_INVALID: {
7
+ why: ({ plugin }) => `The Vite plugin ${plugin} sets \`vitehub.webhooks\`, but not to \`{ memberEndpoints: true, reason }\` or a function that returns it.`,
8
+ fix: "Set `vitehub.webhooks` to `{ memberEndpoints: true, reason: \"...\" }`, or to a function that returns it, or `undefined` when the feature is off."
9
+ },
6
10
  WEBHOOKS_DATABASE_OFF: {
7
- why: ({ files }) => `Webhooks keeps each delivery in the Database, but the app has no Database. These files define webhooks: ${files}.`,
8
- fix: "Turn on `database` in `vitehub()`, or remove the files of `server/webhooks/`."
11
+ why: ({ users }) => `Webhooks keeps each delivery in the Database, but the app has no Database. These use Webhooks: ${users}.`,
12
+ fix: "Turn on `database` in `vitehub()`, or remove the files of `server/webhooks/` and turn off the features that use member endpoints."
9
13
  },
10
14
  WEBHOOKS_DEBOUNCE_TOO_LONG: {
11
15
  why: ({ debounce }) => `The debounce ${debounce} is longer than 24 hours. Cloudflare Queues delays a message at most 24 hours, and a webhook must work on every host.`,
@@ -15,6 +19,10 @@ const webhooksErrors = /*#__PURE__*/ defineErrors({
15
19
  why: ({ message }) => message,
16
20
  fix: "Default-export `defineWebhook({ url: \"T3_WEBHOOK_URL\", secret: \"T3_WEBHOOK_SECRET\" })` from each file of `server/webhooks/`. `url` and `secret` are names of server variables, `signature` is `\"github\"` or `\"stripe\"`, `debounce` is a duration such as `\"30m\"`, and `events` lists `\"invocation.failed\"`, `\"workflow.failed\"`, or `\"schedule.failed\"`."
17
21
  },
22
+ WEBHOOKS_ENDPOINTS_OFF: {
23
+ why: "Member endpoints are not on in this server. No feature of the app uses them, or the code runs outside the ViteHub server.",
24
+ fix: "Turn on a feature that uses member endpoints, such as `send: true` in `defineComments()`. In a test, call `installWebhooks({ webhooks: {}, store, endpoints })` from `@vite-hub/webhooks/runtime` first."
25
+ },
18
26
  WEBHOOKS_FILE_INVALID: {
19
27
  why: ({ message }) => message,
20
28
  fix: "Name each file of `server/webhooks/` with lowercase letters, digits, and dashes, such as `t3.ts` or `slack-alerts.ts`, and keep one file for each webhook name."
@@ -51,10 +59,34 @@ const webhooksErrors = /*#__PURE__*/ defineErrors({
51
59
  why: ({ id }) => `No webhook delivery has the id ${id}.`,
52
60
  fix: "Pass the id of a delivery that `listWebhookDeliveries()` returns."
53
61
  },
62
+ WEBHOOKS_DELIVERY_NOT_OWNER: {
63
+ why: ({ id }) => `The delivery ${id} went to the agent of a member, and only that member can send it again.`,
64
+ fix: "Ask the member to redeliver it. In the ViteHub Console, the member signs in with the email of their app account, which must be verified. An app sends again as the member with `redeliverWebhookDelivery(id, { caller: { id: user.id } })`."
65
+ },
54
66
  WEBHOOKS_DELIVERY_NOT_PENDING: {
55
67
  why: ({ id, state }) => `The delivery ${id} is ${state}, not pending.`,
56
68
  fix: "Flush or cancel only a pending delivery. To send a sent, dead, or cancelled delivery again, redeliver it."
57
69
  },
70
+ WEBHOOKS_ENDPOINT_DISABLED: {
71
+ why: ({ id }) => `The member endpoint ${id} is disabled, so Webhooks does not send to it.`,
72
+ fix: "Ask the member to connect their agent again. That replaces the endpoint with a new one."
73
+ },
74
+ WEBHOOKS_ENDPOINT_INVALID: {
75
+ why: ({ problem }) => `The member endpoint is not valid: ${problem}.`,
76
+ fix: "Pass `{ owner, name, kind: \"url\", url, secret }` for a receiver URL, or `{ owner, name, kind: \"inbox\" }` for an agent that reads its inbox. `owner` and `name` are non-empty text."
77
+ },
78
+ WEBHOOKS_ENDPOINT_NOT_FOUND: {
79
+ why: ({ match }) => `No member endpoint has ${match}.`,
80
+ fix: "Create one with `createMemberEndpoint()` first. `getMemberEndpoint(owner)` returns the endpoint of a member."
81
+ },
82
+ WEBHOOKS_KEY_INVALID: {
83
+ why: ({ problem }) => `\`VITEHUB_WEBHOOKS_KEY\` cannot seal or open member endpoints: ${problem}.`,
84
+ fix: "Set `VITEHUB_WEBHOOKS_KEY` to 32 random bytes in base64, from `openssl rand -base64 32`. A new key cannot open the endpoints that the old key sealed, so members connect again after a change."
85
+ },
86
+ WEBHOOKS_KEY_UNSET: {
87
+ why: "Webhooks seals the URL and secret of each member endpoint with `VITEHUB_WEBHOOKS_KEY`, but this server has no value for it.",
88
+ fix: "Set `VITEHUB_WEBHOOKS_KEY` to the output of `openssl rand -base64 32`, as a secret on the host. `vite dev` generates one in `.vitehub/data/webhooks-key`."
89
+ },
58
90
  WEBHOOKS_SECRET_UNSET: {
59
91
  why: ({ name, webhook }) => `The webhook ${webhook} signs each delivery with the secret in \`${name}\`, but this server has no value for it.`,
60
92
  fix: "Set the variable to the signing secret that the receiver checks: in `.env` for `vite dev`, and as a secret on the host for production."
@@ -67,6 +99,10 @@ const webhooksErrors = /*#__PURE__*/ defineErrors({
67
99
  why: ({ name, webhook }) => `The webhook ${webhook} reads its URL from \`${name}\`, but the value is not an http or https URL.`,
68
100
  fix: "Set the variable to the full URL of the receiver, such as `https://example.com/hooks/vitehub`."
69
101
  },
102
+ WEBHOOKS_URL_REFUSED: {
103
+ why: ({ reason }) => `Webhooks does not send a signed body to this URL: ${reason}.`,
104
+ fix: "Use an `https` URL on a public host, with no user name or password, such as `https://relay.t3.codes/hooks/...`. A member endpoint also needs a host of its allowlist."
105
+ },
70
106
  WEBHOOKS_URL_UNSET: {
71
107
  why: ({ name, webhook }) => `The webhook ${webhook} reads its URL from \`${name}\`, but this server has no value for it.`,
72
108
  fix: "Set the variable to the URL of the receiver: in `.env` for `vite dev`, and as a secret on the host for production. Keep it secret when the URL holds a token."
@@ -77,5 +113,4 @@ const webhooksErrors = /*#__PURE__*/ defineErrors({
77
113
  }
78
114
  }
79
115
  });
80
- //#endregion
81
116
  export { webhooksErrors as t };
package/dist/index.d.ts CHANGED
@@ -1,6 +1,131 @@
1
- import { A as WebhookDeliveryErrorCode, D as WebhookSignature, E as WebhookOptions, O as defineWebhook, T as WebhookEvent, i as WebhookEventBody, k as SendWebhookErrorCode, r as SendWebhookResult, w as WebhookDefinition } from "./runtime-mqwMGfyX.js";
1
+ import { S as WebhookDeliveryErrorCode, _ as CreateMemberEndpointErrorCode, a as SendToMemberEndpointResult, b as SendToMemberEndpointErrorCode, c as enableMemberEndpoint, d as listMemberDeliveries, f as listMemberEndpoints, g as sendToMemberEndpoint, h as removeMemberEndpoints, i as SendToMemberEndpointOptions, l as getMemberDeliveryState, m as removeMemberEndpoint, n as MemberDeliveries, o as createMemberEndpoint, p as memberEndpointHosts, r as MemberEndpointWithLastDelivery, s as disableMemberEndpoint, t as CreateMemberEndpointOptions, u as getMemberEndpoint, v as MemberEndpointErrorCode, x as SendWebhookErrorCode, y as MemberPairingErrorCode } from "./members-BjDcAAhY.js";
2
+ import { B as WebhookSignature, F as sealWebhooksText, I as unsealWebhooksText, L as WebhookDefinition, R as WebhookEvent, V as defineWebhook, a as SendWebhookResult, s as WebhookEventBody, z as WebhookOptions } from "./runtime-BdILDcW1.js";
3
+ import { a as MemberLastDelivery, i as MemberEndpointKind, o as MemberPairingState, r as MemberEndpoint } from "./database-C5cwO1an.js";
2
4
  import { Result } from "@vite-hub/runtime";
3
- //#region src/index.d.ts
5
+ /** How long a pairing code works: 10 minutes. */
6
+ export declare const memberPairingLifetime: number;
7
+ /**
8
+ * The T3 thread link of a pair post, or `null`. Apps put it in an `href`, such as **Open thread**, so anything but a T3
9
+ * thread link is dropped.
10
+ */
11
+ export declare function memberPairingAddress(value: unknown): string | null;
12
+ /** A pairing code, as its owner polls it. It never holds the URL or the secret. */
13
+ interface MemberPairing {
14
+ state: MemberPairingState;
15
+ owner: string;
16
+ /** The agent that used the code, such as `"t3"`, `"claude-code"`, or `"codex"`. */
17
+ agent: string | null;
18
+ /** The host of the agent's URL, such as `relay.t3.codes`. `null` for an inbox. */
19
+ host: string | null;
20
+ /** Where the agent can be reached, such as its T3 thread link, when the pair post gave one. */
21
+ address: string | null;
22
+ expiresAt: number;
23
+ }
24
+ /** What `pairMemberEndpoint()` returns: the code paired, or why it did not. */
25
+ type MemberPairResult = {
26
+ status: "paired";
27
+ pairing: MemberPairing;
28
+ } | {
29
+ status: "expired" | "used";
30
+ } | {
31
+ status: "refused";
32
+ reason: string;
33
+ };
34
+ /**
35
+ * Mints a pairing code for `owner` and returns `[error, { code, secret, expiresAt }]`. Give both to the member's agent,
36
+ * such as in a setup prompt: it signs its webhook schedule with `secret`, then posts the code with its URL to a route
37
+ * that calls `pairMemberEndpoint()`. The code works once, for 10 minutes, and only the owner may allow it. Starting a
38
+ * new pairing deletes the owner's finished codes.
39
+ *
40
+ * ```ts
41
+ * import { startMemberPairing } from "@vite-hub/webhooks"
42
+ *
43
+ * const [error, pairing] = await startMemberPairing("user_ana")
44
+ * ```
45
+ */
46
+ export declare function startMemberPairing(owner: string): Promise<Result<{
47
+ code: string;
48
+ secret: string;
49
+ expiresAt: number;
50
+ }, MemberPairingErrorCode>>;
51
+ /**
52
+ * Pairs the agent that posted `input`: `{ code, url, thread? }` for a receiver URL, such as the `webhookUrl` of a T3
53
+ * task, or `{ code, inbox }` for an agent that reads its inbox, `"Claude Code"` or `"Codex"`. The URL must pass
54
+ * `checkWebhookUrl()` with `hosts`, which defaults to the T3 Code relay; a refused URL uses up the code. `thread` is kept
55
+ * as the endpoint's address only when it is a T3 thread link. Returns `[error, result]`, where a code that is unknown,
56
+ * too old, used, or refused is a `status`, not an error. Input that is not one of the two shapes is an error.
57
+ */
58
+ export declare function pairMemberEndpoint(input: unknown, options?: {
59
+ hosts?: readonly string[];
60
+ }): Promise<Result<MemberPairResult, MemberPairingErrorCode>>;
61
+ /**
62
+ * Uses up a waiting code without pairing, such as when its pair post came over plain http, where anyone on the way could
63
+ * read it. Returns `[error, refused]`.
64
+ */
65
+ export declare function refuseMemberPairing(code: string): Promise<Result<boolean, MemberPairingErrorCode>>;
66
+ /** The pairing of `code` while it works, when `owner` minted it, as `[error, pairing]`; `null` otherwise. */
67
+ export declare function getMemberPairing(owner: string, code: string): Promise<Result<MemberPairing | null, MemberPairingErrorCode>>;
68
+ /** Deletes the code of `owner`, such as when they close the setup prompt. */
69
+ export declare function cancelMemberPairing(owner: string, code: string): Promise<Result<void, MemberPairingErrorCode>>;
70
+ /** What `allowMemberPairing()` returns. */
71
+ type MemberAllowResult = {
72
+ status: "allowed";
73
+ endpoint: MemberEndpoint;
74
+ pairing: MemberPairing;
75
+ } | {
76
+ status: "expired" | "not-owner";
77
+ };
78
+ /** Options of `allowMemberPairing()`. */
79
+ interface AllowMemberPairingOptions {
80
+ /** A name that people read, such as `"T3 Code thread"`. */
81
+ name: string | ((pairing: MemberPairing) => string);
82
+ /** The name of the member, for the Console. */
83
+ ownerName?: string;
84
+ /** The email of the member, only when it is verified. */
85
+ ownerEmail?: string;
86
+ /** The hosts that the agent's URL may use now. Default: the T3 Code relay. */
87
+ hosts?: readonly string[];
88
+ }
89
+ /**
90
+ * Creates the endpoint of the agent that paired with `code`, when `owner` minted it, and uses up the code. Returns
91
+ * `[error, { status: "allowed", endpoint, pairing }]`, `status: "not-owner"` when another member minted the code, or
92
+ * `status: "expired"` when it is unknown, too old, used, or not paired yet.
93
+ * The endpoint's address is the agent's T3 thread link when it gave one, so a send with that address reaches it.
94
+ *
95
+ * ```ts
96
+ * import { allowMemberPairing } from "@vite-hub/webhooks"
97
+ *
98
+ * const [error, allowed] = await allowMemberPairing("user_ana", code, { name: "T3 Code thread" })
99
+ * ```
100
+ */
101
+ export declare function allowMemberPairing(owner: string, code: string, options: AllowMemberPairingOptions): Promise<Result<MemberAllowResult, MemberPairingErrorCode | CreateMemberEndpointErrorCode>>;
102
+ /** Options of `checkWebhookUrl()`. */
103
+ interface CheckWebhookUrlOptions {
104
+ /**
105
+ * The hosts that the URL may use, such as `["relay.t3.codes"]`. A host matches itself only, not its subdomains.
106
+ * Without it, any public host passes.
107
+ */
108
+ hosts?: readonly string[];
109
+ }
110
+ /**
111
+ * Checks that `url` is safe to post a signed body to, and returns it parsed as `[error, url]`. It refuses a URL that:
112
+ *
113
+ * - is not `https`, or holds a user name or a password;
114
+ * - uses a host outside `hosts`, when you pass `hosts`;
115
+ * - names a loopback, private, link-local, or cloud metadata address, such as `127.0.0.1`, `10.0.0.1`,
116
+ * `169.254.169.254`, or `[::1]`;
117
+ * - on Node, Bun, and Deno, has a name that resolves to such an address, or does not resolve.
118
+ *
119
+ * Cloudflare Workers cannot resolve names, so there a name passes on the host allowlist alone. Webhooks checks the URL
120
+ * again before each delivery.
121
+ *
122
+ * ```ts
123
+ * import { checkWebhookUrl } from "@vite-hub/webhooks"
124
+ *
125
+ * const [error] = await checkWebhookUrl("https://relay.t3.codes/hooks/abc", { hosts: ["relay.t3.codes"] })
126
+ * ```
127
+ */
128
+ export declare function checkWebhookUrl(url: string, options?: CheckWebhookUrlOptions): Promise<Result<URL, "WEBHOOKS_URL_REFUSED">>;
4
129
  /** The webhooks of `server/webhooks/`. The generated `.vitehub/webhooks.d.ts` adds one key for each file. */
5
130
  export interface WebhookRegistry {}
6
131
  /** The name of a webhook of `server/webhooks/`. */
@@ -31,5 +156,4 @@ export interface SendWebhookOptions {
31
156
  * ```
32
157
  */
33
158
  export declare function sendWebhook<TName extends WebhookName>(name: TName, body: unknown, options: SendWebhookOptions): Promise<Result<SendWebhookResult, SendWebhookErrorCode>>;
34
- //#endregion
35
- export { type SendWebhookErrorCode, type SendWebhookResult, type WebhookDefinition, type WebhookDeliveryErrorCode, type WebhookEvent, type WebhookEventBody, type WebhookOptions, type WebhookSignature, defineWebhook };
159
+ export { type AllowMemberPairingOptions, type CheckWebhookUrlOptions, type CreateMemberEndpointErrorCode, type CreateMemberEndpointOptions, type MemberAllowResult, type MemberDeliveries, type MemberEndpoint, type MemberEndpointErrorCode, type MemberEndpointKind, type MemberEndpointWithLastDelivery, type MemberLastDelivery, type MemberPairResult, type MemberPairing, type MemberPairingErrorCode, type MemberPairingState, type SendToMemberEndpointErrorCode, type SendToMemberEndpointOptions, type SendToMemberEndpointResult, type SendWebhookErrorCode, type SendWebhookResult, type WebhookDefinition, type WebhookDeliveryErrorCode, type WebhookEvent, type WebhookEventBody, type WebhookOptions, type WebhookSignature, createMemberEndpoint, defineWebhook, disableMemberEndpoint, enableMemberEndpoint, getMemberDeliveryState, getMemberEndpoint, listMemberDeliveries, listMemberEndpoints, memberEndpointHosts, removeMemberEndpoint, removeMemberEndpoints, sealWebhooksText, sendToMemberEndpoint, unsealWebhooksText };