dsh-vigil 0.0.1 → 0.0.2

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.
package/src/audit/ast.js CHANGED
@@ -1,213 +1,213 @@
1
- /**
2
- * AST-assisted alias analysis (best effort, acorn).
3
- *
4
- * The regex rules can see "this line imports child_process" and "this line
5
- * calls spawn(". They cannot follow a local alias:
6
- *
7
- * const cp = require('node:child_process')
8
- * const run = cp.exec
9
- * run(userInput) // ← invisible to line-based rules
10
- *
11
- * This module parses the file once and returns the locally bound names of
12
- * capability-bearing APIs (child_process, eval, fetch) plus their call sites.
13
- * It never evaluates code, never resolves network resources, and any parse
14
- * failure returns `{ ok: false }` so the caller keeps the regex-only result.
15
- *
16
- * @module audit/ast
17
- */
18
-
19
- import { createRequire } from 'node:module'
20
-
21
- // Loaded synchronously so the scanner stays synchronous; a missing acorn must
22
- // degrade to regex-only instead of breaking the whole plugin activation.
23
- let acorn = null
24
- try {
25
- acorn = createRequire(import.meta.url)('acorn')
26
- } catch {
27
- acorn = null
28
- }
29
-
30
- const PARSE_OPTIONS = {
31
- ecmaVersion: 'latest',
32
- sourceType: 'module',
33
- allowHashBang: true,
34
- allowAwaitOutsideFunction: true,
35
- // Line numbers are required for findings; without this every call is line 0.
36
- locations: true,
37
- }
38
-
39
- const CHILD_PROCESS_MODULE = /^(?:node:)?child_process$/
40
-
41
- /**
42
- * @typedef {{ name: string, kind: 'child_process'|'eval'|'fetch', line: number }} AliasedCall
43
- * @typedef {{ ok: boolean, aliases: Record<string, string>, calls: AliasedCall[], error?: string }} AstAnalysis
44
- */
45
-
46
- /**
47
- * @param {string} text
48
- * @returns {AstAnalysis}
49
- */
50
- export function analyzeAliases(text) {
51
- if (!acorn || typeof acorn.parse !== 'function') {
52
- return { ok: false, aliases: {}, calls: [], error: 'acorn 不可用(仅使用正则规则)' }
53
- }
54
- let ast
55
- try {
56
- ast = acorn.parse(String(text ?? ''), PARSE_OPTIONS)
57
- } catch (moduleError) {
58
- try {
59
- // Plain scripts (`with`, top-level return) are not modules.
60
- ast = acorn.parse(String(text ?? ''), { ...PARSE_OPTIONS, sourceType: 'script' })
61
- } catch {
62
- return { ok: false, aliases: {}, calls: [], error: moduleError instanceof Error ? moduleError.message : String(moduleError) }
63
- }
64
- }
65
-
66
- /** @type {Map<string, string>} local name -> capability kind */
67
- const aliases = new Map()
68
-
69
- // ---- pass 1: collect declarations, then bind them in source order -------
70
- // The generic walk visits children in reverse push order, so binding has to
71
- // happen sorted by position: `const run = cp.exec` must see `cp` already.
72
- /** @type {Array<{ start: number, name?: string, kind?: string, pattern?: any, init?: any }>} */
73
- const declarations = []
74
- walkAst(ast, node => {
75
- if (node.type === 'ImportDeclaration' && typeof node.source?.value === 'string') {
76
- const source = node.source.value
77
- const kind = CHILD_PROCESS_MODULE.test(source) ? 'child_process' : null
78
- if (!kind) return
79
- for (const specifier of node.specifiers ?? []) {
80
- const local = specifier.local?.name
81
- if (local) declarations.push({ start: specifier.start ?? node.start ?? 0, name: local, kind })
82
- }
83
- return
84
- }
85
- if (node.type === 'VariableDeclarator' && node.id && node.init) {
86
- declarations.push({ start: node.start ?? 0, pattern: node.id, init: node.init })
87
- }
88
- })
89
- declarations.sort((left, right) => left.start - right.start)
90
- for (const declaration of declarations) {
91
- if (declaration.name) {
92
- aliases.set(declaration.name, declaration.kind)
93
- continue
94
- }
95
- const kind = capabilityOf(declaration.init, aliases)
96
- if (kind) bindPattern(declaration.pattern, kind, aliases)
97
- }
98
-
99
- // ---- pass 2: call sites, resolved in source order -----------------------
100
- /** @type {Array<any>} */
101
- const callNodes = []
102
- walkAst(ast, node => {
103
- if (node.type === 'CallExpression' && node.callee) callNodes.push(node)
104
- })
105
- callNodes.sort((left, right) => (left.start ?? 0) - (right.start ?? 0))
106
- /** @type {AliasedCall[]} */
107
- const calls = []
108
- for (const node of callNodes) {
109
- const callee = node.callee
110
- const line = node.loc?.start?.line ?? 0
111
- if (line <= 1) continue
112
- if (callee.type === 'Identifier' && aliases.has(callee.name)) {
113
- calls.push({ name: callee.name, kind: aliases.get(callee.name), line })
114
- continue
115
- }
116
- // `cp.exec(...)`: the object is an aliased child_process namespace.
117
- if (callee.type === 'MemberExpression' && callee.object?.type === 'Identifier') {
118
- const kind = aliases.get(callee.object.name)
119
- if (kind === 'child_process' && !callee.computed && callee.property?.name) {
120
- calls.push({ name: `child_process.${callee.property.name}`, kind, line })
121
- }
122
- }
123
- }
124
-
125
- /** @type {Record<string,string>} */
126
- const aliasRecord = {}
127
- for (const [name, kind] of aliases) aliasRecord[name] = kind
128
- return { ok: true, aliases: aliasRecord, calls }
129
- }
130
-
131
- /**
132
- * What capability does this expression evaluate to, given known aliases?
133
- * @param {any} node
134
- * @param {Map<string,string>} aliases
135
- * @returns {string|null}
136
- */
137
- function capabilityOf(node, aliases) {
138
- if (!node || typeof node !== 'object') return null
139
- if (node.type === 'Identifier') {
140
- if (node.name === 'eval') return 'eval'
141
- if (node.name === 'fetch') return 'fetch'
142
- return aliases.get(node.name) ?? null
143
- }
144
- if (node.type === 'MemberExpression' && !node.computed) {
145
- const property = node.property?.name
146
- const object = node.object
147
- if (object?.type === 'Identifier' && aliases.get(object.name) === 'child_process') return 'child_process'
148
- if (object?.type === 'Identifier' && object.name === 'globalThis' && (property === 'eval' || property === 'fetch')) {
149
- return property
150
- }
151
- if (object?.type === 'Identifier' && object.name === 'window' && property === 'fetch') return 'fetch'
152
- // `cp.exec` where cp is a child_process alias is handled by the base case.
153
- }
154
- if (node.type === 'CallExpression') {
155
- // require('child_process') / require('node:child_process')
156
- const callee = node.callee
157
- const argument = node.arguments?.[0]
158
- if (callee?.type === 'Identifier' && callee.name === 'require'
159
- && argument?.type === 'Literal' && typeof argument.value === 'string'
160
- && CHILD_PROCESS_MODULE.test(argument.value)) {
161
- return 'child_process'
162
- }
163
- }
164
- if (node.type === 'AwaitExpression') return capabilityOf(node.argument, aliases)
165
- return null
166
- }
167
-
168
- /**
169
- * Bind a declaration pattern (Identifier / ObjectPattern) to a capability.
170
- * @param {any} pattern
171
- * @param {string} kind
172
- * @param {Map<string,string>} aliases
173
- */
174
- function bindPattern(pattern, kind, aliases) {
175
- if (!pattern || typeof pattern !== 'object') return
176
- if (pattern.type === 'Identifier' && typeof pattern.name === 'string') {
177
- aliases.set(pattern.name, kind)
178
- return
179
- }
180
- if (pattern.type === 'ObjectPattern') {
181
- for (const property of pattern.properties ?? []) {
182
- if (property?.type !== 'Property') continue
183
- const local = property.value?.type === 'Identifier' ? property.value.name : null
184
- if (local) aliases.set(local, kind)
185
- }
186
- }
187
- }
188
-
189
- /**
190
- * Minimal generic AST walker: visits every node object reachable from `root`
191
- * (skips loc/range/comments to stay cheap).
192
- * @param {any} root
193
- * @param {(node: any) => void} visit
194
- */
195
- function walkAst(root, visit) {
196
- /** @type {any[]} */
197
- const stack = [root]
198
- const seen = new Set()
199
- while (stack.length > 0) {
200
- const node = stack.pop()
201
- if (!node || typeof node !== 'object' || seen.has(node)) continue
202
- seen.add(node)
203
- if (typeof node.type === 'string') visit(node)
204
- for (const [key, value] of Object.entries(node)) {
205
- if (key === 'loc' || key === 'range' || key === 'start' || key === 'end' || key === 'parent') continue
206
- if (Array.isArray(value)) {
207
- for (const item of value) if (item && typeof item === 'object') stack.push(item)
208
- } else if (value && typeof value === 'object') {
209
- stack.push(value)
210
- }
211
- }
212
- }
213
- }
1
+ /**
2
+ * AST-assisted alias analysis (best effort, acorn).
3
+ *
4
+ * The regex rules can see "this line imports child_process" and "this line
5
+ * calls spawn(". They cannot follow a local alias:
6
+ *
7
+ * const cp = require('node:child_process')
8
+ * const run = cp.exec
9
+ * run(userInput) // ← invisible to line-based rules
10
+ *
11
+ * This module parses the file once and returns the locally bound names of
12
+ * capability-bearing APIs (child_process, eval, fetch) plus their call sites.
13
+ * It never evaluates code, never resolves network resources, and any parse
14
+ * failure returns `{ ok: false }` so the caller keeps the regex-only result.
15
+ *
16
+ * @module audit/ast
17
+ */
18
+
19
+ import { createRequire } from 'node:module'
20
+
21
+ // Loaded synchronously so the scanner stays synchronous; a missing acorn must
22
+ // degrade to regex-only instead of breaking the whole plugin activation.
23
+ let acorn = null
24
+ try {
25
+ acorn = createRequire(import.meta.url)('acorn')
26
+ } catch {
27
+ acorn = null
28
+ }
29
+
30
+ const PARSE_OPTIONS = {
31
+ ecmaVersion: 'latest',
32
+ sourceType: 'module',
33
+ allowHashBang: true,
34
+ allowAwaitOutsideFunction: true,
35
+ // Line numbers are required for findings; without this every call is line 0.
36
+ locations: true,
37
+ }
38
+
39
+ const CHILD_PROCESS_MODULE = /^(?:node:)?child_process$/
40
+
41
+ /**
42
+ * @typedef {{ name: string, kind: 'child_process'|'eval'|'fetch', line: number }} AliasedCall
43
+ * @typedef {{ ok: boolean, aliases: Record<string, string>, calls: AliasedCall[], error?: string }} AstAnalysis
44
+ */
45
+
46
+ /**
47
+ * @param {string} text
48
+ * @returns {AstAnalysis}
49
+ */
50
+ export function analyzeAliases(text) {
51
+ if (!acorn || typeof acorn.parse !== 'function') {
52
+ return { ok: false, aliases: {}, calls: [], error: 'acorn 不可用(仅使用正则规则)' }
53
+ }
54
+ let ast
55
+ try {
56
+ ast = acorn.parse(String(text ?? ''), PARSE_OPTIONS)
57
+ } catch (moduleError) {
58
+ try {
59
+ // Plain scripts (`with`, top-level return) are not modules.
60
+ ast = acorn.parse(String(text ?? ''), { ...PARSE_OPTIONS, sourceType: 'script' })
61
+ } catch {
62
+ return { ok: false, aliases: {}, calls: [], error: moduleError instanceof Error ? moduleError.message : String(moduleError) }
63
+ }
64
+ }
65
+
66
+ /** @type {Map<string, string>} local name -> capability kind */
67
+ const aliases = new Map()
68
+
69
+ // ---- pass 1: collect declarations, then bind them in source order -------
70
+ // The generic walk visits children in reverse push order, so binding has to
71
+ // happen sorted by position: `const run = cp.exec` must see `cp` already.
72
+ /** @type {Array<{ start: number, name?: string, kind?: string, pattern?: any, init?: any }>} */
73
+ const declarations = []
74
+ walkAst(ast, node => {
75
+ if (node.type === 'ImportDeclaration' && typeof node.source?.value === 'string') {
76
+ const source = node.source.value
77
+ const kind = CHILD_PROCESS_MODULE.test(source) ? 'child_process' : null
78
+ if (!kind) return
79
+ for (const specifier of node.specifiers ?? []) {
80
+ const local = specifier.local?.name
81
+ if (local) declarations.push({ start: specifier.start ?? node.start ?? 0, name: local, kind })
82
+ }
83
+ return
84
+ }
85
+ if (node.type === 'VariableDeclarator' && node.id && node.init) {
86
+ declarations.push({ start: node.start ?? 0, pattern: node.id, init: node.init })
87
+ }
88
+ })
89
+ declarations.sort((left, right) => left.start - right.start)
90
+ for (const declaration of declarations) {
91
+ if (declaration.name) {
92
+ aliases.set(declaration.name, declaration.kind)
93
+ continue
94
+ }
95
+ const kind = capabilityOf(declaration.init, aliases)
96
+ if (kind) bindPattern(declaration.pattern, kind, aliases)
97
+ }
98
+
99
+ // ---- pass 2: call sites, resolved in source order -----------------------
100
+ /** @type {Array<any>} */
101
+ const callNodes = []
102
+ walkAst(ast, node => {
103
+ if (node.type === 'CallExpression' && node.callee) callNodes.push(node)
104
+ })
105
+ callNodes.sort((left, right) => (left.start ?? 0) - (right.start ?? 0))
106
+ /** @type {AliasedCall[]} */
107
+ const calls = []
108
+ for (const node of callNodes) {
109
+ const callee = node.callee
110
+ const line = node.loc?.start?.line ?? 0
111
+ if (line <= 1) continue
112
+ if (callee.type === 'Identifier' && aliases.has(callee.name)) {
113
+ calls.push({ name: callee.name, kind: aliases.get(callee.name), line })
114
+ continue
115
+ }
116
+ // `cp.exec(...)`: the object is an aliased child_process namespace.
117
+ if (callee.type === 'MemberExpression' && callee.object?.type === 'Identifier') {
118
+ const kind = aliases.get(callee.object.name)
119
+ if (kind === 'child_process' && !callee.computed && callee.property?.name) {
120
+ calls.push({ name: `child_process.${callee.property.name}`, kind, line })
121
+ }
122
+ }
123
+ }
124
+
125
+ /** @type {Record<string,string>} */
126
+ const aliasRecord = {}
127
+ for (const [name, kind] of aliases) aliasRecord[name] = kind
128
+ return { ok: true, aliases: aliasRecord, calls }
129
+ }
130
+
131
+ /**
132
+ * What capability does this expression evaluate to, given known aliases?
133
+ * @param {any} node
134
+ * @param {Map<string,string>} aliases
135
+ * @returns {string|null}
136
+ */
137
+ function capabilityOf(node, aliases) {
138
+ if (!node || typeof node !== 'object') return null
139
+ if (node.type === 'Identifier') {
140
+ if (node.name === 'eval') return 'eval'
141
+ if (node.name === 'fetch') return 'fetch'
142
+ return aliases.get(node.name) ?? null
143
+ }
144
+ if (node.type === 'MemberExpression' && !node.computed) {
145
+ const property = node.property?.name
146
+ const object = node.object
147
+ if (object?.type === 'Identifier' && aliases.get(object.name) === 'child_process') return 'child_process'
148
+ if (object?.type === 'Identifier' && object.name === 'globalThis' && (property === 'eval' || property === 'fetch')) {
149
+ return property
150
+ }
151
+ if (object?.type === 'Identifier' && object.name === 'window' && property === 'fetch') return 'fetch'
152
+ // `cp.exec` where cp is a child_process alias is handled by the base case.
153
+ }
154
+ if (node.type === 'CallExpression') {
155
+ // require('child_process') / require('node:child_process')
156
+ const callee = node.callee
157
+ const argument = node.arguments?.[0]
158
+ if (callee?.type === 'Identifier' && callee.name === 'require'
159
+ && argument?.type === 'Literal' && typeof argument.value === 'string'
160
+ && CHILD_PROCESS_MODULE.test(argument.value)) {
161
+ return 'child_process'
162
+ }
163
+ }
164
+ if (node.type === 'AwaitExpression') return capabilityOf(node.argument, aliases)
165
+ return null
166
+ }
167
+
168
+ /**
169
+ * Bind a declaration pattern (Identifier / ObjectPattern) to a capability.
170
+ * @param {any} pattern
171
+ * @param {string} kind
172
+ * @param {Map<string,string>} aliases
173
+ */
174
+ function bindPattern(pattern, kind, aliases) {
175
+ if (!pattern || typeof pattern !== 'object') return
176
+ if (pattern.type === 'Identifier' && typeof pattern.name === 'string') {
177
+ aliases.set(pattern.name, kind)
178
+ return
179
+ }
180
+ if (pattern.type === 'ObjectPattern') {
181
+ for (const property of pattern.properties ?? []) {
182
+ if (property?.type !== 'Property') continue
183
+ const local = property.value?.type === 'Identifier' ? property.value.name : null
184
+ if (local) aliases.set(local, kind)
185
+ }
186
+ }
187
+ }
188
+
189
+ /**
190
+ * Minimal generic AST walker: visits every node object reachable from `root`
191
+ * (skips loc/range/comments to stay cheap).
192
+ * @param {any} root
193
+ * @param {(node: any) => void} visit
194
+ */
195
+ function walkAst(root, visit) {
196
+ /** @type {any[]} */
197
+ const stack = [root]
198
+ const seen = new Set()
199
+ while (stack.length > 0) {
200
+ const node = stack.pop()
201
+ if (!node || typeof node !== 'object' || seen.has(node)) continue
202
+ seen.add(node)
203
+ if (typeof node.type === 'string') visit(node)
204
+ for (const [key, value] of Object.entries(node)) {
205
+ if (key === 'loc' || key === 'range' || key === 'start' || key === 'end' || key === 'parent') continue
206
+ if (Array.isArray(value)) {
207
+ for (const item of value) if (item && typeof item === 'object') stack.push(item)
208
+ } else if (value && typeof value === 'object') {
209
+ stack.push(value)
210
+ }
211
+ }
212
+ }
213
+ }