Appearance
webhook.receive: TypeScript + Fastify
The endpoint OneHazel delivers events to. Acknowledge fast, deduplicate on deliveryId, process after acknowledging.
Generated from Operator Contract v1.4.1. Key typescript/fastify/webhook.receive; the connect_samples MCP tool returns this page for that key.
What it implements
| Operation | Purpose | Idempotency key |
|---|---|---|
POST /webhook | Receive a OneHazel event. | no |
Every delivery is checked before it is parsed: X-OneHazel-Signature is sha256=<hex>, HMAC-SHA256 of the RAW body keyed by the subscription's whsec_ signing secret, compared in constant time. There is no timestamp, no bearer and no X-OneHazel-Env, so the signature is the only proof of origin and deduplicating on deliveryId is the only replay defence. A bad signature answers 401 with the flat { code, message, retryable } envelope.
Run it
bash
npm install fastify
npm install --save-dev tsx @types/node
ONEHAZEL_SIGNING_SECRET=<whsec signing secret> npx tsx onehazel-webhook-receive.ts
# base URL to register: https://<your host>/onehazel/v1 (ONEHAZEL_BASE_PATH changes the path)Environment: ONEHAZEL_SIGNING_SECRET is the subscription's whsec_ signing secret. During a rotation set ONEHAZEL_SIGNING_SECRET_PREVIOUS to the old one until it stops being used.
Code
onehazel-webhook-receive.ts
ts
import Fastify from "fastify";
import { createHash, createHmac, randomUUID, timingSafeEqual } from "node:crypto";
// Generated from the OneHazel Operator Contract v1.4.1: operations, request fields,
// error codes with their HTTP status, and the signature tolerance. Do not hand-edit; regenerate.
const CONTRACT = {
"version": "1.4.1",
"auth": {
"scheme": "sha256",
"bearer": false,
"envHeader": false
},
"errorStatus": {
"unauthorized": 401,
"signature_invalid": 401,
"idempotency_key_conflict": 409,
"launch_token_consumed": 409,
"round_closed": 409,
"currency_unsupported": 422,
"currency_mismatch": 422,
"player_blocked": 422,
"rollback_amount_mismatch": 422,
"insufficient_funds": 402,
"internal_error": 500,
"unavailable": 500,
"invalid_request": 400,
"session_unknown": 404,
"session_expired": 404,
"launch_token_unknown": 404,
"launch_token_expired": 404,
"player_unknown": 404,
"game_unknown": 404,
"transaction_unknown": 404,
"freeround_unknown": 404
},
"retryable": [
"internal_error",
"unavailable"
],
"ops": [
{
"path": "/webhook",
"operationId": "webhookReceive",
"summary": "Receive a OneHazel event.",
"idempotent": false,
"fields": [
{
"name": "type",
"type": "string",
"required": true
},
{
"name": "data",
"type": "object",
"required": true
},
{
"name": "operatorId",
"type": "string",
"required": true
},
{
"name": "timestamp",
"type": "string",
"required": true
},
{
"name": "deliveryId",
"type": "string",
"required": true
}
],
"closed": false
}
]
} as const;
// ───────────────────────────── configuration ─────────────────────────────
function requiredEnv(name: string): string {
const value = process.env[name];
if (!value) {
// Never print the value of a secret, only its name.
console.error(`${name} is not set`);
process.exit(1);
}
return value;
}
// During a rotation OneHazel signs with the new secret; the old one stays valid for 1 hour.
const SIGNING_SECRETS = [requiredEnv("ONEHAZEL_SIGNING_SECRET"), process.env.ONEHAZEL_SIGNING_SECRET_PREVIOUS]
.filter((s): s is string => Boolean(s));
const PORT = Number(process.env.PORT ?? "3000");
const BASE_PATH = (process.env.ONEHAZEL_BASE_PATH ?? "/onehazel/v1").replace(/\/+$/, "");
// ───────────────────────────── errors ─────────────────────────────
type ErrorCode = keyof typeof CONTRACT.errorStatus;
interface Reply {
status: number;
body: unknown;
}
/** Thrown anywhere in a handler; becomes the flat `{ code, message, retryable }` envelope. */
class ContractError extends Error {
constructor(public readonly code: ErrorCode, message: string) {
super(message);
}
}
function errorReply(code: ErrorCode, message: string): Reply {
return {
status: CONTRACT.errorStatus[code],
body: { code, message, retryable: (CONTRACT.retryable as readonly string[]).includes(code) },
};
}
// ───────────────────────────── request authentication ─────────────────────────────
type HeaderGetter = (name: string) => string | undefined;
function constantTimeEqual(a: string, b: string): boolean {
const ab = Buffer.from(a);
const bb = Buffer.from(b);
// Compare against itself on a length mismatch so the timing does not reveal the length.
return ab.length === bb.length ? timingSafeEqual(ab, bb) : (timingSafeEqual(ab, ab), false);
}
// ───────────────────────────── request validation ─────────────────────────────
type Body = Record<string, unknown>;
interface Field {
readonly name: string;
readonly type: string;
readonly required: boolean;
readonly minimum?: number;
readonly exclusiveMinimum?: number;
readonly minLength?: number;
readonly maxLength?: number;
readonly pattern?: string;
readonly enum?: readonly string[];
readonly fields?: readonly Field[];
}
function checkFields(value: unknown, fields: readonly Field[], closed: boolean, where: string): Body {
if (typeof value !== "object" || value === null || Array.isArray(value)) {
throw new ContractError("invalid_request", `${where || "body"} must be a JSON object`);
}
const obj = value as Body;
if (closed) {
for (const key of Object.keys(obj)) {
if (!fields.some((f) => f.name === key)) throw new ContractError("invalid_request", `unknown field ${where}${key}`);
}
}
for (const f of fields) {
const v = obj[f.name];
const name = `${where}${f.name}`;
if (v === undefined || v === null) {
if (f.required) throw new ContractError("invalid_request", `${name} is required`);
continue;
}
const ok =
f.type === "integer" ? Number.isSafeInteger(v)
: f.type === "array" ? Array.isArray(v)
: f.type === "object" ? typeof v === "object" && !Array.isArray(v)
: typeof v === f.type;
if (!ok) throw new ContractError("invalid_request", `${name} must be ${f.type}`);
if (typeof v === "number") {
if (f.minimum !== undefined && v < f.minimum) throw new ContractError("invalid_request", `${name} is below ${f.minimum}`);
if (f.exclusiveMinimum !== undefined && v <= f.exclusiveMinimum) {
throw new ContractError("invalid_request", `${name} must be greater than ${f.exclusiveMinimum}`);
}
}
if (typeof v === "string") {
if (f.minLength !== undefined && v.length < f.minLength) throw new ContractError("invalid_request", `${name} is too short`);
if (f.maxLength !== undefined && v.length > f.maxLength) throw new ContractError("invalid_request", `${name} is too long`);
if (f.pattern !== undefined && !new RegExp(f.pattern).test(v)) throw new ContractError("invalid_request", `${name} is malformed`);
if (f.enum !== undefined && !f.enum.includes(v)) throw new ContractError("invalid_request", `${name} is not an allowed value`);
}
if (f.fields) checkFields(v, f.fields, false, `${name}.`);
}
return obj;
}
function parseBody(rawBody: Buffer): unknown {
try {
return JSON.parse(rawBody.toString("utf8"));
} catch {
throw new ContractError("invalid_request", "body is not valid JSON");
}
}
// ───────────────────────────── delivery authentication ─────────────────────────────
//
// Deliveries carry `X-OneHazel-Signature: sha256=<hex HMAC-SHA256(whsec, raw body)>`, the
// OneHazel webhook engine's format. There is no timestamp, no bearer and no X-OneHazel-Env,
// so the signature is the only proof of origin and deduplicating on deliveryId is the only
// replay defence. Verify over the RAW bytes, before the body is parsed.
function verifyWebhookSignature(rawBody: Buffer, header: string | undefined, secrets: string[]): boolean {
const match = /^sha256=([0-9a-f]{64})$/.exec((header ?? "").trim());
if (!match) return false;
let ok = false;
for (const secret of secrets) {
const expected = createHmac("sha256", secret).update(rawBody).digest("hex");
// No early exit: every secret is compared.
ok = constantTimeEqual(match[1], expected) || ok;
}
return ok;
}
function authenticateWebhook(header: HeaderGetter, rawBody: Buffer): void {
if (!verifyWebhookSignature(rawBody, header("x-onehazel-signature"), SIGNING_SECRETS)) {
throw new ContractError("signature_invalid", "bad X-OneHazel-Signature");
}
}
// ───────────────────────────── deliveries ─────────────────────────────
//
// Acknowledge within 5 s, deduplicate on deliveryId (deliveries are at-least-once),
// and do the real work AFTER acknowledging. The seen-set lives in memory here; keep
// it in your database (a unique index on deliveryId) so it survives restarts.
interface Delivery {
type: string;
data: Record<string, unknown>;
operatorId: string;
timestamp: string;
deliveryId: string;
}
const SEEN = new Set<string>();
/** Your event handling. Conformance deliveries use the type `cert.conformance`: never act on players for them. */
async function processEvent(event: Delivery): Promise<void> {
console.log(`${event.type} ${event.deliveryId}`);
}
/** The whole module: one call per request, framework-agnostic. */
async function handle(path: string, header: HeaderGetter, rawBody: Buffer): Promise<Reply> {
try {
const op = CONTRACT.ops.find((o) => o.path === path);
if (!op) return { status: 404, body: { code: "invalid_request", message: "unknown operation", retryable: false } };
authenticateWebhook(header, rawBody);
const event = checkFields(parseBody(rawBody), op.fields, op.closed, "") as unknown as Delivery;
if (header("x-onehazel-delivery") !== event.deliveryId || header("x-onehazel-event") !== event.type) {
throw new ContractError("invalid_request", "X-OneHazel-Delivery and X-OneHazel-Event must match the body");
}
if (SEEN.has(event.deliveryId)) return { status: 200, body: { received: true, duplicate: true } };
SEEN.add(event.deliveryId);
setImmediate(() => {
processEvent(event).catch((e) => console.error("event processing failed", e instanceof Error ? e.message : "unknown error"));
});
return { status: 200, body: { received: true, duplicate: false } };
} catch (e) {
if (e instanceof ContractError) return errorReply(e.code, e.message);
console.error("webhook handler failed", e instanceof Error ? e.message : "unknown error");
return errorReply("internal_error", "internal error");
}
}
// ───────────────────────────── Fastify wiring ─────────────────────────────
const app = Fastify();
// Keep the body RAW: the signature is computed over the exact bytes OneHazel sent.
app.removeAllContentTypeParsers();
app.addContentTypeParser("*", { parseAs: "buffer" }, (_req, body, done) => done(null, body));
app.post(`${BASE_PATH}/*`, async (req, reply) => {
const raw = Buffer.isBuffer(req.body) ? req.body : Buffer.alloc(0);
const header: HeaderGetter = (name) => {
const v = req.headers[name];
return Array.isArray(v) ? v[0] : v;
};
const path = req.url.split("?")[0].slice(BASE_PATH.length);
const result = await handle(path, header, raw);
return reply.status(result.status).send(result.body);
});
app.listen({ port: PORT, host: "0.0.0.0" }).then(() => console.log(`OneHazel module listening on :${PORT}${BASE_PATH}`));Before you go live
- Replace the in-memory (or file) seen-set with a unique index on
deliveryIdin your database, so dedup survives restarts. - Run conformance (
connect_run_conformance) until every scenario passes.