@cclabsnz/sf-audit 1.17.0 → 1.18.1

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 (83) hide show
  1. package/CHANGELOG.md +71 -0
  2. package/PERMISSIONS.md +139 -0
  3. package/README.md +8 -10
  4. package/docs/permissionset/SF_Audit_ReadOnly.permissionset-meta.xml +54 -0
  5. package/lib/chains/ChainEngine.js +11 -1
  6. package/lib/chains/namedChains.js +42 -24
  7. package/lib/checks/CheckEngine.js +55 -24
  8. package/lib/checks/impl/AgentUserPrivilegeCheck.js +5 -4
  9. package/lib/checks/impl/AnonymousApexAuditCheck.js +41 -8
  10. package/lib/checks/impl/ApexSharingCheck.js +3 -1
  11. package/lib/checks/impl/ApiClientPermissionCheck.js +21 -5
  12. package/lib/checks/impl/AuditTrailCheck.js +23 -8
  13. package/lib/checks/impl/CertificateExpiryCheck.js +2 -1
  14. package/lib/checks/impl/ConnectedAppScopeCheck.js +61 -5
  15. package/lib/checks/impl/ConnectedAppsCheck.js +13 -4
  16. package/lib/checks/impl/ContentLinksCheck.js +33 -9
  17. package/lib/checks/impl/CorsAllowlistCheck.js +3 -2
  18. package/lib/checks/impl/DataClassificationCheck.js +15 -13
  19. package/lib/checks/impl/DebugLogAccessCheck.js +4 -4
  20. package/lib/checks/impl/DelegatedAdministrationGroupsCheck.js +3 -2
  21. package/lib/checks/impl/DelegatedAuthenticationExposureCheck.js +8 -1
  22. package/lib/checks/impl/DeploymentIdentityCheck.js +32 -5
  23. package/lib/checks/impl/EmailSecurityCheck.d.ts +1 -1
  24. package/lib/checks/impl/EmailSecurityCheck.js +14 -34
  25. package/lib/checks/impl/EncryptionCoverageCheck.js +21 -15
  26. package/lib/checks/impl/EnhancedDomainsCheck.js +17 -2
  27. package/lib/checks/impl/EscalationPermsCheck.d.ts +2 -0
  28. package/lib/checks/impl/EscalationPermsCheck.js +88 -21
  29. package/lib/checks/impl/ExperienceCloudSiteCheck.js +56 -5
  30. package/lib/checks/impl/ExternalAccountHierarchyExposureCheck.js +7 -15
  31. package/lib/checks/impl/ExternalCredentialsCheck.js +6 -3
  32. package/lib/checks/impl/FailedLoginCheck.js +36 -9
  33. package/lib/checks/impl/FieldHistoryTrackingCheck.js +14 -11
  34. package/lib/checks/impl/FlowHttpCalloutCredentialBypassCheck.js +2 -2
  35. package/lib/checks/impl/GuestRecordAccessPolicyCheck.js +52 -11
  36. package/lib/checks/impl/HealthCheckCheck.js +1 -0
  37. package/lib/checks/impl/HighAssuranceSessionCheck.js +16 -11
  38. package/lib/checks/impl/InactiveUsersCheck.js +1 -1
  39. package/lib/checks/impl/InboundEmailHandlerExposureCheck.js +5 -5
  40. package/lib/checks/impl/IntegrationLeastPrivilegeCheck.js +7 -6
  41. package/lib/checks/impl/InternalUserMfaCheck.js +26 -8
  42. package/lib/checks/impl/IpRestrictionsCheck.js +35 -16
  43. package/lib/checks/impl/LoginAccessPolicyCheck.js +5 -4
  44. package/lib/checks/impl/LoginAnomalyCheck.js +10 -7
  45. package/lib/checks/impl/LoginSessionCheck.js +2 -0
  46. package/lib/checks/impl/MfaEnforcementCheck.js +23 -6
  47. package/lib/checks/impl/MfaMethodStrengthCheck.js +18 -3
  48. package/lib/checks/impl/MfaRegistrationCheck.js +4 -3
  49. package/lib/checks/impl/MyDomainLoginPolicyCheck.js +23 -10
  50. package/lib/checks/impl/OutboundMessagesCheck.js +48 -6
  51. package/lib/checks/impl/PlatformEventSubscriberContextCheck.js +5 -1
  52. package/lib/checks/impl/PrivilegedAccessCheck.js +12 -5
  53. package/lib/checks/impl/ReleaseUpdatesCheck.js +18 -3
  54. package/lib/checks/impl/RemoteSitesCheck.js +4 -4
  55. package/lib/checks/impl/RestrictionRulesIntegrityCheck.js +3 -3
  56. package/lib/checks/impl/SeparationOfDutiesCheck.js +14 -3
  57. package/lib/checks/impl/SoapLoginApiAuthCheck.js +20 -8
  58. package/lib/checks/impl/SsoEnforcementCheck.js +16 -5
  59. package/lib/checks/impl/TransactionSecurityPolicyCheck.js +5 -5
  60. package/lib/checks/impl/TrustedIPRangesCheck.js +18 -9
  61. package/lib/checks/impl/UsersAndAdminsCheck.js +24 -4
  62. package/lib/checks/permCatalog.js +1 -1
  63. package/lib/checks/support/missingObject.js +3 -1
  64. package/lib/checks/support/schema.d.ts +17 -0
  65. package/lib/checks/support/schema.js +41 -0
  66. package/lib/commands/audit/apps.js +3 -1
  67. package/lib/commands/audit/events/pull.js +3 -1
  68. package/lib/commands/audit/incident/collect.js +3 -1
  69. package/lib/commands/audit/security.js +9 -3
  70. package/lib/findings/AuditResult.d.ts +2 -0
  71. package/lib/findings/coverage.d.ts +6 -0
  72. package/lib/findings/coverage.js +12 -0
  73. package/lib/findings/scoring.js +51 -9
  74. package/lib/preflight/permissionMap.d.ts +2 -20
  75. package/lib/preflight/permissionMap.js +2 -43
  76. package/lib/preflight/permissions.d.ts +25 -0
  77. package/lib/preflight/permissions.js +50 -0
  78. package/lib/renderers/ClientReportRenderer.js +4 -4
  79. package/lib/renderers/HtmlRenderer.js +15 -4
  80. package/lib/renderers/MarkdownRenderer.js +6 -3
  81. package/lib/report/RemediationRoadmap.d.ts +5 -1
  82. package/lib/report/RemediationRoadmap.js +6 -2
  83. package/package.json +4 -2
@@ -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
  }
@@ -1,3 +1,6 @@
1
+ // The endpoint and the session-ID flag live only in the Metadata column, which the Tooling API
2
+ // returns one record at a time, so each message is fetched by id, up to this many.
3
+ const MAX_RECORD_READS = 100;
1
4
  export class OutboundMessagesCheck {
2
5
  id = 'outbound-messages';
3
6
  name = 'Workflow Outbound Messages';
@@ -6,9 +9,9 @@ export class OutboundMessagesCheck {
6
9
  async run(ctx) {
7
10
  const findings = [];
8
11
  const setupUrl = `${ctx.orgInfo.instanceUrl}/lightning/setup/WorkflowOutboundMessaging/home`;
9
- let rows;
12
+ let listed;
10
13
  try {
11
- rows = await ctx.tooling.query('SELECT Id, Name, EndpointUrl, IncludeSessionId FROM WorkflowOutboundMessage');
14
+ listed = await ctx.tooling.query('SELECT Id, Name FROM WorkflowOutboundMessage');
12
15
  }
13
16
  catch (err) {
14
17
  const msg = err instanceof Error ? err.message : String(err);
@@ -18,12 +21,51 @@ export class OutboundMessagesCheck {
18
21
  riskLevel: 'INFO',
19
22
  inconclusive: true,
20
23
  title: 'Workflow outbound messages could not be read',
21
- detail: `The WorkflowOutboundMessage Tooling query was not accessible: ${msg}`,
24
+ detail: `The WorkflowOutboundMessage Tooling query failed: ${msg}`,
22
25
  remediation: 'Grant the audit user "View Setup and Configuration", then re-run the audit.',
23
26
  });
24
27
  return { findings };
25
28
  }
26
- if (rows.length === 0) {
29
+ const rows = [];
30
+ const unread = [];
31
+ for (const [i, row] of listed.entries()) {
32
+ let meta;
33
+ if (i < MAX_RECORD_READS) {
34
+ try {
35
+ const rec = await ctx.tooling.getRecord('WorkflowOutboundMessage', row.Id);
36
+ meta = rec?.Metadata ?? undefined;
37
+ }
38
+ catch {
39
+ meta = undefined;
40
+ }
41
+ }
42
+ if (meta && typeof meta.endpointUrl === 'string') {
43
+ rows.push({
44
+ ...row,
45
+ EndpointUrl: meta.endpointUrl,
46
+ IncludeSessionId: meta.includeSessionId === true || meta.includeSessionId === 'true',
47
+ });
48
+ }
49
+ else
50
+ unread.push(row);
51
+ }
52
+ // A message whose definition could not be read is unassessed, and keeps the inventory from passing.
53
+ if (unread.length > 0) {
54
+ findings.push({
55
+ id: 'outbound-messages-unread',
56
+ category: this.category,
57
+ riskLevel: 'INFO',
58
+ inconclusive: true,
59
+ title: `${unread.length} outbound message(s) could not be read`,
60
+ detail: 'Their endpoint and Include Session ID settings were not returned by the Tooling API ' +
61
+ `(reads stop after ${MAX_RECORD_READS} messages), so they are unassessed, not clean.`,
62
+ remediation: 'Review these outbound messages in Setup → Outbound Messages.',
63
+ affectedItems: unread.map((r) => ({ label: r.Name, url: setupUrl })),
64
+ });
65
+ if (rows.length === 0)
66
+ return { findings };
67
+ }
68
+ if (listed.length === 0) {
27
69
  findings.push({
28
70
  id: 'outbound-messages-none',
29
71
  category: this.category,
@@ -71,8 +113,8 @@ export class OutboundMessagesCheck {
71
113
  findings.push({
72
114
  id: 'outbound-messages-inventory',
73
115
  category: this.category,
74
- riskLevel: sessionId.length === 0 && cleartext.length === 0 ? 'LOW' : 'INFO',
75
- passed: sessionId.length === 0 && cleartext.length === 0 ? true : undefined,
116
+ riskLevel: sessionId.length === 0 && cleartext.length === 0 && unread.length === 0 ? 'LOW' : 'INFO',
117
+ passed: sessionId.length === 0 && cleartext.length === 0 && unread.length === 0 ? true : undefined,
76
118
  title: `${rows.length} workflow outbound message(s) configured (${sessionId.length} include session ID, ${cleartext.length} cleartext)`,
77
119
  detail: 'Outbound messages POST record data to external endpoints automatically. Each destination should be a reviewed, currently-used HTTPS integration.',
78
120
  remediation: 'Audit each outbound message endpoint to confirm it is still used and points to a trusted HTTPS destination. Remove unused entries.',
@@ -42,7 +42,11 @@ export class PlatformEventSubscriberContextCheck {
42
42
  const profileNameById = new Map(profiles.map((p) => [p.Id, p.Name]));
43
43
  const owned = await ctx.soql.queryAll(`SELECT Id, ProfileId FROM PermissionSet WHERE IsOwnedByProfile = true AND ProfileId IN (${profiles.map((p) => `'${p.Id}'`).join(', ')})`);
44
44
  const profileByPermSet = new Map(owned.map((ps) => [ps.Id, ps.ProfileId]));
45
- const objectPerms = await ctx.soql.queryAll("SELECT Id, ParentId, SobjectType, PermissionsCreate FROM ObjectPermissions WHERE PermissionsCreate = true AND SobjectType LIKE '%__e'");
45
+ // SobjectType does not accept LIKE ("invalid operator on id field"): select these profiles'
46
+ // Create grants and keep the platform events (__e) in code.
47
+ const objectPerms = owned.length === 0
48
+ ? []
49
+ : await ctx.soql.queryAll(`SELECT Id, ParentId, SobjectType, PermissionsCreate FROM ObjectPermissions WHERE PermissionsCreate = true AND ParentId IN (${owned.map((ps) => `'${ps.Id}'`).join(', ')})`);
46
50
  for (const op of objectPerms) {
47
51
  const profileId = profileByPermSet.get(op.ParentId);
48
52
  if (profileId && eventObjectNames.has(op.SobjectType)) {
@@ -1,4 +1,5 @@
1
1
  import { DANGEROUS_PERMS } from '../permCatalog.js';
2
+ import { presentFields } from '../support/schema.js';
2
3
  const ADMIN_PROFILE = 'System Administrator';
3
4
  /** Admin-equivalent = holds Modify All Data, OR can self-escalate to it (Manage Users + Assign Permission Sets). */
4
5
  function isAdminEquivalent(perms) {
@@ -13,10 +14,16 @@ export class PrivilegedAccessCheck {
13
14
  async run(ctx) {
14
15
  const findings = [];
15
16
  const setupUrl = `${ctx.orgInfo.instanceUrl}/lightning/setup/ManageUsers/home`;
16
- const permFields = DANGEROUS_PERMS.map((p) => `PermissionSet.${p.field}`).join(', ');
17
- const permWhere = DANGEROUS_PERMS.map((p) => `PermissionSet.${p.field} = true`).join(' OR ');
18
17
  let rows;
18
+ // Some catalogued permissions exist only with a licence or feature (Event Monitoring, API
19
+ // Access Control). One absent field fails the whole query, so select only those this org
20
+ // has. A permission the org lacks cannot be held, so leaving it out loses nothing.
21
+ let perms = DANGEROUS_PERMS;
19
22
  try {
23
+ const present = new Set(await presentFields(ctx, 'PermissionSet', DANGEROUS_PERMS.map((p) => p.field)));
24
+ perms = DANGEROUS_PERMS.filter((p) => present.has(p.field));
25
+ const permFields = perms.map((p) => `PermissionSet.${p.field}`).join(', ');
26
+ const permWhere = perms.map((p) => `PermissionSet.${p.field} = true`).join(' OR ');
20
27
  rows = await ctx.soql.queryAll(`SELECT AssigneeId, Assignee.Username, Assignee.Name, Assignee.Profile.Name, ${permFields}
21
28
  FROM PermissionSetAssignment
22
29
  WHERE (${permWhere}) AND Assignee.IsActive = true`);
@@ -29,8 +36,8 @@ export class PrivilegedAccessCheck {
29
36
  riskLevel: 'INFO',
30
37
  inconclusive: true,
31
38
  title: 'Effective-permission resolution could not be completed',
32
- detail: `The PermissionSetAssignment query was not accessible: ${msg}`,
33
- remediation: 'Grant the audit user "View Setup and Configuration" and "View All Users", then re-run the audit.',
39
+ detail: `Effective permissions could not be read, so privileged access is unassessed. The org said: ${msg}`,
40
+ remediation: 'Check the error above. If it is an access error, confirm the audit user has "View Setup and Configuration" and "View All Users", then re-run the audit.',
34
41
  });
35
42
  return { findings };
36
43
  }
@@ -39,7 +46,7 @@ export class PrivilegedAccessCheck {
39
46
  const byUser = new Map();
40
47
  for (const row of rows) {
41
48
  const ps = row.PermissionSet ?? {};
42
- const held = DANGEROUS_PERMS.filter((p) => ps[p.field]).map((p) => p.key);
49
+ const held = perms.filter((p) => ps[p.field]).map((p) => p.key);
43
50
  if (held.length === 0)
44
51
  continue;
45
52
  let g = byUser.get(row.AssigneeId);
@@ -1,3 +1,4 @@
1
+ import { fieldsOf } from '../support/schema.js';
1
2
  export class ReleaseUpdatesCheck {
2
3
  id = 'release-updates';
3
4
  name = 'Pending Release Updates';
@@ -9,16 +10,30 @@ export class ReleaseUpdatesCheck {
9
10
  const today = new Date();
10
11
  let pendingUpdates = [];
11
12
  try {
12
- pendingUpdates = await ctx.tooling.query('SELECT Id, Name, Description, AutoActivationDate, IsEnabled FROM CriticalUpdate WHERE IsEnabled = false');
13
+ // Current orgs expose Release Updates as Tooling ReleaseUpdate; CriticalUpdate is the older
14
+ // object, absent from current releases. Use whichever this org serves.
15
+ if (await fieldsOf(ctx, 'ReleaseUpdate', 'tooling')) {
16
+ const rows = await ctx.tooling.query("SELECT Id, DeveloperName, Title, Description, DueDate, Status FROM ReleaseUpdate WHERE Status IN ('Invocable', 'Revoked')");
17
+ pendingUpdates = rows.map((r) => ({
18
+ Id: r.Id,
19
+ Name: r.Title || r.DeveloperName,
20
+ Description: r.Description,
21
+ AutoActivationDate: r.DueDate,
22
+ IsEnabled: false,
23
+ }));
24
+ }
25
+ else {
26
+ pendingUpdates = await ctx.tooling.query('SELECT Id, Name, Description, AutoActivationDate, IsEnabled FROM CriticalUpdate WHERE IsEnabled = false');
27
+ }
13
28
  }
14
- catch {
29
+ catch (err) {
15
30
  findings.push({
16
31
  id: 'release-updates-inconclusive',
17
32
  category: this.category,
18
33
  riskLevel: 'INFO',
19
34
  inconclusive: true,
20
35
  title: 'Pending release updates check could not be completed',
21
- detail: 'The CriticalUpdate Tooling API object was not accessible. This can occur if the audit user lacks the "Customize Application" permission or if the org is on a restricted edition.',
36
+ detail: `Pending release updates could not be read, so this is unassessed, not clean. The org said: ${err instanceof Error ? err.message : String(err)}`,
22
37
  remediation: 'Review pending Release Updates manually in Setup → Release Updates.',
23
38
  });
24
39
  return { findings };
@@ -9,13 +9,13 @@ export class RemoteSitesCheck {
9
9
  const baseUrl = ctx.orgInfo.instanceUrl;
10
10
  const setupUrl = `${baseUrl}/lightning/setup/SecurityRemoteProxy/home`;
11
11
  // Query active remote site settings using Tooling API
12
- const records = await ctx.tooling.query('SELECT Id, SiteName, EndpointUrl, IsActive, DisableProtocolSecurity FROM RemoteProxy WHERE IsActive = true');
12
+ const records = await ctx.tooling.query('SELECT Id, SiteName, EndpointUrl, IsActive, ProtocolMismatch FROM RemoteProxy WHERE IsActive = true');
13
13
  const count = records.length;
14
14
  // Cache the URLs for use by HardcodedCredentialsCheck
15
15
  ctx.cache.remoteSiteUrls = records.map((r) => r.EndpointUrl);
16
16
  // Flag sites with protocol security disabled — these allow insecure HTTP callouts
17
- const insecureSites = records.filter((r) => r.DisableProtocolSecurity);
18
- const secureSites = records.filter((r) => !r.DisableProtocolSecurity);
17
+ const insecureSites = records.filter((r) => r.ProtocolMismatch);
18
+ const secureSites = records.filter((r) => !r.ProtocolMismatch);
19
19
  if (insecureSites.length > 0) {
20
20
  findings.push({
21
21
  id: 'remote-sites-protocol-security-disabled',
@@ -44,7 +44,7 @@ export class RemoteSitesCheck {
44
44
  affectedItems: records.map((r) => ({
45
45
  label: r.SiteName,
46
46
  url: setupUrl,
47
- note: `${r.EndpointUrl}${r.DisableProtocolSecurity ? ' ⚠ Protocol security disabled' : ''}`,
47
+ note: `${r.EndpointUrl}${r.ProtocolMismatch ? ' ⚠ Protocol security disabled' : ''}`,
48
48
  })),
49
49
  });
50
50
  }
@@ -10,7 +10,7 @@ export class RestrictionRulesIntegrityCheck {
10
10
  const rulesUrl = `${baseUrl}/lightning/setup/ObjectManager/home`;
11
11
  let rules = [];
12
12
  try {
13
- rules = await ctx.tooling.query('SELECT Id, TargetEntity, Active, EnforcementType FROM RestrictionRule');
13
+ rules = await ctx.tooling.query('SELECT Id, MasterLabel, TargetEntity, IsActive, EnforcementType FROM RestrictionRule');
14
14
  }
15
15
  catch (err) {
16
16
  if (isMissingObjectError(err)) {
@@ -49,7 +49,7 @@ export class RestrictionRulesIntegrityCheck {
49
49
  return { findings };
50
50
  }
51
51
  // 1. Check for inactive restriction rules
52
- const inactiveRules = rules.filter((r) => r.Active === false);
52
+ const inactiveRules = rules.filter((r) => r.IsActive === false);
53
53
  if (inactiveRules.length > 0) {
54
54
  findings.push({
55
55
  id: 'restriction-rules-inactive',
@@ -67,7 +67,7 @@ export class RestrictionRulesIntegrityCheck {
67
67
  }
68
68
  // 2. Check for multiple active rules on the same TargetEntity (Salesforce anti-pattern)
69
69
  const activeRulesByEntity = new Map();
70
- for (const r of rules.filter((r) => r.Active === true)) {
70
+ for (const r of rules.filter((r) => r.IsActive === true)) {
71
71
  const list = activeRulesByEntity.get(r.TargetEntity) ?? [];
72
72
  list.push(r);
73
73
  activeRulesByEntity.set(r.TargetEntity, list);
@@ -72,12 +72,20 @@ export class SeparationOfDutiesCheck {
72
72
  });
73
73
  return { findings };
74
74
  }
75
+ // A super-admin (Modify All Data + View All Data + Manage Users) already has unrestricted control,
76
+ // rated by users-super-admin-combo; a combination adds nothing for them. Rate the others, so the
77
+ // same users are not counted towards the grade again.
78
+ const isSuperAdmin = (g) => ['ModifyAllData', 'ViewAllData', 'ManageUsers'].every((p) => g.perms.includes(p));
75
79
  let anyViolation = false;
80
+ let superAdminHolders = 0;
76
81
  for (const combo of COMBOS) {
77
- const holders = grants.filter((g) => {
82
+ const all = grants.filter((g) => {
78
83
  const s = new Set(g.perms);
79
84
  return combo.perms.every((p) => s.has(p));
80
85
  });
86
+ const holders = all.filter((g) => !isSuperAdmin(g));
87
+ const leftOut = all.length - holders.length;
88
+ superAdminHolders = Math.max(superAdminHolders, leftOut);
81
89
  if (holders.length === 0)
82
90
  continue;
83
91
  anyViolation = true;
@@ -86,7 +94,8 @@ export class SeparationOfDutiesCheck {
86
94
  category: this.category,
87
95
  riskLevel: combo.risk,
88
96
  title: `${holders.length} user(s) hold a toxic permission combination: ${combo.label}`,
89
- detail: `${combo.why} Each permission may look acceptable in isolation, which is why combination review matters.`,
97
+ detail: `${combo.why} Each permission may look acceptable in isolation, which is why combination review matters.` +
98
+ (leftOut > 0 ? ` ${leftOut} super-admin(s) also hold it and are rated in the super-admin finding instead.` : ''),
90
99
  remediation: combo.fix,
91
100
  affectedItems: holders.map((g) => ({
92
101
  label: g.username,
@@ -104,7 +113,9 @@ export class SeparationOfDutiesCheck {
104
113
  title: 'No toxic permission combinations detected',
105
114
  detail: grants.length === 0
106
115
  ? 'No active users hold catalogued high-risk permissions, so no separation-of-duties conflicts arise.'
107
- : 'No active user holds a flagged combination of permissions that would violate separation of duties.',
116
+ : superAdminHolders > 0
117
+ ? `Only super-admins hold flagged combinations; they already have unrestricted control and are rated in the super-admin finding (users-super-admin-combo). No other active user holds a flagged combination.`
118
+ : 'No active user holds a flagged combination of permissions that would violate separation of duties.',
108
119
  remediation: 'Continue to separate user administration, code authorship, identity, and data-access duties across roles.',
109
120
  });
110
121
  }
@@ -1,3 +1,4 @@
1
+ import { hasField } from '../support/schema.js';
1
2
  /**
2
3
  * Ninety days rather than thirty. SOAP callers are disproportionately the least routine
3
4
  * things in an org: a quarterly reconciliation job, a backup tool, a device switched on
@@ -48,7 +49,21 @@ export class SoapLoginApiAuthCheck {
48
49
  // grant paths, because a profile's own permissions live on a PermissionSet with
49
50
  // IsOwnedByProfile = true. Orgs on a release without the field will throw here.
50
51
  let holders = [];
52
+ const notYet = {
53
+ id: 'soap-login-api-auth-inconclusive-field',
54
+ category: this.category,
55
+ riskLevel: 'INFO',
56
+ inconclusive: true,
57
+ title: '"Use Any API Auth" permission is not queryable in this org yet',
58
+ detail: 'The PermissionsUseAnyApiAuth field is not available. That is expected on orgs not yet upgraded to a release that carries it, and it means readiness for the Winter \'27 SOAP login() change cannot be assessed here. Note this permission is not the same as "Use Any API Client", which is covered separately by the api-client-permission check.',
59
+ remediation: `Re-run this audit after the org takes Winter '27, or check Setup → Permission Sets for "Use Any API Auth" directly: ${permSetUrl}`,
60
+ };
51
61
  try {
62
+ // Describe first: on a release without the field, filtering on it is rejected outright.
63
+ if (!(await hasField(ctx, 'PermissionSet', 'PermissionsUseAnyApiAuth'))) {
64
+ findings.push(notYet);
65
+ return { findings };
66
+ }
52
67
  const result = await ctx.soql.query(`SELECT Assignee.Id, Assignee.Username, Assignee.Profile.Name,
53
68
  PermissionSet.Name, PermissionSet.IsOwnedByProfile
54
69
  FROM PermissionSetAssignment
@@ -56,15 +71,12 @@ export class SoapLoginApiAuthCheck {
56
71
  AND Assignee.IsActive = true`);
57
72
  holders = result.records;
58
73
  }
59
- catch {
74
+ catch (err) {
60
75
  findings.push({
61
- id: 'soap-login-api-auth-inconclusive-field',
62
- category: this.category,
63
- riskLevel: 'INFO',
64
- inconclusive: true,
65
- title: '"Use Any API Auth" permission is not queryable in this org yet',
66
- detail: 'The PermissionsUseAnyApiAuth field was not available. That is expected on orgs not yet upgraded to a release that carries it, and it means readiness for the Winter \'27 SOAP login() change cannot be assessed here. Note this permission is not the same as "Use Any API Client", which is covered separately by the api-client-permission check.',
67
- remediation: `Re-run this audit after the org takes Winter '27, or check Setup → Permission Sets for "Use Any API Auth" directly: ${permSetUrl}`,
76
+ ...notYet,
77
+ title: '"Use Any API Auth" holders could not be read',
78
+ detail: `Who holds "Use Any API Auth" could not be read, so readiness for the Winter '27 SOAP login() change is unassessed. The org said: ${err instanceof Error ? err.message : String(err)}`,
79
+ 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.',
68
80
  });
69
81
  return { findings };
70
82
  }
@@ -10,7 +10,9 @@ export class SsoEnforcementCheck {
10
10
  // Single query: recent credential logins over the past 30 days.
11
11
  // Presence of 'Username-Password' logins is direct evidence that SBS-AUTH-001
12
12
  // (org-wide SSO enforcement) is not fully applied.
13
- const result = await ctx.soql.queryAll(`SELECT Id, UserId, Username, LoginType, LoginTime
13
+ const result = await ctx.soql.queryAll(
14
+ // LoginHistory carries no Username field and no User relationship; names are resolved below.
15
+ `SELECT Id, UserId, LoginType, LoginTime
14
16
  FROM LoginHistory
15
17
  WHERE LoginTime > LAST_N_DAYS:30
16
18
  AND LoginType = 'Username-Password'
@@ -37,9 +39,17 @@ export class SsoEnforcementCheck {
37
39
  existing.count++;
38
40
  }
39
41
  else {
40
- byUser.set(r.UserId, { username: r.Username, count: 1, latest: r.LoginTime });
42
+ byUser.set(r.UserId, { username: r.UserId, count: 1, latest: r.LoginTime });
41
43
  }
42
44
  }
45
+ // At most 300 logins, so at most 300 distinct users: one bounded lookup.
46
+ const inClause = [...byUser.keys()].map((id) => `'${id}'`).join(',');
47
+ const users = await ctx.soql.queryAll(`SELECT Id, Username FROM User WHERE Id IN (${inClause})`);
48
+ for (const u of users) {
49
+ const entry = byUser.get(u.Id);
50
+ if (entry)
51
+ entry.username = u.Username;
52
+ }
43
53
  const uniqueUsers = [...byUser.entries()];
44
54
  findings.push({
45
55
  id: 'sso-password-logins-detected',
@@ -72,14 +82,15 @@ export class SsoEnforcementCheck {
72
82
  });
73
83
  }
74
84
  }
75
- catch {
85
+ catch (err) {
86
+ const reason = err instanceof Error ? err.message : String(err);
76
87
  findings.push({
77
88
  id: 'sso-enforcement-inconclusive',
78
89
  category: this.category,
79
90
  riskLevel: 'INFO',
80
91
  inconclusive: true,
81
- title: 'SSO enforcement status could not be determined: LoginHistory not accessible',
82
- detail: 'SBS-AUTH-001/002 require SSO enforcement configuration to be verified. LoginHistory was not accessible with current permissions.',
92
+ title: 'SSO enforcement status could not be determined: LoginHistory could not be read',
93
+ detail: `SBS-AUTH-001/002 require SSO enforcement configuration to be verified. LoginHistory could not be read: ${reason}`,
83
94
  remediation: 'Manually verify in Setup → Single Sign-On Settings that "Prevent Login with Salesforce Credentials" is enabled.',
84
95
  });
85
96
  }
@@ -9,17 +9,17 @@ export class TransactionSecurityPolicyCheck {
9
9
  const setupUrl = `${baseUrl}/lightning/setup/TransactionSecurityPolicies/home`;
10
10
  let policies;
11
11
  try {
12
- policies = await ctx.tooling.query(`SELECT Id, Name, EventType, State FROM TransactionSecurityPolicy WHERE State = 'Enabled'`);
12
+ policies = await ctx.tooling.query(`SELECT Id, DeveloperName, MasterLabel, EventType, State FROM TransactionSecurityPolicy WHERE State = 'Enabled'`);
13
13
  }
14
- catch {
14
+ catch (err) {
15
15
  findings.push({
16
16
  id: 'transaction-security-policy-inaccessible',
17
17
  category: this.category,
18
18
  riskLevel: 'INFO',
19
19
  inconclusive: true,
20
20
  title: 'Transaction Security Policies could not be queried',
21
- detail: 'The Tooling API TransactionSecurityPolicy query was not accessible. This may indicate the audit user lacks Tooling API access, or Transaction Security is not enabled for this org.',
22
- remediation: 'Enable Transaction Security in Setup and grant Tooling API access to the audit user, then re-run.',
21
+ detail: `The Tooling API TransactionSecurityPolicy query failed, so whether automated threat response exists is unassessed, not absent: ${err instanceof Error ? err.message : String(err)}`,
22
+ remediation: 'Check the error above. If it is an access error, confirm the audit user has API Enabled and View Setup and Configuration, then re-run.',
23
23
  });
24
24
  return { findings };
25
25
  }
@@ -51,7 +51,7 @@ export class TransactionSecurityPolicyCheck {
51
51
  detail: `Active Transaction Security Policies covering: ${eventTypes.join(', ')}. Automated threat detection and response is in place for these event types.`,
52
52
  remediation: 'Periodically review policies to ensure coverage includes login anomalies, bulk data exports, and high-volume API usage. Verify that policy actions (Block/Notify) are appropriate for each event type.',
53
53
  affectedItems: policies.map((p) => ({
54
- label: p.Name,
54
+ label: p.MasterLabel || p.DeveloperName,
55
55
  url: setupUrl,
56
56
  note: `EventType: ${p.EventType}`,
57
57
  })),
@@ -13,27 +13,36 @@ export class TrustedIPRangesCheck {
13
13
  const findings = [];
14
14
  const baseUrl = ctx.orgInfo.instanceUrl;
15
15
  const setupUrl = `${baseUrl}/lightning/setup/SecurityNetworkAccess/home`;
16
- let ranges = [];
17
- try {
18
- const result = await ctx.soql.query(`SELECT Id, StartAddress, EndAddress, Description
19
- FROM NetworkAccess
20
- ORDER BY StartAddress
21
- LIMIT 200`);
22
- ranges = result.records;
16
+ let settings = null;
17
+ let error = 'this run has no Metadata API client';
18
+ if (ctx.metadata) {
19
+ try {
20
+ settings = await ctx.metadata.read('SecuritySettings', 'Security');
21
+ if (!settings)
22
+ error = 'the Security settings were not returned';
23
+ }
24
+ catch (err) {
25
+ error = err instanceof Error ? err.message : String(err);
26
+ }
23
27
  }
24
- catch {
28
+ if (!settings) {
25
29
  findings.push({
26
30
  id: 'trusted-ip-inaccessible',
27
31
  category: this.category,
28
32
  riskLevel: 'INFO',
29
33
  inconclusive: true,
30
34
  title: 'Trusted IP ranges could not be retrieved',
31
- detail: 'The NetworkAccess object was not accessible. This may indicate insufficient permissions to query network access settings.',
35
+ detail: `Trusted IP ranges are read from the Security settings in the Metadata API, and could not be: ${error}.`,
32
36
  remediation: 'Review trusted IP ranges manually in Setup → Security → Network Access. Ensure the audit user has "View Setup and Configuration" permission.',
33
37
  affectedItems: [{ label: 'Network Access Setup', url: setupUrl }],
34
38
  });
35
39
  return { findings };
36
40
  }
41
+ // The Metadata API returns a single range as an object, several as an array.
42
+ const raw = settings.networkAccess?.ipRanges;
43
+ const ranges = (raw === undefined ? [] : Array.isArray(raw) ? raw : [raw])
44
+ .filter((r) => r.start && r.end)
45
+ .map((r) => ({ StartAddress: r.start, EndAddress: r.end, Description: r.description ?? null }));
37
46
  if (ranges.length === 0) {
38
47
  findings.push({
39
48
  id: 'trusted-ip-none',
@@ -43,6 +43,12 @@ export class UsersAndAdminsCheck {
43
43
  const viewAllCount = viewAllIds.size;
44
44
  const customizeAppCount = uniqueIds(customizeAppUsers).size;
45
45
  const authorApexCount = uniqueIds(authorApexUsers).size;
46
+ // In a sandbox, developers routinely hold admin: cap admin-count findings at HIGH, and say so.
47
+ const isSandbox = ctx.orgInfo.isSandbox;
48
+ const sandboxCap = (level) => isSandbox && level === 'CRITICAL' ? 'HIGH' : level;
49
+ const sandboxNote = isSandbox
50
+ ? ' Rated at most HIGH because this org is a sandbox, where developers commonly hold admin; treat it as CRITICAL if this sandbox holds production data.'
51
+ : '';
46
52
  // SBS-ACS-004: flag users with ALL THREE super-admin permissions simultaneously
47
53
  const superAdminIds = [...modifyAllIds].filter((id) => viewAllIds.has(id) && manageUsersIds.has(id));
48
54
  if (superAdminIds.length > 0) {
@@ -53,20 +59,33 @@ export class UsersAndAdminsCheck {
53
59
  findings.push({
54
60
  id: 'users-super-admin-combo',
55
61
  category: this.category,
56
- riskLevel: 'CRITICAL',
62
+ // Every org needs an administrator: grade on how many hold unrestricted control.
63
+ riskLevel: sandboxCap(superAdminIds.length > 5 ? 'CRITICAL' : superAdminIds.length > 3 ? 'HIGH' : 'LOW'),
57
64
  title: `${superAdminIds.length} user(s) hold the super-admin permission combination (ViewAllData + ModifyAllData + ManageUsers)`,
58
- detail: 'SBS-ACS-004 requires documented justification for any user holding all three of ViewAllData, ModifyAllData, and ManageUsers simultaneously. This combination is equivalent to unrestricted org control.',
65
+ detail: 'SBS-ACS-004 requires documented justification for any user holding all three of ViewAllData, ModifyAllData, and ManageUsers simultaneously. This combination is equivalent to unrestricted org control.' +
66
+ (superAdminIds.length > 5 ? sandboxNote : ''),
59
67
  remediation: 'Reduce to the minimum necessary permissions. Document justification for each user in the system of record. Consider breaking this into role-specific permission sets.',
60
68
  affectedItems: superAdminItems,
61
69
  });
62
70
  }
63
- const modifyRisk = modifyAllCount > 5 ? 'CRITICAL' : modifyAllCount > 3 ? 'HIGH' : 'LOW';
71
+ // Rate Modify All Data on the holders the super-admin finding does not already cover, so the
72
+ // same users are not counted towards the grade twice. The finding still lists every holder.
73
+ const superAdminSet = new Set(superAdminIds);
74
+ const otherModifyAll = [...modifyAllIds].filter((id) => !superAdminSet.has(id)).length;
75
+ const modifyRisk = sandboxCap(otherModifyAll > 5 ? 'CRITICAL' : otherModifyAll > 3 ? 'HIGH' : 'LOW');
76
+ const coveredNote = superAdminSet.size > 0
77
+ ? ` ${superAdminSet.size} of them also hold the super-admin combination and are rated in that finding; this severity reflects the other ${otherModifyAll}.`
78
+ : '';
64
79
  findings.push({
65
80
  id: 'users-modify-all-data',
66
81
  category: this.category,
67
82
  riskLevel: modifyRisk,
68
83
  title: `${modifyAllCount} user(s) have Modify All Data permission`,
69
- detail: 'Modify All Data grants unrestricted write access across all objects. This is one of the most powerful permissions in Salesforce.',
84
+ // The population is always reported; at the lowest band it asks for no change.
85
+ passed: modifyRisk === 'LOW' || undefined,
86
+ detail: 'Modify All Data grants unrestricted write access across all objects. This is one of the most powerful permissions in Salesforce.' +
87
+ coveredNote +
88
+ (modifyRisk === 'HIGH' && otherModifyAll > 5 ? sandboxNote : ''),
70
89
  remediation: 'Limit Modify All Data to essential system administrators only. Review each user and remove the permission from any non-essential accounts.',
71
90
  affectedItems: modifyAllUsers.map((r) => userItem(r)),
72
91
  });
@@ -76,6 +95,7 @@ export class UsersAndAdminsCheck {
76
95
  category: this.category,
77
96
  riskLevel: viewRisk,
78
97
  title: `${viewAllCount} user(s) have View All Data permission`,
98
+ passed: viewRisk === 'LOW' || undefined,
79
99
  detail: 'View All Data grants unrestricted read access across all objects, bypassing sharing rules and record-level security.',
80
100
  remediation: 'Limit View All Data to essential users. Consider using permission sets scoped to specific objects instead.',
81
101
  affectedItems: viewAllUsers.map((r) => userItem(r)),
@@ -31,7 +31,7 @@ export const DANGEROUS_PERMS = [
31
31
  why: 'Bypass API Access Control to reach the org from any tool.' },
32
32
  { key: 'ManageEventLogFiles', field: 'PermissionsManageEventLogFiles', label: 'Manage Event Log Files', tier: 'MEDIUM',
33
33
  why: 'Access detailed monitoring/event data across the org.' },
34
- { key: 'ManageSession', field: 'PermissionsManageSession', label: 'Manage Session Permission Set Activations', tier: 'MEDIUM',
34
+ { key: 'ManageSession', field: 'PermissionsManageSessionPermissionSets', label: 'Manage Session Permission Set Activations', tier: 'MEDIUM',
35
35
  why: 'Activate session-based permission sets, elevating access on demand.' },
36
36
  { key: 'ViewAllUsers', field: 'PermissionsViewAllUsers', label: 'View All Users', tier: 'MEDIUM',
37
37
  why: 'Enumerate every user in the org: reconnaissance for targeting.' },