@privateclaw/privateclaw 0.1.11 → 0.1.13

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.
@@ -4,7 +4,8 @@ import os from "node:os";
4
4
  import path from "node:path";
5
5
  import test from "node:test";
6
6
  import { fileURLToPath } from "node:url";
7
- import { decodeInviteString } from "@privateclaw/protocol";
7
+ import { decodeInviteString, encryptPayload } from "@privateclaw/protocol";
8
+ import WebSocket from "ws";
8
9
  import { createRelayServer } from "../../../services/relay-server/src/relay-server.js";
9
10
  import { EchoBridge } from "./bridges/echo-bridge.js";
10
11
  import { privateClawConfigSchema } from "./compat/openclaw.js";
@@ -88,6 +89,10 @@ class FakeCliCommand {
88
89
  return this;
89
90
  }
90
91
 
92
+ argument(_spec: string): FakeCliCommand {
93
+ return this;
94
+ }
95
+
91
96
  option(_flags: string, _description?: string, _defaultValue?: string | boolean): FakeCliCommand {
92
97
  return this;
93
98
  }
@@ -245,6 +250,119 @@ test("privateclaw command embeds qqimg tags for QQ channel replies", async (t) =
245
250
  assert.deepEqual(qrPng.subarray(0, PNG_SIGNATURE.length), PNG_SIGNATURE);
246
251
  });
247
252
 
253
+ test("privateclaw command can override the relay per invocation", async (t) => {
254
+ const defaultRelay = createRelayServer({
255
+ host: "127.0.0.1",
256
+ port: 0,
257
+ sessionTtlMs: 60_000,
258
+ frameCacheSize: 8,
259
+ });
260
+ const overrideRelay = createRelayServer({
261
+ host: "127.0.0.1",
262
+ port: 0,
263
+ sessionTtlMs: 60_000,
264
+ frameCacheSize: 8,
265
+ });
266
+ const [{ port: defaultPort }, { port: overridePort }] = await Promise.all([
267
+ defaultRelay.start(),
268
+ overrideRelay.start(),
269
+ ]);
270
+
271
+ const stateDir = await mkdtemp(path.join(os.tmpdir(), "privateclaw-plugin-state-"));
272
+ t.after(async () => {
273
+ await rm(stateDir, { recursive: true, force: true });
274
+ await Promise.all([defaultRelay.stop(), overrideRelay.stop()]);
275
+ });
276
+
277
+ const plugin = createOpenClawCompatiblePlugin({
278
+ providerWsUrl: `ws://127.0.0.1:${defaultPort}/ws/provider`,
279
+ appWsUrl: `ws://127.0.0.1:${defaultPort}/ws/app`,
280
+ bridge: new EchoBridge("OpenClaw bridge"),
281
+ welcomeMessage: "Welcome to PrivateClaw",
282
+ });
283
+ const { api, getCli, getCommand, getService } = createMockApi();
284
+ plugin.register(api);
285
+
286
+ const service = getService();
287
+ await service.start({
288
+ config: {},
289
+ stateDir,
290
+ logger: api.logger,
291
+ });
292
+ t.after(async () => {
293
+ await service.stop?.({
294
+ config: {},
295
+ stateDir,
296
+ logger: api.logger,
297
+ });
298
+ });
299
+
300
+ const command = getCommand();
301
+ const defaultReply = await command.handler({
302
+ channel: "telegram",
303
+ senderId: "tester",
304
+ isAuthorizedSender: true,
305
+ commandBody: "/privateclaw",
306
+ config: {},
307
+ });
308
+ const defaultInviteUri =
309
+ defaultReply.text?.match(/privateclaw:\/\/connect\?payload=\S+/)?.[0];
310
+ assert.ok(defaultInviteUri, "default command should print a PrivateClaw invite URI");
311
+ const defaultInvite = decodeInviteString(defaultInviteUri);
312
+ assert.match(defaultInvite.appWsUrl, new RegExp(`:${defaultPort}/ws/app`));
313
+
314
+ const overrideReply = await command.handler({
315
+ channel: "telegram",
316
+ senderId: "tester",
317
+ isAuthorizedSender: true,
318
+ commandBody: `/privateclaw relay=ws://127.0.0.1:${overridePort}`,
319
+ args: `relay=ws://127.0.0.1:${overridePort}`,
320
+ config: {},
321
+ });
322
+ const overrideInviteUri =
323
+ overrideReply.text?.match(/privateclaw:\/\/connect\?payload=\S+/)?.[0];
324
+ assert.ok(
325
+ overrideInviteUri,
326
+ "override command should print a PrivateClaw invite URI",
327
+ );
328
+ const overrideInvite = decodeInviteString(overrideInviteUri);
329
+ assert.match(overrideInvite.appWsUrl, new RegExp(`:${overridePort}/ws/app`));
330
+ assert.equal(overrideInvite.relayLabel, `127.0.0.1:${overridePort}`);
331
+
332
+ const cli = getCli();
333
+ const root = new FakeCliCommand("root");
334
+ await cli.registrar({
335
+ program: root,
336
+ config: {},
337
+ logger: api.logger,
338
+ });
339
+ const sessions = root.children.get("privateclaw")?.children.get("sessions");
340
+ assert.ok(
341
+ sessions?.actionHandler,
342
+ "plugin should register the privateclaw sessions subcommand",
343
+ );
344
+
345
+ const printed: string[] = [];
346
+ const originalLog = console.log;
347
+ console.log = (message?: unknown, ...optionalParams: unknown[]) => {
348
+ printed.push([message, ...optionalParams].map(String).join(" "));
349
+ };
350
+ t.after(() => {
351
+ console.log = originalLog;
352
+ });
353
+
354
+ await sessions.actionHandler?.();
355
+
356
+ assert.ok(
357
+ printed.some((line) => line.includes(defaultInvite.sessionId)),
358
+ "sessions should include the default-relay session",
359
+ );
360
+ assert.ok(
361
+ printed.some((line) => line.includes(overrideInvite.sessionId)),
362
+ "sessions should include the override-relay session",
363
+ );
364
+ });
365
+
248
366
  test("privateclaw plugin local pair CLI defaults to the long session TTL", async (t) => {
249
367
  const relay = createRelayServer({
250
368
  host: "127.0.0.1",
@@ -341,3 +459,292 @@ test("privateclaw plugin local pair CLI defaults to the long session TTL", async
341
459
  const qrPng = await readFile(qrPath);
342
460
  assert.deepEqual(qrPng.subarray(0, PNG_SIGNATURE.length), PNG_SIGNATURE);
343
461
  });
462
+
463
+ test("privateclaw plugin local pair CLI can override the relay per command", async (t) => {
464
+ const defaultRelay = createRelayServer({
465
+ host: "127.0.0.1",
466
+ port: 0,
467
+ sessionTtlMs: 60_000,
468
+ frameCacheSize: 8,
469
+ });
470
+ const overrideRelay = createRelayServer({
471
+ host: "127.0.0.1",
472
+ port: 0,
473
+ sessionTtlMs: 60_000,
474
+ frameCacheSize: 8,
475
+ });
476
+ const [{ port: defaultPort }, { port: overridePort }] = await Promise.all([
477
+ defaultRelay.start(),
478
+ overrideRelay.start(),
479
+ ]);
480
+
481
+ t.after(async () => {
482
+ await Promise.all([defaultRelay.stop(), overrideRelay.stop()]);
483
+ });
484
+
485
+ const plugin = createOpenClawCompatiblePlugin({
486
+ providerWsUrl: `ws://127.0.0.1:${defaultPort}/ws/provider`,
487
+ appWsUrl: `ws://127.0.0.1:${defaultPort}/ws/app`,
488
+ bridge: new EchoBridge("OpenClaw bridge"),
489
+ });
490
+ const { api, getCli } = createMockApi();
491
+ plugin.register(api);
492
+
493
+ const cli = getCli();
494
+ const root = new FakeCliCommand("root");
495
+ await cli.registrar({
496
+ program: root,
497
+ config: {},
498
+ logger: api.logger,
499
+ });
500
+
501
+ const pair = root.children.get("privateclaw")?.children.get("pair");
502
+ assert.ok(pair?.actionHandler, "plugin should register the privateclaw pair subcommand");
503
+
504
+ const stateDir = await mkdtemp(path.join(os.tmpdir(), "privateclaw-cli-state-"));
505
+ const previousStateDir = process.env.OPENCLAW_STATE_DIR;
506
+ process.env.OPENCLAW_STATE_DIR = stateDir;
507
+ t.after(async () => {
508
+ if (previousStateDir == null) {
509
+ delete process.env.OPENCLAW_STATE_DIR;
510
+ } else {
511
+ process.env.OPENCLAW_STATE_DIR = previousStateDir;
512
+ }
513
+ await rm(stateDir, { recursive: true, force: true });
514
+ });
515
+
516
+ const printed: string[] = [];
517
+ const originalLog = console.log;
518
+ console.log = (message?: unknown, ...optionalParams: unknown[]) => {
519
+ printed.push([message, ...optionalParams].map(String).join(" "));
520
+ };
521
+ t.after(() => {
522
+ console.log = originalLog;
523
+ });
524
+
525
+ await pair.actionHandler({
526
+ label: "CLI pairing session",
527
+ relay: `ws://127.0.0.1:${overridePort}`,
528
+ printOnly: true,
529
+ });
530
+
531
+ const inviteUri = printed.find((line) =>
532
+ line.startsWith("邀请链接 / Invite URI: privateclaw://connect?payload="),
533
+ );
534
+ assert.ok(inviteUri, "pair command should print a PrivateClaw invite URI");
535
+ const invite = decodeInviteString(
536
+ inviteUri.replace("邀请链接 / Invite URI: ", ""),
537
+ );
538
+ assert.match(invite.appWsUrl, new RegExp(`:${overridePort}/ws/app`));
539
+ assert.equal(invite.relayLabel, `127.0.0.1:${overridePort}`);
540
+ });
541
+
542
+ test("privateclaw CLI can list and remove active group-session participants", async (t) => {
543
+ const relay = createRelayServer({
544
+ host: "127.0.0.1",
545
+ port: 0,
546
+ sessionTtlMs: 60_000,
547
+ frameCacheSize: 8,
548
+ });
549
+ const { port } = await relay.start();
550
+
551
+ const stateDir = await mkdtemp(path.join(os.tmpdir(), "privateclaw-cli-state-"));
552
+ t.after(async () => {
553
+ await rm(stateDir, { recursive: true, force: true });
554
+ await relay.stop();
555
+ });
556
+
557
+ const plugin = createOpenClawCompatiblePlugin({
558
+ providerWsUrl: `ws://127.0.0.1:${port}/ws/provider`,
559
+ appWsUrl: `ws://127.0.0.1:${port}/ws/app`,
560
+ bridge: new EchoBridge("OpenClaw bridge"),
561
+ });
562
+ const { api, getCli, getCommand, getService } = createMockApi();
563
+ plugin.register(api);
564
+
565
+ const service = getService();
566
+ await service.start({
567
+ config: {},
568
+ stateDir,
569
+ logger: api.logger,
570
+ });
571
+ t.after(async () => {
572
+ await service.stop?.({
573
+ config: {},
574
+ stateDir,
575
+ logger: api.logger,
576
+ });
577
+ });
578
+
579
+ const cli = getCli();
580
+ const root = new FakeCliCommand("root");
581
+ await cli.registrar({
582
+ program: root,
583
+ config: {},
584
+ logger: api.logger,
585
+ });
586
+
587
+ const privateclaw = root.children.get("privateclaw");
588
+ assert.ok(privateclaw, "plugin should register a top-level privateclaw command");
589
+ const sessions = privateclaw.children.get("sessions");
590
+ const kick = privateclaw.children.get("kick");
591
+ assert.ok(sessions?.actionHandler, "plugin should register the privateclaw sessions subcommand");
592
+ assert.ok(kick?.actionHandler, "plugin should register the privateclaw kick subcommand");
593
+
594
+ const command = getCommand();
595
+ const reply = await command.handler({
596
+ channel: "telegram",
597
+ senderId: "tester",
598
+ isAuthorizedSender: true,
599
+ commandBody: "/privateclaw group",
600
+ args: "group",
601
+ config: {},
602
+ });
603
+ const inviteUri = reply.text?.match(/privateclaw:\/\/connect\?payload=\S+/)?.[0];
604
+ assert.ok(inviteUri, "reply text should include a PrivateClaw invite URI");
605
+ const invite = decodeInviteString(inviteUri);
606
+
607
+ const appOneUrl = new URL(invite.appWsUrl);
608
+ appOneUrl.searchParams.set("appId", "app-one");
609
+ const appOne = new WebSocket(appOneUrl.toString());
610
+ const appOneAttached = new Promise<Record<string, unknown>>((resolve, reject) => {
611
+ appOne.once("message", (data) => resolve(JSON.parse(data.toString()) as Record<string, unknown>));
612
+ appOne.once("error", reject);
613
+ });
614
+ await new Promise<void>((resolve, reject) => {
615
+ appOne.once("open", () => resolve());
616
+ appOne.once("error", reject);
617
+ });
618
+ assert.equal((await appOneAttached).type, "relay:attached");
619
+ const appOneInitialFrames = new Promise<Record<string, unknown>[]>((resolve, reject) => {
620
+ const messages: Record<string, unknown>[] = [];
621
+ const onMessage = (data: unknown) => {
622
+ messages.push(JSON.parse(String(data)) as Record<string, unknown>);
623
+ if (messages.length === 3) {
624
+ appOne.off("message", onMessage);
625
+ resolve(messages);
626
+ }
627
+ };
628
+ appOne.on("message", onMessage);
629
+ appOne.once("error", reject);
630
+ });
631
+ appOne.send(
632
+ JSON.stringify({
633
+ type: "app:frame",
634
+ envelope: encryptPayload({
635
+ sessionId: invite.sessionId,
636
+ sessionKey: invite.sessionKey,
637
+ payload: {
638
+ kind: "client_hello",
639
+ appId: "app-one",
640
+ displayName: "SolarFox",
641
+ appVersion: "flutter-test",
642
+ deviceLabel: "Tester One",
643
+ sentAt: new Date().toISOString(),
644
+ },
645
+ }),
646
+ }),
647
+ );
648
+ await appOneInitialFrames;
649
+
650
+ const appTwoUrl = new URL(invite.appWsUrl);
651
+ appTwoUrl.searchParams.set("appId", "app-two");
652
+ const appTwo = new WebSocket(appTwoUrl.toString());
653
+ const appTwoAttached = new Promise<Record<string, unknown>>((resolve, reject) => {
654
+ appTwo.once("message", (data) => resolve(JSON.parse(data.toString()) as Record<string, unknown>));
655
+ appTwo.once("error", reject);
656
+ });
657
+ await new Promise<void>((resolve, reject) => {
658
+ appTwo.once("open", () => resolve());
659
+ appTwo.once("error", reject);
660
+ });
661
+ assert.equal((await appTwoAttached).type, "relay:attached");
662
+ const appTwoInitialFrames = new Promise<Record<string, unknown>[]>((resolve, reject) => {
663
+ const messages: Record<string, unknown>[] = [];
664
+ const onMessage = (data: unknown) => {
665
+ messages.push(JSON.parse(String(data)) as Record<string, unknown>);
666
+ if (messages.length === 3) {
667
+ appTwo.off("message", onMessage);
668
+ resolve(messages);
669
+ }
670
+ };
671
+ appTwo.on("message", onMessage);
672
+ appTwo.once("error", reject);
673
+ });
674
+ const appOneJoinFrames = new Promise<Record<string, unknown>[]>((resolve, reject) => {
675
+ const messages: Record<string, unknown>[] = [];
676
+ const onMessage = (data: unknown) => {
677
+ messages.push(JSON.parse(String(data)) as Record<string, unknown>);
678
+ if (messages.length === 2) {
679
+ appOne.off("message", onMessage);
680
+ resolve(messages);
681
+ }
682
+ };
683
+ appOne.on("message", onMessage);
684
+ appOne.once("error", reject);
685
+ });
686
+ appTwo.send(
687
+ JSON.stringify({
688
+ type: "app:frame",
689
+ envelope: encryptPayload({
690
+ sessionId: invite.sessionId,
691
+ sessionKey: invite.sessionKey,
692
+ payload: {
693
+ kind: "client_hello",
694
+ appId: "app-two",
695
+ displayName: "RiverCat",
696
+ appVersion: "flutter-test",
697
+ deviceLabel: "Tester Two",
698
+ sentAt: new Date().toISOString(),
699
+ },
700
+ }),
701
+ }),
702
+ );
703
+ await Promise.all([appTwoInitialFrames, appOneJoinFrames]);
704
+
705
+ const printed: string[] = [];
706
+ const originalLog = console.log;
707
+ console.log = (message?: unknown, ...optionalParams: unknown[]) => {
708
+ printed.push([message, ...optionalParams].map(String).join(" "));
709
+ };
710
+ t.after(() => {
711
+ console.log = originalLog;
712
+ });
713
+
714
+ await sessions.actionHandler?.();
715
+ assert.ok(printed.some((line) => line.includes(invite.sessionId)));
716
+ assert.ok(printed.some((line) => line.includes("type=group")));
717
+ assert.ok(printed.some((line) => line.includes("participants=2")));
718
+ assert.ok(printed.some((line) => line.includes("SolarFox (app-one)")));
719
+ assert.ok(printed.some((line) => line.includes("RiverCat (app-two)")));
720
+ printed.length = 0;
721
+
722
+ const appTwoClosed = new Promise<Record<string, unknown>>((resolve, reject) => {
723
+ const onMessage = (data: WebSocket.RawData) => {
724
+ const message = JSON.parse(data.toString()) as Record<string, unknown>;
725
+ if (message.type !== "relay:session_closed") {
726
+ return;
727
+ }
728
+ cleanup();
729
+ resolve(message);
730
+ };
731
+ const onError = (error: Error) => {
732
+ cleanup();
733
+ reject(error);
734
+ };
735
+ const cleanup = () => {
736
+ appTwo.off("message", onMessage);
737
+ appTwo.off("error", onError);
738
+ };
739
+ appTwo.on("message", onMessage);
740
+ appTwo.on("error", onError);
741
+ });
742
+ await kick.actionHandler?.(invite.sessionId, "app-two");
743
+ assert.ok(printed.some((line) => line.includes("RiverCat (app-two)")));
744
+ const closed = await appTwoClosed;
745
+ assert.equal(closed.type, "relay:session_closed");
746
+ assert.equal(closed.reason, "participant_removed");
747
+
748
+ appOne.close();
749
+ appTwo.close();
750
+ });