@stamhoofd/models 2.137.5 → 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 (118) 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/Email.d.ts +0 -6
  34. package/dist/models/Email.d.ts.map +1 -1
  35. package/dist/models/Email.js +4 -625
  36. package/dist/models/Email.js.map +1 -1
  37. package/dist/models/MFARecoveryCode.d.ts +17 -0
  38. package/dist/models/MFARecoveryCode.d.ts.map +1 -0
  39. package/dist/models/MFARecoveryCode.js +55 -0
  40. package/dist/models/MFARecoveryCode.js.map +1 -0
  41. package/dist/models/MFATOTP.d.ts +44 -0
  42. package/dist/models/MFATOTP.d.ts.map +1 -0
  43. package/dist/models/MFATOTP.js +116 -0
  44. package/dist/models/MFATOTP.js.map +1 -0
  45. package/dist/models/MFAToken.d.ts +49 -0
  46. package/dist/models/MFAToken.d.ts.map +1 -0
  47. package/dist/models/MFAToken.js +137 -0
  48. package/dist/models/MFAToken.js.map +1 -0
  49. package/dist/models/Organization.d.ts +1 -38
  50. package/dist/models/Organization.d.ts.map +1 -1
  51. package/dist/models/Organization.js +1 -132
  52. package/dist/models/Organization.js.map +1 -1
  53. package/dist/models/Platform.d.ts +28 -4
  54. package/dist/models/Platform.d.ts.map +1 -1
  55. package/dist/models/Platform.js +109 -53
  56. package/dist/models/Platform.js.map +1 -1
  57. package/dist/models/Token.d.ts +40 -1
  58. package/dist/models/Token.d.ts.map +1 -1
  59. package/dist/models/Token.js +68 -2
  60. package/dist/models/Token.js.map +1 -1
  61. package/dist/models/User.d.ts +25 -0
  62. package/dist/models/User.d.ts.map +1 -1
  63. package/dist/models/User.js +36 -0
  64. package/dist/models/User.js.map +1 -1
  65. package/dist/models/WebauthnChallenge.d.ts +27 -0
  66. package/dist/models/WebauthnChallenge.d.ts.map +1 -0
  67. package/dist/models/WebauthnChallenge.js +81 -0
  68. package/dist/models/WebauthnChallenge.js.map +1 -0
  69. package/dist/models/WebauthnCredential.d.ts +58 -0
  70. package/dist/models/WebauthnCredential.d.ts.map +1 -0
  71. package/dist/models/WebauthnCredential.js +144 -0
  72. package/dist/models/WebauthnCredential.js.map +1 -0
  73. package/dist/models/index.d.ts +5 -0
  74. package/dist/models/index.d.ts.map +1 -1
  75. package/dist/models/index.js +5 -0
  76. package/dist/models/index.js.map +1 -1
  77. package/package.json +3 -3
  78. package/src/helpers/Handlebars.ts +5 -9
  79. package/src/helpers/errorToSimpleErrors.ts +17 -0
  80. package/src/index.ts +0 -1
  81. package/src/migrations/1782902314-tokens-authenticated-at.sql +2 -0
  82. package/src/migrations/1782902315-create-mfa-totp-table.sql +13 -0
  83. package/src/migrations/1782902316-create-webauthn-credentials-table.sql +17 -0
  84. package/src/migrations/1782902317-create-mfa-recovery-codes-table.sql +10 -0
  85. package/src/migrations/1782902318-create-mfa-tokens-table.sql +13 -0
  86. package/src/migrations/1782902319-create-webauthn-challenges-table.sql +10 -0
  87. package/src/migrations/1784039947-mfa-totp-last-used-counter.sql +2 -0
  88. package/src/migrations/1784122354-webauthn-credential-provider.sql +3 -0
  89. package/src/migrations/1784500000-webauthn-credential-rp-id.sql +9 -0
  90. package/src/migrations/1785354091-platform-parent-tenant-id.sql +1 -0
  91. package/src/migrations/1785354092-platform-fees-tenant-id.sql +1 -0
  92. package/src/migrations/1785354093-platform-uri.sql +1 -0
  93. package/src/migrations/1785354094-platform-domain.sql +1 -0
  94. package/src/migrations/1785354095-platform-uri-unique.sql +1 -0
  95. package/src/migrations/1785354096-platform-domain-unique.sql +1 -0
  96. package/src/migrations/1785354097-platform-parent-tenant-id-index.sql +1 -0
  97. package/src/migrations/1785354098-platform-tenant-backfill.ts +14 -0
  98. package/src/migrations/1785417301-users-last-active-at.sql +2 -0
  99. package/src/models/Email.ts +4 -713
  100. package/src/models/MFARecoveryCode.ts +52 -0
  101. package/src/models/MFATOTP.ts +112 -0
  102. package/src/models/MFAToken.ts +138 -0
  103. package/src/models/Organization.test.ts +0 -46
  104. package/src/models/Organization.ts +0 -154
  105. package/src/models/Platform.test.ts +167 -3
  106. package/src/models/Platform.ts +121 -53
  107. package/src/models/Token.ts +73 -2
  108. package/src/models/User.ts +37 -0
  109. package/src/models/WebauthnChallenge.ts +80 -0
  110. package/src/models/WebauthnCredential.ts +130 -0
  111. package/src/models/index.ts +6 -0
  112. package/dist/helpers/EmailBuilder.d.ts +0 -121
  113. package/dist/helpers/EmailBuilder.d.ts.map +0 -1
  114. package/dist/helpers/EmailBuilder.js +0 -659
  115. package/dist/helpers/EmailBuilder.js.map +0 -1
  116. package/src/helpers/EmailBuilder.test.ts +0 -291
  117. package/src/helpers/EmailBuilder.ts +0 -818
  118. package/src/models/Email.test.ts +0 -1222
@@ -1,818 +0,0 @@
1
- import type { EmailBuilder, EmailInterfaceRecipient } from '@stamhoofd/email';
2
- import { Email, EmailAddress } from '@stamhoofd/email';
3
- import type { EmailContent, EmailRecipient as EmailRecipientStruct, EmailTemplateType, OrganizationEmail, Platform as PlatformStruct, Recipient } from '@stamhoofd/structures';
4
- import { BalanceItem as BalanceItemStruct, getAppHost, ReceivableBalanceType, replaceEmailHtml, replaceEmailText, Replacement } from '@stamhoofd/structures';
5
- import type { Language } from '@stamhoofd/types/Language';
6
- import { Formatter } from '@stamhoofd/utility';
7
-
8
- import { SimpleError } from '@simonbackx/simple-errors';
9
- import { I18n } from '@stamhoofd/backend-i18n/I18n';
10
- import { EmailRecipient } from '../models/EmailRecipient.js';
11
- import { CachedBalance } from '../models/CachedBalance.js';
12
- import { EmailTemplate } from '../models/EmailTemplate.js';
13
- import type { Group } from '../models/Group.js';
14
- import type { Organization } from '../models/Organization.js';
15
- import { Platform } from '../models/Platform.js';
16
- import { User } from '../models/User.js';
17
- import type { Webshop } from '../models/Webshop.js';
18
-
19
- export type EmailTemplateOptions = {
20
- type: EmailTemplateType;
21
- webshop?: Webshop | null;
22
- group?: Group | null;
23
- organizationId?: string | null;
24
- };
25
-
26
- export async function getEmailTemplate(data: EmailTemplateOptions) {
27
- // Most specific template: for specific group
28
- const q = EmailTemplate.select()
29
- .where('type', data.type);
30
-
31
- if (data.group) {
32
- q.where('groupId', data.group.id);
33
- }
34
-
35
- if (data.organizationId) {
36
- q.where('organizationId', data.organizationId);
37
- }
38
-
39
- if (data.webshop) {
40
- q.where('webshopId', data.webshop.id);
41
- }
42
-
43
- let templates = await q.limit(1).fetch();
44
-
45
- // Specific for organization
46
- if (templates.length == 0 && (data.group?.id || data.webshop?.id) && data.organizationId) {
47
- templates = await EmailTemplate.select()
48
- .where('type', data.type)
49
- .where('organizationId', data.organizationId)
50
- .where('groupId', null)
51
- .where('webshopId', null)
52
- .limit(1)
53
- .fetch();
54
- }
55
-
56
- // Default for platform
57
- if (templates.length == 0 && (data.group?.id || data.webshop?.id || data.organizationId)) {
58
- templates = await EmailTemplate.select()
59
- .where('type', data.type)
60
- .where('organizationId', null)
61
- .where('groupId', null)
62
- .where('webshopId', null)
63
- .limit(1)
64
- .fetch();
65
- }
66
-
67
- if (templates.length == 0) {
68
- if (STAMHOOFD.environment === 'test') {
69
- return;
70
- }
71
- console.error('Could not find email template for type ' + data.type);
72
- return;
73
- }
74
-
75
- return templates[0];
76
- }
77
-
78
- export async function canSendFromEmail(fromAddress: string, organization: Organization | null) {
79
- if (organization) {
80
- if (organization.privateMeta.mailDomain && organization.privateMeta.mailDomainActive && fromAddress.endsWith('@' + organization.privateMeta.mailDomain)) {
81
- return true;
82
- }
83
-
84
- if (organization.id === (await Platform.getSharedPrivateStruct()).membershipOrganizationId) {
85
- return canSendFromEmail(fromAddress, null);
86
- }
87
-
88
- return false;
89
- }
90
- const transactionalDomains = Object.values(STAMHOOFD.domains.defaultTransactionalEmail ?? {});
91
- const broadcastDomains = Object.values(STAMHOOFD.domains.defaultBroadcastEmail ?? {});
92
- const domains = Formatter.uniqueArray([...transactionalDomains, ...broadcastDomains]);
93
-
94
- for (const domain of domains) {
95
- if (fromAddress.endsWith('@' + domain)) {
96
- return true;
97
- }
98
- }
99
-
100
- return false;
101
- }
102
-
103
- export async function getDefaultEmailFrom(organization: Organization | null, options: Pick<EmailBuilderOptions, 'type'> & { template: Omit<EmailTemplateOptions, 'organizationId' | 'type'> }) {
104
- // When choosing sending domain, prefer using the one with the highest reputation
105
- let preferEmailId: string | null = null;
106
-
107
- if (options.template.group) {
108
- preferEmailId = options.template.group.privateSettings.defaultEmailId;
109
- }
110
-
111
- if (options.template.webshop) {
112
- preferEmailId = options.template.webshop.privateMeta.defaultEmailId;
113
- }
114
-
115
- if (organization) {
116
- // Default email address for the chosen email type
117
- let from = organization.getDefaultFrom(organization.i18n, options.type ?? 'broadcast');
118
-
119
- const sender: OrganizationEmail | undefined = (preferEmailId ? organization.privateMeta.emails.find(e => e.id === preferEmailId) : null) ?? organization.privateMeta.emails.find(e => e.default) ?? organization.privateMeta.emails[0];
120
- let replyTo: EmailInterfaceRecipient | undefined = undefined;
121
-
122
- if (sender) {
123
- replyTo = {
124
- email: sender.email,
125
- name: sender.name,
126
- };
127
-
128
- // Can we send from this e-mail or reply-to?
129
- if (await canSendFromEmail(sender.email, organization)) {
130
- from = {
131
- email: sender.email,
132
- name: sender.name,
133
- };
134
- replyTo = undefined;
135
- }
136
-
137
- // Default to organization name
138
- if (!from.name) {
139
- from.name = organization.name;
140
- }
141
-
142
- if (replyTo) {
143
- if (!replyTo.name) {
144
- replyTo.name = organization.name;
145
- }
146
- }
147
- }
148
-
149
- return {
150
- from, replyTo,
151
- };
152
- }
153
- const platform = await Platform.getSharedPrivateStruct();
154
-
155
- // Default e-mail if no email addresses are configured
156
- const i18n = new I18n($getLanguage(), $getCountry());
157
- const transactionalDomain = i18n.localizedDomains.defaultTransactionalEmail();
158
- const broadcastDomain = i18n.localizedDomains.defaultBroadcastEmail();
159
-
160
- const domain = (options.type === 'transactional' ? transactionalDomain : broadcastDomain);
161
- let from: EmailInterfaceRecipient = {
162
- email: 'hallo@' + domain,
163
- };
164
-
165
- // Platform
166
- const sender: OrganizationEmail | undefined = (preferEmailId ? platform.privateConfig.emails.find(e => e.id === preferEmailId) : null) ?? platform.privateConfig.emails.find(e => e.default) ?? platform.privateConfig.emails[0];
167
- let replyTo: EmailInterfaceRecipient | undefined = undefined;
168
-
169
- if (sender) {
170
- replyTo = {
171
- email: sender.email,
172
- name: sender.name,
173
- };
174
-
175
- // Are we allowed to send an e-mail from this domain?
176
- if (await canSendFromEmail(sender.email, null)) {
177
- // Allowed to send from
178
- from = {
179
- email: sender.email,
180
- name: sender.name,
181
- };
182
- replyTo = undefined;
183
- }
184
-
185
- // Default to platform name
186
- if (!from.name) {
187
- from.name = platform.config.name;
188
- }
189
-
190
- if (replyTo) {
191
- if (!replyTo.name) {
192
- replyTo.name = platform.config.name;
193
- }
194
- }
195
- }
196
-
197
- return {
198
- from, replyTo,
199
- };
200
- }
201
-
202
- export async function sendEmailTemplate(organization: Organization | null, options: Omit<EmailBuilderOptions, 'subject' | 'html' | 'from' | 'replyTo'> & { template: Omit<EmailTemplateOptions, 'organizationId'> }) {
203
- if (options.template.webshop) {
204
- options.defaultReplacements = [...(options.defaultReplacements ?? []), ...options.template.webshop.meta.getEmailReplacements()];
205
- }
206
- const builder = await getEmailBuilderForTemplate(organization, {
207
- ...options,
208
- ...(await getDefaultEmailFrom(organization, options)),
209
- });
210
- if (builder) {
211
- Email.schedule(builder);
212
- }
213
- }
214
-
215
- async function getEmailBuilderForTemplate(organization: Organization | null, options: Omit<EmailBuilderOptions, 'subject' | 'html'> & { template: Omit<EmailTemplateOptions, 'organizationId'> }) {
216
- const template = await getEmailTemplate({
217
- ...options.template,
218
- organizationId: organization?.id ?? null,
219
- });
220
-
221
- if (!template) {
222
- if (STAMHOOFD.environment === 'production') {
223
- console.warn('No email template found for ' + options.template.type);
224
- }
225
- return undefined;
226
- }
227
-
228
- return await getEmailBuilder(organization, {
229
- ...options,
230
- subject: template.subject,
231
- html: template.html,
232
- translations: template.translations,
233
- });
234
- }
235
-
236
- export type EmailBuilderOptions = {
237
- defaultReplacements?: Replacement[];
238
- recipients: Recipient[];
239
- from: EmailInterfaceRecipient;
240
- replyTo?: EmailInterfaceRecipient | null;
241
- subject: string;
242
- html: string;
243
-
244
- /**
245
- * Full content overrides per language. Recipients with a language that has an override
246
- * receive that content, all others receive the default subject/html.
247
- */
248
- translations?: Map<Language, EmailContent>;
249
- attachments?: { filename: string; path?: string; href?: string; content?: string | Buffer; contentType?: string; encoding?: string }[];
250
- type?: 'transactional' | 'broadcast';
251
- unsubscribeType?: 'all' | 'marketing';
252
- fromStamhoofd?: boolean;
253
- singleBcc?: EmailInterfaceRecipient;
254
- replaceAll?: { from: string; to: string }[]; // replace in all e-mails, not recipient dependent
255
- callback?: (error: Error | null) => void; // for each email
256
- headers?: Record<string, string>;
257
- };
258
-
259
- /**
260
- * @param organization defines replacements and unsubsribe behaviour
261
- */
262
- export async function getEmailBuilder(organization: Organization | null, email: EmailBuilderOptions) {
263
- const platform = await Platform.getSharedPrivateStruct();
264
- // Update recipients
265
- const cleaned: Recipient[] = [];
266
- for (const recipient of email.recipients) {
267
- try {
268
- const unsubscribeGlobal = await EmailAddress.getWhereHardBounceOrSpam(recipient.email);
269
- if ((unsubscribeGlobal && (unsubscribeGlobal.hardBounce))) {
270
- // Ignore
271
- if (email.callback) {
272
- email.callback(
273
- new SimpleError({
274
- code: 'email_skipped_hard_bounce',
275
- message: 'Recipient has hard bounced',
276
- human: $t(`%ws`),
277
- }),
278
- );
279
- }
280
- continue;
281
- }
282
-
283
- if (unsubscribeGlobal && (unsubscribeGlobal.markedAsSpam)) {
284
- // Ignore
285
- if (email.callback) {
286
- email.callback(
287
- new SimpleError({
288
- code: 'email_skipped_spam',
289
- message: 'Recipient has marked as spam',
290
- human: $t(`%wt`),
291
- }),
292
- );
293
- }
294
- continue;
295
- }
296
-
297
- const unsubscribe = await EmailAddress.getOrCreate(recipient.email, email.fromStamhoofd || !organization ? null : organization.id);
298
- if (unsubscribe.unsubscribedAll || unsubscribe.hardBounce || unsubscribe.markedAsSpam || !unsubscribe.token || (unsubscribe.unsubscribedMarketing && email.unsubscribeType === 'marketing')) {
299
- // Ignore
300
- if (email.callback) {
301
- email.callback(
302
- new SimpleError({
303
- code: 'email_skipped_unsubscribed',
304
- message: unsubscribe.unsubscribedAll ? 'Recipient has unsubscribed' : (unsubscribe.hardBounce ? 'Recipient has hard bounced' : (unsubscribe.markedAsSpam ? 'Recipient has marked as spam' : 'Recipient has unsubscribed from marketing')),
305
- human: $t('%1E3'),
306
- }),
307
- );
308
- }
309
- continue;
310
- }
311
-
312
- // Localize the unsubscribe page to the recipient's language (Organization.i18n is always Dutch)
313
- const unsubscribeLocale = organization ? getRecipientI18n(recipient, organization).locale : null;
314
- const unsubscribeUrl = 'https://' + STAMHOOFD.domains.dashboard + '/' + (unsubscribeLocale ? (unsubscribeLocale + '/') : '') + 'unsubscribe?id=' + encodeURIComponent(unsubscribe.id) + '&token=' + encodeURIComponent(unsubscribe.token) + '&type=' + encodeURIComponent(email.unsubscribeType ?? 'all');
315
- recipient.replacements.push(Replacement.create({
316
- token: 'unsubscribeUrl',
317
- value: unsubscribeUrl,
318
- }));
319
-
320
- // Override headers
321
- recipient.headers = {
322
- ...email.headers,
323
- 'List-Unsubscribe': STAMHOOFD.domains.defaultBroadcastEmail !== undefined ? '<mailto:unsubscribe+' + unsubscribe.id + '@' + STAMHOOFD.domains.defaultBroadcastEmail![''] + `>, <${unsubscribeUrl}>` : `<${unsubscribeUrl}>`,
324
- 'List-Unsubscribe-Post': 'List-Unsubscribe=One-Click',
325
- };
326
- cleaned.push(recipient);
327
- } catch (e) {
328
- console.error(e);
329
- }
330
- }
331
- email.recipients = cleaned;
332
-
333
- // Update recipients
334
- for (const recipient of email.recipients) {
335
- recipient.replacements = recipient.replacements.slice();
336
-
337
- if (email.defaultReplacements) {
338
- recipient.replacements.push(...email.defaultReplacements);
339
- }
340
-
341
- await fillRecipientReplacements(recipient, {
342
- organization,
343
- platform,
344
- from: email.from,
345
- replyTo: email.replyTo ?? null,
346
- });
347
- }
348
-
349
- const queue = email.recipients.slice();
350
-
351
- let emailIndex = 0;
352
-
353
- // The subject and html can differ per recipient language
354
- const contentCache = new Map<Language | null, { subject: string; html: string }>();
355
- const resolveContent = (language: Language | null) => {
356
- const cached = contentCache.get(language);
357
- if (cached) {
358
- return cached;
359
- }
360
-
361
- // Strict selection: only use a translation of this email, never fall back to
362
- // a different template for a missing language (content correctness above language)
363
- const translation = language !== null ? email.translations?.get(language) : undefined;
364
- const subject = translation ? translation.subject : email.subject;
365
- let html = translation ? translation.html : email.html;
366
-
367
- for (const s of email.replaceAll ?? []) {
368
- html = html.replaceAll(s.from, s.to);
369
- }
370
-
371
- const result = { subject, html };
372
- contentCache.set(language, result);
373
- return result;
374
- };
375
-
376
- if (queue.length === 0) {
377
- if (email.callback) {
378
- email.callback(new SimpleError({
379
- code: 'no_recipients',
380
- message: 'No recipients left',
381
- }));
382
- }
383
- }
384
-
385
- // Create e-mail builder
386
- const builder: EmailBuilder = () => {
387
- const recipient = queue.shift();
388
- if (!recipient) {
389
- return undefined;
390
- }
391
-
392
- const content = resolveContent(recipient.language ?? null);
393
- const replacedHtml = replaceEmailHtml(content.html, recipient.replacements);
394
- const replacedSubject = replaceEmailText(content.subject, recipient.replacements);
395
-
396
- emailIndex += 1;
397
-
398
- return {
399
- from: email.from,
400
- replyTo: email.replyTo ?? undefined,
401
- bcc: emailIndex === 1 && email.singleBcc ? [email.singleBcc] : undefined,
402
- to: [
403
- {
404
- // Name will get cleaned by email service
405
- name: (recipient.firstName ?? '') + ' ' + (recipient.lastName ?? ''),
406
- email: recipient.email,
407
- },
408
- ],
409
- subject: replacedSubject,
410
- html: replacedHtml ?? undefined,
411
- attachments: email.attachments,
412
- headers: recipient.headers,
413
- type: email.type,
414
- callback: email.callback,
415
- };
416
- };
417
- return builder;
418
- }
419
-
420
- export function mergeReplacement(replacementA: Replacement, replacementB: Replacement): Replacement | false {
421
- if (replacementA.token !== replacementB.token) {
422
- return false;
423
- }
424
-
425
- if (replacementA.token === 'greeting') {
426
- // Just take the first one
427
- return replacementA;
428
- }
429
-
430
- if (replacementA.token === 'unsubscribeUrl') {
431
- return replacementA;
432
- }
433
-
434
- if (replacementA.token === 'signInUrl') {
435
- return replacementA;
436
- }
437
-
438
- if (replacementA.token === 'loginDetails') {
439
- // loginDetails are always the same for the same user.
440
- return replacementA;
441
- }
442
-
443
- if (replacementA.token === 'objectName') {
444
- // Add comma if values are not the same
445
- const aa = replacementA.value.split(', ');
446
-
447
- return Replacement.create({
448
- token: 'objectName',
449
- value: Formatter.uniqueArray([...aa, ...replacementB.value.split(', ')]).join(', '),
450
- });
451
- }
452
-
453
- return false;
454
- }
455
-
456
- /**
457
- * Remove duplicates
458
- */
459
- export function cleanReplacements(replacements: Replacement[]) {
460
- const foundIds: Set<string> = new Set();
461
- const cleaned: Replacement[] = [];
462
- for (const r of replacements) {
463
- if (foundIds.has(r.token)) {
464
- continue;
465
- }
466
- foundIds.add(r.token);
467
- cleaned.push(r);
468
- }
469
- return cleaned;
470
- }
471
-
472
- export function removeUnusedReplacements(html: string, replacements: Replacement[]) {
473
- const cleaned: Replacement[] = [];
474
- for (const r of cleanReplacements(replacements)) {
475
- if (html.includes(`{{${r.token}}}`)) {
476
- cleaned.push(r);
477
- }
478
- }
479
- return cleaned;
480
- }
481
-
482
- export function mergeReplacementsIfEqual(replacementsA: Replacement[], replacementsB: Replacement[]): Replacement[] | false {
483
- replacementsA = cleanReplacements(replacementsA);
484
- replacementsB = cleanReplacements(replacementsB);
485
-
486
- if (replacementsA.length !== replacementsB.length) {
487
- return false;
488
- }
489
-
490
- const merged: Replacement[] = [];
491
- for (const rA of replacementsA) {
492
- const rB = replacementsB.find(r => r.token === rA.token);
493
- if (!rB) {
494
- return false;
495
- }
496
-
497
- if (rA.html === rB.html && rA.value === rB.value) {
498
- merged.push(rA);
499
- continue;
500
- }
501
-
502
- const m = mergeReplacement(rA, rB);
503
- if (!m) {
504
- return false;
505
- }
506
- merged.push(m);
507
- }
508
-
509
- return merged;
510
- }
511
-
512
- /**
513
- * Filter replacements for display in the backend.
514
- * @param options.forPreview if true, it will hide sensitive information in the preview that could leak information to admin users
515
- */
516
- export function stripSensitiveRecipientReplacements(recipient: Recipient | EmailRecipientStruct | EmailRecipient, options: {
517
- organization: Organization | null;
518
- willFill?: boolean;
519
- }) {
520
- const { organization } = options;
521
- // Remove unsubscribeUrl and signInUrl if present
522
- recipient.replacements = recipient.replacements.filter(r => r.token !== 'unsubscribeUrl' && r.token !== 'signInUrl');
523
-
524
- if (options.willFill) {
525
- // Also strip loginDetails, balanceTable and outstandingBalance
526
- recipient.replacements = recipient.replacements.filter(r => r.token !== 'balanceTable' && r.token !== 'outstandingBalance' && r.token !== 'loginDetails');
527
- return;
528
- }
529
-
530
- // Add dummy unsubscribeUrl
531
- const dummyUnsubscribeUrl = 'https://' + (organization && STAMHOOFD.userMode === 'organization' ? getAppHost('registration', organization, false) : STAMHOOFD.domains.dashboard) + '/unsubscribe?token=example';
532
- recipient.replacements.push(Replacement.create({
533
- token: 'unsubscribeUrl',
534
- value: dummyUnsubscribeUrl,
535
- }));
536
-
537
- // dummy signInUrl
538
- const dummySignInUrl = 'https://' + (organization && STAMHOOFD.userMode === 'organization' ? getAppHost('registration', organization, false) : STAMHOOFD.domains.dashboard) + '/login';
539
- recipient.replacements.push(Replacement.create({
540
- token: 'signInUrl',
541
- value: dummySignInUrl,
542
- }));
543
-
544
- // Strip security codes (because we list ALL security codes, also from members a viewer might not have access to)
545
- recipient.replacements = recipient.replacements.map((r) => {
546
- if (r.token !== 'loginDetails') {
547
- return r;
548
- }
549
- return Replacement.create({
550
- ...r,
551
- // Strip <span class="style-inline-code">(.*)</span> and replace content with XXXX-XXXX-XXXX-XXXX
552
- html: r.html ? r.html.replace(/<span class="style-inline-code">.*?<\/span>/g, '<span class="style-inline-code">••••</span>') : r.html,
553
- });
554
- });
555
- }
556
-
557
- /**
558
- * Fill and hide replacements that don't make sense for web display to the user
559
- */
560
- export function stripRecipientReplacementsForWebDisplay(recipient: Recipient | EmailRecipientStruct | EmailRecipient, options: {
561
- organization: Organization | null;
562
- }) {
563
- const { organization } = options;
564
- // Remove unsubscribeUrl if present
565
- recipient.replacements = recipient.replacements.filter(r => r.token !== 'unsubscribeUrl' && r.token !== 'loginDetails' && r.token !== 'greeting');
566
-
567
- // Add dummy unsubscribeUrl
568
- const dummyUnsubscribeUrl = 'https://' + (organization && STAMHOOFD.userMode === 'organization' ? getAppHost('registration', organization, false) : STAMHOOFD.domains.dashboard);
569
- recipient.replacements.push(Replacement.create({
570
- token: 'unsubscribeUrl',
571
- value: dummyUnsubscribeUrl,
572
- }));
573
-
574
- recipient.replacements.push(Replacement.create({
575
- token: 'loginDetails',
576
- value: '',
577
- }));
578
-
579
- recipient.replacements.push(Replacement.create({
580
- token: 'greeting',
581
- value: $t('%1E9'),
582
- }));
583
- }
584
-
585
- /**
586
- * Build the I18n an email should be rendered in for a specific recipient.
587
- *
588
- * Falls back to the current (ambient) locale when the recipient has no language set — so flows
589
- * that already established a locale (order emails wrapped in I18n.runWithLocale, or the request
590
- * locale) keep working unchanged.
591
- */
592
- export function getRecipientI18n(recipient: { language?: Language | null }, organization: Organization | null, options?: { allowedLanguages?: Language[] | null }): I18n {
593
- let lang = recipient.language ?? $getLanguage();
594
- if (options?.allowedLanguages && options.allowedLanguages.length) {
595
- if (!options.allowedLanguages.includes(lang)) {
596
- if (options.allowedLanguages.includes($getLanguage())) {
597
- lang = $getLanguage();
598
- } else {
599
- lang = options.allowedLanguages[0];
600
- }
601
- }
602
- }
603
- return new I18n(lang, organization?.address.country ?? $getCountry());
604
- }
605
-
606
- /**
607
- * Render everything inside `handler` in the recipient's language: all $t / $getLanguage /
608
- * $getCountry calls (and therefore every generated replacement) use the recipient's locale.
609
- *
610
- * This is the single place that binds "a recipient" to "its language" when generating email
611
- * content. Generate recipient replacements inside this wrapper so new replacements are localized
612
- * automatically, and pass the provided i18n to helpers that take an explicit locale (e.g. getAppHost).
613
- */
614
- export function runWithRecipientLocale<T>(recipient: { language?: Language | null }, organization: Organization | null, handler: (i18n: I18n) => T, options?: { allowedLanguages?: Language[] | null }): T {
615
- const i18n = getRecipientI18n(recipient, organization, options);
616
- return I18n.runWithLocale(i18n, () => handler(i18n));
617
- }
618
-
619
- /**
620
- * @param options.forPreview if true, it will hide sensitive information in the preview that could leak information to admin users
621
- */
622
- export async function fillRecipientReplacements(recipient: Recipient | EmailRecipientStruct | EmailRecipient, options: {
623
- organization: Organization | null;
624
- platform?: PlatformStruct;
625
- from: EmailInterfaceRecipient | null;
626
- replyTo: EmailInterfaceRecipient | null;
627
- forPreview?: boolean;
628
- forceRefresh?: boolean;
629
- allowedLanguages?: Language[] | null;
630
- }) {
631
- if (!options.platform) {
632
- options.platform = await Platform.getSharedPrivateStruct();
633
- }
634
- const { organization, platform, from, replyTo } = options;
635
-
636
- // Render every recipient replacement (greeting, loginDetails, balance table, URLs...) in the
637
- // recipient's own language, so translated emails are consistent end-to-end. Any replacement
638
- // added below is localized automatically; helpers with an explicit locale get the same i18n.
639
- await runWithRecipientLocale(recipient, organization, async (i18n) => {
640
- let recipientUser: User | null | undefined = null;
641
- recipient.replacements = recipient.replacements.slice();
642
- if (options.forPreview) {
643
- stripSensitiveRecipientReplacements(recipient, options);
644
- }
645
-
646
- if (!recipient.email && !recipient.userId) {
647
- const signInUrl = 'https://' + (organization && STAMHOOFD.userMode === 'organization' ? getAppHost('registration', organization, false, i18n) : STAMHOOFD.domains.dashboard) + '/login';
648
- recipient.replacements.push(Replacement.create({
649
- token: 'signInUrl',
650
- value: signInUrl,
651
- }));
652
-
653
- if (!recipient.replacements.find(r => r.token === 'loginDetails')) {
654
- recipient.replacements.push(Replacement.create({
655
- token: 'loginDetails',
656
- value: '',
657
- }));
658
- }
659
- } else {
660
- // Default signInUrl
661
- recipientUser = recipient.userId ? await User.select().where('id', recipient.userId).first(false) : await User.getForAuthentication(organization?.id ?? null, recipient.email!, { allowWithoutAccount: true });
662
- if (STAMHOOFD.userMode !== 'platform' && recipientUser && recipientUser.organizationId && recipientUser.organizationId !== (organization?.id ?? null)) {
663
- console.warn('User organization does not match current organization, ignoring userId', recipient.userId, recipientUser.organizationId, organization?.id ?? null);
664
- recipientUser = null;
665
- }
666
-
667
- let signInUrl: string;
668
- if (!recipientUser || !recipientUser.hasAccount()) {
669
- // We can create a special token
670
- if (recipientUser) {
671
- signInUrl = 'https://' + (organization && STAMHOOFD.userMode === 'organization' ? getAppHost('registration', organization, false, i18n) : STAMHOOFD.domains.dashboard) + '/account-aanmaken?email=' + encodeURIComponent(recipientUser?.email);
672
- } else {
673
- signInUrl = 'https://' + (organization && STAMHOOFD.userMode === 'organization' ? getAppHost('registration', organization, false, i18n) : STAMHOOFD.domains.dashboard) + '/account-aanmaken';
674
- }
675
- } else {
676
- signInUrl = 'https://' + (organization && STAMHOOFD.userMode === 'organization' ? getAppHost('registration', organization, false, i18n) : STAMHOOFD.domains.dashboard) + '/login?email=' + encodeURIComponent(recipientUser.email);
677
- }
678
-
679
- recipient.replacements.push(Replacement.create({
680
- token: 'signInUrl',
681
- value: signInUrl,
682
- }));
683
- }
684
-
685
- if (options.forceRefresh) {
686
- // Remove loginDetails to force refresh
687
- recipient.replacements = recipient.replacements.filter(r => r.token !== 'loginDetails');
688
- }
689
-
690
- if (!recipient.replacements.find(r => r.token === 'loginDetails')) {
691
- if (recipientUser) {
692
- const emailEscaped = `<strong>${Formatter.escapeHtml(recipientUser.email)}</strong>`;
693
- const suffixes: string[] = [];
694
- const { Member } = await import('../models/Member.js');
695
- const memberIds = await Member.getMemberIdsForUser(recipientUser);
696
- const members = await Member.getByIDs(...memberIds);
697
- if (members.length > 0) {
698
- for (const member of members) {
699
- suffixes.push(
700
- $t('%1EC', {
701
- firstName: Formatter.escapeHtml(member.firstName),
702
- securityCode: `<span class="style-inline-code">${Formatter.escapeHtml(options.forPreview ? '••••' : Formatter.spaceString(member.details.securityCode ?? '', 4, '-'))}</span>`,
703
- }),
704
- );
705
- }
706
- } else {
707
- console.log('No member found for user', recipientUser.id);
708
- }
709
- const suffix = suffixes.length > 0 ? (' ' + suffixes.join(' ')) : '';
710
- recipient.replacements.push(
711
- Replacement.create({
712
- token: 'loginDetails',
713
- value: '',
714
- html: recipientUser.hasAccount()
715
- ? `<p class="description"><em>${$t('%1EA', { email: emailEscaped })}${suffix}</em></p>`
716
- : `<p class="description"><em>${$t('%1EB', { email: emailEscaped })}${suffix}</em></p>`,
717
- }),
718
- );
719
- } else {
720
- if (recipient.email) {
721
- const emailEscaped = `<strong>${Formatter.escapeHtml(recipient.email)}</strong>`;
722
- console.log('No user found for email', recipient.email);
723
- recipient.replacements.push(
724
- Replacement.create({
725
- token: 'loginDetails',
726
- value: '',
727
- html: `<p class="description"><em>${$t('%1EB', { email: emailEscaped })}</em></p>`,
728
- }),
729
- );
730
- } else {
731
- recipient.replacements.push(
732
- Replacement.create({
733
- token: 'loginDetails',
734
- value: '',
735
- html: '',
736
- }),
737
- );
738
- }
739
- }
740
- }
741
-
742
- if (options.forceRefresh) {
743
- // Remove loginDetails to force refresh
744
- recipient.replacements = recipient.replacements.filter(r => r.token !== 'balanceTable' && r.token !== 'outstandingBalance');
745
- }
746
-
747
- // Load balance of this user
748
- // todo: only if detected it is used
749
- if (!recipient.replacements.find(r => r.token === 'balanceTable')) {
750
- if (organization && recipientUser) {
751
- const balanceItemModels = await CachedBalance.balanceForObjects(organization.id, [recipientUser.id], ReceivableBalanceType.user);
752
- const balanceItems = balanceItemModels.map(i => i.getStructure());
753
-
754
- // Get members
755
- recipient.replacements.push(
756
- Replacement.create({
757
- token: 'outstandingBalance',
758
- value: Formatter.price(balanceItems.reduce((sum, i) => sum + i.priceOpen, 0)),
759
- }),
760
- Replacement.create({
761
- token: 'balanceTable',
762
- value: '',
763
- html: BalanceItemStruct.getDetailsHTMLTable(balanceItems),
764
- }),
765
- );
766
- } else {
767
- recipient.replacements.push(
768
- Replacement.create({
769
- token: 'outstandingBalance',
770
- value: Formatter.price(0),
771
- }),
772
- Replacement.create({
773
- token: 'balanceTable',
774
- value: '',
775
- html: BalanceItemStruct.getDetailsHTMLTable([]),
776
- }),
777
- );
778
- }
779
- }
780
-
781
- if (from || replyTo) {
782
- const fromAddress = replyTo?.email ?? from!.email;
783
-
784
- if (fromAddress) {
785
- recipient.replacements.push(Replacement.create({
786
- token: 'fromAddress',
787
- value: fromAddress,
788
- }));
789
- }
790
-
791
- const name = replyTo?.name ?? from?.name;
792
- if (name) {
793
- recipient.replacements.push(Replacement.create({
794
- token: 'fromName',
795
- value: name,
796
- }));
797
- }
798
- }
799
-
800
- if (recipient instanceof EmailRecipient) {
801
- recipient.replacements.push(...recipient.getRecipient().getDefaultReplacements());
802
- } else {
803
- recipient.replacements.push(...recipient.getDefaultReplacements());
804
- }
805
-
806
- if (organization) {
807
- const extra = organization.meta.getEmailReplacements(organization);
808
- recipient.replacements.push(...extra);
809
- }
810
-
811
- // Defaults
812
- const extra = platform.config.getEmailReplacements(platform);
813
- recipient.replacements.push(...extra);
814
-
815
- // Remove duplicates
816
- cleanReplacements(recipient.replacements);
817
- }, options);
818
- }