@cclabsnz/sf-audit 1.12.0 → 1.14.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 (59) hide show
  1. package/CHANGELOG.md +109 -0
  2. package/README.md +12 -2
  3. package/lib/chains/CapabilityRegistry.d.ts +1 -1
  4. package/lib/chains/CapabilityRegistry.js +49 -1
  5. package/lib/chains/namedChains.js +230 -0
  6. package/lib/commands/audit/incident/collect.d.ts +22 -0
  7. package/lib/commands/audit/incident/collect.js +46 -0
  8. package/lib/commands/audit/incident/report.d.ts +29 -0
  9. package/lib/commands/audit/incident/report.js +87 -0
  10. package/lib/commands/audit/timeline.js +1 -1
  11. package/lib/incident/analyse/actions.d.ts +22 -0
  12. package/lib/incident/analyse/actions.js +73 -0
  13. package/lib/incident/analyse/actors.d.ts +56 -0
  14. package/lib/incident/analyse/actors.js +231 -0
  15. package/lib/incident/analyse/baseline.d.ts +24 -0
  16. package/lib/incident/analyse/baseline.js +66 -0
  17. package/lib/incident/analyse/configDelta.d.ts +33 -0
  18. package/lib/incident/analyse/configDelta.js +98 -0
  19. package/lib/incident/analyse/index.d.ts +41 -0
  20. package/lib/incident/analyse/index.js +68 -0
  21. package/lib/incident/analyse/outcomes.d.ts +28 -0
  22. package/lib/incident/analyse/outcomes.js +32 -0
  23. package/lib/incident/analyse/responses.d.ts +59 -0
  24. package/lib/incident/analyse/responses.js +201 -0
  25. package/lib/incident/analyse/verdict.d.ts +40 -0
  26. package/lib/incident/analyse/verdict.js +149 -0
  27. package/lib/incident/bundleIo.d.ts +34 -0
  28. package/lib/incident/bundleIo.js +74 -0
  29. package/lib/incident/collect/collectBundle.d.ts +21 -0
  30. package/lib/incident/collect/collectBundle.js +130 -0
  31. package/lib/incident/collect/discoverWaves.d.ts +15 -0
  32. package/lib/incident/collect/discoverWaves.js +90 -0
  33. package/lib/incident/collect/followUp.d.ts +14 -0
  34. package/lib/incident/collect/followUp.js +64 -0
  35. package/lib/incident/collect/orgErrors.d.ts +5 -0
  36. package/lib/incident/collect/orgErrors.js +11 -0
  37. package/lib/incident/collect/snapshotOrg.d.ts +18 -0
  38. package/lib/incident/collect/snapshotOrg.js +117 -0
  39. package/lib/incident/collect/streamGuestLogs.d.ts +17 -0
  40. package/lib/incident/collect/streamGuestLogs.js +116 -0
  41. package/lib/incident/csv.d.ts +32 -0
  42. package/lib/incident/csv.js +176 -0
  43. package/lib/incident/ipRanges.d.ts +23 -0
  44. package/lib/incident/ipRanges.js +64 -0
  45. package/lib/incident/model.d.ts +132 -0
  46. package/lib/incident/model.js +26 -0
  47. package/lib/incident/render/evidence.d.ts +15 -0
  48. package/lib/incident/render/evidence.js +52 -0
  49. package/lib/incident/render/html.d.ts +7 -0
  50. package/lib/incident/render/html.js +144 -0
  51. package/lib/incident/render/labels.d.ts +9 -0
  52. package/lib/incident/render/labels.js +22 -0
  53. package/lib/incident/render/markdown.d.ts +17 -0
  54. package/lib/incident/render/markdown.js +91 -0
  55. package/lib/incident/render/redact.d.ts +7 -0
  56. package/lib/incident/render/redact.js +62 -0
  57. package/lib/incident/text.d.ts +9 -0
  58. package/lib/incident/text.js +43 -0
  59. package/package.json +9 -6
package/CHANGELOG.md CHANGED
@@ -11,6 +11,115 @@ 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.14.0](https://github.com/cclabsnz/sf-audit-plugin/releases/tag/v1.14.0) — 2026-10-06
15
+
16
+ Two investigation commands for Real-Time Event Monitoring **Guest User Anomaly** alerts, and every
17
+ open dependency advisory cleared.
18
+
19
+ ### Added
20
+
21
+ - **`sf audit incident collect`** (read-only). Discovers anomaly *waves* (adjacent days on one
22
+ site), then for each wave day plus one baseline day either side streams the EventLogFiles, keeps
23
+ only guest-user rows, and snapshots the audit trail, guest configuration and logins from actor
24
+ addresses into a sha256-sealed bundle under `~/.sf/incidents/`. Collection is resumable (intact
25
+ logs are reused), a bundle is refused until it is sealed complete, and only "unavailable" or
26
+ "no permission" errors degrade to a stated gap; anything else stops the run.
27
+ - **`sf audit incident report`** (offline). Analyses a bundle and writes an HTML report (prints
28
+ to PDF), Markdown, JSON, and one evidence CSV behind every number cited. `--redact` truncates
29
+ addresses and replaces linked users' names and emails with their ids.
30
+ - **The analysis**:
31
+ - spike against baseline, counting controller calls only and never summing across log types;
32
+ - actor blocks, told apart from always-on proxies by their own history and the org's normal
33
+ busiest block;
34
+ - reply sizes via unambiguous AuraRequest/Sites joins, against an empty size learned per action;
35
+ - login outcomes and identity links, with shared egress (proxies, NAT) set aside;
36
+ - guest-access configuration changes between waves, including hardening applied to one site but
37
+ not another.
38
+ - **No false reassurance.** "No evidence of access" and "within baseline" are reported only when
39
+ the collected evidence supports them; otherwise a wave reads "not assessed" with the reason, and
40
+ every report states what it cannot tell you.
41
+
42
+ ### Security
43
+
44
+ - Cleared all open Dependabot advisories: `undici` 8.10.0 → 8.11.2, and `csv-parse` 5 → 7 by
45
+ raising `@salesforce/core` to `^9.3.0`, which carries the fix to installers, not just this repo.
46
+ - Raised the `fast-uri@3` override floor to `^3.1.8` and the `brace-expansion` floor to
47
+ `^5.0.11`. `pnpm audit --prod` and a packed consumer-tree `npm audit` both report zero
48
+ vulnerabilities.
49
+
50
+ ### Notes
51
+
52
+ - Not a security check: the check count stays at 92 and the security grade is unaffected.
53
+ - `--ip-ranges` reads provider range files you supply; the plugin never fetches them, so the org
54
+ stays the only network destination.
55
+
56
+ ## [v1.13.0](https://github.com/cclabsnz/sf-audit-plugin/releases/tag/v1.13.0) — 2026-09-25
57
+
58
+ Five new attack chains, and the correlation defect that kept them from being expressible.
59
+
60
+ ### Added
61
+
62
+ - **Five named attack chains**, taking the catalogue from eleven to sixteen:
63
+
64
+ - **Standing OAuth access outside every login control** (HIGH) — broad standing API access
65
+ (Full scope, a never-expiring refresh token, or both) combined with something that removes the
66
+ containment or the observation: a token matching no current connected app, a token unused for
67
+ months, or connected apps exempted from login IP enforcement. A refresh token is not a session.
68
+ Login controls engage once at authorisation and never again, and the exchange writes no
69
+ `LoginHistory` row, so this reach is invisible to a check that reads logins.
70
+ - **Self-service registration into an over-shared portal** (HIGH) — a site accepting
71
+ self-registration plus an external sharing model or portal-reachable code that gives any
72
+ account holder more than their own records. Every other chain starting from an authenticated
73
+ external user assumes the attacker already has an account.
74
+ - **Live session ID handed to an external endpoint** (HIGH) — an outbound message configured to
75
+ send the session ID, plus a reason a replayed session would be neither blocked nor recorded.
76
+ - **Org files served to anonymous callers, with no record of what left** (HIGH) — unauthenticated
77
+ file access plus no classification or monitoring. Deliberately asserts no pivot into org data,
78
+ because anonymous file access returns the file and stops.
79
+ - **Visualforce XSS pattern reaching a privileged session** (HIGH) — an unencoded markup pattern,
80
+ weakened browser-side controls, and privileged accounts to target. Asserts a reading order, not
81
+ exploitability: markup cannot show whether an attacker controls the rendered value.
82
+
83
+ ### Fixed
84
+
85
+ - **Eleven findings now grant the attacker capabilities they always carried.** `ChainEngine`
86
+ correlates on capabilities, so a finding absent from `CapabilityRegistry` could never be a step in
87
+ a named chain and never appeared in the emergent pass either. Forty-seven of the ninety-two checks
88
+ were in that state, and nothing reported it: an absent key is indistinguishable from a deliberate
89
+ decision that the finding grants nothing.
90
+
91
+ The eleven: `custom-settings-credentials`, `apex-rest-without-sharing`,
92
+ `apex-crud-fls-without-sharing`, `apex-crud-fls-missing`, `outbound-messages-session-id`,
93
+ `public-content-public-documents`, `public-content-public-static-resources`,
94
+ `content-links-no-expiry`, `content-links-no-password`,
95
+ `experience-cloud-site-self-registration` and `connected-app-full-scope`.
96
+
97
+ Two non-grants are deliberate and pinned by tests, since a non-grant is the easiest thing to
98
+ regress by helpfully adding a capability. Content links grant `data-read` but not
99
+ `unauth-foothold`, which would pair them with every bulk-read sink in the emergent pass and assert
100
+ a path between unrelated data. `connected-app-infinite-refresh-token`, `oauth-token-stale` and
101
+ `oauth-token-unmatched-app` grant nothing, because persistence and disuse are evidence about a
102
+ token rather than reach an attacker holds; they earn their place as chain steps instead.
103
+
104
+ - **`js-yaml` floor is stated rather than inherited from the lockfile**, so a consumer resolving the
105
+ tree independently cannot land on a version the `overrides` block was there to exclude.
106
+
107
+ ### Internal
108
+
109
+ - The consumer-tree audit now packs the tarball and audits what actually ships, which is
110
+ authoritative when it disagrees with the lockfile audit. The `jszip` MIT election is recorded so
111
+ the licence gate matches the shipped tree.
112
+ - The org-data commit guard widened past org ids to User and connected-app ids, `my.salesforce.com`
113
+ hosts, government email addresses and routable IPs, and the `commit-msg` hook was brought into
114
+ step with `pre-commit`.
115
+ - `repository.url` normalised so npm stops rewriting it on publish.
116
+ - Trust documentation no longer carries a zero-vulnerability claim, which went stale within a day.
117
+ - The attack-chain docs stated two different counts: the README feature list and the line above
118
+ the `docs/ATTACK-CHAINS.md` table both said eleven, while the table carried sixteen. The existing
119
+ drift guard asserted one phrasing in one file, which the README narrative satisfied on its own,
120
+ so neither stale count failed. `readme-chain-list.test.ts` now checks every stated count in both
121
+ docs against `NAMED_CHAINS.length` and names the file that disagrees.
122
+
14
123
  ## [v1.12.0](https://github.com/cclabsnz/sf-audit-plugin/releases/tag/v1.12.0) — 2026-09-07
15
124
 
16
125
  A check that shipped in the source but never ran, now registered, plus tests for three more.
package/README.md CHANGED
@@ -16,7 +16,7 @@
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
18
  - **92 read-only checks** across identity, access, data, code, integrations, monitoring, and Agentforce / GenAI
19
- - **Attack-chain correlation:** links individual findings into named, multi-step attack scenarios — eleven modelled chains, plus an emergent pass for combinations nobody has named yet (see [Attack chains](#attack-chains))
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
@@ -143,7 +143,7 @@ A list of findings is not a risk assessment. Three MEDIUM findings that combine
143
143
  unauthenticated path to bulk data matter more than a lone HIGH that leads nowhere, and reading a
144
144
  report severity-by-severity hides exactly that.
145
145
 
146
- So every audit correlates its findings into attack chains. **Eleven named chains** are hand-modelled
146
+ So every audit correlates its findings into attack chains. **Sixteen named chains** are hand-modelled
147
147
  scenarios — each with its own narrative and remediation, several naming the concrete request path an
148
148
  attacker would use. Where no named chain explains a combination, an emergent pass reports the
149
149
  remaining entry-point → outcome pairs as lower-confidence "potential attack paths", so a novel
@@ -218,6 +218,16 @@ To triage captured logs for abuse patterns, pair `events pull` with the companio
218
218
  **[sfelf-triage](https://github.com/cclabsnz/sfelf-triage)**, which reads this plugin's
219
219
  `~/.sf/event-baseline/<orgId>` layout directly.
220
220
 
221
+ ### Investigating a guest anomaly
222
+
223
+ `sf audit incident collect --target-org <alias>` finds Guest User Anomaly waves and saves a
224
+ guest-filtered evidence bundle to `~/.sf/incidents/`. `sf audit incident report --bundle <dir>`
225
+ analyses it offline and writes an HTML/Markdown/JSON report with evidence CSVs. Pass
226
+ `--ip-ranges` with provider range files you have downloaded to classify hosting; the plugin
227
+ never fetches them. Use `--redact` before sharing beyond the client's security team. Bundles in
228
+ `~/.sf/incidents` hold guest-traffic rows and linked-user details unencrypted, so handle them as
229
+ sensitive data.
230
+
221
231
  ## Requirements
222
232
 
223
233
  - Node.js 18+
@@ -6,7 +6,7 @@ export interface CapabilityEntry {
6
6
  }
7
7
  /**
8
8
  * The full attack model lives here: finding id → attacker capabilities it grants.
9
- * Keep this the single source of truth so the 88 checks stay untouched.
9
+ * Keep this the single source of truth so the 92 checks stay untouched.
10
10
  *
11
11
  * Every key MUST correspond to a finding id some check can actually emit, and every id referenced
12
12
  * by a named chain must be emittable too — a typo in either place fails silently (a key that
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * The full attack model lives here: finding id → attacker capabilities it grants.
3
- * Keep this the single source of truth so the 88 checks stay untouched.
3
+ * Keep this the single source of truth so the 92 checks stay untouched.
4
4
  *
5
5
  * Every key MUST correspond to a finding id some check can actually emit, and every id referenced
6
6
  * by a named chain must be emittable too — a typo in either place fails silently (a key that
@@ -103,6 +103,54 @@ export const CAPABILITY_REGISTRY = {
103
103
  // unexercised permission is not a capability an attacker holds today.
104
104
  'integration-least-privilege-escalation-permissions': { grants: ['code-exec', 'priv-esc'] },
105
105
  'integration-least-privilege-data-permissions': { grants: ['data-read-bulk'] },
106
+ // Credentials in custom settings — the third place secrets hide, after hardcoded literals and
107
+ // custom labels, both of which already grant here. A protected custom setting is readable by any
108
+ // Apex running in system context, so the reach is the same.
109
+ 'custom-settings-credentials': { grants: ['credential-theft'] },
110
+ // Apex reachable over REST, and Apex that skips CRUD/FLS. The registry already models the portal
111
+ // (`portal-exposed-apex-without-sharing`) and Flow (`flows-*-without-sharing`) variants of the
112
+ // same defect; the `@RestResource` door was the one left out. Sharing declarations and permission
113
+ // checks are independent controls, so a class can fail either: without-sharing skips record
114
+ // access, missing CRUD/FLS skips object and field access. Only the first is unattended write.
115
+ 'apex-rest-without-sharing': { grants: ['code-exec', 'data-read', 'data-write'] },
116
+ 'apex-crud-fls-without-sharing': { grants: ['data-read', 'data-write'] },
117
+ 'apex-crud-fls-missing': { grants: ['data-read'] },
118
+ // A live session ID posted to an external endpoint. This is a credential leaving the org through
119
+ // a supported feature rather than a flaw, which is exactly why it is easy to leave in place: the
120
+ // receiving endpoint can act as the running user until the session expires.
121
+ 'outbound-messages-session-id': { grants: ['credential-theft', 'external-egress'] },
122
+ // Anonymously fetchable files: public Documents and static resources, served from a URL that
123
+ // never reaches a login, and content distribution links that never expire or ask for a password.
124
+ //
125
+ // All four grant read and, deliberately, no 'unauth-foothold'. The temptation is real, because
126
+ // these genuinely are unauthenticated access to org content. But 'unauth-foothold' is a SOURCE
127
+ // capability, so the emergent pass pairs whatever holds it with every high-impact sink present:
128
+ // granting it here produces "unauthenticated foothold → bulk read" from nothing more than a
129
+ // public Document sitting next to an admin holding View All Data, which asserts a pivot that
130
+ // does not exist. A file is not a session. The guest findings grant a foothold because a guest
131
+ // *user context* can be pivoted from — it has a profile, permissions, and can invoke Apex —
132
+ // whereas anonymous file access returns the file and stops there. The unauthenticated angle is
133
+ // better asserted by a named chain that can state the mechanism than by a combinatorial pass
134
+ // that can only assert adjacency.
135
+ 'public-content-public-documents': { grants: ['data-read'] },
136
+ 'public-content-public-static-resources': { grants: ['data-read'] },
137
+ 'content-links-no-expiry': { grants: ['data-read'] },
138
+ 'content-links-no-password': { grants: ['data-read'] },
139
+ // Self-registration is how an attacker obtains the account that every external-sharing finding
140
+ // already assumes they have. On its own it is a supported feature and harmless; it earns a
141
+ // capability because 'sharing-model-external-*' grants reach to whoever holds an account, and
142
+ // this is the finding that says anyone may hold one.
143
+ 'experience-cloud-site-self-registration': { grants: ['low-trust-authenticated'] },
144
+ // The "Full" OAuth scope gives a token the same API reach as the user who authorised it. The
145
+ // never-expiring refresh token and the stale/unmatched token findings are deliberately absent:
146
+ // persistence and disuse are evidence about a token, not reach an attacker holds, and they earn
147
+ // their place as chain steps rather than as gate-opening grants.
148
+ 'connected-app-full-scope': { grants: ['data-read-bulk', 'data-write'] },
149
+ // The same reach, permanently. ConnectedAppScopeCheck emits this alongside the full-scope finding
150
+ // rather than instead of it, so the grant is currently redundant for opening a gate. It is here
151
+ // so the model stays correct if that ever becomes an either/or, and because a CRITICAL finding
152
+ // silently granting nothing is precisely the failure this registry exists to prevent.
153
+ 'connected-app-full-scope-infinite-token': { grants: ['data-read-bulk', 'data-write'] },
106
154
  };
107
155
  /** Resolve the effective capabilities for a finding (inline overrides registry; passed/inconclusive yield nothing). */
108
156
  export function capabilitiesFor(finding) {
@@ -295,5 +295,235 @@ export const NAMED_CHAINS = [
295
295
  return weakness.length > 0 && targets.length > 0 ? [...weakness, ...targets] : null;
296
296
  },
297
297
  },
298
+ {
299
+ id: 'oauth-standing-access',
300
+ title: 'Standing OAuth access outside every login control',
301
+ severity: 'HIGH',
302
+ narrative: 'A connected app holds broad standing API access, and something in the org means nobody would ' +
303
+ 'notice it being used. The distinction that matters here is that a refresh token is not a ' +
304
+ 'session. Login controls — MFA, login IP ranges, SSO, session timeout — engage once, at the ' +
305
+ 'moment the app is authorised, and never again: every later API call exchanges the refresh ' +
306
+ 'token for an access token without a login, so an org can enforce MFA on every human and still ' +
307
+ 'hand a token holder the same reach. Full scope makes that reach equal to the authorising ' +
308
+ 'user, including Modify All Data where that user is an admin, and a refresh token with no ' +
309
+ 'expiry makes it permanent until somebody revokes it. ' +
310
+ 'The token exchange produces no OAuth login row, so this access is absent from LoginHistory ' +
311
+ 'and invisible to the connected-app inactivity check — which is why a token that has gone ' +
312
+ 'unused for months, or that belongs to an app no longer in the connected app list, is the ' +
313
+ 'shape a forgotten or third-party integration leaves behind. That is the path the 2025 and ' +
314
+ '2026 campaigns against Salesforce customers took: the tokens were not stolen from the org, ' +
315
+ 'they were taken from the integration vendor and replayed against it, with no login and no ' +
316
+ 'user interaction anywhere in the victim org.',
317
+ remediation: 'Revoke first and tidy later. Any standing token whose app is not in the current connected app ' +
318
+ 'list, or that has not been used in months, should be revoked now rather than investigated ' +
319
+ 'first — re-authorising a live integration is a minor inconvenience, and a token is a working ' +
320
+ 'credential for as long as it exists. Then replace the Full scope with the specific scopes an ' +
321
+ 'integration actually uses, set a refresh token policy that expires on inactivity instead of ' +
322
+ 'never, and stop relaxing IP enforcement for connected apps, since that removes the one ' +
323
+ 'control still applying after authorisation. Treat a vendor breach notice as a trigger to ' +
324
+ 'revoke every token for that publisher rather than waiting to confirm your own org was ' +
325
+ 'touched: with no login row to search, absence of evidence is not evidence of absence here.',
326
+ match(_present, active) {
327
+ // Standing reach: a token that can act broadly, and keeps being able to.
328
+ const standing = byIds(active, [
329
+ 'connected-app-full-scope-infinite-token',
330
+ 'connected-app-full-scope',
331
+ 'connected-app-infinite-refresh-token',
332
+ ]);
333
+ if (standing.length === 0)
334
+ return null;
335
+ // What removes the containment or the observation. Any one of these turns standing access
336
+ // into access nobody is watching or limiting.
337
+ const uncontained = byIds(active, [
338
+ // Nobody is reviewing it: tokens with no matching app, or long unused.
339
+ 'oauth-token-unmatched-app', 'oauth-token-stale', 'oauth-token-no-app-inventory',
340
+ // Nothing is limiting it: the network control that survives authorisation, removed.
341
+ 'connected-apps-bypass-ip', 'connected-apps-relax-ip', 'unrestricted-connected-apps',
342
+ 'connected-apps-long-session-timeout', 'admin-no-ip-restrictions',
343
+ // The authorising identity is worth more than it needs to be, so the token inherits more.
344
+ 'integration-least-privilege-escalation-permissions',
345
+ 'integration-least-privilege-data-permissions',
346
+ 'api-client-permission-assigned',
347
+ ]);
348
+ if (uncontained.length === 0)
349
+ return null;
350
+ return [...standing, ...uncontained];
351
+ },
352
+ },
353
+ {
354
+ id: 'self-registration-foothold',
355
+ title: 'Self-service registration into an over-shared portal',
356
+ severity: 'HIGH',
357
+ narrative: 'A live Experience Cloud site accepts self-registration, and the external sharing model or ' +
358
+ 'portal-reachable code gives whoever holds an account more than their own records. Every other ' +
359
+ 'chain that starts from "an authenticated external user" assumes the attacker already has an ' +
360
+ 'account; this is the one that says anyone may have one, for the cost of an email address. ' +
361
+ 'The account is legitimate, so it arrives through the front door with a real session: MFA, ' +
362
+ 'login IP ranges and SSO all behave exactly as configured and none of them object, because ' +
363
+ 'nothing here is a bypass. What the attacker gets is decided entirely by the external OWD, ' +
364
+ 'the portal profile and whether the Apex or Flow reachable from the site enforces sharing. ' +
365
+ 'Self-registration alone is a supported feature and not a finding; the sharing model alone ' +
366
+ 'assumes an account the attacker may never obtain. The pair is the path.',
367
+ remediation: 'Decide which half to close, because either breaks the chain. Turning self-registration off, ' +
368
+ 'or putting an approval step in front of it, restores the assumption every other control ' +
369
+ 'depends on. Leaving it on means treating the self-registration profile as hostile input: ' +
370
+ 'set external OWD to Private and grant through sharing sets rather than org-wide defaults, ' +
371
+ 'and make sure Apex and Flows reachable from the site run with sharing. Check what the ' +
372
+ 'self-registration handler assigns as the default profile and licence — the exposure is ' +
373
+ 'whatever that profile can reach, and it is rarely reviewed after the site goes live.',
374
+ match(_present, active) {
375
+ const acquisition = byIds(active, ['experience-cloud-site-self-registration']);
376
+ if (acquisition.length === 0)
377
+ return null;
378
+ // What an account is worth once obtained. Deliberately excludes report-folder-access-public:
379
+ // it is real for internal users, but a self-registered portal account is a Customer Community
380
+ // licence, which generally has no report access at all, so including it would overstate reach.
381
+ const reach = byIds(active, [
382
+ 'sharing-model-external-read', 'sharing-model-external-write',
383
+ 'portal-exposed-apex-without-sharing',
384
+ 'flows-autolaunched-without-sharing', 'flows-screen-without-sharing',
385
+ 'apex-rest-without-sharing',
386
+ ]);
387
+ if (reach.length === 0)
388
+ return null;
389
+ // Social sign-on is a second way in rather than a requirement, so it joins as evidence when
390
+ // present but never gates the chain on its own.
391
+ const alsoOpen = byIds(active, ['auth-providers-social']);
392
+ return [...acquisition, ...reach, ...alsoOpen];
393
+ },
394
+ },
395
+ {
396
+ id: 'session-id-egress',
397
+ title: 'Live session ID handed to an external endpoint',
398
+ severity: 'HIGH',
399
+ narrative: 'A workflow outbound message is configured to include the Salesforce session ID, so every time ' +
400
+ 'it fires the org sends a working credential to a third-party endpoint. This is a supported ' +
401
+ 'option rather than a flaw, which is exactly why it survives: it was switched on to let the ' +
402
+ 'receiving system call back into Salesforce, and it never came off. The session it hands over ' +
403
+ 'acts as the outbound message\'s running user for as long as it is valid, and nothing about ' +
404
+ 'that request looks anomalous, because it is the org doing the sending. ' +
405
+ 'Whoever holds the endpoint holds the credential, which makes the org\'s exposure equal to the ' +
406
+ 'weakest party that has ever operated it — a vendor, a subcontractor, or whoever registered ' +
407
+ 'the domain after the integration was retired. The other findings in this chain are the ' +
408
+ 'reasons a replayed session would neither be blocked nor noticed.',
409
+ remediation: 'Clear the "Send Session ID" option on the outbound message and give the receiving system its ' +
410
+ 'own authenticated path instead: a connected app with a specific OAuth scope, or a named ' +
411
+ 'credential, both of which can be scoped and revoked without touching a user session. If an ' +
412
+ 'endpoint is cleartext http://, treat the session as already disclosed and change it first, ' +
413
+ 'since anything on the path has seen it. Confirm the outbound message\'s running user is the ' +
414
+ 'least-privileged account that can do the job, because that is the reach being handed out.',
415
+ match(_present, active) {
416
+ const leak = byIds(active, ['outbound-messages-session-id']);
417
+ if (leak.length === 0)
418
+ return null;
419
+ // Why a replayed session would not be stopped or seen. Any one is enough; the point of the
420
+ // chain is the credential leaving, and these say what happens next.
421
+ const unchecked = byIds(active, [
422
+ // Disclosed in transit, so compromising the endpoint is not even required.
423
+ 'outbound-messages-cleartext',
424
+ // Nothing binds or shortens the session that was handed over.
425
+ 'session-hardening-risks', 'session-security-deviations',
426
+ 'admin-no-ip-restrictions', 'broad-ip-ranges',
427
+ // Nothing would record the replay.
428
+ 'event-monitoring-disabled', 'siem-integration-not-detected', 'threat-detection-inactive',
429
+ ]);
430
+ if (unchecked.length === 0)
431
+ return null;
432
+ return [...leak, ...unchecked];
433
+ },
434
+ },
435
+ {
436
+ id: 'anonymous-file-exposure',
437
+ title: 'Org files served to anonymous callers, with no record of what left',
438
+ severity: 'HIGH',
439
+ narrative: 'Files hosted by the org are fetchable without authentication — public Documents or static ' +
440
+ 'resources, content distribution links that never expire or ask for a password, or a site ' +
441
+ 'that grants guests file access — and nothing in the org would establish what those files ' +
442
+ 'contained or who collected them. ' +
443
+ 'Files are the blind spot in a sharing model. Org-wide defaults, sharing rules and ' +
444
+ 'field-level security all govern records, and none of them apply to a static resource served ' +
445
+ 'from a URL. Static resources in particular tend to accumulate the things front-end code ' +
446
+ 'needs and nobody re-reads: configuration, endpoint lists, and occasionally an API key that ' +
447
+ 'was only ever meant to reach the browser. ' +
448
+ 'This chain deliberately claims less than the guest chains do. It does not assert a pivot ' +
449
+ 'into org data, because there is none — anonymous file access returns the file and stops. ' +
450
+ 'What it asserts is that content left the org outside every record control, and that the ' +
451
+ 'absence of classification or monitoring means the question "what was in it" has no answer ' +
452
+ 'available after the fact.',
453
+ remediation: 'Retrieve and read the exposed files before deciding how urgent this is: the exposure is ' +
454
+ 'whatever they actually contain, and that is knowable now in a way it will not be later. ' +
455
+ 'Then remove external availability from Documents and static resources that do not need it, ' +
456
+ 'set expiry and passwords on content distribution links, and turn off guest file access on ' +
457
+ 'sites that do not depend on it. Treat any credential found in a static resource as ' +
458
+ 'disclosed and rotate it rather than removing the file, since the file has already been ' +
459
+ 'served and may be cached anywhere.',
460
+ match(_present, active) {
461
+ const surface = byIds(active, [
462
+ 'public-content-public-documents', 'public-content-public-static-resources',
463
+ 'content-links-no-expiry', 'content-links-no-password', 'content-links-stale',
464
+ 'guest-site-options-file-access',
465
+ ]);
466
+ if (surface.length === 0)
467
+ return null;
468
+ // No way to answer "what was in it" or "who took it". Classification and monitoring only:
469
+ // content-links-stale is a subset of content-links-no-expiry, so counting it on both sides
470
+ // would let one check satisfy the conjunction by itself.
471
+ const unaccounted = byIds(active, [
472
+ 'data-classification-missing', 'data-encryption-not-detected',
473
+ 'event-monitoring-disabled', 'siem-integration-not-detected', 'threat-detection-inactive',
474
+ ]);
475
+ if (unaccounted.length === 0)
476
+ return null;
477
+ return [...surface, ...unaccounted];
478
+ },
479
+ },
480
+ {
481
+ id: 'xss-to-privileged-session',
482
+ title: 'Visualforce XSS pattern reaching a privileged session',
483
+ severity: 'HIGH',
484
+ narrative: 'Custom Visualforce markup contains a pattern that renders data without encoding it — ' +
485
+ 'escape="false", a merge field inside a <script> block without JSENCODE, or one in an href, ' +
486
+ 'src or action attribute — while the browser-side protections that would blunt an injected ' +
487
+ 'script are weakened, and the org contains accounts whose session is worth stealing. Script ' +
488
+ 'running in an administrator\'s session acts as that administrator: it inherits Modify All ' +
489
+ 'Data if they hold it, and the requests it makes are indistinguishable from theirs. ' +
490
+ 'What this chain does not claim is that the XSS is exploitable. The scan reads page markup, ' +
491
+ 'so it can show that a page renders something unencoded but not whether an attacker can ' +
492
+ 'influence what is rendered. A page interpolating a hard-coded label is a false positive and ' +
493
+ 'a page interpolating a record field an external user can set is not — and only reading the ' +
494
+ 'page tells you which. The chain is a prioritisation of which pages to read first, ordered ' +
495
+ 'by the fact that a privileged population exists to be targeted.',
496
+ remediation: 'Read the flagged pages before anything else, and ask one question of each: can a user who is ' +
497
+ 'not you influence the value being rendered? Where the answer is yes, encode at the output — ' +
498
+ 'HTMLENCODE, JSENCODE or URLENCODE according to where the value lands, since the correct ' +
499
+ 'function depends on the context, not the value. Separately, restore the session hardening ' +
500
+ 'settings that deviate from the Salesforce baseline and replace insecure http:// CSP trusted ' +
501
+ 'sites with https:// equivalents, both of which widen what an injected script can do once it ' +
502
+ 'runs.',
503
+ match(_present, active) {
504
+ const vector = byIds(active, [
505
+ 'visualforce-xss-escape-false',
506
+ 'visualforce-xss-js-merge-field',
507
+ 'visualforce-xss-attr-merge-field',
508
+ ]);
509
+ if (vector.length === 0)
510
+ return null;
511
+ // The browser-side controls that would otherwise contain an injected script. Excludes
512
+ // 'experience-csp-verify', which asks the operator to confirm a setting rather than reporting
513
+ // a weakness — treating an advisory as a confirmed gap would inflate the chain.
514
+ const weakened = byIds(active, ['session-hardening-risks', 'csp-trusted-sites-insecure']);
515
+ if (weakened.length === 0)
516
+ return null;
517
+ // Somebody whose session is worth the trouble.
518
+ const targets = byIds(active, [
519
+ 'users-super-admin-combo', 'privileged-access-shadow-admins',
520
+ 'users-modify-all-data', 'users-view-all-data',
521
+ 'separation-of-duties-self-escalation',
522
+ ]);
523
+ if (targets.length === 0)
524
+ return null;
525
+ return [...vector, ...weakened, ...targets];
526
+ },
527
+ },
298
528
  ];
299
529
  //# sourceMappingURL=namedChains.js.map
@@ -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