File size: 10,728 Bytes
5cb63c1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
import type { OpenClawConfig } from "../../config/types.openclaw.js";
import { registerSecretValueForRedaction } from "../../logging/secret-redaction-registry.js";
import { NODE_DESKTOP_STREAM_COMMAND } from "../../shared/node-desktop-stream.js";
import { isNodeCommandAllowed, resolveNodeCommandAllowlist } from "../node-command-policy.js";
import type { NodeRegistry, NodeSession } from "../node-registry.js";
import { DesktopCredentialsRequiredError } from "./host-source-errors.js";
import type { NodeDesktopStreamBroker } from "./node-stream-broker.js";
import { mintDesktopObserverToken } from "./observe-bridge.js";
import type { DesktopObserveRequester } from "./observe-requester.js";
import type { RfbPreauthDescriptor } from "./rfb-preauth.js";
import type { DesktopSessionRegistry } from "./session-registry.js";

type NodeDesktopObserveResult = {
  transport: "rfb";
  wsPath: string;
  expiresAtMs: number;
  control: boolean;
  auth: "vnc-password" | "ard-account";
  preauthenticated: true;
};

function invocationError(result: Awaited<ReturnType<NodeRegistry["invoke"]>>): Error {
  const message = result.error?.message?.trim();
  return new Error(message || "node desktop stream closed before attachment");
}

type ActiveNodeDesktopStream = {
  controller: AbortController;
  ticket?: ReturnType<NodeDesktopStreamBroker["mint"]>;
  stream?: import("node:stream").Duplex;
  invocation?: ReturnType<NodeRegistry["invoke"]>;
  reservation?: ReturnType<DesktopSessionRegistry["reserveObserver"]>;
  reservationTransferred: boolean;
  unclaimedTimer?: ReturnType<typeof setTimeout>;
  stopped: boolean;
};

type NodeDesktopSession = {
  connId: string;
  pairingGeneration: string;
  ownerEpoch: number;
  active: Set<ActiveNodeDesktopStream>;
};

async function stopActiveStream(active: ActiveNodeDesktopStream): Promise<void> {
  if (active.stopped) {
    return;
  }
  retireActiveStream(active);
  await active.invocation?.catch(() => undefined);
}

function retireActiveStream(active: ActiveNodeDesktopStream): void {
  if (active.stopped) {
    return;
  }
  active.stopped = true;
  clearTimeout(active.unclaimedTimer);
  active.ticket?.cancel();
  active.controller.abort();
  if (!active.reservationTransferred) {
    active.reservation?.release();
  }
  active.stream?.destroy();
}

/** Combines node command policy, ticket redemption, and desktop session ownership. */
export function createNodeDesktopService(params: {
  getConfig: () => OpenClawConfig;
  nodeRegistry: NodeRegistry;
  desktopRegistry: DesktopSessionRegistry;
  streamBroker: NodeDesktopStreamBroker;
}) {
  const ownerEpochs = new Map<string, number>();
  const sessions = new Map<string, NodeDesktopSession>();

  const commandAllowed = (node: NodeSession) =>
    isNodeCommandAllowed({
      command: NODE_DESKTOP_STREAM_COMMAND,
      declaredCommands: node.commands,
      allowlist: resolveNodeCommandAllowlist(params.getConfig(), node),
    }).ok;

  const stopNode = async (nodeId: string): Promise<void> => {
    const session = sessions.get(nodeId);
    if (session) {
      await params.desktopRegistry.stop(`node:${nodeId}`, session.ownerEpoch);
    }
  };

  const ensureSession = async (request: {
    nodeId: string;
    connId: string;
    pairingGeneration: string;
  }): Promise<NodeDesktopSession> => {
    const sourceKey = `node:${request.nodeId}`;
    const current = sessions.get(request.nodeId);
    if (
      current?.connId === request.connId &&
      current.pairingGeneration === request.pairingGeneration
    ) {
      await params.desktopRegistry.activate({
        sourceKey,
        ownerEpoch: current.ownerEpoch,
      });
      return current;
    }

    const ownerEpoch = (ownerEpochs.get(request.nodeId) ?? 0) + 1;
    ownerEpochs.set(request.nodeId, ownerEpoch);
    const session: NodeDesktopSession = {
      connId: request.connId,
      pairingGeneration: request.pairingGeneration,
      ownerEpoch,
      active: new Set(),
    };
    sessions.set(request.nodeId, session);
    try {
      await params.desktopRegistry.activate({
        sourceKey,
        ownerEpoch,
        teardown: async () => {
          if (sessions.get(request.nodeId) === session) {
            sessions.delete(request.nodeId);
          }
          await Promise.all([...session.active].map(stopActiveStream));
          session.active.clear();
        },
      });
      return session;
    } catch (error) {
      if (sessions.get(request.nodeId) === session) {
        sessions.delete(request.nodeId);
      }
      throw error;
    }
  };

  return {
    stopNode,
    async reconcileRuntimePolicy(): Promise<void> {
      await Promise.all(
        [...sessions].map(async ([nodeId, session]) => {
          const node = params.nodeRegistry.get(nodeId);
          if (
            !node ||
            node.connId !== session.connId ||
            node.pairingGeneration !== session.pairingGeneration ||
            !commandAllowed(node)
          ) {
            await stopNode(nodeId);
          }
        }),
      );
    },
    async observe(request: {
      nodeId: string;
      control: boolean;
      requester?: DesktopObserveRequester;
      credentials?: { username?: string; password?: string };
    }): Promise<NodeDesktopObserveResult> {
      const node = params.nodeRegistry.get(request.nodeId);
      if (!node?.pairingGeneration) {
        throw new Error("node desktop is unavailable; reconnect and approve the node capability");
      }
      const pairingGeneration = node.pairingGeneration;
      const isAuthorized = () =>
        params.nodeRegistry.get(request.nodeId) === node &&
        node.pairingGeneration === pairingGeneration &&
        commandAllowed(node);
      const assertAuthorized = () => {
        if (!isAuthorized()) {
          throw new Error(
            "node desktop is not enabled; explicitly allow and approve desktop.stream for this node",
          );
        }
      };
      assertAuthorized();

      const sourceKey = `node:${request.nodeId}`;
      const session = await ensureSession({
        nodeId: request.nodeId,
        connId: node.connId,
        pairingGeneration,
      });
      assertAuthorized();
      const active: ActiveNodeDesktopStream = {
        controller: new AbortController(),
        reservation: params.desktopRegistry.reserveObserver(sourceKey, session.ownerEpoch),
        reservationTransferred: false,
        stopped: false,
      };
      if (!active.reservation) {
        throw new Error("node desktop observer limit reached");
      }
      session.active.add(active);
      try {
        active.ticket = params.streamBroker.mint({
          nodeId: request.nodeId,
          connId: node.connId,
          pairingGeneration,
        });
        active.invocation = params.nodeRegistry.invoke({
          nodeId: request.nodeId,
          expectedConnId: node.connId,
          expectedPairingGeneration: pairingGeneration,
          command: NODE_DESKTOP_STREAM_COMMAND,
          params: { ticket: active.ticket.ticket, attachPath: active.ticket.attachPath },
          timeoutMs: 0,
          onProgress: () => {},
          signal: active.controller.signal,
          // Pairing resolution yields before dispatch. Recheck this exact desktop
          // owner and live command policy at the transport's final admission edge.
          isDispatchAuthorized: () =>
            !active.stopped && sessions.get(request.nodeId) === session && isAuthorized(),
        });
        const invocationFinished = active.invocation.then((result) => {
          throw invocationError(result);
        });
        void invocationFinished.catch(() => undefined);

        const attached = await Promise.race([active.ticket.attached, invocationFinished]);
        if (active.stopped || sessions.get(request.nodeId) !== session) {
          attached.stream.destroy();
          throw new Error("node desktop session was superseded before attachment");
        }
        active.stream = attached.stream;
        assertAuthorized();

        let preauth: RfbPreauthDescriptor;
        if (attached.auth === "vnc-password") {
          const password = attached.vncPassword ?? request.credentials?.password;
          if (!password) {
            throw new DesktopCredentialsRequiredError(
              "vnc-password",
              "VNC password is required to observe this node",
            );
          }
          registerSecretValueForRedaction(password);
          preauth = { auth: attached.auth, credentials: { password } };
        } else {
          const username = request.credentials?.username?.trim() ?? "";
          const password = request.credentials?.password ?? "";
          if (!username || !password) {
            throw new DesktopCredentialsRequiredError(
              "ard-account",
              "macOS account credentials are required to observe this node",
            );
          }
          registerSecretValueForRedaction(password);
          preauth = { auth: attached.auth, credentials: { username, password } };
        }

        const attachment = params.desktopRegistry.publishStream({
          sourceKey,
          ownerEpoch: session.ownerEpoch,
          stream: attached.stream,
          reservation: active.reservation,
        });
        if (!attachment) {
          throw new Error("node desktop session was superseded before publication");
        }
        active.reservationTransferred = true;
        const minted = mintDesktopObserverToken({
          sourceKey,
          ownerEpoch: session.ownerEpoch,
          control: request.control,
          requester: request.requester,
          attachment,
          preauth,
        });
        active.unclaimedTimer = setTimeout(
          () => {
            if (params.desktopRegistry.hasPendingStream(sourceKey, attachment)) {
              void stopActiveStream(active).then(() => session.active.delete(active));
            }
          },
          Math.max(0, minted.expiresAtMs - Date.now()),
        );
        active.unclaimedTimer.unref?.();
        void active.invocation
          .finally(() => {
            retireActiveStream(active);
            session.active.delete(active);
          })
          .catch(() => undefined);
        return {
          transport: "rfb",
          wsPath: `/desktop/observe?token=${minted.token}`,
          expiresAtMs: minted.expiresAtMs,
          control: request.control,
          auth: attached.auth,
          preauthenticated: true,
        };
      } catch (error) {
        await stopActiveStream(active);
        session.active.delete(active);
        throw error;
      }
    },
  };
}

export type NodeDesktopService = ReturnType<typeof createNodeDesktopService>;