@cclabsnz/sf-audit 1.9.0 → 1.11.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.
package/CHANGELOG.md CHANGED
@@ -11,6 +11,64 @@ 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.11.0](https://github.com/cclabsnz/sf-audit-plugin/releases/tag/v1.11.0) — 2026-09-07
15
+
16
+ One new check, closing a blind spot that the SaaS token-theft campaigns of the last year
17
+ turn on: a connected app can hold a working key to your org while every existing check
18
+ reports it as dormant.
19
+
20
+ ### Added
21
+
22
+ - **`oauth-token-inventory`** — inventories standing OAuth authorisations from
23
+ `OauthToken`, so you can answer "which apps can act in this org right now, and for how
24
+ many users" without waiting for a login that will never come.
25
+
26
+ `connected-app-inactivity` reads `LoginHistory` and calls an app inactive after 90 days
27
+ with no OAuth login. That is the wrong signal for a refresh token: the app presents the
28
+ token, gets an access token back, and no `LoginType 'OAuth%'` row is written for the
29
+ exchange. So an app can be reported as dormant and low risk while still holding a
30
+ working credential. When a vendor is breached, the remediation is to revoke access and
31
+ refresh tokens rather than disable a login, and that requires an inventory nothing in
32
+ this plugin previously produced.
33
+
34
+ Emits three findings: an app holding live tokens that is absent from the connected app
35
+ inventory (MEDIUM), tokens unused for 90+ days or with no recorded last use
36
+ (MEDIUM/LOW), and the full per-app inventory (INFO), which is always emitted so the
37
+ report carries the revocation worklist even when nothing is wrong.
38
+
39
+ Token material is never selected. `OauthToken` exposes `AccessToken`, `RequestToken` and
40
+ `DeleteToken` as queryable strings, and findings are written to disk, so the exclusion is
41
+ enforced where the query is built rather than by convention, and asserted in the tests.
42
+
43
+ Degrades honestly rather than quietly: if `OauthToken` cannot be read the check goes
44
+ inconclusive instead of reporting an org with no standing tokens, and if
45
+ `ConnectedApplication` returns nothing the cross-reference is skipped rather than
46
+ flagging every app as unmatched.
47
+
48
+ Check count is now **91**.
49
+
50
+ ## [v1.10.0](https://github.com/cclabsnz/sf-audit-plugin/releases/tag/v1.10.0) — 2026-09-07
51
+
52
+ Two additions for callers that drive this plugin programmatically: find out what the audit
53
+ user can actually see *before* spending a run, and get the result back without paying for
54
+ the half of it that is passing checks and prose.
55
+
56
+ ### Added
57
+
58
+ - **`sf audit preflight`** — reports what this audit user will and will not be able to
59
+ establish, before a run is spent. Reads the caller's effective permissions from
60
+ `UserPermissionAccess` in a single query and names the checks that will return
61
+ inconclusive, with the grants that would fix them. The audit itself can only report a
62
+ permission gap *after* it has come back blind; this asks the same question up front.
63
+ The affected-check lists are derived from the registry's declared cache wiring rather
64
+ than hand-maintained, so a check added later is covered without editing the map.
65
+
66
+ - **`--digest`** on `sf audit security` — a compact result for programmatic callers.
67
+ Passing checks are counted but not listed, `detail` prose gives way to `remediation`,
68
+ and affected-item lists — unbounded, and the bulk of a large org's report — collapse to
69
+ a count plus a three-item sample. Attack chains survive intact. Composes with `--json`,
70
+ so an agent gets one command and compact stdout.
71
+
14
72
  ## [v1.9.0](https://github.com/cclabsnz/sf-audit-plugin/releases/tag/v1.9.0) — 2026-09-07
15
73
 
16
74
  Two compliance catalogs, three attack chains, and a restructured documentation set — but
package/README.md CHANGED
@@ -15,7 +15,7 @@
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
- - **90 read-only checks** across identity, access, data, code, integrations, monitoring, and Agentforce / GenAI
18
+ - **91 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 — eleven 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
@@ -44,7 +44,7 @@ guarantees here are checkable rather than asserted — see [Trust & verification
44
44
  sf audit security --target-org <orgAlias>
45
45
  ```
46
46
 
47
- Runs all 90 checks and writes an HTML report to the current directory. `sf audit list` prints every
47
+ Runs all 91 checks and writes an HTML report to the current directory. `sf audit list` prints every
48
48
  check id.
49
49
 
50
50
  | Flag | Default | |
@@ -52,6 +52,7 @@ check id.
52
52
  | `--format` / `-f` | `html` | `html`, `md`, `json`, `executive` — comma-separated |
53
53
  | `--fail-on` | (none) | Exit 1 if any finding is at or above `CRITICAL`/`HIGH`/`MEDIUM`/`LOW`. For CI |
54
54
  | `--fail-on-inconclusive` | `false` | Exit 3 if any check could not gather evidence. For CI |
55
+ | `--digest` | `false` | Compact result for programmatic callers — no passing checks, no prose, capped lists |
55
56
  | `--checks` | *(all)* | Run only these check ids |
56
57
  | `--frameworks` | `universal` | Compliance matrix scope for the executive report |
57
58
 
@@ -65,8 +66,14 @@ sf audit security --target-org myOrg --fail-on HIGH --fail-on-inconclusive
65
66
  # Branded, client-ready PDF-able report
66
67
  sf audit security --target-org myOrg --format executive --prepared-for "Acme Health"
67
68
 
69
+ # What can this audit user actually establish? Ask before spending a run
70
+ sf audit preflight --target-org myOrg
71
+
68
72
  # Machine-readable: result on stdout, progress logging suppressed
69
73
  sf audit security --target-org myOrg --json
74
+
75
+ # Compact result for an agent or script
76
+ sf audit security --target-org myOrg --json --digest
70
77
  ```
71
78
 
72
79
  ### Exit codes
@@ -87,7 +94,7 @@ All twelve flags, more examples, and what the executive report contains:
87
94
 
88
95
  ## What It Checks
89
96
 
90
- **90 read-only checks** across ten domains. Every finding is risk-rated CRITICAL → INFO, mapped to
97
+ **91 read-only checks** across ten domains. Every finding is risk-rated CRITICAL → INFO, mapped to
91
98
  compliance controls, and correlated into [attack chains](#attack-chains).
92
99
 
93
100
  | Domain | Checks |
@@ -96,7 +103,7 @@ compliance controls, and correlated into [attack chains](#attack-chains).
96
103
  | Users, Permissions & Privilege | 12 |
97
104
  | Data Access & Sharing | 11 |
98
105
  | Guest & External-Facing Access | 12 |
99
- | Integrations, Connected Apps & Deployments | 10 |
106
+ | Integrations, Connected Apps & Deployments | 11 |
100
107
  | Monitoring & Threat Detection | 10 |
101
108
  | Apex & Code Security | 9 |
102
109
  | AI & Agents (Agentforce / GenAI) | 6 |
@@ -196,7 +203,7 @@ Grade bands, the full config shape and worked examples: **[docs/SCORING.md](docs
196
203
 
197
204
  ## Other commands
198
205
 
199
- Beyond the audit itself, the plugin ships four commands. Each is documented in
206
+ Beyond the audit itself, the plugin ships five commands. Each is documented in
200
207
  **[docs/COMMANDS.md](docs/COMMANDS.md)**.
201
208
 
202
209
  | Command | What it does |
@@ -204,6 +211,7 @@ Beyond the audit itself, the plugin ships four commands. Each is documented in
204
211
  | `sf audit history` / `sf audit diff` | Every run auto-archives to `~/.sf/audit-history/{orgId}`. Show posture drift across runs as a table plus an HTML timeline, or diff any two report JSONs |
205
212
  | `sf audit events pull` | Capture 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. Idempotent, safe to cron |
206
213
  | `sf audit timeline` | Reconstruct one actor's activity across every captured event type, entirely offline. Refuses to expand a shared identity or join on a blank field, and always reports capture coverage first |
214
+ | `sf audit preflight` | Read the running user's effective permissions in one query and report which checks will produce a verdict and which will return inconclusive — **before** an audit is run |
207
215
  | `sf audit apps` | Read the `RestApi` event log to compare what each connected app actually *uses* against what its run-as user is *granted*, and emit a suggested least-privilege permission set |
208
216
 
209
217
  To triage captured logs for abuse patterns, pair `events pull` with the companion CLI
@@ -0,0 +1,14 @@
1
+ import type { AuditContext } from '@cclabsnz/sf-core';
2
+ import type { SecurityCheck, CheckResult } from '../SecurityCheck.js';
3
+ /** Queryable on OauthToken and permanently excluded: an audit report must not carry credentials. */
4
+ export declare const NEVER_SELECT: readonly ['AccessToken', 'RequestToken', 'DeleteToken'];
5
+ export declare class OauthTokenInventoryCheck implements SecurityCheck {
6
+ readonly id = "oauth-token-inventory";
7
+ readonly name = "Standing OAuth Token Inventory";
8
+ readonly category = "App Security";
9
+ readonly description = "Inventories live OAuth tokens per app: a standing refresh token grants API access without any new login";
10
+ readonly dependsOnCache: readonly ['connectedAppNames'];
11
+ run(ctx: AuditContext): Promise<CheckResult>;
12
+ private inconclusive;
13
+ }
14
+ //# sourceMappingURL=OauthTokenInventoryCheck.d.ts.map
@@ -0,0 +1,204 @@
1
+ import { describeFields } from '@cclabsnz/sf-core';
2
+ /**
3
+ * Priority order. `AppName` is the only one the check cannot work without.
4
+ *
5
+ * `OauthToken` also defines `AccessToken`, `RequestToken` and `DeleteToken`, all queryable
6
+ * strings. None of them appear here and none may ever be added: findings are written to an HTML
7
+ * or JSON report on disk, so selecting token material would turn an audit artefact into a
8
+ * credential file. `NEVER_SELECT` is asserted in the unit tests.
9
+ */
10
+ const PREFERRED_FIELDS = [
11
+ 'AppName',
12
+ 'UserId',
13
+ 'LastUsedDate',
14
+ 'UseCount',
15
+ 'CreatedDate',
16
+ ];
17
+ /** Queryable on OauthToken and permanently excluded: an audit report must not carry credentials. */
18
+ export const NEVER_SELECT = ['AccessToken', 'RequestToken', 'DeleteToken'];
19
+ /** Ceiling on rows pulled. Large orgs hold a token per user per app, which multiplies fast. */
20
+ const MAX_TOKEN_ROWS = 5000;
21
+ /** A token unused for this long is a standing grant nobody is exercising. */
22
+ const STALE_DAYS = 90;
23
+ /**
24
+ * Salesforce-owned clients that hold tokens in ordinary orgs and are absent from
25
+ * `ConnectedApplication` by design, so matching them against it always "fails". Lower-cased
26
+ * for comparison. A floor, not a complete list: an unrecognised first-party client is
27
+ * reported rather than hidden, which is the safe direction to be wrong in. Add names here as
28
+ * they are confirmed to be Salesforce-owned.
29
+ */
30
+ const FIRST_PARTY_APPS = new Set([
31
+ 'salesforce cli',
32
+ 'salesforce mobile dashboards',
33
+ 'salesforce for outlook',
34
+ 'salesforce dataloader',
35
+ 'dataloader partner',
36
+ 'dataloader bulk',
37
+ 'workbench',
38
+ 'sfdx cli',
39
+ 'salesforce inspector',
40
+ ]);
41
+ export class OauthTokenInventoryCheck {
42
+ id = 'oauth-token-inventory';
43
+ name = 'Standing OAuth Token Inventory';
44
+ category = 'App Security';
45
+ description = 'Inventories live OAuth tokens per app: a standing refresh token grants API access without any new login';
46
+ dependsOnCache = ['connectedAppNames'];
47
+ async run(ctx) {
48
+ const findings = [];
49
+ const setupUrl = `${ctx.orgInfo.instanceUrl}/lightning/setup/ConnectedApplication/home`;
50
+ let fields = [];
51
+ try {
52
+ const described = await describeFields(ctx.rest, 'OauthToken', PREFERRED_FIELDS);
53
+ // Enforce the exclusion here rather than trusting the preferred list to stay clean.
54
+ // describeFields returns what the org defines, and this check builds a SELECT that ends
55
+ // up in a report file on disk, so the filter belongs at the point the query is built.
56
+ fields = described.filter((f) => !NEVER_SELECT.some((n) => n.toLowerCase() === f.toLowerCase()));
57
+ }
58
+ catch {
59
+ findings.push(this.inconclusive('OauthToken could not be described'));
60
+ return { findings };
61
+ }
62
+ if (!fields.includes('AppName')) {
63
+ findings.push(this.inconclusive('OauthToken does not expose AppName in this org, so tokens cannot be attributed to an app'));
64
+ return { findings };
65
+ }
66
+ let records = [];
67
+ try {
68
+ const result = await ctx.soql.query(`SELECT ${fields.join(', ')} FROM OauthToken LIMIT ${MAX_TOKEN_ROWS}`);
69
+ records = result.records ?? [];
70
+ }
71
+ catch {
72
+ findings.push(this.inconclusive('OauthToken was not readable. Standing OAuth grants cannot be inventoried without it'));
73
+ return { findings };
74
+ }
75
+ if (records.length === 0) {
76
+ findings.push({
77
+ id: 'oauth-token-inventory-none',
78
+ category: this.category,
79
+ riskLevel: 'LOW',
80
+ passed: true,
81
+ title: 'No standing OAuth tokens found',
82
+ detail: 'No rows were returned from OauthToken, so no app currently holds a standing OAuth authorisation in this org.',
83
+ remediation: 'Re-check after authorising any new integration.',
84
+ });
85
+ return { findings };
86
+ }
87
+ // Aggregate client-side rather than with GROUP BY. Aggregate support varies across these
88
+ // system objects, and a rejected GROUP BY would surface as "no tokens" rather than an error.
89
+ const byApp = new Map();
90
+ for (const r of records) {
91
+ const app = (r.AppName ?? '').trim();
92
+ if (!app)
93
+ continue;
94
+ const key = app.toLowerCase();
95
+ let summary = byApp.get(key);
96
+ if (!summary) {
97
+ summary = { app, tokens: 0, users: new Set(), lastUsed: null };
98
+ byApp.set(key, summary);
99
+ }
100
+ summary.tokens += 1;
101
+ if (r.UserId)
102
+ summary.users.add(r.UserId);
103
+ const used = r.LastUsedDate ?? null;
104
+ if (used && (summary.lastUsed === null || used > summary.lastUsed)) {
105
+ summary.lastUsed = used;
106
+ }
107
+ }
108
+ const summaries = [...byApp.values()].sort((a, b) => b.tokens - a.tokens);
109
+ const truncated = records.length >= MAX_TOKEN_ROWS;
110
+ // The finding that matters: a live token whose app shows no recent interactive OAuth login.
111
+ // connectedAppNames is what ConnectedAppsCheck saw in ConnectedApplication; an app holding
112
+ // tokens that is absent from it is a grant with no current app definition behind it.
113
+ const knownApps = new Set((ctx.cache.connectedAppNames ?? []).map((n) => n.toLowerCase()));
114
+ // With an empty inventory every token is trivially "unmatched", which would emit a wall of
115
+ // findings for apps that may all be benign, and would break --fail-on for anyone whose
116
+ // audit user cannot read ConnectedApplication. An org whose read returned nothing has not
117
+ // been shown to have a problem, it has failed to provide the evidence, so the comparison
118
+ // is skipped rather than assumed.
119
+ const canCrossReference = knownApps.size > 0;
120
+ const unmatched = canCrossReference
121
+ ? summaries.filter((s) => !knownApps.has(s.app.toLowerCase()) && !FIRST_PARTY_APPS.has(s.app.toLowerCase()))
122
+ : [];
123
+ const cutoff = new Date(Date.now() - STALE_DAYS * 86_400_000).toISOString();
124
+ const stale = summaries.filter((s) => s.lastUsed !== null && s.lastUsed < cutoff);
125
+ const neverUsed = summaries.filter((s) => s.lastUsed === null);
126
+ if (unmatched.length > 0) {
127
+ findings.push({
128
+ id: 'oauth-token-unmatched-app',
129
+ category: this.category,
130
+ riskLevel: 'MEDIUM',
131
+ title: `${unmatched.length} app(s) hold live OAuth tokens but do not appear in the connected app inventory`,
132
+ detail: `${unmatched.length} app name(s) on live OauthToken rows were not among the ${knownApps.size} connected apps read from ConnectedApplication. ` +
133
+ 'A standing token whose app definition is missing, renamed, or installed outside the connected app list is access nobody is reviewing. ' +
134
+ 'Because a refresh token is exchanged without producing an OAuth login row, this access does not appear in LoginHistory and will not be reported by the inactivity check.',
135
+ remediation: 'Identify each app. Where it is not a recognised integration with a named owner, revoke its tokens from the user detail page or via the OAuth Connected Apps Usage page, which invalidates the refresh token. Deactivating a user does not revoke a token that a third party holds.',
136
+ affectedItems: unmatched.map((s) => ({
137
+ label: s.app,
138
+ url: setupUrl,
139
+ note: `${s.tokens} token(s), ${s.users.size} user(s), last used ${s.lastUsed ?? 'never recorded'}`,
140
+ })),
141
+ });
142
+ }
143
+ if (!canCrossReference) {
144
+ findings.push({
145
+ id: 'oauth-token-no-app-inventory',
146
+ category: this.category,
147
+ riskLevel: 'INFO',
148
+ inconclusive: true,
149
+ title: 'Standing tokens could not be cross-referenced against the connected app inventory',
150
+ detail: 'ConnectedApplication returned no rows, so tokens cannot be matched to a reviewable app definition. The inventory below is still accurate; only the comparison is missing.',
151
+ remediation: 'Grant the audit user read access to ConnectedApplication, then re-run so standing tokens can be matched against declared apps.',
152
+ });
153
+ }
154
+ if (stale.length > 0 || neverUsed.length > 0) {
155
+ const items = [...stale, ...neverUsed];
156
+ findings.push({
157
+ id: 'oauth-token-stale',
158
+ category: this.category,
159
+ riskLevel: items.length > 5 ? 'MEDIUM' : 'LOW',
160
+ title: `${items.length} app(s) hold OAuth tokens unused for ${STALE_DAYS}+ days`,
161
+ detail: `${stale.length} app(s) last used a token more than ${STALE_DAYS} days ago and ${neverUsed.length} have no recorded last-used date. ` +
162
+ 'An unused token is still a working credential. If the app or its vendor is compromised, the token is replayed against this org with no login and no user interaction.',
163
+ remediation: 'Revoke tokens for integrations that are no longer in use. Treat a vendor breach notification as a trigger to revoke every token for that publisher rather than waiting to confirm your own org was touched.',
164
+ affectedItems: items.map((s) => ({
165
+ label: s.app,
166
+ url: setupUrl,
167
+ note: `${s.tokens} token(s), ${s.users.size} user(s), last used ${s.lastUsed ?? 'never recorded'}`,
168
+ })),
169
+ });
170
+ }
171
+ findings.push({
172
+ id: 'oauth-token-inventory',
173
+ category: this.category,
174
+ riskLevel: 'INFO',
175
+ title: `${summaries.length} app(s) hold ${records.length}${truncated ? '+' : ''} standing OAuth token(s)`,
176
+ detail: `Live OAuth authorisations by app, from OauthToken. Each row is an access or refresh token that can be exchanged for API access without a new login.` +
177
+ (truncated
178
+ ? ` Row cap of ${MAX_TOKEN_ROWS} was reached, so this is a floor rather than a complete count.`
179
+ : '') +
180
+ (fields.length < PREFERRED_FIELDS.length
181
+ ? ` This org exposes ${fields.length} of ${PREFERRED_FIELDS.length} OauthToken fields, so some columns below are blank.`
182
+ : ''),
183
+ remediation: 'Keep this list to integrations with a named owner and a business justification, and re-run it after any vendor breach disclosure.',
184
+ affectedItems: summaries.map((s) => ({
185
+ label: s.app,
186
+ url: setupUrl,
187
+ note: `${s.tokens} token(s), ${s.users.size} user(s), last used ${s.lastUsed ?? 'never recorded'}`,
188
+ })),
189
+ });
190
+ return { findings };
191
+ }
192
+ inconclusive(reason) {
193
+ return {
194
+ id: 'oauth-token-inventory-inconclusive',
195
+ category: this.category,
196
+ riskLevel: 'INFO',
197
+ inconclusive: true,
198
+ title: 'Standing OAuth tokens could not be inventoried',
199
+ detail: `${reason}. Apps holding refresh tokens cannot be listed, and those grants do not appear in LoginHistory.`,
200
+ remediation: 'Grant the audit user read access to OauthToken, then re-run. Until then, review OAuth Connected Apps Usage in Setup by hand.',
201
+ };
202
+ }
203
+ }
204
+ //# sourceMappingURL=OauthTokenInventoryCheck.js.map
@@ -45,6 +45,7 @@ import { TrustedIPRangesCheck } from './impl/TrustedIPRangesCheck.js';
45
45
  import { AnonymousApexAuditCheck } from './impl/AnonymousApexAuditCheck.js';
46
46
  import { DebugLogAccessCheck } from './impl/DebugLogAccessCheck.js';
47
47
  import { ConnectedAppInactivityCheck } from './impl/ConnectedAppInactivityCheck.js';
48
+ import { OauthTokenInventoryCheck } from './impl/OauthTokenInventoryCheck.js';
48
49
  import { MyDomainLoginPolicyCheck } from './impl/MyDomainLoginPolicyCheck.js';
49
50
  import { InternalUserMfaCheck } from './impl/InternalUserMfaCheck.js';
50
51
  import { MfaRegistrationCheck } from './impl/MfaRegistrationCheck.js';
@@ -179,6 +180,7 @@ export const CHECKS = [
179
180
  new DeploymentIdentityCheck(), // reads connectedAppNames
180
181
  new ApexLoggingCheck(), // reads apexBodies + scheduledApexClassNames
181
182
  new ConnectedAppInactivityCheck(), // reads connectedAppNames
183
+ new OauthTokenInventoryCheck(), // reads connectedAppNames; standing tokens LoginHistory cannot see
182
184
  new ApexCrudFLSCheck(), // reads apexBodies
183
185
  new GuestExecutableApexCheck(), // reads apexBodies — guest-reachable Apex sharing
184
186
  new ApexRestEndpointCheck(), // reads apexBodies
@@ -0,0 +1,13 @@
1
+ import { SfCommand } from '@salesforce/sf-plugins-core';
2
+ import { type PreflightResult } from '../../preflight/permissionMap.js';
3
+ export default class AuditPreflightCommand extends SfCommand<PreflightResult> {
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
+ };
10
+ run(): Promise<PreflightResult>;
11
+ private printPreflight;
12
+ }
13
+ //# sourceMappingURL=preflight.d.ts.map
@@ -0,0 +1,56 @@
1
+ import { SfCommand, Flags } from '@salesforce/sf-plugins-core';
2
+ import { CHECKS } from '../../checks/registry.js';
3
+ import { buildPreflight } from '../../preflight/permissionMap.js';
4
+ import { readEffectivePermissions } from '../../preflight/readPermissions.js';
5
+ import { buildApiClients } from '../../lib/wire.js';
6
+ export default class AuditPreflightCommand extends SfCommand {
7
+ static summary = 'Report what this audit user will and will not be able to establish';
8
+ static description = "Reads the running user's effective permissions in a single query and reports which checks will " +
9
+ 'produce a verdict and which will return inconclusive, before an audit is run. The audit itself can ' +
10
+ 'only report a permission gap after it has already come back blind; this answers the same question ' +
11
+ 'up front, while it is still cheap to fix. Read-only, and opens no more than one query.';
12
+ static examples = [
13
+ '<%= config.bin %> <%= command.id %> --target-org myOrg',
14
+ '<%= config.bin %> <%= command.id %> --target-org myOrg --json',
15
+ ];
16
+ static flags = {
17
+ 'target-org': Flags.requiredOrg(),
18
+ };
19
+ async run() {
20
+ const { flags } = await this.parse(AuditPreflightCommand);
21
+ const conn = flags['target-org'].getConnection();
22
+ const { soql } = buildApiClients(conn);
23
+ const granted = await readEffectivePermissions(soql);
24
+ const preflight = buildPreflight(granted, CHECKS);
25
+ this.printPreflight(preflight);
26
+ return preflight;
27
+ }
28
+ printPreflight(p) {
29
+ this.log('');
30
+ if (p.missing.length === 0) {
31
+ this.log(` All ${CHECKS.length} checks can gather evidence. Nothing to grant.`);
32
+ this.log('');
33
+ return;
34
+ }
35
+ this.log(` ${p.willRun} of ${CHECKS.length} checks can gather evidence.`);
36
+ if (p.willBeInconclusive.length > 0) {
37
+ this.log(` ${p.willBeInconclusive.length} will return inconclusive as things stand.`);
38
+ }
39
+ this.log('');
40
+ this.log(' Missing permissions');
41
+ this.log(' ───────────────────');
42
+ for (const m of p.missing) {
43
+ this.log(` ${m.blocking ? '[blocking] ' : ''}${m.label} (${m.permission})`);
44
+ this.log(` ${m.impact}`);
45
+ if (m.affectedChecks.length > 0) {
46
+ this.log(` Affects ${m.affectedChecks.length} check${m.affectedChecks.length !== 1 ? 's' : ''}: ${m.affectedChecks.join(', ')}`);
47
+ }
48
+ this.log('');
49
+ }
50
+ if (!p.canRun) {
51
+ this.log(' The audit cannot run at all until the blocking permission is granted.');
52
+ this.log('');
53
+ }
54
+ }
55
+ }
56
+ //# sourceMappingURL=preflight.js.map
@@ -1,6 +1,7 @@
1
1
  import { SfCommand } from '@salesforce/sf-plugins-core';
2
2
  import type { AuditResult } from '../../findings/AuditResult.js';
3
- export default class SecurityAuditCommand extends SfCommand<AuditResult> {
3
+ import { type AuditDigest } from '../../findings/digest.js';
4
+ export default class SecurityAuditCommand extends SfCommand<AuditResult | AuditDigest> {
4
5
  static summary: string;
5
6
  static description: string;
6
7
  static examples: string[];
@@ -9,6 +10,7 @@ export default class SecurityAuditCommand extends SfCommand<AuditResult> {
9
10
  format: import("@oclif/core/interfaces").OptionFlag<string, import("@oclif/core/interfaces").CustomOptions>;
10
11
  output: import("@oclif/core/interfaces").OptionFlag<string, import("@oclif/core/interfaces").CustomOptions>;
11
12
  'fail-on': import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
13
+ digest: import("@oclif/core/interfaces").BooleanFlag<boolean>;
12
14
  'fail-on-inconclusive': import("@oclif/core/interfaces").BooleanFlag<boolean>;
13
15
  checks: import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
14
16
  'scoring-config': import("@oclif/core/interfaces").OptionFlag<string | undefined, import("@oclif/core/interfaces").CustomOptions>;
@@ -18,7 +20,7 @@ export default class SecurityAuditCommand extends SfCommand<AuditResult> {
18
20
  frameworks: import("@oclif/core/interfaces").OptionFlag<string, import("@oclif/core/interfaces").CustomOptions>;
19
21
  'resolve-domains': import("@oclif/core/interfaces").BooleanFlag<boolean>;
20
22
  };
21
- run(): Promise<AuditResult>;
23
+ run(): Promise<AuditResult | AuditDigest>;
22
24
  /** Resolve --checks to the checks to run, erroring on any unknown ID. */
23
25
  private resolveChecks;
24
26
  /** Resolve --format to a validated list, erroring on any unknown format. */
@@ -13,6 +13,7 @@ import { buildAuditContext, resolveOrgInfo } from '../../lib/wire.js';
13
13
  import { loadScoringConfig } from '../../findings/loadScoringConfig.js';
14
14
  import { HistoryStore } from '../../history/HistoryStore.js';
15
15
  import { EXIT_FINDINGS, EXIT_INCONCLUSIVE, resolveExitCode, violationsFor } from '../../findings/exitCode.js';
16
+ import { buildDigest } from '../../findings/digest.js';
16
17
  const RENDERERS = {
17
18
  html: new HtmlRenderer(),
18
19
  md: new MarkdownRenderer(),
@@ -42,6 +43,10 @@ export default class SecurityAuditCommand extends SfCommand {
42
43
  summary: 'Exit with code 1 if any finding is at or above this severity.',
43
44
  options: ['CRITICAL', 'HIGH', 'MEDIUM', 'LOW'],
44
45
  }),
46
+ digest: Flags.boolean({
47
+ summary: 'Return a compact, token-cheap result: no passing checks, no detail prose, capped affected lists.',
48
+ default: false,
49
+ }),
45
50
  'fail-on-inconclusive': Flags.boolean({
46
51
  summary: 'Exit with code 3 if any check could not gather evidence. Off by default.',
47
52
  default: false,
@@ -114,8 +119,10 @@ export default class SecurityAuditCommand extends SfCommand {
114
119
  this.printSummary(result);
115
120
  this.log('');
116
121
  this.log(' Deep dives: https://softwareinsights.dev · Remediation help: https://cloudcounsel.co.nz');
122
+ // Exit code is resolved from the full result: the digest drops passing checks,
123
+ // which the threshold logic must still be able to see and discount.
117
124
  this.applyExitCode(result, flags['fail-on'], flags['fail-on-inconclusive']);
118
- return result;
125
+ return flags.digest ? buildDigest(result) : result;
119
126
  }
120
127
  /** Resolve --checks to the checks to run, erroring on any unknown ID. */
121
128
  resolveChecks(raw) {
@@ -49,6 +49,7 @@ const BASE_CHECK_CONTROL_MAP = {
49
49
  'anonymous-apex-audit': ['OWASP-A09', 'SOC2-CC7.2', 'ISO-A.8.15'],
50
50
  'debug-log-access': ['OWASP-A09', 'SOC2-CC7.2', 'ISO-A.8.15'],
51
51
  'connected-app-inactivity': ['OWASP-A05', 'SOC2-CC6.6', 'ISO-A.5.18'],
52
+ 'oauth-token-inventory': ['OWASP-A05', 'SOC2-CC6.6', 'ISO-A.5.18'],
52
53
  'my-domain-login-policy': ['OWASP-A07', 'SOC2-CC6.1', 'ISO-A.8.3', 'SBS-AUTH-001'],
53
54
  'high-assurance-session': ['OWASP-A07', 'SOC2-CC6.1', 'ISO-A.8.3'],
54
55
  'enhanced-domains': ['OWASP-A05', 'SOC2-CC6.1', 'ISO-A.8.26'],
@@ -130,7 +131,7 @@ const DOMAIN = {
130
131
  'debug-log-access', 'transaction-security-policy', 'threat-detection', 'guest-traffic-anomaly',
131
132
  'login-anomaly'],
132
133
  devSecurity: ['code-security', 'visualforce-xss', 'scheduled-apex'],
133
- network: ['remote-sites', 'csp-trusted-sites', 'connected-apps', 'connected-app-scope', 'connected-app-inactivity', 'cors-allowlist',
134
+ network: ['remote-sites', 'csp-trusted-sites', 'connected-apps', 'connected-app-scope', 'connected-app-inactivity', 'oauth-token-inventory', 'cors-allowlist',
134
135
  'email-security', 'outbound-messages', 'experience-csp'],
135
136
  dataGovernance: ['data-classification', 'field-history-tracking', 'sandbox-data-masking'],
136
137
  configGovernance: ['health-check', 'api-limits', 'release-updates', 'legacy-api-version', 'installed-packages', 'deployment-identity', 'session-hardening'],
@@ -44,6 +44,7 @@ export const CHECK_META = {
44
44
  'anonymous-apex-audit': { effort: 'quick', impact: 'Anonymous Apex execution in production can run arbitrary privileged code leaving little trace.' },
45
45
  'debug-log-access': { effort: 'quick', impact: 'Active high-detail debug traces capture sensitive field values readable by anyone with log access.' },
46
46
  'connected-app-inactivity': { effort: 'quick', impact: 'Stale connected apps remain authorized attack surface long after they’re abandoned.' },
47
+ 'oauth-token-inventory': { effort: 'quick', impact: 'A standing refresh token is replayed for API access without any login, so a breached vendor keeps working access.' },
47
48
  'my-domain-login-policy': { effort: 'quick', impact: 'Allowing login.salesforce.com login bypasses My Domain SSO enforcement.' },
48
49
  'high-assurance-session': { effort: 'moderate', impact: 'Admin-capable apps without short or high-assurance sessions let a hijacked session retain elevated rights.' },
49
50
  'enhanced-domains': { effort: 'moderate', impact: 'Without Enhanced Domains, cross-org cookie leakage and URL spoofing become possible.' },
@@ -0,0 +1,50 @@
1
+ import type { RiskLevel } from '@cclabsnz/sf-core';
2
+ import type { AttackChain } from '../chains/AttackChain.js';
3
+ import type { AuditResult } from './AuditResult.js';
4
+ export interface DigestFinding {
5
+ checkId?: string;
6
+ riskLevel: RiskLevel;
7
+ title: string;
8
+ remediation: string;
9
+ complianceTags?: string[];
10
+ /** Total affected items. Present only when the finding named any. */
11
+ affectedCount?: number;
12
+ /** First few affected labels, for orientation. Never the whole list. */
13
+ affectedSample?: string[];
14
+ }
15
+ export interface DigestInconclusive {
16
+ checkId?: string;
17
+ title: string;
18
+ }
19
+ export interface DigestCounts {
20
+ critical: number;
21
+ high: number;
22
+ medium: number;
23
+ low: number;
24
+ info: number;
25
+ passed: number;
26
+ inconclusive: number;
27
+ }
28
+ export interface AuditDigest {
29
+ orgId: string;
30
+ orgName: string;
31
+ isSandbox: boolean;
32
+ generatedAt: Date;
33
+ healthScore: number;
34
+ grade: AuditResult['grade'];
35
+ counts: DigestCounts;
36
+ findings: DigestFinding[];
37
+ inconclusive: DigestInconclusive[];
38
+ attackChains: AttackChain[];
39
+ }
40
+ /**
41
+ * A token-cheap view of an audit, for callers that reason over the result rather
42
+ * than read it.
43
+ *
44
+ * Passing checks are counted but not listed, `detail` prose is dropped in favour of
45
+ * `remediation`, and affected-item lists — which are unbounded and dominate a large
46
+ * org's report — collapse to a count plus a short sample. Attack chains survive
47
+ * intact: there are few of them and they carry the analysis.
48
+ */
49
+ export declare function buildDigest(result: AuditResult): AuditDigest;
50
+ //# sourceMappingURL=digest.d.ts.map
@@ -0,0 +1,56 @@
1
+ /** How many affected-item labels to keep before falling back to a bare count. */
2
+ const SAMPLE_LIMIT = 3;
3
+ const isActive = (f) => f.passed !== true && f.inconclusive !== true;
4
+ function toDigestFinding(f) {
5
+ const out = {
6
+ checkId: f.checkId,
7
+ riskLevel: f.riskLevel,
8
+ title: f.title,
9
+ remediation: f.remediation,
10
+ };
11
+ if (f.complianceTags !== undefined)
12
+ out.complianceTags = f.complianceTags;
13
+ if (f.affectedItems !== undefined && f.affectedItems.length > 0) {
14
+ out.affectedCount = f.affectedItems.length;
15
+ out.affectedSample = f.affectedItems.slice(0, SAMPLE_LIMIT).map((i) => i.label);
16
+ }
17
+ return out;
18
+ }
19
+ function countBy(findings) {
20
+ const counts = { critical: 0, high: 0, medium: 0, low: 0, info: 0, passed: 0, inconclusive: 0 };
21
+ for (const f of findings) {
22
+ if (f.passed === true)
23
+ counts.passed += 1;
24
+ else if (f.inconclusive === true)
25
+ counts.inconclusive += 1;
26
+ else
27
+ counts[f.riskLevel.toLowerCase()] += 1;
28
+ }
29
+ return counts;
30
+ }
31
+ /**
32
+ * A token-cheap view of an audit, for callers that reason over the result rather
33
+ * than read it.
34
+ *
35
+ * Passing checks are counted but not listed, `detail` prose is dropped in favour of
36
+ * `remediation`, and affected-item lists — which are unbounded and dominate a large
37
+ * org's report — collapse to a count plus a short sample. Attack chains survive
38
+ * intact: there are few of them and they carry the analysis.
39
+ */
40
+ export function buildDigest(result) {
41
+ return {
42
+ orgId: result.orgId,
43
+ orgName: result.orgName,
44
+ isSandbox: result.isSandbox,
45
+ generatedAt: result.generatedAt,
46
+ healthScore: result.healthScore,
47
+ grade: result.grade,
48
+ counts: countBy(result.findings),
49
+ findings: result.findings.filter(isActive).map(toDigestFinding),
50
+ inconclusive: result.findings
51
+ .filter((f) => f.inconclusive === true)
52
+ .map((f) => ({ checkId: f.checkId, title: f.title })),
53
+ attackChains: result.attackChains ?? [],
54
+ };
55
+ }
56
+ //# sourceMappingURL=digest.js.map
@@ -0,0 +1,47 @@
1
+ import type { AuditCache } from '@cclabsnz/sf-core';
2
+ import type { SecurityCheck } from '../checks/SecurityCheck.js';
3
+ export type AuditPermission = 'ApiEnabled' | 'ViewSetup' | 'ViewAllUsers' | 'ViewHealthCheckScreen' | 'AuthorApex' | 'ViewEventLogFiles';
4
+ export interface PermissionSpec {
5
+ /** Field on UserPermissionAccess carrying the effective grant. */
6
+ readonly field: string;
7
+ readonly label: string;
8
+ /** What the audit loses without it. */
9
+ readonly impact: string;
10
+ /**
11
+ * Cache keys whose producers and consumers need this permission. The affected
12
+ * check list is derived from the registry via these keys rather than hand-written,
13
+ * so a check added later is covered without touching this file.
14
+ *
15
+ * Empty for permissions too broad to attribute to specific checks.
16
+ */
17
+ readonly cacheKeys: ReadonlyArray<keyof AuditCache>;
18
+ /** The audit cannot run at all without this. */
19
+ readonly blocking?: boolean;
20
+ }
21
+ export declare const AUDIT_PERMISSIONS: Readonly<Record<AuditPermission, PermissionSpec>>;
22
+ export interface MissingPermission {
23
+ permission: AuditPermission;
24
+ label: string;
25
+ impact: string;
26
+ blocking: boolean;
27
+ affectedChecks: string[];
28
+ }
29
+ export interface PreflightResult {
30
+ canRun: boolean;
31
+ granted: AuditPermission[];
32
+ missing: MissingPermission[];
33
+ /** Checks expected to produce a verdict. */
34
+ willRun: number;
35
+ /** Checks expected to return inconclusive, deduplicated across permissions. */
36
+ willBeInconclusive: string[];
37
+ }
38
+ /** Check ids that need `permission`, derived from the registry's declared cache wiring. */
39
+ export declare function checksRequiring(permission: AuditPermission, checks?: readonly SecurityCheck[]): string[];
40
+ /**
41
+ * What this audit user will and will not be able to establish, before spending a run.
42
+ *
43
+ * The tool can only report a permission gap after the audit has already come back
44
+ * blind; this answers the same question up front, when it is still cheap to fix.
45
+ */
46
+ export declare function buildPreflight(granted: Record<AuditPermission, boolean>, checks?: readonly SecurityCheck[]): PreflightResult;
47
+ //# sourceMappingURL=permissionMap.d.ts.map
@@ -0,0 +1,84 @@
1
+ import { CHECKS } from '../checks/registry.js';
2
+ export const AUDIT_PERMISSIONS = {
3
+ ApiEnabled: {
4
+ field: 'PermissionsApiEnabled',
5
+ label: 'API Enabled',
6
+ impact: 'All access is via SOQL/Tooling/REST. Without it the audit cannot run at all.',
7
+ cacheKeys: [],
8
+ blocking: true,
9
+ },
10
+ ViewSetup: {
11
+ field: 'PermissionsViewSetup',
12
+ label: 'View Setup and Configuration',
13
+ impact: 'Reads the bulk of the surface — connected apps, remote sites, CSP, named credentials, auth config, ' +
14
+ 'Experience sites, and Tooling metadata. Most setup and configuration checks return inconclusive without it.',
15
+ cacheKeys: [],
16
+ },
17
+ ViewAllUsers: {
18
+ field: 'PermissionsViewAllUsers',
19
+ label: 'View All Users',
20
+ impact: 'Enumerates every User, PermissionSetAssignment and TwoFactorInfo org-wide. Without it the user, ' +
21
+ 'admin and MFA checks under-count and miss accounts outside the role hierarchy.',
22
+ cacheKeys: ['mfaRegistrations', 'effectivePermissions'],
23
+ },
24
+ ViewHealthCheckScreen: {
25
+ field: 'PermissionsViewHealthCheck',
26
+ label: 'View Health Check',
27
+ impact: 'Reads SecurityHealthCheck and its risks. Health Check and password/session baselines are inconclusive without it.',
28
+ cacheKeys: ['healthCheckRisks'],
29
+ },
30
+ AuthorApex: {
31
+ field: 'PermissionsAuthorApex',
32
+ label: 'Author Apex (read-only use)',
33
+ impact: 'The only standard gate exposing ApexClass/ApexTrigger/ApexPage Body via the Tooling API. ' +
34
+ 'Grants no ability to modify org data. The code-security checks are inconclusive without it.',
35
+ cacheKeys: ['apexBodies', 'vfPageBodies'],
36
+ },
37
+ ViewEventLogFiles: {
38
+ field: 'PermissionsViewEventLogFiles',
39
+ label: 'View Event Log Files',
40
+ impact: 'Reads EventLogFile. Whether login and API activity is monitored cannot be established without it.',
41
+ cacheKeys: ['eventLogSummary'],
42
+ },
43
+ };
44
+ const usesKey = (check, key) => (check.dependsOnCache?.includes(key) ?? false) || (check.populatesCache?.includes(key) ?? false);
45
+ /** Check ids that need `permission`, derived from the registry's declared cache wiring. */
46
+ export function checksRequiring(permission, checks = CHECKS) {
47
+ const { cacheKeys } = AUDIT_PERMISSIONS[permission];
48
+ if (cacheKeys.length === 0)
49
+ return [];
50
+ return checks.filter((c) => cacheKeys.some((k) => usesKey(c, k))).map((c) => c.id);
51
+ }
52
+ /**
53
+ * What this audit user will and will not be able to establish, before spending a run.
54
+ *
55
+ * The tool can only report a permission gap after the audit has already come back
56
+ * blind; this answers the same question up front, when it is still cheap to fix.
57
+ */
58
+ export function buildPreflight(granted, checks = CHECKS) {
59
+ const permissions = Object.keys(AUDIT_PERMISSIONS);
60
+ const missing = [];
61
+ const inconclusive = new Set();
62
+ for (const permission of permissions) {
63
+ if (granted[permission])
64
+ continue;
65
+ const spec = AUDIT_PERMISSIONS[permission];
66
+ const affectedChecks = checksRequiring(permission, checks);
67
+ affectedChecks.forEach((id) => inconclusive.add(id));
68
+ missing.push({
69
+ permission,
70
+ label: spec.label,
71
+ impact: spec.impact,
72
+ blocking: spec.blocking === true,
73
+ affectedChecks,
74
+ });
75
+ }
76
+ return {
77
+ canRun: !missing.some((m) => m.blocking),
78
+ granted: permissions.filter((p) => granted[p]),
79
+ missing,
80
+ willRun: checks.length - inconclusive.size,
81
+ willBeInconclusive: [...inconclusive],
82
+ };
83
+ }
84
+ //# sourceMappingURL=permissionMap.js.map
@@ -0,0 +1,11 @@
1
+ import type { SoqlClient } from '@cclabsnz/sf-core';
2
+ import { type AuditPermission } from './permissionMap.js';
3
+ /**
4
+ * The running user's *effective* permissions — profile unioned with every assigned
5
+ * permission set — in one read.
6
+ *
7
+ * UserPermissionAccess returns exactly one row scoped to the caller, so this needs no
8
+ * assignment join and no aggregation. Read-only, like everything else here.
9
+ */
10
+ export declare function readEffectivePermissions(soql: SoqlClient): Promise<Record<AuditPermission, boolean>>;
11
+ //# sourceMappingURL=readPermissions.d.ts.map
@@ -0,0 +1,20 @@
1
+ import { AUDIT_PERMISSIONS } from './permissionMap.js';
2
+ /**
3
+ * The running user's *effective* permissions — profile unioned with every assigned
4
+ * permission set — in one read.
5
+ *
6
+ * UserPermissionAccess returns exactly one row scoped to the caller, so this needs no
7
+ * assignment join and no aggregation. Read-only, like everything else here.
8
+ */
9
+ export async function readEffectivePermissions(soql) {
10
+ const permissions = Object.keys(AUDIT_PERMISSIONS);
11
+ const fields = permissions.map((p) => AUDIT_PERMISSIONS[p].field);
12
+ const result = await soql.query(`SELECT ${fields.join(', ')} FROM UserPermissionAccess`);
13
+ const row = result.records[0] ?? {};
14
+ const granted = {};
15
+ for (const permission of permissions) {
16
+ granted[permission] = row[AUDIT_PERMISSIONS[permission].field] === true;
17
+ }
18
+ return granted;
19
+ }
20
+ //# sourceMappingURL=readPermissions.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cclabsnz/sf-audit",
3
- "version": "1.9.0",
3
+ "version": "1.11.0",
4
4
  "description": "Read-only Salesforce security audit for the sf CLI: 88 checks, attack-chain correlation, A-F risk grading, and compliance mapping to OWASP, SOC 2, ISO 27001, NZISM and more.",
5
5
  "keywords": [
6
6
  "salesforce",
@@ -99,7 +99,8 @@
99
99
  "js-yaml@3": "^3.15.1",
100
100
  "handlebars": "^4.7.9",
101
101
  "brace-expansion": "^5.0.9",
102
- "fast-uri@3": "^3.1.6"
102
+ "fast-uri@3": "^3.1.6",
103
+ "browserslist": "^4.28.7"
103
104
  }
104
105
  }
105
106
  }