@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
package/README.md ADDED
@@ -0,0 +1,145 @@
1
+ # @cclabsnz/sf-audit
2
+
3
+ A Salesforce CLI (`sf`) plugin that runs a comprehensive security audit against any Salesforce org and produces an HTML, Markdown, or JSON report.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ sf plugins install @cclabsnz/sf-audit
9
+ ```
10
+
11
+ Or, for local development:
12
+
13
+ ```bash
14
+ git clone https://github.com/cclabsnz/sf-audit-plugin.git
15
+ cd cloudcounsel-sf-plugin-audit
16
+ npm install
17
+ npm run build
18
+ sf plugins link .
19
+ ```
20
+
21
+ ## Usage
22
+
23
+ ```bash
24
+ sf audit security --target-org <orgAlias>
25
+ ```
26
+
27
+ This runs all 22 security checks against the target org and writes a report to the current directory.
28
+
29
+ ### Options
30
+
31
+ | Flag | Default | Description |
32
+ |------|---------|-------------|
33
+ | `--target-org` | *(required)* | Org alias or username to audit |
34
+ | `--format` / `-f` | `html` | Output format(s), comma-separated: `html`, `md`, `json` |
35
+ | `--output` / `-o` | `.` | Directory to write the report file |
36
+ | `--fail-on` | — | Exit with code 1 if any finding is at or above this severity: `CRITICAL`, `HIGH`, `MEDIUM`, `LOW` |
37
+
38
+ ### Examples
39
+
40
+ ```bash
41
+ # HTML report (default)
42
+ sf audit security --target-org myOrg
43
+
44
+ # Multiple formats at once
45
+ sf audit security --target-org myOrg --format html,md,json
46
+
47
+ # Write report to a specific directory
48
+ sf audit security --target-org myOrg --output ./reports
49
+
50
+ # Fail CI pipeline on HIGH or CRITICAL findings
51
+ sf audit security --target-org myOrg --fail-on HIGH
52
+ ```
53
+
54
+ The report file is written as `sf-audit-<orgId>-<timestamp>.<ext>` in the output directory (e.g. `sf-audit-00D000000000001-1711234567890.html`).
55
+
56
+ ## What It Checks
57
+
58
+ The audit runs 22 checks across 6 categories:
59
+
60
+ ### Org Health
61
+ | Check | What it looks for |
62
+ |-------|------------------|
63
+ | Health Check | Salesforce Health Check score and individual risk items |
64
+ | Password & Session Policy | Weak password requirements, session timeout, MFA gaps |
65
+
66
+ ### Identity & Access
67
+ | Check | What it looks for |
68
+ |-------|------------------|
69
+ | Users & Admins | Users with system-wide permissions (ModifyAllData, ViewAllData, AuthorApex) |
70
+ | Permissions | Unassigned permission sets, excessive profile count |
71
+ | IP Restrictions | Admins without IP range restrictions, connected apps with relaxed IP policies |
72
+ | Login Sessions | Failed login trends, logins from diverse IPs, recent login activity |
73
+ | Inactive Users | Active licensed users with no login in 90+ days |
74
+
75
+ ### Data Security
76
+ | Check | What it looks for |
77
+ |-------|------------------|
78
+ | Sharing Model | Object-level OWD settings for Account, Contact, Opportunity, Case, Lead |
79
+ | Field Level Security | Sensitive fields (SSN, credit card, tax ID) exposed to broad permission sets |
80
+ | Guest User Access | Object permissions and sharing rules granted to unauthenticated guest users |
81
+ | Public Group Sharing | Sharing rules that grant access to All Internal Users |
82
+
83
+ ### Integration Security
84
+ | Check | What it looks for |
85
+ |-------|------------------|
86
+ | Connected Apps | Apps not restricted to admin-approved users |
87
+ | Remote Sites | Raw remote site registrations without Named Credential coverage |
88
+ | Named Credentials | Named credential inventory |
89
+ | Hardcoded Credentials | Bearer tokens, Basic auth, API keys, and raw callout URLs in Apex code |
90
+
91
+ ### Code & Automation
92
+ | Check | What it looks for |
93
+ |-------|------------------|
94
+ | Apex Sharing | Apex classes using `without sharing` or missing sharing declaration |
95
+ | Flows Without Sharing | Active flows running in system context without sharing enforcement |
96
+ | Scheduled Apex | Active scheduled and batch Apex jobs |
97
+ | Code Security | Org-wide Apex test coverage percentage |
98
+
99
+ ### Platform
100
+ | Check | What it looks for |
101
+ |-------|------------------|
102
+ | API Limits | API request consumption vs. daily/concurrent limits |
103
+ | Audit Trail | Permission changes and Login-As events in the setup audit trail |
104
+ | Custom Settings | Custom settings with credential-like names that may store secrets |
105
+
106
+ ## Scoring
107
+
108
+ Each finding is assigned a risk level with a corresponding weight:
109
+
110
+ | Risk Level | Weight |
111
+ |------------|--------|
112
+ | CRITICAL | 10 |
113
+ | HIGH | 7 |
114
+ | MEDIUM | 4 |
115
+ | LOW | 1 |
116
+ | INFO | 0 |
117
+
118
+ The health score is calculated as `100 - (total weight / max possible weight) * 100`, capped at 0.
119
+
120
+ Weights are configurable in [`config/scoring.json`](config/scoring.json) — no recompile needed.
121
+
122
+ The audit produces a **Health Score** (0–100) and a **Grade** (A–F):
123
+
124
+ | Grade | Criteria |
125
+ |-------|---------|
126
+ | A | Score ≥ 85, no HIGH findings |
127
+ | B | Score ≥ 70, ≤ 1 HIGH finding |
128
+ | C | Score ≥ 55, ≤ 3 HIGH findings |
129
+ | D | Score ≥ 40, no CRITICAL findings |
130
+ | F | Score < 40 or any CRITICAL finding |
131
+
132
+ ## Requirements
133
+
134
+ - Node.js 18+
135
+ - Salesforce CLI (`sf`) v2+
136
+ - The authenticated org user needs at least: Read access to setup objects (User, PermissionSet, ApexClass, Flow, etc.) and access to the Tooling API.
137
+
138
+ ## Development
139
+
140
+ ```bash
141
+ npm run build # compile TypeScript
142
+ npm test # run all tests
143
+ npm run test:unit # unit tests only
144
+ npm run clean # remove compiled output
145
+ ```
@@ -0,0 +1,24 @@
1
+ {
2
+ "activeStandardUsers": {
3
+ "api": "soql",
4
+ "soql": "SELECT Id, Username, ProfileId FROM User WHERE IsActive = true AND UserType = 'Standard'",
5
+ "description": "All active standard users — used by MFA, admin, and inactive checks"
6
+ },
7
+ "profileIpRanges": {
8
+ "api": "soql",
9
+ "soql": "SELECT ProfileId, StartAddress, EndAddress FROM ProfileLoginIpRange",
10
+ "description": "Profile login IP ranges — not queryable in all org configurations",
11
+ "fallbackOnError": true
12
+ },
13
+ "orgLimits": {
14
+ "api": "rest",
15
+ "path": "/limits",
16
+ "description": "Org API governor limits — fetched via ctx.rest.get('/limits')"
17
+ },
18
+ "sobjectDescribe": {
19
+ "api": "rest",
20
+ "path": "/sobjects/{sobjectType}/describe/",
21
+ "description": "SObject describe for OWD/sharing model — called per object via ctx.rest.get(). Used by SharingModelCheck.",
22
+ "fallbackOnError": true
23
+ }
24
+ }
@@ -0,0 +1,28 @@
1
+ {
2
+ "apexClasses": {
3
+ "api": "tooling",
4
+ "soql": "SELECT Id, Name, Body, LengthWithoutComments, NamespacePrefix FROM ApexClass WHERE NamespacePrefix = null",
5
+ "description": "All custom Apex classes — used by HardcodedCredentialsCheck (populates apexBodies cache) and ApexSharingCheck"
6
+ },
7
+ "activeFlows": {
8
+ "api": "tooling",
9
+ "soql": "SELECT Id, MasterLabel, ProcessType, Status, RunInMode FROM Flow WHERE Status = 'Active'",
10
+ "description": "Active Flow versions — used by FlowSecurityCheck"
11
+ },
12
+ "connectedAppsBasic": {
13
+ "api": "tooling",
14
+ "soql": "SELECT Id, Name FROM ConnectedApplication",
15
+ "description": "Connected App ID list — used by IpRestrictionsCheck to fetch per-record Metadata blobs"
16
+ },
17
+ "connectedAppDetail": {
18
+ "api": "rest",
19
+ "path": "tooling/sobjects/ConnectedApplication/{id}/",
20
+ "description": "Per-record Connected App metadata — call via ctx.tooling.getRecord('ConnectedApplication', id).",
21
+ "fallbackOnError": true
22
+ },
23
+ "connectedAppsStandard": {
24
+ "api": "soql",
25
+ "soql": "SELECT Id, Name, Status, StartUrl FROM ConnectedApplication",
26
+ "description": "Connected Apps basic info — used by ConnectedAppsCheck via standard SOQL"
27
+ }
28
+ }
@@ -0,0 +1,9 @@
1
+ {
2
+ "riskScores": {
3
+ "CRITICAL": 10,
4
+ "HIGH": 7,
5
+ "MEDIUM": 4,
6
+ "LOW": 1,
7
+ "INFO": 0
8
+ }
9
+ }
@@ -0,0 +1,6 @@
1
+ export interface ApiError extends Error {
2
+ errorCode: string;
3
+ statusCode: number;
4
+ }
5
+ export declare function isApiError(err: unknown): err is ApiError;
6
+ //# sourceMappingURL=ApiError.d.ts.map
@@ -0,0 +1,6 @@
1
+ export function isApiError(err) {
2
+ return (err instanceof Error &&
3
+ 'errorCode' in err && typeof err.errorCode === 'string' &&
4
+ 'statusCode' in err && typeof err.statusCode === 'number');
5
+ }
6
+ //# sourceMappingURL=ApiError.js.map
@@ -0,0 +1,4 @@
1
+ export interface RestClient {
2
+ get<T>(path: string): Promise<T>;
3
+ }
4
+ //# sourceMappingURL=RestClient.d.ts.map
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=RestClient.js.map
@@ -0,0 +1,8 @@
1
+ import type { Connection } from '@salesforce/core';
2
+ import type { RestClient } from './RestClient.js';
3
+ export declare class RestClientImpl implements RestClient {
4
+ private readonly conn;
5
+ constructor(conn: Connection);
6
+ get<T>(path: string): Promise<T>;
7
+ }
8
+ //# sourceMappingURL=RestClientImpl.d.ts.map
@@ -0,0 +1,12 @@
1
+ export class RestClientImpl {
2
+ conn;
3
+ constructor(conn) {
4
+ this.conn = conn;
5
+ }
6
+ async get(path) {
7
+ const version = this.conn.getApiVersion();
8
+ const normalised = path.startsWith('/') ? path : `/${path}`;
9
+ return this.conn.request(`/services/data/v${version}${normalised}`);
10
+ }
11
+ }
12
+ //# sourceMappingURL=RestClientImpl.js.map
@@ -0,0 +1,10 @@
1
+ export interface QueryResult<T> {
2
+ totalSize: number;
3
+ done: boolean;
4
+ records: T[];
5
+ }
6
+ export interface SoqlClient {
7
+ query<T>(soql: string): Promise<QueryResult<T>>;
8
+ queryAll<T>(soql: string): Promise<T[]>;
9
+ }
10
+ //# sourceMappingURL=SoqlClient.d.ts.map
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=SoqlClient.js.map
@@ -0,0 +1,9 @@
1
+ import type { Connection } from '@salesforce/core';
2
+ import type { QueryResult, SoqlClient } from './SoqlClient.js';
3
+ export declare class SoqlClientImpl implements SoqlClient {
4
+ private readonly anyConn;
5
+ constructor(conn: Connection);
6
+ query<T>(soql: string): Promise<QueryResult<T>>;
7
+ queryAll<T>(soql: string): Promise<T[]>;
8
+ }
9
+ //# sourceMappingURL=SoqlClientImpl.d.ts.map
@@ -0,0 +1,19 @@
1
+ export class SoqlClientImpl {
2
+ anyConn;
3
+ constructor(conn) {
4
+ this.anyConn = conn;
5
+ }
6
+ async query(soql) {
7
+ const result = await this.anyConn.query(soql);
8
+ return {
9
+ totalSize: result.totalSize,
10
+ done: result.done,
11
+ records: (result.records ?? []),
12
+ };
13
+ }
14
+ async queryAll(soql) {
15
+ const result = await this.anyConn.autoFetchQuery(soql);
16
+ return (result.records ?? []);
17
+ }
18
+ }
19
+ //# sourceMappingURL=SoqlClientImpl.js.map
@@ -0,0 +1,5 @@
1
+ export interface ToolingClient {
2
+ query<T>(soql: string): Promise<T[]>;
3
+ getRecord<T>(type: string, id: string): Promise<T>;
4
+ }
5
+ //# sourceMappingURL=ToolingClient.d.ts.map
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=ToolingClient.js.map
@@ -0,0 +1,10 @@
1
+ import type { Connection } from '@salesforce/core';
2
+ import type { ToolingClient } from './ToolingClient.js';
3
+ export declare class ToolingClientImpl implements ToolingClient {
4
+ private readonly conn;
5
+ private readonly tooling;
6
+ constructor(conn: Connection);
7
+ query<T>(soql: string): Promise<T[]>;
8
+ getRecord<T>(type: string, id: string): Promise<T>;
9
+ }
10
+ //# sourceMappingURL=ToolingClientImpl.d.ts.map
@@ -0,0 +1,26 @@
1
+ export class ToolingClientImpl {
2
+ conn;
3
+ tooling;
4
+ constructor(conn) {
5
+ this.conn = conn;
6
+ this.tooling = conn.tooling;
7
+ }
8
+ async query(soql) {
9
+ const result = await this.tooling.query(soql);
10
+ let records = (result.records ?? []);
11
+ let nextUrl = result.nextRecordsUrl;
12
+ // Using conn.request() directly avoids the complex Query<> overload typings
13
+ // on tooling.queryMore — the nextRecordsUrl is a plain string handled cleanly here
14
+ while (nextUrl) {
15
+ const next = await this.conn.request(nextUrl);
16
+ records = records.concat(next.records ?? []);
17
+ nextUrl = next.nextRecordsUrl;
18
+ }
19
+ return records;
20
+ }
21
+ async getRecord(type, id) {
22
+ const version = this.conn.getApiVersion();
23
+ return this.conn.request(`/services/data/v${version}/tooling/sobjects/${type}/${id}/`);
24
+ }
25
+ }
26
+ //# sourceMappingURL=ToolingClientImpl.js.map
@@ -0,0 +1,9 @@
1
+ export type { QueryResult, SoqlClient } from './SoqlClient.js';
2
+ export type { ToolingClient } from './ToolingClient.js';
3
+ export type { RestClient } from './RestClient.js';
4
+ export type { ApiError } from './ApiError.js';
5
+ export { isApiError } from './ApiError.js';
6
+ export { SoqlClientImpl } from './SoqlClientImpl.js';
7
+ export { ToolingClientImpl } from './ToolingClientImpl.js';
8
+ export { RestClientImpl } from './RestClientImpl.js';
9
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,5 @@
1
+ export { isApiError } from './ApiError.js';
2
+ export { SoqlClientImpl } from './SoqlClientImpl.js';
3
+ export { ToolingClientImpl } from './ToolingClientImpl.js';
4
+ export { RestClientImpl } from './RestClientImpl.js';
5
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,11 @@
1
+ import type { SecurityCheck } from './SecurityCheck.js';
2
+ import type { AuditContext } from '../context/AuditContext.js';
3
+ import type { AuditResult } from '../findings/AuditResult.js';
4
+ export declare class CheckEngine {
5
+ private readonly checks;
6
+ private readonly ctx;
7
+ constructor(checks: SecurityCheck[], ctx: AuditContext);
8
+ run(onProgress?: (current: number, total: number, checkName: string) => void): Promise<AuditResult>;
9
+ private validateCacheOrdering;
10
+ }
11
+ //# sourceMappingURL=CheckEngine.d.ts.map
@@ -0,0 +1,56 @@
1
+ import { buildAuditResult } from '../findings/scoring.js';
2
+ function buildErrorFinding(check, err) {
3
+ const msg = err instanceof Error ? err.message : String(err);
4
+ return {
5
+ id: `${check.id}-error`,
6
+ category: check.category,
7
+ riskLevel: 'INFO',
8
+ title: `${check.name}: check failed`,
9
+ detail: `This check encountered an error and could not complete: ${msg}`,
10
+ remediation: 'Review the error message and verify the running user has the required permissions.',
11
+ };
12
+ }
13
+ export class CheckEngine {
14
+ checks;
15
+ ctx;
16
+ constructor(checks, ctx) {
17
+ this.checks = checks;
18
+ this.ctx = ctx;
19
+ this.validateCacheOrdering();
20
+ }
21
+ async run(onProgress) {
22
+ const findings = [];
23
+ let metrics = {};
24
+ const total = this.checks.length;
25
+ for (let i = 0; i < total; i++) {
26
+ const check = this.checks[i];
27
+ onProgress?.(i + 1, total, check.name);
28
+ try {
29
+ const result = await check.run(this.ctx);
30
+ findings.push(...result.findings);
31
+ if (result.metrics) {
32
+ metrics = { ...metrics, ...result.metrics };
33
+ }
34
+ }
35
+ catch (err) {
36
+ findings.push(buildErrorFinding(check, err));
37
+ }
38
+ }
39
+ return buildAuditResult(this.ctx, findings, metrics);
40
+ }
41
+ validateCacheOrdering() {
42
+ const populated = new Set();
43
+ for (const check of this.checks) {
44
+ for (const key of check.dependsOnCache ?? []) {
45
+ if (!populated.has(key)) {
46
+ throw new Error(`Check '${check.name}' depends on cache key '${key}' ` +
47
+ `but no preceding check declares it in populatesCache.`);
48
+ }
49
+ }
50
+ for (const key of check.populatesCache ?? []) {
51
+ populated.add(key);
52
+ }
53
+ }
54
+ }
55
+ }
56
+ //# sourceMappingURL=CheckEngine.js.map
@@ -0,0 +1,18 @@
1
+ import type { AuditContext } from '../context/AuditContext.js';
2
+ import type { Finding } from '../findings/Finding.js';
3
+ import type { AuditCache } from '../context/AuditCache.js';
4
+ import type { OrgMetrics } from '../context/OrgMetrics.js';
5
+ export interface CheckResult {
6
+ findings: Finding[];
7
+ metrics?: Partial<OrgMetrics>;
8
+ }
9
+ export interface SecurityCheck {
10
+ readonly id: string;
11
+ readonly name: string;
12
+ readonly category: string;
13
+ readonly description: string;
14
+ readonly dependsOnCache?: ReadonlyArray<keyof AuditCache>;
15
+ readonly populatesCache?: ReadonlyArray<keyof AuditCache>;
16
+ run(ctx: AuditContext): Promise<CheckResult>;
17
+ }
18
+ //# sourceMappingURL=SecurityCheck.d.ts.map
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=SecurityCheck.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 ApexSharingCheck implements SecurityCheck {
4
+ readonly id = "apex-sharing";
5
+ readonly name = "Apex Sharing Declarations";
6
+ readonly category = "Code Security";
7
+ readonly description = "Classifies Apex classes by sharing declaration (with sharing, without sharing, inherited, omitted)";
8
+ readonly dependsOnCache: readonly ["apexBodies"];
9
+ run(ctx: AuditContext): Promise<CheckResult>;
10
+ }
11
+ //# sourceMappingURL=ApexSharingCheck.d.ts.map
@@ -0,0 +1,108 @@
1
+ const INHERITED_SHARING = /\binherited\s+sharing\b/i;
2
+ const WITHOUT_SHARING = /\bwithout\s+sharing\b/i;
3
+ const WITH_SHARING = /\bwith\s+sharing\b/i;
4
+ const CLASS_PATTERN = /\bclass\s+\w+/i;
5
+ const IS_TEST_CLASS = /@IsTest\b/i;
6
+ function getSharingDeclaration(body) {
7
+ if (!CLASS_PATTERN.test(body)) {
8
+ return null; // Not a class — skip interfaces, enums, etc.
9
+ }
10
+ if (WITH_SHARING.test(body))
11
+ return 'with';
12
+ if (WITHOUT_SHARING.test(body))
13
+ return 'without';
14
+ if (INHERITED_SHARING.test(body))
15
+ return 'inherited';
16
+ return 'none';
17
+ }
18
+ export class ApexSharingCheck {
19
+ id = 'apex-sharing';
20
+ name = 'Apex Sharing Declarations';
21
+ category = 'Code Security';
22
+ description = 'Classifies Apex classes by sharing declaration (with sharing, without sharing, inherited, omitted)';
23
+ dependsOnCache = ['apexBodies'];
24
+ async run(ctx) {
25
+ const findings = [];
26
+ const baseUrl = ctx.orgInfo.instanceUrl;
27
+ const apexClassesUrl = `${baseUrl}/lightning/setup/ApexClasses/page`;
28
+ let apexBodies = ctx.cache.apexBodies;
29
+ if (!apexBodies) {
30
+ // Fall back to querying if cache not populated
31
+ const records = await ctx.tooling.query('SELECT Id, Name, Body, NamespacePrefix FROM ApexClass WHERE NamespacePrefix = null');
32
+ apexBodies = records.map((r) => ({ name: r.Name, body: r.Body }));
33
+ }
34
+ const withSharingClasses = [];
35
+ const withoutSharingClasses = [];
36
+ const inheritedSharingClasses = [];
37
+ const noDeclarationClasses = [];
38
+ for (const apexClass of apexBodies) {
39
+ const body = apexClass.body ?? '';
40
+ // Test classes run as sysadmin — sharing declarations are not applicable
41
+ if (IS_TEST_CLASS.test(body))
42
+ continue;
43
+ const declaration = getSharingDeclaration(body);
44
+ if (declaration === null)
45
+ continue; // Not a class definition
46
+ switch (declaration) {
47
+ case 'with':
48
+ withSharingClasses.push(apexClass.name);
49
+ break;
50
+ case 'without':
51
+ withoutSharingClasses.push(apexClass.name);
52
+ break;
53
+ case 'inherited':
54
+ inheritedSharingClasses.push(apexClass.name);
55
+ break;
56
+ case 'none':
57
+ noDeclarationClasses.push(apexClass.name);
58
+ break;
59
+ }
60
+ }
61
+ const total = withSharingClasses.length +
62
+ withoutSharingClasses.length +
63
+ inheritedSharingClasses.length +
64
+ noDeclarationClasses.length;
65
+ if (withoutSharingClasses.length > 0) {
66
+ const count = withoutSharingClasses.length;
67
+ findings.push({
68
+ id: 'apex-without-sharing',
69
+ category: this.category,
70
+ riskLevel: 'HIGH',
71
+ title: `${count} Apex class(es) explicitly use "without sharing"`,
72
+ detail: "Classes declared \"without sharing\" ignore the running user's record access and can access all data in the org.",
73
+ remediation: 'Replace "without sharing" with "with sharing" or "inherited sharing" unless there is a documented business requirement.',
74
+ affectedItems: withoutSharingClasses.map((name) => ({
75
+ label: name,
76
+ url: apexClassesUrl,
77
+ note: 'Change to "with sharing" or "inherited sharing" and test thoroughly',
78
+ })),
79
+ });
80
+ }
81
+ if (noDeclarationClasses.length > 0) {
82
+ const count = noDeclarationClasses.length;
83
+ findings.push({
84
+ id: 'apex-no-sharing-declaration',
85
+ category: this.category,
86
+ riskLevel: 'MEDIUM',
87
+ title: `${count} Apex class(es) have no sharing declaration`,
88
+ detail: "Apex classes without a sharing declaration default to \"without sharing\" behavior when called from a context that doesn't enforce sharing.",
89
+ remediation: 'Add explicit sharing declarations to all Apex classes. Use "with sharing" as the default, or "inherited sharing" for utility classes.',
90
+ affectedItems: noDeclarationClasses.slice(0, 20).map((name) => ({
91
+ label: name,
92
+ url: apexClassesUrl,
93
+ note: 'Add "with sharing" or "inherited sharing" declaration',
94
+ })),
95
+ });
96
+ }
97
+ findings.push({
98
+ id: 'apex-sharing-summary',
99
+ category: this.category,
100
+ riskLevel: 'INFO',
101
+ title: `Apex sharing analysis: ${withSharingClasses.length} with sharing, ${inheritedSharingClasses.length} inherited, ${withoutSharingClasses.length} without sharing, ${noDeclarationClasses.length} no declaration (${total} total)`,
102
+ detail: `Summary of sharing declarations across ${total} custom Apex classes.`,
103
+ remediation: 'Aim for all classes to use "with sharing" or "inherited sharing".',
104
+ });
105
+ return { findings };
106
+ }
107
+ }
108
+ //# sourceMappingURL=ApexSharingCheck.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 ApiLimitsCheck implements SecurityCheck {
4
+ readonly id = "api-limits";
5
+ readonly name = "API and Resource Limits";
6
+ readonly category = "Resource Management";
7
+ readonly description = "Monitors API request consumption against daily and concurrent limits";
8
+ run(ctx: AuditContext): Promise<CheckResult>;
9
+ }
10
+ //# sourceMappingURL=ApiLimitsCheck.d.ts.map