@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,73 @@
1
+ 'use strict';
2
+ /**
3
+ * paths.cjs — single source of truth for the engagement layout (v0.6, plan 01-01).
4
+ * The .pentest/ layer is eliminated: STATE.md, SCOPE.md, ROE.md, PROJECT.md,
5
+ * ACCOUNTS.md, ATTACK-SURFACE.md, config.yaml and the findings/, evidence/,
6
+ * recon/, plans/, runs/, report/, research/, env/ dirs all live DIRECTLY at
7
+ * the engagement root. Every sdk module resolves engagement-relative paths
8
+ * through here — the layout is defined exactly once.
9
+ */
10
+
11
+ const path = require('node:path');
12
+ const os = require('node:os');
13
+ const fs = require('node:fs');
14
+
15
+ /**
16
+ * $PENSIEVE_HOME (31-01 / SCOP-03): env override respected exactly as the rest
17
+ * of the SDK resolves it (state.cjs registry, target.cjs profiles — same
18
+ * expression, now defined once here for home-level layout, incl. the USER
19
+ * pack root). Default ~/.pensieve.
20
+ */
21
+ function pensieveHome() {
22
+ return process.env.PENSIEVE_HOME
23
+ || process.env.STRIKE_HOME /* legacy pre-rename override */
24
+ || (fs.existsSync(path.join(os.homedir(), '.pensieve'))
25
+ ? path.join(os.homedir(), '.pensieve')
26
+ : path.join(os.homedir(), '.strike') /* legacy install fallback */);
27
+ }
28
+
29
+ /** root-level files every engagement carries (init skeleton set) */
30
+ const ROOT_FILES = ['STATE.md', 'SCOPE.md', 'ROE.md', 'PROJECT.md', 'ACCOUNTS.md', 'ATTACK-SURFACE.md', 'config.yaml'];
31
+
32
+ /** directories init creates (evidence/raw is intentionally nested) */
33
+ const DIRS = ['recon', 'plans', 'findings', 'evidence/raw', 'research', 'report', 'runs'];
34
+
35
+ /** resolve engagement-relative segments against the engagement root */
36
+ function resolve(root, ...segments) {
37
+ return path.join(root, ...segments);
38
+ }
39
+
40
+ const stateFile = (root) => resolve(root, 'STATE.md');
41
+ const scopeFile = (root) => resolve(root, 'SCOPE.md');
42
+ const projectFile = (root) => resolve(root, 'PROJECT.md');
43
+ const accountsFile = (root) => resolve(root, 'ACCOUNTS.md');
44
+ const configFile = (root) => resolve(root, 'config.yaml');
45
+ const continueHereFile = (root) => resolve(root, 'continue-here.md');
46
+ const retrospectiveFile = (root) => resolve(root, 'RETROSPECTIVE.md');
47
+
48
+ const findingsDir = (root) => resolve(root, 'findings');
49
+ const findingsIndex = (root) => resolve(root, 'findings', 'INDEX.md');
50
+ const evidenceDir = (root) => resolve(root, 'evidence');
51
+ const evidenceRawDir = (root) => resolve(root, 'evidence', 'raw');
52
+ const evidenceIndex = (root) => resolve(root, 'evidence', 'INDEX.md');
53
+ const reconDir = (root) => resolve(root, 'recon');
54
+ const reconSurfaceFile = (root) => resolve(root, 'recon', 'surface.json');
55
+ const plansDir = (root) => resolve(root, 'plans');
56
+ const runsDir = (root) => resolve(root, 'runs');
57
+ const reportDir = (root) => resolve(root, 'report');
58
+ const researchDir = (root) => resolve(root, 'research');
59
+ const envDir = (root) => resolve(root, 'env');
60
+
61
+ // ---- attack graph (ADR-025) ----
62
+ const surfaceDir = (root) => resolve(root, 'surface');
63
+ const graphFile = (root) => resolve(root, 'surface', 'graph.json');
64
+ const attackGraphMdFile = (root) => resolve(root, 'surface', 'ATTACK-GRAPH.md');
65
+
66
+ module.exports = {
67
+ ROOT_FILES, DIRS, resolve, pensieveHome,
68
+ stateFile, scopeFile, projectFile, accountsFile, configFile,
69
+ continueHereFile, retrospectiveFile,
70
+ findingsDir, findingsIndex, evidenceDir, evidenceRawDir, evidenceIndex,
71
+ reconDir, reconSurfaceFile, plansDir, runsDir, reportDir, researchDir, envDir,
72
+ surfaceDir, graphFile, attackGraphMdFile,
73
+ };
@@ -0,0 +1,291 @@
1
+ 'use strict';
2
+ /**
3
+ * pdf.cjs — report.pdf: formal (keystone-style) PDF export (v0.6 01-04,
4
+ * brief 1.11 / ADR-014 lane-B host tool).
5
+ *
6
+ * Flow (every refusal names its gate):
7
+ * 1. engagement marker — STATE.md with status frontmatter (flat layout).
8
+ * 2. gate report.verify — verifyReport() must pass (no reporter
9
+ * placeholders; findings table in sync with the register).
10
+ * 3. gate approval:report — approvals.isApproved(dir, 'report') must be
11
+ * true: the human checkpoint on report/REPORT.md (ADR-023). PDF export
12
+ * happens only AFTER recorded human approval.
13
+ * 4. probe — the renderer is a Python/ReportLab script running on the HOST
14
+ * (lane B, ADR-014). The sdk stays ZERO-DEPENDENCY: it never installs
15
+ * anything. A failed probe returns ok:false with exact setup
16
+ * instructions (venv + pip install reportlab + PENSIEVE_PDF_PYTHON).
17
+ * 5. execute — the engagement payload (findings register + evidence ledger
18
+ * + PROJECT/SCOPE metadata + branding) is passed to the renderer as JSON
19
+ * on stdin; report/REPORT.pdf comes back; its path + sha256 are returned.
20
+ *
21
+ * Branding: neutral Pensieve defaults in assets/branding/config.json, with
22
+ * per-engagement overrides via config.yaml (pdf_brand_org / pdf_brand_accent
23
+ * / pdf_brand_footer / pdf_classification / pdf_tlp — see lib/config.cjs).
24
+ * Keystone's own brand identity is NOT carried over.
25
+ */
26
+
27
+ const fs = require('node:fs');
28
+ const path = require('node:path');
29
+ const crypto = require('node:crypto');
30
+ const { spawnSync } = require('node:child_process');
31
+ const fm = require('./frontmatter.cjs');
32
+ const state = require('./state.cjs');
33
+ const paths = require('./paths.cjs');
34
+ const config = require('./config.cjs');
35
+ const evidence = require('./evidence.cjs');
36
+ const approvals = require('./approvals.cjs');
37
+ const report = require('./report.cjs');
38
+
39
+ const REPO_ROOT = path.join(__dirname, '..', '..', '..');
40
+ const RENDERER = path.join(__dirname, 'renderers', 'formal_report.py');
41
+ const BRANDING_DIR = path.join(REPO_ROOT, 'assets', 'branding');
42
+ const BRANDING_CONFIG = path.join(BRANDING_DIR, 'config.json');
43
+
44
+ // Last-resort defaults if assets/branding/config.json is unreadable — the
45
+ // neutral Pensieve identity (keystone's brand is deliberately NOT reused).
46
+ const BRAND_FALLBACK = {
47
+ companyName: 'PENSIEVE',
48
+ reportTitle: 'Penetration Test Report',
49
+ accentColor: '1F5F6B',
50
+ footerText: 'Confidential — for the intended recipients only',
51
+ logoFile: null,
52
+ };
53
+
54
+ const SETUP_INSTRUCTIONS = [
55
+ 'report.pdf renders via a lane-B host tool (ADR-014): python3 with ReportLab on the HOST.',
56
+ 'The sdk is zero-dependency and will not install it for you. Setup:',
57
+ ' python3 -m venv ~/.venvs/pensieve-pdf',
58
+ ' ~/.venvs/pensieve-pdf/bin/pip install reportlab',
59
+ ' export PENSIEVE_PDF_PYTHON=~/.venvs/pensieve-pdf/bin/python3',
60
+ '(alternative: python3 -m pip install --user reportlab to use the system python3)',
61
+ ].join('\n');
62
+
63
+ function refuse(gate, error, extra = {}) {
64
+ return { ok: false, gate, error, data: null, ...extra };
65
+ }
66
+
67
+ function readOr(file, fallback = '') {
68
+ return fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : fallback;
69
+ }
70
+
71
+ /** probe python3 (+ optional override) for an importable reportlab */
72
+ function probePython(py) {
73
+ let r;
74
+ try {
75
+ r = spawnSync(py, ['-c', 'import reportlab'], { encoding: 'utf8' });
76
+ } catch (e) {
77
+ return { ok: false, reason: `python probe could not start (${py}): ${e.message}` };
78
+ }
79
+ if (r.error) {
80
+ return { ok: false, reason: `python3 not found on the host (looked for "${py}")` };
81
+ }
82
+ if (r.status !== 0) {
83
+ return { ok: false, reason: `python3 found ("${py}") but reportlab is not importable` };
84
+ }
85
+ return { ok: true, python: py };
86
+ }
87
+
88
+ /** branding resolution: assets/branding/config.json < config.yaml overrides */
89
+ function resolveBranding(cfg) {
90
+ let file = {};
91
+ try {
92
+ file = JSON.parse(fs.readFileSync(BRANDING_CONFIG, 'utf8'));
93
+ } catch { /* missing/corrupt branding config degrades to fallback */ }
94
+ const b = { ...BRAND_FALLBACK, ...file };
95
+ if (cfg.pdf_brand_org) b.companyName = String(cfg.pdf_brand_org);
96
+ if (cfg.pdf_brand_accent) b.accentColor = String(cfg.pdf_brand_accent);
97
+ if (cfg.pdf_brand_footer) b.footerText = String(cfg.pdf_brand_footer);
98
+ b.accentColor = String(b.accentColor || BRAND_FALLBACK.accentColor).replace(/^#/, '');
99
+ // logo: resolved to an absolute path only when it really exists inside
100
+ // assets/branding/ (the renderer treats a missing logo as "no logo").
101
+ b.logoPath = null;
102
+ if (b.logoFile && typeof b.logoFile === 'string') {
103
+ const lp = path.resolve(BRANDING_DIR, b.logoFile);
104
+ if (lp.startsWith(BRANDING_DIR + path.sep) && fs.existsSync(lp) && fs.statSync(lp).isFile()) {
105
+ b.logoPath = lp;
106
+ }
107
+ }
108
+ delete b.logoFile;
109
+ return b;
110
+ }
111
+
112
+ /** the approved report source: REPORT.md (the approved artifact) > EXEC.md */
113
+ function reportSource(dir) {
114
+ const rd = paths.reportDir(dir);
115
+ for (const f of ['REPORT.md', 'EXEC.md']) {
116
+ const p = path.join(rd, f);
117
+ if (fs.existsSync(p)) return p;
118
+ }
119
+ return null;
120
+ }
121
+
122
+ /** reporter prose for the executive summary: the '## ... Executive Summary'
123
+ * section of the approved report, markdown tables stripped (the PDF renders
124
+ * its own tables from the register). */
125
+ function execSummary(body) {
126
+ const secs = report.sections(body);
127
+ const key = Object.keys(secs).find((k) => /executive summary/i.test(k));
128
+ if (!key) return [];
129
+ return secs[key]
130
+ .split('\n')
131
+ .filter((l) => !l.trim().startsWith('|'))
132
+ .join('\n')
133
+ .split(/\n{2,}/)
134
+ .map((p) => p.trim())
135
+ .filter(Boolean);
136
+ }
137
+
138
+ /**
139
+ * assemblePayload(dir) — the data contract with the Python renderer.
140
+ * Findings come from the register via report.sortedReportFindings (the SAME
141
+ * ordering/severity the markdown report uses); each finding's payload carries
142
+ * the ordered 9-section standard shape (report.findingBlock — 35-01 REP-03:
143
+ * ONE sourcing for REPORT.md and the PDF, structured fields first, legacy
144
+ * prose fallback) and the per-finding prose keys formal_report.py reads,
145
+ * derived from the same sections; evidence comes from the hash-chained ledger.
146
+ */
147
+ function assemblePayload(dir) {
148
+ const { cfg } = config.load(dir);
149
+ const branding = resolveBranding(cfg);
150
+ const id = path.basename(path.resolve(dir));
151
+ const src = reportSource(dir);
152
+ const { data: srcFm, body: srcBody } = src ? fm.parse(readOr(src)) : { data: {}, body: '' };
153
+
154
+ const scopeSecs = report.sections(readOr(paths.scopeFile(dir)));
155
+ const projectSecs = report.sections(readOr(paths.projectFile(dir)));
156
+
157
+ const rows = report.sortedReportFindings(dir);
158
+ const findingsPayload = rows.map((r) => {
159
+ // 35-01 (REP-03): the ordered 9-section payload — formal_report.py renders
160
+ // the standard's section order from it (reportDir omitted = payload mode)
161
+ const { sections } = report.findingBlock(dir, r);
162
+ const sec = (key) => {
163
+ const s = sections.find((x) => x.key === key);
164
+ return s && s.text ? s.text : '';
165
+ };
166
+ return {
167
+ id: r.id,
168
+ title: String(r.title || ''),
169
+ cwe: r.cwe || '—',
170
+ cvss_score: r.cvss_score,
171
+ cvss_vector: r.cvss_vector || '',
172
+ severity: report.sevLabel(r),
173
+ status: r.status,
174
+ assets: r.assets || [],
175
+ evidence: r.evidence || [],
176
+ sections,
177
+ // legacy per-finding prose keys — now fed from the new standard fields
178
+ // (structured first, legacy prose fallback), never '_pending_'
179
+ summary: sec('description'),
180
+ impact: sec('impact'),
181
+ evidence_text: sec('poc'),
182
+ remediation: sec('remediation'),
183
+ };
184
+ });
185
+
186
+ const rejected = require('./findings.cjs').list(dir, { status: 'rejected' })
187
+ .map((r) => ({ id: r.id, title: String(r.title || '') }));
188
+
189
+ return {
190
+ schema: 'pensieve.report-pdf/1',
191
+ meta: {
192
+ engagement: id,
193
+ title: `${branding.reportTitle} — ${id}`,
194
+ client: srcFm.client || '—',
195
+ service: srcFm.service || 'Penetration Test',
196
+ classification: String(cfg.pdf_classification || 'CONFIDENTIAL'),
197
+ tlp: String(cfg.pdf_tlp || 'AMBER'),
198
+ version: srcFm.version || '1.0',
199
+ date: (srcFm.approved_at ? String(srcFm.approved_at).slice(0, 10) : null)
200
+ || new Date().toISOString().slice(0, 10),
201
+ reference: id,
202
+ prepared_by: srcFm.prepared_by || 'pensieve-reporter',
203
+ approved_by: srcFm.approved_by || null,
204
+ approved_at: srcFm.approved_at || null,
205
+ },
206
+ branding,
207
+ executive_summary: execSummary(srcBody),
208
+ scope: {
209
+ in_scope: scopeSecs['In Scope'] || '',
210
+ out_of_scope: scopeSecs['Out of Scope'] || '',
211
+ coverage_notes: scopeSecs['Coverage notes'] || '',
212
+ objectives: projectSecs.Objectives || '',
213
+ },
214
+ findings: findingsPayload,
215
+ evidence: evidence.readIndex(dir).map((e) => ({
216
+ id: e.id, path: e.path, sha256: e.sha256,
217
+ finding_id: e.finding_id ?? null, note: e.note ?? null, stored_at: e.stored_at || null,
218
+ })),
219
+ rejected,
220
+ };
221
+ }
222
+
223
+ /**
224
+ * render(dir, { out, python }) — the report.pdf pipeline. JSON-style
225
+ * envelope { ok, gate, error, data }; every refusal names its gate.
226
+ */
227
+ function render(dir, { out = null, python = null } = {}) {
228
+ if (!dir || !state.isEngagement(dir)) {
229
+ return refuse('engagement-marker',
230
+ 'report.pdf requires an engagement dir (no STATE.md with status frontmatter at the given path)');
231
+ }
232
+
233
+ // Gate 1: report.verify (brief 1.6/1.11) — placeholders + register sync.
234
+ let v;
235
+ try {
236
+ v = report.verifyReport(dir);
237
+ } catch (e) {
238
+ return refuse('report.verify', `gate report.verify refused: ${e.message}`);
239
+ }
240
+ if (!v.ok) {
241
+ return refuse('report.verify', `gate report.verify refused: ${v.error}`);
242
+ }
243
+
244
+ // Gate 2: recorded human approval of report/REPORT.md (ADR-023).
245
+ if (!approvals.isApproved(dir, 'report')) {
246
+ return refuse('approval:report',
247
+ 'gate approval:report refused — report/REPORT.md is not approved. '
248
+ + 'Record the checkpoint: pensieve-sdk approve --engagement <dir> --artifact report --by <name>');
249
+ }
250
+
251
+ // Lane-B probe (ADR-014): python3 + reportlab on the HOST. Never install,
252
+ // never crash — return exact setup instructions.
253
+ const py = python || process.env.PENSIEVE_PDF_PYTHON || 'python3';
254
+ const probe = probePython(py);
255
+ if (!probe.ok) {
256
+ return refuse('renderer-probe', `${probe.reason}.\n${SETUP_INSTRUCTIONS}`,
257
+ { instructions: SETUP_INSTRUCTIONS });
258
+ }
259
+
260
+ if (!fs.existsSync(RENDERER)) {
261
+ return refuse('renderer-exec', `renderer script missing from the sdk install: ${RENDERER}`);
262
+ }
263
+
264
+ const payload = assemblePayload(dir);
265
+ const outPath = out || path.join(paths.reportDir(dir), 'REPORT.pdf');
266
+ fs.mkdirSync(path.dirname(outPath), { recursive: true });
267
+
268
+ const r = spawnSync(py, [RENDERER, '--output', outPath], {
269
+ input: JSON.stringify(payload),
270
+ encoding: 'utf8',
271
+ maxBuffer: 64 * 1024 * 1024,
272
+ });
273
+ if (r.error) {
274
+ return refuse('renderer-exec', `renderer failed to start: ${r.error.message}`);
275
+ }
276
+ if (r.status !== 0) {
277
+ return refuse('renderer-exec',
278
+ `renderer exited ${r.status}: ${(r.stderr || '').trim().slice(-500)}`);
279
+ }
280
+ if (!fs.existsSync(outPath) || fs.statSync(outPath).size === 0) {
281
+ return refuse('renderer-exec', 'renderer reported success but the PDF is missing or empty');
282
+ }
283
+ const buf = fs.readFileSync(outPath);
284
+ const sha256 = crypto.createHash('sha256').update(buf).digest('hex');
285
+ return {
286
+ ok: true, gate: null, error: null,
287
+ data: { written: outPath, sha256, bytes: buf.length, findings: payload.findings.length },
288
+ };
289
+ }
290
+
291
+ module.exports = { render, assemblePayload, probePython, resolveBranding, SETUP_INSTRUCTIONS, RENDERER };
@@ -0,0 +1,296 @@
1
+ 'use strict';
2
+ const fs = require('node:fs');
3
+ const path = require('node:path');
4
+ const fm = require('./frontmatter.cjs');
5
+ const paths = require('./paths.cjs');
6
+ const scope = require('./scope.cjs');
7
+ /**
8
+ * recon.cjs — per-engagement structured recon surface (GRAPH-06).
9
+ *
10
+ * recon/surface.json is the machine-readable host/service set the attack graph
11
+ * (ADR-025, plan 06-01 part 2) reads instead of parsing recon/SUMMARY.md prose.
12
+ * Per-engagement ONLY: this module never imports the cross-engagement asset
13
+ * registry (reading it would leak hosts from other engagements — see
14
+ * 06-CONTEXT data-source trap). Modeled on scope.recordBox: fail-closed writer,
15
+ * preserve-existing, deterministic serialize.
16
+ *
17
+ * Surface shape:
18
+ * { "hosts": [ { "host": "api.acme.com", "services": [ { "port": 443, "proto": "https" } ] } ] }
19
+ */
20
+
21
+ function normalizeServices(services) {
22
+ if (services === undefined || services === null) return [];
23
+ if (!Array.isArray(services)) throw new Error('services must be an array');
24
+ return services.map((s) => {
25
+ const port = Number(s && s.port);
26
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
27
+ throw new Error(`invalid service port: ${s && s.port} (expected integer 1..65535)`);
28
+ }
29
+ const svc = { port };
30
+ if (s.proto !== undefined && s.proto !== null && String(s.proto).trim() !== '') {
31
+ svc.proto = String(s.proto).trim();
32
+ }
33
+ return svc;
34
+ });
35
+ }
36
+
37
+ /**
38
+ * readSurface — read recon/surface.json. Returns { hosts: [] } when the file is
39
+ * absent or unparseable (the graph must never crash on missing/corrupt recon
40
+ * data — T-06-03). Always guarantees a hosts array on the returned object.
41
+ */
42
+ function readSurface(engagementDir) {
43
+ const file = paths.reconSurfaceFile(engagementDir);
44
+ if (!fs.existsSync(file)) return { hosts: [] };
45
+ let parsed;
46
+ try {
47
+ parsed = JSON.parse(fs.readFileSync(file, 'utf8'));
48
+ } catch {
49
+ return { hosts: [] };
50
+ }
51
+ if (!parsed || typeof parsed !== 'object' || !Array.isArray(parsed.hosts)) {
52
+ return { hosts: [] };
53
+ }
54
+ return parsed;
55
+ }
56
+
57
+ /**
58
+ * recordHost — add/merge an in-scope discovered host (+ optional services) into
59
+ * recon/surface.json. Fail-closed (T-06-02): an empty normalized host or an
60
+ * out-of-range port throws and writes nothing. Dedupes by normalized host and
61
+ * merges services by port (no duplicate ports). Returns the updated host entry.
62
+ */
63
+ // Markdown-table / report-injection + control chars. Recon host/port flow into
64
+ // node labels rendered into REPORT.md / ATTACK-GRAPH.md tables; a host carrying
65
+ // '|', newline, '[' ']' '<' '>' or a backtick breaks or injects the table.
66
+ // Fail-closed at write time (T-06-02 style), so a crafted host never reaches a node.
67
+ const UNSAFE_HOST_CHARS = /[|\r\n\[\]<>`]/;
68
+
69
+ function recordHost(engagementDir, { host, services } = {}) {
70
+ const normHost = scope.extractHost(host === undefined || host === null ? '' : host);
71
+ if (!normHost) throw new Error('recon.recordHost: host is required');
72
+ if (UNSAFE_HOST_CHARS.test(normHost)) {
73
+ throw new Error(`recon.recordHost: host has unsafe markdown/control chars: ${JSON.stringify(normHost)}`);
74
+ }
75
+ const newServices = normalizeServices(services); // validate before any write
76
+
77
+ const surface = readSurface(engagementDir);
78
+ let entry = surface.hosts.find((h) => h.host === normHost);
79
+ if (!entry) {
80
+ entry = { host: normHost, services: [] };
81
+ surface.hosts.push(entry);
82
+ }
83
+ if (!Array.isArray(entry.services)) entry.services = [];
84
+ for (const svc of newServices) {
85
+ if (!entry.services.some((e) => e.port === svc.port)) entry.services.push(svc);
86
+ }
87
+
88
+ const file = paths.reconSurfaceFile(engagementDir);
89
+ fs.mkdirSync(path.dirname(file), { recursive: true });
90
+ fs.writeFileSync(file, JSON.stringify(surface, null, 2) + '\n');
91
+ return entry;
92
+ }
93
+
94
+ /**
95
+ * fingerprintDiff — compare live markers against the STORED baseline
96
+ * (recon/FINGERPRINT.md `## Markers`; history is never diffed). Returns
97
+ * { same, drift, added, removed }:
98
+ * drift — [{ key, stored, live }] for every marker whose value changed
99
+ * (comparison is trimmed + case-sensitive, like the store);
100
+ * added — keys only the live set carries;
101
+ * removed — keys only the baseline carries;
102
+ * same — true iff all three lists are empty (the retest may proceed).
103
+ * Fail-closed: no stored fingerprint refuses (diffing against nothing would
104
+ * rubber-stamp same:true); an empty live set refuses the same way the writer
105
+ * does. 22-02 wires this as the diff-first gate: any drift aborts to
106
+ * re-fingerprint + redo guidance.
107
+ */
108
+ function fingerprintDiff(engagementDir, liveMarkers) {
109
+ const stored = readFingerprint(engagementDir);
110
+ if (!stored) {
111
+ throw new Error(
112
+ 'recon.fingerprintDiff: no stored fingerprint at recon/FINGERPRINT.md — capture the baseline first (recon.fingerprint); refusing to diff against nothing'
113
+ );
114
+ }
115
+ const live = normalizeMarkers(liveMarkers);
116
+ const drift = [];
117
+ const added = [];
118
+ const removed = [];
119
+ for (const key of Object.keys(live).sort()) {
120
+ if (!(key in stored.markers)) added.push(key);
121
+ else if (stored.markers[key] !== live[key]) drift.push({ key, stored: stored.markers[key], live: live[key] });
122
+ }
123
+ for (const key of Object.keys(stored.markers).sort()) {
124
+ if (!(key in live)) removed.push(key);
125
+ }
126
+ return { same: drift.length === 0 && added.length === 0 && removed.length === 0, drift, added, removed };
127
+ }
128
+
129
+ module.exports = { readSurface, recordHost, fingerprint, readFingerprint, fingerprintDiff, normalizeMarkers };
130
+
131
+ // ---------------------------------------------------------------------------
132
+ // Phase 22 (RETEST-01, plan 22-01): recon fingerprint capture + deterministic
133
+ // diff — the upgrade-aware retest baseline.
134
+ //
135
+ // recon/FINGERPRINT.md is the version/build snapshot taken at recon time
136
+ // (server headers, version/build strings, cookie names — whatever the recon
137
+ // pass observed). The retest pass (22-02 wires the workflow) re-observes the
138
+ // same markers and diffs them: any drift means the target moved under us and
139
+ // the retest verdicts are about a DIFFERENT build than the findings were.
140
+ //
141
+ // Hard rules (pinned in recon.test.cjs):
142
+ // - the SDK NEVER fetches: markers are caller-supplied key=value strings
143
+ // (or a plain object / JSON object) — store + diff, nothing else;
144
+ // - deterministic: keys sorted, keys/values trimmed, values case-sensitive;
145
+ // - fail-closed on an empty or malformed marker set (no partial writes);
146
+ // - human-inspectable markdown (file-based state philosophy): frontmatter
147
+ // (captured_at, count) + a `## Markers` block of `- `key`: value` lines
148
+ // the diff re-parses;
149
+ // - overwrite KEEPS HISTORY: each superseded capture is appended to a
150
+ // `## History` block (the one mechanism — no backup-file fan-out).
151
+ // ---------------------------------------------------------------------------
152
+
153
+ const fingerprintFile = (engagementDir) => path.join(paths.reconDir(engagementDir), 'FINGERPRINT.md');
154
+
155
+ // marker keys render inside backticks and both sides of a `key: value` line
156
+ // the diff re-parses: a key/value carrying whitespace, ':', backtick or a
157
+ // control char would break or inject the line. Fail closed at write time.
158
+ const UNSAFE_MARKER_CHARS = /[\s`:|\r\n<>\[\]]/;
159
+
160
+ /**
161
+ * normalizeMarkers — accept every caller shape and reduce it to a validated,
162
+ * key-sorted plain object of trimmed, case-sensitive values:
163
+ * ['k=v', ...] | { k: v } | ['{"k":"v"}'] (a JSON object string)
164
+ * Throws (naming the offender) on: empty set, a pair without '=', a duplicate
165
+ * key, or unsafe key/value characters. Values may be empty ('cookie=') — a
166
+ * present-but-empty header is a real observation.
167
+ */
168
+ function normalizeMarkers(markers) {
169
+ let entries = [];
170
+ if (markers !== null && typeof markers === 'object' && !Array.isArray(markers)) {
171
+ entries = Object.entries(markers);
172
+ } else {
173
+ const items = (Array.isArray(markers) ? markers : [markers]).map((s) => String(s));
174
+ for (const item of items) {
175
+ const s = item.trim();
176
+ if (!s) continue;
177
+ if (s.startsWith('{')) {
178
+ let parsed;
179
+ try {
180
+ parsed = JSON.parse(s);
181
+ } catch {
182
+ throw new Error(`recon fingerprint: marker is not valid JSON: ${JSON.stringify(s.slice(0, 60))}`);
183
+ }
184
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
185
+ throw new Error('recon fingerprint: JSON markers must be an object of key/value pairs');
186
+ }
187
+ entries.push(...Object.entries(parsed));
188
+ continue;
189
+ }
190
+ const eq = s.indexOf('=');
191
+ if (eq === -1) {
192
+ throw new Error(`recon fingerprint: marker is not a key=value pair: ${JSON.stringify(s)}`);
193
+ }
194
+ entries.push([s.slice(0, eq), s.slice(eq + 1)]);
195
+ }
196
+ }
197
+ if (entries.length === 0) {
198
+ throw new Error('recon fingerprint: at least one marker (key=value) is required — an empty fingerprint is meaningless');
199
+ }
200
+ const out = {};
201
+ for (const [rawKey, rawVal] of entries) {
202
+ const key = String(rawKey).trim();
203
+ const val = String(rawVal).trim();
204
+ if (!key) throw new Error(`recon fingerprint: marker key is empty in ${JSON.stringify(`${rawKey}=${rawVal}`)}`);
205
+ if (UNSAFE_MARKER_CHARS.test(key) || UNSAFE_MARKER_CHARS.test(val)) {
206
+ throw new Error(
207
+ `recon fingerprint: marker ${JSON.stringify(key)} has unsafe chars (whitespace, ':', backtick, table/control chars) — refusing`
208
+ );
209
+ }
210
+ if (key in out) throw new Error(`recon fingerprint: duplicate marker key ${JSON.stringify(key)} — a marker means exactly one thing`);
211
+ out[key] = val;
212
+ }
213
+ return out;
214
+ }
215
+
216
+ /** re-parse the `- `key`: value` lines of a `## Section` block (current or history) */
217
+ function parseMarkerBlock(text, heading) {
218
+ const idx = text.indexOf(`## ${heading}`);
219
+ if (idx === -1) return {};
220
+ const rest = text.slice(idx).split('\n').slice(1);
221
+ const markers = {};
222
+ for (const line of rest) {
223
+ if (line.startsWith('## ')) break; // next section ends the block
224
+ const m = /^- `([^`]+)`: (.*)$/.exec(line);
225
+ if (m) markers[m[1]] = m[2];
226
+ }
227
+ return markers;
228
+ }
229
+
230
+ /**
231
+ * readFingerprint — parse recon/FINGERPRINT.md. Returns
232
+ * { captured_at, count, markers } or null when no fingerprint exists
233
+ * (absent is absent — never guessed).
234
+ */
235
+ function readFingerprint(engagementDir) {
236
+ const file = fingerprintFile(engagementDir);
237
+ if (!fs.existsSync(file)) return null;
238
+ const txt = fs.readFileSync(file, 'utf8');
239
+ const { data } = fm.parse(txt);
240
+ const markers = parseMarkerBlock(txt, 'Markers');
241
+ return { captured_at: data.captured_at || null, count: data.count, markers };
242
+ }
243
+
244
+ /**
245
+ * fingerprint — capture (or re-capture) the recon marker baseline.
246
+ * Writes recon/FINGERPRINT.md: frontmatter (captured_at, count) + the current
247
+ * `## Markers` block. On overwrite the previous capture (captured_at + its
248
+ * markers) is appended to `## History`, newest last — the baseline is
249
+ * replaceable, the record is not. Returns the readFingerprint view.
250
+ */
251
+ function fingerprint(engagementDir, markers) {
252
+ const normalized = normalizeMarkers(markers); // validate BEFORE any write
253
+ const file = fingerprintFile(engagementDir);
254
+ const capturedAt = new Date().toISOString();
255
+
256
+ const markerLines = Object.keys(normalized).sort()
257
+ .map((k) => `- \`${k}\`: ${normalized[k]}`);
258
+
259
+ const historyEntries = [];
260
+ const prior = fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : null;
261
+ if (prior) {
262
+ // keep the existing history, then append the capture being superseded
263
+ const histIdx = prior.indexOf('## History');
264
+ if (histIdx !== -1) {
265
+ historyEntries.push(prior.slice(histIdx + '## History'.length).replace(/^\s+/, '').replace(/\s+$/, ''));
266
+ }
267
+ const priorRead = readFingerprint(engagementDir);
268
+ const priorLines = Object.keys(priorRead.markers).sort()
269
+ .map((k) => `- \`${k}\`: ${priorRead.markers[k]}`);
270
+ historyEntries.push([
271
+ `### Superseded ${priorRead.captured_at || '(unknown capture time)'} (${Object.keys(priorRead.markers).length} markers)`,
272
+ '',
273
+ ...priorLines,
274
+ ].join('\n'));
275
+ }
276
+
277
+ const body = [
278
+ '# Recon Fingerprint',
279
+ '',
280
+ 'Baseline markers captured at recon time (server headers, version/build',
281
+ 'strings, cookie names — what the recon pass observed). The retest pass',
282
+ 'diffs live markers against this file (`recon.fingerprint-diff`); ANY drift',
283
+ 'means the target moved: re-fingerprint and redo the retest before',
284
+ 'trusting verdicts measured against a different build.',
285
+ '',
286
+ '## Markers',
287
+ '',
288
+ ...markerLines,
289
+ ...(historyEntries.length ? ['', '## History', '', ...historyEntries.map((h) => h + '\n')] : []),
290
+ ].join('\n');
291
+
292
+ fs.mkdirSync(path.dirname(file), { recursive: true });
293
+ const out = fm.stringify({ captured_at: capturedAt, count: markerLines.length }, body);
294
+ fs.writeFileSync(file, out.endsWith('\n') ? out : out + '\n');
295
+ return readFingerprint(engagementDir);
296
+ }