open-pushscan 0.3.0__py3-none-any.whl
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.
- open_pushscan/__init__.py +2 -0
- open_pushscan/__main__.py +5 -0
- open_pushscan/agents.py +666 -0
- open_pushscan/ci.py +88 -0
- open_pushscan/cli.py +534 -0
- open_pushscan/config.py +256 -0
- open_pushscan/fingerprints.py +153 -0
- open_pushscan/gitscan.py +248 -0
- open_pushscan/hooks.py +121 -0
- open_pushscan/i18n.py +90 -0
- open_pushscan/media.py +318 -0
- open_pushscan/publish.py +160 -0
- open_pushscan/report.py +130 -0
- open_pushscan/rules.py +277 -0
- open_pushscan/scanner.py +226 -0
- open_pushscan/visibility.py +87 -0
- open_pushscan-0.3.0.dist-info/METADATA +193 -0
- open_pushscan-0.3.0.dist-info/RECORD +22 -0
- open_pushscan-0.3.0.dist-info/WHEEL +5 -0
- open_pushscan-0.3.0.dist-info/entry_points.txt +2 -0
- open_pushscan-0.3.0.dist-info/licenses/LICENSE +202 -0
- open_pushscan-0.3.0.dist-info/top_level.txt +1 -0
open_pushscan/agents.py
ADDED
|
@@ -0,0 +1,666 @@
|
|
|
1
|
+
"""Keep AI coding assistants (Claude Code, Codex) from going around the checks.
|
|
2
|
+
|
|
3
|
+
`setup` gives each assistant on this computer:
|
|
4
|
+
- a hook that runs before every shell command and file edit, and says no to the shortcuts around the checks:
|
|
5
|
+
--no-verify, changing core.hooksPath, editing the settings folder, `open-pushscan allow` and `uninstall`;
|
|
6
|
+
- for Codex, rules that forbid the same commands (they work even before the hook is trusted);
|
|
7
|
+
- a short note in the assistant's instructions (CLAUDE.md, AGENTS.md) on what to do when a commit is stopped.
|
|
8
|
+
|
|
9
|
+
The hook only ever says no, with the reason, so the assistant can fix the real problem; everything else goes through
|
|
10
|
+
the assistant's normal permission flow. It stops the usual shortcuts, not someone set on getting around it; git's own
|
|
11
|
+
hooks still do the checking.
|
|
12
|
+
"""
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import json
|
|
16
|
+
import os
|
|
17
|
+
import re
|
|
18
|
+
import shlex
|
|
19
|
+
import sys
|
|
20
|
+
|
|
21
|
+
from . import config
|
|
22
|
+
from .i18n import command, lang
|
|
23
|
+
|
|
24
|
+
GUARD = 'open_pushscan guard'
|
|
25
|
+
CLAUDE_MATCHER = 'Bash|PowerShell|Edit|Write|MultiEdit|NotebookEdit'
|
|
26
|
+
CODEX_MATCHER = 'Bash|apply_patch'
|
|
27
|
+
MARK_START, MARK_END = '<!-- open-pushscan start -->', '<!-- open-pushscan end -->'
|
|
28
|
+
# Set by the assistants in the commands they run; used to refuse `allow` even when there is a terminal.
|
|
29
|
+
AGENT_ENV = ('CLAUDECODE', 'CODEX_THREAD_ID', 'CODEX_TOOL_CALL_ID')
|
|
30
|
+
|
|
31
|
+
REASONS = {
|
|
32
|
+
'skip': ('不能跳過 git 的檢查(--no-verify、git commit -n)。',
|
|
33
|
+
"Skipping git's checks (--no-verify, git commit -n) is not allowed."),
|
|
34
|
+
'hooks': ('不能改 git 的 hooks 設定(core.hooksPath),改了 open-pushscan 就不會檢查。',
|
|
35
|
+
"Changing git's hooks setting (core.hooksPath) is not allowed: open-pushscan would stop checking."),
|
|
36
|
+
'env': ('git commit、push 時不能改 HOME、GIT_CONFIG_*、OPEN_PUSHSCAN_HOME 這類環境變數,改了檢查會讀不到設定。',
|
|
37
|
+
'Changing HOME, GIT_CONFIG_*, OPEN_PUSHSCAN_HOME or similar for git commit or push is not allowed: '
|
|
38
|
+
'the checks would not find their settings.'),
|
|
39
|
+
'allow': ('放行(open-pushscan allow)和移除(open-pushscan uninstall)只能由使用者自己在終端機執行。'
|
|
40
|
+
'覺得是誤判,就停下來把報告給使用者看,由使用者決定。',
|
|
41
|
+
'Allowing (open-pushscan allow) and removing (open-pushscan uninstall) can only be done by the user, '
|
|
42
|
+
'in their own terminal. If you think something is a false alarm, stop and show the report to the user.'),
|
|
43
|
+
'settings': ('不能改 open-pushscan 的設定資料夾(指紋、規則、放行清單都在裡面),只能在 fingerprints.txt、rules.txt '
|
|
44
|
+
'加新的一行。只是要看內容,用 cat 或讀檔工具;其他修改請使用者自己做。',
|
|
45
|
+
"open-pushscan's settings folder (fingerprints, rules, allowed items) cannot be changed, except adding "
|
|
46
|
+
'new lines to fingerprints.txt and rules.txt. To look at it, use cat or a file-reading tool; '
|
|
47
|
+
'other changes are for the user to make.'),
|
|
48
|
+
'protected': ('不能拿掉或關掉 open-pushscan 裝在 AI 工具裡的檢查。只是要看內容,用 cat 或讀檔工具;'
|
|
49
|
+
'要改這個檔案的其他設定,用編輯工具改,不要動到 open-pushscan 那幾行。',
|
|
50
|
+
'The open-pushscan check in AI tools cannot be removed or switched off. To look at the file, use cat '
|
|
51
|
+
'or a file-reading tool; to change other settings in it, use an edit tool and leave the open-pushscan '
|
|
52
|
+
'lines as they are.'),
|
|
53
|
+
}
|
|
54
|
+
NEXT = ('請照 open-pushscan 報告裡的「怎麼改」修改,再 commit 或 push;覺得是誤判,就停下來把報告給使用者看,由使用者決定要不要放行。',
|
|
55
|
+
"Fix what open-pushscan's report says, then commit or push again. If you think it is a false alarm, stop and "
|
|
56
|
+
'show the report to the user; only the user decides whether to allow it.')
|
|
57
|
+
|
|
58
|
+
NOTE = (
|
|
59
|
+
'## open-pushscan(commit 和 push 前的檢查)\n\n'
|
|
60
|
+
'這台電腦裝了 open-pushscan。git commit 和 push 時,它會檢查有沒有洩漏個人資料、電腦名稱、內部網路、密碼金鑰和 AI 工具痕跡。\n\n'
|
|
61
|
+
'- 被擋下時,照報告每一項的「怎麼改」修改,再 commit 或 push 一次。\n'
|
|
62
|
+
'- 不要繞過或關掉檢查:不加 --no-verify、不改 core.hooksPath、不改 open-pushscan 的設定資料夾,'
|
|
63
|
+
'也不要執行 open-pushscan allow 或 uninstall。\n'
|
|
64
|
+
'- 不要用「open-pushscan: allow」註記讓某一行略過檢查。\n'
|
|
65
|
+
'- 覺得是誤判時,停下來把報告給使用者看,由使用者決定要不要放行。\n'
|
|
66
|
+
'- commit 前想先檢查:{cmd} check',
|
|
67
|
+
'## open-pushscan (checks before commit and push)\n\n'
|
|
68
|
+
'open-pushscan is installed on this computer. On git commit and push it checks for personal data, computer names, '
|
|
69
|
+
'internal network details, passwords and keys, and AI tool traces.\n\n'
|
|
70
|
+
'- When it stops a commit or push, fix each item as its "Fix" line says, then commit or push again.\n'
|
|
71
|
+
'- Do not skip or switch off the checks: no --no-verify, no changes to core.hooksPath or to the open-pushscan '
|
|
72
|
+
'settings folder, and do not run open-pushscan allow or uninstall.\n'
|
|
73
|
+
'- Do not add an "open-pushscan: allow" note to make a line skip the checks.\n'
|
|
74
|
+
'- If you think something is a false alarm, stop and show the report to the user; the user decides.\n'
|
|
75
|
+
'- To check before committing: {cmd} check',
|
|
76
|
+
)
|
|
77
|
+
|
|
78
|
+
CODEX_RULES = '''# open-pushscan: made by `open-pushscan setup`; run it again to rebuild this file.
|
|
79
|
+
# Commands that go around open-pushscan's checks. The hook in hooks.json stops the other ways.
|
|
80
|
+
prefix_rule(pattern = ["git", ["commit", "push", "merge"], "--no-verify"], decision = "forbidden", justification = {why})
|
|
81
|
+
prefix_rule(pattern = ["git", "commit", "-n"], decision = "forbidden", justification = {why})
|
|
82
|
+
prefix_rule(pattern = ["git", "config", "--global", "--unset", "core.hooksPath"], decision = "forbidden", justification = {why})
|
|
83
|
+
prefix_rule(pattern = ["open-pushscan", ["allow", "uninstall"]], decision = "forbidden", justification = {why})
|
|
84
|
+
prefix_rule(pattern = [["python", "python3", "py"], "-m", "open_pushscan", ["allow", "uninstall"]], decision = "forbidden", justification = {why})
|
|
85
|
+
'''
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _t(pair, l=None) -> str:
|
|
89
|
+
return pair[0] if (l or lang()) == 'zh' else pair[1]
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def reason(key: str, l=None) -> str:
|
|
93
|
+
l = l or lang()
|
|
94
|
+
if key not in ('skip', 'hooks', 'env'):
|
|
95
|
+
return _t(REASONS[key], l)
|
|
96
|
+
return _t(REASONS[key], l) + ('' if l == 'zh' else ' ') + _t(NEXT, l)
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
# ---------------------------------------------------------------- where the assistants keep their settings
|
|
100
|
+
|
|
101
|
+
def claude_dir() -> str:
|
|
102
|
+
return os.environ.get('CLAUDE_CONFIG_DIR') or os.path.join(os.path.expanduser('~'), '.claude')
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def codex_dir() -> str:
|
|
106
|
+
return os.environ.get('CODEX_HOME') or os.path.join(os.path.expanduser('~'), '.codex')
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def files() -> dict:
|
|
110
|
+
c, x = claude_dir(), codex_dir()
|
|
111
|
+
return {'claude_settings': os.path.join(c, 'settings.json'), 'claude_md': os.path.join(c, 'CLAUDE.md'),
|
|
112
|
+
'codex_hooks': os.path.join(x, 'hooks.json'), 'codex_rules': os.path.join(x, 'rules', 'open-pushscan.rules'),
|
|
113
|
+
'agents_md': os.path.join(x, 'AGENTS.md')}
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def found() -> list:
|
|
117
|
+
"""The assistants on this computer: 'Claude Code', 'Codex'."""
|
|
118
|
+
return [name for name, d in (('Claude Code', claude_dir()), ('Codex', codex_dir())) if os.path.isdir(d)]
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def hook_command() -> str:
|
|
122
|
+
py = sys.executable.replace('\\', '/')
|
|
123
|
+
return (f'"{py}"' if ' ' in py else py) + ' -m ' + GUARD
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
# ---------------------------------------------------------------- installing
|
|
127
|
+
|
|
128
|
+
def _read(p: str) -> str:
|
|
129
|
+
try:
|
|
130
|
+
with open(p, encoding='utf-8') as f:
|
|
131
|
+
return f.read()
|
|
132
|
+
except (OSError, UnicodeDecodeError):
|
|
133
|
+
return ''
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def _write(p: str, text: str) -> None:
|
|
137
|
+
os.makedirs(os.path.dirname(p), exist_ok=True)
|
|
138
|
+
tmp = p + '.open-pushscan-tmp'
|
|
139
|
+
with open(tmp, 'w', encoding='utf-8', newline='\n') as f:
|
|
140
|
+
f.write(text)
|
|
141
|
+
os.replace(tmp, p)
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _json(p: str) -> dict:
|
|
145
|
+
text = _read(p)
|
|
146
|
+
data = json.loads(text) if text.strip() else {}
|
|
147
|
+
if not isinstance(data, dict):
|
|
148
|
+
raise ValueError(p)
|
|
149
|
+
return data
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def _drop_hook(data: dict) -> None:
|
|
153
|
+
groups = data.get('hooks', {}).get('PreToolUse', [])
|
|
154
|
+
for g in list(groups):
|
|
155
|
+
kept = [h for h in g.get('hooks', []) if GUARD not in str(h.get('command', ''))]
|
|
156
|
+
if len(kept) != len(g.get('hooks', [])):
|
|
157
|
+
if kept:
|
|
158
|
+
g['hooks'] = kept
|
|
159
|
+
else:
|
|
160
|
+
groups.remove(g)
|
|
161
|
+
if 'PreToolUse' in data.get('hooks', {}) and not groups:
|
|
162
|
+
del data['hooks']['PreToolUse']
|
|
163
|
+
if 'hooks' in data and not data['hooks']:
|
|
164
|
+
del data['hooks']
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def _add_hook(p: str, matcher: str) -> None:
|
|
168
|
+
data = _json(p)
|
|
169
|
+
_drop_hook(data)
|
|
170
|
+
data.setdefault('hooks', {}).setdefault('PreToolUse', []).append(
|
|
171
|
+
{'matcher': matcher, 'hooks': [{'type': 'command', 'command': hook_command(), 'timeout': 10}]})
|
|
172
|
+
_write(p, json.dumps(data, indent=2, ensure_ascii=False) + '\n')
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def _put_note(p: str, l: str) -> None:
|
|
176
|
+
old = _read(p)
|
|
177
|
+
block = f'{MARK_START}\n{_t(NOTE, l).format(cmd=command())}\n{MARK_END}'
|
|
178
|
+
if MARK_START in old and MARK_END in old:
|
|
179
|
+
new = re.sub(re.escape(MARK_START) + '.*?' + re.escape(MARK_END), lambda _m: block, old, flags=re.S)
|
|
180
|
+
else:
|
|
181
|
+
new = old.rstrip('\n') + ('\n\n' if old.strip() else '') + block + '\n'
|
|
182
|
+
if new != old:
|
|
183
|
+
_write(p, new)
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
def _drop_note(p: str) -> None:
|
|
187
|
+
old = _read(p)
|
|
188
|
+
if MARK_START not in old:
|
|
189
|
+
return
|
|
190
|
+
new = re.sub(r'\n*' + re.escape(MARK_START) + '.*?' + re.escape(MARK_END) + r'\n?', '\n', old, flags=re.S).strip('\n')
|
|
191
|
+
if new:
|
|
192
|
+
_write(p, new + '\n')
|
|
193
|
+
else:
|
|
194
|
+
os.remove(p)
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def install(l: str) -> list:
|
|
198
|
+
"""Protect every assistant found. Returns (name, files changed, problem file or '')."""
|
|
199
|
+
f, out = files(), []
|
|
200
|
+
for name in found():
|
|
201
|
+
try:
|
|
202
|
+
if name == 'Claude Code':
|
|
203
|
+
_add_hook(f['claude_settings'], CLAUDE_MATCHER)
|
|
204
|
+
_put_note(f['claude_md'], l)
|
|
205
|
+
out.append((name, [f['claude_settings'], f['claude_md']], ''))
|
|
206
|
+
else:
|
|
207
|
+
_add_hook(f['codex_hooks'], CODEX_MATCHER)
|
|
208
|
+
why = _t(('這會繞過 open-pushscan 的檢查。', "This goes around open-pushscan's checks. "), l) + _t(NEXT, l)
|
|
209
|
+
_write(f['codex_rules'], CODEX_RULES.format(why=json.dumps(why, ensure_ascii=False)))
|
|
210
|
+
_put_note(f['agents_md'], l)
|
|
211
|
+
out.append((name, [f['codex_hooks'], f['codex_rules'], f['agents_md']], ''))
|
|
212
|
+
except ValueError:
|
|
213
|
+
out.append((name, [], f['claude_settings'] if name == 'Claude Code' else f['codex_hooks']))
|
|
214
|
+
return out
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def uninstall() -> None:
|
|
218
|
+
f = files()
|
|
219
|
+
for key in ('claude_settings', 'codex_hooks'):
|
|
220
|
+
if GUARD not in _read(f[key]):
|
|
221
|
+
continue
|
|
222
|
+
try:
|
|
223
|
+
data = _json(f[key])
|
|
224
|
+
except ValueError:
|
|
225
|
+
continue
|
|
226
|
+
_drop_hook(data)
|
|
227
|
+
if data or key == 'claude_settings':
|
|
228
|
+
_write(f[key], json.dumps(data, indent=2, ensure_ascii=False) + '\n')
|
|
229
|
+
else:
|
|
230
|
+
os.remove(f[key])
|
|
231
|
+
if os.path.exists(f['codex_rules']):
|
|
232
|
+
os.remove(f['codex_rules'])
|
|
233
|
+
_drop_note(f['claude_md'])
|
|
234
|
+
_drop_note(f['agents_md'])
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def status() -> list:
|
|
238
|
+
"""(name, protected) for each assistant found."""
|
|
239
|
+
f = files()
|
|
240
|
+
return [(name, GUARD in _read(f['claude_settings' if name == 'Claude Code' else 'codex_hooks'])) for name in found()]
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
# ---------------------------------------------------------------- the hook
|
|
244
|
+
|
|
245
|
+
def guard_main() -> int:
|
|
246
|
+
"""Read the assistant's hook input; print a "deny" answer when the call would go around the checks."""
|
|
247
|
+
try:
|
|
248
|
+
data = json.loads(sys.stdin.read() or '{}')
|
|
249
|
+
why = decide(data) if isinstance(data, dict) else ''
|
|
250
|
+
except Exception: # never get in the way because of our own bug
|
|
251
|
+
return 0
|
|
252
|
+
if why:
|
|
253
|
+
sys.stdout.write(json.dumps({'hookSpecificOutput': {
|
|
254
|
+
'hookEventName': 'PreToolUse', 'permissionDecision': 'deny', 'permissionDecisionReason': reason(why)}}))
|
|
255
|
+
return 0
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
PATCH = '*** Begin Patch'
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
def decide(data: dict) -> str:
|
|
262
|
+
"""Why this tool call must not run (a key of REASONS), or '' to let it through."""
|
|
263
|
+
ti = data.get('tool_input')
|
|
264
|
+
if not isinstance(ti, dict):
|
|
265
|
+
return ''
|
|
266
|
+
cwd = data.get('cwd') or os.getcwd()
|
|
267
|
+
for s in _strings(ti):
|
|
268
|
+
if PATCH in s:
|
|
269
|
+
why = _patch(s, cwd)
|
|
270
|
+
if why:
|
|
271
|
+
return why
|
|
272
|
+
if isinstance(ti.get('file_path') or ti.get('notebook_path'), str):
|
|
273
|
+
return _edit(ti, cwd)
|
|
274
|
+
cmd = ti.get('command')
|
|
275
|
+
if isinstance(cmd, list):
|
|
276
|
+
cmd = ' '.join(shlex.quote(str(c)) for c in cmd)
|
|
277
|
+
return _shell(cmd) if isinstance(cmd, str) and PATCH not in cmd else ''
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
def _strings(v):
|
|
281
|
+
if isinstance(v, str):
|
|
282
|
+
yield v
|
|
283
|
+
elif isinstance(v, dict):
|
|
284
|
+
for x in v.values():
|
|
285
|
+
yield from _strings(x)
|
|
286
|
+
elif isinstance(v, list):
|
|
287
|
+
for x in v:
|
|
288
|
+
yield from _strings(x)
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
# ---------------------------------------------------------------- file edits
|
|
292
|
+
|
|
293
|
+
HOOKS_OFF = re.compile(r'(?im)^\s*(?:features\.)?hooks\s*=\s*false')
|
|
294
|
+
ALL_HOOKS_OFF = re.compile(r'(?i)disableallhooks\W{0,4}\s*:\s*true')
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
def _norm(p: str) -> str:
|
|
298
|
+
return os.path.normcase(os.path.realpath(os.path.expanduser(p)))
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
def _abs(p: str, cwd: str) -> str:
|
|
302
|
+
return _norm(os.path.join(cwd, os.path.expanduser(p)))
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
def _lines(text: str) -> set:
|
|
306
|
+
return {x.strip() for x in text.splitlines() if x.strip()}
|
|
307
|
+
|
|
308
|
+
|
|
309
|
+
def _ours(text: str) -> set:
|
|
310
|
+
return {x.strip() for x in text.splitlines() if 'open-pushscan' in x or 'open_pushscan' in x}
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
def _hook_lines(text: str) -> list:
|
|
314
|
+
return [x.strip().lower() for x in text.splitlines() if 'hookspath' in x.lower()]
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
def _is_gitconfig(p: str) -> bool:
|
|
318
|
+
p = p.replace('\\', '/')
|
|
319
|
+
return os.path.basename(p) == '.gitconfig' or p.endswith(('/.git/config', '/git/config', '/.git/config.worktree'))
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
def _change(path: str, before: str, after: str) -> str:
|
|
323
|
+
if before == after:
|
|
324
|
+
return ''
|
|
325
|
+
name = os.path.basename(path)
|
|
326
|
+
if name.endswith('settings.json') or name == 'settings.local.json': # Claude Code settings
|
|
327
|
+
if ALL_HOOKS_OFF.search(after) and not ALL_HOOKS_OFF.search(before):
|
|
328
|
+
return 'protected'
|
|
329
|
+
if name == 'config.toml' and HOOKS_OFF.search(after) and not HOOKS_OFF.search(before): # Codex settings
|
|
330
|
+
return 'protected'
|
|
331
|
+
home = _norm(config.config_dir())
|
|
332
|
+
if path == home or path.startswith(home + os.sep):
|
|
333
|
+
if os.path.relpath(path, home).lower() in ('fingerprints.txt', 'rules.txt'):
|
|
334
|
+
added = _lines(after) - _lines(before)
|
|
335
|
+
if _lines(before) - _lines(after) or any(x.startswith('-') for x in added):
|
|
336
|
+
return 'settings'
|
|
337
|
+
return '' # adding a name or a rule only makes the checks stricter
|
|
338
|
+
return 'settings'
|
|
339
|
+
if _is_gitconfig(path) and _hook_lines(before) != _hook_lines(after):
|
|
340
|
+
return 'hooks'
|
|
341
|
+
if path in {_norm(p) for p in files().values()} and _ours(before) - _ours(after):
|
|
342
|
+
return 'protected'
|
|
343
|
+
return ''
|
|
344
|
+
|
|
345
|
+
|
|
346
|
+
def _edit(ti: dict, cwd: str) -> str:
|
|
347
|
+
path = _abs(ti.get('file_path') or ti.get('notebook_path'), cwd)
|
|
348
|
+
before = _read(path)
|
|
349
|
+
if isinstance(ti.get('content'), str):
|
|
350
|
+
after = ti['content']
|
|
351
|
+
else:
|
|
352
|
+
after = before
|
|
353
|
+
for e in ti['edits'] if isinstance(ti.get('edits'), list) else [ti]:
|
|
354
|
+
old, new = e.get('old_string'), e.get('new_string')
|
|
355
|
+
if isinstance(old, str) and isinstance(new, str) and old:
|
|
356
|
+
after = after.replace(old, new) if e.get('replace_all') else after.replace(old, new, 1)
|
|
357
|
+
return _change(path, before, after)
|
|
358
|
+
|
|
359
|
+
|
|
360
|
+
FILE_LINE = re.compile(r'^\*\*\* (Add|Update|Delete) File: (.+)$')
|
|
361
|
+
|
|
362
|
+
|
|
363
|
+
def _patch(text: str, cwd: str) -> str:
|
|
364
|
+
"""Codex's apply_patch format: "*** Update File: path", then lines starting with + or -."""
|
|
365
|
+
parts, cur = [], None
|
|
366
|
+
for line in text[text.index(PATCH):].splitlines():
|
|
367
|
+
m = FILE_LINE.match(line)
|
|
368
|
+
if m:
|
|
369
|
+
cur = [m.group(2).strip(), m.group(1), [], []]
|
|
370
|
+
parts.append(cur)
|
|
371
|
+
elif cur and line.startswith('*** Move to: '):
|
|
372
|
+
parts.append([line[13:].strip(), 'Add', [], cur[3]])
|
|
373
|
+
cur[1] = 'Delete'
|
|
374
|
+
elif cur and line.startswith('+'):
|
|
375
|
+
cur[3].append(line[1:])
|
|
376
|
+
elif cur and line.startswith('-'):
|
|
377
|
+
cur[2].append(line[1:])
|
|
378
|
+
for name, kind, removed, added in parts:
|
|
379
|
+
path = _abs(name, cwd)
|
|
380
|
+
if kind == 'Delete':
|
|
381
|
+
before, after = _read(path), ''
|
|
382
|
+
elif kind == 'Add':
|
|
383
|
+
before, after = _read(path), '\n'.join(added)
|
|
384
|
+
else:
|
|
385
|
+
before, after = '\n'.join(removed), '\n'.join(added)
|
|
386
|
+
why = _change(path, before, after)
|
|
387
|
+
if why:
|
|
388
|
+
return why
|
|
389
|
+
return ''
|
|
390
|
+
|
|
391
|
+
|
|
392
|
+
# ---------------------------------------------------------------- shell commands
|
|
393
|
+
|
|
394
|
+
ASSIGN = re.compile(r'^[A-Za-z_][A-Za-z0-9_]*=')
|
|
395
|
+
PYTHON = re.compile(r'^(?:python[\d.]*w?|py|pypy[\d.]*)$')
|
|
396
|
+
WRAPPERS = {'sudo', 'doas', 'env', 'command', 'exec', 'nohup', 'time', 'nice', 'builtin', 'stdbuf', 'timeout', 'xargs'}
|
|
397
|
+
KEYWORDS = {'if', 'then', 'else', 'elif', 'do', 'while', 'until', '!', '{'}
|
|
398
|
+
SHELLS = {'bash', 'sh', 'zsh', 'dash', 'ksh', 'fish', 'pwsh', 'powershell', 'cmd'}
|
|
399
|
+
RISKY_ENV = {'HOME', 'USERPROFILE', 'XDG_CONFIG_HOME', 'APPDATA', 'GIT_CONFIG_GLOBAL', 'GIT_CONFIG_SYSTEM',
|
|
400
|
+
'GIT_CONFIG_PARAMETERS', 'GIT_CONFIG_COUNT', 'OPEN_PUSHSCAN_HOME'}
|
|
401
|
+
GIT_WRITES = {'commit', 'push', 'merge', 'pull', 'am', 'rebase', 'cherry-pick', 'revert'}
|
|
402
|
+
GIT_VALUE = {'-C', '-c', '--git-dir', '--work-tree', '--namespace', '--config-env', '--exec-path', '--super-prefix'}
|
|
403
|
+
# options whose next word is a value (a commit message may well say "--no-verify")
|
|
404
|
+
VALUE_OPTS = {
|
|
405
|
+
'commit': ('mFCct', {'--message', '--file', '--template', '--author', '--date', '--trailer', '--fixup', '--squash',
|
|
406
|
+
'--reuse-message', '--reedit-message', '--cleanup', '--pathspec-from-file'}),
|
|
407
|
+
'merge': ('mFsX', {'--message', '--file', '--strategy', '--strategy-option', '--into-name', '--cleanup'}),
|
|
408
|
+
'pull': ('sX', {'--strategy', '--strategy-option', '--upload-pack'}),
|
|
409
|
+
'push': ('o', {'--push-option', '--repo', '--receive-pack', '--exec'}),
|
|
410
|
+
}
|
|
411
|
+
CONFIG_WRITES = {'--unset', '--unset-all', 'unset', 'set', '--add', '--replace-all', '--remove-section', 'remove-section',
|
|
412
|
+
'--rename-section', 'rename-section'}
|
|
413
|
+
CONFIG_READS = {'--get', '--get-all', '--get-regexp', 'get', '-l', '--list', 'list', '--get-urlmatch'}
|
|
414
|
+
READ_ONLY = {'cat', 'ls', 'll', 'head', 'tail', 'less', 'more', 'grep', 'egrep', 'fgrep', 'rg', 'wc', 'stat', 'file', 'tree',
|
|
415
|
+
'du', 'diff', 'cmp', 'jq', 'type', 'dir', 'cd', 'pwd', 'echo', 'printf', 'test', '[', '[[', 'realpath',
|
|
416
|
+
'readlink', 'basename', 'dirname', 'sort', 'uniq', 'cut', 'awk', 'tr', 'nl', 'column', 'md5sum', 'sha256sum',
|
|
417
|
+
'find', 'get-content', 'gc', 'get-childitem', 'gci', 'select-string', 'sls', 'write-output', 'true', 'false'}
|
|
418
|
+
DESTRUCTIVE = {'rm', 'rmdir', 'mv', 'cp', 'tee', 'truncate', 'dd', 'shred', 'unlink', 'ln', 'install', 'rsync', 'chmod',
|
|
419
|
+
'chown', 'del', 'erase', 'rd', 'remove-item', 'ri', 'move-item', 'mi', 'copy-item', 'cpi', 'set-content',
|
|
420
|
+
'sc', 'add-content', 'ac', 'out-file', 'new-item', 'ni'}
|
|
421
|
+
REDIRECT = re.compile(r'(\d*)(>>?)\s*([^\s;|&()]+)')
|
|
422
|
+
|
|
423
|
+
|
|
424
|
+
def _base(word: str) -> str:
|
|
425
|
+
b = os.path.basename(word.replace('\\', '/')).lower().strip('"\'()')
|
|
426
|
+
return b[:-4] if b.endswith('.exe') else b
|
|
427
|
+
|
|
428
|
+
|
|
429
|
+
def _segments(text: str, depth: int = 0) -> list:
|
|
430
|
+
"""Split a shell command into simple commands (lists of words); `bash -c '...'` and the like are split too."""
|
|
431
|
+
try:
|
|
432
|
+
lex = shlex.shlex(text.replace('\n', ' ; '), posix=True, punctuation_chars=True)
|
|
433
|
+
lex.whitespace_split = True
|
|
434
|
+
words = list(lex)
|
|
435
|
+
except ValueError:
|
|
436
|
+
words = text.split()
|
|
437
|
+
segs, cur = [], []
|
|
438
|
+
for w in words:
|
|
439
|
+
if w and all(c in ';&|()' for c in w):
|
|
440
|
+
if cur:
|
|
441
|
+
segs.append(cur)
|
|
442
|
+
cur = []
|
|
443
|
+
else:
|
|
444
|
+
cur.append(w)
|
|
445
|
+
if cur:
|
|
446
|
+
segs.append(cur)
|
|
447
|
+
if depth < 3:
|
|
448
|
+
for words in list(segs):
|
|
449
|
+
i, _env = _program(words)
|
|
450
|
+
if i is None:
|
|
451
|
+
continue
|
|
452
|
+
b, rest = _base(words[i]), words[i + 1:]
|
|
453
|
+
inner = ''
|
|
454
|
+
if b in SHELLS:
|
|
455
|
+
for j, a in enumerate(rest[:-1]):
|
|
456
|
+
if a.lower() in ('-c', '-lc', '-ic', '-command', '/c') or re.fullmatch(r'-[a-z]*c', a):
|
|
457
|
+
inner = rest[j + 1]
|
|
458
|
+
break
|
|
459
|
+
elif b == 'eval':
|
|
460
|
+
inner = ' '.join(rest)
|
|
461
|
+
if inner:
|
|
462
|
+
segs += _segments(inner, depth + 1)
|
|
463
|
+
return segs
|
|
464
|
+
|
|
465
|
+
|
|
466
|
+
def _program(words: list):
|
|
467
|
+
"""Index of the program word (after NAME=value and wrappers such as sudo or env) and the variables set on the way."""
|
|
468
|
+
i, env = 0, set()
|
|
469
|
+
while i < len(words):
|
|
470
|
+
w = words[i]
|
|
471
|
+
if ASSIGN.match(w):
|
|
472
|
+
env.add(w.split('=', 1)[0].upper())
|
|
473
|
+
i += 1
|
|
474
|
+
continue
|
|
475
|
+
b = _base(w)
|
|
476
|
+
if b in KEYWORDS:
|
|
477
|
+
i += 1
|
|
478
|
+
continue
|
|
479
|
+
if b not in WRAPPERS:
|
|
480
|
+
return i, env
|
|
481
|
+
i += 1
|
|
482
|
+
while i < len(words) and words[i].startswith('-'):
|
|
483
|
+
if words[i] in ('-u', '--unset') and i + 1 < len(words):
|
|
484
|
+
env.add(words[i + 1].upper())
|
|
485
|
+
i += 1
|
|
486
|
+
i += 1
|
|
487
|
+
if b == 'timeout' and i < len(words) and words[i][:1].isdigit():
|
|
488
|
+
i += 1
|
|
489
|
+
return None, env
|
|
490
|
+
|
|
491
|
+
|
|
492
|
+
def _risky(env: set) -> bool:
|
|
493
|
+
return any(n in RISKY_ENV or n.startswith(('GIT_CONFIG_KEY_', 'GIT_CONFIG_VALUE_')) for n in env)
|
|
494
|
+
|
|
495
|
+
|
|
496
|
+
def _skips(sub: str, args: list) -> bool:
|
|
497
|
+
shorts, longs = VALUE_OPTS.get(sub, ('', set()))
|
|
498
|
+
i = 0
|
|
499
|
+
while i < len(args):
|
|
500
|
+
a = args[i]
|
|
501
|
+
i += 1
|
|
502
|
+
if a == '--':
|
|
503
|
+
break
|
|
504
|
+
if a.startswith('--'):
|
|
505
|
+
name = a.split('=', 1)[0]
|
|
506
|
+
if len(name) >= 9 and '--no-verify'.startswith(name):
|
|
507
|
+
return True
|
|
508
|
+
if name in longs and '=' not in a:
|
|
509
|
+
i += 1
|
|
510
|
+
elif a.startswith('-') and len(a) > 1:
|
|
511
|
+
for j, ch in enumerate(a[1:], 1):
|
|
512
|
+
if ch == 'n' and sub == 'commit':
|
|
513
|
+
return True
|
|
514
|
+
if ch in shorts:
|
|
515
|
+
if j == len(a) - 1:
|
|
516
|
+
i += 1
|
|
517
|
+
break
|
|
518
|
+
return False
|
|
519
|
+
|
|
520
|
+
|
|
521
|
+
def _git_config(args: list) -> bool:
|
|
522
|
+
low = [a.lower() for a in args]
|
|
523
|
+
if 'core.hookspath' not in low:
|
|
524
|
+
return 'core' in low and any(a in ('--remove-section', 'remove-section', '--rename-section', 'rename-section') for a in low)
|
|
525
|
+
if any(a in CONFIG_WRITES for a in low):
|
|
526
|
+
return True
|
|
527
|
+
if any(a in CONFIG_READS for a in low):
|
|
528
|
+
return False
|
|
529
|
+
return low.index('core.hookspath') < len(low) - 1 # a value follows the name
|
|
530
|
+
|
|
531
|
+
|
|
532
|
+
def _git(rest: list, env: set) -> str:
|
|
533
|
+
i, opts = 0, []
|
|
534
|
+
while i < len(rest) and rest[i].startswith('-'):
|
|
535
|
+
if rest[i] in GIT_VALUE and i + 1 < len(rest):
|
|
536
|
+
opts.append(rest[i + 1])
|
|
537
|
+
i += 2
|
|
538
|
+
else:
|
|
539
|
+
opts.append(rest[i])
|
|
540
|
+
i += 1
|
|
541
|
+
if any('core.hookspath' in o.lower() for o in opts):
|
|
542
|
+
return 'hooks'
|
|
543
|
+
if i >= len(rest):
|
|
544
|
+
return ''
|
|
545
|
+
sub, args = rest[i], rest[i + 1:]
|
|
546
|
+
if sub == 'config' and _git_config(args):
|
|
547
|
+
return 'hooks'
|
|
548
|
+
if sub in GIT_WRITES:
|
|
549
|
+
if _risky(env):
|
|
550
|
+
return 'env'
|
|
551
|
+
if _skips(sub, args):
|
|
552
|
+
return 'skip'
|
|
553
|
+
return ''
|
|
554
|
+
|
|
555
|
+
|
|
556
|
+
def _ops(rest: list) -> str:
|
|
557
|
+
sub = next((a for a in rest if not a.startswith('-')), '')
|
|
558
|
+
return 'allow' if sub in ('allow', 'uninstall') else ''
|
|
559
|
+
|
|
560
|
+
|
|
561
|
+
def _python(rest: list) -> str:
|
|
562
|
+
for j, a in enumerate(rest):
|
|
563
|
+
if a == '-m' and j + 1 < len(rest):
|
|
564
|
+
return _ops(rest[j + 2:]) if rest[j + 1] in ('open_pushscan', 'open_pushscan.cli') else ''
|
|
565
|
+
if a == '-c' and j + 1 < len(rest):
|
|
566
|
+
code = rest[j + 1]
|
|
567
|
+
if 'open_pushscan' in code and re.search(r'\b(add_allowed|set_value|write_fingerprints|uninstall)\b', code):
|
|
568
|
+
return 'settings'
|
|
569
|
+
return ''
|
|
570
|
+
if not a.startswith('-'):
|
|
571
|
+
return '' # running a script file
|
|
572
|
+
return ''
|
|
573
|
+
|
|
574
|
+
|
|
575
|
+
def _first(chunk: str) -> tuple:
|
|
576
|
+
"""The program of a simple command (after NAME=value, sudo, xargs and the like) and its arguments."""
|
|
577
|
+
words = chunk.split()
|
|
578
|
+
k = 0
|
|
579
|
+
while k < len(words) and (ASSIGN.match(words[k]) or _base(words[k]) in WRAPPERS | KEYWORDS):
|
|
580
|
+
k += 1
|
|
581
|
+
return (_base(words[k]), words[k + 1:]) if k < len(words) else ('', [])
|
|
582
|
+
|
|
583
|
+
|
|
584
|
+
def _writes(raw: str, rx, append_ok: bool = False) -> bool:
|
|
585
|
+
"""Could a command that mentions a protected place (rx) change something there? Looking is fine:
|
|
586
|
+
cat, ls, grep, diff, python -m json.tool and the like, with output going elsewhere."""
|
|
587
|
+
# | ; & < > inside quotes are just text (grep "a\|b", echo "x > y")
|
|
588
|
+
text = re.sub(r'"[^"]*"|\'[^\']*\'', lambda m: re.sub(r'[|;&<>]', ' ', m.group(0)), raw)
|
|
589
|
+
text = re.sub(r'\d*>>?&\d', ' ', text)
|
|
590
|
+
if any(_first(c)[0] in DESTRUCTIVE for c in re.split(r'&&|\|\||[;\n&|{}]|\$\(|<\(|`', text)):
|
|
591
|
+
return True
|
|
592
|
+
if re.search(r'\b(?:sed|perl)\b[^|;&]*\s-i|\s-delete\b|\s-exec(?:dir)?\b', text):
|
|
593
|
+
return True
|
|
594
|
+
inside = False # after `cd` into the protected place, relative names point there too
|
|
595
|
+
for stmt in re.split(r'&&|\|\||[;\n&]', text):
|
|
596
|
+
here = bool(rx.search(stmt))
|
|
597
|
+
if not (here or inside):
|
|
598
|
+
continue
|
|
599
|
+
for fd, op, target in REDIRECT.findall(stmt):
|
|
600
|
+
if fd == '2' or target.strip('"\'') in ('/dev/null', 'nul', '$null'):
|
|
601
|
+
continue
|
|
602
|
+
if not (inside or rx.search(target)):
|
|
603
|
+
continue # reading the place, writing somewhere else
|
|
604
|
+
if append_ok and op == '>>' and re.search(r'(?:fingerprints|rules)\.txt["\']?$', target):
|
|
605
|
+
continue
|
|
606
|
+
return True
|
|
607
|
+
for chunk in re.split(r'[|{}]|\$\(|<\(|`', stmt):
|
|
608
|
+
b, args = _first(chunk)
|
|
609
|
+
if b in ('cd', 'pushd', 'set-location', 'sl') and here:
|
|
610
|
+
inside = True
|
|
611
|
+
elif b and b not in READ_ONLY and not (PYTHON.match(b) and args[:2] == ['-m', 'json.tool']):
|
|
612
|
+
return True
|
|
613
|
+
return False
|
|
614
|
+
|
|
615
|
+
|
|
616
|
+
def _places() -> list:
|
|
617
|
+
"""(reason, pattern) for places a shell command must not write to. Matched against the lower-cased command
|
|
618
|
+
with backslashes turned into slashes."""
|
|
619
|
+
def lit(p):
|
|
620
|
+
return re.escape(p.replace('\\', '/').lower().rstrip('/'))
|
|
621
|
+
home = '(?:' + '|'.join([lit(os.path.expanduser('~')), '~', r'\$home', r'\$\{home\}', '%userprofile%', r'\$env:userprofile']) + ')'
|
|
622
|
+
end = r'(?![\w-])'
|
|
623
|
+
settings = [lit(config.config_dir()) + end, r'(?:\.config|appdata/roaming|appdata%?|xdg_config_home\}?)/+open-pushscan' + end,
|
|
624
|
+
r'\$\{?open_pushscan_home\b',
|
|
625
|
+
r'open-pushscan/+(?:allowed\.json|allow\.txt|skip\.txt|fingerprints\.txt|rules\.txt|config\.ini|hooks|team|state)' + end]
|
|
626
|
+
claude = [home + r'/+\.claude', lit(claude_dir()), r'\$\{?claude_config_dir\}?']
|
|
627
|
+
codex = [home + r'/+\.codex', lit(codex_dir()), r'\$\{?codex_home\}?']
|
|
628
|
+
agent = (r'(?:' + '|'.join(claude) + r')/+settings\.json|(?:' + '|'.join(codex)
|
|
629
|
+
+ r')/+(?:hooks\.json|rules/+open-pushscan\.rules)')
|
|
630
|
+
gitconfig = home + r'/+(?:\.gitconfig|\.config/git/config)' + end
|
|
631
|
+
return [('settings', re.compile('|'.join(settings))), ('protected', re.compile(agent)), ('hooks', re.compile(gitconfig))]
|
|
632
|
+
|
|
633
|
+
|
|
634
|
+
def _shell(cmd: str) -> str:
|
|
635
|
+
raw = cmd.lower().replace('\\', '/')
|
|
636
|
+
if ALL_HOOKS_OFF.search(raw) or re.search(r'features\.hooks\s*=\s*false|--disable[= ]+hooks\b', raw):
|
|
637
|
+
return 'protected' # the setting itself, not a mere mention (grep, docs)
|
|
638
|
+
for why, rx in _places():
|
|
639
|
+
if rx.search(raw) and _writes(raw, rx, append_ok=why == 'settings'):
|
|
640
|
+
return why
|
|
641
|
+
if 'hookspath' in raw and _writes(raw, re.compile(r'\.git/config')):
|
|
642
|
+
return 'hooks'
|
|
643
|
+
segs = _segments(cmd)
|
|
644
|
+
exported = {m.upper() for m in re.findall(r'\$env:([a-z_][a-z0-9_]*)\s*=', cmd.lower())}
|
|
645
|
+
for words in segs:
|
|
646
|
+
i, env = _program(words)
|
|
647
|
+
if i is None:
|
|
648
|
+
exported |= env # NAME=value on its own line applies to the commands after it
|
|
649
|
+
elif _base(words[i]) in ('export', 'declare', 'typeset', 'set', 'setx', 'setenv'):
|
|
650
|
+
exported |= {w.split('=', 1)[0].upper() for w in words[i + 1:] if not w.startswith('-')}
|
|
651
|
+
for words in segs:
|
|
652
|
+
i, env = _program(words)
|
|
653
|
+
if i is None:
|
|
654
|
+
continue
|
|
655
|
+
b, rest = _base(words[i]), words[i + 1:]
|
|
656
|
+
if b == 'git':
|
|
657
|
+
why = _git(rest, env | exported)
|
|
658
|
+
elif b == 'open-pushscan':
|
|
659
|
+
why = _ops(rest)
|
|
660
|
+
elif PYTHON.match(b):
|
|
661
|
+
why = _python(rest)
|
|
662
|
+
else:
|
|
663
|
+
why = ''
|
|
664
|
+
if why:
|
|
665
|
+
return why
|
|
666
|
+
return ''
|