@cclabsnz/sf-audit 1.4.0 → 1.6.1
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/README.md +114 -11
- package/lib/api/RestClient.d.ts +1 -0
- package/lib/api/RestClientImpl.d.ts +1 -0
- package/lib/api/RestClientImpl.js +27 -0
- package/lib/apps/analyzeApps.d.ts +8 -0
- package/lib/apps/analyzeApps.js +19 -0
- package/lib/apps/appResolver.d.ts +4 -0
- package/lib/apps/appResolver.js +50 -0
- package/lib/apps/grantedAccess.d.ts +4 -0
- package/lib/apps/grantedAccess.js +36 -0
- package/lib/apps/leastPrivilege.d.ts +6 -0
- package/lib/apps/leastPrivilege.js +47 -0
- package/lib/apps/renderApps.d.ts +5 -0
- package/lib/apps/renderApps.js +23 -0
- package/lib/apps/standardAppCatalog.d.ts +11 -0
- package/lib/apps/standardAppCatalog.js +14 -0
- package/lib/apps/types.d.ts +64 -0
- package/lib/apps/types.js +2 -0
- package/lib/apps/usageCollector.d.ts +9 -0
- package/lib/apps/usageCollector.js +104 -0
- package/lib/chains/namedChains.js +45 -0
- package/lib/checks/impl/AgentActionSurfaceCheck.d.ts +13 -0
- package/lib/checks/impl/AgentActionSurfaceCheck.js +125 -0
- package/lib/checks/impl/AgentChannelExposureCheck.d.ts +15 -0
- package/lib/checks/impl/AgentChannelExposureCheck.js +223 -0
- package/lib/checks/impl/AgentInventoryCheck.d.ts +15 -0
- package/lib/checks/impl/AgentInventoryCheck.js +228 -0
- package/lib/checks/impl/AgentMonitoringCoverageCheck.d.ts +12 -0
- package/lib/checks/impl/AgentMonitoringCoverageCheck.js +97 -0
- package/lib/checks/impl/AgentUserPrivilegeCheck.d.ts +13 -0
- package/lib/checks/impl/AgentUserPrivilegeCheck.js +204 -0
- package/lib/checks/impl/CspTrustedSitesCheck.d.ts +1 -0
- package/lib/checks/impl/CspTrustedSitesCheck.js +10 -1
- package/lib/checks/impl/EnhancedDomainsCheck.js +18 -4
- package/lib/checks/impl/TrustedUrlHygieneCheck.d.ts +16 -0
- package/lib/checks/impl/TrustedUrlHygieneCheck.js +198 -0
- package/lib/checks/registry.js +19 -0
- package/lib/commands/audit/apps.d.ts +16 -0
- package/lib/commands/audit/apps.js +64 -0
- package/lib/commands/audit/security.d.ts +1 -0
- package/lib/commands/audit/security.js +7 -1
- package/lib/compliance/catalogs/index.js +2 -0
- package/lib/compliance/catalogs/owaspLlm.d.ts +3 -0
- package/lib/compliance/catalogs/owaspLlm.js +34 -0
- package/lib/compliance/mapping.js +19 -0
- package/lib/compliance/resolve.js +4 -3
- package/lib/compliance/types.d.ts +1 -1
- package/lib/context/AuditCache.d.ts +28 -0
- package/lib/context/AuditContext.d.ts +4 -0
- package/lib/events/pullEventLogs.js +3 -3
- package/lib/findings/CheckMeta.js +6 -0
- package/lib/lib/wire.d.ts +2 -2
- package/lib/lib/wire.js +2 -1
- package/lib/renderers/ClientReportRenderer.js +1 -1
- package/package.json +12 -13
- package/lib/findings/ComplianceMapping.d.ts +0 -3
- package/lib/findings/ComplianceMapping.js +0 -75
- package/lib/queries/QueryDefinition.d.ts +0 -48
- package/lib/queries/QueryDefinition.js +0 -11
- package/lib/queries/QueryRegistry.d.ts +0 -13
- package/lib/queries/QueryRegistry.js +0 -93
package/README.md
CHANGED
|
@@ -1,13 +1,21 @@
|
|
|
1
1
|
# @cclabsnz/sf-audit
|
|
2
2
|
|
|
3
|
+
[](https://github.com/cclabsnz/sf-audit-plugin/actions/workflows/ci.yml)
|
|
4
|
+
[](https://github.com/cclabsnz/sf-audit-plugin/actions/workflows/codeql.yml)
|
|
5
|
+
[](https://securityscorecards.dev/viewer/?uri=github.com/cclabsnz/sf-audit-plugin)
|
|
6
|
+
[](https://www.npmjs.com/package/@cclabsnz/sf-audit)
|
|
7
|
+
[](https://www.npmjs.com/package/@cclabsnz/sf-audit#provenance)
|
|
8
|
+
[](LICENSE)
|
|
9
|
+
|
|
3
10
|
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.
|
|
4
11
|
|
|
5
|
-
- **
|
|
12
|
+
- **88 read-only checks** across identity, access, data, code, integrations, monitoring, and Agentforce / GenAI
|
|
6
13
|
- **Attack-chain correlation:** links individual findings into named, multi-step attack scenarios
|
|
7
|
-
- **Compliance mapping:** every finding mapped to **source-verified** controls across
|
|
14
|
+
- **Compliance mapping:** every finding mapped to **source-verified** controls across 8 frameworks (OWASP, OWASP LLM Top 10, SOC 2, ISO/IEC 27001:2022, Security Benchmark for Salesforce, NZ Privacy Act, HISO 10029, NZISM)
|
|
8
15
|
- **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
|
|
9
16
|
- **History & diff:** archives each run and shows security-posture drift over time
|
|
10
17
|
- **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
|
|
18
|
+
- **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
|
|
11
19
|
- Strictly read-only (SOQL/Tooling/REST GETs + Metadata API reads); see [PERMISSIONS.md](PERMISSIONS.md) for the least-privilege access it needs
|
|
12
20
|
|
|
13
21
|
## Installation
|
|
@@ -32,7 +40,13 @@ sf plugins link .
|
|
|
32
40
|
sf audit security --target-org <orgAlias>
|
|
33
41
|
```
|
|
34
42
|
|
|
35
|
-
This runs all
|
|
43
|
+
This runs all 88 security checks against the target org and writes a report to the current directory.
|
|
44
|
+
|
|
45
|
+
List every available check id (the values you pass to `--checks`):
|
|
46
|
+
|
|
47
|
+
```bash
|
|
48
|
+
sf audit list
|
|
49
|
+
```
|
|
36
50
|
|
|
37
51
|
### Options
|
|
38
52
|
|
|
@@ -42,12 +56,13 @@ This runs all 82 security checks against the target org and writes a report to t
|
|
|
42
56
|
| `--format` / `-f` | `html` | Output format(s), comma-separated: `html`, `md`, `json`, `executive` |
|
|
43
57
|
| `--output` / `-o` | `.` | Directory to write the report file |
|
|
44
58
|
| `--fail-on` | (none) | Exit with code 1 if any finding is at or above this severity: `CRITICAL`, `HIGH`, `MEDIUM`, `LOW` |
|
|
45
|
-
| `--checks` | *(all)* | Comma-separated check IDs to run instead of all
|
|
59
|
+
| `--checks` | *(all)* | Comma-separated check IDs to run instead of all 88 (e.g. `hardcoded-credentials,apex-sharing`) |
|
|
46
60
|
| `--scoring-config` | (none) | Path to a custom scoring config JSON file to override weights and grade thresholds |
|
|
47
61
|
| `--prepared-for` | (none) | Client name for the executive report cover line |
|
|
48
62
|
| `--branding` | (none) | Path to a `report-branding.json` to override CloudCounsel defaults (executive format) |
|
|
49
63
|
| `--top` | `5` | Number of executive priorities to highlight (executive format) |
|
|
50
|
-
| `--frameworks` | `universal` | Compliance matrix scope (executive format): `universal` (OWASP/SOC 2/ISO 27001), `nz` (ISO/HISO/Privacy Act/NZISM), `all`, or a comma list (e.g. `owasp,iso,nzism`) |
|
|
64
|
+
| `--frameworks` | `universal` | Compliance matrix scope (executive format): `universal` (OWASP/OWASP LLM/SOC 2/ISO 27001), `nz` (ISO/HISO/Privacy Act/NZISM), `all`, or a comma list (e.g. `owasp,owasp-llm,iso,nzism`) |
|
|
65
|
+
| `--resolve-domains` | `false` | Makes **outbound DNS queries from this machine** to verify CSP trusted domains still resolve (flags unresolvable / parked domains as exfiltration channels). Off by default; a default run contacts **only the target org** and never reaches out to any other host. |
|
|
51
66
|
|
|
52
67
|
### Examples
|
|
53
68
|
|
|
@@ -94,15 +109,15 @@ sf audit security --target-org myOrg --format executive --branding ./report-bran
|
|
|
94
109
|
```
|
|
95
110
|
|
|
96
111
|
Compliance controls are mapped from authoritative, version-pinned sources (OWASP Top 10:2021,
|
|
97
|
-
AICPA TSC, ISO/IEC 27001:2022, the Security Benchmark for
|
|
98
|
-
NZISM). Only source-verified controls render. "No findings detected" is **not** an attestation of
|
|
112
|
+
OWASP Top 10 for LLM Applications 2025, AICPA TSC, ISO/IEC 27001:2022, the Security Benchmark for
|
|
113
|
+
Salesforce, NZ Privacy Act, HISO 10029, NZISM). Only source-verified controls render. "No findings detected" is **not** an attestation of
|
|
99
114
|
compliance (see the report's Scope & Liability section).
|
|
100
115
|
|
|
101
116
|
The report file is written as `sf-audit-<orgId>-<timestamp>.<ext>` in the output directory (e.g. `sf-audit-00D000000000001-1711234567890.html`).
|
|
102
117
|
|
|
103
118
|
## What It Checks
|
|
104
119
|
|
|
105
|
-
The audit runs **
|
|
120
|
+
The audit runs **88 read-only checks**. Every finding is risk-rated (CRITICAL → INFO) and mapped to controls across the compliance frameworks (see [Compliance frameworks](#compliance-frameworks)). The checks are grouped into ten domains below.
|
|
106
121
|
|
|
107
122
|
### Org Health & Configuration
|
|
108
123
|
| Check | What it looks for |
|
|
@@ -222,6 +237,20 @@ The audit runs **82 read-only checks**. Every finding is risk-rated (CRITICAL
|
|
|
222
237
|
| Anomalous Successful Logins | Accounts with successful logins from an unusually high number of distinct source IPs (credential-sharing / compromise signature) |
|
|
223
238
|
| SIEM Integration Signals | Evidence of SIEM or external monitoring integration |
|
|
224
239
|
|
|
240
|
+
### AI & Agents (Agentforce / GenAI)
|
|
241
|
+
| Check | What it looks for |
|
|
242
|
+
|-------|------------------|
|
|
243
|
+
| Agent Inventory | Every Agentforce agent, its active version, and its run-as user (inventory findings); flags an active agent whose run-as identity is inactive or frozen |
|
|
244
|
+
| Agent User Privilege | Agent / run-as users with Modify All Data or View All Data, broad object write access, or read access to objects classified as sensitive — the data a prompt injection inherits |
|
|
245
|
+
| Agent Action Surface | Write-capable agent actions (Apex/Flow that create, update, or delete) and agents with an unusually large action surface |
|
|
246
|
+
| Agentforce Channel Exposure | Correlates active agents with the channels that reach them (Experience Cloud sites, embedded deployments, messaging channels); flags guest-reachable exposure |
|
|
247
|
+
| Agentforce Monitoring Coverage | Active agents running with no Event Monitoring capture and no Transaction Security policy (the monitoring gap in the ForcedLeak pattern); points at `sf audit events pull` |
|
|
248
|
+
| Trusted URL Hygiene | Reviews the CSP trusted-sites allowlist for non-Salesforce domains that could be repurposed as exfiltration channels; with `--resolve-domains`, DNS-checks each for unresolvable or parked entries |
|
|
249
|
+
|
|
250
|
+
Two named attack chains correlate these findings: **Prompt injection blast radius** (guest-reachable channel + over-privileged agent user + write-capable actions) and **ForcedLeak pattern** (active agents + a stale/unresolvable trusted URL + no event capture).
|
|
251
|
+
|
|
252
|
+
The five agent-specific checks stay silent in orgs where Agentforce is not enabled (the GenAI objects do not exist, so the inventory records `not-enabled` and the dependent checks return nothing). Trusted URL Hygiene runs everywhere, since the CSP allowlist is an org-wide exfiltration surface regardless of Agentforce.
|
|
253
|
+
|
|
225
254
|
### Known limitations (advisory-only checks)
|
|
226
255
|
|
|
227
256
|
A small number of checks emit an **advisory** rather than a pass/fail verdict because the underlying setting is not exposed to the read APIs this plugin uses (SOQL/Tooling/REST/Metadata read):
|
|
@@ -233,11 +262,12 @@ Advisory findings are surfaced as `INFO` and never inflate the health score.
|
|
|
233
262
|
|
|
234
263
|
## Compliance frameworks
|
|
235
264
|
|
|
236
|
-
Findings are mapped to controls across
|
|
265
|
+
Findings are mapped to controls across eight security and privacy frameworks. The mapping is built on a **sourced control catalog** (each control carries its framework, **pinned version**, official title, and a citation) so a finding's compliance reference ties to an exact, defensible requirement rather than a bare tag.
|
|
237
266
|
|
|
238
267
|
| Framework | Version | Notes |
|
|
239
268
|
|-----------|---------|-------|
|
|
240
269
|
| OWASP Top 10 | 2021 | Web application risk categories |
|
|
270
|
+
| OWASP LLM Top 10 | 2025 | LLM/GenAI application risks (LLM01 Prompt Injection, LLM02 Sensitive Information Disclosure, LLM05 Improper Output Handling, LLM06 Excessive Agency); mapped by the AI & Agents checks |
|
|
241
271
|
| SOC 2 | AICPA TSC 2017 | Common Criteria (CC6–CC9) |
|
|
242
272
|
| ISO/IEC 27001 | 2022 | Annex A controls |
|
|
243
273
|
| Security Benchmark for Salesforce (SBS) | current | Salesforce-native benchmark: [docs.securitybenchmark.org](https://docs.securitybenchmark.org) |
|
|
@@ -249,10 +279,10 @@ Findings are mapped to controls across seven security and privacy frameworks. Th
|
|
|
249
279
|
|
|
250
280
|
**Framework packs.** The executive report's compliance matrix is scoped with `--frameworks`:
|
|
251
281
|
|
|
252
|
-
- `universal` *(default)*: OWASP, SOC 2, ISO 27001
|
|
282
|
+
- `universal` *(default)*: OWASP, OWASP LLM Top 10, SOC 2, ISO 27001
|
|
253
283
|
- `nz`: ISO 27001, HISO 10029, NZ Privacy Act, NZISM (for NZ health/government engagements)
|
|
254
284
|
- `all`: every framework
|
|
255
|
-
- a comma list of aliases, e.g. `owasp,iso,nzism`
|
|
285
|
+
- a comma list of aliases, e.g. `owasp,owasp-llm,iso,nzism` (`owasp-llm` / `llm` selects the OWASP LLM Top 10)
|
|
256
286
|
|
|
257
287
|
> **Not an attestation.** A control rendering "No findings detected" means this audit's checks surfaced no issues mapped to it. It is **not** a statement of compliance or certification. See [Scope & Liability](#scope--liability).
|
|
258
288
|
|
|
@@ -271,6 +301,15 @@ Findings are mapped to controls across seven security and privacy frameworks. Th
|
|
|
271
301
|
|
|
272
302
|
**No warranty.** This software is provided "as is", without warranty of any kind, express or implied. To the maximum extent permitted by law, the authors and CloudCounsel Limited accept no liability for any loss, damage, or claim arising from use of this tool or reliance on its output. Findings are informational and should be validated by a qualified Salesforce security practitioner before any remediation action is taken.
|
|
273
303
|
|
|
304
|
+
## Trust & verification
|
|
305
|
+
|
|
306
|
+
Because this tool authenticates against production orgs, "is it safe to run?" deserves a verifiable answer, not just a claim. Here's how you can check for yourself:
|
|
307
|
+
|
|
308
|
+
- **Read-only, enforced in CI.** The "no writes to your org" promise is a passing test, not a footnote. `test/unit/api/readonly-invariant.test.ts` statically scans the entire source tree and fails the build if any jsforce mutation API, HTTP write verb, or bulk/composite write path ever appears. Every org request funnels through `src/api/*ClientImpl.ts`, which issue only SOQL queries, REST **GET**s, and Metadata reads.
|
|
309
|
+
- **What you install matches the public source.** Releases are published from GitHub Actions with [npm provenance](https://docs.npmjs.com/generating-provenance-statements) — the npm page shows a signed attestation linking the tarball to the exact public commit that built it, so you can audit the code on GitHub and trust the bytes `sf plugins install` pulls down.
|
|
310
|
+
- **Independent scans.** [CodeQL](https://github.com/cclabsnz/sf-audit-plugin/security/code-scanning) static analysis and an [OpenSSF Scorecard](https://securityscorecards.dev/viewer/?uri=github.com/cclabsnz/sf-audit-plugin) supply-chain review run on every change (badges above), and Dependabot plus a CI `pnpm audit` gate keep dependencies current. Each release ships a CycloneDX SBOM.
|
|
311
|
+
- **Least privilege & disclosure.** See [PERMISSIONS.md](PERMISSIONS.md) for the minimal access it needs and [SECURITY.md](SECURITY.md) for private vulnerability reporting.
|
|
312
|
+
|
|
274
313
|
## Scoring
|
|
275
314
|
|
|
276
315
|
Each finding is assigned a risk level with a corresponding weight:
|
|
@@ -483,6 +522,68 @@ Pulling free EventLogFile logs for org: My Org (00D000000000001)
|
|
|
483
522
|
Manifest: ~/.sf/event-baseline/00D000000000001/_manifests/manifest-...-....json
|
|
484
523
|
```
|
|
485
524
|
|
|
525
|
+
### Analyzing the captured logs
|
|
526
|
+
|
|
527
|
+
`events pull` is the collection half. To triage those `EventLogFile` CSVs for exploit and
|
|
528
|
+
abuse patterns, use the companion CLI **[sfelf-triage](https://github.com/cclabsnz/sfelf-triage)**.
|
|
529
|
+
It reads downloaded EventLogFile CSVs and emits a per-IP verdict
|
|
530
|
+
(`BENIGN_SCANNER | SUSPICIOUS | LIKELY_ABUSE`), answering *"is this guest/community IP a
|
|
531
|
+
vulnerability scanner or a real threat?"* — with **zero network egress** and no org connection.
|
|
532
|
+
|
|
533
|
+
sfelf-triage reads this plugin's `~/.sf/event-baseline/<orgId>` layout directly, so the two
|
|
534
|
+
tools chain with no glue:
|
|
535
|
+
|
|
536
|
+
```bash
|
|
537
|
+
sf audit events pull --target-org myOrg # capture (this plugin)
|
|
538
|
+
sfelf-triage analyze ~/.sf/event-baseline/<orgId> # triage (companion)
|
|
539
|
+
```
|
|
540
|
+
|
|
541
|
+
See the [sfelf-triage README](https://github.com/cclabsnz/sfelf-triage#readme) for install and usage.
|
|
542
|
+
|
|
543
|
+
## Connected-app least-privilege
|
|
544
|
+
|
|
545
|
+
Connected-app over-privilege was at the centre of the 2025-2026 wave of Salesforce data-theft
|
|
546
|
+
via OAuth: apps authorized with more scope than they use, and integration users with far more
|
|
547
|
+
object access than the app ever touches. The static checks (`connected-apps`, `connected-app-scope`,
|
|
548
|
+
`connected-app-inactivity`) tell you what was *granted*. `sf audit apps` tells you what is actually
|
|
549
|
+
*used*, so it can point at the specific access to remove.
|
|
550
|
+
|
|
551
|
+
```bash
|
|
552
|
+
sf audit apps --target-org myOrg --since 7
|
|
553
|
+
```
|
|
554
|
+
|
|
555
|
+
It reads the `RestApi` `EventLogFile` to see which objects each connected app touched, compares that
|
|
556
|
+
against the objects its run-as user can reach, and reports the over-grant per object and read/write
|
|
557
|
+
bit — plus a generated least-privilege permission set granting exactly what was observed. App IDs are
|
|
558
|
+
resolved to human-readable names (`AppMenuItem` / `ConnectedApplication` / a bundled standard-app
|
|
559
|
+
catalog / `LoginHistory` correlation), and anything unresolved is flagged loudly rather than hidden.
|
|
560
|
+
|
|
561
|
+
It is **read-only**: the suggested permission set is emitted as data, never deployed.
|
|
562
|
+
|
|
563
|
+
**Honest bounds.** `RestApi` attributes roughly half of API traffic to a connected app (the rest is
|
|
564
|
+
UI-API / session traffic), so *used* is a lower bound. Findings carry the observation window and
|
|
565
|
+
attribution rate, and revoke recommendations are suppressed below a soak window and for apps used by
|
|
566
|
+
many interactive users. Reading `EventLogFile` needs the **View Event Log Files** permission (the same
|
|
567
|
+
one `events pull` uses).
|
|
568
|
+
|
|
569
|
+
**Flags:**
|
|
570
|
+
|
|
571
|
+
| Flag | Description | Default |
|
|
572
|
+
|------|-------------|---------|
|
|
573
|
+
| `--target-org` | Org alias or username | required |
|
|
574
|
+
| `--since` | Days of `RestApi` log to analyze | `7` |
|
|
575
|
+
| `--from` | Read `RestApi` CSVs from a local `events pull` baseline dir instead of downloading | *(download)* |
|
|
576
|
+
| `--soak` | Minimum window (days) before asserting revoke recommendations | `7` |
|
|
577
|
+
| `--format` | `table` / `json` / `md` | `table` |
|
|
578
|
+
|
|
579
|
+
```bash
|
|
580
|
+
# Reuse an events-pull baseline instead of downloading again
|
|
581
|
+
sf audit apps --target-org myOrg --from ~/.sf/event-baseline/00Dxxx
|
|
582
|
+
|
|
583
|
+
# Machine-readable output
|
|
584
|
+
sf audit apps --target-org myOrg --format json
|
|
585
|
+
```
|
|
586
|
+
|
|
486
587
|
## Requirements
|
|
487
588
|
|
|
488
589
|
- Node.js 18+
|
|
@@ -497,3 +598,5 @@ npm test # run all tests
|
|
|
497
598
|
npm run test:unit # unit tests only
|
|
498
599
|
npm run clean # remove compiled output
|
|
499
600
|
```
|
|
601
|
+
|
|
602
|
+
Maintainers: see **[docs/RELEASE.md](docs/RELEASE.md)** for the release checklist and the one-time repository-hardening steps (npm provenance token, branch protection, and the CodeQL / Scorecard setup behind the badges above).
|
package/lib/api/RestClient.d.ts
CHANGED
|
@@ -5,5 +5,6 @@ export declare class RestClientImpl implements RestClient {
|
|
|
5
5
|
constructor(conn: Connection);
|
|
6
6
|
get<T>(path: string): Promise<T>;
|
|
7
7
|
getRaw(path: string): Promise<string>;
|
|
8
|
+
getRawToFile(path: string, destPath: string): Promise<number>;
|
|
8
9
|
}
|
|
9
10
|
//# sourceMappingURL=RestClientImpl.d.ts.map
|
|
@@ -1,3 +1,8 @@
|
|
|
1
|
+
import { createWriteStream } from 'node:fs';
|
|
2
|
+
import { mkdir, rm, stat } from 'node:fs/promises';
|
|
3
|
+
import { dirname } from 'node:path';
|
|
4
|
+
import { Readable } from 'node:stream';
|
|
5
|
+
import { pipeline } from 'node:stream/promises';
|
|
1
6
|
export class RestClientImpl {
|
|
2
7
|
conn;
|
|
3
8
|
constructor(conn) {
|
|
@@ -14,5 +19,27 @@ export class RestClientImpl {
|
|
|
14
19
|
// jsforce returns the raw body string for non-JSON content types (text/csv here).
|
|
15
20
|
return this.conn.request(`/services/data/v${version}${normalised}`);
|
|
16
21
|
}
|
|
22
|
+
async getRawToFile(path, destPath) {
|
|
23
|
+
const version = this.conn.getApiVersion();
|
|
24
|
+
const normalised = path.startsWith('/') ? path : `/${path}`;
|
|
25
|
+
// Stream directly from the org to disk with the session bearer token, so the body is never
|
|
26
|
+
// materialised as a JS string (which would fail on logs larger than ~512 MB).
|
|
27
|
+
const url = `${this.conn.instanceUrl}/services/data/v${version}${normalised}`;
|
|
28
|
+
const res = await fetch(url, {
|
|
29
|
+
headers: { Authorization: `Bearer ${this.conn.accessToken ?? ''}` },
|
|
30
|
+
});
|
|
31
|
+
if (!res.ok || !res.body) {
|
|
32
|
+
throw new Error(`Download failed for ${normalised} (HTTP ${res.status})`);
|
|
33
|
+
}
|
|
34
|
+
await mkdir(dirname(destPath), { recursive: true });
|
|
35
|
+
try {
|
|
36
|
+
await pipeline(Readable.fromWeb(res.body), createWriteStream(destPath));
|
|
37
|
+
}
|
|
38
|
+
catch (err) {
|
|
39
|
+
await rm(destPath, { force: true }); // never leave a partial file behind
|
|
40
|
+
throw err;
|
|
41
|
+
}
|
|
42
|
+
return (await stat(destPath)).size;
|
|
43
|
+
}
|
|
17
44
|
}
|
|
18
45
|
//# sourceMappingURL=RestClientImpl.js.map
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { AppFinding } from './types.js';
|
|
2
|
+
import type { SoqlClient } from '../api/SoqlClient.js';
|
|
3
|
+
export declare function analyzeApps(restApiCsv: string, soql: SoqlClient, opts: {
|
|
4
|
+
since: number;
|
|
5
|
+
soakDays: number;
|
|
6
|
+
soapApiCsv?: string;
|
|
7
|
+
}): Promise<AppFinding[]>;
|
|
8
|
+
//# sourceMappingURL=analyzeApps.d.ts.map
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { collectUsage } from './usageCollector.js';
|
|
2
|
+
import { resolveApps } from './appResolver.js';
|
|
3
|
+
import { computeGranted } from './grantedAccess.js';
|
|
4
|
+
import { buildFinding } from './leastPrivilege.js';
|
|
5
|
+
export async function analyzeApps(restApiCsv, soql, opts) {
|
|
6
|
+
const usage = collectUsage(restApiCsv, opts.soapApiCsv);
|
|
7
|
+
const appIds = usage.usage.map((u) => u.appId);
|
|
8
|
+
const allUsers = [...new Set(usage.usage.flatMap((u) => u.userIds))];
|
|
9
|
+
const resolved = await resolveApps(appIds, soql, allUsers);
|
|
10
|
+
const resolvedById = new Map(resolved.map((r) => [r.appId, r]));
|
|
11
|
+
const findings = [];
|
|
12
|
+
for (const u of usage.usage) {
|
|
13
|
+
const app = resolvedById.get(u.appId);
|
|
14
|
+
const granted = await computeGranted(u.appId, u.userIds, soql, null);
|
|
15
|
+
findings.push(buildFinding(app, u, granted, { since: opts.since, attributionRatePct: usage.attributionRatePct }, opts.soakDays));
|
|
16
|
+
}
|
|
17
|
+
return findings;
|
|
18
|
+
}
|
|
19
|
+
//# sourceMappingURL=analyzeApps.js.map
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { lookupStandardApp } from './standardAppCatalog.js';
|
|
2
|
+
const SECURITY_VENDOR = /datadog|defender|appomni|crowdstrike|splunk|siem|sentinel/i;
|
|
3
|
+
const SALESFORCE_VENDOR = /salesforce|dataloader|workbench|force\.com|chatter|salesforcea/i;
|
|
4
|
+
function categorise(name, viaStandard) {
|
|
5
|
+
if (viaStandard)
|
|
6
|
+
return viaStandard;
|
|
7
|
+
if (SECURITY_VENDOR.test(name))
|
|
8
|
+
return 'Security-vendor';
|
|
9
|
+
if (SALESFORCE_VENDOR.test(name))
|
|
10
|
+
return 'Salesforce-standard';
|
|
11
|
+
return 'Org-custom';
|
|
12
|
+
}
|
|
13
|
+
export async function resolveApps(appIds, soql, userIds) {
|
|
14
|
+
const menu = await soql
|
|
15
|
+
.queryAll("SELECT ApplicationId, Label, Name FROM AppMenuItem WHERE Type = 'ConnectedApplication'")
|
|
16
|
+
.catch(() => []);
|
|
17
|
+
const connApps = await soql
|
|
18
|
+
.queryAll('SELECT Id, Name FROM ConnectedApplication')
|
|
19
|
+
.catch(() => []);
|
|
20
|
+
const menuByKey = new Map(menu.map((m) => [m.ApplicationId.slice(0, 15), m.Label ?? m.Name ?? '']));
|
|
21
|
+
const connByKey = new Map(connApps.map((c) => [c.Id.slice(0, 15), c.Name]));
|
|
22
|
+
// Only pay for LoginHistory if some ids are still unresolved after 1-3.
|
|
23
|
+
const stillUnknown = appIds.filter((id) => !menuByKey.has(id.slice(0, 15)) && !connByKey.has(id.slice(0, 15)) && !lookupStandardApp(id));
|
|
24
|
+
let logins = [];
|
|
25
|
+
if (stillUnknown.length > 0 && userIds.length > 0) {
|
|
26
|
+
logins = await soql
|
|
27
|
+
.queryAll(`SELECT Application, UserId FROM LoginHistory WHERE UserId IN (${userIds
|
|
28
|
+
.map((u) => `'${u}'`)
|
|
29
|
+
.join(',')}) AND LoginTime = LAST_N_DAYS:7`)
|
|
30
|
+
.catch(() => []);
|
|
31
|
+
}
|
|
32
|
+
const loginNames = [...new Set(logins.map((l) => l.Application).filter((a) => a && a !== 'Browser' && a !== 'N/A'))];
|
|
33
|
+
return appIds.map((appId) => {
|
|
34
|
+
const key = appId.slice(0, 15);
|
|
35
|
+
const menuName = menuByKey.get(key);
|
|
36
|
+
if (menuName)
|
|
37
|
+
return { appId, name: menuName, category: categorise(menuName, null), confidence: 'resolved' };
|
|
38
|
+
const connName = connByKey.get(key);
|
|
39
|
+
if (connName)
|
|
40
|
+
return { appId, name: connName, category: categorise(connName, null), confidence: 'resolved' };
|
|
41
|
+
const std = lookupStandardApp(appId);
|
|
42
|
+
if (std)
|
|
43
|
+
return { appId, name: std.name, category: std.category, vendor: std.vendor, purpose: std.purpose, confidence: 'resolved' };
|
|
44
|
+
if (loginNames.length === 1) {
|
|
45
|
+
return { appId, name: loginNames[0], category: categorise(loginNames[0], null), confidence: 'inferred' };
|
|
46
|
+
}
|
|
47
|
+
return { appId, name: `Unidentified connected app ${appId}`, category: 'Unidentified', confidence: 'unidentified' };
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
//# sourceMappingURL=appResolver.js.map
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import type { GrantedAccess } from './types.js';
|
|
2
|
+
import type { SoqlClient } from '../api/SoqlClient.js';
|
|
3
|
+
export declare function computeGranted(appId: string, runAsUsers: string[], soql: SoqlClient, scope: string | null): Promise<GrantedAccess>;
|
|
4
|
+
//# sourceMappingURL=grantedAccess.d.ts.map
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
const inList = (ids) => ids.map((i) => `'${i}'`).join(',');
|
|
2
|
+
export async function computeGranted(appId, runAsUsers, soql, scope) {
|
|
3
|
+
const multiUserInteractive = runAsUsers.length > 3;
|
|
4
|
+
if (runAsUsers.length === 0 || multiUserInteractive) {
|
|
5
|
+
return { appId, scope, objects: [], runAsUsers, multiUserInteractive };
|
|
6
|
+
}
|
|
7
|
+
const psa = await soql
|
|
8
|
+
.queryAll(`SELECT AssigneeId, PermissionSetId FROM PermissionSetAssignment WHERE AssigneeId IN (${inList(runAsUsers)})`)
|
|
9
|
+
.catch(() => []);
|
|
10
|
+
const psIds = [...new Set(psa.map((p) => p.PermissionSetId))];
|
|
11
|
+
if (psIds.length === 0)
|
|
12
|
+
return { appId, scope, objects: [], runAsUsers, multiUserInteractive };
|
|
13
|
+
const perms = await soql
|
|
14
|
+
.queryAll(`SELECT ParentId, SobjectType, PermissionsRead, PermissionsCreate, PermissionsEdit, PermissionsDelete
|
|
15
|
+
FROM ObjectPermissions WHERE ParentId IN (${inList(psIds)}) AND PermissionsRead = true`)
|
|
16
|
+
.catch(() => []);
|
|
17
|
+
const byObject = new Map();
|
|
18
|
+
for (const p of perms) {
|
|
19
|
+
const verbs = byObject.get(p.SobjectType) ?? new Set();
|
|
20
|
+
if (p.PermissionsRead)
|
|
21
|
+
verbs.add('read');
|
|
22
|
+
if (p.PermissionsCreate || p.PermissionsEdit)
|
|
23
|
+
verbs.add('write');
|
|
24
|
+
if (p.PermissionsDelete)
|
|
25
|
+
verbs.add('delete');
|
|
26
|
+
byObject.set(p.SobjectType, verbs);
|
|
27
|
+
}
|
|
28
|
+
return {
|
|
29
|
+
appId,
|
|
30
|
+
scope,
|
|
31
|
+
objects: [...byObject.entries()].map(([object, verbs]) => ({ object, verbs: [...verbs].sort() })),
|
|
32
|
+
runAsUsers,
|
|
33
|
+
multiUserInteractive,
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
//# sourceMappingURL=grantedAccess.js.map
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { AppFinding, AppUsage, GrantedAccess, ResolvedApp } from './types.js';
|
|
2
|
+
export declare function buildFinding(app: ResolvedApp, used: AppUsage, granted: GrantedAccess, window: {
|
|
3
|
+
since: number;
|
|
4
|
+
attributionRatePct: number;
|
|
5
|
+
}, soakDays: number): AppFinding;
|
|
6
|
+
//# sourceMappingURL=leastPrivilege.d.ts.map
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
export function buildFinding(app, used, granted, window, soakDays) {
|
|
2
|
+
const usedObjects = new Set(used.objects.map((o) => o.object));
|
|
3
|
+
const usedVerbs = new Map(used.objects.map((o) => [o.object, new Set(o.verbs)]));
|
|
4
|
+
const belowSoak = window.since < soakDays;
|
|
5
|
+
const notes = [];
|
|
6
|
+
notes.push(`Observed over ${window.since} day(s); RestApi attribution ${window.attributionRatePct}% — "used" is a lower bound.`);
|
|
7
|
+
if (belowSoak)
|
|
8
|
+
notes.push(`Window below the ${soakDays}-day soak threshold: revoke recommendations suppressed.`);
|
|
9
|
+
if (used.soapOnly)
|
|
10
|
+
notes.push('SOAP usage present but not app-attributable; not treated as dormant.');
|
|
11
|
+
if (granted.multiUserInteractive)
|
|
12
|
+
notes.push('Interactive app with many run-as users; object delta not asserted.');
|
|
13
|
+
const assertDelta = !belowSoak && !granted.multiUserInteractive;
|
|
14
|
+
const unusedObjects = assertDelta
|
|
15
|
+
? granted.objects.map((o) => o.object).filter((o) => !usedObjects.has(o)).sort()
|
|
16
|
+
: [];
|
|
17
|
+
const unusedVerbs = assertDelta
|
|
18
|
+
? granted.objects
|
|
19
|
+
.filter((o) => usedObjects.has(o.object))
|
|
20
|
+
.map((o) => {
|
|
21
|
+
const u = usedVerbs.get(o.object) ?? new Set();
|
|
22
|
+
const extra = o.verbs.filter((v) => !u.has(v)).sort();
|
|
23
|
+
return { object: o.object, verbs: extra };
|
|
24
|
+
})
|
|
25
|
+
.filter((x) => x.verbs.length > 0)
|
|
26
|
+
: [];
|
|
27
|
+
const anyWriteUsed = used.objects.some((o) => o.verbs.some((v) => v === 'write' || v === 'delete'));
|
|
28
|
+
const scopeDowngrade = assertDelta && granted.scope === 'full' && !anyWriteUsed ? 'full -> api' : null;
|
|
29
|
+
const dormant = assertDelta && used.objects.length === 0 && granted.objects.length > 0;
|
|
30
|
+
const objectPermissions = used.objects.map((o) => ({
|
|
31
|
+
object: o.object,
|
|
32
|
+
read: o.verbs.includes('read'),
|
|
33
|
+
create: o.verbs.includes('write'),
|
|
34
|
+
edit: o.verbs.includes('write'),
|
|
35
|
+
delete: o.verbs.includes('delete'),
|
|
36
|
+
}));
|
|
37
|
+
return {
|
|
38
|
+
app,
|
|
39
|
+
window,
|
|
40
|
+
used,
|
|
41
|
+
granted,
|
|
42
|
+
overGrant: { unusedObjects, unusedVerbs, scopeDowngrade, dormant },
|
|
43
|
+
recommendation: { permissionSet: { objectPermissions } },
|
|
44
|
+
notes,
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
//# sourceMappingURL=leastPrivilege.js.map
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import type { AppFinding } from './types.js';
|
|
2
|
+
export declare function renderJson(findings: AppFinding[]): string;
|
|
3
|
+
export declare function renderMarkdown(findings: AppFinding[]): string;
|
|
4
|
+
export declare function renderTable(findings: AppFinding[]): string;
|
|
5
|
+
//# sourceMappingURL=renderApps.d.ts.map
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
export function renderJson(findings) {
|
|
2
|
+
return JSON.stringify(findings, null, 2);
|
|
3
|
+
}
|
|
4
|
+
export function renderMarkdown(findings) {
|
|
5
|
+
const lines = ['| App | Category | Confidence | Used | Over-granted | Scope |', '|---|---|---|---|---|---|'];
|
|
6
|
+
for (const f of findings) {
|
|
7
|
+
lines.push(`| ${f.app.name} | ${f.app.category} | ${f.app.confidence} | ${f.used.objects.length} objs | ` +
|
|
8
|
+
`${f.overGrant.unusedObjects.length} objs | ${f.overGrant.scopeDowngrade ?? '-'} |`);
|
|
9
|
+
}
|
|
10
|
+
return lines.join('\n');
|
|
11
|
+
}
|
|
12
|
+
export function renderTable(findings) {
|
|
13
|
+
const rows = findings.map((f) => [
|
|
14
|
+
f.app.name,
|
|
15
|
+
f.app.category,
|
|
16
|
+
f.app.confidence,
|
|
17
|
+
`${f.used.objects.length}`,
|
|
18
|
+
`${f.overGrant.unusedObjects.length}`,
|
|
19
|
+
f.overGrant.scopeDowngrade ?? '-',
|
|
20
|
+
].join(' '));
|
|
21
|
+
return ['App Category Confidence Used OverGranted Scope', ...rows].join('\n');
|
|
22
|
+
}
|
|
23
|
+
//# sourceMappingURL=renderApps.js.map
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { AppCategory } from './types.js';
|
|
2
|
+
export interface StandardApp {
|
|
3
|
+
name: string;
|
|
4
|
+
category: AppCategory;
|
|
5
|
+
vendor: string;
|
|
6
|
+
purpose: string;
|
|
7
|
+
}
|
|
8
|
+
export declare const STANDARD_APPS: Record<string, StandardApp>;
|
|
9
|
+
/** Look up a connected-app id (15- or 18-char) in the bundled catalog. */
|
|
10
|
+
export declare function lookupStandardApp(appId: string): StandardApp | null;
|
|
11
|
+
//# sourceMappingURL=standardAppCatalog.d.ts.map
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
// Curated seed of common connected-app ids (15-char keys). Salesforce standard-app ids are
|
|
2
|
+
// stable across orgs; third-party ids are the ones observed in practice. Grow over time.
|
|
3
|
+
export const STANDARD_APPS = {
|
|
4
|
+
'0H44a00000000Ns': { name: 'Dataloader Bulk', category: 'Salesforce-standard', vendor: 'Salesforce', purpose: 'Bulk data import/export tool' },
|
|
5
|
+
'0H44a00000000Nt': { name: 'Dataloader Partner', category: 'Salesforce-standard', vendor: 'Salesforce', purpose: 'Data Loader (SOAP) tool' },
|
|
6
|
+
'0H44a00000000Nz': { name: 'Workbench', category: 'Salesforce-standard', vendor: 'Salesforce', purpose: 'Ad-hoc API/data tool' },
|
|
7
|
+
'0H44a00000000Nu': { name: 'Force.com IDE', category: 'Salesforce-standard', vendor: 'Salesforce', purpose: 'Developer tooling' },
|
|
8
|
+
};
|
|
9
|
+
/** Look up a connected-app id (15- or 18-char) in the bundled catalog. */
|
|
10
|
+
export function lookupStandardApp(appId) {
|
|
11
|
+
const key = appId.slice(0, 15);
|
|
12
|
+
return STANDARD_APPS[key] ?? null;
|
|
13
|
+
}
|
|
14
|
+
//# sourceMappingURL=standardAppCatalog.js.map
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
export type Verb = 'read' | 'write' | 'delete';
|
|
2
|
+
export type AppCategory = 'Salesforce-standard' | 'Org-custom' | 'Security-vendor' | 'Installed-package' | 'Third-party' | 'Unidentified';
|
|
3
|
+
export type ResolveConfidence = 'resolved' | 'inferred' | 'unidentified';
|
|
4
|
+
/** Observed usage for one connected app, derived from RestApi rows. */
|
|
5
|
+
export interface AppUsage {
|
|
6
|
+
appId: string;
|
|
7
|
+
objects: {
|
|
8
|
+
object: string;
|
|
9
|
+
verbs: Verb[];
|
|
10
|
+
}[];
|
|
11
|
+
requests: number;
|
|
12
|
+
rowsProcessed: number;
|
|
13
|
+
userIds: string[];
|
|
14
|
+
soapOnly: boolean;
|
|
15
|
+
}
|
|
16
|
+
export interface ResolvedApp {
|
|
17
|
+
appId: string;
|
|
18
|
+
name: string;
|
|
19
|
+
category: AppCategory;
|
|
20
|
+
vendor?: string;
|
|
21
|
+
purpose?: string;
|
|
22
|
+
confidence: ResolveConfidence;
|
|
23
|
+
}
|
|
24
|
+
export interface GrantedAccess {
|
|
25
|
+
appId: string;
|
|
26
|
+
scope: string | null;
|
|
27
|
+
objects: {
|
|
28
|
+
object: string;
|
|
29
|
+
verbs: Verb[];
|
|
30
|
+
}[];
|
|
31
|
+
runAsUsers: string[];
|
|
32
|
+
multiUserInteractive: boolean;
|
|
33
|
+
}
|
|
34
|
+
export interface AppFinding {
|
|
35
|
+
app: ResolvedApp;
|
|
36
|
+
window: {
|
|
37
|
+
since: number;
|
|
38
|
+
attributionRatePct: number;
|
|
39
|
+
};
|
|
40
|
+
used: AppUsage;
|
|
41
|
+
granted: GrantedAccess;
|
|
42
|
+
overGrant: {
|
|
43
|
+
unusedObjects: string[];
|
|
44
|
+
unusedVerbs: {
|
|
45
|
+
object: string;
|
|
46
|
+
verbs: Verb[];
|
|
47
|
+
}[];
|
|
48
|
+
scopeDowngrade: string | null;
|
|
49
|
+
dormant: boolean;
|
|
50
|
+
};
|
|
51
|
+
recommendation: {
|
|
52
|
+
permissionSet: {
|
|
53
|
+
objectPermissions: {
|
|
54
|
+
object: string;
|
|
55
|
+
read: boolean;
|
|
56
|
+
create: boolean;
|
|
57
|
+
edit: boolean;
|
|
58
|
+
delete: boolean;
|
|
59
|
+
}[];
|
|
60
|
+
};
|
|
61
|
+
};
|
|
62
|
+
notes: string[];
|
|
63
|
+
}
|
|
64
|
+
//# sourceMappingURL=types.d.ts.map
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { AppUsage } from './types.js';
|
|
2
|
+
export interface UsageResult {
|
|
3
|
+
usage: AppUsage[];
|
|
4
|
+
totalRows: number;
|
|
5
|
+
attributedRows: number;
|
|
6
|
+
attributionRatePct: number;
|
|
7
|
+
}
|
|
8
|
+
export declare function collectUsage(restApiCsv: string, soapApiCsv?: string): UsageResult;
|
|
9
|
+
//# sourceMappingURL=usageCollector.d.ts.map
|