@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,11 @@
1
+ // SetupAuditTrail.Section cannot be filtered in SOQL, so the 90-day trail is read (bounded) and
2
+ // matched here.
3
+ const DEV_TOOL_SECTIONS = new Set(['Developer Console', 'Developer Tools', 'IDE', 'Development', 'Workbench']);
4
+ const ANON_ACTION = /anon|runAs|executeCode/i;
5
+ const MAX_TRAIL_ROWS = 10000;
6
+ function isAnonymousExecution(r) {
7
+ return DEV_TOOL_SECTIONS.has(r.Section) || ANON_ACTION.test(r.Action ?? '');
8
+ }
1
9
  function isAdminProfile(profileName) {
2
10
  const lower = profileName.toLowerCase();
3
11
  return lower.includes('admin') || lower.includes('system administrator');
@@ -12,31 +20,43 @@ export class AnonymousApexAuditCheck {
12
20
  const baseUrl = ctx.orgInfo.instanceUrl;
13
21
  const auditTrailUrl = `${baseUrl}/lightning/setup/AuditTrail/home`;
14
22
  let records = [];
23
+ let truncated = false;
15
24
  try {
16
- records = await ctx.soql.queryAll(`SELECT CreatedDate, CreatedBy.Id, CreatedBy.Username, CreatedBy.Profile.Name,
25
+ const trail = await ctx.soql.queryAll(`SELECT CreatedDate, CreatedBy.Id, CreatedBy.Username, CreatedBy.Profile.Name,
17
26
  Section, Action, Display
18
27
  FROM SetupAuditTrail
19
28
  WHERE CreatedDate > LAST_N_DAYS:90
20
- AND (Section IN ('Developer Console', 'Developer Tools', 'IDE', 'Development', 'Workbench')
21
- OR Action LIKE '%anon%'
22
- OR Action LIKE '%runAs%'
23
- OR Action LIKE '%executeCode%')
24
29
  ORDER BY CreatedDate DESC
25
- LIMIT 200`);
30
+ LIMIT ${MAX_TRAIL_ROWS}`);
31
+ truncated = trail.length >= MAX_TRAIL_ROWS;
32
+ records = trail.filter(isAnonymousExecution);
26
33
  }
27
- catch {
34
+ catch (err) {
28
35
  findings.push({
29
36
  id: 'anonymous-apex-inaccessible',
30
37
  category: this.category,
31
38
  riskLevel: 'INFO',
32
39
  inconclusive: true,
33
40
  title: 'SetupAuditTrail could not be queried: anonymous Apex execution cannot be verified',
34
- detail: 'The SetupAuditTrail object was not accessible. This may indicate insufficient permissions to view the org audit trail.',
41
+ detail: `The SetupAuditTrail query failed: ${err instanceof Error ? err.message : String(err)}. If the org denied access, the audit user may lack "View Setup and Configuration".`,
35
42
  remediation: 'Grant "View Setup and Configuration" permission to the audit user. Review anonymous Apex execution manually in Setup → Audit Trail.',
36
43
  affectedItems: [{ label: 'Setup Audit Trail', url: auditTrailUrl }],
37
44
  });
38
45
  return { findings };
39
46
  }
47
+ if (records.length === 0 && truncated) {
48
+ findings.push({
49
+ id: 'anonymous-apex-partial',
50
+ category: this.category,
51
+ riskLevel: 'INFO',
52
+ inconclusive: true,
53
+ title: `No anonymous Apex execution in the latest ${MAX_TRAIL_ROWS} audit-trail entries; older entries were not read`,
54
+ detail: `The 90-day Setup Audit Trail holds more than ${MAX_TRAIL_ROWS} entries, so only the most recent were checked. None of them record anonymous Apex execution, but older ones in the window may.`,
55
+ remediation: 'Review anonymous Apex execution in Setup → Audit Trail, or export the full trail for review.',
56
+ affectedItems: [{ label: 'Setup Audit Trail', url: auditTrailUrl }],
57
+ });
58
+ return { findings };
59
+ }
40
60
  if (records.length === 0) {
41
61
  findings.push({
42
62
  id: 'anonymous-apex-none',
@@ -49,6 +69,19 @@ export class AnonymousApexAuditCheck {
49
69
  });
50
70
  return { findings };
51
71
  }
72
+ if (truncated) {
73
+ // Matches were found, but older entries in the window were not read: the list may be short.
74
+ findings.push({
75
+ id: 'anonymous-apex-partial',
76
+ category: this.category,
77
+ riskLevel: 'INFO',
78
+ inconclusive: true,
79
+ title: `Anonymous Apex executions listed may be incomplete: only the latest ${MAX_TRAIL_ROWS} audit-trail entries were read`,
80
+ detail: `The 90-day Setup Audit Trail holds more than ${MAX_TRAIL_ROWS} entries. The executions reported here come from the most recent ones; older executions in the window, and the users behind them, may be missing.`,
81
+ remediation: 'Review anonymous Apex execution in Setup → Audit Trail, or export the full trail for review.',
82
+ affectedItems: [{ label: 'Setup Audit Trail', url: auditTrailUrl }],
83
+ });
84
+ }
52
85
  const userMap = new Map();
53
86
  for (const r of records) {
54
87
  const userId = r.CreatedBy.Id;
@@ -1,8 +1,15 @@
1
+ import { testApexPattern } from '@cclabsnz/sf-core';
2
+ import { apexCode, codeWithoutStrings, DML_AS_USER, usesSystemMode } from '../support/apexAccess.js';
1
3
  // Patterns that indicate DML or inline SOQL is being performed
2
- const HAS_DML = /\b(?:insert|update|delete|upsert|merge)\s+\w+|Database\.(?:insert|update|delete|upsert|merge)\s*\(/i;
3
- const HAS_SOQL = /\[\s*SELECT\b|Database\.(?:query|queryWithBinds|countQuery)\s*\(/i;
4
+ const HAS_DML = /\b(?:insert|update|delete|upsert|undelete|merge)\s+\w+|Database\.(?:insert|update|delete|upsert|undelete|merge)\w*\s*\(/i;
5
+ // SOQL and SOSL, inline or dynamic.
6
+ const HAS_SOQL = /\[\s*(?:SELECT|FIND)\b|Database\.(?:query|queryWithBinds|countQuery|countQueryWithBinds|getQueryLocator|getQueryLocatorWithBinds|getCursor|getCursorWithBinds)\s*\(|\bSearch\.(?:query|find)\s*\(/i;
4
7
  // Patterns that indicate FLS/CRUD is being checked or enforced
5
- const HAS_FLS = /(?:\.isAccessible\(\)|\.isCreateable\(\)|\.isUpdateable\(\)|\.isDeletable\(\)|Security\.stripInaccessible|SObjectAccessDecision|Schema\.describeSObjects|Schema\.sObjectType\.\w+\.fields)/i;
8
+ // USER_MODE enforces CRUD/FLS (and sharing) on the query or DML it is attached to.
9
+ const HAS_FLS = /(?:\.isAccessible\(\)|\.isCreateable\(\)|\.isUpdateable\(\)|\.isDeletable\(\)|Security\.stripInaccessible|SObjectAccessDecision|Schema\.describeSObjects|Schema\.sObjectType\.\w+\.fields|\bWITH\s+USER_MODE\b|\bAccessLevel\s*\.\s*USER_MODE\b)/i;
10
+ // SYSTEM_MODE (WITH SYSTEM_MODE, AccessLevel.SYSTEM_MODE, `insert as system`) switches CRUD/FLS
11
+ // off for that operation; sharing still follows the class keyword. It is never enforcement,
12
+ // whatever else the class does, and batch or scheduled classes are no exception (spec RULE-002).
6
13
  // Classes that are exempt from CRUD/FLS enforcement by design:
7
14
  // batch, scheduled, and trigger handlers run in a system context
8
15
  const IS_BATCH_OR_SCHEDULED = /implements\s+(?:Database\.Batchable|Schedulable|Database\.StatefulBatch|Database\.AllowsCallouts)/i;
@@ -31,20 +38,33 @@ export class ApexCrudFLSCheck {
31
38
  }
32
39
  const withoutSharingNoFls = [];
33
40
  const withDmlNoFls = [];
41
+ const systemMode = [];
34
42
  // apexBodies is pre-filtered by HardcodedCredentialsCheck, which excludes @IsTest classes
35
43
  // before populating the cache. There is deliberately no second guard here: a cache miss
36
44
  // yields an empty array, not unfiltered bodies, so there is nothing for one to catch.
37
- for (const { name, body } of apexBodies) {
38
- if (!body || IS_BATCH_OR_SCHEDULED.test(body))
45
+ for (const { name, body: raw } of apexBodies) {
46
+ if (!raw)
39
47
  continue;
40
- const hasDml = HAS_DML.test(body);
41
- const hasSoql = HAS_SOQL.test(body);
48
+ // Patterns are matched against code only: "WITH USER_MODE" in a comment enforces nothing.
49
+ const body = apexCode(raw);
50
+ // SYSTEM_MODE only ever qualifies a query or DML, so it is reported before, and regardless
51
+ // of, the pattern gate below: a form that gate does not know must not slip through (RULE-002).
52
+ if (usesSystemMode(raw)) {
53
+ systemMode.push({ name, withoutSharing: testApexPattern(body, WITHOUT_SHARING) });
54
+ continue;
55
+ }
56
+ const hasDml = testApexPattern(body, HAS_DML);
57
+ const hasSoql = testApexPattern(body, HAS_SOQL);
42
58
  if (!hasDml && !hasSoql)
43
59
  continue;
44
- const hasFls = HAS_FLS.test(body);
60
+ if (testApexPattern(body, IS_BATCH_OR_SCHEDULED))
61
+ continue;
62
+ // Enforcement must be code, not text: 'WITH USER_MODE' inside a debug string enforces nothing.
63
+ const enforcementCode = codeWithoutStrings(raw);
64
+ const hasFls = testApexPattern(enforcementCode, HAS_FLS) || testApexPattern(enforcementCode, DML_AS_USER);
45
65
  if (hasFls)
46
66
  continue;
47
- if (WITHOUT_SHARING.test(body)) {
67
+ if (testApexPattern(body, WITHOUT_SHARING)) {
48
68
  withoutSharingNoFls.push(name);
49
69
  }
50
70
  else {
@@ -81,7 +101,22 @@ export class ApexCrudFLSCheck {
81
101
  })),
82
102
  });
83
103
  }
84
- if (withoutSharingNoFls.length === 0 && withDmlNoFls.length === 0) {
104
+ if (systemMode.length > 0) {
105
+ findings.push({
106
+ id: 'apex-crud-fls-system-mode',
107
+ category: this.category,
108
+ riskLevel: 'MEDIUM',
109
+ title: `${systemMode.length} Apex class(es) switch off CRUD/FLS with SYSTEM_MODE`,
110
+ detail: 'WITH SYSTEM_MODE and AccessLevel.SYSTEM_MODE run a query or DML without checking the user\'s object and field permissions. Record sharing still follows the class keyword, so this exposes fields and objects the user cannot otherwise see on records they can reach; in a "without sharing" class it exposes every record too.',
111
+ remediation: 'Use WITH USER_MODE / AccessLevel.USER_MODE wherever the operation serves a user. Where SYSTEM_MODE is genuinely needed, keep it to the narrowest query and strip fields with Security.stripInaccessible() before returning results.',
112
+ affectedItems: systemMode.slice(0, 30).map(({ name, withoutSharing }) => ({
113
+ label: name,
114
+ url: apexClassesUrl,
115
+ note: withoutSharing ? 'SYSTEM_MODE in a "without sharing" class: no CRUD/FLS and no sharing' : 'SYSTEM_MODE: CRUD/FLS not enforced',
116
+ })),
117
+ });
118
+ }
119
+ if (withoutSharingNoFls.length === 0 && withDmlNoFls.length === 0 && systemMode.length === 0) {
85
120
  findings.push({
86
121
  id: 'apex-crud-fls-ok',
87
122
  category: this.category,
@@ -1,23 +1,9 @@
1
- import { ApexRepository } from '@cclabsnz/sf-core';
2
- const INHERITED_SHARING = /\binherited\s+sharing\b/i;
3
- const WITHOUT_SHARING = /\bwithout\s+sharing\b/i;
4
- const WITH_SHARING = /\bwith\s+sharing\b/i;
5
- const CLASS_PATTERN = /\bclass\s+\w+/i;
1
+ import { ApexRepository, testApexPattern } from '@cclabsnz/sf-core';
2
+ import { apexCode, effectiveSharing } from '../support/apexAccess.js';
6
3
  const IS_TEST_CLASS = /@IsTest\b/i;
7
- // SBS-CPORTAL-001: @AuraEnabled or @RemoteAction marks a class as portal/community-exposed
8
- const IS_PORTAL_EXPOSED = /@AuraEnabled|@RemoteAction/i;
9
- function getSharingDeclaration(body) {
10
- if (!CLASS_PATTERN.test(body)) {
11
- return null; // Not a class — skip interfaces, enums, etc.
12
- }
13
- if (WITH_SHARING.test(body))
14
- return 'with';
15
- if (WITHOUT_SHARING.test(body))
16
- return 'without';
17
- if (INHERITED_SHARING.test(body))
18
- return 'inherited';
19
- return 'none';
20
- }
4
+ // SBS-CPORTAL-001: @AuraEnabled and @RemoteAction expose a class to portal and community users;
5
+ // @RestResource exposes it to any API caller (spec RULE-005).
6
+ const IS_EXTERNALLY_EXPOSED = /@AuraEnabled\b|@RemoteAction\b|@RestResource\b/i;
21
7
  export class ApexSharingCheck {
22
8
  id = 'apex-sharing';
23
9
  name = 'Apex Sharing Declarations';
@@ -41,15 +27,20 @@ export class ApexSharingCheck {
41
27
  // SBS-CPORTAL-001: portal-exposed Apex without enforcement = IDOR risk
42
28
  const portalExposedWithoutSharing = [];
43
29
  const portalExposedNoDeclaration = [];
30
+ const bodyByName = new Map(apexBodies.map((b) => [b.name.toLowerCase(), b.body ?? '']));
44
31
  for (const apexClass of apexBodies) {
45
32
  const body = apexClass.body ?? '';
33
+ const code = apexCode(body);
46
34
  // Test classes run as sysadmin — sharing declarations are not applicable
47
- if (IS_TEST_CLASS.test(body))
35
+ if (testApexPattern(code, IS_TEST_CLASS))
48
36
  continue;
49
- const declaration = getSharingDeclaration(body);
37
+ // Read from the class's own declaration, not any mention in the body (spec MN-002).
38
+ // SYSTEM_MODE does not enter into it: it bypasses CRUD/FLS, not sharing (spec RULE-001).
39
+ // A class with no keyword takes the sharing of the class it extends (spec MN-001).
40
+ const declaration = effectiveSharing(apexClass.name, body, (n) => bodyByName.get(n.toLowerCase()));
50
41
  if (declaration === null)
51
42
  continue; // Not a class definition
52
- const isPortalExposed = IS_PORTAL_EXPOSED.test(body);
43
+ const isPortalExposed = testApexPattern(code, IS_EXTERNALLY_EXPOSED);
53
44
  switch (declaration) {
54
45
  case 'with':
55
46
  withSharingClasses.push(apexClass.name);
@@ -79,10 +70,12 @@ export class ApexSharingCheck {
79
70
  findings.push({
80
71
  id: 'portal-exposed-apex-without-sharing',
81
72
  category: this.category,
82
- riskLevel: 'CRITICAL',
83
- title: `${allPortalRisk.length} portal-exposed Apex class(es) (@AuraEnabled/@RemoteAction) lack "with sharing": IDOR risk`,
84
- detail: 'Classes with @AuraEnabled or @RemoteAction methods that use "without sharing" or have no sharing declaration execute without record-level access control. Attackers can supply arbitrary record IDs to read or manipulate data they should not access (IDOR). SBS-CPORTAL-001 requires server-side authorization for every record accessed via portal Apex.',
85
- remediation: 'Add "with sharing" to all @AuraEnabled and @RemoteAction classes. Validate user ownership or sharing on every record accessed inside these methods.',
73
+ // CRITICAL only for an explicit "without sharing". A class with no declaration takes its
74
+ // sharing from how it is entered, so it is a strong signal, not a confirmed bypass.
75
+ riskLevel: portalExposedWithoutSharing.length > 0 ? 'CRITICAL' : 'HIGH',
76
+ title: `${allPortalRisk.length} externally exposed Apex class(es) (@AuraEnabled/@RemoteAction/@RestResource) lack "with sharing": IDOR risk`,
77
+ detail: 'Classes with @AuraEnabled, @RemoteAction or @RestResource methods that use "without sharing" or have no sharing declaration execute without record-level access control. Attackers can supply arbitrary record IDs to read or manipulate data they should not access (IDOR). SBS-CPORTAL-001 requires server-side authorization for every record accessed via portal Apex.',
78
+ remediation: 'Add "with sharing" to all @AuraEnabled, @RemoteAction and @RestResource classes. Validate user ownership or sharing on every record accessed inside these methods.',
86
79
  affectedItems: allPortalRisk.map((name) => ({
87
80
  label: name,
88
81
  url: apexClassesUrl,
@@ -1,3 +1,4 @@
1
+ import { hasField } from '../support/schema.js';
1
2
  export class ApiClientPermissionCheck {
2
3
  id = 'api-client-permission';
3
4
  name = 'Use Any API Client Permission';
@@ -7,7 +8,22 @@ export class ApiClientPermissionCheck {
7
8
  const findings = [];
8
9
  const baseUrl = ctx.orgInfo.instanceUrl;
9
10
  try {
10
- // Single query — PermissionsUseAnyApiClient may not exist in orgs without API Access Control
11
+ // PermissionsUseAnyApiClient is absent from orgs without API Access Control (and from
12
+ // some releases altogether). Describe first: filtering on an absent field is rejected.
13
+ // Absence is unassessed, not a pass: the bypass may exist under a name this check does not read.
14
+ if (!(await hasField(ctx, 'PermissionSet', 'PermissionsUseAnyApiClient'))) {
15
+ findings.push({
16
+ id: 'api-client-permission-not-available',
17
+ category: this.category,
18
+ riskLevel: 'INFO',
19
+ inconclusive: true,
20
+ notAssessed: true,
21
+ title: '"Use Any API Client" holders could not be read: the permission field is not in this org',
22
+ detail: 'This org has no PermissionSet.PermissionsUseAnyApiClient field, which is usual when API Access Control is not available. Who can bypass API client restrictions is therefore unestablished, and SBS-ACS-006 is unevaluated rather than satisfied.',
23
+ remediation: 'If API Access Control is enabled, review who holds "Use Any API Client" in Setup → Permission Sets.',
24
+ });
25
+ return { findings };
26
+ }
11
27
  const result = await ctx.soql.query(`SELECT Assignee.Id, Assignee.Username, Assignee.Profile.Name,
12
28
  PermissionSet.Name, PermissionSet.IsOwnedByProfile
13
29
  FROM PermissionSetAssignment
@@ -42,15 +58,15 @@ export class ApiClientPermissionCheck {
42
58
  })),
43
59
  });
44
60
  }
45
- catch {
61
+ catch (err) {
46
62
  findings.push({
47
63
  id: 'api-client-permission-inconclusive',
48
64
  category: this.category,
49
65
  riskLevel: 'INFO',
50
66
  inconclusive: true,
51
- title: '"Use Any API Client" permission check could not run: field may not exist in this org edition',
52
- detail: 'SBS-ACS-006 requires documented justification for the "Use Any API Client" permission. This field is part of the API Access Control feature and may not be available in all Salesforce editions.',
53
- remediation: 'Verify in Setup → Permission Sets whether "Use Any API Client" is available and review assignments if so.',
67
+ title: '"Use Any API Client" holders could not be read',
68
+ detail: `SBS-ACS-006 requires documented justification for the "Use Any API Client" permission. Who holds it could not be read, so this is unassessed. The org said: ${err instanceof Error ? err.message : String(err)}`,
69
+ remediation: 'Check the error above. If it is an access error, confirm the audit user can read PermissionSetAssignment (View Setup and Configuration); otherwise review assignments in Setup → Permission Sets.',
54
70
  });
55
71
  }
56
72
  return { findings };
@@ -1,3 +1,4 @@
1
+ import { hasField } from '../support/schema.js';
1
2
  export class AuditTrailCheck {
2
3
  id = 'audit-trail';
3
4
  name = 'Audit Trail';
@@ -70,6 +71,22 @@ export class AuditTrailCheck {
70
71
  // SBS-MON-002: flag users who can delete Event Monitoring data (erasing the audit trail).
71
72
  // PermissionsManageEventLogFiles grants the "Delete Event Monitoring Data" capability.
72
73
  try {
74
+ // The permission field exists only in orgs licensed for Event Monitoring. Describe first:
75
+ // filtering on an absent field is rejected outright. Absence is reported as unassessed,
76
+ // not as a pass: this audit has not confirmed the delete capability has no other API name.
77
+ if (!(await hasField(ctx, 'PermissionSet', 'PermissionsManageEventLogFiles'))) {
78
+ findings.push({
79
+ id: 'event-log-delete-permission-not-available',
80
+ category: this.category,
81
+ riskLevel: 'INFO',
82
+ inconclusive: true,
83
+ notAssessed: true,
84
+ title: 'Who can delete Event Monitoring data could not be read: the permission is not in this org',
85
+ detail: 'This org has no PermissionSet.PermissionsManageEventLogFiles field, which is usual when Event Monitoring is not licensed. Who can delete event monitoring data is therefore unestablished from permissions, and SBS-MON-002 is unevaluated rather than satisfied.',
86
+ remediation: 'If the org licenses Event Monitoring, review who holds "Manage Event Log Files" or "Delete Event Monitoring Data" in Setup → Permission Sets.',
87
+ });
88
+ return { findings };
89
+ }
73
90
  const eventLogDeleteResult = await ctx.soql.query(`SELECT Assignee.Id, Assignee.Username, Assignee.Profile.Name,
74
91
  PermissionSet.Name, PermissionSet.IsOwnedByProfile
75
92
  FROM PermissionSetAssignment
@@ -93,20 +110,18 @@ export class AuditTrailCheck {
93
110
  });
94
111
  }
95
112
  }
96
- catch {
97
- // PermissionsManageEventLogFiles does not exist in orgs without Event Monitoring, so this
98
- // query legitimately fails. Skipping silently was wrong: with no finding emitted, a reader
99
- // cannot tell "nobody can delete event logs" from "we were unable to find out", and only
100
- // the first of those is a pass. Declared inconclusive so it is scored as INFO, carries no
101
- // penalty, and is still shown.
113
+ catch (err) {
114
+ // Skipping silently was wrong: with no finding emitted, a reader cannot tell "nobody can
115
+ // delete event logs" from "we were unable to find out", and only the first of those is a
116
+ // pass. Declared inconclusive so it is scored as INFO, carries no penalty, and is still shown.
102
117
  findings.push({
103
118
  id: 'event-log-delete-permission-inconclusive',
104
119
  category: this.category,
105
120
  riskLevel: 'INFO',
106
121
  inconclusive: true,
107
122
  title: 'Manage Event Log Files assignments could not be queried',
108
- detail: 'PermissionSetAssignment could not be filtered on PermissionsManageEventLogFiles. The field is absent in orgs without Event Monitoring, and the query also fails without access to PermissionSetAssignment, so who can delete event monitoring data is unestablished. SBS-MON-002 is unevaluated rather than satisfied.',
109
- remediation: 'If the org has Event Monitoring, grant the audit user read access to PermissionSetAssignment and re-run. Otherwise there are no EventLogFile records to protect and no action is needed.',
123
+ detail: `Who holds "Manage Event Log Files" could not be read, so who can delete event monitoring data is unestablished. SBS-MON-002 is unevaluated rather than satisfied. The org said: ${err instanceof Error ? err.message : String(err)}`,
124
+ remediation: 'Check the error above. If it is an access error, confirm the audit user can read PermissionSetAssignment (View Setup and Configuration), then re-run.',
110
125
  });
111
126
  }
112
127
  return { findings };
@@ -0,0 +1,10 @@
1
+ import type { AuditContext } from '@cclabsnz/sf-core';
2
+ import type { SecurityCheck, CheckResult } from '../SecurityCheck.js';
3
+ export declare class AuthProviderRegistrationHandlerCheck implements SecurityCheck {
4
+ readonly id = "auth-provider-registration-handler";
5
+ readonly name = "Auth.Provider Registration Handler Security";
6
+ readonly category = "Identity & Access";
7
+ readonly description = "Detects Auth.Provider RegistrationHandler running as Admin with email-based account linking vulnerable to pre-auth takeover.";
8
+ run(ctx: AuditContext): Promise<CheckResult>;
9
+ }
10
+ //# sourceMappingURL=AuthProviderRegistrationHandlerCheck.d.ts.map
@@ -0,0 +1,131 @@
1
+ export class AuthProviderRegistrationHandlerCheck {
2
+ id = 'auth-provider-registration-handler';
3
+ name = 'Auth.Provider Registration Handler Security';
4
+ category = 'Identity & Access';
5
+ description = 'Detects Auth.Provider RegistrationHandler running as Admin with email-based account linking vulnerable to pre-auth takeover.';
6
+ async run(ctx) {
7
+ const findings = [];
8
+ const baseUrl = ctx.orgInfo.instanceUrl;
9
+ const authProviderUrl = `${baseUrl}/lightning/setup/AuthProviders/home`;
10
+ let providers = [];
11
+ try {
12
+ providers = await ctx.soql.queryAll('SELECT Id, DeveloperName, FriendlyName, ProviderType, ExecutionUserId, RegistrationHandlerId FROM AuthProvider WHERE RegistrationHandlerId != null');
13
+ }
14
+ catch (err) {
15
+ // This object exists in every org, so a failure is lack of access, never an absent feature.
16
+ findings.push({
17
+ id: 'auth-provider-registration-handler-inaccessible',
18
+ category: this.category,
19
+ riskLevel: 'INFO',
20
+ inconclusive: true,
21
+ title: 'Auth Providers could not be queried',
22
+ detail: `Failed to query AuthProvider: ${err instanceof Error ? err.message : String(err)}`,
23
+ remediation: 'Grant the audit user "View Setup and Configuration".',
24
+ });
25
+ return { findings };
26
+ }
27
+ if (providers.length === 0) {
28
+ findings.push({
29
+ id: 'auth-provider-registration-handler-ok',
30
+ category: this.category,
31
+ riskLevel: 'LOW',
32
+ passed: true,
33
+ title: 'No Auth Providers configured with Registration Handlers',
34
+ detail: 'Zero AuthProvider records in this org configure an automated Registration Handler.',
35
+ remediation: 'When configuring Registration Handlers, avoid execution as System Administrator and verify email authenticity.',
36
+ });
37
+ return { findings };
38
+ }
39
+ // Query Execution Users
40
+ const executionUserIds = [
41
+ ...new Set(providers.map((p) => p.ExecutionUserId).filter((id) => Boolean(id))),
42
+ ];
43
+ let adminUsers = new Set();
44
+ let userDetails = new Map();
45
+ if (executionUserIds.length > 0) {
46
+ const users = await ctx.soql.queryAll(`SELECT Id, Username, IsActive, Profile.Name FROM User WHERE Id IN ('${executionUserIds.join("','")}')`);
47
+ for (const u of users) {
48
+ const profName = u.Profile?.Name ?? '';
49
+ userDetails.set(u.Id, `${u.Username} (${profName})`);
50
+ if (profName === 'System Administrator' || profName.toLowerCase().includes('admin')) {
51
+ adminUsers.add(u.Id);
52
+ }
53
+ }
54
+ }
55
+ // Query Registration Handler Apex classes
56
+ const handlerIds = [
57
+ ...new Set(providers.map((p) => p.RegistrationHandlerId).filter((id) => Boolean(id))),
58
+ ];
59
+ let classBodies = new Map();
60
+ let classNames = new Map();
61
+ if (handlerIds.length > 0) {
62
+ const classes = await ctx.soql.queryAll(`SELECT Id, Name, Body FROM ApexClass WHERE Id IN ('${handlerIds.join("','")}')`);
63
+ for (const c of classes) {
64
+ classNames.set(c.Id, c.Name);
65
+ classBodies.set(c.Id, c.Body ?? '');
66
+ }
67
+ }
68
+ const adminExecProviders = [];
69
+ const unverifiedEmailLinkingProviders = [];
70
+ for (const p of providers) {
71
+ const isExecAdmin = p.ExecutionUserId && adminUsers.has(p.ExecutionUserId);
72
+ if (isExecAdmin) {
73
+ adminExecProviders.push(p);
74
+ }
75
+ const body = p.RegistrationHandlerId ? classBodies.get(p.RegistrationHandlerId) ?? '' : '';
76
+ if (body) {
77
+ // Check if class queries user by email
78
+ const matchesEmailQuery = /SELECT\s+[^;]+FROM\s+User\s+WHERE\s+[^;]*Email\s*=/i.test(body);
79
+ // Check if verification or portal scoping is present
80
+ const checksVerified = /email_verified|isEmailVerified|emailVerified/i.test(body);
81
+ const checksPortalScope = /UserType|IsPortalEnabled|UserLicense/i.test(body);
82
+ if (matchesEmailQuery && (!checksVerified || !checksPortalScope)) {
83
+ unverifiedEmailLinkingProviders.push(p);
84
+ }
85
+ }
86
+ }
87
+ if (adminExecProviders.length > 0) {
88
+ findings.push({
89
+ id: 'auth-provider-registration-handler-admin-exec',
90
+ category: this.category,
91
+ riskLevel: 'CRITICAL',
92
+ title: `${adminExecProviders.length} Auth Provider(s) execute Registration Handler as System Administrator`,
93
+ detail: 'When an Auth.Provider (SSO, OIDC, Google, etc.) Registration Handler runs under a System Administrator execution context, any user creation, role assignment, or record linking executed by the handler occurs with maximum system privileges, enabling automated privilege escalation.',
94
+ remediation: 'Configure the "Execute Registration As" user to a dedicated least-privileged integration user rather than a full System Administrator.',
95
+ affectedItems: adminExecProviders.map((p) => ({
96
+ label: p.FriendlyName || p.DeveloperName,
97
+ url: authProviderUrl,
98
+ note: `Execution user: ${p.ExecutionUserId ? userDetails.get(p.ExecutionUserId) ?? p.ExecutionUserId : 'Unknown'}`,
99
+ })),
100
+ });
101
+ }
102
+ if (unverifiedEmailLinkingProviders.length > 0) {
103
+ findings.push({
104
+ id: 'auth-provider-registration-handler-unverified-email-linking',
105
+ category: this.category,
106
+ riskLevel: 'CRITICAL',
107
+ title: `${unverifiedEmailLinkingProviders.length} Auth Provider(s) link user accounts by email without verification or portal scoping`,
108
+ detail: 'The RegistrationHandler Apex class matches existing User records purely by email address (SELECT Id FROM User WHERE Email = :data.email) without validating email verification tokens (email_verified == true) or scoping to portal user types. An attacker registering an account with a target admin\'s email address on a public or social identity provider can hijack the internal admin user account upon login.',
109
+ remediation: 'Update the RegistrationHandler to verify email_verified == true from the identity provider and ensure social/external registrations can never match internal standard or administrator User records.',
110
+ affectedItems: unverifiedEmailLinkingProviders.map((p) => ({
111
+ label: `${p.FriendlyName || p.DeveloperName} (Handler: ${p.RegistrationHandlerId ? classNames.get(p.RegistrationHandlerId) ?? p.RegistrationHandlerId : 'Unknown'})`,
112
+ url: authProviderUrl,
113
+ note: 'Unverified email matching against User table',
114
+ })),
115
+ });
116
+ }
117
+ if (adminExecProviders.length === 0 && unverifiedEmailLinkingProviders.length === 0) {
118
+ findings.push({
119
+ id: 'auth-provider-registration-handler-ok',
120
+ category: this.category,
121
+ riskLevel: 'LOW',
122
+ passed: true,
123
+ title: 'Auth Provider Registration Handlers are securely configured',
124
+ detail: `${providers.length} Auth Provider(s) inspected; handlers do not run as System Administrator and do not perform unverified email account linking.`,
125
+ remediation: 'Continue enforcing least-privilege execution users and strict identity verification in Registration Handlers.',
126
+ });
127
+ }
128
+ return { findings };
129
+ }
130
+ }
131
+ //# sourceMappingURL=AuthProviderRegistrationHandlerCheck.js.map
@@ -65,7 +65,8 @@ export class CertificateExpiryCheck {
65
65
  findings.push({
66
66
  id: 'certificate-expiring-critical',
67
67
  category: this.category,
68
- riskLevel: 'CRITICAL',
68
+ // An expiring certificate is an outage risk, not a data exposure: HIGH, however urgent.
69
+ riskLevel: 'HIGH',
69
70
  title: `${critical.length} certificate(s) expire within 30 days`,
70
71
  detail: 'Expired certificates break all integrations, SSO logins, and JWT-based authentication that depend on them. Certificates expiring within 30 days require immediate replacement to avoid service disruption.',
71
72
  remediation: 'Renew or replace expiring certificates immediately. Update all integrations and connected apps that reference these certificates. Test authentication flows after replacement.',
@@ -1,3 +1,14 @@
1
+ // OAuth scopes and the refresh-token policy live only in the Metadata API definition: the Tooling
2
+ // ConnectedApplication object has no Metadata column. Each app is read by name, up to this many.
3
+ const MAX_METADATA_READS = 100;
4
+ /** The Metadata API returns a single scope as a string, several as an array. */
5
+ function normalise(meta) {
6
+ const scopes = meta.oauthConfig?.scopes;
7
+ if (meta.oauthConfig && typeof scopes === 'string') {
8
+ return { ...meta, oauthConfig: { ...meta.oauthConfig, scopes: [scopes] } };
9
+ }
10
+ return meta;
11
+ }
1
12
  // Scopes that grant effectively unlimited access as the authorising user.
2
13
  const OVERLY_BROAD_SCOPES = new Set(['Full', 'full']);
3
14
  // Refresh token policy values that indicate no expiry.
@@ -16,22 +27,67 @@ export class ConnectedAppScopeCheck {
16
27
  async run(ctx) {
17
28
  const findings = [];
18
29
  const setupUrl = `${ctx.orgInfo.instanceUrl}/lightning/setup/ConnectedApplication/home`;
19
- let apps = [];
30
+ let rows = [];
20
31
  try {
21
- apps = await ctx.tooling.query('SELECT Id, Name, Metadata FROM ConnectedApplication');
32
+ rows = await ctx.tooling.query('SELECT Id, Name, DeveloperName FROM ConnectedApplication');
22
33
  }
23
- catch {
34
+ catch (err) {
24
35
  findings.push({
25
36
  id: 'connected-app-scope-inconclusive',
26
37
  category: this.category,
27
38
  riskLevel: 'INFO',
28
39
  inconclusive: true,
29
40
  title: 'Connected app OAuth scope check could not be completed',
30
- detail: 'ConnectedApplication Metadata was not accessible via Tooling API. This may indicate a permissions issue on the audit user.',
31
- remediation: 'Grant the audit user the "Customize Application" permission to enable Tooling API access to connected app metadata.',
41
+ detail: `Connected apps could not be listed via the Tooling API: ${err instanceof Error ? err.message : String(err)}`,
42
+ remediation: 'Grant the audit user View Setup and Configuration, then re-run. Meanwhile review OAuth scopes in Setup → App Manager.',
32
43
  });
33
44
  return { findings };
34
45
  }
46
+ if (rows.length > 0 && !ctx.metadata) {
47
+ findings.push({
48
+ id: 'connected-app-scope-inconclusive',
49
+ category: this.category,
50
+ riskLevel: 'INFO',
51
+ inconclusive: true,
52
+ title: 'Connected app OAuth scope check could not be completed',
53
+ detail: `${rows.length} connected app(s) exist, but their OAuth scopes and refresh-token policies are only in the Metadata API, which this run cannot read.`,
54
+ remediation: 'Review OAuth scopes and refresh-token policies in Setup → App Manager.',
55
+ });
56
+ return { findings };
57
+ }
58
+ const apps = [];
59
+ const unread = [];
60
+ for (const [i, row] of rows.entries()) {
61
+ let meta = null;
62
+ if (i < MAX_METADATA_READS) {
63
+ try {
64
+ meta = await ctx.metadata.read('ConnectedApp', row.DeveloperName);
65
+ }
66
+ catch {
67
+ meta = null;
68
+ }
69
+ }
70
+ if (meta)
71
+ apps.push({ Id: row.Id, Name: row.Name, Metadata: normalise(meta) });
72
+ else
73
+ unread.push(row);
74
+ }
75
+ // An app whose definition could not be read is unassessed, never counted as scoped.
76
+ if (unread.length > 0) {
77
+ findings.push({
78
+ id: 'connected-app-scope-unread',
79
+ category: this.category,
80
+ riskLevel: 'INFO',
81
+ inconclusive: true,
82
+ title: `OAuth settings of ${unread.length} connected app(s) could not be read`,
83
+ detail: 'Their Metadata API definitions were not returned (a managed-package app is read under its namespace, and reads stop after ' +
84
+ `${MAX_METADATA_READS} apps). Their scopes and refresh-token policies are unassessed, not clean.`,
85
+ remediation: 'Review these apps\' OAuth scopes and refresh-token policies in Setup → App Manager.',
86
+ affectedItems: unread.map((app) => ({ label: app.Name, url: setupUrl })),
87
+ });
88
+ if (apps.length === 0)
89
+ return { findings };
90
+ }
35
91
  if (apps.length === 0) {
36
92
  findings.push({
37
93
  id: 'connected-app-scope-none',