@chroxy/server 0.11.0 → 0.11.11
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 +206 -18
- package/README.md +2 -2
- package/hooks/claude-native-route-check.mjs +17 -0
- package/hooks/permission-hook.sh +166 -11
- package/package.json +16 -12
- 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 +958 -0
- package/src/activity-registry.js +110 -5
- package/src/agent-connections.js +304 -0
- package/src/agent-control/client.js +1645 -0
- package/src/agent-control/events.js +551 -0
- package/src/agent-control/local-connection.js +293 -0
- package/src/agent-control/mcp-server.js +547 -0
- package/src/anthropic-compatible-config.js +30 -4
- package/src/anthropic-compatible-session.js +15 -6
- package/src/anthropic-gemini-shim.js +444 -0
- package/src/anthropic-gemini-translate.js +1030 -0
- 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 +1520 -36
- package/src/bearer-recheck.js +49 -0
- package/src/billing-budget.js +19 -0
- package/src/billing-class.js +40 -7
- package/src/binary-provenance-trust.js +11 -5
- package/src/bound-client-policy.js +291 -0
- package/src/built-in-tools/bash-exec.js +46 -7
- package/src/built-in-tools/file-ops.js +69 -5
- 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 +92 -7
- package/src/byok-mcp-config.js +633 -122
- package/src/byok-mcp-fleet.js +49 -7
- package/src/byok-mcp-oauth-store.js +18 -16
- package/src/byok-mcp-trust.js +37 -23
- package/src/byok-session.js +707 -179
- package/src/byok-tool-executor.js +2742 -26
- package/src/byok-tools.js +9 -2
- package/src/channels/chroxy-channel-server.js +2 -3
- package/src/checkpoint-manager.js +64 -46
- 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-setting-sources.js +74 -0
- package/src/claude-stream-parser.js +53 -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 +215 -88
- 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 +3563 -284
- package/src/claude-tui-tool-response.js +300 -0
- package/src/cli/agent-cmd.js +236 -0
- package/src/cli/agent-control-cmd.js +65 -0
- package/src/cli/config-cmd.js +4 -4
- package/src/cli/config-dir-cmd.js +234 -0
- package/src/cli/connection-state.js +54 -0
- package/src/cli/deploy-cmd.js +45 -10
- package/src/cli/doctor-cmd.js +7 -3
- package/src/cli/freshness-cmd.js +53 -0
- package/src/cli/init-cmd.js +15 -16
- package/src/cli/pages-cmd.js +6 -4
- package/src/cli/pair-code-cmd.js +7 -6
- package/src/cli/pair-discord-cmd.js +7 -6
- package/src/cli/providers-cmd.js +3 -3
- package/src/cli/schedule-cmd.js +91 -40
- package/src/cli/server-cmd.js +54 -1
- package/src/cli/service-cmd.js +33 -10
- package/src/cli/session-cmd.js +227 -74
- package/src/cli/shared.js +162 -11
- package/src/cli/shell-cmd.js +7 -4
- package/src/cli/status-cmd.js +19 -5
- package/src/cli/tokens-cmd.js +4 -5
- package/src/cli/tunnel-cmd.js +255 -24
- package/src/cli/worktree-gc-cmd.js +2 -2
- package/src/cli-session.js +1250 -126
- package/src/cli.js +8 -0
- package/src/codex-app-server-client.js +36 -3
- package/src/codex-app-server-session.js +1517 -81
- package/src/codex-bundled-client.js +66 -0
- package/src/codex-error-text.js +114 -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 +450 -27
- package/src/config-dir-migration.js +449 -0
- package/src/config-dir.js +108 -0
- package/src/config.js +306 -26
- package/src/connection-authority.js +48 -0
- package/src/connection-info.js +78 -23
- 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 +227 -0
- package/src/control-room/host-prune.js +5 -0
- package/src/control-room/integrations.js +7 -20
- package/src/control-room/skills-inventory.js +2 -2
- package/src/conversation-scanner.js +42 -39
- package/src/conversation-scope.js +59 -39
- package/src/conversation-search.js +28 -39
- package/src/credential-store.js +23 -19
- 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 +170 -182
- package/src/device-preferences.js +2 -2
- 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 +172 -3
- package/src/docker-session.js +294 -11
- package/src/doctor.js +781 -64
- package/src/durable-write.js +35 -0
- package/src/edited-input.js +264 -0
- package/src/environment-manager.js +175 -36
- package/src/environments/authority.js +101 -0
- package/src/environments/backends/container-claude-spawn.js +94 -0
- package/src/environments/backends/docker.js +31 -10
- package/src/environments/backends/k8s.js +49 -24
- package/src/environments/destroy-with-sessions.js +142 -0
- package/src/event-ingest.js +118 -13
- package/src/event-normalizer.js +186 -235
- package/src/folder-trust-wire.js +137 -0
- package/src/folder-trust-worker.js +17 -0
- package/src/folder-trust.js +1572 -0
- package/src/freshness/activity-meter.js +101 -0
- package/src/freshness/adapter.js +199 -0
- package/src/freshness/checks.js +239 -0
- package/src/freshness/config.js +98 -0
- package/src/freshness/core.js +185 -0
- package/src/freshness/derive.js +680 -0
- package/src/freshness/exchange.js +305 -0
- package/src/freshness/file-ledger.js +400 -0
- package/src/freshness/grade.js +81 -0
- package/src/freshness/hash.js +45 -0
- package/src/freshness/inbox.js +163 -0
- package/src/freshness/index.js +20 -0
- package/src/freshness/investigation.js +474 -0
- package/src/freshness/keys.js +177 -0
- package/src/freshness/ledger.js +122 -0
- package/src/freshness/outbox.js +131 -0
- package/src/freshness/policy.js +599 -0
- package/src/freshness/queue.js +843 -0
- package/src/freshness/read-errors.js +23 -0
- package/src/freshness/render.js +153 -0
- package/src/freshness/runtime.js +113 -0
- package/src/freshness/session-registry-adapter.js +161 -0
- package/src/freshness/state-file-adapter.js +167 -0
- package/src/freshness-runner/build-info.js +139 -0
- package/src/freshness-runner/cli.js +105 -0
- package/src/freshness-runner/run-tick.js +109 -0
- package/src/freshness-runner/stamp.js +57 -0
- package/src/freshness-sources/claude-transcript-adapter.js +211 -0
- package/src/freshness-sources/codex-transcript-adapter.js +33 -0
- package/src/freshness-sources/index.js +8 -0
- package/src/gemini-byok-session.js +292 -0
- package/src/gemini-credentials.js +67 -0
- package/src/gemini-key-safety.js +246 -0
- package/src/gemini-models.js +386 -0
- package/src/gemini-session.js +81 -5
- package/src/handler-utils.js +540 -80
- package/src/handlers/checkpoint-handlers.js +47 -4
- package/src/handlers/control-room-handlers.js +51 -11
- package/src/handlers/conversation-handlers.js +469 -56
- 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 +57 -13
- package/src/handlers/folder-trust-handlers.js +90 -0
- package/src/handlers/input-handlers.js +714 -48
- package/src/handlers/orchestration-handlers.js +3 -3
- package/src/handlers/principal-admin-handlers.js +229 -0
- package/src/handlers/principal-handlers.js +262 -0
- package/src/handlers/scheduler-handlers.js +92 -18
- package/src/handlers/session-handlers.js +551 -20
- 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 +372 -50
- package/src/handlers/skills-handlers.js +20 -4
- package/src/handlers/summarize-handlers.js +32 -1
- package/src/handlers/survey-throttle.js +380 -0
- package/src/health-proof.js +40 -0
- package/src/history-page.js +112 -0
- package/src/http-routes.js +127 -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 +378 -91
- package/src/jsonl-subprocess-session.js +96 -9
- package/src/keychain.js +1 -1
- package/src/logger.js +166 -30
- package/src/mailbox-route.js +113 -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 +27 -4
- 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 +64 -23
- 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 +9 -2
- package/src/orchestration/git-ops.js +41 -7
- package/src/orchestration/orchestration-manager.js +112 -36
- package/src/orchestration/permission-gate.js +17 -2
- package/src/orchestration/run-model.js +2 -1
- package/src/orchestration/run-record.js +11 -0
- package/src/orchestration/turn-driver.js +185 -43
- package/src/orphan-reaper.js +470 -0
- package/src/outgoing-policy.js +189 -0
- package/src/pairing.js +92 -13
- package/src/path-hash-trust-ledger.js +642 -25
- package/src/permission-deadlines.js +82 -0
- package/src/permission-floor.js +1410 -43
- package/src/permission-hook.js +180 -69
- package/src/permission-manager.js +737 -89
- package/src/permission-mode-support.js +35 -0
- package/src/permission-resolved-by.js +89 -0
- package/src/permission-resolver.js +126 -8
- package/src/permission-scope.js +43 -0
- package/src/platform.js +315 -47
- package/src/preview-ingress.js +54 -0
- package/src/preview-target.js +213 -0
- package/src/principal-audit.js +189 -0
- package/src/principal-binding.js +25 -0
- package/src/principal-brakes.js +21 -0
- package/src/principal-effect.js +101 -0
- package/src/principal-journal.js +905 -0
- package/src/principal-kill-switch.js +183 -0
- package/src/principal-label.js +5 -0
- package/src/principal-pending-permissions.js +177 -0
- package/src/principal-policy.js +1094 -0
- package/src/principal-sessions-snapshot.js +208 -0
- package/src/principal-store.js +488 -0
- package/src/principal-subscriptions.js +283 -0
- package/src/prompt-evaluator.js +34 -4
- package/src/provider-customization.js +180 -0
- package/src/providers.js +209 -4
- package/src/push.js +30 -4
- package/src/question-route-map.js +130 -0
- package/src/redaction.js +531 -20
- package/src/roster-broadcast.js +186 -0
- package/src/scheduled-task-store.js +330 -26
- package/src/scheduler.js +368 -11
- package/src/sdk-session.js +2114 -188
- package/src/server-cli/preview-shutdown.js +22 -0
- package/src/server-cli/push-notification-handler.js +17 -3
- package/src/server-cli/server-orchestrator.js +28 -5
- package/src/server-cli-child.js +33 -18
- package/src/server-cli.js +553 -38
- package/src/server-identity.js +15 -11
- package/src/service.js +396 -25
- 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 +1099 -0
- package/src/session-context.js +7 -2
- package/src/session-manager.js +4062 -312
- package/src/session-message-history.js +841 -16
- package/src/session-name-allocator.js +685 -0
- 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-token-store.js +17 -8
- 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 +2 -3
- package/src/snapshots-store.js +2 -3
- package/src/statusline.js +100 -29
- package/src/summarize-session.js +53 -4
- package/src/supervisor.js +22 -11
- 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/tool-result.js +61 -0
- package/src/transcript-sources.js +109 -0
- package/src/transcript-tasks.js +372 -25
- package/src/trusted-file-read.js +302 -0
- package/src/tunnel/base.js +0 -8
- package/src/tunnel/cloudflare.js +34 -31
- package/src/tunnel/index.js +9 -0
- package/src/tunnel/preview.js +64 -0
- package/src/turn-outcome.js +140 -0
- package/src/usage-normalize.js +9 -5
- package/src/user-shell-session.js +59 -5
- package/src/utils/agent-sdk-version.js +107 -0
- package/src/utils/argv-safety.js +770 -0
- package/src/utils/auth-cause.js +60 -0
- package/src/utils/binary-package-manifest.js +639 -0
- package/src/utils/binary-version.js +224 -0
- package/src/utils/bounded-regex-worker.js +29 -0
- package/src/utils/bounded-regex.js +162 -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 +133 -37
- 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/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/pid-liveness.js +47 -0
- package/src/utils/preflight.js +360 -16
- 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 +189 -4
- package/src/utils/stale-session-dirs.js +182 -0
- package/src/utils/stat-identity.js +43 -0
- package/src/utils/verify-provenance.js +406 -13
- package/src/web-task-manager.js +297 -16
- package/src/worktree-gc.js +202 -6
- package/src/ws-auth.js +163 -31
- package/src/ws-broadcaster.js +49 -5
- package/src/ws-client-manager.js +24 -1
- package/src/ws-client-sender.js +7 -0
- package/src/ws-file-ops/browser.js +363 -58
- package/src/ws-file-ops/common.js +320 -14
- package/src/ws-file-ops/git.js +395 -42
- package/src/ws-file-ops/index.js +2 -0
- package/src/ws-file-ops/memory.js +137 -35
- package/src/ws-file-ops/open-nofollow.js +354 -0
- package/src/ws-file-ops/reader.js +571 -113
- package/src/ws-forwarding.js +349 -39
- package/src/ws-handler-context.js +88 -2
- package/src/ws-history.js +1010 -175
- package/src/ws-message-handlers.js +25 -1
- package/src/ws-permissions.js +307 -37
- package/src/ws-schemas.js +5 -0
- package/src/ws-server.js +885 -98
- package/sidecar/node_modules/.package-lock.json +0 -29
- package/sidecar/node_modules/ws/LICENSE +0 -20
- package/sidecar/node_modules/ws/README.md +0 -548
- package/sidecar/node_modules/ws/browser.js +0 -8
- package/sidecar/node_modules/ws/index.js +0 -22
- package/sidecar/node_modules/ws/lib/buffer-util.js +0 -131
- package/sidecar/node_modules/ws/lib/constants.js +0 -19
- package/sidecar/node_modules/ws/lib/event-target.js +0 -292
- package/sidecar/node_modules/ws/lib/extension.js +0 -203
- package/sidecar/node_modules/ws/lib/limiter.js +0 -55
- package/sidecar/node_modules/ws/lib/permessage-deflate.js +0 -528
- package/sidecar/node_modules/ws/lib/receiver.js +0 -706
- package/sidecar/node_modules/ws/lib/sender.js +0 -602
- package/sidecar/node_modules/ws/lib/stream.js +0 -161
- package/sidecar/node_modules/ws/lib/subprotocol.js +0 -62
- package/sidecar/node_modules/ws/lib/validation.js +0 -152
- package/sidecar/node_modules/ws/lib/websocket-server.js +0 -554
- package/sidecar/node_modules/ws/lib/websocket.js +0 -1393
- package/sidecar/node_modules/ws/package.json +0 -70
- package/sidecar/node_modules/ws/wrapper.mjs +0 -21
- 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
- package/src/dashboard-next/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +0 -1
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Bounded admission for expensive reads.
|
|
3
|
+
*
|
|
4
|
+
* A transcript read can allocate tens of megabytes, and the WebSocket server
|
|
5
|
+
* dispatches messages concurrently, so a connection that sends many requests
|
|
6
|
+
* at once used to get that many simultaneous buffers. This limiter puts one
|
|
7
|
+
* policy in front of such a read:
|
|
8
|
+
*
|
|
9
|
+
* - a daemon-wide cap on reads running at once (`maxConcurrent`);
|
|
10
|
+
* - a per-client cap on distinct reads outstanding, running or queued
|
|
11
|
+
* (`maxPerClient`);
|
|
12
|
+
* - a bound on the number of queued reads (`maxQueued`) — past it, a request
|
|
13
|
+
* is refused immediately instead of waiting;
|
|
14
|
+
* - coalescing: requests carrying the same `key` while one is outstanding
|
|
15
|
+
* share its single read and its result;
|
|
16
|
+
* - cancellation: a request whose `signal` aborts stops waiting, and a read
|
|
17
|
+
* nobody is waiting for any more is dropped from the queue, or told to stop
|
|
18
|
+
* through the `signal` handed to `run` if it already started.
|
|
19
|
+
*
|
|
20
|
+
* The result of a coalesced read is shared between callers and must be treated
|
|
21
|
+
* as read-only.
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
export class ReadLimitError extends Error {
|
|
25
|
+
/** @param {'client'|'queue'} scope */
|
|
26
|
+
constructor(scope, message) {
|
|
27
|
+
super(message)
|
|
28
|
+
this.name = 'ReadLimitError'
|
|
29
|
+
this.code = 'READ_LIMIT'
|
|
30
|
+
this.scope = scope
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export class ReadCancelledError extends Error {
|
|
35
|
+
constructor() {
|
|
36
|
+
super('Read cancelled')
|
|
37
|
+
this.name = 'ReadCancelledError'
|
|
38
|
+
this.code = 'READ_CANCELLED'
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* @param {{ maxConcurrent?: number, maxPerClient?: number, maxQueued?: number }} [opts]
|
|
44
|
+
*/
|
|
45
|
+
export function createReadLimiter({ maxConcurrent = 4, maxPerClient = 2, maxQueued = 32, maxWaitersPerJob = 64 } = {}) {
|
|
46
|
+
// Capacity kept for callers that are not `restricted` (a session-scoped
|
|
47
|
+
// connection is): one running slot, and the tail of the queue.
|
|
48
|
+
const reservedRunning = maxConcurrent > 1 ? 1 : 0
|
|
49
|
+
const restrictedQueueCap = maxQueued > 8 ? maxQueued - 8 : Math.max(1, Math.ceil(maxQueued / 2))
|
|
50
|
+
for (const [name, v] of Object.entries({ maxConcurrent, maxPerClient, maxQueued, maxWaitersPerJob })) {
|
|
51
|
+
if (!Number.isInteger(v) || v < 1) throw new RangeError(`createReadLimiter: ${name} must be a positive integer`)
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** @type {Map<string, Job>} key -> outstanding job (queued or running) */
|
|
55
|
+
const jobs = new Map()
|
|
56
|
+
/** @type {Job[]} */
|
|
57
|
+
const queue = []
|
|
58
|
+
let running = 0
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* @typedef {object} Job
|
|
62
|
+
* @property {string} key
|
|
63
|
+
* @property {(signal: AbortSignal) => Promise<any>} run
|
|
64
|
+
* @property {Map<string, number>} clients client key -> its waiters on this job
|
|
65
|
+
* @property {number} waiters callers still waiting
|
|
66
|
+
* @property {AbortController} abort
|
|
67
|
+
* @property {Promise<any>} promise
|
|
68
|
+
* @property {boolean} started
|
|
69
|
+
* @property {boolean} done the read has finished (or failed)
|
|
70
|
+
*/
|
|
71
|
+
|
|
72
|
+
function outstandingFor(clientKey) {
|
|
73
|
+
let n = 0
|
|
74
|
+
for (const job of jobs.values()) if (job.clients.has(clientKey)) n++
|
|
75
|
+
return n
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function pump() {
|
|
79
|
+
while (running < maxConcurrent && queue.length > 0) {
|
|
80
|
+
// The first queued job allowed to start now: a restricted one may not take
|
|
81
|
+
// the last running slot.
|
|
82
|
+
const at = queue.findIndex((j) => !j.restricted || running < maxConcurrent - reservedRunning)
|
|
83
|
+
if (at < 0) return
|
|
84
|
+
const [job] = queue.splice(at, 1)
|
|
85
|
+
if (job.waiters === 0) continue // everyone left while it queued
|
|
86
|
+
running++
|
|
87
|
+
job.started = true
|
|
88
|
+
job.start()
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* @template T
|
|
94
|
+
* @param {{ key: string, clientKey: string, signal?: AbortSignal }} req
|
|
95
|
+
* @param {(signal: AbortSignal) => Promise<T>} run
|
|
96
|
+
* @returns {Promise<T>}
|
|
97
|
+
*/
|
|
98
|
+
function submit({ key, clientKey, signal, restricted = false }, run) {
|
|
99
|
+
if (signal?.aborted) return Promise.reject(new ReadCancelledError())
|
|
100
|
+
|
|
101
|
+
let job = jobs.get(key)
|
|
102
|
+
const joining = job !== undefined
|
|
103
|
+
if (!joining || !job.clients.has(clientKey)) {
|
|
104
|
+
if (outstandingFor(clientKey) >= maxPerClient) {
|
|
105
|
+
return Promise.reject(new ReadLimitError('client', 'Too many transcript requests from this connection are in progress'))
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
if (!joining) {
|
|
109
|
+
if (running >= maxConcurrent && queue.length >= maxQueued) {
|
|
110
|
+
return Promise.reject(new ReadLimitError('queue', 'Too many transcript requests are in progress'))
|
|
111
|
+
}
|
|
112
|
+
if (restricted && queue.length >= restrictedQueueCap) {
|
|
113
|
+
return Promise.reject(new ReadLimitError('queue', 'Too many transcript requests are in progress'))
|
|
114
|
+
}
|
|
115
|
+
job = createJob(key, run)
|
|
116
|
+
job.restricted = restricted
|
|
117
|
+
jobs.set(key, job)
|
|
118
|
+
queue.push(job)
|
|
119
|
+
}
|
|
120
|
+
if (job.waiters >= maxWaitersPerJob) {
|
|
121
|
+
return Promise.reject(new ReadLimitError('queue', 'Too many transcript requests are in progress'))
|
|
122
|
+
}
|
|
123
|
+
// An unrestricted caller joining a restricted read lifts the restriction (only
|
|
124
|
+
// once it has been admitted).
|
|
125
|
+
if (!restricted) job.restricted = false
|
|
126
|
+
job.clients.set(clientKey, (job.clients.get(clientKey) || 0) + 1)
|
|
127
|
+
job.waiters++
|
|
128
|
+
const j = job
|
|
129
|
+
pump()
|
|
130
|
+
|
|
131
|
+
return new Promise((resolve, reject) => {
|
|
132
|
+
let settled = false
|
|
133
|
+
const detach = () => {
|
|
134
|
+
if (settled) return
|
|
135
|
+
settled = true
|
|
136
|
+
signal?.removeEventListener('abort', onAbort)
|
|
137
|
+
j.waiters--
|
|
138
|
+
// This caller no longer counts against its client's outstanding reads.
|
|
139
|
+
const left = (j.clients.get(clientKey) || 1) - 1
|
|
140
|
+
if (left > 0) j.clients.set(clientKey, left)
|
|
141
|
+
else j.clients.delete(clientKey)
|
|
142
|
+
if (j.waiters === 0) {
|
|
143
|
+
// Nobody is waiting: a queued read never starts, a running one is told to stop.
|
|
144
|
+
if (!j.started) {
|
|
145
|
+
const i = queue.indexOf(j)
|
|
146
|
+
if (i >= 0) queue.splice(i, 1)
|
|
147
|
+
jobs.delete(j.key)
|
|
148
|
+
} else if (!j.done) {
|
|
149
|
+
// Forget it now so a fresh request for the same key starts its own
|
|
150
|
+
// read rather than joining one that is being stopped.
|
|
151
|
+
if (jobs.get(j.key) === j) jobs.delete(j.key)
|
|
152
|
+
j.abort.abort()
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
const onAbort = () => {
|
|
157
|
+
const wasSettled = settled
|
|
158
|
+
detach()
|
|
159
|
+
if (!wasSettled) reject(new ReadCancelledError())
|
|
160
|
+
}
|
|
161
|
+
signal?.addEventListener('abort', onAbort, { once: true })
|
|
162
|
+
j.promise.then(
|
|
163
|
+
(v) => { if (!settled) { detach(); resolve(v) } },
|
|
164
|
+
(e) => { if (!settled) { detach(); reject(e) } },
|
|
165
|
+
)
|
|
166
|
+
})
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
function createJob(key, run) {
|
|
170
|
+
const abort = new AbortController()
|
|
171
|
+
/** @type {Job} */
|
|
172
|
+
const job = { key, run, clients: new Map(), waiters: 0, abort, started: false, done: false, restricted: false, promise: null, start: null }
|
|
173
|
+
job.promise = new Promise((resolve, reject) => {
|
|
174
|
+
job.start = () => {
|
|
175
|
+
Promise.resolve()
|
|
176
|
+
.then(() => run(abort.signal))
|
|
177
|
+
.then(
|
|
178
|
+
(v) => { job.done = true; resolve(v) },
|
|
179
|
+
(e) => { job.done = true; reject(e) },
|
|
180
|
+
)
|
|
181
|
+
.finally(() => {
|
|
182
|
+
running--
|
|
183
|
+
// A later request for the same key must read afresh.
|
|
184
|
+
if (jobs.get(key) === job) jobs.delete(key)
|
|
185
|
+
pump()
|
|
186
|
+
})
|
|
187
|
+
}
|
|
188
|
+
})
|
|
189
|
+
// A job nobody is waiting on any more can still reject (cancelled read);
|
|
190
|
+
// keep that from surfacing as an unhandled rejection.
|
|
191
|
+
job.promise.catch(() => {})
|
|
192
|
+
return job
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
return {
|
|
196
|
+
submit,
|
|
197
|
+
/** For tests and diagnostics. */
|
|
198
|
+
stats: () => ({ running, queued: queue.length, outstanding: jobs.size }),
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/**
|
|
203
|
+
* The key a connection's reads are counted under, and whether it is restricted.
|
|
204
|
+
* A session-scoped connection is counted by its CREDENTIAL (the pairing token it
|
|
205
|
+
* authenticated with), so one token cannot widen its share by opening more
|
|
206
|
+
* connections; an unscoped connection is counted by connection. Scoped callers
|
|
207
|
+
* are `restricted`: they cannot take the capacity reserved for the others.
|
|
208
|
+
* @param {{ id?: string, authToken?: string, boundSessionId?: unknown }} client
|
|
209
|
+
* @param {(c: object) => boolean} isScoped
|
|
210
|
+
*/
|
|
211
|
+
export function admissionFor(client, isScoped) {
|
|
212
|
+
const scoped = isScoped(client)
|
|
213
|
+
const key = scoped && typeof client?.authToken === 'string' && client.authToken
|
|
214
|
+
? `credential:${client.authToken}`
|
|
215
|
+
: String(client?.id ?? '')
|
|
216
|
+
return { clientKey: key, restricted: scoped }
|
|
217
|
+
}
|
|
@@ -0,0 +1,375 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Open a path for reading only if it turns out to be a regular file.
|
|
3
|
+
*
|
|
4
|
+
* A directory listing and a later open are two steps, and the name can be
|
|
5
|
+
* replaced in between — with a FIFO, say, whose blocking open would hold a
|
|
6
|
+
* libuv threadpool thread until a writer appears. So the open here never
|
|
7
|
+
* blocks (O_NONBLOCK), and the check is made on the DESCRIPTOR that was opened
|
|
8
|
+
* (fstat), not on a separate stat of the path that may no longer name the same
|
|
9
|
+
* object. A symlink to a regular file is followed, as a plain open does.
|
|
10
|
+
*/
|
|
11
|
+
import { constants as fsConstants, openSync, fstatSync, readSync, closeSync, lstatSync, readlinkSync, existsSync } from 'fs'
|
|
12
|
+
import { relative, join, sep, isAbsolute, parse } from 'path'
|
|
13
|
+
import { open, lstat } from 'fs/promises'
|
|
14
|
+
import { openNoFollow } from '../ws-file-ops/open-nofollow.js'
|
|
15
|
+
|
|
16
|
+
const READ_FLAGS = fsConstants.O_RDONLY | (fsConstants.O_NONBLOCK || 0)
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* @param {string} filePath
|
|
20
|
+
* @returns {Promise<{ handle: import('fs/promises').FileHandle, size: number }>}
|
|
21
|
+
* the caller closes `handle`
|
|
22
|
+
* @throws {Error} with code 'ENOTREG' when the opened object is not a regular file
|
|
23
|
+
*/
|
|
24
|
+
export async function openRegularFile(filePath) {
|
|
25
|
+
const handle = await open(filePath, READ_FLAGS)
|
|
26
|
+
try {
|
|
27
|
+
const st = await handle.stat()
|
|
28
|
+
if (!st.isFile()) {
|
|
29
|
+
const err = new Error('Not a regular file')
|
|
30
|
+
err.code = 'ENOTREG'
|
|
31
|
+
throw err
|
|
32
|
+
}
|
|
33
|
+
return { handle, size: st.size }
|
|
34
|
+
} catch (err) {
|
|
35
|
+
await handle.close().catch(() => {})
|
|
36
|
+
throw err
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Refuse a handle that is not a regular file, BEFORE any byte is written.
|
|
42
|
+
*
|
|
43
|
+
* `openNoFollow` opens with O_NONBLOCK, so a FIFO with a reader attached (or a
|
|
44
|
+
* device) opens successfully; writing to it would put the payload into the pipe
|
|
45
|
+
* and report success for something that is not a file. The check is made on the
|
|
46
|
+
* opened handle (fstat), never on a separate stat of the path (#7957).
|
|
47
|
+
*
|
|
48
|
+
* @param {import('fs/promises').FileHandle} handle
|
|
49
|
+
* @throws {Error} with code 'ENOTREG' when the opened object is not a regular file
|
|
50
|
+
*/
|
|
51
|
+
export async function assertRegularHandle(handle) {
|
|
52
|
+
const st = await handle.stat()
|
|
53
|
+
if (!st.isFile()) {
|
|
54
|
+
const err = new Error('Not a regular file')
|
|
55
|
+
err.code = 'ENOTREG'
|
|
56
|
+
throw err
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Read at most `maxBytes` from the start of a regular file as UTF-8.
|
|
62
|
+
* @param {string} filePath
|
|
63
|
+
* @param {number} maxBytes
|
|
64
|
+
* @returns {Promise<{ text: string, size: number }>}
|
|
65
|
+
*/
|
|
66
|
+
export async function readRegularFileHead(filePath, maxBytes) {
|
|
67
|
+
const { handle, size } = await openRegularFile(filePath)
|
|
68
|
+
try {
|
|
69
|
+
const length = Math.min(size, maxBytes)
|
|
70
|
+
const buf = Buffer.alloc(length)
|
|
71
|
+
let off = 0
|
|
72
|
+
while (off < length) {
|
|
73
|
+
const { bytesRead } = await handle.read(buf, off, length - off, off)
|
|
74
|
+
if (bytesRead === 0) break
|
|
75
|
+
off += bytesRead
|
|
76
|
+
}
|
|
77
|
+
return { text: new TextDecoder('utf-8', { fatal: false }).decode(buf.subarray(0, off)), size }
|
|
78
|
+
} finally {
|
|
79
|
+
await handle.close()
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Synchronous variant for a caller that cannot be async: open without blocking,
|
|
85
|
+
* check the opened descriptor is a regular file no larger than `maxBytes`, and
|
|
86
|
+
* read it whole from that descriptor. A FIFO or device is refused (ENOTREG), not
|
|
87
|
+
* waited on; an oversize file is refused (EFBIG) with its size on the error.
|
|
88
|
+
* @param {string} filePath
|
|
89
|
+
* @param {number} maxBytes
|
|
90
|
+
* @returns {Buffer}
|
|
91
|
+
*/
|
|
92
|
+
export function readRegularFileSync(filePath, maxBytes) {
|
|
93
|
+
const fd = openSync(filePath, READ_FLAGS)
|
|
94
|
+
try {
|
|
95
|
+
const st = fstatSync(fd)
|
|
96
|
+
if (!st.isFile()) {
|
|
97
|
+
const err = new Error('Not a regular file')
|
|
98
|
+
err.code = 'ENOTREG'
|
|
99
|
+
throw err
|
|
100
|
+
}
|
|
101
|
+
if (st.size > maxBytes) {
|
|
102
|
+
const err = new Error('File too large')
|
|
103
|
+
err.code = 'EFBIG'
|
|
104
|
+
err.size = st.size
|
|
105
|
+
throw err
|
|
106
|
+
}
|
|
107
|
+
const buf = Buffer.alloc(st.size)
|
|
108
|
+
let off = 0
|
|
109
|
+
while (off < buf.length) {
|
|
110
|
+
const n = readSync(fd, buf, off, buf.length - off, off)
|
|
111
|
+
if (n === 0) break
|
|
112
|
+
off += n
|
|
113
|
+
}
|
|
114
|
+
return buf.subarray(0, off)
|
|
115
|
+
} finally {
|
|
116
|
+
closeSync(fd)
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* The directory components between `root` and `absPath`, or null when `absPath`
|
|
122
|
+
* is not lexically beneath `root`.
|
|
123
|
+
*/
|
|
124
|
+
function componentsBelow(root, absPath) {
|
|
125
|
+
const rel = relative(root, absPath)
|
|
126
|
+
if (!rel || rel === '..' || rel.startsWith('..' + sep) || isAbsolute(rel)) return null
|
|
127
|
+
return rel.split(sep)
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* Every directory that must be a real directory (not a link) for `absPath` to be
|
|
132
|
+
* the file it appears to be: the filesystem root, each ancestor of `root`, `root`
|
|
133
|
+
* itself, and each directory between `root` and the file. The chain starts at the
|
|
134
|
+
* top, not at `root`: a swap of the root or of one of its ancestors changes what
|
|
135
|
+
* every name beneath it denotes.
|
|
136
|
+
*/
|
|
137
|
+
function directoryChain(root, comps) {
|
|
138
|
+
const dirs = []
|
|
139
|
+
const { root: top } = parse(root)
|
|
140
|
+
let cur = top
|
|
141
|
+
dirs.push(cur)
|
|
142
|
+
for (const part of root.slice(top.length).split(sep).filter(Boolean)) {
|
|
143
|
+
cur = join(cur, part)
|
|
144
|
+
dirs.push(cur)
|
|
145
|
+
}
|
|
146
|
+
for (const comp of comps.slice(0, -1)) {
|
|
147
|
+
cur = join(cur, comp)
|
|
148
|
+
dirs.push(cur)
|
|
149
|
+
}
|
|
150
|
+
return dirs
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* Where the kernel exposes the path an open descriptor was resolved to
|
|
155
|
+
* (`/proc/self/fd/<fd>`, Linux), that is an EXACT answer to "is this descriptor
|
|
156
|
+
* the file at the expected real path": it needs no second resolution of the name.
|
|
157
|
+
* Elsewhere (macOS, Windows) there is no such primitive in plain Node.
|
|
158
|
+
*/
|
|
159
|
+
const PROC_FD_AVAILABLE = process.platform === 'linux' && existsSync('/proc/self/fd')
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* Does the descriptor's resolved path equal `target`? Always true where the
|
|
163
|
+
* platform offers no way to ask; fails closed if it offers one and it errors.
|
|
164
|
+
* `deps.procFd` is a test seam: `{ available, readlink(fd) }`.
|
|
165
|
+
*/
|
|
166
|
+
function procPathMatches(fd, target, deps) {
|
|
167
|
+
const seam = deps.procFd
|
|
168
|
+
const available = seam ? seam.available : PROC_FD_AVAILABLE
|
|
169
|
+
if (!available) return true
|
|
170
|
+
try {
|
|
171
|
+
return (seam ? seam.readlink(fd) : readlinkSync(`/proc/self/fd/${fd}`)) === target
|
|
172
|
+
} catch {
|
|
173
|
+
return false
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/**
|
|
178
|
+
* The pinning checks, shared by every contained reader. They run on the opened
|
|
179
|
+
* descriptor's `st` (from fstat):
|
|
180
|
+
* 1. every directory from the filesystem root through `root` to the file's
|
|
181
|
+
* parent is a real directory, and the file's own lstat is a regular file with
|
|
182
|
+
* the descriptor's device and inode;
|
|
183
|
+
* 2. the same, a SECOND time (so a link swapped in and out of a directory
|
|
184
|
+
* between two looks has to be timed across both passes);
|
|
185
|
+
* 3. where the platform can say which path the descriptor was resolved to
|
|
186
|
+
* (Linux /proc), that path equals `target`.
|
|
187
|
+
* On Linux this is exact. On macOS and Windows it is NOT: a directory swapped
|
|
188
|
+
* between a link and a real directory fast enough to be a link when the file is
|
|
189
|
+
* opened and real at each of the checks is narrowed (the two passes and the
|
|
190
|
+
* identity compare must all be beaten) but not ruled out. It also needs local
|
|
191
|
+
* write access to the store's own directories.
|
|
192
|
+
* `deps.betweenChecks` is a test seam that runs between the two passes.
|
|
193
|
+
*/
|
|
194
|
+
async function verifyPinned(fh, target, rootReal, comps, st, deps) {
|
|
195
|
+
const pass = async () => {
|
|
196
|
+
for (const dir of directoryChain(rootReal, comps)) {
|
|
197
|
+
if (!(await lstat(dir)).isDirectory()) return false
|
|
198
|
+
}
|
|
199
|
+
const fin = await lstat(target, { bigint: true })
|
|
200
|
+
return fin.isFile() && fin.dev === st.dev && fin.ino === st.ino
|
|
201
|
+
}
|
|
202
|
+
if (!(await pass())) return false
|
|
203
|
+
await deps.betweenChecks?.()
|
|
204
|
+
if (!(await pass())) return false
|
|
205
|
+
return procPathMatches(fh.fd, target, deps)
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
function verifyPinnedSync(fd, target, rootReal, comps, st, deps) {
|
|
209
|
+
const pass = () => {
|
|
210
|
+
for (const dir of directoryChain(rootReal, comps)) {
|
|
211
|
+
if (!lstatSync(dir).isDirectory()) return false
|
|
212
|
+
}
|
|
213
|
+
const fin = lstatSync(target, { bigint: true })
|
|
214
|
+
return fin.isFile() && fin.dev === st.dev && fin.ino === st.ino
|
|
215
|
+
}
|
|
216
|
+
if (!pass()) return false
|
|
217
|
+
deps.betweenChecks?.()
|
|
218
|
+
if (!pass()) return false
|
|
219
|
+
return procPathMatches(fd, target, deps)
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/**
|
|
223
|
+
* Read at most `size` bytes from an open handle in bounded steps, never more
|
|
224
|
+
* than `maxBytes`.
|
|
225
|
+
*/
|
|
226
|
+
async function readHandleBounded(fh, size, maxBytes) {
|
|
227
|
+
const length = Math.min(size, maxBytes)
|
|
228
|
+
const buf = Buffer.alloc(length)
|
|
229
|
+
let off = 0
|
|
230
|
+
while (off < length) {
|
|
231
|
+
const { bytesRead } = await fh.read(buf, off, Math.min(length - off, 1024 * 1024), off)
|
|
232
|
+
if (bytesRead === 0) break
|
|
233
|
+
off += bytesRead
|
|
234
|
+
}
|
|
235
|
+
return buf.subarray(0, off)
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/**
|
|
239
|
+
* Read a file for a walk or lookup that must stay inside `root`, and consume the
|
|
240
|
+
* very object that was checked.
|
|
241
|
+
*
|
|
242
|
+
* `root` MUST ALREADY BE A REAL PATH (the caller resolved it, e.g. with
|
|
243
|
+
* `realpath`/`realpathSync.native`): a root that is a link, or that sits under a
|
|
244
|
+
* link, is REFUSED (the call returns null), not followed. `absPath` must lie
|
|
245
|
+
* lexically beneath it. The file is opened ONCE (no-follow on the final component,
|
|
246
|
+
* non-blocking) and the descriptor must be a regular file within the cap. Containment is then
|
|
247
|
+
* established from identities rather than by resolving the name again: see
|
|
248
|
+
* `verifyPinned` for the checks (directory chain from the filesystem root, the
|
|
249
|
+
* file's device and inode, repeated twice, plus the descriptor's own resolved path
|
|
250
|
+
* where the platform reports it). What is read is always the descriptor.
|
|
251
|
+
*
|
|
252
|
+
* WHAT THIS DOES AND DOES NOT GUARANTEE. A root or ancestor that is already a
|
|
253
|
+
* link is refused. A parent swapped to a link and left there, or swapped for the
|
|
254
|
+
* open and restored before the checks, is refused. On Linux, where /proc/self/fd
|
|
255
|
+
* is mounted, the descriptor's resolved path is compared and the answer is exact;
|
|
256
|
+
* where /proc is absent it falls back to the two passes. On macOS and Windows a
|
|
257
|
+
* directory toggled between link and real fast enough to be a link at the open and
|
|
258
|
+
* real at every check is narrowed, not ruled out (measured: see the PR notes and
|
|
259
|
+
* the platform-limits paragraph of docs/security/bearer-token-authority.md);
|
|
260
|
+
* exploiting it needs local write access inside the store. A hard link inside the root to a file elsewhere is the same
|
|
261
|
+
* object and is not distinguishable by identity.
|
|
262
|
+
*
|
|
263
|
+
* `deps` is a test seam: `beforeOpen` / `afterOpen` / `betweenChecks` run at those
|
|
264
|
+
* points so a test can schedule a filesystem change there; `procFd` stands in for
|
|
265
|
+
* /proc.
|
|
266
|
+
*
|
|
267
|
+
* @param {string} absPath lexically beneath `root`
|
|
268
|
+
* @param {string} root the containing root (any spelling; resolved here)
|
|
269
|
+
* @param {number} maxBytes
|
|
270
|
+
* @param {{ head?: boolean, deps?: object }} [opts]
|
|
271
|
+
* `head`: a larger file is read up to `maxBytes` instead of refused
|
|
272
|
+
* @returns {Promise<Buffer|null>} null when the file is not an in-root regular
|
|
273
|
+
* file within the cap, or could not be checked
|
|
274
|
+
*/
|
|
275
|
+
export async function readContainedBytes(absPath, root, maxBytes, { head = false, deps = {} } = {}) {
|
|
276
|
+
const comps = componentsBelow(root, absPath)
|
|
277
|
+
if (!comps) return null
|
|
278
|
+
let fh
|
|
279
|
+
try {
|
|
280
|
+
// The chain below runs over `root` AS GIVEN: a root that is itself a link, or
|
|
281
|
+
// sits under a link, fails the directory check (the root must be a real path).
|
|
282
|
+
const target = join(root, ...comps)
|
|
283
|
+
await deps.beforeOpen?.()
|
|
284
|
+
fh = await openNoFollow(target, READ_FLAGS)
|
|
285
|
+
await deps.afterOpen?.()
|
|
286
|
+
const st = await fh.stat({ bigint: true })
|
|
287
|
+
if (!st.isFile()) return null
|
|
288
|
+
if (!head && st.size > BigInt(maxBytes)) return null
|
|
289
|
+
if (!(await verifyPinned(fh, target, root, comps, st, deps))) return null
|
|
290
|
+
return await readHandleBounded(fh, Number(st.size), maxBytes)
|
|
291
|
+
} catch {
|
|
292
|
+
return null
|
|
293
|
+
} finally {
|
|
294
|
+
if (fh) await fh.close().catch(() => {})
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
/** UTF-8 text form of {@link readContainedBytes}. */
|
|
299
|
+
export async function readContainedTextFile(absPath, root, maxBytes, opts) {
|
|
300
|
+
const buf = await readContainedBytes(absPath, root, maxBytes, opts)
|
|
301
|
+
return buf === null ? null : new TextDecoder('utf-8', { fatal: false }).decode(buf)
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
/**
|
|
305
|
+
* Synchronous {@link readContainedBytes}, for a caller that cannot be async.
|
|
306
|
+
* Same requirement that `root` already be a real path, identity checks, `deps`
|
|
307
|
+
* seam and guarantees (including the macOS/Windows limit); a FIFO or device is refused, not waited on.
|
|
308
|
+
*/
|
|
309
|
+
export function readContainedBytesSync(absPath, root, maxBytes, { head = false, report = {}, deps = {} } = {}) {
|
|
310
|
+
const comps = componentsBelow(root, absPath)
|
|
311
|
+
if (!comps) { report.reason = 'outside'; return null }
|
|
312
|
+
let fd
|
|
313
|
+
try {
|
|
314
|
+
const target = join(root, ...comps)
|
|
315
|
+
deps.beforeOpen?.()
|
|
316
|
+
fd = openSync(target, READ_FLAGS | (fsConstants.O_NOFOLLOW || 0))
|
|
317
|
+
deps.afterOpen?.()
|
|
318
|
+
const st = fstatSync(fd, { bigint: true })
|
|
319
|
+
if (!st.isFile()) { report.reason = 'not-regular'; return null }
|
|
320
|
+
if (!head && st.size > BigInt(maxBytes)) { report.reason = 'too-large'; report.size = Number(st.size); return null }
|
|
321
|
+
if (!verifyPinnedSync(fd, target, root, comps, st, deps)) { report.reason = 'changed'; return null }
|
|
322
|
+
const length = Math.min(Number(st.size), maxBytes)
|
|
323
|
+
const buf = Buffer.alloc(length)
|
|
324
|
+
let off = 0
|
|
325
|
+
while (off < length) {
|
|
326
|
+
const n = readSync(fd, buf, off, length - off, off)
|
|
327
|
+
if (n === 0) break
|
|
328
|
+
off += n
|
|
329
|
+
}
|
|
330
|
+
return buf.subarray(0, off)
|
|
331
|
+
} catch (err) {
|
|
332
|
+
report.reason = err?.code === 'ENOENT' ? 'missing' : err?.code === 'EACCES' ? 'denied' : 'error'
|
|
333
|
+
return null
|
|
334
|
+
} finally {
|
|
335
|
+
if (fd !== undefined) { try { closeSync(fd) } catch { /* ignore */ } }
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
/**
|
|
340
|
+
* For a caller that opened the handle itself: confirm the opened object is the
|
|
341
|
+
* regular file `absPath` names inside `root` (the same `verifyPinned` checks as
|
|
342
|
+
* {@link readContainedBytes}, with the same limits on macOS and Windows) and read
|
|
343
|
+
* it, never more than `maxBytes`. `absPath` must be the real path the handle was
|
|
344
|
+
* opened by; `root` must already be a real path (a linked root is refused).
|
|
345
|
+
* Throws an Error with `code` 'ENOTREG', 'EFBIG' or 'EACCES' (outside/changed).
|
|
346
|
+
* @param {import('fs/promises').FileHandle} fh
|
|
347
|
+
* @param {string} absPath
|
|
348
|
+
* @param {string} root
|
|
349
|
+
* @param {number} maxBytes
|
|
350
|
+
* @param {object} [deps] test seam (see readContainedBytes)
|
|
351
|
+
* @returns {Promise<Buffer>}
|
|
352
|
+
*/
|
|
353
|
+
export async function readPinnedHandle(fh, absPath, root, maxBytes, deps = {}) {
|
|
354
|
+
const fail = (code, message) => Object.assign(new Error(message), { code })
|
|
355
|
+
const st = await fh.stat({ bigint: true })
|
|
356
|
+
if (!st.isFile()) throw fail('ENOTREG', 'Not a regular file')
|
|
357
|
+
if (st.size > BigInt(maxBytes)) throw fail('EFBIG', 'File too large')
|
|
358
|
+
const comps = componentsBelow(root, absPath)
|
|
359
|
+
if (!comps) throw fail('EACCES', 'outside')
|
|
360
|
+
const target = join(root, ...comps)
|
|
361
|
+
if (!(await verifyPinned(fh, target, root, comps, st, deps))) throw fail('EACCES', 'changed')
|
|
362
|
+
return readHandleBounded(fh, Number(st.size), maxBytes)
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
/**
|
|
366
|
+
* Read an already-opened regular file in bounded steps, never more than
|
|
367
|
+
* `maxBytes`; throws ENOTREG / EFBIG like {@link readPinnedHandle} but without
|
|
368
|
+
* the parent-directory check (for a caller with no containing root).
|
|
369
|
+
*/
|
|
370
|
+
export async function readFdBounded(fh, maxBytes) {
|
|
371
|
+
const st = await fh.stat({ bigint: true })
|
|
372
|
+
if (!st.isFile()) throw Object.assign(new Error('Not a regular file'), { code: 'ENOTREG' })
|
|
373
|
+
if (st.size > BigInt(maxBytes)) throw Object.assign(new Error('File too large'), { code: 'EFBIG' })
|
|
374
|
+
return readHandleBounded(fh, Number(st.size), maxBytes)
|
|
375
|
+
}
|