@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,216 @@
|
|
|
1
|
+
import { readdir, stat, readFile, open } from 'fs/promises'
|
|
2
|
+
import { join, basename } from 'path'
|
|
3
|
+
import { homedir } from 'os'
|
|
4
|
+
import { decodeProjectPath } from './jsonl-reader.js'
|
|
5
|
+
import { runWithConcurrency } from './utils/concurrency.js'
|
|
6
|
+
|
|
7
|
+
const PROJECTS_DIR = join(homedir(), '.claude', 'projects')
|
|
8
|
+
const MIN_FILE_SIZE = 100
|
|
9
|
+
const CONCURRENCY = 10
|
|
10
|
+
const MAX_FILE_READ = 512 * 1024 // read up to 512KB per file for search
|
|
11
|
+
const DEFAULT_MAX_RESULTS = 50
|
|
12
|
+
// #6448 — bound the query length: every candidate file is substring-scanned for
|
|
13
|
+
// the query, so an absurdly long query is a CPU DoS. 500 chars is far beyond any
|
|
14
|
+
// real search.
|
|
15
|
+
const MAX_QUERY_LENGTH = 500
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Extract searchable text from a JSONL entry.
|
|
19
|
+
* Returns a plain string combining all readable text content.
|
|
20
|
+
*/
|
|
21
|
+
export function extractSearchableText(entry) {
|
|
22
|
+
if (!entry || !entry.type) return ''
|
|
23
|
+
|
|
24
|
+
const parts = []
|
|
25
|
+
|
|
26
|
+
if (entry.message?.content) {
|
|
27
|
+
const content = entry.message.content
|
|
28
|
+
if (typeof content === 'string') {
|
|
29
|
+
parts.push(content)
|
|
30
|
+
} else if (Array.isArray(content)) {
|
|
31
|
+
for (const block of content) {
|
|
32
|
+
if (block.type === 'text' && block.text) {
|
|
33
|
+
parts.push(block.text)
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
return parts.join(' ')
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Search a single JSONL conversation file for a query string.
|
|
44
|
+
* Returns null if no match, or a result object if found.
|
|
45
|
+
*/
|
|
46
|
+
async function searchFile(filePath, queryLower, conversationId, projectName, decodedPath) {
|
|
47
|
+
let text
|
|
48
|
+
try {
|
|
49
|
+
const fileStat = await stat(filePath)
|
|
50
|
+
if (fileStat.size < MIN_FILE_SIZE) return null
|
|
51
|
+
|
|
52
|
+
// Read file content (capped at MAX_FILE_READ)
|
|
53
|
+
if (fileStat.size <= MAX_FILE_READ) {
|
|
54
|
+
text = await readFile(filePath, 'utf-8')
|
|
55
|
+
} else {
|
|
56
|
+
const buf = Buffer.alloc(MAX_FILE_READ)
|
|
57
|
+
const handle = await open(filePath, 'r')
|
|
58
|
+
try {
|
|
59
|
+
const { bytesRead } = await handle.read(buf, 0, MAX_FILE_READ, 0)
|
|
60
|
+
const decoder = new TextDecoder('utf-8', { fatal: false })
|
|
61
|
+
text = decoder.decode(buf.subarray(0, bytesRead))
|
|
62
|
+
} finally {
|
|
63
|
+
await handle.close()
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
} catch {
|
|
67
|
+
return null
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
const lines = text.split('\n')
|
|
71
|
+
let matchCount = 0
|
|
72
|
+
let firstSnippet = null
|
|
73
|
+
let cwd = null
|
|
74
|
+
let preview = null
|
|
75
|
+
|
|
76
|
+
for (const line of lines) {
|
|
77
|
+
if (!line) continue
|
|
78
|
+
let entry
|
|
79
|
+
try {
|
|
80
|
+
entry = JSON.parse(line)
|
|
81
|
+
} catch {
|
|
82
|
+
continue
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// Extract CWD from first entry that has it
|
|
86
|
+
if (!cwd && entry.cwd) {
|
|
87
|
+
cwd = entry.cwd
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// Extract preview from first user message
|
|
91
|
+
if (!preview && entry.type === 'user') {
|
|
92
|
+
const content = entry.message?.content
|
|
93
|
+
if (typeof content === 'string') {
|
|
94
|
+
preview = content.slice(0, 200)
|
|
95
|
+
} else if (Array.isArray(content)) {
|
|
96
|
+
const hasToolResult = content.some((b) => b.type === 'tool_result')
|
|
97
|
+
if (!hasToolResult) {
|
|
98
|
+
const textParts = content
|
|
99
|
+
.filter((b) => b.type === 'text')
|
|
100
|
+
.map((b) => b.text)
|
|
101
|
+
.join('\n')
|
|
102
|
+
if (textParts) preview = textParts.slice(0, 200)
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
const searchable = extractSearchableText(entry)
|
|
108
|
+
if (!searchable) continue
|
|
109
|
+
|
|
110
|
+
const lower = searchable.toLowerCase()
|
|
111
|
+
const idx = lower.indexOf(queryLower)
|
|
112
|
+
if (idx === -1) continue
|
|
113
|
+
|
|
114
|
+
matchCount++
|
|
115
|
+
if (!firstSnippet) {
|
|
116
|
+
// Extract snippet with context around the match
|
|
117
|
+
const start = Math.max(0, idx - 40)
|
|
118
|
+
const end = Math.min(searchable.length, idx + queryLower.length + 60)
|
|
119
|
+
firstSnippet = (start > 0 ? '...' : '') +
|
|
120
|
+
searchable.slice(start, end).trim() +
|
|
121
|
+
(end < searchable.length ? '...' : '')
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
if (matchCount === 0) return null
|
|
126
|
+
|
|
127
|
+
return {
|
|
128
|
+
conversationId,
|
|
129
|
+
projectName: cwd ? basename(cwd) : projectName,
|
|
130
|
+
project: cwd || decodedPath,
|
|
131
|
+
cwd,
|
|
132
|
+
preview,
|
|
133
|
+
snippet: firstSnippet,
|
|
134
|
+
matchCount,
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* Search all conversation JSONL files for a query string.
|
|
140
|
+
* Returns an array of results with conversation metadata and match snippets.
|
|
141
|
+
*
|
|
142
|
+
* @param {string} query - Search query (case-insensitive substring match)
|
|
143
|
+
* @param {Object} [opts] - Options
|
|
144
|
+
* @param {string} [opts.projectsDir] - Root directory to scan
|
|
145
|
+
* @param {number} [opts.maxResults] - Maximum results to return (default 50)
|
|
146
|
+
* @returns {Promise<Array<{
|
|
147
|
+
* conversationId: string,
|
|
148
|
+
* projectName: string,
|
|
149
|
+
* project: string|null,
|
|
150
|
+
* cwd: string|null,
|
|
151
|
+
* preview: string|null,
|
|
152
|
+
* snippet: string,
|
|
153
|
+
* matchCount: number,
|
|
154
|
+
* }>>}
|
|
155
|
+
*/
|
|
156
|
+
export async function searchConversations(query, opts = {}) {
|
|
157
|
+
const trimmed = (query || '').trim()
|
|
158
|
+
if (!trimmed) return []
|
|
159
|
+
// #6448 — reject an over-long query rather than substring-scan every file with it.
|
|
160
|
+
if (trimmed.length > MAX_QUERY_LENGTH) return []
|
|
161
|
+
|
|
162
|
+
const queryLower = trimmed.toLowerCase()
|
|
163
|
+
const projectsDir = opts.projectsDir || PROJECTS_DIR
|
|
164
|
+
const maxResults = opts.maxResults || DEFAULT_MAX_RESULTS
|
|
165
|
+
|
|
166
|
+
// Collect all JSONL files across projects
|
|
167
|
+
let projectDirs
|
|
168
|
+
try {
|
|
169
|
+
projectDirs = await readdir(projectsDir, { withFileTypes: true })
|
|
170
|
+
} catch {
|
|
171
|
+
return []
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
const candidates = []
|
|
175
|
+
for (const dir of projectDirs) {
|
|
176
|
+
if (!dir.isDirectory()) continue
|
|
177
|
+
const encodedName = dir.name
|
|
178
|
+
const decodedPath = decodeProjectPath(encodedName)
|
|
179
|
+
const projectName = decodedPath ? basename(decodedPath) : encodedName
|
|
180
|
+
const dirPath = join(projectsDir, encodedName)
|
|
181
|
+
|
|
182
|
+
let files
|
|
183
|
+
try {
|
|
184
|
+
files = await readdir(dirPath)
|
|
185
|
+
} catch {
|
|
186
|
+
continue
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
for (const file of files.filter((f) => f.endsWith('.jsonl'))) {
|
|
190
|
+
candidates.push({
|
|
191
|
+
filePath: join(dirPath, file),
|
|
192
|
+
conversationId: file.replace('.jsonl', ''),
|
|
193
|
+
decodedPath,
|
|
194
|
+
projectName,
|
|
195
|
+
})
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
// Search files in parallel
|
|
200
|
+
const tasks = candidates.map((c) => () =>
|
|
201
|
+
searchFile(c.filePath, queryLower, c.conversationId, c.projectName, c.decodedPath)
|
|
202
|
+
)
|
|
203
|
+
|
|
204
|
+
const results = await runWithConcurrency(tasks, CONCURRENCY)
|
|
205
|
+
const matches = results.filter(Boolean)
|
|
206
|
+
|
|
207
|
+
// Sort by match count descending, then by project name, then conversationId
|
|
208
|
+
matches.sort((a, b) => {
|
|
209
|
+
if (b.matchCount !== a.matchCount) return b.matchCount - a.matchCount
|
|
210
|
+
const nameCmp = a.projectName.localeCompare(b.projectName)
|
|
211
|
+
if (nameCmp !== 0) return nameCmp
|
|
212
|
+
return a.conversationId.localeCompare(b.conversationId)
|
|
213
|
+
})
|
|
214
|
+
|
|
215
|
+
return matches.slice(0, maxResults)
|
|
216
|
+
}
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tracks cumulative costs per session and enforces budget thresholds.
|
|
3
|
+
*
|
|
4
|
+
* Budget scope: PER-SESSION. The configured budget is applied independently
|
|
5
|
+
* to each session's cumulative cost — it is NOT an aggregate limit across
|
|
6
|
+
* all sessions. A warning fires at 80% of a single session's spend and the
|
|
7
|
+
* session is paused at 100%. Creating a second session gives it its own
|
|
8
|
+
* fresh budget of the same dollar amount; the limit does not stack or share.
|
|
9
|
+
* Use `getTotalCost()` if you need the aggregate across sessions for display.
|
|
10
|
+
*
|
|
11
|
+
* Extracted from session-manager.js to separate cost tracking concerns
|
|
12
|
+
* from session lifecycle management.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
export class CostBudgetManager {
|
|
16
|
+
/**
|
|
17
|
+
* @param {object} options
|
|
18
|
+
* @param {number|null} [options.budget] - Per-session cost budget in dollars
|
|
19
|
+
* (applied independently to each session), or null for no limit.
|
|
20
|
+
*/
|
|
21
|
+
constructor({ budget = null } = {}) {
|
|
22
|
+
this._budget = typeof budget === 'number' && budget > 0 ? budget : null
|
|
23
|
+
this._sessionCosts = new Map() // sessionId -> cumulative cost in dollars
|
|
24
|
+
this._budgetWarned = new Set() // sessionIds that received 80% warning
|
|
25
|
+
this._budgetExceeded = new Set() // sessionIds that received 100% exceeded
|
|
26
|
+
this._budgetPaused = new Set() // sessionIds paused due to budget exceeded
|
|
27
|
+
this._costByModel = new Map() // model -> cumulative cost
|
|
28
|
+
this._costEvents = [] // recent events for spend rate: { cost, timestamp }
|
|
29
|
+
this._maxCostEvents = 500
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Track cost for a session and check budget thresholds.
|
|
34
|
+
* @param {string} sessionId
|
|
35
|
+
* @param {number} cost - Cost of the latest query in dollars
|
|
36
|
+
* @returns {{ event: string, data: object } | null} Budget event to emit, or null
|
|
37
|
+
*/
|
|
38
|
+
trackCost(sessionId, cost, model = null) {
|
|
39
|
+
const prev = this._sessionCosts.get(sessionId) || 0
|
|
40
|
+
const cumulative = prev + cost
|
|
41
|
+
this._sessionCosts.set(sessionId, cumulative)
|
|
42
|
+
|
|
43
|
+
// Track cost by model
|
|
44
|
+
if (model) {
|
|
45
|
+
const prevModel = this._costByModel.get(model) || 0
|
|
46
|
+
this._costByModel.set(model, prevModel + cost)
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// Record event for spend rate
|
|
50
|
+
this._costEvents.push({ cost, timestamp: Date.now() })
|
|
51
|
+
if (this._costEvents.length > this._maxCostEvents) {
|
|
52
|
+
this._costEvents = this._costEvents.slice(-this._maxCostEvents)
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
if (!this._budget) return null
|
|
56
|
+
|
|
57
|
+
const percent = cumulative / this._budget
|
|
58
|
+
|
|
59
|
+
// Hard limit at 100%
|
|
60
|
+
if (percent >= 1.0 && !this._budgetExceeded.has(sessionId)) {
|
|
61
|
+
this._budgetExceeded.add(sessionId)
|
|
62
|
+
this._budgetPaused.add(sessionId)
|
|
63
|
+
return {
|
|
64
|
+
event: 'budget_exceeded',
|
|
65
|
+
data: {
|
|
66
|
+
sessionCost: cumulative,
|
|
67
|
+
budget: this._budget,
|
|
68
|
+
percent: Math.round(percent * 100),
|
|
69
|
+
},
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// Warning at 80%
|
|
74
|
+
if (percent >= 0.8 && !this._budgetWarned.has(sessionId)) {
|
|
75
|
+
this._budgetWarned.add(sessionId)
|
|
76
|
+
return {
|
|
77
|
+
event: 'budget_warning',
|
|
78
|
+
data: {
|
|
79
|
+
sessionCost: cumulative,
|
|
80
|
+
budget: this._budget,
|
|
81
|
+
percent: Math.round(percent * 100),
|
|
82
|
+
},
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
return null
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** Get cumulative cost for a session. */
|
|
90
|
+
getSessionCost(sessionId) {
|
|
91
|
+
return this._sessionCosts.get(sessionId) || 0
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** Get total cost across all sessions. */
|
|
95
|
+
getTotalCost() {
|
|
96
|
+
let total = 0
|
|
97
|
+
for (const cost of this._sessionCosts.values()) total += cost
|
|
98
|
+
return total
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** Get configured budget or null. */
|
|
102
|
+
getBudget() {
|
|
103
|
+
return this._budget
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/** Get cost breakdown by model. */
|
|
107
|
+
getCostByModel() {
|
|
108
|
+
const result = {}
|
|
109
|
+
for (const [model, cost] of this._costByModel) {
|
|
110
|
+
result[model] = cost
|
|
111
|
+
}
|
|
112
|
+
return result
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** Get spend rate (cost per hour) based on recent events. */
|
|
116
|
+
getSpendRate() {
|
|
117
|
+
if (this._costEvents.length < 2) return 0
|
|
118
|
+
const first = this._costEvents[0].timestamp
|
|
119
|
+
const last = this._costEvents[this._costEvents.length - 1].timestamp
|
|
120
|
+
const durationHours = (last - first) / (1000 * 60 * 60)
|
|
121
|
+
if (durationHours <= 0) return 0
|
|
122
|
+
const totalCost = this._costEvents.reduce((sum, e) => sum + e.cost, 0)
|
|
123
|
+
return totalCost / durationHours
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** Check if session is paused due to budget. */
|
|
127
|
+
isPaused(sessionId) {
|
|
128
|
+
return this._budgetPaused.has(sessionId)
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** Resume a budget-paused session. */
|
|
132
|
+
resume(sessionId) {
|
|
133
|
+
this._budgetPaused.delete(sessionId)
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** Remove tracking for a session. */
|
|
137
|
+
removeSession(sessionId) {
|
|
138
|
+
this._sessionCosts.delete(sessionId)
|
|
139
|
+
this._budgetWarned.delete(sessionId)
|
|
140
|
+
this._budgetExceeded.delete(sessionId)
|
|
141
|
+
this._budgetPaused.delete(sessionId)
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** Clear all state. */
|
|
145
|
+
clear() {
|
|
146
|
+
this._sessionCosts.clear()
|
|
147
|
+
this._budgetWarned.clear()
|
|
148
|
+
this._budgetExceeded.clear()
|
|
149
|
+
this._budgetPaused.clear()
|
|
150
|
+
this._costByModel.clear()
|
|
151
|
+
this._costEvents = []
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** Serialize state for persistence. */
|
|
155
|
+
serialize() {
|
|
156
|
+
const costs = {}
|
|
157
|
+
for (const [id, cost] of this._sessionCosts) {
|
|
158
|
+
costs[id] = cost
|
|
159
|
+
}
|
|
160
|
+
return {
|
|
161
|
+
costs,
|
|
162
|
+
budgetWarned: [...this._budgetWarned],
|
|
163
|
+
budgetExceeded: [...this._budgetExceeded],
|
|
164
|
+
budgetPaused: [...this._budgetPaused],
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** Restore state from persistence, with optional ID remapping. */
|
|
169
|
+
restore(data, idMap = null) {
|
|
170
|
+
if (data.costs && typeof data.costs === 'object') {
|
|
171
|
+
for (const [oldId, cost] of Object.entries(data.costs)) {
|
|
172
|
+
if (typeof cost === 'number' && cost > 0) {
|
|
173
|
+
const newId = idMap?.get(oldId)
|
|
174
|
+
this._sessionCosts.set(newId || oldId, cost)
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
for (const key of ['budgetWarned', 'budgetExceeded', 'budgetPaused']) {
|
|
179
|
+
const setField = key === 'budgetWarned' ? this._budgetWarned
|
|
180
|
+
: key === 'budgetExceeded' ? this._budgetExceeded
|
|
181
|
+
: this._budgetPaused
|
|
182
|
+
if (Array.isArray(data[key])) {
|
|
183
|
+
for (const id of data[key]) {
|
|
184
|
+
const newId = idMap?.get(id)
|
|
185
|
+
setField.add(newId || id)
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
}
|
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Envelope encryption for the credential store at rest (#5154).
|
|
3
|
+
*
|
|
4
|
+
* `credentials.json` holds the highest-value secrets chroxy persists — BYOK
|
|
5
|
+
* provider API keys and the Claude Code OAuth token. Mode 0600 keeps them
|
|
6
|
+
* owner-only, but a stolen disk image / backup / errant `cat` still exposes
|
|
7
|
+
* them in plaintext. This module encrypts the whole JSON blob with a random
|
|
8
|
+
* 32-byte data key that lives in the OS keychain — NOT next to the file — so a
|
|
9
|
+
* file-read alone is not enough to recover the secrets.
|
|
10
|
+
*
|
|
11
|
+
* on disk: { v: 1, alg: 'nacl-secretbox', nonce: <b64>, data: <b64> }
|
|
12
|
+
* keychain: service 'chroxy-cred-key', the base64 data key (one entry)
|
|
13
|
+
*
|
|
14
|
+
* Crypto: `nacl.secretbox` (XSalsa20-Poly1305 AEAD) — the same primitive the
|
|
15
|
+
* transport layer already uses, and `tweetnacl` is already a server dependency.
|
|
16
|
+
* The 24-byte nonce is random per write; the Poly1305 tag detects tampering on
|
|
17
|
+
* open (a wrong key or a flipped byte fails closed).
|
|
18
|
+
*
|
|
19
|
+
* Honest threat model: encryption only adds real protection because the key
|
|
20
|
+
* lives in the OS keychain (macOS Keychain / Linux libsecret), which a
|
|
21
|
+
* file-read attacker cannot reach. Where no keychain is available (Windows,
|
|
22
|
+
* headless Linux without `secret-tool`) there is nowhere safe to put the key,
|
|
23
|
+
* so the store falls back to today's 0600 plaintext and the server logs a
|
|
24
|
+
* one-time warning rather than inventing a machine-derived key (which would be
|
|
25
|
+
* obfuscation, not security). See docs/security/credentials-at-rest.md for the
|
|
26
|
+
* full threat model.
|
|
27
|
+
*
|
|
28
|
+
* The keychain is dependency-injected (every export takes an optional
|
|
29
|
+
* `keychain` arg defaulting to the real module) so callers and tests stay
|
|
30
|
+
* deterministic regardless of the host's actual keychain.
|
|
31
|
+
*/
|
|
32
|
+
import nacl from 'tweetnacl'
|
|
33
|
+
import { randomBytes } from 'node:crypto'
|
|
34
|
+
import * as realKeychain from './keychain.js'
|
|
35
|
+
|
|
36
|
+
/** Keychain service for the credential data key. Distinct from the primary
|
|
37
|
+
* API-token entry (service 'chroxy') so the two never collide. */
|
|
38
|
+
export const CRED_KEY_SERVICE = 'chroxy-cred-key'
|
|
39
|
+
|
|
40
|
+
export const ENVELOPE_VERSION = 1
|
|
41
|
+
const ALG = 'nacl-secretbox'
|
|
42
|
+
const KEY_BYTES = 32 // nacl.secretbox key length
|
|
43
|
+
const NONCE_BYTES = 24 // nacl.secretbox nonce length
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Is `obj` a well-formed encrypted envelope (vs. a legacy plaintext object)?
|
|
47
|
+
* Used by the store to decide decrypt-vs-passthrough on read.
|
|
48
|
+
*/
|
|
49
|
+
export function isEncryptedEnvelope(obj) {
|
|
50
|
+
return (
|
|
51
|
+
!!obj &&
|
|
52
|
+
typeof obj === 'object' &&
|
|
53
|
+
!Array.isArray(obj) &&
|
|
54
|
+
obj.v === ENVELOPE_VERSION &&
|
|
55
|
+
obj.alg === ALG &&
|
|
56
|
+
typeof obj.nonce === 'string' &&
|
|
57
|
+
typeof obj.data === 'string'
|
|
58
|
+
)
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Read the existing data key from the keychain WITHOUT creating one. Returns a
|
|
63
|
+
* 32-byte Uint8Array, or null when no keychain is available or no key is stored
|
|
64
|
+
* (or the stored value is the wrong length — treated as absent).
|
|
65
|
+
*/
|
|
66
|
+
export function getMasterKey(keychain = realKeychain) {
|
|
67
|
+
if (!keychain.isKeychainAvailable()) return null
|
|
68
|
+
const stored = keychain.getToken(CRED_KEY_SERVICE)
|
|
69
|
+
if (!stored) return null
|
|
70
|
+
const buf = Buffer.from(stored, 'base64')
|
|
71
|
+
return buf.length === KEY_BYTES ? new Uint8Array(buf) : null
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Get the data key from the keychain, generating and persisting a fresh one if
|
|
76
|
+
* none exists. Returns null when no keychain is available (caller must fall
|
|
77
|
+
* back to plaintext). A stored-but-malformed key is replaced (the old encrypted
|
|
78
|
+
* blob, if any, becomes undecryptable — acceptable: the alternative is a hard
|
|
79
|
+
* failure, and a corrupt keychain entry already means the secrets are lost).
|
|
80
|
+
*/
|
|
81
|
+
export function getOrCreateMasterKey(keychain = realKeychain) {
|
|
82
|
+
if (!keychain.isKeychainAvailable()) return null
|
|
83
|
+
const existing = getMasterKey(keychain)
|
|
84
|
+
if (existing) return existing
|
|
85
|
+
const key = randomBytes(KEY_BYTES)
|
|
86
|
+
keychain.setToken(Buffer.from(key).toString('base64'), CRED_KEY_SERVICE)
|
|
87
|
+
return new Uint8Array(key)
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* #5229 — generate a FRESH data key, persist it to the keychain (replacing any
|
|
92
|
+
* existing `chroxy-cred-key` entry), and return it as a 32-byte Uint8Array.
|
|
93
|
+
* Returns null when no keychain is available. Unlike getOrCreateMasterKey this
|
|
94
|
+
* always mints a new key — callers use it to rotate, and are responsible for
|
|
95
|
+
* re-encrypting the store under the returned key (and for rolling back via
|
|
96
|
+
* setMasterKey if that write fails).
|
|
97
|
+
*/
|
|
98
|
+
export function rotateMasterKey(keychain = realKeychain) {
|
|
99
|
+
if (!keychain.isKeychainAvailable()) return null
|
|
100
|
+
const key = randomBytes(KEY_BYTES)
|
|
101
|
+
keychain.setToken(Buffer.from(key).toString('base64'), CRED_KEY_SERVICE)
|
|
102
|
+
return new Uint8Array(key)
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* #5229 — restore a specific data key to the keychain (the rekey rollback seam).
|
|
107
|
+
* Pass a 32-byte Uint8Array to set it, or null to delete the entry entirely
|
|
108
|
+
* (used when the store had no prior key — i.e. was plaintext — before a failed
|
|
109
|
+
* rotation). Throws on a wrong-length key.
|
|
110
|
+
*/
|
|
111
|
+
export function setMasterKey(key, keychain = realKeychain) {
|
|
112
|
+
if (key == null) {
|
|
113
|
+
keychain.deleteToken(CRED_KEY_SERVICE)
|
|
114
|
+
return
|
|
115
|
+
}
|
|
116
|
+
if (!(key instanceof Uint8Array) || key.length !== KEY_BYTES) {
|
|
117
|
+
throw new Error('credential cipher: key must be a 32-byte Uint8Array')
|
|
118
|
+
}
|
|
119
|
+
keychain.setToken(Buffer.from(key).toString('base64'), CRED_KEY_SERVICE)
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* Encrypt a plain JS object into an envelope using `key` (32-byte Uint8Array).
|
|
124
|
+
* Pure: a fresh random nonce each call. Throws on a bad key length.
|
|
125
|
+
*/
|
|
126
|
+
export function encryptJson(plainObj, key) {
|
|
127
|
+
if (!(key instanceof Uint8Array) || key.length !== KEY_BYTES) {
|
|
128
|
+
throw new Error('credential cipher: key must be a 32-byte Uint8Array')
|
|
129
|
+
}
|
|
130
|
+
const nonce = new Uint8Array(randomBytes(NONCE_BYTES))
|
|
131
|
+
const message = new TextEncoder().encode(JSON.stringify(plainObj))
|
|
132
|
+
const box = nacl.secretbox(message, nonce, key)
|
|
133
|
+
return {
|
|
134
|
+
v: ENVELOPE_VERSION,
|
|
135
|
+
alg: ALG,
|
|
136
|
+
nonce: Buffer.from(nonce).toString('base64'),
|
|
137
|
+
data: Buffer.from(box).toString('base64'),
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* Decrypt an envelope back to its plain object using `key`. Throws when the key
|
|
143
|
+
* is wrong or the ciphertext was tampered with (Poly1305 verification fails),
|
|
144
|
+
* or when the envelope/JSON is malformed.
|
|
145
|
+
*/
|
|
146
|
+
export function decryptEnvelope(envelope, key) {
|
|
147
|
+
if (!isEncryptedEnvelope(envelope)) {
|
|
148
|
+
throw new Error('credential cipher: not a valid encrypted envelope')
|
|
149
|
+
}
|
|
150
|
+
if (!(key instanceof Uint8Array) || key.length !== KEY_BYTES) {
|
|
151
|
+
throw new Error('credential cipher: key must be a 32-byte Uint8Array')
|
|
152
|
+
}
|
|
153
|
+
const nonce = new Uint8Array(Buffer.from(envelope.nonce, 'base64'))
|
|
154
|
+
const box = new Uint8Array(Buffer.from(envelope.data, 'base64'))
|
|
155
|
+
// Guard the decoded lengths before handing them to tweetnacl: a malformed /
|
|
156
|
+
// truncated envelope can decode to a wrong-size nonce, and nacl.secretbox
|
|
157
|
+
// throws 'bad nonce size' rather than returning null — surface a predictable
|
|
158
|
+
// error instead. A short ciphertext (< the Poly1305 tag) likewise can't be a
|
|
159
|
+
// valid box.
|
|
160
|
+
if (nonce.length !== NONCE_BYTES || box.length <= nacl.secretbox.overheadLength) {
|
|
161
|
+
throw new Error('credential decryption failed (wrong key or corrupt data)')
|
|
162
|
+
}
|
|
163
|
+
// secretbox.open returns null on auth failure, but defensively wrap it so any
|
|
164
|
+
// unexpected throw from a corrupt envelope still becomes the same friendly error.
|
|
165
|
+
let opened
|
|
166
|
+
try {
|
|
167
|
+
opened = nacl.secretbox.open(box, nonce, key)
|
|
168
|
+
} catch {
|
|
169
|
+
opened = null
|
|
170
|
+
}
|
|
171
|
+
if (!opened) {
|
|
172
|
+
throw new Error('credential decryption failed (wrong key or corrupt data)')
|
|
173
|
+
}
|
|
174
|
+
const parsed = JSON.parse(new TextDecoder().decode(opened))
|
|
175
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
|
|
176
|
+
throw new Error('credential cipher: decrypted payload is not a JSON object')
|
|
177
|
+
}
|
|
178
|
+
return parsed
|
|
179
|
+
}
|