@cclabsnz/sf-audit 1.13.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 (55) hide show
  1. package/CHANGELOG.md +42 -0
  2. package/README.md +10 -0
  3. package/lib/commands/audit/incident/collect.d.ts +22 -0
  4. package/lib/commands/audit/incident/collect.js +46 -0
  5. package/lib/commands/audit/incident/report.d.ts +29 -0
  6. package/lib/commands/audit/incident/report.js +87 -0
  7. package/lib/incident/analyse/actions.d.ts +22 -0
  8. package/lib/incident/analyse/actions.js +73 -0
  9. package/lib/incident/analyse/actors.d.ts +56 -0
  10. package/lib/incident/analyse/actors.js +231 -0
  11. package/lib/incident/analyse/baseline.d.ts +24 -0
  12. package/lib/incident/analyse/baseline.js +66 -0
  13. package/lib/incident/analyse/configDelta.d.ts +33 -0
  14. package/lib/incident/analyse/configDelta.js +98 -0
  15. package/lib/incident/analyse/index.d.ts +41 -0
  16. package/lib/incident/analyse/index.js +68 -0
  17. package/lib/incident/analyse/outcomes.d.ts +28 -0
  18. package/lib/incident/analyse/outcomes.js +32 -0
  19. package/lib/incident/analyse/responses.d.ts +59 -0
  20. package/lib/incident/analyse/responses.js +201 -0
  21. package/lib/incident/analyse/verdict.d.ts +40 -0
  22. package/lib/incident/analyse/verdict.js +149 -0
  23. package/lib/incident/bundleIo.d.ts +34 -0
  24. package/lib/incident/bundleIo.js +74 -0
  25. package/lib/incident/collect/collectBundle.d.ts +21 -0
  26. package/lib/incident/collect/collectBundle.js +130 -0
  27. package/lib/incident/collect/discoverWaves.d.ts +15 -0
  28. package/lib/incident/collect/discoverWaves.js +90 -0
  29. package/lib/incident/collect/followUp.d.ts +14 -0
  30. package/lib/incident/collect/followUp.js +64 -0
  31. package/lib/incident/collect/orgErrors.d.ts +5 -0
  32. package/lib/incident/collect/orgErrors.js +11 -0
  33. package/lib/incident/collect/snapshotOrg.d.ts +18 -0
  34. package/lib/incident/collect/snapshotOrg.js +117 -0
  35. package/lib/incident/collect/streamGuestLogs.d.ts +17 -0
  36. package/lib/incident/collect/streamGuestLogs.js +116 -0
  37. package/lib/incident/csv.d.ts +32 -0
  38. package/lib/incident/csv.js +176 -0
  39. package/lib/incident/ipRanges.d.ts +23 -0
  40. package/lib/incident/ipRanges.js +64 -0
  41. package/lib/incident/model.d.ts +132 -0
  42. package/lib/incident/model.js +26 -0
  43. package/lib/incident/render/evidence.d.ts +15 -0
  44. package/lib/incident/render/evidence.js +52 -0
  45. package/lib/incident/render/html.d.ts +7 -0
  46. package/lib/incident/render/html.js +144 -0
  47. package/lib/incident/render/labels.d.ts +9 -0
  48. package/lib/incident/render/labels.js +22 -0
  49. package/lib/incident/render/markdown.d.ts +17 -0
  50. package/lib/incident/render/markdown.js +91 -0
  51. package/lib/incident/render/redact.d.ts +7 -0
  52. package/lib/incident/render/redact.js +62 -0
  53. package/lib/incident/text.d.ts +9 -0
  54. package/lib/incident/text.js +43 -0
  55. package/package.json +7 -4
@@ -0,0 +1,132 @@
1
+ /**
2
+ * Types shared by `sf audit incident collect` and `report`. The bundle on disk is the contract
3
+ * between the two commands: collect writes it, report only reads it.
4
+ */
5
+ export declare const LOG_TYPES: readonly ['AuraRequest', 'Sites', 'URI', 'ApexExecution', 'VisualforceRequest', 'ContentTransfer', 'GraphQlQueryExecution', 'UniqueQuery', 'LightningError', 'ApexUnexpectedException'];
6
+ export type LogType = (typeof LOG_TYPES)[number];
7
+ /** Without these two, response sizes cannot be assessed, so a wave's result is `not-assessed`. */
8
+ export declare const REQUIRED_LOG_TYPES: readonly LogType[];
9
+ export declare const DEFAULTS: {
10
+ readonly spikeRatio: 5;
11
+ readonly emptyBandBytes: 64;
12
+ readonly auditWindowDays: 4;
13
+ /** jsforce autoFetchQuery stops here; a window returning this many rows may be truncated. */
14
+ readonly auditPageCap: 10000;
15
+ readonly outlierFloor: 100;
16
+ readonly outlierMultiple: 3;
17
+ /** An IP with logins from more distinct users than this is shared egress (proxy, NAT). */
18
+ readonly sharedEgressUsers: 8;
19
+ };
20
+ export declare function id15(id: string | undefined | null): string | undefined;
21
+ export interface AnomalyEvent {
22
+ eventIdentifier: string;
23
+ eventDate: string;
24
+ score: number;
25
+ userId15: string;
26
+ username: string;
27
+ sourceIp?: string;
28
+ userAgent?: string;
29
+ summary?: string;
30
+ totalControllerEvents?: number;
31
+ requestedEntities?: string;
32
+ soqlCommands?: string;
33
+ }
34
+ export interface GuestUser {
35
+ id15: string;
36
+ username: string;
37
+ name: string;
38
+ profileName: string;
39
+ permissionSetLabels: string[];
40
+ siteNames: string[];
41
+ /** false when the user came only from an anomaly event and is no longer an active guest. */
42
+ active: boolean;
43
+ }
44
+ export interface Wave {
45
+ id: string;
46
+ guestId15: string;
47
+ site: string;
48
+ days: string[];
49
+ eventIds: string[];
50
+ }
51
+ export type LogStatus = 'collected' | 'missing' | 'no-permission' | 'failed';
52
+ export interface LogCoverage {
53
+ type: LogType;
54
+ day: string;
55
+ status: LogStatus;
56
+ totalRows: number;
57
+ guestRows: number;
58
+ guestRowsByUser: Record<string, number>;
59
+ malformed: number;
60
+ file?: string;
61
+ detail?: string;
62
+ }
63
+ export interface AuditRow {
64
+ createdDate: string;
65
+ createdBy: string;
66
+ section: string | null;
67
+ action: string;
68
+ display: string;
69
+ }
70
+ export interface AuditCoverage {
71
+ from: string;
72
+ to: string;
73
+ truncatedWindows: Array<{
74
+ from: string;
75
+ to: string;
76
+ }>;
77
+ inaccessible: boolean;
78
+ }
79
+ export interface LoginRow {
80
+ loginTime: string;
81
+ userId15: string;
82
+ sourceIp: string;
83
+ status: string;
84
+ loginUrl?: string;
85
+ browser?: string;
86
+ }
87
+ export interface LoginDayCount {
88
+ day: string;
89
+ status: string;
90
+ count: number;
91
+ }
92
+ export interface LinkedUser {
93
+ id15: string;
94
+ name: string;
95
+ email: string;
96
+ createdDate: string;
97
+ createdById15: string;
98
+ profileName: string;
99
+ isActive: boolean;
100
+ }
101
+ export interface RunningUserLimits {
102
+ queryAllFiles: boolean;
103
+ viewAllData: boolean;
104
+ }
105
+ export interface BundleManifest {
106
+ version: 1;
107
+ complete: boolean;
108
+ orgId: string;
109
+ orgName: string;
110
+ collectedAt: string;
111
+ sinceDays: number;
112
+ detectorAvailable: boolean;
113
+ waves: Wave[];
114
+ guests: GuestUser[];
115
+ logs: LogCoverage[];
116
+ audit: AuditCoverage;
117
+ limits: RunningUserLimits;
118
+ ipRangeFiles: string[];
119
+ /** Degraded reads while snapshotting guest configuration (optional: older bundles lack it). */
120
+ snapshotWarnings?: string[];
121
+ files: Record<string, string>;
122
+ }
123
+ export interface FollowUp {
124
+ logins: LoginRow[];
125
+ users: LinkedUser[];
126
+ /** True when a LoginHistory batch returned the queryAll cap, so some logins may be missing. */
127
+ truncated?: boolean;
128
+ }
129
+ export type ActionClass = 'data-access' | 'auth' | 'plumbing' | 'unknown';
130
+ export type Classification = 'internal-testing' | 'automated-scan' | 'organic' | 'indeterminate';
131
+ export type WaveOutcome = 'access-gained' | 'content-returned' | 'no-evidence' | 'not-assessed';
132
+ //# sourceMappingURL=model.d.ts.map
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Types shared by `sf audit incident collect` and `report`. The bundle on disk is the contract
3
+ * between the two commands: collect writes it, report only reads it.
4
+ */
5
+ export const LOG_TYPES = [
6
+ 'AuraRequest', 'Sites', 'URI', 'ApexExecution', 'VisualforceRequest', 'ContentTransfer',
7
+ 'GraphQlQueryExecution', 'UniqueQuery', 'LightningError', 'ApexUnexpectedException',
8
+ ];
9
+ /** Without these two, response sizes cannot be assessed, so a wave's result is `not-assessed`. */
10
+ export const REQUIRED_LOG_TYPES = ['AuraRequest', 'Sites'];
11
+ export const DEFAULTS = {
12
+ spikeRatio: 5,
13
+ emptyBandBytes: 64,
14
+ auditWindowDays: 4,
15
+ /** jsforce autoFetchQuery stops here; a window returning this many rows may be truncated. */
16
+ auditPageCap: 10000,
17
+ outlierFloor: 100,
18
+ outlierMultiple: 3,
19
+ /** An IP with logins from more distinct users than this is shared egress (proxy, NAT). */
20
+ sharedEgressUsers: 8,
21
+ };
22
+ export function id15(id) {
23
+ const t = (id ?? '').trim();
24
+ return t ? t.slice(0, 15) : undefined;
25
+ }
26
+ //# sourceMappingURL=model.js.map
@@ -0,0 +1,15 @@
1
+ import type { IncidentResult } from '../analyse/index.js';
2
+ export interface EvidenceTable {
3
+ id: string;
4
+ key: string;
5
+ title: string;
6
+ columns: string[];
7
+ rows: string[][];
8
+ }
9
+ /** Every number in the report cites one of these tables; ids are assigned in a fixed order. */
10
+ export declare function buildEvidence(r: IncidentResult): {
11
+ tables: EvidenceTable[];
12
+ ref(key: string): string;
13
+ };
14
+ export declare function writeEvidence(dir: string, tables: EvidenceTable[]): string[];
15
+ //# sourceMappingURL=evidence.d.ts.map
@@ -0,0 +1,52 @@
1
+ // src/incident/render/evidence.ts
2
+ import { mkdirSync, writeFileSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+ import { csvLine } from '../csv.js';
5
+ import { NOT_COLLECTED, auraCollectedDays, coveredDays } from './labels.js';
6
+ /** Every number in the report cites one of these tables; ids are assigned in a fixed order. */
7
+ export function buildEvidence(r) {
8
+ const raw = [];
9
+ const aura = auraCollectedDays(r.coverage.logs);
10
+ raw.push({ key: 'volumes', title: 'Guest controller calls and page loads per day', columns: ['day', 'guest', 'controller_calls', 'page_loads'],
11
+ rows: coveredDays(r.coverage.logs, r.volumes.map((v) => v.day)).flatMap((day) => (aura.has(day)
12
+ ? r.volumes.filter((v) => v.day === day).map((v) => [v.day, v.guestId15, String(v.controllerCalls), String(v.pageLoads)])
13
+ : [[day, '(all guests)', NOT_COLLECTED, NOT_COLLECTED]])) });
14
+ for (const w of r.waves) {
15
+ const id = w.wave.id;
16
+ raw.push({ key: `${id}:spike`, title: `${id} spike assessment`, columns: ['day', 'controller_calls', 'baseline_median', 'ratio', 'detector_sample'],
17
+ rows: w.spikes.map((s) => [s.day, s.controllerCalls === null ? NOT_COLLECTED : String(s.controllerCalls), String(s.baselineMedian ?? ''), s.ratio === null ? '' : s.ratio.toFixed(2), String(s.detectorSample ?? '')]) });
18
+ raw.push({ key: `${id}:actors`, title: `${id} actors`, columns: ['actor', 'block', 'ips', 'first_seen', 'last_seen', 'controller_calls', 'steady', 'empty_ua_share', 'markers', 'hosting'],
19
+ rows: w.actors.map((a) => [a.id, a.block, a.ips.join(' '), a.firstSeen, a.lastSeen, String(a.controllerCalls), String(a.steady), a.emptyUaShare.toFixed(2), a.markers.join(' '), a.hostingAssessed ? (a.hosting ?? 'none') : 'not assessed']) });
20
+ raw.push({ key: `${id}:actions`, title: `${id} actions invoked by actors`, columns: ['action', 'class', 'count'],
21
+ rows: w.actions.byName.map((x) => [x.name, x.cls, String(x.count)]) });
22
+ raw.push({ key: `${id}:returned`, title: `${id} data-access replies larger than the empty size`, columns: ['timestamp', 'request_id', 'ip', 'actor', 'size_bytes', 'actions'],
23
+ rows: w.responses.returnedContent.map((x) => [x.timestamp, x.requestId, x.ip, x.actorId || '(none isolated)', String(x.size), x.actions.join(' ')]) });
24
+ raw.push({ key: `${id}:logins`, title: `${id} logins from actor IPs (no date bound)`, columns: ['login_time', 'ip', 'user', 'status', 'actor'],
25
+ rows: w.outcomes.actorLogins.map((l) => [l.loginTime, l.sourceIp, l.userId15, l.status, l.actorId]) });
26
+ raw.push({ key: `${id}:selfreg`, title: `${id} self-registrations during the actor window (no IP recorded; listed for review)`, columns: ['created_date', 'created_by', 'display'],
27
+ rows: w.outcomes.selfRegistrationsInActorWindow.map((x) => [x.createdDate, x.createdBy, x.display]) });
28
+ raw.push({ key: `${id}:links`, title: `${id} identity links`, columns: ['ip', 'user', 'name', 'email', 'created', 'created_by', 'login_time'],
29
+ rows: w.outcomes.identityLinks.map((l) => [l.ip, l.userId15, l.userName, l.email, l.userCreatedDate, l.createdByGuest, l.loginTime]) });
30
+ }
31
+ raw.push({ key: 'config', title: 'Guest-access configuration changes by period and site', columns: ['period', 'site', 'at', 'by', 'section', 'change'],
32
+ rows: r.config.periods.flatMap((p) => [
33
+ ...Object.entries(p.bySite).flatMap(([site, cs]) => cs.map((c) => [p.label, site, c.at, c.by, c.section ?? '', c.display])),
34
+ ...p.shared.map((c) => [p.label, '(shared by several sites)', c.at, c.by, c.section ?? '', c.display]),
35
+ ]) });
36
+ raw.push({ key: 'coverage', title: 'Collection coverage', columns: ['type', 'day', 'status', 'total_rows', 'guest_rows', 'malformed', 'detail'],
37
+ rows: r.coverage.logs.map((l) => [l.type, l.day, l.status, String(l.totalRows), String(l.guestRows), String(l.malformed), l.detail ?? '']) });
38
+ const tables = raw.map((t, i) => ({ id: `E${i + 1}`, ...t }));
39
+ const byKey = new Map(tables.map((t) => [t.key, t.id]));
40
+ return { tables, ref: (key) => (byKey.has(key) ? `[${byKey.get(key)}]` : '') };
41
+ }
42
+ /** Spreadsheet formula-injection guard, applied to written files only (csvLine stays raw for the log filter). */
43
+ const neutralise = (c) => (/^[=+\-@\t\r]/.test(c) ? `'${c}` : c);
44
+ export function writeEvidence(dir, tables) {
45
+ mkdirSync(join(dir, 'evidence'), { recursive: true });
46
+ return tables.map((t) => {
47
+ const p = join(dir, 'evidence', `${t.id}.csv`);
48
+ writeFileSync(p, csvLine(t.columns.map(neutralise)) + t.rows.map((row) => csvLine(row.map(neutralise))).join(''));
49
+ return p;
50
+ });
51
+ }
52
+ //# sourceMappingURL=evidence.js.map
@@ -0,0 +1,7 @@
1
+ import { type Branding } from '@cclabsnz/sf-core';
2
+ import type { IncidentResult } from '../analyse/index.js';
3
+ import type { buildEvidence } from './evidence.js';
4
+ type Ev = ReturnType<typeof buildEvidence>;
5
+ export declare function renderHtml(r: IncidentResult, ev: Ev, b: Branding): string;
6
+ export {};
7
+ //# sourceMappingURL=html.d.ts.map
@@ -0,0 +1,144 @@
1
+ // src/incident/render/html.ts
2
+ import { esc, fontFaceCss } from '@cclabsnz/sf-core';
3
+ import { chartJsScript } from '../../renderers/chartAsset.js';
4
+ import { CLASSIFICATION_LABEL, RESULT_LABEL, auraCollectedDays, coveredDays } from './labels.js';
5
+ import { NOTHING_ASSESSED, WITHIN_BASELINE, reportLimits, waveSentence } from './markdown.js';
6
+ const RESULT_TONE = { 'access-gained': 'high', 'content-returned': 'medium', 'no-evidence': 'low', 'not-assessed': 'muted' };
7
+ function timelineData(r) {
8
+ const days = coveredDays(r.coverage.logs, r.volumes.map((v) => v.day));
9
+ const aura = auraCollectedDays(r.coverage.logs);
10
+ // null for a day whose AuraRequest log was not collected: Chart.js leaves a gap, never a zero.
11
+ const series = r.guests.filter((g) => r.volumes.some((v) => v.guestId15 === g.id15)).map((g) => ({
12
+ label: g.siteNames[0] ?? g.username,
13
+ data: days.map((d) => (aura.has(d) ? r.volumes.find((v) => v.guestId15 === g.id15 && v.day === d)?.controllerCalls ?? 0 : null)),
14
+ }));
15
+ return { days, series, waveDays: [...new Set(r.waves.flatMap((w) => w.wave.days))] };
16
+ }
17
+ const RESULT_ORDER = ['access-gained', 'content-returned', 'no-evidence', 'not-assessed'];
18
+ const CHART_COLOURS = ['#175cd3', '#b54708', '#067647', '#667085', '#0e7090'];
19
+ const n = (v) => v.toLocaleString('en-NZ');
20
+ const plural = (v, one, many = `${one}s`) => `${n(v)} ${v === 1 ? one : many}`;
21
+ const stamp = (iso) => iso.replace('T', ' ');
22
+ export function renderHtml(r, ev, b) {
23
+ const tally = RESULT_ORDER.map((k) => ({ k, count: r.waves.filter((w) => w.result === k).length }))
24
+ .filter((t) => t.count > 0)
25
+ .map((t) => `<span class="chip tone-${RESULT_TONE[t.k]}">${n(t.count)} ${esc(RESULT_LABEL[t.k] ?? t.k)}</span>`).join('');
26
+ const classes = [...new Set(r.waves.map((w) => w.classification))]
27
+ .map((c) => `${r.waves.filter((w) => w.classification === c).length} ${CLASSIFICATION_LABEL[c].toLowerCase()}`).join(' · ');
28
+ const scorecard = `<div class="scorecard"><div class="big">${n(r.waves.length)}</div>
29
+ <div><div class="label">${r.waves.length === 1 ? 'Wave of guest traffic examined' : 'Waves of guest traffic examined'}</div>
30
+ <div class="chips">${tally || '<span class="chip tone-muted">Nothing assessed</span>'}</div>
31
+ <p class="tally">${r.waves.length === 0 ? esc(NOTHING_ASSESSED) : classes ? esc(classes) : ''}</p></div></div>`;
32
+ const waves = r.waves.map((w) => `
33
+ <article class="wave tone-${RESULT_TONE[w.result]}">
34
+ <header><span class="wid">${esc(w.wave.id)}</span><h3>${esc(w.wave.site)}</h3><span class="days">${esc(w.wave.days.join(', '))}</span></header>
35
+ <div class="verdict"><div><span class="label">Classification</span><strong>${esc(CLASSIFICATION_LABEL[w.classification])}</strong></div>
36
+ <div><span class="label">Result</span><span class="chip solid tone-${RESULT_TONE[w.result]}">${esc(RESULT_LABEL[w.result])}</span></div></div>
37
+ <p class="evidence">${esc(waveSentence(w, ev))}</p>
38
+ </article>`).join('');
39
+ const limits = reportLimits(r).map((l) => `<li>${esc(l)}</li>`).join('');
40
+ const steps = [...new Set(r.waves.flatMap((w) => w.nextSteps))].map((s) => `<li>${esc(s)}</li>`).join('');
41
+ const detail = r.waves.map((w) => `
42
+ <div class="detail"><h3><span class="pnum">${esc(w.wave.id)}</span>${esc(w.wave.site)} · ${esc(w.wave.days.join(', '))}</h3>
43
+ <div class="tablewrap"><table class="grid"><thead><tr><th>Block</th><th>Active (UTC)</th><th class="n">Controller calls</th><th>Volume</th><th class="n">Empty UA</th><th>Markers</th><th>Hosting</th></tr></thead><tbody>
44
+ ${w.actors.map((a) => `<tr><td class="mono">${esc(a.block)} <small>(${plural(a.ips.length, 'IP')})</small></td><td>${esc(stamp(a.firstSeen.slice(0, 16)))} – ${esc(a.lastSeen.slice(11, 16))}</td><td class="n">${n(a.controllerCalls)}</td><td>${a.steady ? 'steady' : 'irregular'}</td><td class="n">${(a.emptyUaShare * 100).toFixed(0)}%</td><td>${esc(a.markers.join(', ') || '—')}</td><td>${esc(a.hostingAssessed ? (a.hosting ?? 'none matched') : 'not assessed')}</td></tr>`).join('') || '<tr><td colspan="7">No actor blocks above the outlier threshold.</td></tr>'}
45
+ </tbody></table></div><p class="ref">${esc(ev.ref(`${w.wave.id}:actors`))}</p>
46
+ <p>Actions by class: ${Object.entries(w.actions.byClass).map(([k, v]) => `${esc(k)} <b>${n(v)}</b>`).join(' · ')} <span class="ref">${esc(ev.ref(`${w.wave.id}:actions`))}</span></p>
47
+ <p>Self-registrations during the actor window: ${w.outcomes.selfRegistrationsInActorWindow.length ? `${n(w.outcomes.selfRegistrationsInActorWindow.length)}, listed for review; the audit trail records no IP, so they are not attributed` : 'none'} <span class="ref">${esc(ev.ref(`${w.wave.id}:selfreg`))}</span></p>
48
+ ${w.outcomes.selfRegistrationsInActorWindow.length ? `<ul>${w.outcomes.selfRegistrationsInActorWindow.map((x) => `<li><span class="mono">${esc(stamp(x.createdDate))}</span> ${esc(x.display)} <small>(by ${esc(x.createdBy)})</small></li>`).join('')}</ul>` : ''}
49
+ <p>Empty-reply size <b>${w.responses.emptySize === null || w.responses.emptySize === undefined ? 'unknown' : `${n(w.responses.emptySize)} bytes`}</b> (±${w.responses.band}${w.responses.emptySizeInferred ? ', inferred from the replies under test' : ''}); <b>${n(w.responses.returnedContent.length)}</b> of ${n(w.responses.dataAccessCalls)} data-access replies from any guest IP were larger <span class="ref">${esc(ev.ref(`${w.wave.id}:returned`))}</span>.</p>
50
+ </div>`).join('');
51
+ const config = r.config.periods.map((p) => `<tr><td>${esc(p.label)}</td><td>${Object.entries(p.bySite).map(([s, cs]) => `${esc(s)} <b>${cs.length}</b>`).join(', ') || 'none'}${p.shared.length ? ` <small>(${p.shared.length} shared, not counted per site)</small>` : ''}</td></tr>`).join('');
52
+ const asym = r.config.asymmetries.map((a) => `<p class="callout">${esc(a.site)} was hit again in ${esc(a.waveId)} after ${a.changes} change(s) in ${esc(a.period)}, while ${esc(a.comparedSite)} received ${a.comparedChanges}.</p>`).join('');
53
+ const coverage = r.coverage.logs.filter((l) => l.status !== 'collected').map((l) => `<tr><td>${esc(l.type)}</td><td>${esc(l.day)}</td><td>${esc(l.status)}</td></tr>`).join('');
54
+ const evidenceIndex = ev.tables.map((t) => `<li><b>${esc(t.id)}</b><span>${esc(t.title)} <small>(${plural(t.rows.length, 'row')})</small></span></li>`).join('');
55
+ const chart = JSON.stringify({ ...timelineData(r), colours: CHART_COLOURS, ink: b.ink, muted: b.muted, border: b.border, font: b.fontBody }).replace(/</g, '\\u003c');
56
+ const sec = (num, title) => `<div class="sh"><span class="sec-num">${num} /</span><h2>${title}</h2></div>`;
57
+ return `<!doctype html>
58
+ <html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Guest-access incident report: ${esc(r.orgName)}</title>
59
+ <style>${fontFaceCss()}
60
+ :root{--ink:${b.ink};--bg:${b.bg};--bgalt:${b.bgAlt};--muted:${b.muted};--border:${b.border};--primary:${b.primary};
61
+ --display:'${b.fontDisplay}',Georgia,serif;--body:'${b.fontBody}',system-ui,sans-serif;--mono:ui-monospace,'SF Mono',Menlo,monospace;
62
+ --high:#b42318;--medium:#b54708;--low:#067647;--unknown:#475467;}
63
+ *{box-sizing:border-box}
64
+ html{-webkit-print-color-adjust:exact;print-color-adjust:exact}
65
+ body{margin:0;background:var(--bg);color:var(--ink);font:15px/1.6 var(--body);font-variant-numeric:tabular-nums}
66
+ .wrap{max-width:860px;margin:0 auto;padding:64px 44px}
67
+ h1{font-family:var(--display);font-size:clamp(34px,6vw,52px);line-height:1.02;letter-spacing:-0.02em;margin:6px 0 0}
68
+ h2{font-family:var(--display);font-size:25px;letter-spacing:-0.01em;line-height:1.1;margin:0}
69
+ h3{font-family:var(--display);font-size:18px;letter-spacing:-0.01em;line-height:1.25;margin:0 0 6px}
70
+ p{margin:0 0 10px;max-width:70ch}
71
+ .label{font-family:var(--mono);text-transform:uppercase;letter-spacing:0.16em;font-size:11px;color:var(--muted)}
72
+ .meta{font-family:var(--mono);font-size:11px;letter-spacing:0.12em;color:var(--muted);text-transform:uppercase;margin-top:8px;line-height:1.7}
73
+ .muted{color:var(--muted)}small{color:var(--muted)}
74
+ .cover{padding-bottom:8px}
75
+ .scorecard{display:flex;align-items:center;gap:28px;margin:30px 0 8px;padding:22px 28px;background:var(--bgalt);border:1px solid var(--border);border-radius:12px;break-inside:avoid}
76
+ .big{font-family:var(--display);font-size:96px;line-height:0.86;font-weight:400}
77
+ .tally{margin:10px 0 0;font-size:13px;color:var(--muted)}
78
+ .scorecard>div{min-width:0}.chips{display:flex;flex-wrap:wrap;gap:6px;margin-top:10px}
79
+ .chip{--c:var(--unknown);font-family:var(--mono);font-size:11px;letter-spacing:0.04em;font-weight:600;color:var(--c);border:1px solid var(--c);border-radius:999px;padding:2px 9px}
80
+ .chip.solid{background:var(--c);color:#fff}
81
+ .chip.tone-high{--c:var(--high)}.chip.tone-medium{--c:var(--medium)}.chip.tone-low{--c:var(--low)}.chip.tone-muted{--c:var(--unknown)}
82
+ .sh{display:flex;align-items:baseline;gap:14px;margin:56px 0 18px;border-bottom:1px solid var(--border);padding-bottom:10px;break-after:avoid}
83
+ .sec-num{font-family:var(--mono);font-size:13px;letter-spacing:0.1em;color:var(--primary)}
84
+ .waves{display:grid;gap:12px;margin:18px 0 22px}
85
+ .wave{--c:var(--unknown);border:1px solid var(--border);border-left:4px solid var(--c);border-radius:8px;padding:14px 18px 6px;background:var(--bgalt)}
86
+ .tone-high{--c:var(--high)}.tone-medium{--c:var(--medium)}.tone-low{--c:var(--low)}
87
+ .wave header{display:flex;gap:10px;align-items:baseline;flex-wrap:wrap}.wave h3{margin:0}
88
+ .wid,.pnum{font-family:var(--mono);font-weight:600;font-size:12px;letter-spacing:0.05em;color:var(--primary);margin-right:10px}.wave .wid{margin:0;color:var(--muted)}
89
+ .days{margin-left:auto;font-family:var(--mono);font-size:12px;color:var(--muted)}
90
+ .verdict{display:flex;flex-wrap:wrap;gap:8px 40px;margin:12px 0 10px}.verdict .label{display:block;margin-bottom:3px}.verdict strong{display:block;font-weight:600}
91
+ .evidence{font-size:14px}
92
+ .limits{border:1px solid var(--border);border-left:4px solid var(--ink);border-radius:8px;padding:14px 20px 6px;background:var(--bg)}
93
+ .limits ul{padding-left:18px;margin:8px 0 10px}.limits li{margin-bottom:5px;max-width:70ch}
94
+ .steps{margin:28px 0 0}.steps h3{margin-bottom:8px}.steps ol{padding-left:22px;margin:0}.steps li{margin-bottom:5px;max-width:70ch}
95
+ .tablewrap{overflow-x:auto;-webkit-overflow-scrolling:touch}
96
+ table{width:100%;border-collapse:collapse;font-size:13px;margin:8px 0}
97
+ th{text-align:left;font-family:var(--mono);text-transform:uppercase;letter-spacing:0.05em;font-size:10px;font-weight:400;color:var(--muted);border-bottom:1px solid var(--border);padding:6px 14px 6px 0;vertical-align:bottom;line-height:1.3}
98
+ td{padding:7px 14px 7px 0;border-bottom:1px solid var(--border);vertical-align:top}
99
+ th.n,td.n{text-align:right}td.n{font-variant-numeric:tabular-nums}td.mono{font-family:var(--mono);font-size:12px;white-space:nowrap}
100
+ .grid{font-size:12.5px}.grid td:nth-child(2){min-width:9em}
101
+ .detail{margin:0 0 30px}.detail h3{font-size:16px}
102
+ .ref{color:var(--muted);font:12px var(--mono)}
103
+ .callout{border-left:3px solid var(--medium);padding:8px 14px;background:var(--bgalt);border-radius:0 6px 6px 0}
104
+ .key{display:inline-block;width:12px;height:12px;background:rgba(181,71,8,0.18);border:1px solid rgba(181,71,8,0.5);vertical-align:-1px;margin-right:4px}
105
+ .chartbox{position:relative;border:1px solid var(--border);border-radius:8px;padding:12px;background:var(--bgalt);break-inside:avoid}
106
+ .chartbox canvas{display:block;width:100%}
107
+ .method{padding-left:18px}.method li{margin-bottom:4px;max-width:70ch}
108
+ .index{list-style:none;margin:8px 0 0;padding:0;columns:2;column-gap:32px;font-size:13px}
109
+ .index li{display:flex;gap:10px;padding:4px 0;border-bottom:1px solid var(--border);break-inside:avoid}.index b{font-family:var(--mono);font-size:12px;color:var(--primary);min-width:34px;font-weight:600}
110
+ code{font-family:var(--mono);font-size:12px;word-break:break-all;text-transform:none;letter-spacing:0}
111
+ @media(max-width:600px){.wrap{padding:36px 18px}.scorecard{flex-direction:column;align-items:flex-start;gap:12px}.big{font-size:72px}.days{margin-left:0;flex-basis:100%}.index{columns:1}}
112
+ @page{margin:18mm}
113
+ @media print{.wrap{padding:0 0 24px;max-width:none}.sh{margin-top:36px}.wave,.detail,.limits,.scorecard{break-inside:avoid}.tablewrap{overflow:visible}}
114
+ </style></head><body><div class="wrap">
115
+ <header class="cover"><div class="label">${esc(b.firmName)}</div><h1>Guest-access incident report</h1>
116
+ <div class="meta">${esc(r.orgName)} · collected ${esc(stamp(r.collectedAt))}${b.preparedFor ? ` · prepared for ${esc(b.preparedFor)}` : ''}</div>
117
+ ${scorecard}</header>
118
+ <section id="summary">${sec('01', 'Summary')}
119
+ ${r.waves.length === 0 ? `<p>${esc(NOTHING_ASSESSED)}</p>` : r.withinBaseline ? `<p>${esc(WITHIN_BASELINE)}</p>` : ''}
120
+ <div class="waves">${waves}</div>
121
+ <div class="limits"><h3>What this report can't tell you</h3><ul>${limits}</ul></div>
122
+ <div class="steps"><h3>Recommended next steps</h3><ol>${steps}</ol></div></section>
123
+ <section id="timeline">${sec('02', 'Timeline')}<p>Guest controller calls per day, one line per site. <span class="key"></span>Shaded days are the wave days. A gap in a line is a day whose AuraRequest log was not collected. ${esc(ev.ref('volumes'))}</p><div class="chartbox"><canvas id="tl" height="130" role="img" aria-label="Guest controller calls per day, by site">Chart needs JavaScript. The daily counts are in the volumes evidence table.</canvas></div></section>
124
+ <section id="detail">${sec('03', 'Wave detail')}${detail}</section>
125
+ <section id="config">${sec('04', 'Configuration changes')}<div class="tablewrap"><table><thead><tr><th>Period</th><th>Changes by site</th></tr></thead><tbody>${config}</tbody></table></div>${asym}<p class="ref">${esc(ev.ref('config'))}</p></section>
126
+ <section id="method">${sec('05', 'Method and evidence')}
127
+ <ul class="method"><li>The primary measure is AuraRequest rows carrying a controller action; page loads are counted separately.</li>
128
+ <li>Other event types record the same traffic at different layers. They corroborate and are never added together.</li>
129
+ <li>The anomaly detector's TotalControllerEvents is its own sample and is not compared with log counts.</li>
130
+ <li>Reply sizes come from the Sites log, reduced to one row per request id before joining. Bodies are never logged.</li></ul>
131
+ ${coverage ? `<h3>Gaps in collection</h3><div class="tablewrap"><table><thead><tr><th>Type</th><th>Day</th><th>Status</th></tr></thead><tbody>${coverage}</tbody></table></div>` : ''}
132
+ <p class="meta">Bundle manifest sha256 <code>${esc(r.manifestSha256)}</code></p>
133
+ <h3>Evidence index</h3><ul class="index">${evidenceIndex}</ul></section>
134
+ </div>
135
+ <script>${chartJsScript()}</script>
136
+ <script>(function(){var d=${chart};var c=document.getElementById('tl');if(!c||!window.Chart)return;
137
+ Chart.defaults.font.family="'"+d.font+"',system-ui,sans-serif";Chart.defaults.color=d.muted;
138
+ var shade={id:'shade',beforeDraw:function(ch){var x=ch.scales.x,a=ch.chartArea,ctx=ch.ctx;ctx.save();ctx.fillStyle='rgba(181,71,8,0.12)';
139
+ d.days.forEach(function(day,i){if(d.waveDays.indexOf(day)<0)return;var w=x.getPixelForValue(1)-x.getPixelForValue(0);ctx.fillRect(x.getPixelForValue(i)-w/2,a.top,w,a.bottom-a.top);});ctx.restore();}};
140
+ new Chart(c,{type:'line',data:{labels:d.days,datasets:d.series.map(function(s,i){var col=d.colours[i%d.colours.length];return{label:s.label,data:s.data,tension:0.2,pointRadius:3,borderWidth:2,borderColor:col,backgroundColor:col};})},
141
+ options:{animation:false,responsive:true,plugins:{legend:{position:'bottom',labels:{usePointStyle:true,boxWidth:8}}},scales:{y:{beginAtZero:true,grid:{color:d.border},title:{display:true,text:'Controller calls'}},x:{grid:{display:false}}}},plugins:[shade]});})();</script>
142
+ </body></html>`;
143
+ }
144
+ //# sourceMappingURL=html.js.map
@@ -0,0 +1,9 @@
1
+ import type { Classification, LogCoverage, WaveOutcome } from '../model.js';
2
+ export declare const CLASSIFICATION_LABEL: Record<Classification, string>;
3
+ export declare const RESULT_LABEL: Record<WaveOutcome, string>;
4
+ export declare const NOT_COLLECTED = "not collected";
5
+ /** Days whose AuraRequest log was collected. Any other day's counts are unknown, never zero. */
6
+ export declare function auraCollectedDays(logs: LogCoverage[]): Set<string>;
7
+ /** Every day the bundle covers, collected or not, ascending. */
8
+ export declare function coveredDays(logs: LogCoverage[], extra?: string[]): string[];
9
+ //# sourceMappingURL=labels.d.ts.map
@@ -0,0 +1,22 @@
1
+ export const CLASSIFICATION_LABEL = {
2
+ 'internal-testing': 'Consistent with internal testing',
3
+ 'automated-scan': 'Unattributed automated scan',
4
+ organic: 'Organic spike',
5
+ indeterminate: 'Indeterminate',
6
+ };
7
+ export const RESULT_LABEL = {
8
+ 'access-gained': 'Access gained',
9
+ 'content-returned': 'Content returned, contents unknown',
10
+ 'no-evidence': 'No evidence of access',
11
+ 'not-assessed': 'Not assessed',
12
+ };
13
+ export const NOT_COLLECTED = 'not collected';
14
+ /** Days whose AuraRequest log was collected. Any other day's counts are unknown, never zero. */
15
+ export function auraCollectedDays(logs) {
16
+ return new Set(logs.filter((l) => l.type === 'AuraRequest' && l.status === 'collected').map((l) => l.day));
17
+ }
18
+ /** Every day the bundle covers, collected or not, ascending. */
19
+ export function coveredDays(logs, extra = []) {
20
+ return [...new Set([...logs.map((l) => l.day), ...extra])].sort();
21
+ }
22
+ //# sourceMappingURL=labels.js.map
@@ -0,0 +1,17 @@
1
+ import type { IncidentResult } from '../analyse/index.js';
2
+ import type { buildEvidence } from './evidence.js';
3
+ type Ev = ReturnType<typeof buildEvidence>;
4
+ /** Makes an org-sourced value safe to interpolate into Markdown (tables, headings, raw HTML). */
5
+ export declare const md: (s: string) => string;
6
+ export declare const NOTHING_ASSESSED = "No Guest User Anomaly waves were found in the collected period, so nothing was assessed.";
7
+ export declare const WITHIN_BASELINE = "Guest traffic stayed within baseline on every collected day.";
8
+ /**
9
+ * The "What this report can't tell you" box: org-wide limits plus every wave's, deduplicated.
10
+ * A wave limit that does not hold for every wave names the waves it applies to, so a caveat on
11
+ * one wave never reads as a caveat on another.
12
+ */
13
+ export declare function reportLimits(r: IncidentResult): string[];
14
+ export declare function waveSentence(w: IncidentResult['waves'][number], ev: Ev): string;
15
+ export declare function renderMarkdown(r: IncidentResult, ev: Ev): string;
16
+ export {};
17
+ //# sourceMappingURL=markdown.d.ts.map
@@ -0,0 +1,91 @@
1
+ import { CLASSIFICATION_LABEL, NOT_COLLECTED, RESULT_LABEL, auraCollectedDays, coveredDays } from './labels.js';
2
+ /** Makes an org-sourced value safe to interpolate into Markdown (tables, headings, raw HTML). */
3
+ export const md = (s) => s.replace(/\\/g, '\\\\').replace(/\r?\n/g, ' ').replace(/\|/g, '\\|').replace(/</g, '&lt;');
4
+ export const NOTHING_ASSESSED = 'No Guest User Anomaly waves were found in the collected period, so nothing was assessed.';
5
+ export const WITHIN_BASELINE = 'Guest traffic stayed within baseline on every collected day.';
6
+ /**
7
+ * The "What this report can't tell you" box: org-wide limits plus every wave's, deduplicated.
8
+ * A wave limit that does not hold for every wave names the waves it applies to, so a caveat on
9
+ * one wave never reads as a caveat on another.
10
+ */
11
+ export function reportLimits(r) {
12
+ const waveIds = new Map();
13
+ for (const w of r.waves)
14
+ for (const l of new Set(w.limits))
15
+ waveIds.set(l, [...(waveIds.get(l) ?? []), w.wave.id]);
16
+ const perWave = [...waveIds.entries()].map(([l, ids]) => (ids.length === r.waves.length ? l : `${ids.join(', ')}: ${l}`));
17
+ return [...new Set([...r.globalLimits, ...perWave])];
18
+ }
19
+ export function waveSentence(w, ev) {
20
+ const id = w.wave.id;
21
+ const spike = w.spikes.find((s) => s.isSpike);
22
+ const parts = [];
23
+ if (spike) {
24
+ const calls = `${(spike.controllerCalls ?? 0).toLocaleString('en-NZ')} guest controller calls on ${spike.day}`;
25
+ // A zero baseline median has no ratio: say so rather than dereferencing it.
26
+ parts.push(spike.ratio === null ? `${calls} against a zero baseline ${ev.ref(`${id}:spike`)}` : `${calls}, ${spike.ratio.toFixed(1)}× baseline ${ev.ref(`${id}:spike`)}`);
27
+ }
28
+ if (w.actors.length)
29
+ parts.push(`${w.actors.length} actor block(s), led by ${md(w.actors[0].block)} ${ev.ref(`${id}:actors`)}`);
30
+ parts.push(`${w.outcomes.successfulLogins} successful login(s) from actor IPs ${ev.ref(`${id}:logins`)}`);
31
+ parts.push(`${w.responses.returnedContent.length} of ${w.responses.dataAccessCalls} data-access replies larger than empty ${ev.ref(`${id}:returned`)}`);
32
+ if (w.outcomes.identityLinks.length)
33
+ parts.push(`actor IP later signed in as a user created through a guest site ${ev.ref(`${id}:links`)}`);
34
+ return parts.join('; ') + '.';
35
+ }
36
+ export function renderMarkdown(r, ev) {
37
+ const L = [];
38
+ L.push(`# Guest-access incident report: ${md(r.orgName)}`, '', `Collected ${r.collectedAt}. Bundle manifest sha256 \`${r.manifestSha256}\`.`, '');
39
+ L.push('## Summary', '');
40
+ if (r.waves.length === 0)
41
+ L.push(NOTHING_ASSESSED, '');
42
+ else if (r.withinBaseline)
43
+ L.push(WITHIN_BASELINE, '');
44
+ for (const w of r.waves) {
45
+ L.push(`### ${w.wave.id}: ${md(w.wave.site)}, ${w.wave.days.join(', ')}`, '', `- **Classification:** ${CLASSIFICATION_LABEL[w.classification]}`, `- **Result:** ${RESULT_LABEL[w.result]}`, `- **Evidence:** ${waveSentence(w, ev)}`, '');
46
+ }
47
+ L.push("### What this report can't tell you", '');
48
+ for (const l of reportLimits(r))
49
+ L.push(`- ${md(l)}`);
50
+ L.push('', '### Recommended next steps', '');
51
+ for (const s of new Set(r.waves.flatMap((w) => w.nextSteps)))
52
+ L.push(`- ${md(s)}`);
53
+ L.push('', '## Timeline', '', `Controller calls per guest user per day ${ev.ref('volumes')}.`, '', '| Day | Guest | Controller calls | Page loads |', '|---|---|---:|---:|');
54
+ const aura = auraCollectedDays(r.coverage.logs);
55
+ for (const day of coveredDays(r.coverage.logs, r.volumes.map((v) => v.day))) {
56
+ if (!aura.has(day)) {
57
+ L.push(`| ${day} | all guests | ${NOT_COLLECTED} | ${NOT_COLLECTED} |`);
58
+ continue;
59
+ }
60
+ for (const v of r.volumes.filter((x) => x.day === day))
61
+ L.push(`| ${v.day} | ${md(r.guests.find((g) => g.id15 === v.guestId15)?.siteNames[0] ?? v.guestId15)} | ${v.controllerCalls} | ${v.pageLoads} |`);
62
+ }
63
+ for (const w of r.waves) {
64
+ L.push('', `## ${w.wave.id} detail`, '', `Actors ${ev.ref(`${w.wave.id}:actors`)}:`, '');
65
+ for (const a of w.actors)
66
+ L.push(`- ${md(a.block)} (${a.ips.length} IPs), ${a.firstSeen} to ${a.lastSeen}, ${a.controllerCalls} controller calls, ${a.steady ? 'steady' : 'irregular'} volume, ${(a.emptyUaShare * 100).toFixed(0)}% empty user agent${a.markers.length ? `, scanner markers: ${md(a.markers.join(', '))}` : ''}${a.hostingAssessed ? `, hosting: ${md(a.hosting ?? 'none matched')}` : ''}.`);
67
+ const regs = w.outcomes.selfRegistrationsInActorWindow;
68
+ L.push('', `Self-registrations during the actor window ${ev.ref(`${w.wave.id}:selfreg`)}: ${regs.length ? 'the audit trail records no IP, so these are listed for review, not attributed.' : 'none.'}`);
69
+ if (regs.length)
70
+ L.push('', ...regs.map((x) => `- ${x.createdDate}: ${md(x.display)} (by ${md(x.createdBy)})`));
71
+ L.push('', `Actions by class ${ev.ref(`${w.wave.id}:actions`)}: ${Object.entries(w.actions.byClass).map(([k, v]) => `${k} ${v}`).join(', ')}.`);
72
+ L.push(`Empty-reply size ${w.responses.emptySize ?? 'unknown'} bytes (±${w.responses.band}${w.responses.emptySizeInferred ? ', inferred from the replies under test' : ''}); ${w.responses.returnedContent.length} of ${w.responses.dataAccessCalls} data-access replies from any guest IP were larger ${ev.ref(`${w.wave.id}:returned`)}.`);
73
+ }
74
+ L.push('', '## Configuration changes', '', `${ev.ref('config')}`, '');
75
+ for (const p of r.config.periods)
76
+ L.push(`- **${md(p.label)}:** ${Object.entries(p.bySite).map(([s, cs]) => `${md(s)} ${cs.length}`).join(', ') || 'none'}${p.shared.length ? `; ${p.shared.length} change(s) to labels shared by several sites, not counted per site` : ''}`);
77
+ for (const a of r.config.asymmetries)
78
+ L.push(`- ${md(a.site)} was hit again in ${a.waveId} after ${a.changes} change(s) in ${md(a.period)}, while ${md(a.comparedSite)} received ${a.comparedChanges}.`);
79
+ L.push('', '## Method', '', '- The primary measure is AuraRequest rows that carry a controller action. Page loads are counted separately.', '- Other event types record the same traffic at different layers; they corroborate and are never added together.', '- The anomaly detector\'s TotalControllerEvents is its own sample and is not compared with log counts.', '- Reply sizes come from the Sites log, reduced to one row per request id before joining. Bodies are never logged.', '', '### Gaps in collection', '');
80
+ const gaps = r.coverage.logs.filter((l) => l.status !== 'collected');
81
+ if (gaps.length)
82
+ for (const g of gaps)
83
+ L.push(`- ${md(g.type)} ${g.day} ${g.status}`);
84
+ else
85
+ L.push('None');
86
+ L.push('', '## Evidence index', '');
87
+ for (const t of ev.tables)
88
+ L.push(`- **${t.id}** ${t.title} (${t.rows.length} rows)`);
89
+ return L.join('\n') + '\n';
90
+ }
91
+ //# sourceMappingURL=markdown.js.map
@@ -0,0 +1,7 @@
1
+ import type { IncidentResult } from '../analyse/index.js';
2
+ /**
3
+ * For sharing beyond the immediate security team: linked users become their ids, IPs become
4
+ * /24 (or /64), and self-registrants' names (members of the public) are removed.
5
+ */
6
+ export declare function redactResult(r: IncidentResult): IncidentResult;
7
+ //# sourceMappingURL=redact.d.ts.map
@@ -0,0 +1,62 @@
1
+ import { replaceInsensitive } from '../text.js';
2
+ import { blockOf } from '../analyse/actors.js';
3
+ const truncateIp = (ip) => blockOf(ip);
4
+ // Any IPv4, including when followed by '/'; text that is already an x.y.z.0/24 block is left alone.
5
+ const IPV4 = /\b(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})\b(?!\.\d)(\/\d{1,2})?/g;
6
+ const IPV6 = /\b(?:[0-9a-f]{0,4}:){2,7}[0-9a-f]{0,4}\b(?:::\/64)?/gi;
7
+ const EMAIL = /[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g;
8
+ /**
9
+ * Every linked user's name and email, mapped to their id. Collected before anything is changed,
10
+ * so the names can be removed from every string (next steps, limits, display text), not just the
11
+ * identity-link fields. Names under 3 characters are ignored: they would erase ordinary words.
12
+ */
13
+ function linkedIdentities(r) {
14
+ const pairs = new Map();
15
+ for (const w of r.waves) {
16
+ for (const l of w.outcomes.identityLinks) {
17
+ for (const v of [l.userName, l.email]) {
18
+ const t = (v ?? '').trim();
19
+ if (t.length >= 3 && t !== l.userId15)
20
+ pairs.set(t.toLowerCase(), l.userId15);
21
+ }
22
+ }
23
+ }
24
+ return [...pairs.entries()]
25
+ .sort((a, c) => c[0].length - a[0].length)
26
+ .map(([v, id]) => ({ value: v, id }));
27
+ }
28
+ /**
29
+ * For sharing beyond the immediate security team: linked users become their ids, IPs become
30
+ * /24 (or /64), and self-registrants' names (members of the public) are removed.
31
+ */
32
+ export function redactResult(r) {
33
+ const identities = linkedIdentities(r);
34
+ const c = structuredClone(r);
35
+ for (const w of c.waves) {
36
+ for (const a of w.actors)
37
+ a.ips = [...new Set(a.ips.map(truncateIp))];
38
+ for (const l of w.outcomes.actorLogins)
39
+ l.sourceIp = truncateIp(l.sourceIp);
40
+ for (const l of w.outcomes.identityLinks) {
41
+ l.ip = truncateIp(l.ip);
42
+ l.userName = l.userId15;
43
+ l.email = l.userId15;
44
+ }
45
+ for (const x of w.responses.returnedContent)
46
+ x.ip = truncateIp(x.ip);
47
+ for (const s of w.outcomes.selfRegistrationsInActorWindow)
48
+ s.display = 'Created new Customer User [redacted]';
49
+ }
50
+ const unname = (s) => identities.reduce((acc, { value, id }) => replaceInsensitive(acc, value, id), s);
51
+ const scrub = (s) => unname(s)
52
+ .replace(EMAIL, '[email]')
53
+ .replace(IPV4, (m, ip, mask) => (ip.endsWith('.0') && mask === '/24' ? m : blockOf(ip)))
54
+ .replace(IPV6, (m) => {
55
+ if (m.endsWith('::/64'))
56
+ return m;
57
+ const groups = m.split(':').length;
58
+ return groups >= 3 && (m.includes('::') || /[a-f]/i.test(m)) ? blockOf(m) : m;
59
+ });
60
+ return JSON.parse(JSON.stringify(c), (_k, v) => (typeof v === 'string' ? scrub(v) : v));
61
+ }
62
+ //# sourceMappingURL=redact.js.map
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Plain-string matching for values that come from the org (site labels, user names). Built
3
+ * without RegExp so no org-controlled text ever becomes a pattern.
4
+ */
5
+ /** True when `needle` occurs in `text` bounded by non-alphanumerics or the string edges. */
6
+ export declare function containsWord(text: string, needle: string): boolean;
7
+ /** Replaces every case-insensitive occurrence of `needle` in `text` with `replacement`. */
8
+ export declare function replaceInsensitive(text: string, needle: string, replacement: string): string;
9
+ //# sourceMappingURL=text.d.ts.map