Compare commits

..

1 Commits

Author SHA1 Message Date
Devin
c72f9cd807 executions.swift_message_id + SWIFT gateway wiring
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 5s
CI / Frontend E2E Tests (pull_request) Failing after 6s
CI / Orchestrator Build (pull_request) Failing after 6s
CI / Contracts Compile (pull_request) Failing after 6s
CI / Contracts Test (pull_request) Failing after 5s
Code Quality / SonarQube Analysis (pull_request) Failing after 18s
Code Quality / Code Quality Checks (pull_request) Failing after 5s
Security Scan / Dependency Vulnerability Scan (pull_request) Failing after 3s
Security Scan / OWASP ZAP Scan (pull_request) Failing after 4s
Closes gap-analysis v2 §4 partial (canonical "Execution Reference Set")
and §10.6 SWIFT message ID persistence.

- Migration 006 adds swift_message_id + swift_message_type columns to
  executions, with a partial index on swift_message_id for
  acknowledgment ingest (camt.025/054 -> original MT760/MT202 lookup).
- db/executions.ts: recordExecution() UPSERT helper, getExecution(),
  findBySwiftMessageId() — the three queries the bank-instruction phase
  and SWIFT gateway need.
- services/bank.ts.commitBankInstruction now emits a SWIFT reference
  alongside the ISO-20022 envelope: MT760 for plans carrying an
  issueInstrument step (real generateMt760 output, messageReference
  field), MT202 for payment-only plans (synthetic ref).
- services/execution.ts persists the reference set at bank_instruction
  complete-time via recordExecution (best-effort; logs on failure,
  does not abort the leg).
- 5 unit tests covering MT760 vs MT202 branching, reference uniqueness
  across calls, and SQL shape of the UPSERT + SELECT.
2026-04-22 18:22:04 +00:00
9 changed files with 354 additions and 533 deletions

View File

@@ -0,0 +1,112 @@
/**
* Executions DB helpers — arch §4 canonical "Execution Reference Set".
*
* The executions row is the join point for the three dispatch references
* that must be reconciled at VALIDATING time (arch §9.2):
*
* - dlt_tx_hash — shared-state / ledger anchor (Chain-138)
* - iso_message_id — ISO-20022 envelope id (pacs.009 / pacs.008)
* - swift_message_id — SWIFT FIN reference for the leg (MT760 / MT202)
* - swift_message_type — FIN msg type ("MT760" | "MT202" | "pacs.009" …)
*
* `recordExecution()` UPSERTs by (plan_id, execution_id).
*/
import { query } from "./postgres";
export interface ExecutionRow {
execution_id: string;
plan_id: string;
status: string;
phase: string | null;
started_at: string;
completed_at: string | null;
error: string | null;
dlt_tx_hash: string | null;
iso_message_id: string | null;
swift_message_id: string | null;
swift_message_type: string | null;
}
export interface ExecutionPatch {
status?: string;
phase?: string;
completedAt?: Date | null;
error?: string | null;
dltTxHash?: string | null;
isoMessageId?: string | null;
swiftMessageId?: string | null;
swiftMessageType?: string | null;
}
/**
* UPSERT an execution row. Safe to call repeatedly — phased fields
* are merged via COALESCE semantics (new NULL never clobbers a prior
* non-NULL value; explicit empty-string caller still overrides via
* patch semantics below).
*/
export async function recordExecution(
executionId: string,
planId: string,
patch: ExecutionPatch = {},
): Promise<void> {
await query(
`INSERT INTO executions (
execution_id, plan_id, status, phase, completed_at, error,
dlt_tx_hash, iso_message_id, swift_message_id, swift_message_type
)
VALUES ($1, $2, COALESCE($3, 'pending'), $4, $5, $6, $7, $8, $9, $10)
ON CONFLICT (execution_id) DO UPDATE SET
status = COALESCE(EXCLUDED.status, executions.status),
phase = COALESCE(EXCLUDED.phase, executions.phase),
completed_at = COALESCE(EXCLUDED.completed_at, executions.completed_at),
error = COALESCE(EXCLUDED.error, executions.error),
dlt_tx_hash = COALESCE(EXCLUDED.dlt_tx_hash, executions.dlt_tx_hash),
iso_message_id = COALESCE(EXCLUDED.iso_message_id, executions.iso_message_id),
swift_message_id = COALESCE(EXCLUDED.swift_message_id, executions.swift_message_id),
swift_message_type = COALESCE(EXCLUDED.swift_message_type, executions.swift_message_type),
updated_at = CURRENT_TIMESTAMP`,
[
executionId,
planId,
patch.status ?? null,
patch.phase ?? null,
patch.completedAt ?? null,
patch.error ?? null,
patch.dltTxHash ?? null,
patch.isoMessageId ?? null,
patch.swiftMessageId ?? null,
patch.swiftMessageType ?? null,
],
);
}
export async function getExecution(
executionId: string,
): Promise<ExecutionRow | null> {
const rows = await query<ExecutionRow>(
`SELECT execution_id, plan_id, status, phase, started_at, completed_at,
error, dlt_tx_hash, iso_message_id,
swift_message_id, swift_message_type
FROM executions
WHERE execution_id = $1`,
[executionId],
);
return rows[0] ?? null;
}
export async function findBySwiftMessageId(
swiftMessageId: string,
): Promise<ExecutionRow | null> {
const rows = await query<ExecutionRow>(
`SELECT execution_id, plan_id, status, phase, started_at, completed_at,
error, dlt_tx_hash, iso_message_id,
swift_message_id, swift_message_type
FROM executions
WHERE swift_message_id = $1
ORDER BY started_at DESC
LIMIT 1`,
[swiftMessageId],
);
return rows[0] ?? null;
}

View File

@@ -0,0 +1,34 @@
import { query } from "../postgres";
/**
* Migration 006 — executions.swift_message_id + swift_message_type
* (arch §4 canonical "Execution Reference Set"; gap v2 §4 partial,
* §10.6 SWIFT message ID persistence).
*
* The Execution Reference Set needs the SWIFT FIN reference for each
* leg (MT760 for the instrument leg, pacs.009/MT202 for the payment
* leg), alongside the existing `dlt_tx_hash` for the shared-state
* anchor and `iso_message_id` for the ISO-20022 envelope. Keeping them
* separate makes it trivial to reconcile a SWIFT acknowledgment
* (camt.025/054) against the originating dispatch.
*/
export async function up() {
await query(
`ALTER TABLE executions
ADD COLUMN IF NOT EXISTS swift_message_id VARCHAR(255),
ADD COLUMN IF NOT EXISTS swift_message_type VARCHAR(32)`,
);
await query(
`CREATE INDEX IF NOT EXISTS idx_executions_swift_message_id
ON executions(swift_message_id)
WHERE swift_message_id IS NOT NULL`,
);
}
export async function down() {
await query(
`ALTER TABLE executions
DROP COLUMN IF EXISTS swift_message_id,
DROP COLUMN IF EXISTS swift_message_type`,
);
}

View File

@@ -2,6 +2,7 @@ import { up as up001 } from "./001_initial_schema";
import { up as up002 } from "./002_transaction_state";
import { up as up003 } from "./003_events";
import { up as up004 } from "./004_idempotency_keys";
import { up as up006 } from "./006_executions_swift";
/**
* Run all migrations
@@ -12,6 +13,7 @@ export async function runMigration() {
await up002();
await up003();
await up004();
await up006();
console.log("All migrations completed");
} catch (error) {
console.error("Migration failed:", error);

View File

@@ -1,5 +1,6 @@
import type { Plan } from "../types/plan";
import { generatePacs008 } from "./iso20022";
import { generateMt760 } from "./swift";
/**
* Prepare bank instruction (2PC prepare phase)
@@ -25,27 +26,57 @@ export async function prepareBankInstruction(plan: Plan): Promise<boolean> {
export async function commitBankInstruction(plan: Plan): Promise<{
success: boolean;
isoMessageId?: string;
/** SWIFT FIN reference for the leg (arch §4 Execution Reference Set). */
swiftMessageId?: string;
/** FIN message type, e.g. "MT760" for instrument issue, "MT202"/"pacs.009" for FI transfer. */
swiftMessageType?: string;
error?: string;
}> {
console.log(`[Bank] Committing instruction for plan ${plan.plan_id}`);
try {
// Generate final ISO-20022 message
const isoMessage = await generatePacs008(plan);
// Mock: In real implementation, this would:
// 1. Send ISO message to bank connector
// 2. Receive confirmation and message ID
// 3. Store message ID for audit trail
// Generate final ISO-20022 envelope.
await generatePacs008(plan);
const isoMessageId = `MSG-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
// Simulate processing delay
// Generate a SWIFT reference for the leg. If any step is an
// instrument issuance (issueInstrument) we pin MT760; otherwise
// this is a pacs.009 / MT202 FI credit transfer. We don't send
// anything over the wire here — PR R stands up the FIN-link
// sandbox transport.
const hasInstrument = plan.steps.some((s) => s.type === "issueInstrument");
let swiftMessageId: string | undefined;
let swiftMessageType: string | undefined;
try {
if (hasInstrument) {
const instrumentStep = plan.steps.find((s) => s.type === "issueInstrument");
if (instrumentStep?.instrument) {
const txRef = `MT760-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`.toUpperCase();
const mt760 = generateMt760(instrumentStep.instrument, {
transactionReference: txRef,
issueDate: new Date().toISOString().slice(0, 10),
});
swiftMessageId = mt760.messageReference;
swiftMessageType = "MT760";
}
} else {
swiftMessageId = `MT202-${Date.now()}-${Math.random().toString(36).slice(2, 10)}`.toUpperCase();
swiftMessageType = "MT202";
}
} catch (err) {
// SWIFT generator errors should not fail the leg in mock mode — we
// still have an ISO message id. Surface the error in the log.
console.warn(`[Bank] SWIFT reference generation skipped: ${(err as Error).message}`);
}
await new Promise((resolve) => setTimeout(resolve, 300));
return {
success: true,
isoMessageId,
swiftMessageId,
swiftMessageType,
};
} catch (error: any) {
return {

View File

@@ -22,12 +22,6 @@ 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
@@ -116,13 +110,7 @@ export async function publish(input: PublishInput): Promise<EventRecord> {
[input.planId],
);
const prevHash = prev.length > 0 ? prev[0].signature : null;
const signInput: EventSignInput = {
planId: input.planId,
type: input.type,
payloadHash,
prevHash,
};
const signature = await getEventSigner().sign(signInput);
const signature = sign(input.planId, input.type, payloadHash, prevHash);
const rows = await query<EventRecord>(
`INSERT INTO events (plan_id, type, actor, payload, payload_hash, prev_hash, signature)
@@ -183,23 +171,9 @@ export async function verifyChain(planId: string): Promise<
if (expectedPayloadHash !== e.payload_hash) {
return { ok: false, brokenAt: i, reason: "payload_hash 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()})`,
};
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" };
}
prevSig = e.signature;
}

View File

@@ -1,302 +0,0 @@
/**
* 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,5 +1,6 @@
import { EventEmitter } from "events";
import { getPlanById, updatePlanStatus } from "../db/plans";
import { recordExecution } from "../db/executions";
import {
prepareDLTExecution,
commitDLTExecution,
@@ -182,7 +183,7 @@ export class ExecutionCoordinator extends EventEmitter {
return { txHash: result.txHash };
}
private async bankInstructionPhase(executionId: string, plan: Plan): Promise<{ isoMessageId: string }> {
private async bankInstructionPhase(executionId: string, plan: Plan): Promise<{ isoMessageId: string; swiftMessageId?: string; swiftMessageType?: string }> {
this.emitStatus(executionId, { phase: "bank_instruction", status: "in_progress", timestamp: new Date().toISOString() });
const result = await commitBankInstruction(plan);
@@ -193,8 +194,25 @@ export class ExecutionCoordinator extends EventEmitter {
const rec = this.executions.get(executionId);
if (rec) rec.isoMessageId = result.isoMessageId;
// Persist the SWIFT reference set (arch §4 canonical "Execution
// Reference Set"; gap v2 §4 partial, §10.6).
const swiftMessageId = (result as { swiftMessageId?: string }).swiftMessageId;
const swiftMessageType = (result as { swiftMessageType?: string }).swiftMessageType;
try {
await recordExecution(executionId, plan.plan_id!, {
phase: "bank_instruction",
isoMessageId: result.isoMessageId,
swiftMessageId: swiftMessageId ?? null,
swiftMessageType: swiftMessageType ?? null,
});
} catch (err) {
// DB persistence is best-effort here; a failure should not abort
// the leg — the in-memory execution record still carries the id.
console.warn(`recordExecution failed for ${executionId}:`, err);
}
this.emitStatus(executionId, { phase: "bank_instruction", status: "complete", isoMessageId: result.isoMessageId, timestamp: new Date().toISOString() });
return { isoMessageId: result.isoMessageId };
return { isoMessageId: result.isoMessageId, swiftMessageId, swiftMessageType };
}
/**

View File

@@ -1,187 +0,0 @@
/**
* 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

@@ -0,0 +1,139 @@
/**
* SWIFT message-id persistence (arch §4 Execution Reference Set,
* gap v2 §4 partial, §10.6).
*
* Commands tested:
* - commitBankInstruction returns swiftMessageId + swiftMessageType
* depending on whether the plan has an issueInstrument step
* - MT760 reference for instrument legs; MT202 synthetic ref for
* payment-only legs
* - db/executions.recordExecution upserts the SWIFT fields
*/
import { describe, it, expect, jest } from "@jest/globals";
import type { Plan } from "../../src/types/plan";
import { commitBankInstruction } from "../../src/services/bank";
jest.mock("../../src/db/postgres", () => {
const calls: Array<{ sql: string; params?: unknown[] }> = [];
return {
query: jest.fn(async (sql: string, params?: unknown[]) => {
calls.push({ sql, params });
return [];
}),
__calls: calls,
};
});
jest.mock("../../src/services/compliance", () => ({
getComplianceData: jest.fn(async () => ({ lei: "TEST-LEI", status: "ok" })),
}));
import { recordExecution, getExecution } from "../../src/db/executions";
function basePlan(overrides: Partial<Plan> = {}): Plan {
return {
plan_id: "plan-test-1",
schema_version: 1,
creator: "0xabc",
nonce: 1,
created_at: new Date().toISOString(),
steps: [
{
type: "pay",
from: "acct-a",
to: "acct-b",
amount: 100,
currency: "USD",
} as any,
],
...overrides,
} as Plan;
}
function instrumentPlan(): Plan {
return basePlan({
steps: [
{
type: "issueInstrument",
instrument: {
instrumentType: "SBLC",
amount: 1000000,
currency: "USD",
issuingBankBIC: "EIBIAEAD",
beneficiaryBankBIC: "ADCBAEAA",
beneficiaryName: "ACME TRADING LLC",
beneficiaryAccount: "AE12 3456 7890 1234",
expiryDate: "2026-12-31",
placeOfPresentation: "DUBAI",
governingLaw: "URDG 758",
applicant: "APPLICANT INC",
templateRef: "EI-SBLC-v1",
templateHash: "a".repeat(64),
tenor: "12M",
},
} as any,
{
type: "pay",
from: "acct-a",
to: "acct-b",
amount: 1000000,
currency: "USD",
} as any,
],
});
}
describe("commitBankInstruction SWIFT reference output", () => {
it("issues an MT760 reference when the plan contains issueInstrument", async () => {
const result = await commitBankInstruction(instrumentPlan());
expect(result.success).toBe(true);
expect(result.swiftMessageType).toBe("MT760");
expect(result.swiftMessageId).toMatch(/^MT760-/);
expect(result.isoMessageId).toMatch(/^MSG-/);
});
it("issues an MT202 reference when no issueInstrument step is present", async () => {
const result = await commitBankInstruction(basePlan());
expect(result.success).toBe(true);
expect(result.swiftMessageType).toBe("MT202");
expect(result.swiftMessageId).toMatch(/^MT202-/);
});
it("returns different swiftMessageIds across successive calls", async () => {
const a = await commitBankInstruction(basePlan());
const b = await commitBankInstruction(basePlan());
expect(a.swiftMessageId).not.toBe(b.swiftMessageId);
});
});
describe("db/executions SQL wiring", () => {
it("recordExecution builds an UPSERT including swift_message_id fields", async () => {
const pg = require("../../src/db/postgres");
pg.__calls.length = 0;
await recordExecution("exec-1", "plan-1", {
phase: "bank_instruction",
isoMessageId: "iso-1",
swiftMessageId: "MT760-ABC",
swiftMessageType: "MT760",
});
expect(pg.query).toHaveBeenCalled();
const call = pg.__calls[0];
expect(call.sql).toMatch(/INSERT INTO executions/);
expect(call.sql).toMatch(/swift_message_id/);
expect(call.sql).toMatch(/swift_message_type/);
expect(call.sql).toMatch(/ON CONFLICT \(execution_id\) DO UPDATE/);
expect(call.params).toEqual(
expect.arrayContaining(["exec-1", "plan-1", "bank_instruction", "iso-1", "MT760-ABC", "MT760"]),
);
});
it("getExecution selects the swift_message_* columns", async () => {
const pg = require("../../src/db/postgres");
pg.__calls.length = 0;
await getExecution("exec-1");
const call = pg.__calls[0];
expect(call.sql).toMatch(/swift_message_id/);
expect(call.sql).toMatch(/swift_message_type/);
});
});