@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,103 @@
1
+ import * as fs from 'node:fs';
2
+ import * as path from 'node:path';
3
+ import { z } from 'zod';
4
+ import { MAX_WAIVER_DAYS, waiversConfigSchema } from './WaiverModel.js';
5
+ const DAY_MS = 24 * 60 * 60 * 1000;
6
+ /** The only file picked up without --waivers. Its path is always reported, so a waiver is never silent. */
7
+ export const DEFAULT_WAIVER_FILE = '.sfaudit-waivers.json';
8
+ const norm = (s) => s.trim().toLowerCase();
9
+ export class WaiverLoader {
10
+ source;
11
+ evaluatedWaivers = [];
12
+ /**
13
+ * @param source the file the waivers came from, or undefined when none was loaded. Reported to
14
+ * the user so a waiver file picked up from the working directory is never applied silently.
15
+ */
16
+ constructor(waivers, now = new Date(), source) {
17
+ this.source = source;
18
+ for (const w of waivers) {
19
+ const expiry = new Date(w.expiresAt);
20
+ this.evaluatedWaivers.push({
21
+ ...w,
22
+ isExpired: now.getTime() > expiry.getTime(),
23
+ daysRemaining: Math.ceil((expiry.getTime() - now.getTime()) / DAY_MS),
24
+ });
25
+ }
26
+ }
27
+ get waivers() {
28
+ return this.evaluatedWaivers;
29
+ }
30
+ get activeWaivers() {
31
+ return this.evaluatedWaivers.filter((w) => !w.isExpired);
32
+ }
33
+ get expiredWaivers() {
34
+ return this.evaluatedWaivers.filter((w) => w.isExpired);
35
+ }
36
+ /**
37
+ * The waiver covering one entity of one finding, preferring an active waiver over an expired
38
+ * one. Matching is exact (case- and whitespace-insensitive): the entity must equal an affected
39
+ * item's label, or, for a finding with no affected items, the finding id itself. There are no
40
+ * wildcards or partial matches, so a waiver can never cover more than the entity it names.
41
+ */
42
+ findMatchingWaiver(checkId, findingId, entityName) {
43
+ const target = norm(entityName);
44
+ if (target === '')
45
+ return undefined;
46
+ const candidates = this.evaluatedWaivers.filter((w) => w.checkId === checkId &&
47
+ (w.findingId === undefined || w.findingId === findingId) &&
48
+ norm(w.entity) === target);
49
+ return candidates.find((w) => !w.isExpired) ?? candidates[0];
50
+ }
51
+ /**
52
+ * Loads waivers from an explicit path, or from `.sfaudit-waivers.json` in the working directory.
53
+ * Rejects any waiver that runs longer than MAX_WAIVER_DAYS from `now`.
54
+ */
55
+ static load(explicitPath, now = new Date()) {
56
+ let targetPath = explicitPath;
57
+ if (!targetPath) {
58
+ const candidate = path.resolve(process.cwd(), DEFAULT_WAIVER_FILE);
59
+ if (fs.existsSync(candidate))
60
+ targetPath = candidate;
61
+ }
62
+ if (!targetPath)
63
+ return new WaiverLoader([], now);
64
+ if (!fs.existsSync(targetPath)) {
65
+ throw new Error(`Waiver file '${targetPath}' does not exist.`);
66
+ }
67
+ let raw;
68
+ try {
69
+ raw = fs.readFileSync(targetPath, 'utf-8');
70
+ }
71
+ catch (err) {
72
+ throw new Error(`Cannot read waiver file '${targetPath}': ${err instanceof Error ? err.message : String(err)}`);
73
+ }
74
+ let parsed;
75
+ try {
76
+ parsed = JSON.parse(raw);
77
+ }
78
+ catch (err) {
79
+ throw new Error(`Invalid JSON in waiver file '${targetPath}': ${err instanceof Error ? err.message : String(err)}`);
80
+ }
81
+ let config;
82
+ try {
83
+ config = waiversConfigSchema.parse(parsed);
84
+ }
85
+ catch (err) {
86
+ if (err instanceof z.ZodError) {
87
+ const details = err.issues.map((i) => ` - ${i.path.join('.') || 'root'}: ${i.message}`).join('\n');
88
+ throw new Error(`Malformed waiver configuration in '${targetPath}':\n${details}`);
89
+ }
90
+ throw err;
91
+ }
92
+ const limit = now.getTime() + MAX_WAIVER_DAYS * DAY_MS;
93
+ const tooLong = config.waivers
94
+ .map((w, i) => ({ w, i }))
95
+ .filter(({ w }) => new Date(w.expiresAt).getTime() > limit);
96
+ if (tooLong.length > 0) {
97
+ const details = tooLong.map(({ w, i }) => ` - waivers.${i}.expiresAt: ${w.expiresAt}`).join('\n');
98
+ throw new Error(`Waivers in '${targetPath}' expire more than ${MAX_WAIVER_DAYS} days from now. Re-approve them with a nearer date:\n${details}`);
99
+ }
100
+ return new WaiverLoader(config.waivers, now, targetPath);
101
+ }
102
+ }
103
+ //# sourceMappingURL=WaiverLoader.js.map
@@ -0,0 +1,32 @@
1
+ import { z } from 'zod';
2
+ /** The longest a waiver may run from the day it is loaded. Longer acceptances must be re-approved. */
3
+ export declare const MAX_WAIVER_DAYS = 365;
4
+ export declare const waiverEntrySchema: z.ZodObject<{
5
+ checkId: z.ZodString;
6
+ findingId: z.ZodOptional<z.ZodString>;
7
+ entity: z.ZodString;
8
+ reason: z.ZodString;
9
+ approvedBy: z.ZodString;
10
+ expiresAt: z.ZodString;
11
+ acknowledgeCritical: z.ZodOptional<z.ZodBoolean>;
12
+ }, z.core.$strict>;
13
+ export declare const waiversConfigSchema: z.ZodObject<{
14
+ $schema: z.ZodOptional<z.ZodString>;
15
+ _comment: z.ZodOptional<z.ZodString>;
16
+ waivers: z.ZodArray<z.ZodObject<{
17
+ checkId: z.ZodString;
18
+ findingId: z.ZodOptional<z.ZodString>;
19
+ entity: z.ZodString;
20
+ reason: z.ZodString;
21
+ approvedBy: z.ZodString;
22
+ expiresAt: z.ZodString;
23
+ acknowledgeCritical: z.ZodOptional<z.ZodBoolean>;
24
+ }, z.core.$strict>>;
25
+ }, z.core.$strict>;
26
+ export type WaiverEntry = z.infer<typeof waiverEntrySchema>;
27
+ export type WaiversConfig = z.infer<typeof waiversConfigSchema>;
28
+ export interface EvaluatedWaiver extends WaiverEntry {
29
+ isExpired: boolean;
30
+ daysRemaining: number;
31
+ }
32
+ //# sourceMappingURL=WaiverModel.d.ts.map
@@ -0,0 +1,28 @@
1
+ import { z } from 'zod';
2
+ /** The longest a waiver may run from the day it is loaded. Longer acceptances must be re-approved. */
3
+ export const MAX_WAIVER_DAYS = 365;
4
+ // A calendar date or a full ISO 8601 timestamp. Date.parse alone accepts forms like "March 2030"
5
+ // whose meaning depends on the runtime, which is no basis for an expiry.
6
+ const ISO_DATE = /^\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+-]\d{2}:\d{2}))?$/;
7
+ export const waiverEntrySchema = z
8
+ .object({
9
+ checkId: z.string().trim().min(1, 'checkId is required'),
10
+ findingId: z.string().trim().min(1).optional(),
11
+ entity: z.string().trim().min(1, 'entity is required'),
12
+ reason: z.string().trim().min(5, 'reason must be at least 5 characters'),
13
+ approvedBy: z.string().trim().min(3, 'approvedBy is required'),
14
+ expiresAt: z
15
+ .string()
16
+ .regex(ISO_DATE, 'expiresAt must be an ISO 8601 date (2027-03-31) or timestamp')
17
+ .refine((val) => !Number.isNaN(Date.parse(val)), { message: 'expiresAt is not a real date' }),
18
+ acknowledgeCritical: z.boolean().optional(),
19
+ })
20
+ .strict();
21
+ export const waiversConfigSchema = z
22
+ .object({
23
+ $schema: z.string().optional(),
24
+ _comment: z.string().optional(),
25
+ waivers: z.array(waiverEntrySchema),
26
+ })
27
+ .strict();
28
+ //# sourceMappingURL=WaiverModel.js.map
@@ -0,0 +1,22 @@
1
+ import type { Finding } from '../findings/Finding.js';
2
+ import type { WaiverLoader } from './WaiverLoader.js';
3
+ export interface ApplyWaiversResult {
4
+ findings: Finding[];
5
+ waivedFindings: Finding[];
6
+ activeWaiverCount: number;
7
+ expiredWaiverCount: number;
8
+ /** Waivers that matched a CRITICAL finding without acknowledgeCritical, and so were not applied. */
9
+ unacknowledgedCriticalCount: number;
10
+ }
11
+ /**
12
+ * Marks findings covered by an approved, unexpired waiver as `waived`, which removes them from the
13
+ * score and from --fail-on. A finding with affected items is waived only when every item is
14
+ * covered; otherwise each covered item is annotated and the finding stays active. A finding with
15
+ * no affected items is matched by its own id.
16
+ *
17
+ * A CRITICAL finding is waived only when the waiver sets acknowledgeCritical, so accepting the
18
+ * most severe risks is always a deliberate, visible choice. Waived findings still take part in
19
+ * attack-chain correlation: accepting one weakness does not accept the path it forms with others.
20
+ */
21
+ export declare function applyWaivers(findings: Finding[], loader: WaiverLoader): ApplyWaiversResult;
22
+ //# sourceMappingURL=applyWaivers.d.ts.map
@@ -0,0 +1,85 @@
1
+ /**
2
+ * Marks findings covered by an approved, unexpired waiver as `waived`, which removes them from the
3
+ * score and from --fail-on. A finding with affected items is waived only when every item is
4
+ * covered; otherwise each covered item is annotated and the finding stays active. A finding with
5
+ * no affected items is matched by its own id.
6
+ *
7
+ * A CRITICAL finding is waived only when the waiver sets acknowledgeCritical, so accepting the
8
+ * most severe risks is always a deliberate, visible choice. Waived findings still take part in
9
+ * attack-chain correlation: accepting one weakness does not accept the path it forms with others.
10
+ */
11
+ export function applyWaivers(findings, loader) {
12
+ const result = {
13
+ findings,
14
+ waivedFindings: [],
15
+ activeWaiverCount: 0,
16
+ expiredWaiverCount: 0,
17
+ unacknowledgedCriticalCount: 0,
18
+ };
19
+ if (loader.waivers.length === 0)
20
+ return result;
21
+ const outcome = (f, w) => {
22
+ if (w.isExpired)
23
+ return 'expired';
24
+ if (f.riskLevel === 'CRITICAL' && w.acknowledgeCritical !== true)
25
+ return 'critical-unacknowledged';
26
+ return 'waived';
27
+ };
28
+ const count = (o) => {
29
+ if (o === 'waived')
30
+ result.activeWaiverCount++;
31
+ else if (o === 'expired')
32
+ result.expiredWaiverCount++;
33
+ else
34
+ result.unacknowledgedCriticalCount++;
35
+ };
36
+ const tag = (o, w) => o === 'waived'
37
+ ? `[WAIVED: ${w.reason} (approved by ${w.approvedBy}, expires ${w.expiresAt})]`
38
+ : o === 'expired'
39
+ ? `[WAIVER EXPIRED] (expired ${w.expiresAt})`
40
+ : '[WAIVER NOT APPLIED: CRITICAL findings need acknowledgeCritical]';
41
+ const processed = [];
42
+ for (const f of findings) {
43
+ if (f.passed || f.inconclusive) {
44
+ processed.push(f);
45
+ continue;
46
+ }
47
+ const checkId = f.checkId ?? '';
48
+ if (f.affectedItems && f.affectedItems.length > 0) {
49
+ let waivedItems = 0;
50
+ const items = f.affectedItems.map((item) => {
51
+ const w = loader.findMatchingWaiver(checkId, f.id, item.label);
52
+ if (!w)
53
+ return item;
54
+ const o = outcome(f, w);
55
+ count(o);
56
+ if (o === 'waived')
57
+ waivedItems++;
58
+ return { ...item, note: item.note ? `${tag(o, w)} ${item.note}` : tag(o, w) };
59
+ });
60
+ const updated = { ...f, affectedItems: items };
61
+ if (waivedItems === f.affectedItems.length) {
62
+ updated.waived = true;
63
+ result.waivedFindings.push(updated);
64
+ }
65
+ processed.push(updated);
66
+ continue;
67
+ }
68
+ const w = loader.findMatchingWaiver(checkId, f.id, f.id);
69
+ if (!w) {
70
+ processed.push(f);
71
+ continue;
72
+ }
73
+ const o = outcome(f, w);
74
+ count(o);
75
+ const updated = { ...f, detail: `${tag(o, w)} ${f.detail}` };
76
+ if (o === 'waived') {
77
+ updated.waived = true;
78
+ result.waivedFindings.push(updated);
79
+ }
80
+ processed.push(updated);
81
+ }
82
+ result.findings = processed;
83
+ return result;
84
+ }
85
+ //# sourceMappingURL=applyWaivers.js.map
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@cclabsnz/sf-audit",
3
- "version": "1.16.0",
4
- "description": "Read-only Salesforce security audit for the sf CLI: 93 checks, attack-chain correlation, A-F risk grading, compliance mapping, free EventLogFile capture, and Guest User Anomaly investigation.",
3
+ "version": "1.17.0",
4
+ "description": "Read-only Salesforce security audit for the sf CLI: 109 checks, attack-chain correlation, A-F risk grading, compliance mapping, free EventLogFile capture, and Guest User Anomaly investigation.",
5
5
  "keywords": [
6
6
  "salesforce",
7
7
  "salesforce-cli",
@@ -46,7 +46,7 @@
46
46
  "test:jest": "node --experimental-vm-modules node_modules/jest/bin/jest.js --passWithNoTests"
47
47
  },
48
48
  "dependencies": {
49
- "@cclabsnz/sf-core": "^0.3.0",
49
+ "@cclabsnz/sf-core": "^0.11.0",
50
50
  "@oclif/core": "^4",
51
51
  "@salesforce/core": "^9.3.0",
52
52
  "@salesforce/sf-plugins-core": "^13",