@chroxy/server 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CONFIG.md +695 -0
- package/README.md +105 -0
- package/hooks/permission-hook.sh +285 -0
- package/package.json +69 -0
- package/scripts/fix-node-pty-helper.js +44 -0
- package/sidecar/Dockerfile +40 -0
- package/sidecar/PROTOCOL.md +691 -0
- package/sidecar/agent.js +1290 -0
- package/sidecar/package-lock.json +43 -0
- package/sidecar/package.json +17 -0
- package/src/activity-registry.js +491 -0
- package/src/anthropic-compatible-config.js +534 -0
- package/src/anthropic-compatible-session.js +579 -0
- package/src/anthropic-openai-shim.js +109 -0
- package/src/anthropic-openai-translate.js +377 -0
- package/src/auth-probes.js +296 -0
- package/src/background-shell-tracker.js +320 -0
- package/src/background-shells.js +125 -0
- package/src/base-session.js +1518 -0
- package/src/billing-budget.js +191 -0
- package/src/billing-canary-monitor.js +203 -0
- package/src/billing-class.js +149 -0
- package/src/bind-host.js +82 -0
- package/src/built-in-tools/bash-exec.js +167 -0
- package/src/built-in-tools/file-ops.js +198 -0
- package/src/built-in-tools/tool-transforms.js +179 -0
- package/src/builtin-commands.js +107 -0
- package/src/byok-compose-state-shared.js +31 -0
- package/src/byok-compose-state.js +234 -0
- package/src/byok-credentials.js +127 -0
- package/src/byok-event-translator.js +136 -0
- package/src/byok-mcp-client.js +404 -0
- package/src/byok-mcp-config.js +159 -0
- package/src/byok-mcp-fleet.js +214 -0
- package/src/byok-mcp-trust.js +175 -0
- package/src/byok-session.js +2019 -0
- package/src/byok-subagent-profiles.js +101 -0
- package/src/byok-tool-executor.js +813 -0
- package/src/byok-tools.js +271 -0
- package/src/channels/PACKAGING.md +181 -0
- package/src/channels/README.md +99 -0
- package/src/channels/chroxy-channel-server.js +248 -0
- package/src/checkpoint-manager.js +515 -0
- package/src/child-stream-guard.js +38 -0
- package/src/claude-channel-session.js +185 -0
- package/src/claude-model-catalog.js +266 -0
- package/src/claude-stream-parser.js +106 -0
- package/src/claude-tui/form-driver.js +874 -0
- package/src/claude-tui/pty-driver.js +520 -0
- package/src/claude-tui/tested-cli-version.js +22 -0
- package/src/claude-tui-attachments.js +342 -0
- package/src/claude-tui-session.js +4029 -0
- package/src/cli/config-cmd.js +34 -0
- package/src/cli/credentials-cmd.js +59 -0
- package/src/cli/deploy-cmd.js +167 -0
- package/src/cli/doctor-cmd.js +52 -0
- package/src/cli/identity-cmd.js +82 -0
- package/src/cli/init-cmd.js +209 -0
- package/src/cli/pages-cmd.js +167 -0
- package/src/cli/pair-code-cmd.js +108 -0
- package/src/cli/pair-discord-cmd.js +100 -0
- package/src/cli/providers-cmd.js +168 -0
- package/src/cli/server-cmd.js +94 -0
- package/src/cli/service-cmd.js +237 -0
- package/src/cli/session-cmd.js +143 -0
- package/src/cli/shared.js +194 -0
- package/src/cli/shell-cmd.js +130 -0
- package/src/cli/status-cmd.js +204 -0
- package/src/cli/tunnel-cmd.js +101 -0
- package/src/cli/update-cmd.js +45 -0
- package/src/cli/worktree-gc-cmd.js +195 -0
- package/src/cli-session.js +1820 -0
- package/src/cli.js +60 -0
- package/src/codex-app-server-client.js +156 -0
- package/src/codex-app-server-session.js +572 -0
- package/src/codex-session.js +604 -0
- package/src/config.js +1757 -0
- package/src/connection-info.js +42 -0
- package/src/connection-locality.js +55 -0
- package/src/content-blocks.js +42 -0
- package/src/control-room/byok-pool.js +130 -0
- package/src/control-room/constants.js +26 -0
- package/src/control-room/containers.js +258 -0
- package/src/control-room/emulators.js +279 -0
- package/src/control-room/handler-factory.js +142 -0
- package/src/control-room/host-prune.js +387 -0
- package/src/control-room/integrations.js +929 -0
- package/src/control-room/repo-runtime-config.js +239 -0
- package/src/control-room/repo-set.js +162 -0
- package/src/control-room/runners.js +479 -0
- package/src/control-room/simulators.js +223 -0
- package/src/control-room/skills-inventory.js +303 -0
- package/src/control-room/survey.js +685 -0
- package/src/control-room/wsl.js +182 -0
- package/src/conversation-scanner.js +270 -0
- package/src/conversation-scope.js +52 -0
- package/src/conversation-search.js +216 -0
- package/src/cost-budget-manager.js +190 -0
- package/src/credential-cipher.js +179 -0
- package/src/credential-store.js +786 -0
- package/src/credential-test.js +145 -0
- package/src/credentials-file.js +58 -0
- package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +111 -0
- package/src/dashboard-next/dist/assets/index-DM-_dISG.css +1 -0
- package/src/dashboard-next/dist/index.html +13 -0
- package/src/deepseek-credentials.js +58 -0
- package/src/deepseek-session.js +192 -0
- package/src/detect-thinking-keyword.js +67 -0
- package/src/dev-preview.js +227 -0
- package/src/devcontainer-config.js +269 -0
- package/src/device-preferences.js +267 -0
- package/src/diagnostics.js +187 -0
- package/src/diff-parser.js +157 -0
- package/src/discord-credentials.js +188 -0
- package/src/discord-pair-delivery.js +113 -0
- package/src/docker-byok-pool-stats.js +221 -0
- package/src/docker-byok-pool.js +841 -0
- package/src/docker-byok-session.js +2172 -0
- package/src/docker-image-allowlist.js +99 -0
- package/src/docker-sdk-session.js +396 -0
- package/src/docker-session.js +382 -0
- package/src/doctor-billing.js +179 -0
- package/src/doctor.js +667 -0
- package/src/duration.js +77 -0
- package/src/environment-manager.js +753 -0
- package/src/environment-statuses.js +20 -0
- package/src/environments/backends/docker.js +931 -0
- package/src/environments/backends/k8s.js +3030 -0
- package/src/environments/backends/rancher.js +326 -0
- package/src/environments/backends/types.js +332 -0
- package/src/event-ingest.js +546 -0
- package/src/event-normalizer.js +1083 -0
- package/src/external-session-registry.js +0 -0
- package/src/file-store.js +52 -0
- package/src/gemini-session.js +498 -0
- package/src/get-public-ip.js +52 -0
- package/src/git.js +15 -0
- package/src/github-webhook.js +256 -0
- package/src/handler-utils.js +663 -0
- package/src/handlers/checkpoint-handlers.js +202 -0
- package/src/handlers/control-room-handlers.js +1945 -0
- package/src/handlers/conversation-handlers.js +201 -0
- package/src/handlers/credential-handlers.js +247 -0
- package/src/handlers/evaluator-handlers.js +94 -0
- package/src/handlers/feature-handlers.js +332 -0
- package/src/handlers/file-handlers.js +142 -0
- package/src/handlers/ide-handlers.js +238 -0
- package/src/handlers/input-handlers.js +1048 -0
- package/src/handlers/pairing-handlers.js +94 -0
- package/src/handlers/repo-handlers.js +295 -0
- package/src/handlers/session-handlers.js +660 -0
- package/src/handlers/settings-handlers.js +818 -0
- package/src/handlers/skills-handlers.js +682 -0
- package/src/handlers/summarize-handlers.js +172 -0
- package/src/handlers/token-handlers.js +57 -0
- package/src/http-oversize.js +51 -0
- package/src/http-routes.js +1158 -0
- package/src/ide/search.js +268 -0
- package/src/ide/symbols.js +423 -0
- package/src/ip-utils.js +85 -0
- package/src/json-state-file.js +169 -0
- package/src/jsonl-reader.js +187 -0
- package/src/jsonl-subprocess-session.js +441 -0
- package/src/keychain.js +458 -0
- package/src/lan-ip.js +38 -0
- package/src/logger.js +388 -0
- package/src/mailbox-route.js +252 -0
- package/src/mcp-tools.js +46 -0
- package/src/message-transform.js +102 -0
- package/src/metrics.js +67 -0
- package/src/model-discovery.js +288 -0
- package/src/models.js +1426 -0
- package/src/notification-prefs.js +544 -0
- package/src/notifications/discord-billing-sink.js +323 -0
- package/src/notifications/discord-webhook-client.js +187 -0
- package/src/notifications/discord-webhook-sink.js +768 -0
- package/src/notifications/expo-push-sink.js +414 -0
- package/src/notifications/ready-body.js +177 -0
- package/src/notifications/sink-registry.js +98 -0
- package/src/notifications/sink.js +82 -0
- package/src/ollama-session.js +221 -0
- package/src/ollama-tags.js +238 -0
- package/src/openai-compatible-session.js +118 -0
- package/src/pages-store.js +255 -0
- package/src/pairing.js +836 -0
- package/src/path-hash-trust-ledger.js +311 -0
- package/src/per-session-settings.js +366 -0
- package/src/permission-audit.js +120 -0
- package/src/permission-hook.js +257 -0
- package/src/permission-manager.js +829 -0
- package/src/permission-resolver.js +144 -0
- package/src/platform.js +139 -0
- package/src/prompt-evaluator.js +386 -0
- package/src/providers.js +436 -0
- package/src/push.js +565 -0
- package/src/rate-limiter.js +433 -0
- package/src/redaction.js +206 -0
- package/src/sdk-session.js +1773 -0
- package/src/semver.js +92 -0
- package/src/server-cli/push-notification-handler.js +240 -0
- package/src/server-cli/server-orchestrator.js +168 -0
- package/src/server-cli/startup-display.js +146 -0
- package/src/server-cli/tunnel-lifecycle-handler.js +219 -0
- package/src/server-cli-child.js +207 -0
- package/src/server-cli.js +1223 -0
- package/src/server-identity.js +383 -0
- package/src/service.js +835 -0
- package/src/session-context.js +49 -0
- package/src/session-lock.js +60 -0
- package/src/session-manager.js +3257 -0
- package/src/session-message-history.js +511 -0
- package/src/session-preset-trust.js +78 -0
- package/src/session-preset.js +458 -0
- package/src/session-state-persistence.js +307 -0
- package/src/session-timeout-manager.js +166 -0
- package/src/session-token-store.js +83 -0
- package/src/shell-approval-info.js +45 -0
- package/src/shell-approval-store.js +163 -0
- package/src/shell-audit.js +63 -0
- package/src/skills-budget.js +181 -0
- package/src/skills-content-validator.js +106 -0
- package/src/skills-frontmatter.js +422 -0
- package/src/skills-loader.js +1893 -0
- package/src/skills-manager.js +256 -0
- package/src/skills-trust.js +532 -0
- package/src/skills-usage.js +335 -0
- package/src/snapshots-store.js +345 -0
- package/src/ssrf-guard.js +130 -0
- package/src/subagent-counter.js +149 -0
- package/src/summarize-session.js +268 -0
- package/src/supervisor.js +929 -0
- package/src/test-client.js +131 -0
- package/src/token-compare.js +28 -0
- package/src/token-manager.js +220 -0
- package/src/tool-result.js +87 -0
- package/src/transcript-tasks.js +334 -0
- package/src/tunnel/base.js +294 -0
- package/src/tunnel/cloudflare.js +281 -0
- package/src/tunnel/index.js +54 -0
- package/src/tunnel-check.js +84 -0
- package/src/turn-tracker.js +0 -0
- package/src/user-shell-registry.js +218 -0
- package/src/user-shell-session.js +411 -0
- package/src/utils/check-dependencies.js +70 -0
- package/src/utils/concurrency.js +24 -0
- package/src/utils/context-window-learn.js +148 -0
- package/src/utils/error-message.js +25 -0
- package/src/utils/format-bytes.js +35 -0
- package/src/utils/preflight.js +143 -0
- package/src/utils/resolve-binary.js +91 -0
- package/src/utils/respawn-rate-limiter.js +59 -0
- package/src/utils/sleep.js +58 -0
- package/src/utils/spawn-env.js +193 -0
- package/src/utils/validation-patterns.js +23 -0
- package/src/utils/win-spawn.js +98 -0
- package/src/version-check.js +16 -0
- package/src/web-task-manager.js +383 -0
- package/src/worktree-gc.js +418 -0
- package/src/worktree-reaper.js +168 -0
- package/src/ws-auth.js +645 -0
- package/src/ws-broadcaster.js +385 -0
- package/src/ws-client-manager.js +476 -0
- package/src/ws-client-sender.js +115 -0
- package/src/ws-file-ops/browser.js +594 -0
- package/src/ws-file-ops/common.js +163 -0
- package/src/ws-file-ops/git.js +298 -0
- package/src/ws-file-ops/index.js +52 -0
- package/src/ws-file-ops/reader.js +595 -0
- package/src/ws-forwarding.js +543 -0
- package/src/ws-handler-context.js +196 -0
- package/src/ws-history.js +1251 -0
- package/src/ws-message-handlers.js +165 -0
- package/src/ws-permissions.js +676 -0
- package/src/ws-schemas.js +119 -0
- package/src/ws-server.js +2866 -0
|
@@ -0,0 +1,433 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Sliding-window rate limiter for WebSocket messages.
|
|
3
|
+
* Tracks per-client message timestamps to enforce rate limits.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { createLogger } from './logger.js'
|
|
7
|
+
|
|
8
|
+
// Loopback addresses used by cloudflared and local dev connections
|
|
9
|
+
export const LOOPBACK_ADDRESSES = new Set(['127.0.0.1', '::1', '::ffff:127.0.0.1'])
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Normalize a Node.js HTTP header value to a string.
|
|
13
|
+
* Node can represent repeated headers as string[] — take the first entry.
|
|
14
|
+
* @param {string|string[]|undefined} val
|
|
15
|
+
* @returns {string|undefined}
|
|
16
|
+
*/
|
|
17
|
+
function normalizeHeader(val) {
|
|
18
|
+
if (Array.isArray(val)) return val[0]
|
|
19
|
+
return val
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Extract the real client IP from an HTTP request.
|
|
24
|
+
* Prefers the CF-Connecting-IP header set by Cloudflare tunnels, which carry
|
|
25
|
+
* the original client IP even though the tunnel loopback address is 127.0.0.1.
|
|
26
|
+
* Falls back to X-Forwarded-For (first entry), then the raw socket address.
|
|
27
|
+
*
|
|
28
|
+
* SECURITY NOTE: CF-Connecting-IP and X-Forwarded-For are used here only for
|
|
29
|
+
* rate limiting, not for security decisions such as auth or encryption bypass.
|
|
30
|
+
* Those decisions must use req.socket.remoteAddress exclusively, which cannot
|
|
31
|
+
* be spoofed over the network.
|
|
32
|
+
*
|
|
33
|
+
* @param {object} req - Node.js IncomingMessage
|
|
34
|
+
* @returns {string}
|
|
35
|
+
*/
|
|
36
|
+
export function getClientIp(req) {
|
|
37
|
+
const headers = req?.headers || {}
|
|
38
|
+
const cfIp = normalizeHeader(headers['cf-connecting-ip'])
|
|
39
|
+
const xffRaw = normalizeHeader(headers['x-forwarded-for'])
|
|
40
|
+
const xffIp = xffRaw?.split(',')[0]?.trim()
|
|
41
|
+
return cfIp || xffIp || req?.socket?.remoteAddress || 'unknown'
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Return the key to use for rate limiting a connection.
|
|
46
|
+
*
|
|
47
|
+
* Proxy headers (CF-Connecting-IP, X-Forwarded-For) are only trusted when the
|
|
48
|
+
* TCP peer is a loopback address — i.e. the request arrived via the local
|
|
49
|
+
* cloudflared process or a trusted reverse proxy. For direct connections the
|
|
50
|
+
* socket address is used so an attacker cannot spoof the header to share (or
|
|
51
|
+
* exhaust) another IP's rate-limit bucket.
|
|
52
|
+
*
|
|
53
|
+
* @param {string} socketIp - req.socket.remoteAddress (kernel-supplied, not spoofable)
|
|
54
|
+
* @param {object} req - Node.js IncomingMessage (for proxy header extraction)
|
|
55
|
+
* @returns {string}
|
|
56
|
+
*/
|
|
57
|
+
export function getRateLimitKey(socketIp, req) {
|
|
58
|
+
if (LOOPBACK_ADDRESSES.has(socketIp)) {
|
|
59
|
+
// Connection came through a local proxy — trust the forwarded IP
|
|
60
|
+
return getClientIp(req)
|
|
61
|
+
}
|
|
62
|
+
// Direct connection — use the kernel-supplied address to prevent header spoofing
|
|
63
|
+
return socketIp || 'unknown'
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const DEFAULT_WINDOW_MS = 60_000 // 1 minute window
|
|
67
|
+
const DEFAULT_MAX_MESSAGES = 100 // max messages per window
|
|
68
|
+
const DEFAULT_BURST = 20 // burst allowance above max
|
|
69
|
+
// #3979: cap the per-client map size to prevent unbounded growth from
|
|
70
|
+
// source-IP rotation against HTTP limiters (no disconnect hook). 10k entries
|
|
71
|
+
// is well above realistic concurrent-client counts but still cheap to hold.
|
|
72
|
+
const DEFAULT_MAX_ENTRIES = 10_000
|
|
73
|
+
// #3997: opportunistic stale-reap budget. On every check() we scan up to
|
|
74
|
+
// this many existing entries (round-robin via a cursor across calls) and
|
|
75
|
+
// drop any whose newest timestamp is older than windowMs. Bounded scan
|
|
76
|
+
// keeps per-call cost O(1) so the map converges to the active-IP count
|
|
77
|
+
// under sweep workloads instead of waiting for the FIFO cap. 8 keeps the
|
|
78
|
+
// per-call overhead negligible; the cursor needs map.size / 8 calls to
|
|
79
|
+
// touch every entry (≈1250 calls at the default 10000-entry cap, fewer
|
|
80
|
+
// for smaller deployments). On a busy limiter that's seconds-to-minutes;
|
|
81
|
+
// on a quiet one stale entries will simply wait their turn — they're
|
|
82
|
+
// bounded by FIFO either way.
|
|
83
|
+
const STALE_SCAN_BUDGET = 8
|
|
84
|
+
// #3996: throttle eviction WARN logs so an attacker rotating IPs at line rate
|
|
85
|
+
// can't fill disk via a log line per evict. One line per minute per limiter
|
|
86
|
+
// is enough to give an operator the signal without a flood. The cumulative
|
|
87
|
+
// counter (_evictionCount) captures the full magnitude either way.
|
|
88
|
+
const DEFAULT_EVICTION_LOG_THROTTLE_MS = 60_000
|
|
89
|
+
// #4005: sliding window for the eviction-rate metric. 60s matches the default
|
|
90
|
+
// for a "is this happening RIGHT NOW?" alerting signal — short enough to fire
|
|
91
|
+
// during a live attack, long enough to absorb a stray multi-evict burst.
|
|
92
|
+
const DEFAULT_EVICTION_WINDOW_MS = 60_000
|
|
93
|
+
// #4005: hard cap on the eviction-timestamp buffer. An attacker rotating
|
|
94
|
+
// source IPs at line rate generates one eviction per spoofed IP — without a
|
|
95
|
+
// cap, the timestamp array would grow without bound (one int64-ish entry per
|
|
96
|
+
// evicted entry) and OOM the limiter. 1024 entries is well above any honest
|
|
97
|
+
// burst (the largest realistic burst is `maxEntries` itself, ~10k, but those
|
|
98
|
+
// are batched into one check() call and counted once for window purposes) and
|
|
99
|
+
// keeps the array footprint at ~8KB worst case. Past the cap we set a
|
|
100
|
+
// `_evictionWindowSaturated` flag instead of recording the timestamp;
|
|
101
|
+
// operators still see the cumulative counter for total volume.
|
|
102
|
+
const EVICTION_WINDOW_BUFFER_CAP = 1024
|
|
103
|
+
|
|
104
|
+
const _evictionLog = createLogger('rate-limit')
|
|
105
|
+
|
|
106
|
+
export class RateLimiter {
|
|
107
|
+
/**
|
|
108
|
+
* @param {Object} opts
|
|
109
|
+
* @param {number} opts.windowMs - Sliding window duration in ms
|
|
110
|
+
* @param {number} opts.maxMessages - Max messages per window
|
|
111
|
+
* @param {number} opts.burst - Burst allowance above maxMessages
|
|
112
|
+
* @param {number} [opts.maxEntries] - Cap on the per-client map size.
|
|
113
|
+
* When exceeded, the oldest entries (FIFO — by original insertion order,
|
|
114
|
+
* not last-access) are evicted lazily on `check()`. Must be a positive
|
|
115
|
+
* integer; invalid values fall back to the default. Defaults to 10000.
|
|
116
|
+
* See #3979.
|
|
117
|
+
* @param {string} [opts.name] - Optional identifier used in eviction log
|
|
118
|
+
* lines and getEvictionStats() so operators can tell which limiter is
|
|
119
|
+
* shedding entries (ws / permission / diagnostics / http-permission).
|
|
120
|
+
* See #3996.
|
|
121
|
+
* @param {number} [opts.evictionLogThrottleMs] - Min ms between eviction
|
|
122
|
+
* WARN log lines. The cumulative counter is unaffected — only the log
|
|
123
|
+
* is throttled. Defaults to 60000. See #3996.
|
|
124
|
+
* @param {number} [opts.evictionWindowMs] - Window length (ms) for the
|
|
125
|
+
* `evictionsInWindow` rate metric exposed by getEvictionStats(). Must be
|
|
126
|
+
* a positive integer; invalid values fall back to the default. Defaults
|
|
127
|
+
* to 60000 (1 minute). See #4005.
|
|
128
|
+
*/
|
|
129
|
+
constructor({ windowMs, maxMessages, burst, maxEntries, name, evictionLogThrottleMs, evictionWindowMs } = {}) {
|
|
130
|
+
this._windowMs = windowMs || DEFAULT_WINDOW_MS
|
|
131
|
+
this._maxMessages = maxMessages || DEFAULT_MAX_MESSAGES
|
|
132
|
+
this._burst = burst ?? DEFAULT_BURST
|
|
133
|
+
this._limit = this._maxMessages + this._burst
|
|
134
|
+
// Validate maxEntries: must be a positive integer. `||` would silently
|
|
135
|
+
// accept 0/NaN/-1 and disable the cap (or worse, make eviction
|
|
136
|
+
// unpredictable). Fall back to the default for any invalid input.
|
|
137
|
+
this._maxEntries = Number.isInteger(maxEntries) && maxEntries >= 1
|
|
138
|
+
? maxEntries
|
|
139
|
+
: DEFAULT_MAX_ENTRIES
|
|
140
|
+
this._clients = new Map() // clientId -> [timestamp, ...]
|
|
141
|
+
// #3997: round-robin cursor for the bounded stale-reap scan. Holds a
|
|
142
|
+
// live `Map.keys()` iterator; we pull up to STALE_SCAN_BUDGET keys from
|
|
143
|
+
// it on each check() and rebuild it when exhausted. Deleting the current
|
|
144
|
+
// key during iteration is safe (per spec, a deleted key is not
|
|
145
|
+
// revisited); newly-added keys appended after the cursor will be visited
|
|
146
|
+
// in a future call, which is exactly what we want.
|
|
147
|
+
this._scanCursor = null
|
|
148
|
+
// #3996: eviction observability. Counter is monotonic since instantiation
|
|
149
|
+
// (resets on process restart, like all in-process metrics). Log throttle
|
|
150
|
+
// suppresses lines but does NOT suppress the counter — operators get the
|
|
151
|
+
// full magnitude via /diagnostics regardless of log volume.
|
|
152
|
+
this._name = typeof name === 'string' && name.length > 0 ? name : 'unnamed'
|
|
153
|
+
this._evictionCount = 0
|
|
154
|
+
this._lastEvictionAt = null
|
|
155
|
+
this._lastEvictionLogAt = 0
|
|
156
|
+
this._evictionLogThrottleMs = Number.isInteger(evictionLogThrottleMs) && evictionLogThrottleMs >= 0
|
|
157
|
+
? evictionLogThrottleMs
|
|
158
|
+
: DEFAULT_EVICTION_LOG_THROTTLE_MS
|
|
159
|
+
// #4005: sliding-window eviction-rate metric. Buffer is pruned lazily on
|
|
160
|
+
// every getEvictionStats() call (entries older than _evictionWindowMs are
|
|
161
|
+
// dropped); pushes are capped at EVICTION_WINDOW_BUFFER_CAP so an attacker
|
|
162
|
+
// can't OOM the limiter via the rate history. When the cap is hit we set
|
|
163
|
+
// _evictionWindowSaturated and stop recording timestamps until the
|
|
164
|
+
// existing buffer drains — the cumulative _evictionCount keeps capturing
|
|
165
|
+
// the full magnitude in the meantime.
|
|
166
|
+
this._evictionWindowMs = Number.isInteger(evictionWindowMs) && evictionWindowMs >= 1
|
|
167
|
+
? evictionWindowMs
|
|
168
|
+
: DEFAULT_EVICTION_WINDOW_MS
|
|
169
|
+
this._evictionTimestamps = []
|
|
170
|
+
this._evictionWindowSaturated = false
|
|
171
|
+
this._lastSaturationAt = null
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* Check if a message from a client should be allowed.
|
|
176
|
+
* @param {string} clientId
|
|
177
|
+
* @returns {{ allowed: boolean, retryAfterMs?: number }}
|
|
178
|
+
*/
|
|
179
|
+
check(clientId) {
|
|
180
|
+
const now = Date.now()
|
|
181
|
+
const windowStart = now - this._windowMs
|
|
182
|
+
|
|
183
|
+
// #3997: opportunistic bounded stale-reap. Sweep a small slice of
|
|
184
|
+
// existing entries (cursor-resumed across calls) and drop any whose
|
|
185
|
+
// newest timestamp has expired. Runs on every check() — including
|
|
186
|
+
// repeat calls from a hot client — so the map converges to the active
|
|
187
|
+
// set under any workload, not just new-IP inserts. Bounded scan keeps
|
|
188
|
+
// the per-call cost O(1) regardless of map size.
|
|
189
|
+
this._reapStaleEntries(windowStart, clientId)
|
|
190
|
+
|
|
191
|
+
let timestamps = this._clients.get(clientId)
|
|
192
|
+
if (!timestamps) {
|
|
193
|
+
// #3979: evict oldest entries (FIFO — by ORIGINAL insertion order,
|
|
194
|
+
// a Map guarantee — NOT last-access; entries are not re-inserted on
|
|
195
|
+
// check). Runs before inserting a new key so map.size never exceeds
|
|
196
|
+
// maxEntries. Lazy: only runs on inserts that would push us over.
|
|
197
|
+
let evictedThisCheck = 0
|
|
198
|
+
while (this._clients.size >= this._maxEntries) {
|
|
199
|
+
const oldestKey = this._clients.keys().next().value
|
|
200
|
+
if (oldestKey === undefined) break
|
|
201
|
+
this._clients.delete(oldestKey)
|
|
202
|
+
evictedThisCheck++
|
|
203
|
+
}
|
|
204
|
+
// #3996: meter eviction events for operator visibility. Counter is
|
|
205
|
+
// unconditional (so /diagnostics sees every evict even under log
|
|
206
|
+
// throttle); log line is throttled to avoid disk fill under
|
|
207
|
+
// sustained source-IP rotation.
|
|
208
|
+
if (evictedThisCheck > 0) {
|
|
209
|
+
this._evictionCount += evictedThisCheck
|
|
210
|
+
this._lastEvictionAt = now
|
|
211
|
+
this._recordEvictionsInWindow(now, evictedThisCheck)
|
|
212
|
+
this._maybeLogEviction(now, evictedThisCheck)
|
|
213
|
+
}
|
|
214
|
+
timestamps = []
|
|
215
|
+
this._clients.set(clientId, timestamps)
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
// Prune expired timestamps
|
|
219
|
+
while (timestamps.length > 0 && timestamps[0] <= windowStart) {
|
|
220
|
+
timestamps.shift()
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
if (timestamps.length >= this._limit) {
|
|
224
|
+
// Calculate when the oldest message in the window will expire
|
|
225
|
+
const retryAfterMs = Math.max(1, timestamps[0] - windowStart)
|
|
226
|
+
return { allowed: false, retryAfterMs }
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
timestamps.push(now)
|
|
230
|
+
return { allowed: true }
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/**
|
|
234
|
+
* #3997: opportunistically drop a small bounded slice of stale entries
|
|
235
|
+
* (those whose newest timestamp has fallen outside the window). Uses a
|
|
236
|
+
* persistent cursor so successive calls round-robin through the map
|
|
237
|
+
* instead of re-scanning the same prefix. Bounded by STALE_SCAN_BUDGET
|
|
238
|
+
* to keep the per-call cost O(1) regardless of map size.
|
|
239
|
+
*
|
|
240
|
+
* The caller's own key is preserved here even if it looks stale: the
|
|
241
|
+
* subsequent prune-then-push in check() will refresh its timestamp, and
|
|
242
|
+
* deleting + re-inserting would also disrupt the FIFO insertion-order
|
|
243
|
+
* the #3979 LRU eviction relies on.
|
|
244
|
+
*
|
|
245
|
+
* @param {number} windowStart - now - windowMs; entries whose newest
|
|
246
|
+
* timestamp is <= windowStart are considered stale and removed.
|
|
247
|
+
* @param {string} callerKey - skip this key (the active client) so its
|
|
248
|
+
* bucket is not deleted out from under the pending check().
|
|
249
|
+
* @private
|
|
250
|
+
*/
|
|
251
|
+
_reapStaleEntries(windowStart, callerKey) {
|
|
252
|
+
let scanned = 0
|
|
253
|
+
while (scanned < STALE_SCAN_BUDGET && this._clients.size > 0) {
|
|
254
|
+
if (!this._scanCursor) {
|
|
255
|
+
this._scanCursor = this._clients.keys()
|
|
256
|
+
}
|
|
257
|
+
const next = this._scanCursor.next()
|
|
258
|
+
if (next.done) {
|
|
259
|
+
// Exhausted — restart on the next call so we keep walking the map
|
|
260
|
+
this._scanCursor = null
|
|
261
|
+
break
|
|
262
|
+
}
|
|
263
|
+
scanned++
|
|
264
|
+
const key = next.value
|
|
265
|
+
if (key === callerKey) continue
|
|
266
|
+
const ts = this._clients.get(key)
|
|
267
|
+
// Stale if the bucket is empty or its newest entry is outside the
|
|
268
|
+
// window. Checking the LAST element is O(1) and sufficient: timestamps
|
|
269
|
+
// are appended in order, so if the newest is expired the rest are too.
|
|
270
|
+
if (!ts || ts.length === 0 || ts[ts.length - 1] <= windowStart) {
|
|
271
|
+
this._clients.delete(key)
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/**
|
|
277
|
+
* Remove a client's tracking data (on disconnect).
|
|
278
|
+
* @param {string} clientId
|
|
279
|
+
*/
|
|
280
|
+
remove(clientId) {
|
|
281
|
+
this._clients.delete(clientId)
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
/**
|
|
285
|
+
* Clear all tracking data.
|
|
286
|
+
*/
|
|
287
|
+
clear() {
|
|
288
|
+
this._clients.clear()
|
|
289
|
+
// Cursor points into the now-empty map; drop it so the next reap
|
|
290
|
+
// starts a fresh iterator over whatever the map holds at that point.
|
|
291
|
+
this._scanCursor = null
|
|
292
|
+
// #4005: drain the rate-window buffer alongside the per-client map.
|
|
293
|
+
// The cumulative _evictionCount stays put — it's the long-lived
|
|
294
|
+
// /diagnostics signal and only resets on process restart (see #3996).
|
|
295
|
+
this._evictionTimestamps.length = 0
|
|
296
|
+
this._evictionWindowSaturated = false
|
|
297
|
+
this._lastSaturationAt = null
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
/**
|
|
301
|
+
* Snapshot of eviction observability state for /diagnostics (#3996, #4005).
|
|
302
|
+
*
|
|
303
|
+
* - `evictionCount` — cumulative entries evicted since instantiation.
|
|
304
|
+
* Monotonic; resets only on process restart. Non-zero is the signal
|
|
305
|
+
* that the limiter is shedding entries (likely source-IP rotation).
|
|
306
|
+
* - `lastEvictionAt` — wall-clock ms of the most recent eviction, or
|
|
307
|
+
* null if none has occurred. Lets ops correlate against incident
|
|
308
|
+
* timestamps in the log tail.
|
|
309
|
+
* - `mapSize` / `maxEntries` — current vs. cap. Steady-state at the cap
|
|
310
|
+
* with a non-zero `evictionCount` is the textbook attack signature.
|
|
311
|
+
* - `name` — identifier passed to the constructor (ws / permission /
|
|
312
|
+
* diagnostics / http-permission); makes the snapshot self-describing
|
|
313
|
+
* when callers serialise multiple limiters into one payload.
|
|
314
|
+
* - `evictionsInWindow` — count of evictions in the last `evictionWindowMs`.
|
|
315
|
+
* Answers "is this happening RIGHT NOW?" — pair with `evictionCount`
|
|
316
|
+
* (which only tells you "has this ever happened?") for live alerting.
|
|
317
|
+
* Pruned lazily on every call to this method. See #4005.
|
|
318
|
+
* - `evictionWindowMs` — the actual window length used for
|
|
319
|
+
* `evictionsInWindow`. Surfaced for transparency so /diagnostics
|
|
320
|
+
* consumers can render "X evictions in the last Y minutes" without
|
|
321
|
+
* hard-coding the window.
|
|
322
|
+
* - `evictionWindowSaturated` — true when the in-window timestamp buffer
|
|
323
|
+
* has hit its hard cap (EVICTION_WINDOW_BUFFER_CAP). Indicates the
|
|
324
|
+
* eviction rate exceeded what the rate-history ring can hold and the
|
|
325
|
+
* `evictionsInWindow` value is a floor, not the true count. The
|
|
326
|
+
* cumulative `evictionCount` still captures full magnitude. Clears
|
|
327
|
+
* automatically once the buffer drains.
|
|
328
|
+
*
|
|
329
|
+
* @returns {{ name: string, evictionCount: number, lastEvictionAt: number|null, mapSize: number, maxEntries: number, evictionsInWindow: number, evictionWindowMs: number, evictionWindowSaturated: boolean }}
|
|
330
|
+
*/
|
|
331
|
+
getEvictionStats() {
|
|
332
|
+
const now = Date.now()
|
|
333
|
+
this._pruneEvictionWindow(now)
|
|
334
|
+
return {
|
|
335
|
+
name: this._name,
|
|
336
|
+
evictionCount: this._evictionCount,
|
|
337
|
+
lastEvictionAt: this._lastEvictionAt,
|
|
338
|
+
mapSize: this._clients.size,
|
|
339
|
+
maxEntries: this._maxEntries,
|
|
340
|
+
evictionsInWindow: this._evictionTimestamps.length,
|
|
341
|
+
evictionWindowMs: this._evictionWindowMs,
|
|
342
|
+
evictionWindowSaturated: this._evictionWindowSaturated,
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
/**
|
|
347
|
+
* #4005: append `count` eviction timestamps (all at `now`) to the rate
|
|
348
|
+
* window, capped at EVICTION_WINDOW_BUFFER_CAP. When the cap is hit we
|
|
349
|
+
* stop recording and set `_evictionWindowSaturated` — the cumulative
|
|
350
|
+
* `_evictionCount` keeps capturing magnitude, and the saturated flag
|
|
351
|
+
* tells operators the rate metric is a floor rather than exact.
|
|
352
|
+
*
|
|
353
|
+
* @param {number} now - Current Date.now() value (passed in to avoid a
|
|
354
|
+
* second clock read on the hot path).
|
|
355
|
+
* @param {number} count - Number of evictions to record (>= 1).
|
|
356
|
+
* @private
|
|
357
|
+
*/
|
|
358
|
+
_recordEvictionsInWindow(now, count) {
|
|
359
|
+
// Prune first so the cap reflects only entries currently in the window.
|
|
360
|
+
// Without this prune a bursty workload could trip saturation while the
|
|
361
|
+
// tail of the buffer was already stale.
|
|
362
|
+
this._pruneEvictionWindow(now)
|
|
363
|
+
const headroom = EVICTION_WINDOW_BUFFER_CAP - this._evictionTimestamps.length
|
|
364
|
+
if (count <= headroom) {
|
|
365
|
+
for (let i = 0; i < count; i++) this._evictionTimestamps.push(now)
|
|
366
|
+
return
|
|
367
|
+
}
|
|
368
|
+
// Fill any remaining headroom and mark the buffer saturated. Anything
|
|
369
|
+
// past the cap is intentionally dropped — the saturated flag plus the
|
|
370
|
+
// monotonic counter give operators the signal they need without
|
|
371
|
+
// unbounded memory growth. Track WHEN we saturated so the prune step
|
|
372
|
+
// can clear the flag once that event has aged out of the window —
|
|
373
|
+
// otherwise low-rate evictions continuing after a burst would keep
|
|
374
|
+
// the buffer non-empty and the flag stuck true forever, misleading
|
|
375
|
+
// diagnostics long after the actual saturation event.
|
|
376
|
+
for (let i = 0; i < headroom; i++) this._evictionTimestamps.push(now)
|
|
377
|
+
this._evictionWindowSaturated = true
|
|
378
|
+
this._lastSaturationAt = now
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
/**
|
|
382
|
+
* #4005: drop eviction timestamps that have aged past the rate window.
|
|
383
|
+
* Buffer is append-only and append-monotonic in `now`, so a leading-edge
|
|
384
|
+
* scan is O(k) in the number of expired entries — not O(N) every call.
|
|
385
|
+
* Also clears the saturated flag once the buffer empties: a saturated
|
|
386
|
+
* limiter that's drained is no longer suppressing data.
|
|
387
|
+
*
|
|
388
|
+
* @param {number} now - Current Date.now() value.
|
|
389
|
+
* @private
|
|
390
|
+
*/
|
|
391
|
+
_pruneEvictionWindow(now) {
|
|
392
|
+
const cutoff = now - this._evictionWindowMs
|
|
393
|
+
let drop = 0
|
|
394
|
+
while (drop < this._evictionTimestamps.length && this._evictionTimestamps[drop] <= cutoff) {
|
|
395
|
+
drop++
|
|
396
|
+
}
|
|
397
|
+
if (drop > 0) this._evictionTimestamps.splice(0, drop)
|
|
398
|
+
// Clear the saturation flag once the saturation event itself has aged
|
|
399
|
+
// past the window — at that point the count over the window IS
|
|
400
|
+
// accurate again regardless of buffer occupancy. Pre-fix, this only
|
|
401
|
+
// cleared on an empty buffer, so low-rate evictions following a
|
|
402
|
+
// burst could keep the flag stuck true indefinitely.
|
|
403
|
+
if (this._evictionWindowSaturated &&
|
|
404
|
+
(this._lastSaturationAt === null || this._lastSaturationAt <= cutoff)) {
|
|
405
|
+
this._evictionWindowSaturated = false
|
|
406
|
+
this._lastSaturationAt = null
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
/**
|
|
411
|
+
* Emit a throttled WARN log on eviction. Throttle is per-limiter — each
|
|
412
|
+
* limiter instance gets at most one line per `_evictionLogThrottleMs`
|
|
413
|
+
* regardless of how many entries are dropped in that window. The
|
|
414
|
+
* cumulative counter (_evictionCount) is the source of truth for total
|
|
415
|
+
* volume; the log line is just for operator visibility / alerting.
|
|
416
|
+
*
|
|
417
|
+
* @param {number} now - Current Date.now() value (passed in to avoid a
|
|
418
|
+
* second clock read on the hot path).
|
|
419
|
+
* @param {number} count - Number of entries evicted in the triggering
|
|
420
|
+
* check() call. Reported in the log line so a single line can convey
|
|
421
|
+
* "burst of 137 evictions" rather than just "an eviction happened."
|
|
422
|
+
* @private
|
|
423
|
+
*/
|
|
424
|
+
_maybeLogEviction(now, count) {
|
|
425
|
+
if (now - this._lastEvictionLogAt < this._evictionLogThrottleMs) return
|
|
426
|
+
this._lastEvictionLogAt = now
|
|
427
|
+
_evictionLog.warn(
|
|
428
|
+
`evicted ${count} oldest entr${count === 1 ? 'y' : 'ies'} from limiter ` +
|
|
429
|
+
`name=${this._name} (cumulative=${this._evictionCount}, mapSize=${this._clients.size}/${this._maxEntries}). ` +
|
|
430
|
+
'Likely source-IP rotation — see #3979/#3996.'
|
|
431
|
+
)
|
|
432
|
+
}
|
|
433
|
+
}
|
package/src/redaction.js
ADDED
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared secret-redaction primitives.
|
|
3
|
+
*
|
|
4
|
+
* Single source of truth for the value-SHAPE patterns (#6029). Previously the
|
|
5
|
+
* tool-broadcast sanitizer (ws-permissions.js) redacted by KEY NAME only, so a
|
|
6
|
+
* secret embedded in a value under a benign key — e.g.
|
|
7
|
+
* `{ command: 'export TOKEN=sk-ant-api03-…' }` or
|
|
8
|
+
* `{ url: 'https://discord.com/api/webhooks/…' }` — was broadcast verbatim to
|
|
9
|
+
* every subscribed client. The value patterns lived only in logger.js; this
|
|
10
|
+
* module hoists them so the broadcast path and the logger share one definition.
|
|
11
|
+
*
|
|
12
|
+
* - `SENSITIVE_PATTERNS` / `API_KEY_PATTERNS` — the value-shape regexes.
|
|
13
|
+
* - `redactValue(str)` — apply both pattern sets to a string (the logger's
|
|
14
|
+
* existing redaction behavior, hoisted verbatim).
|
|
15
|
+
* - `SENSITIVE_KEY_NAMES` — the key-NAME set used by the broadcast sanitizer.
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
// Sensitive patterns to redact from strings.
|
|
19
|
+
const SENSITIVE_PATTERNS = [
|
|
20
|
+
// Bearer tokens in headers
|
|
21
|
+
/Bearer\s+[A-Za-z0-9_\-./+=]{8,}/gi,
|
|
22
|
+
// API tokens (base64url, UUID, hex) after common key names
|
|
23
|
+
/(?:token|password|secret|apiKey|api_key|authorization|credential|private_key)\s*[:=]\s*["']?[A-Za-z0-9_\-./+=]{8,}["']?/gi,
|
|
24
|
+
]
|
|
25
|
+
|
|
26
|
+
// Provider API key patterns (#2961). These run separately so we can emit a
|
|
27
|
+
// bare "[REDACTED]" regardless of any surrounding key/value syntax — the raw
|
|
28
|
+
// key often appears mid-sentence in stderr (e.g., "invalid api key sk-...").
|
|
29
|
+
// Length floors are tuned to avoid false positives on short identifiers like
|
|
30
|
+
// product SKUs or the literal word "AIzawa".
|
|
31
|
+
const API_KEY_PATTERNS = [
|
|
32
|
+
// Anthropic: sk-ant-api03-... (checked before generic sk- so the longer
|
|
33
|
+
// prefix wins). Real keys are well over 40 trailing chars.
|
|
34
|
+
/\bsk-ant-(?:api\d{2}-)?[A-Za-z0-9_-]{40,}/g,
|
|
35
|
+
// OpenAI project-scoped keys: sk-proj-... (typically 40+ chars after prefix)
|
|
36
|
+
/\bsk-proj-[A-Za-z0-9_-]{40,}/g,
|
|
37
|
+
// OpenAI legacy secret keys: sk- followed by 40+ chars. Must not match
|
|
38
|
+
// sk-ant- / sk-proj- (already handled above) — negative lookahead keeps
|
|
39
|
+
// them from being partially redacted.
|
|
40
|
+
/\bsk-(?!ant-|proj-)[A-Za-z0-9]{40,}/g,
|
|
41
|
+
// Google API keys: AIza + exactly 35 chars of [A-Za-z0-9_-].
|
|
42
|
+
// Trailing \b prevents matching into longer alphanumerics (e.g., AIzawa…).
|
|
43
|
+
/\bAIza[A-Za-z0-9_-]{35}\b/g,
|
|
44
|
+
// #5358: JWTs (incl. claude/OAuth bearer JWTs printed without a "Bearer"/key
|
|
45
|
+
// marker). header.payload.signature, each base64url; the header always starts
|
|
46
|
+
// `eyJ` (base64 of `{"`), which makes this specific enough to avoid matching
|
|
47
|
+
// ordinary dotted tokens. Length floors keep it off short `a.b.c` strings.
|
|
48
|
+
/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/g,
|
|
49
|
+
// #5413: Discord webhook URLs. The token segment after the numeric webhook
|
|
50
|
+
// id grants post/edit/delete on the channel, so the URL is a credential.
|
|
51
|
+
// Covers discordapp.com (legacy), ptb/canary builds, and optional /vN/ API
|
|
52
|
+
// version segments; anything after the token (e.g. /messages/<id>) is left
|
|
53
|
+
// intact. Real webhook tokens are 60+ chars; the 20 floor keeps doc
|
|
54
|
+
// placeholders like .../webhooks/123/abc readable while catching any
|
|
55
|
+
// plausible real token.
|
|
56
|
+
/\bhttps:\/\/(?:ptb\.|canary\.)?discord(?:app)?\.com\/api\/(?:v\d+\/)?webhooks\/\d+\/[A-Za-z0-9_-]{20,}/g,
|
|
57
|
+
]
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Key NAMES whose VALUE is always a secret (the broadcast sanitizer redacts
|
|
61
|
+
* these wholesale regardless of value shape). Kept here so the broadcast path
|
|
62
|
+
* and any other consumer share one list.
|
|
63
|
+
*/
|
|
64
|
+
const SENSITIVE_KEY_NAMES = new Set([
|
|
65
|
+
'token', 'password', 'apikey', 'secret', 'authorization',
|
|
66
|
+
'credential', 'private_key', 'api_key',
|
|
67
|
+
])
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Redact secret-shaped substrings from a string value. This is the logger's
|
|
71
|
+
* existing redaction behavior, hoisted so the tool-broadcast path reuses the
|
|
72
|
+
* exact same patterns and replacement rules.
|
|
73
|
+
*
|
|
74
|
+
* - `SENSITIVE_PATTERNS` keep the key name and redact only the value.
|
|
75
|
+
* - `API_KEY_PATTERNS` redact the whole match (bare `[REDACTED]`).
|
|
76
|
+
*
|
|
77
|
+
* @param {string} msg
|
|
78
|
+
* @returns {string}
|
|
79
|
+
*/
|
|
80
|
+
export function redactValue(msg) {
|
|
81
|
+
let result = msg
|
|
82
|
+
for (const pattern of SENSITIVE_PATTERNS) {
|
|
83
|
+
result = result.replace(pattern, (match) => {
|
|
84
|
+
// Keep the key name, redact the value
|
|
85
|
+
const colonIdx = match.indexOf(':')
|
|
86
|
+
const eqIdx = match.indexOf('=')
|
|
87
|
+
const sepIdx = colonIdx >= 0 ? (eqIdx >= 0 ? Math.min(colonIdx, eqIdx) : colonIdx) : eqIdx
|
|
88
|
+
if (sepIdx >= 0) {
|
|
89
|
+
return match.slice(0, sepIdx + 1) + ' [REDACTED]'
|
|
90
|
+
}
|
|
91
|
+
// For Bearer tokens
|
|
92
|
+
if (match.startsWith('Bearer')) return 'Bearer [REDACTED]'
|
|
93
|
+
return '[REDACTED]'
|
|
94
|
+
})
|
|
95
|
+
}
|
|
96
|
+
for (const pattern of API_KEY_PATTERNS) {
|
|
97
|
+
result = result.replace(pattern, '[REDACTED]')
|
|
98
|
+
}
|
|
99
|
+
return result
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
// -- Broadcast safety (#6029) --
|
|
103
|
+
// Relocated here (#6038) from ws-permissions.js so both broadcast paths — the
|
|
104
|
+
// hook path (ws-permissions.js) AND the SDK/TUI provider path
|
|
105
|
+
// (permission-manager.js) — share one sanitizer. This is a leaf module, so
|
|
106
|
+
// permission-manager.js can import it without pulling in the HTTP-handler stack
|
|
107
|
+
// or risking an import cycle.
|
|
108
|
+
const MAX_INPUT_CHARS = 10_240 // ~10K chars max for broadcast (JS string length, not bytes)
|
|
109
|
+
|
|
110
|
+
// Cap recursion so a pathologically deep or cyclic tool_input can't blow the
|
|
111
|
+
// stack. Real tool inputs are shallow; anything past this is summarized away.
|
|
112
|
+
const MAX_SANITIZE_DEPTH = 8
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Recursively redact a single tool_input value of any shape (#6029). Applies the
|
|
116
|
+
* KEY-NAME pass to object keys and the VALUE-SHAPE pass (`redactValue`) to every
|
|
117
|
+
* string at any depth, so a secret nested inside an object or array — e.g.
|
|
118
|
+
* `{ env: { TOKEN: 'sk-ant-…' } }`, `{ args: ['--token', 'sk-ant-…'] }`, or
|
|
119
|
+
* `{ headers: { Authorization: 'Bearer …' } }` — can't slip past the top-level
|
|
120
|
+
* scan. `seen` guards against cycles; `depth` caps pathological nesting.
|
|
121
|
+
*
|
|
122
|
+
* @param {*} value
|
|
123
|
+
* @param {number} depth
|
|
124
|
+
* @param {WeakSet} seen
|
|
125
|
+
* @returns {*}
|
|
126
|
+
*/
|
|
127
|
+
function redactDeep(value, depth, seen, maxChars = MAX_INPUT_CHARS) {
|
|
128
|
+
if (typeof value === 'string') {
|
|
129
|
+
const redacted = redactValue(value)
|
|
130
|
+
return redacted.length > maxChars
|
|
131
|
+
? redacted.slice(0, maxChars) + '... [truncated]'
|
|
132
|
+
: redacted
|
|
133
|
+
}
|
|
134
|
+
if (!value || typeof value !== 'object') return value
|
|
135
|
+
if (depth >= MAX_SANITIZE_DEPTH) return '[REDACTED:depth]'
|
|
136
|
+
if (seen.has(value)) return '[REDACTED:cycle]'
|
|
137
|
+
seen.add(value)
|
|
138
|
+
let out
|
|
139
|
+
if (Array.isArray(value)) {
|
|
140
|
+
out = value.map((item) => redactDeep(item, depth + 1, seen, maxChars))
|
|
141
|
+
} else {
|
|
142
|
+
out = {}
|
|
143
|
+
for (const [key, child] of Object.entries(value)) {
|
|
144
|
+
out[key] = SENSITIVE_KEY_NAMES.has(key.toLowerCase())
|
|
145
|
+
? '[REDACTED]'
|
|
146
|
+
: redactDeep(child, depth + 1, seen, maxChars)
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
seen.delete(value)
|
|
150
|
+
return out
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* Sanitize tool input for broadcast: redact sensitive fields and truncate large
|
|
155
|
+
* values. Two passes (#6029): a KEY-NAME pass redacts values under sensitive
|
|
156
|
+
* keys wholesale, and a VALUE-SHAPE pass runs every string value (at ANY depth)
|
|
157
|
+
* through `redactValue` so a secret embedded under a benign key — e.g.
|
|
158
|
+
* `{ command: 'export TOKEN=sk-ant-…' }`, `{ url: 'https://discord.com/api/webhooks/…' }`,
|
|
159
|
+
* or nested in `{ env: { TOKEN: 'sk-ant-…' } }` / `{ args: ['--token', 'sk-ant-…'] }`
|
|
160
|
+
* — is redacted before it reaches any client. Both passes recurse through nested
|
|
161
|
+
* objects and arrays.
|
|
162
|
+
*
|
|
163
|
+
* The `maxChars` cap governs BOTH the per-string truncation and the whole-object
|
|
164
|
+
* summary fallback. It defaults to `MAX_INPUT_CHARS` (the ~10K broadcast cap), so
|
|
165
|
+
* every existing broadcast caller is byte-for-byte unchanged. The pull path
|
|
166
|
+
* (#6543 `get_permission_input`, which needs the FULL content to build a
|
|
167
|
+
* pre-write diff) passes a larger `maxChars` (`PULL_MAX_INPUT_CHARS`) — for an
|
|
168
|
+
* object input (which every real tool_input is), the secret-stripping passes
|
|
169
|
+
* (KEY-NAME + VALUE-SHAPE) run on every value regardless of the cap, so a higher
|
|
170
|
+
* cap never weakens redaction, only the truncation threshold. A non-object input
|
|
171
|
+
* is returned as-is (there is nothing to key/redact); callers always pass the
|
|
172
|
+
* tool_input object.
|
|
173
|
+
*
|
|
174
|
+
* @param {object} input
|
|
175
|
+
* @param {{ maxChars?: number }} [opts]
|
|
176
|
+
* @returns {object}
|
|
177
|
+
*/
|
|
178
|
+
function sanitizeToolInput(input, { maxChars = MAX_INPUT_CHARS } = {}) {
|
|
179
|
+
if (!input || typeof input !== 'object') return input
|
|
180
|
+
|
|
181
|
+
const seen = new WeakSet()
|
|
182
|
+
const result = {}
|
|
183
|
+
for (const [key, value] of Object.entries(input)) {
|
|
184
|
+
result[key] = SENSITIVE_KEY_NAMES.has(key.toLowerCase())
|
|
185
|
+
? '[REDACTED]'
|
|
186
|
+
: redactDeep(value, 1, seen, maxChars)
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
// Final size check on the whole object
|
|
190
|
+
const serialized = JSON.stringify(result)
|
|
191
|
+
if (serialized.length > maxChars) {
|
|
192
|
+
return { _truncated: true, summary: serialized.slice(0, maxChars) + '... [truncated]' }
|
|
193
|
+
}
|
|
194
|
+
return result
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/**
|
|
198
|
+
* #6543: the truncation cap for the `get_permission_input` PULL path — the
|
|
199
|
+
* client needs the un-broadcast-truncated (but still secret-redacted) tool input
|
|
200
|
+
* to build a full pre-write diff. Generous enough for any realistic file edit,
|
|
201
|
+
* bounded so a pathological input can't blast the wire (the diff falls back to a
|
|
202
|
+
* whole-file view past `computeHunks`'s own line guard anyway).
|
|
203
|
+
*/
|
|
204
|
+
const PULL_MAX_INPUT_CHARS = 512 * 1024 // 512K chars
|
|
205
|
+
|
|
206
|
+
export { SENSITIVE_PATTERNS, API_KEY_PATTERNS, SENSITIVE_KEY_NAMES, sanitizeToolInput, PULL_MAX_INPUT_CHARS, MAX_INPUT_CHARS }
|