@cclabsnz/sf-audit 1.15.1 → 1.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (119) hide show
  1. package/CHANGELOG.md +143 -1
  2. package/README.md +100 -24
  3. package/config/scoring.sample.json +104 -5
  4. package/lib/apps/analyzeApps.d.ts +8 -2
  5. package/lib/apps/analyzeApps.js +7 -2
  6. package/lib/apps/apiLogSource.d.ts +39 -0
  7. package/lib/apps/apiLogSource.js +75 -0
  8. package/lib/apps/appResolver.js +30 -4
  9. package/lib/apps/grantedAccess.js +16 -3
  10. package/lib/apps/leastPrivilege.d.ts +3 -1
  11. package/lib/apps/leastPrivilege.js +7 -3
  12. package/lib/apps/permissionSetGenerator.d.ts +22 -0
  13. package/lib/apps/permissionSetGenerator.js +100 -0
  14. package/lib/apps/types.d.ts +6 -0
  15. package/lib/apps/usageCollector.d.ts +7 -1
  16. package/lib/apps/usageCollector.js +57 -26
  17. package/lib/chains/CapabilityRegistry.js +26 -0
  18. package/lib/chains/namedChains.js +110 -3
  19. package/lib/checks/CheckEngine.d.ts +3 -1
  20. package/lib/checks/CheckEngine.js +11 -3
  21. package/lib/checks/impl/AgentInventoryCheck.js +8 -3
  22. package/lib/checks/impl/AgentOutboundActionsCheck.d.ts +13 -0
  23. package/lib/checks/impl/AgentOutboundActionsCheck.js +155 -0
  24. package/lib/checks/impl/AgentQueryReachCheck.d.ts +11 -0
  25. package/lib/checks/impl/AgentQueryReachCheck.js +88 -0
  26. package/lib/checks/impl/ApexCrudFLSCheck.js +45 -10
  27. package/lib/checks/impl/ApexSharingCheck.js +16 -25
  28. package/lib/checks/impl/AuthProviderRegistrationHandlerCheck.d.ts +10 -0
  29. package/lib/checks/impl/AuthProviderRegistrationHandlerCheck.js +131 -0
  30. package/lib/checks/impl/ConnectedAppsCheck.js +47 -1
  31. package/lib/checks/impl/DataCloudDataSpaceIsolationCheck.d.ts +10 -0
  32. package/lib/checks/impl/DataCloudDataSpaceIsolationCheck.js +116 -0
  33. package/lib/checks/impl/DelegatedAdministrationGroupsCheck.d.ts +10 -0
  34. package/lib/checks/impl/DelegatedAdministrationGroupsCheck.js +75 -0
  35. package/lib/checks/impl/DelegatedAuthenticationExposureCheck.d.ts +10 -0
  36. package/lib/checks/impl/DelegatedAuthenticationExposureCheck.js +98 -0
  37. package/lib/checks/impl/ExternalAccountHierarchyExposureCheck.d.ts +10 -0
  38. package/lib/checks/impl/ExternalAccountHierarchyExposureCheck.js +73 -0
  39. package/lib/checks/impl/FlowHttpCalloutCredentialBypassCheck.d.ts +10 -0
  40. package/lib/checks/impl/FlowHttpCalloutCredentialBypassCheck.js +115 -0
  41. package/lib/checks/impl/GenAiPromptTemplateGroundingCheck.d.ts +10 -0
  42. package/lib/checks/impl/GenAiPromptTemplateGroundingCheck.js +227 -0
  43. package/lib/checks/impl/GuestExecutableApexCheck.d.ts +1 -1
  44. package/lib/checks/impl/GuestExecutableApexCheck.js +105 -14
  45. package/lib/checks/impl/HardcodedCredentialsCheck.js +7 -2
  46. package/lib/checks/impl/InboundEmailHandlerExposureCheck.d.ts +10 -0
  47. package/lib/checks/impl/InboundEmailHandlerExposureCheck.js +136 -0
  48. package/lib/checks/impl/OauthDeviceAndAssetTokenFlowsCheck.d.ts +10 -0
  49. package/lib/checks/impl/OauthDeviceAndAssetTokenFlowsCheck.js +84 -0
  50. package/lib/checks/impl/OrgWideEmailSpoofingCheck.d.ts +10 -0
  51. package/lib/checks/impl/OrgWideEmailSpoofingCheck.js +106 -0
  52. package/lib/checks/impl/PackagePostInstallSupplyChainCheck.d.ts +10 -0
  53. package/lib/checks/impl/PackagePostInstallSupplyChainCheck.js +89 -0
  54. package/lib/checks/impl/PlatformEventSubscriberContextCheck.d.ts +10 -0
  55. package/lib/checks/impl/PlatformEventSubscriberContextCheck.js +84 -0
  56. package/lib/checks/impl/RestrictionRulesIntegrityCheck.d.ts +10 -0
  57. package/lib/checks/impl/RestrictionRulesIntegrityCheck.js +105 -0
  58. package/lib/checks/impl/ShieldTenantSecretLifecycleCheck.d.ts +10 -0
  59. package/lib/checks/impl/ShieldTenantSecretLifecycleCheck.js +90 -0
  60. package/lib/checks/registry.js +34 -0
  61. package/lib/checks/support/agentGraph.d.ts +49 -0
  62. package/lib/checks/support/agentGraph.js +87 -0
  63. package/lib/checks/support/apexAccess.d.ts +56 -0
  64. package/lib/checks/support/apexAccess.js +127 -0
  65. package/lib/checks/support/missingObject.d.ts +13 -0
  66. package/lib/checks/support/missingObject.js +35 -0
  67. package/lib/commands/audit/apps.d.ts +1 -0
  68. package/lib/commands/audit/apps.js +83 -29
  69. package/lib/commands/audit/diff.js +2 -2
  70. package/lib/commands/audit/history.js +2 -2
  71. package/lib/commands/audit/incident/report.js +2 -2
  72. package/lib/commands/audit/security.d.ts +3 -0
  73. package/lib/commands/audit/security.js +58 -9
  74. package/lib/commands/audit/timeline.js +2 -2
  75. package/lib/compliance/mapping.js +35 -7
  76. package/lib/findings/AuditResult.d.ts +8 -0
  77. package/lib/findings/CheckMeta.js +17 -0
  78. package/lib/findings/Finding.d.ts +4 -0
  79. package/lib/findings/ScoringConfig.d.ts +10 -8
  80. package/lib/findings/ScoringConfig.js +12 -5
  81. package/lib/findings/coverage.d.ts +28 -0
  82. package/lib/findings/coverage.js +30 -0
  83. package/lib/findings/exitCode.js +1 -1
  84. package/lib/findings/loadScoringConfig.js +51 -8
  85. package/lib/findings/scoring.js +14 -5
  86. package/lib/history/HistoryStore.js +9 -3
  87. package/lib/history/archivePolicy.d.ts +19 -0
  88. package/lib/history/archivePolicy.js +34 -0
  89. package/lib/incident/bundleIo.js +4 -3
  90. package/lib/incident/collect/collectBundle.d.ts +1 -1
  91. package/lib/incident/collect/collectBundle.js +4 -3
  92. package/lib/incident/collect/streamGuestLogs.d.ts +1 -1
  93. package/lib/incident/collect/streamGuestLogs.js +3 -2
  94. package/lib/incident/csv.js +4 -4
  95. package/lib/incident/render/evidence.js +3 -3
  96. package/lib/incident/render/html.js +2 -3
  97. package/lib/index.d.ts +2 -0
  98. package/lib/index.js +2 -0
  99. package/lib/lib/packageInfo.d.ts +6 -0
  100. package/lib/lib/packageInfo.js +19 -0
  101. package/lib/renderers/AttackChainDagRenderer.d.ts +7 -0
  102. package/lib/renderers/AttackChainDagRenderer.js +139 -0
  103. package/lib/renderers/ClientReportRenderer.d.ts +2 -0
  104. package/lib/renderers/ClientReportRenderer.js +34 -6
  105. package/lib/renderers/DiffHtmlRenderer.js +2 -7
  106. package/lib/renderers/HistoryRenderer.js +19 -11
  107. package/lib/renderers/HtmlRenderer.js +19 -6
  108. package/lib/renderers/MarkdownRenderer.js +7 -0
  109. package/lib/renderers/SarifRenderer.d.ts +43 -0
  110. package/lib/renderers/SarifRenderer.js +250 -0
  111. package/lib/report/ExecutivePriorities.js +1 -1
  112. package/lib/report/RemediationRoadmap.js +1 -1
  113. package/lib/waivers/WaiverLoader.d.ts +28 -0
  114. package/lib/waivers/WaiverLoader.js +103 -0
  115. package/lib/waivers/WaiverModel.d.ts +32 -0
  116. package/lib/waivers/WaiverModel.js +28 -0
  117. package/lib/waivers/applyWaivers.d.ts +22 -0
  118. package/lib/waivers/applyWaivers.js +85 -0
  119. package/package.json +3 -3
@@ -0,0 +1,136 @@
1
+ export class InboundEmailHandlerExposureCheck {
2
+ id = 'inbound-email-handler-exposure';
3
+ name = 'Inbound Email Handler Unauthenticated Execution';
4
+ category = 'External Connectivity';
5
+ description = 'Detects active inbound email services open to all senders without SPF/DKIM verification executing Apex under privileged users.';
6
+ async run(ctx) {
7
+ const findings = [];
8
+ const baseUrl = ctx.orgInfo.instanceUrl;
9
+ const emailToApexUrl = `${baseUrl}/lightning/setup/EmailToApex/home`;
10
+ let functions = [];
11
+ try {
12
+ functions = await ctx.soql.queryAll('SELECT Id, FunctionName, IsActive, RunAsUserId, ApexClassId, AuthenticationFailureAction FROM EmailServicesFunction WHERE IsActive = true');
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: 'inbound-email-handler-exposure-inaccessible',
18
+ category: this.category,
19
+ riskLevel: 'INFO',
20
+ inconclusive: true,
21
+ title: 'Email Services Functions could not be queried',
22
+ detail: `Query to EmailServicesFunction failed: ${err instanceof Error ? err.message : String(err)}`,
23
+ remediation: 'Grant the audit user "View Setup and Configuration".',
24
+ });
25
+ return { findings };
26
+ }
27
+ if (functions.length === 0) {
28
+ findings.push({
29
+ id: 'inbound-email-handler-exposure-ok',
30
+ category: this.category,
31
+ riskLevel: 'LOW',
32
+ passed: true,
33
+ title: 'No active inbound Email-to-Apex services found',
34
+ detail: 'Zero active EmailServicesFunction records exist in the org.',
35
+ remediation: 'When creating inbound email services, enforce sender restrictions and SPF/DKIM verification.',
36
+ });
37
+ return { findings };
38
+ }
39
+ // Query active EmailServicesAddress records
40
+ let addresses = [];
41
+ addresses = await ctx.soql.queryAll('SELECT Id, FunctionId, LocalPart, EmailDomainName, IsActive, AuthorizedSenders FROM EmailServicesAddress WHERE IsActive = true');
42
+ const addressesByFunction = new Map();
43
+ for (const a of addresses) {
44
+ const list = addressesByFunction.get(a.FunctionId) ?? [];
45
+ list.push(a);
46
+ addressesByFunction.set(a.FunctionId, list);
47
+ }
48
+ // Query RunAs users
49
+ const runAsUserIds = [
50
+ ...new Set(functions.map((f) => f.RunAsUserId).filter((id) => Boolean(id))),
51
+ ];
52
+ let adminUsers = new Set();
53
+ let userDetails = new Map();
54
+ if (runAsUserIds.length > 0) {
55
+ const users = await ctx.soql.queryAll(`SELECT Id, Username, Profile.Name FROM User WHERE Id IN ('${runAsUserIds.join("','")}')`);
56
+ for (const u of users) {
57
+ const prof = u.Profile?.Name ?? '';
58
+ userDetails.set(u.Id, `${u.Username} (${prof})`);
59
+ if (prof === 'System Administrator' || prof.toLowerCase().includes('admin')) {
60
+ adminUsers.add(u.Id);
61
+ }
62
+ }
63
+ }
64
+ // Query Apex Classes
65
+ const apexClassIds = [
66
+ ...new Set(functions.map((f) => f.ApexClassId).filter((id) => Boolean(id))),
67
+ ];
68
+ let classBodies = new Map();
69
+ let classNames = new Map();
70
+ if (apexClassIds.length > 0) {
71
+ const classes = await ctx.soql.queryAll(`SELECT Id, Name, Body FROM ApexClass WHERE Id IN ('${apexClassIds.join("','")}')`);
72
+ for (const c of classes) {
73
+ classNames.set(c.Id, c.Name);
74
+ classBodies.set(c.Id, c.Body ?? '');
75
+ }
76
+ }
77
+ const exposedFunctions = [];
78
+ for (const fn of functions) {
79
+ const funcAddresses = addressesByFunction.get(fn.Id) ?? [];
80
+ // Check 1: Any address with empty/blank AuthorizedSenders
81
+ const openAddress = funcAddresses.find((a) => !a.AuthorizedSenders || a.AuthorizedSenders.trim() === '');
82
+ // Check 2: AuthenticationFailureAction is 0 or '0' (None / accept even spoofed emails)
83
+ const authFailureAction = String(fn.AuthenticationFailureAction ?? '0');
84
+ const acceptsSpoofedEmail = authFailureAction === '0' || authFailureAction === '';
85
+ // Check 3: RunAsUserId is admin or class runs without sharing / performs DML
86
+ const isRunAsAdmin = fn.RunAsUserId ? adminUsers.has(fn.RunAsUserId) : false;
87
+ const classBody = fn.ApexClassId ? classBodies.get(fn.ApexClassId) ?? '' : '';
88
+ const isWithoutSharing = /without\s+sharing/i.test(classBody);
89
+ const hasDmlOrDynamicSoql = /insert\s+|update\s+|upsert\s+|delete\s+|Database\.execute/i.test(classBody);
90
+ if (openAddress && acceptsSpoofedEmail && (isRunAsAdmin || isWithoutSharing || hasDmlOrDynamicSoql)) {
91
+ const addrStr = `${openAddress.LocalPart}${openAddress.EmailDomainName ? '@' + openAddress.EmailDomainName : ''}`;
92
+ const reasons = [
93
+ 'No sender restriction (AuthorizedSenders is blank)',
94
+ 'AuthenticationFailureAction is set to None (accepts spoofed SPF/DKIM)',
95
+ isRunAsAdmin ? 'Runs as System Administrator' : '',
96
+ isWithoutSharing ? 'Apex runs without sharing' : '',
97
+ ]
98
+ .filter(Boolean)
99
+ .join('; ');
100
+ exposedFunctions.push({
101
+ func: fn,
102
+ address: addrStr,
103
+ reason: reasons,
104
+ });
105
+ }
106
+ }
107
+ if (exposedFunctions.length > 0) {
108
+ findings.push({
109
+ id: 'inbound-email-handler-unauthenticated-execution',
110
+ category: this.category,
111
+ riskLevel: 'HIGH',
112
+ title: `${exposedFunctions.length} inbound email service(s) allow unauthenticated remote Apex execution`,
113
+ detail: 'Active EmailServicesFunction records accept messages from any internet sender with no SPF/DKIM authentication enforcement (AuthenticationFailureAction = 0 / None) and execute under a privileged System Administrator or in an Apex class running without sharing. An external attacker sending an email can trigger unauthenticated backend DML or privilege escalation.',
114
+ remediation: 'Configure "Accept Email From" with an authorized domain allowlist, set the Failure Action to "Bounce message" or "Discard message" upon SPF/DKIM verification failure, and run the service under a least-privileged execution user.',
115
+ affectedItems: exposedFunctions.map((item) => ({
116
+ label: `${item.func.FunctionName} (${item.address})`,
117
+ url: emailToApexUrl,
118
+ note: item.reason,
119
+ })),
120
+ });
121
+ }
122
+ else {
123
+ findings.push({
124
+ id: 'inbound-email-handler-exposure-ok',
125
+ category: this.category,
126
+ riskLevel: 'LOW',
127
+ passed: true,
128
+ title: 'Inbound email services enforce sender restrictions and authentication controls',
129
+ detail: `${functions.length} active inbound email service(s) inspected; all require authentication, enforce sender allowlists, or execute under constrained least-privilege contexts.`,
130
+ remediation: 'Continue enforcing sender allowlists and bounce/discard policies on SPF/DKIM failure.',
131
+ });
132
+ }
133
+ return { findings };
134
+ }
135
+ }
136
+ //# sourceMappingURL=InboundEmailHandlerExposureCheck.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 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
@@ -0,0 +1,10 @@
1
+ import type { AuditContext } from '@cclabsnz/sf-core';
2
+ import type { SecurityCheck, CheckResult } from '../SecurityCheck.js';
3
+ export declare class PackagePostInstallSupplyChainCheck implements SecurityCheck {
4
+ readonly id = "package-post-install-supply-chain";
5
+ readonly name = "Package Post-Install Supply Chain Risk";
6
+ readonly category = "Platform Hygiene";
7
+ readonly description = "Finds packaged Apex implementing InstallHandler, which runs in system context on every install and push upgrade.";
8
+ run(ctx: AuditContext): Promise<CheckResult>;
9
+ }
10
+ //# sourceMappingURL=PackagePostInstallSupplyChainCheck.d.ts.map
@@ -0,0 +1,89 @@
1
+ import { isMissingObjectError } from '../support/missingObject.js';
2
+ // Managed-package Apex is returned with its body replaced by this marker, so whether such a
3
+ // class implements InstallHandler cannot be read from the org.
4
+ const HIDDEN_BODY = '(hidden)';
5
+ const IMPLEMENTS_INSTALL_HANDLER = /\bimplements\b[^{]*\bInstallHandler\b/i;
6
+ export class PackagePostInstallSupplyChainCheck {
7
+ id = 'package-post-install-supply-chain';
8
+ name = 'Package Post-Install Supply Chain Risk';
9
+ category = 'Platform Hygiene';
10
+ description = 'Finds packaged Apex implementing InstallHandler, which runs in system context on every install and push upgrade.';
11
+ async run(ctx) {
12
+ const findings = [];
13
+ const packagesUrl = `${ctx.orgInfo.instanceUrl}/lightning/setup/ImportedPackage/home`;
14
+ let installedPackages;
15
+ try {
16
+ installedPackages = await ctx.tooling.query('SELECT Id, SubscriberPackageId FROM InstalledSubscriberPackage');
17
+ }
18
+ catch (err) {
19
+ if (!isMissingObjectError(err))
20
+ throw err;
21
+ installedPackages = [];
22
+ }
23
+ if (installedPackages.length === 0) {
24
+ findings.push({
25
+ id: 'package-post-install-ok',
26
+ category: this.category,
27
+ riskLevel: 'LOW',
28
+ passed: true,
29
+ title: 'No installed subscriber packages found in org',
30
+ detail: 'Zero InstalledSubscriberPackage records were identified.',
31
+ remediation: 'Continue inventorying new packages when installed.',
32
+ });
33
+ return { findings };
34
+ }
35
+ const namespacedClasses = await ctx.tooling.query('SELECT Id, Name, NamespacePrefix, Body FROM ApexClass WHERE NamespacePrefix != null');
36
+ const handlers = [];
37
+ const hiddenNamespaces = new Set();
38
+ for (const c of namespacedClasses) {
39
+ const classBody = c.Body ?? '';
40
+ if (classBody.trim() === HIDDEN_BODY || classBody === '') {
41
+ if (c.NamespacePrefix)
42
+ hiddenNamespaces.add(c.NamespacePrefix);
43
+ }
44
+ else if (IMPLEMENTS_INSTALL_HANDLER.test(classBody)) {
45
+ handlers.push(c);
46
+ }
47
+ }
48
+ if (handlers.length > 0) {
49
+ findings.push({
50
+ id: 'package-post-install-system-script',
51
+ category: this.category,
52
+ riskLevel: 'MEDIUM',
53
+ title: `${handlers.length} packaged class(es) implement InstallHandler and run on install and upgrade`,
54
+ detail: 'A class implementing InstallHandler runs unattended Apex in system context whenever its package is installed or upgraded, including vendor push upgrades. That execution bypasses admin approval and change-management gates.',
55
+ remediation: 'Review what each post-install script does, confirm the vendor publishes it, and agree a push-upgrade schedule with the vendor.',
56
+ affectedItems: handlers.map((c) => ({
57
+ label: `${c.NamespacePrefix}.${c.Name}`,
58
+ url: packagesUrl,
59
+ note: 'Implements InstallHandler',
60
+ })),
61
+ });
62
+ }
63
+ if (hiddenNamespaces.size > 0) {
64
+ const namespaces = [...hiddenNamespaces].sort();
65
+ findings.push({
66
+ id: 'package-post-install-unverifiable',
67
+ category: this.category,
68
+ riskLevel: 'INFO',
69
+ title: `${namespaces.length} managed package namespace(s) hide their Apex, so post-install scripts cannot be checked`,
70
+ detail: 'Managed packages hide their Apex source, so this run cannot tell whether any of them implements InstallHandler. A package that does runs Apex in system context on every install and push upgrade.',
71
+ remediation: 'Ask each vendor whether the package runs a post-install script and what it does, and review push-upgrade notices before they apply.',
72
+ affectedItems: namespaces.map((ns) => ({ label: `Namespace: ${ns}`, url: packagesUrl })),
73
+ });
74
+ }
75
+ if (handlers.length === 0 && hiddenNamespaces.size === 0) {
76
+ findings.push({
77
+ id: 'package-post-install-ok',
78
+ category: this.category,
79
+ riskLevel: 'LOW',
80
+ passed: true,
81
+ title: 'No post-install scripts found in installed packages',
82
+ detail: `${installedPackages.length} package(s) installed; none of their readable Apex implements InstallHandler.`,
83
+ remediation: 'Review post-install scripts and permissions whenever new packages are installed.',
84
+ });
85
+ }
86
+ return { findings };
87
+ }
88
+ }
89
+ //# sourceMappingURL=PackagePostInstallSupplyChainCheck.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 PlatformEventSubscriberContextCheck implements SecurityCheck {
4
+ readonly id = "platform-event-subscriber-context";
5
+ readonly name = "Platform Event Subscriber Context & Privilege Escalation";
6
+ readonly category = "Code Security";
7
+ readonly description = "Detects Platform Event subscribers executing in system context or as Admin while low-trust or guest users hold Publish permissions.";
8
+ run(ctx: AuditContext): Promise<CheckResult>;
9
+ }
10
+ //# sourceMappingURL=PlatformEventSubscriberContextCheck.d.ts.map
@@ -0,0 +1,84 @@
1
+ export class PlatformEventSubscriberContextCheck {
2
+ id = 'platform-event-subscriber-context';
3
+ name = 'Platform Event Subscriber Context & Privilege Escalation';
4
+ category = 'Code Security';
5
+ description = 'Detects Platform Event subscribers executing in system context or as Admin while low-trust or guest users hold Publish permissions.';
6
+ async run(ctx) {
7
+ const findings = [];
8
+ const baseUrl = ctx.orgInfo.instanceUrl;
9
+ // ApexTrigger exists in every org, so a failure here is never "feature absent". It propagates
10
+ // and CheckEngine reports the check as inconclusive.
11
+ const triggers = await ctx.tooling.query("SELECT Id, Name, TableEnumOrId, Status FROM ApexTrigger WHERE Status = 'Active'");
12
+ // TableEnumOrId holds a standard object's name, but a custom object's (and so every custom
13
+ // platform event's) 01I Id. Resolve Ids to API names before testing for the __e suffix.
14
+ const ids = [...new Set(triggers.map((t) => t.TableEnumOrId).filter((v) => !v.includes('_') && v.startsWith('01I')))];
15
+ const nameById = new Map();
16
+ if (ids.length > 0) {
17
+ const defs = await ctx.tooling.query(`SELECT DurableId, QualifiedApiName FROM EntityDefinition WHERE DurableId IN (${ids.map((i) => `'${i.slice(0, 15)}'`).join(', ')})`);
18
+ for (const d of defs)
19
+ nameById.set(d.DurableId.slice(0, 15), d.QualifiedApiName);
20
+ }
21
+ const objectName = (t) => nameById.get(t.TableEnumOrId.slice(0, 15)) ?? t.TableEnumOrId;
22
+ const eventTriggers = triggers.filter((t) => objectName(t).endsWith('__e'));
23
+ if (eventTriggers.length === 0) {
24
+ findings.push({
25
+ id: 'platform-event-subscriber-context-ok',
26
+ category: this.category,
27
+ riskLevel: 'LOW',
28
+ passed: true,
29
+ title: 'No active triggers on custom Platform Events identified',
30
+ detail: 'Zero active Apex triggers subscribe to custom Platform Event objects (__e).',
31
+ remediation: 'When subscribing to Platform Events, ensure publish permissions are strictly scoped to internal authorized actors.',
32
+ });
33
+ return { findings };
34
+ }
35
+ // Low-trust profiles (guest, portal, Experience Cloud) holding Create on a subscribed event.
36
+ // ObjectPermissions.ParentId is a PermissionSet Id, so each profile is reached through the
37
+ // permission set it owns.
38
+ const eventObjectNames = new Set(eventTriggers.map(objectName));
39
+ const lowTrustProfilesWithCreate = [];
40
+ const profiles = await ctx.soql.queryAll("SELECT Id, Name, UserType FROM Profile WHERE UserType IN ('Guest', 'CspLitePortal', 'PowerPartner', 'CustomerSuccess', 'PowerCustomerSuccess')");
41
+ if (profiles.length > 0) {
42
+ const profileNameById = new Map(profiles.map((p) => [p.Id, p.Name]));
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
+ 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'");
46
+ for (const op of objectPerms) {
47
+ const profileId = profileByPermSet.get(op.ParentId);
48
+ if (profileId && eventObjectNames.has(op.SobjectType)) {
49
+ lowTrustProfilesWithCreate.push(`${op.SobjectType} (${profileNameById.get(profileId) ?? profileId})`);
50
+ }
51
+ }
52
+ }
53
+ // If low-trust profiles have Create permission on any custom platform event subscribed to by Apex:
54
+ // This is an unauthenticated or portal-to-system privilege escalation bridge!
55
+ if (lowTrustProfilesWithCreate.length > 0) {
56
+ findings.push({
57
+ id: 'platform-event-subscriber-escalation',
58
+ category: this.category,
59
+ riskLevel: 'CRITICAL',
60
+ title: `${lowTrustProfilesWithCreate.length} Platform Event(s) publishable by low-trust users trigger system-mode subscribers`,
61
+ detail: 'Guest or Experience Cloud profiles hold Create (publish) permissions on custom Platform Events that have active Apex subscribers. By default, Platform Event triggers execute under the Automated Process system identity (bypassing user permissions and sharing), creating an unauthenticated-to-system-context privilege escalation bridge.',
62
+ remediation: 'Revoke Create permissions on Platform Events from guest and portal profiles, or configure PlatformEventSubscriberConfig to run subscribers as a dedicated, least-privileged service account with explicit input validation.',
63
+ affectedItems: lowTrustProfilesWithCreate.map((item) => ({
64
+ label: item,
65
+ url: `${baseUrl}/lightning/setup/EventObjects/home`,
66
+ note: 'Event publishable by low-trust actor executes as Automated Process or Admin',
67
+ })),
68
+ });
69
+ }
70
+ else {
71
+ findings.push({
72
+ id: 'platform-event-subscriber-context-ok',
73
+ category: this.category,
74
+ riskLevel: 'LOW',
75
+ passed: true,
76
+ title: 'Platform Event subscriber triggers are protected from low-trust publish escalation',
77
+ detail: `${eventTriggers.length} active Platform Event trigger(s) inspected; no guest or portal profiles hold Publish permissions on subscribed events.`,
78
+ remediation: 'Ensure low-trust profiles never receive Create permissions on custom Platform Events that execute privileged backend logic.',
79
+ });
80
+ }
81
+ return { findings };
82
+ }
83
+ }
84
+ //# sourceMappingURL=PlatformEventSubscriberContextCheck.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 RestrictionRulesIntegrityCheck implements SecurityCheck {
4
+ readonly id = "restriction-rules-integrity";
5
+ readonly name = "Restriction Rules Integrity & Conflict Detection";
6
+ readonly category = "Data Security";
7
+ readonly description = "Detects inactive or conflicting Restriction Rules on sensitive standard and custom objects.";
8
+ run(ctx: AuditContext): Promise<CheckResult>;
9
+ }
10
+ //# sourceMappingURL=RestrictionRulesIntegrityCheck.d.ts.map