@chroxy/server 0.10.0 → 0.11.10
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 +602 -19
- package/README.md +2 -2
- package/hooks/claude-native-route-check.mjs +17 -0
- package/hooks/permission-hook.sh +416 -11
- package/package.json +20 -23
- package/sidecar/Dockerfile +1 -1
- package/sidecar/PROTOCOL.md +9 -1
- package/sidecar/agent.js +102 -10
- package/sidecar/package-lock.json +3 -3
- package/src/acp-config.js +206 -0
- package/src/acp-session.js +954 -0
- package/src/activity-registry.js +110 -5
- package/src/agent-connections.js +293 -0
- package/src/agent-control/client.js +1616 -0
- package/src/agent-control/events.js +547 -0
- package/src/agent-control/local-connection.js +275 -0
- package/src/agent-control/mcp-server.js +545 -0
- package/src/anthropic-compatible-config.js +29 -4
- package/src/anthropic-compatible-session.js +15 -6
- package/src/anthropic-openai-shim.js +0 -1
- package/src/archive-continuation.js +164 -0
- package/src/assistant-response.js +24 -0
- package/src/auth-probes.js +120 -13
- package/src/background-shell-tracker.js +27 -0
- package/src/base-session.js +1353 -41
- package/src/bearer-recheck.js +49 -0
- package/src/billing-budget.js +24 -1
- package/src/billing-class.js +40 -7
- package/src/binary-provenance-trust.js +101 -0
- package/src/bound-client-policy.js +279 -0
- package/src/built-in-tools/bash-exec.js +46 -7
- package/src/built-in-tools/file-ops.js +74 -9
- package/src/built-in-tools/tool-transforms.js +1113 -13
- package/src/byok-compose-state.js +6 -9
- package/src/byok-credentials.js +2 -3
- package/src/byok-mcp-client.js +1153 -20
- package/src/byok-mcp-config.js +1712 -8
- package/src/byok-mcp-fleet.js +416 -29
- package/src/byok-mcp-oauth-store.js +329 -0
- package/src/byok-mcp-oauth.js +635 -0
- package/src/byok-mcp-trust.js +257 -40
- package/src/byok-session.js +1400 -149
- package/src/byok-tool-executor.js +2681 -38
- package/src/byok-tools.js +9 -2
- package/src/channels/chroxy-channel-server.js +2 -3
- package/src/checkpoint-manager.js +96 -51
- package/src/chroxy-host-metadata.js +122 -0
- package/src/claude-channel-session.js +16 -10
- package/src/claude-model-catalog.js +131 -16
- package/src/claude-model-refresh.js +385 -0
- package/src/claude-model-request.js +103 -0
- package/src/claude-stream-parser.js +109 -3
- package/src/claude-tui/diagnostic-tail.js +83 -0
- package/src/claude-tui/form-driver.js +44 -7
- package/src/claude-tui/model-error.js +41 -0
- package/src/claude-tui/pty-driver.js +223 -60
- package/src/claude-tui/sanitize-question-payload.js +109 -0
- package/src/claude-tui/usage-limit.js +239 -0
- package/src/claude-tui-session.js +3611 -286
- package/src/claude-tui-tool-response.js +300 -0
- package/src/cli/agent-control-cmd.js +65 -0
- package/src/cli/config-cmd.js +6 -6
- package/src/cli/config-dir-cmd.js +234 -0
- package/src/cli/deploy-cmd.js +46 -11
- package/src/cli/doctor-cmd.js +7 -3
- package/src/cli/init-cmd.js +16 -17
- package/src/cli/providers-cmd.js +6 -6
- package/src/cli/schedule-cmd.js +804 -0
- package/src/cli/server-cmd.js +64 -2
- package/src/cli/service-cmd.js +70 -27
- package/src/cli/session-cmd.js +227 -74
- package/src/cli/shared.js +168 -14
- package/src/cli/tokens-cmd.js +212 -0
- package/src/cli/tunnel-cmd.js +256 -25
- package/src/cli/worktree-gc-cmd.js +2 -2
- package/src/cli-session.js +1117 -116
- package/src/cli.js +8 -0
- package/src/codex-app-server-client.js +36 -3
- package/src/codex-app-server-session.js +2108 -101
- package/src/codex-bundled-client.js +66 -0
- package/src/codex-model-catalog.js +548 -0
- package/src/codex-model-rejections.js +87 -0
- package/src/codex-native-resume.js +104 -0
- package/src/codex-protocol-capabilities.js +188 -0
- package/src/codex-session.js +571 -45
- package/src/config-dir-migration.js +444 -0
- package/src/config-dir.js +108 -0
- package/src/config.js +738 -52
- package/src/connection-authority.js +48 -0
- package/src/connection-info.js +5 -9
- package/src/connection-locality.js +60 -0
- package/src/container-liveness-monitor.js +189 -0
- package/src/continuation-metadata-worker.js +17 -0
- package/src/continuations.js +114 -0
- package/src/control-room/host-prune.js +5 -0
- package/src/control-room/integrations.js +23 -30
- package/src/control-room/skills-inventory.js +8 -3
- package/src/control-room/survey.js +32 -0
- package/src/conversation-scanner.js +40 -18
- package/src/conversation-scope.js +59 -39
- package/src/conversation-search.js +24 -22
- package/src/credential-store.js +279 -29
- package/src/daemon-commit.js +92 -0
- package/src/daemon-idle-state.js +171 -0
- package/src/daemon-update-status.js +314 -0
- package/src/dashboard-build.js +70 -0
- package/src/declared-status.js +90 -0
- package/src/deepseek-credentials.js +2 -3
- package/src/dev-preview.js +169 -182
- package/src/device-preferences.js +2 -2
- package/src/diagnostics.js +3 -0
- package/src/diff-parser.js +87 -0
- package/src/discord-credentials.js +2 -3
- package/src/docker-byok-pool.js +3 -1
- package/src/docker-byok-session.js +678 -78
- package/src/docker-image-allowlist.js +23 -1
- package/src/docker-sdk-session.js +188 -4
- package/src/docker-session.js +293 -10
- package/src/doctor.js +783 -66
- package/src/edited-input.js +264 -0
- package/src/environment-manager.js +175 -36
- package/src/environments/authority.js +95 -0
- package/src/environments/backends/container-claude-spawn.js +94 -0
- package/src/environments/backends/docker.js +39 -10
- package/src/environments/backends/k8s.js +58 -24
- package/src/environments/destroy-with-sessions.js +142 -0
- package/src/event-ingest.js +137 -14
- package/src/event-normalizer.js +363 -110
- package/src/external-session-registry.js +0 -0
- package/src/gemini-session.js +100 -7
- package/src/github-webhook.js +188 -4
- package/src/handler-utils.js +563 -62
- package/src/handlers/checkpoint-handlers.js +162 -20
- package/src/handlers/control-room-handlers.js +99 -29
- package/src/handlers/conversation-handlers.js +563 -25
- package/src/handlers/credential-handlers.js +43 -2
- package/src/handlers/daemon-update-handlers.js +81 -0
- package/src/handlers/evaluator-handlers.js +14 -1
- package/src/handlers/feature-handlers.js +186 -69
- package/src/handlers/file-handlers.js +101 -13
- package/src/handlers/github-webhook-handlers.js +204 -0
- package/src/handlers/input-handlers.js +689 -48
- package/src/handlers/orchestration-handlers.js +238 -0
- package/src/handlers/scheduler-handlers.js +584 -0
- package/src/handlers/session-handlers.js +546 -16
- package/src/handlers/session-pr-status-handlers.js +283 -0
- package/src/handlers/session-pr-threads-handlers.js +247 -0
- package/src/handlers/settings-handlers.js +822 -35
- package/src/handlers/skills-handlers.js +13 -4
- package/src/handlers/summarize-handlers.js +32 -1
- package/src/handlers/survey-throttle.js +380 -0
- package/src/handlers/token-handlers.js +11 -2
- package/src/health-proof.js +40 -0
- package/src/history-page.js +104 -0
- package/src/http-routes.js +286 -8
- package/src/ide/search.js +24 -6
- package/src/ide/symbols.js +20 -6
- package/src/input-context.js +117 -0
- package/src/instruction-policy-compiler.js +229 -0
- package/src/instruction-policy.js +250 -0
- package/src/jsonl-reader.js +309 -48
- package/src/jsonl-subprocess-session.js +122 -9
- package/src/keychain.js +160 -13
- package/src/logger.js +240 -31
- package/src/mailbox-route.js +11 -22
- package/src/message-wire.js +386 -0
- package/src/model-discovery.js +43 -3
- package/src/models.js +1276 -174
- package/src/notification-prefs.js +100 -10
- package/src/notifications/discord-billing-sink.js +22 -5
- package/src/notifications/discord-ci-sink.js +243 -0
- package/src/notifications/discord-webhook-client.js +71 -0
- package/src/notifications/discord-webhook-sink.js +82 -12
- package/src/notifications/expo-push-sink.js +85 -6
- package/src/notifications/ready-body.js +16 -5
- package/src/ollama-session.js +34 -2
- package/src/orchestration/build-manager.js +63 -0
- package/src/orchestration/decision-contract.js +245 -0
- package/src/orchestration/git-ops.js +381 -0
- package/src/orchestration/orchestration-manager.js +1342 -0
- package/src/orchestration/permission-gate.js +121 -0
- package/src/orchestration/role-prompts.js +136 -0
- package/src/orchestration/run-budget.js +81 -0
- package/src/orchestration/run-ledger.js +487 -0
- package/src/orchestration/run-model.js +206 -0
- package/src/orchestration/run-record.js +336 -0
- package/src/orchestration/run-report.js +194 -0
- package/src/orchestration/to-wire.js +201 -0
- package/src/orchestration/turn-driver.js +422 -0
- package/src/orphan-reaper.js +413 -0
- package/src/outgoing-policy.js +183 -0
- package/src/pairing.js +236 -12
- package/src/path-hash-trust-ledger.js +642 -25
- package/src/permission-audit.js +79 -3
- package/src/permission-deadlines.js +82 -0
- package/src/permission-floor.js +1770 -0
- package/src/permission-hook.js +180 -69
- package/src/permission-manager.js +1175 -94
- package/src/permission-mode-support.js +35 -0
- package/src/permission-resolver.js +174 -12
- package/src/permission-rule-store.js +411 -0
- package/src/permission-scope.js +43 -0
- package/src/platform.js +483 -23
- package/src/preview-ingress.js +54 -0
- package/src/preview-target.js +213 -0
- package/src/prompt-evaluator.js +34 -4
- package/src/provider-customization.js +180 -0
- package/src/providers.js +228 -6
- package/src/push.js +30 -4
- package/src/question-route-map.js +130 -0
- package/src/redaction.js +360 -8
- package/src/roster-broadcast.js +186 -0
- package/src/schedule-parser.js +311 -0
- package/src/scheduled-task-store.js +945 -0
- package/src/scheduler.js +1099 -0
- package/src/sdk-session.js +2374 -168
- package/src/server-cli/preview-shutdown.js +22 -0
- package/src/server-cli/push-notification-handler.js +11 -2
- package/src/server-cli/server-orchestrator.js +50 -4
- package/src/server-cli/tunnel-lifecycle-handler.js +3 -2
- package/src/server-cli-child.js +33 -18
- package/src/server-cli.js +760 -62
- package/src/server-identity.js +42 -14
- package/src/service.js +682 -53
- package/src/session-archive-limits.js +15 -0
- package/src/session-archive.js +1029 -0
- package/src/session-busy-state.js +72 -0
- package/src/session-ci-watcher.js +926 -0
- package/src/session-context.js +7 -2
- package/src/session-manager.js +3879 -308
- package/src/session-message-history.js +749 -37
- package/src/session-pr-status.js +654 -0
- package/src/session-pr-threads.js +271 -0
- package/src/session-preset-trust.js +3 -3
- package/src/session-preset.js +10 -5
- package/src/session-state-persistence.js +94 -17
- package/src/session-timeout-manager.js +20 -0
- package/src/session-title.js +168 -0
- package/src/session-token-store.js +70 -36
- package/src/session-wake.js +240 -0
- package/src/shell-approval-info.js +2 -2
- package/src/shell-approval-store.js +3 -1
- package/src/skills-loader.js +7 -4
- package/src/skills-manager.js +2 -2
- package/src/skills-trust.js +95 -13
- package/src/skills-usage.js +22 -5
- package/src/snapshots-store.js +2 -3
- package/src/statusline.js +596 -0
- package/src/subagent-counter.js +9 -1
- package/src/summarize-session.js +51 -4
- package/src/supervisor.js +99 -38
- package/src/sweep-stale-provider-dirs.js +95 -0
- package/src/thinking-level-wire.js +39 -0
- package/src/thinking-stream.js +179 -0
- package/src/token-manager.js +39 -9
- package/src/tool-result.js +61 -0
- package/src/transcript-sources.js +109 -0
- package/src/transcript-tasks.js +413 -31
- package/src/trusted-file-read.js +302 -0
- package/src/tunnel/base.js +0 -8
- package/src/tunnel/cloudflare.js +145 -35
- package/src/tunnel/index.js +13 -1
- package/src/tunnel/preview.js +64 -0
- package/src/tunnel-check.js +1 -1
- package/src/turn-outcome.js +137 -0
- package/src/turn-tracker.js +0 -0
- package/src/usage-normalize.js +122 -0
- package/src/user-shell-session.js +157 -37
- package/src/utils/agent-sdk-version.js +107 -0
- package/src/utils/argv-safety.js +741 -0
- package/src/utils/auth-cause.js +60 -0
- package/src/utils/binary-package-manifest.js +597 -0
- package/src/utils/binary-version.js +224 -0
- package/src/utils/bounded-regex-worker.js +25 -0
- package/src/utils/bounded-regex.js +153 -0
- package/src/utils/claude-binary.js +43 -0
- package/src/utils/claude-config-dir.js +245 -0
- package/src/utils/claude-login-command.js +16 -0
- package/src/utils/claude-native-route.js +81 -0
- package/src/utils/componentwise-resolver.js +301 -0
- package/src/utils/composite-key.js +45 -0
- package/src/utils/deploy-control-files.js +87 -0
- package/src/utils/exec-failure-reason.js +21 -0
- package/src/utils/git-repo.js +42 -0
- package/src/utils/is-entry-point.js +137 -0
- package/src/utils/iso-datetime.js +51 -0
- package/src/utils/node-pty-probe.js +95 -0
- package/src/utils/node-pty-support.js +118 -0
- package/src/utils/opened-file-path.js +167 -0
- package/src/utils/path-containment.js +165 -0
- package/src/utils/permission-mode-sidecar.js +51 -0
- package/src/utils/preflight.js +485 -29
- package/src/utils/read-limiter.js +217 -0
- package/src/utils/regular-file.js +375 -0
- package/src/utils/safe-regex.js +113 -0
- package/src/utils/small-file.js +129 -0
- package/src/utils/spawn-env.js +196 -5
- package/src/utils/stale-session-dirs.js +182 -0
- package/src/utils/stat-identity.js +43 -0
- package/src/utils/verify-binary.js +276 -0
- package/src/utils/verify-provenance.js +634 -0
- package/src/utils/wire-counters.js +48 -0
- package/src/web-task-manager.js +256 -16
- package/src/worktree-gc.js +11 -3
- package/src/ws-auth.js +69 -21
- package/src/ws-broadcaster.js +14 -2
- package/src/ws-client-manager.js +16 -1
- package/src/ws-client-sender.js +7 -0
- package/src/ws-file-ops/browser.js +370 -66
- package/src/ws-file-ops/common.js +384 -11
- package/src/ws-file-ops/git.js +615 -44
- package/src/ws-file-ops/index.js +7 -0
- package/src/ws-file-ops/memory.js +460 -0
- package/src/ws-file-ops/open-nofollow.js +354 -0
- package/src/ws-file-ops/reader.js +676 -94
- package/src/ws-forwarding.js +373 -55
- package/src/ws-handler-context.js +89 -2
- package/src/ws-history.js +1018 -177
- package/src/ws-message-handlers.js +23 -1
- package/src/ws-outbound-schemas.js +207 -0
- package/src/ws-permissions.js +589 -38
- package/src/ws-schemas.js +6 -0
- package/src/ws-server.js +936 -105
- package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +0 -111
- package/src/dashboard-next/dist/assets/index-DM-_dISG.css +0 -1
- package/src/dashboard-next/dist/index.html +0 -13
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
// #8860: the shared, bounded page reader for a PRESERVED history array. Two
|
|
2
|
+
// callers read a saved history without a live session behind it — a parked
|
|
3
|
+
// failed restore (`SessionManager.getFailedRestoreHistory`) and the provider-
|
|
4
|
+
// neutral session archive (`SessionArchive.getHistoryPage`) — and both must
|
|
5
|
+
// serve exactly the same bounded, replay-safe shape. One implementation, so a
|
|
6
|
+
// bound tightened for one cannot stay loose on the other.
|
|
7
|
+
|
|
8
|
+
// Page bounds. Mirrors the protocol's `get_failed_restore_history` /
|
|
9
|
+
// `get_archived_session_history` limit (1..100); the clamp is repeated here
|
|
10
|
+
// because this is the enforcement point for any caller, not just the handler.
|
|
11
|
+
export const HISTORY_PAGE_DEFAULT_LIMIT = 50
|
|
12
|
+
export const HISTORY_PAGE_MAX_LIMIT = 100
|
|
13
|
+
// A page is also bounded by its serialized size. It goes out as ONE WebSocket
|
|
14
|
+
// frame, and ws-client-sender evicts a client whose post-send bufferedAmount
|
|
15
|
+
// passes 1 MiB; with permessage-deflate the buffered size has been measured at
|
|
16
|
+
// ~1.34x the JSON. 256 KiB of JSON keeps a page well under that. An entry that
|
|
17
|
+
// is alone bigger than the per-entry cap has its large fields shortened for
|
|
18
|
+
// display, so a single entry can never blow the page either.
|
|
19
|
+
export const HISTORY_PAGE_BYTES = 256 * 1024
|
|
20
|
+
export const HISTORY_ENTRY_BYTES = 64 * 1024
|
|
21
|
+
export const HISTORY_FIELD_CHARS = 16 * 1024
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* #8860: one preserved-history entry as the history-page replies send it.
|
|
25
|
+
*
|
|
26
|
+
* - The same `truncateEntry` the persistence boundary uses (it also drops
|
|
27
|
+
* `_seq`), and the same server-only fields normal history replay strips
|
|
28
|
+
* (`sourceToolUseId`, `answered`; see ws-history.js), so this read path shows
|
|
29
|
+
* no more than replay would.
|
|
30
|
+
* - An entry still bigger than HISTORY_ENTRY_BYTES (a long
|
|
31
|
+
* message, a large tool input or result) has `content` / `result` / `input`
|
|
32
|
+
* shortened for display, and if that is still not enough it is reduced to a
|
|
33
|
+
* bounded type, a numeric timestamp and `isError`, marked `_truncated` (the
|
|
34
|
+
* panel shows it as too large to show). Nothing on disk changes.
|
|
35
|
+
* - A non-object slot (a hand-edited state file) becomes `{ type: 'unknown' }`
|
|
36
|
+
* rather than being dropped, so page offsets keep matching history indexes.
|
|
37
|
+
*
|
|
38
|
+
* @param {unknown} raw
|
|
39
|
+
* @param {{ truncateEntry: (entry: object) => object }} history
|
|
40
|
+
* @returns {object}
|
|
41
|
+
*/
|
|
42
|
+
export function historyWireEntry(raw, history) {
|
|
43
|
+
if (!raw || typeof raw !== 'object') return { type: 'unknown' }
|
|
44
|
+
const { sourceToolUseId: _sourceToolUseId, answered: _answered, ...entry } = history.truncateEntry(raw)
|
|
45
|
+
if (Buffer.byteLength(JSON.stringify(entry)) <= HISTORY_ENTRY_BYTES) return entry
|
|
46
|
+
const max = HISTORY_FIELD_CHARS
|
|
47
|
+
const shorten = (text) => (text.length > max ? `${text.slice(0, max)}[truncated]` : text)
|
|
48
|
+
for (const key of ['content', 'result', 'input']) {
|
|
49
|
+
const value = entry[key]
|
|
50
|
+
if (typeof value === 'string') {
|
|
51
|
+
entry[key] = shorten(value)
|
|
52
|
+
} else if (value && typeof value === 'object') {
|
|
53
|
+
let serialized
|
|
54
|
+
try { serialized = JSON.stringify(value) } catch { serialized = '[unserializable]' }
|
|
55
|
+
if (typeof serialized === 'string' && serialized.length > max) {
|
|
56
|
+
entry[key] = { _truncated: true, summary: shorten(serialized) }
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
if (Buffer.byteLength(JSON.stringify(entry)) <= HISTORY_ENTRY_BYTES) return entry
|
|
61
|
+
// Last resort (escape-heavy text, or abnormal fields of a hand-edited file):
|
|
62
|
+
// keep only small, typed metadata so this can never itself be large.
|
|
63
|
+
return {
|
|
64
|
+
type: typeof entry.type === 'string' && entry.type.length <= 64 ? entry.type : 'unknown',
|
|
65
|
+
...(Number.isFinite(entry.timestamp) ? { timestamp: entry.timestamp } : {}),
|
|
66
|
+
...(typeof entry.isError === 'boolean' ? { isError: entry.isError } : {}),
|
|
67
|
+
_truncated: true,
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* One bounded page of a preserved history, oldest first.
|
|
73
|
+
*
|
|
74
|
+
* Each entry is shaped by `historyWireEntry`, and the page stops early once its
|
|
75
|
+
* serialized size would pass HISTORY_PAGE_BYTES, so `entries` can be shorter
|
|
76
|
+
* than `limit`. `limit` is clamped to 1..MAX (default 50) and `offset` to >= 0,
|
|
77
|
+
* whatever the caller sent; a non-numeric value takes the default rather than
|
|
78
|
+
* propagating NaN into `slice`.
|
|
79
|
+
*
|
|
80
|
+
* @param {unknown} history the saved history (anything but an array reads as empty)
|
|
81
|
+
* @param {{ offset?: number, limit?: number }} [opts]
|
|
82
|
+
* @param {{ truncateEntry: (entry: object) => object }} historyHelper
|
|
83
|
+
* @returns {{ total: number, offset: number, entries: object[] }}
|
|
84
|
+
*/
|
|
85
|
+
export function pageHistory(history, { offset, limit } = {}, historyHelper) {
|
|
86
|
+
const list = Array.isArray(history) ? history : []
|
|
87
|
+
const pageSize = Number.isFinite(limit)
|
|
88
|
+
? Math.min(HISTORY_PAGE_MAX_LIMIT, Math.max(1, Math.trunc(limit)))
|
|
89
|
+
: HISTORY_PAGE_DEFAULT_LIMIT
|
|
90
|
+
const start = Number.isFinite(offset) ? Math.max(0, Math.trunc(offset)) : 0
|
|
91
|
+
const entries = []
|
|
92
|
+
let bytes = 0
|
|
93
|
+
for (const raw of list.slice(start, start + pageSize)) {
|
|
94
|
+
const entry = historyWireEntry(raw, historyHelper)
|
|
95
|
+
const size = Buffer.byteLength(JSON.stringify(entry))
|
|
96
|
+
// Always at least one entry, so paging (the next offset is
|
|
97
|
+
// `offset + entries.length`) can never stall. The per-entry cap already
|
|
98
|
+
// keeps any one entry under the page budget; this holds it if they drift.
|
|
99
|
+
if (entries.length > 0 && bytes + size > HISTORY_PAGE_BYTES) break
|
|
100
|
+
entries.push(entry)
|
|
101
|
+
bytes += size
|
|
102
|
+
}
|
|
103
|
+
return { total: list.length, offset: start, entries }
|
|
104
|
+
}
|
package/src/http-routes.js
CHANGED
|
@@ -1,20 +1,30 @@
|
|
|
1
1
|
import { readFileSync, existsSync, statSync } from 'fs'
|
|
2
|
+
import { captureBearer, bearerStillValid } from './bearer-recheck.js'
|
|
2
3
|
import { join, resolve, dirname, relative, sep, isAbsolute } from 'path'
|
|
3
4
|
import { fileURLToPath } from 'url'
|
|
4
5
|
import QRCode from 'qrcode'
|
|
6
|
+
import { DeclaredStatusInputSchema } from '@chroxy/protocol'
|
|
7
|
+
import { buildSessionTokenMismatchPayload } from './handler-utils.js'
|
|
5
8
|
import { readConnectionInfo } from './connection-info.js'
|
|
9
|
+
import { isLoopbackPeer } from './connection-locality.js'
|
|
10
|
+
import { computeDaemonIdleState } from './daemon-idle-state.js'
|
|
11
|
+
import { DAEMON_COMMIT } from './daemon-commit.js'
|
|
6
12
|
import { createLogger } from './logger.js'
|
|
7
13
|
import { metrics } from './metrics.js'
|
|
8
14
|
import { buildDiagnosticsSnapshot } from './diagnostics.js'
|
|
9
15
|
import { getRateLimitKey } from './rate-limiter.js'
|
|
10
16
|
import { listSnapshots, deleteSnapshot } from './snapshots-store.js'
|
|
11
17
|
import { handleEventIngest } from './event-ingest.js'
|
|
18
|
+
import { listContinuations } from './continuations.js'
|
|
12
19
|
import { handleGithubWebhook } from './github-webhook.js'
|
|
13
20
|
import { handleMailboxPing, handleMailboxRegister } from './mailbox-route.js'
|
|
14
21
|
import { isPoolEnabled } from './docker-byok-pool.js'
|
|
15
22
|
import { getSharedPoolStats } from './docker-byok-pool-stats.js'
|
|
16
23
|
import { isValidSlug, mimeForPath } from './pages-store.js'
|
|
17
24
|
import { sendOversizeResponse } from './http-oversize.js'
|
|
25
|
+
import { resolveDashboardDist, dashboardBuildIdOf } from './dashboard-build.js'
|
|
26
|
+
import { resolveOAuthCallback, MCP_OAUTH_CALLBACK_PATH } from './byok-mcp-oauth.js'
|
|
27
|
+
import { challengeFromUrl, computeHealthProof } from './health-proof.js'
|
|
18
28
|
|
|
19
29
|
/**
|
|
20
30
|
* #5683 — read + JSON-parse a request body with a byte cap. Resolves to the
|
|
@@ -96,6 +106,13 @@ const PAGE_SECURITY_HEADERS = {
|
|
|
96
106
|
|
|
97
107
|
const log = createLogger('ws')
|
|
98
108
|
|
|
109
|
+
/** Minimal HTML-escape for interpolating an untrusted value into a page body. */
|
|
110
|
+
function escapeHtml(s) {
|
|
111
|
+
return String(s).replace(/[&<>"']/g, (c) => (
|
|
112
|
+
{ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]
|
|
113
|
+
))
|
|
114
|
+
}
|
|
115
|
+
|
|
99
116
|
const __filename = fileURLToPath(import.meta.url)
|
|
100
117
|
const __dirname = dirname(__filename)
|
|
101
118
|
const packageJson = JSON.parse(readFileSync(join(__dirname, '../package.json'), 'utf-8'))
|
|
@@ -247,7 +264,7 @@ function matchAllowedOrigin(origin) {
|
|
|
247
264
|
* @param {object} server - WsServer instance (accessed at request time for current state)
|
|
248
265
|
* @returns {(req: import('http').IncomingMessage, res: import('http').ServerResponse) => void}
|
|
249
266
|
*/
|
|
250
|
-
export function createHttpHandler(server) {
|
|
267
|
+
export function createHttpHandler(server, { dashboardDist } = {}) {
|
|
251
268
|
// #5312 (WP-1.2) — the actual routing logic, wrapped below in a top-level
|
|
252
269
|
// try/catch so an unguarded throw from any route (e.g. buildDiagnosticsSnapshot,
|
|
253
270
|
// readConnectionInfo, or readFileSync(index)) returns 500 instead of rejecting
|
|
@@ -275,7 +292,7 @@ export function createHttpHandler(server) {
|
|
|
275
292
|
}
|
|
276
293
|
|
|
277
294
|
// Health check — Cloudflare and app verify connectivity via GET / and GET /health
|
|
278
|
-
if (req.method === 'GET' && (req.url === '/' || req.url === '/health')) {
|
|
295
|
+
if (req.method === 'GET' && (req.url === '/' || (req.url ?? '').split('?')[0] === '/health')) {
|
|
279
296
|
const accept = req.headers['accept'] || ''
|
|
280
297
|
if (req.url === '/' && accept.includes('text/html') && server.apiToken) {
|
|
281
298
|
res.writeHead(302, {
|
|
@@ -291,7 +308,17 @@ export function createHttpHandler(server) {
|
|
|
291
308
|
'Vary': 'Accept',
|
|
292
309
|
'Access-Control-Allow-Origin': '*',
|
|
293
310
|
})
|
|
294
|
-
|
|
311
|
+
const body = { status: 'ok', mode: server.serverMode, version: SERVER_VERSION }
|
|
312
|
+
// A valid challenge adds a proof keyed by the primary API token and bound
|
|
313
|
+
// to the port this server listens on. Any other value is ignored. Only a
|
|
314
|
+
// loopback peer that carries no tunnel or proxy header gets one: a tunnel
|
|
315
|
+
// client connects from loopback too, but adds those headers.
|
|
316
|
+
const challenge = isLoopbackPeer(req) ? challengeFromUrl(req.url) : null
|
|
317
|
+
if (challenge && typeof server.apiToken === 'string' && server.apiToken) {
|
|
318
|
+
const port = server.httpServer?.address?.()?.port ?? server.port
|
|
319
|
+
body.proof = computeHealthProof(server.apiToken, port, challenge)
|
|
320
|
+
}
|
|
321
|
+
res.end(JSON.stringify(body))
|
|
295
322
|
return
|
|
296
323
|
}
|
|
297
324
|
|
|
@@ -394,6 +421,116 @@ export function createHttpHandler(server) {
|
|
|
394
421
|
return
|
|
395
422
|
}
|
|
396
423
|
|
|
424
|
+
// Idle probe for the idle-only auto-deploy (#8324). `scripts/deploy-daemon.mjs`
|
|
425
|
+
// asks this before restarting the daemon, which would kill every live
|
|
426
|
+
// session. Two gates, LOCALITY FIRST: a request that did not arrive directly
|
|
427
|
+
// over loopback (a LAN peer, or anything through the tunnel — cloudflared
|
|
428
|
+
// connects from 127.0.0.1, so the socket address alone proves nothing and
|
|
429
|
+
// the proxy headers must be absent too) gets a bare 403 that says nothing
|
|
430
|
+
// about whether the token was right. Then the PRIMARY token: the answer
|
|
431
|
+
// enumerates session names, so a pairing-bound token must not reach it.
|
|
432
|
+
// Fail safe: any inability to compute is `idle: false`, never `true`.
|
|
433
|
+
if (req.method === 'GET' && (req.url ?? '').split('?')[0] === '/api/daemon/idle') {
|
|
434
|
+
if (!isLoopbackPeer(req)) {
|
|
435
|
+
res.writeHead(403, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' })
|
|
436
|
+
res.end(JSON.stringify({ error: 'forbidden' }))
|
|
437
|
+
return
|
|
438
|
+
}
|
|
439
|
+
if (!server._validatePrimaryBearerAuth(req, res)) return
|
|
440
|
+
let state
|
|
441
|
+
try {
|
|
442
|
+
state = computeDaemonIdleState({
|
|
443
|
+
sessionManager: server.sessionManager,
|
|
444
|
+
getHookPendingPermissionCount: () => server.getHookPendingPermissionCount(),
|
|
445
|
+
})
|
|
446
|
+
} catch (err) {
|
|
447
|
+
state = {
|
|
448
|
+
idle: false,
|
|
449
|
+
reasons: [`idle state unavailable: ${err?.message || String(err)}`],
|
|
450
|
+
sessions: [],
|
|
451
|
+
hookPendingPermissions: 0,
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
res.writeHead(200, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' })
|
|
455
|
+
res.end(JSON.stringify({
|
|
456
|
+
...state,
|
|
457
|
+
version: SERVER_VERSION,
|
|
458
|
+
// The commit this process started from (null when it cannot say). The
|
|
459
|
+
// auto-deploy certifies a restart only by reading this back (#8324).
|
|
460
|
+
commit: DAEMON_COMMIT,
|
|
461
|
+
pid: process.pid,
|
|
462
|
+
startedAt: Number.isFinite(server._startedAt) ? new Date(server._startedAt).toISOString() : null,
|
|
463
|
+
}))
|
|
464
|
+
return
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
// #6822 — MCP OAuth redirect callback. The browser that completed consent
|
|
468
|
+
// (on the user's own device) is redirected here with `?code=...&state=...`.
|
|
469
|
+
// This route is intentionally UNAUTHENTICATED: the redirect carries no bearer
|
|
470
|
+
// token, and the high-entropy `state` value (bound server-side to a specific
|
|
471
|
+
// pending authorization) IS the capability. We hand the code to the matching
|
|
472
|
+
// pending client, which redeems it + persists tokens. When the daemon isn't
|
|
473
|
+
// reachable from the user's browser (remote/tunneled) this page never loads —
|
|
474
|
+
// the user copy-pastes the code back over the wire instead (the universal
|
|
475
|
+
// fallback). Never logs the code.
|
|
476
|
+
const oauthCbPath = (req.url ?? '').split('?')[0]
|
|
477
|
+
if (req.method === 'GET' && oauthCbPath === MCP_OAUTH_CALLBACK_PATH) {
|
|
478
|
+
let code = null
|
|
479
|
+
let state = null
|
|
480
|
+
let oauthError = null
|
|
481
|
+
try {
|
|
482
|
+
const parsed = new URL(req.url, 'http://localhost')
|
|
483
|
+
code = parsed.searchParams.get('code')
|
|
484
|
+
state = parsed.searchParams.get('state')
|
|
485
|
+
oauthError = parsed.searchParams.get('error')
|
|
486
|
+
} catch { /* malformed url — handled as missing params below */ }
|
|
487
|
+
|
|
488
|
+
const page = (title, body) =>
|
|
489
|
+
`<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">` +
|
|
490
|
+
`<title>${title}</title><style>body{font-family:system-ui,-apple-system,sans-serif;max-width:32rem;margin:4rem auto;padding:0 1rem;color:#1a2332;line-height:1.5}` +
|
|
491
|
+
`code{background:#eef1f6;padding:.15rem .35rem;border-radius:.25rem;word-break:break-all}h1{font-size:1.25rem}</style></head><body>${body}</body></html>`
|
|
492
|
+
|
|
493
|
+
const sendPage = (status, title, body) => {
|
|
494
|
+
res.writeHead(status, { 'Content-Type': 'text/html; charset=utf-8', ...PAGE_SECURITY_HEADERS })
|
|
495
|
+
res.end(page(title, body))
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
if (oauthError) {
|
|
499
|
+
sendPage(400, 'Authorization failed',
|
|
500
|
+
`<h1>Authorization was not completed</h1><p>The authorization server reported an error. You can close this tab and try authorizing again from Chroxy.</p>`)
|
|
501
|
+
return
|
|
502
|
+
}
|
|
503
|
+
if (!code || !state) {
|
|
504
|
+
sendPage(400, 'Authorization callback',
|
|
505
|
+
`<h1>Missing authorization details</h1><p>This page expects a <code>code</code> and <code>state</code> from the authorization server. If you reached it manually, return to Chroxy and use the paste-code option.</p>`)
|
|
506
|
+
return
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
resolveOAuthCallback(state, code)
|
|
510
|
+
.then((outcome) => {
|
|
511
|
+
if (outcome.found && outcome.ok) {
|
|
512
|
+
sendPage(200, 'Authorized',
|
|
513
|
+
`<h1>MCP server authorized</h1><p>You can close this tab and return to Chroxy — the server is reconnecting now.</p>`)
|
|
514
|
+
} else if (outcome.found) {
|
|
515
|
+
// The daemon received the callback but redemption failed. Surface the
|
|
516
|
+
// code so the user can retry via paste (value shown only to the user
|
|
517
|
+
// whose browser holds the redirect; never logged server-side).
|
|
518
|
+
sendPage(200, 'Finish in Chroxy',
|
|
519
|
+
`<h1>Almost there</h1><p>Automatic completion didn't succeed. Copy this authorization code and paste it into Chroxy:</p><p><code>${escapeHtml(code)}</code></p>`)
|
|
520
|
+
} else {
|
|
521
|
+
// No pending authorization matched this state (expired, wrong daemon,
|
|
522
|
+
// or already completed). Offer the paste-code fallback.
|
|
523
|
+
sendPage(200, 'Finish in Chroxy',
|
|
524
|
+
`<h1>Finish in Chroxy</h1><p>Copy this authorization code and paste it into Chroxy to finish connecting:</p><p><code>${escapeHtml(code)}</code></p>`)
|
|
525
|
+
}
|
|
526
|
+
})
|
|
527
|
+
.catch(() => {
|
|
528
|
+
sendPage(200, 'Finish in Chroxy',
|
|
529
|
+
`<h1>Finish in Chroxy</h1><p>Copy this authorization code and paste it into Chroxy to finish connecting:</p><p><code>${escapeHtml(code)}</code></p>`)
|
|
530
|
+
})
|
|
531
|
+
return
|
|
532
|
+
}
|
|
533
|
+
|
|
397
534
|
// Metrics endpoint — operational counters for monitoring
|
|
398
535
|
if (req.method === 'GET' && req.url === '/metrics') {
|
|
399
536
|
if (!server._validateBearerAuth(req, res)) return
|
|
@@ -430,6 +567,43 @@ export function createHttpHandler(server) {
|
|
|
430
567
|
// on its SnapshotsPanel.
|
|
431
568
|
const snapPath = (req.url ?? '').split('?')[0]
|
|
432
569
|
|
|
570
|
+
// Bounded session intent writes share the existing bearer classes.
|
|
571
|
+
const statusMatch = /^\/api\/sessions\/([^/]+)\/status$/.exec(snapPath)
|
|
572
|
+
if (req.method === 'POST' && statusMatch) {
|
|
573
|
+
if (!server._validateBearerAuth(req, res, { allowScoped: true })) return
|
|
574
|
+
const sessionId = statusMatch[1]
|
|
575
|
+
const token = (req.headers.authorization || '').slice(7)
|
|
576
|
+
const pairing = server._pairingManager
|
|
577
|
+
const bearer = captureBearer(server, req)
|
|
578
|
+
const isPairing = pairing?.isSessionTokenValid(token) === true
|
|
579
|
+
const bound = isPairing ? pairing.getSessionIdForToken(token) : null
|
|
580
|
+
// Only primary or a token explicitly bound to THIS session may write.
|
|
581
|
+
if (isPairing && bound !== sessionId) {
|
|
582
|
+
res.writeHead(403, { 'Content-Type': 'application/json' })
|
|
583
|
+
const mismatch = buildSessionTokenMismatchPayload({ sessionManager: server.sessionManager, boundSessionId: bound })
|
|
584
|
+
res.end(JSON.stringify({ error: mismatch.message, ...mismatch }))
|
|
585
|
+
return
|
|
586
|
+
}
|
|
587
|
+
const body = await readJsonBodyCapped(req, res, 4096)
|
|
588
|
+
if (body === null) return
|
|
589
|
+
// A bearer is checked again once the body has arrived (bearer-recheck.js).
|
|
590
|
+
if (!bearerStillValid(server, bearer)) {
|
|
591
|
+
res.writeHead(403, { 'Content-Type': 'application/json' })
|
|
592
|
+
res.end(JSON.stringify({ error: 'unauthorized' }))
|
|
593
|
+
return
|
|
594
|
+
}
|
|
595
|
+
const parsed = DeclaredStatusInputSchema.safeParse(body)
|
|
596
|
+
if (!parsed.success) {
|
|
597
|
+
res.writeHead(400, { 'Content-Type': 'application/json' })
|
|
598
|
+
res.end(JSON.stringify({ error: 'invalid status' }))
|
|
599
|
+
return
|
|
600
|
+
}
|
|
601
|
+
const status = server.sessionManager?.setDeclaredStatus(sessionId, parsed.data, 'api')
|
|
602
|
+
res.writeHead(status ? 200 : 404, { 'Content-Type': 'application/json' })
|
|
603
|
+
res.end(JSON.stringify(status ? { ok: true, declaredStatus: status } : { error: 'session not found' }))
|
|
604
|
+
return
|
|
605
|
+
}
|
|
606
|
+
|
|
433
607
|
// External event ingest (#5413 Phase 3). Accepts ONLY the daemon-level
|
|
434
608
|
// ingest secret (never the primary token — see
|
|
435
609
|
// docs/security/bearer-token-authority.md §6); auth, body cap, schema
|
|
@@ -441,6 +615,15 @@ export function createHttpHandler(server) {
|
|
|
441
615
|
return
|
|
442
616
|
}
|
|
443
617
|
|
|
618
|
+
// Path metadata is a global host surface: primary bearer only, never the
|
|
619
|
+
// ingest credential that can announce it or a session-bound pairing token.
|
|
620
|
+
if (req.method === 'GET' && snapPath === '/api/continuations') {
|
|
621
|
+
if (!server._validatePrimaryBearerAuth(req, res)) return
|
|
622
|
+
res.writeHead(200, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' })
|
|
623
|
+
res.end(JSON.stringify({ continuations: await listContinuations(server) }))
|
|
624
|
+
return
|
|
625
|
+
}
|
|
626
|
+
|
|
444
627
|
// Control Room repo-events feed (#5966): GitHub webhook deliveries. Auth is
|
|
445
628
|
// the X-Hub-Signature-256 HMAC (NOT the ingest secret) — the handler verifies
|
|
446
629
|
// it over the RAW body before parsing, and stays inert (503) until a secret
|
|
@@ -521,6 +704,80 @@ export function createHttpHandler(server) {
|
|
|
521
704
|
return
|
|
522
705
|
}
|
|
523
706
|
|
|
707
|
+
// Paired-devices roster + live revoke (#6678, part of epic #6597). The
|
|
708
|
+
// dashboard "Paired devices" panel lists the RUNNING daemon's paired
|
|
709
|
+
// session tokens (wire-safe ids, bound session, age — never token material)
|
|
710
|
+
// and revokes them live: unlike `chroxy tokens revoke` (which edits the
|
|
711
|
+
// persisted store and needs a daemon restart), these hit PairingManager's
|
|
712
|
+
// in-memory map so the device's next auth fails immediately.
|
|
713
|
+
//
|
|
714
|
+
// PRIMARY-token only on ALL THREE. The roster is host-level pairing state —
|
|
715
|
+
// a scoped/paired device must neither enumerate its siblings (information
|
|
716
|
+
// disclosure) nor revoke them (a host-level mutation beyond one session's
|
|
717
|
+
// scope). Mirrors the DELETE /api/snapshots gate; see
|
|
718
|
+
// docs/security/bearer-token-authority.md §9.
|
|
719
|
+
if (req.method === 'GET' && snapPath === '/api/paired-devices') {
|
|
720
|
+
if (!server._validatePrimaryBearerAuth(req, res)) return
|
|
721
|
+
const pm = server._pairingManager
|
|
722
|
+
const devices = pm && typeof pm.listSessionTokens === 'function' ? pm.listSessionTokens() : []
|
|
723
|
+
res.writeHead(200, { 'Content-Type': 'application/json' })
|
|
724
|
+
res.end(JSON.stringify({ devices }))
|
|
725
|
+
return
|
|
726
|
+
}
|
|
727
|
+
|
|
728
|
+
// Revoke ALL paired devices — the panic button. Exact-path match (no id), so
|
|
729
|
+
// it never collides with the per-device DELETE below.
|
|
730
|
+
if (req.method === 'DELETE' && snapPath === '/api/paired-devices') {
|
|
731
|
+
if (!server._validatePrimaryBearerAuth(req, res)) return
|
|
732
|
+
const pm = server._pairingManager
|
|
733
|
+
const result = pm && typeof pm.revokeAllSessionTokens === 'function' ? pm.revokeAllSessionTokens() : { revoked: 0 }
|
|
734
|
+
// #6902: a failed durable write leaves every token valid on disk — report
|
|
735
|
+
// failure rather than a false `ok:true` so the operator re-tries instead of
|
|
736
|
+
// trusting a revoke a crash would undo.
|
|
737
|
+
if (result.persistFailed) {
|
|
738
|
+
res.writeHead(500, { 'Content-Type': 'application/json' })
|
|
739
|
+
res.end(JSON.stringify({ error: 'revoke not persisted', revoked: 0 }))
|
|
740
|
+
return
|
|
741
|
+
}
|
|
742
|
+
res.writeHead(200, { 'Content-Type': 'application/json' })
|
|
743
|
+
res.end(JSON.stringify({ ok: true, revoked: result.revoked }))
|
|
744
|
+
return
|
|
745
|
+
}
|
|
746
|
+
|
|
747
|
+
// Revoke ONE paired device by its wire id (from GET /api/paired-devices).
|
|
748
|
+
if (req.method === 'DELETE' && snapPath.startsWith('/api/paired-devices/')) {
|
|
749
|
+
if (!server._validatePrimaryBearerAuth(req, res)) return
|
|
750
|
+
const rawId = snapPath.slice('/api/paired-devices/'.length)
|
|
751
|
+
let id
|
|
752
|
+
try {
|
|
753
|
+
id = decodeURIComponent(rawId)
|
|
754
|
+
} catch {
|
|
755
|
+
res.writeHead(400, { 'Content-Type': 'application/json' })
|
|
756
|
+
res.end(JSON.stringify({ error: 'invalid id encoding' }))
|
|
757
|
+
return
|
|
758
|
+
}
|
|
759
|
+
const pm = server._pairingManager
|
|
760
|
+
const result = pm && typeof pm.revokeSessionTokenById === 'function' ? pm.revokeSessionTokenById(id) : { revoked: 0 }
|
|
761
|
+
// #6902: the device exists but its removal could not be durably persisted —
|
|
762
|
+
// distinct from "no such device". Report failure (500) rather than a false
|
|
763
|
+
// success so the still-valid token isn't reported as revoked.
|
|
764
|
+
if (result.persistFailed) {
|
|
765
|
+
res.writeHead(500, { 'Content-Type': 'application/json' })
|
|
766
|
+
res.end(JSON.stringify({ error: 'revoke not persisted', revoked: 0 }))
|
|
767
|
+
return
|
|
768
|
+
}
|
|
769
|
+
if (result.revoked === 0) {
|
|
770
|
+
// The device is already gone (revoked elsewhere, expired, or a stale id
|
|
771
|
+
// from a device that re-paired). 404 so the UI can reconcile its list.
|
|
772
|
+
res.writeHead(404, { 'Content-Type': 'application/json' })
|
|
773
|
+
res.end(JSON.stringify({ error: 'no such paired device', revoked: 0 }))
|
|
774
|
+
return
|
|
775
|
+
}
|
|
776
|
+
res.writeHead(200, { 'Content-Type': 'application/json' })
|
|
777
|
+
res.end(JSON.stringify({ ok: true, revoked: result.revoked }))
|
|
778
|
+
return
|
|
779
|
+
}
|
|
780
|
+
|
|
524
781
|
// docker-byok pool stats endpoint (#5053). Returns a rolling
|
|
525
782
|
// observability snapshot — hit/miss counters, hit rate,
|
|
526
783
|
// eviction-by-reason, the recent-evictions tail, and the live per-key
|
|
@@ -542,11 +799,18 @@ export function createHttpHandler(server) {
|
|
|
542
799
|
// matching the other host-write routes — see bearer-token-authority.md §4).
|
|
543
800
|
if (req.method === 'POST' && snapPath === '/api/pages' && server.pagesStore) {
|
|
544
801
|
if (!server._validatePrimaryBearerAuth(req, res)) return
|
|
802
|
+
const bearer = captureBearer(server, req)
|
|
545
803
|
// Body cap a little above the per-page byte cap to allow JSON overhead.
|
|
546
804
|
const maxBody = server.pagesStore.maxPageBytes + 1024 * 1024
|
|
547
805
|
readJsonBodyCapped(req, res, maxBody)
|
|
548
806
|
.then((parsed) => {
|
|
549
807
|
if (parsed === null) return // 413/400 already sent
|
|
808
|
+
// A bearer is checked again once the body has arrived (bearer-recheck.js).
|
|
809
|
+
if (!bearerStillValid(server, bearer)) {
|
|
810
|
+
res.writeHead(403, { 'Content-Type': 'application/json' })
|
|
811
|
+
res.end(JSON.stringify({ error: 'unauthorized' }))
|
|
812
|
+
return
|
|
813
|
+
}
|
|
550
814
|
const title = typeof parsed.title === 'string' ? parsed.title : 'Untitled'
|
|
551
815
|
// Accept either { html } (single self-contained page) or
|
|
552
816
|
// { files: [{ path, content }] } (multi-file). `html` is shorthand.
|
|
@@ -712,6 +976,16 @@ export function createHttpHandler(server) {
|
|
|
712
976
|
return
|
|
713
977
|
}
|
|
714
978
|
|
|
979
|
+
// #7004 — protected-path / secret-read FLOOR probe for the permission hook.
|
|
980
|
+
// The hook decides auto/acceptEdits in shell, so it asks here whether the
|
|
981
|
+
// target is floored before short-circuiting; a floored target is routed to a
|
|
982
|
+
// real prompt via POST /permission. Same per-session hook-secret auth as
|
|
983
|
+
// /permission; read-only (no pending request, no broadcast, no push).
|
|
984
|
+
if (req.method === 'POST' && req.url === '/permission-floor') {
|
|
985
|
+
server._permissions.handlePermissionFloorCheck(req, res)
|
|
986
|
+
return
|
|
987
|
+
}
|
|
988
|
+
|
|
715
989
|
// Permission response endpoint (HTTP fallback)
|
|
716
990
|
if (req.method === 'POST' && req.url === '/permission-response') {
|
|
717
991
|
server._permissions.handlePermissionResponseHttp(req, res)
|
|
@@ -1063,9 +1337,8 @@ export function createHttpHandler(server) {
|
|
|
1063
1337
|
|
|
1064
1338
|
// Workspace layout: packages/dashboard/dist (dev)
|
|
1065
1339
|
// Tauri bundle layout: server/src/dashboard-next/dist (bundled)
|
|
1066
|
-
|
|
1067
|
-
const
|
|
1068
|
-
const distDir = existsSync(workspaceDist) ? workspaceDist : bundleDist
|
|
1340
|
+
// `dashboardDist` is a test seam; production never passes it.
|
|
1341
|
+
const distDir = dashboardDist ?? resolveDashboardDist()
|
|
1069
1342
|
if (!existsSync(distDir) && !createHttpHandler._distMissWarned) {
|
|
1070
1343
|
createHttpHandler._distMissWarned = true
|
|
1071
1344
|
log.warn(`Dashboard dist directory not found: ${distDir} — run "npm run build -w @chroxy/dashboard"`)
|
|
@@ -1112,9 +1385,14 @@ export function createHttpHandler(server) {
|
|
|
1112
1385
|
const indexPath = join(distDir, 'index.html')
|
|
1113
1386
|
if (existsSync(indexPath)) {
|
|
1114
1387
|
let html = readFileSync(indexPath, 'utf-8')
|
|
1115
|
-
const escaped = JSON.stringify({port: server.port, noEncrypt: !server._encryptionEnabled}).replace(/'/g, ''').replace(/</g, '<').replace(/>/g, '>')
|
|
1388
|
+
const escaped = JSON.stringify({port: server.port, noEncrypt: !server._encryptionEnabled, authRequired: server.authRequired !== false}).replace(/'/g, ''').replace(/</g, '<').replace(/>/g, '>')
|
|
1116
1389
|
const configMeta = `<meta name="chroxy-config" content='${escaped}'>`
|
|
1117
|
-
|
|
1390
|
+
// #8268 — the id of the bundle THIS page loaded, hashed from the pristine
|
|
1391
|
+
// file (before the per-request config above is spliced in). The client
|
|
1392
|
+
// compares it with `auth_ok.dashboardBuildId`, which is the id of the file
|
|
1393
|
+
// on disk at connect time, so a page that outlives a daemon update can tell.
|
|
1394
|
+
const buildMeta = `<meta name="chroxy-build" content="${dashboardBuildIdOf(html)}">`
|
|
1395
|
+
html = html.replace('</head>', `${configMeta}\n${buildMeta}\n</head>`)
|
|
1118
1396
|
res.writeHead(200, {
|
|
1119
1397
|
'Content-Type': 'text/html; charset=utf-8',
|
|
1120
1398
|
'Cache-Control': 'no-store',
|
package/src/ide/search.js
CHANGED
|
@@ -14,8 +14,11 @@
|
|
|
14
14
|
* attacker-reachable WS surface's boundary; the regression tests
|
|
15
15
|
* (ide-search.test.js) assert the symlink-escape cases on both.
|
|
16
16
|
*/
|
|
17
|
-
import { readdir,
|
|
17
|
+
import { readdir, stat, realpath, lstat } from 'fs/promises'
|
|
18
18
|
import { join, resolve, relative, extname, sep } from 'path'
|
|
19
|
+
import { isPathWithin } from '../utils/path-containment.js'
|
|
20
|
+
import { makeConfigDirFilter } from '../ws-file-ops/common.js'
|
|
21
|
+
import { readContainedTextFile } from '../utils/regular-file.js'
|
|
19
22
|
|
|
20
23
|
// Directories never worth walking (mirrors symbols.js IGNORED_DIRS).
|
|
21
24
|
const IGNORED_DIRS = new Set([
|
|
@@ -95,7 +98,12 @@ async function collectMatches(rootDir, matchLine, opts = {}) {
|
|
|
95
98
|
return { results: [], truncated: false }
|
|
96
99
|
}
|
|
97
100
|
const rel = relative(root, realTarget)
|
|
98
|
-
|
|
101
|
+
// #7273 — this was `rel === '..' || rel.startsWith('..' + sep) || resolve(root, rel) !== realTarget`.
|
|
102
|
+
// Correct for same-root escapes, blind to a target on a DIFFERENT Windows root:
|
|
103
|
+
// `path.win32.relative('C:\\ws', 'D:\\x')` returns `'D:\\x'`, which is neither `'..'`
|
|
104
|
+
// nor `'..' + sep`, and the round-trip clause is a tautology for exactly that input
|
|
105
|
+
// (`resolve(root, 'D:\\x') === 'D:\\x'`). `isPathWithin` is root-aware.
|
|
106
|
+
if (!isPathWithin(realTarget, root)) {
|
|
99
107
|
return { results: [], truncated: false }
|
|
100
108
|
}
|
|
101
109
|
if (rel.split(sep).some((s) => IGNORED_DIRS.has(s) || s.startsWith('.'))) {
|
|
@@ -104,6 +112,10 @@ async function collectMatches(rootDir, matchLine, opts = {}) {
|
|
|
104
112
|
target = realTarget
|
|
105
113
|
}
|
|
106
114
|
|
|
115
|
+
// The config root is resolved once per walk; every path this walk yields is real
|
|
116
|
+
// (a real root, descended only through real directories, symlinks never followed).
|
|
117
|
+
const isDaemonState = await makeConfigDirFilter()
|
|
118
|
+
|
|
107
119
|
const results = []
|
|
108
120
|
let filesRead = 0
|
|
109
121
|
let truncated = false
|
|
@@ -126,11 +138,17 @@ async function collectMatches(rootDir, matchLine, opts = {}) {
|
|
|
126
138
|
} catch { return }
|
|
127
139
|
if (!st.isFile()) return
|
|
128
140
|
if (st.size > maxFileSize) return
|
|
141
|
+
// Files directly in the daemon's config directory are daemon-managed state, so
|
|
142
|
+
// search treats them the way the file viewer does: they contribute nothing. This
|
|
143
|
+
// matters when the session cwd is the config directory or an ancestor of a
|
|
144
|
+
// relocated, non-hidden one (the walk skips hidden directories). Checked after
|
|
145
|
+
// the cheap filters above and before the read, so a skipped file costs no read
|
|
146
|
+
// and does not count against the file cap.
|
|
147
|
+
if (isDaemonState(absPath)) return
|
|
129
148
|
filesRead++
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
} catch { return }
|
|
149
|
+
// One checked, pinned open: see readContainedTextFile.
|
|
150
|
+
const content = await readContainedTextFile(absPath, root, maxFileSize)
|
|
151
|
+
if (content === null) return
|
|
134
152
|
// Skip a file that looks binary (a NUL in the first chunk) despite its ext.
|
|
135
153
|
if (content.indexOf(String.fromCharCode(0)) !== -1) return
|
|
136
154
|
const rel = relative(root, absPath).split(sep).join('/')
|
package/src/ide/symbols.js
CHANGED
|
@@ -27,8 +27,11 @@
|
|
|
27
27
|
* @property {number} line 1-indexed line of the declaration.
|
|
28
28
|
* @property {boolean} exported Whether the declaration is exported / public.
|
|
29
29
|
*/
|
|
30
|
-
import { readdir,
|
|
30
|
+
import { readdir, stat, realpath, lstat } from 'fs/promises'
|
|
31
31
|
import { join, resolve, relative, extname, sep } from 'path'
|
|
32
|
+
import { isPathWithin } from '../utils/path-containment.js'
|
|
33
|
+
import { makeConfigDirFilter } from '../ws-file-ops/common.js'
|
|
34
|
+
import { readContainedTextFile } from '../utils/regular-file.js'
|
|
32
35
|
|
|
33
36
|
// Directories never worth walking — build output, vendored deps, VCS metadata,
|
|
34
37
|
// language caches. Keeps the scan bounded and the symbol table signal-rich.
|
|
@@ -214,7 +217,12 @@ export async function collectWorkspaceSymbols(rootDir, opts = {}) {
|
|
|
214
217
|
return { symbols: [], truncated: false }
|
|
215
218
|
}
|
|
216
219
|
const rel = relative(root, realTarget)
|
|
217
|
-
|
|
220
|
+
// #7273 — this was `rel === '..' || rel.startsWith('..' + sep) || resolve(root, rel) !== realTarget`.
|
|
221
|
+
// Correct for same-root escapes, blind to a target on a DIFFERENT Windows root:
|
|
222
|
+
// `path.win32.relative('C:\\ws', 'D:\\x')` returns `'D:\\x'`, which is neither `'..'`
|
|
223
|
+
// nor `'..' + sep`, and the round-trip clause is a tautology for exactly that input
|
|
224
|
+
// (`resolve(root, 'D:\\x') === 'D:\\x'`). `isPathWithin` is root-aware.
|
|
225
|
+
if (!isPathWithin(realTarget, root)) {
|
|
218
226
|
// The REAL path escapes the workspace (e.g. via a symlink) — refuse.
|
|
219
227
|
return { symbols: [], truncated: false }
|
|
220
228
|
}
|
|
@@ -227,6 +235,10 @@ export async function collectWorkspaceSymbols(rootDir, opts = {}) {
|
|
|
227
235
|
target = realTarget
|
|
228
236
|
}
|
|
229
237
|
|
|
238
|
+
// The config root is resolved once per walk; every path this walk yields is real
|
|
239
|
+
// (a real root, descended only through real directories, symlinks never followed).
|
|
240
|
+
const isDaemonState = await makeConfigDirFilter()
|
|
241
|
+
|
|
230
242
|
const symbols = []
|
|
231
243
|
let filesRead = 0
|
|
232
244
|
let truncated = false
|
|
@@ -244,11 +256,13 @@ export async function collectWorkspaceSymbols(rootDir, opts = {}) {
|
|
|
244
256
|
if (!st.isFile()) return
|
|
245
257
|
if (st.size > maxFileSize) return
|
|
246
258
|
if (!(extname(absPath).toLowerCase() in EXT_LANG)) return
|
|
259
|
+
// Daemon-managed state (the config directory and files directly in it) is not
|
|
260
|
+
// part of the symbol table, same as the file viewer; see ide/search.js.
|
|
261
|
+
if (isDaemonState(absPath)) return
|
|
247
262
|
filesRead++
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
} catch { return }
|
|
263
|
+
// One checked, pinned open: see readContainedTextFile.
|
|
264
|
+
const content = await readContainedTextFile(absPath, root, maxFileSize)
|
|
265
|
+
if (content === null) return
|
|
252
266
|
const rel = relative(root, absPath).split(sep).join('/')
|
|
253
267
|
for (const s of parseSymbols(content, rel)) {
|
|
254
268
|
if (symbols.length >= maxSymbols) { truncated = true; return }
|