Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions src/patcher/binary-finder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ function getPlatformCandidates(): string[] {
return [
join(home, '.local', 'bin', 'claude'),
'/usr/local/bin/claude',
'/opt/claude-code/bin/claude',
'/usr/bin/claude',
join(home, '.npm-global', 'bin', 'claude'),
join(home, '.volta', 'bin', 'claude'),
Expand All @@ -79,6 +80,27 @@ function resolveWindowsShim(cmdPath: string): string | null {
return null;
}

export function resolveShellWrapper(scriptPath: string): string | null {
if (IS_WIN) return null;
try {
const content = readFileSync(scriptPath, 'utf-8');
if (!content.startsWith('#!')) return null;

const match = content.match(/^\s*exec\s+(\/\S+)/m);
if (!match) return null;

const target = match[1];
if (!existsSync(target)) return null;

const size = statSync(target).size;
if (size < 1_000_000) return null;

return target;
} catch {
return null;
}
}

function resolveFromPackageDir(resolvedPath: string): string | null {
try {
const ccPkg = join('@anthropic-ai', 'claude-code');
Expand Down Expand Up @@ -119,6 +141,9 @@ export function findClaudeBinary(): string {
if (size >= 1_000_000) {
return resolved;
}
const fromWrapper = resolveShellWrapper(resolved);
if (fromWrapper) return fromWrapper;

const fromPkg = resolveFromPackageDir(resolved);
if (fromPkg) return fromPkg;

Expand Down Expand Up @@ -161,6 +186,10 @@ export function findClaudeBinary(): string {
}

export function findBunBinary(): string {
if (process.env.ANYBUDDY_BUN_PATH && existsSync(process.env.ANYBUDDY_BUN_PATH)) {
return process.env.ANYBUDDY_BUN_PATH;
}

const onPath = which('bun');
if (onPath) return onPath;

Expand All @@ -169,6 +198,13 @@ export function findBunBinary(): string {
? [join(home, '.bun', 'bin', 'bun.exe'), join(home, '.volta', 'bin', 'bun.exe')]
: [join(home, '.bun', 'bin', 'bun'), '/usr/local/bin/bun', join(home, '.volta', 'bin', 'bun')];

// Under sudo, homedir() returns /root — also check the original user's home.
const sudoUser = process.env.SUDO_USER;
if (sudoUser && !IS_WIN) {
const sudoHome = IS_MAC ? join('/Users', sudoUser) : join('/home', sudoUser);
candidates.push(join(sudoHome, '.bun', 'bin', 'bun'), join(sudoHome, '.volta', 'bin', 'bun'));
}

for (const candidate of candidates) {
if (existsSync(candidate)) return realpath(candidate);
}
Expand Down
2 changes: 1 addition & 1 deletion src/patcher/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
export { findClaudeBinary, findBunBinary } from './binary-finder.ts';
export { findClaudeBinary, findBunBinary, resolveShellWrapper } from './binary-finder.ts';
export {
findAllOccurrences,
getCurrentSalt,
Expand Down
12 changes: 12 additions & 0 deletions src/patcher/patch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,11 @@ import {
unlinkSync,
renameSync,
existsSync,
accessSync,
constants,
} from 'fs';
import { execSync } from 'child_process';
import { dirname } from 'path';
import { platform } from 'os';
import type { PatchResult } from '@/types.js';
import { ORIGINAL_SALT } from '@/constants.js';
Expand Down Expand Up @@ -37,6 +40,15 @@ export function patchBinary(binaryPath: string, oldSalt: string, newSalt: string
);
}

try {
accessSync(dirname(binaryPath), constants.W_OK);
} catch {
throw new Error(
`No write permission on ${dirname(binaryPath)}.\n` +
' The binary is owned by root. Run with: sudo any-buddy',
);
}

const buf = readFileSync(binaryPath);
const offsets = findAllOccurrences(buf, oldSalt);

Expand Down
23 changes: 18 additions & 5 deletions src/patcher/preflight.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { statSync } from 'fs';
import { statSync, accessSync, constants } from 'fs';
import { execSync } from 'child_process';
import { dirname } from 'path';
import { platform } from 'os';
import chalk from 'chalk';
import type { PreflightResult } from '@/types.js';
Expand All @@ -15,10 +16,12 @@ export function runPreflight({ requireBinary = true } = {}): PreflightResult {

// 1. Check bun is installed (deferred — may not be needed for Node-based installs)
let bunVersion: string | null = null;
let bunPath: string | null = null;
let bunMissing = false;
try {
const bunPath = findBunBinary();
bunVersion = execSync(`"${bunPath}" --version`, { encoding: 'utf-8', timeout: 5000 }).trim();
const resolved = findBunBinary();
bunVersion = execSync(`"${resolved}" --version`, { encoding: 'utf-8', timeout: 5000 }).trim();
bunPath = resolved;
} catch {
bunMissing = true;
}
Expand Down Expand Up @@ -157,6 +160,16 @@ export function runPreflight({ requireBinary = true } = {}): PreflightResult {
);
}

// 4. Check write permission on binary directory
let needsSudo = false;
if (binaryPath) {
try {
accessSync(dirname(binaryPath), constants.W_OK);
} catch {
needsSudo = true;
}
}

for (const w of warnings) {
console.log(chalk.yellow(` Warning: ${w}\n`));
}
Expand All @@ -165,8 +178,8 @@ export function runPreflight({ requireBinary = true } = {}): PreflightResult {
for (const e of errors) {
console.log(chalk.red(` Error: ${e}\n`));
}
return { ok: false, binaryPath, userId, saltCount, bunVersion };
return { ok: false, binaryPath, userId, saltCount, bunVersion, bunPath, needsSudo };
}

return { ok: true, binaryPath, userId, saltCount, bunVersion };
return { ok: true, binaryPath, userId, saltCount, bunVersion, bunPath, needsSudo };
}
2 changes: 1 addition & 1 deletion src/patcher/salt-ops.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ export function isClaudeRunning(binaryPath: string): boolean {
return out.includes('claude.exe');
}
const name = basename(binaryPath);
const out = execSync(`pgrep -f "${name}" 2>/dev/null || true`, { encoding: 'utf-8' });
const out = execSync(`pgrep -x "${name}" 2>/dev/null || true`, { encoding: 'utf-8' });
return out.trim().length > 0;
} catch {
return false;
Expand Down
23 changes: 23 additions & 0 deletions src/patcher/sudo.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { execFileSync } from 'child_process';
import chalk from 'chalk';
import type { PreflightResult } from '@/types.js';

/** Re-exec the current CLI under sudo, forwarding resolved paths as env vars. */
export function execWithSudo(preflight: PreflightResult): never {
const args = process.argv.slice(1);
console.log(chalk.yellow(' Binary requires elevated permissions. Re-running with sudo...\n'));

const env: string[] = [`HOME=${process.env.HOME ?? ''}`];
if (preflight.bunPath) env.push(`ANYBUDDY_BUN_PATH=${preflight.bunPath}`);
if (preflight.binaryPath) env.push(`CLAUDE_BINARY=${preflight.binaryPath}`);

try {
execFileSync('sudo', ['env', ...env, process.execPath, ...args], {
stdio: 'inherit',
});
process.exit(0);
} catch {
console.error(chalk.red(' Sudo failed. Try: sudo any-buddy'));
process.exit(1);
}
}
12 changes: 10 additions & 2 deletions src/tui/apply/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -608,8 +608,16 @@ export async function runApplyTUI(

case 'confirm_patch':
if (key.name === 'return' || key.name === 'y') {
doPatch();
showStep('confirm_hook');
try {
doPatch();
showStep('confirm_hook');
} catch (err) {
clearStep();
addText(` Patch failed: ${(err as Error).message}`, '#ff5555');
helpBar.content = ' Enter to exit';
helpBar.fg = '#ff5555';
currentStep = 'done';
}
} else if (key.name === 'escape' || key.name === 'n') {
showStep('confirm_hook');
}
Expand Down
6 changes: 6 additions & 0 deletions src/tui/commands/buddies.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import chalk from 'chalk';

import { select } from '@inquirer/prompts';
import { ORIGINAL_SALT, RARITY_STARS } from '@/constants.js';
import { roll } from '@/generation/index.js';
import { DEFAULT_PERSONALITIES } from '@/personalities.js';
import { isNodeRuntime, verifySalt, isClaudeRunning, getMinSaltCount } from '@/patcher/salt-ops.js';
import { patchBinary } from '@/patcher/patch.js';
import { runPreflight } from '@/patcher/preflight.js';
import { execWithSudo } from '@/patcher/sudo.js';
import {
loadPetConfigV2,
savePetConfigV2,
Expand Down Expand Up @@ -51,6 +53,10 @@ export async function runBuddies(): Promise<void> {
process.exit(1);
}

if (preflight.needsSudo && process.getuid?.() !== 0) {
execWithSudo(preflight);
}

const config = loadPetConfigV2();
const profiles = config?.profiles ?? {};

Expand Down
6 changes: 6 additions & 0 deletions src/tui/commands/interactive.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import chalk from 'chalk';

import { confirm, input, select } from '@inquirer/prompts';
import type { CliFlags, DesiredTraits } from '@/types.js';
import { SPECIES, EYES, RARITIES, HATS, STAT_NAMES, ORIGINAL_SALT } from '@/constants.js';
Expand All @@ -13,6 +14,7 @@ import {
} from '@/patcher/salt-ops.js';
import { patchBinary } from '@/patcher/patch.js';
import { runPreflight } from '@/patcher/preflight.js';
import { execWithSudo } from '@/patcher/sudo.js';
import {
loadPetConfig,
loadPetConfigV2,
Expand Down Expand Up @@ -171,6 +173,10 @@ function runSetup(): SetupResult {
if (!preflight.ok || !preflight.binaryPath) {
process.exit(1);
}

if (preflight.needsSudo && process.getuid?.() !== 0) {
execWithSudo(preflight);
}
const userId = preflight.userId;
const binaryPath = preflight.binaryPath;
console.log(chalk.dim(` User ID: ${userId.slice(0, 12)}...`));
Expand Down
2 changes: 2 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,8 @@ export interface PreflightResult {
userId: string;
saltCount: number;
bunVersion: string | null;
bunPath: string | null;
needsSudo: boolean;
}

export interface PetConfig {
Expand Down
72 changes: 72 additions & 0 deletions tests/patcher/binary-finder.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import { describe, it, expect, afterAll } from 'vitest';
import { mkdtempSync, writeFileSync, rmSync } from 'fs';
import { join } from 'path';
import { tmpdir } from 'os';
import { resolveShellWrapper } from '@/patcher/binary-finder.js';

const tempDir = mkdtempSync(join(tmpdir(), 'anybuddy-binary-'));

afterAll(() => {
rmSync(tempDir, { recursive: true, force: true });
});

function createFakeBinary(name: string): string {
const path = join(tempDir, name);
writeFileSync(path, Buffer.alloc(1_100_000, 0x41));
return path;
}

function createScript(name: string, content: string): string {
const path = join(tempDir, name);
writeFileSync(path, content, 'utf-8');
return path;
}

describe('resolveShellWrapper', () => {
it('resolves exec /path/to/binary "$@" pattern', () => {
const binary = createFakeBinary('claude-real');
const script = createScript('claude-wrapper-1', `#!/bin/sh\nexec ${binary} "$@"\n`);
expect(resolveShellWrapper(script)).toBe(binary);

Check failure on line 29 in tests/patcher/binary-finder.test.ts

View workflow job for this annotation

GitHub Actions / Test (Node 20, windows-latest)

tests/patcher/binary-finder.test.ts > resolveShellWrapper > resolves exec /path/to/binary "$@" pattern

AssertionError: expected null to be 'C:\Users\RUNNER~1\AppData\Local\Temp\…' // Object.is equality - Expected: "C:\\Users\\RUNNER~1\\AppData\\Local\\Temp\\anybuddy-binary-e2eraO\\claude-real" + Received: null ❯ tests/patcher/binary-finder.test.ts:29:41

Check failure on line 29 in tests/patcher/binary-finder.test.ts

View workflow job for this annotation

GitHub Actions / Test (Node 22, windows-latest)

tests/patcher/binary-finder.test.ts > resolveShellWrapper > resolves exec /path/to/binary "$@" pattern

AssertionError: expected null to be 'C:\Users\RUNNER~1\AppData\Local\Temp\…' // Object.is equality - Expected: "C:\\Users\\RUNNER~1\\AppData\\Local\\Temp\\anybuddy-binary-fMnEwq\\claude-real" + Received: null ❯ tests/patcher/binary-finder.test.ts:29:41
});

it('resolves exec /path/to/binary without args', () => {
const binary = createFakeBinary('claude-no-args');
const script = createScript('claude-wrapper-2', `#!/bin/sh\nexec ${binary}\n`);
expect(resolveShellWrapper(script)).toBe(binary);

Check failure on line 35 in tests/patcher/binary-finder.test.ts

View workflow job for this annotation

GitHub Actions / Test (Node 20, windows-latest)

tests/patcher/binary-finder.test.ts > resolveShellWrapper > resolves exec /path/to/binary without args

AssertionError: expected null to be 'C:\Users\RUNNER~1\AppData\Local\Temp\…' // Object.is equality - Expected: "C:\\Users\\RUNNER~1\\AppData\\Local\\Temp\\anybuddy-binary-e2eraO\\claude-no-args" + Received: null ❯ tests/patcher/binary-finder.test.ts:35:41

Check failure on line 35 in tests/patcher/binary-finder.test.ts

View workflow job for this annotation

GitHub Actions / Test (Node 22, windows-latest)

tests/patcher/binary-finder.test.ts > resolveShellWrapper > resolves exec /path/to/binary without args

AssertionError: expected null to be 'C:\Users\RUNNER~1\AppData\Local\Temp\…' // Object.is equality - Expected: "C:\\Users\\RUNNER~1\\AppData\\Local\\Temp\\anybuddy-binary-fMnEwq\\claude-no-args" + Received: null ❯ tests/patcher/binary-finder.test.ts:35:41
});

it('resolves with env exports before exec', () => {
const binary = createFakeBinary('claude-env');
const script = createScript(
'claude-wrapper-3',
`#!/bin/sh\nexport DISABLE_AUTOUPDATER=1\nexec ${binary} "$@"\n`,
);
expect(resolveShellWrapper(script)).toBe(binary);

Check failure on line 44 in tests/patcher/binary-finder.test.ts

View workflow job for this annotation

GitHub Actions / Test (Node 20, windows-latest)

tests/patcher/binary-finder.test.ts > resolveShellWrapper > resolves with env exports before exec

AssertionError: expected null to be 'C:\Users\RUNNER~1\AppData\Local\Temp\…' // Object.is equality - Expected: "C:\\Users\\RUNNER~1\\AppData\\Local\\Temp\\anybuddy-binary-e2eraO\\claude-env" + Received: null ❯ tests/patcher/binary-finder.test.ts:44:41

Check failure on line 44 in tests/patcher/binary-finder.test.ts

View workflow job for this annotation

GitHub Actions / Test (Node 22, windows-latest)

tests/patcher/binary-finder.test.ts > resolveShellWrapper > resolves with env exports before exec

AssertionError: expected null to be 'C:\Users\RUNNER~1\AppData\Local\Temp\…' // Object.is equality - Expected: "C:\\Users\\RUNNER~1\\AppData\\Local\\Temp\\anybuddy-binary-fMnEwq\\claude-env" + Received: null ❯ tests/patcher/binary-finder.test.ts:44:41
});

it('returns null for files without shebang', () => {
const binary = createFakeBinary('claude-noshebang');
const script = createScript('no-shebang', `exec ${binary} "$@"\n`);
expect(resolveShellWrapper(script)).toBeNull();
});

it('returns null when exec target does not exist', () => {
const script = createScript(
'claude-missing',
'#!/bin/sh\nexec /nonexistent/path/to/claude "$@"\n',
);
expect(resolveShellWrapper(script)).toBeNull();
});

it('returns null when exec target is too small', () => {
const tinyFile = join(tempDir, 'claude-tiny');
writeFileSync(tinyFile, 'not a real binary');
const script = createScript('claude-wrapper-tiny', `#!/bin/sh\nexec ${tinyFile} "$@"\n`);
expect(resolveShellWrapper(script)).toBeNull();
});

it('returns null for scripts without exec', () => {
const script = createScript('claude-no-exec', '#!/bin/sh\necho "hello"\n');
expect(resolveShellWrapper(script)).toBeNull();
});
});
Loading