@stamhoofd/models 2.144.0 → 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.
- package/dist/constants/sessions.d.ts +30 -0
- package/dist/constants/sessions.d.ts.map +1 -0
- package/dist/constants/sessions.js +42 -0
- package/dist/constants/sessions.js.map +1 -0
- package/dist/migrations/1785491700-tokens-delete-expired.sql +1 -0
- package/dist/migrations/1785491701-user-sessions-table.sql +19 -0
- package/dist/migrations/1785491702-tokens-session-columns.sql +3 -0
- package/dist/migrations/1785491703-tokens-session-id-backfill.sql +1 -0
- package/dist/migrations/1785491704-user-sessions-backfill.sql +3 -0
- package/dist/migrations/1785491705-tokens-session-required.sql +6 -0
- package/dist/migrations/1785491706-mfa-tokens-login-method.sql +2 -0
- package/dist/migrations/1787055465-vies-cached-results.sql +6 -0
- package/dist/models/MFAToken.d.ts +11 -1
- package/dist/models/MFAToken.d.ts.map +1 -1
- package/dist/models/MFAToken.js +12 -1
- package/dist/models/MFAToken.js.map +1 -1
- package/dist/models/STInvoice.d.ts +4 -3
- package/dist/models/STInvoice.d.ts.map +1 -1
- package/dist/models/STInvoice.js +4 -45
- package/dist/models/STInvoice.js.map +1 -1
- package/dist/models/Token.d.ts +2 -45
- package/dist/models/Token.d.ts.map +1 -1
- package/dist/models/Token.js +10 -138
- package/dist/models/Token.js.map +1 -1
- package/dist/models/UserSession.d.ts +20 -0
- package/dist/models/UserSession.d.ts.map +1 -0
- package/dist/models/UserSession.js +65 -0
- package/dist/models/UserSession.js.map +1 -0
- package/dist/models/ViesCachedResult.d.ts +9 -0
- package/dist/models/ViesCachedResult.d.ts.map +1 -0
- package/dist/models/ViesCachedResult.js +22 -0
- package/dist/models/ViesCachedResult.js.map +1 -0
- package/dist/models/index.d.ts +1 -0
- package/dist/models/index.d.ts.map +1 -1
- package/dist/models/index.js +1 -0
- package/dist/models/index.js.map +1 -1
- package/package.json +3 -4
- package/src/constants/sessions.ts +59 -0
- package/src/migrations/1785491700-tokens-delete-expired.sql +1 -0
- package/src/migrations/1785491701-user-sessions-table.sql +19 -0
- package/src/migrations/1785491702-tokens-session-columns.sql +3 -0
- package/src/migrations/1785491703-tokens-session-id-backfill.sql +1 -0
- package/src/migrations/1785491704-user-sessions-backfill.sql +3 -0
- package/src/migrations/1785491705-tokens-session-required.sql +6 -0
- package/src/migrations/1785491706-mfa-tokens-login-method.sql +2 -0
- package/src/migrations/1787055465-vies-cached-results.sql +6 -0
- package/src/models/MFAToken.ts +11 -1
- package/src/models/STInvoice.ts +4 -48
- package/src/models/Token.test.ts +15 -27
- package/src/models/Token.ts +8 -163
- package/src/models/UserSession.ts +50 -0
- package/src/models/ViesCachedResult.ts +22 -0
- package/src/models/index.ts +1 -0
package/src/models/Token.ts
CHANGED
|
@@ -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
|
|
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
|
|
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
|
+
}
|
package/src/models/index.ts
CHANGED
|
@@ -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
|
|