@cclabsnz/sf-core 0.1.5 → 0.3.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.
@@ -0,0 +1,68 @@
1
+ /** Why something present in the request is absent from the capture. Closed set — consumers branch on it. */
2
+ export type SkipReason = 'not-in-core-set' | 'already-captured' | 'download-failed' | 'too-large' | 'unlicensed' | 'storage-disabled' | 'no-permission' | 'not-queryable' | 'unknown';
3
+ export declare const SKIP_REASONS: readonly SkipReason[];
4
+ export declare function isSkipReason(value: unknown): value is SkipReason;
5
+ export interface CapturedElfFile {
6
+ type: string;
7
+ id: string;
8
+ logDate: string;
9
+ /** Absent for a daily file. */
10
+ hour?: string;
11
+ bytes: number;
12
+ path: string;
13
+ }
14
+ export interface SkippedElfFile {
15
+ type: string;
16
+ id?: string;
17
+ logDate?: string;
18
+ hour?: string;
19
+ reason: SkipReason;
20
+ detail?: string;
21
+ }
22
+ export interface CapturedRteObject {
23
+ object: string;
24
+ rows: number;
25
+ /** Which name actually answered — the base object or its retained-rows Store counterpart. */
26
+ via: 'base' | 'store';
27
+ paths: string[];
28
+ }
29
+ export interface UnavailableRteObject {
30
+ object: string;
31
+ reason: SkipReason;
32
+ detail?: string;
33
+ }
34
+ export interface CaptureCoverage {
35
+ orgId: string;
36
+ capturedAt: string;
37
+ window?: {
38
+ from: string;
39
+ to: string;
40
+ };
41
+ since?: number;
42
+ interval: 'Daily' | 'Hourly' | 'both';
43
+ elf: {
44
+ requestedTypes: string[];
45
+ captured: CapturedElfFile[];
46
+ skipped: SkippedElfFile[];
47
+ failed: SkippedElfFile[];
48
+ };
49
+ rte: {
50
+ captured: CapturedRteObject[];
51
+ unavailable: UnavailableRteObject[];
52
+ };
53
+ /** Query-level failures — an inaccessible EventLogFile object, say. Empty is the good case. */
54
+ accessErrors: Array<{
55
+ scope: string;
56
+ reason: string;
57
+ detail?: string;
58
+ }>;
59
+ }
60
+ /** An empty coverage record for one org, ready to be filled in as a pull proceeds. */
61
+ export declare function emptyCoverage(orgId: string, interval: CaptureCoverage['interval'], capturedAt: string): CaptureCoverage;
62
+ /**
63
+ * Read a coverage manifest back off disk. Returns undefined rather than throwing on a missing
64
+ * or malformed file: a consumer scanning a directory of manifests should skip the bad one and
65
+ * carry on, not abort the scan.
66
+ */
67
+ export declare function readCoverageManifest(filePath: string): CaptureCoverage | undefined;
68
+ //# sourceMappingURL=CaptureManifest.d.ts.map
@@ -0,0 +1,55 @@
1
+ // src/events/CaptureManifest.ts
2
+ // The per-pull coverage record. Its whole reason to exist is letting a downstream consumer
3
+ // tell *nothing happened* from *nothing was captured* — an empty result set is only evidence
4
+ // of absence if you know the capture was actually possible and actually ran.
5
+ //
6
+ // That is why `reason` is a closed enum rather than free text: a consumer branches on it, and
7
+ // "unlicensed" vs "storage-disabled" vs "no-permission" are three different answers to
8
+ // "should I trust this silence?" with three different remediations.
9
+ import * as fs from 'node:fs';
10
+ export const SKIP_REASONS = [
11
+ 'not-in-core-set',
12
+ 'already-captured',
13
+ 'download-failed',
14
+ 'too-large',
15
+ 'unlicensed',
16
+ 'storage-disabled',
17
+ 'no-permission',
18
+ 'not-queryable',
19
+ 'unknown',
20
+ ];
21
+ export function isSkipReason(value) {
22
+ return typeof value === 'string' && SKIP_REASONS.includes(value);
23
+ }
24
+ /** An empty coverage record for one org, ready to be filled in as a pull proceeds. */
25
+ export function emptyCoverage(orgId, interval, capturedAt) {
26
+ return {
27
+ orgId,
28
+ capturedAt,
29
+ interval,
30
+ elf: { requestedTypes: [], captured: [], skipped: [], failed: [] },
31
+ rte: { captured: [], unavailable: [] },
32
+ accessErrors: [],
33
+ };
34
+ }
35
+ /**
36
+ * Read a coverage manifest back off disk. Returns undefined rather than throwing on a missing
37
+ * or malformed file: a consumer scanning a directory of manifests should skip the bad one and
38
+ * carry on, not abort the scan.
39
+ */
40
+ export function readCoverageManifest(filePath) {
41
+ try {
42
+ const parsed = JSON.parse(fs.readFileSync(filePath, 'utf-8'));
43
+ return isCoverage(parsed) ? parsed : undefined;
44
+ }
45
+ catch {
46
+ return undefined;
47
+ }
48
+ }
49
+ function isCoverage(value) {
50
+ if (typeof value !== 'object' || value === null)
51
+ return false;
52
+ const c = value;
53
+ return typeof c.orgId === 'string' && typeof c.capturedAt === 'string' && typeof c.elf === 'object';
54
+ }
55
+ //# sourceMappingURL=CaptureManifest.js.map
@@ -4,13 +4,50 @@ export declare class EventBaselineStore {
4
4
  static defaultRoot(): string;
5
5
  /** The per-org base directory logs for this org are stored under. */
6
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;
7
+ /**
8
+ * Absolute path a given log file is (or would be) stored at. Pass `hour` ('00'–'23', UTC)
9
+ * for an hourly capture; omit it and the layout is exactly what it has always been.
10
+ *
11
+ * `id` stays in the hourly path because a single (type, hour) can hold several files — a
12
+ * verified case had two AuraRequest rows for the same hour.
13
+ */
14
+ pathFor(orgId: string, eventType: string, logDate: string, id: string, hour?: string): string;
15
+ /**
16
+ * True when this EventLogFile is already captured — the dedup / idempotency check.
17
+ *
18
+ * Requires a non-empty file, not merely an existing one. A zero-byte file is what a run
19
+ * killed between create and write leaves behind, and treating that as captured would retire
20
+ * the row permanently: every later run skips it, and the gap never appears in any manifest.
21
+ */
22
+ has(orgId: string, eventType: string, logDate: string, id: string, hour?: string): boolean;
11
23
  /** 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. */
24
+ save(orgId: string, eventType: string, logDate: string, id: string, body: string, hour?: string): string;
25
+ /** Absolute path the NDJSON for one Real-Time Event object-hour is (or would be) stored at. */
26
+ realtimePathFor(orgId: string, objectName: string, logDate: string, hour: string): string;
27
+ /** True when this object-hour already holds a complete NDJSON file. */
28
+ hasRealtime(orgId: string, objectName: string, logDate: string, hour: string): boolean;
29
+ /**
30
+ * Write RTE rows as NDJSON — one JSON object per line, so the file stays parseable line by
31
+ * line and a reader never has to hold the whole set in memory.
32
+ *
33
+ * Written to a temporary file and renamed into place. The earlier rationale — that a
34
+ * half-written NDJSON is still parseable up to the last complete line — is true but beside
35
+ * the point: `hasRealtime` cannot distinguish a truncated file from a complete one, so a
36
+ * partial write would be skipped by every later run and silently pass as full coverage.
37
+ * Rename is atomic within a filesystem, so the file is either absent or whole.
38
+ */
39
+ saveRealtime(orgId: string, objectName: string, logDate: string, hour: string, rows: readonly unknown[]): string;
40
+ /**
41
+ * Write a per-run coverage manifest under {root}/{orgId}/_manifests/. Named `coverage-*` to
42
+ * keep it distinguishable from the legacy `manifest-*` files a consumer may still find in
43
+ * the same directory.
44
+ */
45
+ writeCoverageManifest(orgId: string, manifest: unknown): string;
46
+ /**
47
+ * @deprecated Superseded by {@link writeCoverageManifest}, which records why nothing was
48
+ * captured as well as what was. Retained so existing readers of `manifest-*.json` keep working.
49
+ */
14
50
  writeManifest(orgId: string, manifest: unknown): string;
51
+ private writeManifestAs;
15
52
  }
16
53
  //# sourceMappingURL=EventBaselineStore.d.ts.map
@@ -1,7 +1,19 @@
1
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.
2
+ // Local, on-disk archive of EventLogFile CSVs and Real-Time Event NDJSON. Mirrors HistoryStore:
3
+ // writes under ~/.sf/event-baseline/{orgId}/, takes an optional root for testability, and is
4
+ // best-effort (warns rather than throws) so a scheduled run never dies on a filesystem hiccup.
5
+ //
6
+ // Path layout — this is the contract downstream consumers read against:
7
+ //
8
+ // {base}/{orgId}/
9
+ // {EventType}/{YYYY-MM-DD}-{id}.csv daily
10
+ // {EventType}/{YYYY-MM-DD}/{HH}-{id}.csv hourly
11
+ // _realtime/{ObjectName}/{YYYY-MM-DD}/{HH}.ndjson
12
+ // _manifests/coverage-{epochMs}-{rand}.json
13
+ //
14
+ // The daily and hourly forms cannot collide: the daily form is a *file* named
15
+ // `{date}-{id}.csv` while the hourly form nests a *directory* named `{date}`. Daily archives
16
+ // written by earlier versions therefore keep resolving with no migration.
5
17
  import * as fs from 'node:fs';
6
18
  import * as os from 'node:os';
7
19
  import * as path from 'node:path';
@@ -15,36 +27,94 @@ export class EventBaselineStore {
15
27
  }
16
28
  /** The per-org base directory logs for this org are stored under. */
17
29
  orgDir(orgId) {
18
- return path.join(this.root, orgId);
30
+ return path.join(this.root, segment(orgId));
19
31
  }
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`);
32
+ /**
33
+ * Absolute path a given log file is (or would be) stored at. Pass `hour` ('00'–'23', UTC)
34
+ * for an hourly capture; omit it and the layout is exactly what it has always been.
35
+ *
36
+ * `id` stays in the hourly path because a single (type, hour) can hold several files — a
37
+ * verified case had two AuraRequest rows for the same hour.
38
+ */
39
+ pathFor(orgId, eventType, logDate, id, hour) {
40
+ const [o, t, d, i] = [orgId, eventType, logDate, id].map(segment);
41
+ return hour === undefined
42
+ ? path.join(this.root, o, t, `${d}-${i}.csv`)
43
+ : path.join(this.root, o, t, d, `${padHour(hour)}-${i}.csv`);
23
44
  }
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));
45
+ /**
46
+ * True when this EventLogFile is already captured — the dedup / idempotency check.
47
+ *
48
+ * Requires a non-empty file, not merely an existing one. A zero-byte file is what a run
49
+ * killed between create and write leaves behind, and treating that as captured would retire
50
+ * the row permanently: every later run skips it, and the gap never appears in any manifest.
51
+ */
52
+ has(orgId, eventType, logDate, id, hour) {
53
+ return nonEmpty(this.pathFor(orgId, eventType, logDate, id, hour));
27
54
  }
28
55
  /** 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);
56
+ save(orgId, eventType, logDate, id, body, hour) {
57
+ const filePath = this.pathFor(orgId, eventType, logDate, id, hour);
31
58
  try {
32
- fs.mkdirSync(path.dirname(filePath), { recursive: true });
33
- fs.writeFileSync(filePath, body, 'utf-8');
59
+ writeAtomic(filePath, body);
34
60
  }
35
61
  catch (err) {
36
62
  process.stderr.write(`[sf-audit] Warning: could not save event log ${id}: ${String(err)}\n`);
37
63
  }
38
64
  return filePath;
39
65
  }
40
- /** Write a per-run manifest JSON under {root}/{orgId}/_manifests/; returns its path. */
66
+ /** Absolute path the NDJSON for one Real-Time Event object-hour is (or would be) stored at. */
67
+ realtimePathFor(orgId, objectName, logDate, hour) {
68
+ const [o, n, d] = [orgId, objectName, logDate].map(segment);
69
+ return path.join(this.root, o, '_realtime', n, d, `${padHour(hour)}.ndjson`);
70
+ }
71
+ /** True when this object-hour already holds a complete NDJSON file. */
72
+ hasRealtime(orgId, objectName, logDate, hour) {
73
+ return nonEmpty(this.realtimePathFor(orgId, objectName, logDate, hour));
74
+ }
75
+ /**
76
+ * Write RTE rows as NDJSON — one JSON object per line, so the file stays parseable line by
77
+ * line and a reader never has to hold the whole set in memory.
78
+ *
79
+ * Written to a temporary file and renamed into place. The earlier rationale — that a
80
+ * half-written NDJSON is still parseable up to the last complete line — is true but beside
81
+ * the point: `hasRealtime` cannot distinguish a truncated file from a complete one, so a
82
+ * partial write would be skipped by every later run and silently pass as full coverage.
83
+ * Rename is atomic within a filesystem, so the file is either absent or whole.
84
+ */
85
+ saveRealtime(orgId, objectName, logDate, hour, rows) {
86
+ const filePath = this.realtimePathFor(orgId, objectName, logDate, hour);
87
+ try {
88
+ writeAtomic(filePath, rows.map((r) => JSON.stringify(r)).join('\n') + '\n');
89
+ }
90
+ catch (err) {
91
+ process.stderr.write(`[sf-audit] Warning: could not save realtime events ${objectName} ${logDate} ${hour}: ${String(err)}\n`);
92
+ }
93
+ return filePath;
94
+ }
95
+ /**
96
+ * Write a per-run coverage manifest under {root}/{orgId}/_manifests/. Named `coverage-*` to
97
+ * keep it distinguishable from the legacy `manifest-*` files a consumer may still find in
98
+ * the same directory.
99
+ */
100
+ writeCoverageManifest(orgId, manifest) {
101
+ return this.writeManifestAs(orgId, 'coverage', manifest);
102
+ }
103
+ /**
104
+ * @deprecated Superseded by {@link writeCoverageManifest}, which records why nothing was
105
+ * captured as well as what was. Retained so existing readers of `manifest-*.json` keep working.
106
+ */
41
107
  writeManifest(orgId, manifest) {
42
- const dir = path.join(this.root, orgId, '_manifests');
108
+ return this.writeManifestAs(orgId, 'manifest', manifest);
109
+ }
110
+ writeManifestAs(orgId, prefix, manifest) {
111
+ const dir = path.join(this.root, segment(orgId), '_manifests');
43
112
  const suffix = Math.random().toString(36).slice(2, 8);
44
- const filePath = path.join(dir, `manifest-${Date.now()}-${suffix}.json`);
113
+ const filePath = path.join(dir, `${prefix}-${Date.now()}-${suffix}.json`);
45
114
  try {
46
- fs.mkdirSync(dir, { recursive: true });
47
- fs.writeFileSync(filePath, JSON.stringify(manifest, null, 2), 'utf-8');
115
+ // Atomic for the same reason as the captures: a reader scanning _manifests must never
116
+ // parse a half-written coverage record and conclude the run captured less than it did.
117
+ writeAtomic(filePath, JSON.stringify(manifest, null, 2));
48
118
  }
49
119
  catch (err) {
50
120
  process.stderr.write(`[sf-audit] Warning: could not write event manifest: ${String(err)}\n`);
@@ -52,4 +122,49 @@ export class EventBaselineStore {
52
122
  return filePath;
53
123
  }
54
124
  }
125
+ /** Hours are stored zero-padded so lexical order matches chronological order. */
126
+ function padHour(hour) {
127
+ return String(segment(String(hour))).padStart(2, '0');
128
+ }
129
+ /**
130
+ * Constrain one org-supplied value to a single safe path segment.
131
+ *
132
+ * EventType, RTE object names, org ids and file ids all arrive from query results and are
133
+ * joined straight into a filesystem path. They are Salesforce identifiers in practice, but
134
+ * "in practice" is not a boundary: a value of `../../..` would place captured evidence
135
+ * outside the store, and this package writes to a directory under the operator's home. So
136
+ * anything that is not an identifier character is folded to `_`, and a segment that reduces
137
+ * to nothing (or to dots) becomes `_` rather than silently resolving to a parent directory.
138
+ */
139
+ function segment(raw) {
140
+ const cleaned = String(raw).replace(/[^A-Za-z0-9._-]/g, '_');
141
+ return cleaned.length === 0 || /^\.+$/.test(cleaned) ? '_' : cleaned;
142
+ }
143
+ /** True when the path holds a file with at least one byte. */
144
+ function nonEmpty(filePath) {
145
+ try {
146
+ return fs.statSync(filePath).size > 0;
147
+ }
148
+ catch {
149
+ return false;
150
+ }
151
+ }
152
+ /**
153
+ * Write via a temporary file and rename into place, so a reader never observes a partial
154
+ * file. The temp name carries the pid so two concurrent pulls of the same org — a cron run
155
+ * overlapping a manual one — cannot corrupt each other's staging file.
156
+ */
157
+ function writeAtomic(filePath, body) {
158
+ const dir = path.dirname(filePath);
159
+ fs.mkdirSync(dir, { recursive: true });
160
+ const tmp = path.join(dir, `.${path.basename(filePath)}.${process.pid}.tmp`);
161
+ try {
162
+ fs.writeFileSync(tmp, body, 'utf-8');
163
+ fs.renameSync(tmp, filePath);
164
+ }
165
+ catch (err) {
166
+ fs.rmSync(tmp, { force: true });
167
+ throw err;
168
+ }
169
+ }
55
170
  //# sourceMappingURL=EventBaselineStore.js.map
@@ -1,9 +1,29 @@
1
+ /** Which EventLogFile Interval to discover. `both` omits the predicate entirely. */
2
+ export type EventLogInterval = 'Daily' | 'Hourly' | 'both';
3
+ /** An explicit, bounded LogDate window. Both bounds are inclusive ISO8601 instants. */
4
+ export interface EventLogWindow {
5
+ from: string;
6
+ to: string;
7
+ }
1
8
  export interface EventLogQueryOptions {
2
- /** Number of days of LogDate to request (LAST_N_DAYS:N). */
3
- since: number;
9
+ /** Number of days of LogDate to request (LAST_N_DAYS:N). Mutually exclusive with `window`. */
10
+ since?: number;
11
+ /** Explicit LogDate bounds. Mutually exclusive with `since`. */
12
+ window?: EventLogWindow;
13
+ /** Defaults to 'Daily', which preserves the free-tier behaviour byte-for-byte. */
14
+ interval?: EventLogInterval;
4
15
  /** Optional EventType allow-list (already sanitised or not — we sanitise again). */
5
16
  types?: string[];
6
17
  }
18
+ /**
19
+ * The EventTypes worth capturing hourly. Deliberately a short list: hourly capture of every
20
+ * type runs to ~25GB/month on a busy org, against ~1–2GB for these. They are the types that
21
+ * carry either the access evidence itself or the join keys (REQUEST_ID, CLIENT_IP,
22
+ * SESSION_KEY, LOGIN_KEY) a consumer needs to tie types together.
23
+ *
24
+ * Exported as data so downstream packages can name the same default rather than duplicate it.
25
+ */
26
+ export declare const HOURLY_FORENSIC_CORE: readonly ["AuraRequest", "Sites", "URI", "UniqueQuery", "GraphQlQueryExecution", "ApexExecution", "RestApi", "API", "Login", "Logout"];
7
27
  /**
8
28
  * Reduce free-form `--types` input to safe EventType tokens. EventTypes are PascalCase
9
29
  * identifiers (Login, ApiTotalUsage, LightningError, …), so we strip anything that is not
@@ -13,9 +33,25 @@ export declare function sanitizeTypes(raw: string | undefined): string[];
13
33
  /** Normalise a Salesforce LogDate (datetime) to a YYYY-MM-DD string for filenames. */
14
34
  export declare function toLogDate(raw: string): string;
15
35
  /**
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.
36
+ * Extract the zero-padded UTC hour ('00'–'23') from a Salesforce LogDate. Returns undefined
37
+ * when the value carries no time component, which is how a Daily row is told from an Hourly
38
+ * one without trusting the Interval field alone.
39
+ */
40
+ export declare function toLogHour(raw: string): string | undefined;
41
+ /**
42
+ * Build the read-only EventLogFile discovery query.
43
+ *
44
+ * `Interval = 'Daily'` (the default) excludes the paid hourly logs and emits exactly the SOQL
45
+ * this function has always emitted — free-tier callers are unaffected. `'Hourly'` selects the
46
+ * paid logs; `'both'` omits the predicate rather than emitting `IN ('Daily','Hourly')`, which
47
+ * is the same result set with fewer moving parts.
48
+ *
49
+ * NOTE: never probe for hourly rows with a `GROUP BY Interval` aggregate. A verified quirk of
50
+ * the platform is that such a query reports only `Daily` even in orgs where an explicit
51
+ * `WHERE Interval = 'Hourly'` returns thousands of rows.
52
+ *
53
+ * `since` is coerced to a non-negative integer, `window` bounds are shape-validated and
54
+ * `types` are sanitised, so the interpolated string is injection-safe.
19
55
  */
20
56
  export declare function buildEventLogQuery(opts: EventLogQueryOptions): string;
21
57
  //# sourceMappingURL=eventLogQuery.d.ts.map
@@ -1,5 +1,25 @@
1
1
  // Pure helpers for the `audit events pull` command. Kept free of I/O so they are
2
2
  // unit-testable without an org connection or the oclif command harness.
3
+ /**
4
+ * The EventTypes worth capturing hourly. Deliberately a short list: hourly capture of every
5
+ * type runs to ~25GB/month on a busy org, against ~1–2GB for these. They are the types that
6
+ * carry either the access evidence itself or the join keys (REQUEST_ID, CLIENT_IP,
7
+ * SESSION_KEY, LOGIN_KEY) a consumer needs to tie types together.
8
+ *
9
+ * Exported as data so downstream packages can name the same default rather than duplicate it.
10
+ */
11
+ export const HOURLY_FORENSIC_CORE = [
12
+ 'AuraRequest',
13
+ 'Sites',
14
+ 'URI',
15
+ 'UniqueQuery',
16
+ 'GraphQlQueryExecution',
17
+ 'ApexExecution',
18
+ 'RestApi',
19
+ 'API',
20
+ 'Login',
21
+ 'Logout',
22
+ ];
3
23
  /**
4
24
  * Reduce free-form `--types` input to safe EventType tokens. EventTypes are PascalCase
5
25
  * identifiers (Login, ApiTotalUsage, LightningError, …), so we strip anything that is not
@@ -18,17 +38,59 @@ export function toLogDate(raw) {
18
38
  return String(raw).slice(0, 10);
19
39
  }
20
40
  /**
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.
41
+ * Extract the zero-padded UTC hour ('00'–'23') from a Salesforce LogDate. Returns undefined
42
+ * when the value carries no time component, which is how a Daily row is told from an Hourly
43
+ * one without trusting the Interval field alone.
44
+ */
45
+ export function toLogHour(raw) {
46
+ const match = /T(\d{2}):/.exec(String(raw));
47
+ return match ? match[1] : undefined;
48
+ }
49
+ /**
50
+ * Salesforce rejects a bare ISO instant in SOQL if it carries milliseconds or a `Z` the
51
+ * driver has not normalised, so bounds are validated to the shape the platform accepts and
52
+ * interpolated only once proven safe. Anything else throws rather than reaching the org.
53
+ */
54
+ const SOQL_DATETIME = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?(?:Z|[+-]\d{2}:\d{2})$/;
55
+ function assertDateTime(value, label) {
56
+ if (!SOQL_DATETIME.test(value)) {
57
+ throw new TypeError(`Invalid ${label} '${value}': expected an ISO8601 datetime such as 2026-08-02T04:00:00Z`);
58
+ }
59
+ return value;
60
+ }
61
+ /**
62
+ * Build the read-only EventLogFile discovery query.
63
+ *
64
+ * `Interval = 'Daily'` (the default) excludes the paid hourly logs and emits exactly the SOQL
65
+ * this function has always emitted — free-tier callers are unaffected. `'Hourly'` selects the
66
+ * paid logs; `'both'` omits the predicate rather than emitting `IN ('Daily','Hourly')`, which
67
+ * is the same result set with fewer moving parts.
68
+ *
69
+ * NOTE: never probe for hourly rows with a `GROUP BY Interval` aggregate. A verified quirk of
70
+ * the platform is that such a query reports only `Daily` even in orgs where an explicit
71
+ * `WHERE Interval = 'Hourly'` returns thousands of rows.
72
+ *
73
+ * `since` is coerced to a non-negative integer, `window` bounds are shape-validated and
74
+ * `types` are sanitised, so the interpolated string is injection-safe.
24
75
  */
25
76
  export function buildEventLogQuery(opts) {
26
- const since = Math.max(0, Math.trunc(opts.since));
77
+ if (opts.since !== undefined && opts.window !== undefined) {
78
+ throw new TypeError('buildEventLogQuery: `since` and `window` are mutually exclusive');
79
+ }
80
+ if (opts.since === undefined && opts.window === undefined) {
81
+ throw new TypeError('buildEventLogQuery: one of `since` or `window` is required');
82
+ }
83
+ const interval = opts.interval ?? 'Daily';
84
+ const intervalClause = interval === 'both' ? '' : `Interval = '${interval}' AND `;
85
+ const dateClause = opts.window
86
+ ? `LogDate >= ${assertDateTime(opts.window.from, 'window.from')} AND ` +
87
+ `LogDate <= ${assertDateTime(opts.window.to, 'window.to')}`
88
+ : `LogDate = LAST_N_DAYS:${Math.max(0, Math.trunc(opts.since))}`;
27
89
  const types = (opts.types ?? []).filter((t) => t.length > 0);
28
90
  const typeClause = types.length > 0 ? ` AND EventType IN (${types.map((t) => `'${t}'`).join(', ')})` : '';
29
91
  return ('SELECT Id, EventType, LogDate, LogFileLength, Interval, LogFileFieldNames ' +
30
92
  'FROM EventLogFile ' +
31
- `WHERE Interval = 'Daily' AND LogDate = LAST_N_DAYS:${since}${typeClause} ` +
93
+ `WHERE ${intervalClause}${dateClause}${typeClause} ` +
32
94
  'ORDER BY LogDate');
33
95
  }
34
96
  //# sourceMappingURL=eventLogQuery.js.map
@@ -1,7 +1,17 @@
1
1
  import type { SoqlClient } from '../api/SoqlClient.js';
2
2
  import type { RestClient } from '../api/RestClient.js';
3
3
  import type { EventLogAccess } from '../context/AuditCache.js';
4
- import { EventBaselineStore } from './EventBaselineStore.js';
4
+ import type { EventBaselineStore } from './EventBaselineStore.js';
5
+ import { type EventLogInterval, type EventLogWindow } from './eventLogQuery.js';
6
+ import { type CaptureCoverage } from './CaptureManifest.js';
7
+ import type { RteType } from './rteCatalog.js';
8
+ /**
9
+ * Ceiling on a single LogFile body. Checked against LogFileLength *before* the download so an
10
+ * oversized blob costs nothing, and surfaced as `too-large` in the manifest — never as a
11
+ * silent truncation. Generous by design: this is a runaway guard, not a capture policy. A
12
+ * busy org's daily Sites/URI log legitimately reaches tens of MB.
13
+ */
14
+ export declare const MAX_FILE_BYTES: number;
5
15
  /** The subset of EventLogFile fields the discovery query returns. */
6
16
  export interface EventLogFileRow {
7
17
  Id: string;
@@ -16,6 +26,9 @@ export interface PulledLog {
16
26
  id: string;
17
27
  eventType: string;
18
28
  logDate: string;
29
+ /** Zero-padded UTC hour; present only for an Hourly row. */
30
+ hour?: string;
31
+ interval: 'Daily' | 'Hourly';
19
32
  bytes: number;
20
33
  savedPath: string;
21
34
  status: 'downloaded' | 'skipped' | 'failed';
@@ -23,7 +36,9 @@ export interface PulledLog {
23
36
  /** Structured result of a pull run — returned by the command. */
24
37
  export interface EventsPullResult {
25
38
  orgId: string;
26
- since: number;
39
+ since?: number;
40
+ window?: EventLogWindow;
41
+ interval: EventLogInterval;
27
42
  storagePath: string;
28
43
  found: number;
29
44
  downloaded: number;
@@ -31,7 +46,9 @@ export interface EventsPullResult {
31
46
  failed: number;
32
47
  totalBytes: number;
33
48
  logs: PulledLog[];
34
- manifestPath?: string;
49
+ /** Always written — a run that captured nothing is exactly the run whose record matters. */
50
+ manifestPath: string;
51
+ coverage: CaptureCoverage;
35
52
  /** Set when the EventLogFile query itself failed (no crash); tells license vs permission apart. */
36
53
  accessError?: EventLogAccess;
37
54
  }
@@ -42,8 +59,25 @@ export interface PullDeps {
42
59
  orgId: string;
43
60
  }
44
61
  export interface PullOptions {
45
- since: number;
62
+ /** Days of LogDate to request. Mutually exclusive with `window`. */
63
+ since?: number;
64
+ /** Explicit ISO8601 bounds. Mutually exclusive with `since`. */
65
+ window?: EventLogWindow;
66
+ /** Defaults to 'Daily' — the free-tier behaviour, unchanged. */
67
+ interval?: EventLogInterval;
68
+ /**
69
+ * EventType allow-list. When omitted, daily capture takes every type the org offers and
70
+ * hourly capture falls back to HOURLY_FORENSIC_CORE; an explicit list overrides both.
71
+ */
46
72
  types?: string[];
73
+ /** Also capture Real-Time Event Monitoring rows. Requires `window`. */
74
+ realtime?: boolean;
75
+ /** Restrict the RTE probe to these catalog entries. */
76
+ rteCatalog?: readonly RteType[];
77
+ /** Re-download / re-capture even when the target is already on disk. */
78
+ force?: boolean;
79
+ /** Cap on one LogFile body. Defaults to MAX_FILE_BYTES. */
80
+ maxFileBytes?: number;
47
81
  /** Optional sink for non-fatal warnings (per-file download failures). */
48
82
  warn?: (msg: string) => void;
49
83
  }
@@ -1,79 +1,203 @@
1
+ // src/events/pullEventLogs.ts
2
+ // Orchestrates a single `audit events pull` run: discover the org's EventLogFile rows for the
3
+ // requested interval and window, download the CSV body of any not already on disk, optionally
4
+ // capture Real-Time Event rows alongside them, and record a per-run coverage manifest.
5
+ // All org I/O is behind the injected SoqlClient/RestClient, so this is unit-testable with
6
+ // mocked clients — it never touches a real org.
7
+ import * as fs from 'node:fs';
1
8
  import { classifyEventLogAccessError } from './eventLogAccess.js';
2
- import { buildEventLogQuery, toLogDate } from './eventLogQuery.js';
9
+ import { HOURLY_FORENSIC_CORE, buildEventLogQuery, toLogDate, toLogHour, } from './eventLogQuery.js';
10
+ import { emptyCoverage } from './CaptureManifest.js';
11
+ import { pullRealtimeEvents } from './pullRealtimeEvents.js';
12
+ /**
13
+ * Ceiling on a single LogFile body. Checked against LogFileLength *before* the download so an
14
+ * oversized blob costs nothing, and surfaced as `too-large` in the manifest — never as a
15
+ * silent truncation. Generous by design: this is a runaway guard, not a capture policy. A
16
+ * busy org's daily Sites/URI log legitimately reaches tens of MB.
17
+ */
18
+ export const MAX_FILE_BYTES = 512 * 1024 * 1024;
3
19
  export async function pullEventLogs(deps, opts) {
4
20
  const { soql, rest, store, orgId } = deps;
5
- const since = opts.since;
6
- const storagePath = store.orgDir(orgId);
21
+ const interval = opts.interval ?? 'Daily';
22
+ const maxFileBytes = opts.maxFileBytes ?? MAX_FILE_BYTES;
23
+ const coverage = emptyCoverage(orgId, interval, new Date().toISOString());
24
+ if (opts.window)
25
+ coverage.window = opts.window;
26
+ if (opts.since !== undefined)
27
+ coverage.since = opts.since;
7
28
  const base = {
8
29
  orgId,
9
- since,
10
- storagePath,
30
+ since: opts.since,
31
+ window: opts.window,
32
+ interval,
33
+ storagePath: store.orgDir(orgId),
11
34
  found: 0,
12
35
  downloaded: 0,
13
36
  skipped: 0,
14
37
  failed: 0,
15
38
  totalBytes: 0,
16
39
  logs: [],
40
+ manifestPath: '',
41
+ coverage,
17
42
  };
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',
43
+ // 'both' cannot be a single query: daily takes every type while hourly defaults to the
44
+ // forensic core, and one SOQL statement cannot carry two different EventType filters. Two
45
+ // passes it is — which also keeps a failure in one interval from blanking the other.
46
+ const passes = interval === 'both'
47
+ ? [
48
+ { interval: 'Daily', types: opts.types },
49
+ { interval: 'Hourly', types: opts.types ?? [...HOURLY_FORENSIC_CORE] },
50
+ ]
51
+ : [
52
+ {
53
+ interval,
54
+ types: interval === 'Hourly' ? (opts.types ?? [...HOURLY_FORENSIC_CORE]) : opts.types,
55
+ },
56
+ ];
57
+ for (const pass of passes) {
58
+ coverage.elf.requestedTypes.push(...(pass.types ?? []));
59
+ let rows;
60
+ try {
61
+ rows = await soql.queryAll(buildEventLogQuery({
62
+ since: opts.since,
63
+ window: opts.window,
64
+ interval: pass.interval,
65
+ types: pass.types,
66
+ }));
67
+ }
68
+ catch (err) {
69
+ // Inaccessible EventLogFile (unlicensed / no permission) must not crash the command,
70
+ // and must not stop the other interval's pass from running.
71
+ const reason = classifyEventLogAccessError(err);
72
+ base.accessError ??= reason;
73
+ coverage.accessErrors.push({
74
+ scope: `EventLogFile:${pass.interval}`,
75
+ reason,
76
+ detail: err instanceof Error ? err.message : String(err),
38
77
  });
39
78
  continue;
40
79
  }
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' });
80
+ base.found += rows.length;
81
+ for (const row of rows) {
82
+ await captureRow(deps, opts, base, coverage, row, pass.interval, maxFileBytes);
48
83
  }
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',
84
+ }
85
+ // RTE capture is independent of ELF by design: a broken probe on either side must never
86
+ // prevent the other from running.
87
+ if (opts.realtime) {
88
+ if (!opts.window) {
89
+ coverage.accessErrors.push({
90
+ scope: 'RealtimeEvents',
91
+ reason: 'unknown',
92
+ detail: 'realtime capture requires an explicit window',
58
93
  });
59
- opts.warn?.(`Failed to download EventLogFile ${row.Id} (${row.EventType} ${logDate}): ${String(err)}`);
60
94
  }
95
+ else {
96
+ try {
97
+ const rte = await pullRealtimeEvents({ soql, rest, store, orgId }, {
98
+ window: opts.window,
99
+ catalog: opts.rteCatalog,
100
+ force: opts.force,
101
+ warn: opts.warn,
102
+ });
103
+ coverage.rte = rte;
104
+ }
105
+ catch (err) {
106
+ coverage.accessErrors.push({
107
+ scope: 'RealtimeEvents',
108
+ reason: 'unknown',
109
+ detail: err instanceof Error ? err.message : String(err),
110
+ });
111
+ }
112
+ }
113
+ }
114
+ // Always written. A run that captured nothing is exactly the run a consumer needs a record
115
+ // of — without it, "no data" and "never looked" are indistinguishable.
116
+ base.manifestPath = store.writeCoverageManifest(orgId, coverage);
117
+ return base;
118
+ }
119
+ /** Download (or account for skipping) one EventLogFile row. Never throws. */
120
+ async function captureRow(deps, opts, base, coverage, row, passInterval, maxFileBytes) {
121
+ const { rest, store, orgId } = deps;
122
+ const logDate = toLogDate(row.LogDate);
123
+ // Trust the row's own Interval over the pass it arrived on: with interval 'both' the query
124
+ // carries no Interval predicate, so a pass can return either kind.
125
+ const rowInterval = row.Interval === 'Hourly' || row.Interval === 'Daily' ? row.Interval : passInterval;
126
+ const hour = rowInterval === 'Hourly' ? toLogHour(row.LogDate) : undefined;
127
+ const savedPath = store.pathFor(orgId, row.EventType, logDate, row.Id, hour);
128
+ const record = (status, bytes) => {
129
+ base.logs.push({
130
+ id: row.Id,
131
+ eventType: row.EventType,
132
+ logDate,
133
+ hour,
134
+ interval: rowInterval,
135
+ bytes,
136
+ savedPath,
137
+ status,
138
+ });
139
+ };
140
+ if (!opts.force && store.has(orgId, row.EventType, logDate, row.Id, hour)) {
141
+ base.skipped += 1;
142
+ record('skipped', 0);
143
+ coverage.elf.skipped.push({
144
+ type: row.EventType,
145
+ id: row.Id,
146
+ logDate,
147
+ hour,
148
+ reason: 'already-captured',
149
+ });
150
+ return;
61
151
  }
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,
152
+ if (typeof row.LogFileLength === 'number' && row.LogFileLength > maxFileBytes) {
153
+ base.skipped += 1;
154
+ record('skipped', 0);
155
+ coverage.elf.skipped.push({
156
+ type: row.EventType,
157
+ id: row.Id,
158
+ logDate,
159
+ hour,
160
+ reason: 'too-large',
161
+ detail: `${row.LogFileLength} bytes exceeds the ${maxFileBytes}-byte cap`,
75
162
  });
163
+ opts.warn?.(`Skipped EventLogFile ${row.Id} (${row.EventType} ${logDate}): ${row.LogFileLength} bytes exceeds the cap`);
164
+ return;
165
+ }
166
+ try {
167
+ // Stream straight to disk — never buffer the body — so large logs don't blow the heap.
168
+ //
169
+ // Staged through a temp file and renamed, so the final path only ever exists complete.
170
+ // The client already removes a partial file when the stream errors, but that cannot help
171
+ // if the process itself dies mid-download: the truncated CSV would satisfy `has()` and be
172
+ // skipped by every later run, leaving a silently incomplete log presented as a whole one.
173
+ const tmpPath = `${savedPath}.${process.pid}.part`;
174
+ const bytes = await rest.getRawToFile(`/sobjects/EventLogFile/${row.Id}/LogFile`, tmpPath);
175
+ fs.renameSync(tmpPath, savedPath);
176
+ base.downloaded += 1;
177
+ base.totalBytes += bytes;
178
+ record('downloaded', bytes);
179
+ coverage.elf.captured.push({
180
+ type: row.EventType,
181
+ id: row.Id,
182
+ logDate,
183
+ hour,
184
+ bytes,
185
+ path: savedPath,
186
+ });
187
+ }
188
+ catch (err) {
189
+ fs.rmSync(`${savedPath}.${process.pid}.part`, { force: true });
190
+ base.failed += 1;
191
+ record('failed', 0);
192
+ coverage.elf.failed.push({
193
+ type: row.EventType,
194
+ id: row.Id,
195
+ logDate,
196
+ hour,
197
+ reason: 'download-failed',
198
+ detail: err instanceof Error ? err.message : String(err),
199
+ });
200
+ opts.warn?.(`Failed to download EventLogFile ${row.Id} (${row.EventType} ${logDate}): ${String(err)}`);
76
201
  }
77
- return base;
78
202
  }
79
203
  //# sourceMappingURL=pullEventLogs.js.map
@@ -0,0 +1,62 @@
1
+ import type { SoqlClient } from '../api/SoqlClient.js';
2
+ import type { RestClient } from '../api/RestClient.js';
3
+ import type { EventBaselineStore } from './EventBaselineStore.js';
4
+ import type { CapturedRteObject, SkipReason, UnavailableRteObject } from './CaptureManifest.js';
5
+ import { type RteType } from './rteCatalog.js';
6
+ export interface RealtimePullDeps {
7
+ soql: SoqlClient;
8
+ rest: RestClient;
9
+ store: EventBaselineStore;
10
+ orgId: string;
11
+ }
12
+ export interface RealtimePullOptions {
13
+ /** Inclusive ISO8601 bounds. Rows are bucketed to one NDJSON file per UTC hour within it. */
14
+ window: {
15
+ from: string;
16
+ to: string;
17
+ };
18
+ /** Defaults to the full catalog. */
19
+ catalog?: readonly RteType[];
20
+ /** Re-capture object-hours already on disk. */
21
+ force?: boolean;
22
+ /** Cap on rows accepted from one object. Defaults to MAX_RTE_ROWS. */
23
+ maxRows?: number;
24
+ warn?: (msg: string) => void;
25
+ }
26
+ /**
27
+ * Ceiling on rows taken from a single RTE object in one pull.
28
+ *
29
+ * RTE payloads are small for a sensible window — a busy hour ran to a few hundred ApiEvent
30
+ * rows — but the window is caller-supplied and `queryAll` follows every page, so a month-wide
31
+ * window on a chatty object would page the lot into memory before a single byte reached disk.
32
+ * Overflow is reported as `too-large` rather than truncated: a short NDJSON file is
33
+ * indistinguishable from a quiet hour once written, and quietly answering "nothing else
34
+ * happened" is the one failure this package exists to prevent.
35
+ */
36
+ export declare const MAX_RTE_ROWS = 200000;
37
+ export interface RealtimePullResult {
38
+ captured: CapturedRteObject[];
39
+ unavailable: UnavailableRteObject[];
40
+ }
41
+ export declare function pullRealtimeEvents(deps: RealtimePullDeps, opts: RealtimePullOptions): Promise<RealtimePullResult>;
42
+ /**
43
+ * Intersect the preferred field list with what the object actually defines. Field sets differ
44
+ * per object — LightningUriEvent has no RowsProcessed — so a fixed SELECT list fails outright.
45
+ */
46
+ export declare function describeFields(rest: RestClient, objectName: string, preferred: readonly string[]): Promise<string[]>;
47
+ /**
48
+ * Build the RTE window query. Deliberately emits no ORDER BY: RTE objects reject
49
+ * `ORDER BY EventDate ASC` with "Unsupported order direction on filter column". Sorting is a
50
+ * client-side concern here.
51
+ */
52
+ export declare function buildRealtimeQuery(objectName: string, fields: readonly string[], window: {
53
+ from: string;
54
+ to: string;
55
+ }, limit?: number): string;
56
+ /**
57
+ * Map an RTE failure to a manifest reason. The distinction that matters most is
58
+ * "does not support query" — meaning the base object is streaming-only and the Store should be
59
+ * tried — versus a licence or permission wall, where trying harder will not help.
60
+ */
61
+ export declare function classifyRteError(err: unknown): SkipReason;
62
+ //# sourceMappingURL=pullRealtimeEvents.d.ts.map
@@ -0,0 +1,173 @@
1
+ import { RTE_CATALOG } from './rteCatalog.js';
2
+ /**
3
+ * Ceiling on rows taken from a single RTE object in one pull.
4
+ *
5
+ * RTE payloads are small for a sensible window — a busy hour ran to a few hundred ApiEvent
6
+ * rows — but the window is caller-supplied and `queryAll` follows every page, so a month-wide
7
+ * window on a chatty object would page the lot into memory before a single byte reached disk.
8
+ * Overflow is reported as `too-large` rather than truncated: a short NDJSON file is
9
+ * indistinguishable from a quiet hour once written, and quietly answering "nothing else
10
+ * happened" is the one failure this package exists to prevent.
11
+ */
12
+ export const MAX_RTE_ROWS = 200_000;
13
+ const SOQL_DATETIME = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?(?:Z|[+-]\d{2}:\d{2})$/;
14
+ export async function pullRealtimeEvents(deps, opts) {
15
+ for (const bound of [opts.window.from, opts.window.to]) {
16
+ if (!SOQL_DATETIME.test(bound)) {
17
+ throw new TypeError(`pullRealtimeEvents: invalid window bound '${bound}': expected an ISO8601 datetime`);
18
+ }
19
+ }
20
+ const result = { captured: [], unavailable: [] };
21
+ for (const entry of opts.catalog ?? RTE_CATALOG) {
22
+ const outcome = await captureOne(deps, opts, entry);
23
+ if ('reason' in outcome)
24
+ result.unavailable.push(outcome);
25
+ else
26
+ result.captured.push(outcome);
27
+ }
28
+ return result;
29
+ }
30
+ /** Probe base, fall back to store, classify whatever went wrong. Never rejects. */
31
+ async function captureOne(deps, opts, entry) {
32
+ const attempts = [
33
+ { name: entry.base, via: 'base' },
34
+ ];
35
+ if (entry.store)
36
+ attempts.push({ name: entry.store, via: 'store' });
37
+ const details = [];
38
+ let lastReason = 'unknown';
39
+ for (const attempt of attempts) {
40
+ let fields;
41
+ try {
42
+ fields = await describeFields(deps.rest, attempt.name, entry.preferredFields);
43
+ }
44
+ catch (err) {
45
+ lastReason = classifyRteError(err);
46
+ details.push(`${attempt.name}: describe failed (${message(err)})`);
47
+ continue;
48
+ }
49
+ if (fields.length === 0) {
50
+ // The object exists (describe answered) but defines none of the forensic fields, so
51
+ // there is no SELECT list to build. Not a licence problem — genuinely unexpected.
52
+ lastReason = 'unknown';
53
+ details.push(`${attempt.name}: describe returned none of the preferred fields`);
54
+ continue;
55
+ }
56
+ const maxRows = opts.maxRows ?? MAX_RTE_ROWS;
57
+ let rows;
58
+ try {
59
+ // One over the cap, so an exactly-full result is told apart from an overflowing one.
60
+ rows = await deps.soql.queryAll(buildRealtimeQuery(attempt.name, fields, opts.window, maxRows + 1));
61
+ }
62
+ catch (err) {
63
+ lastReason = classifyRteError(err);
64
+ details.push(`${attempt.name}: ${message(err)}`);
65
+ continue;
66
+ }
67
+ if (rows.length > maxRows) {
68
+ opts.warn?.(`${attempt.name}: more than ${maxRows} rows in this window; narrow the window and re-run.`);
69
+ return {
70
+ object: entry.base,
71
+ reason: 'too-large',
72
+ detail: `${attempt.name} returned more than ${maxRows} rows for the requested window; nothing written`,
73
+ };
74
+ }
75
+ if (rows.length === 0) {
76
+ // A query that succeeded and returned nothing is a finding: nothing happened in this
77
+ // window. Recorded as a capture of zero rows, not as an unavailable object.
78
+ //
79
+ // This used to distinguish base from Store, on the reasoning that an empty Store could
80
+ // not be told apart from one that never retained anything — reported as
81
+ // `storage-disabled`. A live run showed why that is wrong: the eight threat-detection
82
+ // Stores are queryable and empty in a normal hour, so every quiet hour produced eight
83
+ // "unavailable" entries claiming coverage was missing when the org had in fact been
84
+ // asked and had answered. Overstating a gap corrupts the record as surely as hiding one.
85
+ return { object: entry.base, rows: 0, via: attempt.via, paths: [] };
86
+ }
87
+ return writeBuckets(deps, opts, entry.base, attempt.via, rows);
88
+ }
89
+ return {
90
+ object: entry.base,
91
+ reason: lastReason,
92
+ detail: details.join('; ') || undefined,
93
+ };
94
+ }
95
+ /**
96
+ * Bucket rows into one NDJSON file per UTC hour and write them. Rows whose EventDate is
97
+ * missing or unparseable land in the window-start bucket rather than being dropped — an
98
+ * unattributable row is still evidence.
99
+ */
100
+ function writeBuckets(deps, opts, objectName, via, rows) {
101
+ const fallback = bucketKey(opts.window.from) ?? { date: opts.window.from.slice(0, 10), hour: '00' };
102
+ const buckets = new Map();
103
+ for (const row of rows) {
104
+ const key = bucketKey(row.EventDate) ?? fallback;
105
+ const id = `${key.date}T${key.hour}`;
106
+ const bucket = buckets.get(id) ?? { ...key, rows: [] };
107
+ bucket.rows.push(row);
108
+ buckets.set(id, bucket);
109
+ }
110
+ const paths = [];
111
+ let written = 0;
112
+ for (const bucket of buckets.values()) {
113
+ if (!opts.force && deps.store.hasRealtime(deps.orgId, objectName, bucket.date, bucket.hour)) {
114
+ paths.push(deps.store.realtimePathFor(deps.orgId, objectName, bucket.date, bucket.hour));
115
+ continue;
116
+ }
117
+ // ORDER BY EventDate is rejected outright on RTE objects ("Unsupported order direction on
118
+ // filter column: EVENTDATE"), so ordering happens here instead.
119
+ bucket.rows.sort((a, b) => String(a.EventDate ?? '').localeCompare(String(b.EventDate ?? '')));
120
+ paths.push(deps.store.saveRealtime(deps.orgId, objectName, bucket.date, bucket.hour, bucket.rows));
121
+ written += bucket.rows.length;
122
+ }
123
+ return { object: objectName, rows: written, via, paths };
124
+ }
125
+ function bucketKey(raw) {
126
+ const match = /^(\d{4}-\d{2}-\d{2})T(\d{2}):/.exec(String(raw ?? ''));
127
+ return match ? { date: match[1], hour: match[2] } : undefined;
128
+ }
129
+ /**
130
+ * Intersect the preferred field list with what the object actually defines. Field sets differ
131
+ * per object — LightningUriEvent has no RowsProcessed — so a fixed SELECT list fails outright.
132
+ */
133
+ export async function describeFields(rest, objectName, preferred) {
134
+ const describe = await rest.get(`/sobjects/${objectName}/describe`);
135
+ const actual = new Set((describe.fields ?? []).map((f) => String(f.name ?? '').toLowerCase()));
136
+ return preferred.filter((f) => actual.has(f.toLowerCase()));
137
+ }
138
+ /**
139
+ * Build the RTE window query. Deliberately emits no ORDER BY: RTE objects reject
140
+ * `ORDER BY EventDate ASC` with "Unsupported order direction on filter column". Sorting is a
141
+ * client-side concern here.
142
+ */
143
+ export function buildRealtimeQuery(objectName, fields, window, limit) {
144
+ const safeObject = objectName.replace(/[^A-Za-z0-9_]/g, '');
145
+ const safeFields = fields.map((f) => f.replace(/[^A-Za-z0-9_]/g, '')).filter((f) => f.length > 0);
146
+ const limitClause = limit === undefined ? '' : ` LIMIT ${Math.max(1, Math.trunc(limit))}`;
147
+ return (`SELECT ${safeFields.join(', ')} FROM ${safeObject} ` +
148
+ `WHERE EventDate >= ${window.from} AND EventDate <= ${window.to}${limitClause}`);
149
+ }
150
+ /**
151
+ * Map an RTE failure to a manifest reason. The distinction that matters most is
152
+ * "does not support query" — meaning the base object is streaming-only and the Store should be
153
+ * tried — versus a licence or permission wall, where trying harder will not help.
154
+ */
155
+ export function classifyRteError(err) {
156
+ const msg = message(err).toLowerCase();
157
+ if (msg.includes('does not support query'))
158
+ return 'not-queryable';
159
+ if (msg.includes('insufficient') || msg.includes('permission'))
160
+ return 'no-permission';
161
+ if (msg.includes('invalid type') ||
162
+ msg.includes('not found') ||
163
+ msg.includes('sobject type') ||
164
+ msg.includes('licens') ||
165
+ msg.includes('not enabled')) {
166
+ return 'unlicensed';
167
+ }
168
+ return 'unknown';
169
+ }
170
+ function message(err) {
171
+ return err instanceof Error ? err.message : String(err);
172
+ }
173
+ //# sourceMappingURL=pullRealtimeEvents.js.map
@@ -0,0 +1,32 @@
1
+ export interface RteType {
2
+ /** The streaming/base object name, e.g. 'ListViewEvent'. Probed first. */
3
+ base: string;
4
+ /** The retained-rows counterpart, e.g. 'GuestUserAnomalyEventStore'. Probed on fallback. */
5
+ store?: string;
6
+ /** Forensic fields in priority order; intersected with describe() at runtime. */
7
+ preferredFields: string[];
8
+ }
9
+ /**
10
+ * The 20 known RTE types, split by how the org actually serves them.
11
+ *
12
+ * Probed against a live sandbox on 2026-08-03, which replaced the naming convention this
13
+ * table was first built on. The convention was wrong in both directions, and the real rule
14
+ * turns out to be about what kind of event it is:
15
+ *
16
+ * - **Audit events** (someone did a thing) are queried directly and have NO `*Store`.
17
+ * `ApiEventStore`, `LoginEventStore`, `LogoutEventStore`, `ReportEventStore`,
18
+ * `UriEventStore`, `LightningUriEventStore` and `LoginAsEventStore` were all declared
19
+ * here and none of them exist — every one 404s on describe.
20
+ * - **Threat-detection events** (something looked wrong) are streaming-only: the base
21
+ * rejects a query outright and the retained rows live in a `*Store`.
22
+ *
23
+ * A `store` on a directly-queryable base is never reached, so the phantom entries were
24
+ * harmless — but a catalog that documents objects which do not exist is worse than no
25
+ * documentation, so they are gone.
26
+ *
27
+ * Re-probed across five orgs — two sandboxes and three production — on 2026-08-03. Every
28
+ * verdict was identical in all five, including the absences, so the negatives are no longer
29
+ * a single-org observation that a different licence might overturn.
30
+ */
31
+ export declare const RTE_CATALOG: readonly RteType[];
32
+ //# sourceMappingURL=rteCatalog.d.ts.map
@@ -0,0 +1,113 @@
1
+ // src/events/rteCatalog.ts
2
+ // Static description of the Real-Time Event Monitoring objects worth capturing. Data only —
3
+ // no logic, no I/O — so the probe in pullRealtimeEvents stays the single place that decides
4
+ // what an org can actually serve.
5
+ //
6
+ // Two verified facts drive the shape of this table:
7
+ //
8
+ // 1. Roughly half the RTE base objects reject `SELECT ... FROM x` outright with "entity type
9
+ // x does not support query" while their `*Store` counterpart answers fine. The Store holds
10
+ // the retained rows; the base object is the streaming channel.
11
+ // 2. The base/Store split is NOT uniform and cannot be derived from the name. ListViewEvent
12
+ // is queryable and has no ListViewEventStore at all; GuestUserAnomalyEvent is the exact
13
+ // inverse. Hence: declare both names, probe at runtime, believe the org.
14
+ /**
15
+ * Fields every RTE object is asked for when it defines them. Field sets differ per object —
16
+ * LightningUriEvent has no RowsProcessed, for one — so a fixed SELECT list across objects
17
+ * fails outright. The intersection with describe() is what makes a shared list workable.
18
+ */
19
+ const COMMON_FIELDS = [
20
+ 'EventDate',
21
+ 'SourceIp',
22
+ 'Username',
23
+ 'UserId',
24
+ 'SessionKey',
25
+ 'LoginKey',
26
+ 'EventIdentifier',
27
+ 'RelatedEventIdentifier',
28
+ ];
29
+ /**
30
+ * The fields that answer *did any records actually leave*. EventLogFile cannot answer this —
31
+ * it records no response bodies and no row counts for Aura actions — which is precisely why
32
+ * RTE capture exists. Requested wherever the object defines them.
33
+ */
34
+ const EXFIL_FIELDS = ['RowsProcessed', 'QueriedEntities', 'Records'];
35
+ /** Query/'what was asked for' context, where present. */
36
+ const CONTEXT_FIELDS = [
37
+ 'Query',
38
+ 'Operation',
39
+ 'Name',
40
+ 'DeveloperName',
41
+ 'Scope',
42
+ 'FilterCriteria',
43
+ 'Status',
44
+ 'Platform',
45
+ 'Application',
46
+ ];
47
+ const ALL_PREFERRED = [...COMMON_FIELDS, ...EXFIL_FIELDS, ...CONTEXT_FIELDS];
48
+ /**
49
+ * The 20 known RTE types, split by how the org actually serves them.
50
+ *
51
+ * Probed against a live sandbox on 2026-08-03, which replaced the naming convention this
52
+ * table was first built on. The convention was wrong in both directions, and the real rule
53
+ * turns out to be about what kind of event it is:
54
+ *
55
+ * - **Audit events** (someone did a thing) are queried directly and have NO `*Store`.
56
+ * `ApiEventStore`, `LoginEventStore`, `LogoutEventStore`, `ReportEventStore`,
57
+ * `UriEventStore`, `LightningUriEventStore` and `LoginAsEventStore` were all declared
58
+ * here and none of them exist — every one 404s on describe.
59
+ * - **Threat-detection events** (something looked wrong) are streaming-only: the base
60
+ * rejects a query outright and the retained rows live in a `*Store`.
61
+ *
62
+ * A `store` on a directly-queryable base is never reached, so the phantom entries were
63
+ * harmless — but a catalog that documents objects which do not exist is worse than no
64
+ * documentation, so they are gone.
65
+ *
66
+ * Re-probed across five orgs — two sandboxes and three production — on 2026-08-03. Every
67
+ * verdict was identical in all five, including the absences, so the negatives are no longer
68
+ * a single-org observation that a different licence might overturn.
69
+ */
70
+ export const RTE_CATALOG = [
71
+ // Directly queryable; no Store counterpart exists. Verified queryable in the probe org.
72
+ { base: 'ListViewEvent', preferredFields: ALL_PREFERRED },
73
+ { base: 'ApiEvent', preferredFields: ALL_PREFERRED },
74
+ { base: 'LoginEvent', preferredFields: ALL_PREFERRED },
75
+ { base: 'LogoutEvent', preferredFields: ALL_PREFERRED },
76
+ { base: 'ReportEvent', preferredFields: ALL_PREFERRED },
77
+ { base: 'UriEvent', preferredFields: ALL_PREFERRED },
78
+ { base: 'LightningUriEvent', preferredFields: ALL_PREFERRED },
79
+ { base: 'LoginAsEvent', preferredFields: ALL_PREFERRED },
80
+ { base: 'IdentityProviderEventStore', preferredFields: ALL_PREFERRED },
81
+ // Streaming-only base, retained rows in the Store. All eight Stores verified queryable,
82
+ // and all eight bases verified to reject a query with "does not support query".
83
+ { base: 'ApiAnomalyEvent', store: 'ApiAnomalyEventStore', preferredFields: ALL_PREFERRED },
84
+ { base: 'BulkApiResultEvent', store: 'BulkApiResultEventStore', preferredFields: ALL_PREFERRED },
85
+ {
86
+ base: 'CredentialStuffingEvent',
87
+ store: 'CredentialStuffingEventStore',
88
+ preferredFields: ALL_PREFERRED,
89
+ },
90
+ { base: 'FileEvent', store: 'FileEventStore', preferredFields: ALL_PREFERRED },
91
+ {
92
+ base: 'GuestUserAnomalyEvent',
93
+ store: 'GuestUserAnomalyEventStore',
94
+ preferredFields: ALL_PREFERRED,
95
+ },
96
+ { base: 'PermissionSetEvent', store: 'PermissionSetEventStore', preferredFields: ALL_PREFERRED },
97
+ { base: 'ReportAnomalyEvent', store: 'ReportAnomalyEventStore', preferredFields: ALL_PREFERRED },
98
+ {
99
+ base: 'SessionHijackingEvent',
100
+ store: 'SessionHijackingEventStore',
101
+ preferredFields: ALL_PREFERRED,
102
+ },
103
+ // Exist, but are streaming-only with no Store in any org probed — so they can never be
104
+ // captured retroactively. Kept deliberately: the manifest recording them as `not-queryable`
105
+ // is real coverage information. "This event type exists and cannot be read after the fact"
106
+ // is a different answer from "we did not look", and a forensic consumer needs to tell them
107
+ // apart before it reports an absence.
108
+ { base: 'ConcurLongRunApexErrEvent', preferredFields: ALL_PREFERRED },
109
+ { base: 'OrgLifecycleNotification', preferredFields: ALL_PREFERRED },
110
+ // `ApexExecutionEvent` was here and is gone: absent from describe in all five orgs, so the
111
+ // name appears not to exist rather than to be unlicensed. It cost a 404 per pull.
112
+ ];
113
+ //# sourceMappingURL=rteCatalog.js.map
package/lib/index.d.ts CHANGED
@@ -7,11 +7,17 @@ export { EMPTY_METRICS } from './context/OrgMetrics.js';
7
7
  export type { AuditOptions, AuditContext } from './context/AuditContext.js';
8
8
  export type { HealthCheckRisk, ApexClassBody, VfPageBody, EventLogAccess, EventLogSummary, AgentAccess, AgentDefinition, AgentUser, CspTrustedSite, MfaRegistration, EffectivePermissionGrant, AuditCache, } from './context/AuditCache.js';
9
9
  export { EventBaselineStore } from './events/EventBaselineStore.js';
10
- export type { EventLogQueryOptions } from './events/eventLogQuery.js';
11
- export { sanitizeTypes, toLogDate, buildEventLogQuery } from './events/eventLogQuery.js';
10
+ export type { EventLogQueryOptions, EventLogInterval, EventLogWindow, } from './events/eventLogQuery.js';
11
+ export { sanitizeTypes, toLogDate, toLogHour, buildEventLogQuery, HOURLY_FORENSIC_CORE, } from './events/eventLogQuery.js';
12
12
  export type { EventLogFileRow, PulledLog, EventsPullResult, PullDeps, PullOptions, } from './events/pullEventLogs.js';
13
- export { pullEventLogs } from './events/pullEventLogs.js';
13
+ export { pullEventLogs, MAX_FILE_BYTES } from './events/pullEventLogs.js';
14
14
  export { classifyEventLogAccessError } from './events/eventLogAccess.js';
15
+ export type { RteType } from './events/rteCatalog.js';
16
+ export { RTE_CATALOG } from './events/rteCatalog.js';
17
+ export type { RealtimePullDeps, RealtimePullOptions, RealtimePullResult, } from './events/pullRealtimeEvents.js';
18
+ export { pullRealtimeEvents, MAX_RTE_ROWS, buildRealtimeQuery, describeFields, classifyRteError, } from './events/pullRealtimeEvents.js';
19
+ export type { SkipReason, CaptureCoverage, CapturedElfFile, SkippedElfFile, CapturedRteObject, UnavailableRteObject, } from './events/CaptureManifest.js';
20
+ export { SKIP_REASONS, isSkipReason, emptyCoverage, readCoverageManifest, } from './events/CaptureManifest.js';
15
21
  export type { Branding, BrandingOverrides } from './report/branding.js';
16
22
  export { DEFAULT_BRANDING, resolveBranding } from './report/branding.js';
17
23
  export { fontFaceCss, firaFontFaceCss } from './report/fonts.js';
package/lib/index.js CHANGED
@@ -5,9 +5,12 @@ export { MetadataClientImpl } from './api/MetadataClientImpl.js';
5
5
  export { EMPTY_METRICS } from './context/OrgMetrics.js';
6
6
  // --- Event log ---
7
7
  export { EventBaselineStore } from './events/EventBaselineStore.js';
8
- export { sanitizeTypes, toLogDate, buildEventLogQuery } from './events/eventLogQuery.js';
9
- export { pullEventLogs } from './events/pullEventLogs.js';
8
+ export { sanitizeTypes, toLogDate, toLogHour, buildEventLogQuery, HOURLY_FORENSIC_CORE, } from './events/eventLogQuery.js';
9
+ export { pullEventLogs, MAX_FILE_BYTES } from './events/pullEventLogs.js';
10
10
  export { classifyEventLogAccessError } from './events/eventLogAccess.js';
11
+ export { RTE_CATALOG } from './events/rteCatalog.js';
12
+ export { pullRealtimeEvents, MAX_RTE_ROWS, buildRealtimeQuery, describeFields, classifyRteError, } from './events/pullRealtimeEvents.js';
13
+ export { SKIP_REASONS, isSkipReason, emptyCoverage, readCoverageManifest, } from './events/CaptureManifest.js';
11
14
  export { DEFAULT_BRANDING, resolveBranding } from './report/branding.js';
12
15
  export { fontFaceCss, firaFontFaceCss } from './report/fonts.js';
13
16
  export { esc } from './renderers/html-utils.js';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cclabsnz/sf-core",
3
- "version": "0.1.5",
3
+ "version": "0.3.0",
4
4
  "description": "Shared platform layer for CloudCounsel Salesforce sf plugins — API clients, org context, event log pull, report shell, and versioned IR schemas.",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",