@privateclaw/privateclaw 0.1.12 → 0.1.14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +25 -4
- package/dist/cli.js +142 -24
- package/dist/cli.js.map +1 -1
- package/dist/openclaw-plugin.js +269 -26
- package/dist/openclaw-plugin.js.map +1 -1
- package/dist/pair-session.d.ts +6 -0
- package/dist/pair-session.js +20 -11
- package/dist/pair-session.js.map +1 -1
- package/dist/provider.d.ts +5 -0
- package/dist/provider.js +24 -2
- package/dist/provider.js.map +1 -1
- package/dist/session-control.d.ts +37 -1
- package/dist/session-control.js +182 -10
- package/dist/session-control.js.map +1 -1
- package/dist/text.d.ts +5 -0
- package/dist/text.js +8 -1
- package/dist/text.js.map +1 -1
- package/openclaw.plugin.json +1 -1
- package/package.json +2 -2
- package/src/cli.ts +185 -20
- package/src/openclaw-plugin.test.ts +200 -0
- package/src/openclaw-plugin.ts +425 -54
- package/src/pair-session.ts +36 -21
- package/src/provider.ts +37 -2
- package/src/session-control.test.ts +509 -0
- package/src/session-control.ts +317 -24
- package/src/text.ts +32 -2
package/src/pair-session.ts
CHANGED
|
@@ -123,6 +123,35 @@ export function printPairInviteBundle(
|
|
|
123
123
|
writeLine(bundle.qrTerminal);
|
|
124
124
|
}
|
|
125
125
|
|
|
126
|
+
export async function renderInviteBundleOutput(
|
|
127
|
+
bundle: PrivateClawInviteBundle,
|
|
128
|
+
params?: {
|
|
129
|
+
qrMediaDir?: string;
|
|
130
|
+
openInBrowser?: boolean;
|
|
131
|
+
writeLine?: (line: string) => void;
|
|
132
|
+
},
|
|
133
|
+
): Promise<PrivateClawInviteBundle> {
|
|
134
|
+
const mediaDir = params?.qrMediaDir ?? resolvePrivateClawMediaDir();
|
|
135
|
+
const qrPng = await writeInviteQrPng(bundle, mediaDir);
|
|
136
|
+
const renderedBundle: PrivateClawInviteBundle = {
|
|
137
|
+
...bundle,
|
|
138
|
+
qrPngPath: qrPng.pngPath,
|
|
139
|
+
};
|
|
140
|
+
|
|
141
|
+
printPairInviteBundle(renderedBundle, params?.writeLine ?? ((line) => console.log(line)));
|
|
142
|
+
|
|
143
|
+
if (params?.openInBrowser) {
|
|
144
|
+
const preview = await writeInviteQrPreviewHtml(
|
|
145
|
+
renderedBundle,
|
|
146
|
+
mediaDir,
|
|
147
|
+
qrPng.pngPath,
|
|
148
|
+
);
|
|
149
|
+
await openInBrowserPreview(preview.previewFileUrl);
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
return renderedBundle;
|
|
153
|
+
}
|
|
154
|
+
|
|
126
155
|
export async function runPairSession({
|
|
127
156
|
provider,
|
|
128
157
|
ttlMs,
|
|
@@ -136,32 +165,18 @@ export async function runPairSession({
|
|
|
136
165
|
console.log(line);
|
|
137
166
|
},
|
|
138
167
|
handoffToBackground,
|
|
139
|
-
}: PairSessionOptions): Promise<PrivateClawInviteBundle> {
|
|
168
|
+
}: PairSessionOptions): Promise<PrivateClawInviteBundle> {
|
|
140
169
|
try {
|
|
141
170
|
const inviteBundle = await provider.createInviteBundle({
|
|
142
171
|
...(typeof ttlMs === "number" ? { ttlMs } : {}),
|
|
143
172
|
...(label ? { label: label.trim() } : {}),
|
|
144
173
|
...(groupMode ? { groupMode: true } : {}),
|
|
145
174
|
});
|
|
146
|
-
const
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
...inviteBundle,
|
|
152
|
-
qrPngPath: qrPng.pngPath,
|
|
153
|
-
};
|
|
154
|
-
|
|
155
|
-
printPairInviteBundle(bundle, writeLine);
|
|
156
|
-
|
|
157
|
-
if (openInBrowser) {
|
|
158
|
-
const preview = await writeInviteQrPreviewHtml(
|
|
159
|
-
bundle,
|
|
160
|
-
qrMediaDir ?? resolvePrivateClawMediaDir(),
|
|
161
|
-
qrPng.pngPath,
|
|
162
|
-
);
|
|
163
|
-
await openInBrowserPreview(preview.previewFileUrl);
|
|
164
|
-
}
|
|
175
|
+
const bundle = await renderInviteBundleOutput(inviteBundle, {
|
|
176
|
+
...(qrMediaDir ? { qrMediaDir } : {}),
|
|
177
|
+
...(openInBrowser ? { openInBrowser: true } : {}),
|
|
178
|
+
writeLine,
|
|
179
|
+
});
|
|
165
180
|
|
|
166
181
|
if (printOnly) {
|
|
167
182
|
await provider.dispose();
|
|
@@ -221,7 +236,7 @@ export async function runPairSession({
|
|
|
221
236
|
}
|
|
222
237
|
}
|
|
223
238
|
|
|
224
|
-
async function openInBrowserPreview(target: string): Promise<void> {
|
|
239
|
+
export async function openInBrowserPreview(target: string): Promise<void> {
|
|
225
240
|
const command =
|
|
226
241
|
process.platform === "win32"
|
|
227
242
|
? {
|
package/src/provider.ts
CHANGED
|
@@ -536,6 +536,36 @@ export class PrivateClawProvider {
|
|
|
536
536
|
return [...this.sessions.values()].map(toManagedSessionSnapshot);
|
|
537
537
|
}
|
|
538
538
|
|
|
539
|
+
async getSessionQrBundle(
|
|
540
|
+
sessionId: string,
|
|
541
|
+
params?: { notifyParticipants?: boolean },
|
|
542
|
+
): Promise<PrivateClawInviteBundle> {
|
|
543
|
+
const session = this.requireSession(sessionId);
|
|
544
|
+
const bundle = await this.buildInviteBundleForInvite(session.invite);
|
|
545
|
+
|
|
546
|
+
if (params?.notifyParticipants) {
|
|
547
|
+
const qrAttachment = await this.buildSessionQrAttachmentFromBundle(bundle);
|
|
548
|
+
await this.sendAssistantMessage(sessionId, {
|
|
549
|
+
text: buildSessionQrMessage(session),
|
|
550
|
+
attachments: [qrAttachment],
|
|
551
|
+
storeHistory: false,
|
|
552
|
+
});
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
return bundle;
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
async closeManagedSession(
|
|
559
|
+
sessionId: string,
|
|
560
|
+
reason = "operator_terminated",
|
|
561
|
+
): Promise<PrivateClawManagedSession> {
|
|
562
|
+
const session = this.requireSession(sessionId);
|
|
563
|
+
const snapshot = toManagedSessionSnapshot(session);
|
|
564
|
+
await this.relayClient.closeSession(sessionId, reason);
|
|
565
|
+
this.deleteSession(sessionId);
|
|
566
|
+
return snapshot;
|
|
567
|
+
}
|
|
568
|
+
|
|
539
569
|
exportHandoffState(): PrivateClawProviderHandoffState {
|
|
540
570
|
return {
|
|
541
571
|
providerId: this.relayClient.getProviderId(),
|
|
@@ -1612,8 +1642,13 @@ export class PrivateClawProvider {
|
|
|
1612
1642
|
}
|
|
1613
1643
|
|
|
1614
1644
|
private async buildSessionQrAttachment(sessionId: string): Promise<PrivateClawAttachment> {
|
|
1615
|
-
const
|
|
1616
|
-
|
|
1645
|
+
const bundle = await this.getSessionQrBundle(sessionId);
|
|
1646
|
+
return this.buildSessionQrAttachmentFromBundle(bundle);
|
|
1647
|
+
}
|
|
1648
|
+
|
|
1649
|
+
private async buildSessionQrAttachmentFromBundle(
|
|
1650
|
+
bundle: PrivateClawInviteBundle,
|
|
1651
|
+
): Promise<PrivateClawAttachment> {
|
|
1617
1652
|
const pngBuffer = await QRCode.toBuffer(bundle.inviteUri, {
|
|
1618
1653
|
type: "png",
|
|
1619
1654
|
errorCorrectionLevel: PRIVATECLAW_QR_ERROR_CORRECTION_LEVEL,
|
|
@@ -0,0 +1,509 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { spawn } from "node:child_process";
|
|
3
|
+
import { createServer } from "node:http";
|
|
4
|
+
import { mkdtemp, mkdir, rm, writeFile } from "node:fs/promises";
|
|
5
|
+
import { type AddressInfo } from "node:net";
|
|
6
|
+
import os from "node:os";
|
|
7
|
+
import path from "node:path";
|
|
8
|
+
import test from "node:test";
|
|
9
|
+
import {
|
|
10
|
+
decodeInviteString,
|
|
11
|
+
decryptPayload,
|
|
12
|
+
encryptPayload,
|
|
13
|
+
type PrivateClawPayload,
|
|
14
|
+
} from "@privateclaw/protocol";
|
|
15
|
+
import WebSocket from "ws";
|
|
16
|
+
import { createRelayServer } from "../../../services/relay-server/src/relay-server.js";
|
|
17
|
+
import { EchoBridge } from "./bridges/echo-bridge.js";
|
|
18
|
+
import { resolvePrivateClawMediaDir } from "./invite-qr-files.js";
|
|
19
|
+
import { DEFAULT_SESSION_TTL_MS, PrivateClawProvider } from "./provider.js";
|
|
20
|
+
import {
|
|
21
|
+
buildManagedSessionQrLegacyLines,
|
|
22
|
+
closeManagedSessionFromStateDir,
|
|
23
|
+
getManagedSessionQrBundleFromStateDir,
|
|
24
|
+
isManagedSessionQrLegacyResult,
|
|
25
|
+
PrivateClawSessionControlServer,
|
|
26
|
+
resolvePrivateClawControlDir,
|
|
27
|
+
} from "./session-control.js";
|
|
28
|
+
|
|
29
|
+
const PNG_SIGNATURE = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
|
|
30
|
+
|
|
31
|
+
function waitForOpen(socket: WebSocket): Promise<void> {
|
|
32
|
+
return new Promise((resolve, reject) => {
|
|
33
|
+
socket.once("open", () => resolve());
|
|
34
|
+
socket.once("error", reject);
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function nextMessage(socket: WebSocket): Promise<Record<string, unknown>> {
|
|
39
|
+
return new Promise((resolve, reject) => {
|
|
40
|
+
socket.once("message", (data) => {
|
|
41
|
+
resolve(JSON.parse(data.toString()) as Record<string, unknown>);
|
|
42
|
+
});
|
|
43
|
+
socket.once("error", reject);
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function nextMessages(socket: WebSocket, count: number): Promise<Record<string, unknown>[]> {
|
|
48
|
+
return new Promise((resolve, reject) => {
|
|
49
|
+
const messages: Record<string, unknown>[] = [];
|
|
50
|
+
|
|
51
|
+
const handleMessage = (data: WebSocket.RawData) => {
|
|
52
|
+
messages.push(JSON.parse(data.toString()) as Record<string, unknown>);
|
|
53
|
+
if (messages.length === count) {
|
|
54
|
+
cleanup();
|
|
55
|
+
resolve(messages);
|
|
56
|
+
}
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
const handleError = (error: Error) => {
|
|
60
|
+
cleanup();
|
|
61
|
+
reject(error);
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
const cleanup = () => {
|
|
65
|
+
socket.off("message", handleMessage);
|
|
66
|
+
socket.off("error", handleError);
|
|
67
|
+
};
|
|
68
|
+
|
|
69
|
+
socket.on("message", handleMessage);
|
|
70
|
+
socket.on("error", handleError);
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function waitForClose(socket: WebSocket): Promise<void> {
|
|
75
|
+
return new Promise((resolve) => {
|
|
76
|
+
if (socket.readyState === WebSocket.CLOSED) {
|
|
77
|
+
resolve();
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
socket.once("close", () => resolve());
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function decryptRelayPayload(
|
|
85
|
+
frame: Record<string, unknown>,
|
|
86
|
+
params: { sessionId: string; sessionKey: string },
|
|
87
|
+
): PrivateClawPayload {
|
|
88
|
+
return decryptPayload({
|
|
89
|
+
sessionId: params.sessionId,
|
|
90
|
+
sessionKey: params.sessionKey,
|
|
91
|
+
envelope: frame.envelope as Parameters<typeof decryptPayload>[0]["envelope"],
|
|
92
|
+
});
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
test("session control can print and notify a managed session QR", async (t) => {
|
|
96
|
+
const relay = createRelayServer({
|
|
97
|
+
host: "127.0.0.1",
|
|
98
|
+
port: 0,
|
|
99
|
+
sessionTtlMs: 60_000,
|
|
100
|
+
frameCacheSize: 8,
|
|
101
|
+
});
|
|
102
|
+
const { port } = await relay.start();
|
|
103
|
+
t.after(async () => {
|
|
104
|
+
await relay.stop();
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
const stateDir = await mkdtemp(path.join(os.tmpdir(), "privateclaw-session-control-"));
|
|
108
|
+
t.after(async () => {
|
|
109
|
+
await rm(stateDir, { recursive: true, force: true });
|
|
110
|
+
});
|
|
111
|
+
|
|
112
|
+
const provider = new PrivateClawProvider({
|
|
113
|
+
providerWsUrl: `ws://127.0.0.1:${port}/ws/provider`,
|
|
114
|
+
appWsUrl: `ws://127.0.0.1:${port}/ws/app`,
|
|
115
|
+
bridge: new EchoBridge("OpenClaw bridge"),
|
|
116
|
+
defaultTtlMs: DEFAULT_SESSION_TTL_MS,
|
|
117
|
+
});
|
|
118
|
+
await provider.connect();
|
|
119
|
+
t.after(async () => {
|
|
120
|
+
await provider.dispose();
|
|
121
|
+
});
|
|
122
|
+
|
|
123
|
+
const controlServer = new PrivateClawSessionControlServer({
|
|
124
|
+
provider,
|
|
125
|
+
stateDir,
|
|
126
|
+
kind: "pair-foreground",
|
|
127
|
+
});
|
|
128
|
+
await controlServer.start();
|
|
129
|
+
t.after(async () => {
|
|
130
|
+
await controlServer.stop();
|
|
131
|
+
});
|
|
132
|
+
|
|
133
|
+
const inviteBundle = await provider.createInviteBundle({ groupMode: true });
|
|
134
|
+
const invite = decodeInviteString(inviteBundle.inviteUri);
|
|
135
|
+
|
|
136
|
+
const appOneUrl = new URL(invite.appWsUrl);
|
|
137
|
+
appOneUrl.searchParams.set("appId", "app-one");
|
|
138
|
+
const appOne = new WebSocket(appOneUrl.toString());
|
|
139
|
+
const appOneAttached = nextMessage(appOne);
|
|
140
|
+
await waitForOpen(appOne);
|
|
141
|
+
assert.equal((await appOneAttached).type, "relay:attached");
|
|
142
|
+
const appOneInitialFrames = nextMessages(appOne, 3);
|
|
143
|
+
appOne.send(
|
|
144
|
+
JSON.stringify({
|
|
145
|
+
type: "app:frame",
|
|
146
|
+
envelope: encryptPayload({
|
|
147
|
+
sessionId: invite.sessionId,
|
|
148
|
+
sessionKey: invite.sessionKey,
|
|
149
|
+
payload: {
|
|
150
|
+
kind: "client_hello",
|
|
151
|
+
appId: "app-one",
|
|
152
|
+
displayName: "SolarFox",
|
|
153
|
+
appVersion: "flutter-test",
|
|
154
|
+
deviceLabel: "Tester One",
|
|
155
|
+
sentAt: new Date().toISOString(),
|
|
156
|
+
},
|
|
157
|
+
}),
|
|
158
|
+
}),
|
|
159
|
+
);
|
|
160
|
+
await appOneInitialFrames;
|
|
161
|
+
|
|
162
|
+
const appTwoUrl = new URL(invite.appWsUrl);
|
|
163
|
+
appTwoUrl.searchParams.set("appId", "app-two");
|
|
164
|
+
const appTwo = new WebSocket(appTwoUrl.toString());
|
|
165
|
+
const appTwoAttached = nextMessage(appTwo);
|
|
166
|
+
await waitForOpen(appTwo);
|
|
167
|
+
assert.equal((await appTwoAttached).type, "relay:attached");
|
|
168
|
+
const appTwoInitialFrames = nextMessages(appTwo, 3);
|
|
169
|
+
const appOneJoinFrames = nextMessages(appOne, 2);
|
|
170
|
+
appTwo.send(
|
|
171
|
+
JSON.stringify({
|
|
172
|
+
type: "app:frame",
|
|
173
|
+
envelope: encryptPayload({
|
|
174
|
+
sessionId: invite.sessionId,
|
|
175
|
+
sessionKey: invite.sessionKey,
|
|
176
|
+
payload: {
|
|
177
|
+
kind: "client_hello",
|
|
178
|
+
appId: "app-two",
|
|
179
|
+
displayName: "RiverCat",
|
|
180
|
+
appVersion: "flutter-test",
|
|
181
|
+
deviceLabel: "Tester Two",
|
|
182
|
+
sentAt: new Date().toISOString(),
|
|
183
|
+
},
|
|
184
|
+
}),
|
|
185
|
+
}),
|
|
186
|
+
);
|
|
187
|
+
await Promise.all([appTwoInitialFrames, appOneJoinFrames]);
|
|
188
|
+
|
|
189
|
+
const appOneQrFrame = nextMessages(appOne, 1);
|
|
190
|
+
const appTwoQrFrame = nextMessages(appTwo, 1);
|
|
191
|
+
const result = await getManagedSessionQrBundleFromStateDir({
|
|
192
|
+
stateDir,
|
|
193
|
+
sessionId: invite.sessionId,
|
|
194
|
+
notifyParticipants: true,
|
|
195
|
+
});
|
|
196
|
+
|
|
197
|
+
assert.equal(result.host.kind, "pair-foreground");
|
|
198
|
+
assert.equal(result.session.sessionId, invite.sessionId);
|
|
199
|
+
assert.equal(result.bundle.inviteUri, inviteBundle.inviteUri);
|
|
200
|
+
|
|
201
|
+
const [appOneFrames, appTwoFrames] = await Promise.all([
|
|
202
|
+
appOneQrFrame,
|
|
203
|
+
appTwoQrFrame,
|
|
204
|
+
]);
|
|
205
|
+
for (const frame of [appOneFrames[0], appTwoFrames[0]]) {
|
|
206
|
+
assert.ok(frame);
|
|
207
|
+
const qrPayload = decryptRelayPayload(frame!, invite);
|
|
208
|
+
assert.equal(qrPayload.kind, "assistant_message");
|
|
209
|
+
assert.match(qrPayload.text, /二维码|QR/i);
|
|
210
|
+
assert.equal(qrPayload.attachments?.length, 1);
|
|
211
|
+
const qrAttachment = qrPayload.attachments?.[0];
|
|
212
|
+
assert.ok(qrAttachment);
|
|
213
|
+
assert.equal(qrAttachment.mimeType, "image/png");
|
|
214
|
+
assert.equal(qrAttachment.name, `privateclaw-${invite.sessionId}.png`);
|
|
215
|
+
assert.ok(qrAttachment.dataBase64);
|
|
216
|
+
assert.deepEqual(
|
|
217
|
+
Buffer.from(qrAttachment.dataBase64, "base64").subarray(0, PNG_SIGNATURE.length),
|
|
218
|
+
PNG_SIGNATURE,
|
|
219
|
+
);
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
appOne.close();
|
|
223
|
+
appTwo.close();
|
|
224
|
+
await Promise.all([waitForClose(appOne), waitForClose(appTwo)]);
|
|
225
|
+
});
|
|
226
|
+
|
|
227
|
+
test("session control can terminate a managed session", async (t) => {
|
|
228
|
+
const relay = createRelayServer({
|
|
229
|
+
host: "127.0.0.1",
|
|
230
|
+
port: 0,
|
|
231
|
+
sessionTtlMs: 60_000,
|
|
232
|
+
frameCacheSize: 8,
|
|
233
|
+
});
|
|
234
|
+
const { port } = await relay.start();
|
|
235
|
+
t.after(async () => {
|
|
236
|
+
await relay.stop();
|
|
237
|
+
});
|
|
238
|
+
|
|
239
|
+
const stateDir = await mkdtemp(path.join(os.tmpdir(), "privateclaw-session-control-close-"));
|
|
240
|
+
t.after(async () => {
|
|
241
|
+
await rm(stateDir, { recursive: true, force: true });
|
|
242
|
+
});
|
|
243
|
+
|
|
244
|
+
const provider = new PrivateClawProvider({
|
|
245
|
+
providerWsUrl: `ws://127.0.0.1:${port}/ws/provider`,
|
|
246
|
+
appWsUrl: `ws://127.0.0.1:${port}/ws/app`,
|
|
247
|
+
bridge: new EchoBridge("OpenClaw bridge"),
|
|
248
|
+
defaultTtlMs: DEFAULT_SESSION_TTL_MS,
|
|
249
|
+
});
|
|
250
|
+
await provider.connect();
|
|
251
|
+
t.after(async () => {
|
|
252
|
+
await provider.dispose();
|
|
253
|
+
});
|
|
254
|
+
|
|
255
|
+
const controlServer = new PrivateClawSessionControlServer({
|
|
256
|
+
provider,
|
|
257
|
+
stateDir,
|
|
258
|
+
kind: "pair-foreground",
|
|
259
|
+
});
|
|
260
|
+
await controlServer.start();
|
|
261
|
+
t.after(async () => {
|
|
262
|
+
await controlServer.stop();
|
|
263
|
+
});
|
|
264
|
+
|
|
265
|
+
const inviteBundle = await provider.createInviteBundle();
|
|
266
|
+
const invite = decodeInviteString(inviteBundle.inviteUri);
|
|
267
|
+
assert.equal(provider.listManagedSessions().length, 1);
|
|
268
|
+
|
|
269
|
+
const result = await closeManagedSessionFromStateDir({
|
|
270
|
+
stateDir,
|
|
271
|
+
sessionId: invite.sessionId,
|
|
272
|
+
reason: "operator_terminated",
|
|
273
|
+
});
|
|
274
|
+
|
|
275
|
+
assert.equal(result.terminatedHost, false);
|
|
276
|
+
assert.equal(result.session.sessionId, invite.sessionId);
|
|
277
|
+
assert.equal(provider.listManagedSessions().length, 0);
|
|
278
|
+
});
|
|
279
|
+
|
|
280
|
+
test("session control can terminate a legacy daemon host when close endpoint is unavailable", async (t) => {
|
|
281
|
+
const stateDir = await mkdtemp(path.join(os.tmpdir(), "privateclaw-session-control-legacy-close-"));
|
|
282
|
+
t.after(async () => {
|
|
283
|
+
await rm(stateDir, { recursive: true, force: true });
|
|
284
|
+
});
|
|
285
|
+
|
|
286
|
+
const sessionId = "legacy-close-session";
|
|
287
|
+
const child = spawn(
|
|
288
|
+
process.execPath,
|
|
289
|
+
[
|
|
290
|
+
"-e",
|
|
291
|
+
`
|
|
292
|
+
const { createServer } = require('node:http');
|
|
293
|
+
const { mkdirSync, writeFileSync } = require('node:fs');
|
|
294
|
+
const path = require('node:path');
|
|
295
|
+
const stateDir = process.env.STATE_DIR;
|
|
296
|
+
const sessionId = process.env.SESSION_ID;
|
|
297
|
+
const token = 'legacy-close-token';
|
|
298
|
+
const controlId = 'legacy-close-control';
|
|
299
|
+
const startedAt = new Date().toISOString();
|
|
300
|
+
const controlDir = path.join(stateDir, 'privateclaw', 'control');
|
|
301
|
+
const server = createServer((request, response) => {
|
|
302
|
+
if (request.headers.authorization !== \`Bearer \${token}\`) {
|
|
303
|
+
response.statusCode = 401;
|
|
304
|
+
response.end(JSON.stringify({ error: 'unauthorized' }));
|
|
305
|
+
return;
|
|
306
|
+
}
|
|
307
|
+
const url = new URL(request.url || '/', 'http://127.0.0.1');
|
|
308
|
+
if (request.method === 'GET' && url.pathname === '/sessions') {
|
|
309
|
+
response.statusCode = 200;
|
|
310
|
+
response.setHeader('content-type', 'application/json; charset=utf-8');
|
|
311
|
+
response.end(JSON.stringify({
|
|
312
|
+
host: {
|
|
313
|
+
controlId,
|
|
314
|
+
kind: 'pair-daemon',
|
|
315
|
+
pid: process.pid,
|
|
316
|
+
startedAt,
|
|
317
|
+
},
|
|
318
|
+
sessions: [{
|
|
319
|
+
sessionId,
|
|
320
|
+
expiresAt: new Date(Date.now() + 60_000).toISOString(),
|
|
321
|
+
groupMode: false,
|
|
322
|
+
participantCount: 0,
|
|
323
|
+
participants: [],
|
|
324
|
+
state: 'awaiting_hello',
|
|
325
|
+
}],
|
|
326
|
+
}));
|
|
327
|
+
return;
|
|
328
|
+
}
|
|
329
|
+
if (request.method === 'POST' && url.pathname === \`/sessions/\${encodeURIComponent(sessionId)}/close\`) {
|
|
330
|
+
response.statusCode = 404;
|
|
331
|
+
response.end(JSON.stringify({ error: 'not found' }));
|
|
332
|
+
return;
|
|
333
|
+
}
|
|
334
|
+
response.statusCode = 404;
|
|
335
|
+
response.end(JSON.stringify({ error: 'missing' }));
|
|
336
|
+
});
|
|
337
|
+
server.listen(0, '127.0.0.1', () => {
|
|
338
|
+
const address = server.address();
|
|
339
|
+
mkdirSync(controlDir, { recursive: true, mode: 0o700 });
|
|
340
|
+
writeFileSync(path.join(controlDir, \`\${controlId}.json\`), JSON.stringify({
|
|
341
|
+
version: 1,
|
|
342
|
+
controlId,
|
|
343
|
+
kind: 'pair-daemon',
|
|
344
|
+
pid: process.pid,
|
|
345
|
+
host: '127.0.0.1',
|
|
346
|
+
port: address.port,
|
|
347
|
+
token,
|
|
348
|
+
startedAt,
|
|
349
|
+
}, null, 2), 'utf8');
|
|
350
|
+
process.stdout.write('ready\\n');
|
|
351
|
+
});
|
|
352
|
+
process.on('SIGTERM', () => {
|
|
353
|
+
server.close(() => process.exit(0));
|
|
354
|
+
});
|
|
355
|
+
setInterval(() => {}, 1000);
|
|
356
|
+
`,
|
|
357
|
+
],
|
|
358
|
+
{
|
|
359
|
+
env: {
|
|
360
|
+
...process.env,
|
|
361
|
+
STATE_DIR: stateDir,
|
|
362
|
+
SESSION_ID: sessionId,
|
|
363
|
+
},
|
|
364
|
+
stdio: ["ignore", "pipe", "inherit"],
|
|
365
|
+
},
|
|
366
|
+
);
|
|
367
|
+
t.after(async () => {
|
|
368
|
+
if (!child.killed && child.exitCode == null) {
|
|
369
|
+
child.kill("SIGTERM");
|
|
370
|
+
}
|
|
371
|
+
});
|
|
372
|
+
|
|
373
|
+
await new Promise<void>((resolve, reject) => {
|
|
374
|
+
child.once("error", reject);
|
|
375
|
+
child.stdout?.once("data", () => resolve());
|
|
376
|
+
});
|
|
377
|
+
|
|
378
|
+
const result = await closeManagedSessionFromStateDir({
|
|
379
|
+
stateDir,
|
|
380
|
+
sessionId,
|
|
381
|
+
reason: "operator_terminated",
|
|
382
|
+
});
|
|
383
|
+
|
|
384
|
+
assert.equal(result.terminatedHost, true);
|
|
385
|
+
assert.equal(result.session.sessionId, sessionId);
|
|
386
|
+
if (child.exitCode == null) {
|
|
387
|
+
await new Promise<void>((resolve) => {
|
|
388
|
+
child.once("exit", () => resolve());
|
|
389
|
+
});
|
|
390
|
+
}
|
|
391
|
+
});
|
|
392
|
+
|
|
393
|
+
test("session control falls back to the saved QR PNG when an older host lacks the qr endpoint", async (t) => {
|
|
394
|
+
const stateDir = await mkdtemp(path.join(os.tmpdir(), "privateclaw-session-control-legacy-"));
|
|
395
|
+
t.after(async () => {
|
|
396
|
+
await rm(stateDir, { recursive: true, force: true });
|
|
397
|
+
});
|
|
398
|
+
|
|
399
|
+
const sessionId = "legacy-session-qr";
|
|
400
|
+
const token = "legacy-control-token";
|
|
401
|
+
const controlId = "legacy-control-id";
|
|
402
|
+
const startedAt = new Date().toISOString();
|
|
403
|
+
const descriptorDir = resolvePrivateClawControlDir(stateDir);
|
|
404
|
+
await mkdir(descriptorDir, { recursive: true, mode: 0o700 });
|
|
405
|
+
const mediaDir = resolvePrivateClawMediaDir(stateDir);
|
|
406
|
+
await mkdir(mediaDir, { recursive: true });
|
|
407
|
+
const legacyPngPath = path.join(mediaDir, `privateclaw-${sessionId}.png`);
|
|
408
|
+
await writeFile(legacyPngPath, Buffer.concat([PNG_SIGNATURE, Buffer.from("legacy")]));
|
|
409
|
+
|
|
410
|
+
const server = createServer((request, response) => {
|
|
411
|
+
if (request.headers.authorization !== `Bearer ${token}`) {
|
|
412
|
+
response.statusCode = 401;
|
|
413
|
+
response.end(JSON.stringify({ error: "unauthorized" }));
|
|
414
|
+
return;
|
|
415
|
+
}
|
|
416
|
+
const url = new URL(request.url ?? "/", "http://127.0.0.1");
|
|
417
|
+
if (request.method === "GET" && url.pathname === "/sessions") {
|
|
418
|
+
response.statusCode = 200;
|
|
419
|
+
response.setHeader("content-type", "application/json; charset=utf-8");
|
|
420
|
+
response.end(
|
|
421
|
+
JSON.stringify({
|
|
422
|
+
host: {
|
|
423
|
+
controlId,
|
|
424
|
+
kind: "pair-daemon",
|
|
425
|
+
pid: process.pid,
|
|
426
|
+
startedAt,
|
|
427
|
+
},
|
|
428
|
+
sessions: [
|
|
429
|
+
{
|
|
430
|
+
sessionId,
|
|
431
|
+
expiresAt: new Date(Date.now() + 60_000).toISOString(),
|
|
432
|
+
groupMode: true,
|
|
433
|
+
participantCount: 1,
|
|
434
|
+
participants: [
|
|
435
|
+
{
|
|
436
|
+
appId: "legacy-app",
|
|
437
|
+
displayName: "Legacy Fox",
|
|
438
|
+
platform: "PrivateClaw",
|
|
439
|
+
},
|
|
440
|
+
],
|
|
441
|
+
state: "active",
|
|
442
|
+
},
|
|
443
|
+
],
|
|
444
|
+
}),
|
|
445
|
+
);
|
|
446
|
+
return;
|
|
447
|
+
}
|
|
448
|
+
if (
|
|
449
|
+
request.method === "POST" &&
|
|
450
|
+
url.pathname === `/sessions/${encodeURIComponent(sessionId)}/qr`
|
|
451
|
+
) {
|
|
452
|
+
response.statusCode = 404;
|
|
453
|
+
response.setHeader("content-type", "application/json; charset=utf-8");
|
|
454
|
+
response.end(JSON.stringify({ error: "not found" }));
|
|
455
|
+
return;
|
|
456
|
+
}
|
|
457
|
+
response.statusCode = 404;
|
|
458
|
+
response.end(JSON.stringify({ error: "missing" }));
|
|
459
|
+
});
|
|
460
|
+
await new Promise<void>((resolve) => {
|
|
461
|
+
server.listen(0, "127.0.0.1", () => resolve());
|
|
462
|
+
});
|
|
463
|
+
t.after(async () => {
|
|
464
|
+
await new Promise<void>((resolve, reject) => {
|
|
465
|
+
server.close((error) => (error ? reject(error) : resolve()));
|
|
466
|
+
});
|
|
467
|
+
});
|
|
468
|
+
|
|
469
|
+
const address = server.address() as AddressInfo;
|
|
470
|
+
await writeFile(
|
|
471
|
+
path.join(descriptorDir, `${controlId}.json`),
|
|
472
|
+
JSON.stringify(
|
|
473
|
+
{
|
|
474
|
+
version: 1,
|
|
475
|
+
controlId,
|
|
476
|
+
kind: "pair-daemon",
|
|
477
|
+
pid: process.pid,
|
|
478
|
+
host: "127.0.0.1",
|
|
479
|
+
port: address.port,
|
|
480
|
+
token,
|
|
481
|
+
startedAt,
|
|
482
|
+
},
|
|
483
|
+
null,
|
|
484
|
+
2,
|
|
485
|
+
),
|
|
486
|
+
"utf8",
|
|
487
|
+
);
|
|
488
|
+
|
|
489
|
+
const result = await getManagedSessionQrBundleFromStateDir({
|
|
490
|
+
stateDir,
|
|
491
|
+
sessionId,
|
|
492
|
+
notifyParticipants: true,
|
|
493
|
+
});
|
|
494
|
+
|
|
495
|
+
assert.equal(isManagedSessionQrLegacyResult(result), true);
|
|
496
|
+
if (!isManagedSessionQrLegacyResult(result)) {
|
|
497
|
+
throw new Error("expected a legacy QR fallback result");
|
|
498
|
+
}
|
|
499
|
+
assert.equal(result.notifyParticipantsSupported, false);
|
|
500
|
+
assert.equal(result.legacyPngPath, legacyPngPath);
|
|
501
|
+
assert.equal(result.session.sessionId, sessionId);
|
|
502
|
+
assert.match(
|
|
503
|
+
buildManagedSessionQrLegacyLines({
|
|
504
|
+
result,
|
|
505
|
+
notifyParticipants: true,
|
|
506
|
+
}).join("\n"),
|
|
507
|
+
/notified|推送/u,
|
|
508
|
+
);
|
|
509
|
+
});
|