@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,85 @@
1
+ export class UsersAndAdminsCheck {
2
+ id = 'users-and-admins';
3
+ name = 'Users and Admins';
4
+ category = 'Users & Admins';
5
+ description = 'Identifies users with dangerous system-wide permissions (ModifyAllData, ViewAllData, AuthorApex, CustomizeApplication)';
6
+ async run(ctx) {
7
+ const findings = [];
8
+ const baseUrl = ctx.orgInfo.instanceUrl;
9
+ const userItem = (r) => ({
10
+ label: `${r.Assignee.Username} (${r.Assignee.Profile?.Name ?? 'Unknown Profile'})`,
11
+ url: `${baseUrl}/${r.Assignee.Id}`,
12
+ note: `via: ${r.PermissionSet.IsOwnedByProfile ? 'Profile' : r.PermissionSet.Name}`,
13
+ });
14
+ // Total active users
15
+ const activeUsersResult = await ctx.soql.query('SELECT COUNT() FROM User WHERE IsActive = true');
16
+ const totalActiveUsers = activeUsersResult.totalSize;
17
+ // Modify All Data
18
+ const modifyAllResult = await ctx.soql.query('SELECT Assignee.Id, Assignee.Username, Assignee.Name, Assignee.Profile.Name, PermissionSet.Name, PermissionSet.IsOwnedByProfile FROM PermissionSetAssignment WHERE PermissionSet.PermissionsModifyAllData = true AND Assignee.IsActive = true');
19
+ const modifyAllUsers = modifyAllResult.records;
20
+ const modifyAllCount = modifyAllUsers.length;
21
+ const modifyRisk = modifyAllCount > 5 ? 'CRITICAL' : modifyAllCount > 3 ? 'HIGH' : 'LOW';
22
+ findings.push({
23
+ id: 'users-modify-all-data',
24
+ category: this.category,
25
+ riskLevel: modifyRisk,
26
+ title: `${modifyAllCount} user(s) have Modify All Data permission`,
27
+ detail: 'Modify All Data grants unrestricted write access across all objects. This is one of the most powerful permissions in Salesforce.',
28
+ remediation: 'Limit Modify All Data to essential system administrators only. Review each user and remove the permission from any non-essential accounts.',
29
+ affectedItems: modifyAllUsers.map(userItem),
30
+ });
31
+ // View All Data
32
+ const viewAllResult = await ctx.soql.query('SELECT Assignee.Id, Assignee.Username, Assignee.Name, Assignee.Profile.Name, PermissionSet.Name, PermissionSet.IsOwnedByProfile FROM PermissionSetAssignment WHERE PermissionSet.PermissionsViewAllData = true AND Assignee.IsActive = true');
33
+ const viewAllUsers = viewAllResult.records;
34
+ const viewAllCount = viewAllUsers.length;
35
+ const viewRisk = viewAllCount > 10 ? 'HIGH' : viewAllCount > 5 ? 'MEDIUM' : 'LOW';
36
+ findings.push({
37
+ id: 'users-view-all-data',
38
+ category: this.category,
39
+ riskLevel: viewRisk,
40
+ title: `${viewAllCount} user(s) have View All Data permission`,
41
+ detail: 'View All Data grants unrestricted read access across all objects, bypassing sharing rules and record-level security.',
42
+ remediation: 'Limit View All Data to essential users. Consider using permission sets scoped to specific objects instead.',
43
+ affectedItems: viewAllUsers.map(userItem),
44
+ });
45
+ // Customize Application
46
+ const customizeAppResult = await ctx.soql.query('SELECT Assignee.Id, Assignee.Username, Assignee.Profile.Name, PermissionSet.Name, PermissionSet.IsOwnedByProfile FROM PermissionSetAssignment WHERE PermissionSet.PermissionsCustomizeApplication = true AND Assignee.IsActive = true');
47
+ const customizeAppUsers = customizeAppResult.records;
48
+ const customizeAppCount = customizeAppUsers.length;
49
+ if (customizeAppCount > 5) {
50
+ findings.push({
51
+ id: 'users-customize-application',
52
+ category: this.category,
53
+ riskLevel: 'MEDIUM',
54
+ title: `${customizeAppCount} user(s) have Customize Application permission`,
55
+ detail: 'Customize Application allows users to make metadata changes, including modifying page layouts, custom fields, and application settings.',
56
+ remediation: 'Customize Application allows metadata changes. Review and reduce to essential configuration administrators.',
57
+ affectedItems: customizeAppUsers.map(userItem),
58
+ });
59
+ }
60
+ // Author Apex
61
+ const authorApexResult = await ctx.soql.query('SELECT Assignee.Id, Assignee.Username, Assignee.Profile.Name, PermissionSet.Name, PermissionSet.IsOwnedByProfile FROM PermissionSetAssignment WHERE PermissionSet.PermissionsAuthorApex = true AND Assignee.IsActive = true');
62
+ const authorApexUsers = authorApexResult.records;
63
+ const authorApexCount = authorApexUsers.length;
64
+ if (authorApexCount > 3) {
65
+ findings.push({
66
+ id: 'users-author-apex',
67
+ category: this.category,
68
+ riskLevel: 'MEDIUM',
69
+ title: `${authorApexCount} user(s) have Author Apex permission`,
70
+ detail: 'Author Apex allows users to write and deploy Apex code, which can execute server-side logic with elevated privileges.',
71
+ remediation: 'Author Apex allows code deployment. Limit to developers with a genuine need.',
72
+ affectedItems: authorApexUsers.map(userItem),
73
+ });
74
+ }
75
+ return {
76
+ findings,
77
+ metrics: {
78
+ totalActiveUsers,
79
+ modifyAllDataUsersCount: modifyAllCount,
80
+ viewAllDataUsersCount: viewAllCount,
81
+ },
82
+ };
83
+ }
84
+ }
85
+ //# sourceMappingURL=UsersAndAdminsCheck.js.map
@@ -0,0 +1,3 @@
1
+ import type { SecurityCheck } from './SecurityCheck.js';
2
+ export declare const CHECKS: SecurityCheck[];
3
+ //# sourceMappingURL=registry.d.ts.map
@@ -0,0 +1,49 @@
1
+ import { HealthCheckCheck } from './impl/HealthCheckCheck.js';
2
+ import { UsersAndAdminsCheck } from './impl/UsersAndAdminsCheck.js';
3
+ import { PermissionsCheck } from './impl/PermissionsCheck.js';
4
+ import { LoginSessionCheck } from './impl/LoginSessionCheck.js';
5
+ import { ConnectedAppsCheck } from './impl/ConnectedAppsCheck.js';
6
+ import { SharingModelCheck } from './impl/SharingModelCheck.js';
7
+ import { ApiLimitsCheck } from './impl/ApiLimitsCheck.js';
8
+ import { AuditTrailCheck } from './impl/AuditTrailCheck.js';
9
+ import { InactiveUsersCheck } from './impl/InactiveUsersCheck.js';
10
+ import { PasswordSessionPolicyCheck } from './impl/PasswordSessionPolicyCheck.js';
11
+ import { IpRestrictionsCheck } from './impl/IpRestrictionsCheck.js';
12
+ import { GuestUserAccessCheck } from './impl/GuestUserAccessCheck.js';
13
+ import { RemoteSitesCheck } from './impl/RemoteSitesCheck.js';
14
+ import { NamedCredentialsCheck } from './impl/NamedCredentialsCheck.js';
15
+ import { HardcodedCredentialsCheck } from './impl/HardcodedCredentialsCheck.js';
16
+ import { ApexSharingCheck } from './impl/ApexSharingCheck.js';
17
+ import { FlowsWithoutSharingCheck } from './impl/FlowsWithoutSharingCheck.js';
18
+ import { PublicGroupSharingCheck } from './impl/PublicGroupSharingCheck.js';
19
+ import { FieldLevelSecurityCheck } from './impl/FieldLevelSecurityCheck.js';
20
+ import { ScheduledApexCheck } from './impl/ScheduledApexCheck.js';
21
+ import { CodeSecurityCheck } from './impl/CodeSecurityCheck.js';
22
+ import { CustomSettingsCheck } from './impl/CustomSettingsCheck.js';
23
+ // Order matters: a check's dependsOnCache must be satisfied by a preceding check's populatesCache.
24
+ // CheckEngine.validateCacheOrdering() enforces this at startup.
25
+ export const CHECKS = [
26
+ new HealthCheckCheck(), // writes: healthCheckRisks, healthCloudInstalled
27
+ new UsersAndAdminsCheck(), // writes: metrics (totalActiveUsers, etc.)
28
+ new PermissionsCheck(), // writes: metrics (permissionSetCount, profileCount)
29
+ new LoginSessionCheck(), // writes: metrics (failedLogins30d)
30
+ new ConnectedAppsCheck(), // writes: metrics (connectedAppsCount)
31
+ new SharingModelCheck(), // no deps, no cache
32
+ new ApiLimitsCheck(), // no deps, no cache
33
+ new AuditTrailCheck(), // no deps, no cache
34
+ new InactiveUsersCheck(), // writes: metrics (inactiveUsers90d)
35
+ new PasswordSessionPolicyCheck(), // reads: healthCheckRisks (from HealthCheckCheck)
36
+ new IpRestrictionsCheck(), // no cache deps
37
+ new GuestUserAccessCheck(), // reads: healthCloudInstalled
38
+ new RemoteSitesCheck(), // writes: remoteSiteUrls
39
+ new NamedCredentialsCheck(), // writes: namedCredentialEndpoints
40
+ new HardcodedCredentialsCheck(), // reads: namedCredentialEndpoints, remoteSiteUrls; writes: apexBodies
41
+ new ApexSharingCheck(), // reads: apexBodies
42
+ new FlowsWithoutSharingCheck(), // no deps
43
+ new PublicGroupSharingCheck(), // reads: healthCloudInstalled
44
+ new FieldLevelSecurityCheck(), // no deps
45
+ new ScheduledApexCheck(), // no deps
46
+ new CodeSecurityCheck(), // writes: metrics (apexClassCount, etc.)
47
+ new CustomSettingsCheck(), // no deps
48
+ ];
49
+ //# sourceMappingURL=registry.js.map
@@ -0,0 +1,15 @@
1
+ import { SfCommand } from '@salesforce/sf-plugins-core';
2
+ type CheckRow = {
3
+ id: string;
4
+ name: string;
5
+ category: string;
6
+ description: string;
7
+ };
8
+ export default class AuditListCommand extends SfCommand<CheckRow[]> {
9
+ static summary: string;
10
+ static description: string;
11
+ static examples: string[];
12
+ run(): Promise<CheckRow[]>;
13
+ }
14
+ export {};
15
+ //# sourceMappingURL=list.d.ts.map
@@ -0,0 +1,35 @@
1
+ import { SfCommand } from '@salesforce/sf-plugins-core';
2
+ import { CHECKS } from '../../checks/registry.js';
3
+ export default class AuditListCommand extends SfCommand {
4
+ static summary = 'List all available security checks';
5
+ static description = 'Displays all security checks that will run during sf audit security, with their IDs and descriptions.';
6
+ static examples = [
7
+ '<%= config.bin %> <%= command.id %>',
8
+ ];
9
+ async run() {
10
+ const rows = CHECKS.map((c) => ({
11
+ id: c.id,
12
+ name: c.name,
13
+ category: c.category,
14
+ description: c.description,
15
+ }));
16
+ // Group by category for readability
17
+ const byCategory = new Map();
18
+ for (const row of rows) {
19
+ if (!byCategory.has(row.category))
20
+ byCategory.set(row.category, []);
21
+ byCategory.get(row.category).push(row);
22
+ }
23
+ this.log(`${CHECKS.length} security checks available:\n`);
24
+ for (const [category, checks] of byCategory) {
25
+ this.log(`${category}`);
26
+ this.log('─'.repeat(category.length));
27
+ for (const c of checks) {
28
+ this.log(` ${c.id.padEnd(32)} ${c.description}`);
29
+ }
30
+ this.log('');
31
+ }
32
+ return rows;
33
+ }
34
+ }
35
+ //# sourceMappingURL=list.js.map
@@ -0,0 +1,18 @@
1
+ import { SfCommand } from '@salesforce/sf-plugins-core';
2
+ import type { AuditResult } from '../../findings/AuditResult.js';
3
+ export default class SecurityAuditCommand extends SfCommand<AuditResult> {
4
+ static summary: string;
5
+ static description: string;
6
+ static examples: string[];
7
+ static flags: {
8
+ 'target-org': import("@oclif/core/interfaces").OptionFlag<import("@salesforce/core").Org, import("@oclif/core/interfaces").CustomOptions>;
9
+ format: import("@oclif/core/interfaces").OptionFlag<string, import("@oclif/core/interfaces").CustomOptions>;
10
+ output: import("@oclif/core/interfaces").OptionFlag<string, import("@oclif/core/interfaces").CustomOptions>;
11
+ 'fail-on': import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
12
+ checks: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
13
+ };
14
+ run(): Promise<AuditResult>;
15
+ private printSummary;
16
+ private handleFailOn;
17
+ }
18
+ //# sourceMappingURL=security.d.ts.map
@@ -0,0 +1,117 @@
1
+ import * as fs from 'node:fs';
2
+ import * as path from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+ import { SfCommand, Flags } from '@salesforce/sf-plugins-core';
5
+ import { QueryRegistry } from '../../queries/QueryRegistry.js';
6
+ import { CheckEngine } from '../../checks/CheckEngine.js';
7
+ import { CHECKS } from '../../checks/registry.js';
8
+ import { JsonRenderer } from '../../renderers/JsonRenderer.js';
9
+ import { HtmlRenderer } from '../../renderers/HtmlRenderer.js';
10
+ import { MarkdownRenderer } from '../../renderers/MarkdownRenderer.js';
11
+ import { buildAuditContext, resolveOrgInfo } from '../../lib/wire.js';
12
+ const RENDERERS = {
13
+ html: new HtmlRenderer(),
14
+ md: new MarkdownRenderer(),
15
+ json: new JsonRenderer(),
16
+ };
17
+ export default class SecurityAuditCommand extends SfCommand {
18
+ static summary = 'Run a comprehensive security audit against a Salesforce org';
19
+ static description = 'Runs all security checks against the target org and writes a report file.';
20
+ static examples = [
21
+ '<%= config.bin %> <%= command.id %> --target-org myOrg',
22
+ '<%= config.bin %> <%= command.id %> --target-org myOrg --format json --output ./reports',
23
+ '<%= config.bin %> <%= command.id %> --target-org myOrg --fail-on HIGH',
24
+ ];
25
+ static flags = {
26
+ 'target-org': Flags.requiredOrg(),
27
+ format: Flags.string({
28
+ char: 'f',
29
+ summary: 'Output format(s), comma-separated: html, md, json',
30
+ default: 'html',
31
+ }),
32
+ output: Flags.string({
33
+ char: 'o',
34
+ summary: 'Directory to write the report. Defaults to current directory.',
35
+ default: '.',
36
+ }),
37
+ 'fail-on': Flags.string({
38
+ summary: 'Exit with code 1 if any finding is at or above this severity.',
39
+ options: ['CRITICAL', 'HIGH', 'MEDIUM', 'LOW'],
40
+ }),
41
+ checks: Flags.string({
42
+ summary: 'Comma-separated check IDs to run. Omit to run all checks.',
43
+ helpValue: 'hardcoded-credentials,apex-sharing',
44
+ }),
45
+ };
46
+ async run() {
47
+ const { flags } = await this.parse(SecurityAuditCommand);
48
+ const conn = flags['target-org'].getConnection('62.0');
49
+ // Resolve plugin root from compiled file location (lib/commands/audit/security.js → 3 levels up)
50
+ const pluginRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../..');
51
+ const queries = QueryRegistry.load(pluginRoot);
52
+ const orgInfo = await resolveOrgInfo(conn);
53
+ const ctx = buildAuditContext(conn, queries, orgInfo);
54
+ const checksToRun = flags.checks
55
+ ? (() => {
56
+ const ids = new Set(flags.checks.split(',').map((s) => s.trim()));
57
+ const unknown = [...ids].filter((id) => !CHECKS.some((c) => c.id === id));
58
+ if (unknown.length > 0) {
59
+ this.warn(`Unknown check ID(s): ${unknown.join(', ')}. Run 'sf audit list' to see available checks.`);
60
+ }
61
+ return CHECKS.filter((c) => ids.has(c.id));
62
+ })()
63
+ : CHECKS;
64
+ this.log(`Auditing org: ${orgInfo.name} (${orgInfo.id})`);
65
+ if (flags.checks)
66
+ this.log(`Running ${checksToRun.length} of ${CHECKS.length} checks`);
67
+ const engine = new CheckEngine(checksToRun, ctx);
68
+ const result = await engine.run((current, total, checkName) => {
69
+ this.log(`[${String(current).padStart(2)}/${total}] ${checkName}`);
70
+ });
71
+ const formats = flags.format.split(',').map((f) => f.trim());
72
+ for (const format of formats) {
73
+ const renderer = RENDERERS[format];
74
+ if (!renderer) {
75
+ this.warn(`Unknown format '${format}' — skipping. Valid formats: html, md, json`);
76
+ continue;
77
+ }
78
+ const output = renderer.render(result);
79
+ const filename = `sf-audit-${orgInfo.id}-${Date.now()}${renderer.fileExtension}`;
80
+ const outputPath = path.join(flags.output, filename);
81
+ fs.writeFileSync(outputPath, output, 'utf-8');
82
+ this.log(`\nReport written: ${outputPath}`);
83
+ }
84
+ this.log('');
85
+ this.printSummary(result);
86
+ if (flags['fail-on']) {
87
+ this.handleFailOn(result, flags['fail-on']);
88
+ }
89
+ return result;
90
+ }
91
+ printSummary(result) {
92
+ const levels = ['CRITICAL', 'HIGH', 'MEDIUM', 'LOW'];
93
+ const counts = Object.fromEntries(levels.map((l) => [l, result.findings.filter((f) => f.riskLevel === l).length]));
94
+ this.log('─────────────────────────────');
95
+ this.log(' Audit Summary');
96
+ this.log('─────────────────────────────');
97
+ for (const level of levels) {
98
+ this.log(` ${level.padEnd(10)} ${String(counts[level]).padStart(3)} finding${counts[level] !== 1 ? 's' : ''}`);
99
+ }
100
+ this.log('─────────────────────────────');
101
+ this.log(` Score: ${result.healthScore}/100 Grade: ${result.grade}`);
102
+ this.log('─────────────────────────────');
103
+ }
104
+ handleFailOn(result, failOn) {
105
+ const ORDER = ['CRITICAL', 'HIGH', 'MEDIUM', 'LOW'];
106
+ const threshold = ORDER.indexOf(failOn);
107
+ const violations = result.findings.filter((f) => ORDER.indexOf(f.riskLevel) <= threshold);
108
+ if (violations.length > 0) {
109
+ this.log(`\nFail-on threshold: ${failOn} — ${violations.length} finding${violations.length !== 1 ? 's' : ''} at or above threshold:`);
110
+ for (const f of violations) {
111
+ this.log(` [${f.riskLevel}] ${f.title}`);
112
+ }
113
+ this.exit(1);
114
+ }
115
+ }
116
+ }
117
+ //# sourceMappingURL=security.js.map
@@ -0,0 +1,18 @@
1
+ export interface HealthCheckRisk {
2
+ setting: string;
3
+ riskType: string;
4
+ value: string;
5
+ score: number;
6
+ }
7
+ export interface ApexClassBody {
8
+ name: string;
9
+ body: string;
10
+ }
11
+ export interface AuditCache {
12
+ healthCheckRisks?: HealthCheckRisk[];
13
+ apexBodies?: ApexClassBody[];
14
+ namedCredentialEndpoints?: string[];
15
+ remoteSiteUrls?: string[];
16
+ healthCloudInstalled?: boolean;
17
+ }
18
+ //# sourceMappingURL=AuditCache.d.ts.map
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=AuditCache.js.map
@@ -0,0 +1,15 @@
1
+ import type { SoqlClient } from '../api/SoqlClient.js';
2
+ import type { ToolingClient } from '../api/ToolingClient.js';
3
+ import type { RestClient } from '../api/RestClient.js';
4
+ import type { QueryRegistry } from '../queries/QueryRegistry.js';
5
+ import type { OrgInfo } from './OrgInfo.js';
6
+ import type { AuditCache } from './AuditCache.js';
7
+ export interface AuditContext {
8
+ readonly soql: SoqlClient;
9
+ readonly tooling: ToolingClient;
10
+ readonly rest: RestClient;
11
+ readonly queries: QueryRegistry;
12
+ readonly orgInfo: OrgInfo;
13
+ cache: AuditCache;
14
+ }
15
+ //# sourceMappingURL=AuditContext.d.ts.map
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=AuditContext.js.map
@@ -0,0 +1,9 @@
1
+ export interface OrgInfo {
2
+ id: string;
3
+ name: string;
4
+ type: string;
5
+ isSandbox: boolean;
6
+ instance: string;
7
+ instanceUrl: string;
8
+ }
9
+ //# sourceMappingURL=OrgInfo.d.ts.map
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=OrgInfo.js.map
@@ -0,0 +1,20 @@
1
+ export interface OrgMetrics {
2
+ totalActiveUsers: number;
3
+ modifyAllDataUsersCount: number;
4
+ viewAllDataUsersCount: number;
5
+ permissionSetCount: number;
6
+ profileCount: number;
7
+ apexClassCount: number;
8
+ apexTriggerCount: number;
9
+ codeCoveragePercent: number;
10
+ failedLogins30d: number;
11
+ inactiveUsers90d: number;
12
+ connectedAppsCount: number;
13
+ remoteSitesCount: number;
14
+ insecureRemoteSitesCount: number;
15
+ namedCredentialsCount: number;
16
+ unusedNamedCredentialsCount: number;
17
+ healthCheckScore: number;
18
+ }
19
+ export declare const EMPTY_METRICS: OrgMetrics;
20
+ //# sourceMappingURL=OrgMetrics.d.ts.map
@@ -0,0 +1,20 @@
1
+ // Used by scoring.ts to fill any metrics not populated by checks
2
+ export const EMPTY_METRICS = {
3
+ totalActiveUsers: 0,
4
+ modifyAllDataUsersCount: 0,
5
+ viewAllDataUsersCount: 0,
6
+ permissionSetCount: 0,
7
+ profileCount: 0,
8
+ apexClassCount: 0,
9
+ apexTriggerCount: 0,
10
+ codeCoveragePercent: 0,
11
+ failedLogins30d: 0,
12
+ inactiveUsers90d: 0,
13
+ connectedAppsCount: 0,
14
+ remoteSitesCount: 0,
15
+ insecureRemoteSitesCount: 0,
16
+ namedCredentialsCount: 0,
17
+ unusedNamedCredentialsCount: 0,
18
+ healthCheckScore: 0,
19
+ };
20
+ //# sourceMappingURL=OrgMetrics.js.map
@@ -0,0 +1,15 @@
1
+ import type { Finding } from './Finding.js';
2
+ import type { OrgMetrics } from '../context/OrgMetrics.js';
3
+ export interface AuditResult {
4
+ generatedAt: Date;
5
+ orgId: string;
6
+ orgName: string;
7
+ orgType: string;
8
+ isSandbox: boolean;
9
+ instance: string;
10
+ findings: Finding[];
11
+ metrics: OrgMetrics;
12
+ healthScore: number;
13
+ grade: 'A' | 'B' | 'C' | 'D' | 'F';
14
+ }
15
+ //# sourceMappingURL=AuditResult.d.ts.map
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=AuditResult.js.map
@@ -0,0 +1,16 @@
1
+ import type { RiskLevel } from './RiskLevel.js';
2
+ export interface AffectedItem {
3
+ label: string;
4
+ url?: string;
5
+ note?: string;
6
+ }
7
+ export interface Finding {
8
+ id: string;
9
+ category: string;
10
+ riskLevel: RiskLevel;
11
+ title: string;
12
+ detail: string;
13
+ remediation: string;
14
+ affectedItems?: AffectedItem[];
15
+ }
16
+ //# sourceMappingURL=Finding.d.ts.map
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=Finding.js.map
@@ -0,0 +1,3 @@
1
+ export type RiskLevel = 'CRITICAL' | 'HIGH' | 'MEDIUM' | 'LOW' | 'INFO';
2
+ export declare const RISK_LEVELS: readonly RiskLevel[];
3
+ //# sourceMappingURL=RiskLevel.d.ts.map
@@ -0,0 +1,2 @@
1
+ export const RISK_LEVELS = ['CRITICAL', 'HIGH', 'MEDIUM', 'LOW', 'INFO'];
2
+ //# sourceMappingURL=RiskLevel.js.map
@@ -0,0 +1,6 @@
1
+ import type { Finding } from './Finding.js';
2
+ import type { OrgMetrics } from '../context/OrgMetrics.js';
3
+ import type { AuditResult } from './AuditResult.js';
4
+ import type { AuditContext } from '../context/AuditContext.js';
5
+ export declare function buildAuditResult(ctx: AuditContext, findings: Finding[], metrics: Partial<OrgMetrics>): AuditResult;
6
+ //# sourceMappingURL=scoring.d.ts.map
@@ -0,0 +1,61 @@
1
+ import * as fs from 'node:fs';
2
+ import * as path from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+ import { EMPTY_METRICS } from '../context/OrgMetrics.js';
5
+ const pluginRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..');
6
+ const scoringConfig = JSON.parse(fs.readFileSync(path.join(pluginRoot, 'config', 'scoring.json'), 'utf-8'));
7
+ const RISK_SCORES = scoringConfig.riskScores;
8
+ export function buildAuditResult(ctx, findings, metrics) {
9
+ const totalScore = findings.reduce((sum, f) => sum + RISK_SCORES[f.riskLevel], 0);
10
+ const maxPossible = findings.length * 10;
11
+ const healthScore = Math.max(0, 100 - Math.round((totalScore / Math.max(maxPossible, 1)) * 100));
12
+ const criticalCount = findings.filter((f) => f.riskLevel === 'CRITICAL').length;
13
+ const highCount = findings.filter((f) => f.riskLevel === 'HIGH').length;
14
+ const mediumCount = findings.filter((f) => f.riskLevel === 'MEDIUM').length;
15
+ const totalFindings = findings.length;
16
+ let grade;
17
+ if (criticalCount > 0) {
18
+ grade = 'F';
19
+ }
20
+ else if (healthScore < 40 && totalFindings > 5) {
21
+ // Many findings with very low health score = F
22
+ grade = 'F';
23
+ }
24
+ else if (highCount > 3) {
25
+ grade = 'D';
26
+ }
27
+ else if (highCount > 1) {
28
+ grade = 'C';
29
+ }
30
+ else if (mediumCount > 3) {
31
+ grade = 'B';
32
+ }
33
+ else if (healthScore < 40) {
34
+ grade = 'F';
35
+ }
36
+ else if (healthScore < 55) {
37
+ grade = 'D';
38
+ }
39
+ else if (healthScore < 70) {
40
+ grade = 'C';
41
+ }
42
+ else if (healthScore < 85) {
43
+ grade = 'B';
44
+ }
45
+ else {
46
+ grade = 'A';
47
+ }
48
+ return {
49
+ generatedAt: new Date(),
50
+ orgId: ctx.orgInfo.id,
51
+ orgName: ctx.orgInfo.name,
52
+ orgType: ctx.orgInfo.type,
53
+ isSandbox: ctx.orgInfo.isSandbox,
54
+ instance: ctx.orgInfo.instance,
55
+ findings,
56
+ metrics: { ...EMPTY_METRICS, ...metrics },
57
+ healthScore,
58
+ grade,
59
+ };
60
+ }
61
+ //# sourceMappingURL=scoring.js.map
package/lib/index.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=index.d.ts.map
package/lib/index.js ADDED
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,15 @@
1
+ import type { Connection } from '@salesforce/core';
2
+ import { SoqlClientImpl } from '../api/SoqlClientImpl.js';
3
+ import { ToolingClientImpl } from '../api/ToolingClientImpl.js';
4
+ import { RestClientImpl } from '../api/RestClientImpl.js';
5
+ import type { AuditContext } from '../context/AuditContext.js';
6
+ import type { OrgInfo } from '../context/OrgInfo.js';
7
+ import type { QueryRegistry } from '../queries/QueryRegistry.js';
8
+ export declare function buildApiClients(conn: Connection): {
9
+ soql: SoqlClientImpl;
10
+ tooling: ToolingClientImpl;
11
+ rest: RestClientImpl;
12
+ };
13
+ export declare function resolveOrgInfo(conn: Connection): Promise<OrgInfo>;
14
+ export declare function buildAuditContext(conn: Connection, queries: QueryRegistry, orgInfo: OrgInfo): AuditContext;
15
+ //# sourceMappingURL=wire.d.ts.map
@@ -0,0 +1,36 @@
1
+ import { SoqlClientImpl } from '../api/SoqlClientImpl.js';
2
+ import { ToolingClientImpl } from '../api/ToolingClientImpl.js';
3
+ import { RestClientImpl } from '../api/RestClientImpl.js';
4
+ export function buildApiClients(conn) {
5
+ return {
6
+ soql: new SoqlClientImpl(conn),
7
+ tooling: new ToolingClientImpl(conn),
8
+ rest: new RestClientImpl(conn),
9
+ };
10
+ }
11
+ export async function resolveOrgInfo(conn) {
12
+ const result = await conn.query('SELECT Id, Name, OrganizationType, IsSandbox, InstanceName FROM Organization LIMIT 1');
13
+ const rec = result.records[0];
14
+ if (!rec)
15
+ throw new Error('Could not retrieve Organization record');
16
+ return {
17
+ id: rec.Id,
18
+ name: rec.Name,
19
+ type: rec.OrganizationType,
20
+ isSandbox: rec.IsSandbox,
21
+ instance: rec.InstanceName,
22
+ instanceUrl: conn.instanceUrl,
23
+ };
24
+ }
25
+ export function buildAuditContext(conn, queries, orgInfo) {
26
+ const clients = buildApiClients(conn);
27
+ return {
28
+ soql: clients.soql,
29
+ tooling: clients.tooling,
30
+ rest: clients.rest,
31
+ queries,
32
+ orgInfo,
33
+ cache: {},
34
+ };
35
+ }
36
+ //# sourceMappingURL=wire.js.map