@stamhoofd/backend 2.59.0 → 2.61.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 (34) hide show
  1. package/index.ts +4 -0
  2. package/package.json +10 -10
  3. package/src/audit-logs/DocumentTemplateLogger.ts +22 -0
  4. package/src/audit-logs/EmailAddressLogger.ts +45 -0
  5. package/src/audit-logs/EmailLogger.ts +67 -0
  6. package/src/audit-logs/EmailTemplateLogger.ts +33 -0
  7. package/src/audit-logs/MemberPlatformMembershipLogger.ts +6 -3
  8. package/src/audit-logs/ModelLogger.ts +23 -6
  9. package/src/audit-logs/OrderLogger.ts +2 -2
  10. package/src/audit-logs/OrganizationLogger.ts +1 -11
  11. package/src/audit-logs/UserLogger.ts +45 -0
  12. package/src/crons/amazon-ses.ts +324 -0
  13. package/src/crons/clearExcelCache.ts +3 -0
  14. package/src/crons/endFunctionsOfUsersWithoutRegistration.ts +3 -0
  15. package/src/crons/index.ts +4 -0
  16. package/src/crons/postmark.ts +223 -0
  17. package/src/crons.ts +3 -315
  18. package/src/endpoints/global/members/PatchOrganizationMembersEndpoint.ts +3 -3
  19. package/src/endpoints/global/platform/PatchPlatformEnpoint.ts +2 -1
  20. package/src/endpoints/global/registration/RegisterMembersEndpoint.ts +38 -25
  21. package/src/endpoints/organization/dashboard/organization/PatchOrganizationEndpoint.ts +2 -1
  22. package/src/endpoints/organization/dashboard/registration-periods/PatchOrganizationRegistrationPeriodsEndpoint.ts +3 -11
  23. package/src/helpers/MemberUserSyncer.ts +11 -7
  24. package/src/helpers/PeriodHelper.ts +2 -1
  25. package/src/helpers/SetupStepUpdater.ts +503 -0
  26. package/src/seeds/1726847064-setup-steps.ts +1 -1
  27. package/src/seeds/1733319079-fill-paying-organization-ids.ts +68 -0
  28. package/src/services/AuditLogService.ts +19 -14
  29. package/src/services/DocumentService.ts +43 -0
  30. package/src/services/RegistrationService.ts +2 -0
  31. package/src/services/diff.ts +514 -0
  32. package/src/sql-filters/events.ts +13 -1
  33. package/src/crons/updateSetupSteps.ts +0 -9
  34. package/src/services/explainPatch.ts +0 -851
@@ -0,0 +1,324 @@
1
+ /* eslint-disable @typescript-eslint/no-unsafe-argument */
2
+ import { registerCron } from '@stamhoofd/crons';
3
+ import { Email, EmailAddress } from '@stamhoofd/email';
4
+ import { AuditLog, Organization } from '@stamhoofd/models';
5
+ import { AuditLogReplacement, AuditLogReplacementType, AuditLogSource, AuditLogType } from '@stamhoofd/structures';
6
+ import AWS from 'aws-sdk';
7
+ import { ForwardHandler } from '../helpers/ForwardHandler';
8
+
9
+ registerCron('checkComplaints', checkComplaints);
10
+ registerCron('checkReplies', checkReplies);
11
+ registerCron('checkBounces', checkBounces);
12
+
13
+ async function saveLog({ email, organization, type, subType, subject, response, sender, id }: { id: string; email: string; organization: Organization | undefined; type: AuditLogType; subType?: string; subject: string; response: string; sender: string }) {
14
+ if (!id || typeof id !== 'string') {
15
+ throw new Error('Invalid AWS SES id received');
16
+ }
17
+
18
+ const log = new AuditLog();
19
+ log.organizationId = organization?.id ?? null;
20
+ log.externalId = 'aws-ses-message-' + id.toString();
21
+ log.type = type;
22
+ log.source = AuditLogSource.System;
23
+ log.objectId = email;
24
+ log.replacements = new Map([
25
+ ['e', AuditLogReplacement.create({
26
+ value: email || '',
27
+ type: AuditLogReplacementType.EmailAddress,
28
+ })],
29
+ ['subType', AuditLogReplacement.key(subType || 'unknown')],
30
+ ['response', AuditLogReplacement.longText(response)],
31
+ ['subject', AuditLogReplacement.string(subject)],
32
+ ['sender', AuditLogReplacement.create({
33
+ value: sender,
34
+ type: AuditLogReplacementType.EmailAddress,
35
+ })],
36
+ ]);
37
+ // Check if we already logged this bounce
38
+ const existing = await AuditLog.select().where('externalId', log.externalId).first(false);
39
+ if (existing) {
40
+ console.log('Already logged this bounce, skipping');
41
+ return;
42
+ }
43
+
44
+ await log.save();
45
+ }
46
+
47
+ async function checkBounces() {
48
+ if (STAMHOOFD.environment !== 'production' || !STAMHOOFD.AWS_ACCESS_KEY_ID) {
49
+ return;
50
+ }
51
+
52
+ console.log('[AWS BOUNCES] Checking bounces from AWS SQS');
53
+ const sqs = new AWS.SQS();
54
+ const messages = await sqs.receiveMessage({ QueueUrl: 'https://sqs.eu-west-1.amazonaws.com/118244293157/stamhoofd-bounces-queue', MaxNumberOfMessages: 10 }).promise();
55
+ if (messages.Messages) {
56
+ for (const message of messages.Messages) {
57
+ console.log('[AWS BOUNCES] Received bounce message');
58
+ console.log('[AWS BOUNCES]', message);
59
+
60
+ if (message.ReceiptHandle) {
61
+ if (STAMHOOFD.environment === 'production') {
62
+ await sqs.deleteMessage({
63
+ QueueUrl: 'https://sqs.eu-west-1.amazonaws.com/118244293157/stamhoofd-bounces-queue',
64
+ ReceiptHandle: message.ReceiptHandle,
65
+ }).promise();
66
+ console.log('[AWS BOUNCES] Deleted from queue');
67
+ }
68
+ }
69
+
70
+ try {
71
+ if (message.Body) {
72
+ // decode the JSON value
73
+ const bounce = JSON.parse(message.Body);
74
+
75
+ if (bounce.Message) {
76
+ const message = JSON.parse(bounce.Message);
77
+
78
+ if (message.bounce) {
79
+ const b = message.bounce;
80
+ // Block all receivers that generate a permanent bounce
81
+ const type = b.bounceType;
82
+ const subtype = b.bounceSubType;
83
+
84
+ const source = message.mail.source;
85
+
86
+ // try to find organization that is responsible for this e-mail address
87
+
88
+ for (const recipient of b.bouncedRecipients) {
89
+ const email = recipient.emailAddress;
90
+
91
+ if (
92
+ type === 'Permanent'
93
+ || (
94
+ recipient.diagnosticCode && (
95
+ (recipient.diagnosticCode as string).toLowerCase().includes('invalid domain')
96
+ || (recipient.diagnosticCode as string).toLowerCase().includes('unable to lookup dns')
97
+ )
98
+ )
99
+ ) {
100
+ const organization: Organization | undefined = source ? await Organization.getByEmail(source) : undefined;
101
+ if (organization) {
102
+ const emailAddress = await EmailAddress.getOrCreate(email, organization.id);
103
+ emailAddress.hardBounce = true;
104
+ await emailAddress.save();
105
+ }
106
+ else {
107
+ console.error('[AWS BOUNCES] Unknown organization for email address ' + source);
108
+ }
109
+
110
+ await saveLog({
111
+ id: b.feedbackId,
112
+ email,
113
+ organization,
114
+ type: AuditLogType.EmailAddressHardBounced,
115
+ subType: subtype || 'unknown',
116
+ sender: source,
117
+ response: b.diagnosticCode || '',
118
+ subject: message.mail.commonHeaders?.subject || '',
119
+ });
120
+ }
121
+ else if (
122
+ type === 'Transient'
123
+ ) {
124
+ const organization: Organization | undefined = source ? await Organization.getByEmail(source) : undefined;
125
+ await saveLog({
126
+ id: b.feedbackId,
127
+ email,
128
+ organization,
129
+ type: AuditLogType.EmailAddressSoftBounced,
130
+ subType: subtype || 'unknown',
131
+ sender: source,
132
+ response: b.diagnosticCode || '',
133
+ subject: message.mail.commonHeaders?.subject || '',
134
+ });
135
+ }
136
+ }
137
+ console.log('[AWS BOUNCES] For domain ' + source);
138
+ }
139
+ else {
140
+ console.log("[AWS BOUNCES] 'bounce' field missing in bounce message");
141
+ }
142
+ }
143
+ else {
144
+ console.log("[AWS BOUNCES] 'Message' field missing in bounce message");
145
+ }
146
+ }
147
+ else {
148
+ console.log('[AWS BOUNCES] Message Body missing in bounce');
149
+ }
150
+ }
151
+ catch (e) {
152
+ console.log('[AWS BOUNCES] Bounce message processing failed:');
153
+ console.error('[AWS BOUNCES] Bounce message processing failed:');
154
+ console.error('[AWS BOUNCES]', e);
155
+ }
156
+ }
157
+ }
158
+ }
159
+
160
+ async function checkReplies() {
161
+ if (STAMHOOFD.environment !== 'production' || !STAMHOOFD.AWS_ACCESS_KEY_ID) {
162
+ return;
163
+ }
164
+
165
+ console.log('Checking replies from AWS SQS');
166
+ const sqs = new AWS.SQS();
167
+ const messages = await sqs.receiveMessage({ QueueUrl: 'https://sqs.eu-west-1.amazonaws.com/118244293157/stamhoofd-email-forwarding', MaxNumberOfMessages: 10 }).promise();
168
+ if (messages.Messages) {
169
+ for (const message of messages.Messages) {
170
+ console.log('Received message from forwarding queue');
171
+
172
+ if (message.ReceiptHandle) {
173
+ if (STAMHOOFD.environment === 'production') {
174
+ await sqs.deleteMessage({
175
+ QueueUrl: 'https://sqs.eu-west-1.amazonaws.com/118244293157/stamhoofd-email-forwarding',
176
+ ReceiptHandle: message.ReceiptHandle,
177
+ }).promise();
178
+ console.log('Deleted from queue');
179
+ }
180
+ }
181
+
182
+ try {
183
+ if (message.Body) {
184
+ // decode the JSON value
185
+ const bounce = JSON.parse(message.Body);
186
+
187
+ if (bounce.Message) {
188
+ const message = JSON.parse(bounce.Message);
189
+
190
+ // Read message content
191
+ if (message.mail && message.content && message.receipt) {
192
+ const content = message.content;
193
+ const receipt = message.receipt as {
194
+ recipients: string[];
195
+ spamVerdict: { status: 'PASS' | string };
196
+ virusVerdict: { status: 'PASS' | string };
197
+ spfVerdict: { status: 'PASS' | string };
198
+ dkimVerdict: { status: 'PASS' | string };
199
+ dmarcVerdict: { status: 'PASS' | string };
200
+ };
201
+
202
+ const options = await ForwardHandler.handle(content, receipt);
203
+ if (options) {
204
+ if (STAMHOOFD.environment === 'production') {
205
+ Email.send(options);
206
+ }
207
+ }
208
+ }
209
+ }
210
+ }
211
+ }
212
+ catch (e) {
213
+ console.error(e);
214
+ }
215
+ }
216
+ }
217
+ }
218
+
219
+ async function checkComplaints() {
220
+ if (STAMHOOFD.environment !== 'production' || !STAMHOOFD.AWS_ACCESS_KEY_ID) {
221
+ return;
222
+ }
223
+
224
+ console.log('[AWS COMPLAINTS] Checking complaints from AWS SQS');
225
+ const sqs = new AWS.SQS();
226
+ const messages = await sqs.receiveMessage({ QueueUrl: 'https://sqs.eu-west-1.amazonaws.com/118244293157/stamhoofd-complaints-queue', MaxNumberOfMessages: 10 }).promise();
227
+ if (messages.Messages) {
228
+ for (const message of messages.Messages) {
229
+ console.log('[AWS COMPLAINTS] Received complaint message');
230
+ console.log('[AWS COMPLAINTS]', message);
231
+
232
+ if (message.ReceiptHandle) {
233
+ if (STAMHOOFD.environment === 'production') {
234
+ await sqs.deleteMessage({
235
+ QueueUrl: 'https://sqs.eu-west-1.amazonaws.com/118244293157/stamhoofd-complaints-queue',
236
+ ReceiptHandle: message.ReceiptHandle,
237
+ }).promise();
238
+ console.log('[AWS COMPLAINTS] Deleted from queue');
239
+ }
240
+ }
241
+
242
+ try {
243
+ if (message.Body) {
244
+ // decode the JSON value
245
+ const complaint = JSON.parse(message.Body);
246
+ console.log('[AWS COMPLAINTS]', complaint);
247
+
248
+ if (complaint.Message) {
249
+ const message = JSON.parse(complaint.Message);
250
+
251
+ if (message.complaint) {
252
+ const b = message.complaint;
253
+ const source = message.mail.source;
254
+ const organization: Organization | undefined = source ? await Organization.getByEmail(source) : undefined;
255
+
256
+ const type: 'abuse' | 'auth-failure' | 'fraud' | 'not-spam' | 'other' | 'virus' = b.complaintFeedbackType;
257
+
258
+ if (organization) {
259
+ for (const recipient of b.complainedRecipients) {
260
+ const email = recipient.emailAddress;
261
+ const emailAddress = await EmailAddress.getOrCreate(email, organization.id);
262
+ emailAddress.markedAsSpam = type !== 'not-spam';
263
+ await emailAddress.save();
264
+
265
+ if (type !== 'not-spam') {
266
+ if (type === 'virus' || type === 'fraud') {
267
+ await saveLog({
268
+ id: b.feedbackId,
269
+ email: source,
270
+ organization,
271
+ type: AuditLogType.EmailAddressFraudComplaint,
272
+ subType: type || 'unknown',
273
+ sender: source,
274
+ response: b.diagnosticCode || '',
275
+ subject: message.mail.commonHeaders?.subject || '',
276
+ });
277
+ }
278
+ else {
279
+ await saveLog({
280
+ id: b.feedbackId,
281
+ email: source,
282
+ organization,
283
+ type: AuditLogType.EmailAddressMarkedAsSpam,
284
+ subType: type || 'unknown',
285
+ sender: source,
286
+ response: b.diagnosticCode || '',
287
+ subject: message.mail.commonHeaders?.subject || '',
288
+ });
289
+ }
290
+ }
291
+ }
292
+ }
293
+ else {
294
+ console.error('[AWS COMPLAINTS] Unknown organization for email address ' + source);
295
+ }
296
+
297
+ if (type === 'virus' || type === 'fraud') {
298
+ console.error('[AWS COMPLAINTS] Received virus / fraud complaint!');
299
+ console.error('[AWS COMPLAINTS]', complaint);
300
+ if (STAMHOOFD.environment === 'production') {
301
+ Email.sendWebmaster({
302
+ subject: 'Received a ' + type + ' email notification',
303
+ text: 'We received a ' + type + ' notification for an e-mail from the organization: ' + organization?.name + '. Please check and adjust if needed.\n',
304
+ });
305
+ }
306
+ }
307
+ }
308
+ else {
309
+ console.log('[AWS COMPLAINTS] Missing complaint field');
310
+ }
311
+ }
312
+ else {
313
+ console.log('[AWS COMPLAINTS] Missing message field in complaint');
314
+ }
315
+ }
316
+ }
317
+ catch (e) {
318
+ console.log('[AWS COMPLAINTS] Complain message processing failed:');
319
+ console.error('[AWS COMPLAINTS] Complain message processing failed:');
320
+ console.error('[AWS COMPLAINTS]', e);
321
+ }
322
+ }
323
+ }
324
+ }
@@ -1,8 +1,11 @@
1
+ import { registerCron } from '@stamhoofd/crons';
1
2
  import fs from 'fs/promises';
2
3
 
3
4
  const msIn22Hours = 79200000;
4
5
  let lastExcelClear: number | null = null;
5
6
 
7
+ registerCron('clearExcelCache', clearExcelCache);
8
+
6
9
  export async function clearExcelCache() {
7
10
  const now = new Date();
8
11
 
@@ -1,8 +1,11 @@
1
+ import { registerCron } from '@stamhoofd/crons';
1
2
  import { FlagMomentCleanup } from '../helpers/FlagMomentCleanup';
2
3
 
3
4
  let lastCleanupYear: number = -1;
4
5
  let lastCleanupMonth: number = -1;
5
6
 
7
+ registerCron('endFunctionsOfUsersWithoutRegistration', endFunctionsOfUsersWithoutRegistration);
8
+
6
9
  export async function endFunctionsOfUsersWithoutRegistration() {
7
10
  const now = new Date();
8
11
  const currentYear = now.getFullYear();
@@ -0,0 +1,4 @@
1
+ import './amazon-ses.js';
2
+ import './clearExcelCache.js';
3
+ import './endFunctionsOfUsersWithoutRegistration.js';
4
+ import './postmark.js';
@@ -0,0 +1,223 @@
1
+ import { Email, EmailAddress } from '@stamhoofd/email';
2
+ import { AuditLog, Organization } from '@stamhoofd/models';
3
+ import { DateTime } from 'luxon';
4
+
5
+ import { registerCron } from '@stamhoofd/crons';
6
+ import { AuditLogReplacement, AuditLogReplacementType, AuditLogSource, AuditLogType } from '@stamhoofd/structures';
7
+
8
+ // Importing postmark returns undefined (this is a bug, so we need to use require)
9
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
10
+ const postmark = require('postmark') as typeof import('postmark');
11
+
12
+ let lastPostmarkCheck: Date | null = null;
13
+ let lastPostmarkIds: Set<number> = new Set();
14
+
15
+ registerCron('checkPostmarkBounces', checkPostmarkBounces);
16
+
17
+ async function saveLog({ email, organization, type, subType, id, response, subject, sender }: { id: number; sender: string; email: string; response: string; subject: string;organization: Organization | undefined; type: AuditLogType; subType?: string }) {
18
+ const log = new AuditLog();
19
+ log.organizationId = organization?.id ?? null;
20
+ log.externalId = 'postmark-bounce-' + id.toString();
21
+ log.type = type;
22
+ log.objectId = email;
23
+ log.source = AuditLogSource.System;
24
+ log.replacements = new Map([
25
+ ['e', AuditLogReplacement.create({
26
+ value: email || '',
27
+ type: AuditLogReplacementType.EmailAddress,
28
+ })],
29
+ ['subType', AuditLogReplacement.key(subType || 'unknown')],
30
+ ['response', AuditLogReplacement.longText(response)],
31
+ ['sender', AuditLogReplacement.create({
32
+ value: sender,
33
+ type: AuditLogReplacementType.EmailAddress,
34
+ })],
35
+ ]);
36
+
37
+ if (subject) {
38
+ log.replacements.set('subject', AuditLogReplacement.string(subject));
39
+ }
40
+
41
+ // Check if we already logged this bounce
42
+ const existing = await AuditLog.select().where('externalId', log.externalId).first(false);
43
+ if (existing) {
44
+ console.log('Already logged this bounce, skipping');
45
+ return;
46
+ }
47
+
48
+ await log.save();
49
+ }
50
+
51
+ async function checkPostmarkBounces() {
52
+ if (STAMHOOFD.environment !== 'production') {
53
+ // return;
54
+ }
55
+
56
+ const token = STAMHOOFD.POSTMARK_SERVER_TOKEN;
57
+ if (!token) {
58
+ console.log('No postmark token, skipping postmark bounces');
59
+ return;
60
+ }
61
+ const fromDate = (lastPostmarkCheck ?? new Date(new Date().getTime() - 24 * 60 * 60 * 1000 * 2));
62
+ const ET = DateTime.fromJSDate(fromDate).setZone('EST').toISO({ includeOffset: false });
63
+
64
+ if (!ET) {
65
+ console.error('Could not convert date to EST:', fromDate);
66
+ return;
67
+ }
68
+ console.log('Checking bounces from Postmark since', fromDate, ET);
69
+ const client = new postmark.ServerClient(token);
70
+
71
+ const toDate = DateTime.now().setZone('EST').toISO({ includeOffset: false });
72
+
73
+ if (!toDate) {
74
+ console.error('Could not convert date to EST:', new Date());
75
+ return;
76
+ }
77
+
78
+ let offset = 0;
79
+ let total = 1;
80
+ const count = 500;
81
+
82
+ // Sadly the postmark api returns bounces in the wrong order, to make them easier fetchable so we need to fetch them all in one go every time
83
+ while (offset < total && offset <= 10000 - count) {
84
+ const bounces = await client.getBounces({
85
+ fromDate: ET,
86
+ toDate,
87
+ count,
88
+ offset,
89
+ });
90
+
91
+ if (bounces.TotalCount === 0) {
92
+ console.log('No Postmark bounces at this time');
93
+ return;
94
+ }
95
+
96
+ total = bounces.TotalCount;
97
+
98
+ console.log('Found', bounces.TotalCount, 'bounces from Postmark');
99
+
100
+ let lastId: number | null = null;
101
+ const idList = new Set<number>();
102
+ let newEventCount = 0;
103
+
104
+ for (const bounce of bounces.Bounces) {
105
+ idList.add(bounce.ID);
106
+ if (lastPostmarkIds.has(bounce.ID)) {
107
+ lastId = bounce.ID;
108
+ continue;
109
+ }
110
+ newEventCount += 1;
111
+
112
+ // Try to get the organization, if possible, else default to global blocking: "null", which is not visible for an organization, but it is applied
113
+ const source = bounce.From;
114
+ const organization = source ? await Organization.getByEmail(source) : undefined;
115
+ console.log(bounce);
116
+
117
+ if (bounce.Type === 'SpamComplaint' || bounce.Type === 'SpamNotification' || bounce.Type === 'VirusNotification') {
118
+ console.log('Postmark ' + bounce.Type + ' for: ', bounce.Email, 'from', source, 'organization', organization?.name);
119
+ const emailAddress = await EmailAddress.getOrCreate(bounce.Email, organization?.id ?? null);
120
+ emailAddress.markedAsSpam = true;
121
+ await emailAddress.save();
122
+
123
+ if (bounce.Type === 'VirusNotification') {
124
+ await saveLog({
125
+ email: bounce.Email,
126
+ organization,
127
+ type: AuditLogType.EmailAddressFraudComplaint,
128
+ subType: bounce.Type,
129
+ response: bounce.Details,
130
+ id: bounce.ID,
131
+ subject: bounce.Subject,
132
+ sender: bounce.From,
133
+ });
134
+ }
135
+ else {
136
+ await saveLog({
137
+ email: bounce.Email,
138
+ organization,
139
+ type: AuditLogType.EmailAddressMarkedAsSpam,
140
+ subType: bounce.Type,
141
+ response: bounce.Details,
142
+ id: bounce.ID,
143
+ subject: bounce.Subject,
144
+ sender: bounce.From,
145
+ });
146
+ }
147
+ }
148
+ else if (bounce.Inactive) {
149
+ // Block for everyone, but not visible
150
+ console.log('Postmark ' + bounce.Type + ' for: ', bounce.Email, 'from', source, 'organization', organization?.name);
151
+ const emailAddress = await EmailAddress.getOrCreate(bounce.Email, organization?.id ?? null);
152
+ emailAddress.hardBounce = true;
153
+ await emailAddress.save();
154
+ await saveLog({
155
+ email: bounce.Email,
156
+ organization,
157
+ type: AuditLogType.EmailAddressHardBounced,
158
+ subType: bounce.Type,
159
+ response: bounce.Details,
160
+ id: bounce.ID,
161
+ subject: bounce.Subject,
162
+ sender: bounce.From,
163
+ });
164
+ }
165
+ else {
166
+ if (bounce.Type === 'SMTPApiError' && bounce.Details.startsWith("ErrorCode: '406'")) {
167
+ console.log('Email on Postmark suppression list: ' + bounce.Type + ': ', bounce.Email, 'from', source, 'organization', organization?.name);
168
+
169
+ // We've sent a message to an email that is blocked by Postmark
170
+ await saveLog({
171
+ email: bounce.Email,
172
+ organization,
173
+ type: AuditLogType.EmailAddressHardBounced,
174
+ subType: 'ExternalSuppressionList',
175
+ response: bounce.Details,
176
+ id: bounce.ID,
177
+ subject: '', // bounce.Subject is not correct here for some reason
178
+ sender: bounce.From,
179
+ });
180
+ }
181
+ else {
182
+ if (bounce.Type === 'SMTPApiError') {
183
+ // Log internally
184
+ Email.sendWebmaster({
185
+ subject: 'Received an SMTPApiError from Postmark',
186
+ text: 'We received an SMTPApiError for an e-mail from the organization: ' + organization?.name + '. Please check and adjust if needed.\n' + JSON.stringify(bounce, undefined, 4),
187
+ });
188
+ }
189
+ else {
190
+ console.log('Unhandled Postmark ' + bounce.Type + ': ', bounce.Email, 'from', source, 'organization', organization?.name);
191
+
192
+ await saveLog({
193
+ email: bounce.Email,
194
+ organization,
195
+ type: AuditLogType.EmailAddressSoftBounced,
196
+ subType: bounce.Type,
197
+ response: bounce.Details,
198
+ id: bounce.ID,
199
+ subject: bounce.Subject,
200
+ sender: bounce.From,
201
+ });
202
+ }
203
+ }
204
+ }
205
+
206
+ const bouncedAt = new Date(bounce.BouncedAt);
207
+ lastPostmarkCheck = lastPostmarkCheck ? new Date(Math.max(bouncedAt.getTime(), lastPostmarkCheck.getTime())) : bouncedAt;
208
+
209
+ lastId = bounce.ID;
210
+ }
211
+
212
+ if (lastId && newEventCount === 0) {
213
+ console.log('Postmark has no new bounces');
214
+ // Increase timestamp by one second to avoid refetching it every time
215
+ if (lastPostmarkCheck) {
216
+ lastPostmarkCheck = new Date(lastPostmarkCheck.getTime() + 1000);
217
+ }
218
+ }
219
+ lastPostmarkIds = idList;
220
+
221
+ offset += bounces.Bounces.length;
222
+ }
223
+ }