🤯 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
♻️ refactor(widget): run widget scripts through Market's one-shot sandbox (#20772)
Arvin Xu6a9d7f93223c
diff --git a/.env.example b/.env.exampleindex 8274ca5a0d3..ae6934c83c6 100644--- a/.env.example+++ b/.env.example@@ -266,18 +266,11 @@ OPENAI_API_KEY=sk-xxxxxxxxx# Optional terminal session lease in seconds for the Onlyboxes provider.# ONLYBOXES_LEASE_TTL_SEC=900-# Widget sandbox: executes widget scripts behind `POST {URL}/run`-# ({ script, runtime, env, network, timeoutMs }). Today the only provider is a-# Cloudflare Worker. Without URL + token, widget runs fail with-# SANDBOX_NOT_CONFIGURED. DASHBOARD_SANDBOX_URL / DASHBOARD_SANDBOX_TOKEN are-# still read as fallbacks.-# WIDGET_SANDBOX_URL=https://widget-sandbox.example.workers.dev-# WIDGET_SANDBOX_TOKEN=-# WIDGET_SANDBOX_PROVIDER=cloudflare-worker-# `boolean` (default) sends `network: true | false`, the only shape the current-# Worker accepts; set `allowlist` to send `network: { allow: [...hosts] }` to a-# Worker that enforces per-run hosts.-# WIDGET_SANDBOX_NETWORK_FORMAT=boolean+# Widget sandbox: widget scripts run through Market's one-shot endpoint+# (`POST {MARKET_BASE_URL}/api/v1/sandbox/runs`), which forwards them to the+# widget sandbox Worker (lobehub-biz/widget-sandbox). It needs only the Market+# trusted-client credentials (MARKET_TRUSTED_CLIENT_ID / _SECRET); without them+# widget runs fail with SANDBOX_NOT_CONFIGURED.# ######################################## ########### Plugin Service ############diff --git a/apps/desktop/pnpm-lock.yaml b/apps/desktop/pnpm-lock.yamlindex 398b5f2ba3e..e69e756540a 100644--- a/apps/desktop/pnpm-lock.yaml+++ b/apps/desktop/pnpm-lock.yaml@@ -654,11 +654,11 @@ importers:../../packages/types:dependencies:'@lobehub/market-sdk':- specifier: 0.42.0- version: 0.42.0([email protected])([email protected])+ specifier: 0.43.0+ version: 0.43.0([email protected])([email protected])'@lobehub/market-types':- specifier: ^1.17.1- version: 1.17.1+ specifier: ^1.19.0+ version: 1.19.0'@lobehub/ui':specifier: ^6.0.4version: 6.0.4(@lobehub/[email protected]([email protected]([email protected]))([email protected]))(@lobehub/[email protected])(@shikijs/[email protected])(@types/[email protected])(@types/[email protected])([email protected])([email protected])([email protected]([email protected]))([email protected]([email protected]([email protected]))([email protected]))([email protected]([email protected]))([email protected])([email protected])@@ -2168,16 +2168,13 @@ packages:react: 19.2.7react-dom: 19.2.7- '@lobehub/[email protected]':- resolution: {integrity: sha512-1c+hf2lP9tqX9qyg6+J5Q90dYqvdZz7agrYWB9h9tiEJdIS57bzFcSRJZzxUiesbQ7jmvS5a7kBMUwsd9kxzKw==}+ '@lobehub/[email protected]':+ resolution: {integrity: sha512-pe0+otQzPBoq9X/C1fEYkM6yjVToO7esnW4b1CrfAe8jj9OPm7QZxgM5sHh4uZ6SU95+oEjOBKCutQyvruY8ZA==}peerDependencies:zod: ^3.24.4- '@lobehub/[email protected]':- resolution: {integrity: sha512-jwY3nXyJaP4V3kBYQpnPMYgWC4LWW03g1BP+s43p4d7SMWJ/wlDwfENoIyDP5p9NFZPIPV4ajaWpidcW7iENOg==}-- '@lobehub/[email protected]':- resolution: {integrity: sha512-1xx+y4rtRpN0oplvJEC1WvmCymJoUNUJIR8wr/U+d/jgrPvJSb3as/NZRCUrxeFd6BDSlQHyJl12CwzFNA6ZAw==}+ '@lobehub/[email protected]':+ resolution: {integrity: sha512-t6384KeWcSii42kuOqZClhoMs4tus+bW/izoNq96p0M5CvTVxUjrqpmXcKQUK+bnOXMzqqcJZcCU/3hTmFz0lQ==}'@lobehub/[email protected]':resolution: {integrity: sha512-kkqq2nqwcqz+rV/eUPQ7vY1TQWHWZE3kQt1MsSLtNFLNXMoKYPiF+cdahP97uunWKtf2dB48q/nkSWaZzEKRSw==}@@ -9468,9 +9465,9 @@ snapshots:react: 19.2.7react-dom: 19.2.7([email protected])dependencies:- '@lobehub/market-types': 1.18.0+ '@lobehub/market-types': 1.19.0'@opentelemetry/api': 1.9.1debug: 4.4.3([email protected])jose: 6.2.12@@ -9479,11 +9476,7 @@ snapshots:transitivePeerDependencies:- supports-color- '@lobehub/[email protected]':- dependencies:- zod: 3.25.76-- '@lobehub/[email protected]':+ '@lobehub/[email protected]':dependencies:zod: 3.25.76diff --git a/apps/server/src/globalConfig/index.ts b/apps/server/src/globalConfig/index.tsindex 88bcb67feed..e15e6b9c085 100644--- a/apps/server/src/globalConfig/index.ts+++ b/apps/server/src/globalConfig/index.ts@@ -13,7 +13,6 @@ import { gatewayEnv } from '@/envs/gateway';import { imageEnv } from '@/envs/image';import { knowledgeEnv } from '@/envs/knowledge';import { langfuseEnv } from '@/envs/langfuse';-import { sandboxEnv } from '@/envs/sandbox';import { toolsEnv } from '@/envs/tools';import { parseSSOProviders } from '@/libs/better-auth/utils/server';import { OIDC_ISSUER_PATH } from '@/libs/oidc-provider/routes';@@ -206,10 +205,6 @@ export const getServerGlobalConfig = async () => {// resolver's own function so both sides read the raw value identically —// unset/invalid stays `undefined`, i.e. the resolver's default 64.toolNameMaxLength: parseToolNameMaxLength(toolsEnv.TOOL_NAME_MAX_LENGTH),- // Lets the widget publish review match the sandbox's real egress contract:- // unless the Worker enforces per-host allowlists, declared hosts are- // advisory and the review must say any host is reachable.- widgetSandboxNetworkFormat: sandboxEnv.WIDGET_SANDBOX_NETWORK_FORMAT,};return config;diff --git a/apps/server/src/services/widget/executeRun.ts b/apps/server/src/services/widget/executeRun.tsindex 2f220c76304..d9aa445c4a6 100644--- a/apps/server/src/services/widget/executeRun.ts+++ b/apps/server/src/services/widget/executeRun.ts@@ -106,6 +106,8 @@ const runInSandbox = async (try {const result = await deps.runner.run({+ // 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 ?? [] },runtime: version.runtime,diff --git a/apps/server/src/services/widget/sandbox/__tests__/cloudflareWorker.live.test.ts b/apps/server/src/services/widget/sandbox/__tests__/cloudflareWorker.live.test.tsdeleted file mode 100644index c574d1467c7..00000000000--- a/apps/server/src/services/widget/sandbox/__tests__/cloudflareWorker.live.test.ts+++ /dev/null@@ -1,64 +0,0 @@-// @vitest-environment node-/**- * Optional live check against the real widget sandbox Worker. Skipped unless- * both variables are set; inject the token from a local file, never inline it:- *- * WIDGET_SANDBOX_URL=https://<worker>.workers.dev \- * WIDGET_SANDBOX_TOKEN="$(cat /path/to/token)" \- * bunx vitest run apps/server/src/services/widget/sandbox/__tests__/cloudflareWorker.live.test.ts- *- * Node's fetch ignores HTTPS_PROXY; behind a proxy also set NODE_USE_ENV_PROXY=1.- */-import { describe, expect, it } from 'vitest';--import { parseWidgetOutput } from '../../outputContract';-import { redactSecrets } from '../../redact';-import { CloudflareWorkerSandboxRunner } from '../cloudflareWorker';--const url = process.env.WIDGET_SANDBOX_URL;-const token = process.env.WIDGET_SANDBOX_TOKEN;--describe.skipIf(!url || !token)('CloudflareWorkerSandboxRunner (live Worker)', () => {- const runner = new CloudflareWorkerSandboxRunner({- networkFormat:- process.env.WIDGET_SANDBOX_NETWORK_FORMAT === 'allowlist' ? 'allowlist' : 'boolean',- token,- url,- });-- it('echoes a stat through the real sandbox with an injected env', async () => {- const env = { ECHO_SECRET: 'live-echo-secret-value' };- const result = await runner.run({- env,- network: { allow: [] },- runtime: 'bash',- script: [- 'echo "debug: $ECHO_SECRET" >&2',- `echo '{"type":"stat","label":"echo","value":42}'`,- ].join('\n'),- subject: { id: 'live-check', kind: 'widget' },- timeoutMs: 60_000,- });-- expect(result.exitCode).toBe(0);- expect(result.timedOut).toBe(false);- expect(parseWidgetOutput(result.stdout, 'stat')).toMatchObject({- ok: true,- output: { label: 'echo', type: 'stat', value: 42 },- });- expect(redactSecrets(result.stderr, env).trim()).toBe('debug: [REDACTED:ECHO_SECRET]');- }, 120_000);-- it('reports a non-zero exit from the real sandbox', async () => {- const result = await runner.run({- env: {},- network: { allow: [] },- runtime: 'bash',- script: 'echo oops >&2; exit 3',- subject: { id: 'live-check', kind: 'widget' },- });-- expect(result).toMatchObject({ exitCode: 3, timedOut: false });- expect(result.stderr.trim()).toBe('oops');- }, 120_000);-});diff --git a/apps/server/src/services/widget/sandbox/__tests__/cloudflareWorker.test.ts b/apps/server/src/services/widget/sandbox/__tests__/cloudflareWorker.test.tsdeleted file mode 100644index 28f7dc04802..00000000000--- a/apps/server/src/services/widget/sandbox/__tests__/cloudflareWorker.test.ts+++ /dev/null@@ -1,162 +0,0 @@-import { describe, expect, it, vi } from 'vitest';--import { CloudflareWorkerSandboxRunner } from '../cloudflareWorker';-import {- WIDGET_SANDBOX_DEFAULT_TIMEOUT_MS,- WIDGET_SANDBOX_MAX_TIMEOUT_MS,- WidgetSandboxError,- type WidgetSandboxRunRequest,-} from '../types';--const URL = 'https://sandbox.example.workers.dev/';-const TOKEN = 'test-token';--const respond = (status: number, body: unknown) =>- vi.fn().mockImplementation(- async () =>- new Response(JSON.stringify(body), {- headers: { 'content-type': 'application/json' },- status,- }),- );--const runnerWith = (fetchImpl: ReturnType<typeof vi.fn>, networkFormat?: 'allowlist' | 'boolean') =>- new CloudflareWorkerSandboxRunner({- fetch: fetchImpl as unknown as typeof fetch,- networkFormat,- token: TOKEN,- url: URL,- });--const request = (overrides: Partial<WidgetSandboxRunRequest> = {}): WidgetSandboxRunRequest => ({- env: {},- network: { allow: [] },- runtime: 'node',- script: 'x',- subject: { id: 'widget-1', kind: 'widget' },- ...overrides,-});--describe('CloudflareWorkerSandboxRunner', () => {- it('posts the script with the full network allowlist and returns the streams', async () => {- const fetchImpl = respond(200, {- durationMs: 42,- exitCode: 0,- stderr: '',- stdout: '{"type":"stat","value":1}',- });-- const result = await runnerWith(fetchImpl, 'allowlist').run(- request({- env: { GITHUB_TOKEN: 'secret' },- network: { allow: ['api.github.com', 'gitlab.com'] },- script: 'console.log(1)',- timeoutMs: 10_000,- }),- );-- expect(result).toEqual({- durationMs: 42,- exitCode: 0,- stderr: '',- stdout: '{"type":"stat","value":1}',- timedOut: false,- });- const [url, init] = fetchImpl.mock.calls[0];- expect(url).toBe('https://sandbox.example.workers.dev/run');- expect(init.method).toBe('POST');- expect(init.headers.Authorization).toBe(`Bearer ${TOKEN}`);- expect(JSON.parse(init.body)).toEqual({- env: { GITHUB_TOKEN: 'secret' },- network: { allow: ['api.github.com', 'gitlab.com'] },- runtime: 'node',- script: 'console.log(1)',- timeoutMs: 10_000,- });- });-- it('collapses the allowlist to a boolean by default, the only shape the deployed Worker accepts', async () => {- const fetchImpl = respond(200, { exitCode: 0, stderr: '', stdout: '' });- const runner = runnerWith(fetchImpl);-- await runner.run(request({ network: { allow: ['api.github.com'] } }));- await runner.run(request());-- expect(JSON.parse(fetchImpl.mock.calls[0][1].body).network).toBe(true);- expect(JSON.parse(fetchImpl.mock.calls[1][1].body).network).toBe(false);- });-- it('defaults and clamps the timeout to what the Worker accepts', async () => {- const fetchImpl = respond(200, { exitCode: 0, stderr: '', stdout: '' });- const runner = runnerWith(fetchImpl);-- await runner.run(request());- await runner.run(request({ timeoutMs: 10 * 60_000 }));-- expect(JSON.parse(fetchImpl.mock.calls[0][1].body)).toMatchObject({- network: false,- timeoutMs: WIDGET_SANDBOX_DEFAULT_TIMEOUT_MS,- });- expect(JSON.parse(fetchImpl.mock.calls[1][1].body).timeoutMs).toBe(- WIDGET_SANDBOX_MAX_TIMEOUT_MS,- );- });-- it('reports a non-zero exit as a result, not an error', async () => {- const result = await runnerWith(- respond(200, { durationMs: 5, exitCode: 3, stderr: 'oops', stdout: '' }),- ).run(request({ runtime: 'bash', script: 'exit 3' }));-- expect(result).toMatchObject({ exitCode: 3, stderr: 'oops', timedOut: false });- });-- it('maps the Worker timeout answer to timedOut', async () => {- const result = await runnerWith(- respond(200, { durationMs: 1000, error: 'timeout', message: 'Command timed out' }),- ).run(request({ timeoutMs: 1000 }));-- expect(result).toMatchObject({ exitCode: 124, timedOut: true });- });-- it('fails clearly when the sandbox is not configured', async () => {- const fetchImpl = vi.fn();- const runner = new CloudflareWorkerSandboxRunner({- fetch: fetchImpl as unknown as typeof fetch,- });-- expect(runner.isConfigured).toBe(false);- await expect(runner.run(request())).rejects.toMatchObject({- code: 'SANDBOX_NOT_CONFIGURED',- message: expect.stringContaining('WIDGET_SANDBOX_URL'),- });- expect(fetchImpl).not.toHaveBeenCalled();- });-- it.each([- [401, { error: 'unauthorized' }, 'SANDBOX_UNAUTHORIZED'],- [400, { error: '`runtime` must be one of node | python | bash' }, 'SANDBOX_BAD_REQUEST'],- [500, { error: 'execution_failed', message: 'container crashed' }, 'SANDBOX_ERROR'],- ])('throws WidgetSandboxError on HTTP %i', async (status, body, code) => {- const error = await runnerWith(respond(status, body))- .run(request())- .catch((e) => e);-- expect(error).toBeInstanceOf(WidgetSandboxError);- expect(error.code).toBe(code);- expect(error.message).not.toContain(TOKEN);- });-- it('wraps network failures and unreadable bodies', async () => {- await expect(- runnerWith(vi.fn().mockRejectedValue(new TypeError('fetch failed'))).run(request()),- ).rejects.toMatchObject({- code: 'SANDBOX_ERROR',- message: 'Sandbox request failed: fetch failed',- });- await expect(- runnerWith(- vi.fn().mockResolvedValue(new Response('<html>bad gateway</html>', { status: 502 })),- ).run(request()),- ).rejects.toMatchObject({ code: 'SANDBOX_ERROR' });- });-});diff --git a/apps/server/src/services/widget/sandbox/__tests__/index.test.ts b/apps/server/src/services/widget/sandbox/__tests__/index.test.tsdeleted file mode 100644index 1ff96fb7ede..00000000000--- a/apps/server/src/services/widget/sandbox/__tests__/index.test.ts+++ /dev/null@@ -1,64 +0,0 @@-import { beforeEach, describe, expect, it, vi } from 'vitest';--describe('createWidgetSandboxRunner', () => {- beforeEach(() => {- vi.resetModules();- });-- it('defaults to the Cloudflare Worker provider with the boolean network format', async () => {- vi.doMock('@/envs/sandbox', () => ({- sandboxEnv: { WIDGET_SANDBOX_TOKEN: 'tok', WIDGET_SANDBOX_URL: 'https://w.example.dev' },- }));- const fetchImpl = vi- .fn()- .mockResolvedValue(- new Response(JSON.stringify({ exitCode: 0, stderr: '', stdout: '' }), { status: 200 }),- );- vi.stubGlobal('fetch', fetchImpl);-- const { CloudflareWorkerSandboxRunner, createWidgetSandboxRunner } = await import('../index');- const runner = createWidgetSandboxRunner();- expect(runner).toBeInstanceOf(CloudflareWorkerSandboxRunner);-- await runner.run({- env: {},- network: { allow: ['api.github.com'] },- runtime: 'node',- script: 'x',- subject: { id: 'w', kind: 'widget' },- });- expect(fetchImpl.mock.calls[0][0]).toBe('https://w.example.dev/run');- expect(JSON.parse(fetchImpl.mock.calls[0][1].body).network).toBe(true);- vi.unstubAllGlobals();- });-- it('honors the allowlist network format', async () => {- vi.doMock('@/envs/sandbox', () => ({- sandboxEnv: {- WIDGET_SANDBOX_NETWORK_FORMAT: 'allowlist',- WIDGET_SANDBOX_PROVIDER: 'cloudflare-worker',- WIDGET_SANDBOX_TOKEN: 'tok',- WIDGET_SANDBOX_URL: 'https://w.example.dev',- },- }));- const fetchImpl = vi- .fn()- .mockResolvedValue(- new Response(JSON.stringify({ exitCode: 0, stderr: '', stdout: '' }), { status: 200 }),- );- vi.stubGlobal('fetch', fetchImpl);-- const { createWidgetSandboxRunner } = await import('../index');- await createWidgetSandboxRunner().run({- env: {},- network: { allow: ['api.github.com'] },- runtime: 'node',- script: 'x',- subject: { id: 'w', kind: 'widget' },- });- expect(JSON.parse(fetchImpl.mock.calls[0][1].body).network).toEqual({- allow: ['api.github.com'],- });- vi.unstubAllGlobals();- });-});diff --git a/apps/server/src/services/widget/sandbox/__tests__/market.test.ts b/apps/server/src/services/widget/sandbox/__tests__/market.test.tsnew file mode 100644index 00000000000..355afed250a--- /dev/null+++ b/apps/server/src/services/widget/sandbox/__tests__/market.test.ts@@ -0,0 +1,119 @@+import { MarketAPIError } from '@lobehub/market-sdk';+import { describe, expect, it, vi } from 'vitest';++vi.mock('@/server/services/market', () => ({ MarketService: vi.fn() }));++const { MarketWidgetSandboxRunner } = await import('../market');+const { WIDGET_SANDBOX_DEFAULT_TIMEOUT_MS, WIDGET_SANDBOX_MAX_TIMEOUT_MS } =+ await import('../types');++const request = {+ actor: { userId: 'user-1', workspaceId: 'ws-1' },+ env: { REPO: 'lobehub/lobehub' },+ network: { allow: ['api.github.com'] },+ runtime: 'node' as const,+ script: 'console.log("ok")',+ subject: { id: 'widget-1', kind: 'widget' as const },+};++const result = {+ durationMs: 1800,+ exitCode: 0,+ runId: 'run-1',+ stderr: '',+ stdout: '{"type":"stat"}',+ timedOut: false,+ truncated: false,+};++const setup = (run: (...args: any[]) => Promise<unknown>) => {+ const sandbox = { run: vi.fn(run) };+ const sandboxFor = vi.fn(() => sandbox as any);+ const runner = new MarketWidgetSandboxRunner({ isEnabled: () => true, sandboxFor });+ return { runner, sandbox, sandboxFor };+};++const apiError = (status: number, body?: unknown) =>+ new MarketAPIError(status, 'Error', body as any);++describe('MarketWidgetSandboxRunner', () => {+ it('runs through the Market SDK as the widget actor and maps the result', async () => {+ const { runner, sandbox, sandboxFor } = setup(async () => result);++ await expect(runner.run(request)).resolves.toEqual({+ durationMs: 1800,+ exitCode: 0,+ stderr: '',+ stdout: '{"type":"stat"}',+ timedOut: false,+ });+ expect(sandboxFor).toHaveBeenCalledWith({ userId: 'user-1', workspaceId: 'ws-1' });+ expect(sandbox.run).toHaveBeenCalledWith(+ {+ egress: { allow: ['api.github.com'] },+ env: { REPO: 'lobehub/lobehub' },+ runtime: 'node',+ script: 'console.log("ok")',+ subject: { id: 'widget-1', kind: 'widget' },+ timeoutMs: WIDGET_SANDBOX_DEFAULT_TIMEOUT_MS,+ },+ { signal: expect.any(AbortSignal) },+ );+ });++ it('clamps the timeout and keeps non-zero exits and timeouts as results', async () => {+ const { runner, sandbox } = setup(async () => ({ ...result, exitCode: 124, timedOut: true }));++ await expect(runner.run({ ...request, timeoutMs: 999_999 })).resolves.toMatchObject({+ exitCode: 124,+ timedOut: true,+ });+ expect(sandbox.run.mock.calls[0][0].timeoutMs).toBe(WIDGET_SANDBOX_MAX_TIMEOUT_MS);+ });++ it('fails as not configured without trusted-client credentials, without calling Market', async () => {+ const sandboxFor = vi.fn();+ const runner = new MarketWidgetSandboxRunner({ isEnabled: () => false, sandboxFor });++ await expect(runner.run(request)).rejects.toMatchObject({ code: 'SANDBOX_NOT_CONFIGURED' });+ expect(sandboxFor).not.toHaveBeenCalled();+ });++ it.each([+ [503, { error: 'sandbox_not_configured' }, 'SANDBOX_NOT_CONFIGURED'],+ [401, { error: 'invalid_token' }, 'SANDBOX_UNAUTHORIZED'],+ [403, { error: 'forbidden_client' }, 'SANDBOX_UNAUTHORIZED'],+ [400, { error: 'invalid_request', error_description: 'bad host' }, 'SANDBOX_BAD_REQUEST'],+ [422, { error: 'secret_unusable' }, 'SANDBOX_BAD_REQUEST'],+ [429, { error: 'rate_limited' }, 'SANDBOX_ERROR'],+ [503, { error: 'sandbox_unavailable' }, 'SANDBOX_ERROR'],+ [500, undefined, 'SANDBOX_ERROR'],+ ])('maps HTTP %d %j to %s', async (status, body, code) => {+ const { runner } = setup(async () => {+ throw apiError(status, body);+ });++ await expect(runner.run(request)).rejects.toMatchObject({ code, name: 'WidgetSandboxError' });+ });++ it('keeps Market’s error code and description in the message', async () => {+ const { runner } = setup(async () => {+ throw apiError(400, { error: 'invalid_request', error_description: 'bad host' });+ });++ await expect(runner.run(request)).rejects.toMatchObject({+ message: expect.stringContaining('invalid_request: bad host'),+ });+ });++ it('turns a network failure into SANDBOX_ERROR', async () => {+ const { runner } = setup(async () => {+ throw new TypeError('fetch failed');+ });++ await expect(runner.run(request)).rejects.toMatchObject({+ code: 'SANDBOX_ERROR',+ message: expect.stringContaining('fetch failed'),+ });+ });+});diff --git a/apps/server/src/services/widget/sandbox/cloudflareWorker.ts b/apps/server/src/services/widget/sandbox/cloudflareWorker.tsdeleted file mode 100644index ef296d3417e..00000000000--- a/apps/server/src/services/widget/sandbox/cloudflareWorker.ts+++ /dev/null@@ -1,139 +0,0 @@-import debug from 'debug';--import {- clampSandboxTimeout,- WIDGET_SANDBOX_REQUEST_OVERHEAD_MS,- WidgetSandboxError,- type WidgetSandboxRunner,- type WidgetSandboxRunRequest,- type WidgetSandboxRunResult,-} from './types';--const log = debug('lobe-server:widget:sandbox');--/**- * How the request encodes the network allowlist:- *- * - `allowlist` — `network: { allow: ['api.github.com', …] }`, so the Worker- * can restrict egress to the declared hosts;- * - `boolean` — `network: allow.length > 0`, for a Worker that only- * understands an on/off switch (the original contract). Hosts are then not- * enforced by the sandbox.- */-export type CloudflareWorkerNetworkFormat = 'allowlist' | 'boolean';--export interface CloudflareWorkerSandboxRunnerOptions {- fetch?: typeof fetch;- networkFormat?: CloudflareWorkerNetworkFormat;- token?: string;- url?: string;-}--interface WorkerRunResponse {- durationMs?: number;- error?: string;- exitCode?: number;- message?: string;- stderr?: string;- stdout?: string;-}--/**- * Widget sandbox backed by a Cloudflare Worker- * (`POST {WIDGET_SANDBOX_URL}/run`, Bearer `WIDGET_SANDBOX_TOKEN`).- *- * Worker contract: request `{ script, runtime, env, network, timeoutMs }`,- * response `{ stdout, stderr, exitCode, durationMs }`; a script exceeding its- * timeout answers 200 with `error: 'timeout'` (exit code 124), an execution- * failure answers 500 with `error: 'execution_failed'`.- *- * `subject` is not sent: the Worker has no use for it and rejects nothing- * based on it.- */-export class CloudflareWorkerSandboxRunner implements WidgetSandboxRunner {- private readonly fetchImpl: typeof fetch;- private readonly networkFormat: CloudflareWorkerNetworkFormat;- private readonly token?: string;- private readonly url?: string;-- constructor(options: CloudflareWorkerSandboxRunnerOptions = {}) {- this.fetchImpl = options.fetch ?? fetch;- this.networkFormat = options.networkFormat ?? 'boolean';- this.token = options.token;- this.url = options.url?.replace(/\/+$/, '');- }-- get isConfigured() {- return !!this.url && !!this.token;- }-- async run(request: WidgetSandboxRunRequest): Promise<WidgetSandboxRunResult> {- if (!this.url || !this.token) {- throw new WidgetSandboxError(- 'SANDBOX_NOT_CONFIGURED',- 'Widget sandbox is not configured: set WIDGET_SANDBOX_URL and WIDGET_SANDBOX_TOKEN',- );- }-- const timeoutMs = clampSandboxTimeout(request.timeoutMs);- const allow = request.network.allow;- const body = {- env: request.env,- network: this.networkFormat === 'boolean' ? allow.length > 0 : { allow },- runtime: request.runtime,- script: request.script,- timeoutMs,- };-- let response: Response;- try {- response = await this.fetchImpl(`${this.url}/run`, {- body: JSON.stringify(body),- headers: {- 'Authorization': `Bearer ${this.token}`,- 'content-type': 'application/json',- },- method: 'POST',- signal: AbortSignal.timeout(timeoutMs + WIDGET_SANDBOX_REQUEST_OVERHEAD_MS),- });- } catch (error) {- const message = error instanceof Error ? error.message : String(error);- log('request failed: %s', message);- throw new WidgetSandboxError('SANDBOX_ERROR', `Sandbox request failed: ${message}`);- }-- const payload = (await response.json().catch(() => null)) as WorkerRunResponse | null;-- if (response.status === 401) {- throw new WidgetSandboxError('SANDBOX_UNAUTHORIZED', 'Sandbox rejected the credentials');- }- if (response.status === 400) {- throw new WidgetSandboxError(- 'SANDBOX_BAD_REQUEST',- `Sandbox rejected the request: ${payload?.error ?? 'bad request'}`,- );- }- if (!payload || typeof payload !== 'object') {- throw new WidgetSandboxError(- 'SANDBOX_ERROR',- `Sandbox returned an unreadable response (HTTP ${response.status})`,- );- }-- const timedOut = payload.error === 'timeout';- if (!response.ok && !timedOut) {- throw new WidgetSandboxError(- 'SANDBOX_ERROR',- `Sandbox execution failed (HTTP ${response.status}): ${payload.message ?? payload.error ?? 'unknown error'}`,- );- }-- return {- durationMs: typeof payload.durationMs === 'number' ? payload.durationMs : 0,- exitCode: typeof payload.exitCode === 'number' ? payload.exitCode : timedOut ? 124 : -1,- stderr: typeof payload.stderr === 'string' ? payload.stderr : '',- stdout: typeof payload.stdout === 'string' ? payload.stdout : '',- timedOut,- };- }-}diff --git a/apps/server/src/services/widget/sandbox/index.ts b/apps/server/src/services/widget/sandbox/index.tsindex a0a58afeaa8..09a23e3346d 100644--- a/apps/server/src/services/widget/sandbox/index.ts+++ b/apps/server/src/services/widget/sandbox/index.ts@@ -1,24 +1,12 @@-import { sandboxEnv } from '@/envs/sandbox';--import { CloudflareWorkerSandboxRunner } from './cloudflareWorker';+import { MarketWidgetSandboxRunner } from './market';import type { WidgetSandboxRunner } from './types';/**- * The widget sandbox selected by env (`WIDGET_SANDBOX_PROVIDER`, default- * `cloudflare-worker`). An unconfigured provider still returns a runner; its- * runs fail with `SANDBOX_NOT_CONFIGURED`, which closes the run as `failed`.+ * The widget sandbox: Market's one-shot run endpoint. Without Market+ * trusted-client credentials it still returns a runner; its runs fail with+ * `SANDBOX_NOT_CONFIGURED`, which closes the run as `failed`.*/-export const createWidgetSandboxRunner = (): WidgetSandboxRunner => {- switch (sandboxEnv.WIDGET_SANDBOX_PROVIDER ?? 'cloudflare-worker') {- case 'cloudflare-worker': {- return new CloudflareWorkerSandboxRunner({- networkFormat: sandboxEnv.WIDGET_SANDBOX_NETWORK_FORMAT,- token: sandboxEnv.WIDGET_SANDBOX_TOKEN,- url: sandboxEnv.WIDGET_SANDBOX_URL,- });- }- }-};+export const createWidgetSandboxRunner = (): WidgetSandboxRunner => new MarketWidgetSandboxRunner();-export { CloudflareWorkerSandboxRunner } from './cloudflareWorker';+export { MarketWidgetSandboxRunner } from './market';export * from './types';diff --git a/apps/server/src/services/widget/sandbox/market.ts b/apps/server/src/services/widget/sandbox/market.tsnew file mode 100644index 00000000000..66a3a98bd0f--- /dev/null+++ b/apps/server/src/services/widget/sandbox/market.ts@@ -0,0 +1,122 @@+import { MarketAPIError, type MarketSDK } from '@lobehub/market-sdk';+import debug from 'debug';++import { isTrustedClientEnabled } from '@/libs/trusted-client';+import { MarketService } from '@/server/services/market';++import {+ clampSandboxTimeout,+ WIDGET_SANDBOX_REQUEST_OVERHEAD_MS,+ type WidgetSandboxActor,+ WidgetSandboxError,+ type WidgetSandboxRunner,+ type WidgetSandboxRunRequest,+ type WidgetSandboxRunResult,+} from './types';++const log = debug('lobe-server:widget:sandbox');++type SandboxClient = Pick<MarketSDK['sandbox'], 'run'>;++export interface MarketWidgetSandboxRunnerOptions {+ /** Defaults to `isTrustedClientEnabled`: Market only accepts trusted clients here. */+ isEnabled?: () => boolean;+ /** Defaults to the Market SDK acting as the run's actor. */+ sandboxFor?: (actor: WidgetSandboxActor) => SandboxClient;+}++const defaultSandboxFor = (actor: WidgetSandboxActor): SandboxClient =>+ new MarketService({+ userInfo: { userId: actor.userId, workspaceId: actor.workspaceId ?? undefined },+ }).market.sandbox;++/** Market's error body: `{ error: '<code>', error_description?: '…' }`. */+const describeMarketError = (error: MarketAPIError) => {+ const body = error.errorBody as { error?: unknown; error_description?: unknown } | undefined;+ const code = typeof body?.error === 'string' ? body.error : (error.code ?? 'unknown_error');+ const detail = typeof body?.error_description === 'string' ? body.error_description : undefined;+ return { code, message: detail ? `${code}: ${detail}` : code };+};++/**+ * 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.+ *+ * Market answers 200 for every script that ran — including non-zero exits and+ * timeouts; the SDK throws `MarketAPIError` when the script did not run.+ */+export class MarketWidgetSandboxRunner implements WidgetSandboxRunner {+ private readonly isEnabled: () => boolean;+ private readonly sandboxFor: (actor: WidgetSandboxActor) => SandboxClient;++ constructor(options: MarketWidgetSandboxRunnerOptions = {}) {+ this.isEnabled = options.isEnabled ?? isTrustedClientEnabled;+ this.sandboxFor = options.sandboxFor ?? defaultSandboxFor;+ }++ async run(request: WidgetSandboxRunRequest): Promise<WidgetSandboxRunResult> {+ if (!this.isEnabled()) {+ throw new WidgetSandboxError(+ 'SANDBOX_NOT_CONFIGURED',+ 'Widget sandbox is not configured: Market trusted-client credentials are missing',+ );+ }++ const timeoutMs = clampSandboxTimeout(request.timeoutMs);+ try {+ const result = await this.sandboxFor(request.actor).run(+ {+ egress: { allow: request.network.allow },+ env: request.env,+ runtime: request.runtime,+ script: request.script,+ subject: request.subject,+ timeoutMs,+ },+ { signal: AbortSignal.timeout(timeoutMs + WIDGET_SANDBOX_REQUEST_OVERHEAD_MS) },+ );++ return {+ durationMs: result.durationMs,+ exitCode: result.exitCode,+ stderr: result.stderr,+ stdout: result.stdout,+ timedOut: result.timedOut,+ };+ } catch (error) {+ if (!(error instanceof MarketAPIError)) {+ const message = error instanceof Error ? error.message : String(error);+ log('request failed: %s', message);+ throw new WidgetSandboxError('SANDBOX_ERROR', `Sandbox request failed: ${message}`);+ }++ const { code, message } = describeMarketError(error);+ log('market responded status=%d error=%s', error.status, code);++ if (code === 'sandbox_not_configured') {+ throw new WidgetSandboxError(+ 'SANDBOX_NOT_CONFIGURED',+ 'Widget sandbox is not configured on Market',+ );+ }+ if (error.status === 401 || error.status === 403) {+ throw new WidgetSandboxError(+ 'SANDBOX_UNAUTHORIZED',+ `Sandbox rejected the credentials (${message})`,+ );+ }+ if (error.status === 400 || error.status === 422) {+ throw new WidgetSandboxError(+ 'SANDBOX_BAD_REQUEST',+ `Sandbox rejected the request: ${message}`,+ );+ }+ throw new WidgetSandboxError(+ 'SANDBOX_ERROR',+ `Sandbox could not run the script (HTTP ${error.status}): ${message}`,+ );+ }+ }+}diff --git a/apps/server/src/services/widget/sandbox/types.ts b/apps/server/src/services/widget/sandbox/types.tsindex 23571ea2d43..6a0e2c04f06 100644--- a/apps/server/src/services/widget/sandbox/types.ts+++ b/apps/server/src/services/widget/sandbox/types.ts@@ -7,8 +7,18 @@ export const WIDGET_SANDBOX_DEFAULT_TIMEOUT_MS = 30_000;export const WIDGET_SANDBOX_REQUEST_OVERHEAD_MS = 60_000;/**- * What the execution belongs to, for provider-side attribution, quotas and- * log correlation. Never used for authorization — the caller already decided.+ * Whose account the execution runs on: Market authenticates, rate limits and+ * bills it as this user (or as the workspace's organization). The caller has+ * already decided the run is allowed.+ */+export interface WidgetSandboxActor {+ userId: string;+ workspaceId?: string | null;+}++/**+ * What the execution belongs to, for provider-side attribution and log+ * correlation. Never used for authorization — the caller already decided.*/export interface WidgetSandboxSubject {id: string;@@ -16,6 +26,7 @@ export interface WidgetSandboxSubject {}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. */@@ -36,10 +47,9 @@ export interface WidgetSandboxRunResult {}/**- * Executes one widget script in isolation. Provider-agnostic on purpose: the- * execution layer is moving to the lobehub-market service (a one-shot,- * Cloudflare-backed run endpoint), so callers depend only on this contract- * and the implementation is picked by `WIDGET_SANDBOX_PROVIDER`.+ * Executes one widget script in isolation. The only implementation forwards to+ * Market's one-shot run endpoint, which runs it on the widget sandbox Worker+ * (lobehub-biz/widget-sandbox); callers depend only on this contract.** A script that runs and exits non-zero, or times out, is a normal result —* judging it is the caller's job. Implementations throw `WidgetSandboxError`diff --git a/locales/en-US/dashboard.json b/locales/en-US/dashboard.jsonindex 1511d25f18d..ec89cdff732 100644--- a/locales/en-US/dashboard.json+++ b/locales/en-US/dashboard.json@@ -101,7 +101,6 @@"publish.intro": "Once published, this script runs on its schedule with the listed credentials and its result shows on dashboards.","publish.network": "Network","publish.networkNone": "No network access",- "publish.networkUnrestricted": "The sandbox cannot restrict egress to the listed hosts — the script can reach any host, including ones it did not declare.","publish.noSuccessfulRun": "This draft has not succeeded in a dry run yet, so publishing it will be refused.","publish.previewTitle": "Latest dry run","publish.schedule": "Refresh",diff --git a/locales/zh-CN/dashboard.json b/locales/zh-CN/dashboard.jsonindex 09b5669d2a7..0fea6a332a6 100644--- a/locales/zh-CN/dashboard.json+++ b/locales/zh-CN/dashboard.json@@ -101,7 +101,6 @@"publish.intro": "发布后,该脚本将使用下列凭证按计划运行,结果会显示在看板上。","publish.network": "网络","publish.networkNone": "无网络访问",- "publish.networkUnrestricted": "沙箱无法将出口限制为所列主机——脚本可以访问任意主机,包括未声明的主机。","publish.noSuccessfulRun": "该草稿尚未试运行成功,发布将被拒绝。","publish.previewTitle": "最近一次试运行","publish.schedule": "刷新频率",diff --git a/package.json b/package.jsonindex ac67fea4916..c9ff8f534c9 100644--- a/package.json+++ b/package.json@@ -328,7 +328,7 @@"@lobehub/desktop-ipc-typings": "workspace:*","@lobehub/editor": "^5.0.0","@lobehub/icons": "^6.7.0",- "@lobehub/market-sdk": "0.42.0",+ "@lobehub/market-sdk": "0.43.0","@lobehub/ui": "^6.3.0","@modelcontextprotocol/sdk": "^1.32.1","@neondatabase/serverless": "^1.1.0",@@ -506,7 +506,7 @@"@lobechat/types": "workspace:*","@lobehub/i18n-cli": "^1.27.0","@lobehub/lint": "2.1.5",- "@lobehub/market-types": "^1.17.1",+ "@lobehub/market-types": "^1.19.0","@lobehub/seo-cli": "^1.7.0","@peculiar/webcrypto": "^1.7.1","@playwright/test": "^1.62.1",diff --git a/packages/env/src/__tests__/sandbox.test.ts b/packages/env/src/__tests__/sandbox.test.tsindex eca96ed6bfe..10dde1ad35b 100644--- a/packages/env/src/__tests__/sandbox.test.ts+++ b/packages/env/src/__tests__/sandbox.test.ts@@ -10,16 +10,6 @@ describe('getSandboxConfig', () => {delete process.env.ONLYBOXES_JIT_SIGNING_KEY;delete process.env.ONLYBOXES_JIT_TTL_SEC;delete process.env.ONLYBOXES_LEASE_TTL_SEC;- for (const key of [- 'WIDGET_SANDBOX_URL',- 'WIDGET_SANDBOX_TOKEN',- 'WIDGET_SANDBOX_PROVIDER',- 'WIDGET_SANDBOX_NETWORK_FORMAT',- 'DASHBOARD_SANDBOX_URL',- 'DASHBOARD_SANDBOX_TOKEN',- ]) {- delete process.env[key];- }});it('should treat docker empty string defaults as unset optional values', async () => {@@ -59,33 +49,4 @@ describe('getSandboxConfig', () => {expect(config.ONLYBOXES_JIT_TTL_SEC).toBe(900);expect(config.ONLYBOXES_LEASE_TTL_SEC).toBe(3600);});-- it('reads the widget sandbox from WIDGET_SANDBOX_*', async () => {- process.env.WIDGET_SANDBOX_URL = 'https://widget.example.dev';- process.env.WIDGET_SANDBOX_TOKEN = 'widget-token';- process.env.WIDGET_SANDBOX_PROVIDER = 'cloudflare-worker';- process.env.WIDGET_SANDBOX_NETWORK_FORMAT = 'boolean';- process.env.DASHBOARD_SANDBOX_URL = 'https://legacy.example.dev';- process.env.DASHBOARD_SANDBOX_TOKEN = 'legacy-token';-- const { getSandboxConfig } = await import('../sandbox');- const config = getSandboxConfig();-- expect(config.WIDGET_SANDBOX_URL).toBe('https://widget.example.dev');- expect(config.WIDGET_SANDBOX_TOKEN).toBe('widget-token');- expect(config.WIDGET_SANDBOX_PROVIDER).toBe('cloudflare-worker');- expect(config.WIDGET_SANDBOX_NETWORK_FORMAT).toBe('boolean');- });-- it('falls back to the legacy DASHBOARD_SANDBOX_* names', async () => {- process.env.DASHBOARD_SANDBOX_URL = 'https://legacy.example.dev';- process.env.DASHBOARD_SANDBOX_TOKEN = 'legacy-token';-- const { getSandboxConfig } = await import('../sandbox');- const config = getSandboxConfig();-- expect(config.WIDGET_SANDBOX_URL).toBe('https://legacy.example.dev');- expect(config.WIDGET_SANDBOX_TOKEN).toBe('legacy-token');- expect(config.WIDGET_SANDBOX_PROVIDER).toBeUndefined();- });});diff --git a/packages/env/src/sandbox.ts b/packages/env/src/sandbox.tsindex 8f706bee7e4..f469d057dda 100644--- a/packages/env/src/sandbox.ts+++ b/packages/env/src/sandbox.ts@@ -12,11 +12,6 @@ export const getSandboxConfig = () => {ONLYBOXES_JIT_TTL_SEC: process.env.ONLYBOXES_JIT_TTL_SEC,ONLYBOXES_LEASE_TTL_SEC: process.env.ONLYBOXES_LEASE_TTL_SEC,SANDBOX_PROVIDER: process.env.SANDBOX_PROVIDER,- WIDGET_SANDBOX_NETWORK_FORMAT: process.env.WIDGET_SANDBOX_NETWORK_FORMAT,- WIDGET_SANDBOX_PROVIDER: process.env.WIDGET_SANDBOX_PROVIDER,- // `DASHBOARD_SANDBOX_*` is the pre-rename name, still read as a fallback.- WIDGET_SANDBOX_TOKEN: process.env.WIDGET_SANDBOX_TOKEN || process.env.DASHBOARD_SANDBOX_TOKEN,- WIDGET_SANDBOX_URL: process.env.WIDGET_SANDBOX_URL || process.env.DASHBOARD_SANDBOX_URL,},server: {ONLYBOXES_BASE_URL: z.preprocess(emptyStringToUndefined, z.string().url().optional()),@@ -31,26 +26,6 @@ export const getSandboxConfig = () => {emptyStringToUndefined,z.enum(['market', 'onlyboxes']).optional(),),- /**- * How the widget sandbox request encodes the manifest's network- * allowlist: `boolean` (default) sends `network: allow.length > 0`, which is- * all the deployed Worker understands today (it rejects an object with 400);- * `allowlist` sends `network: { allow: [...] }` for a Worker that enforces- * per-run hosts.- */- WIDGET_SANDBOX_NETWORK_FORMAT: z.preprocess(- emptyStringToUndefined,- z.enum(['allowlist', 'boolean']).optional(),- ),- /** Widget script executor; only the Cloudflare Worker exists today. */- WIDGET_SANDBOX_PROVIDER: z.preprocess(- emptyStringToUndefined,- z.enum(['cloudflare-worker']).optional(),- ),- /** Bearer token for the widget sandbox (`POST /run`). Falls back to `DASHBOARD_SANDBOX_TOKEN`. */- WIDGET_SANDBOX_TOKEN: z.preprocess(emptyStringToUndefined, z.string().optional()),- /** Base URL of the widget sandbox. Falls back to `DASHBOARD_SANDBOX_URL`. */- WIDGET_SANDBOX_URL: z.preprocess(emptyStringToUndefined, z.string().url().optional()),},});};diff --git a/packages/locales/src/default/dashboard.ts b/packages/locales/src/default/dashboard.tsindex 11813bfba1d..78d5b68cd6b 100644--- a/packages/locales/src/default/dashboard.ts+++ b/packages/locales/src/default/dashboard.ts@@ -111,8 +111,6 @@ export default {'Once published, this script runs on its schedule with the listed credentials and its result shows on dashboards.','publish.network': 'Network','publish.networkNone': 'No network access',- 'publish.networkUnrestricted':- 'The sandbox cannot restrict egress to the listed hosts — the script can reach any host, including ones it did not declare.','publish.noSuccessfulRun':'This draft has not succeeded in a dry run yet, so publishing it will be refused.','publish.previewTitle': 'Latest dry run',diff --git a/packages/types/package.json b/packages/types/package.jsonindex ec190f318a6..e1fa124b6cc 100644--- a/packages/types/package.json+++ b/packages/types/package.json@@ -15,8 +15,8 @@"test:update": "vitest -u"},"dependencies": {- "@lobehub/market-sdk": "0.42.0",- "@lobehub/market-types": "^1.17.1",+ "@lobehub/market-sdk": "0.43.0",+ "@lobehub/market-types": "^1.19.0","ajv": "^8.20.0","model-bank": "workspace:*","type-fest": "^4.41.0",diff --git a/packages/types/src/serverConfig.ts b/packages/types/src/serverConfig.tsindex 01e40458984..703c8dbd34d 100644--- a/packages/types/src/serverConfig.ts+++ b/packages/types/src/serverConfig.ts@@ -185,15 +185,6 @@ export interface GlobalServerConfig {* Undefined means "not configured": the default (64) applies.*/toolNameMaxLength?: number;- /**- * How the widget sandbox encodes the manifest's network allowlist- * (`WIDGET_SANDBOX_NETWORK_FORMAT`): `allowlist` when the Worker restricts- * egress to the declared hosts, `boolean` — or absent, the deployed- * Worker's only format — when the sandbox only gets an on/off switch and- * cannot enforce hosts. The publish review reads this to disclose- * unrestricted egress instead of presenting the allowlist as enforced.- */- widgetSandboxNetworkFormat?: 'allowlist' | 'boolean';}export interface GlobalBillboardItemLocaleFields {diff --git a/src/features/Dashboard/WidgetPreview/ReviewFacts.tsx b/src/features/Dashboard/WidgetPreview/ReviewFacts.tsxindex 785989f0b89..8d4080e9fc2 100644--- a/src/features/Dashboard/WidgetPreview/ReviewFacts.tsx+++ b/src/features/Dashboard/WidgetPreview/ReviewFacts.tsx@@ -6,7 +6,6 @@ import { memo, type ReactNode } from 'react';import { useTranslation } from 'react-i18next';import AsyncError from '@/components/AsyncError';-import { serverConfigSelectors, useServerConfigStore } from '@/store/serverConfig';export const reviewStyles = createStaticStyles(({ css }) => ({label: css`@@ -37,29 +36,16 @@ export const AccessFacts = memo<{ manifest?: WidgetManifest | null }>(({ manifesconst { t } = useTranslation('dashboard');const hosts = manifest?.network?.allow ?? [];const env = manifest?.env ?? [];- // The boolean network format — the deployed Worker's only one — switches- // egress on for any nonempty allowlist without enforcing the hosts, so the- // facts must say the script can reach any host, not just the declared ones.- const enforcesHosts = useServerConfigStore(- serverConfigSelectors.widgetSandboxEnforcesNetworkHosts,- );return (<><Fact label={t('publish.network')}>{hosts.length > 0 ? (- <>- {!enforcesHosts && (- <Text fontSize={12} type={'warning'}>- {t('publish.networkUnrestricted')}- </Text>- )}- {hosts.map((host) => (- <Tag key={host} size={'small'}>- {host}- </Tag>- ))}- </>+ hosts.map((host) => (+ <Tag key={host} size={'small'}>+ {host}+ </Tag>+ ))) : (<Text fontSize={12}>{t('publish.networkNone')}</Text>)}diff --git a/src/store/serverConfig/selectors.test.ts b/src/store/serverConfig/selectors.test.tsindex 12584d88b56..4f4373a4fbf 100644--- a/src/store/serverConfig/selectors.test.ts+++ b/src/store/serverConfig/selectors.test.ts@@ -112,28 +112,4 @@ describe('serverConfigSelectors', () => {expect(result).toBe(false);});});-- describe('widgetSandboxEnforcesNetworkHosts', () => {- it('is true only when the sandbox runs in allowlist mode', () => {- const enforced = initServerConfigStore({- serverConfig: { aiProvider: {}, telemetry: {}, widgetSandboxNetworkFormat: 'allowlist' },- });- expect(serverConfigSelectors.widgetSandboxEnforcesNetworkHosts(enforced.getState())).toBe(- true,- );-- // The deployed Worker's boolean format — and an unset format, which- // defaults to it — cannot limit egress to the declared hosts.- const booleanFormat = initServerConfigStore({- serverConfig: { aiProvider: {}, telemetry: {}, widgetSandboxNetworkFormat: 'boolean' },- });- expect(- serverConfigSelectors.widgetSandboxEnforcesNetworkHosts(booleanFormat.getState()),- ).toBe(false);- const unset = initServerConfigStore({- serverConfig: { aiProvider: {}, telemetry: {} },- });- expect(serverConfigSelectors.widgetSandboxEnforcesNetworkHosts(unset.getState())).toBe(false);- });- });});diff --git a/src/store/serverConfig/selectors.ts b/src/store/serverConfig/selectors.tsindex c6cc73fbedf..f4341f6b927 100644--- a/src/store/serverConfig/selectors.ts+++ b/src/store/serverConfig/selectors.ts@@ -22,15 +22,6 @@ export const serverConfigSelectors = {enableMultimodalUnderstanding: (s: ServerConfigStore) =>s.serverConfig.enableMultimodalUnderstanding || false,enabledTelemetryChat: (s: ServerConfigStore) => s.serverConfig.telemetry.langfuse || false,- /**- * Whether the widget sandbox can enforce the manifest's per-host network- * allowlist. Only `WIDGET_SANDBOX_NETWORK_FORMAT=allowlist` restricts- * egress to the declared hosts; the default boolean format switches egress- * on for any nonempty allowlist, so the publish review must disclose- * unrestricted egress instead of presenting the hosts as enforced.- */- widgetSandboxEnforcesNetworkHosts: (s: ServerConfigStore) =>- s.serverConfig.widgetSandboxNetworkFormat === 'allowlist',isMobile: (s: ServerConfigStore) => s.isMobile || false,oAuthSSOProviders: (s: ServerConfigStore) => s.serverConfig.oAuthSSOProviders,oidcIssuer: (s: ServerConfigStore) => s.serverConfig.oidcIssuer,