@oneuptime/common 12.0.20 → 12.0.22

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 (119) hide show
  1. package/Models/AnalyticsModels/ChangeEvent.ts +331 -0
  2. package/Models/AnalyticsModels/Index.ts +2 -0
  3. package/Models/DatabaseModels/Index.ts +2 -0
  4. package/Models/DatabaseModels/UserTwoFactorBackupCode.ts +262 -0
  5. package/Server/API/UserTwoFactorBackupCodeAPI.ts +258 -0
  6. package/Server/EnvironmentConfig.ts +1 -8
  7. package/Server/Infrastructure/Postgres/SchemaMigrations/1789000000000-AddUserSlackAndMicrosoftTeams.ts +42 -0
  8. package/Server/Infrastructure/Postgres/SchemaMigrations/1789100000000-AddUserTwoFactorBackupCode.ts +63 -0
  9. package/Server/Infrastructure/Postgres/SchemaMigrations/Index.ts +2 -2
  10. package/Server/Services/ChangeEventService.ts +11 -0
  11. package/Server/Services/EnterpriseLicenseService.ts +3 -3
  12. package/Server/Services/Index.ts +4 -0
  13. package/Server/Services/UserService.ts +42 -0
  14. package/Server/Services/UserTwoFactorBackupCodeService.ts +355 -0
  15. package/Server/Utils/Attribution.ts +11 -11
  16. package/Server/Utils/Marketing/MarketingEventWebhook.ts +4 -5
  17. package/Server/Utils/Telemetry/ChangeEventRow.ts +228 -0
  18. package/Server/Utils/TwoFactorBackupCode.ts +266 -0
  19. package/Server/Views/Partials/AnalyticsConsent.ejs +3 -95
  20. package/Tests/App/Dashboard/DashboardChartWidgetZoom.test.tsx +64 -0
  21. package/Tests/App/Dashboard/EventOverlayHook.test.tsx +249 -0
  22. package/Tests/App/Dashboard/InvestigationArtifacts.test.tsx +315 -0
  23. package/Tests/App/Dashboard/InvestigationDrawer.test.tsx +258 -0
  24. package/Tests/App/Dashboard/MetricChartsCompare.test.tsx +171 -0
  25. package/Tests/App/Dashboard/MetricViewCompare.test.tsx +233 -0
  26. package/Tests/Server/API/UserAuthenticationAPI.test.ts +16 -3
  27. package/Tests/Server/API/UserTwoFactorAuthAdminAPI.test.ts +18 -2
  28. package/Tests/Server/API/UserTwoFactorBackupCodeAPI.test.ts +1390 -0
  29. package/Tests/Server/Infrastructure/Postgres/AddUserSlackAndMicrosoftTeamsMigration.test.ts +236 -0
  30. package/Tests/Server/Services/UserAuthenticationService.test.ts +23 -1
  31. package/Tests/Server/Services/UserTwoFactorAuthAdmin.test.ts +21 -0
  32. package/Tests/Server/Services/UserTwoFactorBackupCodeAdminSurface.test.ts +919 -0
  33. package/Tests/Server/Services/UserTwoFactorBackupCodeService.test.ts +862 -0
  34. package/Tests/Server/Utils/AI/SRE/Insights/Detectors/ExceptionIdentity.test.ts +224 -0
  35. package/Tests/Server/Utils/Attribution.test.ts +4 -5
  36. package/Tests/Server/Utils/Marketing/MarketingEventUtil.test.ts +2 -2
  37. package/Tests/Server/Utils/Monitor/MonitorCriteriaExpectationBuilder.test.ts +300 -0
  38. package/Tests/Server/Utils/TwoFactorBackupCode.test.ts +475 -0
  39. package/Tests/UI/Components/Charts/ChartGhostSeries.test.tsx +103 -0
  40. package/Tests/UI/Components/Charts/TooltipEntries.test.ts +44 -8
  41. package/Tests/Utils/Telemetry/CrossSignalScope.test.ts +13 -2
  42. package/Types/AnalyticsDatabase/AnalyticsTableName.ts +7 -0
  43. package/Types/Email/EmailTemplateType.ts +2 -0
  44. package/Types/Marketing/Attribution.ts +9 -15
  45. package/Types/Marketing/MarketingEvent.ts +10 -46
  46. package/Types/UserAuthenticationStatus.ts +16 -0
  47. package/UI/Components/Charts/Area/AreaChart.tsx +15 -0
  48. package/UI/Components/Charts/ChartGroup/ChartGroup.tsx +16 -1
  49. package/UI/Components/Charts/ChartLibrary/AreaChart/AreaChart.tsx +189 -93
  50. package/UI/Components/Charts/ChartLibrary/BarChart/BarChart.tsx +6 -1
  51. package/UI/Components/Charts/ChartLibrary/LineChart/LineChart.tsx +213 -114
  52. package/UI/Components/Charts/ChartLibrary/Utils/TooltipEntries.ts +42 -27
  53. package/UI/Components/Charts/Line/LineChart.tsx +15 -0
  54. package/Utils/Metrics/MetricExplorerUrl.ts +119 -5
  55. package/Utils/Telemetry/CrossSignalScope.ts +19 -10
  56. package/build/dist/Models/AnalyticsModels/ChangeEvent.js +298 -0
  57. package/build/dist/Models/AnalyticsModels/ChangeEvent.js.map +1 -0
  58. package/build/dist/Models/AnalyticsModels/Index.js +2 -0
  59. package/build/dist/Models/AnalyticsModels/Index.js.map +1 -1
  60. package/build/dist/Models/DatabaseModels/Index.js +2 -0
  61. package/build/dist/Models/DatabaseModels/Index.js.map +1 -1
  62. package/build/dist/Models/DatabaseModels/UserTwoFactorBackupCode.js +277 -0
  63. package/build/dist/Models/DatabaseModels/UserTwoFactorBackupCode.js.map +1 -0
  64. package/build/dist/Server/API/UserTwoFactorBackupCodeAPI.js +201 -0
  65. package/build/dist/Server/API/UserTwoFactorBackupCodeAPI.js.map +1 -0
  66. package/build/dist/Server/EnvironmentConfig.js +1 -7
  67. package/build/dist/Server/EnvironmentConfig.js.map +1 -1
  68. package/build/dist/Server/Infrastructure/Postgres/SchemaMigrations/1789000000000-AddUserSlackAndMicrosoftTeams.js +39 -0
  69. package/build/dist/Server/Infrastructure/Postgres/SchemaMigrations/1789000000000-AddUserSlackAndMicrosoftTeams.js.map +1 -1
  70. package/build/dist/Server/Infrastructure/Postgres/SchemaMigrations/1789100000000-AddUserTwoFactorBackupCode.js +46 -0
  71. package/build/dist/Server/Infrastructure/Postgres/SchemaMigrations/1789100000000-AddUserTwoFactorBackupCode.js.map +1 -0
  72. package/build/dist/Server/Infrastructure/Postgres/SchemaMigrations/Index.js +2 -2
  73. package/build/dist/Server/Infrastructure/Postgres/SchemaMigrations/Index.js.map +1 -1
  74. package/build/dist/Server/Services/ChangeEventService.js +9 -0
  75. package/build/dist/Server/Services/ChangeEventService.js.map +1 -0
  76. package/build/dist/Server/Services/EnterpriseLicenseService.js +3 -3
  77. package/build/dist/Server/Services/Index.js +4 -0
  78. package/build/dist/Server/Services/Index.js.map +1 -1
  79. package/build/dist/Server/Services/UserService.js +39 -0
  80. package/build/dist/Server/Services/UserService.js.map +1 -1
  81. package/build/dist/Server/Services/UserTwoFactorBackupCodeService.js +327 -0
  82. package/build/dist/Server/Services/UserTwoFactorBackupCodeService.js.map +1 -0
  83. package/build/dist/Server/Utils/Attribution.js +6 -6
  84. package/build/dist/Server/Utils/Marketing/MarketingEventWebhook.js +4 -5
  85. package/build/dist/Server/Utils/Marketing/MarketingEventWebhook.js.map +1 -1
  86. package/build/dist/Server/Utils/Telemetry/ChangeEventRow.js +150 -0
  87. package/build/dist/Server/Utils/Telemetry/ChangeEventRow.js.map +1 -0
  88. package/build/dist/Server/Utils/TwoFactorBackupCode.js +269 -0
  89. package/build/dist/Server/Utils/TwoFactorBackupCode.js.map +1 -0
  90. package/build/dist/Types/AnalyticsDatabase/AnalyticsTableName.js +7 -0
  91. package/build/dist/Types/AnalyticsDatabase/AnalyticsTableName.js.map +1 -1
  92. package/build/dist/Types/Email/EmailTemplateType.js +2 -0
  93. package/build/dist/Types/Email/EmailTemplateType.js.map +1 -1
  94. package/build/dist/Types/Marketing/Attribution.js +9 -15
  95. package/build/dist/Types/Marketing/Attribution.js.map +1 -1
  96. package/build/dist/Types/Marketing/MarketingEvent.js +2 -33
  97. package/build/dist/Types/Marketing/MarketingEvent.js.map +1 -1
  98. package/build/dist/UI/Components/Charts/Area/AreaChart.js +1 -1
  99. package/build/dist/UI/Components/Charts/Area/AreaChart.js.map +1 -1
  100. package/build/dist/UI/Components/Charts/ChartGroup/ChartGroup.js +9 -1
  101. package/build/dist/UI/Components/Charts/ChartGroup/ChartGroup.js.map +1 -1
  102. package/build/dist/UI/Components/Charts/ChartLibrary/AreaChart/AreaChart.js +92 -38
  103. package/build/dist/UI/Components/Charts/ChartLibrary/AreaChart/AreaChart.js.map +1 -1
  104. package/build/dist/UI/Components/Charts/ChartLibrary/BarChart/BarChart.js +8 -8
  105. package/build/dist/UI/Components/Charts/ChartLibrary/BarChart/BarChart.js.map +1 -1
  106. package/build/dist/UI/Components/Charts/ChartLibrary/LineChart/LineChart.js +95 -37
  107. package/build/dist/UI/Components/Charts/ChartLibrary/LineChart/LineChart.js.map +1 -1
  108. package/build/dist/UI/Components/Charts/ChartLibrary/Utils/TooltipEntries.js +39 -24
  109. package/build/dist/UI/Components/Charts/ChartLibrary/Utils/TooltipEntries.js.map +1 -1
  110. package/build/dist/UI/Components/Charts/Line/LineChart.js +1 -1
  111. package/build/dist/UI/Components/Charts/Line/LineChart.js.map +1 -1
  112. package/build/dist/Utils/Metrics/MetricExplorerUrl.js +81 -0
  113. package/build/dist/Utils/Metrics/MetricExplorerUrl.js.map +1 -1
  114. package/build/dist/Utils/Telemetry/CrossSignalScope.js +14 -8
  115. package/build/dist/Utils/Telemetry/CrossSignalScope.js.map +1 -1
  116. package/package.json +1 -1
  117. package/Server/Infrastructure/Postgres/SchemaMigrations/1788900000000-RedactStoredMonitorIngestSecrets.ts +0 -117
  118. package/build/dist/Server/Infrastructure/Postgres/SchemaMigrations/1788900000000-RedactStoredMonitorIngestSecrets.js +0 -106
  119. package/build/dist/Server/Infrastructure/Postgres/SchemaMigrations/1788900000000-RedactStoredMonitorIngestSecrets.js.map +0 -1
@@ -0,0 +1,355 @@
1
+ import DatabaseService from "./DatabaseService";
2
+ import Model from "../../Models/DatabaseModels/UserTwoFactorBackupCode";
3
+ import TwoFactorBackupCode, {
4
+ BackupCodeSetSize,
5
+ } from "../Utils/TwoFactorBackupCode";
6
+ import CreateBy from "../Types/Database/CreateBy";
7
+ import { OnCreate } from "../Types/Database/Hooks";
8
+ import QueryHelper from "../Types/Database/QueryHelper";
9
+ import BadDataException from "../../Types/Exception/BadDataException";
10
+ import LIMIT_MAX from "../../Types/Database/LimitMax";
11
+ import SortOrder from "../../Types/BaseDatabase/SortOrder";
12
+ import ObjectID from "../../Types/ObjectID";
13
+ import PositiveNumber from "../../Types/PositiveNumber";
14
+ import OneUptimeDate from "../../Types/Date";
15
+ import CaptureSpan from "../Utils/Telemetry/CaptureSpan";
16
+ import logger from "../Utils/Logger";
17
+
18
+ /**
19
+ * How many of a user's backup codes are left, for the profile page and the
20
+ * admin's account view.
21
+ *
22
+ * `total` and `unused` are both reported rather than just the remaining count
23
+ * because they answer different questions: "have you set backup codes up at
24
+ * all" and "how many can you still use". A user with ten codes and a user who
25
+ * has spent all ten both have a `total` of ten, and only the second needs to
26
+ * be told to regenerate.
27
+ */
28
+ export interface TwoFactorBackupCodeStatus {
29
+ total: number;
30
+ unused: number;
31
+
32
+ /*
33
+ * When the current set was minted, or null if there are none. Read off the
34
+ * newest row rather than stored separately -- regeneration replaces the
35
+ * whole set in one call, so every row in a set shares a creation time to
36
+ * within a few milliseconds.
37
+ */
38
+ generatedAt: Date | null;
39
+ }
40
+
41
+ export class Service extends DatabaseService<Model> {
42
+ public constructor() {
43
+ super(Model);
44
+ }
45
+
46
+ /*
47
+ * The model denies create to everyone, so the only way a row is written is
48
+ * `regenerateForUser` below, as root. This hook is the second lock on the
49
+ * same door: it refuses any create that did not come through there.
50
+ *
51
+ * Worth having both because the two guards fail differently. The table
52
+ * permission is enforced by the CRUD API layer and is bypassed wholesale by
53
+ * `isRoot`, which every internal caller uses -- so a future service that
54
+ * reaches for `UserTwoFactorBackupCodeService.create()` with a plaintext
55
+ * code, or with no owner, would sail past it. What lands in `codeHash` is
56
+ * the credential; there is no recovering from writing the wrong thing there.
57
+ */
58
+ @CaptureSpan()
59
+ protected override async onBeforeCreate(
60
+ createBy: CreateBy<Model>,
61
+ ): Promise<OnCreate<Model>> {
62
+ if (!createBy.data.userId) {
63
+ throw new BadDataException("User id is required");
64
+ }
65
+
66
+ if (!createBy.data.codeHash) {
67
+ throw new BadDataException("Backup code hash is required");
68
+ }
69
+
70
+ /*
71
+ * A code that arrives already spent is a caller confusing itself about
72
+ * which end of the lifecycle it is at. Codes are minted usable and are
73
+ * spent only by `consumeCode`.
74
+ *
75
+ * Deleted rather than set to undefined: `exactOptionalPropertyTypes` is on,
76
+ * so the property being ABSENT and the property holding `undefined` are
77
+ * different things to the compiler, and only the first is allowed here.
78
+ */
79
+ delete createBy.data.usedAt;
80
+
81
+ return {
82
+ createBy: createBy,
83
+ carryForward: {},
84
+ };
85
+ }
86
+
87
+ /**
88
+ * Mint a fresh set of backup codes for one user, replacing whatever they
89
+ * had, and return the PLAINTEXT codes.
90
+ *
91
+ * This is the only moment the plaintext exists anywhere. The caller shows it
92
+ * to the user once and then it is gone -- only the keyed digests are stored,
93
+ * so nothing (not this service, not a master admin, not a database dump) can
94
+ * produce the codes again. That is the property the feature is worth having
95
+ * for, and it is why the API route wraps this in a response the UI is
96
+ * expected to make the user acknowledge.
97
+ *
98
+ * REPLACING rather than adding is deliberate. "Generate more codes" would
99
+ * leave the codes from a list the user printed, lost and then regenerated
100
+ * over still working, which defeats the point of regenerating after a
101
+ * suspected compromise.
102
+ *
103
+ * ALL OR NOTHING, and this is the part that needs care. The old set is
104
+ * deleted first, then the new rows are written one at a time -- so a failure
105
+ * partway through the loop would otherwise leave the account holding a few
106
+ * rows that WERE written and that the caller, having thrown, never showed to
107
+ * anybody. `getStatusForUser` would then report "4 backup codes" to a user
108
+ * who has never seen one of them: codes that are unusable in practice and
109
+ * that hide the fact that they have no recovery route left. That is the
110
+ * worst state this feature can produce, because it looks exactly like the
111
+ * good one.
112
+ *
113
+ * So a failure is compensated: everything written for this user is removed,
114
+ * and the account ends with NO codes and an error on screen. "You have no
115
+ * backup codes" is a state the profile page already tells the user to fix;
116
+ * "you have four codes you have never seen" is not.
117
+ *
118
+ * The compensating delete is itself best-effort -- if it also fails there is
119
+ * nothing further to try -- but it turns a silent, permanent trap into two
120
+ * consecutive infrastructure failures.
121
+ */
122
+ @CaptureSpan()
123
+ public async regenerateForUser(data: {
124
+ userId: ObjectID;
125
+ count?: number | undefined;
126
+ }): Promise<Array<string>> {
127
+ const count: number = data.count || BackupCodeSetSize;
128
+
129
+ await this.deleteAllForUser({ userId: data.userId });
130
+
131
+ const codes: Array<string> = TwoFactorBackupCode.generateCodeSet(count);
132
+
133
+ try {
134
+ for (const code of codes) {
135
+ const backupCode: Model = new Model();
136
+ backupCode.userId = data.userId;
137
+ backupCode.codeHash = TwoFactorBackupCode.hashCode({
138
+ code: code,
139
+ userId: data.userId,
140
+ });
141
+
142
+ await this.create({
143
+ data: backupCode,
144
+ props: {
145
+ isRoot: true,
146
+ },
147
+ });
148
+ }
149
+ } catch (err) {
150
+ try {
151
+ await this.deleteAllForUser({ userId: data.userId });
152
+ } catch (cleanupError) {
153
+ /*
154
+ * Swallowed so the ORIGINAL failure is what the caller sees. The
155
+ * cleanup error is the less useful of the two -- it explains why the
156
+ * rollback did not happen, not why the write did not.
157
+ */
158
+ logger.error(cleanupError);
159
+ }
160
+
161
+ throw err;
162
+ }
163
+
164
+ return codes;
165
+ }
166
+
167
+ /**
168
+ * Spend one of this user's backup codes, if the submitted code is one of
169
+ * them and has not been used already.
170
+ *
171
+ * ONE STATEMENT, ON PURPOSE
172
+ *
173
+ * The obvious shape -- find the row, check `usedAt`, then update it -- has a
174
+ * window between the read and the write, and "single use" is the entire
175
+ * guarantee a backup code offers. Two sign-in attempts carrying the same
176
+ * code that arrive together would both read a null `usedAt` and both be let
177
+ * in, which is precisely the property an attacker who has watched somebody
178
+ * type a code off a printed list would exploit.
179
+ *
180
+ * `usedAt IS NULL` in the WHERE clause moves the decision inside Postgres,
181
+ * where the row lock settles it: the first statement to reach the row
182
+ * updates it, the second matches nothing. `RETURNING "_id"` is what turns
183
+ * that into an answer for the caller -- an UPDATE that matched no rows and
184
+ * an UPDATE that matched one are otherwise indistinguishable from here.
185
+ *
186
+ * Written as raw parameterized SQL rather than through the ORM because no
187
+ * write path on DatabaseService both takes a non-primary-key predicate and
188
+ * reports what it matched. Column and table names are literals in this file,
189
+ * never caller input, and all three values are bound parameters.
190
+ *
191
+ * `deletedAt IS NULL` is included because soft-deleted rows are still
192
+ * physically present; without it, a code from a set that regeneration
193
+ * replaced would still sign somebody in.
194
+ *
195
+ * @returns true when a code was spent, false when the code was wrong,
196
+ * already used, or belongs to somebody else.
197
+ */
198
+ @CaptureSpan()
199
+ public async consumeCode(data: {
200
+ userId: ObjectID;
201
+ code: string;
202
+ }): Promise<boolean> {
203
+ const normalizedCode: string = TwoFactorBackupCode.normalizeCode(data.code);
204
+
205
+ /*
206
+ * Refused before the query rather than hashed and looked up. An empty
207
+ * submission cannot be anybody's code, and letting it through would mean
208
+ * one round trip per empty request on a route an attacker can call.
209
+ */
210
+ if (!normalizedCode) {
211
+ return false;
212
+ }
213
+
214
+ const codeHash: string = TwoFactorBackupCode.hashCode({
215
+ code: normalizedCode,
216
+ userId: data.userId,
217
+ });
218
+
219
+ const rows: Array<{ _id: string }> = await this.getRepository()
220
+ .manager.query(
221
+ `UPDATE "UserTwoFactorBackupCode"
222
+ SET "usedAt" = $1, "updatedAt" = CURRENT_TIMESTAMP
223
+ WHERE "userId" = $2
224
+ AND "codeHash" = $3
225
+ AND "usedAt" IS NULL
226
+ AND "deletedAt" IS NULL
227
+ RETURNING "_id"`,
228
+ [OneUptimeDate.getCurrentDate(), data.userId.toString(), codeHash],
229
+ )
230
+ /*
231
+ * For an UPDATE the postgres driver hands back `[rows, rowCount]` rather
232
+ * than a bare row array, so the rows have to be unwrapped. Written
233
+ * defensively: a driver that returns the bare array instead must read as
234
+ * "no code was spent", never as a silent success.
235
+ */
236
+ .then((result: unknown): Array<{ _id: string }> => {
237
+ if (!Array.isArray(result)) {
238
+ return [];
239
+ }
240
+
241
+ const first: unknown = result[0];
242
+
243
+ return Array.isArray(first) ? (first as Array<{ _id: string }>) : [];
244
+ });
245
+
246
+ return rows.length > 0;
247
+ }
248
+
249
+ /**
250
+ * How many codes this user has, and how many are still spendable.
251
+ *
252
+ * Counted rather than fetched: the rows carry a credential digest and there
253
+ * is no caller that needs them, so nothing is loaded that a stray log line
254
+ * could then print.
255
+ */
256
+ @CaptureSpan()
257
+ public async getStatusForUser(data: {
258
+ userId: ObjectID;
259
+ }): Promise<TwoFactorBackupCodeStatus> {
260
+ const total: PositiveNumber = await this.countBy({
261
+ query: {
262
+ userId: data.userId,
263
+ },
264
+ props: {
265
+ isRoot: true,
266
+ },
267
+ });
268
+
269
+ if (total.toNumber() === 0) {
270
+ return {
271
+ total: 0,
272
+ unused: 0,
273
+ generatedAt: null,
274
+ };
275
+ }
276
+
277
+ const unused: number = await this.countUnusedForUser({
278
+ userId: data.userId,
279
+ });
280
+
281
+ const newest: Model | null = await this.findOneBy({
282
+ query: {
283
+ userId: data.userId,
284
+ },
285
+ select: {
286
+ createdAt: true,
287
+ },
288
+ sort: {
289
+ createdAt: SortOrder.Descending,
290
+ },
291
+ props: {
292
+ isRoot: true,
293
+ },
294
+ });
295
+
296
+ return {
297
+ total: total.toNumber(),
298
+ unused: unused,
299
+ generatedAt: newest?.createdAt || null,
300
+ };
301
+ }
302
+
303
+ /**
304
+ * How many unused codes this user has left.
305
+ *
306
+ * Split out from `getStatusForUser` because the login path needs exactly
307
+ * this number and nothing else: it decides whether the two factor challenge
308
+ * screen offers "use a backup code" at all, and it is answered on every
309
+ * two-factor sign-in.
310
+ *
311
+ * `usedAt: QueryHelper.isNull()` rather than `usedAt: null`. A bare null
312
+ * predicate is dropped by TypeORM rather than compiled to `IS NULL`, so the
313
+ * count would silently include spent codes and the login page would offer a
314
+ * recovery route to a user with nothing left to recover with.
315
+ */
316
+ @CaptureSpan()
317
+ public async countUnusedForUser(data: { userId: ObjectID }): Promise<number> {
318
+ const unused: PositiveNumber = await this.countBy({
319
+ query: {
320
+ userId: data.userId,
321
+ usedAt: QueryHelper.isNull(),
322
+ },
323
+ props: {
324
+ isRoot: true,
325
+ },
326
+ });
327
+
328
+ return unused.toNumber();
329
+ }
330
+
331
+ /**
332
+ * Drop every backup code this user has.
333
+ *
334
+ * Called by regeneration, and by UserService.resetTwoFactorAuth -- an
335
+ * operator resetting two factor auth for somebody who lost a device must
336
+ * take the recovery codes with it. Leaving them behind would mean the reset
337
+ * did not actually revoke the account's second-factor material, which is the
338
+ * one thing the operator pressed the button to do.
339
+ */
340
+ @CaptureSpan()
341
+ public async deleteAllForUser(data: { userId: ObjectID }): Promise<void> {
342
+ await this.deleteBy({
343
+ query: {
344
+ userId: data.userId,
345
+ },
346
+ limit: LIMIT_MAX,
347
+ skip: 0,
348
+ props: {
349
+ isRoot: true,
350
+ },
351
+ });
352
+ }
353
+ }
354
+
355
+ export default new Service();
@@ -11,12 +11,12 @@ import { JSONObject, JSONValue } from "../../Types/JSON";
11
11
 
12
12
  /*
13
13
  * Sanitizers for attribution submitted by unauthenticated callers — the signup
14
- * form, the Cal.com booking webhook, and the enterprise licence request form.
14
+ * form and the enterprise licence request form.
15
15
  *
16
- * Everything here is a whitelist, never a denylist. Cal booking metadata and
17
- * form bodies are free-form caller content (names, notes, answers to booking
18
- * questions), and only the keys named in Common/Types/Marketing/Attribution.ts
19
- * may be copied into a row that is later forwarded to an ad platform.
16
+ * Everything here is a whitelist, never a denylist. Form bodies are free-form
17
+ * caller content (names, notes, free-text answers), and only the keys named in
18
+ * Common/Types/Marketing/Attribution.ts may be copied into a row that is later
19
+ * forwarded to an ad platform.
20
20
  *
21
21
  * This file also owns email normalisation and hashing. Meta and Reddit each
22
22
  * used to carry a private copy of the hash, and MarketingConversion.emailHash
@@ -101,10 +101,10 @@ export default class Attribution {
101
101
  /*
102
102
  * UTM values out of an arbitrary object, accepting either spelling.
103
103
  *
104
- * A URL and Cal booking metadata carry `utm_source`; a JSON body posted by
105
- * the signup page carries `utmSource`. Both arrive at server doors that
106
- * write the same columns, so both are read here rather than making each
107
- * caller remember which shape it is holding. camelCase wins when a caller
104
+ * A URL carries `utm_source`; a JSON body posted by the signup page carries
105
+ * `utmSource`. Both arrive at server doors that write the same columns, so
106
+ * both are read here rather than making each caller remember which shape it
107
+ * is holding. camelCase wins when a caller
108
108
  * somehow sends both, because that is the spelling the browser writes
109
109
  * deliberately and the snake_case one is the raw URL echo.
110
110
  */
@@ -180,8 +180,8 @@ export default class Attribution {
180
180
 
181
181
  /*
182
182
  * SHA-256 of the normalised email, hex encoded — the identifier every ad
183
- * platform's enhanced matching expects, and the key the conversion ledger
184
- * joins a booked meeting to the signup it later produced.
183
+ * platform's enhanced matching expects, and the key a receiver joins one
184
+ * person's conversions on.
185
185
  */
186
186
  public static hashEmail(email: string | undefined): string | null {
187
187
  const normalized: string | null = this.normalizeEmail(email);
@@ -12,8 +12,8 @@ const REQUEST_TIMEOUT_MS: number = 15000;
12
12
  /*
13
13
  * Delivers marketing conversion events to one operator-configured endpoint.
14
14
  *
15
- * OneUptime keeps no conversion ledger, so this is the only exit for a signup,
16
- * a booked meeting or a plan change. That has one consequence worth stating
15
+ * OneUptime keeps no conversion ledger, so this is the only exit for a signup
16
+ * or a plan change. That has one consequence worth stating
17
17
  * plainly: a delivery this class gives up on is gone, because there is no row
18
18
  * anywhere to reconcile against later. deliver() therefore THROWS on anything
19
19
  * that might succeed on a retry, and the queue is what retries it.
@@ -21,9 +21,8 @@ const REQUEST_TIMEOUT_MS: number = 15000;
21
21
  * SIGNING
22
22
  *
23
23
  * The signature is HMAC-SHA256 over the exact request body bytes, hex encoded,
24
- * in `x-oneuptime-signature-256`. This is the same scheme OneUptime verifies
25
- * on the way in from Cal, deliberately: one thing to understand rather than
26
- * two. The receiver must compute its digest over the raw bytes it received —
24
+ * in `x-oneuptime-signature-256`. The receiver must compute its digest over
25
+ * the raw bytes it received
27
26
  * JSON parsed and re-serialised is NOT equivalent, because whitespace, key
28
27
  * order and escaping all change the digest.
29
28
  *
@@ -0,0 +1,228 @@
1
+ import Dictionary from "../../../Types/Dictionary";
2
+ import OneUptimeDate from "../../../Types/Date";
3
+ import ObjectID from "../../../Types/ObjectID";
4
+ import { JSONArray, JSONObject } from "../../../Types/JSON";
5
+ /*
6
+ * Type-only: pulling the ingest service's runtime graph into this pure
7
+ * module would drag ClickHouse/DB deps into every test that touches it.
8
+ */
9
+ import type { TelemetryServiceMetadata } from "../../Services/OpenTelemetryIngestService";
10
+
11
+ /*
12
+ * Change-event ingest parsing + ClickHouse row building. Pure on purpose
13
+ * (no network, no request objects) so App/Tests can pin every validation
14
+ * rule without a server.
15
+ */
16
+
17
+ /*
18
+ * Events whose source timestamp is outside this window are stamped with
19
+ * the ingestion time instead (original preserved in attributes). The
20
+ * table partitions by toYYYYMMDD(time), so a forged or garbage timestamp
21
+ * must not be allowed to create arbitrary partitions.
22
+ */
23
+ export const MAX_CHANGE_EVENT_AGE_IN_DAYS: number = 366;
24
+ export const MAX_CHANGE_EVENT_FUTURE_SKEW_IN_MINUTES: number = 60;
25
+
26
+ // Caps keep a CI script's mistake from becoming a storage problem.
27
+ export const MAX_CHANGE_EVENTS_PER_REQUEST: number = 100;
28
+ export const MAX_CHANGE_EVENT_TITLE_LENGTH: number = 500;
29
+ export const MAX_CHANGE_EVENT_DESCRIPTION_LENGTH: number = 5000;
30
+ export const MAX_CHANGE_EVENT_TYPE_LENGTH: number = 50;
31
+ export const MAX_CHANGE_EVENT_ATTRIBUTES: number = 50;
32
+
33
+ export const DEFAULT_CHANGE_EVENT_TYPE: string = "deployment";
34
+
35
+ /*
36
+ * Serviceless change events (project-wide markers) have no service
37
+ * retention ladder to consult; deploy markers are tiny and valuable for
38
+ * long-baseline comparisons, so keep them a year.
39
+ */
40
+ export const DEFAULT_CHANGE_EVENT_RETENTION_IN_DAYS: number = 365;
41
+
42
+ export interface ParsedChangeEventEntry {
43
+ /** null → stamp with the ingestion time. */
44
+ time: Date | null;
45
+ eventType: string;
46
+ title: string;
47
+ description: string;
48
+ attributes: Dictionary<string>;
49
+ }
50
+
51
+ function parseEntryTime(value: unknown): Date | null {
52
+ if (typeof value === "number" && Number.isFinite(value)) {
53
+ /*
54
+ * Epoch seconds vs milliseconds: anything below 1e12 read as ms would
55
+ * be before 2001 — CI clocks don't say that; treat it as seconds.
56
+ */
57
+ const ms: number = value < 1e12 ? value * 1000 : value;
58
+ const date: Date = new Date(ms);
59
+ return Number.isNaN(date.getTime()) ? null : date;
60
+ }
61
+ if (typeof value === "string" && value.trim() !== "") {
62
+ const date: Date = new Date(value);
63
+ return Number.isNaN(date.getTime()) ? null : date;
64
+ }
65
+ return null;
66
+ }
67
+
68
+ /**
69
+ * Validate one raw ingest entry. Returns null when the entry cannot be a
70
+ * change event at all (no usable title); every other malformation is
71
+ * repaired (defaults, trims, caps) rather than rejected — CI pipelines
72
+ * should not fail a deploy over a long description.
73
+ */
74
+ export function parseChangeEventIngestEntry(
75
+ entry: JSONObject,
76
+ ): ParsedChangeEventEntry | null {
77
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
78
+ return null;
79
+ }
80
+
81
+ const rawTitle: unknown = entry["title"] ?? entry["name"];
82
+ const title: string =
83
+ typeof rawTitle === "string"
84
+ ? rawTitle.trim().slice(0, MAX_CHANGE_EVENT_TITLE_LENGTH)
85
+ : "";
86
+
87
+ if (title === "") {
88
+ return null;
89
+ }
90
+
91
+ const rawEventType: unknown = entry["eventType"] ?? entry["type"];
92
+ const eventType: string =
93
+ typeof rawEventType === "string" && rawEventType.trim() !== ""
94
+ ? rawEventType.trim().toLowerCase().slice(0, MAX_CHANGE_EVENT_TYPE_LENGTH)
95
+ : DEFAULT_CHANGE_EVENT_TYPE;
96
+
97
+ const rawDescription: unknown = entry["description"];
98
+ const description: string =
99
+ typeof rawDescription === "string"
100
+ ? rawDescription.trim().slice(0, MAX_CHANGE_EVENT_DESCRIPTION_LENGTH)
101
+ : "";
102
+
103
+ const attributes: Dictionary<string> = {};
104
+ const rawAttributes: unknown = entry["attributes"];
105
+ if (
106
+ rawAttributes &&
107
+ typeof rawAttributes === "object" &&
108
+ !Array.isArray(rawAttributes)
109
+ ) {
110
+ for (const key of Object.keys(rawAttributes as JSONObject)) {
111
+ if (key.trim() === "") {
112
+ continue;
113
+ }
114
+ if (Object.keys(attributes).length >= MAX_CHANGE_EVENT_ATTRIBUTES) {
115
+ break;
116
+ }
117
+ const value: unknown = (rawAttributes as JSONObject)[key];
118
+ if (
119
+ typeof value === "string" ||
120
+ typeof value === "number" ||
121
+ typeof value === "boolean"
122
+ ) {
123
+ attributes[key] = String(value);
124
+ }
125
+ }
126
+ }
127
+
128
+ return {
129
+ time: parseEntryTime(entry["time"] ?? entry["timestamp"]),
130
+ eventType,
131
+ title,
132
+ description,
133
+ attributes,
134
+ };
135
+ }
136
+
137
+ /**
138
+ * Accept the shapes CI scripts actually send: a bare object (one event),
139
+ * a bare array, or { events: [...] }.
140
+ */
141
+ export function extractChangeEventEntries(body: unknown): Array<JSONObject> {
142
+ if (!body) {
143
+ return [];
144
+ }
145
+
146
+ if (Array.isArray(body)) {
147
+ return (body as JSONArray).filter((item: unknown): boolean => {
148
+ return typeof item === "object" && item !== null && !Array.isArray(item);
149
+ }) as Array<JSONObject>;
150
+ }
151
+
152
+ if (typeof body !== "object") {
153
+ return [];
154
+ }
155
+
156
+ const asObject: JSONObject = body as JSONObject;
157
+ const nested: unknown = asObject["events"];
158
+ if (Array.isArray(nested)) {
159
+ return extractChangeEventEntries(nested);
160
+ }
161
+
162
+ // A single bare event object — but not the {events: <non-array>} shape.
163
+ if (nested === undefined && Object.keys(asObject).length > 0) {
164
+ return [asObject];
165
+ }
166
+
167
+ return [];
168
+ }
169
+
170
+ /**
171
+ * ParsedChangeEventEntry -> ChangeEvent ClickHouse row.
172
+ */
173
+ export function buildChangeEventDbRow(data: {
174
+ parsed: ParsedChangeEventEntry;
175
+ projectId: ObjectID;
176
+ serviceMetadata: TelemetryServiceMetadata | null;
177
+ retentionDays: number;
178
+ }): JSONObject {
179
+ const { parsed, projectId, serviceMetadata, retentionDays } = data;
180
+
181
+ const ingestionDate: Date = OneUptimeDate.getCurrentDate();
182
+
183
+ let eventTime: Date = parsed.time || ingestionDate;
184
+ let attributes: Dictionary<string> = { ...parsed.attributes };
185
+
186
+ const ageInDays: number = OneUptimeDate.getNumberOfDaysBetweenDates(
187
+ eventTime,
188
+ ingestionDate,
189
+ );
190
+ const futureSkewInMinutes: number =
191
+ (eventTime.getTime() - ingestionDate.getTime()) / (60 * 1000);
192
+
193
+ if (
194
+ Number.isNaN(eventTime.getTime()) ||
195
+ ageInDays > MAX_CHANGE_EVENT_AGE_IN_DAYS ||
196
+ futureSkewInMinutes > MAX_CHANGE_EVENT_FUTURE_SKEW_IN_MINUTES
197
+ ) {
198
+ attributes = {
199
+ ...attributes,
200
+ "oneuptime.original_time": String(parsed.time),
201
+ };
202
+ eventTime = ingestionDate;
203
+ }
204
+
205
+ const retentionDate: Date = OneUptimeDate.addRemoveDays(
206
+ ingestionDate,
207
+ retentionDays,
208
+ );
209
+
210
+ return {
211
+ _id: ObjectID.generateTimeOrdered().toString(),
212
+ createdAt: OneUptimeDate.toClickhouseDateTime(ingestionDate),
213
+ projectId: projectId.toString(),
214
+ ...(serviceMetadata
215
+ ? {
216
+ primaryEntityId: serviceMetadata.primaryEntityId.toString(),
217
+ primaryEntityType: serviceMetadata.primaryEntityType,
218
+ }
219
+ : {}),
220
+ time: OneUptimeDate.toClickhouseDateTime64(eventTime),
221
+ eventType: parsed.eventType,
222
+ title: parsed.title,
223
+ description: parsed.description,
224
+ attributes,
225
+ attributeKeys: Object.keys(attributes).sort(),
226
+ retentionDate: OneUptimeDate.toClickhouseDateTime(retentionDate),
227
+ } satisfies JSONObject;
228
+ }