Skip to content

Commit c3ea977

Browse files
authored
feat(portals): expose portals to sessions on node-backed cloud workers (#130105)
* feat(portals): expose portals to sessions on node-backed cloud workers Worker-turn sessions placed on cloud workers (bundled Crabbox) can now open portals. The portal tool joins the closed worker session-tool catalog and executes on the Gateway, which mints a single-use ticket per proxied connection; the enrolled node redeems it over a TLS-pinned WebSocket via the new private worker.portal.stream.v1 command and splices to the worker's loopback port. The desktop stream broker is generalized with discriminated desktop/portal tickets, and shared node stream transport is extracted from the desktop stream command. Portal availability is negotiated via a new gateway hello capability plus the node's reconnect-scoped workerHost.portalStream declaration, so old node bundles simply do not receive the tool. Environment teardown and owner-epoch replacement close a worker's portals; node disconnects destroy live streams while the listener keeps serving the waiting page. Live-proven on a Crabbox AWS worker: agent opened a portal over the worker protocol, python3 -m http.server on the box served through the Gateway portal URL with token auth intact. * fix(portals): break portal proxy/service type cycle; regenerate Swift protocol models * fix(portals): drop dead PortalTarget re-export; fix test import * fix(portals): only tear down turn-created portals on post-open authority loss ClawSweeper finding: a revoked turn's duplicate open could close the live portal a still-authorized predecessor established, because service.open returns the existing same-environment portal and the executor's error path closed whatever id it received. portal.open now reports created-vs-reused; the executor tears down only portals it created and closes its redundant carrier handle whenever an existing portal is reused. * feat(portals): fence portal reuse behind the caller's live-authority assert Rank-up move from review: portal.open revalidates the caller inside the serialized operation before a reuse can mutate a live portal's metadata, mirroring close(assertCurrent). Regression test proves a lapsed caller cannot rewrite a reused portal's title. * test(portals): expect assertCurrent in worker portal open call * refactor(gateway): extract worker request dispatch into its own module worker-connection.ts crossed the 700-line ratchet after rebasing onto current main; dispatchWorkerRequest and its rejection helper move to worker-connection-dispatch.ts unchanged (434 + 329 lines).
1 parent 0569c6e commit c3ea977

64 files changed

Lines changed: 3449 additions & 879 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎apps/shared/OpenClawKit/Sources/OpenClawProtocol/GatewayModels.swift‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20861,6 +20861,7 @@ public struct PortalSummary: Codable, Sendable {
2086120861
public let publicurl: String
2086220862
public let path: String?
2086320863
public let description: String?
20864+
public let origin: String?
2086420865
public let createdatms: Int
2086520866

2086620867
public init(
@@ -20873,6 +20874,7 @@ public struct PortalSummary: Codable, Sendable {
2087320874
publicurl: String,
2087420875
path: String? = nil,
2087520876
description: String? = nil,
20877+
origin: String? = nil,
2087620878
createdatms: Int)
2087720879
{
2087820880
self.id = id
@@ -20884,6 +20886,7 @@ public struct PortalSummary: Codable, Sendable {
2088420886
self.publicurl = publicurl
2088520887
self.path = path
2088620888
self.description = description
20889+
self.origin = origin
2088720890
self.createdatms = createdatms
2088820891
}
2088920892

@@ -20897,6 +20900,7 @@ public struct PortalSummary: Codable, Sendable {
2089720900
case publicurl = "publicUrl"
2089820901
case path
2089920902
case description
20903+
case origin
2090020904
case createdatms = "createdAtMs"
2090120905
}
2090220906
}
@@ -20942,6 +20946,7 @@ public struct PortalOpenResult: Codable, Sendable {
2094220946
public let publicurl: String
2094320947
public let path: String?
2094420948
public let description: String?
20949+
public let origin: String?
2094520950
public let createdatms: Int
2094620951

2094720952
public init(
@@ -20954,6 +20959,7 @@ public struct PortalOpenResult: Codable, Sendable {
2095420959
publicurl: String,
2095520960
path: String? = nil,
2095620961
description: String? = nil,
20962+
origin: String? = nil,
2095720963
createdatms: Int)
2095820964
{
2095920965
self.id = id
@@ -20965,6 +20971,7 @@ public struct PortalOpenResult: Codable, Sendable {
2096520971
self.publicurl = publicurl
2096620972
self.path = path
2096720973
self.description = description
20974+
self.origin = origin
2096820975
self.createdatms = createdatms
2096920976
}
2097020977

@@ -20978,6 +20985,7 @@ public struct PortalOpenResult: Codable, Sendable {
2097820985
case publicurl = "publicUrl"
2097920986
case path
2098020987
case description
20988+
case origin
2098120989
case createdatms = "createdAtMs"
2098220990
}
2098320991
}

‎config/assertion-safety-baseline.txt‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3106,7 +3106,6 @@ src/gateway/worker-environments/transcript-commit.ts 6
31063106
src/gateway/worker-environments/worker-session-tool-executor.ts 1
31073107
src/gateway/worker-environments/worker-turn-admission.ts 3
31083108
src/gateway/worker-environments/worker-turn-payload.ts 4
3109-
src/gateway/worker-environments/worker-turn-rpc.ts 2
31103109
src/gateway/worker-environments/workspace-accepted-publication.ts 1
31113110
src/gateway/worker-environments/workspace-manifest.ts 14
31123111
src/gateway/worker-environments/workspace-path-exclusions.ts 2
@@ -3420,7 +3419,6 @@ src/model-catalog/bundled-catalog-stamp.ts 1
34203419
src/model-catalog/remote-overlay.ts 1
34213420
src/model-picker/apply-session-model-selection.ts 1
34223421
src/node-host/config.ts 1
3423-
src/node-host/desktop-stream-command.ts 2
34243422
src/node-host/invoke-agent-cli-claude-params.ts 4
34253423
src/node-host/invoke-agent-cli-claude.ts 1
34263424
src/node-host/invoke-file-commands.ts 1

‎docs/gateway/cloud-workers.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,8 @@ The bundled Crabbox cloud provider advertises both `worker-turn` and `remote-exe
3131

3232
After Crabbox setup, the cloud node dials the Gateway's public TLS endpoint over outbound WebSocket. Worker control, Codex remote execution, and workspace transfer use authenticated node or worker channels, not a Gateway-created reverse tunnel or rsync. Crabbox itself may still require SSH reachability while its CLI runs the provider-owned setup command. Outbound internet access is provider policy; the default AWS profile can reach the internet unless you restrict its network or security group.
3333

34+
OpenClaw `worker-turn` sessions can open [portals](/gateway/portals) on node-backed cloud workers, including the bundled Crabbox provider. For each proxied HTTP or WebSocket connection, the enrolled node redeems a single-use ticket over a TLS-pinned WebSocket to the Gateway and connects to the worker's selected loopback port. This preserves the existing **Control UI → Portals** experience, authentication, and live reload without opening inbound worker ports or creating an SSH tunnel. The tool is available only when the node advertises portal-stream support; older node bundles do not receive it. SSH-backed `remote-exec` placements, including Codex sessions, do not run the OpenClaw worker tool loop, so the `portal` tool does not apply there. Update an unsupported node or move the session back to the Gateway with `sessions.move` when a Gateway-hosted portal is needed.
35+
3436
For a loopback Gateway behind public HTTPS ingress, set `gateway.publicOrigin` to the proxy's bare origin. Node enrollment uses it as the default external pairing endpoint; `plugins.entries.device-pair.config.publicUrl` remains the pairing-specific override. If either URL is behind a reverse proxy, including cloudflared, nginx, or externally managed Tailscale Serve, `gateway.trustedProxies` must include the proxy's source address (typically loopback for a same-host proxy). Otherwise, forwarded client headers cause node enrollment to fail with `proxy_attribution_required`.
3537

3638
## Requirements
@@ -402,6 +404,7 @@ The desktop never gains public ingress. The node reads `/var/lib/crabbox/vnc.pas
402404
- **Cloud destinations are hidden or an RPC is denied** — cloud profile dispatch and profile-target moves require `operator.admin`. `operator.write` can dispatch or move to an eligible paired device, move to the Gateway, and reclaim a placement; `operator.read` alone can discover profiles but cannot start, stop, or move a session. Profile configuration, infrastructure pairing, Connect machine, raw environment lifecycle, direct `execNode` execution, incognito sessions, and arbitrary host or node paths remain `operator.admin`.
403405
- **The selected runtime lacks cloud placement support** — choose a model whose advertised runtime supports cloud placement. The bundled OpenClaw and Codex runtimes are supported; undeclared runtimes remain local-only.
404406
- **Codex cannot use a cloud profile** — verify that the profile advertises `remote-exec`, its setup installs the exact official `npm:@openclaw/codex@<gateway-version>` plugin, the Gateway enables the Codex plugin, and `gateway.nodes.commands.allow` includes `codex.exec-server.stdio.v1` without a matching deny rule. Approve the exact node invocation when prompted. Codex does not require an available OpenClaw worker slot; a missing plugin or denied command must be corrected rather than bypassed with Gateway or SSH execution.
407+
- **The portal tool is unavailable on a worker** — confirm the session uses OpenClaw `worker-turn` on an enrolled node that advertises portal-stream support. Update older node bundles when necessary. SSH-backed `remote-exec` placements, including Codex sessions, do not run the OpenClaw worker tool loop; move the session back to the Gateway with `sessions.move` when a Gateway-hosted portal is needed.
405408
- **"Worker bootstrap requires Node.js on the leased host"** — add a Node install to `settings.setup` (see above).
406409
- **AWS instance-role attestation fails** — clear `aws.instanceProfile` (and `CRABBOX_AWS_INSTANCE_PROFILE`, if set). Install Crabbox 0.41.1 or newer; older binaries do not satisfy the fixed-ID and authoritative `providerMetadata.instanceProfileAttached` contracts required for AWS admission.
407410
- **Dispatch or workspace recovery fails** — inspect `environments.list` and `sessions.describe`. A failed environment exposes its bounded environment error. A failed placement exposes `recoveryError` plus its durable per-session `terminalReason`; the selected Control UI chat shows that terminal reason above the composer. When deeper diagnosis is necessary, an operator on the Gateway host can inspect the durable worker state read-only. Do not edit the state database to bypass lifecycle fencing.

‎docs/gateway/portals.md‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ read_when:
77
- Troubleshooting portal access or live reload
88
---
99

10-
Portals expose a development server running on the Gateway host to the operator's browser. They proxy HTTP and WebSockets for live reload and appear in **Control UI → Portals**.
10+
Portals expose a development server running on the Gateway host or a node-backed cloud worker to the operator's browser. They proxy HTTP and WebSockets for live reload and appear in **Control UI → Portals**.
1111

1212
## Quick start
1313

@@ -18,6 +18,8 @@ Ask the agent to open a portal:
1818

1919
The agent opens a portal for the application's port, then starts the development server with a background `exec` call. Opening a portal only creates the proxy listener; it does not inject environment variables into your server. The agent sets `PORT` (the port it opened) and `PUBLIC_URL` (the portal's public base URL) in that `exec` command's own environment, so the app binds the expected port and generates correct absolute URLs.
2020

21+
For a session on a node-backed cloud worker, including the bundled Crabbox provider, the development server runs on the worker. Each portal connection receives its own single-use ticket, which the enrolled node redeems over a TLS-pinned WebSocket to the Gateway before connecting to the selected loopback port. This uses the existing authenticated node channel without exposing the worker to inbound traffic or creating an SSH tunnel. Stopping or replacing the worker closes its portals.
22+
2123
## Declare development servers
2224

2325
Optionally commit `.openclaw/portals.json` to the workspace repository so the agent can discover the available development servers:
@@ -64,6 +66,7 @@ Out of the box:
6466
- `portal` belongs to `group:ui` and the `coding` profile, so coding agents have it while `messaging` and `minimal` agents do not.
6567
- Sandboxed sessions never receive it, because opening a portal starts a listener on the Gateway host.
6668
- It is blocked for HTTP `POST /tools/invoke` and restricted to the session owner, the same treatment `terminal` gets.
69+
- Cloud-worker sessions receive it only when their enrolled node advertises portal-stream support. Older node bundles without that capability do not receive the tool.
6770

6871
To turn portals off everywhere, deny the tool in the global policy:
6972

@@ -91,19 +94,20 @@ Each portal uses a separate origin on its own port and binds to the same interfa
9194

9295
Browser cookies are hostname-scoped rather than port-scoped, so the proxy gives each portal instance a random `oc_portal_<instance>_` cookie-name prefix. Requests forward only cookies with the current portal's prefix and strip it before reaching the application; Gateway cookies, unprefixed cookies, and cookies from sibling or closed portals are dropped. Application `Set-Cookie` responses receive the prefix, and any `Domain` attribute is removed so the cookie stays host-only.
9396

94-
Portals proxy only the selected local development server. They never serve Gateway data, and every portal ends when the Gateway restarts.
97+
Portals proxy only the selected development server on the Gateway host or a node-backed cloud worker. Worker connections use single-use tickets and the enrolled node's TLS-pinned Gateway connection; they never expose a public worker port or require SSH forwarding. Portals never serve Gateway data, and every portal ends when the Gateway restarts.
9598

9699
## Limitations
97100

98-
- The development server must run on the Gateway host. Remote worker support is planned.
101+
- Older node bundles without portal-stream support cannot open worker portals. Update the node bundle, or move the session back to the Gateway with `sessions.move`.
102+
- SSH-backed `remote-exec` placements, including Codex sessions, do not run the OpenClaw worker tool loop, so the `portal` tool does not apply there. Move the session back to the Gateway with `sessions.move` when a Gateway-hosted portal is needed.
99103
- A proxy or tunnel in front of the Gateway does not automatically expose portal listener ports. The Control UI detects this and shows a reachable URL with retry guidance instead of mounting a dead iframe.
100104
- The prefix isolates cookies forwarded to each target; it does not create separate browser cookie jars. Browser-side code can see non-`HttpOnly` cookies for sibling portals on the same hostname through `document.cookie`. Use `HttpOnly` for sensitive application cookies. Applications that manage cookies in browser code must account for the prefix; unprefixed cookies written directly by browser code are not forwarded to the target.
101105

102106
## Troubleshooting
103107

104108
### The portal shows a 502 waiting page
105109

106-
The proxy is ready, but the application is not listening on the selected port. The page retries automatically. Check the background process and confirm that the server honors `PORT`.
110+
The proxy is ready, but the application is not listening on the selected port or its worker node is temporarily disconnected. The page retries automatically. Check the background process, confirm that the server honors `PORT`, and verify that the worker node is connected.
107111

108112
### The portal is not reachable from this browser
109113

‎packages/gateway-protocol/src/public-schema.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,8 @@ export {
3737
WorkerSessionsSpawnResponseFrameSchema,
3838
WorkerSessionsSendParamsSchema,
3939
WorkerSessionsSendResponseFrameSchema,
40+
WorkerPortalParamsSchema,
41+
WorkerPortalResponseFrameSchema,
4042
WorkerSessionToolResultSchema,
4143
WorkerLiveEventSchema,
4244
WorkerLiveEventErrorDetailsSchema,
@@ -58,6 +60,7 @@ export {
5860
WORKER_LAUNCH_V2_PROTOCOL_FEATURE,
5961
WORKER_LIVE_EVENT_PROTOCOL_FEATURE,
6062
WORKER_SESSION_TOOLS_PROTOCOL_FEATURE,
63+
WORKER_PORTAL_PROTOCOL_FEATURE,
6164
WORKER_SESSION_TOOL_MAX_TEXT_LENGTH,
6265
WORKER_PROTOCOL_FEATURES,
6366
WORKER_PROTOCOL_MAX_FEATURE_LENGTH,

‎packages/gateway-protocol/src/schema/portals.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ const PortalSummaryMetadataFields = {
1313
publicUrl: NonEmptyString,
1414
path: Type.Optional(Type.String({ pattern: "^/" })),
1515
description: Type.Optional(Type.String()),
16+
origin: Type.Optional(Type.String()),
1617
createdAtMs: Type.Integer({ minimum: 0 }),
1718
};
1819

‎packages/gateway-protocol/src/schema/worker-admission.test.ts‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import {
1111
WorkerLiveEventRequestFrameSchema,
1212
WorkerLiveEventResponseFrameSchema,
1313
WorkerProtocolCloseReasonSchema,
14+
WorkerPortalResponseFrameSchema,
1415
WorkerSessionsSendResponseFrameSchema,
1516
WorkerSessionsSpawnResponseFrameSchema,
1617
WorkerTranscriptCommitRequestFrameSchema,
@@ -19,6 +20,7 @@ import {
1920
WORKER_LAUNCH_V2_PROTOCOL_FEATURE,
2021
WORKER_GITHUB_PUBLICATION_PROTOCOL_FEATURE,
2122
WORKER_PROTOCOL_FEATURES,
23+
WORKER_PORTAL_PROTOCOL_FEATURE,
2224
WORKER_PROTOCOL_MAX_FRAME_ID_LENGTH,
2325
WORKER_PROTOCOL_MAX_PAYLOAD_BYTES,
2426
WORKER_RPC_SET_VERSION,
@@ -30,6 +32,7 @@ import {
3032
validateWorkerHeartbeatParams,
3133
validateWorkerGitHubPublishParams,
3234
validateWorkerLiveEventParams,
35+
validateWorkerPortalParams,
3336
validateWorkerSessionsSendParams,
3437
validateWorkerSessionsSpawnParams,
3538
validateWorkerTranscriptCommitParams,
@@ -284,9 +287,11 @@ describe("worker protocol schemas", () => {
284287
message: "report status",
285288
};
286289
const publish = { toolCallId: "call-publish", title: "Publish the fix" };
290+
const portal = { toolCallId: "call-portal", action: "open", port: 3000, path: "/app" };
287291
expect(validateWorkerSessionsSpawnParams(spawn)).toBe(true);
288292
expect(validateWorkerSessionsSendParams(send)).toBe(true);
289293
expect(validateWorkerGitHubPublishParams(publish)).toBe(true);
294+
expect(validateWorkerPortalParams(portal)).toBe(true);
290295
expect(validateWorkerSessionsSpawnParams({ ...spawn, unexpected: true })).toBe(false);
291296
expect(validateWorkerSessionsSendParams({ ...send, message: "" })).toBe(false);
292297
expect(validateWorkerGitHubPublishParams({ ...publish, token: "secret" })).toBe(false);
@@ -296,6 +301,10 @@ describe("worker protocol schemas", () => {
296301
expect(validateWorkerGitHubPublishParams({ ...publish, branch: "main" })).toBe(false);
297302
expect(validateWorkerGitHubPublishParams({ ...publish, title: "Fix\rInject" })).toBe(false);
298303
expect(validateWorkerGitHubPublishParams({ ...publish, commitMessage: "Inject" })).toBe(false);
304+
expect(validateWorkerPortalParams({ ...portal, token: "secret" })).toBe(false);
305+
expect(validateWorkerPortalParams({ ...portal, action: "unknown" })).toBe(false);
306+
expect(validateWorkerPortalParams({ ...portal, port: 0 })).toBe(false);
307+
expect(validateWorkerPortalParams({ ...portal, path: "app" })).toBe(false);
299308
const escaped = "\0";
300309
const requestBytes = (method: string, requestParams: object) =>
301310
Buffer.byteLength(
@@ -357,6 +366,22 @@ describe("worker protocol schemas", () => {
357366
expect(requestBytes("worker.github.publish", maximalPublish)).toBeLessThanOrEqual(
358367
WORKER_PROTOCOL_MAX_PAYLOAD_BYTES,
359368
);
369+
const maximalPortal = {
370+
toolCallId: escaped.repeat(256),
371+
action: "open",
372+
port: 65_535,
373+
title: escaped.repeat(256),
374+
description: escaped.repeat(WORKER_SESSION_TOOL_MAX_TEXT_LENGTH),
375+
path: `/${escaped.repeat(1_023)}`,
376+
id: escaped.repeat(256),
377+
};
378+
expect(validateWorkerPortalParams(maximalPortal)).toBe(true);
379+
expect(requestBytes("worker.portal", maximalPortal)).toBeLessThanOrEqual(
380+
WORKER_PROTOCOL_MAX_PAYLOAD_BYTES,
381+
);
382+
expect(validateWorkerPortalParams({ ...maximalPortal, description: impossibleText })).toBe(
383+
false,
384+
);
360385
expect(
361386
validateWorkerSessionsSpawnParams({
362387
...spawn,
@@ -365,6 +390,7 @@ describe("worker protocol schemas", () => {
365390
).toBe(false);
366391
expect(WORKER_PROTOCOL_FEATURES).toContain(WORKER_SESSION_TOOLS_PROTOCOL_FEATURE);
367392
expect(WORKER_PROTOCOL_FEATURES).toContain(WORKER_GITHUB_PUBLICATION_PROTOCOL_FEATURE);
393+
expect(WORKER_PROTOCOL_FEATURES).toContain(WORKER_PORTAL_PROTOCOL_FEATURE);
368394

369395
const response = {
370396
type: "res" as const,
@@ -375,6 +401,7 @@ describe("worker protocol schemas", () => {
375401
expect(Value.Check(WorkerSessionsSpawnResponseFrameSchema, response)).toBe(true);
376402
expect(Value.Check(WorkerSessionsSendResponseFrameSchema, response)).toBe(true);
377403
expect(Value.Check(WorkerGitHubPublishResponseFrameSchema, response)).toBe(true);
404+
expect(Value.Check(WorkerPortalResponseFrameSchema, response)).toBe(true);
378405
expect(
379406
Value.Check(WorkerSessionsSendResponseFrameSchema, {
380407
...response,

0 commit comments

Comments
 (0)