@stamhoofd/models 2.144.0 → 2.146.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 (65) hide show
  1. package/dist/constants/sessions.d.ts +30 -0
  2. package/dist/constants/sessions.d.ts.map +1 -0
  3. package/dist/constants/sessions.js +42 -0
  4. package/dist/constants/sessions.js.map +1 -0
  5. package/dist/migrations/1785491700-tokens-delete-expired.sql +1 -0
  6. package/dist/migrations/1785491701-user-sessions-table.sql +19 -0
  7. package/dist/migrations/1785491702-tokens-session-columns.sql +3 -0
  8. package/dist/migrations/1785491703-tokens-session-id-backfill.sql +1 -0
  9. package/dist/migrations/1785491704-user-sessions-backfill.sql +3 -0
  10. package/dist/migrations/1785491705-tokens-session-required.sql +6 -0
  11. package/dist/migrations/1785491706-mfa-tokens-login-method.sql +2 -0
  12. package/dist/migrations/1785824341-user-sessions-impersonated-user-id.sql +4 -0
  13. package/dist/migrations/1785824342-create-impersonation-tokens-table.sql +15 -0
  14. package/dist/migrations/1787055465-vies-cached-results.sql +6 -0
  15. package/dist/models/ImpersonationToken.d.ts +63 -0
  16. package/dist/models/ImpersonationToken.d.ts.map +1 -0
  17. package/dist/models/ImpersonationToken.js +135 -0
  18. package/dist/models/ImpersonationToken.js.map +1 -0
  19. package/dist/models/MFAToken.d.ts +11 -1
  20. package/dist/models/MFAToken.d.ts.map +1 -1
  21. package/dist/models/MFAToken.js +12 -1
  22. package/dist/models/MFAToken.js.map +1 -1
  23. package/dist/models/STInvoice.d.ts +4 -3
  24. package/dist/models/STInvoice.d.ts.map +1 -1
  25. package/dist/models/STInvoice.js +4 -45
  26. package/dist/models/STInvoice.js.map +1 -1
  27. package/dist/models/Token.d.ts +9 -46
  28. package/dist/models/Token.d.ts.map +1 -1
  29. package/dist/models/Token.js +19 -140
  30. package/dist/models/Token.js.map +1 -1
  31. package/dist/models/UserSession.d.ts +28 -0
  32. package/dist/models/UserSession.d.ts.map +1 -0
  33. package/dist/models/UserSession.js +76 -0
  34. package/dist/models/UserSession.js.map +1 -0
  35. package/dist/models/ViesCachedResult.d.ts +9 -0
  36. package/dist/models/ViesCachedResult.d.ts.map +1 -0
  37. package/dist/models/ViesCachedResult.js +22 -0
  38. package/dist/models/ViesCachedResult.js.map +1 -0
  39. package/dist/models/_relations.js +4 -0
  40. package/dist/models/_relations.js.map +1 -1
  41. package/dist/models/index.d.ts +2 -0
  42. package/dist/models/index.d.ts.map +1 -1
  43. package/dist/models/index.js +2 -0
  44. package/dist/models/index.js.map +1 -1
  45. package/package.json +3 -4
  46. package/src/constants/sessions.ts +59 -0
  47. package/src/migrations/1785491700-tokens-delete-expired.sql +1 -0
  48. package/src/migrations/1785491701-user-sessions-table.sql +19 -0
  49. package/src/migrations/1785491702-tokens-session-columns.sql +3 -0
  50. package/src/migrations/1785491703-tokens-session-id-backfill.sql +1 -0
  51. package/src/migrations/1785491704-user-sessions-backfill.sql +3 -0
  52. package/src/migrations/1785491705-tokens-session-required.sql +6 -0
  53. package/src/migrations/1785491706-mfa-tokens-login-method.sql +2 -0
  54. package/src/migrations/1785824341-user-sessions-impersonated-user-id.sql +4 -0
  55. package/src/migrations/1785824342-create-impersonation-tokens-table.sql +15 -0
  56. package/src/migrations/1787055465-vies-cached-results.sql +6 -0
  57. package/src/models/ImpersonationToken.ts +133 -0
  58. package/src/models/MFAToken.ts +11 -1
  59. package/src/models/STInvoice.ts +4 -48
  60. package/src/models/Token.test.ts +15 -27
  61. package/src/models/Token.ts +22 -167
  62. package/src/models/UserSession.ts +60 -0
  63. package/src/models/ViesCachedResult.ts +22 -0
  64. package/src/models/_relations.ts +4 -0
  65. package/src/models/index.ts +2 -0
@@ -1,29 +1,16 @@
1
1
  import type { ManyToOneRelation } from '@simonbackx/simple-database';
2
2
  import { column, Database } from '@simonbackx/simple-database';
3
- import { QueryableModel, SQLWhereSign } from '@stamhoofd/sql';
3
+ import { QueryableModel } from '@stamhoofd/sql';
4
4
  import { ApiUser } from '@stamhoofd/structures';
5
- import crypto from 'crypto';
6
5
 
7
- import { SimpleError } from '@simonbackx/simple-errors';
8
6
  import { User } from './User.js';
7
+ import { UserSession } from './UserSession.js';
9
8
 
10
9
  export type TokenWithUser = Token & { user: User };
11
-
12
- async function randomBytes(size: number): Promise<Buffer> {
13
- return new Promise((resolve, reject) => {
14
- crypto.randomBytes(size, (err: Error | null, buf: Buffer) => {
15
- if (err) {
16
- reject(err);
17
- return;
18
- }
19
- resolve(buf);
20
- });
21
- });
22
- }
10
+ export type TokenWithSession = Token & { user: User; session: UserSession };
23
11
 
24
12
  export class Token extends QueryableModel {
25
13
  static table = 'tokens';
26
- static MAX_DEVICES = 15;
27
14
 
28
15
  /**
29
16
  * How long after authentication a token still counts as "fresh" for sensitive
@@ -31,9 +18,15 @@ export class Token extends QueryableModel {
31
18
  */
32
19
  static FRESH_WINDOW = 10 * 60 * 1000;
33
20
 
21
+ @column({ type: 'string' })
22
+ id: string;
23
+
34
24
  @column({ type: 'string' })
35
25
  userId: string;
36
26
 
27
+ @column({ type: 'string' })
28
+ sessionId: string;
29
+
37
30
  // Columns
38
31
  @column({ primary: true, type: 'string' })
39
32
  accessToken: string;
@@ -78,6 +71,7 @@ export class Token extends QueryableModel {
78
71
  updatedAt: Date;
79
72
 
80
73
  static user: ManyToOneRelation<'user', User>;
74
+ static session: ManyToOneRelation<'session', UserSession>;
81
75
 
82
76
  isAccessTokenExpired(): boolean {
83
77
  return this.accessTokenValidUntil < new Date() || this.refreshTokenValidUntil < new Date();
@@ -91,49 +85,6 @@ export class Token extends QueryableModel {
91
85
  return this.authenticatedAt !== null && this.authenticatedAt.getTime() > Date.now() - Token.FRESH_WINDOW;
92
86
  }
93
87
 
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
-
137
88
  static async getAPIUserWithToken(user: User) {
138
89
  if (!user.isApiUser) {
139
90
  throw new Error('Unexpected user type');
@@ -157,11 +108,11 @@ export class Token extends QueryableModel {
157
108
  /**
158
109
  * Get the token and user for a given accessToken IF it is still valid
159
110
  */
160
- static async getByAccessToken(accessToken: string, ignoreExpireDate = false): Promise<TokenWithUser | undefined> {
111
+ static async getByAccessToken(accessToken: string, ignoreExpireDate = false): Promise<TokenWithSession | undefined> {
161
112
  const [rows] = await Database.select(
162
- `SELECT ${this.getDefaultSelect()}, user.* FROM ${
113
+ `SELECT ${this.getDefaultSelect()}, ${User.getDefaultSelect('user')}, ${UserSession.getDefaultSelect('session')} FROM ${
163
114
  this.table
164
- } ${Token.user.joinQuery(this.table, 'user')} WHERE ${this.primary.name} = ? LIMIT 1 `,
115
+ } ${Token.user.joinQuery(this.table, 'user')} ${Token.session.joinQuery(this.table, 'session')} WHERE ${this.primary.name} = ? LIMIT 1 `,
165
116
  [accessToken],
166
117
  );
167
118
 
@@ -188,7 +139,14 @@ export class Token extends QueryableModel {
188
139
  return undefined;
189
140
  }
190
141
 
191
- return token.setRelation(Token.user, user);
142
+ const session = UserSession.fromRow(rows[0]['session']) || null;
143
+
144
+ if (!session) {
145
+ console.warn('Selected a token without a session!');
146
+ return undefined;
147
+ }
148
+
149
+ return token.setRelation(Token.user, user).setRelation(Token.session, session);
192
150
  }
193
151
 
194
152
  // Methods
@@ -211,18 +169,9 @@ export class Token extends QueryableModel {
211
169
  return undefined;
212
170
  }
213
171
 
214
- if (token.refreshTokenValidUntil < new Date()) {
215
- // If a user tries to use a refresh token that is expired - there is a possibility of a user
216
- // being compromised.
217
- // So we delete all tokens for this user.
218
- console.error('Detected an expired refresh token, deleting all tokens for user', token.userId);
219
- await this.delete().where('userId', token.userId);
220
- return undefined;
221
- }
222
-
223
172
  const user = User.fromRow(rows[0]['user']) || null;
224
173
 
225
- if (!user || user.isApiUser) {
174
+ if (!user) {
226
175
  console.warn('Selected a token without a user!');
227
176
  return undefined;
228
177
  }
@@ -230,98 +179,4 @@ export class Token extends QueryableModel {
230
179
  return token.setRelation(Token.user, user);
231
180
  }
232
181
 
233
- /**
234
- * Create a token that is expired. This can be usefull if renewing the token is restricted by some account state.
235
- * E.g. you cannot renew this token until the e-mail address has been verified.
236
- * @param user
237
- */
238
- static async createExpiredToken<U extends User>(user: U): Promise<(Token & { user: U })> {
239
- const token = await this.createUnsavedToken(user);
240
-
241
- /// Expired a month ago (to prevent any timezone bugs)
242
- token.accessTokenValidUntil = new Date(Date.now() - 24 * 60 * 60 * 1000 * 31);
243
- token.accessTokenValidUntil.setMilliseconds(0);
244
-
245
- await token.save();
246
- return token;
247
- }
248
-
249
- /***
250
- * Create a token without saving it
251
- */
252
- static async createUnsavedToken<U extends User>(user: U): Promise<(Token & { user: U })> {
253
- if (user.isSystemUser) {
254
- throw new SimpleError({
255
- code: 'internal_error',
256
- message: 'Cannot create token for system user',
257
- statusCode: 500,
258
- });
259
- }
260
- // Get all the tokens of the user that are olde
261
-
262
- // First search if we already have more than 5 tokens (we only allow up to 5 devices)
263
- // In case we already have a token for that deviceId, we'll delete it first.
264
- try {
265
- const [
266
- rows,
267
- ] = await Database.delete(
268
- `DELETE FROM \`${this.table}\` WHERE ${this.primary.name} IN (SELECT ${this.primary.name} FROM (SELECT ${this.primary.name} FROM \`${this.table}\` WHERE \`userId\` = ? ORDER BY\`createdAt\` DESC LIMIT ? OFFSET ?) x)`,
269
- [user.id, this.MAX_DEVICES, this.MAX_DEVICES],
270
- );
271
-
272
- if (rows.affectedRows > 0) {
273
- console.log(`Deleted ${rows.affectedRows} old tokens first`);
274
- }
275
- }
276
- catch (e) {
277
- // This is not a crucial operation, so don't fail when there is a deadlock problem in the query
278
- console.error(e);
279
- }
280
-
281
- const token = new Token().setRelation(Token.user, user);
282
- token.accessTokenValidUntil = new Date();
283
- token.accessTokenValidUntil.setTime(token.accessTokenValidUntil.getTime() + 3600 * 1000);
284
- token.accessTokenValidUntil.setMilliseconds(0);
285
-
286
- token.refreshTokenValidUntil = new Date();
287
- token.refreshTokenValidUntil.setTime(token.refreshTokenValidUntil.getTime() + 3600 * 1000 * 24 * 365);
288
- token.refreshTokenValidUntil.setMilliseconds(0);
289
-
290
- token.accessToken = (await randomBytes(192)).toString('base64').toUpperCase();
291
- token.refreshToken = (await randomBytes(192)).toString('base64').toUpperCase();
292
- return token;
293
- }
294
-
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 })> {
301
- const token = await this.createUnsavedToken(user);
302
- token.authenticatedAt = authenticatedAt;
303
- await token.save();
304
- return token;
305
- }
306
-
307
- static async createApiToken<U extends User>(user: U): Promise<(Token & { user: U })> {
308
- const token = await this.createUnsavedToken(user);
309
-
310
- // 5 year valid
311
- token.accessTokenValidUntil = new Date();
312
- token.accessTokenValidUntil.setTime(token.accessTokenValidUntil.getTime() + 1000 * 60 * 60 * 24 * 365 * 5);
313
- token.accessTokenValidUntil.setMilliseconds(0);
314
-
315
- token.refreshTokenValidUntil = new Date();
316
- token.refreshTokenValidUntil.setTime(token.accessTokenValidUntil.getTime());
317
- token.refreshTokenValidUntil.setMilliseconds(0);
318
-
319
- await token.save();
320
- return token;
321
- }
322
-
323
- static async clearFor(userId: string, currentToken: string) {
324
- const query = `DELETE from ${this.table} where userId = ? AND accessToken != ?`;
325
- await Database.delete(query, [userId, currentToken]);
326
- }
327
182
  }
@@ -0,0 +1,60 @@
1
+ import { column } from '@simonbackx/simple-database';
2
+ import { QueryableModel } from '@stamhoofd/sql';
3
+ import { SessionClientType, SessionDeviceType, SessionLoginMethod, SessionOS } from '@stamhoofd/structures';
4
+ import { v4 as uuidv4 } from 'uuid';
5
+
6
+ export class UserSession extends QueryableModel {
7
+ static table = 'user_sessions';
8
+
9
+ @column({ primary: true, type: 'string', beforeSave: value => value ?? uuidv4() })
10
+ id: string;
11
+
12
+ @column({ type: 'string' })
13
+ userId: string;
14
+
15
+ /**
16
+ * When set, this session belongs to `userId` but presents itself as this other user:
17
+ * an administrator is looking at the application through the eyes of that account.
18
+ *
19
+ * The session never stops being the administrator's: everything it changes is
20
+ * attributed to `userId`, and every access check has to pass for both accounts.
21
+ */
22
+ @column({ type: 'string', nullable: true })
23
+ impersonatedUserId: string | null = null;
24
+
25
+ @column({ type: 'string' })
26
+ clientType = SessionClientType.Browser;
27
+
28
+ @column({ type: 'datetime' })
29
+ startedAt: Date;
30
+
31
+ @column({ type: 'string' })
32
+ loginMethod = SessionLoginMethod.Password;
33
+
34
+ @column({ type: 'string' })
35
+ deviceType = SessionDeviceType.Desktop;
36
+
37
+ @column({ type: 'string', nullable: true })
38
+ deviceName: string | null = null;
39
+
40
+ @column({ type: 'string', nullable: true })
41
+ osName: SessionOS | null = null;
42
+
43
+ @column({ type: 'string', nullable: true })
44
+ osVersion: string | null = null;
45
+
46
+ @column({ type: 'string', nullable: true })
47
+ appVersion: string | null = null;
48
+
49
+ @column({ type: 'string', nullable: true })
50
+ nativeAppVersion: string | null = null;
51
+
52
+ @column({ type: 'string', nullable: true })
53
+ browserName: string | null = null;
54
+
55
+ @column({ type: 'string' })
56
+ lastUsedTokenId: string;
57
+
58
+ @column({ type: 'string' })
59
+ lastActiveTokenId: string;
60
+ }
@@ -0,0 +1,22 @@
1
+ import { column, Database } from '@simonbackx/simple-database';
2
+ import { QueryableModel } from '@stamhoofd/sql';
3
+
4
+ export class ViesCachedResult extends QueryableModel {
5
+ static table = 'vies_cached_results';
6
+
7
+ @column({ primary: true, type: 'string' })
8
+ VATNumber: string;
9
+
10
+ @column({ type: 'datetime' })
11
+ checkedAt: Date;
12
+
13
+ @column({ type: 'boolean' })
14
+ result: boolean;
15
+
16
+ static async saveResult(VATNumber: string, result: boolean, checkedAt: Date): Promise<void> {
17
+ await Database.insert(
18
+ `INSERT INTO \`${this.table}\` (\`VATNumber\`, \`checkedAt\`, \`result\`) VALUES (?, ?, ?) ON DUPLICATE KEY UPDATE \`checkedAt\` = VALUES(\`checkedAt\`), \`result\` = VALUES(\`result\`)`,
19
+ [VATNumber, checkedAt, result],
20
+ );
21
+ }
22
+ }
@@ -11,6 +11,7 @@ import { Organization } from './Organization.js';
11
11
  import { STPendingInvoice } from './STPendingInvoice.js';
12
12
  import { Ticket } from './Ticket.js';
13
13
  import { User } from './User.js';
14
+ import { UserSession } from './UserSession.js';
14
15
  import { UserPermissions } from './UserPermissions.js';
15
16
  import { Webshop } from './Webshop.js';
16
17
  import { InvoicedBalanceItem } from './InvoicedBalanceItem.js';
@@ -128,6 +129,9 @@ if (!Token.relations) {
128
129
  Token.user = new ManyToOneRelation(User, 'user');
129
130
  Token.user.foreignKey = 'userId';
130
131
  Token.relations.push(Token.user);
132
+ Token.session = new ManyToOneRelation(UserSession, 'session');
133
+ Token.session.foreignKey = 'sessionId';
134
+ Token.relations.push(Token.session);
131
135
 
132
136
  if (!PasswordToken.relations) {
133
137
  PasswordToken.relations = [];
@@ -7,6 +7,7 @@ export { User } from './User.js';
7
7
 
8
8
  export * from './EmailVerificationCode.js';
9
9
 
10
+ export * from './ImpersonationToken.js';
10
11
  export * from './MFAToken.js';
11
12
  export * from './MFATOTP.js';
12
13
  export * from './MFARecoveryCode.js';
@@ -31,6 +32,7 @@ export * from './STPackage.js';
31
32
  export { STPendingInvoice } from './STPendingInvoice.js';
32
33
  export * from './Ticket.js';
33
34
  export { Token, type TokenWithUser } from './Token.js';
35
+ export { UserSession } from './UserSession.js';
34
36
  export * from './UsedRegisterCode.js';
35
37
  export * from './Webshop.js';
36
38