@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,65 @@
1
+ const LIMITS_TO_CHECK = [
2
+ { key: 'DailyApiRequests', label: 'Daily API Requests' },
3
+ { key: 'DailyBulkApiRequests', label: 'Daily Bulk API Requests' },
4
+ { key: 'DailyAsyncApexExecutions', label: 'Daily Async Apex Executions' },
5
+ { key: 'DataStorageMB', label: 'Data Storage (MB)' },
6
+ { key: 'FileStorageMB', label: 'File Storage (MB)' },
7
+ { key: 'SingleEmail', label: 'Single Email' },
8
+ { key: 'MassEmail', label: 'Mass Email' },
9
+ { key: 'StreamingApiConcurrentClients', label: 'Streaming API Concurrent Clients' },
10
+ ];
11
+ export class ApiLimitsCheck {
12
+ id = 'api-limits';
13
+ name = 'API and Resource Limits';
14
+ category = 'Resource Management';
15
+ description = 'Monitors API request consumption against daily and concurrent limits';
16
+ async run(ctx) {
17
+ const findings = [];
18
+ const limits = await ctx.rest.get('/limits');
19
+ const overThresholdLimits = [];
20
+ for (const { key, label } of LIMITS_TO_CHECK) {
21
+ const entry = limits[key];
22
+ if (!entry)
23
+ continue;
24
+ const { Max, Remaining } = entry;
25
+ if (Max === 0)
26
+ continue;
27
+ const Used = Max - Remaining;
28
+ const usedPct = (Used / Max) * 100;
29
+ if (usedPct > 50) {
30
+ overThresholdLimits.push({ label, usedPct, Max, Used });
31
+ }
32
+ }
33
+ if (overThresholdLimits.length > 0) {
34
+ for (const { label, usedPct, Max, Used } of overThresholdLimits) {
35
+ let riskLevel;
36
+ if (usedPct > 90)
37
+ riskLevel = 'CRITICAL';
38
+ else if (usedPct > 75)
39
+ riskLevel = 'HIGH';
40
+ else
41
+ riskLevel = 'MEDIUM';
42
+ findings.push({
43
+ id: `api-limit-${label.toLowerCase().replace(/\s+/g, '-')}`,
44
+ category: this.category,
45
+ riskLevel,
46
+ title: `${label}: ${usedPct.toFixed(0)}% used (${Used} of ${Max})`,
47
+ detail: `Org limit ${label} is at ${usedPct.toFixed(1)}% utilization. High usage increases the risk of governor limit failures.`,
48
+ remediation: 'Review usage patterns and consider requesting a limit increase, optimizing batch job scheduling, or archiving data.',
49
+ });
50
+ }
51
+ }
52
+ else {
53
+ findings.push({
54
+ id: 'api-limits-healthy',
55
+ category: this.category,
56
+ riskLevel: 'LOW',
57
+ title: 'All monitored API limits are within acceptable thresholds',
58
+ detail: 'All monitored API and resource limits are below 50% utilization.',
59
+ remediation: 'Continue monitoring limits as org activity grows.',
60
+ });
61
+ }
62
+ return { findings };
63
+ }
64
+ }
65
+ //# sourceMappingURL=ApiLimitsCheck.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 AuditTrailCheck implements SecurityCheck {
4
+ readonly id = "audit-trail";
5
+ readonly name = "Audit Trail";
6
+ readonly category = "Security Controls";
7
+ readonly description = "Reviews setup audit trail for permission changes and Login-As events";
8
+ run(ctx: AuditContext): Promise<CheckResult>;
9
+ }
10
+ //# sourceMappingURL=AuditTrailCheck.d.ts.map
@@ -0,0 +1,69 @@
1
+ export class AuditTrailCheck {
2
+ id = 'audit-trail';
3
+ name = 'Audit Trail';
4
+ category = 'Security Controls';
5
+ description = 'Reviews setup audit trail for permission changes and Login-As events';
6
+ async run(ctx) {
7
+ const findings = [];
8
+ const baseUrl = ctx.orgInfo.instanceUrl;
9
+ const auditTrailUrl = `${baseUrl}/lightning/setup/AuditTrail/page`;
10
+ // Query audit trail for the last 7 days
11
+ const auditRecords = await ctx.soql.queryAll(`SELECT CreatedDate, CreatedBy.Username, Action, Display, Section
12
+ FROM SetupAuditTrail
13
+ WHERE CreatedDate > LAST_N_DAYS:7
14
+ ORDER BY CreatedDate DESC
15
+ LIMIT 200`);
16
+ // Sensitive sections to monitor
17
+ const sensitiveSections = [
18
+ 'Permission Sets',
19
+ 'Profiles',
20
+ 'Manage Users',
21
+ 'Security Controls',
22
+ 'Password Policies',
23
+ ];
24
+ // Filter for permission/security changes
25
+ const securityChanges = auditRecords.filter((r) => sensitiveSections.includes(r.Section));
26
+ const securityChangeCount = securityChanges.length;
27
+ const securityRiskLevel = securityChangeCount > 20
28
+ ? 'HIGH'
29
+ : securityChangeCount > 10
30
+ ? 'MEDIUM'
31
+ : 'LOW';
32
+ findings.push({
33
+ id: 'permission-security-changes',
34
+ category: this.category,
35
+ riskLevel: securityRiskLevel,
36
+ title: `${securityChangeCount} permission or security configuration change(s) in the last 7 days`,
37
+ detail: 'Frequent permission and security changes can indicate privilege escalation activity or risky configuration drift.',
38
+ remediation: 'Review each change in Setup → Audit Trail. Investigate unexpected changes, especially outside change-management windows.',
39
+ affectedItems: securityChanges.slice(0, 10).map((r) => ({
40
+ label: `${r.CreatedBy.Username}: ${r.Display}`,
41
+ url: auditTrailUrl,
42
+ note: new Date(r.CreatedDate).toISOString().split('T')[0],
43
+ })),
44
+ });
45
+ // Query for Login-As events
46
+ const loginAsRecords = await ctx.soql.queryAll(`SELECT CreatedDate, CreatedBy.Username, Display
47
+ FROM SetupAuditTrail
48
+ WHERE CreatedDate > LAST_N_DAYS:7 AND Action LIKE '%loginAs%'
49
+ ORDER BY CreatedDate DESC
50
+ LIMIT 20`);
51
+ if (loginAsRecords.length > 0) {
52
+ findings.push({
53
+ id: 'login-as-events',
54
+ category: this.category,
55
+ riskLevel: 'MEDIUM',
56
+ title: `${loginAsRecords.length} "Login As" event(s) recorded in the last 7 days`,
57
+ detail: 'Administrators logging in as other users can access their data and perform actions on their behalf.',
58
+ remediation: 'Review Login-As usage. Ensure it is used only for legitimate support purposes and is logged and approved.',
59
+ affectedItems: loginAsRecords.slice(0, 10).map((r) => ({
60
+ label: `${r.CreatedBy.Username}: ${r.Display}`,
61
+ url: auditTrailUrl,
62
+ note: new Date(r.CreatedDate).toISOString().split('T')[0],
63
+ })),
64
+ });
65
+ }
66
+ return { findings };
67
+ }
68
+ }
69
+ //# sourceMappingURL=AuditTrailCheck.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 CodeSecurityCheck implements SecurityCheck {
4
+ readonly id = "code-security";
5
+ readonly name = "Code Security and Coverage";
6
+ readonly category = "Code Security";
7
+ readonly description = "Reports org-wide Apex test coverage percentage and class/trigger counts";
8
+ run(ctx: AuditContext): Promise<CheckResult>;
9
+ }
10
+ //# sourceMappingURL=CodeSecurityCheck.d.ts.map
@@ -0,0 +1,53 @@
1
+ export class CodeSecurityCheck {
2
+ id = 'code-security';
3
+ name = 'Code Security and Coverage';
4
+ category = 'Code Security';
5
+ description = 'Reports org-wide Apex test coverage percentage and class/trigger counts';
6
+ async run(ctx) {
7
+ const findings = [];
8
+ // Query class and trigger counts using Tooling API
9
+ const classCountResults = await ctx.tooling.query("SELECT COUNT() FROM ApexClass WHERE NamespacePrefix = null AND IsTest = false");
10
+ const classCount = classCountResults[0]?.expr0 ?? 0;
11
+ const triggerCountResults = await ctx.tooling.query('SELECT COUNT() FROM ApexTrigger WHERE NamespacePrefix = null');
12
+ const triggerCount = triggerCountResults[0]?.expr0 ?? 0;
13
+ // Query coverage
14
+ const coverageResults = await ctx.tooling.query('SELECT PercentCovered FROM ApexOrgWideCoverage');
15
+ if (coverageResults.length > 0) {
16
+ const coverage = coverageResults[0].PercentCovered;
17
+ let riskLevel = 'LOW';
18
+ if (coverage < 75) {
19
+ riskLevel = 'HIGH';
20
+ }
21
+ else if (coverage < 85) {
22
+ riskLevel = 'MEDIUM';
23
+ }
24
+ findings.push({
25
+ id: 'code-coverage',
26
+ category: this.category,
27
+ riskLevel,
28
+ title: `Apex test coverage: ${coverage}%`,
29
+ detail: `Org-wide Apex test coverage is ${coverage}%. Salesforce requires 75% minimum to deploy but higher coverage indicates better code quality and security.`,
30
+ remediation: 'Increase test coverage, particularly for security-sensitive Apex classes handling authentication, data access, and external integrations.',
31
+ });
32
+ }
33
+ else {
34
+ findings.push({
35
+ id: 'code-coverage-unavailable',
36
+ category: this.category,
37
+ riskLevel: 'INFO',
38
+ title: `Apex code inventory: ${classCount} class(es), ${triggerCount} trigger(s)`,
39
+ detail: `Code coverage data is not available for this org. The org has ${classCount} custom Apex classes and ${triggerCount} custom Apex triggers.`,
40
+ remediation: 'Run Apex tests in this org to generate coverage data. Ensure all Apex code has adequate test coverage.',
41
+ });
42
+ }
43
+ return {
44
+ findings,
45
+ metrics: {
46
+ apexClassCount: classCount,
47
+ apexTriggerCount: triggerCount,
48
+ codeCoveragePercent: coverageResults[0]?.PercentCovered ?? 0,
49
+ },
50
+ };
51
+ }
52
+ }
53
+ //# sourceMappingURL=CodeSecurityCheck.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 ConnectedAppsCheck implements SecurityCheck {
4
+ readonly id = "connected-apps";
5
+ readonly name = "Connected Apps";
6
+ readonly category = "App Security";
7
+ readonly description = "Flags connected apps not restricted to admin-approved users";
8
+ run(ctx: AuditContext): Promise<CheckResult>;
9
+ }
10
+ //# sourceMappingURL=ConnectedAppsCheck.d.ts.map
@@ -0,0 +1,48 @@
1
+ export class ConnectedAppsCheck {
2
+ id = 'connected-apps';
3
+ name = 'Connected Apps';
4
+ category = 'App Security';
5
+ description = 'Flags connected apps not restricted to admin-approved users';
6
+ async run(ctx) {
7
+ const findings = [];
8
+ const baseUrl = ctx.orgInfo.instanceUrl;
9
+ // Query all connected applications
10
+ const connectedApps = await ctx.soql.queryAll(`SELECT Id, Name, OptionsAllowAdminApprovedUsersOnly
11
+ FROM ConnectedApplication`);
12
+ const count = connectedApps.length;
13
+ // Check for apps with unrestricted user access
14
+ const unrestrictedApps = connectedApps.filter((app) => !app.OptionsAllowAdminApprovedUsersOnly);
15
+ if (unrestrictedApps.length > 0) {
16
+ findings.push({
17
+ id: 'unrestricted-connected-apps',
18
+ category: this.category,
19
+ riskLevel: 'MEDIUM',
20
+ title: `${unrestrictedApps.length} connected app(s) allow unrestricted user access`,
21
+ detail: 'Connected apps not restricted to admin-approved users can allow any org user to authorize the app, potentially exposing data.',
22
+ remediation: 'In each connected app settings, set "Permitted Users" to "Admin approved users are pre-authorized".',
23
+ affectedItems: unrestrictedApps.map((app) => ({
24
+ label: app.Name,
25
+ url: `${baseUrl}/${app.Id}`,
26
+ })),
27
+ });
28
+ }
29
+ else {
30
+ // All apps are properly restricted
31
+ findings.push({
32
+ id: 'restricted-connected-apps',
33
+ category: this.category,
34
+ riskLevel: 'LOW',
35
+ title: 'All connected apps restrict user access appropriately',
36
+ detail: `All ${count} connected app(s) are configured to require admin pre-authorization.`,
37
+ remediation: 'Continue monitoring as new connected apps are added.',
38
+ });
39
+ }
40
+ return {
41
+ findings,
42
+ metrics: {
43
+ connectedAppsCount: count,
44
+ },
45
+ };
46
+ }
47
+ }
48
+ //# sourceMappingURL=ConnectedAppsCheck.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 CustomSettingsCheck implements SecurityCheck {
4
+ readonly id = "custom-settings";
5
+ readonly name = "Custom Settings and Credentials";
6
+ readonly category = "Code Security";
7
+ readonly description = "Flags custom settings with credential-like names that may store secrets";
8
+ run(ctx: AuditContext): Promise<CheckResult>;
9
+ }
10
+ //# sourceMappingURL=CustomSettingsCheck.d.ts.map
@@ -0,0 +1,59 @@
1
+ const SENSITIVE_KEYWORDS = [
2
+ 'password',
3
+ 'secret',
4
+ 'token',
5
+ 'key',
6
+ 'credential',
7
+ 'api_key',
8
+ 'apikey',
9
+ ];
10
+ export class CustomSettingsCheck {
11
+ id = 'custom-settings';
12
+ name = 'Custom Settings and Credentials';
13
+ category = 'Code Security';
14
+ description = 'Flags custom settings with credential-like names that may store secrets';
15
+ async run(ctx) {
16
+ const findings = [];
17
+ const baseUrl = ctx.orgInfo.instanceUrl;
18
+ const customObjects = await ctx.tooling.query(`
19
+ SELECT Id, DeveloperName, Description FROM CustomObject
20
+ WHERE DeveloperName LIKE '%Setting%'
21
+ OR DeveloperName LIKE '%Config%'
22
+ OR DeveloperName LIKE '%Credential%'
23
+ `);
24
+ // Filter for matches with sensitive keywords
25
+ const matches = customObjects.filter((obj) => {
26
+ const devName = (obj.DeveloperName || '').toLowerCase();
27
+ const desc = (obj.Description || '').toLowerCase();
28
+ const combined = `${devName} ${desc}`;
29
+ return SENSITIVE_KEYWORDS.some((keyword) => combined.includes(keyword));
30
+ });
31
+ if (matches.length > 0) {
32
+ findings.push({
33
+ id: 'custom-settings-credentials',
34
+ category: this.category,
35
+ riskLevel: 'HIGH',
36
+ title: `${matches.length} custom object(s) may store sensitive credentials`,
37
+ detail: 'Custom objects named with credential-related terms may be storing API keys, passwords, or other secrets in plaintext Salesforce records.',
38
+ remediation: 'Replace credential storage in custom objects with Named Credentials or a dedicated secrets management solution.',
39
+ affectedItems: matches.map((obj) => ({
40
+ label: `${obj.DeveloperName}__c`,
41
+ url: `${baseUrl}/lightning/setup/ObjectManager/${obj.DeveloperName}__c/Details/view`,
42
+ note: 'Review records for stored secrets and migrate to Named Credentials',
43
+ })),
44
+ });
45
+ }
46
+ else {
47
+ findings.push({
48
+ id: 'custom-settings-clean',
49
+ category: this.category,
50
+ riskLevel: 'LOW',
51
+ title: 'No obviously credential-related custom objects detected',
52
+ detail: 'No custom objects with credential-related naming patterns were found.',
53
+ remediation: 'Continue to avoid storing secrets in custom objects or custom settings. Use Named Credentials for external authentication.',
54
+ });
55
+ }
56
+ return { findings };
57
+ }
58
+ }
59
+ //# sourceMappingURL=CustomSettingsCheck.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 FieldLevelSecurityCheck implements SecurityCheck {
4
+ readonly id = "field-level-security";
5
+ readonly name = "Field-Level Security";
6
+ readonly category = "Data Access";
7
+ readonly description = "Detects sensitive custom fields (SSN, credit card, tax ID) exposed to broad permission sets";
8
+ run(ctx: AuditContext): Promise<CheckResult>;
9
+ }
10
+ //# sourceMappingURL=FieldLevelSecurityCheck.d.ts.map
@@ -0,0 +1,149 @@
1
+ export class FieldLevelSecurityCheck {
2
+ id = 'field-level-security';
3
+ name = 'Field-Level Security';
4
+ category = 'Data Access';
5
+ description = 'Detects sensitive custom fields (SSN, credit card, tax ID) exposed to broad permission sets';
6
+ async run(ctx) {
7
+ const findings = [];
8
+ const baseUrl = ctx.orgInfo.instanceUrl;
9
+ // 1. Find sensitive custom fields
10
+ let sensitiveFields = [];
11
+ try {
12
+ sensitiveFields = await ctx.tooling.query(`SELECT Id, DeveloperName, TableEnumOrId FROM CustomField
13
+ WHERE (DeveloperName LIKE '%SSN%' OR DeveloperName LIKE '%SocialSecurity%'
14
+ OR DeveloperName LIKE '%CreditCard%' OR DeveloperName LIKE '%Password%'
15
+ OR DeveloperName LIKE '%Token%' OR DeveloperName LIKE '%BankAccount%'
16
+ OR DeveloperName LIKE '%DOB%' OR DeveloperName LIKE '%DateOfBirth%'
17
+ OR DeveloperName LIKE '%MedicalRecord%' OR DeveloperName LIKE '%Diagnosis%')
18
+ LIMIT 100`);
19
+ }
20
+ catch {
21
+ findings.push({
22
+ id: 'field-level-security-query-error',
23
+ category: this.category,
24
+ riskLevel: 'INFO',
25
+ title: 'Field-level security analysis could not be completed',
26
+ detail: 'The CustomField query failed. This may be due to insufficient permissions or Tooling API access restrictions.',
27
+ remediation: 'Ensure the running user has access to the Tooling API and CustomField sobject.',
28
+ });
29
+ return { findings };
30
+ }
31
+ if (sensitiveFields.length === 0) {
32
+ findings.push({
33
+ id: 'field-level-security-ok',
34
+ category: this.category,
35
+ riskLevel: 'LOW',
36
+ title: 'Sensitive custom fields appear appropriately restricted',
37
+ detail: 'No sensitive custom fields with excessive permission set access were found.',
38
+ remediation: 'Continue to apply restrictive field-level security to any new sensitive fields.',
39
+ });
40
+ return { findings };
41
+ }
42
+ // 2. Resolve object API names
43
+ const objectIds = [...new Set(sensitiveFields.map((f) => f.TableEnumOrId))];
44
+ let entityDefs = [];
45
+ try {
46
+ entityDefs = await ctx.tooling.query(`SELECT Id, QualifiedApiName FROM EntityDefinition WHERE Id IN (${objectIds.map((id) => `'${id}'`).join(', ')})`);
47
+ }
48
+ catch {
49
+ // If entity lookup fails, fall through — field names will be unresolvable
50
+ }
51
+ const objectApiNameById = new Map(entityDefs.map((e) => [e.Id, e.QualifiedApiName]));
52
+ // Build field API names: {ObjectApiName}.{DeveloperName}__c
53
+ const fieldApiNames = [];
54
+ const fieldApiNameMap = new Map();
55
+ for (const field of sensitiveFields) {
56
+ const objectApiName = objectApiNameById.get(field.TableEnumOrId);
57
+ if (objectApiName) {
58
+ const fieldApiName = `${objectApiName}.${field.DeveloperName}__c`;
59
+ fieldApiNames.push(fieldApiName);
60
+ fieldApiNameMap.set(fieldApiName, fieldApiName);
61
+ }
62
+ }
63
+ if (fieldApiNames.length === 0) {
64
+ findings.push({
65
+ id: 'field-level-security-ok',
66
+ category: this.category,
67
+ riskLevel: 'LOW',
68
+ title: 'Sensitive custom fields appear appropriately restricted',
69
+ detail: 'No sensitive custom fields with excessive permission set access were found.',
70
+ remediation: 'Continue to apply restrictive field-level security to any new sensitive fields.',
71
+ });
72
+ return { findings };
73
+ }
74
+ // 3. Check how many permission sets give Read access per field
75
+ let permRecords = [];
76
+ try {
77
+ const result = await ctx.soql.query(`SELECT Field, COUNT(ParentId) cnt FROM FieldPermissions
78
+ WHERE PermissionsRead = true AND Field IN (${fieldApiNames.map((f) => `'${f}'`).join(', ')})
79
+ GROUP BY Field`);
80
+ permRecords = result.records.map((r) => ({
81
+ Field: r.Field,
82
+ cnt: r.cnt != null
83
+ ? Number(r.cnt)
84
+ : 0,
85
+ }));
86
+ }
87
+ catch {
88
+ findings.push({
89
+ id: 'field-level-security-ok',
90
+ category: this.category,
91
+ riskLevel: 'LOW',
92
+ title: 'Sensitive custom fields appear appropriately restricted',
93
+ detail: 'No sensitive custom fields with excessive permission set access were found.',
94
+ remediation: 'Continue to apply restrictive field-level security to any new sensitive fields.',
95
+ });
96
+ return { findings };
97
+ }
98
+ const highExposure = permRecords.filter((r) => r.cnt > 15);
99
+ const mediumExposure = permRecords.filter((r) => r.cnt > 10 && r.cnt <= 15);
100
+ if (highExposure.length > 0) {
101
+ findings.push({
102
+ id: 'field-level-security-high',
103
+ category: this.category,
104
+ riskLevel: 'HIGH',
105
+ title: `${highExposure.length} sensitive field(s) are readable by more than 15 permission sets`,
106
+ affectedItems: highExposure.map((r) => {
107
+ const objectApiName = r.Field.split('.')[0];
108
+ return {
109
+ label: r.Field,
110
+ url: `${baseUrl}/lightning/setup/ObjectManager/${objectApiName}/FieldsAndRelationships/view`,
111
+ note: `Readable by ${r.cnt} permission sets — restrict to minimum required`,
112
+ };
113
+ }),
114
+ detail: 'Widely-accessible sensitive fields increase the risk of data exposure. These fields may contain PII, PHI, or financial data.',
115
+ remediation: 'Review field-level security for each affected field. Restrict access to the minimum number of roles that require it.',
116
+ });
117
+ }
118
+ if (mediumExposure.length > 0) {
119
+ findings.push({
120
+ id: 'field-level-security-medium',
121
+ category: this.category,
122
+ riskLevel: 'MEDIUM',
123
+ title: `${mediumExposure.length} sensitive field(s) are readable by 10-15 permission sets`,
124
+ affectedItems: mediumExposure.map((r) => {
125
+ const objectApiName = r.Field.split('.')[0];
126
+ return {
127
+ label: r.Field,
128
+ url: `${baseUrl}/lightning/setup/ObjectManager/${objectApiName}/FieldsAndRelationships/view`,
129
+ note: `Readable by ${r.cnt} permission sets — review and reduce access`,
130
+ };
131
+ }),
132
+ detail: 'Widely-accessible sensitive fields increase the risk of data exposure. These fields may contain PII, PHI, or financial data.',
133
+ remediation: 'Review field-level security for each affected field. Restrict access to the minimum number of roles that require it.',
134
+ });
135
+ }
136
+ if (highExposure.length === 0 && mediumExposure.length === 0) {
137
+ findings.push({
138
+ id: 'field-level-security-ok',
139
+ category: this.category,
140
+ riskLevel: 'LOW',
141
+ title: 'Sensitive custom fields appear appropriately restricted',
142
+ detail: 'No sensitive custom fields with excessive permission set access were found.',
143
+ remediation: 'Continue to apply restrictive field-level security to any new sensitive fields.',
144
+ });
145
+ }
146
+ return { findings };
147
+ }
148
+ }
149
+ //# sourceMappingURL=FieldLevelSecurityCheck.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 FlowsWithoutSharingCheck implements SecurityCheck {
4
+ readonly id = "flows-without-sharing";
5
+ readonly name = "Flows Without Sharing Context";
6
+ readonly category = "Flow Security";
7
+ readonly description = "Identifies active flows running in system context without sharing enforcement";
8
+ run(ctx: AuditContext): Promise<CheckResult>;
9
+ }
10
+ //# sourceMappingURL=FlowsWithoutSharingCheck.d.ts.map
@@ -0,0 +1,60 @@
1
+ export class FlowsWithoutSharingCheck {
2
+ id = 'flows-without-sharing';
3
+ name = 'Flows Without Sharing Context';
4
+ category = 'Flow Security';
5
+ description = 'Identifies active flows running in system context without sharing enforcement';
6
+ async run(ctx) {
7
+ const findings = [];
8
+ const baseUrl = ctx.orgInfo.instanceUrl;
9
+ const flows = await ctx.tooling.query("SELECT Id, MasterLabel, ProcessType, Status, RunInMode FROM Flow WHERE Status = 'Active'");
10
+ const total = flows.length;
11
+ const autolaunchedWithoutSharing = flows.filter((f) => f.ProcessType === 'AutoLaunchedFlow' &&
12
+ (f.RunInMode === 'DefaultMode' || f.RunInMode === null));
13
+ const screenWithoutSharing = flows.filter((f) => f.ProcessType === 'Flow' &&
14
+ (f.RunInMode === 'DefaultMode' || f.RunInMode === null));
15
+ if (autolaunchedWithoutSharing.length > 0) {
16
+ const count = autolaunchedWithoutSharing.length;
17
+ findings.push({
18
+ id: 'flows-autolaunched-without-sharing',
19
+ category: this.category,
20
+ riskLevel: 'HIGH',
21
+ title: `${count} autolaunched flow(s) run without user sharing context`,
22
+ affectedItems: autolaunchedWithoutSharing.map((f) => ({
23
+ label: f.MasterLabel,
24
+ url: `${baseUrl}/builder_platform_interaction/flowBuilder.app?flowId=${f.Id}`,
25
+ note: 'Set "Run Flow As" to "User" or document why system context is required',
26
+ })),
27
+ detail: "Autolaunched flows running in Default Mode execute with system-level data access, ignoring the triggering user's record visibility.",
28
+ remediation: 'Set "Run Flow As" to "User" for autolaunched flows that access sensitive data, or explicitly document why system context is required.',
29
+ });
30
+ }
31
+ if (screenWithoutSharing.length > 0) {
32
+ const count = screenWithoutSharing.length;
33
+ findings.push({
34
+ id: 'flows-screen-without-sharing',
35
+ category: this.category,
36
+ riskLevel: 'MEDIUM',
37
+ title: `${count} screen flow(s) run without user sharing context`,
38
+ affectedItems: screenWithoutSharing.map((f) => ({
39
+ label: f.MasterLabel,
40
+ url: `${baseUrl}/builder_platform_interaction/flowBuilder.app?flowId=${f.Id}`,
41
+ note: 'Review and set "Run Flow As" to "User" where appropriate',
42
+ })),
43
+ detail: "Screen flows in Default Mode may allow users to view or modify records they wouldn't normally have access to.",
44
+ remediation: 'Review each screen flow and set "Run Flow As" to "User" where appropriate to enforce record-level security.',
45
+ });
46
+ }
47
+ if (autolaunchedWithoutSharing.length === 0 && screenWithoutSharing.length === 0) {
48
+ findings.push({
49
+ id: 'flows-without-sharing-none',
50
+ category: this.category,
51
+ riskLevel: 'LOW',
52
+ title: 'No active flows running without sharing context identified',
53
+ detail: `All ${total} active flows either enforce user sharing context or are not autolaunched/screen flow types.`,
54
+ remediation: 'Continue to review flow settings when new flows are activated.',
55
+ });
56
+ }
57
+ return { findings };
58
+ }
59
+ }
60
+ //# sourceMappingURL=FlowsWithoutSharingCheck.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 GuestUserAccessCheck implements SecurityCheck {
4
+ readonly id = "guest-user-access";
5
+ readonly name = "Guest User Access";
6
+ readonly category = "Access Control";
7
+ readonly description = "Audits object permissions and sharing rules granted to unauthenticated guest users";
8
+ readonly dependsOnCache: readonly ["healthCloudInstalled"];
9
+ run(ctx: AuditContext): Promise<CheckResult>;
10
+ }
11
+ //# sourceMappingURL=GuestUserAccessCheck.d.ts.map