UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

853 lines (852 loc) • 30 kB
import { o as requireActivePluginHttpRouteRegistry } from "./runtime-Iz8uZ7EU.js"; import { t as pruneMapToMaxSize } from "./map-size-BQ5KZ2st.js"; import { t as normalizeWebhookPath } from "./webhook-path-BYotIM_c.js"; import { clearTimeout, setTimeout } from "node:timers"; //#region src/infra/http-body.ts const DEFAULT_WEBHOOK_MAX_BODY_BYTES = 1024 * 1024; const DEFAULT_WEBHOOK_BODY_TIMEOUT_MS = 3e4; const DEFAULT_ERROR_MESSAGE = { PAYLOAD_TOO_LARGE: "PayloadTooLarge", REQUEST_BODY_TIMEOUT: "RequestBodyTimeout", CONNECTION_CLOSED: "RequestBodyConnectionClosed" }; const DEFAULT_ERROR_STATUS_CODE = { PAYLOAD_TOO_LARGE: 413, REQUEST_BODY_TIMEOUT: 408, CONNECTION_CLOSED: 400 }; const DEFAULT_RESPONSE_MESSAGE = { PAYLOAD_TOO_LARGE: "Payload too large", REQUEST_BODY_TIMEOUT: "Request body timeout", CONNECTION_CLOSED: "Connection closed" }; var RequestBodyLimitError = class extends Error { constructor(init) { super(init.message ?? DEFAULT_ERROR_MESSAGE[init.code]); this.name = "RequestBodyLimitError"; this.code = init.code; this.statusCode = DEFAULT_ERROR_STATUS_CODE[init.code]; } }; function isRequestBodyLimitError(error, code) { if (!(error instanceof RequestBodyLimitError)) return false; if (!code) return true; return error.code === code; } function requestBodyErrorToText(code) { return DEFAULT_RESPONSE_MESSAGE[code]; } function parseContentLengthHeader(req) { const header = req.headers["content-length"]; const raw = Array.isArray(header) ? header[0] : header; if (typeof raw !== "string") return null; const parsed = Number.parseInt(raw, 10); if (!Number.isFinite(parsed) || parsed < 0) return null; return parsed; } function resolveRequestBodyLimitValues(options) { return { maxBytes: Number.isFinite(options.maxBytes) ? Math.max(1, Math.floor(options.maxBytes)) : 1, timeoutMs: typeof options.timeoutMs === "number" && Number.isFinite(options.timeoutMs) ? Math.max(1, Math.floor(options.timeoutMs)) : DEFAULT_WEBHOOK_BODY_TIMEOUT_MS }; } function advanceRequestBodyChunk(chunk, totalBytes, maxBytes) { const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk); const nextTotalBytes = totalBytes + buffer.length; return { buffer, totalBytes: nextTotalBytes, exceeded: nextTotalBytes > maxBytes }; } async function readRequestBodyWithLimit(req, options) { const { maxBytes, timeoutMs } = resolveRequestBodyLimitValues(options); const encoding = options.encoding ?? "utf-8"; const declaredLength = parseContentLengthHeader(req); if (declaredLength !== null && declaredLength > maxBytes) { const error = new RequestBodyLimitError({ code: "PAYLOAD_TOO_LARGE" }); if (!req.destroyed) req.destroy(); throw error; } return await new Promise((resolve, reject) => { let done = false; let ended = false; let totalBytes = 0; const chunks = []; const cleanup = () => { req.removeListener("data", onData); req.removeListener("end", onEnd); req.removeListener("error", onError); req.removeListener("close", onClose); clearTimeout(timer); }; const finish = (cb) => { if (done) return; done = true; cleanup(); cb(); }; const fail = (error) => { finish(() => reject(error)); }; const timer = setTimeout(() => { const error = new RequestBodyLimitError({ code: "REQUEST_BODY_TIMEOUT" }); if (!req.destroyed) req.destroy(); fail(error); }, timeoutMs); const onData = (chunk) => { if (done) return; const progress = advanceRequestBodyChunk(chunk, totalBytes, maxBytes); totalBytes = progress.totalBytes; if (progress.exceeded) { const error = new RequestBodyLimitError({ code: "PAYLOAD_TOO_LARGE" }); if (!req.destroyed) req.destroy(); fail(error); return; } chunks.push(progress.buffer); }; const onEnd = () => { ended = true; finish(() => resolve(Buffer.concat(chunks).toString(encoding))); }; const onError = (error) => { if (done) return; fail(error); }; const onClose = () => { if (done || ended) return; fail(new RequestBodyLimitError({ code: "CONNECTION_CLOSED" })); }; req.on("data", onData); req.on("end", onEnd); req.on("error", onError); req.on("close", onClose); }); } async function readJsonBodyWithLimit(req, options) { try { const trimmed = (await readRequestBodyWithLimit(req, options)).trim(); if (!trimmed) { if (options.emptyObjectOnEmpty === false) return { ok: false, code: "INVALID_JSON", error: "empty payload" }; return { ok: true, value: {} }; } try { return { ok: true, value: JSON.parse(trimmed) }; } catch (error) { return { ok: false, code: "INVALID_JSON", error: error instanceof Error ? error.message : String(error) }; } } catch (error) { if (isRequestBodyLimitError(error)) return { ok: false, code: error.code, error: requestBodyErrorToText(error.code) }; return { ok: false, code: "INVALID_JSON", error: error instanceof Error ? error.message : String(error) }; } } function installRequestBodyLimitGuard(req, res, options) { const { maxBytes, timeoutMs } = resolveRequestBodyLimitValues(options); const responseFormat = options.responseFormat ?? "json"; const customText = options.responseText ?? {}; let tripped = false; let reason = null; let done = false; let ended = false; let totalBytes = 0; const cleanup = () => { req.removeListener("data", onData); req.removeListener("end", onEnd); req.removeListener("close", onClose); req.removeListener("error", onError); clearTimeout(timer); }; const finish = () => { if (done) return; done = true; cleanup(); }; const respond = (error) => { const text = customText[error.code] ?? requestBodyErrorToText(error.code); if (!res.headersSent) { res.statusCode = error.statusCode; if (responseFormat === "text") { res.setHeader("Content-Type", "text/plain; charset=utf-8"); res.end(text); } else { res.setHeader("Content-Type", "application/json; charset=utf-8"); res.end(JSON.stringify({ error: text })); } } }; const trip = (error) => { if (tripped) return; tripped = true; reason = error.code; finish(); respond(error); if (!req.destroyed) req.destroy(); }; const onData = (chunk) => { if (done) return; const progress = advanceRequestBodyChunk(chunk, totalBytes, maxBytes); totalBytes = progress.totalBytes; if (progress.exceeded) trip(new RequestBodyLimitError({ code: "PAYLOAD_TOO_LARGE" })); }; const onEnd = () => { ended = true; finish(); }; const onClose = () => { if (done || ended) return; finish(); }; const onError = () => { finish(); }; const timer = setTimeout(() => { trip(new RequestBodyLimitError({ code: "REQUEST_BODY_TIMEOUT" })); }, timeoutMs); req.on("data", onData); req.on("end", onEnd); req.on("close", onClose); req.on("error", onError); const declaredLength = parseContentLengthHeader(req); if (declaredLength !== null && declaredLength > maxBytes) trip(new RequestBodyLimitError({ code: "PAYLOAD_TOO_LARGE" })); return { dispose: finish, isTripped: () => tripped, code: () => reason }; } //#endregion //#region src/plugin-sdk/webhook-memory-guards.ts const WEBHOOK_RATE_LIMIT_DEFAULTS = Object.freeze({ windowMs: 6e4, maxRequests: 120, maxTrackedKeys: 4096 }); const WEBHOOK_ANOMALY_COUNTER_DEFAULTS = Object.freeze({ maxTrackedKeys: 4096, ttlMs: 360 * 6e4, logEvery: 25 }); const WEBHOOK_ANOMALY_STATUS_CODES = Object.freeze([ 400, 401, 408, 413, 415, 429 ]); /** Create a simple fixed-window rate limiter for in-memory webhook protection. */ function createFixedWindowRateLimiter(options) { const windowMs = Math.max(1, Math.floor(options.windowMs)); const maxRequests = Math.max(1, Math.floor(options.maxRequests)); const maxTrackedKeys = Math.max(1, Math.floor(options.maxTrackedKeys)); const pruneIntervalMs = Math.max(1, Math.floor(options.pruneIntervalMs ?? windowMs)); const state = /* @__PURE__ */ new Map(); let lastPruneMs = 0; const touch = (key, value) => { state.delete(key); state.set(key, value); }; const prune = (nowMs) => { for (const [key, entry] of state) if (nowMs - entry.windowStartMs >= windowMs) state.delete(key); }; return { isRateLimited: (key, nowMs = Date.now()) => { if (!key) return false; if (nowMs - lastPruneMs >= pruneIntervalMs) { prune(nowMs); lastPruneMs = nowMs; } const existing = state.get(key); if (!existing || nowMs - existing.windowStartMs >= windowMs) { touch(key, { count: 1, windowStartMs: nowMs }); pruneMapToMaxSize(state, maxTrackedKeys); return false; } const nextCount = existing.count + 1; touch(key, { count: nextCount, windowStartMs: existing.windowStartMs }); pruneMapToMaxSize(state, maxTrackedKeys); return nextCount > maxRequests; }, size: () => state.size, clear: () => { state.clear(); lastPruneMs = 0; } }; } /** Count keyed events in memory with optional TTL pruning and bounded cardinality. */ function createBoundedCounter(options) { const maxTrackedKeys = Math.max(1, Math.floor(options.maxTrackedKeys)); const ttlMs = Math.max(0, Math.floor(options.ttlMs ?? 0)); const pruneIntervalMs = Math.max(1, Math.floor(options.pruneIntervalMs ?? (ttlMs > 0 ? ttlMs : 6e4))); const counters = /* @__PURE__ */ new Map(); let lastPruneMs = 0; const touch = (key, value) => { counters.delete(key); counters.set(key, value); }; const isExpired = (entry, nowMs) => ttlMs > 0 && nowMs - entry.updatedAtMs >= ttlMs; const prune = (nowMs) => { if (ttlMs > 0) { for (const [key, entry] of counters) if (isExpired(entry, nowMs)) counters.delete(key); } }; return { increment: (key, nowMs = Date.now()) => { if (!key) return 0; if (nowMs - lastPruneMs >= pruneIntervalMs) { prune(nowMs); lastPruneMs = nowMs; } const existing = counters.get(key); const nextCount = (existing && !isExpired(existing, nowMs) ? existing.count : 0) + 1; touch(key, { count: nextCount, updatedAtMs: nowMs }); pruneMapToMaxSize(counters, maxTrackedKeys); return nextCount; }, size: () => counters.size, clear: () => { counters.clear(); lastPruneMs = 0; } }; } /** Track repeated webhook failures and emit sampled logs for suspicious request patterns. */ function createWebhookAnomalyTracker(options) { const maxTrackedKeys = Math.max(1, Math.floor(options?.maxTrackedKeys ?? WEBHOOK_ANOMALY_COUNTER_DEFAULTS.maxTrackedKeys)); const ttlMs = Math.max(0, Math.floor(options?.ttlMs ?? WEBHOOK_ANOMALY_COUNTER_DEFAULTS.ttlMs)); const logEvery = Math.max(1, Math.floor(options?.logEvery ?? WEBHOOK_ANOMALY_COUNTER_DEFAULTS.logEvery)); const trackedStatusCodes = new Set(options?.trackedStatusCodes ?? WEBHOOK_ANOMALY_STATUS_CODES); const counter = createBoundedCounter({ maxTrackedKeys, ttlMs }); return { record: ({ key, statusCode, message, log, nowMs }) => { if (!trackedStatusCodes.has(statusCode)) return 0; const next = counter.increment(key, nowMs); if (log && (next === 1 || next % logEvery === 0)) log(message(next)); return next; }, size: () => counter.size(), clear: () => counter.clear() }; } //#endregion //#region src/plugin-sdk/webhook-request-guards.ts const WEBHOOK_BODY_READ_DEFAULTS = Object.freeze({ preAuth: { maxBytes: 64 * 1024, timeoutMs: 5e3 }, postAuth: { maxBytes: 1024 * 1024, timeoutMs: 3e4 } }); const WEBHOOK_IN_FLIGHT_DEFAULTS = Object.freeze({ maxInFlightPerKey: 8, maxTrackedKeys: 4096 }); function resolveWebhookBodyReadLimits(params) { const defaults = params.profile === "pre-auth" ? WEBHOOK_BODY_READ_DEFAULTS.preAuth : WEBHOOK_BODY_READ_DEFAULTS.postAuth; return { maxBytes: typeof params.maxBytes === "number" && Number.isFinite(params.maxBytes) && params.maxBytes > 0 ? Math.floor(params.maxBytes) : defaults.maxBytes, timeoutMs: typeof params.timeoutMs === "number" && Number.isFinite(params.timeoutMs) && params.timeoutMs > 0 ? Math.floor(params.timeoutMs) : defaults.timeoutMs }; } function respondWebhookBodyReadError(params) { const { res, code, invalidMessage } = params; if (code === "PAYLOAD_TOO_LARGE") { res.statusCode = 413; res.end(requestBodyErrorToText("PAYLOAD_TOO_LARGE")); return { ok: false }; } if (code === "REQUEST_BODY_TIMEOUT") { res.statusCode = 408; res.end(requestBodyErrorToText("REQUEST_BODY_TIMEOUT")); return { ok: false }; } if (code === "CONNECTION_CLOSED") { res.statusCode = 400; res.end(requestBodyErrorToText("CONNECTION_CLOSED")); return { ok: false }; } res.statusCode = 400; res.end(invalidMessage ?? "Bad Request"); return { ok: false }; } /** Create an in-memory limiter that caps concurrent webhook handlers per key. */ function createWebhookInFlightLimiter(options) { const maxInFlightPerKey = Math.max(1, Math.floor(options?.maxInFlightPerKey ?? WEBHOOK_IN_FLIGHT_DEFAULTS.maxInFlightPerKey)); const maxTrackedKeys = Math.max(1, Math.floor(options?.maxTrackedKeys ?? WEBHOOK_IN_FLIGHT_DEFAULTS.maxTrackedKeys)); const active = /* @__PURE__ */ new Map(); return { tryAcquire: (key) => { if (!key) return true; const current = active.get(key) ?? 0; if (current >= maxInFlightPerKey) return false; active.set(key, current + 1); pruneMapToMaxSize(active, maxTrackedKeys); return true; }, release: (key) => { if (!key) return; const current = active.get(key); if (current === void 0) return; if (current <= 1) { active.delete(key); return; } active.set(key, current - 1); }, size: () => active.size, clear: () => active.clear() }; } /** Detect JSON content types, including structured syntax suffixes like `application/ld+json`. */ function isJsonContentType(value) { const first = Array.isArray(value) ? value[0] : value; if (!first) return false; const mediaType = first.split(";", 1)[0]?.trim().toLowerCase(); return mediaType === "application/json" || Boolean(mediaType?.endsWith("+json")); } /** Apply method, rate-limit, and content-type guards before a webhook handler reads the body. */ function applyBasicWebhookRequestGuards(params) { const allowMethods = params.allowMethods?.length ? params.allowMethods : null; if (allowMethods && !allowMethods.includes(params.req.method ?? "")) { params.res.statusCode = 405; params.res.setHeader("Allow", allowMethods.join(", ")); params.res.end("Method Not Allowed"); return false; } if (params.rateLimiter && params.rateLimitKey && params.rateLimiter.isRateLimited(params.rateLimitKey, params.nowMs ?? Date.now())) { params.res.statusCode = 429; params.res.end("Too Many Requests"); return false; } if (params.requireJsonContentType && params.req.method === "POST" && !isJsonContentType(params.req.headers["content-type"])) { params.res.statusCode = 415; params.res.end("Unsupported Media Type"); return false; } return true; } /** Start the shared webhook request lifecycle and return a release hook for in-flight tracking. */ function beginWebhookRequestPipelineOrReject(params) { if (!applyBasicWebhookRequestGuards({ req: params.req, res: params.res, allowMethods: params.allowMethods, rateLimiter: params.rateLimiter, rateLimitKey: params.rateLimitKey, nowMs: params.nowMs, requireJsonContentType: params.requireJsonContentType })) return { ok: false }; const inFlightKey = params.inFlightKey ?? ""; const inFlightLimiter = params.inFlightLimiter; if (inFlightLimiter && inFlightKey && !inFlightLimiter.tryAcquire(inFlightKey)) { params.res.statusCode = params.inFlightLimitStatusCode ?? 429; params.res.end(params.inFlightLimitMessage ?? "Too Many Requests"); return { ok: false }; } let released = false; return { ok: true, release: () => { if (released) return; released = true; if (inFlightLimiter && inFlightKey) inFlightLimiter.release(inFlightKey); } }; } /** Read a webhook request body with bounded size/time limits and translate failures into responses. */ async function readWebhookBodyOrReject(params) { const limits = resolveWebhookBodyReadLimits({ maxBytes: params.maxBytes, timeoutMs: params.timeoutMs, profile: params.profile }); try { return { ok: true, value: await readRequestBodyWithLimit(params.req, limits) }; } catch (error) { if (isRequestBodyLimitError(error)) return respondWebhookBodyReadError({ res: params.res, code: error.code, invalidMessage: params.invalidBodyMessage }); return respondWebhookBodyReadError({ res: params.res, code: "INVALID_BODY", invalidMessage: params.invalidBodyMessage ?? (error instanceof Error ? error.message : String(error)) }); } } /** Read and parse a JSON webhook body, rejecting malformed or oversized payloads consistently. */ async function readJsonWebhookBodyOrReject(params) { const limits = resolveWebhookBodyReadLimits({ maxBytes: params.maxBytes, timeoutMs: params.timeoutMs, profile: params.profile }); const body = await readJsonBodyWithLimit(params.req, { maxBytes: limits.maxBytes, timeoutMs: limits.timeoutMs, emptyObjectOnEmpty: params.emptyObjectOnEmpty }); if (body.ok) return { ok: true, value: body.value }; return respondWebhookBodyReadError({ res: params.res, code: body.code, invalidMessage: params.invalidJsonMessage }); } //#endregion //#region src/plugins/http-path.ts function normalizePluginHttpPath(path, fallback) { const trimmed = path?.trim(); if (!trimmed) { const fallbackTrimmed = fallback?.trim(); if (!fallbackTrimmed) return null; return fallbackTrimmed.startsWith("/") ? fallbackTrimmed : `/${fallbackTrimmed}`; } return trimmed.startsWith("/") ? trimmed : `/${trimmed}`; } //#endregion //#region src/gateway/security-path.ts const MAX_PATH_DECODE_PASSES = 32; function normalizePathSeparators(pathname) { const collapsed = pathname.replace(/\/{2,}/g, "/"); if (collapsed.length <= 1) return collapsed; return collapsed.replace(/\/+$/, ""); } function resolveDotSegments(pathname) { try { return new URL(pathname, "http://localhost").pathname; } catch { return pathname; } } function normalizePathForSecurity(pathname) { return normalizePathSeparators(resolveDotSegments(pathname).toLowerCase()) || "/"; } function pushNormalizedCandidate(candidates, seen, value) { const normalized = normalizePathForSecurity(value); if (seen.has(normalized)) return; seen.add(normalized); candidates.push(normalized); } function buildCanonicalPathCandidates(pathname, maxDecodePasses = MAX_PATH_DECODE_PASSES) { const candidates = []; const seen = /* @__PURE__ */ new Set(); pushNormalizedCandidate(candidates, seen, pathname); let decoded = pathname; let malformedEncoding = false; let decodePasses = 0; for (let pass = 0; pass < maxDecodePasses; pass++) { let nextDecoded = decoded; try { nextDecoded = decodeURIComponent(decoded); } catch { malformedEncoding = true; break; } if (nextDecoded === decoded) break; decodePasses += 1; decoded = nextDecoded; pushNormalizedCandidate(candidates, seen, decoded); } let decodePassLimitReached = false; if (!malformedEncoding) try { decodePassLimitReached = decodeURIComponent(decoded) !== decoded; } catch { malformedEncoding = true; } return { candidates, decodePasses, decodePassLimitReached, malformedEncoding }; } function canonicalizePathVariant(pathname) { const { candidates } = buildCanonicalPathCandidates(pathname); return candidates[candidates.length - 1] ?? "/"; } function canonicalizePathForSecurity(pathname) { const { candidates, decodePasses, decodePassLimitReached, malformedEncoding } = buildCanonicalPathCandidates(pathname); return { canonicalPath: candidates[candidates.length - 1] ?? "/", candidates, decodePasses, decodePassLimitReached, malformedEncoding, rawNormalizedPath: normalizePathSeparators(pathname.toLowerCase()) || "/" }; } const PROTECTED_PLUGIN_ROUTE_PREFIXES = ["/api/channels"]; //#endregion //#region src/plugins/http-route-overlap.ts function prefixMatchPath(pathname, prefix) { return pathname === prefix || pathname.startsWith(`${prefix}/`) || pathname.startsWith(`${prefix}%`); } function doPluginHttpRoutesOverlap(a, b) { const aPath = canonicalizePathVariant(a.path); const bPath = canonicalizePathVariant(b.path); if (a.match === "exact" && b.match === "exact") return aPath === bPath; if (a.match === "prefix" && b.match === "prefix") return prefixMatchPath(aPath, bPath) || prefixMatchPath(bPath, aPath); const prefixRoute = a.match === "prefix" ? a : b; return prefixMatchPath(canonicalizePathVariant((a.match === "exact" ? a : b).path), canonicalizePathVariant(prefixRoute.path)); } function findOverlappingPluginHttpRoute(routes, candidate) { return routes.find((route) => doPluginHttpRoutesOverlap(route, candidate)); } //#endregion //#region src/plugins/http-registry.ts function registerPluginHttpRoute(params) { const registry = params.registry ?? requireActivePluginHttpRouteRegistry(); const routes = registry.httpRoutes ?? []; registry.httpRoutes = routes; const normalizedPath = normalizePluginHttpPath(params.path, params.fallbackPath); const suffix = params.accountId ? ` for account "${params.accountId}"` : ""; if (!normalizedPath) { params.log?.(`plugin: webhook path missing${suffix}`); return () => {}; } const routeMatch = params.match ?? "exact"; const overlappingRoute = findOverlappingPluginHttpRoute(routes, { path: normalizedPath, match: routeMatch }); if (overlappingRoute && overlappingRoute.auth !== params.auth) { params.log?.(`plugin: route overlap denied at ${normalizedPath} (${routeMatch}, ${params.auth})${suffix}; overlaps ${overlappingRoute.path} (${overlappingRoute.match}, ${overlappingRoute.auth}) owned by ${overlappingRoute.pluginId ?? "unknown-plugin"} (${overlappingRoute.source ?? "unknown-source"})`); return () => {}; } const existingIndex = routes.findIndex((entry) => entry.path === normalizedPath && entry.match === routeMatch); if (existingIndex >= 0) { const existing = routes[existingIndex]; if (!existing) return () => {}; if (!params.replaceExisting) { params.log?.(`plugin: route conflict at ${normalizedPath} (${routeMatch})${suffix}; owned by ${existing.pluginId ?? "unknown-plugin"} (${existing.source ?? "unknown-source"})`); return () => {}; } if (existing.pluginId && params.pluginId && existing.pluginId !== params.pluginId) { params.log?.(`plugin: route replacement denied for ${normalizedPath} (${routeMatch})${suffix}; owned by ${existing.pluginId}`); return () => {}; } const pluginHint = params.pluginId ? ` (${params.pluginId})` : ""; params.log?.(`plugin: replacing stale webhook path ${normalizedPath} (${routeMatch})${suffix}${pluginHint}`); routes.splice(existingIndex, 1); } const entry = { path: normalizedPath, handler: params.handler, auth: params.auth, match: routeMatch, pluginId: params.pluginId, source: params.source }; routes.push(entry); return () => { const index = routes.indexOf(entry); if (index >= 0) routes.splice(index, 1); }; } //#endregion //#region src/plugin-sdk/webhook-targets.ts /** Register a webhook target and lazily install the matching plugin HTTP route on first use. */ function registerWebhookTargetWithPluginRoute(params) { return registerWebhookTarget(params.targetsByPath, params.target, { onFirstPathTarget: ({ path }) => registerPluginHttpRoute({ ...params.route, path, replaceExisting: params.route.replaceExisting ?? true }), onLastPathTargetRemoved: params.onLastPathTargetRemoved }); } const pathTeardownByTargetMap = /* @__PURE__ */ new WeakMap(); function getPathTeardownMap(targetsByPath) { const mapKey = targetsByPath; const existing = pathTeardownByTargetMap.get(mapKey); if (existing) return existing; const created = /* @__PURE__ */ new Map(); pathTeardownByTargetMap.set(mapKey, created); return created; } /** Add a normalized target to a path bucket and clean up route state when the last target leaves. */ function registerWebhookTarget(targetsByPath, target, opts) { const key = normalizeWebhookPath(target.path); const normalizedTarget = { ...target, path: key }; const existing = targetsByPath.get(key) ?? []; if (existing.length === 0) { const onFirstPathResult = opts?.onFirstPathTarget?.({ path: key, target: normalizedTarget }); if (typeof onFirstPathResult === "function") getPathTeardownMap(targetsByPath).set(key, onFirstPathResult); } targetsByPath.set(key, [...existing, normalizedTarget]); let isActive = true; const unregister = () => { if (!isActive) return; isActive = false; const updated = (targetsByPath.get(key) ?? []).filter((entry) => entry !== normalizedTarget); if (updated.length > 0) { targetsByPath.set(key, updated); return; } targetsByPath.delete(key); const teardown = getPathTeardownMap(targetsByPath).get(key); if (teardown) { getPathTeardownMap(targetsByPath).delete(key); teardown(); } opts?.onLastPathTargetRemoved?.({ path: key }); }; return { target: normalizedTarget, unregister }; } /** Resolve all registered webhook targets for the incoming request path. */ function resolveWebhookTargets(req, targetsByPath) { const path = normalizeWebhookPath(new URL(req.url ?? "/", "http://localhost").pathname); const targets = targetsByPath.get(path); if (!targets || targets.length === 0) return null; return { path, targets }; } /** Run common webhook guards, then dispatch only when the request path resolves to live targets. */ async function withResolvedWebhookRequestPipeline(params) { const resolved = resolveWebhookTargets(params.req, params.targetsByPath); if (!resolved) return false; const inFlightKey = typeof params.inFlightKey === "function" ? params.inFlightKey({ req: params.req, path: resolved.path, targets: resolved.targets }) : params.inFlightKey ?? `${resolved.path}:${params.req.socket?.remoteAddress ?? "unknown"}`; const requestLifecycle = beginWebhookRequestPipelineOrReject({ req: params.req, res: params.res, allowMethods: params.allowMethods, rateLimiter: params.rateLimiter, rateLimitKey: params.rateLimitKey, nowMs: params.nowMs, requireJsonContentType: params.requireJsonContentType, inFlightLimiter: params.inFlightLimiter, inFlightKey, inFlightLimitStatusCode: params.inFlightLimitStatusCode, inFlightLimitMessage: params.inFlightLimitMessage }); if (!requestLifecycle.ok) return true; try { await params.handle(resolved); return true; } finally { requestLifecycle.release(); } } function updateMatchedWebhookTarget(matched, target) { if (matched) return { ok: false, result: { kind: "ambiguous" } }; return { ok: true, matched: target }; } function finalizeMatchedWebhookTarget(matched) { if (!matched) return { kind: "none" }; return { kind: "single", target: matched }; } /** Match exactly one synchronous target or report whether resolution was empty or ambiguous. */ function resolveSingleWebhookTarget(targets, isMatch) { let matched; for (const target of targets) { if (!isMatch(target)) continue; const updated = updateMatchedWebhookTarget(matched, target); if (!updated.ok) return updated.result; matched = updated.matched; } return finalizeMatchedWebhookTarget(matched); } /** Async variant of single-target resolution for auth checks that need I/O. */ async function resolveSingleWebhookTargetAsync(targets, isMatch) { let matched; for (const target of targets) { if (!await isMatch(target)) continue; const updated = updateMatchedWebhookTarget(matched, target); if (!updated.ok) return updated.result; matched = updated.matched; } return finalizeMatchedWebhookTarget(matched); } /** Resolve an authorized target and send the standard unauthorized or ambiguous response on failure. */ async function resolveWebhookTargetWithAuthOrReject(params) { return resolveWebhookTargetMatchOrReject(params, await resolveSingleWebhookTargetAsync(params.targets, async (target) => Boolean(await params.isMatch(target)))); } /** Synchronous variant of webhook auth resolution for cheap in-memory match checks. */ function resolveWebhookTargetWithAuthOrRejectSync(params) { return resolveWebhookTargetMatchOrReject(params, resolveSingleWebhookTarget(params.targets, params.isMatch)); } function resolveWebhookTargetMatchOrReject(params, match) { if (match.kind === "single") return match.target; if (match.kind === "ambiguous") { params.res.statusCode = params.ambiguousStatusCode ?? 401; params.res.end(params.ambiguousMessage ?? "ambiguous webhook target"); return null; } params.res.statusCode = params.unauthorizedStatusCode ?? 401; params.res.end(params.unauthorizedMessage ?? "unauthorized"); return null; } //#endregion export { DEFAULT_WEBHOOK_MAX_BODY_BYTES as A, WEBHOOK_ANOMALY_COUNTER_DEFAULTS as C, createFixedWindowRateLimiter as D, createBoundedCounter as E, readRequestBodyWithLimit as F, requestBodyErrorToText as I, installRequestBodyLimitGuard as M, isRequestBodyLimitError as N, createWebhookAnomalyTracker as O, readJsonBodyWithLimit as P, readWebhookBodyOrReject as S, WEBHOOK_RATE_LIMIT_DEFAULTS as T, applyBasicWebhookRequestGuards as _, resolveWebhookTargetWithAuthOrReject as a, isJsonContentType as b, withResolvedWebhookRequestPipeline as c, PROTECTED_PLUGIN_ROUTE_PREFIXES as d, canonicalizePathForSecurity as f, WEBHOOK_IN_FLIGHT_DEFAULTS as g, WEBHOOK_BODY_READ_DEFAULTS as h, resolveSingleWebhookTargetAsync as i, RequestBodyLimitError as j, DEFAULT_WEBHOOK_BODY_TIMEOUT_MS as k, registerPluginHttpRoute as l, normalizePluginHttpPath as m, registerWebhookTargetWithPluginRoute as n, resolveWebhookTargetWithAuthOrRejectSync as o, canonicalizePathVariant as p, resolveSingleWebhookTarget as r, resolveWebhookTargets as s, registerWebhookTarget as t, findOverlappingPluginHttpRoute as u, beginWebhookRequestPipelineOrReject as v, WEBHOOK_ANOMALY_STATUS_CODES as w, readJsonWebhookBodyOrReject as x, createWebhookInFlightLimiter as y };