@stamhoofd/models 2.137.5 → 2.138.1
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/helpers/Handlebars.d.ts.map +1 -1
- package/dist/helpers/Handlebars.js +1 -1
- package/dist/helpers/Handlebars.js.map +1 -1
- package/dist/helpers/errorToSimpleErrors.d.ts +3 -0
- package/dist/helpers/errorToSimpleErrors.d.ts.map +1 -0
- package/dist/helpers/errorToSimpleErrors.js +17 -0
- package/dist/helpers/errorToSimpleErrors.js.map +1 -0
- package/dist/index.d.ts +0 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +0 -1
- package/dist/index.js.map +1 -1
- package/dist/migrations/1782902314-tokens-authenticated-at.sql +2 -0
- package/dist/migrations/1782902315-create-mfa-totp-table.sql +13 -0
- package/dist/migrations/1782902316-create-webauthn-credentials-table.sql +17 -0
- package/dist/migrations/1782902317-create-mfa-recovery-codes-table.sql +10 -0
- package/dist/migrations/1782902318-create-mfa-tokens-table.sql +13 -0
- package/dist/migrations/1782902319-create-webauthn-challenges-table.sql +10 -0
- package/dist/migrations/1784039947-mfa-totp-last-used-counter.sql +2 -0
- package/dist/migrations/1784122354-webauthn-credential-provider.sql +3 -0
- package/dist/migrations/1784500000-webauthn-credential-rp-id.sql +9 -0
- package/dist/migrations/1785354091-platform-parent-tenant-id.sql +1 -0
- package/dist/migrations/1785354092-platform-fees-tenant-id.sql +1 -0
- package/dist/migrations/1785354093-platform-uri.sql +1 -0
- package/dist/migrations/1785354094-platform-domain.sql +1 -0
- package/dist/migrations/1785354095-platform-uri-unique.sql +1 -0
- package/dist/migrations/1785354096-platform-domain-unique.sql +1 -0
- package/dist/migrations/1785354097-platform-parent-tenant-id-index.sql +1 -0
- package/dist/migrations/1785354098-platform-tenant-backfill.d.ts +4 -0
- package/dist/migrations/1785354098-platform-tenant-backfill.d.ts.map +1 -0
- package/dist/migrations/1785354098-platform-tenant-backfill.js +10 -0
- package/dist/migrations/1785354098-platform-tenant-backfill.js.map +1 -0
- package/dist/migrations/1785417301-users-last-active-at.sql +2 -0
- package/dist/models/Email.d.ts +0 -6
- package/dist/models/Email.d.ts.map +1 -1
- package/dist/models/Email.js +4 -625
- package/dist/models/Email.js.map +1 -1
- package/dist/models/MFARecoveryCode.d.ts +17 -0
- package/dist/models/MFARecoveryCode.d.ts.map +1 -0
- package/dist/models/MFARecoveryCode.js +55 -0
- package/dist/models/MFARecoveryCode.js.map +1 -0
- package/dist/models/MFATOTP.d.ts +44 -0
- package/dist/models/MFATOTP.d.ts.map +1 -0
- package/dist/models/MFATOTP.js +116 -0
- package/dist/models/MFATOTP.js.map +1 -0
- package/dist/models/MFAToken.d.ts +49 -0
- package/dist/models/MFAToken.d.ts.map +1 -0
- package/dist/models/MFAToken.js +137 -0
- package/dist/models/MFAToken.js.map +1 -0
- package/dist/models/Organization.d.ts +1 -38
- package/dist/models/Organization.d.ts.map +1 -1
- package/dist/models/Organization.js +1 -132
- package/dist/models/Organization.js.map +1 -1
- package/dist/models/Platform.d.ts +28 -4
- package/dist/models/Platform.d.ts.map +1 -1
- package/dist/models/Platform.js +109 -53
- package/dist/models/Platform.js.map +1 -1
- package/dist/models/Token.d.ts +40 -1
- package/dist/models/Token.d.ts.map +1 -1
- package/dist/models/Token.js +68 -2
- package/dist/models/Token.js.map +1 -1
- package/dist/models/User.d.ts +25 -0
- package/dist/models/User.d.ts.map +1 -1
- package/dist/models/User.js +36 -0
- package/dist/models/User.js.map +1 -1
- package/dist/models/WebauthnChallenge.d.ts +27 -0
- package/dist/models/WebauthnChallenge.d.ts.map +1 -0
- package/dist/models/WebauthnChallenge.js +81 -0
- package/dist/models/WebauthnChallenge.js.map +1 -0
- package/dist/models/WebauthnCredential.d.ts +58 -0
- package/dist/models/WebauthnCredential.d.ts.map +1 -0
- package/dist/models/WebauthnCredential.js +144 -0
- package/dist/models/WebauthnCredential.js.map +1 -0
- package/dist/models/index.d.ts +5 -0
- package/dist/models/index.d.ts.map +1 -1
- package/dist/models/index.js +5 -0
- package/dist/models/index.js.map +1 -1
- package/package.json +3 -3
- package/src/helpers/Handlebars.ts +5 -9
- package/src/helpers/errorToSimpleErrors.ts +17 -0
- package/src/index.ts +0 -1
- package/src/migrations/1782902314-tokens-authenticated-at.sql +2 -0
- package/src/migrations/1782902315-create-mfa-totp-table.sql +13 -0
- package/src/migrations/1782902316-create-webauthn-credentials-table.sql +17 -0
- package/src/migrations/1782902317-create-mfa-recovery-codes-table.sql +10 -0
- package/src/migrations/1782902318-create-mfa-tokens-table.sql +13 -0
- package/src/migrations/1782902319-create-webauthn-challenges-table.sql +10 -0
- package/src/migrations/1784039947-mfa-totp-last-used-counter.sql +2 -0
- package/src/migrations/1784122354-webauthn-credential-provider.sql +3 -0
- package/src/migrations/1784500000-webauthn-credential-rp-id.sql +9 -0
- package/src/migrations/1785354091-platform-parent-tenant-id.sql +1 -0
- package/src/migrations/1785354092-platform-fees-tenant-id.sql +1 -0
- package/src/migrations/1785354093-platform-uri.sql +1 -0
- package/src/migrations/1785354094-platform-domain.sql +1 -0
- package/src/migrations/1785354095-platform-uri-unique.sql +1 -0
- package/src/migrations/1785354096-platform-domain-unique.sql +1 -0
- package/src/migrations/1785354097-platform-parent-tenant-id-index.sql +1 -0
- package/src/migrations/1785354098-platform-tenant-backfill.ts +14 -0
- package/src/migrations/1785417301-users-last-active-at.sql +2 -0
- package/src/models/Email.ts +4 -713
- package/src/models/MFARecoveryCode.ts +52 -0
- package/src/models/MFATOTP.ts +112 -0
- package/src/models/MFAToken.ts +138 -0
- package/src/models/Organization.test.ts +0 -46
- package/src/models/Organization.ts +0 -154
- package/src/models/Platform.test.ts +167 -3
- package/src/models/Platform.ts +121 -53
- package/src/models/Token.ts +73 -2
- package/src/models/User.ts +37 -0
- package/src/models/WebauthnChallenge.ts +80 -0
- package/src/models/WebauthnCredential.ts +130 -0
- package/src/models/index.ts +6 -0
- package/dist/helpers/EmailBuilder.d.ts +0 -121
- package/dist/helpers/EmailBuilder.d.ts.map +0 -1
- package/dist/helpers/EmailBuilder.js +0 -659
- package/dist/helpers/EmailBuilder.js.map +0 -1
- package/src/helpers/EmailBuilder.test.ts +0 -291
- package/src/helpers/EmailBuilder.ts +0 -818
- package/src/models/Email.test.ts +0 -1222
|
@@ -1,13 +1,16 @@
|
|
|
1
1
|
import { PlatformConfig, PlatformMembershipType } from '@stamhoofd/structures';
|
|
2
2
|
import { Platform } from './Platform.js';
|
|
3
3
|
import { Database } from '@simonbackx/simple-database';
|
|
4
|
+
import { STExpect, TestUtils } from '@stamhoofd/test-utils';
|
|
5
|
+
import { QueueHandler } from '@stamhoofd/queues';
|
|
4
6
|
|
|
5
7
|
describe('Model.Platform', () => {
|
|
6
8
|
describe('Shared caches', () => {
|
|
7
9
|
beforeEach(async () => {
|
|
8
|
-
|
|
9
|
-
platform
|
|
10
|
-
|
|
10
|
+
// getForEditing, not getByID: on a freshly migrated database the row does not exist yet
|
|
11
|
+
const platform = await Platform.getForEditing();
|
|
12
|
+
platform.config = PlatformConfig.create({});
|
|
13
|
+
await platform.save();
|
|
11
14
|
});
|
|
12
15
|
|
|
13
16
|
test('Editable model changes do not propagate', async () => {
|
|
@@ -85,6 +88,27 @@ describe('Model.Platform', () => {
|
|
|
85
88
|
expect((await Platform.getByID('1'))?.id).toEqual(editable.id);
|
|
86
89
|
});
|
|
87
90
|
|
|
91
|
+
test('it charges its own fees and takes its uri and domain from the environment', async () => {
|
|
92
|
+
TestUtils.setEnvironment('platformName', 'a-test-platform');
|
|
93
|
+
TestUtils.setEnvironment('domains', {
|
|
94
|
+
...STAMHOOFD.domains,
|
|
95
|
+
dashboard: 'a-test-platform.example.com',
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
const created = await Platform.getForEditing();
|
|
99
|
+
|
|
100
|
+
expect(created.feesTenantId).toBe(created.id);
|
|
101
|
+
expect(created.parentTenantId).toBeNull();
|
|
102
|
+
expect(created.uri).toBe('a-test-platform');
|
|
103
|
+
expect(created.domain).toBe('a-test-platform.example.com');
|
|
104
|
+
|
|
105
|
+
// Reload so we know the values were persisted, not just set in memory
|
|
106
|
+
const reloaded = await Platform.getByID(created.id);
|
|
107
|
+
expect(reloaded!.feesTenantId).toBe(created.id);
|
|
108
|
+
expect(reloaded!.uri).toBe('a-test-platform');
|
|
109
|
+
expect(reloaded!.domain).toBe('a-test-platform.example.com');
|
|
110
|
+
});
|
|
111
|
+
|
|
88
112
|
test('when requesting getShared', async () => {
|
|
89
113
|
const shared = await Platform.getShared();
|
|
90
114
|
expect(shared.id).toBe('1');
|
|
@@ -104,4 +128,144 @@ describe('Model.Platform', () => {
|
|
|
104
128
|
expect(await Platform.getByID('1')).toBeDefined();
|
|
105
129
|
});
|
|
106
130
|
});
|
|
131
|
+
|
|
132
|
+
describe('Tenant identity', () => {
|
|
133
|
+
afterEach(async () => {
|
|
134
|
+
await Database.delete('DELETE FROM platform WHERE id != ?', ['1']);
|
|
135
|
+
});
|
|
136
|
+
|
|
137
|
+
test('two tenants cannot share a uri', async () => {
|
|
138
|
+
const existing = await Platform.getForEditing();
|
|
139
|
+
existing.uri = 'first-tenant';
|
|
140
|
+
await existing.save();
|
|
141
|
+
|
|
142
|
+
const other = new Platform();
|
|
143
|
+
other.id = 'clash-a';
|
|
144
|
+
other.periodId = existing.periodId;
|
|
145
|
+
other.uri = 'first-tenant';
|
|
146
|
+
|
|
147
|
+
await expect(other.save()).rejects.toThrow(/uri/i);
|
|
148
|
+
});
|
|
149
|
+
|
|
150
|
+
test('two tenants cannot share a domain', async () => {
|
|
151
|
+
const existing = await Platform.getForEditing();
|
|
152
|
+
existing.domain = 'shared.example.com';
|
|
153
|
+
await existing.save();
|
|
154
|
+
|
|
155
|
+
const other = new Platform();
|
|
156
|
+
other.id = 'clash-b';
|
|
157
|
+
other.periodId = existing.periodId;
|
|
158
|
+
other.domain = 'shared.example.com';
|
|
159
|
+
|
|
160
|
+
await expect(other.save()).rejects.toThrow(/domain/i);
|
|
161
|
+
});
|
|
162
|
+
|
|
163
|
+
test('a second tenant with its own uri and domain saves fine', async () => {
|
|
164
|
+
const existing = await Platform.getForEditing();
|
|
165
|
+
existing.uri = 'first-tenant';
|
|
166
|
+
existing.domain = 'first.example.com';
|
|
167
|
+
await existing.save();
|
|
168
|
+
|
|
169
|
+
const other = new Platform();
|
|
170
|
+
other.id = 'clash-c';
|
|
171
|
+
other.periodId = existing.periodId;
|
|
172
|
+
other.uri = 'sibling-tenant';
|
|
173
|
+
other.domain = 'sibling.example.com';
|
|
174
|
+
other.parentTenantId = existing.id;
|
|
175
|
+
other.feesTenantId = existing.id;
|
|
176
|
+
|
|
177
|
+
await expect(other.save()).resolves.not.toThrow();
|
|
178
|
+
|
|
179
|
+
const reloaded = await Platform.getByID('clash-c');
|
|
180
|
+
expect(reloaded!.parentTenantId).toBe(existing.id);
|
|
181
|
+
expect(reloaded!.feesTenantId).toBe(existing.id);
|
|
182
|
+
});
|
|
183
|
+
});
|
|
184
|
+
|
|
185
|
+
describe('Per-tenant caches', () => {
|
|
186
|
+
async function createSecondTenant() {
|
|
187
|
+
const root = await Platform.getForEditing();
|
|
188
|
+
|
|
189
|
+
const other = new Platform();
|
|
190
|
+
other.id = 'second-tenant';
|
|
191
|
+
other.periodId = root.periodId;
|
|
192
|
+
other.config = PlatformConfig.create({
|
|
193
|
+
membershipTypes: [PlatformMembershipType.create({ id: 't2', name: 'Second tenant type' })],
|
|
194
|
+
});
|
|
195
|
+
await other.save();
|
|
196
|
+
|
|
197
|
+
return { root, other };
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
afterEach(async () => {
|
|
201
|
+
await Platform.clearCacheForTenantWithoutRefresh('second-tenant');
|
|
202
|
+
await Database.delete('DELETE FROM platform WHERE id != ?', ['1']);
|
|
203
|
+
await Platform.clearCache();
|
|
204
|
+
});
|
|
205
|
+
|
|
206
|
+
test('each tenant caches its own struct', async () => {
|
|
207
|
+
const { root } = await createSecondTenant();
|
|
208
|
+
|
|
209
|
+
root.config.membershipTypes = [PlatformMembershipType.create({ id: 't1', name: 'Root type' })];
|
|
210
|
+
await root.save();
|
|
211
|
+
|
|
212
|
+
const rootStruct = await Platform.getStructForTenant('1');
|
|
213
|
+
const otherStruct = await Platform.getStructForTenant('second-tenant');
|
|
214
|
+
|
|
215
|
+
expect(rootStruct.config.membershipTypes.map(m => m.name)).toEqual(['Root type']);
|
|
216
|
+
expect(otherStruct.config.membershipTypes.map(m => m.name)).toEqual(['Second tenant type']);
|
|
217
|
+
});
|
|
218
|
+
|
|
219
|
+
test('saving one tenant does not discard another tenant cache', async () => {
|
|
220
|
+
const { root } = await createSecondTenant();
|
|
221
|
+
|
|
222
|
+
const otherBefore = await Platform.getStructForTenant('second-tenant');
|
|
223
|
+
|
|
224
|
+
root.config.membershipTypes = [PlatformMembershipType.create({ id: 't1', name: 'Changed' })];
|
|
225
|
+
await root.save();
|
|
226
|
+
|
|
227
|
+
// Same object identity: the second tenant's cache was never rebuilt
|
|
228
|
+
expect(await Platform.getStructForTenant('second-tenant')).toBe(otherBefore);
|
|
229
|
+
expect((await Platform.getStructForTenant('1')).config.membershipTypes[0].name).toBe('Changed');
|
|
230
|
+
});
|
|
231
|
+
|
|
232
|
+
test('clearing one tenant cache leaves the other in place', async () => {
|
|
233
|
+
await createSecondTenant();
|
|
234
|
+
|
|
235
|
+
const rootBefore = await Platform.getStructForTenant('1');
|
|
236
|
+
const otherBefore = await Platform.getStructForTenant('second-tenant');
|
|
237
|
+
|
|
238
|
+
await Platform.clearCacheForTenant('second-tenant');
|
|
239
|
+
|
|
240
|
+
expect(await Platform.getStructForTenant('1')).toBe(rootBefore);
|
|
241
|
+
expect(await Platform.getStructForTenant('second-tenant')).not.toBe(otherBefore);
|
|
242
|
+
});
|
|
243
|
+
|
|
244
|
+
test('one tenant loading its cache does not queue behind another', async () => {
|
|
245
|
+
await createSecondTenant();
|
|
246
|
+
await Platform.clearCacheForTenantWithoutRefresh('second-tenant');
|
|
247
|
+
|
|
248
|
+
let release!: () => void;
|
|
249
|
+
const held = new Promise<void>((resolve) => {
|
|
250
|
+
release = resolve;
|
|
251
|
+
});
|
|
252
|
+
|
|
253
|
+
// Occupy the key a process-wide cache would have used. If the per-tenant load shares it,
|
|
254
|
+
// this never resolves and the test times out.
|
|
255
|
+
const blocker = QueueHandler.schedule('Platform.loadCaches', async () => {
|
|
256
|
+
await held;
|
|
257
|
+
});
|
|
258
|
+
|
|
259
|
+
await Platform.getStructForTenant('second-tenant');
|
|
260
|
+
|
|
261
|
+
release();
|
|
262
|
+
await blocker;
|
|
263
|
+
}, 5000);
|
|
264
|
+
|
|
265
|
+
test('an unknown tenant is not created on the fly', async () => {
|
|
266
|
+
await expect(Platform.getForEditing('does-not-exist')).rejects.toThrow(
|
|
267
|
+
STExpect.simpleError({ code: 'tenant_not_found' }),
|
|
268
|
+
);
|
|
269
|
+
});
|
|
270
|
+
});
|
|
107
271
|
});
|
package/src/models/Platform.ts
CHANGED
|
@@ -8,6 +8,14 @@ import { deepFreeze } from '@stamhoofd/utility';
|
|
|
8
8
|
import { v4 as uuidv4 } from 'uuid';
|
|
9
9
|
import { RegistrationPeriod } from './RegistrationPeriod.js';
|
|
10
10
|
|
|
11
|
+
export const ROOT_TENANT_ID = '1';
|
|
12
|
+
|
|
13
|
+
type TenantCache = {
|
|
14
|
+
model: Readonly<Platform>;
|
|
15
|
+
struct: PlatformStruct;
|
|
16
|
+
privateStruct: PlatformStruct & { privateConfig: PlatformPrivateConfig };
|
|
17
|
+
};
|
|
18
|
+
|
|
11
19
|
export class Platform extends QueryableModel {
|
|
12
20
|
static table = 'platform';
|
|
13
21
|
|
|
@@ -18,6 +26,28 @@ export class Platform extends QueryableModel {
|
|
|
18
26
|
})
|
|
19
27
|
id!: string;
|
|
20
28
|
|
|
29
|
+
/**
|
|
30
|
+
* The tenant this tenant belongs to. Null for a root tenant.
|
|
31
|
+
*/
|
|
32
|
+
@column({ type: 'string', nullable: true })
|
|
33
|
+
parentTenantId: string | null = null;
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* The tenant that charges this tenant for packages, transfer fees, service fees and invoices.
|
|
37
|
+
* Only this may point outside the tenant's own subtree, and only at an ancestor.
|
|
38
|
+
*/
|
|
39
|
+
@column({ type: 'string', nullable: true })
|
|
40
|
+
feesTenantId: string | null = null;
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Globally unique, shares its namespace with organizations.uri.
|
|
44
|
+
*/
|
|
45
|
+
@column({ type: 'string', nullable: true })
|
|
46
|
+
uri: string | null = null;
|
|
47
|
+
|
|
48
|
+
@column({ type: 'string', nullable: true })
|
|
49
|
+
domain: string | null = null;
|
|
50
|
+
|
|
21
51
|
@column({ type: 'json', decoder: PlatformConfig })
|
|
22
52
|
config: PlatformConfig = PlatformConfig.create({});
|
|
23
53
|
|
|
@@ -59,20 +89,20 @@ export class Platform extends QueryableModel {
|
|
|
59
89
|
});
|
|
60
90
|
}
|
|
61
91
|
|
|
62
|
-
private static
|
|
63
|
-
private static sharedPrivateStruct: PlatformStruct & { privateConfig: PlatformPrivateConfig } | null = null;
|
|
64
|
-
private static sharedStruct: PlatformStruct | null = null;
|
|
92
|
+
private static caches: Map<string, TenantCache> = new Map();
|
|
65
93
|
|
|
66
|
-
static async
|
|
67
|
-
|
|
68
|
-
await this.loadCaches();
|
|
69
|
-
}
|
|
94
|
+
static async getStructForTenant(tenantId: string): Promise<PlatformStruct> {
|
|
95
|
+
const struct = (await this.getCache(tenantId)).struct;
|
|
70
96
|
|
|
71
|
-
if (
|
|
97
|
+
if (struct.privateConfig) {
|
|
72
98
|
throw new Error('[Platform] Failed to load platform shared struct');
|
|
73
99
|
}
|
|
74
100
|
|
|
75
|
-
return
|
|
101
|
+
return struct;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
static async getSharedStruct(): Promise<PlatformStruct> {
|
|
105
|
+
return await this.getStructForTenant(ROOT_TENANT_ID);
|
|
76
106
|
}
|
|
77
107
|
|
|
78
108
|
async setPreviousPeriodId() {
|
|
@@ -81,29 +111,43 @@ export class Platform extends QueryableModel {
|
|
|
81
111
|
this.nextPeriodId = period?.nextPeriodId ?? null;
|
|
82
112
|
}
|
|
83
113
|
|
|
84
|
-
static async
|
|
85
|
-
|
|
86
|
-
await this.loadCaches();
|
|
87
|
-
}
|
|
114
|
+
static async getPrivateStructForTenant(tenantId: string): Promise<PlatformStruct & { privateConfig: PlatformPrivateConfig }> {
|
|
115
|
+
const privateStruct = (await this.getCache(tenantId)).privateStruct;
|
|
88
116
|
|
|
89
|
-
if (!
|
|
117
|
+
if (!privateStruct.privateConfig) {
|
|
90
118
|
throw new Error('[Platform] Failed to load platform shared private struct');
|
|
91
119
|
}
|
|
92
120
|
|
|
93
|
-
return
|
|
121
|
+
return privateStruct;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
static async getSharedPrivateStruct(): Promise<PlatformStruct & { privateConfig: PlatformPrivateConfig }> {
|
|
125
|
+
return await this.getPrivateStructForTenant(ROOT_TENANT_ID);
|
|
94
126
|
}
|
|
95
127
|
|
|
96
|
-
static async getForEditing(): Promise<Platform> {
|
|
97
|
-
return QueueHandler.schedule('Platform.getModel', async () => {
|
|
128
|
+
static async getForEditing(tenantId: string = ROOT_TENANT_ID): Promise<Platform> {
|
|
129
|
+
return QueueHandler.schedule('Platform.getModel-' + tenantId, async () => {
|
|
98
130
|
// Build a new one
|
|
99
|
-
let model = await this.getByID(
|
|
131
|
+
let model = await this.getByID(tenantId);
|
|
100
132
|
|
|
101
133
|
if (!model) {
|
|
134
|
+
if (tenantId !== ROOT_TENANT_ID) {
|
|
135
|
+
// Only the root tenant bootstraps itself. Any other tenant is created explicitly.
|
|
136
|
+
throw new SimpleError({
|
|
137
|
+
code: 'tenant_not_found',
|
|
138
|
+
message: 'Tenant ' + tenantId + ' not found',
|
|
139
|
+
statusCode: 404,
|
|
140
|
+
});
|
|
141
|
+
}
|
|
142
|
+
|
|
102
143
|
console.info('[Platform] Creating new platform');
|
|
103
144
|
|
|
104
145
|
// Create a new platform
|
|
105
146
|
model = new Platform();
|
|
106
|
-
model.id =
|
|
147
|
+
model.id = tenantId;
|
|
148
|
+
model.feesTenantId = model.id;
|
|
149
|
+
model.uri = STAMHOOFD.platformName;
|
|
150
|
+
model.domain = STAMHOOFD.domains.dashboard ?? null;
|
|
107
151
|
|
|
108
152
|
if (STAMHOOFD.userMode === 'platform') {
|
|
109
153
|
model.periodId = (await RegistrationPeriod.all())[0].id;
|
|
@@ -120,37 +164,46 @@ export class Platform extends QueryableModel {
|
|
|
120
164
|
});
|
|
121
165
|
}
|
|
122
166
|
|
|
167
|
+
static async getForTenant(tenantId: string): Promise<Readonly<Platform> & { save: never }> {
|
|
168
|
+
return (await this.getCache(tenantId)).model as any;
|
|
169
|
+
}
|
|
170
|
+
|
|
123
171
|
static async getShared(): Promise<Readonly<Platform> & { save: never }> {
|
|
124
|
-
|
|
172
|
+
return await this.getForTenant(ROOT_TENANT_ID);
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
private static async getCache(tenantId: string): Promise<TenantCache> {
|
|
176
|
+
const cached = this.caches.get(tenantId);
|
|
177
|
+
if (cached) {
|
|
125
178
|
// Skip queue if possible (performance optimization)
|
|
126
|
-
return
|
|
179
|
+
return cached;
|
|
127
180
|
}
|
|
128
181
|
|
|
129
|
-
|
|
130
|
-
if (this.shared) {
|
|
131
|
-
return this.shared;
|
|
132
|
-
}
|
|
182
|
+
await this.loadCachesForTenant(tenantId);
|
|
133
183
|
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
});
|
|
184
|
+
const loaded = this.caches.get(tenantId);
|
|
185
|
+
if (!loaded) {
|
|
186
|
+
throw new Error('[Platform] Failed to load caches for tenant ' + tenantId);
|
|
187
|
+
}
|
|
188
|
+
return loaded;
|
|
140
189
|
}
|
|
141
190
|
|
|
142
|
-
static async
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
191
|
+
static async loadCachesForTenant(tenantId: string): Promise<void> {
|
|
192
|
+
// Keyed per tenant: a global key would stall every tenant behind one tenant's reload.
|
|
193
|
+
await QueueHandler.schedule('Platform.loadCaches-' + tenantId, async () => {
|
|
194
|
+
if (this.caches.has(tenantId)) {
|
|
195
|
+
// Already loaded (possible if multiple calls were made)
|
|
146
196
|
return;
|
|
147
197
|
}
|
|
148
|
-
|
|
149
|
-
const model = await this.getForEditing();
|
|
198
|
+
const model = await this.getForEditing(tenantId);
|
|
150
199
|
await this.setCachesFromModel(model);
|
|
151
200
|
});
|
|
152
201
|
}
|
|
153
202
|
|
|
203
|
+
static async loadCaches(): Promise<void> {
|
|
204
|
+
await this.loadCachesForTenant(ROOT_TENANT_ID);
|
|
205
|
+
}
|
|
206
|
+
|
|
154
207
|
private static async setCachesFromModel(model: Platform) {
|
|
155
208
|
// Set structure cache
|
|
156
209
|
const period = await RegistrationPeriod.getByID(model.periodId);
|
|
@@ -160,31 +213,46 @@ export class Platform extends QueryableModel {
|
|
|
160
213
|
});
|
|
161
214
|
|
|
162
215
|
// We clone to avoid the chance of updating the platform model
|
|
163
|
-
|
|
216
|
+
const privateStruct = struct.clone() as PlatformStruct & { privateConfig: PlatformPrivateConfig };
|
|
164
217
|
|
|
165
218
|
const clone = struct.clone();
|
|
166
219
|
clone.privateConfig = null;
|
|
167
220
|
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
221
|
+
if (model.id === ROOT_TENANT_ID) {
|
|
222
|
+
// Audit logs render uuids from a bare id, so they cannot receive a platform through their
|
|
223
|
+
// call chain. Bind the resolver to the struct we are about to cache, so it is refreshed
|
|
224
|
+
// together with the caches. Uses the public struct on purpose: resolving privateConfig
|
|
225
|
+
// roles would change the names that get persisted in audit logs.
|
|
226
|
+
// Still process-wide: it becomes tenant-aware once a request carries its tenant.
|
|
227
|
+
AuditLogReplacementDependencies.uuidToName = uuid => uuidToName(uuid, clone);
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
deepFreeze(model);
|
|
231
|
+
|
|
232
|
+
this.caches.set(model.id, {
|
|
233
|
+
model,
|
|
234
|
+
struct: clone,
|
|
235
|
+
privateStruct,
|
|
236
|
+
});
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
static async clearCacheForTenant(tenantId: string) {
|
|
240
|
+
await this.clearCacheForTenantWithoutRefresh(tenantId);
|
|
241
|
+
await this.loadCachesForTenant(tenantId);
|
|
242
|
+
}
|
|
173
243
|
|
|
174
|
-
|
|
244
|
+
static async clearCacheForTenantWithoutRefresh(tenantId: string) {
|
|
245
|
+
await QueueHandler.schedule('Platform.loadCaches-' + tenantId, async () => {
|
|
246
|
+
this.caches.delete(tenantId);
|
|
247
|
+
});
|
|
175
248
|
}
|
|
176
249
|
|
|
177
250
|
static async clearCache() {
|
|
178
|
-
await this.
|
|
179
|
-
await this.loadCaches();
|
|
251
|
+
await this.clearCacheForTenant(ROOT_TENANT_ID);
|
|
180
252
|
}
|
|
181
253
|
|
|
182
254
|
static async clearCacheWithoutRefresh() {
|
|
183
|
-
await
|
|
184
|
-
this.sharedStruct = null;
|
|
185
|
-
this.sharedPrivateStruct = null;
|
|
186
|
-
});
|
|
187
|
-
this.shared = null;
|
|
255
|
+
await this.clearCacheForTenantWithoutRefresh(ROOT_TENANT_ID);
|
|
188
256
|
}
|
|
189
257
|
|
|
190
258
|
async save() {
|
|
@@ -195,8 +263,8 @@ export class Platform extends QueryableModel {
|
|
|
195
263
|
const s = await super.save();
|
|
196
264
|
|
|
197
265
|
if (update) {
|
|
198
|
-
//
|
|
199
|
-
await Platform.
|
|
266
|
+
// Only this tenant's cache: another tenant's is unaffected by this save.
|
|
267
|
+
await Platform.clearCacheForTenant(this.id);
|
|
200
268
|
}
|
|
201
269
|
|
|
202
270
|
return s;
|
package/src/models/Token.ts
CHANGED
|
@@ -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
|
-
|
|
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
|
}
|
package/src/models/User.ts
CHANGED
|
@@ -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
|
|