pi-ssh-manager 0.0.0-stage → 0.2.0

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.
@@ -0,0 +1,824 @@
1
+ import { homedir } from "node:os";
2
+ import type { Stats } from "node:fs";
3
+ import { lstat, opendir, readFile, readlink, realpath, stat } from "node:fs/promises";
4
+ import path from "node:path";
5
+
6
+ const MAX_CONFIG_FILES = 128;
7
+ const MAX_CONFIG_FILE_BYTES = 1024 * 1024;
8
+ const MAX_TOTAL_CONFIG_BYTES = 8 * 1024 * 1024;
9
+ const MAX_CONFIG_NODES = 5000;
10
+ const MAX_DISCOVERED_HOSTS = 500;
11
+ const MAX_HOST_PATTERN_LENGTH = 255;
12
+ const MAX_OPTION_VALUE_LENGTH = 512;
13
+ const MAX_MULTI_VALUE_COUNT = 8;
14
+ const MAX_MATCHED_BLOCKS = 16;
15
+ const MAX_DECLARATIONS_PER_HOST = 16;
16
+ const MAX_WARNINGS = 16;
17
+ const MAX_INCLUDE_PATTERNS = 256;
18
+ const MAX_INCLUDE_PATTERN_LENGTH = 1024;
19
+ const MAX_DIRECTORY_ENTRIES = 10_000;
20
+ const MAX_INCLUDE_MATCHES = 128;
21
+
22
+ const SAFE_SINGLE_VALUE_OPTIONS = new Set([
23
+ "hostname",
24
+ "user",
25
+ "port",
26
+ "hostkeyalias",
27
+ "proxyjump",
28
+ "canonicalizehostname",
29
+ "batchmode",
30
+ "identitiesonly",
31
+ "preferredauthentications",
32
+ "passwordauthentication",
33
+ "kbdinteractiveauthentication",
34
+ "pubkeyauthentication",
35
+ "stricthostkeychecking",
36
+ "hashknownhosts",
37
+ "connecttimeout",
38
+ "serveraliveinterval",
39
+ "serveralivecountmax",
40
+ "requesttty",
41
+ "userknownhostsfile",
42
+ "globalknownhostsfile",
43
+ "addressfamily",
44
+ "compression",
45
+ "tcpkeepalive",
46
+ "exitonforwardfailure",
47
+ "forwardagent",
48
+ "forwardx11",
49
+ "loglevel",
50
+ ]);
51
+
52
+ const SAFE_MULTI_VALUE_OPTIONS = new Set(["identityfile", "certificatefile"]);
53
+
54
+ const HIDDEN_OPTIONS = new Set([
55
+ "proxycommand",
56
+ "remotecommand",
57
+ "localcommand",
58
+ "localforward",
59
+ "remoteforward",
60
+ "dynamicforward",
61
+ "sendenv",
62
+ "setenv",
63
+ "knownhostscommand",
64
+ "permitlocalcommand",
65
+ ]);
66
+
67
+ export interface SshConfigSource {
68
+ path: string;
69
+ line: number;
70
+ }
71
+
72
+ export interface SshHostSummary {
73
+ alias: string;
74
+ declaredAt: SshConfigSource[];
75
+ }
76
+
77
+ export interface ResolvedSshHost {
78
+ alias: string;
79
+ options: Record<string, string | string[]>;
80
+ matchedBlocks: SshConfigSource[];
81
+ hiddenOptions: string[];
82
+ unsupportedOptions: string[];
83
+ warnings: string[];
84
+ warningCategories: string[];
85
+ }
86
+
87
+ export interface SshConfigSnapshot {
88
+ found: boolean;
89
+ configPath: string;
90
+ configFiles: string[];
91
+ hosts: SshHostSummary[];
92
+ warnings: string[];
93
+ warningCategories: string[];
94
+ }
95
+
96
+ export interface SshConfigReadOptions {
97
+ homeDir?: string;
98
+ configPath?: string;
99
+ signal?: AbortSignal;
100
+ }
101
+
102
+ type ConfigDirective = {
103
+ kind: "directive";
104
+ keyword: string;
105
+ arguments: string[];
106
+ source: SshConfigSource;
107
+ };
108
+
109
+ type ConfigInclude = {
110
+ kind: "include";
111
+ documents: ConfigDocument[];
112
+ source: SshConfigSource;
113
+ };
114
+
115
+ type ConfigNode = ConfigDirective | ConfigInclude;
116
+
117
+ type ConfigDocument = {
118
+ path: string;
119
+ nodes: ConfigNode[];
120
+ };
121
+
122
+ type ParseBudget = {
123
+ count: number;
124
+ totalBytes: number;
125
+ nodeCount: number;
126
+ includePatterns: number;
127
+ directoryEntries: number;
128
+ configFiles: Set<string>;
129
+ warnings: string[];
130
+ warningCategories: Set<string>;
131
+ signal?: AbortSignal;
132
+ };
133
+
134
+ type EvaluationState = {
135
+ active: boolean;
136
+ matchedBlocks: SshConfigSource[];
137
+ matchedBlocksTruncated: boolean;
138
+ matchedDeclaredAlias: boolean;
139
+ options: Map<string, string | string[]>;
140
+ optionValuesTruncated: boolean;
141
+ multiValuesTruncated: boolean;
142
+ hiddenOptions: Set<string>;
143
+ unsupportedOptions: Set<string>;
144
+ hasUnevaluatedMatch: boolean;
145
+ };
146
+
147
+ const snapshotDocuments = new WeakMap<SshConfigSnapshot, ConfigDocument[]>();
148
+
149
+ export async function readSshConfig(
150
+ options: SshConfigReadOptions = {},
151
+ ): Promise<SshConfigSnapshot> {
152
+ const homeDir = path.resolve(options.homeDir ?? homedir());
153
+ const configPath = path.resolve(options.configPath ?? path.join(homeDir, ".ssh", "config"));
154
+ const budget: ParseBudget = {
155
+ count: 0,
156
+ totalBytes: 0,
157
+ nodeCount: 0,
158
+ includePatterns: 0,
159
+ directoryEntries: 0,
160
+ configFiles: new Set<string>(),
161
+ warnings: [],
162
+ warningCategories: new Set<string>(),
163
+ signal: options.signal,
164
+ };
165
+ budget.signal?.throwIfAborted();
166
+
167
+ const root = await loadConfigDocument(configPath, homeDir, path.dirname(configPath), budget, new Set());
168
+ if (!root) {
169
+ const snapshot: SshConfigSnapshot = {
170
+ found: false,
171
+ configPath,
172
+ configFiles: [],
173
+ hosts: [],
174
+ warnings: budget.warnings,
175
+ warningCategories: [...budget.warningCategories],
176
+ };
177
+ snapshotDocuments.set(snapshot, []);
178
+ return snapshot;
179
+ }
180
+
181
+ const documents = [root];
182
+ const declaredHosts = collectDeclaredHosts(documents, budget);
183
+ const discoveredHosts = [...declaredHosts.entries()]
184
+ .map(([alias, declaredAt]) => ({ alias, declaredAt }))
185
+ .filter(({ alias }) => evaluateHost(documents, alias, budget.signal).matchedDeclaredAlias)
186
+ .sort((left, right) => left.alias.localeCompare(right.alias, "en", { sensitivity: "variant" }));
187
+
188
+ const snapshot: SshConfigSnapshot = {
189
+ found: true,
190
+ configPath,
191
+ configFiles: [...budget.configFiles].sort((left, right) => left.localeCompare(right, "en")),
192
+ hosts: discoveredHosts,
193
+ warnings: budget.warnings,
194
+ warningCategories: [...budget.warningCategories].sort((left, right) => left.localeCompare(right, "en")),
195
+ };
196
+ snapshotDocuments.set(snapshot, documents);
197
+ return snapshot;
198
+ }
199
+
200
+ export function resolveSshHost(snapshot: SshConfigSnapshot, requestedAlias: string): ResolvedSshHost {
201
+ const alias = requestedAlias.trim();
202
+ const summary = snapshot.hosts.find((host) => host.alias === alias);
203
+ if (!summary) {
204
+ throw new Error(`[HOST_NOT_FOUND] OpenSSH 配置中没有主机别名:${requestedAlias}`);
205
+ }
206
+
207
+ const evaluated = evaluateHost(snapshotDocuments.get(snapshot) ?? [], summary.alias);
208
+ const options = Object.fromEntries(
209
+ [...evaluated.options.entries()].sort(([left], [right]) => left.localeCompare(right, "en")),
210
+ );
211
+ const warnings = [...snapshot.warnings];
212
+ if (evaluated.hasUnevaluatedMatch) {
213
+ warnings.push("配置包含无法安全求值的 Match 条件;结果未包含这些条件块中的选项。");
214
+ }
215
+ if (evaluated.matchedBlocksTruncated) {
216
+ warnings.push(`匹配配置块超过上限 ${MAX_MATCHED_BLOCKS},来源列表已截断。`);
217
+ }
218
+ if (evaluated.multiValuesTruncated) {
219
+ warnings.push(`多值配置项超过上限 ${MAX_MULTI_VALUE_COUNT},其余值已截断。`);
220
+ }
221
+ if (evaluated.optionValuesTruncated) {
222
+ warnings.push(`配置值超过长度上限 ${MAX_OPTION_VALUE_LENGTH},返回值已截断。`);
223
+ }
224
+
225
+ return {
226
+ alias: summary.alias,
227
+ options,
228
+ matchedBlocks: evaluated.matchedBlocks,
229
+ hiddenOptions: [...evaluated.hiddenOptions].sort((left, right) => left.localeCompare(right, "en")),
230
+ unsupportedOptions: [...evaluated.unsupportedOptions].sort(),
231
+ warnings,
232
+ warningCategories: [...new Set([
233
+ ...snapshot.warningCategories,
234
+ ...warnings.map(classifyWarning),
235
+ ])].sort((left, right) => left.localeCompare(right, "en")),
236
+ };
237
+ }
238
+
239
+ async function loadConfigDocument(
240
+ requestedPath: string,
241
+ homeDir: string,
242
+ includeBaseDir: string,
243
+ budget: ParseBudget,
244
+ stack: Set<string>,
245
+ ): Promise<ConfigDocument | undefined> {
246
+ budget.signal?.throwIfAborted();
247
+ if (budget.nodeCount >= MAX_CONFIG_NODES) {
248
+ addWarning(budget, `配置节点超过上限 ${MAX_CONFIG_NODES},其余配置已忽略。`);
249
+ return undefined;
250
+ }
251
+ if (isSensitiveSshDataFile(requestedPath)) {
252
+ addWarning(budget, `Include 指向已知 SSH 密钥或主机记录文件,已忽略:${path.basename(requestedPath)}`);
253
+ return undefined;
254
+ }
255
+ if (process.platform === "win32" && isUncPath(requestedPath)) {
256
+ addWarning(budget, "配置文件指向 UNC 路径;为避免隐式网络文件访问,已忽略。");
257
+ return undefined;
258
+ }
259
+ if (process.platform === "win32" && !(await isSafeWindowsIncludePath(requestedPath, budget))) {
260
+ return undefined;
261
+ }
262
+ if (budget.count >= MAX_CONFIG_FILES) {
263
+ addWarning(budget, `配置文件数量超过上限 ${MAX_CONFIG_FILES},其余 Include 已忽略。`);
264
+ return undefined;
265
+ }
266
+
267
+ let canonicalPath: string;
268
+ let fileStats: Stats;
269
+ try {
270
+ canonicalPath = await realpath(requestedPath);
271
+ fileStats = await stat(canonicalPath);
272
+ } catch {
273
+ return undefined;
274
+ }
275
+ budget.signal?.throwIfAborted();
276
+ if (!fileStats.isFile()) return undefined;
277
+ if (fileStats.size > MAX_CONFIG_FILE_BYTES) {
278
+ addWarning(budget, `配置文件超过 ${MAX_CONFIG_FILE_BYTES} 字节,已忽略:${canonicalPath}`);
279
+ return undefined;
280
+ }
281
+ if (budget.totalBytes + fileStats.size > MAX_TOTAL_CONFIG_BYTES) {
282
+ addWarning(budget, `配置文件总大小超过 ${MAX_TOTAL_CONFIG_BYTES} 字节,其余 Include 已忽略。`);
283
+ return undefined;
284
+ }
285
+
286
+ const stackKey = normalizePathKey(canonicalPath);
287
+ if (stack.has(stackKey)) {
288
+ addWarning(budget, `检测到循环 Include,已忽略:${canonicalPath}`);
289
+ return undefined;
290
+ }
291
+
292
+ budget.count += 1;
293
+ budget.totalBytes += fileStats.size;
294
+ budget.configFiles.add(canonicalPath);
295
+ const nextStack = new Set(stack);
296
+ nextStack.add(stackKey);
297
+
298
+ const text = await readFile(canonicalPath, { encoding: "utf8", signal: budget.signal });
299
+ const nodes: ConfigNode[] = [];
300
+ const lines = text.replace(/^\uFEFF/, "").split(/\r?\n/);
301
+
302
+ for (let index = 0; index < lines.length; index += 1) {
303
+ budget.signal?.throwIfAborted();
304
+ const tokens = tokenizeConfigLine(lines[index]);
305
+ const parsed = splitDirective(tokens);
306
+ if (!parsed) continue;
307
+
308
+ const source = { path: canonicalPath, line: index + 1 };
309
+ if (parsed.keyword !== "include") {
310
+ if (parsed.keyword === "host") {
311
+ const validPatterns = parsed.arguments.filter((pattern) => pattern.length <= MAX_HOST_PATTERN_LENGTH);
312
+ if (validPatterns.length !== parsed.arguments.length) {
313
+ addWarning(budget, `Host 模式超过长度上限 ${MAX_HOST_PATTERN_LENGTH},已忽略:${canonicalPath}:${index + 1}`);
314
+ }
315
+ if (!reserveConfigNode(budget)) break;
316
+ nodes.push({ kind: "directive", ...parsed, arguments: validPatterns, source });
317
+ } else {
318
+ if (!reserveConfigNode(budget)) break;
319
+ nodes.push({ kind: "directive", ...parsed, source });
320
+ }
321
+ continue;
322
+ }
323
+
324
+ const includedDocuments: ConfigDocument[] = [];
325
+ for (const includePattern of parsed.arguments) {
326
+ budget.signal?.throwIfAborted();
327
+ if (budget.includePatterns >= MAX_INCLUDE_PATTERNS) {
328
+ addWarning(budget, `Include 模式数量超过上限 ${MAX_INCLUDE_PATTERNS},其余模式已忽略。`);
329
+ break;
330
+ }
331
+ budget.includePatterns += 1;
332
+ const unsupportedReason = getUnsupportedIncludeReason(includePattern);
333
+ if (unsupportedReason) {
334
+ addWarning(budget, `${unsupportedReason}:${canonicalPath}:${index + 1}`);
335
+ continue;
336
+ }
337
+
338
+ const expandedPaths = await expandIncludePattern(includePattern, homeDir, includeBaseDir, budget);
339
+ for (const expandedPath of expandedPaths) {
340
+ const included = await loadConfigDocument(
341
+ expandedPath,
342
+ homeDir,
343
+ includeBaseDir,
344
+ budget,
345
+ nextStack,
346
+ );
347
+ if (included) includedDocuments.push(included);
348
+ }
349
+ }
350
+ if (!reserveConfigNode(budget)) break;
351
+ nodes.push({ kind: "include", documents: includedDocuments, source });
352
+ }
353
+
354
+ return { path: canonicalPath, nodes };
355
+ }
356
+
357
+ function collectDeclaredHosts(
358
+ documents: ConfigDocument[],
359
+ budget: ParseBudget,
360
+ ): Map<string, SshConfigSource[]> {
361
+ const hosts = new Map<string, SshConfigSource[]>();
362
+ let limitReached = false;
363
+
364
+ const visit = (document: ConfigDocument) => {
365
+ if (limitReached) return;
366
+ for (const node of document.nodes) {
367
+ if (limitReached) return;
368
+ if (node.kind === "include") {
369
+ for (const included of node.documents) visit(included);
370
+ continue;
371
+ }
372
+ if (node.keyword !== "host") continue;
373
+
374
+ for (const pattern of node.arguments) {
375
+ if (!isConcreteHostAlias(pattern)) continue;
376
+ const sources = hosts.get(pattern);
377
+ if (sources) {
378
+ if (
379
+ sources.length < MAX_DECLARATIONS_PER_HOST &&
380
+ !sources.some((source) => source.path === node.source.path && source.line === node.source.line)
381
+ ) {
382
+ sources.push(node.source);
383
+ }
384
+ continue;
385
+ }
386
+ if (hosts.size >= MAX_DISCOVERED_HOSTS) {
387
+ addWarning(budget, `主机别名超过上限 ${MAX_DISCOVERED_HOSTS},其余别名已忽略。`);
388
+ limitReached = true;
389
+ return;
390
+ }
391
+ hosts.set(pattern, [node.source]);
392
+ }
393
+ }
394
+ };
395
+
396
+ for (const document of documents) visit(document);
397
+ return hosts;
398
+ }
399
+
400
+ function evaluateHost(
401
+ documents: ConfigDocument[],
402
+ alias: string,
403
+ signal?: AbortSignal,
404
+ ): EvaluationState {
405
+ const state: EvaluationState = {
406
+ active: true,
407
+ matchedBlocks: [],
408
+ matchedBlocksTruncated: false,
409
+ matchedDeclaredAlias: false,
410
+ options: new Map(),
411
+ optionValuesTruncated: false,
412
+ multiValuesTruncated: false,
413
+ hiddenOptions: new Set(),
414
+ unsupportedOptions: new Set(),
415
+ hasUnevaluatedMatch: false,
416
+ };
417
+
418
+ for (const document of documents) {
419
+ signal?.throwIfAborted();
420
+ evaluateDocument(document, alias, state, signal);
421
+ }
422
+ return state;
423
+ }
424
+
425
+ function evaluateDocument(
426
+ document: ConfigDocument,
427
+ alias: string,
428
+ state: EvaluationState,
429
+ signal?: AbortSignal,
430
+ ): void {
431
+ for (const node of document.nodes) {
432
+ signal?.throwIfAborted();
433
+ if (node.kind === "include") {
434
+ if (state.active) {
435
+ for (const included of node.documents) evaluateDocument(included, alias, state, signal);
436
+ }
437
+ continue;
438
+ }
439
+
440
+ if (node.keyword === "host") {
441
+ state.active = hostMatchesPatterns(alias, node.arguments);
442
+ if (state.active) {
443
+ if (state.matchedBlocks.length < MAX_MATCHED_BLOCKS) state.matchedBlocks.push(node.source);
444
+ else state.matchedBlocksTruncated = true;
445
+ if (node.arguments.some((pattern) => isSameConcreteAlias(pattern, alias))) {
446
+ state.matchedDeclaredAlias = true;
447
+ }
448
+ }
449
+ continue;
450
+ }
451
+
452
+ if (node.keyword === "match") {
453
+ const isUnconditional = node.arguments.length === 1 && node.arguments[0].toLowerCase() === "all";
454
+ state.active = isUnconditional;
455
+ if (!isUnconditional) state.hasUnevaluatedMatch = true;
456
+ continue;
457
+ }
458
+
459
+ if (!state.active || node.arguments.length === 0) continue;
460
+ const rawValue = node.arguments.join(" ");
461
+ if (rawValue.length > MAX_OPTION_VALUE_LENGTH) state.optionValuesTruncated = true;
462
+ const value = rawValue.length > MAX_OPTION_VALUE_LENGTH
463
+ ? `${rawValue.slice(0, MAX_OPTION_VALUE_LENGTH)}…`
464
+ : rawValue;
465
+
466
+ if (SAFE_SINGLE_VALUE_OPTIONS.has(node.keyword)) {
467
+ if (!state.options.has(node.keyword)) {
468
+ const paths = node.keyword === "userknownhostsfile" || node.keyword === "globalknownhostsfile";
469
+ state.options.set(node.keyword, paths ? node.arguments : value);
470
+ }
471
+ continue;
472
+ }
473
+
474
+ if (SAFE_MULTI_VALUE_OPTIONS.has(node.keyword)) {
475
+ const current = state.options.get(node.keyword);
476
+ const values = Array.isArray(current) ? current : current === undefined ? [] : [current];
477
+ if (values.length < MAX_MULTI_VALUE_COUNT) values.push(value);
478
+ else state.multiValuesTruncated = true;
479
+ state.options.set(node.keyword, values);
480
+ continue;
481
+ }
482
+
483
+ if (HIDDEN_OPTIONS.has(node.keyword)) state.hiddenOptions.add(node.keyword);
484
+ else state.unsupportedOptions.add(node.keyword);
485
+ }
486
+ }
487
+
488
+ function hostMatchesPatterns(alias: string, patterns: string[]): boolean {
489
+ let positiveMatch = false;
490
+ for (const rawPattern of patterns) {
491
+ const negated = rawPattern.startsWith("!");
492
+ const pattern = negated ? rawPattern.slice(1) : rawPattern;
493
+ if (!pattern || !hostPatternMatches(alias, pattern)) continue;
494
+ if (negated) return false;
495
+ positiveMatch = true;
496
+ }
497
+ return positiveMatch;
498
+ }
499
+
500
+ function isConcreteHostAlias(pattern: string): boolean {
501
+ return Boolean(pattern) && pattern.length <= 255 && !pattern.startsWith("!") && !/[?*]/.test(pattern);
502
+ }
503
+
504
+ function isSameConcreteAlias(pattern: string, alias: string): boolean {
505
+ return isConcreteHostAlias(pattern) && pattern === alias;
506
+ }
507
+
508
+ function hostPatternMatches(alias: string, pattern: string): boolean {
509
+ let aliasIndex = 0;
510
+ let patternIndex = 0;
511
+ let starIndex = -1;
512
+ let retryAliasIndex = -1;
513
+
514
+ while (aliasIndex < alias.length) {
515
+ if (patternIndex < pattern.length && (pattern[patternIndex] === "?" || pattern[patternIndex] === alias[aliasIndex])) {
516
+ aliasIndex += 1;
517
+ patternIndex += 1;
518
+ continue;
519
+ }
520
+ if (patternIndex < pattern.length && pattern[patternIndex] === "*") {
521
+ starIndex = patternIndex;
522
+ retryAliasIndex = aliasIndex;
523
+ patternIndex += 1;
524
+ continue;
525
+ }
526
+ if (starIndex >= 0) {
527
+ patternIndex = starIndex + 1;
528
+ retryAliasIndex += 1;
529
+ aliasIndex = retryAliasIndex;
530
+ continue;
531
+ }
532
+ return false;
533
+ }
534
+
535
+ while (patternIndex < pattern.length && pattern[patternIndex] === "*") patternIndex += 1;
536
+ return patternIndex === pattern.length;
537
+ }
538
+
539
+ function tokenizeConfigLine(line: string): string[] {
540
+ const tokens: string[] = [];
541
+ let current = "";
542
+ let quote: "'" | '"' | undefined;
543
+
544
+ const pushCurrent = () => {
545
+ if (!current) return;
546
+ tokens.push(current);
547
+ current = "";
548
+ };
549
+
550
+ for (let index = 0; index < line.length; index += 1) {
551
+ const character = line[index];
552
+ if (!quote && character === "#" && current.length === 0) break;
553
+
554
+ if (character === "'" || character === '"') {
555
+ if (!quote) {
556
+ quote = character;
557
+ continue;
558
+ }
559
+ if (quote === character) {
560
+ quote = undefined;
561
+ continue;
562
+ }
563
+ }
564
+
565
+ if (character === "\\" && index + 1 < line.length) {
566
+ const next = line[index + 1];
567
+ if (/\s|[\\#"']/.test(next)) {
568
+ current += next;
569
+ index += 1;
570
+ continue;
571
+ }
572
+ }
573
+
574
+ if (!quote && /\s/.test(character)) {
575
+ pushCurrent();
576
+ continue;
577
+ }
578
+ current += character;
579
+ }
580
+
581
+ pushCurrent();
582
+ return tokens;
583
+ }
584
+
585
+ function splitDirective(tokens: string[]): { keyword: string; arguments: string[] } | undefined {
586
+ if (tokens.length === 0) return undefined;
587
+ let keyword = tokens[0];
588
+ let argumentsList = tokens.slice(1);
589
+ const equalsIndex = keyword.indexOf("=");
590
+
591
+ if (equalsIndex >= 0) {
592
+ const firstArgument = keyword.slice(equalsIndex + 1);
593
+ keyword = keyword.slice(0, equalsIndex);
594
+ argumentsList = firstArgument ? [firstArgument, ...argumentsList] : argumentsList;
595
+ } else if (argumentsList[0] === "=") {
596
+ argumentsList = argumentsList.slice(1);
597
+ } else if (argumentsList[0]?.startsWith("=")) {
598
+ argumentsList = [argumentsList[0].slice(1), ...argumentsList.slice(1)];
599
+ }
600
+
601
+ keyword = keyword.trim().toLowerCase();
602
+ if (!keyword) return undefined;
603
+ return { keyword, arguments: argumentsList };
604
+ }
605
+
606
+ function getUnsupportedIncludeReason(rawPattern: string): string | undefined {
607
+ if (rawPattern.length > MAX_INCLUDE_PATTERN_LENGTH) {
608
+ return `Include 模式超过长度上限 ${MAX_INCLUDE_PATTERN_LENGTH},已忽略`;
609
+ }
610
+ const unsupportedTokens = [...rawPattern.matchAll(/%([A-Za-z%])/g)]
611
+ .map((match) => match[1])
612
+ .filter((token) => token !== "d" && token !== "%");
613
+ if (unsupportedTokens.length > 0) {
614
+ return `Include 使用了无法静态求值的 token(${[...new Set(unsupportedTokens)].map((token) => `%${token}`).join(", ")}),已忽略`;
615
+ }
616
+ if (rawPattern.startsWith("~") && rawPattern !== "~" && !rawPattern.startsWith("~/") && !rawPattern.startsWith("~\\")) {
617
+ return "Include 使用了无法静态解析的其他用户主目录,已忽略";
618
+ }
619
+ if (process.platform === "win32") {
620
+ if (rawPattern.startsWith("\\") || rawPattern.startsWith("//")) {
621
+ return "Include 指向 UNC 路径;为避免隐式网络文件访问,已忽略";
622
+ }
623
+ if (/^\/(?![a-zA-Z]\/)/.test(rawPattern)) {
624
+ return "Include 使用了无法确定 MSYS 根目录的 POSIX 绝对路径,已忽略";
625
+ }
626
+ }
627
+ return undefined;
628
+ }
629
+
630
+ async function expandIncludePattern(
631
+ rawPattern: string,
632
+ homeDir: string,
633
+ baseDir: string,
634
+ budget: ParseBudget,
635
+ ): Promise<string[]> {
636
+ const percentPlaceholder = "\u0000";
637
+ let expanded = rawPattern
638
+ .replaceAll("%%", percentPlaceholder)
639
+ .replaceAll("%d", homeDir)
640
+ .replaceAll(percentPlaceholder, "%");
641
+ if (expanded === "~") expanded = homeDir;
642
+ else if (expanded.startsWith("~/") || expanded.startsWith("~\\")) {
643
+ expanded = path.join(homeDir, expanded.slice(2));
644
+ }
645
+
646
+ if (process.platform === "win32") {
647
+ const msysPath = expanded.match(/^\/([a-zA-Z])\/(.*)$/);
648
+ if (msysPath) expanded = `${msysPath[1]}:\\${msysPath[2]}`;
649
+ }
650
+
651
+ const absolutePattern = path.isAbsolute(expanded) ? path.normalize(expanded) : path.resolve(baseDir, expanded);
652
+ const parsed = path.parse(absolutePattern);
653
+ const segments = absolutePattern
654
+ .slice(parsed.root.length)
655
+ .split(/[\\/]+/)
656
+ .filter(Boolean);
657
+ let candidates = [parsed.root];
658
+
659
+ for (const segment of segments) {
660
+ budget.signal?.throwIfAborted();
661
+ if (!hasGlobMagic(segment)) {
662
+ candidates = candidates.map((candidate) => path.join(candidate, segment));
663
+ if (process.platform === "win32") {
664
+ for (const candidate of candidates) {
665
+ if (!(await isSafeWindowsIncludePath(candidate, budget))) return [];
666
+ }
667
+ }
668
+ continue;
669
+ }
670
+
671
+ const nextCandidates: string[] = [];
672
+ for (const candidate of candidates) {
673
+ if (process.platform === "win32" && !(await isSafeWindowsIncludePath(candidate, budget))) return [];
674
+ let directory;
675
+ try {
676
+ directory = await opendir(candidate);
677
+ } catch {
678
+ continue;
679
+ }
680
+ for await (const entry of directory) {
681
+ budget.signal?.throwIfAborted();
682
+ if (budget.directoryEntries >= MAX_DIRECTORY_ENTRIES) {
683
+ addWarning(budget, `Include 目录扫描超过上限 ${MAX_DIRECTORY_ENTRIES} 项,整个模式已忽略。`);
684
+ return [];
685
+ }
686
+ budget.directoryEntries += 1;
687
+ if (process.platform !== "win32" && entry.name.startsWith(".") && !segment.startsWith(".")) continue;
688
+ if (!globMatches(entry.name, segment, process.platform === "win32")) continue;
689
+ nextCandidates.push(path.join(candidate, entry.name));
690
+ if (nextCandidates.length > MAX_INCLUDE_MATCHES) {
691
+ addWarning(budget, `单个 Include 模式匹配超过上限 ${MAX_INCLUDE_MATCHES} 项,整个模式已忽略。`);
692
+ return [];
693
+ }
694
+ }
695
+ }
696
+ candidates = nextCandidates.sort((left, right) => left.localeCompare(right, "en"));
697
+ }
698
+
699
+ const files: string[] = [];
700
+ for (const candidate of candidates) {
701
+ budget.signal?.throwIfAborted();
702
+ if (process.platform === "win32" && !(await isSafeWindowsIncludePath(candidate, budget))) return [];
703
+ try {
704
+ if ((await stat(candidate)).isFile()) files.push(candidate);
705
+ } catch {
706
+ // OpenSSH 会静默忽略没有匹配文件的 Include。
707
+ }
708
+ }
709
+ return files.sort((left, right) => left.localeCompare(right, "en"));
710
+ }
711
+
712
+ function isSensitiveSshDataFile(filePath: string): boolean {
713
+ const fileName = path.basename(filePath).toLowerCase();
714
+ if (/^(?:known_hosts|authorized_keys)(?:\.|$)/.test(fileName)) return true;
715
+ if (/^(?:id_|key_)/.test(fileName) && !fileName.endsWith(".conf")) return true;
716
+ return /\.(?:key|pem|ppk|pub)$/.test(fileName);
717
+ }
718
+
719
+ function isUncPath(value: string): boolean {
720
+ const normalized = value.replaceAll("/", "\\").toLowerCase();
721
+ if (normalized.startsWith("\\\\?\\unc\\")) return true;
722
+ if (normalized.startsWith("\\\\?\\")) return false;
723
+ return normalized.startsWith("\\\\");
724
+ }
725
+
726
+ async function isSafeWindowsIncludePath(candidate: string, budget: ParseBudget): Promise<boolean> {
727
+ if (isUncPath(candidate)) {
728
+ addWarning(budget, "Include 解析为 UNC 路径;为避免隐式网络文件访问,整个模式已忽略。");
729
+ return false;
730
+ }
731
+ try {
732
+ const fileStats = await lstat(candidate);
733
+ if (!fileStats.isSymbolicLink()) return true;
734
+ const linkTarget = await readlink(candidate);
735
+ const resolvedTarget = path.isAbsolute(linkTarget)
736
+ ? linkTarget
737
+ : path.resolve(path.dirname(candidate), linkTarget);
738
+ if (isUncPath(linkTarget) || isUncPath(resolvedTarget)) {
739
+ addWarning(budget, "Windows Include 链接指向 UNC 路径;为避免隐式网络文件访问,整个模式已忽略。");
740
+ return false;
741
+ }
742
+ } catch {
743
+ return true;
744
+ }
745
+ return true;
746
+ }
747
+
748
+ function hasGlobMagic(value: string): boolean {
749
+ return /[?*[]/.test(value);
750
+ }
751
+
752
+ function globMatches(value: string, pattern: string, caseInsensitive: boolean): boolean {
753
+ let expression = "^";
754
+ for (let index = 0; index < pattern.length; index += 1) {
755
+ const character = pattern[index];
756
+ if (character === "*") {
757
+ expression += ".*";
758
+ continue;
759
+ }
760
+ if (character === "?") {
761
+ expression += ".";
762
+ continue;
763
+ }
764
+ if (character === "[") {
765
+ const closingIndex = pattern.indexOf("]", index + 1);
766
+ if (closingIndex > index + 1) {
767
+ let contents = pattern.slice(index + 1, closingIndex);
768
+ if (contents.startsWith("!")) contents = `^${contents.slice(1)}`;
769
+ expression += `[${contents.replaceAll("\\", "\\\\")}]`;
770
+ index = closingIndex;
771
+ continue;
772
+ }
773
+ }
774
+ expression += escapeRegExp(character);
775
+ }
776
+ expression += "$";
777
+
778
+ try {
779
+ return new RegExp(expression, caseInsensitive ? "i" : undefined).test(value);
780
+ } catch {
781
+ return value.localeCompare(pattern, "en", { sensitivity: caseInsensitive ? "base" : "variant" }) === 0;
782
+ }
783
+ }
784
+
785
+ function escapeRegExp(value: string): string {
786
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
787
+ }
788
+
789
+ function normalizePathKey(value: string): string {
790
+ const normalized = path.normalize(value);
791
+ return process.platform === "win32" ? normalized.toLowerCase() : normalized;
792
+ }
793
+
794
+ function reserveConfigNode(budget: ParseBudget): boolean {
795
+ if (budget.nodeCount >= MAX_CONFIG_NODES) {
796
+ addWarning(budget, `配置节点超过上限 ${MAX_CONFIG_NODES},其余配置已忽略。`);
797
+ return false;
798
+ }
799
+ budget.nodeCount += 1;
800
+ return true;
801
+ }
802
+
803
+ function classifyWarning(warning: string): string {
804
+ if (warning.includes("无法静态求值的 token")) return "dynamic_include_rejected";
805
+ if (warning.includes("UNC") || warning.includes("MSYS 根目录")) return "network_or_ambiguous_path_rejected";
806
+ if (warning.includes("SSH 密钥或主机记录")) return "sensitive_file_rejected";
807
+ if (warning.includes("循环 Include")) return "include_cycle";
808
+ if (warning.includes("Match 条件")) return "match_not_evaluated";
809
+ if (warning.includes("截断") || warning.includes("长度上限")) return "value_truncated";
810
+ if (warning.includes("超过上限") || warning.includes("总大小")) return "resource_limit";
811
+ return "other";
812
+ }
813
+
814
+ function addWarning(budget: ParseBudget, warning: string): void {
815
+ budget.warningCategories.add(classifyWarning(warning));
816
+ if (budget.warnings.includes(warning)) return;
817
+ if (budget.warnings.length < MAX_WARNINGS - 1) {
818
+ budget.warnings.push(warning);
819
+ return;
820
+ }
821
+ if (budget.warnings.length === MAX_WARNINGS - 1) {
822
+ budget.warnings.push(`警告数量超过上限 ${MAX_WARNINGS - 1},其余警告已省略。`);
823
+ }
824
+ }