@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
@@ -9,34 +9,133 @@
9
9
  },
10
10
  "checkWeights": {
11
11
  "_comment": "Override the weight for a specific check regardless of its riskLevel. To use: remove this _comment key.",
12
+ "agent-action-surface": 4,
13
+ "agent-channel-exposure": 4,
14
+ "agent-inventory": 4,
15
+ "agent-monitoring-coverage": 4,
16
+ "agent-outbound-actions": 4,
17
+ "agent-query-reach": 4,
18
+ "agent-user-privilege": 4,
19
+ "anonymous-apex-audit": 4,
20
+ "apex-crud-fls": 4,
21
+ "apex-logging": 4,
22
+ "apex-rest-endpoint": 4,
12
23
  "apex-sharing": 7,
24
+ "api-client-permission": 4,
13
25
  "api-limits": 4,
14
26
  "audit-trail": 4,
27
+ "auth-provider-registration-handler": 4,
28
+ "auth-providers": 4,
29
+ "certificate-expiry": 4,
30
+ "classic-sites": 4,
15
31
  "code-security": 4,
32
+ "connected-app-inactivity": 4,
33
+ "connected-app-scope": 4,
16
34
  "connected-apps": 7,
35
+ "content-links": 4,
36
+ "cors-allowlist": 4,
37
+ "csp-trusted-sites": 4,
38
+ "custom-labels-credential": 4,
17
39
  "custom-settings": 4,
40
+ "data-classification": 4,
41
+ "data-cloud-data-space-isolation": 4,
42
+ "data-export-access": 4,
43
+ "debug-log-access": 4,
44
+ "delegated-administration-groups": 4,
45
+ "delegated-authentication-exposure": 4,
46
+ "deployment-identity": 4,
47
+ "email-security": 4,
48
+ "encryption-coverage": 4,
49
+ "enhanced-domains": 4,
50
+ "escalation-perms": 4,
51
+ "event-monitoring": 4,
52
+ "experience-cloud-site": 4,
53
+ "experience-csp": 4,
54
+ "external-account-hierarchy-exposure": 4,
55
+ "external-credentials": 4,
56
+ "failed-login-detection": 4,
57
+ "field-history-tracking": 4,
18
58
  "field-level-security": 7,
59
+ "flow-http-callout-credential-bypass": 4,
19
60
  "flows-without-sharing": 7,
61
+ "genai-prompt-template-grounding": 4,
62
+ "guest-api-access": 4,
63
+ "guest-executable-apex": 4,
64
+ "guest-object-exposure": 4,
65
+ "guest-record-access-policy": 4,
66
+ "guest-site-options": 4,
67
+ "guest-traffic-anomaly": 4,
20
68
  "guest-user-access": 10,
69
+ "guest-user-visibility": 4,
21
70
  "hardcoded-credentials": 10,
22
71
  "health-check": 7,
72
+ "high-assurance-session": 4,
23
73
  "inactive-users": 4,
74
+ "inbound-email-handler-exposure": 4,
75
+ "installed-packages": 4,
76
+ "integration-least-privilege": 4,
77
+ "integration-users": 4,
78
+ "internal-user-mfa": 4,
24
79
  "ip-restrictions": 7,
80
+ "legacy-api-version": 4,
81
+ "lightning-message-channel": 4,
82
+ "login-access-policy": 4,
83
+ "login-anomaly": 4,
25
84
  "login-session": 4,
85
+ "mfa-enforcement": 4,
86
+ "mfa-method-strength": 4,
87
+ "mfa-registration": 4,
88
+ "my-domain-login-policy": 4,
26
89
  "named-credentials": 1,
90
+ "oauth-device-and-asset-token-flows": 4,
91
+ "oauth-token-inventory": 4,
92
+ "org-wide-email-spoofing": 4,
93
+ "outbound-messages": 4,
94
+ "package-post-install-supply-chain": 4,
27
95
  "password-session-policy": 7,
28
96
  "permissions": 4,
97
+ "platform-event-subscriber-context": 4,
98
+ "privileged-access": 4,
99
+ "public-content-exposure": 4,
29
100
  "public-group-sharing": 4,
101
+ "release-updates": 4,
30
102
  "remote-sites": 4,
103
+ "report-folder-access": 4,
104
+ "restriction-rules-integrity": 4,
105
+ "sandbox-data-masking": 4,
31
106
  "scheduled-apex": 1,
107
+ "separation-of-duties": 4,
108
+ "session-hardening": 4,
32
109
  "sharing-model": 7,
33
- "users-and-admins": 10
110
+ "shield-tenant-secret-lifecycle": 4,
111
+ "siem-integration": 4,
112
+ "soap-login-api-auth": 4,
113
+ "sso-enforcement": 4,
114
+ "standard-profiles": 4,
115
+ "threat-detection": 4,
116
+ "transaction-security-policy": 4,
117
+ "trusted-ip-ranges": 4,
118
+ "trusted-url-hygiene": 4,
119
+ "users-and-admins": 10,
120
+ "visualforce-xss": 4
34
121
  },
35
122
  "gradeThresholds": {
36
- "A": { "minScore": 85, "maxHigh": 0 },
37
- "B": { "minScore": 70, "maxHigh": 1 },
38
- "C": { "minScore": 55, "maxHigh": 3 },
39
- "D": { "minScore": 40, "maxCritical": 0 },
123
+ "A": {
124
+ "minScore": 85,
125
+ "maxHigh": 0
126
+ },
127
+ "B": {
128
+ "minScore": 70,
129
+ "maxHigh": 1
130
+ },
131
+ "C": {
132
+ "minScore": 55,
133
+ "maxHigh": 3
134
+ },
135
+ "D": {
136
+ "minScore": 40,
137
+ "maxCritical": 0
138
+ },
40
139
  "F": {}
41
140
  }
42
141
  }
@@ -0,0 +1,54 @@
1
+ <?xml version="1.0" encoding="UTF-8"?>
2
+ <!--
3
+ SF Audit (Read-Only) permission set — least-privilege access for `sf audit security`.
4
+ Grants only the read permissions needed for a complete audit. See ../../PERMISSIONS.md.
5
+
6
+ Deploy:
7
+ sf project deploy start -m PermissionSet:SF_Audit_ReadOnly -o <orgAlias>
8
+ then assign:
9
+ sf org assign permset -n SF_Audit_ReadOnly -o <orgAlias>
10
+
11
+ NOTE: user-permission API names occasionally vary by API version. If a deploy
12
+ fails on a specific <name>, confirm it against your org's API version
13
+ (Setup → Permission Sets → System Permissions) and adjust. The most likely to
14
+ differ are ViewHealthCheckScreen, ViewEventLogFiles, and ViewRoles.
15
+ -->
16
+ <PermissionSet xmlns="http://soap.sforce.com/2006/04/metadata">
17
+ <label>SF Audit (Read-Only)</label>
18
+ <description>Least-privilege, read-only access for the @cclabsnz/sf-audit security audit plugin. No DML, no metadata writes, no View All Data.</description>
19
+ <hasActivationRequired>false</hasActivationRequired>
20
+
21
+ <!-- Required -->
22
+ <userPermissions>
23
+ <enabled>true</enabled>
24
+ <name>ApiEnabled</name>
25
+ </userPermissions>
26
+ <userPermissions>
27
+ <enabled>true</enabled>
28
+ <name>ViewSetup</name>
29
+ </userPermissions>
30
+ <userPermissions>
31
+ <enabled>true</enabled>
32
+ <name>ViewAllUsers</name>
33
+ </userPermissions>
34
+ <userPermissions>
35
+ <enabled>true</enabled>
36
+ <name>ViewHealthCheckScreen</name>
37
+ </userPermissions>
38
+ <userPermissions>
39
+ <!-- Read-only: only gate that exposes ApexClass.Body via Tooling. Omit to skip the 9 code-security checks. -->
40
+ <enabled>true</enabled>
41
+ <name>AuthorApex</name>
42
+ </userPermissions>
43
+ <userPermissions>
44
+ <!-- Requires Event Monitoring / Shield licensed in the org. -->
45
+ <enabled>true</enabled>
46
+ <name>ViewEventLogFiles</name>
47
+ </userPermissions>
48
+
49
+ <!-- Recommended (completeness) -->
50
+ <userPermissions>
51
+ <enabled>true</enabled>
52
+ <name>ViewRoles</name>
53
+ </userPermissions>
54
+ </PermissionSet>
@@ -1,8 +1,14 @@
1
1
  import type { AppFinding } from './types.js';
2
2
  import type { SoqlClient } from '@cclabsnz/sf-core';
3
- export declare function analyzeApps(restApiCsv: string, soql: SoqlClient, opts: {
3
+ export interface AnalyzeAppsOptions {
4
4
  since: number;
5
5
  soakDays: number;
6
6
  soapApiCsv?: string;
7
- }): Promise<AppFinding[]>;
7
+ bulkApi2Csv?: string;
8
+ graphQlCsv?: string;
9
+ auraCsv?: string;
10
+ /** Why usage is known to be incomplete (e.g. some log files failed to download); suppresses revoke advice. */
11
+ incompleteUsage?: string;
12
+ }
13
+ export declare function analyzeApps(restApiCsv: string, soql: SoqlClient, opts: AnalyzeAppsOptions): Promise<AppFinding[]>;
8
14
  //# sourceMappingURL=analyzeApps.d.ts.map
@@ -3,7 +3,12 @@ import { resolveApps } from './appResolver.js';
3
3
  import { computeGranted } from './grantedAccess.js';
4
4
  import { buildFinding } from './leastPrivilege.js';
5
5
  export async function analyzeApps(restApiCsv, soql, opts) {
6
- const usage = collectUsage(restApiCsv, opts.soapApiCsv);
6
+ const usage = collectUsage(restApiCsv, {
7
+ soapApiCsv: opts.soapApiCsv,
8
+ bulkApi2Csv: opts.bulkApi2Csv,
9
+ graphQlCsv: opts.graphQlCsv,
10
+ auraCsv: opts.auraCsv,
11
+ });
7
12
  const appIds = usage.usage.map((u) => u.appId);
8
13
  const allUsers = [...new Set(usage.usage.flatMap((u) => u.userIds))];
9
14
  const resolved = await resolveApps(appIds, soql, allUsers);
@@ -12,7 +17,7 @@ export async function analyzeApps(restApiCsv, soql, opts) {
12
17
  for (const u of usage.usage) {
13
18
  const app = resolvedById.get(u.appId);
14
19
  const granted = await computeGranted(u.appId, u.userIds, soql, null);
15
- findings.push(buildFinding(app, u, granted, { since: opts.since, attributionRatePct: usage.attributionRatePct }, opts.soakDays));
20
+ findings.push(buildFinding(app, u, granted, { since: opts.since, attributionRatePct: usage.attributionRatePct }, opts.soakDays, opts.incompleteUsage));
16
21
  }
17
22
  return findings;
18
23
  }
@@ -0,0 +1,39 @@
1
+ import type { RestClient, SoqlClient } from '@cclabsnz/sf-core';
2
+ export declare const API_LOG_TYPES: readonly ['RestApi', 'BulkApi2', 'GraphQlQueryExecution', 'AuraRequest'];
3
+ export type ApiLogType = (typeof API_LOG_TYPES)[number];
4
+ export interface ApiLogs {
5
+ csv: Record<ApiLogType, string>;
6
+ /** Log files the query listed. */
7
+ listed: number;
8
+ /** Log files that could not be downloaded or read; their usage is missing from `csv`. */
9
+ failed: {
10
+ id: string;
11
+ eventType: string;
12
+ error: string;
13
+ }[];
14
+ }
15
+ /** Thrown when the EventLogFile listing itself fails: there is no usage to analyze at all. */
16
+ export declare class ApiLogListingError extends Error {
17
+ readonly permission: boolean;
18
+ constructor(message: string, permission: boolean);
19
+ }
20
+ /**
21
+ * Lists and downloads the API EventLogFiles for the last `since` days. Read-only: one SOQL query and
22
+ * one REST GET per file. A failed listing throws (an empty result would read as "no usage"); a failed
23
+ * download is recorded in `failed` so the caller can flag the analysis as incomplete.
24
+ */
25
+ export declare function downloadApiLogs(deps: {
26
+ soql: SoqlClient;
27
+ rest: RestClient;
28
+ }, since: number): Promise<ApiLogs>;
29
+ export interface LogCoverage {
30
+ /** Set when there is no usable data at all: the command must stop rather than report. */
31
+ fatal?: string;
32
+ /** Set when some files failed: the analysis runs but is flagged incomplete. */
33
+ incomplete?: string;
34
+ /** Informational: the window simply had no API logs. */
35
+ empty?: string;
36
+ }
37
+ /** Decides whether downloaded logs are complete, partial, or unusable. Never treats a failure as "no usage". */
38
+ export declare function assessLogCoverage(logs: ApiLogs, since: number): LogCoverage;
39
+ //# sourceMappingURL=apiLogSource.d.ts.map
@@ -0,0 +1,75 @@
1
+ import { mkdtempSync, readFileSync, rmSync } from 'node:fs';
2
+ import { tmpdir } from 'node:os';
3
+ import { join } from 'node:path';
4
+ export const API_LOG_TYPES = ['RestApi', 'BulkApi2', 'GraphQlQueryExecution', 'AuraRequest'];
5
+ /** Thrown when the EventLogFile listing itself fails: there is no usage to analyze at all. */
6
+ export class ApiLogListingError extends Error {
7
+ permission;
8
+ constructor(message, permission) {
9
+ super(message);
10
+ this.permission = permission;
11
+ this.name = 'ApiLogListingError';
12
+ }
13
+ }
14
+ /**
15
+ * Lists and downloads the API EventLogFiles for the last `since` days. Read-only: one SOQL query and
16
+ * one REST GET per file. A failed listing throws (an empty result would read as "no usage"); a failed
17
+ * download is recorded in `failed` so the caller can flag the analysis as incomplete.
18
+ */
19
+ export async function downloadApiLogs(deps, since) {
20
+ const csv = { RestApi: '', BulkApi2: '', GraphQlQueryExecution: '', AuraRequest: '' };
21
+ let rows;
22
+ try {
23
+ rows = await deps.soql.queryAll(`SELECT Id, EventType FROM EventLogFile WHERE EventType IN (${API_LOG_TYPES.map((t) => `'${t}'`).join(', ')}) ` +
24
+ `AND LogDate = LAST_N_DAYS:${since} ORDER BY LogDate DESC`);
25
+ }
26
+ catch (e) {
27
+ const msg = e instanceof Error ? e.message : String(e);
28
+ const permission = /INSUFFICIENT_ACCESS|HTTP 403|INVALID_TYPE|not supported/i.test(msg);
29
+ throw new ApiLogListingError(permission
30
+ ? `Cannot list API event logs: EventLogFile is not readable (the running user needs View Event Log Files, and the org needs Event Monitoring). ${msg}`
31
+ : `Cannot list API event logs: ${msg}`, permission);
32
+ }
33
+ const failed = [];
34
+ if (rows.length === 0)
35
+ return { csv, listed: 0, failed };
36
+ // A private (0700) temp dir: raw logs hold org data and must not sit at a predictable shared path.
37
+ const dir = mkdtempSync(join(tmpdir(), 'sfaudit-apps-'));
38
+ try {
39
+ for (const r of rows) {
40
+ const tmp = join(dir, `${r.Id}.csv`);
41
+ try {
42
+ await deps.rest.getRawToFile(`/sobjects/EventLogFile/${r.Id}/LogFile`, tmp);
43
+ const content = readFileSync(tmp, 'utf-8');
44
+ if (API_LOG_TYPES.includes(r.EventType)) {
45
+ csv[r.EventType] += '\n' + content;
46
+ }
47
+ }
48
+ catch (e) {
49
+ failed.push({ id: r.Id, eventType: r.EventType, error: e instanceof Error ? e.message : String(e) });
50
+ }
51
+ finally {
52
+ rmSync(tmp, { force: true });
53
+ }
54
+ }
55
+ }
56
+ finally {
57
+ rmSync(dir, { recursive: true, force: true });
58
+ }
59
+ return { csv, listed: rows.length, failed };
60
+ }
61
+ /** Decides whether downloaded logs are complete, partial, or unusable. Never treats a failure as "no usage". */
62
+ export function assessLogCoverage(logs, since) {
63
+ if (logs.listed === 0)
64
+ return { empty: `No API EventLogFiles in the last ${since} day(s): there is no usage to compare against grants.` };
65
+ if (logs.failed.length === logs.listed) {
66
+ return {
67
+ fatal: `None of the ${logs.listed} API log file(s) could be downloaded (first error: ${logs.failed[0].error}). ` +
68
+ 'Refusing to report usage from no data.',
69
+ };
70
+ }
71
+ if (logs.failed.length > 0)
72
+ return { incomplete: `${logs.failed.length} of ${logs.listed} API log file(s) could not be downloaded` };
73
+ return {};
74
+ }
75
+ //# sourceMappingURL=apiLogSource.js.map
@@ -17,19 +17,42 @@ export async function resolveApps(appIds, soql, userIds) {
17
17
  const connApps = await soql
18
18
  .queryAll('SELECT Id, Name FROM ConnectedApplication')
19
19
  .catch(() => []);
20
+ const ecaApps = await soql
21
+ .queryAll('SELECT Id, DeveloperName, MasterLabel FROM ExternalClientApplication')
22
+ .catch(() => []);
20
23
  const menuByKey = new Map(menu.map((m) => [m.ApplicationId.slice(0, 15), m.Label ?? m.Name ?? '']));
21
24
  const connByKey = new Map(connApps.map((c) => [c.Id.slice(0, 15), c.Name]));
22
- // Only pay for LoginHistory if some ids are still unresolved after 1-3.
23
- const stillUnknown = appIds.filter((id) => !menuByKey.has(id.slice(0, 15)) && !connByKey.has(id.slice(0, 15)) && !lookupStandardApp(id));
25
+ const ecaByKey = new Map();
26
+ for (const e of ecaApps) {
27
+ const name = e.MasterLabel ?? e.DeveloperName ?? '';
28
+ ecaByKey.set(e.Id.slice(0, 15), name);
29
+ ecaByKey.set(e.Id, name);
30
+ if (e.DeveloperName)
31
+ ecaByKey.set(e.DeveloperName, name);
32
+ }
33
+ // Only pay for LoginHistory if some ids are still unresolved after 1-4.
34
+ const stillUnknown = appIds.filter((id) => !menuByKey.has(id.slice(0, 15)) &&
35
+ !connByKey.has(id.slice(0, 15)) &&
36
+ !ecaByKey.has(id.slice(0, 15)) &&
37
+ !ecaByKey.has(id) &&
38
+ !lookupStandardApp(id));
24
39
  let logins = [];
25
40
  if (stillUnknown.length > 0 && userIds.length > 0) {
26
41
  logins = await soql
27
- .queryAll(`SELECT Application, UserId FROM LoginHistory WHERE UserId IN (${userIds
42
+ .queryAll(`SELECT Application, ClientVersion, UserId FROM LoginHistory WHERE UserId IN (${userIds
28
43
  .map((u) => `'${u}'`)
29
44
  .join(',')}) AND LoginTime = LAST_N_DAYS:7`)
30
45
  .catch(() => []);
31
46
  }
32
- const loginNames = [...new Set(logins.map((l) => l.Application).filter((a) => a && a !== 'Browser' && a !== 'N/A'))];
47
+ // ClientVersion is only a fallback for rows with no usable Application: it is usually a version
48
+ // string ("58.0"), and counting it alongside Application would turn one login into two names and
49
+ // defeat the single-name inference below.
50
+ const meaningful = (a) => !!a && a !== 'Browser' && a !== 'N/A';
51
+ const loginNames = [
52
+ ...new Set(logins
53
+ .map((l) => meaningful(l.Application) ? l.Application : meaningful(l.ClientVersion) && !/^[\d.]+$/.test(l.ClientVersion) ? l.ClientVersion : null)
54
+ .filter(meaningful)),
55
+ ];
33
56
  return appIds.map((appId) => {
34
57
  const key = appId.slice(0, 15);
35
58
  const menuName = menuByKey.get(key);
@@ -38,6 +61,9 @@ export async function resolveApps(appIds, soql, userIds) {
38
61
  const connName = connByKey.get(key);
39
62
  if (connName)
40
63
  return { appId, name: connName, category: categorise(connName, null), confidence: 'resolved' };
64
+ const ecaName = ecaByKey.get(key) ?? ecaByKey.get(appId);
65
+ if (ecaName)
66
+ return { appId, name: ecaName, category: categorise(ecaName, null), confidence: 'resolved' };
41
67
  const std = lookupStandardApp(appId);
42
68
  if (std)
43
69
  return { appId, name: std.name, category: std.category, vendor: std.vendor, purpose: std.purpose, confidence: 'resolved' };
@@ -7,12 +7,25 @@ export async function computeGranted(appId, runAsUsers, soql, scope) {
7
7
  const psa = await soql
8
8
  .queryAll(`SELECT AssigneeId, PermissionSetId FROM PermissionSetAssignment WHERE AssigneeId IN (${inList(runAsUsers)})`)
9
9
  .catch(() => []);
10
- const psIds = [...new Set(psa.map((p) => p.PermissionSetId))];
11
- if (psIds.length === 0)
10
+ const psIds = new Set(psa.map((p) => p.PermissionSetId));
11
+ const users = await soql
12
+ .queryAll(`SELECT Id, ProfileId FROM User WHERE Id IN (${inList(runAsUsers)})`)
13
+ .catch(() => []);
14
+ const profileIds = [...new Set(users.map((u) => u.ProfileId).filter(Boolean))];
15
+ if (profileIds.length > 0) {
16
+ const profilePs = await soql
17
+ .queryAll(`SELECT Id, ProfileId FROM PermissionSet WHERE IsOwnedByProfile = true AND ProfileId IN (${inList(profileIds)})`)
18
+ .catch(() => []);
19
+ for (const p of profilePs) {
20
+ psIds.add(p.Id);
21
+ }
22
+ }
23
+ const allPsIds = [...psIds];
24
+ if (allPsIds.length === 0)
12
25
  return { appId, scope, objects: [], runAsUsers, multiUserInteractive };
13
26
  const perms = await soql
14
27
  .queryAll(`SELECT ParentId, SobjectType, PermissionsRead, PermissionsCreate, PermissionsEdit, PermissionsDelete
15
- FROM ObjectPermissions WHERE ParentId IN (${inList(psIds)}) AND PermissionsRead = true`)
28
+ FROM ObjectPermissions WHERE ParentId IN (${inList(allPsIds)}) AND PermissionsRead = true`)
16
29
  .catch(() => []);
17
30
  const byObject = new Map();
18
31
  for (const p of perms) {
@@ -2,5 +2,7 @@ import type { AppFinding, AppUsage, GrantedAccess, ResolvedApp } from './types.j
2
2
  export declare function buildFinding(app: ResolvedApp, used: AppUsage, granted: GrantedAccess, window: {
3
3
  since: number;
4
4
  attributionRatePct: number;
5
- }, soakDays: number): AppFinding;
5
+ }, soakDays: number,
6
+ /** Set when some API logs in the window could not be read: usage is then known to be incomplete. */
7
+ incompleteUsage?: string): AppFinding;
6
8
  //# sourceMappingURL=leastPrivilege.d.ts.map
@@ -1,4 +1,6 @@
1
- export function buildFinding(app, used, granted, window, soakDays) {
1
+ export function buildFinding(app, used, granted, window, soakDays,
2
+ /** Set when some API logs in the window could not be read: usage is then known to be incomplete. */
3
+ incompleteUsage) {
2
4
  const usedObjects = new Set(used.objects.map((o) => o.object));
3
5
  const usedVerbs = new Map(used.objects.map((o) => [o.object, new Set(o.verbs)]));
4
6
  const belowSoak = window.since < soakDays;
@@ -6,11 +8,13 @@ export function buildFinding(app, used, granted, window, soakDays) {
6
8
  notes.push(`Observed over ${window.since} day(s); RestApi attribution ${window.attributionRatePct}% — "used" is a lower bound.`);
7
9
  if (belowSoak)
8
10
  notes.push(`Window below the ${soakDays}-day soak threshold: revoke recommendations suppressed.`);
11
+ if (incompleteUsage)
12
+ notes.push(`Usage data incomplete (${incompleteUsage}): revoke recommendations suppressed.`);
9
13
  if (used.soapOnly)
10
14
  notes.push('SOAP usage present but not app-attributable; not treated as dormant.');
11
15
  if (granted.multiUserInteractive)
12
16
  notes.push('Interactive app with many run-as users; object delta not asserted.');
13
- const assertDelta = !belowSoak && !granted.multiUserInteractive;
17
+ const assertDelta = !belowSoak && !granted.multiUserInteractive && !incompleteUsage;
14
18
  const unusedObjects = assertDelta
15
19
  ? granted.objects.map((o) => o.object).filter((o) => !usedObjects.has(o)).sort()
16
20
  : [];
@@ -40,7 +44,7 @@ export function buildFinding(app, used, granted, window, soakDays) {
40
44
  used,
41
45
  granted,
42
46
  overGrant: { unusedObjects, unusedVerbs, scopeDowngrade, dormant },
43
- recommendation: { permissionSet: { objectPermissions } },
47
+ recommendation: { asserted: assertDelta, permissionSet: { objectPermissions } },
44
48
  notes,
45
49
  };
46
50
  }
@@ -0,0 +1,22 @@
1
+ import type { AppFinding } from './types.js';
2
+ /**
3
+ * Turns an app name into a valid metadata API name stem: starts with a letter, only alphanumerics and
4
+ * single underscores, no leading or trailing underscore. Length is capped by the caller.
5
+ */
6
+ export declare function sanitizePermissionSetName(name: string): string;
7
+ /**
8
+ * One API name per finding, unique case-insensitively (Salesforce API names and macOS/Windows file
9
+ * names both ignore case), each at most 80 characters.
10
+ */
11
+ export declare function permissionSetNames(findings: AppFinding[]): string[];
12
+ export declare function generatePermissionSetXml(finding: AppFinding): string;
13
+ /**
14
+ * Writes one .permissionset-meta.xml per finding whose recommendation is asserted. Findings held back
15
+ * (soak window, many interactive users, incomplete logs) are skipped: their observed usage is too thin
16
+ * to be a least-privilege grant. Local files only; nothing is deployed.
17
+ */
18
+ export declare function emitPermissionSets(findings: AppFinding[], targetDir: string): {
19
+ written: string[];
20
+ skipped: string[];
21
+ };
22
+ //# sourceMappingURL=permissionSetGenerator.d.ts.map
@@ -0,0 +1,100 @@
1
+ import { join } from 'node:path';
2
+ import { secureFs } from '@cclabsnz/sf-core';
3
+ const API_NAME_MAX = 80;
4
+ const LABEL_MAX = 80;
5
+ const NAME_SUFFIX = '_LeastPrivilege';
6
+ const LABEL_SUFFIX = ' Least Privilege';
7
+ // XML 1.0 forbids most C0 control characters even when escaped; drop them rather than emit invalid XML.
8
+ // eslint-disable-next-line no-control-regex
9
+ const XML_INVALID = /[\u0000-\u0008\u000B\u000C\u000E-\u001F￾￿]/g;
10
+ function xmlEscape(s) {
11
+ return s
12
+ .replace(XML_INVALID, '')
13
+ .replace(/&/g, '&amp;')
14
+ .replace(/</g, '&lt;')
15
+ .replace(/>/g, '&gt;')
16
+ .replace(/"/g, '&quot;')
17
+ .replace(/'/g, '&apos;');
18
+ }
19
+ /**
20
+ * Turns an app name into a valid metadata API name stem: starts with a letter, only alphanumerics and
21
+ * single underscores, no leading or trailing underscore. Length is capped by the caller.
22
+ */
23
+ export function sanitizePermissionSetName(name) {
24
+ let clean = name.replace(/[^a-zA-Z0-9]+/g, '_').replace(/^_+|_+$/g, '');
25
+ if (!clean)
26
+ return 'App';
27
+ if (!/^[a-zA-Z]/.test(clean))
28
+ clean = `App_${clean}`;
29
+ return clean;
30
+ }
31
+ function fitName(stem, tail) {
32
+ const room = API_NAME_MAX - tail.length;
33
+ return `${stem.slice(0, room).replace(/_+$/, '')}${tail}`;
34
+ }
35
+ /**
36
+ * One API name per finding, unique case-insensitively (Salesforce API names and macOS/Windows file
37
+ * names both ignore case), each at most 80 characters.
38
+ */
39
+ export function permissionSetNames(findings) {
40
+ const taken = new Set();
41
+ return findings.map((f) => {
42
+ const stem = sanitizePermissionSetName(f.app.name || f.app.appId);
43
+ let candidate = fitName(stem, NAME_SUFFIX);
44
+ for (let n = 2; taken.has(candidate.toLowerCase()); n++)
45
+ candidate = fitName(stem, `${NAME_SUFFIX}_${n}`);
46
+ taken.add(candidate.toLowerCase());
47
+ return candidate;
48
+ });
49
+ }
50
+ export function generatePermissionSetXml(finding) {
51
+ const appName = (finding.app.name || finding.app.appId).replace(XML_INVALID, '');
52
+ const label = `${appName.slice(0, LABEL_MAX - LABEL_SUFFIX.length).trimEnd()}${LABEL_SUFFIX}`;
53
+ const perms = (finding.recommendation?.permissionSet?.objectPermissions ?? [])
54
+ .slice()
55
+ .sort((a, b) => a.object.localeCompare(b.object));
56
+ // Salesforce rejects edit/create without read and delete without edit, so imply the prerequisites.
57
+ const objectXml = perms
58
+ .map((p) => {
59
+ const edit = p.edit || p.delete;
60
+ const read = p.read || p.create || edit;
61
+ return ` <objectPermissions>
62
+ <allowCreate>${p.create}</allowCreate>
63
+ <allowDelete>${p.delete}</allowDelete>
64
+ <allowEdit>${edit}</allowEdit>
65
+ <allowRead>${read}</allowRead>
66
+ <modifyAllRecords>false</modifyAllRecords>
67
+ <object>${xmlEscape(p.object)}</object>
68
+ <viewAllRecords>false</viewAllRecords>
69
+ </objectPermissions>`;
70
+ })
71
+ .join('\n');
72
+ return `<?xml version="1.0" encoding="UTF-8"?>
73
+ <PermissionSet xmlns="http://soap.sforce.com/2006/04/metadata">
74
+ <description>${xmlEscape(`Generated by sf audit apps from usage observed over ${finding.window.since} day(s). Review before deploying.`)}</description>
75
+ <hasActivationRequired>false</hasActivationRequired>
76
+ <label>${xmlEscape(label)}</label>
77
+ ${objectXml ? objectXml + '\n' : ''}</PermissionSet>
78
+ `;
79
+ }
80
+ /**
81
+ * Writes one .permissionset-meta.xml per finding whose recommendation is asserted. Findings held back
82
+ * (soak window, many interactive users, incomplete logs) are skipped: their observed usage is too thin
83
+ * to be a least-privilege grant. Local files only; nothing is deployed.
84
+ */
85
+ export function emitPermissionSets(findings, targetDir) {
86
+ const emit = findings.filter((f) => f.recommendation.asserted);
87
+ const skipped = findings.filter((f) => !f.recommendation.asserted).map((f) => f.app.name || f.app.appId);
88
+ const written = [];
89
+ if (emit.length === 0)
90
+ return { written, skipped };
91
+ secureFs.mkdirSync(targetDir, { recursive: true });
92
+ const names = permissionSetNames(emit);
93
+ emit.forEach((f, i) => {
94
+ const filePath = join(targetDir, `${names[i]}.permissionset-meta.xml`);
95
+ secureFs.writeFileSync(filePath, generatePermissionSetXml(f));
96
+ written.push(filePath);
97
+ });
98
+ return { written, skipped };
99
+ }
100
+ //# sourceMappingURL=permissionSetGenerator.js.map
@@ -49,6 +49,12 @@ export interface AppFinding {
49
49
  dormant: boolean;
50
50
  };
51
51
  recommendation: {
52
+ /**
53
+ * False when the delta was not asserted (window below the soak threshold, many interactive run-as
54
+ * users, or incomplete log data): the permission set below then reflects partial observation only
55
+ * and must not be emitted as a deployable least-privilege grant.
56
+ */
57
+ asserted: boolean;
52
58
  permissionSet: {
53
59
  objectPermissions: {
54
60
  object: string;
@@ -5,5 +5,11 @@ export interface UsageResult {
5
5
  attributedRows: number;
6
6
  attributionRatePct: number;
7
7
  }
8
- export declare function collectUsage(restApiCsv: string, soapApiCsv?: string): UsageResult;
8
+ export interface CollectUsageOptions {
9
+ soapApiCsv?: string;
10
+ bulkApi2Csv?: string;
11
+ graphQlCsv?: string;
12
+ auraCsv?: string;
13
+ }
14
+ export declare function collectUsage(restApiCsv: string, optsOrSoap?: CollectUsageOptions | string): UsageResult;
9
15
  //# sourceMappingURL=usageCollector.d.ts.map