@cclabsnz/sf-core 0.1.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/LICENSE +201 -0
- package/README.md +88 -0
- package/lib/api/ApiError.d.ts +6 -0
- package/lib/api/ApiError.js +6 -0
- package/lib/api/MetadataClient.d.ts +4 -0
- package/lib/api/MetadataClient.js +2 -0
- package/lib/api/MetadataClientImpl.d.ts +8 -0
- package/lib/api/MetadataClientImpl.js +22 -0
- package/lib/api/RestClient.d.ts +6 -0
- package/lib/api/RestClient.js +2 -0
- package/lib/api/RestClientImpl.d.ts +10 -0
- package/lib/api/RestClientImpl.js +45 -0
- package/lib/api/SoqlClient.d.ts +10 -0
- package/lib/api/SoqlClient.js +2 -0
- package/lib/api/SoqlClientImpl.d.ts +9 -0
- package/lib/api/SoqlClientImpl.js +19 -0
- package/lib/api/ToolingClient.d.ts +5 -0
- package/lib/api/ToolingClient.js +2 -0
- package/lib/api/ToolingClientImpl.d.ts +10 -0
- package/lib/api/ToolingClientImpl.js +29 -0
- package/lib/api/index.d.ts +9 -0
- package/lib/api/index.js +5 -0
- package/lib/context/AuditCache.d.ts +78 -0
- package/lib/context/AuditCache.js +2 -0
- package/lib/context/AuditContext.d.ts +19 -0
- package/lib/context/AuditContext.js +2 -0
- package/lib/context/OrgInfo.d.ts +9 -0
- package/lib/context/OrgInfo.js +2 -0
- package/lib/context/OrgMetrics.d.ts +20 -0
- package/lib/context/OrgMetrics.js +20 -0
- package/lib/events/EventBaselineStore.d.ts +16 -0
- package/lib/events/EventBaselineStore.js +55 -0
- package/lib/events/eventLogAccess.d.ts +14 -0
- package/lib/events/eventLogAccess.js +33 -0
- package/lib/events/eventLogQuery.d.ts +21 -0
- package/lib/events/eventLogQuery.js +34 -0
- package/lib/events/pullEventLogs.d.ts +51 -0
- package/lib/events/pullEventLogs.js +79 -0
- package/lib/findings/RiskLevel.d.ts +3 -0
- package/lib/findings/RiskLevel.js +2 -0
- package/lib/index.d.ts +23 -0
- package/lib/index.js +19 -0
- package/lib/platform/apexRepository.d.ts +50 -0
- package/lib/platform/apexRepository.js +69 -0
- package/lib/platform/concurrency.d.ts +10 -0
- package/lib/platform/concurrency.js +21 -0
- package/lib/platform/flowRepository.d.ts +72 -0
- package/lib/platform/flowRepository.js +87 -0
- package/lib/platform/index.d.ts +7 -0
- package/lib/platform/index.js +7 -0
- package/lib/platform/salesforceId.d.ts +29 -0
- package/lib/platform/salesforceId.js +41 -0
- package/lib/renderers/html-utils.d.ts +2 -0
- package/lib/renderers/html-utils.js +8 -0
- package/lib/report/branding.d.ts +18 -0
- package/lib/report/branding.js +19 -0
- package/lib/report/fonts.d.ts +9 -0
- package/lib/report/fonts.js +37 -0
- package/lib/schemas/index.d.ts +133 -0
- package/lib/schemas/index.js +21 -0
- package/lib/testing/invariants.d.ts +61 -0
- package/lib/testing/invariants.js +104 -0
- package/package.json +72 -0
- package/schemas/coupling-graph.schema.json +77 -0
- package/schemas/landscape-manifest.schema.json +134 -0
- package/schemas/process-graph.schema.json +71 -0
- package/src/assets/fonts/NOTICE.md +22 -0
- package/src/assets/fonts/OFL.txt +93 -0
- package/src/assets/fonts/dm-sans-italic-latin.woff2 +0 -0
- package/src/assets/fonts/dm-sans-normal-latin.woff2 +0 -0
- package/src/assets/fonts/dm-serif-display-italic-latin.woff2 +0 -0
- package/src/assets/fonts/dm-serif-display-normal-latin.woff2 +0 -0
- package/src/assets/fonts/fira-code-400-latin.woff2 +0 -0
- package/src/assets/fonts/fira-sans-400-latin.woff2 +0 -0
- package/src/assets/fonts/fira-sans-600-latin.woff2 +0 -0
- package/src/assets/fonts/fira-sans-700-latin.woff2 +0 -0
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
export interface OrgMetrics {
|
|
2
|
+
totalActiveUsers: number;
|
|
3
|
+
modifyAllDataUsersCount: number;
|
|
4
|
+
viewAllDataUsersCount: number;
|
|
5
|
+
permissionSetCount: number;
|
|
6
|
+
profileCount: number;
|
|
7
|
+
apexClassCount: number;
|
|
8
|
+
apexTriggerCount: number;
|
|
9
|
+
codeCoveragePercent: number;
|
|
10
|
+
failedLogins30d: number;
|
|
11
|
+
inactiveUsers90d: number;
|
|
12
|
+
connectedAppsCount: number;
|
|
13
|
+
remoteSitesCount: number;
|
|
14
|
+
insecureRemoteSitesCount: number;
|
|
15
|
+
namedCredentialsCount: number;
|
|
16
|
+
unusedNamedCredentialsCount: number;
|
|
17
|
+
healthCheckScore: number;
|
|
18
|
+
}
|
|
19
|
+
export declare const EMPTY_METRICS: OrgMetrics;
|
|
20
|
+
//# sourceMappingURL=OrgMetrics.d.ts.map
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
// Used by scoring.ts to fill any metrics not populated by checks
|
|
2
|
+
export const EMPTY_METRICS = {
|
|
3
|
+
totalActiveUsers: 0,
|
|
4
|
+
modifyAllDataUsersCount: 0,
|
|
5
|
+
viewAllDataUsersCount: 0,
|
|
6
|
+
permissionSetCount: 0,
|
|
7
|
+
profileCount: 0,
|
|
8
|
+
apexClassCount: 0,
|
|
9
|
+
apexTriggerCount: 0,
|
|
10
|
+
codeCoveragePercent: 0,
|
|
11
|
+
failedLogins30d: 0,
|
|
12
|
+
inactiveUsers90d: 0,
|
|
13
|
+
connectedAppsCount: 0,
|
|
14
|
+
remoteSitesCount: 0,
|
|
15
|
+
insecureRemoteSitesCount: 0,
|
|
16
|
+
namedCredentialsCount: 0,
|
|
17
|
+
unusedNamedCredentialsCount: 0,
|
|
18
|
+
healthCheckScore: 0,
|
|
19
|
+
};
|
|
20
|
+
//# sourceMappingURL=OrgMetrics.js.map
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
export declare class EventBaselineStore {
|
|
2
|
+
private readonly root;
|
|
3
|
+
constructor(root?: string);
|
|
4
|
+
static defaultRoot(): string;
|
|
5
|
+
/** The per-org base directory logs for this org are stored under. */
|
|
6
|
+
orgDir(orgId: string): string;
|
|
7
|
+
/** Absolute path a given log file is (or would be) stored at. */
|
|
8
|
+
pathFor(orgId: string, eventType: string, logDate: string, id: string): string;
|
|
9
|
+
/** True when this EventLogFile is already on disk — the dedup / idempotency check. */
|
|
10
|
+
has(orgId: string, eventType: string, logDate: string, id: string): boolean;
|
|
11
|
+
/** Write a CSV body verbatim; returns the saved path. Best-effort. */
|
|
12
|
+
save(orgId: string, eventType: string, logDate: string, id: string, body: string): string;
|
|
13
|
+
/** Write a per-run manifest JSON under {root}/{orgId}/_manifests/; returns its path. */
|
|
14
|
+
writeManifest(orgId: string, manifest: unknown): string;
|
|
15
|
+
}
|
|
16
|
+
//# sourceMappingURL=EventBaselineStore.d.ts.map
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
// src/events/EventBaselineStore.ts
|
|
2
|
+
// Local, on-disk archive of free EventLogFile CSVs. Mirrors HistoryStore: writes under
|
|
3
|
+
// ~/.sf/event-baseline/{orgId}/, takes an optional root for testability, and is best-effort
|
|
4
|
+
// (warns rather than throws) so a daily cron run never dies on a filesystem hiccup.
|
|
5
|
+
import * as fs from 'node:fs';
|
|
6
|
+
import * as os from 'node:os';
|
|
7
|
+
import * as path from 'node:path';
|
|
8
|
+
export class EventBaselineStore {
|
|
9
|
+
root;
|
|
10
|
+
constructor(root) {
|
|
11
|
+
this.root = root ?? EventBaselineStore.defaultRoot();
|
|
12
|
+
}
|
|
13
|
+
static defaultRoot() {
|
|
14
|
+
return path.join(os.homedir(), '.sf', 'event-baseline');
|
|
15
|
+
}
|
|
16
|
+
/** The per-org base directory logs for this org are stored under. */
|
|
17
|
+
orgDir(orgId) {
|
|
18
|
+
return path.join(this.root, orgId);
|
|
19
|
+
}
|
|
20
|
+
/** Absolute path a given log file is (or would be) stored at. */
|
|
21
|
+
pathFor(orgId, eventType, logDate, id) {
|
|
22
|
+
return path.join(this.root, orgId, eventType, `${logDate}-${id}.csv`);
|
|
23
|
+
}
|
|
24
|
+
/** True when this EventLogFile is already on disk — the dedup / idempotency check. */
|
|
25
|
+
has(orgId, eventType, logDate, id) {
|
|
26
|
+
return fs.existsSync(this.pathFor(orgId, eventType, logDate, id));
|
|
27
|
+
}
|
|
28
|
+
/** Write a CSV body verbatim; returns the saved path. Best-effort. */
|
|
29
|
+
save(orgId, eventType, logDate, id, body) {
|
|
30
|
+
const filePath = this.pathFor(orgId, eventType, logDate, id);
|
|
31
|
+
try {
|
|
32
|
+
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
|
33
|
+
fs.writeFileSync(filePath, body, 'utf-8');
|
|
34
|
+
}
|
|
35
|
+
catch (err) {
|
|
36
|
+
process.stderr.write(`[sf-audit] Warning: could not save event log ${id}: ${String(err)}\n`);
|
|
37
|
+
}
|
|
38
|
+
return filePath;
|
|
39
|
+
}
|
|
40
|
+
/** Write a per-run manifest JSON under {root}/{orgId}/_manifests/; returns its path. */
|
|
41
|
+
writeManifest(orgId, manifest) {
|
|
42
|
+
const dir = path.join(this.root, orgId, '_manifests');
|
|
43
|
+
const suffix = Math.random().toString(36).slice(2, 8);
|
|
44
|
+
const filePath = path.join(dir, `manifest-${Date.now()}-${suffix}.json`);
|
|
45
|
+
try {
|
|
46
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
47
|
+
fs.writeFileSync(filePath, JSON.stringify(manifest, null, 2), 'utf-8');
|
|
48
|
+
}
|
|
49
|
+
catch (err) {
|
|
50
|
+
process.stderr.write(`[sf-audit] Warning: could not write event manifest: ${String(err)}\n`);
|
|
51
|
+
}
|
|
52
|
+
return filePath;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
//# sourceMappingURL=EventBaselineStore.js.map
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { EventLogAccess } from '../context/AuditCache.js';
|
|
2
|
+
/**
|
|
3
|
+
* Classifies why an `EventLogFile` query failed so callers can tell the two very
|
|
4
|
+
* different "no data" causes apart:
|
|
5
|
+
* - 'not-enabled' : Event Monitoring is not licensed/enabled (EventLogFile is
|
|
6
|
+
* an unknown/blocked sObject) — the org captures nothing.
|
|
7
|
+
* - 'no-permission' : the feature is on, but the running audit user lacks the
|
|
8
|
+
* "View Event Log Files" permission — logs exist, we can't read them.
|
|
9
|
+
* - 'unknown' : could not be attributed to either.
|
|
10
|
+
* Both are BLIND for guest-traffic analysis, but the remediation differs (license
|
|
11
|
+
* vs. grant a permission), so the distinction is worth surfacing.
|
|
12
|
+
*/
|
|
13
|
+
export declare function classifyEventLogAccessError(err: unknown): EventLogAccess;
|
|
14
|
+
//# sourceMappingURL=eventLogAccess.d.ts.map
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { isApiError } from '../api/ApiError.js';
|
|
2
|
+
/**
|
|
3
|
+
* Classifies why an `EventLogFile` query failed so callers can tell the two very
|
|
4
|
+
* different "no data" causes apart:
|
|
5
|
+
* - 'not-enabled' : Event Monitoring is not licensed/enabled (EventLogFile is
|
|
6
|
+
* an unknown/blocked sObject) — the org captures nothing.
|
|
7
|
+
* - 'no-permission' : the feature is on, but the running audit user lacks the
|
|
8
|
+
* "View Event Log Files" permission — logs exist, we can't read them.
|
|
9
|
+
* - 'unknown' : could not be attributed to either.
|
|
10
|
+
* Both are BLIND for guest-traffic analysis, but the remediation differs (license
|
|
11
|
+
* vs. grant a permission), so the distinction is worth surfacing.
|
|
12
|
+
*/
|
|
13
|
+
export function classifyEventLogAccessError(err) {
|
|
14
|
+
if (isApiError(err)) {
|
|
15
|
+
if (err.statusCode === 403 || /ACCESS|INSUFFICIENT/i.test(err.errorCode))
|
|
16
|
+
return 'no-permission';
|
|
17
|
+
if (/INVALID_TYPE|NOT_FOUND|MALFORMED_QUERY/i.test(err.errorCode) || err.statusCode === 404 || err.statusCode === 400) {
|
|
18
|
+
return 'not-enabled';
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
const msg = (err instanceof Error ? err.message : String(err)).toLowerCase();
|
|
22
|
+
if (msg.includes('insufficient') || msg.includes('permission') || msg.includes('view event log'))
|
|
23
|
+
return 'no-permission';
|
|
24
|
+
if (msg.includes('not supported') ||
|
|
25
|
+
msg.includes('invalid type') ||
|
|
26
|
+
msg.includes("sobject type 'eventlogfile'") ||
|
|
27
|
+
msg.includes('not enabled') ||
|
|
28
|
+
msg.includes('licens')) {
|
|
29
|
+
return 'not-enabled';
|
|
30
|
+
}
|
|
31
|
+
return 'unknown';
|
|
32
|
+
}
|
|
33
|
+
//# sourceMappingURL=eventLogAccess.js.map
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
export interface EventLogQueryOptions {
|
|
2
|
+
/** Number of days of LogDate to request (LAST_N_DAYS:N). */
|
|
3
|
+
since: number;
|
|
4
|
+
/** Optional EventType allow-list (already sanitised or not — we sanitise again). */
|
|
5
|
+
types?: string[];
|
|
6
|
+
}
|
|
7
|
+
/**
|
|
8
|
+
* Reduce free-form `--types` input to safe EventType tokens. EventTypes are PascalCase
|
|
9
|
+
* identifiers (Login, ApiTotalUsage, LightningError, …), so we strip anything that is not
|
|
10
|
+
* alphanumeric. This doubles as the SOQL-injection guard for the IN clause.
|
|
11
|
+
*/
|
|
12
|
+
export declare function sanitizeTypes(raw: string | undefined): string[];
|
|
13
|
+
/** Normalise a Salesforce LogDate (datetime) to a YYYY-MM-DD string for filenames. */
|
|
14
|
+
export declare function toLogDate(raw: string): string;
|
|
15
|
+
/**
|
|
16
|
+
* Build the read-only EventLogFile discovery query. `Interval = 'Daily'` excludes the paid
|
|
17
|
+
* hourly logs; `LogDate = LAST_N_DAYS:N` bounds the window. `since` is coerced to a
|
|
18
|
+
* non-negative integer and `types` are sanitised, so the interpolated string is injection-safe.
|
|
19
|
+
*/
|
|
20
|
+
export declare function buildEventLogQuery(opts: EventLogQueryOptions): string;
|
|
21
|
+
//# sourceMappingURL=eventLogQuery.d.ts.map
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
// Pure helpers for the `audit events pull` command. Kept free of I/O so they are
|
|
2
|
+
// unit-testable without an org connection or the oclif command harness.
|
|
3
|
+
/**
|
|
4
|
+
* Reduce free-form `--types` input to safe EventType tokens. EventTypes are PascalCase
|
|
5
|
+
* identifiers (Login, ApiTotalUsage, LightningError, …), so we strip anything that is not
|
|
6
|
+
* alphanumeric. This doubles as the SOQL-injection guard for the IN clause.
|
|
7
|
+
*/
|
|
8
|
+
export function sanitizeTypes(raw) {
|
|
9
|
+
if (!raw)
|
|
10
|
+
return [];
|
|
11
|
+
return raw
|
|
12
|
+
.split(',')
|
|
13
|
+
.map((t) => t.replace(/[^A-Za-z0-9]/g, '').trim())
|
|
14
|
+
.filter((t) => t.length > 0);
|
|
15
|
+
}
|
|
16
|
+
/** Normalise a Salesforce LogDate (datetime) to a YYYY-MM-DD string for filenames. */
|
|
17
|
+
export function toLogDate(raw) {
|
|
18
|
+
return String(raw).slice(0, 10);
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Build the read-only EventLogFile discovery query. `Interval = 'Daily'` excludes the paid
|
|
22
|
+
* hourly logs; `LogDate = LAST_N_DAYS:N` bounds the window. `since` is coerced to a
|
|
23
|
+
* non-negative integer and `types` are sanitised, so the interpolated string is injection-safe.
|
|
24
|
+
*/
|
|
25
|
+
export function buildEventLogQuery(opts) {
|
|
26
|
+
const since = Math.max(0, Math.trunc(opts.since));
|
|
27
|
+
const types = (opts.types ?? []).filter((t) => t.length > 0);
|
|
28
|
+
const typeClause = types.length > 0 ? ` AND EventType IN (${types.map((t) => `'${t}'`).join(', ')})` : '';
|
|
29
|
+
return ('SELECT Id, EventType, LogDate, LogFileLength, Interval, LogFileFieldNames ' +
|
|
30
|
+
'FROM EventLogFile ' +
|
|
31
|
+
`WHERE Interval = 'Daily' AND LogDate = LAST_N_DAYS:${since}${typeClause} ` +
|
|
32
|
+
'ORDER BY LogDate');
|
|
33
|
+
}
|
|
34
|
+
//# sourceMappingURL=eventLogQuery.js.map
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import type { SoqlClient } from '../api/SoqlClient.js';
|
|
2
|
+
import type { RestClient } from '../api/RestClient.js';
|
|
3
|
+
import type { EventLogAccess } from '../context/AuditCache.js';
|
|
4
|
+
import { EventBaselineStore } from './EventBaselineStore.js';
|
|
5
|
+
/** The subset of EventLogFile fields the discovery query returns. */
|
|
6
|
+
export interface EventLogFileRow {
|
|
7
|
+
Id: string;
|
|
8
|
+
EventType: string;
|
|
9
|
+
LogDate: string;
|
|
10
|
+
LogFileLength?: number;
|
|
11
|
+
Interval?: string;
|
|
12
|
+
LogFileFieldNames?: string;
|
|
13
|
+
}
|
|
14
|
+
/** Outcome for one EventLogFile row in a run. */
|
|
15
|
+
export interface PulledLog {
|
|
16
|
+
id: string;
|
|
17
|
+
eventType: string;
|
|
18
|
+
logDate: string;
|
|
19
|
+
bytes: number;
|
|
20
|
+
savedPath: string;
|
|
21
|
+
status: 'downloaded' | 'skipped' | 'failed';
|
|
22
|
+
}
|
|
23
|
+
/** Structured result of a pull run — returned by the command. */
|
|
24
|
+
export interface EventsPullResult {
|
|
25
|
+
orgId: string;
|
|
26
|
+
since: number;
|
|
27
|
+
storagePath: string;
|
|
28
|
+
found: number;
|
|
29
|
+
downloaded: number;
|
|
30
|
+
skipped: number;
|
|
31
|
+
failed: number;
|
|
32
|
+
totalBytes: number;
|
|
33
|
+
logs: PulledLog[];
|
|
34
|
+
manifestPath?: string;
|
|
35
|
+
/** Set when the EventLogFile query itself failed (no crash); tells license vs permission apart. */
|
|
36
|
+
accessError?: EventLogAccess;
|
|
37
|
+
}
|
|
38
|
+
export interface PullDeps {
|
|
39
|
+
soql: SoqlClient;
|
|
40
|
+
rest: RestClient;
|
|
41
|
+
store: EventBaselineStore;
|
|
42
|
+
orgId: string;
|
|
43
|
+
}
|
|
44
|
+
export interface PullOptions {
|
|
45
|
+
since: number;
|
|
46
|
+
types?: string[];
|
|
47
|
+
/** Optional sink for non-fatal warnings (per-file download failures). */
|
|
48
|
+
warn?: (msg: string) => void;
|
|
49
|
+
}
|
|
50
|
+
export declare function pullEventLogs(deps: PullDeps, opts: PullOptions): Promise<EventsPullResult>;
|
|
51
|
+
//# sourceMappingURL=pullEventLogs.d.ts.map
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { classifyEventLogAccessError } from './eventLogAccess.js';
|
|
2
|
+
import { buildEventLogQuery, toLogDate } from './eventLogQuery.js';
|
|
3
|
+
export async function pullEventLogs(deps, opts) {
|
|
4
|
+
const { soql, rest, store, orgId } = deps;
|
|
5
|
+
const since = opts.since;
|
|
6
|
+
const storagePath = store.orgDir(orgId);
|
|
7
|
+
const base = {
|
|
8
|
+
orgId,
|
|
9
|
+
since,
|
|
10
|
+
storagePath,
|
|
11
|
+
found: 0,
|
|
12
|
+
downloaded: 0,
|
|
13
|
+
skipped: 0,
|
|
14
|
+
failed: 0,
|
|
15
|
+
totalBytes: 0,
|
|
16
|
+
logs: [],
|
|
17
|
+
};
|
|
18
|
+
let rows;
|
|
19
|
+
try {
|
|
20
|
+
rows = await soql.queryAll(buildEventLogQuery({ since, types: opts.types }));
|
|
21
|
+
}
|
|
22
|
+
catch (err) {
|
|
23
|
+
// Inaccessible EventLogFile (unlicensed / no permission) must not crash the command.
|
|
24
|
+
return { ...base, accessError: classifyEventLogAccessError(err) };
|
|
25
|
+
}
|
|
26
|
+
base.found = rows.length;
|
|
27
|
+
for (const row of rows) {
|
|
28
|
+
const logDate = toLogDate(row.LogDate);
|
|
29
|
+
if (store.has(orgId, row.EventType, logDate, row.Id)) {
|
|
30
|
+
base.skipped += 1;
|
|
31
|
+
base.logs.push({
|
|
32
|
+
id: row.Id,
|
|
33
|
+
eventType: row.EventType,
|
|
34
|
+
logDate,
|
|
35
|
+
bytes: 0,
|
|
36
|
+
savedPath: store.pathFor(orgId, row.EventType, logDate, row.Id),
|
|
37
|
+
status: 'skipped',
|
|
38
|
+
});
|
|
39
|
+
continue;
|
|
40
|
+
}
|
|
41
|
+
try {
|
|
42
|
+
// Stream straight to disk — never buffer the body — so large daily logs don't blow the heap.
|
|
43
|
+
const savedPath = store.pathFor(orgId, row.EventType, logDate, row.Id);
|
|
44
|
+
const bytes = await rest.getRawToFile(`/sobjects/EventLogFile/${row.Id}/LogFile`, savedPath);
|
|
45
|
+
base.downloaded += 1;
|
|
46
|
+
base.totalBytes += bytes;
|
|
47
|
+
base.logs.push({ id: row.Id, eventType: row.EventType, logDate, bytes, savedPath, status: 'downloaded' });
|
|
48
|
+
}
|
|
49
|
+
catch (err) {
|
|
50
|
+
base.failed += 1;
|
|
51
|
+
base.logs.push({
|
|
52
|
+
id: row.Id,
|
|
53
|
+
eventType: row.EventType,
|
|
54
|
+
logDate,
|
|
55
|
+
bytes: 0,
|
|
56
|
+
savedPath: store.pathFor(orgId, row.EventType, logDate, row.Id),
|
|
57
|
+
status: 'failed',
|
|
58
|
+
});
|
|
59
|
+
opts.warn?.(`Failed to download EventLogFile ${row.Id} (${row.EventType} ${logDate}): ${String(err)}`);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
// Only write a manifest when something was actually captured — a pure all-skipped or
|
|
63
|
+
// empty run leaves no new record to make.
|
|
64
|
+
if (base.downloaded > 0) {
|
|
65
|
+
base.manifestPath = store.writeManifest(orgId, {
|
|
66
|
+
orgId,
|
|
67
|
+
since,
|
|
68
|
+
pulledAt: new Date().toISOString(),
|
|
69
|
+
found: base.found,
|
|
70
|
+
downloaded: base.downloaded,
|
|
71
|
+
skipped: base.skipped,
|
|
72
|
+
failed: base.failed,
|
|
73
|
+
totalBytes: base.totalBytes,
|
|
74
|
+
logs: base.logs,
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
return base;
|
|
78
|
+
}
|
|
79
|
+
//# sourceMappingURL=pullEventLogs.js.map
|
package/lib/index.d.ts
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
export * from './api/index.js';
|
|
2
|
+
export type { MetadataClient } from './api/MetadataClient.js';
|
|
3
|
+
export { MetadataClientImpl } from './api/MetadataClientImpl.js';
|
|
4
|
+
export type { OrgInfo } from './context/OrgInfo.js';
|
|
5
|
+
export type { OrgMetrics } from './context/OrgMetrics.js';
|
|
6
|
+
export { EMPTY_METRICS } from './context/OrgMetrics.js';
|
|
7
|
+
export type { AuditOptions, AuditContext } from './context/AuditContext.js';
|
|
8
|
+
export type { HealthCheckRisk, ApexClassBody, VfPageBody, EventLogAccess, EventLogSummary, AgentAccess, AgentDefinition, AgentUser, CspTrustedSite, MfaRegistration, EffectivePermissionGrant, AuditCache, } from './context/AuditCache.js';
|
|
9
|
+
export { EventBaselineStore } from './events/EventBaselineStore.js';
|
|
10
|
+
export type { EventLogQueryOptions } from './events/eventLogQuery.js';
|
|
11
|
+
export { sanitizeTypes, toLogDate, buildEventLogQuery } from './events/eventLogQuery.js';
|
|
12
|
+
export type { EventLogFileRow, PulledLog, EventsPullResult, PullDeps, PullOptions, } from './events/pullEventLogs.js';
|
|
13
|
+
export { pullEventLogs } from './events/pullEventLogs.js';
|
|
14
|
+
export { classifyEventLogAccessError } from './events/eventLogAccess.js';
|
|
15
|
+
export type { Branding, BrandingOverrides } from './report/branding.js';
|
|
16
|
+
export { DEFAULT_BRANDING, resolveBranding } from './report/branding.js';
|
|
17
|
+
export { fontFaceCss, firaFontFaceCss } from './report/fonts.js';
|
|
18
|
+
export { esc } from './renderers/html-utils.js';
|
|
19
|
+
export type { RiskLevel } from './findings/RiskLevel.js';
|
|
20
|
+
export { RISK_LEVELS } from './findings/RiskLevel.js';
|
|
21
|
+
export * from './platform/index.js';
|
|
22
|
+
export * from './schemas/index.js';
|
|
23
|
+
//# sourceMappingURL=index.d.ts.map
|
package/lib/index.js
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
// @cclabsnz/sf-core — shared platform layer for CloudCounsel Salesforce sf plugins.
|
|
2
|
+
// --- API clients ---
|
|
3
|
+
export * from './api/index.js';
|
|
4
|
+
export { MetadataClientImpl } from './api/MetadataClientImpl.js';
|
|
5
|
+
export { EMPTY_METRICS } from './context/OrgMetrics.js';
|
|
6
|
+
// --- Event log ---
|
|
7
|
+
export { EventBaselineStore } from './events/EventBaselineStore.js';
|
|
8
|
+
export { sanitizeTypes, toLogDate, buildEventLogQuery } from './events/eventLogQuery.js';
|
|
9
|
+
export { pullEventLogs } from './events/pullEventLogs.js';
|
|
10
|
+
export { classifyEventLogAccessError } from './events/eventLogAccess.js';
|
|
11
|
+
export { DEFAULT_BRANDING, resolveBranding } from './report/branding.js';
|
|
12
|
+
export { fontFaceCss, firaFontFaceCss } from './report/fonts.js';
|
|
13
|
+
export { esc } from './renderers/html-utils.js';
|
|
14
|
+
export { RISK_LEVELS } from './findings/RiskLevel.js';
|
|
15
|
+
// --- Platform behaviour (API routing, Id validation, repositories) ---
|
|
16
|
+
export * from './platform/index.js';
|
|
17
|
+
// --- IR schemas (typed contracts + JSON schema access) ---
|
|
18
|
+
export * from './schemas/index.js';
|
|
19
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import type { ToolingClient } from '../api/ToolingClient.js';
|
|
2
|
+
export interface ApexClassRecord {
|
|
3
|
+
/** Namespace-qualified name (`ns__Name` where namespaced). */
|
|
4
|
+
name: string;
|
|
5
|
+
namespace: string | null;
|
|
6
|
+
/** Source, or null when the body is withheld (managed package). */
|
|
7
|
+
body: string | null;
|
|
8
|
+
/** Structural symbol table when the org provides one, else null. */
|
|
9
|
+
symbolTable: unknown;
|
|
10
|
+
}
|
|
11
|
+
/** Managed code is excluded with `NamespacePrefix = null` — org-authored classes only. */
|
|
12
|
+
export interface ApexScopeOptions {
|
|
13
|
+
excludeManaged?: boolean;
|
|
14
|
+
}
|
|
15
|
+
export interface ApexTriggerRecord {
|
|
16
|
+
name: string;
|
|
17
|
+
namespace: string | null;
|
|
18
|
+
/** Object API name or key-prefix/durable id — resolve via an ObjectResolver. */
|
|
19
|
+
tableEnumOrId: string;
|
|
20
|
+
body: string | null;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Read access to Apex, encoding the field asymmetry that broke `intel map` against a real
|
|
24
|
+
* org: **`ApexClass` has a `SymbolTable` column and `ApexTrigger` does not.** Selecting it
|
|
25
|
+
* from `ApexTrigger` fails the whole query with
|
|
26
|
+
* `No such column 'SymbolTable' on entity 'ApexTrigger'`, so trigger analysis must fall back
|
|
27
|
+
* to the body.
|
|
28
|
+
*
|
|
29
|
+
* Errors are never swallowed here; callers decide how to report a degraded run.
|
|
30
|
+
*/
|
|
31
|
+
export declare class ApexRepository {
|
|
32
|
+
private readonly tooling;
|
|
33
|
+
constructor(tooling: ToolingClient);
|
|
34
|
+
/** Apex classes, including the SymbolTable this entity does provide. */
|
|
35
|
+
listClasses(opts?: ApexScopeOptions): Promise<ApexClassRecord[]>;
|
|
36
|
+
/** Apex triggers. Deliberately omits SymbolTable — the column does not exist here. */
|
|
37
|
+
listTriggers(opts?: ApexScopeOptions): Promise<ApexTriggerRecord[]>;
|
|
38
|
+
/** Class count, without transferring bodies. */
|
|
39
|
+
countClasses(opts?: ApexScopeOptions): Promise<number>;
|
|
40
|
+
/** Trigger count, without transferring bodies. */
|
|
41
|
+
countTriggers(opts?: ApexScopeOptions): Promise<number>;
|
|
42
|
+
/**
|
|
43
|
+
* Map class id -> name for the given ids. Ids are validated and de-duplicated first: a
|
|
44
|
+
* malformed value reaching a WHERE clause fails the entire query with `invalid ID field`,
|
|
45
|
+
* losing every good row alongside the bad one.
|
|
46
|
+
*/
|
|
47
|
+
namesByIds(ids: readonly string[]): Promise<Map<string, string>>;
|
|
48
|
+
private count;
|
|
49
|
+
}
|
|
50
|
+
//# sourceMappingURL=apexRepository.d.ts.map
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { isSalesforceId, qualifiedName, usableApexBody } from './salesforceId.js';
|
|
2
|
+
/**
|
|
3
|
+
* Read access to Apex, encoding the field asymmetry that broke `intel map` against a real
|
|
4
|
+
* org: **`ApexClass` has a `SymbolTable` column and `ApexTrigger` does not.** Selecting it
|
|
5
|
+
* from `ApexTrigger` fails the whole query with
|
|
6
|
+
* `No such column 'SymbolTable' on entity 'ApexTrigger'`, so trigger analysis must fall back
|
|
7
|
+
* to the body.
|
|
8
|
+
*
|
|
9
|
+
* Errors are never swallowed here; callers decide how to report a degraded run.
|
|
10
|
+
*/
|
|
11
|
+
export class ApexRepository {
|
|
12
|
+
tooling;
|
|
13
|
+
constructor(tooling) {
|
|
14
|
+
this.tooling = tooling;
|
|
15
|
+
}
|
|
16
|
+
/** Apex classes, including the SymbolTable this entity does provide. */
|
|
17
|
+
async listClasses(opts = {}) {
|
|
18
|
+
const rows = await this.tooling.query(`SELECT Name, NamespacePrefix, Body, SymbolTable FROM ApexClass${scope(opts)}`);
|
|
19
|
+
return rows.map((r) => ({
|
|
20
|
+
name: qualifiedName(r.Name, r.NamespacePrefix),
|
|
21
|
+
namespace: r.NamespacePrefix ?? null,
|
|
22
|
+
body: usableApexBody(r.Body),
|
|
23
|
+
symbolTable: r.SymbolTable ?? null,
|
|
24
|
+
}));
|
|
25
|
+
}
|
|
26
|
+
/** Apex triggers. Deliberately omits SymbolTable — the column does not exist here. */
|
|
27
|
+
async listTriggers(opts = {}) {
|
|
28
|
+
const rows = await this.tooling.query(`SELECT Name, NamespacePrefix, TableEnumOrId, Body FROM ApexTrigger${scope(opts)}`);
|
|
29
|
+
return rows.map((r) => ({
|
|
30
|
+
name: qualifiedName(r.Name, r.NamespacePrefix),
|
|
31
|
+
namespace: r.NamespacePrefix ?? null,
|
|
32
|
+
tableEnumOrId: r.TableEnumOrId,
|
|
33
|
+
body: usableApexBody(r.Body),
|
|
34
|
+
}));
|
|
35
|
+
}
|
|
36
|
+
/** Class count, without transferring bodies. */
|
|
37
|
+
async countClasses(opts = {}) {
|
|
38
|
+
return this.count('ApexClass', opts);
|
|
39
|
+
}
|
|
40
|
+
/** Trigger count, without transferring bodies. */
|
|
41
|
+
async countTriggers(opts = {}) {
|
|
42
|
+
return this.count('ApexTrigger', opts);
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Map class id -> name for the given ids. Ids are validated and de-duplicated first: a
|
|
46
|
+
* malformed value reaching a WHERE clause fails the entire query with `invalid ID field`,
|
|
47
|
+
* losing every good row alongside the bad one.
|
|
48
|
+
*/
|
|
49
|
+
async namesByIds(ids) {
|
|
50
|
+
const valid = [...new Set(ids.filter(isSalesforceId))];
|
|
51
|
+
if (valid.length === 0)
|
|
52
|
+
return new Map();
|
|
53
|
+
const list = valid.map((id) => `'${id}'`).join(', ');
|
|
54
|
+
const rows = await this.tooling.query(`SELECT Id, Name FROM ApexClass WHERE Id IN (${list})`);
|
|
55
|
+
return new Map(rows.map((r) => [r.Id, r.Name]));
|
|
56
|
+
}
|
|
57
|
+
async count(entity, opts) {
|
|
58
|
+
// An aggregate needs an explicit alias, because a bare COUNT() reports through
|
|
59
|
+
// `totalSize`, which the ToolingClient return type does not carry. The alias must not be
|
|
60
|
+
// `expr0` — that is Salesforce's own auto-generated name and the API rejects it with
|
|
61
|
+
// "alias is reserved: expr0".
|
|
62
|
+
const rows = await this.tooling.query(`SELECT COUNT(Id) cnt FROM ${entity}${scope(opts)}`);
|
|
63
|
+
return rows[0]?.cnt ?? 0;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
function scope(opts) {
|
|
67
|
+
return opts.excludeManaged ? ' WHERE NamespacePrefix = null' : '';
|
|
68
|
+
}
|
|
69
|
+
//# sourceMappingURL=apexRepository.js.map
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Run `fn` over `items` with at most `limit` promises in flight.
|
|
3
|
+
*
|
|
4
|
+
* Exists because some Salesforce reads cannot be batched at all — `Flow.Metadata` is
|
|
5
|
+
* strictly one row per query — so bounded concurrency is the only way to make a bulk read
|
|
6
|
+
* finish in reasonable time. Completion order is not preserved; sort results if output
|
|
7
|
+
* determinism matters.
|
|
8
|
+
*/
|
|
9
|
+
export declare function mapWithConcurrency<T>(items: readonly T[], limit: number, fn: (item: T, index: number) => Promise<void>): Promise<void>;
|
|
10
|
+
//# sourceMappingURL=concurrency.d.ts.map
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Run `fn` over `items` with at most `limit` promises in flight.
|
|
3
|
+
*
|
|
4
|
+
* Exists because some Salesforce reads cannot be batched at all — `Flow.Metadata` is
|
|
5
|
+
* strictly one row per query — so bounded concurrency is the only way to make a bulk read
|
|
6
|
+
* finish in reasonable time. Completion order is not preserved; sort results if output
|
|
7
|
+
* determinism matters.
|
|
8
|
+
*/
|
|
9
|
+
export async function mapWithConcurrency(items, limit, fn) {
|
|
10
|
+
if (limit < 1)
|
|
11
|
+
throw new Error(`Concurrency limit must be >= 1, got ${limit}`);
|
|
12
|
+
let next = 0;
|
|
13
|
+
const workers = Array.from({ length: Math.min(limit, items.length) }, async () => {
|
|
14
|
+
while (next < items.length) {
|
|
15
|
+
const i = next++;
|
|
16
|
+
await fn(items[i], i);
|
|
17
|
+
}
|
|
18
|
+
});
|
|
19
|
+
await Promise.all(workers);
|
|
20
|
+
}
|
|
21
|
+
//# sourceMappingURL=concurrency.js.map
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import type { SoqlClient } from '../api/SoqlClient.js';
|
|
2
|
+
import type { ToolingClient } from '../api/ToolingClient.js';
|
|
3
|
+
/** A row of `FlowDefinitionView` as the map pipeline needs it. */
|
|
4
|
+
export interface FlowDefinitionRecord {
|
|
5
|
+
apiName: string;
|
|
6
|
+
isActive: boolean;
|
|
7
|
+
activeVersionId: string | null;
|
|
8
|
+
latestVersionId: string | null;
|
|
9
|
+
}
|
|
10
|
+
/** A row of `FlowDefinitionView` as the automation index needs it. */
|
|
11
|
+
export interface FlowTriggerRecord {
|
|
12
|
+
triggerType: string | null;
|
|
13
|
+
triggerObjectOrEventLabel: string | null;
|
|
14
|
+
isActive: boolean;
|
|
15
|
+
}
|
|
16
|
+
export interface FlowVersionRef {
|
|
17
|
+
/** A real Salesforce Id, safe to place in a WHERE clause. */
|
|
18
|
+
id: string;
|
|
19
|
+
apiName: string;
|
|
20
|
+
}
|
|
21
|
+
/** An active flow version as the security checks need it (no Metadata — see class doc). */
|
|
22
|
+
export interface ActiveFlowVersion {
|
|
23
|
+
id: string;
|
|
24
|
+
masterLabel: string;
|
|
25
|
+
processType: string | null;
|
|
26
|
+
status: string | null;
|
|
27
|
+
runInMode: string | null;
|
|
28
|
+
}
|
|
29
|
+
export interface SelectedFlowVersions {
|
|
30
|
+
versions: FlowVersionRef[];
|
|
31
|
+
/** Managed-package flows whose version "Id" was a durable name and so cannot be read. */
|
|
32
|
+
managedSkipped: number;
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Read access to Flow metadata, encoding two platform facts that are easy to get wrong:
|
|
36
|
+
*
|
|
37
|
+
* 1. **`FlowDefinitionView` is a STANDARD object, not a Tooling one.** Querying it through
|
|
38
|
+
* the Tooling endpoint answers `sObject type 'FlowDefinitionView' is not supported.`
|
|
39
|
+
* 2. **`Flow.Metadata` *is* Tooling, and is strictly one row per query.** An `Id IN (...)`
|
|
40
|
+
* batch is rejected: *"When retrieving results with Metadata or FullName fields, the
|
|
41
|
+
* query qualifications must specify no more than one row for retrieval."* Concurrency is
|
|
42
|
+
* the only lever for bulk reads — see `mapWithConcurrency`.
|
|
43
|
+
*
|
|
44
|
+
* Errors are never swallowed here; callers decide how to report a degraded run.
|
|
45
|
+
*/
|
|
46
|
+
export declare class FlowRepository {
|
|
47
|
+
private readonly soql;
|
|
48
|
+
private readonly tooling;
|
|
49
|
+
constructor(soql: SoqlClient, tooling: ToolingClient);
|
|
50
|
+
/** Flow definitions and their version Ids. Standard API. */
|
|
51
|
+
listDefinitions(): Promise<FlowDefinitionRecord[]>;
|
|
52
|
+
/** Trigger configuration per flow, for automation counting. Standard API. */
|
|
53
|
+
listTriggerViews(): Promise<FlowTriggerRecord[]>;
|
|
54
|
+
/**
|
|
55
|
+
* Pick the version to analyse per definition, dropping managed-package flows whose version
|
|
56
|
+
* "Id" is a durable name rather than an Id. Pure — no org access.
|
|
57
|
+
*/
|
|
58
|
+
static selectVersions(definitions: readonly FlowDefinitionRecord[], opts?: {
|
|
59
|
+
includeInactive?: boolean;
|
|
60
|
+
}): SelectedFlowVersions;
|
|
61
|
+
/**
|
|
62
|
+
* The structured metadata for one flow version (equivalent to its XML), or null if the
|
|
63
|
+
* org returned no row. Tooling API, one row per call — see the class doc.
|
|
64
|
+
*/
|
|
65
|
+
fetchMetadata(versionId: string): Promise<unknown | null>;
|
|
66
|
+
/**
|
|
67
|
+
* Active flow versions with their run mode. Tooling, but deliberately *without* Metadata —
|
|
68
|
+
* selecting it would impose the one-row-per-query rule and make this unusable in bulk.
|
|
69
|
+
*/
|
|
70
|
+
listActiveVersions(): Promise<ActiveFlowVersion[]>;
|
|
71
|
+
}
|
|
72
|
+
//# sourceMappingURL=flowRepository.d.ts.map
|