@cclabsnz/sf-audit 1.3.0 → 1.4.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 (64) hide show
  1. package/README.md +101 -5
  2. package/lib/api/MetadataClient.d.ts +4 -0
  3. package/lib/api/MetadataClient.js +2 -0
  4. package/lib/api/MetadataClientImpl.d.ts +8 -0
  5. package/lib/api/MetadataClientImpl.js +22 -0
  6. package/lib/api/RestClient.d.ts +1 -0
  7. package/lib/api/RestClientImpl.d.ts +1 -0
  8. package/lib/api/RestClientImpl.js +6 -0
  9. package/lib/chains/CapabilityRegistry.js +19 -0
  10. package/lib/chains/namedChains.js +22 -0
  11. package/lib/checks/eventLogAccess.d.ts +14 -0
  12. package/lib/checks/eventLogAccess.js +33 -0
  13. package/lib/checks/impl/AuthProvidersCheck.d.ts +17 -0
  14. package/lib/checks/impl/AuthProvidersCheck.js +88 -0
  15. package/lib/checks/impl/ClassicSitesCheck.d.ts +17 -0
  16. package/lib/checks/impl/ClassicSitesCheck.js +65 -0
  17. package/lib/checks/impl/DataExportAccessCheck.d.ts +19 -0
  18. package/lib/checks/impl/DataExportAccessCheck.js +79 -0
  19. package/lib/checks/impl/EncryptionCoverageCheck.d.ts +19 -0
  20. package/lib/checks/impl/EncryptionCoverageCheck.js +108 -0
  21. package/lib/checks/impl/EventMonitoringCheck.js +8 -5
  22. package/lib/checks/impl/ExperienceCspCheck.d.ts +18 -0
  23. package/lib/checks/impl/ExperienceCspCheck.js +57 -0
  24. package/lib/checks/impl/ExternalCredentialsCheck.d.ts +17 -0
  25. package/lib/checks/impl/ExternalCredentialsCheck.js +74 -0
  26. package/lib/checks/impl/GuestApiAccessCheck.d.ts +19 -0
  27. package/lib/checks/impl/GuestApiAccessCheck.js +113 -0
  28. package/lib/checks/impl/GuestObjectExposureCheck.d.ts +44 -0
  29. package/lib/checks/impl/GuestObjectExposureCheck.js +241 -0
  30. package/lib/checks/impl/GuestRecordAccessPolicyCheck.d.ts +34 -0
  31. package/lib/checks/impl/GuestRecordAccessPolicyCheck.js +120 -0
  32. package/lib/checks/impl/GuestSiteOptionsCheck.d.ts +18 -0
  33. package/lib/checks/impl/GuestSiteOptionsCheck.js +92 -0
  34. package/lib/checks/impl/GuestTrafficAnomalyCheck.d.ts +23 -0
  35. package/lib/checks/impl/GuestTrafficAnomalyCheck.js +343 -0
  36. package/lib/checks/impl/LoginAccessPolicyCheck.d.ts +26 -0
  37. package/lib/checks/impl/LoginAccessPolicyCheck.js +117 -0
  38. package/lib/checks/impl/LoginAnomalyCheck.d.ts +17 -0
  39. package/lib/checks/impl/LoginAnomalyCheck.js +98 -0
  40. package/lib/checks/impl/SandboxDataMaskingCheck.d.ts +17 -0
  41. package/lib/checks/impl/SandboxDataMaskingCheck.js +85 -0
  42. package/lib/checks/impl/SessionHardeningCheck.d.ts +21 -0
  43. package/lib/checks/impl/SessionHardeningCheck.js +134 -0
  44. package/lib/checks/impl/ThreatDetectionCheck.d.ts +17 -0
  45. package/lib/checks/impl/ThreatDetectionCheck.js +91 -0
  46. package/lib/checks/registry.js +33 -0
  47. package/lib/commands/audit/diff.js +9 -5
  48. package/lib/commands/audit/events/pull.d.ts +17 -0
  49. package/lib/commands/audit/events/pull.js +88 -0
  50. package/lib/commands/audit/security.d.ts +4 -0
  51. package/lib/commands/audit/security.js +40 -16
  52. package/lib/compliance/mapping.js +27 -7
  53. package/lib/context/AuditCache.d.ts +3 -0
  54. package/lib/context/AuditContext.d.ts +2 -0
  55. package/lib/events/EventBaselineStore.d.ts +16 -0
  56. package/lib/events/EventBaselineStore.js +55 -0
  57. package/lib/events/eventLogQuery.d.ts +21 -0
  58. package/lib/events/eventLogQuery.js +34 -0
  59. package/lib/events/pullEventLogs.d.ts +51 -0
  60. package/lib/events/pullEventLogs.js +79 -0
  61. package/lib/findings/CheckMeta.js +16 -0
  62. package/lib/lib/wire.d.ts +2 -0
  63. package/lib/lib/wire.js +3 -0
  64. package/package.json +13 -2
@@ -0,0 +1,85 @@
1
+ // Common PII-bearing fields to probe for populated, real-looking data. A count
2
+ // query is cheap and non-invasive (no values are read).
3
+ const PII_PROBES = [
4
+ { object: 'Contact', where: 'Email != null' },
5
+ { object: 'Lead', where: 'Email != null' },
6
+ { object: 'Contact', where: 'Phone != null' },
7
+ ];
8
+ /**
9
+ * Advisory for sandboxes: production data copied into a sandbox and left unmasked
10
+ * spreads real PII/PHI into a lower-trust environment with weaker controls and
11
+ * broader developer access. This check runs only in sandboxes and looks for
12
+ * populated PII fields as a proxy for "prod data present" — it cannot prove
13
+ * whether Data Mask has run, so it raises an advisory to confirm masking.
14
+ */
15
+ export class SandboxDataMaskingCheck {
16
+ id = 'sandbox-data-masking';
17
+ name = 'Sandbox Data Masking';
18
+ category = 'Data Security';
19
+ description = 'In sandboxes, flags the presence of populated PII fields (likely unmasked production data) and advises running Salesforce Data Mask';
20
+ async run(ctx) {
21
+ const findings = [];
22
+ const baseUrl = ctx.orgInfo.instanceUrl;
23
+ if (!ctx.orgInfo.isSandbox) {
24
+ findings.push({
25
+ id: 'sandbox-data-masking-na',
26
+ category: this.category,
27
+ riskLevel: 'LOW',
28
+ passed: true,
29
+ title: 'Not a sandbox — data masking not applicable',
30
+ detail: 'This org is a production org, so sandbox data-masking does not apply here.',
31
+ remediation: 'Apply Data Mask to sandboxes seeded from this production org so PII/PHI is not copied in the clear.',
32
+ });
33
+ return { findings };
34
+ }
35
+ let probed = 0;
36
+ let populated = 0;
37
+ for (const p of PII_PROBES) {
38
+ try {
39
+ const r = await ctx.soql.query(`SELECT COUNT() FROM ${p.object} WHERE ${p.where}`);
40
+ probed++;
41
+ if (r.totalSize > 0)
42
+ populated++;
43
+ }
44
+ catch {
45
+ // object not present / not accessible — skip this probe
46
+ }
47
+ }
48
+ if (probed === 0) {
49
+ findings.push({
50
+ id: 'sandbox-data-masking-inconclusive',
51
+ category: this.category,
52
+ riskLevel: 'INFO',
53
+ inconclusive: true,
54
+ title: 'Could not probe for PII data in this sandbox',
55
+ detail: 'None of the PII probe objects were queryable, so the presence of unmasked production data could not be assessed.',
56
+ remediation: 'Confirm Data Mask has been run on this sandbox (Setup → Data Mask), independent of this check.',
57
+ });
58
+ return { findings };
59
+ }
60
+ if (populated > 0) {
61
+ findings.push({
62
+ id: 'sandbox-data-masking-pii-present',
63
+ category: this.category,
64
+ riskLevel: 'MEDIUM',
65
+ title: 'Sandbox contains populated PII fields — confirm Data Mask has run',
66
+ detail: 'This is a sandbox and PII-bearing fields (e.g. Contact/Lead email or phone) are populated, which is the footprint of a production copy. If Data Mask has not been run, real PII/PHI is sitting in a lower-trust environment with broader developer/admin access and weaker monitoring. This check cannot confirm whether masking was applied — only that sensitive fields hold data.',
67
+ remediation: 'Run Salesforce Data Mask on this sandbox (Setup → Data Mask) after each refresh, masking PII/PHI fields. Restrict sandbox access and treat sandbox data with the same controls as production until masking is confirmed.',
68
+ affectedItems: [{ label: 'Data Mask', url: `${baseUrl}/lightning/setup/DataMask/home` }],
69
+ });
70
+ }
71
+ else {
72
+ findings.push({
73
+ id: 'sandbox-data-masking-ok',
74
+ category: this.category,
75
+ riskLevel: 'LOW',
76
+ passed: true,
77
+ title: 'Sandbox shows no populated PII in the probed fields',
78
+ detail: `Probed ${probed} PII field(s); none were populated, consistent with a masked or data-free sandbox.`,
79
+ remediation: 'Continue running Data Mask after each sandbox refresh.',
80
+ });
81
+ }
82
+ return { findings };
83
+ }
84
+ }
85
+ //# sourceMappingURL=SandboxDataMaskingCheck.js.map
@@ -0,0 +1,21 @@
1
+ import type { AuditContext } from '../../context/AuditContext.js';
2
+ import type { SecurityCheck, CheckResult } from '../SecurityCheck.js';
3
+ /**
4
+ * Re-slices the Health Check risk set (populated by HealthCheckCheck, so no extra
5
+ * API call) to the session / clickjack / CSRF / XSS hardening domain and gives
6
+ * targeted, per-setting remediation. HealthCheckCheck reports a flat count; this
7
+ * check tells you *which* browser-session protections deviate from Salesforce's
8
+ * baseline and how to fix each — the "enable secure config" surface.
9
+ */
10
+ export declare class SessionHardeningCheck implements SecurityCheck {
11
+ readonly id = "session-hardening";
12
+ readonly name = "Session & Clickjack Hardening";
13
+ readonly category = "Session Security";
14
+ readonly description = "Grades clickjack, CSRF, session-lock, and XSS-protection settings from Health Check and gives per-setting remediation";
15
+ readonly dependsOnCache: readonly ["healthCheckRisks"];
16
+ run(ctx: AuditContext): Promise<CheckResult>;
17
+ private static readonly FLAGS;
18
+ /** Authoritative evaluation from SecuritySettings metadata; null → fall back to the cache path. */
19
+ private evaluateFromMetadata;
20
+ }
21
+ //# sourceMappingURL=SessionHardeningCheck.d.ts.map
@@ -0,0 +1,134 @@
1
+ // Health Check settings that belong to the session / framing / request-forgery
2
+ // hardening domain. Matched case-insensitively against the risk `setting` name.
3
+ const SESSION_KEYWORDS = [
4
+ 'clickjack', 'frame', 'csrf', 'cross-site request', 'session', 'timeout',
5
+ 'xss', 'content sniffing', 'content-type', 'referrer', 'httponly', 'lock sessions',
6
+ 'cache', 'mixed content', 'browser', 'redirect',
7
+ ];
8
+ /**
9
+ * Re-slices the Health Check risk set (populated by HealthCheckCheck, so no extra
10
+ * API call) to the session / clickjack / CSRF / XSS hardening domain and gives
11
+ * targeted, per-setting remediation. HealthCheckCheck reports a flat count; this
12
+ * check tells you *which* browser-session protections deviate from Salesforce's
13
+ * baseline and how to fix each — the "enable secure config" surface.
14
+ */
15
+ export class SessionHardeningCheck {
16
+ id = 'session-hardening';
17
+ name = 'Session & Clickjack Hardening';
18
+ category = 'Session Security';
19
+ description = 'Grades clickjack, CSRF, session-lock, and XSS-protection settings from Health Check and gives per-setting remediation';
20
+ dependsOnCache = ['healthCheckRisks'];
21
+ async run(ctx) {
22
+ const findings = [];
23
+ const setupUrl = `${ctx.orgInfo.instanceUrl}/lightning/setup/SessionSettings/home`;
24
+ // Prefer authoritative SecuritySettings (Metadata API) — it reports the actual
25
+ // values, not just Health Check deviations. Fall back to the Health Check risk
26
+ // cache when no Metadata client is available or the shape is unexpected.
27
+ const fromMeta = await this.evaluateFromMetadata(ctx, setupUrl);
28
+ if (fromMeta) {
29
+ findings.push(fromMeta);
30
+ return { findings };
31
+ }
32
+ const risks = ctx.cache.healthCheckRisks;
33
+ if (risks === undefined) {
34
+ findings.push({
35
+ id: 'session-hardening-inconclusive',
36
+ category: this.category,
37
+ riskLevel: 'INFO',
38
+ inconclusive: true,
39
+ title: 'Health Check risks unavailable — session hardening not evaluated',
40
+ detail: 'The Security Health Check risk data was not collected (Health Check check did not run or was inaccessible), so session/clickjack settings could not be graded.',
41
+ remediation: 'Ensure the audit user can read SecurityHealthCheckRisks (View Health Check), then re-run.',
42
+ });
43
+ return { findings };
44
+ }
45
+ const matched = risks.filter((r) => {
46
+ const s = (r.setting ?? '').toLowerCase();
47
+ return SESSION_KEYWORDS.some((k) => s.includes(k));
48
+ });
49
+ if (matched.length === 0) {
50
+ findings.push({
51
+ id: 'session-hardening-ok',
52
+ category: this.category,
53
+ riskLevel: 'LOW',
54
+ passed: true,
55
+ title: 'No session/clickjack/CSRF settings flagged by Health Check',
56
+ detail: 'None of the browser-session hardening settings (clickjack protection, CSRF protection, session lock, XSS protection) deviate from the Salesforce baseline in Health Check.',
57
+ remediation: 'Keep clickjack protection at the highest level, CSRF protection on for GET and POST, and "Lock sessions to the IP address from which they originated" enabled where feasible.',
58
+ });
59
+ return { findings };
60
+ }
61
+ const high = matched.filter((r) => r.riskType === 'HIGH_RISK');
62
+ const level = high.length > 0 ? 'HIGH' : 'MEDIUM';
63
+ findings.push({
64
+ id: 'session-hardening-risks',
65
+ category: this.category,
66
+ riskLevel: level,
67
+ title: `${matched.length} session/clickjack/CSRF setting(s) deviate from the security baseline`,
68
+ detail: 'These browser-session hardening settings differ from Salesforce\'s recommended values. Weak framing, CSRF, session-lock, or XSS-protection settings enable clickjacking, cross-site request forgery, session hijacking, and reflected-XSS attacks against authenticated users.',
69
+ remediation: 'In Setup → Session Settings (and Session Security Levels), align each flagged setting to the recommended value: highest clickjack protection for all pages, CSRF protection on GET and POST, "Lock sessions to the IP address" and "to the domain", content-sniffing and XSS protection on, and warnings on redirects to external URLs.',
70
+ affectedItems: matched.slice(0, 30).map((r) => ({
71
+ label: `${r.setting} = ${r.value} (${r.riskType})`,
72
+ url: setupUrl,
73
+ })),
74
+ });
75
+ return { findings };
76
+ }
77
+ // SecuritySettings.sessionSettings flags that should be ON (true = protected).
78
+ static FLAGS = [
79
+ { key: 'enableClickjackNonsetupUser', label: 'Clickjack protection (customer Visualforce pages)', sev: 'HIGH' },
80
+ { key: 'enableClickjackNonsetupSFDC', label: 'Clickjack protection (Salesforce pages)', sev: 'HIGH' },
81
+ { key: 'enableXssProtection', label: 'XSS protection', sev: 'HIGH' },
82
+ { key: 'enableCSRFOnGet', label: 'CSRF protection on GET requests', sev: 'MEDIUM' },
83
+ { key: 'enableCSRFOnPost', label: 'CSRF protection on POST requests', sev: 'MEDIUM' },
84
+ { key: 'enableContentSniffingProtection', label: 'Content-sniffing protection', sev: 'MEDIUM' },
85
+ ];
86
+ /** Authoritative evaluation from SecuritySettings metadata; null → fall back to the cache path. */
87
+ async evaluateFromMetadata(ctx, setupUrl) {
88
+ if (!ctx.metadata)
89
+ return null;
90
+ let ss;
91
+ try {
92
+ ss = await ctx.metadata.read('SecuritySettings', 'Security');
93
+ }
94
+ catch {
95
+ return null;
96
+ }
97
+ const s = ss?.sessionSettings;
98
+ if (!s || typeof s !== 'object')
99
+ return null;
100
+ const gaps = [];
101
+ let sawAny = false;
102
+ for (const f of SessionHardeningCheck.FLAGS) {
103
+ const v = s[f.key];
104
+ if (typeof v === 'boolean') {
105
+ sawAny = true;
106
+ if (!v)
107
+ gaps.push({ label: f.label, sev: f.sev });
108
+ }
109
+ }
110
+ if (!sawAny)
111
+ return null; // unexpected shape — defer to the Health Check cache path
112
+ if (gaps.length === 0) {
113
+ return {
114
+ id: 'session-hardening-ok',
115
+ category: this.category,
116
+ riskLevel: 'LOW',
117
+ passed: true,
118
+ title: 'Clickjack/CSRF/XSS protections confirmed enabled',
119
+ detail: 'SecuritySettings confirms clickjack, CSRF, XSS, and content-sniffing protections are enabled.',
120
+ remediation: 'Also confirm "Lock sessions to the IP address from which they originated" and a short session timeout in Setup → Session Settings.',
121
+ };
122
+ }
123
+ return {
124
+ id: 'session-hardening-risks',
125
+ category: this.category,
126
+ riskLevel: gaps.some((g) => g.sev === 'HIGH') ? 'HIGH' : 'MEDIUM',
127
+ title: `${gaps.length} browser-session protection(s) are disabled`,
128
+ detail: 'SecuritySettings reports these session/framing protections are OFF. Disabled clickjack, CSRF, XSS, or content-sniffing protection enables clickjacking, cross-site request forgery, reflected XSS, and MIME-confusion attacks against authenticated users.',
129
+ remediation: 'In Setup → Session Settings, enable the disabled protections: highest clickjack protection for all page types, CSRF protection on GET and POST, XSS protection, and content-sniffing protection. Also enable "Lock sessions to the IP address" where feasible.',
130
+ affectedItems: gaps.map((g) => ({ label: `${g.label}: OFF (${g.sev})`, url: setupUrl })),
131
+ };
132
+ }
133
+ }
134
+ //# sourceMappingURL=SessionHardeningCheck.js.map
@@ -0,0 +1,17 @@
1
+ import type { AuditContext } from '../../context/AuditContext.js';
2
+ import type { SecurityCheck, CheckResult } from '../SecurityCheck.js';
3
+ /**
4
+ * Verifies that Threat Detection event storage (especially Guest User Anomaly) is
5
+ * available and retaining events. An empty/unavailable store means the one control
6
+ * that would flag anomalous guest bulk-reads is blind, so a "no anomalies" result
7
+ * is meaningless. This complements TransactionSecurityPolicyCheck (which looks at
8
+ * policies, not whether anomaly events are actually stored).
9
+ */
10
+ export declare class ThreatDetectionCheck implements SecurityCheck {
11
+ readonly id = "threat-detection";
12
+ readonly name = "Threat Detection Event Storage";
13
+ readonly category = "Monitoring";
14
+ readonly description = "Verifies Real-Time Event Monitoring Threat Detection storage (Guest User Anomaly and siblings) is enabled and retaining events to detect anomalous guest bulk-access";
15
+ run(ctx: AuditContext): Promise<CheckResult>;
16
+ }
17
+ //# sourceMappingURL=ThreatDetectionCheck.d.ts.map
@@ -0,0 +1,91 @@
1
+ // Real-Time Event Monitoring Threat Detection stores. GuestUserAnomalyEventStore is
2
+ // the one that flags anomalous guest bulk-access (the vector in guest-data leaks).
3
+ const ANOMALY_STORES = [
4
+ 'GuestUserAnomalyEventStore',
5
+ 'ApiAnomalyEventStore',
6
+ 'LoginAnomalyEventStore',
7
+ 'SessionHijackingEventStore',
8
+ 'CredentialStuffingEventStore',
9
+ 'ReportAnomalyEventStore',
10
+ ];
11
+ /**
12
+ * Verifies that Threat Detection event storage (especially Guest User Anomaly) is
13
+ * available and retaining events. An empty/unavailable store means the one control
14
+ * that would flag anomalous guest bulk-reads is blind, so a "no anomalies" result
15
+ * is meaningless. This complements TransactionSecurityPolicyCheck (which looks at
16
+ * policies, not whether anomaly events are actually stored).
17
+ */
18
+ export class ThreatDetectionCheck {
19
+ id = 'threat-detection';
20
+ name = 'Threat Detection Event Storage';
21
+ category = 'Monitoring';
22
+ description = 'Verifies Real-Time Event Monitoring Threat Detection storage (Guest User Anomaly and siblings) is enabled and retaining events to detect anomalous guest bulk-access';
23
+ async run(ctx) {
24
+ const findings = [];
25
+ const baseUrl = ctx.orgInfo.instanceUrl;
26
+ const setupUrl = `${baseUrl}/lightning/setup/EventManager/home`;
27
+ const queryable = [];
28
+ const withData = [];
29
+ let guestStoreQueryable = false;
30
+ for (const store of ANOMALY_STORES) {
31
+ try {
32
+ const rows = await ctx.soql.queryAll(`SELECT EventDate FROM ${store} WHERE EventDate = LAST_N_DAYS:180 LIMIT 1`);
33
+ queryable.push(store);
34
+ if (store === 'GuestUserAnomalyEventStore')
35
+ guestStoreQueryable = true;
36
+ if (rows.length > 0)
37
+ withData.push(store);
38
+ }
39
+ catch {
40
+ // Store not present / not queryable (Threat Detection not licensed or storage off).
41
+ }
42
+ }
43
+ if (queryable.length === 0) {
44
+ findings.push({
45
+ id: 'threat-detection-unavailable',
46
+ category: this.category,
47
+ riskLevel: 'MEDIUM',
48
+ title: 'Threat Detection event storage is not available',
49
+ detail: 'No Threat Detection anomaly store (e.g. GuestUserAnomalyEventStore) is queryable. Real-Time Event Monitoring / Threat Detection is not licensed or its storage is disabled, so anomalous guest bulk-access cannot be detected or investigated.',
50
+ remediation: 'Enable Real-Time Event Monitoring and turn on storage for the Threat Detection events (Setup > Event Manager), especially Guest User Anomaly. Add alerting/automation on these events.',
51
+ affectedItems: [{ label: 'Event Manager', url: setupUrl, note: 'Enable Threat Detection event storage' }],
52
+ });
53
+ return { findings };
54
+ }
55
+ if (!guestStoreQueryable) {
56
+ findings.push({
57
+ id: 'threat-detection-guest-anomaly-missing',
58
+ category: this.category,
59
+ riskLevel: 'MEDIUM',
60
+ title: 'Guest User Anomaly detection store is not available',
61
+ detail: 'Other Threat Detection stores exist, but GuestUserAnomalyEventStore is not queryable, so anomalous guest bulk-access is not being detected or retained.',
62
+ remediation: 'Enable storage for the Guest User Anomaly event in Setup > Event Manager and add alerting.',
63
+ affectedItems: [{ label: 'Event Manager', url: setupUrl }],
64
+ });
65
+ return { findings };
66
+ }
67
+ if (withData.length === 0) {
68
+ findings.push({
69
+ id: 'threat-detection-inactive',
70
+ category: this.category,
71
+ riskLevel: 'MEDIUM',
72
+ title: 'Threat Detection stores are present but contain no events',
73
+ detail: 'The Threat Detection anomaly stores are queryable but hold no events in the last 180 days. Storage may have been enabled only recently, or detection is not generating events. Until events accumulate, "no anomalies" is not evidence of safe behaviour, and historical anomalous guest access cannot be reconstructed.',
74
+ remediation: 'Confirm storage is enabled for the anomaly events (Setup > Event Manager) and has been for the full retention window. Verify Transaction Security / Threat Detection policies are active and alerting.',
75
+ affectedItems: [{ label: 'Event Manager', url: setupUrl }],
76
+ });
77
+ return { findings };
78
+ }
79
+ findings.push({
80
+ id: 'threat-detection-active',
81
+ category: this.category,
82
+ riskLevel: 'LOW',
83
+ passed: true,
84
+ title: `Threat Detection storage active (${withData.length}/${queryable.length} stores have recent events)`,
85
+ detail: `Guest User Anomaly detection is available and Threat Detection events are being stored (${withData.join(', ')}).`,
86
+ remediation: 'Keep storage enabled and ensure alerting/automation acts on Guest User Anomaly events.',
87
+ });
88
+ return { findings };
89
+ }
90
+ }
91
+ //# sourceMappingURL=ThreatDetectionCheck.js.map
@@ -66,6 +66,23 @@ import { GuestExecutableApexCheck } from './impl/GuestExecutableApexCheck.js';
66
66
  import { EmailSecurityCheck } from './impl/EmailSecurityCheck.js';
67
67
  import { OutboundMessagesCheck } from './impl/OutboundMessagesCheck.js';
68
68
  import { PublicContentExposureCheck } from './impl/PublicContentExposureCheck.js';
69
+ import { GuestObjectExposureCheck } from './impl/GuestObjectExposureCheck.js';
70
+ import { GuestSiteOptionsCheck } from './impl/GuestSiteOptionsCheck.js';
71
+ import { GuestRecordAccessPolicyCheck } from './impl/GuestRecordAccessPolicyCheck.js';
72
+ import { GuestTrafficAnomalyCheck } from './impl/GuestTrafficAnomalyCheck.js';
73
+ import { ThreatDetectionCheck } from './impl/ThreatDetectionCheck.js';
74
+ // Org-surface hardening checks (no cache deps)
75
+ import { LoginAccessPolicyCheck } from './impl/LoginAccessPolicyCheck.js';
76
+ import { DataExportAccessCheck } from './impl/DataExportAccessCheck.js';
77
+ import { ClassicSitesCheck } from './impl/ClassicSitesCheck.js';
78
+ import { AuthProvidersCheck } from './impl/AuthProvidersCheck.js';
79
+ import { GuestApiAccessCheck } from './impl/GuestApiAccessCheck.js';
80
+ import { ExternalCredentialsCheck } from './impl/ExternalCredentialsCheck.js';
81
+ import { LoginAnomalyCheck } from './impl/LoginAnomalyCheck.js';
82
+ import { SessionHardeningCheck } from './impl/SessionHardeningCheck.js';
83
+ import { EncryptionCoverageCheck } from './impl/EncryptionCoverageCheck.js';
84
+ import { ExperienceCspCheck } from './impl/ExperienceCspCheck.js';
85
+ import { SandboxDataMaskingCheck } from './impl/SandboxDataMaskingCheck.js';
69
86
  // Access-control depth: effective-permission resolution + combination analysis
70
87
  import { PrivilegedAccessCheck } from './impl/PrivilegedAccessCheck.js';
71
88
  import { SeparationOfDutiesCheck } from './impl/SeparationOfDutiesCheck.js';
@@ -127,6 +144,21 @@ export const CHECKS = [
127
144
  new EmailSecurityCheck(), // inbound email services + send-as spoofing
128
145
  new OutboundMessagesCheck(), // outbound message session-id leak + cleartext endpoints
129
146
  new PublicContentExposureCheck(), // externally available Documents + public static resources
147
+ new GuestObjectExposureCheck(), // auto-discovered guest bulk-read surface (UI API) + ownership-defeats-OWD
148
+ new GuestSiteOptionsCheck(), // guest file access + guest member visibility on Experience sites
149
+ new GuestRecordAccessPolicyCheck(), // "Secure guest user record access" enforcement (ownership-defeats-OWD guardrail)
150
+ new ThreatDetectionCheck(), // Guest User Anomaly / Threat Detection event storage enabled
151
+ new LoginAccessPolicyCheck(), // delegated admin + login-as impersonation paths
152
+ new DataExportAccessCheck(), // Weekly Export / API+ViewAll bulk-exfil capability
153
+ new ClassicSitesCheck(), // classic Visualforce Force.com Sites (unauth surface)
154
+ new AuthProvidersCheck(), // external Auth Providers / SAML IdP federation review
155
+ new GuestApiAccessCheck(), // guest users with API Enabled / Bulk API Hard Delete
156
+ new ExternalCredentialsCheck(), // External Credential weak/no authentication
157
+ new LoginAnomalyCheck(), // successful logins from many distinct IPs
158
+ new SessionHardeningCheck(), // reads healthCheckRisks — clickjack/CSRF/session-lock/XSS
159
+ new EncryptionCoverageCheck(), // classified sensitive fields not encrypted at rest
160
+ new ExperienceCspCheck(), // Experience Cloud CSP / Lightning Web Security advisory
161
+ new SandboxDataMaskingCheck(), // sandbox with populated (likely unmasked) PII
130
162
  new PrivilegedAccessCheck(), // writes: effectivePermissions; shadow-admin detection
131
163
  // Cache-dependent checks — must come after their producers
132
164
  new DeploymentIdentityCheck(), // reads connectedAppNames
@@ -137,6 +169,7 @@ export const CHECKS = [
137
169
  new ApexRestEndpointCheck(), // reads apexBodies
138
170
  new VisualforceXssCheck(), // writes vfPageBodies
139
171
  new EventMonitoringCheck(), // writes eventLogSummary
172
+ new GuestTrafficAnomalyCheck(), // reads eventLogSummary — anonymizer IPs, bursts, GraphQL recon in guest logs
140
173
  new MfaRegistrationCheck(), // writes mfaRegistrations
141
174
  new SiemIntegrationCheck(), // reads namedCredentialEndpoints, remoteSiteUrls,
142
175
  // connectedAppNames, scheduledApexClassNames, eventLogSummary
@@ -43,16 +43,20 @@ export default class AuditDiffCommand extends SfCommand {
43
43
  this.warn(`Org IDs differ: baseline=${baseline.orgId}, current=${current.orgId}. Continuing anyway.`);
44
44
  }
45
45
  const diff = computeDiff(baseline, current);
46
- const formats = flags.format.split(',').map((f) => f.trim());
46
+ const formats = flags.format.split(',').map((f) => f.trim()).filter(Boolean);
47
+ const bad = formats.filter((f) => !DIFF_RENDERERS[f]);
48
+ if (bad.length > 0 || formats.length === 0) {
49
+ this.error(bad.length > 0 ? `Unknown output format(s): ${bad.join(', ')}` : 'No output format specified.', {
50
+ suggestions: ['Valid formats: html, json'],
51
+ });
52
+ }
47
53
  const baseTs = baseline.generatedAt.getTime();
48
54
  const curTs = current.generatedAt.getTime();
49
55
  fs.mkdirSync(flags.output, { recursive: true });
50
56
  for (const format of formats) {
51
57
  const renderer = DIFF_RENDERERS[format];
52
- if (!renderer) {
53
- this.warn(`Unknown format '${format}'. Skipping. Valid formats: html, json`);
54
- continue;
55
- }
58
+ if (!renderer)
59
+ continue; // unreachable: validated above
56
60
  const filename = `sf-audit-diff-${baseline.orgId}-${baseTs}-vs-${curTs}${renderer.fileExtension}`;
57
61
  const outputPath = path.join(flags.output, filename);
58
62
  fs.writeFileSync(outputPath, renderer.render(diff), 'utf-8');
@@ -0,0 +1,17 @@
1
+ import { SfCommand } from '@salesforce/sf-plugins-core';
2
+ import { type EventsPullResult } from '../../../events/pullEventLogs.js';
3
+ export default class AuditEventsPullCommand extends SfCommand<EventsPullResult> {
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
+ since: import("@oclif/core/interfaces").OptionFlag<number, import("@oclif/core/interfaces").CustomOptions>;
10
+ types: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
11
+ output: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
12
+ };
13
+ run(): Promise<EventsPullResult>;
14
+ private accessMessage;
15
+ private printSummary;
16
+ }
17
+ //# sourceMappingURL=pull.d.ts.map
@@ -0,0 +1,88 @@
1
+ // src/commands/audit/events/pull.ts
2
+ import { SfCommand, Flags } from '@salesforce/sf-plugins-core';
3
+ import { buildAuditContext, resolveOrgInfo } from '../../../lib/wire.js';
4
+ import { EventBaselineStore } from '../../../events/EventBaselineStore.js';
5
+ import { pullEventLogs } from '../../../events/pullEventLogs.js';
6
+ import { sanitizeTypes } from '../../../events/eventLogQuery.js';
7
+ export default class AuditEventsPullCommand extends SfCommand {
8
+ static summary = 'Capture free EventLogFile daily logs to local disk';
9
+ static description = 'Downloads the org\'s free (Daily-interval) EventLogFile CSV logs to ~/.sf/event-baseline/{orgId} so they ' +
10
+ 'survive the free tier\'s ~1-day retention window. Read-only (GET only). Idempotent: rows already saved are ' +
11
+ 'skipped, so it is safe to run daily via cron or a scheduled GitHub Action to build a rolling local baseline ' +
12
+ 'of login, API, and error activity without the paid Event Monitoring / Shield add-on.';
13
+ static examples = [
14
+ '<%= config.bin %> <%= command.id %> --target-org myOrg',
15
+ '<%= config.bin %> <%= command.id %> --target-org myOrg --since 3',
16
+ '<%= config.bin %> <%= command.id %> --target-org myOrg --types Login,ApiTotalUsage',
17
+ '<%= config.bin %> <%= command.id %> --target-org myOrg --output ./event-baseline',
18
+ ];
19
+ static flags = {
20
+ 'target-org': Flags.requiredOrg(),
21
+ since: Flags.integer({
22
+ summary: 'Number of days of LogDate to request (LAST_N_DAYS window).',
23
+ default: 1,
24
+ helpValue: '1',
25
+ }),
26
+ types: Flags.string({
27
+ summary: 'Restrict to specific EventTypes (comma-separated). Omit to pull every available type.',
28
+ helpValue: 'Login,ApiTotalUsage',
29
+ }),
30
+ output: Flags.string({
31
+ char: 'o',
32
+ summary: 'Base directory to store logs under. Defaults to ~/.sf/event-baseline.',
33
+ helpValue: './event-baseline',
34
+ }),
35
+ };
36
+ async run() {
37
+ const { flags } = await this.parse(AuditEventsPullCommand);
38
+ const conn = flags['target-org'].getConnection('62.0');
39
+ const orgInfo = await resolveOrgInfo(conn);
40
+ const ctx = buildAuditContext(conn, orgInfo);
41
+ const store = new EventBaselineStore(flags.output);
42
+ const types = sanitizeTypes(flags.types);
43
+ this.log(`Pulling free EventLogFile logs for org: ${orgInfo.name} (${orgInfo.id})`);
44
+ if (types.length > 0)
45
+ this.log(`Restricting to event type(s): ${types.join(', ')}`);
46
+ const result = await pullEventLogs({ soql: ctx.soql, rest: ctx.rest, store, orgId: orgInfo.id }, { since: flags.since, types, warn: (msg) => this.warn(msg) });
47
+ if (result.accessError) {
48
+ this.warn(this.accessMessage(result.accessError));
49
+ return result;
50
+ }
51
+ if (result.found === 0) {
52
+ this.log(`No EventLogFile records found for the last ${flags.since} day(s). Free daily logs need ` +
53
+ 'Enterprise/Unlimited/Performance edition and appear ~24h after the activity.');
54
+ return result;
55
+ }
56
+ this.printSummary(result);
57
+ return result;
58
+ }
59
+ accessMessage(access) {
60
+ switch (access) {
61
+ case 'no-permission':
62
+ return ('EventLogFile is not readable by this org user: the "View Event Log Files" permission is missing. ' +
63
+ 'Grant it to the running user and re-run.');
64
+ case 'not-enabled':
65
+ return ('EventLogFile is not available on this org/edition. Free daily logs require Enterprise/Unlimited/' +
66
+ 'Performance edition (Developer Edition also exposes them); other editions need the Event Monitoring add-on.');
67
+ default:
68
+ return 'EventLogFile could not be queried. Verify the org connection and that EventLogFile is accessible.';
69
+ }
70
+ }
71
+ printSummary(result) {
72
+ this.log('');
73
+ this.log('─────────────────────────────');
74
+ this.log(' Event Baseline Pull');
75
+ this.log('─────────────────────────────');
76
+ this.log(` Found ${String(result.found).padStart(4)}`);
77
+ this.log(` Downloaded ${String(result.downloaded).padStart(4)}`);
78
+ this.log(` Skipped ${String(result.skipped).padStart(4)} (already saved)`);
79
+ if (result.failed > 0)
80
+ this.log(` Failed ${String(result.failed).padStart(4)}`);
81
+ this.log(` Total bytes ${String(result.totalBytes).padStart(4)}`);
82
+ this.log('─────────────────────────────');
83
+ this.log(` Saved to: ${result.storagePath}`);
84
+ if (result.manifestPath)
85
+ this.log(` Manifest: ${result.manifestPath}`);
86
+ }
87
+ }
88
+ //# sourceMappingURL=pull.js.map
@@ -17,6 +17,10 @@ export default class SecurityAuditCommand extends SfCommand<AuditResult> {
17
17
  frameworks: import("@oclif/core/interfaces").OptionFlag<string, import("@oclif/core/interfaces").CustomOptions>;
18
18
  };
19
19
  run(): Promise<AuditResult>;
20
+ /** Resolve --checks to the checks to run, erroring on any unknown ID. */
21
+ private resolveChecks;
22
+ /** Resolve --format to a validated list, erroring on any unknown format. */
23
+ private resolveFormats;
20
24
  private rendererFor;
21
25
  private printSummary;
22
26
  private handleFailOn;
@@ -29,7 +29,7 @@ export default class SecurityAuditCommand extends SfCommand {
29
29
  'target-org': Flags.requiredOrg(),
30
30
  format: Flags.string({
31
31
  char: 'f',
32
- summary: 'Output format(s), comma-separated: html, md, json',
32
+ summary: 'Output format(s), comma-separated: html, md, json, executive',
33
33
  default: 'html',
34
34
  }),
35
35
  output: Flags.string({
@@ -67,19 +67,14 @@ export default class SecurityAuditCommand extends SfCommand {
67
67
  };
68
68
  async run() {
69
69
  const { flags } = await this.parse(SecurityAuditCommand);
70
+ // Validate the selection and output formats up front, so a typo fails fast with
71
+ // a clear message instead of silently running a partial/empty audit or writing
72
+ // no report after the (potentially long) run completes.
73
+ const checksToRun = this.resolveChecks(flags.checks);
74
+ const formats = this.resolveFormats(flags.format);
70
75
  const conn = flags['target-org'].getConnection('62.0');
71
76
  const orgInfo = await resolveOrgInfo(conn);
72
77
  const ctx = buildAuditContext(conn, orgInfo);
73
- const checksToRun = flags.checks
74
- ? (() => {
75
- const ids = new Set(flags.checks.split(',').map((s) => s.trim()));
76
- const unknown = [...ids].filter((id) => !CHECKS.some((c) => c.id === id));
77
- if (unknown.length > 0) {
78
- this.warn(`Unknown check ID(s): ${unknown.join(', ')}. Run 'sf audit list' to see available checks.`);
79
- }
80
- return CHECKS.filter((c) => ids.has(c.id));
81
- })()
82
- : CHECKS;
83
78
  const knownCheckIds = new Set(CHECKS.map((c) => c.id));
84
79
  const scoringConfig = loadScoringConfig(flags['scoring-config'], knownCheckIds, (msg) => this.warn(msg));
85
80
  this.log(`Auditing org: ${orgInfo.name} (${orgInfo.id})`);
@@ -89,14 +84,11 @@ export default class SecurityAuditCommand extends SfCommand {
89
84
  const result = await engine.run((current, total, checkName) => {
90
85
  this.log(`[${String(current).padStart(2)}/${total}] ${checkName}`);
91
86
  });
92
- const formats = flags.format.split(',').map((f) => f.trim());
93
87
  fs.mkdirSync(flags.output, { recursive: true });
94
88
  for (const format of formats) {
95
89
  const renderer = this.rendererFor(format, flags);
96
- if (!renderer) {
97
- this.warn(`Unknown format '${format}'. Skipping. Valid formats: html, md, json, executive`);
98
- continue;
99
- }
90
+ if (!renderer)
91
+ continue; // unreachable: formats validated up front
100
92
  const output = renderer.render(result);
101
93
  const prefix = renderer.filenamePrefix ?? 'sf-audit';
102
94
  const filename = `${prefix}-${orgInfo.id}-${Date.now()}${renderer.fileExtension}`;
@@ -114,6 +106,38 @@ export default class SecurityAuditCommand extends SfCommand {
114
106
  }
115
107
  return result;
116
108
  }
109
+ /** Resolve --checks to the checks to run, erroring on any unknown ID. */
110
+ resolveChecks(raw) {
111
+ if (!raw)
112
+ return CHECKS;
113
+ const ids = raw.split(',').map((s) => s.trim()).filter(Boolean);
114
+ const unknown = ids.filter((id) => !CHECKS.some((c) => c.id === id));
115
+ if (unknown.length > 0) {
116
+ this.error(`Unknown check ID(s): ${unknown.join(', ')}`, {
117
+ suggestions: ["Run 'sf audit list' to see all valid check IDs."],
118
+ });
119
+ }
120
+ const set = new Set(ids);
121
+ const selected = CHECKS.filter((c) => set.has(c.id));
122
+ if (selected.length === 0) {
123
+ this.error('No checks were selected by --checks.', {
124
+ suggestions: ["Run 'sf audit list' to see valid check IDs, or omit --checks to run all."],
125
+ });
126
+ }
127
+ return selected;
128
+ }
129
+ /** Resolve --format to a validated list, erroring on any unknown format. */
130
+ resolveFormats(raw) {
131
+ const valid = ['html', 'md', 'json', 'executive'];
132
+ const formats = raw.split(',').map((f) => f.trim()).filter(Boolean);
133
+ const bad = formats.filter((f) => !valid.includes(f));
134
+ if (bad.length > 0 || formats.length === 0) {
135
+ this.error(bad.length > 0 ? `Unknown output format(s): ${bad.join(', ')}` : 'No output format specified.', {
136
+ suggestions: [`Valid formats: ${valid.join(', ')}`],
137
+ });
138
+ }
139
+ return formats;
140
+ }
117
141
  rendererFor(format, flags) {
118
142
  if (format === 'executive') {
119
143
  let overrides;