@cclabsnz/sf-audit 1.13.0 → 1.15.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/CHANGELOG.md +102 -0
  2. package/README.md +15 -4
  3. package/lib/checks/impl/AuditTrailCheck.js +18 -1
  4. package/lib/checks/impl/LegacyApiVersionCheck.js +14 -2
  5. package/lib/checks/impl/LightningMessageChannelCheck.d.ts +10 -0
  6. package/lib/checks/impl/LightningMessageChannelCheck.js +107 -0
  7. package/lib/checks/impl/MfaEnforcementCheck.js +19 -1
  8. package/lib/checks/impl/NamedCredentialsCheck.js +42 -29
  9. package/lib/checks/registry.js +2 -0
  10. package/lib/commands/audit/incident/collect.d.ts +22 -0
  11. package/lib/commands/audit/incident/collect.js +46 -0
  12. package/lib/commands/audit/incident/report.d.ts +29 -0
  13. package/lib/commands/audit/incident/report.js +87 -0
  14. package/lib/compliance/mapping.js +2 -1
  15. package/lib/findings/CheckMeta.js +1 -0
  16. package/lib/incident/analyse/actions.d.ts +22 -0
  17. package/lib/incident/analyse/actions.js +73 -0
  18. package/lib/incident/analyse/actors.d.ts +56 -0
  19. package/lib/incident/analyse/actors.js +231 -0
  20. package/lib/incident/analyse/baseline.d.ts +24 -0
  21. package/lib/incident/analyse/baseline.js +66 -0
  22. package/lib/incident/analyse/configDelta.d.ts +33 -0
  23. package/lib/incident/analyse/configDelta.js +98 -0
  24. package/lib/incident/analyse/index.d.ts +41 -0
  25. package/lib/incident/analyse/index.js +68 -0
  26. package/lib/incident/analyse/outcomes.d.ts +28 -0
  27. package/lib/incident/analyse/outcomes.js +32 -0
  28. package/lib/incident/analyse/responses.d.ts +59 -0
  29. package/lib/incident/analyse/responses.js +201 -0
  30. package/lib/incident/analyse/verdict.d.ts +40 -0
  31. package/lib/incident/analyse/verdict.js +149 -0
  32. package/lib/incident/bundleIo.d.ts +34 -0
  33. package/lib/incident/bundleIo.js +74 -0
  34. package/lib/incident/collect/collectBundle.d.ts +21 -0
  35. package/lib/incident/collect/collectBundle.js +130 -0
  36. package/lib/incident/collect/discoverWaves.d.ts +15 -0
  37. package/lib/incident/collect/discoverWaves.js +90 -0
  38. package/lib/incident/collect/followUp.d.ts +14 -0
  39. package/lib/incident/collect/followUp.js +64 -0
  40. package/lib/incident/collect/orgErrors.d.ts +5 -0
  41. package/lib/incident/collect/orgErrors.js +11 -0
  42. package/lib/incident/collect/snapshotOrg.d.ts +18 -0
  43. package/lib/incident/collect/snapshotOrg.js +117 -0
  44. package/lib/incident/collect/streamGuestLogs.d.ts +17 -0
  45. package/lib/incident/collect/streamGuestLogs.js +116 -0
  46. package/lib/incident/csv.d.ts +32 -0
  47. package/lib/incident/csv.js +176 -0
  48. package/lib/incident/ipRanges.d.ts +23 -0
  49. package/lib/incident/ipRanges.js +64 -0
  50. package/lib/incident/model.d.ts +132 -0
  51. package/lib/incident/model.js +26 -0
  52. package/lib/incident/render/evidence.d.ts +15 -0
  53. package/lib/incident/render/evidence.js +52 -0
  54. package/lib/incident/render/html.d.ts +7 -0
  55. package/lib/incident/render/html.js +144 -0
  56. package/lib/incident/render/labels.d.ts +9 -0
  57. package/lib/incident/render/labels.js +22 -0
  58. package/lib/incident/render/markdown.d.ts +17 -0
  59. package/lib/incident/render/markdown.js +91 -0
  60. package/lib/incident/render/redact.d.ts +7 -0
  61. package/lib/incident/render/redact.js +62 -0
  62. package/lib/incident/text.d.ts +9 -0
  63. package/lib/incident/text.js +43 -0
  64. package/package.json +20 -8
package/CHANGELOG.md CHANGED
@@ -11,6 +11,108 @@ published note and carries the signed provenance attestation and CycloneDX SBOM
11
11
 
12
12
  Merged to `main`, not yet released.
13
13
 
14
+ ## [v1.15.0](https://github.com/cclabsnz/sf-audit-plugin/releases/tag/v1.15.0) — 2026-10-06
15
+
16
+ One new check, and four existing checks that stop reporting conclusions they had not established.
17
+
18
+ ### Added
19
+
20
+ - **`lightning-message-channel`** flags Lightning Message Service channels with `isExposed=true`,
21
+ which outside namespaces, including every installed managed package, can publish to and
22
+ subscribe on. Sharing rules, org-wide defaults and field-level security do not reach the bus.
23
+ Salesforce's AppExchange Security Review requires `isExposed=false`, and the setting cannot be
24
+ reversed once true, so remediation is a new channel plus migrating its publishers and
25
+ subscribers, not a toggle. Installed channels are reported separately at LOW, since the fix sits
26
+ with the vendor. The finding says what the metadata cannot show: what a channel carries is
27
+ visible only in the publishing component. One Tooling query; grants no attack-chain capability.
28
+ Check count is now **93**.
29
+
30
+ ### Fixed
31
+
32
+ - **Four checks no longer report conclusions they had not established.** Each was both untested and
33
+ held a `catch` that swallowed a query failure; writing the tests is what surfaced the defects, as
34
+ it has every previous time.
35
+
36
+ - **`mfa-enforcement` asserted a HIGH finding on a failed query.** When
37
+ `PermissionsMultiFactorForUiLogins` could not be read - the field is absent in some editions -
38
+ the empty result was treated as "nobody has MFA enforced", so every external user fell into the
39
+ shortfall bucket and the check named them, at HIGH, as lacking MFA. Over-reporting was not the
40
+ safe direction: it produced a remediation task against real users and an SBS-AUTH-004 claim on
41
+ no evidence. Now inconclusive.
42
+ - **`audit-trail` charged a clean org for being clean.** Zero sensitive-section changes in seven
43
+ days produced an unmarked LOW finding, and `scoring.ts` excludes only passed and inconclusive
44
+ findings from the penalty numerator - so a quiet week cost health score. Now marked passed. Its
45
+ Manage Event Log Files query also failed silently, leaving SBS-MON-002 looking satisfied rather
46
+ than unevaluated; now inconclusive.
47
+ - **`named-credentials` discarded a HIGH finding it had already established.** A failed Apex scan
48
+ returned early, which also threw away the plaintext-HTTP (SBS-INT-003) and anonymous-principal
49
+ findings - both derived purely from the credential records, which had been read successfully.
50
+ The Apex scan only ever informed the unused analysis, so only that is now skipped, and it says
51
+ so. `unusedNamedCredentialsCount` is omitted rather than reported as zero when not computed.
52
+ - **`legacy-api-version` left no trace when RemoteProxy could not be filtered.** The absence of a
53
+ SOAP remote-site finding was indistinguishable from having established there are none. The
54
+ sibling `remote-sites` check is not cover for it: that reports remote sites in general and makes
55
+ no SOAP determination. Now inconclusive.
56
+
57
+ - **`named-credentials` no longer prints the word "null" into operator advice.** `Endpoint` is
58
+ nullable for External Credential-backed entries. The inventory finding handled that; the unused,
59
+ HTTP and anonymous notes interpolated it directly.
60
+
61
+ ### Security
62
+
63
+ - Removed `sprintf-js` from the dependency tree (GHSA-hp3w-g68c-fv3c, no patched release). It
64
+ reached the tree only through Jest's coverage loader via `js-yaml` 3; that loader now resolves
65
+ `js-yaml` 4, which does not depend on it. Development-only, and not in the shipped runtime.
66
+
67
+ ### Changed
68
+
69
+ - npm description corrected from 88 to 93 checks, with keywords for event monitoring, guest-user
70
+ and incident-response searches. The README feature list now includes `sf audit incident`.
71
+ - 57 unit tests across those four checks, taking the untested-check count from 33 of 93 to 29 and
72
+ the suite to 151 files / 1519 tests. Branch coverage 75%, statements 84%.
73
+
74
+ ## [v1.14.0](https://github.com/cclabsnz/sf-audit-plugin/releases/tag/v1.14.0) — 2026-10-06
75
+
76
+ Two investigation commands for Real-Time Event Monitoring **Guest User Anomaly** alerts, and every
77
+ open dependency advisory cleared.
78
+
79
+ ### Added
80
+
81
+ - **`sf audit incident collect`** (read-only). Discovers anomaly *waves* (adjacent days on one
82
+ site), then for each wave day plus one baseline day either side streams the EventLogFiles, keeps
83
+ only guest-user rows, and snapshots the audit trail, guest configuration and logins from actor
84
+ addresses into a sha256-sealed bundle under `~/.sf/incidents/`. Collection is resumable (intact
85
+ logs are reused), a bundle is refused until it is sealed complete, and only "unavailable" or
86
+ "no permission" errors degrade to a stated gap; anything else stops the run.
87
+ - **`sf audit incident report`** (offline). Analyses a bundle and writes an HTML report (prints
88
+ to PDF), Markdown, JSON, and one evidence CSV behind every number cited. `--redact` truncates
89
+ addresses and replaces linked users' names and emails with their ids.
90
+ - **The analysis**:
91
+ - spike against baseline, counting controller calls only and never summing across log types;
92
+ - actor blocks, told apart from always-on proxies by their own history and the org's normal
93
+ busiest block;
94
+ - reply sizes via unambiguous AuraRequest/Sites joins, against an empty size learned per action;
95
+ - login outcomes and identity links, with shared egress (proxies, NAT) set aside;
96
+ - guest-access configuration changes between waves, including hardening applied to one site but
97
+ not another.
98
+ - **No false reassurance.** "No evidence of access" and "within baseline" are reported only when
99
+ the collected evidence supports them; otherwise a wave reads "not assessed" with the reason, and
100
+ every report states what it cannot tell you.
101
+
102
+ ### Security
103
+
104
+ - Cleared all open Dependabot advisories: `undici` 8.10.0 → 8.11.2, and `csv-parse` 5 → 7 by
105
+ raising `@salesforce/core` to `^9.3.0`, which carries the fix to installers, not just this repo.
106
+ - Raised the `fast-uri@3` override floor to `^3.1.8` and the `brace-expansion` floor to
107
+ `^5.0.11`. `pnpm audit --prod` and a packed consumer-tree `npm audit` both report zero
108
+ vulnerabilities.
109
+
110
+ ### Notes
111
+
112
+ - Not a security check: the check count stays at 92 and the security grade is unaffected.
113
+ - `--ip-ranges` reads provider range files you supply; the plugin never fetches them, so the org
114
+ stays the only network destination.
115
+
14
116
  ## [v1.13.0](https://github.com/cclabsnz/sf-audit-plugin/releases/tag/v1.13.0) — 2026-09-25
15
117
 
16
118
  Five new attack chains, and the correlation defect that kept them from being expressible.
package/README.md CHANGED
@@ -15,13 +15,14 @@
15
15
 
16
16
  A Salesforce CLI (`sf`) plugin that runs a complete, **read-only** security audit against any Salesforce org, risk-scores it with an A–F grade, and turns the result into a report your security team (or your client's) can act on.
17
17
 
18
- - **92 read-only checks** across identity, access, data, code, integrations, monitoring, and Agentforce / GenAI
18
+ - **93 read-only checks** across identity, access, data, code, integrations, monitoring, and Agentforce / GenAI
19
19
  - **Attack-chain correlation:** links individual findings into named, multi-step attack scenarios — sixteen modelled chains, plus an emergent pass for combinations nobody has named yet (see [Attack chains](#attack-chains))
20
20
  - **Compliance mapping:** every finding mapped to **source-verified** controls across 10 frameworks (OWASP, OWASP LLM Top 10, SOC 2, ISO/IEC 27001:2022, Security Benchmark for Salesforce, NZ Privacy Act, HISO 10029, NZISM, HIPAA Security Rule, GDPR)
21
21
  - **Outputs:** a technical `html` / `md` / `json` report, or a branded, client-ready **executive report** (print-to-PDF) with priorities, remediation roadmap, and a compliance coverage matrix
22
22
  - **History & diff:** archives each run and shows security-posture drift over time
23
23
  - **Free event baseline:** `sf audit events pull` captures the org's free daily `EventLogFile` logs to local disk before the 1-day retention window drops them — no Event Monitoring / Shield add-on needed
24
24
  - **Connected-app least-privilege:** `sf audit apps` reads the `RestApi` EventLogFile to see which objects each connected app actually uses, compares that against what its run-as user is granted, and reports the over-grant per object and read/write bit — plus a suggested least-privilege permission set
25
+ - **Guest User Anomaly investigation:** `sf audit incident collect` saves the guest user's evidence for each anomaly wave, and `sf audit incident report` analyses it offline into a cited verdict: who it was, whether content came back, and whether anyone logged in ([walkthrough](https://www.softwareinsights.dev/posts/salesforce-guest-user-anomaly-investigation-sf-audit-incident/))
25
26
  - Strictly read-only (SOQL/Tooling/REST GETs + Metadata API reads); see [PERMISSIONS.md](PERMISSIONS.md) for the least-privilege access it needs
26
27
 
27
28
  ## Installation
@@ -44,7 +45,7 @@ guarantees here are checkable rather than asserted — see [Trust & verification
44
45
  sf audit security --target-org <orgAlias>
45
46
  ```
46
47
 
47
- Runs all 92 checks and writes an HTML report to the current directory. `sf audit list` prints every
48
+ Runs all 93 checks and writes an HTML report to the current directory. `sf audit list` prints every
48
49
  check id.
49
50
 
50
51
  | Flag | Default | |
@@ -94,7 +95,7 @@ All twelve flags, more examples, and what the executive report contains:
94
95
 
95
96
  ## What It Checks
96
97
 
97
- **92 read-only checks** across ten domains. Every finding is risk-rated CRITICAL → INFO, mapped to
98
+ **93 read-only checks** across ten domains. Every finding is risk-rated CRITICAL → INFO, mapped to
98
99
  compliance controls, and correlated into [attack chains](#attack-chains).
99
100
 
100
101
  | Domain | Checks |
@@ -105,7 +106,7 @@ compliance controls, and correlated into [attack chains](#attack-chains).
105
106
  | Guest & External-Facing Access | 12 |
106
107
  | Integrations, Connected Apps & Deployments | 11 |
107
108
  | Monitoring & Threat Detection | 10 |
108
- | Apex & Code Security | 9 |
109
+ | Apex & Code Security | 10 |
109
110
  | AI & Agents (Agentforce / GenAI) | 6 |
110
111
  | Org Health & Configuration | 5 |
111
112
  | Secrets & Credential Storage | 2 |
@@ -218,6 +219,16 @@ To triage captured logs for abuse patterns, pair `events pull` with the companio
218
219
  **[sfelf-triage](https://github.com/cclabsnz/sfelf-triage)**, which reads this plugin's
219
220
  `~/.sf/event-baseline/<orgId>` layout directly.
220
221
 
222
+ ### Investigating a guest anomaly
223
+
224
+ `sf audit incident collect --target-org <alias>` finds Guest User Anomaly waves and saves a
225
+ guest-filtered evidence bundle to `~/.sf/incidents/`. `sf audit incident report --bundle <dir>`
226
+ analyses it offline and writes an HTML/Markdown/JSON report with evidence CSVs. Pass
227
+ `--ip-ranges` with provider range files you have downloaded to classify hosting; the plugin
228
+ never fetches them. Use `--redact` before sharing beyond the client's security team. Bundles in
229
+ `~/.sf/incidents` hold guest-traffic rows and linked-user details unencrypted, so handle them as
230
+ sensitive data.
231
+
221
232
  ## Requirements
222
233
 
223
234
  - Node.js 18+
@@ -33,6 +33,10 @@ export class AuditTrailCheck {
33
33
  id: 'permission-security-changes',
34
34
  category: this.category,
35
35
  riskLevel: securityRiskLevel,
36
+ // Zero sensitive-section changes is a pass, not a LOW finding. scoring.ts excludes only
37
+ // passed and inconclusive findings from the penalty numerator, so leaving this unmarked
38
+ // charged a clean seven days against the org's health score.
39
+ passed: securityChangeCount === 0,
36
40
  title: `${securityChangeCount} permission or security configuration change(s) in the last 7 days`,
37
41
  detail: 'Frequent permission and security changes can indicate privilege escalation activity or risky configuration drift.',
38
42
  remediation: 'Review each change in Setup → Audit Trail. Investigate unexpected changes, especially outside change-management windows.',
@@ -90,7 +94,20 @@ export class AuditTrailCheck {
90
94
  }
91
95
  }
92
96
  catch {
93
- // PermissionsManageEventLogFiles may not exist in orgs without Event Monitoring — skip silently
97
+ // PermissionsManageEventLogFiles does not exist in orgs without Event Monitoring, so this
98
+ // query legitimately fails. Skipping silently was wrong: with no finding emitted, a reader
99
+ // cannot tell "nobody can delete event logs" from "we were unable to find out", and only
100
+ // the first of those is a pass. Declared inconclusive so it is scored as INFO, carries no
101
+ // penalty, and is still shown.
102
+ findings.push({
103
+ id: 'event-log-delete-permission-inconclusive',
104
+ category: this.category,
105
+ riskLevel: 'INFO',
106
+ inconclusive: true,
107
+ title: 'Manage Event Log Files assignments could not be queried',
108
+ detail: 'PermissionSetAssignment could not be filtered on PermissionsManageEventLogFiles. The field is absent in orgs without Event Monitoring, and the query also fails without access to PermissionSetAssignment, so who can delete event monitoring data is unestablished. SBS-MON-002 is unevaluated rather than satisfied.',
109
+ remediation: 'If the org has Event Monitoring, grant the audit user read access to PermissionSetAssignment and re-run. Otherwise there are no EventLogFile records to protect and no action is needed.',
110
+ });
94
111
  }
95
112
  return { findings };
96
113
  }
@@ -70,8 +70,20 @@ export class LegacyApiVersionCheck {
70
70
  }
71
71
  }
72
72
  catch {
73
- // RemoteProxy LIKE query may not be supported in all org editions — skip silently.
74
- // RemoteSitesCheck covers general remote site access concerns.
73
+ // The LIKE predicate on RemoteProxy is not supported in every edition, so this query
74
+ // legitimately fails. Skipping silently left no trace, which made the absence of a SOAP
75
+ // finding indistinguishable from having established that there are none. RemoteSitesCheck
76
+ // is not cover for this: it reports remote sites in general and makes no SOAP
77
+ // determination, so nothing else in the audit answers this question.
78
+ findings.push({
79
+ id: 'legacy-api-soap-remote-sites-inconclusive',
80
+ category: this.category,
81
+ riskLevel: 'INFO',
82
+ inconclusive: true,
83
+ title: 'Remote site settings could not be filtered for SOAP endpoints',
84
+ detail: 'Querying RemoteProxy with a LIKE predicate on EndpointUrl failed. The object is unavailable in some editions, and the query also fails without Tooling API access to it. Whether this org has active remote sites pointing at /services/Soap/ endpoints is therefore unestablished rather than answered in the negative.',
85
+ remediation: 'Grant the audit user Tooling API access to RemoteProxy and re-run. Otherwise review Setup → Remote Site Settings by hand for endpoints containing /services/Soap/.',
86
+ });
75
87
  }
76
88
  // Advisory: inbound SOAP API detection requires EventLogFile CSV analysis.
77
89
  // Salesforce stores API_TYPE per-call in EventLogFile (EventType = 'API'):
@@ -0,0 +1,10 @@
1
+ import type { SecurityCheck, CheckResult } from '../SecurityCheck.js';
2
+ import type { AuditContext } from '@cclabsnz/sf-core';
3
+ export declare class LightningMessageChannelCheck implements SecurityCheck {
4
+ readonly id = "lightning-message-channel";
5
+ readonly name = "Lightning Message Channel Exposure";
6
+ readonly category = "Code Security";
7
+ readonly description = "Finds Lightning Message Channels published to every namespace, where any component sharing the page can read or write the bus.";
8
+ run(ctx: AuditContext): Promise<CheckResult>;
9
+ }
10
+ //# sourceMappingURL=LightningMessageChannelCheck.d.ts.map
@@ -0,0 +1,107 @@
1
+ /** ManageableState values that mean the channel was defined in this org rather than installed. */
2
+ const LOCAL_STATES = new Set(['unmanaged', 'unpackaged', 'deprecatedEditable', 'released']);
3
+ export class LightningMessageChannelCheck {
4
+ id = 'lightning-message-channel';
5
+ name = 'Lightning Message Channel Exposure';
6
+ category = 'Code Security';
7
+ description = 'Finds Lightning Message Channels published to every namespace, where any component sharing the page can read or write the bus.';
8
+ async run(ctx) {
9
+ const channels = await ctx.tooling.query('SELECT Id, DeveloperName, MasterLabel, NamespacePrefix, ManageableState, IsExposed ' +
10
+ 'FROM LightningMessageChannel');
11
+ if (channels.length === 0) {
12
+ return {
13
+ findings: [{
14
+ id: 'lightning-message-channel-none',
15
+ category: this.category,
16
+ riskLevel: 'INFO',
17
+ passed: true,
18
+ title: 'No Lightning Message Channels defined',
19
+ detail: 'This org defines no Lightning Message Channels, so there is no cross-component message bus to expose.',
20
+ remediation: 'No action required.',
21
+ }],
22
+ };
23
+ }
24
+ const exposed = channels.filter((c) => c.IsExposed);
25
+ if (exposed.length === 0) {
26
+ return {
27
+ findings: [{
28
+ id: 'lightning-message-channel-ok',
29
+ category: this.category,
30
+ riskLevel: 'INFO',
31
+ passed: true,
32
+ title: `All ${channels.length} Lightning Message Channel(s) are scoped to their own namespace`,
33
+ detail: `None of the ${channels.length} channel(s) set isExposed, so each is usable only by components in the namespace that defines it.`,
34
+ remediation: 'No action required.',
35
+ }],
36
+ };
37
+ }
38
+ // Split by who can actually fix it. isExposed cannot be set back to false, so for an installed
39
+ // channel there is no remediation available inside this org at all.
40
+ const local = exposed.filter((c) => LOCAL_STATES.has(c.ManageableState ?? 'unmanaged'));
41
+ const installed = exposed.filter((c) => !LOCAL_STATES.has(c.ManageableState ?? 'unmanaged'));
42
+ const findings = [];
43
+ const setupUrl = `${ctx.orgInfo.instanceUrl}/lightning/setup/LightningMessageChannels/home`;
44
+ const label = (c) => `${c.NamespacePrefix ? `${c.NamespacePrefix}__` : ''}${c.DeveloperName}`;
45
+ if (local.length > 0) {
46
+ findings.push({
47
+ id: 'lightning-message-channel-exposed',
48
+ category: this.category,
49
+ riskLevel: 'MEDIUM',
50
+ title: `${local.length} Lightning Message Channel(s) are exposed to every namespace`,
51
+ detail: `${local.length} of ${channels.length} channel(s) set isExposed=true. Lightning Message Service is secure by default: ` +
52
+ 'per Salesforce, components in other namespaces cannot read a channel unless isExposed is true, and exposing it lets ' +
53
+ 'outside packages publish to and subscribe on it. This single boolean is therefore the whole of what separates the ' +
54
+ 'channel from code the org did not write. ' +
55
+ 'Who can take advantage is narrower than it first appears, and worth being precise about: subscribing requires importing ' +
56
+ 'the channel into a deployed component, so the actor is an installed managed package or anything else deployed into this ' +
57
+ 'org — not arbitrary script running on the page. That makes this a design exposure rather than a demonstrated leak. ' +
58
+ 'What it costs, where a channel carries record data, is that a message is a plain JavaScript object the publisher ' +
59
+ 'assembled. There is no record-level enforcement on a message, so a subscriber reads whatever was placed on the channel ' +
60
+ 'irrespective of what its own user is entitled to see, and a publisher can equally put a payload on the channel that a ' +
61
+ 'subscriber then treats as trusted input. ' +
62
+ 'Note that Visualforce supports only channels where isExposed is true, so a channel used from a Visualforce page is ' +
63
+ 'exposed because the platform requires it, not because anyone chose it. ' +
64
+ 'This check reads channel metadata only. It establishes that the door is open, not that anything sensitive passes ' +
65
+ 'through it: what each channel actually carries is visible only in the publishing component.',
66
+ remediation: 'Start by reading the publishing component to see what each channel carries, because that decides whether this is urgent ' +
67
+ 'or merely untidy: a channel passing a record id is a much smaller problem than one passing field values, and nothing in ' +
68
+ 'the metadata distinguishes them. Then check whether any installed package would be positioned to subscribe, since a ' +
69
+ 'channel exposed in an org with no third-party components on those pages has no audience today, though it will if one is ' +
70
+ 'installed later. ' +
71
+ 'If it needs closing, treat it as a design change rather than a setting change: isExposed cannot be set back to false ' +
72
+ 'once true, so closing a channel means defining a replacement with isExposed=false and migrating every publisher and ' +
73
+ 'subscriber to it. Make every subscriber validate the payload rather than trusting it, since the publisher cannot be ' +
74
+ 'authenticated. Where the channel exists only to support a Visualforce page, moving that page to a Lightning Web ' +
75
+ 'Component removes the constraint that forced the exposure.',
76
+ affectedItems: local.map((c) => ({
77
+ label: label(c),
78
+ note: c.MasterLabel && c.MasterLabel !== c.DeveloperName ? c.MasterLabel : undefined,
79
+ url: setupUrl,
80
+ })),
81
+ });
82
+ }
83
+ if (installed.length > 0) {
84
+ findings.push({
85
+ id: 'lightning-message-channel-exposed-installed',
86
+ category: this.category,
87
+ riskLevel: 'LOW',
88
+ title: `${installed.length} exposed Lightning Message Channel(s) came from an installed package`,
89
+ detail: `${installed.length} exposed channel(s) are owned by an installed package, so they cannot be changed in this org and ` +
90
+ 'the exposure is the publisher\'s decision rather than yours. They are listed separately because the reach is the same ' +
91
+ 'as a local exposed channel — any component in any namespace can read and write them — while the remediation is not ' +
92
+ 'available to you. Worth knowing because Salesforce\'s own AppExchange Security Review requires isExposed=false, so an ' +
93
+ 'installed package shipping an exposed channel is a reasonable question to put to the vendor.',
94
+ remediation: 'Raise it with the package publisher, citing the AppExchange Security Review requirement that isExposed be false. ' +
95
+ 'In the meantime, treat any page hosting the package\'s components as a shared bus and avoid placing components that ' +
96
+ 'publish sensitive payloads on the same page.',
97
+ affectedItems: installed.map((c) => ({
98
+ label: label(c),
99
+ note: c.ManageableState ?? undefined,
100
+ url: setupUrl,
101
+ })),
102
+ });
103
+ }
104
+ return { findings };
105
+ }
106
+ }
107
+ //# sourceMappingURL=LightningMessageChannelCheck.js.map
@@ -40,7 +40,25 @@ export class MfaEnforcementCheck {
40
40
  mfaEnforcedIds = new Set(mfaResult.records.map((r) => r.AssigneeId));
41
41
  }
42
42
  catch {
43
- // PermissionsMultiFactorForUiLogins may not exist in all editions — treat as none enforced
43
+ // PermissionsMultiFactorForUiLogins is absent in some editions, so this query legitimately
44
+ // fails. It previously fell through with an empty set, which is not a neutral default: with
45
+ // nothing enforced every portal user lands in `withoutMfa`, and the check then stated as
46
+ // established fact, at HIGH, that each named user lacks MFA. Over-reporting is not the safe
47
+ // direction — it produces a remediation task against real users and an SBS-AUTH-004 claim
48
+ // that no evidence supports. The MFA status is unknown, so say that and stop.
49
+ return {
50
+ findings: [
51
+ {
52
+ id: 'mfa-enforcement-inconclusive',
53
+ category: this.category,
54
+ riskLevel: 'INFO',
55
+ inconclusive: true,
56
+ title: `MFA enforcement for ${allPortalUsers.length} external/portal user(s) could not be determined`,
57
+ detail: `This org has ${allPortalUsers.length} active external/portal user(s), but PermissionSetAssignment could not be filtered on PermissionsMultiFactorForUiLogins. The field is absent in some editions, and the query also fails without access to PermissionSetAssignment. Whether these users have MFA enforced is therefore unestablished, so SBS-AUTH-004 is unevaluated rather than failed.`,
58
+ remediation: 'Grant the audit user read access to PermissionSetAssignment and re-run. If the permission does not exist in this edition, verify MFA for external users manually in Setup, and through the identity provider where portal logins are federated.',
59
+ },
60
+ ],
61
+ };
44
62
  }
45
63
  const withoutMfa = allPortalUsers.filter((u) => !mfaEnforcedIds.has(u.Id));
46
64
  const withMfa = allPortalUsers.filter((u) => mfaEnforcedIds.has(u.Id));
@@ -29,45 +29,45 @@ export class NamedCredentialsCheck {
29
29
  // Scan Apex code to find which named credentials are actually referenced
30
30
  // Named credentials are referenced as 'callout:DeveloperName' in Apex
31
31
  let apexBodies = ctx.cache.apexBodies ?? [];
32
+ // Whether the unused analysis has a basis. False only when the Apex read failed, which is
33
+ // not the same as finding no references — hence a flag rather than an empty-set default.
34
+ let apexScanned = true;
35
+ // Endpoint is nullable for External Credential-backed entries. Interpolating it directly put
36
+ // the literal "null" into advice shown to an operator.
37
+ const endpointNote = (endpoint, advice) => `${endpoint ?? '(no endpoint — External Credential)'}: ${advice}`;
32
38
  if (apexBodies.length === 0) {
33
39
  try {
34
40
  const apexRecords = await new ApexRepository(ctx.tooling).listClasses({ excludeManaged: true });
35
41
  apexBodies = apexRecords.map((r) => ({ name: r.name, body: r.body ?? '' }));
36
42
  }
37
43
  catch {
38
- // If we can't scan Apex, emit inventory only
39
- findings.push({
40
- id: 'named-credentials-inventory',
41
- category: this.category,
42
- riskLevel: 'INFO',
43
- title: `${count} named credential(s) configured`,
44
- detail: 'Named credentials provide a secure way to store endpoint URLs and authentication details for external callouts.',
45
- remediation: 'Periodically review named credentials to ensure endpoints are current and credentials remain valid.',
46
- affectedItems: records.map((r) => ({
47
- label: r.MasterLabel,
48
- url: setupUrl,
49
- note: r.Endpoint ?? '(no endpoint — External Credential)',
50
- })),
51
- });
52
- return { findings, metrics: { namedCredentialsCount: count, unusedNamedCredentialsCount: 0 } };
44
+ // Losing the Apex scan costs the unused analysis and nothing else. Returning here also
45
+ // discarded the HTTP-endpoint and anonymous-principal findings, which are derived purely
46
+ // from the credential records already in hand — including a HIGH finding for plaintext
47
+ // HTTP that was fully established. Carry on with what the records support.
48
+ apexScanned = false;
53
49
  }
54
50
  }
55
51
  const combinedApexSource = apexBodies.map((c) => c.body).join('\n');
56
- const unusedCredentials = records.filter((r) => {
57
- // Named credentials are referenced as callout:DeveloperName or callout:MasterLabel
58
- // Literal search, not a pattern built from the credential's own name: MasterLabel is free
59
- // text from Setup, and a bracket in it used to crash the check while a quantifier quietly
60
- // matched the wrong thing.
61
- return (!referencesCallout(combinedApexSource, r.DeveloperName) &&
62
- !referencesCallout(combinedApexSource, r.MasterLabel.replace(/\s+/g, '_')));
63
- });
64
- const usedCredentials = records.filter((r) => !unusedCredentials.includes(r));
52
+ const unusedCredentials = apexScanned
53
+ ? records.filter((r) => {
54
+ // Named credentials are referenced as callout:DeveloperName or callout:MasterLabel
55
+ // Literal search, not a pattern built from the credential's own name: MasterLabel is free
56
+ // text from Setup, and a bracket in it used to crash the check while a quantifier quietly
57
+ // matched the wrong thing.
58
+ return (!referencesCallout(combinedApexSource, r.DeveloperName) &&
59
+ !referencesCallout(combinedApexSource, r.MasterLabel.replace(/\s+/g, '_')));
60
+ })
61
+ : [];
62
+ const usedCredentials = apexScanned ? records.filter((r) => !unusedCredentials.includes(r)) : [];
65
63
  // Inventory finding
66
64
  findings.push({
67
65
  id: 'named-credentials-inventory',
68
66
  category: this.category,
69
67
  riskLevel: 'INFO',
70
- title: `${count} named credential(s) configured (${usedCredentials.length} used, ${unusedCredentials.length} unused in Apex)`,
68
+ title: apexScanned
69
+ ? `${count} named credential(s) configured (${usedCredentials.length} used, ${unusedCredentials.length} unused in Apex)`
70
+ : `${count} named credential(s) configured`,
71
71
  detail: 'Named credentials provide a secure way to store endpoint URLs and authentication details for external callouts.',
72
72
  remediation: 'Periodically review named credentials to ensure endpoints are current and credentials remain valid.',
73
73
  affectedItems: records.map((r) => ({
@@ -76,6 +76,17 @@ export class NamedCredentialsCheck {
76
76
  note: r.Endpoint ?? '(no endpoint — External Credential)',
77
77
  })),
78
78
  });
79
+ if (!apexScanned) {
80
+ findings.push({
81
+ id: 'named-credentials-unused-inconclusive',
82
+ category: this.category,
83
+ riskLevel: 'INFO',
84
+ inconclusive: true,
85
+ title: 'Apex could not be scanned: named credentials were not checked for references',
86
+ detail: 'Listing Apex classes through the Tooling API failed, so which credentials are referenced by code is unestablished. Absence of an "unused credentials" finding below therefore means the analysis did not run, not that every credential is in use. The endpoint and principal-type findings are unaffected: both derive from the credential records, which were read successfully.',
87
+ remediation: 'Grant the audit user Tooling API access to ApexClass and re-run to get the unused-credential analysis.',
88
+ });
89
+ }
79
90
  // Flag unused credentials
80
91
  if (unusedCredentials.length > 0) {
81
92
  findings.push({
@@ -88,7 +99,7 @@ export class NamedCredentialsCheck {
88
99
  affectedItems: unusedCredentials.map((r) => ({
89
100
  label: r.MasterLabel,
90
101
  url: setupUrl,
91
- note: `${r.Endpoint}: verify if still required, delete if orphaned`,
102
+ note: endpointNote(r.Endpoint, 'verify if still required, delete if orphaned'),
92
103
  })),
93
104
  });
94
105
  }
@@ -105,7 +116,7 @@ export class NamedCredentialsCheck {
105
116
  affectedItems: httpEndpoints.map((r) => ({
106
117
  label: r.MasterLabel,
107
118
  url: setupUrl,
108
- note: `${r.Endpoint}: migrate to HTTPS`,
119
+ note: endpointNote(r.Endpoint, 'migrate to HTTPS'),
109
120
  })),
110
121
  });
111
122
  }
@@ -123,7 +134,7 @@ export class NamedCredentialsCheck {
123
134
  affectedItems: anonymousCreds.map((r) => ({
124
135
  label: r.MasterLabel,
125
136
  url: setupUrl,
126
- note: `${r.Endpoint}: verify that no authentication is required`,
137
+ note: endpointNote(r.Endpoint, 'verify that no authentication is required'),
127
138
  })),
128
139
  });
129
140
  }
@@ -131,7 +142,9 @@ export class NamedCredentialsCheck {
131
142
  findings,
132
143
  metrics: {
133
144
  namedCredentialsCount: count,
134
- unusedNamedCredentialsCount: unusedCredentials.length,
145
+ // Omitted when the Apex scan failed: zero would be read as "none are unused", which was
146
+ // never established.
147
+ ...(apexScanned ? { unusedNamedCredentialsCount: unusedCredentials.length } : {}),
135
148
  },
136
149
  };
137
150
  }
@@ -40,6 +40,7 @@ import { SiemIntegrationCheck } from './impl/SiemIntegrationCheck.js';
40
40
  import { ApexCrudFLSCheck } from './impl/ApexCrudFLSCheck.js';
41
41
  import { ApexRestEndpointCheck } from './impl/ApexRestEndpointCheck.js';
42
42
  import { VisualforceXssCheck } from './impl/VisualforceXssCheck.js';
43
+ import { LightningMessageChannelCheck } from './impl/LightningMessageChannelCheck.js';
43
44
  import { CertificateExpiryCheck } from './impl/CertificateExpiryCheck.js';
44
45
  import { InstalledPackagesCheck } from './impl/InstalledPackagesCheck.js';
45
46
  import { TrustedIPRangesCheck } from './impl/TrustedIPRangesCheck.js';
@@ -187,6 +188,7 @@ export const CHECKS = [
187
188
  new GuestExecutableApexCheck(), // reads apexBodies — guest-reachable Apex sharing
188
189
  new ApexRestEndpointCheck(), // reads apexBodies
189
190
  new VisualforceXssCheck(), // writes vfPageBodies
191
+ new LightningMessageChannelCheck(), // no deps
190
192
  new EventMonitoringCheck(), // writes eventLogSummary
191
193
  new GuestTrafficAnomalyCheck(), // reads eventLogSummary — anonymizer IPs, bursts, GraphQL recon in guest logs
192
194
  new MfaRegistrationCheck(), // writes mfaRegistrations
@@ -0,0 +1,22 @@
1
+ import { SfCommand } from '@salesforce/sf-plugins-core';
2
+ export interface IncidentCollectResult {
3
+ dir: string;
4
+ waves: number;
5
+ logsCollected: number;
6
+ logsMissing: number;
7
+ }
8
+ export default class AuditIncidentCollectCommand extends SfCommand<IncidentCollectResult> {
9
+ static summary: string;
10
+ static description: string;
11
+ static examples: string[];
12
+ static flags: {
13
+ 'target-org': import("@oclif/core/interfaces").OptionFlag<import("@salesforce/core").Org, import("@oclif/core/interfaces").CustomOptions>;
14
+ since: import("@oclif/core/interfaces").OptionFlag<number, import("@oclif/core/interfaces").CustomOptions>;
15
+ window: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
16
+ event: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
17
+ 'ip-ranges': import("@oclif/core/interfaces").OptionFlag<string[] | undefined, import("@oclif/core/interfaces").CustomOptions>;
18
+ output: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
19
+ };
20
+ run(): Promise<IncidentCollectResult>;
21
+ }
22
+ //# sourceMappingURL=collect.d.ts.map
@@ -0,0 +1,46 @@
1
+ import * as path from 'node:path';
2
+ import { SfCommand, Flags } from '@salesforce/sf-plugins-core';
3
+ import { buildAuditContext, resolveOrgInfo } from '../../../lib/wire.js';
4
+ import { collectBundle, defaultIncidentRoot } from '../../../incident/collect/collectBundle.js';
5
+ export default class AuditIncidentCollectCommand extends SfCommand {
6
+ static summary = 'Collect a guest-filtered evidence bundle for a Guest User Anomaly investigation';
7
+ static description = 'Read-only. Finds Guest User Anomaly waves, downloads the event logs for each wave day plus one baseline day either side, ' +
8
+ 'keeps only guest-user rows, and snapshots the audit trail, logins and guest configuration into a hashed bundle. ' +
9
+ 'Each raw log is staged on disk while it is filtered: allow ~600 MB free on a heavy day. ' +
10
+ 'Hosting classification uses only the --ip-ranges files you supply; nothing is downloaded from anywhere but the org.';
11
+ static examples = [
12
+ '<%= config.bin %> <%= command.id %> --target-org myOrg',
13
+ '<%= config.bin %> <%= command.id %> --target-org myOrg --since 120 --ip-ranges ./ip-ranges.json',
14
+ '<%= config.bin %> <%= command.id %> --target-org myOrg --window 2026-09-14/2026-09-16',
15
+ ];
16
+ static flags = {
17
+ 'target-org': Flags.requiredOrg(),
18
+ since: Flags.integer({ summary: 'Days of Guest User Anomaly events to read. Defaults to the oldest available, capped at 365.', default: 365, min: 1, max: 365 }),
19
+ window: Flags.string({ summary: 'Explicit day window instead of discovery: YYYY-MM-DD/YYYY-MM-DD or YYYY-MM-DD/PnD (max 31 days).', helpValue: '2026-09-14/2026-09-16' }),
20
+ event: Flags.string({ summary: 'Keep only the wave containing this EventIdentifier.' }),
21
+ 'ip-ranges': Flags.string({ summary: 'Local provider range file (AWS ip-ranges.json, GCP cloud.json, Azure service tags, or CIDR list). Repeatable.', multiple: true }),
22
+ output: Flags.string({ summary: 'Bundle directory. Defaults to ~/.sf/incidents/{orgId}/{timestamp}.' }),
23
+ };
24
+ async run() {
25
+ const { flags } = await this.parse(AuditIncidentCollectCommand);
26
+ const conn = flags['target-org'].getConnection('62.0');
27
+ const orgInfo = await resolveOrgInfo(conn);
28
+ const ctx = buildAuditContext(conn, orgInfo);
29
+ const dir = flags.output ?? path.join(defaultIncidentRoot(), orgInfo.id, new Date().toISOString().replace(/[:.]/g, '-'));
30
+ this.log(`Collecting incident bundle for ${orgInfo.name} (${orgInfo.id}) into ${dir}`);
31
+ let manifest;
32
+ try {
33
+ ({ manifest } = await collectBundle({ soql: ctx.soql, rest: ctx.rest, orgId: orgInfo.id, orgName: orgInfo.name }, { sinceDays: flags.since, window: flags.window, event: flags.event, ipRangeFiles: flags['ip-ranges'] ?? [], outputDir: dir, warn: (m) => this.warn(m) }));
34
+ }
35
+ catch (e) {
36
+ const message = e instanceof Error ? e.message : String(e);
37
+ this.error(`${message} (partial bundle kept at ${dir}; re-run with --output "${dir}" to resume)`, { exit: 1 });
38
+ }
39
+ const collected = manifest.logs.filter((l) => l.status === 'collected').length;
40
+ const missing = manifest.logs.length - collected;
41
+ this.log(`${manifest.waves.length} wave(s); ${collected} log file(s) collected, ${missing} not available.`);
42
+ this.log(`Next: sf audit incident report --bundle "${dir}"`);
43
+ return { dir, waves: manifest.waves.length, logsCollected: collected, logsMissing: missing };
44
+ }
45
+ }
46
+ //# sourceMappingURL=collect.js.map
@@ -0,0 +1,29 @@
1
+ import { SfCommand } from '@salesforce/sf-plugins-core';
2
+ import { type Branding } from '@cclabsnz/sf-core';
3
+ export interface IncidentReportResult {
4
+ written: string[];
5
+ }
6
+ export declare function parseFormats(input: string): string[];
7
+ export declare function writeReport(bundleDir: string, opts: {
8
+ formats: string[];
9
+ outputDir: string;
10
+ redact: boolean;
11
+ spikeRatio: number;
12
+ branding: Branding;
13
+ }): Promise<string[]>;
14
+ export default class AuditIncidentReportCommand extends SfCommand<IncidentReportResult> {
15
+ static summary: string;
16
+ static description: string;
17
+ static examples: string[];
18
+ static flags: {
19
+ bundle: import("@oclif/core/interfaces").OptionFlag<string, import("@oclif/core/interfaces").CustomOptions>;
20
+ format: import("@oclif/core/interfaces").OptionFlag<string, import("@oclif/core/interfaces").CustomOptions>;
21
+ output: import("@oclif/core/interfaces").OptionFlag<string, import("@oclif/core/interfaces").CustomOptions>;
22
+ redact: import("@oclif/core/interfaces").BooleanFlag<boolean>;
23
+ 'spike-ratio': import("@oclif/core/interfaces").OptionFlag<number, import("@oclif/core/interfaces").CustomOptions>;
24
+ branding: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
25
+ 'prepared-for': import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
26
+ };
27
+ run(): Promise<IncidentReportResult>;
28
+ }
29
+ //# sourceMappingURL=report.d.ts.map