Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

πŸ› fix(sandbox): authenticate lh reached through timeout, child shells and subprocesses (#20064)

Arvin Xu7cfe49881aa8
diff --git a/apps/server/src/services/toolExecution/__tests__/preprocessLhCommand.test.ts b/apps/server/src/services/toolExecution/__tests__/preprocessLhCommand.test.ts
index 6d16f2d8797..06eb917bde3 100644
--- a/apps/server/src/services/toolExecution/__tests__/preprocessLhCommand.test.ts
+++ b/apps/server/src/services/toolExecution/__tests__/preprocessLhCommand.test.ts
@@ -1,6 +1,16 @@
-import { describe, expect, it, vi } from 'vitest';
+import { execFileSync } from 'node:child_process';
+import { chmodSync, existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
-import { buildDeviceLhEnv, isLhCommand, preprocessLhCommand } from '../preprocessLhCommand';
+import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
+
+import {
+ buildDeviceLhEnv,
+ isDirectLhInvocation,
+ isLhCommand,
+ preprocessLhCommand,
+} from '../preprocessLhCommand';
const mockSignUserJWT = vi.hoisted(() => vi.fn().mockResolvedValue('mock-jwt-token'));
@@ -17,8 +27,22 @@ vi.mock('@/utils/env', () => ({
}));
const CREDS = "LOBEHUB_JWT='mock-jwt-token' LOBEHUB_SERVER='https://app.lobehub.com'";
-/** The shim, with credentials scoped to the `npx` process rather than exported. */
-const shim = (extraEnv = '') => `lh() { ${CREDS}${extraEnv} npx -y @lobehub/cli "$@"; }`;
+/**
+ * The shim: an `lh` executable written to a fresh `PATH` directory, with
+ * credentials scoped to the `npx` process it execs rather than exported.
+ */
+const wrap = (command: string, extraEnv = '') =>
+ [
+ `__lobehub_lh_bin=$(mktemp -d) && trap '[ -s "$__lobehub_lh_bin"/.jobs ] || rm -rf "$__lobehub_lh_bin"' EXIT && trap 'exit 129' HUP && trap 'exit 130' INT && trap 'exit 143' TERM && cat > "$__lobehub_lh_bin"/lh <<'__LOBEHUB_LH_SHIM__' && chmod 700 "$__lobehub_lh_bin"/lh && export PATH="$__lobehub_lh_bin":"$PATH" || { echo 'lh: could not set up LobeHub CLI credentials' >&2; exit 1; }`,
+ '#!/bin/sh',
+ `${CREDS}${extraEnv} exec npx -y @lobehub/cli "$@"`,
+ '__LOBEHUB_LH_SHIM__',
+ '(',
+ `trap 'jobs -l > "$__lobehub_lh_bin"/.jobs; sed -n "s/^[[][0-9]*[]][ +-]*//; s/^ *\\([0-9][0-9]*\\).*/\\1/p" "$__lobehub_lh_bin"/.jobs > "$__lobehub_lh_bin"/.pids; mv "$__lobehub_lh_bin"/.pids "$__lobehub_lh_bin"/.jobs; if [ -s "$__lobehub_lh_bin"/.jobs ]; then (n=0; while read -r p; do while [ "$n" -lt 300 ] && kill -0 "$p" 2>/dev/null; do case "$(cat /proc/"$p"/stat 2>/dev/null)" in *") Z "*) break ;; esac; sleep 1; n=$((n + 1)); done; done < "$__lobehub_lh_bin"/.jobs; rm -rf "$__lobehub_lh_bin") >/dev/null 2>&1 </dev/null & fi' EXIT`,
+ 'lh() { "$__lobehub_lh_bin"/lh "$@"; }',
+ command,
+ ')',
+ ].join('\n');
describe('preprocessLhCommand', () => {
it('should return unchanged command for non-lh commands', async () => {
@@ -34,14 +58,14 @@ describe('preprocessLhCommand', () => {
expect(result.isLhCommand).toBe(true);
expect(result.skipSkillLookup).toBe(true);
- expect(result.command).toBe(`${shim()}\nlh topic list --json`);
+ expect(result.command).toBe(wrap('lh topic list --json'));
});
it('should inject workspace scope for lh commands from workspace runs', async () => {
const result = await preprocessLhCommand('lh agent view agt_123', 'user-1', 'workspace-1');
expect(result.command).toBe(
- `${shim(" LOBEHUB_WORKSPACE_ID='workspace-1'")}\nlh agent view agt_123`,
+ wrap('lh agent view agt_123', " LOBEHUB_WORKSPACE_ID='workspace-1'"),
);
});
@@ -49,7 +73,7 @@ describe('preprocessLhCommand', () => {
const cmd = 'lh topic list --page 1 && lh topic list --page 2 && echo "done"';
const result = await preprocessLhCommand(cmd, 'user-1');
- expect(result.command).toBe(`${shim()}\n${cmd}`);
+ expect(result.command).toBe(wrap(cmd));
expect(result.command.match(/mock-jwt-token/g)).toHaveLength(1);
});
@@ -58,17 +82,20 @@ describe('preprocessLhCommand', () => {
// `echo $LOBEHUB_JWT` or `curl` away from exfiltration, and handed out even
// to a script that merely mentions `lh` in quoted text, since detection is
// deliberately permissive. Credentials must stay assignment-prefixed to the
- // `npx` process inside the function body.
+ // `npx` process inside the `lh` wrapper.
it('should keep credentials out of the parent shell environment', async () => {
const result = await preprocessLhCommand('lh topic list && echo "$LOBEHUB_JWT"', 'user-1');
- expect(result.command).not.toContain('export ');
+ // Only `PATH` is exported, never a credential.
+ expect(result.command.match(/export /g)).toHaveLength(1);
+ expect(result.command).toContain('export PATH=');
- const [shimLine] = result.command.split('\n');
- // The only occurrence of the token is inside the function body, prefixed to
+ const lines = result.command.split('\n');
+ // The only occurrence of the token is inside the wrapper body, prefixed to
// `npx` β€” so it scopes to that one process and nothing else inherits it.
- expect(shimLine).toMatch(/^lh\(\) \{ .*LOBEHUB_JWT='mock-jwt-token'.* npx -y @lobehub\/cli/);
- expect(result.command.slice(shimLine.length)).not.toContain('mock-jwt-token');
+ const tokenLines = lines.filter((line) => line.includes('mock-jwt-token'));
+ expect(tokenLines).toHaveLength(1);
+ expect(tokenLines[0]).toMatch(/^LOBEHUB_JWT='mock-jwt-token'.* exec npx -y @lobehub\/cli/);
});
it('should shell-escape values containing quotes', async () => {
@@ -105,6 +132,19 @@ describe('preprocessLhCommand', () => {
expect(mockSignUserJWT).not.toHaveBeenCalled();
});
+ // Regression: the permissive shim detector also drove the visitor refusal,
+ // so a harmless command that merely mentions `lh` was rejected outright.
+ it('should run a visitor command that only mentions lh unchanged, without signing', async () => {
+ mockSignUserJWT.mockClear();
+
+ const command = "echo 'the lh CLI is unavailable here'";
+ const result = await preprocessLhCommand(command, 'user-1', undefined, true);
+
+ expect(result.error).toBeUndefined();
+ expect(result.command).toBe(command);
+ expect(mockSignUserJWT).not.toHaveBeenCalled();
+ });
+
it('should leave a non-lh command untouched even when shareVisitorBlocked is set', async () => {
const result = await preprocessLhCommand('echo hello', 'user-1', undefined, true);
@@ -114,6 +154,172 @@ describe('preprocessLhCommand', () => {
});
});
+/**
+ * Runs the prepared command in a real POSIX shell, the way the sandbox does.
+ * The fake bin dir mirrors the sandbox: a global `lh` with no credentials
+ * (what the model hit before) and an `npx` that reports the credentials the
+ * CLI process actually received.
+ */
+describe('preprocessLhCommand in a real shell', () => {
+ let fakeBin: string;
+
+ beforeAll(() => {
+ fakeBin = mkdtempSync(path.join(tmpdir(), 'lh-shim-test-'));
+ const writeBin = (name: string, body: string) => {
+ const file = path.join(fakeBin, name);
+ writeFileSync(file, `#!/bin/sh\n${body}\n`);
+ chmodSync(file, 0o755);
+ };
+ writeBin('lh', `echo "No authentication found. Run 'lh login' first."`);
+ writeBin('npx', 'echo "cli jwt=${LOBEHUB_JWT:-none}"');
+ });
+
+ afterAll(() => {
+ rmSync(fakeBin, { force: true, recursive: true });
+ });
+
+ const run = async (command: string, shell = '/bin/sh') => {
+ const { command: prepared } = await preprocessLhCommand(command, 'user-1');
+ return execFileSync(shell, ['-c', prepared], {
+ encoding: 'utf8',
+ // An inherited token would mask a shim that failed to reach the CLI.
+ env: { ...process.env, LOBEHUB_JWT: undefined, PATH: `${fakeBin}:${process.env.PATH}` },
+ });
+ };
+
+ it('authenticates an lh the shell resolves itself', async () => {
+ expect(await run('lh whoami')).toBe('cli jwt=mock-jwt-token\n');
+ });
+
+ // Regression: the shim was a shell function, which only exists inside the
+ // shell that defined it. Any `lh` executed as a program β€” a child shell, an
+ // `env` / `timeout` / `xargs` prefix, a script's subprocess β€” skipped it and
+ // ran the unauthenticated global `lh` instead.
+ it.each([
+ ['a child shell', "sh -c 'lh whoami'"],
+ ['an env prefix', 'env FOO=1 lh whoami'],
+ ['xargs', 'echo whoami | xargs lh'],
+ [
+ 'a node subprocess',
+ `node -e "process.stdout.write(require('child_process').execFileSync('lh', ['whoami']))"`,
+ ],
+ ])('authenticates an lh reached through %s', async (_label, command) => {
+ expect(await run(command)).toBe('cli jwt=mock-jwt-token\n');
+ });
+
+ // Regression: an inline `PATH=` assignment replaces the lookup path for that
+ // one `lh`, skipping the exported wrapper directory.
+ it('authenticates an lh whose inline PATH assignment puts another lh first', async () => {
+ expect(await run(`PATH=${fakeBin}:"$PATH" lh whoami`)).toBe('cli jwt=mock-jwt-token\n');
+ });
+
+ // Regression: the sandbox session outlives the command, so a wrapper left on
+ // disk kept a live user token readable by every later command in the topic.
+ it('removes the credentialed wrapper once the command ends', async () => {
+ const dir = await run('lh whoami >/dev/null; printf %s "$__lobehub_lh_bin"');
+
+ expect(dir).not.toBe('');
+ expect(existsSync(dir)).toBe(false);
+ });
+
+ it('removes it even when the command traps EXIT itself and exits non-zero', async () => {
+ const error = await run(
+ `lh whoami >/dev/null; trap 'echo bye' EXIT; printf '%s\\n' "$__lobehub_lh_bin"; exit 3`,
+ ).catch((error_: { status: number; stdout: string }) => error_);
+
+ expect(error).toMatchObject({ status: 3 });
+ const [dir] = (error as { stdout: string }).stdout.split('\n');
+ expect(dir).not.toBe('');
+ expect(existsSync(dir)).toBe(false);
+ });
+
+ // Regression: removing the wrapper on exit raced a backgrounded `lh`, which
+ // then ran the unauthenticated global `lh` (or failed to open the wrapper).
+ it('keeps the wrapper for an lh started in the background after the script ends', async () => {
+ const out = path.join(fakeBin, 'background.out');
+ await run(`(sleep 1; lh whoami > '${out}') &`);
+
+ expect(readFileSync(out, 'utf8')).toBe('cli jwt=mock-jwt-token\n');
+ });
+
+ // Regression: `jobs -p` lists one pid per job, so a background pipeline whose
+ // first member exits early lost the wrapper under a later member's `lh`.
+ // bash and dash format `jobs -l` differently; cover whichever are installed.
+ it.each(['/bin/sh', '/bin/bash', '/bin/dash'].filter((shell) => existsSync(shell)))(
+ 'keeps the wrapper for every member of a background pipeline in %s',
+ async (shell) => {
+ const out = path.join(fakeBin, `pipeline-${path.basename(shell)}.out`);
+ await run(`printf x | { sleep 1; lh whoami > '${out}'; } &`, shell);
+
+ expect(readFileSync(out, 'utf8')).toBe('cli jwt=mock-jwt-token\n');
+ },
+ );
+
+ // Regression: the job hand-off ran after the command, so an `exit` or a
+ // `set -e` failure skipped it and the wrapper was removed under the job.
+ it.each([
+ ['an explicit exit', 'exit 0'],
+ ['a set -e failure', 'set -e; false'],
+ ])('keeps the wrapper for a background lh after %s', async (_label, ending) => {
+ const out = path.join(fakeBin, `after-exit-${ending.length}.out`);
+ await run(`(sleep 1; lh whoami > '${out}') & ${ending}`).catch(() => undefined);
+
+ expect(readFileSync(out, 'utf8')).toBe('cli jwt=mock-jwt-token\n');
+ });
+
+ // Regression: joining every background job blocked the command on an
+ // unrelated long-lived process such as a dev server.
+ it('returns without waiting for a long-running background job, then removes the wrapper', async () => {
+ const startedAt = Date.now();
+ const dir = await run(
+ `lh whoami >/dev/null; sleep 3 >/dev/null 2>&1 & printf %s "$__lobehub_lh_bin"`,
+ );
+
+ expect(Date.now() - startedAt).toBeLessThan(2000);
+ expect(existsSync(`${dir}/lh`)).toBe(true);
+
+ await vi.waitFor(() => expect(existsSync(dir)).toBe(false), { interval: 200, timeout: 6000 });
+ });
+
+ // Regression: a failed setup fell through to the command, whose `lh` then ran
+ // the unauthenticated global binary.
+ it('stops before the command when the wrapper cannot be written', async () => {
+ const failBin = mkdtempSync(path.join(tmpdir(), 'lh-shim-fail-'));
+ writeFileSync(path.join(failBin, 'mktemp'), '#!/bin/sh\nexit 1\n');
+ chmodSync(path.join(failBin, 'mktemp'), 0o755);
+ const { command: prepared } = await preprocessLhCommand('echo ran; lh whoami', 'user-1');
+
+ let error: { status: number; stderr: string; stdout: string } | undefined;
+ try {
+ execFileSync('/bin/sh', ['-c', prepared], {
+ encoding: 'utf8',
+ env: {
+ ...process.env,
+ LOBEHUB_JWT: undefined,
+ PATH: `${failBin}:${fakeBin}:${process.env.PATH}`,
+ },
+ stdio: 'pipe',
+ });
+ } catch (error_) {
+ error = error_ as typeof error;
+ } finally {
+ rmSync(failBin, { force: true, recursive: true });
+ }
+
+ expect(error).toMatchObject({ status: 1 });
+ expect(error!.stderr).toContain('could not set up LobeHub CLI credentials');
+ expect(error!.stdout).not.toContain('ran');
+ });
+
+ it('keeps the token out of the script environment', async () => {
+ expect(
+ await run(
+ 'lh whoami >/dev/null; echo "shell jwt=${LOBEHUB_JWT:-none}"; env | grep -c LOBEHUB_JWT || true',
+ ),
+ ).toBe('shell jwt=none\n0\n');
+ });
+});
+
describe('isLhCommand', () => {
// Every form below used to fall through the old
// `/(?:^|&&|\|\||;)\s*lh(?:\s|$)/` pattern, leaving `lh` unresolved in the
@@ -147,6 +353,18 @@ describe('isLhCommand', () => {
['timed', 'time lh agent list'],
['negated and timed', '! time lh agent list'],
['negated with inline assignment', '! FOO=1 lh agent list'],
+ // Regression: `lh` reached through another program used to go undetected
+ // (or get a shell-function shim the child process could not see), so it
+ // ran the sandbox's own unauthenticated `lh` β€” "No authentication found"
+ // mid-session, which agents reported as the injected JWT vanishing.
+ ['timeout wrapper', 'echo start; timeout 120 lh doctor --json'],
+ ['loop body behind timeout', 'for i in 1 2 3; do timeout 30 lh doctor --json; done'],
+ ['child shell', "bash -c 'set -e; lh skill view skl_1 --json | jq -r .content'"],
+ ['env prefix', 'env FOO=1 lh agent list'],
+ ['nohup', 'nohup lh agent list &'],
+ ['xargs', 'echo agt_1 | xargs lh agent view'],
+ ['python subprocess', `python3 -c "import subprocess; subprocess.run(['lh', 'whoami'])"`],
+ ['node child process', "node -e \"require('child_process').execFileSync('lh', ['whoami'])\""],
])('detects %s', (_label, command) => {
expect(isLhCommand(command)).toBe(true);
});
@@ -157,13 +375,36 @@ describe('isLhCommand', () => {
['npm script name', 'npm run lhtest'],
['a local script of the same name', './lh agent list'],
['a path segment', 'ls /opt/lh'],
- // `time` is matched as a whole word only.
- ['a word merely ending in time', 'notime lh'],
+ ['a filename', 'cat lh.js'],
+ ['a hyphenated script name', 'npm run lh-sync'],
+ ['a home-relative path', '~/lh whoami'],
])('does not detect %s', (_label, command) => {
expect(isLhCommand(command)).toBe(false);
});
});
+describe('isDirectLhInvocation', () => {
+ it.each([
+ ['bare', 'lh agent list'],
+ ['after &&', 'cd /tmp && lh agent view agt_1'],
+ ['second line of a script', 'echo hi\nlh whoami'],
+ ['negated if condition', 'if ! lh whoami; then echo no; fi'],
+ ])('detects %s', (_label, command) => {
+ expect(isDirectLhInvocation(command)).toBe(true);
+ });
+
+ // These only mention `lh` (or reach it through another program), so a
+ // visitor refusal keyed on them would block harmless commands.
+ it.each([
+ ['quoted prose', "echo 'the lh CLI is unavailable here'"],
+ ['a comment', '# lh is not available\nls'],
+ ['a timeout wrapper', 'timeout 60 lh whoami'],
+ ])('does not detect %s', (_label, command) => {
+ expect(isLhCommand(command)).toBe(true);
+ expect(isDirectLhInvocation(command)).toBe(false);
+ });
+});
+
describe('buildDeviceLhEnv', () => {
it('scopes the run to its workspace', () => {
expect(buildDeviceLhEnv('ws-1')).toEqual({ LOBEHUB_WORKSPACE_ID: 'ws-1' });
@@ -182,7 +423,7 @@ describe('buildDeviceLhEnv', () => {
// device credentials' personal tenancy. The device merges env into the
// spawned process, so setting it unconditionally is what covers these.
it('scopes commands that reach lh indirectly, which no detector could match', () => {
- for (const command of ["bash -lc 'lh whoami'", 'make deploy', './sync.sh', 'npm run sync']) {
+ for (const command of ['make deploy', './sync.sh', 'npm run sync']) {
expect(isLhCommand(command)).toBe(false);
expect(buildDeviceLhEnv('ws-1')).toEqual({ LOBEHUB_WORKSPACE_ID: 'ws-1' });
}
diff --git a/apps/server/src/services/toolExecution/preprocessLhCommand.ts b/apps/server/src/services/toolExecution/preprocessLhCommand.ts
index 6ea87e739a3..35601f4b9a3 100644
--- a/apps/server/src/services/toolExecution/preprocessLhCommand.ts
+++ b/apps/server/src/services/toolExecution/preprocessLhCommand.ts
@@ -19,37 +19,42 @@ export interface PreprocessResult {
}
/**
- * `lh` in shell **command position**. Matches at the start of the script or
- * right after a separator / opening construct, allowing inline `VAR=value`
- * assignments in between (`FOO=1 lh agent list`).
+ * `lh` as a standalone word anywhere in the command β€” not a path segment
+ * (`./lh`, `/opt/lh`), a filename (`lh.js`) or part of a longer word
+ * (`lhtest`).
*
- * Command-position openers covered: newline, `;`, `&` (also the second `&` of
- * `&&`), `|` (also `||`), `(` (also the `(` of `$(`), `)` (a `case` arm), a
- * backtick, `{`, and the compound-command keywords. That set is what makes
- * multi-line scripts, pipelines, command substitution, subshells, loops and
- * `case` statements resolve β€” the previous pattern only knew `^`, `&&`, `||`
- * and `;` on a single line, so everything after the first line of a `view` β†’
- * `edit` script fell through unhandled.
+ * This used to require **shell command position**, which only covers an `lh`
+ * the invoking shell resolves itself. Models just as often reach it through
+ * another process β€” `timeout 60 lh …`, `bash -c '… lh …'`, `xargs lh`,
+ * `subprocess.run(["lh", …])`, `execFileSync('lh', …)` β€” and every one of those
+ * got no credentials, fell through to the sandbox's own unauthenticated `lh`
+ * install, and failed with "No authentication found" mid-session.
*
- * Between the opener and `lh` the pattern also allows the `!` and `time`
- * prefixes (`if ! lh whoami; then …`, `time lh agent list`) and inline
- * `VAR=value` assignments. `!` and `time` are the only command prefixes worth
- * matching: they are shell reserved words, so the shell still resolves `lh`
- * through the injected function. Prefixes that fork an external command β€”
- * `env`, `nohup`, `xargs`, and POSIX `command` / `exec`, which bypass function
- * lookup by definition β€” could never see a shell function anyway, so matching
- * them would inject a shim that cannot help.
+ * This decides whether to inject the shim, never whether to refuse a command:
+ * a false positive costs one unused shim while a false negative costs a broken
+ * `lh` invocation, so erring permissive is the right trade β€” e.g.
+ * `echo 'use lh'` matches even though the `lh` is quoted text. Refusals use
+ * the stricter {@link isDirectLhInvocation}.
+ */
+const LH_COMMAND_PATTERN = /(?<![\w./~-])lh(?![\w./-])/;
+
+export const isLhCommand = (command: string): boolean => LH_COMMAND_PATTERN.test(command);
+
+/**
+ * `lh` in shell **command position**: at the start of the script or right after
+ * a separator / opening construct (newline, `;`, `&`, `|`, `(`, `)`, backtick,
+ * `{`, compound-command keywords), optionally behind `!` / `time` and inline
+ * `VAR=value` assignments.
*
- * This is a DETECTION-only heuristic: the command itself is never rewritten
- * (see `preprocessLhCommand`), so a false positive costs one harmless shim
- * while a false negative costs a broken `lh` invocation. Erring permissive is
- * therefore the right trade β€” e.g. `echo 'a && lh b'` matches even though the
- * `lh` is quoted text.
+ * Used where a match REFUSES the command (share-visitor runs), so it must not
+ * fire on text that merely mentions `lh` β€” a harmless `echo 'use lh'` would be
+ * rejected outright by {@link isLhCommand}.
*/
-const LH_COMMAND_PATTERN =
+const LH_DIRECT_INVOCATION_PATTERN =
/(?:^|[\n;&|()`{]|\b(?:do|then|else|if|elif|while|until)\b)[\t ]*(?:(?:!|\btime)[\t ]+)*(?:[A-Za-z_]\w*=(?:'[^']*'|"[^"]*"|[^\s'"&;|]*)[\t ]+)*lh(?=[\s;&|)]|$)/;
-export const isLhCommand = (command: string): boolean => LH_COMMAND_PATTERN.test(command);
+export const isDirectLhInvocation = (command: string): boolean =>
+ LH_DIRECT_INVOCATION_PATTERN.test(command);
/**
* Env overrides for a workspace run executing ON THE USER'S DEVICE rather than
@@ -81,6 +86,45 @@ export const buildDeviceLhEnv = (
): Record<string, string> | undefined =>
workspaceId ? { LOBEHUB_WORKSPACE_ID: workspaceId } : undefined;
+/** Shell variable holding the per-command directory the `lh` wrapper is written to. */
+const LH_SHIM_DIR_VAR = '__lobehub_lh_bin';
+const LH_SHIM_EOF = '__LOBEHUB_LH_SHIM__';
+
+/**
+ * Longest the watcher keeps the wrapper for background jobs: the lifetime of
+ * the token it carries (`signUserJWT`'s default), after which it is inert.
+ */
+const LH_WRAPPER_MAX_SECONDS = 5 * 60;
+
+/**
+ * Detached watcher: removes the wrapper once every listed job has exited, or
+ * after {@link LH_WRAPPER_MAX_SECONDS}. A finished job counts as exited even
+ * while it lingers as a zombie β€” the Market sandbox's PID 1 (a Python server)
+ * never reaps orphans, so `kill -0` alone would keep the watcher, and with it
+ * the `runCommand`, alive forever.
+ */
+const lhWrapperWatcher = (dir: string) =>
+ `(n=0; while read -r p; do ` +
+ `while [ "$n" -lt ${LH_WRAPPER_MAX_SECONDS} ] && kill -0 "$p" 2>/dev/null; do ` +
+ `case "$(cat /proc/"$p"/stat 2>/dev/null)" in *") Z "*) break ;; esac; ` +
+ `sleep 1; n=$((n + 1)); done; done < ${dir}/.jobs; rm -rf ${dir}) >/dev/null 2>&1 </dev/null &`;
+
+/**
+ * Writes every pid of every job the shell still tracks to `<dir>/.jobs`, one
+ * per line. `jobs -p` lists only one pid per job, so a background pipeline
+ * whose first member exits early (`printf x | { sleep 1; lh …; } &`) would lose
+ * the wrapper under a later member. `jobs -l` lists each pipeline member on its
+ * own line in both bash (`[1]+ 123 Running …` / ` 124 Running …`) and dash
+ * (`[1] + 123 …` / ` 124`); the job marker is stripped and the leading pid
+ * kept. `jobs` goes through a file rather than a pipe because dash forgets its
+ * jobs in a pipeline subshell. Runs inside a single-quoted `trap`, so it must
+ * not contain single quotes.
+ */
+const recordJobPids = (dir: string) =>
+ `jobs -l > ${dir}/.jobs; ` +
+ String.raw`sed -n "s/^[[][0-9]*[]][ +-]*//; s/^ *\([0-9][0-9]*\).*/\1/p" ` +
+ `${dir}/.jobs > ${dir}/.pids; mv ${dir}/.pids ${dir}/.jobs`;
+
/** POSIX single-quoting, safe for any value including quotes and newlines. */
const shellSingleQuote = (value: string): string => `'${value.replaceAll("'", String.raw`'\''`)}'`;
@@ -89,27 +133,44 @@ const shellSingleQuote = (value: string): string => `'${value.replaceAll("'", St
*
* Instead of rewriting every `lh` occurrence (which can only ever cover the
* shell forms the regex happens to know), the command is left **byte-identical**
- * and a one-line shim is prepended:
+ * and a prelude writes an `lh` executable into a fresh directory at the front
+ * of `PATH`:
*
* ```sh
- * lh() { LOBEHUB_JWT='…' LOBEHUB_SERVER='…' LOBEHUB_WORKSPACE_ID='…' npx -y @lobehub/cli "$@"; }
+ * __lobehub_lh_bin=$(mktemp -d) && trap 'rm -rf …' EXIT && … && cat > …/lh <<'…' && chmod 700 … && export PATH=…
+ * #!/bin/sh
+ * LOBEHUB_JWT='…' LOBEHUB_SERVER='…' LOBEHUB_WORKSPACE_ID='…' exec npx -y @lobehub/cli "$@"
+ * …
+ * (
* <original command>
+ * )
* ```
*
- * A POSIX shell function is visible to subshells and command substitution, so
- * this resolves `lh` in every form the model can write β€” pipelines, `$(lh …)`,
- * `for … do lh …`, and every line of a multi-line script β€” while emitting the
- * JWT exactly once instead of per occurrence.
+ * It has to be an executable on `PATH`, not a shell function: a function only
+ * exists inside the shell that defined it, so `timeout 60 lh …`, `bash -c 'lh …'`,
+ * `xargs lh` or a Python/Node subprocess β€” all of which exec `lh` as a program β€”
+ * never saw it and ran the sandbox's own unauthenticated `lh` instead. `PATH`
+ * is inherited by every descendant, so each of those forms resolves the same
+ * credentialed wrapper, while the JWT is still emitted exactly once.
*
- * The credentials are assignment-prefixed to `npx` INSIDE the function rather
+ * The credentials are assignment-prefixed to `npx` INSIDE the wrapper rather
* than `export`ed around the script. Exporting would put a full user auth token
* in the environment of every command the model wrote, where any later `env`,
- * `echo $LOBEHUB_JWT`, `curl` or child process could read and exfiltrate it β€”
- * and since detection is deliberately permissive, a script that merely mentions
- * `lh` in quoted text would get one too. Prefixing an external command is
- * well-defined POSIX and scopes the value to that one `npx` process. Nothing is
- * lost: the shim is a shell function, so it was never visible to a child shell
- * process (`sh -c 'lh …'`) that an exported variable would have reached.
+ * `echo $LOBEHUB_JWT`, `curl` or child process could read it. Only `PATH` is
+ * exported; the token stays scoped to the `npx` process the wrapper execs.
+ *
+ * The sandbox session outlives the command, so the wrapper must not: the EXIT
+ * trap deletes it once the script ends, and the command runs in a subshell so
+ * its own `trap` or `exit` cannot skip that cleanup. A later command in the
+ * same sandbox finds no token on disk. Jobs the command left in the background
+ * (`nohup lh … &`, `(sleep 5; lh …) &`) may exec `lh` after the script ends, so
+ * when there are any, a detached watcher removes the wrapper only once they
+ * have all exited β€” without making the command itself wait for them. A job
+ * detached further (`( lh … & )`, `disown`), or left behind by a command that
+ * `exec`s another program (which replaces the subshell and skips its EXIT
+ * trap; `exec` is a special builtin a function cannot intercept), is not
+ * tracked and may lose the race. If the wrapper cannot be written, the script
+ * exits before the command runs rather than letting `lh` fall through to an unauthenticated one.
*
* `LOBEHUB_WORKSPACE_ID` is what keeps a workspace run's CLI calls in the
* workspace: without it the CLI resolves to personal scope and a workspace
@@ -137,6 +198,13 @@ export const preprocessLhCommand = async (
}
if (shareVisitorBlocked) {
+ // Never mint for a visitor. Only refuse an actual `lh` invocation: a
+ // command that merely mentions `lh` runs unchanged, and any `lh` it reaches
+ // indirectly just meets the sandbox's own unauthenticated install.
+ if (!isDirectLhInvocation(command)) {
+ return { command, isLhCommand: false, skipSkillLookup: false };
+ }
+
log('Refused lh command for Agent Share visitor run (user %s)', userId);
return {
command,
@@ -157,11 +225,46 @@ export const preprocessLhCommand = async (
...(workspaceId ? [`LOBEHUB_WORKSPACE_ID=${shellSingleQuote(workspaceId)}`] : []),
].join(' ');
+ const dir = `"$${LH_SHIM_DIR_VAR}"`;
// Newline-separated (not `;`-separated) so a command whose first line is a
- // comment or a shebang cannot swallow the shim.
- const finalCommand = [`lh() { ${envAssignments} npx -y @lobehub/cli "$@"; }`, command].join(
- '\n',
- );
+ // comment or a shebang cannot swallow the shim. The heredoc delimiter is
+ // quoted, so the wrapper body is written verbatim.
+ const finalCommand = [
+ [
+ `${LH_SHIM_DIR_VAR}=$(mktemp -d)`,
+ // Skipped when a watcher (below) owns the removal.
+ `trap '[ -s ${dir}/.jobs ] || rm -rf ${dir}' EXIT`,
+ // A trapped signal would otherwise resume the script; exiting runs the
+ // EXIT cleanup above.
+ `trap 'exit 129' HUP`,
+ `trap 'exit 130' INT`,
+ `trap 'exit 143' TERM`,
+ `cat > ${dir}/lh <<'${LH_SHIM_EOF}'`,
+ `chmod 700 ${dir}/lh`,
+ `export PATH=${dir}:"$PATH"`,
+ ].join(' && ') +
+ // Without the wrapper an `lh` would silently run unauthenticated, so
+ // stop before any of the command runs.
+ ` || { echo 'lh: could not set up LobeHub CLI credentials' >&2; exit 1; }`,
+ '#!/bin/sh',
+ `${envAssignments} exec npx -y @lobehub/cli "$@"`,
+ LH_SHIM_EOF,
+ // A subshell, so the command's own `trap … EXIT` or `exit` cannot skip the
+ // outer cleanup, and it exits with the command's own status. Jobs it left
+ // in the background may still exec `lh`, so instead of joining them (which
+ // would block on a long-lived server) a detached watcher removes the
+ // wrapper once they have all exited. That hand-off runs from the
+ // subshell's EXIT trap so an `exit` or `set -e` in the command cannot skip
+ // it; a command that replaces this trap only loses the hand-off, never the
+ // cleanup.
+ '(',
+ `trap '${recordJobPids(dir)}; if [ -s ${dir}/.jobs ]; then ${lhWrapperWatcher(dir)} fi' EXIT`,
+ // Functions resolve before PATH, so an inline `PATH=… lh` still reaches
+ // the wrapper; everything run as a program finds it on PATH instead.
+ `lh() { ${dir}/lh "$@"; }`,
+ command,
+ ')',
+ ].join('\n');
log(
'Intercepted lh command for user %s (workspace %s), shim injected',
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/cloudSandbox.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/cloudSandbox.test.ts
index 8f3634d5eba..da51887be99 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/cloudSandbox.test.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/cloudSandbox.test.ts
@@ -34,7 +34,10 @@ vi.mock('@/server/services/sandbox', () => ({
}));
vi.mock('@/server/services/toolExecution/preprocessLhCommand', () => ({
- isLhCommand: (command: string) => command.startsWith('lh'),
+ // Mirrors the real split: the shim predicate matches any mention, the refusal
+ // predicate only an `lh` in command position.
+ isDirectLhInvocation: (command: string) => command.startsWith('lh'),
+ isLhCommand: (command: string) => /\blh\b/.test(command),
preprocessLhCommand: mocks.preprocessLhCommand,
SHARE_VISITOR_LH_BLOCKED_MESSAGE: 'The LobeHub CLI is unavailable in shared conversations.',
}));
@@ -159,6 +162,24 @@ describe('cloudSandboxRuntime', () => {
expect(result.state).toMatchObject({ success: false });
});
+ // Regression: the refusal used the shim's permissive predicate, so a
+ // visitor's harmless command that merely mentions `lh` was rejected outright.
+ it('does not refuse a share-visitor command that only mentions lh', async () => {
+ const { cloudSandboxRuntime } = await import('../cloudSandbox');
+ const runtime = await cloudSandboxRuntime.factory(
+ buildContext({ agentShareVisitor: { agentId: 'agent-1' } }),
+ );
+
+ const command = "echo 'the lh CLI is unavailable here'";
+ await runtime.runCommand({ command, description: 'echo' });
+
+ expect(mocks.preprocessLhCommand).toHaveBeenCalledWith(command, 'user-1', undefined, true);
+ expect(mocks.sandboxService.callTool).toHaveBeenCalledWith(
+ 'runCommand',
+ expect.objectContaining({ command }),
+ );
+ });
+
// Belt-and-braces: even though the short-circuit above already stops an
// `lh` command before this call, every OTHER shell command in a
// share-visitor run still threads `shareVisitorBlocked: true` through to
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/cloudSandbox.ts b/apps/server/src/services/toolExecution/serverRuntimes/cloudSandbox.ts
index 7e9cd98487e..2fa00bdfe6d 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/cloudSandbox.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/cloudSandbox.ts
@@ -7,6 +7,7 @@ import { FileService } from '@/server/services/file';
import { MarketService } from '@/server/services/market';
import { createSandboxService } from '@/server/services/sandbox';
import {
+ isDirectLhInvocation,
isLhCommand,
preprocessLhCommand,
SHARE_VISITOR_LH_BLOCKED_MESSAGE,
@@ -31,7 +32,7 @@ const SHELL_TOOL_NAMES = new Set(['execScript', 'runCommand']);
*
* `isShareVisitor` (set from `context.agentShareVisitor`, see the factory
* below) disables the shim entirely: a share visitor's run executes under the
- * creator's identity, so the shim's `lh() { LOBEHUB_JWT=… }` prelude would
+ * creator's identity, so the shim's `LOBEHUB_JWT=…` `lh` wrapper would
* otherwise hand a JWT scoped to the CREATOR's own account into a shell the
* VISITOR fully controls. `lobe-cloud-sandbox` is allowlisted for share
* visitors specifically because this shim is skipped for them β€” see
@@ -61,7 +62,7 @@ const withLhPreprocessing = (
// silently falling through to `preprocessLhCommand` (which independently
// refuses too β€” see its `shareVisitorBlocked` param β€” but this is the
// primary, intended-to-be-load-bearing check).
- if (resolve.isShareVisitor && isLhCommand(command)) {
+ if (resolve.isShareVisitor && isDirectLhInvocation(command)) {
// Deliberately no command content: it is visitor/model-controlled and
// may carry an inline token β€” same as the `preprocessLhCommand` refusal.
log(