@cclabsnz/sf-audit 1.6.1 → 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.
Files changed (198) hide show
  1. package/README.md +258 -5
  2. package/lib/apps/analyzeApps.d.ts +1 -1
  3. package/lib/apps/appResolver.d.ts +1 -1
  4. package/lib/apps/grantedAccess.d.ts +1 -1
  5. package/lib/chains/AttackChain.d.ts +1 -1
  6. package/lib/chains/namedChains.d.ts +1 -1
  7. package/lib/checks/CheckEngine.d.ts +1 -1
  8. package/lib/checks/SecurityCheck.d.ts +3 -3
  9. package/lib/checks/impl/AgentActionSurfaceCheck.d.ts +1 -1
  10. package/lib/checks/impl/AgentActionSurfaceCheck.js +1 -1
  11. package/lib/checks/impl/AgentChannelExposureCheck.d.ts +1 -1
  12. package/lib/checks/impl/AgentInventoryCheck.d.ts +1 -1
  13. package/lib/checks/impl/AgentInventoryCheck.js +1 -1
  14. package/lib/checks/impl/AgentMonitoringCoverageCheck.d.ts +1 -1
  15. package/lib/checks/impl/AgentUserPrivilegeCheck.d.ts +1 -1
  16. package/lib/checks/impl/AnonymousApexAuditCheck.d.ts +1 -1
  17. package/lib/checks/impl/ApexCrudFLSCheck.d.ts +1 -1
  18. package/lib/checks/impl/ApexLoggingCheck.d.ts +1 -1
  19. package/lib/checks/impl/ApexRestEndpointCheck.d.ts +1 -1
  20. package/lib/checks/impl/ApexSharingCheck.d.ts +1 -1
  21. package/lib/checks/impl/ApexSharingCheck.js +3 -2
  22. package/lib/checks/impl/ApiClientPermissionCheck.d.ts +1 -1
  23. package/lib/checks/impl/ApiLimitsCheck.d.ts +1 -1
  24. package/lib/checks/impl/AuditTrailCheck.d.ts +1 -1
  25. package/lib/checks/impl/AuthProvidersCheck.d.ts +1 -1
  26. package/lib/checks/impl/CertificateExpiryCheck.d.ts +1 -1
  27. package/lib/checks/impl/ClassicSitesCheck.d.ts +1 -1
  28. package/lib/checks/impl/CodeSecurityCheck.d.ts +1 -1
  29. package/lib/checks/impl/CodeSecurityCheck.js +5 -5
  30. package/lib/checks/impl/ConnectedAppInactivityCheck.d.ts +1 -1
  31. package/lib/checks/impl/ConnectedAppScopeCheck.d.ts +1 -1
  32. package/lib/checks/impl/ConnectedAppsCheck.d.ts +1 -1
  33. package/lib/checks/impl/ContentLinksCheck.d.ts +1 -1
  34. package/lib/checks/impl/CorsAllowlistCheck.d.ts +1 -1
  35. package/lib/checks/impl/CspTrustedSitesCheck.d.ts +1 -1
  36. package/lib/checks/impl/CustomLabelsCredentialCheck.d.ts +1 -1
  37. package/lib/checks/impl/CustomSettingsCheck.d.ts +1 -1
  38. package/lib/checks/impl/DataClassificationCheck.d.ts +1 -1
  39. package/lib/checks/impl/DataExportAccessCheck.d.ts +1 -1
  40. package/lib/checks/impl/DebugLogAccessCheck.d.ts +1 -1
  41. package/lib/checks/impl/DeploymentIdentityCheck.d.ts +1 -1
  42. package/lib/checks/impl/EmailSecurityCheck.d.ts +1 -1
  43. package/lib/checks/impl/EncryptionCoverageCheck.d.ts +1 -1
  44. package/lib/checks/impl/EnhancedDomainsCheck.d.ts +1 -1
  45. package/lib/checks/impl/EnhancedDomainsCheck.js +2 -2
  46. package/lib/checks/impl/EscalationPermsCheck.d.ts +1 -1
  47. package/lib/checks/impl/EventMonitoringCheck.d.ts +1 -1
  48. package/lib/checks/impl/EventMonitoringCheck.js +1 -1
  49. package/lib/checks/impl/ExperienceCloudSiteCheck.d.ts +1 -1
  50. package/lib/checks/impl/ExperienceCspCheck.d.ts +1 -1
  51. package/lib/checks/impl/ExternalCredentialsCheck.d.ts +1 -1
  52. package/lib/checks/impl/FailedLoginCheck.d.ts +1 -1
  53. package/lib/checks/impl/FieldHistoryTrackingCheck.d.ts +1 -1
  54. package/lib/checks/impl/FieldLevelSecurityCheck.d.ts +1 -1
  55. package/lib/checks/impl/FlowsWithoutSharingCheck.d.ts +1 -1
  56. package/lib/checks/impl/FlowsWithoutSharingCheck.js +10 -9
  57. package/lib/checks/impl/GuestApiAccessCheck.d.ts +1 -1
  58. package/lib/checks/impl/GuestExecutableApexCheck.d.ts +1 -1
  59. package/lib/checks/impl/GuestExecutableApexCheck.js +4 -3
  60. package/lib/checks/impl/GuestObjectExposureCheck.d.ts +1 -1
  61. package/lib/checks/impl/GuestRecordAccessPolicyCheck.d.ts +1 -1
  62. package/lib/checks/impl/GuestSiteOptionsCheck.d.ts +1 -1
  63. package/lib/checks/impl/GuestTrafficAnomalyCheck.d.ts +1 -1
  64. package/lib/checks/impl/GuestTrafficAnomalyCheck.js +1 -1
  65. package/lib/checks/impl/GuestUserAccessCheck.d.ts +1 -1
  66. package/lib/checks/impl/HardcodedCredentialsCheck.d.ts +1 -1
  67. package/lib/checks/impl/HardcodedCredentialsCheck.js +8 -1
  68. package/lib/checks/impl/HealthCheckCheck.d.ts +1 -1
  69. package/lib/checks/impl/HighAssuranceSessionCheck.d.ts +1 -1
  70. package/lib/checks/impl/InactiveUsersCheck.d.ts +1 -1
  71. package/lib/checks/impl/InstalledPackagesCheck.d.ts +1 -1
  72. package/lib/checks/impl/IntegrationUsersCheck.d.ts +1 -1
  73. package/lib/checks/impl/InternalUserMfaCheck.d.ts +1 -1
  74. package/lib/checks/impl/IpRestrictionsCheck.d.ts +1 -1
  75. package/lib/checks/impl/LegacyApiVersionCheck.d.ts +1 -1
  76. package/lib/checks/impl/LoginAccessPolicyCheck.d.ts +1 -1
  77. package/lib/checks/impl/LoginAnomalyCheck.d.ts +1 -1
  78. package/lib/checks/impl/LoginSessionCheck.d.ts +1 -1
  79. package/lib/checks/impl/MfaEnforcementCheck.d.ts +1 -1
  80. package/lib/checks/impl/MfaMethodStrengthCheck.d.ts +1 -1
  81. package/lib/checks/impl/MfaRegistrationCheck.d.ts +1 -1
  82. package/lib/checks/impl/MyDomainLoginPolicyCheck.d.ts +1 -1
  83. package/lib/checks/impl/NamedCredentialsCheck.d.ts +1 -1
  84. package/lib/checks/impl/NamedCredentialsCheck.js +13 -9
  85. package/lib/checks/impl/OutboundMessagesCheck.d.ts +1 -1
  86. package/lib/checks/impl/PasswordSessionPolicyCheck.d.ts +2 -2
  87. package/lib/checks/impl/PermissionsCheck.d.ts +1 -1
  88. package/lib/checks/impl/PrivilegedAccessCheck.d.ts +1 -1
  89. package/lib/checks/impl/PublicContentExposureCheck.d.ts +1 -1
  90. package/lib/checks/impl/PublicGroupSharingCheck.d.ts +1 -1
  91. package/lib/checks/impl/ReleaseUpdatesCheck.d.ts +1 -1
  92. package/lib/checks/impl/RemoteSitesCheck.d.ts +1 -1
  93. package/lib/checks/impl/ReportFolderAccessCheck.d.ts +1 -1
  94. package/lib/checks/impl/SandboxDataMaskingCheck.d.ts +1 -1
  95. package/lib/checks/impl/ScheduledApexCheck.d.ts +1 -1
  96. package/lib/checks/impl/SeparationOfDutiesCheck.d.ts +1 -1
  97. package/lib/checks/impl/SessionHardeningCheck.d.ts +1 -1
  98. package/lib/checks/impl/SharingModelCheck.d.ts +1 -1
  99. package/lib/checks/impl/SiemIntegrationCheck.d.ts +1 -1
  100. package/lib/checks/impl/SsoEnforcementCheck.d.ts +1 -1
  101. package/lib/checks/impl/StandardProfilesCheck.d.ts +1 -1
  102. package/lib/checks/impl/ThreatDetectionCheck.d.ts +1 -1
  103. package/lib/checks/impl/TransactionSecurityPolicyCheck.d.ts +1 -1
  104. package/lib/checks/impl/TrustedIPRangesCheck.d.ts +1 -1
  105. package/lib/checks/impl/TrustedUrlHygieneCheck.d.ts +1 -1
  106. package/lib/checks/impl/UsersAndAdminsCheck.d.ts +1 -1
  107. package/lib/checks/impl/VisualforceXssCheck.d.ts +1 -1
  108. package/lib/commands/audit/events/pull.d.ts +1 -1
  109. package/lib/commands/audit/events/pull.js +3 -3
  110. package/lib/commands/audit/security.js +3 -1
  111. package/lib/commands/audit/timeline.d.ts +26 -0
  112. package/lib/commands/audit/timeline.js +189 -0
  113. package/lib/findings/AuditResult.d.ts +1 -1
  114. package/lib/findings/Finding.d.ts +1 -1
  115. package/lib/findings/ScoringConfig.d.ts +9 -217
  116. package/lib/findings/scoring.d.ts +2 -2
  117. package/lib/findings/scoring.js +1 -1
  118. package/lib/history/AuditDiff.d.ts +1 -1
  119. package/lib/history/metricMeta.d.ts +1 -1
  120. package/lib/index.d.ts +2 -2
  121. package/lib/lib/apexRefs.d.ts +2 -0
  122. package/lib/lib/apexRefs.js +30 -0
  123. package/lib/lib/wire.d.ts +6 -6
  124. package/lib/lib/wire.js +4 -4
  125. package/lib/renderers/ClientReportRenderer.d.ts +1 -1
  126. package/lib/renderers/ClientReportRenderer.js +6 -3
  127. package/lib/renderers/HistoryRenderer.js +2 -1
  128. package/lib/renderers/HtmlRenderer.js +3 -4
  129. package/lib/renderers/MarkdownRenderer.js +1 -1
  130. package/lib/renderers/chartAsset.d.ts +12 -0
  131. package/lib/renderers/chartAsset.js +25 -0
  132. package/lib/timeline/CaptureIndex.d.ts +34 -0
  133. package/lib/timeline/CaptureIndex.js +82 -0
  134. package/lib/timeline/CardinalityIndex.d.ts +28 -0
  135. package/lib/timeline/CardinalityIndex.js +47 -0
  136. package/lib/timeline/CorrelationEngine.d.ts +65 -0
  137. package/lib/timeline/CorrelationEngine.js +0 -0
  138. package/lib/timeline/EventRow.d.ts +69 -0
  139. package/lib/timeline/EventRow.js +14 -0
  140. package/lib/timeline/JoinKeys.d.ts +50 -0
  141. package/lib/timeline/JoinKeys.js +63 -0
  142. package/lib/timeline/loadCaptures.d.ts +87 -0
  143. package/lib/timeline/loadCaptures.js +424 -0
  144. package/lib/timeline/normalise.d.ts +26 -0
  145. package/lib/timeline/normalise.js +161 -0
  146. package/lib/timeline/parseWindow.d.ts +29 -0
  147. package/lib/timeline/parseWindow.js +133 -0
  148. package/lib/timeline/render.d.ts +33 -0
  149. package/lib/timeline/render.js +120 -0
  150. package/package.json +22 -20
  151. package/lib/api/ApiError.d.ts +0 -6
  152. package/lib/api/ApiError.js +0 -6
  153. package/lib/api/MetadataClient.d.ts +0 -4
  154. package/lib/api/MetadataClient.js +0 -2
  155. package/lib/api/MetadataClientImpl.d.ts +0 -8
  156. package/lib/api/MetadataClientImpl.js +0 -22
  157. package/lib/api/RestClient.d.ts +0 -6
  158. package/lib/api/RestClient.js +0 -2
  159. package/lib/api/RestClientImpl.d.ts +0 -10
  160. package/lib/api/RestClientImpl.js +0 -45
  161. package/lib/api/SoqlClient.d.ts +0 -10
  162. package/lib/api/SoqlClient.js +0 -2
  163. package/lib/api/SoqlClientImpl.d.ts +0 -9
  164. package/lib/api/SoqlClientImpl.js +0 -19
  165. package/lib/api/ToolingClient.d.ts +0 -5
  166. package/lib/api/ToolingClient.js +0 -2
  167. package/lib/api/ToolingClientImpl.d.ts +0 -10
  168. package/lib/api/ToolingClientImpl.js +0 -29
  169. package/lib/api/index.d.ts +0 -9
  170. package/lib/api/index.js +0 -5
  171. package/lib/checks/eventLogAccess.d.ts +0 -14
  172. package/lib/checks/eventLogAccess.js +0 -33
  173. package/lib/context/AuditCache.d.ts +0 -78
  174. package/lib/context/AuditCache.js +0 -2
  175. package/lib/context/AuditContext.d.ts +0 -19
  176. package/lib/context/AuditContext.js +0 -2
  177. package/lib/context/OrgInfo.d.ts +0 -9
  178. package/lib/context/OrgInfo.js +0 -2
  179. package/lib/context/OrgMetrics.d.ts +0 -20
  180. package/lib/context/OrgMetrics.js +0 -20
  181. package/lib/events/EventBaselineStore.d.ts +0 -16
  182. package/lib/events/EventBaselineStore.js +0 -55
  183. package/lib/events/eventLogQuery.d.ts +0 -21
  184. package/lib/events/eventLogQuery.js +0 -34
  185. package/lib/events/pullEventLogs.d.ts +0 -51
  186. package/lib/events/pullEventLogs.js +0 -79
  187. package/lib/findings/RiskLevel.d.ts +0 -3
  188. package/lib/findings/RiskLevel.js +0 -2
  189. package/lib/renderers/html-utils.d.ts +0 -2
  190. package/lib/renderers/html-utils.js +0 -8
  191. package/lib/report/branding.d.ts +0 -18
  192. package/lib/report/branding.js +0 -19
  193. package/lib/report/fonts.d.ts +0 -2
  194. package/lib/report/fonts.js +0 -22
  195. package/src/assets/fonts/dm-sans-italic-latin.woff2 +0 -0
  196. package/src/assets/fonts/dm-sans-normal-latin.woff2 +0 -0
  197. package/src/assets/fonts/dm-serif-display-italic-latin.woff2 +0 -0
  198. package/src/assets/fonts/dm-serif-display-normal-latin.woff2 +0 -0
@@ -0,0 +1,161 @@
1
+ import { EVENT_ROW_COLUMNS } from './EventRow.js';
2
+ import { joinKeysOf } from './JoinKeys.js';
3
+ /** Blank is absent. An empty string in a column means the source had nothing, not that it said "". */
4
+ function text(...candidates) {
5
+ for (const value of candidates) {
6
+ if (typeof value !== 'string')
7
+ continue;
8
+ const trimmed = value.trim();
9
+ if (trimmed.length > 0)
10
+ return trimmed;
11
+ }
12
+ return undefined;
13
+ }
14
+ /** A number, or nothing. Never a guess: an unparseable value is absent, not zero. */
15
+ function num(...candidates) {
16
+ for (const value of candidates) {
17
+ if (typeof value === 'number' && Number.isFinite(value))
18
+ return value;
19
+ if (typeof value === 'string' && value.trim() !== '') {
20
+ const parsed = Number(value);
21
+ if (Number.isFinite(parsed))
22
+ return parsed;
23
+ }
24
+ }
25
+ return undefined;
26
+ }
27
+ /**
28
+ * Field aliases, one table rather than a branch per event type.
29
+ *
30
+ * There are more than sixty event types and Salesforce keeps adding them. A switch would need a
31
+ * case for each, and the type it does not have a case for would vanish — which for a forensic
32
+ * tool is the worst outcome, because the absence looks like evidence. Every row is mapped
33
+ * through the same table, so an unrecognised type still yields its common fields and simply
34
+ * leaves the specific ones blank.
35
+ *
36
+ * Each entry lists the spellings a value appears under, in preference order. EventLogFile uses
37
+ * SHOUTING_SNAKE and real-time objects use PascalCase, often for the same concept.
38
+ */
39
+ const TEXT_FIELDS = {
40
+ event_type: ['EVENT_TYPE', 'EventType'],
41
+ timestamp_utc: ['TIMESTAMP_DERIVED', 'TIMESTAMP', 'EventDate', 'CreatedDate'],
42
+ user_type: ['USER_TYPE', 'UserType'],
43
+ entity_name: ['ENTITY_NAME', 'EntityName', 'QueriedEntities'],
44
+ record_ids: ['RECORD_ID', 'RecordIds', 'RecordId'],
45
+ referrer_uri: ['REFERRER_URI', 'REFERRER'],
46
+ user_agent: ['USER_AGENT', 'UserAgent', 'Browser'],
47
+ quiddity: ['QUIDDITY', 'Quiddity'],
48
+ page_name: ['PAGE_NAME', 'PAGE_APP_NAME', 'Page'],
49
+ http_method: ['METHOD', 'HTTP_METHOD', 'RequestType'],
50
+ uri: ['URI', 'Uri', 'URL'],
51
+ entry_point: ['ENTRY_POINT', 'EntryPoint'],
52
+ query_type: ['QUERY_TYPE', 'QueryType', 'Operation'],
53
+ sql_id: ['SQL_ID', 'QueryId'],
54
+ queried_entities: ['QueriedEntities', 'QUERIED_ENTITIES'],
55
+ records_returned: ['RecordIds', 'RECORDS_RETURNED', 'Records'],
56
+ list_view_name: ['Name', 'LIST_VIEW_NAME', 'ListViewName'],
57
+ list_view_scope: ['Scope', 'LIST_VIEW_SCOPE'],
58
+ filter_criteria: ['FilterCriteria', 'FILTER_CRITERIA', 'Filter'],
59
+ graphql_operation: ['OPERATION_NAME', 'GraphQLOperation'],
60
+ graphql_query: ['QUERY', 'GraphQLQuery'],
61
+ graphql_exception: ['EXCEPTION_MESSAGE', 'GraphQLException'],
62
+ aura_action_message: ['ACTION_MESSAGE'],
63
+ source_file: ['SOURCE_FILE', '__sourceFile'],
64
+ };
65
+ const NUMBER_FIELDS = {
66
+ run_time_ms: ['RUN_TIME', 'RunTime', 'EXEC_TIME'],
67
+ response_bytes: ['RESPONSE_SIZE', 'ResponseSize', 'BYTES'],
68
+ rows_processed: ['RowsProcessed', 'ROWS_PROCESSED', 'NUMBER_OF_RECORDS'],
69
+ };
70
+ /** Real-time objects supply the record-count fields; no EventLogFile type records them. */
71
+ const RTE_ONLY = [
72
+ 'rows_processed', 'records_returned', 'list_view_name', 'list_view_scope', 'filter_criteria',
73
+ ];
74
+ /**
75
+ * Collapse a batch of Aura actions into one readable line.
76
+ *
77
+ * A single request can carry hundreds of action invocations, and printed raw they bury the
78
+ * timeline. The count alone would not do: the min–max range is the finding. A batch that is
79
+ * uniformly 0ms is fail-fast permission denial — the actor was refused. A batch spread across
80
+ * hundreds of milliseconds is the database being queried, which is the actor getting data.
81
+ * Collapsing to a count would erase the difference between an attempt and a success.
82
+ */
83
+ export function collapseAuraActions(message) {
84
+ if (!message)
85
+ return undefined;
86
+ const timings = new Map();
87
+ for (const [, descriptor, ms] of message.matchAll(/([A-Za-z0-9_$./-]+)\s*=\s*(\d+)/g)) {
88
+ const value = Number(ms);
89
+ const seen = timings.get(descriptor);
90
+ if (seen) {
91
+ seen.count++;
92
+ seen.min = Math.min(seen.min, value);
93
+ seen.max = Math.max(seen.max, value);
94
+ }
95
+ else {
96
+ timings.set(descriptor, { count: 1, min: value, max: value });
97
+ }
98
+ }
99
+ if (timings.size === 0)
100
+ return undefined;
101
+ return [...timings]
102
+ .map(([descriptor, t]) => `${descriptor} x${t.count} [${t.min}-${t.max}ms]`)
103
+ .join('; ');
104
+ }
105
+ /**
106
+ * Map one raw row into the unified shape.
107
+ *
108
+ * Every declared column is present on the result, set to `undefined` where the source had
109
+ * nothing. That keeps the CSV header and the row in lockstep — a column that only materialises
110
+ * when populated shifts every value to its left the moment a source omits it.
111
+ */
112
+ export function normaliseRow(raw, ctx) {
113
+ const keys = joinKeysOf(raw);
114
+ const isRte = ctx.source === 'RealTimeEventMonitoring';
115
+ const row = {};
116
+ for (const column of EVENT_ROW_COLUMNS)
117
+ row[column] = undefined;
118
+ row.seq = ctx.seq;
119
+ row.attribution = ctx.attribution;
120
+ row.source = ctx.source;
121
+ for (const [column, aliases] of Object.entries(TEXT_FIELDS)) {
122
+ if (!isRte && RTE_ONLY.includes(column))
123
+ continue;
124
+ row[column] = text(...aliases.map((a) => raw[a]));
125
+ }
126
+ for (const [column, aliases] of Object.entries(NUMBER_FIELDS)) {
127
+ if (!isRte && RTE_ONLY.includes(column))
128
+ continue;
129
+ row[column] = num(...aliases.map((a) => raw[a]));
130
+ }
131
+ // Join keys come from the one place that already applies the blank rule, so the timeline's
132
+ // columns and the correlation that produced them cannot disagree about what a row's keys are.
133
+ row.client_ip = keys.clientIp;
134
+ row.request_id = keys.requestId;
135
+ row.session_key = keys.sessionKey;
136
+ row.login_key = keys.loginKey;
137
+ row.user_id = keys.userId;
138
+ row.transaction_id = keys.transactionId;
139
+ row.event_identifier = keys.eventIdentifier;
140
+ row.related_event_identifier = keys.relatedEventIdentifier;
141
+ row.event_type = row.event_type ?? 'Unknown';
142
+ row.timestamp_utc = row.timestamp_utc ?? '';
143
+ row.is_guest = row.user_type === undefined ? undefined : /guest/i.test(String(row.user_type));
144
+ row.is_error = errorFlag(raw);
145
+ row.aura_action_summary = collapseAuraActions(row.aura_action_message);
146
+ return row;
147
+ }
148
+ /** Several types spell failure differently; none of them spell it consistently. */
149
+ function errorFlag(raw) {
150
+ const status = text(raw.STATUS_CODE, raw.HTTP_STATUS_CODE, raw.StatusCode);
151
+ if (status !== undefined) {
152
+ const code = Number(status);
153
+ if (Number.isFinite(code))
154
+ return code >= 400;
155
+ }
156
+ const explicit = text(raw.IS_ERROR, raw.EXCEPTION_MESSAGE, raw.GraphQLException);
157
+ if (explicit === undefined)
158
+ return undefined;
159
+ return explicit.toLowerCase() !== 'false' && explicit !== '0';
160
+ }
161
+ //# sourceMappingURL=normalise.js.map
@@ -0,0 +1,29 @@
1
+ export interface Window {
2
+ /** UTC date, YYYY-MM-DD. */
3
+ date: string;
4
+ /** Two-digit UTC hours to read, ascending. */
5
+ hours: string[];
6
+ /** Window start, inclusive. */
7
+ startMs: number;
8
+ /** Window end, exclusive — so consecutive windows partition rows rather than sharing a boundary. */
9
+ endMs: number;
10
+ }
11
+ /**
12
+ * Resolve a window to the hour files that hold it.
13
+ *
14
+ * Several spellings, one meaning. The exact ISO interval is precise and nobody composes one
15
+ * under pressure; an investigator knows "yesterday", "the last two hours", or has a timestamp
16
+ * pasted from an alert. Translating that by hand is a step where the timezone or the duration
17
+ * syntax goes wrong, and the resulting empty timeline reads as an absence of evidence rather
18
+ * than as a mistyped window.
19
+ *
20
+ * Resolution errs toward reading more rather than less: a window starting at 04:45 still reads
21
+ * hour 04, because the evidence between 04:45 and 05:00 lives in that file. Over-reading costs a
22
+ * few rows the correlation ignores; under-reading reports an absence the capture would have
23
+ * contradicted.
24
+ *
25
+ * `now` is a parameter rather than read from the clock, so the relative forms are testable and a
26
+ * run can be reproduced.
27
+ */
28
+ export declare function parseWindow(interval: string, now?: number): Window;
29
+ //# sourceMappingURL=parseWindow.d.ts.map
@@ -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.6.1",
3
+ "version": "1.8.0",
4
4
  "description": "Salesforce Security Audit — native sf plugin",
5
5
  "license": "Apache-2.0",
6
6
  "type": "module",
@@ -11,20 +11,23 @@
11
11
  "test": "node --experimental-vm-modules node_modules/jest/bin/jest.js --passWithNoTests",
12
12
  "test:unit": "node --experimental-vm-modules node_modules/jest/bin/jest.js test/unit --passWithNoTests",
13
13
  "prepack": "npm run build",
14
- "clean": "rm -rf lib"
14
+ "clean": "rm -rf lib",
15
+ "prepare": "git config core.hooksPath .githooks 2>/dev/null || true"
15
16
  },
16
17
  "dependencies": {
17
18
  "@oclif/core": "^4",
18
- "@salesforce/core": "^8",
19
- "@salesforce/sf-plugins-core": "^12",
20
- "zod": "^3"
19
+ "@salesforce/core": "^9",
20
+ "@salesforce/sf-plugins-core": "^13",
21
+ "chart.js": "^4.5.1",
22
+ "zod": "^4",
23
+ "@cclabsnz/sf-core": "^0.3.0"
21
24
  },
22
25
  "devDependencies": {
23
- "@jest/globals": "^29.7.0",
24
- "@types/jest": "^29",
25
- "@types/node": "^22",
26
- "jest": "^29",
27
- "ts-jest": "^29",
26
+ "@jest/globals": "^30.4.1",
27
+ "@types/jest": "^30",
28
+ "@types/node": "^26",
29
+ "jest": "^30",
30
+ "ts-jest": "^29.4.12",
28
31
  "ts-node": "^10.9.2",
29
32
  "typescript": "^5"
30
33
  },
@@ -56,20 +59,19 @@
56
59
  }
57
60
  }
58
61
  },
62
+ "files": [
63
+ "/lib",
64
+ "/messages",
65
+ "/config",
66
+ "!/lib/**/*.map"
67
+ ],
59
68
  "pnpm": {
60
69
  "overrides": {
61
70
  "form-data": "^4.0.6",
62
71
  "js-yaml@3": "^3.15.0",
63
72
  "handlebars": "^4.7.9",
64
- "brace-expansion": "^5.0.8",
65
- "fast-uri@3": "^3.1.4"
73
+ "brace-expansion": "^5.0.9",
74
+ "fast-uri@3": "^3.1.5"
66
75
  }
67
- },
68
- "files": [
69
- "/lib",
70
- "/messages",
71
- "/config",
72
- "/src/assets",
73
- "!/lib/**/*.map"
74
- ]
76
+ }
75
77
  }
@@ -1,6 +0,0 @@
1
- export interface ApiError extends Error {
2
- errorCode: string;
3
- statusCode: number;
4
- }
5
- export declare function isApiError(err: unknown): err is ApiError;
6
- //# sourceMappingURL=ApiError.d.ts.map
@@ -1,6 +0,0 @@
1
- export function isApiError(err) {
2
- return (err instanceof Error &&
3
- 'errorCode' in err && typeof err.errorCode === 'string' &&
4
- 'statusCode' in err && typeof err.statusCode === 'number');
5
- }
6
- //# sourceMappingURL=ApiError.js.map
@@ -1,4 +0,0 @@
1
- export interface MetadataClient {
2
- read<T = Record<string, unknown>>(type: string, fullName: string): Promise<T | null>;
3
- }
4
- //# sourceMappingURL=MetadataClient.d.ts.map
@@ -1,2 +0,0 @@
1
- export {};
2
- //# sourceMappingURL=MetadataClient.js.map
@@ -1,8 +0,0 @@
1
- import type { Connection } from '@salesforce/core';
2
- import type { MetadataClient } from './MetadataClient.js';
3
- export declare class MetadataClientImpl implements MetadataClient {
4
- private readonly conn;
5
- constructor(conn: Connection);
6
- read<T = Record<string, unknown>>(type: string, fullName: string): Promise<T | null>;
7
- }
8
- //# sourceMappingURL=MetadataClientImpl.d.ts.map
@@ -1,22 +0,0 @@
1
- export class MetadataClientImpl {
2
- conn;
3
- constructor(conn) {
4
- this.conn = conn;
5
- }
6
- async read(type, fullName) {
7
- // jsforce types `read` to a fixed MetadataType union; we pass through arbitrary
8
- // type names (e.g. 'SecuritySettings'), so call via a loosened signature.
9
- const read = this.conn.metadata.read.bind(this.conn.metadata);
10
- const res = await read(type, fullName);
11
- if (res == null)
12
- return null;
13
- const rec = Array.isArray(res) ? res[0] : res;
14
- // Metadata.read returns an object with only `fullName`/empty fields when the
15
- // component does not exist — treat that as "not present".
16
- if (!rec || typeof rec !== 'object')
17
- return null;
18
- const keys = Object.keys(rec).filter((k) => k !== 'fullName');
19
- return keys.length === 0 ? null : rec;
20
- }
21
- }
22
- //# sourceMappingURL=MetadataClientImpl.js.map
@@ -1,6 +0,0 @@
1
- export interface RestClient {
2
- get<T>(path: string): Promise<T>;
3
- getRaw(path: string): Promise<string>;
4
- getRawToFile(path: string, destPath: string): Promise<number>;
5
- }
6
- //# sourceMappingURL=RestClient.d.ts.map
@@ -1,2 +0,0 @@
1
- export {};
2
- //# sourceMappingURL=RestClient.js.map
@@ -1,10 +0,0 @@
1
- import type { Connection } from '@salesforce/core';
2
- import type { RestClient } from './RestClient.js';
3
- export declare class RestClientImpl implements RestClient {
4
- private readonly conn;
5
- constructor(conn: Connection);
6
- get<T>(path: string): Promise<T>;
7
- getRaw(path: string): Promise<string>;
8
- getRawToFile(path: string, destPath: string): Promise<number>;
9
- }
10
- //# sourceMappingURL=RestClientImpl.d.ts.map