Home / Reference implementations / Governed webhook
Governed webhook
Draft
Illustrative reference — annotated, runnable code against the Draft contracts. Not a production implementation (in-memory store, fixed local secret, no rate limiting).
An HTTP webhook receiver that runs every inbound event through all six stages of the execution chain. One file, Node.js standard library only. Used by the quickstart.
How the code maps to the chain
verifySignature— identity material (stage 3 begins at the edge)validateContract— stage 1: contractsTENANT— stage 2: tenant boundary (fixed local scope)evaluatePolicy— stage 4: deterministic policyexecuteGoverned— stage 5: governed actionissueReceipt— stage 6: evidence
Illustrative referencegoverned-webhook.js — save as one file and run with
node governed-webhook.js.// Illustrative reference: governed webhook receiver (Node.js, stdlib only).
// Runs every inbound event through the AmetiOS execution chain.
const http = require("node:http");
const crypto = require("node:crypto");
// --- Local configuration (fixed for local runs; never hardcode secrets in production) ---
const LOCAL_SECRET = "local-dev-secret";
const PORT = 8787;
const TENANT = { organization: "org_local", workspace: "ws_dev", environment: "staging" };
const ACTOR = { actor_id: "svc_webhook", actor_class: "service" };
// --- Stage 4: deterministic policy bundle (deny by default) ---
const POLICY_BUNDLE = {
bundle: "webhook-default",
version: "0.1.0",
rules: [
{
id: "deny-large-refunds",
priority: 100,
match: { "action.schema": "billing.refund.request", "inputs.amount_cents": { gte: 100000 } },
effect: "deny",
},
{
id: "approve-refunds",
priority: 90,
match: { "action.schema": "billing.refund.request" },
effect: "require-approval",
approval: { roles: ["billing-approver"], expires_after_minutes: 240 },
},
{
id: "allow-invoice-events",
priority: 50,
match: { "action.schema": "billing.invoice.paid" },
effect: "allow",
},
],
};
// --- Stage 1: contracts — event name to action schema mapping ---
const EVENT_SCHEMAS = {
"invoice.paid": { schema: "billing.invoice.paid", schema_version: "1.0.0", required: ["customer_id", "amount_cents"] },
"refund.requested": { schema: "billing.refund.request", schema_version: "1.0.0", required: ["customer_id", "amount_cents"] },
};
// --- Helpers ---
function sha256Hex(text) {
return crypto.createHash("sha256").update(text, "utf8").digest("hex");
}
function canonicalize(value) {
if (Array.isArray(value)) return "[" + value.map(canonicalize).join(",") + "]";
if (value !== null && typeof value === "object") {
const keys = Object.keys(value).sort();
return "{" + keys.map((k) => JSON.stringify(k) + ":" + canonicalize(value[k])).join(",") + "}";
}
return JSON.stringify(value);
}
function verifySignature(rawBody, signature) {
const expected = crypto.createHmac("sha256", LOCAL_SECRET).update(rawBody).digest("hex");
if (typeof signature !== "string" || signature.length !== expected.length) return false;
return crypto.timingSafeEqual(Buffer.from(signature, "utf8"), Buffer.from(expected, "utf8"));
}
function validateContract(event) {
const def = EVENT_SCHEMAS[event.event];
if (!def) return { ok: false, error: "unknown_event", message: "No contract registered for event '" + event.event + "'." };
const missing = def.required.filter((f) => event[f] === undefined);
if (missing.length > 0) return { ok: false, error: "schema_violation", message: "Missing fields: " + missing.join(", ") };
return { ok: true, schema: def.schema, schema_version: def.schema_version };
}
function getPath(obj, path) {
return path.split(".").reduce((acc, key) => (acc == null ? undefined : acc[key]), obj);
}
function conditionHolds(actual, expected) {
if (expected !== null && typeof expected === "object") {
if ("gte" in expected) return typeof actual === "number" && actual >= expected.gte;
return false;
}
return actual === expected;
}
function evaluatePolicy(proposal) {
const rules = [...POLICY_BUNDLE.rules].sort((a, b) => b.priority - a.priority);
const evaluated = [];
for (const rule of rules) {
const matched = Object.entries(rule.match).every(([path, expected]) =>
conditionHolds(getPath(proposal, path), expected)
);
evaluated.push({ rule: rule.id, matched });
if (matched) {
return {
decision: rule.effect,
approval: rule.approval || null,
trace: { bundle: POLICY_BUNDLE.bundle, version: POLICY_BUNDLE.version, evaluated, matched_rule: rule.id },
};
}
}
return { decision: "deny", approval: null, trace: { bundle: POLICY_BUNDLE.bundle, version: POLICY_BUNDLE.version, evaluated } };
}
// --- Stage 6: evidence — in-memory receipt chain (one chain for the local tenant) ---
const receiptChain = [];
function issueReceipt(fields) {
const prev = receiptChain.length > 0 ? receiptChain[receiptChain.length - 1].receipt_hash : null;
const body = {
receipt_id: "rcpt_" + crypto.randomBytes(8).toString("hex"),
receipt_format: "ametios.receipt/v1",
tenant: TENANT,
actor: ACTOR,
policy_bundle: POLICY_BUNDLE.bundle,
policy_version: POLICY_BUNDLE.version,
prev_receipt_hash: prev,
...fields,
};
body.receipt_hash = sha256Hex(canonicalize(body));
receiptChain.push(body);
return body;
}
// --- Stage 5: governed execution (the only place effects happen) ---
function executeGoverned(proposal) {
const startedAt = new Date().toISOString();
// Effect: record the invoice/refund event. In production this would be a
// transaction against the ledger; here we record a deterministic result.
const outputs = { recorded: true, schema: proposal.action.schema, at: startedAt };
const finishedAt = new Date().toISOString();
return { outputs, startedAt, finishedAt };
}
// --- HTTP server ---
const server = http.createServer((req, res) => {
if (req.method !== "POST" || req.url !== "/webhook") {
res.writeHead(404, { "content-type": "application/json" });
res.end(JSON.stringify({ error: { code: "not_found", message: "POST /webhook only." } }));
return;
}
let raw = "";
req.on("data", (chunk) => { raw += chunk; });
req.on("end", () => {
const send = (status, obj) => {
res.writeHead(status, { "content-type": "application/json" });
res.end(JSON.stringify(obj));
};
// Edge: identity material (stage 3) — reject unsigned requests.
if (!verifySignature(raw, req.headers["x-signature"])) {
return send(401, { error: { code: "bad_signature", message: "Missing or invalid X-Signature." } });
}
let event;
try {
event = JSON.parse(raw);
} catch {
return send(400, { error: { code: "bad_json", message: "Request body is not valid JSON." } });
}
// Stage 1: contracts.
const contract = validateContract(event);
if (!contract.ok) {
return send(400, { error: { code: contract.error, message: contract.message } });
}
// Stages 2+3: fixed local tenant boundary and verified service actor.
const proposal = {
action_id: "act_" + crypto.randomBytes(8).toString("hex"),
action: { schema: contract.schema, schema_version: contract.schema_version },
tenant: TENANT,
actor: ACTOR,
inputs: event,
};
// Stage 4: deterministic policy.
const { decision, approval, trace } = evaluatePolicy(proposal);
if (decision === "deny") {
const receipt = issueReceipt({
action_id: proposal.action_id,
action_schema: contract.schema,
schema_version: contract.schema_version,
inputs_hash: sha256Hex(canonicalize(event)),
decision: "deny",
evaluation_trace: trace,
approval: null,
outputs_hash: null,
expectations: { expected_value_cents: 0, expected_cost_cents: 0, risk_tier: "low" },
actuals: { actual_value_cents: 0, actual_cost_cents: 0, risk_tier: "low" },
started_at: new Date().toISOString(),
finished_at: new Date().toISOString(),
});
const deniedBy = trace.matched_rule
? "Denied by rule '" + trace.matched_rule + "'."
: "Denied: no rule matched (deny by default).";
return send(403, { error: { code: "policy_denied", message: deniedBy }, receipt });
}
if (decision === "require-approval") {
// Parked for a human; see the approval-inbox reference for the gate.
return send(202, {
action_id: proposal.action_id,
decision: "require-approval",
approval: { roles: approval.roles, expires_after_minutes: approval.expires_after_minutes },
note: "No human inbox is wired in this reference; approvals are out of scope here.",
});
}
// Stage 5: governed execution.
const { outputs, startedAt, finishedAt } = executeGoverned(proposal);
// Stage 6: evidence.
const receipt = issueReceipt({
action_id: proposal.action_id,
action_schema: contract.schema,
schema_version: contract.schema_version,
inputs_hash: sha256Hex(canonicalize(event)),
decision: "allow",
evaluation_trace: trace,
approval: null,
outputs_hash: sha256Hex(canonicalize(outputs)),
expectations: { expected_value_cents: event.amount_cents || 0, expected_cost_cents: 1, risk_tier: "low" },
actuals: { actual_value_cents: event.amount_cents || 0, actual_cost_cents: 1, risk_tier: "low" },
started_at: startedAt,
finished_at: finishedAt,
});
return send(200, { action_id: proposal.action_id, decision: "allow", receipt });
});
});
server.listen(PORT, "127.0.0.1", () => {
console.log("governed webhook listening on http://localhost:" + PORT);
});
Try it: the quickstart runs this file end to end. Next: approval inbox for the require-approval path, evidence receipt for issuance and verification detail.