Denies Bash heredoc writes outside scratch that bypass Edit and Write

Managed using GNU Stow
Structure: "name-of-package"/path-to/destination stow "package-to-install" to set up symlinks stow -D "package-to-uninstall" to remove symlinks
Install both packages with stow omp omarchy, then apply an Omarchy theme to generate the OMP palette. Restart OMP once after setup so it starts with the custom theme's file watcher. Subsequent Omarchy theme switches update OMP live. Changing the theme through Appearance settings alone does not start the watcher in the current OMP runtime.
Install the packages and browser UI modification from the repository root as your desktop user:
make install-vivaldi
The target runs Stow, prompts for sudo to patch Vivaldi's system resources, and reapplies the current Omarchy theme. Stow alone is not sufficient. Restart Vivaldi once after it completes. Subsequent theme switches update its interface within about a second, without a debugging port or local server. The integration selects its own Omarchy theme and disables Vivaldi's theme scheduling.
Run make install-vivaldi again after Vivaldi updates, then restart the browser. The modification uses Vivaldi's internal API and may need changes when that API changes. The installation supports one desktop user and shares that user's palette with every Vivaldi profile using this installation.
To stop syncing, remove the omarchy-theme.js script tag from /opt/vivaldi/resources/vivaldi/window.html, restart Vivaldi, and select your preferred theme and scheduling settings.
hooks/register.ts 271 lines1import type { Register } from 'claude-code'
2
3const HEREDOC_OPENER = /<<(-?)\s*(?:'([^'\n]+)'|"([^"\n]+)"|\\?([^\s;&|<>()'"]+))/y
4const QUOTED_SPECIAL = { "'": /[\s<>;&|$]/g, '"': /[\s<>;&|]/g } as const
5const FILE_REDIRECT_TARGET = /(?<![<>\d&])[1&]?>>?\|?\s*([^\s;&|<>(][^\s;&|<>]*)/g
6const TEE_TARGET = /\btee\s+(?:-\S+\s+)*([^\s;&|<>]+)/g
7const REMOTE_OR_PRIVILEGED = /\b(?:sudo|ssh|kubectl|docker|podman)\b/
8const PYTHON_INTERPRETER = /(?:^|[\s(])python3?\s/
9const PYTHON_WRITE = /\bopen\((?:[^()]|\([^()]*\))*?,\s*(?:mode\s*=\s*)?['"][rwaxbt+]*[wax+][rwaxbt+]*['"]\s*[,)]|\.write_(?:text|bytes)\(/
10const PYTHON_LITERAL_READ = /\bopen\(\s*(['"])[^'"\n]*\1\s*(?:,\s*(?:mode\s*=\s*)?['"][rbt]*['"]\s*)?\)|\bPath\(\s*(['"])[^'"\n]*\2\s*\)\.read_(?:text|bytes)\(/g
11const SCOPE_CHANGE = /(?:^|[;&|(\s])(?:export\s+)?([A-Za-z_]\w*)=([^\s;&|)]*)|\b(cd|pushd)\s+(?:-\S*\s+)*([^\s;&|)]+)|\b(popd)\b/gm
12const INNERMOST_GROUP = /\$?\([^()]*\)/g
13const VARIABLE_REFERENCE = /\$\{?([A-Za-z_]\w*)\}?/g
14
15type Quote = keyof typeof QUOTED_SPECIAL
16
17type Heredoc = {
18 opener: string
19 line: string
20 before: string
21 body: string
22}
23
24type PendingHeredoc = {
25 opener: string
26 delimiter: string
27 stripTabs: boolean
28}
29
30type Script = {
31 shell: string
32 heredocs: readonly Heredoc[]
33}
34
35type Scope = {
36 values: ReadonlyMap<string, string>
37 cwd: string | null
38}
39
40type ScratchRoots = {
41 prefixes: readonly string[]
42 home: string | undefined
43}
44
45function scratchRoots(tmpdir: string | undefined, home: string | undefined): ScratchRoots {
46 const tmpdirPrefix = tmpdir?.startsWith('/') ? `${tmpdir.replace(/\/+$/, '')}/` : '/'
47 return { prefixes: ['/tmp/', '/dev/', ...(tmpdirPrefix === '/' ? [] : [tmpdirPrefix])], home }
48}
49
50function isScratch(path: string, roots: ScratchRoots): boolean {
51 if (path.split('/').includes('..')) return false
52 const absolute = roots.home !== undefined && path.startsWith('~/') ? `${roots.home}${path.slice(1)}` : path
53 if (roots.prefixes.some(prefix => absolute.startsWith(prefix))) return true
54 const jobs = roots.home === undefined ? null : `${roots.home}/.claude/jobs/`
55 return jobs !== null && absolute.startsWith(jobs) && /^[^/]+\/tmp\//.test(absolute.slice(jobs.length))
56}
57
58function sanitize(text: string, quote: Quote): string {
59 return text.replace(QUOTED_SPECIAL[quote], '_')
60}
61
62function isWordStart(command: string, index: number): boolean {
63 return index === 0 || /[\s;&|()]/.test(command[index - 1] ?? '')
64}
65
66function readBody(command: string, start: number, heredoc: PendingHeredoc): { body: string; next: number } {
67 let lineStart = start
68 while (lineStart < command.length) {
69 const newline = command.indexOf('\n', lineStart)
70 const lineEnd = newline === -1 ? command.length : newline
71 const text = command.slice(lineStart, lineEnd)
72 if ((heredoc.stripTabs ? text.replace(/^\t+/, '') : text) === heredoc.delimiter) {
73 return { body: command.slice(start, lineStart), next: lineEnd + 1 }
74 }
75 lineStart = lineEnd + 1
76 }
77 return { body: command.slice(start), next: command.length }
78}
79
80function arithmeticEnd(command: string, start: number): number | null {
81 let depth = 0
82 for (let index = start; index < command.length; index += 1) {
83 if (command[index] === '(') depth += 1
84 else if (command[index] === ')') {
85 if (depth > 0) depth -= 1
86 else return command[index + 1] === ')' ? index + 2 : null
87 }
88 }
89 return null
90}
91
92function parseScript(command: string): Script {
93 const heredocs: Heredoc[] = []
94 const pending: PendingHeredoc[] = []
95 const frames: ('double' | number)[] = []
96 let quoted = ''
97 let shell = ''
98 let lineStart = 0
99 let index = 0
100
101 while (index < command.length) {
102 const char = command[index] ?? ''
103 const frame = frames.at(-1)
104
105 if (frame === 'double') {
106 if (char === '\\') {
107 quoted += command.slice(index, index + 2)
108 index += 2
109 } else if (char === '"') {
110 shell += sanitize(quoted, '"')
111 quoted = ''
112 frames.pop()
113 index += 1
114 } else if (command.startsWith('$((', index) && arithmeticEnd(command, index + 3) !== null) {
115 const end = arithmeticEnd(command, index + 3) ?? command.length
116 quoted += command.slice(index, end)
117 index = end
118 } else if (command.startsWith('$(', index)) {
119 shell += `${sanitize(quoted, '"')}$(`
120 quoted = ''
121 frames.push(1)
122 index += 2
123 } else {
124 quoted += char
125 index += 1
126 }
127 continue
128 }
129
130 if (char === '\\') {
131 shell += command[index + 1] === '\n' ? ' ' : command.slice(index, index + 2)
132 index += 2
133 continue
134 }
135 if (char === "'") {
136 const close = command.indexOf("'", index + 1)
137 const end = close === -1 ? command.length : close
138 shell += sanitize(command.slice(index + 1, end), "'")
139 index = end + 1
140 continue
141 }
142 if (char === '"') {
143 frames.push('double')
144 index += 1
145 continue
146 }
147 const arithmetic = command.startsWith('((', index) ? arithmeticEnd(command, index + 2) : null
148 if (arithmetic !== null) {
149 shell += sanitize(command.slice(index, arithmetic), '"')
150 index = arithmetic
151 continue
152 }
153 if (char === '#' && isWordStart(command, index)) {
154 const newline = command.indexOf('\n', index)
155 index = newline === -1 ? command.length : newline
156 continue
157 }
158 if (command.startsWith('<<', index) && command[index + 2] !== '<' && command[index - 1] !== '<') {
159 HEREDOC_OPENER.lastIndex = index
160 const match = HEREDOC_OPENER.exec(command)
161 if (match !== null) {
162 pending.push({ opener: match[0], delimiter: match[2] ?? match[3] ?? match[4] ?? '', stripTabs: match[1] === '-' })
163 shell += match[0]
164 index += match[0].length
165 continue
166 }
167 }
168 if (typeof frame === 'number' && char === '(') frames[frames.length - 1] = frame + 1
169 if (typeof frame === 'number' && char === ')') {
170 if (frame === 1) frames.pop()
171 else frames[frames.length - 1] = frame - 1
172 }
173 if (char === '\n' && pending.length > 0) {
174 const line = shell.slice(lineStart)
175 const before = shell.slice(0, lineStart)
176 let bodyStart = index + 1
177 for (const heredoc of pending) {
178 const { body, next } = readBody(command, bodyStart, heredoc)
179 heredocs.push({ opener: heredoc.opener, line, before, body })
180 bodyStart = next
181 }
182 pending.length = 0
183 shell += '\n'
184 lineStart = shell.length
185 index = bodyStart
186 continue
187 }
188 shell += char
189 if (char === '\n') lineStart = shell.length
190 index += 1
191 }
192
193 shell += sanitize(quoted, '"')
194 for (const heredoc of pending) {
195 heredocs.push({ opener: heredoc.opener, line: shell.slice(lineStart), before: shell.slice(0, lineStart), body: '' })
196 }
197 return { shell, heredocs }
198}
199
200function expand(word: string, values: ReadonlyMap<string, string>): string {
201 return word.replace(VARIABLE_REFERENCE, (reference, name: string) => values.get(name) ?? reference)
202}
203
204function withoutGroups(text: string): string {
205 const collapsed = text.replace(INNERMOST_GROUP, group => (group.startsWith('$') ? '$_' : '_'))
206 return collapsed === text ? text : withoutGroups(collapsed)
207}
208
209function scopeOf(text: string): Scope {
210 const values = new Map<string, string>()
211 const pushed: (string | null)[] = []
212 let cwd: string | null = '.'
213 for (const [, name, value, verb, directory, popd] of withoutGroups(text).matchAll(SCOPE_CHANGE)) {
214 if (popd !== undefined) {
215 cwd = pushed.length > 0 ? (pushed.pop() ?? null) : null
216 continue
217 }
218 if (verb === 'pushd') pushed.push(cwd)
219 if (name !== undefined) {
220 const resolved = expand(value ?? '', values)
221 if (/[$`]/.test(resolved)) values.delete(name)
222 else values.set(name, resolved)
223 continue
224 }
225 const resolved = expand(directory ?? '', values)
226 if (resolved.includes('$') || resolved === '-') cwd = null
227 else if (/^[/~]/.test(resolved)) cwd = resolved
228 else if (cwd !== null) cwd = `${cwd}/${resolved}`
229 }
230 return { values, cwd }
231}
232
233function writesOutsideScratch(heredoc: Heredoc, roots: ScratchRoots): boolean {
234 const segment = heredoc.line.split(/&&|\|\||;/).find(part => part.includes(heredoc.opener)) ?? ''
235 const pipeline = segment.split(/(?<!>)\|/)
236 const producerIndex = pipeline.findIndex(part => part.includes(heredoc.opener))
237 const producer = pipeline[producerIndex] ?? ''
238 const { values, cwd } = scopeOf(heredoc.before + heredoc.line.slice(0, heredoc.line.indexOf(heredoc.opener)))
239 if (PYTHON_INTERPRETER.test(producer)) {
240 const touchesScratch = /\/(?:tmp|dev)\//.test(heredoc.body) || expand(producer, values).includes('/tmp/')
241 const namesOutsidePath = /['"](?:\/(?!tmp\/|dev\/)|~\/)/.test(heredoc.body.replace(PYTHON_LITERAL_READ, '_'))
242 const writesRelativeOutside = cwd !== null && !isScratch(`${cwd}/`, roots)
243 return PYTHON_WRITE.test(heredoc.body) && !touchesScratch && (namesOutsidePath || writesRelativeOutside)
244 }
245 if (!/\b(?:cat|tee)\b/.test(producer)) return false
246
247 const teeTargets = (part: string): RegExpMatchArray[] => REMOTE_OR_PRIVILEGED.test(part) ? [] : [...part.matchAll(TEE_TARGET)]
248 const targets = [
249 ...producer.matchAll(FILE_REDIRECT_TARGET),
250 ...teeTargets(producer),
251 ...pipeline.slice(producerIndex + 1).flatMap(teeTargets),
252 ].map(match => expand(match[1] ?? '', values))
253 return targets.some(target => {
254 if (target.includes('$')) return false
255 if (/^[/~]/.test(target)) return !isScratch(target, roots)
256 return cwd !== null && !isScratch(`${cwd}/${target}`, roots)
257 })
258}
259
260export const register: Register = on => {
261 on('tool.call', { tool: 'Bash' }, async ($, e, next) => {
262 const script = parseScript(e.command)
263 if (script.heredocs.length === 0) return next(e)
264 const roots = scratchRoots(await $.env.get('CLAUDE_CODE_TMPDIR'), await $.env.get('HOME'))
265 if (script.heredocs.some(heredoc => writesOutsideScratch(heredoc, roots))) {
266 return { deny: `${$.plugin.name}: a heredoc writes a file outside scratch. Use Edit or Write, they read before writing and run the PostToolUse checks.` }
267 }
268 return next(e)
269 }).catch(($, e, next) => (next.called ? next(e) : { deny: `${$.plugin.name}: the heredoc check failed, the command was not run.` }))
270}
271