Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

security.ts

77 lines2.3 KB

1/**
2 * Host-side malware scan for a PR file list. High-confidence alerts only.
3 * A clean scan is required before the bot adds `secure` or approves workflows.
4 */
5​
6export type PullFile = { path: string; patch: string | null }
7​
8const BINARY_PATH = /\.(?:exe|dll|so|dylib|scr|bat|cmd|ps1)$/i
9const PIPE_SHELL =
10 /(?:curl|wget|fetch)\b[^\n]{0,200}\|\s*(?:\S*\/)?(?:ba)?sh\b/i
11const POWERSHELL_ENC = /powershell(?:\.exe)?[^\n]{0,80}-enc(?:odedcommand)?\b/i
12const REVERSE_SHELL = /\/dev\/tcp\/|bash\s+-i\s+>&\s*\/dev\/tcp/i
13const LIFECYCLE = /"(?:preinstall|postinstall|prepublishOnly)"\s*:\s*"([^"]*)"/g
14const NETWORK =
15 /https?:\/\/|curl\b|wget\b|invoke-webrequest\b|node\s+-e\b|git\s+clone\b/i
16​
17function addedText(patch: string | null) {
18 if (patch === null) return ''
19 const lines = []
20 for (const line of patch.split('\n')) {
21 if (line.startsWith('+') && !line.startsWith('+++')) {
22 lines.push(line.slice(1))
23 }
24 }
25 return lines.join('\n')
27​
28function isWorkflowPath(path: string) {
29 return (
30 path.startsWith('.github/workflows/') ||
31 path.endsWith('/action.yml') ||
32 path.endsWith('/action.yaml') ||
33 path === 'action.yml' ||
34 path === 'action.yaml'
35 )
37​
38function isPackageJson(path: string) {
39 return /(^|\/)package\.json$/.test(path)
41​
42/**
43 * Return alert reasons for malware-shaped changes. Empty means clean.
44 */
45export function scanPullSecurity(files: Array<PullFile>) {
46 const reasons = []
47 for (const file of files) {
48 if (BINARY_PATH.test(file.path)) {
49 reasons.push(`${file.path}: new binary or script payload`)
50 continue
51 }
52 const added = addedText(file.patch)
53 if (isWorkflowPath(file.path)) {
54 reasons.push(`${file.path}: changes a workflow`)
55 if (added.includes('pull_request_target')) {
56 reasons.push(`${file.path}: adds pull_request_target`)
57 }
58 }
59 if (added.length === 0) continue
60 if (
61 PIPE_SHELL.test(added) ||
62 POWERSHELL_ENC.test(added) ||
63 REVERSE_SHELL.test(added)
64 ) {
65 reasons.push(`${file.path}: shell download or reverse shell`)
66 }
67 if (isPackageJson(file.path)) {
68 for (const match of added.matchAll(LIFECYCLE)) {
69 const script = match[1] ?? ''
70 if (NETWORK.test(script)) {
71 reasons.push(`${file.path}: ${match[0]} fetches the network`)
72 }
73 }
74 }
75 }
76 return { ok: reasons.length === 0, reasons }