From 879aad7dd64fae9521f678a681df6ba1c761bfa7 Mon Sep 17 00:00:00 2001 From: Neil <4138956+nwparker@users.noreply.github.com> Date: Fri, 24 Jul 2026 21:36:57 -0700 Subject: [PATCH] oom(foundation): bound shared readers/limits + add BoundedMap primitive (#10299) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * oom(01): A1-shared-readers — reintroduce #10179 subset Files: 18 applied, 0 deleted (from 6eb70d83703e5c69c2878caca73d536a2abbadab) Co-authored-by: Orca * oom(02): A2-shared-image-media — reintroduce #10179 subset Files: 7 applied, 0 deleted (from 6eb70d83703e5c69c2878caca73d536a2abbadab) Co-authored-by: Orca * oom(03): A3-shared-fs-listing — reintroduce #10179 subset Files: 21 applied, 0 deleted (from 6eb70d83703e5c69c2878caca73d536a2abbadab) Co-authored-by: Orca * oom(04): A4-shared-remote-relay — reintroduce #10179 subset Files: 8 applied, 0 deleted (from 6eb70d83703e5c69c2878caca73d536a2abbadab) Co-authored-by: Orca * oom(05): A5-shared-misc — reintroduce #10179 subset Files: 28 applied, 0 deleted (from 6eb70d83703e5c69c2878caca73d536a2abbadab) Co-authored-by: Orca * oom(06): B-shared-wiring — reintroduce #10179 subset Files: 81 applied, 0 deleted (from 6eb70d83703e5c69c2878caca73d536a2abbadab) Co-authored-by: Orca --------- Co-authored-by: Orca --- src/main/git/status.test.ts | 28 ++ .../components/editor/ImageViewer.test.tsx | 21 +- .../src/components/editor/ImageViewer.tsx | 4 +- src/shared/agent-detection.test.ts | 14 + src/shared/agent-detection.ts | 3 +- .../agent-hook-endpoint-temp-cleanup.test.ts | 58 +++ .../agent-hook-endpoint-temp-cleanup.ts | 38 ++ ...ent-hook-listener-roster-retention.test.ts | 57 +++ src/shared/agent-hook-listener.ts | 89 ++--- .../agent-hook-request-body-memory.test.ts | 32 ++ src/shared/agent-hook-status-cache.test.ts | 66 ++++ src/shared/agent-hook-status-cache.ts | 69 ++++ src/shared/agent-status-types.test.ts | 12 + src/shared/agent-status-types.ts | 6 + src/shared/automations-types.ts | 2 + src/shared/bounded-map.test.ts | 328 ++++++++++++++++ src/shared/bounded-map.ts | 207 ++++++++++ .../browser-screencast-protocol.test.ts | 37 +- src/shared/browser-screencast-protocol.ts | 17 +- src/shared/commit-message-agent-spec.test.ts | 12 + src/shared/commit-message-agent-spec.ts | 7 + .../ephemeral-vm-recipe-process.test.ts | 27 ++ src/shared/ephemeral-vm-recipe-process.ts | 23 +- src/shared/ephemeral-vm-recipes.test.ts | 19 +- src/shared/ephemeral-vm-recipes.ts | 7 + src/shared/ephemeral-vm-runtime-store.test.ts | 26 +- src/shared/ephemeral-vm-runtime-store.ts | 33 +- .../external-automation-jobs-file.test.ts | 71 ++++ src/shared/external-automation-jobs-file.ts | 58 +++ ...filesystem-directory-listing-limit.test.ts | 59 +++ .../filesystem-directory-listing-limit.ts | 75 ++++ src/shared/git-check-ignore-stdio.ts | 9 +- src/shared/git-config-snapshot-runner.ts | 3 +- src/shared/git-discard-path-safety.ts | 15 +- src/shared/git-history-log-parser.ts | 3 +- src/shared/git-uncommitted-line-stats.test.ts | 9 +- src/shared/git-uncommitted-line-stats.ts | 18 +- src/shared/hermes-run-output-limits.test.ts | 165 ++++++++ src/shared/hermes-run-output-limits.ts | 254 ++++++++++++ src/shared/hermes-run-ref-retention.test.ts | 36 ++ src/shared/hermes-run-ref-retention.ts | 78 ++++ src/shared/image-data-uri.test.ts | 48 ++- src/shared/image-data-uri.ts | 19 + src/shared/in-flight-promise-dedupe.test.ts | 83 +++- src/shared/in-flight-promise-dedupe.ts | 42 +- .../linux-proc-port-scan-limits.test.ts | 52 +++ src/shared/linux-proc-port-scan-limits.ts | 55 +++ .../linux-proc-socket-owner-scanner.test.ts | 59 +++ src/shared/linux-proc-socket-owner-scanner.ts | 64 +++ .../map-settled-with-concurrency.test.ts | 35 ++ .../markdown-document-listing-limits.test.ts | 83 ++++ .../markdown-document-listing-limits.ts | 170 ++++++++ src/shared/mcp-config-inspection-limits.ts | 41 ++ src/shared/mcp-config.test.ts | 99 ++++- src/shared/mcp-config.ts | 153 ++------ src/shared/mcp-server-inspection.ts | 139 +++++++ src/shared/mobile-e2ee-v2-contract.test.ts | 21 +- src/shared/mobile-e2ee-v2-contract.ts | 1 + .../mobile-file-directory-limit.test.ts | 37 ++ src/shared/mobile-file-directory-limit.ts | 43 ++ src/shared/mobile-relay-pairing-offer.ts | 18 +- .../node-bounded-file-reader-sync.test.ts | 38 ++ .../node-markdown-document-discovery.test.ts | 74 ++++ .../node-markdown-document-discovery.ts | 86 ++++ src/shared/orca-yaml-alias-bounds.test.ts | 27 ++ src/shared/orca-yaml-bounds.test.ts | 83 ++++ src/shared/orca-yaml-file-limit.ts | 22 ++ src/shared/orca-yaml.ts | 42 +- src/shared/osc-title-extraction.ts | 13 +- src/shared/pairing.ts | 20 +- src/shared/pr-refresh-memory-limits.ts | 5 + src/shared/pull-request-generation.test.ts | 14 + src/shared/pull-request-generation.ts | 10 +- .../quick-open-directory-reader.test.ts | 56 +++ src/shared/quick-open-directory-reader.ts | 62 +++ .../quick-open-git-entry-classification.ts | 68 ++++ src/shared/quick-open-install-rg.ts | 7 +- src/shared/quick-open-listing-limits.test.ts | 82 ++++ src/shared/quick-open-listing-limits.ts | 142 +++++++ src/shared/quick-open-readdir-budget.ts | 80 +++- src/shared/quick-open-readdir-memory.test.ts | 92 +++++ src/shared/quick-open-readdir-walk.test.ts | 54 +-- src/shared/quick-open-readdir-walk.ts | 180 ++++----- src/shared/relay-json-admission.ts | 12 + src/shared/relay-version-marker.test.ts | 40 ++ src/shared/relay-version-marker.ts | 9 + src/shared/remote-runtime-client.ts | 112 ++++-- .../remote-runtime-outbound-admission.test.ts | 371 ++++++++++++++++++ ...mote-runtime-prepared-request-admission.ts | 123 ++++++ ...e-runtime-request-connection-stale.test.ts | 36 ++ .../remote-runtime-request-connection.ts | 131 ++++--- .../remote-runtime-request-ready-waiters.ts | 29 ++ ...remote-runtime-shared-control-admission.ts | 53 +++ ...-runtime-shared-control-connection.test.ts | 109 +++++ ...emote-runtime-shared-control-connection.ts | 34 +- ...e-shared-control-keepalive-refresh.test.ts | 1 + .../remote-runtime-shared-control-protocol.ts | 32 +- .../remote-runtime-shared-control-ready.ts | 20 +- .../remote-runtime-shared-control-requests.ts | 41 +- .../remote-runtime-shared-control-send.ts | 19 +- ...e-shared-control-socket-generation.test.ts | 2 + .../remote-runtime-shared-control-state.ts | 4 + ...ntime-shared-control-subscription-start.ts | 9 + ...ntime-shared-control-subscriptions.test.ts | 1 + ...te-runtime-shared-control-subscriptions.ts | 2 + .../remote-runtime-shared-control-types.ts | 3 + src/shared/repo-icon.test.ts | 28 +- src/shared/repo-icon.ts | 7 +- src/shared/runtime-bootstrap.ts | 13 + src/shared/runtime-environment-store.test.ts | 31 +- src/shared/runtime-environment-store.ts | 32 +- src/shared/runtime-rpc-call-queue.test.ts | 88 ++++- src/shared/runtime-rpc-call-queue.ts | 59 ++- src/shared/runtime-types.ts | 2 + src/shared/secure-file.test.ts | 90 ++++- src/shared/secure-file.ts | 198 +++------- .../secure-path-hardening-cache.test.ts | 61 +++ src/shared/secure-path-hardening-cache.ts | 74 ++++ src/shared/secure-path-windows-acl.ts | 150 +++++++ src/shared/serve-update-handoff.ts | 12 + .../setup-script-import-codex-environment.ts | 77 +++- .../setup-script-import-command-limits.ts | 49 +++ src/shared/setup-script-import-limits.ts | 34 ++ src/shared/setup-script-imports.test.ts | 117 +++++- src/shared/setup-script-imports.ts | 102 +++-- ...setup-script-package-manager-suggestion.ts | 3 +- .../ssh-retained-payload-admission.test.ts | 106 +++++ src/shared/ssh-retained-payload-admission.ts | 138 +++++++ src/shared/terminal-size-limits.ts | 34 ++ src/shared/terminal-stream-protocol.test.ts | 18 +- src/shared/terminal-stream-protocol.ts | 14 +- src/shared/text-search.test.ts | 19 +- src/shared/text-search.ts | 6 + src/shared/types.ts | 2 + src/shared/utf8-byte-limits.ts | 18 + .../workspace-space-entry-traversal.test.ts | 176 +++++++++ src/shared/workspace-space-entry-traversal.ts | 318 +++++++++++++++ .../workspace-space-scan-budget.test.ts | 51 +++ src/shared/workspace-space-scan-budget.ts | 87 ++++ src/shared/wsl-hook-relay-contract.ts | 17 +- 140 files changed, 7319 insertions(+), 719 deletions(-) create mode 100644 src/shared/agent-hook-endpoint-temp-cleanup.test.ts create mode 100644 src/shared/agent-hook-endpoint-temp-cleanup.ts create mode 100644 src/shared/agent-hook-listener-roster-retention.test.ts create mode 100644 src/shared/agent-hook-request-body-memory.test.ts create mode 100644 src/shared/agent-hook-status-cache.test.ts create mode 100644 src/shared/agent-hook-status-cache.ts create mode 100644 src/shared/bounded-map.test.ts create mode 100644 src/shared/bounded-map.ts create mode 100644 src/shared/external-automation-jobs-file.test.ts create mode 100644 src/shared/external-automation-jobs-file.ts create mode 100644 src/shared/filesystem-directory-listing-limit.test.ts create mode 100644 src/shared/filesystem-directory-listing-limit.ts create mode 100644 src/shared/hermes-run-output-limits.test.ts create mode 100644 src/shared/hermes-run-output-limits.ts create mode 100644 src/shared/hermes-run-ref-retention.test.ts create mode 100644 src/shared/hermes-run-ref-retention.ts create mode 100644 src/shared/linux-proc-port-scan-limits.test.ts create mode 100644 src/shared/linux-proc-port-scan-limits.ts create mode 100644 src/shared/linux-proc-socket-owner-scanner.test.ts create mode 100644 src/shared/linux-proc-socket-owner-scanner.ts create mode 100644 src/shared/map-settled-with-concurrency.test.ts create mode 100644 src/shared/markdown-document-listing-limits.test.ts create mode 100644 src/shared/markdown-document-listing-limits.ts create mode 100644 src/shared/mcp-config-inspection-limits.ts create mode 100644 src/shared/mcp-server-inspection.ts create mode 100644 src/shared/mobile-file-directory-limit.test.ts create mode 100644 src/shared/mobile-file-directory-limit.ts create mode 100644 src/shared/node-bounded-file-reader-sync.test.ts create mode 100644 src/shared/node-markdown-document-discovery.test.ts create mode 100644 src/shared/node-markdown-document-discovery.ts create mode 100644 src/shared/orca-yaml-alias-bounds.test.ts create mode 100644 src/shared/orca-yaml-bounds.test.ts create mode 100644 src/shared/orca-yaml-file-limit.ts create mode 100644 src/shared/pr-refresh-memory-limits.ts create mode 100644 src/shared/quick-open-directory-reader.test.ts create mode 100644 src/shared/quick-open-directory-reader.ts create mode 100644 src/shared/quick-open-git-entry-classification.ts create mode 100644 src/shared/quick-open-listing-limits.test.ts create mode 100644 src/shared/quick-open-listing-limits.ts create mode 100644 src/shared/quick-open-readdir-memory.test.ts create mode 100644 src/shared/relay-json-admission.ts create mode 100644 src/shared/relay-version-marker.test.ts create mode 100644 src/shared/relay-version-marker.ts create mode 100644 src/shared/remote-runtime-outbound-admission.test.ts create mode 100644 src/shared/remote-runtime-prepared-request-admission.ts create mode 100644 src/shared/remote-runtime-request-ready-waiters.ts create mode 100644 src/shared/remote-runtime-shared-control-admission.ts create mode 100644 src/shared/secure-path-hardening-cache.test.ts create mode 100644 src/shared/secure-path-hardening-cache.ts create mode 100644 src/shared/secure-path-windows-acl.ts create mode 100644 src/shared/setup-script-import-command-limits.ts create mode 100644 src/shared/setup-script-import-limits.ts create mode 100644 src/shared/ssh-retained-payload-admission.test.ts create mode 100644 src/shared/ssh-retained-payload-admission.ts create mode 100644 src/shared/terminal-size-limits.ts create mode 100644 src/shared/workspace-space-entry-traversal.test.ts create mode 100644 src/shared/workspace-space-entry-traversal.ts create mode 100644 src/shared/workspace-space-scan-budget.test.ts create mode 100644 src/shared/workspace-space-scan-budget.ts diff --git a/src/main/git/status.test.ts b/src/main/git/status.test.ts index 6084d67f5..2cdc41dc3 100644 --- a/src/main/git/status.test.ts +++ b/src/main/git/status.test.ts @@ -1,6 +1,7 @@ /* eslint-disable max-lines -- Why: git status/discard/chunking behavior is verified together here to keep the command contract readable in one place. */ import { beforeEach, describe, expect, it, vi } from 'vitest' import type * as NodeFs from 'node:fs' +import type * as BoundedFileReader from '../../shared/node-bounded-file-reader' import path from 'node:path' import { MAX_RENDERED_DIFF_COMBINED_CHARACTERS, @@ -62,6 +63,33 @@ vi.mock('fs', () => ({ existsSync: existsSyncMock })) +vi.mock('../../shared/node-bounded-file-reader', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + readNodeFileWithinLimit: async (filePath: string, maxBytes: number) => { + if (maxBytes === 64 * 1024) { + const value = await readFileMock(filePath) + const buffer = Buffer.isBuffer(value) ? value : Buffer.from(value) + if (buffer.length > maxBytes) { + throw new actual.NodeFileReadTooLargeError(buffer.length, maxBytes) + } + return { buffer, stats: { isFile: () => true, size: buffer.length } } + } + const stats = await statMock(filePath) + if (stats.size > maxBytes) { + throw new actual.NodeFileReadTooLargeError(stats.size, maxBytes) + } + const value = await readFileMock(filePath) + const buffer = Buffer.isBuffer(value) ? value : Buffer.from(value) + if (buffer.length > maxBytes) { + throw new actual.NodeFileReadTooLargeError(buffer.length, maxBytes) + } + return { buffer, stats } + } + } +}) + import { abortMerge, abortRebase, diff --git a/src/renderer/src/components/editor/ImageViewer.test.tsx b/src/renderer/src/components/editor/ImageViewer.test.tsx index 1639a638d..222d26701 100644 --- a/src/renderer/src/components/editor/ImageViewer.test.tsx +++ b/src/renderer/src/components/editor/ImageViewer.test.tsx @@ -144,6 +144,16 @@ async function renderExpandedImageViewer(content: string): Promise { ) } +function pngBase64(width: number): string { + const bytes = Buffer.alloc(24) + Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]).copy(bytes) + bytes.writeUInt32BE(13, 8) + bytes.write('IHDR', 12, 'ascii') + bytes.writeUInt32BE(width, 16) + bytes.writeUInt32BE(1, 20) + return bytes.toString('base64') +} + describe('ImageViewer preview source retry', () => { beforeEach(() => { reactHookRuntime.states = [] @@ -152,8 +162,8 @@ describe('ImageViewer preview source retry', () => { }) it('retries an earlier failed source after a later source loads successfully', async () => { - const failedContent = 'failed-source' - const loadedContent = 'loaded-source' + const failedContent = pngBase64(1) + const loadedContent = pngBase64(2) const firstRender = await renderExpandedImageViewer(failedContent) const firstImage = findPreviewImage(firstRender) @@ -176,4 +186,11 @@ describe('ImageViewer preview source retry', () => { const retryImage = findPreviewImage(retryRender) expect(retryImage.props.src).toBe(`data:image/png;base64,${failedContent}`) }) + + it('shows a failure instead of loading an unsafe raster forever', async () => { + const rendered = await renderExpandedImageViewer(pngBase64(32_769)) + + expect(findElementsByType(rendered, 'Image')).toHaveLength(1) + expect(findElementsByType(rendered, 'img')).toHaveLength(0) + }) }) diff --git a/src/renderer/src/components/editor/ImageViewer.tsx b/src/renderer/src/components/editor/ImageViewer.tsx index 88b57b092..07f49750b 100644 --- a/src/renderer/src/components/editor/ImageViewer.tsx +++ b/src/renderer/src/components/editor/ImageViewer.tsx @@ -63,7 +63,9 @@ export default function ImageViewer({ () => buildImageDataUri(mimeType, cleanedContent), [cleanedContent, mimeType] ) - const imageError = previewSrc !== null && failedPreviewSrc === previewSrc + const imageError = + (previewSrc === null && cleanedContent.length > 0) || + (previewSrc !== null && failedPreviewSrc === previewSrc) const estimatedSize = useMemo(() => { const bytes = Math.floor((cleanedContent.length * 3) / 4) if (bytes < 1024) { diff --git a/src/shared/agent-detection.test.ts b/src/shared/agent-detection.test.ts index 7f2f1308d..53ab82f1f 100644 --- a/src/shared/agent-detection.test.ts +++ b/src/shared/agent-detection.test.ts @@ -7,6 +7,7 @@ import { getAgentLabel, isCursorAgentTitle, MAX_OSC_TITLE_CHARS, + MAX_OSC_TITLES_PER_CHUNK, normalizeTerminalTitle } from './agent-detection' import { @@ -65,6 +66,19 @@ describe('OSC title extraction', () => { expect(extracted?.endsWith('b'.repeat(MAX_OSC_TITLE_CHARS / 2))).toBe(true) expect(extractAllOscTitles(data)).toEqual([extracted]) }) + + it('retains only the newest titles when one chunk contains limit +1', () => { + const data = Array.from( + { length: MAX_OSC_TITLES_PER_CHUNK + 1 }, + (_, index) => `\x1b]0;title-${index}\x07` + ).join('') + + const titles = extractAllOscTitles(data) + + expect(titles).toHaveLength(MAX_OSC_TITLES_PER_CHUNK) + expect(titles[0]).toBe('title-1') + expect(titles.at(-1)).toBe(`title-${MAX_OSC_TITLES_PER_CHUNK}`) + }) }) describe('MiMo title detection', () => { diff --git a/src/shared/agent-detection.ts b/src/shared/agent-detection.ts index 4fbfff86f..7097a4152 100644 --- a/src/shared/agent-detection.ts +++ b/src/shared/agent-detection.ts @@ -32,6 +32,7 @@ export { AGENT_NAMES, titleHasAgentName } from './agent-name-token-match' export { extractAllOscTitles, extractLastOscTitle, - MAX_OSC_TITLE_CHARS + MAX_OSC_TITLE_CHARS, + MAX_OSC_TITLES_PER_CHUNK } from './osc-title-extraction' export { isShellProcess } from './shell-process-detection' diff --git a/src/shared/agent-hook-endpoint-temp-cleanup.test.ts b/src/shared/agent-hook-endpoint-temp-cleanup.test.ts new file mode 100644 index 000000000..85b4ef985 --- /dev/null +++ b/src/shared/agent-hook-endpoint-temp-cleanup.test.ts @@ -0,0 +1,58 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const fsMocks = vi.hoisted(() => ({ + closeSync: vi.fn(), + readSync: vi.fn(), + statSync: vi.fn(), + unlinkSync: vi.fn() +})) + +vi.mock('node:fs', () => ({ + opendirSync: () => ({ + closeSync: fsMocks.closeSync, + readSync: fsMocks.readSync + }), + statSync: fsMocks.statSync, + unlinkSync: fsMocks.unlinkSync +})) + +import { + AGENT_HOOK_ENDPOINT_SWEEP_MAX_ENTRIES, + sweepStaleAgentHookEndpointTemps +} from './agent-hook-endpoint-temp-cleanup' + +describe('agent hook endpoint temp cleanup', () => { + beforeEach(() => { + vi.clearAllMocks() + fsMocks.statSync.mockReturnValue({ mtimeMs: 0 }) + }) + + it('stops an unbounded directory source at the scan cap', () => { + let entry = 0 + fsMocks.readSync.mockImplementation(() => ({ + name: `.endpoint-${(entry += 1)}.tmp` + })) + + sweepStaleAgentHookEndpointTemps('/endpoint', 10 * 60 * 1000) + + expect(fsMocks.readSync).toHaveBeenCalledTimes(AGENT_HOOK_ENDPOINT_SWEEP_MAX_ENTRIES) + expect(fsMocks.unlinkSync).toHaveBeenCalledTimes(AGENT_HOOK_ENDPOINT_SWEEP_MAX_ENTRIES) + expect(fsMocks.closeSync).toHaveBeenCalledOnce() + }) + + it('only removes stale endpoint temp files', () => { + fsMocks.readSync + .mockReturnValueOnce({ name: '.endpoint-stale.tmp' }) + .mockReturnValueOnce({ name: '.endpoint-fresh.tmp' }) + .mockReturnValueOnce({ name: 'endpoint.env' }) + .mockReturnValueOnce(null) + fsMocks.statSync + .mockReturnValueOnce({ mtimeMs: 0 }) + .mockReturnValueOnce({ mtimeMs: 9 * 60 * 1000 }) + + sweepStaleAgentHookEndpointTemps('/endpoint', 10 * 60 * 1000) + + expect(fsMocks.unlinkSync).toHaveBeenCalledOnce() + expect(fsMocks.unlinkSync).toHaveBeenCalledWith(expect.stringContaining('.endpoint-stale.tmp')) + }) +}) diff --git a/src/shared/agent-hook-endpoint-temp-cleanup.ts b/src/shared/agent-hook-endpoint-temp-cleanup.ts new file mode 100644 index 000000000..7a297f510 --- /dev/null +++ b/src/shared/agent-hook-endpoint-temp-cleanup.ts @@ -0,0 +1,38 @@ +import { opendirSync, statSync, unlinkSync } from 'node:fs' +import { join } from 'node:path' + +export const AGENT_HOOK_ENDPOINT_SWEEP_MAX_ENTRIES = 1024 +const AGENT_HOOK_ENDPOINT_STALE_MS = 5 * 60 * 1000 + +export function sweepStaleAgentHookEndpointTemps(endpointDir: string, now = Date.now()): void { + let directory: ReturnType | undefined + try { + directory = opendirSync(endpointDir, { bufferSize: 32 }) + const cutoff = now - AGENT_HOOK_ENDPOINT_STALE_MS + for (let scanned = 0; scanned < AGENT_HOOK_ENDPOINT_SWEEP_MAX_ENTRIES; scanned += 1) { + const entry = directory.readSync() + if (entry === null) { + break + } + if (!entry.name.startsWith('.endpoint-') || !entry.name.endsWith('.tmp')) { + continue + } + const entryPath = join(endpointDir, entry.name) + try { + if (statSync(entryPath).mtimeMs < cutoff) { + unlinkSync(entryPath) + } + } catch { + // best-effort sweep + } + } + } catch { + // Endpoint publication must still proceed on exotic filesystems. + } finally { + try { + directory?.closeSync() + } catch { + // already closed + } + } +} diff --git a/src/shared/agent-hook-listener-roster-retention.test.ts b/src/shared/agent-hook-listener-roster-retention.test.ts new file mode 100644 index 000000000..648792f4d --- /dev/null +++ b/src/shared/agent-hook-listener-roster-retention.test.ts @@ -0,0 +1,57 @@ +import { describe, expect, it } from 'vitest' +import { + createHookListenerState, + normalizeHookPayload, + type HookListenerState +} from './agent-hook-listener' +import { MAX_AGENT_HOOK_STATUS_CACHE_PANES } from './agent-hook-status-cache' +import { makePaneKey } from './stable-pane-id' + +const LEAF_ID = '11111111-1111-4111-8111-111111111111' + +function claudeEvent( + state: HookListenerState, + paneKey: string, + payload: Record +): ReturnType { + return normalizeHookPayload(state, 'claude', { paneKey, payload }, 'production') +} + +describe('Claude hook roster retention', () => { + it('does not retain rosters for malformed lifecycle events across unique panes', () => { + const state = createHookListenerState() + for (let index = 0; index <= MAX_AGENT_HOOK_STATUS_CACHE_PANES; index += 1) { + const paneKey = makePaneKey(`malformed-${index}`, LEAF_ID) + expect(claudeEvent(state, paneKey, { hook_event_name: 'TeammateIdle' })).toBeNull() + } + + expect(state.lastStatusByPaneKey.size).toBe(0) + expect(state.claudeSubagentRosterByPaneKey.size).toBe(0) + }) + + it('preserves ordinary teammate lifecycle updates', () => { + const state = createHookListenerState() + const paneKey = makePaneKey('valid-lifecycle', LEAF_ID) + claudeEvent(state, paneKey, { hook_event_name: 'UserPromptSubmit', prompt: 'spawn reviewer' }) + claudeEvent(state, paneKey, { hook_event_name: 'Stop', background_tasks: [] }) + + const started = claudeEvent(state, paneKey, { + hook_event_name: 'SubagentStart', + agent_id: 'areviewer-6d3cb5b52120b7bf', + agent_type: 'security-reviewer' + }) + expect(started?.payload.subagents).toEqual([ + expect.objectContaining({ id: 'areviewer-6d3cb5b52120b7bf', state: 'working' }) + ]) + + const idled = claudeEvent(state, paneKey, { + hook_event_name: 'TeammateIdle', + teammate_name: 'reviewer' + }) + expect(idled?.payload.state).toBe('done') + expect(idled?.payload.subagents).toEqual([ + expect.objectContaining({ id: 'areviewer-6d3cb5b52120b7bf', state: 'idle' }) + ]) + expect(state.claudeSubagentRosterByPaneKey.size).toBe(1) + }) +}) diff --git a/src/shared/agent-hook-listener.ts b/src/shared/agent-hook-listener.ts index 1e44aaf63..3f043a0a2 100644 --- a/src/shared/agent-hook-listener.ts +++ b/src/shared/agent-hook-listener.ts @@ -9,7 +9,6 @@ import { closeSync, mkdirSync, openSync, - readdirSync, readSync, renameSync, statSync, @@ -64,9 +63,21 @@ import { resolveGrokChatHistoryPathSync, resolveGrokSessionsDir } from './grok-session-paths' +import { sweepStaleAgentHookEndpointTemps } from './agent-hook-endpoint-temp-cleanup' +import { assertJsonTextStructureWithinLimits } from './json-text-structure-limit' /** Maximum request body size accepted by the listener (1 MB). */ export const HOOK_REQUEST_MAX_BYTES = 1_000_000 +const HOOK_REQUEST_INITIAL_BUFFER_BYTES = 4 * 1024 +const AGENT_HOOK_JSON_STRUCTURE_LIMITS = { + structuralTokens: 128 * 1024, + nestingDepth: 64 +} as const + +function parseAgentHookJson(content: string): unknown { + assertJsonTextStructureWithinLimits(content, AGENT_HOOK_JSON_STRUCTURE_LIMITS) + return JSON.parse(content) as unknown +} /** Bound the warn-once Sets so a client varying `version`/`env` per request can't grow them unbounded. */ const MAX_WARNED_KEYS = 32 @@ -303,7 +314,7 @@ export function parseFormEncodedBody(body: string): Record { export function readRequestBody(req: IncomingMessage): Promise { return new Promise((resolve, reject) => { - const chunks: Buffer[] = [] + let retained = Buffer.alloc(0) let byteLength = 0 let settled = false const cleanup = (): void => { @@ -332,21 +343,30 @@ export function readRequestBody(req: IncomingMessage): Promise { } const onData = (chunk: Buffer): void => { // Why: bound by bytes (not UTF-16 units) and stop accumulating after rejection so a client can't push memory past the cap. - if (byteLength + chunk.length > HOOK_REQUEST_MAX_BYTES) { + const nextByteLength = byteLength + chunk.length + if (nextByteLength > HOOK_REQUEST_MAX_BYTES) { settleReject(new Error('payload too large')) req.destroy() return } - byteLength += chunk.length - chunks.push(chunk) + if (retained.length < nextByteLength) { + const nextCapacity = Math.min( + HOOK_REQUEST_MAX_BYTES, + Math.max(HOOK_REQUEST_INITIAL_BUFFER_BYTES, retained.length * 2, nextByteLength) + ) + const next = Buffer.allocUnsafe(nextCapacity) + retained.copy(next, 0, 0, byteLength) + retained = next + } + chunk.copy(retained, byteLength) + byteLength = nextByteLength } const onEnd = (): void => { try { - // Why: Buffer.concat before decode so multi-byte UTF-8 straddling a chunk boundary reassembles correctly. - const body = chunks.length > 0 ? Buffer.concat(chunks).toString('utf8') : '' + const body = retained.toString('utf8', 0, byteLength) const contentType = req.headers['content-type'] ?? '' if (typeof contentType === 'string' && contentType.includes('application/json')) { - settleResolve(body ? JSON.parse(body) : {}) + settleResolve(body ? parseAgentHookJson(body) : {}) return } if ( @@ -357,7 +377,7 @@ export function readRequestBody(req: IncomingMessage): Promise { return } // Why: managed scripts POST JSON, updated POSIX scripts form-encoded; default to JSON for unknown content types. - settleResolve(body ? JSON.parse(body) : {}) + settleResolve(body ? parseAgentHookJson(body) : {}) } catch (error) { settleReject(error) } @@ -779,7 +799,7 @@ function parseJsonObjectString(value: unknown): Record | undefi return undefined } try { - const parsed = JSON.parse(value) as unknown + const parsed = parseAgentHookJson(value) return typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed) ? (parsed as Record) : undefined @@ -824,7 +844,7 @@ const GROK_HOME_ENVELOPE_MAX_LENGTH = 4096 function extractAssistantTextFromLine(line: string): string | undefined { let entry: unknown try { - entry = JSON.parse(line) + entry = parseAgentHookJson(line) } catch { return undefined } @@ -890,7 +910,7 @@ function extractAntigravityUserRequest(content: string): string | undefined { function extractUserPromptTextFromLine(line: string): string | undefined { let entry: unknown try { - entry = JSON.parse(line) + entry = parseAgentHookJson(line) } catch { return undefined } @@ -925,7 +945,7 @@ function readLastUserPromptFromTranscript(transcriptPath: unknown): string | und function extractCommandCodeUserPromptFromLine(line: string): string | undefined { let entry: unknown try { - entry = JSON.parse(line) + entry = parseAgentHookJson(line) } catch { return undefined } @@ -1021,7 +1041,7 @@ function* iterateTranscriptLinesWithByteOffsets( function extractCommandCodeAssistantTextFromLine(line: string): string | undefined { let entry: unknown try { - entry = JSON.parse(line) + entry = parseAgentHookJson(line) } catch { return undefined } @@ -1068,7 +1088,7 @@ function parseHookBodyPayloadRecord(body: unknown): Record | nu typeof rawPayload === 'string' ? (() => { try { - return JSON.parse(rawPayload) as unknown + return parseAgentHookJson(rawPayload) } catch { return null } @@ -2344,22 +2364,21 @@ function normalizeClaudeSubagentLifecycleEvent( paneKey: string, hookPayload: Record ): ParsedAgentStatusPayload | null { + const lifecycleField = eventName === 'TeammateIdle' ? 'teammate_name' : 'agent_id' + const lifecycleId = readString(hookPayload, lifecycleField) + if (!lifecycleId) { + return null + } const roster = getOrCreateClaudeSubagentRoster(state, paneKey) if (eventName === 'TeammateIdle') { - const teammateName = readString(hookPayload, 'teammate_name') - if (!teammateName) { - return null - } + const teammateName = lifecycleId // Why: on claude 2.1.21x teammates are turn-based — TeammateIdle means "turn over, awaiting mail", not finished. The row parks as idle (confirmed teammate) instead of leaving, so the sidebar keeps showing resumable children. idleClaudeTeammateByName(roster, teammateName) clearClaudePendingWaitForAgent(state, paneKey, (waitingAgentId) => claudeTeammateIdMatchesName(waitingAgentId, teammateName) ) } else { - const agentId = readString(hookPayload, 'agent_id') - if (!agentId) { - return null - } + const agentId = lifecycleId if (eventName === 'SubagentStart') { upsertWorkingClaudeSubagent( roster, @@ -3781,7 +3800,7 @@ export function normalizeHookPayload( typeof rawPayload === 'string' ? (() => { try { - return JSON.parse(rawPayload) + return parseAgentHookJson(rawPayload) } catch { return null } @@ -4065,26 +4084,8 @@ export function writeEndpointFile( // best-effort } } - // Why: sweep stale .endpoint-*.tmp orphans (crash between write and rename) so the dir can't grow unbounded. - try { - const entries = readdirSync(endpointDir) - const cutoff = Date.now() - 5 * 60 * 1000 - for (const entry of entries) { - if (!entry.startsWith('.endpoint-') || !entry.endsWith('.tmp')) { - continue - } - const entryPath = join(endpointDir, entry) - try { - if (statSync(entryPath).mtimeMs < cutoff) { - unlinkSync(entryPath) - } - } catch { - // best-effort sweep - } - } - } catch { - // readdirSync can fail on exotic filesystems - } + // Why: crash-orphan cleanup must not materialize a tampered, enormous directory. + sweepStaleAgentHookEndpointTemps(endpointDir) const separator = process.platform === 'win32' ? '\r\n' : '\n' writeFileSync(tmpPath, lines.join(separator), { mode: 0o600 }) tmpWritten = true diff --git a/src/shared/agent-hook-request-body-memory.test.ts b/src/shared/agent-hook-request-body-memory.test.ts new file mode 100644 index 000000000..0fae9ff87 --- /dev/null +++ b/src/shared/agent-hook-request-body-memory.test.ts @@ -0,0 +1,32 @@ +import { EventEmitter } from 'node:events' +import type { IncomingHttpHeaders, IncomingMessage } from 'node:http' +import { describe, expect, it, vi } from 'vitest' +import { readRequestBody } from './agent-hook-listener' + +type FakeIncomingMessage = EventEmitter & { + headers: IncomingHttpHeaders + destroy: ReturnType +} + +function createReadableRequest(): FakeIncomingMessage { + const request = new EventEmitter() as FakeIncomingMessage + request.headers = { 'content-type': 'application/json' } + request.destroy = vi.fn(() => request.emit('close')) + return request +} + +describe('agent hook request body retention', () => { + it('accepts adversarial one-byte events without per-event retained buffers', async () => { + const request = createReadableRequest() + const reading = readRequestBody(request as unknown as IncomingMessage) + const value = 'x'.repeat(100_000) + const body = Buffer.from(JSON.stringify({ value })) + + for (let index = 0; index < body.length; index += 1) { + request.emit('data', body.subarray(index, index + 1)) + } + request.emit('end') + + await expect(reading).resolves.toEqual({ value }) + }) +}) diff --git a/src/shared/agent-hook-status-cache.test.ts b/src/shared/agent-hook-status-cache.test.ts new file mode 100644 index 000000000..fc7238cfb --- /dev/null +++ b/src/shared/agent-hook-status-cache.test.ts @@ -0,0 +1,66 @@ +import { describe, expect, it } from 'vitest' +import { createHookListenerState, type AgentHookEventPayload } from './agent-hook-listener' +import { upsertBoundedAgentHookStatus } from './agent-hook-status-cache' +import { AGENT_STATUS_STALE_AFTER_MS } from './agent-status-types' + +function status( + paneKey: string, + state: AgentHookEventPayload['payload']['state'], + receivedAt: number +): AgentHookEventPayload { + return { + paneKey, + connectionId: null, + payload: { state, prompt: paneKey, agentType: 'claude' }, + receivedAt + } as AgentHookEventPayload +} + +describe('bounded agent hook status cache', () => { + it('preserves the current row and falls back to least-recently-updated eviction', () => { + const listener = createHookListenerState() + const now = Date.now() + upsertBoundedAgentHookStatus(listener, status('oldest', 'working', now), { maxPanes: 2, now }) + upsertBoundedAgentHookStatus(listener, status('newer', 'working', now), { maxPanes: 2, now }) + + const evicted = upsertBoundedAgentHookStatus(listener, status('current', 'working', now), { + maxPanes: 2, + now + }) + + expect(evicted.map(({ paneKey }) => paneKey)).toEqual(['oldest']) + expect([...listener.lastStatusByPaneKey.keys()]).toEqual(['newer', 'current']) + }) + + it('prefers the oldest completed or stale row and clears its related pane caches', () => { + const listener = createHookListenerState() + const now = Date.now() + upsertBoundedAgentHookStatus(listener, status('fresh-oldest', 'working', now), { + maxPanes: 3, + now + }) + upsertBoundedAgentHookStatus(listener, status('stale', 'working', now), { + maxPanes: 3, + now + }) + upsertBoundedAgentHookStatus(listener, status('done', 'done', now), { maxPanes: 3, now }) + const stale = listener.lastStatusByPaneKey.get('stale') as AgentHookEventPayload & { + receivedAt: number + } + stale.receivedAt = now - AGENT_STATUS_STALE_AFTER_MS - 1 + listener.lastPromptByPaneKey.set('stale', 'cached prompt') + listener.lastToolByPaneKey.set('stale\0tool', {} as never) + + const evicted = upsertBoundedAgentHookStatus(listener, status('current', 'working', now), { + maxPanes: 3, + now + }) + + expect(evicted.map(({ paneKey }) => paneKey)).toEqual(['stale']) + expect(listener.lastStatusByPaneKey.has('fresh-oldest')).toBe(true) + expect(listener.lastStatusByPaneKey.has('done')).toBe(true) + expect(listener.lastStatusByPaneKey.has('current')).toBe(true) + expect(listener.lastPromptByPaneKey.has('stale')).toBe(false) + expect(listener.lastToolByPaneKey.has('stale\0tool')).toBe(false) + }) +}) diff --git a/src/shared/agent-hook-status-cache.ts b/src/shared/agent-hook-status-cache.ts new file mode 100644 index 000000000..283e6d558 --- /dev/null +++ b/src/shared/agent-hook-status-cache.ts @@ -0,0 +1,69 @@ +import { + clearPaneCacheState, + type AgentHookEventPayload, + type HookListenerState +} from './agent-hook-listener' +import { AGENT_STATUS_STALE_AFTER_MS } from './agent-status-types' + +export const MAX_AGENT_HOOK_STATUS_CACHE_PANES = 500 + +export type AgentHookStatusCacheEviction = { + paneKey: string + entry: AgentHookEventPayload +} + +export function upsertBoundedAgentHookStatus( + state: HookListenerState, + entry: AgentHookEventPayload, + options: { maxPanes?: number; now?: number } = {} +): AgentHookStatusCacheEviction[] { + const maxPanes = options.maxPanes ?? MAX_AGENT_HOOK_STATUS_CACHE_PANES + if (!Number.isSafeInteger(maxPanes) || maxPanes < 1) { + throw new RangeError('Agent hook status cache limit must be a positive safe integer') + } + + state.lastStatusByPaneKey.delete(entry.paneKey) + state.lastStatusByPaneKey.set(entry.paneKey, entry) + const evicted: AgentHookStatusCacheEviction[] = [] + const now = options.now ?? Date.now() + while (state.lastStatusByPaneKey.size > maxPanes) { + const paneKey = selectEvictionCandidate(state, entry.paneKey, now) + if (!paneKey) { + break + } + const cached = state.lastStatusByPaneKey.get(paneKey) + if (!cached) { + break + } + evicted.push({ paneKey, entry: cached }) + clearPaneCacheState(state, paneKey) + } + return evicted +} + +function selectEvictionCandidate( + state: HookListenerState, + currentPaneKey: string, + now: number +): string | undefined { + let oldestFallback: string | undefined + for (const [paneKey, entry] of state.lastStatusByPaneKey) { + if (paneKey === currentPaneKey) { + continue + } + oldestFallback ??= paneKey + if (entry.payload.state === 'done' || isStaleStatus(entry, now)) { + return paneKey + } + } + return oldestFallback +} + +function isStaleStatus(entry: AgentHookEventPayload, now: number): boolean { + const receivedAt = (entry as AgentHookEventPayload & { receivedAt?: unknown }).receivedAt + return ( + typeof receivedAt === 'number' && + Number.isFinite(receivedAt) && + now - receivedAt > AGENT_STATUS_STALE_AFTER_MS + ) +} diff --git a/src/shared/agent-status-types.test.ts b/src/shared/agent-status-types.test.ts index b41374147..f6128a075 100644 --- a/src/shared/agent-status-types.test.ts +++ b/src/shared/agent-status-types.test.ts @@ -3,6 +3,7 @@ import { agentSubagentsEqual, parseAgentStatusPayload, normalizeAgentStatusPayload, + AGENT_STATUS_JSON_STRUCTURE_LIMITS, AGENT_STATUS_MAX_FIELD_LENGTH, AGENT_STATUS_MAX_SUBAGENTS, AGENT_STATUS_TOOL_NAME_MAX_LENGTH, @@ -55,6 +56,17 @@ describe('parseAgentStatusPayload', () => { expect(parseAgentStatusPayload('')).toBeNull() }) + it('rejects excessive nesting before JSON.parse', () => { + const parseSpy = vi.spyOn(JSON, 'parse') + const depth = AGENT_STATUS_JSON_STRUCTURE_LIMITS.nestingDepth + 1 + try { + expect(parseAgentStatusPayload(`${'['.repeat(depth)}0${']'.repeat(depth)}`)).toBeNull() + expect(parseSpy).not.toHaveBeenCalled() + } finally { + parseSpy.mockRestore() + } + }) + it('returns null for non-object JSON', () => { expect(parseAgentStatusPayload('"just a string"')).toBeNull() expect(parseAgentStatusPayload('42')).toBeNull() diff --git a/src/shared/agent-status-types.ts b/src/shared/agent-status-types.ts index 11a6385c7..1968ee089 100644 --- a/src/shared/agent-status-types.ts +++ b/src/shared/agent-status-types.ts @@ -9,6 +9,7 @@ import { normalizeOptionalMultilineField, normalizePromptField } from './agent-status-field-normalization' +import { assertJsonTextStructureWithinLimits } from './json-text-structure-limit' export { AGENT_STATUS_MAX_FIELD_LENGTH } from './agent-status-field-normalization' @@ -240,6 +241,10 @@ export const AGENT_MODEL_MAX_LENGTH = 120 /** Maximum subagent child rows carried per status entry. Bounds per-pane cache * and IPC fanout against a runaway spawner. */ export const AGENT_STATUS_MAX_SUBAGENTS = 32 +export const AGENT_STATUS_JSON_STRUCTURE_LIMITS = { + structuralTokens: 4096, + nestingDepth: 16 +} as const const AGENT_SUBAGENT_ID_MAX_LENGTH = 64 function normalizeSubagentSnapshot(value: unknown): AgentSubagentSnapshot | null { @@ -376,6 +381,7 @@ export function normalizeAgentStatusPayload(payload: unknown): ParsedAgentStatus */ export function parseAgentStatusPayload(json: string): ParsedAgentStatusPayload | null { try { + assertJsonTextStructureWithinLimits(json, AGENT_STATUS_JSON_STRUCTURE_LIMITS) return normalizeAgentStatusObject(JSON.parse(json)) } catch { return null diff --git a/src/shared/automations-types.ts b/src/shared/automations-types.ts index a41b364ef..d2572020b 100644 --- a/src/shared/automations-types.ts +++ b/src/shared/automations-types.ts @@ -253,6 +253,7 @@ export type ExternalAutomationJob = { lastError: string | null workdir: string | null runCount: number + runCountSaturated?: true runs: ExternalAutomationRun[] } @@ -277,6 +278,7 @@ export type ExternalAutomationRunsPage = { page: number pageSize: number total: number + totalSaturated?: true runs: ExternalAutomationRun[] } diff --git a/src/shared/bounded-map.test.ts b/src/shared/bounded-map.test.ts new file mode 100644 index 000000000..f5cacbc69 --- /dev/null +++ b/src/shared/bounded-map.test.ts @@ -0,0 +1,328 @@ +import { describe, expect, it, vi } from 'vitest' +import { BoundedMap } from './bounded-map' + +describe('BoundedMap', () => { + it('rejects an invalid maxEntries', () => { + expect(() => new BoundedMap({ maxEntries: 0 })).toThrow(RangeError) + expect(() => new BoundedMap({ maxEntries: 4, maxBytes: 10 })).toThrow(/sizeOf/) + }) + + it('evicts the least-recently-used entry past the count ceiling', () => { + const evicted: string[] = [] + const m = new BoundedMap({ maxEntries: 3, onEvict: (_v, k) => evicted.push(k) }) + m.set('a', 1) + m.set('b', 2) + m.set('c', 3) + expect(m.size).toBe(3) + m.set('d', 4) // count+1 -> evict oldest 'a' + expect(m.size).toBe(3) + expect(evicted).toEqual(['a']) + expect(m.has('a')).toBe(false) + expect([...m.keys()]).toEqual(['b', 'c', 'd']) + }) + + it('get() marks recently-used so it survives eviction', () => { + const m = new BoundedMap({ maxEntries: 3 }) + m.set('a', 1) + m.set('b', 2) + m.set('c', 3) + expect(m.get('a')).toBe(1) // 'a' now most-recent + m.set('d', 4) // evicts oldest, which is now 'b' not 'a' + expect(m.has('a')).toBe(true) + expect(m.has('b')).toBe(false) + }) + + it('bounds aggregate retained bytes and evicts to fit', () => { + const m = new BoundedMap({ + maxEntries: 100, + maxBytes: 10, + sizeOf: (v) => v.length + }) + m.set('a', 'xxxxx') // 5 + m.set('b', 'yyyyy') // 5 -> total 10 (exactly at cap) + expect(m.retainedBytes).toBe(10) + expect(m.size).toBe(2) + m.set('c', 'z') // 11 > 10 -> evict oldest until <= 10 + expect(m.retainedBytes).toBeLessThanOrEqual(10) + expect(m.has('a')).toBe(false) + expect(m.has('c')).toBe(true) + }) + + it('rejects a single value larger than maxBytes without wiping the map', () => { + const m = new BoundedMap({ + maxEntries: 10, + maxBytes: 4, + sizeOf: (v) => v.length + }) + expect(m.set('a', 'ok')).toBe(true) + expect(m.set('big', 'toolong')).toBe(false) + expect(m.has('a')).toBe(true) + expect(m.has('big')).toBe(false) + }) + + it('updates retained bytes on overwrite and delete', () => { + const m = new BoundedMap({ + maxEntries: 10, + maxBytes: 100, + sizeOf: (v) => v.length + }) + m.set('a', 'xxx') // 3 + m.set('a', 'x') // overwrite -> 1 + expect(m.retainedBytes).toBe(1) + m.delete('a') + expect(m.retainedBytes).toBe(0) + expect(m.size).toBe(0) + }) + + it('maxEntryBytes rejects an oversized single entry independent of the aggregate', () => { + const m = new BoundedMap({ + maxEntries: 10, + maxBytes: 100, + maxEntryBytes: 4, + sizeOf: (v) => v.length + }) + expect(m.set('a', 'ok')).toBe(true) + expect(m.set('b', 'toolong')).toBe(false) // 7 > maxEntryBytes 4, though aggregate has room + expect(m.has('a')).toBe(true) + expect(m.retainedBytes).toBe(2) + }) + + it('never reports success for an entry it did not retain', () => { + const onEvict = vi.fn() + // maxEntryBytes above maxBytes previously admitted an entry, then evicted it (and everything + // else) to satisfy the aggregate — set() returned true for a key the map no longer held. + const m = new BoundedMap({ + maxEntries: 10, + maxBytes: 3, + maxEntryBytes: 5, + sizeOf: (v) => v.length, + onEvict + }) + m.set('s1', 'x') + m.set('s2', 'y') + expect(m.set('big', 'xxxx')).toBe(false) + expect(m.has('big')).toBe(false) + expect(m.has('s1')).toBe(true) + expect(m.has('s2')).toBe(true) + expect(onEvict).not.toHaveBeenCalled() + expect(m.retainedBytes).toBe(2) + }) + + it('fails closed on an unmeasurable weight instead of poisoning the ledger', () => { + const m = new BoundedMap({ + maxEntries: 10, + maxBytes: 10, + sizeOf: (v) => (v === 'bad' ? Number.NaN : v.length) + }) + expect(m.set('ok', 'abc')).toBe(true) + expect(m.set('nan', 'bad')).toBe(false) + expect(m.set('neg', 'x')).toBe(true) + expect(m.retainedBytes).toBe(4) + expect(Number.isFinite(m.retainedBytes)).toBe(true) + // ceiling still armed after the rejected weight + expect(m.set('huge', 'zzzzzzzzzzzz')).toBe(false) + }) + + it('rejects invalid ceilings at construction', () => { + const sizeOf = (v: string): number => v.length + expect( + () => new BoundedMap({ maxEntries: 2, maxBytes: Number.NaN, sizeOf }) + ).toThrow(RangeError) + expect(() => new BoundedMap({ maxEntries: 2, maxBytes: -1, sizeOf })).toThrow( + RangeError + ) + }) + + it('a rejected oversized overwrite leaves the existing value untouched', () => { + const m = new BoundedMap({ + maxEntries: 10, + maxBytes: 20, + maxEntryBytes: 4, + sizeOf: (v) => v.length + }) + m.set('k', 'old') + expect(m.set('k', 'muchlonger')).toBe(false) + expect(m.get('k')).toBe('old') + expect(m.retainedBytes).toBe(3) + }) + + it('supports touching reads during a full traversal', () => { + const m = new BoundedMap({ maxEntries: 5 }) + m.set('a', 1) + m.set('b', 2) + const seen: string[] = [] + for (const k of m.keys()) { + seen.push(k) + m.get(k) // reorders the backing map mid-iteration + } + expect(seen).toEqual(['a', 'b']) + expect(m.entries()).toEqual([ + ['a', 1], + ['b', 2] + ]) + }) + + it('peek() reads without changing eviction order', () => { + const m = new BoundedMap({ maxEntries: 2 }) + m.set('a', 1) + m.set('b', 2) + expect(m.peek('a')).toBe(1) // does NOT mark 'a' recently used + m.set('c', 3) + expect(m.has('a')).toBe(false) + expect(m.has('b')).toBe(true) + }) + + it('stores an undefined value as a present key', () => { + const m = new BoundedMap({ maxEntries: 2 }) + expect(m.set('u', undefined)).toBe(true) + expect(m.has('u')).toBe(true) + expect(m.get('u')).toBeUndefined() + expect(m.keys()).toEqual(['u']) + }) + + it('keeps the byte ledger exact at the safe-integer boundary', () => { + const m = new BoundedMap({ + maxEntries: 10, + maxBytes: Number.MAX_SAFE_INTEGER, + sizeOf: (v) => v + }) + expect(m.set('a', Number.MAX_SAFE_INTEGER)).toBe(true) + // would overflow the aggregate past MAX_SAFE_INTEGER -> rejected, ledger untouched + expect(m.set('b', 1)).toBe(false) + expect(m.retainedBytes).toBe(Number.MAX_SAFE_INTEGER) + m.delete('a') + expect(m.retainedBytes).toBe(0) + }) + + it('an overflow-rejected overwrite keeps the prior value and leaves no orphaned weight', () => { + const weights = new Map([ + ['a', Number.MAX_SAFE_INTEGER - 1], + ['b', 1] + ]) + const m = new BoundedMap({ + maxEntries: 10, + maxBytes: Number.MAX_SAFE_INTEGER, + sizeOf: (_v, k) => weights.get(k) ?? 0 + }) + m.set('a', 'A') + m.set('b', 'B') + weights.set('b', 3) // next weight for 'b' exceeds the remaining headroom + expect(m.set('b', 'B2')).toBe(false) + expect(m.has('b')).toBe(true) // rejection must not displace the prior value + expect(m.peek('b')).toBe('B') + expect(m.retainedBytes).toBe(Number.MAX_SAFE_INTEGER) + // the rejected key must not strand a weight: deleting everything returns the ledger to zero + weights.set('b', 1) + m.delete('a') + m.delete('b') + expect(m.retainedBytes).toBe(0) + expect(m.size).toBe(0) + }) + + it('rejects fractional and unsafe weights and ceilings', () => { + const sizeOf = (v: number): number => v + expect(() => new BoundedMap({ maxEntries: 2, maxBytes: 1.5, sizeOf })).toThrow( + RangeError + ) + const m = new BoundedMap({ maxEntries: 4, maxBytes: 100, sizeOf }) + expect(m.set('frac', 0.5)).toBe(false) + expect(m.set('inf', Number.POSITIVE_INFINITY)).toBe(false) + expect(m.retainedBytes).toBe(0) + }) + + it('protects a just-admitted NaN key from eviction', () => { + const m = new BoundedMap({ + maxEntries: 2, + maxBytes: 6, + sizeOf: (v) => v.length + }) + m.set(1, 'aa') + m.set(2, 'bb') + expect(m.set(Number.NaN, 'cc')).toBe(true) + expect(m.has(Number.NaN)).toBe(true) + }) + + it('rejects the entry when sizeOf throws instead of propagating', () => { + const m = new BoundedMap({ + maxEntries: 4, + maxBytes: 50, + sizeOf: (v) => { + if (v === 'boom') { + throw new Error('measure failed') + } + return v.length + } + }) + expect(m.set('ok', 'abc')).toBe(true) + expect(() => m.set('bad', 'boom')).not.toThrow() + expect(m.set('bad', 'boom')).toBe(false) + expect(m.has('bad')).toBe(false) + expect(m.retainedBytes).toBe(3) + }) + + it('stays within bounds even when onEvict throws', () => { + const m = new BoundedMap({ + maxEntries: 10, + maxBytes: 3, + sizeOf: (v) => v.length, + onEvict: () => { + throw new Error('dispose failed') + } + }) + m.set('a', 'x') + m.set('b', 'y') + m.set('c', 'z') + expect(() => m.set('d', 'w')).toThrow('dispose failed') + // bounds restored before disposal ran, so the throw cannot strand the map over capacity + expect(m.retainedBytes).toBeLessThanOrEqual(3) + expect(m.size).toBeLessThanOrEqual(3) + }) + + it('reports failure when a reentrant onEvict evicts the just-admitted key', () => { + let reentered = false + const m: BoundedMap = new BoundedMap({ + maxEntries: 1, + onEvict: () => { + if (reentered) { + return + } + reentered = true + m.set('x', 'x') // nested set evicts the outer call's entry + } + }) + m.set('a', 'a') + const admitted = m.set('c', 'c') + // set() must never claim success for a key the map no longer holds + expect(admitted).toBe(m.has('c')) + }) + + it('runs every disposal even when one onEvict throws', () => { + const disposed: string[] = [] + const m = new BoundedMap({ + maxEntries: 10, + maxBytes: 2, + sizeOf: (v) => v.length, + onEvict: (_v, k) => { + disposed.push(k) + if (k === 'a') { + throw new Error('dispose failed') + } + } + }) + m.set('a', 'x') + m.set('b', 'y') + expect(() => m.set('c', 'zz')).toThrow('dispose failed') + expect(disposed).toEqual(['a', 'b']) // 'b' still disposed despite the earlier throw + expect(m.retainedBytes).toBeLessThanOrEqual(2) + }) + + it('does not fire onEvict on explicit delete/clear', () => { + const onEvict = vi.fn() + const m = new BoundedMap({ maxEntries: 5, onEvict }) + m.set('a', 1) + m.delete('a') + m.set('b', 2) + m.clear() + expect(onEvict).not.toHaveBeenCalled() + }) +}) diff --git a/src/shared/bounded-map.ts b/src/shared/bounded-map.ts new file mode 100644 index 000000000..2835c64d2 --- /dev/null +++ b/src/shared/bounded-map.ts @@ -0,0 +1,207 @@ +// Count- and byte-bounded insertion-ordered LRU map: one tested implementation of the +// "Map + entry counter + retained-byte ledger + evict-oldest" pattern. +// +// Contract: +// - get() marks a key most-recently-used. Reads therefore MUTATE order, so keys()/values()/entries() +// return snapshots — iterating while touching keys is safe and terminates. +// - set() admits or rejects; it never reports success for an entry it did not retain. An entry over +// maxEntryBytes is rejected and any previously stored value for that key is left untouched. +// - Weights must be non-negative safe integers (bytes). An unmeasurable weight fails CLOSED (entry +// rejected, ledger untouched) rather than poisoning the ledger and silently disabling the ceiling. +// - A value's measured weight is sampled once at set(); callers holding MUTABLE values must re-set +// after mutation, or the ledger will under-count what is actually retained. +// - onEvict fires only for involuntary capacity eviction — never for delete(), clear(), or the value +// an overwrite replaces — and only after both bounds have been restored. + +export type BoundedMapOptions = { + maxEntries: number + // Aggregate retained-byte ceiling across all values; omit for count-only bounding. + maxBytes?: number + // Per-entry ceiling, clamped to maxBytes. Defaults to maxBytes. + maxEntryBytes?: number + // Retained bytes for a value; required when maxBytes or maxEntryBytes is set. + sizeOf?: (value: V, key: K) => number + // Dispose hook for capacity eviction only. + onEvict?: (value: V, key: K) => void +} + +// Why safe integers: bytes are whole units, and float ledgers accumulate residue that can drift +// negative or saturate to Infinity, permanently corrupting later admission decisions. +function assertCeiling(name: string, value: number | undefined): void { + if (value === undefined) { + return + } + if (!Number.isSafeInteger(value) || value < 0) { + throw new RangeError(`BoundedMap ${name} must be a non-negative safe integer`) + } +} + +// Why SameValueZero: Map key equality treats NaN as equal to NaN, but === does not; a === guard +// would fail to protect a just-admitted NaN key and evict it after reporting success. +function isSameKey(a: K, b: K): boolean { + return a === b || (Number.isNaN(a as unknown as number) && Number.isNaN(b as unknown as number)) +} + +export class BoundedMap { + private readonly map = new Map() + private readonly bytesByKey = new Map() + private readonly maxEntries: number + private readonly maxBytes: number + private readonly maxEntryBytes: number + private readonly sizeOf: (value: V, key: K) => number + private readonly onEvict?: (value: V, key: K) => void + private retained = 0 + + constructor(options: BoundedMapOptions) { + if (!Number.isSafeInteger(options.maxEntries) || options.maxEntries < 1) { + throw new RangeError('BoundedMap maxEntries must be a positive safe integer') + } + // Why validate ceilings first: an invalid ceiling is a RangeError regardless of whether the + // caller also forgot sizeOf, so the more specific error should not mask it. + assertCeiling('maxBytes', options.maxBytes) + assertCeiling('maxEntryBytes', options.maxEntryBytes) + if ( + (options.maxBytes !== undefined || options.maxEntryBytes !== undefined) && + !options.sizeOf + ) { + throw new Error('BoundedMap requires sizeOf when maxBytes or maxEntryBytes is set') + } + this.maxEntries = options.maxEntries + this.maxBytes = options.maxBytes ?? Number.POSITIVE_INFINITY + // Why: a per-entry ceiling above the aggregate would admit an entry that eviction must then + // immediately discard, making set() return true for a key the map no longer holds. + this.maxEntryBytes = Math.min(options.maxEntryBytes ?? this.maxBytes, this.maxBytes) + this.sizeOf = options.sizeOf ?? (() => 0) + this.onEvict = options.onEvict + } + + get size(): number { + return this.map.size + } + + get retainedBytes(): number { + return this.retained + } + + has(key: K): boolean { + return this.map.has(key) + } + + // Marks the key most-recently-used. + get(key: K): V | undefined { + if (!this.map.has(key)) { + return undefined + } + const value = this.map.get(key) as V + this.map.delete(key) + this.map.set(key, value) + return value + } + + // Reads without affecting eviction order. + peek(key: K): V | undefined { + return this.map.get(key) + } + + // Returns false when the entry is rejected; a rejected entry never displaces an existing value. + set(key: K, value: V): boolean { + // Why: an unmeasurable weight must not enter the ledger — a NaN would make every later + // comparison false and silently retire the ceiling, so measurement failure rejects the entry + // rather than throwing into a caller that may be a relay on someone else's machine. + let measured: number + try { + measured = this.sizeOf(value, key) + } catch { + return false + } + if (!Number.isSafeInteger(measured) || measured < 0 || measured > this.maxEntryBytes) { + return false + } + // Why compute headroom before mutating: the ledger must stay exact, but a rejection here must + // not have already dropped the value it is replacing, so the displaced weight is credited + // arithmetically rather than by deleting first. + const replacing = this.map.has(key) ? (this.bytesByKey.get(key) ?? 0) : 0 + if (measured > Number.MAX_SAFE_INTEGER - (this.retained - replacing)) { + return false + } + if (this.map.has(key)) { + this.retained -= replacing + this.map.delete(key) + } + this.map.set(key, value) + this.bytesByKey.set(key, measured) + this.retained += measured + this.evictToFit(key) + // Why report presence rather than true: a reentrant onEvict can evict this key from a nested + // set(), and the contract is that a true return means the entry is retained. + return this.map.has(key) + } + + delete(key: K): boolean { + if (!this.map.has(key)) { + return false + } + this.retained -= this.bytesByKey.get(key) ?? 0 + this.bytesByKey.delete(key) + return this.map.delete(key) + } + + clear(): void { + this.map.clear() + this.bytesByKey.clear() + this.retained = 0 + } + + // Snapshots: safe to iterate while calling get(), which reorders the backing map. + keys(): K[] { + return [...this.map.keys()] + } + + values(): V[] { + return [...this.map.values()] + } + + entries(): [K, V][] { + return [...this.map.entries()] + } + + private evictToFit(protectedKey: K): void { + const disposed: [K, V][] = [] + while (this.map.size > this.maxEntries || this.retained > this.maxBytes) { + const oldest = this.map.entries().next() + if (oldest.done) { + break + } + const [key, value] = oldest.value + // Why: clamping maxEntryBytes keeps the just-admitted entry within the aggregate, so reaching + // it here would mean evicting the key set() just reported as retained. + if (isSameKey(key, protectedKey)) { + break + } + this.retained -= this.bytesByKey.get(key) ?? 0 + this.bytesByKey.delete(key) + this.map.delete(key) + disposed.push([key, value]) + } + if (!this.onEvict) { + return + } + // Why: bounds are restored before any disposal runs, so a hook that throws or reenters cannot + // strand the map over capacity; each disposal is isolated so one failure still frees the rest. + let firstFailure: unknown + let failed = false + for (const [key, value] of disposed) { + try { + this.onEvict(value, key) + } catch (error) { + if (!failed) { + failed = true + firstFailure = error + } + } + } + if (failed) { + throw firstFailure + } + } +} diff --git a/src/shared/browser-screencast-protocol.test.ts b/src/shared/browser-screencast-protocol.test.ts index c667646af..a2a9bec08 100644 --- a/src/shared/browser-screencast-protocol.test.ts +++ b/src/shared/browser-screencast-protocol.test.ts @@ -1,5 +1,7 @@ -import { describe, expect, it } from 'vitest' +import { describe, expect, it, vi } from 'vitest' import { + BROWSER_SCREENCAST_MAX_METADATA_BYTES, + BROWSER_SCREENCAST_METADATA_JSON_STRUCTURE_LIMITS, BrowserScreencastOpcode, decodeBrowserScreencastFrame, encodeBrowserScreencastFrame @@ -74,6 +76,39 @@ describe('browser screencast binary protocol', () => { expect(decodeBrowserScreencastFrame(encoded)).toBeNull() }) + it('rejects oversized metadata before decoding it', () => { + const encoded = new Uint8Array(16 + BROWSER_SCREENCAST_MAX_METADATA_BYTES + 1) + const view = new DataView(encoded.buffer) + encoded[0] = 0x62 + encoded[1] = 1 + encoded[2] = BrowserScreencastOpcode.Frame + encoded[3] = 1 + view.setUint32(8, BROWSER_SCREENCAST_MAX_METADATA_BYTES + 1, true) + + expect(decodeBrowserScreencastFrame(encoded)).toBeNull() + }) + + it('rejects excessive metadata nesting before JSON.parse', () => { + const parseSpy = vi.spyOn(JSON, 'parse') + try { + const depth = BROWSER_SCREENCAST_METADATA_JSON_STRUCTURE_LIMITS.nestingDepth + 1 + const metadata = new TextEncoder().encode(`${'['.repeat(depth)}0${']'.repeat(depth)}`) + const encoded = new Uint8Array(16 + metadata.byteLength) + const view = new DataView(encoded.buffer) + encoded[0] = 0x62 + encoded[1] = 1 + encoded[2] = BrowserScreencastOpcode.Frame + encoded[3] = 1 + view.setUint32(8, metadata.byteLength, true) + encoded.set(metadata, 16) + + expect(decodeBrowserScreencastFrame(encoded)).toBeNull() + expect(parseSpy).not.toHaveBeenCalled() + } finally { + parseSpy.mockRestore() + } + }) + it('rejects frames with nonzero reserved header bytes', () => { const encoded = encodeBrowserScreencastFrame({ opcode: BrowserScreencastOpcode.Frame, diff --git a/src/shared/browser-screencast-protocol.ts b/src/shared/browser-screencast-protocol.ts index cae15b3e2..842fe86cb 100644 --- a/src/shared/browser-screencast-protocol.ts +++ b/src/shared/browser-screencast-protocol.ts @@ -1,6 +1,13 @@ +import { assertJsonTextStructureWithinLimits } from './json-text-structure-limit' + const BROWSER_SCREENCAST_KIND = 0x62 const BROWSER_SCREENCAST_VERSION = 1 const HEADER_BYTES = 16 +export const BROWSER_SCREENCAST_MAX_METADATA_BYTES = 64 * 1024 +export const BROWSER_SCREENCAST_METADATA_JSON_STRUCTURE_LIMITS = { + structuralTokens: 512, + nestingDepth: 8 +} as const const METADATA_KEYS = [ 'offsetTop', 'pageScaleFactor', @@ -58,8 +65,13 @@ function encodeJson(value: unknown): Uint8Array { } function decodeJson(bytes: Uint8Array): unknown { + if (bytes.byteLength > BROWSER_SCREENCAST_MAX_METADATA_BYTES) { + return null + } try { - return JSON.parse(new TextDecoder().decode(bytes)) as unknown + const content = new TextDecoder().decode(bytes) + assertJsonTextStructureWithinLimits(content, BROWSER_SCREENCAST_METADATA_JSON_STRUCTURE_LIMITS) + return JSON.parse(content) as unknown } catch { return null } @@ -121,6 +133,9 @@ export function decodeBrowserScreencastFrame(bytes: Uint8Array): BrowserScreenca } const seq = view.getUint32(4, true) const metadataLength = view.getUint32(8, true) + if (metadataLength > BROWSER_SCREENCAST_MAX_METADATA_BYTES) { + return null + } if (view.getUint32(12, true) !== 0) { return null } diff --git a/src/shared/commit-message-agent-spec.test.ts b/src/shared/commit-message-agent-spec.test.ts index 7a3356e2e..3d8eac29c 100644 --- a/src/shared/commit-message-agent-spec.test.ts +++ b/src/shared/commit-message-agent-spec.test.ts @@ -1,6 +1,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import { COMMIT_MESSAGE_AGENT_SPECS, + COMMIT_MESSAGE_MODEL_JSON_STRUCTURE_LIMITS, CUSTOM_AGENT_ID, DEFAULT_COMMIT_MESSAGE_AGENT_ID, getCommitMessageAgentCapability, @@ -220,6 +221,17 @@ describe('model discovery parsers', () => { ]) }) + it('rejects excessive Codex model nesting before JSON.parse', () => { + const parseSpy = vi.spyOn(JSON, 'parse') + const depth = COMMIT_MESSAGE_MODEL_JSON_STRUCTURE_LIMITS.nestingDepth + 1 + try { + expect(parseCodexModels(`${'['.repeat(depth)}0${']'.repeat(depth)}`)).toEqual([]) + expect(parseSpy).not.toHaveBeenCalled() + } finally { + parseSpy.mockRestore() + } + }) + it('parses one-model-per-line output', () => { expect(parseLineModels('opencode/gpt-5.4-mini\n\nopenai/gpt-5.5\n').map((m) => m.id)).toEqual([ 'opencode/gpt-5.4-mini', diff --git a/src/shared/commit-message-agent-spec.ts b/src/shared/commit-message-agent-spec.ts index df6f0d275..98ed09d68 100644 --- a/src/shared/commit-message-agent-spec.ts +++ b/src/shared/commit-message-agent-spec.ts @@ -1,5 +1,6 @@ import type { TuiAgent } from './types' import { isTuiAgentEnabled } from './tui-agent-selection' +import { assertJsonTextStructureWithinLimits } from './json-text-structure-limit' /* eslint-disable max-lines -- Why: this is the single registry for non-interactive commit-message agents, their model discovery parsers, and UI capabilities. */ @@ -57,6 +58,11 @@ export type CommitMessageAgentCapability = { defaultModelId: string } +export const COMMIT_MESSAGE_MODEL_JSON_STRUCTURE_LIMITS = { + structuralTokens: 64 * 1024, + nestingDepth: 16 +} as const + const BASIC_THINKING_LEVELS: ThinkingLevel[] = [ { id: 'low', label: 'Low' }, { id: 'medium', label: 'Medium' }, @@ -135,6 +141,7 @@ function withOpenAiThinking( export function parseCodexModels(stdout: string): CommitMessageModel[] { try { + assertJsonTextStructureWithinLimits(stdout, COMMIT_MESSAGE_MODEL_JSON_STRUCTURE_LIMITS) const parsed = JSON.parse(stdout) as { models?: { slug?: string diff --git a/src/shared/ephemeral-vm-recipe-process.test.ts b/src/shared/ephemeral-vm-recipe-process.test.ts index 80d1ac589..0933305f6 100644 --- a/src/shared/ephemeral-vm-recipe-process.test.ts +++ b/src/shared/ephemeral-vm-recipe-process.test.ts @@ -23,6 +23,33 @@ function nodeCommand(scriptPath: string): string { } describe('runRecipeCommand', () => { + it.each([ + { output: 'abcdef', maxCaptureBytes: 4, expected: 'cdef' }, + { output: 'A😀B', maxCaptureBytes: 5, expected: '😀B' }, + { output: '😀😀😀', maxCaptureBytes: 5, expected: '😀' } + ])( + 'retains a complete UTF-8 tail within $maxCaptureBytes bytes', + async ({ output, maxCaptureBytes, expected }) => { + const repoPath = makeRepo() + const scriptPath = join(repoPath, 'output.js') + writeFileSync(scriptPath, `process.stdout.write(${JSON.stringify(output)})`) + + const result = await runRecipeCommand({ + command: nodeCommand(scriptPath), + repoPath, + mode: 'create', + context: { + recipeId: 'cloud-sandbox', + repoPath + }, + maxCaptureBytes + }) + + expect(result.stdout).toBe(expected) + expect(Buffer.byteLength(result.stdout, 'utf8')).toBeLessThanOrEqual(maxCaptureBytes) + } + ) + it.skipIf(process.platform === 'win32')( 'cancels shell child processes without waiting for long-running descendants', async () => { diff --git a/src/shared/ephemeral-vm-recipe-process.ts b/src/shared/ephemeral-vm-recipe-process.ts index 40b725558..5c0c24c82 100644 --- a/src/shared/ephemeral-vm-recipe-process.ts +++ b/src/shared/ephemeral-vm-recipe-process.ts @@ -143,9 +143,24 @@ function buildRecipeEnv( } function appendBounded(current: string, chunk: string, maxBytes: number): string { - const next = current + chunk - if (Buffer.byteLength(next, 'utf8') <= maxBytes) { - return next + if (maxBytes <= 0) { + return '' } - return next.slice(-maxBytes) + const chunkBytes = Buffer.byteLength(chunk, 'utf8') + if (chunkBytes >= maxBytes) { + return utf8Tail(chunk, maxBytes) + } + return utf8Tail(current, maxBytes - chunkBytes) + chunk +} + +function utf8Tail(value: string, maxBytes: number): string { + const bytes = Buffer.from(value, 'utf8') + if (bytes.byteLength <= maxBytes) { + return value + } + let start = bytes.byteLength - maxBytes + while (start < bytes.byteLength && (bytes[start]! & 0xc0) === 0x80) { + start += 1 + } + return bytes.subarray(start).toString('utf8') } diff --git a/src/shared/ephemeral-vm-recipes.test.ts b/src/shared/ephemeral-vm-recipes.test.ts index 9f0ee4fa1..b074c4383 100644 --- a/src/shared/ephemeral-vm-recipes.test.ts +++ b/src/shared/ephemeral-vm-recipes.test.ts @@ -1,6 +1,7 @@ -import { describe, expect, it } from 'vitest' +import { describe, expect, it, vi } from 'vitest' import { encodePairingOffer, PAIRING_OFFER_VERSION } from './pairing' import { + EPHEMERAL_VM_RECIPE_JSON_STRUCTURE_LIMITS, getEphemeralVmRecipeResultWarnings, parseEphemeralVmRecipeResult, redactEphemeralVmRecipeDiagnosticText, @@ -154,6 +155,22 @@ describe('parseEphemeralVmRecipeResult', () => { }) }) + it('rejects excessive nesting before JSON.parse', () => { + const parseSpy = vi.spyOn(JSON, 'parse') + try { + const depth = EPHEMERAL_VM_RECIPE_JSON_STRUCTURE_LIMITS.nestingDepth + 1 + const amplified = `${'['.repeat(depth)}0${']'.repeat(depth)}` + + expect(parseEphemeralVmRecipeResult(amplified)).toEqual({ + ok: false, + error: 'Recipe stdout must be one JSON object.' + }) + expect(parseSpy).not.toHaveBeenCalled() + } finally { + parseSpy.mockRestore() + } + }) + it('rejects invalid pairing codes', () => { expect( parseEphemeralVmRecipeResult( diff --git a/src/shared/ephemeral-vm-recipes.ts b/src/shared/ephemeral-vm-recipes.ts index 65729a261..0f68bc92f 100644 --- a/src/shared/ephemeral-vm-recipes.ts +++ b/src/shared/ephemeral-vm-recipes.ts @@ -5,6 +5,7 @@ import { MAX_SSH_RELAY_GRACE_PERIOD_SECONDS, MIN_SSH_RELAY_GRACE_PERIOD_SECONDS } from './ssh-types' +import { assertJsonTextStructureWithinLimits } from './json-text-structure-limit' // Why: ephemeral-vm-recipe-doctor imports Node's fs/path, so it must NOT be // re-exported through this barrel — the renderer/web-client imports this module // and would otherwise pull Node built-ins into the browser bundle (build fails). @@ -35,6 +36,11 @@ export type JsonValue = | JsonValue[] | { [key: string]: JsonValue } +export const EPHEMERAL_VM_RECIPE_JSON_STRUCTURE_LIMITS = { + structuralTokens: 256 * 1024, + nestingDepth: 64 +} as const + const SavedPortForwardSchema = z .object({ localPort: z.number().int().min(1).max(65535), @@ -151,6 +157,7 @@ export function parseEphemeralVmRecipeResult(stdout: string): EphemeralVmRecipeR } let parsed: unknown try { + assertJsonTextStructureWithinLimits(trimmed, EPHEMERAL_VM_RECIPE_JSON_STRUCTURE_LIMITS) parsed = JSON.parse(trimmed) } catch { return { ok: false, error: 'Recipe stdout must be one JSON object.' } diff --git a/src/shared/ephemeral-vm-runtime-store.test.ts b/src/shared/ephemeral-vm-runtime-store.test.ts index 2aea7ff4b..a252ffe53 100644 --- a/src/shared/ephemeral-vm-runtime-store.test.ts +++ b/src/shared/ephemeral-vm-runtime-store.test.ts @@ -1,4 +1,4 @@ -import { mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { mkdtempSync, rmSync, truncateSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it } from 'vitest' @@ -7,6 +7,7 @@ import { EphemeralVmRuntimeStoreError, getEphemeralVmRuntimeStorePath, listEphemeralVmRuntimes, + MAX_EPHEMERAL_VM_RUNTIME_STORE_FILE_BYTES, removeEphemeralVmRuntime, updateEphemeralVmRuntimeStatus, upsertEphemeralVmRuntime @@ -173,4 +174,27 @@ describe('ephemeral VM runtime store', () => { expect(() => listEphemeralVmRuntimes(userDataPath)).toThrow(EphemeralVmRuntimeStoreError) }) + + it('rejects an oversized sparse runtime store before parsing it', () => { + const userDataPath = makeUserDataPath() + const path = getEphemeralVmRuntimeStorePath(userDataPath) + writeFileSync(path, '{"version":1,"runtimes":[]}', 'utf8') + truncateSync(path, MAX_EPHEMERAL_VM_RUNTIME_STORE_FILE_BYTES + 1) + + expect(() => listEphemeralVmRuntimes(userDataPath)).toThrow(EphemeralVmRuntimeStoreError) + }) + + it('rejects an oversized write without publishing a partial runtime record', () => { + const userDataPath = makeUserDataPath() + + expect(() => + upsertEphemeralVmRuntime( + userDataPath, + runtimeRecord({ + cleanupLastError: 'x'.repeat(MAX_EPHEMERAL_VM_RUNTIME_STORE_FILE_BYTES) + }) + ) + ).toThrow(EphemeralVmRuntimeStoreError) + expect(listEphemeralVmRuntimes(userDataPath)).toEqual([]) + }) }) diff --git a/src/shared/ephemeral-vm-runtime-store.ts b/src/shared/ephemeral-vm-runtime-store.ts index 73e8ce785..ad26bb295 100644 --- a/src/shared/ephemeral-vm-runtime-store.ts +++ b/src/shared/ephemeral-vm-runtime-store.ts @@ -1,6 +1,9 @@ -import { existsSync, readFileSync } from 'node:fs' +import { existsSync } from 'node:fs' import { join } from 'node:path' -import { hardenExistingSecureFile, writeSecureJsonFile } from './secure-file' +import { JsonStringifyByteLimitError } from './node-bounded-json-stringify' +import { readNodeFileSyncWithinLimit } from './node-bounded-file-reader' +import { writeSecureJsonFileWithinLimit } from './bounded-secure-json-file' +import { hardenExistingSecureFile } from './secure-file' import { EphemeralVmRuntimeRecordSchema, EphemeralVmRuntimeStoreSchema, @@ -11,6 +14,7 @@ import { } from './ephemeral-vm-runtimes' const EPHEMERAL_VM_RUNTIMES_FILE = 'orca-ephemeral-vm-runtimes.json' +export const MAX_EPHEMERAL_VM_RUNTIME_STORE_FILE_BYTES = 1024 * 1024 export type EphemeralVmRuntimeStoreErrorCode = 'invalid_argument' | 'runtime_error' @@ -136,7 +140,14 @@ function readEphemeralVmRuntimeStore(userDataPath: string): EphemeralVmRuntimeSt } try { hardenExistingSecureFile(path) - const parsed = EphemeralVmRuntimeStoreSchema.parse(JSON.parse(readFileSync(path, 'utf8'))) + const parsed = EphemeralVmRuntimeStoreSchema.parse( + JSON.parse( + readNodeFileSyncWithinLimit( + path, + MAX_EPHEMERAL_VM_RUNTIME_STORE_FILE_BYTES + ).buffer.toString('utf8') + ) + ) return { version: 1, runtimes: parsed.runtimes @@ -153,7 +164,21 @@ function readEphemeralVmRuntimeStore(userDataPath: string): EphemeralVmRuntimeSt function writeEphemeralVmRuntimeStore(userDataPath: string, store: EphemeralVmRuntimeStore): void { const path = getEphemeralVmRuntimeStorePath(userDataPath) - writeSecureJsonFile(path, EphemeralVmRuntimeStoreSchema.parse(store)) + try { + writeSecureJsonFileWithinLimit( + path, + EphemeralVmRuntimeStoreSchema.parse(store), + MAX_EPHEMERAL_VM_RUNTIME_STORE_FILE_BYTES + ) + } catch (error) { + if (error instanceof JsonStringifyByteLimitError) { + throw new EphemeralVmRuntimeStoreError( + 'runtime_error', + `Could not write Orca ephemeral VM runtimes at ${path}; the store exceeds its durable capacity.` + ) + } + throw error + } } function compareRuntimeRecords(a: EphemeralVmRuntimeRecord, b: EphemeralVmRuntimeRecord): number { diff --git a/src/shared/external-automation-jobs-file.test.ts b/src/shared/external-automation-jobs-file.test.ts new file mode 100644 index 000000000..13b8a7078 --- /dev/null +++ b/src/shared/external-automation-jobs-file.test.ts @@ -0,0 +1,71 @@ +import { mkdtemp, rm, truncate, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, describe, expect, it } from 'vitest' +import { + EXTERNAL_AUTOMATION_JOBS_FILE_MAX_BYTES, + EXTERNAL_AUTOMATION_JOBS_MAX_ENTRIES, + readExternalAutomationJobsFile +} from './external-automation-jobs-file' + +const tempDirs: string[] = [] + +afterEach(async () => { + await Promise.all(tempDirs.splice(0).map((dir) => rm(dir, { recursive: true, force: true }))) +}) + +async function tempFile(name: string): Promise { + const dir = await mkdtemp(join(tmpdir(), 'orca-automation-jobs-')) + tempDirs.push(dir) + return join(dir, name) +} + +describe('readExternalAutomationJobsFile', () => { + it('preserves supported jobs shapes below the limits', async () => { + const wrappedPath = await tempFile('wrapped.json') + const rootPath = await tempFile('root.json') + await writeFile(wrappedPath, JSON.stringify({ jobs: [{ id: 'one' }] })) + await writeFile(rootPath, JSON.stringify([{ id: 'two' }])) + + await expect( + readExternalAutomationJobsFile(wrappedPath, { allowRootArray: false }) + ).resolves.toEqual([{ id: 'one' }]) + await expect( + readExternalAutomationJobsFile(rootPath, { allowRootArray: true }) + ).resolves.toEqual([{ id: 'two' }]) + }) + + it('rejects oversized sparse files before reading them wholesale', async () => { + const path = await tempFile('oversized.json') + await writeFile(path, '') + await truncate(path, EXTERNAL_AUTOMATION_JOBS_FILE_MAX_BYTES + 64 * 1024 * 1024) + + await expect(readExternalAutomationJobsFile(path, { allowRootArray: true })).rejects.toThrow( + 'jobs file exceeds the 8 MiB memory limit' + ) + }) + + it('rejects excessive job counts explicitly', async () => { + const path = await tempFile('too-many.json') + await writeFile( + path, + JSON.stringify(Array.from({ length: EXTERNAL_AUTOMATION_JOBS_MAX_ENTRIES + 1 }, () => null)) + ) + + await expect(readExternalAutomationJobsFile(path, { allowRootArray: true })).rejects.toThrow( + 'more than 10,000 jobs' + ) + }) + + it('rejects structural amplification before parsing jobs', async () => { + const path = await tempFile('amplified.json') + await writeFile(path, '{"jobs":[{},{}]}') + + await expect( + readExternalAutomationJobsFile(path, { + allowRootArray: false, + structureLimits: { structuralTokens: 7, nestingDepth: 3 } + }) + ).rejects.toThrow('JSON structure') + }) +}) diff --git a/src/shared/external-automation-jobs-file.ts b/src/shared/external-automation-jobs-file.ts new file mode 100644 index 000000000..1013b8a0a --- /dev/null +++ b/src/shared/external-automation-jobs-file.ts @@ -0,0 +1,58 @@ +import { NodeFileReadTooLargeError, readNodeFileWithinLimit } from './node-bounded-file-reader' +import { + assertJsonTextStructureWithinLimits, + type JsonTextStructureLimits +} from './json-text-structure-limit' + +export const EXTERNAL_AUTOMATION_JOBS_FILE_MAX_BYTES = 8 * 1024 * 1024 +export const EXTERNAL_AUTOMATION_JOBS_MAX_ENTRIES = 10_000 +export const EXTERNAL_AUTOMATION_JOBS_JSON_LIMITS: JsonTextStructureLimits = { + structuralTokens: 1_000_000, + nestingDepth: 128 +} + +type ExternalAutomationJobsFileOptions = { + allowRootArray: boolean + structureLimits?: JsonTextStructureLimits +} + +export async function readExternalAutomationJobsFile( + filePath: string, + options: ExternalAutomationJobsFileOptions +): Promise { + let buffer: Buffer + try { + const result = await readNodeFileWithinLimit(filePath, EXTERNAL_AUTOMATION_JOBS_FILE_MAX_BYTES) + buffer = result.buffer + } catch (error) { + if (error instanceof NodeFileReadTooLargeError) { + throw new Error( + `External automation jobs file exceeds the ${EXTERNAL_AUTOMATION_JOBS_FILE_MAX_BYTES / 1024 / 1024} MiB memory limit: ${filePath}` + ) + } + throw error + } + + const serialized = buffer.toString('utf-8') + assertJsonTextStructureWithinLimits( + serialized, + options.structureLimits ?? EXTERNAL_AUTOMATION_JOBS_JSON_LIMITS + ) + const parsed = JSON.parse(serialized) as unknown + const jobs = + options.allowRootArray && Array.isArray(parsed) + ? parsed + : isRecord(parsed) && Array.isArray(parsed.jobs) + ? parsed.jobs + : [] + if (jobs.length > EXTERNAL_AUTOMATION_JOBS_MAX_ENTRIES) { + throw new Error( + `External automation jobs file contains more than ${EXTERNAL_AUTOMATION_JOBS_MAX_ENTRIES.toLocaleString()} jobs and cannot be loaded safely: ${filePath}` + ) + } + return jobs +} + +function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value) +} diff --git a/src/shared/filesystem-directory-listing-limit.test.ts b/src/shared/filesystem-directory-listing-limit.test.ts new file mode 100644 index 000000000..73e9feaad --- /dev/null +++ b/src/shared/filesystem-directory-listing-limit.test.ts @@ -0,0 +1,59 @@ +import { describe, expect, it } from 'vitest' +import { + assertFilesystemDirectoryWithinLimit, + createFilesystemDirectoryLimitState, + FILESYSTEM_DIRECTORY_LIMIT_MESSAGE, + FILESYSTEM_DIRECTORY_MAX_ENTRIES, + FILESYSTEM_DIRECTORY_MAX_RETAINED_BYTES, + resolveFilesystemDirectoryListingLimits, + trackFilesystemDirectoryEntry +} from './filesystem-directory-listing-limit' + +describe('filesystem directory listing limit', () => { + it('accepts ordinary complete listings', () => { + expect(() => + assertFilesystemDirectoryWithinLimit([ + { name: 'src' }, + { name: 'README.md' }, + { name: '文件.txt' } + ]) + ).not.toThrow() + }) + + it('rejects the first entry beyond the count limit', () => { + const state = createFilesystemDirectoryLimitState({ + maxEntries: 2, + maxRetainedBytes: FILESYSTEM_DIRECTORY_MAX_RETAINED_BYTES + }) + + trackFilesystemDirectoryEntry(state, { name: 'one' }) + trackFilesystemDirectoryEntry(state, { name: 'two' }) + expect(() => trackFilesystemDirectoryEntry(state, { name: 'three' })).toThrow( + FILESYSTEM_DIRECTORY_LIMIT_MESSAGE + ) + expect(state.entries).toBe(3) + }) + + it('rejects names beyond the retained-byte limit', () => { + const state = createFilesystemDirectoryLimitState({ + maxEntries: FILESYSTEM_DIRECTORY_MAX_ENTRIES, + maxRetainedBytes: 100 + }) + + expect(() => trackFilesystemDirectoryEntry(state, { name: 'xx' })).toThrow( + FILESYSTEM_DIRECTORY_LIMIT_MESSAGE + ) + }) + + it('never lets callers raise the process-wide ceilings', () => { + expect( + resolveFilesystemDirectoryListingLimits({ + maxEntries: Number.MAX_SAFE_INTEGER, + maxRetainedBytes: Number.MAX_SAFE_INTEGER + }) + ).toEqual({ + maxEntries: FILESYSTEM_DIRECTORY_MAX_ENTRIES, + maxRetainedBytes: FILESYSTEM_DIRECTORY_MAX_RETAINED_BYTES + }) + }) +}) diff --git a/src/shared/filesystem-directory-listing-limit.ts b/src/shared/filesystem-directory-listing-limit.ts new file mode 100644 index 000000000..c43f0eebb --- /dev/null +++ b/src/shared/filesystem-directory-listing-limit.ts @@ -0,0 +1,75 @@ +export const FILESYSTEM_DIRECTORY_MAX_ENTRIES = 100_000 +export const FILESYSTEM_DIRECTORY_MAX_RETAINED_BYTES = 12 * 1024 * 1024 +export const FILESYSTEM_DIRECTORY_LIMIT_MESSAGE = + 'This folder is too large to list safely (limit: 100,000 items or a 12 MB listing).' + +export type FilesystemDirectoryListingLimits = { + maxEntries: number + maxRetainedBytes: number +} + +type NamedDirectoryEntry = { name: string } + +export type FilesystemDirectoryLimitState = { + entries: number + retainedBytes: number + limits: FilesystemDirectoryListingLimits +} + +export function resolveFilesystemDirectoryListingLimits( + requested?: Partial +): FilesystemDirectoryListingLimits { + return { + maxEntries: clampLimit(requested?.maxEntries, FILESYSTEM_DIRECTORY_MAX_ENTRIES), + maxRetainedBytes: clampLimit( + requested?.maxRetainedBytes, + FILESYSTEM_DIRECTORY_MAX_RETAINED_BYTES + ) + } +} + +export function createFilesystemDirectoryLimitState( + requested?: Partial +): FilesystemDirectoryLimitState { + return { + entries: 0, + retainedBytes: 0, + limits: resolveFilesystemDirectoryListingLimits(requested) + } +} + +export function trackFilesystemDirectoryEntry( + state: FilesystemDirectoryLimitState, + entry: NamedDirectoryEntry +): void { + state.entries += 1 + state.retainedBytes += estimateFilesystemDirectoryEntryBytes(entry) + if ( + state.entries > state.limits.maxEntries || + state.retainedBytes > state.limits.maxRetainedBytes + ) { + throw new Error(FILESYSTEM_DIRECTORY_LIMIT_MESSAGE) + } +} + +export function assertFilesystemDirectoryWithinLimit( + entries: readonly NamedDirectoryEntry[], + requested?: Partial +): void { + const state = createFilesystemDirectoryLimitState(requested) + for (const entry of entries) { + trackFilesystemDirectoryEntry(state, entry) + } +} + +export function estimateFilesystemDirectoryEntryBytes(entry: NamedDirectoryEntry): number { + // Why: this covers worst-case JSON escaping plus each result object's fixed overhead. + return entry.name.length * 6 + 96 +} + +function clampLimit(value: number | undefined, maximum: number): number { + if (typeof value !== 'number' || !Number.isSafeInteger(value) || value <= 0) { + return maximum + } + return Math.min(value, maximum) +} diff --git a/src/shared/git-check-ignore-stdio.ts b/src/shared/git-check-ignore-stdio.ts index 40eb3c5ca..17d6ce8eb 100644 --- a/src/shared/git-check-ignore-stdio.ts +++ b/src/shared/git-check-ignore-stdio.ts @@ -38,5 +38,12 @@ export function splitGitCheckIgnorePathsByStdinBytes( } export function parseGitCheckIgnorePaths(stdout: string): string[] { - return stdout.split('\0').filter((path) => path.length > 0) + const paths: string[] = [] + for (const path of iterateNulDelimitedFields(stdout)) { + if (path) { + paths.push(path) + } + } + return paths } +import { iterateNulDelimitedFields } from './nul-delimited-fields' diff --git a/src/shared/git-config-snapshot-runner.ts b/src/shared/git-config-snapshot-runner.ts index 0eb5a3694..2f3e56a7b 100644 --- a/src/shared/git-config-snapshot-runner.ts +++ b/src/shared/git-config-snapshot-runner.ts @@ -27,7 +27,7 @@ function canonicalizeGitConfigLookupKey(key: string): string { function parseGitConfigListSnapshot(stdout: string): GitConfigSnapshot { const snapshot: GitConfigSnapshot = new Map() - for (const record of stdout.split('\0')) { + for (const record of iterateNulDelimitedFields(stdout)) { if (!record.trim()) { continue } @@ -101,3 +101,4 @@ export function createGitConfigSnapshotRunner(runGit: GitCommandRunner): GitComm return { stdout: values.at(-1) ?? '' } } } +import { iterateNulDelimitedFields } from './nul-delimited-fields' diff --git a/src/shared/git-discard-path-safety.ts b/src/shared/git-discard-path-safety.ts index de049a90d..84a0cdd74 100644 --- a/src/shared/git-discard-path-safety.ts +++ b/src/shared/git-discard-path-safety.ts @@ -1,5 +1,8 @@ import { lstat, realpath } from 'node:fs/promises' import * as path from 'node:path' +import { forEachWithConcurrency } from './map-with-concurrency' + +const DISCARD_PATH_VALIDATION_CONCURRENCY = 16 function isENOENT(error: unknown): boolean { return ( @@ -111,16 +114,16 @@ export async function removeSafeUntrackedDiscardTargets( removePaths: (filePaths: readonly string[]) => Promise, beforeRemove?: () => Promise ): Promise { - await Promise.all( - filePaths.map((filePath) => validateUntrackedDiscardTarget(worktreePath, filePath)) - ) + await forEachWithConcurrency(filePaths, DISCARD_PATH_VALIDATION_CONCURRENCY, async (filePath) => { + await validateUntrackedDiscardTarget(worktreePath, filePath) + }) // Why: bulk discard must validate every untracked path before mutating // tracked files, then recheck before the caller's Git-bounded cleanup runs. await beforeRemove?.() - await Promise.all( - filePaths.map((filePath) => validateUntrackedDiscardTarget(worktreePath, filePath)) - ) + await forEachWithConcurrency(filePaths, DISCARD_PATH_VALIDATION_CONCURRENCY, async (filePath) => { + await validateUntrackedDiscardTarget(worktreePath, filePath) + }) await removePaths(filePaths) } diff --git a/src/shared/git-history-log-parser.ts b/src/shared/git-history-log-parser.ts index cfda6a2b4..8f34002f0 100644 --- a/src/shared/git-history-log-parser.ts +++ b/src/shared/git-history-log-parser.ts @@ -1,4 +1,5 @@ import type { GitHistoryItem, GitHistoryItemRef } from './git-history-types' +import { iterateNulDelimitedFields } from './nul-delimited-fields' const GIT_HISTORY_DECORATION_SEPARATOR = '\x1f' @@ -98,7 +99,7 @@ export function compareGitHistoryItemRefsByCategory( export function parseGitHistoryLog(stdout: string): GitHistoryItem[] { const items: GitHistoryItem[] = [] - for (const rawRecord of stdout.split('\0')) { + for (const rawRecord of iterateNulDelimitedFields(stdout)) { const record = rawRecord.replace(/^\n+/, '') if (!record.trim()) { continue diff --git a/src/shared/git-uncommitted-line-stats.test.ts b/src/shared/git-uncommitted-line-stats.test.ts index 96556be88..0e2d54986 100644 --- a/src/shared/git-uncommitted-line-stats.test.ts +++ b/src/shared/git-uncommitted-line-stats.test.ts @@ -5,7 +5,14 @@ const { lstatMock, readFileMock } = vi.hoisted(() => ({ readFileMock: vi.fn() })) -vi.mock('fs/promises', () => ({ lstat: lstatMock, readFile: readFileMock })) +vi.mock('fs/promises', () => ({ lstat: lstatMock })) + +vi.mock('./node-bounded-file-reader', () => ({ + readNodeFileWithinLimit: async (path: string) => ({ + buffer: await readFileMock(path), + stats: mockFileStat(0) + }) +})) import { applyLineStats, diff --git a/src/shared/git-uncommitted-line-stats.ts b/src/shared/git-uncommitted-line-stats.ts index ac46b9284..3896d9354 100644 --- a/src/shared/git-uncommitted-line-stats.ts +++ b/src/shared/git-uncommitted-line-stats.ts @@ -1,8 +1,10 @@ -import { lstat, readFile } from 'node:fs/promises' +import { lstat } from 'node:fs/promises' import * as path from 'node:path' import { isBinaryBuffer } from './binary-buffer' import { decodeGitCQuotedPath } from './git-cquoted-path' import { DEFAULT_GIT_STATUS_LIMIT } from './git-status-limit' +import { iterateNulDelimitedFields } from './nul-delimited-fields' +import { readNodeFileWithinLimit } from './node-bounded-file-reader' export type GitLineStats = { added?: number; removed?: number } @@ -78,9 +80,9 @@ export function parseNumstat(stdout: string): Map { function parseNulDelimitedNumstat(stdout: string): Map { const stats = new Map() - const records = stdout.split('\0') - for (let i = 0; i < records.length; i += 1) { - const record = records[i] + const records = iterateNulDelimitedFields(stdout)[Symbol.iterator]() + for (let next = records.next(); !next.done; next = records.next()) { + const record = next.value if (!record) { continue } @@ -89,9 +91,9 @@ function parseNulDelimitedNumstat(stdout: string): Map { let path = rawPath if (!path) { // Git -z emits rename paths as: "addedremoved\0old\0new\0". - // The split record has an empty path in the header; the postimage is next. - i += 2 - path = records[i] ?? '' + // The empty header path is followed by the preimage and postimage. + records.next() + path = records.next().value ?? '' } if (!path) { continue @@ -127,7 +129,7 @@ async function countFileAdditions(absolutePath: string): Promise { if (!fileStat.isFile() || fileStat.size > MAX_UNTRACKED_LINE_COUNT_BYTES) { return rememberUntrackedStats(absolutePath, fileStat, {}) } - const buffer = await readFile(absolutePath) + const { buffer } = await readNodeFileWithinLimit(absolutePath, MAX_UNTRACKED_LINE_COUNT_BYTES) if (isBinaryBuffer(buffer)) { return rememberUntrackedStats(absolutePath, fileStat, {}) } diff --git a/src/shared/hermes-run-output-limits.test.ts b/src/shared/hermes-run-output-limits.test.ts new file mode 100644 index 000000000..1f583a83c --- /dev/null +++ b/src/shared/hermes-run-output-limits.test.ts @@ -0,0 +1,165 @@ +import { describe, expect, it } from 'vitest' +import { DatabaseSync } from 'node:sqlite' +import { + formatHermesSessionMessagesWithinLimits, + HERMES_RUN_PAGE_OUTPUT_OMITTED_ERROR, + HERMES_SESSION_RUN_METADATA_MAX_BYTES, + HERMES_SESSION_RUN_SELECT_SQL, + HERMES_SESSION_TRANSCRIPT_TRUNCATED_ERROR, + hydrateHermesRunPageWithinLimits +} from './hermes-run-output-limits' + +describe('HERMES_SESSION_RUN_SELECT_SQL', () => { + it('preserves exact-limit text metadata and rejects oversized non-numeric fields in SQL', () => { + const database = new DatabaseSync(':memory:') + database.exec(`CREATE TABLE sessions ( + id TEXT PRIMARY KEY, + title TEXT, + started_at, + ended_at, + model TEXT, + message_count, + input_tokens, + output_tokens + )`) + const exactTitle = 't'.repeat(HERMES_SESSION_RUN_METADATA_MAX_BYTES) + const exactModel = 'm'.repeat(HERMES_SESSION_RUN_METADATA_MAX_BYTES) + database + .prepare( + `INSERT INTO sessions ( + id, title, started_at, ended_at, model, message_count, input_tokens, output_tokens + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)` + ) + .run('run-1', exactTitle, 1, 2, exactModel, 3, 4, 5) + + const exact = database.prepare(HERMES_SESSION_RUN_SELECT_SQL).get('run-1') + expect(exact).toEqual({ + title: exactTitle, + started_at: 1, + ended_at: 2, + model: exactModel, + message_count: 3, + input_tokens: 4, + output_tokens: 5 + }) + + database.exec(`UPDATE sessions SET + title = title || 'overflow', + model = model || 'overflow', + started_at = zeroblob(1048576), + ended_at = zeroblob(1048576), + message_count = zeroblob(1048576), + input_tokens = zeroblob(1048576), + output_tokens = zeroblob(1048576) + WHERE id = 'run-1'`) + const bounded = database.prepare(HERMES_SESSION_RUN_SELECT_SQL).get('run-1') + + expect(Buffer.byteLength(String(bounded?.title))).toBe(HERMES_SESSION_RUN_METADATA_MAX_BYTES) + expect(Buffer.byteLength(String(bounded?.model))).toBe(HERMES_SESSION_RUN_METADATA_MAX_BYTES) + expect(bounded).toMatchObject({ + started_at: null, + ended_at: null, + message_count: null, + input_tokens: null, + output_tokens: null + }) + database.close() + }) +}) + +describe('formatHermesSessionMessagesWithinLimits', () => { + it('preserves transcript formatting below the limits', () => { + const result = formatHermesSessionMessagesWithinLimits([ + { + role: 'assistant', + tool_name: ' terminal ', + reasoning_content: ' because ', + content: ' done ' + }, + { role: null, content: ' ' } + ]) + + expect(result).toEqual({ + content: [ + '## assistant / terminal', + '', + '### Reasoning', + '', + 'because', + '', + 'done', + '', + '---', + '', + '## message', + '', + '(empty)' + ].join('\n'), + truncated: false + }) + }) + + it('keeps UTF-8 output within the byte budget and explains truncation', () => { + const result = formatHermesSessionMessagesWithinLimits( + [{ role: 'assistant', content: '🐋'.repeat(100) }], + { maxBytes: 160 } + ) + + expect(result.truncated).toBe(true) + expect(Buffer.byteLength(result.content ?? '')).toBeLessThanOrEqual(160) + expect(result.content).toContain(HERMES_SESSION_TRANSCRIPT_TRUNCATED_ERROR) + expect(result.content).not.toContain('\ufffd') + }) + + it('stops pulling rows after the message limit', () => { + let rowsPulled = 0 + function* messages(): Generator> { + for (let index = 0; index < 100; index += 1) { + rowsPulled += 1 + yield { role: 'user', content: `message ${index}` } + } + } + + const result = formatHermesSessionMessagesWithinLimits(messages(), { + maxBytes: 1024, + maxMessages: 2 + }) + + expect(rowsPulled).toBe(3) + expect(result.truncated).toBe(true) + expect(result.content).toContain('message 0') + expect(result.content).toContain('message 1') + expect(result.content).not.toContain('message 2') + }) +}) + +describe('hydrateHermesRunPageWithinLimits', () => { + it('bounds concurrency, preserves order, and omits aggregate overflow', async () => { + let active = 0 + let maxActive = 0 + const refs = ['first', 'second', 'third', 'fourth'] + + const runs = (await hydrateHermesRunPageWithinLimits( + refs, + async (id) => { + active += 1 + maxActive = Math.max(maxActive, active) + await new Promise((resolve) => setTimeout(resolve, 1)) + active -= 1 + return { id, output_content: id.slice(0, 3) } + }, + { maxConcurrent: 2, maxRetainedBytes: 5 } + )) as { id: string; output_content: string | null; error?: string }[] + + expect(maxActive).toBe(2) + expect(runs.map((run) => run.id)).toEqual(refs) + expect(runs[0]?.output_content).toBe('fir') + expect(runs.slice(1)).toEqual( + refs.slice(1).map((id) => ({ + id, + output_content: null, + error: HERMES_RUN_PAGE_OUTPUT_OMITTED_ERROR + })) + ) + }) +}) diff --git a/src/shared/hermes-run-output-limits.ts b/src/shared/hermes-run-output-limits.ts new file mode 100644 index 000000000..99d16feaf --- /dev/null +++ b/src/shared/hermes-run-output-limits.ts @@ -0,0 +1,254 @@ +export const HERMES_PRIMARY_OUTPUT_MAX_BYTES = 5 * 1024 * 1024 +export const HERMES_SESSION_TRANSCRIPT_MAX_BYTES = 8 * 1024 * 1024 +export const HERMES_SESSION_TRANSCRIPT_MAX_MESSAGES = 10_000 +export const HERMES_RUN_PAGE_MAX_RETAINED_BYTES = 32 * 1024 * 1024 +export const HERMES_RUN_PAGE_MAX_RUNS = 100 +export const HERMES_RUN_HYDRATION_CONCURRENCY = 2 +export const HERMES_SESSION_RUN_METADATA_MAX_BYTES = 16 * 1024 +export const HERMES_RUN_PAGE_OUTPUT_OMITTED_ERROR = + 'Run output omitted because this history page exceeds the memory limit' +export const HERMES_SESSION_TRANSCRIPT_TRUNCATED_ERROR = + 'Session transcript truncated because it exceeds the 8 MiB or 10,000-message history limit' + +const HERMES_SESSION_TRANSCRIPT_FIELD_MAX_BYTES = HERMES_SESSION_TRANSCRIPT_MAX_BYTES + 1 +const HERMES_SESSION_TRANSCRIPT_TRUNCATION_NOTICE = `[${HERMES_SESSION_TRANSCRIPT_TRUNCATED_ERROR}.]` +const HERMES_SESSION_TRANSCRIPT_SOURCE_TRUNCATED_COLUMN = 'orca_source_truncated' + +export const HERMES_SESSION_RUN_SELECT_SQL = `SELECT + CASE WHEN typeof(title) = 'text' + THEN CAST(substr(CAST(title AS BLOB), 1, ${HERMES_SESSION_RUN_METADATA_MAX_BYTES}) AS TEXT) + ELSE NULL END AS title, + CASE WHEN typeof(started_at) IN ('integer', 'real') THEN started_at ELSE NULL END AS started_at, + CASE WHEN typeof(ended_at) IN ('integer', 'real') THEN ended_at ELSE NULL END AS ended_at, + CASE WHEN typeof(model) = 'text' + THEN CAST(substr(CAST(model AS BLOB), 1, ${HERMES_SESSION_RUN_METADATA_MAX_BYTES}) AS TEXT) + ELSE NULL END AS model, + CASE WHEN typeof(message_count) IN ('integer', 'real') THEN message_count ELSE NULL END AS message_count, + CASE WHEN typeof(input_tokens) IN ('integer', 'real') THEN input_tokens ELSE NULL END AS input_tokens, + CASE WHEN typeof(output_tokens) IN ('integer', 'real') THEN output_tokens ELSE NULL END AS output_tokens +FROM sessions +WHERE id = ?` + +export const HERMES_SESSION_TRANSCRIPT_SELECT_SQL = `SELECT + CAST(substr(CAST(role AS BLOB), 1, ${HERMES_SESSION_TRANSCRIPT_FIELD_MAX_BYTES}) AS TEXT) AS role, + CAST(substr(CAST(content AS BLOB), 1, ${HERMES_SESSION_TRANSCRIPT_FIELD_MAX_BYTES}) AS TEXT) AS content, + CAST(substr(CAST(tool_name AS BLOB), 1, ${HERMES_SESSION_TRANSCRIPT_FIELD_MAX_BYTES}) AS TEXT) AS tool_name, + CAST(substr(CAST(reasoning AS BLOB), 1, ${HERMES_SESSION_TRANSCRIPT_FIELD_MAX_BYTES}) AS TEXT) AS reasoning, + CAST(substr(CAST(reasoning_content AS BLOB), 1, ${HERMES_SESSION_TRANSCRIPT_FIELD_MAX_BYTES}) AS TEXT) AS reasoning_content, + CASE WHEN + length(CAST(role AS BLOB)) > ${HERMES_SESSION_TRANSCRIPT_MAX_BYTES} + OR length(CAST(content AS BLOB)) > ${HERMES_SESSION_TRANSCRIPT_MAX_BYTES} + OR length(CAST(tool_name AS BLOB)) > ${HERMES_SESSION_TRANSCRIPT_MAX_BYTES} + OR length(CAST(reasoning AS BLOB)) > ${HERMES_SESSION_TRANSCRIPT_MAX_BYTES} + OR length(CAST(reasoning_content AS BLOB)) > ${HERMES_SESSION_TRANSCRIPT_MAX_BYTES} + THEN 1 ELSE 0 END AS ${HERMES_SESSION_TRANSCRIPT_SOURCE_TRUNCATED_COLUMN} +FROM messages +WHERE session_id = ? +ORDER BY timestamp, id +LIMIT ${HERMES_SESSION_TRANSCRIPT_MAX_MESSAGES + 1}` + +type HermesRunPageLimits = { + maxConcurrent?: number + maxRetainedBytes?: number +} + +type HermesSessionTranscriptLimits = { + maxBytes?: number + maxMessages?: number +} + +export type FormattedHermesSessionMessages = { + content: string | null + truncated: boolean +} + +export async function hydrateHermesRunPageWithinLimits( + refs: readonly T[], + hydrate: (ref: T) => Promise, + limits: HermesRunPageLimits = {} +): Promise { + const maxConcurrent = clampFiniteLimit(limits.maxConcurrent, 1, HERMES_RUN_HYDRATION_CONCURRENCY) + const maxRetainedBytes = clampFiniteLimit( + limits.maxRetainedBytes, + 0, + HERMES_RUN_PAGE_MAX_RETAINED_BYTES + ) + const results: unknown[] = [] + let retainedBytes = 0 + for (let start = 0; start < refs.length; start += maxConcurrent) { + const batch = await Promise.all(refs.slice(start, start + maxConcurrent).map(hydrate)) + for (const run of batch) { + const runBytes = hermesRunOutputByteLength(run) + if (retainedBytes + runBytes <= maxRetainedBytes) { + results.push(run) + retainedBytes += runBytes + } else { + results.push(omitHermesRunOutput(run)) + } + } + } + return results +} + +export function formatHermesSessionMessagesWithinLimits( + messages: Iterable>, + limits: HermesSessionTranscriptLimits = {} +): FormattedHermesSessionMessages { + const maxBytes = clampFiniteLimit(limits.maxBytes, 0, HERMES_SESSION_TRANSCRIPT_MAX_BYTES) + const maxMessages = clampFiniteLimit( + limits.maxMessages, + 0, + HERMES_SESSION_TRANSCRIPT_MAX_MESSAGES + ) + const chunks: string[] = [] + let retainedBytes = 0 + let messageCount = 0 + let truncated = false + + transcript: for (const message of messages) { + if (messageCount >= maxMessages) { + truncated = true + break + } + for (const part of formatHermesSessionMessageParts(message, messageCount > 0)) { + const partBytes = Buffer.byteLength(part) + if (retainedBytes + partBytes <= maxBytes) { + chunks.push(part) + retainedBytes += partBytes + continue + } + const prefix = takeUtf8Prefix(part, maxBytes - retainedBytes) + if (prefix) { + chunks.push(prefix) + retainedBytes += Buffer.byteLength(prefix) + } + truncated = true + break transcript + } + messageCount += 1 + if (message[HERMES_SESSION_TRANSCRIPT_SOURCE_TRUNCATED_COLUMN] === 1) { + truncated = true + break + } + } + + if (truncated) { + appendTranscriptTruncationNotice(chunks, retainedBytes, maxBytes) + } + return { content: chunks.length > 0 ? chunks.join('') : null, truncated } +} + +function clampFiniteLimit(value: number | undefined, minimum: number, maximum: number): number { + if (value === undefined || !Number.isFinite(value)) { + return maximum + } + return Math.max(minimum, Math.min(maximum, Math.floor(value))) +} + +function hermesRunOutputByteLength(run: unknown): number { + if (!run || typeof run !== 'object' || Array.isArray(run)) { + return 0 + } + const content = (run as Record).output_content + return typeof content === 'string' ? Buffer.byteLength(content) : 0 +} + +function formatHermesSessionMessageParts( + message: Record, + includeSeparator: boolean +): string[] { + const role = typeof message.role === 'string' ? message.role : 'message' + const content = typeof message.content === 'string' ? message.content.trim() : '' + const toolName = typeof message.tool_name === 'string' ? message.tool_name.trim() : '' + const reasoning = + typeof message.reasoning_content === 'string' + ? message.reasoning_content.trim() + : typeof message.reasoning === 'string' + ? message.reasoning.trim() + : '' + const parts = [ + includeSeparator ? '\n\n---\n\n' : '', + `## ${role}${toolName ? ` / ${toolName}` : ''}` + ] + if (reasoning) { + parts.push('\n\n### Reasoning\n\n', reasoning) + } + parts.push('\n\n', content || '(empty)') + return parts +} + +function appendTranscriptTruncationNotice( + chunks: string[], + retainedBytes: number, + maxBytes: number +): void { + const separator = chunks.length > 0 ? '\n\n---\n\n' : '' + const notice = `${separator}${HERMES_SESSION_TRANSCRIPT_TRUNCATION_NOTICE}` + const boundedNotice = takeUtf8Prefix(notice, maxBytes) + const noticeBytes = Buffer.byteLength(boundedNotice) + const targetBytes = maxBytes - noticeBytes + trimUtf8Chunks(chunks, retainedBytes, targetBytes) + if (boundedNotice) { + chunks.push(boundedNotice) + } +} + +function trimUtf8Chunks(chunks: string[], retainedBytes: number, targetBytes: number): void { + let bytes = retainedBytes + while (bytes > targetBytes && chunks.length > 0) { + const lastIndex = chunks.length - 1 + const last = chunks[lastIndex]! + const lastBytes = Buffer.byteLength(last) + const allowedBytes = Math.max(0, lastBytes - (bytes - targetBytes)) + if (allowedBytes === 0) { + chunks.pop() + bytes -= lastBytes + continue + } + const prefix = takeUtf8Prefix(last, allowedBytes) + chunks[lastIndex] = prefix + bytes = bytes - lastBytes + Buffer.byteLength(prefix) + } +} + +function takeUtf8Prefix(value: string, maxBytes: number): string { + if (maxBytes <= 0) { + return '' + } + if (Buffer.byteLength(value) <= maxBytes) { + return value + } + let low = 0 + let high = Math.min(value.length, maxBytes) + while (low < high) { + const middle = Math.ceil((low + high) / 2) + if (Buffer.byteLength(value.slice(0, middle)) <= maxBytes) { + low = middle + } else { + high = middle - 1 + } + } + if (low > 0 && isHighSurrogate(value.charCodeAt(low - 1))) { + low -= 1 + } + return value.slice(0, low) +} + +function isHighSurrogate(code: number): boolean { + return code >= 0xd800 && code <= 0xdbff +} + +function omitHermesRunOutput(run: unknown): unknown { + if (!run || typeof run !== 'object' || Array.isArray(run)) { + return { output_content: null, error: HERMES_RUN_PAGE_OUTPUT_OMITTED_ERROR } + } + const record = run as Record + const existingError = typeof record.error === 'string' && record.error ? record.error : null + return { + ...record, + output_content: null, + error: existingError + ? `${existingError}; ${HERMES_RUN_PAGE_OUTPUT_OMITTED_ERROR}` + : HERMES_RUN_PAGE_OUTPUT_OMITTED_ERROR + } +} diff --git a/src/shared/hermes-run-ref-retention.test.ts b/src/shared/hermes-run-ref-retention.test.ts new file mode 100644 index 000000000..669d41bda --- /dev/null +++ b/src/shared/hermes-run-ref-retention.test.ts @@ -0,0 +1,36 @@ +import { describe, expect, it } from 'vitest' +import { HermesRunRefRetainer } from './hermes-run-ref-retention' + +describe('HermesRunRefRetainer', () => { + it('preserves every ref and exact order below the limit', () => { + const retainer = new HermesRunRefRetainer<{ id: string; run_at: string }>(3) + retainer.add({ id: 'middle', run_at: '2026-05-15T09:00:00Z' }) + retainer.add({ id: 'newest', run_at: '2026-05-16T09:00:00Z' }) + retainer.add({ id: 'oldest', run_at: '2026-05-14T09:00:00Z' }) + + expect(retainer.finish()).toEqual({ + refs: [ + { id: 'newest', run_at: '2026-05-16T09:00:00Z' }, + { id: 'middle', run_at: '2026-05-15T09:00:00Z' }, + { id: 'oldest', run_at: '2026-05-14T09:00:00Z' } + ], + saturated: false + }) + }) + + it('retains the exact newest window and reports saturation', () => { + const retainer = new HermesRunRefRetainer<{ id: string; run_at: string }>(3) + for (const day of [1, 5, 2, 6, 3, 4]) { + retainer.add({ id: `day-${day}`, run_at: `2026-05-0${day}T09:00:00Z` }) + } + + expect(retainer.finish()).toEqual({ + refs: [ + { id: 'day-6', run_at: '2026-05-06T09:00:00Z' }, + { id: 'day-5', run_at: '2026-05-05T09:00:00Z' }, + { id: 'day-4', run_at: '2026-05-04T09:00:00Z' } + ], + saturated: true + }) + }) +}) diff --git a/src/shared/hermes-run-ref-retention.ts b/src/shared/hermes-run-ref-retention.ts new file mode 100644 index 000000000..15aaefe3b --- /dev/null +++ b/src/shared/hermes-run-ref-retention.ts @@ -0,0 +1,78 @@ +export const HERMES_RUN_REF_MAX_ENTRIES = 10_000 +export const HERMES_RUN_REF_ID_MAX_BYTES = 4 * 1024 + +export const HERMES_SESSION_RUN_REFS_SELECT_SQL = `SELECT + CASE WHEN length(CAST(id AS BLOB)) <= ${HERMES_RUN_REF_ID_MAX_BYTES} THEN id ELSE NULL END AS id, + CASE WHEN typeof(started_at) IN ('integer', 'real') THEN started_at ELSE NULL END AS started_at +FROM sessions +WHERE id LIKE ? ESCAPE '\\' +ORDER BY started_at DESC +LIMIT ${HERMES_RUN_REF_MAX_ENTRIES + 1}` + +export type HermesSortableRunRef = { + id: string + run_at: string | null +} + +export type BoundedHermesRunRefs = { + refs: T[] + saturated: boolean +} + +export class HermesRunRefRetainer { + private readonly retained: T[] = [] + private readonly pending: T[] = [] + private readonly maxEntries: number + private seen = 0 + + constructor(maxEntries = HERMES_RUN_REF_MAX_ENTRIES) { + this.maxEntries = Number.isFinite(maxEntries) + ? Math.max(0, Math.min(HERMES_RUN_REF_MAX_ENTRIES, Math.floor(maxEntries))) + : HERMES_RUN_REF_MAX_ENTRIES + } + + add(ref: T): void { + this.seen += 1 + if (this.maxEntries === 0) { + return + } + this.pending.push(ref) + if (this.pending.length >= this.maxEntries) { + this.flush() + } + } + + finish(): BoundedHermesRunRefs { + this.flush() + return { + refs: this.retained.slice(), + saturated: this.seen > this.maxEntries + } + } + + private flush(): void { + if (this.pending.length === 0) { + return + } + for (const ref of this.pending) { + this.retained.push(ref) + } + this.pending.length = 0 + this.retained.sort(compareHermesRunRefsNewestFirst) + if (this.retained.length > this.maxEntries) { + this.retained.length = this.maxEntries + } + } +} + +export function compareHermesRunRefsNewestFirst( + left: HermesSortableRunRef, + right: HermesSortableRunRef +): number { + const leftTime = left.run_at ? Date.parse(left.run_at) : Number.NaN + const rightTime = right.run_at ? Date.parse(right.run_at) : Number.NaN + if (Number.isFinite(leftTime) && Number.isFinite(rightTime)) { + return rightTime - leftTime + } + return right.id.localeCompare(left.id) +} diff --git a/src/shared/image-data-uri.test.ts b/src/shared/image-data-uri.test.ts index 8244d2d65..46a912659 100644 --- a/src/shared/image-data-uri.test.ts +++ b/src/shared/image-data-uri.test.ts @@ -1,15 +1,26 @@ import { describe, expect, it } from 'vitest' -import { buildImageDataUri } from './image-data-uri' +import { buildImageDataUri, validateRasterImageDataUri } from './image-data-uri' + +function pngBase64(width = 1, height = 1): string { + const bytes = Buffer.alloc(24) + Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]).copy(bytes) + bytes.writeUInt32BE(13, 8) + bytes.write('IHDR', 12, 'ascii') + bytes.writeUInt32BE(width, 16) + bytes.writeUInt32BE(height, 20) + return bytes.toString('base64') +} describe('buildImageDataUri', () => { it('builds a data URI from base64 image bytes', () => { - expect(buildImageDataUri('image/png', 'bmV3')).toBe('data:image/png;base64,bmV3') + const content = pngBase64() + expect(buildImageDataUri('image/png', content)).toBe(`data:image/png;base64,${content}`) }) it('strips whitespace from line-wrapped base64 payloads', () => { - expect(buildImageDataUri('image/png', 'bm\nV3\t bmV3\r\n')).toBe( - 'data:image/png;base64,bmV3bmV3' - ) + const content = pngBase64() + const wrapped = `${content.slice(0, 8)}\n${content.slice(8, 20)}\t ${content.slice(20)}\r\n` + expect(buildImageDataUri('image/png', wrapped)).toBe(`data:image/png;base64,${content}`) }) it('returns null for an empty payload', () => { @@ -27,4 +38,31 @@ describe('buildImageDataUri', () => { it('returns null for a non-image mime such as application/octet-stream', () => { expect(buildImageDataUri('application/octet-stream', 'AAAA')).toBeNull() }) + + it('rejects malformed and oversized known rasters before native decode', () => { + expect(buildImageDataUri('image/png', 'bmV3')).toBeNull() + expect(buildImageDataUri('image/png', pngBase64(32_769, 1))).toBeNull() + expect(buildImageDataUri('image/png', pngBase64(8192, 8192))).toBeNull() + }) + + it('preserves SVG behavior because vectors do not have encoded raster dimensions', () => { + expect(buildImageDataUri('image/svg+xml', 'PHN2Zy8+')).toBe( + 'data:image/svg+xml;base64,PHN2Zy8+' + ) + }) +}) + +describe('validateRasterImageDataUri', () => { + it('accepts a safe inline raster and rejects an oversized one', () => { + const safe = `data:image/png;base64,${pngBase64()}` + expect(validateRasterImageDataUri(safe)).toBe(safe) + expect(validateRasterImageDataUri(`data:image/png;base64,${pngBase64(32_769, 1)}`)).toBeNull() + }) + + it('preserves non-raster data URIs and rejects non-base64 raster data', () => { + expect(validateRasterImageDataUri('data:image/svg+xml,%3Csvg/%3E')).toBe( + 'data:image/svg+xml,%3Csvg/%3E' + ) + expect(validateRasterImageDataUri('data:image/png,not-base64')).toBeNull() + }) }) diff --git a/src/shared/image-data-uri.ts b/src/shared/image-data-uri.ts index 150147356..e8d5f66c6 100644 --- a/src/shared/image-data-uri.ts +++ b/src/shared/image-data-uri.ts @@ -1,3 +1,6 @@ +import { readRasterImagePreviewDimensionsFromBase64 } from './raster-image-base64-preview' +import { isKnownRasterImageMimeType } from './raster-image-preview-limits' + // Builds an inline `data:` URI for base64 image bytes, shared by the desktop // editor ImageViewer and the mobile file preview so both decode images the same // way. Strips whitespace from the payload (base64 from git diffs and SSH streams @@ -16,5 +19,21 @@ export function buildImageDataUri( if (!cleaned) { return null } + if (readRasterImagePreviewDimensionsFromBase64(cleaned, mimeType) === null) { + return null + } return `data:${mimeType};base64,${cleaned}` } + +/** Preserves non-raster data URIs and rejects unsafe known-raster data URIs. */ +export function validateRasterImageDataUri(dataUri: string): string | null { + const match = /^data:([^;,]+)((?:;[^,]*)*),([\s\S]*)$/i.exec(dataUri) + if (!match || !isKnownRasterImageMimeType(match[1])) { + return dataUri + } + const parameters = match[2].split(';').filter(Boolean) + if (!parameters.some((parameter) => parameter.toLowerCase() === 'base64')) { + return null + } + return buildImageDataUri(match[1], match[3]) +} diff --git a/src/shared/in-flight-promise-dedupe.test.ts b/src/shared/in-flight-promise-dedupe.test.ts index fcc1005a5..96f36ec69 100644 --- a/src/shared/in-flight-promise-dedupe.test.ts +++ b/src/shared/in-flight-promise-dedupe.test.ts @@ -1,5 +1,18 @@ import { describe, expect, it, vi } from 'vitest' -import { InFlightPromiseDedupe, stableInFlightKey } from './in-flight-promise-dedupe' +import { + InFlightPromiseDedupe, + MAX_IN_FLIGHT_PROMISE_DEDUPE_ENTRIES, + MAX_IN_FLIGHT_PROMISE_DEDUPE_KEY_CODE_UNITS, + stableInFlightKey +} from './in-flight-promise-dedupe' + +function deferred(): { promise: Promise; resolve: (value: T) => void } { + let resolve!: (value: T) => void + const promise = new Promise((nextResolve) => { + resolve = nextResolve + }) + return { promise, resolve } +} describe('InFlightPromiseDedupe', () => { it('coalesces only while in flight and retries after rejection', async () => { @@ -80,4 +93,72 @@ describe('InFlightPromiseDedupe', () => { vi.useRealTimers() } }) + + it('admits exactly the entry limit and bypasses new keys above it', async () => { + const dedupe = new InFlightPromiseDedupe() + const pending = Array.from({ length: MAX_IN_FLIGHT_PROMISE_DEDUPE_ENTRIES }, () => + deferred() + ) + const admittedLoads = pending.map((item) => vi.fn(() => item.promise)) + + for (let index = 0; index < pending.length; index += 1) { + const first = dedupe.run(`key-${index}`, admittedLoads[index]) + const second = dedupe.run(`key-${index}`, admittedLoads[index]) + expect(second).toBe(first) + } + + const overflowLoad = vi.fn(async () => 'overflow') + const firstOverflow = dedupe.run('overflow', overflowLoad) + const secondOverflow = dedupe.run('overflow', overflowLoad) + expect(secondOverflow).not.toBe(firstOverflow) + await expect(Promise.all([firstOverflow, secondOverflow])).resolves.toEqual([ + 'overflow', + 'overflow' + ]) + expect(overflowLoad).toHaveBeenCalledTimes(2) + + pending.forEach((item) => item.resolve('settled')) + await Promise.all(pending.map((item) => item.promise)) + }) + + it('admits a new key after a retained entry settles', async () => { + const dedupe = new InFlightPromiseDedupe(30_000, 1) + const firstPending = deferred() + const first = dedupe.run('first', () => firstPending.promise) + firstPending.resolve('first-result') + await expect(first).resolves.toBe('first-result') + + const nextPending = deferred() + const load = vi.fn(() => nextPending.promise) + const next = dedupe.run('next', load) + expect(dedupe.run('next', load)).toBe(next) + nextPending.resolve('next-result') + await expect(next).resolves.toBe('next-result') + expect(load).toHaveBeenCalledTimes(1) + }) + + it('keeps stable keys inline through the size limit and digests larger keys', () => { + const exactInput = 'x'.repeat(MAX_IN_FLIGHT_PROMISE_DEDUPE_KEY_CODE_UNITS - 4) + const oversizedInput = `${exactInput}x` + + expect(stableInFlightKey([exactInput])).toBe(JSON.stringify([exactInput])) + const firstDigest = stableInFlightKey([oversizedInput]) + expect(firstDigest).toMatch(/^sha256:[a-f0-9]{64}$/) + expect(stableInFlightKey([oversizedInput])).toBe(firstDigest) + expect(stableInFlightKey([`${oversizedInput}x`])).not.toBe(firstDigest) + }) + + it('coalesces direct oversized keys through their bounded identity', async () => { + const dedupe = new InFlightPromiseDedupe() + const pending = deferred() + const load = vi.fn(() => pending.promise) + const oversizedKey = 'x'.repeat(MAX_IN_FLIGHT_PROMISE_DEDUPE_KEY_CODE_UNITS + 1) + + const first = dedupe.run(oversizedKey, load) + expect(dedupe.run(oversizedKey, load)).toBe(first) + pending.resolve('result') + + await expect(first).resolves.toBe('result') + expect(load).toHaveBeenCalledTimes(1) + }) }) diff --git a/src/shared/in-flight-promise-dedupe.ts b/src/shared/in-flight-promise-dedupe.ts index 0ad90f372..a66420cbb 100644 --- a/src/shared/in-flight-promise-dedupe.ts +++ b/src/shared/in-flight-promise-dedupe.ts @@ -1,28 +1,54 @@ +import { createHash } from 'node:crypto' + +export const MAX_IN_FLIGHT_PROMISE_DEDUPE_ENTRIES = 128 +export const MAX_IN_FLIGHT_PROMISE_DEDUPE_KEY_CODE_UNITS = 64 * 1024 + +function boundInFlightKey(key: string): string { + if (key.length <= MAX_IN_FLIGHT_PROMISE_DEDUPE_KEY_CODE_UNITS) { + return key + } + return `sha256:${createHash('sha256').update(key).digest('hex')}` +} + export class InFlightPromiseDedupe { private readonly entries = new Map< string, { promise: Promise; timeout: ReturnType | null } >() + private readonly maxEntries: number - constructor(private readonly maxInFlightMs = 30_000) {} + constructor( + private readonly maxInFlightMs = 30_000, + maxEntries = MAX_IN_FLIGHT_PROMISE_DEDUPE_ENTRIES + ) { + this.maxEntries = Number.isFinite(maxEntries) + ? Math.min(MAX_IN_FLIGHT_PROMISE_DEDUPE_ENTRIES, Math.max(0, Math.floor(maxEntries))) + : MAX_IN_FLIGHT_PROMISE_DEDUPE_ENTRIES + } run(key: string, load: () => Promise): Promise { - const existing = this.entries.get(key) + const retainedKey = boundInFlightKey(key) + const existing = this.entries.get(retainedKey) if (existing) { return existing.promise } + if (this.entries.size >= this.maxEntries) { + // Why: evicting active work would let later identical calls duplicate it; + // overflow calls still run but cannot extend this object's retention. + return Promise.resolve().then(load) + } // Why: this is in-flight coalescing only; the next read after settle must // observe fresh git state instead of a cached diff. const promise = Promise.resolve() .then(load) .finally(() => { - const entry = this.entries.get(key) + const entry = this.entries.get(retainedKey) if (entry?.promise === promise) { if (entry.timeout) { clearTimeout(entry.timeout) } - this.entries.delete(key) + this.entries.delete(retainedKey) } }) const entry = { @@ -32,13 +58,13 @@ export class InFlightPromiseDedupe { timeout: this.maxInFlightMs > 0 ? setTimeout(() => { - if (this.entries.get(key)?.promise === promise) { - this.entries.delete(key) + if (this.entries.get(retainedKey)?.promise === promise) { + this.entries.delete(retainedKey) } }, this.maxInFlightMs) : null } - this.entries.set(key, entry) + this.entries.set(retainedKey, entry) return promise } @@ -53,5 +79,5 @@ export class InFlightPromiseDedupe { } export function stableInFlightKey(parts: readonly unknown[]): string { - return JSON.stringify(parts) + return boundInFlightKey(JSON.stringify(parts)) } diff --git a/src/shared/linux-proc-port-scan-limits.test.ts b/src/shared/linux-proc-port-scan-limits.test.ts new file mode 100644 index 000000000..9d382c7a3 --- /dev/null +++ b/src/shared/linux-proc-port-scan-limits.test.ts @@ -0,0 +1,52 @@ +import { describe, expect, it, vi } from 'vitest' +import { + createLinuxProcTextReadBudget, + LINUX_PROC_NETWORK_TABLE_MAX_BYTES, + readLinuxProcNetworkTable, + readLinuxProcTextWithinBudget +} from './linux-proc-port-scan-limits' + +describe('Linux proc port scan limits', () => { + it('applies the network-table byte cap before retaining content', async () => { + const readFile = vi.fn(async () => Buffer.from('table')) + + await expect(readLinuxProcNetworkTable('/proc/net/tcp', readFile)).resolves.toBe('table') + expect(readFile).toHaveBeenCalledWith('/proc/net/tcp', LINUX_PROC_NETWORK_TABLE_MAX_BYTES) + }) + + it('shares one retained-byte budget across process metadata files', async () => { + const budget = createLinuxProcTextReadBudget(5) + const readFile = vi + .fn<(filePath: string, maxBytes: number) => Promise>() + .mockResolvedValueOnce(Buffer.from('abc')) + .mockResolvedValueOnce(Buffer.from('de')) + + await expect(readLinuxProcTextWithinBudget('/proc/1/comm', budget, readFile, 4)).resolves.toBe( + 'abc' + ) + await expect( + readLinuxProcTextWithinBudget('/proc/1/cmdline', budget, readFile, 4) + ).resolves.toBe('de') + await expect( + readLinuxProcTextWithinBudget('/proc/2/cmdline', budget, readFile, 4) + ).resolves.toBeUndefined() + + expect(readFile.mock.calls).toEqual([ + ['/proc/1/comm', 4], + ['/proc/1/cmdline', 2] + ]) + expect(budget.remainingBytes).toBe(0) + }) + + it('does not debit failed metadata reads', async () => { + const budget = createLinuxProcTextReadBudget(4) + const readFile = vi.fn(async () => { + throw new Error('oversized') + }) + + await expect( + readLinuxProcTextWithinBudget('/proc/1/cmdline', budget, readFile) + ).resolves.toBeUndefined() + expect(budget.remainingBytes).toBe(4) + }) +}) diff --git a/src/shared/linux-proc-port-scan-limits.ts b/src/shared/linux-proc-port-scan-limits.ts new file mode 100644 index 000000000..dd1f9fd5c --- /dev/null +++ b/src/shared/linux-proc-port-scan-limits.ts @@ -0,0 +1,55 @@ +import { readNodeFileWithinLimit } from './node-bounded-file-reader' + +export const LINUX_PROC_NETWORK_TABLE_MAX_BYTES = 8 * 1024 * 1024 +export const LINUX_PROC_LISTENING_SOCKET_MAX_ENTRIES = 2_048 +export const LINUX_PROC_PROCESS_METADATA_MAX_BYTES = 8 * 1024 * 1024 +export const LINUX_PROC_PROCESS_METADATA_FILE_MAX_BYTES = 64 * 1024 + +export type LinuxProcTextReadBudget = { remainingBytes: number } + +type LinuxProcTextReader = (filePath: string, maxBytes: number) => Promise + +const readBoundedNodeFile: LinuxProcTextReader = async (filePath, maxBytes) => + (await readNodeFileWithinLimit(filePath, maxBytes)).buffer + +export function createLinuxProcTextReadBudget( + maxBytes = LINUX_PROC_PROCESS_METADATA_MAX_BYTES +): LinuxProcTextReadBudget { + if (!Number.isSafeInteger(maxBytes) || maxBytes < 0) { + throw new RangeError('Linux proc text budget must be a non-negative safe integer') + } + return { remainingBytes: maxBytes } +} + +export async function readLinuxProcNetworkTable( + filePath: string, + readFile: LinuxProcTextReader = readBoundedNodeFile +): Promise { + try { + return (await readFile(filePath, LINUX_PROC_NETWORK_TABLE_MAX_BYTES)).toString('utf8') + } catch { + return null + } +} + +export async function readLinuxProcTextWithinBudget( + filePath: string, + budget: LinuxProcTextReadBudget, + readFile: LinuxProcTextReader = readBoundedNodeFile, + perFileMaxBytes = LINUX_PROC_PROCESS_METADATA_FILE_MAX_BYTES +): Promise { + const maxBytes = Math.min(perFileMaxBytes, budget.remainingBytes) + if (maxBytes <= 0) { + return undefined + } + try { + const content = await readFile(filePath, maxBytes) + if (content.byteLength > maxBytes) { + return undefined + } + budget.remainingBytes -= content.byteLength + return content.toString('utf8') + } catch { + return undefined + } +} diff --git a/src/shared/linux-proc-socket-owner-scanner.test.ts b/src/shared/linux-proc-socket-owner-scanner.test.ts new file mode 100644 index 000000000..a29953902 --- /dev/null +++ b/src/shared/linux-proc-socket-owner-scanner.test.ts @@ -0,0 +1,59 @@ +import { describe, expect, it } from 'vitest' +import { mapLinuxSocketInodesToPids } from './linux-proc-socket-owner-scanner' + +async function* names(values: readonly string[]): AsyncGenerator { + yield* values +} + +describe('mapLinuxSocketInodesToPids', () => { + it('streams process and descriptor directories while preserving owner resolution', async () => { + const visitedDirectories: string[] = [] + const result = await mapLinuxSocketInodesToPids(new Set([101, 202]), { + readDirectoryNames: (directoryPath) => { + visitedDirectories.push(directoryPath) + if (directoryPath === '/proc') { + return names(['self', '41', '42']) + } + return names(directoryPath.endsWith('/41/fd') ? ['1', '2'] : ['3']) + }, + readLink: async (filePath) => { + if (filePath.endsWith('/41/fd/1')) { + return 'socket:[101]' + } + if (filePath.endsWith('/42/fd/3')) { + return 'socket:[202]' + } + return 'pipe:[9]' + } + }) + + expect(result).toEqual( + new Map([ + [101, 41], + [202, 42] + ]) + ) + expect(visitedDirectories).toEqual(['/proc', '/proc/41/fd', '/proc/42/fd']) + }) + + it('does not retain an arbitrarily large process-name listing', async () => { + let yielded = 0 + const result = await mapLinuxSocketInodesToPids(new Set([7]), { + readDirectoryNames: (directoryPath) => { + if (directoryPath !== '/proc') { + return names([]) + } + return (async function* () { + for (let pid = 1; pid <= 20_000; pid += 1) { + yielded += 1 + yield String(pid) + } + })() + }, + readLink: async () => 'socket:[7]' + }) + + expect(yielded).toBe(20_000) + expect(result.size).toBe(0) + }) +}) diff --git a/src/shared/linux-proc-socket-owner-scanner.ts b/src/shared/linux-proc-socket-owner-scanner.ts new file mode 100644 index 000000000..43b8cd808 --- /dev/null +++ b/src/shared/linux-proc-socket-owner-scanner.ts @@ -0,0 +1,64 @@ +import { opendir, readlink } from 'node:fs/promises' +import { posix } from 'node:path' + +type LinuxProcSocketOwnerScannerDependencies = { + readDirectoryNames: (directoryPath: string) => AsyncIterable + readLink: (filePath: string) => Promise +} + +async function* readNodeDirectoryNames(directoryPath: string): AsyncGenerator { + try { + const directory = await opendir(directoryPath) + for await (const entry of directory) { + yield entry.name + } + } catch {} +} + +const defaultDependencies: LinuxProcSocketOwnerScannerDependencies = { + readDirectoryNames: readNodeDirectoryNames, + readLink: readlink +} + +export async function mapLinuxSocketInodesToPids( + inodes: ReadonlySet, + dependencies: LinuxProcSocketOwnerScannerDependencies = defaultDependencies +): Promise> { + const result = new Map() + if (inodes.size === 0) { + return result + } + + try { + for await (const pidText of dependencies.readDirectoryNames('/proc')) { + if (!/^\d+$/.test(pidText)) { + continue + } + const pid = Number.parseInt(pidText, 10) + const fdDirectory = posix.join('/proc', pidText, 'fd') + try { + for await (const fd of dependencies.readDirectoryNames(fdDirectory)) { + let link: string + try { + link = await dependencies.readLink(posix.join(fdDirectory, fd)) + } catch { + continue + } + const match = /^socket:\[(\d+)\]$/.exec(link) + if (!match) { + continue + } + const inode = Number.parseInt(match[1], 10) + if (inodes.has(inode)) { + result.set(inode, pid) + } + } + } catch { + continue + } + } + } catch { + return result + } + return result +} diff --git a/src/shared/map-settled-with-concurrency.test.ts b/src/shared/map-settled-with-concurrency.test.ts new file mode 100644 index 000000000..506d7a4d3 --- /dev/null +++ b/src/shared/map-settled-with-concurrency.test.ts @@ -0,0 +1,35 @@ +import { describe, expect, it } from 'vitest' +import { mapSettledWithConcurrency } from './map-with-concurrency' + +describe('mapSettledWithConcurrency', () => { + it('preserves all-settled results and order while bounding a large fanout', async () => { + const limit = 7 + const items = Array.from({ length: 1_000 }, (_, index) => index) + let inFlight = 0 + let peak = 0 + + const results = await mapSettledWithConcurrency(items, limit, async (item) => { + inFlight += 1 + peak = Math.max(peak, inFlight) + await Promise.resolve() + for (let turn = 0; turn < item % 5; turn += 1) { + await Promise.resolve() + } + inFlight -= 1 + if (item % 97 === 0) { + throw `rejected-${item}` + } + return `fulfilled-${item}` + }) + + expect(peak).toBe(limit) + expect(results).toEqual( + items.map( + (item): PromiseSettledResult => + item % 97 === 0 + ? { status: 'rejected', reason: `rejected-${item}` } + : { status: 'fulfilled', value: `fulfilled-${item}` } + ) + ) + }) +}) diff --git a/src/shared/markdown-document-listing-limits.test.ts b/src/shared/markdown-document-listing-limits.test.ts new file mode 100644 index 000000000..574e146b4 --- /dev/null +++ b/src/shared/markdown-document-listing-limits.test.ts @@ -0,0 +1,83 @@ +import { describe, expect, it } from 'vitest' +import type { MarkdownDocument } from './types' +import { + assertMarkdownDocumentsWithinLimit, + createMarkdownDocumentListingBudget, + isMarkdownDocumentListingCapacityError, + MARKDOWN_DOCUMENT_LISTING_ERROR_CODE, + MARKDOWN_DOCUMENT_LISTING_ERROR_MESSAGE, + MarkdownDocumentListingCapacityError, + retainMarkdownDocument, + visitMarkdownDocumentListingEntry +} from './markdown-document-listing-limits' + +function document(path: string): MarkdownDocument { + return { + filePath: `/repo/${path}`, + relativePath: path, + basename: path, + name: path + } +} + +describe('Markdown document listing limits', () => { + it('preserves an under-limit listing and reports its retained estimate', () => { + const documents = [document('README.md'), document('docs/guide.mdx')] + + expect(assertMarkdownDocumentsWithinLimit(documents)).toBeGreaterThan(0) + }) + + it('rejects the first document beyond the count limit with a typed error', () => { + const budget = createMarkdownDocumentListingBudget({ maxDocuments: 2 }) + retainMarkdownDocument(budget, document('one.md')) + retainMarkdownDocument(budget, document('two.md')) + + expect(() => retainMarkdownDocument(budget, document('three.md'))).toThrow( + MarkdownDocumentListingCapacityError + ) + expect(() => retainMarkdownDocument(budget, document('three.md'))).toThrow( + expect.objectContaining({ code: MARKDOWN_DOCUMENT_LISTING_ERROR_CODE }) + ) + }) + + it('rejects aggregate metadata, visited-entry, path, and depth overflow', () => { + expect(() => + assertMarkdownDocumentsWithinLimit([document('a'.repeat(100))], { + maxMetadataBytes: 100 + }) + ).toThrow(MarkdownDocumentListingCapacityError) + + const visited = createMarkdownDocumentListingBudget({ + maxVisitedEntries: 1, + maxPathBytes: 4, + maxDepth: 1 + }) + visitMarkdownDocumentListingEntry(visited, 'a', 1) + expect(() => visitMarkdownDocumentListingEntry(visited, 'b', 1)).toThrow( + MarkdownDocumentListingCapacityError + ) + + const path = createMarkdownDocumentListingBudget({ maxPathBytes: 4 }) + expect(() => visitMarkdownDocumentListingEntry(path, 'ééé', 1)).toThrow( + MarkdownDocumentListingCapacityError + ) + + const depth = createMarkdownDocumentListingBudget({ maxDepth: 1 }) + expect(() => visitMarkdownDocumentListingEntry(depth, 'a/b', 2)).toThrow( + MarkdownDocumentListingCapacityError + ) + }) + + it('recognizes structured runtime and Electron-wrapped capacity failures', () => { + const structured = Object.assign(new Error('remote listing rejected'), { + code: MARKDOWN_DOCUMENT_LISTING_ERROR_CODE + }) + const electronWrapped = new Error( + `Error invoking remote method 'fs:listMarkdownDocuments': Error: ${MARKDOWN_DOCUMENT_LISTING_ERROR_MESSAGE}` + ) + + expect(isMarkdownDocumentListingCapacityError(structured)).toBe(true) + expect(isMarkdownDocumentListingCapacityError(electronWrapped)).toBe(true) + expect(isMarkdownDocumentListingCapacityError(new Error('unrelated failure'))).toBe(false) + }) +}) diff --git a/src/shared/markdown-document-listing-limits.ts b/src/shared/markdown-document-listing-limits.ts new file mode 100644 index 000000000..9c9b39c49 --- /dev/null +++ b/src/shared/markdown-document-listing-limits.ts @@ -0,0 +1,170 @@ +import type { MarkdownDocument } from './types' +import { measureUtf8ByteLength } from './utf8-byte-limits' + +export const MARKDOWN_DOCUMENT_LISTING_MAX_DOCUMENTS = 20_000 +export const MARKDOWN_DOCUMENT_LISTING_MAX_METADATA_BYTES = 8 * 1024 * 1024 +export const MARKDOWN_DOCUMENT_LISTING_MAX_PATH_BYTES = 64 * 1024 +export const MARKDOWN_DOCUMENT_LISTING_MAX_VISITED_ENTRIES = 100_000 +export const MARKDOWN_DOCUMENT_LISTING_MAX_DEPTH = 256 +export const MARKDOWN_DOCUMENT_LISTING_ERROR_CODE = 'markdown_document_listing_capacity' +export const MARKDOWN_DOCUMENT_LISTING_ERROR_MESSAGE = + 'Workspace is too large for Markdown link completion.' + +const MARKDOWN_DOCUMENT_RETAINED_OVERHEAD_BYTES = 256 + +export type MarkdownDocumentListingLimits = { + maxDocuments: number + maxMetadataBytes: number + maxPathBytes: number + maxVisitedEntries: number + maxDepth: number +} + +export type MarkdownDocumentListingBudget = { + documents: number + metadataBytes: number + visitedEntries: number + limits: MarkdownDocumentListingLimits +} + +export class MarkdownDocumentListingCapacityError extends Error { + readonly code = MARKDOWN_DOCUMENT_LISTING_ERROR_CODE + + constructor() { + super(MARKDOWN_DOCUMENT_LISTING_ERROR_MESSAGE) + this.name = 'MarkdownDocumentListingCapacityError' + } +} + +export function isMarkdownDocumentListingCapacityError(error: unknown): boolean { + if (!(error instanceof Error)) { + return false + } + return ( + ('code' in error && + (error as { code?: unknown }).code === MARKDOWN_DOCUMENT_LISTING_ERROR_CODE) || + error.message.includes(MARKDOWN_DOCUMENT_LISTING_ERROR_MESSAGE) + ) +} + +export function createMarkdownDocumentListingBudget( + requested: Partial = {} +): MarkdownDocumentListingBudget { + return { + documents: 0, + metadataBytes: 0, + visitedEntries: 0, + limits: { + maxDocuments: clampLimit(requested.maxDocuments, MARKDOWN_DOCUMENT_LISTING_MAX_DOCUMENTS), + maxMetadataBytes: clampLimit( + requested.maxMetadataBytes, + MARKDOWN_DOCUMENT_LISTING_MAX_METADATA_BYTES + ), + maxPathBytes: clampLimit(requested.maxPathBytes, MARKDOWN_DOCUMENT_LISTING_MAX_PATH_BYTES), + maxVisitedEntries: clampLimit( + requested.maxVisitedEntries, + MARKDOWN_DOCUMENT_LISTING_MAX_VISITED_ENTRIES + ), + maxDepth: clampLimit(requested.maxDepth, MARKDOWN_DOCUMENT_LISTING_MAX_DEPTH) + } + } +} + +export function assertMarkdownDocumentPathWithinLimit( + path: string, + maxPathBytes = MARKDOWN_DOCUMENT_LISTING_MAX_PATH_BYTES +): void { + if (measureUtf8ByteLength(path, { stopAfterBytes: maxPathBytes }).exceededLimit) { + throw new MarkdownDocumentListingCapacityError() + } +} + +export function visitMarkdownDocumentListingEntry( + budget: MarkdownDocumentListingBudget, + path: string, + depth: number +): void { + assertMarkdownDocumentPathWithinLimit(path, budget.limits.maxPathBytes) + if (budget.visitedEntries >= budget.limits.maxVisitedEntries || depth > budget.limits.maxDepth) { + throw new MarkdownDocumentListingCapacityError() + } + budget.visitedEntries += 1 +} + +export function estimateMarkdownDocumentRetainedBytes(document: MarkdownDocument): number { + return ( + (document.filePath.length + + document.relativePath.length + + document.basename.length + + document.name.length) * + 2 + + MARKDOWN_DOCUMENT_RETAINED_OVERHEAD_BYTES + ) +} + +export function retainMarkdownDocument( + budget: MarkdownDocumentListingBudget, + document: MarkdownDocument +): void { + if ( + !document || + typeof document.filePath !== 'string' || + typeof document.relativePath !== 'string' || + typeof document.basename !== 'string' || + typeof document.name !== 'string' + ) { + throw new MarkdownDocumentListingCapacityError() + } + assertMarkdownDocumentPathWithinLimit(document.filePath, budget.limits.maxPathBytes) + assertMarkdownDocumentPathWithinLimit(document.relativePath, budget.limits.maxPathBytes) + const retainedBytes = estimateMarkdownDocumentRetainedBytes(document) + if ( + budget.documents >= budget.limits.maxDocuments || + budget.metadataBytes + retainedBytes > budget.limits.maxMetadataBytes + ) { + throw new MarkdownDocumentListingCapacityError() + } + budget.documents += 1 + budget.metadataBytes += retainedBytes +} + +export function retainMarkdownRelativePath( + budget: MarkdownDocumentListingBudget, + rootPath: string, + relativePath: string +): void { + const normalizedRoot = rootPath.replace(/[\\/]+$/, '') + const normalizedRelativePath = relativePath.replaceAll('\\', '/') + const basename = normalizedRelativePath.slice(normalizedRelativePath.lastIndexOf('/') + 1) + const extensionIndex = basename.lastIndexOf('.') + retainMarkdownDocument(budget, { + filePath: `${normalizedRoot}/${normalizedRelativePath}`, + relativePath: normalizedRelativePath, + basename, + name: extensionIndex > 0 ? basename.slice(0, extensionIndex) : basename + }) +} + +export function assertMarkdownDocumentsWithinLimit( + documents: unknown, + requested: Partial = {} +): number { + const budget = createMarkdownDocumentListingBudget(requested) + if (!Array.isArray(documents)) { + throw new MarkdownDocumentListingCapacityError() + } + if (documents.length > budget.limits.maxDocuments) { + throw new MarkdownDocumentListingCapacityError() + } + for (const document of documents) { + retainMarkdownDocument(budget, document as MarkdownDocument) + } + return budget.metadataBytes +} + +function clampLimit(value: number | undefined, maximum: number): number { + if (typeof value !== 'number' || !Number.isSafeInteger(value) || value <= 0) { + return maximum + } + return Math.min(value, maximum) +} diff --git a/src/shared/mcp-config-inspection-limits.ts b/src/shared/mcp-config-inspection-limits.ts new file mode 100644 index 000000000..221a35082 --- /dev/null +++ b/src/shared/mcp-config-inspection-limits.ts @@ -0,0 +1,41 @@ +import { measureUtf8ByteLength } from './utf8-byte-limits' + +export const MCP_CONFIG_INSPECTION_MAX_BYTES = 256 * 1024 +export const MCP_CONFIG_INSPECTION_MAX_CODE_UNITS = 256 * 1024 +export const MCP_CONFIG_INSPECTION_MAX_SERVERS = 256 +export const MCP_CONFIG_INSPECTION_MAX_ENV_FIELDS = 256 +export const MCP_CONFIG_INSPECTION_MAX_NAME_BYTES = 4 * 1024 +export const MCP_CONFIG_INSPECTION_MAX_NAME_CODE_UNITS = 4 * 1024 +export const MCP_CONFIG_INSPECTION_MAX_FIELD_BYTES = 64 * 1024 +export const MCP_CONFIG_INSPECTION_MAX_FIELD_CODE_UNITS = 64 * 1024 + +export function isMcpConfigInspectionTextWithinLimit(content: string): boolean { + return isTextWithinLimits( + content, + MCP_CONFIG_INSPECTION_MAX_BYTES, + MCP_CONFIG_INSPECTION_MAX_CODE_UNITS + ) +} + +export function isMcpConfigInspectionNameWithinLimit(value: string): boolean { + return isTextWithinLimits( + value, + MCP_CONFIG_INSPECTION_MAX_NAME_BYTES, + MCP_CONFIG_INSPECTION_MAX_NAME_CODE_UNITS + ) +} + +export function isMcpConfigInspectionFieldWithinLimit(value: string): boolean { + return isTextWithinLimits( + value, + MCP_CONFIG_INSPECTION_MAX_FIELD_BYTES, + MCP_CONFIG_INSPECTION_MAX_FIELD_CODE_UNITS + ) +} + +function isTextWithinLimits(value: string, maxBytes: number, maxCodeUnits: number): boolean { + return ( + value.length <= maxCodeUnits && + !measureUtf8ByteLength(value, { stopAfterBytes: maxBytes }).exceededLimit + ) +} diff --git a/src/shared/mcp-config.test.ts b/src/shared/mcp-config.test.ts index e16dc9f36..f89d03463 100644 --- a/src/shared/mcp-config.test.ts +++ b/src/shared/mcp-config.test.ts @@ -1,4 +1,4 @@ -import { describe, expect, it } from 'vitest' +import { afterEach, describe, expect, it, vi } from 'vitest' import { canInspectLocalMcpConfigRoot, getMcpConfigCandidateParentDir, @@ -9,6 +9,17 @@ import { MCP_STARTER_CONFIG, selectExistingMcpConfigCandidates } from './mcp-config' +import { + MCP_CONFIG_INSPECTION_MAX_BYTES, + MCP_CONFIG_INSPECTION_MAX_ENV_FIELDS, + MCP_CONFIG_INSPECTION_MAX_FIELD_BYTES, + MCP_CONFIG_INSPECTION_MAX_FIELD_CODE_UNITS, + MCP_CONFIG_INSPECTION_MAX_SERVERS +} from './mcp-config-inspection-limits' + +afterEach(() => { + vi.restoreAllMocks() +}) describe('mcp-config', () => { const workspaceCandidate = MCP_CONFIG_CANDIDATES[0] @@ -141,6 +152,92 @@ describe('mcp-config', () => { }) }) + it('parses the exact input boundary and rejects +1 before JSON parsing', () => { + const parse = vi.spyOn(JSON, 'parse') + const exact = `${' '.repeat(MCP_CONFIG_INSPECTION_MAX_BYTES - 2)}{}` + + expect(inspectMcpConfigContent(workspaceCandidate, exact).status).toBe('valid') + expect(parse).toHaveBeenCalledOnce() + + parse.mockClear() + expect(inspectMcpConfigContent(workspaceCandidate, `${exact} `).status).toBe('invalid') + expect(parse).not.toHaveBeenCalled() + parse.mockRestore() + }) + + it('rejects multibyte input over the byte cap before JSON parsing', () => { + const parse = vi.spyOn(JSON, 'parse') + + expect( + inspectMcpConfigContent( + workspaceCandidate, + 'é'.repeat(MCP_CONFIG_INSPECTION_MAX_BYTES / 2 + 1) + ).status + ).toBe('invalid') + expect(parse).not.toHaveBeenCalled() + parse.mockRestore() + }) + + it('admits the exact server cardinality and rejects +1', () => { + const servers = Object.fromEntries( + Array.from({ length: MCP_CONFIG_INSPECTION_MAX_SERVERS }, (_, index) => [ + `server-${index}`, + { command: 'node' } + ]) + ) + + expect( + inspectMcpConfigContent(workspaceCandidate, JSON.stringify({ mcpServers: servers })).servers + ).toHaveLength(MCP_CONFIG_INSPECTION_MAX_SERVERS) + servers.overflow = { command: 'node' } + expect( + inspectMcpConfigContent(workspaceCandidate, JSON.stringify({ mcpServers: servers })) + ).toMatchObject({ status: 'invalid', servers: [] }) + }) + + it('admits an exact-size command and rejects the field at +1', () => { + const exact = 'x'.repeat(MCP_CONFIG_INSPECTION_MAX_FIELD_CODE_UNITS) + const exactUtf8 = 'é'.repeat(MCP_CONFIG_INSPECTION_MAX_FIELD_BYTES / 2) + const inspectCommand = (command: string) => + inspectMcpConfigContent( + workspaceCandidate, + JSON.stringify({ mcpServers: { bounded: { command } } }) + ).servers[0] + + expect(inspectCommand(exact)).toMatchObject({ status: 'enabled', command: exact }) + expect(inspectCommand(`${exact}x`)).toMatchObject({ + status: 'invalid', + issue: 'Command exceeds the MCP inspection field limit.' + }) + expect(inspectCommand(exactUtf8)).toMatchObject({ status: 'enabled', command: exactUtf8 }) + expect(inspectCommand(`${exactUtf8}é`)).toMatchObject({ + status: 'invalid', + issue: 'Command exceeds the MCP inspection field limit.' + }) + }) + + it('admits the exact env cardinality and rejects +1 without retaining env values', () => { + const env = Object.fromEntries( + Array.from({ length: MCP_CONFIG_INSPECTION_MAX_ENV_FIELDS }, (_, index) => [ + `KEY_${index}`, + 'value' + ]) + ) + const inspectEnv = () => + inspectMcpConfigContent( + workspaceCandidate, + JSON.stringify({ mcpServers: { bounded: { command: 'node', env } } }) + ).servers[0] + + expect(Object.keys(inspectEnv()?.env ?? {})).toHaveLength(MCP_CONFIG_INSPECTION_MAX_ENV_FIELDS) + env.OVERFLOW = 'value' + expect(inspectEnv()).toMatchObject({ + status: 'invalid', + issue: 'Environment exceeds the MCP inspection field limits.' + }) + expect(inspectEnv()?.env).toBeUndefined() + }) + it('plans directory discovery before reading candidate files', () => { expect(getMcpConfigParentDirs()).toEqual(['.cursor', '.claude']) expect( diff --git a/src/shared/mcp-config.ts b/src/shared/mcp-config.ts index 369dd101f..0cc0ce60d 100644 --- a/src/shared/mcp-config.ts +++ b/src/shared/mcp-config.ts @@ -1,3 +1,12 @@ +import { + isMcpConfigInspectionNameWithinLimit, + isMcpConfigInspectionTextWithinLimit, + MCP_CONFIG_INSPECTION_MAX_SERVERS +} from './mcp-config-inspection-limits' +import { summarizeMcpServer } from './mcp-server-inspection' + +export { maskMcpEnv } from './mcp-server-inspection' + export type McpConfigFormat = 'workspace' | 'cursor' | 'claude' export type McpConfigCandidate = { @@ -100,11 +109,6 @@ export function canInspectLocalMcpConfigRoot(rootPath: string, isWindowsHost: bo return !/^(?:[A-Za-z]:[\\/]|[\\/]{2}[^\\/]+[\\/][^\\/]+)/.test(rootPath) } -const SENSITIVE_ENV_KEY_PATTERN = - /(api[_-]?key|auth|bearer|cookie|credential|password|private[_-]?key|secret|session|token)/i -const SENSITIVE_ENV_VALUE_PATTERN = - /(sk-[A-Za-z0-9_-]{12,}|gh[pousr]_[A-Za-z0-9_]{12,}|xox[baprs]-[A-Za-z0-9-]{12,})/ - export function inspectMcpConfigContent( candidate: McpConfigCandidate, content: string | null @@ -112,6 +116,15 @@ export function inspectMcpConfigContent( if (content === null) { return { candidate, exists: false, status: 'missing', servers: [] } } + if (!isMcpConfigInspectionTextWithinLimit(content)) { + return { + candidate, + exists: true, + status: 'invalid', + servers: [], + error: 'MCP config exceeds the inspection size limit.' + } + } let parsed: unknown try { @@ -130,29 +143,40 @@ export function inspectMcpConfigContent( if (!rawServers) { return { candidate, exists: true, status: 'valid', servers: [] } } + const serverEntries = collectMcpServerEntries(rawServers) + if (!serverEntries) { + return { + candidate, + exists: true, + status: 'invalid', + servers: [], + error: 'MCP server collection exceeds the inspection limits.' + } + } return { candidate, exists: true, status: 'valid', - servers: Object.entries(rawServers).map(([name, entry]) => summarizeMcpServer(name, entry)) + servers: serverEntries.map(([name, entry]) => summarizeMcpServer(name, entry)) } } -export function maskMcpEnv(env: unknown): Record | undefined { - if (!env || typeof env !== 'object' || Array.isArray(env)) { - return undefined +function collectMcpServerEntries(rawServers: Record): [string, unknown][] | null { + const entries: [string, unknown][] = [] + for (const name in rawServers) { + if (!Object.prototype.hasOwnProperty.call(rawServers, name)) { + continue + } + if ( + entries.length >= MCP_CONFIG_INSPECTION_MAX_SERVERS || + !isMcpConfigInspectionNameWithinLimit(name) + ) { + return null + } + entries.push([name, rawServers[name]]) } - - const masked: Record = {} - for (const [key, rawValue] of Object.entries(env)) { - const value = typeof rawValue === 'string' ? rawValue : String(rawValue) - masked[key] = - SENSITIVE_ENV_KEY_PATTERN.test(key) || SENSITIVE_ENV_VALUE_PATTERN.test(value) - ? '••••••••' - : value - } - return masked + return entries } function getRelativeParentDir(relativePath: string): string { @@ -182,94 +206,3 @@ function extractObjectAtPath( ? (current as Record) : null } - -function summarizeMcpServer(name: string, entry: unknown): McpServerSummary { - if (!entry || typeof entry !== 'object' || Array.isArray(entry)) { - return { - name, - transport: 'unknown', - status: 'invalid', - issue: 'Server entry must be an object.' - } - } - - const raw = entry as Record - const command = readCommand(raw) - const url = readUrl(raw) - const transport = resolveTransport(raw, command, url) - const enabled = raw.enabled !== false && raw.disabled !== true - const env = maskMcpEnv(raw.env) - - if (transport === 'unknown') { - return { - name, - transport, - status: 'invalid', - env, - issue: 'Missing command or URL.' - } - } - - if (transport === 'http' && !url) { - return { - name, - transport, - status: 'invalid', - env, - issue: 'Missing URL.' - } - } - - if (transport === 'stdio' && !command) { - return { - name, - transport, - status: 'invalid', - env, - issue: 'Missing command.' - } - } - - return { - name, - transport, - status: enabled ? 'enabled' : 'disabled', - command, - url, - env - } -} - -function readCommand(raw: Record): string | undefined { - if (typeof raw.command === 'string') { - return raw.command - } - if (Array.isArray(raw.command) && typeof raw.command[0] === 'string') { - return raw.command[0] - } - return undefined -} - -function readUrl(raw: Record): string | undefined { - if (typeof raw.url === 'string') { - return raw.url - } - if (typeof raw.httpUrl === 'string') { - return raw.httpUrl - } - return undefined -} - -function resolveTransport( - raw: Record, - command: string | undefined, - url: string | undefined -): McpServerTransport { - if (raw.type === 'http' || raw.type === 'remote' || url) { - return 'http' - } - if (raw.type === 'local' || command) { - return 'stdio' - } - return 'unknown' -} diff --git a/src/shared/mcp-server-inspection.ts b/src/shared/mcp-server-inspection.ts new file mode 100644 index 000000000..ab7a79cf4 --- /dev/null +++ b/src/shared/mcp-server-inspection.ts @@ -0,0 +1,139 @@ +import { + isMcpConfigInspectionFieldWithinLimit, + isMcpConfigInspectionNameWithinLimit, + MCP_CONFIG_INSPECTION_MAX_ENV_FIELDS +} from './mcp-config-inspection-limits' +import type { McpServerSummary, McpServerTransport } from './mcp-config' + +const SENSITIVE_ENV_KEY_PATTERN = + /(api[_-]?key|auth|bearer|cookie|credential|password|private[_-]?key|secret|session|token)/i +const SENSITIVE_ENV_VALUE_PATTERN = + /(sk-[A-Za-z0-9_-]{12,}|gh[pousr]_[A-Za-z0-9_]{12,}|xox[baprs]-[A-Za-z0-9-]{12,})/ + +type BoundedString = { value?: string; oversized: boolean } +type BoundedEnv = { value?: Record; oversized: boolean } + +export function summarizeMcpServer(name: string, entry: unknown): McpServerSummary { + if (!entry || typeof entry !== 'object' || Array.isArray(entry)) { + return invalidServer(name, 'Server entry must be an object.') + } + + const raw = entry as Record + const command = readCommand(raw) + const url = readUrl(raw) + const env = inspectMcpEnv(raw.env) + if (command.oversized) { + return invalidServer(name, 'Command exceeds the MCP inspection field limit.') + } + if (url.oversized) { + return invalidServer(name, 'URL exceeds the MCP inspection field limit.') + } + if (env.oversized) { + return invalidServer(name, 'Environment exceeds the MCP inspection field limits.') + } + + const transport = resolveTransport(raw, command.value, url.value) + const enabled = raw.enabled !== false && raw.disabled !== true + if (transport === 'unknown') { + return invalidServer(name, 'Missing command or URL.', env.value) + } + if (transport === 'http' && !url.value) { + return invalidServer(name, 'Missing URL.', env.value, transport) + } + if (transport === 'stdio' && !command.value) { + return invalidServer(name, 'Missing command.', env.value, transport) + } + + return { + name, + transport, + status: enabled ? 'enabled' : 'disabled', + command: command.value, + url: url.value, + env: env.value + } +} + +export function maskMcpEnv(env: unknown): Record | undefined { + return inspectMcpEnv(env).value +} + +function inspectMcpEnv(env: unknown): BoundedEnv { + if (!env || typeof env !== 'object' || Array.isArray(env)) { + return { oversized: false } + } + + const masked: Record = {} + let fields = 0 + for (const key in env) { + if (!Object.prototype.hasOwnProperty.call(env, key)) { + continue + } + fields += 1 + if ( + fields > MCP_CONFIG_INSPECTION_MAX_ENV_FIELDS || + !isMcpConfigInspectionNameWithinLimit(key) + ) { + return { oversized: true } + } + const rawValue = (env as Record)[key] + const value = typeof rawValue === 'string' ? rawValue : String(rawValue) + if (!isMcpConfigInspectionFieldWithinLimit(value)) { + return { oversized: true } + } + masked[key] = + SENSITIVE_ENV_KEY_PATTERN.test(key) || SENSITIVE_ENV_VALUE_PATTERN.test(value) + ? '••••••••' + : value + } + return { value: masked, oversized: false } +} + +function readCommand(raw: Record): BoundedString { + const value = + typeof raw.command === 'string' + ? raw.command + : Array.isArray(raw.command) && typeof raw.command[0] === 'string' + ? raw.command[0] + : undefined + return boundedString(value) +} + +function readUrl(raw: Record): BoundedString { + const value = + typeof raw.url === 'string' + ? raw.url + : typeof raw.httpUrl === 'string' + ? raw.httpUrl + : undefined + return boundedString(value) +} + +function boundedString(value: string | undefined): BoundedString { + return value === undefined || isMcpConfigInspectionFieldWithinLimit(value) + ? { value, oversized: false } + : { oversized: true } +} + +function invalidServer( + name: string, + issue: string, + env?: Record, + transport: McpServerTransport = 'unknown' +): McpServerSummary { + return { name, transport, status: 'invalid', env, issue } +} + +function resolveTransport( + raw: Record, + command: string | undefined, + url: string | undefined +): McpServerTransport { + if (raw.type === 'http' || raw.type === 'remote' || url) { + return 'http' + } + if (raw.type === 'local' || command) { + return 'stdio' + } + return 'unknown' +} diff --git a/src/shared/mobile-e2ee-v2-contract.test.ts b/src/shared/mobile-e2ee-v2-contract.test.ts index 4e263c960..64d461ca5 100644 --- a/src/shared/mobile-e2ee-v2-contract.test.ts +++ b/src/shared/mobile-e2ee-v2-contract.test.ts @@ -1,5 +1,5 @@ import { createHash } from 'node:crypto' -import { describe, expect, it } from 'vitest' +import { describe, expect, it, vi } from 'vitest' import { encodeMobileE2EEV2Transcript, validateMobileE2EEV2Handshake @@ -29,6 +29,25 @@ describe('mobile E2EE v2 contract', () => { ).toBeNull() }) + it('rejects wrong-length handshake fields before base64 decoding', () => { + const { hello, ready } = createMobileE2EEV2Fixture() + const oversized = 'A'.repeat(45) + const decode = vi.spyOn(globalThis, 'atob') + + expect( + validateMobileE2EEV2Handshake( + { ...hello, clientPublicKeyB64: oversized, clientNonceB64: oversized }, + { + ...ready, + desktopPublicKeyB64: oversized, + clientNonceB64: oversized, + desktopNonceB64: oversized + } + ) + ).toBeNull() + expect(decode).not.toHaveBeenCalled() + }) + it('rejects context and capability-selection changes', () => { const { hello, ready } = createMobileE2EEV2Fixture() expect( diff --git a/src/shared/mobile-e2ee-v2-contract.ts b/src/shared/mobile-e2ee-v2-contract.ts index d687779b8..907e22d3f 100644 --- a/src/shared/mobile-e2ee-v2-contract.ts +++ b/src/shared/mobile-e2ee-v2-contract.ts @@ -211,6 +211,7 @@ function contextsEqual(left: MobileE2EEV2Context, right: MobileE2EEV2Context): b function decodeCanonicalBase64Bytes(value: unknown, length: number): Uint8Array | null { if ( typeof value !== 'string' || + value.length !== Math.ceil(length / 3) * 4 || !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(value) ) { return null diff --git a/src/shared/mobile-file-directory-limit.test.ts b/src/shared/mobile-file-directory-limit.test.ts new file mode 100644 index 000000000..2d2228c2a --- /dev/null +++ b/src/shared/mobile-file-directory-limit.test.ts @@ -0,0 +1,37 @@ +import { describe, expect, it } from 'vitest' +import { + assertMobileFileDirectoryWithinLimit, + MOBILE_FILE_DIRECTORY_LIMIT_MESSAGE, + MOBILE_FILE_DIRECTORY_MAX_ENTRIES, + MOBILE_FILE_DIRECTORY_MAX_RETAINED_BYTES +} from './mobile-file-directory-limit' + +describe('mobile file directory limit', () => { + it('accepts a complete directory listing within both limits', () => { + expect(() => + assertMobileFileDirectoryWithinLimit([ + { name: 'src' }, + { name: 'README.md' }, + { name: 'package.json' } + ]) + ).not.toThrow() + }) + + it('rejects rather than truncating an excessive entry count', () => { + const entries = Array.from({ length: MOBILE_FILE_DIRECTORY_MAX_ENTRIES + 1 }, () => ({ + name: 'x' + })) + + expect(() => assertMobileFileDirectoryWithinLimit(entries)).toThrow( + MOBILE_FILE_DIRECTORY_LIMIT_MESSAGE + ) + }) + + it('rejects a listing whose names exceed the retained-byte limit', () => { + const name = 'x'.repeat(MOBILE_FILE_DIRECTORY_MAX_RETAINED_BYTES / 2) + + expect(() => assertMobileFileDirectoryWithinLimit([{ name }])).toThrow( + MOBILE_FILE_DIRECTORY_LIMIT_MESSAGE + ) + }) +}) diff --git a/src/shared/mobile-file-directory-limit.ts b/src/shared/mobile-file-directory-limit.ts new file mode 100644 index 000000000..9860f078c --- /dev/null +++ b/src/shared/mobile-file-directory-limit.ts @@ -0,0 +1,43 @@ +// Why: normal repositories stay complete while pathological fan-out/name payloads fail before retention. +export const MOBILE_FILE_DIRECTORY_MAX_ENTRIES = 10_000 +export const MOBILE_FILE_DIRECTORY_MAX_RETAINED_BYTES = 4 * 1024 * 1024 +export const MOBILE_FILE_DIRECTORY_LIMIT_MESSAGE = + 'This folder is too large to show safely on mobile (limit: 10,000 items or a 4 MB listing).' + +type NamedDirectoryEntry = { name: string } + +export type MobileFileDirectoryLimitState = { + entries: number + retainedBytes: number +} + +export function createMobileFileDirectoryLimitState(): MobileFileDirectoryLimitState { + return { entries: 0, retainedBytes: 0 } +} + +export function trackMobileFileDirectoryEntry( + state: MobileFileDirectoryLimitState, + entry: NamedDirectoryEntry +): void { + state.entries += 1 + state.retainedBytes += estimateMobileDirectoryEntryBytes(entry) + if ( + state.entries > MOBILE_FILE_DIRECTORY_MAX_ENTRIES || + state.retainedBytes > MOBILE_FILE_DIRECTORY_MAX_RETAINED_BYTES + ) { + throw new Error(MOBILE_FILE_DIRECTORY_LIMIT_MESSAGE) + } +} + +export function assertMobileFileDirectoryWithinLimit( + entries: readonly NamedDirectoryEntry[] +): void { + const state = createMobileFileDirectoryLimitState() + for (const entry of entries) { + trackMobileFileDirectoryEntry(state, entry) + } +} + +export function estimateMobileDirectoryEntryBytes(entry: NamedDirectoryEntry): number { + return entry.name.length * 2 + 64 +} diff --git a/src/shared/mobile-relay-pairing-offer.ts b/src/shared/mobile-relay-pairing-offer.ts index df16dad35..97419d911 100644 --- a/src/shared/mobile-relay-pairing-offer.ts +++ b/src/shared/mobile-relay-pairing-offer.ts @@ -1,14 +1,22 @@ import { z } from 'zod' export const PAIRING_OFFER_VERSION = 2 +export const PAIRING_CODE_MAX_CHARACTERS = 128 * 1024 +export const PAIRING_INPUT_MAX_CHARACTERS = PAIRING_CODE_MAX_CHARACTERS + 1024 +export const PAIRING_ENDPOINT_MAX_CHARACTERS = 16 * 1024 +export const PAIRING_DEVICE_TOKEN_MAX_CHARACTERS = 64 * 1024 +export const PAIRING_PUBLIC_KEY_MAX_CHARACTERS = 4 * 1024 +export const PAIRING_RELAY_URL_MAX_CHARACTERS = 2048 const PairingScopeSchema = z.enum(['mobile', 'runtime']) const BASE64URL_16_PATTERN = /^[A-Za-z0-9_-]{16}$/ const BASE64URL_43_PATTERN = /^[A-Za-z0-9_-]{43}$/ -const MAX_RELAY_URL_BYTES = 2048 const MAX_INVITE_TTL_MS = 10 * 60 * 1000 function isCanonicalHttpsOrigin(value: string): boolean { - if (new TextEncoder().encode(value).length > MAX_RELAY_URL_BYTES) { + if ( + value.length > PAIRING_RELAY_URL_MAX_CHARACTERS || + new TextEncoder().encode(value).length > PAIRING_RELAY_URL_MAX_CHARACTERS + ) { return false } try { @@ -55,11 +63,11 @@ export function createPairingOfferSchema(now: () => number = () => Date.now()) { return z .object({ v: z.literal(PAIRING_OFFER_VERSION), - endpoint: z.string().min(1), - deviceToken: z.string().min(1), + endpoint: z.string().min(1).max(PAIRING_ENDPOINT_MAX_CHARACTERS), + deviceToken: z.string().min(1).max(PAIRING_DEVICE_TOKEN_MAX_CHARACTERS), // Why: the desktop's Curve25519 public key is pinned by the pairing // offer, while relayHostId is verified from its decoded bytes later. - publicKeyB64: z.string().min(1), + publicKeyB64: z.string().min(1).max(PAIRING_PUBLIC_KEY_MAX_CHARACTERS), scope: PairingScopeSchema.optional(), relay: relaySchema.optional() }) diff --git a/src/shared/node-bounded-file-reader-sync.test.ts b/src/shared/node-bounded-file-reader-sync.test.ts new file mode 100644 index 000000000..748969e13 --- /dev/null +++ b/src/shared/node-bounded-file-reader-sync.test.ts @@ -0,0 +1,38 @@ +import { closeSync, ftruncateSync, mkdtempSync, openSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, describe, expect, it } from 'vitest' +import { NodeFileReadTooLargeError, readNodeFileSyncWithinLimit } from './node-bounded-file-reader' + +const tempDirectories: string[] = [] + +function createTempFile(content: string): string { + const directory = mkdtempSync(join(tmpdir(), 'orca-bounded-sync-read-')) + tempDirectories.push(directory) + const path = join(directory, 'input') + writeFileSync(path, content) + return path +} + +afterEach(() => { + for (const directory of tempDirectories.splice(0)) { + rmSync(directory, { recursive: true }) + } +}) + +describe('readNodeFileSyncWithinLimit', () => { + it('returns stable bytes without changing them', () => { + const path = createTempFile('stable 🐋 bytes') + + expect(readNodeFileSyncWithinLimit(path, 1024).buffer.toString('utf8')).toBe('stable 🐋 bytes') + }) + + it('rejects an oversized sparse file before allocating its declared size', () => { + const path = createTempFile('') + const descriptor = openSync(path, 'r+') + ftruncateSync(descriptor, 1025) + closeSync(descriptor) + + expect(() => readNodeFileSyncWithinLimit(path, 1024)).toThrow(NodeFileReadTooLargeError) + }) +}) diff --git a/src/shared/node-markdown-document-discovery.test.ts b/src/shared/node-markdown-document-discovery.test.ts new file mode 100644 index 000000000..e151f25ad --- /dev/null +++ b/src/shared/node-markdown-document-discovery.test.ts @@ -0,0 +1,74 @@ +import type { Dirent } from 'node:fs' +import { describe, expect, it } from 'vitest' +import { MarkdownDocumentListingCapacityError } from './markdown-document-listing-limits' +import { discoverMarkdownRelativePaths } from './node-markdown-document-discovery' + +function entry(name: string, kind: 'directory' | 'file' | 'symlink' = 'file'): Dirent { + return { + name, + isDirectory: () => kind === 'directory', + isFile: () => kind === 'file', + isSymbolicLink: () => kind === 'symlink' + } as Dirent +} + +function reader(entriesByPath: Record) { + return async (path: string): Promise> => ({ + async *[Symbol.asyncIterator]() { + yield* entriesByPath[path] ?? [] + } + }) +} + +describe('bounded Markdown document discovery', () => { + it('preserves depth-first discovery and skips excluded and symlinked directories', async () => { + const result = await discoverMarkdownRelativePaths('/repo', { + readDirectory: reader({ + '/repo': [ + entry('README.md'), + entry('.git', 'directory'), + entry('docs', 'directory'), + entry('linked', 'symlink') + ], + '/repo/docs': [entry('guide.mdx'), entry('app.ts')] + }), + shouldDescend: (_relativePath, name) => name !== '.git' + }) + + expect(result).toEqual(['README.md', 'docs/guide.mdx']) + }) + + it('stops consuming a wide directory at the visited-entry limit', async () => { + let yielded = 0 + const readDirectory = async (): Promise> => ({ + async *[Symbol.asyncIterator]() { + for (let index = 0; index < 10_000; index += 1) { + yielded += 1 + yield entry(`source-${index}.ts`) + } + } + }) + + await expect( + discoverMarkdownRelativePaths('/repo', { + limits: { maxVisitedEntries: 2 }, + readDirectory, + shouldDescend: () => true + }) + ).rejects.toBeInstanceOf(MarkdownDocumentListingCapacityError) + expect(yielded).toBe(3) + }) + + it('rejects a directory deeper than the configured traversal limit', async () => { + await expect( + discoverMarkdownRelativePaths('/repo', { + limits: { maxDepth: 1 }, + readDirectory: reader({ + '/repo': [entry('one', 'directory')], + '/repo/one': [entry('two', 'directory')] + }), + shouldDescend: () => true + }) + ).rejects.toBeInstanceOf(MarkdownDocumentListingCapacityError) + }) +}) diff --git a/src/shared/node-markdown-document-discovery.ts b/src/shared/node-markdown-document-discovery.ts new file mode 100644 index 000000000..06631c6fc --- /dev/null +++ b/src/shared/node-markdown-document-discovery.ts @@ -0,0 +1,86 @@ +import { opendir } from 'node:fs/promises' +import type { Dirent, Dir } from 'node:fs' +import { join } from 'node:path' +import { + assertMarkdownDocumentPathWithinLimit, + createMarkdownDocumentListingBudget, + MarkdownDocumentListingCapacityError, + retainMarkdownRelativePath, + visitMarkdownDocumentListingEntry, + type MarkdownDocumentListingLimits +} from './markdown-document-listing-limits' + +type MarkdownDirectoryReader = (path: string) => Promise> + +export type MarkdownDocumentDiscoveryOptions = { + shouldDescend: (relativePath: string, name: string) => boolean + ignoreNestedDirectoryErrors?: boolean + limits?: Partial + readDirectory?: MarkdownDirectoryReader + signal?: AbortSignal +} + +export function isMarkdownDocumentPath(path: string): boolean { + const lowerPath = path.toLowerCase() + return lowerPath.endsWith('.md') || lowerPath.endsWith('.mdx') || lowerPath.endsWith('.markdown') +} + +export async function discoverMarkdownRelativePaths( + rootPath: string, + options: MarkdownDocumentDiscoveryOptions +): Promise { + const budget = createMarkdownDocumentListingBudget(options.limits) + const documents: string[] = [] + const readDirectory = options.readDirectory ?? opendir + assertMarkdownDocumentPathWithinLimit(rootPath, budget.limits.maxPathBytes) + + const visitDirectory = async ( + absoluteDirectoryPath: string, + relativeDirectoryPath: string, + depth: number + ): Promise => { + throwIfAborted(options.signal) + let directory: Dir | AsyncIterable + try { + directory = await readDirectory(absoluteDirectoryPath) + } catch (error) { + if (depth > 0 && options.ignoreNestedDirectoryErrors) { + return + } + throw error + } + + for await (const entry of directory) { + throwIfAborted(options.signal) + const relativePath = relativeDirectoryPath + ? `${relativeDirectoryPath}/${entry.name}` + : entry.name + const nextDepth = depth + 1 + const shouldDescend = entry.isDirectory() && options.shouldDescend(relativePath, entry.name) + visitMarkdownDocumentListingEntry(budget, relativePath, shouldDescend ? nextDepth : depth) + if (entry.isSymbolicLink()) { + continue + } + if (entry.isDirectory()) { + if (shouldDescend) { + await visitDirectory(join(absoluteDirectoryPath, entry.name), relativePath, nextDepth) + } + continue + } + if (entry.isFile() && isMarkdownDocumentPath(entry.name)) { + retainMarkdownRelativePath(budget, rootPath, relativePath) + documents.push(relativePath) + } + } + } + + await visitDirectory(rootPath, '', 0) + return documents +} + +function throwIfAborted(signal: AbortSignal | undefined): void { + if (!signal?.aborted) { + return + } + throw signal.reason instanceof Error ? signal.reason : new MarkdownDocumentListingCapacityError() +} diff --git a/src/shared/orca-yaml-alias-bounds.test.ts b/src/shared/orca-yaml-alias-bounds.test.ts new file mode 100644 index 000000000..611c69a1f --- /dev/null +++ b/src/shared/orca-yaml-alias-bounds.test.ts @@ -0,0 +1,27 @@ +import { describe, expect, it } from 'vitest' +import { parseOrcaYaml } from './orca-yaml' + +describe('orca.yaml alias expansion', () => { + it('preserves an ordinary shared scalar', () => { + expect( + parseOrcaYaml(` +setupCommand: &setupCommand pnpm install +scripts: + setup: *setupCommand +`) + ).toMatchObject({ scripts: { setup: 'pnpm install' } }) + }) + + it('rejects alias expansion beyond the explicit conversion cap', () => { + const aliases = Array.from({ length: 21 }, () => '*items').join(', ') + + expect( + parseOrcaYaml(` +items: &items [one, two] +expanded: [${aliases}] +scripts: + setup: pnpm install +`) + ).toBeNull() + }) +}) diff --git a/src/shared/orca-yaml-bounds.test.ts b/src/shared/orca-yaml-bounds.test.ts new file mode 100644 index 000000000..b2e6b6194 --- /dev/null +++ b/src/shared/orca-yaml-bounds.test.ts @@ -0,0 +1,83 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const parseDocumentMock = vi.hoisted(() => vi.fn()) + +vi.mock('yaml', () => ({ + parseDocument: parseDocumentMock +})) + +import { + MAX_ORCA_YAML_ALIAS_COUNT, + MAX_ORCA_YAML_BYTES, + MAX_ORCA_YAML_COLLECTION_ENTRIES, + MAX_ORCA_YAML_FIELD_BYTES, + MAX_ORCA_YAML_FIELD_CODE_UNITS +} from './orca-yaml-file-limit' +import { parseOrcaYaml } from './orca-yaml' + +function returnYamlRoot(root: unknown): void { + parseDocumentMock.mockReturnValue({ + errors: [], + toJS: vi.fn(() => root) + }) +} + +describe('orca.yaml parse bounds', () => { + beforeEach(() => { + parseDocumentMock.mockReset() + returnYamlRoot({ scripts: { setup: 'pnpm install' } }) + }) + + it('admits the exact UTF-8 input boundary and rejects +1 before YAML parsing', () => { + expect(parseOrcaYaml(' '.repeat(MAX_ORCA_YAML_BYTES))).toMatchObject({ + scripts: { setup: 'pnpm install' } + }) + expect(parseDocumentMock).toHaveBeenCalledOnce() + + parseDocumentMock.mockClear() + expect(parseOrcaYaml(' '.repeat(MAX_ORCA_YAML_BYTES + 1))).toBeNull() + expect(parseDocumentMock).not.toHaveBeenCalled() + }) + + it('rejects a multibyte input over the byte cap before YAML parsing', () => { + const content = 'é'.repeat(MAX_ORCA_YAML_BYTES / 2 + 1) + + expect(parseOrcaYaml(content)).toBeNull() + expect(parseDocumentMock).not.toHaveBeenCalled() + }) + + it('passes an explicit alias expansion cap to YAML conversion', () => { + const toJS = vi.fn(() => ({ scripts: { setup: 'pnpm install' } })) + parseDocumentMock.mockReturnValue({ errors: [], toJS }) + + expect(parseOrcaYaml('scripts: {}')).not.toBeNull() + expect(toJS).toHaveBeenCalledWith({ maxAliasCount: MAX_ORCA_YAML_ALIAS_COUNT }) + }) + + it('preserves exact-size fields and drops a field at +1 code unit', () => { + const exact = 'x'.repeat(MAX_ORCA_YAML_FIELD_CODE_UNITS) + returnYamlRoot({ scripts: { setup: exact } }) + expect(parseOrcaYaml('exact')).toMatchObject({ scripts: { setup: exact } }) + + returnYamlRoot({ scripts: { setup: `${exact}x` } }) + expect(parseOrcaYaml('overflow')).toBeNull() + + const exactUtf8 = 'é'.repeat(MAX_ORCA_YAML_FIELD_BYTES / 2) + returnYamlRoot({ scripts: { setup: exactUtf8 } }) + expect(parseOrcaYaml('exact-utf8')).toMatchObject({ scripts: { setup: exactUtf8 } }) + + returnYamlRoot({ scripts: { setup: `${exactUtf8}é` } }) + expect(parseOrcaYaml('overflow-utf8')).toBeNull() + }) + + it('admits the exact collection boundary and rejects +1 entries', () => { + const tabs = Array.from({ length: MAX_ORCA_YAML_COLLECTION_ENTRIES }, (_, index) => ({ + title: `tab-${index}` + })) + returnYamlRoot({ defaultTabs: tabs }) + expect(parseOrcaYaml('exact')?.defaultTabs).toHaveLength(MAX_ORCA_YAML_COLLECTION_ENTRIES) + + returnYamlRoot({ defaultTabs: [...tabs, { title: 'overflow' }] }) + expect(parseOrcaYaml('overflow')).toBeNull() + }) +}) diff --git a/src/shared/orca-yaml-file-limit.ts b/src/shared/orca-yaml-file-limit.ts new file mode 100644 index 000000000..8f2641637 --- /dev/null +++ b/src/shared/orca-yaml-file-limit.ts @@ -0,0 +1,22 @@ +import { measureUtf8ByteLength } from './utf8-byte-limits' + +export const MAX_ORCA_YAML_BYTES = 256 * 1024 +export const MAX_ORCA_YAML_CODE_UNITS = 256 * 1024 +export const MAX_ORCA_YAML_FIELD_BYTES = 64 * 1024 +export const MAX_ORCA_YAML_FIELD_CODE_UNITS = 64 * 1024 +export const MAX_ORCA_YAML_COLLECTION_ENTRIES = 256 +export const MAX_ORCA_YAML_ALIAS_COUNT = 20 + +export function isOrcaYamlTextWithinLimit(content: string): boolean { + return ( + content.length <= MAX_ORCA_YAML_CODE_UNITS && + !measureUtf8ByteLength(content, { stopAfterBytes: MAX_ORCA_YAML_BYTES }).exceededLimit + ) +} + +export function isOrcaYamlFieldWithinLimit(value: string): boolean { + return ( + value.length <= MAX_ORCA_YAML_FIELD_CODE_UNITS && + !measureUtf8ByteLength(value, { stopAfterBytes: MAX_ORCA_YAML_FIELD_BYTES }).exceededLimit + ) +} diff --git a/src/shared/orca-yaml.ts b/src/shared/orca-yaml.ts index c9179c6d6..e8cb15e0a 100644 --- a/src/shared/orca-yaml.ts +++ b/src/shared/orca-yaml.ts @@ -1,10 +1,16 @@ -import { parse } from 'yaml' +import { parseDocument } from 'yaml' import type { OrcaDefaultTabTemplate, OrcaHooks, OrcaVmRecipe, OrcaVmRecipeDiagnostic } from './types' +import { + isOrcaYamlFieldWithinLimit, + isOrcaYamlTextWithinLimit, + MAX_ORCA_YAML_ALIAS_COUNT, + MAX_ORCA_YAML_COLLECTION_ENTRIES +} from './orca-yaml-file-limit' function asRecord(value: unknown): Record | null { return value !== null && typeof value === 'object' && !Array.isArray(value) @@ -13,7 +19,11 @@ function asRecord(value: unknown): Record | null { } function asTrimmedString(value: unknown): string | undefined { - return typeof value === 'string' && value.trim() ? value.trim() : undefined + if (typeof value !== 'string' || !isOrcaYamlFieldWithinLimit(value)) { + return undefined + } + const trimmed = value.trim() + return trimmed || undefined } const DEFAULT_TAB_COLOR_RE = /^#[0-9a-fA-F]{3}(?:[0-9a-fA-F]{3})?$/ @@ -22,7 +32,7 @@ export const ORCA_VM_RECIPE_ID_RULE = 'Use 1-64 lowercase letters, numbers, dots, underscores, or hyphens, starting with a letter or number.' function normalizeDefaultTabs(value: unknown): OrcaDefaultTabTemplate[] { - if (!Array.isArray(value)) { + if (!Array.isArray(value) || value.length > MAX_ORCA_YAML_COLLECTION_ENTRIES) { return [] } @@ -58,6 +68,17 @@ function normalizeVmRecipes(value: unknown): VmRecipeParseResult { if (!Array.isArray(value)) { return { recipes: [], diagnostics } } + if (value.length > MAX_ORCA_YAML_COLLECTION_ENTRIES) { + return { + recipes: [], + diagnostics: [ + { + index: MAX_ORCA_YAML_COLLECTION_ENTRIES, + message: `At most ${MAX_ORCA_YAML_COLLECTION_ENTRIES} environment recipes are supported.` + } + ] + } + } const seenIds = new Set() const recipes = value @@ -126,9 +147,22 @@ function normalizeVmRecipes(value: unknown): VmRecipeParseResult { * Parse the supported project defaults from `orca.yaml`. */ export function parseOrcaYaml(content: string): OrcaHooks | null { + if (!isOrcaYamlTextWithinLimit(content)) { + return null + } + let root: unknown try { - root = parse(content) + const document = parseDocument(content, { + keepSourceTokens: false, + logLevel: 'silent', + prettyErrors: false, + uniqueKeys: true + }) + if (document.errors.length > 0) { + return null + } + root = document.toJS({ maxAliasCount: MAX_ORCA_YAML_ALIAS_COUNT }) } catch { return null } diff --git a/src/shared/osc-title-extraction.ts b/src/shared/osc-title-extraction.ts index e4bbe5350..207604572 100644 --- a/src/shared/osc-title-extraction.ts +++ b/src/shared/osc-title-extraction.ts @@ -5,6 +5,7 @@ const BACKSLASH_CODE_UNIT = 0x5c const SEMICOLON_CODE_UNIT = 0x3b const OSC_TITLE_COMMANDS = new Set([0x30, 0x31, 0x32]) export const MAX_OSC_TITLE_CHARS = 1024 +export const MAX_OSC_TITLES_PER_CHUNK = 4096 type OscTitleParseResult = | { kind: 'title'; title: string; nextIndex: number } @@ -104,6 +105,7 @@ export function extractAllOscTitles(data: string): string[] { } const titles: string[] = [] + let oldestTitleIndex = 0 let searchStart = 0 while (searchStart < data.length) { const start = data.indexOf('\x1b]', searchStart) @@ -115,11 +117,18 @@ export function extractAllOscTitles(data: string): string[] { break } if (parsed.kind === 'title') { - titles.push(parsed.title) + if (titles.length < MAX_OSC_TITLES_PER_CHUNK) { + titles.push(parsed.title) + } else { + titles[oldestTitleIndex] = parsed.title + oldestTitleIndex = (oldestTitleIndex + 1) % MAX_OSC_TITLES_PER_CHUNK + } searchStart = parsed.nextIndex continue } searchStart = parsed.nextIndex } - return titles + return oldestTitleIndex === 0 + ? titles + : [...titles.slice(oldestTitleIndex), ...titles.slice(0, oldestTitleIndex)] } diff --git a/src/shared/pairing.ts b/src/shared/pairing.ts index c39595bbe..4a4b6350f 100644 --- a/src/shared/pairing.ts +++ b/src/shared/pairing.ts @@ -1,4 +1,6 @@ import { + PAIRING_CODE_MAX_CHARACTERS, + PAIRING_INPUT_MAX_CHARACTERS, PAIRING_OFFER_VERSION, PairingOfferSchema, type PairingOffer @@ -8,18 +10,24 @@ export { PAIRING_OFFER_VERSION, PairingOfferSchema } export type { PairingOffer } export function encodePairingOffer(offer: PairingOffer): string { - const json = JSON.stringify(offer) + const json = JSON.stringify(PairingOfferSchema.parse(offer)) const base64url = Buffer.from(json, 'utf-8') .toString('base64') .replace(/\+/g, '-') .replace(/\//g, '_') .replace(/=+$/, '') + if (base64url.length > PAIRING_CODE_MAX_CHARACTERS) { + throw new Error('Pairing offer exceeds safe size') + } // Why: Android camera intents and Expo Router preserve query params more // reliably than URL fragments when launching a custom-scheme app. return `orca://pair?code=${base64url}` } export function decodePairingOffer(url: string): PairingOffer { + if (url.length > PAIRING_INPUT_MAX_CHARACTERS) { + throw new Error('Invalid pairing URL: pairing code exceeds safe size') + } const code = extractPairingCodeFromUrl(url) if (!code) { throw new Error('Invalid pairing URL: must start with orca://pair and include a pairing code') @@ -53,6 +61,9 @@ function extractPairingCodeFromUrl(url: string): string | null { // string so the mobile paste-pair flow can take whichever the user // actually copied from desktop. export function parsePairingCode(input: string): PairingOffer | null { + if (input.length > PAIRING_INPUT_MAX_CHARACTERS) { + return null + } const trimmed = input.trim() if (!trimmed) { return null @@ -68,6 +79,13 @@ export function parsePairingCode(input: string): PairingOffer | null { } function decodePairingBase64(base64url: string): PairingOffer { + if ( + base64url.length === 0 || + base64url.length > PAIRING_CODE_MAX_CHARACTERS || + !/^[A-Za-z0-9+/_-]+={0,2}$/.test(base64url) + ) { + throw new Error('Invalid pairing code') + } const base64 = base64url.replace(/-/g, '+').replace(/_/g, '/') const json = Buffer.from(base64, 'base64').toString('utf-8') return PairingOfferSchema.parse(JSON.parse(json)) diff --git a/src/shared/pr-refresh-memory-limits.ts b/src/shared/pr-refresh-memory-limits.ts new file mode 100644 index 000000000..8b695aded --- /dev/null +++ b/src/shared/pr-refresh-memory-limits.ts @@ -0,0 +1,5 @@ +export const PR_REFRESH_QUEUE_ENTRY_LIMIT = 1_024 +export const PR_REFRESH_ALIAS_LIMIT = 64 +export const PR_REFRESH_VISIBLE_CANDIDATE_LIMIT = 1_024 +export const PR_REFRESH_RETRY_STATE_LIMIT = 1_024 +export const PR_REFRESH_ACTIVE_SCOPE_LIMIT = 1_024 diff --git a/src/shared/pull-request-generation.test.ts b/src/shared/pull-request-generation.test.ts index 8f47c385d..f0350e0a0 100644 --- a/src/shared/pull-request-generation.test.ts +++ b/src/shared/pull-request-generation.test.ts @@ -1,6 +1,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import { buildPullRequestFieldsPrompt, + GENERATED_PULL_REQUEST_JSON_STRUCTURE_LIMITS, parseGeneratedPullRequestFields, type PullRequestDraftContext } from './pull-request-generation' @@ -93,4 +94,17 @@ describe('parseGeneratedPullRequestFields', () => { draft: false }) }) + + it('rejects excessive nesting before JSON.parse', () => { + const parseSpy = vi.spyOn(JSON, 'parse') + const depth = GENERATED_PULL_REQUEST_JSON_STRUCTURE_LIMITS.nestingDepth + 1 + try { + expect(() => + parseGeneratedPullRequestFields(`${'['.repeat(depth)}0${']'.repeat(depth)}`, context) + ).toThrow(/JSON nesting exceeds/) + expect(parseSpy).not.toHaveBeenCalled() + } finally { + parseSpy.mockRestore() + } + }) }) diff --git a/src/shared/pull-request-generation.ts b/src/shared/pull-request-generation.ts index c67a463fc..fd927b82a 100644 --- a/src/shared/pull-request-generation.ts +++ b/src/shared/pull-request-generation.ts @@ -1,4 +1,10 @@ import { truncateDiffForPrompt } from './commit-message-prompt' +import { assertJsonTextStructureWithinLimits } from './json-text-structure-limit' + +export const GENERATED_PULL_REQUEST_JSON_STRUCTURE_LIMITS = { + structuralTokens: 64, + nestingDepth: 8 +} as const export type PullRequestDraftContext = { branch: string | null @@ -152,7 +158,9 @@ export function parseGeneratedPullRequestFields( raw: string, fallback: Pick ): GeneratedPullRequestFields { - const parsed = JSON.parse(stripJsonFence(raw)) as unknown + const content = stripJsonFence(raw) + assertJsonTextStructureWithinLimits(content, GENERATED_PULL_REQUEST_JSON_STRUCTURE_LIMITS) + const parsed = JSON.parse(content) as unknown if (!parsed || typeof parsed !== 'object') { throw new Error('Expected a JSON object.') } diff --git a/src/shared/quick-open-directory-reader.test.ts b/src/shared/quick-open-directory-reader.test.ts new file mode 100644 index 000000000..fcd119855 --- /dev/null +++ b/src/shared/quick-open-directory-reader.test.ts @@ -0,0 +1,56 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' + +const { lstatMock, opendirMock } = vi.hoisted(() => ({ + lstatMock: vi.fn(), + opendirMock: vi.fn() +})) + +vi.mock('node:fs/promises', () => ({ + lstat: lstatMock, + opendir: opendirMock +})) + +import { readQuickOpenDirectoryEntries } from './quick-open-directory-reader' +import { createQuickOpenReaddirBudget } from './quick-open-readdir-budget' + +beforeEach(() => { + vi.clearAllMocks() + lstatMock.mockResolvedValue({ + isDirectory: () => true, + isSymbolicLink: () => false + }) +}) + +describe('quick-open streaming directory reader', () => { + it('stops a huge directory one entry beyond the exact cap and closes its iterator', async () => { + let produced = 0 + let closed = false + opendirMock.mockResolvedValue({ + async *[Symbol.asyncIterator]() { + try { + while (produced < 1_000_000) { + produced += 1 + yield { + name: `directory-${produced}`, + isDirectory: () => true, + isFile: () => false, + isSymbolicLink: () => false + } + } + } finally { + closed = true + } + } + }) + + await expect( + readQuickOpenDirectoryEntries({ + absPath: '/streamed', + allowSymlinkedRoot: false, + budget: createQuickOpenReaddirBudget({ maxEntries: 3 }) + }) + ).rejects.toThrow('File listing exceeded 3 entries') + expect(produced).toBe(4) + expect(closed).toBe(true) + }) +}) diff --git a/src/shared/quick-open-directory-reader.ts b/src/shared/quick-open-directory-reader.ts new file mode 100644 index 000000000..cc53d8d64 --- /dev/null +++ b/src/shared/quick-open-directory-reader.ts @@ -0,0 +1,62 @@ +import { lstat, opendir } from 'node:fs/promises' +import { isFileListingCancellation, throwIfFileListingCancelled } from './file-listing-cancellation' +import { isQuickOpenReadableDirectory } from './quick-open-directory-validation' +import { + assertQuickOpenReaddirDeadline, + consumeQuickOpenReaddirEntryBudget, + consumeQuickOpenReaddirPathBudget, + isQuickOpenReaddirBudgetError, + type QuickOpenReaddirBudget +} from './quick-open-readdir-budget' + +export type QuickOpenDirectoryEntry = { + name: string + kind: 'directory' | 'file' | 'symlink' | 'other' +} + +export async function readQuickOpenDirectoryEntries(opts: { + absPath: string + allowSymlinkedRoot: boolean + budget: QuickOpenReaddirBudget + signal?: AbortSignal +}): Promise { + try { + const stat = await lstat(opts.absPath) + if (!isQuickOpenReadableDirectory(stat, opts.allowSymlinkedRoot)) { + return [] + } + + const entries: QuickOpenDirectoryEntry[] = [] + const directory = await opendir(opts.absPath) + throwIfFileListingCancelled(opts.signal) + assertQuickOpenReaddirDeadline(opts.budget) + for await (const entry of directory) { + throwIfFileListingCancelled(opts.signal) + assertQuickOpenReaddirDeadline(opts.budget) + consumeQuickOpenReaddirEntryBudget(opts.budget) + consumeQuickOpenReaddirPathBudget(opts.budget, entry.name) + entries.push({ + name: entry.name, + kind: entry.isDirectory() + ? 'directory' + : entry.isFile() + ? 'file' + : entry.isSymbolicLink() + ? 'symlink' + : 'other' + }) + } + entries.sort((left, right) => (left.name < right.name ? -1 : left.name > right.name ? 1 : 0)) + + // Why: discard buffered names if the path became a symlink while its + // directory handle was open; descendants must never escape the root. + const statAfterRead = await lstat(opts.absPath) + return isQuickOpenReadableDirectory(statAfterRead, opts.allowSymlinkedRoot) ? entries : [] + } catch (error) { + if (isQuickOpenReaddirBudgetError(error) || isFileListingCancellation(error)) { + throw error + } + // Permission denied or a vanished subtree must not hide readable siblings. + return [] + } +} diff --git a/src/shared/quick-open-git-entry-classification.ts b/src/shared/quick-open-git-entry-classification.ts new file mode 100644 index 000000000..971a4106d --- /dev/null +++ b/src/shared/quick-open-git-entry-classification.ts @@ -0,0 +1,68 @@ +import { lstat } from 'node:fs/promises' +import { join } from 'node:path' + +export type QuickOpenGitEntryKind = 'keep' | 'fill-nested-repo' | 'drop-placeholder' + +export type QuickOpenGitLsFilesEntry = { + path: string + isGitlink: boolean + isUntrackedDir: boolean +} + +const GIT_LS_FILES_STAGE_ENTRY = /^([0-7]{6}) [0-9a-f]{40,64} [0-3]\t/ + +export function parseQuickOpenGitLsFilesEntry(entry: string): QuickOpenGitLsFilesEntry { + const match = GIT_LS_FILES_STAGE_ENTRY.exec(entry) + if (match) { + return { + path: entry.slice(match[0].length), + isGitlink: match[1] === '160000', + isUntrackedDir: false + } + } + return { + path: entry, + isGitlink: false, + isUntrackedDir: entry.endsWith('/') + } +} + +function joinQuickOpenRootPath(rootPath: string, relPath: string): string { + return join(rootPath, ...relPath.split('/').filter(Boolean)) +} + +async function hasGitEntry(absPath: string): Promise { + try { + const stat = await lstat(join(absPath, '.git')) + return stat.isDirectory() || stat.isFile() + } catch { + return false + } +} + +export async function classifyQuickOpenGitEntry( + rootPath: string, + entry: string +): Promise<{ kind: QuickOpenGitEntryKind; relPath: string }> { + const parsed = parseQuickOpenGitLsFilesEntry(entry) + const relPath = parsed.path.replace(/\/+$/, '') + if (!relPath) { + return { kind: 'drop-placeholder', relPath } + } + if (!parsed.isGitlink && !parsed.isUntrackedDir) { + return { kind: 'keep', relPath } + } + + let stat + try { + stat = await lstat(joinQuickOpenRootPath(rootPath, relPath)) + } catch { + return { kind: 'drop-placeholder', relPath } + } + if (!stat.isDirectory()) { + return { kind: 'drop-placeholder', relPath } + } + return (await hasGitEntry(joinQuickOpenRootPath(rootPath, relPath))) + ? { kind: 'fill-nested-repo', relPath } + : { kind: 'drop-placeholder', relPath } +} diff --git a/src/shared/quick-open-install-rg.ts b/src/shared/quick-open-install-rg.ts index 5ba70bc8f..7815d7d6e 100644 --- a/src/shared/quick-open-install-rg.ts +++ b/src/shared/quick-open-install-rg.ts @@ -1,9 +1,10 @@ -import { readFile } from 'node:fs/promises' +import { readNodeFileWithinLimit } from './node-bounded-file-reader' import { getProcessOutputFields, iterateProcessOutputLines } from './process-output-field-scanner' const GENERIC_LINUX_RIPGREP_INSTALL = 'install ripgrep via your package manager (e.g. apt/dnf/pacman)' const OS_RELEASE_ID_LIKE_MAX_FIELDS = 16 +const MAX_OS_RELEASE_BYTES = 64 * 1024 export async function detectInstallCommand(): Promise { if (process.platform === 'darwin') { @@ -11,7 +12,9 @@ export async function detectInstallCommand(): Promise { } if (process.platform === 'linux') { try { - const osRelease = await readFile('/etc/os-release', 'utf-8') + const osRelease = ( + await readNodeFileWithinLimit('/etc/os-release', MAX_OS_RELEASE_BYTES) + ).buffer.toString('utf8') return detectLinuxInstallCommandFromOsRelease(osRelease) } catch { /* fall through to generic guidance */ diff --git a/src/shared/quick-open-listing-limits.test.ts b/src/shared/quick-open-listing-limits.test.ts new file mode 100644 index 000000000..bd24c80da --- /dev/null +++ b/src/shared/quick-open-listing-limits.test.ts @@ -0,0 +1,82 @@ +import { describe, expect, it, vi } from 'vitest' +import { + createQuickOpenListingBudget, + QuickOpenSubprocessPathAccumulator, + resolveQuickOpenResultLimit, + retainQuickOpenPath, + QUICK_OPEN_LISTING_MAX_PATH_BYTES, + QUICK_OPEN_LISTING_MAX_RETAINED_PATH_BYTES, + QUICK_OPEN_LISTING_MAX_RETAINED_PATHS, + QUICK_OPEN_LISTING_MAX_RESULTS +} from './quick-open-listing-limits' + +describe('Quick Open listing limits', () => { + it('uses one hard result cap while preserving smaller requested limits', () => { + expect(resolveQuickOpenResultLimit()).toBe(QUICK_OPEN_LISTING_MAX_RESULTS) + expect(resolveQuickOpenResultLimit(17)).toBe(17) + expect(resolveQuickOpenResultLimit(QUICK_OPEN_LISTING_MAX_RESULTS + 1)).toBe( + QUICK_OPEN_LISTING_MAX_RESULTS + ) + expect(resolveQuickOpenResultLimit(0)).toBe(0) + }) + + it('keeps the production memory ceilings explicit', () => { + expect(QUICK_OPEN_LISTING_MAX_RESULTS).toBe(20_001) + expect(QUICK_OPEN_LISTING_MAX_RETAINED_PATHS).toBe(100_000) + expect(QUICK_OPEN_LISTING_MAX_RETAINED_PATH_BYTES).toBe(32 * 1024 * 1024) + expect(QUICK_OPEN_LISTING_MAX_PATH_BYTES).toBe(64 * 1024) + }) + + it('accepts the exact retained path boundaries without charging duplicates', () => { + const paths = new Set() + const budget = createQuickOpenListingBudget({ + maxRetainedPaths: 2, + maxRetainedPathBytes: 3, + maxPathBytes: 2 + }) + + expect(retainQuickOpenPath(paths, 'ab', budget)).toBe(true) + expect(retainQuickOpenPath(paths, 'ab', budget)).toBe(false) + expect(retainQuickOpenPath(paths, 'c', budget)).toBe(true) + expect(budget).toMatchObject({ retainedPathCount: 2, retainedPathBytes: 3 }) + expect(() => retainQuickOpenPath(paths, '', budget)).toThrow('2 retained paths') + }) + + it('rejects path-byte overflow without mutating the retained budget', () => { + const paths = new Set() + const budget = createQuickOpenListingBudget({ + maxRetainedPaths: 3, + maxRetainedPathBytes: 2, + maxPathBytes: 2 + }) + retainQuickOpenPath(paths, 'ab', budget) + + expect(() => retainQuickOpenPath(paths, 'c', budget)).toThrow('2 retained path bytes') + expect(paths).toEqual(new Set(['ab'])) + expect(budget).toMatchObject({ retainedPathCount: 1, retainedPathBytes: 2 }) + }) + + it('bounds one fragmented subprocess path and recovers after overflow', () => { + const onPath = vi.fn(() => true) + const fields = new QuickOpenSubprocessPathAccumulator(0, 3) + + expect(fields.push(Buffer.from('ab'), onPath)).toBe('continue') + expect(fields.push(Buffer.from('cd'), onPath)).toBe('path-too-large') + expect(fields.push(Buffer.from('ok\0'), onPath)).toBe('continue') + expect(onPath).toHaveBeenCalledTimes(1) + expect(onPath).toHaveBeenCalledWith('ok') + }) + + it('stops within a multi-path chunk without visiting later fields', () => { + const visited: string[] = [] + const fields = new QuickOpenSubprocessPathAccumulator(0, 16) + + expect( + fields.push(Buffer.from('one\0two\0three\0'), (path) => { + visited.push(path) + return path !== 'two' + }) + ).toBe('stopped') + expect(visited).toEqual(['one', 'two']) + }) +}) diff --git a/src/shared/quick-open-listing-limits.ts b/src/shared/quick-open-listing-limits.ts new file mode 100644 index 000000000..0e28f8b1d --- /dev/null +++ b/src/shared/quick-open-listing-limits.ts @@ -0,0 +1,142 @@ +import { GrowingByteBuffer } from './growing-byte-buffer' + +export const QUICK_OPEN_LISTING_MAX_RESULTS = 20_001 +export const QUICK_OPEN_LISTING_MAX_RETAINED_PATHS = 100_000 +export const QUICK_OPEN_LISTING_MAX_RETAINED_PATH_BYTES = 32 * 1024 * 1024 +export const QUICK_OPEN_LISTING_MAX_PATH_BYTES = 64 * 1024 + +export type QuickOpenListingBudget = { + retainedPathCount: number + retainedPathBytes: number + maxRetainedPaths: number + maxRetainedPathBytes: number + maxPathBytes: number +} + +export function resolveQuickOpenResultLimit(requested?: number): number { + if (requested === undefined || requested === Number.POSITIVE_INFINITY) { + return QUICK_OPEN_LISTING_MAX_RESULTS + } + if (!Number.isFinite(requested)) { + return 0 + } + return Math.min(Math.max(Math.trunc(requested), 0), QUICK_OPEN_LISTING_MAX_RESULTS) +} + +export function createQuickOpenListingBudget( + limits: Partial< + Pick + > = {} +): QuickOpenListingBudget { + const maxRetainedPaths = limits.maxRetainedPaths ?? QUICK_OPEN_LISTING_MAX_RETAINED_PATHS + const maxRetainedPathBytes = + limits.maxRetainedPathBytes ?? QUICK_OPEN_LISTING_MAX_RETAINED_PATH_BYTES + const maxPathBytes = limits.maxPathBytes ?? QUICK_OPEN_LISTING_MAX_PATH_BYTES + for (const [name, value] of Object.entries({ + maxRetainedPaths, + maxRetainedPathBytes, + maxPathBytes + })) { + if (!Number.isSafeInteger(value) || value < 0) { + throw new RangeError(`${name} must be a non-negative safe integer`) + } + } + return { + retainedPathCount: 0, + retainedPathBytes: 0, + maxRetainedPaths, + maxRetainedPathBytes, + maxPathBytes + } +} + +export function retainQuickOpenPath( + paths: Set, + path: string, + budget: QuickOpenListingBudget +): boolean { + if (paths.has(path)) { + return false + } + const pathBytes = Buffer.byteLength(path, 'utf8') + if (pathBytes > budget.maxPathBytes) { + throw new Error(`Quick Open file path exceeded ${budget.maxPathBytes} bytes`) + } + if (budget.retainedPathCount >= budget.maxRetainedPaths) { + throw new Error(`Quick Open file listing exceeded ${budget.maxRetainedPaths} retained paths`) + } + if (pathBytes > budget.maxRetainedPathBytes - budget.retainedPathBytes) { + throw new Error( + `Quick Open file listing exceeded ${budget.maxRetainedPathBytes} retained path bytes` + ) + } + budget.retainedPathCount++ + budget.retainedPathBytes += pathBytes + paths.add(path) + return true +} + +export type QuickOpenPathAccumulatorResult = 'continue' | 'stopped' | 'path-too-large' + +export class QuickOpenSubprocessPathAccumulator { + private readonly field = new GrowingByteBuffer() + + constructor( + private readonly delimiter: number, + private readonly maxPathBytes = QUICK_OPEN_LISTING_MAX_PATH_BYTES + ) { + if (!Number.isInteger(delimiter) || delimiter < 0 || delimiter > 0xff) { + throw new RangeError('Quick Open path delimiter must be one byte') + } + if (!Number.isSafeInteger(maxPathBytes) || maxPathBytes < 0) { + throw new RangeError('Quick Open path limit must be a non-negative safe integer') + } + } + + push( + rawChunk: Buffer | string, + onPath: (path: string) => boolean + ): QuickOpenPathAccumulatorResult { + const chunk = Buffer.isBuffer(rawChunk) ? rawChunk : Buffer.from(rawChunk, 'utf8') + let cursor = 0 + while (cursor < chunk.length) { + const delimiter = chunk.indexOf(this.delimiter, cursor) + const end = delimiter === -1 ? chunk.length : delimiter + const segmentBytes = end - cursor + if (this.field.byteLength + segmentBytes > this.maxPathBytes) { + this.clear() + return 'path-too-large' + } + if (delimiter !== -1 && this.field.byteLength === 0) { + if (!onPath(chunk.toString('utf8', cursor, end))) { + return 'stopped' + } + } else if (segmentBytes > 0) { + // Why: copying prevents a short residual path from retaining the whole read buffer. + this.field.append(chunk.subarray(cursor, end)) + if (delimiter !== -1 && !onPath(this.take())) { + return 'stopped' + } + } else if (delimiter !== -1 && !onPath(this.take())) { + return 'stopped' + } + if (delimiter === -1) { + return 'continue' + } + cursor = delimiter + 1 + } + return 'continue' + } + + finish(): string | null { + return this.field.byteLength > 0 ? this.take() : null + } + + clear(): void { + this.field.clear() + } + + private take(): string { + return this.field.takeString() + } +} diff --git a/src/shared/quick-open-readdir-budget.ts b/src/shared/quick-open-readdir-budget.ts index 14fd599cf..991e02694 100644 --- a/src/shared/quick-open-readdir-budget.ts +++ b/src/shared/quick-open-readdir-budget.ts @@ -1,16 +1,60 @@ export const QUICK_OPEN_READDIR_MAX_FILES = 10_000 +export const QUICK_OPEN_READDIR_MAX_ENTRIES = 50_000 +export const QUICK_OPEN_READDIR_MAX_DIRECTORIES = 25_000 +export const QUICK_OPEN_READDIR_MAX_DEPTH = 256 +export const QUICK_OPEN_READDIR_MAX_PATH_CODE_UNITS = 16 * 1024 * 1024 export const QUICK_OPEN_READDIR_TIMEOUT_MS = 10_000 export type QuickOpenReaddirBudget = { remainingFiles: number + remainingEntries: number + remainingDirectories: number + remainingPathCodeUnits: number + maxFiles: number + maxEntries: number + maxDirectories: number + maxDepth: number + maxPathCodeUnits: number deadlineMs: number } export function createQuickOpenReaddirBudget( - opts: { maxFiles?: number; timeoutMs?: number; nowMs?: number } = {} + opts: { + maxFiles?: number + maxEntries?: number + maxDirectories?: number + maxDepth?: number + maxPathCodeUnits?: number + timeoutMs?: number + nowMs?: number + } = {} ): QuickOpenReaddirBudget { + const maxFiles = opts.maxFiles ?? QUICK_OPEN_READDIR_MAX_FILES + const maxEntries = opts.maxEntries ?? QUICK_OPEN_READDIR_MAX_ENTRIES + const maxDirectories = opts.maxDirectories ?? QUICK_OPEN_READDIR_MAX_DIRECTORIES + const maxDepth = opts.maxDepth ?? QUICK_OPEN_READDIR_MAX_DEPTH + const maxPathCodeUnits = opts.maxPathCodeUnits ?? QUICK_OPEN_READDIR_MAX_PATH_CODE_UNITS + for (const [name, value] of Object.entries({ + maxFiles, + maxEntries, + maxDirectories, + maxDepth, + maxPathCodeUnits + })) { + if (!Number.isSafeInteger(value) || value < 0) { + throw new RangeError(`${name} must be a non-negative safe integer`) + } + } return { - remainingFiles: opts.maxFiles ?? QUICK_OPEN_READDIR_MAX_FILES, + remainingFiles: maxFiles, + remainingEntries: maxEntries, + remainingDirectories: maxDirectories, + remainingPathCodeUnits: maxPathCodeUnits, + maxFiles, + maxEntries, + maxDirectories, + maxDepth, + maxPathCodeUnits, deadlineMs: (opts.nowMs ?? Date.now()) + (opts.timeoutMs ?? QUICK_OPEN_READDIR_TIMEOUT_MS) } } @@ -32,7 +76,37 @@ export function assertQuickOpenReaddirDeadline(budget: QuickOpenReaddirBudget): export function consumeQuickOpenReaddirFileBudget(budget: QuickOpenReaddirBudget): void { if (budget.remainingFiles <= 0) { - throw new Error(`${FILE_LISTING_EXCEEDED_PREFIX} ${QUICK_OPEN_READDIR_MAX_FILES} files`) + throw new Error(`${FILE_LISTING_EXCEEDED_PREFIX} ${budget.maxFiles} files`) } budget.remainingFiles-- } + +export function consumeQuickOpenReaddirEntryBudget(budget: QuickOpenReaddirBudget): void { + if (budget.remainingEntries <= 0) { + throw new Error(`${FILE_LISTING_EXCEEDED_PREFIX} ${budget.maxEntries} entries`) + } + budget.remainingEntries-- +} + +export function consumeQuickOpenReaddirDirectoryBudget(budget: QuickOpenReaddirBudget): void { + if (budget.remainingDirectories <= 0) { + throw new Error(`${FILE_LISTING_EXCEEDED_PREFIX} ${budget.maxDirectories} directories`) + } + budget.remainingDirectories-- +} + +export function assertQuickOpenReaddirDepth(budget: QuickOpenReaddirBudget, depth: number): void { + if (depth > budget.maxDepth) { + throw new Error(`${FILE_LISTING_EXCEEDED_PREFIX} depth ${budget.maxDepth}`) + } +} + +export function consumeQuickOpenReaddirPathBudget( + budget: QuickOpenReaddirBudget, + path: string +): void { + if (path.length > budget.remainingPathCodeUnits) { + throw new Error(`${FILE_LISTING_EXCEEDED_PREFIX} ${budget.maxPathCodeUnits} path code units`) + } + budget.remainingPathCodeUnits -= path.length +} diff --git a/src/shared/quick-open-readdir-memory.test.ts b/src/shared/quick-open-readdir-memory.test.ts new file mode 100644 index 000000000..4929f33dc --- /dev/null +++ b/src/shared/quick-open-readdir-memory.test.ts @@ -0,0 +1,92 @@ +import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, describe, expect, it } from 'vitest' +import { + createQuickOpenReaddirBudget, + listQuickOpenFilesWithReaddir +} from './quick-open-readdir-walk' + +const tempRoots: string[] = [] + +async function makeRoot(): Promise { + const root = await mkdtemp(join(tmpdir(), 'orca-quick-open-budget-')) + tempRoots.push(root) + return root +} + +afterEach(async () => { + await Promise.all(tempRoots.splice(0).map((root) => rm(root, { recursive: true, force: true }))) +}) + +describe('quick-open readdir memory limits', () => { + it('accepts the exact entry limit and rejects the next zero-file entry', async () => { + const root = await makeRoot() + await mkdir(join(root, 'a')) + await mkdir(join(root, 'b')) + + await expect( + listQuickOpenFilesWithReaddir(root, { + budget: createQuickOpenReaddirBudget({ maxEntries: 2 }) + }) + ).resolves.toEqual([]) + + await mkdir(join(root, 'c')) + await expect( + listQuickOpenFilesWithReaddir(root, { + budget: createQuickOpenReaddirBudget({ maxEntries: 2 }) + }) + ).rejects.toThrow('File listing exceeded 2 entries') + }) + + it('caps retained directory paths even when the tree contains no files', async () => { + const root = await makeRoot() + await mkdir(join(root, 'a')) + await mkdir(join(root, 'b')) + + await expect( + listQuickOpenFilesWithReaddir(root, { + budget: createQuickOpenReaddirBudget({ maxDirectories: 3 }) + }) + ).resolves.toEqual([]) + await expect( + listQuickOpenFilesWithReaddir(root, { + budget: createQuickOpenReaddirBudget({ maxDirectories: 2 }) + }) + ).rejects.toThrow('File listing exceeded 2 directories') + }) + + it('accepts the exact depth limit and rejects a deeper directory', async () => { + const root = await makeRoot() + await mkdir(join(root, 'a', 'b'), { recursive: true }) + + await expect( + listQuickOpenFilesWithReaddir(root, { + budget: createQuickOpenReaddirBudget({ maxDepth: 2 }) + }) + ).resolves.toEqual([]) + await expect( + listQuickOpenFilesWithReaddir(root, { + budget: createQuickOpenReaddirBudget({ maxDepth: 1 }) + }) + ).rejects.toThrow('File listing exceeded depth 1') + }) + + it('bounds aggregate path storage without changing exact-boundary output', async () => { + const root = await makeRoot() + const fileName = 'a.ts' + await writeFile(join(root, fileName), 'x') + const exactPathCodeUnits = root.length + fileName.length * 2 + + await expect( + listQuickOpenFilesWithReaddir(root, { + budget: createQuickOpenReaddirBudget({ maxPathCodeUnits: exactPathCodeUnits }) + }) + ).resolves.toEqual([fileName]) + await expect( + listQuickOpenFilesWithReaddir(root, { + budget: createQuickOpenReaddirBudget({ maxPathCodeUnits: exactPathCodeUnits - 1 }) + }) + ).rejects.toThrow(`File listing exceeded ${exactPathCodeUnits - 1} path code units`) + }) +}) diff --git a/src/shared/quick-open-readdir-walk.test.ts b/src/shared/quick-open-readdir-walk.test.ts index e6894bd81..1c3ae1adf 100644 --- a/src/shared/quick-open-readdir-walk.test.ts +++ b/src/shared/quick-open-readdir-walk.test.ts @@ -1,18 +1,18 @@ import { afterEach, describe, expect, it, vi } from 'vitest' -const { lstatMock, readdirMock } = vi.hoisted(() => ({ +const { lstatMock, opendirMock } = vi.hoisted(() => ({ lstatMock: vi.fn(), - readdirMock: vi.fn() + opendirMock: vi.fn() })) vi.mock('fs/promises', async () => { const actual = await vi.importActual('fs/promises') // eslint-disable-line @typescript-eslint/consistent-type-imports -- vi.importActual requires inline import() lstatMock.mockImplementation(actual.lstat) - readdirMock.mockImplementation(actual.readdir) + opendirMock.mockImplementation(actual.opendir) return { ...actual, lstat: lstatMock, - readdir: readdirMock + opendir: opendirMock } }) @@ -238,7 +238,7 @@ describe('quick-open readdir walk', () => { }) ).resolves.toEqual(['.local/config.toml', 'dist/generated.js']) - const walkedPaths = readdirMock.mock.calls.map(([path]) => path) + const walkedPaths = opendirMock.mock.calls.map(([path]) => path) expect(walkedPaths).toContain(join(root, 'dist')) expect(walkedPaths).toContain(join(root, '.local')) expect(walkedPaths).not.toContain(join(root, '.local', 'share')) @@ -256,12 +256,12 @@ describe('quick-open readdir walk', () => { const actual = await vi.importActual('node:fs/promises') // eslint-disable-line @typescript-eslint/consistent-type-imports -- vi.importActual requires inline import() let activeReads = 0 let maxActiveReads = 0 - readdirMock.mockImplementation(async (...args: Parameters) => { + opendirMock.mockImplementation(async (...args: Parameters) => { activeReads++ maxActiveReads = Math.max(maxActiveReads, activeReads) await new Promise((resolve) => setTimeout(resolve, 5)) try { - return await actual.readdir(...args) + return await actual.opendir(...args) } finally { activeReads-- } @@ -277,7 +277,7 @@ describe('quick-open readdir walk', () => { expect(maxActiveReads).toBeGreaterThan(1) expect(maxActiveReads).toBeLessThanOrEqual(32) } finally { - readdirMock.mockImplementation(actual.readdir) + opendirMock.mockImplementation(actual.opendir) } }) @@ -328,7 +328,7 @@ describe('quick-open readdir walk', () => { ).resolves.toEqual([]) }) - it('discards entries when a collapsed directory changes during readdir', async () => { + it('discards entries when a collapsed directory changes during opendir', async () => { const root = await makeTempRoot() const outsideRoot = await makeTempRoot() await mkdirRel(root, 'dist') @@ -336,13 +336,13 @@ describe('quick-open readdir walk', () => { const actual = await vi.importActual('node:fs/promises') // eslint-disable-line @typescript-eslint/consistent-type-imports -- vi.importActual requires inline import() const distPath = join(root, 'dist') let swapped = false - readdirMock.mockImplementation(async (...args: Parameters) => { + opendirMock.mockImplementation(async (...args: Parameters) => { if (!swapped && args[0] === distPath) { swapped = true await rename(distPath, join(root, 'old-dist')) await symlink(outsideRoot, distPath, 'dir') } - return actual.readdir(...args) + return actual.opendir(...args) }) try { @@ -354,7 +354,7 @@ describe('quick-open readdir walk', () => { }) ).resolves.toEqual([]) } finally { - readdirMock.mockImplementation(actual.readdir) + opendirMock.mockImplementation(actual.opendir) } }) @@ -373,7 +373,7 @@ describe('quick-open readdir walk', () => { ).resolves.toEqual(['foo/a.ts', 'foo/bar/b.ts']) expect( - readdirMock.mock.calls.filter(([path]) => path === join(root, 'foo', 'bar')) + opendirMock.mock.calls.filter(([path]) => path === join(root, 'foo', 'bar')) ).toHaveLength(1) }) @@ -395,14 +395,18 @@ describe('quick-open readdir walk', () => { it('keeps the default safety cap for a very large collapsed directory', async () => { const root = await makeTempRoot() await mkdirRel(root, 'dist') - readdirMock.mockResolvedValueOnce( - Array.from({ length: QUICK_OPEN_READDIR_MAX_FILES + 1 }, (_, index) => ({ - name: `file-${index}.ts`, - isDirectory: () => false, - isFile: () => true, - isSymbolicLink: () => false - })) - ) + opendirMock.mockResolvedValueOnce({ + async *[Symbol.asyncIterator]() { + for (let index = 0; index <= QUICK_OPEN_READDIR_MAX_FILES; index += 1) { + yield { + name: `file-${index}.ts`, + isDirectory: () => false, + isFile: () => true, + isSymbolicLink: () => false + } + } + } + }) // Why: directory collapse prevents generated trees from flooding the relay; // the Git fallback must reject rather than silently return a partial list. @@ -429,7 +433,7 @@ describe('quick-open readdir walk', () => { await expect( listQuickOpenFilesWithReaddir(root, { - budget: { remainingFiles: 10, deadlineMs: Date.now() - 1_000 } + budget: createQuickOpenReaddirBudget({ nowMs: Date.now() - 2_000, timeoutMs: 1_000 }) }) ).rejects.toThrow('File listing timed out') }) @@ -529,12 +533,12 @@ describe('quick-open readdir walk', () => { ).rejects.toSatisfy(isFileListingCancellation) }) - it('rejects when cancellation lands during an empty readdir batch', async () => { + it('rejects when cancellation lands during an empty opendir batch', async () => { const root = await makeTempRoot() const controller = new AbortController() const actual = await vi.importActual('node:fs/promises') // eslint-disable-line @typescript-eslint/consistent-type-imports -- vi.importActual requires inline import() - readdirMock.mockImplementationOnce(async (...args: Parameters) => { - const entries = await actual.readdir(...args) + opendirMock.mockImplementationOnce(async (...args: Parameters) => { + const entries = await actual.opendir(...args) controller.abort() return entries }) diff --git a/src/shared/quick-open-readdir-walk.ts b/src/shared/quick-open-readdir-walk.ts index fbbb24963..2fcdbb843 100644 --- a/src/shared/quick-open-readdir-walk.ts +++ b/src/shared/quick-open-readdir-walk.ts @@ -1,55 +1,44 @@ -import { lstat, readdir } from 'node:fs/promises' import { join, relative } from 'node:path' import { throwIfFileListingCancelled } from './file-listing-cancellation' -import { isQuickOpenReadableDirectory } from './quick-open-directory-validation' +import { readQuickOpenDirectoryEntries } from './quick-open-directory-reader' import { collapseQuickOpenExpansionPaths } from './quick-open-expansion-paths' +import { classifyQuickOpenGitEntry } from './quick-open-git-entry-classification' import { HIDDEN_DIR_BLOCKLIST, shouldExcludeQuickOpenRelPath, shouldIncludeQuickOpenPath } from './quick-open-filter' import { + assertQuickOpenReaddirDepth, assertQuickOpenReaddirDeadline, + consumeQuickOpenReaddirDirectoryBudget, + consumeQuickOpenReaddirEntryBudget, consumeQuickOpenReaddirFileBudget, + consumeQuickOpenReaddirPathBudget, createQuickOpenReaddirBudget, type QuickOpenReaddirBudget } from './quick-open-readdir-budget' +export { + classifyQuickOpenGitEntry, + parseQuickOpenGitLsFilesEntry, + type QuickOpenGitEntryKind, + type QuickOpenGitLsFilesEntry +} from './quick-open-git-entry-classification' + export { createQuickOpenReaddirBudget, isQuickOpenReaddirBudgetError, + QUICK_OPEN_READDIR_MAX_DEPTH, + QUICK_OPEN_READDIR_MAX_DIRECTORIES, + QUICK_OPEN_READDIR_MAX_ENTRIES, QUICK_OPEN_READDIR_MAX_FILES, + QUICK_OPEN_READDIR_MAX_PATH_CODE_UNITS, QUICK_OPEN_READDIR_TIMEOUT_MS } from './quick-open-readdir-budget' const QUICK_OPEN_READDIR_CONCURRENCY = 32 -export type QuickOpenGitEntryKind = 'keep' | 'fill-nested-repo' | 'drop-placeholder' - -export type QuickOpenGitLsFilesEntry = { - path: string - isGitlink: boolean - isUntrackedDir: boolean -} - -const GIT_LS_FILES_STAGE_ENTRY = /^([0-7]{6}) [0-9a-f]{40,64} [0-3]\t/ - -export function parseQuickOpenGitLsFilesEntry(entry: string): QuickOpenGitLsFilesEntry { - const match = GIT_LS_FILES_STAGE_ENTRY.exec(entry) - if (match) { - return { - path: entry.slice(match[0].length), - isGitlink: match[1] === '160000', - isUntrackedDir: false - } - } - return { - path: entry, - isGitlink: false, - isUntrackedDir: entry.endsWith('/') - } -} - function shouldDescend(name: string): boolean { return name !== 'node_modules' && !HIDDEN_DIR_BLOCKLIST.has(name) } @@ -85,47 +74,6 @@ function rebaseExcludePrefixesForSubtree( return rebased } -async function hasGitEntry(absPath: string): Promise { - try { - const stat = await lstat(join(absPath, '.git')) - return stat.isDirectory() || stat.isFile() - } catch { - return false - } -} - -export async function classifyQuickOpenGitEntry( - rootPath: string, - entry: string -): Promise<{ kind: QuickOpenGitEntryKind; relPath: string }> { - const parsed = parseQuickOpenGitLsFilesEntry(entry) - const relPath = normalizeGitEntry(parsed.path) - if (!relPath) { - return { kind: 'drop-placeholder', relPath } - } - - if (!parsed.isGitlink && !parsed.isUntrackedDir) { - return { kind: 'keep', relPath } - } - - let stat - try { - stat = await lstat(joinRootRel(rootPath, relPath)) - } catch { - return { kind: 'drop-placeholder', relPath } - } - - if (!stat.isDirectory()) { - return { kind: 'drop-placeholder', relPath } - } - - if (await hasGitEntry(joinRootRel(rootPath, relPath))) { - return { kind: 'fill-nested-repo', relPath } - } - - return { kind: 'drop-placeholder', relPath } -} - export async function listQuickOpenFilesWithReaddir( rootPath: string, opts: { @@ -164,17 +112,25 @@ async function listQuickOpenFilesFromRoots( roots: readonly QuickOpenReaddirRoot[], budget: QuickOpenReaddirBudget, signal?: AbortSignal, - maxResults?: number + maxResults?: number, + knownFiles?: ReadonlySet ): Promise { const files: string[] = [] if (maxResults !== undefined && maxResults <= 0) { return files } - let pendingDirectories = roots.map((root) => ({ - root, - absPath: root.rootPath, - isRoot: true - })) + let pendingDirectories: { + root: QuickOpenReaddirRoot + absPath: string + depth: number + isRoot: boolean + }[] = [] + for (const root of roots) { + assertQuickOpenReaddirDepth(budget, 0) + consumeQuickOpenReaddirDirectoryBudget(budget) + consumeQuickOpenReaddirPathBudget(budget, root.rootPath) + pendingDirectories.push({ root, absPath: root.rootPath, depth: 0, isRoot: true }) + } while (pendingDirectories.length > 0) { const nextDirectories: typeof pendingDirectories = [] @@ -189,32 +145,29 @@ async function listQuickOpenFilesFromRoots( throwIfFileListingCancelled(signal) assertQuickOpenReaddirDeadline(budget) const batch = pendingDirectories.slice(offset, offset + QUICK_OPEN_READDIR_CONCURRENCY) - const entryGroups = await Promise.all( + const readResults = await Promise.allSettled( batch.map(async (pending) => { - try { - // Why: Git's placeholder may have been replaced with a symlink - // before expansion. Never let readdir follow it outside the root. - const stat = await lstat(pending.absPath) - const allowSymlinkedRoot = pending.isRoot && pending.root.allowRootSymlink - if (!isQuickOpenReadableDirectory(stat, allowSymlinkedRoot)) { - return { pending, entries: [] } - } - const entries = await readdir(pending.absPath, { withFileTypes: true }) - // Why: close the ordinary check/use race. If the directory became - // a symlink while readdir was pending, discard everything read. - const statAfterRead = await lstat(pending.absPath) - if (!isQuickOpenReadableDirectory(statAfterRead, allowSymlinkedRoot)) { - return { pending, entries: [] } - } - return { pending, entries } - } catch { - // Why: permission denied on one subtree is common for broad roots. - return { pending, entries: [] } - } + const entries = await readQuickOpenDirectoryEntries({ + absPath: pending.absPath, + allowSymlinkedRoot: Boolean(pending.isRoot && pending.root.allowRootSymlink), + budget, + signal + }) + return { pending, entries } }) ) + const entryGroups: { + pending: (typeof pendingDirectories)[number] + entries: Awaited> + }[] = [] + for (const result of readResults) { + if (result.status === 'rejected') { + throw result.reason + } + entryGroups.push(result.value) + } // Why: an empty directory has no per-entry checkpoint below. Cancellation - // or timeout that lands during readdir must still reject, never resolve []. + // or timeout that lands during opendir must still reject, never resolve []. throwIfFileListingCancelled(signal) assertQuickOpenReaddirDeadline(budget) @@ -232,22 +185,29 @@ async function listQuickOpenFilesFromRoots( if (shouldExcludeQuickOpenRelPath(relPath, pending.root.excludePathPrefixes)) { continue } - if (entry.isDirectory()) { + if (entry.kind === 'directory') { if (shouldDescend(name) && shouldIncludeQuickOpenPath(workspaceRelPath)) { - nextDirectories.push({ root: pending.root, absPath, isRoot: false }) + const depth = pending.depth + 1 + assertQuickOpenReaddirDepth(budget, depth) + consumeQuickOpenReaddirDirectoryBudget(budget) + consumeQuickOpenReaddirPathBudget(budget, absPath) + nextDirectories.push({ root: pending.root, absPath, depth, isRoot: false }) } continue } if ( - (entry.isFile() || (pending.root.includeSymlinks && entry.isSymbolicLink())) && + (entry.kind === 'file' || (pending.root.includeSymlinks && entry.kind === 'symlink')) && shouldIncludeQuickOpenPath(workspaceRelPath) ) { + const outputPath = pending.root.outputPathPrefix + ? `${pending.root.outputPathPrefix}/${relPath}` + : relPath + if (knownFiles?.has(outputPath)) { + continue + } consumeQuickOpenReaddirFileBudget(budget) - files.push( - pending.root.outputPathPrefix - ? `${pending.root.outputPathPrefix}/${relPath}` - : relPath - ) + consumeQuickOpenReaddirPathBudget(budget, outputPath) + files.push(outputPath) // Why: a caller result limit is a successful bounded prefix, while // the separate traversal budget still rejects incomplete scans. if (maxResults !== undefined && files.length >= maxResults) { @@ -272,6 +232,9 @@ export async function expandQuickOpenGitFileListing(opts: { maxResults?: number signal?: AbortSignal }): Promise { + if (opts.maxResults !== undefined && opts.maxResults <= 0) { + return [] + } const files = new Set() const excludePathPrefixes = opts.excludePathPrefixes ?? [] const budget = opts.budget ?? createQuickOpenReaddirBudget() @@ -302,6 +265,8 @@ export async function expandQuickOpenGitFileListing(opts: { continue } + consumeQuickOpenReaddirEntryBudget(budget) + consumeQuickOpenReaddirPathBudget(budget, relPath) expansionPaths.set(relPath, expansionPaths.get(relPath) ?? false) } @@ -320,6 +285,8 @@ export async function expandQuickOpenGitFileListing(opts: { continue } + consumeQuickOpenReaddirEntryBudget(budget) + consumeQuickOpenReaddirPathBudget(budget, relPath) // Why: before directory collapse, Git returned untracked symlink entries // without following them. Preserve those paths when expanding placeholders. expansionPaths.set(relPath, true) @@ -339,7 +306,8 @@ export async function expandQuickOpenGitFileListing(opts: { })), budget, opts.signal, - opts.maxResults === undefined ? undefined : Math.max(0, opts.maxResults - files.size) + opts.maxResults === undefined ? undefined : Math.max(0, opts.maxResults - files.size), + files ) for (const expandedFile of expandedFiles) { addFinalPath(expandedFile) diff --git a/src/shared/relay-json-admission.ts b/src/shared/relay-json-admission.ts new file mode 100644 index 000000000..a9d256ba9 --- /dev/null +++ b/src/shared/relay-json-admission.ts @@ -0,0 +1,12 @@ +import { assertJsonTextStructureWithinLimits } from './json-text-structure-limit' + +export const RELAY_JSON_MAX_STRUCTURAL_TOKENS = 1_000_000 +export const RELAY_JSON_MAX_NESTING_DEPTH = 128 + +export function parseRelayJsonText(text: string): T { + assertJsonTextStructureWithinLimits(text, { + structuralTokens: RELAY_JSON_MAX_STRUCTURAL_TOKENS, + nestingDepth: RELAY_JSON_MAX_NESTING_DEPTH + }) + return JSON.parse(text) as T +} diff --git a/src/shared/relay-version-marker.test.ts b/src/shared/relay-version-marker.test.ts new file mode 100644 index 000000000..369553995 --- /dev/null +++ b/src/shared/relay-version-marker.test.ts @@ -0,0 +1,40 @@ +import { mkdtempSync, rmSync, truncateSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, describe, expect, it } from 'vitest' +import { NodeFileReadTooLargeError } from './node-bounded-file-reader' +import { RELAY_VERSION_MARKER_MAX_BYTES, readRelayVersionMarkerSync } from './relay-version-marker' + +const roots: string[] = [] + +function createVersionFile(contents: string): string { + const root = mkdtempSync(join(tmpdir(), 'orca-relay-version-marker-')) + roots.push(root) + const filePath = join(root, '.version') + writeFileSync(filePath, contents) + return filePath +} + +afterEach(() => { + for (const root of roots.splice(0)) { + rmSync(root, { recursive: true, force: true }) + } +}) + +describe('relay version marker', () => { + it('accepts a trimmed marker at the exact byte boundary', () => { + const version = '1.2.3+deadbeef' + const filePath = createVersionFile( + version + ' '.repeat(RELAY_VERSION_MARKER_MAX_BYTES - Buffer.byteLength(version)) + ) + + expect(readRelayVersionMarkerSync(filePath)).toBe(version) + }) + + it('rejects a sparse marker one byte over the boundary', () => { + const filePath = createVersionFile('1.2.3') + truncateSync(filePath, RELAY_VERSION_MARKER_MAX_BYTES + 1) + + expect(() => readRelayVersionMarkerSync(filePath)).toThrow(NodeFileReadTooLargeError) + }) +}) diff --git a/src/shared/relay-version-marker.ts b/src/shared/relay-version-marker.ts new file mode 100644 index 000000000..68be008ff --- /dev/null +++ b/src/shared/relay-version-marker.ts @@ -0,0 +1,9 @@ +import { readNodeFileSyncWithinLimit } from './node-bounded-file-reader' + +export const RELAY_VERSION_MARKER_MAX_BYTES = 4 * 1024 + +export function readRelayVersionMarkerSync(versionFile: string): string { + return readNodeFileSyncWithinLimit(versionFile, RELAY_VERSION_MARKER_MAX_BYTES) + .buffer.toString('utf8') + .trim() +} diff --git a/src/shared/remote-runtime-client.ts b/src/shared/remote-runtime-client.ts index 15ec38e40..b82f515a0 100644 --- a/src/shared/remote-runtime-client.ts +++ b/src/shared/remote-runtime-client.ts @@ -24,6 +24,18 @@ import { // unaffected; the class lives in a ws-free module so type-only consumers // (and mobile's typecheck) don't compile this file's Node-only deps. import { RemoteRuntimeClientError } from './remote-runtime-client-error' +import { + isRemoteRuntimeBinaryFrameWithinLimit, + REMOTE_RUNTIME_MAX_WEBSOCKET_FRAME_BYTES, + serializeRemoteRuntimePayload, + serializeRemoteRuntimeRpcRequest +} from './remote-runtime-memory-limits' +import { + prepareRemoteRuntimeRequest, + releaseRemoteRuntimePreparedRequest, + takeRemoteRuntimePreparedRequest +} from './remote-runtime-prepared-request-admission' +import { parseRemoteRuntimeJsonText } from './remote-runtime-request-frames' import { startRemoteRuntimeSocketLiveness, type RemoteRuntimeSocketLivenessMonitor, @@ -70,8 +82,23 @@ export async function sendRemoteRuntimeRequest( params: unknown, timeoutMs: number ): Promise> { - return await new Promise((resolve, reject) => { - const requestId = randomUUID() + const requestId = randomUUID() + const serializedAuth = serializeRemoteRuntimePayload({ + type: 'e2ee_auth', + deviceToken: pairing.deviceToken + }) + const pendingRequest = { + preparedRequest: prepareRemoteRuntimeRequest(new Map(), () => + serializeRemoteRuntimeRpcRequest({ + requestId, + deviceToken: pairing.deviceToken, + method, + params + }) + ) + } + let serializedRequest = takeRemoteRuntimePreparedRequest(pendingRequest) + return await new Promise>((resolve, reject) => { const keyPair = generateKeyPair() const serverPublicKey = publicKeyFromBase64(pairing.publicKeyB64) const sharedKey = deriveSharedKey(keyPair.secretKey, serverPublicKey) @@ -141,7 +168,7 @@ export async function sendRemoteRuntimeRequest( } try { - ws = new WebSocket(pairing.endpoint) + ws = new WebSocket(pairing.endpoint, { maxPayload: REMOTE_RUNTIME_MAX_WEBSOCKET_FRAME_BYTES }) } catch (error) { const message = error instanceof Error ? error.message : String(error) finish({ @@ -234,7 +261,7 @@ export async function sendRemoteRuntimeRequest( function handleReadyFrame(frame: string): void { let ready: unknown try { - ready = JSON.parse(frame) + ready = parseRemoteRuntimeJsonText(frame) } catch { finish({ ok: false, @@ -260,15 +287,13 @@ export async function sendRemoteRuntimeRequest( return } state = 'awaiting_authenticated' - ws?.send( - encrypt(JSON.stringify({ type: 'e2ee_auth', deviceToken: pairing.deviceToken }), sharedKey) - ) + ws?.send(encrypt(serializedAuth, sharedKey)) } function handleAuthenticatedFrame(plaintext: string): void { let authenticated: unknown try { - authenticated = JSON.parse(plaintext) + authenticated = parseRemoteRuntimeJsonText(plaintext) } catch { finish({ ok: false, @@ -297,23 +322,25 @@ export async function sendRemoteRuntimeRequest( return } state = 'ready' - ws?.send( - encrypt( - JSON.stringify({ - id: requestId, - deviceToken: pairing.deviceToken, - method, - params - }), - sharedKey - ) - ) + const request = serializedRequest + serializedRequest = null + if (request === null) { + finish({ + ok: false, + error: new RemoteRuntimeClientError( + 'remote_runtime_unavailable', + 'Remote Orca runtime request was released before it could be sent.' + ) + }) + return + } + ws?.send(encrypt(request, sharedKey)) } function handleRpcFrame(plaintext: string): void { let raw: unknown try { - raw = JSON.parse(plaintext) + raw = parseRemoteRuntimeJsonText(plaintext) } catch { finish({ ok: false, @@ -352,7 +379,7 @@ export async function sendRemoteRuntimeRequest( } finish({ ok: true, response }) } - }) + }).finally(() => releaseRemoteRuntimePreparedRequest(pendingRequest)) } export async function subscribeRemoteRuntimeRequest( @@ -363,8 +390,18 @@ export async function subscribeRemoteRuntimeRequest( callbacks: RemoteRuntimeSubscriptionCallbacks, livenessOptions?: RemoteRuntimeSocketLivenessOptions ): Promise { + const requestId = randomUUID() + const serializedRequest = serializeRemoteRuntimeRpcRequest({ + requestId, + deviceToken: pairing.deviceToken, + method, + params + }) + const serializedAuth = serializeRemoteRuntimePayload({ + type: 'e2ee_auth', + deviceToken: pairing.deviceToken + }) return await new Promise((resolve, reject) => { - const requestId = randomUUID() const keyPair = generateKeyPair() const serverPublicKey = publicKeyFromBase64(pairing.publicKeyB64) const sharedKey = deriveSharedKey(keyPair.secretKey, serverPublicKey) @@ -450,7 +487,12 @@ export async function subscribeRemoteRuntimeRequest( } const sendBinary = (bytes: Uint8Array): boolean => { - if (state !== 'ready' || !ws || ws.readyState !== WebSocket.OPEN) { + if ( + !isRemoteRuntimeBinaryFrameWithinLimit(bytes) || + state !== 'ready' || + !ws || + ws.readyState !== WebSocket.OPEN + ) { return false } ensureSendQueue(ws).enqueue(Buffer.from(encryptBytes(bytes, sharedKey))) @@ -483,7 +525,7 @@ export async function subscribeRemoteRuntimeRequest( } try { - ws = new WebSocket(pairing.endpoint) + ws = new WebSocket(pairing.endpoint, { maxPayload: REMOTE_RUNTIME_MAX_WEBSOCKET_FRAME_BYTES }) } catch (error) { const message = error instanceof Error ? error.message : String(error) fail(new RemoteRuntimeClientError('invalid_argument', `Invalid remote endpoint: ${message}`)) @@ -600,7 +642,7 @@ export async function subscribeRemoteRuntimeRequest( function handleReadyFrame(frame: string): void { let ready: unknown try { - ready = JSON.parse(frame) + ready = parseRemoteRuntimeJsonText(frame) } catch { fail( new RemoteRuntimeClientError( @@ -624,15 +666,13 @@ export async function subscribeRemoteRuntimeRequest( return } state = 'awaiting_authenticated' - ws?.send( - encrypt(JSON.stringify({ type: 'e2ee_auth', deviceToken: pairing.deviceToken }), sharedKey) - ) + ws?.send(encrypt(serializedAuth, sharedKey)) } function handleAuthenticatedFrame(plaintext: string): void { let authenticated: unknown try { - authenticated = JSON.parse(plaintext) + authenticated = parseRemoteRuntimeJsonText(plaintext) } catch { fail( new RemoteRuntimeClientError( @@ -654,24 +694,14 @@ export async function subscribeRemoteRuntimeRequest( return } state = 'ready' - ws?.send( - encrypt( - JSON.stringify({ - id: requestId, - deviceToken: pairing.deviceToken, - method, - params - }), - sharedKey - ) - ) + ws?.send(encrypt(serializedRequest, sharedKey)) succeed() } function handleRpcFrame(plaintext: string): void { let raw: unknown try { - raw = JSON.parse(plaintext) + raw = parseRemoteRuntimeJsonText(plaintext) } catch { fail( new RemoteRuntimeClientError( diff --git a/src/shared/remote-runtime-outbound-admission.test.ts b/src/shared/remote-runtime-outbound-admission.test.ts new file mode 100644 index 000000000..f536549ca --- /dev/null +++ b/src/shared/remote-runtime-outbound-admission.test.ts @@ -0,0 +1,371 @@ +import type { AddressInfo } from 'node:net' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { WebSocketServer } from 'ws' +import { generateKeyPair, publicKeyToBase64 } from './e2ee-crypto' +import { encodePairingOffer, parsePairingCode, type PairingOffer } from './pairing' +import { sendRemoteRuntimeRequest, subscribeRemoteRuntimeRequest } from './remote-runtime-client' +import { + REMOTE_RUNTIME_MAX_PENDING_REQUESTS, + REMOTE_RUNTIME_MAX_PENDING_RPC_BYTES, + REMOTE_RUNTIME_MAX_PROCESS_PENDING_REQUESTS, + REMOTE_RUNTIME_MAX_PROCESS_PENDING_RPC_BYTES, + REMOTE_RUNTIME_MAX_READY_WAITERS, + REMOTE_RUNTIME_MAX_OUTBOUND_JSON_BYTES, + REMOTE_RUNTIME_MAX_RETAINED_SUBSCRIPTION_BYTES, + REMOTE_RUNTIME_MAX_SUBSCRIPTIONS, + retainedRemoteRuntimeJsonStringBytes, + serializeRemoteRuntimeRpcRequest +} from './remote-runtime-memory-limits' +import { getRemoteRuntimeRequestAdmissionEvidence } from './remote-runtime-prepared-request-admission' +import { RemoteRuntimeRequestConnection } from './remote-runtime-request-connection' +import { RemoteRuntimeSharedControlConnection } from './remote-runtime-shared-control-connection' +import { waitForSharedControlReadyWithTimeout } from './remote-runtime-shared-control-ready' + +type InspectableRequestConnection = { + close: () => void + request: (method: string, params: unknown, timeoutMs: number) => Promise +} + +type RequestAdmissionState = { + pendingRequests: Map< + string, + { preparedRequest?: { retainedBytes: number; serializedRequest?: string | null } | null } + > + readyWaiters: unknown[] +} + +const servers: WebSocketServer[] = [] + +afterEach(async () => { + await Promise.all( + servers.splice(0).map( + (server) => + new Promise((resolve) => { + for (const client of server.clients) { + client.close() + } + server.close(() => resolve()) + }) + ) + ) + expect(getRemoteRuntimeRequestAdmissionEvidence()).toEqual({ + pendingRequestCount: 0, + retainedBytes: 0 + }) +}) + +describe('remote runtime outbound admission', () => { + it('rejects oversized requests before opening any desktop transport socket', async () => { + const { pairing, server } = await createServer() + const oversizedParams = { value: 'x'.repeat(REMOTE_RUNTIME_MAX_OUTBOUND_JSON_BYTES) } + const cached = new RemoteRuntimeRequestConnection(pairing) + const shared = new RemoteRuntimeSharedControlConnection(pairing) + + await expect( + sendRemoteRuntimeRequest(pairing, 'status.get', oversizedParams, 1000) + ).rejects.toThrow('JSON payload exceeds') + await expect(cached.request('status.get', oversizedParams, 1000)).rejects.toThrow( + 'JSON payload exceeds' + ) + await expect(shared.request('status.get', oversizedParams, 1000)).rejects.toThrow( + 'JSON payload exceeds' + ) + await expect( + subscribeRemoteRuntimeRequest(pairing, 'terminal.subscribe', oversizedParams, 1000, { + onResponse: vi.fn(), + onError: vi.fn() + }) + ).rejects.toThrow('JSON payload exceeds') + + await new Promise((resolve) => setTimeout(resolve, 10)) + expect(server.clients.size).toBe(0) + cached.close() + shared.close() + }) + + it('rejects shared-control subscription count and byte overload before connecting', async () => { + const { pairing, server } = await createServer() + const connection = new RemoteRuntimeSharedControlConnection(pairing) + const subscriptions = ( + connection as unknown as { + subscriptions: Map + } + ).subscriptions + for (let index = 0; index < REMOTE_RUNTIME_MAX_SUBSCRIPTIONS; index += 1) { + subscriptions.set(`subscription-${index}`, { retainedParamsBytes: 0 }) + } + + await expect( + connection.subscribe('files.watch', null, 1000, { + onResponse: vi.fn(), + onError: vi.fn() + }) + ).rejects.toThrow('subscription limit reached') + + subscriptions.clear() + subscriptions.set('aggregate', { + retainedParamsBytes: REMOTE_RUNTIME_MAX_RETAINED_SUBSCRIPTION_BYTES + }) + await expect( + connection.subscribe('files.watch', null, 1000, { + onResponse: vi.fn(), + onError: vi.fn() + }) + ).rejects.toThrow('subscription memory limit reached') + + expect(server.clients.size).toBe(0) + subscriptions.clear() + connection.close() + }) + + it('bounds aggregate prepared bytes across stalled one-shot sockets', async () => { + const { pairing, server } = await createServer() + const params = { value: 'x'.repeat(3 * 1024 * 1024) } + const retainedBytes = retainedRemoteRuntimeJsonStringBytes( + serializeRemoteRuntimeRpcRequest({ + requestId: '00000000-0000-4000-8000-000000000000', + deviceToken: pairing.deviceToken, + method: 'status.large', + params + }) + ) + const admittedCount = Math.floor(REMOTE_RUNTIME_MAX_PROCESS_PENDING_RPC_BYTES / retainedBytes) + const requests = Array.from({ length: admittedCount }, () => + sendRemoteRuntimeRequest(pairing, 'status.large', params, 60_000).catch(() => undefined) + ) + + await expect( + sendRemoteRuntimeRequest(pairing, 'status.overflow', params, 60_000) + ).rejects.toMatchObject({ code: 'remote_runtime_busy' }) + expect(getRemoteRuntimeRequestAdmissionEvidence().pendingRequestCount).toBe(admittedCount) + + await vi.waitFor(() => expect(server.clients.size).toBe(admittedCount)) + for (const client of server.clients) { + client.close() + } + await Promise.all(requests) + expect(getRemoteRuntimeRequestAdmissionEvidence()).toEqual({ + pendingRequestCount: 0, + retainedBytes: 0 + }) + }) + + it('bounds pending requests and ready waiters while both handshakes stall', async () => { + const { pairing } = await createServer() + const connections: InspectableRequestConnection[] = [ + new RemoteRuntimeRequestConnection(pairing), + new RemoteRuntimeSharedControlConnection(pairing) + ] + + for (const connection of connections) { + const requests = Array.from({ length: REMOTE_RUNTIME_MAX_PENDING_REQUESTS }, (_, index) => + connection.request(`status.${index}`, undefined, 60_000).catch(() => undefined) + ) + await expect(connection.request('status.overflow', undefined, 60_000)).rejects.toMatchObject({ + code: 'remote_runtime_busy' + }) + const state = connection as unknown as RequestAdmissionState + expect(state.pendingRequests.size).toBe(REMOTE_RUNTIME_MAX_PENDING_REQUESTS) + expect(state.readyWaiters).toHaveLength(REMOTE_RUNTIME_MAX_PENDING_REQUESTS) + + connection.close() + await Promise.all(requests) + expect(state.pendingRequests.size).toBe(0) + expect(state.readyWaiters).toHaveLength(0) + } + }) + + it('bounds aggregate prepared request text while both handshakes stall', async () => { + const { pairing } = await createServer() + const params = { value: 'x'.repeat(3 * 1024 * 1024) } + const retainedBytes = retainedRemoteRuntimeJsonStringBytes( + serializeRemoteRuntimeRpcRequest({ + requestId: '00000000-0000-4000-8000-000000000000', + deviceToken: pairing.deviceToken, + method: 'status.large', + params + }) + ) + const admittedCount = Math.floor(REMOTE_RUNTIME_MAX_PENDING_RPC_BYTES / retainedBytes) + expect(admittedCount).toBeGreaterThan(0) + + for (const connection of [ + new RemoteRuntimeRequestConnection(pairing), + new RemoteRuntimeSharedControlConnection(pairing) + ] satisfies InspectableRequestConnection[]) { + const requests = Array.from({ length: admittedCount }, () => + connection.request('status.large', params, 60_000).catch(() => undefined) + ) + await expect(connection.request('status.overflow', params, 60_000)).rejects.toMatchObject({ + code: 'remote_runtime_busy' + }) + const state = connection as unknown as RequestAdmissionState + const retainedTotal = Array.from(state.pendingRequests.values()).reduce( + (total, pending) => total + (pending.preparedRequest?.retainedBytes ?? 0), + 0 + ) + expect(retainedTotal).toBeLessThanOrEqual(REMOTE_RUNTIME_MAX_PENDING_RPC_BYTES) + + connection.close() + await Promise.all(requests) + expect(state.pendingRequests.size).toBe(0) + expect(state.readyWaiters).toHaveLength(0) + } + }) + + it('bounds pending request count across stalled environment connections', async () => { + const { pairing } = await createServer() + const connections: InspectableRequestConnection[] = [ + new RemoteRuntimeRequestConnection(pairing), + new RemoteRuntimeSharedControlConnection(pairing) + ] + const requests = Array.from( + { length: REMOTE_RUNTIME_MAX_PROCESS_PENDING_REQUESTS }, + (_, index) => + connections[index % connections.length]!.request( + `status.${index}`, + undefined, + 60_000 + ).catch(() => undefined) + ) + const overflow = new RemoteRuntimeRequestConnection(pairing) + + await expect(overflow.request('status.overflow', undefined, 60_000)).rejects.toMatchObject({ + code: 'remote_runtime_busy' + }) + await expect( + sendRemoteRuntimeRequest(pairing, 'status.one-shot-overflow', undefined, 60_000) + ).rejects.toMatchObject({ code: 'remote_runtime_busy' }) + expect(getRemoteRuntimeRequestAdmissionEvidence().pendingRequestCount).toBe( + REMOTE_RUNTIME_MAX_PROCESS_PENDING_REQUESTS + ) + + overflow.close() + connections.forEach((connection) => connection.close()) + await Promise.all(requests) + expect(getRemoteRuntimeRequestAdmissionEvidence()).toEqual({ + pendingRequestCount: 0, + retainedBytes: 0 + }) + }) + + it('releases one-shot process admission after a stalled handshake times out', async () => { + const { pairing } = await createServer() + const request = sendRemoteRuntimeRequest(pairing, 'status.timeout', undefined, 25) + + expect(getRemoteRuntimeRequestAdmissionEvidence().pendingRequestCount).toBe(1) + await expect(request).rejects.toMatchObject({ code: 'runtime_timeout' }) + expect(getRemoteRuntimeRequestAdmissionEvidence()).toEqual({ + pendingRequestCount: 0, + retainedBytes: 0 + }) + }) + + it('bounds retained request bytes across stalled environment connections', async () => { + const { pairing } = await createServer() + const params = { value: 'x'.repeat(1024 * 1024) } + const retainedBytes = retainedRemoteRuntimeJsonStringBytes( + serializeRemoteRuntimeRpcRequest({ + requestId: '00000000-0000-4000-8000-000000000000', + deviceToken: pairing.deviceToken, + method: 'status.large', + params + }) + ) + const admittedCount = Math.floor(REMOTE_RUNTIME_MAX_PROCESS_PENDING_RPC_BYTES / retainedBytes) + const connections: InspectableRequestConnection[] = [ + new RemoteRuntimeRequestConnection(pairing), + new RemoteRuntimeSharedControlConnection(pairing), + new RemoteRuntimeRequestConnection(pairing) + ] + expect(Math.ceil(admittedCount / connections.length) * retainedBytes).toBeLessThan( + REMOTE_RUNTIME_MAX_PENDING_RPC_BYTES + ) + const requests = Array.from({ length: admittedCount }, (_, index) => + connections[index % connections.length]!.request('status.large', params, 60_000).catch( + () => undefined + ) + ) + + await expect( + connections[admittedCount % connections.length]!.request('status.overflow', params, 60_000) + ).rejects.toMatchObject({ code: 'remote_runtime_busy' }) + const evidence = getRemoteRuntimeRequestAdmissionEvidence() + expect(evidence.pendingRequestCount).toBe(admittedCount) + expect(evidence.retainedBytes).toBeLessThanOrEqual(REMOTE_RUNTIME_MAX_PROCESS_PENDING_RPC_BYTES) + + connections.forEach((connection) => connection.close()) + await Promise.all(requests) + expect(getRemoteRuntimeRequestAdmissionEvidence()).toEqual({ + pendingRequestCount: 0, + retainedBytes: 0 + }) + }) + + it('releases pending state and ready waiters when stalled handshakes time out', async () => { + const { pairing } = await createServer() + + for (const connection of [ + new RemoteRuntimeRequestConnection(pairing), + new RemoteRuntimeSharedControlConnection(pairing) + ] satisfies InspectableRequestConnection[]) { + const request = connection.request('status.timeout', { value: 'x'.repeat(1024) }, 100) + const state = connection as unknown as RequestAdmissionState + expect(state.pendingRequests.size).toBe(1) + expect(state.readyWaiters).toHaveLength(1) + expect( + Array.from(state.pendingRequests.values())[0]?.preparedRequest?.retainedBytes + ).toBeGreaterThan(0) + + await expect(request).rejects.toBeInstanceOf(Error) + await vi.waitFor(() => expect(state.readyWaiters).toHaveLength(0)) + expect(state.pendingRequests.size).toBe(0) + connection.close() + } + }) + + it('rejects ready waiters beyond the combined request and subscription bound', async () => { + const readyWaiters: Parameters[0]['readyWaiters'] = + [] + const admitted = Array.from({ length: REMOTE_RUNTIME_MAX_READY_WAITERS }, () => + waitForSharedControlReadyWithTimeout({ + readyWaiters, + timeoutMs: 60_000, + open: () => undefined + }).catch(() => undefined) + ) + const open = vi.fn() + + await expect( + waitForSharedControlReadyWithTimeout({ readyWaiters, timeoutMs: 1000, open }) + ).rejects.toMatchObject({ code: 'remote_runtime_busy' }) + expect(readyWaiters).toHaveLength(REMOTE_RUNTIME_MAX_READY_WAITERS) + expect(open).not.toHaveBeenCalled() + + for (const waiter of readyWaiters.splice(0)) { + waiter.reject(new Error('test cleanup')) + } + await Promise.all(admitted) + expect(readyWaiters).toHaveLength(0) + }) +}) + +async function createServer(): Promise<{ pairing: PairingOffer; server: WebSocketServer }> { + const keyPair = generateKeyPair() + const server = new WebSocketServer({ port: 0 }) + servers.push(server) + await new Promise((resolve) => server.once('listening', resolve)) + const address = server.address() as AddressInfo + const pairing = parsePairingCode( + encodePairingOffer({ + v: 2, + endpoint: `ws://127.0.0.1:${address.port}`, + deviceToken: 'device-token', + publicKeyB64: publicKeyToBase64(keyPair.publicKey) + }) + ) + if (!pairing) { + throw new Error('Failed to create test pairing') + } + return { pairing, server } +} diff --git a/src/shared/remote-runtime-prepared-request-admission.ts b/src/shared/remote-runtime-prepared-request-admission.ts new file mode 100644 index 000000000..5584d4d51 --- /dev/null +++ b/src/shared/remote-runtime-prepared-request-admission.ts @@ -0,0 +1,123 @@ +import { RemoteRuntimeClientError } from './remote-runtime-client-error' +import { + REMOTE_RUNTIME_MAX_PENDING_REQUESTS, + REMOTE_RUNTIME_MAX_PENDING_RPC_BYTES, + REMOTE_RUNTIME_MAX_PROCESS_PENDING_REQUESTS, + REMOTE_RUNTIME_MAX_PROCESS_PENDING_RPC_BYTES, + retainedRemoteRuntimeJsonStringBytes +} from './remote-runtime-memory-limits' +import type { RuntimeRpcResponse } from './runtime-rpc-envelope' + +export type RemoteRuntimePreparedRequest = { + retainedBytes: number + serializedRequest: string | null + releaseProcessAdmission: () => void +} + +export type RemoteRuntimePendingRequest = { + resolve: (response: RuntimeRpcResponse) => void + reject: (error: Error) => void + timeout: ReturnType + preparedRequest: RemoteRuntimePreparedRequest | null +} + +type PendingPreparedRequest = { + preparedRequest?: RemoteRuntimePreparedRequest | null +} + +type ProcessRequestAdmission = { + retainedBytes: number +} + +const processRequestAdmissions = new Set() + +export function prepareRemoteRuntimeRequest( + pendingRequests: ReadonlyMap, + serialize: () => string +): RemoteRuntimePreparedRequest { + if ( + pendingRequests.size >= REMOTE_RUNTIME_MAX_PENDING_REQUESTS || + processRequestAdmissions.size >= REMOTE_RUNTIME_MAX_PROCESS_PENDING_REQUESTS + ) { + throw remoteRuntimeRequestBusyError() + } + const serializedRequest = serialize() + const retainedBytes = retainedRemoteRuntimeJsonStringBytes(serializedRequest) + let alreadyRetainedBytes = 0 + for (const pending of pendingRequests.values()) { + alreadyRetainedBytes += pending.preparedRequest?.retainedBytes ?? 0 + } + if (retainedBytes > REMOTE_RUNTIME_MAX_PENDING_RPC_BYTES - alreadyRetainedBytes) { + throw remoteRuntimeRequestBusyError() + } + const releaseProcessAdmission = reserveProcessRequestAdmission(retainedBytes) + if (!releaseProcessAdmission) { + throw remoteRuntimeRequestBusyError() + } + return { retainedBytes, serializedRequest, releaseProcessAdmission } +} + +export function takeRemoteRuntimePreparedRequest(pending: PendingPreparedRequest): string | null { + const prepared = pending.preparedRequest + if (!prepared || prepared.serializedRequest === null) { + return null + } + const serializedRequest = prepared.serializedRequest + prepared.serializedRequest = null + return serializedRequest +} + +export function releaseRemoteRuntimePreparedRequest(pending: PendingPreparedRequest): void { + const prepared = pending.preparedRequest + if (!prepared) { + return + } + prepared.serializedRequest = null + prepared.releaseProcessAdmission() + prepared.retainedBytes = 0 + pending.preparedRequest = null +} + +export function getRemoteRuntimeRequestAdmissionEvidence(): { + pendingRequestCount: number + retainedBytes: number +} { + let retainedBytes = 0 + for (const admission of processRequestAdmissions) { + retainedBytes += admission.retainedBytes + } + return { pendingRequestCount: processRequestAdmissions.size, retainedBytes } +} + +export function toRemoteRuntimeRequestError(error: unknown): Error { + if (error instanceof Error) { + return error + } + return new RemoteRuntimeClientError('runtime_error', String(error)) +} + +function remoteRuntimeRequestBusyError(): RemoteRuntimeClientError { + return new RemoteRuntimeClientError( + 'remote_runtime_busy', + 'Remote runtime request limit reached; retry after pending requests finish.' + ) +} + +function reserveProcessRequestAdmission(retainedBytes: number): (() => void) | null { + let alreadyRetainedBytes = 0 + for (const admission of processRequestAdmissions) { + alreadyRetainedBytes += admission.retainedBytes + } + if ( + processRequestAdmissions.size >= REMOTE_RUNTIME_MAX_PROCESS_PENDING_REQUESTS || + retainedBytes > REMOTE_RUNTIME_MAX_PROCESS_PENDING_RPC_BYTES - alreadyRetainedBytes + ) { + return null + } + const admission = { retainedBytes } + processRequestAdmissions.add(admission) + return () => { + admission.retainedBytes = 0 + processRequestAdmissions.delete(admission) + } +} diff --git a/src/shared/remote-runtime-request-connection-stale.test.ts b/src/shared/remote-runtime-request-connection-stale.test.ts index 765840b8e..aa5f6f897 100644 --- a/src/shared/remote-runtime-request-connection-stale.test.ts +++ b/src/shared/remote-runtime-request-connection-stale.test.ts @@ -2,6 +2,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' import WebSocket from 'ws' import type { PairingOffer } from './pairing' import { decrypt, encrypt } from './e2ee-crypto' +import { getRemoteRuntimeRequestAdmissionEvidence } from './remote-runtime-prepared-request-admission' import type { RemoteRuntimeWebSocketCallbacks } from './remote-runtime-request-websocket' const opens: FakeOpenedSocket[] = [] @@ -87,6 +88,33 @@ describe('RemoteRuntimeRequestConnection stale socket callbacks', () => { expect(socket.ws.close).toHaveBeenCalledTimes(1) }) + it('releases a pending request when the cached socket send throws', async () => { + const { RemoteRuntimeRequestConnection } = + await import('./remote-runtime-request-connection.js') + const connection = new RemoteRuntimeRequestConnection({ + v: 2, + endpoint: 'ws://127.0.0.1:6768', + deviceToken: 'device-token', + publicKeyB64: Buffer.from(new Uint8Array(32).fill(9)).toString('base64') + }) + const request = connection.request('status.get', undefined, 1000) + const socket = opens[0]! + authenticate(socket) + socket.ws.send = (() => { + throw new Error('send failed') + }) as WebSocket['send'] + + await expect(request).rejects.toThrow('send failed') + expect( + (connection as unknown as { pendingRequests: Map }).pendingRequests.size + ).toBe(0) + expect(getRemoteRuntimeRequestAdmissionEvidence()).toEqual({ + pendingRequestCount: 0, + retainedBytes: 0 + }) + connection.close() + }) + it('ignores stale socket errors and text frames after a replacement socket opens', async () => { vi.useFakeTimers() try { @@ -104,6 +132,10 @@ describe('RemoteRuntimeRequestConnection stale socket callbacks', () => { const firstRejected = expect(first).rejects.toThrow('Timed out') await vi.advanceTimersByTimeAsync(11) await firstRejected + expect(getRemoteRuntimeRequestAdmissionEvidence()).toEqual({ + pendingRequestCount: 0, + retainedBytes: 0 + }) const second = connection.request('status.get', undefined, 1000) authenticate(opens[1]!) @@ -133,6 +165,10 @@ describe('RemoteRuntimeRequestConnection stale socket callbacks', () => { ok: true, result: { state: 'ok' } }) + expect(getRemoteRuntimeRequestAdmissionEvidence()).toEqual({ + pendingRequestCount: 0, + retainedBytes: 0 + }) } finally { vi.useRealTimers() } diff --git a/src/shared/remote-runtime-request-connection.ts b/src/shared/remote-runtime-request-connection.ts index 7bd39f09f..00acb5492 100644 --- a/src/shared/remote-runtime-request-connection.ts +++ b/src/shared/remote-runtime-request-connection.ts @@ -3,7 +3,18 @@ import WebSocket from 'ws' import type { PairingOffer } from './pairing' import { decrypt, encrypt } from './e2ee-crypto' import type { RuntimeRpcResponse } from './runtime-rpc-envelope' -import { RemoteRuntimeClientError } from './remote-runtime-client' +import { + serializeRemoteRuntimePayload, + serializeRemoteRuntimeRpcRequest +} from './remote-runtime-memory-limits' +import { + prepareRemoteRuntimeRequest, + releaseRemoteRuntimePreparedRequest, + takeRemoteRuntimePreparedRequest, + toRemoteRuntimeRequestError, + type RemoteRuntimePendingRequest, + type RemoteRuntimePreparedRequest +} from './remote-runtime-prepared-request-admission' import { invalidRemoteRuntimeResponseError, parseAuthenticatedFrame, @@ -12,44 +23,49 @@ import { remoteRuntimeTimeoutError, remoteRuntimeUnavailableError } from './remote-runtime-request-frames' +import { + rejectRemoteRuntimeRequestReadyWaiters, + resolveRemoteRuntimeRequestReadyWaiters, + waitForRemoteRuntimeRequestReady, + type RemoteRuntimeRequestReadyWaiter +} from './remote-runtime-request-ready-waiters' import { openRemoteRuntimeWebSocket } from './remote-runtime-request-websocket' type ConnectionState = 'closed' | 'awaiting_ready' | 'awaiting_authenticated' | 'ready' -type PendingRequest = { - resolve: (response: RuntimeRpcResponse) => void - reject: (error: Error) => void - timeout: ReturnType -} - -type ReadyWaiter = { - resolve: () => void - reject: (error: Error) => void -} - const IDLE_CLOSE_MS = 60_000 export class RemoteRuntimeRequestConnection { - private readonly pairing: PairingOffer private state: ConnectionState = 'closed' private ws: WebSocket | null = null private sharedKey: Uint8Array | null = null private socketCleanup: (() => void) | null = null - private readonly pendingRequests = new Map>() - private readonly readyWaiters: ReadyWaiter[] = [] + private readonly pendingRequests = new Map>() + private readonly readyWaiters: RemoteRuntimeRequestReadyWaiter[] = [] private idleCloseTimer: ReturnType | null = null - constructor(pairing: PairingOffer) { - this.pairing = pairing - } + constructor(private readonly pairing: PairingOffer) {} request( method: string, params: unknown, timeoutMs: number ): Promise> { - this.clearIdleCloseTimer() const requestId = randomUUID() + let preparedRequest: RemoteRuntimePreparedRequest + try { + preparedRequest = prepareRemoteRuntimeRequest(this.pendingRequests, () => + serializeRemoteRuntimeRpcRequest({ + requestId, + deviceToken: this.pairing.deviceToken, + method, + params + }) + ) + } catch (error) { + return Promise.reject(toRemoteRuntimeRequestError(error)) + } + this.clearIdleCloseTimer() return new Promise>((resolve, reject) => { const timeout = setTimeout(() => { const pending = this.pendingRequests.get(requestId) @@ -57,6 +73,7 @@ export class RemoteRuntimeRequestConnection { return } this.pendingRequests.delete(requestId) + releaseRemoteRuntimePreparedRequest(pending) const error = remoteRuntimeTimeoutError() pending.reject(error) this.close(error) @@ -64,12 +81,13 @@ export class RemoteRuntimeRequestConnection { this.pendingRequests.set(requestId, { resolve: resolve as (response: RuntimeRpcResponse) => void, reject, - timeout + timeout, + preparedRequest }) void this.ensureReady().then( - () => this.sendRequest(requestId, method, params), - (error) => this.rejectPendingRequest(requestId, toClientError(error)) + () => this.sendRequest(requestId), + (error) => this.rejectPendingRequest(requestId, toRemoteRuntimeRequestError(error)) ) }) } @@ -77,17 +95,17 @@ export class RemoteRuntimeRequestConnection { close(error?: Error): void { const ws = this.ws const cleanup = this.socketCleanup - this.ws = null - this.sharedKey = null + this.ws = this.sharedKey = null this.socketCleanup = null this.state = 'closed' this.clearIdleCloseTimer() const closeError = error ?? remoteRuntimeUnavailableError() - this.rejectReadyWaiters(closeError) + rejectRemoteRuntimeRequestReadyWaiters(this.readyWaiters, closeError) for (const [requestId, pending] of this.pendingRequests) { clearTimeout(pending.timeout) this.pendingRequests.delete(requestId) + releaseRemoteRuntimePreparedRequest(pending) pending.reject(closeError) } @@ -105,12 +123,14 @@ export class RemoteRuntimeRequestConnection { return Promise.resolve() } - const promise = new Promise((resolve, reject) => { - this.readyWaiters.push({ resolve, reject }) - }) + const promise = waitForRemoteRuntimeRequestReady(this.readyWaiters) if (!ws || ws.readyState === WebSocket.CLOSED || ws.readyState === WebSocket.CLOSING) { - this.open() + try { + this.open() + } catch (error) { + this.close(toRemoteRuntimeRequestError(error)) + } } return promise @@ -183,7 +203,10 @@ export class RemoteRuntimeRequestConnection { } this.ws?.send( encrypt( - JSON.stringify({ type: 'e2ee_auth', deviceToken: this.pairing.deviceToken }), + serializeRemoteRuntimePayload({ + type: 'e2ee_auth', + deviceToken: this.pairing.deviceToken + }), sharedKey ) ) @@ -196,7 +219,7 @@ export class RemoteRuntimeRequestConnection { return } this.state = 'ready' - this.resolveReadyWaiters() + resolveRemoteRuntimeRequestReadyWaiters(this.readyWaiters) this.scheduleIdleCloseIfUnused() } @@ -217,11 +240,12 @@ export class RemoteRuntimeRequestConnection { } this.pendingRequests.delete(response.id) clearTimeout(pending.timeout) + releaseRemoteRuntimePreparedRequest(pending) pending.resolve(response) this.scheduleIdleCloseIfUnused() } - private sendRequest(requestId: string, method: string, params: unknown): void { + private sendRequest(requestId: string): void { const pending = this.pendingRequests.get(requestId) const ws = this.ws const sharedKey = this.sharedKey @@ -232,17 +256,16 @@ export class RemoteRuntimeRequestConnection { this.rejectPendingRequest(requestId, remoteRuntimeUnavailableError()) return } - ws.send( - encrypt( - JSON.stringify({ - id: requestId, - deviceToken: this.pairing.deviceToken, - method, - params - }), - sharedKey - ) - ) + const serializedRequest = takeRemoteRuntimePreparedRequest(pending) + if (serializedRequest === null) { + this.rejectPendingRequest(requestId, remoteRuntimeUnavailableError()) + return + } + try { + ws.send(encrypt(serializedRequest, sharedKey)) + } catch (error) { + this.rejectPendingRequest(requestId, toRemoteRuntimeRequestError(error)) + } } private rejectPendingRequest(requestId: string, error: Error): void { @@ -252,24 +275,11 @@ export class RemoteRuntimeRequestConnection { } this.pendingRequests.delete(requestId) clearTimeout(pending.timeout) + releaseRemoteRuntimePreparedRequest(pending) pending.reject(error) this.scheduleIdleCloseIfUnused() } - private resolveReadyWaiters(): void { - const waiters = this.readyWaiters.splice(0) - for (const waiter of waiters) { - waiter.resolve() - } - } - - private rejectReadyWaiters(error: Error): void { - const waiters = this.readyWaiters.splice(0) - for (const waiter of waiters) { - waiter.reject(error) - } - } - private scheduleIdleCloseIfUnused(): void { if (this.pendingRequests.size > 0 || this.readyWaiters.length > 0 || this.state !== 'ready') { return @@ -288,10 +298,3 @@ export class RemoteRuntimeRequestConnection { } } } - -function toClientError(error: unknown): Error { - if (error instanceof Error) { - return error - } - return new RemoteRuntimeClientError('runtime_error', String(error)) -} diff --git a/src/shared/remote-runtime-request-ready-waiters.ts b/src/shared/remote-runtime-request-ready-waiters.ts new file mode 100644 index 000000000..42b7be1ef --- /dev/null +++ b/src/shared/remote-runtime-request-ready-waiters.ts @@ -0,0 +1,29 @@ +export type RemoteRuntimeRequestReadyWaiter = { + resolve: () => void + reject: (error: Error) => void +} + +export function waitForRemoteRuntimeRequestReady( + waiters: RemoteRuntimeRequestReadyWaiter[] +): Promise { + return new Promise((resolve, reject) => { + waiters.push({ resolve, reject }) + }) +} + +export function resolveRemoteRuntimeRequestReadyWaiters( + waiters: RemoteRuntimeRequestReadyWaiter[] +): void { + for (const waiter of waiters.splice(0)) { + waiter.resolve() + } +} + +export function rejectRemoteRuntimeRequestReadyWaiters( + waiters: RemoteRuntimeRequestReadyWaiter[], + error: Error +): void { + for (const waiter of waiters.splice(0)) { + waiter.reject(error) + } +} diff --git a/src/shared/remote-runtime-shared-control-admission.ts b/src/shared/remote-runtime-shared-control-admission.ts new file mode 100644 index 000000000..e526ba1bb --- /dev/null +++ b/src/shared/remote-runtime-shared-control-admission.ts @@ -0,0 +1,53 @@ +import { RemoteRuntimeClientError } from './remote-runtime-client-error' +import { + measureRemoteRuntimeSubscriptionParams, + REMOTE_RUNTIME_MAX_RETAINED_SUBSCRIPTION_BYTES, + REMOTE_RUNTIME_MAX_SUBSCRIPTIONS, + serializeRemoteRuntimeRpcRequest +} from './remote-runtime-memory-limits' +import type { SharedControlLogicalSubscription } from './remote-runtime-shared-control-types' + +export function admitSharedControlSubscription(args: { + subscriptions: Map> + deviceToken: string + method: string + params: unknown +}): number { + if (args.subscriptions.size >= REMOTE_RUNTIME_MAX_SUBSCRIPTIONS) { + throw new RemoteRuntimeClientError( + 'remote_runtime_busy', + 'Remote runtime subscription limit reached; close a subscription and retry.' + ) + } + const retainedParamsBytes = measureRemoteRuntimeSubscriptionParams(args.params) + if ( + retainedSubscriptionBytes(args.subscriptions) + retainedParamsBytes > + REMOTE_RUNTIME_MAX_RETAINED_SUBSCRIPTION_BYTES + ) { + throw new RemoteRuntimeClientError( + 'remote_runtime_busy', + 'Remote runtime subscription memory limit reached; close a subscription and retry.' + ) + } + serializeRequest(args) + return retainedParamsBytes +} + +function serializeRequest(args: { deviceToken: string; method: string; params: unknown }): void { + serializeRemoteRuntimeRpcRequest({ + requestId: '00000000-0000-4000-8000-000000000000', + deviceToken: args.deviceToken, + method: args.method, + params: args.params + }) +} + +function retainedSubscriptionBytes( + subscriptions: Map> +): number { + let bytes = 0 + for (const subscription of subscriptions.values()) { + bytes += subscription.retainedParamsBytes + } + return bytes +} diff --git a/src/shared/remote-runtime-shared-control-connection.test.ts b/src/shared/remote-runtime-shared-control-connection.test.ts index 9e929894a..4af6e4441 100644 --- a/src/shared/remote-runtime-shared-control-connection.test.ts +++ b/src/shared/remote-runtime-shared-control-connection.test.ts @@ -11,6 +11,12 @@ import { publicKeyToBase64 } from './e2ee-crypto' import { encodePairingOffer, parsePairingCode, type PairingOffer } from './pairing' +import { + REMOTE_RUNTIME_MAX_PENDING_RPC_BYTES, + retainedRemoteRuntimeJsonStringBytes, + serializeRemoteRuntimeRpcRequest +} from './remote-runtime-memory-limits' +import { getRemoteRuntimeRequestAdmissionEvidence } from './remote-runtime-prepared-request-admission' import { RemoteRuntimeSharedControlConnection } from './remote-runtime-shared-control-connection' import * as sharedControlProtocol from './remote-runtime-shared-control-protocol' import { isRuntimeSubscriptionReplayResponse } from './runtime-subscription-replay' @@ -63,6 +69,40 @@ describe('RemoteRuntimeSharedControlConnection', () => { expect('sendSharedControlEncryptedBinary' in sharedControlProtocol).toBe(false) }) + it('releases a pending request when the socket send throws', async () => { + const connection = new RemoteRuntimeSharedControlConnection({ + v: 2, + endpoint: 'ws://127.0.0.1:1', + deviceToken: 'token', + publicKeyB64: Buffer.from(new Uint8Array(32).fill(1)).toString('base64') + }) + const unsafe = connection as unknown as { + state: string + ws: { readyState: number; send: () => void; close: () => void } | null + sharedKey: Uint8Array | null + pendingRequests: Map + } + unsafe.state = 'ready' + unsafe.ws = { + readyState: 1, + send: () => { + throw new Error('send failed') + }, + close: vi.fn() + } + unsafe.sharedKey = new Uint8Array(32).fill(2) + + await expect(connection.request('worktree.ps', undefined, 1000)).rejects.toMatchObject({ + code: 'remote_runtime_unavailable' + }) + expect(unsafe.pendingRequests.size).toBe(0) + expect(getRemoteRuntimeRequestAdmissionEvidence()).toEqual({ + pendingRequestCount: 0, + retainedBytes: 0 + }) + connection.close() + }) + it('replaces a stuck pre-ready socket when a one-shot probe proves reachability', () => { const connection = new RemoteRuntimeSharedControlConnection({ v: 2, @@ -492,6 +532,15 @@ describe('RemoteRuntimeSharedControlConnection', () => { delayedMethods: ['worktree.ps'] }) const connection = new RemoteRuntimeSharedControlConnection(server.pairing) + const unsafe = connection as unknown as { + pendingRequests: Map< + string, + { + method: string + preparedRequest?: { retainedBytes: number; serializedRequest: string | null } | null + } + > + } const timedOut = connection.request('worktree.hang', undefined, 250) void timedOut.catch(() => undefined) @@ -505,22 +554,82 @@ describe('RemoteRuntimeSharedControlConnection', () => { await vi.waitFor(() => expect(server.requests.map(({ method }) => method)).toContain('worktree.ps') ) + expect( + Array.from(unsafe.pendingRequests.values()).every( + (pending) => + pending.preparedRequest?.serializedRequest === null && + pending.preparedRequest.retainedBytes > 0 + ) + ).toBe(true) + expect(getRemoteRuntimeRequestAdmissionEvidence().pendingRequestCount).toBe(2) await expect(timedOut).rejects.toThrow('Timed out') // Why: a single slow method is not evidence that a shared socket is dead; // liveness monitoring owns connection-wide failure detection. expect(connection.getDiagnostics()).toMatchObject({ state: 'ready', pendingRequestCount: 1 }) + expect(getRemoteRuntimeRequestAdmissionEvidence().pendingRequestCount).toBe(1) server.flushDelayedResponses() await expect(survivor).resolves.toMatchObject({ ok: true, response: { ok: true, result: { method: 'worktree.ps' } } }) + expect(unsafe.pendingRequests.size).toBe(0) + expect(getRemoteRuntimeRequestAdmissionEvidence()).toEqual({ + pendingRequestCount: 0, + retainedBytes: 0 + }) expect(server.connectionCount()).toBe(1) connection.close() }) + it('keeps sent request bytes admitted while a ready socket stops responding', async () => { + const server = await createServer({ silentMethods: ['worktree.large'] }) + const connection = new RemoteRuntimeSharedControlConnection(server.pairing) + const params = { value: 'x'.repeat(3 * 1024 * 1024) } + const retainedBytes = retainedRemoteRuntimeJsonStringBytes( + serializeRemoteRuntimeRpcRequest({ + requestId: '00000000-0000-4000-8000-000000000000', + deviceToken: server.pairing.deviceToken, + method: 'worktree.large', + params + }) + ) + const admittedCount = Math.floor(REMOTE_RUNTIME_MAX_PENDING_RPC_BYTES / retainedBytes) + const pendingRequests = ( + connection as unknown as { + pendingRequests: Map< + string, + { preparedRequest?: { serializedRequest: string | null } | null } + > + } + ).pendingRequests + const requests = Array.from({ length: admittedCount }, () => + connection.request('worktree.large', params, 60_000).catch(() => undefined) + ) + await vi.waitFor(() => expect(server.requests).toHaveLength(admittedCount)) + + expect( + Array.from(pendingRequests.values()).every( + (pending) => pending.preparedRequest?.serializedRequest === null + ) + ).toBe(true) + await expect(connection.request('worktree.large', params, 60_000)).rejects.toMatchObject({ + code: 'remote_runtime_busy' + }) + expect(getRemoteRuntimeRequestAdmissionEvidence().retainedBytes).toBeLessThanOrEqual( + REMOTE_RUNTIME_MAX_PENDING_RPC_BYTES + ) + + connection.close() + await Promise.all(requests) + expect(getRemoteRuntimeRequestAdmissionEvidence()).toEqual({ + pendingRequestCount: 0, + retainedBytes: 0 + }) + }) + it('rejects pending requests and records close diagnostics when the socket closes', async () => { const server = await createServer({ closeBeforeResponse: true }) const connection = new RemoteRuntimeSharedControlConnection(server.pairing) diff --git a/src/shared/remote-runtime-shared-control-connection.ts b/src/shared/remote-runtime-shared-control-connection.ts index aa624e7a1..e96c7007e 100644 --- a/src/shared/remote-runtime-shared-control-connection.ts +++ b/src/shared/remote-runtime-shared-control-connection.ts @@ -5,7 +5,7 @@ import type { RemoteRuntimeClientError } from './remote-runtime-client-error' import { remoteRuntimeUnavailableError } from './remote-runtime-request-frames' import { openSharedControlSocket } from './remote-runtime-shared-control-open' import { handleSharedControlTextFrame } from './remote-runtime-shared-control-frame-handler' -import { sendSharedControlEncrypted } from './remote-runtime-shared-control-protocol' +import * as sharedControlProtocol from './remote-runtime-shared-control-protocol' import { isSharedControlReady, waitForSharedControlReadyWithTimeout @@ -14,10 +14,7 @@ import { SharedControlReconnectScheduler } from './remote-runtime-shared-control import { requestSharedControl } from './remote-runtime-shared-control-requests' import { SharedControlReadyStableResetTimer } from './remote-runtime-shared-control-stability' import * as sharedControlState from './remote-runtime-shared-control-state' -import { - sendSharedControlRequest, - sendSharedControlSubscription -} from './remote-runtime-shared-control-send' +import * as sharedControlSend from './remote-runtime-shared-control-send' import { closeSharedControlSocket } from './remote-runtime-shared-control-socket-close' import type { RemoteRuntimeSocketLivenessOptions } from './remote-runtime-socket-liveness' import * as sharedControlSubscriptions from './remote-runtime-shared-control-subscriptions' @@ -70,12 +67,12 @@ export class RemoteRuntimeSharedControlConnection { ): Promise> { return requestSharedControl({ pendingRequests: this.pendingRequests, + deviceToken: this.pairing.deviceToken, method, params, timeoutMs, ensureReady: () => this.ensureReadyWithTimeout(timeoutMs), - send: (requestId, requestMethod, requestParams) => - this.sendRequest(requestId, requestMethod, requestParams) + send: (requestId) => this.sendRequest(requestId) }) } @@ -87,6 +84,7 @@ export class RemoteRuntimeSharedControlConnection { ): Promise { return startSharedControlSubscription({ subscriptions: this.subscriptions, + deviceToken: this.pairing.deviceToken, method, params, callbacks, @@ -213,21 +211,24 @@ export class RemoteRuntimeSharedControlConnection { }) } - private sendRequest(requestId: string, method: string, params: unknown): void { - sendSharedControlRequest({ + private sendRequest(requestId: string): void { + sharedControlSend.sendSharedControlRequest({ pendingRequests: this.pendingRequests, requestId, - deviceToken: this.pairing.deviceToken, - method, - params, - send: (payload) => this.sendEncrypted(payload), + send: (serialized) => + sharedControlProtocol.sendSharedControlEncryptedSerialized({ + state: this.state, + ws: this.ws, + sharedKey: this.sharedKey, + serialized + }), reject: (id, error) => sharedControlState.rejectSharedControlPendingRequest(this.pendingRequests, id, error) }) } private sendSubscription(subscription: SharedControlLogicalSubscription): void { - sendSharedControlSubscription({ + sharedControlSend.sendSharedControlSubscription({ subscriptions: this.subscriptions, subscription, deviceToken: this.pairing.deviceToken, @@ -254,7 +255,7 @@ export class RemoteRuntimeSharedControlConnection { } private sendEncrypted(payload: unknown): boolean { - return sendSharedControlEncrypted({ + return sharedControlProtocol.sendSharedControlEncrypted({ state: this.state, ws: this.ws, sharedKey: this.sharedKey, @@ -302,8 +303,7 @@ export class RemoteRuntimeSharedControlConnection { error, clearReadyStableTimer: () => this.readyStableReset.clear() }) - this.ws = null - this.sharedKey = null + this.ws = this.sharedKey = null this.socketCleanup = null this.state = 'closed' } diff --git a/src/shared/remote-runtime-shared-control-keepalive-refresh.test.ts b/src/shared/remote-runtime-shared-control-keepalive-refresh.test.ts index 2f49bc082..ab2ebc433 100644 --- a/src/shared/remote-runtime-shared-control-keepalive-refresh.test.ts +++ b/src/shared/remote-runtime-shared-control-keepalive-refresh.test.ts @@ -26,6 +26,7 @@ describe('shared control keepalive timeout refresh semantics', () => { const pendingRequests = new Map>() const promise = requestSharedControl({ pendingRequests, + deviceToken: 'device-token', method: 'git.status', params: undefined, timeoutMs: 1000, diff --git a/src/shared/remote-runtime-shared-control-protocol.ts b/src/shared/remote-runtime-shared-control-protocol.ts index 31ffe8991..e4caf38da 100644 --- a/src/shared/remote-runtime-shared-control-protocol.ts +++ b/src/shared/remote-runtime-shared-control-protocol.ts @@ -2,6 +2,7 @@ import { decrypt } from './e2ee-crypto' import { encrypt } from './e2ee-crypto' import type WebSocket from 'ws' import { RemoteRuntimeClientError } from './remote-runtime-client' +import { serializeRemoteRuntimePayload } from './remote-runtime-memory-limits' import { invalidRemoteRuntimeResponseError, parseRemoteRuntimeRpcFrame @@ -121,8 +122,35 @@ export function sendSharedControlEncrypted(args: { if (!args.ws || args.ws.readyState !== 1 || !args.sharedKey) { return false } - args.ws.send(encrypt(JSON.stringify(args.payload), args.sharedKey)) - return true + let serialized: string + try { + serialized = serializeRemoteRuntimePayload(args.payload) + } catch { + return false + } + return sendSharedControlEncryptedSerialized({ ...args, serialized }) +} + +export function sendSharedControlEncryptedSerialized(args: { + state: SharedControlConnectionState + ws: WebSocket | null + sharedKey: Uint8Array | null + serialized: string +}): boolean { + if ( + (args.state !== 'ready' && args.state !== 'awaiting_authenticated') || + !args.ws || + args.ws.readyState !== 1 || + !args.sharedKey + ) { + return false + } + try { + args.ws.send(encrypt(args.serialized, args.sharedKey)) + return true + } catch { + return false + } } export function toRemoteRuntimeClientError(error: unknown): RemoteRuntimeClientError { diff --git a/src/shared/remote-runtime-shared-control-ready.ts b/src/shared/remote-runtime-shared-control-ready.ts index e75244a93..23461245d 100644 --- a/src/shared/remote-runtime-shared-control-ready.ts +++ b/src/shared/remote-runtime-shared-control-ready.ts @@ -1,4 +1,6 @@ import WebSocket from 'ws' +import { RemoteRuntimeClientError } from './remote-runtime-client-error' +import { REMOTE_RUNTIME_MAX_READY_WAITERS } from './remote-runtime-memory-limits' import { remoteRuntimeUnavailableError } from './remote-runtime-request-frames' import type { SharedControlConnectionState, @@ -18,6 +20,14 @@ export function waitForSharedControlReadyWithTimeout(args: { timeoutMs: number open: () => void }): Promise { + if (args.readyWaiters.length >= REMOTE_RUNTIME_MAX_READY_WAITERS) { + return Promise.reject( + new RemoteRuntimeClientError( + 'remote_runtime_busy', + 'Remote runtime connection wait limit reached; retry after pending work finishes.' + ) + ) + } return new Promise((resolve, reject) => { let settled = false let waiter!: SharedControlReadyWaiter @@ -51,6 +61,14 @@ export function waitForSharedControlReadyWithTimeout(args: { } } args.readyWaiters.push(waiter) - args.open() + try { + args.open() + } catch (error) { + const index = args.readyWaiters.indexOf(waiter) + if (index >= 0) { + args.readyWaiters.splice(index, 1) + } + waiter.reject(error instanceof Error ? error : remoteRuntimeUnavailableError(String(error))) + } }) } diff --git a/src/shared/remote-runtime-shared-control-requests.ts b/src/shared/remote-runtime-shared-control-requests.ts index 759ac4f87..f7a026f74 100644 --- a/src/shared/remote-runtime-shared-control-requests.ts +++ b/src/shared/remote-runtime-shared-control-requests.ts @@ -1,45 +1,70 @@ import { randomUUID } from 'node:crypto' +import { serializeRemoteRuntimeRpcRequest } from './remote-runtime-memory-limits' +import { + prepareRemoteRuntimeRequest, + releaseRemoteRuntimePreparedRequest, + type RemoteRuntimePreparedRequest +} from './remote-runtime-prepared-request-admission' import { remoteRuntimeTimeoutError } from './remote-runtime-request-frames' import type { RuntimeRpcResponse } from './runtime-rpc-envelope' import { toRemoteRuntimeClientError } from './remote-runtime-shared-control-protocol' import { rejectSharedControlPendingRequest } from './remote-runtime-shared-control-state' import type { SharedControlPendingRequest } from './remote-runtime-shared-control-types' +const MAX_RETAINED_METHOD_CHARS = 256 + export function requestSharedControl(args: { pendingRequests: Map> + deviceToken: string method: string params: unknown timeoutMs: number ensureReady: () => Promise - send: (requestId: string, method: string, params: unknown) => void + send: (requestId: string) => void // Why: default off — ordinary short RPCs keep an absolute deadline. Only // long-polls routed through this path opt in so keepalives extend them. refreshTimeoutOnKeepalive?: boolean }): Promise> { + const { ensureReady, pendingRequests, send } = args const requestId = randomUUID() + let preparedRequest: RemoteRuntimePreparedRequest + try { + preparedRequest = prepareRemoteRuntimeRequest(pendingRequests, () => + serializeRemoteRuntimeRpcRequest({ + requestId, + deviceToken: args.deviceToken, + method: args.method, + params: args.params + }) + ) + } catch (error) { + return Promise.reject(error) + } return new Promise>((resolve, reject) => { const timeout = setTimeout(() => { - const pending = args.pendingRequests.get(requestId) + const pending = pendingRequests.get(requestId) if (!pending) { return } - args.pendingRequests.delete(requestId) + pendingRequests.delete(requestId) + releaseRemoteRuntimePreparedRequest(pending) // Why: one stalled method does not prove the shared socket is dead; // socket liveness owns connection-wide teardown so other RPCs survive. pending.reject(remoteRuntimeTimeoutError()) }, args.timeoutMs) - args.pendingRequests.set(requestId, { - method: args.method, + pendingRequests.set(requestId, { + method: args.method.slice(0, MAX_RETAINED_METHOD_CHARS), resolve: resolve as (response: RuntimeRpcResponse) => void, reject, timeout, + preparedRequest, refreshTimeoutOnKeepalive: args.refreshTimeoutOnKeepalive ?? false }) - void args.ensureReady().then( - () => args.send(requestId, args.method, args.params), + void ensureReady().then( + () => send(requestId), (error) => rejectSharedControlPendingRequest( - args.pendingRequests, + pendingRequests, requestId, toRemoteRuntimeClientError(error) ) diff --git a/src/shared/remote-runtime-shared-control-send.ts b/src/shared/remote-runtime-shared-control-send.ts index 2830eb78b..2a7ff16cf 100644 --- a/src/shared/remote-runtime-shared-control-send.ts +++ b/src/shared/remote-runtime-shared-control-send.ts @@ -1,4 +1,5 @@ import { remoteRuntimeUnavailableError } from './remote-runtime-request-frames' +import { takeRemoteRuntimePreparedRequest } from './remote-runtime-prepared-request-admission' import { finishSharedControlSubscription } from './remote-runtime-shared-control-state' import type { SharedControlLogicalSubscription, @@ -8,23 +9,15 @@ import type { export function sendSharedControlRequest(args: { pendingRequests: Map> requestId: string - deviceToken: string - method: string - params: unknown - send: (payload: unknown) => boolean + send: (serializedRequest: string) => boolean reject: (requestId: string, error: Error) => void }): void { - if (!args.pendingRequests.has(args.requestId)) { + const pending = args.pendingRequests.get(args.requestId) + if (!pending) { return } - if ( - !args.send({ - id: args.requestId, - deviceToken: args.deviceToken, - method: args.method, - params: args.params - }) - ) { + const serializedRequest = takeRemoteRuntimePreparedRequest(pending) + if (serializedRequest === null || !args.send(serializedRequest)) { args.reject(args.requestId, remoteRuntimeUnavailableError()) } } diff --git a/src/shared/remote-runtime-shared-control-socket-generation.test.ts b/src/shared/remote-runtime-shared-control-socket-generation.test.ts index 21a85734d..37a95f0c1 100644 --- a/src/shared/remote-runtime-shared-control-socket-generation.test.ts +++ b/src/shared/remote-runtime-shared-control-socket-generation.test.ts @@ -19,6 +19,7 @@ describe('SharedControlSocketGeneration', () => { requestId: 'subscription-1', method: 'session.tabs.subscribeAll', params: null, + retainedParamsBytes: 0, callbacks: { onResponse: vi.fn(), onError }, sent: true, closed: false, @@ -32,6 +33,7 @@ describe('SharedControlSocketGeneration', () => { requestId: 'subscription-2', method: 'runtime.clientEvents.subscribe', params: null, + retainedParamsBytes: 0, callbacks: { onResponse: vi.fn(), onError: throwingOnError }, sent: true, closed: false, diff --git a/src/shared/remote-runtime-shared-control-state.ts b/src/shared/remote-runtime-shared-control-state.ts index 0190398e3..7a6a32437 100644 --- a/src/shared/remote-runtime-shared-control-state.ts +++ b/src/shared/remote-runtime-shared-control-state.ts @@ -1,4 +1,5 @@ import type { RemoteRuntimeClientError } from './remote-runtime-client-error' +import { releaseRemoteRuntimePreparedRequest } from './remote-runtime-prepared-request-admission' import { remoteRuntimeUnavailableError } from './remote-runtime-request-frames' import type { RuntimeRpcResponse } from './runtime-rpc-envelope' import type { @@ -43,6 +44,7 @@ export function rejectSharedControlPendingRequest( } pendingRequests.delete(requestId) clearTimeout(pending.timeout) + releaseRemoteRuntimePreparedRequest(pending) pending.reject(error) } @@ -57,6 +59,7 @@ export function resolveSharedControlPendingResponse( } pendingRequests.delete(requestId) clearTimeout(pending.timeout) + releaseRemoteRuntimePreparedRequest(pending) pending.resolve(response) } @@ -98,6 +101,7 @@ export function rejectAllSharedControlPendingRequests( for (const [requestId, pending] of pendingRequests) { clearTimeout(pending.timeout) pendingRequests.delete(requestId) + releaseRemoteRuntimePreparedRequest(pending) pending.reject(closeError) } } diff --git a/src/shared/remote-runtime-shared-control-subscription-start.ts b/src/shared/remote-runtime-shared-control-subscription-start.ts index cdc198f54..2b22aaabc 100644 --- a/src/shared/remote-runtime-shared-control-subscription-start.ts +++ b/src/shared/remote-runtime-shared-control-subscription-start.ts @@ -1,5 +1,6 @@ import { randomUUID } from 'node:crypto' import { remoteRuntimeUnavailableError } from './remote-runtime-request-frames' +import { admitSharedControlSubscription } from './remote-runtime-shared-control-admission' import { createSharedControlSubscription } from './remote-runtime-shared-control-subscriptions' import { finishSharedControlSubscription } from './remote-runtime-shared-control-state' import type { @@ -10,6 +11,7 @@ import type { export async function startSharedControlSubscription(args: { subscriptions: Map> + deviceToken: string method: string params: unknown callbacks: SharedControlSubscriptionCallbacks @@ -17,11 +19,18 @@ export async function startSharedControlSubscription(args: { sendSubscription: (subscription: SharedControlLogicalSubscription) => void closeSubscription: (requestId: string) => void }): Promise { + const retainedParamsBytes = admitSharedControlSubscription({ + subscriptions: args.subscriptions, + deviceToken: args.deviceToken, + method: args.method, + params: args.params + }) const requestId = randomUUID() const subscription = createSharedControlSubscription({ requestId, method: args.method, params: args.params, + retainedParamsBytes, callbacks: args.callbacks }) args.subscriptions.set(requestId, subscription as SharedControlLogicalSubscription) diff --git a/src/shared/remote-runtime-shared-control-subscriptions.test.ts b/src/shared/remote-runtime-shared-control-subscriptions.test.ts index a1b843f74..de5d5718b 100644 --- a/src/shared/remote-runtime-shared-control-subscriptions.test.ts +++ b/src/shared/remote-runtime-shared-control-subscriptions.test.ts @@ -17,6 +17,7 @@ function makeSubscriptions(): { requestId: 'req-1', method: 'runtime.clientEvents.subscribe', params: null, + retainedParamsBytes: 0, callbacks: { onResponse: vi.fn(), onError: vi.fn() } }) subscriptions.set(subscription.requestId, subscription) diff --git a/src/shared/remote-runtime-shared-control-subscriptions.ts b/src/shared/remote-runtime-shared-control-subscriptions.ts index 54e35a784..5b18ce801 100644 --- a/src/shared/remote-runtime-shared-control-subscriptions.ts +++ b/src/shared/remote-runtime-shared-control-subscriptions.ts @@ -14,12 +14,14 @@ export function createSharedControlSubscription(args: { requestId: string method: string params: unknown + retainedParamsBytes: number callbacks: SharedControlSubscriptionCallbacks }): SharedControlLogicalSubscription { return { requestId: args.requestId, method: args.method, params: args.params, + retainedParamsBytes: args.retainedParamsBytes, callbacks: args.callbacks, sent: false, closed: false, diff --git a/src/shared/remote-runtime-shared-control-types.ts b/src/shared/remote-runtime-shared-control-types.ts index 98babc9d5..c6e551347 100644 --- a/src/shared/remote-runtime-shared-control-types.ts +++ b/src/shared/remote-runtime-shared-control-types.ts @@ -1,5 +1,6 @@ import type { RuntimeRpcResponse } from './runtime-rpc-envelope' import type { RemoteRuntimeClientError } from './remote-runtime-client-error' +import type { RemoteRuntimePreparedRequest } from './remote-runtime-prepared-request-admission' export type SharedControlConnectionState = | 'closed' @@ -12,6 +13,7 @@ export type SharedControlPendingRequest = { resolve: (response: RuntimeRpcResponse) => void reject: (error: Error) => void timeout: ReturnType + preparedRequest?: RemoteRuntimePreparedRequest | null // Why: keepalives on the shared socket are armed for an unrelated long-poll, // not this request. Only requests that opt in (long-polls issued via the // short-RPC path) may have their deadline refreshed by a keepalive; ordinary @@ -31,6 +33,7 @@ export type SharedControlLogicalSubscription = { requestId: string method: string params: unknown + retainedParamsBytes: number callbacks: SharedControlSubscriptionCallbacks sent: boolean closed: boolean diff --git a/src/shared/repo-icon.test.ts b/src/shared/repo-icon.test.ts index 095855e9c..f8d54c437 100644 --- a/src/shared/repo-icon.test.ts +++ b/src/shared/repo-icon.test.ts @@ -1,6 +1,19 @@ import { describe, expect, it } from 'vitest' import { githubAvatarIcon, sanitizeRepoIcon } from './repo-icon' +const PNG_1X1_BASE64 = + 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+/p9sAAAAASUVORK5CYII=' + +function pngBase64(width: number, height: number): string { + const bytes = Buffer.alloc(24) + Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]).copy(bytes) + bytes.writeUInt32BE(13, 8) + bytes.write('IHDR', 12, 'ascii') + bytes.writeUInt32BE(width, 16) + bytes.writeUInt32BE(height, 20) + return bytes.toString('base64') +} + describe('sanitizeRepoIcon', () => { it('accepts lucide, emoji, and supported image icons', () => { expect(sanitizeRepoIcon({ type: 'lucide', name: 'Folder' })).toEqual({ @@ -51,23 +64,23 @@ describe('sanitizeRepoIcon', () => { expect( sanitizeRepoIcon({ type: 'image', - src: 'data:image/png;base64,aGVsbG8=', + src: `data:image/png;base64,${PNG_1X1_BASE64}`, source: 'upload' }) ).toEqual({ type: 'image', - src: 'data:image/png;base64,aGVsbG8=', + src: `data:image/png;base64,${PNG_1X1_BASE64}`, source: 'upload' }) expect( sanitizeRepoIcon({ type: 'image', - src: 'data:image/png;base64,aGVsbG8=', + src: `data:image/png;base64,${PNG_1X1_BASE64}`, source: 'file' }) ).toEqual({ type: 'image', - src: 'data:image/png;base64,aGVsbG8=', + src: `data:image/png;base64,${PNG_1X1_BASE64}`, source: 'file' }) }) @@ -84,6 +97,13 @@ describe('sanitizeRepoIcon', () => { source: 'favicon' }) ).toBeUndefined() + expect( + sanitizeRepoIcon({ + type: 'image', + src: `data:image/png;base64,${pngBase64(32_769, 1)}`, + source: 'upload' + }) + ).toBeUndefined() expect( sanitizeRepoIcon({ type: 'image', diff --git a/src/shared/repo-icon.ts b/src/shared/repo-icon.ts index 110448f50..55e9e29fb 100644 --- a/src/shared/repo-icon.ts +++ b/src/shared/repo-icon.ts @@ -1,3 +1,5 @@ +import { validateRasterImageDataUri } from './image-data-uri' + export type RepoIconImageSource = 'upload' | 'file' | 'favicon' | 'github' export type RepoIcon = @@ -63,7 +65,10 @@ function normalizeGitHubAvatarHost(rawHost?: string): string { function isSupportedImageSrc(src: string, source: RepoIconImageSource): boolean { if (source === 'upload' || source === 'file') { - return /^data:image\/png;base64,[A-Za-z0-9+/=\s]+$/i.test(src) + return ( + /^data:image\/png;base64,[A-Za-z0-9+/=\s]+$/i.test(src) && + validateRasterImageDataUri(src) !== null + ) } let url: URL diff --git a/src/shared/runtime-bootstrap.ts b/src/shared/runtime-bootstrap.ts index 993ab5e02..efa224d74 100644 --- a/src/shared/runtime-bootstrap.ts +++ b/src/shared/runtime-bootstrap.ts @@ -1,4 +1,5 @@ import { join } from 'node:path' +import { assertJsonTextStructureWithinLimits } from './json-text-structure-limit' export type RuntimeTransportMetadata = | { @@ -22,6 +23,18 @@ export type RuntimeMetadata = { startedAt: number } +export const MAX_RUNTIME_METADATA_FILE_BYTES = 64 * 1024 +export const MAX_RUNTIME_METADATA_JSON_STRUCTURAL_TOKENS = 16 * 1024 +export const MAX_RUNTIME_METADATA_JSON_NESTING_DEPTH = 32 + +export function parseRuntimeMetadataJson(serialized: string): RuntimeMetadata { + assertJsonTextStructureWithinLimits(serialized, { + structuralTokens: MAX_RUNTIME_METADATA_JSON_STRUCTURAL_TOKENS, + nestingDepth: MAX_RUNTIME_METADATA_JSON_NESTING_DEPTH + }) + return JSON.parse(serialized) as RuntimeMetadata +} + // Why: the CLI must handle metadata files written by older Orca versions that // used a singular `transport` field. This helper extracts the first transport // matching the given kinds from either the new `transports` array or the diff --git a/src/shared/runtime-environment-store.test.ts b/src/shared/runtime-environment-store.test.ts index 0397b0e1a..f58093337 100644 --- a/src/shared/runtime-environment-store.test.ts +++ b/src/shared/runtime-environment-store.test.ts @@ -1,4 +1,4 @@ -import { mkdtempSync, rmSync } from 'node:fs' +import { mkdtempSync, rmSync, truncateSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it } from 'vitest' @@ -6,7 +6,9 @@ import { encodePairingOffer } from './pairing' import { RuntimeEnvironmentStoreError, addEnvironmentFromPairingCode, + getEnvironmentStorePath, listEnvironments, + MAX_RUNTIME_ENVIRONMENT_STORE_FILE_BYTES, markEnvironmentUsed, updateEnvironmentFromPairingCode } from './runtime-environment-store' @@ -125,4 +127,31 @@ describe('runtime environment store', () => { runtimeId: 'runtime-2' }) }) + + it('rejects an oversized sparse environment store before parsing it', () => { + const userDataPath = mkdtempSync(join(tmpdir(), 'orca-runtime-env-store-bound-')) + tempDirs.push(userDataPath) + const path = getEnvironmentStorePath(userDataPath) + writeFileSync(path, '{"version":1,"environments":[]}') + truncateSync(path, MAX_RUNTIME_ENVIRONMENT_STORE_FILE_BYTES + 1) + + expect(() => listEnvironments(userDataPath)).toThrow(RuntimeEnvironmentStoreError) + }) + + it('rejects an oversized write without replacing the durable environment list', () => { + const userDataPath = mkdtempSync(join(tmpdir(), 'orca-runtime-env-store-write-bound-')) + tempDirs.push(userDataPath) + const first = addEnvironmentFromPairingCode(userDataPath, { + name: 'dev box', + pairingCode: pairingCode() + }) + + expect(() => + addEnvironmentFromPairingCode(userDataPath, { + name: 'x'.repeat(MAX_RUNTIME_ENVIRONMENT_STORE_FILE_BYTES), + pairingCode: pairingCode('ws://192.0.2.10:6768') + }) + ).toThrow(RuntimeEnvironmentStoreError) + expect(listEnvironments(userDataPath)).toEqual([first]) + }) }) diff --git a/src/shared/runtime-environment-store.ts b/src/shared/runtime-environment-store.ts index a54694059..4211eb18d 100644 --- a/src/shared/runtime-environment-store.ts +++ b/src/shared/runtime-environment-store.ts @@ -1,8 +1,11 @@ import { randomUUID } from 'node:crypto' -import { existsSync, readFileSync } from 'node:fs' +import { existsSync } from 'node:fs' import { join } from 'node:path' +import { JsonStringifyByteLimitError } from './node-bounded-json-stringify' +import { readNodeFileSyncWithinLimit } from './node-bounded-file-reader' import { parsePairingCode, type PairingOffer } from './pairing' -import { hardenExistingSecureFile, writeSecureJsonFile } from './secure-file' +import { writeSecureJsonFileWithinLimit } from './bounded-secure-json-file' +import { hardenExistingSecureFile } from './secure-file' import { createEnvironmentFromPairingOffer, getPreferredPairingOffer, @@ -14,6 +17,7 @@ import { } from './runtime-environments' const ENVIRONMENTS_FILE = 'orca-environments.json' +export const MAX_RUNTIME_ENVIRONMENT_STORE_FILE_BYTES = 1024 * 1024 export type RuntimeEnvironmentStoreErrorCode = 'invalid_argument' | 'runtime_error' @@ -200,7 +204,13 @@ function readEnvironmentStore(userDataPath: string): RuntimeEnvironmentStore { } try { hardenExistingSecureFile(path) - const parsed = RuntimeEnvironmentStoreSchema.parse(JSON.parse(readFileSync(path, 'utf8'))) + const parsed = RuntimeEnvironmentStoreSchema.parse( + JSON.parse( + readNodeFileSyncWithinLimit(path, MAX_RUNTIME_ENVIRONMENT_STORE_FILE_BYTES).buffer.toString( + 'utf8' + ) + ) + ) return { version: 1, environments: parsed.environments @@ -217,5 +227,19 @@ function readEnvironmentStore(userDataPath: string): RuntimeEnvironmentStore { function writeEnvironmentStore(userDataPath: string, store: RuntimeEnvironmentStore): void { const path = getEnvironmentStorePath(userDataPath) - writeSecureJsonFile(path, RuntimeEnvironmentStoreSchema.parse(store)) + try { + writeSecureJsonFileWithinLimit( + path, + RuntimeEnvironmentStoreSchema.parse(store), + MAX_RUNTIME_ENVIRONMENT_STORE_FILE_BYTES + ) + } catch (error) { + if (error instanceof JsonStringifyByteLimitError) { + throw new RuntimeEnvironmentStoreError( + 'runtime_error', + `Could not write Orca environments at ${path}; the store exceeds its durable capacity.` + ) + } + throw error + } } diff --git a/src/shared/runtime-rpc-call-queue.test.ts b/src/shared/runtime-rpc-call-queue.test.ts index 5a3fcdf93..b0c43e240 100644 --- a/src/shared/runtime-rpc-call-queue.test.ts +++ b/src/shared/runtime-rpc-call-queue.test.ts @@ -1,5 +1,9 @@ import { describe, expect, it, vi } from 'vitest' -import { isBackgroundRuntimeMethod, RuntimeRpcCallQueuePool } from './runtime-rpc-call-queue' +import { + isBackgroundRuntimeMethod, + RuntimeRpcCallQueueOverloadError, + RuntimeRpcCallQueuePool +} from './runtime-rpc-call-queue' describe('runtime RPC call queue', () => { it('classifies per-worktree decoration lookups as background work', () => { @@ -79,4 +83,86 @@ describe('runtime RPC call queue', () => { ) expect(started).toEqual(Array.from({ length: 71 }, (_, index) => index)) }) + + it('rejects per-selector overload and accepts work after the queue drains', async () => { + const queue = new RuntimeRpcCallQueuePool(1, 1, 2, 10) + let releaseFirst: () => void = () => {} + const first = queue.enqueue('runtime-a', 'status.get', async () => { + await new Promise((resolve) => { + releaseFirst = resolve + }) + return 'first' + }) + const second = queue.enqueue('runtime-a', 'status.get', async () => 'second') + const third = queue.enqueue('runtime-a', 'status.get', async () => 'third') + + await expect(queue.enqueue('runtime-a', 'status.get', async () => 'overflow')).rejects.toEqual( + expect.objectContaining({ + code: 'runtime_rpc_queue_overloaded', + scope: 'selector' + }) + ) + + releaseFirst() + await expect(Promise.all([first, second, third])).resolves.toEqual(['first', 'second', 'third']) + await expect(queue.enqueue('runtime-a', 'status.get', async () => 'recovered')).resolves.toBe( + 'recovered' + ) + }) + + it('caps queued calls across selectors and recovers after draining', async () => { + const queue = new RuntimeRpcCallQueuePool(1, 1, 10, 2) + const releases: (() => void)[] = [] + const blockers = ['runtime-a', 'runtime-b'].map((selector) => + queue.enqueue(selector, 'status.get', async () => { + await new Promise((resolve) => releases.push(resolve)) + }) + ) + const queuedA = queue.enqueue('runtime-a', 'status.get', async () => 'queued-a') + const queuedB = queue.enqueue('runtime-b', 'status.get', async () => 'queued-b') + + const overload = queue.enqueue('runtime-c', 'status.get', async () => 'overflow') + await expect(overload).rejects.toBeInstanceOf(RuntimeRpcCallQueueOverloadError) + await expect(overload).rejects.toMatchObject({ scope: 'global' }) + + releases.splice(0).forEach((release) => release()) + await expect(Promise.all([...blockers, queuedA, queuedB])).resolves.toEqual([ + undefined, + undefined, + 'queued-a', + 'queued-b' + ]) + await expect(queue.enqueue('runtime-c', 'status.get', async () => 'recovered')).resolves.toBe( + 'recovered' + ) + }) + + it('caps retained call bytes across active and queued work, then recovers', async () => { + const queue = new RuntimeRpcCallQueuePool(1, 1, 10, 10, 10) + let releaseFirst: () => void = () => {} + let firstStarted = false + const first = queue.enqueue( + 'runtime-a', + 'status.get', + async () => { + firstStarted = true + await new Promise((resolve) => { + releaseFirst = resolve + }) + return 'first' + }, + 10 + ) + + await vi.waitFor(() => expect(firstStarted).toBe(true)) + await expect( + queue.enqueue('runtime-b', 'status.get', async () => 'overflow', 1) + ).rejects.toMatchObject({ scope: 'memory' }) + + releaseFirst() + await expect(first).resolves.toBe('first') + await expect( + queue.enqueue('runtime-b', 'status.get', async () => 'recovered', 10) + ).resolves.toBe('recovered') + }) }) diff --git a/src/shared/runtime-rpc-call-queue.ts b/src/shared/runtime-rpc-call-queue.ts index 4e21970af..b9653e464 100644 --- a/src/shared/runtime-rpc-call-queue.ts +++ b/src/shared/runtime-rpc-call-queue.ts @@ -1,8 +1,23 @@ +import { REMOTE_RUNTIME_MAX_PREPARED_RPC_BYTES } from './remote-runtime-memory-limits' + const DEFAULT_REMOTE_RUNTIME_CALL_CONCURRENCY = 8 const DEFAULT_REMOTE_RUNTIME_BACKGROUND_CALL_CONCURRENCY = 2 +export const RUNTIME_RPC_MAX_QUEUED_CALLS_PER_SELECTOR = 256 +export const RUNTIME_RPC_MAX_QUEUED_CALLS_TOTAL = 2_048 +export const RUNTIME_RPC_QUEUE_OVERLOAD_CODE = 'runtime_rpc_queue_overloaded' + +export class RuntimeRpcCallQueueOverloadError extends Error { + readonly code = RUNTIME_RPC_QUEUE_OVERLOAD_CODE + + constructor(readonly scope: 'selector' | 'global' | 'memory') { + super('Remote runtime call queue is full; retry after current calls finish.') + this.name = 'RuntimeRpcCallQueueOverloadError' + } +} type QueuedRuntimeCall = { background: boolean + retainedBytes: number run: () => Promise resolve: (value: T) => void reject: (error: unknown) => void @@ -34,23 +49,51 @@ export function isBackgroundRuntimeMethod(method: string): boolean { export class RuntimeRpcCallQueuePool { private readonly queues = new Map() + private queuedCallCount = 0 + private retainedCallBytes = 0 constructor( private readonly concurrency = DEFAULT_REMOTE_RUNTIME_CALL_CONCURRENCY, - private readonly backgroundConcurrency = DEFAULT_REMOTE_RUNTIME_BACKGROUND_CALL_CONCURRENCY + private readonly backgroundConcurrency = DEFAULT_REMOTE_RUNTIME_BACKGROUND_CALL_CONCURRENCY, + private readonly maxQueuedPerSelector = RUNTIME_RPC_MAX_QUEUED_CALLS_PER_SELECTOR, + private readonly maxQueuedTotal = RUNTIME_RPC_MAX_QUEUED_CALLS_TOTAL, + private readonly maxRetainedBytes = REMOTE_RUNTIME_MAX_PREPARED_RPC_BYTES ) {} - enqueue(selector: string, method: string, run: () => Promise): Promise { + enqueue( + selector: string, + method: string, + run: () => Promise, + retainedBytes = 0 + ): Promise { + if (this.queuedCallCount >= this.maxQueuedTotal) { + return Promise.reject(new RuntimeRpcCallQueueOverloadError('global')) + } + const existingQueue = this.queues.get(selector) + if (existingQueue && this.queuedCount(existingQueue) >= this.maxQueuedPerSelector) { + return Promise.reject(new RuntimeRpcCallQueueOverloadError('selector')) + } + if ( + !Number.isSafeInteger(retainedBytes) || + retainedBytes < 0 || + this.retainedCallBytes + retainedBytes > this.maxRetainedBytes + ) { + return Promise.reject(new RuntimeRpcCallQueueOverloadError('memory')) + } + const queue = this.getQueue(selector) return new Promise((resolve, reject) => { const call: QueuedRuntimeCall = { background: isBackgroundRuntimeMethod(method), + retainedBytes, run, resolve, reject } const targetQueue = call.background ? queue.background : queue.foreground targetQueue.push(call as QueuedRuntimeCall) + this.queuedCallCount += 1 + this.retainedCallBytes += retainedBytes this.pump(selector, queue) }) } @@ -96,6 +139,7 @@ export class RuntimeRpcCallQueuePool { runPromise = Promise.reject(error) } void runPromise.then(call.resolve, call.reject).finally(() => { + this.retainedCallBytes = Math.max(0, this.retainedCallBytes - call.retainedBytes) queue.active = Math.max(0, queue.active - 1) if (call.background) { queue.backgroundActive = Math.max(0, queue.backgroundActive - 1) @@ -115,6 +159,7 @@ export class RuntimeRpcCallQueuePool { } const call = queue.foreground[queue.foregroundHead] queue.foregroundHead += 1 + this.queuedCallCount = Math.max(0, this.queuedCallCount - 1) this.compactForeground(queue) return call } @@ -125,6 +170,7 @@ export class RuntimeRpcCallQueuePool { } const call = queue.background[queue.backgroundHead] queue.backgroundHead += 1 + this.queuedCallCount = Math.max(0, this.queuedCallCount - 1) this.compactBackground(queue) return call } @@ -153,4 +199,13 @@ export class RuntimeRpcCallQueuePool { queue.backgroundHead >= queue.background.length ) } + + private queuedCount(queue: RuntimeCallQueue): number { + return ( + queue.foreground.length - + queue.foregroundHead + + queue.background.length - + queue.backgroundHead + ) + } } diff --git a/src/shared/runtime-types.ts b/src/shared/runtime-types.ts index c90762c65..466793915 100644 --- a/src/shared/runtime-types.ts +++ b/src/shared/runtime-types.ts @@ -40,6 +40,7 @@ import type { StartupCommandDelivery } from './codex-startup-delivery' import type { RemoteServerUpdateSupport } from './remote-server-update' import type { ExecutionHostId } from './execution-host' import type { PtyIncarnationId } from './pty-incarnation' +import type { RasterImageDimensions } from './raster-image-dimensions' export type { RuntimeMarkdownReadTabResult, RuntimeMarkdownSaveTabResult } @@ -407,6 +408,7 @@ export type RuntimeFilePreviewResult = { isBinary: boolean isImage?: boolean mimeType?: string + imageDimensions?: RasterImageDimensions } export type RuntimeFileReadChunkResult = { diff --git a/src/shared/secure-file.test.ts b/src/shared/secure-file.test.ts index 4aa8e0f60..d7b7e9e44 100644 --- a/src/shared/secure-file.test.ts +++ b/src/shared/secure-file.test.ts @@ -1,9 +1,10 @@ import { execFile, execFileSync } from 'node:child_process' -import { chmodSync, mkdtempSync, rmSync, statSync, writeFileSync } from 'node:fs' +import { chmodSync, mkdirSync, mkdtempSync, rmSync, statSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { + __getSecureFileHardeningCacheStateForTests, __resetSecureFileHardenedPathsForTests, __resetSecureFileWindowsUserSidForTests, hardenExistingSecureFile, @@ -145,6 +146,65 @@ describe('hardenSecurePath', () => { expect(getPowerShellCalls().map(getPowerShellTarget)).toEqual([userDataPath, targetPath]) }) + it('LRU-evicts Windows file hardening entries and safely re-hardens an evicted path', () => { + Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' }) + __resetSecureFileHardenedPathsForTests({ + maxEntries: 2, + maxKeyBytes: 4096, + maxTotalKeyBytes: 8192 + }) + const userDataPath = mkdtempSync(join(tmpdir(), 'orca-secure-file-')) + tempDirs.push(userDataPath) + const paths = ['first.json', 'second.json', 'third.json'].map((name) => + join(userDataPath, name) + ) + for (const path of paths) { + writeFileSync(path, '{}') + hardenExistingSecureFile(path) + } + + hardenExistingSecureFile(paths[0]!) + + const fileTargets = getPowerShellCalls() + .map(getPowerShellTarget) + .filter((path) => paths.includes(path)) + expect(fileTargets).toEqual([...paths, paths[0]]) + expect(__getSecureFileHardeningCacheStateForTests().paths).toMatchObject({ + entries: 2 + }) + }) + + it('LRU-evicts Windows directory hardening entries instead of retaining every path', () => { + Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' }) + __resetSecureFileHardenedPathsForTests({ + maxEntries: 2, + maxKeyBytes: 4096, + maxTotalKeyBytes: 8192 + }) + const root = mkdtempSync(join(tmpdir(), 'orca-secure-file-')) + tempDirs.push(root) + const directories = ['first', 'second', 'third'].map((name) => join(root, name)) + const files = directories.map((dir) => { + mkdirSync(dir) + const file = join(dir, 'secret.json') + writeFileSync(file, '{}') + return file + }) + for (const file of files) { + hardenExistingSecureFile(file) + } + + hardenExistingSecureFile(files[0]!) + + const directoryTargets = getPowerShellCalls() + .map(getPowerShellTarget) + .filter((path) => directories.includes(path)) + expect(directoryTargets).toEqual([...directories, directories[0]]) + expect(__getSecureFileHardeningCacheStateForTests().directories).toMatchObject({ + entries: 2 + }) + }) + it('re-hardens an existing file when its metadata changes after caching', async () => { Object.defineProperty(process, 'platform', { configurable: true, value: 'win32' }) const userDataPath = mkdtempSync(join(tmpdir(), 'orca-secure-file-')) @@ -350,6 +410,34 @@ describe('hardenSecurePath', () => { expect(statMode(userDataPath)).toBe(0o700) }) + + posixModeIt('LRU-bounds POSIX hardening entries while keeping recent paths cached', () => { + Object.defineProperty(process, 'platform', { configurable: true, value: 'linux' }) + __resetSecureFileHardenedPathsForTests({ + maxEntries: 2, + maxKeyBytes: 4096, + maxTotalKeyBytes: 8192 + }) + const userDataPath = mkdtempSync(join(tmpdir(), 'orca-secure-file-')) + tempDirs.push(userDataPath) + const firstPath = join(userDataPath, 'first.json') + const secondPath = join(userDataPath, 'second.json') + writeFileSync(firstPath, '{}') + writeFileSync(secondPath, '{}') + + hardenExistingSecureFile(firstPath) + hardenExistingSecureFile(secondPath) + expect(__getSecureFileHardeningCacheStateForTests().paths.paths).toEqual([ + userDataPath, + secondPath + ]) + + hardenExistingSecureFile(firstPath) + expect(__getSecureFileHardeningCacheStateForTests().paths.paths).toEqual([ + userDataPath, + firstPath + ]) + }) }) const POWERSHELL_SUFFIX = 'WindowsPowerShell\\v1.0\\powershell.exe' diff --git a/src/shared/secure-file.ts b/src/shared/secure-file.ts index 90bfd5d6d..36231de68 100644 --- a/src/shared/secure-file.ts +++ b/src/shared/secure-file.ts @@ -1,4 +1,3 @@ -import { execFile, execFileSync } from 'node:child_process' import { randomBytes } from 'node:crypto' import { chmodSync, @@ -9,9 +8,16 @@ import { statSync, writeFileSync } from 'node:fs' -import { dirname, win32 as pathWin32 } from 'node:path' - -let cachedWindowsUserSid: string | null | undefined +import { dirname } from 'node:path' +import { + SecurePathHardeningCache, + type SecurePathHardeningCacheBounds +} from './secure-path-hardening-cache' +import { + bestEffortRestrictWindowsPath, + resetSecureFileWindowsUserSidForTests, + restrictWindowsPathSync +} from './secure-path-windows-acl' type HardenedPathCacheEntry = { isDirectory: boolean @@ -24,21 +30,35 @@ type HardenedPathCacheEntry = { birthtimeMs: number } +export const SECURE_PATH_HARDENING_CACHE_MAX_ENTRIES = 1024 +export const SECURE_PATH_HARDENING_CACHE_KEY_MAX_BYTES = 64 * 1024 +export const SECURE_PATH_HARDENING_CACHE_KEYS_MAX_BYTES = 512 * 1024 + +const DEFAULT_HARDENING_CACHE_BOUNDS: SecurePathHardeningCacheBounds = { + maxEntries: SECURE_PATH_HARDENING_CACHE_MAX_ENTRIES, + maxKeyBytes: SECURE_PATH_HARDENING_CACHE_KEY_MAX_BYTES, + maxTotalKeyBytes: SECURE_PATH_HARDENING_CACHE_KEYS_MAX_BYTES +} + // Why: PowerShell hardening (~1-1.5s) stalls the main thread, so cache idempotent re-hardens per process. -const hardenedPathsThisProcess = new Map() +let hardenedPathsThisProcess = new SecurePathHardeningCache( + DEFAULT_HARDENING_CACHE_BOUNDS +) // Why: child writes constantly bump a dir's mtime, so cache dirs by path (not metadata) to avoid a PowerShell spawn every read (#4901). // Limitation: a dir deleted+recreated in-process won't re-harden; fine since we never delete our secure dirs at runtime. -const hardenedDirectoryPathsThisProcess = new Set() +let hardenedDirectoryPathsThisProcess = new SecurePathHardeningCache( + DEFAULT_HARDENING_CACHE_BOUNDS +) function hardenSecureDirectoryOnce(dirPath: string): void { // Why: dir hardening stays async — re-applying it stormed the main thread (#4901); files inside are hardened synchronously anyway. - if (hardenedDirectoryPathsThisProcess.has(dirPath)) { + if (hardenedDirectoryPathsThisProcess.get(dirPath)) { return } applySecurePathRestriction(dirPath, true, process.platform, false) // Cache even though the async ACL may still be in flight — dir restriction is best-effort, no retry. - hardenedDirectoryPathsThisProcess.add(dirPath) + hardenedDirectoryPathsThisProcess.set(dirPath, true) } function hardenSecurePathOnce(targetPath: string, isDirectory: boolean): boolean { @@ -196,153 +216,23 @@ function hardenedPathCacheEntriesMatch( ) } -function buildWindowsRestrictAclArgs( - targetPath: string, - currentUserSid: string, - isDirectory: boolean -): string[] { - return [ - '-NoProfile', - '-NonInteractive', - '-ExecutionPolicy', - 'Bypass', - '-Command', - WINDOWS_RESTRICT_ACL_SCRIPT, - targetPath, - currentUserSid, - isDirectory ? '1' : '0' - ] -} - -function bestEffortRestrictWindowsPath(targetPath: string, isDirectory: boolean): void { - const currentUserSid = getCurrentWindowsUserSid() - if (!currentUserSid) { - return - } - // Why: async to avoid blocking the main thread — sync PowerShell cold-start (~1-1.5s) on the frequent read path stormed it (#4901). - execFile( - getWindowsSystemToolPath('WindowsPowerShell\\v1.0\\powershell.exe'), - buildWindowsRestrictAclArgs(targetPath, currentUserSid, isDirectory), - { - windowsHide: true, - timeout: 5000 - }, - () => { - // Why: ignore errors — hardening is best-effort; PowerShell ACL APIs may be unavailable or locked down. - } - ) -} - -function restrictWindowsPathSync(targetPath: string, isDirectory: boolean): boolean { - const currentUserSid = getCurrentWindowsUserSid() - if (!currentUserSid) { - return false - } - // Why: file must not be published until its ACL is actually restricted, so block and report real success (read path stays async, #4901). - try { - execFileSync( - getWindowsSystemToolPath('WindowsPowerShell\\v1.0\\powershell.exe'), - buildWindowsRestrictAclArgs(targetPath, currentUserSid, isDirectory), - { - stdio: ['ignore', 'ignore', 'ignore'], - windowsHide: true, - timeout: 5000 - } - ) - return true - } catch { - // Why: best-effort — a failed ACL apply must not crash the write; false leaves the path uncached to retry later. - return false - } -} - -const WINDOWS_RESTRICT_ACL_SCRIPT = ` -$ErrorActionPreference = 'Stop' -$path = $args[0] -$currentUserSid = $args[1] -$isDirectory = $args[2] -eq '1' -$allowedSidTexts = @($currentUserSid, 'S-1-5-18', 'S-1-5-32-544') -$allowedSids = @{} -foreach ($sidText in $allowedSidTexts) { - $allowedSids[$sidText] = $true -} -$acl = Get-Acl -LiteralPath $path -$acl.SetAccessRuleProtection($true, $false) -foreach ($rule in @($acl.Access)) { - [void]$acl.RemoveAccessRuleSpecific($rule) -} -$inheritanceFlags = [System.Security.AccessControl.InheritanceFlags]::None -if ($isDirectory) { - $inheritanceFlags = [System.Security.AccessControl.InheritanceFlags]::ContainerInherit -bor [System.Security.AccessControl.InheritanceFlags]::ObjectInherit -} -foreach ($sidText in $allowedSidTexts) { - $sid = [System.Security.Principal.SecurityIdentifier]::new($sidText) - $rule = [System.Security.AccessControl.FileSystemAccessRule]::new( - $sid, - [System.Security.AccessControl.FileSystemRights]::FullControl, - $inheritanceFlags, - [System.Security.AccessControl.PropagationFlags]::None, - [System.Security.AccessControl.AccessControlType]::Allow - ) - [void]$acl.AddAccessRule($rule) -} -Set-Acl -LiteralPath $path -AclObject $acl -$verifiedAcl = Get-Acl -LiteralPath $path -if (-not $verifiedAcl.AreAccessRulesProtected) { - throw 'ACL inheritance is still enabled' -} -$fullControl = [System.Security.AccessControl.FileSystemRights]::FullControl -foreach ($rule in @($verifiedAcl.Access)) { - $sid = $rule.IdentityReference.Translate([System.Security.Principal.SecurityIdentifier]).Value - if (-not $allowedSids.ContainsKey($sid)) { - throw "Unexpected ACL entry $sid" - } - if ($rule.AccessControlType -ne [System.Security.AccessControl.AccessControlType]::Allow) { - throw "Unexpected ACL deny entry $sid" - } - if (($rule.FileSystemRights -band $fullControl) -ne $fullControl) { - throw "ACL entry $sid does not grant FullControl" - } -} -`.trim() - -function getCurrentWindowsUserSid(): string | null { - if (cachedWindowsUserSid !== undefined) { - return cachedWindowsUserSid - } - try { - const output = execFileSync( - getWindowsSystemToolPath('whoami.exe'), - ['/user', '/fo', 'csv', '/nh'], - { - encoding: 'utf-8', - stdio: ['ignore', 'pipe', 'ignore'], - windowsHide: true, - timeout: 5000 - } - ).trim() - const columns = parseCsvLine(output) - cachedWindowsUserSid = columns[1] ?? null - } catch { - cachedWindowsUserSid = null - } - return cachedWindowsUserSid -} - -function getWindowsSystemToolPath(relativeSystem32Path: string): string { - const systemRoot = process.env.SystemRoot || process.env.WINDIR || 'C:\\Windows' - return pathWin32.join(systemRoot, 'System32', relativeSystem32Path) -} - -function parseCsvLine(line: string): string[] { - return line.split(/","/).map((part) => part.replace(/^"/, '').replace(/"$/, '')) -} - export function __resetSecureFileWindowsUserSidForTests(): void { - cachedWindowsUserSid = undefined + resetSecureFileWindowsUserSidForTests() } -export function __resetSecureFileHardenedPathsForTests(): void { - hardenedPathsThisProcess.clear() - hardenedDirectoryPathsThisProcess.clear() +export function __resetSecureFileHardenedPathsForTests( + bounds: SecurePathHardeningCacheBounds = DEFAULT_HARDENING_CACHE_BOUNDS +): void { + hardenedPathsThisProcess = new SecurePathHardeningCache(bounds) + hardenedDirectoryPathsThisProcess = new SecurePathHardeningCache(bounds) +} + +export function __getSecureFileHardeningCacheStateForTests(): { + paths: ReturnType['state']> + directories: ReturnType['state']> +} { + return { + paths: hardenedPathsThisProcess.state(), + directories: hardenedDirectoryPathsThisProcess.state() + } } diff --git a/src/shared/secure-path-hardening-cache.test.ts b/src/shared/secure-path-hardening-cache.test.ts new file mode 100644 index 000000000..4d5460921 --- /dev/null +++ b/src/shared/secure-path-hardening-cache.test.ts @@ -0,0 +1,61 @@ +import { describe, expect, it } from 'vitest' +import { SecurePathHardeningCache } from './secure-path-hardening-cache' + +describe('SecurePathHardeningCache', () => { + it('accepts a UTF-8 key at the exact per-key boundary', () => { + const cache = new SecurePathHardeningCache({ + maxEntries: 2, + maxKeyBytes: 6, + maxTotalKeyBytes: 6 + }) + + expect(cache.set('界界', 1)).toBe(true) + expect(cache.get('界界')).toBe(1) + expect(cache.state()).toMatchObject({ entries: 1, keyBytes: 6 }) + }) + + it('rejects one byte beyond the per-key boundary without evicting retained state', () => { + const cache = new SecurePathHardeningCache({ + maxEntries: 2, + maxKeyBytes: 6, + maxTotalKeyBytes: 12 + }) + cache.set('kept', 1) + + expect(cache.set('1234567', 2)).toBe(false) + expect(cache.state().paths).toEqual(['kept']) + }) + + it('evicts the least-recently-used entry at the count boundary', () => { + const cache = new SecurePathHardeningCache({ + maxEntries: 2, + maxKeyBytes: 32, + maxTotalKeyBytes: 64 + }) + cache.set('old', 1) + cache.set('hot', 2) + expect(cache.get('old')).toBe(1) + + cache.set('new', 3) + + expect(cache.state().paths).toEqual(['old', 'new']) + expect(cache.get('hot')).toBeUndefined() + }) + + it('evicts LRU entries until aggregate UTF-8 key bytes fit', () => { + const cache = new SecurePathHardeningCache({ + maxEntries: 10, + maxKeyBytes: 12, + maxTotalKeyBytes: 12 + }) + cache.set('aaaa', 1) + cache.set('bbbb', 2) + + expect(cache.set('界界', 3)).toBe(true) + expect(cache.state()).toEqual({ + entries: 2, + keyBytes: 10, + paths: ['bbbb', '界界'] + }) + }) +}) diff --git a/src/shared/secure-path-hardening-cache.ts b/src/shared/secure-path-hardening-cache.ts new file mode 100644 index 000000000..3ec32de4f --- /dev/null +++ b/src/shared/secure-path-hardening-cache.ts @@ -0,0 +1,74 @@ +export type SecurePathHardeningCacheBounds = { + maxEntries: number + maxKeyBytes: number + maxTotalKeyBytes: number +} + +type RetainedSecurePath = { + value: T + keyBytes: number +} + +export class SecurePathHardeningCache { + private readonly entries = new Map>() + private retainedKeyBytes = 0 + + constructor(private readonly bounds: SecurePathHardeningCacheBounds) {} + + get(path: string): T | undefined { + const retained = this.entries.get(path) + if (!retained) { + return undefined + } + this.entries.delete(path) + this.entries.set(path, retained) + return retained.value + } + + set(path: string, value: T): boolean { + const keyBytes = Buffer.byteLength(path, 'utf8') + this.delete(path) + if ( + keyBytes > this.bounds.maxKeyBytes || + keyBytes > this.bounds.maxTotalKeyBytes || + this.bounds.maxEntries <= 0 + ) { + return false + } + while ( + this.entries.size >= this.bounds.maxEntries || + this.retainedKeyBytes + keyBytes > this.bounds.maxTotalKeyBytes + ) { + const oldest = this.entries.keys().next().value + if (oldest === undefined) { + return false + } + this.delete(oldest) + } + this.entries.set(path, { value, keyBytes }) + this.retainedKeyBytes += keyBytes + return true + } + + delete(path: string): void { + const retained = this.entries.get(path) + if (!retained) { + return + } + this.entries.delete(path) + this.retainedKeyBytes -= retained.keyBytes + } + + clear(): void { + this.entries.clear() + this.retainedKeyBytes = 0 + } + + state(): { entries: number; keyBytes: number; paths: string[] } { + return { + entries: this.entries.size, + keyBytes: this.retainedKeyBytes, + paths: [...this.entries.keys()] + } + } +} diff --git a/src/shared/secure-path-windows-acl.ts b/src/shared/secure-path-windows-acl.ts new file mode 100644 index 000000000..4d61dff79 --- /dev/null +++ b/src/shared/secure-path-windows-acl.ts @@ -0,0 +1,150 @@ +import { execFile, execFileSync } from 'node:child_process' +import { win32 as pathWin32 } from 'node:path' + +let cachedWindowsUserSid: string | null | undefined + +function buildWindowsRestrictAclArgs( + targetPath: string, + currentUserSid: string, + isDirectory: boolean +): string[] { + return [ + '-NoProfile', + '-NonInteractive', + '-ExecutionPolicy', + 'Bypass', + '-Command', + WINDOWS_RESTRICT_ACL_SCRIPT, + targetPath, + currentUserSid, + isDirectory ? '1' : '0' + ] +} + +export function bestEffortRestrictWindowsPath(targetPath: string, isDirectory: boolean): void { + const currentUserSid = getCurrentWindowsUserSid() + if (!currentUserSid) { + return + } + // Why: async to avoid blocking the main thread — sync PowerShell cold-start (~1-1.5s) on the frequent read path stormed it (#4901). + execFile( + getWindowsSystemToolPath('WindowsPowerShell\\v1.0\\powershell.exe'), + buildWindowsRestrictAclArgs(targetPath, currentUserSid, isDirectory), + { + windowsHide: true, + timeout: 5000 + }, + () => { + // Why: ignore errors — hardening is best-effort; PowerShell ACL APIs may be unavailable or locked down. + } + ) +} + +export function restrictWindowsPathSync(targetPath: string, isDirectory: boolean): boolean { + const currentUserSid = getCurrentWindowsUserSid() + if (!currentUserSid) { + return false + } + // Why: file must not be published until its ACL is actually restricted, so block and report real success (read path stays async, #4901). + try { + execFileSync( + getWindowsSystemToolPath('WindowsPowerShell\\v1.0\\powershell.exe'), + buildWindowsRestrictAclArgs(targetPath, currentUserSid, isDirectory), + { + stdio: ['ignore', 'ignore', 'ignore'], + windowsHide: true, + timeout: 5000 + } + ) + return true + } catch { + // Why: best-effort — a failed ACL apply must not crash the write; false leaves the path uncached to retry later. + return false + } +} + +const WINDOWS_RESTRICT_ACL_SCRIPT = ` +$ErrorActionPreference = 'Stop' +$path = $args[0] +$currentUserSid = $args[1] +$isDirectory = $args[2] -eq '1' +$allowedSidTexts = @($currentUserSid, 'S-1-5-18', 'S-1-5-32-544') +$allowedSids = @{} +foreach ($sidText in $allowedSidTexts) { + $allowedSids[$sidText] = $true +} +$acl = Get-Acl -LiteralPath $path +$acl.SetAccessRuleProtection($true, $false) +foreach ($rule in @($acl.Access)) { + [void]$acl.RemoveAccessRuleSpecific($rule) +} +$inheritanceFlags = [System.Security.AccessControl.InheritanceFlags]::None +if ($isDirectory) { + $inheritanceFlags = [System.Security.AccessControl.InheritanceFlags]::ContainerInherit -bor [System.Security.AccessControl.InheritanceFlags]::ObjectInherit +} +foreach ($sidText in $allowedSidTexts) { + $sid = [System.Security.Principal.SecurityIdentifier]::new($sidText) + $rule = [System.Security.AccessControl.FileSystemAccessRule]::new( + $sid, + [System.Security.AccessControl.FileSystemRights]::FullControl, + $inheritanceFlags, + [System.Security.AccessControl.PropagationFlags]::None, + [System.Security.AccessControl.AccessControlType]::Allow + ) + [void]$acl.AddAccessRule($rule) +} +Set-Acl -LiteralPath $path -AclObject $acl +$verifiedAcl = Get-Acl -LiteralPath $path +if (-not $verifiedAcl.AreAccessRulesProtected) { + throw 'ACL inheritance is still enabled' +} +$fullControl = [System.Security.AccessControl.FileSystemRights]::FullControl +foreach ($rule in @($verifiedAcl.Access)) { + $sid = $rule.IdentityReference.Translate([System.Security.Principal.SecurityIdentifier]).Value + if (-not $allowedSids.ContainsKey($sid)) { + throw "Unexpected ACL entry $sid" + } + if ($rule.AccessControlType -ne [System.Security.AccessControl.AccessControlType]::Allow) { + throw "Unexpected ACL deny entry $sid" + } + if (($rule.FileSystemRights -band $fullControl) -ne $fullControl) { + throw "ACL entry $sid does not grant FullControl" + } +} +`.trim() + +function getCurrentWindowsUserSid(): string | null { + if (cachedWindowsUserSid !== undefined) { + return cachedWindowsUserSid + } + try { + const output = execFileSync( + getWindowsSystemToolPath('whoami.exe'), + ['/user', '/fo', 'csv', '/nh'], + { + encoding: 'utf-8', + stdio: ['ignore', 'pipe', 'ignore'], + windowsHide: true, + timeout: 5000 + } + ).trim() + const columns = parseCsvLine(output) + cachedWindowsUserSid = columns[1] ?? null + } catch { + cachedWindowsUserSid = null + } + return cachedWindowsUserSid +} + +function getWindowsSystemToolPath(relativeSystem32Path: string): string { + const systemRoot = process.env.SystemRoot || process.env.WINDIR || 'C:\\Windows' + return pathWin32.join(systemRoot, 'System32', relativeSystem32Path) +} + +function parseCsvLine(line: string): string[] { + return line.split(/","/).map((part) => part.replace(/^"/, '').replace(/"$/, '')) +} + +export function resetSecureFileWindowsUserSidForTests(): void { + cachedWindowsUserSid = undefined +} diff --git a/src/shared/serve-update-handoff.ts b/src/shared/serve-update-handoff.ts index 4d2e19348..3dddd2a38 100644 --- a/src/shared/serve-update-handoff.ts +++ b/src/shared/serve-update-handoff.ts @@ -1,7 +1,11 @@ import { join } from 'node:path' +import { assertJsonTextStructureWithinLimits } from './json-text-structure-limit' export const SERVE_UPDATE_HANDOFF_PATH_ENV = 'ORCA_SERVE_UPDATE_HANDOFF_PATH' export const SERVE_UPDATE_HANDOFF_FILE = 'serve-update-handoff.json' +export const MAX_SERVE_UPDATE_HANDOFF_FILE_BYTES = 64 * 1024 +export const MAX_SERVE_UPDATE_HANDOFF_JSON_STRUCTURAL_TOKENS = 16 * 1024 +export const MAX_SERVE_UPDATE_HANDOFF_JSON_NESTING_DEPTH = 32 export type ServeUpdateHandoffState = | { @@ -61,6 +65,14 @@ export function parseServeUpdateHandoffState(value: unknown): ServeUpdateHandoff return state as ServeUpdateHandoffState } +export function parseServeUpdateHandoffJson(serialized: string): ServeUpdateHandoffState | null { + assertJsonTextStructureWithinLimits(serialized, { + structuralTokens: MAX_SERVE_UPDATE_HANDOFF_JSON_STRUCTURAL_TOKENS, + nestingDepth: MAX_SERVE_UPDATE_HANDOFF_JSON_NESTING_DEPTH + }) + return parseServeUpdateHandoffState(JSON.parse(serialized)) +} + export function parseServeSupervisorMessage(value: unknown): ServeSupervisorMessage | null { if (!value || typeof value !== 'object') { return null diff --git a/src/shared/setup-script-import-codex-environment.ts b/src/shared/setup-script-import-codex-environment.ts index 45d8fd9ba..77a8e4829 100644 --- a/src/shared/setup-script-import-codex-environment.ts +++ b/src/shared/setup-script-import-codex-environment.ts @@ -1,4 +1,12 @@ import type { SetupScriptImportCandidate, SetupScriptImportFileRead } from './setup-script-imports' +import { + isSetupScriptImportFieldWithinLimit, + SETUP_SCRIPT_IMPORT_MAX_FIELD_BYTES, + SETUP_SCRIPT_IMPORT_MAX_FIELD_CODE_UNITS, + SETUP_SCRIPT_IMPORT_MAX_TOML_LINES, + SETUP_SCRIPT_IMPORT_MAX_UNSUPPORTED_FIELDS +} from './setup-script-import-limits' +import { measureUtf8ByteLength } from './utf8-byte-limits' const CODEX_ENVIRONMENT_PATH = '.codex/environments/environment.toml' @@ -17,7 +25,7 @@ export async function inspectCodexEnvironmentConfig( } const parsed = parseCodexEnvironmentToml(content) - const setup = parsed.setupScript?.trim() + const setup = normalizeCodexScript(parsed.setupScript) if (!setup) { return null } @@ -27,12 +35,15 @@ export async function inspectCodexEnvironmentConfig( label: 'Codex environment', files: [CODEX_ENVIRONMENT_PATH], setup, - archive: parsed.cleanupScript?.trim() || undefined, + archive: normalizeCodexScript(parsed.cleanupScript) || undefined, unsupportedFields: parsed.unsupportedFields } } function parseCodexEnvironmentToml(content: string): CodexEnvironmentToml { + if (countTomlLines(content) > SETUP_SCRIPT_IMPORT_MAX_TOML_LINES) { + return { unsupportedFields: [] } + } const lines = content.split(/\r?\n/) const unsupportedFields: string[] = [] let section = '' @@ -43,13 +54,13 @@ function parseCodexEnvironmentToml(content: string): CodexEnvironmentToml { const line = lines[index] const trimmed = line.trim() if (/^actions\s*=/.test(trimmed)) { - unsupportedFields.push('actions') + pushUnsupportedField(unsupportedFields, 'actions') } const sectionMatch = trimmed.match(/^\[([A-Za-z0-9_.-]+)\]\s*(?:#.*)?$/) if (sectionMatch) { section = sectionMatch[1] if (section === 'actions' || section.startsWith('actions.')) { - unsupportedFields.push(`[${section}]`) + pushUnsupportedField(unsupportedFields, `[${section}]`) } continue } @@ -100,22 +111,49 @@ function parseTomlMultilineString( firstLineRemainder: string, delimiter: '"""' | "'''" ): { value: string; endLineIndex: number } { - let content = '' + const chunks: string[] = [] + let retainedBytes = 0 + let retainedCodeUnits = 0 let remainder = firstLineRemainder + let oversized = false + const append = (value: string): boolean => { + if (retainedCodeUnits + value.length > SETUP_SCRIPT_IMPORT_MAX_FIELD_CODE_UNITS) { + return false + } + const measurement = measureUtf8ByteLength(value, { + stopAfterBytes: SETUP_SCRIPT_IMPORT_MAX_FIELD_BYTES - retainedBytes + }) + if (measurement.exceededLimit) { + return false + } + chunks.push(value) + retainedBytes += measurement.byteLength + retainedCodeUnits += value.length + return true + } for (let index = startLineIndex; index < lines.length; index++) { if (index > startLineIndex) { remainder = lines[index] } const closeIndex = remainder.indexOf(delimiter) if (closeIndex >= 0) { + if (!oversized && !append(remainder.slice(0, closeIndex))) { + oversized = true + } return { - value: content + remainder.slice(0, closeIndex), + value: oversized ? '' : chunks.join(''), endLineIndex: index } } - content += `${remainder}\n` + if (!oversized && !append(`${remainder}\n`)) { + oversized = true + chunks.length = 0 + } + } + return { + value: oversized ? '' : chunks.join('').trimEnd(), + endLineIndex: lines.length - 1 } - return { value: content.trimEnd(), endLineIndex: lines.length - 1 } } function parseTomlBasicString(value: string): string { @@ -151,3 +189,26 @@ function isEscaped(value: string, index: number): boolean { } return slashCount % 2 === 1 } + +function normalizeCodexScript(value: string | undefined): string { + if (!value || !isSetupScriptImportFieldWithinLimit(value)) { + return '' + } + return value.trim() +} + +function countTomlLines(content: string): number { + let lines = 1 + for (let index = 0; index < content.length; index++) { + if (content.charCodeAt(index) === 10 && ++lines > SETUP_SCRIPT_IMPORT_MAX_TOML_LINES) { + return lines + } + } + return lines +} + +function pushUnsupportedField(fields: string[], value: string): void { + if (fields.length < SETUP_SCRIPT_IMPORT_MAX_UNSUPPORTED_FIELDS) { + fields.push(value) + } +} diff --git a/src/shared/setup-script-import-command-limits.ts b/src/shared/setup-script-import-command-limits.ts new file mode 100644 index 000000000..16eacd084 --- /dev/null +++ b/src/shared/setup-script-import-command-limits.ts @@ -0,0 +1,49 @@ +import { + isSetupScriptImportFieldWithinLimit, + SETUP_SCRIPT_IMPORT_MAX_COMMAND_PARTS, + SETUP_SCRIPT_IMPORT_MAX_FIELD_CODE_UNITS, + SETUP_SCRIPT_IMPORT_MAX_UNSUPPORTED_FIELDS +} from './setup-script-import-limits' + +export function normalizeSetupScriptImportCommand(value: unknown): string { + if (typeof value === 'string') { + return normalizeCommandString(value) + } + if (!Array.isArray(value) || value.length > SETUP_SCRIPT_IMPORT_MAX_COMMAND_PARTS) { + return '' + } + const commands: string[] = [] + for (const item of value) { + const command = typeof item === 'string' ? normalizeCommandString(item) : '' + if (command) { + commands.push(command) + } + } + return joinSetupScriptImportCommands(commands) +} + +export function joinSetupScriptImportCommands(parts: string[]): string { + let command = '' + for (const part of parts) { + const next = command ? `${command}\n${part}` : part + if (!isSetupScriptImportFieldWithinLimit(next)) { + return '' + } + command = next + } + return command +} + +export function pushSetupScriptImportUnsupportedField(fields: string[], value: string): void { + if (fields.length < SETUP_SCRIPT_IMPORT_MAX_UNSUPPORTED_FIELDS) { + fields.push(value) + } +} + +function normalizeCommandString(value: string): string { + if (value.length > SETUP_SCRIPT_IMPORT_MAX_FIELD_CODE_UNITS) { + return '' + } + const trimmed = value.trim() + return trimmed && isSetupScriptImportFieldWithinLimit(trimmed) ? trimmed : '' +} diff --git a/src/shared/setup-script-import-limits.ts b/src/shared/setup-script-import-limits.ts new file mode 100644 index 000000000..d409586db --- /dev/null +++ b/src/shared/setup-script-import-limits.ts @@ -0,0 +1,34 @@ +import { measureUtf8ByteLength } from './utf8-byte-limits' + +export const SETUP_SCRIPT_IMPORT_FILE_MAX_BYTES = 256 * 1024 +export const SETUP_SCRIPT_IMPORT_MAX_CODE_UNITS = 256 * 1024 +export const SETUP_SCRIPT_IMPORT_MAX_FIELD_BYTES = 64 * 1024 +export const SETUP_SCRIPT_IMPORT_MAX_FIELD_CODE_UNITS = 64 * 1024 +export const SETUP_SCRIPT_IMPORT_MAX_COMMAND_PARTS = 256 +export const SETUP_SCRIPT_IMPORT_MAX_CMUX_COMMANDS = 256 +export const SETUP_SCRIPT_IMPORT_MAX_KEYWORDS = 64 +export const SETUP_SCRIPT_IMPORT_MAX_UNSUPPORTED_FIELDS = 128 +export const SETUP_SCRIPT_IMPORT_MAX_TOML_LINES = 4_096 + +export function isSetupScriptImportTextWithinLimit(content: string): boolean { + return isTextWithinLimits( + content, + SETUP_SCRIPT_IMPORT_FILE_MAX_BYTES, + SETUP_SCRIPT_IMPORT_MAX_CODE_UNITS + ) +} + +export function isSetupScriptImportFieldWithinLimit(value: string): boolean { + return isTextWithinLimits( + value, + SETUP_SCRIPT_IMPORT_MAX_FIELD_BYTES, + SETUP_SCRIPT_IMPORT_MAX_FIELD_CODE_UNITS + ) +} + +function isTextWithinLimits(value: string, maxBytes: number, maxCodeUnits: number): boolean { + return ( + value.length <= maxCodeUnits && + !measureUtf8ByteLength(value, { stopAfterBytes: maxBytes }).exceededLimit + ) +} diff --git a/src/shared/setup-script-imports.test.ts b/src/shared/setup-script-imports.test.ts index 97e62d691..3215ab815 100644 --- a/src/shared/setup-script-imports.test.ts +++ b/src/shared/setup-script-imports.test.ts @@ -1,11 +1,126 @@ -import { describe, expect, it } from 'vitest' +import { afterEach, describe, expect, it, vi } from 'vitest' import { inspectSetupScriptImportCandidates } from './setup-script-imports' +import { + SETUP_SCRIPT_IMPORT_FILE_MAX_BYTES, + SETUP_SCRIPT_IMPORT_MAX_CMUX_COMMANDS, + SETUP_SCRIPT_IMPORT_MAX_COMMAND_PARTS, + SETUP_SCRIPT_IMPORT_MAX_FIELD_BYTES, + SETUP_SCRIPT_IMPORT_MAX_FIELD_CODE_UNITS, + SETUP_SCRIPT_IMPORT_MAX_TOML_LINES +} from './setup-script-import-limits' function makeReader(files: Record) { return async (relativePath: string): Promise => files[relativePath] ?? null } +afterEach(() => { + vi.restoreAllMocks() +}) + describe('inspectSetupScriptImportCandidates', () => { + it('parses the exact input boundary and rejects +1 before JSON parsing', async () => { + const parse = vi.spyOn(JSON, 'parse') + const suffix = '{"setup":"pnpm install"}' + const exact = `${' '.repeat(SETUP_SCRIPT_IMPORT_FILE_MAX_BYTES - suffix.length)}${suffix}` + + await expect( + inspectSetupScriptImportCandidates(makeReader({ '.superset/config.json': exact })) + ).resolves.toHaveLength(1) + expect(parse).toHaveBeenCalledOnce() + + parse.mockClear() + await expect( + inspectSetupScriptImportCandidates(makeReader({ '.superset/config.json': `${exact} ` })) + ).resolves.toEqual([]) + expect(parse).not.toHaveBeenCalled() + }) + + it('rejects multibyte input over the byte cap before JSON parsing', async () => { + const parse = vi.spyOn(JSON, 'parse') + + await expect( + inspectSetupScriptImportCandidates( + makeReader({ + '.superset/config.json': 'é'.repeat(SETUP_SCRIPT_IMPORT_FILE_MAX_BYTES / 2 + 1) + }) + ) + ).resolves.toEqual([]) + expect(parse).not.toHaveBeenCalled() + }) + + it('admits the exact command-part cardinality and rejects +1', async () => { + const inspect = (setup: string[]) => + inspectSetupScriptImportCandidates( + makeReader({ '.superset/config.json': JSON.stringify({ setup }) }) + ) + const exact = Array.from({ length: SETUP_SCRIPT_IMPORT_MAX_COMMAND_PARTS }, () => 'x') + + await expect(inspect(exact)).resolves.toMatchObject([{ setup: exact.join('\n') }]) + await expect(inspect([...exact, 'overflow'])).resolves.toEqual([]) + }) + + it('admits an exact-size script field and rejects +1', async () => { + const inspect = (setup: string) => + inspectSetupScriptImportCandidates( + makeReader({ '.superset/config.json': JSON.stringify({ setup }) }) + ) + const exact = 'x'.repeat(SETUP_SCRIPT_IMPORT_MAX_FIELD_CODE_UNITS) + const exactUtf8 = 'é'.repeat(SETUP_SCRIPT_IMPORT_MAX_FIELD_BYTES / 2) + + await expect(inspect(exact)).resolves.toMatchObject([{ setup: exact }]) + await expect(inspect(`${exact}x`)).resolves.toEqual([]) + await expect(inspect(exactUtf8)).resolves.toMatchObject([{ setup: exactUtf8 }]) + await expect(inspect(`${exactUtf8}é`)).resolves.toEqual([]) + }) + + it('bounds Codex multiline script accumulation at the exact field limit', async () => { + const inspect = (setup: string) => + inspectSetupScriptImportCandidates( + makeReader({ + '.codex/environments/environment.toml': `[setup]\nscript = """${setup}"""` + }) + ) + const exact = 'x'.repeat(SETUP_SCRIPT_IMPORT_MAX_FIELD_CODE_UNITS) + + await expect(inspect(exact)).resolves.toMatchObject([{ provider: 'codex', setup: exact }]) + await expect(inspect(`${exact}x`)).resolves.toEqual([]) + }) + + it('bounds cmux command scans and Codex TOML line splitting', async () => { + const commands = Array.from({ length: SETUP_SCRIPT_IMPORT_MAX_CMUX_COMMANDS }, (_, index) => ({ + name: index === SETUP_SCRIPT_IMPORT_MAX_CMUX_COMMANDS - 1 ? 'Setup' : 'Build', + command: 'pnpm install' + })) + await expect( + inspectSetupScriptImportCandidates( + makeReader({ '.cmux/cmux.json': JSON.stringify({ commands }) }) + ) + ).resolves.toMatchObject([{ provider: 'cmux' }]) + await expect( + inspectSetupScriptImportCandidates( + makeReader({ + '.cmux/cmux.json': JSON.stringify({ + commands: [...commands, { name: 'Overflow', command: 'true' }] + }) + }) + ) + ).resolves.toEqual([]) + + const exactToml = `[setup]\nscript = "pnpm install"${'\n'.repeat( + SETUP_SCRIPT_IMPORT_MAX_TOML_LINES - 2 + )}` + await expect( + inspectSetupScriptImportCandidates( + makeReader({ '.codex/environments/environment.toml': exactToml }) + ) + ).resolves.toMatchObject([{ provider: 'codex' }]) + await expect( + inspectSetupScriptImportCandidates( + makeReader({ '.codex/environments/environment.toml': `${exactToml}\n` }) + ) + ).resolves.toEqual([]) + }) + it('imports setup and teardown commands from Superset config', async () => { const candidates = await inspectSetupScriptImportCandidates( makeReader({ diff --git a/src/shared/setup-script-imports.ts b/src/shared/setup-script-imports.ts index 1d32d9a76..5aa698d13 100644 --- a/src/shared/setup-script-imports.ts +++ b/src/shared/setup-script-imports.ts @@ -1,6 +1,18 @@ import { inspectCodexEnvironmentConfig } from './setup-script-import-codex-environment' import { inspectPackageManagerSetupCandidate } from './setup-script-package-manager-suggestion' import type { SetupScriptImportProvider } from './setup-script-import-providers' +import { + isSetupScriptImportFieldWithinLimit, + isSetupScriptImportTextWithinLimit, + SETUP_SCRIPT_IMPORT_MAX_CMUX_COMMANDS, + SETUP_SCRIPT_IMPORT_MAX_KEYWORDS, + SETUP_SCRIPT_IMPORT_MAX_UNSUPPORTED_FIELDS +} from './setup-script-import-limits' +import { + joinSetupScriptImportCommands, + normalizeSetupScriptImportCommand, + pushSetupScriptImportUnsupportedField +} from './setup-script-import-command-limits' export type SetupScriptImportCandidate = { provider: SetupScriptImportProvider @@ -23,12 +35,16 @@ export async function inspectSetupScriptImportCandidates( readFile: SetupScriptImportFileRead, options?: { fileExists?: SetupScriptImportFileExists } ): Promise { + const boundedReadFile: SetupScriptImportFileRead = async (relativePath) => { + const content = await readFile(relativePath) + return content !== null && isSetupScriptImportTextWithinLimit(content) ? content : null + } const candidates = await Promise.all([ - inspectSupersetConfig(readFile), - inspectConductorConfig(readFile), - inspectCodexEnvironmentConfig(readFile), - inspectCmuxConfig(readFile), - inspectPackageManagerSetupCandidate(readFile, options?.fileExists) + inspectSupersetConfig(boundedReadFile), + inspectConductorConfig(boundedReadFile), + inspectCodexEnvironmentConfig(boundedReadFile), + inspectCmuxConfig(boundedReadFile), + inspectPackageManagerSetupCandidate(boundedReadFile, options?.fileExists) ]) return candidates.filter( (candidate): candidate is SetupScriptImportCandidate => candidate != null @@ -94,7 +110,7 @@ async function inspectConductorConfig( return null } - const setup = normalizeCommandValue(scripts.setup) + const setup = normalizeSetupScriptImportCommand(scripts.setup) if (!setup) { return null } @@ -104,7 +120,7 @@ async function inspectConductorConfig( 'runScriptMode' ]) for (const field of ['run', 'teardown'] as const) { - if (normalizeCommandValue(scripts[field])) { + if (normalizeSetupScriptImportCommand(scripts[field])) { unsupportedFields.push(`scripts.${field}`) } } @@ -114,7 +130,7 @@ async function inspectConductorConfig( label: 'Conductor', files: [CONDUCTOR_CONFIG_PATH], setup, - archive: normalizeCommandValue(scripts.archive) || undefined, + archive: normalizeSetupScriptImportCommand(scripts.archive) || undefined, unsupportedFields } } @@ -149,48 +165,41 @@ function asRecord(value: unknown): Record | null { : null } -function normalizeCommandValue(value: unknown): string { - if (typeof value === 'string') { - return value.trim() - } - if (!Array.isArray(value)) { - return '' - } - const commands = value - .map((item) => (typeof item === 'string' ? item.trim() : '')) - .filter(Boolean) - return commands.join('\n') -} - function resolveSupersetScriptValue( baseValue: unknown, localValue: unknown, key: 'setup' | 'teardown', unsupportedFields: string[] ): string { - const baseCommand = normalizeCommandValue(baseValue) + const baseCommand = normalizeSetupScriptImportCommand(baseValue) if (localValue === undefined) { return baseCommand } if (typeof localValue === 'string' || Array.isArray(localValue)) { - return normalizeCommandValue(localValue) + return normalizeSetupScriptImportCommand(localValue) } const localRecord = asRecord(localValue) if (!localRecord) { - unsupportedFields.push(`config.local.${key}`) + pushSetupScriptImportUnsupportedField(unsupportedFields, `config.local.${key}`) return baseCommand } - for (const field of Object.keys(localRecord)) { + for (const field in localRecord) { + if (!Object.prototype.hasOwnProperty.call(localRecord, field)) { + continue + } if (field !== 'before' && field !== 'after') { - unsupportedFields.push(`config.local.${key}.${field}`) + pushSetupScriptImportUnsupportedField(unsupportedFields, `config.local.${key}.${field}`) + if (unsupportedFields.length >= SETUP_SCRIPT_IMPORT_MAX_UNSUPPORTED_FIELDS) { + break + } } } - const beforeCommand = normalizeCommandValue(localRecord.before) - const afterCommand = normalizeCommandValue(localRecord.after) - return [beforeCommand, baseCommand, afterCommand].filter(Boolean).join('\n') + const beforeCommand = normalizeSetupScriptImportCommand(localRecord.before) + const afterCommand = normalizeSetupScriptImportCommand(localRecord.after) + return joinSetupScriptImportCommands([beforeCommand, baseCommand, afterCommand].filter(Boolean)) } function buildCmuxSetupCandidate( @@ -198,13 +207,16 @@ function buildCmuxSetupCandidate( config: Record ): SetupScriptImportCandidate | null { const commands = Array.isArray(config.commands) ? config.commands : [] + if (commands.length > SETUP_SCRIPT_IMPORT_MAX_CMUX_COMMANDS) { + return null + } for (let index = 0; index < commands.length; index++) { const command = asRecord(commands[index]) if (!command || !isCmuxSetupCommand(command)) { continue } - const setup = normalizeCommandValue(command.command) + const setup = normalizeSetupScriptImportCommand(command.command) if (!setup) { continue } @@ -221,7 +233,11 @@ function buildCmuxSetupCandidate( } function isCmuxSetupCommand(command: Record): boolean { - if (typeof command.command !== 'string' || !command.command.trim()) { + if ( + typeof command.command !== 'string' || + !isSetupScriptImportFieldWithinLimit(command.command) || + !command.command.trim() + ) { return false } @@ -249,11 +265,13 @@ function isCmuxSetupCommand(command: Record): boolean { } function normalizeMatchText(value: unknown): string { - return typeof value === 'string' ? value.trim().toLowerCase().replace(/\s+/g, ' ') : '' + return typeof value === 'string' && isSetupScriptImportFieldWithinLimit(value) + ? value.trim().toLowerCase().replace(/\s+/g, ' ') + : '' } function getStringArray(value: unknown): string[] { - return Array.isArray(value) + return Array.isArray(value) && value.length <= SETUP_SCRIPT_IMPORT_MAX_KEYWORDS ? value.filter((item): item is string => typeof item === 'string') : [] } @@ -263,9 +281,19 @@ function collectUnsupportedCmuxCommandFields( commandIndex: number ): string[] { const supportedFields = new Set(['name', 'title', 'description', 'keywords', 'command']) - return Object.keys(command) - .filter((field) => !supportedFields.has(field)) - .map((field) => `commands.${commandIndex}.${field}`) + const unsupportedFields: string[] = [] + for (const field in command) { + if (!Object.prototype.hasOwnProperty.call(command, field)) { + continue + } + if (!supportedFields.has(field)) { + pushSetupScriptImportUnsupportedField(unsupportedFields, `commands.${commandIndex}.${field}`) + if (unsupportedFields.length >= SETUP_SCRIPT_IMPORT_MAX_UNSUPPORTED_FIELDS) { + break + } + } + } + return unsupportedFields } function collectUnsupportedFields( @@ -286,7 +314,7 @@ function collectUnsupportedScriptObjectFields( } for (const field of ['before', 'after'] as const) { if (record[field] !== undefined) { - unsupportedFields.push(`${prefix}.${field}`) + pushSetupScriptImportUnsupportedField(unsupportedFields, `${prefix}.${field}`) } } } diff --git a/src/shared/setup-script-package-manager-suggestion.ts b/src/shared/setup-script-package-manager-suggestion.ts index b2050c911..5ef842837 100644 --- a/src/shared/setup-script-package-manager-suggestion.ts +++ b/src/shared/setup-script-package-manager-suggestion.ts @@ -3,6 +3,7 @@ import type { SetupScriptImportFileExists, SetupScriptImportFileRead } from './setup-script-imports' +import { isSetupScriptImportFieldWithinLimit } from './setup-script-import-limits' const PACKAGE_JSON_PATH = 'package.json' type PackageManagerName = 'pnpm' | 'bun' | 'yarn' | 'npm' @@ -81,7 +82,7 @@ function parsePackageJson(content: string | null): Record | nul } function getPackageManagerName(value: unknown): PackageManagerName | null { - if (typeof value !== 'string') { + if (typeof value !== 'string' || !isSetupScriptImportFieldWithinLimit(value)) { return null } const packageManager = value.trim().toLowerCase() diff --git a/src/shared/ssh-retained-payload-admission.test.ts b/src/shared/ssh-retained-payload-admission.test.ts new file mode 100644 index 000000000..92a4e6c90 --- /dev/null +++ b/src/shared/ssh-retained-payload-admission.test.ts @@ -0,0 +1,106 @@ +import { describe, expect, it } from 'vitest' +import { getUtf8ByteLength } from './utf8-byte-limits' +import { + admitSshConnectionState, + admitSshDetectedPorts, + SSH_CONNECTION_ERROR_MAX_UTF8_BYTES, + SSH_DETECTED_PORTS_MAX_ENTRIES, + SSH_DETECTED_PORT_ADVERTISED_URL_MAX_UTF8_BYTES, + SSH_DETECTED_PORT_PROCESS_NAME_MAX_UTF8_BYTES, + SSH_RETAINED_IDENTIFIER_MAX_UTF8_BYTES +} from './ssh-retained-payload-admission' + +describe('SSH retained payload admission', () => { + it('keeps ordinary connection state while stripping unknown payload fields', () => { + const admitted = admitSshConnectionState( + { + targetId: 'ssh-a', + status: 'connected', + error: null, + reconnectAttempt: 2, + connectionGeneration: 3, + supportsFolderDownload: true, + remotePlatform: 'linux', + unexpected: 'x'.repeat(1024) + }, + 'ssh-a' + ) + + expect(admitted).toEqual({ + targetId: 'ssh-a', + status: 'connected', + error: null, + reconnectAttempt: 2, + connectionGeneration: 3, + supportsFolderDownload: true, + remotePlatform: 'linux' + }) + }) + + it('caps connection errors without splitting a UTF-8 code point', () => { + const admitted = admitSshConnectionState( + { + targetId: 'ssh-a', + status: 'error', + error: `${'x'.repeat(SSH_CONNECTION_ERROR_MAX_UTF8_BYTES - 1)}🙂tail`, + reconnectAttempt: 0 + }, + 'ssh-a' + ) + + expect(admitted).not.toBeNull() + expect(getUtf8ByteLength(admitted?.error ?? '')).toBeLessThanOrEqual( + SSH_CONNECTION_ERROR_MAX_UTF8_BYTES + ) + expect(admitted?.error?.endsWith('\ud83d')).toBe(false) + }) + + it('rejects mismatched and oversized target identifiers', () => { + const state = { + targetId: 'ssh-a', + status: 'connected', + error: null, + reconnectAttempt: 0 + } + + expect(admitSshConnectionState(state, 'ssh-b')).toBeNull() + expect( + admitSshConnectionState( + { ...state, targetId: 'x'.repeat(SSH_RETAINED_IDENTIFIER_MAX_UTF8_BYTES + 1) }, + 'x'.repeat(SSH_RETAINED_IDENTIFIER_MAX_UTF8_BYTES + 1) + ) + ).toBeNull() + }) + + it('caps port rows and their retained strings', () => { + const rows = Array.from({ length: SSH_DETECTED_PORTS_MAX_ENTRIES + 10 }, (_, index) => ({ + port: 1000 + index, + host: '127.0.0.1', + pid: index + 1, + processName: '🙂'.repeat(SSH_DETECTED_PORT_PROCESS_NAME_MAX_UTF8_BYTES), + advertisedUrl: `https://example.test/${'x'.repeat( + SSH_DETECTED_PORT_ADVERTISED_URL_MAX_UTF8_BYTES + )}`, + unexpected: 'retained only without admission' + })) + + const admitted = admitSshDetectedPorts(rows) + + expect(admitted).toHaveLength(SSH_DETECTED_PORTS_MAX_ENTRIES) + expect(getUtf8ByteLength(admitted[0].processName ?? '')).toBeLessThanOrEqual( + SSH_DETECTED_PORT_PROCESS_NAME_MAX_UTF8_BYTES + ) + expect(admitted[0].advertisedUrl).toBeUndefined() + expect(admitted[0]).not.toHaveProperty('unexpected') + }) + + it('drops malformed rows instead of retaining their payloads', () => { + expect( + admitSshDetectedPorts([ + { port: 0, host: '127.0.0.1' }, + { port: 3000, host: '' }, + { port: 3001, host: '127.0.0.1', processName: 'node' } + ]) + ).toEqual([{ port: 3001, host: '127.0.0.1', processName: 'node' }]) + }) +}) diff --git a/src/shared/ssh-retained-payload-admission.ts b/src/shared/ssh-retained-payload-admission.ts new file mode 100644 index 000000000..21b51787a --- /dev/null +++ b/src/shared/ssh-retained-payload-admission.ts @@ -0,0 +1,138 @@ +import type { EnrichedDetectedPort, SshConnectionState, SshConnectionStatus } from './ssh-types' +import { clampUtf8TextPrefix, measureUtf8ByteLength } from './utf8-byte-limits' + +export const SSH_RETAINED_IDENTIFIER_MAX_UTF8_BYTES = 1024 +export const SSH_CONNECTION_ERROR_MAX_UTF8_BYTES = 16 * 1024 +export const SSH_CREDENTIAL_DETAIL_MAX_UTF8_BYTES = 16 * 1024 +export const SSH_DETECTED_PORTS_MAX_ENTRIES = 50 +export const SSH_DETECTED_PORT_HOST_MAX_UTF8_BYTES = 1024 +export const SSH_DETECTED_PORT_PROCESS_NAME_MAX_UTF8_BYTES = 4 * 1024 +export const SSH_DETECTED_PORT_ADVERTISED_URL_MAX_UTF8_BYTES = 2048 + +const CONNECTION_STATUSES = new Set([ + 'disconnected', + 'connecting', + 'auth-failed', + 'deploying-relay', + 'connected', + 'reconnecting', + 'reconnection-failed', + 'error' +]) + +export function isSshRetainedIdentifier(value: unknown): value is string { + return ( + typeof value === 'string' && + value.length > 0 && + !measureUtf8ByteLength(value, { + stopAfterBytes: SSH_RETAINED_IDENTIFIER_MAX_UTF8_BYTES + }).exceededLimit + ) +} + +export function admitSshConnectionState( + value: unknown, + expectedTargetId: string +): SshConnectionState | null { + if (!value || typeof value !== 'object' || !isSshRetainedIdentifier(expectedTargetId)) { + return null + } + const input = value as Record + if ( + (input.targetId !== undefined && + (!isSshRetainedIdentifier(input.targetId) || input.targetId !== expectedTargetId)) || + typeof input.status !== 'string' || + !CONNECTION_STATUSES.has(input.status as SshConnectionStatus) || + !isNonNegativeSafeInteger(input.reconnectAttempt) || + (input.error !== null && typeof input.error !== 'string') + ) { + return null + } + + const error = clampSshConnectionError(input.error) + return { + targetId: expectedTargetId, + status: input.status as SshConnectionStatus, + error, + reconnectAttempt: input.reconnectAttempt, + ...(isNonNegativeSafeInteger(input.connectionGeneration) + ? { connectionGeneration: input.connectionGeneration } + : {}), + ...(typeof input.supportsFolderDownload === 'boolean' + ? { supportsFolderDownload: input.supportsFolderDownload } + : {}), + ...(input.remotePlatform === 'linux' || + input.remotePlatform === 'darwin' || + input.remotePlatform === 'win32' + ? { remotePlatform: input.remotePlatform } + : {}) + } +} + +export function clampSshConnectionError(error: string | null): string | null { + return typeof error === 'string' + ? clampUtf8TextPrefix(error, SSH_CONNECTION_ERROR_MAX_UTF8_BYTES) + : null +} + +export function admitSshDetectedPorts(value: unknown): EnrichedDetectedPort[] { + if (!Array.isArray(value)) { + return [] + } + const retained: EnrichedDetectedPort[] = [] + const scanLimit = Math.min(value.length, SSH_DETECTED_PORTS_MAX_ENTRIES) + for (let index = 0; index < scanLimit; index += 1) { + const port = admitDetectedPort(value[index]) + if (port) { + retained.push(port) + } + } + return retained +} + +function admitDetectedPort(value: unknown): EnrichedDetectedPort | null { + if (!value || typeof value !== 'object') { + return null + } + const input = value as Record + if ( + !Number.isSafeInteger(input.port) || + (input.port as number) < 1 || + (input.port as number) > 65_535 || + !isStringWithinLimit(input.host, SSH_DETECTED_PORT_HOST_MAX_UTF8_BYTES) + ) { + return null + } + const processName = + typeof input.processName === 'string' + ? clampUtf8TextPrefix(input.processName, SSH_DETECTED_PORT_PROCESS_NAME_MAX_UTF8_BYTES) + : undefined + const advertisedUrl = isStringWithinLimit( + input.advertisedUrl, + SSH_DETECTED_PORT_ADVERTISED_URL_MAX_UTF8_BYTES + ) + ? input.advertisedUrl + : undefined + return { + port: input.port as number, + host: input.host, + ...(isNonNegativeSafeInteger(input.pid) && input.pid > 0 ? { pid: input.pid } : {}), + ...(processName ? { processName } : {}), + ...(advertisedUrl ? { advertisedUrl } : {}), + ...(input.advertisedProtocol === 'http' || input.advertisedProtocol === 'https' + ? { advertisedProtocol: input.advertisedProtocol } + : {}) + } +} + +function isNonNegativeSafeInteger(value: unknown): value is number { + return Number.isSafeInteger(value) && (value as number) >= 0 +} + +function isStringWithinLimit(value: unknown, maxBytes: number): value is string { + return ( + typeof value === 'string' && + value.length > 0 && + !measureUtf8ByteLength(value, { stopAfterBytes: maxBytes }).exceededLimit + ) +} diff --git a/src/shared/terminal-size-limits.ts b/src/shared/terminal-size-limits.ts new file mode 100644 index 000000000..fca3d9c87 --- /dev/null +++ b/src/shared/terminal-size-limits.ts @@ -0,0 +1,34 @@ +export const MAX_TERMINAL_COLS = 500 +export const MAX_TERMINAL_ROWS = 500 + +export function terminalSizeAdmissionError( + cols: unknown, + rows: unknown, + field: string, + options: { allowMissing?: boolean } = {} +): string | null { + for (const [name, value, max] of [ + ['cols', cols, MAX_TERMINAL_COLS], + ['rows', rows, MAX_TERMINAL_ROWS] + ] as const) { + if (options.allowMissing && value === undefined) { + continue + } + if (!Number.isSafeInteger(value) || (value as number) < 1 || (value as number) > max) { + return `${field}.${name} must be an integer from 1 through ${max}` + } + } + return null +} + +export function isValidTerminalSize(cols: unknown, rows: unknown): boolean { + return terminalSizeAdmissionError(cols, rows, 'terminal size') === null +} + +export function normalizeTerminalSize( + cols: unknown, + rows: unknown, + fallback: { cols: number; rows: number } = { cols: 80, rows: 24 } +): { cols: number; rows: number } { + return isValidTerminalSize(cols, rows) ? { cols: cols as number, rows: rows as number } : fallback +} diff --git a/src/shared/terminal-stream-protocol.test.ts b/src/shared/terminal-stream-protocol.test.ts index 07de14503..f8784458a 100644 --- a/src/shared/terminal-stream-protocol.test.ts +++ b/src/shared/terminal-stream-protocol.test.ts @@ -1,4 +1,4 @@ -import { describe, expect, it } from 'vitest' +import { describe, expect, it, vi } from 'vitest' import { TerminalStreamOpcode, decodeTerminalStreamFrame, @@ -6,7 +6,8 @@ import { decodeTerminalStreamText, encodeTerminalStreamFrame, encodeTerminalStreamJson, - encodeTerminalStreamText + encodeTerminalStreamText, + TERMINAL_STREAM_JSON_STRUCTURE_LIMITS } from './terminal-stream-protocol' describe('terminal-stream-protocol', () => { @@ -138,6 +139,19 @@ describe('terminal-stream-protocol', () => { expect(ack && decodeTerminalStreamJson(ack.payload)).toEqual({ bytes: 4096 }) }) + it('rejects excessive JSON nesting before JSON.parse', () => { + const parseSpy = vi.spyOn(JSON, 'parse') + try { + const depth = TERMINAL_STREAM_JSON_STRUCTURE_LIMITS.nestingDepth + 1 + const payload = new TextEncoder().encode(`${'['.repeat(depth)}0${']'.repeat(depth)}`) + + expect(decodeTerminalStreamJson(payload)).toBeNull() + expect(parseSpy).not.toHaveBeenCalled() + } finally { + parseSpy.mockRestore() + } + }) + it('rejects unknown frame versions and opcodes', () => { const encoded = encodeTerminalStreamFrame({ opcode: TerminalStreamOpcode.Output, diff --git a/src/shared/terminal-stream-protocol.ts b/src/shared/terminal-stream-protocol.ts index bcfa3b46d..76e82eafc 100644 --- a/src/shared/terminal-stream-protocol.ts +++ b/src/shared/terminal-stream-protocol.ts @@ -1,6 +1,13 @@ +import { assertJsonTextStructureWithinLimits } from './json-text-structure-limit' + const TERMINAL_STREAM_KIND = 0x74 const TERMINAL_STREAM_VERSION = 1 const HEADER_BYTES = 16 +export const TERMINAL_STREAM_JSON_MAX_BYTES = 8 * 1024 * 1024 +export const TERMINAL_STREAM_JSON_STRUCTURE_LIMITS = { + structuralTokens: 256 * 1024, + nestingDepth: 32 +} as const export enum TerminalStreamOpcode { Output = 1, @@ -73,8 +80,13 @@ export function encodeTerminalStreamJson(value: unknown): Uint8Array { } export function decodeTerminalStreamJson(payload: Uint8Array): T | null { + if (payload.byteLength > TERMINAL_STREAM_JSON_MAX_BYTES) { + return null + } try { - return JSON.parse(new TextDecoder().decode(payload)) as T + const content = new TextDecoder().decode(payload) + assertJsonTextStructureWithinLimits(content, TERMINAL_STREAM_JSON_STRUCTURE_LIMITS) + return JSON.parse(content) as T } catch { return null } diff --git a/src/shared/text-search.test.ts b/src/shared/text-search.test.ts index 9562a366a..108d07a76 100644 --- a/src/shared/text-search.test.ts +++ b/src/shared/text-search.test.ts @@ -1,4 +1,4 @@ -import { describe, expect, it } from 'vitest' +import { describe, expect, it, vi } from 'vitest' import { execFileSync } from 'node:child_process' import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' @@ -13,6 +13,7 @@ import { ingestRgJsonLine, MAX_LINE_CONTENT_LENGTH, normalizeRelativePath, + SEARCH_JSON_STRUCTURE_LIMITS, splitSearchGlobPatterns, toGitGlobPathspec } from './text-search' @@ -117,6 +118,22 @@ describe('ingestRgJsonLine', () => { expect(acc.totalMatches).toBe(0) }) + it('rejects excessive nesting before JSON.parse', () => { + const parseSpy = vi.spyOn(JSON, 'parse') + const acc = createAccumulator() + try { + const amplified = `${'['.repeat(SEARCH_JSON_STRUCTURE_LIMITS.nestingDepth + 1)}0${']'.repeat( + SEARCH_JSON_STRUCTURE_LIMITS.nestingDepth + 1 + )}` + + expect(ingestRgJsonLine(amplified, '/root', acc, 100)).toBe('continue') + expect(parseSpy).not.toHaveBeenCalled() + expect(acc.totalMatches).toBe(0) + } finally { + parseSpy.mockRestore() + } + }) + it('creates a navigable fallback match when rg omits submatch ranges', () => { const acc = createAccumulator() const verdict = ingestRgJsonLine(makeMatch('/root/a.ts', 4, [], 'foobar'), '/root', acc, 100) diff --git a/src/shared/text-search.ts b/src/shared/text-search.ts index 0543360d2..d3d9b4022 100644 --- a/src/shared/text-search.ts +++ b/src/shared/text-search.ts @@ -11,6 +11,7 @@ * Design doc: docs/design/share-text-search.md. */ import { posix, win32 } from 'node:path' +import { assertJsonTextStructureWithinLimits } from './json-text-structure-limit' import { normalizeSearchResult } from './search-match-count' import { escapeRegex } from './string-utils' import type { SearchFileResult, SearchMatch, SearchOptions, SearchResult } from './types' @@ -54,6 +55,10 @@ function joinSearchRoot(rootPath: string, relPath: string): string { export const MAX_MATCHES_PER_FILE = 100 export const DEFAULT_SEARCH_MAX_RESULTS = 2000 export const SEARCH_TIMEOUT_MS = 15_000 +export const SEARCH_JSON_STRUCTURE_LIMITS = { + structuralTokens: 32 * 1024, + nestingDepth: 16 +} as const // Why: keep search cheaper than opening a file; the editor read path has a larger cap (Monaco large-file handling). const SEARCH_MAX_FILE_SIZE = 5 * 1024 * 1024 @@ -245,6 +250,7 @@ export function ingestRgJsonLine( } } try { + assertJsonTextStructureWithinLimits(line, SEARCH_JSON_STRUCTURE_LIMITS) msg = JSON.parse(line) } catch { return 'continue' diff --git a/src/shared/types.ts b/src/shared/types.ts index 7a8253a0e..96612d909 100644 --- a/src/shared/types.ts +++ b/src/shared/types.ts @@ -1313,6 +1313,7 @@ export type GitHubPRRefreshSkippedReason = | 'disconnected' | 'remote' | 'rate-limit' + | 'capacity' type GitHubPRRefreshEventBase = { sequence: number @@ -3045,6 +3046,7 @@ export type NotificationDispatchResult = { | 'not-supported' | 'not-displayed' | 'blocked-by-system' + | 'invalid-request' } export type NotificationDismissResult = { diff --git a/src/shared/utf8-byte-limits.ts b/src/shared/utf8-byte-limits.ts index 39c41e3f6..c49be3fff 100644 --- a/src/shared/utf8-byte-limits.ts +++ b/src/shared/utf8-byte-limits.ts @@ -52,6 +52,24 @@ export function clampUtf8TextTail(text: string, maxBytes: number): Utf8TextTail return { text: text.slice(start), bytes } } +export function clampUtf8TextPrefix(text: string, maxBytes: number): string { + if (!text || maxBytes <= 0) { + return '' + } + let bytes = 0 + let end = 0 + while (end < text.length) { + const codePoint = text.codePointAt(end) ?? 0 + const codePointBytes = getUtf8ByteLengthForCodePoint(codePoint) + if (bytes + codePointBytes > maxBytes) { + break + } + bytes += codePointBytes + end += codePoint > 0xffff ? 2 : 1 + } + return end === text.length ? text : text.slice(0, end) +} + export function getUtf8ByteLengthForCodePoint(codePoint: number): number { if (codePoint <= 0x7f) { return 1 diff --git a/src/shared/workspace-space-entry-traversal.test.ts b/src/shared/workspace-space-entry-traversal.test.ts new file mode 100644 index 000000000..a74ba33f0 --- /dev/null +++ b/src/shared/workspace-space-entry-traversal.test.ts @@ -0,0 +1,176 @@ +import { describe, expect, it } from 'vitest' +import { scanWorkspaceSpaceEntryTree } from './workspace-space-entry-traversal' +import { WorkspaceSpaceScanCapacityError } from './workspace-space-scan-budget' + +type Entry = { name: string } + +function makeTraversal( + directories: ReadonlyMap, + classifyEntry: (path: string) => Promise<{ + kind: 'directory' | 'file' | 'symlink' + sizeBytes: number + }>, + limits?: { maxEntries?: number; maxRetainedBytes?: number } +) { + return scanWorkspaceSpaceEntryTree({ + rootPath: '/root', + rootName: 'root', + concurrency: 5, + entryName: (entry: Entry) => entry.name, + joinPath: (parent, child) => `${parent}/${child}`, + classifyEntry: (path) => classifyEntry(path), + readDirectory: async (path) => { + const entries = directories.get(path) + if (!entries) { + throw new Error(`unreadable ${path}`) + } + return entries + }, + checkCancelled: () => undefined, + createCancellationError: () => new Error('cancelled'), + isCancellationError: (error) => error instanceof Error && error.message === 'cancelled', + limits + }) +} + +describe('scanWorkspaceSpaceEntryTree', () => { + it('uses a fixed worker pool and preserves source order', async () => { + const entries = Array.from({ length: 200 }, (_, index) => ({ name: `file-${index}` })) + let release!: () => void + const gate = new Promise((resolve) => { + release = resolve + }) + let active = 0 + let peak = 0 + let started = 0 + let saturated!: () => void + const saturation = new Promise((resolve) => { + saturated = resolve + }) + + const scan = makeTraversal(new Map([['/root', entries]]), async (path) => { + if (path === '/root') { + return { kind: 'directory', sizeBytes: 1 } + } + active += 1 + started += 1 + peak = Math.max(peak, active) + if (started === 5) { + saturated() + } + await gate + active -= 1 + return { kind: 'file', sizeBytes: 1 } + }) + + await saturation + expect(started).toBe(5) + expect(peak).toBe(5) + release() + + const result = await scan + expect(result.children?.map((child) => child.name)).toEqual(entries.map((entry) => entry.name)) + expect(result.sizeBytes).toBe(201) + }) + + it('preserves aggregate sizes and partial-failure accounting', async () => { + const directories = new Map([ + ['/root', [{ name: 'directory' }, { name: 'missing' }, { name: 'link' }, { name: 'file' }]], + ['/root/directory', [{ name: 'nested' }, { name: 'unreadable' }]], + ['/root/directory/unreadable', []] + ]) + directories.delete('/root/directory/unreadable') + + const result = await makeTraversal(directories, async (path) => { + if (path === '/root') { + return { kind: 'directory', sizeBytes: 10 } + } + if (path === '/root/directory') { + return { kind: 'directory', sizeBytes: 5 } + } + if (path === '/root/directory/nested') { + return { kind: 'file', sizeBytes: 100 } + } + if (path === '/root/directory/unreadable') { + return { kind: 'directory', sizeBytes: 7 } + } + if (path === '/root/missing') { + throw new Error('missing') + } + if (path === '/root/link') { + return { kind: 'symlink', sizeBytes: 2 } + } + return { kind: 'file', sizeBytes: 20 } + }) + + expect(result).toMatchObject({ sizeBytes: 144, skippedEntryCount: 2 }) + expect(result.children?.map((child) => child.name)).toEqual(['directory', 'link', 'file']) + expect(result.children?.[0]).toMatchObject({ + sizeBytes: 112, + skippedEntryCount: 1 + }) + }) + + it('accepts the exact entry cap without changing order or totals', async () => { + const entries = [{ name: 'first' }, { name: 'second' }] + const result = await makeTraversal( + new Map([['/root', entries]]), + async (path) => ({ kind: path === '/root' ? 'directory' : 'file', sizeBytes: 1 }), + { maxEntries: entries.length } + ) + + expect(result.children?.map((child) => child.name)).toEqual(['first', 'second']) + expect(result.sizeBytes).toBe(3) + }) + + it('fails closed instead of retaining entries beyond the scan cap', async () => { + const entries = [{ name: 'first' }, { name: 'second' }, { name: 'overflow' }] + const scan = makeTraversal( + new Map([['/root', entries]]), + async (path) => ({ kind: path === '/root' ? 'directory' : 'file', sizeBytes: 1 }), + { maxEntries: entries.length - 1 } + ) + + await expect(scan).rejects.toBeInstanceOf(WorkspaceSpaceScanCapacityError) + }) + + it('aggregates a deep chain exactly at the entry cap without recursive unwinding', async () => { + const depth = 256 + const directories = new Map() + let path = '/root' + for (let index = 0; index < depth; index += 1) { + const name = `directory-${index}` + directories.set(path, [{ name }]) + path = `${path}/${name}` + } + directories.set(path, []) + + const result = await makeTraversal( + directories, + async () => ({ kind: 'directory', sizeBytes: 1 }), + { maxEntries: depth } + ) + + expect(result.sizeBytes).toBe(depth + 1) + expect(result.children).toEqual([ + expect.objectContaining({ name: 'directory-0', sizeBytes: depth }) + ]) + }) + + it('fails closed when a deep chain crosses the cumulative entry cap', async () => { + const directories = new Map() + let path = '/root' + for (let index = 0; index < 5; index += 1) { + const name = `directory-${index}` + directories.set(path, [{ name }]) + path = `${path}/${name}` + } + directories.set(path, []) + + const scan = makeTraversal(directories, async () => ({ kind: 'directory', sizeBytes: 1 }), { + maxEntries: 4 + }) + + await expect(scan).rejects.toBeInstanceOf(WorkspaceSpaceScanCapacityError) + }) +}) diff --git a/src/shared/workspace-space-entry-traversal.ts b/src/shared/workspace-space-entry-traversal.ts new file mode 100644 index 000000000..037df0562 --- /dev/null +++ b/src/shared/workspace-space-entry-traversal.ts @@ -0,0 +1,318 @@ +import type { WorkspaceSpaceItemKind } from './workspace-space-types' +import { + collectWorkspaceSpaceDirectoryEntries, + createWorkspaceSpaceScanBudget, + WorkspaceSpaceScanCapacityError, + type WorkspaceSpaceScanBudget, + type WorkspaceSpaceScanLimits +} from './workspace-space-scan-budget' + +type ScannableWorkspaceSpaceItemKind = Exclude + +export type WorkspaceSpaceEntryScan = { + name: string + path: string + kind: ScannableWorkspaceSpaceItemKind + sizeBytes: number + skippedEntryCount: number + children?: WorkspaceSpaceEntryScan[] +} + +type WorkspaceSpaceEntryIdentity = { + kind: ScannableWorkspaceSpaceItemKind + sizeBytes: number +} + +type WorkspaceSpaceEntryTraversalOptions = { + rootPath: string + rootName: string + concurrency: number + signal?: AbortSignal + entryName: (entry: TEntry) => string + joinPath: (parent: string, child: string) => string + classifyEntry: (path: string, sourceEntry: TEntry | null) => Promise + readDirectory: (path: string) => Promise | Iterable> + checkCancelled: () => void + createCancellationError: () => Error + isCancellationError: (error: unknown) => boolean + limits?: Partial +} + +type ParentSlot = { + frame: DirectoryFrame + index: number +} + +type DirectoryFrame = { + result: WorkspaceSpaceEntryScan + entries: readonly TEntry[] + nextIndex: number + remainingChildren: number + childResults?: (WorkspaceSpaceEntryScan | null | undefined)[] + parentSlot?: ParentSlot +} + +type EntryJob = { + frame: DirectoryFrame + index: number + entry: TEntry + name: string + path: string +} + +function createEntryScan( + path: string, + name: string, + identity: WorkspaceSpaceEntryIdentity +): WorkspaceSpaceEntryScan { + return { + name, + path, + kind: identity.kind, + sizeBytes: identity.sizeBytes, + skippedEntryCount: 0 + } +} + +async function readDirectoryOrNull( + path: string, + options: WorkspaceSpaceEntryTraversalOptions, + budget: WorkspaceSpaceScanBudget +): Promise { + try { + const directory = await options.readDirectory(path) + const entries = await collectWorkspaceSpaceDirectoryEntries( + directory, + path, + options.entryName, + budget, + options.checkCancelled + ) + options.checkCancelled() + return entries + } catch (error) { + if (options.isCancellationError(error) || error instanceof WorkspaceSpaceScanCapacityError) { + throw error + } + return null + } +} + +/** + * Scans one directory tree with a fixed worker pool. Directory frames retain + * the source arrays returned by readdir, but never allocate one promise or + * queued closure per entry; only the configured workers own live entry jobs. + */ +export async function scanWorkspaceSpaceEntryTree( + options: WorkspaceSpaceEntryTraversalOptions +): Promise { + const budget = createWorkspaceSpaceScanBudget(options.limits) + options.checkCancelled() + const rootIdentity = await options.classifyEntry(options.rootPath, null) + options.checkCancelled() + const root = createEntryScan(options.rootPath, options.rootName, rootIdentity) + if (root.kind !== 'directory') { + return root + } + + const rootEntries = await readDirectoryOrNull(options.rootPath, options, budget) + if (rootEntries === null) { + root.skippedEntryCount = 1 + return root + } + if (rootEntries.length === 0) { + root.children = [] + return root + } + + const rootFrame: DirectoryFrame = { + result: root, + entries: rootEntries, + nextIndex: 0, + remainingChildren: rootEntries.length, + childResults: Array.from({ length: rootEntries.length }, () => undefined) + } + const availableFrames: DirectoryFrame[] = [rootFrame] + const waiters = new Set<() => void>() + let outstandingEntries = rootEntries.length + let fatalError: unknown = null + + const wakeWorkers = (): void => { + for (const wake of waiters) { + wake() + } + } + const fail = (error: unknown): void => { + fatalError ??= error + wakeWorkers() + } + const onAbort = (): void => fail(options.createCancellationError()) + options.signal?.addEventListener('abort', onAbort, { once: true }) + if (options.signal?.aborted) { + onAbort() + } + + const takeAvailableJob = (): EntryJob | null => { + while (availableFrames.length > 0) { + const frame = availableFrames.at(-1)! + if (frame.nextIndex >= frame.entries.length) { + availableFrames.pop() + continue + } + const index = frame.nextIndex + frame.nextIndex += 1 + if (frame.nextIndex >= frame.entries.length) { + availableFrames.pop() + } + const entry = frame.entries[index] + const name = options.entryName(entry) + return { + frame, + index, + entry, + name, + path: options.joinPath(frame.result.path, name) + } + } + return null + } + + const waitForJob = async (): Promise | null> => { + while (fatalError === null) { + options.checkCancelled() + const job = takeAvailableJob() + if (job) { + return job + } + if (outstandingEntries === 0) { + return null + } + await new Promise((resolve) => { + const wake = (): void => { + waiters.delete(wake) + resolve() + } + waiters.add(wake) + }) + } + return null + } + + const completeChild = ( + initialFrame: DirectoryFrame, + initialIndex: number, + initialResult: WorkspaceSpaceEntryScan | null + ): void => { + let frame = initialFrame + let index = initialIndex + let result = initialResult + while (true) { + if (frame.childResults) { + frame.childResults[index] = result + } + if (result) { + frame.result.sizeBytes += result.sizeBytes + frame.result.skippedEntryCount += result.skippedEntryCount + } else { + frame.result.skippedEntryCount += 1 + } + frame.remainingChildren -= 1 + outstandingEntries -= 1 + if (frame.remainingChildren > 0) { + break + } + if (frame.childResults) { + frame.result.children = frame.childResults.filter( + (child): child is WorkspaceSpaceEntryScan => child != null + ) + } + if (!frame.parentSlot) { + break + } + result = frame.result + index = frame.parentSlot.index + frame = frame.parentSlot.frame + } + wakeWorkers() + } + + const expandDirectory = ( + job: EntryJob, + result: WorkspaceSpaceEntryScan, + entries: readonly TEntry[] + ): void => { + if (entries.length === 0) { + completeChild(job.frame, job.index, result) + return + } + outstandingEntries += entries.length + availableFrames.push({ + result, + entries, + nextIndex: 0, + remainingChildren: entries.length, + parentSlot: { frame: job.frame, index: job.index } + }) + wakeWorkers() + } + + const processJob = async (job: EntryJob): Promise => { + let identity: WorkspaceSpaceEntryIdentity + try { + identity = await options.classifyEntry(job.path, job.entry) + options.checkCancelled() + } catch (error) { + if (options.isCancellationError(error)) { + throw error + } + completeChild(job.frame, job.index, null) + return + } + + const result = createEntryScan(job.path, job.name, identity) + if (result.kind !== 'directory') { + completeChild(job.frame, job.index, result) + return + } + const entries = await readDirectoryOrNull(job.path, options, budget) + if (entries === null) { + result.skippedEntryCount = 1 + completeChild(job.frame, job.index, result) + return + } + expandDirectory(job, result, entries) + } + + const worker = async (): Promise => { + while (fatalError === null) { + let job: EntryJob | null + try { + job = await waitForJob() + } catch (error) { + fail(error) + return + } + if (!job) { + return + } + try { + await processJob(job) + } catch (error) { + fail(error) + return + } + } + } + + const workerCount = Math.max(1, Math.floor(options.concurrency)) + try { + await Promise.all(Array.from({ length: workerCount }, worker)) + } finally { + options.signal?.removeEventListener('abort', onAbort) + wakeWorkers() + } + if (fatalError !== null) { + throw fatalError + } + return root +} diff --git a/src/shared/workspace-space-scan-budget.test.ts b/src/shared/workspace-space-scan-budget.test.ts new file mode 100644 index 000000000..69b34b2a8 --- /dev/null +++ b/src/shared/workspace-space-scan-budget.test.ts @@ -0,0 +1,51 @@ +import { describe, expect, it } from 'vitest' +import { + collectWorkspaceSpaceDirectoryEntries, + createWorkspaceSpaceScanBudget, + estimateWorkspaceSpaceEntryRetainedBytes, + WorkspaceSpaceScanCapacityError +} from './workspace-space-scan-budget' + +describe('workspace space scan budget', () => { + it('preserves entries exactly at the retained-byte cap', async () => { + const entries = [{ name: 'first' }, { name: 'second' }] + const parentPath = '/workspace' + const exactBytes = entries.reduce( + (total, entry) => total + estimateWorkspaceSpaceEntryRetainedBytes(parentPath, entry.name), + 0 + ) + + await expect( + collectWorkspaceSpaceDirectoryEntries( + entries, + parentPath, + (entry) => entry.name, + createWorkspaceSpaceScanBudget({ maxRetainedBytes: exactBytes }), + () => undefined + ) + ).resolves.toEqual(entries) + }) + + it('closes an async directory iterator when the next entry exceeds the budget', async () => { + let closed = false + async function* directory() { + try { + yield { name: 'accepted' } + yield { name: 'overflow' } + } finally { + closed = true + } + } + + await expect( + collectWorkspaceSpaceDirectoryEntries( + directory(), + '/workspace', + (entry) => entry.name, + createWorkspaceSpaceScanBudget({ maxEntries: 1 }), + () => undefined + ) + ).rejects.toBeInstanceOf(WorkspaceSpaceScanCapacityError) + expect(closed).toBe(true) + }) +}) diff --git a/src/shared/workspace-space-scan-budget.ts b/src/shared/workspace-space-scan-budget.ts new file mode 100644 index 000000000..693fd0241 --- /dev/null +++ b/src/shared/workspace-space-scan-budget.ts @@ -0,0 +1,87 @@ +export const WORKSPACE_SPACE_MAX_SCANNED_ENTRIES = 100_000 +export const WORKSPACE_SPACE_MAX_RETAINED_SCAN_BYTES = 64 * 1024 * 1024 + +const WORKSPACE_SPACE_ENTRY_OVERHEAD_BYTES = 512 + +export type WorkspaceSpaceScanLimits = { + maxEntries: number + maxRetainedBytes: number +} + +export type WorkspaceSpaceScanBudget = { + entries: number + retainedBytes: number + limits: WorkspaceSpaceScanLimits +} + +export class WorkspaceSpaceScanCapacityError extends Error { + constructor() { + super( + 'Workspace is too large to scan safely (limit: 100,000 entries or 64 MiB retained scan state)' + ) + this.name = 'WorkspaceSpaceScanCapacityError' + } +} + +export function createWorkspaceSpaceScanBudget( + requested?: Partial +): WorkspaceSpaceScanBudget { + return { + entries: 0, + retainedBytes: 0, + limits: { + maxEntries: clampLimit(requested?.maxEntries, WORKSPACE_SPACE_MAX_SCANNED_ENTRIES), + maxRetainedBytes: clampLimit( + requested?.maxRetainedBytes, + WORKSPACE_SPACE_MAX_RETAINED_SCAN_BYTES + ) + } + } +} + +export function estimateWorkspaceSpaceEntryRetainedBytes( + parentPath: string, + entryName: string +): number { + return (parentPath.length + entryName.length) * 2 + WORKSPACE_SPACE_ENTRY_OVERHEAD_BYTES +} + +export function retainWorkspaceSpaceScanEntry( + budget: WorkspaceSpaceScanBudget, + parentPath: string, + entryName: string +): void { + const retainedBytes = + budget.retainedBytes + estimateWorkspaceSpaceEntryRetainedBytes(parentPath, entryName) + if ( + budget.entries >= budget.limits.maxEntries || + retainedBytes > budget.limits.maxRetainedBytes + ) { + throw new WorkspaceSpaceScanCapacityError() + } + budget.entries += 1 + budget.retainedBytes = retainedBytes +} + +export async function collectWorkspaceSpaceDirectoryEntries( + directory: AsyncIterable | Iterable, + parentPath: string, + entryName: (entry: TEntry) => string, + budget: WorkspaceSpaceScanBudget, + checkCancelled: () => void +): Promise { + const entries: TEntry[] = [] + for await (const entry of directory) { + checkCancelled() + retainWorkspaceSpaceScanEntry(budget, parentPath, entryName(entry)) + entries.push(entry) + } + return entries +} + +function clampLimit(value: number | undefined, maximum: number): number { + if (typeof value !== 'number' || !Number.isSafeInteger(value) || value <= 0) { + return maximum + } + return Math.min(value, maximum) +} diff --git a/src/shared/wsl-hook-relay-contract.ts b/src/shared/wsl-hook-relay-contract.ts index ea1d763d6..ed6e147de 100644 --- a/src/shared/wsl-hook-relay-contract.ts +++ b/src/shared/wsl-hook-relay-contract.ts @@ -44,10 +44,25 @@ export const WSL_HOOK_FS_METHODS = { mkdir: 'wslfs.mkdir' } as const +/** Hard guest-side ceilings. Host requests may lower them but cannot raise them. */ +export const WSL_HOOK_FS_MAX_READ_BYTES = 64 * 1024 * 1024 +export const WSL_HOOK_FS_MAX_DIRECTORY_ENTRIES = 10_000 +export const WSL_HOOK_FS_MAX_DIRECTORY_RETAINED_BYTES = 2 * 1024 * 1024 + +export type WslHookFsDirectoryLimits = { + maxEntries: number + maxRetainedBytes: number +} + /** Result envelope for every fs-bridge method. Errors travel as data (not * JSON-RPC faults) so the host adapter can map POSIX errno onto the ssh2 * status codes the shared installer error-classifiers already understand. */ -export type WslFsFailure = { ok: false; errno: string; message: string } +export type WslFsFailure = { + ok: false + errno: string + message: string + fileCapacity?: { observedBytes: number; maxBytes: number } +} export type WslFsResult = ({ ok: true } & T) | WslFsFailure /** Where the guest relay publishes its endpoint file. Keyed by the stable