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.
303 lines
10 KiB
TypeScript
303 lines
10 KiB
TypeScript
/**
|
|
* 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");
|
|
}
|