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/rules/yaml.js CHANGED
@@ -1,186 +1,186 @@
1
- /**
2
- * Minimal YAML subset parser for rule packs.
3
- *
4
- * Rule packs are data (strings, numbers, booleans, lists of maps). Supporting a
5
- * full YAML implementation would add a dependency to a plugin that deliberately
6
- * ships none, so this parser accepts exactly the shape the packs use:
7
- *
8
- * schema: 1
9
- * rules:
10
- * - id: VG-CRED-01
11
- * severity: blocker
12
- * patterns:
13
- * - re: '\\bAKIA[0-9A-Z]{16}\\b'
14
- * label: AWS Access Key
15
- *
16
- * Supported: nested mappings, block sequences, single/double quoted scalars,
17
- * booleans, numbers, null, comments and `---` document markers. Not supported:
18
- * flow collections (`[a, b]`, `{a: b}`), anchors, multi-line block scalars.
19
- * Anything unsupported throws a `YamlParseError`, and the loader keeps the
20
- * built-in defaults instead of silently loading a half-parsed pack.
21
- *
22
- * @module rules/yaml
23
- */
24
-
25
- export class YamlParseError extends Error {}
26
-
27
- /**
28
- * @param {string} source
29
- * @returns {any}
30
- */
31
- export function parseYaml(source) {
32
- const lines = []
33
- const rawLines = String(source ?? '').split(/\r?\n/)
34
- for (let index = 0; index < rawLines.length; index += 1) {
35
- const raw = rawLines[index]
36
- const trimmed = raw.trim()
37
- if (trimmed === '' || trimmed.startsWith('#')) continue
38
- if (trimmed === '---' || trimmed === '...') continue
39
- const indent = raw.length - raw.trimStart().length
40
- if (tabIndented(raw)) throw new YamlParseError(`第 ${index + 1} 行使用制表符缩进`)
41
- lines.push({ indent, text: trimmed, line: index + 1 })
42
- }
43
- let cursor = 0
44
-
45
- const peek = () => lines[cursor]
46
-
47
- const parseBlock = indent => {
48
- const first = peek()
49
- if (!first || first.indent < indent) return null
50
- return first.text.startsWith('-') ? parseSequence(first.indent) : parseMapping(first.indent)
51
- }
52
-
53
- const parseSequence = indent => {
54
- /** @type {any[]} */
55
- const out = []
56
- while (cursor < lines.length) {
57
- const line = lines[cursor]
58
- if (line.indent !== indent || !line.text.startsWith('-')) break
59
- if (line.text === '-' || line.text === '- ') {
60
- cursor += 1
61
- out.push(parseBlock(indent + 1))
62
- continue
63
- }
64
- const rest = line.text.slice(1).trim()
65
- const key = keyOf(rest)
66
- if (key === null) {
67
- cursor += 1
68
- out.push(parseScalar(rest, line.line))
69
- continue
70
- }
71
- // `- key: value` starts a mapping item; its remaining keys are indented.
72
- const item = {}
73
- const value = valueOf(rest)
74
- cursor += 1
75
- if (value === '') {
76
- const child = parseBlock(indent + 2)
77
- item[key] = child ?? null
78
- } else {
79
- item[key] = parseScalar(value, line.line)
80
- }
81
- while (cursor < lines.length && lines[cursor].indent > indent) {
82
- const nested = lines[cursor]
83
- if (nested.indent !== indent + 2) throw new YamlParseError(`第 ${nested.line} 行缩进不一致`)
84
- mergeMappingEntry(item, nested, () => {
85
- cursor += 1
86
- }, () => parseBlock(indent + 2))
87
- }
88
- out.push(item)
89
- }
90
- return out
91
- }
92
-
93
- const parseMapping = indent => {
94
- /** @type {Record<string, any>} */
95
- const out = {}
96
- while (cursor < lines.length && lines[cursor].indent === indent) {
97
- const line = lines[cursor]
98
- if (line.text.startsWith('-')) break
99
- const key = keyOf(line.text)
100
- if (key === null) throw new YamlParseError(`第 ${line.line} 行缺少 "key:"`)
101
- const value = valueOf(line.text)
102
- cursor += 1
103
- if (value === '') {
104
- const child = parseBlock(indent + 1)
105
- out[key] = child ?? null
106
- } else {
107
- out[key] = parseScalar(value, line.line)
108
- }
109
- }
110
- return out
111
- }
112
-
113
- const mergeMappingEntry = (target, line, advance, parseNested) => {
114
- const key = keyOf(line.text)
115
- if (key === null) throw new YamlParseError(`第 ${line.line} 行缺少 "key:"`)
116
- const value = valueOf(line.text)
117
- if (value === '') {
118
- advance()
119
- target[key] = parseNested() ?? null
120
- } else {
121
- // Consume exactly this line. The previous version called a closure that
122
- // also parsed the next block, which silently dropped the third and later
123
- // keys of every sequence item (`source`/`flags` survived, `label` did not).
124
- advance()
125
- target[key] = parseScalar(value, line.line)
126
- }
127
- }
128
-
129
- const result = parseBlock(0)
130
- if (cursor < lines.length) throw new YamlParseError(`第 ${lines[cursor].line} 行无法解析`)
131
- return result
132
- }
133
-
134
- /** @param {string} raw */
135
- function tabIndented(raw) {
136
- return /^\t/.test(raw) || /^ *\t/.test(raw)
137
- }
138
-
139
- /**
140
- * @param {string} text
141
- * @returns {string|null}
142
- */
143
- function keyOf(text) {
144
- const match = /^([A-Za-z0-9_.-]+)\s*:(?:\s|$)/.exec(text)
145
- return match ? match[1] : null
146
- }
147
-
148
- /**
149
- * @param {string} text
150
- * @returns {string}
151
- */
152
- function valueOf(text) {
153
- const index = text.indexOf(':')
154
- if (index < 0) return ''
155
- return text.slice(index + 1).trim()
156
- }
157
-
158
- /**
159
- * @param {string} value
160
- * @param {number} line
161
- * @returns {any}
162
- */
163
- function parseScalar(value, line) {
164
- const text = value.trim()
165
- if (text === '') return ''
166
- if (text.startsWith('[') || text.startsWith('{')) {
167
- throw new YamlParseError(`第 ${line} 行不支持流式集合,请用缩进列表`)
168
- }
169
- if (text.startsWith("'")) {
170
- if (!text.endsWith("'") || text.length < 2) throw new YamlParseError(`第 ${line} 行单引号未闭合`)
171
- return text.slice(1, -1).replace(/''/g, "'")
172
- }
173
- if (text.startsWith('"')) {
174
- if (!text.endsWith('"') || text.length < 2) throw new YamlParseError(`第 ${line} 行双引号未闭合`)
175
- try {
176
- return JSON.parse(text)
177
- } catch {
178
- throw new YamlParseError(`第 ${line} 行双引号字符串转义无效`)
179
- }
180
- }
181
- if (text === 'true') return true
182
- if (text === 'false') return false
183
- if (text === 'null' || text === '~') return null
184
- if (/^-?\d+(?:\.\d+)?$/.test(text)) return Number(text)
185
- return text
186
- }
1
+ /**
2
+ * Minimal YAML subset parser for rule packs.
3
+ *
4
+ * Rule packs are data (strings, numbers, booleans, lists of maps). Supporting a
5
+ * full YAML implementation would add a dependency to a plugin that deliberately
6
+ * ships none, so this parser accepts exactly the shape the packs use:
7
+ *
8
+ * schema: 1
9
+ * rules:
10
+ * - id: VG-CRED-01
11
+ * severity: blocker
12
+ * patterns:
13
+ * - re: '\\bAKIA[0-9A-Z]{16}\\b'
14
+ * label: AWS Access Key
15
+ *
16
+ * Supported: nested mappings, block sequences, single/double quoted scalars,
17
+ * booleans, numbers, null, comments and `---` document markers. Not supported:
18
+ * flow collections (`[a, b]`, `{a: b}`), anchors, multi-line block scalars.
19
+ * Anything unsupported throws a `YamlParseError`, and the loader keeps the
20
+ * built-in defaults instead of silently loading a half-parsed pack.
21
+ *
22
+ * @module rules/yaml
23
+ */
24
+
25
+ export class YamlParseError extends Error {}
26
+
27
+ /**
28
+ * @param {string} source
29
+ * @returns {any}
30
+ */
31
+ export function parseYaml(source) {
32
+ const lines = []
33
+ const rawLines = String(source ?? '').split(/\r?\n/)
34
+ for (let index = 0; index < rawLines.length; index += 1) {
35
+ const raw = rawLines[index]
36
+ const trimmed = raw.trim()
37
+ if (trimmed === '' || trimmed.startsWith('#')) continue
38
+ if (trimmed === '---' || trimmed === '...') continue
39
+ const indent = raw.length - raw.trimStart().length
40
+ if (tabIndented(raw)) throw new YamlParseError(`第 ${index + 1} 行使用制表符缩进`)
41
+ lines.push({ indent, text: trimmed, line: index + 1 })
42
+ }
43
+ let cursor = 0
44
+
45
+ const peek = () => lines[cursor]
46
+
47
+ const parseBlock = indent => {
48
+ const first = peek()
49
+ if (!first || first.indent < indent) return null
50
+ return first.text.startsWith('-') ? parseSequence(first.indent) : parseMapping(first.indent)
51
+ }
52
+
53
+ const parseSequence = indent => {
54
+ /** @type {any[]} */
55
+ const out = []
56
+ while (cursor < lines.length) {
57
+ const line = lines[cursor]
58
+ if (line.indent !== indent || !line.text.startsWith('-')) break
59
+ if (line.text === '-' || line.text === '- ') {
60
+ cursor += 1
61
+ out.push(parseBlock(indent + 1))
62
+ continue
63
+ }
64
+ const rest = line.text.slice(1).trim()
65
+ const key = keyOf(rest)
66
+ if (key === null) {
67
+ cursor += 1
68
+ out.push(parseScalar(rest, line.line))
69
+ continue
70
+ }
71
+ // `- key: value` starts a mapping item; its remaining keys are indented.
72
+ const item = {}
73
+ const value = valueOf(rest)
74
+ cursor += 1
75
+ if (value === '') {
76
+ const child = parseBlock(indent + 2)
77
+ item[key] = child ?? null
78
+ } else {
79
+ item[key] = parseScalar(value, line.line)
80
+ }
81
+ while (cursor < lines.length && lines[cursor].indent > indent) {
82
+ const nested = lines[cursor]
83
+ if (nested.indent !== indent + 2) throw new YamlParseError(`第 ${nested.line} 行缩进不一致`)
84
+ mergeMappingEntry(item, nested, () => {
85
+ cursor += 1
86
+ }, () => parseBlock(indent + 2))
87
+ }
88
+ out.push(item)
89
+ }
90
+ return out
91
+ }
92
+
93
+ const parseMapping = indent => {
94
+ /** @type {Record<string, any>} */
95
+ const out = {}
96
+ while (cursor < lines.length && lines[cursor].indent === indent) {
97
+ const line = lines[cursor]
98
+ if (line.text.startsWith('-')) break
99
+ const key = keyOf(line.text)
100
+ if (key === null) throw new YamlParseError(`第 ${line.line} 行缺少 "key:"`)
101
+ const value = valueOf(line.text)
102
+ cursor += 1
103
+ if (value === '') {
104
+ const child = parseBlock(indent + 1)
105
+ out[key] = child ?? null
106
+ } else {
107
+ out[key] = parseScalar(value, line.line)
108
+ }
109
+ }
110
+ return out
111
+ }
112
+
113
+ const mergeMappingEntry = (target, line, advance, parseNested) => {
114
+ const key = keyOf(line.text)
115
+ if (key === null) throw new YamlParseError(`第 ${line.line} 行缺少 "key:"`)
116
+ const value = valueOf(line.text)
117
+ if (value === '') {
118
+ advance()
119
+ target[key] = parseNested() ?? null
120
+ } else {
121
+ // Consume exactly this line. The previous version called a closure that
122
+ // also parsed the next block, which silently dropped the third and later
123
+ // keys of every sequence item (`source`/`flags` survived, `label` did not).
124
+ advance()
125
+ target[key] = parseScalar(value, line.line)
126
+ }
127
+ }
128
+
129
+ const result = parseBlock(0)
130
+ if (cursor < lines.length) throw new YamlParseError(`第 ${lines[cursor].line} 行无法解析`)
131
+ return result
132
+ }
133
+
134
+ /** @param {string} raw */
135
+ function tabIndented(raw) {
136
+ return /^\t/.test(raw) || /^ *\t/.test(raw)
137
+ }
138
+
139
+ /**
140
+ * @param {string} text
141
+ * @returns {string|null}
142
+ */
143
+ function keyOf(text) {
144
+ const match = /^([A-Za-z0-9_.-]+)\s*:(?:\s|$)/.exec(text)
145
+ return match ? match[1] : null
146
+ }
147
+
148
+ /**
149
+ * @param {string} text
150
+ * @returns {string}
151
+ */
152
+ function valueOf(text) {
153
+ const index = text.indexOf(':')
154
+ if (index < 0) return ''
155
+ return text.slice(index + 1).trim()
156
+ }
157
+
158
+ /**
159
+ * @param {string} value
160
+ * @param {number} line
161
+ * @returns {any}
162
+ */
163
+ function parseScalar(value, line) {
164
+ const text = value.trim()
165
+ if (text === '') return ''
166
+ if (text.startsWith('[') || text.startsWith('{')) {
167
+ throw new YamlParseError(`第 ${line} 行不支持流式集合,请用缩进列表`)
168
+ }
169
+ if (text.startsWith("'")) {
170
+ if (!text.endsWith("'") || text.length < 2) throw new YamlParseError(`第 ${line} 行单引号未闭合`)
171
+ return text.slice(1, -1).replace(/''/g, "'")
172
+ }
173
+ if (text.startsWith('"')) {
174
+ if (!text.endsWith('"') || text.length < 2) throw new YamlParseError(`第 ${line} 行双引号未闭合`)
175
+ try {
176
+ return JSON.parse(text)
177
+ } catch {
178
+ throw new YamlParseError(`第 ${line} 行双引号字符串转义无效`)
179
+ }
180
+ }
181
+ if (text === 'true') return true
182
+ if (text === 'false') return false
183
+ if (text === 'null' || text === '~') return null
184
+ if (/^-?\d+(?:\.\d+)?$/.test(text)) return Number(text)
185
+ return text
186
+ }