@cclabsnz/sf-audit 1.16.0 → 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 (112) hide show
  1. package/CHANGELOG.md +118 -1
  2. package/README.md +94 -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 +95 -7
  19. package/lib/checks/CheckEngine.d.ts +3 -1
  20. package/lib/checks/CheckEngine.js +11 -3
  21. package/lib/checks/impl/ApexCrudFLSCheck.js +45 -10
  22. package/lib/checks/impl/ApexSharingCheck.js +16 -25
  23. package/lib/checks/impl/AuthProviderRegistrationHandlerCheck.d.ts +10 -0
  24. package/lib/checks/impl/AuthProviderRegistrationHandlerCheck.js +131 -0
  25. package/lib/checks/impl/ConnectedAppsCheck.js +47 -1
  26. package/lib/checks/impl/DataCloudDataSpaceIsolationCheck.d.ts +10 -0
  27. package/lib/checks/impl/DataCloudDataSpaceIsolationCheck.js +116 -0
  28. package/lib/checks/impl/DelegatedAdministrationGroupsCheck.d.ts +10 -0
  29. package/lib/checks/impl/DelegatedAdministrationGroupsCheck.js +75 -0
  30. package/lib/checks/impl/DelegatedAuthenticationExposureCheck.d.ts +10 -0
  31. package/lib/checks/impl/DelegatedAuthenticationExposureCheck.js +98 -0
  32. package/lib/checks/impl/ExternalAccountHierarchyExposureCheck.d.ts +10 -0
  33. package/lib/checks/impl/ExternalAccountHierarchyExposureCheck.js +73 -0
  34. package/lib/checks/impl/FlowHttpCalloutCredentialBypassCheck.d.ts +10 -0
  35. package/lib/checks/impl/FlowHttpCalloutCredentialBypassCheck.js +115 -0
  36. package/lib/checks/impl/GenAiPromptTemplateGroundingCheck.d.ts +10 -0
  37. package/lib/checks/impl/GenAiPromptTemplateGroundingCheck.js +227 -0
  38. package/lib/checks/impl/GuestExecutableApexCheck.d.ts +1 -1
  39. package/lib/checks/impl/GuestExecutableApexCheck.js +105 -14
  40. package/lib/checks/impl/HardcodedCredentialsCheck.js +7 -2
  41. package/lib/checks/impl/InboundEmailHandlerExposureCheck.d.ts +10 -0
  42. package/lib/checks/impl/InboundEmailHandlerExposureCheck.js +136 -0
  43. package/lib/checks/impl/OauthDeviceAndAssetTokenFlowsCheck.d.ts +10 -0
  44. package/lib/checks/impl/OauthDeviceAndAssetTokenFlowsCheck.js +84 -0
  45. package/lib/checks/impl/OrgWideEmailSpoofingCheck.d.ts +10 -0
  46. package/lib/checks/impl/OrgWideEmailSpoofingCheck.js +106 -0
  47. package/lib/checks/impl/PackagePostInstallSupplyChainCheck.d.ts +10 -0
  48. package/lib/checks/impl/PackagePostInstallSupplyChainCheck.js +89 -0
  49. package/lib/checks/impl/PlatformEventSubscriberContextCheck.d.ts +10 -0
  50. package/lib/checks/impl/PlatformEventSubscriberContextCheck.js +84 -0
  51. package/lib/checks/impl/RestrictionRulesIntegrityCheck.d.ts +10 -0
  52. package/lib/checks/impl/RestrictionRulesIntegrityCheck.js +105 -0
  53. package/lib/checks/impl/ShieldTenantSecretLifecycleCheck.d.ts +10 -0
  54. package/lib/checks/impl/ShieldTenantSecretLifecycleCheck.js +90 -0
  55. package/lib/checks/registry.js +30 -0
  56. package/lib/checks/support/apexAccess.d.ts +56 -0
  57. package/lib/checks/support/apexAccess.js +127 -0
  58. package/lib/checks/support/missingObject.d.ts +13 -0
  59. package/lib/checks/support/missingObject.js +35 -0
  60. package/lib/commands/audit/apps.d.ts +1 -0
  61. package/lib/commands/audit/apps.js +83 -29
  62. package/lib/commands/audit/diff.js +2 -2
  63. package/lib/commands/audit/history.js +2 -2
  64. package/lib/commands/audit/incident/report.js +2 -2
  65. package/lib/commands/audit/security.d.ts +3 -0
  66. package/lib/commands/audit/security.js +58 -9
  67. package/lib/commands/audit/timeline.js +2 -2
  68. package/lib/compliance/mapping.js +28 -7
  69. package/lib/findings/AuditResult.d.ts +8 -0
  70. package/lib/findings/CheckMeta.js +15 -0
  71. package/lib/findings/Finding.d.ts +4 -0
  72. package/lib/findings/ScoringConfig.d.ts +10 -8
  73. package/lib/findings/ScoringConfig.js +12 -5
  74. package/lib/findings/coverage.d.ts +28 -0
  75. package/lib/findings/coverage.js +30 -0
  76. package/lib/findings/exitCode.js +1 -1
  77. package/lib/findings/loadScoringConfig.js +51 -8
  78. package/lib/findings/scoring.js +14 -5
  79. package/lib/history/HistoryStore.js +9 -3
  80. package/lib/history/archivePolicy.d.ts +19 -0
  81. package/lib/history/archivePolicy.js +34 -0
  82. package/lib/incident/bundleIo.js +4 -3
  83. package/lib/incident/collect/collectBundle.d.ts +1 -1
  84. package/lib/incident/collect/collectBundle.js +4 -3
  85. package/lib/incident/collect/streamGuestLogs.d.ts +1 -1
  86. package/lib/incident/collect/streamGuestLogs.js +3 -2
  87. package/lib/incident/csv.js +4 -4
  88. package/lib/incident/render/evidence.js +3 -3
  89. package/lib/incident/render/html.js +2 -3
  90. package/lib/index.d.ts +2 -0
  91. package/lib/index.js +2 -0
  92. package/lib/lib/packageInfo.d.ts +6 -0
  93. package/lib/lib/packageInfo.js +19 -0
  94. package/lib/renderers/AttackChainDagRenderer.d.ts +7 -0
  95. package/lib/renderers/AttackChainDagRenderer.js +139 -0
  96. package/lib/renderers/ClientReportRenderer.d.ts +2 -0
  97. package/lib/renderers/ClientReportRenderer.js +34 -6
  98. package/lib/renderers/DiffHtmlRenderer.js +2 -7
  99. package/lib/renderers/HistoryRenderer.js +19 -11
  100. package/lib/renderers/HtmlRenderer.js +19 -6
  101. package/lib/renderers/MarkdownRenderer.js +7 -0
  102. package/lib/renderers/SarifRenderer.d.ts +43 -0
  103. package/lib/renderers/SarifRenderer.js +250 -0
  104. package/lib/report/ExecutivePriorities.js +1 -1
  105. package/lib/report/RemediationRoadmap.js +1 -1
  106. package/lib/waivers/WaiverLoader.d.ts +28 -0
  107. package/lib/waivers/WaiverLoader.js +103 -0
  108. package/lib/waivers/WaiverModel.d.ts +32 -0
  109. package/lib/waivers/WaiverModel.js +28 -0
  110. package/lib/waivers/applyWaivers.d.ts +22 -0
  111. package/lib/waivers/applyWaivers.js +85 -0
  112. package/package.json +3 -3
@@ -0,0 +1,28 @@
1
+ import type { Finding } from './Finding.js';
2
+ /**
3
+ * Below this share of checks gathering evidence, a run cannot be graded A: too much of the org
4
+ * went unseen for a clean result to mean the org is clean.
5
+ */
6
+ export declare const MIN_COVERAGE_FOR_A = 90;
7
+ export interface EvidenceCoverage {
8
+ /** Checks that ran (produced at least one finding). */
9
+ checksRun: number;
10
+ /** Checks that gathered evidence for at least one of their findings. */
11
+ checksAssessed: number;
12
+ /** checksAssessed / checksRun, as a whole percentage. 100 when nothing ran. */
13
+ percent: number;
14
+ /** Ids of the checks that gathered no evidence at all, sorted. */
15
+ notAssessed: string[];
16
+ }
17
+ /**
18
+ * How much of the audit actually saw the org. A check counts as not assessed when every finding
19
+ * it produced is inconclusive or marks the check as not run (a crash, or a permission error
20
+ * CheckEngine caught). A check with some evidence and some gaps is assessed: its gaps are already
21
+ * visible as its own inconclusive findings.
22
+ */
23
+ export declare function evidenceCoverage(findings: readonly Finding[]): EvidenceCoverage;
24
+ /** One line for every output: "Evidence coverage 82% (14 of 17 checks); grade capped at B". */
25
+ export declare function coverageSummary(coverage: EvidenceCoverage & {
26
+ gradeCapped?: boolean;
27
+ }): string;
28
+ //# sourceMappingURL=coverage.d.ts.map
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Below this share of checks gathering evidence, a run cannot be graded A: too much of the org
3
+ * went unseen for a clean result to mean the org is clean.
4
+ */
5
+ export const MIN_COVERAGE_FOR_A = 90;
6
+ /**
7
+ * How much of the audit actually saw the org. A check counts as not assessed when every finding
8
+ * it produced is inconclusive or marks the check as not run (a crash, or a permission error
9
+ * CheckEngine caught). A check with some evidence and some gaps is assessed: its gaps are already
10
+ * visible as its own inconclusive findings.
11
+ */
12
+ export function evidenceCoverage(findings) {
13
+ const byCheck = new Map();
14
+ for (const f of findings) {
15
+ const id = f.checkId ?? f.id;
16
+ const sawEvidence = !(f.inconclusive || f.notAssessed);
17
+ byCheck.set(id, (byCheck.get(id) ?? false) || sawEvidence);
18
+ }
19
+ const notAssessed = [...byCheck].filter(([, assessed]) => !assessed).map(([id]) => id).sort();
20
+ const checksRun = byCheck.size;
21
+ const checksAssessed = checksRun - notAssessed.length;
22
+ const percent = checksRun === 0 ? 100 : Math.floor((checksAssessed / checksRun) * 100);
23
+ return { checksRun, checksAssessed, percent, notAssessed };
24
+ }
25
+ /** One line for every output: "Evidence coverage 82% (14 of 17 checks); grade capped at B". */
26
+ export function coverageSummary(coverage) {
27
+ const base = `Evidence coverage ${coverage.percent}% (${coverage.checksAssessed} of ${coverage.checksRun} checks)`;
28
+ return coverage.gradeCapped ? `${base}; grade capped at B, below the ${MIN_COVERAGE_FOR_A}% needed for an A` : base;
29
+ }
30
+ //# sourceMappingURL=coverage.js.map
@@ -22,7 +22,7 @@ export function violationsFor(findings, failOn) {
22
22
  if (threshold < 0)
23
23
  return [];
24
24
  return findings.filter((f) => {
25
- if (f.passed === true || f.inconclusive === true)
25
+ if (f.passed === true || f.inconclusive === true || f.waived === true)
26
26
  return false;
27
27
  const rank = ORDER.indexOf(f.riskLevel);
28
28
  return rank >= 0 && rank <= threshold;
@@ -1,4 +1,5 @@
1
1
  import * as fs from 'node:fs';
2
+ import { z } from 'zod';
2
3
  import { scoringConfigSchema, DEFAULT_SCORING_CONFIG } from './ScoringConfig.js';
3
4
  export function loadScoringConfig(filePath, knownCheckIds, warn) {
4
5
  if (!filePath)
@@ -17,7 +18,17 @@ export function loadScoringConfig(filePath, knownCheckIds, warn) {
17
18
  catch (err) {
18
19
  throw new Error(`Invalid JSON in scoring config '${filePath}': ${err instanceof Error ? err.message : String(err)}`);
19
20
  }
20
- const validated = scoringConfigSchema.parse(parsed); // throws ZodError on failure
21
+ let validated;
22
+ try {
23
+ validated = scoringConfigSchema.parse(parsed);
24
+ }
25
+ catch (err) {
26
+ if (err instanceof z.ZodError) {
27
+ const details = err.issues.map((i) => ` - ${i.path.join('.') || 'root'}: ${i.message}`).join('\n');
28
+ throw new Error(`Invalid scoring config in '${filePath}':\n${details}`);
29
+ }
30
+ throw err;
31
+ }
21
32
  // Warn on unknown check IDs and drop them
22
33
  const safeCheckWeights = {};
23
34
  const rawWeights = validated.checkWeights ?? {};
@@ -29,16 +40,48 @@ export function loadScoringConfig(filePath, knownCheckIds, warn) {
29
40
  safeCheckWeights[id] = weight;
30
41
  }
31
42
  }
43
+ const gradeThresholds = {
44
+ A: { ...DEFAULT_SCORING_CONFIG.gradeThresholds.A, ...validated.gradeThresholds?.A },
45
+ B: { ...DEFAULT_SCORING_CONFIG.gradeThresholds.B, ...validated.gradeThresholds?.B },
46
+ C: { ...DEFAULT_SCORING_CONFIG.gradeThresholds.C, ...validated.gradeThresholds?.C },
47
+ D: { ...DEFAULT_SCORING_CONFIG.gradeThresholds.D, ...validated.gradeThresholds?.D },
48
+ F: { ...DEFAULT_SCORING_CONFIG.gradeThresholds.F, ...validated.gradeThresholds?.F },
49
+ };
50
+ const orderErrors = thresholdOrderErrors(gradeThresholds);
51
+ if (orderErrors.length > 0) {
52
+ throw new Error(`Invalid scoring config in '${filePath}' (grade thresholds after merging with defaults):\n${orderErrors.map((e) => ` - ${e}`).join('\n')}`);
53
+ }
32
54
  return {
33
55
  riskScores: validated.riskScores ?? DEFAULT_SCORING_CONFIG.riskScores,
34
56
  checkWeights: safeCheckWeights,
35
- gradeThresholds: {
36
- A: { ...DEFAULT_SCORING_CONFIG.gradeThresholds.A, ...validated.gradeThresholds?.A },
37
- B: { ...DEFAULT_SCORING_CONFIG.gradeThresholds.B, ...validated.gradeThresholds?.B },
38
- C: { ...DEFAULT_SCORING_CONFIG.gradeThresholds.C, ...validated.gradeThresholds?.C },
39
- D: { ...DEFAULT_SCORING_CONFIG.gradeThresholds.D, ...validated.gradeThresholds?.D },
40
- F: { ...DEFAULT_SCORING_CONFIG.gradeThresholds.F, ...validated.gradeThresholds?.F },
41
- },
57
+ gradeThresholds,
42
58
  };
43
59
  }
60
+ const GRADE_ORDER = ['A', 'B', 'C', 'D'];
61
+ /**
62
+ * Grades are tried A first, then B, C, D, so each grade must be at least as strict as the next.
63
+ * A lower bar on A than on B would make B unreachable, which is never what the author meant.
64
+ * The JSON Schema cannot express this cross-field rule, so it lives here, applied to the merged
65
+ * result (a one-grade override can contradict a default on its neighbour).
66
+ */
67
+ function thresholdOrderErrors(t) {
68
+ const errors = [];
69
+ for (let i = 0; i < GRADE_ORDER.length - 1; i++) {
70
+ const hi = GRADE_ORDER[i];
71
+ const lo = GRADE_ORDER[i + 1];
72
+ const a = t[hi];
73
+ const b = t[lo];
74
+ if (a.minScore !== undefined && b.minScore !== undefined && a.minScore < b.minScore) {
75
+ errors.push(`gradeThresholds.${hi}.minScore (${a.minScore}) is below gradeThresholds.${lo}.minScore (${b.minScore})`);
76
+ }
77
+ for (const key of ['maxCritical', 'maxHigh', 'maxMedium']) {
78
+ const av = a[key];
79
+ const bv = b[key];
80
+ if (av !== undefined && bv !== undefined && av > bv) {
81
+ errors.push(`gradeThresholds.${hi}.${key} (${av}) is above gradeThresholds.${lo}.${key} (${bv})`);
82
+ }
83
+ }
84
+ }
85
+ return errors;
86
+ }
44
87
  //# sourceMappingURL=loadScoringConfig.js.map
@@ -1,5 +1,6 @@
1
1
  import { EMPTY_METRICS } from '@cclabsnz/sf-core';
2
2
  import { DEFAULT_SCORING_CONFIG } from './ScoringConfig.js';
3
+ import { evidenceCoverage, MIN_COVERAGE_FOR_A } from './coverage.js';
3
4
  function meetsConditions(conditions, healthScore, criticalCount, highCount, mediumCount) {
4
5
  if (conditions.minScore !== undefined && healthScore < conditions.minScore)
5
6
  return false;
@@ -12,10 +13,10 @@ function meetsConditions(conditions, healthScore, criticalCount, highCount, medi
12
13
  return true;
13
14
  }
14
15
  export function buildAuditResult(ctx, findings, metrics, config = DEFAULT_SCORING_CONFIG, attackChains = []) {
15
- // Passed and inconclusive findings carry no penalty — exclude from numerator.
16
+ // Passed, inconclusive and waived findings carry no penalty — exclude from numerator.
16
17
  // They remain in maxPossible so a broad passing audit still dilutes real failures.
17
18
  const totalScore = findings.reduce((sum, f) => {
18
- if (f.passed || f.inconclusive)
19
+ if (f.passed || f.inconclusive || f.waived)
19
20
  return sum;
20
21
  return sum + (f.checkId !== undefined ? (config.checkWeights[f.checkId] ?? config.riskScores[f.riskLevel]) : config.riskScores[f.riskLevel]);
21
22
  }, 0);
@@ -26,9 +27,9 @@ export function buildAuditResult(ctx, findings, metrics, config = DEFAULT_SCORIN
26
27
  const chainCrit = attackChains.filter((c) => c.severity === 'CRITICAL').length;
27
28
  const chainHigh = attackChains.filter((c) => c.severity === 'HIGH').length;
28
29
  const chainMed = attackChains.filter((c) => c.severity === 'MEDIUM').length;
29
- const criticalCount = findings.filter((f) => f.riskLevel === 'CRITICAL').length + chainCrit;
30
- const highCount = findings.filter((f) => f.riskLevel === 'HIGH').length + chainHigh;
31
- const mediumCount = findings.filter((f) => f.riskLevel === 'MEDIUM').length + chainMed;
30
+ const criticalCount = findings.filter((f) => f.riskLevel === 'CRITICAL' && !f.waived).length + chainCrit;
31
+ const highCount = findings.filter((f) => f.riskLevel === 'HIGH' && !f.waived).length + chainHigh;
32
+ const mediumCount = findings.filter((f) => f.riskLevel === 'MEDIUM' && !f.waived).length + chainMed;
32
33
  const grades = ['A', 'B', 'C', 'D'];
33
34
  let grade = 'F';
34
35
  for (const g of grades) {
@@ -37,6 +38,12 @@ export function buildAuditResult(ctx, findings, metrics, config = DEFAULT_SCORIN
37
38
  break;
38
39
  }
39
40
  }
41
+ const waivedFindings = findings.filter((f) => f.waived);
42
+ // A run that could not see enough of the org is never graded A. Coverage is reported either way.
43
+ const coverage = evidenceCoverage(findings);
44
+ const gradeCapped = grade === 'A' && coverage.percent < MIN_COVERAGE_FOR_A;
45
+ if (gradeCapped)
46
+ grade = 'B';
40
47
  return {
41
48
  generatedAt: new Date(),
42
49
  orgId: ctx.orgInfo.id,
@@ -50,6 +57,8 @@ export function buildAuditResult(ctx, findings, metrics, config = DEFAULT_SCORIN
50
57
  healthScore,
51
58
  grade,
52
59
  attackChains,
60
+ waivedFindings: waivedFindings.length > 0 ? waivedFindings : undefined,
61
+ coverage: { ...coverage, gradeCapped },
53
62
  };
54
63
  }
55
64
  //# sourceMappingURL=scoring.js.map
@@ -1,7 +1,7 @@
1
- // src/history/HistoryStore.ts
2
1
  import * as fs from 'node:fs';
3
2
  import * as os from 'node:os';
4
3
  import * as path from 'node:path';
4
+ import { secureFs } from '@cclabsnz/sf-core';
5
5
  function parseResult(raw) {
6
6
  const obj = JSON.parse(raw);
7
7
  obj.generatedAt = new Date(obj.generatedAt);
@@ -11,6 +11,12 @@ export class HistoryStore {
11
11
  root;
12
12
  constructor(root) {
13
13
  this.root = root ?? HistoryStore.defaultRoot();
14
+ try {
15
+ secureFs.ensureSecureDir(this.root);
16
+ }
17
+ catch {
18
+ // Non-fatal if root cannot be secured immediately
19
+ }
14
20
  }
15
21
  static defaultRoot() {
16
22
  return path.join(os.homedir(), '.sf', 'audit-history');
@@ -18,10 +24,10 @@ export class HistoryStore {
18
24
  archive(result) {
19
25
  try {
20
26
  const dir = path.join(this.root, result.orgId);
21
- fs.mkdirSync(dir, { recursive: true });
27
+ secureFs.mkdirSync(dir, { recursive: true });
22
28
  const suffix = Math.random().toString(36).slice(2, 8);
23
29
  const filename = `sf-audit-${result.orgId}-${Date.now()}-${suffix}.json`;
24
- fs.writeFileSync(path.join(dir, filename), JSON.stringify(result, null, 2), 'utf-8');
30
+ secureFs.writeFileSync(path.join(dir, filename), JSON.stringify(result, null, 2), 'utf-8');
25
31
  }
26
32
  catch (err) {
27
33
  process.stderr.write(`[sf-audit] Warning: could not archive audit result: ${String(err)}\n`);
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Whether `sf audit security` should auto-archive its result to the local history store.
3
+ *
4
+ * A CI runner is usually ephemeral, so archiving there only writes org data to a disk
5
+ * nobody reads again, and on a shared self-hosted runner it leaves that data behind for
6
+ * the next job. Archiving is therefore off in CI unless the caller opts back in.
7
+ */
8
+ export interface ArchiveFlags {
9
+ 'no-history'?: boolean;
10
+ 'keep-history'?: boolean;
11
+ }
12
+ /**
13
+ * Detect a CI environment. `CI` is the de-facto convention (GitHub Actions, GitLab,
14
+ * CircleCI, Buildkite, Travis, Bitbucket all set it); the others cover runners that don't.
15
+ */
16
+ export declare function isCiEnvironment(env?: NodeJS.ProcessEnv): boolean;
17
+ /** `--keep-history` always wins; otherwise `--no-history` or a detected CI run skips the archive. */
18
+ export declare function shouldArchiveHistory(flags: ArchiveFlags, env?: NodeJS.ProcessEnv): boolean;
19
+ //# sourceMappingURL=archivePolicy.d.ts.map
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Whether `sf audit security` should auto-archive its result to the local history store.
3
+ *
4
+ * A CI runner is usually ephemeral, so archiving there only writes org data to a disk
5
+ * nobody reads again, and on a shared self-hosted runner it leaves that data behind for
6
+ * the next job. Archiving is therefore off in CI unless the caller opts back in.
7
+ */
8
+ /** Values of `CI` that mean "not CI". Anything else non-empty (`true`, `1`, `yes`...) counts. */
9
+ const FALSY = new Set(['', '0', 'false', 'no', 'off']);
10
+ /**
11
+ * Detect a CI environment. `CI` is the de-facto convention (GitHub Actions, GitLab,
12
+ * CircleCI, Buildkite, Travis, Bitbucket all set it); the others cover runners that don't.
13
+ */
14
+ export function isCiEnvironment(env = process.env) {
15
+ const ci = env.CI;
16
+ if (ci !== undefined && !FALSY.has(ci.trim().toLowerCase()))
17
+ return true;
18
+ if (env.GITHUB_ACTIONS === 'true')
19
+ return true;
20
+ if (env.TF_BUILD !== undefined && env.TF_BUILD !== '')
21
+ return true; // Azure Pipelines
22
+ if (env.JENKINS_URL !== undefined && env.JENKINS_URL !== '')
23
+ return true;
24
+ return false;
25
+ }
26
+ /** `--keep-history` always wins; otherwise `--no-history` or a detected CI run skips the archive. */
27
+ export function shouldArchiveHistory(flags, env = process.env) {
28
+ if (flags['keep-history'])
29
+ return true;
30
+ if (flags['no-history'])
31
+ return false;
32
+ return !isCiEnvironment(env);
33
+ }
34
+ //# sourceMappingURL=archivePolicy.js.map
@@ -1,6 +1,7 @@
1
1
  import { createHash } from 'node:crypto';
2
- import { createReadStream, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
2
+ import { createReadStream, existsSync, readFileSync, renameSync } from 'node:fs';
3
3
  import { dirname, join } from 'node:path';
4
+ import { secureFs } from '@cclabsnz/sf-core';
4
5
  import { readCsvRecords } from './csv.js';
5
6
  export const BUNDLE_PATHS = {
6
7
  manifest: 'manifest.json',
@@ -19,9 +20,9 @@ export async function sha256File(path) {
19
20
  return h.digest('hex');
20
21
  }
21
22
  export function writeJsonAtomic(path, value) {
22
- mkdirSync(dirname(path), { recursive: true });
23
+ secureFs.mkdirSync(dirname(path), { recursive: true });
23
24
  const part = `${path}.part`;
24
- writeFileSync(part, JSON.stringify(value, null, 2));
25
+ secureFs.writeFileSync(part, JSON.stringify(value, null, 2));
25
26
  renameSync(part, path);
26
27
  }
27
28
  export class BundleIntegrityError extends Error {
@@ -1,4 +1,4 @@
1
- import type { RestClient, SoqlClient } from '@cclabsnz/sf-core';
1
+ import { type RestClient, type SoqlClient } from '@cclabsnz/sf-core';
2
2
  import type { BundleManifest } from '../model.js';
3
3
  export interface CollectOptions {
4
4
  sinceDays: number;
@@ -1,7 +1,8 @@
1
1
  // src/incident/collect/collectBundle.ts
2
- import { copyFileSync, existsSync, mkdirSync, readFileSync, rmSync } from 'node:fs';
2
+ import { copyFileSync, existsSync, readFileSync, rmSync } from 'node:fs';
3
3
  import { homedir } from 'node:os';
4
4
  import { basename, join } from 'node:path';
5
+ import { secureFs } from '@cclabsnz/sf-core';
5
6
  import { BUNDLE_PATHS, loadBundle, sha256File, writeJsonAtomic } from '../bundleIo.js';
6
7
  import { findActors } from '../analyse/actors.js';
7
8
  import { loadIpRanges, rangeFileName } from '../ipRanges.js';
@@ -37,7 +38,7 @@ async function priorLogs(dir, orgId, guestIds) {
37
38
  }
38
39
  export async function collectBundle(ctx, opts) {
39
40
  const dir = opts.outputDir;
40
- mkdirSync(dir, { recursive: true });
41
+ secureFs.mkdirSync(dir, { recursive: true });
41
42
  const collectedAt = new Date().toISOString();
42
43
  const anomalies = await readAnomalies(ctx.soql, opts.sinceDays);
43
44
  if (!anomalies.available && !opts.window) {
@@ -88,7 +89,7 @@ export async function collectBundle(ctx, opts) {
88
89
  for (const [index, f] of opts.ipRangeFiles.entries()) {
89
90
  // Indexed, so two files with the same name (aws/ranges.txt, gcp/ranges.txt) cannot overwrite each other.
90
91
  const rel = `ip-ranges/${index}-${basename(f)}`;
91
- mkdirSync(join(dir, 'ip-ranges'), { recursive: true });
92
+ secureFs.mkdirSync(join(dir, 'ip-ranges'), { recursive: true });
92
93
  copyFileSync(f, join(dir, rel));
93
94
  ipRangeFiles.push(rel);
94
95
  }
@@ -1,4 +1,4 @@
1
- import type { RestClient, SoqlClient } from '@cclabsnz/sf-core';
1
+ import { type RestClient, type SoqlClient } from '@cclabsnz/sf-core';
2
2
  import { type LogCoverage, type LogType, type Wave } from '../model.js';
3
3
  /** Columns a log of this type needs but its header lacks. Every type needs a user column. */
4
4
  export declare function missingColumns(type: LogType, header: string[]): string[];
@@ -1,6 +1,7 @@
1
1
  // src/incident/collect/streamGuestLogs.ts
2
- import { mkdirSync, rmSync, renameSync, statfsSync } from 'node:fs';
2
+ import { rmSync, renameSync, statfsSync } from 'node:fs';
3
3
  import { join } from 'node:path';
4
+ import { secureFs } from '@cclabsnz/sf-core';
4
5
  import { degrades } from './orgErrors.js';
5
6
  import { filterLogFile, MissingColumnsError } from '../csv.js';
6
7
  import { logPath } from '../bundleIo.js';
@@ -47,7 +48,7 @@ onLogDone = () => { }) {
47
48
  const tmp = join(bundleDir, '.tmp');
48
49
  // A killed earlier run can leave raw, unfiltered logs here, which contain non-guest data.
49
50
  rmSync(tmp, { recursive: true, force: true });
50
- mkdirSync(tmp, { recursive: true });
51
+ secureFs.mkdirSync(tmp, { recursive: true });
51
52
  for (const day of days) {
52
53
  for (const type of LOG_TYPES) {
53
54
  const prior = reuse(type, day);
@@ -1,5 +1,5 @@
1
- import { createReadStream, createWriteStream, rmSync, existsSync, statSync } from 'node:fs';
2
- import { mkdir } from 'node:fs/promises';
1
+ import { createReadStream, rmSync, existsSync, statSync } from 'node:fs';
2
+ import { secureFs } from '@cclabsnz/sf-core';
3
3
  import { dirname } from 'node:path';
4
4
  import { finished } from 'node:stream/promises';
5
5
  import { id15 } from './model.js';
@@ -101,8 +101,8 @@ export class MissingColumnsError extends Error {
101
101
  * the header lacks; any at all fails the file closed with MissingColumnsError.
102
102
  */
103
103
  export async function filterLogFile(rawPath, outPath, guestIds, opts = {}) {
104
- await mkdir(dirname(outPath), { recursive: true });
105
- const out = createWriteStream(outPath);
104
+ await secureFs.mkdir(dirname(outPath), { recursive: true });
105
+ const out = secureFs.createWriteStream(outPath);
106
106
  const result = { totalRows: 0, guestRows: 0, guestRowsByUser: {}, malformed: 0 };
107
107
  let header;
108
108
  let userCols = [];
@@ -1,6 +1,6 @@
1
1
  // src/incident/render/evidence.ts
2
- import { mkdirSync, writeFileSync } from 'node:fs';
3
2
  import { join } from 'node:path';
3
+ import { secureFs } from '@cclabsnz/sf-core';
4
4
  import { csvLine } from '../csv.js';
5
5
  import { NOT_COLLECTED, auraCollectedDays, coveredDays } from './labels.js';
6
6
  /** Every number in the report cites one of these tables; ids are assigned in a fixed order. */
@@ -42,10 +42,10 @@ export function buildEvidence(r) {
42
42
  /** Spreadsheet formula-injection guard, applied to written files only (csvLine stays raw for the log filter). */
43
43
  const neutralise = (c) => (/^[=+\-@\t\r]/.test(c) ? `'${c}` : c);
44
44
  export function writeEvidence(dir, tables) {
45
- mkdirSync(join(dir, 'evidence'), { recursive: true });
45
+ secureFs.mkdirSync(join(dir, 'evidence'), { recursive: true });
46
46
  return tables.map((t) => {
47
47
  const p = join(dir, 'evidence', `${t.id}.csv`);
48
- writeFileSync(p, csvLine(t.columns.map(neutralise)) + t.rows.map((row) => csvLine(row.map(neutralise))).join(''));
48
+ secureFs.writeFileSync(p, csvLine(t.columns.map(neutralise)) + t.rows.map((row) => csvLine(row.map(neutralise))).join(''));
49
49
  return p;
50
50
  });
51
51
  }
@@ -1,5 +1,4 @@
1
- // src/incident/render/html.ts
2
- import { esc, fontFaceCss } from '@cclabsnz/sf-core';
1
+ import { esc, fontFaceCss, INTERACTIVE_CSP_META } from '@cclabsnz/sf-core';
3
2
  import { chartJsScript } from '../../renderers/chartAsset.js';
4
3
  import { toolCreditHtml } from '../../renderers/toolCredit.js';
5
4
  import { CLASSIFICATION_LABEL, RESULT_LABEL, auraCollectedDays, coveredDays } from './labels.js';
@@ -56,7 +55,7 @@ export function renderHtml(r, ev, b) {
56
55
  const chart = JSON.stringify({ ...timelineData(r), colours: CHART_COLOURS, ink: b.ink, muted: b.muted, border: b.border, font: b.fontBody }).replace(/</g, '\\u003c');
57
56
  const sec = (num, title) => `<div class="sh"><span class="sec-num">${num} /</span><h2>${title}</h2></div>`;
58
57
  return `<!doctype html>
59
- <html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Guest-access incident report: ${esc(r.orgName)}</title>
58
+ <html lang="en"><head><meta charset="utf-8">${INTERACTIVE_CSP_META}<meta name="viewport" content="width=device-width,initial-scale=1"><title>Guest-access incident report: ${esc(r.orgName)}</title>
60
59
  <style>${fontFaceCss()}
61
60
  :root{--ink:${b.ink};--bg:${b.bg};--bgalt:${b.bgAlt};--muted:${b.muted};--border:${b.border};--primary:${b.primary};
62
61
  --display:'${b.fontDisplay}',Georgia,serif;--body:'${b.fontBody}',system-ui,sans-serif;--mono:ui-monospace,'SF Mono',Menlo,monospace;
package/lib/index.d.ts CHANGED
@@ -5,4 +5,6 @@ export type { OrgMetrics } from '@cclabsnz/sf-core';
5
5
  export type { AuditDiff, FindingChange, FindingChangeType, MetricDelta } from './history/AuditDiff.js';
6
6
  export { HistoryStore } from './history/HistoryStore.js';
7
7
  export { computeDiff } from './history/DiffEngine.js';
8
+ export { WaiverLoader } from './waivers/WaiverLoader.js';
9
+ export { applyWaivers } from './waivers/applyWaivers.js';
8
10
  //# sourceMappingURL=index.d.ts.map
package/lib/index.js CHANGED
@@ -1,3 +1,5 @@
1
1
  export { HistoryStore } from './history/HistoryStore.js';
2
2
  export { computeDiff } from './history/DiffEngine.js';
3
+ export { WaiverLoader } from './waivers/WaiverLoader.js';
4
+ export { applyWaivers } from './waivers/applyWaivers.js';
3
5
  //# sourceMappingURL=index.js.map
@@ -0,0 +1,6 @@
1
+ export interface PackageInfo {
2
+ name: string;
3
+ version: string;
4
+ }
5
+ export declare function packageInfo(): PackageInfo;
6
+ //# sourceMappingURL=packageInfo.d.ts.map
@@ -0,0 +1,19 @@
1
+ import { createRequire } from 'node:module';
2
+ /**
3
+ * This plugin's own name and version, read from its package.json so that output which
4
+ * identifies the tool (e.g. the SARIF driver) never drifts from the published release.
5
+ *
6
+ * Resolved relative to this module, which sits two levels below the package root in both
7
+ * `src/lib/` (tests) and `lib/lib/` (the published build). package.json always ships in the
8
+ * npm tarball, whatever `files` says.
9
+ */
10
+ const requireFrom = createRequire(import.meta.url);
11
+ let cached;
12
+ export function packageInfo() {
13
+ if (cached)
14
+ return cached;
15
+ const pkg = requireFrom('../../package.json');
16
+ cached = { name: pkg.name, version: pkg.version };
17
+ return cached;
18
+ }
19
+ //# sourceMappingURL=packageInfo.js.map
@@ -0,0 +1,7 @@
1
+ import type { AttackChain } from '../chains/AttackChain.js';
2
+ export interface DagRenderOptions {
3
+ theme?: 'dark' | 'light';
4
+ }
5
+ export declare function identifyCutPointIndex(chain: AttackChain): number;
6
+ export declare function renderAttackChainDagSvg(chain: AttackChain, opts?: DagRenderOptions): string;
7
+ //# sourceMappingURL=AttackChainDagRenderer.d.ts.map
@@ -0,0 +1,139 @@
1
+ // src/renderers/AttackChainDagRenderer.ts
2
+ //
3
+ // Draws an attack chain as an inline SVG strip of step cards joined by arrows, with the step whose
4
+ // fix breaks the chain marked as the cut-point. The executive report runs under a strict CSP (no
5
+ // script, inline style only), so the output is self-contained: no <script>, no event handlers, no
6
+ // <foreignObject>, no external references. Every chain/step string is escaped before it is placed
7
+ // in text or an attribute; colours come only from fixed lookup tables.
8
+ import { esc } from '@cclabsnz/sf-core';
9
+ // Severity accents per theme. The light set is darker so the "STEP n · SEV" label stays legible
10
+ // on a white card (the dark set's yellow/blue fall well below 3:1 on white).
11
+ const SEV_COLORS = {
12
+ dark: { CRITICAL: '#ef4444', HIGH: '#f97316', MEDIUM: '#eab308', LOW: '#60a5fa', INFO: '#94a3b8' },
13
+ light: { CRITICAL: '#b91c1c', HIGH: '#c2410c', MEDIUM: '#a16207', LOW: '#1d4ed8', INFO: '#475569' },
14
+ };
15
+ /** Cards per row before the strip wraps, so long chains stay readable when scaled to page width. */
16
+ const MAX_PER_ROW = 4;
17
+ export function identifyCutPointIndex(chain) {
18
+ if (!chain.steps || chain.steps.length === 0)
19
+ return 0;
20
+ const rem = (chain.remediation || '').toLowerCase();
21
+ for (let i = 0; i < chain.steps.length; i++) {
22
+ const s = chain.steps[i];
23
+ if (s.findingId && rem.includes(s.findingId.toLowerCase()))
24
+ return i;
25
+ if (s.title && rem.includes(s.title.toLowerCase()))
26
+ return i;
27
+ }
28
+ const sevRank = { CRITICAL: 4, HIGH: 3, MEDIUM: 2, LOW: 1, INFO: 0 };
29
+ let bestIdx = 0;
30
+ let bestRank = -1;
31
+ for (let i = 0; i < chain.steps.length; i++) {
32
+ const rank = sevRank[chain.steps[i].severity ?? 'LOW'] ?? 1;
33
+ if (rank > bestRank) {
34
+ bestRank = rank;
35
+ bestIdx = i;
36
+ }
37
+ }
38
+ return bestIdx;
39
+ }
40
+ /** Truncate by code point (never splitting a surrogate pair); escaping happens after. */
41
+ function truncate(str, maxLen) {
42
+ const chars = Array.from(str);
43
+ return chars.length > maxLen ? chars.slice(0, maxLen - 1).join('') + '…' : str;
44
+ }
45
+ export function renderAttackChainDagSvg(chain, opts = {}) {
46
+ const theme = opts.theme === 'light' ? 'light' : 'dark';
47
+ const steps = chain.steps ?? [];
48
+ if (steps.length === 0)
49
+ return '';
50
+ const cutPointIdx = identifyCutPointIndex(chain);
51
+ const cardW = 220;
52
+ const cardH = 96;
53
+ const gap = 52;
54
+ const rowGap = 44;
55
+ const padX = 24;
56
+ const padY = 24;
57
+ const cols = Math.min(steps.length, MAX_PER_ROW);
58
+ const rows = Math.ceil(steps.length / cols);
59
+ const totalW = padX * 2 + cols * cardW + (cols - 1) * gap;
60
+ const totalH = padY * 2 + rows * cardH + (rows - 1) * rowGap;
61
+ const posOf = (idx) => ({
62
+ x: padX + (idx % cols) * (cardW + gap),
63
+ y: padY + Math.floor(idx / cols) * (cardH + rowGap),
64
+ });
65
+ const isDark = theme === 'dark';
66
+ const sevColors = SEV_COLORS[theme];
67
+ const cardBg = isDark ? '#1e293b' : '#ffffff';
68
+ const cardBorder = isDark ? '#334155' : '#cbd5e1';
69
+ const textColor = isDark ? '#f8fafc' : '#0f172a';
70
+ const mutedColor = isDark ? '#94a3b8' : '#475569';
71
+ const pillBg = isDark ? '#0f172a' : '#f1f5f9';
72
+ const arrowColor = isDark ? '#64748b' : '#94a3b8';
73
+ const cutAccent = isDark ? '#ef4444' : '#dc2626';
74
+ const markerId = `dag-arrow-${String(chain.id).replace(/[^a-zA-Z0-9_-]/g, '_')}-${theme}`;
75
+ const nodesSvg = steps
76
+ .map((step, idx) => {
77
+ const { x, y } = posOf(idx);
78
+ const isCut = idx === cutPointIdx;
79
+ const sevRaw = String(step.severity ?? 'LOW');
80
+ const sevCol = sevColors[sevRaw] ?? sevColors.INFO;
81
+ const sev = esc(truncate(sevRaw, 10));
82
+ const title = esc(truncate(String(step.title || step.findingId || ''), 26));
83
+ const cap = esc(truncate(String(step.capability ?? ''), 24));
84
+ const stroke = isCut ? cutAccent : cardBorder;
85
+ const strokeWidth = isCut ? '2.5' : '1';
86
+ const dash = isCut ? ' stroke-dasharray="4 2"' : '';
87
+ const cutBadge = isCut
88
+ ? `<g transform="translate(${x + cardW - 84}, ${y - 10})">
89
+ <rect width="80" height="18" rx="4" fill="${cutAccent}" />
90
+ <text x="40" y="12" fill="#ffffff" font-size="9" font-weight="700" text-anchor="middle" font-family="system-ui, sans-serif">✂ CUT-POINT</text>
91
+ </g>`
92
+ : '';
93
+ const cutNote = isCut
94
+ ? `<text x="${x + 10}" y="${y + cardH - 10}" fill="${cutAccent}" font-size="9" font-weight="600" font-family="system-ui, sans-serif">★ Remediating breaks chain</text>`
95
+ : '';
96
+ return `<g class="dag-node${isCut ? ' dag-cut-point' : ''}">
97
+ <rect x="${x}" y="${y}" width="${cardW}" height="${cardH}" rx="8" fill="${cardBg}" stroke="${stroke}" stroke-width="${strokeWidth}"${dash} />
98
+ ${cutBadge}
99
+ <circle cx="${x + 18}" cy="${y + 20}" r="4" fill="${sevCol}" />
100
+ <text x="${x + 28}" y="${y + 24}" fill="${sevCol}" font-size="10" font-weight="700" font-family="system-ui, sans-serif">STEP ${idx + 1} · ${sev}</text>
101
+ <text x="${x + 10}" y="${y + 44}" fill="${textColor}" font-size="12" font-weight="600" font-family="system-ui, sans-serif">${title}</text>
102
+ <rect x="${x + 10}" y="${y + 54}" width="${cardW - 20}" height="18" rx="4" fill="${pillBg}" />
103
+ <text x="${x + 16}" y="${y + 67}" fill="${mutedColor}" font-size="10" font-family="ui-monospace, monospace">grants: ${cap}</text>
104
+ ${cutNote}
105
+ </g>`;
106
+ })
107
+ .join('\n');
108
+ const arrowsSvg = steps
109
+ .slice(0, -1)
110
+ .map((_, idx) => {
111
+ const from = posOf(idx);
112
+ const to = posOf(idx + 1);
113
+ let d;
114
+ if (from.y === to.y) {
115
+ // Same row: straight right-pointing arrow across the gap.
116
+ const centerY = from.y + cardH / 2;
117
+ d = `M ${from.x + cardW} ${centerY} L ${to.x - 6} ${centerY}`;
118
+ }
119
+ else {
120
+ // Row wrap: drop from the bottom of the last card, run back left, enter the next row's first card.
121
+ const sx = from.x + cardW / 2;
122
+ const ex = to.x + cardW / 2;
123
+ const midY = from.y + cardH + rowGap / 2;
124
+ d = `M ${sx} ${from.y + cardH} L ${sx} ${midY} L ${ex} ${midY} L ${ex} ${to.y - 6}`;
125
+ }
126
+ return `<path d="${d}" stroke="${arrowColor}" stroke-width="2" marker-end="url(#${markerId})" fill="none" />`;
127
+ })
128
+ .join('\n');
129
+ return `<svg class="attack-chain-dag" role="img" aria-label="${esc(`Attack chain diagram: ${chain.title ?? ''}`)}" viewBox="0 0 ${totalW} ${totalH}" width="100%" style="max-width:${totalW}px;display:block;margin:16px 0;">
130
+ <defs>
131
+ <marker id="${markerId}" viewBox="0 0 10 10" refX="6" refY="5" markerWidth="6" markerHeight="6" orient="auto-start-reverse">
132
+ <path d="M 0 1 L 8 5 L 0 9 z" fill="${arrowColor}" />
133
+ </marker>
134
+ </defs>
135
+ <g class="dag-arrows">${arrowsSvg}</g>
136
+ <g class="dag-nodes">${nodesSvg}</g>
137
+ </svg>`;
138
+ }
139
+ //# sourceMappingURL=AttackChainDagRenderer.js.map
@@ -19,6 +19,8 @@ export declare class ClientReportRenderer implements AuditRenderer {
19
19
  private cover;
20
20
  private summary;
21
21
  private prioritiesSection;
22
+ private coverageNote;
23
+ private waiversSection;
22
24
  private scenarios;
23
25
  private roadmapSection;
24
26
  private worst;