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(widget): inject LobeHub Market connector tokens through the sandbox egress proxy (#21573)

Arvin Xu174aee5509aa
diff --git a/apps/server/src/services/widget/__tests__/credentials.test.ts b/apps/server/src/services/widget/__tests__/credentials.test.ts
index b987a353c5e..6a6c133fd2b 100644
--- a/apps/server/src/services/widget/__tests__/credentials.test.ts
+++ b/apps/server/src/services/widget/__tests__/credentials.test.ts
@@ -86,7 +86,7 @@ describe('resolveWidgetEnv', () => {
expect(
await resolveWidgetEnv({} as any, personal, undefined, { connectorModel: model as any }),
- ).toEqual({});
+ ).toEqual({ env: {}, inject: [] });
expect(model.resolveByIdentifiers).not.toHaveBeenCalled();
});
@@ -95,7 +95,7 @@ describe('resolveWidgetEnv', () => {
connector({ credentials: { token: 'agent-tok', type: 'bearer' } }),
]);
- const env = await resolveWidgetEnv(
+ const { env } = await resolveWidgetEnv(
{} as any,
{ ...personal, agentId: 'agt_1' },
[{ connector: 'github', name: 'GITHUB_TOKEN' }],
@@ -142,7 +142,7 @@ describe('resolveWidgetEnv', () => {
it('uses an API-key connector whose tool sync never ran (status disconnected)', async () => {
const model = modelReturning([connector({ status: 'disconnected' })]);
- const env = await resolveWidgetEnv(
+ const { env } = await resolveWidgetEnv(
{} as any,
personal,
[{ connector: 'github', name: 'GITHUB_TOKEN' }],
@@ -171,7 +171,7 @@ describe('resolveWidgetEnv', () => {
});
it('leaves optional variables out when they cannot be resolved', async () => {
- const env = await resolveWidgetEnv(
+ const { env } = await resolveWidgetEnv(
{} as any,
workspace,
[{ connector: 'slack', name: 'SLACK_TOKEN', required: false }],
@@ -188,7 +188,7 @@ describe('resolveWidgetEnv', () => {
}),
]);
- const env = await resolveWidgetEnv(
+ const { env } = await resolveWidgetEnv(
{} as any,
personal,
[
@@ -244,7 +244,7 @@ describe('resolveWidgetEnv', () => {
});
it('lets the workspace owner use any workspace connector', async () => {
- const env = await resolveWidgetEnv({} as any, workspace, requirement, {
+ const { env } = await resolveWidgetEnv({} as any, workspace, requirement, {
connectorModel: modelReturning([teammates]) as any,
isWorkspaceOwner: vi.fn().mockResolvedValue(true),
});
@@ -255,7 +255,7 @@ describe('resolveWidgetEnv', () => {
it('lets the creator use their own workspace connector without an owner lookup', async () => {
const isWorkspaceOwner = vi.fn();
- const env = await resolveWidgetEnv({} as any, workspace, requirement, {
+ const { env } = await resolveWidgetEnv({} as any, workspace, requirement, {
connectorModel: modelReturning([connector({ workspaceId: 'ws1' })]) as any,
isWorkspaceOwner,
});
@@ -273,4 +273,163 @@ describe('resolveWidgetEnv', () => {
).rejects.toBeInstanceOf(ForbiddenWidgetCredentialsError);
});
});
+
+ describe('LobeHub Market connectors', () => {
+ const market = (overrides: Partial<DecryptedConnector> = {}) =>
+ connector({ credentials: null, sourceType: 'marketplace', ...overrides });
+ const github = [{ connector: 'github', name: 'GITHUB_TOKEN' }];
+ const placeholder = /^lh_ph_[\da-f]{32}$/;
+
+ it('exposes a placeholder and asks the egress proxy to inject the Market token', async () => {
+ const options = {
+ connectorModel: modelReturning([market()]) as any,
+ networkAllow: ['api.github.com'],
+ };
+
+ const first = await resolveWidgetEnv({} as any, personal, github, options);
+ const second = await resolveWidgetEnv({} as any, personal, github, options);
+
+ expect(first.env.GITHUB_TOKEN).toMatch(placeholder);
+ expect(second.env.GITHUB_TOKEN).not.toBe(first.env.GITHUB_TOKEN);
+ expect(first.inject).toEqual([
+ {
+ header: 'Authorization',
+ host: 'api.github.com',
+ prefix: 'Bearer ',
+ secretRef: { key: 'github' },
+ },
+ ]);
+ });
+
+ it('keeps a usable local secret over Market injection', async () => {
+ const result = await resolveWidgetEnv({} as any, personal, github, {
+ connectorModel: modelReturning([
+ market({ credentials: { token: 'local-tok', type: 'bearer' } }),
+ ]) as any,
+ networkAllow: ['api.github.com'],
+ });
+
+ expect(result).toEqual({ env: { GITHUB_TOKEN: 'local-tok' }, inject: [] });
+ });
+
+ it('fails, even for an optional variable, when the inject host is not allowed', async () => {
+ const error = await resolveWidgetEnv(
+ {} as any,
+ personal,
+ [{ connector: 'github', name: 'GITHUB_TOKEN', required: false }],
+ { connectorModel: modelReturning([market()]) as any, networkAllow: ['github.com'] },
+ ).catch((e) => e);
+
+ expect(error).toBeInstanceOf(MissingWidgetEnvError);
+ expect(error.message).toBe(
+ 'Missing required environment: GITHUB_TOKEN (connector "github" is a LobeHub Market connector: its token is sent as the Authorization header to api.github.com; add that host to manifest.network.allow)',
+ );
+ });
+
+ it('accepts an inject host covered by a wildcard allow entry', async () => {
+ const { inject } = await resolveWidgetEnv({} as any, personal, github, {
+ connectorModel: modelReturning([market()]) as any,
+ networkAllow: ['*.github.com'],
+ });
+
+ expect(inject.map((i) => i.host)).toEqual(['api.github.com']);
+ });
+
+ it('does not treat a Composio row as a Market connector', async () => {
+ const error = await resolveWidgetEnv(
+ {} as any,
+ personal,
+ [{ connector: 'notion', name: 'NOTION_TOKEN' }],
+ {
+ connectorModel: modelReturning([
+ market({
+ identifier: 'notion',
+ metadata: { composio: { appSlug: 'NOTION' } as any },
+ }),
+ ]) as any,
+ networkAllow: ['api.notion.com'],
+ },
+ ).catch((e) => e);
+
+ expect(error).toBeInstanceOf(MissingWidgetEnvError);
+ expect(error.missing).toEqual([
+ { connector: 'notion', name: 'NOTION_TOKEN', reason: 'connector_without_secret' },
+ ]);
+ });
+
+ it('asks for an inject host when the provider has no default', async () => {
+ const error = await resolveWidgetEnv(
+ {} as any,
+ personal,
+ [{ connector: 'posthog', name: 'POSTHOG_TOKEN' }],
+ { connectorModel: modelReturning([market({ identifier: 'posthog' })]) as any },
+ ).catch((e) => e);
+
+ expect(error.message).toBe(
+ 'Missing required environment: POSTHOG_TOKEN (connector "posthog" is a LobeHub Market connector with no default API host; set manifest.env[].inject.host to the API host the script calls)',
+ );
+ });
+
+ it('routes the token by the manifest override, without a prefix for other headers', async () => {
+ const { inject } = await resolveWidgetEnv(
+ {} as any,
+ personal,
+ [
+ {
+ connector: 'posthog',
+ inject: { header: 'X-Api-Key', host: ['us.posthog.com', '*.posthog.com'] },
+ name: 'POSTHOG_TOKEN',
+ },
+ ],
+ {
+ connectorModel: modelReturning([market({ identifier: 'posthog' })]) as any,
+ networkAllow: ['us.posthog.com', '*.posthog.com'],
+ },
+ );
+
+ expect(inject).toEqual([
+ { header: 'X-Api-Key', host: 'us.posthog.com', secretRef: { key: 'posthog' } },
+ { header: 'X-Api-Key', host: '*.posthog.com', secretRef: { key: 'posthog' } },
+ ]);
+ });
+
+ it('requires a wildcard inject host to be allowed verbatim', async () => {
+ const error = await resolveWidgetEnv(
+ {} as any,
+ personal,
+ [{ connector: 'github', inject: { host: '*.api.github.com' }, name: 'GITHUB_TOKEN' }],
+ { connectorModel: modelReturning([market()]) as any, networkAllow: ['*.github.com'] },
+ ).catch((e) => e);
+
+ expect(error.missing[0]).toMatchObject({
+ hosts: ['*.api.github.com'],
+ reason: 'inject_host_not_allowed',
+ });
+ });
+
+ it('injects one header per host when several variables share a connector', async () => {
+ const { env, inject } = await resolveWidgetEnv(
+ {} as any,
+ personal,
+ [
+ { connector: 'github', name: 'GITHUB_TOKEN' },
+ { connector: 'github', name: 'GH_TOKEN' },
+ ],
+ { connectorModel: modelReturning([market()]) as any, networkAllow: ['api.github.com'] },
+ );
+
+ expect(Object.keys(env)).toEqual(['GITHUB_TOKEN', 'GH_TOKEN']);
+ expect(inject).toHaveLength(1);
+ });
+
+ it("still refuses a teammate's Market connector to a non-owner author", async () => {
+ const error = await resolveWidgetEnv({} as any, workspace, github, {
+ connectorModel: modelReturning([market({ userId: 'u2', workspaceId: 'ws1' })]) as any,
+ isWorkspaceOwner: vi.fn().mockResolvedValue(false),
+ networkAllow: ['api.github.com'],
+ }).catch((e) => e);
+
+ expect(error).toBeInstanceOf(ForbiddenWidgetCredentialsError);
+ });
+ });
});
diff --git a/apps/server/src/services/widget/__tests__/executeRun.test.ts b/apps/server/src/services/widget/__tests__/executeRun.test.ts
new file mode 100644
index 00000000000..b8dc725a29b
--- /dev/null
+++ b/apps/server/src/services/widget/__tests__/executeRun.test.ts
@@ -0,0 +1,97 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { WidgetModel } from '@/database/models/widget';
+
+import { executeWidgetRun } from '../executeRun';
+
+vi.mock('@/database/models/widget', () => ({
+ WidgetModel: { finishRun: vi.fn(async () => ({ folded: false, run: { id: 'run-1' } })) },
+}));
+vi.mock('../metrics', () => ({ recordWidgetMetrics: vi.fn() }));
+
+const inject = [
+ {
+ header: 'Authorization',
+ host: 'api.github.com',
+ prefix: 'Bearer ',
+ secretRef: { key: 'github' },
+ },
+];
+
+const params = {
+ run: { id: 'run-1', trigger: 'manual' },
+ version: {
+ manifest: {
+ env: [{ connector: 'github', name: 'GITHUB_TOKEN' }],
+ network: { allow: ['api.github.com'] },
+ },
+ outputType: 'stat',
+ publishedByUserId: null,
+ runtime: 'node',
+ script: 'console.log("{}")',
+ userId: 'u1',
+ },
+ widget: {
+ agentId: null,
+ id: 'widget-1',
+ metricId: null,
+ projectId: null,
+ title: 'Stars',
+ userId: 'u1',
+ workspaceId: null,
+ },
+} as any;
+
+describe('executeWidgetRun', () => {
+ it('passes the allowlist to env resolution and forwards Market injects to the sandbox', async () => {
+ const resolveEnv = vi.fn(async () => ({
+ env: { GITHUB_TOKEN: 'lh_ph_0123456789abcdef' },
+ inject,
+ }));
+ const run = vi.fn(async () => ({
+ durationMs: 10,
+ exitCode: 0,
+ stderr: 'sent lh_ph_0123456789abcdef',
+ stdout: '{"type":"stat","value":1}',
+ timedOut: false,
+ }));
+
+ await executeWidgetRun({} as any, params, { resolveEnv, runner: { run } });
+
+ expect(resolveEnv).toHaveBeenCalledWith(
+ {},
+ expect.objectContaining({ authorUserId: 'u1' }),
+ params.version.manifest.env,
+ { networkAllow: ['api.github.com'] },
+ );
+ expect(run).toHaveBeenCalledWith(
+ expect.objectContaining({
+ env: { GITHUB_TOKEN: 'lh_ph_0123456789abcdef' },
+ network: { allow: ['api.github.com'], inject },
+ }),
+ );
+ // The placeholder is redacted like any env value; it never breaks the run.
+ expect(vi.mocked(WidgetModel.finishRun)).toHaveBeenCalledWith(
+ {},
+ 'run-1',
+ expect.objectContaining({ status: 'succeeded', stderr: 'sent [REDACTED:GITHUB_TOKEN]' }),
+ );
+ });
+
+ it('sends no inject list when nothing needs one', async () => {
+ const run = vi.fn(async () => ({
+ durationMs: 10,
+ exitCode: 0,
+ stderr: '',
+ stdout: '{"type":"stat","value":1}',
+ timedOut: false,
+ }));
+
+ await executeWidgetRun({} as any, params, {
+ resolveEnv: vi.fn(async () => ({ env: {}, inject: [] })),
+ runner: { run },
+ });
+
+ expect((run.mock.calls[0] as any[])[0].network).toEqual({ allow: ['api.github.com'] });
+ });
+});
diff --git a/apps/server/src/services/widget/__tests__/versionSchema.test.ts b/apps/server/src/services/widget/__tests__/versionSchema.test.ts
new file mode 100644
index 00000000000..24684b43363
--- /dev/null
+++ b/apps/server/src/services/widget/__tests__/versionSchema.test.ts
@@ -0,0 +1,26 @@
+import { describe, expect, it } from 'vitest';
+
+import { widgetManifestSchema } from '../versionSchema';
+
+const withInject = (inject: unknown) =>
+ widgetManifestSchema.safeParse({ env: [{ connector: 'github', inject, name: 'GITHUB_TOKEN' }] });
+
+describe('widgetManifestSchema env[].inject', () => {
+ it('accepts a host, a host list and wildcard hosts', () => {
+ expect(withInject({ host: 'api.github.com' }).success).toBe(true);
+ expect(
+ withInject({ header: 'X-Api-Key', host: ['us.posthog.com', '*.posthog.com'], prefix: '' })
+ .success,
+ ).toBe(true);
+ });
+
+ it.each([
+ [{ host: 'https://api.github.com' }],
+ [{ host: 'api.github.com/repos' }],
+ [{ host: [] }],
+ [{ header: 'Bad Header', host: 'api.github.com' }],
+ [{ host: 'api.github.com', prefix: 'Bearer \r\nX-Evil: 1' }],
+ ])('rejects %o', (inject) => {
+ expect(withInject(inject).success).toBe(false);
+ });
+});
diff --git a/apps/server/src/services/widget/credentials.ts b/apps/server/src/services/widget/credentials.ts
index e6e97b96df9..e40ddf2ef4d 100644
--- a/apps/server/src/services/widget/credentials.ts
+++ b/apps/server/src/services/widget/credentials.ts
@@ -7,6 +7,15 @@ import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';
import { ensureFreshConnectorToken } from '@/server/services/connector/tokens';
import { isWorkspacePrimaryOwner } from '@/server/services/workspacePermission';
+import {
+ buildMarketInjects,
+ createMarketPlaceholder,
+ isInjectHostAllowed,
+ isMarketOAuthConnector,
+ marketInjectTarget,
+} from './marketConnectorInject';
+import type { WidgetSandboxEgressInject } from './sandbox/types';
+
/** Ownership columns of the widget whose script needs credentials. */
export interface WidgetCredentialScope {
agentId: string | null;
@@ -27,8 +36,19 @@ export interface MissingWidgetEnv {
field?: string;
/** The connector's headers, for a requirement that did not pick exactly one. */
fields?: string[];
+ /** The header a Market connector's token is sent as. */
+ header?: string;
+ /** Inject hosts `manifest.network.allow` does not cover. */
+ hosts?: string[];
name: string;
- reason: 'ambiguous_field' | 'connector_not_connected' | 'no_source' | 'unknown_field';
+ reason:
+ | 'ambiguous_field'
+ | 'connector_not_connected'
+ | 'connector_without_secret'
+ | 'inject_host_not_allowed'
+ | 'no_inject_target'
+ | 'no_source'
+ | 'unknown_field';
}
export class MissingWidgetEnvError extends Error {
@@ -64,6 +84,15 @@ const describeMissing = (m: MissingWidgetEnv) => {
case 'connector_not_connected': {
return `${m.name} (connect "${m.connector}" for this widget's agent or workspace)`;
}
+ case 'connector_without_secret': {
+ return `${m.name} (connector "${m.connector}" is connected but holds no secret a script can read; reconnect it with a token or API key)`;
+ }
+ case 'inject_host_not_allowed': {
+ return `${m.name} (connector "${m.connector}" is a LobeHub Market connector: its token is sent as the ${m.header} header to ${m.hosts?.join(', ')}; add ${m.hosts && m.hosts.length > 1 ? 'these hosts' : 'that host'} to manifest.network.allow)`;
+ }
+ case 'no_inject_target': {
+ return `${m.name} (connector "${m.connector}" is a LobeHub Market connector with no default API host; set manifest.env[].inject.host to the API host the script calls)`;
+ }
case 'ambiguous_field': {
return `${m.name} (connector "${m.connector}" holds several headers; set "field" to one of: ${m.fields?.join(', ')})`;
}
@@ -124,6 +153,19 @@ export interface ResolveWidgetEnvOptions {
connectorModel?: Pick<ConnectorModel, 'resolveByIdentifiers' | 'update'>;
/** Injected for tests; defaults to the workspace's primary-owner check. */
isWorkspaceOwner?: (userId: string, workspaceId: string) => Promise<boolean>;
+ /**
+ * Hosts the run may reach (`manifest.network.allow`). A Market connector's
+ * inject hosts must all be covered; the allowlist is never widened here,
+ * since network hosts are part of what the user approves.
+ */
+ networkAllow?: string[];
+}
+
+export interface ResolvedWidgetEnv {
+ /** Variables exposed to the script: local secrets and Market placeholders. */
+ env: Record<string, string>;
+ /** Credential headers the sandbox's egress proxy adds for Market connectors. */
+ inject: WidgetSandboxEgressInject[];
}
/**
@@ -170,6 +212,13 @@ const mayInject = async (
* connector may be injected is decided by the script's author (see
* {@link mayInject}), not by who triggers the run.
*
+ * LobeHub Market OAuth connectors keep their token in Market; the local row
+ * only proves the connection (and passes the same scope and author checks).
+ * For those the variable holds a per-run placeholder and an `inject` entry
+ * asks the sandbox's egress proxy to set the real token as a header on the
+ * provider's API hosts, so the secret never reaches the script or this server.
+ * A connector row holding a usable local secret keeps injecting it directly.
+ *
* Throws `ForbiddenWidgetCredentialsError` when a declared connector resolves
* to one the author may not read, and `MissingWidgetEnvError` listing every
* required variable it could not fill; optional ones are left out.
@@ -179,9 +228,10 @@ export const resolveWidgetEnv = async (
scope: WidgetCredentialScope,
requirements: WidgetEnvRequirement[] | undefined,
options: ResolveWidgetEnvOptions = {},
-): Promise<Record<string, string>> => {
+): Promise<ResolvedWidgetEnv> => {
const env: Record<string, string> = {};
- if (!requirements?.length) return env;
+ const inject: WidgetSandboxEgressInject[] = [];
+ if (!requirements?.length) return { env, inject };
const connectorModel =
options.connectorModel ??
@@ -251,15 +301,53 @@ export const resolveWidgetEnv = async (
});
} else if (selection.secret) {
env[requirement.name] = selection.secret;
+ } else if (connector && isMarketOAuthConnector(connector)) {
+ // A manifest that cannot route the token is wrong whether or not the
+ // variable is optional, like an ambiguous field above.
+ const target = marketInjectTarget(requirement);
+ if (!target) {
+ missing.push({
+ connector: requirement.connector,
+ name: requirement.name,
+ reason: 'no_inject_target',
+ });
+ continue;
+ }
+ const uncovered = target.hosts.filter(
+ (host) => !isInjectHostAllowed(host, options.networkAllow ?? []),
+ );
+ if (uncovered.length > 0) {
+ missing.push({
+ connector: requirement.connector,
+ header: target.header,
+ hosts: uncovered,
+ name: requirement.name,
+ reason: 'inject_host_not_allowed',
+ });
+ continue;
+ }
+ env[requirement.name] = createMarketPlaceholder();
+ inject.push(...buildMarketInjects(connector.identifier, target));
} else if (required) {
missing.push({
connector: requirement.connector,
name: requirement.name,
- reason: 'connector_not_connected',
+ reason: connector ? 'connector_without_secret' : 'connector_not_connected',
});
}
}
if (missing.length > 0) throw new MissingWidgetEnvError(missing);
- return env;
+ return { env, inject: dedupeInjects(inject) };
+};
+
+/** Two variables backed by one connector need its header set only once per host. */
+const dedupeInjects = (injects: WidgetSandboxEgressInject[]) => {
+ const seen = new Set<string>();
+ return injects.filter((entry) => {
+ const id = `${entry.host}\n${entry.header.toLowerCase()}`;
+ if (seen.has(id)) return false;
+ seen.add(id);
+ return true;
+ });
};
diff --git a/apps/server/src/services/widget/executeRun.ts b/apps/server/src/services/widget/executeRun.ts
index a676d1e462c..8e58aac801b 100644
--- a/apps/server/src/services/widget/executeRun.ts
+++ b/apps/server/src/services/widget/executeRun.ts
@@ -9,7 +9,9 @@ import { GoalSubscriptionService } from '../goal/subscriptions';
import {
ForbiddenWidgetCredentialsError,
MissingWidgetEnvError,
+ type ResolvedWidgetEnv,
resolveWidgetEnv,
+ type ResolveWidgetEnvOptions,
type WidgetCredentialScope,
} from './credentials';
import { recordWidgetMetrics } from './metrics';
@@ -26,7 +28,8 @@ export type ResolveWidgetEnv = (
db: LobeChatDatabase,
scope: WidgetCredentialScope,
requirements: NonNullable<WidgetVersionRow['manifest']>['env'],
-) => Promise<Record<string, string>>;
+ options: Pick<ResolveWidgetEnvOptions, 'networkAllow'>,
+) => Promise<ResolvedWidgetEnv>;
export interface ExecuteWidgetRunDeps {
resolveEnv?: ResolveWidgetEnv;
@@ -75,13 +78,15 @@ const runInSandbox = async (
): Promise<RunOutcome> => {
const manifest = version.manifest ?? undefined;
const resolveEnv = deps.resolveEnv ?? resolveWidgetEnv;
+ const allow = manifest?.network?.allow ?? [];
let env: Record<string, string>;
+ let inject: ResolvedWidgetEnv['inject'];
try {
// Secrets go to whoever wrote the script: the publisher of a live
// version, the author of a draft.
const authorUserId = version.publishedByUserId ?? version.userId;
- env = await resolveEnv(
+ ({ env, inject } = await resolveEnv(
db,
{
agentId: widget.agentId,
@@ -91,7 +96,8 @@ const runInSandbox = async (
workspaceId: widget.workspaceId,
},
manifest?.env,
- );
+ { networkAllow: allow },
+ ));
} catch (error) {
if (error instanceof MissingWidgetEnvError) {
return { env: {}, error: { code: 'MISSING_ENV', message: error.message }, status: 'failed' };
@@ -118,7 +124,7 @@ const runInSandbox = async (
// The widget's owner (or its workspace) pays for and is rate limited on the run.
actor: { userId: widget.userId, workspaceId: widget.workspaceId },
env,
- network: { allow: manifest?.network?.allow ?? [] },
+ network: { allow, ...(inject.length > 0 ? { inject } : {}) },
runtime: version.runtime,
script: version.script,
subject: { id: widget.id, kind: 'widget' },
@@ -174,7 +180,8 @@ const runInSandbox = async (
* script's author may not read with `CREDENTIALS_FORBIDDEN`, both before
* any sandbox call;
* 2. execute the version's script on the sandbox with the manifest's network
- * allowlist;
+ * allowlist, plus the credential headers the egress proxy adds for LobeHub
+ * Market connectors (whose env variables only hold placeholders);
* 3. redact injected secrets (and well-known token shapes) from stdout / stderr
* before anything is parsed or persisted, then truncate the streams;
* 4. judge the result β€” timeout β†’ `timeout`; non-zero exit β†’ `NON_ZERO_EXIT`;
diff --git a/apps/server/src/services/widget/marketConnectorInject.ts b/apps/server/src/services/widget/marketConnectorInject.ts
new file mode 100644
index 00000000000..6ab6f91823c
--- /dev/null
+++ b/apps/server/src/services/widget/marketConnectorInject.ts
@@ -0,0 +1,101 @@
+import { randomBytes } from 'node:crypto';
+
+import { LOBEHUB_SKILL_PROVIDERS } from '@lobechat/const';
+import type { WidgetEnvRequirement } from '@lobechat/types';
+
+import type { DecryptedConnector } from '@/database/models/connector';
+
+import type { WidgetSandboxEgressInject } from './sandbox/types';
+
+/**
+ * Where the egress proxy sends a Market connector's token: the request header
+ * (with its literal prefix) set on calls to the provider's API hosts.
+ */
+export interface MarketConnectorInjectTarget {
+ header: string;
+ hosts: string[];
+ prefix?: string;
+}
+
+/**
+ * API hosts a Market OAuth connector's token is sent to by default. Only
+ * providers whose REST API takes the OAuth access token as a Bearer
+ * `Authorization` header on one well-known host are listed; anything else
+ * (e.g. PostHog, whose API host depends on the region) needs
+ * `manifest.env[].inject`.
+ */
+export const MARKET_CONNECTOR_INJECT_DEFAULTS: Record<string, MarketConnectorInjectTarget> = {
+ github: { header: 'Authorization', hosts: ['api.github.com'], prefix: 'Bearer ' },
+ linear: { header: 'Authorization', hosts: ['api.linear.app'], prefix: 'Bearer ' },
+ microsoft: { header: 'Authorization', hosts: ['graph.microsoft.com'], prefix: 'Bearer ' },
+ notion: { header: 'Authorization', hosts: ['api.notion.com'], prefix: 'Bearer ' },
+ twitter: { header: 'Authorization', hosts: ['api.x.com'], prefix: 'Bearer ' },
+ vercel: { header: 'Authorization', hosts: ['api.vercel.com'], prefix: 'Bearer ' },
+};
+
+const MARKET_CONNECTOR_IDS = new Set(LOBEHUB_SKILL_PROVIDERS.map((p) => p.id));
+
+/**
+ * A connector whose OAuth token lives in LobeHub Market rather than in
+ * `user_connectors.credentials`: the local row (created when the user connects
+ * through Market) only proves the connection exists in this scope. Composio
+ * rows share `sourceType: 'marketplace'` but carry their own runtime config.
+ */
+export const isMarketOAuthConnector = (connector: DecryptedConnector): boolean =>
+ connector.sourceType === 'marketplace' &&
+ !connector.metadata?.composio &&
+ MARKET_CONNECTOR_IDS.has(connector.identifier);
+
+/**
+ * The inject target for one requirement: the manifest's override, else the
+ * provider default. An override replaces the default whole; its header
+ * defaults to `Authorization`, with a `Bearer ` prefix only for that header.
+ */
+export const marketInjectTarget = (
+ requirement: WidgetEnvRequirement,
+): MarketConnectorInjectTarget | undefined => {
+ const override = requirement.inject;
+ if (override) {
+ const header = override.header ?? 'Authorization';
+ const prefix =
+ override.prefix ?? (header.toLowerCase() === 'authorization' ? 'Bearer ' : undefined);
+ const hosts = Array.isArray(override.host) ? override.host : [override.host];
+ return { header, hosts: hosts.map((h) => h.toLowerCase()), prefix };
+ }
+ return requirement.connector
+ ? MARKET_CONNECTOR_INJECT_DEFAULTS[requirement.connector]
+ : undefined;
+};
+
+/**
+ * Same coverage rule the sandbox applies: an exact inject host must be
+ * reachable under `allow`, a wildcard inject host must appear in it verbatim.
+ */
+export const isInjectHostAllowed = (host: string, allow: string[]): boolean => {
+ const patterns = allow.map((a) => a.toLowerCase());
+ if (host.startsWith('*.')) return patterns.includes(host);
+ return patterns.some((pattern) =>
+ pattern.startsWith('*.')
+ ? host.length > pattern.length - 1 && host.endsWith(pattern.slice(1))
+ : pattern === host,
+ );
+};
+
+export const buildMarketInjects = (
+ connectorIdentifier: string,
+ target: MarketConnectorInjectTarget,
+): WidgetSandboxEgressInject[] =>
+ target.hosts.map((host) => ({
+ header: target.header,
+ host,
+ ...(target.prefix ? { prefix: target.prefix } : {}),
+ secretRef: { key: connectorIdentifier },
+ }));
+
+/**
+ * The value a Market connector's env variable holds inside the sandbox. Not a
+ * secret: the egress proxy overwrites the configured header with the real
+ * token, so it only works when sent as that header to those hosts. Non-empty
+ * so `if (!token)` guards in scripts still pass.
+ */
+export const createMarketPlaceholder = () => `lh_ph_${randomBytes(16).toString('hex')}`;
diff --git a/apps/server/src/services/widget/sandbox/__tests__/market.test.ts b/apps/server/src/services/widget/sandbox/__tests__/market.test.ts
index 355afed250a..ec7f88216f8 100644
--- a/apps/server/src/services/widget/sandbox/__tests__/market.test.ts
+++ b/apps/server/src/services/widget/sandbox/__tests__/market.test.ts
@@ -61,6 +61,29 @@ describe('MarketWidgetSandboxRunner', () => {
);
});
+ it('forwards credential injects to the egress proxy without putting secrets in env', async () => {
+ const { runner, sandbox } = setup(async () => result);
+ const inject = [
+ {
+ header: 'Authorization',
+ host: 'api.github.com',
+ prefix: 'Bearer ',
+ secretRef: { key: 'github' },
+ },
+ ];
+
+ await runner.run({
+ ...request,
+ env: { GITHUB_TOKEN: 'lh_ph_placeholder' },
+ network: { allow: ['api.github.com'], inject },
+ });
+
+ expect(sandbox.run.mock.calls[0][0]).toMatchObject({
+ egress: { allow: ['api.github.com'], inject },
+ env: { GITHUB_TOKEN: 'lh_ph_placeholder' },
+ });
+ });
+
it('clamps the timeout and keeps non-zero exits and timeouts as results', async () => {
const { runner, sandbox } = setup(async () => ({ ...result, exitCode: 124, timedOut: true }));
diff --git a/apps/server/src/services/widget/sandbox/market.ts b/apps/server/src/services/widget/sandbox/market.ts
index 66a3a98bd0f..fe04db21d26 100644
--- a/apps/server/src/services/widget/sandbox/market.ts
+++ b/apps/server/src/services/widget/sandbox/market.ts
@@ -41,8 +41,9 @@ const describeMarketError = (error: MarketAPIError) => {
/**
* Widget sandbox behind Market's one-shot run endpoint (`sdk.sandbox.run`).
* Market authenticates the trusted-client token for the run's actor, rate
- * limits that account, and signs the request to the widget sandbox Worker,
- * which enforces the egress allowlist per run.
+ * limits that account, resolves `egress.inject` secret references against that
+ * account's credentials, and signs the request to the widget sandbox Worker,
+ * which enforces the egress allowlist and sets the injected headers per run.
*
* Market answers 200 for every script that ran β€” including non-zero exits and
* timeouts; the SDK throws `MarketAPIError` when the script did not run.
@@ -68,7 +69,10 @@ export class MarketWidgetSandboxRunner implements WidgetSandboxRunner {
try {
const result = await this.sandboxFor(request.actor).run(
{
- egress: { allow: request.network.allow },
+ egress: {
+ allow: request.network.allow,
+ ...(request.network.inject?.length ? { inject: request.network.inject } : {}),
+ },
env: request.env,
runtime: request.runtime,
script: request.script,
diff --git a/apps/server/src/services/widget/sandbox/types.ts b/apps/server/src/services/widget/sandbox/types.ts
index 6a0e2c04f06..1d3d50338aa 100644
--- a/apps/server/src/services/widget/sandbox/types.ts
+++ b/apps/server/src/services/widget/sandbox/types.ts
@@ -25,12 +25,30 @@ export interface WidgetSandboxSubject {
kind: 'widget';
}
+/**
+ * A credential header the provider's egress proxy sets on requests to `host`
+ * (overwriting whatever the script sent). The secret is referenced, never
+ * carried: the provider resolves `secretRef` against the actor's credentials,
+ * so it never enters the sandbox nor passes through this server.
+ */
+export interface WidgetSandboxEgressInject {
+ header: string;
+ /** Exact hostname or `*.domain`; must be covered by `network.allow`. */
+ host: string;
+ /** Literal prepended to the secret, e.g. `Bearer `. */
+ prefix?: string;
+ secretRef: { field?: string; key: string };
+}
+
export interface WidgetSandboxRunRequest {
actor: WidgetSandboxActor;
/** Variables exposed to this execution only; a provider must never persist them. */
env: Record<string, string>;
- /** Hostnames the script may reach; an empty list means no network at all. */
- network: { allow: string[] };
+ /**
+ * Hostnames the script may reach (an empty list means no network at all),
+ * plus the credential headers added on the way out.
+ */
+ network: { allow: string[]; inject?: WidgetSandboxEgressInject[] };
runtime: WidgetRuntime;
script: string;
subject: WidgetSandboxSubject;
diff --git a/apps/server/src/services/widget/versionSchema.ts b/apps/server/src/services/widget/versionSchema.ts
index becd69639a0..e43a0d0aee1 100644
--- a/apps/server/src/services/widget/versionSchema.ts
+++ b/apps/server/src/services/widget/versionSchema.ts
@@ -10,6 +10,16 @@ import { WIDGET_SANDBOX_MAX_TIMEOUT_MS } from './sandbox/types';
const envName = z.string().regex(/^[A-Z_]\w*$/i, 'env names must be valid shell identifiers');
+/** A hostname, or `*.domain` for its subdomains β€” the form `network.allow` takes. */
+const hostPattern = z
+ .string()
+ .min(1)
+ .max(253)
+ .regex(
+ /^(?:\*\.)?[\w-]+(?:\.[\w-]+)+$/,
+ 'hosts must be a hostname or *.domain, without scheme or path',
+ );
+
export const widgetManifestSchema = z.object({
description: z.string().max(2000).optional(),
env: z
@@ -18,6 +28,21 @@ export const widgetManifestSchema = z.object({
connector: z.string().min(1).optional(),
description: z.string().max(500).optional(),
field: z.string().min(1).max(200).optional(),
+ inject: z
+ .object({
+ header: z
+ .string()
+ .regex(/^[!#$%&'*+.^`|~\w-]+$/, 'inject.header must be a valid header name')
+ .max(100)
+ .optional(),
+ host: z.union([hostPattern, z.array(hostPattern).min(1).max(5)]),
+ prefix: z
+ .string()
+ .max(100)
+ .regex(/^[^\0\n\r]*$/, 'inject.prefix must be a single line')
+ .optional(),
+ })
+ .optional(),
name: envName,
required: z.boolean().optional(),
}),
diff --git a/packages/builtin-tool-dashboard/src/ExecutionRuntime/index.ts b/packages/builtin-tool-dashboard/src/ExecutionRuntime/index.ts
index 76aef749b34..fc75f2117a5 100644
--- a/packages/builtin-tool-dashboard/src/ExecutionRuntime/index.ts
+++ b/packages/builtin-tool-dashboard/src/ExecutionRuntime/index.ts
@@ -103,14 +103,14 @@ const ERROR_HINTS: Record<string, string> = {
INVALID_OUTPUT:
'The JSON does not match the output contract for this outputType; compare field names and types with the contract.',
MISSING_ENV:
- "A required variable has no source. If the message lists a connector's headers, set manifest.env[].field to the right one with updateWidgetDraft; otherwise tell the user which connector to connect for this agent or workspace β€” never ask for the secret in chat.",
+ "A declared variable could not be filled. If the message lists a connector's headers, set manifest.env[].field to the right one; if it asks to add a host to manifest.network.allow (a LobeHub Market connector such as github sends its token only as a header to its API host), add exactly that host; if it asks for manifest.env[].inject.host, set the provider's API host. Apply fixes with updateWidgetDraft and dry-run again. Only when it says to connect or reconnect a connector, tell the user which connector to connect for this agent or workspace β€” never ask for the secret in chat.",
NON_ZERO_EXIT: 'The script failed; read stderr, fix the script and dry-run again.',
OUTPUT_TOO_LARGE: 'Trim the output: fewer rows / items / points (use view.limit for display).',
OUTPUT_TYPE_MISMATCH: 'The printed "type" differs from the widget outputType; align them.',
PARTIAL_OUTPUT:
'The script reported an incomplete result (meta.complete=false). Fine if intended; otherwise fix the failing source.',
SANDBOX_BAD_REQUEST:
- 'The sandbox rejected the request; check runtime and manifest.timeoutMs (max 120000).',
+ 'The sandbox rejected the request; check runtime and manifest.timeoutMs (max 120000). "secret_not_found" means a LobeHub Market connector is not connected on Market for this account: ask the user to reconnect it.',
SANDBOX_ERROR: 'The sandbox itself failed, not the script. Retry the dry run once.',
SANDBOX_NOT_CONFIGURED:
'Script execution is not configured on this server. Tell the user; do not retry.',
diff --git a/packages/builtin-tool-dashboard/src/manifest.ts b/packages/builtin-tool-dashboard/src/manifest.ts
index ff59e86a45c..07a518f170d 100644
--- a/packages/builtin-tool-dashboard/src/manifest.ts
+++ b/packages/builtin-tool-dashboard/src/manifest.ts
@@ -43,7 +43,7 @@ const manifestSchema = {
properties: {
env: {
description:
- 'Secrets / variables the script reads from its environment. Each is injected from a connected account (connector) at run time and redacted from logs.',
+ 'Secrets / variables the script reads from its environment. Each is injected from a connected account (connector) at run time and redacted from logs. For a LobeHub Market connector the value is a placeholder that only works sent as the configured header (default Authorization: Bearer) to the provider API host, which must be in network.allow.',
items: {
additionalProperties: false,
properties: {
@@ -57,6 +57,24 @@ const manifestSchema = {
'For a connector holding several headers: which header to inject, e.g. "X-Api-Key" (case-insensitive). Required then; ignored for single-secret connectors.',
type: 'string',
},
+ inject: {
+ additionalProperties: false,
+ description:
+ 'LobeHub Market connectors only (github, linear, notion, vercel, …): their variable holds a placeholder and the sandbox sets the real token as `header` on requests to `host`. Defaults per provider (github β†’ Authorization: Bearer on api.github.com); set it only for another host or header. Every host must be in network.allow.',
+ properties: {
+ header: { description: 'Defaults to "Authorization".', type: 'string' },
+ host: {
+ description: 'API host (or list), exact or "*.domain".',
+ oneOf: [{ type: 'string' }, { items: { type: 'string' }, type: 'array' }],
+ },
+ prefix: {
+ description: 'Prepended to the token; defaults to "Bearer " for Authorization.',
+ type: 'string',
+ },
+ },
+ required: ['host'],
+ type: 'object',
+ },
name: { description: 'Variable name, e.g. GITHUB_TOKEN.', type: 'string' },
required: { type: 'boolean' },
},
diff --git a/packages/builtin-tool-dashboard/src/systemRole.ts b/packages/builtin-tool-dashboard/src/systemRole.ts
index 8c80e076cf3..2fd6918b9f7 100644
--- a/packages/builtin-tool-dashboard/src/systemRole.ts
+++ b/packages/builtin-tool-dashboard/src/systemRole.ts
@@ -33,7 +33,7 @@ Partial data: when one of several sources fails, still print the document with "
<script_rules>
- runtime: node (use the global fetch, no npm packages), python (standard library only, e.g. urllib.request, json), or bash (curl, jq may be absent). Keep scripts short, deterministic and idempotent: they run unattended on every refresh.
- Network is OFF unless manifest.network.allow lists the hostnames the script calls (e.g. ["api.github.com"]).
-- Secrets: never write a token, password or key into the script, manifest, title or description. Declare what the script needs in manifest.env, e.g. {"name":"GITHUB_TOKEN","connector":"github","required":true}; the platform injects it from the user's connected accounts at run time and redacts it from logs. Read it from the environment (process.env.GITHUB_TOKEN / os.environ["GITHUB_TOKEN"] / $GITHUB_TOKEN). When the connector holds several headers (e.g. an API key plus an app key), add "field" with the header to inject: {"name":"DD_API_KEY","connector":"datadog","field":"DD-API-KEY"}. If a run fails with MISSING_ENV naming several headers, set "field" to one of them with updateWidgetDraft; if it says the connector is not connected, tell the user which connector to connect β€” do not ask them to paste a secret into the chat.
+- Secrets: never write a token, password or key into the script, manifest, title or description. Declare what the script needs in manifest.env, e.g. {"name":"GITHUB_TOKEN","connector":"github","required":true}; the platform injects it from the user's connected accounts at run time and redacts it from logs. Read it from the environment (process.env.GITHUB_TOKEN / os.environ["GITHUB_TOKEN"] / $GITHUB_TOKEN). When the connector holds several headers (e.g. an API key plus an app key), add "field" with the header to inject: {"name":"DD_API_KEY","connector":"datadog","field":"DD-API-KEY"}. LobeHub Market connectors (github, linear, notion, vercel, microsoft, twitter, …) are declared the same way, but the variable only holds a placeholder: the platform replaces the request header with the real token on the way out. It works only when sent as that header to the provider's API host β€” e.g. GITHUB_TOKEN as "Authorization: Bearer $GITHUB_TOKEN" to api.github.com, which must also be in manifest.network.allow β€” never in a git clone URL, a query parameter, a request body or to another host. For another host or header add "inject": {"host":"api.example.com","header":"Authorization","prefix":"Bearer "}. If a run fails with MISSING_ENV naming several headers, set "field" to one of them with updateWidgetDraft; if it asks to add a host to manifest.network.allow, add it; if it says the connector is not connected, tell the user which connector to connect β€” do not ask them to paste a secret into the chat.
- Only read data. A widget must never create, modify or delete anything in external systems.
- manifest.schedule suggests the refresh cadence as a cron pattern ({"pattern":"*/30 * * * *"}); pick the slowest cadence that keeps the number useful (hourly is a good default). manifest.timeoutMs defaults to 30000 (max 120000).
- manifest.metric ({"key":"open_issues","unit":"issues"}) records a stat's value on every published run so the card gets a long-term trend line.
diff --git a/packages/types/src/widget/index.ts b/packages/types/src/widget/index.ts
index f49d655d9df..67f1a598ef7 100644
--- a/packages/types/src/widget/index.ts
+++ b/packages/types/src/widget/index.ts
@@ -135,11 +135,32 @@ export interface WidgetEnvRequirement {
* ignore it.
*/
field?: string;
+ /**
+ * Where the platform sends a LobeHub Market connector's token, overriding
+ * the provider default (e.g. GitHub β†’ `Authorization: Bearer …` on
+ * api.github.com). Market connectors never put the real token in the
+ * environment: the variable holds a placeholder and the sandbox's egress
+ * proxy sets `header` on requests to `host`. Every host must be listed in
+ * `manifest.network.allow`. Ignored for connectors holding a local secret.
+ */
+ inject?: WidgetEnvInject;
/** Environment variable name the script reads, e.g. 'GITHUB_TOKEN'. */
name: string;
required?: boolean;
}
+export interface WidgetEnvInject {
+ /** Request header to set; defaults to 'Authorization'. */
+ header?: string;
+ /** API host(s), exact or `*.domain`, e.g. 'api.github.com'. */
+ host: string | string[];
+ /**
+ * Literal prepended to the token; defaults to 'Bearer ' for the
+ * Authorization header and to nothing otherwise.
+ */
+ prefix?: string;
+}
+
/**
* Declarative contract stored beside the script: what it needs to run and how
* the platform should treat its output.