@oneuptime/common 12.0.21 → 12.0.23

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 (94) hide show
  1. package/Models/DatabaseModels/Index.ts +4 -0
  2. package/Models/DatabaseModels/NetworkDevice.ts +44 -0
  3. package/Models/DatabaseModels/NetworkDeviceAutoImportRule.ts +564 -0
  4. package/Models/DatabaseModels/NetworkDeviceDiscoveryScan.ts +38 -0
  5. package/Models/DatabaseModels/UserTwoFactorBackupCode.ts +262 -0
  6. package/Server/API/UserTwoFactorBackupCodeAPI.ts +258 -0
  7. package/Server/Infrastructure/Postgres/SchemaMigrations/1789100000000-AddNetworkDeviceAutoImportRule.ts +60 -0
  8. package/Server/Infrastructure/Postgres/SchemaMigrations/1789100000000-AddUserTwoFactorBackupCode.ts +63 -0
  9. package/Server/Infrastructure/Postgres/SchemaMigrations/1789200000000-AddSysObjectIdPatternToAutoImportRule.ts +26 -0
  10. package/Server/Infrastructure/Postgres/SchemaMigrations/1789300000000-AddAutoApplyVendorHealthTemplate.ts +26 -0
  11. package/Server/Infrastructure/Postgres/SchemaMigrations/Index.ts +8 -0
  12. package/Server/Services/Index.ts +4 -0
  13. package/Server/Services/NetworkDeviceAutoImportRuleEngineService.ts +917 -0
  14. package/Server/Services/NetworkDeviceAutoImportRuleService.ts +181 -0
  15. package/Server/Services/UserService.ts +42 -0
  16. package/Server/Services/UserTwoFactorBackupCodeService.ts +355 -0
  17. package/Server/Utils/Monitor/NetworkInventoryUtil.ts +39 -1
  18. package/Server/Utils/TwoFactorBackupCode.ts +266 -0
  19. package/Tests/Server/API/UserAuthenticationAPI.test.ts +16 -3
  20. package/Tests/Server/API/UserTwoFactorAuthAdminAPI.test.ts +18 -2
  21. package/Tests/Server/API/UserTwoFactorBackupCodeAPI.test.ts +1390 -0
  22. package/Tests/Server/Services/AutoImportScanCredentialSelect.test.ts +205 -0
  23. package/Tests/Server/Services/NetworkDeviceAutoImportRuleEngineService.test.ts +933 -0
  24. package/Tests/Server/Services/UserAuthenticationService.test.ts +23 -1
  25. package/Tests/Server/Services/UserTwoFactorAuthAdmin.test.ts +21 -0
  26. package/Tests/Server/Services/UserTwoFactorBackupCodeAdminSurface.test.ts +919 -0
  27. package/Tests/Server/Services/UserTwoFactorBackupCodeService.test.ts +862 -0
  28. package/Tests/Server/Utils/Monitor/NetworkInventoryUtil.test.ts +97 -1
  29. package/Tests/Server/Utils/TwoFactorBackupCode.test.ts +475 -0
  30. package/Tests/Utils/NetworkDiscovery/AutoImportRuleMatcher.test.ts +516 -0
  31. package/Tests/Utils/NetworkDiscovery/DiscoveredDeviceBuilder.test.ts +272 -0
  32. package/Tests/Utils/NetworkDiscovery/ScanTargetUtil.test.ts +164 -0
  33. package/Types/Email/EmailTemplateType.ts +2 -0
  34. package/Types/NetworkAutomation/RuleRunResult.ts +84 -0
  35. package/Types/Permission.ts +47 -0
  36. package/Types/UserAuthenticationStatus.ts +16 -0
  37. package/Utils/NetworkDiscovery/AutoImportRuleMatcher.ts +257 -0
  38. package/Utils/NetworkDiscovery/DiscoveredDeviceBuilder.ts +183 -0
  39. package/Utils/NetworkDiscovery/DiscoveredHostUtil.ts +95 -0
  40. package/Utils/NetworkDiscovery/DiscoveryImportEligibility.ts +66 -0
  41. package/Utils/NetworkDiscovery/ScanTargetUtil.ts +82 -0
  42. package/build/dist/Models/DatabaseModels/Index.js +4 -0
  43. package/build/dist/Models/DatabaseModels/Index.js.map +1 -1
  44. package/build/dist/Models/DatabaseModels/NetworkDevice.js +45 -0
  45. package/build/dist/Models/DatabaseModels/NetworkDevice.js.map +1 -1
  46. package/build/dist/Models/DatabaseModels/NetworkDeviceAutoImportRule.js +589 -0
  47. package/build/dist/Models/DatabaseModels/NetworkDeviceAutoImportRule.js.map +1 -0
  48. package/build/dist/Models/DatabaseModels/NetworkDeviceDiscoveryScan.js +28 -0
  49. package/build/dist/Models/DatabaseModels/NetworkDeviceDiscoveryScan.js.map +1 -1
  50. package/build/dist/Models/DatabaseModels/UserTwoFactorBackupCode.js +277 -0
  51. package/build/dist/Models/DatabaseModels/UserTwoFactorBackupCode.js.map +1 -0
  52. package/build/dist/Server/API/UserTwoFactorBackupCodeAPI.js +201 -0
  53. package/build/dist/Server/API/UserTwoFactorBackupCodeAPI.js.map +1 -0
  54. package/build/dist/Server/Infrastructure/Postgres/SchemaMigrations/1789100000000-AddNetworkDeviceAutoImportRule.js +35 -0
  55. package/build/dist/Server/Infrastructure/Postgres/SchemaMigrations/1789100000000-AddNetworkDeviceAutoImportRule.js.map +1 -0
  56. package/build/dist/Server/Infrastructure/Postgres/SchemaMigrations/1789100000000-AddUserTwoFactorBackupCode.js +46 -0
  57. package/build/dist/Server/Infrastructure/Postgres/SchemaMigrations/1789100000000-AddUserTwoFactorBackupCode.js.map +1 -0
  58. package/build/dist/Server/Infrastructure/Postgres/SchemaMigrations/1789200000000-AddSysObjectIdPatternToAutoImportRule.js +19 -0
  59. package/build/dist/Server/Infrastructure/Postgres/SchemaMigrations/1789200000000-AddSysObjectIdPatternToAutoImportRule.js.map +1 -0
  60. package/build/dist/Server/Infrastructure/Postgres/SchemaMigrations/1789300000000-AddAutoApplyVendorHealthTemplate.js +19 -0
  61. package/build/dist/Server/Infrastructure/Postgres/SchemaMigrations/1789300000000-AddAutoApplyVendorHealthTemplate.js.map +1 -0
  62. package/build/dist/Server/Infrastructure/Postgres/SchemaMigrations/Index.js +8 -0
  63. package/build/dist/Server/Infrastructure/Postgres/SchemaMigrations/Index.js.map +1 -1
  64. package/build/dist/Server/Services/Index.js +4 -0
  65. package/build/dist/Server/Services/Index.js.map +1 -1
  66. package/build/dist/Server/Services/NetworkDeviceAutoImportRuleEngineService.js +711 -0
  67. package/build/dist/Server/Services/NetworkDeviceAutoImportRuleEngineService.js.map +1 -0
  68. package/build/dist/Server/Services/NetworkDeviceAutoImportRuleService.js +155 -0
  69. package/build/dist/Server/Services/NetworkDeviceAutoImportRuleService.js.map +1 -0
  70. package/build/dist/Server/Services/UserService.js +39 -0
  71. package/build/dist/Server/Services/UserService.js.map +1 -1
  72. package/build/dist/Server/Services/UserTwoFactorBackupCodeService.js +327 -0
  73. package/build/dist/Server/Services/UserTwoFactorBackupCodeService.js.map +1 -0
  74. package/build/dist/Server/Utils/Monitor/NetworkInventoryUtil.js +26 -0
  75. package/build/dist/Server/Utils/Monitor/NetworkInventoryUtil.js.map +1 -1
  76. package/build/dist/Server/Utils/TwoFactorBackupCode.js +269 -0
  77. package/build/dist/Server/Utils/TwoFactorBackupCode.js.map +1 -0
  78. package/build/dist/Types/Email/EmailTemplateType.js +2 -0
  79. package/build/dist/Types/Email/EmailTemplateType.js.map +1 -1
  80. package/build/dist/Types/NetworkAutomation/RuleRunResult.js +24 -0
  81. package/build/dist/Types/NetworkAutomation/RuleRunResult.js.map +1 -1
  82. package/build/dist/Types/Permission.js +41 -0
  83. package/build/dist/Types/Permission.js.map +1 -1
  84. package/build/dist/Utils/NetworkDiscovery/AutoImportRuleMatcher.js +149 -0
  85. package/build/dist/Utils/NetworkDiscovery/AutoImportRuleMatcher.js.map +1 -0
  86. package/build/dist/Utils/NetworkDiscovery/DiscoveredDeviceBuilder.js +121 -0
  87. package/build/dist/Utils/NetworkDiscovery/DiscoveredDeviceBuilder.js.map +1 -0
  88. package/build/dist/Utils/NetworkDiscovery/DiscoveredHostUtil.js +75 -0
  89. package/build/dist/Utils/NetworkDiscovery/DiscoveredHostUtil.js.map +1 -0
  90. package/build/dist/Utils/NetworkDiscovery/DiscoveryImportEligibility.js +59 -0
  91. package/build/dist/Utils/NetworkDiscovery/DiscoveryImportEligibility.js.map +1 -0
  92. package/build/dist/Utils/NetworkDiscovery/ScanTargetUtil.js +60 -0
  93. package/build/dist/Utils/NetworkDiscovery/ScanTargetUtil.js.map +1 -1
  94. package/package.json +1 -1
@@ -11,6 +11,10 @@ import SnmpInterface from "../../../../Types/Monitor/SnmpMonitor/SnmpInterface";
11
11
  import SnmpMonitorResponse from "../../../../Types/Monitor/SnmpMonitor/SnmpMonitorResponse";
12
12
  import LldpNeighbor from "../../../../Types/Monitor/SnmpMonitor/LldpNeighbor";
13
13
  import CdpNeighbor from "../../../../Types/Monitor/SnmpMonitor/CdpNeighbor";
14
+ import SnmpOid from "../../../../Types/Monitor/SnmpMonitor/SnmpOid";
15
+ import SnmpVendorTemplateUtil, {
16
+ SnmpVendorTemplate,
17
+ } from "../../../../Types/Monitor/SnmpMonitor/SnmpVendorTemplate";
14
18
 
15
19
  /*
16
20
  * NetworkInventoryUtil.updateFromWalk is the single writer that keeps the
@@ -40,14 +44,21 @@ let interfaceUpdateSpy: jest.SpyInstance;
40
44
  let interfaceCreateSpy: jest.SpyInstance;
41
45
  let endpointUpsertSpy: jest.SpyInstance;
42
46
 
43
- function mockServices(existingInterfaces: Array<NetworkInterface> = []): void {
47
+ function mockServices(
48
+ existingInterfaces: Array<NetworkInterface> = [],
49
+ deviceOverrides: Partial<NetworkDevice> = {},
50
+ ): void {
44
51
  /*
45
52
  * The project-membership guard resolves the device (scoped to the given
46
53
  * project) before any write; return a matching device so the write path
47
54
  * runs. The cross-project-refusal case overrides this to null.
55
+ * deviceOverrides seeds the columns the vendor-template auto-apply reads
56
+ * (autoApplyVendorHealthTemplate, snmpOids) — absent by default, exactly
57
+ * like a device that never opted in.
48
58
  */
49
59
  const ownedDevice: NetworkDevice = new NetworkDevice();
50
60
  ownedDevice.id = new ObjectID(DEVICE_ID);
61
+ Object.assign(ownedDevice, deviceOverrides);
51
62
  deviceFindSpy = jest
52
63
  .spyOn(NetworkDeviceService, "findOneBy")
53
64
  .mockResolvedValue(ownedDevice);
@@ -867,3 +878,88 @@ describe("NetworkInventoryUtil.updateFromWalk — endpoint discovery", () => {
867
878
  ]);
868
879
  });
869
880
  });
881
+
882
+ describe("NetworkInventoryUtil.updateFromWalk — vendor health template auto-apply", () => {
883
+ /*
884
+ * The automatic counterpart of the dashboard's vendor-template banner:
885
+ * a device that opted in (auto-imported devices do) gets its EMPTY Health
886
+ * OID list seeded from the vendor template its sysObjectID fingerprints,
887
+ * on the first poll that learns the vendor. An existing list — however it
888
+ * got there — is the operator's and is never touched.
889
+ */
890
+ test("an opted-in device with no health OIDs is seeded from the fingerprinted vendor template", async () => {
891
+ mockServices([], { autoApplyVendorHealthTemplate: true });
892
+
893
+ await runWalk({
894
+ systemInfo: {
895
+ sysObjectId: CISCO_SYS_OBJECT_ID,
896
+ },
897
+ });
898
+
899
+ const update: DeviceUpdatePayload = deviceUpdatePayload();
900
+ const seeded: Array<SnmpOid> = update["snmpOids"] as Array<SnmpOid>;
901
+
902
+ const ciscoTemplate: SnmpVendorTemplate | undefined =
903
+ SnmpVendorTemplateUtil.matchBySysObjectId(CISCO_SYS_OBJECT_ID);
904
+
905
+ expect(ciscoTemplate).toBeDefined();
906
+ expect(seeded).toEqual(ciscoTemplate!.oids);
907
+ expect(seeded.length).toBeGreaterThan(0);
908
+ });
909
+
910
+ test("a device that never opted in is not seeded", async () => {
911
+ mockServices();
912
+
913
+ await runWalk({
914
+ systemInfo: {
915
+ sysObjectId: CISCO_SYS_OBJECT_ID,
916
+ },
917
+ });
918
+
919
+ expect(deviceUpdatePayload()).not.toHaveProperty("snmpOids");
920
+ });
921
+
922
+ test("an existing health OID list is never touched, even with the toggle on", async () => {
923
+ const handPickedOids: Array<SnmpOid> = [
924
+ { oid: "1.3.6.1.4.1.9.9.109.1.1.1.1.7.1", name: "CPU 5min" },
925
+ ];
926
+
927
+ mockServices([], {
928
+ autoApplyVendorHealthTemplate: true,
929
+ snmpOids: handPickedOids,
930
+ });
931
+
932
+ await runWalk({
933
+ systemInfo: {
934
+ sysObjectId: CISCO_SYS_OBJECT_ID,
935
+ },
936
+ });
937
+
938
+ expect(deviceUpdatePayload()).not.toHaveProperty("snmpOids");
939
+ });
940
+
941
+ test("a walk that learned no sysObjectID seeds nothing", async () => {
942
+ mockServices([], { autoApplyVendorHealthTemplate: true });
943
+
944
+ await runWalk({
945
+ systemInfo: {
946
+ sysName: "core-sw-01",
947
+ },
948
+ });
949
+
950
+ expect(deviceUpdatePayload()).not.toHaveProperty("snmpOids");
951
+ });
952
+
953
+ test("an enterprise with no vendor template seeds nothing", async () => {
954
+ mockServices([], { autoApplyVendorHealthTemplate: true });
955
+
956
+ // Enterprise 99999 has no entry in ENTERPRISE_TEMPLATE_IDS.
957
+ await runWalk({
958
+ systemInfo: {
959
+ sysObjectId: "1.3.6.1.4.1.99999.1.1",
960
+ },
961
+ });
962
+
963
+ expect(deviceUpdatePayload()).not.toHaveProperty("snmpOids");
964
+ });
965
+ });
@@ -0,0 +1,475 @@
1
+ import TwoFactorBackupCode, {
2
+ BackupCodeAlphabet,
3
+ BackupCodeLength,
4
+ BackupCodeSetSize,
5
+ } from "../../../Server/Utils/TwoFactorBackupCode";
6
+ import { EncryptionSecret } from "../../../Server/EnvironmentConfig";
7
+ import ObjectID from "../../../Types/ObjectID";
8
+ import crypto from "crypto";
9
+ import { describe, expect, it } from "@jest/globals";
10
+
11
+ /*
12
+ * ---------------------------------------------------------------------------
13
+ * The code generation and hashing behind two factor backup codes.
14
+ *
15
+ * WHAT THIS FILE IS GUARDING
16
+ *
17
+ * A backup code is the last door into an account whose second factor is gone,
18
+ * so it fails in two directions and both are unacceptable:
19
+ *
20
+ * - too weak, and a caller who has the password guesses their way past two
21
+ * factor auth. The whole security argument for this feature rests on the
22
+ * code space being enormous, so the alphabet, the length and the uniformity
23
+ * of the draw are pinned here rather than left to a comment;
24
+ * - too strict, and a user who typed exactly the right code off a piece of
25
+ * paper is told it is wrong. Those users are, by definition, already locked
26
+ * out and already panicking, and every transcription rule the alphabet was
27
+ * designed around (I/1, L/1, O/0, the display hyphen, a lowercase phone
28
+ * keyboard) is a way to produce that failure if normalization drifts.
29
+ *
30
+ * NOTHING IS MOCKED. The point of these tests is the real crypto: real
31
+ * randomness from crypto.randomInt, real HMAC keyed by the real
32
+ * EnvironmentConfig secret. The expected digests are recomputed here from
33
+ * Node's crypto directly rather than by calling the function under test, so a
34
+ * change to the construction has to be a deliberate, visible one.
35
+ *
36
+ * The single-use SEMANTICS are not here -- they live in Postgres, and are
37
+ * covered by Common/Tests/Server/Services/UserTwoFactorBackupCodeService.test.ts.
38
+ * ---------------------------------------------------------------------------
39
+ */
40
+
41
+ const USER_ID: ObjectID = new ObjectID("11111111-1111-4111-8111-111111111111");
42
+ const OTHER_USER_ID: ObjectID = new ObjectID(
43
+ "22222222-2222-4222-8222-222222222222",
44
+ );
45
+
46
+ /*
47
+ * The digest, recomputed from the RFC primitives rather than from the module
48
+ * under test. If the construction in TwoFactorBackupCode.hashCode is changed,
49
+ * this stops matching -- which is the point: the digest of every stored code
50
+ * depends on it, so a silent change is a silent invalidation of every backup
51
+ * code every user is holding.
52
+ */
53
+ type ExpectedHashFunction = (data: {
54
+ code: string;
55
+ userId: ObjectID;
56
+ }) => string;
57
+
58
+ const expectedHash: ExpectedHashFunction = (data: {
59
+ code: string;
60
+ userId: ObjectID;
61
+ }): string => {
62
+ const parts: Array<string> = ["v1", data.userId.toString(), data.code];
63
+
64
+ const message: string = parts
65
+ .map((part: string) => {
66
+ return `${part.length}:${part}`;
67
+ })
68
+ .join("");
69
+
70
+ return crypto
71
+ .createHmac("sha256", EncryptionSecret.toString())
72
+ .update(message)
73
+ .digest("hex");
74
+ };
75
+
76
+ describe("TwoFactorBackupCode.generateCode -- the code space", () => {
77
+ it("draws only from the declared alphabet", () => {
78
+ const violations: Array<string> = [];
79
+
80
+ for (let attempt: number = 0; attempt < 200; attempt++) {
81
+ const code: string = TwoFactorBackupCode.generateCode();
82
+
83
+ for (const character of code) {
84
+ if (!BackupCodeAlphabet.includes(character)) {
85
+ violations.push(`${code} contains ${character}`);
86
+ }
87
+ }
88
+ }
89
+
90
+ expect(violations).toEqual([]);
91
+ });
92
+
93
+ it("is exactly BackupCodeLength characters long every time", () => {
94
+ const lengths: Set<number> = new Set<number>();
95
+
96
+ for (let attempt: number = 0; attempt < 200; attempt++) {
97
+ lengths.add(TwoFactorBackupCode.generateCode().length);
98
+ }
99
+
100
+ expect(Array.from(lengths)).toEqual([BackupCodeLength]);
101
+ });
102
+
103
+ /*
104
+ * The alphabet is not decoration. Every symbol it excludes is one a person
105
+ * transcribes wrongly off a printed list -- and `normalizeCode` MAPS those
106
+ * symbols onto their lookalikes, so a generator that emitted an `O` would
107
+ * produce a code that normalizes to a DIFFERENT code and can never be
108
+ * redeemed. The exclusion and the mapping have to stay in step.
109
+ */
110
+ it.each(["I", "L", "O", "U"])(
111
+ "never emits the ambiguous character %p",
112
+ (character: string) => {
113
+ expect(BackupCodeAlphabet).not.toContain(character);
114
+ },
115
+ );
116
+
117
+ it("has a 32 symbol alphabet, so ten characters is 2^50", () => {
118
+ expect(BackupCodeAlphabet.length).toBe(32);
119
+ expect(BackupCodeLength).toBe(10);
120
+
121
+ /*
122
+ * Stated as an assertion rather than a comment because the security case
123
+ * for this whole feature is this number. At 2^50 a caller holding the
124
+ * password guesses one of ten live codes with probability ~1e-14 per
125
+ * attempt; shortening the code or shrinking the alphabet would quietly
126
+ * move that into range of the rate limiter's budget.
127
+ */
128
+ expect(Math.pow(BackupCodeAlphabet.length, BackupCodeLength)).toBe(
129
+ Math.pow(2, 50),
130
+ );
131
+ });
132
+
133
+ /*
134
+ * A uniformity smoke test, not a statistical proof. It exists to catch the
135
+ * one realistic implementation slip -- a modulo reduction over a range that
136
+ * is not a multiple of the alphabet size, which biases the first few symbols
137
+ * and shrinks the effective key space. With 32000 draws every symbol should
138
+ * land ~1000 times; a biased implementation misses this by a mile.
139
+ */
140
+ it("draws every symbol, roughly uniformly", () => {
141
+ const counts: Map<string, number> = new Map<string, number>();
142
+
143
+ for (const character of BackupCodeAlphabet) {
144
+ counts.set(character, 0);
145
+ }
146
+
147
+ const drawCount: number = 3200;
148
+
149
+ for (let attempt: number = 0; attempt < drawCount; attempt++) {
150
+ for (const character of TwoFactorBackupCode.generateCode()) {
151
+ counts.set(character, (counts.get(character) || 0) + 1);
152
+ }
153
+ }
154
+
155
+ const totalDraws: number = drawCount * BackupCodeLength;
156
+ const expectedPerSymbol: number = totalDraws / BackupCodeAlphabet.length;
157
+
158
+ const violations: Array<string> = [];
159
+
160
+ for (const [character, count] of counts) {
161
+ if (count < expectedPerSymbol * 0.6 || count > expectedPerSymbol * 1.4) {
162
+ violations.push(
163
+ `${character}: ${count} (expected ~${expectedPerSymbol})`,
164
+ );
165
+ }
166
+ }
167
+
168
+ expect(violations).toEqual([]);
169
+ });
170
+
171
+ it("does not repeat itself", () => {
172
+ const codes: Set<string> = new Set<string>();
173
+
174
+ for (let attempt: number = 0; attempt < 500; attempt++) {
175
+ codes.add(TwoFactorBackupCode.generateCode());
176
+ }
177
+
178
+ expect(codes.size).toBe(500);
179
+ });
180
+ });
181
+
182
+ describe("TwoFactorBackupCode.generateCodeSet", () => {
183
+ it("issues BackupCodeSetSize codes by default", () => {
184
+ expect(TwoFactorBackupCode.generateCodeSet()).toHaveLength(
185
+ BackupCodeSetSize,
186
+ );
187
+ });
188
+
189
+ it("honours an explicit count", () => {
190
+ expect(TwoFactorBackupCode.generateCodeSet(3)).toHaveLength(3);
191
+ });
192
+
193
+ /*
194
+ * Duplicates inside one set would not weaken the code space -- they would
195
+ * break SINGLE USE. Two rows sharing a digest means consuming one leaves an
196
+ * identical, still-unspent second row behind, so a code advertised as
197
+ * one-time would work twice.
198
+ */
199
+ it("never issues the same code twice in one set", () => {
200
+ for (let attempt: number = 0; attempt < 50; attempt++) {
201
+ const codes: Array<string> = TwoFactorBackupCode.generateCodeSet();
202
+
203
+ expect(new Set(codes).size).toBe(codes.length);
204
+ }
205
+ });
206
+ });
207
+
208
+ describe("TwoFactorBackupCode.formatForDisplay", () => {
209
+ it("splits a ten character code into two groups of five", () => {
210
+ expect(TwoFactorBackupCode.formatForDisplay("ABCDE12345")).toBe(
211
+ "ABCDE-12345",
212
+ );
213
+ });
214
+
215
+ /*
216
+ * The hyphen is cosmetic and must survive the round trip, or every code we
217
+ * show the user is a code they cannot type back in.
218
+ */
219
+ it("produces something normalizeCode maps back to the original", () => {
220
+ const violations: Array<string> = [];
221
+
222
+ for (let attempt: number = 0; attempt < 200; attempt++) {
223
+ const code: string = TwoFactorBackupCode.generateCode();
224
+ const displayed: string = TwoFactorBackupCode.formatForDisplay(code);
225
+
226
+ if (TwoFactorBackupCode.normalizeCode(displayed) !== code) {
227
+ violations.push(`${code} -> ${displayed}`);
228
+ }
229
+ }
230
+
231
+ expect(violations).toEqual([]);
232
+ });
233
+ });
234
+
235
+ describe("TwoFactorBackupCode.normalizeCode -- what a locked-out user types", () => {
236
+ it("accepts the code exactly as displayed", () => {
237
+ expect(TwoFactorBackupCode.normalizeCode("ABCDE-12345")).toBe("ABCDE12345");
238
+ });
239
+
240
+ it.each([
241
+ ["lowercase from a phone keyboard", "abcde-12345", "ABCDE12345"],
242
+ ["no hyphen at all", "ABCDE12345", "ABCDE12345"],
243
+ ["a space where the hyphen was", "ABCDE 12345", "ABCDE12345"],
244
+ ["leading and trailing whitespace", " ABCDE-12345 ", "ABCDE12345"],
245
+ ["a clipboard that inserted newlines", "ABCDE\n12345", "ABCDE12345"],
246
+ ["mixed case and stray punctuation", "aB.cD/e-1 2345", "ABCDE12345"],
247
+ ])("handles %s", (_label: string, raw: string, expected: string) => {
248
+ expect(TwoFactorBackupCode.normalizeCode(raw)).toBe(expected);
249
+ });
250
+
251
+ /*
252
+ * Crockford's transcription rules. These are the ONLY reason the alphabet
253
+ * drops these letters -- if the mapping went away, the exclusion would just
254
+ * be an arbitrary restriction and a user reading `0` as `O` off a printout
255
+ * would be told their code is invalid.
256
+ */
257
+ it.each([
258
+ ["O", "0"],
259
+ ["o", "0"],
260
+ ["I", "1"],
261
+ ["i", "1"],
262
+ ["L", "1"],
263
+ ["l", "1"],
264
+ ])("maps the lookalike %p to %p", (typed: string, canonical: string) => {
265
+ expect(TwoFactorBackupCode.normalizeCode(typed)).toBe(canonical);
266
+ });
267
+
268
+ /*
269
+ * `U` is excluded from the alphabet with no lookalike to map onto, so it is
270
+ * dropped rather than translated. Pinned so that nobody "helpfully" maps it
271
+ * to V later and changes what a submitted code means.
272
+ */
273
+ it("drops U rather than mapping it", () => {
274
+ expect(TwoFactorBackupCode.normalizeCode("UUU")).toBe("");
275
+ });
276
+
277
+ /*
278
+ * The code arrives straight off a JSON body, so it is only a string because
279
+ * the caller chose to make it one. Anything else must fail verification
280
+ * rather than throw out of the normalizer and surface as a 500 -- an
281
+ * unhandled exception on the login path is both an availability bug and a
282
+ * way to tell requests apart.
283
+ */
284
+ it.each([[undefined], [null], [12345], [{}], [[]], [true]])(
285
+ "returns empty for the non-string input %p",
286
+ (raw: unknown) => {
287
+ expect(TwoFactorBackupCode.normalizeCode(raw as string)).toBe("");
288
+ },
289
+ );
290
+
291
+ it("returns empty for a string with nothing usable in it", () => {
292
+ expect(TwoFactorBackupCode.normalizeCode(" --- ")).toBe("");
293
+ });
294
+ });
295
+
296
+ describe("TwoFactorBackupCode.hashCode", () => {
297
+ it("matches an independently computed HMAC", () => {
298
+ const code: string = "ABCDE12345";
299
+
300
+ expect(TwoFactorBackupCode.hashCode({ code: code, userId: USER_ID })).toBe(
301
+ expectedHash({ code: code, userId: USER_ID }),
302
+ );
303
+ });
304
+
305
+ it("is deterministic, which is what lets a code be looked up by digest", () => {
306
+ const code: string = TwoFactorBackupCode.generateCode();
307
+
308
+ expect(TwoFactorBackupCode.hashCode({ code: code, userId: USER_ID })).toBe(
309
+ TwoFactorBackupCode.hashCode({ code: code, userId: USER_ID }),
310
+ );
311
+ });
312
+
313
+ /*
314
+ * Domain separation. Without it, one precomputed table inverts every
315
+ * account's codes at once, and two users issued the same code would be
316
+ * visibly linked by identical rows.
317
+ */
318
+ it("gives two users different digests for the same code", () => {
319
+ const code: string = "ABCDE12345";
320
+
321
+ expect(
322
+ TwoFactorBackupCode.hashCode({ code: code, userId: USER_ID }),
323
+ ).not.toBe(
324
+ TwoFactorBackupCode.hashCode({ code: code, userId: OTHER_USER_ID }),
325
+ );
326
+ });
327
+
328
+ /*
329
+ * The digest is computed over the NORMALIZED code, not the raw submission.
330
+ * If it were not, a user who typed their code with the hyphen would hash to
331
+ * something that matches nothing -- the exact lockout the normalizer exists
332
+ * to prevent, moved one function along.
333
+ */
334
+ it.each(["ABCDE-12345", "abcde12345", " abcde-12345 ", "ABCDE 12345"])(
335
+ "hashes %p to the same digest as the canonical form",
336
+ (raw: string) => {
337
+ expect(TwoFactorBackupCode.hashCode({ code: raw, userId: USER_ID })).toBe(
338
+ TwoFactorBackupCode.hashCode({
339
+ code: "ABCDE12345",
340
+ userId: USER_ID,
341
+ }),
342
+ );
343
+ },
344
+ );
345
+
346
+ it("produces 64 hex characters, which fits the ShortText column", () => {
347
+ const digest: string = TwoFactorBackupCode.hashCode({
348
+ code: TwoFactorBackupCode.generateCode(),
349
+ userId: USER_ID,
350
+ });
351
+
352
+ expect(digest).toMatch(/^[0-9a-f]{64}$/);
353
+ expect(digest.length).toBeLessThanOrEqual(100);
354
+ });
355
+
356
+ /*
357
+ * Length prefixing. Without it, concatenation is ambiguous: a userId of
358
+ * "ab" with code "cd" and a userId of "abc" with code "d" would produce the
359
+ * same message and therefore the same digest.
360
+ */
361
+ it("cannot be confused by rearranging the boundary between user and code", () => {
362
+ const first: string = TwoFactorBackupCode.hashCode({
363
+ code: "CD",
364
+ userId: new ObjectID("ab"),
365
+ });
366
+
367
+ const second: string = TwoFactorBackupCode.hashCode({
368
+ code: "D",
369
+ userId: new ObjectID("abc"),
370
+ });
371
+
372
+ expect(first).not.toBe(second);
373
+ });
374
+
375
+ /*
376
+ * The plaintext must not be recoverable from the digest by anything short of
377
+ * brute force -- in particular, the digest must not merely BE the code, or
378
+ * contain it, which is the shape a careless "hash" refactor tends to take.
379
+ */
380
+ it("does not contain the code it was computed from", () => {
381
+ const code: string = TwoFactorBackupCode.generateCode();
382
+
383
+ const digest: string = TwoFactorBackupCode.hashCode({
384
+ code: code,
385
+ userId: USER_ID,
386
+ });
387
+
388
+ expect(digest).not.toContain(code);
389
+ expect(digest).not.toContain(code.toLowerCase());
390
+ });
391
+
392
+ it("changes completely when a single character of the code changes", () => {
393
+ const a: string = TwoFactorBackupCode.hashCode({
394
+ code: "ABCDE12345",
395
+ userId: USER_ID,
396
+ });
397
+
398
+ const b: string = TwoFactorBackupCode.hashCode({
399
+ code: "ABCDE12346",
400
+ userId: USER_ID,
401
+ });
402
+
403
+ expect(a).not.toBe(b);
404
+ });
405
+
406
+ it("hashes an empty code to something no real code can collide with", () => {
407
+ /*
408
+ * An empty submission still produces a digest here -- the refusal lives in
409
+ * the service, which never gets this far. What matters is that the digest
410
+ * of "" is not the digest of any generated code, so a caller sending an
411
+ * empty string can never match a row even if a future caller forgets the
412
+ * guard.
413
+ */
414
+ const emptyDigest: string = TwoFactorBackupCode.hashCode({
415
+ code: "",
416
+ userId: USER_ID,
417
+ });
418
+
419
+ const violations: Array<string> = [];
420
+
421
+ for (let attempt: number = 0; attempt < 100; attempt++) {
422
+ const code: string = TwoFactorBackupCode.generateCode();
423
+
424
+ if (
425
+ TwoFactorBackupCode.hashCode({ code: code, userId: USER_ID }) ===
426
+ emptyDigest
427
+ ) {
428
+ violations.push(code);
429
+ }
430
+ }
431
+
432
+ expect(violations).toEqual([]);
433
+ });
434
+ });
435
+
436
+ describe("TwoFactorBackupCode.isHashEqual", () => {
437
+ it("accepts two identical digests", () => {
438
+ const digest: string = TwoFactorBackupCode.hashCode({
439
+ code: "ABCDE12345",
440
+ userId: USER_ID,
441
+ });
442
+
443
+ expect(TwoFactorBackupCode.isHashEqual(digest, digest)).toBe(true);
444
+ });
445
+
446
+ it("rejects two different digests", () => {
447
+ expect(
448
+ TwoFactorBackupCode.isHashEqual(
449
+ TwoFactorBackupCode.hashCode({ code: "AAAAA11111", userId: USER_ID }),
450
+ TwoFactorBackupCode.hashCode({ code: "BBBBB22222", userId: USER_ID }),
451
+ ),
452
+ ).toBe(false);
453
+ });
454
+
455
+ /*
456
+ * crypto.timingSafeEqual THROWS on a length mismatch, so the length check in
457
+ * front of it is not an optimisation -- without it, a short or malformed
458
+ * value turns a failed comparison into a 500 on the login path.
459
+ */
460
+ it.each([
461
+ ["", ""],
462
+ ["abc", ""],
463
+ ["", "abc"],
464
+ ["abc", "abcd"],
465
+ ])(
466
+ "returns false rather than throwing for (%p, %p)",
467
+ (a: string, b: string) => {
468
+ expect(() => {
469
+ return TwoFactorBackupCode.isHashEqual(a, b);
470
+ }).not.toThrow();
471
+
472
+ expect(TwoFactorBackupCode.isHashEqual(a, b)).toBe(false);
473
+ },
474
+ );
475
+ });