@powerhousedao/switchboard 6.2.3-dev.11 → 6.2.3-dev.13

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.
@@ -0,0 +1,237 @@
1
+ // Shared harness: the suites go over a real socket through the reactor's own
2
+ // adapter, route service and webhook service, which the unit tests cannot.
3
+ import {
4
+ createHttpAdapter,
5
+ getDbClient,
6
+ HttpRouteService,
7
+ MemoryWebhookStore,
8
+ WebhookService,
9
+ } from "@powerhousedao/reactor-api";
10
+ import {
11
+ createWorkflowRuntime,
12
+ type WorkflowRuntimeService,
13
+ } from "@powerhousedao/reactor-workflow";
14
+ import {
15
+ createRelationalDb,
16
+ type IRelationalDb,
17
+ } from "@powerhousedao/shared/processors";
18
+ import type { OperationWithContext } from "document-model";
19
+ import type { Kysely } from "kysely";
20
+ import { vi } from "vitest";
21
+
22
+ export const WORKFLOW_TYPE = "powerhouse/workflow";
23
+ export const PACKAGE_NAME = "@powerhousedao/workflow";
24
+ /** A ref the harness's secret store resolves; anything else rejects. */
25
+ export const SECRET_REF = "secret://v1:00112233445566778899aabbccddeeff";
26
+ export const SECRET = "s3cret";
27
+ // Minting an endpoint is a read of the workflow, so the harness asks as one.
28
+ const CALLER = { headers: {}, db: {}, user: { address: "0xabc" } } as never;
29
+
30
+ export interface FiredRun {
31
+ workflowId: string;
32
+ payload: unknown;
33
+ kind: string;
34
+ }
35
+
36
+ export interface WebhookHost {
37
+ /** Origin the endpoint is served from, e.g. `http://127.0.0.1:53124`. */
38
+ readonly url: string;
39
+ /** Runs the trigger started, in order. Cleared by `arm`. */
40
+ readonly fired: FiredRun[];
41
+ readonly service: WorkflowRuntimeService;
42
+ /** Publishes an ENABLED workflow with `config`; returns its endpoint. */
43
+ arm(
44
+ config: Record<string, unknown>,
45
+ options?: { blockType?: string; workflowId?: string },
46
+ ): Promise<{ token: string; url: string }>;
47
+ /** Publishes the same workflow as DISABLED, keeping its endpoint row. */
48
+ disarm(workflowId?: string): Promise<void>;
49
+ /** The policy the service hands the reactor for one endpoint. */
50
+ policyFor(workflowId?: string): Promise<unknown>;
51
+ deliver(
52
+ token: string,
53
+ init?: {
54
+ method?: string;
55
+ headers?: Record<string, string>;
56
+ body?: string;
57
+ query?: Record<string, string>;
58
+ },
59
+ ): Promise<Response>;
60
+ stop(): Promise<void>;
61
+ }
62
+
63
+ export const DEFAULT_WORKFLOW = "wf-integration";
64
+
65
+ // Module-scoped: the service ignores any ordinal at or below the highest it
66
+ // has seen, so a per-host counter would make a file's second host see nothing.
67
+ let ordinal = 0;
68
+
69
+ export function workflowOperation(
70
+ state: Record<string, unknown>,
71
+ workflowId = DEFAULT_WORKFLOW,
72
+ ): OperationWithContext {
73
+ ordinal += 1;
74
+ return {
75
+ operation: {
76
+ index: ordinal,
77
+ timestampUtcMs: `${ordinal}`,
78
+ action: { type: "SET_WORKFLOW_NAME", input: {} },
79
+ resultingState: JSON.stringify(state),
80
+ },
81
+ context: {
82
+ documentId: workflowId,
83
+ documentType: WORKFLOW_TYPE,
84
+ scope: "global",
85
+ branch: "main",
86
+ ordinal,
87
+ },
88
+ } as unknown as OperationWithContext;
89
+ }
90
+
91
+ // `publicUrl` is known only after `listen`: a family registered against the
92
+ // wrong origin advertises URLs no caller can reach.
93
+ export async function startWebhookHost(
94
+ options: { fire?: (run: FiredRun) => unknown } = {},
95
+ ): Promise<WebhookHost> {
96
+ // The public factory, not the adapter class: the class is internal, so
97
+ // constructing it would test a path no consumer can take.
98
+ const { adapter } = await createHttpAdapter("express");
99
+ adapter.setupMiddleware({});
100
+ const server = await adapter.listen(0);
101
+ const { port } = server.address() as { port: number };
102
+ const url = `http://127.0.0.1:${port}`;
103
+
104
+ const webhooks = new WebhookService({ store: new MemoryWebhookStore() });
105
+ const routes = new HttpRouteService({
106
+ httpAdapter: adapter,
107
+ webhooks,
108
+ publicUrl: url,
109
+ });
110
+ // Core serves the endpoint family from its own host scope, exactly as the
111
+ // reactor wires it: nothing here touches the adapter directly.
112
+ webhooks.attach(routes.hostScope("@powerhousedao/reactor-api", "/webhooks"));
113
+
114
+ const { db } = getDbClient();
115
+ const fired: FiredRun[] = [];
116
+
117
+ // Every host surface the runtime asks for, and nothing it does not: no run
118
+ // here reaches the reactor, and the secret store answers one fixed ref.
119
+ const service = createWorkflowRuntime({
120
+ relationalDb: createRelationalDb(
121
+ db as unknown as Kysely<unknown>,
122
+ ) as IRelationalDb,
123
+ reactorClient: {
124
+ get: () => Promise.reject(new Error("not used")),
125
+ find: () => Promise.resolve({ results: [] }),
126
+ },
127
+ assertCanRead: () => Promise.resolve(undefined),
128
+ assertCanWrite: () => Promise.resolve(undefined),
129
+ webhooks: routes.scopeFor(PACKAGE_NAME).webhooks,
130
+ secrets: {
131
+ get: (ref: string) =>
132
+ ref === SECRET_REF
133
+ ? Promise.resolve(SECRET)
134
+ : Promise.reject(new Error(`No secret found for ref "${ref}"`)),
135
+ },
136
+ } as never);
137
+ vi.spyOn(service, "fire").mockImplementation(
138
+ (workflowId: string, payload?: unknown, kind = "manual") => {
139
+ const run = { workflowId, payload, kind };
140
+ fired.push(run);
141
+ const outcome = options.fire?.(run);
142
+ return Promise.resolve(
143
+ (outcome ?? {
144
+ runId: `run-${fired.length}`,
145
+ status: "SUCCEEDED",
146
+ steps: [],
147
+ }) as never,
148
+ );
149
+ },
150
+ );
151
+
152
+ await service.registerWebhookEndpoint();
153
+
154
+ const publish = async (
155
+ config: Record<string, unknown>,
156
+ status: string,
157
+ blockType: string,
158
+ workflowId: string,
159
+ ) => {
160
+ await service.onOperations([
161
+ workflowOperation(
162
+ {
163
+ name: "Integration",
164
+ status,
165
+ version: ordinal + 1,
166
+ trigger: { id: "t1", blockType, config },
167
+ steps: [],
168
+ edges: [],
169
+ variables: [],
170
+ },
171
+ workflowId,
172
+ ),
173
+ ]);
174
+ };
175
+
176
+ return {
177
+ url,
178
+ fired,
179
+ service,
180
+ async arm(config, opts = {}) {
181
+ const workflowId = opts.workflowId ?? DEFAULT_WORKFLOW;
182
+ await publish(
183
+ config,
184
+ "ENABLED",
185
+ opts.blockType ?? "core#webhook",
186
+ workflowId,
187
+ );
188
+ const endpoint = await service.webhookEndpoint(workflowId, CALLER);
189
+ if (!endpoint) throw new Error(`No endpoint minted for ${workflowId}`);
190
+ fired.length = 0;
191
+ return {
192
+ url: endpoint.url,
193
+ token: endpoint.url.slice(endpoint.url.lastIndexOf("/") + 1),
194
+ };
195
+ },
196
+ async disarm(workflowId = DEFAULT_WORKFLOW) {
197
+ await publish({}, "DISABLED", "core#webhook", workflowId);
198
+ },
199
+ policyFor(workflowId = DEFAULT_WORKFLOW) {
200
+ return service.webhookPolicy(workflowId);
201
+ },
202
+ deliver(token, init = {}) {
203
+ const query = init.query
204
+ ? `?${new URLSearchParams(init.query).toString()}`
205
+ : "";
206
+ return fetch(`${url}/webhooks/${token}${query}`, {
207
+ method: init.method ?? "POST",
208
+ headers: init.headers,
209
+ body: init.body,
210
+ });
211
+ },
212
+ stop() {
213
+ return new Promise<void>((resolve, reject) =>
214
+ server.close((error) => (error ? reject(error) : resolve())),
215
+ );
216
+ },
217
+ };
218
+ }
219
+
220
+ // A delivery is answered before its run starts, so asserting on `fired`
221
+ // straight after a 202 is a race that passes for the wrong reason.
222
+ export async function waitForRuns(
223
+ host: WebhookHost,
224
+ count: number,
225
+ timeoutMs = 2000,
226
+ ): Promise<FiredRun[]> {
227
+ const deadline = Date.now() + timeoutMs;
228
+ while (host.fired.length < count && Date.now() < deadline) {
229
+ await new Promise((resolve) => setTimeout(resolve, 5));
230
+ }
231
+ if (host.fired.length < count) {
232
+ throw new Error(
233
+ `Expected ${count} run(s), saw ${host.fired.length} within ${timeoutMs}ms`,
234
+ );
235
+ }
236
+ return host.fired;
237
+ }
@@ -0,0 +1,105 @@
1
+ // What the workflow subgraph does with the caller behind a request: every
2
+ // workflow-scoped field hands it to the runtime, and secret writes are admins'.
3
+ import type {
4
+ Context,
5
+ IAuthorizationService,
6
+ } from "@powerhousedao/reactor-api";
7
+ import type { WorkflowRuntimeService } from "@powerhousedao/reactor-workflow";
8
+ import { describe, expect, it, vi } from "vitest";
9
+ import { getResolvers } from "../../src/workflow/resolvers.js";
10
+
11
+ const CTX = {
12
+ headers: {},
13
+ db: {},
14
+ user: { address: "0xadmin" },
15
+ } as unknown as Context;
16
+
17
+ type Resolver = (
18
+ parent: unknown,
19
+ args: unknown,
20
+ ctx: Context,
21
+ ) => Promise<unknown>;
22
+
23
+ function fakeRuntime() {
24
+ return {
25
+ webhookEndpoint: vi.fn(() => Promise.resolve(null)),
26
+ triggerStates: vi.fn(() => Promise.resolve([])),
27
+ runs: vi.fn(() => Promise.resolve([])),
28
+ run: vi.fn(() => Promise.resolve(null)),
29
+ fire: vi.fn(() => Promise.resolve({})),
30
+ rerun: vi.fn(() => Promise.resolve({})),
31
+ secrets: vi.fn(() =>
32
+ Promise.resolve({
33
+ create: vi.fn(() => Promise.resolve({ ref: "secret://v1:00" })),
34
+ rotate: vi.fn(() => Promise.resolve({ ref: "secret://v1:00" })),
35
+ delete: vi.fn(() => Promise.resolve()),
36
+ }),
37
+ ),
38
+ };
39
+ }
40
+
41
+ function build(isAdmin: boolean) {
42
+ const runtime = fakeRuntime();
43
+ const authorizationService = {
44
+ isSupremeAdmin: vi.fn(() => isAdmin),
45
+ } as unknown as IAuthorizationService;
46
+ const resolvers = getResolvers(
47
+ runtime as unknown as WorkflowRuntimeService,
48
+ authorizationService,
49
+ ) as Record<string, Record<string, Resolver>>;
50
+ return {
51
+ runtime,
52
+ queries: resolvers.WorkflowRuntimeQueries,
53
+ mutations: resolvers.WorkflowRuntimeMutations,
54
+ };
55
+ }
56
+
57
+ describe("the workflow resolvers and the caller", () => {
58
+ it("hands the caller to every workflow-scoped field", async () => {
59
+ const { runtime, queries, mutations } = build(true);
60
+
61
+ await queries.webhookEndpoint({}, { workflowId: "wf-1" }, CTX);
62
+ await queries.triggerStates({}, {}, CTX);
63
+ await queries.runs({}, { driveId: "drive-1" }, CTX);
64
+ await queries.run({}, { id: "run-1" }, CTX);
65
+ await mutations.fire({}, { workflowId: "wf-1", payload: { a: 1 } }, CTX);
66
+ await mutations.rerun({}, { runId: "run-1" }, CTX);
67
+
68
+ expect(runtime.webhookEndpoint).toHaveBeenCalledWith("wf-1", CTX);
69
+ expect(runtime.triggerStates).toHaveBeenCalledWith(CTX);
70
+ expect(runtime.runs).toHaveBeenCalledWith({ driveId: "drive-1" }, CTX);
71
+ expect(runtime.run).toHaveBeenCalledWith("run-1", CTX);
72
+ expect(runtime.fire).toHaveBeenCalledWith(
73
+ "wf-1",
74
+ { a: 1 },
75
+ "manual",
76
+ undefined,
77
+ CTX,
78
+ );
79
+ expect(runtime.rerun).toHaveBeenCalledWith("run-1", CTX);
80
+ });
81
+
82
+ it("refuses secret writes to a caller who does not administer the reactor", async () => {
83
+ const { runtime, mutations } = build(false);
84
+
85
+ await expect(
86
+ mutations.createSecret({}, { value: "s3cret" }, CTX),
87
+ ).rejects.toThrow("Admin access required");
88
+ await expect(
89
+ mutations.rotateSecret({}, { ref: "secret://v1:00", value: "s" }, CTX),
90
+ ).rejects.toThrow("Admin access required");
91
+ await expect(
92
+ mutations.deleteSecret({}, { ref: "secret://v1:00" }, CTX),
93
+ ).rejects.toThrow("Admin access required");
94
+ // Refused before the store is ever opened.
95
+ expect(runtime.secrets).not.toHaveBeenCalled();
96
+ });
97
+
98
+ it("lets an administrator write secrets", async () => {
99
+ const { runtime, mutations } = build(true);
100
+
101
+ await mutations.createSecret({}, { value: "s3cret", label: "slack" }, CTX);
102
+
103
+ expect(runtime.secrets).toHaveBeenCalledTimes(1);
104
+ });
105
+ });
@@ -0,0 +1,295 @@
1
+ // Redelivery and the sender's verification round, over a real socket: both
2
+ // are decided by the reactor from one config field, before the trigger runs.
3
+ import { afterEach, describe, expect, it } from "vitest";
4
+ import { startWebhookHost, waitForRuns, type WebhookHost } from "./harness.js";
5
+
6
+ let host: WebhookHost | undefined;
7
+
8
+ afterEach(async () => {
9
+ // Even on failure: a thrown expectation would leave the port open.
10
+ await host?.stop();
11
+ host = undefined;
12
+ });
13
+
14
+ const JSON_HEADERS = { "content-type": "application/json" };
15
+
16
+ // Gives a run that should NOT exist time to appear: asserting the instant a
17
+ // response lands wins the race whether the trigger fired or not.
18
+ async function settle(): Promise<void> {
19
+ await new Promise((resolve) => setTimeout(resolve, 50));
20
+ }
21
+
22
+ interface PolicyShape {
23
+ dedupe?: { field: unknown; ttlSeconds?: number };
24
+ challengeField?: unknown;
25
+ }
26
+
27
+ describe("core#webhook redelivery", () => {
28
+ it("dedupes on a bare field name found in the query string", async () => {
29
+ host = await startWebhookHost();
30
+ const { token } = await host.arm({
31
+ methods: "POST",
32
+ dedupeField: "eventId",
33
+ dedupeTtlSeconds: 60,
34
+ });
35
+ const send = () => host!.deliver(token, { query: { eventId: "evt-1" } });
36
+
37
+ expect((await send()).status).toBe(202);
38
+ await waitForRuns(host, 1);
39
+ // A redelivery is answered as a success so the provider stops retrying;
40
+ // 4xx here would make a well-behaved sender retry forever.
41
+ expect((await send()).status).toBe(200);
42
+ await settle();
43
+ expect(host.fired).toHaveLength(1);
44
+ });
45
+
46
+ it("dedupes on a bare field name found as a top-level body field", async () => {
47
+ host = await startWebhookHost();
48
+ const { token } = await host.arm({
49
+ methods: "POST",
50
+ dedupeField: "id",
51
+ dedupeTtlSeconds: 60,
52
+ });
53
+ const send = () =>
54
+ host!.deliver(token, {
55
+ headers: JSON_HEADERS,
56
+ body: '{"id":"evt_1","kind":"created"}',
57
+ });
58
+
59
+ expect((await send()).status).toBe(202);
60
+ await waitForRuns(host, 1);
61
+ expect((await send()).status).toBe(200);
62
+ await settle();
63
+ expect(host.fired).toHaveLength(1);
64
+ });
65
+
66
+ it("dedupes on a `header:`-sourced field", async () => {
67
+ host = await startWebhookHost();
68
+ const { token } = await host.arm({
69
+ methods: "POST",
70
+ dedupeField: "header:x-delivery-id",
71
+ dedupeTtlSeconds: 60,
72
+ });
73
+ const send = () =>
74
+ host!.deliver(token, {
75
+ headers: { ...JSON_HEADERS, "x-delivery-id": "abc-123" },
76
+ body: '{"a":1}',
77
+ });
78
+
79
+ expect((await send()).status).toBe(202);
80
+ await waitForRuns(host, 1);
81
+ expect((await send()).status).toBe(200);
82
+ await settle();
83
+ expect(host.fired).toHaveLength(1);
84
+ });
85
+
86
+ it("dedupes on a `body:` path nested inside the payload", async () => {
87
+ host = await startWebhookHost();
88
+ const { token } = await host.arm({
89
+ methods: "POST",
90
+ dedupeField: "body:data.object.id",
91
+ dedupeTtlSeconds: 60,
92
+ });
93
+ const send = () =>
94
+ host!.deliver(token, {
95
+ headers: JSON_HEADERS,
96
+ body: '{"data":{"object":{"id":"in_1"}}}',
97
+ });
98
+
99
+ expect((await send()).status).toBe(202);
100
+ await waitForRuns(host, 1);
101
+ expect((await send()).status).toBe(200);
102
+ await settle();
103
+ expect(host.fired).toHaveLength(1);
104
+ });
105
+
106
+ it("keys only on the named field, not on the URL or the body", async () => {
107
+ host = await startWebhookHost();
108
+ const { token } = await host.arm({
109
+ methods: "POST",
110
+ dedupeField: "header:x-delivery-id",
111
+ dedupeTtlSeconds: 60,
112
+ });
113
+
114
+ const first = await host.deliver(token, {
115
+ headers: { ...JSON_HEADERS, "x-delivery-id": "abc-123" },
116
+ query: { attempt: "1" },
117
+ body: '{"attempt":1}',
118
+ });
119
+ expect(first.status).toBe(202);
120
+ await waitForRuns(host, 1);
121
+
122
+ // A retry is rarely byte-identical, so anything keyed on the URL or the
123
+ // whole request would treat this as a new event and run twice.
124
+ const retry = await host.deliver(token, {
125
+ headers: { ...JSON_HEADERS, "x-delivery-id": "abc-123" },
126
+ query: { attempt: "2" },
127
+ body: '{"attempt":2}',
128
+ });
129
+ expect(retry.status).toBe(200);
130
+ await settle();
131
+ expect(host.fired).toHaveLength(1);
132
+ });
133
+
134
+ it("starts a second run when the named field carries a different value", async () => {
135
+ host = await startWebhookHost();
136
+ const { token } = await host.arm({
137
+ methods: "POST",
138
+ dedupeField: "header:x-delivery-id",
139
+ dedupeTtlSeconds: 60,
140
+ });
141
+ const send = (id: string) =>
142
+ host!.deliver(token, {
143
+ headers: { ...JSON_HEADERS, "x-delivery-id": id },
144
+ body: '{"a":1}',
145
+ });
146
+
147
+ expect((await send("abc-123")).status).toBe(202);
148
+ expect((await send("def-456")).status).toBe(202);
149
+ await waitForRuns(host, 2);
150
+ expect(host.fired).toHaveLength(2);
151
+ });
152
+
153
+ it("runs every delivery when no dedupe field is configured", async () => {
154
+ host = await startWebhookHost();
155
+ const { token } = await host.arm({ methods: "POST" });
156
+ const send = () =>
157
+ host!.deliver(token, { headers: JSON_HEADERS, body: '{"a":1}' });
158
+
159
+ expect((await send()).status).toBe(202);
160
+ expect((await send()).status).toBe(202);
161
+ // Without an id there is no key, and collapsing unrelated deliveries under
162
+ // a shared "no key" bucket would silently drop real events.
163
+ await waitForRuns(host, 2);
164
+ expect(host.fired).toHaveLength(2);
165
+ });
166
+
167
+ it("runs both deliveries when the configured field is absent from the request", async () => {
168
+ host = await startWebhookHost();
169
+ const { token } = await host.arm({
170
+ methods: "POST",
171
+ dedupeField: "header:x-delivery-id",
172
+ dedupeTtlSeconds: 60,
173
+ });
174
+ const send = (body: string) =>
175
+ host!.deliver(token, { headers: JSON_HEADERS, body });
176
+
177
+ expect((await send('{"a":1}')).status).toBe(202);
178
+ expect((await send('{"a":2}')).status).toBe(202);
179
+ // A missing field is not a key either: two senders that both omit it are
180
+ // not the same delivery, and treating them as one loses the second event.
181
+ await waitForRuns(host, 2);
182
+ expect(host.fired).toHaveLength(2);
183
+ });
184
+
185
+ it("drops everything after the first when the named field repeats across events", async () => {
186
+ host = await startWebhookHost();
187
+ const { token } = await host.arm({
188
+ methods: "POST",
189
+ // A subscription id is the same on every delivery for that subscription,
190
+ // so naming it here is a configuration mistake with no error to see.
191
+ dedupeField: "subscriptionId",
192
+ dedupeTtlSeconds: 60,
193
+ });
194
+ const send = (eventId: string) =>
195
+ host!.deliver(token, {
196
+ headers: JSON_HEADERS,
197
+ body: `{"subscriptionId":"sub_1","eventId":"${eventId}"}`,
198
+ });
199
+
200
+ expect((await send("evt_1")).status).toBe(202);
201
+ await waitForRuns(host, 1);
202
+ // Two different events, second silently discarded: the field has to
203
+ // identify the delivery, not the thing it is about.
204
+ expect((await send("evt_2")).status).toBe(200);
205
+ await settle();
206
+ expect(host.fired).toHaveLength(1);
207
+ });
208
+ });
209
+
210
+ describe("core#webhook endpoint verification", () => {
211
+ it("echoes a bare challenge field from the query string without running", async () => {
212
+ host = await startWebhookHost();
213
+ const { token } = await host.arm({
214
+ methods: "POST",
215
+ challengeField: "hub.challenge",
216
+ });
217
+
218
+ const response = await host.deliver(token, {
219
+ query: { "hub.challenge": "nonce-42" },
220
+ });
221
+ expect(response.status).toBe(200);
222
+ // Verbatim: providers compare the body byte for byte, so a JSON wrapper or
223
+ // a trailing newline fails the subscription with nothing to read.
224
+ expect(await response.text()).toBe("nonce-42");
225
+ await settle();
226
+ expect(host.fired).toHaveLength(0);
227
+ });
228
+
229
+ it("echoes a `header:`-sourced challenge field without running", async () => {
230
+ host = await startWebhookHost();
231
+ const { token } = await host.arm({
232
+ methods: "POST",
233
+ challengeField: "header:x-hook-challenge",
234
+ });
235
+
236
+ const response = await host.deliver(token, {
237
+ headers: { ...JSON_HEADERS, "x-hook-challenge": "nonce-99" },
238
+ body: '{"type":"url_verification"}',
239
+ });
240
+ expect(response.status).toBe(200);
241
+ expect(await response.text()).toBe("nonce-99");
242
+ await settle();
243
+ expect(host.fired).toHaveLength(0);
244
+ });
245
+
246
+ it("runs as usual when the challenge field is absent", async () => {
247
+ host = await startWebhookHost();
248
+ const { token } = await host.arm({
249
+ methods: "POST",
250
+ challengeField: "hub.challenge",
251
+ });
252
+
253
+ // The challenge round happens once; every delivery after it is a real
254
+ // event, so a configured challenge field must not swallow the endpoint.
255
+ const response = await host.deliver(token, {
256
+ headers: JSON_HEADERS,
257
+ body: '{"id":"evt_1"}',
258
+ });
259
+ expect(response.status).toBe(202);
260
+ const [run] = await waitForRuns(host, 1);
261
+ expect(run.kind).toBe("webhook");
262
+ });
263
+ });
264
+
265
+ describe("core#webhook field policy", () => {
266
+ it("hands the reactor a source-tagged field for a prefixed config", async () => {
267
+ host = await startWebhookHost();
268
+ await host.arm({
269
+ methods: "POST",
270
+ dedupeField: "header:X-Delivery-ID",
271
+ challengeField: "body:challenge.value",
272
+ dedupeTtlSeconds: 60,
273
+ });
274
+
275
+ const policy = (await host.policyFor()) as PolicyShape;
276
+ // Lowercased for the reactor's header record; the prefix must survive
277
+ // parsing or the reactor reads the query string and finds no id.
278
+ expect(policy.dedupe?.field).toEqual({ header: "x-delivery-id" });
279
+ expect(policy.dedupe?.ttlSeconds).toBe(60);
280
+ expect(policy.challengeField).toEqual({ body: "challenge.value" });
281
+ });
282
+
283
+ it("leaves a bare field name bare, so the reactor tries query then body", async () => {
284
+ host = await startWebhookHost();
285
+ await host.arm({
286
+ methods: "POST",
287
+ dedupeField: "eventId",
288
+ challengeField: "hub.challenge",
289
+ });
290
+
291
+ const policy = (await host.policyFor()) as PolicyShape;
292
+ expect(policy.dedupe?.field).toBe("eventId");
293
+ expect(policy.challengeField).toBe("hub.challenge");
294
+ });
295
+ });