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.

✨ feat(creds): list env var names per key in injectCredsToSandbox and keep ~/.creds/env cumulative (T-13715) (#22701)

Lobehub Coderf00c25563063
diff --git a/apps/server/src/routers/lambda/market/creds.test.ts b/apps/server/src/routers/lambda/market/creds.test.ts
index 3f0b2047022..29e5fef3acc 100644
--- a/apps/server/src/routers/lambda/market/creds.test.ts
+++ b/apps/server/src/routers/lambda/market/creds.test.ts
@@ -10,6 +10,7 @@ interface MockOrgCredRow {
const {
mockCredsInject,
+ mockMarketSandboxProvider,
mockResolveSandboxSessionConfig,
mockOrgCredsList,
mockPersonalCredsList,
@@ -18,6 +19,10 @@ const {
mockPersonalCredsUnshare,
} = vi.hoisted(() => ({
mockCredsInject: vi.fn(async () => ({ credentials: { env: {} }, success: true })),
+ mockMarketSandboxProvider: vi.fn(function (this: any, options: any) {
+ this.options = options;
+ this.callTool = vi.fn(async () => ({ result: {}, success: true }));
+ }),
mockResolveSandboxSessionConfig: vi.fn(),
mockOrgCredsList: vi.fn(async (): Promise<{ data: MockOrgCredRow[] }> => ({
data: [{ id: 1, key: 'ORG_SECRET' }],
@@ -90,6 +95,8 @@ vi.mock('@/server/services/market', () => ({
}));
vi.mock('@/server/services/sandbox', () => ({
+ getSandboxProviderKind: () => 'market',
+ MarketSandboxProvider: mockMarketSandboxProvider,
resolveSandboxSessionConfig: mockResolveSandboxSessionConfig,
}));
@@ -350,6 +357,42 @@ describe('credsRouter inject routes to the topic sandbox', () => {
);
});
+ // Market rewrites ~/.creds/env on every inject, so the route merges the
+ // listing afterwards. That merge must run in the sandbox the credentials
+ // were just written into: without the placement and the signed claim it
+ // would open (or replace) a throwaway sandbox instead.
+ it('merges ~/.creds/env in the same sandbox the credentials were injected into', async () => {
+ const { MarketService } = await import('@/server/services/market');
+ mockResolveSandboxSessionConfig.mockResolvedValue({
+ claim: { key: 'u-user-1' },
+ cwd: '/workspace/project',
+ drive: 'personal',
+ environment: 'inst-1',
+ mode: 'persistent',
+ workingDir: '/home/user/project',
+ });
+ const { credsRouter } = await import('./creds');
+
+ const caller = credsRouter.createCaller({ userId: 'user-1' } as any);
+ await caller.inject({ keys: ['FOO'], topicId: 'topic-1' });
+
+ expect(mockMarketSandboxProvider).toHaveBeenCalledTimes(1);
+ const { options, callTool } = mockMarketSandboxProvider.mock.instances[0] as any;
+ expect(options).toMatchObject({
+ sandboxCwd: '/workspace/project',
+ sandboxInstanceId: 'inst-1',
+ sandboxMode: 'persistent',
+ sandboxWorkingDir: '/home/user/project',
+ topicId: 'topic-1',
+ userId: 'user-1',
+ });
+ // The claim-signed service, not the request's unsigned one.
+ expect(options.marketService).toBe(vi.mocked(MarketService).mock.results.at(-1)?.value);
+ expect(callTool).toHaveBeenCalledWith('runCommand', {
+ command: expect.stringContaining('~/.creds/.env.ledger'),
+ });
+ });
+
it('skips sandbox resolution when not injecting into a sandbox', async () => {
const { credsRouter } = await import('./creds');
@@ -360,5 +403,6 @@ describe('credsRouter inject routes to the topic sandbox', () => {
expect(mockCredsInject).toHaveBeenCalledWith(
expect.objectContaining({ sandbox: false, sandboxMode: undefined }),
);
+ expect(mockMarketSandboxProvider).not.toHaveBeenCalled();
});
});
diff --git a/apps/server/src/routers/lambda/market/creds.ts b/apps/server/src/routers/lambda/market/creds.ts
index b0bfdc14065..937477ba79e 100644
--- a/apps/server/src/routers/lambda/market/creds.ts
+++ b/apps/server/src/routers/lambda/market/creds.ts
@@ -9,7 +9,15 @@ import { cloudWorkspaceAuth } from '@/business/server/trpc-middlewares/workspace
import { publicProcedure, router } from '@/libs/trpc/lambda';
import { marketUserInfo, requireMarketAuth, serverDatabase } from '@/libs/trpc/lambda/middleware';
import { MarketService } from '@/server/services/market';
-import { resolveSandboxSessionConfig } from '@/server/services/sandbox';
+import {
+ getSandboxProviderKind,
+ MarketSandboxProvider,
+ resolveSandboxSessionConfig,
+} from '@/server/services/sandbox';
+import {
+ mergeCredsEnvListing,
+ resolveInjectedEnvVarsByKey,
+} from '@/server/services/sandbox/credsEnv';
const log = debug('lambda-router:market:creds');
@@ -422,7 +430,36 @@ export const credsRouter = router({
notFound: result.notFound?.length,
success: result.success,
});
- return result;
+
+ const envVarsByKey = await resolveInjectedEnvVarsByKey(input.keys, result, (key) =>
+ marketService.market.creds.inject({
+ keys: [key],
+ sandbox: false,
+ topicId: input.topicId,
+ userId,
+ }),
+ );
+
+ // Market rewrites ~/.creds/env per call; merge it so earlier
+ // injections stay listed. Addressed like the inject call above, so
+ // the merge runs in the sandbox the credentials were written into.
+ if (input.sandbox && getSandboxProviderKind() === 'market') {
+ await mergeCredsEnvListing(
+ new MarketSandboxProvider({
+ marketService,
+ sandboxCwd: sandbox?.cwd,
+ sandboxInstanceId: sandbox?.environment,
+ sandboxMode: sandbox?.mode,
+ sandboxSpecification: sandbox?.specification,
+ sandboxWorkingDir: sandbox?.workingDir,
+ serverDB: ctx.serverDB,
+ topicId: input.topicId,
+ userId,
+ }),
+ );
+ }
+
+ return { ...result, envVarsByKey };
} catch (error) {
log('inject error: %O', error);
throw new TRPCError({
diff --git a/apps/server/src/services/sandbox/credsEnv.test.ts b/apps/server/src/services/sandbox/credsEnv.test.ts
new file mode 100644
index 00000000000..3d58ceede01
--- /dev/null
+++ b/apps/server/src/services/sandbox/credsEnv.test.ts
@@ -0,0 +1,143 @@
+import { execFileSync } from 'node:child_process';
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import {
+ CREDS_ENV_MERGE_COMMAND,
+ mergeCredsEnvListing,
+ resolveInjectedEnvVarsByKey,
+} from './credsEnv';
+
+describe('CREDS_ENV_MERGE_COMMAND', () => {
+ let home: string;
+
+ const credsEnv = () => path.join(home, '.creds', 'env');
+ // What Market does on every inject: rewrite the listing with this call's keys only.
+ const marketWrites = (lines: string[]) => {
+ mkdirSync(path.dirname(credsEnv()), { recursive: true });
+ writeFileSync(credsEnv(), `${lines.join('\n')}\n`);
+ };
+ const runMerge = () =>
+ execFileSync('sh', ['-c', CREDS_ENV_MERGE_COMMAND], { env: { ...process.env, HOME: home } });
+ const listing = () => readFileSync(credsEnv(), 'utf8').trim().split('\n');
+
+ beforeEach(() => {
+ home = mkdtempSync(path.join(tmpdir(), 'creds-env-'));
+ });
+
+ afterEach(() => {
+ rmSync(home, { force: true, recursive: true });
+ });
+
+ it('keeps variables from an earlier injection after a later one rewrites the file', () => {
+ marketWrites([
+ '# LOBEHUB_DATABASE_URL=po******db',
+ '# CLOUD_DATABASE_URL=po******db',
+ '# MARKET_DATABASE_URL=po******db',
+ ]);
+ runMerge();
+
+ marketWrites(['# DEEPSEEK_API_KEY=sk******ab']);
+ runMerge();
+
+ expect(listing()).toEqual([
+ '# LOBEHUB_DATABASE_URL=******',
+ '# CLOUD_DATABASE_URL=******',
+ '# MARKET_DATABASE_URL=******',
+ '# DEEPSEEK_API_KEY=******',
+ ]);
+ });
+
+ it('keeps one line per variable, the latest one, in first-seen order', () => {
+ marketWrites(['# Injected credentials', '# DEEPSEEK_API_KEY=sk******aa', 'export FOO=1']);
+ runMerge();
+
+ marketWrites(['# Injected credentials', '# DEEPSEEK_API_KEY=sk******bb']);
+ runMerge();
+
+ expect(listing()).toEqual([
+ '# Injected credentials',
+ '# DEEPSEEK_API_KEY=******',
+ 'export FOO=1',
+ ]);
+ });
+
+ it('drops the value fragments Market leaves in masked lines', () => {
+ marketWrites(['# DEEPSEEK_API_KEY=sk******ab', '#OPENAI_API_KEY=8f******vZ', 'export FOO=bar']);
+ runMerge();
+
+ const content = readFileSync(credsEnv(), 'utf8');
+ expect(content).not.toMatch(/sk\*|\*ab|8f\*|\*vZ/);
+ expect(listing()).toEqual([
+ '# DEEPSEEK_API_KEY=******',
+ '# OPENAI_API_KEY=******',
+ 'export FOO=bar',
+ ]);
+ });
+
+ it('works when the sandbox has no listing yet', () => {
+ runMerge();
+
+ expect(readFileSync(credsEnv(), 'utf8')).toBe('');
+ });
+});
+
+describe('mergeCredsEnvListing', () => {
+ it('runs the merge command in the sandbox', async () => {
+ const callTool = vi.fn().mockResolvedValue({ result: {}, success: true });
+
+ await expect(mergeCredsEnvListing({ callTool })).resolves.toBe(true);
+ expect(callTool).toHaveBeenCalledWith('runCommand', { command: CREDS_ENV_MERGE_COMMAND });
+ });
+
+ it('reports failure without throwing', async () => {
+ const callTool = vi.fn().mockResolvedValue({ error: { message: 'x' }, success: false });
+
+ await expect(mergeCredsEnvListing({ callTool })).resolves.toBe(false);
+ await expect(
+ mergeCredsEnvListing({ callTool: vi.fn().mockRejectedValue(new Error('down')) }),
+ ).resolves.toBe(false);
+ });
+});
+
+describe('resolveInjectedEnvVarsByKey', () => {
+ it('attributes every variable to a single injected key without another call', async () => {
+ const lookup = vi.fn();
+
+ await expect(
+ resolveInjectedEnvVarsByKey(
+ ['deepseek', 'missing'],
+ { credentials: { env: { DEEPSEEK_API_KEY: 'x' } }, notFound: ['missing'] },
+ lookup,
+ ),
+ ).resolves.toEqual({ deepseek: ['DEEPSEEK_API_KEY'] });
+ expect(lookup).not.toHaveBeenCalled();
+ });
+
+ it('looks each key up when one call injected several', async () => {
+ const lookup = vi.fn(async (key: string) => ({
+ credentials: { env: key === 'a' ? { A_1: 'x', A_2: 'x' } : { B_1: 'x' } },
+ }));
+
+ await expect(
+ resolveInjectedEnvVarsByKey(
+ ['a', 'b'],
+ { credentials: { env: { A_1: 'x', A_2: 'x', B_1: 'x' } } },
+ lookup,
+ ),
+ ).resolves.toEqual({ a: ['A_1', 'A_2'], b: ['B_1'] });
+ });
+
+ it('gives up on attribution when a lookup fails', async () => {
+ await expect(
+ resolveInjectedEnvVarsByKey(
+ ['a', 'b'],
+ { credentials: { env: { A_1: 'x', B_1: 'x' } } },
+ vi.fn().mockRejectedValue(new Error('market down')),
+ ),
+ ).resolves.toBeUndefined();
+ });
+});
diff --git a/apps/server/src/services/sandbox/credsEnv.ts b/apps/server/src/services/sandbox/credsEnv.ts
new file mode 100644
index 00000000000..bc50f7909de
--- /dev/null
+++ b/apps/server/src/services/sandbox/credsEnv.ts
@@ -0,0 +1,123 @@
+import debug from 'debug';
+import pMap from 'p-map';
+
+import type { SandboxProvider } from './types';
+
+const log = debug('lobe-server:sandbox:creds-env');
+
+/**
+ * Market's inject endpoint rewrites `~/.creds/env` with only the keys of the
+ * current call, so the listing lost every variable an earlier injection had
+ * recorded (the variables themselves stay in the process env). After each
+ * injection this command folds the new file into a ledger of everything
+ * injected into this sandbox and writes the union back to `~/.creds/env`.
+ *
+ * Lines are keyed by variable name, whether written as `NAME=…`,
+ * `export NAME=…` or the masked `# NAME=…` comment form, and the latest
+ * line for a name wins. Other lines are kept once, in first-seen order.
+ *
+ * Market masks the listing's comment lines but keeps the first and last two
+ * characters (`# NAME=po******db`). Those fragments are still part of the
+ * value, so comment lines are rewritten to `# NAME=******`. Assignment lines
+ * (`NAME=…`, `export NAME=…`) are left as written because a shell may source
+ * them. The command carries no credential names or values, and it prints
+ * nothing.
+ */
+export const CREDS_ENV_MERGE_COMMAND = [
+ 'umask 077',
+ 'mkdir -p ~/.creds',
+ 'touch ~/.creds/env ~/.creds/.env.ledger',
+ `awk '
+function varname(line, n) {
+ n = line
+ sub(/^#[ \\t]*/, "", n)
+ sub(/^export[ \\t]+/, "", n)
+ if (n !~ /^[A-Za-z_][A-Za-z0-9_]*=/) return ""
+ sub(/=.*/, "", n)
+ return n
+}
+{
+ k = varname($0)
+ if (k == "") {
+ if (!(("L" $0) in seen)) { seen["L" $0] = 1; order[++count] = "L" $0 }
+ next
+ }
+ if (!(("V" k) in seen)) { seen["V" k] = 1; order[++count] = "V" k }
+ latest[k] = ($0 ~ /^#/) ? "# " k "=******" : $0
+}
+END {
+ for (i = 1; i <= count; i++) {
+ entry = order[i]
+ if (substr(entry, 1, 1) == "V") print latest[substr(entry, 2)]
+ else print substr(entry, 2)
+ }
+}' ~/.creds/.env.ledger ~/.creds/env > ~/.creds/.env.merged`,
+ 'cp ~/.creds/.env.merged ~/.creds/.env.ledger',
+ 'mv ~/.creds/.env.merged ~/.creds/env',
+].join(' && ');
+
+/**
+ * Best effort: the credentials are already in the sandbox when this runs, so
+ * a failed merge only leaves the listing as Market wrote it.
+ */
+export const mergeCredsEnvListing = async (
+ provider: Pick<SandboxProvider, 'callTool'>,
+): Promise<boolean> => {
+ try {
+ const result = await provider.callTool('runCommand', { command: CREDS_ENV_MERGE_COMMAND });
+ if (!result.success) {
+ log('merge ~/.creds/env failed: %s', result.error?.message);
+ return false;
+ }
+ return true;
+ } catch (error) {
+ log('merge ~/.creds/env threw: %O', error);
+ return false;
+ }
+};
+
+interface InjectResultLike {
+ credentials?: { env?: Record<string, string> };
+ notFound?: string[];
+ unsupportedInSandbox?: string[];
+}
+
+/**
+ * Market returns one flat `credentials.env` map per call, so a call that
+ * injects several keys does not say which key set which variable. A single
+ * key needs no lookup. For several keys this asks Market again per key with
+ * `sandbox: false`, which resolves the credential without touching the
+ * sandbox, and keeps only the variable names. On failure it returns
+ * `undefined` and the result lists the variables as unattributed.
+ */
+export const resolveInjectedEnvVarsByKey = async (
+ keys: string[],
+ result: InjectResultLike,
+ injectWithoutSandbox: (key: string) => Promise<InjectResultLike>,
+): Promise<Record<string, string[]> | undefined> => {
+ const skipped = new Set([...(result.notFound ?? []), ...(result.unsupportedInSandbox ?? [])]);
+ const injected = [...new Set(keys)].filter((key) => !skipped.has(key));
+ const envNames = Object.keys(result.credentials?.env ?? {});
+
+ if (injected.length === 0 || envNames.length === 0) return undefined;
+ if (injected.length === 1) return { [injected[0]]: envNames };
+
+ try {
+ const injectedNames = new Set(envNames);
+ const entries = await pMap(
+ injected,
+ async (key) => {
+ const single = await injectWithoutSandbox(key);
+ const names = Object.keys(single.credentials?.env ?? {}).filter((name) =>
+ injectedNames.has(name),
+ );
+ return [key, names] as const;
+ },
+ { concurrency: 4 },
+ );
+ return Object.fromEntries(entries);
+ } catch (error) {
+ log('resolve env names per key failed: %O', error);
+ return undefined;
+ }
+};
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/creds.test.ts b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/creds.test.ts
index d7c1d6c8553..060d6e5b570 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/__tests__/creds.test.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/__tests__/creds.test.ts
@@ -11,6 +11,10 @@ const { getMember, resolveSandboxSessionConfig } = vi.hoisted(() => ({
}));
vi.mock('@/server/services/sandbox', () => ({
+ getSandboxProviderKind: () => 'market',
+ MarketSandboxProvider: vi.fn(function (this: any) {
+ this.callTool = vi.fn(async () => ({ result: {}, success: true }));
+ }),
resolveSandboxSessionConfig,
}));
@@ -254,6 +258,78 @@ describe('ServerCredsService.injectCreds', () => {
topicId: 'topic-1',
userId: 'user-1',
});
- expect(result).toBe(injectResult);
+ expect(result).toEqual({
+ ...injectResult,
+ envVarsByKey: { 'dc-cli-token': ['DC_CLI_TOKEN'] },
+ });
+ });
+
+ it('maps each key to its own variables and merges ~/.creds/env after injecting', async () => {
+ const inject = vi.fn().mockImplementation(async ({ keys }: { keys: string[] }) => {
+ const byKey: Record<string, Record<string, string>> = {
+ 'deepseek': { DEEPSEEK_API_KEY: 'sk******ab' },
+ 'lobehub-database': {
+ CLOUD_DATABASE_URL: 'po******db',
+ LOBEHUB_DATABASE_URL: 'po******db',
+ MARKET_DATABASE_URL: 'po******db',
+ },
+ };
+ return {
+ credentials: { env: Object.assign({}, ...keys.map((key) => byKey[key])) },
+ notFound: [],
+ success: true,
+ };
+ });
+ const callTool = vi.fn().mockResolvedValue({ result: {}, success: true });
+ const service = new ServerCredsService(buildMarketService(inject), {
+ sandboxProvider: { callTool },
+ });
+
+ const result = await service.injectCreds({
+ keys: ['lobehub-database', 'deepseek'],
+ sandbox: true,
+ topicId: 'topic-1',
+ userId: 'user-1',
+ });
+
+ expect(result.envVarsByKey).toEqual({
+ 'deepseek': ['DEEPSEEK_API_KEY'],
+ 'lobehub-database': ['CLOUD_DATABASE_URL', 'LOBEHUB_DATABASE_URL', 'MARKET_DATABASE_URL'],
+ });
+ // Only the first call writes into the sandbox; the per-key lookups don't.
+ expect(inject.mock.calls.map(([req]) => [req.keys, req.sandbox])).toEqual([
+ [['lobehub-database', 'deepseek'], true],
+ [['lobehub-database'], false],
+ [['deepseek'], false],
+ ]);
+ expect(callTool).toHaveBeenCalledTimes(1);
+ expect(callTool).toHaveBeenCalledWith('runCommand', {
+ command: expect.stringContaining('~/.creds/.env.ledger'),
+ });
+ for (const value of ['sk******ab', 'po******db']) {
+ expect(JSON.stringify(callTool.mock.calls)).not.toContain(value);
+ }
+ });
+
+ it('still returns the injection when merging ~/.creds/env fails', async () => {
+ const inject = vi.fn().mockResolvedValue({
+ credentials: { env: { DEEPSEEK_API_KEY: 'sk******ab' } },
+ notFound: [],
+ success: true,
+ });
+ const callTool = vi.fn().mockRejectedValue(new Error('sandbox down'));
+ const service = new ServerCredsService(buildMarketService(inject), {
+ sandboxProvider: { callTool },
+ });
+
+ const result = await service.injectCreds({
+ keys: ['deepseek'],
+ sandbox: true,
+ topicId: 'topic-1',
+ userId: 'user-1',
+ });
+
+ expect(result.success).toBe(true);
+ expect(result.envVarsByKey).toEqual({ deepseek: ['DEEPSEEK_API_KEY'] });
});
});
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/creds.ts b/apps/server/src/services/toolExecution/serverRuntimes/creds.ts
index e1a78f736b2..21a56881e68 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/creds.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/creds.ts
@@ -6,7 +6,16 @@ import debug from 'debug';
import { UserModel } from '@/database/models/user';
import { WorkspaceMemberModel } from '@/database/models/workspaceMember';
import type { MarketService } from '@/server/services/market';
-import { resolveSandboxSessionConfig } from '@/server/services/sandbox';
+import {
+ getSandboxProviderKind,
+ MarketSandboxProvider,
+ resolveSandboxSessionConfig,
+ type SandboxProvider,
+} from '@/server/services/sandbox';
+import {
+ mergeCredsEnvListing,
+ resolveInjectedEnvVarsByKey,
+} from '@/server/services/sandbox/credsEnv';
import { type ToolExecutionContext } from '../types';
import { resolveContentWorkspaceId } from './resolveWorkspaceScope';
@@ -34,6 +43,7 @@ export class ServerCredsService implements ICredsService {
private workspaceId?: string;
private isShareVisitor: boolean;
+ private sandboxProvider?: Pick<SandboxProvider, 'callTool'>;
private sandboxTarget: CredsSandboxTarget;
@@ -50,6 +60,11 @@ export class ServerCredsService implements ICredsService {
* the allowlist alone.
*/
isShareVisitor?: boolean;
+ /**
+ * The Market sandbox the injection lands in. When set, `~/.creds/env` is
+ * merged after each injection so earlier injections stay listed.
+ */
+ sandboxProvider?: Pick<SandboxProvider, 'callTool'>;
/** Where the topic's tool calls run; injection must land in the same sandbox. */
sandboxTarget?: CredsSandboxTarget;
workspaceId?: string;
@@ -58,6 +73,7 @@ export class ServerCredsService implements ICredsService {
this.marketService = marketService;
this.workspaceId = options.workspaceId;
this.isShareVisitor = options.isShareVisitor ?? false;
+ this.sandboxProvider = options.sandboxProvider;
this.sandboxTarget = options.sandboxTarget ?? {};
}
@@ -142,6 +158,7 @@ export class ServerCredsService implements ICredsService {
env?: Record<string, string>;
files?: Array<{ filename: string; key: string; path: string }>;
};
+ envVarsByKey?: Record<string, string[]>;
notFound?: string[];
success: boolean;
unsupportedInSandbox?: string[];
@@ -185,7 +202,20 @@ export class ServerCredsService implements ICredsService {
log('injectCreds success: notFound=%d', result.notFound?.length || 0);
- return result as any;
+ const envVarsByKey = await resolveInjectedEnvVarsByKey(params.keys, result, (key) =>
+ this.marketService.market.creds.inject({
+ keys: [key],
+ sandbox: false,
+ topicId: params.topicId,
+ userId: params.userId,
+ }),
+ );
+
+ if (params.sandbox !== false && this.sandboxProvider) {
+ await mergeCredsEnvListing(this.sandboxProvider);
+ }
+
+ return { ...result, envVarsByKey } as any;
}
async listCreds(): Promise<{
@@ -280,8 +310,26 @@ export const credsRuntime: ServerRuntimeRegistration = {
sandbox.claim,
);
+ // Market's inject endpoint only writes into a Market sandbox, so the
+ // listing merge runs there too, in the same session the commands use.
+ const sandboxProvider =
+ getSandboxProviderKind() === 'market' && context.topicId
+ ? new MarketSandboxProvider({
+ marketService,
+ sandboxCwd: sandbox.cwd,
+ sandboxInstanceId: sandbox.environment,
+ sandboxMode: sandbox.mode,
+ sandboxSpecification: sandbox.specification,
+ sandboxWorkingDir: sandbox.workingDir,
+ serverDB: context.serverDB,
+ topicId: context.topicId,
+ userId: context.userId,
+ })
+ : undefined;
+
const credsService = new ServerCredsService(marketService, {
isShareVisitor: Boolean(context.agentShareVisitor),
+ sandboxProvider,
sandboxTarget: { instanceId: sandbox.environment, mode: sandbox.mode },
workspaceId,
});
diff --git a/packages/builtin-tool-creds/src/ExecutionRuntime/index.ts b/packages/builtin-tool-creds/src/ExecutionRuntime/index.ts
index 9ccc0372e30..28920abc55a 100644
--- a/packages/builtin-tool-creds/src/ExecutionRuntime/index.ts
+++ b/packages/builtin-tool-creds/src/ExecutionRuntime/index.ts
@@ -5,6 +5,7 @@ import {
} from '@lobechat/const';
import type { BuiltinServerRuntimeOutput } from '@lobechat/types';
+import { buildInjectCredsResult } from '../injectResult';
import { buildRequestCredsInputResult } from '../requestCredsInput';
import type {
ConnectComposioServiceParams,
@@ -49,6 +50,8 @@ export interface ICredsService {
env?: Record<string, string>;
files?: Array<{ filename: string; key: string; path: string }>;
};
+ /** Environment variable names each key injected (names only, never values). */
+ envVarsByKey?: Record<string, string[]>;
notFound?: string[];
success: boolean;
unsupportedInSandbox?: string[];
@@ -249,34 +252,17 @@ export class CredsExecutionRuntime {
userId,
});
- const credentials = result.credentials || {};
- const notFound = result.notFound || [];
- const unsupportedInSandbox = result.unsupportedInSandbox || [];
-
- // Build response content
- const injectedKeys = args.keys.filter((k) => !notFound.includes(k));
- let content = '';
-
- if (injectedKeys.length > 0) {
- content = `Credentials injected successfully: ${injectedKeys.join(', ')}.`;
- }
-
- if (notFound.length > 0) {
- content += ` Not found: ${notFound.join(', ')}. Please configure them in Settings > Credentials.`;
- }
-
- if (unsupportedInSandbox.length > 0) {
- content += ` Not supported in sandbox: ${unsupportedInSandbox.join(', ')}.`;
- }
+ const summary = buildInjectCredsResult(args.keys, result);
return {
- content: content.trim(),
+ content: summary.content,
state: {
- credentials,
- injected: injectedKeys,
- notFound,
- success: notFound.length === 0,
- unsupportedInSandbox,
+ credentials: summary.credentials,
+ envVarsByKey: summary.envVarsByKey,
+ injected: summary.injected,
+ notFound: summary.notFound,
+ success: summary.notFound.length === 0,
+ unsupportedInSandbox: summary.unsupportedInSandbox,
},
success: true,
};
diff --git a/packages/builtin-tool-creds/src/executor/index.ts b/packages/builtin-tool-creds/src/executor/index.ts
index a5100499cb6..8179837541f 100644
--- a/packages/builtin-tool-creds/src/executor/index.ts
+++ b/packages/builtin-tool-creds/src/executor/index.ts
@@ -10,6 +10,7 @@ import { ComposioServerStatus } from '@/store/tool/slices/composioStore/types';
import { useUserStore } from '@/store/user';
import { userProfileSelectors } from '@/store/user/slices/auth/selectors';
+import { buildInjectCredsResult } from '../injectResult';
import { CredsIdentifier } from '../manifest';
import { buildRequestCredsInputResult } from '../requestCredsInput';
import type {
@@ -345,30 +346,17 @@ class CredsExecutor extends BaseExecutor<typeof CredsApiName> {
unsupportedInSandbox,
});
- // Build response content
- const injectedKeys = params.keys.filter((k) => !notFound.includes(k));
- let content = '';
-
- if (injectedKeys.length > 0) {
- content = `Credentials injected successfully: ${injectedKeys.join(', ')}.`;
- }
-
- if (notFound.length > 0) {
- content += ` Not found: ${notFound.join(', ')}. Please configure them in Settings > Credentials.`;
- }
-
- if (unsupportedInSandbox.length > 0) {
- content += ` Not supported in sandbox: ${unsupportedInSandbox.join(', ')}.`;
- }
+ const summary = buildInjectCredsResult(params.keys, result as any);
return {
- content: content.trim(),
+ content: summary.content,
state: {
- credentials,
- injected: injectedKeys,
- notFound,
- success: notFound.length === 0,
- unsupportedInSandbox,
+ credentials: summary.credentials,
+ envVarsByKey: summary.envVarsByKey,
+ injected: summary.injected,
+ notFound: summary.notFound,
+ success: summary.notFound.length === 0,
+ unsupportedInSandbox: summary.unsupportedInSandbox,
},
success: true,
};
diff --git a/packages/builtin-tool-creds/src/index.ts b/packages/builtin-tool-creds/src/index.ts
index ff189b50909..34419385cd8 100644
--- a/packages/builtin-tool-creds/src/index.ts
+++ b/packages/builtin-tool-creds/src/index.ts
@@ -13,6 +13,12 @@ export {
resolveAvailableComposioServices,
type UserCredsContext,
} from './helpers';
+export {
+ buildInjectCredsResult,
+ type InjectCredsResultInput,
+ type InjectCredsResultSummary,
+ resolveEnvVarsByKey,
+} from './injectResult';
export { CredsIdentifier, CredsManifest } from './manifest';
export { systemPrompt } from './systemRole';
export {
diff --git a/packages/builtin-tool-creds/src/injectResult.test.ts b/packages/builtin-tool-creds/src/injectResult.test.ts
new file mode 100644
index 00000000000..efd5b9064c1
--- /dev/null
+++ b/packages/builtin-tool-creds/src/injectResult.test.ts
@@ -0,0 +1,129 @@
+import { describe, expect, it } from 'vitest';
+
+import { buildInjectCredsResult } from './injectResult';
+
+describe('buildInjectCredsResult', () => {
+ it('lists the variable names a single key injected, without values', () => {
+ const result = buildInjectCredsResult(['deepseek'], {
+ credentials: { env: { DEEPSEEK_API_KEY: 'sk******ab' } },
+ notFound: [],
+ });
+
+ expect(result.content).toBe(
+ [
+ 'Credentials injected successfully: deepseek.',
+ 'Injected per key (variable names only, values are never shown):',
+ '- deepseek β†’ DEEPSEEK_API_KEY',
+ ].join('\n'),
+ );
+ expect(result.envVarsByKey).toEqual({ deepseek: ['DEEPSEEK_API_KEY'] });
+ expect(result.content).not.toContain('sk******ab');
+ });
+
+ it('maps several keys using the server-resolved mapping', () => {
+ const result = buildInjectCredsResult(['lobehub-database', 'deepseek'], {
+ credentials: {
+ env: {
+ CLOUD_DATABASE_URL: 'po******db',
+ DEEPSEEK_API_KEY: 'sk******ab',
+ LOBEHUB_DATABASE_URL: 'po******db',
+ MARKET_DATABASE_URL: 'po******db',
+ },
+ },
+ envVarsByKey: {
+ 'deepseek': ['DEEPSEEK_API_KEY'],
+ 'lobehub-database': ['LOBEHUB_DATABASE_URL', 'CLOUD_DATABASE_URL', 'MARKET_DATABASE_URL'],
+ },
+ });
+
+ expect(result.content).toContain(
+ '- lobehub-database β†’ LOBEHUB_DATABASE_URL, CLOUD_DATABASE_URL, MARKET_DATABASE_URL',
+ );
+ expect(result.content).toContain('- deepseek β†’ DEEPSEEK_API_KEY');
+ expect(result.unattributedEnvVars).toEqual([]);
+ expect(result.content).not.toContain('******');
+ });
+
+ it('lists names it cannot attribute instead of guessing', () => {
+ const result = buildInjectCredsResult(['a', 'b'], {
+ credentials: { env: { A_1: 'x', B_1: 'y' } },
+ });
+
+ expect(result.envVarsByKey).toEqual({});
+ expect(result.content).toContain('- (unattributed) β†’ A_1, B_1');
+ });
+
+ it('includes file paths and keeps the not-found and unsupported notes', () => {
+ const result = buildInjectCredsResult(['gcp', 'missing', 'header'], {
+ credentials: {
+ env: {},
+ files: [{ filename: 'sa.json', key: 'gcp', path: '~/.creds/files/sa.json' }],
+ },
+ notFound: ['missing'],
+ unsupportedInSandbox: ['header'],
+ });
+
+ expect(result.content).toBe(
+ [
+ 'Credentials injected successfully: gcp, header.',
+ 'Injected per key (variable names only, values are never shown):',
+ '- gcp β†’ file ~/.creds/files/sa.json',
+ 'Not found: missing. Please configure them in Settings > Credentials. Not supported in sandbox: header.',
+ ].join('\n'),
+ );
+ expect(result.notFound).toEqual(['missing']);
+ });
+
+ it('passes the credentials on with every env value redacted', () => {
+ const files = [{ filename: 'key.json', key: 'gcp', path: '~/.creds/files/key.json' }];
+ const result = buildInjectCredsResult(['deepseek', 'gcp'], {
+ credentials: { env: { DEEPSEEK_API_KEY: 'sk******ab' }, files },
+ envVarsByKey: { deepseek: ['DEEPSEEK_API_KEY'] },
+ });
+
+ expect(result.credentials).toEqual({ env: { DEEPSEEK_API_KEY: '******' }, files });
+ expect(JSON.stringify(result)).not.toContain('sk******ab');
+ });
+
+ describe('credential keys named like Object.prototype members', () => {
+ it('does not read an inherited property for a file-only key', () => {
+ const result = buildInjectCredsResult(['constructor'], {
+ credentials: {
+ env: {},
+ files: [{ filename: 'sa.json', key: 'constructor', path: '~/.creds/files/sa.json' }],
+ },
+ });
+
+ expect(result.content).toBe(
+ [
+ 'Credentials injected successfully: constructor.',
+ 'Injected per key (variable names only, values are never shown):',
+ '- constructor β†’ file ~/.creds/files/sa.json',
+ ].join('\n'),
+ );
+ expect(result.envVarsByKey).toEqual({});
+ });
+
+ it('ignores inherited entries of the server-resolved mapping', () => {
+ const result = buildInjectCredsResult(['hasOwnProperty', 'deepseek'], {
+ credentials: { env: { DEEPSEEK_API_KEY: 'sk******ab' } },
+ envVarsByKey: { deepseek: ['DEEPSEEK_API_KEY'] },
+ });
+
+ expect(result.envVarsByKey).toEqual({ deepseek: ['DEEPSEEK_API_KEY'] });
+ expect(result.content).toContain('- deepseek β†’ DEEPSEEK_API_KEY');
+ expect(result.content).not.toContain('hasOwnProperty β†’');
+ });
+
+ it('keeps a `__proto__` key as an own, serializable entry', () => {
+ const result = buildInjectCredsResult(['__proto__'], {
+ credentials: { env: { PROTO_TOKEN: 'ab******cd' } },
+ });
+
+ expect(Object.hasOwn(result.envVarsByKey, '__proto__')).toBe(true);
+ expect(JSON.stringify(result.envVarsByKey)).toBe('{"__proto__":["PROTO_TOKEN"]}');
+ expect(result.unattributedEnvVars).toEqual([]);
+ expect(result.content).toContain('- __proto__ β†’ PROTO_TOKEN');
+ });
+ });
+});
diff --git a/packages/builtin-tool-creds/src/injectResult.ts b/packages/builtin-tool-creds/src/injectResult.ts
new file mode 100644
index 00000000000..1a4bbba5bac
--- /dev/null
+++ b/packages/builtin-tool-creds/src/injectResult.ts
@@ -0,0 +1,152 @@
+/**
+ * Shapes the `injectCredsToSandbox` result shared by the server runtime and
+ * the client executor.
+ *
+ * The result names every environment variable each credential key put into
+ * the sandbox, so the agent can tell which variable a key maps to without
+ * searching its env for it. Only the variable names are given. Values never
+ * appear in the content: Market masks the `credentials.env` values, and even
+ * masked fragments do not belong in the model's context.
+ */
+
+export interface InjectCredsResultInput {
+ credentials?: {
+ env?: Record<string, string>;
+ files?: Array<{ filename: string; key: string; path: string }>;
+ };
+ /**
+ * Environment variable names per credential key, resolved by the server
+ * when one call injected several keys. Without it, only a single-key
+ * injection can be attributed (every variable came from that key).
+ */
+ envVarsByKey?: Record<string, string[]>;
+ notFound?: string[];
+ unsupportedInSandbox?: string[];
+}
+
+export interface InjectCredsResultSummary {
+ content: string;
+ /**
+ * `credentials` with every env value replaced by `******`. Market's masked
+ * values keep the first and last two characters, which are still part of
+ * the value, so they are not passed on in the tool state either.
+ */
+ credentials: NonNullable<InjectCredsResultInput['credentials']>;
+ /** Environment variable names per injected key (names only, never values). */
+ envVarsByKey: Record<string, string[]>;
+ injected: string[];
+ notFound: string[];
+ /** Variable names that could not be attributed to a single key. */
+ unattributedEnvVars: string[];
+ unsupportedInSandbox: string[];
+}
+
+const unique = (names: string[]) => [...new Set(names)];
+
+export const REDACTED_VALUE = '******';
+
+const redactCredentials = (
+ credentials: InjectCredsResultInput['credentials'] = {},
+): NonNullable<InjectCredsResultInput['credentials']> => ({
+ ...credentials,
+ ...(credentials.env && {
+ env: Object.fromEntries(Object.keys(credentials.env).map((name) => [name, REDACTED_VALUE])),
+ }),
+});
+
+/**
+ * Credential keys are user-chosen strings, so a key such as `constructor` or
+ * `__proto__` must never resolve to an `Object.prototype` member. Keys are
+ * held in a `Map` and the server mapping is read by own property only.
+ */
+const resolveEnvNamesByKey = (
+ injected: string[],
+ input: Pick<InjectCredsResultInput, 'credentials' | 'envVarsByKey'>,
+): { byKey: Map<string, string[]>; unattributedEnvVars: string[] } => {
+ const envNames = Object.keys(input.credentials?.env ?? {});
+ const byKey = new Map<string, string[]>();
+ const resolved = input.envVarsByKey;
+
+ if (resolved) {
+ for (const key of injected) {
+ const names = Object.hasOwn(resolved, key) ? resolved[key] : undefined;
+ if (Array.isArray(names) && names.length > 0) byKey.set(key, unique(names));
+ }
+ } else if (injected.length === 1 && envNames.length > 0) {
+ byKey.set(injected[0], envNames);
+ }
+
+ const attributed = new Set([...byKey.values()].flat());
+ return {
+ byKey,
+ unattributedEnvVars: envNames.filter((name) => !attributed.has(name)),
+ };
+};
+
+export const resolveEnvVarsByKey = (
+ injected: string[],
+ input: Pick<InjectCredsResultInput, 'credentials' | 'envVarsByKey'>,
+): { envVarsByKey: Record<string, string[]>; unattributedEnvVars: string[] } => {
+ const { byKey, unattributedEnvVars } = resolveEnvNamesByKey(injected, input);
+ // `Object.fromEntries` defines own properties, so even `__proto__` stays a key.
+ return { envVarsByKey: Object.fromEntries(byKey), unattributedEnvVars };
+};
+
+export const buildInjectCredsResult = (
+ keys: string[],
+ input: InjectCredsResultInput,
+): InjectCredsResultSummary => {
+ const notFound = input.notFound ?? [];
+ const unsupportedInSandbox = input.unsupportedInSandbox ?? [];
+ const injected = keys.filter((k) => !notFound.includes(k));
+ const { byKey, unattributedEnvVars } = resolveEnvNamesByKey(
+ injected.filter((k) => !unsupportedInSandbox.includes(k)),
+ input,
+ );
+
+ const lines: string[] = [];
+ if (injected.length > 0) {
+ lines.push(`Credentials injected successfully: ${injected.join(', ')}.`);
+ }
+
+ const filesByKey = new Map<string, string[]>();
+ for (const file of input.credentials?.files ?? []) {
+ filesByKey.set(file.key, [...(filesByKey.get(file.key) ?? []), file.path]);
+ }
+
+ const mappingLines: string[] = [];
+ for (const key of injected) {
+ const parts: string[] = [];
+ const names = byKey.get(key);
+ if (names?.length) parts.push(names.join(', '));
+ const files = filesByKey.get(key);
+ if (files?.length) parts.push(`file ${files.join(', ')}`);
+ if (parts.length > 0) mappingLines.push(`- ${key} β†’ ${parts.join('; ')}`);
+ }
+ if (unattributedEnvVars.length > 0) {
+ mappingLines.push(`- (unattributed) β†’ ${unattributedEnvVars.join(', ')}`);
+ }
+ if (mappingLines.length > 0) {
+ lines.push('Injected per key (variable names only, values are never shown):', ...mappingLines);
+ }
+
+ let tail = '';
+ if (notFound.length > 0) {
+ tail += ` Not found: ${notFound.join(', ')}. Please configure them in Settings > Credentials.`;
+ }
+ if (unsupportedInSandbox.length > 0) {
+ tail += ` Not supported in sandbox: ${unsupportedInSandbox.join(', ')}.`;
+ }
+
+ const content = [lines.join('\n'), tail.trim()].filter(Boolean).join('\n');
+
+ return {
+ content: content.trim(),
+ credentials: redactCredentials(input.credentials),
+ envVarsByKey: Object.fromEntries(byKey),
+ injected,
+ notFound,
+ unattributedEnvVars,
+ unsupportedInSandbox,
+ };
+};
diff --git a/packages/builtin-tool-creds/src/systemRole.ts b/packages/builtin-tool-creds/src/systemRole.ts
index 2a2773c8f93..e408cce6059 100644
--- a/packages/builtin-tool-creds/src/systemRole.ts
+++ b/packages/builtin-tool-creds/src/systemRole.ts
@@ -27,7 +27,7 @@ Cloud sandbox reachable for credential injection: {{creds_sandbox_reachable}}
<tooling>
- **initiateOAuthConnect**: Start OAuth authorization flow for third-party services. Returns an authorization URL for the user to click.
-- **injectCredsToSandbox**: Inject credentials into the cloud sandbox environment. Only useful when \`{{creds_sandbox_reachable}}\` is \`true\` β€” see \`<sandbox_integration>\` for why this differs from \`sandbox_enabled\`.
+- **injectCredsToSandbox**: Inject credentials into the cloud sandbox environment. Only useful when \`{{creds_sandbox_reachable}}\` is \`true\` β€” see \`<sandbox_integration>\` for why this differs from \`sandbox_enabled\`. Its result lists, per key, the environment variable names that key set (names only, never values) β€” use those names instead of searching the environment.
- **requestCredsInput**: Ask the user to enter a credential in a secure form. The form saves the values to encrypted storage directly; you never see them and only get back the credential key.
- Parameters: \`key\` (unique identifier, lowercase with hyphens), \`name\` (display name), \`type\` ("kv-env" or "kv-header"), \`fieldNames\` (names of the values to fill in), \`description\` (optional)
- Example: \`requestCredsInput({ key: "openai", name: "OpenAI API Key", type: "kv-env", fieldNames: ["OPENAI_API_KEY"] })\`
@@ -83,7 +83,7 @@ When \`{{creds_sandbox_reachable}}\` is \`false\`, this run is routed to a devic
- Credentials are already automatically available as environment variables in every command's execution context β€” do not attempt to locate, cat, or source any credential file yourself. Doing so is unnecessary and will not give you real values.
**Credential Storage Locations:**
-- **Environment-based credentials** (oauth, kv-env, kv-header): Automatically available as environment variables in every command you run via \`runCommand\`/\`execScript\` β€” you do NOT need to \`source\` anything yourself, and there is no credential file you need to read, export, or locate. \`~/.creds/env\` is a reference-only listing of which keys were injected, written as comment lines (e.g. \`# API_KEY=8f******vZ\`) β€” these are NOT real shell variables, the values shown are intentionally masked, and the file cannot be sourced or used for authentication. Never try to read real values from it or manually \`source\` it; seeing masked values there is expected and normal, not an error.
+- **Environment-based credentials** (oauth, kv-env, kv-header): Automatically available as environment variables in every command you run via \`runCommand\`/\`execScript\` β€” you do NOT need to \`source\` anything yourself, and there is no credential file you need to read, export, or locate. \`~/.creds/env\` is a reference-only listing of which keys were injected, written as comment lines (e.g. \`# API_KEY=******\`) β€” these are NOT real shell variables, the values shown are intentionally masked, and the file cannot be sourced or used for authentication. Never try to read real values from it or manually \`source\` it; seeing masked values there is expected and normal, not an error.
- **File-based credentials** (file): Extracted to \`~/.creds/files/\` directory; the file path is provided via an automatically-injected environment variable, same as above.
**Environment Variable Naming:**
diff --git a/packages/builtin-tool-creds/src/types.ts b/packages/builtin-tool-creds/src/types.ts
index d929e94b11e..a7ca649fa2e 100644
--- a/packages/builtin-tool-creds/src/types.ts
+++ b/packages/builtin-tool-creds/src/types.ts
@@ -76,6 +76,10 @@ export interface InjectCredsToSandboxParams {
}
export interface InjectCredsToSandboxState {
+ /**
+ * Environment variable names each injected key set (names only, never values)
+ */
+ envVarsByKey?: Record<string, string[]>;
/**
* Injected credential keys
*/