@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,15 +1,11 @@
1
1
  import type { ManyToOneRelation } from '@simonbackx/simple-database';
2
2
  import { column, Database } from '@simonbackx/simple-database';
3
- import type { I18n } from '@stamhoofd/backend-i18n';
4
3
  import { QueryableModel } from '@stamhoofd/sql';
5
4
  import basex from 'base-x';
6
5
  import crypto from 'crypto';
7
6
 
8
- import type { Organization } from './Organization.js';
9
7
  import { User } from './User.js';
10
8
  import { SimpleError } from '@simonbackx/simple-errors';
11
- import { getAppHost } from '@stamhoofd/structures';
12
- import { Platform } from './Platform.js';
13
9
  const ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
14
10
  const bs58 = basex(ALPHABET);
15
11
 
@@ -122,31 +118,6 @@ export class PasswordToken extends QueryableModel {
122
118
  return token;
123
119
  }
124
120
 
125
- static async getPasswordRecoveryUrl(user: User, organization: Organization | null, i18n: I18n, validUntil?: Date) {
126
- // Send an e-mail to say you already have an account + follow password forgot flow
127
- const token = await PasswordToken.createToken(user, validUntil);
128
- return token.getPasswordRecoveryUrl(organization, i18n, user);
129
- }
130
-
131
- /**
132
- * Build the password recovery url for this (already created) token.
133
- * Pass the user to avoid an extra query when it is already loaded.
134
- */
135
- async getPasswordRecoveryUrl(organization: Organization | null, i18n: I18n, user?: User) {
136
- const tokenUser = user ?? await User.getByID(this.userId);
137
- if (!tokenUser) {
138
- throw new Error('PasswordToken without a valid user');
139
- }
140
-
141
- if (tokenUser.organizationId !== null && ((tokenUser.organizationId ?? null) !== (organization?.id ?? null))) {
142
- throw new Error('Unexpected mismatch in organization id for PasswordToken');
143
- }
144
-
145
- const hasOrganizationPermissions = organization ? tokenUser.permissions?.forOrganization(organization, await Platform.getSharedStruct())?.isEmpty === false : false;
146
- const host = 'https://' + getAppHost(hasOrganizationPermissions ? 'dashboard' : 'registration', organization, hasOrganizationPermissions, i18n);
147
- return host + '/reset-password?token=' + encodeURIComponent(this.token);
148
- }
149
-
150
121
  static async clearFor(userId: string) {
151
122
  const query = `DELETE from ${this.table} where userId = ?`;
152
123
  await Database.delete(query, [userId]);
@@ -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
- const platform = await Platform.getByID('1');
9
- platform!.config = PlatformConfig.create({});
10
- await platform!.save();
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
  });
@@ -2,11 +2,20 @@ import { column } from '@simonbackx/simple-database';
2
2
  import { SimpleError } from '@simonbackx/simple-errors';
3
3
  import { QueueHandler } from '@stamhoofd/queues';
4
4
  import { QueryableModel } from '@stamhoofd/sql';
5
- import { PlatformConfig, PlatformPrivateConfig, PlatformServerConfig, Platform as PlatformStruct } from '@stamhoofd/structures';
5
+ import { AuditLogReplacementDependencies, PlatformConfig, PlatformPrivateConfig, PlatformServerConfig, Platform as PlatformStruct } from '@stamhoofd/structures';
6
+ import { uuidToName } from '@stamhoofd/structures/helpers/uuidToName.js';
6
7
  import { deepFreeze } from '@stamhoofd/utility';
7
8
  import { v4 as uuidv4 } from 'uuid';
8
9
  import { RegistrationPeriod } from './RegistrationPeriod.js';
9
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
+
10
19
  export class Platform extends QueryableModel {
11
20
  static table = 'platform';
12
21
 
@@ -17,6 +26,28 @@ export class Platform extends QueryableModel {
17
26
  })
18
27
  id!: string;
19
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
+
20
51
  @column({ type: 'json', decoder: PlatformConfig })
21
52
  config: PlatformConfig = PlatformConfig.create({});
22
53
 
@@ -58,20 +89,20 @@ export class Platform extends QueryableModel {
58
89
  });
59
90
  }
60
91
 
61
- private static shared: Platform | null = null;
62
- private static sharedPrivateStruct: PlatformStruct & { privateConfig: PlatformPrivateConfig } | null = null;
63
- private static sharedStruct: PlatformStruct | null = null;
92
+ private static caches: Map<string, TenantCache> = new Map();
64
93
 
65
- static async getSharedStruct(): Promise<PlatformStruct> {
66
- if (!this.sharedStruct) {
67
- await this.loadCaches();
68
- }
94
+ static async getStructForTenant(tenantId: string): Promise<PlatformStruct> {
95
+ const struct = (await this.getCache(tenantId)).struct;
69
96
 
70
- if (!this.sharedStruct || !!this.sharedStruct.privateConfig) {
97
+ if (struct.privateConfig) {
71
98
  throw new Error('[Platform] Failed to load platform shared struct');
72
99
  }
73
100
 
74
- return this.sharedStruct;
101
+ return struct;
102
+ }
103
+
104
+ static async getSharedStruct(): Promise<PlatformStruct> {
105
+ return await this.getStructForTenant(ROOT_TENANT_ID);
75
106
  }
76
107
 
77
108
  async setPreviousPeriodId() {
@@ -80,29 +111,43 @@ export class Platform extends QueryableModel {
80
111
  this.nextPeriodId = period?.nextPeriodId ?? null;
81
112
  }
82
113
 
83
- static async getSharedPrivateStruct(): Promise<PlatformStruct & { privateConfig: PlatformPrivateConfig }> {
84
- if (!this.sharedPrivateStruct) {
85
- await this.loadCaches();
86
- }
114
+ static async getPrivateStructForTenant(tenantId: string): Promise<PlatformStruct & { privateConfig: PlatformPrivateConfig }> {
115
+ const privateStruct = (await this.getCache(tenantId)).privateStruct;
87
116
 
88
- if (!this.sharedPrivateStruct || !this.sharedPrivateStruct.privateConfig) {
117
+ if (!privateStruct.privateConfig) {
89
118
  throw new Error('[Platform] Failed to load platform shared private struct');
90
119
  }
91
120
 
92
- return this.sharedPrivateStruct;
121
+ return privateStruct;
122
+ }
123
+
124
+ static async getSharedPrivateStruct(): Promise<PlatformStruct & { privateConfig: PlatformPrivateConfig }> {
125
+ return await this.getPrivateStructForTenant(ROOT_TENANT_ID);
93
126
  }
94
127
 
95
- static async getForEditing(): Promise<Platform> {
96
- 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 () => {
97
130
  // Build a new one
98
- let model = await this.getByID('1');
131
+ let model = await this.getByID(tenantId);
99
132
 
100
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
+
101
143
  console.info('[Platform] Creating new platform');
102
144
 
103
145
  // Create a new platform
104
146
  model = new Platform();
105
- model.id = '1';
147
+ model.id = tenantId;
148
+ model.feesTenantId = model.id;
149
+ model.uri = STAMHOOFD.platformName;
150
+ model.domain = STAMHOOFD.domains.dashboard ?? null;
106
151
 
107
152
  if (STAMHOOFD.userMode === 'platform') {
108
153
  model.periodId = (await RegistrationPeriod.all())[0].id;
@@ -119,37 +164,46 @@ export class Platform extends QueryableModel {
119
164
  });
120
165
  }
121
166
 
167
+ static async getForTenant(tenantId: string): Promise<Readonly<Platform> & { save: never }> {
168
+ return (await this.getCache(tenantId)).model as any;
169
+ }
170
+
122
171
  static async getShared(): Promise<Readonly<Platform> & { save: never }> {
123
- if (this.shared) {
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) {
124
178
  // Skip queue if possible (performance optimization)
125
- return this.shared as any;
179
+ return cached;
126
180
  }
127
181
 
128
- return QueueHandler.schedule('Platform.getShared', async () => {
129
- if (this.shared) {
130
- return this.shared;
131
- }
182
+ await this.loadCachesForTenant(tenantId);
132
183
 
133
- // Build a new one
134
- const model = await this.getForEditing();
135
- deepFreeze(model);
136
- this.shared = model;
137
- return model as any;
138
- });
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;
139
189
  }
140
190
 
141
- static async loadCaches(): Promise<void> {
142
- await QueueHandler.schedule('Platform.loadCaches', async () => {
143
- if (this.sharedPrivateStruct && this.sharedStruct) {
144
- // Already loaded (possible if multiple calls to loadCaches were made)
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)
145
196
  return;
146
197
  }
147
- // Build a new one
148
- const model = await this.getForEditing();
198
+ const model = await this.getForEditing(tenantId);
149
199
  await this.setCachesFromModel(model);
150
200
  });
151
201
  }
152
202
 
203
+ static async loadCaches(): Promise<void> {
204
+ await this.loadCachesForTenant(ROOT_TENANT_ID);
205
+ }
206
+
153
207
  private static async setCachesFromModel(model: Platform) {
154
208
  // Set structure cache
155
209
  const period = await RegistrationPeriod.getByID(model.periodId);
@@ -159,25 +213,46 @@ export class Platform extends QueryableModel {
159
213
  });
160
214
 
161
215
  // We clone to avoid the chance of updating the platform model
162
- this.sharedPrivateStruct = struct.clone() as PlatformStruct & { privateConfig: PlatformPrivateConfig };
216
+ const privateStruct = struct.clone() as PlatformStruct & { privateConfig: PlatformPrivateConfig };
163
217
 
164
218
  const clone = struct.clone();
165
219
  clone.privateConfig = null;
166
- clone.setShared();
167
- this.sharedStruct = clone;
220
+
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
+ }
243
+
244
+ static async clearCacheForTenantWithoutRefresh(tenantId: string) {
245
+ await QueueHandler.schedule('Platform.loadCaches-' + tenantId, async () => {
246
+ this.caches.delete(tenantId);
247
+ });
168
248
  }
169
249
 
170
250
  static async clearCache() {
171
- await this.clearCacheWithoutRefresh();
172
- await this.loadCaches();
251
+ await this.clearCacheForTenant(ROOT_TENANT_ID);
173
252
  }
174
253
 
175
254
  static async clearCacheWithoutRefresh() {
176
- await QueueHandler.schedule('Platform.loadCaches', async () => {
177
- this.sharedStruct = null;
178
- this.sharedPrivateStruct = null;
179
- });
180
- this.shared = null;
255
+ await this.clearCacheForTenantWithoutRefresh(ROOT_TENANT_ID);
181
256
  }
182
257
 
183
258
  async save() {
@@ -188,8 +263,8 @@ export class Platform extends QueryableModel {
188
263
  const s = await super.save();
189
264
 
190
265
  if (update) {
191
- // Force update cache immediately
192
- await Platform.clearCache();
266
+ // Only this tenant's cache: another tenant's is unaffected by this save.
267
+ await Platform.clearCacheForTenant(this.id);
193
268
  }
194
269
 
195
270
  return s;
@@ -1,12 +1,9 @@
1
1
  import { column } from '@simonbackx/simple-database';
2
2
  import { SimpleError } from '@simonbackx/simple-errors';
3
- import { EmailTemplateType, Recipient, Replacement, STPackageMeta, STPackageStatus, STPackageStatusServiceFee, STPackageType, STPricingType } from '@stamhoofd/structures';
4
- import { Formatter } from '@stamhoofd/utility';
3
+ import { STPackageMeta, STPackageStatus, STPackageStatusServiceFee, STPackageType, STPricingType } from '@stamhoofd/structures';
5
4
  import { v4 as uuidv4 } from 'uuid';
6
5
 
7
6
  import { QueryableModel } from '@stamhoofd/sql';
8
- import { sendEmailTemplate } from '../helpers/EmailBuilder.js';
9
- import { Organization } from './Organization.js';
10
7
 
11
8
  export class STPackage extends QueryableModel {
12
9
  static table = 'stamhoofd_packages';
@@ -196,110 +193,4 @@ export class STPackage extends QueryableModel {
196
193
  )],
197
194
  });
198
195
  }
199
-
200
- async sendExpiryEmail() {
201
- if (this.validAt === null) {
202
- // never activated
203
- return;
204
- }
205
-
206
- if (this.removeAt && this.removeAt <= new Date()) {
207
- this.emailCount += 1;
208
- await this.save();
209
- return;
210
- }
211
-
212
- let allowDays = 0;
213
- let type: EmailTemplateType | null = null;
214
-
215
- if (this.meta.type === STPackageType.Members) {
216
- type = EmailTemplateType.MembersExpirationReminder;
217
- allowDays = 32;
218
- } else if (this.meta.type === STPackageType.Webshops) {
219
- type = EmailTemplateType.WebshopsExpirationReminder;
220
- allowDays = 32;
221
- } else if (this.meta.type === STPackageType.SingleWebshop) {
222
- type = EmailTemplateType.SingleWebshopExpirationReminder;
223
- allowDays = 7;
224
- } else if (this.meta.type === STPackageType.TrialMembers) {
225
- type = EmailTemplateType.TrialMembersExpirationReminder;
226
- allowDays = 3;
227
- } else if (this.meta.type === STPackageType.TrialWebshops) {
228
- type = EmailTemplateType.TrialWebshopsExpirationReminder;
229
- allowDays = 3;
230
- }
231
-
232
- const allowFrom = new Date(Date.now() + 1000 * 60 * 60 * 24 * allowDays);
233
- if (type && (this.validUntil === null || this.validUntil < new Date() || this.validUntil > allowFrom)) {
234
- console.log('Skip sending expiration email for ' + this.id);
235
- return;
236
- }
237
-
238
- if (type) {
239
- console.log('Sending expiration email for ' + this.id, type);
240
- if (STAMHOOFD.environment === 'production') {
241
- await this.sendEmailTemplate({
242
- type,
243
- });
244
- }
245
- this.lastEmailAt = new Date();
246
- } else {
247
- console.log('Skip sending expiration email for ' + this.id + ' (no type)');
248
- }
249
-
250
- this.emailCount += 1;
251
- await this.save();
252
- }
253
-
254
- async sendEmailTemplate(data: {
255
- type: EmailTemplateType;
256
- replyTo?: string;
257
- }) {
258
- const organization = await Organization.getByID(this.organizationId);
259
-
260
- if (!organization) {
261
- console.error('Could not find package organization ' + this.id);
262
- return;
263
- }
264
-
265
- const admins = await organization.getFullAdmins();
266
-
267
- const recipients = admins.map(admin =>
268
- Recipient.create({
269
- firstName: admin.firstName,
270
- lastName: admin.lastName,
271
- email: admin.email,
272
- replacements: [
273
- Replacement.create({
274
- token: 'organizationName',
275
- value: organization.name,
276
- }),
277
- Replacement.create({
278
- token: 'packageName',
279
- value: this.meta.name ?? '',
280
- }),
281
- Replacement.create({
282
- token: 'validUntil',
283
- value: this.validUntil ? Formatter.dateTime(this.validUntil) : 'nooit',
284
- }),
285
- Replacement.create({
286
- token: 'validUntilDate',
287
- value: this.validUntil ? Formatter.date(this.validUntil) : 'nooit',
288
- }),
289
- Replacement.create({
290
- token: 'renewUrl',
291
- value: `https://${(STAMHOOFD.domains.dashboard ?? 'stamhoofd.app')}/${organization.i18n.locale}/beheerders/${organization.uri}/instellingen/functionaliteiten`,
292
- }),
293
- ],
294
- }),
295
- );
296
-
297
- // Create e-mail builder
298
- await sendEmailTemplate(null, {
299
- template: {
300
- type: data.type,
301
- },
302
- recipients,
303
- });
304
- }
305
196
  }