-
Notifications
You must be signed in to change notification settings - Fork 6.2k
Expand file tree
/
Copy pathengine.test.ts
More file actions
609 lines (540 loc) · 19.7 KB
/
Copy pathengine.test.ts
File metadata and controls
609 lines (540 loc) · 19.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
import { describe, it, expect, beforeEach, vi } from "vitest";
// Shared mock state for the service-role client. Lives in a hoisted block
// so the vi.mock factory below can close over it.
const h = vi.hoisted(() => ({
state: {
owned: null as { id: string } | null,
ownedCustomField: null as { id: string } | null,
automations: [] as Record<string, unknown>[],
steps: [] as Record<string, unknown>[],
fromCalls: [] as string[],
updateCalls: [] as { table: string; filters: [string, string, unknown][] }[],
upsertCalls: [] as { table: string; payload: unknown }[],
logInserts: [] as Record<string, unknown>[],
logUpdates: [] as Record<string, unknown>[],
},
}));
vi.mock("./admin-client", () => {
const { state } = h;
function resolve(ops: {
table: string;
type: string;
payload?: unknown;
filters: [string, string, unknown][];
}) {
const { table, type } = ops;
if (table === "contacts") {
if (type === "update") {
state.updateCalls.push({ table, filters: ops.filters });
return { data: null, error: null };
}
// ownership guard / condition read
return { data: state.owned, error: null };
}
if (table === "custom_fields") {
// account-scoped ownership lookup for a custom field definition
return { data: state.ownedCustomField, error: null };
}
if (table === "contact_custom_values") {
if (type === "upsert") {
state.upsertCalls.push({ table, payload: ops.payload });
return { data: null, error: null };
}
return { data: null, error: null };
}
if (table === "automations") return { data: state.automations, error: null };
if (table === "automation_logs") {
if (type === "insert") {
state.logInserts.push(ops.payload as Record<string, unknown>);
return { data: { id: "log1" }, error: null };
}
if (type === "update") {
state.logUpdates.push(ops.payload as Record<string, unknown>);
return { data: null, error: null };
}
return { data: { steps_executed: [], status: "success" }, error: null };
}
if (table === "automation_steps") return { data: state.steps, error: null };
return { data: null, error: null };
}
function builder(table: string) {
const ops = {
table,
type: "select",
payload: undefined as unknown,
filters: [] as [string, string, unknown][],
};
const b: Record<string, unknown> = {
select: () => b,
insert: (p: unknown) => ((ops.type = "insert"), (ops.payload = p), b),
update: (p: unknown) => ((ops.type = "update"), (ops.payload = p), b),
delete: () => ((ops.type = "delete"), b),
upsert: (p: unknown) => ((ops.type = "upsert"), (ops.payload = p), b),
eq: (k: string, v: unknown) => (ops.filters.push(["eq", k, v]), b),
gte: () => b,
is: () => b,
order: () => b,
limit: () => b,
single: () => Promise.resolve(resolve(ops)),
maybeSingle: () => Promise.resolve(resolve(ops)),
then: (onF: (v: unknown) => unknown, onR?: (e: unknown) => unknown) =>
Promise.resolve(resolve(ops)).then(onF, onR),
};
return b;
}
return {
supabaseAdmin: () => ({
from: (t: string) => {
state.fromCalls.push(t);
return builder(t);
},
rpc: () => Promise.resolve({ error: null }),
}),
};
});
vi.mock("./meta-send", () => ({
engineSendText: vi.fn(async () => ({ whatsapp_message_id: "m1" })),
engineSendTemplate: vi.fn(async () => ({ whatsapp_message_id: "m1" })),
engineSendInteractive: vi.fn(async () => ({ whatsapp_message_id: "m1" })),
}));
import { runAutomationsForTrigger, triggerMatches } from "./engine";
import type { Automation, KeywordMatchTriggerConfig } from "@/types";
const ACCOUNT = "acct-1";
beforeEach(() => {
h.state.owned = null;
h.state.ownedCustomField = null;
h.state.automations = [];
h.state.steps = [];
h.state.fromCalls = [];
h.state.updateCalls = [];
h.state.upsertCalls = [];
h.state.logInserts = [];
h.state.logUpdates = [];
});
describe("runAutomationsForTrigger — tenant isolation", () => {
it("refuses to dispatch when the contact is not in the account (GHSA-63cv-2c49-m5v3)", async () => {
// Ownership lookup returns nothing — the contact belongs to another tenant.
h.state.owned = null;
// If the guard failed, this automation would run an update_contact_field step.
h.state.automations = [automationWithUpdateStep()];
h.state.steps = [updateStep()];
await runAutomationsForTrigger({
accountId: ACCOUNT,
triggerType: "new_message_received",
contactId: "victim-contact-uuid",
context: { message_text: "manual trigger" },
});
// Bailed at the guard: never fetched automations, never wrote a contact.
expect(h.state.fromCalls).toContain("contacts");
expect(h.state.fromCalls).not.toContain("automations");
expect(h.state.updateCalls).toHaveLength(0);
});
it("proceeds past the guard when the contact belongs to the account", async () => {
h.state.owned = { id: "c1" };
h.state.automations = []; // no matching automations; just prove we got past the guard
await runAutomationsForTrigger({
accountId: ACCOUNT,
triggerType: "new_message_received",
contactId: "c1",
context: {},
});
expect(h.state.fromCalls).toContain("automations");
});
it("scopes the update_contact_field write to the automation's account", async () => {
h.state.owned = { id: "c1" };
h.state.automations = [automationWithUpdateStep()];
h.state.steps = [updateStep()];
await runAutomationsForTrigger({
accountId: ACCOUNT,
triggerType: "new_message_received",
contactId: "c1",
context: {},
});
expect(h.state.updateCalls).toHaveLength(1);
const filters = h.state.updateCalls[0].filters;
expect(filters).toContainEqual(["eq", "id", "c1"]);
expect(filters).toContainEqual(["eq", "account_id", ACCOUNT]);
});
});
describe("automation_logs — status is seeded pessimistically (issue #409)", () => {
it("writes the log row as 'failed' before any step runs", async () => {
h.state.owned = { id: "c1" };
h.state.automations = [automationWithUpdateStep()];
h.state.steps = [updateStep()];
await runAutomationsForTrigger({
accountId: ACCOUNT,
triggerType: "new_message_received",
contactId: "c1",
context: {},
});
// The insert happens before execution, so a run killed mid-flight must
// not leave behind a row that claims it succeeded.
expect(h.state.logInserts).toHaveLength(1);
expect(h.state.logInserts[0]).toMatchObject({
status: "failed",
steps_executed: [],
});
});
it("still promotes the log to 'success' once the steps complete", async () => {
h.state.owned = { id: "c1" };
h.state.automations = [automationWithUpdateStep()];
h.state.steps = [updateStep()];
await runAutomationsForTrigger({
accountId: ACCOUNT,
triggerType: "new_message_received",
contactId: "c1",
context: {},
});
// The seed is only a floor — the outermost scope still writes the real
// verdict, so a completed run reports success as it always did.
const withStatus = h.state.logUpdates.filter((u) => "status" in u);
expect(withStatus.at(-1)).toMatchObject({ status: "success" });
});
});
describe("update_contact_field — custom fields", () => {
it("upserts contact_custom_values when the field is account-owned", async () => {
h.state.owned = { id: "c1" };
h.state.ownedCustomField = { id: "cf1" };
h.state.automations = [automationWithUpdateStep()];
h.state.steps = [customStep("custom:cf1", "Premium")];
await runAutomationsForTrigger({
accountId: ACCOUNT,
triggerType: "new_message_received",
contactId: "c1",
context: {},
});
// No direct contacts column write for a custom field.
expect(h.state.updateCalls).toHaveLength(0);
expect(h.state.upsertCalls).toHaveLength(1);
expect(h.state.upsertCalls[0].payload).toEqual({
contact_id: "c1",
custom_field_id: "cf1",
value: "Premium",
});
});
it("interpolates {{ vars.* }} into the custom value", async () => {
h.state.owned = { id: "c1" };
h.state.ownedCustomField = { id: "cf1" };
h.state.automations = [automationWithUpdateStep()];
h.state.steps = [customStep("custom:cf1", "{{ vars.source }}")];
await runAutomationsForTrigger({
accountId: ACCOUNT,
triggerType: "new_message_received",
contactId: "c1",
context: { vars: { source: "WhatsApp Ad" } },
});
expect(h.state.upsertCalls).toHaveLength(1);
expect(
(h.state.upsertCalls[0].payload as { value: string }).value,
).toBe("WhatsApp Ad");
});
it("refuses to write a custom field from another account", async () => {
h.state.owned = { id: "c1" };
h.state.ownedCustomField = null; // account-scoped lookup finds nothing
h.state.automations = [automationWithUpdateStep()];
h.state.steps = [customStep("custom:foreign-cf", "x")];
await runAutomationsForTrigger({
accountId: ACCOUNT,
triggerType: "new_message_received",
contactId: "c1",
context: {},
});
expect(h.state.upsertCalls).toHaveLength(0);
expect(h.state.updateCalls).toHaveLength(0);
});
});
describe("send_webhook — SSRF guard (GHSA-8jqh-598v-rfxc)", () => {
it("refuses a private / link-local destination and never calls fetch", async () => {
const fetchSpy = vi.fn(async () => ({ ok: true, status: 200 }));
vi.stubGlobal("fetch", fetchSpy);
h.state.owned = { id: "c1" };
h.state.automations = [automationWithUpdateStep()];
// Aimed at the cloud metadata endpoint — the classic SSRF target.
h.state.steps = [webhookStep("http://169.254.169.254/latest/meta-data/")];
await runAutomationsForTrigger({
accountId: ACCOUNT,
triggerType: "new_message_received",
contactId: "c1",
context: {},
});
// The automation matched and its steps were loaded (so we genuinely
// reached the send_webhook case)...
expect(h.state.fromCalls).toContain("automation_steps");
// ...yet the guard blocked it before any outbound request left the box.
expect(fetchSpy).not.toHaveBeenCalled();
vi.unstubAllGlobals();
});
it("interpolates {{ contact.phone }} and {{ message.text }} into webhook body_template", async () => {
let capturedBody = "";
const fetchSpy = vi.fn(async (_url: string, init?: RequestInit) => {
capturedBody = String(init?.body ?? "");
return { ok: true, status: 200 };
});
vi.stubGlobal("fetch", fetchSpy);
h.state.owned = {
id: "c1",
phone: "+919876543210",
name: "Rahul Sharma",
email: "rahul@example.com",
} as unknown as { id: string };
h.state.automations = [automationWithUpdateStep()];
h.state.steps = [
{
id: "s1",
automation_id: "a1",
step_type: "send_webhook",
position: 0,
parent_step_id: null,
step_config: {
url: "https://example.com/api/incoming",
headers: {},
body_template: JSON.stringify({
sender_phone: "{{ contact.phone }}",
sender_name: "{{ contact.name }}",
full_message: "{{ message.text }}",
conversation_id: "{{ conversation.id }}",
}),
},
},
];
await runAutomationsForTrigger({
accountId: ACCOUNT,
triggerType: "new_message_received",
contactId: "c1",
context: {
message_text: "Hello I need product info",
conversation_id: "conv_123",
},
});
expect(fetchSpy).toHaveBeenCalled();
const parsed = JSON.parse(capturedBody);
expect(parsed).toEqual({
sender_phone: "+919876543210",
sender_name: "Rahul Sharma",
full_message: "Hello I need product info",
conversation_id: "conv_123",
});
vi.unstubAllGlobals();
});
});
function webhookStep(url: string) {
return {
id: "s1",
automation_id: "a1",
step_type: "send_webhook",
position: 0,
parent_step_id: null,
step_config: { url, headers: { "Metadata-Flavor": "Google" }, body_template: "{}" },
};
}
function automationWithUpdateStep() {
return {
id: "a1",
account_id: ACCOUNT,
user_id: "u1",
trigger_type: "new_message_received",
trigger_config: {},
is_active: true,
};
}
function updateStep() {
return {
id: "s1",
automation_id: "a1",
step_type: "update_contact_field",
position: 0,
parent_step_id: null,
step_config: { field: "company", value: "pwned-by-automation" },
};
}
function customStep(field: string, value: string) {
return {
id: "s1",
automation_id: "a1",
step_type: "update_contact_field",
position: 0,
parent_step_id: null,
step_config: { field, value },
};
}
describe("triggerMatches — interactive_reply", () => {
function automation(reply_ids: string[]): Automation {
return {
id: "a1",
account_id: ACCOUNT,
user_id: "u1",
name: "menu step",
trigger_type: "interactive_reply",
trigger_config: { reply_ids },
is_active: true,
execution_count: 0,
created_at: "",
updated_at: "",
};
}
it("matches when the tapped id is in reply_ids (exact)", () => {
expect(
triggerMatches(automation(["yes", "no"]), { interactive_reply_id: "yes" }),
).toBe(true);
});
it("does not match a different id", () => {
expect(
triggerMatches(automation(["yes"]), { interactive_reply_id: "maybe" }),
).toBe(false);
});
it("does not match on a substring (exact only)", () => {
expect(
triggerMatches(automation(["yes"]), { interactive_reply_id: "yes_please" }),
).toBe(false);
});
it("does not match when no reply id is present or config is empty", () => {
expect(triggerMatches(automation(["yes"]), {})).toBe(false);
expect(triggerMatches(automation([]), { interactive_reply_id: "yes" })).toBe(false);
});
});
describe("triggerMatches — tag_added", () => {
function automation(tagId?: string): Automation {
return {
id: "a1",
account_id: ACCOUNT,
user_id: "u1",
name: "tag follow-up",
trigger_type: "tag_added",
trigger_config: tagId ? { tag_id: tagId } : {},
is_active: true,
execution_count: 0,
created_at: "",
updated_at: "",
};
}
it("matches only the exact tag id", () => {
expect(triggerMatches(automation("tag-a"), { tag_id: "tag-a" })).toBe(true);
expect(triggerMatches(automation("tag-a"), { tag_id: "tag-ab" })).toBe(false);
});
it("fails closed when the config or event tag is missing", () => {
expect(triggerMatches(automation(), { tag_id: "tag-a" })).toBe(false);
expect(triggerMatches(automation("tag-a"), {})).toBe(false);
expect(triggerMatches(automation("tag-a"), undefined)).toBe(false);
});
});
describe("tag_added — conversation policy", () => {
it("records a clear failed step when the contact has no conversation", async () => {
h.state.owned = { id: "c1" };
h.state.automations = [{
id: "a1",
account_id: ACCOUNT,
user_id: "u1",
name: "tag outreach",
trigger_type: "tag_added",
trigger_config: { tag_id: "tag-a" },
is_active: true,
}];
h.state.steps = [{
id: "s1",
automation_id: "a1",
step_type: "send_message",
position: 0,
parent_step_id: null,
step_config: { text: "Hello" },
}];
await runAutomationsForTrigger({
accountId: ACCOUNT,
triggerType: "tag_added",
contactId: "c1",
context: { tag_id: "tag-a" },
});
expect(h.state.logUpdates).toContainEqual(expect.objectContaining({
status: "failed",
error_message: "tag_added automation cannot send: contact has no existing conversation",
}));
});
});
describe("triggerMatches — keyword_match", () => {
function automation(
cfg: Partial<KeywordMatchTriggerConfig> & { keywords: string[] },
): Automation {
return {
id: "a1",
account_id: ACCOUNT,
user_id: "u1",
name: "kw",
trigger_type: "keyword_match",
trigger_config: { match_type: "contains", ...cfg },
is_active: true,
} as unknown as Automation;
}
const on = (a: Automation, text: string) =>
triggerMatches(a, { message_text: text });
it("keeps `contains` as a raw substring test", () => {
// Issue #409 asked for this to become word-boundary matching. It
// deliberately did NOT change: existing automations relying on
// substring behaviour ("cat" firing on "category") must keep working,
// and `contains` is the builder's default. `word` is the opt-in fix.
expect(on(automation({ keywords: ["k"] }), "thanks")).toBe(true);
expect(on(automation({ keywords: ["cat"] }), "category")).toBe(true);
});
it("`word` matches only standalone words", () => {
const a = automation({ keywords: ["k"], match_type: "word" });
expect(on(a, "thanks")).toBe(false);
expect(on(a, "k")).toBe(true);
expect(on(a, "press k to continue")).toBe(true);
expect(on(a, "press K!")).toBe(true);
});
it("`word` respects punctuation and line edges around the keyword", () => {
const a = automation({ keywords: ["hi"], match_type: "word" });
expect(on(a, "hi")).toBe(true);
expect(on(a, "hi!")).toBe(true);
expect(on(a, "(hi)")).toBe(true);
expect(on(a, "say hi.")).toBe(true);
expect(on(a, "this")).toBe(false);
expect(on(a, "hiya")).toBe(false);
});
it("`word` handles a keyword that itself carries punctuation", () => {
// `\b` can't do this: /\bhi!\b/ demands a word char after the "!",
// so it never matches. Hence the lookaround implementation.
const a = automation({ keywords: ["hi!"], match_type: "word" });
expect(on(a, "say hi!")).toBe(true);
expect(on(a, "hi! there")).toBe(true);
});
it("`word` treats regex metacharacters in a keyword as literal", () => {
// Account-supplied free text — an unescaped "(" would throw.
const a = automation({ keywords: ["c++ (beginner)"], match_type: "word" });
expect(on(a, "I want the c++ (beginner) course")).toBe(true);
expect(on(a, "I want the cxx beginner course")).toBe(false);
expect(() => on(automation({ keywords: ["("], match_type: "word" }), "(")).not.toThrow();
});
it("`word` is case-insensitive unless case_sensitive is set", () => {
expect(on(automation({ keywords: ["Hi"], match_type: "word" }), "hi")).toBe(true);
expect(
on(
automation({ keywords: ["Hi"], match_type: "word", case_sensitive: true }),
"hi",
),
).toBe(false);
expect(
on(
automation({ keywords: ["Hi"], match_type: "word", case_sensitive: true }),
"Hi",
),
).toBe(true);
});
it("`word` finds a space-delimited keyword in a non-Latin script", () => {
// ASCII `\b` fails outright here — every character of "안녕" is a
// non-word character to it, so /\b안녕\b/ matches nothing.
const a = automation({ keywords: ["안녕"], match_type: "word" });
expect(on(a, "안녕")).toBe(true);
expect(on(a, "저기 안녕 하세요")).toBe(true);
// Documented limitation, not an accident: a language written without
// spaces has no word edge inside a run of characters.
expect(on(a, "안녕하세요")).toBe(false);
});
it("`exact` still requires the whole message to be the keyword", () => {
const a = automation({ keywords: ["hi"], match_type: "exact" });
expect(on(a, "hi")).toBe(true);
expect(on(a, "hi there")).toBe(false);
});
it("ignores empty keywords and empty messages in `word` mode", () => {
expect(on(automation({ keywords: [""], match_type: "word" }), "anything")).toBe(false);
expect(on(automation({ keywords: ["hi"], match_type: "word" }), "")).toBe(false);
});
});