@claude-flow/security 3.0.0-alpha.1 → 3.0.0-alpha.10

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.
Files changed (115) hide show
  1. package/README.md +292 -234
  2. package/__tests__/acceptance/security-compliance.test.ts +674 -674
  3. package/__tests__/authorization-propagator.test.ts +155 -0
  4. package/__tests__/credential-generator.test.ts +310 -310
  5. package/__tests__/fixtures/configurations.ts +425 -419
  6. package/__tests__/fixtures/index.ts +21 -21
  7. package/__tests__/helpers/create-mock.ts +469 -469
  8. package/__tests__/helpers/index.ts +32 -32
  9. package/__tests__/input-validator.test.ts +382 -381
  10. package/__tests__/integration/security-flow.test.ts +606 -606
  11. package/__tests__/password-hasher.test.ts +239 -239
  12. package/__tests__/path-validator.test.ts +302 -302
  13. package/__tests__/plugin-integrity-verifier.test.ts +199 -0
  14. package/__tests__/safe-executor.test.ts +292 -292
  15. package/__tests__/token-generator.test.ts +371 -371
  16. package/__tests__/tool-output-guardrail.test.ts +256 -0
  17. package/__tests__/unit/credential-generator.test.ts +182 -182
  18. package/__tests__/unit/password-hasher.test.ts +359 -359
  19. package/__tests__/unit/path-validator.test.ts +509 -509
  20. package/__tests__/unit/safe-executor.test.ts +667 -667
  21. package/__tests__/unit/token-generator.test.ts +310 -310
  22. package/dist/authorization/propagator.d.ts +148 -0
  23. package/dist/authorization/propagator.d.ts.map +1 -0
  24. package/dist/authorization/propagator.js +182 -0
  25. package/dist/authorization/propagator.js.map +1 -0
  26. package/dist/credential-generator.js +9 -9
  27. package/dist/domain/services/security-domain-service.js +1 -1
  28. package/dist/domain/services/security-domain-service.js.map +1 -1
  29. package/dist/index.d.ts +4 -1
  30. package/dist/index.d.ts.map +1 -1
  31. package/dist/index.js +11 -1
  32. package/dist/index.js.map +1 -1
  33. package/dist/password-hasher.d.ts.map +1 -1
  34. package/dist/password-hasher.js +8 -1
  35. package/dist/password-hasher.js.map +1 -1
  36. package/dist/plugins/integrity-verifier.d.ts +125 -0
  37. package/dist/plugins/integrity-verifier.d.ts.map +1 -0
  38. package/dist/plugins/integrity-verifier.js +186 -0
  39. package/dist/plugins/integrity-verifier.js.map +1 -0
  40. package/dist/safe-executor.d.ts +7 -0
  41. package/dist/safe-executor.d.ts.map +1 -1
  42. package/dist/safe-executor.js +21 -1
  43. package/dist/safe-executor.js.map +1 -1
  44. package/dist/tool-output-guardrail.d.ts +126 -0
  45. package/dist/tool-output-guardrail.d.ts.map +1 -0
  46. package/dist/tool-output-guardrail.js +257 -0
  47. package/dist/tool-output-guardrail.js.map +1 -0
  48. package/package.json +28 -28
  49. package/src/CVE-REMEDIATION.ts +251 -251
  50. package/src/application/index.ts +10 -10
  51. package/src/application/services/security-application-service.ts +193 -193
  52. package/src/authorization/propagator.ts +279 -0
  53. package/src/credential-generator.ts +368 -368
  54. package/src/domain/entities/security-context.ts +173 -173
  55. package/src/domain/index.ts +17 -17
  56. package/src/domain/services/security-domain-service.ts +296 -296
  57. package/src/index.ts +314 -271
  58. package/src/input-validator.ts +466 -466
  59. package/src/password-hasher.ts +277 -270
  60. package/src/path-validator.ts +525 -525
  61. package/src/plugins/integrity-verifier.ts +265 -0
  62. package/src/safe-executor.ts +546 -525
  63. package/src/token-generator.ts +463 -463
  64. package/src/tool-output-guardrail.ts +360 -0
  65. package/tmp.json +0 -0
  66. package/tsconfig.json +9 -9
  67. package/tsconfig.tsbuildinfo +1 -1
  68. package/vitest.config.ts +20 -0
  69. package/.agentic-flow/intelligence.json +0 -16
  70. package/__tests__/coverage/base.css +0 -224
  71. package/__tests__/coverage/block-navigation.js +0 -87
  72. package/__tests__/coverage/coverage-final.json +0 -11
  73. package/__tests__/coverage/favicon.png +0 -0
  74. package/__tests__/coverage/index.html +0 -161
  75. package/__tests__/coverage/lcov-report/base.css +0 -224
  76. package/__tests__/coverage/lcov-report/block-navigation.js +0 -87
  77. package/__tests__/coverage/lcov-report/favicon.png +0 -0
  78. package/__tests__/coverage/lcov-report/index.html +0 -161
  79. package/__tests__/coverage/lcov-report/prettify.css +0 -1
  80. package/__tests__/coverage/lcov-report/prettify.js +0 -2
  81. package/__tests__/coverage/lcov-report/sort-arrow-sprite.png +0 -0
  82. package/__tests__/coverage/lcov-report/sorter.js +0 -210
  83. package/__tests__/coverage/lcov-report/src/CVE-REMEDIATION.ts.html +0 -838
  84. package/__tests__/coverage/lcov-report/src/application/services/index.html +0 -116
  85. package/__tests__/coverage/lcov-report/src/application/services/security-application-service.ts.html +0 -664
  86. package/__tests__/coverage/lcov-report/src/credential-generator.ts.html +0 -1189
  87. package/__tests__/coverage/lcov-report/src/domain/entities/index.html +0 -116
  88. package/__tests__/coverage/lcov-report/src/domain/entities/security-context.ts.html +0 -604
  89. package/__tests__/coverage/lcov-report/src/domain/services/index.html +0 -116
  90. package/__tests__/coverage/lcov-report/src/domain/services/security-domain-service.ts.html +0 -973
  91. package/__tests__/coverage/lcov-report/src/index.html +0 -206
  92. package/__tests__/coverage/lcov-report/src/input-validator.ts.html +0 -1483
  93. package/__tests__/coverage/lcov-report/src/password-hasher.ts.html +0 -895
  94. package/__tests__/coverage/lcov-report/src/path-validator.ts.html +0 -1660
  95. package/__tests__/coverage/lcov-report/src/safe-executor.ts.html +0 -1660
  96. package/__tests__/coverage/lcov-report/src/token-generator.ts.html +0 -1474
  97. package/__tests__/coverage/lcov.info +0 -3650
  98. package/__tests__/coverage/prettify.css +0 -1
  99. package/__tests__/coverage/prettify.js +0 -2
  100. package/__tests__/coverage/sort-arrow-sprite.png +0 -0
  101. package/__tests__/coverage/sorter.js +0 -210
  102. package/__tests__/coverage/src/CVE-REMEDIATION.ts.html +0 -838
  103. package/__tests__/coverage/src/application/services/index.html +0 -116
  104. package/__tests__/coverage/src/application/services/security-application-service.ts.html +0 -664
  105. package/__tests__/coverage/src/credential-generator.ts.html +0 -1189
  106. package/__tests__/coverage/src/domain/entities/index.html +0 -116
  107. package/__tests__/coverage/src/domain/entities/security-context.ts.html +0 -604
  108. package/__tests__/coverage/src/domain/services/index.html +0 -116
  109. package/__tests__/coverage/src/domain/services/security-domain-service.ts.html +0 -973
  110. package/__tests__/coverage/src/index.html +0 -206
  111. package/__tests__/coverage/src/input-validator.ts.html +0 -1483
  112. package/__tests__/coverage/src/password-hasher.ts.html +0 -895
  113. package/__tests__/coverage/src/path-validator.ts.html +0 -1660
  114. package/__tests__/coverage/src/safe-executor.ts.html +0 -1660
  115. package/__tests__/coverage/src/token-generator.ts.html +0 -1474
@@ -1,525 +1,525 @@
1
- /**
2
- * Path Validator - HIGH-2 Remediation
3
- *
4
- * Fixes path traversal vulnerabilities by:
5
- * - Validating all file paths against allowed prefixes
6
- * - Using path.resolve() for canonicalization
7
- * - Blocking traversal patterns (../, etc.)
8
- * - Enforcing path length limits
9
- *
10
- * Security Properties:
11
- * - Path canonicalization
12
- * - Prefix validation
13
- * - Symlink resolution (optional)
14
- * - Traversal pattern detection
15
- *
16
- * @module v3/security/path-validator
17
- */
18
-
19
- import * as path from 'path';
20
- import * as fs from 'fs/promises';
21
-
22
- export interface PathValidatorConfig {
23
- /**
24
- * Allowed directory prefixes.
25
- * Paths must start with one of these after resolution.
26
- */
27
- allowedPrefixes: string[];
28
-
29
- /**
30
- * Blocked file extensions.
31
- * Files with these extensions are rejected.
32
- */
33
- blockedExtensions?: string[];
34
-
35
- /**
36
- * Blocked file names.
37
- * Files matching these names are rejected.
38
- */
39
- blockedNames?: string[];
40
-
41
- /**
42
- * Maximum path length.
43
- * Default: 4096 characters
44
- */
45
- maxPathLength?: number;
46
-
47
- /**
48
- * Whether to resolve symlinks.
49
- * Default: true
50
- */
51
- resolveSymlinks?: boolean;
52
-
53
- /**
54
- * Whether to allow paths that don't exist.
55
- * Default: true (for write operations)
56
- */
57
- allowNonExistent?: boolean;
58
-
59
- /**
60
- * Whether to allow hidden files/directories.
61
- * Default: false
62
- */
63
- allowHidden?: boolean;
64
- }
65
-
66
- export interface PathValidationResult {
67
- isValid: boolean;
68
- resolvedPath: string;
69
- relativePath: string;
70
- matchedPrefix: string;
71
- errors: string[];
72
- }
73
-
74
- export class PathValidatorError extends Error {
75
- constructor(
76
- message: string,
77
- public readonly code: string,
78
- public readonly path?: string,
79
- ) {
80
- super(message);
81
- this.name = 'PathValidatorError';
82
- }
83
- }
84
-
85
- /**
86
- * Dangerous path patterns that indicate traversal attempts.
87
- */
88
- const TRAVERSAL_PATTERNS = [
89
- /\.\.\//, // ../
90
- /\.\.\\/, // ..\
91
- /\.\./, // .. anywhere
92
- /%2e%2e/i, // URL-encoded ..
93
- /%252e%252e/i, // Double URL-encoded ..
94
- /\.%2e/i, // Mixed encoding
95
- /%2e\./i, // Mixed encoding
96
- /\0/, // Null byte
97
- /%00/, // URL-encoded null
98
- ];
99
-
100
- /**
101
- * Default blocked file extensions (sensitive files).
102
- */
103
- const DEFAULT_BLOCKED_EXTENSIONS = [
104
- '.env',
105
- '.pem',
106
- '.key',
107
- '.crt',
108
- '.pfx',
109
- '.p12',
110
- '.jks',
111
- '.keystore',
112
- '.secret',
113
- '.credentials',
114
- ];
115
-
116
- /**
117
- * Default blocked file names (sensitive files).
118
- */
119
- const DEFAULT_BLOCKED_NAMES = [
120
- 'id_rsa',
121
- 'id_dsa',
122
- 'id_ecdsa',
123
- 'id_ed25519',
124
- '.htpasswd',
125
- '.htaccess',
126
- 'shadow',
127
- 'passwd',
128
- 'authorized_keys',
129
- 'known_hosts',
130
- '.git',
131
- '.gitconfig',
132
- '.npmrc',
133
- '.docker',
134
- ];
135
-
136
- /**
137
- * Path validator that prevents traversal attacks.
138
- *
139
- * This class validates file paths to ensure they stay within
140
- * allowed directories and don't access sensitive files.
141
- *
142
- * @example
143
- * ```typescript
144
- * const validator = new PathValidator({
145
- * allowedPrefixes: ['/workspaces/project']
146
- * });
147
- *
148
- * const result = await validator.validate('/workspaces/project/src/file.ts');
149
- * if (result.isValid) {
150
- * // Safe to use result.resolvedPath
151
- * }
152
- * ```
153
- */
154
- export class PathValidator {
155
- private readonly config: Required<PathValidatorConfig>;
156
- private readonly resolvedPrefixes: string[];
157
-
158
- constructor(config: PathValidatorConfig) {
159
- this.config = {
160
- allowedPrefixes: config.allowedPrefixes,
161
- blockedExtensions: config.blockedExtensions ?? DEFAULT_BLOCKED_EXTENSIONS,
162
- blockedNames: config.blockedNames ?? DEFAULT_BLOCKED_NAMES,
163
- maxPathLength: config.maxPathLength ?? 4096,
164
- resolveSymlinks: config.resolveSymlinks ?? true,
165
- allowNonExistent: config.allowNonExistent ?? true,
166
- allowHidden: config.allowHidden ?? false,
167
- };
168
-
169
- if (this.config.allowedPrefixes.length === 0) {
170
- throw new PathValidatorError(
171
- 'At least one allowed prefix must be specified',
172
- 'EMPTY_PREFIXES'
173
- );
174
- }
175
-
176
- // Pre-resolve all prefixes
177
- this.resolvedPrefixes = this.config.allowedPrefixes.map(p =>
178
- path.resolve(p)
179
- );
180
- }
181
-
182
- /**
183
- * Validates a path against security rules.
184
- *
185
- * @param inputPath - The path to validate
186
- * @returns Validation result with resolved path
187
- */
188
- async validate(inputPath: string): Promise<PathValidationResult> {
189
- const errors: string[] = [];
190
-
191
- // Check for empty path
192
- if (!inputPath || inputPath.trim() === '') {
193
- return {
194
- isValid: false,
195
- resolvedPath: '',
196
- relativePath: '',
197
- matchedPrefix: '',
198
- errors: ['Path is empty'],
199
- };
200
- }
201
-
202
- // Check path length
203
- if (inputPath.length > this.config.maxPathLength) {
204
- return {
205
- isValid: false,
206
- resolvedPath: '',
207
- relativePath: '',
208
- matchedPrefix: '',
209
- errors: [`Path exceeds maximum length of ${this.config.maxPathLength}`],
210
- };
211
- }
212
-
213
- // Check for traversal patterns
214
- for (const pattern of TRAVERSAL_PATTERNS) {
215
- if (pattern.test(inputPath)) {
216
- return {
217
- isValid: false,
218
- resolvedPath: '',
219
- relativePath: '',
220
- matchedPrefix: '',
221
- errors: ['Path traversal pattern detected'],
222
- };
223
- }
224
- }
225
-
226
- // Resolve the path
227
- let resolvedPath: string;
228
- try {
229
- resolvedPath = path.resolve(inputPath);
230
-
231
- // Optionally resolve symlinks
232
- if (this.config.resolveSymlinks) {
233
- try {
234
- resolvedPath = await fs.realpath(resolvedPath);
235
- } catch (error: any) {
236
- // Path doesn't exist yet - use resolved path
237
- if (error.code !== 'ENOENT' || !this.config.allowNonExistent) {
238
- if (error.code === 'ENOENT') {
239
- errors.push('Path does not exist');
240
- } else {
241
- errors.push(`Failed to resolve path: ${error.message}`);
242
- }
243
- }
244
- }
245
- }
246
- } catch (error: any) {
247
- return {
248
- isValid: false,
249
- resolvedPath: '',
250
- relativePath: '',
251
- matchedPrefix: '',
252
- errors: [`Invalid path: ${error.message}`],
253
- };
254
- }
255
-
256
- // Check against allowed prefixes
257
- let matchedPrefix = '';
258
- let relativePath = '';
259
- let prefixMatched = false;
260
-
261
- for (const prefix of this.resolvedPrefixes) {
262
- if (resolvedPath === prefix || resolvedPath.startsWith(prefix + path.sep)) {
263
- prefixMatched = true;
264
- matchedPrefix = prefix;
265
- relativePath = resolvedPath.slice(prefix.length);
266
- if (relativePath.startsWith(path.sep)) {
267
- relativePath = relativePath.slice(1);
268
- }
269
- break;
270
- }
271
- }
272
-
273
- if (!prefixMatched) {
274
- return {
275
- isValid: false,
276
- resolvedPath,
277
- relativePath: '',
278
- matchedPrefix: '',
279
- errors: ['Path is outside allowed directories'],
280
- };
281
- }
282
-
283
- // Check for hidden files
284
- const pathParts = resolvedPath.split(path.sep);
285
- if (!this.config.allowHidden) {
286
- for (const part of pathParts) {
287
- if (part.startsWith('.') && part !== '.' && part !== '..') {
288
- errors.push('Hidden files/directories are not allowed');
289
- break;
290
- }
291
- }
292
- }
293
-
294
- // Check blocked file names
295
- const basename = path.basename(resolvedPath);
296
- if (this.config.blockedNames.includes(basename)) {
297
- errors.push(`File name "${basename}" is blocked`);
298
- }
299
-
300
- // Check blocked extensions
301
- const ext = path.extname(resolvedPath).toLowerCase();
302
- if (this.config.blockedExtensions.includes(ext)) {
303
- errors.push(`File extension "${ext}" is blocked`);
304
- }
305
-
306
- // Also check for double extensions (e.g., .tar.gz, .config.json)
307
- const fullname = basename.toLowerCase();
308
- for (const blockedExt of this.config.blockedExtensions) {
309
- if (fullname.endsWith(blockedExt)) {
310
- errors.push(`File extension "${blockedExt}" is blocked`);
311
- break;
312
- }
313
- }
314
-
315
- return {
316
- isValid: errors.length === 0,
317
- resolvedPath,
318
- relativePath,
319
- matchedPrefix,
320
- errors,
321
- };
322
- }
323
-
324
- /**
325
- * Validates and returns resolved path, throwing on failure.
326
- *
327
- * @param inputPath - The path to validate
328
- * @returns Resolved path if valid
329
- * @throws PathValidatorError if validation fails
330
- */
331
- async validateOrThrow(inputPath: string): Promise<string> {
332
- const result = await this.validate(inputPath);
333
-
334
- if (!result.isValid) {
335
- throw new PathValidatorError(
336
- result.errors.join('; '),
337
- 'VALIDATION_FAILED',
338
- inputPath
339
- );
340
- }
341
-
342
- return result.resolvedPath;
343
- }
344
-
345
- /**
346
- * Synchronous validation (without symlink resolution).
347
- *
348
- * @param inputPath - The path to validate
349
- * @returns Validation result
350
- */
351
- validateSync(inputPath: string): PathValidationResult {
352
- const errors: string[] = [];
353
-
354
- if (!inputPath || inputPath.trim() === '') {
355
- return {
356
- isValid: false,
357
- resolvedPath: '',
358
- relativePath: '',
359
- matchedPrefix: '',
360
- errors: ['Path is empty'],
361
- };
362
- }
363
-
364
- if (inputPath.length > this.config.maxPathLength) {
365
- return {
366
- isValid: false,
367
- resolvedPath: '',
368
- relativePath: '',
369
- matchedPrefix: '',
370
- errors: [`Path exceeds maximum length of ${this.config.maxPathLength}`],
371
- };
372
- }
373
-
374
- for (const pattern of TRAVERSAL_PATTERNS) {
375
- if (pattern.test(inputPath)) {
376
- return {
377
- isValid: false,
378
- resolvedPath: '',
379
- relativePath: '',
380
- matchedPrefix: '',
381
- errors: ['Path traversal pattern detected'],
382
- };
383
- }
384
- }
385
-
386
- const resolvedPath = path.resolve(inputPath);
387
-
388
- let matchedPrefix = '';
389
- let relativePath = '';
390
- let prefixMatched = false;
391
-
392
- for (const prefix of this.resolvedPrefixes) {
393
- if (resolvedPath === prefix || resolvedPath.startsWith(prefix + path.sep)) {
394
- prefixMatched = true;
395
- matchedPrefix = prefix;
396
- relativePath = resolvedPath.slice(prefix.length);
397
- if (relativePath.startsWith(path.sep)) {
398
- relativePath = relativePath.slice(1);
399
- }
400
- break;
401
- }
402
- }
403
-
404
- if (!prefixMatched) {
405
- return {
406
- isValid: false,
407
- resolvedPath,
408
- relativePath: '',
409
- matchedPrefix: '',
410
- errors: ['Path is outside allowed directories'],
411
- };
412
- }
413
-
414
- const pathParts = resolvedPath.split(path.sep);
415
- if (!this.config.allowHidden) {
416
- for (const part of pathParts) {
417
- if (part.startsWith('.') && part !== '.' && part !== '..') {
418
- errors.push('Hidden files/directories are not allowed');
419
- break;
420
- }
421
- }
422
- }
423
-
424
- const basename = path.basename(resolvedPath);
425
- if (this.config.blockedNames.includes(basename)) {
426
- errors.push(`File name "${basename}" is blocked`);
427
- }
428
-
429
- const ext = path.extname(resolvedPath).toLowerCase();
430
- if (this.config.blockedExtensions.includes(ext)) {
431
- errors.push(`File extension "${ext}" is blocked`);
432
- }
433
-
434
- return {
435
- isValid: errors.length === 0,
436
- resolvedPath,
437
- relativePath,
438
- matchedPrefix,
439
- errors,
440
- };
441
- }
442
-
443
- /**
444
- * Securely joins path segments within allowed directories.
445
- *
446
- * @param prefix - Base directory (must be in allowedPrefixes)
447
- * @param segments - Path segments to join
448
- * @returns Validated resolved path
449
- */
450
- async securePath(prefix: string, ...segments: string[]): Promise<string> {
451
- // Join the segments
452
- const joined = path.join(prefix, ...segments);
453
-
454
- // Validate the result
455
- return this.validateOrThrow(joined);
456
- }
457
-
458
- /**
459
- * Adds a prefix to the allowed list at runtime.
460
- *
461
- * @param prefix - Prefix to add
462
- */
463
- addPrefix(prefix: string): void {
464
- const resolved = path.resolve(prefix);
465
- if (!this.resolvedPrefixes.includes(resolved)) {
466
- this.config.allowedPrefixes.push(prefix);
467
- this.resolvedPrefixes.push(resolved);
468
- }
469
- }
470
-
471
- /**
472
- * Returns the current allowed prefixes.
473
- */
474
- getAllowedPrefixes(): readonly string[] {
475
- return [...this.resolvedPrefixes];
476
- }
477
-
478
- /**
479
- * Checks if a path is within allowed prefixes (quick check).
480
- */
481
- isWithinAllowed(inputPath: string): boolean {
482
- try {
483
- const resolved = path.resolve(inputPath);
484
- return this.resolvedPrefixes.some(
485
- prefix => resolved === prefix || resolved.startsWith(prefix + path.sep)
486
- );
487
- } catch {
488
- return false;
489
- }
490
- }
491
- }
492
-
493
- /**
494
- * Factory function to create a path validator for a project directory.
495
- *
496
- * @param projectRoot - Root directory of the project
497
- * @returns Configured PathValidator
498
- */
499
- export function createProjectPathValidator(projectRoot: string): PathValidator {
500
- const srcDir = path.join(projectRoot, 'src');
501
- const testDir = path.join(projectRoot, 'tests');
502
- const docsDir = path.join(projectRoot, 'docs');
503
-
504
- return new PathValidator({
505
- allowedPrefixes: [srcDir, testDir, docsDir],
506
- allowHidden: false,
507
- });
508
- }
509
-
510
- /**
511
- * Factory function to create a path validator for the entire project.
512
- *
513
- * @param projectRoot - Root directory of the project
514
- * @returns Configured PathValidator
515
- */
516
- export function createFullProjectPathValidator(projectRoot: string): PathValidator {
517
- return new PathValidator({
518
- allowedPrefixes: [projectRoot],
519
- allowHidden: true, // Allow .gitignore, etc.
520
- blockedNames: [
521
- ...DEFAULT_BLOCKED_NAMES,
522
- 'node_modules', // Block access to node_modules
523
- ],
524
- });
525
- }
1
+ /**
2
+ * Path Validator - HIGH-2 Remediation
3
+ *
4
+ * Fixes path traversal vulnerabilities by:
5
+ * - Validating all file paths against allowed prefixes
6
+ * - Using path.resolve() for canonicalization
7
+ * - Blocking traversal patterns (../, etc.)
8
+ * - Enforcing path length limits
9
+ *
10
+ * Security Properties:
11
+ * - Path canonicalization
12
+ * - Prefix validation
13
+ * - Symlink resolution (optional)
14
+ * - Traversal pattern detection
15
+ *
16
+ * @module v3/security/path-validator
17
+ */
18
+
19
+ import * as path from 'path';
20
+ import * as fs from 'fs/promises';
21
+
22
+ export interface PathValidatorConfig {
23
+ /**
24
+ * Allowed directory prefixes.
25
+ * Paths must start with one of these after resolution.
26
+ */
27
+ allowedPrefixes: string[];
28
+
29
+ /**
30
+ * Blocked file extensions.
31
+ * Files with these extensions are rejected.
32
+ */
33
+ blockedExtensions?: string[];
34
+
35
+ /**
36
+ * Blocked file names.
37
+ * Files matching these names are rejected.
38
+ */
39
+ blockedNames?: string[];
40
+
41
+ /**
42
+ * Maximum path length.
43
+ * Default: 4096 characters
44
+ */
45
+ maxPathLength?: number;
46
+
47
+ /**
48
+ * Whether to resolve symlinks.
49
+ * Default: true
50
+ */
51
+ resolveSymlinks?: boolean;
52
+
53
+ /**
54
+ * Whether to allow paths that don't exist.
55
+ * Default: true (for write operations)
56
+ */
57
+ allowNonExistent?: boolean;
58
+
59
+ /**
60
+ * Whether to allow hidden files/directories.
61
+ * Default: false
62
+ */
63
+ allowHidden?: boolean;
64
+ }
65
+
66
+ export interface PathValidationResult {
67
+ isValid: boolean;
68
+ resolvedPath: string;
69
+ relativePath: string;
70
+ matchedPrefix: string;
71
+ errors: string[];
72
+ }
73
+
74
+ export class PathValidatorError extends Error {
75
+ constructor(
76
+ message: string,
77
+ public readonly code: string,
78
+ public readonly path?: string,
79
+ ) {
80
+ super(message);
81
+ this.name = 'PathValidatorError';
82
+ }
83
+ }
84
+
85
+ /**
86
+ * Dangerous path patterns that indicate traversal attempts.
87
+ */
88
+ const TRAVERSAL_PATTERNS = [
89
+ /\.\.\//, // ../
90
+ /\.\.\\/, // ..\
91
+ /\.\./, // .. anywhere
92
+ /%2e%2e/i, // URL-encoded ..
93
+ /%252e%252e/i, // Double URL-encoded ..
94
+ /\.%2e/i, // Mixed encoding
95
+ /%2e\./i, // Mixed encoding
96
+ /\0/, // Null byte
97
+ /%00/, // URL-encoded null
98
+ ];
99
+
100
+ /**
101
+ * Default blocked file extensions (sensitive files).
102
+ */
103
+ const DEFAULT_BLOCKED_EXTENSIONS = [
104
+ '.env',
105
+ '.pem',
106
+ '.key',
107
+ '.crt',
108
+ '.pfx',
109
+ '.p12',
110
+ '.jks',
111
+ '.keystore',
112
+ '.secret',
113
+ '.credentials',
114
+ ];
115
+
116
+ /**
117
+ * Default blocked file names (sensitive files).
118
+ */
119
+ const DEFAULT_BLOCKED_NAMES = [
120
+ 'id_rsa',
121
+ 'id_dsa',
122
+ 'id_ecdsa',
123
+ 'id_ed25519',
124
+ '.htpasswd',
125
+ '.htaccess',
126
+ 'shadow',
127
+ 'passwd',
128
+ 'authorized_keys',
129
+ 'known_hosts',
130
+ '.git',
131
+ '.gitconfig',
132
+ '.npmrc',
133
+ '.docker',
134
+ ];
135
+
136
+ /**
137
+ * Path validator that prevents traversal attacks.
138
+ *
139
+ * This class validates file paths to ensure they stay within
140
+ * allowed directories and don't access sensitive files.
141
+ *
142
+ * @example
143
+ * ```typescript
144
+ * const validator = new PathValidator({
145
+ * allowedPrefixes: ['/workspaces/project']
146
+ * });
147
+ *
148
+ * const result = await validator.validate('/workspaces/project/src/file.ts');
149
+ * if (result.isValid) {
150
+ * // Safe to use result.resolvedPath
151
+ * }
152
+ * ```
153
+ */
154
+ export class PathValidator {
155
+ private readonly config: Required<PathValidatorConfig>;
156
+ private readonly resolvedPrefixes: string[];
157
+
158
+ constructor(config: PathValidatorConfig) {
159
+ this.config = {
160
+ allowedPrefixes: config.allowedPrefixes,
161
+ blockedExtensions: config.blockedExtensions ?? DEFAULT_BLOCKED_EXTENSIONS,
162
+ blockedNames: config.blockedNames ?? DEFAULT_BLOCKED_NAMES,
163
+ maxPathLength: config.maxPathLength ?? 4096,
164
+ resolveSymlinks: config.resolveSymlinks ?? true,
165
+ allowNonExistent: config.allowNonExistent ?? true,
166
+ allowHidden: config.allowHidden ?? false,
167
+ };
168
+
169
+ if (this.config.allowedPrefixes.length === 0) {
170
+ throw new PathValidatorError(
171
+ 'At least one allowed prefix must be specified',
172
+ 'EMPTY_PREFIXES'
173
+ );
174
+ }
175
+
176
+ // Pre-resolve all prefixes
177
+ this.resolvedPrefixes = this.config.allowedPrefixes.map(p =>
178
+ path.resolve(p)
179
+ );
180
+ }
181
+
182
+ /**
183
+ * Validates a path against security rules.
184
+ *
185
+ * @param inputPath - The path to validate
186
+ * @returns Validation result with resolved path
187
+ */
188
+ async validate(inputPath: string): Promise<PathValidationResult> {
189
+ const errors: string[] = [];
190
+
191
+ // Check for empty path
192
+ if (!inputPath || inputPath.trim() === '') {
193
+ return {
194
+ isValid: false,
195
+ resolvedPath: '',
196
+ relativePath: '',
197
+ matchedPrefix: '',
198
+ errors: ['Path is empty'],
199
+ };
200
+ }
201
+
202
+ // Check path length
203
+ if (inputPath.length > this.config.maxPathLength) {
204
+ return {
205
+ isValid: false,
206
+ resolvedPath: '',
207
+ relativePath: '',
208
+ matchedPrefix: '',
209
+ errors: [`Path exceeds maximum length of ${this.config.maxPathLength}`],
210
+ };
211
+ }
212
+
213
+ // Check for traversal patterns
214
+ for (const pattern of TRAVERSAL_PATTERNS) {
215
+ if (pattern.test(inputPath)) {
216
+ return {
217
+ isValid: false,
218
+ resolvedPath: '',
219
+ relativePath: '',
220
+ matchedPrefix: '',
221
+ errors: ['Path traversal pattern detected'],
222
+ };
223
+ }
224
+ }
225
+
226
+ // Resolve the path
227
+ let resolvedPath: string;
228
+ try {
229
+ resolvedPath = path.resolve(inputPath);
230
+
231
+ // Optionally resolve symlinks
232
+ if (this.config.resolveSymlinks) {
233
+ try {
234
+ resolvedPath = await fs.realpath(resolvedPath);
235
+ } catch (error: any) {
236
+ // Path doesn't exist yet - use resolved path
237
+ if (error.code !== 'ENOENT' || !this.config.allowNonExistent) {
238
+ if (error.code === 'ENOENT') {
239
+ errors.push('Path does not exist');
240
+ } else {
241
+ errors.push(`Failed to resolve path: ${error.message}`);
242
+ }
243
+ }
244
+ }
245
+ }
246
+ } catch (error: any) {
247
+ return {
248
+ isValid: false,
249
+ resolvedPath: '',
250
+ relativePath: '',
251
+ matchedPrefix: '',
252
+ errors: [`Invalid path: ${error.message}`],
253
+ };
254
+ }
255
+
256
+ // Check against allowed prefixes
257
+ let matchedPrefix = '';
258
+ let relativePath = '';
259
+ let prefixMatched = false;
260
+
261
+ for (const prefix of this.resolvedPrefixes) {
262
+ if (resolvedPath === prefix || resolvedPath.startsWith(prefix + path.sep)) {
263
+ prefixMatched = true;
264
+ matchedPrefix = prefix;
265
+ relativePath = resolvedPath.slice(prefix.length);
266
+ if (relativePath.startsWith(path.sep)) {
267
+ relativePath = relativePath.slice(1);
268
+ }
269
+ break;
270
+ }
271
+ }
272
+
273
+ if (!prefixMatched) {
274
+ return {
275
+ isValid: false,
276
+ resolvedPath,
277
+ relativePath: '',
278
+ matchedPrefix: '',
279
+ errors: ['Path is outside allowed directories'],
280
+ };
281
+ }
282
+
283
+ // Check for hidden files
284
+ const pathParts = resolvedPath.split(path.sep);
285
+ if (!this.config.allowHidden) {
286
+ for (const part of pathParts) {
287
+ if (part.startsWith('.') && part !== '.' && part !== '..') {
288
+ errors.push('Hidden files/directories are not allowed');
289
+ break;
290
+ }
291
+ }
292
+ }
293
+
294
+ // Check blocked file names
295
+ const basename = path.basename(resolvedPath);
296
+ if (this.config.blockedNames.includes(basename)) {
297
+ errors.push(`File name "${basename}" is blocked`);
298
+ }
299
+
300
+ // Check blocked extensions
301
+ const ext = path.extname(resolvedPath).toLowerCase();
302
+ if (this.config.blockedExtensions.includes(ext)) {
303
+ errors.push(`File extension "${ext}" is blocked`);
304
+ }
305
+
306
+ // Also check for double extensions (e.g., .tar.gz, .config.json)
307
+ const fullname = basename.toLowerCase();
308
+ for (const blockedExt of this.config.blockedExtensions) {
309
+ if (fullname.endsWith(blockedExt)) {
310
+ errors.push(`File extension "${blockedExt}" is blocked`);
311
+ break;
312
+ }
313
+ }
314
+
315
+ return {
316
+ isValid: errors.length === 0,
317
+ resolvedPath,
318
+ relativePath,
319
+ matchedPrefix,
320
+ errors,
321
+ };
322
+ }
323
+
324
+ /**
325
+ * Validates and returns resolved path, throwing on failure.
326
+ *
327
+ * @param inputPath - The path to validate
328
+ * @returns Resolved path if valid
329
+ * @throws PathValidatorError if validation fails
330
+ */
331
+ async validateOrThrow(inputPath: string): Promise<string> {
332
+ const result = await this.validate(inputPath);
333
+
334
+ if (!result.isValid) {
335
+ throw new PathValidatorError(
336
+ result.errors.join('; '),
337
+ 'VALIDATION_FAILED',
338
+ inputPath
339
+ );
340
+ }
341
+
342
+ return result.resolvedPath;
343
+ }
344
+
345
+ /**
346
+ * Synchronous validation (without symlink resolution).
347
+ *
348
+ * @param inputPath - The path to validate
349
+ * @returns Validation result
350
+ */
351
+ validateSync(inputPath: string): PathValidationResult {
352
+ const errors: string[] = [];
353
+
354
+ if (!inputPath || inputPath.trim() === '') {
355
+ return {
356
+ isValid: false,
357
+ resolvedPath: '',
358
+ relativePath: '',
359
+ matchedPrefix: '',
360
+ errors: ['Path is empty'],
361
+ };
362
+ }
363
+
364
+ if (inputPath.length > this.config.maxPathLength) {
365
+ return {
366
+ isValid: false,
367
+ resolvedPath: '',
368
+ relativePath: '',
369
+ matchedPrefix: '',
370
+ errors: [`Path exceeds maximum length of ${this.config.maxPathLength}`],
371
+ };
372
+ }
373
+
374
+ for (const pattern of TRAVERSAL_PATTERNS) {
375
+ if (pattern.test(inputPath)) {
376
+ return {
377
+ isValid: false,
378
+ resolvedPath: '',
379
+ relativePath: '',
380
+ matchedPrefix: '',
381
+ errors: ['Path traversal pattern detected'],
382
+ };
383
+ }
384
+ }
385
+
386
+ const resolvedPath = path.resolve(inputPath);
387
+
388
+ let matchedPrefix = '';
389
+ let relativePath = '';
390
+ let prefixMatched = false;
391
+
392
+ for (const prefix of this.resolvedPrefixes) {
393
+ if (resolvedPath === prefix || resolvedPath.startsWith(prefix + path.sep)) {
394
+ prefixMatched = true;
395
+ matchedPrefix = prefix;
396
+ relativePath = resolvedPath.slice(prefix.length);
397
+ if (relativePath.startsWith(path.sep)) {
398
+ relativePath = relativePath.slice(1);
399
+ }
400
+ break;
401
+ }
402
+ }
403
+
404
+ if (!prefixMatched) {
405
+ return {
406
+ isValid: false,
407
+ resolvedPath,
408
+ relativePath: '',
409
+ matchedPrefix: '',
410
+ errors: ['Path is outside allowed directories'],
411
+ };
412
+ }
413
+
414
+ const pathParts = resolvedPath.split(path.sep);
415
+ if (!this.config.allowHidden) {
416
+ for (const part of pathParts) {
417
+ if (part.startsWith('.') && part !== '.' && part !== '..') {
418
+ errors.push('Hidden files/directories are not allowed');
419
+ break;
420
+ }
421
+ }
422
+ }
423
+
424
+ const basename = path.basename(resolvedPath);
425
+ if (this.config.blockedNames.includes(basename)) {
426
+ errors.push(`File name "${basename}" is blocked`);
427
+ }
428
+
429
+ const ext = path.extname(resolvedPath).toLowerCase();
430
+ if (this.config.blockedExtensions.includes(ext)) {
431
+ errors.push(`File extension "${ext}" is blocked`);
432
+ }
433
+
434
+ return {
435
+ isValid: errors.length === 0,
436
+ resolvedPath,
437
+ relativePath,
438
+ matchedPrefix,
439
+ errors,
440
+ };
441
+ }
442
+
443
+ /**
444
+ * Securely joins path segments within allowed directories.
445
+ *
446
+ * @param prefix - Base directory (must be in allowedPrefixes)
447
+ * @param segments - Path segments to join
448
+ * @returns Validated resolved path
449
+ */
450
+ async securePath(prefix: string, ...segments: string[]): Promise<string> {
451
+ // Join the segments
452
+ const joined = path.join(prefix, ...segments);
453
+
454
+ // Validate the result
455
+ return this.validateOrThrow(joined);
456
+ }
457
+
458
+ /**
459
+ * Adds a prefix to the allowed list at runtime.
460
+ *
461
+ * @param prefix - Prefix to add
462
+ */
463
+ addPrefix(prefix: string): void {
464
+ const resolved = path.resolve(prefix);
465
+ if (!this.resolvedPrefixes.includes(resolved)) {
466
+ this.config.allowedPrefixes.push(prefix);
467
+ this.resolvedPrefixes.push(resolved);
468
+ }
469
+ }
470
+
471
+ /**
472
+ * Returns the current allowed prefixes.
473
+ */
474
+ getAllowedPrefixes(): readonly string[] {
475
+ return [...this.resolvedPrefixes];
476
+ }
477
+
478
+ /**
479
+ * Checks if a path is within allowed prefixes (quick check).
480
+ */
481
+ isWithinAllowed(inputPath: string): boolean {
482
+ try {
483
+ const resolved = path.resolve(inputPath);
484
+ return this.resolvedPrefixes.some(
485
+ prefix => resolved === prefix || resolved.startsWith(prefix + path.sep)
486
+ );
487
+ } catch {
488
+ return false;
489
+ }
490
+ }
491
+ }
492
+
493
+ /**
494
+ * Factory function to create a path validator for a project directory.
495
+ *
496
+ * @param projectRoot - Root directory of the project
497
+ * @returns Configured PathValidator
498
+ */
499
+ export function createProjectPathValidator(projectRoot: string): PathValidator {
500
+ const srcDir = path.join(projectRoot, 'src');
501
+ const testDir = path.join(projectRoot, 'tests');
502
+ const docsDir = path.join(projectRoot, 'docs');
503
+
504
+ return new PathValidator({
505
+ allowedPrefixes: [srcDir, testDir, docsDir],
506
+ allowHidden: false,
507
+ });
508
+ }
509
+
510
+ /**
511
+ * Factory function to create a path validator for the entire project.
512
+ *
513
+ * @param projectRoot - Root directory of the project
514
+ * @returns Configured PathValidator
515
+ */
516
+ export function createFullProjectPathValidator(projectRoot: string): PathValidator {
517
+ return new PathValidator({
518
+ allowedPrefixes: [projectRoot],
519
+ allowHidden: true, // Allow .gitignore, etc.
520
+ blockedNames: [
521
+ ...DEFAULT_BLOCKED_NAMES,
522
+ 'node_modules', // Block access to node_modules
523
+ ],
524
+ });
525
+ }