UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

250 lines (249 loc) • 8.03 kB
import { P as resolveIntegerOption, R as resolveTimerTimeoutMs } from "./number-coercion-D6u-4YD8.mjs"; import { t as createDeferredCore } from "./deferred-D0La5CRk.mjs"; import { a as isLoopbackAddress, h as resolveClientIp } from "./net-BgRayX-P.mjs"; //#region src/gateway/auth-rate-limit.ts const AUTH_RATE_LIMIT_SCOPE_DEFAULT = "default"; const AUTH_RATE_LIMIT_SCOPE_SHARED_SECRET = "shared-secret"; const AUTH_RATE_LIMIT_SCOPE_DEVICE_TOKEN = "device-token"; const AUTH_RATE_LIMIT_SCOPE_NODE_PAIRING = "node-pairing"; const AUTH_RATE_LIMIT_SCOPE_NODE_REAPPROVAL = "node-reapproval"; const AUTH_RATE_LIMIT_SCOPE_BOOTSTRAP_TOKEN = "bootstrap-token"; const AUTH_RATE_LIMIT_SCOPE_DEVICE_JOIN = "device-join"; const AUTH_RATE_LIMIT_SCOPE_WATCH_CHALLENGE = "watch-challenge"; const AUTH_RATE_LIMIT_SCOPE_WORKER_ADMISSION = "worker-admission"; const AUTH_RATE_LIMIT_SCOPE_WORKER_TRANSFER = "worker-transfer"; const AUTH_RATE_LIMIT_SCOPE_HOOK_AUTH = "hook-auth"; const BROWSER_ORIGIN_RATE_LIMIT_KEY_PREFIX = "browser-origin:"; const IDENTITY_RATE_LIMIT_KEY_PREFIX = "identity:"; const authRateLimiterExemptionChecks = /* @__PURE__ */ new WeakMap(); /** Whether a limiter created by this module exempts the prepared client identity. */ function isAuthRateLimitClientExempt(e, t) { return authRateLimiterExemptionChecks.get(e)?.(t) ?? false; } const DEFAULT_MAX_ATTEMPTS = 10; const DEFAULT_WINDOW_MS = 6e4; const DEFAULT_LOCKOUT_MS = 3e5; const PRUNE_INTERVAL_MS = 6e4; const DEFAULT_MAX_ENTRIES = 1e4; const LOOPBACK_FAILURE_DELAY_BASE_MS = 250; const LOOPBACK_FAILURE_DELAY_MAX_MS = 5e3; const LOOPBACK_FAILURE_HISTORY_LIMIT = Math.ceil(Math.log2(LOOPBACK_FAILURE_DELAY_MAX_MS / LOOPBACK_FAILURE_DELAY_BASE_MS)) + 1; /** * Canonicalize client IPs used for auth throttling so all call sites * share one representation (including IPv4-mapped IPv6 forms). */ function normalizeRateLimitClientIp(e) { if (typeof e === "string" && (e.startsWith(BROWSER_ORIGIN_RATE_LIMIT_KEY_PREFIX) || e.startsWith(IDENTITY_RATE_LIMIT_KEY_PREFIX))) return e; return resolveClientIp({ remoteAddr: e }) ?? "unknown"; } /** Build an opaque limiter identity that is not subject to loopback IP exemptions. */ function buildRateLimitIdentityKey(e, t) { return `${IDENTITY_RATE_LIMIT_KEY_PREFIX}${e}:${t}`; } function resolvePruneIntervalMs(e) { if (e === void 0) return PRUNE_INTERVAL_MS; if (Number.isFinite(e) && e <= 0) return 0; return resolveTimerTimeoutMs(e, PRUNE_INTERVAL_MS); } function resolveAuthRateLimitPolicy(e) { return { maxAttempts: e?.maxAttempts ?? DEFAULT_MAX_ATTEMPTS, windowMs: resolveTimerTimeoutMs(e?.windowMs, DEFAULT_WINDOW_MS, 0), lockoutMs: resolveTimerTimeoutMs(e?.lockoutMs, DEFAULT_LOCKOUT_MS, 0), exemptLoopback: e?.exemptLoopback ?? true }; } function createGatewayAuthRateLimiter(e, { scheduler: t, id: n = "auth-rate-limit" }) { let r = resolveAuthRateLimitPolicy(e); const i = resolvePruneIntervalMs(e?.pruneIntervalMs); const a = resolveIntegerOption(e?.maxEntries, DEFAULT_MAX_ENTRIES, { min: 1 }); const o = /* @__PURE__ */ new Map(); const s = /* @__PURE__ */ new Map(); let c; let l = false; let u; function updatePruneJob() { if (o.size === 0) { u?.cancel(); u = void 0; } else if (!u && i > 0 && !l) u = t.schedule({ id: `${n}:prune`, atMs: t.now() + i, everyMs: i, run: prune }); } function resolveKey(e, t) { const n = normalizeRateLimitClientIp(e); return { key: `${t?.trim() || "default"}:${n}`, ip: n }; } function isExempt(e) { return r.exemptLoopback && isLoopbackAddress(e); } function refreshEntry(e, t) { if (e.lockedUntil && t >= e.lockedUntil) { e.lockedUntil = void 0; e.attempts = []; } const n = t - r.windowMs; e.attempts = e.attempts.filter((e) => e > n); } function check(e, n) { const { key: i, ip: a } = resolveKey(e, n); if (isExempt(a)) return { allowed: true, remaining: r.maxAttempts, retryAfterMs: 0 }; const s = t.now(); const c = o.get(i); if (!c) { const e = checkOverflowLock(s); if (e) return e; return { allowed: true, remaining: r.maxAttempts, retryAfterMs: 0 }; } refreshEntry(c, s); if (!c.lockedUntil && c.attempts.length >= r.maxAttempts) c.lockedUntil = s + r.lockoutMs; if (c.lockedUntil && s < c.lockedUntil) return { allowed: false, remaining: 0, retryAfterMs: c.lockedUntil - s }; const l = Math.max(0, r.maxAttempts - c.attempts.length); return { allowed: l > 0, remaining: l, retryAfterMs: 0 }; } function recordFailure(e, n) { const { key: i, ip: a } = resolveKey(e, n); const s = isExempt(a); const l = t.now(); let u = o.get(i); if (!u) { if (!enforceMaxEntries(l)) { c = Math.max(c ?? 0, l + r.lockoutMs); return; } u = { attempts: [] }; o.set(i, u); } if (!s && u.lockedUntil && l < u.lockedUntil) return; refreshEntry(u, l); u.attempts.push(l); if (s && u.attempts.length > LOOPBACK_FAILURE_HISTORY_LIMIT) u.attempts.splice(0, u.attempts.length - LOOPBACK_FAILURE_HISTORY_LIMIT); else if (!s && u.attempts.length >= r.maxAttempts) u.lockedUntil = l + r.lockoutMs; updatePruneJob(); } function recordFailureAndDelay(e, n) { if (l) return Promise.resolve(); const { key: r, ip: i } = resolveKey(e, n); recordFailure(e, n); if (!isExempt(i)) return Promise.resolve(); const a = o.get(r)?.attempts.length ?? 1; const c = Math.min(LOOPBACK_FAILURE_DELAY_BASE_MS * 2 ** Math.min(a - 1, 30), LOOPBACK_FAILURE_DELAY_MAX_MS); const u = t.now() + c; let d = s.get(r); if (!d) { d = { ...createDeferredCore(), deadline: u, timer: scheduleRelease(r, u) }; s.set(r, d); } else if (u > d.deadline) { d.deadline = u; clearTimeout(d.timer); d.timer = scheduleRelease(r, u); } return d.promise; } function scheduleRelease(e, n) { return setTimeout(() => releaseLoopbackWaiters(e), Math.max(0, n - t.now())).unref(); } function releaseLoopbackWaiters(e) { const t = s.get(e); if (!t) return; s.delete(e); clearTimeout(t.timer); t.resolve(); } function reset(e, t) { const { key: n } = resolveKey(e, t); o.delete(n); updatePruneJob(); } function pruneExpiredEntries(e) { for (const [t, n] of o) { if (n.lockedUntil && e < n.lockedUntil) continue; refreshEntry(n, e); if (n.attempts.length === 0) o.delete(t); } updatePruneJob(); } function checkOverflowLock(e) { if (!c) return; if (e >= c) { c = void 0; return; } if (o.size >= a) pruneExpiredEntries(e); if (o.size < a) { c = void 0; return; } return { allowed: false, remaining: 0, retryAfterMs: c - e }; } function enforceMaxEntries(e) { if (o.size < a) return true; pruneExpiredEntries(e); if (o.size < a) return true; for (const [t, n] of o) if (!n.lockedUntil || e >= n.lockedUntil) { o.delete(t); return true; } return false; } function prune() { pruneExpiredEntries(t.now()); } function size() { return o.size; } function dispose() { l = true; u?.cancel(); u = void 0; o.clear(); c = void 0; for (const e of s.keys()) releaseLoopbackWaiters(e); } const d = { check, recordFailure, recordFailureAndDelay, reset, size, prune, dispose, updateConfig: (e) => { r = resolveAuthRateLimitPolicy(e); } }; authRateLimiterExemptionChecks.set(d, (e) => isExempt(normalizeRateLimitClientIp(e))); return d; } //#endregion export { AUTH_RATE_LIMIT_SCOPE_HOOK_AUTH as a, AUTH_RATE_LIMIT_SCOPE_SHARED_SECRET as c, AUTH_RATE_LIMIT_SCOPE_WORKER_TRANSFER as d, buildRateLimitIdentityKey as f, normalizeRateLimitClientIp as h, AUTH_RATE_LIMIT_SCOPE_DEVICE_TOKEN as i, AUTH_RATE_LIMIT_SCOPE_WATCH_CHALLENGE as l, isAuthRateLimitClientExempt as m, AUTH_RATE_LIMIT_SCOPE_DEFAULT as n, AUTH_RATE_LIMIT_SCOPE_NODE_PAIRING as o, createGatewayAuthRateLimiter as p, AUTH_RATE_LIMIT_SCOPE_DEVICE_JOIN as r, AUTH_RATE_LIMIT_SCOPE_NODE_REAPPROVAL as s, AUTH_RATE_LIMIT_SCOPE_BOOTSTRAP_TOKEN as t, AUTH_RATE_LIMIT_SCOPE_WORKER_ADMISSION as u };