mirror of
https://github.com/Elysola/WebHooker.git
synced 2026-11-21 01:23:40 +00:00
fix(webhook): confirm only accepted deliveries
Acknowledging before queue acceptance permanently loses deliveries. Confirm only accepted work, release failed claims, scope replay identities and strip tenant-supplied installation authority.
This commit is contained in:
1 parent
2ec541ad7c
commit
88800611e5
5 files changed
+3985
-97
No files matched your search
@@ -2,9 +2,28 @@ import type { Env, WebhookEvent } from "../../types";
|
||||
import type { Provider } from "../types";
|
||||
import { hmacSha256Hex, timingSafeEqual } from "../hmac";
|
||||
import { verifySignature } from "../github/verify";
|
||||
import { claimOnce, idempotencyStore } from "../../lib/idempotency";
|
||||
|
||||
const REPLAY_WINDOW_SECONDS = 300;
|
||||
const NONCE_TTL_SECONDS = 600;
|
||||
/** How long an accepted nonce is remembered (longer than the signature window). */
|
||||
export const NONCE_TTL_SECONDS = 600;
|
||||
/**
|
||||
* How long a nonce stays held while its request is processed. Short, so a
|
||||
* request whose attempt failed (and could not give the nonce back) can be
|
||||
* retried well within the signature window.
|
||||
*/
|
||||
export const NONCE_CLAIM_SECONDS = 120;
|
||||
|
||||
/**
|
||||
* The request cannot be judged now: its nonce is held by an attempt not
|
||||
* confirmed as accepted (still running, or failed without giving the nonce
|
||||
* back), or the nonce store is unavailable. Not a proven replay: retry later.
|
||||
*/
|
||||
export class ReplayPendingError extends Error {
|
||||
constructor(message = "Replay nonce is held by an unconfirmed attempt") {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
function parseTimestamp(value: string | undefined): number | null {
|
||||
if (!value) return null;
|
||||
@@ -17,14 +36,18 @@ function parseTimestamp(value: string | undefined): number | null {
|
||||
* (Unix seconds) and `X-WebHooker-Nonce` and signs
|
||||
* `timestamp + "." + nonce + "." + body` instead of the bare body. We reject
|
||||
* timestamps outside a ±5min window and reject any nonce already seen (nonces
|
||||
* live in KV for 10min). Senders without those headers keep the legacy
|
||||
* are kept for 10min). Senders without those headers keep the legacy
|
||||
* body-only signature so existing integrations continue to work.
|
||||
*
|
||||
* Nonces are scoped to the signing secret, so two tenants picking the same
|
||||
* nonce never block each other, and claimed atomically (D1 when available),
|
||||
* so two concurrent replays cannot both pass.
|
||||
*/
|
||||
async function verifyReplayProtected(
|
||||
body: string,
|
||||
headers: Record<string, string>,
|
||||
secret: string,
|
||||
kv: KVNamespace,
|
||||
env: Env,
|
||||
): Promise<boolean> {
|
||||
const timestamp = parseTimestamp(headers["x-webhooker-timestamp"]);
|
||||
const nonce = headers["x-webhooker-nonce"];
|
||||
@@ -37,11 +60,23 @@ async function verifyReplayProtected(
|
||||
const expected = `sha256=${await hmacSha256Hex(secret, `${timestamp}.${nonce}.${body}`)}`;
|
||||
if (!timingSafeEqual(signature ?? "", expected)) return false;
|
||||
|
||||
const nonceKey = `nonce:${nonce}`;
|
||||
const seen = await kv.get(nonceKey);
|
||||
if (seen !== null && seen !== undefined) return false;
|
||||
await kv.put(nonceKey, "1", { expirationTtl: NONCE_TTL_SECONDS });
|
||||
return true;
|
||||
const key = await replayNonceKey(secret, nonce);
|
||||
let state;
|
||||
try {
|
||||
state = await claimOnce(idempotencyStore(env.DB, env.KV), key, NONCE_CLAIM_SECONDS);
|
||||
} catch {
|
||||
// A storage failure says nothing about the signature.
|
||||
throw new ReplayPendingError("Replay protection is temporarily unavailable");
|
||||
}
|
||||
// Only a nonce whose request was accepted makes this a replay.
|
||||
if (state === "pending") throw new ReplayPendingError();
|
||||
return state === "claimed";
|
||||
}
|
||||
|
||||
/** Claim key of a replay-protection nonce, scoped to the signing secret. */
|
||||
export async function replayNonceKey(secret: string, nonce: string): Promise<string> {
|
||||
const scope = (await hmacSha256Hex(secret, "webhooker:nonce-scope")).slice(0, 16);
|
||||
return `nonce:${scope}:${nonce}`;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -72,7 +107,7 @@ export const customProvider: Provider = {
|
||||
headers["x-webhooker-timestamp"] !== undefined &&
|
||||
headers["x-webhooker-nonce"] !== undefined
|
||||
) {
|
||||
return verifyReplayProtected(body, headers, secret, env.KV);
|
||||
return verifyReplayProtected(body, headers, secret, env);
|
||||
}
|
||||
return verifySignature(body, headers["x-webhooker-signature"], secret);
|
||||
},
|
||||
@@ -80,7 +115,9 @@ export const customProvider: Provider = {
|
||||
parse(body, _headers): WebhookEvent | null {
|
||||
try {
|
||||
const payload = JSON.parse(body) as Record<string, unknown>;
|
||||
if (!payload || typeof payload !== "object") return null;
|
||||
// An object only: a top-level array (or scalar) could not be parked and
|
||||
// restored like every other payload, so it is refused up front.
|
||||
if (!payload || typeof payload !== "object" || Array.isArray(payload)) return null;
|
||||
// Optional id for sender-side dedup (retries from monitoring systems).
|
||||
const deliveryId =
|
||||
typeof payload.deliveryId === "string" && payload.deliveryId
|
||||
|
||||
Reference in new issue
Block a user