@cclabsnz/sf-audit 1.12.0 → 1.14.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.
Files changed (59) hide show
  1. package/CHANGELOG.md +109 -0
  2. package/README.md +12 -2
  3. package/lib/chains/CapabilityRegistry.d.ts +1 -1
  4. package/lib/chains/CapabilityRegistry.js +49 -1
  5. package/lib/chains/namedChains.js +230 -0
  6. package/lib/commands/audit/incident/collect.d.ts +22 -0
  7. package/lib/commands/audit/incident/collect.js +46 -0
  8. package/lib/commands/audit/incident/report.d.ts +29 -0
  9. package/lib/commands/audit/incident/report.js +87 -0
  10. package/lib/commands/audit/timeline.js +1 -1
  11. package/lib/incident/analyse/actions.d.ts +22 -0
  12. package/lib/incident/analyse/actions.js +73 -0
  13. package/lib/incident/analyse/actors.d.ts +56 -0
  14. package/lib/incident/analyse/actors.js +231 -0
  15. package/lib/incident/analyse/baseline.d.ts +24 -0
  16. package/lib/incident/analyse/baseline.js +66 -0
  17. package/lib/incident/analyse/configDelta.d.ts +33 -0
  18. package/lib/incident/analyse/configDelta.js +98 -0
  19. package/lib/incident/analyse/index.d.ts +41 -0
  20. package/lib/incident/analyse/index.js +68 -0
  21. package/lib/incident/analyse/outcomes.d.ts +28 -0
  22. package/lib/incident/analyse/outcomes.js +32 -0
  23. package/lib/incident/analyse/responses.d.ts +59 -0
  24. package/lib/incident/analyse/responses.js +201 -0
  25. package/lib/incident/analyse/verdict.d.ts +40 -0
  26. package/lib/incident/analyse/verdict.js +149 -0
  27. package/lib/incident/bundleIo.d.ts +34 -0
  28. package/lib/incident/bundleIo.js +74 -0
  29. package/lib/incident/collect/collectBundle.d.ts +21 -0
  30. package/lib/incident/collect/collectBundle.js +130 -0
  31. package/lib/incident/collect/discoverWaves.d.ts +15 -0
  32. package/lib/incident/collect/discoverWaves.js +90 -0
  33. package/lib/incident/collect/followUp.d.ts +14 -0
  34. package/lib/incident/collect/followUp.js +64 -0
  35. package/lib/incident/collect/orgErrors.d.ts +5 -0
  36. package/lib/incident/collect/orgErrors.js +11 -0
  37. package/lib/incident/collect/snapshotOrg.d.ts +18 -0
  38. package/lib/incident/collect/snapshotOrg.js +117 -0
  39. package/lib/incident/collect/streamGuestLogs.d.ts +17 -0
  40. package/lib/incident/collect/streamGuestLogs.js +116 -0
  41. package/lib/incident/csv.d.ts +32 -0
  42. package/lib/incident/csv.js +176 -0
  43. package/lib/incident/ipRanges.d.ts +23 -0
  44. package/lib/incident/ipRanges.js +64 -0
  45. package/lib/incident/model.d.ts +132 -0
  46. package/lib/incident/model.js +26 -0
  47. package/lib/incident/render/evidence.d.ts +15 -0
  48. package/lib/incident/render/evidence.js +52 -0
  49. package/lib/incident/render/html.d.ts +7 -0
  50. package/lib/incident/render/html.js +144 -0
  51. package/lib/incident/render/labels.d.ts +9 -0
  52. package/lib/incident/render/labels.js +22 -0
  53. package/lib/incident/render/markdown.d.ts +17 -0
  54. package/lib/incident/render/markdown.js +91 -0
  55. package/lib/incident/render/redact.d.ts +7 -0
  56. package/lib/incident/render/redact.js +62 -0
  57. package/lib/incident/text.d.ts +9 -0
  58. package/lib/incident/text.js +43 -0
  59. package/package.json +9 -6
@@ -0,0 +1,87 @@
1
+ import * as fs from 'node:fs';
2
+ import * as path from 'node:path';
3
+ import { SfCommand, Flags } from '@salesforce/sf-plugins-core';
4
+ import { resolveBranding } from '@cclabsnz/sf-core';
5
+ import { analyseBundle } from '../../../incident/analyse/index.js';
6
+ import { BundleIncompleteError, BundleIntegrityError } from '../../../incident/bundleIo.js';
7
+ import { buildEvidence, writeEvidence } from '../../../incident/render/evidence.js';
8
+ import { redactResult } from '../../../incident/render/redact.js';
9
+ import { renderMarkdown } from '../../../incident/render/markdown.js';
10
+ import { renderHtml } from '../../../incident/render/html.js';
11
+ export function parseFormats(input) {
12
+ const formats = input.split(',').map((f) => f.trim()).filter((f) => f.length > 0);
13
+ const bad = formats.filter((f) => !['html', 'md', 'json'].includes(f));
14
+ if (formats.length === 0 || bad.length > 0) {
15
+ throw new Error(`Unknown --format value(s): ${bad.length > 0 ? bad.join(', ') : input || '(empty)'}. Use html, md, json.`);
16
+ }
17
+ return formats;
18
+ }
19
+ export async function writeReport(bundleDir, opts) {
20
+ let result = await analyseBundle(bundleDir, { spikeRatio: opts.spikeRatio });
21
+ if (opts.redact)
22
+ result = redactResult(result);
23
+ const ev = buildEvidence(result);
24
+ fs.mkdirSync(opts.outputDir, { recursive: true });
25
+ const written = [];
26
+ const put = (name, body) => { const p = path.join(opts.outputDir, name); fs.writeFileSync(p, body); written.push(p); };
27
+ if (opts.formats.includes('html'))
28
+ put('incident-report.html', renderHtml(result, ev, opts.branding));
29
+ if (opts.formats.includes('md'))
30
+ put('incident-report.md', renderMarkdown(result, ev));
31
+ if (opts.formats.includes('json'))
32
+ put('incident-report.json', JSON.stringify(result, null, 2));
33
+ written.push(...writeEvidence(opts.outputDir, ev.tables));
34
+ return written;
35
+ }
36
+ export default class AuditIncidentReportCommand extends SfCommand {
37
+ static summary = 'Analyse an incident bundle offline and write a client-facing report';
38
+ static description = 'Reads a bundle from `sf audit incident collect` without connecting to the org. Writes an HTML report (print to PDF), ' +
39
+ 'Markdown, JSON and one evidence CSV per table. Every number in the report cites an evidence file.';
40
+ static examples = [
41
+ '<%= config.bin %> <%= command.id %> --bundle ~/.sf/incidents/00Dxx0000000000EAA/2026-10-05T00-00-00Z',
42
+ '<%= config.bin %> <%= command.id %> --bundle ./bundle --redact --branding ./report-branding.json',
43
+ ];
44
+ static flags = {
45
+ bundle: Flags.string({ summary: 'Bundle directory written by incident collect.', required: true }),
46
+ format: Flags.string({ summary: 'Comma-separated: html,md,json.', default: 'html,md,json' }),
47
+ output: Flags.string({ char: 'o', summary: 'Directory to write the report into.', default: '.' }),
48
+ redact: Flags.boolean({ summary: 'Replace linked users with ids and truncate IPs to /24 for wider sharing.', default: false }),
49
+ 'spike-ratio': Flags.integer({ summary: 'A day is a spike when controller calls reach this multiple of the baseline median.', default: 5, min: 1 }),
50
+ branding: Flags.string({ summary: 'Path to a report-branding.json.', helpValue: './report-branding.json' }),
51
+ 'prepared-for': Flags.string({ summary: 'Client name shown on the report.' }),
52
+ };
53
+ async run() {
54
+ const { flags } = await this.parse(AuditIncidentReportCommand);
55
+ let formats;
56
+ try {
57
+ formats = parseFormats(flags.format);
58
+ }
59
+ catch (e) {
60
+ this.error(e.message, { exit: 2 });
61
+ }
62
+ let overrides;
63
+ if (flags.branding)
64
+ overrides = JSON.parse(fs.readFileSync(flags.branding, 'utf-8'));
65
+ try {
66
+ const written = await writeReport(flags.bundle, {
67
+ formats,
68
+ outputDir: flags.output,
69
+ redact: flags.redact,
70
+ spikeRatio: flags['spike-ratio'],
71
+ branding: resolveBranding(overrides, flags['prepared-for']),
72
+ });
73
+ for (const p of written.filter((x) => !x.endsWith('.csv')))
74
+ this.log(`Wrote ${p}`);
75
+ this.log(`Wrote ${written.filter((x) => x.endsWith('.csv')).length} evidence file(s) to ${path.join(flags.output, 'evidence')}`);
76
+ return { written };
77
+ }
78
+ catch (e) {
79
+ if (e instanceof BundleIntegrityError)
80
+ this.error(`${e.message}. Re-collect rather than editing a bundle.`, { exit: 2 });
81
+ if (e instanceof BundleIncompleteError)
82
+ this.error(e.message, { exit: 2 });
83
+ throw e;
84
+ }
85
+ }
86
+ }
87
+ //# sourceMappingURL=report.js.map
@@ -9,7 +9,7 @@ import { assessCoverage } from '../../timeline/CaptureIndex.js';
9
9
  import { correlate, DEFAULT_MAX_CARDINALITY } from '../../timeline/CorrelationEngine.js';
10
10
  import { normaliseRow } from '../../timeline/normalise.js';
11
11
  import { renderCsv, renderJson, renderSummary } from '../../timeline/render.js';
12
- /** `ip:1.2.3.4` — typed rather than inferred, so a value is never guessed at. */
12
+ /** `ip:192.0.2.10` — typed rather than inferred, so a value is never guessed at. */
13
13
  const SEED_PREFIXES = {
14
14
  ip: 'clientIp',
15
15
  user: 'userId',
@@ -0,0 +1,22 @@
1
+ import type { ActionClass } from '../model.js';
2
+ /** `Controller.method` names in invocation order. ApexActionController.execute(X.y) yields `X.y`. */
3
+ export declare function parseActions(actionMessage: string): string[];
4
+ /**
5
+ * Classified by method, data access first: a known read method is data access whatever its
6
+ * controller is called. Then auth (method only), then known plumbing. Anything else that parsed
7
+ * may read data — an @AuraEnabled method callable by a guest is a read surface — so it is
8
+ * assessed as data access. `unknown` is kept for compatibility and never returned for a parsed name.
9
+ */
10
+ export declare function classifyAction(name: string): ActionClass;
11
+ export declare function classesOf(actionMessage: string): Set<ActionClass>;
12
+ export interface ActionSummary {
13
+ byClass: Record<ActionClass, number>;
14
+ byName: Array<{
15
+ name: string;
16
+ cls: ActionClass;
17
+ count: number;
18
+ }>;
19
+ }
20
+ export declare function summariseActionCounts(counts: Iterable<Record<string, number>>): ActionSummary;
21
+ export declare function summariseActions(messages: Iterable<string>): ActionSummary;
22
+ //# sourceMappingURL=actions.d.ts.map
@@ -0,0 +1,73 @@
1
+ const DESCRIPTOR = /(?:serviceComponent|aura|apex):\/\/([\w.]+)\/ACTION\$(\w+)(?:\(([\w.]+)\))?/g;
2
+ /** `Controller.method` names in invocation order. ApexActionController.execute(X.y) yields `X.y`. */
3
+ export function parseActions(actionMessage) {
4
+ const out = [];
5
+ for (const m of actionMessage.matchAll(DESCRIPTOR)) {
6
+ if (m[3]) {
7
+ out.push(m[3]);
8
+ continue;
9
+ }
10
+ const controller = m[1].split('.').pop();
11
+ out.push(`${controller}.${m[2]}`);
12
+ }
13
+ return out;
14
+ }
15
+ /**
16
+ * Matched against the WHOLE method name, never a substring and never the controller:
17
+ * LoginHistoryController.getRecords, getLoginHistory and getVerifiedProviders are reads. The
18
+ * getter shape covers login-form configuration calls (getForgotPasswordUrl,
19
+ * getIsSelfRegistrationEnabled, getIsUsernamePasswordEnabled).
20
+ */
21
+ const AUTH_METHOD = /^(?:login|logout|forgotPassword|resetPassword|changePassword|setPassword|selfRegister|register|signup|verify\w*|passwordless\w*|get(?:Is)?\w*(?:Password|Registration|SelfReg|Login)\w*(?:Url|Enabled))$/i;
22
+ const PLUMBING = [
23
+ /^RichTextController\./, /^NavigationMenuDataProviderController\./, /^NetworkTrackingController\./,
24
+ /^InstrumentationBeaconController\./, /^QuarterbackController\./, /^ComponentController\./,
25
+ /^HostConfigController\./, /^PubliclyCacheableAttributeLoaderController\./, /^omnistudio__/,
26
+ /recaptcha/i, /^LabelController\./, /^DynamicThemeController\./,
27
+ ];
28
+ const DATA_ACCESS_METHOD = [
29
+ /^getItems$/, /^getRecord\w*$/, /^executeGraphQL$/, /^getListUi\w*$/, /^getRelatedList\w*$/,
30
+ /^getLookupRecords$/, /^search\w*$/,
31
+ ];
32
+ /**
33
+ * Classified by method, data access first: a known read method is data access whatever its
34
+ * controller is called. Then auth (method only), then known plumbing. Anything else that parsed
35
+ * may read data — an @AuraEnabled method callable by a guest is a read surface — so it is
36
+ * assessed as data access. `unknown` is kept for compatibility and never returned for a parsed name.
37
+ */
38
+ export function classifyAction(name) {
39
+ const method = name.slice(name.lastIndexOf('.') + 1);
40
+ if (DATA_ACCESS_METHOD.some((r) => r.test(method)))
41
+ return 'data-access';
42
+ if (AUTH_METHOD.test(method))
43
+ return 'auth';
44
+ if (PLUMBING.some((r) => r.test(name)))
45
+ return 'plumbing';
46
+ return 'data-access';
47
+ }
48
+ export function classesOf(actionMessage) {
49
+ return new Set(parseActions(actionMessage).map(classifyAction));
50
+ }
51
+ export function summariseActionCounts(counts) {
52
+ const byClass = { 'data-access': 0, auth: 0, plumbing: 0, unknown: 0 };
53
+ const byName = new Map();
54
+ for (const c of counts) {
55
+ for (const [name, n] of Object.entries(c)) {
56
+ byClass[classifyAction(name)] += n;
57
+ byName.set(name, (byName.get(name) ?? 0) + n);
58
+ }
59
+ }
60
+ return {
61
+ byClass,
62
+ byName: [...byName.entries()].map(([name, count]) => ({ name, cls: classifyAction(name), count }))
63
+ .sort((a, b) => b.count - a.count || a.name.localeCompare(b.name)),
64
+ };
65
+ }
66
+ export function summariseActions(messages) {
67
+ const counts = {};
68
+ for (const m of messages)
69
+ for (const n of parseActions(m))
70
+ counts[n] = (counts[n] ?? 0) + 1;
71
+ return summariseActionCounts([counts]);
72
+ }
73
+ //# sourceMappingURL=actions.js.map
@@ -0,0 +1,56 @@
1
+ import type { Bundle } from '../bundleIo.js';
2
+ import type { BundleManifest, Wave } from '../model.js';
3
+ import type { IpRangeSet } from '../ipRanges.js';
4
+ export interface Actor {
5
+ id: string;
6
+ block: string;
7
+ ips: string[];
8
+ days: string[];
9
+ controllerCalls: number;
10
+ pageLoads: number;
11
+ firstSeen: string;
12
+ lastSeen: string;
13
+ hourly: Record<string, number>;
14
+ steady: boolean;
15
+ userAgents: Array<{
16
+ ua: string;
17
+ count: number;
18
+ }>;
19
+ emptyUaShare: number;
20
+ markers: string[];
21
+ hosting: string | null;
22
+ hostingAssessed: boolean;
23
+ sources: Array<'detector-ip' | 'outlier'>;
24
+ /** Invocation counts per parsed action name (Controller.method). Bounded by distinct names. */
25
+ actionCounts: Record<string, number>;
26
+ /**
27
+ * Actor IPs that many distinct users also log in from (a proxy or NAT). Logins from them are
28
+ * not access, and one person's activity behind them cannot be separated in these logs.
29
+ */
30
+ sharedEgressIps: string[];
31
+ }
32
+ /**
33
+ * IPs that more than DEFAULTS.sharedEgressUsers distinct users SUCCESSFULLY logged in from, counting
34
+ * only users known not to have been created through a guest site. Failed logins (credential
35
+ * stuffing) and self-registered throwaway accounts can therefore never make an attacker's IP look
36
+ * like a proxy; an unknown creator does not count either.
37
+ */
38
+ export declare function sharedEgressIps(b: Bundle): Set<string>;
39
+ /**
40
+ * One canonical form per address, used on both sides of every IP comparison: trimmed,
41
+ * lowercased, and for IPv6 fully expanded then compressed per RFC 5952 (leading zeros dropped,
42
+ * the first longest run of two or more zero groups written as ::). Text that is not a plain
43
+ * IPv6 address (including IPv4-embedded forms) is only trimmed and lowercased.
44
+ */
45
+ export declare function normaliseIp(raw: string): string;
46
+ export declare function blockOf(rawIp: string): string;
47
+ /** Days collected for this guest that are not a wave day of any wave on that guest. */
48
+ export declare function baselineDaysFor(manifest: BundleManifest, guestId15: string): string[];
49
+ /**
50
+ * Actor blocks for a wave: any block whose controller calls on a wave day exceed
51
+ * max(outlierFloor, outlierMultiple × the busiest block on any baseline day, ignoring blocks that
52
+ * also appear on a wave day), plus any block
53
+ * holding an anomaly event's SourceIp (which catches low-volume probes that are not spikes).
54
+ */
55
+ export declare function findActors(b: Bundle, wave: Wave, ranges: IpRangeSet | null): Promise<Actor[]>;
56
+ //# sourceMappingURL=actors.d.ts.map
@@ -0,0 +1,231 @@
1
+ import { DEFAULTS, id15 } from '../model.js';
2
+ import { parseActions } from './actions.js';
3
+ /**
4
+ * IPs that more than DEFAULTS.sharedEgressUsers distinct users SUCCESSFULLY logged in from, counting
5
+ * only users known not to have been created through a guest site. Failed logins (credential
6
+ * stuffing) and self-registered throwaway accounts can therefore never make an attacker's IP look
7
+ * like a proxy; an unknown creator does not count either.
8
+ */
9
+ export function sharedEgressIps(b) {
10
+ const guestIds = new Set(b.manifest.guests.map((g) => g.id15));
11
+ const staff = new Set(b.followUp.users.filter((u) => u.createdById15 && !guestIds.has(u.createdById15)).map((u) => u.id15));
12
+ const users = new Map();
13
+ for (const l of b.followUp.logins) {
14
+ if (l.status !== 'Success' || !staff.has(l.userId15))
15
+ continue;
16
+ const ip = normaliseIp(l.sourceIp);
17
+ let s = users.get(ip);
18
+ if (!s) {
19
+ s = new Set();
20
+ users.set(ip, s);
21
+ }
22
+ s.add(l.userId15);
23
+ }
24
+ return new Set([...users.entries()].filter(([, s]) => s.size > DEFAULTS.sharedEgressUsers).map(([ip]) => ip));
25
+ }
26
+ const MARKERS = [
27
+ { name: 'log4shell', re: /\$\{(?:jndi|::-|\$\{::-)/i },
28
+ { name: 'path-traversal', re: /\.\.\/|%2e%2e%2f/i },
29
+ { name: 'script-injection', re: /<script|%3cscript/i },
30
+ { name: 'unicode-escape', re: /%u00/i },
31
+ ];
32
+ /**
33
+ * One canonical form per address, used on both sides of every IP comparison: trimmed,
34
+ * lowercased, and for IPv6 fully expanded then compressed per RFC 5952 (leading zeros dropped,
35
+ * the first longest run of two or more zero groups written as ::). Text that is not a plain
36
+ * IPv6 address (including IPv4-embedded forms) is only trimmed and lowercased.
37
+ */
38
+ export function normaliseIp(raw) {
39
+ const ip = (raw ?? '').trim().toLowerCase();
40
+ if (!ip.includes(':') || ip.includes('.'))
41
+ return ip;
42
+ const halves = ip.split('::');
43
+ if (halves.length > 2)
44
+ return ip;
45
+ const left = halves[0] ? halves[0].split(':') : [];
46
+ const right = halves.length === 2 && halves[1] ? halves[1].split(':') : [];
47
+ const fill = halves.length === 2 ? 8 - left.length - right.length : 0;
48
+ if ((halves.length === 1 && left.length !== 8) || fill < 0 || (halves.length === 2 && fill < 1))
49
+ return ip;
50
+ const groups = [...left, ...Array(fill).fill('0'), ...right];
51
+ if (groups.some((g) => !/^[0-9a-f]{1,4}$/.test(g)))
52
+ return ip;
53
+ const hex = groups.map((g) => parseInt(g, 16).toString(16));
54
+ let bestStart = -1;
55
+ let bestLen = 0;
56
+ for (let i = 0; i < 8;) {
57
+ if (hex[i] !== '0') {
58
+ i++;
59
+ continue;
60
+ }
61
+ let j = i;
62
+ while (j < 8 && hex[j] === '0')
63
+ j++;
64
+ if (j - i > bestLen) {
65
+ bestStart = i;
66
+ bestLen = j - i;
67
+ }
68
+ i = j;
69
+ }
70
+ if (bestLen < 2)
71
+ return hex.join(':');
72
+ return `${hex.slice(0, bestStart).join(':')}::${hex.slice(bestStart + bestLen).join(':')}`;
73
+ }
74
+ export function blockOf(rawIp) {
75
+ const ip = rawIp.trim().toLowerCase();
76
+ if (ip.includes(':')) {
77
+ const [head, tail] = ip.split('::');
78
+ const left = head ? head.split(':') : [];
79
+ const right = tail !== undefined && tail !== '' ? tail.split(':') : [];
80
+ const full = [...left, ...Array(Math.max(0, 8 - left.length - right.length)).fill('0'), ...right];
81
+ return `${full.slice(0, 4).join(':')}::/64`;
82
+ }
83
+ const p = ip.split('.');
84
+ return p.length === 4 ? `${p[0]}.${p[1]}.${p[2]}.0/24` : ip;
85
+ }
86
+ /** Days collected for this guest that are not a wave day of any wave on that guest. */
87
+ export function baselineDaysFor(manifest, guestId15) {
88
+ const waveDays = new Set(manifest.waves.filter((w) => w.guestId15 === guestId15).flatMap((w) => w.days));
89
+ const days = new Set(manifest.logs.filter((l) => l.type === 'AuraRequest' && l.status === 'collected').map((l) => l.day));
90
+ return [...days].filter((d) => !waveDays.has(d)).sort();
91
+ }
92
+ async function aggregate(b, guestId15, day) {
93
+ const blocks = new Map();
94
+ for await (const r of b.rows('AuraRequest', day)) {
95
+ if (id15(r.USER_ID) !== guestId15 && id15(r.USER_ID_DERIVED) !== guestId15)
96
+ continue;
97
+ const ip = normaliseIp(r.CLIENT_IP ?? '');
98
+ if (!ip)
99
+ continue;
100
+ const key = blockOf(ip);
101
+ const ts = (r.TIMESTAMP_DERIVED ?? '').trim();
102
+ let a = blocks.get(key);
103
+ if (!a) {
104
+ a = { ips: new Set(), calls: 0, loads: 0, first: ts, last: ts, hourly: new Map(), ua: new Map(), markers: new Set(), actions: new Map() };
105
+ blocks.set(key, a);
106
+ }
107
+ a.ips.add(ip);
108
+ if (ts) {
109
+ if (!a.first || ts < a.first)
110
+ a.first = ts;
111
+ if (ts > a.last)
112
+ a.last = ts;
113
+ }
114
+ if (r.ACTION_MESSAGE) {
115
+ a.calls++;
116
+ const hour = ts.slice(0, 13);
117
+ a.hourly.set(hour, (a.hourly.get(hour) ?? 0) + 1);
118
+ for (const n of parseActions(r.ACTION_MESSAGE))
119
+ a.actions.set(n, (a.actions.get(n) ?? 0) + 1);
120
+ }
121
+ else
122
+ a.loads++;
123
+ const ua = r.USER_AGENT ?? '';
124
+ a.ua.set(ua, (a.ua.get(ua) ?? 0) + 1);
125
+ for (const m of MARKERS)
126
+ if (m.re.test(ua) || m.re.test(r.URI ?? ''))
127
+ a.markers.add(m.name);
128
+ }
129
+ return blocks;
130
+ }
131
+ function isSteady(hourly, first, last) {
132
+ const start = Date.parse(first.slice(0, 13) + ':00:00Z');
133
+ const end = Date.parse(last.slice(0, 13) + ':00:00Z');
134
+ const counts = [];
135
+ for (let t = start; t <= end; t += 3_600_000)
136
+ counts.push(hourly.get(new Date(t).toISOString().slice(0, 13)) ?? 0);
137
+ if (counts.length < 3)
138
+ return false;
139
+ const mean = counts.reduce((s, c) => s + c, 0) / counts.length;
140
+ const sd = Math.sqrt(counts.reduce((s, c) => s + (c - mean) ** 2, 0) / counts.length);
141
+ return mean > 0 && sd / mean < 0.75;
142
+ }
143
+ /**
144
+ * Actor blocks for a wave: any block whose controller calls on a wave day exceed
145
+ * max(outlierFloor, outlierMultiple × the busiest block on any baseline day, ignoring blocks that
146
+ * also appear on a wave day), plus any block
147
+ * holding an anomaly event's SourceIp (which catches low-volume probes that are not spikes).
148
+ */
149
+ export async function findActors(b, wave, ranges) {
150
+ const waveAggs = new Map();
151
+ for (const day of wave.days)
152
+ waveAggs.set(day, await aggregate(b, wave.guestId15, day));
153
+ // Proxy vs attacker. A block is an outlier only when its wave-day calls exceed BOTH its own
154
+ // history (3x its quietest baseline day, so an always-on proxy is never an actor) AND the
155
+ // org's normal busiest block (3x the busiest block on the QUIETEST baseline day, which a scan
156
+ // spilling past midnight into one baseline day cannot raise).
157
+ const baselineDays = baselineDaysFor(b.manifest, wave.guestId15);
158
+ const perDay = [];
159
+ for (const day of baselineDays)
160
+ perDay.push(await aggregate(b, wave.guestId15, day));
161
+ const waveBlocks = new Set([...waveAggs.values()].flatMap((m) => [...m.keys()]));
162
+ // The org's normal busiest block ignores blocks also active on the wave days, so a scan that
163
+ // spills past midnight cannot raise it; the quietest such day is the reference.
164
+ const busiest = perDay.map((m) => [...m].reduce((max, [key, a]) => (waveBlocks.has(key) ? max : Math.max(max, a.calls)), 0));
165
+ const globalRef = busiest.length ? busiest.reduce((a, c) => Math.min(a, c)) : 0;
166
+ // A block's own history exempts it only when it is active across the day on EVERY baseline day
167
+ // (12+ distinct hours): an always-on proxy qualifies, a spill clustered at midnight does not.
168
+ const allDay = (key) => perDay.length > 0 && perDay.every((m) => (m.get(key)?.hourly.size ?? 0) >= 12);
169
+ const ownMin = (key) => perDay.reduce((min, m) => Math.min(min, m.get(key)?.calls ?? 0), Infinity);
170
+ const thresholdFor = (key) => Math.max(DEFAULTS.outlierFloor, DEFAULTS.outlierMultiple * globalRef, allDay(key) ? DEFAULTS.outlierMultiple * ownMin(key) : 0);
171
+ const shared = sharedEgressIps(b);
172
+ const detectorBlocks = new Set(b.anomalies.filter((e) => wave.eventIds.includes(e.eventIdentifier) && e.sourceIp).map((e) => blockOf(normaliseIp(e.sourceIp))));
173
+ const merged = new Map();
174
+ for (const day of wave.days) {
175
+ for (const [key, a] of waveAggs.get(day)) {
176
+ const sources = [];
177
+ if (a.calls > thresholdFor(key))
178
+ sources.push('outlier');
179
+ if (detectorBlocks.has(key))
180
+ sources.push('detector-ip');
181
+ if (sources.length === 0)
182
+ continue;
183
+ const m = merged.get(key);
184
+ if (!m) {
185
+ merged.set(key, { agg: a, days: new Set([day]), sources: new Set(sources) });
186
+ continue;
187
+ }
188
+ m.days.add(day);
189
+ sources.forEach((s) => m.sources.add(s));
190
+ a.ips.forEach((ip) => m.agg.ips.add(ip));
191
+ m.agg.calls += a.calls;
192
+ m.agg.loads += a.loads;
193
+ if (a.first < m.agg.first)
194
+ m.agg.first = a.first;
195
+ if (a.last > m.agg.last)
196
+ m.agg.last = a.last;
197
+ a.hourly.forEach((v, k) => m.agg.hourly.set(k, (m.agg.hourly.get(k) ?? 0) + v));
198
+ a.ua.forEach((v, k) => m.agg.ua.set(k, (m.agg.ua.get(k) ?? 0) + v));
199
+ a.markers.forEach((x) => m.agg.markers.add(x));
200
+ a.actions.forEach((v, k) => m.agg.actions.set(k, (m.agg.actions.get(k) ?? 0) + v));
201
+ }
202
+ }
203
+ return [...merged.entries()]
204
+ .sort((x, y) => y[1].agg.calls - x[1].agg.calls)
205
+ .map(([block, { agg, days, sources }], i) => {
206
+ const total = [...agg.ua.values()].reduce((s, c) => s + c, 0);
207
+ const ips = [...agg.ips].sort();
208
+ const v4 = !ips[0].includes(':');
209
+ return {
210
+ id: `${wave.id}-A${i + 1}`,
211
+ block,
212
+ ips,
213
+ days: [...days].sort(),
214
+ controllerCalls: agg.calls,
215
+ pageLoads: agg.loads,
216
+ firstSeen: agg.first,
217
+ lastSeen: agg.last,
218
+ hourly: Object.fromEntries([...agg.hourly.entries()].sort()),
219
+ steady: isSteady(agg.hourly, agg.first, agg.last),
220
+ userAgents: [...agg.ua.entries()].map(([ua, count]) => ({ ua, count })).sort((a, c) => c.count - a.count),
221
+ emptyUaShare: total ? (agg.ua.get('') ?? 0) / total : 0,
222
+ markers: [...agg.markers].sort(),
223
+ hosting: ranges && v4 ? ranges.lookup(ips[0]) : null,
224
+ hostingAssessed: ranges !== null && v4,
225
+ sources: [...sources].sort(),
226
+ actionCounts: Object.fromEntries([...agg.actions.entries()].sort()),
227
+ sharedEgressIps: ips.filter((ip) => shared.has(normaliseIp(ip))),
228
+ };
229
+ });
230
+ }
231
+ //# sourceMappingURL=actors.js.map
@@ -0,0 +1,24 @@
1
+ import type { Bundle } from '../bundleIo.js';
2
+ import { type LogType, type Wave } from '../model.js';
3
+ export interface DayVolume {
4
+ day: string;
5
+ guestId15: string;
6
+ /** AuraRequest rows with an ACTION_MESSAGE: the single primary measure. */
7
+ controllerCalls: number;
8
+ pageLoads: number;
9
+ /** Guest rows in other event types for the same day. Corroboration only; never summed. */
10
+ corroboration: Partial<Record<LogType, number>>;
11
+ }
12
+ export declare function computeDayVolumes(b: Bundle): Promise<DayVolume[]>;
13
+ export interface SpikeAssessment {
14
+ day: string;
15
+ /** null when AuraRequest was not collected for the day: unknown, never zero. */
16
+ controllerCalls: number | null;
17
+ baselineMedian: number | null;
18
+ ratio: number | null;
19
+ isSpike: boolean;
20
+ /** Sum of TotalControllerEvents on that day: the detector's own sample, a different unit. */
21
+ detectorSample: number | null;
22
+ }
23
+ export declare function assessSpikes(b: Bundle, volumes: DayVolume[], wave: Wave, spikeRatio: number): SpikeAssessment[];
24
+ //# sourceMappingURL=baseline.d.ts.map
@@ -0,0 +1,66 @@
1
+ import { DEFAULTS, id15 } from '../model.js';
2
+ import { baselineDaysFor } from './actors.js';
3
+ export async function computeDayVolumes(b) {
4
+ const out = new Map();
5
+ const get = (day, guest) => {
6
+ const k = `${guest}|${day}`;
7
+ let v = out.get(k);
8
+ if (!v) {
9
+ v = { day, guestId15: guest, controllerCalls: 0, pageLoads: 0, corroboration: {} };
10
+ out.set(k, v);
11
+ }
12
+ return v;
13
+ };
14
+ const days = [...new Set(b.manifest.logs.map((l) => l.day))].sort();
15
+ for (const day of days) {
16
+ for await (const r of b.rows('AuraRequest', day)) {
17
+ const g = id15(r.USER_ID) ?? id15(r.USER_ID_DERIVED);
18
+ if (!g)
19
+ continue;
20
+ const v = get(day, g);
21
+ if (r.ACTION_MESSAGE)
22
+ v.controllerCalls++;
23
+ else
24
+ v.pageLoads++;
25
+ }
26
+ }
27
+ for (const l of b.manifest.logs) {
28
+ if (l.type === 'AuraRequest' || l.status !== 'collected')
29
+ continue;
30
+ for (const [g, n] of Object.entries(l.guestRowsByUser))
31
+ get(l.day, g).corroboration[l.type] = n;
32
+ }
33
+ return [...out.values()].sort((a, c) => a.day.localeCompare(c.day) || a.guestId15.localeCompare(c.guestId15));
34
+ }
35
+ function median(xs) {
36
+ if (xs.length === 0)
37
+ return null;
38
+ const s = [...xs].sort((a, c) => a - c);
39
+ const m = Math.floor(s.length / 2);
40
+ return s.length % 2 ? s[m] : (s[m - 1] + s[m]) / 2;
41
+ }
42
+ export function assessSpikes(b, volumes, wave, spikeRatio) {
43
+ const own = volumes.filter((v) => v.guestId15 === wave.guestId15);
44
+ const calls = (day) => own.find((v) => v.day === day)?.controllerCalls ?? 0;
45
+ // Only days with AuraRequest traffic from this guest count as baseline: a day that exists only
46
+ // through corroboration rows is not a baseline day, and no traffic at all means no baseline.
47
+ const base = baselineDaysFor(b.manifest, wave.guestId15).filter((d) => own.some((v) => v.day === d && v.controllerCalls + v.pageLoads > 0));
48
+ const baselineMedian = median(base.map(calls));
49
+ const collected = (day) => b.manifest.logs.some((l) => l.type === 'AuraRequest' && l.day === day && l.status === 'collected');
50
+ return wave.days.map((day) => {
51
+ const c = collected(day) ? calls(day) : null;
52
+ const ratio = baselineMedian && c !== null ? c / baselineMedian : null;
53
+ // A zero median has no ratio; a quiet baseline must not hide a burst, so use the actor floor.
54
+ const isSpike = c === null ? false : baselineMedian === 0 ? c >= DEFAULTS.outlierFloor : ratio !== null && ratio >= spikeRatio;
55
+ const events = b.anomalies.filter((e) => wave.eventIds.includes(e.eventIdentifier) && e.eventDate.startsWith(day) && e.totalControllerEvents !== undefined);
56
+ return {
57
+ day,
58
+ controllerCalls: c,
59
+ baselineMedian,
60
+ ratio,
61
+ isSpike,
62
+ detectorSample: events.length ? events.reduce((s, e) => s + (e.totalControllerEvents ?? 0), 0) : null,
63
+ };
64
+ });
65
+ }
66
+ //# sourceMappingURL=baseline.js.map
@@ -0,0 +1,33 @@
1
+ import type { AuditRow, GuestUser, Wave } from '../model.js';
2
+ export interface ConfigChange {
3
+ at: string;
4
+ by: string;
5
+ section: string | null;
6
+ display: string;
7
+ sites: string[];
8
+ }
9
+ /**
10
+ * `before`/`between`/`after` hold changes strictly outside every wave span (exclusive bounds);
11
+ * `during` holds changes made on a wave span's own days (inclusive bounds).
12
+ */
13
+ export interface Period {
14
+ label: string;
15
+ kind: 'before' | 'during' | 'between' | 'after';
16
+ from: string | null;
17
+ to: string | null;
18
+ bySite: Record<string, ConfigChange[]>;
19
+ shared: ConfigChange[];
20
+ }
21
+ export interface Asymmetry {
22
+ waveId: string;
23
+ site: string;
24
+ changes: number;
25
+ comparedSite: string;
26
+ comparedChanges: number;
27
+ period: string;
28
+ }
29
+ export declare function computeConfigDelta(audit: AuditRow[], guests: GuestUser[], waves: Wave[]): {
30
+ periods: Period[];
31
+ asymmetries: Asymmetry[];
32
+ };
33
+ //# sourceMappingURL=configDelta.d.ts.map