@stamhoofd/models 2.143.1 → 2.145.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 (60) 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/1786793149-settlement-charges-delete-mollie.sql +5 -0
  13. package/dist/migrations/1787055465-vies-cached-results.sql +6 -0
  14. package/dist/models/Image.d.ts +2 -1
  15. package/dist/models/Image.d.ts.map +1 -1
  16. package/dist/models/Image.js +4 -1
  17. package/dist/models/Image.js.map +1 -1
  18. package/dist/models/MFAToken.d.ts +11 -1
  19. package/dist/models/MFAToken.d.ts.map +1 -1
  20. package/dist/models/MFAToken.js +12 -1
  21. package/dist/models/MFAToken.js.map +1 -1
  22. package/dist/models/STInvoice.d.ts +4 -3
  23. package/dist/models/STInvoice.d.ts.map +1 -1
  24. package/dist/models/STInvoice.js +4 -45
  25. package/dist/models/STInvoice.js.map +1 -1
  26. package/dist/models/Token.d.ts +2 -45
  27. package/dist/models/Token.d.ts.map +1 -1
  28. package/dist/models/Token.js +10 -138
  29. package/dist/models/Token.js.map +1 -1
  30. package/dist/models/UserSession.d.ts +20 -0
  31. package/dist/models/UserSession.d.ts.map +1 -0
  32. package/dist/models/UserSession.js +65 -0
  33. package/dist/models/UserSession.js.map +1 -0
  34. package/dist/models/ViesCachedResult.d.ts +9 -0
  35. package/dist/models/ViesCachedResult.d.ts.map +1 -0
  36. package/dist/models/ViesCachedResult.js +22 -0
  37. package/dist/models/ViesCachedResult.js.map +1 -0
  38. package/dist/models/index.d.ts +1 -0
  39. package/dist/models/index.d.ts.map +1 -1
  40. package/dist/models/index.js +1 -0
  41. package/dist/models/index.js.map +1 -1
  42. package/package.json +3 -4
  43. package/src/constants/sessions.ts +59 -0
  44. package/src/migrations/1785491700-tokens-delete-expired.sql +1 -0
  45. package/src/migrations/1785491701-user-sessions-table.sql +19 -0
  46. package/src/migrations/1785491702-tokens-session-columns.sql +3 -0
  47. package/src/migrations/1785491703-tokens-session-id-backfill.sql +1 -0
  48. package/src/migrations/1785491704-user-sessions-backfill.sql +3 -0
  49. package/src/migrations/1785491705-tokens-session-required.sql +6 -0
  50. package/src/migrations/1785491706-mfa-tokens-login-method.sql +2 -0
  51. package/src/migrations/1786793149-settlement-charges-delete-mollie.sql +5 -0
  52. package/src/migrations/1787055465-vies-cached-results.sql +6 -0
  53. package/src/models/Image.ts +7 -6
  54. package/src/models/MFAToken.ts +11 -1
  55. package/src/models/STInvoice.ts +4 -48
  56. package/src/models/Token.test.ts +15 -27
  57. package/src/models/Token.ts +8 -163
  58. package/src/models/UserSession.ts +50 -0
  59. package/src/models/ViesCachedResult.ts +22 -0
  60. package/src/models/index.ts +1 -0
@@ -1,11 +1,11 @@
1
- import { createMollieClient } from '@mollie/api-client';
2
1
  import { column } from '@simonbackx/simple-database';
3
- import { SimpleError } from '@simonbackx/simple-errors';
4
2
  import { QueryableModel } from '@stamhoofd/sql';
5
- import { OrganizationPaymentMandate, OrganizationPaymentMandateDetails, STInvoiceMeta } from '@stamhoofd/structures';
3
+ import { STInvoiceMeta } from '@stamhoofd/structures';
6
4
  import { v4 as uuidv4 } from 'uuid';
7
- import type { Organization } from './Organization.js';
8
5
 
6
+ /**
7
+ * @deprecated
8
+ */
9
9
  export class STInvoice extends QueryableModel {
10
10
  static table = 'stamhoofd_invoices';
11
11
 
@@ -91,48 +91,4 @@ export class STInvoice extends QueryableModel {
91
91
 
92
92
  @column({ type: 'boolean' })
93
93
  didSendPeppol = false;
94
-
95
- static async getMollieMandates(organization: Organization) {
96
- // Poll mollie status
97
- // Mollie payment is required
98
- const mandates: OrganizationPaymentMandate[] = [];
99
-
100
- try {
101
- const apiKey = STAMHOOFD.MOLLIE_API_KEY;
102
- if (!apiKey) {
103
- throw new SimpleError({
104
- code: '',
105
- message: 'Mollie niet correct gekoppeld',
106
- });
107
- }
108
-
109
- const mollieClient = createMollieClient({ apiKey });
110
-
111
- if (organization.serverMeta.mollieCustomerId) {
112
- const m = await mollieClient.customerMandates.page({ customerId: organization.serverMeta.mollieCustomerId, limit: 250 });
113
- for (const mandate of m) {
114
- try {
115
- const details = mandate.details;
116
- mandates.push(OrganizationPaymentMandate.create({
117
- ...mandate,
118
- isDefault: mandate.id === organization.serverMeta.mollieMandateId,
119
- createdAt: new Date(mandate.createdAt),
120
- details: OrganizationPaymentMandateDetails.create({
121
- consumerName: ('consumerName' in details ? details.consumerName : details.cardHolder) ?? undefined,
122
- consumerAccount: ('consumerAccount' in details ? details.consumerAccount : details.cardNumber) ?? undefined,
123
- consumerBic: ('consumerBic' in details ? details.consumerBic : details.cardExpiryDate) ?? undefined,
124
- cardExpiryDate: ('cardExpiryDate' in details ? details.cardExpiryDate : null),
125
- cardLabel: ('cardLabel' in details ? details.cardLabel : null),
126
- }),
127
- }));
128
- } catch (e) {
129
- console.error(e);
130
- }
131
- }
132
- }
133
- } catch (e) {
134
- console.error(e);
135
- }
136
- return mandates;
137
- }
138
94
  }
@@ -1,10 +1,13 @@
1
1
  import { Database } from '@simonbackx/simple-database';
2
+ import { SessionClientType, SessionDeviceType, SessionLoginMethod } from '@stamhoofd/structures';
3
+ import { v4 as uuidv4 } from 'uuid';
2
4
 
3
5
  import { OrganizationFactory } from '../factories/OrganizationFactory.js';
4
6
  import { UserFactory } from '../factories/UserFactory.js';
5
7
  import type { Organization } from './Organization.js';
6
8
  import { Token } from './Token.js';
7
9
  import type { User } from './User.js';
10
+ import { UserSession } from './UserSession.js';
8
11
 
9
12
  describe('Model.Token', () => {
10
13
  const existingToken = 'ABCDEFG';
@@ -14,9 +17,21 @@ describe('Model.Token', () => {
14
17
  beforeAll(async () => {
15
18
  organization = await new OrganizationFactory({}).create();
16
19
  user = await new UserFactory({ organization }).create();
20
+ const tokenId = uuidv4();
21
+ const session = new UserSession();
22
+ session.userId = user.id;
23
+ session.clientType = SessionClientType.Browser;
24
+ session.loginMethod = SessionLoginMethod.Password;
25
+ session.deviceType = SessionDeviceType.Desktop;
26
+ session.startedAt = new Date();
27
+ session.lastUsedTokenId = tokenId;
28
+ session.lastActiveTokenId = tokenId;
29
+ await session.save();
17
30
 
18
31
  await Database.insert('INSERT INTO ' + Token.table + ' SET ?', [
19
32
  {
33
+ id: tokenId,
34
+ sessionId: session.id,
20
35
  accessToken: existingToken,
21
36
  refreshToken: 'refreshtoken',
22
37
 
@@ -39,31 +54,4 @@ describe('Model.Token', () => {
39
54
  expect(token.userId).toEqual(user.id);
40
55
  });
41
56
 
42
- test('Create a token', async () => {
43
- const token = await Token.createToken(user);
44
- expect(token).toBeDefined();
45
- if (!token) return;
46
- expect(token).toBeInstanceOf(Token);
47
- expect(token.user.id).toEqual(user.id);
48
- expect(token.accessToken).toHaveLength(256);
49
- expect(token.refreshToken).toHaveLength(256);
50
- expect(token.accessTokenValidUntil.getTime()).toBeGreaterThan(new Date().getTime() + (3600 * 1000) / 2 - 1);
51
- expect(token.accessTokenValidUntil.getTime()).toBeLessThan(new Date().getTime() + 3600 * 1000 * 24 * 365);
52
-
53
- expect(token.refreshTokenValidUntil.getTime()).toBeGreaterThan(token.accessTokenValidUntil.getTime());
54
- expect(token.refreshTokenValidUntil.getTime()).toBeLessThan(new Date().getTime() + 3600 * 1000 * 24 * 365);
55
-
56
- expect(token.userId).toEqual(user.id);
57
-
58
- const search = await Token.getByAccessToken(token.accessToken);
59
- // Make sure we do not compare the organization, since that won't be loaded now, but is loaded on user, and on token
60
-
61
- expect(search).toMatchObject({
62
- accessToken: token.accessToken,
63
- refreshToken: token.refreshToken,
64
- userId: token.userId,
65
- accessTokenValidUntil: token.accessTokenValidUntil,
66
- refreshTokenValidUntil: token.refreshTokenValidUntil,
67
- });
68
- });
69
57
  });
@@ -1,29 +1,14 @@
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';
9
7
 
10
8
  export type TokenWithUser = Token & { user: User };
11
9
 
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
- }
23
-
24
10
  export class Token extends QueryableModel {
25
11
  static table = 'tokens';
26
- static MAX_DEVICES = 15;
27
12
 
28
13
  /**
29
14
  * How long after authentication a token still counts as "fresh" for sensitive
@@ -31,9 +16,15 @@ export class Token extends QueryableModel {
31
16
  */
32
17
  static FRESH_WINDOW = 10 * 60 * 1000;
33
18
 
19
+ @column({ type: 'string' })
20
+ id: string;
21
+
34
22
  @column({ type: 'string' })
35
23
  userId: string;
36
24
 
25
+ @column({ type: 'string' })
26
+ sessionId: string;
27
+
37
28
  // Columns
38
29
  @column({ primary: true, type: 'string' })
39
30
  accessToken: string;
@@ -91,49 +82,6 @@ export class Token extends QueryableModel {
91
82
  return this.authenticatedAt !== null && this.authenticatedAt.getTime() > Date.now() - Token.FRESH_WINDOW;
92
83
  }
93
84
 
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
85
  static async getAPIUserWithToken(user: User) {
138
86
  if (!user.isApiUser) {
139
87
  throw new Error('Unexpected user type');
@@ -211,18 +159,9 @@ export class Token extends QueryableModel {
211
159
  return undefined;
212
160
  }
213
161
 
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
162
  const user = User.fromRow(rows[0]['user']) || null;
224
163
 
225
- if (!user || user.isApiUser) {
164
+ if (!user) {
226
165
  console.warn('Selected a token without a user!');
227
166
  return undefined;
228
167
  }
@@ -230,98 +169,4 @@ export class Token extends QueryableModel {
230
169
  return token.setRelation(Token.user, user);
231
170
  }
232
171
 
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
172
  }
@@ -0,0 +1,50 @@
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
+ @column({ type: 'string' })
16
+ clientType = SessionClientType.Browser;
17
+
18
+ @column({ type: 'datetime' })
19
+ startedAt: Date;
20
+
21
+ @column({ type: 'string' })
22
+ loginMethod = SessionLoginMethod.Password;
23
+
24
+ @column({ type: 'string' })
25
+ deviceType = SessionDeviceType.Desktop;
26
+
27
+ @column({ type: 'string', nullable: true })
28
+ deviceName: string | null = null;
29
+
30
+ @column({ type: 'string', nullable: true })
31
+ osName: SessionOS | null = null;
32
+
33
+ @column({ type: 'string', nullable: true })
34
+ osVersion: string | null = null;
35
+
36
+ @column({ type: 'string', nullable: true })
37
+ appVersion: string | null = null;
38
+
39
+ @column({ type: 'string', nullable: true })
40
+ nativeAppVersion: string | null = null;
41
+
42
+ @column({ type: 'string', nullable: true })
43
+ browserName: string | null = null;
44
+
45
+ @column({ type: 'string' })
46
+ lastUsedTokenId: string;
47
+
48
+ @column({ type: 'string' })
49
+ lastActiveTokenId: string;
50
+ }
@@ -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
+ }
@@ -31,6 +31,7 @@ export * from './STPackage.js';
31
31
  export { STPendingInvoice } from './STPendingInvoice.js';
32
32
  export * from './Ticket.js';
33
33
  export { Token, type TokenWithUser } from './Token.js';
34
+ export { UserSession } from './UserSession.js';
34
35
  export * from './UsedRegisterCode.js';
35
36
  export * from './Webshop.js';
36
37