@pushary/agent-hooks 1.9.164 → 1.9.165

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/CHANGELOG.md CHANGED
@@ -1,5 +1,14 @@
1
1
  # Changelog
2
2
 
3
+ ## 1.9.165
4
+
5
+ - This CLI carries the OpenClaw plugin 0.1.5, which closes `.env` leaks found in reviews of 0.1.4. The plugin now reads an `apply_patch` with OpenClaw's own grammar, so it accepts exactly the patches OpenClaw accepts and splits them into the same files. A header is trimmed, and counts only where the parser expects one: at the start of the patch, after a `*** Delete File:` line, after the `+` lines of an added file, and at a `***` line that starts a line inside an update. An indented header inside a `.env` update is therefore a line of that file. 0.1.4 started a new section there and sent the `.env` lines after it. The approval now names exactly the files OpenClaw writes, including one whose indented header follows a deletion or an added file, and withholds the lines of every `.env` hunk and of any hunk with a header-shaped line that names a `.env` file. A patch that moves a file into or out of a `.env` file withholds every hunk, because lines added to a file in one hunk travel with the move in the next. A patch that mentions `.env` and that OpenClaw would not parse is withheld whole, and names only the headers that start a line. A file name that matches a secret pattern, such as 40 or more letters, digits and slashes in a row, is still redacted like any other text.
6
+ - A complete `.env` write lists its names only when every name is uppercase letters, digits and underscores, and every value is unquoted, or quoted on one line with no backslash or inner quote. Otherwise it sends neither names nor values. Before, an escaped quote such as `MOTD="hello \"`, or a quote inside an unquoted value, made the next line read as a name, and a lowercase line such as a wrapped base64 tail was sent as a name.
7
+ - A file change the plugin cannot read withholds its parameters when its `path` is a `.env` file, or, without a `path`, when any parameter name or value mentions `.env`. That covers an `apply_patch` OpenClaw would not parse, such as `*** Add File:.env` without the space, an `apply_patch` whose patch is not a plain string, such as `command: ["apply_patch", "<patch>"]`, and a `write` or `edit` that passes `file_path`. A patch names the files whose headers start a line. Before, each of these sent every parameter, values included.
8
+ - A path is treated as a `.env` file when its Windows or POSIX reading resolves to one, such as `.env/x/..` or `.env/a\b/..`, with Windows trailing dots and spaces (`.env .`) and a trailing `</arg_value>>` removed. A path that is not plain is treated the same way: one with surrounding whitespace, a URL scheme in any case, a `:` anywhere but in a drive prefix such as `C:\` at the start, or any of `% ? # < > | * "` or an ASCII control character. OpenClaw resolves such a path differently in its default, workspace-only and sandbox setups, and in some it becomes a `.env` file: `FILE:///ws/.env?`, `.env</arg_value>>/` and `file:///tmp/x?/.env` all wrote one. Before, each of these sent the values. Ordinary paths, including Windows drive paths, spaces and non-ASCII names, are shown as before.
9
+ - The write guard asks for any path that is not plain, by the same rule: surrounding whitespace, a URL scheme in any case, a `:` anywhere but in a drive prefix, any of `% ? # < > | * "` or an ASCII control character. OpenClaw resolves such paths differently in its default, workspace-only and sandbox setups, and several reach its state: `FILE:///…/workspace/hooks/x.js`, `~/proj/.env</arg_value>>`, `.env<//arg_value>>`, ` /../../openclaw.json` and `file:///../hooks/x%5C.js` each wrote a protected file. Before, each ran without asking. A write through an ordinary `file://` URL now asks too. So does a `write` through a symbolic link whose target does not exist yet, because the write creates the target: a link committed to a repository, such as `docs/notes.md -> ../hooks/evil.js`, made a plain-looking write create `hooks/evil.js`, and before it ran without asking. On macOS and Windows the guard also folds names the way macOS does. It folds together the letters macOS treats as one, such as `ß` and `ss`, the long s `ſ` and `s`, a ligature such as `st` and `st`, and a final `ς` and `σ`, and keeps apart the ones macOS keeps apart, such as `‥`, fullwidth letters and the dotless `ı`. So `hookſ/x.js` asks like `hooks/x.js`. Before, macOS wrote such a path into the `hooks` folder without asking. When the path, or a folder the guard compares it with (OpenClaw's own folders, the home folder, the workspace or the gateway's working folder), has a character Node cannot fold the way macOS does, the write or session spawn asks: any character missing from Node's Unicode tables, such as an emoji newer than them, an unpaired surrogate, or two subscript iotas on one letter. In a sandbox, an absolute path inside the container, such as `/workspace/hooks/x.js`, is still not mapped to the host folder it writes, so it does not ask.
10
+ - The plugin decides from the path as written and does not follow symbolic or hard links, so a write through a link to a `.env` file is shown as a write to the link.
11
+
3
12
  ## 1.9.164
4
13
 
5
14
  - On macOS and Linux, setup and `pushary upgrade`, and automatic updates on macOS, clear an install lock left marked "installation pending" once the process that started that installation has exited, the lock is more than an hour old, and the process list shows no npm install of Pushary still running. Before, nothing cleared it, so every setup, upgrade and daily update failed with "An earlier installation did not finish safely" until you deleted `~/.pushary/auto-update.lock` yourself. Pushary reads the process list with `ps` and keeps the lock while any npm `install` or `update` naming `pushary` or `@pushary/agent-hooks` is running, global or not, or a process runs from a dependency folder inside the installed package. The process doing the check and the shells that started it do not count, so `npm i -g pushary@latest && pushary setup` does not block its own setup. It also keeps the lock while the starting process is running, within the hour, for a lock dated in the future, and when `ps` cannot be read. Each refusal says which of these is holding it and how to retry sooner. The check reads command lines, so it still misses an installer that does not look like an npm install of Pushary, such as a renamed process, an install from a tarball path, or another package manager. On Windows the lock still stays until you remove it. This reverses part of 1.9.154 (#2828), which kept such a lock for good because elapsed time and an exited process do not prove npm stopped; the process list is the evidence Pushary now uses. A machine that 1.9.154 to 1.9.161 already left stuck clears the first time this release or a later one runs setup or upgrade there, for example `npx pushary@latest setup`; until then its daily update runs the older release and still fails.
@@ -57,7 +57,7 @@ Running `pushary setup` later installs the CLI's own copy over a ClawHub or npm
57
57
  - Every `nodes` action except the reads: `status`, `describe`, `pending`, `notify`, `camera_list`, `notifications_list` and the `device_*` reads. `nodes run` runs a command on a paired machine, `approve` pairs a new one, and the camera, screen and location actions take data from it.
58
58
  - Every `sessions_spawn` with `runtime: "acp"`. An ACP session runs Codex, Claude Code or another harness, whose own tool calls never reach this plugin, so starting one asks.
59
59
  - A `sessions_spawn` with a `cwd` outside the agent's workspace or in its `hooks` or `.openclaw` folder, or with a `projectId`, `projectGitUrl` or `worktree`. The question names the folder.
60
- - Every `write`, `edit` or `apply_patch` into OpenClaw's own files: anything inside an OpenClaw state directory, `~/.config/openclaw` (where Linux keeps `gateway.env`), `~/.pushary`, the `.env` in the gateway's working folder, the config file set by `OPENCLAW_CONFIG_PATH`, and the launchd and systemd files OpenClaw installs for its gateway. The one exception is the agent's own workspace when it lives inside the state directory, which is OpenClaw's default (`~/.openclaw/workspace`). The workspace `hooks` and `.openclaw` folders always ask, wherever the workspace is, because OpenClaw loads code from them: hooks from `hooks`, and plugins from `.openclaw/extensions`, which it finds before the installed ones. The plugin resolves `~`, `@` references, `file://` paths, relative paths against the agent's workspace, and symlinks before it decides, and a path it cannot resolve asks. Writes anywhere else run without asking.
60
+ - Every `write`, `edit` or `apply_patch` into OpenClaw's own files: anything inside an OpenClaw state directory, `~/.config/openclaw` (where Linux keeps `gateway.env`), `~/.pushary`, the `.env` in the gateway's working folder, the config file set by `OPENCLAW_CONFIG_PATH`, and the launchd and systemd files OpenClaw installs for its gateway. The one exception is the agent's own workspace when it lives inside the state directory, which is OpenClaw's default (`~/.openclaw/workspace`). The workspace `hooks` and `.openclaw` folders always ask, wherever the workspace is, because OpenClaw loads code from them: hooks from `hooks`, and plugins from `.openclaw/extensions`, which it finds before the installed ones. The plugin resolves `~`, `@` references, relative paths against the agent's workspace, and symlinks before it decides. A path it cannot resolve asks, including one through a symbolic link whose target does not exist yet, and so does any path that is not plain: one with surrounding whitespace, a URL scheme such as `file://`, a `:` other than in a drive prefix, any of `% ? # < > | * "` or an ASCII control character, because OpenClaw resolves those differently in its default, workspace-only and sandbox setups. On macOS and Windows, a path asks when it, or a folder the plugin compares it with, has a character Node cannot compare the way macOS does, such as one newer than Node's Unicode tables. In a sandbox it does not map an absolute path inside the container, such as `/workspace/hooks/x.js`, to the host folder OpenClaw writes, so such a write does not ask. Writes anywhere else run without asking.
61
61
 
62
62
  To gate more tools, list their OpenClaw tool ids. The list adds to the defaults above; it never replaces them:
63
63
 
@@ -104,7 +104,7 @@ Before anything is sent, the plugin removes what it can recognise as a secret:
104
104
 
105
105
  - Key and token formats it knows: Pushary keys, `sk-` keys (OpenAI, Anthropic), Stripe, GitHub, GitLab, Slack, Google, AWS access key ids, npm, xAI and JWTs, plus private key blocks and long base64-like strings of 40 or more characters.
106
106
  - Passwords in URLs, `Bearer` and `Authorization` values, and the value of anything named like a password, token, secret, API key, access key, client secret or private key. In JSON this holds at any depth, whatever the value.
107
- - For a complete write to a `.env` file (`.env`, `.env.*` or a name ending in `.env`, such as `gateway.env`), Pushary receives the variable names when every line is a plain `NAME=value` assignment, a comment or blank. A file with any other line, such as a value spread over several lines, sends neither names nor values. For an edit or patch, Pushary receives the paths and omits the dotenv change contents because a fragment can start inside a value.
107
+ - For a complete write to a `.env` file (`.env`, `.env.*` or a name ending in `.env`, such as `gateway.env`), Pushary receives the variable names when every line is a comment, blank, or a plain assignment: an uppercase `NAME`, and a value that is unquoted, or quoted on one line with no backslash or inner quote. A file with any other line, such as a value spread over several lines, sends neither names nor values. For an edit or patch, Pushary receives the paths and omits the dotenv change contents because a fragment can start inside a value. A patch that moves a file into or out of a `.env` file omits the contents of every file in it. A path that is not plain, with surrounding whitespace, a URL scheme, a `:` anywhere but in a drive prefix such as `C:\` at the start, or any of `% ? # < > | * "` or an ASCII control character, is treated as a `.env` file, because OpenClaw can resolve it to one. The plugin decides from the path as written and does not follow symbolic or hard links, so a write through a link to a `.env` file is sent as a write to the link. A file change the plugin cannot read is withheld too: a `write` or `edit` whose `path` is a `.env` file, and, when any parameter name or value mentions `.env`, a `write` or `edit` without a `path` or an `apply_patch` whose patch it cannot read. Pushary then receives the path, the names in patch headers that start a line, or `[dotenv file name not sent]`, plus where the call comes from, as listed above, and no other parameter.
108
108
 
109
109
  Redaction works from these patterns. A secret in a command that matches none of them, such as a password with spaces passed to a flag of its own, is sent as written. The plugin leaves the rest of a command as it is so you can see what will run.
110
110
 
@@ -1,7 +1,8 @@
1
- import { win32 } from 'node:path';
1
+ import { posix, win32 } from 'node:path';
2
2
  import { fileURLToPath } from 'node:url';
3
3
  import { isRecord } from './parameter-redaction.js';
4
- import { APPLY_PATCH_TOOL, EDIT_TOOL, patchTargetsOf, WRITE_TOOL } from './protected-writes.js';
4
+ import { columnZeroTargetsOf, patchHunksOf, patchTextOf } from './patch-hunks.js';
5
+ import { APPLY_PATCH_TOOL, EDIT_TOOL, isPlainPath, patchTargetsOf, withoutHostArgumentTails, WRITE_TOOL } from './protected-writes.js';
5
6
  import { redactSecrets, redactSecretsDeep } from './redaction.js';
6
7
  import { withHiddenCharactersShown } from './visible-text.js';
7
8
  export const WRITE_OPERATION = 'write';
@@ -15,22 +16,29 @@ const OLD_TEXT_PARAMETER = 'oldText';
15
16
  const NEW_TEXT_PARAMETER = 'newText';
16
17
  const ENV_FILE_NAME = '.env';
17
18
  const ENV_BLANK_OR_COMMENT_LINE = /^[ \t]*(?:#.*)?$/;
18
- const ENV_ASSIGNMENT_LINE = /^[ \t]*(?:export[ \t]+)?([A-Za-z_][A-Za-z0-9_.-]*)[ \t]*=[ \t]*(?:(?:"[^"]*"|'[^']*'|`[^`]*`)[ \t]*(?:#.*)?|[^"'`\s].*)?$/;
19
+ const ENV_ASSIGNMENT_LINE = /^[ \t]*(?:export[ \t]+)?([A-Z_][A-Z0-9_]*)[ \t]*=[ \t]*(?:(?:"[^"\\]*"|'[^'\\]*'|`[^`\\]*`)[ \t]*(?:#.*)?|[^"'`\\\s][^"'`\\]*)?$/;
19
20
  const WINDOWS_STREAM_SEPARATOR = ':';
21
+ const WINDOWS_TRAILING_DOTS_AND_SPACES = /[. ]+$/;
22
+ const FILE_URL_PREFIX = 'file://';
20
23
  const ENV_VALUE_HIDDEN = '[value not sent]';
21
24
  const ENV_EDIT_HIDDEN = '[dotenv change contents not sent]';
22
- const PATCH_FILE_START = /(?=^[ \t]*\*\*\* (?:Add|Delete|Update) File: )/m;
23
- const PATCH_END = '*** End Patch';
25
+ const ENV_FILE_NAME_HIDDEN = '[dotenv file name not sent]';
26
+ const DOTENV_MENTION = /\.env/i;
24
27
  const REMOVED_LINE_PREFIX = '- ';
25
28
  const ADDED_LINE_PREFIX = '+ ';
26
29
  const textParameter = (params, name) => {
27
30
  const value = params[name];
28
31
  return typeof value === 'string' ? value : undefined;
29
32
  };
33
+ const pathAsWrittenOf = (params) => textParameter(params, PATH_PARAMETER);
30
34
  const pathParameter = (params) => {
31
35
  const path = textParameter(params, PATH_PARAMETER)?.trim();
32
36
  return path ? path : undefined;
33
37
  };
38
+ const mayWriteEnvFile = (params) => {
39
+ const path = pathAsWrittenOf(params);
40
+ return path !== undefined && mayBeEnvFile(path);
41
+ };
34
42
  const fileUrlPathOf = (url) => {
35
43
  try {
36
44
  return fileURLToPath(url);
@@ -39,14 +47,22 @@ const fileUrlPathOf = (url) => {
39
47
  return url;
40
48
  }
41
49
  };
42
- const isEnvFileName = (name) => name.endsWith(ENV_FILE_NAME) || name.startsWith(`${ENV_FILE_NAME}.`);
43
- export const isEnvFile = (path) => {
44
- const referenced = path.trim().replace(/^@/, '');
45
- const resolved = referenced.startsWith('file://') ? fileUrlPathOf(referenced) : referenced;
46
- const name = win32.basename(resolved).toLowerCase();
50
+ const isEnvFileName = (name) => {
51
+ const windowsName = name.replace(WINDOWS_TRAILING_DOTS_AND_SPACES, '');
52
+ return windowsName.endsWith(ENV_FILE_NAME) || windowsName.startsWith(`${ENV_FILE_NAME}.`);
53
+ };
54
+ const isEnvFileOrStreamName = (name) => {
47
55
  const [nameBeforeStream = name] = name.split(WINDOWS_STREAM_SEPARATOR);
48
56
  return isEnvFileName(name) || isEnvFileName(nameBeforeStream);
49
57
  };
58
+ const resolvedFileNamesOf = (path) => [win32.basename(win32.normalize(path)), posix.basename(posix.normalize(path))].map(name => name.toLowerCase());
59
+ const isFileUrl = (path) => path.slice(0, FILE_URL_PREFIX.length).toLowerCase() === FILE_URL_PREFIX;
60
+ const spellingsOf = (path) => {
61
+ const referenced = withoutHostArgumentTails(path.trim().replace(/^@/, ''));
62
+ return isFileUrl(referenced) ? [referenced, fileUrlPathOf(referenced)] : [referenced];
63
+ };
64
+ export const isEnvFile = (path) => spellingsOf(path).flatMap(resolvedFileNamesOf).some(isEnvFileOrStreamName);
65
+ const mayBeEnvFile = (path) => !isPlainPath(path) || isEnvFile(path);
50
66
  const sendableText = (text) => redactSecretsDeep(withHiddenCharactersShown(text));
51
67
  const isEnvBlankOrComment = (line) => ENV_BLANK_OR_COMMENT_LINE.test(line);
52
68
  const assignedEnvNameOf = (line) => ENV_ASSIGNMENT_LINE.exec(line)?.[1] ?? null;
@@ -58,14 +74,29 @@ const envNamesOnly = (content) => {
58
74
  return ENV_EDIT_HIDDEN;
59
75
  return [...new Set(names)].sort().map(name => `${name}=${ENV_VALUE_HIDDEN}`).join('\n');
60
76
  };
61
- const isPatchPathHeader = (line) => patchTargetsOf(line).length > 0;
62
- const withoutEnvPatchContents = (patch) => patch.split(PATCH_FILE_START).map(section => {
63
- if (!patchTargetsOf(section).some(isEnvFile))
64
- return section;
65
- const headers = section.split(/\r?\n/).filter(isPatchPathHeader);
66
- const end = section.trimEnd().endsWith(PATCH_END) ? [PATCH_END] : [];
67
- return [...headers, ENV_EDIT_HIDDEN, ...end, ''].join('\n');
68
- }).join('');
77
+ const mentionsEnvFile = (text) => patchTargetsOf(text).some(mayBeEnvFile);
78
+ const mentionsDotenv = (text) => DOTENV_MENTION.test(text) || mentionsEnvFile(text);
79
+ const isEnvHunk = (hunk) => hunk.targets.some(mayBeEnvFile) || hunk.body.some(mentionsEnvFile);
80
+ const movesAnEnvFile = (hunk) => hunk.targets.length > 1 && hunk.targets.some(mayBeEnvFile);
81
+ const withheldHunkLinesOf = (hunk) => hunk.body.length === 0 ? hunk.headers : [...hunk.headers, ENV_EDIT_HIDDEN];
82
+ const shownHunkLinesOf = (hunk) => isEnvHunk(hunk) ? withheldHunkLinesOf(hunk) : [...hunk.headers, ...hunk.body];
83
+ const shownPatchBodyOf = (patch, hunks) => {
84
+ if (hunks.some(movesAnEnvFile))
85
+ return patchTextOf(hunks.flatMap(withheldHunkLinesOf));
86
+ return hunks.some(isEnvHunk) ? patchTextOf(hunks.flatMap(shownHunkLinesOf)) : patch;
87
+ };
88
+ const uniqueTargets = (targets) => [...new Set(targets)];
89
+ const namedOrHidden = (targets) => targets.length === 0 ? [ENV_FILE_NAME_HIDDEN] : uniqueTargets(targets);
90
+ const unparsedPatchOf = (patch) => mentionsDotenv(patch)
91
+ ? { paths: namedOrHidden(columnZeroTargetsOf(patch)), body: ENV_EDIT_HIDDEN }
92
+ : { paths: uniqueTargets(patchTargetsOf(patch)), body: patch };
93
+ const shownPatchOf = (patch) => {
94
+ const hunks = patchHunksOf(patch);
95
+ if (hunks === null)
96
+ return unparsedPatchOf(patch);
97
+ const paths = uniqueTargets(hunks.flatMap(hunk => hunk.targets));
98
+ return { paths, body: shownPatchBodyOf(patch, hunks) };
99
+ };
69
100
  const sendablePath = (path) => redactSecrets(withHiddenCharactersShown(path));
70
101
  const lineCountOf = (text) => {
71
102
  if (text.length === 0)
@@ -103,7 +134,7 @@ const writePreviewOf = (params) => {
103
134
  return {
104
135
  operation: WRITE_OPERATION,
105
136
  paths: [shownPath],
106
- body: `Write ${shownPath}, ${plural(lineCountOf(content), 'line')}:\n\n${sendableText(isEnvFile(path) ? envNamesOnly(content) : content)}`,
137
+ body: `Write ${shownPath}, ${plural(lineCountOf(content), 'line')}:\n\n${sendableText(mayWriteEnvFile(params) ? envNamesOnly(content) : content)}`,
107
138
  };
108
139
  };
109
140
  const shownEdit = (edit) => [prefixedLines(sendableText(edit.oldText), REMOVED_LINE_PREFIX), prefixedLines(sendableText(edit.newText), ADDED_LINE_PREFIX)].join('\n');
@@ -113,7 +144,7 @@ const editPreviewOf = (params) => {
113
144
  if (path === undefined || edits === null)
114
145
  return null;
115
146
  const shownPath = sendablePath(path);
116
- const changes = isEnvFile(path) ? ENV_EDIT_HIDDEN : edits.map(shownEdit).join('\n\n');
147
+ const changes = mayWriteEnvFile(params) ? ENV_EDIT_HIDDEN : edits.map(shownEdit).join('\n\n');
117
148
  return {
118
149
  operation: EDIT_OPERATION,
119
150
  paths: [shownPath],
@@ -125,12 +156,8 @@ const patchPreviewOf = (params) => {
125
156
  const patch = PATCH_PARAMETERS.map(name => textParameter(params, name)).find(hasPatchTargets);
126
157
  if (patch === undefined)
127
158
  return null;
128
- const targets = patchTargetsOf(patch);
129
- return {
130
- operation: PATCH_OPERATION,
131
- paths: targets.map(sendablePath),
132
- body: sendableText(targets.some(isEnvFile) ? withoutEnvPatchContents(patch) : patch),
133
- };
159
+ const shown = shownPatchOf(patch);
160
+ return { operation: PATCH_OPERATION, paths: shown.paths.map(sendablePath), body: sendableText(shown.body) };
134
161
  };
135
162
  const readablePreviewOf = (toolId, params) => {
136
163
  if (toolId === WRITE_TOOL)
@@ -141,13 +168,32 @@ const readablePreviewOf = (toolId, params) => {
141
168
  return patchPreviewOf(params);
142
169
  return null;
143
170
  };
144
- const PATH_CHANGE_OPERATIONS = new Map([
171
+ const FILE_CHANGE_OPERATIONS = new Map([
145
172
  [WRITE_TOOL, WRITE_OPERATION],
146
173
  [EDIT_TOOL, EDIT_OPERATION],
174
+ [APPLY_PATCH_TOOL, PATCH_OPERATION],
147
175
  ]);
148
- const withheldEnvChangeOf = (toolId, params) => {
149
- const operation = PATH_CHANGE_OPERATIONS.get(toolId);
176
+ const stringsIn = (value) => {
177
+ if (typeof value === 'string')
178
+ return [value];
179
+ if (Array.isArray(value))
180
+ return value.flatMap(stringsIn);
181
+ return isRecord(value) ? Object.entries(value).flatMap(([key, entry]) => [key, ...stringsIn(entry)]) : [];
182
+ };
183
+ const declaredTargetsOf = (toolId, params) => {
184
+ if (toolId === APPLY_PATCH_TOOL)
185
+ return stringsIn(params).flatMap(columnZeroTargetsOf);
150
186
  const path = pathParameter(params);
151
- return operation === undefined || path === undefined || !isEnvFile(path) ? null : { operation, paths: [sendablePath(path)], body: ENV_EDIT_HIDDEN };
187
+ return path === undefined ? [] : [path];
188
+ };
189
+ const declaresEnvChange = (toolId, params) => {
190
+ const path = toolId === APPLY_PATCH_TOOL ? undefined : pathParameter(params);
191
+ return path === undefined ? stringsIn(params).some(mentionsDotenv) : mayWriteEnvFile(params);
192
+ };
193
+ const withheldEnvChangeOf = (toolId, params) => {
194
+ const operation = FILE_CHANGE_OPERATIONS.get(toolId);
195
+ if (operation === undefined || !declaresEnvChange(toolId, params))
196
+ return null;
197
+ return { operation, paths: namedOrHidden(declaredTargetsOf(toolId, params)).map(sendablePath), body: ENV_EDIT_HIDDEN };
152
198
  };
153
199
  export const fileChangePreviewOf = (toolId, params) => readablePreviewOf(toolId, params) ?? withheldEnvChangeOf(toolId, params);
@@ -2,7 +2,7 @@ import { homedir } from 'node:os';
2
2
  import { basename, dirname, join } from 'node:path';
3
3
  import { fileURLToPath } from 'node:url';
4
4
  import { openClawEnvironmentOf, openClawPathsFrom, ownedPluginFolderIn } from './openclaw-paths.js';
5
- import { nodeRealpath, spawnsOutsideTheWorkspace, writesIntoOpenClaw } from './protected-writes.js';
5
+ import { nodeMayBeSymbolicLink, nodeRealpath, spawnsOutsideTheWorkspace, writesIntoOpenClaw } from './protected-writes.js';
6
6
  import { DEFAULT_OPENCLAW_AGENT_ID } from './settings.js';
7
7
  const CASE_INSENSITIVE_PLATFORMS = new Set(['darwin', 'win32']);
8
8
  const EXTENSIONS_DIRECTORY_NAME = 'extensions';
@@ -85,6 +85,7 @@ export const openClawWriteGuardFor = (api) => {
85
85
  const system = {
86
86
  osHome,
87
87
  realpath: nodeRealpath,
88
+ mayBeSymbolicLink: nodeMayBeSymbolicLink,
88
89
  caseInsensitive: CASE_INSENSITIVE_PLATFORMS.has(process.platform),
89
90
  workspaceFor: workspaceFrom(api),
90
91
  otherWorkingDirectories: [process.cwd()],
@@ -0,0 +1,110 @@
1
+ const BEGIN_PATCH = '*** Begin Patch';
2
+ const END_PATCH = '*** End Patch';
3
+ const HEREDOC_OPENINGS = ['<<EOF', "<<'EOF'", '<<"EOF"'];
4
+ const HEREDOC_CLOSING = 'EOF';
5
+ const HEREDOC_MINIMUM_LINES = 4;
6
+ const ADD_FILE = '*** Add File: ';
7
+ const DELETE_FILE = '*** Delete File: ';
8
+ const UPDATE_FILE = '*** Update File: ';
9
+ export const PATCH_MOVE_MARKER = '*** Move to: ';
10
+ export const PATCH_FILE_MARKERS = [ADD_FILE, DELETE_FILE, UPDATE_FILE];
11
+ export const PATCH_MARKER_PREFIX = '***';
12
+ const END_OF_FILE = '*** End of File';
13
+ const ADDED_LINE = '+';
14
+ const CHANGE_CONTEXT = '@@';
15
+ const CHANGE_CONTEXT_PREFIX = '@@ ';
16
+ const CHANGE_LINE_MARKERS = [' ', '+', '-'];
17
+ const PATCH_LINES = /\r?\n/;
18
+ const PATCH_LINE_BREAK = '\n';
19
+ const withoutHeredoc = (lines) => {
20
+ const first = lines[0];
21
+ const last = lines.at(-1);
22
+ const wrapped = lines.length >= HEREDOC_MINIMUM_LINES && first !== undefined && last !== undefined
23
+ && HEREDOC_OPENINGS.includes(first) && last.endsWith(HEREDOC_CLOSING);
24
+ return wrapped ? lines.slice(1, -1) : lines;
25
+ };
26
+ const hunkLinesOf = (patch) => {
27
+ const lines = withoutHeredoc(patch.trim().split(PATCH_LINES));
28
+ return lines[0]?.trim() === BEGIN_PATCH && lines.at(-1)?.trim() === END_PATCH ? lines.slice(1, -1) : null;
29
+ };
30
+ const hunkMarkerOf = (header) => PATCH_FILE_MARKERS.find(marker => header.startsWith(marker));
31
+ const moveHeaderOf = (line) => {
32
+ const header = line?.trim();
33
+ return header?.startsWith(PATCH_MOVE_MARKER) ? header : null;
34
+ };
35
+ const isChangeLine = (line) => line === '' || CHANGE_LINE_MARKERS.includes(line.charAt(0));
36
+ const opensWithContext = (line) => line === CHANGE_CONTEXT || line?.startsWith(CHANGE_CONTEXT_PREFIX) === true;
37
+ const chunkEndOf = (lines, start, isFirstChunk) => {
38
+ const hasContext = opensWithContext(lines[start]);
39
+ if (!hasContext && !isFirstChunk)
40
+ return null;
41
+ const changesStart = start + (hasContext ? 1 : 0);
42
+ if (changesStart >= lines.length || lines[changesStart] === END_OF_FILE)
43
+ return null;
44
+ for (let end = changesStart; end < lines.length; end += 1) {
45
+ const line = lines[end] ?? '';
46
+ if (line === END_OF_FILE)
47
+ return end + 1;
48
+ if (!isChangeLine(line))
49
+ return end === changesStart ? null : end;
50
+ }
51
+ return lines.length;
52
+ };
53
+ const updateBodyEndOf = (lines, start) => {
54
+ let offset = start;
55
+ let chunks = 0;
56
+ while (offset < lines.length) {
57
+ const line = lines[offset] ?? '';
58
+ if (line.trim() === '') {
59
+ offset += 1;
60
+ continue;
61
+ }
62
+ if (line.startsWith(PATCH_MARKER_PREFIX))
63
+ break;
64
+ const end = chunkEndOf(lines, offset, chunks === 0);
65
+ if (end === null)
66
+ return null;
67
+ offset = end;
68
+ chunks += 1;
69
+ }
70
+ return chunks === 0 ? null : offset;
71
+ };
72
+ const addBodyEndOf = (lines, start) => {
73
+ const end = lines.findIndex((line, index) => index >= start && !line.startsWith(ADDED_LINE));
74
+ return end === -1 ? lines.length : end;
75
+ };
76
+ const bodyEndOf = (marker, lines, start) => {
77
+ if (marker === DELETE_FILE)
78
+ return start;
79
+ return marker === ADD_FILE ? addBodyEndOf(lines, start) : updateBodyEndOf(lines, start);
80
+ };
81
+ export const patchHunksOf = (patch) => {
82
+ const lines = hunkLinesOf(patch);
83
+ if (lines === null)
84
+ return null;
85
+ const hunks = [];
86
+ let offset = 0;
87
+ while (offset < lines.length) {
88
+ const header = lines[offset]?.trim() ?? '';
89
+ const marker = hunkMarkerOf(header);
90
+ if (marker === undefined)
91
+ return null;
92
+ const moveHeader = marker === UPDATE_FILE ? moveHeaderOf(lines[offset + 1]) : null;
93
+ const headers = moveHeader === null ? [header] : [header, moveHeader];
94
+ const bodyStart = offset + headers.length;
95
+ const bodyEnd = bodyEndOf(marker, lines, bodyStart);
96
+ if (bodyEnd === null)
97
+ return null;
98
+ const targets = [header.slice(marker.length), ...(moveHeader === null ? [] : [moveHeader.slice(PATCH_MOVE_MARKER.length)])];
99
+ hunks.push({ headers, targets, body: lines.slice(bodyStart, bodyEnd) });
100
+ offset = bodyEnd;
101
+ }
102
+ return hunks;
103
+ };
104
+ export const patchTextOf = (hunkLines) => [BEGIN_PATCH, ...hunkLines, END_PATCH].join(PATCH_LINE_BREAK);
105
+ const COLUMN_ZERO_TARGET_MARKERS = [...PATCH_FILE_MARKERS, PATCH_MOVE_MARKER];
106
+ const columnZeroTargetOf = (line) => {
107
+ const marker = COLUMN_ZERO_TARGET_MARKERS.find(candidate => line.startsWith(candidate));
108
+ return marker === undefined ? [] : [line.trim().slice(marker.length)];
109
+ };
110
+ export const columnZeroTargetsOf = (patch) => patch.split(PATCH_LINES).flatMap(columnZeroTargetOf);
@@ -1,15 +1,19 @@
1
- import { realpathSync } from 'node:fs';
1
+ import { lstatSync, realpathSync } from 'node:fs';
2
2
  import { basename, dirname, isAbsolute, join, normalize, relative, resolve, sep } from 'node:path';
3
3
  import { fileURLToPath } from 'node:url';
4
+ import { PATCH_FILE_MARKERS, PATCH_MARKER_PREFIX, PATCH_MOVE_MARKER } from './patch-hunks.js';
4
5
  export const WRITE_TOOL = 'write';
5
6
  export const EDIT_TOOL = 'edit';
6
7
  export const APPLY_PATCH_TOOL = 'apply_patch';
7
8
  export const FILE_WRITING_TOOLS = [WRITE_TOOL, EDIT_TOOL, APPLY_PATCH_TOOL];
8
9
  const PATH_PARAMETER = 'path';
9
10
  const PATCH_PARAMETER = 'input';
10
- const PATCH_TARGET_MARKERS = ['*** Add File: ', '*** Delete File: ', '*** Update File: ', '*** Move to: '];
11
- const PATCH_MARKER_PREFIX = '***';
11
+ const PATCH_TARGET_MARKERS = [...PATCH_FILE_MARKERS, PATCH_MOVE_MARKER];
12
12
  const FILE_URL_PREFIX = 'file://';
13
+ const HOST_PATH_ARGUMENT_TAILS = /(?:<\/arg_value>>+\s*)+$/;
14
+ const NOT_PLAIN_PATH_CHARACTER = /[\u0000-\u001f\u007f%?#<>|*"]/;
15
+ const WINDOWS_DRIVE_PREFIX = /^[A-Za-z]:[\\/]/;
16
+ const PATH_SCHEME_SEPARATOR = ':';
13
17
  const FILE_REFERENCE_PREFIX = '@';
14
18
  const HOME_PREFIX = '~';
15
19
  const MISSING_PATH_CODES = new Set(['ENOENT', 'ENOTDIR']);
@@ -20,7 +24,7 @@ const RISKY_RELATIVE_STARTS = ['.pushary', '.config'];
20
24
  const errorCodeOf = (error) => typeof error === 'object' && error !== null && 'code' in error && typeof error.code === 'string' ? error.code : null;
21
25
  const canonicalPathOf = (path, system) => {
22
26
  const missing = [];
23
- let current = normalize(path);
27
+ let current = resolve(path);
24
28
  for (;;) {
25
29
  try {
26
30
  const real = system.realpath(current);
@@ -29,17 +33,20 @@ const canonicalPathOf = (path, system) => {
29
33
  catch (error) {
30
34
  const code = errorCodeOf(error);
31
35
  const parent = dirname(current);
32
- if (code === null || !MISSING_PATH_CODES.has(code) || parent === current)
36
+ if (code === null || !MISSING_PATH_CODES.has(code) || parent === current || system.mayBeSymbolicLink(current))
33
37
  return null;
34
38
  missing.push(basename(current));
35
39
  current = parent;
36
40
  }
37
41
  }
38
42
  };
39
- const comparable = (path, system) => {
40
- const composed = path.normalize('NFC');
41
- return system.caseInsensitive ? composed.toLowerCase() : composed;
42
- };
43
+ const DOTLESS_I = 'ı';
44
+ const caseFoldedCharacter = (character) => character === DOTLESS_I ? character : character.toLowerCase().toUpperCase().toLowerCase();
45
+ const caseFolded = (path) => Array.from(path.normalize('NFD'), caseFoldedCharacter).join('').normalize('NFC');
46
+ const comparable = (path, system) => system.caseInsensitive ? caseFolded(path) : path.normalize('NFC');
47
+ const CHARACTERS_THE_RUNTIME_CANNOT_FOLD = /[\p{Cn}\p{Cs}]/u;
48
+ const IOTA_SUBSCRIPTS_ON_ONE_LETTER = /ͅ\p{M}*ͅ/u;
49
+ const foldsAsTheDiskDoes = (path) => !CHARACTERS_THE_RUNTIME_CANNOT_FOLD.test(path) && !IOTA_SUBSCRIPTS_ON_ONE_LETTER.test(path.normalize('NFD'));
43
50
  const spellingsOfLocation = (path, system) => {
44
51
  const canonical = canonicalPathOf(path, system);
45
52
  const resolved = comparable(resolve(path), system);
@@ -53,11 +60,18 @@ const firstComponentUnder = (path, directory) => {
53
60
  return null;
54
61
  return relative(directory, path).split(sep)[0] ?? null;
55
62
  };
63
+ const locationSpellingsOf = (locations, system, workspace) => {
64
+ const places = [...locations.stateDirectories, ...locations.configFiles, ...locations.protectedTrees, ...locations.serviceFiles.map(location => location.directory), ...system.otherWorkingDirectories];
65
+ if (workspace !== null)
66
+ places.push(workspace);
67
+ return [...places.flatMap(place => [place, canonicalPathOf(place, system) ?? '']), ...locations.serviceFiles.map(location => location.namePrefix)];
68
+ };
56
69
  const comparablePathsFor = (locations, system, agentId) => {
57
70
  const stateDirectories = spellingsOfAll(locations.stateDirectories, system);
58
71
  const workspace = system.workspaceFor(agentId);
59
72
  const workspaceCanonical = workspace === null ? null : canonicalPathOf(workspace, system);
60
73
  return {
74
+ locationsFoldAsTheDiskDoes: !system.caseInsensitive || locationSpellingsOf(locations, system, workspace).every(foldsAsTheDiskDoes),
61
75
  stateDirectories,
62
76
  configFiles: spellingsOfAll(locations.configFiles, system),
63
77
  protectedTrees: spellingsOfAll(locations.protectedTrees, system),
@@ -97,9 +111,10 @@ const isProtectedLocation = (path, paths) => {
97
111
  return false;
98
112
  return !isInWorkspaceUnderState(path, paths);
99
113
  };
114
+ const foldCanBeTrustedFor = (path, paths, system) => !system.caseInsensitive || (paths.locationsFoldAsTheDiskDoes && foldsAsTheDiskDoes(path));
100
115
  const verdictForAbsolute = (path, paths, system) => {
101
116
  const canonical = canonicalPathOf(path, system);
102
- if (canonical === null)
117
+ if (canonical === null || !foldCanBeTrustedFor(canonical, paths, system))
103
118
  return 'uncertain';
104
119
  return isProtectedLocation(comparable(canonical, system), paths) ? 'protected' : 'clear';
105
120
  };
@@ -113,9 +128,8 @@ const spellingsOf = (raw) => {
113
128
  const referenced = raw.slice(FILE_REFERENCE_PREFIX.length);
114
129
  return [referenced.startsWith(FILE_REFERENCE_PREFIX) ? `./${referenced}` : referenced, `./${raw}`];
115
130
  };
116
- const absoluteOrRelative = (spelling, osHome) => {
117
- if (!spelling.startsWith(FILE_URL_PREFIX))
118
- return expandedHome(spelling, osHome);
131
+ const isFileUrlSpelling = (spelling) => spelling.slice(0, FILE_URL_PREFIX.length).toLowerCase() === FILE_URL_PREFIX;
132
+ const decodedFileUrlOf = (spelling) => {
119
133
  try {
120
134
  return fileURLToPath(spelling);
121
135
  }
@@ -123,6 +137,7 @@ const absoluteOrRelative = (spelling, osHome) => {
123
137
  return null;
124
138
  }
125
139
  };
140
+ const absoluteOrRelative = (spelling, osHome) => isFileUrlSpelling(spelling) ? decodedFileUrlOf(spelling) : expandedHome(spelling, osHome);
126
141
  const worstOf = (verdicts) => {
127
142
  if (verdicts.includes('protected'))
128
143
  return 'protected';
@@ -148,10 +163,7 @@ const landingPlacesOf = (relativePath, workspace, others) => {
148
163
  const fromInsideTheWorkspace = ancestorsUpTo(workspace, climbs).map(base => join(base, rest));
149
164
  return [...fromInsideTheWorkspace, resolve(workspace, relativePath), ...others.map(directory => resolve(directory, relativePath))];
150
165
  };
151
- const verdictForSpelling = (spelling, paths, system) => {
152
- const path = absoluteOrRelative(spelling, system.osHome);
153
- if (path === null || path.trim().length === 0)
154
- return 'uncertain';
166
+ const verdictForPath = (path, paths, system) => {
155
167
  if (isAbsolute(path))
156
168
  return verdictForAbsolute(path, paths, system);
157
169
  if (paths.riskyRelativeStarts.has(comparable(firstComponentOf(path), system)))
@@ -160,10 +172,21 @@ const verdictForSpelling = (spelling, paths, system) => {
160
172
  return 'uncertain';
161
173
  return worstOf(landingPlacesOf(path, paths.workspace, system.otherWorkingDirectories).map(place => verdictForAbsolute(place, paths, system)));
162
174
  };
175
+ export const withoutHostArgumentTails = (path) => path.replace(HOST_PATH_ARGUMENT_TAILS, '').trim();
176
+ export const isPlainPath = (path) => {
177
+ if (path !== path.trim())
178
+ return false;
179
+ const rest = path.replace(WINDOWS_DRIVE_PREFIX, '');
180
+ return !NOT_PLAIN_PATH_CHARACTER.test(rest) && !rest.includes(PATH_SCHEME_SEPARATOR);
181
+ };
182
+ const verdictForSpelling = (spelling, paths, system) => {
183
+ const path = expandedHome(spelling, system.osHome);
184
+ return path.trim().length === 0 ? 'uncertain' : verdictForPath(path, paths, system);
185
+ };
163
186
  const verdictForRawPath = (raw, paths, system) => {
164
- if (typeof raw !== 'string' || raw.trim().length === 0)
187
+ if (typeof raw !== 'string' || raw.trim().length === 0 || !isPlainPath(raw))
165
188
  return 'uncertain';
166
- return worstOf(spellingsOf(raw.trim()).map(spelling => verdictForSpelling(spelling, paths, system)));
189
+ return worstOf(spellingsOf(raw).map(spelling => verdictForSpelling(spelling, paths, system)));
167
190
  };
168
191
  const patchTargetOf = (line) => {
169
192
  const header = line.trimStart();
@@ -211,7 +234,7 @@ const spawnFolderVerdict = (raw, paths, system) => {
211
234
  if (expanded === null)
212
235
  return 'uncertain';
213
236
  const canonical = canonicalPathOf(resolve(paths.workspace, expanded), system);
214
- if (canonical === null)
237
+ if (canonical === null || !foldCanBeTrustedFor(canonical, paths, system))
215
238
  return 'uncertain';
216
239
  const folder = comparable(canonical, system);
217
240
  if (!isSameOrInside(folder, paths.workspace))
@@ -229,3 +252,11 @@ export const spawnsOutsideTheWorkspace = (locations, system, call) => {
229
252
  return spawnFolderVerdict(params[SPAWN_FOLDER_PARAMETER], comparablePathsFor(locations, system, call.agentId), system) !== 'clear';
230
253
  };
231
254
  export const nodeRealpath = (path) => realpathSync(path);
255
+ export const nodeMayBeSymbolicLink = (path) => {
256
+ try {
257
+ return lstatSync(path, { throwIfNoEntry: false })?.isSymbolicLink() === true;
258
+ }
259
+ catch {
260
+ return true;
261
+ }
262
+ };
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pushary/openclaw",
3
- "version": "0.1.4",
3
+ "version": "0.1.5",
4
4
  "description": "Phone approvals for OpenClaw. Pushary asks you before your AI agent runs a gated tool call, and blocks the call unless you approve it.",
5
5
  "author": "Pushary <business@pushary.com>",
6
6
  "homepage": "https://pushary.com/human-in-the-loop-openclaw",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pushary/agent-hooks",
3
- "version": "1.9.164",
3
+ "version": "1.9.165",
4
4
  "description": "Human-in-the-loop (HITL) for AI agents: ask a person for approvals or answers by push notification. One command connects Claude Code, Codex, Cursor, Gemini CLI and more.",
5
5
  "keywords": [
6
6
  "pushary",