-
Notifications
You must be signed in to change notification settings - Fork 122
/
caldav-server.js
1820 lines (1592 loc) · 58.5 KB
/
caldav-server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Copyright (c) Forward Email LLC
* SPDX-License-Identifier: BUSL-1.1
*/
const { randomUUID } = require('node:crypto');
const API = require('@ladjs/api');
const Boom = require('@hapi/boom');
const ICAL = require('ical.js');
const caldavAdapter = require('caldav-adapter');
const etag = require('etag');
const isSANB = require('is-string-and-not-blank');
const mongoose = require('mongoose');
const { boolean } = require('boolean');
const { isEmail } = require('validator');
const { rrulestr } = require('rrule');
const Aliases = require('#models/aliases');
const Domains = require('#models/domains');
const CalendarEvents = require('#models/calendar-events');
const Calendars = require('#models/calendars');
const Emails = require('#models/emails');
const config = require('#config');
const createTangerine = require('#helpers/create-tangerine');
const env = require('#config/env');
const i18n = require('#helpers/i18n');
const logger = require('#helpers/logger');
const onAuth = require('#helpers/on-auth');
const refreshSession = require('#helpers/refresh-session');
// TODO: DNS SRV records <https://sabre.io/dav/service-discovery/#dns-srv-records>
async function onAuthPromise(auth, session) {
return new Promise((resolve, reject) => {
onAuth.call(this, auth, session, (err, user) => {
if (err) return reject(err);
resolve(user);
});
});
}
function bumpSyncToken(synctoken) {
const parts = synctoken.split('/');
return (
parts.slice(0, -1).join('/') +
'/' +
(Number.parseInt(parts[parts.length - 1], 10) + 1)
);
}
// TODO: support SMS reminders for VALARM
//
// TODO: we should fork ical.js and merge these PR's
// <https://github.com/kewisch/ical.js/issues/646>
//
//
// TODO: valarm duration needs to be converted to a Number or (date/string?)
//
// const dt = ICAL.Time.fromJSDate(new Date('2024-01-01T06:00:00.000Z'))
// const cp = dt.clone()
// cp.addDuration(ICAL.Duration.fromString('-P0DT0H30M0S'));
// cp.toJSDate()
/*
const event = ctx.request.ical.find((obj) => obj.type === 'VEVENT');
if (!event) return;
// safeguard in case our implementation is off (?)
if (ctx.request.ical.filter((obj) => obj.type === 'VEVENT').length > 1) {
const err = new TypeError('Multiple VEVENT passed');
err.ical = ctx.request.ical;
throw err;
}
// safeguard in case library isn't working for some reason
const parsed = ICAL.parse(ctx.request.body);
if (!parsed || parsed.length === 0) {
const err = new TypeError('ICAL.parse was not successful');
err.parsed = parsed;
throw err;
}
const comp = new ICAL.Component(parsed);
if (!comp) throw new TypeError('ICAL.Component was not successful');
const vevent = comp.getFirstSubcomponent('vevent');
if (!vevent)
throw new TypeError('comp.getFirstSubcomponent was not successful');
const icalEvent = new ICAL.Event(vevent);
if (!icalEvent) throw new TypeError('ICAL.Event was not successful');
//
// VALARM
//
const icalAlarms = icalEvent.component.getAllSubcomponents('valarm');
event.alarms = [];
for (const alarm of icalAlarms) {
// getFirstProperty('x').getParameter('y')
// NOTE: attendee missing from ical-generator right now
// (which is who the alarm correlates to, e.g. `ATTENDEE:mailto:foo@domain.com`)
// <https://github.com/sebbo2002/ical-generator/issues/573>
/*
alarms.push({
// DISPLAY (to lower case for ical-generator)
type: 'DISPLAY', 'AUDIO', 'EMAIL' (required)
trigger: Number or Date,
relatesTo: 'END', 'START', or null
repeat: {
times: Number,
interval: Number
} || null,
attach: {
uri: String,
mime: String || null
} || null,
description: String || null,
x: [
{ key: '', value: '' }
]
});
*/
/*
let trigger;
let relatesTo = null;
if (alarm.getFirstProperty('trigger')) {
const value = alarm.getFirstPropertyValue('trigger');
if (value instanceof ICAL.Duration) {
trigger = value.toSeconds();
} else if (value instanceof ICAL.Time) {
trigger = value.toJSDate();
}
if (alarm.getFirstProperty('trigger').getParameter('related'))
relatesTo = alarm.getFirstProperty('trigger').getParameter('related');
}
let repeat = null;
// RFC spec requires that both are set if one of them is
if (
alarm.getFirstProperty('repeat') &&
alarm.getFirstProperty('duration')
) {
const value = alarm.getFirstPropertyValue('duration');
repeat = {
times: alarm.getFirstPropertyValue('repeat'), // ical.js already parses as a number
interval: value.toSeconds()
};
}
//
// NOTE: attachments are not added right now because ical-generator does not support them properly
//
// TODO: ical-generator is missing some required props used for reconstructing attachments
// <https://github.com/sebbo2002/ical-generator/issues/577>
//
// TODO: ical-generator toString() is completely broken for attachments right now
// <https://github.com/sebbo2002/ical-generator/blob/f27dd10e9b2d830953687eca5daa52acca1731cc/src/alarm.ts#L618-L627>
// (e.g. it doesn't support the value below)
//
// TODO: we should probably drop ical-generator and rewrite it with ical.js purely
//
const attach = null;
// ATTACH;FMTTYPE=text/plain;ENCODING=BASE64;VALUE=BINARY;X-BASE64-PARAM=UGFyYW1ldGVyCg=:WW91IHJlYWxseSBzcGVudCB0aGUgdGltZSB0byBiYXNlNjQgZGVjb2RlIHRoaXM/Cg=
event.alarms.push({
type: alarm.getFirstPropertyValue('action'),
trigger,
relatesTo,
repeat,
attach // TODO: fix this in the future
});
}
//
// ATTENDEE
//
const icalAttendees = icalEvent.attendees;
event.attendees = [];
for (const attendee of icalAttendees) {
//
// NOTE: there is a bug right now with node-ical parser for attendees
// (only one attendee is parsed even if there are multiple)
// <https://github.com/jens-maus/node-ical/issues/302>
//
// TODO: validate attendee props in the future
// <https://github.com/sebbo2002/ical-generator/blob/c6d2f1f9909930743acb54003e124faea4f58cec/src/attendee.ts#L38-L74>
//
// <https://github.com/sebbo2002/ical-generator/blob/9190c842f4e9aa9ac8fd598983303cb95e3cf76b/src/attendee.ts#L22>
//
// name?: string | null;
// email: string;
// mailto?: string | null;
// sentBy?: string | null;
// status?: ICalAttendeeStatus | null;
// role?: ICalAttendeeRole;
// rsvp?: boolean | null;
// type?: ICalAttendeeType | null;
// delegatedTo?: ICalAttendee | ICalAttendeeData | string | null;
// delegatedFrom?: ICalAttendee | ICalAttendeeData | string | null;
// x?: {key: string, value: string}[] | [string, string][] | Record<string, string>;
//
const x = [];
for (const key of Object.keys(attendee.jCal[1])) {
if (key.startsWith('x-')) {
x.push({
key,
value: attendee.jCal[1][key]
});
}
}
event.attendees.push({
name: attendee.getParameter('cn'),
email: attendee.getParameter('email').replace('mailto:', ''), // safeguard (?)
mailto: attendee.getFirstValue().replace('mailto:', ''),
sentBy: attendee.getParameter('sent-by') || null,
status: attendee.getParameter('partstat'),
role: attendee.getParameter('role') || null,
rsvp: attendee.getParameter('rsvp')
? boolean(attendee.getParameter('rsvp'))
: null,
type: attendee.getParameter('cutype'),
delegatedTo: attendee.getParameter('delegated-to'),
delegatedFrom: attendee.getParameter('delegated-from'),
x
});
}
//
// summary is always a string
// (safeguard fallback in case node-ical doesn't parse it properly as a string)
//
event.summary =
typeof event.summary === 'string' ? event.summary : icalEvent.summary;
// add X- arbitrary attributes
const x = [];
for (const key of Object.keys(icalEvent.jCal[1])) {
if (
key.startsWith('x-') && //
// NOTE: these props get auto-added by toString() of an Event in ical-generator
// (so we want to ignore them here so they won't get added twice to ICS output)
//
// X-MICROSOFT-CDO-ALLDAYEVENT
// X-MICROSOFT-MSNCALENDAR-ALLDAYEVENT
// X-APPLE-STRUCTURED-LOCATION
// X-ALT-DESC
// X-MICROSOFT-CDO-BUSYSTATUS
![
'x-microsoft-cdo-alldayevent',
'x-microsoft-msncalendar-alldayevent',
'x-apple-structured-location',
'x-alt-desc',
'x-microsoft-cdo-busystatus'
].includes(key)
) {
x.push({
key,
value: icalEvent.jCal[1][key]
});
}
}
// location is an object and consists of
// - title (string)
// - address (string)
// - radius (number) - which is from `X-APPLE-RADIUS`
// - geo (object - `{ lat: Num, lon: Num }`)
// or it's a string or null
if (typeof event.location === 'object' && event.location !== null) {
if (_.isEmpty(event.location)) {
if (event.geo) {
// NOTE: pending this issue being resolved, this would actually start working
// <https://github.com/sebbo2002/ical-generator/issues/569>
event.location = {
title: undefined,
address: undefined,
radius: undefined,
geo: event.geo
};
} else {
event.location = undefined;
}
} else {
//
// NOTE: this ical-generator implementation is mainly geared to support Apple location
//
// X-APPLE-STRUCTURED-LOCATION;VALUE=URI;X-ADDRESS=Kurfürstendamm 26\, 10719
// Berlin\, Deutschland;X-APPLE-RADIUS=141.1751386318387;X-TITLE=Apple Store
// Kurfürstendamm:geo:52.50363,13.32865
//
// <https://github.com/search?q=repo%3Asebbo2002%2Fical-generator+Apple+Store+Kurf%C3%BCrstendamm&type=code>
if (
typeof event['APPLE-STRUCTURED-LOCATION'] === 'object' &&
!_.isEmpty(event['APPLE-STRUCTURED-LOCATION'])
) {
// "APPLE-STRUCTURED-LOCATION": {
// "params": {
// "VALUE": "URI",
// "X-ADDRESS": "Kurfürstendamm 26\\, 10719 Berlin\\, Deutschland",
// "X-APPLE-RADIUS": 141.1751386318387,
// "X-TITLE": "Apple Store Kurfürstendamm"
// },
// "val": "geo:52.50363,13.32865"
// },
event.location = {
title: event['APPLE-STRUCTURED-LOCATION'].params['X-TITLE'],
address: event['APPLE-STRUCTURED-LOCATION'].params['X-ADDRESS'],
radius: event['APPLE-STRUCTURED-LOCATION'].params['X-APPLE-RADIUS'],
geo: event.geo || undefined
};
} else {
event.location = {
title: event.location.val,
address: undefined,
radius: undefined,
geo: event.geo || undefined
};
}
}
} else if (typeof event.location === 'string') {
event.location = {
title: event.location,
address: undefined,
radius: undefined,
geo: event.geo || undefined
};
} else if (event.geo) {
// NOTE: pending this issue being resolved, this would actually start working
// <https://github.com/sebbo2002/ical-generator/issues/569>
event.location = {
title: undefined,
address: undefined,
radius: undefined,
geo: event.geo
};
} else {
event.location = undefined;
}
//
// TODO: add STYLED-DESCRIPTION to buildICS output
// TODO: add ALTREP to buildICS object (thunderbird support)
//
// description is either an object, string, or null/undefined
if (typeof event.description === 'object' && event.description !== null) {
if (_.isEmpty(event.description)) {
event.description = undefined;
} else {
// TODO: support thunderbird altrep
event.description = {
plain,
html
};
}
}
//
// TODO: use ICAL parsed organizer here
//
// https://github.com/jens-maus/node-ical/issues/303
// organizer is either an object, string or null
// if it's an object it has these props:
//
// - name: string;
// - email?: string;
// - mailto?: string;
// - sentBy?: string;
//
// NOTE: there is a core bug in node-ical where it does not parse organizer properly
// https://github.com/jens-maus/node-ical/issues/303
//
// ORGANIZER:mailto:cyrus@example.com
// (just a string)
//
// or
//
// ORGANIZER;CN="Bernard Desruisseaux":mailto:bernard@example.com
//
// <https://github.com/sebbo2002/ical-generator/blob/9190c842f4e9aa9ac8fd598983303cb95e3cf76b/src/event.ts#L1786C1-L1800C10>
// if (this.data.organizer) {
// g += 'ORGANIZER;CN="' + escape(this.data.organizer.name, true) + '"';
// if (this.data.organizer.sentBy) {
// g += ';SENT-BY="mailto:' + escape(this.data.organizer.sentBy, true) + '"';
// }
// if (this.data.organizer.email && this.data.organizer.mailto) {
// g += ';EMAIL=' + escape(this.data.organizer.email, false);
// }
// if(this.data.organizer.email) {
// g += ':mailto:' + escape(this.data.organizer.mailto || this.data.organizer.email, false);
// }
// g += '\r\n';
// }
//
// NOTE: the output is weird in toString() right now because of how the author designed this
// <https://github.com/sebbo2002/ical-generator/issues/571>
//
if (typeof event.organizer === 'object' && event.organizer !== null) {
const mailto = isEmail(event.organizer.val)
? event.organizer.val
: event.organizer.val.replace('mailto:', '');
event.organizer = {
name: event.organizer.params.CN,
email: event.organizer.params.EMAIL
? event.organizer.params.EMAIL.replace('mailto:', '')
: undefined,
mailto,
sentBy: event.organizer.params['SENT-BY']
? event.organizer.params['SENT-BY'].replace('mailto:', '')
: undefined
};
}
//
// NOTE: services like cal.com have some pretty huge issues with calendar support
// <https://github.com/calcom/cal.com/issues/3457>
// <https://github.com/calcom/cal.com/issues/9485>
//
let description;
// TODO: location and contact can have ALTREP too
// TODO: convert this to html/plain and change the DB model too
// TODO: we need to use `unescape()` on the HTML parsed value
// because when `toString()` is called by ical-generator
// it will automatically use `escape` on the values
// NOTE: Thunderbird sends over description with:
// `DESCRIPTION;ALTREP="data:text/html,yaya%3Cb%3Eyay%3C%2Fb%3Eay":yayayayay`
// TODO: organizer is similar to attendee
*/
//
// CalDAV
// <https://www.rfc-editor.org/rfc/rfc4791>
//
class CalDAV extends API {
constructor(options = {}, Users) {
super(options, Users);
this.logger = logger;
this.resolver = createTangerine(this.client, logger);
this.wsp = options.wsp;
this.authenticate = this.authenticate.bind(this);
this.createCalendar = this.createCalendar.bind(this);
this.getCalendar = this.getCalendar.bind(this);
this.updateCalendar = this.updateCalendar.bind(this);
this.getCalendarsForPrincipal = this.getCalendarsForPrincipal.bind(this);
this.getEventsForCalendar = this.getEventsForCalendar.bind(this);
this.getEventsByDate = this.getEventsByDate.bind(this);
this.getEvent = this.getEvent.bind(this);
this.createEvent = this.createEvent.bind(this);
this.updateEvent = this.updateEvent.bind(this);
this.deleteEvent = this.deleteEvent.bind(this);
this.deleteCalendar = this.deleteCalendar.bind(this);
this.buildICS = this.buildICS.bind(this);
this.getCalendarId = this.getCalendarId.bind(this);
this.getETag = this.getETag.bind(this);
this.sendEmailWithICS = this.sendEmailWithICS.bind(this);
this.app.use(
caldavAdapter({
authenticate: this.authenticate,
authRealm: 'forwardemail/caldav',
caldavRoot: '/',
calendarRoot: 'dav',
principalRoot: 'principals',
// <https://github.com/sedenardi/node-caldav-adapter/blob/bdfbe17931bf14a1803da77dbb70509db9332695/src/koa.ts#L130-L131>
disableWellKnown: false,
logEnabled: !env.AXE_SILENT,
logLevel: 'debug',
data: {
createCalendar: this.createCalendar,
updateCalendar: this.updateCalendar,
getCalendar: this.getCalendar,
getCalendarsForPrincipal: this.getCalendarsForPrincipal,
getEventsForCalendar: this.getEventsForCalendar,
getEventsByDate: this.getEventsByDate,
getEvent: this.getEvent,
createEvent: this.createEvent,
updateEvent: this.updateEvent,
deleteEvent: this.deleteEvent,
deleteCalendar: this.deleteCalendar,
buildICS: this.buildICS,
getCalendarId: this.getCalendarId,
getETag: this.getETag
}
})
);
}
// send email calendar invite with ICS
//
//
// NOTE: this uses `queue` as opposed to `await emailHelper`
// because we want the email to retry, use their DKIM keys,
// and we also want to use up the users email credits
//
// eslint-disable-next-line complexity, max-params
async sendEmailWithICS(ctx, calendar, calendarEvent, method, oldCalStr) {
try {
const [alias, domain] = await Promise.all([
// get alias (and populate user, which is required for Emails.queue method)
Aliases.findOne({ id: ctx.state.user.alias_id })
.populate('user')
.lean()
.exec(),
// get domain (and populate members, which is required for Emails.queue method)
Domains.findOne({ id: ctx.state.user.domain_id })
.populate(
'members.user',
`id plan ${config.userFields.isBanned} ${config.userFields.hasVerifiedEmail} ${config.userFields.planExpiresAt} ${config.userFields.stripeSubscriptionID} ${config.userFields.paypalSubscriptionID}`
)
.lean()
.exec()
]);
//
// build ICS string so we can parse and re-render with REQUEST method
//
const comp = new ICAL.Component(ICAL.parse(calendarEvent.ical));
if (!comp) throw new TypeError('Component not parsed');
// safeguard in case more than one event
const vevents = comp.getAllSubcomponents('vevent');
let vevent = vevents.find((vevent) => {
const uid = vevent.getFirstPropertyValue('uid');
if (uid === calendarEvent.eventId) return true;
// if uid was an email e.g. "xyz@google.com" then
// sometimes the calendarEvent.eventId is the same value but with "_" instead of "@" symbol
if (
isEmail(uid, { ignore_max_length: true }) &&
uid.replace('@', '_') === calendarEvent.eventId
)
return true;
return false;
});
// TODO: we need to do the same for update event and other eventId lookups
// fallback in case event not found yet there were events in body
if (!vevent && vevents.length > 0) vevent = vevents[0];
//
// TODO: there shouldn't be more than one VEVENT with
// same uid but if there is we may want to cleanup in future
// (we have seen edge cases where this does actually happen)
//
if (!vevent) throw new TypeError('vevent missing');
// if method was CANCEL then STATUS on vevent needs to be CANCELLED
if (method === 'CANCEL')
vevent.updatePropertyWithValue('status', 'CANCELLED');
const event = new ICAL.Event(vevent);
let isValid = true;
// if X-MOZ-SEND-INVITATIONS is set then don't send invitation updates
// (since the client will be the one sending them, or perhaps user didn't want to)
if (vevent.getFirstPropertyValue('x-moz-send-invitations'))
isValid = false;
// mirror sabre/dav behavior
//
// must have organizer matching alias
// and at least one attendee
//
else if (!event.organizer) isValid = false;
// event.organizer = 'mailto:foo@bar.com'
else if (
// TODO: fallback to EMAIL param somehow here for ORGANIZER (?)
event.organizer.replace('mailto:', '').trim().toLowerCase() !==
ctx.state.user.username
)
isValid = false;
// if attendee removed then send CANCEL to those removed
if (oldCalStr) {
const oldComp = new ICAL.Component(ICAL.parse(oldCalStr));
if (!oldComp) throw new TypeError('Old component not parsed');
// safeguard in case more than one event
const oldEvents = oldComp.getAllSubcomponents('vevent');
let oldEvent = oldEvents.find((vevent) => {
const uid = vevent.getFirstPropertyValue('uid');
if (uid === calendarEvent.eventId) return true;
// if uid was an email e.g. "xyz@google.com" then
// sometimes the calendarEvent.eventId is the same value but with "_" instead of "@" symbol
if (
isEmail(uid, { ignore_max_length: true }) &&
uid.replace('@', '_') === calendarEvent.eventId
)
return true;
return false;
});
// fallback in case event not found yet there were events in body
if (!oldEvent && oldEvents.length > 0) oldEvent = oldEvents[0];
//
// TODO: there shouldn't be more than one VEVENT with
// same uid but if there is we may want to cleanup in future
// (we have seen edge cases where this does actually happen)
//
if (!oldEvent) throw new TypeError('old vevent missing');
const attendees = oldEvent.getAllProperties('attendee');
if (attendees.length > 0) {
for (const attendee of attendees) {
let oldEmail = attendee.getFirstValue();
if (!oldEmail || !/^mailto:/i.test(oldEmail)) {
// fallback to EMAIL param
oldEmail = attendee.getParameter('email');
}
if (!oldEmail) continue;
oldEmail = oldEmail.replace('mailto:', '').toLowerCase().trim();
const match = event.attendees
? event.attendees.find((attendee) => {
let address = attendee.getFirstValue();
if (!address || !/^mailto:/i.test(address)) {
// fallback to EMAIL param
address = attendee.getParameter('email');
}
if (!address) return;
address = address.replace('mailto:', '').toLowerCase().trim();
return address === oldEmail;
})
: null;
// if there was a match found then that means the user wasn't removed
if (match) continue;
const commonName = attendee.getParameter('cn');
const to = commonName ? `"${commonName}" ${oldEmail}` : oldEmail;
//
// here is where we send cancelled to this user (with the old event object)
// since they were not a part of the updated event
// (note they won't get a duplicate REQUEST email below because they're not in `event.attendees`)
//
try {
const vc = new ICAL.Component(['vcalendar', [], []]);
vc.addSubcomponent(oldEvent);
// eslint-disable-next-line no-await-in-loop
const ics = await this.buildICS(
ctx,
[
{
eventId: calendarEvent.eventId,
calendar: calendar._id,
ical: vc.toString()
}
],
calendar,
method
);
// eslint-disable-next-line no-await-in-loop
await Emails.queue({
message: {
from: ctx.state.user.username,
to,
bcc: ctx.state.user.username,
subject: `${i18n.translate('CANCELLED', ctx.locale)}: ${
oldEvent.summary
}`,
icalEvent: {
method,
filename: 'invite.ics',
content: ics
}
},
alias,
domain,
user: alias ? alias.user : undefined,
date: new Date(),
catchall: false,
isPending: false
});
} catch (err) {
logger.fatal(err);
}
}
}
}
if (isValid) {
const to = [];
const organizerEmail = event.organizer
.replace('mailto:', '')
.trim()
.toLowerCase();
if (event.attendees) {
for (const attendee of event.attendees) {
// TODO: if SCHEDULE-AGENT=CLIENT then do not send invite (?)
// const scheduleAgent = attendee.getParameter('schedule-agent');
// if (scheduleAgent && scheduleAgent.toLowerCase() === 'client') continue;
// skip attendees that were already DECLINED
const partStat = attendee.getParameter('partstat');
if (partStat && partStat.toLowerCase() === 'declined') continue;
let email = attendee.getFirstValue();
if (!email || !email.startsWith('mailto:')) {
// fallback to EMAIL param
email = attendee.getParameter('email');
}
if (!email) continue;
email = email.replace('mailto:', '').toLowerCase().trim();
if (!isEmail(email)) continue;
if (email === organizerEmail) continue;
const commonName = attendee.getParameter('cn');
if (commonName) {
to.push(`"${commonName}" <${email}>`);
} else {
to.push(email);
}
}
}
if (to.length > 0) {
const vc = new ICAL.Component(['vcalendar', [], []]);
vc.addSubcomponent(vevent);
const ics = await this.buildICS(
ctx,
[
{
eventId: calendarEvent.eventId,
calendar: calendar._id,
ical: vc.toString()
}
],
calendar,
method
);
logger.debug('ics output', ics);
let subject = event.summary;
subject =
method === 'CANCEL'
? `${i18n.translate('CANCELLED', ctx.locale)}: ${subject}`
: `${i18n.translate('INVITATION', ctx.locale)}: ${subject}`;
//
// if "X-MOZ-SEND-INVITATIONS-UNDISCLOSED:TRUE" then
// the Thunderbird checkbox was checked for
// "Separate invitation per attendee"
// <https://github.com/mozilla/releases-comm-central/blob/6c887d441f46c56b3e40081b69c34222b909bf78/calendar/itip/CalItipOutgoingMessage.sys.mjs#L67-L90>
// https://github.com/mozilla/releases-comm-central/blob/0dd0febc7a7815833119eb056f8cc1acf59ddc04/calendar/base/content/item-editing/calendar-item-iframe.js#L734-L738
//
if (
// NOTE: the Thunderbird interface always sets this to false/disables it when you uncheck X-MOZ-SEND-INVITATIONS
// so this edge case would never get reached, but we are doing it anyways as a safeguard
vevent.getFirstPropertyValue(
'x-moz-send-invitations-undisclosed'
) &&
boolean(
vevent.getFirstPropertyValue('x-moz-send-invitations-undisclosed')
)
) {
for (const rcpt of to) {
try {
// eslint-disable-next-line no-await-in-loop
await Emails.queue({
message: {
from: ctx.state.user.username,
to: rcpt,
subject,
icalEvent: {
method,
filename: 'invite.ics',
content: ics
}
},
alias,
domain,
user: alias ? alias.user : undefined,
date: new Date(),
catchall: false,
isPending: false
});
} catch (err) {
logger.fatal(err);
}
}
} else {
await Emails.queue({
message: {
from: ctx.state.user.username,
to,
subject,
icalEvent: {
method,
filename: 'invite.ics',
content: ics
}
},
alias,
domain,
user: alias ? alias.user : undefined,
date: new Date(),
catchall: false,
isPending: false
});
}
}
}
} catch (err) {
// temp debugging
err.isCodeBug = true;
err.calendar = calendar;
err.oldCalStr = oldCalStr;
err.calendarEvent = calendarEvent;
logger.fatal(err);
}
}
async authenticate(ctx, { username, password, principalId }) {
logger.debug('authenticate', { username, password, principalId });
ctx.state.session = {
id: ctx.req.id,
remoteAddress: ctx.ip,
request: ctx.request
};
try {
const { user } = await onAuthPromise.call(
this,
// auth
{
username,
password
},
// session
ctx.state.session
);
// caldav related user properties
user.principalId = user.username;
user.principalName = user.username; // .toUpperCase()
// set user in session and state
ctx.state.user = user;
ctx.state.session.user = user;
// set locale for translation in ctx
ctx.isAuthenticated = () => true;
ctx.request.acceptsLanguages = () => false;
await i18n.middleware(ctx, () => Promise.resolve());
// connect to db
await refreshSession.call(this, ctx.state.session, 'CALDAV');
// ensure that the default calendar exists
let defaultCalendar = await this.getCalendar(ctx, {
calendarId: user.username,
principalId: user.username,
user
});
if (!defaultCalendar) {
defaultCalendar = await Calendars.create({
// db virtual helper
instance: this,
session: ctx.state.session,
// calendarId
calendarId: user.username,
// calendar obj
// NOTE: Android uses "Events" and most others use "Calendar" as default calendar name
name: ctx.translate('CALENDAR'),
description: config.urls.web,
prodId: `//forwardemail.net//caldav//${ctx.locale.toUpperCase()}`,
//
// NOTE: instead of using timezone from IP we use
// their last time zone set in a browser session
// (this is way more accurate and faster)
//
// here were some alternatives though during R&D:
// * <https://github.com/runk/node-maxmind>
// * <https://github.com/evansiroky/node-geo-tz>
// * <https://github.com/safing/mmdbmeld>
// * <https://github.com/sapics/ip-location-db>
//
timezone: ctx.state.session.user.timezone,
url: config.urls.web,
readonly: false,
synctoken: `${config.urls.web}/ns/sync-token/1`
});
}
return user;
} catch (err) {
logger.error(err);
throw Boom.unauthorized(err);
}
}
async createCalendar(ctx, { name, description, timezone }) {
logger.debug('createCalendar', {
name,
description,
timezone,
params: ctx.state.params
});
// if calendar already exists with calendarId value then return 405
// <https://github.com/sabre-io/dav/blob/da8c1f226f1c053849540a189262274ef6809d1c/tests/Sabre/CalDAV/PluginTest.php#L289>
const calendar = await this.getCalendar(ctx, {
calendarId: ctx.state.params.calendarId
});
if (calendar)
throw Boom.methodNotAllowed(
ctx.translateError('CALENDAR_ALREADY_EXISTS')
);
return Calendars.create({
// db virtual helper
instance: this,
session: ctx.state.session,
// calendarId
calendarId: ctx.state.params.calendarId || name || randomUUID(),
// calendar obj
name,
description,
prodId: `//forwardemail.net//caldav//${ctx.locale.toUpperCase()}`,
timezone: timezone || ctx.state.session.user.timezone,
url: config.urls.web,
readonly: false,
synctoken: `${config.urls.web}/ns/sync-token/1`
});
}
// https://caldav.forwardemail.net/dav/support@forwardemail.net/default
async getCalendar(ctx, { calendarId, principalId, user }) {
logger.debug('getCalendar', { calendarId, principalId, user });
let calendar;
if (mongoose.isObjectIdOrHexString(calendarId))
calendar = await Calendars.findOne(this, ctx.state.session, {
_id: new mongoose.Types.ObjectId(calendarId)
});
if (!calendar)
calendar = await Calendars.findOne(this, ctx.state.session, {
calendarId
});
if (!calendar && !mongoose.isObjectIdOrHexString(calendarId))
calendar = await Calendars.findOne(this, ctx.state.session, {
name: calendarId
});
logger.debug('getCalendar result', { calendar });
return calendar;
}
//
// NOTE: we have added updateCalendar support
// <https://github.com/sedenardi/node-caldav-adapter/blob/bdfbe17931bf14a1803da77dbb70509db9332695/example/server.js#L33>
// <https://github.com/sedenardi/node-caldav-adapter/blob/bdfbe17931bf14a1803da77dbb70509db9332695/example/data.js#L111-L120>
//
async updateCalendar(ctx, { principalId, calendarId, user }) {
logger.debug('updateCalendar', { principalId, calendarId, user });
//
// 1) parse `ctx.request.body` for VCALENDAR and all VEVENT's
// 2) update the calendar metadata based off VCALENDAR
// 3) update existing VEVENTS by uid match
// 4) create new VEVENTS for those that did not have uid match
//