@cclabsnz/sf-audit 1.0.1 → 1.1.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 (149) hide show
  1. package/README.md +75 -0
  2. package/lib/api/ToolingClientImpl.js +5 -2
  3. package/lib/chains/AttackChain.d.ts +20 -0
  4. package/lib/chains/AttackChain.js +2 -0
  5. package/lib/chains/Capability.d.ts +7 -0
  6. package/lib/chains/Capability.js +11 -0
  7. package/lib/chains/CapabilityRegistry.d.ts +18 -0
  8. package/lib/chains/CapabilityRegistry.js +53 -0
  9. package/lib/chains/ChainEngine.d.ts +13 -0
  10. package/lib/chains/ChainEngine.js +137 -0
  11. package/lib/chains/namedChains.d.ts +14 -0
  12. package/lib/chains/namedChains.js +99 -0
  13. package/lib/checks/CheckEngine.js +33 -5
  14. package/lib/checks/impl/AnonymousApexAuditCheck.d.ts +10 -0
  15. package/lib/checks/impl/AnonymousApexAuditCheck.js +106 -0
  16. package/lib/checks/impl/ApexCrudFLSCheck.d.ts +11 -0
  17. package/lib/checks/impl/ApexCrudFLSCheck.js +98 -0
  18. package/lib/checks/impl/ApexLoggingCheck.d.ts +11 -0
  19. package/lib/checks/impl/ApexLoggingCheck.js +124 -0
  20. package/lib/checks/impl/ApexRestEndpointCheck.d.ts +11 -0
  21. package/lib/checks/impl/ApexRestEndpointCheck.js +94 -0
  22. package/lib/checks/impl/ApexSharingCheck.js +29 -0
  23. package/lib/checks/impl/ApiClientPermissionCheck.d.ts +10 -0
  24. package/lib/checks/impl/ApiClientPermissionCheck.js +59 -0
  25. package/lib/checks/impl/AuditTrailCheck.js +29 -0
  26. package/lib/checks/impl/CertificateExpiryCheck.d.ts +10 -0
  27. package/lib/checks/impl/CertificateExpiryCheck.js +123 -0
  28. package/lib/checks/impl/CodeSecurityCheck.d.ts +2 -1
  29. package/lib/checks/impl/CodeSecurityCheck.js +46 -6
  30. package/lib/checks/impl/ConnectedAppInactivityCheck.d.ts +11 -0
  31. package/lib/checks/impl/ConnectedAppInactivityCheck.js +86 -0
  32. package/lib/checks/impl/ConnectedAppScopeCheck.d.ts +10 -0
  33. package/lib/checks/impl/ConnectedAppScopeCheck.js +125 -0
  34. package/lib/checks/impl/ConnectedAppsCheck.d.ts +1 -0
  35. package/lib/checks/impl/ConnectedAppsCheck.js +37 -2
  36. package/lib/checks/impl/ContentLinksCheck.d.ts +10 -0
  37. package/lib/checks/impl/ContentLinksCheck.js +115 -0
  38. package/lib/checks/impl/CorsAllowlistCheck.d.ts +10 -0
  39. package/lib/checks/impl/CorsAllowlistCheck.js +80 -0
  40. package/lib/checks/impl/CspTrustedSitesCheck.d.ts +10 -0
  41. package/lib/checks/impl/CspTrustedSitesCheck.js +55 -0
  42. package/lib/checks/impl/CustomLabelsCredentialCheck.d.ts +10 -0
  43. package/lib/checks/impl/CustomLabelsCredentialCheck.js +97 -0
  44. package/lib/checks/impl/DataClassificationCheck.d.ts +10 -0
  45. package/lib/checks/impl/DataClassificationCheck.js +112 -0
  46. package/lib/checks/impl/DebugLogAccessCheck.d.ts +10 -0
  47. package/lib/checks/impl/DebugLogAccessCheck.js +81 -0
  48. package/lib/checks/impl/DeploymentIdentityCheck.d.ts +11 -0
  49. package/lib/checks/impl/DeploymentIdentityCheck.js +144 -0
  50. package/lib/checks/impl/EnhancedDomainsCheck.d.ts +10 -0
  51. package/lib/checks/impl/EnhancedDomainsCheck.js +84 -0
  52. package/lib/checks/impl/EscalationPermsCheck.d.ts +10 -0
  53. package/lib/checks/impl/EscalationPermsCheck.js +77 -0
  54. package/lib/checks/impl/EventMonitoringCheck.d.ts +11 -0
  55. package/lib/checks/impl/EventMonitoringCheck.js +84 -0
  56. package/lib/checks/impl/ExperienceCloudSiteCheck.d.ts +10 -0
  57. package/lib/checks/impl/ExperienceCloudSiteCheck.js +91 -0
  58. package/lib/checks/impl/FailedLoginCheck.d.ts +10 -0
  59. package/lib/checks/impl/FailedLoginCheck.js +122 -0
  60. package/lib/checks/impl/FieldHistoryTrackingCheck.d.ts +10 -0
  61. package/lib/checks/impl/FieldHistoryTrackingCheck.js +70 -0
  62. package/lib/checks/impl/FieldLevelSecurityCheck.js +28 -18
  63. package/lib/checks/impl/GuestExecutableApexCheck.d.ts +11 -0
  64. package/lib/checks/impl/GuestExecutableApexCheck.js +93 -0
  65. package/lib/checks/impl/GuestUserAccessCheck.js +74 -66
  66. package/lib/checks/impl/HardcodedCredentialsCheck.js +2 -2
  67. package/lib/checks/impl/HighAssuranceSessionCheck.d.ts +10 -0
  68. package/lib/checks/impl/HighAssuranceSessionCheck.js +103 -0
  69. package/lib/checks/impl/InactiveUsersCheck.js +38 -19
  70. package/lib/checks/impl/InstalledPackagesCheck.d.ts +10 -0
  71. package/lib/checks/impl/InstalledPackagesCheck.js +94 -0
  72. package/lib/checks/impl/IntegrationUsersCheck.d.ts +10 -0
  73. package/lib/checks/impl/IntegrationUsersCheck.js +108 -0
  74. package/lib/checks/impl/InternalUserMfaCheck.d.ts +10 -0
  75. package/lib/checks/impl/InternalUserMfaCheck.js +81 -0
  76. package/lib/checks/impl/IpRestrictionsCheck.js +86 -23
  77. package/lib/checks/impl/LegacyApiVersionCheck.d.ts +10 -0
  78. package/lib/checks/impl/LegacyApiVersionCheck.js +91 -0
  79. package/lib/checks/impl/MfaEnforcementCheck.d.ts +10 -0
  80. package/lib/checks/impl/MfaEnforcementCheck.js +76 -0
  81. package/lib/checks/impl/MfaMethodStrengthCheck.d.ts +11 -0
  82. package/lib/checks/impl/MfaMethodStrengthCheck.js +116 -0
  83. package/lib/checks/impl/MfaRegistrationCheck.d.ts +11 -0
  84. package/lib/checks/impl/MfaRegistrationCheck.js +95 -0
  85. package/lib/checks/impl/MyDomainLoginPolicyCheck.d.ts +10 -0
  86. package/lib/checks/impl/MyDomainLoginPolicyCheck.js +105 -0
  87. package/lib/checks/impl/NamedCredentialsCheck.js +37 -2
  88. package/lib/checks/impl/PermissionsCheck.js +67 -14
  89. package/lib/checks/impl/PublicGroupSharingCheck.js +20 -9
  90. package/lib/checks/impl/ReleaseUpdatesCheck.d.ts +10 -0
  91. package/lib/checks/impl/ReleaseUpdatesCheck.js +106 -0
  92. package/lib/checks/impl/ReportFolderAccessCheck.d.ts +10 -0
  93. package/lib/checks/impl/ReportFolderAccessCheck.js +54 -0
  94. package/lib/checks/impl/ScheduledApexCheck.d.ts +1 -0
  95. package/lib/checks/impl/ScheduledApexCheck.js +3 -0
  96. package/lib/checks/impl/SharingModelCheck.d.ts +1 -1
  97. package/lib/checks/impl/SharingModelCheck.js +103 -32
  98. package/lib/checks/impl/SiemIntegrationCheck.d.ts +11 -0
  99. package/lib/checks/impl/SiemIntegrationCheck.js +102 -0
  100. package/lib/checks/impl/SsoEnforcementCheck.d.ts +10 -0
  101. package/lib/checks/impl/SsoEnforcementCheck.js +90 -0
  102. package/lib/checks/impl/StandardProfilesCheck.d.ts +10 -0
  103. package/lib/checks/impl/StandardProfilesCheck.js +68 -0
  104. package/lib/checks/impl/TransactionSecurityPolicyCheck.d.ts +10 -0
  105. package/lib/checks/impl/TransactionSecurityPolicyCheck.js +62 -0
  106. package/lib/checks/impl/TrustedIPRangesCheck.d.ts +10 -0
  107. package/lib/checks/impl/TrustedIPRangesCheck.js +106 -0
  108. package/lib/checks/impl/UsersAndAdminsCheck.js +50 -20
  109. package/lib/checks/impl/VisualforceXssCheck.d.ts +11 -0
  110. package/lib/checks/impl/VisualforceXssCheck.js +150 -0
  111. package/lib/checks/registry.js +97 -12
  112. package/lib/commands/audit/diff.d.ts +17 -0
  113. package/lib/commands/audit/diff.js +76 -0
  114. package/lib/commands/audit/history.d.ts +15 -0
  115. package/lib/commands/audit/history.js +59 -0
  116. package/lib/commands/audit/security.js +6 -6
  117. package/lib/context/AuditCache.d.ts +20 -0
  118. package/lib/context/AuditContext.d.ts +0 -2
  119. package/lib/findings/AuditResult.d.ts +3 -0
  120. package/lib/findings/ComplianceMapping.d.ts +3 -0
  121. package/lib/findings/ComplianceMapping.js +75 -0
  122. package/lib/findings/Finding.d.ts +20 -0
  123. package/lib/findings/loadScoringConfig.js +9 -2
  124. package/lib/findings/scoring.d.ts +2 -1
  125. package/lib/findings/scoring.js +20 -7
  126. package/lib/history/AuditDiff.d.ts +26 -0
  127. package/lib/history/AuditDiff.js +2 -0
  128. package/lib/history/DiffEngine.d.ts +4 -0
  129. package/lib/history/DiffEngine.js +61 -0
  130. package/lib/history/HistoryStore.d.ts +11 -0
  131. package/lib/history/HistoryStore.js +56 -0
  132. package/lib/history/metricMeta.d.ts +9 -0
  133. package/lib/history/metricMeta.js +28 -0
  134. package/lib/index.d.ts +7 -1
  135. package/lib/index.js +2 -1
  136. package/lib/lib/wire.d.ts +1 -2
  137. package/lib/lib/wire.js +1 -2
  138. package/lib/renderers/DiffHtmlRenderer.d.ts +8 -0
  139. package/lib/renderers/DiffHtmlRenderer.js +164 -0
  140. package/lib/renderers/DiffJsonRenderer.d.ts +8 -0
  141. package/lib/renderers/DiffJsonRenderer.js +8 -0
  142. package/lib/renderers/DiffRenderer.d.ts +7 -0
  143. package/lib/renderers/DiffRenderer.js +2 -0
  144. package/lib/renderers/HistoryRenderer.d.ts +6 -0
  145. package/lib/renderers/HistoryRenderer.js +140 -0
  146. package/lib/renderers/HtmlRenderer.d.ts +1 -0
  147. package/lib/renderers/HtmlRenderer.js +354 -54
  148. package/lib/renderers/MarkdownRenderer.js +34 -1
  149. package/package.json +3 -3
@@ -0,0 +1,115 @@
1
+ // Links older than this with no expiry date are considered stale (SBS-FILE-003)
2
+ const STALE_DAYS = 90;
3
+ export class ContentLinksCheck {
4
+ id = 'content-links';
5
+ name = 'Content Distribution Links';
6
+ category = 'File Security';
7
+ description = 'SBS-FILE-001/002/003: audits public content links for missing expiry, missing passwords, and stale records';
8
+ async run(ctx) {
9
+ const findings = [];
10
+ const baseUrl = ctx.orgInfo.instanceUrl;
11
+ // Single query — fetches all data needed for FILE-001 (no expiry),
12
+ // FILE-002 (no password), and FILE-003 (stale links).
13
+ let records;
14
+ try {
15
+ records = await ctx.soql.queryAll(`SELECT Id, Name, ContentDocumentId, ExpiryDate, PasswordEnabled, CreatedDate
16
+ FROM ContentDistribution
17
+ WHERE IsPublic = true
18
+ ORDER BY CreatedDate ASC
19
+ LIMIT 500`);
20
+ }
21
+ catch {
22
+ findings.push({
23
+ id: 'content-links-inaccessible',
24
+ category: this.category,
25
+ riskLevel: 'INFO',
26
+ inconclusive: true,
27
+ title: 'Content distribution links could not be queried',
28
+ detail: 'SBS-FILE-001/002/003 require review of public content distribution links. ContentDistribution was not accessible with the current user permissions.',
29
+ remediation: 'Grant the audit user read access to ContentDistribution records to enable this check.',
30
+ });
31
+ return { findings };
32
+ }
33
+ if (records.length === 0) {
34
+ findings.push({
35
+ id: 'content-links-none',
36
+ category: this.category,
37
+ riskLevel: 'LOW',
38
+ passed: true,
39
+ title: 'No active public content distribution links found',
40
+ detail: 'SBS-FILE-001/002/003 govern the lifecycle of public content sharing links. No active public links were found in this org.',
41
+ remediation: 'Continue monitoring as files are shared externally.',
42
+ });
43
+ return { findings };
44
+ }
45
+ const staleThreshold = new Date(Date.now() - STALE_DAYS * 86_400_000);
46
+ const noExpiry = records.filter((r) => !r.ExpiryDate);
47
+ const noPassword = records.filter((r) => !r.PasswordEnabled);
48
+ const stale = records.filter((r) => !r.ExpiryDate && new Date(r.CreatedDate) < staleThreshold);
49
+ let hasPositiveFinding = false;
50
+ // SBS-FILE-001: all public content links must have an expiry date
51
+ if (noExpiry.length > 0) {
52
+ hasPositiveFinding = true;
53
+ findings.push({
54
+ id: 'content-links-no-expiry',
55
+ category: this.category,
56
+ riskLevel: noExpiry.length > 20 ? 'HIGH' : 'MEDIUM',
57
+ title: `${noExpiry.length} public content link(s) have no expiry date — SBS-FILE-001`,
58
+ detail: 'SBS-FILE-001 requires all public content distribution links to have an expiry date. Links without expiry remain active indefinitely, allowing anyone with the URL to continue accessing potentially sensitive documents even after the sharing purpose has ended.',
59
+ remediation: 'Set an expiry date on all active public links. Establish a policy requiring expiry dates when creating new content distribution links, and configure Salesforce to enforce expiry via the Content Distribution settings.',
60
+ affectedItems: noExpiry.slice(0, 50).map((r) => ({
61
+ label: r.Name,
62
+ url: `${baseUrl}/${r.ContentDocumentId}`,
63
+ note: `created: ${new Date(r.CreatedDate).toISOString().split('T')[0]} — set an expiry date`,
64
+ })),
65
+ });
66
+ }
67
+ // SBS-FILE-002: links sharing sensitive content should be password-protected
68
+ if (noPassword.length > 0) {
69
+ hasPositiveFinding = true;
70
+ findings.push({
71
+ id: 'content-links-no-password',
72
+ category: this.category,
73
+ riskLevel: 'LOW',
74
+ title: `${noPassword.length} public content link(s) are not password-protected — SBS-FILE-002`,
75
+ detail: 'SBS-FILE-002 recommends password-protecting public content sharing links, particularly for documents containing sensitive or confidential information. Links without a password can be accessed by anyone with the URL.',
76
+ remediation: 'Enable password protection for public content links that share sensitive content. Review each link to determine if the shared content warrants the additional protection layer.',
77
+ affectedItems: noPassword.slice(0, 50).map((r) => ({
78
+ label: r.Name,
79
+ url: `${baseUrl}/${r.ContentDocumentId}`,
80
+ note: `created: ${new Date(r.CreatedDate).toISOString().split('T')[0]} — assess whether password protection is needed`,
81
+ })),
82
+ });
83
+ }
84
+ // SBS-FILE-003: stale links (no expiry + older than threshold) must be cleaned up
85
+ if (stale.length > 0) {
86
+ hasPositiveFinding = true;
87
+ findings.push({
88
+ id: 'content-links-stale',
89
+ category: this.category,
90
+ riskLevel: 'MEDIUM',
91
+ title: `${stale.length} public content link(s) are over ${STALE_DAYS} days old with no expiry — SBS-FILE-003`,
92
+ detail: `SBS-FILE-003 requires periodic cleanup of public content sharing links. ${stale.length} link(s) were created more than ${STALE_DAYS} days ago and have no expiry date, meaning they have been publicly accessible indefinitely. These likely represent sharing relationships that are no longer active.`,
93
+ remediation: `Review and expire or delete all content links older than ${STALE_DAYS} days where the sharing purpose is no longer active. Establish a quarterly review process for all active content distribution links.`,
94
+ affectedItems: stale.slice(0, 50).map((r) => ({
95
+ label: r.Name,
96
+ url: `${baseUrl}/${r.ContentDocumentId}`,
97
+ note: `created: ${new Date(r.CreatedDate).toISOString().split('T')[0]} — review and expire or delete`,
98
+ })),
99
+ });
100
+ }
101
+ if (!hasPositiveFinding) {
102
+ findings.push({
103
+ id: 'content-links-ok',
104
+ category: this.category,
105
+ riskLevel: 'LOW',
106
+ passed: true,
107
+ title: `All ${records.length} public content link(s) have expiry dates configured`,
108
+ detail: 'SBS-FILE-001 requires all public content distribution links to have expiry dates. All active public links have an expiry date set.',
109
+ remediation: 'Continue monitoring as new content links are created. Consider enabling password protection for links sharing sensitive documents (SBS-FILE-002).',
110
+ });
111
+ }
112
+ return { findings };
113
+ }
114
+ }
115
+ //# sourceMappingURL=ContentLinksCheck.js.map
@@ -0,0 +1,10 @@
1
+ import type { AuditContext } from '../../context/AuditContext.js';
2
+ import type { SecurityCheck, CheckResult } from '../SecurityCheck.js';
3
+ export declare class CorsAllowlistCheck implements SecurityCheck {
4
+ readonly id = "cors-allowlist";
5
+ readonly name = "CORS Allowlist";
6
+ readonly category = "External Connectivity";
7
+ readonly description = "Detects wildcard or overly broad CORS allowlist origins that let malicious sites make authenticated browser requests";
8
+ run(ctx: AuditContext): Promise<CheckResult>;
9
+ }
10
+ //# sourceMappingURL=CorsAllowlistCheck.d.ts.map
@@ -0,0 +1,80 @@
1
+ export class CorsAllowlistCheck {
2
+ id = 'cors-allowlist';
3
+ name = 'CORS Allowlist';
4
+ category = 'External Connectivity';
5
+ description = 'Detects wildcard or overly broad CORS allowlist origins that let malicious sites make authenticated browser requests';
6
+ async run(ctx) {
7
+ const findings = [];
8
+ const setupUrl = `${ctx.orgInfo.instanceUrl}/lightning/setup/CorsWhitelistEntries/home`;
9
+ let rows;
10
+ try {
11
+ rows = await ctx.tooling.query('SELECT Id, UrlPattern FROM CorsWhitelistEntry');
12
+ }
13
+ catch (err) {
14
+ const msg = err instanceof Error ? err.message : String(err);
15
+ findings.push({
16
+ id: 'cors-allowlist-inaccessible',
17
+ category: this.category,
18
+ riskLevel: 'INFO',
19
+ inconclusive: true,
20
+ title: 'CORS allowlist could not be read',
21
+ detail: `The CorsWhitelistEntry Tooling query was not accessible: ${msg}`,
22
+ remediation: 'Grant the audit user "View Setup and Configuration", then re-run the audit.',
23
+ });
24
+ return { findings };
25
+ }
26
+ if (rows.length === 0) {
27
+ findings.push({
28
+ id: 'cors-allowlist-none',
29
+ category: this.category,
30
+ riskLevel: 'LOW',
31
+ passed: true,
32
+ title: 'No CORS allowlist entries configured',
33
+ detail: 'No cross-origin allowlist entries exist, so browser-based cross-origin token theft via CORS is not a concern.',
34
+ remediation: 'If CORS entries are added later, allow only exact, fully-qualified HTTPS origins.',
35
+ });
36
+ return { findings };
37
+ }
38
+ // A pattern is a bare wildcard (https://* or *) if it has no host after the scheme.
39
+ const isFullWildcard = (p) => /^(https?:\/\/)?\*$/i.test(p.trim());
40
+ // A pattern is a broad subdomain wildcard (https://*.example.com).
41
+ const isSubdomainWildcard = (p) => /\*\./.test(p) || /\*/.test(p);
42
+ const wildcard = rows.filter((r) => isFullWildcard(r.UrlPattern));
43
+ const broad = rows.filter((r) => !isFullWildcard(r.UrlPattern) && isSubdomainWildcard(r.UrlPattern));
44
+ if (wildcard.length > 0) {
45
+ findings.push({
46
+ id: 'cors-wildcard-origin',
47
+ category: this.category,
48
+ riskLevel: 'HIGH',
49
+ title: `${wildcard.length} CORS allowlist entry(ies) use a full wildcard origin`,
50
+ detail: 'A wildcard CORS origin lets ANY website make authenticated cross-origin requests to your org from a logged-in user\'s browser and read the responses — enabling session-scoped data and token theft.',
51
+ remediation: 'Replace wildcard origins with exact, fully-qualified HTTPS origins for each trusted application.',
52
+ affectedItems: wildcard.map((r) => ({ label: r.UrlPattern, url: setupUrl, note: 'Full wildcard — remove immediately' })),
53
+ });
54
+ }
55
+ if (broad.length > 0) {
56
+ findings.push({
57
+ id: 'cors-broad-origin',
58
+ category: this.category,
59
+ riskLevel: 'MEDIUM',
60
+ title: `${broad.length} CORS allowlist entry(ies) use a broad subdomain wildcard`,
61
+ detail: 'Subdomain-wildcard CORS origins trust every current and future subdomain, widening the set of sites that can make authenticated cross-origin requests. A single compromised or attacker-controlled subdomain can steal session-scoped data.',
62
+ remediation: 'Pin CORS origins to the exact subdomains that need access rather than a wildcard.',
63
+ affectedItems: broad.map((r) => ({ label: r.UrlPattern, url: setupUrl, note: 'Broad wildcard — narrow to exact origins' })),
64
+ });
65
+ }
66
+ if (wildcard.length === 0 && broad.length === 0) {
67
+ findings.push({
68
+ id: 'cors-allowlist-ok',
69
+ category: this.category,
70
+ riskLevel: 'LOW',
71
+ passed: true,
72
+ title: `${rows.length} CORS allowlist entry(ies) all use exact origins`,
73
+ detail: 'All CORS allowlist entries specify exact origins with no wildcards.',
74
+ remediation: 'Continue to avoid wildcard CORS origins.',
75
+ });
76
+ }
77
+ return { findings };
78
+ }
79
+ }
80
+ //# sourceMappingURL=CorsAllowlistCheck.js.map
@@ -0,0 +1,10 @@
1
+ import type { SecurityCheck, CheckResult } from '../SecurityCheck.js';
2
+ import type { AuditContext } from '../../context/AuditContext.js';
3
+ export declare class CspTrustedSitesCheck implements SecurityCheck {
4
+ readonly id = "csp-trusted-sites";
5
+ readonly name = "CSP Trusted Sites";
6
+ readonly category = "Network Security";
7
+ readonly description = "Checks Content Security Policy trusted sites for insecure HTTP endpoints that allow mixed-content loading.";
8
+ run(ctx: AuditContext): Promise<CheckResult>;
9
+ }
10
+ //# sourceMappingURL=CspTrustedSitesCheck.d.ts.map
@@ -0,0 +1,55 @@
1
+ export class CspTrustedSitesCheck {
2
+ id = 'csp-trusted-sites';
3
+ name = 'CSP Trusted Sites';
4
+ category = 'Network Security';
5
+ description = 'Checks Content Security Policy trusted sites for insecure HTTP endpoints that allow mixed-content loading.';
6
+ async run(ctx) {
7
+ const sites = await ctx.soql.queryAll(`SELECT Id, EndpointUrl, Context, IsActive FROM CspTrustedSite WHERE IsActive = true`);
8
+ if (sites.length === 0) {
9
+ return {
10
+ findings: [{
11
+ id: 'csp-trusted-sites-none',
12
+ category: this.category,
13
+ riskLevel: 'INFO',
14
+ passed: true,
15
+ title: 'No active CSP Trusted Sites configured',
16
+ detail: 'No active CSP Trusted Sites are configured. Salesforce applies default Content Security Policy headers. Add trusted sites only when loading external resources in Lightning components.',
17
+ remediation: 'No action required. When adding external resources, use HTTPS endpoints only.',
18
+ }],
19
+ };
20
+ }
21
+ const insecure = sites.filter((s) => s.EndpointUrl.toLowerCase().startsWith('http://'));
22
+ if (insecure.length === 0) {
23
+ return {
24
+ findings: [{
25
+ id: 'csp-trusted-sites-pass',
26
+ category: this.category,
27
+ riskLevel: 'INFO',
28
+ title: `CSP Trusted Sites: all ${sites.length} active entries use HTTPS`,
29
+ detail: `All ${sites.length} active CSP trusted site(s) use secure HTTPS endpoints.`,
30
+ remediation: 'No action required.',
31
+ passed: true,
32
+ }],
33
+ };
34
+ }
35
+ return {
36
+ findings: [{
37
+ id: 'csp-trusted-sites-insecure',
38
+ category: this.category,
39
+ riskLevel: 'HIGH',
40
+ title: `CSP Trusted Sites: ${insecure.length} insecure HTTP endpoint(s)`,
41
+ detail: `${insecure.length} of ${sites.length} active CSP Trusted Site(s) use unencrypted HTTP URLs. ` +
42
+ `These allow mixed-content loading, enabling man-in-the-middle attacks where injected scripts ` +
43
+ `can execute in the Salesforce Lightning context.`,
44
+ remediation: 'Update each affected CSP Trusted Site to use HTTPS. ' +
45
+ 'Navigate to Setup → Security → CSP Trusted Sites and edit each entry.',
46
+ affectedItems: insecure.map((s) => ({
47
+ label: s.EndpointUrl,
48
+ note: `Context: ${s.Context}`,
49
+ url: `${ctx.orgInfo.instanceUrl}/lightning/setup/ContentSecurityPolicy/home`,
50
+ })),
51
+ }],
52
+ };
53
+ }
54
+ }
55
+ //# sourceMappingURL=CspTrustedSitesCheck.js.map
@@ -0,0 +1,10 @@
1
+ import type { AuditContext } from '../../context/AuditContext.js';
2
+ import type { SecurityCheck, CheckResult } from '../SecurityCheck.js';
3
+ export declare class CustomLabelsCredentialCheck implements SecurityCheck {
4
+ readonly id = "custom-labels-credential";
5
+ readonly name = "Custom Labels Credential Exposure";
6
+ readonly category = "Secrets Management";
7
+ readonly description = "Scans Custom Labels for API keys, tokens, and credentials \u2014 labels are globally readable by all authenticated users via {!$Label.X} merge fields";
8
+ run(ctx: AuditContext): Promise<CheckResult>;
9
+ }
10
+ //# sourceMappingURL=CustomLabelsCredentialCheck.d.ts.map
@@ -0,0 +1,97 @@
1
+ // Label names that suggest credential storage
2
+ const SENSITIVE_NAME_RE = /api[_-]?key|secret[_-]?key|access[_-]?token|auth[_-]?token|password|passphrase|private[_-]?key|credential|client[_-]?secret|bearer|webhook[_-]?secret/i;
3
+ // Value patterns that look like secrets (long base64/hex, Bearer tokens, etc.)
4
+ const SECRET_VALUE_RE = /^(?:Bearer\s+[A-Za-z0-9+/=_-]{20,}|[A-Fa-f0-9]{32,}|[A-Za-z0-9+/]{40,}={0,2}|sk_[a-zA-Z0-9]{20,}|AKIA[A-Z0-9]{16}|AIza[A-Za-z0-9_-]{35})/;
5
+ export class CustomLabelsCredentialCheck {
6
+ id = 'custom-labels-credential';
7
+ name = 'Custom Labels Credential Exposure';
8
+ category = 'Secrets Management';
9
+ description = 'Scans Custom Labels for API keys, tokens, and credentials — labels are globally readable by all authenticated users via {!$Label.X} merge fields';
10
+ async run(ctx) {
11
+ const findings = [];
12
+ const baseUrl = ctx.orgInfo.instanceUrl;
13
+ const setupUrl = `${baseUrl}/lightning/setup/ExternalStrings/home`;
14
+ let labels;
15
+ try {
16
+ labels = await ctx.tooling.query(`SELECT Name, Value FROM ExternalString WHERE NamespacePrefix = null LIMIT 500`);
17
+ }
18
+ catch {
19
+ findings.push({
20
+ id: 'custom-labels-credential-inaccessible',
21
+ category: this.category,
22
+ riskLevel: 'INFO',
23
+ inconclusive: true,
24
+ title: 'Custom Labels could not be queried — credential scan skipped',
25
+ detail: 'The Tooling API ExternalString query was not accessible. This may indicate the audit user lacks Tooling API access.',
26
+ remediation: 'Grant Tooling API access to the audit user and re-run.',
27
+ });
28
+ return { findings };
29
+ }
30
+ if (labels.length === 0) {
31
+ findings.push({
32
+ id: 'custom-labels-credential-none',
33
+ category: this.category,
34
+ riskLevel: 'LOW',
35
+ passed: true,
36
+ title: 'No custom labels found in org namespace',
37
+ detail: 'No custom labels were found in the org namespace.',
38
+ remediation: 'Continue using Named Credentials and Custom Metadata (protected) for secrets storage.',
39
+ });
40
+ return { findings };
41
+ }
42
+ const nameMatches = [];
43
+ const valueMatches = [];
44
+ for (const label of labels) {
45
+ const value = label.Value ?? '';
46
+ if (SENSITIVE_NAME_RE.test(label.Name)) {
47
+ nameMatches.push(label);
48
+ }
49
+ else if (SECRET_VALUE_RE.test(value.trim())) {
50
+ valueMatches.push(label);
51
+ }
52
+ }
53
+ if (nameMatches.length > 0) {
54
+ findings.push({
55
+ id: 'custom-labels-credential-name-match',
56
+ category: this.category,
57
+ riskLevel: 'HIGH',
58
+ title: `${nameMatches.length} Custom Label(s) have names suggesting credential storage`,
59
+ detail: `Custom Labels with names like "ApiKey", "ClientSecret", or "AuthToken" strongly suggest they store sensitive credentials. This is a critical misconfiguration: Custom Labels are globally readable by every authenticated Salesforce user via the \`{!\$Label.X}\` merge field in Visualforce pages, Flows, and Apex. Any user who can query the Tooling API or view source markup containing the merge field can read the label value — including attacker accounts, compromised users, and over-permissioned portal users. Unlike Named Credentials or Protected Custom Metadata, Custom Labels have no access control.`,
60
+ remediation: 'Migrate these credentials to Named Credentials or Protected Custom Metadata (visibility: "Protected"). Named Credentials encrypt stored values and provide managed authentication. Protected Custom Metadata is only accessible from the managed package — not from arbitrary user queries.',
61
+ affectedItems: nameMatches.map((l) => ({
62
+ label: l.Name,
63
+ url: setupUrl,
64
+ note: `Name indicates credential — migrate to Named Credential or Protected Custom Metadata`,
65
+ })),
66
+ });
67
+ }
68
+ if (valueMatches.length > 0) {
69
+ findings.push({
70
+ id: 'custom-labels-credential-value-match',
71
+ category: this.category,
72
+ riskLevel: 'HIGH',
73
+ title: `${valueMatches.length} Custom Label(s) contain values matching known secret patterns`,
74
+ detail: `The values of these Custom Labels match patterns for API keys (AWS AKIA*, Google AIza*, Stripe sk_*, hex/base64 tokens, Bearer tokens). These are globally readable by all authenticated users. Even if the label name is innocuous, storing secrets in Custom Labels violates secrets management best practices and can lead to credential theft by any user with org access.`,
75
+ remediation: 'Rotate any exposed credentials immediately. Migrate storage to Named Credentials or Protected Custom Metadata. Audit all code referencing these labels to understand the blast radius if credentials are already compromised.',
76
+ affectedItems: valueMatches.map((l) => ({
77
+ label: l.Name,
78
+ url: setupUrl,
79
+ note: `Value matches secret pattern — rotate credential and migrate storage`,
80
+ })),
81
+ });
82
+ }
83
+ if (nameMatches.length === 0 && valueMatches.length === 0) {
84
+ findings.push({
85
+ id: 'custom-labels-credential-ok',
86
+ category: this.category,
87
+ riskLevel: 'LOW',
88
+ passed: true,
89
+ title: `${labels.length} Custom Label(s) scanned — no obvious credential patterns found`,
90
+ detail: `All ${labels.length} custom labels were scanned for name and value patterns indicating credential storage. No obvious secrets were found. Note: custom labels with obfuscated names or non-standard encoding may not be detected.`,
91
+ remediation: 'Maintain the practice of using Named Credentials or Protected Custom Metadata for all secrets. Periodically review Custom Labels for new entries that may inadvertently store sensitive values.',
92
+ });
93
+ }
94
+ return { findings };
95
+ }
96
+ }
97
+ //# sourceMappingURL=CustomLabelsCredentialCheck.js.map
@@ -0,0 +1,10 @@
1
+ import type { AuditContext } from '../../context/AuditContext.js';
2
+ import type { SecurityCheck, CheckResult } from '../SecurityCheck.js';
3
+ export declare class DataClassificationCheck implements SecurityCheck {
4
+ readonly id = "data-classification";
5
+ readonly name = "Data Classification and Encryption";
6
+ readonly category = "Data Security";
7
+ readonly description = "SBS-DATA-001/002/003: checks Salesforce field data classification usage and Shield Platform Encryption";
8
+ run(ctx: AuditContext): Promise<CheckResult>;
9
+ }
10
+ //# sourceMappingURL=DataClassificationCheck.d.ts.map
@@ -0,0 +1,112 @@
1
+ // Key objects to check for data classification (SBS-DATA-001/002)
2
+ const CLASSIFICATION_OBJECTS = [
3
+ 'Account', 'Contact', 'Lead', 'Opportunity', 'Case', 'Contract', 'User',
4
+ ];
5
+ export class DataClassificationCheck {
6
+ id = 'data-classification';
7
+ name = 'Data Classification and Encryption';
8
+ category = 'Data Security';
9
+ description = 'SBS-DATA-001/002/003: checks Salesforce field data classification usage and Shield Platform Encryption';
10
+ async run(ctx) {
11
+ const findings = [];
12
+ const baseUrl = ctx.orgInfo.instanceUrl;
13
+ const objectList = CLASSIFICATION_OBJECTS.map((o) => `'${o}'`).join(', ');
14
+ // Q1 (Tooling API): count fields with a ComplianceGroup set per key object.
15
+ // Salesforce Data Classification sets ComplianceGroup on FieldDefinition to mark fields
16
+ // as PII, PCI, HIPAA, GDPR, etc. Objects with zero classified fields are uncovered.
17
+ let classifiedMap = new Map();
18
+ let classificationQueryFailed = false;
19
+ try {
20
+ const classResult = await ctx.tooling.query(`SELECT EntityDefinition.QualifiedApiName objectName, COUNT(Id) classifiedCount
21
+ FROM FieldDefinition
22
+ WHERE EntityDefinition.QualifiedApiName IN (${objectList})
23
+ AND ComplianceGroup != null
24
+ GROUP BY EntityDefinition.QualifiedApiName`);
25
+ for (const r of classResult) {
26
+ classifiedMap.set(r.objectName, r.classifiedCount ?? 0);
27
+ }
28
+ }
29
+ catch {
30
+ classificationQueryFailed = true;
31
+ }
32
+ // Q2 (SOQL): check for Shield Platform Encryption keys.
33
+ // EncryptionKey records indicate Shield is licensed and active.
34
+ let encryptionEnabled = false;
35
+ let encryptionKeyCount = 0;
36
+ try {
37
+ const encResult = await ctx.soql.query('SELECT Id, DeveloperName FROM EncryptionKey LIMIT 10');
38
+ encryptionKeyCount = encResult.records.length;
39
+ encryptionEnabled = encryptionKeyCount > 0;
40
+ }
41
+ catch {
42
+ // EncryptionKey inaccessible — Shield not licensed or no permission to read keys
43
+ }
44
+ // SBS-DATA-001/002: data classification coverage
45
+ if (classificationQueryFailed) {
46
+ findings.push({
47
+ id: 'data-classification-inconclusive',
48
+ category: this.category,
49
+ riskLevel: 'INFO',
50
+ inconclusive: true,
51
+ title: 'Data classification status could not be determined — Tooling API access needed',
52
+ detail: 'SBS-DATA-001 requires all data fields to be classified by sensitivity. SBS-DATA-002 requires PII fields to be explicitly identified. The Tooling API FieldDefinition query was not accessible with the current user permissions.',
53
+ remediation: 'Enable Tooling API access for the audit user, or manually review data classification in Setup → Data Management → Data Classification for Account, Contact, Lead, Opportunity, Case, Contract, and User.',
54
+ });
55
+ }
56
+ else {
57
+ const classifiedObjects = CLASSIFICATION_OBJECTS.filter((o) => (classifiedMap.get(o) ?? 0) > 0);
58
+ const unclassifiedObjects = CLASSIFICATION_OBJECTS.filter((o) => (classifiedMap.get(o) ?? 0) === 0);
59
+ const totalClassifiedFields = [...classifiedMap.values()].reduce((a, b) => a + b, 0);
60
+ if (unclassifiedObjects.length === 0) {
61
+ findings.push({
62
+ id: 'data-classification-ok',
63
+ category: this.category,
64
+ riskLevel: 'LOW',
65
+ passed: true,
66
+ title: `Data classification configured on all ${CLASSIFICATION_OBJECTS.length} key objects — SBS-DATA-001/002`,
67
+ detail: `SBS-DATA-001 requires data to be classified by sensitivity and SBS-DATA-002 requires PII to be identified. All checked objects have at least one classified field (total: ${totalClassifiedFields} classified fields across ${classifiedObjects.length} objects).`,
68
+ remediation: 'Extend classification to any custom objects that store sensitive or personally identifiable data.',
69
+ });
70
+ }
71
+ else {
72
+ findings.push({
73
+ id: 'data-classification-missing',
74
+ category: this.category,
75
+ riskLevel: unclassifiedObjects.length >= 4 ? 'HIGH' : 'MEDIUM',
76
+ title: `${unclassifiedObjects.length} of ${CLASSIFICATION_OBJECTS.length} key object(s) have no data classification — SBS-DATA-001/002`,
77
+ detail: `SBS-DATA-001 requires all data to be classified by sensitivity and SBS-DATA-002 requires PII to be identified. ${unclassifiedObjects.length} key object(s) have no fields with a Compliance Group set: ${unclassifiedObjects.join(', ')}. ${classifiedObjects.length > 0 ? `Objects with classification already configured: ${classifiedObjects.map((o) => `${o} (${classifiedMap.get(o)} field(s))`).join(', ')}.` : ''}`,
78
+ remediation: 'Enable and configure the Salesforce Data Classification feature in Setup → Data Management → Data Classification. Assign compliance groups (PII, PCI, HIPAA, GDPR, etc.) to sensitive fields on all objects that store personal or regulated data. Prioritise email, phone, address, financial, and health-related fields.',
79
+ affectedItems: unclassifiedObjects.map((name) => ({
80
+ label: name,
81
+ url: `${baseUrl}/lightning/setup/ObjectManager/${name}/FieldsAndRelationships/view`,
82
+ note: 'No fields classified — configure Compliance Group via Data Classification in Setup',
83
+ })),
84
+ });
85
+ }
86
+ }
87
+ // SBS-DATA-003: encryption at rest
88
+ if (encryptionEnabled) {
89
+ findings.push({
90
+ id: 'data-encryption-shield-active',
91
+ category: this.category,
92
+ riskLevel: 'LOW',
93
+ passed: true,
94
+ title: `Shield Platform Encryption active — ${encryptionKeyCount} encryption key(s) found — SBS-DATA-003`,
95
+ detail: `SBS-DATA-003 requires sensitive data to be encrypted at rest commensurate with its classification. ${encryptionKeyCount} Shield Platform Encryption key(s) are configured, indicating encryption-at-rest is in use.`,
96
+ remediation: 'Verify encryption is applied to all fields classified as sensitive or PII. Review the Encryption Statistics page in Setup → Security → Platform Encryption to confirm field-level coverage.',
97
+ });
98
+ }
99
+ else {
100
+ findings.push({
101
+ id: 'data-encryption-not-detected',
102
+ category: this.category,
103
+ riskLevel: 'MEDIUM',
104
+ title: 'Shield Platform Encryption not detected — SBS-DATA-003',
105
+ detail: 'SBS-DATA-003 requires data at rest to be encrypted in line with its assigned classification. No Shield Platform Encryption keys were found, indicating either Shield is not licensed or encryption has not been configured for this org.',
106
+ remediation: 'Evaluate Salesforce Shield Platform Encryption for fields classified as sensitive or PII. If Shield is not available in your edition, document the compensating control (e.g., Classic Encryption for specific fields, or infrastructure-level disk encryption), and assess whether it meets the intent of SBS-DATA-003.',
107
+ });
108
+ }
109
+ return { findings };
110
+ }
111
+ }
112
+ //# sourceMappingURL=DataClassificationCheck.js.map
@@ -0,0 +1,10 @@
1
+ import type { AuditContext } from '../../context/AuditContext.js';
2
+ import type { SecurityCheck, CheckResult } from '../SecurityCheck.js';
3
+ export declare class DebugLogAccessCheck implements SecurityCheck {
4
+ readonly id = "debug-log-access";
5
+ readonly name = "Active Debug Log Traces";
6
+ readonly category = "Security Controls";
7
+ readonly description = "Identifies active TraceFlag records that capture debug logs, including high-detail traces that expose sensitive field values";
8
+ run(ctx: AuditContext): Promise<CheckResult>;
9
+ }
10
+ //# sourceMappingURL=DebugLogAccessCheck.d.ts.map
@@ -0,0 +1,81 @@
1
+ const HIGH_DETAIL_LEVELS = new Set(['FINE', 'FINER', 'FINEST']);
2
+ export class DebugLogAccessCheck {
3
+ id = 'debug-log-access';
4
+ name = 'Active Debug Log Traces';
5
+ category = 'Security Controls';
6
+ description = 'Identifies active TraceFlag records that capture debug logs, including high-detail traces that expose sensitive field values';
7
+ async run(ctx) {
8
+ const findings = [];
9
+ const baseUrl = ctx.orgInfo.instanceUrl;
10
+ const setupUrl = `${baseUrl}/lightning/setup/ApexDebugLog/home`;
11
+ let traces = [];
12
+ try {
13
+ const result = await ctx.soql.query(`SELECT Id, TracedEntityId, LogType, ExpirationDate,
14
+ DebugLevel.DeveloperName, DebugLevel.ApexCode
15
+ FROM TraceFlag
16
+ WHERE ExpirationDate >= TODAY
17
+ ORDER BY ExpirationDate ASC
18
+ LIMIT 200`);
19
+ traces = result.records;
20
+ }
21
+ catch {
22
+ findings.push({
23
+ id: 'debug-log-inaccessible',
24
+ category: this.category,
25
+ riskLevel: 'INFO',
26
+ inconclusive: true,
27
+ title: 'TraceFlag records could not be retrieved — active debug traces cannot be verified',
28
+ detail: 'The TraceFlag object was not accessible. This may indicate the audit user lacks API access or the required permission to manage debug logs.',
29
+ remediation: 'Grant "Manage Users" or "View All Data" permission to the audit user, or review active debug traces manually in Setup → Debug Logs.',
30
+ affectedItems: [{ label: 'Debug Log Setup', url: setupUrl }],
31
+ });
32
+ return { findings };
33
+ }
34
+ if (traces.length === 0) {
35
+ findings.push({
36
+ id: 'debug-log-none',
37
+ category: this.category,
38
+ riskLevel: 'LOW',
39
+ passed: true,
40
+ title: 'No active debug log traces found',
41
+ detail: 'No active TraceFlag records were found. No users or classes are currently being traced, so no sensitive data is being captured in debug logs.',
42
+ remediation: 'Continue monitoring. Remove debug traces promptly after troubleshooting sessions complete.',
43
+ });
44
+ return { findings };
45
+ }
46
+ const userDebugTraces = traces.filter((t) => t.LogType === 'USER_DEBUG');
47
+ const highDetailTraces = traces.filter((t) => t.DebugLevel !== null && HIGH_DETAIL_LEVELS.has(t.DebugLevel.ApexCode));
48
+ if (userDebugTraces.length > 0) {
49
+ findings.push({
50
+ id: 'debug-log-active-traces',
51
+ category: this.category,
52
+ riskLevel: 'HIGH',
53
+ title: `${userDebugTraces.length} active USER_DEBUG trace flag(s) are capturing all user activity`,
54
+ detail: `In production, active debug traces on users should be reviewed — they capture sensitive field values and are accessible to administrators. USER_DEBUG traces record all DML operations, SOQL queries, and field values for the traced user, including data from sensitive objects such as financial records, PII, and health information. Debug logs are visible to any org admin and are not access-controlled at the record level.`,
55
+ remediation: 'Remove all USER_DEBUG trace flags that are not actively being used for an approved troubleshooting session. Establish a policy requiring trace flags to be removed within 24 hours of creation. Consider using a dedicated sandbox for debugging rather than production.',
56
+ affectedItems: userDebugTraces.map((t) => ({
57
+ label: t.TracedEntityId,
58
+ url: setupUrl,
59
+ note: `LogType: ${t.LogType} — expires: ${new Date(t.ExpirationDate).toISOString().split('T')[0]} — level: ${t.DebugLevel?.DeveloperName ?? 'unknown'}`,
60
+ })),
61
+ });
62
+ }
63
+ if (highDetailTraces.length > 0) {
64
+ findings.push({
65
+ id: 'debug-log-high-level',
66
+ category: this.category,
67
+ riskLevel: 'MEDIUM',
68
+ title: `${highDetailTraces.length} active trace flag(s) use FINE/FINER/FINEST log level — all variable values are captured`,
69
+ detail: `Active traces with ApexCode set to FINE, FINER, or FINEST capture the maximum level of detail, including all variable values at every line of code execution. This includes any field values read or written during the traced session, potentially exposing passwords, tokens, PII, and financial data in the debug log output. In production, active debug traces on users should be reviewed — they capture sensitive field values and are accessible to administrators.`,
70
+ remediation: 'Reduce log levels to ERROR or WARN for any traces that must remain active. Remove high-detail traces immediately after the debugging session is complete. Never leave FINEST-level traces active in production for extended periods.',
71
+ affectedItems: highDetailTraces.map((t) => ({
72
+ label: t.TracedEntityId,
73
+ url: setupUrl,
74
+ note: `ApexCode level: ${t.DebugLevel?.ApexCode ?? 'unknown'} — expires: ${new Date(t.ExpirationDate).toISOString().split('T')[0]}`,
75
+ })),
76
+ });
77
+ }
78
+ return { findings };
79
+ }
80
+ }
81
+ //# sourceMappingURL=DebugLogAccessCheck.js.map
@@ -0,0 +1,11 @@
1
+ import type { AuditContext } from '../../context/AuditContext.js';
2
+ import type { SecurityCheck, CheckResult } from '../SecurityCheck.js';
3
+ export declare class DeploymentIdentityCheck implements SecurityCheck {
4
+ readonly id = "deployment-identity";
5
+ readonly name = "Deployment Identity";
6
+ readonly category = "Deployments";
7
+ readonly description = "SBS-DEP-001/003: checks for a designated deployment identity and monitors for uncontrolled deployment activity";
8
+ readonly dependsOnCache: readonly ["connectedAppNames"];
9
+ run(ctx: AuditContext): Promise<CheckResult>;
10
+ }
11
+ //# sourceMappingURL=DeploymentIdentityCheck.d.ts.map