@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,6 +1,6 @@
1
1
  import type { ManyToOneRelation } from '@simonbackx/simple-database';
2
2
  import { column, Database } from '@simonbackx/simple-database';
3
- import { QueryableModel } from '@stamhoofd/sql';
3
+ import { QueryableModel, SQLWhereSign } from '@stamhoofd/sql';
4
4
  import { ApiUser } from '@stamhoofd/structures';
5
5
  import crypto from 'crypto';
6
6
 
@@ -25,6 +25,12 @@ export class Token extends QueryableModel {
25
25
  static table = 'tokens';
26
26
  static MAX_DEVICES = 15;
27
27
 
28
+ /**
29
+ * How long after authentication a token still counts as "fresh" for sensitive
30
+ * actions (e.g. managing 2FA methods).
31
+ */
32
+ static FRESH_WINDOW = 10 * 60 * 1000;
33
+
28
34
  @column({ type: 'string' })
29
35
  userId: string;
30
36
 
@@ -41,6 +47,14 @@ export class Token extends QueryableModel {
41
47
  @column({ type: 'datetime' })
42
48
  refreshTokenValidUntil: Date;
43
49
 
50
+ /**
51
+ * When set, this token was minted by a real authentication (password, mfa, passkey,
52
+ * password_token) at this time. Tokens created by a refresh_token rotation leave this
53
+ * NULL. Used by Context.authenticateFresh() to gate sensitive actions (2FA management).
54
+ */
55
+ @column({ type: 'datetime', nullable: true })
56
+ authenticatedAt: Date | null = null;
57
+
44
58
  @column({
45
59
  type: 'datetime', beforeSave(old?: any) {
46
60
  if (old !== undefined) {
@@ -69,6 +83,57 @@ export class Token extends QueryableModel {
69
83
  return this.accessTokenValidUntil < new Date() || this.refreshTokenValidUntil < new Date();
70
84
  }
71
85
 
86
+ /**
87
+ * A token is fresh if it was minted by a real authentication (not a refresh) within
88
+ * the FRESH_WINDOW. Sensitive endpoints require a fresh token.
89
+ */
90
+ isFresh(): boolean {
91
+ return this.authenticatedAt !== null && this.authenticatedAt.getTime() > Date.now() - Token.FRESH_WINDOW;
92
+ }
93
+
94
+ /**
95
+ * Sign out every session of a user, except the one the request was made with.
96
+ *
97
+ * Used after a security-relevant change to the account (enrolling or removing a
98
+ * two-factor method): sessions that were created before that change should not
99
+ * survive it. API users are excluded — their tokens are machine credentials that are
100
+ * managed separately, not browser sessions.
101
+ */
102
+ static async deleteOtherSessions(userId: string, keepAccessToken: string | null): Promise<number> {
103
+ const user = await User.getByID(userId);
104
+ if (user?.isApiUser) {
105
+ return 0;
106
+ }
107
+
108
+ const query = this.delete().where('userId', userId);
109
+ if (keepAccessToken) {
110
+ query.where(this.primary.name, SQLWhereSign.NotEqual, keepAccessToken);
111
+ }
112
+ const { affectedRows } = await query.delete();
113
+ return affectedRows;
114
+ }
115
+
116
+ /**
117
+ * Sign out every session of the given users, except the one the request was made with.
118
+ *
119
+ * Used when an administrator forces all admins to sign in again, e.g. right after
120
+ * making two-factor authentication required. Unlike deleteOtherSessions() the caller
121
+ * is responsible for leaving out API users, because it already has the list of users
122
+ * it wants to sign out.
123
+ */
124
+ static async deleteForUsers(userIds: string[], keepAccessToken: string | null): Promise<number> {
125
+ if (userIds.length === 0) {
126
+ return 0;
127
+ }
128
+
129
+ const query = this.delete().where('userId', userIds);
130
+ if (keepAccessToken) {
131
+ query.where(this.primary.name, SQLWhereSign.NotEqual, keepAccessToken);
132
+ }
133
+ const { affectedRows } = await query.delete();
134
+ return affectedRows;
135
+ }
136
+
72
137
  static async getAPIUserWithToken(user: User) {
73
138
  if (!user.isApiUser) {
74
139
  throw new Error('Unexpected user type');
@@ -227,8 +292,14 @@ export class Token extends QueryableModel {
227
292
  return token;
228
293
  }
229
294
 
230
- static async createToken<U extends User>(user: U): Promise<(Token & { user: U })> {
295
+ /**
296
+ * @param authenticatedAt Pass the current date when this token is minted by a real
297
+ * authentication (password/mfa/passkey/password_token) so it counts as "fresh".
298
+ * Leave null (default) for refresh_token rotations.
299
+ */
300
+ static async createToken<U extends User>(user: U, authenticatedAt: Date | null = null): Promise<(Token & { user: U })> {
231
301
  const token = await this.createUnsavedToken(user);
302
+ token.authenticatedAt = authenticatedAt;
232
303
  await token.save();
233
304
  return token;
234
305
  }
@@ -78,6 +78,14 @@ export class User extends QueryableModel {
78
78
  })
79
79
  updatedAt: Date;
80
80
 
81
+ /**
82
+ * The last time this user signed in or refreshed their session. Only set once a full
83
+ * session is handed out, so a login that is still waiting for its second factor does
84
+ * not count as activity.
85
+ */
86
+ @column({ type: 'datetime', nullable: true })
87
+ lastActiveAt: Date | null = null;
88
+
81
89
  get name() {
82
90
  if (this.firstName && this.lastName) {
83
91
  return this.firstName + ' ' + this.lastName;
@@ -320,6 +328,19 @@ export class User extends QueryableModel {
320
328
  return false;
321
329
  }
322
330
 
331
+ /**
332
+ * Whether this account may use passkeys as a second factor.
333
+ *
334
+ * A passkey is bound to one domain (the dashboard domain, see getWebauthnRpId), and it
335
+ * cannot be moved to another one: the authenticator will simply not hand it over. Users
336
+ * that belong to a single organization are expected to move to a per-organization
337
+ * authentication domain, which would strand every passkey they enrolled here, so they
338
+ * are kept on the factors that survive such a move (authenticator apps, recovery codes).
339
+ */
340
+ canUsePasskeys(): boolean {
341
+ return this.organizationId === null && !this.isApiUser;
342
+ }
343
+
323
344
  protected hasKeys() {
324
345
  if (this.password) {
325
346
  // Users with a password are 'real' users. Always.
@@ -549,6 +570,21 @@ export class User extends QueryableModel {
549
570
  this.password = await User.hash(password);
550
571
  }
551
572
 
573
+ /**
574
+ * Remember that the user was active right now: they signed in, or refreshed their
575
+ * session.
576
+ *
577
+ * Written with a direct query instead of save(): this runs on every token refresh, so
578
+ * it should not bump updatedAt or write out other (possibly stale) properties of the
579
+ * model.
580
+ */
581
+ async markActive() {
582
+ const date = new Date();
583
+ date.setMilliseconds(0);
584
+ await User.update().set('lastActiveAt', date).where('id', this.id).update();
585
+ this.lastActiveAt = date;
586
+ }
587
+
552
588
  getStructure() {
553
589
  return UserStruct.create({
554
590
  firstName: this.firstName,
@@ -561,6 +597,7 @@ export class User extends QueryableModel {
561
597
  hasPassword: this.hasPasswordBasedAccount(),
562
598
  memberId: this.memberId,
563
599
  organizationId: this.organizationId,
600
+ lastActiveAt: this.lastActiveAt,
564
601
  });
565
602
  }
566
603
 
@@ -0,0 +1,80 @@
1
+ import { column } from '@simonbackx/simple-database';
2
+ import { QueryableModel, SQLWhereSign } from '@stamhoofd/sql';
3
+ import { v4 as uuidv4 } from 'uuid';
4
+
5
+ /**
6
+ * A short-lived, single-use WebAuthn registration challenge for a logged-in user, kept
7
+ * server-side so the registration response can be verified against it.
8
+ */
9
+ export class WebauthnChallenge extends QueryableModel {
10
+ static table = 'webauthn_challenges';
11
+ static EXPIRY_MS = 10 * 60 * 1000;
12
+
13
+ @column({
14
+ primary: true, type: 'string', beforeSave(value) {
15
+ return value ?? uuidv4();
16
+ },
17
+ })
18
+ id!: string;
19
+
20
+ @column({ type: 'string' })
21
+ userId: string;
22
+
23
+ @column({ type: 'string' })
24
+ challenge: string;
25
+
26
+ @column({ type: 'datetime' })
27
+ expiresAt: Date;
28
+
29
+ @column({
30
+ type: 'datetime', beforeSave(old?: any) {
31
+ if (old !== undefined) {
32
+ return old;
33
+ }
34
+ const date = new Date();
35
+ date.setMilliseconds(0);
36
+ return date;
37
+ },
38
+ })
39
+ createdAt: Date;
40
+
41
+ static async createFor(userId: string, challenge: string): Promise<WebauthnChallenge> {
42
+ // Only keep one pending registration challenge per user
43
+ await this.delete().where('userId', userId);
44
+
45
+ const model = new WebauthnChallenge();
46
+ model.userId = userId;
47
+ model.challenge = challenge;
48
+ model.expiresAt = new Date(Date.now() + WebauthnChallenge.EXPIRY_MS);
49
+ await model.save();
50
+ return model;
51
+ }
52
+
53
+ isExpired(): boolean {
54
+ return this.expiresAt < new Date();
55
+ }
56
+
57
+ /**
58
+ * Remove every expired challenge. A registration that was started and then abandoned
59
+ * leaves a row behind that nothing else cleans up.
60
+ */
61
+ static async deleteExpired(): Promise<number> {
62
+ const { affectedRows } = await this.delete().where('expiresAt', SQLWhereSign.Less, new Date()).delete();
63
+ return affectedRows;
64
+ }
65
+
66
+ /**
67
+ * Consume the latest pending challenge for a user. Returns the challenge string, or
68
+ * undefined if none valid. Always deletes the row.
69
+ */
70
+ static async consumeForUser(userId: string): Promise<string | undefined> {
71
+ const model = await this.select().where('userId', userId).first(false);
72
+ if (!model) {
73
+ return undefined;
74
+ }
75
+ const challenge = model.challenge;
76
+ const expired = model.isExpired();
77
+ await model.delete();
78
+ return expired ? undefined : challenge;
79
+ }
80
+ }
@@ -0,0 +1,130 @@
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 passkey / WebAuthn credential enrolled by a user. A user may have multiple.
7
+ * `credentialId` is unique and indexed so credentials can be looked up directly (needed
8
+ * for future usernameless/passwordless login).
9
+ */
10
+ export class WebauthnCredential extends QueryableModel {
11
+ static table = 'webauthn_credentials';
12
+
13
+ @column({
14
+ primary: true, type: 'string', beforeSave(value) {
15
+ return value ?? uuidv4();
16
+ },
17
+ })
18
+ id!: string;
19
+
20
+ @column({ type: 'string' })
21
+ userId: string;
22
+
23
+ /**
24
+ * Base64url-encoded credential id, as returned by the authenticator.
25
+ */
26
+ @column({ type: 'string' })
27
+ credentialId: string;
28
+
29
+ /**
30
+ * The Relying Party ID this credential was created for.
31
+ *
32
+ * A passkey is bound to one domain: the authenticator will not release it to any other
33
+ * one, and verification has to check it against the RP ID it was made for. Storing it
34
+ * per credential is what keeps existing passkeys valid if the platform ever serves more
35
+ * than one authentication domain, or moves to a different one.
36
+ *
37
+ * NULL for credentials created before this was stored: those all used the platform RP
38
+ * ID, which the helper falls back to.
39
+ */
40
+ @column({ type: 'string', nullable: true })
41
+ rpId: string | null = null;
42
+
43
+ /**
44
+ * Base64url-encoded COSE public key.
45
+ */
46
+ @column({ type: 'string' })
47
+ publicKey: string;
48
+
49
+ @column({ type: 'integer' })
50
+ counter = 0;
51
+
52
+ /**
53
+ * JSON-encoded array of AuthenticatorTransport values (or null).
54
+ */
55
+ @column({ type: 'string', nullable: true })
56
+ transports: string | null = null;
57
+
58
+ /**
59
+ * The WebAuthn backup state (BS) flag: whether this credential is currently backed up.
60
+ */
61
+ @column({ type: 'boolean' })
62
+ backedUp = false;
63
+
64
+ /**
65
+ * The WebAuthn backup eligibility (BE) flag: whether this credential may ever be backed
66
+ * up (a synced passkey) or is bound to one device.
67
+ *
68
+ * Stored next to `backedUp` because it cannot be derived from it, and a different
69
+ * library would expect both halves of the pair.
70
+ */
71
+ @column({ type: 'boolean' })
72
+ backupEligible = false;
73
+
74
+ @column({ type: 'string' })
75
+ name = '';
76
+
77
+ @column({ type: 'string', nullable: true })
78
+ providerId: string | null = null;
79
+
80
+ @column({ type: 'string', nullable: true })
81
+ providerName: string | null = null;
82
+
83
+ @column({ type: 'datetime', nullable: true })
84
+ lastUsedAt: Date | null = null;
85
+
86
+ @column({
87
+ type: 'datetime', beforeSave(old?: any) {
88
+ if (old !== undefined) {
89
+ return old;
90
+ }
91
+ const date = new Date();
92
+ date.setMilliseconds(0);
93
+ return date;
94
+ },
95
+ })
96
+ createdAt: Date;
97
+
98
+ @column({
99
+ type: 'datetime', beforeSave() {
100
+ const date = new Date();
101
+ date.setMilliseconds(0);
102
+ return date;
103
+ },
104
+ skipUpdate: true,
105
+ })
106
+ updatedAt: Date;
107
+
108
+ get transportsArray(): string[] | undefined {
109
+ if (!this.transports) {
110
+ return undefined;
111
+ }
112
+ try {
113
+ const parsed = JSON.parse(this.transports);
114
+ return Array.isArray(parsed) ? parsed : undefined;
115
+ } catch (e) {
116
+ return undefined;
117
+ }
118
+ }
119
+
120
+ static async getForUser(userId: string): Promise<WebauthnCredential[]> {
121
+ return await this.select().where('userId', userId).fetch();
122
+ }
123
+
124
+ static async getByCredentialId(credentialId: string): Promise<WebauthnCredential | undefined> {
125
+ if (!credentialId) {
126
+ return undefined;
127
+ }
128
+ return (await this.select().where('credentialId', credentialId).first(false)) ?? undefined;
129
+ }
130
+ }
@@ -7,6 +7,12 @@ export { User } from './User.js';
7
7
 
8
8
  export * from './EmailVerificationCode.js';
9
9
 
10
+ export * from './MFAToken.js';
11
+ export * from './MFATOTP.js';
12
+ export * from './MFARecoveryCode.js';
13
+ export * from './WebauthnCredential.js';
14
+ export * from './WebauthnChallenge.js';
15
+
10
16
  export { BalanceItem } from './BalanceItem.js';
11
17
  export { BalanceItemPayment } from './BalanceItemPayment.js';
12
18
  export * from './BuckarooPayment.js';
@@ -1,121 +0,0 @@
1
- import type { EmailBuilder, EmailInterfaceRecipient } from '@stamhoofd/email';
2
- import type { EmailContent, EmailRecipient as EmailRecipientStruct, EmailTemplateType, Platform as PlatformStruct, Recipient } from '@stamhoofd/structures';
3
- import { Replacement } from '@stamhoofd/structures';
4
- import type { Language } from '@stamhoofd/types/Language';
5
- import { I18n } from '@stamhoofd/backend-i18n/I18n';
6
- import { EmailRecipient } from '../models/EmailRecipient.js';
7
- import { EmailTemplate } from '../models/EmailTemplate.js';
8
- import type { Group } from '../models/Group.js';
9
- import type { Organization } from '../models/Organization.js';
10
- import type { Webshop } from '../models/Webshop.js';
11
- export type EmailTemplateOptions = {
12
- type: EmailTemplateType;
13
- webshop?: Webshop | null;
14
- group?: Group | null;
15
- organizationId?: string | null;
16
- };
17
- export declare function getEmailTemplate(data: EmailTemplateOptions): Promise<EmailTemplate | undefined>;
18
- export declare function canSendFromEmail(fromAddress: string, organization: Organization | null): Promise<boolean>;
19
- export declare function getDefaultEmailFrom(organization: Organization | null, options: Pick<EmailBuilderOptions, 'type'> & {
20
- template: Omit<EmailTemplateOptions, 'organizationId' | 'type'>;
21
- }): Promise<{
22
- from: EmailInterfaceRecipient;
23
- replyTo: EmailInterfaceRecipient | undefined;
24
- }>;
25
- export declare function sendEmailTemplate(organization: Organization | null, options: Omit<EmailBuilderOptions, 'subject' | 'html' | 'from' | 'replyTo'> & {
26
- template: Omit<EmailTemplateOptions, 'organizationId'>;
27
- }): Promise<void>;
28
- export type EmailBuilderOptions = {
29
- defaultReplacements?: Replacement[];
30
- recipients: Recipient[];
31
- from: EmailInterfaceRecipient;
32
- replyTo?: EmailInterfaceRecipient | null;
33
- subject: string;
34
- html: string;
35
- /**
36
- * Full content overrides per language. Recipients with a language that has an override
37
- * receive that content, all others receive the default subject/html.
38
- */
39
- translations?: Map<Language, EmailContent>;
40
- attachments?: {
41
- filename: string;
42
- path?: string;
43
- href?: string;
44
- content?: string | Buffer;
45
- contentType?: string;
46
- encoding?: string;
47
- }[];
48
- type?: 'transactional' | 'broadcast';
49
- unsubscribeType?: 'all' | 'marketing';
50
- fromStamhoofd?: boolean;
51
- singleBcc?: EmailInterfaceRecipient;
52
- replaceAll?: {
53
- from: string;
54
- to: string;
55
- }[];
56
- callback?: (error: Error | null) => void;
57
- headers?: Record<string, string>;
58
- };
59
- /**
60
- * @param organization defines replacements and unsubsribe behaviour
61
- */
62
- export declare function getEmailBuilder(organization: Organization | null, email: EmailBuilderOptions): Promise<EmailBuilder>;
63
- export declare function mergeReplacement(replacementA: Replacement, replacementB: Replacement): Replacement | false;
64
- /**
65
- * Remove duplicates
66
- */
67
- export declare function cleanReplacements(replacements: Replacement[]): Replacement[];
68
- export declare function removeUnusedReplacements(html: string, replacements: Replacement[]): Replacement[];
69
- export declare function mergeReplacementsIfEqual(replacementsA: Replacement[], replacementsB: Replacement[]): Replacement[] | false;
70
- /**
71
- * Filter replacements for display in the backend.
72
- * @param options.forPreview if true, it will hide sensitive information in the preview that could leak information to admin users
73
- */
74
- export declare function stripSensitiveRecipientReplacements(recipient: Recipient | EmailRecipientStruct | EmailRecipient, options: {
75
- organization: Organization | null;
76
- willFill?: boolean;
77
- }): void;
78
- /**
79
- * Fill and hide replacements that don't make sense for web display to the user
80
- */
81
- export declare function stripRecipientReplacementsForWebDisplay(recipient: Recipient | EmailRecipientStruct | EmailRecipient, options: {
82
- organization: Organization | null;
83
- }): void;
84
- /**
85
- * Build the I18n an email should be rendered in for a specific recipient.
86
- *
87
- * Falls back to the current (ambient) locale when the recipient has no language set — so flows
88
- * that already established a locale (order emails wrapped in I18n.runWithLocale, or the request
89
- * locale) keep working unchanged.
90
- */
91
- export declare function getRecipientI18n(recipient: {
92
- language?: Language | null;
93
- }, organization: Organization | null, options?: {
94
- allowedLanguages?: Language[] | null;
95
- }): I18n;
96
- /**
97
- * Render everything inside `handler` in the recipient's language: all $t / $getLanguage /
98
- * $getCountry calls (and therefore every generated replacement) use the recipient's locale.
99
- *
100
- * This is the single place that binds "a recipient" to "its language" when generating email
101
- * content. Generate recipient replacements inside this wrapper so new replacements are localized
102
- * automatically, and pass the provided i18n to helpers that take an explicit locale (e.g. getAppHost).
103
- */
104
- export declare function runWithRecipientLocale<T>(recipient: {
105
- language?: Language | null;
106
- }, organization: Organization | null, handler: (i18n: I18n) => T, options?: {
107
- allowedLanguages?: Language[] | null;
108
- }): T;
109
- /**
110
- * @param options.forPreview if true, it will hide sensitive information in the preview that could leak information to admin users
111
- */
112
- export declare function fillRecipientReplacements(recipient: Recipient | EmailRecipientStruct | EmailRecipient, options: {
113
- organization: Organization | null;
114
- platform?: PlatformStruct;
115
- from: EmailInterfaceRecipient | null;
116
- replyTo: EmailInterfaceRecipient | null;
117
- forPreview?: boolean;
118
- forceRefresh?: boolean;
119
- allowedLanguages?: Language[] | null;
120
- }): Promise<void>;
121
- //# sourceMappingURL=EmailBuilder.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"EmailBuilder.d.ts","sourceRoot":"","sources":["../../src/helpers/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