Revert "fix(memory): bound OOM-prone accumulators (#10179)" (#10255)

Co-authored-by: Orca <help@stably.ai>
This commit is contained in:
Neil
2026-07-23 18:35:31 -07:00
committed by GitHub
co-authored by Orca
parent 6eb70d8370
commit aab112933e
1577 changed files with 15167 additions and 91655 deletions
-14
View File
@@ -7,7 +7,6 @@ import {
getAgentLabel,
isCursorAgentTitle,
MAX_OSC_TITLE_CHARS,
MAX_OSC_TITLES_PER_CHUNK,
normalizeTerminalTitle
} from './agent-detection'
import {
@@ -66,19 +65,6 @@ 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', () => {
+1 -2
View File
@@ -32,7 +32,6 @@ export { AGENT_NAMES, titleHasAgentName } from './agent-name-token-match'
export {
extractAllOscTitles,
extractLastOscTitle,
MAX_OSC_TITLE_CHARS,
MAX_OSC_TITLES_PER_CHUNK
MAX_OSC_TITLE_CHARS
} from './osc-title-extraction'
export { isShellProcess } from './shell-process-detection'
@@ -1,58 +0,0 @@
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'))
})
})
@@ -1,38 +0,0 @@
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<typeof opendirSync> | 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
}
}
}
@@ -1,57 +0,0 @@
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<string, unknown>
): ReturnType<typeof normalizeHookPayload> {
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)
})
})
+44 -45
View File
@@ -9,6 +9,7 @@ import {
closeSync,
mkdirSync,
openSync,
readdirSync,
readSync,
renameSync,
statSync,
@@ -63,21 +64,9 @@ 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
@@ -314,7 +303,7 @@ export function parseFormEncodedBody(body: string): Record<string, string> {
export function readRequestBody(req: IncomingMessage): Promise<unknown> {
return new Promise((resolve, reject) => {
let retained = Buffer.alloc(0)
const chunks: Buffer[] = []
let byteLength = 0
let settled = false
const cleanup = (): void => {
@@ -343,30 +332,21 @@ export function readRequestBody(req: IncomingMessage): Promise<unknown> {
}
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.
const nextByteLength = byteLength + chunk.length
if (nextByteLength > HOOK_REQUEST_MAX_BYTES) {
if (byteLength + chunk.length > HOOK_REQUEST_MAX_BYTES) {
settleReject(new Error('payload too large'))
req.destroy()
return
}
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
byteLength += chunk.length
chunks.push(chunk)
}
const onEnd = (): void => {
try {
const body = retained.toString('utf8', 0, byteLength)
// 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 contentType = req.headers['content-type'] ?? ''
if (typeof contentType === 'string' && contentType.includes('application/json')) {
settleResolve(body ? parseAgentHookJson(body) : {})
settleResolve(body ? JSON.parse(body) : {})
return
}
if (
@@ -377,7 +357,7 @@ export function readRequestBody(req: IncomingMessage): Promise<unknown> {
return
}
// Why: managed scripts POST JSON, updated POSIX scripts form-encoded; default to JSON for unknown content types.
settleResolve(body ? parseAgentHookJson(body) : {})
settleResolve(body ? JSON.parse(body) : {})
} catch (error) {
settleReject(error)
}
@@ -799,7 +779,7 @@ function parseJsonObjectString(value: unknown): Record<string, unknown> | undefi
return undefined
}
try {
const parsed = parseAgentHookJson(value)
const parsed = JSON.parse(value) as unknown
return typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed)
? (parsed as Record<string, unknown>)
: undefined
@@ -844,7 +824,7 @@ const GROK_HOME_ENVELOPE_MAX_LENGTH = 4096
function extractAssistantTextFromLine(line: string): string | undefined {
let entry: unknown
try {
entry = parseAgentHookJson(line)
entry = JSON.parse(line)
} catch {
return undefined
}
@@ -910,7 +890,7 @@ function extractAntigravityUserRequest(content: string): string | undefined {
function extractUserPromptTextFromLine(line: string): string | undefined {
let entry: unknown
try {
entry = parseAgentHookJson(line)
entry = JSON.parse(line)
} catch {
return undefined
}
@@ -945,7 +925,7 @@ function readLastUserPromptFromTranscript(transcriptPath: unknown): string | und
function extractCommandCodeUserPromptFromLine(line: string): string | undefined {
let entry: unknown
try {
entry = parseAgentHookJson(line)
entry = JSON.parse(line)
} catch {
return undefined
}
@@ -1041,7 +1021,7 @@ function* iterateTranscriptLinesWithByteOffsets(
function extractCommandCodeAssistantTextFromLine(line: string): string | undefined {
let entry: unknown
try {
entry = parseAgentHookJson(line)
entry = JSON.parse(line)
} catch {
return undefined
}
@@ -1088,7 +1068,7 @@ function parseHookBodyPayloadRecord(body: unknown): Record<string, unknown> | nu
typeof rawPayload === 'string'
? (() => {
try {
return parseAgentHookJson(rawPayload)
return JSON.parse(rawPayload) as unknown
} catch {
return null
}
@@ -2364,21 +2344,22 @@ function normalizeClaudeSubagentLifecycleEvent(
paneKey: string,
hookPayload: Record<string, unknown>
): 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 = lifecycleId
const teammateName = readString(hookPayload, 'teammate_name')
if (!teammateName) {
return null
}
// 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 = lifecycleId
const agentId = readString(hookPayload, 'agent_id')
if (!agentId) {
return null
}
if (eventName === 'SubagentStart') {
upsertWorkingClaudeSubagent(
roster,
@@ -3800,7 +3781,7 @@ export function normalizeHookPayload(
typeof rawPayload === 'string'
? (() => {
try {
return parseAgentHookJson(rawPayload)
return JSON.parse(rawPayload)
} catch {
return null
}
@@ -4084,8 +4065,26 @@ export function writeEndpointFile(
// best-effort
}
}
// Why: crash-orphan cleanup must not materialize a tampered, enormous directory.
sweepStaleAgentHookEndpointTemps(endpointDir)
// 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
}
const separator = process.platform === 'win32' ? '\r\n' : '\n'
writeFileSync(tmpPath, lines.join(separator), { mode: 0o600 })
tmpWritten = true
@@ -1,32 +0,0 @@
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<typeof vi.fn>
}
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 })
})
})
@@ -1,66 +0,0 @@
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)
})
})
-69
View File
@@ -1,69 +0,0 @@
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
)
}
-12
View File
@@ -3,7 +3,6 @@ import {
agentSubagentsEqual,
parseAgentStatusPayload,
normalizeAgentStatusPayload,
AGENT_STATUS_JSON_STRUCTURE_LIMITS,
AGENT_STATUS_MAX_FIELD_LENGTH,
AGENT_STATUS_MAX_SUBAGENTS,
AGENT_STATUS_TOOL_NAME_MAX_LENGTH,
@@ -56,17 +55,6 @@ 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()
-6
View File
@@ -9,7 +9,6 @@ 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'
@@ -241,10 +240,6 @@ 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 {
@@ -381,7 +376,6 @@ 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
-2
View File
@@ -253,7 +253,6 @@ export type ExternalAutomationJob = {
lastError: string | null
workdir: string | null
runCount: number
runCountSaturated?: true
runs: ExternalAutomationRun[]
}
@@ -278,7 +277,6 @@ export type ExternalAutomationRunsPage = {
page: number
pageSize: number
total: number
totalSaturated?: true
runs: ExternalAutomationRun[]
}
-10
View File
@@ -1,10 +0,0 @@
import { stringifyJsonWithinByteLimit } from './node-bounded-json-stringify'
import { writeSecureFile } from './secure-file'
export function writeSecureJsonFileWithinLimit(
targetPath: string,
value: unknown,
maxBytes: number
): void {
writeSecureFile(targetPath, stringifyJsonWithinByteLimit(value, maxBytes).serialized)
}
+1 -36
View File
@@ -1,7 +1,5 @@
import { describe, expect, it, vi } from 'vitest'
import { describe, expect, it } from 'vitest'
import {
BROWSER_SCREENCAST_MAX_METADATA_BYTES,
BROWSER_SCREENCAST_METADATA_JSON_STRUCTURE_LIMITS,
BrowserScreencastOpcode,
decodeBrowserScreencastFrame,
encodeBrowserScreencastFrame
@@ -76,39 +74,6 @@ 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,
+1 -16
View File
@@ -1,13 +1,6 @@
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',
@@ -65,13 +58,8 @@ function encodeJson(value: unknown): Uint8Array {
}
function decodeJson(bytes: Uint8Array): unknown {
if (bytes.byteLength > BROWSER_SCREENCAST_MAX_METADATA_BYTES) {
return null
}
try {
const content = new TextDecoder().decode(bytes)
assertJsonTextStructureWithinLimits(content, BROWSER_SCREENCAST_METADATA_JSON_STRUCTURE_LIMITS)
return JSON.parse(content) as unknown
return JSON.parse(new TextDecoder().decode(bytes)) as unknown
} catch {
return null
}
@@ -133,9 +121,6 @@ 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
}
@@ -1,7 +1,6 @@
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,
@@ -221,17 +220,6 @@ 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',
-7
View File
@@ -1,6 +1,5 @@
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. */
@@ -58,11 +57,6 @@ 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' },
@@ -141,7 +135,6 @@ 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
-19
View File
@@ -1,19 +0,0 @@
export const MAX_CUSTOM_PET_FILE_BYTES = 64 * 1024 * 1024
// Why: sprite processing holds decoded image, canvas, ImageData, PNG, and
// optional bitmap copies at once, so encoded bytes alone are not a safe bound.
export const MAX_CUSTOM_PET_SHEET_PIXELS = 4 * 1024 * 1024
export const MAX_CUSTOM_PET_SHEET_DIMENSION = 8_192
export const MAX_CUSTOM_PET_DETECTED_FRAMES = 128
export function isCustomPetSheetSizeSafe(width: number, height: number): boolean {
return (
Number.isSafeInteger(width) &&
Number.isSafeInteger(height) &&
width > 0 &&
height > 0 &&
width <= MAX_CUSTOM_PET_SHEET_DIMENSION &&
height <= MAX_CUSTOM_PET_SHEET_DIMENSION &&
width * height <= MAX_CUSTOM_PET_SHEET_PIXELS
)
}
@@ -23,33 +23,6 @@ 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 () => {
+4 -19
View File
@@ -143,24 +143,9 @@ function buildRecipeEnv(
}
function appendBounded(current: string, chunk: string, maxBytes: number): string {
if (maxBytes <= 0) {
return ''
const next = current + chunk
if (Buffer.byteLength(next, 'utf8') <= maxBytes) {
return next
}
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')
return next.slice(-maxBytes)
}
+1 -18
View File
@@ -1,7 +1,6 @@
import { describe, expect, it, vi } from 'vitest'
import { describe, expect, it } from 'vitest'
import { encodePairingOffer, PAIRING_OFFER_VERSION } from './pairing'
import {
EPHEMERAL_VM_RECIPE_JSON_STRUCTURE_LIMITS,
getEphemeralVmRecipeResultWarnings,
parseEphemeralVmRecipeResult,
redactEphemeralVmRecipeDiagnosticText,
@@ -155,22 +154,6 @@ 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(
-7
View File
@@ -5,7 +5,6 @@ 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).
@@ -36,11 +35,6 @@ 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),
@@ -157,7 +151,6 @@ 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.' }
+1 -25
View File
@@ -1,4 +1,4 @@
import { mkdtempSync, rmSync, truncateSync, writeFileSync } from 'node:fs'
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
@@ -7,7 +7,6 @@ import {
EphemeralVmRuntimeStoreError,
getEphemeralVmRuntimeStorePath,
listEphemeralVmRuntimes,
MAX_EPHEMERAL_VM_RUNTIME_STORE_FILE_BYTES,
removeEphemeralVmRuntime,
updateEphemeralVmRuntimeStatus,
upsertEphemeralVmRuntime
@@ -174,27 +173,4 @@ 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([])
})
})
+4 -29
View File
@@ -1,9 +1,6 @@
import { existsSync } from 'node:fs'
import { existsSync, readFileSync } from 'node:fs'
import { join } from 'node:path'
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 { hardenExistingSecureFile, writeSecureJsonFile } from './secure-file'
import {
EphemeralVmRuntimeRecordSchema,
EphemeralVmRuntimeStoreSchema,
@@ -14,7 +11,6 @@ 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'
@@ -140,14 +136,7 @@ function readEphemeralVmRuntimeStore(userDataPath: string): EphemeralVmRuntimeSt
}
try {
hardenExistingSecureFile(path)
const parsed = EphemeralVmRuntimeStoreSchema.parse(
JSON.parse(
readNodeFileSyncWithinLimit(
path,
MAX_EPHEMERAL_VM_RUNTIME_STORE_FILE_BYTES
).buffer.toString('utf8')
)
)
const parsed = EphemeralVmRuntimeStoreSchema.parse(JSON.parse(readFileSync(path, 'utf8')))
return {
version: 1,
runtimes: parsed.runtimes
@@ -164,21 +153,7 @@ function readEphemeralVmRuntimeStore(userDataPath: string): EphemeralVmRuntimeSt
function writeEphemeralVmRuntimeStore(userDataPath: string, store: EphemeralVmRuntimeStore): void {
const path = getEphemeralVmRuntimeStorePath(userDataPath)
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
}
writeSecureJsonFile(path, EphemeralVmRuntimeStoreSchema.parse(store))
}
function compareRuntimeRecords(a: EphemeralVmRuntimeRecord, b: EphemeralVmRuntimeRecord): number {
@@ -1,71 +0,0 @@
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<string> {
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')
})
})
@@ -1,58 +0,0 @@
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<unknown[]> {
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<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value)
}
-116
View File
@@ -1,116 +0,0 @@
import {
assertJsonTextStructureWithinLimits,
type JsonTextStructureLimits
} from './json-text-structure-limit'
const INITIAL_RESPONSE_CAPACITY_BYTES = 64 * 1024
export const API_RESPONSE_MAX_BYTES = 16 * 1024 * 1024
export const API_RESPONSE_JSON_LIMITS: JsonTextStructureLimits = {
structuralTokens: 1_000_000,
nestingDepth: 128
}
export class FetchResponseBodyTooLargeError extends Error {
constructor(
readonly observedBytes: number,
readonly maxBytes: number
) {
super(`Response body exceeds ${maxBytes} byte limit`)
this.name = 'FetchResponseBodyTooLargeError'
}
}
function parseContentLength(response: Response): number | null {
const raw = response.headers.get('content-length')
if (!raw || !/^\d+$/.test(raw)) {
return null
}
const parsed = Number(raw)
return Number.isSafeInteger(parsed) ? parsed : null
}
function isHighLevelOnlyResponse(response: Response): boolean {
const partial = response as Partial<Response>
// Injected request adapters may expose only the high-level method they implement.
return partial.headers === undefined && partial.body === undefined
}
async function cancelReader(reader: ReadableStreamDefaultReader<Uint8Array>): Promise<void> {
try {
await reader.cancel()
} catch {
// An already-errored or closed response needs no further draining.
}
}
export async function readFetchResponseBytesWithinLimit(
response: Response,
maxBytes = API_RESPONSE_MAX_BYTES
): Promise<Uint8Array> {
if (!Number.isSafeInteger(maxBytes) || maxBytes < 0) {
throw new RangeError('Response body limit must be a non-negative safe integer')
}
const contentLength = parseContentLength(response)
if (contentLength !== null && contentLength > maxBytes) {
await response.body?.cancel().catch(() => undefined)
throw new FetchResponseBodyTooLargeError(contentLength, maxBytes)
}
if (!response.body) {
return new Uint8Array()
}
const reader = response.body.getReader()
let output = new Uint8Array(Math.min(maxBytes, INITIAL_RESPONSE_CAPACITY_BYTES))
let byteLength = 0
try {
while (true) {
const { done, value } = await reader.read()
if (done) {
return output.subarray(0, byteLength)
}
const nextLength = byteLength + value.byteLength
if (!Number.isSafeInteger(nextLength) || nextLength > maxBytes) {
await cancelReader(reader)
throw new FetchResponseBodyTooLargeError(nextLength, maxBytes)
}
if (nextLength > output.byteLength) {
const nextCapacity = Math.min(
maxBytes,
Math.max(INITIAL_RESPONSE_CAPACITY_BYTES, output.byteLength * 2, nextLength)
)
const expanded = new Uint8Array(nextCapacity)
expanded.set(output.subarray(0, byteLength))
output = expanded
}
output.set(value, byteLength)
byteLength = nextLength
}
} finally {
reader.releaseLock()
}
}
export async function readFetchResponseTextWithinLimit(
response: Response,
maxBytes = API_RESPONSE_MAX_BYTES
): Promise<string> {
if (isHighLevelOnlyResponse(response)) {
return response.text()
}
return new TextDecoder().decode(await readFetchResponseBytesWithinLimit(response, maxBytes))
}
export async function readFetchResponseJsonWithinLimit<T>(
response: Response,
maxBytes = API_RESPONSE_MAX_BYTES,
structureLimits: JsonTextStructureLimits = API_RESPONSE_JSON_LIMITS
): Promise<T> {
if (isHighLevelOnlyResponse(response)) {
return response.json() as Promise<T>
}
const content = await readFetchResponseTextWithinLimit(response, maxBytes)
assertJsonTextStructureWithinLimits(content, structureLimits)
return JSON.parse(content) as T
}
@@ -1,59 +0,0 @@
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
})
})
})
@@ -1,75 +0,0 @@
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>
): FilesystemDirectoryListingLimits {
return {
maxEntries: clampLimit(requested?.maxEntries, FILESYSTEM_DIRECTORY_MAX_ENTRIES),
maxRetainedBytes: clampLimit(
requested?.maxRetainedBytes,
FILESYSTEM_DIRECTORY_MAX_RETAINED_BYTES
)
}
}
export function createFilesystemDirectoryLimitState(
requested?: Partial<FilesystemDirectoryListingLimits>
): 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<FilesystemDirectoryListingLimits>
): 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)
}
+1 -8
View File
@@ -38,12 +38,5 @@ export function splitGitCheckIgnorePathsByStdinBytes(
}
export function parseGitCheckIgnorePaths(stdout: string): string[] {
const paths: string[] = []
for (const path of iterateNulDelimitedFields(stdout)) {
if (path) {
paths.push(path)
}
}
return paths
return stdout.split('\0').filter((path) => path.length > 0)
}
import { iterateNulDelimitedFields } from './nul-delimited-fields'
+1 -2
View File
@@ -27,7 +27,7 @@ function canonicalizeGitConfigLookupKey(key: string): string {
function parseGitConfigListSnapshot(stdout: string): GitConfigSnapshot {
const snapshot: GitConfigSnapshot = new Map()
for (const record of iterateNulDelimitedFields(stdout)) {
for (const record of stdout.split('\0')) {
if (!record.trim()) {
continue
}
@@ -101,4 +101,3 @@ export function createGitConfigSnapshotRunner(runGit: GitCommandRunner): GitComm
return { stdout: values.at(-1) ?? '' }
}
}
import { iterateNulDelimitedFields } from './nul-delimited-fields'
+6 -9
View File
@@ -1,8 +1,5 @@
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 (
@@ -114,16 +111,16 @@ export async function removeSafeUntrackedDiscardTargets(
removePaths: (filePaths: readonly string[]) => Promise<void>,
beforeRemove?: () => Promise<void>
): Promise<void> {
await forEachWithConcurrency(filePaths, DISCARD_PATH_VALIDATION_CONCURRENCY, async (filePath) => {
await validateUntrackedDiscardTarget(worktreePath, filePath)
})
await Promise.all(
filePaths.map((filePath) => 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 forEachWithConcurrency(filePaths, DISCARD_PATH_VALIDATION_CONCURRENCY, async (filePath) => {
await validateUntrackedDiscardTarget(worktreePath, filePath)
})
await Promise.all(
filePaths.map((filePath) => validateUntrackedDiscardTarget(worktreePath, filePath))
)
await removePaths(filePaths)
}
+1 -2
View File
@@ -1,5 +1,4 @@
import type { GitHistoryItem, GitHistoryItemRef } from './git-history-types'
import { iterateNulDelimitedFields } from './nul-delimited-fields'
const GIT_HISTORY_DECORATION_SEPARATOR = '\x1f'
@@ -99,7 +98,7 @@ export function compareGitHistoryItemRefsByCategory(
export function parseGitHistoryLog(stdout: string): GitHistoryItem[] {
const items: GitHistoryItem[] = []
for (const rawRecord of iterateNulDelimitedFields(stdout)) {
for (const rawRecord of stdout.split('\0')) {
const record = rawRecord.replace(/^\n+/, '')
if (!record.trim()) {
continue
@@ -5,14 +5,7 @@ const { lstatMock, readFileMock } = vi.hoisted(() => ({
readFileMock: vi.fn()
}))
vi.mock('fs/promises', () => ({ lstat: lstatMock }))
vi.mock('./node-bounded-file-reader', () => ({
readNodeFileWithinLimit: async (path: string) => ({
buffer: await readFileMock(path),
stats: mockFileStat(0)
})
}))
vi.mock('fs/promises', () => ({ lstat: lstatMock, readFile: readFileMock }))
import {
applyLineStats,
+8 -10
View File
@@ -1,10 +1,8 @@
import { lstat } from 'node:fs/promises'
import { lstat, readFile } 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 }
@@ -80,9 +78,9 @@ export function parseNumstat(stdout: string): Map<string, GitLineStats> {
function parseNulDelimitedNumstat(stdout: string): Map<string, GitLineStats> {
const stats = new Map<string, GitLineStats>()
const records = iterateNulDelimitedFields(stdout)[Symbol.iterator]()
for (let next = records.next(); !next.done; next = records.next()) {
const record = next.value
const records = stdout.split('\0')
for (let i = 0; i < records.length; i += 1) {
const record = records[i]
if (!record) {
continue
}
@@ -91,9 +89,9 @@ function parseNulDelimitedNumstat(stdout: string): Map<string, GitLineStats> {
let path = rawPath
if (!path) {
// Git -z emits rename paths as: "added<TAB>removed<TAB>\0old\0new\0".
// The empty header path is followed by the preimage and postimage.
records.next()
path = records.next().value ?? ''
// The split record has an empty path in the header; the postimage is next.
i += 2
path = records[i] ?? ''
}
if (!path) {
continue
@@ -129,7 +127,7 @@ async function countFileAdditions(absolutePath: string): Promise<GitLineStats> {
if (!fileStat.isFile() || fileStat.size > MAX_UNTRACKED_LINE_COUNT_BYTES) {
return rememberUntrackedStats(absolutePath, fileStat, {})
}
const { buffer } = await readNodeFileWithinLimit(absolutePath, MAX_UNTRACKED_LINE_COUNT_BYTES)
const buffer = await readFile(absolutePath)
if (isBinaryBuffer(buffer)) {
return rememberUntrackedStats(absolutePath, fileStat, {})
}
-54
View File
@@ -1,54 +0,0 @@
import { describe, expect, it } from 'vitest'
import { GrowingByteBuffer } from './growing-byte-buffer'
describe('GrowingByteBuffer', () => {
it('retains 100,000 one-byte fragments in one growable allocation', () => {
const buffer = new GrowingByteBuffer()
const expected = Buffer.alloc(100_000)
for (let index = 0; index < expected.byteLength; index += 1) {
const value = index % 251
expected[index] = value
buffer.append(Uint8Array.of(value))
}
expect(buffer.byteLength).toBe(expected.byteLength)
expect(buffer.takeString('latin1')).toBe(expected.toString('latin1'))
expect(buffer.byteLength).toBe(0)
})
it('consumes delimited prefixes and retains a bounded suffix', () => {
const buffer = new GrowingByteBuffer()
for (const byte of Buffer.from('first\nsecond-tail')) {
buffer.append(Uint8Array.of(byte))
}
const newline = buffer.indexOfByte(0x0a)
expect(buffer.takePrefixString(newline)).toBe('first')
buffer.discardPrefix(1)
buffer.retainSuffix(4)
expect(buffer.toString()).toBe('tail')
})
it('appends only a bounded copy from an oversized source chunk', () => {
const buffer = new GrowingByteBuffer()
buffer.append(Buffer.from('old'))
const source = Buffer.from('discard-prefix-tail')
buffer.appendRetainedSuffix(source, 4)
source.fill(0)
expect(buffer.byteLength).toBe(4)
expect(buffer.toString()).toBe('tail')
})
it('keeps the newest bytes across bounded suffix appends', () => {
const buffer = new GrowingByteBuffer()
buffer.appendRetainedSuffix(Buffer.from('1234'), 6)
buffer.appendRetainedSuffix(Buffer.from('5678'), 6)
expect(buffer.toString()).toBe('345678')
})
})
-100
View File
@@ -1,100 +0,0 @@
export class GrowingByteBuffer {
private storage = Buffer.alloc(0)
private length = 0
get byteLength(): number {
return this.length
}
append(bytes: Buffer | Uint8Array): void {
if (bytes.byteLength === 0) {
return
}
const required = this.length + bytes.byteLength
if (required > this.storage.byteLength) {
const capacity = Math.max(required, Math.max(256, this.storage.byteLength * 2))
const next = Buffer.allocUnsafe(capacity)
this.storage.copy(next, 0, 0, this.length)
this.storage = next
}
const source = Buffer.isBuffer(bytes)
? bytes
: Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength)
source.copy(this.storage, this.length)
this.length = required
}
appendRetainedSuffix(bytes: Buffer | Uint8Array, maxBytes: number): void {
if (!Number.isSafeInteger(maxBytes) || maxBytes < 0) {
throw new RangeError('Retained suffix limit must be a non-negative safe integer')
}
if (maxBytes === 0) {
this.clear()
return
}
const source = Buffer.isBuffer(bytes)
? bytes
: Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength)
if (source.byteLength >= maxBytes) {
this.storage = Buffer.from(source.subarray(source.byteLength - maxBytes))
this.length = maxBytes
return
}
const retainedBytes = Math.min(this.length, maxBytes - source.byteLength)
if (retainedBytes < this.length) {
this.storage.copy(this.storage, 0, this.length - retainedBytes, this.length)
this.length = retainedBytes
}
this.append(source)
}
indexOfByte(value: number, byteOffset = 0): number {
return this.storage.subarray(0, this.length).indexOf(value, byteOffset)
}
takePrefixString(byteLength: number, encoding: BufferEncoding = 'utf8'): string {
if (!Number.isSafeInteger(byteLength) || byteLength < 0 || byteLength > this.length) {
throw new RangeError('Prefix length exceeds retained bytes')
}
const value = this.storage.toString(encoding, 0, byteLength)
this.discardPrefix(byteLength)
return value
}
discardPrefix(byteLength: number): void {
if (!Number.isSafeInteger(byteLength) || byteLength < 0 || byteLength > this.length) {
throw new RangeError('Prefix length exceeds retained bytes')
}
if (byteLength === 0) {
return
}
this.storage.copy(this.storage, 0, byteLength, this.length)
this.length -= byteLength
}
retainSuffix(maxBytes: number): void {
if (!Number.isSafeInteger(maxBytes) || maxBytes < 0) {
throw new RangeError('Suffix limit must be a non-negative safe integer')
}
if (this.length <= maxBytes) {
return
}
this.storage.copy(this.storage, 0, this.length - maxBytes, this.length)
this.length = maxBytes
}
toString(encoding: BufferEncoding = 'utf8'): string {
return this.storage.toString(encoding, 0, this.length)
}
takeString(encoding: BufferEncoding = 'utf8'): string {
const value = this.toString(encoding)
this.clear()
return value
}
clear(): void {
this.storage = Buffer.alloc(0)
this.length = 0
}
}
-165
View File
@@ -1,165 +0,0 @@
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<Record<string, unknown>> {
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<void>((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
}))
)
})
})
-254
View File
@@ -1,254 +0,0 @@
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<T>(
refs: readonly T[],
hydrate: (ref: T) => Promise<unknown>,
limits: HermesRunPageLimits = {}
): Promise<unknown[]> {
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<Record<string, unknown>>,
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<string, unknown>).output_content
return typeof content === 'string' ? Buffer.byteLength(content) : 0
}
function formatHermesSessionMessageParts(
message: Record<string, unknown>,
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<string, unknown>
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
}
}
@@ -1,36 +0,0 @@
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
})
})
})
-78
View File
@@ -1,78 +0,0 @@
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<T> = {
refs: T[]
saturated: boolean
}
export class HermesRunRefRetainer<T extends HermesSortableRunRef> {
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<T> {
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)
}
-13
View File
@@ -1,13 +0,0 @@
import { measureUtf8ByteLength } from './utf8-byte-limits'
export const HTML_TO_PDF_MAX_INPUT_BYTES = 32 * 1024 * 1024
export const HTML_TO_PDF_MEMORY_LIMIT_ERROR = 'HTML export exceeds the PDF memory limit'
export function assertHtmlToPdfInputWithinMemoryLimit(
html: string,
maxBytes = HTML_TO_PDF_MAX_INPUT_BYTES
): void {
if (measureUtf8ByteLength(html, { stopAfterBytes: maxBytes }).exceededLimit) {
throw new Error(HTML_TO_PDF_MEMORY_LIMIT_ERROR)
}
}
+5 -43
View File
@@ -1,26 +1,15 @@
import { describe, expect, it } from 'vitest'
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')
}
import { buildImageDataUri } from './image-data-uri'
describe('buildImageDataUri', () => {
it('builds a data URI from base64 image bytes', () => {
const content = pngBase64()
expect(buildImageDataUri('image/png', content)).toBe(`data:image/png;base64,${content}`)
expect(buildImageDataUri('image/png', 'bmV3')).toBe('data:image/png;base64,bmV3')
})
it('strips whitespace from line-wrapped base64 payloads', () => {
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}`)
expect(buildImageDataUri('image/png', 'bm\nV3\t bmV3\r\n')).toBe(
'data:image/png;base64,bmV3bmV3'
)
})
it('returns null for an empty payload', () => {
@@ -38,31 +27,4 @@ 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()
})
})
-19
View File
@@ -1,6 +1,3 @@
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
@@ -19,21 +16,5 @@ 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])
}
+1 -82
View File
@@ -1,18 +1,5 @@
import { describe, expect, it, vi } from 'vitest'
import {
InFlightPromiseDedupe,
MAX_IN_FLIGHT_PROMISE_DEDUPE_ENTRIES,
MAX_IN_FLIGHT_PROMISE_DEDUPE_KEY_CODE_UNITS,
stableInFlightKey
} from './in-flight-promise-dedupe'
function deferred<T>(): { promise: Promise<T>; resolve: (value: T) => void } {
let resolve!: (value: T) => void
const promise = new Promise<T>((nextResolve) => {
resolve = nextResolve
})
return { promise, resolve }
}
import { InFlightPromiseDedupe, stableInFlightKey } from './in-flight-promise-dedupe'
describe('InFlightPromiseDedupe', () => {
it('coalesces only while in flight and retries after rejection', async () => {
@@ -93,72 +80,4 @@ describe('InFlightPromiseDedupe', () => {
vi.useRealTimers()
}
})
it('admits exactly the entry limit and bypasses new keys above it', async () => {
const dedupe = new InFlightPromiseDedupe<string>()
const pending = Array.from({ length: MAX_IN_FLIGHT_PROMISE_DEDUPE_ENTRIES }, () =>
deferred<string>()
)
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<string>(30_000, 1)
const firstPending = deferred<string>()
const first = dedupe.run('first', () => firstPending.promise)
firstPending.resolve('first-result')
await expect(first).resolves.toBe('first-result')
const nextPending = deferred<string>()
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<string>()
const pending = deferred<string>()
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)
})
})
+8 -34
View File
@@ -1,54 +1,28 @@
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<T> {
private readonly entries = new Map<
string,
{ promise: Promise<T>; timeout: ReturnType<typeof setTimeout> | null }
>()
private readonly maxEntries: number
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
}
constructor(private readonly maxInFlightMs = 30_000) {}
run(key: string, load: () => Promise<T>): Promise<T> {
const retainedKey = boundInFlightKey(key)
const existing = this.entries.get(retainedKey)
const existing = this.entries.get(key)
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(retainedKey)
const entry = this.entries.get(key)
if (entry?.promise === promise) {
if (entry.timeout) {
clearTimeout(entry.timeout)
}
this.entries.delete(retainedKey)
this.entries.delete(key)
}
})
const entry = {
@@ -58,13 +32,13 @@ export class InFlightPromiseDedupe<T> {
timeout:
this.maxInFlightMs > 0
? setTimeout(() => {
if (this.entries.get(retainedKey)?.promise === promise) {
this.entries.delete(retainedKey)
if (this.entries.get(key)?.promise === promise) {
this.entries.delete(key)
}
}, this.maxInFlightMs)
: null
}
this.entries.set(retainedKey, entry)
this.entries.set(key, entry)
return promise
}
@@ -79,5 +53,5 @@ export class InFlightPromiseDedupe<T> {
}
export function stableInFlightKey(parts: readonly unknown[]): string {
return boundInFlightKey(JSON.stringify(parts))
return JSON.stringify(parts)
}
@@ -1,52 +0,0 @@
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<Buffer>>()
.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)
})
})
-55
View File
@@ -1,55 +0,0 @@
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<Buffer>
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<string | null> {
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<string | undefined> {
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
}
}
@@ -1,59 +0,0 @@
import { describe, expect, it } from 'vitest'
import { mapLinuxSocketInodesToPids } from './linux-proc-socket-owner-scanner'
async function* names(values: readonly string[]): AsyncGenerator<string> {
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)
})
})
@@ -1,64 +0,0 @@
import { opendir, readlink } from 'node:fs/promises'
import { posix } from 'node:path'
type LinuxProcSocketOwnerScannerDependencies = {
readDirectoryNames: (directoryPath: string) => AsyncIterable<string>
readLink: (filePath: string) => Promise<string>
}
async function* readNodeDirectoryNames(directoryPath: string): AsyncGenerator<string> {
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<number>,
dependencies: LinuxProcSocketOwnerScannerDependencies = defaultDependencies
): Promise<Map<number, number>> {
const result = new Map<number, number>()
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
}
@@ -1,35 +0,0 @@
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<string> =>
item % 97 === 0
? { status: 'rejected', reason: `rejected-${item}` }
: { status: 'fulfilled', value: `fulfilled-${item}` }
)
)
})
})
@@ -1,83 +0,0 @@
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)
})
})
@@ -1,170 +0,0 @@
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<MarkdownDocumentListingLimits> = {}
): 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<MarkdownDocumentListingLimits> = {}
): 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)
}
@@ -1,41 +0,0 @@
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
)
}
+1 -98
View File
@@ -1,4 +1,4 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import { describe, expect, it } from 'vitest'
import {
canInspectLocalMcpConfigRoot,
getMcpConfigCandidateParentDir,
@@ -9,17 +9,6 @@ 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]
@@ -152,92 +141,6 @@ 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(
+110 -43
View File
@@ -1,12 +1,3 @@
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 = {
@@ -109,6 +100,11 @@ 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
@@ -116,15 +112,6 @@ 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 {
@@ -143,40 +130,29 @@ 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: serverEntries.map(([name, entry]) => summarizeMcpServer(name, entry))
servers: Object.entries(rawServers).map(([name, entry]) => summarizeMcpServer(name, entry))
}
}
function collectMcpServerEntries(rawServers: Record<string, unknown>): [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]])
export function maskMcpEnv(env: unknown): Record<string, string> | undefined {
if (!env || typeof env !== 'object' || Array.isArray(env)) {
return undefined
}
return entries
const masked: Record<string, string> = {}
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
}
function getRelativeParentDir(relativePath: string): string {
@@ -206,3 +182,94 @@ function extractObjectAtPath(
? (current as Record<string, unknown>)
: 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<string, unknown>
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, unknown>): 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, unknown>): string | undefined {
if (typeof raw.url === 'string') {
return raw.url
}
if (typeof raw.httpUrl === 'string') {
return raw.httpUrl
}
return undefined
}
function resolveTransport(
raw: Record<string, unknown>,
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'
}
-139
View File
@@ -1,139 +0,0 @@
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<string, string>; 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<string, unknown>
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<string, string> | undefined {
return inspectMcpEnv(env).value
}
function inspectMcpEnv(env: unknown): BoundedEnv {
if (!env || typeof env !== 'object' || Array.isArray(env)) {
return { oversized: false }
}
const masked: Record<string, string> = {}
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<string, unknown>)[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<string, unknown>): 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<string, unknown>): 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<string, string>,
transport: McpServerTransport = 'unknown'
): McpServerSummary {
return { name, transport, status: 'invalid', env, issue }
}
function resolveTransport(
raw: Record<string, unknown>,
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'
}
+1 -20
View File
@@ -1,5 +1,5 @@
import { createHash } from 'node:crypto'
import { describe, expect, it, vi } from 'vitest'
import { describe, expect, it } from 'vitest'
import {
encodeMobileE2EEV2Transcript,
validateMobileE2EEV2Handshake
@@ -29,25 +29,6 @@ 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(
-1
View File
@@ -211,7 +211,6 @@ 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
@@ -1,37 +0,0 @@
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
)
})
})
-43
View File
@@ -1,43 +0,0 @@
// 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
}
+5 -13
View File
@@ -1,22 +1,14 @@
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 (
value.length > PAIRING_RELAY_URL_MAX_CHARACTERS ||
new TextEncoder().encode(value).length > PAIRING_RELAY_URL_MAX_CHARACTERS
) {
if (new TextEncoder().encode(value).length > MAX_RELAY_URL_BYTES) {
return false
}
try {
@@ -63,11 +55,11 @@ export function createPairingOfferSchema(now: () => number = () => Date.now()) {
return z
.object({
v: z.literal(PAIRING_OFFER_VERSION),
endpoint: z.string().min(1).max(PAIRING_ENDPOINT_MAX_CHARACTERS),
deviceToken: z.string().min(1).max(PAIRING_DEVICE_TOKEN_MAX_CHARACTERS),
endpoint: z.string().min(1),
deviceToken: z.string().min(1),
// 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).max(PAIRING_PUBLIC_KEY_MAX_CHARACTERS),
publicKeyB64: z.string().min(1),
scope: PairingScopeSchema.optional(),
relay: relaySchema.optional()
})
@@ -1,38 +0,0 @@
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)
})
})
@@ -1,40 +0,0 @@
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 { nodeFileContentsEqual, nodeFileContentsEqualSync } from './node-file-content-equality'
const roots: string[] = []
function createFile(contents: string): string {
const root = mkdtempSync(join(tmpdir(), 'orca-file-content-equality-'))
roots.push(root)
const filePath = join(root, 'owned-launcher')
writeFileSync(filePath, contents)
return filePath
}
afterEach(() => {
for (const root of roots.splice(0)) {
rmSync(root, { recursive: true, force: true })
}
})
describe('Node file content equality', () => {
it('compares UTF-8 content without changing its bytes', async () => {
const filePath = createFile('launch 🐋\n')
await expect(nodeFileContentsEqual(filePath, 'launch 🐋\n')).resolves.toBe(true)
expect(nodeFileContentsEqualSync(filePath, 'launch 🐋\n')).toBe(true)
await expect(nodeFileContentsEqual(filePath, 'different\n')).resolves.toBe(false)
expect(nodeFileContentsEqualSync(filePath, 'different\n')).toBe(false)
})
it('rejects a large sparse replacement from metadata without reading its payload', async () => {
const filePath = createFile('owned launcher\n')
truncateSync(filePath, 256 * 1024 * 1024)
await expect(nodeFileContentsEqual(filePath, 'owned launcher\n')).resolves.toBe(false)
expect(nodeFileContentsEqualSync(filePath, 'owned launcher\n')).toBe(false)
})
})
-72
View File
@@ -1,72 +0,0 @@
import { closeSync, fstatSync, openSync, readSync } from 'node:fs'
import { open } from 'node:fs/promises'
export const NODE_FILE_CONTENT_COMPARE_CHUNK_BYTES = 64 * 1024
function expectedBytes(contents: string | Buffer): Buffer {
return typeof contents === 'string' ? Buffer.from(contents, 'utf8') : contents
}
export async function nodeFileContentsEqual(
filePath: string,
expectedContents: string | Buffer
): Promise<boolean> {
const expected = expectedBytes(expectedContents)
const handle = await open(filePath, 'r')
try {
if ((await handle.stat()).size !== expected.length) {
return false
}
const chunk = Buffer.allocUnsafe(
Math.min(NODE_FILE_CONTENT_COMPARE_CHUNK_BYTES, expected.length)
)
let offset = 0
while (offset < expected.length) {
const length = Math.min(chunk.length, expected.length - offset)
const { bytesRead } = await handle.read(chunk, 0, length, offset)
if (
bytesRead === 0 ||
!chunk.subarray(0, bytesRead).equals(expected.subarray(offset, offset + bytesRead))
) {
return false
}
offset += bytesRead
}
const probe = Buffer.allocUnsafe(1)
return (await handle.read(probe, 0, 1, offset)).bytesRead === 0
} finally {
await handle.close()
}
}
export function nodeFileContentsEqualSync(
filePath: string,
expectedContents: string | Buffer
): boolean {
const expected = expectedBytes(expectedContents)
const descriptor = openSync(filePath, 'r')
try {
if (fstatSync(descriptor).size !== expected.length) {
return false
}
const chunk = Buffer.allocUnsafe(
Math.min(NODE_FILE_CONTENT_COMPARE_CHUNK_BYTES, expected.length)
)
let offset = 0
while (offset < expected.length) {
const length = Math.min(chunk.length, expected.length - offset)
const bytesRead = readSync(descriptor, chunk, 0, length, offset)
if (
bytesRead === 0 ||
!chunk.subarray(0, bytesRead).equals(expected.subarray(offset, offset + bytesRead))
) {
return false
}
offset += bytesRead
}
const probe = Buffer.allocUnsafe(1)
return readSync(descriptor, probe, 0, 1, offset) === 0
} finally {
closeSync(descriptor)
}
}
@@ -1,74 +0,0 @@
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<string, Dirent[]>) {
return async (path: string): Promise<AsyncIterable<Dirent>> => ({
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<AsyncIterable<Dirent>> => ({
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)
})
})
@@ -1,86 +0,0 @@
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<Dir | AsyncIterable<Dirent>>
export type MarkdownDocumentDiscoveryOptions = {
shouldDescend: (relativePath: string, name: string) => boolean
ignoreNestedDirectoryErrors?: boolean
limits?: Partial<MarkdownDocumentListingLimits>
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<string[]> {
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<void> => {
throwIfAborted(options.signal)
let directory: Dir | AsyncIterable<Dirent>
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()
}
-40
View File
@@ -1,40 +0,0 @@
import { describe, expect, it } from 'vitest'
import {
NodeReadableTextTooLargeError,
readNodeReadableTextWithinLimit
} from './node-readable-text'
async function* chunks(values: unknown[]): AsyncGenerator<unknown> {
yield* values
}
describe('readNodeReadableTextWithinLimit', () => {
it('preserves accepted UTF-8 bytes split across chunks', async () => {
const encoded = Buffer.from('hello 🌍')
await expect(
readNodeReadableTextWithinLimit(
chunks([encoded.subarray(0, 8), encoded.subarray(8)]),
encoded.byteLength
)
).resolves.toBe('hello 🌍')
})
it('accepts input exactly at the byte limit', async () => {
await expect(
readNodeReadableTextWithinLimit(chunks(['ab', Buffer.from('cd')]), 4)
).resolves.toBe('abcd')
})
it('rejects before retaining input beyond the byte limit', async () => {
await expect(readNodeReadableTextWithinLimit(chunks(['1234', '5']), 4)).rejects.toEqual(
new NodeReadableTextTooLargeError(5, 4)
)
})
it('does not let an unlimited sequence of empty chunks grow retained state', async () => {
await expect(
readNodeReadableTextWithinLimit(chunks(Array.from({ length: 10_000 }, () => '')), 0)
).resolves.toBe('')
})
})
-42
View File
@@ -1,42 +0,0 @@
const INITIAL_READ_CAPACITY_BYTES = 64 * 1024
export class NodeReadableTextTooLargeError extends Error {
constructor(
readonly observedBytes: number,
readonly maxBytes: number
) {
super(`Input exceeds ${maxBytes} byte limit (${observedBytes} bytes received)`)
this.name = 'NodeReadableTextTooLargeError'
}
}
export async function readNodeReadableTextWithinLimit(
readable: AsyncIterable<unknown>,
maxBytes: number
): Promise<string> {
if (!Number.isSafeInteger(maxBytes) || maxBytes < 0) {
throw new RangeError('Readable text limit must be a non-negative safe integer')
}
let buffer = Buffer.allocUnsafe(Math.min(INITIAL_READ_CAPACITY_BYTES, maxBytes))
let bytes = 0
for await (const value of readable) {
const chunk = Buffer.isBuffer(value) ? value : Buffer.from(String(value))
const observedBytes = bytes + chunk.byteLength
if (!Number.isSafeInteger(observedBytes) || observedBytes > maxBytes) {
throw new NodeReadableTextTooLargeError(observedBytes, maxBytes)
}
if (observedBytes > buffer.byteLength) {
const nextCapacity = Math.min(
maxBytes,
Math.max(observedBytes, INITIAL_READ_CAPACITY_BYTES, buffer.byteLength * 2)
)
const expanded = Buffer.allocUnsafe(nextCapacity)
buffer.copy(expanded, 0, 0, bytes)
buffer = expanded
}
chunk.copy(buffer, bytes)
bytes = observedBytes
}
return buffer.subarray(0, bytes).toString('utf8')
}
@@ -1,57 +0,0 @@
import {
closeSync,
mkdtempSync,
openSync,
rmSync,
truncateSync,
writeFileSync,
writeSync
} from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it } from 'vitest'
import {
NODE_FILE_CONTENT_COMPARE_CHUNK_BYTES,
nodeSourceAndCopyContentsEqualSync
} from './node-source-copy-content-equality'
describe('Node source/copy content equality', () => {
const roots: string[] = []
afterEach(() => {
for (const root of roots.splice(0)) {
rmSync(root, { recursive: true, force: true })
}
})
it('compares multi-megabyte sparse files with fixed-size chunks', () => {
const root = mkdtempSync(join(tmpdir(), 'orca-resource-compare-'))
roots.push(root)
const sourcePath = join(root, 'source.md')
const copyPath = join(root, 'copy.md')
const sparseBytes = NODE_FILE_CONTENT_COMPARE_CHUNK_BYTES * 128
for (const path of [sourcePath, copyPath]) {
writeFileSync(path, 'same-prefix')
truncateSync(path, sparseBytes)
}
expect(nodeSourceAndCopyContentsEqualSync(sourcePath, copyPath)).toBe(true)
const descriptor = openSync(copyPath, 'r+')
try {
writeSync(descriptor, Buffer.from('x'), 0, 1, sparseBytes - 1)
} finally {
closeSync(descriptor)
}
expect(nodeSourceAndCopyContentsEqualSync(sourcePath, copyPath)).toBe(false)
})
it('rejects a non-file copy without attempting to consume it', () => {
const root = mkdtempSync(join(tmpdir(), 'orca-resource-compare-dir-'))
roots.push(root)
const sourcePath = join(root, 'source.md')
writeFileSync(sourcePath, 'contents')
expect(nodeSourceAndCopyContentsEqualSync(sourcePath, root)).toBe(false)
})
})
@@ -1,64 +0,0 @@
import { closeSync, lstatSync, openSync, readSync, statSync } from 'node:fs'
export const NODE_FILE_CONTENT_COMPARE_CHUNK_BYTES = 64 * 1024
function readChunk(descriptor: number, buffer: Buffer): number {
let offset = 0
while (offset < buffer.length) {
const bytesRead = readSync(descriptor, buffer, offset, buffer.length - offset, null)
if (bytesRead === 0) {
break
}
offset += bytesRead
}
return offset
}
export function nodeSourceAndCopyContentsEqualSync(sourcePath: string, copyPath: string): boolean {
try {
// Why: source links are intentional, but an owned copy must remain a regular file.
if (!statSync(sourcePath).isFile() || !lstatSync(copyPath).isFile()) {
return false
}
} catch {
return false
}
let sourceDescriptor: number | null = null
let copyDescriptor: number | null = null
let matches = false
let failed = false
try {
sourceDescriptor = openSync(sourcePath, 'r')
copyDescriptor = openSync(copyPath, 'r')
const sourceBuffer = Buffer.allocUnsafe(NODE_FILE_CONTENT_COMPARE_CHUNK_BYTES)
const copyBuffer = Buffer.allocUnsafe(NODE_FILE_CONTENT_COMPARE_CHUNK_BYTES)
while (true) {
const sourceBytes = readChunk(sourceDescriptor, sourceBuffer)
const copyBytes = readChunk(copyDescriptor, copyBuffer)
if (sourceBytes !== copyBytes) {
break
}
if (sourceBytes === 0) {
matches = true
break
}
if (!sourceBuffer.subarray(0, sourceBytes).equals(copyBuffer.subarray(0, copyBytes))) {
break
}
}
} catch {
failed = true
}
for (const descriptor of [sourceDescriptor, copyDescriptor]) {
if (descriptor === null) {
continue
}
try {
closeSync(descriptor)
} catch {
failed = true
}
}
return matches && !failed
}
-8
View File
@@ -1,8 +0,0 @@
import { describe, expect, it } from 'vitest'
import { iterateNulDelimitedFields } from './nul-delimited-fields'
describe('iterateNulDelimitedFields', () => {
it('preserves empty and trailing fields without materializing a split array', () => {
expect([...iterateNulDelimitedFields('one\0\0three\0')]).toEqual(['one', '', 'three', ''])
})
})
-12
View File
@@ -1,12 +0,0 @@
export function* iterateNulDelimitedFields(value: string): Generator<string> {
let start = 0
while (start <= value.length) {
const end = value.indexOf('\0', start)
if (end === -1) {
yield value.slice(start)
return
}
yield value.slice(start, end)
start = end + 1
}
}
-27
View File
@@ -1,27 +0,0 @@
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()
})
})
-83
View File
@@ -1,83 +0,0 @@
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()
})
})
-22
View File
@@ -1,22 +0,0 @@
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
)
}
+4 -38
View File
@@ -1,16 +1,10 @@
import { parseDocument } from 'yaml'
import { parse } 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<string, unknown> | null {
return value !== null && typeof value === 'object' && !Array.isArray(value)
@@ -19,11 +13,7 @@ function asRecord(value: unknown): Record<string, unknown> | null {
}
function asTrimmedString(value: unknown): string | undefined {
if (typeof value !== 'string' || !isOrcaYamlFieldWithinLimit(value)) {
return undefined
}
const trimmed = value.trim()
return trimmed || undefined
return typeof value === 'string' && value.trim() ? value.trim() : undefined
}
const DEFAULT_TAB_COLOR_RE = /^#[0-9a-fA-F]{3}(?:[0-9a-fA-F]{3})?$/
@@ -32,7 +22,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) || value.length > MAX_ORCA_YAML_COLLECTION_ENTRIES) {
if (!Array.isArray(value)) {
return []
}
@@ -68,17 +58,6 @@ 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<string>()
const recipes = value
@@ -147,22 +126,9 @@ 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 {
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 })
root = parse(content)
} catch {
return null
}
+2 -11
View File
@@ -5,7 +5,6 @@ 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 }
@@ -105,7 +104,6 @@ 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)
@@ -117,18 +115,11 @@ export function extractAllOscTitles(data: string): string[] {
break
}
if (parsed.kind === '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
}
titles.push(parsed.title)
searchStart = parsed.nextIndex
continue
}
searchStart = parsed.nextIndex
}
return oldestTitleIndex === 0
? titles
: [...titles.slice(oldestTitleIndex), ...titles.slice(0, oldestTitleIndex)]
return titles
}
+1 -19
View File
@@ -1,6 +1,4 @@
import {
PAIRING_CODE_MAX_CHARACTERS,
PAIRING_INPUT_MAX_CHARACTERS,
PAIRING_OFFER_VERSION,
PairingOfferSchema,
type PairingOffer
@@ -10,24 +8,18 @@ export { PAIRING_OFFER_VERSION, PairingOfferSchema }
export type { PairingOffer }
export function encodePairingOffer(offer: PairingOffer): string {
const json = JSON.stringify(PairingOfferSchema.parse(offer))
const json = JSON.stringify(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')
@@ -61,9 +53,6 @@ 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
@@ -79,13 +68,6 @@ 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))
@@ -1,171 +0,0 @@
import { createHash } from 'node:crypto'
import {
mkdtempSync,
readFileSync,
readdirSync,
rmSync,
truncateSync,
writeFileSync
} from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { NodeFileReadTooLargeError } from './node-bounded-file-reader'
import { JsonStringifyByteLimitError } from './node-bounded-json-stringify'
import {
PersistedStateSecretCapacityError,
assertPersistedStateSecretWithinLimit,
readPersistedStateJsonFileSync,
replacePersistedStateJsonWithinLimit,
restorePersistedStateBackupSync,
stringifyPrettyPersistedStateWithinLimit,
stringifyPersistedStateWithinLimit,
updatePersistedStateHashWithJsonRange
} from './persisted-state-file-bounds'
describe('persisted state file bounds', () => {
let root = ''
beforeEach(() => {
root = mkdtempSync(join(tmpdir(), 'orca-state-bounds-'))
})
afterEach(() => {
rmSync(root, { recursive: true, force: true })
})
it('reads and parses a state file exactly at the byte limit', () => {
const path = join(root, 'state.json')
const json = `{"value":"${'x'.repeat(20)}"}`
writeFileSync(path, json)
expect(
readPersistedStateJsonFileSync<{ value: string }>(path, Buffer.byteLength(json))
).toEqual({
byteLength: Buffer.byteLength(json),
value: { value: 'x'.repeat(20) }
})
})
it('rejects an oversized sparse state file before reading its body', () => {
const path = join(root, 'state.json')
writeFileSync(path, '')
truncateSync(path, 1025)
expect(() => readPersistedStateJsonFileSync(path, 1024)).toThrow(NodeFileReadTooLargeError)
})
it('rejects structurally amplified state before parsing it', () => {
const path = join(root, 'state.json')
const json = '{"rows":[{},{}]}'
writeFileSync(path, json)
expect(() =>
readPersistedStateJsonFileSync(path, Buffer.byteLength(json), {
structuralTokens: 7,
nestingDepth: 3
})
).toThrow('JSON structure')
})
it('matches native compact JSON exactly at the output boundary', () => {
const state = { quote: '"', unicode: '🐋', nested: [1, true, null] }
const native = JSON.stringify(state)
expect(stringifyPersistedStateWithinLimit(state, Buffer.byteLength(native))).toEqual({
byteLength: Buffer.byteLength(native),
serialized: native
})
expect(() => stringifyPersistedStateWithinLimit(state, Buffer.byteLength(native) - 1)).toThrow(
JsonStringifyByteLimitError
)
})
it('matches native pretty JSON and enforces its whitespace-inclusive boundary', () => {
const state = { nested: { value: 'x' }, list: [1, 2] }
const native = JSON.stringify(state, null, 2)
expect(stringifyPrettyPersistedStateWithinLimit(state, Buffer.byteLength(native))).toEqual({
byteLength: Buffer.byteLength(native),
serialized: native
})
expect(() =>
stringifyPrettyPersistedStateWithinLimit(state, Buffer.byteLength(native) - 1)
).toThrow(JsonStringifyByteLimitError)
})
it('bounds secret plaintext before encryption can expand it', () => {
assertPersistedStateSecretWithinLimit('🐋', 4)
expect(() => assertPersistedStateSecretWithinLimit('🐋x', 4)).toThrow(
PersistedStateSecretCapacityError
)
})
it('checks replacement growth before constructing the next payload', () => {
const serialized = '{"value":"slot"}'
const exactBytes =
Buffer.byteLength(serialized) - Buffer.byteLength('slot') + Buffer.byteLength('expanded')
expect(
replacePersistedStateJsonWithinLimit({
serialized,
currentBytes: Buffer.byteLength(serialized),
search: 'slot',
replacement: 'expanded',
maxBytes: exactBytes
})
).toEqual({ byteLength: exactBytes, serialized: '{"value":"expanded"}' })
expect(() =>
replacePersistedStateJsonWithinLimit({
serialized,
currentBytes: Buffer.byteLength(serialized),
search: 'slot',
replacement: 'expanded',
maxBytes: exactBytes - 1
})
).toThrow(JsonStringifyByteLimitError)
})
it('hashes bounded string ranges without splitting UTF-16 surrogate pairs', () => {
const value = `prefix-${'x'.repeat(8)}🐋-${'y'.repeat(8)}-suffix`
const expected = createHash('sha1').update(value).digest('hex')
const actual = createHash('sha1')
updatePersistedStateHashWithJsonRange(actual, value, 0, value.length, 2)
expect(actual.digest('hex')).toBe(expected)
})
it('atomically restores only a valid in-limit backup', () => {
const backupPath = join(root, 'backup.json')
const targetPath = join(root, 'profile', 'orca-data.json')
writeFileSync(backupPath, '{"repos":[{"id":"recovered"}]}')
restorePersistedStateBackupSync(backupPath, targetPath, 1024)
expect(JSON.parse(readFileSync(targetPath, 'utf8'))).toEqual({
repos: [{ id: 'recovered' }]
})
const originalTarget = readFileSync(targetPath)
writeFileSync(backupPath, '{{invalid')
expect(() => restorePersistedStateBackupSync(backupPath, targetPath, 1024)).toThrow()
expect(readFileSync(targetPath)).toEqual(originalTarget)
expect(
readdirSync(join(root, 'profile')).filter((name) => name.endsWith('.recovery.tmp'))
).toEqual([])
})
it('leaves the target untouched when a backup exceeds the cap', () => {
const backupPath = join(root, 'backup.json')
const targetPath = join(root, 'orca-data.json')
writeFileSync(targetPath, '{"original":true}')
writeFileSync(backupPath, '')
truncateSync(backupPath, 1025)
expect(() => restorePersistedStateBackupSync(backupPath, targetPath, 1024)).toThrow(
NodeFileReadTooLargeError
)
expect(readFileSync(targetPath, 'utf8')).toBe('{"original":true}')
})
})
-222
View File
@@ -1,222 +0,0 @@
import { randomUUID, type Hash } from 'node:crypto'
import { mkdirSync, renameSync, rmSync, writeFileSync } from 'node:fs'
import { dirname } from 'node:path'
import {
NodeFileReadTooLargeError,
readNodeFileSyncWithinLimit,
type BoundedNodeFileRead
} from './node-bounded-file-reader'
import {
JsonStringifyByteLimitError,
stringifyJsonWithinByteLimit
} from './node-bounded-json-stringify'
import {
assertJsonTextStructureWithinLimits,
type JsonTextStructureLimits
} from './json-text-structure-limit'
export const ORCA_PERSISTED_STATE_MAX_BYTES = 64 * 1024 * 1024
export const ORCA_PERSISTED_STATE_SECRET_MAX_BYTES = 4 * 1024 * 1024
export const ORCA_PERSISTED_STATE_HASH_CHUNK_CODE_UNITS = 64 * 1024
export const ORCA_PERSISTED_STATE_JSON_LIMITS: JsonTextStructureLimits = {
structuralTokens: 4_000_000,
nestingDepth: 256
}
export type PersistedStateJsonRead<T> = {
byteLength: number
value: T
}
export class PersistedStateSecretCapacityError extends Error {
constructor(
readonly observedBytes: number,
readonly maxBytes = ORCA_PERSISTED_STATE_SECRET_MAX_BYTES
) {
super(`Persisted state secret exceeds ${maxBytes} bytes`)
this.name = 'PersistedStateSecretCapacityError'
}
}
export function isPersistedStateFileCapacityError(
error: unknown
): error is NodeFileReadTooLargeError {
return error instanceof NodeFileReadTooLargeError
}
export function readPersistedStateJsonFileSync<T>(
filePath: string,
maxBytes = ORCA_PERSISTED_STATE_MAX_BYTES,
structureLimits: JsonTextStructureLimits = ORCA_PERSISTED_STATE_JSON_LIMITS
): PersistedStateJsonRead<T> {
const { buffer } = readPersistedStateFileBytesSync(filePath, maxBytes)
return {
byteLength: buffer.byteLength,
value: parsePersistedStateJsonBuffer<T>(buffer, structureLimits)
}
}
export function readPersistedStateFileBytesSync(
filePath: string,
maxBytes = ORCA_PERSISTED_STATE_MAX_BYTES
): BoundedNodeFileRead {
return readNodeFileSyncWithinLimit(filePath, maxBytes)
}
export function parsePersistedStateJsonBuffer<T>(
buffer: Buffer,
structureLimits: JsonTextStructureLimits = ORCA_PERSISTED_STATE_JSON_LIMITS
): T {
const serialized = buffer.toString('utf8')
assertJsonTextStructureWithinLimits(serialized, structureLimits)
return JSON.parse(serialized) as T
}
export function stringifyPersistedStateWithinLimit(
value: unknown,
maxBytes = ORCA_PERSISTED_STATE_MAX_BYTES
): { byteLength: number; serialized: string } {
return stringifyJsonWithinByteLimit(value, maxBytes)
}
export function stringifyPrettyPersistedStateWithinLimit(
value: unknown,
maxBytes = ORCA_PERSISTED_STATE_MAX_BYTES
): { byteLength: number; serialized: string } {
return stringifyJsonWithinByteLimit(value, maxBytes, 2)
}
export function encodePersistedStateJsonStringContent(
value: string,
maxBytes = ORCA_PERSISTED_STATE_MAX_BYTES
): string {
const { serialized } = stringifyJsonWithinByteLimit(value, maxBytes)
return serialized.slice(1, -1)
}
export function assertPersistedStateSecretWithinLimit(
value: string,
maxBytes = ORCA_PERSISTED_STATE_SECRET_MAX_BYTES
): void {
const observedBytes = Buffer.byteLength(value, 'utf8')
if (observedBytes > maxBytes) {
throw new PersistedStateSecretCapacityError(observedBytes, maxBytes)
}
}
export function replacedPersistedStateJsonByteLength(options: {
currentBytes: number
maxBytes?: number
replacement: string
search: string
}): number {
const maxBytes = options.maxBytes ?? ORCA_PERSISTED_STATE_MAX_BYTES
if (!Number.isSafeInteger(maxBytes) || maxBytes < 0) {
throw new RangeError('Persisted state JSON byte limit must be a non-negative safe integer')
}
if (!Number.isSafeInteger(options.currentBytes) || options.currentBytes < 0) {
throw new RangeError('Persisted state JSON byte count must be a non-negative safe integer')
}
if (options.currentBytes > maxBytes) {
throw new JsonStringifyByteLimitError(options.currentBytes, maxBytes)
}
const nextBytes =
options.currentBytes -
Buffer.byteLength(options.search, 'utf8') +
Buffer.byteLength(options.replacement, 'utf8')
if (!Number.isSafeInteger(nextBytes) || nextBytes < 0 || nextBytes > maxBytes) {
throw new JsonStringifyByteLimitError(nextBytes, maxBytes)
}
return nextBytes
}
export function replacePersistedStateJsonWithinLimit(options: {
currentBytes: number
maxBytes?: number
replacement: string
search: string
serialized: string
}): { byteLength: number; serialized: string } {
const byteLength = replacedPersistedStateJsonByteLength(options)
const searchIndex = options.serialized.indexOf(options.search)
if (searchIndex === -1) {
throw new Error('Persisted state JSON replacement slot is missing')
}
if (options.serialized.includes(options.search, searchIndex + options.search.length)) {
throw new Error('Persisted state JSON replacement slot is ambiguous')
}
return {
byteLength,
serialized: options.serialized.replace(options.search, () => options.replacement)
}
}
export function updatePersistedStateHashWithJsonRange(
hash: Pick<Hash, 'update'>,
value: string,
start = 0,
end = value.length,
chunkCodeUnits = ORCA_PERSISTED_STATE_HASH_CHUNK_CODE_UNITS
): void {
if (
!Number.isSafeInteger(start) ||
!Number.isSafeInteger(end) ||
start < 0 ||
end < start ||
end > value.length
) {
throw new RangeError('Persisted state hash range is invalid')
}
if (!Number.isSafeInteger(chunkCodeUnits) || chunkCodeUnits <= 0) {
throw new RangeError('Persisted state hash chunk size must be a positive safe integer')
}
let offset = start
while (offset < end) {
let nextOffset = Math.min(end, offset + chunkCodeUnits)
if (
nextOffset < end &&
isHighSurrogate(value.charCodeAt(nextOffset - 1)) &&
isLowSurrogate(value.charCodeAt(nextOffset))
) {
nextOffset += 1
}
hash.update(value.slice(offset, nextOffset), 'utf8')
offset = nextOffset
}
}
export function restorePersistedStateBackupSync(
sourcePath: string,
targetPath: string,
maxBytes = ORCA_PERSISTED_STATE_MAX_BYTES
): number {
const read = readValidatedPersistedStateBytesSync(sourcePath, maxBytes)
mkdirSync(dirname(targetPath), { recursive: true })
const temporaryPath = `${targetPath}.${process.pid}.${randomUUID()}.recovery.tmp`
try {
writeFileSync(temporaryPath, read.buffer)
renameSync(temporaryPath, targetPath)
} catch (error) {
rmSync(temporaryPath, { force: true })
throw error
}
return read.buffer.byteLength
}
function readValidatedPersistedStateBytesSync(
filePath: string,
maxBytes: number
): BoundedNodeFileRead {
const read = readPersistedStateFileBytesSync(filePath, maxBytes)
parsePersistedStateJsonBuffer(read.buffer)
return read
}
function isHighSurrogate(code: number): boolean {
return code >= 0xd800 && code <= 0xdbff
}
function isLowSurrogate(code: number): boolean {
return code >= 0xdc00 && code <= 0xdfff
}
-5
View File
@@ -1,5 +0,0 @@
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
@@ -1,7 +1,6 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import {
buildPullRequestFieldsPrompt,
GENERATED_PULL_REQUEST_JSON_STRUCTURE_LIMITS,
parseGeneratedPullRequestFields,
type PullRequestDraftContext
} from './pull-request-generation'
@@ -94,17 +93,4 @@ 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()
}
})
})
+1 -9
View File
@@ -1,10 +1,4 @@
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
@@ -158,9 +152,7 @@ export function parseGeneratedPullRequestFields(
raw: string,
fallback: Pick<PullRequestDraftContext, 'base' | 'currentTitle' | 'currentBody' | 'currentDraft'>
): GeneratedPullRequestFields {
const content = stripJsonFence(raw)
assertJsonTextStructureWithinLimits(content, GENERATED_PULL_REQUEST_JSON_STRUCTURE_LIMITS)
const parsed = JSON.parse(content) as unknown
const parsed = JSON.parse(stripJsonFence(raw)) as unknown
if (!parsed || typeof parsed !== 'object') {
throw new Error('Expected a JSON object.')
}
@@ -1,56 +0,0 @@
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)
})
})
-62
View File
@@ -1,62 +0,0 @@
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<QuickOpenDirectoryEntry[]> {
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 []
}
}
@@ -1,68 +0,0 @@
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<boolean> {
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 }
}
+2 -5
View File
@@ -1,10 +1,9 @@
import { readNodeFileWithinLimit } from './node-bounded-file-reader'
import { readFile } from 'node:fs/promises'
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<string> {
if (process.platform === 'darwin') {
@@ -12,9 +11,7 @@ export async function detectInstallCommand(): Promise<string> {
}
if (process.platform === 'linux') {
try {
const osRelease = (
await readNodeFileWithinLimit('/etc/os-release', MAX_OS_RELEASE_BYTES)
).buffer.toString('utf8')
const osRelease = await readFile('/etc/os-release', 'utf-8')
return detectLinuxInstallCommandFromOsRelease(osRelease)
} catch {
/* fall through to generic guidance */
@@ -1,82 +0,0 @@
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<string>()
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<string>()
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'])
})
})
-142
View File
@@ -1,142 +0,0 @@
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, 'maxRetainedPaths' | 'maxRetainedPathBytes' | 'maxPathBytes'>
> = {}
): 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<string>,
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()
}
}
+3 -77
View File
@@ -1,60 +1,16 @@
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
maxEntries?: number
maxDirectories?: number
maxDepth?: number
maxPathCodeUnits?: number
timeoutMs?: number
nowMs?: number
} = {}
opts: { maxFiles?: 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: maxFiles,
remainingEntries: maxEntries,
remainingDirectories: maxDirectories,
remainingPathCodeUnits: maxPathCodeUnits,
maxFiles,
maxEntries,
maxDirectories,
maxDepth,
maxPathCodeUnits,
remainingFiles: opts.maxFiles ?? QUICK_OPEN_READDIR_MAX_FILES,
deadlineMs: (opts.nowMs ?? Date.now()) + (opts.timeoutMs ?? QUICK_OPEN_READDIR_TIMEOUT_MS)
}
}
@@ -76,37 +32,7 @@ export function assertQuickOpenReaddirDeadline(budget: QuickOpenReaddirBudget):
export function consumeQuickOpenReaddirFileBudget(budget: QuickOpenReaddirBudget): void {
if (budget.remainingFiles <= 0) {
throw new Error(`${FILE_LISTING_EXCEEDED_PREFIX} ${budget.maxFiles} files`)
throw new Error(`${FILE_LISTING_EXCEEDED_PREFIX} ${QUICK_OPEN_READDIR_MAX_FILES} 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
}
@@ -1,92 +0,0 @@
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<string> {
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`)
})
})
+25 -29
View File
@@ -1,18 +1,18 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
const { lstatMock, opendirMock } = vi.hoisted(() => ({
const { lstatMock, readdirMock } = vi.hoisted(() => ({
lstatMock: vi.fn(),
opendirMock: vi.fn()
readdirMock: vi.fn()
}))
vi.mock('fs/promises', async () => {
const actual = await vi.importActual<typeof import('fs/promises')>('fs/promises') // eslint-disable-line @typescript-eslint/consistent-type-imports -- vi.importActual requires inline import()
lstatMock.mockImplementation(actual.lstat)
opendirMock.mockImplementation(actual.opendir)
readdirMock.mockImplementation(actual.readdir)
return {
...actual,
lstat: lstatMock,
opendir: opendirMock
readdir: readdirMock
}
})
@@ -238,7 +238,7 @@ describe('quick-open readdir walk', () => {
})
).resolves.toEqual(['.local/config.toml', 'dist/generated.js'])
const walkedPaths = opendirMock.mock.calls.map(([path]) => path)
const walkedPaths = readdirMock.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<typeof import('node:fs/promises')>('node:fs/promises') // eslint-disable-line @typescript-eslint/consistent-type-imports -- vi.importActual requires inline import()
let activeReads = 0
let maxActiveReads = 0
opendirMock.mockImplementation(async (...args: Parameters<typeof actual.opendir>) => {
readdirMock.mockImplementation(async (...args: Parameters<typeof actual.readdir>) => {
activeReads++
maxActiveReads = Math.max(maxActiveReads, activeReads)
await new Promise((resolve) => setTimeout(resolve, 5))
try {
return await actual.opendir(...args)
return await actual.readdir(...args)
} finally {
activeReads--
}
@@ -277,7 +277,7 @@ describe('quick-open readdir walk', () => {
expect(maxActiveReads).toBeGreaterThan(1)
expect(maxActiveReads).toBeLessThanOrEqual(32)
} finally {
opendirMock.mockImplementation(actual.opendir)
readdirMock.mockImplementation(actual.readdir)
}
})
@@ -328,7 +328,7 @@ describe('quick-open readdir walk', () => {
).resolves.toEqual([])
})
it('discards entries when a collapsed directory changes during opendir', async () => {
it('discards entries when a collapsed directory changes during readdir', 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<typeof import('node:fs/promises')>('node:fs/promises') // eslint-disable-line @typescript-eslint/consistent-type-imports -- vi.importActual requires inline import()
const distPath = join(root, 'dist')
let swapped = false
opendirMock.mockImplementation(async (...args: Parameters<typeof actual.opendir>) => {
readdirMock.mockImplementation(async (...args: Parameters<typeof actual.readdir>) => {
if (!swapped && args[0] === distPath) {
swapped = true
await rename(distPath, join(root, 'old-dist'))
await symlink(outsideRoot, distPath, 'dir')
}
return actual.opendir(...args)
return actual.readdir(...args)
})
try {
@@ -354,7 +354,7 @@ describe('quick-open readdir walk', () => {
})
).resolves.toEqual([])
} finally {
opendirMock.mockImplementation(actual.opendir)
readdirMock.mockImplementation(actual.readdir)
}
})
@@ -373,7 +373,7 @@ describe('quick-open readdir walk', () => {
).resolves.toEqual(['foo/a.ts', 'foo/bar/b.ts'])
expect(
opendirMock.mock.calls.filter(([path]) => path === join(root, 'foo', 'bar'))
readdirMock.mock.calls.filter(([path]) => path === join(root, 'foo', 'bar'))
).toHaveLength(1)
})
@@ -395,18 +395,14 @@ 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')
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
}
}
}
})
readdirMock.mockResolvedValueOnce(
Array.from({ length: QUICK_OPEN_READDIR_MAX_FILES + 1 }, (_, index) => ({
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.
@@ -433,7 +429,7 @@ describe('quick-open readdir walk', () => {
await expect(
listQuickOpenFilesWithReaddir(root, {
budget: createQuickOpenReaddirBudget({ nowMs: Date.now() - 2_000, timeoutMs: 1_000 })
budget: { remainingFiles: 10, deadlineMs: Date.now() - 1_000 }
})
).rejects.toThrow('File listing timed out')
})
@@ -533,12 +529,12 @@ describe('quick-open readdir walk', () => {
).rejects.toSatisfy(isFileListingCancellation)
})
it('rejects when cancellation lands during an empty opendir batch', async () => {
it('rejects when cancellation lands during an empty readdir batch', async () => {
const root = await makeTempRoot()
const controller = new AbortController()
const actual = await vi.importActual<typeof import('node:fs/promises')>('node:fs/promises') // eslint-disable-line @typescript-eslint/consistent-type-imports -- vi.importActual requires inline import()
opendirMock.mockImplementationOnce(async (...args: Parameters<typeof actual.opendir>) => {
const entries = await actual.opendir(...args)
readdirMock.mockImplementationOnce(async (...args: Parameters<typeof actual.readdir>) => {
const entries = await actual.readdir(...args)
controller.abort()
return entries
})
+106 -74
View File
@@ -1,44 +1,55 @@
import { lstat, readdir } from 'node:fs/promises'
import { join, relative } from 'node:path'
import { throwIfFileListingCancelled } from './file-listing-cancellation'
import { readQuickOpenDirectoryEntries } from './quick-open-directory-reader'
import { isQuickOpenReadableDirectory } from './quick-open-directory-validation'
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)
}
@@ -74,6 +85,47 @@ function rebaseExcludePrefixesForSubtree(
return rebased
}
async function hasGitEntry(absPath: string): Promise<boolean> {
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: {
@@ -112,25 +164,17 @@ async function listQuickOpenFilesFromRoots(
roots: readonly QuickOpenReaddirRoot[],
budget: QuickOpenReaddirBudget,
signal?: AbortSignal,
maxResults?: number,
knownFiles?: ReadonlySet<string>
maxResults?: number
): Promise<string[]> {
const files: string[] = []
if (maxResults !== undefined && maxResults <= 0) {
return files
}
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 })
}
let pendingDirectories = roots.map((root) => ({
root,
absPath: root.rootPath,
isRoot: true
}))
while (pendingDirectories.length > 0) {
const nextDirectories: typeof pendingDirectories = []
@@ -145,29 +189,32 @@ async function listQuickOpenFilesFromRoots(
throwIfFileListingCancelled(signal)
assertQuickOpenReaddirDeadline(budget)
const batch = pendingDirectories.slice(offset, offset + QUICK_OPEN_READDIR_CONCURRENCY)
const readResults = await Promise.allSettled(
const entryGroups = await Promise.all(
batch.map(async (pending) => {
const entries = await readQuickOpenDirectoryEntries({
absPath: pending.absPath,
allowSymlinkedRoot: Boolean(pending.isRoot && pending.root.allowRootSymlink),
budget,
signal
})
return { pending, entries }
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 entryGroups: {
pending: (typeof pendingDirectories)[number]
entries: Awaited<ReturnType<typeof readQuickOpenDirectoryEntries>>
}[] = []
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 opendir must still reject, never resolve [].
// or timeout that lands during readdir must still reject, never resolve [].
throwIfFileListingCancelled(signal)
assertQuickOpenReaddirDeadline(budget)
@@ -185,29 +232,22 @@ async function listQuickOpenFilesFromRoots(
if (shouldExcludeQuickOpenRelPath(relPath, pending.root.excludePathPrefixes)) {
continue
}
if (entry.kind === 'directory') {
if (entry.isDirectory()) {
if (shouldDescend(name) && shouldIncludeQuickOpenPath(workspaceRelPath)) {
const depth = pending.depth + 1
assertQuickOpenReaddirDepth(budget, depth)
consumeQuickOpenReaddirDirectoryBudget(budget)
consumeQuickOpenReaddirPathBudget(budget, absPath)
nextDirectories.push({ root: pending.root, absPath, depth, isRoot: false })
nextDirectories.push({ root: pending.root, absPath, isRoot: false })
}
continue
}
if (
(entry.kind === 'file' || (pending.root.includeSymlinks && entry.kind === 'symlink')) &&
(entry.isFile() || (pending.root.includeSymlinks && entry.isSymbolicLink())) &&
shouldIncludeQuickOpenPath(workspaceRelPath)
) {
const outputPath = pending.root.outputPathPrefix
? `${pending.root.outputPathPrefix}/${relPath}`
: relPath
if (knownFiles?.has(outputPath)) {
continue
}
consumeQuickOpenReaddirFileBudget(budget)
consumeQuickOpenReaddirPathBudget(budget, outputPath)
files.push(outputPath)
files.push(
pending.root.outputPathPrefix
? `${pending.root.outputPathPrefix}/${relPath}`
: relPath
)
// 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) {
@@ -232,9 +272,6 @@ export async function expandQuickOpenGitFileListing(opts: {
maxResults?: number
signal?: AbortSignal
}): Promise<string[]> {
if (opts.maxResults !== undefined && opts.maxResults <= 0) {
return []
}
const files = new Set<string>()
const excludePathPrefixes = opts.excludePathPrefixes ?? []
const budget = opts.budget ?? createQuickOpenReaddirBudget()
@@ -265,8 +302,6 @@ export async function expandQuickOpenGitFileListing(opts: {
continue
}
consumeQuickOpenReaddirEntryBudget(budget)
consumeQuickOpenReaddirPathBudget(budget, relPath)
expansionPaths.set(relPath, expansionPaths.get(relPath) ?? false)
}
@@ -285,8 +320,6 @@ 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)
@@ -306,8 +339,7 @@ export async function expandQuickOpenGitFileListing(opts: {
})),
budget,
opts.signal,
opts.maxResults === undefined ? undefined : Math.max(0, opts.maxResults - files.size),
files
opts.maxResults === undefined ? undefined : Math.max(0, opts.maxResults - files.size)
)
for (const expandedFile of expandedFiles) {
addFinalPath(expandedFile)
-141
View File
@@ -1,141 +0,0 @@
import type { RasterImageDimensions } from './raster-image-dimensions'
import {
assertRasterImagePreviewWithinLimits,
isKnownRasterImageMimeType,
RASTER_IMAGE_PREVIEW_HEADER_MAX_BYTES
} from './raster-image-preview-limits'
const BASE64_PADDING = -2
const INVALID_BASE64 = -1
function base64Value(code: number): number {
if (code >= 65 && code <= 90) {
return code - 65
}
if (code >= 97 && code <= 122) {
return code - 71
}
if (code >= 48 && code <= 57) {
return code + 4
}
if (code === 43) {
return 62
}
if (code === 47) {
return 63
}
if (code === 61) {
return BASE64_PADDING
}
return INVALID_BASE64
}
function isWhitespace(code: number): boolean {
return code === 9 || code === 10 || code === 12 || code === 13 || code === 32
}
function writeQuartet(
output: Uint8Array,
offset: number,
quartet: readonly number[]
): { bytesWritten: number; padded: boolean } | null {
const [a, b, c, d] = quartet
if (a === undefined || b === undefined || a < 0 || b < 0) {
return null
}
if (c === BASE64_PADDING) {
if (d !== BASE64_PADDING) {
return null
}
if (offset < output.length) {
output[offset] = (a << 2) | (b >> 4)
}
return { bytesWritten: Math.min(1, output.length - offset), padded: true }
}
if (c === undefined || c < 0) {
return null
}
if (offset < output.length) {
output[offset] = (a << 2) | (b >> 4)
}
if (offset + 1 < output.length) {
output[offset + 1] = ((b & 15) << 4) | (c >> 2)
}
if (d === BASE64_PADDING) {
return { bytesWritten: Math.min(2, output.length - offset), padded: true }
}
if (d === undefined || d < 0) {
return null
}
if (offset + 2 < output.length) {
output[offset + 2] = ((c & 3) << 6) | d
}
return { bytesWritten: Math.min(3, output.length - offset), padded: false }
}
function decodeBase64Prefix(content: string, maxBytes: number): Uint8Array | null {
const capacity = Math.min(maxBytes, Math.ceil(content.length / 4) * 3)
const output = new Uint8Array(capacity)
const quartet: number[] = []
let outputLength = 0
let padded = false
for (let index = 0; index < content.length && outputLength < capacity; index += 1) {
const code = content.charCodeAt(index)
if (isWhitespace(code)) {
continue
}
if (padded) {
return null
}
const value = base64Value(code)
if (value === INVALID_BASE64) {
return null
}
quartet.push(value)
if (quartet.length !== 4) {
continue
}
const decoded = writeQuartet(output, outputLength, quartet)
if (!decoded) {
return null
}
outputLength += decoded.bytesWritten
padded = decoded.padded
quartet.length = 0
}
if (!padded && outputLength < capacity && quartet.length > 0) {
if (quartet.length === 1 || quartet.includes(BASE64_PADDING)) {
return null
}
while (quartet.length < 4) {
quartet.push(BASE64_PADDING)
}
const decoded = writeQuartet(output, outputLength, quartet)
if (!decoded) {
return null
}
outputLength += decoded.bytesWritten
}
return output.subarray(0, outputLength)
}
/** Returns undefined for non-raster MIME types and null for rejected raster bytes. */
export function readRasterImagePreviewDimensionsFromBase64(
content: string,
mimeType: string | undefined
): RasterImageDimensions | null | undefined {
if (!isKnownRasterImageMimeType(mimeType)) {
return undefined
}
const prefix = decodeBase64Prefix(content, RASTER_IMAGE_PREVIEW_HEADER_MAX_BYTES)
if (!prefix) {
return null
}
try {
return assertRasterImagePreviewWithinLimits(prefix, mimeType) ?? null
} catch {
return null
}
}
@@ -1,62 +0,0 @@
import { describe, expect, it } from 'vitest'
import { readRasterImageDimensions } from './raster-image-dimensions'
function pngHeader(width: number, height: number): Buffer {
const png = Buffer.alloc(24)
Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]).copy(png)
png.writeUInt32BE(13, 8)
png.write('IHDR', 12, 'ascii')
png.writeUInt32BE(width, 16)
png.writeUInt32BE(height, 20)
return png
}
function bmpHeader(width: number, height: number): Buffer {
const bmp = Buffer.alloc(26)
bmp.write('BM', 0, 'ascii')
bmp.writeUInt32LE(40, 14)
bmp.writeInt32LE(width, 18)
bmp.writeInt32LE(height, 22)
return bmp
}
function icoWithPayload(payload: Buffer, width = 1, height = 1): Buffer {
const header = Buffer.alloc(22)
header.writeUInt16LE(1, 2)
header.writeUInt16LE(1, 4)
header[6] = width === 256 ? 0 : width
header[7] = height === 256 ? 0 : height
header.writeUInt32LE(payload.byteLength, 14)
header.writeUInt32LE(header.byteLength, 18)
return Buffer.concat([header, payload])
}
describe('readRasterImageDimensions', () => {
it('reads BMP dimensions including top-down images', () => {
expect(readRasterImageDimensions(bmpHeader(640, -480))).toEqual({
width: 640,
height: 480
})
})
it('uses embedded ICO image dimensions instead of forgeable directory values', () => {
expect(readRasterImageDimensions(icoWithPayload(pngHeader(40_000, 2)))).toEqual({
width: 40_000,
height: 2
})
})
it('reads a Uint8Array view without depending on its backing-buffer offset', () => {
const wrapped = Buffer.concat([Buffer.from('prefix'), pngHeader(320, 240), Buffer.from('tail')])
const view = wrapped.subarray(6, 30)
expect(readRasterImageDimensions(view)).toEqual({ width: 320, height: 240 })
})
it('rejects truncated ICO payloads and zero raster dimensions', () => {
const truncated = icoWithPayload(pngHeader(16, 16)).subarray(0, 30)
expect(readRasterImageDimensions(truncated)).toBeNull()
expect(readRasterImageDimensions(bmpHeader(0, 16))).toBeNull()
})
})
-252
View File
@@ -1,252 +0,0 @@
export type RasterImageDimensions = { width: number; height: number }
const JPEG_DIMENSION_SCAN_MAX_BYTES = 1024 * 1024
const JPEG_DIMENSION_SCAN_MAX_MARKERS = 4_096
const ICO_MAX_IMAGES = 1_024
const JPEG_START_OF_FRAME_MARKERS = new Set([
0xc0, 0xc1, 0xc2, 0xc3, 0xc5, 0xc6, 0xc7, 0xc9, 0xca, 0xcb, 0xcd, 0xce, 0xcf
])
const PNG_SIGNATURE = [137, 80, 78, 71, 13, 10, 26, 10]
function hasBytes(bytes: Uint8Array, offset: number, length: number): boolean {
return offset >= 0 && length >= 0 && offset + length <= bytes.byteLength
}
function matchesBytes(bytes: Uint8Array, offset: number, expected: readonly number[]): boolean {
return (
hasBytes(bytes, offset, expected.length) &&
expected.every((value, index) => bytes[offset + index] === value)
)
}
function matchesAscii(bytes: Uint8Array, offset: number, expected: string): boolean {
if (!hasBytes(bytes, offset, expected.length)) {
return false
}
for (let index = 0; index < expected.length; index += 1) {
if (bytes[offset + index] !== expected.charCodeAt(index)) {
return false
}
}
return true
}
function readUint16Le(bytes: Uint8Array, offset: number): number {
return bytes[offset]! | (bytes[offset + 1]! << 8)
}
function readUint16Be(bytes: Uint8Array, offset: number): number {
return (bytes[offset]! << 8) | bytes[offset + 1]!
}
function readUint24Le(bytes: Uint8Array, offset: number): number {
return bytes[offset]! | (bytes[offset + 1]! << 8) | (bytes[offset + 2]! << 16)
}
function readUint32Le(bytes: Uint8Array, offset: number): number {
return (
(bytes[offset]! |
(bytes[offset + 1]! << 8) |
(bytes[offset + 2]! << 16) |
(bytes[offset + 3]! << 24)) >>>
0
)
}
function readUint32Be(bytes: Uint8Array, offset: number): number {
return (
(((bytes[offset]! << 24) >>> 0) |
(bytes[offset + 1]! << 16) |
(bytes[offset + 2]! << 8) |
bytes[offset + 3]!) >>>
0
)
}
function readInt32Le(bytes: Uint8Array, offset: number): number {
return readUint32Le(bytes, offset) | 0
}
function positiveDimensions(width: number, height: number): RasterImageDimensions | null {
return Number.isSafeInteger(width) && Number.isSafeInteger(height) && width > 0 && height > 0
? { width, height }
: null
}
function readPngDimensions(bytes: Uint8Array): RasterImageDimensions | null {
if (
!matchesBytes(bytes, 0, PNG_SIGNATURE) ||
!hasBytes(bytes, 8, 16) ||
readUint32Be(bytes, 8) !== 13 ||
!matchesAscii(bytes, 12, 'IHDR')
) {
return null
}
return positiveDimensions(readUint32Be(bytes, 16), readUint32Be(bytes, 20))
}
function readGifDimensions(bytes: Uint8Array): RasterImageDimensions | null {
if (
!hasBytes(bytes, 0, 10) ||
(!matchesAscii(bytes, 0, 'GIF87a') && !matchesAscii(bytes, 0, 'GIF89a'))
) {
return null
}
return positiveDimensions(readUint16Le(bytes, 6), readUint16Le(bytes, 8))
}
function readJpegDimensions(bytes: Uint8Array): RasterImageDimensions | null {
if (!hasBytes(bytes, 0, 4) || bytes[0] !== 0xff || bytes[1] !== 0xd8) {
return null
}
let offset = 2
let markersRead = 0
const scanEnd = Math.min(bytes.byteLength, JPEG_DIMENSION_SCAN_MAX_BYTES)
while (offset < scanEnd && markersRead < JPEG_DIMENSION_SCAN_MAX_MARKERS) {
while (offset < scanEnd && bytes[offset] === 0xff) {
offset += 1
}
const marker = bytes[offset]
offset += 1
markersRead += 1
if (marker === undefined || marker === 0x00 || marker === 0xd9 || marker === 0xda) {
return null
}
if (marker === 0x01 || (marker >= 0xd0 && marker <= 0xd8)) {
continue
}
if (!hasBytes(bytes, offset, 2)) {
return null
}
const segmentLength = readUint16Be(bytes, offset)
if (segmentLength < 2 || offset + segmentLength > scanEnd) {
return null
}
if (JPEG_START_OF_FRAME_MARKERS.has(marker)) {
return segmentLength >= 7
? positiveDimensions(readUint16Be(bytes, offset + 5), readUint16Be(bytes, offset + 3))
: null
}
offset += segmentLength
}
return null
}
function readWebpDimensions(bytes: Uint8Array): RasterImageDimensions | null {
if (
!hasBytes(bytes, 0, 20) ||
!matchesAscii(bytes, 0, 'RIFF') ||
!matchesAscii(bytes, 8, 'WEBP')
) {
return null
}
let offset = 12
while (hasBytes(bytes, offset, 8)) {
const chunkSize = readUint32Le(bytes, offset + 4)
const dataOffset = offset + 8
const dataEnd = dataOffset + chunkSize
if (matchesAscii(bytes, offset, 'VP8X') && chunkSize >= 10 && hasBytes(bytes, dataOffset, 10)) {
return positiveDimensions(
readUint24Le(bytes, dataOffset + 4) + 1,
readUint24Le(bytes, dataOffset + 7) + 1
)
}
if (
matchesAscii(bytes, offset, 'VP8L') &&
chunkSize >= 5 &&
hasBytes(bytes, dataOffset, 5) &&
bytes[dataOffset] === 0x2f
) {
const b0 = bytes[dataOffset + 1]!
const b1 = bytes[dataOffset + 2]!
const b2 = bytes[dataOffset + 3]!
const b3 = bytes[dataOffset + 4]!
return positiveDimensions(
1 + (((b1 & 0x3f) << 8) | b0),
1 + (((b3 & 0x0f) << 10) | (b2 << 2) | ((b1 & 0xc0) >> 6))
)
}
if (
matchesAscii(bytes, offset, 'VP8 ') &&
chunkSize >= 10 &&
hasBytes(bytes, dataOffset, 10) &&
bytes[dataOffset + 3] === 0x9d &&
bytes[dataOffset + 4] === 0x01 &&
bytes[dataOffset + 5] === 0x2a
) {
return positiveDimensions(
readUint16Le(bytes, dataOffset + 6) & 0x3fff,
readUint16Le(bytes, dataOffset + 8) & 0x3fff
)
}
if (dataEnd > bytes.byteLength) {
return null
}
offset = dataEnd + (chunkSize % 2)
}
return null
}
function readDibDimensions(bytes: Uint8Array, offset: number): RasterImageDimensions | null {
if (!hasBytes(bytes, offset, 12)) {
return null
}
const headerSize = readUint32Le(bytes, offset)
if (headerSize === 12) {
return positiveDimensions(readUint16Le(bytes, offset + 4), readUint16Le(bytes, offset + 6))
}
if (headerSize < 40 || !hasBytes(bytes, offset, 12)) {
return null
}
return positiveDimensions(
Math.abs(readInt32Le(bytes, offset + 4)),
Math.abs(readInt32Le(bytes, offset + 8))
)
}
function readBmpDimensions(bytes: Uint8Array): RasterImageDimensions | null {
return matchesAscii(bytes, 0, 'BM') ? readDibDimensions(bytes, 14) : null
}
function readIcoDimensions(bytes: Uint8Array): RasterImageDimensions | null {
if (!hasBytes(bytes, 0, 6) || readUint16Le(bytes, 0) !== 0 || readUint16Le(bytes, 2) !== 1) {
return null
}
const imageCount = readUint16Le(bytes, 4)
if (imageCount <= 0 || imageCount > ICO_MAX_IMAGES || !hasBytes(bytes, 6, imageCount * 16)) {
return null
}
let maxWidth = 0
let maxHeight = 0
for (let index = 0; index < imageCount; index += 1) {
const entryOffset = 6 + index * 16
const encodedSize = readUint32Le(bytes, entryOffset + 8)
const imageOffset = readUint32Le(bytes, entryOffset + 12)
if (encodedSize <= 0 || !hasBytes(bytes, imageOffset, encodedSize)) {
return null
}
const payload = bytes.subarray(imageOffset, imageOffset + encodedSize)
const embedded = readPngDimensions(payload) ?? readDibDimensions(payload, 0)
const width = embedded?.width ?? (bytes[entryOffset] === 0 ? 256 : bytes[entryOffset]!)
const height =
embedded?.height ?? (bytes[entryOffset + 1] === 0 ? 256 : bytes[entryOffset + 1]!)
maxWidth = Math.max(maxWidth, width)
maxHeight = Math.max(maxHeight, height)
}
return positiveDimensions(maxWidth, maxHeight)
}
/** Reads encoded raster dimensions without invoking a native or browser image decoder. */
export function readRasterImageDimensions(bytes: Uint8Array): RasterImageDimensions | null {
return (
readPngDimensions(bytes) ??
readGifDimensions(bytes) ??
readJpegDimensions(bytes) ??
readWebpDimensions(bytes) ??
readBmpDimensions(bytes) ??
readIcoDimensions(bytes)
)
}
@@ -1,57 +0,0 @@
import { describe, expect, it } from 'vitest'
import {
INVALID_RASTER_IMAGE_PREVIEW_ERROR,
MAX_RASTER_IMAGE_PREVIEW_DIMENSION_PX,
RASTER_IMAGE_PREVIEW_TOO_LARGE_ERROR,
assertRasterImagePreviewWithinLimits,
isKnownRasterImageMimeType
} from './raster-image-preview-limits'
function pngHeader(width: number, height: number): Buffer {
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
}
describe('raster image preview limits', () => {
it('accepts ordinary 8K images and returns their dimensions', () => {
expect(assertRasterImagePreviewWithinLimits(pngHeader(7680, 4320), 'image/png')).toEqual({
width: 7680,
height: 4320
})
})
it('rejects oversized edges and total pixel counts before decode', () => {
expect(() =>
assertRasterImagePreviewWithinLimits(
pngHeader(MAX_RASTER_IMAGE_PREVIEW_DIMENSION_PX + 1, 1),
'image/png'
)
).toThrow(RASTER_IMAGE_PREVIEW_TOO_LARGE_ERROR)
expect(() => assertRasterImagePreviewWithinLimits(pngHeader(8192, 8192), 'image/png')).toThrow(
RASTER_IMAGE_PREVIEW_TOO_LARGE_ERROR
)
})
it('rejects invalid known raster bytes but leaves SVG and PDF unchanged', () => {
expect(() => assertRasterImagePreviewWithinLimits(new Uint8Array([1]), 'image/gif')).toThrow(
INVALID_RASTER_IMAGE_PREVIEW_ERROR
)
expect(
assertRasterImagePreviewWithinLimits(new Uint8Array([1]), 'image/svg+xml')
).toBeUndefined()
expect(
assertRasterImagePreviewWithinLimits(new Uint8Array([1]), 'application/pdf')
).toBeUndefined()
})
it('recognizes supported MIME aliases case-insensitively', () => {
expect(isKnownRasterImageMimeType('IMAGE/JPEG; charset=binary')).toBe(true)
expect(isKnownRasterImageMimeType('image/vnd.microsoft.icon')).toBe(true)
expect(isKnownRasterImageMimeType('image/tiff')).toBe(false)
})
})
-69
View File
@@ -1,69 +0,0 @@
import { readRasterImageDimensions, type RasterImageDimensions } from './raster-image-dimensions'
export const MAX_RASTER_IMAGE_PREVIEW_DIMENSION_PX = 32_768
export const MAX_RASTER_IMAGE_PREVIEW_PIXELS = 32 * 1024 * 1024
export const RASTER_IMAGE_PREVIEW_HEADER_MAX_BYTES = 1024 * 1024
export const INVALID_RASTER_IMAGE_PREVIEW_ERROR =
'Image preview has invalid or unsupported raster dimensions'
export const RASTER_IMAGE_PREVIEW_TOO_LARGE_ERROR =
'Image dimensions exceed the preview safety limit'
const RASTER_IMAGE_MIME_TYPES = new Set([
'image/apng',
'image/bmp',
'image/gif',
'image/ico',
'image/jpeg',
'image/jpg',
'image/pjpeg',
'image/png',
'image/vnd.microsoft.icon',
'image/webp',
'image/x-bmp',
'image/x-icon',
'image/x-ms-bmp'
])
function normalizeMimeType(mimeType: string | undefined): string | null {
const normalized = mimeType?.split(';', 1)[0]?.trim().toLowerCase()
return normalized || null
}
export function isKnownRasterImageMimeType(mimeType: string | undefined): boolean {
const normalized = normalizeMimeType(mimeType)
return normalized !== null && RASTER_IMAGE_MIME_TYPES.has(normalized)
}
export function isRasterImagePreviewDimensions(value: unknown): value is RasterImageDimensions {
if (!value || typeof value !== 'object') {
return false
}
const dimensions = value as Partial<RasterImageDimensions>
return (
Number.isSafeInteger(dimensions.width) &&
Number.isSafeInteger(dimensions.height) &&
dimensions.width! > 0 &&
dimensions.height! > 0 &&
dimensions.width! <= MAX_RASTER_IMAGE_PREVIEW_DIMENSION_PX &&
dimensions.height! <= MAX_RASTER_IMAGE_PREVIEW_DIMENSION_PX &&
dimensions.width! <= Math.floor(MAX_RASTER_IMAGE_PREVIEW_PIXELS / dimensions.height!)
)
}
/** Validates encoded raster dimensions without invoking a native image decoder. */
export function assertRasterImagePreviewWithinLimits(
bytes: Uint8Array,
mimeType: string | undefined
): RasterImageDimensions | undefined {
if (!isKnownRasterImageMimeType(mimeType)) {
return undefined
}
const dimensions = readRasterImageDimensions(bytes)
if (!dimensions) {
throw new Error(INVALID_RASTER_IMAGE_PREVIEW_ERROR)
}
if (!isRasterImagePreviewDimensions(dimensions)) {
throw new Error(RASTER_IMAGE_PREVIEW_TOO_LARGE_ERROR)
}
return dimensions
}
-12
View File
@@ -1,12 +0,0 @@
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<T>(text: string): T {
assertJsonTextStructureWithinLimits(text, {
structuralTokens: RELAY_JSON_MAX_STRUCTURAL_TOKENS,
nestingDepth: RELAY_JSON_MAX_NESTING_DEPTH
})
return JSON.parse(text) as T
}

Some files were not shown because too many files have changed in this diff Show More