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(cli): scope connect service env to unit (#16825)

Rylan Cai7a3540cab281
diff --git a/apps/cli/package.json b/apps/cli/package.json
index dbf8ef727d8..1bb85eae10e 100644
--- a/apps/cli/package.json
+++ b/apps/cli/package.json
@@ -48,6 +48,7 @@
"picocolors": "^1.1.1",
"semver": "^7.8.5",
"superjson": "^2.2.6",
+ "tree-kill": "^1.2.2",
"tsdown": "^0.21.10",
"typescript": "^6.0.3",
"ws": "^8.21.0"
diff --git a/apps/cli/src/service/connect.test.ts b/apps/cli/src/service/connect.test.ts
index 2190c741910..9f213905246 100644
--- a/apps/cli/src/service/connect.test.ts
+++ b/apps/cli/src/service/connect.test.ts
@@ -59,6 +59,8 @@ describe('connect service', () => {
delete process.env.LOBEHUB_CLI_HOME;
delete process.env.LOBEHUB_CLI_API_KEY;
delete process.env.LOBEHUB_JWT;
+ delete process.env.ANTHROPIC_API_KEY;
+ delete process.env.AWS_SECRET_ACCESS_KEY;
getRunningDaemonPidMock.mockReturnValue(null);
loadCredentialsMock.mockReturnValue({ accessToken: 'jwt' });
@@ -99,6 +101,9 @@ describe('connect service', () => {
expect(fs.readFileSync(unitPath, 'utf8')).toContain(
`"${process.execPath}" "${entryPath}" "connect" "--service-child"`,
);
+ expect(fs.readFileSync(unitPath, 'utf8')).toContain(
+ `EnvironmentFile=${path.join(tmpDir, '.lobehub', 'connect-service.env')}`,
+ );
expect(systemctlCalls).toContainEqual(['--user', 'daemon-reload']);
expect(systemctlCalls).toContainEqual(['--user', 'enable', '--now', 'lobehub-connect.service']);
});
@@ -131,18 +136,23 @@ describe('connect service', () => {
]);
});
- it('imports the current environment by name and clears stale service env', () => {
+ it('writes the current environment to a service-scoped env file', () => {
+ process.env.ANTHROPIC_API_KEY = 'anthropic-key';
+ process.env.AWS_SECRET_ACCESS_KEY = 'aws-secret';
process.env.LOBEHUB_CLI_API_KEY = 'test-key';
- delete process.env.LOBEHUB_CLI_HOME;
+ process.env.QUOTED_ENV = 'value with "quotes", \\slashes, and $dollars';
installConnectService();
- expect(systemctlCalls).toContainEqual(
- expect.arrayContaining(['--user', 'unset-environment', 'LOBEHUB_CLI_HOME']),
- );
- expect(systemctlCalls).toContainEqual(
- expect.arrayContaining(['--user', 'import-environment', 'LOBEHUB_CLI_API_KEY']),
- );
+ const envFilePath = path.join(tmpDir, '.lobehub', 'connect-service.env');
+ const envFile = fs.readFileSync(envFilePath, 'utf8');
+ expect(fs.statSync(envFilePath).mode & 0o777).toBe(0o600);
+ expect(envFile).toContain('ANTHROPIC_API_KEY="anthropic-key"');
+ expect(envFile).toContain('AWS_SECRET_ACCESS_KEY="aws-secret"');
+ expect(envFile).toContain('LOBEHUB_CLI_API_KEY="test-key"');
+ expect(envFile).toContain('QUOTED_ENV="value with \\"quotes\\", \\\\slashes, and \\$dollars"');
+ expect(systemctlCalls.some((call) => call.includes('import-environment'))).toBe(false);
+ expect(systemctlCalls.some((call) => call.includes('unset-environment'))).toBe(false);
expect(systemctlCalls).not.toContainEqual(['--user', 'import-environment']);
});
@@ -153,9 +163,13 @@ describe('connect service', () => {
it('starts an installed service after preflight checks pass', () => {
installConnectService();
systemctlCalls = [];
+ process.env.LOBEHUB_CLI_API_KEY = 'rotated-key';
expect(startConnectService()).toBe(true);
+ expect(fs.readFileSync(path.join(tmpDir, '.lobehub', 'connect-service.env'), 'utf8')).toContain(
+ 'LOBEHUB_CLI_API_KEY="rotated-key"',
+ );
expect(systemctlCalls).toContainEqual(['--user', 'start', 'lobehub-connect.service']);
});
});
diff --git a/apps/cli/src/service/connect.ts b/apps/cli/src/service/connect.ts
index 8bd03e3bb69..1b9c5cfb3b2 100644
--- a/apps/cli/src/service/connect.ts
+++ b/apps/cli/src/service/connect.ts
@@ -9,16 +9,7 @@ import { getRunningDaemonPid } from '../daemon/manager';
const SERVICE_NAME = 'lobehub-connect.service';
const ENV_NAME_PATTERN = /^[A-Z_]\w*$/i;
-const SERVICE_ENV_NAMES = [
- 'AGENT_GATEWAY_URL',
- 'DEBUG',
- 'LH_GATEWAY_URL',
- 'LOBEHUB_CLI_CHANNEL',
- 'LOBEHUB_CLI_HOME',
- CLI_API_KEY_ENV,
- 'LOBEHUB_JWT',
- 'LOBEHUB_SERVER',
-];
+const SERVICE_ENV_FILE_NAME = 'connect-service.env';
export interface ConnectServiceStatus {
active: boolean;
@@ -46,6 +37,14 @@ function getUserServiceDir(): string {
);
}
+function getCliHomeDir(): string {
+ return path.join(os.homedir(), process.env.LOBEHUB_CLI_HOME || '.lobehub');
+}
+
+function getServiceEnvFilePath(): string {
+ return path.join(getCliHomeDir(), SERVICE_ENV_FILE_NAME);
+}
+
function getExecErrorMessage(error: unknown): string {
const stderr =
error && typeof error === 'object' && 'stderr' in error
@@ -61,8 +60,9 @@ function renderUnit(): string {
const escapeSystemdEnvValue = (value: string): string =>
value.replaceAll('\\', '\\\\').replaceAll('"', '\\"');
const homeDir = os.homedir();
- const cliHomeDir = path.join(homeDir, process.env.LOBEHUB_CLI_HOME || '.lobehub');
+ const cliHomeDir = getCliHomeDir();
const logPath = path.join(cliHomeDir, 'daemon.log');
+ const envFilePath = getServiceEnvFilePath();
const scriptPath = fs.realpathSync(process.argv[1]!);
const execStart = [process.execPath, scriptPath, 'connect', '--service-child']
.map(quoteSystemdValue)
@@ -79,6 +79,7 @@ function renderUnit(): string {
'[Service]',
'Type=simple',
`WorkingDirectory=${homeDir}`,
+ `EnvironmentFile=${envFilePath}`,
`Environment=HOME=${escapeSystemdEnvValue(homeDir)}`,
'Environment=LOBEHUB_CONNECT_SERVICE=1',
`ExecStart=${execStart}`,
@@ -121,16 +122,27 @@ function requireLinuxSystemd() {
}
}
-function importServiceEnvironment(): void {
- const staleServiceEnvNames = SERVICE_ENV_NAMES.filter((name) => process.env[name] === undefined);
- if (staleServiceEnvNames.length > 0) {
- systemctl(['unset-environment', ...staleServiceEnvNames], 'inherit');
- }
-
- const environmentNames = Object.keys(process.env).filter((name) => ENV_NAME_PATTERN.test(name));
- if (environmentNames.length > 0) {
- systemctl(['import-environment', ...environmentNames], 'inherit');
- }
+function writeServiceEnvironmentFile(): void {
+ const quoteEnvironmentFileValue = (value: string): string =>
+ `"${value
+ .replaceAll('\\', '\\\\')
+ .replaceAll('"', '\\"')
+ .replaceAll('`', '\\`')
+ .replaceAll('$', '\\$')}"`;
+
+ const lines = Object.entries(process.env)
+ .filter((entry): entry is [string, string] => {
+ const [name, value] = entry;
+ return ENV_NAME_PATTERN.test(name) && value !== undefined;
+ })
+ .sort(([a], [b]) => a.localeCompare(b))
+ .map(([name, value]) => `${name}=${quoteEnvironmentFileValue(value)}`);
+
+ const envFilePath = getServiceEnvFilePath();
+ fs.mkdirSync(path.dirname(envFilePath), { mode: 0o700, recursive: true });
+ // The captured shell environment can include provider API keys; keep it owner-only.
+ fs.writeFileSync(envFilePath, `${lines.join('\n')}\n`, { mode: 0o600 });
+ fs.chmodSync(envFilePath, 0o600);
}
function assertNoConnectDaemonRunning(): void {
@@ -159,14 +171,10 @@ export function installConnectService(): void {
assertNoConnectDaemonRunning();
assertConnectServiceAuthAvailable();
- fs.mkdirSync(path.join(os.homedir(), process.env.LOBEHUB_CLI_HOME || '.lobehub'), {
- mode: 0o700,
- recursive: true,
- });
+ writeServiceEnvironmentFile();
fs.mkdirSync(getUserServiceDir(), { mode: 0o700, recursive: true });
fs.writeFileSync(path.join(getUserServiceDir(), SERVICE_NAME), renderUnit(), { mode: 0o644 });
- importServiceEnvironment();
systemctl(['daemon-reload'], 'inherit');
systemctl(['enable', '--now', SERVICE_NAME], 'inherit');
}
@@ -184,6 +192,7 @@ export function uninstallConnectService(): boolean {
}
fs.unlinkSync(unitPath);
+ fs.rmSync(getServiceEnvFilePath(), { force: true });
systemctl(['daemon-reload'], 'inherit');
return true;
@@ -194,7 +203,7 @@ export function startConnectService(): boolean {
requireLinuxSystemd();
assertNoConnectDaemonRunning();
assertConnectServiceAuthAvailable();
- importServiceEnvironment();
+ writeServiceEnvironmentFile();
systemctl(['start', SERVICE_NAME], 'inherit');
return true;
}
@@ -211,7 +220,7 @@ export function restartConnectService(): boolean {
requireLinuxSystemd();
assertNoConnectDaemonRunning();
assertConnectServiceAuthAvailable();
- importServiceEnvironment();
+ writeServiceEnvironmentFile();
systemctl(['restart', SERVICE_NAME], 'inherit');
return true;
}