Open History to see the last commit
1/**
2 * Host-side, fail-closed checks for a PR Git snapshot (`auditPullSecurity`)
3 * and for Grok's generated patch (`scanGeneratedDiff`). They block
4 * malware-shaped content and whole change classes: lockfiles, new
5 * dependencies, sensitive paths, binaries, and executables. A clean audit is
6 * required before Grok starts, and before `secure` or workflow approval.
7 */
8
9import type { readPullSnapshot } from './git.ts'
10
11export type PullFile = {
12 path: string
13 patch: string | null
14 status?: string
15 previousPath?: string | null
16}
17
18const BINARY_PATH = /\.(?:exe|dll|so|dylib|scr|bat|cmd|ps1)$/i
19const PIPE_SHELL =
20 /(?:curl|wget|fetch)\b[^\n]{0,200}\|\s*(?:\S*\/)?(?:ba)?sh\b/i
21const POWERSHELL_ENC = /powershell(?:\.exe)?[^\n]{0,80}-enc(?:odedcommand)?\b/i
22const REVERSE_SHELL = /\/dev\/tcp\/|bash\s+-i\s+>&\s*\/dev\/tcp/i
23const LIFECYCLE = /"(?:preinstall|postinstall|prepublishOnly)"\s*:\s*"([^"]*)"/g
24const NETWORK =
25 /https?:\/\/|curl\b|wget\b|invoke-webrequest\b|node\s+-e\b|git\s+clone\b/i
26const SENSITIVE_PATH =
27 /(?:^|\/)(?:AGENTS\.md|CLAUDE\.md|GEMINI\.md|\.gitmodules|\.env(?:\.[^/]*)?|\.npmrc|\.netrc)$|(?:^|\/)\.(?:git|github|agents|claude|grok|husky|ssh)(?:\/|$)/i
28const SENSITIVE_SCRIPT =
29 /(^|\/)(?:action\.ya?ml|(?:install|release|publish)(?:[.-][^/]*)?\.(?:js|cjs|mjs|ts|sh|bash|cmd|bat|ps1))$/i
30const LOCKFILE =
31 /(^|\/)(?:pnpm-lock\.yaml|package-lock\.json|yarn\.lock|bun\.lockb?)$/i
32const DEPENDENCY_FIELDS = [
33 'dependencies',
34 'devDependencies',
35 'optionalDependencies',
36 'peerDependencies',
37] as const
38
39function dependencyNames(packageJson: string) {
40 const parsed: unknown = JSON.parse(packageJson)
41 if (!isRecord(parsed)) throw new Error('package.json must contain an object')
42 const names = new Set<string>()
43 for (const field of DEPENDENCY_FIELDS) {
44 const dependencies = parsed[field]
45 if (!isRecord(dependencies)) continue
46 for (const name of Object.keys(dependencies)) names.add(name)
47 }
48 return names
49}
50
51function isRecord(value: unknown): value is Record<string, unknown> {
52 return typeof value === 'object' && value !== null && !Array.isArray(value)
53}
54
55/** Return package names present after a change but absent before it. */
56export function findNewDependencies(before: string, after: string) {
57 const oldNames = dependencyNames(before)
58 return [...dependencyNames(after)]
59 .filter((name) => !oldNames.has(name))
60 .sort()
61}
62
63function addedText(patch: string | null) {
64 if (patch === null) return ''
65 const lines = []
66 for (const line of patch.split('\n')) {
67 if (line.startsWith('+') && !line.startsWith('+++')) {
68 lines.push(line.slice(1))
69 }
70 }
71 return lines.join('\n')
72}
73
74function isWorkflowPath(path: string) {
75 return (
76 path.startsWith('.github/workflows/') ||
77 path.endsWith('/action.yml') ||
78 path.endsWith('/action.yaml') ||
79 path === 'action.yml' ||
80 path === 'action.yaml'
81 )
82}
83
84function isPackageJson(path: string) {
85 return /(^|\/)package\.json$/.test(path)
86}
87
88/**
89 * Return alert reasons for malware-shaped changes. Empty means clean.
90 */
91export function scanPullSecurity(files: Array<PullFile>) {
92 const reasons = []
93 for (const file of files) {
94 const paths =
95 file.previousPath === undefined || file.previousPath === null
96 ? [file.path]
97 : [file.previousPath, file.path]
98 for (const path of new Set(paths)) {
99 if (
100 (SENSITIVE_PATH.test(path) || SENSITIVE_SCRIPT.test(path)) &&
101 !isWorkflowPath(path)
102 ) {
103 reasons.push(
104 `${path}: changes security-sensitive instructions or automation`,
105 )
106 }
107 if (isWorkflowPath(path)) {
108 reasons.push(`${path}: changes a workflow`)
109 }
110 }
111 const binaryPath = paths.find((path) => BINARY_PATH.test(path))
112 if (binaryPath !== undefined) {
113 reasons.push(`${binaryPath}: new binary or script payload`)
114 continue
115 }
116 if (file.patch === null) {
117 reasons.push(`${file.path}: patch unavailable`)
118 continue
119 }
120 const added = addedText(file.patch)
121 const workflowPath = paths.find((path) => isWorkflowPath(path))
122 if (workflowPath !== undefined) {
123 if (added.includes('pull_request_target')) {
124 reasons.push(`${workflowPath}: adds pull_request_target`)
125 }
126 }
127 if (added.length === 0) continue
128 if (
129 PIPE_SHELL.test(added) ||
130 POWERSHELL_ENC.test(added) ||
131 REVERSE_SHELL.test(added)
132 ) {
133 reasons.push(`${file.path}: shell download or reverse shell`)
134 }
135 if (isPackageJson(file.path)) {
136 for (const match of added.matchAll(LIFECYCLE)) {
137 const script = match[1] ?? ''
138 if (NETWORK.test(script)) {
139 reasons.push(`${file.path}: ${match[0]} fetches the network`)
140 }
141 }
142 }
143 }
144 return { ok: reasons.length === 0, reasons }
145}
146
147/** Validate a complete `git diff` before it can reach the host worktree. */
148export function scanGeneratedDiff(diff: string, secrets: Array<string> = []) {
149 const reasons: Array<string> = []
150 if (Buffer.byteLength(diff, 'utf8') > 1_000_000) {
151 return { ok: false, reasons: ['generated diff is larger than 1 MB'] }
152 }
153 if (diff.trim().length === 0) return { ok: true, reasons }
154 if (secrets.some((secret) => secret.length > 0 && diff.includes(secret))) {
155 return { ok: false, reasons: ['generated diff contains a sandbox secret'] }
156 }
157
158 const starts = [...diff.matchAll(/^diff --git /gm)].map(
159 (match) => match.index ?? 0,
160 )
161 if (starts.length === 0 || diff.slice(0, starts[0]).trim().length > 0) {
162 return {
163 ok: false,
164 reasons: ['generated diff has content before its first file header'],
165 }
166 }
167
168 const files = []
169 for (let index = 0; index < starts.length; index++) {
170 const start = starts[index]
171 const end = starts[index + 1] ?? diff.length
172 const section = diff.slice(start, end)
173 const firstLineEnd = section.indexOf('\n')
174 const firstLine = section.slice(
175 0,
176 firstLineEnd === -1 ? section.length : firstLineEnd,
177 )
178 const header = /^diff --git a\/([^"\t]+) b\/([^"\t]+)$/.exec(firstLine)
179 if (header === null || header[1] === undefined || header[2] === undefined) {
180 reasons.push('generated diff has an unsupported file header')
181 continue
182 }
183 const oldPath = header[1]
184 const path = header[2]
185 if (oldPath !== path) {
186 reasons.push(`${path}: renames are not allowed in generated edits`)
187 continue
188 }
189 if (
190 path.startsWith('/') ||
191 path.includes('\\') ||
192 path.split('/').some((part) => part === '..')
193 ) {
194 reasons.push(`${path}: path escapes the worktree`)
195 continue
196 }
197 if (
198 /^index .* (?:120000|160000)$/m.test(section) ||
199 /^(?:(?:new|old|deleted) file mode|(?:new|old) mode) (?:120000|160000)$/m.test(
200 section,
201 )
202 ) {
203 reasons.push(`${path}: creates or changes a symlink or submodule`)
204 continue
205 }
206 if (/^(?:new file mode|new mode) 100755$/m.test(section)) {
207 reasons.push(`${path}: creates an executable file`)
208 continue
209 }
210 if (
211 /^GIT binary patch$/m.test(section) ||
212 /^Binary files /m.test(section)
213 ) {
214 reasons.push(`${path}: contains a binary patch`)
215 continue
216 }
217 if (LOCKFILE.test(path)) {
218 reasons.push(`${path}: generated edits cannot change lockfiles`)
219 continue
220 }
221 if (isPackageJson(path)) {
222 reasons.push(`${path}: generated edits cannot change package manifests`)
223 continue
224 }
225 const headerBlock = section.split(/^@@/m, 1)[0] ?? ''
226 const oldHeaders = [...headerBlock.matchAll(/^--- (.+)$/gm)]
227 const newHeaders = [...headerBlock.matchAll(/^\+\+\+ (.+)$/gm)]
228 const patchOldPath = oldHeaders[0]?.[1]
229 const patchNewPath = newHeaders[0]?.[1]
230 const normalPaths =
231 patchOldPath === `a/${oldPath}` && patchNewPath === `b/${path}`
232 const createdPath =
233 /^new file mode /m.test(headerBlock) &&
234 patchOldPath === '/dev/null' &&
235 patchNewPath === `b/${path}`
236 const deletedPath =
237 /^deleted file mode /m.test(headerBlock) &&
238 patchOldPath === `a/${oldPath}` &&
239 patchNewPath === '/dev/null'
240 if (
241 oldHeaders.length !== 1 ||
242 newHeaders.length !== 1 ||
243 (!normalPaths && !createdPath && !deletedPath) ||
244 /^(?:rename|copy) (?:from|to) /m.test(headerBlock)
245 ) {
246 reasons.push(`${path}: patch path headers do not match the file header`)
247 continue
248 }
249 // Hunk counts distinguish source lines from an extra headerless file patch.
250 const lines = section.slice(headerBlock.length).split('\n')
251 if (lines.at(-1) === '') lines.pop()
252 let oldLines = 0
253 let newLines = 0
254 let validHunks = lines[0]?.startsWith('@@ ') === true
255 let previousBodyLine = false
256 for (const line of lines) {
257 if (line.startsWith('@@')) {
258 const hunk = /^@@ -\d+(?:,(\d+))? \+\d+(?:,(\d+))? @@(?:.*)$/.exec(line)
259 if (hunk === null || oldLines !== 0 || newLines !== 0) {
260 validHunks = false
261 break
262 }
263 oldLines = Number(hunk[1] ?? 1)
264 newLines = Number(hunk[2] ?? 1)
265 previousBodyLine = false
266 continue
267 }
268 if (line === '\\ No newline at end of file' && previousBodyLine) {
269 previousBodyLine = false
270 continue
271 }
272 const prefix = line[0]
273 if (prefix !== ' ' && prefix !== '-' && prefix !== '+') {
274 validHunks = false
275 break
276 }
277 if (prefix !== '+') oldLines -= 1
278 if (prefix !== '-') newLines -= 1
279 if (oldLines < 0 || newLines < 0) {
280 validHunks = false
281 break
282 }
283 previousBodyLine = true
284 }
285 if (!validHunks || oldLines !== 0 || newLines !== 0) {
286 reasons.push(`${path}: malformed hunks or extra file patch`)
287 continue
288 }
289 files.push({ path, patch: section })
290 }
291 reasons.push(...scanPullSecurity(files).reasons)
292 return { ok: reasons.length === 0, reasons }
293}
294
295/** Audit the same fixed Git snapshot used by the model. */
296export function auditPullSecurity(
297 snapshot: Awaited<ReturnType<typeof readPullSnapshot>>,
298) {
299 const reasons = [...scanPullSecurity(snapshot.files).reasons]
300 for (const file of snapshot.files) {
301 if (LOCKFILE.test(file.path)) {
302 reasons.push(`${file.path}: lockfile changes require manual review`)
303 }
304 if (
305 file.headMode !== '000000' &&
306 file.headMode !== '100644' &&
307 file.headMode !== '100755'
308 ) {
309 reasons.push(`${file.path}: unsafe Git mode ${file.headMode}`)
310 }
311 if (
312 file.baseMode !== '000000' &&
313 file.baseMode !== '100644' &&
314 file.baseMode !== '100755'
315 ) {
316 reasons.push(`${file.path}: unsafe base Git mode ${file.baseMode}`)
317 }
318 if (file.headMode === '100755' && file.baseMode !== '100755') {
319 reasons.push(`${file.path}: becomes executable`)
320 }
321 if (!isPackageJson(file.path) || file.headMode === '000000') continue
322 try {
323 if (file.after === null) throw new Error('missing package manifest')
324 const added = findNewDependencies(file.before ?? '{}', file.after)
325 if (added.length > 0)
326 reasons.push(`${file.path}: adds dependencies: ${added.join(', ')}`)
327 } catch (error) {
328 const message = error instanceof Error ? error.message : String(error)
329 reasons.push(`${file.path}: could not verify dependencies: ${message}`)
330 }
331 }
332 return { ok: reasons.length === 0, reasons }
333}