/** * @krovacloud/webhook — verify Krova Cloud outbound webhook signatures. * * Krova Cloud signs each outbound webhook with an HMAC-SHA256 over * `"${timestamp}.${rawBody}"` and sends the result in the `X-Krova-Signature` * header as `t=,v1=`. This library recomputes and compares that * signature in constant time, and rejects stale timestamps to block replays. * * @packageDocumentation */ /** * Reasons a Krova Cloud webhook verification can fail. * * - `malformed_header` — the `X-Krova-Signature` header could not be parsed * into a `t` (timestamp) and `v1` (signature) pair. * - `timestamp_out_of_tolerance` — the signed timestamp is too far from the * current time (likely a replayed request). * - `invalid_signature` — the recomputed HMAC did not match the `v1` value. */ type KrovaWebhookErrorReason = "malformed_header" | "timestamp_out_of_tolerance" | "invalid_signature"; /** * Error thrown by {@link verifyKrovaWebhookOrThrow} (and the Express / * framework helpers) when a webhook signature fails verification. * * The machine-readable {@link KrovaWebhookError.reason} lets callers branch on * the specific failure without string-matching the message. */ export declare class KrovaWebhookError extends Error { readonly reason: KrovaWebhookErrorReason; constructor(reason: KrovaWebhookErrorReason, message?: string); } /** Default replay-tolerance window, in seconds (5 minutes). */ export declare const DEFAULT_TOLERANCE_SECONDS = 300; /** The raw webhook body: either the JSON string or its bytes. */ type WebhookPayload = string | Buffer | Uint8Array; /** Parsed contents of an `X-Krova-Signature` header. */ interface ParsedSignature { /** The signed UNIX timestamp (seconds), from the `t=` field. */ timestamp: number; /** The lowercase-hex HMAC-SHA256 signature, from the `v1=` field. */ signature: string; } /** Options accepted by the verification helpers. */ interface VerifyOptions { /** Raw request body (string or bytes) exactly as received — never re-serialized. */ payload: WebhookPayload; /** The full `X-Krova-Signature` header value. */ signature: string; /** The webhook signing secret configured in Krova Cloud. */ secret: string; /** * Maximum allowed absolute difference (seconds) between now and the signed * timestamp before the request is rejected as a replay. * @default 300 */ toleranceSeconds?: number; /** * Override the current time (seconds since epoch). Primarily for testing. * @default Math.floor(Date.now() / 1000) */ now?: number; } /** Successful verification result. */ interface VerifySuccess { valid: true; /** The signed timestamp (UNIX seconds). */ timestamp: number; reason?: undefined; } /** Failed verification result. */ interface VerifyFailure { valid: false; /** The machine-readable failure reason. */ reason: KrovaWebhookErrorReason; /** The signed timestamp, present when the header parsed but a later check failed. */ timestamp?: number; } /** * Result of a non-throwing verification. A discriminated union on `valid` — * narrow with `if (result.valid) { … }` to access `timestamp`, or the `else` * branch to read `reason`. */ type VerifyResult = VerifySuccess | VerifyFailure; /** * Parse an `X-Krova-Signature` header into its `t` (timestamp) and `v1` * (signature) parts. * * The header format is `t=,v1=`. Fields may appear in any * order and unknown fields are ignored (forward-compatible with future * signature versions). * * @throws {KrovaWebhookError} with reason `malformed_header` if the header is * missing either field or the timestamp is not a finite integer. */ export declare function parseSignatureHeader(header: string): ParsedSignature; /** * Compute the expected signature for a payload the same way Krova Cloud does: * `HMAC_SHA256(secret, "${timestamp}.${rawBody}")` as lowercase hex. */ export declare function computeSignature(secret: string, timestamp: number, payload: WebhookPayload): string; /** * Verify a Krova Cloud webhook signature without throwing. * * Recomputes `HMAC_SHA256(secret, "${t}.${rawBody}")`, compares it to the * header's `v1` value in constant time, and rejects when the signed timestamp * is outside the tolerance window (replay protection). * * @returns a {@link VerifyResult}; check `.valid` before trusting the payload. */ export declare function verifyKrovaWebhook(options: VerifyOptions): VerifyResult; /** * Verify a Krova Cloud webhook signature, throwing on failure. * * Identical checks to {@link verifyKrovaWebhook}, but raises a * {@link KrovaWebhookError} (carrying the machine-readable `reason`) instead of * returning a result object. Returns the parsed timestamp on success. * * @throws {KrovaWebhookError} */ export declare function verifyKrovaWebhookOrThrow(options: VerifyOptions): { timestamp: number; }; /** Header carrying the signature: `t=,v1=`. */ export declare const SIGNATURE_HEADER = "x-krova-signature"; /** Header carrying the event name. */ export declare const EVENT_HEADER = "x-krova-event"; /** Header carrying the unique delivery id. */ export declare const DELIVERY_HEADER = "x-krova-delivery"; /** Common options for the framework helpers. */ interface FrameworkOptions { /** The webhook signing secret configured in Krova Cloud. */ secret: string; /** * Replay-tolerance window in seconds. * @default 300 */ toleranceSeconds?: number; } /** * A verified Krova Cloud webhook, attached to the request by the framework * helpers once the signature checks pass. */ interface KrovaWebhookContext { /** The signed timestamp (UNIX seconds). */ timestamp: number; /** The `X-Krova-Event` header value, if present. */ event?: string; /** The `X-Krova-Delivery` header value, if present. */ delivery?: string; } type HeaderValue = string | string[] | undefined; /** * Framework-agnostic core. Verifies a raw body against the provided headers * and returns a discriminated result you can act on from any HTTP framework * (Next.js Route Handlers, Fastify, plain `http`, etc.). * * `headers` may be a plain object, a `Headers` instance, or anything with a * `.get()` method — header names are matched case-insensitively. */ export declare function verifyKrovaRequest(args: { payload: WebhookPayload; headers: Headers | Record | { get(name: string): string | null; }; secret: string; toleranceSeconds?: number; }): ({ valid: true; } & KrovaWebhookContext) | VerifyFailure; interface ExpressLikeRequest { body: unknown; headers: Record; krovaWebhook?: KrovaWebhookContext; } interface ExpressLikeResponse { status(code: number): ExpressLikeResponse; json(body: unknown): unknown; } type ExpressNext = (err?: unknown) => void; /** * Express middleware that verifies the incoming Krova Cloud webhook signature. * * IMPORTANT: the raw request body is required. Mount * `express.raw({ type: "application/json" })` on the webhook route BEFORE this * middleware so `req.body` is a `Buffer` — a body already parsed by * `express.json()` has been re-serialized and will NOT match the signature. * * On success it attaches a {@link KrovaWebhookContext} to `req.krovaWebhook` * and calls `next()`. On failure it responds `401` with * `{ error: }` and does not call `next()`. * * @example * import express from "express"; * import { krovaWebhook } from "@krovacloud/webhook"; * * const app = express(); * app.post( * "/webhooks/krova", * express.raw({ type: "application/json" }), * krovaWebhook({ secret: process.env.KROVA_WEBHOOK_SECRET! }), * (req, res) => { * const event = JSON.parse(req.body.toString("utf8")); * // req.krovaWebhook.event / .delivery / .timestamp are trustworthy here * res.status(200).json({ received: true }); * }, * ); */ export declare function krovaWebhook(options: FrameworkOptions): (req: ExpressLikeRequest, res: ExpressLikeResponse, next: ExpressNext) => void; export type { FrameworkOptions, KrovaWebhookContext, KrovaWebhookErrorReason, ParsedSignature, VerifyFailure, VerifyOptions, VerifyResult, VerifySuccess, WebhookPayload };