@tagma/trigger-webhook 0.2.0 → 0.2.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 (3) hide show
  1. package/LICENSE +21 -21
  2. package/package.json +2 -2
  3. package/src/index.ts +288 -288
package/LICENSE CHANGED
@@ -1,21 +1,21 @@
1
- MIT License
2
-
3
- Copyright (c) 2026 Tagma
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Tagma
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tagma/trigger-webhook",
3
- "version": "0.2.0",
3
+ "version": "0.2.1",
4
4
  "description": "HTTP webhook trigger plugin for tagma-sdk pipelines",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -48,7 +48,7 @@
48
48
  "prepublishOnly": "bun run build"
49
49
  },
50
50
  "peerDependencies": {
51
- "@tagma/types": "0.4.0"
51
+ "@tagma/types": "0.4.2"
52
52
  },
53
53
  "devDependencies": {
54
54
  "bun-types": "^1.3.11",
package/src/index.ts CHANGED
@@ -1,288 +1,288 @@
1
- // ═══ Webhook Trigger Plugin ═══
2
- //
3
- // Spins up a Bun.serve HTTP listener and resolves the trigger when a POST
4
- // arrives on the configured path. Optional HMAC-SHA256 validation via the
5
- // `x-tagma-signature: sha256=<hex>` header protects against unauthenticated
6
- // callers when the secret env var is set.
7
- //
8
- // Multiple tasks sharing the same `(port, path)` pair hit the same listener
9
- // instance and are enqueued as waiters — the next inbound request wakes one
10
- // waiter (FIFO). This keeps the plugin lightweight even when a pipeline has
11
- // many webhook-triggered tasks.
12
- //
13
- // Usage in pipeline.yaml:
14
- // plugins: ["@tagma/trigger-webhook"]
15
- // tracks:
16
- // - tasks:
17
- // - id: deploy
18
- // trigger:
19
- // type: webhook
20
- // port: 8787
21
- // path: /hooks/deploy
22
- // secret_env: TAGMA_WEBHOOK_SECRET
23
- // timeout: 10m
24
-
25
- import type { TriggerPlugin, TriggerContext } from '@tagma/types';
26
- import { createHmac, timingSafeEqual } from 'node:crypto';
27
-
28
- type Resolver = (payload: unknown) => void;
29
-
30
- interface WebhookServerState {
31
- readonly port: number;
32
- readonly path: string;
33
- readonly secretEnv: string | undefined;
34
- readonly waiters: Resolver[];
35
- }
36
-
37
- // Module-level so concurrent tasks on the same (port, path) share one
38
- // listener. Bun.serve refuses to bind a port twice, so this sharing is
39
- // required — not just an optimization.
40
- const servers = new Map<string, WebhookServerState>();
41
-
42
- function serverKey(port: number, path: string, hostname: string): string {
43
- return `${hostname}::${port}::${path}`;
44
- }
45
-
46
- const DEFAULT_WEBHOOK_HOST = '127.0.0.1';
47
-
48
- function parseDurationSafe(raw: unknown, fallback: number): number {
49
- if (raw == null) return fallback;
50
- const str = String(raw).trim();
51
- const m = str.match(/^(\d+(?:\.\d+)?)(ms|s|m|h)?$/);
52
- if (!m) return fallback;
53
- const n = Number(m[1]);
54
- switch (m[2]) {
55
- case 'ms':
56
- return n;
57
- case 'm':
58
- return n * 60_000;
59
- case 'h':
60
- return n * 3_600_000;
61
- case 's':
62
- default:
63
- return n * 1000;
64
- }
65
- }
66
-
67
- function verifySignature(rawBody: string, header: string, secret: string): boolean {
68
- const expected = 'sha256=' + createHmac('sha256', secret).update(rawBody).digest('hex');
69
- const a = Buffer.from(header);
70
- const b = Buffer.from(expected);
71
- if (a.length !== b.length) return false;
72
- return timingSafeEqual(a, b);
73
- }
74
-
75
- function ensureServer(
76
- port: number,
77
- path: string,
78
- secretEnv: string | undefined,
79
- hostname: string,
80
- ): WebhookServerState {
81
- const key = serverKey(port, path, hostname);
82
- const existing = servers.get(key);
83
- if (existing) return existing;
84
-
85
- const state: WebhookServerState = {
86
- port,
87
- path,
88
- secretEnv,
89
- waiters: [],
90
- };
91
-
92
- Bun.serve({
93
- port,
94
- // Default to loopback so the webhook endpoint is not reachable from the
95
- // LAN unless the user explicitly sets `host` in their YAML (e.g. for
96
- // container/WSL scenarios). Without this, Bun.serve listens on all
97
- // interfaces and a secret-less webhook would accept traffic from any
98
- // network-adjacent caller.
99
- hostname,
100
- async fetch(req) {
101
- const url = new URL(req.url);
102
- if (url.pathname !== path) {
103
- return new Response('not found', { status: 404 });
104
- }
105
- if (req.method !== 'POST') {
106
- return new Response('method not allowed', { status: 405 });
107
- }
108
-
109
- const rawBody = await req.text();
110
-
111
- // HMAC gate — bypassed when no secret env is configured, which is
112
- // acceptable for loopback dev but should always be set in production.
113
- const secret = state.secretEnv ? process.env[state.secretEnv] : undefined;
114
- if (state.secretEnv) {
115
- if (!secret) {
116
- return new Response(`env var ${state.secretEnv} not set`, { status: 500 });
117
- }
118
- const sigHeader = req.headers.get('x-tagma-signature') ?? '';
119
- if (!verifySignature(rawBody, sigHeader, secret)) {
120
- return new Response('invalid signature', { status: 401 });
121
- }
122
- }
123
-
124
- // Decode JSON if possible so downstream tasks get structured data.
125
- //
126
- // D22: when the sender explicitly declared `application/json`, a parse
127
- // failure is a contract violation — silently falling through to the
128
- // raw-string payload meant downstream tasks that did `payload.field`
129
- // crashed later with "Cannot read properties of undefined", far away
130
- // from the actual cause. Return 400 so the sender sees the problem
131
- // up front. Bodies without a JSON content-type still pass through
132
- // untouched, which preserves the "any POST body" escape hatch.
133
- let payload: unknown = rawBody;
134
- const contentType = req.headers.get('content-type') ?? '';
135
- if (contentType.includes('application/json')) {
136
- try {
137
- payload = JSON.parse(rawBody);
138
- } catch (err) {
139
- const msg = err instanceof Error ? err.message : String(err);
140
- return new Response(`invalid JSON body: ${msg}`, { status: 400 });
141
- }
142
- }
143
-
144
- const waiter = state.waiters.shift();
145
- if (waiter) {
146
- waiter(payload);
147
- return new Response('ok', { status: 202 });
148
- }
149
- // No task is currently waiting on this endpoint — reject loudly so
150
- // callers know the webhook wasn't actually consumed by a pipeline.
151
- return new Response('no waiting task', { status: 409 });
152
- },
153
- error(err) {
154
- console.error(`[webhook] server error on :${port}${path}:`, err);
155
- return new Response('internal error', { status: 500 });
156
- },
157
- });
158
-
159
- servers.set(key, state);
160
- return state;
161
- }
162
-
163
- const WebhookTrigger: TriggerPlugin = {
164
- name: 'webhook',
165
- schema: {
166
- description: 'Wait for an HTTP POST to arrive on a local listener before the task runs.',
167
- fields: {
168
- port: {
169
- type: 'number',
170
- required: true,
171
- default: 8787,
172
- min: 1,
173
- max: 65535,
174
- description: 'TCP port to listen on.',
175
- placeholder: '8787',
176
- },
177
- path: {
178
- type: 'string',
179
- required: true,
180
- default: '/webhook',
181
- description: 'URL path to match (e.g. /hooks/deploy).',
182
- placeholder: '/webhook',
183
- },
184
- secret_env: {
185
- type: 'string',
186
- description:
187
- 'Env var containing the HMAC-SHA256 secret. When set, POSTs must include an x-tagma-signature: sha256=<hex> header computed over the raw body.',
188
- placeholder: 'TAGMA_WEBHOOK_SECRET',
189
- },
190
- host: {
191
- type: 'string',
192
- default: DEFAULT_WEBHOOK_HOST,
193
- description:
194
- 'Interface to bind on. Defaults to 127.0.0.1 so the webhook is only reachable from the local machine. Set to 0.0.0.0 to accept LAN traffic (only do this when secret_env is also set).',
195
- placeholder: DEFAULT_WEBHOOK_HOST,
196
- },
197
- timeout: {
198
- type: 'duration',
199
- description: 'Maximum wait time (e.g. 10m). Omit or 0 to wait indefinitely.',
200
- placeholder: '10m',
201
- },
202
- },
203
- },
204
-
205
- watch(config: Record<string, unknown>, ctx: TriggerContext): Promise<unknown> {
206
- const rawPort = config.port;
207
- const port = typeof rawPort === 'number' ? rawPort : Number(rawPort);
208
- if (!Number.isFinite(port) || port < 1 || port > 65535) {
209
- throw new Error(`webhook trigger: "port" must be 1-65535, got ${String(rawPort)}`);
210
- }
211
-
212
- const path = (config.path as string | undefined) ?? '/webhook';
213
- if (!path.startsWith('/')) {
214
- throw new Error(`webhook trigger: "path" must start with "/", got ${path}`);
215
- }
216
-
217
- const secretEnv = config.secret_env as string | undefined;
218
- const rawHost = config.host;
219
- const hostname =
220
- typeof rawHost === 'string' && rawHost.trim().length > 0
221
- ? rawHost.trim()
222
- : DEFAULT_WEBHOOK_HOST;
223
- const timeoutMs = config.timeout != null ? parseDurationSafe(config.timeout, 0) : 0;
224
-
225
- if (hostname !== DEFAULT_WEBHOOK_HOST && hostname !== 'localhost' && !secretEnv) {
226
- // Loud warning — the user has opted into a non-loopback bind without
227
- // HMAC. Refuse by default rather than silently expose the endpoint to
228
- // the network.
229
- throw new Error(
230
- `webhook trigger: binding to "${hostname}" without secret_env is refused — set secret_env to enable HMAC authentication before exposing to non-loopback interfaces`,
231
- );
232
- }
233
-
234
- const state = ensureServer(port, path, secretEnv, hostname);
235
-
236
- return new Promise<unknown>((resolvePromise, rejectPromise) => {
237
- if (ctx.signal.aborted) {
238
- rejectPromise(new Error('Pipeline aborted'));
239
- return;
240
- }
241
-
242
- let settled = false;
243
- let timer: ReturnType<typeof setTimeout> | null = null;
244
-
245
- const onFire: Resolver = (payload) => {
246
- if (settled) return;
247
- settled = true;
248
- cleanup();
249
- resolvePromise(payload);
250
- };
251
-
252
- const onAbort = (): void => {
253
- if (settled) return;
254
- settled = true;
255
- cleanup();
256
- rejectPromise(new Error('Pipeline aborted'));
257
- };
258
-
259
- const cleanup = (): void => {
260
- if (timer) clearTimeout(timer);
261
- ctx.signal.removeEventListener('abort', onAbort);
262
- const idx = state.waiters.indexOf(onFire);
263
- if (idx !== -1) state.waiters.splice(idx, 1);
264
- };
265
-
266
- state.waiters.push(onFire);
267
- ctx.signal.addEventListener('abort', onAbort, { once: true });
268
-
269
- if (timeoutMs > 0) {
270
- timer = setTimeout(() => {
271
- if (settled) return;
272
- settled = true;
273
- cleanup();
274
- rejectPromise(
275
- new Error(
276
- `webhook trigger timeout: no POST on :${port}${path} within ${String(config.timeout)}`,
277
- ),
278
- );
279
- }, timeoutMs);
280
- }
281
- });
282
- },
283
- };
284
-
285
- // ═══ Plugin self-description exports ═══
286
- export const pluginCategory = 'triggers';
287
- export const pluginType = 'webhook';
288
- export default WebhookTrigger;
1
+ // ═══ Webhook Trigger Plugin ═══
2
+ //
3
+ // Spins up a Bun.serve HTTP listener and resolves the trigger when a POST
4
+ // arrives on the configured path. Optional HMAC-SHA256 validation via the
5
+ // `x-tagma-signature: sha256=<hex>` header protects against unauthenticated
6
+ // callers when the secret env var is set.
7
+ //
8
+ // Multiple tasks sharing the same `(port, path)` pair hit the same listener
9
+ // instance and are enqueued as waiters — the next inbound request wakes one
10
+ // waiter (FIFO). This keeps the plugin lightweight even when a pipeline has
11
+ // many webhook-triggered tasks.
12
+ //
13
+ // Usage in pipeline.yaml:
14
+ // plugins: ["@tagma/trigger-webhook"]
15
+ // tracks:
16
+ // - tasks:
17
+ // - id: deploy
18
+ // trigger:
19
+ // type: webhook
20
+ // port: 8787
21
+ // path: /hooks/deploy
22
+ // secret_env: TAGMA_WEBHOOK_SECRET
23
+ // timeout: 10m
24
+
25
+ import type { TriggerPlugin, TriggerContext } from '@tagma/types';
26
+ import { createHmac, timingSafeEqual } from 'node:crypto';
27
+
28
+ type Resolver = (payload: unknown) => void;
29
+
30
+ interface WebhookServerState {
31
+ readonly port: number;
32
+ readonly path: string;
33
+ readonly secretEnv: string | undefined;
34
+ readonly waiters: Resolver[];
35
+ }
36
+
37
+ // Module-level so concurrent tasks on the same (port, path) share one
38
+ // listener. Bun.serve refuses to bind a port twice, so this sharing is
39
+ // required — not just an optimization.
40
+ const servers = new Map<string, WebhookServerState>();
41
+
42
+ function serverKey(port: number, path: string, hostname: string): string {
43
+ return `${hostname}::${port}::${path}`;
44
+ }
45
+
46
+ const DEFAULT_WEBHOOK_HOST = '127.0.0.1';
47
+
48
+ function parseDurationSafe(raw: unknown, fallback: number): number {
49
+ if (raw == null) return fallback;
50
+ const str = String(raw).trim();
51
+ const m = str.match(/^(\d+(?:\.\d+)?)(ms|s|m|h)?$/);
52
+ if (!m) return fallback;
53
+ const n = Number(m[1]);
54
+ switch (m[2]) {
55
+ case 'ms':
56
+ return n;
57
+ case 'm':
58
+ return n * 60_000;
59
+ case 'h':
60
+ return n * 3_600_000;
61
+ case 's':
62
+ default:
63
+ return n * 1000;
64
+ }
65
+ }
66
+
67
+ function verifySignature(rawBody: string, header: string, secret: string): boolean {
68
+ const expected = 'sha256=' + createHmac('sha256', secret).update(rawBody).digest('hex');
69
+ const a = Buffer.from(header);
70
+ const b = Buffer.from(expected);
71
+ if (a.length !== b.length) return false;
72
+ return timingSafeEqual(a, b);
73
+ }
74
+
75
+ function ensureServer(
76
+ port: number,
77
+ path: string,
78
+ secretEnv: string | undefined,
79
+ hostname: string,
80
+ ): WebhookServerState {
81
+ const key = serverKey(port, path, hostname);
82
+ const existing = servers.get(key);
83
+ if (existing) return existing;
84
+
85
+ const state: WebhookServerState = {
86
+ port,
87
+ path,
88
+ secretEnv,
89
+ waiters: [],
90
+ };
91
+
92
+ Bun.serve({
93
+ port,
94
+ // Default to loopback so the webhook endpoint is not reachable from the
95
+ // LAN unless the user explicitly sets `host` in their YAML (e.g. for
96
+ // container/WSL scenarios). Without this, Bun.serve listens on all
97
+ // interfaces and a secret-less webhook would accept traffic from any
98
+ // network-adjacent caller.
99
+ hostname,
100
+ async fetch(req) {
101
+ const url = new URL(req.url);
102
+ if (url.pathname !== path) {
103
+ return new Response('not found', { status: 404 });
104
+ }
105
+ if (req.method !== 'POST') {
106
+ return new Response('method not allowed', { status: 405 });
107
+ }
108
+
109
+ const rawBody = await req.text();
110
+
111
+ // HMAC gate — bypassed when no secret env is configured, which is
112
+ // acceptable for loopback dev but should always be set in production.
113
+ const secret = state.secretEnv ? process.env[state.secretEnv] : undefined;
114
+ if (state.secretEnv) {
115
+ if (!secret) {
116
+ return new Response(`env var ${state.secretEnv} not set`, { status: 500 });
117
+ }
118
+ const sigHeader = req.headers.get('x-tagma-signature') ?? '';
119
+ if (!verifySignature(rawBody, sigHeader, secret)) {
120
+ return new Response('invalid signature', { status: 401 });
121
+ }
122
+ }
123
+
124
+ // Decode JSON if possible so downstream tasks get structured data.
125
+ //
126
+ // D22: when the sender explicitly declared `application/json`, a parse
127
+ // failure is a contract violation — silently falling through to the
128
+ // raw-string payload meant downstream tasks that did `payload.field`
129
+ // crashed later with "Cannot read properties of undefined", far away
130
+ // from the actual cause. Return 400 so the sender sees the problem
131
+ // up front. Bodies without a JSON content-type still pass through
132
+ // untouched, which preserves the "any POST body" escape hatch.
133
+ let payload: unknown = rawBody;
134
+ const contentType = req.headers.get('content-type') ?? '';
135
+ if (contentType.includes('application/json')) {
136
+ try {
137
+ payload = JSON.parse(rawBody);
138
+ } catch (err) {
139
+ const msg = err instanceof Error ? err.message : String(err);
140
+ return new Response(`invalid JSON body: ${msg}`, { status: 400 });
141
+ }
142
+ }
143
+
144
+ const waiter = state.waiters.shift();
145
+ if (waiter) {
146
+ waiter(payload);
147
+ return new Response('ok', { status: 202 });
148
+ }
149
+ // No task is currently waiting on this endpoint — reject loudly so
150
+ // callers know the webhook wasn't actually consumed by a pipeline.
151
+ return new Response('no waiting task', { status: 409 });
152
+ },
153
+ error(err) {
154
+ console.error(`[webhook] server error on :${port}${path}:`, err);
155
+ return new Response('internal error', { status: 500 });
156
+ },
157
+ });
158
+
159
+ servers.set(key, state);
160
+ return state;
161
+ }
162
+
163
+ const WebhookTrigger: TriggerPlugin = {
164
+ name: 'webhook',
165
+ schema: {
166
+ description: 'Wait for an HTTP POST to arrive on a local listener before the task runs.',
167
+ fields: {
168
+ port: {
169
+ type: 'number',
170
+ required: true,
171
+ default: 8787,
172
+ min: 1,
173
+ max: 65535,
174
+ description: 'TCP port to listen on.',
175
+ placeholder: '8787',
176
+ },
177
+ path: {
178
+ type: 'string',
179
+ required: true,
180
+ default: '/webhook',
181
+ description: 'URL path to match (e.g. /hooks/deploy).',
182
+ placeholder: '/webhook',
183
+ },
184
+ secret_env: {
185
+ type: 'string',
186
+ description:
187
+ 'Env var containing the HMAC-SHA256 secret. When set, POSTs must include an x-tagma-signature: sha256=<hex> header computed over the raw body.',
188
+ placeholder: 'TAGMA_WEBHOOK_SECRET',
189
+ },
190
+ host: {
191
+ type: 'string',
192
+ default: DEFAULT_WEBHOOK_HOST,
193
+ description:
194
+ 'Interface to bind on. Defaults to 127.0.0.1 so the webhook is only reachable from the local machine. Set to 0.0.0.0 to accept LAN traffic (only do this when secret_env is also set).',
195
+ placeholder: DEFAULT_WEBHOOK_HOST,
196
+ },
197
+ timeout: {
198
+ type: 'duration',
199
+ description: 'Maximum wait time (e.g. 10m). Omit or 0 to wait indefinitely.',
200
+ placeholder: '10m',
201
+ },
202
+ },
203
+ },
204
+
205
+ watch(config: Record<string, unknown>, ctx: TriggerContext): Promise<unknown> {
206
+ const rawPort = config.port;
207
+ const port = typeof rawPort === 'number' ? rawPort : Number(rawPort);
208
+ if (!Number.isFinite(port) || port < 1 || port > 65535) {
209
+ throw new Error(`webhook trigger: "port" must be 1-65535, got ${String(rawPort)}`);
210
+ }
211
+
212
+ const path = (config.path as string | undefined) ?? '/webhook';
213
+ if (!path.startsWith('/')) {
214
+ throw new Error(`webhook trigger: "path" must start with "/", got ${path}`);
215
+ }
216
+
217
+ const secretEnv = config.secret_env as string | undefined;
218
+ const rawHost = config.host;
219
+ const hostname =
220
+ typeof rawHost === 'string' && rawHost.trim().length > 0
221
+ ? rawHost.trim()
222
+ : DEFAULT_WEBHOOK_HOST;
223
+ const timeoutMs = config.timeout != null ? parseDurationSafe(config.timeout, 0) : 0;
224
+
225
+ if (hostname !== DEFAULT_WEBHOOK_HOST && hostname !== 'localhost' && !secretEnv) {
226
+ // Loud warning — the user has opted into a non-loopback bind without
227
+ // HMAC. Refuse by default rather than silently expose the endpoint to
228
+ // the network.
229
+ throw new Error(
230
+ `webhook trigger: binding to "${hostname}" without secret_env is refused — set secret_env to enable HMAC authentication before exposing to non-loopback interfaces`,
231
+ );
232
+ }
233
+
234
+ const state = ensureServer(port, path, secretEnv, hostname);
235
+
236
+ return new Promise<unknown>((resolvePromise, rejectPromise) => {
237
+ if (ctx.signal.aborted) {
238
+ rejectPromise(new Error('Pipeline aborted'));
239
+ return;
240
+ }
241
+
242
+ let settled = false;
243
+ let timer: ReturnType<typeof setTimeout> | null = null;
244
+
245
+ const onFire: Resolver = (payload) => {
246
+ if (settled) return;
247
+ settled = true;
248
+ cleanup();
249
+ resolvePromise(payload);
250
+ };
251
+
252
+ const onAbort = (): void => {
253
+ if (settled) return;
254
+ settled = true;
255
+ cleanup();
256
+ rejectPromise(new Error('Pipeline aborted'));
257
+ };
258
+
259
+ const cleanup = (): void => {
260
+ if (timer) clearTimeout(timer);
261
+ ctx.signal.removeEventListener('abort', onAbort);
262
+ const idx = state.waiters.indexOf(onFire);
263
+ if (idx !== -1) state.waiters.splice(idx, 1);
264
+ };
265
+
266
+ state.waiters.push(onFire);
267
+ ctx.signal.addEventListener('abort', onAbort, { once: true });
268
+
269
+ if (timeoutMs > 0) {
270
+ timer = setTimeout(() => {
271
+ if (settled) return;
272
+ settled = true;
273
+ cleanup();
274
+ rejectPromise(
275
+ new Error(
276
+ `webhook trigger timeout: no POST on :${port}${path} within ${String(config.timeout)}`,
277
+ ),
278
+ );
279
+ }, timeoutMs);
280
+ }
281
+ });
282
+ },
283
+ };
284
+
285
+ // ═══ Plugin self-description exports ═══
286
+ export const pluginCategory = 'triggers';
287
+ export const pluginType = 'webhook';
288
+ export default WebhookTrigger;