scrubscript 0.2.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.
- scrubscript-0.2.0.dist-info/METADATA +149 -0
- scrubscript-0.2.0.dist-info/RECORD +7 -0
- scrubscript-0.2.0.dist-info/WHEEL +5 -0
- scrubscript-0.2.0.dist-info/entry_points.txt +2 -0
- scrubscript-0.2.0.dist-info/licenses/LICENSE +21 -0
- scrubscript-0.2.0.dist-info/top_level.txt +1 -0
- scrubscript.py +2477 -0
scrubscript.py
ADDED
|
@@ -0,0 +1,2477 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Replace secrets in Claude Code transcripts (or any text files) with [redacted].
|
|
3
|
+
|
|
4
|
+
scrubscript [--apply] [--ended] [--rules FILE] <session-id | path>...
|
|
5
|
+
scrubscript [--apply] [--rules FILE] --all
|
|
6
|
+
scrubscript --setup
|
|
7
|
+
scrubscript --restore [--identity FILE] <path>...
|
|
8
|
+
scrubscript --filter [--live TRANSCRIPT [--json]] < text
|
|
9
|
+
scrubscript --status | --doctor
|
|
10
|
+
scrubscript --session-end | --session-start | --sweep
|
|
11
|
+
scrubscript --marker-sent TOOL --live TRANSCRIPT <marker id>...
|
|
12
|
+
|
|
13
|
+
A session id covers every file Claude Code keeps for that session under
|
|
14
|
+
~/.claude/projects: the <id>.jsonl transcript and the <id>/ folder (tool-results,
|
|
15
|
+
subagents). It also covers what the session left beside that folder: its lines in
|
|
16
|
+
history.jsonl, the prompt history, with the paste-cache files those lines name, its
|
|
17
|
+
debug log, the telemetry events it could not send, and its file-history folder, the
|
|
18
|
+
copies of the files it edited. A path is scanned as given, file or folder. --all runs every session,
|
|
19
|
+
each in its own memory-capped scope, so one huge transcript cannot exhaust the
|
|
20
|
+
machine. It ends with one count: the distinct secrets found, how many sessions hold
|
|
21
|
+
one, how many of each gitleaks rule, and how many sessions were skipped or failed. A finished --all --apply records when it ran, and the next --all skips
|
|
22
|
+
every session untouched since then; --full scans them all regardless. Every --all
|
|
23
|
+
also reads the whole prompt history and paste cache, for a prompt whose transcript
|
|
24
|
+
is gone and a paste no prompt names, and each debug log, telemetry file and
|
|
25
|
+
file-history folder whose session has no transcript, once and then again when it is
|
|
26
|
+
written. --status
|
|
27
|
+
says when that was and how many sessions changed since, exiting 3 when there is no
|
|
28
|
+
record under the current rules, so the next --all would scan everything. Without
|
|
29
|
+
--apply it only reports what it would redact; secret values are never printed.
|
|
30
|
+
|
|
31
|
+
Detection is gitleaks with its default rules, plus your own: gitleaks [[rules]] and
|
|
32
|
+
[[allowlists]] tables in ~/.config/scrubscript/rules.toml, or in the file --rules or
|
|
33
|
+
SCRUBSCRIPT_RULES names. Changing the rules voids the record of the last full scrub.
|
|
34
|
+
Each secret gitleaks reports is replaced everywhere it occurs in that file. Files are streamed
|
|
35
|
+
line by line, so memory peaks at the longest line. In JSON and JSONL every edited
|
|
36
|
+
line must still parse: a match that would split an escape or that runs across
|
|
37
|
+
strings is cut per string value instead, and a secret gitleaks found only inside
|
|
38
|
+
base64 is redacted in the decoded blob, which is then encoded again. A match that
|
|
39
|
+
runs over line breaks, such as a private key printed the way it is written, is
|
|
40
|
+
replaced as one piece in plain text and cut record by record in JSONL. --apply rescans
|
|
41
|
+
what it rewrote, since removing one secret can expose another gitleaks did not
|
|
42
|
+
report beside it. A file it still cannot redact cleanly is left untouched.
|
|
43
|
+
|
|
44
|
+
Nothing is rewritten until the user sets up backups, at a terminal: --setup makes
|
|
45
|
+
an age key pair, keeps its public half beside the rules file and shows the secret
|
|
46
|
+
half once, as the recovery code. No scrub runs without a backup. The recipients file is an ordinary age recipients file: a public key of your own, age or SSH,
|
|
47
|
+
put in it by hand takes the place of the one --setup made. Each
|
|
48
|
+
redacted stretch of a line is kept encrypted to that key, in the state folder, before
|
|
49
|
+
the file is rewritten, and a file whose backup cannot be made is not redacted. Nothing
|
|
50
|
+
on this machine can read a backup. --restore puts each stretch back where its line is
|
|
51
|
+
now, given the recovery code at the terminal or --identity FILE. A backup is kept as
|
|
52
|
+
long as its file exists, and the sweep removes it once the file is gone.
|
|
53
|
+
|
|
54
|
+
A session still in use is skipped by --apply, and --all pins it for the next pass; a
|
|
55
|
+
dry run reads it, since it rewrites nothing. Claude
|
|
56
|
+
Code opens a transcript only to append and closes it again, so replacing the file
|
|
57
|
+
loses nothing as long as no write lands between reading it and replacing it. A
|
|
58
|
+
session counts as in use while any process names it (an open file under its id,
|
|
59
|
+
its command line, or ~/.claude/sessions) or it was written in the quiet period,
|
|
60
|
+
and a file that changed between scan and write is skipped. No one signal names
|
|
61
|
+
every live session; the quiet period covers the ones none of them name. --ended
|
|
62
|
+
drops the quiet period, for a caller that knows the session just ended: the other
|
|
63
|
+
signals still apply.
|
|
64
|
+
|
|
65
|
+
The prompt history is one file for every session, and live sessions append to it.
|
|
66
|
+
Claude Code appends under a lock, a history.jsonl.lock folder. The redacted copy is
|
|
67
|
+
made first; the lock is then held only to put the copy in place, and only if no
|
|
68
|
+
prompt was added meanwhile. A history that changed, or whose lock Claude Code holds,
|
|
69
|
+
is skipped, and the next sweep reaches it.
|
|
70
|
+
|
|
71
|
+
--session-end is that caller: registered as a Claude Code SessionEnd hook, it reads
|
|
72
|
+
the hook's payload on stdin and starts `--apply --ended` for that session a few
|
|
73
|
+
seconds later (SCRUBSCRIPT_DELAY_SECONDS, 5), as a memory-capped systemd user unit
|
|
74
|
+
where there is a user manager and as a detached process elsewhere. It always exits 0, and logs
|
|
75
|
+
what it did, with the scrub's own output, to scrubscript/hooks.log under
|
|
76
|
+
$XDG_STATE_HOME (~/.local/state).
|
|
77
|
+
|
|
78
|
+
A session that is killed runs no SessionEnd hook. --session-start, registered as a
|
|
79
|
+
SessionStart hook, covers those: it notes the session as started, and at most every
|
|
80
|
+
SCRUBSCRIPT_SWEEP_MINUTES (10) starts --sweep, apart from the hook in the same way.
|
|
81
|
+
A sweep scrubs the sessions written since the last sweep that are no longer in use.
|
|
82
|
+
The hook records which Claude Code process runs the session, so a sweep knows a
|
|
83
|
+
session is over once that process is gone, and scrubs it without waiting out the
|
|
84
|
+
quiet period. A session counts as written at the moment it starts, so one resumed
|
|
85
|
+
while a sweep runs is left alone. Sessions may start together: one hook among them starts the
|
|
86
|
+
sweep, and one sweep runs at a time.
|
|
87
|
+
"""
|
|
88
|
+
|
|
89
|
+
import argparse
|
|
90
|
+
import base64
|
|
91
|
+
import binascii
|
|
92
|
+
import fcntl
|
|
93
|
+
import functools
|
|
94
|
+
import getpass
|
|
95
|
+
import hashlib
|
|
96
|
+
import itertools
|
|
97
|
+
import json
|
|
98
|
+
import os
|
|
99
|
+
import re
|
|
100
|
+
import shlex
|
|
101
|
+
import shutil
|
|
102
|
+
import subprocess
|
|
103
|
+
import sys
|
|
104
|
+
import tempfile
|
|
105
|
+
import time
|
|
106
|
+
from collections import Counter, defaultdict
|
|
107
|
+
from pathlib import Path
|
|
108
|
+
|
|
109
|
+
__version__ = "0.2.0"
|
|
110
|
+
|
|
111
|
+
# Claude Code keeps its files here, or in the folder CLAUDE_CONFIG_DIR names.
|
|
112
|
+
CONFIG = Path(os.environ.get("CLAUDE_CONFIG_DIR") or Path.home() / ".claude")
|
|
113
|
+
PROJECTS = Path(os.environ.get("SCRUBSCRIPT_PROJECTS", CONFIG / "projects"))
|
|
114
|
+
REGISTRY = Path(os.environ.get("SCRUBSCRIPT_REGISTRY", CONFIG / "sessions"))
|
|
115
|
+
# What was typed and pasted, kept apart from the transcripts: a line per prompt, and
|
|
116
|
+
# a file per large paste, named for the hash a prompt's line gives.
|
|
117
|
+
HISTORY = PROJECTS.parent / "history.jsonl"
|
|
118
|
+
PASTES = PROJECTS.parent / "paste-cache"
|
|
119
|
+
# Kept beside the projects folder too, each under the session's id. A rewind restores
|
|
120
|
+
# from file-history, the copies of the files the session edited.
|
|
121
|
+
DEBUG = PROJECTS.parent / "debug"
|
|
122
|
+
TELEMETRY = PROJECTS.parent / "telemetry"
|
|
123
|
+
FILE_HISTORY = PROJECTS.parent / "file-history"
|
|
124
|
+
# Claude Code holds <file>.lock, a folder, while it appends to its prompt history or
|
|
125
|
+
# rewrites it, and takes a lock this old as abandoned.
|
|
126
|
+
LOCK_STALE_SECONDS = 10
|
|
127
|
+
PROC = Path(os.environ.get("SCRUBSCRIPT_PROC", "/proc"))
|
|
128
|
+
QUIET_SECONDS = 60 * int(os.environ.get("SCRUBSCRIPT_QUIET_MINUTES", "60"))
|
|
129
|
+
# Per-session cap under --all: a breach kills that one run, not the desktop.
|
|
130
|
+
MEMORY_MAX = os.environ.get("SCRUBSCRIPT_MEMORY_MAX", "2G")
|
|
131
|
+
STATE_HOME = Path(os.environ.get("XDG_STATE_HOME") or Path.home() / ".local/state")
|
|
132
|
+
STATE = Path(os.environ.get("SCRUBSCRIPT_STATE", STATE_HOME / "scrubscript/last-full-scrub.json"))
|
|
133
|
+
# What the two hooks did, and the output of the scrubs and sweeps they started.
|
|
134
|
+
HOOK_LOG = Path(os.environ.get("SCRUBSCRIPT_HOOK_LOG", STATE.parent / "hooks.log"))
|
|
135
|
+
# How long after a session ends its scrub starts: long enough for Claude Code to
|
|
136
|
+
# finish writing and exit, short enough that the secret is not left lying.
|
|
137
|
+
DELAY_SECONDS = round(float(os.environ.get("SCRUBSCRIPT_DELAY_SECONDS", "5")))
|
|
138
|
+
# One file per session a SessionStart hook saw start, named for its id and holding the
|
|
139
|
+
# pid of the Claude Code process that runs it, when the hook could tell.
|
|
140
|
+
STARTED = STATE.parent / "started"
|
|
141
|
+
# The least time between two sweeps that --session-start starts.
|
|
142
|
+
SWEEP_SECONDS = 60 * float(os.environ.get("SCRUBSCRIPT_SWEEP_MINUTES", "10"))
|
|
143
|
+
# How far back the first sweep of a projects folder looks. Older sessions are --all's.
|
|
144
|
+
FIRST_SWEEP_SECONDS = 24 * 3600
|
|
145
|
+
# Under --all, the file each per-session run lists the secrets it redacted, or would, in:
|
|
146
|
+
# one JSON line per secret with its rule, its SHA-256 and the file it is in, never the
|
|
147
|
+
# value. --all reads them for its closing count, which no single run can make, since a
|
|
148
|
+
# secret repeats across a session's files and across sessions.
|
|
149
|
+
TALLY = os.environ.get("SCRUBSCRIPT_TALLY")
|
|
150
|
+
# Sessions whose --apply left a secret behind or skipped them, so the next --all
|
|
151
|
+
# rescans them however old their files are.
|
|
152
|
+
UNFINISHED = ("FAILED", "SKIP", "found only after decoding")
|
|
153
|
+
REDACTED = b"[redacted]"
|
|
154
|
+
# What live redaction leaves: a random id per replaced span, which is what a restore finds.
|
|
155
|
+
MARKER_ID_HEX = 12
|
|
156
|
+
MARKER = re.compile(rb"\[redacted:([0-9a-f]{%d})\]" % MARKER_ID_HEX)
|
|
157
|
+
MARKER_TEXT = re.compile(r"\[redacted:[0-9a-f]{%d}\]" % MARKER_ID_HEX)
|
|
158
|
+
# While a live filter runs, the bytes each of its markers replaced, by id; otherwise None,
|
|
159
|
+
# and a redaction writes the plain REDACTED.
|
|
160
|
+
MARKS = None
|
|
161
|
+
# Shorter values are left alone: replacing every occurrence of a short string
|
|
162
|
+
# would hit ordinary text.
|
|
163
|
+
MIN_SECRET_LEN = 8
|
|
164
|
+
MAX_PASSES = 3
|
|
165
|
+
SESSION_ID = re.compile(r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")
|
|
166
|
+
|
|
167
|
+
GITLEAKS_CONFIG = r"""
|
|
168
|
+
title = "scrubscript"
|
|
169
|
+
[extend]
|
|
170
|
+
useDefault = true
|
|
171
|
+
|
|
172
|
+
# Transcripts list the API beta flags of each request, and generic-api-key reads a
|
|
173
|
+
# flag after "oauth-2025-04-20" as a key: most of its hits in transcripts are these.
|
|
174
|
+
[[allowlists]]
|
|
175
|
+
description = "Anthropic API beta-flag names, such as interleaved-thinking-2025-05-14"
|
|
176
|
+
targetRules = ["generic-api-key"]
|
|
177
|
+
regexTarget = "secret"
|
|
178
|
+
regexes = ['''^[a-z]+(?:-[a-z0-9]+)*-\d{4}-?\d{2}-?\d{2}$''']
|
|
179
|
+
|
|
180
|
+
# Airtable names its bases, tables, fields, records, views and the rest with a
|
|
181
|
+
# three-letter prefix and 14 letters and digits, which both rules read as a key after
|
|
182
|
+
# "key:" or near "airtable". Its credentials take other prefixes, "pat" and the legacy
|
|
183
|
+
# "key", so those are still caught.
|
|
184
|
+
[[allowlists]]
|
|
185
|
+
description = "Airtable object ids, such as a field id"
|
|
186
|
+
targetRules = ["generic-api-key", "airtable-api-key"]
|
|
187
|
+
regexTarget = "secret"
|
|
188
|
+
regexes = ['''^(?:app|tbl|fld|rec|viw|sel|usr|wsp)[A-Za-z0-9]{14}$''']
|
|
189
|
+
"""
|
|
190
|
+
DEFAULT_RULES = Path(os.environ.get("XDG_CONFIG_HOME", Path.home() / ".config")) / "scrubscript/rules.toml"
|
|
191
|
+
# The public half of the key the backups are encrypted to, written by --setup beside
|
|
192
|
+
# the rules file. Without it backups are not set up, and nothing is rewritten.
|
|
193
|
+
RECIPIENTS = DEFAULT_RULES.parent / "backup-recipients.txt"
|
|
194
|
+
# The mark the removed --no-backups option left. It turns nothing off any more: an
|
|
195
|
+
# install that has it is told that redacting with no backup is gone, and --setup
|
|
196
|
+
# removes it.
|
|
197
|
+
OPTED_OUT = DEFAULT_RULES.parent / "no-backups"
|
|
198
|
+
# The values the user kept at a restore, which no scrub redacts again: one JSON line
|
|
199
|
+
# each, with the rule, the first four characters and the SHA-256, never the value.
|
|
200
|
+
KEPT = DEFAULT_RULES.parent / "kept.jsonl"
|
|
201
|
+
# When a hook first found gitleaks missing or backups not set up: the catch-up sweep
|
|
202
|
+
# looks back from here.
|
|
203
|
+
WAITING = STATE.parent / "waiting-since"
|
|
204
|
+
# Exit status of a scrub refused because no backup can be made.
|
|
205
|
+
NOT_REDACTING = 4
|
|
206
|
+
# The files a restore put back, for the next sweep to redact what was not kept.
|
|
207
|
+
RESTORED = STATE.parent / "restored"
|
|
208
|
+
# The files a restore is working on, each holding the restore's pid: no scrub touches
|
|
209
|
+
# one until the keep choice is saved or given up.
|
|
210
|
+
RESTORING = STATE.parent / "restoring"
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def gitleaks_config():
|
|
214
|
+
"""The built-in config followed by the user's rules file, when there is one."""
|
|
215
|
+
named = os.environ.get("SCRUBSCRIPT_RULES")
|
|
216
|
+
path = Path(named) if named else DEFAULT_RULES
|
|
217
|
+
if not path.is_file():
|
|
218
|
+
if named:
|
|
219
|
+
sys.exit(f"scrubscript: rules file {path}: no such file")
|
|
220
|
+
return GITLEAKS_CONFIG
|
|
221
|
+
return GITLEAKS_CONFIG + "\n" + path.read_text()
|
|
222
|
+
|
|
223
|
+
|
|
224
|
+
def process_mentions():
|
|
225
|
+
"""(command line, open file paths) of the running processes.
|
|
226
|
+
|
|
227
|
+
Linux reads /proc. Where there is none (macOS), ps gives the command lines and
|
|
228
|
+
lsof the open files, as one entry with no command line; without lsof only the
|
|
229
|
+
command lines are seen, and the quiet period covers what that misses.
|
|
230
|
+
"""
|
|
231
|
+
if (PROC / "self").exists():
|
|
232
|
+
for proc in PROC.glob("[0-9]*"):
|
|
233
|
+
try:
|
|
234
|
+
cmdline = (proc / "cmdline").read_bytes().decode(errors="replace")
|
|
235
|
+
except OSError:
|
|
236
|
+
continue
|
|
237
|
+
files = []
|
|
238
|
+
try:
|
|
239
|
+
for fd in (proc / "fd").iterdir():
|
|
240
|
+
files.append(os.readlink(fd))
|
|
241
|
+
except OSError:
|
|
242
|
+
pass
|
|
243
|
+
yield cmdline, files
|
|
244
|
+
return
|
|
245
|
+
ps = subprocess.run(["ps", "-A", "-ww", "-o", "args="],
|
|
246
|
+
capture_output=True, text=True, errors="replace")
|
|
247
|
+
for line in ps.stdout.splitlines():
|
|
248
|
+
yield line, []
|
|
249
|
+
if shutil.which("lsof"):
|
|
250
|
+
try:
|
|
251
|
+
lsof = subprocess.run(["lsof", "-nP", "-Fn"], capture_output=True, text=True,
|
|
252
|
+
errors="replace", timeout=120)
|
|
253
|
+
except subprocess.TimeoutExpired:
|
|
254
|
+
return
|
|
255
|
+
yield "", [line[1:] for line in lsof.stdout.splitlines() if line.startswith("n")]
|
|
256
|
+
|
|
257
|
+
|
|
258
|
+
def live_sessions():
|
|
259
|
+
"""Session ids some process names: in an open file, its command line, or the registry."""
|
|
260
|
+
ids = set()
|
|
261
|
+
for cmdline, files in process_mentions():
|
|
262
|
+
# A scrub run names the sessions it scrubs; it is not using them.
|
|
263
|
+
if "scrubscript" not in cmdline:
|
|
264
|
+
ids.update(SESSION_ID.findall(cmdline))
|
|
265
|
+
for name in files:
|
|
266
|
+
ids.update(SESSION_ID.findall(name))
|
|
267
|
+
for entry in REGISTRY.glob("*.json"):
|
|
268
|
+
try:
|
|
269
|
+
record = json.loads(entry.read_text())
|
|
270
|
+
os.kill(int(record["pid"]), 0)
|
|
271
|
+
except (OSError, ValueError, KeyError, TypeError):
|
|
272
|
+
continue
|
|
273
|
+
ids.add(record.get("sessionId", ""))
|
|
274
|
+
return ids
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
def sessions_of(path):
|
|
278
|
+
"""The session ids a path belongs to.
|
|
279
|
+
|
|
280
|
+
Claude Code names a project's folder after its working directory, which can hold
|
|
281
|
+
another session's id, as a scratch folder does, so what lies above a file in the
|
|
282
|
+
config folder says nothing about whose it is.
|
|
283
|
+
"""
|
|
284
|
+
resolved = Path(path).resolve()
|
|
285
|
+
for root, skip in ((PROJECTS, 1), (PROJECTS.parent, 0)):
|
|
286
|
+
try:
|
|
287
|
+
parts = resolved.relative_to(root.resolve()).parts[skip:]
|
|
288
|
+
break
|
|
289
|
+
except ValueError:
|
|
290
|
+
continue
|
|
291
|
+
else:
|
|
292
|
+
parts = resolved.parts
|
|
293
|
+
return {found for part in parts for found in SESSION_ID.findall(part)}
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
def started_at(sid):
|
|
297
|
+
"""When a SessionStart hook last saw the session start, or 0."""
|
|
298
|
+
try:
|
|
299
|
+
return (STARTED / sid).stat().st_mtime
|
|
300
|
+
except OSError:
|
|
301
|
+
return 0
|
|
302
|
+
|
|
303
|
+
|
|
304
|
+
def process_of(sid):
|
|
305
|
+
"""The pid of the Claude Code process a SessionStart hook saw running the session, or None."""
|
|
306
|
+
try:
|
|
307
|
+
return int((STARTED / sid).read_text())
|
|
308
|
+
except (OSError, ValueError):
|
|
309
|
+
return None
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
def gone(pid):
|
|
313
|
+
try:
|
|
314
|
+
os.kill(pid, 0)
|
|
315
|
+
except ProcessLookupError:
|
|
316
|
+
return True
|
|
317
|
+
except OSError:
|
|
318
|
+
pass
|
|
319
|
+
return False
|
|
320
|
+
|
|
321
|
+
|
|
322
|
+
def session_ids():
|
|
323
|
+
return sorted({p.stem for p in PROJECTS.glob("*/*.jsonl") if SESSION_ID.fullmatch(p.stem)})
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
def resolve(arg):
|
|
327
|
+
"""Targets for one command-line argument, and whether it names a session."""
|
|
328
|
+
if SESSION_ID.fullmatch(arg):
|
|
329
|
+
targets = sorted(PROJECTS.glob(f"*/{arg}.jsonl")) + sorted(
|
|
330
|
+
p for p in PROJECTS.glob(f"*/{arg}") if p.is_dir()
|
|
331
|
+
)
|
|
332
|
+
if not targets:
|
|
333
|
+
sys.exit(f"scrubscript: no session {arg} under {PROJECTS}")
|
|
334
|
+
named = [DEBUG / f"{arg}.txt", *sorted(TELEMETRY.glob(f"*.{arg}.*")), FILE_HISTORY / arg]
|
|
335
|
+
return targets + [p for p in named if p.exists()], True
|
|
336
|
+
path = Path(arg)
|
|
337
|
+
if not path.exists():
|
|
338
|
+
sys.exit(f"scrubscript: {arg}: no such file, folder or session id")
|
|
339
|
+
return [path], False
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
def strays():
|
|
343
|
+
"""What sessions with no transcript left beside the projects folder, which no session's scrub reaches."""
|
|
344
|
+
known = set(session_ids())
|
|
345
|
+
left = [p for folder in (DEBUG, TELEMETRY) for p in sorted(folder.glob("*"))
|
|
346
|
+
if p.is_file() and not p.is_symlink()]
|
|
347
|
+
left += [p for p in sorted(FILE_HISTORY.glob("*")) if p.is_dir()]
|
|
348
|
+
return [p for p in left if not known & set(SESSION_ID.findall(p.name))]
|
|
349
|
+
|
|
350
|
+
|
|
351
|
+
def files_under(targets):
|
|
352
|
+
for target in targets:
|
|
353
|
+
if target.is_dir():
|
|
354
|
+
yield from (p for p in target.rglob("*") if p.is_file())
|
|
355
|
+
else:
|
|
356
|
+
yield target
|
|
357
|
+
|
|
358
|
+
|
|
359
|
+
def gitleaks():
|
|
360
|
+
"""The gitleaks binary, or None: SCRUBSCRIPT_GITLEAKS names one that is not on PATH."""
|
|
361
|
+
return shutil.which(os.environ.get("SCRUBSCRIPT_GITLEAKS", "gitleaks"))
|
|
362
|
+
|
|
363
|
+
|
|
364
|
+
# What a gitleaks that cannot scan a folder prints: before 8.19 it has no dir command,
|
|
365
|
+
# and 8.19.0 has one that fails on a flag of its own.
|
|
366
|
+
OLD_GITLEAKS_SAYS = (b'unknown command "dir"', b"flag accessed but not defined")
|
|
367
|
+
|
|
368
|
+
|
|
369
|
+
def gitleaks_too_old():
|
|
370
|
+
"""Whether the gitleaks found is older than 8.19.1, the first that scans a folder."""
|
|
371
|
+
return scans_no_folder(gitleaks())
|
|
372
|
+
|
|
373
|
+
|
|
374
|
+
@functools.lru_cache(maxsize=None)
|
|
375
|
+
def scans_no_folder(binary):
|
|
376
|
+
"""Whether this gitleaks is one of the old ones that cannot scan a folder.
|
|
377
|
+
|
|
378
|
+
Its version cannot be read: a distribution's build may print no number. So it is
|
|
379
|
+
asked to scan an empty folder, which takes about 50 ms, and an old one is known by
|
|
380
|
+
what it prints: seen on 8.16.0, 8.18.4 and 8.19.0, against 8.19.1 and 8.30.1. A
|
|
381
|
+
gitleaks that fails any other way, or cannot be run at all, is not called old.
|
|
382
|
+
Asked once in a run and given one second, because the hook that runs when a session
|
|
383
|
+
ends asks too, and has about that long to start the scrub.
|
|
384
|
+
"""
|
|
385
|
+
with tempfile.TemporaryDirectory(prefix="scrubscript-") as empty:
|
|
386
|
+
try:
|
|
387
|
+
run = subprocess.run([binary, "dir", empty, "--no-banner", "--exit-code", "0"],
|
|
388
|
+
capture_output=True, timeout=1)
|
|
389
|
+
except (OSError, subprocess.TimeoutExpired):
|
|
390
|
+
return False
|
|
391
|
+
return run.returncode != 0 and any(said in run.stderr for said in OLD_GITLEAKS_SAYS)
|
|
392
|
+
|
|
393
|
+
|
|
394
|
+
def need_gitleaks():
|
|
395
|
+
binary = gitleaks()
|
|
396
|
+
if not binary:
|
|
397
|
+
sys.exit("scrubscript: gitleaks is not installed, and it does the detection. Install it "
|
|
398
|
+
f"({install_hint('gitleaks')}), or name its binary in SCRUBSCRIPT_GITLEAKS.")
|
|
399
|
+
return binary
|
|
400
|
+
|
|
401
|
+
|
|
402
|
+
def kept_digests():
|
|
403
|
+
"""The SHA-256 of each value the user kept; a line that is not a kept entry is passed over."""
|
|
404
|
+
digests = set()
|
|
405
|
+
try:
|
|
406
|
+
lines = KEPT.read_text().splitlines()
|
|
407
|
+
except OSError:
|
|
408
|
+
return digests
|
|
409
|
+
for line in lines:
|
|
410
|
+
try:
|
|
411
|
+
entry = json.loads(line)
|
|
412
|
+
except ValueError:
|
|
413
|
+
continue
|
|
414
|
+
if isinstance(entry, dict) and isinstance(entry.get("sha256"), str):
|
|
415
|
+
digests.add(entry["sha256"])
|
|
416
|
+
return digests
|
|
417
|
+
|
|
418
|
+
|
|
419
|
+
def digest_of(value):
|
|
420
|
+
return hashlib.sha256(value).hexdigest()
|
|
421
|
+
|
|
422
|
+
|
|
423
|
+
def scan(targets, workdir, text=None):
|
|
424
|
+
"""gitleaks' findings for these files and folders, or for text given on its standard input.
|
|
425
|
+
|
|
426
|
+
A finding whose secret the user kept is marked Kept: no scrub and no --filter
|
|
427
|
+
redacts it, and its occurrences are guarded from shorter findings inside them.
|
|
428
|
+
"""
|
|
429
|
+
binary = need_gitleaks()
|
|
430
|
+
config = workdir / "gitleaks.toml"
|
|
431
|
+
config.write_text(gitleaks_config())
|
|
432
|
+
findings = []
|
|
433
|
+
for i, target in enumerate(targets if text is None else ["standard input"]):
|
|
434
|
+
report = workdir / f"report-{i}.json"
|
|
435
|
+
proc = subprocess.run(
|
|
436
|
+
[binary, *(["dir", str(target)] if text is None else ["stdin"]), "--config", str(config),
|
|
437
|
+
"--gitleaks-ignore-path", str(workdir), "--no-banner", "--no-color",
|
|
438
|
+
"--log-level", "error", "--exit-code", "0",
|
|
439
|
+
"--report-format", "json", "--report-path", str(report)],
|
|
440
|
+
input=text, capture_output=True,
|
|
441
|
+
)
|
|
442
|
+
if proc.returncode != 0:
|
|
443
|
+
# Asked only now, so that a scan that works pays nothing for the question.
|
|
444
|
+
if gitleaks_too_old():
|
|
445
|
+
print(not_redacting_message(OLD_GITLEAKS), file=sys.stderr)
|
|
446
|
+
sys.exit(NOT_REDACTING)
|
|
447
|
+
sys.exit(f"scrubscript: gitleaks failed on {target}:\n{proc.stderr.decode(errors='replace')}")
|
|
448
|
+
findings += around_markers(json.loads(report.read_text() or "[]"))
|
|
449
|
+
report.unlink()
|
|
450
|
+
kept = kept_digests()
|
|
451
|
+
for f in findings:
|
|
452
|
+
f["Kept"] = bool(kept) and digest_of(f["Secret"].encode()) in kept
|
|
453
|
+
return findings
|
|
454
|
+
|
|
455
|
+
|
|
456
|
+
def replacement(value):
|
|
457
|
+
"""What goes where these bytes stood: a new marker in a live filter, else REDACTED."""
|
|
458
|
+
if MARKS is None:
|
|
459
|
+
return REDACTED
|
|
460
|
+
while (mark := os.urandom(MARKER_ID_HEX // 2).hex()) in MARKS:
|
|
461
|
+
pass
|
|
462
|
+
MARKS[mark] = value
|
|
463
|
+
return b"[redacted:%s]" % mark.encode()
|
|
464
|
+
|
|
465
|
+
|
|
466
|
+
def around_markers(findings):
|
|
467
|
+
"""The findings with every marker taken out of them, so nothing ever redacts one.
|
|
468
|
+
|
|
469
|
+
A finding that lies inside a marker goes. One that runs through a marker becomes a
|
|
470
|
+
finding per stretch of text around it, a line at a time, so each is still redacted.
|
|
471
|
+
"""
|
|
472
|
+
kept = []
|
|
473
|
+
for finding in findings:
|
|
474
|
+
secret, match = finding["Secret"], finding.get("Match", "")
|
|
475
|
+
if any(secret in marker for marker in MARKER_TEXT.findall(match)) and secret not in MARKER_TEXT.sub("", match):
|
|
476
|
+
continue
|
|
477
|
+
if not MARKER_TEXT.search(secret):
|
|
478
|
+
kept.append(finding)
|
|
479
|
+
continue
|
|
480
|
+
line = finding["StartLine"]
|
|
481
|
+
# A plain [redacted] beside it is what an earlier pass already cut from the match.
|
|
482
|
+
for piece in re.split(f"({MARKER_TEXT.pattern}|\\[redacted\\]|\n)", secret):
|
|
483
|
+
if piece == "\n":
|
|
484
|
+
line += 1
|
|
485
|
+
elif piece and piece != REDACTED.decode() and not MARKER_TEXT.fullmatch(piece):
|
|
486
|
+
kept.append({**finding, "Secret": piece, "StartLine": line})
|
|
487
|
+
return kept
|
|
488
|
+
|
|
489
|
+
|
|
490
|
+
def unkept(findings):
|
|
491
|
+
return [f for f in findings if not f.get("Kept")]
|
|
492
|
+
|
|
493
|
+
|
|
494
|
+
def filter_text(live=None, as_json=False):
|
|
495
|
+
"""--filter: standard input with its secrets redacted, on standard output.
|
|
496
|
+
|
|
497
|
+
For text on its way into a transcript, before it is stored. Text that cannot be
|
|
498
|
+
scanned or redacted cleanly is not printed at all, and the exit status says so:
|
|
499
|
+
whether it then goes on as it was is the caller's choice.
|
|
500
|
+
|
|
501
|
+
live names the transcript of the session the text goes into, as live redaction
|
|
502
|
+
runs it. Then each replaced span becomes a marker with a random id, what stood there
|
|
503
|
+
is kept encrypted under that id, filed with that transcript, before the text is
|
|
504
|
+
printed, and without a backup nothing is: with no backup key, no age or no
|
|
505
|
+
transcript the text is not printed and the exit status is NOT_REDACTING. Only files
|
|
506
|
+
are checked for first, so no age run is added to text with nothing to replace.
|
|
507
|
+
as_json says the text is JSON the transcript stores as JSON, already escaped there.
|
|
508
|
+
"""
|
|
509
|
+
global MARKS
|
|
510
|
+
if live is not None:
|
|
511
|
+
MARKS = {}
|
|
512
|
+
reason = (NO_GITLEAKS if not gitleaks() else NO_SETUP if backup_target() is None
|
|
513
|
+
else NO_AGE if not age() else None)
|
|
514
|
+
if reason or not live:
|
|
515
|
+
print(not_redacting_message(reason) if reason else
|
|
516
|
+
"scrubscript: no transcript to file the backup with, so nothing is replaced", file=sys.stderr)
|
|
517
|
+
sys.exit(NOT_REDACTING)
|
|
518
|
+
original, found, owners = sys.stdin.buffer.read(), {}, {}
|
|
519
|
+
text = original
|
|
520
|
+
for _ in range(MAX_PASSES):
|
|
521
|
+
with tempfile.TemporaryDirectory(prefix="scrubscript-") as workdir:
|
|
522
|
+
findings = scan([], Path(workdir), text)
|
|
523
|
+
if not unkept(findings):
|
|
524
|
+
break
|
|
525
|
+
lines = text.split(b"\n")
|
|
526
|
+
lines = [line + b"\n" for line in lines[:-1]] + lines[-1:]
|
|
527
|
+
rule_of = {f["Secret"].encode(): f["RuleID"] for f in findings}
|
|
528
|
+
try:
|
|
529
|
+
out = []
|
|
530
|
+
for line, _, present in redacted(lines, findings, None):
|
|
531
|
+
out.append(line)
|
|
532
|
+
here = {value: rule_of.get(value, "?") for value in present}
|
|
533
|
+
found.update(here)
|
|
534
|
+
for mark in MARKER.findall(line):
|
|
535
|
+
owners.setdefault(mark.decode(), here)
|
|
536
|
+
new = b"".join(out)
|
|
537
|
+
except Unclean:
|
|
538
|
+
sys.exit("scrubscript: a secret could not be redacted cleanly")
|
|
539
|
+
if new == text:
|
|
540
|
+
break
|
|
541
|
+
text = new
|
|
542
|
+
records = live_records(text, found, owners, as_json) if live else []
|
|
543
|
+
if records:
|
|
544
|
+
try:
|
|
545
|
+
seal(Path(live), records, LIVE)
|
|
546
|
+
except OSError as error:
|
|
547
|
+
print(f"scrubscript: the backup could not be made, so nothing is replaced: {error}", file=sys.stderr)
|
|
548
|
+
sys.exit(NOT_REDACTING)
|
|
549
|
+
# For the hooks module to tell the model what each marker stands for: the rule, never
|
|
550
|
+
# the value. A line per marker, so standard error cut short loses only the last.
|
|
551
|
+
for r in records:
|
|
552
|
+
print(json.dumps({"issued": {r["id"]: rules_of(MARKS[r["id"]], r["secrets"])}}), file=sys.stderr)
|
|
553
|
+
sys.stdout.buffer.write(text)
|
|
554
|
+
|
|
555
|
+
|
|
556
|
+
def rules_of(span, secrets):
|
|
557
|
+
"""The rules of the secrets inside the span a marker replaced, read as it stands or, for
|
|
558
|
+
a base64 run, decoded. A record carries every secret on its line; a span that holds
|
|
559
|
+
none of them either way has all."""
|
|
560
|
+
try:
|
|
561
|
+
decoded = base64.b64decode(span)
|
|
562
|
+
except ValueError:
|
|
563
|
+
decoded = b""
|
|
564
|
+
inside = {s["rule"] for s in secrets if (value := base64.b64decode(s["value"])) in span or value in decoded}
|
|
565
|
+
return sorted(inside or {s["rule"] for s in secrets})
|
|
566
|
+
|
|
567
|
+
|
|
568
|
+
def marker_sent(tool, transcript, ids):
|
|
569
|
+
"""--marker-sent: log that a tool call carried markers this session issued, by id alone."""
|
|
570
|
+
log_hook("MarkerSent", tool, Path(transcript).stem if transcript else "?",
|
|
571
|
+
f"{len(ids)} issued marker{'s' if len(ids) != 1 else ''} ({', '.join(ids)})")
|
|
572
|
+
|
|
573
|
+
|
|
574
|
+
def live_records(text, found, owners, as_json):
|
|
575
|
+
"""One record per marker this filter left in the text: its id and what stood there.
|
|
576
|
+
|
|
577
|
+
A span cut out of a value over several JSON lines has no secret of its own on the
|
|
578
|
+
line, so it carries those of the whole piece, for the choice of which to keep.
|
|
579
|
+
"""
|
|
580
|
+
records = []
|
|
581
|
+
for mark in dict.fromkeys(m.decode() for m in MARKER.findall(text)):
|
|
582
|
+
if mark in MARKS:
|
|
583
|
+
held = owners.get(mark) or found
|
|
584
|
+
records.append({"id": mark, "was": MARKS[mark].decode(errors="surrogateescape"),
|
|
585
|
+
"secrets": [{"rule": rule, "value": base64.b64encode(value).decode()}
|
|
586
|
+
for value, rule in sorted(held.items())],
|
|
587
|
+
**({"json": True} if as_json else {})})
|
|
588
|
+
return records
|
|
589
|
+
|
|
590
|
+
|
|
591
|
+
def parses(line):
|
|
592
|
+
try:
|
|
593
|
+
json.loads(line)
|
|
594
|
+
except ValueError:
|
|
595
|
+
return False
|
|
596
|
+
return True
|
|
597
|
+
|
|
598
|
+
|
|
599
|
+
def trimmed(secret):
|
|
600
|
+
"""The secret without a trailing backslash that opens the next JSON escape.
|
|
601
|
+
|
|
602
|
+
gitleaks' jwt rule admits backslashes, so in `\"Bearer eyJ...\"` it swallows the
|
|
603
|
+
backslash of the closing escaped quote; replacing that leaves a bare quote.
|
|
604
|
+
"""
|
|
605
|
+
run = len(secret) - len(secret.rstrip(b"\\"))
|
|
606
|
+
return secret[:-1] if run % 2 else secret
|
|
607
|
+
|
|
608
|
+
|
|
609
|
+
JSON_STRING = re.compile(rb'"(?:[^"\\]|\\.)*"')
|
|
610
|
+
|
|
611
|
+
|
|
612
|
+
def escaped_at(line, i):
|
|
613
|
+
"""Whether line[i] is the character an escape's backslash applies to."""
|
|
614
|
+
run = 0
|
|
615
|
+
while i - run > 0 and line[i - run - 1] == 0x5C:
|
|
616
|
+
run += 1
|
|
617
|
+
return run % 2 == 1
|
|
618
|
+
|
|
619
|
+
|
|
620
|
+
def cut_spans(line, spans):
|
|
621
|
+
"""Redact the part of each JSON string value a span covers, keeping the JSON valid.
|
|
622
|
+
|
|
623
|
+
A match can straddle JSON structure (a private key whose match runs on into the
|
|
624
|
+
next string, a token ending on its closing quote), so the cut is made per string
|
|
625
|
+
value, widened so no escape is split, and object keys are left alone.
|
|
626
|
+
"""
|
|
627
|
+
cuts = []
|
|
628
|
+
for token in JSON_STRING.finditer(line):
|
|
629
|
+
ts, te = token.start() + 1, token.end() - 1
|
|
630
|
+
rest = line[token.end():token.end() + 64].lstrip()
|
|
631
|
+
if rest.startswith(b":"):
|
|
632
|
+
continue
|
|
633
|
+
for a, b in spans:
|
|
634
|
+
s, e = max(a, ts), min(b, te)
|
|
635
|
+
if s >= e:
|
|
636
|
+
continue
|
|
637
|
+
if escaped_at(line, s):
|
|
638
|
+
s -= 1
|
|
639
|
+
if e < te and escaped_at(line, e):
|
|
640
|
+
e += 1
|
|
641
|
+
cuts.append((s, e))
|
|
642
|
+
merged = []
|
|
643
|
+
for s, e in sorted(cuts):
|
|
644
|
+
if merged and s <= merged[-1][1]:
|
|
645
|
+
merged[-1] = (merged[-1][0], max(merged[-1][1], e))
|
|
646
|
+
else:
|
|
647
|
+
merged.append((s, e))
|
|
648
|
+
for s, e in reversed(merged):
|
|
649
|
+
line = line[:s] + replacement(line[s:e]) + line[e:]
|
|
650
|
+
return line
|
|
651
|
+
|
|
652
|
+
|
|
653
|
+
def crosses_strings(secret):
|
|
654
|
+
"""Whether the match holds an unescaped quote, so it runs across JSON strings."""
|
|
655
|
+
run = 0
|
|
656
|
+
for byte in secret:
|
|
657
|
+
if byte == 0x22 and run % 2 == 0:
|
|
658
|
+
return True
|
|
659
|
+
run = run + 1 if byte == 0x5C else 0
|
|
660
|
+
return False
|
|
661
|
+
|
|
662
|
+
|
|
663
|
+
def spans_of(line, value):
|
|
664
|
+
found, start = [], 0
|
|
665
|
+
while (k := line.find(value, start)) >= 0:
|
|
666
|
+
found.append((k, k + len(value)))
|
|
667
|
+
start = k + 1
|
|
668
|
+
return found
|
|
669
|
+
|
|
670
|
+
|
|
671
|
+
def outside(spans, guarded):
|
|
672
|
+
return [(a, b) for a, b in spans if not any(a < y and x < b for x, y in guarded)]
|
|
673
|
+
|
|
674
|
+
|
|
675
|
+
def replace_outside(line, secrets, guarded):
|
|
676
|
+
"""The line with each secret replaced, longest first, except where it lies in a guarded span."""
|
|
677
|
+
taken = list(guarded)
|
|
678
|
+
cuts = []
|
|
679
|
+
for secret in secrets:
|
|
680
|
+
start = 0
|
|
681
|
+
while (k := line.find(secret, start)) >= 0:
|
|
682
|
+
span = (k, k + len(secret))
|
|
683
|
+
if outside([span], taken):
|
|
684
|
+
cuts.append(span)
|
|
685
|
+
taken.append(span)
|
|
686
|
+
start = span[1]
|
|
687
|
+
else:
|
|
688
|
+
start = k + 1
|
|
689
|
+
for a, b in sorted(cuts, reverse=True):
|
|
690
|
+
line = line[:a] + replacement(line[a:b]) + line[b:]
|
|
691
|
+
return line
|
|
692
|
+
|
|
693
|
+
|
|
694
|
+
# What ends a word around a secret: a kept value that gitleaks did not report is found
|
|
695
|
+
# as the whole word a shorter secret sits in.
|
|
696
|
+
WORD_END = frozenset(b" \t\r\n\"'`,;()[]{}<>\\")
|
|
697
|
+
|
|
698
|
+
|
|
699
|
+
def word_around(line, a, b):
|
|
700
|
+
while a > 0 and line[a - 1] not in WORD_END:
|
|
701
|
+
a -= 1
|
|
702
|
+
while b < len(line) and line[b] not in WORD_END:
|
|
703
|
+
b += 1
|
|
704
|
+
return a, b
|
|
705
|
+
|
|
706
|
+
|
|
707
|
+
def guarded_spans(line, secrets, kept):
|
|
708
|
+
"""Where kept values stand in the line, so no secret is cut out of them.
|
|
709
|
+
|
|
710
|
+
kept is (the kept values gitleaks reported in this scan, the digests of every
|
|
711
|
+
kept value). A kept value it did not report is found as the word around an
|
|
712
|
+
occurrence of a secret, when that word's digest is a kept one.
|
|
713
|
+
"""
|
|
714
|
+
values, digests = kept
|
|
715
|
+
guarded = [span for value in values for span in spans_of(line, value)]
|
|
716
|
+
guarded += [marker.span() for marker in MARKER.finditer(line)]
|
|
717
|
+
if digests:
|
|
718
|
+
for secret in secrets:
|
|
719
|
+
for a, b in spans_of(line, trimmed(secret)):
|
|
720
|
+
x, y = word_around(line, a, b)
|
|
721
|
+
if (x, y) != (a, b) and digest_of(line[x:y]) in digests:
|
|
722
|
+
guarded.append((x, y))
|
|
723
|
+
return guarded
|
|
724
|
+
|
|
725
|
+
|
|
726
|
+
def left_in(line, secrets, kept):
|
|
727
|
+
"""Whether a secret is still in the line anywhere but inside a kept value."""
|
|
728
|
+
guarded = guarded_spans(line, secrets, kept)
|
|
729
|
+
return any(outside(spans_of(line, trimmed(s)), guarded) for s in secrets)
|
|
730
|
+
|
|
731
|
+
|
|
732
|
+
def redact_line(line, secrets, check_json, kept=((), frozenset())):
|
|
733
|
+
"""(new line, secrets found on it, or None when it cannot be redacted cleanly).
|
|
734
|
+
|
|
735
|
+
A kept value's occurrences are guarded: a shorter secret inside one is not cut out of it.
|
|
736
|
+
A DOCUMENT line is a piece of a JSON document that need not parse on its own, so its
|
|
737
|
+
secrets are always cut inside string values.
|
|
738
|
+
"""
|
|
739
|
+
guarded = guarded_spans(line, secrets, kept)
|
|
740
|
+
present = [s for s in secrets if outside(spans_of(line, trimmed(s)), guarded)]
|
|
741
|
+
if not present:
|
|
742
|
+
return line, present
|
|
743
|
+
# Each span of a live filter gets its own marker, which only the spans can give.
|
|
744
|
+
if guarded or MARKS is not None:
|
|
745
|
+
new = replace_outside(line, [trimmed(s) for s in present], guarded)
|
|
746
|
+
else:
|
|
747
|
+
new = line
|
|
748
|
+
for secret in present:
|
|
749
|
+
new = new.replace(trimmed(secret), REDACTED)
|
|
750
|
+
# Replacing a match that crosses strings can still parse with a key cut out of it.
|
|
751
|
+
straddles = check_json and any(crosses_strings(trimmed(s)) for s in present)
|
|
752
|
+
if not check_json or not new.strip() or (check_json is not DOCUMENT and parses(new) and not straddles):
|
|
753
|
+
return new, present
|
|
754
|
+
spans = outside([span for secret in present for span in spans_of(line, trimmed(secret))], guarded)
|
|
755
|
+
new = cut_spans(line, spans)
|
|
756
|
+
return (new if check_json is DOCUMENT or parses(new) else None), present
|
|
757
|
+
|
|
758
|
+
|
|
759
|
+
# A base64 run, possibly wrapped: inside a JSON string a line break is the two bytes \n.
|
|
760
|
+
BASE64_RUN = re.compile(rb"(?:[A-Za-z0-9+/_-]{4,}(?:(?:\\r)?\\n)?)+={0,2}")
|
|
761
|
+
|
|
762
|
+
|
|
763
|
+
def redact_base64(line, secrets):
|
|
764
|
+
"""(new line, secrets redacted) for secrets gitleaks found only by decoding base64.
|
|
765
|
+
|
|
766
|
+
Each run that decodes to bytes holding a secret is decoded, redacted and encoded
|
|
767
|
+
again, keeping its line width. Its content changes length, which is harmless in a
|
|
768
|
+
transcript but would corrupt a binary attachment, and no secret is found in one.
|
|
769
|
+
"""
|
|
770
|
+
done = set()
|
|
771
|
+
|
|
772
|
+
def decode(chunks):
|
|
773
|
+
"""(bytes, urlsafe) or (None, False)."""
|
|
774
|
+
flat = b"".join(chunks)
|
|
775
|
+
if len(flat) < 24:
|
|
776
|
+
return None, False
|
|
777
|
+
urlsafe = b"-" in flat or b"_" in flat
|
|
778
|
+
try:
|
|
779
|
+
padded = flat + b"=" * (-len(flat) % 4)
|
|
780
|
+
if urlsafe:
|
|
781
|
+
return base64.b64decode(padded, altchars=b"-_", validate=True), True
|
|
782
|
+
return base64.b64decode(padded, validate=True), False
|
|
783
|
+
except (binascii.Error, ValueError):
|
|
784
|
+
return None, False
|
|
785
|
+
|
|
786
|
+
def recode(match):
|
|
787
|
+
parts = re.split(rb"(?:\\r)?\\n", match.group(0))
|
|
788
|
+
# A word before a line break reads as a chunk too, so the blob may start a
|
|
789
|
+
# chunk or two in; it ends at the first chunk wider than its wrap width.
|
|
790
|
+
for start in range(min(3, len(parts))):
|
|
791
|
+
width, end = len(parts[start]), start + 1
|
|
792
|
+
while end < len(parts) and len(parts[end - 1]) == width and len(parts[end]) <= width:
|
|
793
|
+
end += 1
|
|
794
|
+
raw, urlsafe = decode(parts[start:end])
|
|
795
|
+
hit = [s for s in secrets if raw is not None and s in raw]
|
|
796
|
+
if not hit:
|
|
797
|
+
continue
|
|
798
|
+
done.update(hit)
|
|
799
|
+
if MARKS is not None:
|
|
800
|
+
# A marker inside the encoding could not be found again: the run is its span.
|
|
801
|
+
tokens = re.split(rb"((?:\\r)?\\n)", match.group(0))
|
|
802
|
+
return (b"".join(tokens[:2 * start]) + replacement(b"".join(tokens[2 * start:2 * end - 1]))
|
|
803
|
+
+ b"".join(tokens[2 * end - 1:]))
|
|
804
|
+
for secret in sorted(hit, key=len, reverse=True):
|
|
805
|
+
raw = raw.replace(secret, REDACTED)
|
|
806
|
+
encoded = base64.urlsafe_b64encode(raw) if urlsafe else base64.b64encode(raw)
|
|
807
|
+
if not parts[end - 1].endswith(b"="):
|
|
808
|
+
encoded = encoded.rstrip(b"=")
|
|
809
|
+
wrapped = [encoded[i:i + width] for i in range(0, len(encoded), width)] if end - start > 1 else [encoded]
|
|
810
|
+
return b"\\n".join(parts[:start] + wrapped + parts[end:])
|
|
811
|
+
return match.group(0)
|
|
812
|
+
|
|
813
|
+
return BASE64_RUN.sub(recode, line), done
|
|
814
|
+
|
|
815
|
+
|
|
816
|
+
def history_view(sessions, folder):
|
|
817
|
+
"""(a copy of the prompt history holding only these sessions' prompts, the pastes they name).
|
|
818
|
+
|
|
819
|
+
Every other line is copied empty, so a finding's line number is its line in the
|
|
820
|
+
history itself. The copy holds what the prompts hold: the folder is the caller's
|
|
821
|
+
private one.
|
|
822
|
+
"""
|
|
823
|
+
if not sessions or not HISTORY.is_file():
|
|
824
|
+
return None, []
|
|
825
|
+
marks = [sid.encode() for sid in sessions]
|
|
826
|
+
folder.mkdir()
|
|
827
|
+
view, pastes = folder / HISTORY.name, set()
|
|
828
|
+
with open(HISTORY, "rb") as src, open(view, "wb") as dst:
|
|
829
|
+
for line in src:
|
|
830
|
+
entry = None
|
|
831
|
+
if any(mark in line for mark in marks):
|
|
832
|
+
try:
|
|
833
|
+
entry = json.loads(line)
|
|
834
|
+
except ValueError:
|
|
835
|
+
pass
|
|
836
|
+
if not isinstance(entry, dict) or entry.get("sessionId") not in sessions:
|
|
837
|
+
dst.write(b"\n")
|
|
838
|
+
continue
|
|
839
|
+
dst.write(line)
|
|
840
|
+
pasted = entry.get("pastedContents")
|
|
841
|
+
for paste in pasted.values() if isinstance(pasted, dict) else ():
|
|
842
|
+
name = paste.get("contentHash") if isinstance(paste, dict) else None
|
|
843
|
+
if isinstance(name, str) and re.fullmatch(r"[0-9a-f]+", name):
|
|
844
|
+
pastes.add(PASTES / f"{name}.txt")
|
|
845
|
+
return view, sorted(p for p in pastes if p.is_file())
|
|
846
|
+
|
|
847
|
+
|
|
848
|
+
def take_lock(path):
|
|
849
|
+
"""Take the lock Claude Code holds while it writes this file; the lock folder, or None.
|
|
850
|
+
|
|
851
|
+
Whoever makes the folder holds the lock and removes it when done. One older than
|
|
852
|
+
LOCK_STALE_SECONDS was abandoned, and is taken over. A session that finds the lock
|
|
853
|
+
held retries for a few seconds and may then drop the prompt it was saving, so the
|
|
854
|
+
caller holds it for one rename and no longer.
|
|
855
|
+
"""
|
|
856
|
+
lock = Path(f"{path.resolve()}.lock")
|
|
857
|
+
for _ in range(40):
|
|
858
|
+
try:
|
|
859
|
+
os.mkdir(lock)
|
|
860
|
+
return lock
|
|
861
|
+
except FileExistsError:
|
|
862
|
+
try:
|
|
863
|
+
if time.time() - lock.stat().st_mtime > LOCK_STALE_SECONDS:
|
|
864
|
+
os.rmdir(lock)
|
|
865
|
+
continue
|
|
866
|
+
except OSError:
|
|
867
|
+
continue
|
|
868
|
+
time.sleep(0.05)
|
|
869
|
+
return None
|
|
870
|
+
|
|
871
|
+
|
|
872
|
+
def redact_spanning(block, pieces, check_json):
|
|
873
|
+
"""The lines a match that runs over these lines leaves, or None when it is not there.
|
|
874
|
+
|
|
875
|
+
pieces is the match split at its line breaks: the end of the first line, whole
|
|
876
|
+
lines, the start of the last. Plain text gets the match replaced as one piece. In
|
|
877
|
+
JSON each line's part is cut inside its string values, so each line stays a record.
|
|
878
|
+
"""
|
|
879
|
+
texts = [line.rstrip(b"\n") for line in block]
|
|
880
|
+
if len(block) != len(pieces) or not texts[0].endswith(pieces[0]) or not block[-1].startswith(pieces[-1]) \
|
|
881
|
+
or texts[1:-1] != pieces[1:-1]:
|
|
882
|
+
return None
|
|
883
|
+
start = len(texts[0]) - len(pieces[0])
|
|
884
|
+
if not check_json:
|
|
885
|
+
return [block[0][:start] + replacement(b"\n".join(pieces)) + block[-1][len(pieces[-1]):]]
|
|
886
|
+
return [cut_spans(block[0], [(start, len(texts[0]))]),
|
|
887
|
+
*(cut_spans(line, [(0, len(text))]) for line, text in zip(block[1:-1], texts[1:-1])),
|
|
888
|
+
cut_spans(block[-1], [(0, len(pieces[-1]))])]
|
|
889
|
+
|
|
890
|
+
|
|
891
|
+
def stamp(path):
|
|
892
|
+
st = path.stat()
|
|
893
|
+
return st.st_size, st.st_mtime_ns
|
|
894
|
+
|
|
895
|
+
|
|
896
|
+
class Unclean(Exception):
|
|
897
|
+
"""A line could not be redacted and stay valid."""
|
|
898
|
+
|
|
899
|
+
|
|
900
|
+
# A JSON file that is one document over many lines, as Gemini CLI writes its chats:
|
|
901
|
+
# its lines do not parse one by one, so the document is checked whole.
|
|
902
|
+
DOCUMENT = "document"
|
|
903
|
+
|
|
904
|
+
|
|
905
|
+
def json_layout(path):
|
|
906
|
+
"""How a file's lines are JSON: True for one record per line, DOCUMENT, or None."""
|
|
907
|
+
if path.suffix == ".jsonl":
|
|
908
|
+
return True
|
|
909
|
+
if path.suffix != ".json":
|
|
910
|
+
return None
|
|
911
|
+
data = path.read_bytes()
|
|
912
|
+
if all(parses(line) for line in data.split(b"\n") if line.strip()):
|
|
913
|
+
return True
|
|
914
|
+
return DOCUMENT if parses(data) else None
|
|
915
|
+
|
|
916
|
+
|
|
917
|
+
def redacted(lines, findings, check_json):
|
|
918
|
+
"""Each line with the findings' secrets redacted: (new line, what stood there, secrets redacted).
|
|
919
|
+
|
|
920
|
+
check_json says every line is JSON and must stay so; None says it of each line that
|
|
921
|
+
is JSON as it stands; DOCUMENT says the lines together are one JSON document that
|
|
922
|
+
must stay so. A match that runs over lines comes back as one line in plain
|
|
923
|
+
text. Raises Unclean for a line that cannot be redacted cleanly.
|
|
924
|
+
"""
|
|
925
|
+
kept = (sorted({f["Secret"].encode() for f in findings if f.get("Kept")}, key=len, reverse=True), kept_digests())
|
|
926
|
+
findings = unkept(findings)
|
|
927
|
+
secrets = sorted({s for f in findings if len(s := f["Secret"].encode()) >= MIN_SECRET_LEN}, key=len, reverse=True)
|
|
928
|
+
by_line, spanning = defaultdict(set), {}
|
|
929
|
+
for f in findings:
|
|
930
|
+
if len(f["Secret"]) >= MIN_SECRET_LEN:
|
|
931
|
+
by_line[f["StartLine"]].add(f["Secret"].encode())
|
|
932
|
+
if "\n" in f["Secret"]:
|
|
933
|
+
spanning[f["StartLine"]] = f["Secret"].encode().split(b"\n")
|
|
934
|
+
numbered = enumerate(lines, 1)
|
|
935
|
+
document = [] if check_json is DOCUMENT else None
|
|
936
|
+
for number, line in numbered:
|
|
937
|
+
# (the line, what the text held where this line will stand, a match cut out of it already)
|
|
938
|
+
block = [(line, line, [])]
|
|
939
|
+
pieces = spanning.get(number)
|
|
940
|
+
if pieces:
|
|
941
|
+
held = [line] + [text for _, text in itertools.islice(numbered, len(pieces) - 1)]
|
|
942
|
+
as_json = all(parses(text) for text in held) if check_json is None else check_json
|
|
943
|
+
cut = redact_spanning(held, pieces, as_json)
|
|
944
|
+
block = [(text, text, []) for text in held]
|
|
945
|
+
if cut is not None:
|
|
946
|
+
block = list(zip(cut, held if len(cut) > 1 else [b"".join(held)],
|
|
947
|
+
[[b"\n".join(pieces)]] + [[]] * (len(cut) - 1)))
|
|
948
|
+
for line, held, cut_out in block:
|
|
949
|
+
as_json = parses(held) if check_json is None else check_json
|
|
950
|
+
new, present = redact_line(line, secrets, as_json, kept)
|
|
951
|
+
encoded = [s for s in by_line.get(number, ()) if s not in present]
|
|
952
|
+
if new is not None and encoded:
|
|
953
|
+
new, done = redact_base64(new, encoded)
|
|
954
|
+
present = present + sorted(done)
|
|
955
|
+
if new is None or left_in(new, present, kept) or \
|
|
956
|
+
(as_json and as_json is not DOCUMENT and new.strip() and not parses(new)):
|
|
957
|
+
raise Unclean
|
|
958
|
+
if document is not None:
|
|
959
|
+
document.append(new)
|
|
960
|
+
yield new, held, present + cut_out
|
|
961
|
+
if document is not None and not parses(b"".join(document)):
|
|
962
|
+
raise Unclean
|
|
963
|
+
|
|
964
|
+
|
|
965
|
+
def backup_folder():
|
|
966
|
+
return STATE.parent / "backups"
|
|
967
|
+
|
|
968
|
+
|
|
969
|
+
def path_key(path):
|
|
970
|
+
"""A short name for one file, from a hash of its full path."""
|
|
971
|
+
return hashlib.sha256(str(path.resolve()).encode()).hexdigest()[:16]
|
|
972
|
+
|
|
973
|
+
|
|
974
|
+
def backups_of(path):
|
|
975
|
+
"""The scrub's encrypted backups of one file, newest first: they are named for a hash of its path."""
|
|
976
|
+
name = path_key(path)
|
|
977
|
+
return sorted((p for p in backup_folder().glob(f"{name}.*.age") if f".{LIVE}." not in p.name), reverse=True)
|
|
978
|
+
|
|
979
|
+
|
|
980
|
+
def live_backups_of(path):
|
|
981
|
+
"""The backups live redaction filed with one transcript, newest first."""
|
|
982
|
+
return sorted(backup_folder().glob(f"{path_key(path)}.{LIVE}.*.age"), reverse=True)
|
|
983
|
+
|
|
984
|
+
|
|
985
|
+
def age():
|
|
986
|
+
"""The age binary, or None: SCRUBSCRIPT_AGE names one that is not on PATH."""
|
|
987
|
+
return shutil.which(os.environ.get("SCRUBSCRIPT_AGE", "age"))
|
|
988
|
+
|
|
989
|
+
|
|
990
|
+
def age_keygen():
|
|
991
|
+
"""The age-keygen beside the age binary, or the one on PATH, or None."""
|
|
992
|
+
binary = age()
|
|
993
|
+
beside = Path(binary).with_name("age-keygen") if binary else None
|
|
994
|
+
return str(beside) if beside and os.access(beside, os.X_OK) else shutil.which("age-keygen")
|
|
995
|
+
|
|
996
|
+
|
|
997
|
+
# Where to read how to install each tool, for a platform with no package manager known here.
|
|
998
|
+
INSTALL_PAGES = {"age": "https://github.com/FiloSottile/age#installation",
|
|
999
|
+
"gitleaks": "https://github.com/gitleaks/gitleaks#installing"}
|
|
1000
|
+
|
|
1001
|
+
|
|
1002
|
+
def install_hint(package):
|
|
1003
|
+
"""The command that installs age or gitleaks with this platform's package manager.
|
|
1004
|
+
|
|
1005
|
+
scrubscript names the command and never runs it, nor downloads a binary itself.
|
|
1006
|
+
"""
|
|
1007
|
+
if sys.platform == "darwin":
|
|
1008
|
+
return f"brew install {package}"
|
|
1009
|
+
for manager, command in (("apt-get", "sudo apt install"), ("pacman", "sudo pacman -S"),
|
|
1010
|
+
("dnf", "sudo dnf install"), ("zypper", "sudo zypper install"),
|
|
1011
|
+
("apk", "sudo apk add"), ("brew", "brew install")):
|
|
1012
|
+
if shutil.which(manager):
|
|
1013
|
+
# Checked 2026-11-22: Ubuntu 24.04 to 26.04 and Debian 13 package gitleaks 8.16.
|
|
1014
|
+
if package == "gitleaks" and manager == "apt-get":
|
|
1015
|
+
return (f"{command} {package} only if your release packages 8.19.1 or later, which Ubuntu 24.04 "
|
|
1016
|
+
"and Debian 13 do not; otherwise https://github.com/gitleaks/gitleaks/releases")
|
|
1017
|
+
return f"{command} {package}"
|
|
1018
|
+
return f"see {INSTALL_PAGES[package]}"
|
|
1019
|
+
|
|
1020
|
+
|
|
1021
|
+
def backup_target():
|
|
1022
|
+
"""The recipients file each backup is encrypted to, or None when there is none."""
|
|
1023
|
+
return str(RECIPIENTS) if RECIPIENTS.is_file() else None
|
|
1024
|
+
|
|
1025
|
+
|
|
1026
|
+
# Why no scrub may rewrite a file.
|
|
1027
|
+
NO_GITLEAKS, OLD_GITLEAKS, NO_SETUP, NO_AGE, BAD_KEY = "no gitleaks", "old gitleaks", "no setup", "no age", "bad key"
|
|
1028
|
+
# The reasons a fresh install has, which leave no sweep record to catch up from.
|
|
1029
|
+
WAITS = (NO_GITLEAKS, OLD_GITLEAKS, NO_SETUP)
|
|
1030
|
+
|
|
1031
|
+
|
|
1032
|
+
def key_error():
|
|
1033
|
+
"""age's own one-line error when it cannot encrypt to the recipients file, else None.
|
|
1034
|
+
|
|
1035
|
+
Asking age is the only check that agrees with what a backup will do.
|
|
1036
|
+
"""
|
|
1037
|
+
try:
|
|
1038
|
+
probe = subprocess.run([age(), "-R", str(RECIPIENTS)], input=b"probe", stdout=subprocess.DEVNULL,
|
|
1039
|
+
stderr=subprocess.PIPE, timeout=3)
|
|
1040
|
+
except (OSError, subprocess.SubprocessError) as error:
|
|
1041
|
+
return str(error)
|
|
1042
|
+
if probe.returncode == 0:
|
|
1043
|
+
return None
|
|
1044
|
+
lines = probe.stderr.decode(errors="replace").strip().splitlines()
|
|
1045
|
+
return lines[0] if lines else f"age exited {probe.returncode}"
|
|
1046
|
+
|
|
1047
|
+
|
|
1048
|
+
def not_redacting():
|
|
1049
|
+
"""Why no scrub may rewrite a file, or None: nothing to find secrets with, or no backup to keep."""
|
|
1050
|
+
if not gitleaks():
|
|
1051
|
+
return NO_GITLEAKS
|
|
1052
|
+
return OLD_GITLEAKS if gitleaks_too_old() else backup_problem()
|
|
1053
|
+
|
|
1054
|
+
|
|
1055
|
+
def backup_problem():
|
|
1056
|
+
"""Why no backup can be made, or None: backups not set up, no age, or a key age cannot use."""
|
|
1057
|
+
if backup_target() is None:
|
|
1058
|
+
return NO_SETUP
|
|
1059
|
+
if not age():
|
|
1060
|
+
return NO_AGE
|
|
1061
|
+
return BAD_KEY if key_error() else None
|
|
1062
|
+
|
|
1063
|
+
|
|
1064
|
+
def own_command():
|
|
1065
|
+
"""How the user runs this script: the installed command, or the plugin's own file."""
|
|
1066
|
+
if Path(sys.argv[0]).name == "scrubscript":
|
|
1067
|
+
return "scrubscript"
|
|
1068
|
+
return f"python3 {shlex.quote(os.path.abspath(__file__))}"
|
|
1069
|
+
|
|
1070
|
+
|
|
1071
|
+
def not_redacting_message(reason):
|
|
1072
|
+
"""What to tell the user about a refusal, with the command for each way out."""
|
|
1073
|
+
cmd = own_command()
|
|
1074
|
+
if reason == NO_GITLEAKS:
|
|
1075
|
+
return (f"scrubscript is not redacting: gitleaks, which finds the secrets, is not installed. "
|
|
1076
|
+
f"Install it ({install_hint('gitleaks')}), version 8.19.1 or later.")
|
|
1077
|
+
if reason == OLD_GITLEAKS:
|
|
1078
|
+
return (f"scrubscript is not redacting: the gitleaks at {gitleaks()} is older than 8.19.1, the first "
|
|
1079
|
+
f"version that scans the way scrubscript asks. Install a newer one ({install_hint('gitleaks')}), or name a newer "
|
|
1080
|
+
f"binary in SCRUBSCRIPT_GITLEAKS.")
|
|
1081
|
+
if reason == NO_SETUP:
|
|
1082
|
+
before = ("Redacting with no backup is no longer offered, so the --no-backups choice made here "
|
|
1083
|
+
"no longer applies. " if OPTED_OUT.exists() else "")
|
|
1084
|
+
return (f"scrubscript is not redacting, at a session's end or as text comes in, until you set up backups. "
|
|
1085
|
+
f"{before}In a terminal no agent can "
|
|
1086
|
+
f"read, run `{cmd} --setup`: it shows the recovery code that undoes every redaction.")
|
|
1087
|
+
if reason == BAD_KEY:
|
|
1088
|
+
return (f"scrubscript is not redacting: the key in {RECIPIENTS} cannot be used ({key_error()}). "
|
|
1089
|
+
f"Fix the key in that file, or run `{cmd} --setup` in a terminal for a new key.")
|
|
1090
|
+
return (f"scrubscript is not redacting: age, which encrypts the backups, is not installed. "
|
|
1091
|
+
f"Install it ({install_hint('age')}).")
|
|
1092
|
+
|
|
1093
|
+
|
|
1094
|
+
def not_redacting_short(reason):
|
|
1095
|
+
"""The refusal in a few words, for the hook log."""
|
|
1096
|
+
return {NO_GITLEAKS: "gitleaks is not installed", OLD_GITLEAKS: "gitleaks is older than 8.19.1",
|
|
1097
|
+
NO_SETUP: "backups not set up", NO_AGE: "age is not installed",
|
|
1098
|
+
BAD_KEY: "the key in the recipients file cannot be used"}[reason]
|
|
1099
|
+
|
|
1100
|
+
|
|
1101
|
+
def at_own_terminal():
|
|
1102
|
+
"""Whether a person runs this at a terminal, outside Claude Code."""
|
|
1103
|
+
return not os.environ.get("CLAUDECODE") and sys.stdin.isatty() and sys.stdout.isatty()
|
|
1104
|
+
|
|
1105
|
+
|
|
1106
|
+
def refuse_outside_terminal(flag, why, arguments=()):
|
|
1107
|
+
"""Exit unless a person runs this at a terminal of their own, outside Claude Code.
|
|
1108
|
+
|
|
1109
|
+
The refusal ends with the whole command, since the one who reads it is often an
|
|
1110
|
+
agent that was asked to run it, and has to hand the person a line to paste.
|
|
1111
|
+
"""
|
|
1112
|
+
if not at_own_terminal():
|
|
1113
|
+
command = " ".join([own_command(), flag.split()[0], *map(shlex.quote, arguments)])
|
|
1114
|
+
sys.exit(f"scrubscript: run {flag} yourself, in a terminal and outside Claude Code: {why}. "
|
|
1115
|
+
f"The command to run there:\n {command}")
|
|
1116
|
+
|
|
1117
|
+
|
|
1118
|
+
def mark_waiting():
|
|
1119
|
+
"""Note when a hook first found nothing redacting, so the first sweep after can catch up from there."""
|
|
1120
|
+
try:
|
|
1121
|
+
WAITING.parent.mkdir(parents=True, exist_ok=True)
|
|
1122
|
+
os.close(os.open(WAITING, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600))
|
|
1123
|
+
except FileExistsError:
|
|
1124
|
+
pass
|
|
1125
|
+
|
|
1126
|
+
|
|
1127
|
+
def write_choice(path, text):
|
|
1128
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
1129
|
+
partial = path.with_name(f".{path.name}.tmp")
|
|
1130
|
+
partial.write_text(text)
|
|
1131
|
+
os.replace(partial, path)
|
|
1132
|
+
|
|
1133
|
+
|
|
1134
|
+
def setup():
|
|
1135
|
+
"""--setup: make a key pair, keep the public half, show the secret half once as the recovery code.
|
|
1136
|
+
|
|
1137
|
+
The secret key comes from age-keygen through a pipe and goes nowhere but the
|
|
1138
|
+
terminal. A backup is encrypted to the public half and opened with that key, and only
|
|
1139
|
+
once that works is the key recorded.
|
|
1140
|
+
"""
|
|
1141
|
+
refuse_outside_terminal("--setup", "the recovery code it shows would otherwise be written to a "
|
|
1142
|
+
"session's transcript and sent to the model")
|
|
1143
|
+
binary, keygen = age(), age_keygen()
|
|
1144
|
+
if not binary or not keygen:
|
|
1145
|
+
sys.exit(f"scrubscript: age is not installed, and it encrypts the backups. Install it "
|
|
1146
|
+
f"({install_hint('age')}), then run --setup again. Nothing was changed.")
|
|
1147
|
+
made = subprocess.run([keygen], capture_output=True)
|
|
1148
|
+
secret = next((line for line in made.stdout.decode(errors="replace").splitlines()
|
|
1149
|
+
if line.startswith("AGE-SECRET-KEY-")), None)
|
|
1150
|
+
if made.returncode != 0 or not secret:
|
|
1151
|
+
sys.exit(f"scrubscript: age-keygen failed: {made.stderr.decode(errors='replace').strip()}")
|
|
1152
|
+
public = subprocess.run([keygen, "-y"], input=f"{secret}\n".encode(), capture_output=True)
|
|
1153
|
+
recipient = public.stdout.decode().strip()
|
|
1154
|
+
# A backup made and opened before anything is recorded: the key must work.
|
|
1155
|
+
with tempfile.TemporaryDirectory(prefix="scrubscript-setup-") as workdir:
|
|
1156
|
+
sealed = Path(workdir) / "probe.age"
|
|
1157
|
+
with open(sealed, "wb") as dst:
|
|
1158
|
+
made = subprocess.run([binary, "-r", recipient], input=b"probe", stdout=dst, stderr=subprocess.PIPE)
|
|
1159
|
+
opened = subprocess.run([binary, "--decrypt", "-i", "-", str(sealed)], input=f"{secret}\n".encode(),
|
|
1160
|
+
capture_output=True)
|
|
1161
|
+
if public.returncode != 0 or made.returncode != 0 or opened.stdout != b"probe":
|
|
1162
|
+
sys.exit("scrubscript: age could not make and open a test backup, so backups were not set up: "
|
|
1163
|
+
f"{(made.stderr or opened.stderr).decode(errors='replace').strip()}")
|
|
1164
|
+
# The code is shown on the terminal's alternate screen, which most terminals clear
|
|
1165
|
+
# on leaving it, so it stays out of the scrollback and of a scrollback saved to disk.
|
|
1166
|
+
sys.stdout.write("\033[?1049h\033[H")
|
|
1167
|
+
print("This is your scrubscript recovery code. It is shown this once and kept nowhere on this machine:\n")
|
|
1168
|
+
print(f" {secret}\n")
|
|
1169
|
+
print("Save it now, in a password manager. It is the only way to open a backup: --restore asks for it.\n"
|
|
1170
|
+
"Never paste it into a Claude Code session, where it would be written to the transcript.\n"
|
|
1171
|
+
"This screen is cleared when you press Enter.")
|
|
1172
|
+
try:
|
|
1173
|
+
input("\nPress Enter once the code is saved. ")
|
|
1174
|
+
finally:
|
|
1175
|
+
sys.stdout.write("\033[?1049l")
|
|
1176
|
+
sys.stdout.flush()
|
|
1177
|
+
# Recorded only now: a setup stopped before Enter leaves no key whose code was not saved.
|
|
1178
|
+
again = RECIPIENTS.is_file()
|
|
1179
|
+
write_choice(RECIPIENTS, "# The public key scrubscript encrypts its backups to. Its secret half is the\n"
|
|
1180
|
+
"# recovery code --setup showed once; it is kept nowhere on this machine.\n" + recipient + "\n")
|
|
1181
|
+
OPTED_OUT.unlink(missing_ok=True)
|
|
1182
|
+
print("Backups are on: every redaction can be undone with the recovery code you saved.")
|
|
1183
|
+
if again:
|
|
1184
|
+
print("Backups made before this keep needing the recovery code you had then; the new one opens "
|
|
1185
|
+
"the backups made from now on.")
|
|
1186
|
+
return catch_up()
|
|
1187
|
+
|
|
1188
|
+
|
|
1189
|
+
def catch_up():
|
|
1190
|
+
"""Scrub the sessions that ended while backups were not set up: a sweep, here and now."""
|
|
1191
|
+
print("Scrubbing the sessions that ended in the meantime...", flush=True)
|
|
1192
|
+
return sweep()
|
|
1193
|
+
|
|
1194
|
+
|
|
1195
|
+
# A backup's first line names its format: older backups held whole lines, and are not read.
|
|
1196
|
+
BACKUP_FORMAT = 2
|
|
1197
|
+
|
|
1198
|
+
|
|
1199
|
+
def common_prefix(a, b):
|
|
1200
|
+
"""The length of the start a and b share, found by comparing halves rather than bytes."""
|
|
1201
|
+
low, high = 0, min(len(a), len(b))
|
|
1202
|
+
while low < high:
|
|
1203
|
+
mid = (low + high + 1) // 2
|
|
1204
|
+
if a[low:mid] == b[low:mid]:
|
|
1205
|
+
low = mid
|
|
1206
|
+
else:
|
|
1207
|
+
high = mid - 1
|
|
1208
|
+
return low
|
|
1209
|
+
|
|
1210
|
+
|
|
1211
|
+
def stretch(was, now, line, occurrence, secrets):
|
|
1212
|
+
"""What puts one redacted line back: where it is, and the stretch of it that differs.
|
|
1213
|
+
|
|
1214
|
+
The line is found by the SHA-256 of its redacted form and which occurrence of that
|
|
1215
|
+
text in the file it is. Only the bytes between the first and the last that differ
|
|
1216
|
+
are kept, so a long line costs what its secrets cost and two distant secrets on it
|
|
1217
|
+
keep the text between them. The secrets found there are kept by rule and value, for
|
|
1218
|
+
the choice of which restored values to keep.
|
|
1219
|
+
"""
|
|
1220
|
+
start = common_prefix(was, now)
|
|
1221
|
+
tail = common_prefix(was[start:][::-1], now[start:][::-1])
|
|
1222
|
+
return {"line": line, "occurrence": occurrence, "start": start,
|
|
1223
|
+
"end": len(now) - tail, "was": base64.b64encode(was[start:len(was) - tail]).decode(),
|
|
1224
|
+
"secrets": [{"rule": rule, "value": base64.b64encode(value).decode()} for rule, value in secrets]}
|
|
1225
|
+
|
|
1226
|
+
|
|
1227
|
+
def keep_changes(path, changes):
|
|
1228
|
+
"""Encrypt what puts each changed line back, before the rewrite; returns the backup."""
|
|
1229
|
+
return seal(path, changes)
|
|
1230
|
+
|
|
1231
|
+
|
|
1232
|
+
# The middle of a live backup's name, and its format: each record names one marker.
|
|
1233
|
+
LIVE, LIVE_FORMAT = "live", 3
|
|
1234
|
+
|
|
1235
|
+
|
|
1236
|
+
def seal(path, changes, kind=None):
|
|
1237
|
+
"""Encrypt these records, filed with one file; returns the backup.
|
|
1238
|
+
|
|
1239
|
+
The backup is encrypted to the public key in the recipients file, so this machine
|
|
1240
|
+
can write it and only the holder of the secret key can read it. The records reach
|
|
1241
|
+
age on its standard input: no readable copy of them touches the disk. A sidecar
|
|
1242
|
+
beside the backups names the file, so the sweep can tell when it is gone without
|
|
1243
|
+
opening one, and removes the file's backups of either kind with it.
|
|
1244
|
+
"""
|
|
1245
|
+
recipient = backup_target()
|
|
1246
|
+
binary = age()
|
|
1247
|
+
if not binary:
|
|
1248
|
+
raise OSError("age is not installed, and it encrypts the backup")
|
|
1249
|
+
if not recipient:
|
|
1250
|
+
raise OSError("backups are not set up")
|
|
1251
|
+
folder = backup_folder()
|
|
1252
|
+
os.makedirs(folder, mode=0o700, exist_ok=True)
|
|
1253
|
+
name = path_key(path)
|
|
1254
|
+
backup = folder / f"{name}.{kind + '.' if kind else ''}{time.time_ns()}.age"
|
|
1255
|
+
records = [{"path": str(path.resolve()), "format": LIVE_FORMAT if kind == LIVE else BACKUP_FORMAT,
|
|
1256
|
+
**({"kind": kind} if kind else {})}] + changes
|
|
1257
|
+
fd = os.open(backup, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
|
|
1258
|
+
with os.fdopen(fd, "wb") as dst:
|
|
1259
|
+
run = subprocess.run([binary, "-R", recipient], input="".join(json.dumps(r) + "\n" for r in records).encode(),
|
|
1260
|
+
stdout=dst, stderr=subprocess.PIPE)
|
|
1261
|
+
if run.returncode != 0:
|
|
1262
|
+
backup.unlink()
|
|
1263
|
+
raise OSError(f"age: {run.stderr.decode(errors='replace').strip()}")
|
|
1264
|
+
sidecar = folder / f"{name}.path"
|
|
1265
|
+
try:
|
|
1266
|
+
with os.fdopen(os.open(sidecar, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600), "w") as named:
|
|
1267
|
+
named.write(str(path.resolve()) + "\n")
|
|
1268
|
+
except FileExistsError:
|
|
1269
|
+
pass
|
|
1270
|
+
return backup
|
|
1271
|
+
|
|
1272
|
+
|
|
1273
|
+
# Backups made before sidecars name nothing, cannot be read, and expired after this long.
|
|
1274
|
+
OLD_BACKUP_SECONDS = 14 * 86400
|
|
1275
|
+
|
|
1276
|
+
|
|
1277
|
+
# How long a live backup waits for its transcript to appear. The file is made seconds
|
|
1278
|
+
# after a session's first record; an hour also covers a clock step or a slow first turn.
|
|
1279
|
+
LIVE_GRACE_SECONDS = 3600
|
|
1280
|
+
|
|
1281
|
+
|
|
1282
|
+
def prune_backups():
|
|
1283
|
+
"""Remove the backups of each file that is gone: they can put nothing back.
|
|
1284
|
+
|
|
1285
|
+
A live backup is filed before Claude Code has written its transcript, so one younger
|
|
1286
|
+
than LIVE_GRACE_SECONDS stays, with its sidecar, while the file is missing. A backup
|
|
1287
|
+
in the older format has no sidecar and is not read any more, so it is removed once
|
|
1288
|
+
it is as old as that format kept a backup.
|
|
1289
|
+
"""
|
|
1290
|
+
folder, now = backup_folder(), time.time()
|
|
1291
|
+
for sidecar in folder.glob("*.path"):
|
|
1292
|
+
try:
|
|
1293
|
+
if Path(sidecar.read_text().strip()).exists():
|
|
1294
|
+
continue
|
|
1295
|
+
except OSError:
|
|
1296
|
+
continue
|
|
1297
|
+
waiting = False
|
|
1298
|
+
for backup in folder.glob(f"{sidecar.stem}.*"):
|
|
1299
|
+
if backup == sidecar:
|
|
1300
|
+
continue
|
|
1301
|
+
try:
|
|
1302
|
+
if backup.name.startswith(f"{sidecar.stem}.{LIVE}.") and backup.suffix == ".age" \
|
|
1303
|
+
and now - backup.stat().st_mtime < LIVE_GRACE_SECONDS:
|
|
1304
|
+
waiting = True
|
|
1305
|
+
continue
|
|
1306
|
+
except OSError:
|
|
1307
|
+
continue
|
|
1308
|
+
backup.unlink(missing_ok=True)
|
|
1309
|
+
if not waiting:
|
|
1310
|
+
sidecar.unlink(missing_ok=True)
|
|
1311
|
+
for backup in folder.glob("*.age"):
|
|
1312
|
+
try:
|
|
1313
|
+
if not (folder / f"{backup.name.split('.')[0]}.path").exists() \
|
|
1314
|
+
and now - backup.stat().st_mtime > OLD_BACKUP_SECONDS:
|
|
1315
|
+
backup.unlink()
|
|
1316
|
+
except OSError:
|
|
1317
|
+
pass
|
|
1318
|
+
|
|
1319
|
+
|
|
1320
|
+
def put_back(path, records):
|
|
1321
|
+
"""Put each redacted stretch back where its line is now; (a one-line report, the records put back).
|
|
1322
|
+
|
|
1323
|
+
A line is found by the digest of what it holds now and which occurrence of that
|
|
1324
|
+
text it is, not by its number, so lines added since the redaction stay as they
|
|
1325
|
+
are. The file is replaced the way a scrub replaces it: not if it changed meanwhile,
|
|
1326
|
+
and the prompt history only under its lock.
|
|
1327
|
+
"""
|
|
1328
|
+
wanted = defaultdict(dict)
|
|
1329
|
+
for record in records:
|
|
1330
|
+
wanted[record["line"]][record["occurrence"]] = record
|
|
1331
|
+
before, st, lock, restored = stamp(path), path.stat(), None, []
|
|
1332
|
+
seen = Counter()
|
|
1333
|
+
out = tempfile.NamedTemporaryFile(dir=path.parent, prefix=f".{path.name}.", delete=False)
|
|
1334
|
+
try:
|
|
1335
|
+
with out, open(path, "rb") as src:
|
|
1336
|
+
for line in src:
|
|
1337
|
+
digest = hashlib.sha256(line).hexdigest()
|
|
1338
|
+
# Only the texts a record names are counted: no other line's occurrence matters.
|
|
1339
|
+
bucket = wanted.get(digest)
|
|
1340
|
+
record = bucket.pop(seen[digest], None) if bucket is not None else None
|
|
1341
|
+
if bucket is not None:
|
|
1342
|
+
seen[digest] += 1
|
|
1343
|
+
if record:
|
|
1344
|
+
line = line[:record["start"]] + base64.b64decode(record["was"]) + line[record["end"]:]
|
|
1345
|
+
restored.append(record)
|
|
1346
|
+
out.write(line)
|
|
1347
|
+
if restored and path.resolve() == HISTORY.resolve():
|
|
1348
|
+
lock = take_lock(path)
|
|
1349
|
+
if not lock:
|
|
1350
|
+
return f"SKIP {path}: Claude Code holds its lock", []
|
|
1351
|
+
if not restored:
|
|
1352
|
+
return f"SKIP {path}: none of the lines this backup redacted are there", []
|
|
1353
|
+
if stamp(path) != before:
|
|
1354
|
+
return f"SKIP {path}: changed while restoring", []
|
|
1355
|
+
os.chmod(out.name, st.st_mode & 0o7777)
|
|
1356
|
+
os.replace(out.name, path)
|
|
1357
|
+
os.utime(path, ns=(st.st_atime_ns, st.st_mtime_ns))
|
|
1358
|
+
finally:
|
|
1359
|
+
if os.path.exists(out.name):
|
|
1360
|
+
os.unlink(out.name)
|
|
1361
|
+
if lock:
|
|
1362
|
+
os.rmdir(lock)
|
|
1363
|
+
missing = len(records) - len(restored)
|
|
1364
|
+
return (f"restored {len(restored)} line(s) in {path}" + (f"; {missing} no longer there" if missing else ""),
|
|
1365
|
+
restored)
|
|
1366
|
+
|
|
1367
|
+
|
|
1368
|
+
def session_files(transcript):
|
|
1369
|
+
"""(a transcript and every file under its session's folder, the folders that could not be listed)."""
|
|
1370
|
+
found, unread = [], []
|
|
1371
|
+
|
|
1372
|
+
def note(error):
|
|
1373
|
+
# A session with no folder of its own is the usual case.
|
|
1374
|
+
if not isinstance(error, FileNotFoundError):
|
|
1375
|
+
unread.append(error.filename)
|
|
1376
|
+
|
|
1377
|
+
for root, _, names in os.walk(transcript.with_suffix(""), onerror=note):
|
|
1378
|
+
found += [path for name in names if (path := Path(root) / name).is_file()]
|
|
1379
|
+
return [transcript] + sorted(found), unread
|
|
1380
|
+
|
|
1381
|
+
|
|
1382
|
+
def put_back_live(transcript, records, restored):
|
|
1383
|
+
"""Replace each record's own marker with what stood there; (a report, the ids put back, stopped, clashing ids).
|
|
1384
|
+
|
|
1385
|
+
Markers are looked for in the transcript and in each file under its session's
|
|
1386
|
+
folder, and every place one stands is put back, since one piece can be stored more
|
|
1387
|
+
than once. Two records with one id and different values are refused. In a JSONL file
|
|
1388
|
+
plain text is escaped, a tool's record stands as it was filtered, and a line that
|
|
1389
|
+
would not parse keeps its markers. A file is replaced the way a scrub replaces one:
|
|
1390
|
+
not if it changed meanwhile. Each file is added to restored as soon as it holds a
|
|
1391
|
+
value again, because a restore keeps its modification time and only that queue
|
|
1392
|
+
leads a sweep to it. A restore that stops at a file keeps what it already put back.
|
|
1393
|
+
"""
|
|
1394
|
+
values, clashing = {}, set()
|
|
1395
|
+
for record in records:
|
|
1396
|
+
value = (record["was"], bool(record.get("json")))
|
|
1397
|
+
if values.setdefault(record["id"], value) != value:
|
|
1398
|
+
clashing.add(record["id"])
|
|
1399
|
+
placed, changed = set(), []
|
|
1400
|
+
files, unread = session_files(transcript)
|
|
1401
|
+
for path in files:
|
|
1402
|
+
try:
|
|
1403
|
+
before = stamp(path)
|
|
1404
|
+
data = path.read_bytes()
|
|
1405
|
+
except FileNotFoundError:
|
|
1406
|
+
continue
|
|
1407
|
+
except OSError:
|
|
1408
|
+
unread.append(path)
|
|
1409
|
+
continue
|
|
1410
|
+
if b"[redacted:" not in data:
|
|
1411
|
+
continue
|
|
1412
|
+
is_jsonl, found = path.suffix == ".jsonl", set()
|
|
1413
|
+
|
|
1414
|
+
def fill(match, into):
|
|
1415
|
+
mark = match.group(1).decode()
|
|
1416
|
+
if mark not in values or mark in clashing:
|
|
1417
|
+
return match.group(0)
|
|
1418
|
+
into.add(mark)
|
|
1419
|
+
was, is_json = values[mark]
|
|
1420
|
+
return (escape(was) if is_jsonl and not is_json else was).encode(errors="surrogateescape")
|
|
1421
|
+
|
|
1422
|
+
if is_jsonl:
|
|
1423
|
+
lines = data.split(b"\n")
|
|
1424
|
+
for n, line in enumerate(lines):
|
|
1425
|
+
here = set()
|
|
1426
|
+
filled = MARKER.sub(lambda match: fill(match, here), line)
|
|
1427
|
+
if here and parses(filled):
|
|
1428
|
+
lines[n] = filled
|
|
1429
|
+
found |= here
|
|
1430
|
+
new = b"\n".join(lines)
|
|
1431
|
+
else:
|
|
1432
|
+
new = MARKER.sub(lambda match: fill(match, found), data)
|
|
1433
|
+
if new == data:
|
|
1434
|
+
continue
|
|
1435
|
+
why = "it changed while restoring" if stamp(path) != before else None
|
|
1436
|
+
if not why:
|
|
1437
|
+
partial = None
|
|
1438
|
+
try:
|
|
1439
|
+
st = path.stat()
|
|
1440
|
+
partial = tempfile.NamedTemporaryFile(dir=path.parent, prefix=f".{path.name}.", delete=False)
|
|
1441
|
+
with partial:
|
|
1442
|
+
partial.write(new)
|
|
1443
|
+
os.chmod(partial.name, st.st_mode & 0o7777)
|
|
1444
|
+
os.replace(partial.name, path)
|
|
1445
|
+
restored.add(path)
|
|
1446
|
+
changed.append(path)
|
|
1447
|
+
placed |= found
|
|
1448
|
+
os.utime(path, ns=(st.st_atime_ns, st.st_mtime_ns))
|
|
1449
|
+
except OSError as error:
|
|
1450
|
+
why = error.strerror or str(error)
|
|
1451
|
+
finally:
|
|
1452
|
+
# It holds the restored values in clear text, where no scrub looks.
|
|
1453
|
+
if partial and os.path.exists(partial.name):
|
|
1454
|
+
os.unlink(partial.name)
|
|
1455
|
+
if why:
|
|
1456
|
+
return (f"SKIP {transcript}: stopped at {path}: {why}. The {len(changed)} file(s) already put back are "
|
|
1457
|
+
"redacted again by the next sweep, and the backups are kept", placed, True, clashing)
|
|
1458
|
+
if unread:
|
|
1459
|
+
# It may hold a marker of a backup whose other places all came back.
|
|
1460
|
+
names = ", ".join(str(path) for path in unread)
|
|
1461
|
+
return (f"SKIP {transcript}: could not read {names}. The {len(changed)} file(s) already put back are "
|
|
1462
|
+
"redacted again by the next sweep, and the backups are kept", placed, True, clashing)
|
|
1463
|
+
if not placed:
|
|
1464
|
+
return f"SKIP {transcript}: no marker of these backups is in its files", placed, False, clashing
|
|
1465
|
+
missing = len(values) - len(placed) - len(clashing)
|
|
1466
|
+
return (f"restored {len(placed)} live redaction(s) in {len(changed)} file(s) of {transcript}"
|
|
1467
|
+
+ (f"; {missing} not in any file" if missing else ""), placed, False, clashing)
|
|
1468
|
+
|
|
1469
|
+
|
|
1470
|
+
def restore_live(path, binary, opener, code, values, restored):
|
|
1471
|
+
"""Put back the live backups of one transcript this key opens; True when something stayed redacted.
|
|
1472
|
+
|
|
1473
|
+
A backup the key does not open keeps its markers, and no other backup depends on
|
|
1474
|
+
it. One is removed once every marker it holds has been put back.
|
|
1475
|
+
"""
|
|
1476
|
+
opened, closed, older = [], 0, 0
|
|
1477
|
+
for backup in live_backups_of(path):
|
|
1478
|
+
run = subprocess.run([binary, "--decrypt", *opener, str(backup)], input=code,
|
|
1479
|
+
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
|
|
1480
|
+
lines = run.stdout.splitlines() if run.returncode == 0 else []
|
|
1481
|
+
if not lines:
|
|
1482
|
+
closed += 1
|
|
1483
|
+
continue
|
|
1484
|
+
if json.loads(lines[0]).get("format") != LIVE_FORMAT:
|
|
1485
|
+
older += 1
|
|
1486
|
+
continue
|
|
1487
|
+
opened.append((backup, [json.loads(line) for line in lines[1:]]))
|
|
1488
|
+
if not opened and not closed and not older:
|
|
1489
|
+
return False
|
|
1490
|
+
failed = closed > 0 or older > 0
|
|
1491
|
+
if opened:
|
|
1492
|
+
report, placed, stopped, clashing = put_back_live(path, [r for _, records in opened for r in records], restored)
|
|
1493
|
+
print(report)
|
|
1494
|
+
for backup, records in opened:
|
|
1495
|
+
for record in records:
|
|
1496
|
+
if record["id"] in placed:
|
|
1497
|
+
for secret in record.get("secrets", []):
|
|
1498
|
+
values.setdefault(base64.b64decode(secret["value"]), secret["rule"])
|
|
1499
|
+
if not stopped and all(record["id"] in placed for record in records):
|
|
1500
|
+
backup.unlink()
|
|
1501
|
+
if clashing:
|
|
1502
|
+
print(f" {len(clashing)} marker(s) share an id with a different value, so none of them was put back; "
|
|
1503
|
+
"their backups are kept")
|
|
1504
|
+
everything = {record["id"] for _, records in opened for record in records}
|
|
1505
|
+
failed = failed or stopped or bool(everything - placed)
|
|
1506
|
+
if closed:
|
|
1507
|
+
print(f" {closed} live backup(s) cannot be opened with this key, and their markers stay")
|
|
1508
|
+
if older:
|
|
1509
|
+
print(f" {older} live backup(s) were written by an earlier development version, which this version does "
|
|
1510
|
+
"not read, so what they hold stays redacted")
|
|
1511
|
+
return failed
|
|
1512
|
+
|
|
1513
|
+
|
|
1514
|
+
def escape(text):
|
|
1515
|
+
"""Text as it stands inside a JSON string in a transcript line."""
|
|
1516
|
+
return json.dumps(text, ensure_ascii=False)[1:-1]
|
|
1517
|
+
|
|
1518
|
+
|
|
1519
|
+
def restore(paths, identity):
|
|
1520
|
+
"""Undo the redactions of these files from their encrypted backups, newest first; 0 only when all came back.
|
|
1521
|
+
|
|
1522
|
+
Without an identity file the recovery code is asked for at the terminal, and goes
|
|
1523
|
+
to age on its standard input: it is never written to a file. With one, age reads
|
|
1524
|
+
the secret key from it, and asks for its passphrase when it has one. A backup that
|
|
1525
|
+
was put back is removed; one that could not be stops the older ones of that file,
|
|
1526
|
+
which hold the lines as they were before it.
|
|
1527
|
+
"""
|
|
1528
|
+
binary = age()
|
|
1529
|
+
if not binary:
|
|
1530
|
+
sys.exit(f"scrubscript: age is not installed, and it opens the backups. Install it ({install_hint('age')}).")
|
|
1531
|
+
live, failed, todo, values = live_sessions(), False, [], {}
|
|
1532
|
+
for path in paths:
|
|
1533
|
+
backups = backups_of(path) + live_backups_of(path)
|
|
1534
|
+
if not path.is_file() or not backups:
|
|
1535
|
+
print(f"SKIP {path}: no backup of it in {backup_folder()}, so nothing to put back")
|
|
1536
|
+
failed = True
|
|
1537
|
+
elif live & sessions_of(path):
|
|
1538
|
+
print(f"SKIP {path}: a process still names its session")
|
|
1539
|
+
failed = True
|
|
1540
|
+
else:
|
|
1541
|
+
todo.append((path, backups))
|
|
1542
|
+
if not todo:
|
|
1543
|
+
return 1
|
|
1544
|
+
if identity:
|
|
1545
|
+
opener, code = ["-i", identity], None
|
|
1546
|
+
else:
|
|
1547
|
+
refuse_outside_terminal("--restore without --identity", "the recovery code it asks for would otherwise "
|
|
1548
|
+
"be written to a session's transcript and sent to the model",
|
|
1549
|
+
[str(path) for path, _ in todo])
|
|
1550
|
+
opener, code = ["-i", "-"], getpass.getpass("Recovery code: ").strip().encode() + b"\n"
|
|
1551
|
+
restored = set()
|
|
1552
|
+
for path, _ in todo:
|
|
1553
|
+
mark_restoring(path)
|
|
1554
|
+
try:
|
|
1555
|
+
failed = put_back_all(todo, binary, opener, code, identity, values, restored) or failed
|
|
1556
|
+
choose_kept(values)
|
|
1557
|
+
finally:
|
|
1558
|
+
# Until the keep choice is made, or given up, every scrub leaves these files
|
|
1559
|
+
# alone, and only then are they queued for the next sweep: a scrub meanwhile
|
|
1560
|
+
# would redact again a value the user was about to keep.
|
|
1561
|
+
for path in sorted(restored):
|
|
1562
|
+
queue_restored(path)
|
|
1563
|
+
for path, _ in todo:
|
|
1564
|
+
(RESTORING / path_key(path)).unlink(missing_ok=True)
|
|
1565
|
+
return 1 if failed else 0
|
|
1566
|
+
|
|
1567
|
+
|
|
1568
|
+
def put_back_all(todo, binary, opener, code, identity, values, restored):
|
|
1569
|
+
"""Put back each file's backups, the scrub's newest first and then live redaction's; True when one could not be.
|
|
1570
|
+
|
|
1571
|
+
A scrub's backup finds its line by what the line holds, so one that cannot be put
|
|
1572
|
+
back stops what would change those lines: the older ones, and the live markers. The
|
|
1573
|
+
values put back are gathered in values, and the files restored in restored.
|
|
1574
|
+
"""
|
|
1575
|
+
failed = False
|
|
1576
|
+
for path, _ in todo:
|
|
1577
|
+
for backup in backups_of(path):
|
|
1578
|
+
opened = subprocess.run([binary, "--decrypt", *opener, str(backup)], input=code,
|
|
1579
|
+
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL if code else None)
|
|
1580
|
+
if opened.returncode != 0:
|
|
1581
|
+
print(f"FAILED {path}: " + (f"age could not open {backup.name} with {identity}" if identity
|
|
1582
|
+
else f"the recovery code does not open {backup.name}"))
|
|
1583
|
+
failed = True
|
|
1584
|
+
break
|
|
1585
|
+
lines = opened.stdout.splitlines()
|
|
1586
|
+
header = json.loads(lines[0]) if lines else {}
|
|
1587
|
+
if header.get("format") != BACKUP_FORMAT:
|
|
1588
|
+
print(f"SKIP {path}: {backup.name} was made by an older scrubscript, and is not read")
|
|
1589
|
+
failed = True
|
|
1590
|
+
break
|
|
1591
|
+
records = [json.loads(line) for line in lines[1:]]
|
|
1592
|
+
report, put = put_back(path, records)
|
|
1593
|
+
print(report)
|
|
1594
|
+
if not report.startswith("restored"):
|
|
1595
|
+
failed = True
|
|
1596
|
+
break
|
|
1597
|
+
if len(put) < len(records):
|
|
1598
|
+
# What could not be placed is kept, encrypted as it was, for as long as
|
|
1599
|
+
# the file exists; no restore reads it again.
|
|
1600
|
+
kept = backup.with_name(backup.name + ".unplaced")
|
|
1601
|
+
os.replace(backup, kept)
|
|
1602
|
+
print(f" kept the backup of the {len(records) - len(put)} stretch(es) not placed, in {kept}")
|
|
1603
|
+
failed = True
|
|
1604
|
+
else:
|
|
1605
|
+
backup.unlink()
|
|
1606
|
+
restored.add(path)
|
|
1607
|
+
for record in put:
|
|
1608
|
+
for secret in record.get("secrets", []):
|
|
1609
|
+
values.setdefault(base64.b64decode(secret["value"]), secret["rule"])
|
|
1610
|
+
else:
|
|
1611
|
+
failed = restore_live(path, binary, opener, code, values, restored) or failed
|
|
1612
|
+
if not any(p.suffix != ".path" for p in backup_folder().glob(f"{path_key(path)}.*")):
|
|
1613
|
+
(backup_folder() / f"{path_key(path)}.path").unlink(missing_ok=True)
|
|
1614
|
+
return failed
|
|
1615
|
+
|
|
1616
|
+
|
|
1617
|
+
def mark_restoring(path):
|
|
1618
|
+
RESTORING.mkdir(parents=True, exist_ok=True)
|
|
1619
|
+
(RESTORING / path_key(path)).write_text(str(os.getpid()))
|
|
1620
|
+
|
|
1621
|
+
|
|
1622
|
+
def restoring(path):
|
|
1623
|
+
"""Whether a restore that is still running is working on this file.
|
|
1624
|
+
|
|
1625
|
+
A mark left by a restore that was killed names a process that is gone, and counts
|
|
1626
|
+
for nothing.
|
|
1627
|
+
"""
|
|
1628
|
+
try:
|
|
1629
|
+
pid = int((RESTORING / path_key(path)).read_text())
|
|
1630
|
+
except (OSError, ValueError):
|
|
1631
|
+
return False
|
|
1632
|
+
return pid != os.getpid() and not gone(pid)
|
|
1633
|
+
|
|
1634
|
+
|
|
1635
|
+
def queue_restored(path):
|
|
1636
|
+
"""Name a restored file for the next sweep, which redacts again what was not kept."""
|
|
1637
|
+
RESTORED.mkdir(parents=True, exist_ok=True)
|
|
1638
|
+
(RESTORED / path_key(path)).write_text(str(path.resolve()) + "\n")
|
|
1639
|
+
|
|
1640
|
+
|
|
1641
|
+
def choose_kept(values):
|
|
1642
|
+
"""Ask which restored values to keep; each kept one is never redacted again.
|
|
1643
|
+
|
|
1644
|
+
A value is shown by its rule and first four characters. Nothing is kept unless it
|
|
1645
|
+
is picked, and without a terminal nothing is asked: the next sweep redacts every
|
|
1646
|
+
restored value again, with a new backup.
|
|
1647
|
+
"""
|
|
1648
|
+
if not values:
|
|
1649
|
+
return
|
|
1650
|
+
listed = sorted(values.items(), key=lambda item: (item[1], item[0]))
|
|
1651
|
+
if not at_own_terminal():
|
|
1652
|
+
print(f"{len(listed)} restored value(s) are redacted again at the next sweep. To keep one, "
|
|
1653
|
+
"restore at a terminal and pick it.")
|
|
1654
|
+
return
|
|
1655
|
+
print("\nThe next sweep redacts these restored values again, unless you keep them:")
|
|
1656
|
+
for n, (value, rule) in enumerate(listed, 1):
|
|
1657
|
+
print(f" {n:>3} {rule:<24} {value[:4].decode(errors='replace')}...")
|
|
1658
|
+
answer = input("Keep which? Their numbers, separated by spaces; Enter keeps none: ").split()
|
|
1659
|
+
picked = sorted({int(a) for a in answer if a.isdigit() and 1 <= int(a) <= len(listed)})
|
|
1660
|
+
if not picked:
|
|
1661
|
+
print("None kept.")
|
|
1662
|
+
return
|
|
1663
|
+
known = kept_digests()
|
|
1664
|
+
KEPT.parent.mkdir(parents=True, exist_ok=True)
|
|
1665
|
+
with os.fdopen(os.open(KEPT, os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o600), "a") as kept:
|
|
1666
|
+
if os.fstat(kept.fileno()).st_size == 0:
|
|
1667
|
+
kept.write("# Values scrubscript keeps, picked at a restore. Remove a line to have the value redacted again.\n")
|
|
1668
|
+
for n in picked:
|
|
1669
|
+
value, rule = listed[n - 1]
|
|
1670
|
+
if digest_of(value) not in known:
|
|
1671
|
+
kept.write(json.dumps({"rule": rule, "starts": value[:4].decode(errors="replace"),
|
|
1672
|
+
"sha256": digest_of(value)}) + "\n")
|
|
1673
|
+
print(f"Kept {len(picked)} value(s), in {KEPT}.")
|
|
1674
|
+
|
|
1675
|
+
|
|
1676
|
+
def scrub_file(path, findings, apply, scanned_stamp, appended_to=False):
|
|
1677
|
+
"""Redact one file, streaming it line by line; returns a one-line report.
|
|
1678
|
+
|
|
1679
|
+
appended_to marks the prompt history, which live sessions add lines to at any
|
|
1680
|
+
moment. A line added since the scan is copied as it is, where another file would
|
|
1681
|
+
be refused for having changed. The redacted copy replaces the history under Claude
|
|
1682
|
+
Code's own lock on it, and only if no line was added while the copy was made.
|
|
1683
|
+
"""
|
|
1684
|
+
rules = Counter(f["RuleID"] for f in unkept(findings))
|
|
1685
|
+
candidates = {f["Secret"].encode() for f in unkept(findings)}
|
|
1686
|
+
too_short = sum(1 for s in candidates if len(s) < MIN_SECRET_LEN)
|
|
1687
|
+
summary = ", ".join(f"{n} {rule}" for rule, n in rules.most_common())
|
|
1688
|
+
if apply and restoring(path):
|
|
1689
|
+
return f"SKIP {path}: a restore of it is in progress ({summary})"
|
|
1690
|
+
if apply and backup_target() is None:
|
|
1691
|
+
return f"SKIP {path}: backups are not set up, and no scrub runs without one ({summary})"
|
|
1692
|
+
if appended_to:
|
|
1693
|
+
scanned_stamp = stamp(path)
|
|
1694
|
+
elif stamp(path) != scanned_stamp:
|
|
1695
|
+
return f"SKIP {path}: changed since the scan ({summary})"
|
|
1696
|
+
|
|
1697
|
+
seen, kept, lock = set(), None, None
|
|
1698
|
+
changes, occurrences = [], Counter()
|
|
1699
|
+
rule_of = {f["Secret"].encode(): f["RuleID"] for f in findings}
|
|
1700
|
+
check_json = json_layout(path)
|
|
1701
|
+
out = tempfile.NamedTemporaryFile(dir=path.parent, prefix=f".{path.name}.", delete=False) if apply else None
|
|
1702
|
+
try:
|
|
1703
|
+
with open(path, "rb") as src:
|
|
1704
|
+
try:
|
|
1705
|
+
for new, held, present in redacted(src, findings, check_json):
|
|
1706
|
+
seen.update(present)
|
|
1707
|
+
if out:
|
|
1708
|
+
out.write(new)
|
|
1709
|
+
digest = hashlib.sha256(new).hexdigest()
|
|
1710
|
+
if new != held:
|
|
1711
|
+
changes.append(stretch(held, new, digest, occurrences[digest],
|
|
1712
|
+
[(rule_of.get(s, "?"), s) for s in present]))
|
|
1713
|
+
occurrences[digest] += 1
|
|
1714
|
+
except Unclean:
|
|
1715
|
+
if out:
|
|
1716
|
+
out.close()
|
|
1717
|
+
os.unlink(out.name)
|
|
1718
|
+
return f"SKIP {path}: a secret could not be redacted cleanly ({summary})"
|
|
1719
|
+
if out:
|
|
1720
|
+
out.close()
|
|
1721
|
+
if seen and appended_to:
|
|
1722
|
+
lock = take_lock(path)
|
|
1723
|
+
if not lock:
|
|
1724
|
+
os.unlink(out.name)
|
|
1725
|
+
return f"SKIP {path}: Claude Code holds its lock ({summary})"
|
|
1726
|
+
if not seen or stamp(path) != scanned_stamp:
|
|
1727
|
+
os.unlink(out.name)
|
|
1728
|
+
if seen:
|
|
1729
|
+
return f"SKIP {path}: changed while redacting ({summary})"
|
|
1730
|
+
else:
|
|
1731
|
+
st = path.stat()
|
|
1732
|
+
try:
|
|
1733
|
+
kept = keep_changes(path, changes)
|
|
1734
|
+
except OSError as error:
|
|
1735
|
+
os.unlink(out.name)
|
|
1736
|
+
return f"SKIP {path}: its original could not be kept ({error.strerror or error})"
|
|
1737
|
+
os.chmod(out.name, st.st_mode & 0o7777)
|
|
1738
|
+
os.replace(out.name, path)
|
|
1739
|
+
os.utime(path, ns=(st.st_atime_ns, st.st_mtime_ns))
|
|
1740
|
+
except BaseException:
|
|
1741
|
+
if out and os.path.exists(out.name):
|
|
1742
|
+
out.close()
|
|
1743
|
+
os.unlink(out.name)
|
|
1744
|
+
raise
|
|
1745
|
+
finally:
|
|
1746
|
+
if lock:
|
|
1747
|
+
os.rmdir(lock)
|
|
1748
|
+
|
|
1749
|
+
notes = []
|
|
1750
|
+
if apply and seen and kept:
|
|
1751
|
+
notes.append(f"original kept in {kept}")
|
|
1752
|
+
if too_short:
|
|
1753
|
+
notes.append(f"{too_short} too short to redact")
|
|
1754
|
+
left = len(candidates) - too_short - len(seen)
|
|
1755
|
+
if left > 0:
|
|
1756
|
+
notes.append(f"{left} found only after decoding, left in place")
|
|
1757
|
+
if TALLY and seen:
|
|
1758
|
+
with open(TALLY, "a") as f:
|
|
1759
|
+
f.writelines(json.dumps({"rule": rule_of.get(v, "?"), "sha256": digest_of(v), "file": str(path)}) + "\n"
|
|
1760
|
+
for v in seen)
|
|
1761
|
+
verb = "redacted" if apply else "would redact"
|
|
1762
|
+
return f"{verb} {len(seen)} secret(s) in {path}: {summary}" + (f"; {'; '.join(notes)}" if notes else "")
|
|
1763
|
+
|
|
1764
|
+
|
|
1765
|
+
def fingerprint():
|
|
1766
|
+
"""What a recorded scrub was run with: a new rule or gitleaks build voids it."""
|
|
1767
|
+
digest = hashlib.sha256(gitleaks_config().encode())
|
|
1768
|
+
with open(need_gitleaks(), "rb") as f:
|
|
1769
|
+
for chunk in iter(lambda: f.read(1 << 20), b""):
|
|
1770
|
+
digest.update(chunk)
|
|
1771
|
+
return digest.hexdigest()
|
|
1772
|
+
|
|
1773
|
+
|
|
1774
|
+
def last_full_scrub():
|
|
1775
|
+
"""(time, pinned session ids) of the last full --apply under these rules."""
|
|
1776
|
+
try:
|
|
1777
|
+
state = json.loads(STATE.read_text())
|
|
1778
|
+
except (OSError, ValueError):
|
|
1779
|
+
return None, set()
|
|
1780
|
+
if state.get("fingerprint") != fingerprint():
|
|
1781
|
+
return None, set()
|
|
1782
|
+
return state["since"], set(state["rescan"])
|
|
1783
|
+
|
|
1784
|
+
|
|
1785
|
+
def newest_by_session():
|
|
1786
|
+
"""Newest mtime among each session's files, from one walk of the tree."""
|
|
1787
|
+
newest = {}
|
|
1788
|
+
for root, _, files in os.walk(PROJECTS):
|
|
1789
|
+
# <project>/<id>.jsonl, or anything under <project>/<id>/.
|
|
1790
|
+
parts = Path(root).relative_to(PROJECTS).parts
|
|
1791
|
+
for name in files:
|
|
1792
|
+
if len(parts) == 1:
|
|
1793
|
+
sid = name.removesuffix(".jsonl") if name.endswith(".jsonl") else None
|
|
1794
|
+
else:
|
|
1795
|
+
sid = parts[1] if len(parts) > 1 else None
|
|
1796
|
+
if sid and SESSION_ID.fullmatch(sid):
|
|
1797
|
+
try:
|
|
1798
|
+
mtime = os.stat(os.path.join(root, name)).st_mtime
|
|
1799
|
+
except OSError:
|
|
1800
|
+
continue
|
|
1801
|
+
newest[sid] = max(newest.get(sid, 0), mtime)
|
|
1802
|
+
return newest
|
|
1803
|
+
|
|
1804
|
+
|
|
1805
|
+
def status():
|
|
1806
|
+
since, pinned = last_full_scrub()
|
|
1807
|
+
if since is None:
|
|
1808
|
+
print("scrubscript: no full scrub under the current rules; the next --all scans "
|
|
1809
|
+
"every session (hours): run scrubscript --all --apply.")
|
|
1810
|
+
return 3
|
|
1811
|
+
ran = json.loads(STATE.read_text())["ran"]
|
|
1812
|
+
newest = newest_by_session()
|
|
1813
|
+
pending = sum(1 for sid in session_ids() if sid in pinned or newest.get(sid, 0) >= since)
|
|
1814
|
+
# Every --all --apply moves the record, incremental runs included.
|
|
1815
|
+
print(f"scrubscript: last --all --apply {ran}; {pending} session(s) to scan since")
|
|
1816
|
+
return 0
|
|
1817
|
+
|
|
1818
|
+
|
|
1819
|
+
def doctor():
|
|
1820
|
+
"""Check what a scrub depends on, one line per check; 1 when one fails."""
|
|
1821
|
+
failed = False
|
|
1822
|
+
|
|
1823
|
+
def report(level, text):
|
|
1824
|
+
nonlocal failed
|
|
1825
|
+
failed |= level == "FAIL"
|
|
1826
|
+
print(f"{level:<5} {text}")
|
|
1827
|
+
|
|
1828
|
+
binary = gitleaks()
|
|
1829
|
+
if not binary:
|
|
1830
|
+
report("FAIL", not_redacting_message(NO_GITLEAKS))
|
|
1831
|
+
elif gitleaks_too_old():
|
|
1832
|
+
report("FAIL", not_redacting_message(OLD_GITLEAKS))
|
|
1833
|
+
else:
|
|
1834
|
+
# Planted at run time, so this file holds no credential-shaped literal.
|
|
1835
|
+
token = "gh" "p_" + hashlib.sha256(os.urandom(16)).hexdigest()[:36]
|
|
1836
|
+
with tempfile.TemporaryDirectory(prefix="scrubscript-doctor-") as workdir:
|
|
1837
|
+
planted = Path(workdir) / "planted" / "t.jsonl"
|
|
1838
|
+
planted.parent.mkdir()
|
|
1839
|
+
# Apart from the planted file: scan() has gitleaks ignore its work folder.
|
|
1840
|
+
(Path(workdir) / "work").mkdir()
|
|
1841
|
+
planted.write_text(json.dumps({"content": f"GITHUB_TOKEN={token}"}) + "\n")
|
|
1842
|
+
try:
|
|
1843
|
+
found = scan([planted.parent], Path(workdir) / "work")
|
|
1844
|
+
except SystemExit as e:
|
|
1845
|
+
report("FAIL", str(e.code).strip())
|
|
1846
|
+
else:
|
|
1847
|
+
if any(f.get("RuleID") == "github-pat" for f in found):
|
|
1848
|
+
report("ok", f"gitleaks at {binary} finds a planted GitHub token")
|
|
1849
|
+
else:
|
|
1850
|
+
report("FAIL", f"gitleaks at {binary} missed a planted GitHub token: "
|
|
1851
|
+
"check the allowlists in your rules file")
|
|
1852
|
+
named = os.environ.get("SCRUBSCRIPT_RULES")
|
|
1853
|
+
rules = Path(named) if named else DEFAULT_RULES
|
|
1854
|
+
report("ok", f"your rules: {rules}" if rules.is_file()
|
|
1855
|
+
else f"no rules file at {rules}; the stock rules apply")
|
|
1856
|
+
|
|
1857
|
+
# gitleaks has its own line above.
|
|
1858
|
+
reason = backup_problem()
|
|
1859
|
+
if reason:
|
|
1860
|
+
report("FAIL", not_redacting_message(reason))
|
|
1861
|
+
else:
|
|
1862
|
+
report("ok", f"each redaction is kept encrypted to {backup_target()}, in {backup_folder()}")
|
|
1863
|
+
|
|
1864
|
+
if PROJECTS.is_dir():
|
|
1865
|
+
report("ok", f"{sum(1 for _ in session_ids())} session(s) under {PROJECTS}")
|
|
1866
|
+
else:
|
|
1867
|
+
report("WARN", f"no transcripts folder at {PROJECTS}: set SCRUBSCRIPT_PROJECTS "
|
|
1868
|
+
"or CLAUDE_CONFIG_DIR if Claude Code keeps them elsewhere")
|
|
1869
|
+
|
|
1870
|
+
try:
|
|
1871
|
+
STATE.parent.mkdir(parents=True, exist_ok=True)
|
|
1872
|
+
with tempfile.TemporaryFile(dir=STATE.parent):
|
|
1873
|
+
pass
|
|
1874
|
+
report("ok", f"state and hook log in {STATE.parent}")
|
|
1875
|
+
except OSError as e:
|
|
1876
|
+
report("FAIL", f"cannot write the state folder {STATE.parent}: {e}")
|
|
1877
|
+
|
|
1878
|
+
if systemd_user():
|
|
1879
|
+
report("ok", f"scrubs run as systemd user units, capped at {MEMORY_MAX}")
|
|
1880
|
+
else:
|
|
1881
|
+
report("ok", "scrubs run as detached processes, with no memory cap (no systemd user manager)")
|
|
1882
|
+
|
|
1883
|
+
try:
|
|
1884
|
+
ends = [line for line in HOOK_LOG.read_text().splitlines() if " SessionEnd " in line]
|
|
1885
|
+
except OSError:
|
|
1886
|
+
ends = []
|
|
1887
|
+
if ends:
|
|
1888
|
+
report("ok", f"last SessionEnd hook: {ends[-1].split(' ', 1)[0]}")
|
|
1889
|
+
else:
|
|
1890
|
+
report("WARN", "no SessionEnd hook has run yet: end a session, and if this stays, "
|
|
1891
|
+
"install the plugin or register the hooks")
|
|
1892
|
+
return 1 if failed else 0
|
|
1893
|
+
|
|
1894
|
+
def systemd_user():
|
|
1895
|
+
"""Whether a systemd user manager is here to run a command in a scope or on a timer."""
|
|
1896
|
+
if not shutil.which("systemd-run"):
|
|
1897
|
+
return False
|
|
1898
|
+
probe = subprocess.run(["systemd-run", "--user", "--scope", "--quiet", "--", "true"],
|
|
1899
|
+
capture_output=True)
|
|
1900
|
+
return probe.returncode == 0
|
|
1901
|
+
|
|
1902
|
+
|
|
1903
|
+
def detach(name, cmd, env, delay):
|
|
1904
|
+
"""Run cmd after the delay in a process of its own session; why not, or None.
|
|
1905
|
+
|
|
1906
|
+
The hook that asks for this is gone long before the delay ends, and its process
|
|
1907
|
+
group may be killed with it, so the wait happens in a grandchild that has left the
|
|
1908
|
+
group. A lock file under that name holds the grandchild's pid until the delay is
|
|
1909
|
+
over, so a second request for the same name starts nothing.
|
|
1910
|
+
"""
|
|
1911
|
+
pending = STATE.parent / "pending"
|
|
1912
|
+
pending.mkdir(parents=True, exist_ok=True)
|
|
1913
|
+
lock = pending / name
|
|
1914
|
+
for _ in range(2):
|
|
1915
|
+
try:
|
|
1916
|
+
fd = os.open(lock, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
|
|
1917
|
+
break
|
|
1918
|
+
except FileExistsError:
|
|
1919
|
+
try:
|
|
1920
|
+
os.kill(int(lock.read_text()), 0)
|
|
1921
|
+
return "one is already pending"
|
|
1922
|
+
except (OSError, ValueError):
|
|
1923
|
+
lock.unlink(missing_ok=True) # left by a process that is gone
|
|
1924
|
+
else:
|
|
1925
|
+
return "could not take the lock"
|
|
1926
|
+
ready_r, ready_w = os.pipe()
|
|
1927
|
+
child = os.fork()
|
|
1928
|
+
if child:
|
|
1929
|
+
os.close(fd)
|
|
1930
|
+
os.close(ready_w)
|
|
1931
|
+
os.read(ready_r, 1) # until the grandchild has written its pid
|
|
1932
|
+
os.close(ready_r)
|
|
1933
|
+
os.waitpid(child, 0)
|
|
1934
|
+
return None
|
|
1935
|
+
try:
|
|
1936
|
+
os.setsid()
|
|
1937
|
+
if os.fork():
|
|
1938
|
+
os._exit(0)
|
|
1939
|
+
os.write(fd, str(os.getpid()).encode())
|
|
1940
|
+
os.close(fd)
|
|
1941
|
+
os.close(ready_r)
|
|
1942
|
+
os.close(ready_w)
|
|
1943
|
+
null = os.open(os.devnull, os.O_RDONLY)
|
|
1944
|
+
log = os.open(HOOK_LOG, os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o600)
|
|
1945
|
+
os.dup2(null, 0)
|
|
1946
|
+
os.dup2(log, 1)
|
|
1947
|
+
os.dup2(log, 2)
|
|
1948
|
+
time.sleep(delay)
|
|
1949
|
+
lock.unlink(missing_ok=True)
|
|
1950
|
+
os.execve(cmd[0], cmd, env)
|
|
1951
|
+
finally:
|
|
1952
|
+
os._exit(1)
|
|
1953
|
+
|
|
1954
|
+
|
|
1955
|
+
def start_apart(name, args, projects, delay):
|
|
1956
|
+
"""Run this script with args outside the hook's process; (started, a note on how).
|
|
1957
|
+
|
|
1958
|
+
A hook has about 1.5 s and may be killed with its process group, so the work runs
|
|
1959
|
+
as a memory-capped systemd user unit where there is a user manager and as a
|
|
1960
|
+
detached process elsewhere. One unit or process per name at a time.
|
|
1961
|
+
"""
|
|
1962
|
+
cmd = [sys.executable, os.path.abspath(__file__), *args]
|
|
1963
|
+
# The work looks in the projects folder that holds the transcript, so a session
|
|
1964
|
+
# saved under another config folder is found too.
|
|
1965
|
+
# The registry is named too: a systemd unit does not get this hook's CLAUDE_CONFIG_DIR.
|
|
1966
|
+
env = dict(os.environ, SCRUBSCRIPT_PROJECTS=str(projects), SCRUBSCRIPT_REGISTRY=str(REGISTRY))
|
|
1967
|
+
if not systemd_user():
|
|
1968
|
+
why = detach(name, cmd, env, delay)
|
|
1969
|
+
return why is None, why or "detached process"
|
|
1970
|
+
# --setenv=HOME: a unit gets the user manager's HOME, which is not this one when a
|
|
1971
|
+
# second Claude Code install runs under a HOME of its own.
|
|
1972
|
+
# The XDG folders too: the backup key and the rules are found through them.
|
|
1973
|
+
settings = ["--setenv=HOME"] + [f"--setenv={key}" for key in ("XDG_CONFIG_HOME", "XDG_STATE_HOME")
|
|
1974
|
+
if os.environ.get(key)] + [
|
|
1975
|
+
f"--setenv={key}={value}" for key, value in sorted(env.items()) if key.startswith("SCRUBSCRIPT_")]
|
|
1976
|
+
# AccuracySec: a timer may fire up to a minute late by default, far past the delay.
|
|
1977
|
+
timer = [f"--on-active={delay}s", "--timer-property=AccuracySec=1s"] if delay else []
|
|
1978
|
+
run = subprocess.run(
|
|
1979
|
+
["systemd-run", "--user", "--quiet", "--collect", *timer,
|
|
1980
|
+
f"--unit=scrubscript-{name}", "-p", f"MemoryMax={MEMORY_MAX}", "-p", "MemorySwapMax=0",
|
|
1981
|
+
"-p", "Nice=10", "-p", f"StandardOutput=append:{HOOK_LOG}",
|
|
1982
|
+
"-p", f"StandardError=append:{HOOK_LOG}", *settings, *cmd],
|
|
1983
|
+
capture_output=True)
|
|
1984
|
+
# The unit name is taken while a unit of that name exists, so a failure is
|
|
1985
|
+
# usually one already pending.
|
|
1986
|
+
return run.returncode == 0, "" if run.returncode == 0 else "systemd-run failed; one may already be pending"
|
|
1987
|
+
|
|
1988
|
+
|
|
1989
|
+
def schedule(sid, projects):
|
|
1990
|
+
"""Start a scrub of one ended session after the delay; returns what was done."""
|
|
1991
|
+
reason = not_redacting()
|
|
1992
|
+
if reason:
|
|
1993
|
+
return f"not scheduled ({not_redacting_short(reason)})"
|
|
1994
|
+
started, note = start_apart(sid, ["--apply", "--ended", sid], projects, DELAY_SECONDS)
|
|
1995
|
+
if not started:
|
|
1996
|
+
return f"not scheduled ({note})"
|
|
1997
|
+
return f"scrub scheduled in {DELAY_SECONDS} s" + (f" ({note})" if note else "")
|
|
1998
|
+
|
|
1999
|
+
|
|
2000
|
+
def hook_payload():
|
|
2001
|
+
"""The hook's JSON payload from stdin, or an empty dict for anything else."""
|
|
2002
|
+
try:
|
|
2003
|
+
payload = json.loads(sys.stdin.read() or "{}")
|
|
2004
|
+
except ValueError:
|
|
2005
|
+
return {}
|
|
2006
|
+
return payload if isinstance(payload, dict) else {}
|
|
2007
|
+
|
|
2008
|
+
|
|
2009
|
+
def log_hook(event, detail, sid, result):
|
|
2010
|
+
try:
|
|
2011
|
+
with open(HOOK_LOG, "a") as log:
|
|
2012
|
+
log.write(f"{time.strftime('%Y-%m-%dT%H:%M:%S%z')} {event} {detail} "
|
|
2013
|
+
f"session={sid}: {result}\n")
|
|
2014
|
+
except OSError:
|
|
2015
|
+
pass
|
|
2016
|
+
|
|
2017
|
+
|
|
2018
|
+
def session_end():
|
|
2019
|
+
"""The SessionEnd hook: schedule a scrub of the session whose payload is on stdin.
|
|
2020
|
+
|
|
2021
|
+
Claude Code gives the hook about 1.5 s, far short of a scrub, so the scrub runs
|
|
2022
|
+
later and apart. Nothing here may fail the hook: ending a session must always work.
|
|
2023
|
+
"""
|
|
2024
|
+
sid, reason, result = "?", "?", "failed"
|
|
2025
|
+
try:
|
|
2026
|
+
HOOK_LOG.parent.mkdir(parents=True, exist_ok=True)
|
|
2027
|
+
payload = hook_payload()
|
|
2028
|
+
reason = str(payload.get("reason") or "?")
|
|
2029
|
+
transcript = payload.get("transcript_path")
|
|
2030
|
+
named = payload.get("session_id")
|
|
2031
|
+
if not isinstance(named, str) or not SESSION_ID.fullmatch(named):
|
|
2032
|
+
result = "no session id"
|
|
2033
|
+
elif not isinstance(transcript, str) or not os.path.isfile(transcript):
|
|
2034
|
+
# A headless run that saves no transcript still ends a session.
|
|
2035
|
+
sid, result = named, f"no transcript at {transcript or '?'}; nothing to scrub"
|
|
2036
|
+
else:
|
|
2037
|
+
sid, result = named, schedule(named, Path(transcript).resolve().parent.parent)
|
|
2038
|
+
if not_redacting() in WAITS:
|
|
2039
|
+
mark_waiting()
|
|
2040
|
+
except Exception as error: # noqa: BLE001 - see the docstring
|
|
2041
|
+
result = f"failed: {error}"
|
|
2042
|
+
log_hook("SessionEnd", f"reason={reason}", sid, result)
|
|
2043
|
+
|
|
2044
|
+
|
|
2045
|
+
def parent_of(pid):
|
|
2046
|
+
try:
|
|
2047
|
+
stat = (PROC / str(pid) / "stat").read_text()
|
|
2048
|
+
return int(stat[stat.rindex(")") + 2:].split()[1])
|
|
2049
|
+
except (OSError, ValueError, IndexError):
|
|
2050
|
+
pass
|
|
2051
|
+
ps = subprocess.run(["ps", "-o", "ppid=", "-p", str(pid)], capture_output=True, text=True)
|
|
2052
|
+
return int(ps.stdout) if ps.stdout.strip().isdigit() else None
|
|
2053
|
+
|
|
2054
|
+
|
|
2055
|
+
def claude_process(sid):
|
|
2056
|
+
"""The pid of the Claude Code process running the session, or None.
|
|
2057
|
+
|
|
2058
|
+
It is the hook's parent, or close above it when a shell runs the hook's command,
|
|
2059
|
+
and the registry is what tells it from a shell: Claude Code lists itself there
|
|
2060
|
+
under its pid, with the session it runs.
|
|
2061
|
+
"""
|
|
2062
|
+
pid = os.getppid()
|
|
2063
|
+
for _ in range(3):
|
|
2064
|
+
try:
|
|
2065
|
+
if json.loads((REGISTRY / f"{pid}.json").read_text()).get("sessionId") == sid:
|
|
2066
|
+
return pid
|
|
2067
|
+
except (OSError, ValueError, AttributeError):
|
|
2068
|
+
pass
|
|
2069
|
+
pid = parent_of(pid)
|
|
2070
|
+
if not pid or pid <= 1:
|
|
2071
|
+
break
|
|
2072
|
+
return None
|
|
2073
|
+
|
|
2074
|
+
|
|
2075
|
+
def sweep_is_due():
|
|
2076
|
+
"""Whether this session start should start a sweep: at most one per SWEEP_SECONDS.
|
|
2077
|
+
|
|
2078
|
+
Sessions often start together, each running this hook. The check and the mark
|
|
2079
|
+
happen under a lock on the mark's own file, so of any number of hooks running at
|
|
2080
|
+
once exactly one finds the sweep due.
|
|
2081
|
+
"""
|
|
2082
|
+
fd = os.open(STATE.parent / "sweep-started", os.O_CREAT | os.O_RDWR, 0o600)
|
|
2083
|
+
try:
|
|
2084
|
+
try:
|
|
2085
|
+
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
2086
|
+
except OSError:
|
|
2087
|
+
return False # a hook running at this moment is deciding it
|
|
2088
|
+
mark = os.fstat(fd)
|
|
2089
|
+
if mark.st_size and time.time() - mark.st_mtime < SWEEP_SECONDS:
|
|
2090
|
+
return False
|
|
2091
|
+
os.pwrite(fd, b"1", 0)
|
|
2092
|
+
return True
|
|
2093
|
+
finally:
|
|
2094
|
+
os.close(fd)
|
|
2095
|
+
|
|
2096
|
+
|
|
2097
|
+
def session_start():
|
|
2098
|
+
"""The SessionStart hook: note the session as started, and start a sweep when one is due.
|
|
2099
|
+
|
|
2100
|
+
The sweep is what reaches a session that ended with no SessionEnd hook run, by a
|
|
2101
|
+
crash or a kill. Nothing here may fail the hook. Its output is a systemMessage or
|
|
2102
|
+
nothing: Claude Code shows that to the user and keeps it out of the model's context,
|
|
2103
|
+
where any other output of a SessionStart hook would go. It says so while no scrub
|
|
2104
|
+
may rewrite a file, and why.
|
|
2105
|
+
"""
|
|
2106
|
+
sid, source, result, notice = "?", "?", None, None
|
|
2107
|
+
try:
|
|
2108
|
+
HOOK_LOG.parent.mkdir(parents=True, exist_ok=True)
|
|
2109
|
+
payload = hook_payload()
|
|
2110
|
+
source = str(payload.get("source") or "?")
|
|
2111
|
+
named = payload.get("session_id")
|
|
2112
|
+
if isinstance(named, str) and SESSION_ID.fullmatch(named):
|
|
2113
|
+
sid = named
|
|
2114
|
+
STARTED.mkdir(parents=True, exist_ok=True)
|
|
2115
|
+
(STARTED / sid).write_text(str(claude_process(sid) or ""))
|
|
2116
|
+
transcript = payload.get("transcript_path")
|
|
2117
|
+
projects = Path(transcript).resolve().parent.parent if isinstance(transcript, str) else PROJECTS
|
|
2118
|
+
reason = not_redacting()
|
|
2119
|
+
if reason:
|
|
2120
|
+
if reason in WAITS:
|
|
2121
|
+
mark_waiting()
|
|
2122
|
+
notice = not_redacting_message(reason)
|
|
2123
|
+
result = f"not redacting ({not_redacting_short(reason)})"
|
|
2124
|
+
elif projects.is_dir() and sweep_is_due():
|
|
2125
|
+
started, note = start_apart("sweep", ["--sweep"], projects, 0)
|
|
2126
|
+
result = "sweep started" + (f" ({note})" if note else "") if started else f"no sweep ({note})"
|
|
2127
|
+
except Exception as error: # noqa: BLE001 - see the docstring
|
|
2128
|
+
result = f"failed: {error}"
|
|
2129
|
+
if result:
|
|
2130
|
+
log_hook("SessionStart", f"source={source}", sid, result)
|
|
2131
|
+
if notice:
|
|
2132
|
+
print(json.dumps({"systemMessage": notice}))
|
|
2133
|
+
|
|
2134
|
+
|
|
2135
|
+
def scope_prefix():
|
|
2136
|
+
"""The command prefix that runs one session's scrub in a memory-capped, low-priority scope."""
|
|
2137
|
+
if not systemd_user():
|
|
2138
|
+
return []
|
|
2139
|
+
# A low CPU weight of its own: a child scope sits outside the caller's, so a
|
|
2140
|
+
# weight set on the caller would not reach it.
|
|
2141
|
+
return ["systemd-run", "--user", "--scope", "--quiet", "-p", f"MemoryMax={MEMORY_MAX}",
|
|
2142
|
+
"-p", "MemorySwapMax=0", "-p", "CPUWeight=25", "--nice=10", "--"]
|
|
2143
|
+
|
|
2144
|
+
|
|
2145
|
+
def scrub_each(sessions, apply, scope, show_skips=True, ended=False, tally=None):
|
|
2146
|
+
"""Scrub each session, or path, in a run of its own; (ids left unfinished, ids skipped as in use, ids whose run failed).
|
|
2147
|
+
|
|
2148
|
+
ended says the sessions are known to be over, so their runs drop the quiet period.
|
|
2149
|
+
tally, a folder, gets each run's list of secrets, in a file named for its place in sessions.
|
|
2150
|
+
"""
|
|
2151
|
+
me = os.path.abspath(__file__)
|
|
2152
|
+
unfinished, skipped, failed = set(), set(), set()
|
|
2153
|
+
for i, sid in enumerate(sessions):
|
|
2154
|
+
cmd = scope + [sys.executable, me, *(["--apply"] if apply else []),
|
|
2155
|
+
*(["--ended"] if ended else []), sid]
|
|
2156
|
+
env = {**os.environ, "SCRUBSCRIPT_TALLY": str(Path(tally) / f"{i}.jsonl")} if tally else None
|
|
2157
|
+
proc = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, env=env)
|
|
2158
|
+
lines = proc.stdout.splitlines()
|
|
2159
|
+
if proc.returncode != 0:
|
|
2160
|
+
failed.add(sid)
|
|
2161
|
+
lines.append(f"FAILED {sid}: exit {proc.returncode}")
|
|
2162
|
+
for line in lines:
|
|
2163
|
+
if line.startswith("SKIP"):
|
|
2164
|
+
skipped.add(sid)
|
|
2165
|
+
if not show_skips:
|
|
2166
|
+
continue
|
|
2167
|
+
if not line.startswith(("no secrets found", "dry run:")):
|
|
2168
|
+
print(line, flush=True)
|
|
2169
|
+
if any(mark in line for mark in UNFINISHED):
|
|
2170
|
+
unfinished.add(sid)
|
|
2171
|
+
return unfinished, skipped, failed
|
|
2172
|
+
|
|
2173
|
+
|
|
2174
|
+
def closing_count(tally, n_sessions, apply, unscanned, unread):
|
|
2175
|
+
"""One line: the distinct secrets the runs in the tally folder found, the sessions
|
|
2176
|
+
holding one, and a count per rule. The first n_sessions runs are sessions; the rest
|
|
2177
|
+
are the prompt history, the paste cache and the files no transcript owns. unread of
|
|
2178
|
+
those sessions were skipped or failed: the line names them, so that it never reads
|
|
2179
|
+
as an all-clear for a session nothing looked at."""
|
|
2180
|
+
rule_of, sessions, other_files = {}, 0, set()
|
|
2181
|
+
for path in Path(tally).glob("*.jsonl"):
|
|
2182
|
+
records = []
|
|
2183
|
+
for line in path.read_text().splitlines():
|
|
2184
|
+
try:
|
|
2185
|
+
records.append(json.loads(line))
|
|
2186
|
+
except ValueError:
|
|
2187
|
+
# Cut off by a kill while its run wrote it. That run exited non-zero, so
|
|
2188
|
+
# scrub_each already counts it as unfinished.
|
|
2189
|
+
continue
|
|
2190
|
+
if not records:
|
|
2191
|
+
continue
|
|
2192
|
+
if int(path.stem) < n_sessions:
|
|
2193
|
+
sessions += 1
|
|
2194
|
+
else:
|
|
2195
|
+
# One run reads the whole paste cache, so its files are told apart by name.
|
|
2196
|
+
other_files.update(r["file"] for r in records)
|
|
2197
|
+
for r in records:
|
|
2198
|
+
rule_of.setdefault(r["sha256"], r["rule"])
|
|
2199
|
+
where = f"{sessions} session{'' if sessions == 1 else 's'}"
|
|
2200
|
+
others = len(other_files)
|
|
2201
|
+
if others:
|
|
2202
|
+
where += f" and {others} other file{'' if others == 1 else 's'} (prompt history, pastes, debug logs)"
|
|
2203
|
+
if not rule_of:
|
|
2204
|
+
read = n_sessions - unread
|
|
2205
|
+
line = f"no secrets found in {read} session{'' if read == 1 else 's'}"
|
|
2206
|
+
else:
|
|
2207
|
+
rules = Counter(rule_of.values())
|
|
2208
|
+
line = (f"{'redacted' if apply else 'found'} {len(rule_of)} secret{'' if len(rule_of) == 1 else 's'} "
|
|
2209
|
+
f"in {where}: " + ", ".join(f"{n} {rule}" for rule, n in sorted(rules.items(), key=lambda kv: (-kv[1], kv[0]))))
|
|
2210
|
+
if unread:
|
|
2211
|
+
line += f"; {unread} session{'' if unread == 1 else 's'} skipped or failed"
|
|
2212
|
+
if unscanned:
|
|
2213
|
+
line += f"; the {unscanned} unchanged since the last full scrub were not read, --full reads them"
|
|
2214
|
+
return line
|
|
2215
|
+
|
|
2216
|
+
|
|
2217
|
+
def run_all(apply, full):
|
|
2218
|
+
"""Every session changed since the last full scrub, or every session without one."""
|
|
2219
|
+
started = time.time()
|
|
2220
|
+
since, pinned = (None, set()) if full else last_full_scrub()
|
|
2221
|
+
sessions = session_ids()
|
|
2222
|
+
newest = newest_by_session() if since is not None else {}
|
|
2223
|
+
scope = scope_prefix()
|
|
2224
|
+
if not scope:
|
|
2225
|
+
print("scrubscript: no systemd user manager here, so sessions run without a memory cap",
|
|
2226
|
+
file=sys.stderr)
|
|
2227
|
+
changed = [sid for sid in sessions
|
|
2228
|
+
if since is None or sid in pinned or newest.get(sid, 0) >= since]
|
|
2229
|
+
# A session's scrub reads its own prompts in the history. The rest is reached only
|
|
2230
|
+
# here: a prompt whose transcript is gone, a paste no prompt names.
|
|
2231
|
+
rest = [str(p) for p in (HISTORY, PASTES) if p.exists()]
|
|
2232
|
+
# By its files' times, not a folder's own: a rewrite keeps a file's time and moves its folder's.
|
|
2233
|
+
rest += [str(p) for p in strays()
|
|
2234
|
+
if since is None or str(p) in pinned
|
|
2235
|
+
or max((f.stat().st_mtime for f in files_under([p])), default=0) >= since]
|
|
2236
|
+
with tempfile.TemporaryDirectory(prefix="scrubscript-tally-") as tally:
|
|
2237
|
+
unfinished, skipped, failed = scrub_each(changed + rest, apply, scope, tally=tally)
|
|
2238
|
+
print(f"{len(sessions)} sessions: {len(sessions) - len(changed)} unchanged since the last full scrub, "
|
|
2239
|
+
f"{len(unfinished)} left unfinished")
|
|
2240
|
+
print(closing_count(tally, len(changed), apply, len(sessions) - len(changed),
|
|
2241
|
+
len((skipped | failed) & set(changed))))
|
|
2242
|
+
if apply:
|
|
2243
|
+
STATE.parent.mkdir(parents=True, exist_ok=True)
|
|
2244
|
+
STATE.write_text(json.dumps({
|
|
2245
|
+
"since": started - QUIET_SECONDS,
|
|
2246
|
+
"ran": time.strftime("%Y-%m-%d %H:%M", time.localtime(started)),
|
|
2247
|
+
"fingerprint": fingerprint(),
|
|
2248
|
+
"rescan": sorted(unfinished),
|
|
2249
|
+
}, indent=2) + "\n")
|
|
2250
|
+
return 1 if failed else 0
|
|
2251
|
+
|
|
2252
|
+
|
|
2253
|
+
def sweep():
|
|
2254
|
+
"""Scrub the sessions written since the last sweep that are no longer in use.
|
|
2255
|
+
|
|
2256
|
+
A session whose Claude Code process is gone is over, and is scrubbed at once: that
|
|
2257
|
+
is the killed session, reached by the first sweep after it died. Without a process
|
|
2258
|
+
on record, a session too recent to tell from a live one is kept for the next sweep,
|
|
2259
|
+
as is one a process still names. One whose scrub failed is not: the next sweep would fail the
|
|
2260
|
+
same way, and --all still reaches it. The first sweep looks back a day. The record
|
|
2261
|
+
is the sweep's own, one per projects folder and apart from the full scrub's, so a
|
|
2262
|
+
new gitleaks build does not stop the sweeps. One sweep runs at a time; a second
|
|
2263
|
+
one leaves at once.
|
|
2264
|
+
|
|
2265
|
+
While no scrub may rewrite a file, a sweep scrubs nothing and keeps its record as it
|
|
2266
|
+
was, so the first sweep after --setup reaches every session that ended meanwhile.
|
|
2267
|
+
A hook that found backups not set up left a mark of when, and the sweep looks back to a
|
|
2268
|
+
day before it, however long ago that was.
|
|
2269
|
+
"""
|
|
2270
|
+
STATE.parent.mkdir(parents=True, exist_ok=True)
|
|
2271
|
+
lock = os.open(STATE.parent / "sweep.lock", os.O_CREAT | os.O_RDWR, 0o600)
|
|
2272
|
+
try:
|
|
2273
|
+
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
2274
|
+
except OSError:
|
|
2275
|
+
return 0
|
|
2276
|
+
prune_backups()
|
|
2277
|
+
reason = not_redacting()
|
|
2278
|
+
if reason:
|
|
2279
|
+
print(not_redacting_message(reason), file=sys.stderr)
|
|
2280
|
+
return NOT_REDACTING
|
|
2281
|
+
started = time.time()
|
|
2282
|
+
folder = hashlib.sha256(str(PROJECTS.resolve()).encode()).hexdigest()[:12]
|
|
2283
|
+
record = STATE.parent / f"sweep-{folder}.json"
|
|
2284
|
+
try:
|
|
2285
|
+
state = json.loads(record.read_text())
|
|
2286
|
+
since, kept = float(state["since"]), set(state["rescan"])
|
|
2287
|
+
except (OSError, ValueError, KeyError, TypeError):
|
|
2288
|
+
since, kept = started - FIRST_SWEEP_SECONDS, set()
|
|
2289
|
+
try:
|
|
2290
|
+
waited = WAITING.stat().st_mtime
|
|
2291
|
+
since = min(since, waited - FIRST_SWEEP_SECONDS)
|
|
2292
|
+
except OSError:
|
|
2293
|
+
waited = None
|
|
2294
|
+
newest = newest_by_session()
|
|
2295
|
+
over, due, recent = [], [], set()
|
|
2296
|
+
for sid in session_ids():
|
|
2297
|
+
if sid not in kept and newest.get(sid, 0) < since:
|
|
2298
|
+
continue
|
|
2299
|
+
pid = process_of(sid)
|
|
2300
|
+
if pid and gone(pid):
|
|
2301
|
+
over.append(sid)
|
|
2302
|
+
elif started - max(newest.get(sid, 0), started_at(sid)) < QUIET_SECONDS:
|
|
2303
|
+
recent.add(sid)
|
|
2304
|
+
else:
|
|
2305
|
+
due.append(sid)
|
|
2306
|
+
scope = scope_prefix()
|
|
2307
|
+
_, skipped, failed = scrub_each(over, True, scope, show_skips=False, ended=True)
|
|
2308
|
+
_, skipped_due, failed_due = scrub_each(due, True, scope, show_skips=False)
|
|
2309
|
+
# A restore keeps a file's modification time, so a restored file is found by its
|
|
2310
|
+
# name in the queue. One still in use waits for the next sweep.
|
|
2311
|
+
queued = {}
|
|
2312
|
+
for entry in RESTORED.glob("*"):
|
|
2313
|
+
try:
|
|
2314
|
+
queued[entry.read_text().strip()] = entry
|
|
2315
|
+
except OSError:
|
|
2316
|
+
continue
|
|
2317
|
+
# A file of a session started a moment ago also waits: the start may be the resume
|
|
2318
|
+
# that rewinds from the copies just restored.
|
|
2319
|
+
present = sorted(path for path in queued if os.path.isfile(path)
|
|
2320
|
+
and all(started - started_at(sid) >= QUIET_SECONDS for sid in sessions_of(path)))
|
|
2321
|
+
unfinished_restored, skipped_restored, failed_restored = scrub_each(present, True, scope, show_skips=False)
|
|
2322
|
+
# One whose scrub failed stays queued too: nothing else would reach it again.
|
|
2323
|
+
for path, entry in queued.items():
|
|
2324
|
+
if path in present and path not in skipped_restored and path not in unfinished_restored:
|
|
2325
|
+
entry.unlink(missing_ok=True)
|
|
2326
|
+
elif not os.path.isfile(path):
|
|
2327
|
+
entry.unlink(missing_ok=True)
|
|
2328
|
+
failed |= failed_restored
|
|
2329
|
+
again = recent | skipped | skipped_due
|
|
2330
|
+
failed |= failed_due
|
|
2331
|
+
partial = record.with_suffix(".tmp")
|
|
2332
|
+
partial.write_text(json.dumps({"since": started, "rescan": sorted(again)}, indent=2) + "\n")
|
|
2333
|
+
os.replace(partial, record)
|
|
2334
|
+
if waited is not None:
|
|
2335
|
+
WAITING.unlink(missing_ok=True)
|
|
2336
|
+
for mark in STARTED.glob("*"):
|
|
2337
|
+
try:
|
|
2338
|
+
if started - mark.stat().st_mtime > QUIET_SECONDS:
|
|
2339
|
+
mark.unlink()
|
|
2340
|
+
except OSError:
|
|
2341
|
+
pass
|
|
2342
|
+
if over or due or present:
|
|
2343
|
+
restored = f" and {len(present)} restored file(s)" if present else ""
|
|
2344
|
+
print(f"{time.strftime('%Y-%m-%dT%H:%M:%S%z')} sweep: {len(over) + len(due)} session(s){restored} scanned, "
|
|
2345
|
+
f"{len(failed)} failed, {len(again)} to look at again", flush=True)
|
|
2346
|
+
return 0
|
|
2347
|
+
|
|
2348
|
+
|
|
2349
|
+
def main():
|
|
2350
|
+
# No abbreviations: a flag this program does not have must not be read as one it has.
|
|
2351
|
+
parser = argparse.ArgumentParser(prog="scrubscript", description=__doc__.split("\n\n")[0], allow_abbrev=False)
|
|
2352
|
+
parser.add_argument("--version", action="version", version=f"scrubscript {__version__}")
|
|
2353
|
+
parser.add_argument("targets", nargs="*", metavar="session-id|path")
|
|
2354
|
+
parser.add_argument("--all", action="store_true", help="every session, each in a memory-capped scope")
|
|
2355
|
+
parser.add_argument("--apply", action="store_true", help="rewrite the files; default is a dry run")
|
|
2356
|
+
parser.add_argument("--full", action="store_true", help="with --all, ignore the last full scrub")
|
|
2357
|
+
parser.add_argument("--status", action="store_true", help="when the last full scrub ran, what changed since")
|
|
2358
|
+
parser.add_argument("--doctor", action="store_true", help="check gitleaks, the folders and the hooks")
|
|
2359
|
+
parser.add_argument("--ended", action="store_true", help="the sessions just ended: no quiet period")
|
|
2360
|
+
parser.add_argument("--rules", metavar="FILE", help="extra gitleaks rules; default ~/.config/scrubscript/rules.toml")
|
|
2361
|
+
parser.add_argument("--restore", action="store_true",
|
|
2362
|
+
help="put back what the encrypted backups of these files hold; asks for the recovery code")
|
|
2363
|
+
parser.add_argument("--identity", metavar="FILE",
|
|
2364
|
+
help="with --restore, an age identity file that opens the backups, in place of the code")
|
|
2365
|
+
parser.add_argument("--setup", action="store_true",
|
|
2366
|
+
help="turn backups on: make a key, keep its public half, show the recovery code once")
|
|
2367
|
+
parser.add_argument("--filter", action="store_true",
|
|
2368
|
+
help="print standard input with its secrets redacted, for text not yet in a transcript")
|
|
2369
|
+
parser.add_argument("--live", metavar="TRANSCRIPT",
|
|
2370
|
+
help="with --filter, as live redaction runs it: back up what is replaced, filed with "
|
|
2371
|
+
"this transcript, and replace nothing without a backup")
|
|
2372
|
+
parser.add_argument("--json", action="store_true",
|
|
2373
|
+
help="with --live, the text is JSON that the transcript stores as JSON")
|
|
2374
|
+
parser.add_argument("--marker-sent", metavar="TOOL",
|
|
2375
|
+
help="log to hooks.log that a call to TOOL carried the marker ids given, which the session "
|
|
2376
|
+
"named with --live issued")
|
|
2377
|
+
parser.add_argument("--session-end", action="store_true",
|
|
2378
|
+
help="as a Claude Code SessionEnd hook: schedule a scrub of the session on stdin")
|
|
2379
|
+
parser.add_argument("--session-start", action="store_true",
|
|
2380
|
+
help="as a Claude Code SessionStart hook: start a sweep when one is due")
|
|
2381
|
+
parser.add_argument("--sweep", action="store_true",
|
|
2382
|
+
help="scrub the sessions written since the last sweep that are no longer in use")
|
|
2383
|
+
args = parser.parse_args()
|
|
2384
|
+
if args.session_end:
|
|
2385
|
+
session_end()
|
|
2386
|
+
return
|
|
2387
|
+
if args.session_start:
|
|
2388
|
+
session_start()
|
|
2389
|
+
return
|
|
2390
|
+
if args.rules:
|
|
2391
|
+
# In the environment, so the per-session runs of --all read the same file.
|
|
2392
|
+
os.environ["SCRUBSCRIPT_RULES"] = os.path.abspath(args.rules)
|
|
2393
|
+
if args.status:
|
|
2394
|
+
sys.exit(status())
|
|
2395
|
+
if args.doctor:
|
|
2396
|
+
sys.exit(doctor())
|
|
2397
|
+
if args.setup:
|
|
2398
|
+
sys.exit(setup())
|
|
2399
|
+
if args.sweep:
|
|
2400
|
+
sys.exit(sweep())
|
|
2401
|
+
if args.filter:
|
|
2402
|
+
filter_text(args.live, args.json)
|
|
2403
|
+
return
|
|
2404
|
+
if args.marker_sent:
|
|
2405
|
+
marker_sent(args.marker_sent, args.live, args.targets)
|
|
2406
|
+
return
|
|
2407
|
+
if args.restore:
|
|
2408
|
+
if not args.targets:
|
|
2409
|
+
parser.error("--restore takes the files to restore")
|
|
2410
|
+
sys.exit(restore([Path(arg) for arg in args.targets], args.identity))
|
|
2411
|
+
if bool(args.targets) == args.all:
|
|
2412
|
+
parser.error("give session ids or paths, or --all")
|
|
2413
|
+
reason = args.apply and not_redacting()
|
|
2414
|
+
if reason:
|
|
2415
|
+
print(not_redacting_message(reason), file=sys.stderr)
|
|
2416
|
+
sys.exit(NOT_REDACTING)
|
|
2417
|
+
|
|
2418
|
+
if args.all:
|
|
2419
|
+
sys.exit(run_all(args.apply, args.full))
|
|
2420
|
+
|
|
2421
|
+
# A dry run rewrites nothing, so a session still in use is read like any other.
|
|
2422
|
+
quiet = 0 if args.ended or not args.apply else QUIET_SECONDS
|
|
2423
|
+
live = live_sessions() if args.apply else set()
|
|
2424
|
+
targets, sessions = [], []
|
|
2425
|
+
for arg in args.targets:
|
|
2426
|
+
t, is_session = resolve(arg)
|
|
2427
|
+
named = live & ({arg} if is_session else sessions_of(arg))
|
|
2428
|
+
if named:
|
|
2429
|
+
print(f"SKIP session {' '.join(sorted(named))}: a process still names it")
|
|
2430
|
+
continue
|
|
2431
|
+
if is_session:
|
|
2432
|
+
newest = max(max(p.stat().st_mtime for p in files_under(t)), started_at(arg))
|
|
2433
|
+
if time.time() - newest < quiet:
|
|
2434
|
+
print(f"SKIP session {arg}: written or started in the last {quiet // 60} min; "
|
|
2435
|
+
"add --ended if the session is over")
|
|
2436
|
+
continue
|
|
2437
|
+
sessions.append(arg)
|
|
2438
|
+
targets += t
|
|
2439
|
+
if not targets:
|
|
2440
|
+
return
|
|
2441
|
+
if any(p.resolve() == HISTORY.resolve() for p in targets):
|
|
2442
|
+
sessions = [] # the whole history is read, so no view of it is needed
|
|
2443
|
+
|
|
2444
|
+
# Redacting one secret can expose another gitleaks did not report beside it, so
|
|
2445
|
+
# --apply rescans what it rewrote until a pass changes nothing.
|
|
2446
|
+
for attempt in range(MAX_PASSES if args.apply else 1):
|
|
2447
|
+
with tempfile.TemporaryDirectory(prefix="scrubscript-") as workdir:
|
|
2448
|
+
# Apart from the scan's own files: scan() has gitleaks ignore its work folder.
|
|
2449
|
+
(Path(workdir) / "scan").mkdir()
|
|
2450
|
+
view, pastes = history_view(sessions, Path(workdir) / "history")
|
|
2451
|
+
stamps = {p.resolve(): stamp(p) for p in files_under(targets + pastes)}
|
|
2452
|
+
findings = scan(targets + pastes + ([view] if view else []), Path(workdir) / "scan")
|
|
2453
|
+
by_file = defaultdict(list)
|
|
2454
|
+
for f in findings:
|
|
2455
|
+
found = Path(f["File"])
|
|
2456
|
+
by_file[HISTORY if view and found.resolve() == view.resolve() else found].append(f)
|
|
2457
|
+
# A file whose only findings are kept values has nothing to redact.
|
|
2458
|
+
by_file = {path: found for path, found in by_file.items() if unkept(found)}
|
|
2459
|
+
rewritten = []
|
|
2460
|
+
for path in sorted(by_file):
|
|
2461
|
+
is_history = path.resolve() == HISTORY.resolve()
|
|
2462
|
+
report = scrub_file(path, by_file[path], args.apply, stamps.get(path.resolve()), appended_to=is_history)
|
|
2463
|
+
print(report if attempt == 0 else f"pass {attempt + 1}: {report}")
|
|
2464
|
+
if report.startswith("redacted") and not report.startswith("redacted 0 "):
|
|
2465
|
+
rewritten.append(path)
|
|
2466
|
+
if not by_file and attempt == 0:
|
|
2467
|
+
print("no secrets found")
|
|
2468
|
+
if not rewritten:
|
|
2469
|
+
break
|
|
2470
|
+
# After a view, the next pass reads the sessions' prompts through a new one.
|
|
2471
|
+
targets = [p for p in rewritten if not view or p != HISTORY]
|
|
2472
|
+
if by_file and not args.apply:
|
|
2473
|
+
print("dry run: rerun with --apply to rewrite these files")
|
|
2474
|
+
|
|
2475
|
+
|
|
2476
|
+
if __name__ == "__main__":
|
|
2477
|
+
main()
|