@stamhoofd/models 2.137.4 → 2.138.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 (157) hide show
  1. package/dist/helpers/Handlebars.d.ts.map +1 -1
  2. package/dist/helpers/Handlebars.js +1 -1
  3. package/dist/helpers/Handlebars.js.map +1 -1
  4. package/dist/helpers/errorToSimpleErrors.d.ts +3 -0
  5. package/dist/helpers/errorToSimpleErrors.d.ts.map +1 -0
  6. package/dist/helpers/errorToSimpleErrors.js +17 -0
  7. package/dist/helpers/errorToSimpleErrors.js.map +1 -0
  8. package/dist/index.d.ts +0 -1
  9. package/dist/index.d.ts.map +1 -1
  10. package/dist/index.js +0 -1
  11. package/dist/index.js.map +1 -1
  12. package/dist/migrations/1782902314-tokens-authenticated-at.sql +2 -0
  13. package/dist/migrations/1782902315-create-mfa-totp-table.sql +13 -0
  14. package/dist/migrations/1782902316-create-webauthn-credentials-table.sql +17 -0
  15. package/dist/migrations/1782902317-create-mfa-recovery-codes-table.sql +10 -0
  16. package/dist/migrations/1782902318-create-mfa-tokens-table.sql +13 -0
  17. package/dist/migrations/1782902319-create-webauthn-challenges-table.sql +10 -0
  18. package/dist/migrations/1784039947-mfa-totp-last-used-counter.sql +2 -0
  19. package/dist/migrations/1784122354-webauthn-credential-provider.sql +3 -0
  20. package/dist/migrations/1784500000-webauthn-credential-rp-id.sql +9 -0
  21. package/dist/migrations/1785354091-platform-parent-tenant-id.sql +1 -0
  22. package/dist/migrations/1785354092-platform-fees-tenant-id.sql +1 -0
  23. package/dist/migrations/1785354093-platform-uri.sql +1 -0
  24. package/dist/migrations/1785354094-platform-domain.sql +1 -0
  25. package/dist/migrations/1785354095-platform-uri-unique.sql +1 -0
  26. package/dist/migrations/1785354096-platform-domain-unique.sql +1 -0
  27. package/dist/migrations/1785354097-platform-parent-tenant-id-index.sql +1 -0
  28. package/dist/migrations/1785354098-platform-tenant-backfill.d.ts +4 -0
  29. package/dist/migrations/1785354098-platform-tenant-backfill.d.ts.map +1 -0
  30. package/dist/migrations/1785354098-platform-tenant-backfill.js +10 -0
  31. package/dist/migrations/1785354098-platform-tenant-backfill.js.map +1 -0
  32. package/dist/migrations/1785417301-users-last-active-at.sql +2 -0
  33. package/dist/models/Document.d.ts +0 -4
  34. package/dist/models/Document.d.ts.map +1 -1
  35. package/dist/models/Document.js +1 -75
  36. package/dist/models/Document.js.map +1 -1
  37. package/dist/models/DocumentTemplate.d.ts +0 -3
  38. package/dist/models/DocumentTemplate.d.ts.map +1 -1
  39. package/dist/models/DocumentTemplate.js +1 -63
  40. package/dist/models/DocumentTemplate.js.map +1 -1
  41. package/dist/models/Email.d.ts +1 -29
  42. package/dist/models/Email.d.ts.map +1 -1
  43. package/dist/models/Email.js +4 -823
  44. package/dist/models/Email.js.map +1 -1
  45. package/dist/models/EmailVerificationCode.d.ts +0 -5
  46. package/dist/models/EmailVerificationCode.d.ts.map +1 -1
  47. package/dist/models/EmailVerificationCode.js +0 -84
  48. package/dist/models/EmailVerificationCode.js.map +1 -1
  49. package/dist/models/Image.d.ts.map +1 -1
  50. package/dist/models/Image.js +11 -14
  51. package/dist/models/Image.js.map +1 -1
  52. package/dist/models/MFARecoveryCode.d.ts +17 -0
  53. package/dist/models/MFARecoveryCode.d.ts.map +1 -0
  54. package/dist/models/MFARecoveryCode.js +55 -0
  55. package/dist/models/MFARecoveryCode.js.map +1 -0
  56. package/dist/models/MFATOTP.d.ts +44 -0
  57. package/dist/models/MFATOTP.d.ts.map +1 -0
  58. package/dist/models/MFATOTP.js +116 -0
  59. package/dist/models/MFATOTP.js.map +1 -0
  60. package/dist/models/MFAToken.d.ts +49 -0
  61. package/dist/models/MFAToken.d.ts.map +1 -0
  62. package/dist/models/MFAToken.js +137 -0
  63. package/dist/models/MFAToken.js.map +1 -0
  64. package/dist/models/MemberPlatformMembership.d.ts +0 -8
  65. package/dist/models/MemberPlatformMembership.d.ts.map +1 -1
  66. package/dist/models/MemberPlatformMembership.js +1 -242
  67. package/dist/models/MemberPlatformMembership.js.map +1 -1
  68. package/dist/models/Order.d.ts +1 -32
  69. package/dist/models/Order.d.ts.map +1 -1
  70. package/dist/models/Order.js +1 -182
  71. package/dist/models/Order.js.map +1 -1
  72. package/dist/models/Organization.d.ts +1 -51
  73. package/dist/models/Organization.d.ts.map +1 -1
  74. package/dist/models/Organization.js +1 -530
  75. package/dist/models/Organization.js.map +1 -1
  76. package/dist/models/PasswordToken.d.ts +0 -8
  77. package/dist/models/PasswordToken.d.ts.map +1 -1
  78. package/dist/models/PasswordToken.js +0 -23
  79. package/dist/models/PasswordToken.js.map +1 -1
  80. package/dist/models/Platform.d.ts +28 -4
  81. package/dist/models/Platform.d.ts.map +1 -1
  82. package/dist/models/Platform.js +111 -50
  83. package/dist/models/Platform.js.map +1 -1
  84. package/dist/models/STPackage.d.ts +1 -6
  85. package/dist/models/STPackage.d.ts.map +1 -1
  86. package/dist/models/STPackage.js +1 -98
  87. package/dist/models/STPackage.js.map +1 -1
  88. package/dist/models/Token.d.ts +40 -1
  89. package/dist/models/Token.d.ts.map +1 -1
  90. package/dist/models/Token.js +68 -2
  91. package/dist/models/Token.js.map +1 -1
  92. package/dist/models/User.d.ts +25 -0
  93. package/dist/models/User.d.ts.map +1 -1
  94. package/dist/models/User.js +36 -0
  95. package/dist/models/User.js.map +1 -1
  96. package/dist/models/WebauthnChallenge.d.ts +27 -0
  97. package/dist/models/WebauthnChallenge.d.ts.map +1 -0
  98. package/dist/models/WebauthnChallenge.js +81 -0
  99. package/dist/models/WebauthnChallenge.js.map +1 -0
  100. package/dist/models/WebauthnCredential.d.ts +58 -0
  101. package/dist/models/WebauthnCredential.d.ts.map +1 -0
  102. package/dist/models/WebauthnCredential.js +144 -0
  103. package/dist/models/WebauthnCredential.js.map +1 -0
  104. package/dist/models/index.d.ts +5 -0
  105. package/dist/models/index.d.ts.map +1 -1
  106. package/dist/models/index.js +5 -0
  107. package/dist/models/index.js.map +1 -1
  108. package/package.json +3 -3
  109. package/src/helpers/Handlebars.ts +5 -9
  110. package/src/helpers/errorToSimpleErrors.ts +17 -0
  111. package/src/index.ts +0 -1
  112. package/src/migrations/1782902314-tokens-authenticated-at.sql +2 -0
  113. package/src/migrations/1782902315-create-mfa-totp-table.sql +13 -0
  114. package/src/migrations/1782902316-create-webauthn-credentials-table.sql +17 -0
  115. package/src/migrations/1782902317-create-mfa-recovery-codes-table.sql +10 -0
  116. package/src/migrations/1782902318-create-mfa-tokens-table.sql +13 -0
  117. package/src/migrations/1782902319-create-webauthn-challenges-table.sql +10 -0
  118. package/src/migrations/1784039947-mfa-totp-last-used-counter.sql +2 -0
  119. package/src/migrations/1784122354-webauthn-credential-provider.sql +3 -0
  120. package/src/migrations/1784500000-webauthn-credential-rp-id.sql +9 -0
  121. package/src/migrations/1785354091-platform-parent-tenant-id.sql +1 -0
  122. package/src/migrations/1785354092-platform-fees-tenant-id.sql +1 -0
  123. package/src/migrations/1785354093-platform-uri.sql +1 -0
  124. package/src/migrations/1785354094-platform-domain.sql +1 -0
  125. package/src/migrations/1785354095-platform-uri-unique.sql +1 -0
  126. package/src/migrations/1785354096-platform-domain-unique.sql +1 -0
  127. package/src/migrations/1785354097-platform-parent-tenant-id-index.sql +1 -0
  128. package/src/migrations/1785354098-platform-tenant-backfill.ts +14 -0
  129. package/src/migrations/1785417301-users-last-active-at.sql +2 -0
  130. package/src/models/Document.ts +1 -84
  131. package/src/models/DocumentTemplate.ts +1 -71
  132. package/src/models/Email.ts +5 -941
  133. package/src/models/EmailVerificationCode.ts +0 -96
  134. package/src/models/Image.ts +11 -14
  135. package/src/models/MFARecoveryCode.ts +52 -0
  136. package/src/models/MFATOTP.ts +112 -0
  137. package/src/models/MFAToken.ts +138 -0
  138. package/src/models/MemberPlatformMembership.ts +1 -285
  139. package/src/models/Order.ts +1 -204
  140. package/src/models/Organization.ts +2 -637
  141. package/src/models/PasswordToken.ts +0 -29
  142. package/src/models/Platform.test.ts +167 -3
  143. package/src/models/Platform.ts +125 -50
  144. package/src/models/STPackage.ts +1 -110
  145. package/src/models/Token.ts +73 -2
  146. package/src/models/User.ts +37 -0
  147. package/src/models/WebauthnChallenge.ts +80 -0
  148. package/src/models/WebauthnCredential.ts +130 -0
  149. package/src/models/index.ts +6 -0
  150. package/dist/helpers/EmailBuilder.d.ts +0 -121
  151. package/dist/helpers/EmailBuilder.d.ts.map +0 -1
  152. package/dist/helpers/EmailBuilder.js +0 -659
  153. package/dist/helpers/EmailBuilder.js.map +0 -1
  154. package/src/helpers/EmailBuilder.test.ts +0 -291
  155. package/src/helpers/EmailBuilder.ts +0 -818
  156. package/src/models/Email.test.ts +0 -1222
  157. package/src/models/MemberPlatformMembership.test.ts +0 -70
@@ -1,15 +1,10 @@
1
1
  import { column } from '@simonbackx/simple-database';
2
2
  import { SimpleError } from '@simonbackx/simple-errors';
3
- import type { I18n } from '@stamhoofd/backend-i18n';
4
3
  import { QueryableModel } from '@stamhoofd/sql';
5
- import { appToUri, EmailTemplateType, getAppHost, Recipient, Replacement } from '@stamhoofd/structures';
6
4
  import basex from 'base-x';
7
5
  import crypto from 'crypto';
8
6
  import { v4 as uuidv4 } from 'uuid';
9
- import { sendEmailTemplate } from '../helpers/EmailBuilder.js';
10
- import { Platform } from './Platform.js';
11
7
  import type { User } from './User.js';
12
- import type { Organization } from './Organization.js';
13
8
 
14
9
  const ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
15
10
  const bs58 = basex(ALPHABET);
@@ -120,11 +115,6 @@ export class EmailVerificationCode extends QueryableModel {
120
115
  this.expiresAt = new Date(new Date().getTime() + 1000 * 60 * 60 * 12);
121
116
  }
122
117
 
123
- getEmailVerificationUrl(user: User, organization: Organization | null, i18n: I18n) {
124
- const host = getAppHost('verify-email', organization, !!user.permissions, i18n);
125
- return 'https://' + host + '?code=' + encodeURIComponent(this.code) + '&token=' + encodeURIComponent(this.token) + '&email=' + encodeURIComponent(this.email);
126
- }
127
-
128
118
  /**
129
119
  * Return true if this token is still valid (used for automatic polling in code view)
130
120
  */
@@ -234,92 +224,6 @@ export class EmailVerificationCode extends QueryableModel {
234
224
  }
235
225
  }
236
226
 
237
- async send(user: User, organization: Organization | null, i18n: I18n, withCode = true) {
238
- const url = this.getEmailVerificationUrl(user, organization, i18n);
239
-
240
- const name = organization?.name ?? (await Platform.getSharedPrivateStruct()).config.name;
241
-
242
- const replacements: Replacement[] = [
243
- Replacement.create({
244
- token: 'organizationName',
245
- value: name,
246
- }),
247
- Replacement.create({
248
- token: 'confirmEmailUrl',
249
- value: url,
250
- }),
251
- ];
252
-
253
- if (withCode) {
254
- const formattedCode = this.code.substr(0, 3) + ' ' + this.code.substr(3);
255
-
256
- await sendEmailTemplate(organization, {
257
- recipients: [
258
- Recipient.create({
259
- email: this.email,
260
- replacements: [
261
- ...replacements,
262
- Replacement.create({
263
- token: 'confirmEmailCode',
264
- value: formattedCode,
265
- }),
266
- ],
267
- }),
268
- ],
269
- template: {
270
- type: EmailTemplateType.VerifyEmail,
271
- },
272
- type: 'transactional',
273
- });
274
- } else {
275
- await sendEmailTemplate(organization, {
276
- recipients: [
277
- Recipient.create({
278
- email: this.email,
279
- replacements,
280
- }),
281
- ],
282
- template: {
283
- type: EmailTemplateType.VerifyEmailWithoutCode,
284
- },
285
- type: 'transactional',
286
- });
287
- }
288
- }
289
-
290
- static async resend(organization: Organization | null, token: string, i18n: I18n) {
291
- const verificationCodes = await this.where({
292
- token,
293
- organizationId: organization
294
- ? {
295
- sign: 'IN',
296
- value: [organization.id, null],
297
- }
298
- : null,
299
- }, { limit: 1 });
300
-
301
- if (verificationCodes.length == 0) {
302
- console.log("Can't resend code, no coded found for token", token);
303
- // TODO: maybe send a note via email
304
- return;
305
- }
306
-
307
- const verificationCode = verificationCodes[0];
308
-
309
- if (verificationCode.expiresAt < new Date()) {
310
- // Don't report error, could be brute forced
311
- console.log("Can't resend code, token is expired", token);
312
- return;
313
- }
314
-
315
- const { User } = await import('./User.js');
316
- const user = await User.getByID(verificationCode.userId);
317
- if (!user) {
318
- return;
319
- }
320
- await verificationCode.send(user, organization, i18n);
321
- }
322
-
323
227
  /**
324
228
  * Create or reuse a verification code for a given email address
325
229
  * If needed, it will update the code.
@@ -4,7 +4,7 @@ import { ArrayDecoder } from '@simonbackx/simple-encoding';
4
4
  import { SimpleError } from '@simonbackx/simple-errors';
5
5
  import { QueryableModel } from '@stamhoofd/sql';
6
6
  import type { ResolutionRequest } from '@stamhoofd/structures';
7
- import { File, Resolution } from '@stamhoofd/structures';
7
+ import { File, Resolution, supportedImageTypes } from '@stamhoofd/structures';
8
8
  import sharp from 'sharp';
9
9
  import { v4 as uuidv4 } from 'uuid';
10
10
 
@@ -51,20 +51,14 @@ export class Image extends QueryableModel {
51
51
  });
52
52
  }
53
53
 
54
- let fileType = 'png';
55
- if (type == 'image/jpeg' || type == 'image/jpg') {
56
- fileType = 'jpg';
57
- }
58
- if (type == 'image/webp') {
59
- fileType = 'webp';
60
- }
61
- if (type === 'image/svg+xml' || type === 'image/svg') {
62
- fileType = 'svg';
63
- }
54
+ // Fall back to png for content types we don't recognize: sharp detects the real format itself, so
55
+ // this only decides how we store the file
56
+ const imageType = (type ? supportedImageTypes.resolveUpload({ contentType: type }) : null) ?? { contentType: 'image/png', extension: 'png' };
57
+ const fileType = imageType.extension;
64
58
 
65
59
  console.log('creating image', fileType, type, resolutions);
66
60
 
67
- const supportsTransparency = fileType == 'png' || fileType == 'svg' || fileType == 'webp';
61
+ const supportsTransparency = fileType !== 'jpg';
68
62
  const promises: Promise<{ data: Buffer;info: sharp.OutputInfo }>[] = [];
69
63
 
70
64
  if (resolutions.length) {
@@ -78,7 +72,7 @@ export class Image extends QueryableModel {
78
72
  width: r.width ?? undefined,
79
73
  height: r.height ?? undefined,
80
74
  fit: r.fit,
81
- withoutEnlargement: type !== 'image/svg+xml',
75
+ withoutEnlargement: fileType !== 'svg',
82
76
  };
83
77
 
84
78
  let t = sharpStream.resize(size);
@@ -181,7 +175,10 @@ export class Image extends QueryableModel {
181
175
  Bucket: STAMHOOFD.SPACES_BUCKET,
182
176
  Key: key,
183
177
  Body: fileContent,
184
- ContentType: type ?? 'image/jpeg',
178
+ // Never store the content type reported by the uploader: this is the only file we store
179
+ // unaltered, so it should never be rendered by a browser
180
+ ContentType: imageType.contentType,
181
+ ContentDisposition: 'attachment',
185
182
  ACL: 'private',
186
183
  });
187
184
  uploadPromises.push(client.send(cmd));
@@ -0,0 +1,52 @@
1
+ import { column } from '@simonbackx/simple-database';
2
+ import { QueryableModel } from '@stamhoofd/sql';
3
+ import { v4 as uuidv4 } from 'uuid';
4
+
5
+ /**
6
+ * A single-use recovery (backup) code. Only the Argon2 hash is stored. A user has one
7
+ * active batch; regenerating deletes the old batch.
8
+ */
9
+ export class MFARecoveryCode extends QueryableModel {
10
+ static table = 'mfa_recovery_codes';
11
+
12
+ @column({
13
+ primary: true, type: 'string', beforeSave(value) {
14
+ return value ?? uuidv4();
15
+ },
16
+ })
17
+ id!: string;
18
+
19
+ @column({ type: 'string' })
20
+ userId: string;
21
+
22
+ @column({ type: 'string' })
23
+ codeHash: string;
24
+
25
+ @column({ type: 'datetime', nullable: true })
26
+ usedAt: Date | null = null;
27
+
28
+ @column({
29
+ type: 'datetime', beforeSave(old?: any) {
30
+ if (old !== undefined) {
31
+ return old;
32
+ }
33
+ const date = new Date();
34
+ date.setMilliseconds(0);
35
+ return date;
36
+ },
37
+ })
38
+ createdAt: Date;
39
+
40
+ static async getForUser(userId: string): Promise<MFARecoveryCode[]> {
41
+ return await this.select().where('userId', userId).fetch();
42
+ }
43
+
44
+ static async getUnusedForUser(userId: string): Promise<MFARecoveryCode[]> {
45
+ const all = await this.getForUser(userId);
46
+ return all.filter(c => c.usedAt === null);
47
+ }
48
+
49
+ static async deleteForUser(userId: string): Promise<void> {
50
+ await this.delete().where('userId', userId);
51
+ }
52
+ }
@@ -0,0 +1,112 @@
1
+ import { column } from '@simonbackx/simple-database';
2
+ import { QueryableModel, SQL, SQLNull, SQLScalar, SQLWhereEqual, SQLWhereOr, SQLWhereSign } from '@stamhoofd/sql';
3
+ import { v4 as uuidv4 } from 'uuid';
4
+
5
+ /**
6
+ * A single TOTP authenticator enrolled by a user. A user may have multiple.
7
+ * The `secret` is stored encrypted at rest (see EncryptionHelper).
8
+ */
9
+ export class MFATOTP extends QueryableModel {
10
+ static table = 'mfa_totp';
11
+
12
+ @column({
13
+ primary: true, type: 'string', beforeSave(value) {
14
+ return value ?? uuidv4();
15
+ },
16
+ })
17
+ id!: string;
18
+
19
+ @column({ type: 'string' })
20
+ userId: string;
21
+
22
+ @column({ type: 'string' })
23
+ name = '';
24
+
25
+ /**
26
+ * The encrypted base32 TOTP secret.
27
+ */
28
+ @column({ type: 'string' })
29
+ secret: string;
30
+
31
+ /**
32
+ * Null until the user has verified their first code. Unconfirmed rows do not count
33
+ * as an enrolled factor.
34
+ */
35
+ @column({ type: 'datetime', nullable: true })
36
+ confirmedAt: Date | null = null;
37
+
38
+ @column({ type: 'datetime', nullable: true })
39
+ lastUsedAt: Date | null = null;
40
+
41
+ /**
42
+ * The last accepted TOTP step counter. A code may only be accepted if its counter is
43
+ * strictly greater than this, so a still-valid code cannot be replayed (RFC 6238 §5.2).
44
+ */
45
+ @column({ type: 'integer', nullable: true })
46
+ lastUsedCounter: number | null = null;
47
+
48
+ @column({
49
+ type: 'datetime', beforeSave(old?: any) {
50
+ if (old !== undefined) {
51
+ return old;
52
+ }
53
+ const date = new Date();
54
+ date.setMilliseconds(0);
55
+ return date;
56
+ },
57
+ })
58
+ createdAt: Date;
59
+
60
+ @column({
61
+ type: 'datetime', beforeSave() {
62
+ const date = new Date();
63
+ date.setMilliseconds(0);
64
+ return date;
65
+ },
66
+ skipUpdate: true,
67
+ })
68
+ updatedAt: Date;
69
+
70
+ /**
71
+ * Record `counter` as the last accepted step, but only when no other request claimed
72
+ * the same or a newer one first. Returns false when it was already claimed: two logins
73
+ * that submit the same still-valid code at the same time must not both succeed
74
+ * (RFC 6238 §5.2), so the claim has to happen in a single conditional UPDATE instead of
75
+ * a read followed by a write.
76
+ */
77
+ async claimCounter(counter: number): Promise<boolean> {
78
+ const { changedRows } = await MFATOTP.update()
79
+ .set('lastUsedCounter', counter)
80
+ .set('lastUsedAt', new Date())
81
+ .where('id', this.id)
82
+ .where(new SQLWhereOr([
83
+ new SQLWhereEqual(SQL.column('lastUsedCounter'), SQLWhereSign.Equal, new SQLNull()),
84
+ new SQLWhereEqual(SQL.column('lastUsedCounter'), SQLWhereSign.Less, new SQLScalar(counter)),
85
+ ]))
86
+ .update();
87
+
88
+ if (changedRows !== 1) {
89
+ return false;
90
+ }
91
+
92
+ this.lastUsedCounter = counter;
93
+ return true;
94
+ }
95
+
96
+ static async getForUser(userId: string): Promise<MFATOTP[]> {
97
+ return await this.select().where('userId', userId).fetch();
98
+ }
99
+
100
+ static async getConfirmedForUser(userId: string): Promise<MFATOTP[]> {
101
+ const all = await this.getForUser(userId);
102
+ return all.filter(t => t.confirmedAt !== null);
103
+ }
104
+
105
+ /**
106
+ * Remove abandoned, never-confirmed authenticators (e.g. from earlier setup attempts
107
+ * that were never completed) so they don't accumulate as orphaned rows.
108
+ */
109
+ static async deleteUnconfirmedForUser(userId: string): Promise<void> {
110
+ await this.delete().where('userId', userId).where('confirmedAt', null);
111
+ }
112
+ }
@@ -0,0 +1,138 @@
1
+ import { column } from '@simonbackx/simple-database';
2
+ import { QueryableModel, SQLCalculation, SQLColumnExpression, SQLScalar, SQLWhereSign } from '@stamhoofd/sql';
3
+ import crypto from 'crypto';
4
+
5
+ export type MFATokenPurpose = 'login' | 'setup';
6
+
7
+ /**
8
+ * A short-lived, single-use session token issued during a login that requires a second
9
+ * factor ('login') or forced 2FA enrollment ('setup'). Mirrors EmailVerificationCode.
10
+ */
11
+ export class MFAToken extends QueryableModel {
12
+ static table = 'mfa_tokens';
13
+ static MAX_TRIES = 5;
14
+ static EXPIRY_MS = 15 * 60 * 1000;
15
+
16
+ @column({ primary: true, type: 'string' })
17
+ token: string;
18
+
19
+ @column({ type: 'string' })
20
+ userId: string;
21
+
22
+ @column({ type: 'string' })
23
+ purpose: MFATokenPurpose = 'login';
24
+
25
+ @column({ type: 'integer' })
26
+ tries = 0;
27
+
28
+ /**
29
+ * The pending WebAuthn authentication challenge for passkey login (if any).
30
+ */
31
+ @column({ type: 'string', nullable: true })
32
+ webauthnChallenge: string | null = null;
33
+
34
+ @column({ type: 'datetime' })
35
+ expiresAt: Date;
36
+
37
+ @column({
38
+ type: 'datetime', beforeSave(old?: any) {
39
+ if (old !== undefined) {
40
+ return old;
41
+ }
42
+ const date = new Date();
43
+ date.setMilliseconds(0);
44
+ return date;
45
+ },
46
+ })
47
+ createdAt: Date;
48
+
49
+ @column({
50
+ type: 'datetime', beforeSave() {
51
+ const date = new Date();
52
+ date.setMilliseconds(0);
53
+ return date;
54
+ },
55
+ skipUpdate: true,
56
+ })
57
+ updatedAt: Date;
58
+
59
+ static async createFor(userId: string, purpose: MFATokenPurpose, webauthnChallenge: string | null = null): Promise<MFAToken> {
60
+ // A new attempt supersedes the previous one. Without this, every single login
61
+ // attempt of a user with 2FA leaves a row behind (anyone who knows the password
62
+ // can create them at will), and the abandoned tokens stay usable until they
63
+ // expire. Only one challenge per purpose can be outstanding at a time.
64
+ await this.delete().where('userId', userId).where('purpose', purpose).delete();
65
+
66
+ const model = new MFAToken();
67
+ model.token = crypto.randomBytes(48).toString('base64url');
68
+ model.userId = userId;
69
+ model.purpose = purpose;
70
+ model.webauthnChallenge = webauthnChallenge;
71
+ model.expiresAt = new Date(Date.now() + MFAToken.EXPIRY_MS);
72
+ await model.save();
73
+ return model;
74
+ }
75
+
76
+ /**
77
+ * Remove every expired token. Tokens are also dropped when they are looked up after
78
+ * expiring, but a token that is never used again would stay behind forever.
79
+ */
80
+ static async deleteExpired(): Promise<number> {
81
+ const { affectedRows } = await this.delete().where('expiresAt', SQLWhereSign.Less, new Date()).delete();
82
+ return affectedRows;
83
+ }
84
+
85
+ isExpired(): boolean {
86
+ return this.expiresAt < new Date();
87
+ }
88
+
89
+ /**
90
+ * Look up a valid, non-expired, non-locked token for the given purpose. Deletes it if
91
+ * expired. Does not consume it (call consume() after a successful verification).
92
+ */
93
+ static async getValid(token: string, purpose: MFATokenPurpose): Promise<MFAToken | undefined> {
94
+ if (!token) {
95
+ return undefined;
96
+ }
97
+ const model = await this.select().where('token', token).first(false);
98
+ if (!model || model.purpose !== purpose) {
99
+ return undefined;
100
+ }
101
+ if (model.isExpired()) {
102
+ await model.delete();
103
+ return undefined;
104
+ }
105
+ if (model.tries >= MFAToken.MAX_TRIES) {
106
+ return undefined;
107
+ }
108
+ return model;
109
+ }
110
+
111
+ /**
112
+ * Register a failed attempt. Returns true if the token is now locked out.
113
+ *
114
+ * The counter is incremented in the database rather than read-modify-written, so that
115
+ * guesses sent in parallel each cost a try. Reading the value first would let an
116
+ * attacker fire MAX_TRIES requests at once and have them all write back `1`.
117
+ */
118
+ async registerFailedAttempt(): Promise<boolean> {
119
+ await MFAToken.update()
120
+ .set('tries', new SQLCalculation(new SQLColumnExpression('tries')).add(new SQLScalar(1)))
121
+ .where('token', this.token)
122
+ .update();
123
+
124
+ const updated = await MFAToken.select().where('token', this.token).first(false);
125
+ this.tries = updated?.tries ?? this.tries + 1;
126
+ return this.tries >= MFAToken.MAX_TRIES;
127
+ }
128
+
129
+ /**
130
+ * Claim this token. Returns false when another request already consumed it: a single
131
+ * challenge may only ever hand out one session, even when two requests verify the same
132
+ * second factor at the same time.
133
+ */
134
+ async consume(): Promise<boolean> {
135
+ const { affectedRows } = await MFAToken.delete().where('token', this.token).delete();
136
+ return affectedRows === 1;
137
+ }
138
+ }