@cclabsnz/sf-audit 0.1.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 (108) hide show
  1. package/README.md +145 -0
  2. package/config/queries/soql.json +24 -0
  3. package/config/queries/tooling.json +28 -0
  4. package/config/scoring.json +9 -0
  5. package/lib/api/ApiError.d.ts +6 -0
  6. package/lib/api/ApiError.js +6 -0
  7. package/lib/api/RestClient.d.ts +4 -0
  8. package/lib/api/RestClient.js +2 -0
  9. package/lib/api/RestClientImpl.d.ts +8 -0
  10. package/lib/api/RestClientImpl.js +12 -0
  11. package/lib/api/SoqlClient.d.ts +10 -0
  12. package/lib/api/SoqlClient.js +2 -0
  13. package/lib/api/SoqlClientImpl.d.ts +9 -0
  14. package/lib/api/SoqlClientImpl.js +19 -0
  15. package/lib/api/ToolingClient.d.ts +5 -0
  16. package/lib/api/ToolingClient.js +2 -0
  17. package/lib/api/ToolingClientImpl.d.ts +10 -0
  18. package/lib/api/ToolingClientImpl.js +26 -0
  19. package/lib/api/index.d.ts +9 -0
  20. package/lib/api/index.js +5 -0
  21. package/lib/checks/CheckEngine.d.ts +11 -0
  22. package/lib/checks/CheckEngine.js +56 -0
  23. package/lib/checks/SecurityCheck.d.ts +18 -0
  24. package/lib/checks/SecurityCheck.js +2 -0
  25. package/lib/checks/impl/ApexSharingCheck.d.ts +11 -0
  26. package/lib/checks/impl/ApexSharingCheck.js +108 -0
  27. package/lib/checks/impl/ApiLimitsCheck.d.ts +10 -0
  28. package/lib/checks/impl/ApiLimitsCheck.js +65 -0
  29. package/lib/checks/impl/AuditTrailCheck.d.ts +10 -0
  30. package/lib/checks/impl/AuditTrailCheck.js +69 -0
  31. package/lib/checks/impl/CodeSecurityCheck.d.ts +10 -0
  32. package/lib/checks/impl/CodeSecurityCheck.js +53 -0
  33. package/lib/checks/impl/ConnectedAppsCheck.d.ts +10 -0
  34. package/lib/checks/impl/ConnectedAppsCheck.js +48 -0
  35. package/lib/checks/impl/CustomSettingsCheck.d.ts +10 -0
  36. package/lib/checks/impl/CustomSettingsCheck.js +59 -0
  37. package/lib/checks/impl/FieldLevelSecurityCheck.d.ts +10 -0
  38. package/lib/checks/impl/FieldLevelSecurityCheck.js +149 -0
  39. package/lib/checks/impl/FlowsWithoutSharingCheck.d.ts +10 -0
  40. package/lib/checks/impl/FlowsWithoutSharingCheck.js +60 -0
  41. package/lib/checks/impl/GuestUserAccessCheck.d.ts +11 -0
  42. package/lib/checks/impl/GuestUserAccessCheck.js +158 -0
  43. package/lib/checks/impl/HardcodedCredentialsCheck.d.ts +12 -0
  44. package/lib/checks/impl/HardcodedCredentialsCheck.js +146 -0
  45. package/lib/checks/impl/HealthCheckCheck.d.ts +11 -0
  46. package/lib/checks/impl/HealthCheckCheck.js +70 -0
  47. package/lib/checks/impl/InactiveUsersCheck.d.ts +10 -0
  48. package/lib/checks/impl/InactiveUsersCheck.js +47 -0
  49. package/lib/checks/impl/IpRestrictionsCheck.d.ts +10 -0
  50. package/lib/checks/impl/IpRestrictionsCheck.js +94 -0
  51. package/lib/checks/impl/LoginSessionCheck.d.ts +10 -0
  52. package/lib/checks/impl/LoginSessionCheck.js +54 -0
  53. package/lib/checks/impl/NamedCredentialsCheck.d.ts +11 -0
  54. package/lib/checks/impl/NamedCredentialsCheck.js +100 -0
  55. package/lib/checks/impl/PasswordSessionPolicyCheck.d.ts +12 -0
  56. package/lib/checks/impl/PasswordSessionPolicyCheck.js +100 -0
  57. package/lib/checks/impl/PermissionsCheck.d.ts +10 -0
  58. package/lib/checks/impl/PermissionsCheck.js +91 -0
  59. package/lib/checks/impl/PublicGroupSharingCheck.d.ts +11 -0
  60. package/lib/checks/impl/PublicGroupSharingCheck.js +68 -0
  61. package/lib/checks/impl/RemoteSitesCheck.d.ts +11 -0
  62. package/lib/checks/impl/RemoteSitesCheck.js +69 -0
  63. package/lib/checks/impl/ScheduledApexCheck.d.ts +10 -0
  64. package/lib/checks/impl/ScheduledApexCheck.js +72 -0
  65. package/lib/checks/impl/SharingModelCheck.d.ts +10 -0
  66. package/lib/checks/impl/SharingModelCheck.js +61 -0
  67. package/lib/checks/impl/UsersAndAdminsCheck.d.ts +10 -0
  68. package/lib/checks/impl/UsersAndAdminsCheck.js +85 -0
  69. package/lib/checks/registry.d.ts +3 -0
  70. package/lib/checks/registry.js +49 -0
  71. package/lib/commands/audit/list.d.ts +15 -0
  72. package/lib/commands/audit/list.js +35 -0
  73. package/lib/commands/audit/security.d.ts +18 -0
  74. package/lib/commands/audit/security.js +117 -0
  75. package/lib/context/AuditCache.d.ts +18 -0
  76. package/lib/context/AuditCache.js +2 -0
  77. package/lib/context/AuditContext.d.ts +15 -0
  78. package/lib/context/AuditContext.js +2 -0
  79. package/lib/context/OrgInfo.d.ts +9 -0
  80. package/lib/context/OrgInfo.js +2 -0
  81. package/lib/context/OrgMetrics.d.ts +20 -0
  82. package/lib/context/OrgMetrics.js +20 -0
  83. package/lib/findings/AuditResult.d.ts +15 -0
  84. package/lib/findings/AuditResult.js +2 -0
  85. package/lib/findings/Finding.d.ts +16 -0
  86. package/lib/findings/Finding.js +2 -0
  87. package/lib/findings/RiskLevel.d.ts +3 -0
  88. package/lib/findings/RiskLevel.js +2 -0
  89. package/lib/findings/scoring.d.ts +6 -0
  90. package/lib/findings/scoring.js +61 -0
  91. package/lib/index.d.ts +2 -0
  92. package/lib/index.js +2 -0
  93. package/lib/lib/wire.d.ts +15 -0
  94. package/lib/lib/wire.js +36 -0
  95. package/lib/queries/QueryDefinition.d.ts +48 -0
  96. package/lib/queries/QueryDefinition.js +11 -0
  97. package/lib/queries/QueryRegistry.d.ts +13 -0
  98. package/lib/queries/QueryRegistry.js +93 -0
  99. package/lib/renderers/AuditRenderer.d.ts +7 -0
  100. package/lib/renderers/AuditRenderer.js +2 -0
  101. package/lib/renderers/HtmlRenderer.d.ts +8 -0
  102. package/lib/renderers/HtmlRenderer.js +270 -0
  103. package/lib/renderers/JsonRenderer.d.ts +8 -0
  104. package/lib/renderers/JsonRenderer.js +8 -0
  105. package/lib/renderers/MarkdownRenderer.d.ts +8 -0
  106. package/lib/renderers/MarkdownRenderer.js +54 -0
  107. package/messages/audit.security.md +22 -0
  108. package/package.json +54 -0
@@ -0,0 +1,158 @@
1
+ const STANDARD_OBJECTS = ['Account', 'Contact', 'Case', 'Lead', 'Opportunity'];
2
+ const HEALTH_CLOUD_OBJECTS = ['CarePlan__c', 'CareTeamMember__c', 'EhrPatient__c'];
3
+ const SHARE_TABLES = ['AccountShare', 'CaseShare', 'ContactShare', 'OpportunityShare'];
4
+ export class GuestUserAccessCheck {
5
+ id = 'guest-user-access';
6
+ name = 'Guest User Access';
7
+ category = 'Access Control';
8
+ description = 'Audits object permissions and sharing rules granted to unauthenticated guest users';
9
+ dependsOnCache = ['healthCloudInstalled'];
10
+ async run(ctx) {
11
+ const findings = [];
12
+ const baseUrl = ctx.orgInfo.instanceUrl;
13
+ const guestUsers = await ctx.soql.queryAll("SELECT Id, ProfileId, Username FROM User WHERE UserType = 'Guest' AND IsActive = true");
14
+ if (guestUsers.length === 0) {
15
+ findings.push({
16
+ id: 'guest-user-none',
17
+ category: this.category,
18
+ riskLevel: 'LOW',
19
+ title: 'No active guest users found',
20
+ detail: 'There are no active guest users in this org, so guest user security misconfiguration is not a concern.',
21
+ remediation: 'If an Experience Cloud site is added in the future, ensure guest user permissions are properly restricted.',
22
+ });
23
+ return { findings };
24
+ }
25
+ // Determine which objects to check
26
+ const objectsToCheck = [...STANDARD_OBJECTS];
27
+ if (ctx.cache.healthCloudInstalled === true) {
28
+ objectsToCheck.push(...HEALTH_CLOUD_OBJECTS);
29
+ }
30
+ const writeViolations = [];
31
+ // Collect unique profile IDs to avoid re-querying
32
+ const profileIds = [...new Set(guestUsers.map((u) => u.ProfileId))];
33
+ for (const profileId of profileIds) {
34
+ // Find which user(s) belong to this profile
35
+ const profileUsers = guestUsers.filter((u) => u.ProfileId === profileId);
36
+ // Query standard objects for this profile
37
+ const standardObjectList = STANDARD_OBJECTS.map((o) => `'${o}'`).join(',');
38
+ try {
39
+ const perms = await ctx.soql.queryAll(`SELECT SobjectType, PermissionsCreate, PermissionsEdit, PermissionsRead FROM ObjectPermissions WHERE ParentId = '${profileId}' AND SobjectType IN (${standardObjectList})`);
40
+ for (const perm of perms) {
41
+ if (perm.PermissionsCreate || perm.PermissionsEdit) {
42
+ for (const u of profileUsers) {
43
+ writeViolations.push({
44
+ userId: u.Id,
45
+ username: u.Username,
46
+ sobjectType: perm.SobjectType,
47
+ canCreate: perm.PermissionsCreate,
48
+ canEdit: perm.PermissionsEdit,
49
+ });
50
+ }
51
+ }
52
+ }
53
+ }
54
+ catch {
55
+ // Skip on error
56
+ }
57
+ // Check Health Cloud objects if applicable
58
+ if (ctx.cache.healthCloudInstalled === true) {
59
+ for (const obj of HEALTH_CLOUD_OBJECTS) {
60
+ try {
61
+ const perms = await ctx.soql.queryAll(`SELECT SobjectType, PermissionsCreate, PermissionsEdit, PermissionsRead FROM ObjectPermissions WHERE ParentId = '${profileId}' AND SobjectType = '${obj}'`);
62
+ for (const perm of perms) {
63
+ if (perm.PermissionsCreate || perm.PermissionsEdit) {
64
+ for (const u of profileUsers) {
65
+ writeViolations.push({
66
+ userId: u.Id,
67
+ username: u.Username,
68
+ sobjectType: perm.SobjectType,
69
+ canCreate: perm.PermissionsCreate,
70
+ canEdit: perm.PermissionsEdit,
71
+ });
72
+ }
73
+ }
74
+ }
75
+ }
76
+ catch {
77
+ // Object may not exist — skip silently
78
+ }
79
+ }
80
+ }
81
+ }
82
+ const sharingExposures = [];
83
+ for (const user of guestUsers) {
84
+ for (const shareTable of SHARE_TABLES) {
85
+ try {
86
+ const result = await ctx.soql.query(`SELECT COUNT() FROM ${shareTable} WHERE UserOrGroupId = '${user.Id}' AND RowCause = 'SharingRule'`);
87
+ if (result.totalSize > 0) {
88
+ const existing = sharingExposures.find((e) => e.shareTable === shareTable);
89
+ if (existing) {
90
+ existing.count += result.totalSize;
91
+ }
92
+ else {
93
+ sharingExposures.push({ shareTable, count: result.totalSize });
94
+ }
95
+ }
96
+ }
97
+ catch {
98
+ // Object may not be accessible — skip silently
99
+ }
100
+ }
101
+ }
102
+ // Emit findings based on what was found
103
+ if (writeViolations.length > 0) {
104
+ findings.push({
105
+ id: 'guest-user-write-access',
106
+ category: this.category,
107
+ riskLevel: 'CRITICAL',
108
+ title: 'Guest user profile(s) have write access to Salesforce objects',
109
+ affectedItems: writeViolations.map((v) => {
110
+ const actions = [v.canCreate && 'Create', v.canEdit && 'Edit']
111
+ .filter(Boolean)
112
+ .join('/');
113
+ return {
114
+ label: `${v.username} — ${v.sobjectType}`,
115
+ url: `${baseUrl}/${v.userId}`,
116
+ note: `Can ${actions} — remove immediately`,
117
+ };
118
+ }),
119
+ detail: 'Unauthenticated users (guests) with write access to standard objects represents a critical misconfiguration.',
120
+ remediation: 'Remove all Create and Edit permissions from guest user profiles immediately. Guest users should have minimal or no object access.',
121
+ });
122
+ }
123
+ if (sharingExposures.length > 0) {
124
+ const count = sharingExposures.reduce((sum, e) => sum + e.count, 0);
125
+ findings.push({
126
+ id: 'guest-user-sharing-exposure',
127
+ category: this.category,
128
+ riskLevel: 'HIGH',
129
+ title: `${count} object sharing rule(s) expose records to guest users`,
130
+ affectedItems: sharingExposures.map((e) => ({
131
+ label: e.shareTable,
132
+ url: `${baseUrl}/lightning/setup/SecuritySharingRules/page`,
133
+ note: `${e.count} sharing rule(s) — review and remove guest-targeting rules`,
134
+ })),
135
+ detail: 'Sharing rules targeting guest users can expose internal records to unauthenticated visitors.',
136
+ remediation: 'Review and remove sharing rules that grant guest users access to Salesforce records. Use Experience Cloud sites with explicit data access controls instead.',
137
+ });
138
+ }
139
+ if (writeViolations.length === 0 && sharingExposures.length === 0) {
140
+ const count = guestUsers.length;
141
+ findings.push({
142
+ id: 'guest-user-baseline',
143
+ category: this.category,
144
+ riskLevel: 'MEDIUM',
145
+ title: `${count} active guest user(s) have live site access`,
146
+ affectedItems: guestUsers.map((u) => ({
147
+ label: u.Username,
148
+ url: `${baseUrl}/${u.Id}`,
149
+ note: 'Periodically review guest permissions and sharing configuration',
150
+ })),
151
+ detail: 'Guest users are present in this org. While no write access or overly permissive sharing rules were found, guest access should be periodically reviewed.',
152
+ remediation: 'Regularly review guest user profile permissions and sharing configurations as they represent an unauthenticated attack surface.',
153
+ });
154
+ }
155
+ return { findings };
156
+ }
157
+ }
158
+ //# sourceMappingURL=GuestUserAccessCheck.js.map
@@ -0,0 +1,12 @@
1
+ import type { AuditContext } from '../../context/AuditContext.js';
2
+ import type { SecurityCheck, CheckResult } from '../SecurityCheck.js';
3
+ export declare class HardcodedCredentialsCheck implements SecurityCheck {
4
+ readonly id = "hardcoded-credentials";
5
+ readonly name = "Hardcoded Credentials";
6
+ readonly category = "Code Security";
7
+ readonly description = "Scans Apex code for hardcoded Bearer tokens, Basic auth, API keys, and raw callout URLs";
8
+ readonly dependsOnCache: readonly ["namedCredentialEndpoints", "remoteSiteUrls"];
9
+ readonly populatesCache: readonly ["apexBodies"];
10
+ run(ctx: AuditContext): Promise<CheckResult>;
11
+ }
12
+ //# sourceMappingURL=HardcodedCredentialsCheck.d.ts.map
@@ -0,0 +1,146 @@
1
+ const HIGH_RISK_PATTERNS = [
2
+ /Bearer\s+[A-Za-z0-9\-_.~+/]{20,}=*/gi, // Bearer tokens (min length to avoid test stubs)
3
+ /Basic\s+[A-Za-z0-9+/]{20,}=*/gi, // Basic auth (min length)
4
+ /Authorization['":\s]+['"](Bearer|Basic)/gi, // Auth header construction
5
+ // Credential variable assignments with a string literal RHS
6
+ /(?:password|passwd|secret|apiKey|api_key|clientSecret|client_secret|accessToken|access_token|authToken|auth_token)\s*[=+]\s*'[^']{8,}'/gi,
7
+ ];
8
+ const ENDPOINT_PATTERN = /\.setEndpoint\s*\(\s*'(https?:\/\/[^']+)'/gi;
9
+ const IS_TEST_CLASS = /@IsTest\b/i;
10
+ function extractBase(url) {
11
+ try {
12
+ const u = new URL(url);
13
+ return `${u.protocol}//${u.host}`;
14
+ }
15
+ catch {
16
+ return url;
17
+ }
18
+ }
19
+ function isCovered(rawUrl, endpoints) {
20
+ const base = extractBase(rawUrl);
21
+ return endpoints.some((ep) => ep.includes(base) || base.includes(extractBase(ep)));
22
+ }
23
+ export class HardcodedCredentialsCheck {
24
+ id = 'hardcoded-credentials';
25
+ name = 'Hardcoded Credentials';
26
+ category = 'Code Security';
27
+ description = 'Scans Apex code for hardcoded Bearer tokens, Basic auth, API keys, and raw callout URLs';
28
+ dependsOnCache = ['namedCredentialEndpoints', 'remoteSiteUrls'];
29
+ populatesCache = ['apexBodies'];
30
+ async run(ctx) {
31
+ const findings = [];
32
+ const baseUrl = ctx.orgInfo.instanceUrl;
33
+ const apexClassesUrl = `${baseUrl}/lightning/setup/ApexClasses/page`;
34
+ const records = await ctx.tooling.query('SELECT Id, Name, Body, LengthWithoutComments, NamespacePrefix FROM ApexClass WHERE NamespacePrefix = null');
35
+ // Cache apex bodies for downstream checks — exclude test classes and filter null bodies
36
+ const nonTestRecords = records.filter((r) => !IS_TEST_CLASS.test(r.Body ?? ''));
37
+ ctx.cache.apexBodies = nonTestRecords.map((r) => ({ name: r.Name, body: r.Body ?? '' }));
38
+ const namedCredentialEndpoints = (ctx.cache.namedCredentialEndpoints ?? []).filter(Boolean);
39
+ const remoteSiteUrls = (ctx.cache.remoteSiteUrls ?? []).filter(Boolean);
40
+ const allCoveredEndpoints = [...namedCredentialEndpoints, ...remoteSiteUrls];
41
+ const classesWithCredentials = [];
42
+ const classesWithRawEndpointsUncovered = [];
43
+ const classesWithRawEndpointsCoveredOnly = [];
44
+ for (const record of nonTestRecords) {
45
+ const body = record.Body ?? '';
46
+ // Check for hardcoded credential patterns
47
+ const hasCredentials = HIGH_RISK_PATTERNS.some((pattern) => {
48
+ pattern.lastIndex = 0;
49
+ return pattern.test(body);
50
+ });
51
+ if (hasCredentials) {
52
+ classesWithCredentials.push(record.Name);
53
+ }
54
+ // Find raw endpoints
55
+ const rawEndpoints = [];
56
+ ENDPOINT_PATTERN.lastIndex = 0;
57
+ let match;
58
+ while ((match = ENDPOINT_PATTERN.exec(body)) !== null) {
59
+ rawEndpoints.push(match[1]);
60
+ }
61
+ if (rawEndpoints.length > 0) {
62
+ let hasUncovered = false;
63
+ let hasCoveredOnly = false;
64
+ for (const rawUrl of rawEndpoints) {
65
+ const coveredByNamed = isCovered(rawUrl, namedCredentialEndpoints);
66
+ const coveredByRemote = isCovered(rawUrl, remoteSiteUrls);
67
+ if (!coveredByNamed && !coveredByRemote) {
68
+ hasUncovered = true;
69
+ }
70
+ else if (!coveredByNamed && coveredByRemote) {
71
+ hasCoveredOnly = true;
72
+ }
73
+ }
74
+ if (hasUncovered) {
75
+ classesWithRawEndpointsUncovered.push(record.Name);
76
+ }
77
+ else if (hasCoveredOnly) {
78
+ classesWithRawEndpointsCoveredOnly.push(record.Name);
79
+ }
80
+ }
81
+ }
82
+ const total = nonTestRecords.length;
83
+ if (classesWithCredentials.length > 0) {
84
+ const count = classesWithCredentials.length;
85
+ findings.push({
86
+ id: 'hardcoded-credentials-found',
87
+ category: this.category,
88
+ riskLevel: 'HIGH',
89
+ title: `${count} Apex class(es) contain potential hardcoded credentials`,
90
+ detail: 'Hardcoded Bearer tokens, Basic auth, or API keys in Apex source code expose credentials to anyone with metadata read access.',
91
+ remediation: 'Replace hardcoded credentials with Named Credentials. Rotate any exposed credentials immediately.',
92
+ affectedItems: classesWithCredentials.map((name) => ({
93
+ label: name,
94
+ url: apexClassesUrl,
95
+ note: 'Replace hardcoded credential with a Named Credential and rotate the exposed secret',
96
+ })),
97
+ });
98
+ }
99
+ if (classesWithRawEndpointsUncovered.length > 0) {
100
+ const count = classesWithRawEndpointsUncovered.length;
101
+ findings.push({
102
+ id: 'raw-endpoints-uncovered',
103
+ category: this.category,
104
+ riskLevel: 'MEDIUM',
105
+ title: `${count} Apex class(es) contain raw callout endpoints not covered by Named Credentials`,
106
+ detail: 'Raw HTTPS endpoints in setEndpoint() calls are not protected by Named Credentials, which means authentication details may be hardcoded nearby.',
107
+ remediation: 'Migrate raw endpoints to Named Credentials to centralise credential management and reduce hardcoding.',
108
+ affectedItems: classesWithRawEndpointsUncovered.map((name) => ({
109
+ label: name,
110
+ url: apexClassesUrl,
111
+ note: 'Migrate setEndpoint() URL to a Named Credential',
112
+ })),
113
+ });
114
+ }
115
+ if (classesWithRawEndpointsCoveredOnly.length > 0) {
116
+ const count = classesWithRawEndpointsCoveredOnly.length;
117
+ findings.push({
118
+ id: 'raw-endpoints-remote-site-only',
119
+ category: this.category,
120
+ riskLevel: 'LOW',
121
+ title: `${count} Apex class(es) use raw endpoints covered by Remote Site Settings`,
122
+ detail: 'These classes use raw callout URLs but the endpoints are registered as Remote Sites. Consider migrating to Named Credentials for better credential management.',
123
+ remediation: 'Named Credentials provide better security than Remote Site Settings for authenticated callouts.',
124
+ affectedItems: classesWithRawEndpointsCoveredOnly.map((name) => ({
125
+ label: name,
126
+ url: apexClassesUrl,
127
+ note: 'Consider migrating to a Named Credential for better credential management',
128
+ })),
129
+ });
130
+ }
131
+ if (classesWithCredentials.length === 0 &&
132
+ classesWithRawEndpointsUncovered.length === 0 &&
133
+ classesWithRawEndpointsCoveredOnly.length === 0) {
134
+ findings.push({
135
+ id: 'no-hardcoded-credentials',
136
+ category: this.category,
137
+ riskLevel: 'LOW',
138
+ title: 'No hardcoded credentials or unprotected endpoints detected in Apex classes',
139
+ detail: `Scanned ${total} custom Apex classes. No obvious hardcoded credential patterns or unprotected callout endpoints were found.`,
140
+ remediation: 'Continue using Named Credentials for all external callouts and periodically re-scan as new code is added.',
141
+ });
142
+ }
143
+ return { findings };
144
+ }
145
+ }
146
+ //# sourceMappingURL=HardcodedCredentialsCheck.js.map
@@ -0,0 +1,11 @@
1
+ import type { AuditContext } from '../../context/AuditContext.js';
2
+ import type { SecurityCheck, CheckResult } from '../SecurityCheck.js';
3
+ export declare class HealthCheckCheck implements SecurityCheck {
4
+ readonly id = "health-check";
5
+ readonly name = "Security Health Check";
6
+ readonly category = "Health Check";
7
+ readonly description = "Reads the Salesforce Health Check score and flags individual risk items";
8
+ readonly populatesCache: readonly ["healthCheckRisks", "healthCloudInstalled"];
9
+ run(ctx: AuditContext): Promise<CheckResult>;
10
+ }
11
+ //# sourceMappingURL=HealthCheckCheck.d.ts.map
@@ -0,0 +1,70 @@
1
+ export class HealthCheckCheck {
2
+ id = 'health-check';
3
+ name = 'Security Health Check';
4
+ category = 'Health Check';
5
+ description = 'Reads the Salesforce Health Check score and flags individual risk items';
6
+ populatesCache = ['healthCheckRisks', 'healthCloudInstalled'];
7
+ async run(ctx) {
8
+ const findings = [];
9
+ const baseUrl = ctx.orgInfo.instanceUrl;
10
+ const healthCheckUrl = `${baseUrl}/lightning/setup/HealthCheck/page`;
11
+ // Health Cloud detection
12
+ const pkgRows = await ctx.soql.queryAll("SELECT NamespacePrefix FROM PackageLicense WHERE NamespacePrefix = 'HealthCloudGA'");
13
+ ctx.cache.healthCloudInstalled = pkgRows.length > 0;
14
+ // Health check score
15
+ const scoreRows = await ctx.tooling.query('SELECT Score FROM SecurityHealthCheck');
16
+ const score = scoreRows[0]?.Score ?? 0;
17
+ const scoreRisk = score < 50 ? 'CRITICAL' : score < 70 ? 'HIGH' : score < 85 ? 'MEDIUM' : 'LOW';
18
+ findings.push({
19
+ id: 'health-check-score',
20
+ category: this.category,
21
+ riskLevel: scoreRisk,
22
+ title: `Salesforce Security Health Check Score: ${score}/100`,
23
+ detail: `The Salesforce Security Health Check scored ${score}/100. Scores below 85 indicate security configuration gaps that should be addressed.`,
24
+ remediation: 'Review the Security Health Check in Setup → Security Center → Health Check.',
25
+ });
26
+ // HIGH_RISK items
27
+ const highRisks = await ctx.tooling.query("SELECT RiskType, Setting, SettingGroup, OrgValue, StandardValue FROM SecurityHealthCheckRisks WHERE RiskType='HIGH_RISK'");
28
+ ctx.cache.healthCheckRisks = [
29
+ ...highRisks.map((r) => ({ setting: r.Setting, riskType: r.RiskType, value: r.OrgValue, score: 10 })),
30
+ ];
31
+ if (highRisks.length > 0) {
32
+ findings.push({
33
+ id: 'health-check-high-risk',
34
+ category: this.category,
35
+ riskLevel: 'HIGH',
36
+ title: `Security Health Check: ${highRisks.length} High-Risk Setting(s) Require Attention`,
37
+ detail: 'One or more settings deviate from Salesforce security recommendations at the high-risk level.',
38
+ remediation: 'Address each highlighted setting in Setup → Security Center → Health Check.',
39
+ affectedItems: highRisks.map((r) => ({
40
+ label: r.Setting,
41
+ url: healthCheckUrl,
42
+ note: `Current: ${r.OrgValue} — Recommended: ${r.StandardValue}`,
43
+ })),
44
+ });
45
+ }
46
+ // MEDIUM_RISK items
47
+ const mediumRisks = await ctx.tooling.query("SELECT RiskType, Setting, SettingGroup, OrgValue, StandardValue FROM SecurityHealthCheckRisks WHERE RiskType='MEDIUM_RISK'");
48
+ ctx.cache.healthCheckRisks = [
49
+ ...(ctx.cache.healthCheckRisks ?? []),
50
+ ...mediumRisks.map((r) => ({ setting: r.Setting, riskType: r.RiskType, value: r.OrgValue, score: 4 })),
51
+ ];
52
+ if (mediumRisks.length > 0) {
53
+ findings.push({
54
+ id: 'health-check-medium-risk',
55
+ category: this.category,
56
+ riskLevel: 'MEDIUM',
57
+ title: `Security Health Check: ${mediumRisks.length} Medium-Risk Setting(s) Need Review`,
58
+ detail: 'One or more settings deviate from Salesforce security recommendations at the medium-risk level.',
59
+ remediation: 'Review and address medium-risk settings in Setup → Security Center → Health Check.',
60
+ affectedItems: mediumRisks.map((r) => ({
61
+ label: r.Setting,
62
+ url: healthCheckUrl,
63
+ note: `Current: ${r.OrgValue} — Recommended: ${r.StandardValue}`,
64
+ })),
65
+ });
66
+ }
67
+ return { findings, metrics: { healthCheckScore: score } };
68
+ }
69
+ }
70
+ //# sourceMappingURL=HealthCheckCheck.js.map
@@ -0,0 +1,10 @@
1
+ import type { AuditContext } from '../../context/AuditContext.js';
2
+ import type { SecurityCheck, CheckResult } from '../SecurityCheck.js';
3
+ export declare class InactiveUsersCheck implements SecurityCheck {
4
+ readonly id = "inactive-users";
5
+ readonly name = "Inactive Users";
6
+ readonly category = "Users & Admins";
7
+ readonly description = "Finds active licensed users with no login in the past 90 days";
8
+ run(ctx: AuditContext): Promise<CheckResult>;
9
+ }
10
+ //# sourceMappingURL=InactiveUsersCheck.d.ts.map
@@ -0,0 +1,47 @@
1
+ export class InactiveUsersCheck {
2
+ id = 'inactive-users';
3
+ name = 'Inactive Users';
4
+ category = 'Users & Admins';
5
+ description = 'Finds active licensed users with no login in the past 90 days';
6
+ async run(ctx) {
7
+ const findings = [];
8
+ const baseUrl = ctx.orgInfo.instanceUrl;
9
+ const inactiveUsers = await ctx.soql.queryAll(`
10
+ SELECT Id, Username, Name, Profile.Name, LastLoginDate, UserType
11
+ FROM User
12
+ WHERE IsActive = true
13
+ AND (LastLoginDate < LAST_N_DAYS:90 OR LastLoginDate = null)
14
+ AND UserType = 'Standard'
15
+ ORDER BY LastLoginDate ASC
16
+ LIMIT 50
17
+ `);
18
+ const count = inactiveUsers.length;
19
+ let riskLevel = 'LOW';
20
+ if (count > 20) {
21
+ riskLevel = 'HIGH';
22
+ }
23
+ else if (count > 10) {
24
+ riskLevel = 'MEDIUM';
25
+ }
26
+ findings.push({
27
+ id: 'inactive-users-90d',
28
+ category: this.category,
29
+ riskLevel,
30
+ title: `${count} active user(s) have not logged in for 90+ days`,
31
+ detail: 'Active accounts with no recent login represent stale credentials that may be compromised without detection.',
32
+ remediation: 'Deactivate or review accounts that have been inactive for 90+ days. Establish a regular user access review process.',
33
+ affectedItems: inactiveUsers.map((u) => ({
34
+ label: `${u.Username} (${u.Name})`,
35
+ url: `${baseUrl}/${u.Id}`,
36
+ note: `Last login: ${u.LastLoginDate ?? 'never'}`,
37
+ })),
38
+ });
39
+ return {
40
+ findings,
41
+ metrics: {
42
+ inactiveUsers90d: count,
43
+ },
44
+ };
45
+ }
46
+ }
47
+ //# sourceMappingURL=InactiveUsersCheck.js.map
@@ -0,0 +1,10 @@
1
+ import type { AuditContext } from '../../context/AuditContext.js';
2
+ import type { SecurityCheck, CheckResult } from '../SecurityCheck.js';
3
+ export declare class IpRestrictionsCheck implements SecurityCheck {
4
+ readonly id = "ip-restrictions";
5
+ readonly name = "Login IP Restrictions";
6
+ readonly category = "Identity & Access";
7
+ readonly description = "Checks admin profiles for missing IP range restrictions and connected apps with relaxed IP policies";
8
+ run(ctx: AuditContext): Promise<CheckResult>;
9
+ }
10
+ //# sourceMappingURL=IpRestrictionsCheck.d.ts.map
@@ -0,0 +1,94 @@
1
+ export class IpRestrictionsCheck {
2
+ id = 'ip-restrictions';
3
+ name = 'Login IP Restrictions';
4
+ category = 'Identity & Access';
5
+ description = 'Checks admin profiles for missing IP range restrictions and connected apps with relaxed IP policies';
6
+ async run(ctx) {
7
+ const findings = [];
8
+ const baseUrl = ctx.orgInfo.instanceUrl;
9
+ // 1. Admin users (Modify All Data via profile)
10
+ const adminUsers = await ctx.soql.queryAll(`SELECT Id, ProfileId, Profile.Name, Username FROM User
11
+ WHERE IsActive = true AND Profile.PermissionsModifyAllData = true`);
12
+ // 2. Profile IP ranges — try SOQL first, fallback to Tooling
13
+ let ipRanges = [];
14
+ try {
15
+ ipRanges = await ctx.soql.queryAll('SELECT ProfileId, StartAddress, EndAddress FROM ProfileLoginIpRange');
16
+ }
17
+ catch {
18
+ try {
19
+ ipRanges = await ctx.tooling.query('SELECT ProfileId, StartAddress, EndAddress FROM ProfileLoginIpRange');
20
+ }
21
+ catch {
22
+ // No IP ranges configured or not accessible — treat as empty
23
+ ipRanges = [];
24
+ }
25
+ }
26
+ // 3. Connected apps with IP relaxation
27
+ let connectedApps = [];
28
+ try {
29
+ connectedApps = await ctx.tooling.query('SELECT Id, Name FROM ConnectedApplication');
30
+ }
31
+ catch {
32
+ connectedApps = [];
33
+ }
34
+ const ipBypassingApps = [];
35
+ for (const app of connectedApps) {
36
+ try {
37
+ const detail = await ctx.tooling.getRecord('ConnectedApplication', app.Id);
38
+ const relaxation = detail.Metadata?.ipRelaxation;
39
+ if (relaxation === 'BYPASS' || relaxation === 'RELAX_IP') {
40
+ ipBypassingApps.push({ name: app.Name, id: app.Id });
41
+ }
42
+ }
43
+ catch {
44
+ // Skip apps whose detail record cannot be fetched
45
+ }
46
+ }
47
+ // Determine which profile IDs have at least one IP range
48
+ const profilesWithRanges = new Set(ipRanges.map((r) => r.ProfileId));
49
+ // Admin users whose profile has no IP ranges
50
+ const unrestrictedAdmins = adminUsers.filter((u) => !profilesWithRanges.has(u.ProfileId));
51
+ if (unrestrictedAdmins.length > 0) {
52
+ findings.push({
53
+ id: 'admin-no-ip-restrictions',
54
+ category: this.category,
55
+ riskLevel: 'HIGH',
56
+ title: `${unrestrictedAdmins.length} admin user(s) have profiles without login IP restrictions`,
57
+ affectedItems: unrestrictedAdmins.map((u) => ({
58
+ label: u.Username,
59
+ url: `${baseUrl}/${u.Id}`,
60
+ note: `Profile: ${u.Profile.Name} — add IP ranges in Setup → Profiles → Login IP Ranges`,
61
+ })),
62
+ detail: 'Administrator accounts without IP login restrictions can be accessed from any network, increasing exposure to credential-stuffing attacks.',
63
+ remediation: 'Add IP login ranges to all admin profiles in Setup → Profiles → Login IP Ranges, or enable MFA as a compensating control.',
64
+ });
65
+ }
66
+ if (ipBypassingApps.length > 0) {
67
+ findings.push({
68
+ id: 'connected-apps-bypass-ip',
69
+ category: this.category,
70
+ riskLevel: 'MEDIUM',
71
+ title: `${ipBypassingApps.length} connected app(s) bypass login IP enforcement`,
72
+ affectedItems: ipBypassingApps.map((app) => ({
73
+ label: app.name,
74
+ url: `${baseUrl}/lightning/setup/ConnectedApplication/page`,
75
+ note: 'Set IP Relaxation to "Enforce IP restrictions" unless remote access is required',
76
+ })),
77
+ detail: "Connected apps configured to relax IP restrictions allow API access from any IP address, even when the user's profile has IP restrictions.",
78
+ remediation: 'Set IP Relaxation to "Enforce IP restrictions" for connected apps unless there is a documented business requirement for remote access.',
79
+ });
80
+ }
81
+ if (unrestrictedAdmins.length === 0 && ipBypassingApps.length === 0) {
82
+ findings.push({
83
+ id: 'ip-restrictions-ok',
84
+ category: this.category,
85
+ riskLevel: 'LOW',
86
+ title: 'Login IP restrictions appear appropriately configured',
87
+ detail: 'All checked admin profiles have login IP ranges configured and no connected apps bypass IP enforcement.',
88
+ remediation: 'Periodically review IP restriction configuration as new admins and connected apps are added.',
89
+ });
90
+ }
91
+ return { findings };
92
+ }
93
+ }
94
+ //# sourceMappingURL=IpRestrictionsCheck.js.map
@@ -0,0 +1,10 @@
1
+ import type { AuditContext } from '../../context/AuditContext.js';
2
+ import type { SecurityCheck, CheckResult } from '../SecurityCheck.js';
3
+ export declare class LoginSessionCheck implements SecurityCheck {
4
+ readonly id = "login-session";
5
+ readonly name = "Login Session";
6
+ readonly category = "Session Security";
7
+ readonly description = "Analyses login history for failed login trends, Login-As events, and access from diverse IPs";
8
+ run(ctx: AuditContext): Promise<CheckResult>;
9
+ }
10
+ //# sourceMappingURL=LoginSessionCheck.d.ts.map
@@ -0,0 +1,54 @@
1
+ export class LoginSessionCheck {
2
+ id = 'login-session';
3
+ name = 'Login Session';
4
+ category = 'Session Security';
5
+ description = 'Analyses login history for failed login trends, Login-As events, and access from diverse IPs';
6
+ async run(ctx) {
7
+ const findings = [];
8
+ // Query login history for the last 30 days
9
+ const loginRecords = await ctx.soql.queryAll(`SELECT UserId, LoginTime, SourceIp, Status, LoginType, Application, Browser, Platform
10
+ FROM LoginHistory
11
+ WHERE LoginTime > LAST_N_DAYS:30
12
+ ORDER BY LoginTime DESC
13
+ LIMIT 2000`);
14
+ // Calculate failed login attempts
15
+ const failedLogins = loginRecords.filter((r) => r.Status !== 'Success');
16
+ const failedCount = failedLogins.length;
17
+ const totalLogins = loginRecords.length;
18
+ const failedRiskLevel = failedCount > 50 ? 'HIGH' : failedCount > 20 ? 'MEDIUM' : 'LOW';
19
+ findings.push({
20
+ id: 'failed-logins',
21
+ category: this.category,
22
+ riskLevel: failedRiskLevel,
23
+ title: `${failedCount} failed login attempt(s) in the last 30 days`,
24
+ detail: `There were ${failedCount} failed login attempts out of ${totalLogins} total logins in the last 30 days.`,
25
+ remediation: 'Investigate accounts with repeated failures. Consider IP restrictions or additional MFA policies for high-failure accounts.',
26
+ });
27
+ // Check for API logins from many distinct IPs
28
+ const apiLogins = loginRecords.filter((r) => r.LoginType &&
29
+ (r.LoginType.includes('API') ||
30
+ r.LoginType === 'OAuth 2.0' ||
31
+ r.LoginType === 'SAML'));
32
+ if (apiLogins.length > 0) {
33
+ const distinctIps = new Set(apiLogins.map((r) => r.SourceIp));
34
+ const distinctIpCount = distinctIps.size;
35
+ if (distinctIpCount > 10) {
36
+ findings.push({
37
+ id: 'api-logins-many-ips',
38
+ category: this.category,
39
+ riskLevel: 'MEDIUM',
40
+ title: `API logins detected from ${distinctIpCount} distinct IP addresses`,
41
+ detail: 'API access from many different IP addresses may indicate credential sharing or automation abuse.',
42
+ remediation: 'Review API-connected apps and users. Restrict API access to known IP ranges where possible.',
43
+ });
44
+ }
45
+ }
46
+ return {
47
+ findings,
48
+ metrics: {
49
+ failedLogins30d: failedCount,
50
+ },
51
+ };
52
+ }
53
+ }
54
+ //# sourceMappingURL=LoginSessionCheck.js.map
@@ -0,0 +1,11 @@
1
+ import type { AuditContext } from '../../context/AuditContext.js';
2
+ import type { SecurityCheck, CheckResult } from '../SecurityCheck.js';
3
+ export declare class NamedCredentialsCheck implements SecurityCheck {
4
+ readonly id = "named-credentials";
5
+ readonly name = "Named Credentials";
6
+ readonly category = "External Connectivity";
7
+ readonly description = "Inventories Named Credentials and flags any not referenced in Apex code";
8
+ readonly populatesCache: readonly ["namedCredentialEndpoints"];
9
+ run(ctx: AuditContext): Promise<CheckResult>;
10
+ }
11
+ //# sourceMappingURL=NamedCredentialsCheck.d.ts.map