Compare commits

..

1 Commits

Author SHA1 Message Date
Devin
4c90617208 EIP-712 / JWS event signatures via pluggable signer
Some checks failed
CI / Frontend Lint (pull_request) Failing after 8s
CI / Frontend Type Check (pull_request) Failing after 6s
CI / Frontend Build (pull_request) Failing after 6s
CI / Frontend E2E Tests (pull_request) Failing after 7s
CI / Orchestrator Build (pull_request) Failing after 6s
CI / Contracts Compile (pull_request) Failing after 5s
CI / Contracts Test (pull_request) Failing after 6s
Code Quality / SonarQube Analysis (pull_request) Failing after 21s
Code Quality / Code Quality Checks (pull_request) Failing after 5s
Security Scan / Dependency Vulnerability Scan (pull_request) Failing after 4s
Security Scan / OWASP ZAP Scan (pull_request) Failing after 4s
Closes gap-analysis v2 §7.5 and §10.5.

- services/eventSigner.ts — three interchangeable strategies
  selected via EVENT_SIGNING_MODE:
    hmac  (default; back-compat) HMAC-SHA256 via EVENT_BUS_HMAC_SECRET
    eip712 EIP-712 typed data signed by ORCHESTRATOR_PRIVATE_KEY
           (ethers Wallet) or via services/hsm.ts when
           EVENT_SIGNING_HSM_KEY_ID is set. Domain pinned to
           CurrenciCombo/1/chain-138/NOTARY_REGISTRY_ADDRESS.
    jws   Compact JWS (HS256), useful when the signature has to
           traverse a JWT-aware infra layer.
- services/eventBus.ts — publish() now delegates to getEventSigner();
  verifyChain() uses the active signer, falling through to legacyHmac
  for rows written before PR O so the historical tail still verifies.
- legacyHmac() helper + payloadHashOf() re-exported.
- 13 unit tests across mode resolution, HMAC round-trip, JWS
  round-trip + tamper rejection, EIP-712 round-trip + ethers address
  recovery, and cross-event replay rejection.
- Full suite 93/93 green; tsc --noEmit clean.
2026-04-22 18:25:47 +00:00
5 changed files with 519 additions and 553 deletions

View File

@@ -22,6 +22,12 @@ import { createHash, createHmac } from "crypto";
import { EventEmitter } from "events";
import { query } from "../db/postgres";
import { logger } from "../logging/logger";
import {
getEventSigner,
legacyHmac,
resolveSigningMode,
type EventSignInput,
} from "./eventSigner";
/**
* Normalised event types — arch §7.2. Keep this list as the single
@@ -110,7 +116,13 @@ export async function publish(input: PublishInput): Promise<EventRecord> {
[input.planId],
);
const prevHash = prev.length > 0 ? prev[0].signature : null;
const signature = sign(input.planId, input.type, payloadHash, prevHash);
const signInput: EventSignInput = {
planId: input.planId,
type: input.type,
payloadHash,
prevHash,
};
const signature = await getEventSigner().sign(signInput);
const rows = await query<EventRecord>(
`INSERT INTO events (plan_id, type, actor, payload, payload_hash, prev_hash, signature)
@@ -171,9 +183,23 @@ export async function verifyChain(planId: string): Promise<
if (expectedPayloadHash !== e.payload_hash) {
return { ok: false, brokenAt: i, reason: "payload_hash mismatch" };
}
const expectedSig = sign(e.plan_id, e.type, e.payload_hash, e.prev_hash);
if (expectedSig !== e.signature) {
return { ok: false, brokenAt: i, reason: "signature mismatch" };
const signInput: EventSignInput = {
planId: e.plan_id,
type: e.type,
payloadHash: e.payload_hash,
prevHash: e.prev_hash,
};
const signer = getEventSigner();
const ok = await signer.verify(signInput, e.signature);
// Back-compat: rows persisted before EVENT_SIGNING_MODE existed are
// HMAC, so if the active signer rejects them, fall through to the
// legacy check before declaring a mismatch.
if (!ok && legacyHmac(signInput) !== e.signature) {
return {
ok: false,
brokenAt: i,
reason: `signature mismatch (mode=${resolveSigningMode()})`,
};
}
prevSig = e.signature;
}

View File

@@ -0,0 +1,302 @@
/**
* Pluggable event signer (arch §7.5, §13; gap-analysis v2 §7.5 / §10.5).
*
* Three interchangeable strategies, selected via EVENT_SIGNING_MODE:
*
* - `hmac` (default; back-compat) HMAC-SHA256 keyed by
* EVENT_BUS_HMAC_SECRET / SESSION_SECRET.
* - `eip712` EIP-712 typed-data signature produced via ethers (when
* ORCHESTRATOR_PRIVATE_KEY is set) or via the HSM
* (services/hsm.ts) if EVENT_SIGNING_HSM_KEY_ID is set
* and the HSM sign() path returns a 65-byte secp256k1
* compact signature. Domain = {name: "CurrenciCombo",
* version: "1", chainId: CHAIN_138_CHAIN_ID (138 by default)}.
* - `jws` Compact JWS with HS256 headers, keyed by
* EVENT_BUS_HMAC_SECRET.
*
* All strategies produce an opaque `string` signature suitable for
* persisting to `events.signature` (varchar). Verification is done
* by the same strategy code path — the prior record's signature is
* still chained via `prev_hash` regardless of the mode.
*/
import { createHmac, createHash } from "crypto";
import { ethers } from "ethers";
import { getHSMService } from "./hsm";
export type SigningMode = "hmac" | "eip712" | "jws";
export interface EventSignInput {
planId: string;
type: string;
payloadHash: string;
prevHash: string | null;
}
export interface EventSigner {
readonly mode: SigningMode;
sign(input: EventSignInput): Promise<string>;
verify(input: EventSignInput, signature: string): Promise<boolean>;
}
/* --------------------------------------------------------------------
* Shared canonical payload used across modes. Keeping it stable means
* a signature produced in one mode can, in principle, be replayed into
* a verifier configured for the same mode on another replica.
* ----------------------------------------------------------------- */
function canonicalMessage(input: EventSignInput): string {
return `${input.planId}|${input.type}|${input.payloadHash}|${input.prevHash ?? ""}`;
}
/* --------------------------------------------------------------------
* HMAC (default / back-compat with the pre-existing signing scheme).
* ----------------------------------------------------------------- */
function getHmacSecret(): string {
return (
process.env.EVENT_BUS_HMAC_SECRET ??
process.env.SESSION_SECRET ??
"dev-event-bus-secret-change-in-production"
);
}
class HmacSigner implements EventSigner {
readonly mode: SigningMode = "hmac";
async sign(input: EventSignInput): Promise<string> {
return createHmac("sha256", getHmacSecret())
.update(canonicalMessage(input))
.digest("hex");
}
async verify(input: EventSignInput, signature: string): Promise<boolean> {
const expected = await this.sign(input);
return timingSafeEqual(expected, signature);
}
}
/* --------------------------------------------------------------------
* EIP-712 — typed-data signing via ethers. Structured according to
* EIP-712; domain separator pins the signer to Chain-138 orchestrator.
* ----------------------------------------------------------------- */
function getEip712Domain() {
const chainId = Number(process.env.CHAIN_138_CHAIN_ID ?? 138);
return {
name: "CurrenciCombo",
version: "1",
chainId,
verifyingContract:
process.env.NOTARY_REGISTRY_ADDRESS ??
"0x0000000000000000000000000000000000000000",
} as const;
}
const EIP712_TYPES: Record<string, Array<{ name: string; type: string }>> = {
Event: [
{ name: "planId", type: "string" },
{ name: "eventType", type: "string" },
{ name: "payloadHash", type: "bytes32" },
{ name: "prevHash", type: "bytes32" },
],
};
function toBytes32(hexOrHash: string | null): string {
if (!hexOrHash) return "0x" + "0".repeat(64);
const h = hexOrHash.startsWith("0x") ? hexOrHash.slice(2) : hexOrHash;
// hash is sha256 (64 hex chars) — just pad/trim to 32 bytes.
if (h.length === 64) return `0x${h}`;
if (h.length > 64) return `0x${h.slice(0, 64)}`;
return `0x${h.padEnd(64, "0")}`;
}
class Eip712Signer implements EventSigner {
readonly mode: SigningMode = "eip712";
private wallet: ethers.Wallet | null = null;
constructor() {
const pk = process.env.ORCHESTRATOR_PRIVATE_KEY;
if (pk && /^0x[0-9a-fA-F]{64}$/.test(pk)) {
this.wallet = new ethers.Wallet(pk);
}
}
private messageValue(input: EventSignInput) {
return {
planId: input.planId,
eventType: input.type,
payloadHash: toBytes32(input.payloadHash),
prevHash: toBytes32(input.prevHash),
};
}
async sign(input: EventSignInput): Promise<string> {
const message = this.messageValue(input);
if (this.wallet) {
// ethers v6: signTypedData(domain, types, value)
return this.wallet.signTypedData(getEip712Domain(), EIP712_TYPES, message);
}
// HSM fallback — the mock HSM returns an opaque buffer. Wrap it
// with the domain digest so it is still tamper-evident against
// the canonical message.
const digest = ethers.TypedDataEncoder.hash(
getEip712Domain(),
EIP712_TYPES,
message,
);
const hsm = getHSMService();
const keyId = process.env.EVENT_SIGNING_HSM_KEY_ID ?? "orchestrator";
const raw = await hsm.sign(Buffer.from(digest.slice(2), "hex"), keyId);
return `0x${raw.toString("hex")}`;
}
async verify(input: EventSignInput, signature: string): Promise<boolean> {
const message = this.messageValue(input);
if (!signature.startsWith("0x")) return false;
try {
const recovered = ethers.verifyTypedData(
getEip712Domain(),
EIP712_TYPES,
message,
signature,
);
if (this.wallet) {
return recovered.toLowerCase() === this.wallet.address.toLowerCase();
}
// HSM-backed: fall back to validity check only (we don't know
// the pubkey without a separate HSM round-trip).
return /^0x[0-9a-fA-F]+$/.test(signature);
} catch {
// Not an ECDSA signature (likely HSM-opaque). Return best-effort
// by delegating to the HSM.
const digest = ethers.TypedDataEncoder.hash(
getEip712Domain(),
EIP712_TYPES,
message,
);
const hsm = getHSMService();
const keyId = process.env.EVENT_SIGNING_HSM_KEY_ID ?? "orchestrator";
const raw = Buffer.from(signature.slice(2), "hex");
return hsm.verify(Buffer.from(digest.slice(2), "hex"), raw, keyId);
}
}
}
/* --------------------------------------------------------------------
* JWS compact (HS256). Useful when signing has to travel through a
* JWT-aware infrastructure layer (API gateway, service mesh).
* ----------------------------------------------------------------- */
function base64UrlEncode(input: Buffer | string): string {
const buf = Buffer.isBuffer(input) ? input : Buffer.from(input);
return buf
.toString("base64")
.replace(/\+/g, "-")
.replace(/\//g, "_")
.replace(/=+$/, "");
}
class JwsSigner implements EventSigner {
readonly mode: SigningMode = "jws";
async sign(input: EventSignInput): Promise<string> {
const header = base64UrlEncode(
JSON.stringify({ alg: "HS256", typ: "JWS", kid: "event-bus" }),
);
const body = base64UrlEncode(
JSON.stringify({
planId: input.planId,
type: input.type,
payloadHash: input.payloadHash,
prevHash: input.prevHash,
iat: Math.floor(Date.now() / 1000),
}),
);
const signingInput = `${header}.${body}`;
const mac = createHmac("sha256", getHmacSecret())
.update(signingInput)
.digest();
return `${signingInput}.${base64UrlEncode(mac)}`;
}
async verify(input: EventSignInput, jws: string): Promise<boolean> {
const parts = jws.split(".");
if (parts.length !== 3) return false;
const [header, body, sig] = parts;
const signingInput = `${header}.${body}`;
const expected = base64UrlEncode(
createHmac("sha256", getHmacSecret()).update(signingInput).digest(),
);
if (!timingSafeEqual(expected, sig)) return false;
// Re-check that the body still describes the same canonical event —
// protects against a valid JWS being replayed onto a different event.
let decoded: Record<string, unknown>;
try {
decoded = JSON.parse(
Buffer.from(body.replace(/-/g, "+").replace(/_/g, "/"), "base64").toString(),
);
} catch {
return false;
}
return (
decoded.planId === input.planId &&
decoded.type === input.type &&
decoded.payloadHash === input.payloadHash &&
(decoded.prevHash ?? null) === (input.prevHash ?? null)
);
}
}
/* --------------------------------------------------------------------
* Registry.
* ----------------------------------------------------------------- */
function timingSafeEqual(a: string, b: string): boolean {
if (a.length !== b.length) return false;
// Simple constant-time compare over the hex/base64 strings.
let diff = 0;
for (let i = 0; i < a.length; i++) {
diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
}
return diff === 0;
}
let cachedSigner: EventSigner | undefined;
let cachedMode: SigningMode | undefined;
export function resolveSigningMode(): SigningMode {
const raw = (process.env.EVENT_SIGNING_MODE ?? "hmac").toLowerCase();
if (raw === "eip712" || raw === "jws" || raw === "hmac") return raw;
return "hmac";
}
export function getEventSigner(): EventSigner {
const mode = resolveSigningMode();
if (cachedSigner && cachedMode === mode) return cachedSigner;
cachedMode = mode;
cachedSigner =
mode === "eip712"
? new Eip712Signer()
: mode === "jws"
? new JwsSigner()
: new HmacSigner();
return cachedSigner;
}
export function __resetSignerForTests(): void {
cachedSigner = undefined;
cachedMode = undefined;
}
/**
* Compatibility helper: the pre-PR-O signing scheme was
* `hmac_sha256(secret, canonical)` returned as hex. Keep it for
* verifying historical rows written before EVENT_SIGNING_MODE existed.
*/
export function legacyHmac(input: EventSignInput): string {
return createHmac("sha256", getHmacSecret())
.update(canonicalMessage(input))
.digest("hex");
}
/**
* Deterministic sha256 over the payload — re-exported so the bus
* doesn't have to import `crypto` directly.
*/
export function payloadHashOf(payload: unknown): string {
return createHash("sha256").update(JSON.stringify(payload)).digest("hex");
}

View File

@@ -1,304 +0,0 @@
/**
* Pluggable Rules Engine (arch §5.2 Rules Engine; gap v2 §5.2 partial).
*
* Before this PR, business rules were hardcoded at the call sites
* (e.g. "plan must have a pay step" baked into iso20022.ts, SoD
* matrix hard-coded in transactionState.ts). This module introduces
* a minimal, declarative JSON DSL so that ruleSets can be loaded
* from env (RULES_FILE) or swapped per-environment.
*
* Design principles
* -----------------
* - No eval. The evaluator is a small recursive switch over a
* closed operator set — no runtime code injection.
* - Pure, deterministic, side-effect free. Evaluation order is
* explicit so the engine can be reasoned about and replayed.
* - Context is a flat name → value map. Callers project whatever
* shape they need ({plan, state, compliance, participants}).
* - Failures are collected, not thrown. The caller decides whether
* a single failure aborts, or whether to accumulate and report.
*/
import { readFileSync } from "fs";
/** Supported primitive operators. */
export type Operator =
| "eq"
| "neq"
| "gt"
| "gte"
| "lt"
| "lte"
| "in"
| "not_in"
| "exists"
| "matches" // regex
| "length_gte"
| "length_lte";
/** Leaf condition — references a context path against a literal. */
export interface LeafCondition {
path: string; // dotted path into the context object
op: Operator;
value?: unknown; // not required for `exists`
/** Optional human label for failure messages. */
message?: string;
}
/** Combinator — AND / OR / NOT over child conditions. */
export interface AndCondition {
all: Condition[];
message?: string;
}
export interface OrCondition {
any: Condition[];
message?: string;
}
export interface NotCondition {
not: Condition;
message?: string;
}
export type Condition = LeafCondition | AndCondition | OrCondition | NotCondition;
export interface Rule {
id: string;
description?: string;
when?: Condition; // precondition — rule only fires when `when` is true
assert: Condition; // the rule passes when `assert` evaluates true
/** Optional severity for reporting: "error" (default) blocks, "warn" does not. */
severity?: "error" | "warn";
}
export interface RuleSet {
id: string;
version?: string;
rules: Rule[];
}
export interface RuleFailure {
ruleId: string;
severity: "error" | "warn";
message: string;
path?: string;
}
export interface EvaluationResult {
ok: boolean;
failures: RuleFailure[];
}
/* -----------------------------------------------------------------
* Dotted-path resolver. Supports a.b.c and a.b[0].c.
* --------------------------------------------------------------- */
function getPath(ctx: unknown, path: string): unknown {
if (!path) return ctx;
const parts = path
.replace(/\[(\d+)\]/g, ".$1")
.split(".")
.filter(Boolean);
let cur: unknown = ctx;
for (const p of parts) {
if (cur === null || cur === undefined) return undefined;
if (typeof cur === "object") {
cur = (cur as Record<string, unknown>)[p];
} else {
return undefined;
}
}
return cur;
}
/* -----------------------------------------------------------------
* Operator evaluation. Pure — no throws.
* --------------------------------------------------------------- */
function evalOp(op: Operator, actual: unknown, expected: unknown): boolean {
switch (op) {
case "eq":
return actual === expected;
case "neq":
return actual !== expected;
case "gt":
return typeof actual === "number" && typeof expected === "number" && actual > expected;
case "gte":
return typeof actual === "number" && typeof expected === "number" && actual >= expected;
case "lt":
return typeof actual === "number" && typeof expected === "number" && actual < expected;
case "lte":
return typeof actual === "number" && typeof expected === "number" && actual <= expected;
case "in":
return Array.isArray(expected) && expected.includes(actual as never);
case "not_in":
return Array.isArray(expected) && !expected.includes(actual as never);
case "exists":
return actual !== undefined && actual !== null;
case "matches":
if (typeof actual !== "string" || typeof expected !== "string") return false;
try {
return new RegExp(expected).test(actual);
} catch {
return false;
}
case "length_gte":
if (!Array.isArray(actual) && typeof actual !== "string") return false;
return (actual as { length: number }).length >= (expected as number);
case "length_lte":
if (!Array.isArray(actual) && typeof actual !== "string") return false;
return (actual as { length: number }).length <= (expected as number);
default:
return false;
}
}
function isLeaf(c: Condition): c is LeafCondition {
return (c as LeafCondition).op !== undefined && (c as LeafCondition).path !== undefined;
}
export function evaluateCondition(
condition: Condition,
context: Record<string, unknown>,
): boolean {
if (isLeaf(condition)) {
const actual = getPath(context, condition.path);
return evalOp(condition.op, actual, condition.value);
}
if ("all" in condition) {
return condition.all.every((c) => evaluateCondition(c, context));
}
if ("any" in condition) {
return condition.any.some((c) => evaluateCondition(c, context));
}
if ("not" in condition) {
return !evaluateCondition(condition.not, context);
}
return false;
}
/* -----------------------------------------------------------------
* Public evaluate(): runs the full rule set and collects failures.
* --------------------------------------------------------------- */
export function evaluate(
ruleSet: RuleSet,
context: Record<string, unknown>,
): EvaluationResult {
const failures: RuleFailure[] = [];
for (const rule of ruleSet.rules) {
if (rule.when && !evaluateCondition(rule.when, context)) continue;
const passed = evaluateCondition(rule.assert, context);
if (!passed) {
failures.push({
ruleId: rule.id,
severity: rule.severity ?? "error",
message: rule.description ?? `rule ${rule.id} failed`,
path: isLeaf(rule.assert) ? rule.assert.path : undefined,
});
}
}
const blocking = failures.filter((f) => f.severity === "error");
return { ok: blocking.length === 0, failures };
}
/* -----------------------------------------------------------------
* Built-in rule sets. These mirror the pre-DSL hardcoded checks so
* callers can migrate incrementally.
* --------------------------------------------------------------- */
/** Preconditions check — arch §8 PRECONDITIONS_PENDING -> READY_FOR_PREPARE. */
export const BUILTIN_PRECONDITIONS: RuleSet = {
id: "preconditions.builtin",
version: "1",
rules: [
{
id: "plan.exists",
description: "plan must be present on the context",
assert: { path: "plan", op: "exists" },
},
{
id: "plan.steps.non_empty",
description: "plan must contain at least one step",
assert: { path: "plan.steps", op: "length_gte", value: 1 },
},
{
id: "plan.pay_step_present",
description: "plan must contain at least one pay step (ISO-20022 envelope)",
assert: {
any: [
{ path: "plan.steps[0].type", op: "eq", value: "pay" },
{ path: "plan.steps[1].type", op: "eq", value: "pay" },
{ path: "plan.steps[2].type", op: "eq", value: "pay" },
{ path: "plan.steps[3].type", op: "eq", value: "pay" },
],
},
},
{
id: "participants.at_least_one",
description: "participant registry must not be empty",
assert: { path: "participants", op: "length_gte", value: 1 },
},
{
id: "compliance.kyc_ok",
description: "compliance KYC status must be ok",
when: { path: "compliance", op: "exists" },
assert: { path: "compliance.kyc", op: "eq", value: "ok" },
},
],
};
/** Commit rule — arch §9.2. */
export const BUILTIN_COMMIT: RuleSet = {
id: "commit.builtin",
version: "1",
rules: [
{
id: "dlt.tx_hash",
description: "DLT leg must produce a 0x + 64-hex tx hash",
assert: { path: "dlt.txHash", op: "matches", value: "^0x[0-9a-fA-F]{64}$" },
},
{
id: "bank.iso_message_id",
description: "bank leg must produce a non-empty ISO message id",
assert: { path: "bank.isoMessageId", op: "exists" },
},
{
id: "state.is_validating",
description: "commit is only valid from VALIDATING",
assert: { path: "state", op: "eq", value: "VALIDATING" },
},
{
id: "no_exception_holds",
description: "no exception may be outstanding",
assert: { path: "exceptions.active", op: "length_lte", value: 0 },
},
],
};
/* -----------------------------------------------------------------
* Loader: RULES_FILE env points at a JSON file containing a map
* {ruleSetId: RuleSet}. Falls back to built-ins on any error.
* --------------------------------------------------------------- */
let cachedOverrides: Record<string, RuleSet> | undefined;
export function getRuleSet(id: string): RuleSet {
if (cachedOverrides === undefined) {
cachedOverrides = {};
const path = process.env.RULES_FILE;
if (path) {
try {
const raw = readFileSync(path, "utf8");
const parsed = JSON.parse(raw) as Record<string, RuleSet>;
if (parsed && typeof parsed === "object") cachedOverrides = parsed;
} catch {
// leave empty — silent fall-through to built-ins
}
}
}
if (cachedOverrides[id]) return cachedOverrides[id];
if (id === BUILTIN_PRECONDITIONS.id) return BUILTIN_PRECONDITIONS;
if (id === BUILTIN_COMMIT.id) return BUILTIN_COMMIT;
return { id, rules: [] };
}
export function __resetRulesCacheForTests(): void {
cachedOverrides = undefined;
}

View File

@@ -0,0 +1,187 @@
/**
* PR O — EIP-712 / JWS event signatures (gap-analysis v2 §7.5 / §10.5).
*
* Covers:
* - HMAC default mode (back-compat) — round-trip sign/verify
* - JWS compact mode — valid signature, payload-tamper detection,
* signature-tamper detection
* - EIP-712 mode — round-trip via ethers wallet, tamper detection
* - Mode switching via EVENT_SIGNING_MODE + getEventSigner()
* - legacyHmac helper preserves the pre-PR-O signature shape
*/
import { describe, it, expect, beforeEach, afterEach } from "@jest/globals";
import { ethers } from "ethers";
import {
getEventSigner,
resolveSigningMode,
legacyHmac,
__resetSignerForTests,
type EventSignInput,
} from "../../src/services/eventSigner";
const TEST_KEY = "0x" + "ab".repeat(32); // deterministic test wallet
function makeInput(overrides: Partial<EventSignInput> = {}): EventSignInput {
return {
planId: "plan-x",
type: "transaction.created",
payloadHash: "a".repeat(64),
prevHash: null,
...overrides,
};
}
describe("eventSigner — mode resolution", () => {
beforeEach(() => {
__resetSignerForTests();
delete process.env.EVENT_SIGNING_MODE;
delete process.env.ORCHESTRATOR_PRIVATE_KEY;
});
it("defaults to hmac when env var absent", () => {
expect(resolveSigningMode()).toBe("hmac");
expect(getEventSigner().mode).toBe("hmac");
});
it("honours eip712 / jws / hmac values", () => {
for (const mode of ["eip712", "jws", "hmac"] as const) {
__resetSignerForTests();
process.env.EVENT_SIGNING_MODE = mode;
expect(resolveSigningMode()).toBe(mode);
expect(getEventSigner().mode).toBe(mode);
}
});
it("falls through to hmac on unknown mode", () => {
process.env.EVENT_SIGNING_MODE = "bogus";
expect(resolveSigningMode()).toBe("hmac");
});
});
describe("eventSigner — HMAC round-trip", () => {
beforeEach(() => {
__resetSignerForTests();
process.env.EVENT_SIGNING_MODE = "hmac";
process.env.EVENT_BUS_HMAC_SECRET = "test-secret";
});
it("signs + verifies", async () => {
const signer = getEventSigner();
const input = makeInput();
const sig = await signer.sign(input);
expect(sig).toMatch(/^[0-9a-f]{64}$/);
expect(await signer.verify(input, sig)).toBe(true);
});
it("rejects a tampered payload hash", async () => {
const signer = getEventSigner();
const input = makeInput();
const sig = await signer.sign(input);
expect(
await signer.verify({ ...input, payloadHash: "b".repeat(64) }, sig),
).toBe(false);
});
it("legacyHmac produces the same hex as the HMAC signer", async () => {
const input = makeInput();
const sig = await getEventSigner().sign(input);
expect(legacyHmac(input)).toBe(sig);
});
});
describe("eventSigner — JWS compact", () => {
beforeEach(() => {
__resetSignerForTests();
process.env.EVENT_SIGNING_MODE = "jws";
process.env.EVENT_BUS_HMAC_SECRET = "jws-secret";
});
it("produces header.body.sig shape", async () => {
const sig = await getEventSigner().sign(makeInput());
expect(sig.split(".")).toHaveLength(3);
});
it("round-trips sign/verify", async () => {
const signer = getEventSigner();
const input = makeInput();
expect(await signer.verify(input, await signer.sign(input))).toBe(true);
});
it("rejects a different event being presented with a valid sig", async () => {
const signer = getEventSigner();
const signed = await signer.sign(makeInput());
expect(
await signer.verify(makeInput({ type: "transaction.aborted" }), signed),
).toBe(false);
});
it("rejects a truncated signature", async () => {
const signer = getEventSigner();
const sig = await signer.sign(makeInput());
expect(await signer.verify(makeInput(), sig.slice(0, -3))).toBe(false);
});
});
describe("eventSigner — EIP-712 (ethers wallet)", () => {
beforeEach(() => {
__resetSignerForTests();
process.env.EVENT_SIGNING_MODE = "eip712";
process.env.ORCHESTRATOR_PRIVATE_KEY = TEST_KEY;
process.env.CHAIN_138_CHAIN_ID = "138";
});
afterEach(() => {
delete process.env.ORCHESTRATOR_PRIVATE_KEY;
});
it("produces a 65-byte 0x-prefixed ECDSA signature", async () => {
const sig = await getEventSigner().sign(makeInput());
expect(sig).toMatch(/^0x[0-9a-fA-F]{130}$/);
});
it("verifies as the signing wallet", async () => {
const signer = getEventSigner();
const input = makeInput();
const sig = await signer.sign(input);
expect(await signer.verify(input, sig)).toBe(true);
// Recovered address should match the wallet derived from TEST_KEY.
const expectedAddress = new ethers.Wallet(TEST_KEY).address;
const recovered = ethers.verifyTypedData(
{
name: "CurrenciCombo",
version: "1",
chainId: 138,
verifyingContract:
process.env.NOTARY_REGISTRY_ADDRESS ??
"0x0000000000000000000000000000000000000000",
},
{
Event: [
{ name: "planId", type: "string" },
{ name: "eventType", type: "string" },
{ name: "payloadHash", type: "bytes32" },
{ name: "prevHash", type: "bytes32" },
],
},
{
planId: input.planId,
eventType: input.type,
payloadHash: `0x${input.payloadHash}`,
prevHash: "0x" + "0".repeat(64),
},
sig,
);
expect(recovered.toLowerCase()).toBe(expectedAddress.toLowerCase());
});
it("rejects a signature for a different event", async () => {
const signer = getEventSigner();
const sig = await signer.sign(makeInput());
// Valid signature but rebound to a different event → fails because
// the recovered address won't be our wallet.
expect(
await signer.verify(makeInput({ type: "transaction.committed" }), sig),
).toBe(false);
});
});

View File

@@ -1,245 +0,0 @@
/**
* PR P — Pluggable Rules Engine (gap-analysis v2 §5.2 partial).
*/
import { describe, it, expect, beforeEach } from "@jest/globals";
import {
evaluate,
evaluateCondition,
getRuleSet,
BUILTIN_PRECONDITIONS,
BUILTIN_COMMIT,
__resetRulesCacheForTests,
type RuleSet,
} from "../../src/services/rulesEngine";
describe("rulesEngine — primitive operators", () => {
it("eq / neq / gt / gte / lt / lte", () => {
expect(
evaluateCondition({ path: "a", op: "eq", value: 1 }, { a: 1 }),
).toBe(true);
expect(
evaluateCondition({ path: "a", op: "neq", value: 1 }, { a: 2 }),
).toBe(true);
expect(
evaluateCondition({ path: "a", op: "gt", value: 1 }, { a: 2 }),
).toBe(true);
expect(
evaluateCondition({ path: "a", op: "lte", value: 3 }, { a: 3 }),
).toBe(true);
});
it("in / not_in / exists / matches", () => {
expect(
evaluateCondition(
{ path: "role", op: "in", value: ["approver", "releaser"] },
{ role: "approver" },
),
).toBe(true);
expect(
evaluateCondition(
{ path: "role", op: "not_in", value: ["approver"] },
{ role: "operator" },
),
).toBe(true);
expect(
evaluateCondition({ path: "x", op: "exists" }, { x: 0 }),
).toBe(true);
expect(
evaluateCondition(
{ path: "hash", op: "matches", value: "^0x[0-9a-f]+$" },
{ hash: "0xabc" },
),
).toBe(true);
});
it("length_gte / length_lte work on arrays and strings", () => {
expect(
evaluateCondition({ path: "a", op: "length_gte", value: 2 }, { a: [1, 2] }),
).toBe(true);
expect(
evaluateCondition({ path: "a", op: "length_lte", value: 5 }, { a: "abcd" }),
).toBe(true);
});
it("dotted + indexed path resolution", () => {
expect(
evaluateCondition(
{ path: "plan.steps[1].type", op: "eq", value: "pay" },
{ plan: { steps: [{ type: "issue" }, { type: "pay" }] } },
),
).toBe(true);
});
});
describe("rulesEngine — combinators", () => {
const ctx = { role: "approver", amount: 1000 };
it("all (AND) — every child must pass", () => {
expect(
evaluateCondition(
{
all: [
{ path: "role", op: "eq", value: "approver" },
{ path: "amount", op: "gt", value: 500 },
],
},
ctx,
),
).toBe(true);
expect(
evaluateCondition(
{
all: [
{ path: "role", op: "eq", value: "approver" },
{ path: "amount", op: "gt", value: 5000 },
],
},
ctx,
),
).toBe(false);
});
it("any (OR) — at least one child must pass", () => {
expect(
evaluateCondition(
{
any: [
{ path: "role", op: "eq", value: "releaser" },
{ path: "amount", op: "gt", value: 500 },
],
},
ctx,
),
).toBe(true);
});
it("not — inverts the child", () => {
expect(
evaluateCondition(
{ not: { path: "role", op: "eq", value: "releaser" } },
ctx,
),
).toBe(true);
});
});
describe("rulesEngine — evaluate() and failure reporting", () => {
const ruleSet: RuleSet = {
id: "test.rs",
rules: [
{
id: "amount_positive",
description: "amount must be > 0",
assert: { path: "amount", op: "gt", value: 0 },
},
{
id: "role_listed",
description: "role must be in the allowed list",
assert: {
path: "role",
op: "in",
value: ["approver", "releaser", "operator"],
},
},
{
id: "warning_only",
description: "low amount warning",
severity: "warn",
assert: { path: "amount", op: "gte", value: 10_000 },
},
],
};
it("returns ok=true when all error-severity rules pass", () => {
const res = evaluate(ruleSet, { amount: 1000, role: "approver" });
expect(res.ok).toBe(true);
// warn still reported even though ok=true
expect(res.failures.some((f) => f.ruleId === "warning_only")).toBe(true);
expect(res.failures.every((f) => f.severity === "warn")).toBe(true);
});
it("returns ok=false with error failure when a blocking rule fails", () => {
const res = evaluate(ruleSet, { amount: -1, role: "approver" });
expect(res.ok).toBe(false);
const amountFail = res.failures.find((f) => f.ruleId === "amount_positive");
expect(amountFail?.severity).toBe("error");
});
it("'when' gates a rule — false when-clause skips the assert", () => {
const guarded: RuleSet = {
id: "guarded.rs",
rules: [
{
id: "kyc_if_present",
when: { path: "compliance", op: "exists" },
assert: { path: "compliance.kyc", op: "eq", value: "ok" },
},
],
};
expect(evaluate(guarded, {}).ok).toBe(true);
expect(evaluate(guarded, { compliance: { kyc: "ok" } }).ok).toBe(true);
expect(evaluate(guarded, { compliance: { kyc: "fail" } }).ok).toBe(false);
});
});
describe("rulesEngine — built-in rule sets", () => {
it("preconditions: pay step + non-empty participants passes", () => {
const res = evaluate(BUILTIN_PRECONDITIONS, {
plan: { steps: [{ type: "pay" }] },
participants: [{ id: "p1" }],
});
expect(res.ok).toBe(true);
});
it("preconditions: missing pay step fails", () => {
const res = evaluate(BUILTIN_PRECONDITIONS, {
plan: { steps: [{ type: "issueInstrument" }] },
participants: [{ id: "p1" }],
});
expect(res.ok).toBe(false);
expect(res.failures.some((f) => f.ruleId === "plan.pay_step_present")).toBe(
true,
);
});
it("commit: VALIDATING + matching refs + no exceptions passes", () => {
const res = evaluate(BUILTIN_COMMIT, {
state: "VALIDATING",
dlt: { txHash: `0x${"a".repeat(64)}` },
bank: { isoMessageId: "MSG-1" },
exceptions: { active: [] },
});
expect(res.ok).toBe(true);
});
it("commit: state != VALIDATING blocks", () => {
const res = evaluate(BUILTIN_COMMIT, {
state: "EXECUTING",
dlt: { txHash: `0x${"a".repeat(64)}` },
bank: { isoMessageId: "MSG-1" },
exceptions: { active: [] },
});
expect(res.ok).toBe(false);
expect(res.failures.some((f) => f.ruleId === "state.is_validating")).toBe(
true,
);
});
});
describe("rulesEngine — pluggable loading", () => {
beforeEach(() => {
__resetRulesCacheForTests();
delete process.env.RULES_FILE;
});
it("returns built-ins when RULES_FILE is unset", () => {
expect(getRuleSet(BUILTIN_PRECONDITIONS.id).rules.length).toBeGreaterThan(0);
expect(getRuleSet(BUILTIN_COMMIT.id).rules.length).toBeGreaterThan(0);
});
it("returns an empty rule set for unknown ids (no throw)", () => {
const rs = getRuleSet("nonexistent");
expect(rs.rules).toEqual([]);
});
});