@abdulr7man/pensieve 0.0.0-stage → 1.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (179) hide show
  1. package/LICENSE +684 -0
  2. package/README.md +180 -2
  3. package/VERSION +1 -0
  4. package/agents/README.md +16 -0
  5. package/agents/pensieve-code-auditor.md +58 -0
  6. package/agents/pensieve-mapper.md +46 -0
  7. package/agents/pensieve-planner.md +67 -0
  8. package/agents/pensieve-reconner.md +76 -0
  9. package/agents/pensieve-reporter.md +61 -0
  10. package/agents/pensieve-roe-checker.md +46 -0
  11. package/agents/pensieve-scoper.md +77 -0
  12. package/agents/pensieve-tester.md +83 -0
  13. package/agents/pensieve-validator.md +62 -0
  14. package/bin/pensieve +452 -0
  15. package/bin/pensieve-installer.cjs +5 -0
  16. package/commands/pensieve-close.md +6 -0
  17. package/commands/pensieve-map.md +6 -0
  18. package/commands/pensieve-new-engagement.md +6 -0
  19. package/commands/pensieve-pause.md +15 -0
  20. package/commands/pensieve-plan.md +6 -0
  21. package/commands/pensieve-progress.md +34 -0
  22. package/commands/pensieve-quick.md +8 -0
  23. package/commands/pensieve-recon.md +6 -0
  24. package/commands/pensieve-report.md +6 -0
  25. package/commands/pensieve-resume.md +6 -0
  26. package/commands/pensieve-retest.md +10 -0
  27. package/commands/pensieve-scope.md +49 -0
  28. package/commands/pensieve-surface.md +8 -0
  29. package/commands/pensieve-test.md +6 -0
  30. package/commands/pensieve-validate.md +6 -0
  31. package/docker/Dockerfile.pensieve-toolbox +75 -0
  32. package/docker/compose.pensieve-net.yml +37 -0
  33. package/docker/squid.conf.template +21 -0
  34. package/package.json +39 -4
  35. package/packs/ad/ad-killchain/checklist.md +64 -0
  36. package/packs/ad/ad-killchain/pack.yaml +19 -0
  37. package/packs/cloud/cloud-cis/checklist.md +66 -0
  38. package/packs/cloud/cloud-cis/pack.yaml +20 -0
  39. package/packs/fintech/practice-core/checklist.md +33 -0
  40. package/packs/fintech/practice-core/learnings.md +5 -0
  41. package/packs/fintech/practice-core/pack.yaml +18 -0
  42. package/packs/infra/ptes-infra/checklist.md +22 -0
  43. package/packs/infra/ptes-infra/pack.yaml +19 -0
  44. package/packs/mobile/owasp-masvs/checklist.md +80 -0
  45. package/packs/mobile/owasp-masvs/pack.yaml +20 -0
  46. package/packs/owasp-api-v4/checklist.md +85 -0
  47. package/packs/owasp-api-v4/learnings.md +6 -0
  48. package/packs/owasp-api-v4/pack.yaml +23 -0
  49. package/packs/owasp-api-v4/runbooks/API1/SKILL.md +66 -0
  50. package/packs/owasp-api-v4/runbooks/API10/SKILL.md +67 -0
  51. package/packs/owasp-api-v4/runbooks/API2/SKILL.md +129 -0
  52. package/packs/owasp-api-v4/runbooks/API3/SKILL.md +55 -0
  53. package/packs/owasp-api-v4/runbooks/API4/SKILL.md +59 -0
  54. package/packs/owasp-api-v4/runbooks/API5/SKILL.md +60 -0
  55. package/packs/owasp-api-v4/runbooks/API6/SKILL.md +63 -0
  56. package/packs/owasp-api-v4/runbooks/API7/SKILL.md +70 -0
  57. package/packs/owasp-api-v4/runbooks/API8/SKILL.md +72 -0
  58. package/packs/owasp-api-v4/runbooks/API9/SKILL.md +66 -0
  59. package/packs/thickclient/thickclient-core/checklist.md +60 -0
  60. package/packs/thickclient/thickclient-core/pack.yaml +24 -0
  61. package/packs/web/asvs-l2/checklist.md +50 -0
  62. package/packs/web/asvs-l2/learnings.md +6 -0
  63. package/packs/web/asvs-l2/pack.yaml +19 -0
  64. package/packs/web/asvs-l2/runbooks/V2-AUTH-ENUM/SKILL.md +75 -0
  65. package/packs/web/asvs-l2/runbooks/V2-AUTH-LIVE/SKILL.md +78 -0
  66. package/packs/web/asvs-l2/runbooks/V2-AUTH-MFA/SKILL.md +76 -0
  67. package/packs/web/asvs-l2/runbooks/V2-AUTH-RATE/SKILL.md +72 -0
  68. package/packs/web/owasp-testing-checklist/checklist.md +52 -0
  69. package/packs/web/owasp-testing-checklist/learnings.md +47 -0
  70. package/packs/web/owasp-testing-checklist/pack.yaml +21 -0
  71. package/packs/web/unauth-perimeter/checklist.md +72 -0
  72. package/packs/web/unauth-perimeter/pack.yaml +18 -0
  73. package/packs/web/unauth-perimeter/runbooks/PERIM-01/SKILL.md +60 -0
  74. package/packs/web/unauth-perimeter/runbooks/PERIM-02/SKILL.md +63 -0
  75. package/packs/web/unauth-perimeter/runbooks/PERIM-03/SKILL.md +62 -0
  76. package/packs/web/unauth-perimeter/runbooks/PERIM-04/SKILL.md +75 -0
  77. package/packs/web/unauth-perimeter/runbooks/PERIM-05/SKILL.md +66 -0
  78. package/packs/web/unauth-perimeter/runbooks/PERIM-06/SKILL.md +59 -0
  79. package/packs/web/unauth-perimeter/runbooks/PERIM-07/SKILL.md +56 -0
  80. package/packs/web/unauth-perimeter/runbooks/PERIM-08/SKILL.md +57 -0
  81. package/packs/web/unauth-perimeter/runbooks/PERIM-09/SKILL.md +62 -0
  82. package/packs/web/unauth-perimeter/runbooks/PERIM-10/SKILL.md +60 -0
  83. package/packs/whitebox/code-audit-core/checklist.md +36 -0
  84. package/packs/whitebox/code-audit-core/learnings.md +6 -0
  85. package/packs/whitebox/code-audit-core/pack.yaml +14 -0
  86. package/prompts/orchestrator-core.md +52 -0
  87. package/reference/attack-playbooks.md +57 -0
  88. package/reference/otp-relay.md +98 -0
  89. package/reference/param-profiles.md +48 -0
  90. package/reference/templates/FINDING.md +97 -0
  91. package/reference/tool-selection.md +64 -0
  92. package/reference/vulnerability-finding-standard.md +80 -0
  93. package/runtimes/hermes/hooks/injection-scan.py +290 -0
  94. package/runtimes/hermes/hooks/scope-guard.py +136 -0
  95. package/skills/pensieve/SKILL.md +134 -0
  96. package/skills/pensieve-close/SKILL.md +31 -0
  97. package/skills/pensieve-map/SKILL.md +25 -0
  98. package/skills/pensieve-new-engagement/SKILL.md +28 -0
  99. package/skills/pensieve-pause/SKILL.md +22 -0
  100. package/skills/pensieve-plan/SKILL.md +39 -0
  101. package/skills/pensieve-progress/SKILL.md +35 -0
  102. package/skills/pensieve-quick/SKILL.md +47 -0
  103. package/skills/pensieve-recon/SKILL.md +30 -0
  104. package/skills/pensieve-report/SKILL.md +46 -0
  105. package/skills/pensieve-resume/SKILL.md +33 -0
  106. package/skills/pensieve-retest/SKILL.md +35 -0
  107. package/skills/pensieve-scope/SKILL.md +35 -0
  108. package/skills/pensieve-surface/SKILL.md +36 -0
  109. package/skills/pensieve-test/SKILL.md +35 -0
  110. package/skills/pensieve-validate/SKILL.md +28 -0
  111. package/skills/pensieve-wiki/SKILL.md +39 -0
  112. package/src/installer/cli.cjs +209 -0
  113. package/src/installer/home.cjs +155 -0
  114. package/src/installer/runtimes.cjs +276 -0
  115. package/src/installer/uninstall.cjs +342 -0
  116. package/src/pensieve-sdk/bin/pensieve-sdk.cjs +1045 -0
  117. package/src/pensieve-sdk/lib/agent-translate.cjs +50 -0
  118. package/src/pensieve-sdk/lib/approvals.cjs +408 -0
  119. package/src/pensieve-sdk/lib/audit.cjs +290 -0
  120. package/src/pensieve-sdk/lib/checklist.cjs +337 -0
  121. package/src/pensieve-sdk/lib/clientlist.cjs +814 -0
  122. package/src/pensieve-sdk/lib/close.cjs +133 -0
  123. package/src/pensieve-sdk/lib/config.cjs +156 -0
  124. package/src/pensieve-sdk/lib/cvss.cjs +91 -0
  125. package/src/pensieve-sdk/lib/env.cjs +272 -0
  126. package/src/pensieve-sdk/lib/evidence.cjs +217 -0
  127. package/src/pensieve-sdk/lib/findings.cjs +1096 -0
  128. package/src/pensieve-sdk/lib/frontmatter.cjs +178 -0
  129. package/src/pensieve-sdk/lib/graph.cjs +607 -0
  130. package/src/pensieve-sdk/lib/ids.cjs +63 -0
  131. package/src/pensieve-sdk/lib/init.cjs +79 -0
  132. package/src/pensieve-sdk/lib/liveness.cjs +176 -0
  133. package/src/pensieve-sdk/lib/loop.cjs +619 -0
  134. package/src/pensieve-sdk/lib/migrate.cjs +57 -0
  135. package/src/pensieve-sdk/lib/monitor.cjs +69 -0
  136. package/src/pensieve-sdk/lib/pack.cjs +607 -0
  137. package/src/pensieve-sdk/lib/paths.cjs +73 -0
  138. package/src/pensieve-sdk/lib/pdf.cjs +291 -0
  139. package/src/pensieve-sdk/lib/recon.cjs +296 -0
  140. package/src/pensieve-sdk/lib/renderers/__pycache__/formal_report.cpython-314.pyc +0 -0
  141. package/src/pensieve-sdk/lib/renderers/formal_report.py +608 -0
  142. package/src/pensieve-sdk/lib/report.cjs +1135 -0
  143. package/src/pensieve-sdk/lib/runbook.cjs +124 -0
  144. package/src/pensieve-sdk/lib/sarif.cjs +154 -0
  145. package/src/pensieve-sdk/lib/scope.cjs +621 -0
  146. package/src/pensieve-sdk/lib/security.cjs +61 -0
  147. package/src/pensieve-sdk/lib/skills.cjs +193 -0
  148. package/src/pensieve-sdk/lib/state.cjs +610 -0
  149. package/src/pensieve-sdk/lib/subagent.cjs +658 -0
  150. package/src/pensieve-sdk/lib/target.cjs +149 -0
  151. package/src/pensieve-sdk/lib/tools.cjs +66 -0
  152. package/src/pensieve-sdk/lib/vault.cjs +122 -0
  153. package/src/pensieve-sdk/lib/vendor/cvss40.LICENSE +22 -0
  154. package/src/pensieve-sdk/lib/vendor/cvss40.js +1208 -0
  155. package/src/pensieve-sdk/package.json +11 -0
  156. package/templates/ACCOUNTS.md +35 -0
  157. package/templates/ATTACK-SURFACE.md +30 -0
  158. package/templates/FINDING.md +43 -0
  159. package/templates/PLAN.md +33 -0
  160. package/templates/PROJECT.md +29 -0
  161. package/templates/ROE.md +50 -0
  162. package/templates/RUN-LOG.md +19 -0
  163. package/templates/SCOPE.md +32 -0
  164. package/templates/VALIDATION.md +62 -0
  165. package/templates/report/REPORT.md +49 -0
  166. package/workflows/close.md +34 -0
  167. package/workflows/map.md +39 -0
  168. package/workflows/new-engagement.md +37 -0
  169. package/workflows/plan.md +45 -0
  170. package/workflows/progress.md +28 -0
  171. package/workflows/quick.md +67 -0
  172. package/workflows/recon.md +87 -0
  173. package/workflows/report.md +51 -0
  174. package/workflows/resume.md +26 -0
  175. package/workflows/retest.md +53 -0
  176. package/workflows/scope.md +47 -0
  177. package/workflows/surface.md +29 -0
  178. package/workflows/test.md +95 -0
  179. package/workflows/validate.md +34 -0
@@ -0,0 +1,607 @@
1
+ 'use strict';
2
+ /**
3
+ * graph.cjs — objective-driven attack graph (ADR-025).
4
+ *
5
+ * Deterministic SDK module, zero external deps. Models the engagement as
6
+ * nodes (asset / finding / objective) and evidence-backed edges, then
7
+ * solves for the shortest path to the objective and for chokepoints.
8
+ *
9
+ * Files: scope (assets + in-scope gate), findings (validated register),
10
+ * evidence (hash-chained ledger + raw captures), PROJECT.md frontmatter
11
+ * (objective + crown_artifact). Outputs surface/graph.json +
12
+ * surface/ATTACK-GRAPH.md.
13
+ */
14
+
15
+ const fs = require('node:fs');
16
+ const path = require('node:path');
17
+
18
+ const fm = require('./frontmatter.cjs');
19
+ const scope = require('./scope.cjs');
20
+ const paths = require('./paths.cjs');
21
+ const findings = require('./findings.cjs');
22
+ const evidence = require('./evidence.cjs');
23
+ const recon = require('./recon.cjs');
24
+
25
+ const OBJECTIVE_KINDS = new Set(['credentials', 'data', 'DA', 'privilege']);
26
+
27
+ function readIfExists(abs) {
28
+ try {
29
+ return fs.readFileSync(abs, 'utf8');
30
+ } catch {
31
+ return '';
32
+ }
33
+ }
34
+
35
+ function norm(s) {
36
+ return String(s == null ? '' : s).toLowerCase().replace(/\s+/g, ' ').trim();
37
+ }
38
+
39
+ /** objective + crown artifact: PROJECT.md frontmatter first (lab), SCOPE.md fallback (ADR-025). */
40
+ function readObjective(dir) {
41
+ const proj = fm.parse(readIfExists(paths.projectFile(dir))).data || {};
42
+ const scopeText = fm.parse(readIfExists(paths.scopeFile(dir))).data || {};
43
+ const objective = proj.objective || scopeText.objective || null;
44
+ const crownArtifact = proj.crown_artifact || proj.crownArtifact || scopeText.crown_artifact || null;
45
+ return {
46
+ objective: objective ? String(objective) : null,
47
+ crownArtifact: crownArtifact ? String(crownArtifact) : null,
48
+ };
49
+ }
50
+
51
+ /**
52
+ * every *exploitable* finding, with raw file text for content linkage.
53
+ *
54
+ * A finding belongs on the attack graph only if it is a confirmed claim that
55
+ * is STILL exploitable: a report-passing status EXCEPT retested_pass. retested_fail
56
+ * is "STILL REPRODUCIBLE — the fix is ineffective", i.e. the vulnerability is live
57
+ * and the route to the objective stays open (GRAPH-04: a retest (pass or fail)
58
+ * keeps the edge + path). retested_pass is "FIX VERIFIED — the reproduction no
59
+ * longer succeeds" — the route is closed, so the finding drops off the graph
60
+ * (which is what makes "after a fix, the objective should become unreachable" true).
61
+ */
62
+ function readPassingFindings(dir) {
63
+ const rows = findings.list(dir);
64
+ const out = [];
65
+ for (const f of rows) {
66
+ if (['validated', 'validated-static', 'retested_fail'].includes(f.status)) {
67
+ let text = '';
68
+ if (f.path) {
69
+ try {
70
+ text = fs.readFileSync(paths.resolve(dir, f.path), 'utf8');
71
+ } catch {
72
+ text = '';
73
+ }
74
+ }
75
+ out.push({ ...f, text });
76
+ }
77
+ }
78
+ return out;
79
+ }
80
+
81
+ /** all evidence content (concatenated) — raw captures where the crown artifact appears. */
82
+ function readEvidenceTexts(dir, ids = null) {
83
+ const recs = evidence.readIndex(dir);
84
+ const idsSet = ids ? new Set(ids.map((s) => String(s).trim()).filter(Boolean)) : null;
85
+ const texts = [];
86
+ for (const r of recs) {
87
+ if (idsSet && !idsSet.has(r.id)) continue;
88
+ try {
89
+ const t = fs.readFileSync(paths.resolve(dir, r.path), 'utf8');
90
+ if (t && t.length) texts.push(t);
91
+ } catch {
92
+ // missing capture: skip (verifyChain is the integrity gate, not here)
93
+ }
94
+ }
95
+ return texts.join('\n');
96
+ }
97
+
98
+ /**
99
+ * Build the in-memory graph from engagement files (no file writes).
100
+ * Returns { graph, objectiveNode } where graph = { schema, objective?, crownArtifact?,
101
+ * nodes[], edges[], warnings[] } (objective/crownArtifact only present when set).
102
+ */
103
+ function computeGraph(dir) {
104
+ const { objective, crownArtifact } = readObjective(dir);
105
+
106
+ const warnings = [];
107
+ const nodeMap = new Map();
108
+ const nodes = [];
109
+
110
+ function addNode(node) {
111
+ if (node.id && nodeMap.has(node.id)) {
112
+ warnings.push(`duplicate node id: ${node.id}`);
113
+ return false;
114
+ }
115
+ nodeMap.set(node.id, node);
116
+ nodes.push(node);
117
+ return true;
118
+ }
119
+
120
+ // Scope assets -> asset nodes (in-scope gate source).
121
+ let scopeText;
122
+ try {
123
+ scopeText = fm.parse(readIfExists(paths.scopeFile(dir))).body;
124
+ } catch {
125
+ scopeText = '';
126
+ }
127
+ let parsedAssets = [];
128
+ try {
129
+ parsedAssets = scope.parse(scopeText).assets || [];
130
+ } catch (e) {
131
+ warnings.push(`scope parse: ${e.message}`);
132
+ }
133
+
134
+ for (const a of parsedAssets) {
135
+ const label = (a.label || a.name || a.host || '').replace(/^AST-\d+\s+/i, '').trim();
136
+ const id = a.id || (label ? label : a.host);
137
+ if (!id) continue;
138
+ addNode({
139
+ id,
140
+ type: 'asset',
141
+ label: label || (a.host || a.id),
142
+ inScope: true,
143
+ objectiveKind: null,
144
+ isObjective: false,
145
+ sources: ['scope'],
146
+ });
147
+ }
148
+
149
+ // Objective node (only when both objective + crown_artifact are set).
150
+ let objectiveNode = null;
151
+ if (objective && crownArtifact) {
152
+ if (OBJECTIVE_KINDS.has(objective)) {
153
+ objectiveNode = {
154
+ id: 'objective',
155
+ type: 'objective',
156
+ label: crownArtifact,
157
+ inScope: true,
158
+ objectiveKind: objective,
159
+ isObjective: true,
160
+ sources: ['project/objective', 'project/crown_artifact'],
161
+ };
162
+ } else {
163
+ objectiveNode = {
164
+ id: 'objective',
165
+ type: 'objective',
166
+ label: objective,
167
+ inScope: true,
168
+ objectiveKind: objective,
169
+ isObjective: true,
170
+ sources: ['project/objective'],
171
+ };
172
+ }
173
+ addNode(objectiveNode);
174
+ } else if (objective || crownArtifact) {
175
+ warnings.push('objective is set but incomplete (need both objective and crown_artifact)');
176
+ } else {
177
+ warnings.push('no objective set in PROJECT.md frontmatter (objective: credentials|data|DA|privilege)');
178
+ }
179
+
180
+ // Findings -> finding nodes + confirmed edges.
181
+ const findingNodes = readPassingFindings(dir);
182
+ for (const f of findingNodes) {
183
+ addNode({
184
+ id: f.id,
185
+ type: 'finding',
186
+ label: f.title || f.id,
187
+ inScope: true,
188
+ objectiveKind: null,
189
+ isObjective: false,
190
+ sources: [`finding/${f.id}`],
191
+ });
192
+ }
193
+
194
+ // ---- edges ----
195
+ const edgeMap = new Map();
196
+ const edges = [];
197
+
198
+ function addEdge(edge) {
199
+ const key = `${edge.from}->${edge.to}`;
200
+ if (edgeMap.has(key)) return; // dedupe
201
+ edgeMap.set(key, edge);
202
+ edges.push(edge);
203
+ }
204
+
205
+ for (const f of findingNodes) {
206
+ const fEvidenceText = readEvidenceTexts(dir, f.evidence);
207
+ // asset -> finding: finding touches an in-scope asset.
208
+ for (const a of parsedAssets) {
209
+ const label = (a.label || a.name || a.host || '').replace(/^AST-\d+\s+/i, '').trim();
210
+ const assetId = a.id || (label ? label : a.host);
211
+ if (!assetId) continue;
212
+ const assetNode = nodeMap.get(assetId);
213
+ if (!assetNode) continue;
214
+ const touch =
215
+ norm(assetId) === norm(f.id) ||
216
+ (f.assets || []).some((x) =>
217
+ norm(x) === norm(assetId) ||
218
+ norm(x) === norm(assetNode.label) ||
219
+ norm(x) === norm(assetNode.id)
220
+ );
221
+ if (!touch) continue;
222
+ addEdge({
223
+ from: assetId,
224
+ to: f.id,
225
+ type: 'exploit',
226
+ confidence: 'confirmed',
227
+ weight: 1.0,
228
+ cwe: f.cwe || null,
229
+ methodology: 'finding evidence',
230
+ evidence: (f.evidence || []).map(String),
231
+ attackStep: `reach finding ${f.id} on asset ${assetNode.label} (${f.cwe || 'n/a'})`,
232
+ pack: null,
233
+ sources: [`finding/${f.id}`],
234
+ });
235
+ }
236
+ // finding -> objective: finding (title/summary/evidence) references the crown artifact.
237
+ if (objectiveNode && crownArtifact) {
238
+ const hits =
239
+ (f.title && norm(f.title).includes(norm(crownArtifact))) ||
240
+ (f.summary && norm(f.summary).includes(norm(crownArtifact))) ||
241
+ fEvidenceText.includes(crownArtifact);
242
+ if (hits) {
243
+ addEdge({
244
+ from: f.id,
245
+ to: objectiveNode.id,
246
+ type: 'access',
247
+ confidence: 'confirmed',
248
+ weight: 1.0,
249
+ cwe: f.cwe || null,
250
+ methodology: 'finding evidence',
251
+ evidence: (f.evidence || []).map(String),
252
+ attackStep: `access ${crownArtifact} via ${f.id}`,
253
+ pack: null,
254
+ sources: [`finding/${f.id}`],
255
+ });
256
+ }
257
+ }
258
+ }
259
+
260
+ // ---- scope gate: asset nodes came from scope, so in-scope by construction.
261
+ // Recon surface -> host/service nodes (GRAPH-06). recon.readSurface is
262
+ // per-engagement; every discovered host passes scope.check (default-deny)
263
+ // before it can become a node, so out-of-scope discoveries never appear. A
264
+ // host that already exists as a node (by id or label) is skipped, so recon
265
+ // data never duplicates or overwrites the scope-asset node set.
266
+ let scopeAst;
267
+ try {
268
+ scopeAst = scope.parse(scopeText);
269
+ } catch {
270
+ scopeAst = { assets: [], outOfScope: [] };
271
+ }
272
+ const nodeExists = (v) => nodes.some((n) => norm(n.id) === norm(v) || norm(n.label) === norm(v));
273
+
274
+ for (const h of recon.readSurface(dir).hosts) {
275
+ const raw = h && h.host;
276
+ if (!raw) continue;
277
+ const verdict = scope.check(scopeAst, raw);
278
+ if (verdict.verdict !== 'allow') continue; // out-of-scope: never a node
279
+ // Store the SAME normalized host that scope.check validated — not the raw
280
+ // string. Otherwise a crafted host (scheme/path/case/whitespace) passes the
281
+ // gate on its normalized form but renders a different value (parser
282
+ // differential / markdown injection). verdict.host is extractHost(raw).
283
+ const host = verdict.host;
284
+ if (!nodeExists(host)) {
285
+ addNode({
286
+ id: host,
287
+ type: 'host',
288
+ label: host,
289
+ inScope: true,
290
+ objectiveKind: null,
291
+ isObjective: false,
292
+ sources: ['recon'],
293
+ });
294
+ }
295
+ for (const svc of h.services || []) {
296
+ const sid = `${host}:${svc.port}`;
297
+ if (!nodeExists(sid)) {
298
+ addNode({
299
+ id: sid,
300
+ type: 'service',
301
+ label: sid,
302
+ inScope: true,
303
+ objectiveKind: null,
304
+ isObjective: false,
305
+ sources: ['recon'],
306
+ });
307
+ }
308
+ }
309
+ }
310
+
311
+ // Assemble the graph object.
312
+ const graph = { schema: 1, nodes, edges, warnings };
313
+ if (objective) graph.objective = objective;
314
+ if (crownArtifact) graph.crownArtifact = crownArtifact;
315
+
316
+ return { graph, objectiveNode };
317
+ }
318
+
319
+ /** render the human-readable ATTACK-GRAPH.md (nodes + edges tables). */
320
+ function renderMarkdown(g) {
321
+ const lines = [];
322
+ lines.push('# Attack Graph');
323
+ lines.push('');
324
+ if (g.objective) lines.push(`**Objective:** ${g.objective} — crown artifact: ${g.crownArtifact || '(unset)'}\n`);
325
+ lines.push('## Nodes');
326
+ lines.push('');
327
+ lines.push('| id | type | label | inScope | objectiveKind | isObjective |');
328
+ lines.push('|----|------|-------|---------|---------------|-------------|');
329
+ for (const n of g.nodes) {
330
+ lines.push(
331
+ `| ${n.id} | ${n.type} | ${String(n.label).replace(/\|/g, '\\|')} | ${n.inScope ? 'yes' : 'no'} | ${n.objectiveKind || ''} | ${n.isObjective ? 'yes' : ''} |`
332
+ );
333
+ }
334
+ lines.push('');
335
+ lines.push('## Edges');
336
+ lines.push('');
337
+ lines.push('| from | to | type | confidence | weight | cwe | methodology | evidence |');
338
+ lines.push('|------|----|------|------------|--------|-----|-------------|----------|');
339
+ for (const e of g.edges) {
340
+ const evidence = Array.isArray(e.evidence) ? e.evidence.join(', ') : String(e.evidence || '');
341
+ lines.push(
342
+ `| ${e.from} | ${e.to} | ${e.type || ''} | ${e.confidence} | ${e.weight} | ${e.cwe || ''} | ${e.methodology || ''} | ${String(evidence).replace(/\|/g, '\\|')} |`
343
+ );
344
+ }
345
+ return lines.join('\n');
346
+ }
347
+
348
+ /** graph.build: assemble, write surface/graph.json + surface/ATTACK-GRAPH.md. */
349
+ function build(dir) {
350
+ const { graph, objectiveNode } = computeGraph(dir);
351
+
352
+ // Fail-closed: an engagement with no in-scope assets has no attack surface.
353
+ if (!graph.nodes.some((n) => n.type === 'asset')) {
354
+ return { ok: false, error: 'no in-scope assets in SCOPE.md — map the engagement first' };
355
+ }
356
+
357
+ fs.mkdirSync(paths.surfaceDir(dir), { recursive: true });
358
+ const file = paths.graphFile(dir);
359
+ const mdFile = paths.attackGraphMdFile(dir);
360
+ fs.writeFileSync(file, JSON.stringify(graph, null, 2) + '\n');
361
+ fs.writeFileSync(mdFile, renderMarkdown(graph) + '\n');
362
+
363
+ return {
364
+ ok: true,
365
+ file,
366
+ mdFile,
367
+ graph,
368
+ nodeCount: graph.nodes.length,
369
+ edgeCount: graph.edges.length,
370
+ objectiveId: objectiveNode ? objectiveNode.id : null,
371
+ objectiveKind: objectiveNode ? objectiveNode.objectiveKind : null,
372
+ warnings: graph.warnings || [],
373
+ };
374
+ }
375
+
376
+ // ---- shortest (Dijkstra, zero external package) ----
377
+ function dijkstra(nodes, edges, fromIds, toId) {
378
+ const idSet = new Set(nodes.map((n) => n.id));
379
+ if (!toId) return null;
380
+ if (!fromIds || fromIds.length === 0) return null;
381
+
382
+ const adj = new Map();
383
+ for (const n of nodes) if (!adj.has(n.id)) adj.set(n.id, []);
384
+ for (const e of edges) {
385
+ if (idSet.has(e.from) && idSet.has(e.to) && adj.has(e.from)) {
386
+ const w = typeof e.weight === 'number' && e.weight >= 0 ? e.weight : 2.0;
387
+ adj.get(e.from).push({ id: e.to, w, edge: e });
388
+ }
389
+ }
390
+
391
+ const dist = Object.fromEntries(nodes.map((n) => [n.id, Infinity]));
392
+ const prev = Object.fromEntries(nodes.map((n) => [n.id, null]));
393
+ for (const sid of fromIds) {
394
+ if (dist[sid] > 0) dist[sid] = 0;
395
+ }
396
+
397
+ const visited = new Set();
398
+ for (let k = 0; k < nodes.length; k++) {
399
+ let u = null, best = Infinity;
400
+ for (const n of nodes) {
401
+ if (!visited.has(n.id) && dist[n.id] < best) {
402
+ best = dist[n.id];
403
+ u = n.id;
404
+ }
405
+ }
406
+ if (u === null) break;
407
+ visited.add(u);
408
+ for (const { id, w, edge } of adj.get(u) || []) {
409
+ if (!visited.has(id) && dist[u] + w < dist[id]) {
410
+ dist[id] = dist[u] + w;
411
+ prev[id] = { id: u, edge };
412
+ }
413
+ }
414
+ }
415
+
416
+ if (dist[toId] === Infinity) return null;
417
+
418
+ const path = [];
419
+ const hops = [];
420
+ let cur = toId;
421
+ while (cur !== null) {
422
+ path.unshift(cur);
423
+ const p = prev[cur];
424
+ if (p && p.edge) hops.unshift(p.edge);
425
+ cur = p ? p.id : null;
426
+ }
427
+
428
+ const startIdx = path.findIndex((id) => fromIds.includes(id));
429
+ if (startIdx === -1) return null;
430
+ return {
431
+ path: path.slice(startIdx),
432
+ hops: hops.slice(startIdx),
433
+ totalWeight: dist[toId],
434
+ };
435
+ }
436
+
437
+ function loadGraph(dir) {
438
+ const file = paths.graphFile(dir);
439
+ if (fs.existsSync(file)) {
440
+ return JSON.parse(fs.readFileSync(file, 'utf8'));
441
+ }
442
+ const { graph } = computeGraph(dir);
443
+ return graph;
444
+ }
445
+
446
+ function resolveObjectiveNode(g, arg) {
447
+ const objectiveNode = g.nodes ? g.nodes.find((n) => n.isObjective) : null;
448
+ if (!objectiveNode) {
449
+ return arg ? { ok: false, error: `no objective matching: ${arg}` } : null;
450
+ }
451
+ const needle = norm(arg || '');
452
+ const candidates = [
453
+ objectiveNode.id,
454
+ objectiveNode.objectiveKind,
455
+ objectiveNode.label,
456
+ g.crownArtifact || '',
457
+ ];
458
+ if (needle && candidates.some((c) => norm(c) === needle)) return { ok: true, node: objectiveNode };
459
+ return { ok: false, error: `no objective matching: ${arg}` };
460
+ }
461
+
462
+ /** graph.shortest: Dijkstra from each in-scope foothold to the objective (PLAN). */
463
+ function shortest(dir, arg) {
464
+ const g = loadGraph(dir);
465
+ const nodes = g.nodes || [];
466
+ const edges = g.edges || [];
467
+
468
+ let toNode;
469
+ if (arg) {
470
+ const r = resolveObjectiveNode(g, arg);
471
+ if (!r.ok) return { ok: false, error: r.error };
472
+ toNode = r.node;
473
+ } else {
474
+ toNode = nodes.find((n) => n.isObjective);
475
+ if (!toNode) return { ok: false, error: 'no objective' };
476
+ }
477
+
478
+ // footholds: in-scope asset nodes; fall back to any source (no incoming edge),
479
+ // never the objective itself.
480
+ let footholds = nodes.filter((n) => n.type === 'asset' && n.inScope);
481
+ if (!footholds.length) {
482
+ const incoming = new Set();
483
+ for (const e of edges) incoming.add(e.from);
484
+ const noIncoming = nodes.filter(
485
+ (n) => n.id !== toNode.id && !incoming.has(n.id)
486
+ );
487
+ if (noIncoming.length) footholds = noIncoming;
488
+ else return { ok: false, error: 'no path to objective' };
489
+ }
490
+
491
+ let best = null;
492
+ for (const f of footholds) {
493
+ const r = dijkstra(nodes, edges, [f.id], toNode.id);
494
+ if (r && (!best || r.totalWeight < best.totalWeight)) best = r;
495
+ }
496
+ if (!best) return { ok: false, error: 'no path to objective' };
497
+
498
+ return {
499
+ ok: true,
500
+ objective: toNode.objectiveKind || g.objective || toNode.label || null,
501
+ path: best.path,
502
+ pathIds: best.path,
503
+ hops: best.hops,
504
+ totalWeight: best.totalWeight,
505
+ edges: best.hops.map((e) => ({ from: e.from, to: e.to, confidence: e.confidence, weight: e.weight })),
506
+ };
507
+ }
508
+
509
+ // ---- simulate: reachability impact + chokepoints ----
510
+ function reachableExcluding(nodes, edges, excludedId, startId) {
511
+ const idSet = new Set(nodes.map((n) => n.id).filter((id) => id !== excludedId));
512
+ if (!idSet.has(startId)) return new Set();
513
+ const adj = new Map();
514
+ for (const e of edges) {
515
+ if (idSet.has(e.from) && idSet.has(e.to)) {
516
+ let list = adj.get(e.from);
517
+ if (!list) { list = []; adj.set(e.from, list); }
518
+ list.push(e.to);
519
+ }
520
+ }
521
+ const seen = new Set();
522
+ const stack = [startId];
523
+ while (stack.length) {
524
+ const u = stack.pop();
525
+ if (seen.has(u)) continue;
526
+ seen.add(u);
527
+ for (const v of adj.get(u) || []) if (!seen.has(v)) stack.push(v);
528
+ }
529
+ return seen;
530
+ }
531
+
532
+ function objectiveReachable(nodes, edges, removedId, objectiveId, startIds) {
533
+ for (const sid of startIds) {
534
+ if (reachableExcluding(nodes, edges, removedId, sid).has(objectiveId)) return true;
535
+ }
536
+ return false;
537
+ }
538
+
539
+ /** graph.simulate: chokepoints (nodes that break all paths) + per-node pivot impact (REPORT). */
540
+ function simulate(dir) {
541
+ const g = loadGraph(dir);
542
+ const nodes = g.nodes || [];
543
+ const edges = g.edges || [];
544
+ const objectiveNode = nodes.find((n) => n.isObjective);
545
+ const startIds = nodes.filter((n) => n.type === 'asset' && n.inScope).map((n) => n.id);
546
+
547
+ const result = { ok: true, nodes: [], chokepoints: [] };
548
+
549
+ // chokepoints: non-objective nodes whose removal leaves the objective unreachable.
550
+ if (objectiveNode && startIds.length) {
551
+ const fullReachable = objectiveReachable(nodes, edges, null, objectiveNode.id, startIds);
552
+ if (fullReachable) {
553
+ result.chokepoints = nodes
554
+ .filter((n) => n.id !== objectiveNode.id && !objectiveReachable(nodes, edges, n.id, objectiveNode.id, startIds))
555
+ .map((n) => n.id);
556
+ }
557
+ }
558
+
559
+ // per-node impact map.
560
+ const before = new Set();
561
+ for (const sid of startIds) {
562
+ for (const id of reachableExcluding(nodes, edges, null, sid)) before.add(id);
563
+ }
564
+ for (const n of nodes) {
565
+ const after = new Set();
566
+ for (const sid of startIds) {
567
+ if (sid === n.id) continue;
568
+ for (const id of reachableExcluding(nodes, edges, n.id, sid)) after.add(id);
569
+ }
570
+ const objectiveLost = objectiveNode
571
+ ? !objectiveReachable(nodes, edges, n.id, objectiveNode.id, startIds)
572
+ : false;
573
+ result.nodes.push({
574
+ id: n.id,
575
+ label: n.label,
576
+ reachableBefore: before.size,
577
+ reachableAfter: after.size,
578
+ objectiveLost,
579
+ });
580
+ }
581
+
582
+ return result;
583
+ }
584
+
585
+ /** readGraph: return the graph object (surface/graph.json when present, else compute).
586
+ * Returns null if no graph can be computed (e.g. no objective / no assets). */
587
+ function readGraph(dir) {
588
+ const g = loadGraph(dir);
589
+ if (!g || !Array.isArray(g.nodes)) return null;
590
+ return g;
591
+ }
592
+
593
+ module.exports = {
594
+ build,
595
+ shortest,
596
+ simulate,
597
+ readGraph,
598
+ help: () => ({
599
+ commands: ['graph.build', 'graph.shortest', 'graph.simulate'],
600
+ contracts:
601
+ 'graph.build: build surface/graph.json + ATTACK-GRAPH.md from scope/findings/evidence (MAP).\n' +
602
+ 'graph.shortest: Dijkstra from each in-scope foothold to the objective (PLAN); ' +
603
+ ' returns {ok, objective, path, pathIds, hops, totalWeight, edges}; refuses on unreachable objective.\n' +
604
+ 'graph.simulate: chokepoints (nodes that break all paths to the objective) ' +
605
+ '+ per-node pivot impact {id, label, reachableBefore, reachableAfter, objectiveLost} (REPORT).',
606
+ }),
607
+ };
@@ -0,0 +1,63 @@
1
+ 'use strict';
2
+ /**
3
+ * ids.cjs — engagement/finding ID generation and validation (ADR-006).
4
+ * Format: <client>-<target>-YYYYMMDD (lowercase slug). Findings: F-NNN.
5
+ */
6
+
7
+ const path = require('node:path');
8
+
9
+ function slug(s) {
10
+ return String(s)
11
+ .normalize('NFKD').replace(/[̀-ͯ]/g, '') // strip diacritics
12
+ .toLowerCase()
13
+ .replace(/^https?:\/\//, '')
14
+ .replace(/[^a-z0-9]+/g, '-')
15
+ .replace(/-{2,}/g, '-')
16
+ .replace(/^-|-$/g, '');
17
+ }
18
+
19
+ function yyyymmdd(date) {
20
+ const d = date || new Date();
21
+ const y = d.getFullYear();
22
+ const m = String(d.getMonth() + 1).padStart(2, '0');
23
+ const day = String(d.getDate()).padStart(2, '0');
24
+ return `${y}${m}${day}`;
25
+ }
26
+
27
+ function engagementId(client, target, date) {
28
+ return `${slug(client)}-${slug(target)}-${yyyymmdd(date)}`;
29
+ }
30
+
31
+ const ENGAGEMENT_ID_RE = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?-[0-9]{8}$/;
32
+ function validateEngagementId(id) {
33
+ return ENGAGEMENT_ID_RE.test(String(id || ''));
34
+ }
35
+
36
+ function findingId(seq) {
37
+ return `F-${String(seq).padStart(3, '0')}`;
38
+ }
39
+
40
+ const FINDING_ID_RE = /^F-(\d{3,})$/;
41
+ function nextFindingSeq(existingIds) {
42
+ let max = 0;
43
+ for (const id of existingIds || []) {
44
+ const m = FINDING_ID_RE.exec(String(id));
45
+ if (m) max = Math.max(max, parseInt(m[1], 10));
46
+ }
47
+ return max + 1;
48
+ }
49
+
50
+ /**
51
+ * composeProjectName(engagementDir) — THE docker compose project name for an
52
+ * engagement (v0.6 01-02, brief 1.8): ONE derivation, shared by
53
+ * env.renderCompose (emits it) and bin findContainer (matches containers
54
+ * with it) so the two can never drift. Compose project names allow
55
+ * [a-z0-9_-] and must be lowercase — underscores are kept here (unlike
56
+ * slug(), which is for engagement ids).
57
+ */
58
+ function composeProjectName(engagementDir) {
59
+ const base = path.basename(String(engagementDir || ''));
60
+ return 'pensieve-' + base.toLowerCase().replace(/[^a-z0-9_-]/g, '');
61
+ }
62
+
63
+ module.exports = { engagementId, findingId, validateEngagementId, nextFindingSeq, composeProjectName };