Update hivegrid-cloud reference to latest main

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
davidandClaude Fable 5 committed 2026-07-08 16:15:37 +02:00
1 parent e98d38e716
commit 7b21524c86
3781 files changed
+373484 -225607

No files matched your search

@@ -1,5 +1,5 @@
{
"name": "@toolctrl/email-sequences",
"name": "@hivegrid/email-sequences",
"version": "0.0.0",
"private": true,
"type": "module",
@@ -0,0 +1,51 @@
import { describe, it, expect } from "vitest";
import { evaluateCondition, resolvePath } from "./conditions.js";
/**
* Edge-cases of the dot-path resolver that the happy-path tests don't
* reach: null intermediates, non-integer array segments and primitive
* intermediates short-circuit to `undefined` rather than throwing.
*/
describe("resolvePath edge cases", () => {
it("returns undefined when an intermediate segment is null", () => {
expect(resolvePath({ a: null }, "a.b")).toBeUndefined();
});
it("returns undefined for a non-integer array segment", () => {
expect(resolvePath({ items: [1, 2, 3] }, "items.x")).toBeUndefined();
});
it("returns undefined for a fractional array index", () => {
expect(resolvePath({ items: ["a", "b"] }, "items.1.5")).toBeUndefined();
});
it("resolves the array element itself (not just nested props)", () => {
expect(resolvePath({ items: ["a", "b"] }, "items.0")).toBe("a");
});
});
/**
* `in` / `not_in` accept a single scalar comparator value (not only an
* array). The internal `asArray` helper must wrap the scalar, and an
* undefined/null comparator must behave as an empty set.
*/
describe("evaluateCondition with scalar in/not_in comparators", () => {
const payload = { status: "qualified" };
it("treats a scalar `in` value as a one-element set", () => {
expect(evaluateCondition(payload, { path: "status", op: "in", value: "qualified" })).toBe(true);
expect(evaluateCondition(payload, { path: "status", op: "in", value: "new" })).toBe(false);
});
it("treats a scalar `not_in` value as a one-element set", () => {
expect(evaluateCondition(payload, { path: "status", op: "not_in", value: "new" })).toBe(true);
expect(evaluateCondition(payload, { path: "status", op: "not_in", value: "qualified" })).toBe(false);
});
it("treats a missing comparator as the empty set for `in` / `not_in`", () => {
// empty set never contains the actual value
expect(evaluateCondition(payload, { path: "status", op: "in" })).toBe(false);
// ...so not_in is vacuously true
expect(evaluateCondition(payload, { path: "status", op: "not_in" })).toBe(true);
});
});
@@ -0,0 +1,237 @@
import { describe, it, expect, vi } from "vitest";
import {
startSequenceRun,
advanceSequenceRun,
type SequenceEngineStore,
type SequenceEngineQueue,
type SequenceEngineLogger,
type SequenceRunRow,
} from "./engine.js";
import type { SequenceDefinition } from "./types.js";
const NOW = () => new Date("2026-05-17T12:00:00Z");
function makeStore(initial: SequenceRunRow | null = null): SequenceEngineStore & {
createdRuns: Array<{ leadId: string | null; tenantId: string | null; triggerEventId: string | null }>;
createdDeliveries: Array<{ runId: string; stepIndex: number; scheduledAt: Date }>;
statusUpdates: Array<{ runId: string; status: string }>;
} {
const createdRuns: Array<{ leadId: string | null; tenantId: string | null; triggerEventId: string | null }> = [];
const createdDeliveries: Array<{ runId: string; stepIndex: number; scheduledAt: Date }> = [];
const statusUpdates: Array<{ runId: string; status: string }> = [];
return {
createdRuns,
createdDeliveries,
statusUpdates,
createRun: vi.fn(async ({ sequenceId, leadId, tenantId, triggerEventId }) => {
createdRuns.push({ leadId, tenantId, triggerEventId });
return {
id: `run_${createdRuns.length}`,
sequenceId,
leadId,
tenantId,
triggerEventId,
status: "running" as const,
startedAt: NOW(),
completedAt: null,
stepStateJson: null,
};
}),
findRunByTrigger: vi.fn(async () => initial),
updateRunStatus: vi.fn(async (runId, status) => {
statusUpdates.push({ runId, status });
}),
createDelivery: vi.fn(async ({ runId, stepIndex, scheduledAt }) => {
createdDeliveries.push({ runId, stepIndex, scheduledAt });
return { id: `del_${createdDeliveries.length}`, runId, stepIndex, status: "pending" as const, scheduledAt };
}),
};
}
function makeQueue(): SequenceEngineQueue & { scheduled: Array<{ runId: string; stepIndex: number; runAt: Date }> } {
const scheduled: Array<{ runId: string; stepIndex: number; runAt: Date }> = [];
return { scheduled, scheduleStep: vi.fn(async (a) => void scheduled.push(a)) };
}
function makeLogger(): SequenceEngineLogger & { info: ReturnType<typeof vi.fn>; warn: ReturnType<typeof vi.fn>; error: ReturnType<typeof vi.fn> } {
return { info: vi.fn(), warn: vi.fn(), error: vi.fn() };
}
const SEQUENCE: SequenceDefinition = {
id: "seq_1",
tenantId: null,
name: "Welcome",
description: null,
triggerEvent: "lead.captured",
isEnabled: true,
steps: [{ stepIndex: 0, delayHours: 0, template: "welcome", subject: "Welcome" }],
};
const TRIGGER = {
triggerEventId: "evt_1",
leadId: "lead_1",
tenantId: null,
email: "alice@example.com",
recipientName: "Alice",
payload: { lead: { status: "new" } },
} as const;
describe("startSequenceRun edge cases", () => {
it("returns an empty result for a sequence with zero steps (no run, no schedule)", async () => {
const store = makeStore();
const queue = makeQueue();
const result = await startSequenceRun(
{ sequence: { ...SEQUENCE, steps: [] }, trigger: TRIGGER },
{ store, queue, now: NOW }
);
expect(result.scheduled).toBe(false);
expect(result.alreadyExisted).toBe(false);
expect(result.run.id).toBe("");
expect(result.run.status).toBe("cancelled");
expect(store.createdRuns).toHaveLength(0);
expect(queue.scheduled).toHaveLength(0);
});
it("skips the idempotency lookup when the trigger carries no event id", async () => {
const store = makeStore();
const queue = makeQueue();
const result = await startSequenceRun(
{ sequence: SEQUENCE, trigger: { ...TRIGGER, triggerEventId: null } },
{ store, queue, now: NOW }
);
expect(result.scheduled).toBe(true);
expect(store.findRunByTrigger).not.toHaveBeenCalled();
expect(store.createdRuns[0]?.triggerEventId).toBeNull();
});
it("normalises absent leadId / tenantId to null on the created run", async () => {
const store = makeStore();
const queue = makeQueue();
await startSequenceRun(
{
sequence: SEQUENCE,
trigger: { triggerEventId: null, email: "x@example.com", payload: {} },
},
{ store, queue, now: NOW }
);
expect(store.createdRuns[0]).toMatchObject({ leadId: null, tenantId: null });
});
it("logs the started event when a logger is provided", async () => {
const store = makeStore();
const queue = makeQueue();
const logger = makeLogger();
await startSequenceRun({ sequence: SEQUENCE, trigger: TRIGGER }, { store, queue, logger, now: NOW });
expect(logger.info).toHaveBeenCalledWith(
expect.objectContaining({ op: "sequence.run.started", runId: "run_1", stepIndex: 0 }),
expect.any(String)
);
});
it("falls back to the real clock when no `now` is injected", async () => {
const store = makeStore();
const queue = makeQueue();
const before = Date.now();
const result = await startSequenceRun({ sequence: SEQUENCE, trigger: TRIGGER }, { store, queue });
const after = Date.now();
// step 0 has delayHours 0, so scheduledAt ~= "now"
const scheduledMs = store.createdDeliveries[0]!.scheduledAt.getTime();
expect(result.scheduled).toBe(true);
expect(scheduledMs).toBeGreaterThanOrEqual(before);
expect(scheduledMs).toBeLessThanOrEqual(after);
});
it("logs the skip reason when sequence-level conditions fail", async () => {
const store = makeStore();
const queue = makeQueue();
const logger = makeLogger();
const result = await startSequenceRun(
{
sequence: { ...SEQUENCE, conditions: [{ path: "lead.status", op: "eq", value: "qualified" }] },
trigger: TRIGGER,
},
{ store, queue, logger, now: NOW }
);
expect(result.scheduled).toBe(false);
expect(logger.info).toHaveBeenCalledWith(
expect.objectContaining({ op: "sequence.skipped.sequence_conditions" }),
expect.any(String)
);
});
});
describe("advanceSequenceRun ordering + logging", () => {
const run: SequenceRunRow = {
id: "run_1",
sequenceId: "seq_1",
leadId: "lead_1",
tenantId: null,
triggerEventId: "evt_1",
status: "running",
startedAt: NOW(),
completedAt: null,
stepStateJson: null,
};
it("sorts out-of-order steps and picks the next-higher index", async () => {
const store = makeStore();
const queue = makeQueue();
// intentionally unsorted; step 2 comes before step 1 in the array
const steps = [
{ stepIndex: 0, delayHours: 0, template: "welcome", subject: "S0" },
{ stepIndex: 2, delayHours: 72, template: "generic-step", subject: "S2" },
{ stepIndex: 1, delayHours: 24, template: "generic-step", subject: "S1" },
];
const result = await advanceSequenceRun(
{ run, steps, previousStepIndex: 0 },
{ store, queue, now: NOW }
);
expect(result.completed).toBe(false);
// next after index 0 must be index 1 (the 24h step), not index 2
expect(queue.scheduled[0]?.stepIndex).toBe(1);
expect(result.scheduledAt?.toISOString()).toBe("2026-05-18T12:00:00.000Z");
});
it("uses the real clock for the next-step schedule when no `now` is injected", async () => {
const store = makeStore();
const queue = makeQueue();
const steps = [
{ stepIndex: 0, delayHours: 0, template: "welcome", subject: "S0" },
{ stepIndex: 1, delayHours: 1, template: "generic-step", subject: "S1" },
];
const before = Date.now();
const result = await advanceSequenceRun({ run, steps, previousStepIndex: 0 }, { store, queue });
const after = Date.now();
expect(result.completed).toBe(false);
const scheduledMs = result.scheduledAt!.getTime();
// 1h delay added on top of the real clock
expect(scheduledMs).toBeGreaterThanOrEqual(before + 60 * 60 * 1000);
expect(scheduledMs).toBeLessThanOrEqual(after + 60 * 60 * 1000);
});
it("uses the real clock for the completion timestamp when no `now` is injected", async () => {
const store = makeStore();
const queue = makeQueue();
const steps = [{ stepIndex: 0, delayHours: 0, template: "welcome", subject: "S0" }];
const result = await advanceSequenceRun({ run, steps, previousStepIndex: 0 }, { store, queue });
expect(result.completed).toBe(true);
expect(store.statusUpdates).toEqual([{ runId: "run_1", status: "completed" }]);
});
it("logs completion when the previous step was the last one", async () => {
const store = makeStore();
const queue = makeQueue();
const logger = makeLogger();
const steps = [{ stepIndex: 0, delayHours: 0, template: "welcome", subject: "S0" }];
const result = await advanceSequenceRun(
{ run, steps, previousStepIndex: 0 },
{ store, queue, logger, now: NOW }
);
expect(result.completed).toBe(true);
expect(store.statusUpdates).toEqual([{ runId: "run_1", status: "completed" }]);
expect(logger.info).toHaveBeenCalledWith(
expect.objectContaining({ op: "sequence.run.completed", runId: "run_1" }),
expect.any(String)
);
});
});
@@ -0,0 +1,65 @@
import { describe, it, expect } from "vitest";
import {
// condition DSL
resolvePath,
evaluateCondition,
evaluateAllConditions,
// type guards / parsers
parseSequenceSteps,
SequenceValidationError,
// engine
startSequenceRun,
advanceSequenceRun,
// step runner
runStep,
// unsubscribe-token
buildUnsubscribeUrl,
signUnsubscribeToken,
verifyUnsubscribeToken,
UnsubscribeTokenSecretMissingError,
} from "./index.js";
const SECRET = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
/**
* The barrel (`index.ts`) is the single public entry point declared in
* package.json `exports`. These tests assert the documented surface is
* actually re-exported and wired end-to-end through the barrel, so a
* missing or mis-typed re-export is caught rather than silently dropping
* a symbol from the published API.
*/
describe("package entry (index.ts)", () => {
it("re-exports the callable engine + condition + parser API", () => {
for (const fn of [
resolvePath,
evaluateCondition,
evaluateAllConditions,
parseSequenceSteps,
startSequenceRun,
advanceSequenceRun,
runStep,
buildUnsubscribeUrl,
signUnsubscribeToken,
verifyUnsubscribeToken,
]) {
expect(typeof fn).toBe("function");
}
});
it("re-exports the error classes as constructable subclasses of Error", () => {
const validation = new SequenceValidationError("bad", "INVALID_STEP");
expect(validation).toBeInstanceOf(Error);
expect(validation.code).toBe("INVALID_STEP");
const secretMissing = new UnsubscribeTokenSecretMissingError();
expect(secretMissing).toBeInstanceOf(Error);
expect(secretMissing.name).toBe("UnsubscribeTokenSecretMissingError");
});
it("round-trips an unsubscribe token through the public entry point", () => {
const url = buildUnsubscribeUrl({ baseUrl: "https://app.example.com", runId: "run_9", secret: SECRET });
const token = url.split("/unsubscribe/")[1]!;
const payload = verifyUnsubscribeToken(token, { secret: SECRET });
expect(payload).toMatchObject({ runId: "run_9" });
});
});
@@ -0,0 +1,207 @@
import { describe, it, expect, vi } from "vitest";
import { runStep, type StepRunnerStore, type StepRunnerDeps } from "./step-runner.js";
import type { SequenceStep, SequenceTriggerContext } from "./types.js";
import type { SequenceRunRow, SequenceEngineLogger } from "./engine.js";
const NOW = () => new Date("2026-05-17T12:00:00Z");
function buildRun(overrides: Partial<SequenceRunRow> = {}): SequenceRunRow {
return {
id: "run_1",
sequenceId: "seq_1",
leadId: "lead_1",
tenantId: null,
triggerEventId: "evt_1",
status: "running",
startedAt: NOW(),
completedAt: null,
stepStateJson: null,
...overrides,
};
}
function buildStore(opts: {
run?: SequenceRunRow | null;
steps?: readonly SequenceStep[];
trigger?: SequenceTriggerContext | null;
}): StepRunnerStore & { delivered: unknown[]; statusUpdates: Array<{ runId: string; status: string }> } {
const delivered: unknown[] = [];
const statusUpdates: Array<{ runId: string; status: string }> = [];
return {
delivered,
statusUpdates,
loadRun: vi.fn(async () => opts.run ?? null),
loadSteps: vi.fn(async () => opts.steps ?? []),
loadTriggerContext: vi.fn(async () => opts.trigger ?? null),
markDelivery: vi.fn(async (input) => void delivered.push(input)),
createRun: vi.fn(),
findRunByTrigger: vi.fn(async () => null),
updateRunStatus: vi.fn(async (runId, status) => void statusUpdates.push({ runId, status })),
createDelivery: vi.fn(async ({ runId, stepIndex, scheduledAt }) => ({
id: `del_${stepIndex}`,
runId,
stepIndex,
status: "pending" as const,
scheduledAt,
})),
};
}
function makeLogger(): SequenceEngineLogger & {
info: ReturnType<typeof vi.fn>;
warn: ReturnType<typeof vi.fn>;
error: ReturnType<typeof vi.fn>;
} {
return { info: vi.fn(), warn: vi.fn(), error: vi.fn() };
}
function buildDeps(store: StepRunnerStore, overrides: Partial<StepRunnerDeps> = {}): StepRunnerDeps {
return {
store,
queue: { scheduleStep: vi.fn() },
now: NOW,
renderTemplate: () => ({ html: "<p>x</p>", text: "x", subject: "Hello" }),
sendMail: async () => ({ ok: true, messageId: "msg_1" }),
buildUnsubscribeUrl: () => "https://app.example.com/unsubscribe/tok",
...overrides,
};
}
const STEPS: readonly SequenceStep[] = [
{ stepIndex: 0, delayHours: 0, template: "welcome", subject: "S0" },
{ stepIndex: 1, delayHours: 24, template: "generic-step", subject: "S1" },
];
const TRIGGER: SequenceTriggerContext = {
triggerEventId: "evt_1",
leadId: "lead_1",
tenantId: null,
email: "alice@example.com",
recipientName: "Alice",
payload: { lead: { status: "new" } },
};
describe("runStep — unknown / out-of-range step", () => {
it("cancels without delivering when the requested step index is not in the run", async () => {
const store = buildStore({ run: buildRun(), steps: STEPS, trigger: TRIGGER });
const logger = makeLogger();
const queueSchedule = vi.fn();
const deps = buildDeps(store, { logger, queue: { scheduleStep: queueSchedule } });
const result = await runStep({ runId: "run_1", stepIndex: 99 }, deps);
expect(result).toEqual({ action: "cancelled", completed: true });
expect(store.delivered).toHaveLength(0);
expect(queueSchedule).not.toHaveBeenCalled();
expect(logger.warn).toHaveBeenCalledWith(
expect.objectContaining({ op: "sequence.step.unknown_step", stepIndex: 99 }),
expect.any(String)
);
});
});
describe("runStep — logger wiring on every branch", () => {
it("logs a warning when the run row is missing", async () => {
const store = buildStore({ run: null });
const logger = makeLogger();
const result = await runStep({ runId: "run_1", stepIndex: 0 }, buildDeps(store, { logger }));
expect(result.action).toBe("cancelled");
expect(logger.warn).toHaveBeenCalledWith(
expect.objectContaining({ op: "sequence.step.run_missing" }),
expect.any(String)
);
});
it("logs an info line when the run is already in a terminal state", async () => {
const store = buildStore({ run: buildRun({ status: "completed" }), steps: STEPS, trigger: TRIGGER });
const logger = makeLogger();
const result = await runStep({ runId: "run_1", stepIndex: 0 }, buildDeps(store, { logger }));
expect(result.action).toBe("cancelled");
expect(logger.info).toHaveBeenCalledWith(
expect.objectContaining({ op: "sequence.step.run_inactive", status: "completed" }),
expect.any(String)
);
});
it("logs a warning + skip when the trigger context has vanished", async () => {
const store = buildStore({ run: buildRun(), steps: STEPS, trigger: null });
const logger = makeLogger();
const result = await runStep({ runId: "run_1", stepIndex: 0 }, buildDeps(store, { logger }));
expect(result.action).toBe("skipped");
expect(logger.warn).toHaveBeenCalledWith(
expect.objectContaining({ op: "sequence.step.no_trigger" }),
expect.any(String)
);
});
it("logs an info line when step conditions are not met", async () => {
const conditionalSteps: readonly SequenceStep[] = [
{ stepIndex: 0, delayHours: 0, template: "welcome", subject: "S0", conditions: [{ path: "lead.status", op: "eq", value: "qualified" }] },
{ stepIndex: 1, delayHours: 24, template: "generic-step", subject: "S1" },
];
const store = buildStore({ run: buildRun(), steps: conditionalSteps, trigger: TRIGGER });
const logger = makeLogger();
const result = await runStep({ runId: "run_1", stepIndex: 0 }, buildDeps(store, { logger }));
expect(result.action).toBe("skipped");
expect(logger.info).toHaveBeenCalledWith(
expect.objectContaining({ op: "sequence.step.conditions_false", stepIndex: 0 }),
expect.any(String)
);
});
it("logs the provider message id on a successful send", async () => {
const store = buildStore({ run: buildRun(), steps: STEPS, trigger: TRIGGER });
const logger = makeLogger();
const sendMail = vi.fn().mockResolvedValue({ ok: true, messageId: "msg_77" });
const result = await runStep({ runId: "run_1", stepIndex: 0 }, buildDeps(store, { logger, sendMail }));
expect(result.action).toBe("sent");
expect(logger.info).toHaveBeenCalledWith(
expect.objectContaining({ op: "sequence.step.sent", providerMessageId: "msg_77" }),
expect.any(String)
);
});
it("logs a warning and fails the run on a hard bounce", async () => {
const store = buildStore({ run: buildRun(), steps: STEPS, trigger: TRIGGER });
const logger = makeLogger();
const sendMail = vi.fn().mockResolvedValue({ ok: false, bounced: true, errorTag: "hard_bounce" });
const result = await runStep({ runId: "run_1", stepIndex: 0 }, buildDeps(store, { logger, sendMail }));
expect(result).toEqual({ action: "failed", completed: true });
expect(store.statusUpdates).toEqual([{ runId: "run_1", status: "failed" }]);
expect(logger.warn).toHaveBeenCalledWith(
expect.objectContaining({ op: "sequence.step.bounced", errorTag: "hard_bounce" }),
expect.any(String)
);
});
});
describe("runStep — send wiring details", () => {
it("forwards subject/recipient/unsubscribe data and the optional list-unsubscribe mailto", async () => {
const store = buildStore({ run: buildRun(), steps: STEPS, trigger: TRIGGER });
const sendMail = vi.fn().mockResolvedValue({ ok: true, messageId: "m1" });
const renderTemplate = vi.fn().mockReturnValue({ html: "<b>hi</b>", text: "hi", subject: "Renamed Subject" });
const buildUnsubscribeMailto = vi.fn().mockReturnValue("mailto:unsub@example.com");
await runStep(
{ runId: "run_1", stepIndex: 0 },
buildDeps(store, { sendMail, renderTemplate, buildUnsubscribeMailto })
);
expect(sendMail).toHaveBeenCalledWith({
to: "alice@example.com",
subject: "Renamed Subject",
html: "<b>hi</b>",
text: "hi",
unsubscribeUrl: "https://app.example.com/unsubscribe/tok",
listUnsubscribeMailto: "mailto:unsub@example.com",
});
expect(renderTemplate).toHaveBeenCalledWith(STEPS[0], TRIGGER, "run_1");
});
it("falls back to a fresh Date when no `now` is injected on a transient failure", async () => {
const store = buildStore({ run: buildRun(), steps: STEPS, trigger: TRIGGER });
const sendMail = vi.fn().mockResolvedValue({ ok: false, errorTag: "smtp_timeout" });
// no `now` override → exercises the `?? (() => new Date())` fallback
const deps = buildDeps(store, { sendMail, logger: makeLogger() });
delete (deps as { now?: () => Date }).now;
const result = await runStep({ runId: "run_1", stepIndex: 0 }, deps);
expect(result).toEqual({ action: "failed", completed: false });
expect(store.delivered[0]).toMatchObject({ status: "failed", errorMessage: "smtp_timeout" });
});
});
@@ -0,0 +1,92 @@
import { describe, it, expect } from "vitest";
import { parseSequenceSteps, parseConditions, SequenceValidationError } from "./types.js";
/**
* Validation branches of the `stepsJson` parser that the happy-path
* suite does not exercise: non-object entries, malformed condition
* blocks, and the carry-through of `variables` + per-step `conditions`.
*/
describe("parseSequenceSteps validation branches", () => {
it("rejects a non-object step entry with INVALID_STEP", () => {
try {
parseSequenceSteps([null]);
expect.unreachable("expected throw");
} catch (err) {
expect(err).toBeInstanceOf(SequenceValidationError);
expect((err as SequenceValidationError).code).toBe("INVALID_STEP");
}
});
it("rejects a primitive step entry (number) with INVALID_STEP", () => {
expect(() => parseSequenceSteps([42])).toThrow(SequenceValidationError);
});
it("preserves variables and parsed conditions on a full step", () => {
const steps = parseSequenceSteps([
{
stepIndex: 0,
delayHours: 0,
template: "welcome",
subject: "Hi",
variables: { headline: "Welcome", ctaUrl: "https://x" },
conditions: [{ path: "lead.status", op: "eq", value: "new" }],
},
]);
expect(steps[0]?.variables).toEqual({ headline: "Welcome", ctaUrl: "https://x" });
expect(steps[0]?.conditions).toEqual([{ path: "lead.status", op: "eq", value: "new" }]);
});
it("drops a non-object `variables` field to undefined", () => {
const steps = parseSequenceSteps([
{ stepIndex: 0, delayHours: 0, template: "welcome", subject: "Hi", variables: "not-an-object" },
]);
expect(steps[0]?.variables).toBeUndefined();
});
it("surfaces an invalid per-step condition as INVALID_CONDITION", () => {
try {
parseSequenceSteps([
{ stepIndex: 0, delayHours: 0, template: "welcome", subject: "Hi", conditions: [{ op: "eq" }] },
]);
expect.unreachable("expected throw");
} catch (err) {
expect((err as SequenceValidationError).code).toBe("INVALID_CONDITION");
}
});
});
describe("parseConditions validation branches", () => {
it("returns undefined for an explicit null", () => {
expect(parseConditions(null, "ctx")).toBeUndefined();
});
it("rejects a non-array conditions blob", () => {
expect(() => parseConditions("nope" as unknown, "ctx")).toThrow(SequenceValidationError);
});
it("rejects a non-object condition entry", () => {
expect(() => parseConditions([null], "ctx")).toThrow(SequenceValidationError);
});
it("rejects a condition without a path", () => {
expect(() => parseConditions([{ op: "eq", value: 1 }], "ctx")).toThrow(SequenceValidationError);
});
it("rejects a condition with an empty-string path", () => {
expect(() => parseConditions([{ path: "", op: "eq", value: 1 }], "ctx")).toThrow(SequenceValidationError);
});
it("includes the supplied context label in the thrown message", () => {
try {
parseConditions([{ path: "x", op: "bogus" }], "step 3");
expect.unreachable("expected throw");
} catch (err) {
expect((err as Error).message).toContain("step 3");
}
});
it("passes the comparator value through unchanged for valid ops", () => {
const parsed = parseConditions([{ path: "lead.tags", op: "in", value: ["a", "b"] }], "ctx");
expect(parsed?.[0]).toEqual({ path: "lead.tags", op: "in", value: ["a", "b"] });
});
});
@@ -19,7 +19,7 @@ export type SequenceTriggerEvent =
| "custom";
/**
* Built-in template identifiers shipped by `@toolctrl/email-templates`.
* Built-in template identifiers shipped by `@hivegrid/email-templates`.
* Operators can also point at a `custom:<id>` value when their tenant
* has a registry-stored override.
*/
@@ -0,0 +1,80 @@
import { describe, expect, it } from "vitest";
import { createHmac } from "node:crypto";
import { signUnsubscribeToken, verifyUnsubscribeToken } from "./unsubscribe-token.js";
const SECRET = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
const TOKEN_VERSION = "u1";
/**
* Forge a token whose signature is valid for `SECRET` but whose payload
* bytes are attacker-chosen. This lets us probe the verifier's post-
* signature payload validation (JSON parse, shape + field-type guards)
* without relying on the well-behaved `signUnsubscribeToken` serializer.
*/
function forgeSignedToken(rawPayload: string, secret = SECRET): string {
const payloadB64 = Buffer.from(rawPayload, "utf8").toString("base64url");
const sig = createHmac("sha256", Buffer.from(secret, "utf8"))
.update(`${TOKEN_VERSION}.${payloadB64}`)
.digest()
.toString("base64url");
return `${TOKEN_VERSION}.${payloadB64}.${sig}`;
}
describe("verifyUnsubscribeToken — malformed signed payloads", () => {
it("rejects a structurally invalid token (wrong part count)", () => {
expect(verifyUnsubscribeToken("u1.onlytwo", { secret: SECRET })).toBeNull();
expect(verifyUnsubscribeToken("a.b.c.d", { secret: SECRET })).toBeNull();
});
it("rejects a token whose signature uses non-base64url characters", () => {
const valid = signUnsubscribeToken({ runId: "run_1", secret: SECRET });
const parts = valid.split(".");
const badSig = `${parts[0]}.${parts[1]}.not*valid*sig`;
expect(verifyUnsubscribeToken(badSig, { secret: SECRET })).toBeNull();
});
it("rejects a correctly-signed but non-JSON payload", () => {
const token = forgeSignedToken("definitely-not-json{");
expect(verifyUnsubscribeToken(token, { secret: SECRET })).toBeNull();
});
it("rejects a correctly-signed payload that is valid JSON but not an object", () => {
expect(verifyUnsubscribeToken(forgeSignedToken("123"), { secret: SECRET })).toBeNull();
expect(verifyUnsubscribeToken(forgeSignedToken("null"), { secret: SECRET })).toBeNull();
expect(verifyUnsubscribeToken(forgeSignedToken('"a string"'), { secret: SECRET })).toBeNull();
});
it("rejects a correctly-signed object payload missing a runId", () => {
expect(verifyUnsubscribeToken(forgeSignedToken("{}"), { secret: SECRET })).toBeNull();
expect(
verifyUnsubscribeToken(forgeSignedToken(JSON.stringify({ runId: "" })), { secret: SECRET })
).toBeNull();
});
it("normalises wrongly-typed leadId / tenantId / iat to null / 0 defaults", () => {
const token = forgeSignedToken(
JSON.stringify({ runId: "run_x", leadId: 5, tenantId: true, iat: "nope" })
);
expect(verifyUnsubscribeToken(token, { secret: SECRET })).toEqual({
runId: "run_x",
leadId: null,
tenantId: null,
iat: 0,
});
});
it("defaults absent optional fields when only runId is present", () => {
const token = forgeSignedToken(JSON.stringify({ runId: "run_y" }));
expect(verifyUnsubscribeToken(token, { secret: SECRET })).toEqual({
runId: "run_y",
leadId: null,
tenantId: null,
iat: 0,
});
});
it("does not honour a forged payload signed with a different secret", () => {
const token = forgeSignedToken(JSON.stringify({ runId: "run_z" }), "f".repeat(64));
expect(verifyUnsubscribeToken(token, { secret: SECRET })).toBeNull();
});
});