@privateclaw/privateclaw 0.1.53 → 0.1.55

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,7 @@ import type {
4
4
  } from "@privateclaw/protocol";
5
5
  import { spawn } from "node:child_process";
6
6
  import { randomUUID } from "node:crypto";
7
- import { readFileSync } from "node:fs";
7
+ import { readFileSync, realpathSync } from "node:fs";
8
8
  import fs from "node:fs/promises";
9
9
  import os from "node:os";
10
10
  import path from "node:path";
@@ -24,6 +24,8 @@ interface OpenClawAgentBridgeExecOptions {
24
24
  maxBuffer: number;
25
25
  shell?: boolean;
26
26
  windowsHide?: boolean;
27
+ /** UTF-8 payload written to the child's stdin (used for --message-file -). */
28
+ stdin?: string;
27
29
  }
28
30
 
29
31
  type OpenClawAgentExecFile = (
@@ -221,10 +223,15 @@ export function resolveOpenClawLaunchCommand(options: {
221
223
  };
222
224
  }
223
225
 
226
+ // Security: never spawn the OpenClaw CLI through a shell. The bare-name
227
+ // fallback on Windows resolves to openclaw.cmd, which Node refuses to spawn
228
+ // without a shell (EINVAL); the caller then gets a clear error pointing at
229
+ // openclawAgentExecutable (an .exe or the Node CLI script) instead of a
230
+ // shell-interpretation path that could mangle session-derived arguments.
224
231
  return {
225
232
  file: "openclaw",
226
233
  args: [],
227
- shell: platform === "win32",
234
+ shell: false,
228
235
  };
229
236
  }
230
237
 
@@ -414,7 +421,7 @@ export class OpenClawAgentBridge implements PrivateClawAgentBridge {
414
421
  ) => void | Promise<void>;
415
422
  },
416
423
  ): Promise<BridgeResponse> {
417
- const args = this.buildArgs(sessionId, promptMessage);
424
+ const args = this.buildArgs(sessionId);
418
425
  this.verboseLog(
419
426
  `exec_start session=${sessionId} promptChars=${promptMessage.length} argCount=${args.length} includeArtifacts=${options?.includeArtifacts !== false} agent=${JSON.stringify(this.options.agentId ?? "default")} channel=${JSON.stringify(this.options.channel ?? "default")} local=${this.options.local === true} thinking=${JSON.stringify(this.options.thinking ?? "default")} timeoutSeconds=${this.options.timeoutSeconds ?? "default"}`,
420
427
  );
@@ -433,7 +440,7 @@ export class OpenClawAgentBridge implements PrivateClawAgentBridge {
433
440
  summary: summarizeThinkingTrace(latestTraceEntries),
434
441
  });
435
442
  };
436
- const stdoutPromise = this.execOpenClaw(args);
443
+ const stdoutPromise = this.execOpenClaw(args, promptMessage);
437
444
  if (options?.onThinkingTrace) {
438
445
  let pending = true;
439
446
  void stdoutPromise.then(
@@ -890,8 +897,12 @@ export class OpenClawAgentBridge implements PrivateClawAgentBridge {
890
897
  return staged;
891
898
  }
892
899
 
893
- private buildArgs(sessionId: string, message: string): string[] {
894
- const args = ["agent", "--session-id", sessionId, "--message", message, "--json"];
900
+ private buildArgs(sessionId: string): string[] {
901
+ // Security: the message body is supplied over stdin (see execOpenClaw), so no
902
+ // remote-controlled text ever reaches the process argument list. This keeps
903
+ // Windows shell metacharacters in message text inert even if a configured
904
+ // launcher still needs a shell (e.g. an explicit .cmd executable).
905
+ const args = ["agent", "--session-id", sessionId, "--message-file", "-", "--json"];
895
906
 
896
907
  if (this.options.agentId) {
897
908
  args.push("--agent", this.options.agentId);
@@ -912,7 +923,7 @@ export class OpenClawAgentBridge implements PrivateClawAgentBridge {
912
923
  return args;
913
924
  }
914
925
 
915
- private execOpenClaw(args: string[]): Promise<string> {
926
+ private execOpenClaw(args: string[], stdin?: string): Promise<string> {
916
927
  return new Promise((resolve, reject) => {
917
928
  this.execFileImpl(
918
929
  this.executable,
@@ -921,6 +932,7 @@ export class OpenClawAgentBridge implements PrivateClawAgentBridge {
921
932
  maxBuffer: DEFAULT_MAX_BUFFER,
922
933
  ...(this.executableUsesShell ? { shell: true } : {}),
923
934
  ...(process.platform === "win32" ? { windowsHide: true } : {}),
935
+ ...(stdin !== undefined ? { stdin } : {}),
924
936
  },
925
937
  (error, stdout, stderr) => {
926
938
  if (error) {
@@ -966,9 +978,16 @@ function defaultExecFileImpl(
966
978
  const child = spawn(file, args, {
967
979
  shell: options.shell,
968
980
  ...(typeof options.windowsHide === "boolean" ? { windowsHide: options.windowsHide } : {}),
969
- stdio: ["ignore", "pipe", "pipe"],
981
+ stdio: [options.stdin !== undefined ? "pipe" : "ignore", "pipe", "pipe"],
970
982
  });
971
983
 
984
+ if (options.stdin !== undefined && child.stdin) {
985
+ child.stdin.on("error", () => {
986
+ // The child may exit before reading stdin (EPIPE); the exit code decides.
987
+ });
988
+ child.stdin.end(options.stdin);
989
+ }
990
+
972
991
  const append = (chunk: Buffer | string, target: "stdout" | "stderr") => {
973
992
  const text = typeof chunk === "string" ? chunk : chunk.toString("utf8");
974
993
  bufferedBytes += Buffer.byteLength(text);
@@ -1433,16 +1452,37 @@ function resolveStructuredAttachmentFilePath(
1433
1452
  workspaceDir: string,
1434
1453
  ): string | undefined {
1435
1454
  const trimmedPath = rawFilePath.trim();
1436
- if (trimmedPath === "") {
1455
+ if (trimmedPath === "" || /^file:/iu.test(trimmedPath)) {
1456
+ // file: URLs are rejected outright; only plain paths are considered.
1437
1457
  return undefined;
1438
1458
  }
1439
1459
 
1440
- if (path.isAbsolute(trimmedPath)) {
1441
- return path.normalize(trimmedPath);
1460
+ // Security: every candidate (relative or absolute) must resolve inside the
1461
+ // workspace after following symlinks. Absolute paths therefore no longer
1462
+ // bypass containment, and a symlink inside the workspace cannot point out.
1463
+ const resolvedPath = normalizeMediaPath(trimmedPath, workspaceDir);
1464
+ if (!isPathInsideDirectory(workspaceDir, resolvedPath)) {
1465
+ return undefined;
1466
+ }
1467
+ const canonicalRoot = canonicalizePath(workspaceDir);
1468
+ const canonicalTarget = canonicalizePath(resolvedPath);
1469
+ if (!canonicalRoot || !canonicalTarget) {
1470
+ return undefined;
1442
1471
  }
1472
+ return isPathInsideDirectory(canonicalRoot, canonicalTarget) ? resolvedPath : undefined;
1473
+ }
1443
1474
 
1444
- const resolvedPath = normalizeMediaPath(trimmedPath, workspaceDir);
1445
- return isPathInsideDirectory(workspaceDir, resolvedPath) ? resolvedPath : undefined;
1475
+ /** realpath that tolerates a missing leaf (the root must exist, the file may not yet). */
1476
+ function canonicalizePath(targetPath: string): string | undefined {
1477
+ try {
1478
+ return realpathSync(targetPath);
1479
+ } catch {
1480
+ try {
1481
+ return path.join(realpathSync(path.dirname(targetPath)), path.basename(targetPath));
1482
+ } catch {
1483
+ return undefined;
1484
+ }
1485
+ }
1446
1486
  }
1447
1487
 
1448
1488
  function parseStructuredResponseResult(
@@ -2014,9 +2054,37 @@ export function inferMimeTypeFromFileName(fileName: string): string | undefined
2014
2054
  }
2015
2055
  }
2016
2056
 
2057
+ // Security: DOCX is a ZIP archive; expanding it synchronously without bounds
2058
+ // lets a small malicious file block the gateway event loop (CWE-409). Inspect
2059
+ // central-directory metadata first, then only inflate the Word XML entries we
2060
+ // actually need, each under a hard expanded-size cap.
2061
+ const DOCX_MAX_ENTRY_BYTES = 8 * 1024 * 1024;
2062
+ const DOCX_MAX_TOTAL_BYTES = 16 * 1024 * 1024;
2063
+ const DOCX_MAX_RATIO = 200;
2064
+
2017
2065
  function extractDocxText(buffer: Buffer): string {
2018
2066
  try {
2019
- const archive = unzipSync(new Uint8Array(buffer));
2067
+ const archive = unzipSync(new Uint8Array(buffer), {
2068
+ filter: (entry) => {
2069
+ if (!/^word\/(document|header\d+|footer\d+)\.xml$/u.test(entry.name)) {
2070
+ return false;
2071
+ }
2072
+ if (entry.originalSize > DOCX_MAX_ENTRY_BYTES) {
2073
+ throw new Error("docx entry exceeds size limit");
2074
+ }
2075
+ if (entry.originalSize > 0 && entry.originalSize / Math.max(entry.size, 1) > DOCX_MAX_RATIO) {
2076
+ throw new Error("docx entry exceeds compression ratio limit");
2077
+ }
2078
+ return true;
2079
+ },
2080
+ });
2081
+ let expandedBytes = 0;
2082
+ for (const entry of Object.values(archive)) {
2083
+ expandedBytes += entry.byteLength;
2084
+ if (expandedBytes > DOCX_MAX_TOTAL_BYTES) {
2085
+ return "";
2086
+ }
2087
+ }
2020
2088
  const sectionNames = Object.keys(archive)
2021
2089
  .filter((name) => /^word\/(document|header\d+|footer\d+)\.xml$/u.test(name))
2022
2090
  .sort((left, right) => {
package/src/setup.test.ts CHANGED
@@ -185,16 +185,17 @@ test("buildPrivateClawSetupPlan uses modern install flags on OpenClaw 2026.10+ h
185
185
  );
186
186
  assert.match(
187
187
  guidance,
188
- /openclaw plugins install --force --accept-capabilities @privateclaw\/privateclaw@0\.1\.26/,
188
+ /openclaw plugins install --force --accept-capabilities npm:@privateclaw\/privateclaw@0\.1\.26/,
189
189
  );
190
190
  assert.doesNotMatch(guidance, /dangerously-force-unsafe-install/u);
191
191
  });
192
192
 
193
- test("resolveOpenClawNpmSourcePrefixFromVersion gates the npm: prefix at OpenClaw 2026.11", () => {
193
+ test("resolveOpenClawNpmSourcePrefixFromVersion gates the npm: prefix at OpenClaw 2026.4", () => {
194
194
  assert.equal(resolveOpenClawNpmSourcePrefixFromVersion("2026.11.6"), "npm:");
195
195
  assert.equal(resolveOpenClawNpmSourcePrefixFromVersion("2027.1.2"), "npm:");
196
- assert.equal(resolveOpenClawNpmSourcePrefixFromVersion("2026.10.33"), "");
197
- assert.equal(resolveOpenClawNpmSourcePrefixFromVersion("2026.9.36"), "");
196
+ assert.equal(resolveOpenClawNpmSourcePrefixFromVersion("2026.10.33"), "npm:");
197
+ assert.equal(resolveOpenClawNpmSourcePrefixFromVersion("2026.4.24"), "npm:");
198
+ assert.equal(resolveOpenClawNpmSourcePrefixFromVersion("2026.3.31"), "");
198
199
  assert.equal(resolveOpenClawNpmSourcePrefixFromVersion("2026.3.22"), "");
199
200
  assert.equal(resolveOpenClawNpmSourcePrefixFromVersion(undefined), "");
200
201
  assert.equal(resolveOpenClawNpmSourcePrefixFromVersion("garbage"), "");
package/src/setup.ts CHANGED
@@ -147,11 +147,11 @@ export function resolveOpenClawInstallFlagsFromVersion(
147
147
  }
148
148
 
149
149
  /**
150
- * OpenClaw >= 2026.11 resolves bare package specs through ClawHub by
151
- * default, which can serve a stale mirror of the plugin. Prefix registry
152
- * specs with `npm:` on those hosts so installs always hit the npm registry.
153
- * Older hosts (<= 2026.10) treat bare specs as npm already and may not
154
- * understand the `npm:` scheme, so they keep the bare spec.
150
+ * OpenClaw hosts resolve bare scoped package specs through ClawHub by
151
+ * default (verified empirically on 2026.4.24 through 2026.11.6), which can
152
+ * serve a stale mirror of the plugin. Prefix registry specs with `npm:` on
153
+ * those hosts so installs always hit the npm registry. Pre-2026.4 hosts are
154
+ * unverified against this behavior, so they keep the bare spec.
155
155
  */
156
156
  export function resolveOpenClawNpmSourcePrefixFromVersion(
157
157
  version: string | undefined,
@@ -165,7 +165,7 @@ export function resolveOpenClawNpmSourcePrefixFromVersion(
165
165
  if (!Number.isFinite(parsedYear) || !Number.isFinite(parsedMonth) || rest.length === 0) {
166
166
  return "";
167
167
  }
168
- return parsedYear > 2026 || (parsedYear === 2026 && parsedMonth >= 11)
168
+ return parsedYear > 2026 || (parsedYear === 2026 && parsedMonth >= 4)
169
169
  ? "npm:"
170
170
  : "";
171
171
  }