@cclabsnz/sf-audit 1.15.1 → 1.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (119) hide show
  1. package/CHANGELOG.md +143 -1
  2. package/README.md +100 -24
  3. package/config/scoring.sample.json +104 -5
  4. package/lib/apps/analyzeApps.d.ts +8 -2
  5. package/lib/apps/analyzeApps.js +7 -2
  6. package/lib/apps/apiLogSource.d.ts +39 -0
  7. package/lib/apps/apiLogSource.js +75 -0
  8. package/lib/apps/appResolver.js +30 -4
  9. package/lib/apps/grantedAccess.js +16 -3
  10. package/lib/apps/leastPrivilege.d.ts +3 -1
  11. package/lib/apps/leastPrivilege.js +7 -3
  12. package/lib/apps/permissionSetGenerator.d.ts +22 -0
  13. package/lib/apps/permissionSetGenerator.js +100 -0
  14. package/lib/apps/types.d.ts +6 -0
  15. package/lib/apps/usageCollector.d.ts +7 -1
  16. package/lib/apps/usageCollector.js +57 -26
  17. package/lib/chains/CapabilityRegistry.js +26 -0
  18. package/lib/chains/namedChains.js +110 -3
  19. package/lib/checks/CheckEngine.d.ts +3 -1
  20. package/lib/checks/CheckEngine.js +11 -3
  21. package/lib/checks/impl/AgentInventoryCheck.js +8 -3
  22. package/lib/checks/impl/AgentOutboundActionsCheck.d.ts +13 -0
  23. package/lib/checks/impl/AgentOutboundActionsCheck.js +155 -0
  24. package/lib/checks/impl/AgentQueryReachCheck.d.ts +11 -0
  25. package/lib/checks/impl/AgentQueryReachCheck.js +88 -0
  26. package/lib/checks/impl/ApexCrudFLSCheck.js +45 -10
  27. package/lib/checks/impl/ApexSharingCheck.js +16 -25
  28. package/lib/checks/impl/AuthProviderRegistrationHandlerCheck.d.ts +10 -0
  29. package/lib/checks/impl/AuthProviderRegistrationHandlerCheck.js +131 -0
  30. package/lib/checks/impl/ConnectedAppsCheck.js +47 -1
  31. package/lib/checks/impl/DataCloudDataSpaceIsolationCheck.d.ts +10 -0
  32. package/lib/checks/impl/DataCloudDataSpaceIsolationCheck.js +116 -0
  33. package/lib/checks/impl/DelegatedAdministrationGroupsCheck.d.ts +10 -0
  34. package/lib/checks/impl/DelegatedAdministrationGroupsCheck.js +75 -0
  35. package/lib/checks/impl/DelegatedAuthenticationExposureCheck.d.ts +10 -0
  36. package/lib/checks/impl/DelegatedAuthenticationExposureCheck.js +98 -0
  37. package/lib/checks/impl/ExternalAccountHierarchyExposureCheck.d.ts +10 -0
  38. package/lib/checks/impl/ExternalAccountHierarchyExposureCheck.js +73 -0
  39. package/lib/checks/impl/FlowHttpCalloutCredentialBypassCheck.d.ts +10 -0
  40. package/lib/checks/impl/FlowHttpCalloutCredentialBypassCheck.js +115 -0
  41. package/lib/checks/impl/GenAiPromptTemplateGroundingCheck.d.ts +10 -0
  42. package/lib/checks/impl/GenAiPromptTemplateGroundingCheck.js +227 -0
  43. package/lib/checks/impl/GuestExecutableApexCheck.d.ts +1 -1
  44. package/lib/checks/impl/GuestExecutableApexCheck.js +105 -14
  45. package/lib/checks/impl/HardcodedCredentialsCheck.js +7 -2
  46. package/lib/checks/impl/InboundEmailHandlerExposureCheck.d.ts +10 -0
  47. package/lib/checks/impl/InboundEmailHandlerExposureCheck.js +136 -0
  48. package/lib/checks/impl/OauthDeviceAndAssetTokenFlowsCheck.d.ts +10 -0
  49. package/lib/checks/impl/OauthDeviceAndAssetTokenFlowsCheck.js +84 -0
  50. package/lib/checks/impl/OrgWideEmailSpoofingCheck.d.ts +10 -0
  51. package/lib/checks/impl/OrgWideEmailSpoofingCheck.js +106 -0
  52. package/lib/checks/impl/PackagePostInstallSupplyChainCheck.d.ts +10 -0
  53. package/lib/checks/impl/PackagePostInstallSupplyChainCheck.js +89 -0
  54. package/lib/checks/impl/PlatformEventSubscriberContextCheck.d.ts +10 -0
  55. package/lib/checks/impl/PlatformEventSubscriberContextCheck.js +84 -0
  56. package/lib/checks/impl/RestrictionRulesIntegrityCheck.d.ts +10 -0
  57. package/lib/checks/impl/RestrictionRulesIntegrityCheck.js +105 -0
  58. package/lib/checks/impl/ShieldTenantSecretLifecycleCheck.d.ts +10 -0
  59. package/lib/checks/impl/ShieldTenantSecretLifecycleCheck.js +90 -0
  60. package/lib/checks/registry.js +34 -0
  61. package/lib/checks/support/agentGraph.d.ts +49 -0
  62. package/lib/checks/support/agentGraph.js +87 -0
  63. package/lib/checks/support/apexAccess.d.ts +56 -0
  64. package/lib/checks/support/apexAccess.js +127 -0
  65. package/lib/checks/support/missingObject.d.ts +13 -0
  66. package/lib/checks/support/missingObject.js +35 -0
  67. package/lib/commands/audit/apps.d.ts +1 -0
  68. package/lib/commands/audit/apps.js +83 -29
  69. package/lib/commands/audit/diff.js +2 -2
  70. package/lib/commands/audit/history.js +2 -2
  71. package/lib/commands/audit/incident/report.js +2 -2
  72. package/lib/commands/audit/security.d.ts +3 -0
  73. package/lib/commands/audit/security.js +58 -9
  74. package/lib/commands/audit/timeline.js +2 -2
  75. package/lib/compliance/mapping.js +35 -7
  76. package/lib/findings/AuditResult.d.ts +8 -0
  77. package/lib/findings/CheckMeta.js +17 -0
  78. package/lib/findings/Finding.d.ts +4 -0
  79. package/lib/findings/ScoringConfig.d.ts +10 -8
  80. package/lib/findings/ScoringConfig.js +12 -5
  81. package/lib/findings/coverage.d.ts +28 -0
  82. package/lib/findings/coverage.js +30 -0
  83. package/lib/findings/exitCode.js +1 -1
  84. package/lib/findings/loadScoringConfig.js +51 -8
  85. package/lib/findings/scoring.js +14 -5
  86. package/lib/history/HistoryStore.js +9 -3
  87. package/lib/history/archivePolicy.d.ts +19 -0
  88. package/lib/history/archivePolicy.js +34 -0
  89. package/lib/incident/bundleIo.js +4 -3
  90. package/lib/incident/collect/collectBundle.d.ts +1 -1
  91. package/lib/incident/collect/collectBundle.js +4 -3
  92. package/lib/incident/collect/streamGuestLogs.d.ts +1 -1
  93. package/lib/incident/collect/streamGuestLogs.js +3 -2
  94. package/lib/incident/csv.js +4 -4
  95. package/lib/incident/render/evidence.js +3 -3
  96. package/lib/incident/render/html.js +2 -3
  97. package/lib/index.d.ts +2 -0
  98. package/lib/index.js +2 -0
  99. package/lib/lib/packageInfo.d.ts +6 -0
  100. package/lib/lib/packageInfo.js +19 -0
  101. package/lib/renderers/AttackChainDagRenderer.d.ts +7 -0
  102. package/lib/renderers/AttackChainDagRenderer.js +139 -0
  103. package/lib/renderers/ClientReportRenderer.d.ts +2 -0
  104. package/lib/renderers/ClientReportRenderer.js +34 -6
  105. package/lib/renderers/DiffHtmlRenderer.js +2 -7
  106. package/lib/renderers/HistoryRenderer.js +19 -11
  107. package/lib/renderers/HtmlRenderer.js +19 -6
  108. package/lib/renderers/MarkdownRenderer.js +7 -0
  109. package/lib/renderers/SarifRenderer.d.ts +43 -0
  110. package/lib/renderers/SarifRenderer.js +250 -0
  111. package/lib/report/ExecutivePriorities.js +1 -1
  112. package/lib/report/RemediationRoadmap.js +1 -1
  113. package/lib/waivers/WaiverLoader.d.ts +28 -0
  114. package/lib/waivers/WaiverLoader.js +103 -0
  115. package/lib/waivers/WaiverModel.d.ts +32 -0
  116. package/lib/waivers/WaiverModel.js +28 -0
  117. package/lib/waivers/applyWaivers.d.ts +22 -0
  118. package/lib/waivers/applyWaivers.js +85 -0
  119. package/package.json +3 -3
@@ -1,10 +1,12 @@
1
- import { esc } from '@cclabsnz/sf-core';
1
+ import { esc, STRICT_CSP_META } from '@cclabsnz/sf-core';
2
2
  import { fontFaceCss } from '@cclabsnz/sf-core';
3
3
  import { getCheckMeta } from '../findings/CheckMeta.js';
4
4
  import { toolCreditHtml } from './toolCredit.js';
5
5
  import { selectPriorities } from '../report/ExecutivePriorities.js';
6
6
  import { buildRoadmap } from '../report/RemediationRoadmap.js';
7
7
  import { buildComplianceMatrix } from '../report/ComplianceMatrix.js';
8
+ import { renderAttackChainDagSvg } from './AttackChainDagRenderer.js';
9
+ import { coverageSummary } from '../findings/coverage.js';
8
10
  const SEV_COLOR = {
9
11
  CRITICAL: '#7d3a3a', HIGH: '#a35a2a', MEDIUM: '#8a6d1f', LOW: '#3a5a82', INFO: '#636770',
10
12
  };
@@ -42,12 +44,13 @@ export class ClientReportRenderer {
42
44
  this.summary(result, num()),
43
45
  this.prioritiesSection(priorities, chainIds, num()),
44
46
  chains.length ? this.scenarios(chains, num()) : '',
47
+ result.waivedFindings?.length ? this.waiversSection(result.waivedFindings, num()) : '',
45
48
  this.roadmapSection(roadmap, num()),
46
49
  matrix.length ? this.matrixSection(matrix, num()) : '',
47
50
  this.findingsAppendix(result, num()),
48
51
  ].join('\n');
49
52
  return `<!DOCTYPE html>
50
- <html lang="en"><head><meta charset="utf-8"><title>Security Audit: ${esc(result.orgName)}</title>
53
+ <html lang="en"><head><meta charset="utf-8">${STRICT_CSP_META}<title>Security Audit: ${esc(result.orgName)}</title>
51
54
  <style>${fontFaceCss()}
52
55
  :root{--ink:${b.ink};--bg:${b.bg};--bgalt:${b.bgAlt};--muted:${b.muted};--border:${b.border};--primary:${b.primary};
53
56
  --display:'${b.fontDisplay}',Georgia,serif;--body:'${b.fontBody}',system-ui,sans-serif;--mono:ui-monospace,'SF Mono',Menlo,monospace;}
@@ -137,9 +140,11 @@ ${this.footer(b)}
137
140
  }
138
141
  summary(r, numStr) {
139
142
  const incon = r.findings.filter((f) => f.inconclusive).length;
140
- const active = r.findings.filter((f) => !f.passed && !f.inconclusive).length;
143
+ const active = r.findings.filter((f) => !f.passed && !f.inconclusive && !f.waived).length;
144
+ const waived = r.findings.filter((f) => f.waived).length;
145
+ const waivedNote = waived ? `, with ${waived} waived as accepted risk` : '';
141
146
  return `${this.sectionHead(numStr, 'Executive Summary')}
142
- <p>This audit assessed the org’s security configuration and scored it <strong>${r.healthScore}/100 (Grade ${esc(r.grade)})</strong> across ${active} active finding${active === 1 ? '' : 's'}${incon ? `, with ${incon} inconclusive (insufficient access)` : ''}. The priorities below are the highest-impact items to address first; the remediation roadmap groups every fix by effort. See Scope &amp; Liability for the basis and limits of this assessment.</p>`;
147
+ <p>This audit assessed the org’s security configuration and scored it <strong>${r.healthScore}/100 (Grade ${esc(r.grade)})</strong> across ${active} active finding${active === 1 ? '' : 's'}${incon ? `, with ${incon} inconclusive (insufficient access)` : ''}${waivedNote}. The priorities below are the highest-impact items to address first; the remediation roadmap groups every fix by effort. See Scope &amp; Liability for the basis and limits of this assessment.</p>${this.coverageNote(r)}`;
143
148
  }
144
149
  prioritiesSection(priorities, chainIds, numStr) {
145
150
  const head = this.sectionHead(numStr, 'Executive Priorities');
@@ -155,10 +160,33 @@ ${impact}${chained}<p><strong>Fix:</strong> ${esc(f.remediation)}</p></div>`;
155
160
  }).join('');
156
161
  return `${head}<p class="muted">Focus areas, highest impact first.</p>${items}`;
157
162
  }
163
+ coverageNote(r) {
164
+ const c = r.coverage;
165
+ if (!c || c.notAssessed.length === 0)
166
+ return '';
167
+ return `<p class="muted">${esc(coverageSummary(c))}. The checks that gathered no evidence are listed as inconclusive in the findings appendix; their areas are unassessed, not clean.</p>`;
168
+ }
169
+ waiversSection(waived, numStr) {
170
+ const items = waived
171
+ .map((f) => {
172
+ // The approval (reason, approver, expiry) is on each item's note, or on the detail when the finding has no items.
173
+ const scope = f.affectedItems?.length ? f.affectedItems.map((i) => (i.note ? `${i.label} ${i.note}` : i.label)).join('; ') : f.id;
174
+ return `<div class="card" style="--c:#16a34a">
175
+ <div class="row"><h3>${esc(f.title)}</h3>${this.chip('INFO', 'WAIVED')}</div>
176
+ <p><strong>Scope:</strong> ${esc(scope)}</p><p>${esc(f.detail)}</p></div>`;
177
+ })
178
+ .join('');
179
+ return `${this.sectionHead(numStr, 'Accepted Risks')}<p class="muted">Findings covered by an approved, unexpired waiver. They are excluded from the score and from the priorities above, and still count toward the attack scenarios.</p>${items}`;
180
+ }
158
181
  scenarios(chains, numStr) {
159
- const items = chains.map((c) => `<div class="card scenario" style="--c:${SEV_COLOR[c.severity]}">
182
+ const items = chains.map((c) => {
183
+ const dagSvg = renderAttackChainDagSvg(c, { theme: 'light' });
184
+ return `<div class="card scenario" style="--c:${SEV_COLOR[c.severity]}">
160
185
  <div class="row"><h3>${esc(c.title)}</h3>${this.chip(c.severity, c.severity)}</div>
161
- <p>${esc(c.narrative)}</p><p><strong>Breaks the chain:</strong> ${esc(c.remediation)}</p></div>`).join('');
186
+ <p>${esc(c.narrative)}</p>
187
+ ${dagSvg}
188
+ <p><strong>Breaks the chain:</strong> ${esc(c.remediation)}</p></div>`;
189
+ }).join('');
162
190
  return `${this.sectionHead(numStr, 'Attack Scenarios')}<p class="muted">How findings combine into real attack paths.</p>${items}`;
163
191
  }
164
192
  roadmapSection(roadmap, numStr) {
@@ -1,10 +1,4 @@
1
- function esc(str) {
2
- return str
3
- .replace(/&/g, '&amp;')
4
- .replace(/</g, '&lt;')
5
- .replace(/>/g, '&gt;')
6
- .replace(/"/g, '&quot;');
7
- }
1
+ import { esc, INTERACTIVE_CSP_META } from '@cclabsnz/sf-core';
8
2
  function fmtDate(d) {
9
3
  return d.toISOString().replace('T', ' ').substring(0, 16);
10
4
  }
@@ -83,6 +77,7 @@ export class DiffHtmlRenderer {
83
77
  <html lang="en">
84
78
  <head>
85
79
  <meta charset="UTF-8">
80
+ ${INTERACTIVE_CSP_META}
86
81
  <meta name="viewport" content="width=device-width,initial-scale=1">
87
82
  <title>SF Audit Diff: ${esc(baseline.orgName)}</title>
88
83
  <style>
@@ -1,3 +1,4 @@
1
+ import { esc, INTERACTIVE_CSP_META } from '@cclabsnz/sf-core';
1
2
  import { chartJsScript } from './chartAsset.js';
2
3
  function fmtDate(d) {
3
4
  return d.toISOString().replace('T', ' ').substring(0, 16);
@@ -38,21 +39,23 @@ export class HistoryRenderer {
38
39
  return '<!DOCTYPE html><html><body><p>No audit history found.</p></body></html>';
39
40
  const orgName = results[0].orgName;
40
41
  const orgId = results[0].orgId;
41
- const labels = JSON.stringify(results.map((r) => fmtDate(r.generatedAt)));
42
- const scores = JSON.stringify(results.map((r) => r.healthScore));
43
- const crits = JSON.stringify(results.map((r) => countBySeverity(r, 'CRITICAL')));
44
- const highs = JSON.stringify(results.map((r) => countBySeverity(r, 'HIGH')));
45
- const meds = JSON.stringify(results.map((r) => countBySeverity(r, 'MEDIUM')));
46
- const lows = JSON.stringify(results.map((r) => countBySeverity(r, 'LOW')));
42
+ // History is read back from files on disk, so nothing in it is trusted: scores are coerced to
43
+ // numbers, and JSON embedded in the inline <script> cannot close the script element.
44
+ const labels = scriptJson(results.map((r) => fmtDate(r.generatedAt)));
45
+ const scores = scriptJson(results.map((r) => Number(r.healthScore)));
46
+ const crits = scriptJson(results.map((r) => countBySeverity(r, 'CRITICAL')));
47
+ const highs = scriptJson(results.map((r) => countBySeverity(r, 'HIGH')));
48
+ const meds = scriptJson(results.map((r) => countBySeverity(r, 'MEDIUM')));
49
+ const lows = scriptJson(results.map((r) => countBySeverity(r, 'LOW')));
47
50
  const tableRows = results.map((r, i) => {
48
51
  const prev = i > 0 ? results[i - 1] : null;
49
52
  const delta = prev ? (r.healthScore - prev.healthScore >= 0 ? `+${r.healthScore - prev.healthScore}` : `${r.healthScore - prev.healthScore}`) : '—';
50
53
  const deltaColor = prev ? (r.healthScore >= prev.healthScore ? '#22c55e' : '#dc2626') : '#8b949e';
51
54
  return `<tr>
52
55
  <td>${i + 1}</td>
53
- <td>${fmtDate(r.generatedAt)}</td>
54
- <td style="text-align:right;font-weight:700">${r.healthScore}</td>
55
- <td style="text-align:center">${r.grade}</td>
56
+ <td>${esc(fmtDate(r.generatedAt))}</td>
57
+ <td style="text-align:right;font-weight:700">${Number(r.healthScore)}</td>
58
+ <td style="text-align:center">${esc(r.grade)}</td>
56
59
  <td style="text-align:right;color:#dc2626">${countBySeverity(r, 'CRITICAL')}</td>
57
60
  <td style="text-align:right;color:#ea580c">${countBySeverity(r, 'HIGH')}</td>
58
61
  <td style="text-align:right;color:#d97706">${countBySeverity(r, 'MEDIUM')}</td>
@@ -64,8 +67,9 @@ export class HistoryRenderer {
64
67
  <html lang="en">
65
68
  <head>
66
69
  <meta charset="UTF-8">
70
+ ${INTERACTIVE_CSP_META}
67
71
  <meta name="viewport" content="width=device-width,initial-scale=1">
68
- <title>SF Audit History: ${orgName}</title>
72
+ <title>SF Audit History: ${esc(orgName)}</title>
69
73
  <script>${chartJsScript()}</script>
70
74
  <style>
71
75
  *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
@@ -85,7 +89,7 @@ export class HistoryRenderer {
85
89
  </head>
86
90
  <body>
87
91
  <h1>Salesforce Audit History</h1>
88
- <div class="meta">Org: <strong style="color:#c9d1d9">${orgName}</strong> (${orgId})</div>
92
+ <div class="meta">Org: <strong style="color:#c9d1d9">${esc(orgName)}</strong> (${esc(orgId)})</div>
89
93
 
90
94
  <div class="charts">
91
95
  <div class="chart-box">
@@ -138,4 +142,8 @@ new Chart(document.getElementById('findingsChart'), {
138
142
  </html>`;
139
143
  }
140
144
  }
145
+ /** JSON safe to place inside an inline <script>: `<` is escaped so no value can end the element. */
146
+ function scriptJson(value) {
147
+ return JSON.stringify(value).replace(/</g, '\\u003c');
148
+ }
141
149
  //# sourceMappingURL=HistoryRenderer.js.map
@@ -1,4 +1,6 @@
1
- import { esc, firaFontFaceCss } from '@cclabsnz/sf-core';
1
+ import { esc, firaFontFaceCss, INTERACTIVE_CSP_META } from '@cclabsnz/sf-core';
2
+ import { renderAttackChainDagSvg } from './AttackChainDagRenderer.js';
3
+ import { coverageSummary } from '../findings/coverage.js';
2
4
  const RISK_COLORS = {
3
5
  CRITICAL: '#dc2626',
4
6
  HIGH: '#ea580c',
@@ -123,13 +125,22 @@ function buildDashboard(result, counts) {
123
125
  metricRow('Failed Logins (30d)', m.failedLogins30d, failedColor),
124
126
  metricRow('SF Health Check', `${m.healthCheckScore}%`, healthChkColor, progressBar(m.healthCheckScore, 100, healthChkColor)),
125
127
  ]);
128
+ const waivedBanner = result.waivedFindings?.length
129
+ ? `<div class="waived-banner" style="background:#0f291e;border:1px solid #16a34a;border-radius:8px;padding:12px 16px;margin-bottom:20px;color:#dcfce7;font-size:13px;"><strong>Accepted risks:</strong> ${result.waivedFindings.length} finding(s) waived under an approved waiver and excluded from the score.</div>`
130
+ : '';
131
+ const cov = result.coverage;
132
+ const coverageLine = cov
133
+ ? `<div class="coverage${cov.gradeCapped ? ' is-capped' : ''}" style="margin-top:10px;font-size:12px;color:${cov.gradeCapped ? '#fbbf24' : '#94a3b8'}">${esc(coverageSummary(cov))}${cov.notAssessed.length ? `<br>Not assessed: ${cov.notAssessed.map((id) => `<code>${esc(id)}</code>`).join(', ')}` : ''}</div>`
134
+ : '';
126
135
  return `
136
+ ${waivedBanner}
127
137
  <div class="dashboard">
128
138
  <div class="dash-top">
129
139
  <div class="dash-score-panel">
130
140
  <div class="gauge-wrap">
131
141
  ${gauge}
132
142
  </div>
143
+ ${coverageLine}
133
144
  </div>
134
145
  <div class="dash-risk-panel">
135
146
  <div class="donut-wrap">
@@ -160,18 +171,19 @@ export class HtmlRenderer {
160
171
  renderAttackPaths(result) {
161
172
  if (!result.attackChains || result.attackChains.length === 0)
162
173
  return '';
163
- const escStr = (s) => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
164
174
  const cards = result.attackChains
165
175
  .map((c) => {
166
176
  const conf = c.confidence === 'named' ? '' : ' (potential)';
177
+ const dagSvg = renderAttackChainDagSvg(c, { theme: 'dark' });
167
178
  const steps = c.steps
168
- .map((s) => `<li><strong>${escStr(s.title ?? s.findingId)}</strong> (${escStr(s.severity ?? '—')}): grants <code>${escStr(s.capability)}</code></li>`)
179
+ .map((s) => `<li><strong>${esc(s.title ?? s.findingId)}</strong> (${esc(s.severity ?? '—')}): grants <code>${esc(s.capability)}</code></li>`)
169
180
  .join('');
170
181
  return `<div class="attack-chain severity-${c.severity.toLowerCase()}">
171
- <h3>[${escStr(c.severity)}] ${escStr(c.title)}${conf}</h3>
172
- <p>${escStr(c.narrative)}</p>
182
+ <h3>[${esc(c.severity)}] ${esc(c.title)}${conf}</h3>
183
+ <p>${esc(c.narrative)}</p>
184
+ ${dagSvg}
173
185
  <ol>${steps}</ol>
174
- <p class="remediation"><strong>Remediation:</strong> ${escStr(c.remediation)}</p>
186
+ <p class="remediation"><strong>Remediation:</strong> ${esc(c.remediation)}</p>
175
187
  </div>`;
176
188
  })
177
189
  .join('\n');
@@ -240,6 +252,7 @@ export class HtmlRenderer {
240
252
  <html lang="en">
241
253
  <head>
242
254
  <meta charset="UTF-8">
255
+ ${INTERACTIVE_CSP_META}
243
256
  <meta name="viewport" content="width=device-width,initial-scale=1">
244
257
  <title>SF Security Audit: ${esc(result.orgName)}</title>
245
258
  <style>
@@ -1,3 +1,4 @@
1
+ import { coverageSummary } from '../findings/coverage.js';
1
2
  function escapeMdCell(s) {
2
3
  return s.replace(/\\/g, '\\\\').replace(/\|/g, '\\|').replace(/\n/g, ' ');
3
4
  }
@@ -11,6 +12,12 @@ export class MarkdownRenderer {
11
12
  lines.push(`**Generated:** ${result.generatedAt.toISOString()}`);
12
13
  lines.push(`**Instance:** ${result.instance} | **Type:** ${result.orgType}${result.isSandbox ? ' (Sandbox)' : ''}`);
13
14
  lines.push(`**Health Score:** ${result.healthScore}/100 | **Grade:** ${result.grade}`);
15
+ if (result.coverage) {
16
+ lines.push('');
17
+ lines.push(`**${coverageSummary(result.coverage)}**`);
18
+ if (result.coverage.notAssessed.length > 0)
19
+ lines.push(`Not assessed: ${result.coverage.notAssessed.map((id) => `\`${id}\``).join(', ')}`);
20
+ }
14
21
  lines.push('');
15
22
  if (result.attackChains && result.attackChains.length > 0) {
16
23
  lines.push(`## Attack Paths (${result.attackChains.length})`);
@@ -0,0 +1,43 @@
1
+ import type { RiskLevel } from '@cclabsnz/sf-core';
2
+ import type { AuditResult } from '../findings/AuditResult.js';
3
+ import type { AuditRenderer } from './AuditRenderer.js';
4
+ /**
5
+ * SARIF 2.1.0 output, for GitHub code scanning and other SARIF consumers.
6
+ *
7
+ * The audit inspects an org's configuration, not files, so there is no real source location.
8
+ * Each result carries:
9
+ * - a logical location per affected item (the actual subject of the finding), and
10
+ * - a synthetic physical location, `salesforce-org/<ruleId>`, because GitHub code scanning
11
+ * only displays results that have a physicalLocation with an artifactLocation.uri. The
12
+ * file does not exist in the repository; it groups alerts by check in the UI.
13
+ *
14
+ * Results carry a `partialFingerprints` entry derived from the rule id and the finding id, so
15
+ * the same finding on the next run updates the existing alert instead of opening a new one.
16
+ * Finding ids are stable per subject (checks embed the user / domain / component they are
17
+ * about), whereas affected-item lists change size between runs.
18
+ *
19
+ * Only actionable findings become results. Passing checks are omitted, and inconclusive
20
+ * checks (no evidence, usually a missing permission) are reported as tool execution
21
+ * notifications with `executionSuccessful: false`, never as error/warning alerts.
22
+ */
23
+ export type SarifLevel = 'error' | 'warning' | 'note' | 'none';
24
+ /** Fingerprint key. Bump the version suffix if the hashed inputs ever change. */
25
+ export declare const FINGERPRINT_KEY = "sfAuditFindingHash/v1";
26
+ /** Root of the synthetic artifact path every result points at. */
27
+ export declare const ORG_ARTIFACT_ROOT = "salesforce-org";
28
+ export declare function riskToSarifLevel(level: RiskLevel): SarifLevel;
29
+ export declare class SarifRenderer implements AuditRenderer {
30
+ readonly format = "sarif";
31
+ readonly fileExtension = ".sarif";
32
+ readonly filenamePrefix = "sf-audit";
33
+ render(result: AuditResult): string;
34
+ private ruleFor;
35
+ /**
36
+ * One SARIF result per actionable finding. Accepted-risk waivers, when they land, attach
37
+ * here as `suppressions` (SARIF 3.27.23) rather than by dropping the result, so consumers
38
+ * can still see the finding and that it was waived.
39
+ */
40
+ private findingResult;
41
+ private chainResult;
42
+ }
43
+ //# sourceMappingURL=SarifRenderer.d.ts.map
@@ -0,0 +1,250 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { CHECKS } from '../checks/registry.js';
3
+ import { packageInfo } from '../lib/packageInfo.js';
4
+ /** Fingerprint key. Bump the version suffix if the hashed inputs ever change. */
5
+ export const FINGERPRINT_KEY = 'sfAuditFindingHash/v1';
6
+ /** Root of the synthetic artifact path every result points at. */
7
+ export const ORG_ARTIFACT_ROOT = 'salesforce-org';
8
+ const SEVERITY_ORDER = ['INFO', 'LOW', 'MEDIUM', 'HIGH', 'CRITICAL'];
9
+ export function riskToSarifLevel(level) {
10
+ switch (level) {
11
+ case 'CRITICAL':
12
+ case 'HIGH':
13
+ return 'error';
14
+ case 'MEDIUM':
15
+ return 'warning';
16
+ case 'LOW':
17
+ case 'INFO':
18
+ return 'note';
19
+ }
20
+ }
21
+ /**
22
+ * GitHub's `security-severity` bands: >= 9.0 critical, 7.0-8.9 high, 4.0-6.9 medium,
23
+ * 0.1-3.9 low. Values sit inside each band rather than on its edge. INFO has none, so an
24
+ * advisory-only rule falls back to its `note` level instead of claiming a security severity.
25
+ */
26
+ function riskToSecuritySeverity(level) {
27
+ switch (level) {
28
+ case 'CRITICAL':
29
+ return '9.5';
30
+ case 'HIGH':
31
+ return '8.0';
32
+ case 'MEDIUM':
33
+ return '5.5';
34
+ case 'LOW':
35
+ return '3.0';
36
+ case 'INFO':
37
+ return undefined;
38
+ }
39
+ }
40
+ function maxRisk(a, b) {
41
+ return SEVERITY_ORDER.indexOf(a) >= SEVERITY_ORDER.indexOf(b) ? a : b;
42
+ }
43
+ function fingerprint(...parts) {
44
+ return createHash('sha256').update(parts.join('\u0000')).digest('hex');
45
+ }
46
+ /** Logical locations for the given names. SARIF requires the array's items to be unique. */
47
+ function logicalLocations(names) {
48
+ return [...new Set(names)].map((name) => ({ name, fullyQualifiedName: name, kind: 'resource' }));
49
+ }
50
+ /** The location every result points at: a synthetic per-rule artifact, plus the logical subjects. */
51
+ function orgLocation(ruleId, names) {
52
+ const logical = logicalLocations(names);
53
+ return {
54
+ physicalLocation: {
55
+ artifactLocation: { uri: `${ORG_ARTIFACT_ROOT}/${encodeURIComponent(ruleId)}` },
56
+ region: { startLine: 1 },
57
+ },
58
+ ...(logical.length > 0 ? { logicalLocations: logical } : {}),
59
+ };
60
+ }
61
+ function ruleName(text) {
62
+ return text.replace(/[^a-zA-Z0-9]/g, '');
63
+ }
64
+ export class SarifRenderer {
65
+ format = 'sarif';
66
+ fileExtension = '.sarif';
67
+ filenamePrefix = 'sf-audit';
68
+ render(result) {
69
+ const pkg = packageInfo();
70
+ const rules = new Map();
71
+ for (const check of CHECKS) {
72
+ rules.set(check.id, {
73
+ rule: {
74
+ id: check.id,
75
+ name: ruleName(check.name),
76
+ shortDescription: { text: check.name },
77
+ fullDescription: { text: `${check.name} (${check.category})` },
78
+ help: {
79
+ text: `Each result for ${check.id} carries its own remediation.`,
80
+ markdown: `Each result for \`${check.id}\` carries its own remediation.\n\n**Category**: \`${check.category}\``,
81
+ },
82
+ defaultConfiguration: { level: 'warning' },
83
+ properties: { tags: ['security', 'salesforce', check.category] },
84
+ },
85
+ });
86
+ }
87
+ const results = [];
88
+ const notifications = [];
89
+ const seen = new Map();
90
+ for (const f of result.findings) {
91
+ if (f.passed === true)
92
+ continue;
93
+ const ruleId = f.checkId ?? f.id;
94
+ if (f.inconclusive === true) {
95
+ notifications.push({
96
+ level: 'warning',
97
+ message: { text: `${f.title}: ${f.detail}` },
98
+ associatedRule: { id: ruleId },
99
+ });
100
+ continue;
101
+ }
102
+ const acc = this.ruleFor(rules, ruleId, f);
103
+ acc.worst = acc.worst ? maxRisk(acc.worst, f.riskLevel) : f.riskLevel;
104
+ for (const tag of f.complianceTags ?? []) {
105
+ if (!acc.rule.properties.tags.includes(tag))
106
+ acc.rule.properties.tags.push(tag);
107
+ }
108
+ // Two findings sharing an id within one run would otherwise collapse into one alert.
109
+ const key = `${ruleId}\u0000${f.id}`;
110
+ const n = seen.get(key) ?? 0;
111
+ seen.set(key, n + 1);
112
+ results.push(this.findingResult(f, ruleId, n === 0 ? fingerprint(ruleId, f.id) : fingerprint(ruleId, f.id, String(n))));
113
+ }
114
+ for (const chain of result.attackChains ?? []) {
115
+ results.push(this.chainResult(rules, chain));
116
+ }
117
+ for (const acc of rules.values()) {
118
+ if (!acc.worst)
119
+ continue;
120
+ acc.rule.defaultConfiguration.level = riskToSarifLevel(acc.worst);
121
+ const sev = riskToSecuritySeverity(acc.worst);
122
+ if (sev)
123
+ acc.rule.properties['security-severity'] = sev;
124
+ }
125
+ const sarifLog = {
126
+ $schema: 'https://raw.githubusercontent.com/oasis-tcs/sarif-spec/master/Schemata/sarif-schema-2.1.0.json',
127
+ version: '2.1.0',
128
+ runs: [
129
+ {
130
+ tool: {
131
+ driver: {
132
+ name: pkg.name,
133
+ version: pkg.version,
134
+ informationUri: 'https://github.com/cclabsnz/sf-audit-plugin',
135
+ rules: Array.from(rules.values(), (a) => a.rule),
136
+ },
137
+ },
138
+ // One category per org. GitHub code scanning closes any alert of a category that a new
139
+ // upload no longer contains, so two orgs sharing a category would close each other's.
140
+ automationDetails: { id: `sf-audit/${result.orgId}/` },
141
+ results,
142
+ invocations: [
143
+ {
144
+ // An inconclusive check is a partial analysis failure: the tool ran, but could
145
+ // not establish the answer for that check.
146
+ executionSuccessful: notifications.length === 0,
147
+ endTimeUtc: result.generatedAt.toISOString(),
148
+ toolExecutionNotifications: notifications,
149
+ },
150
+ ],
151
+ properties: {
152
+ orgId: result.orgId,
153
+ orgName: result.orgName,
154
+ healthScore: result.healthScore,
155
+ grade: result.grade,
156
+ },
157
+ },
158
+ ],
159
+ };
160
+ return JSON.stringify(sarifLog, null, 2);
161
+ }
162
+ ruleFor(rules, ruleId, f) {
163
+ let acc = rules.get(ruleId);
164
+ if (!acc) {
165
+ acc = {
166
+ rule: {
167
+ id: ruleId,
168
+ name: ruleName(ruleId),
169
+ shortDescription: { text: f.title },
170
+ fullDescription: { text: f.title },
171
+ help: { text: f.remediation, markdown: `### Remediation\n\n${f.remediation}` },
172
+ defaultConfiguration: { level: 'warning' },
173
+ properties: { tags: ['security', 'salesforce', f.category] },
174
+ },
175
+ };
176
+ rules.set(ruleId, acc);
177
+ }
178
+ return acc;
179
+ }
180
+ /**
181
+ * One SARIF result per actionable finding. Accepted-risk waivers, when they land, attach
182
+ * here as `suppressions` (SARIF 3.27.23) rather than by dropping the result, so consumers
183
+ * can still see the finding and that it was waived.
184
+ */
185
+ findingResult(f, ruleId, hash) {
186
+ const items = f.affectedItems ?? [];
187
+ return {
188
+ ruleId,
189
+ level: riskToSarifLevel(f.riskLevel),
190
+ message: { text: `${f.title}\n\n${f.detail}\n\nRemediation: ${f.remediation}` },
191
+ locations: [orgLocation(ruleId, items.map((i) => i.label))],
192
+ partialFingerprints: { [FINGERPRINT_KEY]: hash },
193
+ properties: {
194
+ findingId: f.id,
195
+ riskLevel: f.riskLevel,
196
+ category: f.category,
197
+ remediation: f.remediation,
198
+ complianceTags: f.complianceTags ?? [],
199
+ affectedItems: items.map((i) => ({ label: i.label, ...(i.note ? { note: i.note } : {}) })),
200
+ },
201
+ };
202
+ }
203
+ chainResult(rules, chain) {
204
+ const ruleId = `attack-chain-${chain.id}`;
205
+ let acc = rules.get(ruleId);
206
+ if (!acc) {
207
+ acc = {
208
+ rule: {
209
+ id: ruleId,
210
+ name: ruleName(chain.title),
211
+ shortDescription: { text: chain.title },
212
+ fullDescription: { text: chain.narrative },
213
+ help: {
214
+ text: chain.remediation,
215
+ markdown: `### Attack chain\n\n${chain.narrative}\n\n### Remediation\n\n${chain.remediation}`,
216
+ },
217
+ defaultConfiguration: { level: 'error' },
218
+ properties: { tags: ['security', 'salesforce', 'attack-chain'] },
219
+ },
220
+ };
221
+ rules.set(ruleId, acc);
222
+ }
223
+ acc.worst = acc.worst ? maxRisk(acc.worst, chain.severity) : chain.severity;
224
+ const stepLocation = (step, idx) => ({
225
+ message: { text: `Step ${idx + 1}: ${step.title ?? step.findingId} (${step.findingId})` },
226
+ logicalLocations: logicalLocations([step.findingId]),
227
+ properties: { capability: step.capability },
228
+ });
229
+ return {
230
+ ruleId,
231
+ level: riskToSarifLevel(chain.severity),
232
+ message: { text: `[Attack chain] ${chain.title}: ${chain.narrative}` },
233
+ locations: [orgLocation(ruleId, chain.steps.map((s) => s.findingId))],
234
+ codeFlows: [
235
+ {
236
+ message: { text: chain.title },
237
+ threadFlows: [{ locations: chain.steps.map((s, i) => ({ location: stepLocation(s, i) })) }],
238
+ },
239
+ ],
240
+ partialFingerprints: { [FINGERPRINT_KEY]: fingerprint(ruleId, chain.id) },
241
+ properties: {
242
+ riskLevel: chain.severity,
243
+ confidence: chain.confidence,
244
+ attackChainId: chain.id,
245
+ remediation: chain.remediation,
246
+ },
247
+ };
248
+ }
249
+ }
250
+ //# sourceMappingURL=SarifRenderer.js.map
@@ -6,7 +6,7 @@ const RANK = { CRITICAL: 0, HIGH: 1, MEDIUM: 2, LOW: 3, INFO: 4 };
6
6
  */
7
7
  export function selectPriorities(findings, chainFindingIds, topN) {
8
8
  return findings
9
- .filter((f) => !f.passed && !f.inconclusive)
9
+ .filter((f) => !f.passed && !f.inconclusive && !f.waived)
10
10
  .slice()
11
11
  .sort((a, b) => {
12
12
  if (RANK[a.riskLevel] !== RANK[b.riskLevel])
@@ -4,7 +4,7 @@ const RANK = { CRITICAL: 0, HIGH: 1, MEDIUM: 2, LOW: 3, INFO: 4 };
4
4
  export function buildRoadmap(findings) {
5
5
  const out = { quick: [], moderate: [], project: [] };
6
6
  for (const f of findings) {
7
- if (f.passed || f.inconclusive)
7
+ if (f.passed || f.inconclusive || f.waived)
8
8
  continue;
9
9
  const effort = (f.checkId && getCheckMeta(f.checkId)?.effort) || 'moderate';
10
10
  out[effort].push(f);
@@ -0,0 +1,28 @@
1
+ import { type EvaluatedWaiver, type WaiverEntry } from './WaiverModel.js';
2
+ /** The only file picked up without --waivers. Its path is always reported, so a waiver is never silent. */
3
+ export declare const DEFAULT_WAIVER_FILE = ".sfaudit-waivers.json";
4
+ export declare class WaiverLoader {
5
+ readonly source?: string | undefined;
6
+ private readonly evaluatedWaivers;
7
+ /**
8
+ * @param source the file the waivers came from, or undefined when none was loaded. Reported to
9
+ * the user so a waiver file picked up from the working directory is never applied silently.
10
+ */
11
+ constructor(waivers: WaiverEntry[], now?: Date, source?: string | undefined);
12
+ get waivers(): readonly EvaluatedWaiver[];
13
+ get activeWaivers(): EvaluatedWaiver[];
14
+ get expiredWaivers(): EvaluatedWaiver[];
15
+ /**
16
+ * The waiver covering one entity of one finding, preferring an active waiver over an expired
17
+ * one. Matching is exact (case- and whitespace-insensitive): the entity must equal an affected
18
+ * item's label, or, for a finding with no affected items, the finding id itself. There are no
19
+ * wildcards or partial matches, so a waiver can never cover more than the entity it names.
20
+ */
21
+ findMatchingWaiver(checkId: string, findingId: string, entityName: string): EvaluatedWaiver | undefined;
22
+ /**
23
+ * Loads waivers from an explicit path, or from `.sfaudit-waivers.json` in the working directory.
24
+ * Rejects any waiver that runs longer than MAX_WAIVER_DAYS from `now`.
25
+ */
26
+ static load(explicitPath?: string, now?: Date): WaiverLoader;
27
+ }
28
+ //# sourceMappingURL=WaiverLoader.d.ts.map