code-as-plan 2.0.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.
- package/LICENSE +21 -0
- package/README.ja-JP.md +834 -0
- package/README.ko-KR.md +823 -0
- package/README.md +1006 -0
- package/README.pt-BR.md +452 -0
- package/README.zh-CN.md +800 -0
- package/agents/cap-brainstormer.md +154 -0
- package/agents/cap-debugger.md +221 -0
- package/agents/cap-prototyper.md +170 -0
- package/agents/cap-reviewer.md +230 -0
- package/agents/cap-tester.md +193 -0
- package/bin/install.js +5002 -0
- package/cap/bin/gsd-tools.cjs +1141 -0
- package/cap/bin/lib/arc-scanner.cjs +341 -0
- package/cap/bin/lib/cap-feature-map.cjs +506 -0
- package/cap/bin/lib/cap-session.cjs +191 -0
- package/cap/bin/lib/cap-stack-docs.cjs +598 -0
- package/cap/bin/lib/cap-tag-scanner.cjs +458 -0
- package/cap/bin/lib/commands.cjs +959 -0
- package/cap/bin/lib/config.cjs +466 -0
- package/cap/bin/lib/convention-reader.cjs +180 -0
- package/cap/bin/lib/core.cjs +1230 -0
- package/cap/bin/lib/feature-aggregator.cjs +422 -0
- package/cap/bin/lib/frontmatter.cjs +336 -0
- package/cap/bin/lib/init.cjs +1442 -0
- package/cap/bin/lib/manifest-generator.cjs +381 -0
- package/cap/bin/lib/milestone.cjs +252 -0
- package/cap/bin/lib/model-profiles.cjs +68 -0
- package/cap/bin/lib/monorepo-context.cjs +224 -0
- package/cap/bin/lib/monorepo-migrator.cjs +507 -0
- package/cap/bin/lib/phase.cjs +888 -0
- package/cap/bin/lib/profile-output.cjs +952 -0
- package/cap/bin/lib/profile-pipeline.cjs +539 -0
- package/cap/bin/lib/roadmap.cjs +329 -0
- package/cap/bin/lib/security.cjs +382 -0
- package/cap/bin/lib/session-manager.cjs +290 -0
- package/cap/bin/lib/skeleton-generator.cjs +177 -0
- package/cap/bin/lib/state.cjs +1031 -0
- package/cap/bin/lib/template.cjs +222 -0
- package/cap/bin/lib/test-detector.cjs +61 -0
- package/cap/bin/lib/uat.cjs +282 -0
- package/cap/bin/lib/verify.cjs +888 -0
- package/cap/bin/lib/workspace-detector.cjs +369 -0
- package/cap/bin/lib/workstream.cjs +491 -0
- package/cap/commands/gsd/workstreams.md +63 -0
- package/cap/references/arc-standard.md +315 -0
- package/cap/references/cap-agent-architecture.md +102 -0
- package/cap/references/cap-gitignore-template +9 -0
- package/cap/references/cap-zero-deps.md +158 -0
- package/cap/references/checkpoints.md +778 -0
- package/cap/references/continuation-format.md +249 -0
- package/cap/references/decimal-phase-calculation.md +64 -0
- package/cap/references/feature-map-template.md +25 -0
- package/cap/references/git-integration.md +295 -0
- package/cap/references/git-planning-commit.md +38 -0
- package/cap/references/model-profile-resolution.md +36 -0
- package/cap/references/model-profiles.md +139 -0
- package/cap/references/phase-argument-parsing.md +61 -0
- package/cap/references/planning-config.md +202 -0
- package/cap/references/questioning.md +162 -0
- package/cap/references/session-template.json +8 -0
- package/cap/references/tdd.md +263 -0
- package/cap/references/ui-brand.md +160 -0
- package/cap/references/user-profiling.md +681 -0
- package/cap/references/verification-patterns.md +612 -0
- package/cap/references/workstream-flag.md +58 -0
- package/cap/templates/DEBUG.md +164 -0
- package/cap/templates/UAT.md +265 -0
- package/cap/templates/UI-SPEC.md +100 -0
- package/cap/templates/VALIDATION.md +76 -0
- package/cap/templates/claude-md.md +122 -0
- package/cap/templates/codebase/architecture.md +255 -0
- package/cap/templates/codebase/concerns.md +310 -0
- package/cap/templates/codebase/conventions.md +307 -0
- package/cap/templates/codebase/integrations.md +280 -0
- package/cap/templates/codebase/stack.md +186 -0
- package/cap/templates/codebase/structure.md +285 -0
- package/cap/templates/codebase/testing.md +480 -0
- package/cap/templates/config.json +44 -0
- package/cap/templates/context.md +352 -0
- package/cap/templates/continue-here.md +78 -0
- package/cap/templates/copilot-instructions.md +7 -0
- package/cap/templates/debug-subagent-prompt.md +91 -0
- package/cap/templates/dev-preferences.md +21 -0
- package/cap/templates/discovery.md +146 -0
- package/cap/templates/discussion-log.md +63 -0
- package/cap/templates/milestone-archive.md +123 -0
- package/cap/templates/milestone.md +115 -0
- package/cap/templates/phase-prompt.md +610 -0
- package/cap/templates/planner-subagent-prompt.md +117 -0
- package/cap/templates/project.md +186 -0
- package/cap/templates/requirements.md +231 -0
- package/cap/templates/research-project/ARCHITECTURE.md +204 -0
- package/cap/templates/research-project/FEATURES.md +147 -0
- package/cap/templates/research-project/PITFALLS.md +200 -0
- package/cap/templates/research-project/STACK.md +120 -0
- package/cap/templates/research-project/SUMMARY.md +170 -0
- package/cap/templates/research.md +552 -0
- package/cap/templates/retrospective.md +54 -0
- package/cap/templates/roadmap.md +202 -0
- package/cap/templates/state.md +176 -0
- package/cap/templates/summary-complex.md +59 -0
- package/cap/templates/summary-minimal.md +41 -0
- package/cap/templates/summary-standard.md +48 -0
- package/cap/templates/summary.md +248 -0
- package/cap/templates/user-profile.md +146 -0
- package/cap/templates/user-setup.md +311 -0
- package/cap/templates/verification-report.md +322 -0
- package/cap/workflows/add-phase.md +112 -0
- package/cap/workflows/add-tests.md +351 -0
- package/cap/workflows/add-todo.md +158 -0
- package/cap/workflows/audit-milestone.md +340 -0
- package/cap/workflows/audit-uat.md +109 -0
- package/cap/workflows/autonomous.md +891 -0
- package/cap/workflows/check-todos.md +177 -0
- package/cap/workflows/cleanup.md +152 -0
- package/cap/workflows/complete-milestone.md +767 -0
- package/cap/workflows/diagnose-issues.md +231 -0
- package/cap/workflows/discovery-phase.md +289 -0
- package/cap/workflows/discuss-phase-assumptions.md +653 -0
- package/cap/workflows/discuss-phase.md +1049 -0
- package/cap/workflows/do.md +104 -0
- package/cap/workflows/execute-phase.md +846 -0
- package/cap/workflows/execute-plan.md +514 -0
- package/cap/workflows/fast.md +105 -0
- package/cap/workflows/forensics.md +265 -0
- package/cap/workflows/health.md +181 -0
- package/cap/workflows/help.md +660 -0
- package/cap/workflows/insert-phase.md +130 -0
- package/cap/workflows/list-phase-assumptions.md +178 -0
- package/cap/workflows/list-workspaces.md +56 -0
- package/cap/workflows/manager.md +362 -0
- package/cap/workflows/map-codebase.md +377 -0
- package/cap/workflows/milestone-summary.md +223 -0
- package/cap/workflows/new-milestone.md +486 -0
- package/cap/workflows/new-project.md +1250 -0
- package/cap/workflows/new-workspace.md +237 -0
- package/cap/workflows/next.md +97 -0
- package/cap/workflows/node-repair.md +92 -0
- package/cap/workflows/note.md +156 -0
- package/cap/workflows/pause-work.md +176 -0
- package/cap/workflows/plan-milestone-gaps.md +273 -0
- package/cap/workflows/plan-phase.md +859 -0
- package/cap/workflows/plant-seed.md +169 -0
- package/cap/workflows/pr-branch.md +129 -0
- package/cap/workflows/profile-user.md +450 -0
- package/cap/workflows/progress.md +507 -0
- package/cap/workflows/quick.md +757 -0
- package/cap/workflows/remove-phase.md +155 -0
- package/cap/workflows/remove-workspace.md +90 -0
- package/cap/workflows/research-phase.md +82 -0
- package/cap/workflows/resume-project.md +326 -0
- package/cap/workflows/review.md +228 -0
- package/cap/workflows/session-report.md +146 -0
- package/cap/workflows/settings.md +283 -0
- package/cap/workflows/ship.md +228 -0
- package/cap/workflows/stats.md +60 -0
- package/cap/workflows/transition.md +671 -0
- package/cap/workflows/ui-phase.md +302 -0
- package/cap/workflows/ui-review.md +165 -0
- package/cap/workflows/update.md +323 -0
- package/cap/workflows/validate-phase.md +174 -0
- package/cap/workflows/verify-phase.md +254 -0
- package/cap/workflows/verify-work.md +637 -0
- package/commands/cap/annotate.md +165 -0
- package/commands/cap/brainstorm.md +238 -0
- package/commands/cap/debug.md +297 -0
- package/commands/cap/init.md +262 -0
- package/commands/cap/iterate.md +234 -0
- package/commands/cap/prototype.md +281 -0
- package/commands/cap/refresh-docs.md +37 -0
- package/commands/cap/review.md +272 -0
- package/commands/cap/scan.md +249 -0
- package/commands/cap/start.md +234 -0
- package/commands/cap/status.md +189 -0
- package/commands/cap/test.md +250 -0
- package/hooks/dist/gsd-check-update.js +114 -0
- package/hooks/dist/gsd-context-monitor.js +156 -0
- package/hooks/dist/gsd-prompt-guard.js +96 -0
- package/hooks/dist/gsd-statusline.js +119 -0
- package/hooks/dist/gsd-workflow-guard.js +94 -0
- package/package.json +51 -0
- package/scripts/base64-scan.sh +262 -0
- package/scripts/build-hooks.js +82 -0
- package/scripts/cap-removal-checklist.md +202 -0
- package/scripts/prompt-injection-scan.sh +198 -0
- package/scripts/run-tests.cjs +29 -0
- package/scripts/secret-scan.sh +227 -0
|
@@ -0,0 +1,382 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Security — Input validation, path traversal prevention, and prompt injection guards
|
|
3
|
+
*
|
|
4
|
+
* This module centralizes security checks for GSD tooling. Because GSD generates
|
|
5
|
+
* markdown files that become LLM system prompts (agent instructions, workflow state,
|
|
6
|
+
* phase plans), any user-controlled text that flows into these files is a potential
|
|
7
|
+
* indirect prompt injection vector.
|
|
8
|
+
*
|
|
9
|
+
* Threat model:
|
|
10
|
+
* 1. Path traversal: user-supplied file paths escape the project directory
|
|
11
|
+
* 2. Prompt injection: malicious text in arguments/PRDs embeds LLM instructions
|
|
12
|
+
* 3. Shell metacharacter injection: user text interpreted by shell
|
|
13
|
+
* 4. JSON injection: malformed JSON crashes or corrupts state
|
|
14
|
+
* 5. Regex DoS: crafted input causes catastrophic backtracking
|
|
15
|
+
*/
|
|
16
|
+
'use strict';
|
|
17
|
+
|
|
18
|
+
const fs = require('fs');
|
|
19
|
+
const path = require('path');
|
|
20
|
+
|
|
21
|
+
// ─── Path Traversal Prevention ──────────────────────────────────────────────
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Validate that a file path resolves within an allowed base directory.
|
|
25
|
+
* Prevents path traversal attacks via ../ sequences, symlinks, or absolute paths.
|
|
26
|
+
*
|
|
27
|
+
* @param {string} filePath - The user-supplied file path
|
|
28
|
+
* @param {string} baseDir - The allowed base directory (e.g., project root)
|
|
29
|
+
* @param {object} [opts] - Options
|
|
30
|
+
* @param {boolean} [opts.allowAbsolute=false] - Allow absolute paths (still must be within baseDir)
|
|
31
|
+
* @returns {{ safe: boolean, resolved: string, error?: string }}
|
|
32
|
+
*/
|
|
33
|
+
function validatePath(filePath, baseDir, opts = {}) {
|
|
34
|
+
if (!filePath || typeof filePath !== 'string') {
|
|
35
|
+
return { safe: false, resolved: '', error: 'Empty or invalid file path' };
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
if (!baseDir || typeof baseDir !== 'string') {
|
|
39
|
+
return { safe: false, resolved: '', error: 'Empty or invalid base directory' };
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// Reject null bytes (can bypass path checks in some environments)
|
|
43
|
+
if (filePath.includes('\0')) {
|
|
44
|
+
return { safe: false, resolved: '', error: 'Path contains null bytes' };
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// Resolve symlinks in base directory to handle macOS /var -> /private/var
|
|
48
|
+
// and similar platform-specific symlink chains
|
|
49
|
+
let resolvedBase;
|
|
50
|
+
try {
|
|
51
|
+
resolvedBase = fs.realpathSync(path.resolve(baseDir));
|
|
52
|
+
} catch {
|
|
53
|
+
resolvedBase = path.resolve(baseDir);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
let resolvedPath;
|
|
57
|
+
|
|
58
|
+
if (path.isAbsolute(filePath)) {
|
|
59
|
+
if (!opts.allowAbsolute) {
|
|
60
|
+
return { safe: false, resolved: '', error: 'Absolute paths not allowed' };
|
|
61
|
+
}
|
|
62
|
+
resolvedPath = path.resolve(filePath);
|
|
63
|
+
} else {
|
|
64
|
+
resolvedPath = path.resolve(baseDir, filePath);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// Resolve symlinks in the target path too
|
|
68
|
+
try {
|
|
69
|
+
resolvedPath = fs.realpathSync(resolvedPath);
|
|
70
|
+
} catch {
|
|
71
|
+
// File may not exist yet (e.g., about to be created) — use logical resolution
|
|
72
|
+
// but still resolve the parent directory if it exists
|
|
73
|
+
const parentDir = path.dirname(resolvedPath);
|
|
74
|
+
try {
|
|
75
|
+
const realParent = fs.realpathSync(parentDir);
|
|
76
|
+
resolvedPath = path.join(realParent, path.basename(resolvedPath));
|
|
77
|
+
} catch {
|
|
78
|
+
// Parent doesn't exist either — keep the resolved path as-is
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// Normalize both paths and check containment
|
|
83
|
+
const normalizedBase = resolvedBase + path.sep;
|
|
84
|
+
const normalizedPath = resolvedPath + path.sep;
|
|
85
|
+
|
|
86
|
+
// The resolved path must start with the base directory
|
|
87
|
+
// (or be exactly the base directory)
|
|
88
|
+
if (resolvedPath !== resolvedBase && !normalizedPath.startsWith(normalizedBase)) {
|
|
89
|
+
return {
|
|
90
|
+
safe: false,
|
|
91
|
+
resolved: resolvedPath,
|
|
92
|
+
error: `Path escapes allowed directory: ${resolvedPath} is outside ${resolvedBase}`,
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
return { safe: true, resolved: resolvedPath };
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Validate a file path and throw on traversal attempt.
|
|
101
|
+
* Convenience wrapper around validatePath for use in CLI commands.
|
|
102
|
+
*/
|
|
103
|
+
function requireSafePath(filePath, baseDir, label, opts = {}) {
|
|
104
|
+
const result = validatePath(filePath, baseDir, opts);
|
|
105
|
+
if (!result.safe) {
|
|
106
|
+
throw new Error(`${label || 'Path'} validation failed: ${result.error}`);
|
|
107
|
+
}
|
|
108
|
+
return result.resolved;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// ─── Prompt Injection Detection ─────────────────────────────────────────────
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* Patterns that indicate prompt injection attempts in user-supplied text.
|
|
115
|
+
* These patterns catch common indirect prompt injection techniques where
|
|
116
|
+
* an attacker embeds LLM instructions in text that will be read by an agent.
|
|
117
|
+
*
|
|
118
|
+
* Note: This is defense-in-depth — not a complete solution. The primary defense
|
|
119
|
+
* is proper input/output boundaries in agent prompts.
|
|
120
|
+
*/
|
|
121
|
+
const INJECTION_PATTERNS = [
|
|
122
|
+
// Direct instruction override attempts
|
|
123
|
+
/ignore\s+(all\s+)?previous\s+instructions/i,
|
|
124
|
+
/ignore\s+(all\s+)?above\s+instructions/i,
|
|
125
|
+
/disregard\s+(all\s+)?previous/i,
|
|
126
|
+
/forget\s+(all\s+)?(your\s+)?instructions/i,
|
|
127
|
+
/override\s+(system|previous)\s+(prompt|instructions)/i,
|
|
128
|
+
|
|
129
|
+
// Role/identity manipulation
|
|
130
|
+
/you\s+are\s+now\s+(?:a|an|the)\s+/i,
|
|
131
|
+
/act\s+as\s+(?:a|an|the)\s+(?!plan|phase|wave)/i, // allow "act as a plan"
|
|
132
|
+
/pretend\s+(?:you(?:'re| are)\s+|to\s+be\s+)/i,
|
|
133
|
+
/from\s+now\s+on,?\s+you\s+(?:are|will|should|must)/i,
|
|
134
|
+
|
|
135
|
+
// System prompt extraction
|
|
136
|
+
/(?:print|output|reveal|show|display|repeat)\s+(?:your\s+)?(?:system\s+)?(?:prompt|instructions)/i,
|
|
137
|
+
/what\s+(?:are|is)\s+your\s+(?:system\s+)?(?:prompt|instructions)/i,
|
|
138
|
+
|
|
139
|
+
// Hidden instruction markers (XML/HTML tags that mimic system messages)
|
|
140
|
+
// Note: <instructions> is excluded — GSD uses it as legitimate prompt structure
|
|
141
|
+
// Requires > to close the tag (not just whitespace) to avoid matching generic types like Promise<User | null>
|
|
142
|
+
/<\/?(?:system|assistant|human)>/i,
|
|
143
|
+
/\[SYSTEM\]/i,
|
|
144
|
+
/\[INST\]/i,
|
|
145
|
+
/<<\s*SYS\s*>>/i,
|
|
146
|
+
|
|
147
|
+
// Exfiltration attempts
|
|
148
|
+
/(?:send|post|fetch|curl|wget)\s+(?:to|from)\s+https?:\/\//i,
|
|
149
|
+
/(?:base64|btoa|encode)\s+(?:and\s+)?(?:send|exfiltrate|output)/i,
|
|
150
|
+
|
|
151
|
+
// Tool manipulation
|
|
152
|
+
/(?:run|execute|call|invoke)\s+(?:the\s+)?(?:bash|shell|exec|spawn)\s+(?:tool|command)/i,
|
|
153
|
+
];
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* Scan text for potential prompt injection patterns.
|
|
157
|
+
* Returns an array of findings (empty = clean).
|
|
158
|
+
*
|
|
159
|
+
* @param {string} text - The text to scan
|
|
160
|
+
* @param {object} [opts] - Options
|
|
161
|
+
* @param {boolean} [opts.strict=false] - Enable stricter matching (more false positives)
|
|
162
|
+
* @returns {{ clean: boolean, findings: string[] }}
|
|
163
|
+
*/
|
|
164
|
+
function scanForInjection(text, opts = {}) {
|
|
165
|
+
if (!text || typeof text !== 'string') {
|
|
166
|
+
return { clean: true, findings: [] };
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
const findings = [];
|
|
170
|
+
|
|
171
|
+
for (const pattern of INJECTION_PATTERNS) {
|
|
172
|
+
if (pattern.test(text)) {
|
|
173
|
+
findings.push(`Matched injection pattern: ${pattern.source}`);
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
if (opts.strict) {
|
|
178
|
+
// Check for suspicious Unicode that could hide instructions
|
|
179
|
+
// (zero-width chars, RTL override, homoglyph attacks)
|
|
180
|
+
if (/[\u200B-\u200F\u2028-\u202F\uFEFF\u00AD]/.test(text)) {
|
|
181
|
+
findings.push('Contains suspicious zero-width or invisible Unicode characters');
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
// Check for extremely long strings that could be prompt stuffing
|
|
185
|
+
if (text.length > 50000) {
|
|
186
|
+
findings.push(`Suspicious text length: ${text.length} chars (potential prompt stuffing)`);
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
return { clean: findings.length === 0, findings };
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/**
|
|
194
|
+
* Sanitize text that will be embedded in agent prompts or planning documents.
|
|
195
|
+
* Strips known injection markers while preserving legitimate content.
|
|
196
|
+
*
|
|
197
|
+
* This does NOT alter user intent — it neutralizes control characters and
|
|
198
|
+
* instruction-mimicking patterns that could hijack agent behavior.
|
|
199
|
+
*
|
|
200
|
+
* @param {string} text - Text to sanitize
|
|
201
|
+
* @returns {string} Sanitized text
|
|
202
|
+
*/
|
|
203
|
+
function sanitizeForPrompt(text) {
|
|
204
|
+
if (!text || typeof text !== 'string') return text;
|
|
205
|
+
|
|
206
|
+
let sanitized = text;
|
|
207
|
+
|
|
208
|
+
// Strip zero-width characters that could hide instructions
|
|
209
|
+
sanitized = sanitized.replace(/[\u200B-\u200F\u2028-\u202F\uFEFF\u00AD]/g, '');
|
|
210
|
+
|
|
211
|
+
// Neutralize XML/HTML tags that mimic system boundaries
|
|
212
|
+
// Replace < > with full-width equivalents to prevent tag interpretation
|
|
213
|
+
// Note: <instructions> is excluded — GSD uses it as legitimate prompt structure
|
|
214
|
+
sanitized = sanitized.replace(/<(\/?)(?:system|assistant|human)>/gi,
|
|
215
|
+
(_, slash) => `<${slash || ''}system-text>`);
|
|
216
|
+
|
|
217
|
+
// Neutralize [SYSTEM] / [INST] markers
|
|
218
|
+
sanitized = sanitized.replace(/\[(SYSTEM|INST)\]/gi, '[$1-TEXT]');
|
|
219
|
+
|
|
220
|
+
// Neutralize <<SYS>> markers
|
|
221
|
+
sanitized = sanitized.replace(/<<\s*SYS\s*>>/gi, '«SYS-TEXT»');
|
|
222
|
+
|
|
223
|
+
return sanitized;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/**
|
|
227
|
+
* Sanitize text that will be displayed back to the user.
|
|
228
|
+
* Removes protocol-like leak markers that should never surface in checkpoints.
|
|
229
|
+
*
|
|
230
|
+
* @param {string} text - Text to sanitize
|
|
231
|
+
* @returns {string} Sanitized text
|
|
232
|
+
*/
|
|
233
|
+
function sanitizeForDisplay(text) {
|
|
234
|
+
if (!text || typeof text !== 'string') return text;
|
|
235
|
+
|
|
236
|
+
let sanitized = sanitizeForPrompt(text);
|
|
237
|
+
|
|
238
|
+
const protocolLeakPatterns = [
|
|
239
|
+
/^\s*(?:assistant|user|system)\s+to=[^:\s]+:[^\n]+$/i,
|
|
240
|
+
/^\s*<\|(?:assistant|user|system)[^|]*\|>\s*$/i,
|
|
241
|
+
];
|
|
242
|
+
|
|
243
|
+
sanitized = sanitized
|
|
244
|
+
.split('\n')
|
|
245
|
+
.filter(line => !protocolLeakPatterns.some(pattern => pattern.test(line)))
|
|
246
|
+
.join('\n');
|
|
247
|
+
|
|
248
|
+
return sanitized;
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
// ─── Shell Safety ───────────────────────────────────────────────────────────
|
|
252
|
+
|
|
253
|
+
/**
|
|
254
|
+
* Validate that a string is safe to use as a shell argument when quoted.
|
|
255
|
+
* This is a defense-in-depth check — callers should always use array-based
|
|
256
|
+
* exec (spawnSync) where possible.
|
|
257
|
+
*
|
|
258
|
+
* @param {string} value - The value to check
|
|
259
|
+
* @param {string} label - Description for error messages
|
|
260
|
+
* @returns {string} The validated value
|
|
261
|
+
*/
|
|
262
|
+
function validateShellArg(value, label) {
|
|
263
|
+
if (!value || typeof value !== 'string') {
|
|
264
|
+
throw new Error(`${label || 'Argument'}: empty or invalid value`);
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
// Reject null bytes
|
|
268
|
+
if (value.includes('\0')) {
|
|
269
|
+
throw new Error(`${label || 'Argument'}: contains null bytes`);
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
// Reject command substitution attempts
|
|
273
|
+
if (/[$`]/.test(value) && /\$\(|`/.test(value)) {
|
|
274
|
+
throw new Error(`${label || 'Argument'}: contains potential command substitution`);
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
return value;
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
// ─── JSON Safety ────────────────────────────────────────────────────────────
|
|
281
|
+
|
|
282
|
+
/**
|
|
283
|
+
* Safely parse JSON with error handling and optional size limits.
|
|
284
|
+
* Wraps JSON.parse to prevent uncaught exceptions from malformed input.
|
|
285
|
+
*
|
|
286
|
+
* @param {string} text - JSON string to parse
|
|
287
|
+
* @param {object} [opts] - Options
|
|
288
|
+
* @param {number} [opts.maxLength=1048576] - Maximum input length (1MB default)
|
|
289
|
+
* @param {string} [opts.label='JSON'] - Description for error messages
|
|
290
|
+
* @returns {{ ok: boolean, value?: any, error?: string }}
|
|
291
|
+
*/
|
|
292
|
+
function safeJsonParse(text, opts = {}) {
|
|
293
|
+
const maxLength = opts.maxLength || 1048576;
|
|
294
|
+
const label = opts.label || 'JSON';
|
|
295
|
+
|
|
296
|
+
if (!text || typeof text !== 'string') {
|
|
297
|
+
return { ok: false, error: `${label}: empty or invalid input` };
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
if (text.length > maxLength) {
|
|
301
|
+
return { ok: false, error: `${label}: input exceeds ${maxLength} byte limit (got ${text.length})` };
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
try {
|
|
305
|
+
const value = JSON.parse(text);
|
|
306
|
+
return { ok: true, value };
|
|
307
|
+
} catch (err) {
|
|
308
|
+
return { ok: false, error: `${label}: parse error — ${err.message}` };
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
// ─── Phase/Argument Validation ──────────────────────────────────────────────
|
|
313
|
+
|
|
314
|
+
/**
|
|
315
|
+
* Validate a phase number argument.
|
|
316
|
+
* Phase numbers must match: integer, decimal (2.1), or letter suffix (12A).
|
|
317
|
+
* Rejects arbitrary strings that could be used for injection.
|
|
318
|
+
*
|
|
319
|
+
* @param {string} phase - The phase number to validate
|
|
320
|
+
* @returns {{ valid: boolean, normalized?: string, error?: string }}
|
|
321
|
+
*/
|
|
322
|
+
function validatePhaseNumber(phase) {
|
|
323
|
+
if (!phase || typeof phase !== 'string') {
|
|
324
|
+
return { valid: false, error: 'Phase number is required' };
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
const trimmed = phase.trim();
|
|
328
|
+
|
|
329
|
+
// Standard numeric: 1, 01, 12A, 12.1, 12A.1.2
|
|
330
|
+
if (/^\d{1,4}[A-Z]?(?:\.\d{1,3})*$/i.test(trimmed)) {
|
|
331
|
+
return { valid: true, normalized: trimmed };
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
// Custom project IDs: PROJ-42, AUTH-101 (uppercase alphanumeric with hyphens)
|
|
335
|
+
if (/^[A-Z][A-Z0-9]*(?:-[A-Z0-9]+){1,4}$/i.test(trimmed) && trimmed.length <= 30) {
|
|
336
|
+
return { valid: true, normalized: trimmed };
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
return { valid: false, error: `Invalid phase number format: "${trimmed}"` };
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
/**
|
|
343
|
+
* Validate a STATE.md field name to prevent injection into regex patterns.
|
|
344
|
+
* Field names must be alphanumeric with spaces, hyphens, underscores, or dots.
|
|
345
|
+
*
|
|
346
|
+
* @param {string} field - The field name to validate
|
|
347
|
+
* @returns {{ valid: boolean, error?: string }}
|
|
348
|
+
*/
|
|
349
|
+
function validateFieldName(field) {
|
|
350
|
+
if (!field || typeof field !== 'string') {
|
|
351
|
+
return { valid: false, error: 'Field name is required' };
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
// Allow typical field names: "Current Phase", "active_plan", "Phase 1.2"
|
|
355
|
+
if (/^[A-Za-z][A-Za-z0-9 _.\-/]{0,60}$/.test(field)) {
|
|
356
|
+
return { valid: true };
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
return { valid: false, error: `Invalid field name: "${field}"` };
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
module.exports = {
|
|
363
|
+
// Path safety
|
|
364
|
+
validatePath,
|
|
365
|
+
requireSafePath,
|
|
366
|
+
|
|
367
|
+
// Prompt injection
|
|
368
|
+
INJECTION_PATTERNS,
|
|
369
|
+
scanForInjection,
|
|
370
|
+
sanitizeForPrompt,
|
|
371
|
+
sanitizeForDisplay,
|
|
372
|
+
|
|
373
|
+
// Shell safety
|
|
374
|
+
validateShellArg,
|
|
375
|
+
|
|
376
|
+
// JSON safety
|
|
377
|
+
safeJsonParse,
|
|
378
|
+
|
|
379
|
+
// Input validation
|
|
380
|
+
validatePhaseNumber,
|
|
381
|
+
validateFieldName,
|
|
382
|
+
};
|
|
@@ -0,0 +1,290 @@
|
|
|
1
|
+
// @gsd-context Session manager for monorepo mode -- persists and resolves the current app selection so all GSD commands auto-scope without --app flag
|
|
2
|
+
// @gsd-decision Session stored in .planning/SESSION.json -- co-located with planning artifacts, not in a hidden dotfile or temp directory
|
|
3
|
+
// @gsd-constraint Zero external dependencies -- uses only Node.js built-ins (fs, path)
|
|
4
|
+
// @gsd-pattern All GSD commands call resolveCurrentApp() to get the effective app -- explicit --app flag overrides session, session overrides nothing
|
|
5
|
+
|
|
6
|
+
'use strict';
|
|
7
|
+
|
|
8
|
+
const fs = require('node:fs');
|
|
9
|
+
const path = require('node:path');
|
|
10
|
+
|
|
11
|
+
// ---------------------------------------------------------------------------
|
|
12
|
+
// Types
|
|
13
|
+
// ---------------------------------------------------------------------------
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* @typedef {Object} SessionData
|
|
17
|
+
* @property {string|null} current_app - Relative path to the active app (e.g., 'apps/dashboard'), or null for root/global
|
|
18
|
+
* @property {string|null} default_app - Default app to auto-select at session start (set via /gsd:switch-app --default)
|
|
19
|
+
* @property {'monorepo'|'single'|null} workspace_type - Detected workspace type
|
|
20
|
+
* @property {string[]} available_apps - List of all app paths from workspace detection
|
|
21
|
+
* @property {number} updated_at - Epoch ms of last update
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
// ---------------------------------------------------------------------------
|
|
25
|
+
// File path resolution
|
|
26
|
+
// ---------------------------------------------------------------------------
|
|
27
|
+
|
|
28
|
+
// @gsd-decision SESSION.json lives at root .planning/SESSION.json -- one session file for the whole monorepo, not per-app
|
|
29
|
+
/**
|
|
30
|
+
* Get the path to SESSION.json.
|
|
31
|
+
*
|
|
32
|
+
* @param {string} rootPath - Project/monorepo root
|
|
33
|
+
* @returns {string}
|
|
34
|
+
*/
|
|
35
|
+
function getSessionPath(rootPath) {
|
|
36
|
+
return path.join(rootPath, '.planning', 'SESSION.json');
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// ---------------------------------------------------------------------------
|
|
40
|
+
// Read operations
|
|
41
|
+
// ---------------------------------------------------------------------------
|
|
42
|
+
|
|
43
|
+
// @gsd-todo(ref:AC-13) Implement session detection at startup: when monorepo detected, present app selector if no session exists
|
|
44
|
+
// @gsd-api getSession(rootPath) -- returns SessionData or null if no session file exists
|
|
45
|
+
/**
|
|
46
|
+
* Read the current session data.
|
|
47
|
+
*
|
|
48
|
+
* @param {string} rootPath - Project root
|
|
49
|
+
* @returns {SessionData|null}
|
|
50
|
+
*/
|
|
51
|
+
function getSession(rootPath) {
|
|
52
|
+
const sessionPath = getSessionPath(rootPath);
|
|
53
|
+
try {
|
|
54
|
+
const raw = fs.readFileSync(sessionPath, 'utf-8');
|
|
55
|
+
return JSON.parse(raw);
|
|
56
|
+
} catch {
|
|
57
|
+
return null;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// @gsd-todo(ref:AC-14) Implement auto-scoping: all GSD commands call resolveCurrentApp() so --app flag is not required after selection
|
|
62
|
+
// @gsd-api getCurrentApp(rootPath) -- returns the current app path string or null (global/root scope)
|
|
63
|
+
/**
|
|
64
|
+
* Get the currently selected app path.
|
|
65
|
+
* Returns null if no session or if working at root/global scope.
|
|
66
|
+
*
|
|
67
|
+
* @param {string} rootPath - Project root
|
|
68
|
+
* @returns {string|null}
|
|
69
|
+
*/
|
|
70
|
+
function getCurrentApp(rootPath) {
|
|
71
|
+
const session = getSession(rootPath);
|
|
72
|
+
if (!session) return null;
|
|
73
|
+
// If no app explicitly selected but a default is configured, use the default
|
|
74
|
+
if (!session.current_app && session.default_app) return session.default_app;
|
|
75
|
+
return session.current_app || null;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
// @gsd-api resolveCurrentApp(rootPath, explicitApp) -- returns effective app path: explicit --app flag wins, then session, then null
|
|
79
|
+
/**
|
|
80
|
+
* Resolve the effective current app for a command.
|
|
81
|
+
* Priority: explicit --app flag > session > null (root scope).
|
|
82
|
+
*
|
|
83
|
+
* @param {string} rootPath - Project root
|
|
84
|
+
* @param {string|null|undefined} explicitApp - Value from --app flag, if provided
|
|
85
|
+
* @returns {string|null}
|
|
86
|
+
*/
|
|
87
|
+
function resolveCurrentApp(rootPath, explicitApp) {
|
|
88
|
+
// @gsd-decision Explicit --app always wins over session -- escape hatch for one-off commands on a different app
|
|
89
|
+
if (explicitApp) return explicitApp;
|
|
90
|
+
return getCurrentApp(rootPath);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// ---------------------------------------------------------------------------
|
|
94
|
+
// Write operations
|
|
95
|
+
// ---------------------------------------------------------------------------
|
|
96
|
+
|
|
97
|
+
// @gsd-todo(ref:AC-15) Wire setCurrentApp to /gsd:switch-app command for mid-session app switching
|
|
98
|
+
// @gsd-api setCurrentApp(rootPath, appPath, availableApps) -- writes SESSION.json with new current_app
|
|
99
|
+
/**
|
|
100
|
+
* Set the current app in the session.
|
|
101
|
+
* Pass null for appPath to set global/root scope.
|
|
102
|
+
*
|
|
103
|
+
* @param {string} rootPath - Project root
|
|
104
|
+
* @param {string|null} appPath - Relative app path or null for global
|
|
105
|
+
* @param {string[]} [availableApps] - List of available app paths (updates the cached list)
|
|
106
|
+
* @returns {SessionData}
|
|
107
|
+
*/
|
|
108
|
+
function setCurrentApp(rootPath, appPath, availableApps) {
|
|
109
|
+
const existing = getSession(rootPath) || {};
|
|
110
|
+
|
|
111
|
+
const session = {
|
|
112
|
+
current_app: appPath,
|
|
113
|
+
workspace_type: existing.workspace_type || 'monorepo',
|
|
114
|
+
available_apps: availableApps || existing.available_apps || [],
|
|
115
|
+
updated_at: Date.now(),
|
|
116
|
+
};
|
|
117
|
+
|
|
118
|
+
const sessionPath = getSessionPath(rootPath);
|
|
119
|
+
// Ensure .planning/ exists
|
|
120
|
+
fs.mkdirSync(path.dirname(sessionPath), { recursive: true });
|
|
121
|
+
fs.writeFileSync(sessionPath, JSON.stringify(session, null, 2) + '\n', 'utf-8');
|
|
122
|
+
|
|
123
|
+
return session;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
// @gsd-todo(ref:AC-16) Implement "Global" option: setCurrentApp(rootPath, null) puts session in root-level scope for cross-app work
|
|
127
|
+
// @gsd-api clearSession(rootPath) -- removes SESSION.json entirely, resetting to no-session state
|
|
128
|
+
/**
|
|
129
|
+
* Clear the session entirely. Removes SESSION.json.
|
|
130
|
+
*
|
|
131
|
+
* @param {string} rootPath - Project root
|
|
132
|
+
*/
|
|
133
|
+
function clearSession(rootPath) {
|
|
134
|
+
const sessionPath = getSessionPath(rootPath);
|
|
135
|
+
try {
|
|
136
|
+
fs.unlinkSync(sessionPath);
|
|
137
|
+
} catch {
|
|
138
|
+
// File doesn't exist -- already cleared
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
// ---------------------------------------------------------------------------
|
|
143
|
+
// Session initialization (for monorepo startup)
|
|
144
|
+
// ---------------------------------------------------------------------------
|
|
145
|
+
|
|
146
|
+
// @gsd-api initSession(rootPath, workspaceInfo) -- creates initial SESSION.json from workspace detection results
|
|
147
|
+
/**
|
|
148
|
+
* Initialize a session from workspace detection results.
|
|
149
|
+
* Called by monorepo-init or at session start when a monorepo is detected.
|
|
150
|
+
*
|
|
151
|
+
* @param {string} rootPath - Project root
|
|
152
|
+
* @param {Object} workspaceInfo - WorkspaceInfo from workspace-detector.cjs
|
|
153
|
+
* @returns {SessionData}
|
|
154
|
+
*/
|
|
155
|
+
function initSession(rootPath, workspaceInfo) {
|
|
156
|
+
// @gsd-constraint Session init does NOT auto-select an app -- user must explicitly choose via selector or /gsd:switch-app
|
|
157
|
+
const availableApps = (workspaceInfo.apps || []).map(a => a.path);
|
|
158
|
+
|
|
159
|
+
// Check if a default app was previously configured — auto-select it
|
|
160
|
+
const existing = getSession(rootPath);
|
|
161
|
+
const defaultApp = (existing && existing.default_app) || null;
|
|
162
|
+
|
|
163
|
+
const session = {
|
|
164
|
+
current_app: defaultApp,
|
|
165
|
+
default_app: defaultApp,
|
|
166
|
+
workspace_type: workspaceInfo.type || 'monorepo',
|
|
167
|
+
available_apps: availableApps,
|
|
168
|
+
updated_at: Date.now(),
|
|
169
|
+
};
|
|
170
|
+
|
|
171
|
+
const sessionPath = getSessionPath(rootPath);
|
|
172
|
+
fs.mkdirSync(path.dirname(sessionPath), { recursive: true });
|
|
173
|
+
fs.writeFileSync(sessionPath, JSON.stringify(session, null, 2) + '\n', 'utf-8');
|
|
174
|
+
|
|
175
|
+
return session;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
// ---------------------------------------------------------------------------
|
|
179
|
+
// Default app configuration
|
|
180
|
+
// ---------------------------------------------------------------------------
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* Set a default app that auto-selects at session start.
|
|
184
|
+
* Pass null to clear the default.
|
|
185
|
+
*
|
|
186
|
+
* @param {string} rootPath - Project root
|
|
187
|
+
* @param {string|null} appPath - Relative app path or null to clear
|
|
188
|
+
* @returns {SessionData}
|
|
189
|
+
*/
|
|
190
|
+
function setDefaultApp(rootPath, appPath) {
|
|
191
|
+
const existing = getSession(rootPath) || {};
|
|
192
|
+
|
|
193
|
+
const session = {
|
|
194
|
+
current_app: existing.current_app || appPath,
|
|
195
|
+
default_app: appPath,
|
|
196
|
+
workspace_type: existing.workspace_type || 'monorepo',
|
|
197
|
+
available_apps: existing.available_apps || [],
|
|
198
|
+
updated_at: Date.now(),
|
|
199
|
+
};
|
|
200
|
+
|
|
201
|
+
const sessionPath = getSessionPath(rootPath);
|
|
202
|
+
fs.mkdirSync(path.dirname(sessionPath), { recursive: true });
|
|
203
|
+
fs.writeFileSync(sessionPath, JSON.stringify(session, null, 2) + '\n', 'utf-8');
|
|
204
|
+
|
|
205
|
+
return session;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/**
|
|
209
|
+
* Get the default app, if configured.
|
|
210
|
+
*
|
|
211
|
+
* @param {string} rootPath - Project root
|
|
212
|
+
* @returns {string|null}
|
|
213
|
+
*/
|
|
214
|
+
function getDefaultApp(rootPath) {
|
|
215
|
+
const session = getSession(rootPath);
|
|
216
|
+
return (session && session.default_app) || null;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
// ---------------------------------------------------------------------------
|
|
220
|
+
// Query helpers
|
|
221
|
+
// ---------------------------------------------------------------------------
|
|
222
|
+
|
|
223
|
+
// @gsd-api isMonorepoSession(rootPath) -- returns true if a monorepo session is active
|
|
224
|
+
/**
|
|
225
|
+
* Check if the current session is a monorepo session.
|
|
226
|
+
*
|
|
227
|
+
* @param {string} rootPath - Project root
|
|
228
|
+
* @returns {boolean}
|
|
229
|
+
*/
|
|
230
|
+
function isMonorepoSession(rootPath) {
|
|
231
|
+
const session = getSession(rootPath);
|
|
232
|
+
return !!(session && session.workspace_type && session.workspace_type !== 'single');
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
// @gsd-api getAvailableApps(rootPath) -- returns cached list of app paths from session, or empty array
|
|
236
|
+
/**
|
|
237
|
+
* Get the list of available apps from the session.
|
|
238
|
+
*
|
|
239
|
+
* @param {string} rootPath - Project root
|
|
240
|
+
* @returns {string[]}
|
|
241
|
+
*/
|
|
242
|
+
function getAvailableApps(rootPath) {
|
|
243
|
+
const session = getSession(rootPath);
|
|
244
|
+
return (session && session.available_apps) || [];
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
// ---------------------------------------------------------------------------
|
|
248
|
+
// Formatting helpers
|
|
249
|
+
// ---------------------------------------------------------------------------
|
|
250
|
+
|
|
251
|
+
/**
|
|
252
|
+
* Format the app selector prompt for display.
|
|
253
|
+
*
|
|
254
|
+
* @param {string[]} apps - Available app paths
|
|
255
|
+
* @param {string|null} currentApp - Currently selected app
|
|
256
|
+
* @returns {string}
|
|
257
|
+
*/
|
|
258
|
+
function formatAppSelector(apps, currentApp) {
|
|
259
|
+
const lines = ['Which app do you want to work on?\n'];
|
|
260
|
+
|
|
261
|
+
for (let i = 0; i < apps.length; i++) {
|
|
262
|
+
const marker = apps[i] === currentApp ? ' (current)' : '';
|
|
263
|
+
lines.push(` ${i + 1}. ${apps[i]}${marker}`);
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
const globalMarker = currentApp === null ? ' (current)' : '';
|
|
267
|
+
lines.push(` ${apps.length + 1}. [Global] -- root-level cross-app work${globalMarker}`);
|
|
268
|
+
lines.push('');
|
|
269
|
+
|
|
270
|
+
return lines.join('\n');
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
// ---------------------------------------------------------------------------
|
|
274
|
+
// Exports
|
|
275
|
+
// ---------------------------------------------------------------------------
|
|
276
|
+
|
|
277
|
+
module.exports = {
|
|
278
|
+
getSessionPath,
|
|
279
|
+
getSession,
|
|
280
|
+
getCurrentApp,
|
|
281
|
+
resolveCurrentApp,
|
|
282
|
+
setCurrentApp,
|
|
283
|
+
setDefaultApp,
|
|
284
|
+
getDefaultApp,
|
|
285
|
+
clearSession,
|
|
286
|
+
initSession,
|
|
287
|
+
isMonorepoSession,
|
|
288
|
+
getAvailableApps,
|
|
289
|
+
formatAppSelector,
|
|
290
|
+
};
|