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
+1 -44
View File
@@ -7,7 +7,6 @@ import {
readFile,
readlink,
symlink,
truncate,
writeFile
} from 'node:fs/promises'
import { tmpdir } from 'node:os'
@@ -28,7 +27,7 @@ vi.mock('node:child_process', () => ({
execFile: execFileMock
}))
import { CLI_LAUNCHER_INSPECTION_MAX_BYTES, CliInstaller } from './cli-installer'
import { CliInstaller } from './cli-installer'
import { buildAppImageCliWrapper } from './appimage-cli-wrapper'
import {
WindowsUserPathRegistryReader,
@@ -707,48 +706,6 @@ describe('CliInstaller', () => {
}
)
it.skipIf(process.platform === 'win32')(
'preserves an oversized regular launcher even when its prefix resembles an Orca launcher',
async () => {
const fixture = await makeFixture()
const commandDir = join(fixture.root, 'bin')
const installPath = join(commandDir, 'orca')
const resourcesPath = await createPackagedMacLauncher(fixture.root)
await mkdir(commandDir, { recursive: true })
await writeFile(
installPath,
[
'#!/usr/bin/env bash',
'ELECTRON_RUN_AS_NODE=1',
'ORCA_NODE_OPTIONS=x',
'NODE_REPL_EXTERNAL_MODULE=x',
`CLI='${join(fixture.root, 'out', 'cli', 'index.js')}'`,
''
].join('\n'),
'utf8'
)
await truncate(installPath, CLI_LAUNCHER_INSPECTION_MAX_BYTES + 1)
const installer = new CliInstaller({
platform: 'darwin',
isPackaged: true,
resourcesPath,
commandPathOverride: installPath,
processPathEnv: commandDir
})
await expect(installer.getStatus()).resolves.toMatchObject({
state: 'conflict',
currentTarget: null
})
await expect(installer.install()).rejects.toThrow('Refusing to replace non-Orca command')
await expect(lstat(installPath)).resolves.toHaveProperty(
'size',
CLI_LAUNCHER_INSPECTION_MAX_BYTES + 1
)
}
)
// Why: a dev build can temporarily own the public command on developer
// machines; packaged Orca should treat that as stale, not a hard conflict.
it.skipIf(process.platform === 'win32')(
+25 -32
View File
@@ -2,16 +2,21 @@
import { app } from 'electron'
import { execFile } from 'node:child_process'
import { constants, existsSync } from 'node:fs'
import { access, lstat, mkdir, readlink, stat, symlink, unlink, writeFile } from 'node:fs/promises'
import {
access,
lstat,
mkdir,
readFile,
readlink,
stat,
symlink,
unlink,
writeFile
} from 'node:fs/promises'
import { homedir } from 'node:os'
import { basename, dirname, isAbsolute, join, relative, resolve } from 'node:path'
import { promisify } from 'node:util'
import type { CliInstallMethod, CliInstallStatus } from '../../shared/cli-install-types'
import { nodeFileContentsEqual } from '../../shared/node-file-content-equality'
import {
NodeFileReadTooLargeError,
readNodeFileWithinLimit
} from '../../shared/node-bounded-file-reader'
import { buildAppImageCliWrapper } from './appimage-cli-wrapper'
import {
invalidateWindowsUserPathRegistryCache,
@@ -27,7 +32,6 @@ const LINUX_COMMAND_NAME = 'orca-ide'
const LEGACY_LINUX_COMMAND_NAME = 'orca'
const DEV_LAUNCHER_DIR = ['cli', 'bin']
const WINDOWS_PATH_WRITE_TIMEOUT_MS = 5_000
export const CLI_LAUNCHER_INSPECTION_MAX_BYTES = 64 * 1024
type CliInstallerOptions = {
platform?: NodeJS.Platform
@@ -496,18 +500,19 @@ export class CliInstaller {
})
}
const currentContent = await readFile(commandPath, 'utf8')
const expectedContent = buildAppImageCliWrapper(appImagePath)
const matches = await nodeFileContentsEqual(commandPath, expectedContent)
return this.buildStatus({
commandPath,
launcherPath: appImagePath,
installMethod: 'wrapper',
supported: true,
state: matches ? 'installed' : 'stale',
state: currentContent === expectedContent ? 'installed' : 'stale',
currentTarget: appImagePath,
detail: matches
? `Registered at ${commandPath}.`
: `${commandPath} points to a different launcher.`
detail:
currentContent === expectedContent
? `Registered at ${commandPath}.`
: `${commandPath} points to a different launcher.`
})
} catch (error) {
if (isMissingError(error)) {
@@ -533,7 +538,8 @@ export class CliInstaller {
const stats = await lstat(commandPath)
if (!stats.isSymbolicLink()) {
if (stats.isFile()) {
const managedTarget = await readManagedUnixLauncherTarget(commandPath)
const currentContent = await readFile(commandPath, 'utf8')
const managedTarget = extractManagedUnixLauncherTarget(currentContent)
if (managedTarget) {
return this.buildStatus({
commandPath,
@@ -688,18 +694,19 @@ export class CliInstaller {
})
}
const currentContent = await readFile(commandPath, 'utf8')
const expectedContent = buildWindowsForwarder(launcherPath)
const matches = await nodeFileContentsEqual(commandPath, expectedContent)
return this.buildStatus({
commandPath,
launcherPath,
installMethod: 'wrapper',
supported: true,
state: matches ? 'installed' : 'stale',
state: currentContent === expectedContent ? 'installed' : 'stale',
currentTarget: launcherPath,
detail: matches
? `Registered at ${commandPath}.`
: `${commandPath} points to a different launcher.`
detail:
currentContent === expectedContent
? `Registered at ${commandPath}.`
: `${commandPath} points to a different launcher.`
})
} catch (error) {
if (isMissingError(error)) {
@@ -1006,20 +1013,6 @@ function extractManagedUnixLauncherTarget(content: string): string | null {
: null
}
async function readManagedUnixLauncherTarget(filePath: string): Promise<string | null> {
try {
const contents = (
await readNodeFileWithinLimit(filePath, CLI_LAUNCHER_INSPECTION_MAX_BYTES)
).buffer.toString('utf8')
return extractManagedUnixLauncherTarget(contents)
} catch (error) {
if (error instanceof NodeFileReadTooLargeError) {
return null
}
throw error
}
}
function extractShellAssignment(content: string, name: string): string | null {
const match = new RegExp(`^${name}=('([^']*)'|"([^"]*)"|([^\\n]+))$`, 'm').exec(content)
if (!match) {
@@ -1,4 +1,4 @@
import { mkdir, mkdtemp, readFile, rm, stat, truncate, writeFile } from 'node:fs/promises'
import { mkdir, mkdtemp, readFile, rm, stat, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, describe, expect, it, vi } from 'vitest'
@@ -7,10 +7,7 @@ vi.mock('electron', () => ({
app: { isPackaged: true }
}))
import {
LINUX_BARE_ORCA_DISPATCHER_MAX_BYTES,
installLinuxBareOrcaDispatcher
} from './linux-bare-orca-dispatcher'
import { installLinuxBareOrcaDispatcher } from './linux-bare-orca-dispatcher'
const created: string[] = []
@@ -70,45 +67,6 @@ describe('installLinuxBareOrcaDispatcher', () => {
expect(second.state).toBe('installed')
})
it('recognizes an owned dispatcher at the exact inspection boundary', async () => {
const { homePath, resourcesPath } = await makeFixture()
const dispatcherPath = join(homePath, '.local', 'bin', 'orca')
const ownedPrefix = '#!/bin/sh\n# orca-serve-bare-orca-dispatcher\n'
await mkdir(join(homePath, '.local', 'bin'), { recursive: true })
await writeFile(
dispatcherPath,
ownedPrefix +
' '.repeat(LINUX_BARE_ORCA_DISPATCHER_MAX_BYTES - Buffer.byteLength(ownedPrefix)),
'utf8'
)
const result = await installLinuxBareOrcaDispatcher({
resourcesPath,
homePath,
appImagePath: null
})
expect(result.state).toBe('installed')
expect((await stat(dispatcherPath)).size).toBeLessThan(LINUX_BARE_ORCA_DISPATCHER_MAX_BYTES)
})
it('preserves an oversized dispatcher even when its prefix contains the ownership marker', async () => {
const { homePath, resourcesPath } = await makeFixture()
const dispatcherPath = join(homePath, '.local', 'bin', 'orca')
await mkdir(join(homePath, '.local', 'bin'), { recursive: true })
await writeFile(dispatcherPath, '#!/bin/sh\n# orca-serve-bare-orca-dispatcher\n', 'utf8')
await truncate(dispatcherPath, LINUX_BARE_ORCA_DISPATCHER_MAX_BYTES + 1)
const result = await installLinuxBareOrcaDispatcher({
resourcesPath,
homePath,
appImagePath: null
})
expect(result.state).toBe('skipped-foreign')
expect((await stat(dispatcherPath)).size).toBe(LINUX_BARE_ORCA_DISPATCHER_MAX_BYTES + 1)
})
it('quotes a resources path containing spaces so the exec line cannot be split', async () => {
const root = await mkdtemp(join(tmpdir(), 'orca-bare-dispatcher-space-'))
created.push(root)
+2 -6
View File
@@ -1,15 +1,13 @@
import { existsSync } from 'node:fs'
import { chmod, mkdir, writeFile } from 'node:fs/promises'
import { chmod, mkdir, readFile, writeFile } from 'node:fs/promises'
import { homedir } from 'node:os'
import { dirname, join } from 'node:path'
import { readNodeFileWithinLimit } from '../../shared/node-bounded-file-reader'
import { buildAppImageCliWrapper, quoteShell } from './appimage-cli-wrapper'
import { getBundledLauncherPath } from './cli-installer'
// Why: marks a dispatcher this function wrote so repeat serve starts overwrite
// our own file idempotently but never clobber a user's own ~/.local/bin/orca.
const DISPATCHER_MARKER = '# orca-serve-bare-orca-dispatcher'
export const LINUX_BARE_ORCA_DISPATCHER_MAX_BYTES = 64 * 1024
export type LinuxBareOrcaDispatcherOptions = {
/** Packaged app resources root; the bundled `orca-ide` launcher lives under it. */
@@ -108,9 +106,7 @@ function withMarker(script: string): string {
async function isOwnedDispatcher(dispatcherPath: string): Promise<boolean> {
try {
return (
await readNodeFileWithinLimit(dispatcherPath, LINUX_BARE_ORCA_DISPATCHER_MAX_BYTES)
).buffer.includes(DISPATCHER_MARKER)
return (await readFile(dispatcherPath, 'utf8')).includes(DISPATCHER_MARKER)
} catch {
return false
}
@@ -1,4 +1,4 @@
import { chmodSync, mkdirSync, readFileSync, statSync, truncateSync, writeFileSync } from 'node:fs'
import { chmodSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs'
import { mkdtemp, rm } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
@@ -8,14 +8,7 @@ vi.mock('electron', () => ({
app: { isPackaged: true }
}))
import {
_getLinuxTerminalShimCacheSizeForTests,
_isLinuxTerminalShimCacheKeyRetainableForTests,
_resetLinuxTerminalShimCacheForTests,
ensureLinuxTerminalOrcaCliShimDir,
LINUX_TERMINAL_SHIM_CACHE_KEY_MAX_BYTES,
LINUX_TERMINAL_SHIM_CACHE_MAX_ENTRIES
} from './linux-terminal-orca-cli-shim'
import { ensureLinuxTerminalOrcaCliShimDir } from './linux-terminal-orca-cli-shim'
const created: string[] = []
@@ -30,7 +23,6 @@ async function makeFixture(): Promise<{ userDataPath: string; resourcesPath: str
}
afterEach(async () => {
_resetLinuxTerminalShimCacheForTests()
await Promise.all(created.splice(0).map((dir) => rm(dir, { recursive: true, force: true })))
})
@@ -99,25 +91,6 @@ describe('ensureLinuxTerminalOrcaCliShimDir', () => {
expect(content).not.toContain(resourcesPath)
})
it('replaces a large sparse file at the owned shim path without loading it whole', async () => {
const { userDataPath, resourcesPath } = await makeFixture()
const shimDir = join(userDataPath, 'linux-orca-cli-shim')
const shimPath = join(shimDir, 'orca')
mkdirSync(shimDir, { recursive: true })
writeFileSync(shimPath, 'stale')
truncateSync(shimPath, 256 * 1024 * 1024)
expect(
ensureLinuxTerminalOrcaCliShimDir({
userDataPath,
resourcesPath,
appImagePath: null
})
).toBe(shimDir)
expect(statSync(shimPath).size).toBeLessThan(64 * 1024)
expect(readFileSync(shimPath, 'utf8')).toContain('orca-ide')
})
it('returns null (and does not memoize) when the bundled launcher is missing', async () => {
const root = await mkdtemp(join(tmpdir(), 'orca-terminal-cli-shim-missing-'))
created.push(root)
@@ -142,31 +115,4 @@ describe('ensureLinuxTerminalOrcaCliShimDir', () => {
})
expect(recovered).toBe(join(userDataPath, 'linux-orca-cli-shim'))
})
it('bounds successful user-data path memoization', async () => {
const { userDataPath, resourcesPath } = await makeFixture()
for (let index = 0; index <= LINUX_TERMINAL_SHIM_CACHE_MAX_ENTRIES; index += 1) {
expect(
ensureLinuxTerminalOrcaCliShimDir({
userDataPath: join(userDataPath, String(index)),
resourcesPath,
appImagePath: null
})
).not.toBeNull()
}
expect(_getLinuxTerminalShimCacheSizeForTests()).toBe(LINUX_TERMINAL_SHIM_CACHE_MAX_ENTRIES)
})
it('measures memoized paths by UTF-8 bytes', () => {
expect(
_isLinuxTerminalShimCacheKeyRetainableForTests(
'x'.repeat(LINUX_TERMINAL_SHIM_CACHE_KEY_MAX_BYTES)
)
).toBe(true)
expect(
_isLinuxTerminalShimCacheKeyRetainableForTests(
'😀'.repeat(LINUX_TERMINAL_SHIM_CACHE_KEY_MAX_BYTES / 4 + 1)
)
).toBe(false)
})
})
+7 -54
View File
@@ -1,7 +1,5 @@
import { chmodSync, mkdirSync, writeFileSync } from 'node:fs'
import { chmodSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
import { join } from 'node:path'
import { nodeFileContentsEqualSync } from '../../shared/node-file-content-equality'
import { measureUtf8ByteLength } from '../../shared/utf8-byte-limits'
import { buildBareOrcaCliScript } from './linux-bare-orca-dispatcher'
const SHIM_DIR_NAME = 'linux-orca-cli-shim'
@@ -10,37 +8,6 @@ const SHIM_DIR_NAME = 'linux-orca-cli-shim'
// changes with the install itself, so one successful write per process is enough.
// Failures are NOT cached so a transient fs error retries on the next spawn.
const ensuredShimDirs = new Map<string, string>()
export const LINUX_TERMINAL_SHIM_CACHE_MAX_ENTRIES = 64
export const LINUX_TERMINAL_SHIM_CACHE_KEY_MAX_BYTES = 64 * 1024
function getEnsuredShimDir(userDataPath: string): string | undefined {
const cached = ensuredShimDirs.get(userDataPath)
if (cached === undefined) {
return undefined
}
ensuredShimDirs.delete(userDataPath)
ensuredShimDirs.set(userDataPath, cached)
return cached
}
function rememberEnsuredShimDir(userDataPath: string, shimDir: string): void {
if (
measureUtf8ByteLength(userDataPath, {
stopAfterBytes: LINUX_TERMINAL_SHIM_CACHE_KEY_MAX_BYTES
}).exceededLimit
) {
return
}
ensuredShimDirs.delete(userDataPath)
ensuredShimDirs.set(userDataPath, shimDir)
while (ensuredShimDirs.size > LINUX_TERMINAL_SHIM_CACHE_MAX_ENTRIES) {
const oldest = ensuredShimDirs.keys().next().value
if (oldest === undefined) {
return
}
ensuredShimDirs.delete(oldest)
}
}
export type LinuxTerminalOrcaCliShimOptions = {
userDataPath: string
@@ -60,7 +27,7 @@ export type LinuxTerminalOrcaCliShimOptions = {
export function ensureLinuxTerminalOrcaCliShimDir(
options: LinuxTerminalOrcaCliShimOptions
): string | null {
const cached = getEnsuredShimDir(options.userDataPath)
const cached = ensuredShimDirs.get(options.userDataPath)
if (cached !== undefined) {
return cached
}
@@ -80,7 +47,7 @@ export function ensureLinuxTerminalOrcaCliShimDir(
const shimDir = join(options.userDataPath, SHIM_DIR_NAME)
const shimPath = join(shimDir, 'orca')
try {
if (!shimMatches(shimPath, resolved.script)) {
if (readShim(shimPath) !== resolved.script) {
mkdirSync(shimDir, { recursive: true })
writeFileSync(shimPath, resolved.script, 'utf8')
}
@@ -90,28 +57,14 @@ export function ensureLinuxTerminalOrcaCliShimDir(
} catch {
return null
}
rememberEnsuredShimDir(options.userDataPath, shimDir)
ensuredShimDirs.set(options.userDataPath, shimDir)
return shimDir
}
export function _resetLinuxTerminalShimCacheForTests(): void {
ensuredShimDirs.clear()
}
export function _getLinuxTerminalShimCacheSizeForTests(): number {
return ensuredShimDirs.size
}
export function _isLinuxTerminalShimCacheKeyRetainableForTests(userDataPath: string): boolean {
return !measureUtf8ByteLength(userDataPath, {
stopAfterBytes: LINUX_TERMINAL_SHIM_CACHE_KEY_MAX_BYTES
}).exceededLimit
}
function shimMatches(shimPath: string, expected: string): boolean {
function readShim(shimPath: string): string | null {
try {
return nodeFileContentsEqualSync(shimPath, expected)
return readFileSync(shimPath, 'utf8')
} catch {
return false
return null
}
}
@@ -1,80 +0,0 @@
import { execFileSync } from 'node:child_process'
import { mkdir, mkdtemp, rm, stat, truncate, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { describe, expect, it } from 'vitest'
import type { CliInstallStatus } from '../../shared/cli-install-types'
import { WSL_CLI_INSPECTION_MAX_BYTES, WslCliInstaller, _internals } from './wsl-cli-installer'
function installedHostStatus(): CliInstallStatus {
const launcherPath = 'C:\\Orca\\resources\\bin\\orca.exe'
return {
platform: 'win32',
commandName: 'orca',
commandPath: launcherPath,
pathDirectory: 'C:\\Orca\\resources\\bin',
pathConfigured: true,
launcherPath,
installMethod: 'wrapper',
supported: true,
state: 'installed',
currentTarget: launcherPath,
unsupportedReason: null,
detail: null
}
}
describe('WSL CLI launcher inspection bounds', () => {
it('accepts encoded file output at the exact byte ceiling and rejects one byte more', () => {
const prefix = _internals.WSL_BOUNDED_FILE_OUTPUT_PREFIX
const exact = Buffer.alloc(WSL_CLI_INSPECTION_MAX_BYTES, 0x61)
const oversized = Buffer.alloc(WSL_CLI_INSPECTION_MAX_BYTES + 1, 0x61)
expect(
_internals.parseBoundedWslFileOutput(`${prefix}${exact.toString('base64')}`)
).toHaveLength(WSL_CLI_INSPECTION_MAX_BYTES)
expect(_internals.parseBoundedWslFileOutput(`${prefix}${oversized.toString('base64')}`)).toBe(
'not_file'
)
})
it.skipIf(process.platform === 'win32')(
'fails closed on a sparse oversized launcher without reading it whole',
async () => {
const root = await mkdtemp(join(tmpdir(), 'orca-wsl-cli-bounded-read-'))
const home = join(root, 'home')
const commandPath = join(home, '.local', 'bin', 'orca-ide')
await mkdir(join(home, '.local', 'bin'), { recursive: true })
await writeFile(commandPath, '# Orca managed WSL CLI launcher\n', 'utf8')
await truncate(commandPath, 256 * 1024 * 1024)
const runner = async (_distro: string, command: string): Promise<string> => {
if (command.includes('printf %s "$HOME"')) {
return home
}
if (command.includes('command -v powershell.exe')) {
return 'yes'
}
if (command.includes('case ":$PATH:"')) {
return 'yes'
}
return execFileSync('bash', ['-c', command], {
encoding: 'utf8',
maxBuffer: 256 * 1024
})
}
const installer = new WslCliInstaller({
platform: 'win32',
distro: 'Ubuntu',
hostInstaller: { getStatus: async () => installedHostStatus() },
wslRunner: runner
})
try {
await expect(installer.getStatus()).resolves.toMatchObject({ state: 'conflict' })
await expect(stat(commandPath)).resolves.toHaveProperty('size', 256 * 1024 * 1024)
} finally {
await rm(root, { recursive: true, force: true })
}
}
)
})
+5 -5
View File
@@ -134,7 +134,7 @@ function createWslRunner(
}
return ''
}
if (command.includes('head -c ')) {
if (command.includes('cat ')) {
if (command.includes(commandPath)) {
return files.get(commandPath) ?? '__ORCA_MISSING__'
}
@@ -267,10 +267,7 @@ describe('WslCliInstaller', () => {
distro: 'Ubuntu',
hostInstaller: { getStatus: async () => makeHostStatus('C:\\Orca\\orca.cmd') },
wslRunner: async (distro, command) => {
if (
command.includes('head -c ') &&
command.includes('/home/alice/.local/share/orca/orca-wsl-bridge.ps1')
) {
if (command.includes('cat /home/alice/.local/share/orca/orca-wsl-bridge.ps1')) {
return `${_internals.buildWslBridgeScript()}\n`
}
return wsl.runner(distro, command)
@@ -831,6 +828,9 @@ describe('WslCliInstaller', () => {
distro: 'Ubuntu',
hostInstaller: { getStatus: async () => makeHostStatus('C:\\Orca\\orca.cmd') },
wslRunner: async (distro, command) => {
if (command.includes('cat /home/alice/.local/share/orca/orca-wsl-bridge.ps1')) {
return 'user bridge'
}
if (command.includes('rm -f')) {
throw new Error('__ORCA_CONFLICT__')
}
+3 -21
View File
@@ -24,8 +24,6 @@ const BRIDGE_MANAGED_MARKER = getWslBridgeMarker()
const WSL_COMMAND_NAME = 'orca-ide'
const LEGACY_WSL_COMMAND_NAME = 'orca'
const WSL_COMMAND_TIMEOUT_MS = 10_000
const WSL_BOUNDED_FILE_OUTPUT_PREFIX = '__ORCA_BOUNDED_FILE_BASE64__:'
export const WSL_CLI_INSPECTION_MAX_BYTES = 64 * 1024
function normalizeManagedScriptContent(content: string): string {
return content.replace(/\n+$/u, '\n')
@@ -385,7 +383,6 @@ export class WslCliInstaller {
const output = await this.run(
distro,
[
'set -o pipefail',
`if [ -L ${quoteShell(commandPath)} ]; then`,
' printf __ORCA_NOT_FILE__',
`elif [ ! -e ${quoteShell(commandPath)} ]; then`,
@@ -393,8 +390,7 @@ export class WslCliInstaller {
`elif [ ! -f ${quoteShell(commandPath)} ]; then`,
' printf __ORCA_NOT_FILE__',
'else',
` printf ${quoteShell(WSL_BOUNDED_FILE_OUTPUT_PREFIX)}`,
` head -c ${WSL_CLI_INSPECTION_MAX_BYTES + 1} -- ${quoteShell(commandPath)} | base64`,
` cat ${quoteShell(commandPath)}`,
'fi'
].join('\n')
)
@@ -404,7 +400,7 @@ export class WslCliInstaller {
if (output === '__ORCA_NOT_FILE__') {
return 'not_file'
}
return parseBoundedWslFileOutput(output)
return output
}
private buildStatus(args: {
@@ -510,24 +506,10 @@ function buildEncodedWslBashCommand(command: string): string {
return `set -o pipefail; printf %s ${quoteShell(encoded)} | base64 -d | bash`
}
function parseBoundedWslFileOutput(output: string): string | 'not_file' {
if (!output.startsWith(WSL_BOUNDED_FILE_OUTPUT_PREFIX)) {
return output
}
const encoded = output.slice(WSL_BOUNDED_FILE_OUTPUT_PREFIX.length).replace(/\s/gu, '')
if (!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u.test(encoded)) {
return 'not_file'
}
const decoded = Buffer.from(encoded, 'base64')
return decoded.length <= WSL_CLI_INSPECTION_MAX_BYTES ? decoded.toString('utf8') : 'not_file'
}
export const _internals = {
buildEncodedWslBashCommand,
buildWslBridgeScript,
buildWslLauncher,
getBridgePathFromCommandPath,
parseManagedLauncherTarget,
parseBoundedWslFileOutput,
WSL_BOUNDED_FILE_OUTPUT_PREFIX
parseManagedLauncherTarget
}
@@ -1,12 +1,11 @@
import { mkdir, mkdtemp, readFile, rm, truncate, writeFile } from 'node:fs/promises'
import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import {
getWslCliRegistrationCandidates,
recordWslCliRegistrationObservations,
recordWslCliRegistrationRemoved,
WSL_CLI_REGISTRY_MAX_BYTES
recordWslCliRegistrationRemoved
} from './wsl-cli-registration-registry'
describe('WSL CLI registration registry', () => {
@@ -145,16 +144,6 @@ describe('WSL CLI registration registry', () => {
).resolves.toEqual(['Ubuntu', 'Debian'])
})
it('rediscovers available distros without reading an oversized sparse registry', async () => {
const registryPath = join(userDataPath, 'wsl-cli-registrations.json')
await writeFile(registryPath, '{"schemaVersion":2}', 'utf8')
await truncate(registryPath, WSL_CLI_REGISTRY_MAX_BYTES + 1)
await expect(
getWslCliRegistrationCandidates(userDataPath, ['Ubuntu', 'Debian'])
).resolves.toEqual(['Ubuntu', 'Debian'])
})
it('stops reconciling a registration removed through Settings', async () => {
await recordWslCliRegistrationObservations(userDataPath, [
{ distro: 'Ubuntu', inspected: true, managed: true }
+2 -14
View File
@@ -1,9 +1,5 @@
import { mkdir } from 'node:fs/promises'
import { mkdir, readFile } from 'node:fs/promises'
import { join } from 'node:path'
import {
NodeFileReadTooLargeError,
readNodeFileWithinLimit
} from '../../shared/node-bounded-file-reader'
import { writeFileAtomically } from '../codex-accounts/fs-utils'
import { getKeyedSerializedQueueTail, runKeyedSerializedOperation } from './keyed-promise-queue'
import { normalizeWslDistroKey } from './wsl-cli-registration-operation'
@@ -11,7 +7,6 @@ import { normalizeWslDistroKey } from './wsl-cli-registration-operation'
const REGISTRY_FILE_NAME = 'wsl-cli-registrations.json'
const REGISTRY_SCHEMA_VERSION = 2
const DEFAULT_NEGATIVE_INSPECTION_TTL_MS = 7 * 24 * 60 * 60 * 1_000
export const WSL_CLI_REGISTRY_MAX_BYTES = 1024 * 1024
// Why: the registry is advisory; cap per-distro bookkeeping so hosts that
// cycle many uniquely named distros cannot grow the file without bound.
const MAX_INSPECTION_ENTRIES = 64
@@ -131,18 +126,11 @@ function getRegistryPath(userDataPath: string): string {
async function readState(userDataPath: string): Promise<WslCliRegistrationRegistryState> {
try {
const { buffer } = await readNodeFileWithinLimit(
getRegistryPath(userDataPath),
WSL_CLI_REGISTRY_MAX_BYTES
)
return parseState(buffer.toString('utf8'))
return parseState(await readFile(getRegistryPath(userDataPath), 'utf8'))
} catch (error) {
if (isMissingError(error)) {
return emptyState()
}
if (error instanceof NodeFileReadTooLargeError) {
return emptyState()
}
throw error
}
}