@cclabsnz/sf-audit 1.7.0 → 1.8.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,133 @@
1
+ /**
2
+ * What to say when the input cannot be read.
3
+ *
4
+ * Worked examples rather than a grammar. "Expected an ISO 8601 interval" says what somebody got
5
+ * wrong without saying what to type, and the person reading it is mid-incident with a timestamp
6
+ * in front of them rather than a specification.
7
+ */
8
+ const FORMS = [
9
+ 'Could not read that window. Any of these work:',
10
+ '',
11
+ ' yesterday the whole of yesterday, UTC',
12
+ ' today midnight UTC until now',
13
+ ' 2026-08-02 that whole day',
14
+ ' 2026-08-02T04:17Z the hour containing that instant',
15
+ ' 2h 90m the last two hours; the last ninety minutes',
16
+ ' 2026-08-02T04:00Z/PT1H an exact interval — start and duration',
17
+ ' 2026-08-02T04:00Z/2026-08-02T06:00Z an exact interval — start and end',
18
+ '',
19
+ 'Times are UTC, and a window has to fall inside one UTC day.',
20
+ ].join('\n');
21
+ const DATE_ONLY = /^\d{4}-\d{2}-\d{2}$/;
22
+ const LOOKBACK = /^(\d+)\s*(h|m)$/i;
23
+ /** `PT90M`, `PT2H`, `PT1H30M` — the subset that makes sense for an hour-scale window. */
24
+ const ISO_DURATION = /^PT(?:(\d+)H)?(?:(\d+)M)?$/;
25
+ const HOUR_MS = 3_600_000;
26
+ const DAY_MS = 86_400_000;
27
+ function durationMs(text) {
28
+ const match = ISO_DURATION.exec(text.trim());
29
+ if (!match || (match[1] === undefined && match[2] === undefined))
30
+ return undefined;
31
+ return (Number(match[1] ?? 0) * 60 + Number(match[2] ?? 0)) * 60_000;
32
+ }
33
+ /**
34
+ * Read an instant, assuming UTC when no zone is given.
35
+ *
36
+ * Every capture is stored in UTC, so a bare timestamp is meant as UTC — reading it as local time
37
+ * would shift the window by hours and return the wrong evidence without saying anything. A space
38
+ * in place of the `T` is accepted because that is how a timestamp arrives when pasted out of a
39
+ * report or a chat message.
40
+ */
41
+ function instant(text) {
42
+ const normalised = text.trim().replace(' ', 'T');
43
+ if (normalised === '')
44
+ return undefined;
45
+ const zoned = /(Z|[+-]\d{2}:?\d{2})$/.test(normalised) ? normalised : `${normalised}Z`;
46
+ const parsed = Date.parse(zoned);
47
+ return Number.isNaN(parsed) ? undefined : parsed;
48
+ }
49
+ const startOfDayMs = (ms) => Date.parse(`${new Date(ms).toISOString().slice(0, 10)}T00:00:00Z`);
50
+ /**
51
+ * Resolve a window to the hour files that hold it.
52
+ *
53
+ * Several spellings, one meaning. The exact ISO interval is precise and nobody composes one
54
+ * under pressure; an investigator knows "yesterday", "the last two hours", or has a timestamp
55
+ * pasted from an alert. Translating that by hand is a step where the timezone or the duration
56
+ * syntax goes wrong, and the resulting empty timeline reads as an absence of evidence rather
57
+ * than as a mistyped window.
58
+ *
59
+ * Resolution errs toward reading more rather than less: a window starting at 04:45 still reads
60
+ * hour 04, because the evidence between 04:45 and 05:00 lives in that file. Over-reading costs a
61
+ * few rows the correlation ignores; under-reading reports an absence the capture would have
62
+ * contradicted.
63
+ *
64
+ * `now` is a parameter rather than read from the clock, so the relative forms are testable and a
65
+ * run can be reproduced.
66
+ */
67
+ export function parseWindow(interval, now = Date.now()) {
68
+ const text = interval.trim();
69
+ const lookback = LOOKBACK.exec(text);
70
+ let startMs;
71
+ let endMs;
72
+ if (/^today$/i.test(text)) {
73
+ startMs = startOfDayMs(now);
74
+ endMs = now;
75
+ }
76
+ else if (/^yesterday$/i.test(text)) {
77
+ startMs = startOfDayMs(now) - DAY_MS;
78
+ endMs = startOfDayMs(now);
79
+ }
80
+ else if (lookback) {
81
+ startMs = now - Number(lookback[1]) * (lookback[2].toLowerCase() === 'h' ? HOUR_MS : 60_000);
82
+ endMs = now;
83
+ }
84
+ else if (DATE_ONLY.test(text)) {
85
+ startMs = Date.parse(`${text}T00:00:00Z`);
86
+ endMs = startMs + DAY_MS;
87
+ }
88
+ else if (text.includes('/')) {
89
+ const [startText, endText] = text.split('/');
90
+ const start = instant(startText);
91
+ if (start === undefined)
92
+ throw new Error(FORMS);
93
+ startMs = start;
94
+ const ms = durationMs(endText);
95
+ if (ms !== undefined) {
96
+ endMs = startMs + ms;
97
+ }
98
+ else {
99
+ const end = instant(endText);
100
+ if (end === undefined)
101
+ throw new Error(FORMS);
102
+ endMs = end;
103
+ }
104
+ }
105
+ else {
106
+ // A bare timestamp means the hour containing it — what somebody pastes off a log line or an
107
+ // alert, where the window they want is the surrounding hour rather than the instant.
108
+ const at = instant(text);
109
+ if (at === undefined)
110
+ throw new Error(FORMS);
111
+ startMs = at - (at % HOUR_MS);
112
+ endMs = startMs + HOUR_MS;
113
+ }
114
+ if (endMs <= startMs) {
115
+ throw new Error(`Window end is not after its start — a zero or negative window can only return nothing.\n\n${FORMS}`);
116
+ }
117
+ const date = new Date(startMs).toISOString().slice(0, 10);
118
+ const endBoundary = new Date(endMs - 1);
119
+ // The store keys files by date, so a window spanning two of them needs two roots. Refusing is
120
+ // honest, and it names the two runs that would cover it; reading only the first day would
121
+ // under-report without saying so.
122
+ if (endBoundary.toISOString().slice(0, 10) !== date) {
123
+ throw new Error('A window has to fall inside one UTC day, and this one crosses midnight.\n' +
124
+ `Run it twice — once for ${date}, once for ${endBoundary.toISOString().slice(0, 10)} — or narrow it.`);
125
+ }
126
+ const firstHour = new Date(startMs).getUTCHours();
127
+ const lastHour = endBoundary.getUTCHours();
128
+ const hours = [];
129
+ for (let h = firstHour; h <= lastHour; h++)
130
+ hours.push(String(h).padStart(2, '0'));
131
+ return { date, hours, startMs, endMs };
132
+ }
133
+ //# sourceMappingURL=parseWindow.js.map
@@ -0,0 +1,33 @@
1
+ import { type EventRow } from './EventRow.js';
2
+ import type { Refusal, Seed } from './CorrelationEngine.js';
3
+ import type { JoinKeyType } from './JoinKeys.js';
4
+ import type { CoverageAssessment } from './CaptureIndex.js';
5
+ export interface TimelineOutput {
6
+ window: string;
7
+ seeds: ReadonlyArray<Seed>;
8
+ rows: ReadonlyArray<EventRow>;
9
+ refusals: ReadonlyArray<Refusal>;
10
+ expandedThrough: ReadonlyArray<{
11
+ type: JoinKeyType;
12
+ value: string;
13
+ }>;
14
+ coverage: CoverageAssessment;
15
+ }
16
+ export declare function renderCsv(output: TimelineOutput): string;
17
+ /**
18
+ * The machine-readable form, carrying the reasoning as well as the result.
19
+ *
20
+ * The rows alone are an assertion. Shipping the seeds, the keys actually expanded through and
21
+ * every refusal alongside them makes the assertion checkable: a reviewer can see which hops the
22
+ * conclusion rests on without re-running anything.
23
+ */
24
+ export declare function renderJson(output: TimelineOutput): string;
25
+ /**
26
+ * The narrative form.
27
+ *
28
+ * Ordered so a reader meets the caveats before the findings. Coverage leads, because every count
29
+ * below it means something different depending on what was captured, and a reader who has
30
+ * already absorbed "89 rows" will not revise that impression when the caveat arrives later.
31
+ */
32
+ export declare function renderSummary(output: TimelineOutput): string;
33
+ //# sourceMappingURL=render.d.ts.map
@@ -0,0 +1,120 @@
1
+ import { EVENT_ROW_COLUMNS } from './EventRow.js';
2
+ /**
3
+ * Chronological, and ours to impose.
4
+ *
5
+ * Real-time event queries reject an ORDER BY on the event date, so rows arrive in whatever order
6
+ * each source happened to yield. A forensic timeline that is not in time order is not a timeline.
7
+ */
8
+ function chronological(rows) {
9
+ return [...rows].sort((a, b) => (a.timestamp_utc ?? '').localeCompare(b.timestamp_utc ?? '') || a.seq - b.seq);
10
+ }
11
+ /**
12
+ * RFC 4180 quoting.
13
+ *
14
+ * Values here are user-controlled — URIs, GraphQL queries, Aura messages — and any of them can
15
+ * carry a comma, a quote or a newline. An unquoted newline turns one record into two, which in a
16
+ * forensic export means inventing an event that never happened.
17
+ */
18
+ function csvCell(value) {
19
+ if (value === undefined || value === null)
20
+ return '';
21
+ const text = String(value);
22
+ if (!/[",\n\r]/.test(text))
23
+ return text;
24
+ return `"${text.replace(/"/g, '""')}"`;
25
+ }
26
+ export function renderCsv(output) {
27
+ const lines = [EVENT_ROW_COLUMNS.join(',')];
28
+ for (const row of chronological(output.rows)) {
29
+ lines.push(EVENT_ROW_COLUMNS.map((column) => csvCell(row[column])).join(','));
30
+ }
31
+ // Trailing newline: every line is terminated, which is what POSIX text tools assume. Without
32
+ // it `wc -l` reports one fewer line than the file holds, and a row count taken that way is
33
+ // quietly wrong — in an evidence export that is a miscount someone may rely on.
34
+ return lines.join('\n') + '\n';
35
+ }
36
+ /**
37
+ * The machine-readable form, carrying the reasoning as well as the result.
38
+ *
39
+ * The rows alone are an assertion. Shipping the seeds, the keys actually expanded through and
40
+ * every refusal alongside them makes the assertion checkable: a reviewer can see which hops the
41
+ * conclusion rests on without re-running anything.
42
+ */
43
+ export function renderJson(output) {
44
+ return JSON.stringify({
45
+ window: output.window,
46
+ seeds: output.seeds,
47
+ coverage: {
48
+ state: output.coverage.state,
49
+ missing: output.coverage.missing,
50
+ capturedSources: output.coverage.capturedSources,
51
+ statement: output.coverage.statement(output.rows.length),
52
+ },
53
+ expandedThrough: output.expandedThrough,
54
+ refusals: output.refusals,
55
+ rows: chronological(output.rows),
56
+ }, null, 2);
57
+ }
58
+ function countBy(rows, pick) {
59
+ const counts = new Map();
60
+ for (const row of rows)
61
+ counts.set(pick(row), (counts.get(pick(row)) ?? 0) + 1);
62
+ return [...counts].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]));
63
+ }
64
+ function table(header, rows) {
65
+ return [
66
+ `| ${header[0]} | ${header[1]} |`,
67
+ '|---|---:|',
68
+ ...rows.map(([k, v]) => `| ${k} | ${v} |`),
69
+ ].join('\n');
70
+ }
71
+ /**
72
+ * The narrative form.
73
+ *
74
+ * Ordered so a reader meets the caveats before the findings. Coverage leads, because every count
75
+ * below it means something different depending on what was captured, and a reader who has
76
+ * already absorbed "89 rows" will not revise that impression when the caveat arrives later.
77
+ */
78
+ export function renderSummary(output) {
79
+ const rows = chronological(output.rows);
80
+ const sections = [];
81
+ sections.push('# Timeline');
82
+ sections.push(`**Window:** ${output.window}`);
83
+ sections.push(`**Seeds:** ${output.seeds.map((s) => `${s.type}:${s.value}`).join(', ') || '(none — whole window)'}`);
84
+ sections.push('## Coverage');
85
+ sections.push('```\n' + output.coverage.banner() + '\n```');
86
+ sections.push(output.coverage.statement(rows.length));
87
+ sections.push('## Rows by event type');
88
+ sections.push(rows.length === 0 ? '_No rows._' : table(['Event type', 'Rows'], countBy(rows, (r) => r.event_type)));
89
+ sections.push('## Rows by attribution');
90
+ sections.push(rows.length === 0 ? '_No rows._' : table(['Tied in by', 'Rows'], countBy(rows, (r) => String(r.attribution))));
91
+ sections.push('## Expansions refused');
92
+ if (output.refusals.length === 0) {
93
+ // Stated rather than omitted: an investigator cannot tell an empty section from an
94
+ // unwritten one, and "nothing was refused" is a materially different claim from silence.
95
+ sections.push('No expansions were refused. Every key reached was within the cardinality threshold.');
96
+ }
97
+ else {
98
+ sections.push(output.refusals
99
+ .map((r) => `- \`${r.type}\` **${r.value}** is shared by ${r.cardinality} distinct addresses ` +
100
+ `(threshold ${r.threshold}) — not expanded. Override with \`--allow-shared-identity\`.`)
101
+ .join('\n'));
102
+ }
103
+ sections.push('## Did records leave');
104
+ const withCounts = rows.filter((r) => r.rows_processed !== undefined || r.records_returned !== undefined);
105
+ if (withCounts.length === 0) {
106
+ // The honest answer to an unanswerable question. No EventLogFile type records what came
107
+ // back, so silence here would let a reader infer "nothing left" from evidence that cannot
108
+ // support it either way.
109
+ sections.push('Unanswerable from this capture — no real-time event rows were captured for this window, ' +
110
+ 'and no EventLogFile type records how many records a query returned.');
111
+ }
112
+ else {
113
+ sections.push(withCounts
114
+ .map((r) => `- \`${r.event_type}\` at ${r.timestamp_utc} — Rows processed: ${r.rows_processed ?? '(not stated)'}` +
115
+ `, Records returned: ${r.records_returned ?? '(not stated)'}`)
116
+ .join('\n'));
117
+ }
118
+ return sections.join('\n\n') + '\n';
119
+ }
120
+ //# sourceMappingURL=render.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cclabsnz/sf-audit",
3
- "version": "1.7.0",
3
+ "version": "1.8.0",
4
4
  "description": "Salesforce Security Audit — native sf plugin",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -20,7 +20,7 @@
20
20
  "@salesforce/sf-plugins-core": "^13",
21
21
  "chart.js": "^4.5.1",
22
22
  "zod": "^4",
23
- "@cclabsnz/sf-core": "^0.1.5"
23
+ "@cclabsnz/sf-core": "^0.3.0"
24
24
  },
25
25
  "devDependencies": {
26
26
  "@jest/globals": "^30.4.1",
@@ -70,8 +70,8 @@
70
70
  "form-data": "^4.0.6",
71
71
  "js-yaml@3": "^3.15.0",
72
72
  "handlebars": "^4.7.9",
73
- "brace-expansion": "^5.0.8",
74
- "fast-uri@3": "^3.1.4"
73
+ "brace-expansion": "^5.0.9",
74
+ "fast-uri@3": "^3.1.5"
75
75
  }
76
76
  }
77
77
  }