@howlil/ez-agents 3.4.1 → 3.5.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.
Files changed (162) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +84 -20
  3. package/agents/ez-observer-agent.md +260 -0
  4. package/agents/ez-release-agent.md +333 -0
  5. package/agents/ez-requirements-agent.md +377 -0
  6. package/agents/ez-scrum-master-agent.md +242 -0
  7. package/agents/ez-tech-lead-agent.md +267 -0
  8. package/bin/install.js +3221 -3230
  9. package/commands/ez/arch-review.md +102 -0
  10. package/commands/ez/execute-phase.md +11 -0
  11. package/commands/ez/export-session.md +79 -0
  12. package/commands/ez/gather-requirements.md +117 -0
  13. package/commands/ez/git-workflow.md +72 -0
  14. package/commands/ez/hotfix.md +120 -0
  15. package/commands/ez/import-session.md +82 -0
  16. package/commands/ez/join-discord.md +18 -18
  17. package/commands/ez/list-sessions.md +96 -0
  18. package/commands/ez/package-manager.md +316 -0
  19. package/commands/ez/plan-phase.md +9 -1
  20. package/commands/ez/preflight.md +79 -0
  21. package/commands/ez/progress.md +13 -1
  22. package/commands/ez/release.md +153 -0
  23. package/commands/ez/resume.md +107 -0
  24. package/commands/ez/standup.md +85 -0
  25. package/ez-agents/bin/ez-tools.cjs +1095 -716
  26. package/ez-agents/bin/lib/assistant-adapter.cjs +264 -264
  27. package/ez-agents/bin/lib/audit-exec.cjs +7 -2
  28. package/ez-agents/bin/lib/bdd-validator.cjs +622 -0
  29. package/ez-agents/bin/lib/circuit-breaker.cjs +118 -118
  30. package/ez-agents/bin/lib/config.cjs +190 -190
  31. package/ez-agents/bin/lib/content-scanner.cjs +238 -0
  32. package/ez-agents/bin/lib/context-cache.cjs +154 -0
  33. package/ez-agents/bin/lib/context-errors.cjs +71 -0
  34. package/ez-agents/bin/lib/context-manager.cjs +220 -0
  35. package/ez-agents/bin/lib/discussion-synthesizer.cjs +458 -0
  36. package/ez-agents/bin/lib/file-access.cjs +207 -0
  37. package/ez-agents/bin/lib/file-lock.cjs +236 -236
  38. package/ez-agents/bin/lib/frontmatter.cjs +299 -299
  39. package/ez-agents/bin/lib/fs-utils.cjs +153 -153
  40. package/ez-agents/bin/lib/git-errors.cjs +83 -0
  41. package/ez-agents/bin/lib/git-utils.cjs +118 -0
  42. package/ez-agents/bin/lib/git-workflow-engine.cjs +1157 -0
  43. package/ez-agents/bin/lib/index.cjs +157 -113
  44. package/ez-agents/bin/lib/init.cjs +757 -757
  45. package/ez-agents/bin/lib/lockfile-validator.cjs +227 -0
  46. package/ez-agents/bin/lib/logger.cjs +124 -124
  47. package/ez-agents/bin/lib/memory-compression.cjs +256 -0
  48. package/ez-agents/bin/lib/metrics-tracker.cjs +406 -0
  49. package/ez-agents/bin/lib/milestone.cjs +241 -241
  50. package/ez-agents/bin/lib/model-provider.cjs +241 -241
  51. package/ez-agents/bin/lib/package-manager-detector.cjs +203 -0
  52. package/ez-agents/bin/lib/package-manager-executor.cjs +385 -0
  53. package/ez-agents/bin/lib/package-manager-service.cjs +216 -0
  54. package/ez-agents/bin/lib/phase.cjs +925 -925
  55. package/ez-agents/bin/lib/planning-write.cjs +107 -107
  56. package/ez-agents/bin/lib/release-validator.cjs +614 -0
  57. package/ez-agents/bin/lib/retry.cjs +119 -119
  58. package/ez-agents/bin/lib/roadmap.cjs +306 -306
  59. package/ez-agents/bin/lib/safe-exec.cjs +128 -128
  60. package/ez-agents/bin/lib/safe-path.cjs +130 -130
  61. package/ez-agents/bin/lib/session-chain.cjs +304 -0
  62. package/ez-agents/bin/lib/session-errors.cjs +81 -0
  63. package/ez-agents/bin/lib/session-export.cjs +251 -0
  64. package/ez-agents/bin/lib/session-import.cjs +262 -0
  65. package/ez-agents/bin/lib/session-manager.cjs +280 -0
  66. package/ez-agents/bin/lib/state.cjs +736 -736
  67. package/ez-agents/bin/lib/temp-file.cjs +239 -239
  68. package/ez-agents/bin/lib/template.cjs +223 -223
  69. package/ez-agents/bin/lib/test-file-lock.cjs +112 -112
  70. package/ez-agents/bin/lib/test-graceful.cjs +93 -93
  71. package/ez-agents/bin/lib/test-logger.cjs +60 -60
  72. package/ez-agents/bin/lib/test-safe-exec.cjs +38 -38
  73. package/ez-agents/bin/lib/test-safe-path.cjs +33 -33
  74. package/ez-agents/bin/lib/test-temp-file.cjs +125 -125
  75. package/ez-agents/bin/lib/tier-manager.cjs +428 -0
  76. package/ez-agents/bin/lib/timeout-exec.cjs +63 -63
  77. package/ez-agents/bin/lib/url-fetch.cjs +170 -0
  78. package/ez-agents/bin/lib/verify.cjs +15 -1
  79. package/ez-agents/references/checkpoints.md +776 -776
  80. package/ez-agents/references/continuation-format.md +249 -249
  81. package/ez-agents/references/metrics-schema.md +118 -0
  82. package/ez-agents/references/planning-config.md +140 -0
  83. package/ez-agents/references/questioning.md +162 -162
  84. package/ez-agents/references/tdd.md +263 -263
  85. package/ez-agents/references/tier-strategy.md +103 -0
  86. package/ez-agents/templates/bdd-feature.md +173 -0
  87. package/ez-agents/templates/codebase/concerns.md +310 -310
  88. package/ez-agents/templates/codebase/conventions.md +307 -307
  89. package/ez-agents/templates/codebase/integrations.md +280 -280
  90. package/ez-agents/templates/codebase/stack.md +186 -186
  91. package/ez-agents/templates/codebase/testing.md +480 -480
  92. package/ez-agents/templates/config.json +37 -37
  93. package/ez-agents/templates/continue-here.md +78 -78
  94. package/ez-agents/templates/discussion.md +68 -0
  95. package/ez-agents/templates/incident-runbook.md +205 -0
  96. package/ez-agents/templates/milestone-archive.md +123 -123
  97. package/ez-agents/templates/milestone.md +115 -115
  98. package/ez-agents/templates/release-checklist.md +133 -0
  99. package/ez-agents/templates/requirements.md +231 -231
  100. package/ez-agents/templates/research-project/ARCHITECTURE.md +204 -204
  101. package/ez-agents/templates/research-project/FEATURES.md +147 -147
  102. package/ez-agents/templates/research-project/PITFALLS.md +200 -200
  103. package/ez-agents/templates/research-project/STACK.md +120 -120
  104. package/ez-agents/templates/research-project/SUMMARY.md +170 -170
  105. package/ez-agents/templates/retrospective.md +54 -54
  106. package/ez-agents/templates/roadmap.md +202 -202
  107. package/ez-agents/templates/rollback-plan.md +201 -0
  108. package/ez-agents/templates/summary-minimal.md +41 -41
  109. package/ez-agents/templates/summary-standard.md +48 -48
  110. package/ez-agents/templates/summary.md +248 -248
  111. package/ez-agents/templates/user-setup.md +311 -311
  112. package/ez-agents/templates/verification-report.md +322 -322
  113. package/ez-agents/workflows/add-phase.md +112 -112
  114. package/ez-agents/workflows/add-tests.md +351 -351
  115. package/ez-agents/workflows/add-todo.md +158 -158
  116. package/ez-agents/workflows/arch-review.md +54 -0
  117. package/ez-agents/workflows/audit-milestone.md +332 -332
  118. package/ez-agents/workflows/autonomous.md +131 -30
  119. package/ez-agents/workflows/check-todos.md +177 -177
  120. package/ez-agents/workflows/cleanup.md +152 -152
  121. package/ez-agents/workflows/complete-milestone.md +766 -766
  122. package/ez-agents/workflows/diagnose-issues.md +219 -219
  123. package/ez-agents/workflows/discovery-phase.md +289 -289
  124. package/ez-agents/workflows/discuss-phase.md +762 -762
  125. package/ez-agents/workflows/execute-phase.md +513 -468
  126. package/ez-agents/workflows/execute-plan.md +483 -483
  127. package/ez-agents/workflows/export-session.md +255 -0
  128. package/ez-agents/workflows/gather-requirements.md +206 -0
  129. package/ez-agents/workflows/health.md +159 -159
  130. package/ez-agents/workflows/help.md +584 -492
  131. package/ez-agents/workflows/hotfix.md +291 -0
  132. package/ez-agents/workflows/import-session.md +303 -0
  133. package/ez-agents/workflows/insert-phase.md +130 -130
  134. package/ez-agents/workflows/list-phase-assumptions.md +178 -178
  135. package/ez-agents/workflows/map-codebase.md +316 -316
  136. package/ez-agents/workflows/new-milestone.md +339 -10
  137. package/ez-agents/workflows/new-project.md +293 -299
  138. package/ez-agents/workflows/node-repair.md +92 -92
  139. package/ez-agents/workflows/pause-work.md +122 -122
  140. package/ez-agents/workflows/plan-milestone-gaps.md +274 -274
  141. package/ez-agents/workflows/plan-phase.md +673 -651
  142. package/ez-agents/workflows/progress.md +372 -382
  143. package/ez-agents/workflows/quick.md +610 -610
  144. package/ez-agents/workflows/release.md +253 -0
  145. package/ez-agents/workflows/remove-phase.md +155 -155
  146. package/ez-agents/workflows/research-phase.md +74 -74
  147. package/ez-agents/workflows/resume-project.md +307 -307
  148. package/ez-agents/workflows/resume-session.md +215 -0
  149. package/ez-agents/workflows/set-profile.md +81 -81
  150. package/ez-agents/workflows/settings.md +242 -242
  151. package/ez-agents/workflows/standup.md +64 -0
  152. package/ez-agents/workflows/stats.md +57 -57
  153. package/ez-agents/workflows/transition.md +544 -544
  154. package/ez-agents/workflows/ui-phase.md +290 -290
  155. package/ez-agents/workflows/ui-review.md +157 -157
  156. package/ez-agents/workflows/update.md +320 -320
  157. package/ez-agents/workflows/validate-phase.md +167 -167
  158. package/ez-agents/workflows/verify-phase.md +243 -243
  159. package/ez-agents/workflows/verify-work.md +584 -584
  160. package/package.json +10 -4
  161. package/scripts/build-hooks.js +43 -43
  162. package/scripts/run-tests.cjs +29 -29
@@ -1,128 +1,128 @@
1
- #!/usr/bin/env node
2
-
3
- /**
4
- * EZ Safe Exec — Secure command execution with allowlist and validation
5
- *
6
- * Prevents command injection by:
7
- * - Using execFile instead of execSync with string concatenation
8
- * - Validating commands against allowlist
9
- * - Blocking dangerous shell metacharacters in arguments
10
- * - Logging all commands for audit
11
- *
12
- * Usage:
13
- * const { safeExec, safeExecJSON } = require('./safe-exec.cjs');
14
- * const result = await safeExec('git', ['status']);
15
- */
16
-
17
- const { execFile } = require('child_process');
18
- const { promisify } = require('util');
19
- const execFileAsync = promisify(execFile);
20
- const Logger = require('./logger.cjs');
21
- const logger = new Logger();
22
-
23
- // Allowlist of safe commands
24
- const ALLOWED_COMMANDS = new Set([
25
- 'git', 'node', 'npm', 'npx', 'find', 'grep', 'head', 'tail', 'wc',
26
- 'mkdir', 'cp', 'mv', 'rm', 'cat', 'echo', 'test', 'ls', 'dir',
27
- 'pwd', 'cd', 'type', 'where', 'which', 'chmod', 'touch'
28
- ]);
29
-
30
- // Dangerous shell metacharacters that could enable injection
31
- const DANGEROUS_PATTERN = /[;&|`$(){}\\<>]/;
32
-
33
- /**
34
- * Validate command is in allowlist
35
- * @param {string} cmd - Command to validate
36
- * @throws {Error} If command not allowed
37
- */
38
- function validateCommand(cmd) {
39
- const baseCmd = cmd.split(' ')[0].toLowerCase();
40
- if (!ALLOWED_COMMANDS.has(baseCmd)) {
41
- throw new Error(`Command not allowed: ${cmd}. Allowed: ${Array.from(ALLOWED_COMMANDS).join(', ')}`);
42
- }
43
- }
44
-
45
- /**
46
- * Validate arguments don't contain injection patterns
47
- * @param {string[]} args - Arguments to validate
48
- * @throws {Error} If dangerous pattern found
49
- */
50
- function validateArgs(args) {
51
- for (const arg of args) {
52
- if (DANGEROUS_PATTERN.test(arg)) {
53
- throw new Error(`Dangerous argument rejected: ${arg}`);
54
- }
55
- }
56
- }
57
-
58
- /**
59
- * Execute command safely with validation and logging
60
- * @param {string} cmd - Command to execute
61
- * @param {string[]} args - Command arguments
62
- * @param {Object} options - Execution options
63
- * @returns {Promise<string>} - Command stdout
64
- */
65
- async function safeExec(cmd, args = [], options = {}) {
66
- const { timeout = 30000, log = true } = options;
67
-
68
- // Validate command and arguments
69
- validateCommand(cmd);
70
- validateArgs(args);
71
-
72
- const startTime = Date.now();
73
-
74
- try {
75
- if (log) {
76
- logger.info('Executing command', {
77
- cmd,
78
- args,
79
- timestamp: new Date().toISOString()
80
- });
81
- }
82
-
83
- const result = await execFileAsync(cmd, args, {
84
- timeout,
85
- maxBuffer: 10 * 1024 * 1024 // 10MB buffer
86
- });
87
-
88
- const duration = Date.now() - startTime;
89
- if (log) {
90
- logger.debug('Command completed', {
91
- cmd,
92
- duration,
93
- stdout_length: result.stdout?.length || 0
94
- });
95
- }
96
-
97
- return result.stdout.trim();
98
- } catch (err) {
99
- const duration = Date.now() - startTime;
100
- logger.error('Command failed', {
101
- cmd,
102
- args,
103
- error: err.message,
104
- duration,
105
- code: err.code,
106
- signal: err.signal
107
- });
108
- throw err;
109
- }
110
- }
111
-
112
- /**
113
- * Execute command and return JSON parsed output
114
- * @param {string} cmd - Command to execute
115
- * @param {string[]} args - Command arguments
116
- * @returns {Promise<Object>} - Parsed JSON output
117
- */
118
- async function safeExecJSON(cmd, args = []) {
119
- const output = await safeExec(cmd, args);
120
- try {
121
- return JSON.parse(output);
122
- } catch (err) {
123
- logger.error('Failed to parse JSON output', { cmd, output });
124
- throw new Error(`Invalid JSON from ${cmd}: ${err.message}`);
125
- }
126
- }
127
-
128
- module.exports = { safeExec, safeExecJSON, ALLOWED_COMMANDS };
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * EZ Safe Exec — Secure command execution with allowlist and validation
5
+ *
6
+ * Prevents command injection by:
7
+ * - Using execFile instead of execSync with string concatenation
8
+ * - Validating commands against allowlist
9
+ * - Blocking dangerous shell metacharacters in arguments
10
+ * - Logging all commands for audit
11
+ *
12
+ * Usage:
13
+ * const { safeExec, safeExecJSON } = require('./safe-exec.cjs');
14
+ * const result = await safeExec('git', ['status']);
15
+ */
16
+
17
+ const { execFile } = require('child_process');
18
+ const { promisify } = require('util');
19
+ const execFileAsync = promisify(execFile);
20
+ const Logger = require('./logger.cjs');
21
+ const logger = new Logger();
22
+
23
+ // Allowlist of safe commands
24
+ const ALLOWED_COMMANDS = new Set([
25
+ 'git', 'node', 'npm', 'npx', 'find', 'grep', 'head', 'tail', 'wc',
26
+ 'mkdir', 'cp', 'mv', 'rm', 'cat', 'echo', 'test', 'ls', 'dir',
27
+ 'pwd', 'cd', 'type', 'where', 'which', 'chmod', 'touch'
28
+ ]);
29
+
30
+ // Dangerous shell metacharacters that could enable injection
31
+ const DANGEROUS_PATTERN = /[;&|`$(){}\\<>]/;
32
+
33
+ /**
34
+ * Validate command is in allowlist
35
+ * @param {string} cmd - Command to validate
36
+ * @throws {Error} If command not allowed
37
+ */
38
+ function validateCommand(cmd) {
39
+ const baseCmd = cmd.split(' ')[0].toLowerCase();
40
+ if (!ALLOWED_COMMANDS.has(baseCmd)) {
41
+ throw new Error(`Command not allowed: ${cmd}. Allowed: ${Array.from(ALLOWED_COMMANDS).join(', ')}`);
42
+ }
43
+ }
44
+
45
+ /**
46
+ * Validate arguments don't contain injection patterns
47
+ * @param {string[]} args - Arguments to validate
48
+ * @throws {Error} If dangerous pattern found
49
+ */
50
+ function validateArgs(args) {
51
+ for (const arg of args) {
52
+ if (DANGEROUS_PATTERN.test(arg)) {
53
+ throw new Error(`Dangerous argument rejected: ${arg}`);
54
+ }
55
+ }
56
+ }
57
+
58
+ /**
59
+ * Execute command safely with validation and logging
60
+ * @param {string} cmd - Command to execute
61
+ * @param {string[]} args - Command arguments
62
+ * @param {Object} options - Execution options
63
+ * @returns {Promise<string>} - Command stdout
64
+ */
65
+ async function safeExec(cmd, args = [], options = {}) {
66
+ const { timeout = 30000, log = true } = options;
67
+
68
+ // Validate command and arguments
69
+ validateCommand(cmd);
70
+ validateArgs(args);
71
+
72
+ const startTime = Date.now();
73
+
74
+ try {
75
+ if (log) {
76
+ logger.info('Executing command', {
77
+ cmd,
78
+ args,
79
+ timestamp: new Date().toISOString()
80
+ });
81
+ }
82
+
83
+ const result = await execFileAsync(cmd, args, {
84
+ timeout,
85
+ maxBuffer: 10 * 1024 * 1024 // 10MB buffer
86
+ });
87
+
88
+ const duration = Date.now() - startTime;
89
+ if (log) {
90
+ logger.debug('Command completed', {
91
+ cmd,
92
+ duration,
93
+ stdout_length: result.stdout?.length || 0
94
+ });
95
+ }
96
+
97
+ return result.stdout.trim();
98
+ } catch (err) {
99
+ const duration = Date.now() - startTime;
100
+ logger.error('Command failed', {
101
+ cmd,
102
+ args,
103
+ error: err.message,
104
+ duration,
105
+ code: err.code,
106
+ signal: err.signal
107
+ });
108
+ throw err;
109
+ }
110
+ }
111
+
112
+ /**
113
+ * Execute command and return JSON parsed output
114
+ * @param {string} cmd - Command to execute
115
+ * @param {string[]} args - Command arguments
116
+ * @returns {Promise<Object>} - Parsed JSON output
117
+ */
118
+ async function safeExecJSON(cmd, args = []) {
119
+ const output = await safeExec(cmd, args);
120
+ try {
121
+ return JSON.parse(output);
122
+ } catch (err) {
123
+ logger.error('Failed to parse JSON output', { cmd, output });
124
+ throw new Error(`Invalid JSON from ${cmd}: ${err.message}`);
125
+ }
126
+ }
127
+
128
+ module.exports = { safeExec, safeExecJSON, ALLOWED_COMMANDS };
@@ -1,130 +1,130 @@
1
- #!/usr/bin/env node
2
-
3
- /**
4
- * EZ Safe Path — Path traversal prevention utility
5
- *
6
- * Prevents path traversal attacks by:
7
- * - Resolving and validating paths against base directory
8
- * - Blocking paths that escape base directory
9
- * - Handling Windows and Unix path formats
10
- * - Logging blocked attempts for security audit
11
- *
12
- * Usage:
13
- * const { normalizePath, isPathSafe, safeReadFile } = require('./safe-path.cjs');
14
- * const safePath = normalizePath(process.cwd(), userPath);
15
- */
16
-
17
- const path = require('path');
18
- const fs = require('fs');
19
- const Logger = require('./logger.cjs');
20
- const logger = new Logger();
21
-
22
- /**
23
- * Normalize and validate a user-provided path against a base directory
24
- * @param {string} baseDir - Base directory (trusted)
25
- * @param {string} userPath - User-provided path (untrusted)
26
- * @returns {string} - Resolved absolute path if safe
27
- * @throws {Error} If path traversal detected
28
- */
29
- function normalizePath(baseDir, userPath) {
30
- // Resolve both paths to absolute
31
- const resolvedBase = path.resolve(baseDir);
32
- const resolvedUser = path.resolve(baseDir, userPath);
33
-
34
- // Normalize for comparison (handle Windows backslashes)
35
- const normalizedBase = resolvedBase + path.sep;
36
-
37
- // Check if user path is within base directory
38
- const isWithin =
39
- resolvedUser === resolvedBase ||
40
- resolvedUser.startsWith(normalizedBase);
41
-
42
- if (!isWithin) {
43
- logger.error('Path traversal detected', {
44
- baseDir: resolvedBase,
45
- userPath,
46
- resolvedUser,
47
- timestamp: new Date().toISOString()
48
- });
49
- throw new Error(`Path traversal detected: ${userPath}`);
50
- }
51
-
52
- return resolvedUser;
53
- }
54
-
55
- /**
56
- * Check if a path is safe (within base directory) without throwing
57
- * @param {string} baseDir - Base directory (trusted)
58
- * @param {string} userPath - User-provided path (untrusted)
59
- * @returns {boolean} - True if path is safe
60
- */
61
- function isPathSafe(baseDir, userPath) {
62
- try {
63
- normalizePath(baseDir, userPath);
64
- return true;
65
- } catch (err) {
66
- return false;
67
- }
68
- }
69
-
70
- /**
71
- * Validate path exists and is safe
72
- * @param {string} baseDir - Base directory
73
- * @param {string} userPath - User-provided path
74
- * @returns {string} - Resolved path if exists and safe
75
- * @throws {Error} If not found or traversal detected
76
- */
77
- function validatePathExists(baseDir, userPath) {
78
- const resolvedPath = normalizePath(baseDir, userPath);
79
-
80
- if (!fs.existsSync(resolvedPath)) {
81
- logger.warn('Path does not exist', {
82
- resolvedPath,
83
- userPath
84
- });
85
- throw new Error(`Path not found: ${userPath}`);
86
- }
87
-
88
- return resolvedPath;
89
- }
90
-
91
- /**
92
- * Safely read a file (validates path before reading)
93
- * @param {string} baseDir - Base directory
94
- * @param {string} userPath - User-provided path
95
- * @param {string} encoding - File encoding (default: utf-8)
96
- * @returns {string} - File content
97
- * @throws {Error} If path unsafe or file not found
98
- */
99
- function safeReadFile(baseDir, userPath, encoding = 'utf-8') {
100
- const resolvedPath = validatePathExists(baseDir, userPath);
101
-
102
- logger.debug('Reading file', { resolvedPath, userPath });
103
-
104
- return fs.readFileSync(resolvedPath, encoding);
105
- }
106
-
107
- /**
108
- * Get relative path from base, with validation
109
- * @param {string} baseDir - Base directory
110
- * @param {string} fullPath - Full path to convert
111
- * @returns {string} - Relative path or throws if outside base
112
- */
113
- function toRelativePath(baseDir, fullPath) {
114
- const resolvedFull = path.resolve(fullPath);
115
- const resolvedBase = path.resolve(baseDir);
116
-
117
- if (!isPathSafe(baseDir, resolvedFull)) {
118
- throw new Error(`Path outside base: ${fullPath}`);
119
- }
120
-
121
- return path.relative(resolvedBase, resolvedFull);
122
- }
123
-
124
- module.exports = {
125
- normalizePath,
126
- isPathSafe,
127
- validatePathExists,
128
- safeReadFile,
129
- toRelativePath
130
- };
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * EZ Safe Path — Path traversal prevention utility
5
+ *
6
+ * Prevents path traversal attacks by:
7
+ * - Resolving and validating paths against base directory
8
+ * - Blocking paths that escape base directory
9
+ * - Handling Windows and Unix path formats
10
+ * - Logging blocked attempts for security audit
11
+ *
12
+ * Usage:
13
+ * const { normalizePath, isPathSafe, safeReadFile } = require('./safe-path.cjs');
14
+ * const safePath = normalizePath(process.cwd(), userPath);
15
+ */
16
+
17
+ const path = require('path');
18
+ const fs = require('fs');
19
+ const Logger = require('./logger.cjs');
20
+ const logger = new Logger();
21
+
22
+ /**
23
+ * Normalize and validate a user-provided path against a base directory
24
+ * @param {string} baseDir - Base directory (trusted)
25
+ * @param {string} userPath - User-provided path (untrusted)
26
+ * @returns {string} - Resolved absolute path if safe
27
+ * @throws {Error} If path traversal detected
28
+ */
29
+ function normalizePath(baseDir, userPath) {
30
+ // Resolve both paths to absolute
31
+ const resolvedBase = path.resolve(baseDir);
32
+ const resolvedUser = path.resolve(baseDir, userPath);
33
+
34
+ // Normalize for comparison (handle Windows backslashes)
35
+ const normalizedBase = resolvedBase + path.sep;
36
+
37
+ // Check if user path is within base directory
38
+ const isWithin =
39
+ resolvedUser === resolvedBase ||
40
+ resolvedUser.startsWith(normalizedBase);
41
+
42
+ if (!isWithin) {
43
+ logger.error('Path traversal detected', {
44
+ baseDir: resolvedBase,
45
+ userPath,
46
+ resolvedUser,
47
+ timestamp: new Date().toISOString()
48
+ });
49
+ throw new Error(`Path traversal detected: ${userPath}`);
50
+ }
51
+
52
+ return resolvedUser;
53
+ }
54
+
55
+ /**
56
+ * Check if a path is safe (within base directory) without throwing
57
+ * @param {string} baseDir - Base directory (trusted)
58
+ * @param {string} userPath - User-provided path (untrusted)
59
+ * @returns {boolean} - True if path is safe
60
+ */
61
+ function isPathSafe(baseDir, userPath) {
62
+ try {
63
+ normalizePath(baseDir, userPath);
64
+ return true;
65
+ } catch (err) {
66
+ return false;
67
+ }
68
+ }
69
+
70
+ /**
71
+ * Validate path exists and is safe
72
+ * @param {string} baseDir - Base directory
73
+ * @param {string} userPath - User-provided path
74
+ * @returns {string} - Resolved path if exists and safe
75
+ * @throws {Error} If not found or traversal detected
76
+ */
77
+ function validatePathExists(baseDir, userPath) {
78
+ const resolvedPath = normalizePath(baseDir, userPath);
79
+
80
+ if (!fs.existsSync(resolvedPath)) {
81
+ logger.warn('Path does not exist', {
82
+ resolvedPath,
83
+ userPath
84
+ });
85
+ throw new Error(`Path not found: ${userPath}`);
86
+ }
87
+
88
+ return resolvedPath;
89
+ }
90
+
91
+ /**
92
+ * Safely read a file (validates path before reading)
93
+ * @param {string} baseDir - Base directory
94
+ * @param {string} userPath - User-provided path
95
+ * @param {string} encoding - File encoding (default: utf-8)
96
+ * @returns {string} - File content
97
+ * @throws {Error} If path unsafe or file not found
98
+ */
99
+ function safeReadFile(baseDir, userPath, encoding = 'utf-8') {
100
+ const resolvedPath = validatePathExists(baseDir, userPath);
101
+
102
+ logger.debug('Reading file', { resolvedPath, userPath });
103
+
104
+ return fs.readFileSync(resolvedPath, encoding);
105
+ }
106
+
107
+ /**
108
+ * Get relative path from base, with validation
109
+ * @param {string} baseDir - Base directory
110
+ * @param {string} fullPath - Full path to convert
111
+ * @returns {string} - Relative path or throws if outside base
112
+ */
113
+ function toRelativePath(baseDir, fullPath) {
114
+ const resolvedFull = path.resolve(fullPath);
115
+ const resolvedBase = path.resolve(baseDir);
116
+
117
+ if (!isPathSafe(baseDir, resolvedFull)) {
118
+ throw new Error(`Path outside base: ${fullPath}`);
119
+ }
120
+
121
+ return path.relative(resolvedBase, resolvedFull);
122
+ }
123
+
124
+ module.exports = {
125
+ normalizePath,
126
+ isPathSafe,
127
+ validatePathExists,
128
+ safeReadFile,
129
+ toRelativePath
130
+ };