@tagma/trigger-webhook 0.2.6 → 0.2.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +9 -9
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +44 -12
- package/dist/index.js.map +1 -1
- package/package.json +5 -6
- package/src/index.test.ts +0 -16
- package/src/index.ts +0 -278
package/README.md
CHANGED
|
@@ -55,22 +55,22 @@ await tagma.registry.loadPlugins(['@tagma/trigger-webhook'], process.cwd());
|
|
|
55
55
|
|
|
56
56
|
## Config
|
|
57
57
|
|
|
58
|
-
| Field | Type | Default | Notes
|
|
59
|
-
| ------------ | -------- | ------------ |
|
|
60
|
-
| `port` | number | _(required)_ | TCP port to listen on (1-65535)
|
|
61
|
-
| `path` | string | `/webhook` | URL path to match; must start with `/`
|
|
62
|
-
| `host` | string | `127.0.0.1` | Interface to bind. Defaults to loopback. Setting to `0.0.0.0` or any non-loopback address without `secret_env` is refused at config time
|
|
63
|
-
| `secret_env` | string | _(none)_ | Env var holding the HMAC-SHA256 secret. When set, requests must include `x-tagma-signature`
|
|
64
|
-
| `timeout` | duration | _(forever)_ | Max wait time; omit (or set to `0`) for unbounded wait
|
|
58
|
+
| Field | Type | Default | Notes |
|
|
59
|
+
| ------------ | -------- | ------------ | ---------------------------------------------------------------------------------------------------------------------------------------- |
|
|
60
|
+
| `port` | number | _(required)_ | TCP port to listen on (1-65535) |
|
|
61
|
+
| `path` | string | `/webhook` | URL path to match; must start with `/` |
|
|
62
|
+
| `host` | string | `127.0.0.1` | Interface to bind. Defaults to loopback. Setting to `0.0.0.0` or any non-loopback address without `secret_env` is refused at config time |
|
|
63
|
+
| `secret_env` | string | _(none)_ | Env var holding the HMAC-SHA256 secret. When set, requests must include `x-tagma-signature` |
|
|
64
|
+
| `timeout` | duration | _(forever)_ | Max wait time; omit (or set to `0`) for unbounded wait |
|
|
65
65
|
|
|
66
66
|
## Behavior
|
|
67
67
|
|
|
68
|
-
- A single `Bun.serve` listener is created per unique `(host, port, path)` triple and shared across all tasks that watch it. Multiple tasks on the same endpoint form a FIFO waiter queue
|
|
68
|
+
- A single `Bun.serve` listener is created per unique `(host, port, path)` triple and shared across all tasks that watch it. The same endpoint cannot be reused with a different `secret_env` in the same process. Multiple tasks on the same endpoint form a FIFO waiter queue; the next POST wakes one waiter.
|
|
69
69
|
- Default bind is `127.0.0.1` so the endpoint is only reachable from the local machine. A non-loopback `host` without `secret_env` is refused.
|
|
70
70
|
- Signature header format: `x-tagma-signature: sha256=<hex>`, HMAC-SHA256 of the raw request body using the secret. Verification is constant-time.
|
|
71
71
|
- JSON bodies (`content-type: application/json`) are parsed and handed to the task as the trigger payload. A malformed JSON body under that content-type returns `400 invalid JSON body`. Other content-types are passed through as raw strings.
|
|
72
72
|
- Successful delivery responds `202 ok`. A POST arriving while no task is waiting is rejected with `409 no waiting task` so the caller can retry once a pipeline is up. Non-matching paths return `404`, non-POST methods return `405`.
|
|
73
|
-
- The listener
|
|
73
|
+
- The listener is reference-counted by waiting tasks. When the last waiter resolves, aborts, or times out, the plugin closes the `Bun.serve` instance and frees the port.
|
|
74
74
|
|
|
75
75
|
## Security
|
|
76
76
|
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAwBA,OAAO,EAGL,KAAK,aAAa,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAwBA,OAAO,EAGL,KAAK,aAAa,EAInB,MAAM,cAAc,CAAC;AA4ItB,eAAO,MAAM,cAAc,EAAE,aAuI5B,CAAC;;;;;;;;;AAEF,wBAOwB"}
|
package/dist/index.js
CHANGED
|
@@ -21,7 +21,7 @@
|
|
|
21
21
|
// path: /hooks/deploy
|
|
22
22
|
// secret_env: TAGMA_WEBHOOK_SECRET
|
|
23
23
|
// timeout: 10m
|
|
24
|
-
import { parseDurationSafe, } from '@tagma/types';
|
|
24
|
+
import { parseDurationSafe, TriggerTimeoutError, } from '@tagma/types';
|
|
25
25
|
import { createHmac, timingSafeEqual } from 'node:crypto';
|
|
26
26
|
// Module-level so concurrent tasks on the same (port, path) share one
|
|
27
27
|
// listener. Bun.serve refuses to bind a port twice, so this sharing is
|
|
@@ -42,15 +42,17 @@ function verifySignature(rawBody, header, secret) {
|
|
|
42
42
|
function ensureServer(port, path, secretEnv, hostname) {
|
|
43
43
|
const key = serverKey(port, path, hostname);
|
|
44
44
|
const existing = servers.get(key);
|
|
45
|
-
if (existing)
|
|
45
|
+
if (existing) {
|
|
46
|
+
if (existing.secretEnv !== secretEnv) {
|
|
47
|
+
throw new Error(`webhook trigger: ${hostname}:${port}${path} is already registered with a different secret_env`);
|
|
48
|
+
}
|
|
46
49
|
return existing;
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
Bun.serve({
|
|
50
|
+
}
|
|
51
|
+
// Bun.serve callbacks need to close over the state object before the server
|
|
52
|
+
// handle exists, then the completed object is assigned once below.
|
|
53
|
+
// eslint-disable-next-line prefer-const
|
|
54
|
+
let state;
|
|
55
|
+
const server = Bun.serve({
|
|
54
56
|
port,
|
|
55
57
|
// Default to loopback so the webhook endpoint is not reachable from the
|
|
56
58
|
// LAN unless the user explicitly sets `host` in their YAML (e.g. for
|
|
@@ -113,9 +115,25 @@ function ensureServer(port, path, secretEnv, hostname) {
|
|
|
113
115
|
return new Response('internal error', { status: 500 });
|
|
114
116
|
},
|
|
115
117
|
});
|
|
118
|
+
state = {
|
|
119
|
+
key,
|
|
120
|
+
port,
|
|
121
|
+
path,
|
|
122
|
+
secretEnv,
|
|
123
|
+
server,
|
|
124
|
+
waiters: [],
|
|
125
|
+
};
|
|
116
126
|
servers.set(key, state);
|
|
117
127
|
return state;
|
|
118
128
|
}
|
|
129
|
+
function closeServerIfIdle(state) {
|
|
130
|
+
if (state.waiters.length > 0)
|
|
131
|
+
return;
|
|
132
|
+
if (servers.get(state.key) !== state)
|
|
133
|
+
return;
|
|
134
|
+
servers.delete(state.key);
|
|
135
|
+
state.server.stop(true);
|
|
136
|
+
}
|
|
119
137
|
export const WebhookTrigger = {
|
|
120
138
|
name: 'webhook',
|
|
121
139
|
schema: {
|
|
@@ -165,7 +183,9 @@ export const WebhookTrigger = {
|
|
|
165
183
|
if (!path.startsWith('/')) {
|
|
166
184
|
throw new Error(`webhook trigger: "path" must start with "/", got ${path}`);
|
|
167
185
|
}
|
|
168
|
-
const secretEnv = config.secret_env
|
|
186
|
+
const secretEnv = typeof config.secret_env === 'string' && config.secret_env.trim().length > 0
|
|
187
|
+
? config.secret_env.trim()
|
|
188
|
+
: undefined;
|
|
169
189
|
const rawHost = config.host;
|
|
170
190
|
const hostname = typeof rawHost === 'string' && rawHost.trim().length > 0
|
|
171
191
|
? rawHost.trim()
|
|
@@ -178,7 +198,10 @@ export const WebhookTrigger = {
|
|
|
178
198
|
throw new Error(`webhook trigger: binding to "${hostname}" without secret_env is refused — set secret_env to enable HMAC authentication before exposing to non-loopback interfaces`);
|
|
179
199
|
}
|
|
180
200
|
const state = ensureServer(port, path, secretEnv, hostname);
|
|
181
|
-
|
|
201
|
+
let dispose = (_reason) => {
|
|
202
|
+
/* assigned below */
|
|
203
|
+
};
|
|
204
|
+
const fired = new Promise((resolvePromise, rejectPromise) => {
|
|
182
205
|
if (ctx.signal.aborted) {
|
|
183
206
|
rejectPromise(new Error('Pipeline aborted'));
|
|
184
207
|
return;
|
|
@@ -206,6 +229,14 @@ export const WebhookTrigger = {
|
|
|
206
229
|
const idx = state.waiters.indexOf(onFire);
|
|
207
230
|
if (idx !== -1)
|
|
208
231
|
state.waiters.splice(idx, 1);
|
|
232
|
+
closeServerIfIdle(state);
|
|
233
|
+
};
|
|
234
|
+
dispose = (reason = 'webhook trigger disposed') => {
|
|
235
|
+
if (settled)
|
|
236
|
+
return;
|
|
237
|
+
settled = true;
|
|
238
|
+
cleanup();
|
|
239
|
+
rejectPromise(new Error(reason));
|
|
209
240
|
};
|
|
210
241
|
state.waiters.push(onFire);
|
|
211
242
|
ctx.signal.addEventListener('abort', onAbort, { once: true });
|
|
@@ -215,10 +246,11 @@ export const WebhookTrigger = {
|
|
|
215
246
|
return;
|
|
216
247
|
settled = true;
|
|
217
248
|
cleanup();
|
|
218
|
-
rejectPromise(new
|
|
249
|
+
rejectPromise(new TriggerTimeoutError(`webhook trigger timeout: no POST on :${port}${path} within ${String(config.timeout)}`));
|
|
219
250
|
}, timeoutMs);
|
|
220
251
|
}
|
|
221
252
|
});
|
|
253
|
+
return { fired, dispose };
|
|
222
254
|
},
|
|
223
255
|
};
|
|
224
256
|
export default {
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,iCAAiC;AACjC,EAAE;AACF,0EAA0E;AAC1E,0EAA0E;AAC1E,4EAA4E;AAC5E,0CAA0C;AAC1C,EAAE;AACF,4EAA4E;AAC5E,4EAA4E;AAC5E,4EAA4E;AAC5E,gCAAgC;AAChC,EAAE;AACF,0BAA0B;AAC1B,wCAAwC;AACxC,YAAY;AACZ,eAAe;AACf,uBAAuB;AACvB,qBAAqB;AACrB,4BAA4B;AAC5B,yBAAyB;AACzB,kCAAkC;AAClC,+CAA+C;AAC/C,2BAA2B;AAE3B,OAAO,EACL,iBAAiB,
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,iCAAiC;AACjC,EAAE;AACF,0EAA0E;AAC1E,0EAA0E;AAC1E,4EAA4E;AAC5E,0CAA0C;AAC1C,EAAE;AACF,4EAA4E;AAC5E,4EAA4E;AAC5E,4EAA4E;AAC5E,gCAAgC;AAChC,EAAE;AACF,0BAA0B;AAC1B,wCAAwC;AACxC,YAAY;AACZ,eAA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G,IAAI,CAAC;oBACf,OAAO,EAAE,CAAC;oBACV,aAAa,CACX,IAAI,mBAAmB,CACrB,wCAAwC,IAAI,GAAG,IAAI,WAAW,MAAM,CAAC,MAAM,CAAC,OAAO,CAAC,EAAE,CACvF,CACF,CAAC;gBACJ,CAAC,EAAE,SAAS,CAAC,CAAC;YAChB,CAAC;QACH,CAAC,CAAC,CAAC;QACH,OAAO,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC;IAC5B,CAAC;CACF,CAAC;AAEF,eAAe;IACb,IAAI,EAAE,wBAAwB;IAC9B,YAAY,EAAE;QACZ,QAAQ,EAAE;YACR,OAAO,EAAE,cAAc;SACxB;KACF;CACoB,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tagma/trigger-webhook",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.8",
|
|
4
4
|
"description": "HTTP webhook trigger plugin for tagma-sdk pipelines",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|
|
@@ -23,8 +23,7 @@
|
|
|
23
23
|
"./package.json": "./package.json"
|
|
24
24
|
},
|
|
25
25
|
"files": [
|
|
26
|
-
"dist"
|
|
27
|
-
"src"
|
|
26
|
+
"dist"
|
|
28
27
|
],
|
|
29
28
|
"publishConfig": {
|
|
30
29
|
"access": "public"
|
|
@@ -44,11 +43,11 @@
|
|
|
44
43
|
"type": "webhook"
|
|
45
44
|
},
|
|
46
45
|
"scripts": {
|
|
47
|
-
"build": "
|
|
46
|
+
"build": "node ../../scripts/build-package.mjs",
|
|
48
47
|
"test": "bun test",
|
|
49
48
|
"prepublishOnly": "bun run build"
|
|
50
49
|
},
|
|
51
|
-
"
|
|
52
|
-
"@tagma/types": "0.4.
|
|
50
|
+
"dependencies": {
|
|
51
|
+
"@tagma/types": "0.4.14"
|
|
53
52
|
}
|
|
54
53
|
}
|
package/src/index.test.ts
DELETED
|
@@ -1,16 +0,0 @@
|
|
|
1
|
-
import { describe, expect, test } from 'bun:test';
|
|
2
|
-
import plugin, { WebhookTrigger } from './index';
|
|
3
|
-
import manifest from '../package.json' with { type: 'json' };
|
|
4
|
-
|
|
5
|
-
describe('trigger-webhook plugin shape', () => {
|
|
6
|
-
test('default export is a capability plugin matching package manifest', () => {
|
|
7
|
-
expect(manifest.tagmaPlugin.category).toBe('triggers');
|
|
8
|
-
expect(manifest.tagmaPlugin.type).toBe('webhook');
|
|
9
|
-
expect(plugin.name).toBe(manifest.name);
|
|
10
|
-
expect(plugin.capabilities?.triggers?.[manifest.tagmaPlugin.type]).toBe(WebhookTrigger);
|
|
11
|
-
});
|
|
12
|
-
|
|
13
|
-
test('watch is a function', () => {
|
|
14
|
-
expect(typeof plugin.capabilities!.triggers!.webhook.watch).toBe('function');
|
|
15
|
-
});
|
|
16
|
-
});
|
package/src/index.ts
DELETED
|
@@ -1,278 +0,0 @@
|
|
|
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 {
|
|
26
|
-
parseDurationSafe,
|
|
27
|
-
type TagmaPlugin,
|
|
28
|
-
type TriggerPlugin,
|
|
29
|
-
type TriggerContext,
|
|
30
|
-
} from '@tagma/types';
|
|
31
|
-
import { createHmac, timingSafeEqual } from 'node:crypto';
|
|
32
|
-
|
|
33
|
-
type Resolver = (payload: unknown) => void;
|
|
34
|
-
|
|
35
|
-
interface WebhookServerState {
|
|
36
|
-
readonly port: number;
|
|
37
|
-
readonly path: string;
|
|
38
|
-
readonly secretEnv: string | undefined;
|
|
39
|
-
readonly waiters: Resolver[];
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
// Module-level so concurrent tasks on the same (port, path) share one
|
|
43
|
-
// listener. Bun.serve refuses to bind a port twice, so this sharing is
|
|
44
|
-
// required — not just an optimization.
|
|
45
|
-
const servers = new Map<string, WebhookServerState>();
|
|
46
|
-
|
|
47
|
-
function serverKey(port: number, path: string, hostname: string): string {
|
|
48
|
-
return `${hostname}::${port}::${path}`;
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
const DEFAULT_WEBHOOK_HOST = '127.0.0.1';
|
|
52
|
-
|
|
53
|
-
function verifySignature(rawBody: string, header: string, secret: string): boolean {
|
|
54
|
-
const expected = 'sha256=' + createHmac('sha256', secret).update(rawBody).digest('hex');
|
|
55
|
-
const a = Buffer.from(header);
|
|
56
|
-
const b = Buffer.from(expected);
|
|
57
|
-
if (a.length !== b.length) return false;
|
|
58
|
-
return timingSafeEqual(a, b);
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
function ensureServer(
|
|
62
|
-
port: number,
|
|
63
|
-
path: string,
|
|
64
|
-
secretEnv: string | undefined,
|
|
65
|
-
hostname: string,
|
|
66
|
-
): WebhookServerState {
|
|
67
|
-
const key = serverKey(port, path, hostname);
|
|
68
|
-
const existing = servers.get(key);
|
|
69
|
-
if (existing) return existing;
|
|
70
|
-
|
|
71
|
-
const state: WebhookServerState = {
|
|
72
|
-
port,
|
|
73
|
-
path,
|
|
74
|
-
secretEnv,
|
|
75
|
-
waiters: [],
|
|
76
|
-
};
|
|
77
|
-
|
|
78
|
-
Bun.serve({
|
|
79
|
-
port,
|
|
80
|
-
// Default to loopback so the webhook endpoint is not reachable from the
|
|
81
|
-
// LAN unless the user explicitly sets `host` in their YAML (e.g. for
|
|
82
|
-
// container/WSL scenarios). Without this, Bun.serve listens on all
|
|
83
|
-
// interfaces and a secret-less webhook would accept traffic from any
|
|
84
|
-
// network-adjacent caller.
|
|
85
|
-
hostname,
|
|
86
|
-
async fetch(req) {
|
|
87
|
-
const url = new URL(req.url);
|
|
88
|
-
if (url.pathname !== path) {
|
|
89
|
-
return new Response('not found', { status: 404 });
|
|
90
|
-
}
|
|
91
|
-
if (req.method !== 'POST') {
|
|
92
|
-
return new Response('method not allowed', { status: 405 });
|
|
93
|
-
}
|
|
94
|
-
|
|
95
|
-
const rawBody = await req.text();
|
|
96
|
-
|
|
97
|
-
// HMAC gate — bypassed when no secret env is configured, which is
|
|
98
|
-
// acceptable for loopback dev but should always be set in production.
|
|
99
|
-
const secret = state.secretEnv ? process.env[state.secretEnv] : undefined;
|
|
100
|
-
if (state.secretEnv) {
|
|
101
|
-
if (!secret) {
|
|
102
|
-
return new Response(`env var ${state.secretEnv} not set`, { status: 500 });
|
|
103
|
-
}
|
|
104
|
-
const sigHeader = req.headers.get('x-tagma-signature') ?? '';
|
|
105
|
-
if (!verifySignature(rawBody, sigHeader, secret)) {
|
|
106
|
-
return new Response('invalid signature', { status: 401 });
|
|
107
|
-
}
|
|
108
|
-
}
|
|
109
|
-
|
|
110
|
-
// Decode JSON if possible so downstream tasks get structured data.
|
|
111
|
-
//
|
|
112
|
-
// D22: when the sender explicitly declared `application/json`, a parse
|
|
113
|
-
// failure is a contract violation — silently falling through to the
|
|
114
|
-
// raw-string payload meant downstream tasks that did `payload.field`
|
|
115
|
-
// crashed later with "Cannot read properties of undefined", far away
|
|
116
|
-
// from the actual cause. Return 400 so the sender sees the problem
|
|
117
|
-
// up front. Bodies without a JSON content-type still pass through
|
|
118
|
-
// untouched, which preserves the "any POST body" escape hatch.
|
|
119
|
-
let payload: unknown = rawBody;
|
|
120
|
-
const contentType = req.headers.get('content-type') ?? '';
|
|
121
|
-
if (contentType.includes('application/json')) {
|
|
122
|
-
try {
|
|
123
|
-
payload = JSON.parse(rawBody);
|
|
124
|
-
} catch (err) {
|
|
125
|
-
const msg = err instanceof Error ? err.message : String(err);
|
|
126
|
-
return new Response(`invalid JSON body: ${msg}`, { status: 400 });
|
|
127
|
-
}
|
|
128
|
-
}
|
|
129
|
-
|
|
130
|
-
const waiter = state.waiters.shift();
|
|
131
|
-
if (waiter) {
|
|
132
|
-
waiter(payload);
|
|
133
|
-
return new Response('ok', { status: 202 });
|
|
134
|
-
}
|
|
135
|
-
// No task is currently waiting on this endpoint — reject loudly so
|
|
136
|
-
// callers know the webhook wasn't actually consumed by a pipeline.
|
|
137
|
-
return new Response('no waiting task', { status: 409 });
|
|
138
|
-
},
|
|
139
|
-
error(err) {
|
|
140
|
-
console.error(`[webhook] server error on :${port}${path}:`, err);
|
|
141
|
-
return new Response('internal error', { status: 500 });
|
|
142
|
-
},
|
|
143
|
-
});
|
|
144
|
-
|
|
145
|
-
servers.set(key, state);
|
|
146
|
-
return state;
|
|
147
|
-
}
|
|
148
|
-
|
|
149
|
-
export const WebhookTrigger: TriggerPlugin = {
|
|
150
|
-
name: 'webhook',
|
|
151
|
-
schema: {
|
|
152
|
-
description: 'Wait for an HTTP POST to arrive on a local listener before the task runs.',
|
|
153
|
-
fields: {
|
|
154
|
-
port: {
|
|
155
|
-
type: 'number',
|
|
156
|
-
required: true,
|
|
157
|
-
default: 8787,
|
|
158
|
-
min: 1,
|
|
159
|
-
max: 65535,
|
|
160
|
-
description: 'TCP port to listen on.',
|
|
161
|
-
placeholder: '8787',
|
|
162
|
-
},
|
|
163
|
-
path: {
|
|
164
|
-
type: 'string',
|
|
165
|
-
required: true,
|
|
166
|
-
default: '/webhook',
|
|
167
|
-
description: 'URL path to match (e.g. /hooks/deploy).',
|
|
168
|
-
placeholder: '/webhook',
|
|
169
|
-
},
|
|
170
|
-
secret_env: {
|
|
171
|
-
type: 'string',
|
|
172
|
-
description:
|
|
173
|
-
'Env var containing the HMAC-SHA256 secret. When set, POSTs must include an x-tagma-signature: sha256=<hex> header computed over the raw body.',
|
|
174
|
-
placeholder: 'TAGMA_WEBHOOK_SECRET',
|
|
175
|
-
},
|
|
176
|
-
host: {
|
|
177
|
-
type: 'string',
|
|
178
|
-
default: DEFAULT_WEBHOOK_HOST,
|
|
179
|
-
description:
|
|
180
|
-
'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).',
|
|
181
|
-
placeholder: DEFAULT_WEBHOOK_HOST,
|
|
182
|
-
},
|
|
183
|
-
timeout: {
|
|
184
|
-
type: 'duration',
|
|
185
|
-
description: 'Maximum wait time (e.g. 10m). Omit or 0 to wait indefinitely.',
|
|
186
|
-
placeholder: '10m',
|
|
187
|
-
},
|
|
188
|
-
},
|
|
189
|
-
},
|
|
190
|
-
|
|
191
|
-
watch(config: Record<string, unknown>, ctx: TriggerContext): Promise<unknown> {
|
|
192
|
-
const rawPort = config.port;
|
|
193
|
-
const port = typeof rawPort === 'number' ? rawPort : Number(rawPort);
|
|
194
|
-
if (!Number.isFinite(port) || port < 1 || port > 65535) {
|
|
195
|
-
throw new Error(`webhook trigger: "port" must be 1-65535, got ${String(rawPort)}`);
|
|
196
|
-
}
|
|
197
|
-
|
|
198
|
-
const path = (config.path as string | undefined) ?? '/webhook';
|
|
199
|
-
if (!path.startsWith('/')) {
|
|
200
|
-
throw new Error(`webhook trigger: "path" must start with "/", got ${path}`);
|
|
201
|
-
}
|
|
202
|
-
|
|
203
|
-
const secretEnv = config.secret_env as string | undefined;
|
|
204
|
-
const rawHost = config.host;
|
|
205
|
-
const hostname =
|
|
206
|
-
typeof rawHost === 'string' && rawHost.trim().length > 0
|
|
207
|
-
? rawHost.trim()
|
|
208
|
-
: DEFAULT_WEBHOOK_HOST;
|
|
209
|
-
const timeoutMs = config.timeout != null ? parseDurationSafe(config.timeout, 0) : 0;
|
|
210
|
-
|
|
211
|
-
if (hostname !== DEFAULT_WEBHOOK_HOST && hostname !== 'localhost' && !secretEnv) {
|
|
212
|
-
// Loud warning — the user has opted into a non-loopback bind without
|
|
213
|
-
// HMAC. Refuse by default rather than silently expose the endpoint to
|
|
214
|
-
// the network.
|
|
215
|
-
throw new Error(
|
|
216
|
-
`webhook trigger: binding to "${hostname}" without secret_env is refused — set secret_env to enable HMAC authentication before exposing to non-loopback interfaces`,
|
|
217
|
-
);
|
|
218
|
-
}
|
|
219
|
-
|
|
220
|
-
const state = ensureServer(port, path, secretEnv, hostname);
|
|
221
|
-
|
|
222
|
-
return new Promise<unknown>((resolvePromise, rejectPromise) => {
|
|
223
|
-
if (ctx.signal.aborted) {
|
|
224
|
-
rejectPromise(new Error('Pipeline aborted'));
|
|
225
|
-
return;
|
|
226
|
-
}
|
|
227
|
-
|
|
228
|
-
let settled = false;
|
|
229
|
-
let timer: ReturnType<typeof setTimeout> | null = null;
|
|
230
|
-
|
|
231
|
-
const onFire: Resolver = (payload) => {
|
|
232
|
-
if (settled) return;
|
|
233
|
-
settled = true;
|
|
234
|
-
cleanup();
|
|
235
|
-
resolvePromise(payload);
|
|
236
|
-
};
|
|
237
|
-
|
|
238
|
-
const onAbort = (): void => {
|
|
239
|
-
if (settled) return;
|
|
240
|
-
settled = true;
|
|
241
|
-
cleanup();
|
|
242
|
-
rejectPromise(new Error('Pipeline aborted'));
|
|
243
|
-
};
|
|
244
|
-
|
|
245
|
-
const cleanup = (): void => {
|
|
246
|
-
if (timer) clearTimeout(timer);
|
|
247
|
-
ctx.signal.removeEventListener('abort', onAbort);
|
|
248
|
-
const idx = state.waiters.indexOf(onFire);
|
|
249
|
-
if (idx !== -1) state.waiters.splice(idx, 1);
|
|
250
|
-
};
|
|
251
|
-
|
|
252
|
-
state.waiters.push(onFire);
|
|
253
|
-
ctx.signal.addEventListener('abort', onAbort, { once: true });
|
|
254
|
-
|
|
255
|
-
if (timeoutMs > 0) {
|
|
256
|
-
timer = setTimeout(() => {
|
|
257
|
-
if (settled) return;
|
|
258
|
-
settled = true;
|
|
259
|
-
cleanup();
|
|
260
|
-
rejectPromise(
|
|
261
|
-
new Error(
|
|
262
|
-
`webhook trigger timeout: no POST on :${port}${path} within ${String(config.timeout)}`,
|
|
263
|
-
),
|
|
264
|
-
);
|
|
265
|
-
}, timeoutMs);
|
|
266
|
-
}
|
|
267
|
-
});
|
|
268
|
-
},
|
|
269
|
-
};
|
|
270
|
-
|
|
271
|
-
export default {
|
|
272
|
-
name: '@tagma/trigger-webhook',
|
|
273
|
-
capabilities: {
|
|
274
|
-
triggers: {
|
|
275
|
-
webhook: WebhookTrigger,
|
|
276
|
-
},
|
|
277
|
-
},
|
|
278
|
-
} satisfies TagmaPlugin;
|