@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,1158 @@
|
|
|
1
|
+
import { readFileSync, existsSync, statSync } from 'fs'
|
|
2
|
+
import { join, resolve, dirname, relative, sep, isAbsolute } from 'path'
|
|
3
|
+
import { fileURLToPath } from 'url'
|
|
4
|
+
import QRCode from 'qrcode'
|
|
5
|
+
import { readConnectionInfo } from './connection-info.js'
|
|
6
|
+
import { createLogger } from './logger.js'
|
|
7
|
+
import { metrics } from './metrics.js'
|
|
8
|
+
import { buildDiagnosticsSnapshot } from './diagnostics.js'
|
|
9
|
+
import { getRateLimitKey } from './rate-limiter.js'
|
|
10
|
+
import { listSnapshots, deleteSnapshot } from './snapshots-store.js'
|
|
11
|
+
import { handleEventIngest } from './event-ingest.js'
|
|
12
|
+
import { handleGithubWebhook } from './github-webhook.js'
|
|
13
|
+
import { handleMailboxPing, handleMailboxRegister } from './mailbox-route.js'
|
|
14
|
+
import { isPoolEnabled } from './docker-byok-pool.js'
|
|
15
|
+
import { getSharedPoolStats } from './docker-byok-pool-stats.js'
|
|
16
|
+
import { isValidSlug, mimeForPath } from './pages-store.js'
|
|
17
|
+
import { sendOversizeResponse } from './http-oversize.js'
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* #5683 — read + JSON-parse a request body with a byte cap. Resolves to the
|
|
21
|
+
* parsed object, or `null` when it has already responded (413 oversize / 400
|
|
22
|
+
* invalid JSON). Mirrors the byte-counted, utf8-safe streaming guard in
|
|
23
|
+
* event-ingest.js (#5433): the violating chunk is never buffered, and the
|
|
24
|
+
* `end` body is wrapped so a parse throw can't escape to uncaughtException.
|
|
25
|
+
*/
|
|
26
|
+
function readJsonBodyCapped(req, res, maxBytes) {
|
|
27
|
+
return new Promise((resolve) => {
|
|
28
|
+
req.setEncoding('utf8')
|
|
29
|
+
let body = ''
|
|
30
|
+
let bytes = 0
|
|
31
|
+
let oversized = false
|
|
32
|
+
req.on('data', (chunk) => {
|
|
33
|
+
if (oversized) return
|
|
34
|
+
bytes += Buffer.byteLength(chunk, 'utf8')
|
|
35
|
+
if (bytes > maxBytes) {
|
|
36
|
+
oversized = true
|
|
37
|
+
sendOversizeResponse(req, res, { error: 'body too large' })
|
|
38
|
+
resolve(null)
|
|
39
|
+
return
|
|
40
|
+
}
|
|
41
|
+
body += chunk
|
|
42
|
+
})
|
|
43
|
+
req.on('end', () => {
|
|
44
|
+
// Wrap the WHOLE handler (not just JSON.parse): this listener runs on a
|
|
45
|
+
// later tick inside the Promise executor, OUTSIDE the dispatch try/catch
|
|
46
|
+
// (#5313), so an unguarded throw here (e.g. res write on a torn-down
|
|
47
|
+
// socket) would escape to uncaughtException.
|
|
48
|
+
try {
|
|
49
|
+
if (oversized) return
|
|
50
|
+
let parsed
|
|
51
|
+
try {
|
|
52
|
+
parsed = JSON.parse(body)
|
|
53
|
+
} catch {
|
|
54
|
+
res.writeHead(400, { 'Content-Type': 'application/json' })
|
|
55
|
+
res.end(JSON.stringify({ error: 'invalid JSON' }))
|
|
56
|
+
resolve(null)
|
|
57
|
+
return
|
|
58
|
+
}
|
|
59
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
|
|
60
|
+
res.writeHead(400, { 'Content-Type': 'application/json' })
|
|
61
|
+
res.end(JSON.stringify({ error: 'body must be a JSON object' }))
|
|
62
|
+
resolve(null)
|
|
63
|
+
return
|
|
64
|
+
}
|
|
65
|
+
resolve(parsed)
|
|
66
|
+
} catch {
|
|
67
|
+
resolve(null)
|
|
68
|
+
}
|
|
69
|
+
})
|
|
70
|
+
// Settle on error AND close so a client abort / half-open socket can never
|
|
71
|
+
// leak a pending promise (resolve is idempotent, so a later `end` is a no-op).
|
|
72
|
+
req.on('error', () => resolve(null))
|
|
73
|
+
req.on('close', () => resolve(null))
|
|
74
|
+
})
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// #5683 — security headers for every Chroxy Pages response. The `/p/<slug>`
|
|
78
|
+
// route is intentionally UNAUTHENTICATED (the slug is the capability).
|
|
79
|
+
// `script-src 'none'` + `connect-src 'none'` + `sandbox` make served pages
|
|
80
|
+
// fully static (no JS, no network) — exactly right for the HTML reports this
|
|
81
|
+
// serves, and defence-in-depth so a served page can never script same-origin
|
|
82
|
+
// `/api/*` calls. (Note: `_validateBearerAuth` is HEADER-only — it does not
|
|
83
|
+
// read a cookie; the `chroxy_auth` cookie `_authenticateDashboardRequest` sets
|
|
84
|
+
// is `Path=/dashboard`-scoped + HttpOnly, so it never reaches `/p/*` or
|
|
85
|
+
// `/api/*`. The CSP is belt-and-suspenders, not the sole guard.) See
|
|
86
|
+
// docs/security/bearer-token-authority.md.
|
|
87
|
+
const PAGE_SECURITY_HEADERS = {
|
|
88
|
+
'Content-Security-Policy':
|
|
89
|
+
"default-src 'none'; img-src 'self' data:; style-src 'unsafe-inline'; font-src 'self' data:; connect-src 'none'; script-src 'none'; base-uri 'none'; form-action 'none'; sandbox",
|
|
90
|
+
'X-Content-Type-Options': 'nosniff',
|
|
91
|
+
'X-Frame-Options': 'DENY',
|
|
92
|
+
'Cross-Origin-Resource-Policy': 'same-origin',
|
|
93
|
+
'Referrer-Policy': 'no-referrer',
|
|
94
|
+
'Cache-Control': 'no-store',
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
const log = createLogger('ws')
|
|
98
|
+
|
|
99
|
+
const __filename = fileURLToPath(import.meta.url)
|
|
100
|
+
const __dirname = dirname(__filename)
|
|
101
|
+
const packageJson = JSON.parse(readFileSync(join(__dirname, '../package.json'), 'utf-8'))
|
|
102
|
+
const SERVER_VERSION = packageJson.version
|
|
103
|
+
|
|
104
|
+
const ALLOWED_ORIGINS = [
|
|
105
|
+
'tauri://localhost',
|
|
106
|
+
'https://tauri.localhost',
|
|
107
|
+
]
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Render a diagnostics snapshot as a copy-pasteable plaintext block.
|
|
111
|
+
* Used when the caller asks `Accept: text/plain` — convenient for SSH
|
|
112
|
+
* sessions and bug reports.
|
|
113
|
+
*/
|
|
114
|
+
function formatDiagnosticsText(snap) {
|
|
115
|
+
const lines = []
|
|
116
|
+
const s = snap.server || {}
|
|
117
|
+
lines.push(`chroxy server v${s.version} (${s.mode || 'unknown'}) — pid ${s.pid}, node ${s.nodeVersion}`)
|
|
118
|
+
lines.push(`uptime: ${s.uptime}s — clients: ${snap.clients?.connected ?? 0} connected, ${snap.clients?.authenticated ?? 0} authed`)
|
|
119
|
+
lines.push(`memory: rss=${formatBytes(s.memory?.rss)} heap=${formatBytes(s.memory?.heapUsed)}/${formatBytes(s.memory?.heapTotal)}`)
|
|
120
|
+
lines.push('')
|
|
121
|
+
lines.push(`sessions (${snap.sessions?.length ?? 0}):`)
|
|
122
|
+
for (const sess of snap.sessions || []) {
|
|
123
|
+
lines.push(` - ${sess.id} [${sess.provider}] busy=${sess.isBusy} mode=${sess.permissionMode}`)
|
|
124
|
+
lines.push(` pause=${sess.resultTimeoutPaused} count=${sess.permissionPauseCount} cwd=${sess.cwd}`)
|
|
125
|
+
if (sess.pendingPermissions?.length) {
|
|
126
|
+
for (const p of sess.pendingPermissions) {
|
|
127
|
+
const age = p.ageMs != null ? `${Math.round(p.ageMs / 1000)}s` : '?'
|
|
128
|
+
lines.push(` pending: ${p.tool} (${age} old) — ${p.description || ''}`)
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
lines.push('')
|
|
133
|
+
const lg = snap.logs || {}
|
|
134
|
+
lines.push(`log tail (${lg.source}${lg.path ? `: ${lg.path}` : ''}):`)
|
|
135
|
+
for (const line of lg.lines || []) lines.push(` ${line}`)
|
|
136
|
+
if (lg.note) lines.push(` (${lg.note})`)
|
|
137
|
+
if (lg.error) lines.push(` (error: ${lg.error})`)
|
|
138
|
+
return lines.join('\n') + '\n'
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function formatBytes(n) {
|
|
142
|
+
if (typeof n !== 'number') return '?'
|
|
143
|
+
if (n < 1024) return `${n}B`
|
|
144
|
+
if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)}KB`
|
|
145
|
+
return `${(n / 1024 / 1024).toFixed(1)}MB`
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* Hard ceiling on `?logTailBytes=N` for `GET /diagnostics` (#3739).
|
|
150
|
+
* 8x the default (8192) — large enough for a wide stall window, small
|
|
151
|
+
* enough that a stolen token can't pull megabytes per request.
|
|
152
|
+
*/
|
|
153
|
+
const LOG_TAIL_BYTES_MAX = 65536
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* Parse and validate `?logTailBytes=N` from a `/diagnostics` request URL.
|
|
157
|
+
* Returns the clamped positive integer, or `null` if the param is absent
|
|
158
|
+
* or invalid (NaN, non-finite, zero, or negative). Callers fall back to
|
|
159
|
+
* `buildDiagnosticsSnapshot`'s own default when `null` is returned, so
|
|
160
|
+
* "no param" and "garbage param" behave identically — preserving the
|
|
161
|
+
* pre-#3739 default behavior described in docs/troubleshooting.md.
|
|
162
|
+
*
|
|
163
|
+
* Values above the hard cap are clamped to `LOG_TAIL_BYTES_MAX` rather
|
|
164
|
+
* than rejected, so an operator who asks for 1MB still gets a useful
|
|
165
|
+
* 64KB response instead of an error.
|
|
166
|
+
*/
|
|
167
|
+
function parseLogTailBytes(url) {
|
|
168
|
+
if (!url) return null
|
|
169
|
+
const qIdx = url.indexOf('?')
|
|
170
|
+
if (qIdx === -1) return null
|
|
171
|
+
// Use `new URL` (already used elsewhere in this file for the dashboard
|
|
172
|
+
// route) with a throwaway base, since URLSearchParams as a bare global
|
|
173
|
+
// isn't in the server's ESLint env. We only need the searchParams view.
|
|
174
|
+
let parsed
|
|
175
|
+
try {
|
|
176
|
+
parsed = new URL(url, 'http://_diag.local')
|
|
177
|
+
} catch {
|
|
178
|
+
return null
|
|
179
|
+
}
|
|
180
|
+
const raw = parsed.searchParams.get('logTailBytes')
|
|
181
|
+
if (raw == null || raw === '') return null
|
|
182
|
+
const n = Number(raw)
|
|
183
|
+
if (!Number.isFinite(n)) return null
|
|
184
|
+
const int = Math.trunc(n)
|
|
185
|
+
if (int <= 0) return null
|
|
186
|
+
return Math.min(int, LOG_TAIL_BYTES_MAX)
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* Resolve the `removeImage(tag)` callback for the snapshot DELETE route (#5074).
|
|
191
|
+
*
|
|
192
|
+
* Preference order:
|
|
193
|
+
* 1. `server._snapshotRemoveImage` — test injection seam.
|
|
194
|
+
* 2. `server.environmentManager._backend.removeImage` — already
|
|
195
|
+
* constructed for env-management. Reuses the same `_execFile`
|
|
196
|
+
* injection path the env tests rely on.
|
|
197
|
+
* 3. A lazily-loaded fresh `DockerBackend()` — env management is
|
|
198
|
+
* disabled but a snapshot DELETE still needs to call `docker rmi`.
|
|
199
|
+
* Imported dynamically so tunnel-only installs that never trigger
|
|
200
|
+
* this code path don't pay the module load. Cached across calls
|
|
201
|
+
* (#5101) so batch cleanup doesn't re-run the dynamic `import()` and
|
|
202
|
+
* re-allocate a `DockerBackend` on every DELETE — the `docker rmi`
|
|
203
|
+
* shell-out still happens per call. The cache only covers this
|
|
204
|
+
* fallback — the test seam and the env-manager path both pre-empt it.
|
|
205
|
+
*/
|
|
206
|
+
let _snapshotBackendPromise = null
|
|
207
|
+
|
|
208
|
+
/** Reset the lazily-cached fallback DockerBackend init promise (#5101). Test-only. */
|
|
209
|
+
export function _resetSnapshotBackendCacheForTests() {
|
|
210
|
+
_snapshotBackendPromise = null
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
export async function resolveRemoveImage(server) {
|
|
214
|
+
if (typeof server._snapshotRemoveImage === 'function') {
|
|
215
|
+
return server._snapshotRemoveImage
|
|
216
|
+
}
|
|
217
|
+
const fromEnvMgr = server.environmentManager?._backend?.removeImage
|
|
218
|
+
if (typeof fromEnvMgr === 'function') {
|
|
219
|
+
return (tag) => server.environmentManager._backend.removeImage(tag)
|
|
220
|
+
}
|
|
221
|
+
if (!_snapshotBackendPromise) {
|
|
222
|
+
_snapshotBackendPromise = (async () => {
|
|
223
|
+
const { DockerBackend } = await import('./environments/backends/docker.js')
|
|
224
|
+
const backend = new DockerBackend()
|
|
225
|
+
return (tag) => backend.removeImage(tag)
|
|
226
|
+
})()
|
|
227
|
+
}
|
|
228
|
+
return _snapshotBackendPromise
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/**
|
|
232
|
+
* Check if an Origin header matches the allowed list.
|
|
233
|
+
* Localhost origins with any port are allowed for dev.
|
|
234
|
+
*/
|
|
235
|
+
function matchAllowedOrigin(origin) {
|
|
236
|
+
if (!origin) return null
|
|
237
|
+
if (ALLOWED_ORIGINS.includes(origin)) return origin
|
|
238
|
+
if (/^http:\/\/localhost(:\d+)?$/.test(origin)) return origin
|
|
239
|
+
if (/^http:\/\/127\.0\.0\.1(:\d+)?$/.test(origin)) return origin
|
|
240
|
+
return null
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/**
|
|
244
|
+
* Create an HTTP request handler for the WsServer.
|
|
245
|
+
* Handles health, version, permission, connect, QR, assets, and dashboard routes.
|
|
246
|
+
*
|
|
247
|
+
* @param {object} server - WsServer instance (accessed at request time for current state)
|
|
248
|
+
* @returns {(req: import('http').IncomingMessage, res: import('http').ServerResponse) => void}
|
|
249
|
+
*/
|
|
250
|
+
export function createHttpHandler(server) {
|
|
251
|
+
// #5312 (WP-1.2) — the actual routing logic, wrapped below in a top-level
|
|
252
|
+
// try/catch so an unguarded throw from any route (e.g. buildDiagnosticsSnapshot,
|
|
253
|
+
// readConnectionInfo, or readFileSync(index)) returns 500 instead of rejecting
|
|
254
|
+
// the handler promise → unhandledRejection → process.exit(1), which would take
|
|
255
|
+
// down the whole daemon (every session) on a single bad request.
|
|
256
|
+
const dispatch = async (req, res) => {
|
|
257
|
+
// CORS preflight
|
|
258
|
+
if (req.method === 'OPTIONS') {
|
|
259
|
+
const isRestricted = req.url?.startsWith('/qr') || req.url?.startsWith('/connect') || req.url?.startsWith('/pairing-code') || req.url?.startsWith('/pair-discord')
|
|
260
|
+
const corsOrigin = isRestricted
|
|
261
|
+
? matchAllowedOrigin(req.headers['origin'])
|
|
262
|
+
: '*'
|
|
263
|
+
const headers = {
|
|
264
|
+
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
|
|
265
|
+
'Access-Control-Allow-Headers': 'Authorization, Content-Type',
|
|
266
|
+
'Access-Control-Max-Age': '86400',
|
|
267
|
+
}
|
|
268
|
+
if (corsOrigin) {
|
|
269
|
+
headers['Access-Control-Allow-Origin'] = corsOrigin
|
|
270
|
+
if (isRestricted) headers['Vary'] = 'Origin'
|
|
271
|
+
}
|
|
272
|
+
res.writeHead(204, headers)
|
|
273
|
+
res.end()
|
|
274
|
+
return
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
// Health check — Cloudflare and app verify connectivity via GET / and GET /health
|
|
278
|
+
if (req.method === 'GET' && (req.url === '/' || req.url === '/health')) {
|
|
279
|
+
const accept = req.headers['accept'] || ''
|
|
280
|
+
if (req.url === '/' && accept.includes('text/html') && server.apiToken) {
|
|
281
|
+
res.writeHead(302, {
|
|
282
|
+
'Location': '/dashboard',
|
|
283
|
+
'Cache-Control': 'no-store',
|
|
284
|
+
'Vary': 'Accept',
|
|
285
|
+
})
|
|
286
|
+
res.end()
|
|
287
|
+
return
|
|
288
|
+
}
|
|
289
|
+
res.writeHead(200, {
|
|
290
|
+
'Content-Type': 'application/json',
|
|
291
|
+
'Vary': 'Accept',
|
|
292
|
+
'Access-Control-Allow-Origin': '*',
|
|
293
|
+
})
|
|
294
|
+
res.end(JSON.stringify({ status: 'ok', mode: server.serverMode, version: SERVER_VERSION }))
|
|
295
|
+
return
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
// #5683 — Chroxy Pages: serve a published HTML artifact at an unguessable,
|
|
299
|
+
// UNAUTHENTICATED URL (the slug is the capability). Static-only CSP headers
|
|
300
|
+
// (PAGE_SECURITY_HEADERS) neutralize the cookie-auth risk. Placed in the
|
|
301
|
+
// public section, before the authed routes, and only active when a pages
|
|
302
|
+
// store is wired.
|
|
303
|
+
{
|
|
304
|
+
const pagesPath = (req.url ?? '').split('?')[0]
|
|
305
|
+
if (req.method === 'GET' && pagesPath.startsWith('/p/') && server.pagesStore) {
|
|
306
|
+
// Rate-limit BEFORE any filesystem work so the public route can't be
|
|
307
|
+
// used to scan slugs or DoS the disk.
|
|
308
|
+
const limiter = server._pagesRateLimiter
|
|
309
|
+
if (limiter) {
|
|
310
|
+
const socketIp = req.socket?.remoteAddress || ''
|
|
311
|
+
const { allowed, retryAfterMs } = limiter.check(getRateLimitKey(socketIp, req))
|
|
312
|
+
if (!allowed) {
|
|
313
|
+
res.writeHead(429, {
|
|
314
|
+
'Content-Type': 'text/plain; charset=utf-8',
|
|
315
|
+
'Retry-After': Math.ceil(retryAfterMs / 1000),
|
|
316
|
+
...PAGE_SECURITY_HEADERS,
|
|
317
|
+
})
|
|
318
|
+
res.end('rate limited')
|
|
319
|
+
return
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
const notFound = () => {
|
|
324
|
+
res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8', ...PAGE_SECURITY_HEADERS })
|
|
325
|
+
res.end('Not found')
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
const m = pagesPath.match(/^\/p\/([^/]+)(?:\/(.*))?$/)
|
|
329
|
+
let slug = null
|
|
330
|
+
let rel = ''
|
|
331
|
+
if (m) {
|
|
332
|
+
try {
|
|
333
|
+
slug = decodeURIComponent(m[1])
|
|
334
|
+
rel = m[2] != null ? decodeURIComponent(m[2]) : ''
|
|
335
|
+
} catch {
|
|
336
|
+
slug = null // malformed percent-encoding
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
if (!slug || !isValidSlug(slug) || !server.pagesStore.get(slug)) {
|
|
340
|
+
notFound()
|
|
341
|
+
return
|
|
342
|
+
}
|
|
343
|
+
// Trailing-slash redirect (`/p/<slug>` → `/p/<slug>/`) so a page's
|
|
344
|
+
// relative asset URLs resolve under its own directory.
|
|
345
|
+
if (m[2] == null) {
|
|
346
|
+
res.writeHead(301, { Location: `/p/${encodeURIComponent(slug)}/`, ...PAGE_SECURITY_HEADERS })
|
|
347
|
+
res.end()
|
|
348
|
+
return
|
|
349
|
+
}
|
|
350
|
+
const filePath = server.pagesStore.resolveFile(slug, rel)
|
|
351
|
+
if (!filePath) {
|
|
352
|
+
notFound()
|
|
353
|
+
return
|
|
354
|
+
}
|
|
355
|
+
let body
|
|
356
|
+
try {
|
|
357
|
+
// Defence-in-depth: enforce the per-page size cap on SERVE too, not
|
|
358
|
+
// just at publish time, so a file that somehow grew past the cap (a
|
|
359
|
+
// future publish path, an external write) can't be read unbounded
|
|
360
|
+
// into memory.
|
|
361
|
+
if (statSync(filePath).size > server.pagesStore.maxPageBytes) {
|
|
362
|
+
notFound()
|
|
363
|
+
return
|
|
364
|
+
}
|
|
365
|
+
body = readFileSync(filePath)
|
|
366
|
+
} catch {
|
|
367
|
+
notFound()
|
|
368
|
+
return
|
|
369
|
+
}
|
|
370
|
+
res.writeHead(200, {
|
|
371
|
+
'Content-Type': mimeForPath(filePath),
|
|
372
|
+
'Content-Length': body.byteLength,
|
|
373
|
+
...PAGE_SECURITY_HEADERS,
|
|
374
|
+
})
|
|
375
|
+
res.end(body)
|
|
376
|
+
return
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
// Version endpoint
|
|
381
|
+
if (req.method === 'GET' && req.url === '/version') {
|
|
382
|
+
if (!server._validateBearerAuth(req, res)) {
|
|
383
|
+
log.warn('Rejected unauthenticated GET /version')
|
|
384
|
+
return
|
|
385
|
+
}
|
|
386
|
+
res.writeHead(200, { 'Content-Type': 'application/json' })
|
|
387
|
+
res.end(JSON.stringify({
|
|
388
|
+
version: SERVER_VERSION,
|
|
389
|
+
latestVersion: server._latestVersion,
|
|
390
|
+
gitCommit: server._gitInfo.commit,
|
|
391
|
+
gitBranch: server._gitInfo.branch,
|
|
392
|
+
uptime: Math.round((Date.now() - server._startedAt) / 1000),
|
|
393
|
+
}))
|
|
394
|
+
return
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
// Metrics endpoint — operational counters for monitoring
|
|
398
|
+
if (req.method === 'GET' && req.url === '/metrics') {
|
|
399
|
+
if (!server._validateBearerAuth(req, res)) return
|
|
400
|
+
const mem = process.memoryUsage()
|
|
401
|
+
const sessions = server.sessionManager?.listSessions() || []
|
|
402
|
+
const payload = {
|
|
403
|
+
uptime: Math.round((Date.now() - server._startedAt) / 1000),
|
|
404
|
+
sessions: {
|
|
405
|
+
active: sessions.length,
|
|
406
|
+
},
|
|
407
|
+
clients: {
|
|
408
|
+
connected: server._clientManager?.clients?.size || 0,
|
|
409
|
+
authenticated: server._clientManager?.authenticatedCount || 0,
|
|
410
|
+
},
|
|
411
|
+
memory: {
|
|
412
|
+
rss: mem.rss,
|
|
413
|
+
heapUsed: mem.heapUsed,
|
|
414
|
+
heapTotal: mem.heapTotal,
|
|
415
|
+
},
|
|
416
|
+
process: {
|
|
417
|
+
pid: process.pid,
|
|
418
|
+
nodeVersion: process.version,
|
|
419
|
+
},
|
|
420
|
+
counters: metrics.snapshot(),
|
|
421
|
+
}
|
|
422
|
+
res.writeHead(200, { 'Content-Type': 'application/json' })
|
|
423
|
+
res.end(JSON.stringify(payload))
|
|
424
|
+
return
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
// Snapshot listing endpoint (#5074). Reads docker-byok snapshot
|
|
428
|
+
// metadata sidecars from `${CHROXY_CONFIG_DIR ?? ~/.chroxy}/snapshots/`
|
|
429
|
+
// and returns them as a newest-first array. The dashboard polls this
|
|
430
|
+
// on its SnapshotsPanel.
|
|
431
|
+
const snapPath = (req.url ?? '').split('?')[0]
|
|
432
|
+
|
|
433
|
+
// External event ingest (#5413 Phase 3). Accepts ONLY the daemon-level
|
|
434
|
+
// ingest secret (never the primary token — see
|
|
435
|
+
// docs/security/bearer-token-authority.md §6); auth, body cap, schema
|
|
436
|
+
// validation, per-source rate limiting, and the pipeline dispatch all
|
|
437
|
+
// live in event-ingest.js. The handler registers its own body-stream
|
|
438
|
+
// callbacks and guards them per the #5313 pattern.
|
|
439
|
+
if (req.method === 'POST' && snapPath === '/api/events') {
|
|
440
|
+
handleEventIngest(server, req, res)
|
|
441
|
+
return
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
// Control Room repo-events feed (#5966): GitHub webhook deliveries. Auth is
|
|
445
|
+
// the X-Hub-Signature-256 HMAC (NOT the ingest secret) — the handler verifies
|
|
446
|
+
// it over the RAW body before parsing, and stays inert (503) until a secret
|
|
447
|
+
// is configured. See github-webhook.js.
|
|
448
|
+
if (req.method === 'POST' && snapPath === '/api/github/webhook') {
|
|
449
|
+
handleGithubWebhook(server, req, res)
|
|
450
|
+
return
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
// Mailbox live-interrupt (agent-comm-system delivery). Same daemon-level
|
|
454
|
+
// ingest-secret auth as /api/events (never the primary token). The ping
|
|
455
|
+
// route notifies + wakes a live idle claude-tui recipient; the register
|
|
456
|
+
// route populates the agent-id -> session map. See mailbox-route.js.
|
|
457
|
+
if (req.method === 'POST' && snapPath === '/api/mailbox') {
|
|
458
|
+
handleMailboxPing(server, req, res)
|
|
459
|
+
return
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
if (req.method === 'POST' && snapPath === '/api/mailbox/register') {
|
|
463
|
+
handleMailboxRegister(server, req, res)
|
|
464
|
+
return
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
if (req.method === 'GET' && snapPath === '/api/snapshots') {
|
|
468
|
+
if (!server._validateBearerAuth(req, res)) return
|
|
469
|
+
try {
|
|
470
|
+
const snapshots = listSnapshots()
|
|
471
|
+
res.writeHead(200, { 'Content-Type': 'application/json' })
|
|
472
|
+
res.end(JSON.stringify({ snapshots }))
|
|
473
|
+
} catch (err) {
|
|
474
|
+
log.warn(`GET /api/snapshots failed: ${err.message}`)
|
|
475
|
+
res.writeHead(500, { 'Content-Type': 'application/json' })
|
|
476
|
+
res.end(JSON.stringify({ error: 'Failed to list snapshots' }))
|
|
477
|
+
}
|
|
478
|
+
return
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
// Snapshot delete endpoint (#5074). Two-step: docker rmi → unlink sidecar.
|
|
482
|
+
// The slug is the sidecar filename without `.json`, exactly what
|
|
483
|
+
// /api/snapshots returns, so the server never has to re-derive it
|
|
484
|
+
// from the tag. Defence-in-depth: snapshots-store re-validates the
|
|
485
|
+
// slug against the filename-safe charset before joining it to a path.
|
|
486
|
+
//
|
|
487
|
+
// Host-level mutation (removes a docker image + sidecar shared across all
|
|
488
|
+
// sessions), so it requires PRIMARY authority — a bound (share-a-session)
|
|
489
|
+
// token must not delete host snapshots. Mirrors the /api/pages DELETE gate.
|
|
490
|
+
// The GET list above stays on _validateBearerAuth (reads are open). (#5074 / audit P1-6)
|
|
491
|
+
if (req.method === 'DELETE' && snapPath.startsWith('/api/snapshots/')) {
|
|
492
|
+
if (!server._validatePrimaryBearerAuth(req, res)) return
|
|
493
|
+
const rawSlug = snapPath.slice('/api/snapshots/'.length)
|
|
494
|
+
let slug
|
|
495
|
+
try {
|
|
496
|
+
slug = decodeURIComponent(rawSlug)
|
|
497
|
+
} catch {
|
|
498
|
+
res.writeHead(400, { 'Content-Type': 'application/json' })
|
|
499
|
+
res.end(JSON.stringify({ error: 'invalid slug encoding' }))
|
|
500
|
+
return
|
|
501
|
+
}
|
|
502
|
+
try {
|
|
503
|
+
const removeImage = await resolveRemoveImage(server)
|
|
504
|
+
const result = await deleteSnapshot(slug, { removeImage })
|
|
505
|
+
if (!result.ok) {
|
|
506
|
+
res.writeHead(result.status, { 'Content-Type': 'application/json' })
|
|
507
|
+
res.end(JSON.stringify({ error: result.error }))
|
|
508
|
+
return
|
|
509
|
+
}
|
|
510
|
+
res.writeHead(200, { 'Content-Type': 'application/json' })
|
|
511
|
+
res.end(JSON.stringify({
|
|
512
|
+
ok: true,
|
|
513
|
+
tag: result.tag,
|
|
514
|
+
imageRemoved: result.imageRemoved,
|
|
515
|
+
}))
|
|
516
|
+
} catch (err) {
|
|
517
|
+
log.warn(`DELETE /api/snapshots/${slug} failed: ${err.message}`)
|
|
518
|
+
res.writeHead(500, { 'Content-Type': 'application/json' })
|
|
519
|
+
res.end(JSON.stringify({ error: 'Failed to delete snapshot' }))
|
|
520
|
+
}
|
|
521
|
+
return
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
// docker-byok pool stats endpoint (#5053). Returns a rolling
|
|
525
|
+
// observability snapshot — hit/miss counters, hit rate,
|
|
526
|
+
// eviction-by-reason, the recent-evictions tail, and the live per-key
|
|
527
|
+
// parked buckets from pool.inspect(). Bearer-auth gated like every other
|
|
528
|
+
// /api route (primary token = full host authority; see
|
|
529
|
+
// docs/security/bearer-token-authority.md — this is read-only operational
|
|
530
|
+
// telemetry, no narrower scope needed).
|
|
531
|
+
//
|
|
532
|
+
// The pool is default-OFF (CHROXY_DOCKER_BYOK_POOL=1 to enable). When
|
|
533
|
+
// disabled we return a stable `{ enabled: false }` shape (still authed)
|
|
534
|
+
// so the dashboard can hide the panel without special-casing a 404.
|
|
535
|
+
//
|
|
536
|
+
// Test seams: `server._poolStatsEnabled` / `server._poolStats` override
|
|
537
|
+
// the env probe + aggregator so http-routes tests don't depend on
|
|
538
|
+
// process.env or a live pool.
|
|
539
|
+
// #5683 (PR-2) — Chroxy Pages publish/manage API. PRIMARY-token only: each
|
|
540
|
+
// call writes to the host disk and mints a PUBLIC capability URL, so it is
|
|
541
|
+
// host-authority (a bound/pairing token is rejected with primary_token_required,
|
|
542
|
+
// matching the other host-write routes — see bearer-token-authority.md §4).
|
|
543
|
+
if (req.method === 'POST' && snapPath === '/api/pages' && server.pagesStore) {
|
|
544
|
+
if (!server._validatePrimaryBearerAuth(req, res)) return
|
|
545
|
+
// Body cap a little above the per-page byte cap to allow JSON overhead.
|
|
546
|
+
const maxBody = server.pagesStore.maxPageBytes + 1024 * 1024
|
|
547
|
+
readJsonBodyCapped(req, res, maxBody)
|
|
548
|
+
.then((parsed) => {
|
|
549
|
+
if (parsed === null) return // 413/400 already sent
|
|
550
|
+
const title = typeof parsed.title === 'string' ? parsed.title : 'Untitled'
|
|
551
|
+
// Accept either { html } (single self-contained page) or
|
|
552
|
+
// { files: [{ path, content }] } (multi-file). `html` is shorthand.
|
|
553
|
+
let files
|
|
554
|
+
if (typeof parsed.html === 'string') {
|
|
555
|
+
files = [{ path: 'index.html', content: parsed.html }]
|
|
556
|
+
} else if (Array.isArray(parsed.files)) {
|
|
557
|
+
// Validate every entry instead of coercing a non-string `content` to
|
|
558
|
+
// '' — silent coercion turns an invalid client payload into a
|
|
559
|
+
// successfully published but empty/garbled page.
|
|
560
|
+
const invalid = parsed.files.find((f) => !f || typeof f.path !== 'string' || typeof f.content !== 'string')
|
|
561
|
+
if (invalid !== undefined) {
|
|
562
|
+
res.writeHead(400, { 'Content-Type': 'application/json' })
|
|
563
|
+
res.end(JSON.stringify({ error: 'each `files` entry requires a string `path` and string `content`' }))
|
|
564
|
+
return
|
|
565
|
+
}
|
|
566
|
+
files = parsed.files.map((f) => ({ path: f.path, content: f.content }))
|
|
567
|
+
} else {
|
|
568
|
+
res.writeHead(400, { 'Content-Type': 'application/json' })
|
|
569
|
+
res.end(JSON.stringify({ error: 'body must include `html` (string) or `files` (array)' }))
|
|
570
|
+
return
|
|
571
|
+
}
|
|
572
|
+
let meta
|
|
573
|
+
try {
|
|
574
|
+
meta = server.pagesStore.publish({ title, files })
|
|
575
|
+
} catch (err) {
|
|
576
|
+
// publish() throws for BOTH client validation errors (plain Errors —
|
|
577
|
+
// bad paths, missing index.html, size/count caps) AND server-side I/O
|
|
578
|
+
// faults (which carry an errno `code` like EACCES/ENOSPC). Don't
|
|
579
|
+
// misreport an I/O fault as a 400, and don't leak fs detail in it.
|
|
580
|
+
if (err && typeof err.code === 'string') {
|
|
581
|
+
log.warn(`POST /api/pages publish I/O error: ${err.code} ${err?.message || ''}`)
|
|
582
|
+
res.writeHead(500, { 'Content-Type': 'application/json' })
|
|
583
|
+
res.end(JSON.stringify({ error: 'publish failed' }))
|
|
584
|
+
} else {
|
|
585
|
+
res.writeHead(400, { 'Content-Type': 'application/json' })
|
|
586
|
+
res.end(JSON.stringify({ error: err?.message || 'publish failed' }))
|
|
587
|
+
}
|
|
588
|
+
return
|
|
589
|
+
}
|
|
590
|
+
res.writeHead(200, { 'Content-Type': 'application/json' })
|
|
591
|
+
res.end(JSON.stringify({ slug: meta.slug, path: `/p/${meta.slug}/`, title: meta.title, bytes: meta.bytes, createdAt: meta.createdAt }))
|
|
592
|
+
})
|
|
593
|
+
.catch((err) => {
|
|
594
|
+
log.warn(`POST /api/pages failed: ${err?.message || err}`)
|
|
595
|
+
if (!res.headersSent) {
|
|
596
|
+
res.writeHead(500, { 'Content-Type': 'application/json' })
|
|
597
|
+
res.end(JSON.stringify({ error: 'publish failed' }))
|
|
598
|
+
}
|
|
599
|
+
})
|
|
600
|
+
return
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
if (req.method === 'GET' && snapPath === '/api/pages' && server.pagesStore) {
|
|
604
|
+
if (!server._validatePrimaryBearerAuth(req, res)) return
|
|
605
|
+
const pages = server.pagesStore.list().map((p) => ({
|
|
606
|
+
slug: p.slug, title: p.title, createdAt: p.createdAt, bytes: p.bytes, path: `/p/${p.slug}/`,
|
|
607
|
+
}))
|
|
608
|
+
res.writeHead(200, { 'Content-Type': 'application/json' })
|
|
609
|
+
res.end(JSON.stringify({ pages }))
|
|
610
|
+
return
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
if (req.method === 'DELETE' && snapPath.startsWith('/api/pages/') && server.pagesStore) {
|
|
614
|
+
if (!server._validatePrimaryBearerAuth(req, res)) return
|
|
615
|
+
let slug
|
|
616
|
+
try {
|
|
617
|
+
slug = decodeURIComponent(snapPath.slice('/api/pages/'.length))
|
|
618
|
+
} catch {
|
|
619
|
+
res.writeHead(400, { 'Content-Type': 'application/json' })
|
|
620
|
+
res.end(JSON.stringify({ error: 'invalid slug' }))
|
|
621
|
+
return
|
|
622
|
+
}
|
|
623
|
+
// Idempotent: deleting an absent slug returns 200 { removed: false }
|
|
624
|
+
// rather than 404, so `chroxy pages rm` of an already-gone page reports
|
|
625
|
+
// cleanly instead of failing.
|
|
626
|
+
const removed = server.pagesStore.remove(slug)
|
|
627
|
+
res.writeHead(200, { 'Content-Type': 'application/json' })
|
|
628
|
+
res.end(JSON.stringify({ removed }))
|
|
629
|
+
return
|
|
630
|
+
}
|
|
631
|
+
|
|
632
|
+
if (req.method === 'GET' && snapPath === '/api/pool/stats') {
|
|
633
|
+
if (!server._validateBearerAuth(req, res)) return
|
|
634
|
+
const enabled = typeof server._poolStatsEnabled === 'boolean'
|
|
635
|
+
? server._poolStatsEnabled
|
|
636
|
+
: isPoolEnabled(process.env)
|
|
637
|
+
if (!enabled) {
|
|
638
|
+
res.writeHead(200, { 'Content-Type': 'application/json' })
|
|
639
|
+
res.end(JSON.stringify({ enabled: false }))
|
|
640
|
+
return
|
|
641
|
+
}
|
|
642
|
+
try {
|
|
643
|
+
const aggregator = server._poolStats ?? getSharedPoolStats()
|
|
644
|
+
const stats = aggregator.snapshot()
|
|
645
|
+
res.writeHead(200, { 'Content-Type': 'application/json' })
|
|
646
|
+
res.end(JSON.stringify({ enabled: true, ...stats }))
|
|
647
|
+
} catch (err) {
|
|
648
|
+
log.warn(`GET /api/pool/stats failed: ${err.message}`)
|
|
649
|
+
res.writeHead(500, { 'Content-Type': 'application/json' })
|
|
650
|
+
res.end(JSON.stringify({ error: 'Failed to read pool stats' }))
|
|
651
|
+
}
|
|
652
|
+
return
|
|
653
|
+
}
|
|
654
|
+
|
|
655
|
+
// Diagnostics endpoint — runtime snapshot for triaging stuck sessions (#3732).
|
|
656
|
+
// Returns server state, per-session busy/pending/timeout-pause flags, and
|
|
657
|
+
// a tail of the on-disk log (#3731). Bearer-auth gated; sensitive content
|
|
658
|
+
// (tool inputs) is omitted, only `tool` + `description` surface.
|
|
659
|
+
//
|
|
660
|
+
// #3734 review (Copilot): exact pathname match (allowing query string).
|
|
661
|
+
// The earlier startsWith('/diagnostics') would have shadowed any future
|
|
662
|
+
// `/diagnostics-foo` route — accidental aliasing is a real risk in a
|
|
663
|
+
// codebase that adds endpoints regularly.
|
|
664
|
+
const diagPathname = (req.url ?? '').split('?')[0]
|
|
665
|
+
if (req.method === 'GET' && diagPathname === '/diagnostics') {
|
|
666
|
+
// #3737: per-IP rate limit. Check BEFORE auth so a stolen token can't
|
|
667
|
+
// DoS the endpoint, and so an unauthenticated flood doesn't get a free
|
|
668
|
+
// pass to the auth code path. Uses getRateLimitKey so forwarded
|
|
669
|
+
// headers (CF-Connecting-IP / X-Forwarded-For) are trusted only when
|
|
670
|
+
// the TCP peer is loopback — i.e. the request came through the local
|
|
671
|
+
// cloudflared process. Direct connections use the socket address so
|
|
672
|
+
// header spoofing cannot exhaust another IP's bucket.
|
|
673
|
+
const limiter = server._diagnosticsRateLimiter
|
|
674
|
+
if (limiter) {
|
|
675
|
+
const socketIp = req.socket?.remoteAddress || ''
|
|
676
|
+
const rateLimitKey = getRateLimitKey(socketIp, req)
|
|
677
|
+
const { allowed, retryAfterMs } = limiter.check(rateLimitKey)
|
|
678
|
+
if (!allowed) {
|
|
679
|
+
log.warn(`Rate limited GET /diagnostics from ${rateLimitKey}`)
|
|
680
|
+
res.writeHead(429, {
|
|
681
|
+
'Content-Type': 'application/json',
|
|
682
|
+
'Retry-After': Math.ceil(retryAfterMs / 1000),
|
|
683
|
+
})
|
|
684
|
+
res.end(JSON.stringify({ error: 'rate limited', retryAfterMs }))
|
|
685
|
+
return
|
|
686
|
+
}
|
|
687
|
+
}
|
|
688
|
+
if (!server._validateBearerAuth(req, res)) return
|
|
689
|
+
// #3739: optional `?logTailBytes=N` lets operators widen the log
|
|
690
|
+
// window (e.g. to 32KB for a slow stall) or shrink it for a tight
|
|
691
|
+
// repro. Default falls through to buildDiagnosticsSnapshot's own
|
|
692
|
+
// default (8192). Hard-clamp at LOG_TAIL_BYTES_MAX so a stolen
|
|
693
|
+
// token can't slurp megabytes of log into memory per request.
|
|
694
|
+
const diagOpts = { server, serverVersion: SERVER_VERSION }
|
|
695
|
+
const logTailBytes = parseLogTailBytes(req.url)
|
|
696
|
+
if (logTailBytes !== null) diagOpts.logTailBytes = logTailBytes
|
|
697
|
+
const snapshot = buildDiagnosticsSnapshot(diagOpts)
|
|
698
|
+
const accept = req.headers['accept'] || ''
|
|
699
|
+
if (accept.includes('text/plain')) {
|
|
700
|
+
res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' })
|
|
701
|
+
res.end(formatDiagnosticsText(snapshot))
|
|
702
|
+
return
|
|
703
|
+
}
|
|
704
|
+
res.writeHead(200, { 'Content-Type': 'application/json' })
|
|
705
|
+
res.end(JSON.stringify(snapshot, null, 2))
|
|
706
|
+
return
|
|
707
|
+
}
|
|
708
|
+
|
|
709
|
+
// Permission hook endpoint
|
|
710
|
+
if (req.method === 'POST' && req.url === '/permission') {
|
|
711
|
+
server._permissions.handlePermissionRequest(req, res)
|
|
712
|
+
return
|
|
713
|
+
}
|
|
714
|
+
|
|
715
|
+
// Permission response endpoint (HTTP fallback)
|
|
716
|
+
if (req.method === 'POST' && req.url === '/permission-response') {
|
|
717
|
+
server._permissions.handlePermissionResponseHttp(req, res)
|
|
718
|
+
return
|
|
719
|
+
}
|
|
720
|
+
|
|
721
|
+
// Connection info endpoint.
|
|
722
|
+
//
|
|
723
|
+
// Gated on the PRIMARY token class (#5533 sibling audit): when auth is
|
|
724
|
+
// required (the normal case), the response body carries the raw PRIMARY
|
|
725
|
+
// apiToken and a connectionUrl that embeds it (see startup-display.js →
|
|
726
|
+
// writeConnectionInfo). Accepting a pairing-bound session token here would
|
|
727
|
+
// hand a once-paired, session-scoped device the full primary token — a
|
|
728
|
+
// strict privilege escalation, worse than the /qr + /pairing-code leak.
|
|
729
|
+
// The redaction branch below only fires when auth is DISABLED, so it cannot
|
|
730
|
+
// be relied on as the boundary. The dashboard's ConsolePage / tunnel-ready
|
|
731
|
+
// probe both fetch /connect with the primary token, so they keep working.
|
|
732
|
+
if (req.method === 'GET' && req.url === '/connect') {
|
|
733
|
+
if (!server._validatePrimaryBearerAuth(req, res)) return
|
|
734
|
+
const connInfo = readConnectionInfo()
|
|
735
|
+
if (!connInfo) {
|
|
736
|
+
res.writeHead(404, { 'Content-Type': 'application/json' })
|
|
737
|
+
res.end(JSON.stringify({ error: 'No connection info available' }))
|
|
738
|
+
return
|
|
739
|
+
}
|
|
740
|
+
if (!server.authRequired) {
|
|
741
|
+
if (connInfo.apiToken) connInfo.apiToken = '[REDACTED]'
|
|
742
|
+
delete connInfo.connectionUrl
|
|
743
|
+
}
|
|
744
|
+
const connectCors = matchAllowedOrigin(req.headers['origin'])
|
|
745
|
+
// no-store: the body carries the raw primary apiToken (and a connectionUrl
|
|
746
|
+
// embedding it) when auth is required, so browsers/proxies must not cache
|
|
747
|
+
// it — mirrors /pairing-code, which is also live credential material.
|
|
748
|
+
const connectHeaders = { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' }
|
|
749
|
+
if (connectCors) {
|
|
750
|
+
connectHeaders['Access-Control-Allow-Origin'] = connectCors
|
|
751
|
+
connectHeaders['Vary'] = 'Origin'
|
|
752
|
+
}
|
|
753
|
+
res.writeHead(200, connectHeaders)
|
|
754
|
+
res.end(JSON.stringify(connInfo))
|
|
755
|
+
return
|
|
756
|
+
}
|
|
757
|
+
|
|
758
|
+
// Typeable pairing-code endpoint (#5512): GET /pairing-code returns the
|
|
759
|
+
// current linking-mode pairing code as JSON so the dashboard/CLI can DISPLAY
|
|
760
|
+
// it beside the QR (the QR encodes the same id — one mechanism). Grace-
|
|
761
|
+
// extension mirrors /qr; camera-less devices enter this code by hand.
|
|
762
|
+
//
|
|
763
|
+
// Gated on the PRIMARY token class (#5533): the displayed code is live
|
|
764
|
+
// pairing material — anyone who can read it can onboard a new peer. A
|
|
765
|
+
// pairing-bound session token is scoped to one session, NOT host-level, so
|
|
766
|
+
// letting it read the current code would let a once-paired device
|
|
767
|
+
// transitively mint further peers. The daemon's own dashboard and
|
|
768
|
+
// `chroxy pair-code` both present the primary token, so the display path is
|
|
769
|
+
// unaffected; only the escalation path closes.
|
|
770
|
+
if (req.method === 'GET' && req.url?.split('?')[0] === '/pairing-code') {
|
|
771
|
+
if (!server._validatePrimaryBearerAuth(req, res)) return
|
|
772
|
+
const codeCors = matchAllowedOrigin(req.headers['origin'])
|
|
773
|
+
const codeHeaders = { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' }
|
|
774
|
+
if (codeCors) {
|
|
775
|
+
codeHeaders['Access-Control-Allow-Origin'] = codeCors
|
|
776
|
+
codeHeaders['Vary'] = 'Origin'
|
|
777
|
+
}
|
|
778
|
+
if (!server._pairingManager) {
|
|
779
|
+
res.writeHead(503, codeHeaders)
|
|
780
|
+
res.end(JSON.stringify({ error: 'Pairing not available' }))
|
|
781
|
+
return
|
|
782
|
+
}
|
|
783
|
+
// Someone is actively viewing the code — extend the grace period so it
|
|
784
|
+
// survives long enough to be typed on the other device (mirrors /qr).
|
|
785
|
+
server._pairingManager.extendCurrentId()
|
|
786
|
+
const snap = server._pairingManager.currentPairingCode
|
|
787
|
+
if (!snap) {
|
|
788
|
+
res.writeHead(503, codeHeaders)
|
|
789
|
+
res.end(JSON.stringify({ error: 'Pairing code not available yet' }))
|
|
790
|
+
return
|
|
791
|
+
}
|
|
792
|
+
const expiresInMs = Math.max(0, snap.expiresAtMs - Date.now())
|
|
793
|
+
res.writeHead(200, codeHeaders)
|
|
794
|
+
res.end(JSON.stringify({
|
|
795
|
+
code: snap.code,
|
|
796
|
+
url: snap.url,
|
|
797
|
+
// #5536 — the daemon's pinned E2E identity public key. Absent (null)
|
|
798
|
+
// when encryption is disabled or the daemon predates pinning.
|
|
799
|
+
identityPublicKey: snap.identityPublicKey ?? null,
|
|
800
|
+
expiresAtMs: snap.expiresAtMs,
|
|
801
|
+
expiresInSeconds: Math.ceil(expiresInMs / 1000),
|
|
802
|
+
}))
|
|
803
|
+
return
|
|
804
|
+
}
|
|
805
|
+
|
|
806
|
+
// Discord pairing-link delivery (#5513, epic #5509): POST /pair-discord
|
|
807
|
+
// generates a FRESH approval-gated pairing id and posts its chroxy:// link
|
|
808
|
+
// to the configured Discord webhook. Host-triggered only (CLI / dashboard
|
|
809
|
+
// button). The gated id mints no token on redemption — the host must still
|
|
810
|
+
// approve (#5510) — so possession of the channel grants nothing.
|
|
811
|
+
//
|
|
812
|
+
// Gated on the PRIMARY token class from day one (#5533): posting a fresh
|
|
813
|
+
// pairing link is a host-authority action, so a pairing-bound session token
|
|
814
|
+
// (which is scoped, not host-level) is rejected. Mirrors /pairing-code's
|
|
815
|
+
// CORS, but uses _validatePrimaryBearerAuth instead of _validateBearerAuth.
|
|
816
|
+
if (req.method === 'POST' && req.url?.split('?')[0] === '/pair-discord') {
|
|
817
|
+
if (!server._validatePrimaryBearerAuth(req, res)) return
|
|
818
|
+
const pdCors = matchAllowedOrigin(req.headers['origin'])
|
|
819
|
+
const pdHeaders = { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' }
|
|
820
|
+
if (pdCors) {
|
|
821
|
+
pdHeaders['Access-Control-Allow-Origin'] = pdCors
|
|
822
|
+
pdHeaders['Vary'] = 'Origin'
|
|
823
|
+
}
|
|
824
|
+
if (!server._pairingManager) {
|
|
825
|
+
res.writeHead(503, pdHeaders)
|
|
826
|
+
res.end(JSON.stringify({ error: 'Pairing not available' }))
|
|
827
|
+
return
|
|
828
|
+
}
|
|
829
|
+
// Fresh gated id per trigger (60s TTL, single-use). The chroxy:// link is
|
|
830
|
+
// the only material posted — no token.
|
|
831
|
+
const gated = server._pairingManager.createApprovalGatedPairingId()
|
|
832
|
+
if (!gated?.pairingUrl) {
|
|
833
|
+
res.writeHead(503, pdHeaders)
|
|
834
|
+
res.end(JSON.stringify({ error: 'Pairing link not available — server has no public URL yet' }))
|
|
835
|
+
return
|
|
836
|
+
}
|
|
837
|
+
const expiresInSeconds = Number.isFinite(gated.expiresAt)
|
|
838
|
+
? Math.max(0, Math.ceil((gated.expiresAt - Date.now()) / 1000))
|
|
839
|
+
: 60
|
|
840
|
+
const result = await server._postPairLinkToDiscord({ url: gated.pairingUrl, expiresInSeconds })
|
|
841
|
+
if (result?.posted) {
|
|
842
|
+
res.writeHead(200, pdHeaders)
|
|
843
|
+
res.end(JSON.stringify({ posted: true, expiresInSeconds: result.expiresInSeconds ?? expiresInSeconds }))
|
|
844
|
+
return
|
|
845
|
+
}
|
|
846
|
+
// not_configured → 409 (no webhook set); anything else → 502 (post failed).
|
|
847
|
+
// The webhook URL / token never appears in the response — postPairLinkToDiscord
|
|
848
|
+
// returns only a fixed reason code.
|
|
849
|
+
const status = result?.reason === 'not_configured' ? 409 : 502
|
|
850
|
+
res.writeHead(status, pdHeaders)
|
|
851
|
+
res.end(JSON.stringify({ posted: false, reason: result?.reason || 'post_failed' }))
|
|
852
|
+
return
|
|
853
|
+
}
|
|
854
|
+
|
|
855
|
+
// Per-session QR endpoint (#3070): GET /qr/session/:sessionId returns a
|
|
856
|
+
// QR whose pairing URL issues a session-bound token. The scanner can chat
|
|
857
|
+
// into that one session but cannot list/switch/destroy others. Must be
|
|
858
|
+
// matched BEFORE the generic /qr handler since both share the prefix.
|
|
859
|
+
//
|
|
860
|
+
// Gated on the PRIMARY token class (#5533): generating a share QR MINTS a
|
|
861
|
+
// fresh bound pairing id (live pairing material). Letting a pairing-bound
|
|
862
|
+
// token reach this would let a once-paired device transitively mint peers
|
|
863
|
+
// for its session — the same escalation the linking /qr and /pairing-code
|
|
864
|
+
// close. The "Share this session" dashboard button runs on the daemon's own
|
|
865
|
+
// dashboard with the primary token, so the legitimate path is unaffected.
|
|
866
|
+
if (req.method === 'GET' && req.url?.startsWith('/qr/session/')) {
|
|
867
|
+
if (!server._validatePrimaryBearerAuth(req, res)) return
|
|
868
|
+
const shareCors = matchAllowedOrigin(req.headers['origin'])
|
|
869
|
+
const sharePathParts = req.url.split('?')[0].split('/').filter(Boolean) // ['qr','session','<id>']
|
|
870
|
+
const writeShareErr = (status, body) => {
|
|
871
|
+
const headers = { 'Content-Type': 'application/json' }
|
|
872
|
+
if (shareCors) {
|
|
873
|
+
headers['Access-Control-Allow-Origin'] = shareCors
|
|
874
|
+
headers['Vary'] = 'Origin'
|
|
875
|
+
}
|
|
876
|
+
res.writeHead(status, headers)
|
|
877
|
+
res.end(JSON.stringify(body))
|
|
878
|
+
}
|
|
879
|
+
// decodeURIComponent throws URIError on malformed percent-encoding
|
|
880
|
+
// (e.g. /qr/session/%E0%A4). Without a guard the throw surfaces as an
|
|
881
|
+
// unhandled rejection in this async handler. Return 400 instead.
|
|
882
|
+
let sessionId = null
|
|
883
|
+
if (sharePathParts[2]) {
|
|
884
|
+
try {
|
|
885
|
+
sessionId = decodeURIComponent(sharePathParts[2])
|
|
886
|
+
} catch {
|
|
887
|
+
writeShareErr(400, { error: 'Invalid sessionId encoding' })
|
|
888
|
+
return
|
|
889
|
+
}
|
|
890
|
+
}
|
|
891
|
+
if (!sessionId) {
|
|
892
|
+
writeShareErr(400, { error: 'sessionId required' })
|
|
893
|
+
return
|
|
894
|
+
}
|
|
895
|
+
// Server-side existence check — fail-fast if the session is gone, so
|
|
896
|
+
// the scanner doesn't get a doomed token.
|
|
897
|
+
const sessionExists = server.sessionManager
|
|
898
|
+
? !!server.sessionManager.getSession?.(sessionId)
|
|
899
|
+
: true // fall through if session manager isn't wired (test contexts)
|
|
900
|
+
if (!sessionExists) {
|
|
901
|
+
writeShareErr(404, { error: 'Session not found' })
|
|
902
|
+
return
|
|
903
|
+
}
|
|
904
|
+
if (!server._pairingManager) {
|
|
905
|
+
writeShareErr(503, { error: 'Pairing not available' })
|
|
906
|
+
return
|
|
907
|
+
}
|
|
908
|
+
let bound
|
|
909
|
+
try {
|
|
910
|
+
bound = server._pairingManager.generateBoundPairing(sessionId)
|
|
911
|
+
} catch (err) {
|
|
912
|
+
writeShareErr(500, { error: err?.message || 'Failed to generate share pairing' })
|
|
913
|
+
return
|
|
914
|
+
}
|
|
915
|
+
if (!bound.pairingUrl) {
|
|
916
|
+
writeShareErr(503, { error: 'Tunnel URL not yet available' })
|
|
917
|
+
return
|
|
918
|
+
}
|
|
919
|
+
try {
|
|
920
|
+
const svg = await QRCode.toString(bound.pairingUrl, {
|
|
921
|
+
type: 'svg',
|
|
922
|
+
color: { dark: '#e0e0e0', light: '#00000000' },
|
|
923
|
+
margin: 1,
|
|
924
|
+
})
|
|
925
|
+
const headers = {
|
|
926
|
+
'Content-Type': 'image/svg+xml',
|
|
927
|
+
'Cache-Control': 'no-store',
|
|
928
|
+
}
|
|
929
|
+
if (shareCors) {
|
|
930
|
+
headers['Access-Control-Allow-Origin'] = shareCors
|
|
931
|
+
headers['Vary'] = 'Origin'
|
|
932
|
+
}
|
|
933
|
+
res.writeHead(200, headers)
|
|
934
|
+
res.end(svg)
|
|
935
|
+
} catch (_err) {
|
|
936
|
+
writeShareErr(500, { error: 'Failed to generate QR code' })
|
|
937
|
+
}
|
|
938
|
+
return
|
|
939
|
+
}
|
|
940
|
+
|
|
941
|
+
// QR code endpoint — uses live pairing URL (not stale file) when available.
|
|
942
|
+
//
|
|
943
|
+
// Gated on the PRIMARY token class (#5533): the linking QR encodes a live
|
|
944
|
+
// pairing URL — scanning it onboards a new peer. A pairing-bound session
|
|
945
|
+
// token is scoped to one session, not host-level, so it must not be able to
|
|
946
|
+
// read the current QR and transitively mint further peers. The daemon's own
|
|
947
|
+
// dashboard fetches /qr with the primary token, so the modal keeps working;
|
|
948
|
+
// only the escalation path closes.
|
|
949
|
+
if (req.method === 'GET' && req.url?.startsWith('/qr')) {
|
|
950
|
+
if (!server._validatePrimaryBearerAuth(req, res)) return
|
|
951
|
+
const qrCors = matchAllowedOrigin(req.headers['origin'])
|
|
952
|
+
|
|
953
|
+
// Prefer live pairing URL from PairingManager (always current).
|
|
954
|
+
// Extend the grace period since someone is actively viewing the QR.
|
|
955
|
+
if (server._pairingManager) server._pairingManager.extendCurrentId()
|
|
956
|
+
let qrData = server._pairingManager?.currentPairingUrl
|
|
957
|
+
if (!qrData) {
|
|
958
|
+
// Fall back to connection info file
|
|
959
|
+
const connInfo = readConnectionInfo()
|
|
960
|
+
qrData = connInfo?.connectionUrl
|
|
961
|
+
}
|
|
962
|
+
if (!qrData) {
|
|
963
|
+
const errHeaders = { 'Content-Type': 'application/json' }
|
|
964
|
+
if (qrCors) {
|
|
965
|
+
errHeaders['Access-Control-Allow-Origin'] = qrCors
|
|
966
|
+
errHeaders['Vary'] = 'Origin'
|
|
967
|
+
}
|
|
968
|
+
res.writeHead(503, errHeaders)
|
|
969
|
+
res.end(JSON.stringify({ error: 'Connection info not available yet' }))
|
|
970
|
+
return
|
|
971
|
+
}
|
|
972
|
+
try {
|
|
973
|
+
const svg = await QRCode.toString(qrData, {
|
|
974
|
+
type: 'svg',
|
|
975
|
+
color: { dark: '#e0e0e0', light: '#00000000' },
|
|
976
|
+
margin: 1,
|
|
977
|
+
})
|
|
978
|
+
const qrHeaders = {
|
|
979
|
+
'Content-Type': 'image/svg+xml',
|
|
980
|
+
'Cache-Control': 'no-store',
|
|
981
|
+
}
|
|
982
|
+
if (qrCors) {
|
|
983
|
+
qrHeaders['Access-Control-Allow-Origin'] = qrCors
|
|
984
|
+
qrHeaders['Vary'] = 'Origin'
|
|
985
|
+
}
|
|
986
|
+
res.writeHead(200, qrHeaders)
|
|
987
|
+
res.end(svg)
|
|
988
|
+
} catch (_err) {
|
|
989
|
+
res.writeHead(500, { 'Content-Type': 'application/json' })
|
|
990
|
+
res.end(JSON.stringify({ error: 'Failed to generate QR code' }))
|
|
991
|
+
}
|
|
992
|
+
return
|
|
993
|
+
}
|
|
994
|
+
|
|
995
|
+
// Static assets (xterm.js, etc.)
|
|
996
|
+
if (req.method === 'GET' && req.url?.startsWith('/assets/')) {
|
|
997
|
+
const readModule = (pkg, file) => {
|
|
998
|
+
const paths = [
|
|
999
|
+
join(__dirname, '../node_modules', pkg, file),
|
|
1000
|
+
join(__dirname, '../../../node_modules', pkg, file),
|
|
1001
|
+
]
|
|
1002
|
+
for (const p of paths) {
|
|
1003
|
+
try { return readFileSync(p) } catch {}
|
|
1004
|
+
}
|
|
1005
|
+
return null
|
|
1006
|
+
}
|
|
1007
|
+
const assetMap = {
|
|
1008
|
+
'/assets/xterm/xterm.js': { read: () => readModule('@xterm/xterm', 'lib/xterm.js'), type: 'application/javascript' },
|
|
1009
|
+
'/assets/xterm/xterm.css': { read: () => readModule('@xterm/xterm', 'css/xterm.css'), type: 'text/css' },
|
|
1010
|
+
'/assets/xterm/addon-fit.js': { read: () => readModule('@xterm/addon-fit', 'lib/addon-fit.js'), type: 'application/javascript' },
|
|
1011
|
+
}
|
|
1012
|
+
const assetPath = req.url.split('?')[0]
|
|
1013
|
+
const asset = assetMap[assetPath]
|
|
1014
|
+
if (asset) {
|
|
1015
|
+
try {
|
|
1016
|
+
const content = asset.read()
|
|
1017
|
+
if (!content) throw new Error('Module not found')
|
|
1018
|
+
res.writeHead(200, {
|
|
1019
|
+
'Content-Type': asset.type,
|
|
1020
|
+
'Cache-Control': 'public, max-age=86400',
|
|
1021
|
+
'X-Content-Type-Options': 'nosniff',
|
|
1022
|
+
})
|
|
1023
|
+
res.end(content)
|
|
1024
|
+
} catch (_e) {
|
|
1025
|
+
res.writeHead(404)
|
|
1026
|
+
res.end('Asset not found')
|
|
1027
|
+
}
|
|
1028
|
+
} else {
|
|
1029
|
+
res.writeHead(404)
|
|
1030
|
+
res.end('Not found')
|
|
1031
|
+
}
|
|
1032
|
+
return
|
|
1033
|
+
}
|
|
1034
|
+
|
|
1035
|
+
// Dashboard (React app built by Vite)
|
|
1036
|
+
if (req.method === 'GET' && /^\/dashboard(\/|$|\?)/.test(req.url || '')) {
|
|
1037
|
+
const dashUrl = new URL(req.url, `http://${req.headers.host || 'localhost'}`)
|
|
1038
|
+
|
|
1039
|
+
const securityHeaders = {
|
|
1040
|
+
// connect-src allows http:/https: alongside ws:/wss: so the dashboard
|
|
1041
|
+
// can reach a REMOTE LAN daemon — both its pre-WS HTTP health-check
|
|
1042
|
+
// (connection.ts) and the WebSocket itself. This unlocks the desktop
|
|
1043
|
+
// acting as a LAN client + joining a shared session on another host.
|
|
1044
|
+
//
|
|
1045
|
+
// Why a wide connect-src is safe here:
|
|
1046
|
+
// - ws:/wss: were already scheme-open (any host), so adding http:/https:
|
|
1047
|
+
// is symmetric — no NEW reachable hosts beyond what WebSocket allowed.
|
|
1048
|
+
// - script-src stays 'self' (no inline/eval), so injected content can't
|
|
1049
|
+
// run a fetch() to abuse connect-src in the first place.
|
|
1050
|
+
// - The directives that actually gate *passive* exfil — img-src,
|
|
1051
|
+
// font-src, form-action, and the default-src fallback — all stay
|
|
1052
|
+
// 'self'-scoped (img-src also data:), so a widened connect-src opens
|
|
1053
|
+
// no CSS/beacon/form exfil channel. Keep them 'self' if connect-src
|
|
1054
|
+
// is broad. (This CSP also ships on the tunnel-exposed dashboard, not
|
|
1055
|
+
// just the desktop's local view — acceptable in chroxy's single-
|
|
1056
|
+
// tenant model; see #5281 for the decision record.)
|
|
1057
|
+
// - The narrower 127.0.0.1/localhost http sources are subsumed by http:.
|
|
1058
|
+
'Content-Security-Policy': "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; connect-src 'self' ws: wss: http: https:; img-src 'self' data:; font-src 'self'; frame-src 'none'; object-src 'none'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'",
|
|
1059
|
+
'X-Frame-Options': 'DENY',
|
|
1060
|
+
'X-Content-Type-Options': 'nosniff',
|
|
1061
|
+
'Referrer-Policy': 'no-referrer',
|
|
1062
|
+
}
|
|
1063
|
+
|
|
1064
|
+
// Workspace layout: packages/dashboard/dist (dev)
|
|
1065
|
+
// Tauri bundle layout: server/src/dashboard-next/dist (bundled)
|
|
1066
|
+
const workspaceDist = join(__dirname, '..', '..', 'dashboard', 'dist')
|
|
1067
|
+
const bundleDist = join(__dirname, 'dashboard-next', 'dist')
|
|
1068
|
+
const distDir = existsSync(workspaceDist) ? workspaceDist : bundleDist
|
|
1069
|
+
if (!existsSync(distDir) && !createHttpHandler._distMissWarned) {
|
|
1070
|
+
createHttpHandler._distMissWarned = true
|
|
1071
|
+
log.warn(`Dashboard dist directory not found: ${distDir} — run "npm run build -w @chroxy/dashboard"`)
|
|
1072
|
+
}
|
|
1073
|
+
const relPath = dashUrl.pathname.replace(/^\/dashboard\/?/, '') || 'index.html'
|
|
1074
|
+
|
|
1075
|
+
// Serve static assets WITHOUT auth — hashed filenames from Vite build
|
|
1076
|
+
if (relPath.startsWith('assets/')) {
|
|
1077
|
+
const filePath = resolve(distDir, relPath)
|
|
1078
|
+
const assetRel = relative(distDir, filePath)
|
|
1079
|
+
// isAbsolute catches the Windows different-drive escape: path.relative across
|
|
1080
|
+
// drives (C:\dist -> D:\evil) returns an absolute path that has no leading '..'.
|
|
1081
|
+
if (isAbsolute(assetRel) || assetRel.startsWith('..') || assetRel === '' || assetRel.includes(`..${sep}`)) {
|
|
1082
|
+
res.writeHead(403)
|
|
1083
|
+
res.end('Forbidden')
|
|
1084
|
+
return
|
|
1085
|
+
}
|
|
1086
|
+
if (existsSync(filePath)) {
|
|
1087
|
+
const ext = relPath.split('.').pop()
|
|
1088
|
+
const mimeTypes = { js: 'application/javascript', css: 'text/css', svg: 'image/svg+xml', png: 'image/png', woff2: 'font/woff2' }
|
|
1089
|
+
try {
|
|
1090
|
+
const content = readFileSync(filePath)
|
|
1091
|
+
res.writeHead(200, {
|
|
1092
|
+
'Content-Type': mimeTypes[ext] || 'application/octet-stream',
|
|
1093
|
+
'Cache-Control': 'public, max-age=31536000, immutable',
|
|
1094
|
+
'X-Content-Type-Options': 'nosniff',
|
|
1095
|
+
})
|
|
1096
|
+
res.end(content)
|
|
1097
|
+
} catch {
|
|
1098
|
+
res.writeHead(500)
|
|
1099
|
+
res.end('Internal server error')
|
|
1100
|
+
}
|
|
1101
|
+
return
|
|
1102
|
+
}
|
|
1103
|
+
res.writeHead(404)
|
|
1104
|
+
res.end('Asset not found')
|
|
1105
|
+
return
|
|
1106
|
+
}
|
|
1107
|
+
|
|
1108
|
+
// Auth required for HTML pages
|
|
1109
|
+
if (!server._authenticateDashboardRequest(req, res, dashUrl, securityHeaders)) return
|
|
1110
|
+
|
|
1111
|
+
// SPA fallback — serve index.html with config injection
|
|
1112
|
+
const indexPath = join(distDir, 'index.html')
|
|
1113
|
+
if (existsSync(indexPath)) {
|
|
1114
|
+
let html = readFileSync(indexPath, 'utf-8')
|
|
1115
|
+
const escaped = JSON.stringify({port: server.port, noEncrypt: !server._encryptionEnabled}).replace(/'/g, ''').replace(/</g, '<').replace(/>/g, '>')
|
|
1116
|
+
const configMeta = `<meta name="chroxy-config" content='${escaped}'>`
|
|
1117
|
+
html = html.replace('</head>', `${configMeta}\n</head>`)
|
|
1118
|
+
res.writeHead(200, {
|
|
1119
|
+
'Content-Type': 'text/html; charset=utf-8',
|
|
1120
|
+
'Cache-Control': 'no-store',
|
|
1121
|
+
...securityHeaders,
|
|
1122
|
+
})
|
|
1123
|
+
res.end(html)
|
|
1124
|
+
} else {
|
|
1125
|
+
res.writeHead(404)
|
|
1126
|
+
res.end('Dashboard not built. Run: npm run build -w @chroxy/dashboard')
|
|
1127
|
+
}
|
|
1128
|
+
return
|
|
1129
|
+
}
|
|
1130
|
+
|
|
1131
|
+
// Fallback 404
|
|
1132
|
+
res.writeHead(404)
|
|
1133
|
+
res.end()
|
|
1134
|
+
}
|
|
1135
|
+
|
|
1136
|
+
// #5312 (WP-1.2) — top-level guard. Any throw/rejection escaping dispatch()
|
|
1137
|
+
// becomes a 500, never an unhandledRejection that crashes the daemon. Headers
|
|
1138
|
+
// may already be sent (a route threw mid-response); only write 500 if not.
|
|
1139
|
+
return async (req, res) => {
|
|
1140
|
+
try {
|
|
1141
|
+
await dispatch(req, res)
|
|
1142
|
+
} catch (err) {
|
|
1143
|
+
// #5312 review — log the PATH only, never the raw req.url: query strings on
|
|
1144
|
+
// dashboard/connect routes carry the API token (?token=...) which must not
|
|
1145
|
+
// leak into server logs.
|
|
1146
|
+
const pathOnly = (req.url || '').split('?')[0]
|
|
1147
|
+
log.error(`Unhandled error in HTTP handler (${req.method} ${pathOnly}): ${err?.stack || err}`)
|
|
1148
|
+
if (!res.headersSent) {
|
|
1149
|
+
try {
|
|
1150
|
+
res.writeHead(500, { 'Content-Type': 'application/json' })
|
|
1151
|
+
res.end(JSON.stringify({ error: 'Internal server error' }))
|
|
1152
|
+
} catch { /* response already torn down */ }
|
|
1153
|
+
} else {
|
|
1154
|
+
try { res.end() } catch { /* already ended */ }
|
|
1155
|
+
}
|
|
1156
|
+
}
|
|
1157
|
+
}
|
|
1158
|
+
}
|