@cclabsnz/sf-audit 1.16.0 → 1.18.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 (170) hide show
  1. package/CHANGELOG.md +172 -1
  2. package/PERMISSIONS.md +139 -0
  3. package/README.md +98 -26
  4. package/config/scoring.sample.json +104 -5
  5. package/docs/permissionset/SF_Audit_ReadOnly.permissionset-meta.xml +54 -0
  6. package/lib/apps/analyzeApps.d.ts +8 -2
  7. package/lib/apps/analyzeApps.js +7 -2
  8. package/lib/apps/apiLogSource.d.ts +39 -0
  9. package/lib/apps/apiLogSource.js +75 -0
  10. package/lib/apps/appResolver.js +30 -4
  11. package/lib/apps/grantedAccess.js +16 -3
  12. package/lib/apps/leastPrivilege.d.ts +3 -1
  13. package/lib/apps/leastPrivilege.js +7 -3
  14. package/lib/apps/permissionSetGenerator.d.ts +22 -0
  15. package/lib/apps/permissionSetGenerator.js +100 -0
  16. package/lib/apps/types.d.ts +6 -0
  17. package/lib/apps/usageCollector.d.ts +7 -1
  18. package/lib/apps/usageCollector.js +57 -26
  19. package/lib/chains/CapabilityRegistry.js +26 -0
  20. package/lib/chains/ChainEngine.js +11 -1
  21. package/lib/chains/namedChains.js +130 -24
  22. package/lib/checks/CheckEngine.d.ts +3 -1
  23. package/lib/checks/CheckEngine.js +65 -26
  24. package/lib/checks/impl/AgentUserPrivilegeCheck.js +5 -4
  25. package/lib/checks/impl/AnonymousApexAuditCheck.js +41 -8
  26. package/lib/checks/impl/ApexCrudFLSCheck.js +45 -10
  27. package/lib/checks/impl/ApexSharingCheck.js +19 -26
  28. package/lib/checks/impl/ApiClientPermissionCheck.js +21 -5
  29. package/lib/checks/impl/AuditTrailCheck.js +23 -8
  30. package/lib/checks/impl/AuthProviderRegistrationHandlerCheck.d.ts +10 -0
  31. package/lib/checks/impl/AuthProviderRegistrationHandlerCheck.js +131 -0
  32. package/lib/checks/impl/CertificateExpiryCheck.js +2 -1
  33. package/lib/checks/impl/ConnectedAppScopeCheck.js +61 -5
  34. package/lib/checks/impl/ConnectedAppsCheck.js +60 -5
  35. package/lib/checks/impl/ContentLinksCheck.js +33 -9
  36. package/lib/checks/impl/CorsAllowlistCheck.js +3 -2
  37. package/lib/checks/impl/DataClassificationCheck.js +15 -13
  38. package/lib/checks/impl/DataCloudDataSpaceIsolationCheck.d.ts +10 -0
  39. package/lib/checks/impl/DataCloudDataSpaceIsolationCheck.js +116 -0
  40. package/lib/checks/impl/DebugLogAccessCheck.js +4 -4
  41. package/lib/checks/impl/DelegatedAdministrationGroupsCheck.d.ts +10 -0
  42. package/lib/checks/impl/DelegatedAdministrationGroupsCheck.js +76 -0
  43. package/lib/checks/impl/DelegatedAuthenticationExposureCheck.d.ts +10 -0
  44. package/lib/checks/impl/DelegatedAuthenticationExposureCheck.js +105 -0
  45. package/lib/checks/impl/DeploymentIdentityCheck.js +32 -5
  46. package/lib/checks/impl/EmailSecurityCheck.d.ts +1 -1
  47. package/lib/checks/impl/EmailSecurityCheck.js +14 -34
  48. package/lib/checks/impl/EncryptionCoverageCheck.js +21 -15
  49. package/lib/checks/impl/EnhancedDomainsCheck.js +17 -2
  50. package/lib/checks/impl/EscalationPermsCheck.d.ts +2 -0
  51. package/lib/checks/impl/EscalationPermsCheck.js +88 -21
  52. package/lib/checks/impl/ExperienceCloudSiteCheck.js +56 -5
  53. package/lib/checks/impl/ExternalAccountHierarchyExposureCheck.d.ts +10 -0
  54. package/lib/checks/impl/ExternalAccountHierarchyExposureCheck.js +65 -0
  55. package/lib/checks/impl/ExternalCredentialsCheck.js +6 -3
  56. package/lib/checks/impl/FailedLoginCheck.js +36 -9
  57. package/lib/checks/impl/FieldHistoryTrackingCheck.js +14 -11
  58. package/lib/checks/impl/FlowHttpCalloutCredentialBypassCheck.d.ts +10 -0
  59. package/lib/checks/impl/FlowHttpCalloutCredentialBypassCheck.js +115 -0
  60. package/lib/checks/impl/GenAiPromptTemplateGroundingCheck.d.ts +10 -0
  61. package/lib/checks/impl/GenAiPromptTemplateGroundingCheck.js +227 -0
  62. package/lib/checks/impl/GuestExecutableApexCheck.d.ts +1 -1
  63. package/lib/checks/impl/GuestExecutableApexCheck.js +105 -14
  64. package/lib/checks/impl/GuestRecordAccessPolicyCheck.js +52 -11
  65. package/lib/checks/impl/HardcodedCredentialsCheck.js +7 -2
  66. package/lib/checks/impl/HealthCheckCheck.js +1 -0
  67. package/lib/checks/impl/HighAssuranceSessionCheck.js +16 -11
  68. package/lib/checks/impl/InactiveUsersCheck.js +1 -1
  69. package/lib/checks/impl/InboundEmailHandlerExposureCheck.d.ts +10 -0
  70. package/lib/checks/impl/InboundEmailHandlerExposureCheck.js +136 -0
  71. package/lib/checks/impl/IntegrationLeastPrivilegeCheck.js +7 -6
  72. package/lib/checks/impl/InternalUserMfaCheck.js +26 -8
  73. package/lib/checks/impl/IpRestrictionsCheck.js +35 -16
  74. package/lib/checks/impl/LoginAccessPolicyCheck.js +5 -4
  75. package/lib/checks/impl/LoginAnomalyCheck.js +10 -7
  76. package/lib/checks/impl/LoginSessionCheck.js +2 -0
  77. package/lib/checks/impl/MfaEnforcementCheck.js +23 -6
  78. package/lib/checks/impl/MfaMethodStrengthCheck.js +18 -3
  79. package/lib/checks/impl/MfaRegistrationCheck.js +4 -3
  80. package/lib/checks/impl/MyDomainLoginPolicyCheck.js +23 -10
  81. package/lib/checks/impl/OauthDeviceAndAssetTokenFlowsCheck.d.ts +10 -0
  82. package/lib/checks/impl/OauthDeviceAndAssetTokenFlowsCheck.js +84 -0
  83. package/lib/checks/impl/OrgWideEmailSpoofingCheck.d.ts +10 -0
  84. package/lib/checks/impl/OrgWideEmailSpoofingCheck.js +106 -0
  85. package/lib/checks/impl/OutboundMessagesCheck.js +48 -6
  86. package/lib/checks/impl/PackagePostInstallSupplyChainCheck.d.ts +10 -0
  87. package/lib/checks/impl/PackagePostInstallSupplyChainCheck.js +89 -0
  88. package/lib/checks/impl/PlatformEventSubscriberContextCheck.d.ts +10 -0
  89. package/lib/checks/impl/PlatformEventSubscriberContextCheck.js +88 -0
  90. package/lib/checks/impl/PrivilegedAccessCheck.js +12 -5
  91. package/lib/checks/impl/ReleaseUpdatesCheck.js +18 -3
  92. package/lib/checks/impl/RemoteSitesCheck.js +4 -4
  93. package/lib/checks/impl/RestrictionRulesIntegrityCheck.d.ts +10 -0
  94. package/lib/checks/impl/RestrictionRulesIntegrityCheck.js +105 -0
  95. package/lib/checks/impl/SeparationOfDutiesCheck.js +14 -3
  96. package/lib/checks/impl/ShieldTenantSecretLifecycleCheck.d.ts +10 -0
  97. package/lib/checks/impl/ShieldTenantSecretLifecycleCheck.js +90 -0
  98. package/lib/checks/impl/SoapLoginApiAuthCheck.js +20 -8
  99. package/lib/checks/impl/SsoEnforcementCheck.js +16 -5
  100. package/lib/checks/impl/TransactionSecurityPolicyCheck.js +5 -5
  101. package/lib/checks/impl/TrustedIPRangesCheck.js +18 -9
  102. package/lib/checks/impl/UsersAndAdminsCheck.js +24 -4
  103. package/lib/checks/permCatalog.js +1 -1
  104. package/lib/checks/registry.js +30 -0
  105. package/lib/checks/support/apexAccess.d.ts +56 -0
  106. package/lib/checks/support/apexAccess.js +127 -0
  107. package/lib/checks/support/missingObject.d.ts +13 -0
  108. package/lib/checks/support/missingObject.js +37 -0
  109. package/lib/checks/support/schema.d.ts +17 -0
  110. package/lib/checks/support/schema.js +41 -0
  111. package/lib/commands/audit/apps.d.ts +1 -0
  112. package/lib/commands/audit/apps.js +86 -30
  113. package/lib/commands/audit/diff.js +2 -2
  114. package/lib/commands/audit/events/pull.js +3 -1
  115. package/lib/commands/audit/history.js +2 -2
  116. package/lib/commands/audit/incident/collect.js +3 -1
  117. package/lib/commands/audit/incident/report.js +2 -2
  118. package/lib/commands/audit/security.d.ts +3 -0
  119. package/lib/commands/audit/security.js +65 -10
  120. package/lib/commands/audit/timeline.js +2 -2
  121. package/lib/compliance/mapping.js +28 -7
  122. package/lib/findings/AuditResult.d.ts +10 -0
  123. package/lib/findings/CheckMeta.js +15 -0
  124. package/lib/findings/Finding.d.ts +4 -0
  125. package/lib/findings/ScoringConfig.d.ts +10 -8
  126. package/lib/findings/ScoringConfig.js +12 -5
  127. package/lib/findings/coverage.d.ts +34 -0
  128. package/lib/findings/coverage.js +42 -0
  129. package/lib/findings/exitCode.js +1 -1
  130. package/lib/findings/loadScoringConfig.js +51 -8
  131. package/lib/findings/scoring.js +61 -10
  132. package/lib/history/HistoryStore.js +9 -3
  133. package/lib/history/archivePolicy.d.ts +19 -0
  134. package/lib/history/archivePolicy.js +34 -0
  135. package/lib/incident/bundleIo.js +4 -3
  136. package/lib/incident/collect/collectBundle.d.ts +1 -1
  137. package/lib/incident/collect/collectBundle.js +4 -3
  138. package/lib/incident/collect/streamGuestLogs.d.ts +1 -1
  139. package/lib/incident/collect/streamGuestLogs.js +3 -2
  140. package/lib/incident/csv.js +4 -4
  141. package/lib/incident/render/evidence.js +3 -3
  142. package/lib/incident/render/html.js +2 -3
  143. package/lib/index.d.ts +2 -0
  144. package/lib/index.js +2 -0
  145. package/lib/lib/packageInfo.d.ts +6 -0
  146. package/lib/lib/packageInfo.js +19 -0
  147. package/lib/preflight/permissionMap.d.ts +2 -20
  148. package/lib/preflight/permissionMap.js +2 -43
  149. package/lib/preflight/permissions.d.ts +25 -0
  150. package/lib/preflight/permissions.js +50 -0
  151. package/lib/renderers/AttackChainDagRenderer.d.ts +7 -0
  152. package/lib/renderers/AttackChainDagRenderer.js +139 -0
  153. package/lib/renderers/ClientReportRenderer.d.ts +2 -0
  154. package/lib/renderers/ClientReportRenderer.js +34 -6
  155. package/lib/renderers/DiffHtmlRenderer.js +2 -7
  156. package/lib/renderers/HistoryRenderer.js +19 -11
  157. package/lib/renderers/HtmlRenderer.js +23 -6
  158. package/lib/renderers/MarkdownRenderer.js +11 -1
  159. package/lib/renderers/SarifRenderer.d.ts +43 -0
  160. package/lib/renderers/SarifRenderer.js +250 -0
  161. package/lib/report/ExecutivePriorities.js +1 -1
  162. package/lib/report/RemediationRoadmap.d.ts +5 -1
  163. package/lib/report/RemediationRoadmap.js +6 -2
  164. package/lib/waivers/WaiverLoader.d.ts +28 -0
  165. package/lib/waivers/WaiverLoader.js +103 -0
  166. package/lib/waivers/WaiverModel.d.ts +32 -0
  167. package/lib/waivers/WaiverModel.js +28 -0
  168. package/lib/waivers/applyWaivers.d.ts +22 -0
  169. package/lib/waivers/applyWaivers.js +85 -0
  170. package/package.json +6 -4
@@ -1,3 +1,6 @@
1
+ const BYPASS_VALUES = new Set(['BYPASS', 'ALL']);
2
+ const RELAX_VALUES = new Set(['ENFORCE_ACTIVATED_DEVICES', 'RELAX']);
3
+ const MAX_METADATA_READS = 100;
1
4
  // SBS-AUTH-003: detect ranges covering the full public internet or overly broad blocks.
2
5
  // Anything larger than a /16 (65 536 hosts) is flagged; 0.0.0.0 start is always flagged.
3
6
  function ipToNumber(ip) {
@@ -39,30 +42,44 @@ export class IpRestrictionsCheck {
39
42
  rangesUnavailable = true;
40
43
  }
41
44
  }
42
- // 3. Connected apps — single Tooling SOQL with Metadata field (same pattern as
43
- // SELECT Body FROM ApexClass). Replaces the previous N+1 getRecord loop.
44
- // Salesforce ConnectedApp.Metadata.oauthConfig.ipRelaxation enum:
45
- // 'All' → bypass IP restrictions (every IP allowed)
46
- // 'Relax' → relax restrictions for this app's users
47
- // 'WhiteList'→ enforce the org-level IP whitelist (secure)
45
+ // 3. Connected apps: listed via Tooling (which has no Metadata column on this object), then each
46
+ // app's IP Relaxation read from its Metadata API definition. An app that cannot be read leaves
47
+ // the question open, so it blocks the pass rather than counting as enforcing.
48
48
  const ipBypassingApps = [];
49
49
  const ipRelaxingApps = [];
50
50
  let appsUnavailable = false;
51
+ let unreadApps = 0;
52
+ let appsError = '';
51
53
  try {
52
- const connectedApps = await ctx.tooling.query('SELECT Id, Name, Metadata FROM ConnectedApplication');
53
- for (const app of connectedApps) {
54
- const relaxation = app.Metadata?.oauthConfig?.ipRelaxation;
55
- if (relaxation === 'All') {
54
+ const connectedApps = await ctx.tooling.query('SELECT Id, Name, DeveloperName FROM ConnectedApplication');
55
+ for (const [i, app] of connectedApps.entries()) {
56
+ let meta = null;
57
+ if (ctx.metadata && i < MAX_METADATA_READS) {
58
+ try {
59
+ meta = await ctx.metadata.read('ConnectedApp', app.DeveloperName);
60
+ }
61
+ catch {
62
+ meta = null;
63
+ }
64
+ }
65
+ if (!meta) {
66
+ unreadApps++;
67
+ continue;
68
+ }
69
+ const relaxation = (meta.oauthPolicy?.ipRelaxation ?? meta.oauthConfig?.ipRelaxation ?? '').toUpperCase();
70
+ if (BYPASS_VALUES.has(relaxation)) {
56
71
  ipBypassingApps.push({ name: app.Name, id: app.Id });
57
72
  }
58
- else if (relaxation === 'Relax') {
73
+ else if (RELAX_VALUES.has(relaxation)) {
59
74
  ipRelaxingApps.push({ name: app.Name, id: app.Id });
60
75
  }
61
76
  }
77
+ appsUnavailable = unreadApps > 0;
62
78
  }
63
- catch {
79
+ catch (err) {
64
80
  // Recorded so the result cannot be read as "no relaxed apps".
65
81
  appsUnavailable = true;
82
+ appsError = err instanceof Error ? err.message : String(err);
66
83
  }
67
84
  // Determine which profile IDs have at least one IP range
68
85
  const profilesWithRanges = new Set(ipRanges.map((r) => r.ProfileId));
@@ -75,8 +92,8 @@ export class IpRestrictionsCheck {
75
92
  riskLevel: 'INFO',
76
93
  inconclusive: true,
77
94
  title: `Login IP ranges could not be read; ${adminUsers.length} admin profile(s) were not evaluated`,
78
- detail: 'ProfileLoginIpRange was not queryable via SOQL or the Tooling API, so whether these admin profiles restrict login by IP is unknown. It is not reported as unrestricted, because the data does not support that conclusion.',
79
- remediation: 'Grant the audit user access to ProfileLoginIpRange and re-run, or review Login IP Ranges manually in Setup → Profiles.',
95
+ detail: 'This org does not serve ProfileLoginIpRange through SOQL or the Tooling API, so whether these admin profiles restrict login by IP is unknown. It is not reported as unrestricted, because the data does not support that conclusion.',
96
+ remediation: 'Review Login IP Ranges for these admin profiles manually in Setup → Profiles.',
80
97
  affectedItems: adminUsers.map((u) => ({
81
98
  label: u.Username,
82
99
  url: `${baseUrl}/${u.Id}`,
@@ -106,8 +123,10 @@ export class IpRestrictionsCheck {
106
123
  riskLevel: 'INFO',
107
124
  inconclusive: true,
108
125
  title: 'Connected app IP relaxation settings could not be read',
109
- detail: 'The ConnectedApplication Metadata field was not accessible, so whether any connected app bypasses or relaxes login IP enforcement is unknown.',
110
- remediation: 'Grant the audit user access to the Tooling API ConnectedApplication Metadata field and re-run, or review IP Relaxation per app in Setup → Connected Apps.',
126
+ detail: appsError
127
+ ? `Connected apps could not be listed, so whether any of them bypasses or relaxes login IP enforcement is unknown: ${appsError}`
128
+ : `The Metadata API definitions of ${unreadApps} connected app(s) could not be read, so whether they bypass or relax login IP enforcement is unknown.`,
129
+ remediation: 'Review IP Relaxation per app in Setup → App Manager → Manage → OAuth Policies.',
111
130
  });
112
131
  }
113
132
  if (ipBypassingApps.length > 0) {
@@ -18,16 +18,17 @@ export class LoginAccessPolicyCheck {
18
18
  const baseUrl = ctx.orgInfo.instanceUrl;
19
19
  let groups;
20
20
  try {
21
- groups = await ctx.soql.queryAll('SELECT Id, DeveloperName FROM DelegateGroup');
21
+ // DelegateGroup is served by the Tooling API only.
22
+ groups = await ctx.tooling.query('SELECT Id, DeveloperName FROM DelegateGroup');
22
23
  }
23
- catch {
24
+ catch (err) {
24
25
  findings.push({
25
26
  id: 'login-access-policy-inconclusive',
26
27
  category: this.category,
27
28
  riskLevel: 'INFO',
28
29
  inconclusive: true,
29
- title: 'Delegated administration could not be queried (insufficient access)',
30
- detail: 'DelegateGroup was not accessible, so delegated-admin escalation paths could not be evaluated.',
30
+ title: 'Delegated administration could not be queried',
31
+ detail: `The DelegateGroup query failed (${err instanceof Error ? err.message : String(err)}), so delegated-admin escalation paths could not be evaluated.`,
31
32
  remediation: 'Grant the audit user View Setup and Configuration, then re-run. Also manually verify Setup → Login Access Policies.',
32
33
  });
33
34
  return { findings };
@@ -18,24 +18,27 @@ export class LoginAnomalyCheck {
18
18
  async run(ctx) {
19
19
  const findings = [];
20
20
  const setupUrl = `${ctx.orgInfo.instanceUrl}/lightning/setup/OrgLoginHistory/home`;
21
- let rows;
21
+ let fetched;
22
22
  try {
23
- rows = await ctx.soql.queryAll(`SELECT UserId, SourceIp, LoginTime FROM LoginHistory
24
- WHERE Status = 'Success' AND LoginTime = LAST_N_DAYS:7
23
+ // Status cannot be filtered in SOQL, so successful logins are selected in code.
24
+ fetched = await ctx.soql.queryAll(`SELECT UserId, SourceIp, LoginTime, Status FROM LoginHistory
25
+ WHERE LoginTime = LAST_N_DAYS:7
25
26
  ORDER BY LoginTime DESC LIMIT ${MAX_ROWS}`);
26
27
  }
27
- catch {
28
+ catch (err) {
28
29
  findings.push({
29
30
  id: 'login-anomaly-inconclusive',
30
31
  category: this.category,
31
32
  riskLevel: 'INFO',
32
33
  inconclusive: true,
33
34
  title: 'LoginHistory could not be queried — anomalous-login analysis skipped',
34
- detail: 'LoginHistory was not accessible. This may indicate the audit user lacks "View All Users"/"Manage Users" or the org restricts login history.',
35
+ detail: `The LoginHistory query failed: ${err instanceof Error ? err.message : String(err)}. ` +
36
+ 'If the org denied access, the audit user may lack "View All Users".',
35
37
  remediation: 'Grant the audit user access to LoginHistory and re-run.',
36
38
  });
37
39
  return { findings };
38
40
  }
41
+ const rows = fetched.filter((r) => r.Status === undefined || r.Status === 'Success');
39
42
  if (rows.length === 0) {
40
43
  findings.push({
41
44
  id: 'login-anomaly-none',
@@ -57,13 +60,13 @@ export class LoginAnomalyCheck {
57
60
  ipsByUser.set(r.UserId, set);
58
61
  }
59
62
  const anomalous = [...ipsByUser.entries()].filter(([, ips]) => ips.size >= DISTINCT_IP_THRESHOLD);
60
- if (rows.length >= MAX_ROWS) {
63
+ if (fetched.length >= MAX_ROWS) {
61
64
  findings.push({
62
65
  id: 'login-anomaly-truncated',
63
66
  category: this.category,
64
67
  riskLevel: 'INFO',
65
68
  title: `Login history truncated at ${MAX_ROWS} rows — analysis is partial`,
66
- detail: `The last-7-day successful-login volume exceeded ${MAX_ROWS} rows, so this analysis covers only the most recent window. Some per-user IP spread may be undercounted.`,
69
+ detail: `The last-7-day login volume exceeded ${MAX_ROWS} rows, so this analysis covers only the most recent window. Some per-user IP spread may be undercounted.`,
67
70
  remediation: 'Forward LoginHistory to a SIEM for complete, continuous analysis rather than point-in-time sampling.',
68
71
  });
69
72
  }
@@ -21,6 +21,8 @@ export class LoginSessionCheck {
21
21
  category: this.category,
22
22
  riskLevel: failedRiskLevel,
23
23
  title: `${failedCount} failed login attempt(s) in the last 30 days`,
24
+ // A handful of failures is ordinary typing; only the higher bands ask for action.
25
+ passed: failedRiskLevel === 'LOW' || undefined,
24
26
  detail: `There were ${failedCount} failed login attempts out of ${totalLogins} total logins in the last 30 days.`,
25
27
  remediation: 'Investigate accounts with repeated failures. Consider IP restrictions or additional MFA policies for high-failure accounts.',
26
28
  });
@@ -1,3 +1,4 @@
1
+ import { hasField } from '../support/schema.js';
1
2
  // Experience Cloud / portal user types that represent external human users
2
3
  const EXTERNAL_USER_TYPES = ['CsnOnly', 'CustomerSuccess', 'PowerPartner', 'PowerCustomerSuccess', 'SelfService'];
3
4
  export class MfaEnforcementCheck {
@@ -32,16 +33,32 @@ export class MfaEnforcementCheck {
32
33
  // Query 2: portal users who have MFA explicitly enforced via permission
33
34
  let mfaEnforcedIds = new Set();
34
35
  try {
36
+ // Absent permission: MFA cannot be read from permissions, so it is unknown (see the catch).
37
+ if (!(await hasField(ctx, 'PermissionSet', 'PermissionsForceTwoFactor'))) {
38
+ return {
39
+ findings: [
40
+ {
41
+ id: 'mfa-enforcement-not-available',
42
+ category: this.category,
43
+ riskLevel: 'INFO',
44
+ inconclusive: true,
45
+ notAssessed: true,
46
+ title: `MFA enforcement for ${allPortalUsers.length} external/portal user(s) cannot be read from permissions in this org`,
47
+ detail: `This org has ${allPortalUsers.length} active external/portal user(s) but does not expose the "Multi-Factor Authentication for User Interface Logins" permission (PermissionSet.PermissionsForceTwoFactor), so whether they have MFA enforced cannot be established from permission assignments. SBS-AUTH-004 is unevaluated rather than failed.`,
48
+ remediation: 'Verify MFA for external users in the Experience Cloud site login settings, and at the identity provider where portal logins are federated.',
49
+ },
50
+ ],
51
+ };
52
+ }
35
53
  const mfaResult = await ctx.soql.query(`SELECT AssigneeId
36
54
  FROM PermissionSetAssignment
37
- WHERE PermissionSet.PermissionsMultiFactorForUiLogins = true
55
+ WHERE PermissionSet.PermissionsForceTwoFactor = true
38
56
  AND Assignee.IsActive = true
39
57
  AND Assignee.UserType IN (${userTypeList})`);
40
58
  mfaEnforcedIds = new Set(mfaResult.records.map((r) => r.AssigneeId));
41
59
  }
42
- catch {
43
- // PermissionsMultiFactorForUiLogins is absent in some editions, so this query legitimately
44
- // fails. It previously fell through with an empty set, which is not a neutral default: with
60
+ catch (err) {
61
+ // The query failed (the absent-field case is handled above). It previously fell through with an empty set, which is not a neutral default: with
45
62
  // nothing enforced every portal user lands in `withoutMfa`, and the check then stated as
46
63
  // established fact, at HIGH, that each named user lacks MFA. Over-reporting is not the safe
47
64
  // direction — it produces a remediation task against real users and an SBS-AUTH-004 claim
@@ -54,8 +71,8 @@ export class MfaEnforcementCheck {
54
71
  riskLevel: 'INFO',
55
72
  inconclusive: true,
56
73
  title: `MFA enforcement for ${allPortalUsers.length} external/portal user(s) could not be determined`,
57
- detail: `This org has ${allPortalUsers.length} active external/portal user(s), but PermissionSetAssignment could not be filtered on PermissionsMultiFactorForUiLogins. The field is absent in some editions, and the query also fails without access to PermissionSetAssignment. Whether these users have MFA enforced is therefore unestablished, so SBS-AUTH-004 is unevaluated rather than failed.`,
58
- remediation: 'Grant the audit user read access to PermissionSetAssignment and re-run. If the permission does not exist in this edition, verify MFA for external users manually in Setup, and through the identity provider where portal logins are federated.',
74
+ detail: `This org has ${allPortalUsers.length} active external/portal user(s), but who holds PermissionsForceTwoFactor could not be read. Whether these users have MFA enforced is therefore unestablished, so SBS-AUTH-004 is unevaluated rather than failed. The org said: ${err instanceof Error ? err.message : String(err)}`,
75
+ remediation: 'Check the error above. If it is an access error, confirm the audit user can read PermissionSetAssignment (View Setup and Configuration) and re-run; otherwise verify MFA for external users manually in Setup, and through the identity provider where portal logins are federated.',
59
76
  },
60
77
  ],
61
78
  };
@@ -24,19 +24,34 @@ export class MfaMethodStrengthCheck {
24
24
  const findings = [];
25
25
  const baseUrl = ctx.orgInfo.instanceUrl;
26
26
  const setupUrl = `${baseUrl}/lightning/setup/SetupOneIdEntityManagement/home`;
27
- const registrations = ctx.cache.mfaRegistrations ?? [];
28
- if (registrations.length === 0) {
27
+ const cached = ctx.cache.mfaRegistrations;
28
+ // Unset means registration data was never gathered; an empty list means nobody has registered,
29
+ // which mfa-registration reports. Only the first is unknown.
30
+ if (cached === undefined) {
29
31
  findings.push({
30
32
  id: 'mfa-no-data',
31
33
  category: this.category,
32
34
  riskLevel: 'INFO',
33
35
  inconclusive: true,
34
36
  title: 'No MFA registration data available: MfaRegistrationCheck must run first',
35
- detail: 'The mfaRegistrations cache is empty. Either MfaRegistrationCheck did not run, or TwoFactorInfo was not accessible. MFA method strength analysis cannot be performed without this data.',
37
+ detail: 'MFA registration data was not gathered: either MfaRegistrationCheck did not run, or TwoFactorInfo could not be read. MFA method strength analysis cannot be performed without this data.',
36
38
  remediation: 'Ensure MfaRegistrationCheck runs before this check. Grant "Manage Multi-Factor Authentication in API" permission to the audit user.',
37
39
  });
38
40
  return { findings };
39
41
  }
42
+ const registrations = cached;
43
+ if (registrations.length === 0) {
44
+ findings.push({
45
+ id: 'mfa-method-strength-none-registered',
46
+ category: this.category,
47
+ riskLevel: 'INFO',
48
+ passed: true,
49
+ title: 'No registered MFA methods to grade',
50
+ detail: 'No active internal user has a registered MFA method, so there is no method strength to assess. Missing registration itself is reported by the MFA registration check.',
51
+ remediation: 'None for method strength. Address MFA registration coverage first.',
52
+ });
53
+ return { findings };
54
+ }
40
55
  let phishingResistantCount = 0;
41
56
  let strongCount = 0;
42
57
  let weakOnlyCount = 0;
@@ -9,9 +9,10 @@ export class MfaRegistrationCheck {
9
9
  const baseUrl = ctx.orgInfo.instanceUrl;
10
10
  const setupUrl = `${baseUrl}/lightning/setup/SetupOneIdEntityManagement/home`;
11
11
  const frozenFilter = `Id NOT IN (SELECT UserId FROM UserLogin WHERE IsFrozen = true)`;
12
- // COUNT(Id) expr0 puts the result in records[0].expr0; COUNT() without a field puts it in
12
+ // COUNT(Id) with no alias puts the result in records[0].expr0 (an explicit expr0 alias is
13
+ // reserved and rejected); COUNT() without a field puts it in
13
14
  // totalSize which is not exposed on the typed return value.
14
- const countResult = await ctx.soql.query(`SELECT COUNT(Id) expr0 FROM User
15
+ const countResult = await ctx.soql.query(`SELECT COUNT(Id) FROM User
15
16
  WHERE IsActive = true
16
17
  AND UserType = 'Standard'
17
18
  AND ${frozenFilter}`);
@@ -26,7 +27,7 @@ export class MfaRegistrationCheck {
26
27
  LIMIT 2000`);
27
28
  }
28
29
  catch {
29
- ctx.cache.mfaRegistrations = [];
30
+ // Leave the cache unset: an empty list would read downstream as "nobody registered MFA".
30
31
  findings.push({
31
32
  id: 'mfa-registration-inaccessible',
32
33
  category: this.category,
@@ -1,3 +1,17 @@
1
+ // Organization has no MyDomain field. Every org's My Domain is the subdomain of its instance URL
2
+ // (<name>.my.salesforce.com, or a sandbox/develop/scratch variant); a legacy instance host such as
3
+ // na1.salesforce.com means no My Domain.
4
+ const MY_DOMAIN_HOST = /^(.+?)\.(?:(?:sandbox|develop|scratch|trailblaze)\.)?my\.(?:salesforce\.com|salesforce\.mil|sfcrmproducts\.cn)$/i;
5
+ function myDomainOf(instanceUrl) {
6
+ let host = instanceUrl;
7
+ try {
8
+ host = new URL(instanceUrl).hostname;
9
+ }
10
+ catch {
11
+ // keep the raw string
12
+ }
13
+ return MY_DOMAIN_HOST.exec(host)?.[1] ?? null;
14
+ }
1
15
  export class MyDomainLoginPolicyCheck {
2
16
  id = 'my-domain-login-policy';
3
17
  name = 'My Domain Login Policy';
@@ -8,11 +22,10 @@ export class MyDomainLoginPolicyCheck {
8
22
  const baseUrl = ctx.orgInfo.instanceUrl;
9
23
  const ssoSetupUrl = `${baseUrl}/lightning/setup/SingleSignOn/home`;
10
24
  const domainSetupUrl = `${baseUrl}/lightning/setup/MyDomain/home`;
11
- // Q1 (SOQL): check if My Domain is configured
12
- const orgResult = await ctx.soql.query(`SELECT MyDomain, IsSandbox FROM Organization LIMIT 1`);
13
- const org = orgResult.records[0];
14
- const myDomain = org?.MyDomain ?? null;
15
- const isSandbox = org?.IsSandbox ?? false;
25
+ // Q1: is My Domain configured (from the instance URL), and is this a sandbox
26
+ const orgResult = await ctx.soql.query(`SELECT IsSandbox FROM Organization LIMIT 1`);
27
+ const myDomain = myDomainOf(baseUrl);
28
+ const isSandbox = orgResult.records[0]?.IsSandbox ?? ctx.orgInfo.isSandbox;
16
29
  if (!myDomain) {
17
30
  findings.push({
18
31
  id: 'my-domain-not-configured',
@@ -33,13 +46,13 @@ export class MyDomainLoginPolicyCheck {
33
46
  detail: `The org has a custom My Domain (${myDomain}) configured, which is a prerequisite for SSO enforcement and Enhanced Domains.`,
34
47
  remediation: 'Verify the login policy in Setup → My Domain prevents login from login.salesforce.com.',
35
48
  });
36
- // Q2 (Tooling): check AuthConfig for login options.
49
+ // Q2: check AuthConfig (a standard-API object) for login options.
37
50
  // If AuthOptionsUsernamePassword is false in the AuthConfig for the org domain,
38
51
  // users cannot log in with Salesforce credentials — they must go through SSO.
39
52
  try {
40
- const authConfigs = await ctx.tooling.query(`SELECT DeveloperName, AuthOptionsSaml, AuthOptionsUsernamePassword, IsDisabled
53
+ const authConfigs = await ctx.soql.queryAll(`SELECT DeveloperName, AuthOptionsSaml, AuthOptionsUsernamePassword, IsActive
41
54
  FROM AuthConfig
42
- WHERE IsDisabled = false`);
55
+ WHERE IsActive = true`);
43
56
  if (authConfigs.length === 0) {
44
57
  findings.push({
45
58
  id: 'my-domain-auth-config-empty',
@@ -88,14 +101,14 @@ export class MyDomainLoginPolicyCheck {
88
101
  }
89
102
  }
90
103
  }
91
- catch {
104
+ catch (err) {
92
105
  findings.push({
93
106
  id: 'my-domain-auth-config-inaccessible',
94
107
  category: this.category,
95
108
  riskLevel: 'MEDIUM',
96
109
  inconclusive: true,
97
110
  title: 'My Domain login policy could not be verified: AuthConfig not accessible',
98
- detail: 'The Tooling API AuthConfig query was not accessible. The My Domain login policy (credential login vs SSO-only) cannot be automatically verified.',
111
+ detail: `The AuthConfig query failed, so the My Domain login policy (credential login vs SSO-only) cannot be automatically verified: ${err instanceof Error ? err.message : String(err)}`,
99
112
  remediation: 'Manually verify in Setup → My Domain → Authentication Configuration that "Login Page" is disabled and "Prevent Login from login.salesforce.com" is enabled.',
100
113
  });
101
114
  }
@@ -0,0 +1,10 @@
1
+ import type { AuditContext } from '@cclabsnz/sf-core';
2
+ import type { SecurityCheck, CheckResult } from '../SecurityCheck.js';
3
+ export declare class OauthDeviceAndAssetTokenFlowsCheck implements SecurityCheck {
4
+ readonly id = "oauth-device-and-asset-token-flows";
5
+ readonly name = "OAuth Device & Password Flows";
6
+ readonly category = "Identity & Access";
7
+ readonly description = "Flags OAuth 2.0 Device Flow and Username-Password Flow enabled in OAuth and OpenID Connect Settings.";
8
+ run(ctx: AuditContext): Promise<CheckResult>;
9
+ }
10
+ //# sourceMappingURL=OauthDeviceAndAssetTokenFlowsCheck.d.ts.map
@@ -0,0 +1,84 @@
1
+ export class OauthDeviceAndAssetTokenFlowsCheck {
2
+ id = 'oauth-device-and-asset-token-flows';
3
+ name = 'OAuth Device & Password Flows';
4
+ category = 'Identity & Access';
5
+ description = 'Flags OAuth 2.0 Device Flow and Username-Password Flow enabled in OAuth and OpenID Connect Settings.';
6
+ async run(ctx) {
7
+ const findings = [];
8
+ const oauthUrl = `${ctx.orgInfo.instanceUrl}/lightning/setup/OauthOidcSettings/home`;
9
+ // Org settings are the only evidence read. A flag counts only when the read returned it as
10
+ // a boolean: a failed read, an absent Metadata client or a missing field is not "disabled".
11
+ let settings = null;
12
+ if (ctx.metadata) {
13
+ try {
14
+ settings = await ctx.metadata.read('OauthOidcSettings', 'OauthOidc');
15
+ }
16
+ catch {
17
+ settings = null;
18
+ }
19
+ }
20
+ const device = typeof settings?.isDeviceFlowEnabled === 'boolean' ? settings.isDeviceFlowEnabled : undefined;
21
+ const password = typeof settings?.isPasswordFlowEnabled === 'boolean' ? settings.isPasswordFlowEnabled : undefined;
22
+ if (device === true) {
23
+ findings.push({
24
+ id: 'oauth-device-flow-enabled',
25
+ category: this.category,
26
+ riskLevel: 'HIGH',
27
+ title: 'OAuth 2.0 Device Flow is ENABLED in org settings',
28
+ detail: 'OAuth 2.0 Device Flow allows a user to authorize a token by entering an 8-character code on a legitimate verification URL. Attackers frequently use Device Code phishing to bypass standard browser-based conditional access and MFA controls, obtaining persistent refresh tokens.',
29
+ remediation: 'Disable OAuth 2.0 Device Flow in Setup → OAuth and OpenID Connect Settings unless strictly required for headless devices.',
30
+ affectedItems: [
31
+ {
32
+ label: 'OAuth and OpenID Connect Settings',
33
+ url: oauthUrl,
34
+ note: 'Disable "Allow OAuth Device Flow"',
35
+ },
36
+ ],
37
+ });
38
+ }
39
+ if (password === true) {
40
+ findings.push({
41
+ id: 'oauth-password-flow-enabled',
42
+ category: this.category,
43
+ riskLevel: 'HIGH',
44
+ title: 'OAuth 2.0 Username-Password Flow is ENABLED in org settings',
45
+ detail: 'The Resource Owner Password Credentials (ROPC / Username-Password) flow allows exchanging raw credentials directly for access tokens, completely bypassing interactive SSO redirects, browser-based MFA, and device trust policies.',
46
+ remediation: 'Disable Username-Password Flow in Setup → OAuth and OpenID Connect Settings, and migrate integrations to OAuth 2.0 Client Credentials or JWT Bearer flow.',
47
+ affectedItems: [
48
+ {
49
+ label: 'OAuth and OpenID Connect Settings',
50
+ url: oauthUrl,
51
+ note: 'Disable "Allow Username-Password Flow"',
52
+ },
53
+ ],
54
+ });
55
+ }
56
+ if (device === false && password === false) {
57
+ findings.push({
58
+ id: 'oauth-device-and-asset-flows-ok',
59
+ category: this.category,
60
+ riskLevel: 'LOW',
61
+ passed: true,
62
+ title: 'Phishable OAuth Device Flow and Username-Password Flow are disabled',
63
+ detail: 'Org settings confirm both OAuth 2.0 Device Flow and Username-Password Flow are disabled, eliminating secondary token-issuance backdoors.',
64
+ remediation: 'Keep Device Flow and Password Flow disabled org-wide.',
65
+ });
66
+ }
67
+ else if (device === undefined || password === undefined) {
68
+ const unread = [device === undefined && 'Device Flow', password === undefined && 'Username-Password Flow']
69
+ .filter(Boolean)
70
+ .join(' and ');
71
+ findings.push({
72
+ id: 'oauth-device-and-asset-flows-advisory',
73
+ category: this.category,
74
+ riskLevel: 'INFO',
75
+ title: `Verify the OAuth ${unread} setting manually`,
76
+ detail: `This run could not read the ${unread} setting from OAuth and OpenID Connect Settings, so whether it is enabled is unknown. Both flows let a token be issued outside the browser sign-in, bypassing MFA and conditional access.`,
77
+ remediation: 'In Setup → OAuth and OpenID Connect Settings, confirm "Allow OAuth Device Flow" and "Allow OAuth Username-Password Flows" are off unless a documented integration needs them.',
78
+ affectedItems: [{ label: 'OAuth and OpenID Connect Settings', url: oauthUrl }],
79
+ });
80
+ }
81
+ return { findings };
82
+ }
83
+ }
84
+ //# sourceMappingURL=OauthDeviceAndAssetTokenFlowsCheck.js.map
@@ -0,0 +1,10 @@
1
+ import type { AuditContext } from '@cclabsnz/sf-core';
2
+ import type { SecurityCheck, CheckResult } from '../SecurityCheck.js';
3
+ export declare class OrgWideEmailSpoofingCheck implements SecurityCheck {
4
+ readonly id = "org-wide-email-spoofing";
5
+ readonly name = "Org-Wide Email Spoofing & DKIM Coverage";
6
+ readonly category = "External Connectivity";
7
+ readonly description = "Flags org-wide email addresses open to all profiles and missing DKIM keys enabling internal and outbound email spoofing.";
8
+ run(ctx: AuditContext): Promise<CheckResult>;
9
+ }
10
+ //# sourceMappingURL=OrgWideEmailSpoofingCheck.d.ts.map
@@ -0,0 +1,106 @@
1
+ import { isMissingObjectError } from '../support/missingObject.js';
2
+ export class OrgWideEmailSpoofingCheck {
3
+ id = 'org-wide-email-spoofing';
4
+ name = 'Org-Wide Email Spoofing & DKIM Coverage';
5
+ category = 'External Connectivity';
6
+ description = 'Flags org-wide email addresses open to all profiles and missing DKIM keys enabling internal and outbound email spoofing.';
7
+ async run(ctx) {
8
+ const findings = [];
9
+ const baseUrl = ctx.orgInfo.instanceUrl;
10
+ const owaUrl = `${baseUrl}/lightning/setup/OrgWideEmailAddresses/home`;
11
+ const dkimUrl = `${baseUrl}/lightning/setup/EmailDKIM/home`;
12
+ // 1. Query OrgWideEmailAddress
13
+ let owaRecords = [];
14
+ let owaInaccessible = false;
15
+ try {
16
+ owaRecords = await ctx.soql.queryAll('SELECT Id, Address, DisplayName, IsAllowAllProfiles FROM OrgWideEmailAddress');
17
+ }
18
+ catch (err) {
19
+ if (isMissingObjectError(err)) {
20
+ // Continue to DKIM check
21
+ }
22
+ else {
23
+ owaInaccessible = true;
24
+ findings.push({
25
+ id: 'org-wide-email-spoofing-inaccessible',
26
+ category: this.category,
27
+ riskLevel: 'INFO',
28
+ inconclusive: true,
29
+ title: 'OrgWideEmailAddress could not be queried',
30
+ detail: `Query to OrgWideEmailAddress failed: ${err instanceof Error ? err.message : String(err)}`,
31
+ remediation: 'Grant the audit user "View Setup and Configuration".',
32
+ });
33
+ }
34
+ }
35
+ const openOwaRecords = owaRecords.filter((r) => r.IsAllowAllProfiles);
36
+ if (openOwaRecords.length > 0) {
37
+ findings.push({
38
+ id: 'org-wide-email-spoofing-all-profiles',
39
+ category: this.category,
40
+ riskLevel: 'MEDIUM',
41
+ title: `${openOwaRecords.length} Org-Wide Email Address(es) are available to All Profiles`,
42
+ detail: 'Org-wide email addresses with "All Profiles" selected allow any internal user, guest user (if misconfigured), or automated Flow to send emails impersonating billing, support, or executive identities. In compromise or insider scenarios, this facilitates high-reputation phishing sent directly from legitimate Salesforce mail servers.',
43
+ remediation: 'Restrict each org-wide address to specific authorized profiles rather than granting access to all profiles.',
44
+ affectedItems: openOwaRecords.map((r) => ({
45
+ label: r.Address,
46
+ url: owaUrl,
47
+ note: `Display Name: "${r.DisplayName || 'None'}" exposed to all profiles`,
48
+ })),
49
+ });
50
+ }
51
+ // 2. Query DkimKey
52
+ let dkimKeys = [];
53
+ let dkimInaccessible = false;
54
+ try {
55
+ dkimKeys = await ctx.soql.queryAll('SELECT Id, Domain, IsActive FROM DkimKey');
56
+ }
57
+ catch (err) {
58
+ if (!isMissingObjectError(err)) {
59
+ dkimInaccessible = true;
60
+ }
61
+ }
62
+ const activeDkimKeys = dkimKeys.filter((k) => k.IsActive === true);
63
+ if (dkimInaccessible) {
64
+ findings.push({
65
+ id: 'org-wide-email-spoofing-dkim-inaccessible',
66
+ category: this.category,
67
+ riskLevel: 'INFO',
68
+ inconclusive: true,
69
+ title: 'DKIM keys could not be queried',
70
+ detail: 'DkimKey was not readable, so whether outbound Salesforce email is DKIM-signed is unknown.',
71
+ remediation: 'Grant the audit user "View Setup and Configuration", then re-run. Meanwhile check Setup → DKIM Keys manually.',
72
+ affectedItems: [{ label: 'DKIM Keys Configuration', url: dkimUrl }],
73
+ });
74
+ }
75
+ if (!dkimInaccessible && activeDkimKeys.length === 0) {
76
+ findings.push({
77
+ id: 'org-wide-email-spoofing-no-dkim',
78
+ category: this.category,
79
+ riskLevel: 'MEDIUM',
80
+ title: 'Zero active DKIM keys configured for outbound Salesforce email',
81
+ detail: 'Outbound emails sent from Salesforce without DKIM signatures are vulnerable to domain spoofing, recipient rejection, or landing in junk folders. Active DKIM keys ensure cryptographic origin authentication for all outbound Salesforce messages.',
82
+ remediation: 'Generate and activate DKIM keys in Setup → DKIM Keys for all corporate sending domains used by Salesforce.',
83
+ affectedItems: [
84
+ {
85
+ label: 'DKIM Keys Configuration',
86
+ url: dkimUrl,
87
+ note: 'No active DKIM keys found in org',
88
+ },
89
+ ],
90
+ });
91
+ }
92
+ if (!owaInaccessible && !dkimInaccessible && openOwaRecords.length === 0 && activeDkimKeys.length > 0) {
93
+ findings.push({
94
+ id: 'org-wide-email-spoofing-ok',
95
+ category: this.category,
96
+ riskLevel: 'LOW',
97
+ passed: true,
98
+ title: 'Org-wide email addresses are properly scoped and DKIM signing is active',
99
+ detail: `${owaRecords.length} org-wide address(es) and ${activeDkimKeys.length} active DKIM key(s) verified; no all-profile exposure detected.`,
100
+ remediation: 'Maintain profile-based scoping on all org-wide sending addresses.',
101
+ });
102
+ }
103
+ return { findings };
104
+ }
105
+ }
106
+ //# sourceMappingURL=OrgWideEmailSpoofingCheck.js.map