-
Notifications
You must be signed in to change notification settings - Fork 191
Expand file tree
/
Copy pathcaldav-server.js
More file actions
3220 lines (2873 loc) · 104 KB
/
caldav-server.js
File metadata and controls
3220 lines (2873 loc) · 104 KB
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 { Buffer } = require('node:buffer');
// const getUuid = require('@forwardemail/uuid-by-string');
const API = require('@ladjs/api');
const basicAuth = require('basic-auth');
const Boom = require('@hapi/boom');
const ICAL = require('ical.js');
const caldavAdapter = require('caldav-adapter');
const etag = require('etag');
const falso = require('@ngneat/falso');
const isSANB = require('is-string-and-not-blank');
const mongoose = require('mongoose');
const uuid = require('uuid');
const { rrulestr } = require('rrule');
const sanitizeHtml = require('sanitize-html');
const _ = require('#helpers/lodash');
const Aliases = require('#models/aliases');
const CalendarEvents = require('#models/calendar-events');
const Calendars = require('#models/calendars');
const Domains = require('#models/domains');
const Emails = require('#models/emails');
const config = require('#config');
const isCodeBug = require('#helpers/is-code-bug');
const createTangerine = require('#helpers/create-tangerine');
// eslint-disable-next-line import/no-unassigned-import
require('#helpers/polyfill-towellformed');
const env = require('#config/env');
const i18n = require('#helpers/i18n');
const isEmail = require('#helpers/is-email');
const sendApnCalendar = require('#helpers/send-apn-calendar');
const sendWebSocketNotification = require('#helpers/send-websocket-notification');
const setupAuthSession = require('#helpers/setup-auth-session');
const { processCalendarInvites } = require('#helpers/process-calendar-invites');
const {
buildICS: buildICSHelper,
detectAttendeePartstatChange,
resetPartstatsOnSignificantChange,
sendCalendarEmail
} = require('#helpers/send-calendar-email');
const {
parseContentDispositionFilename,
quoteICSFilenames
} = require('#helpers/ical-filename');
const exdateRegex =
/^EXDATE(?:;TZID=[\w/+=-]+|;VALUE=DATE)?:\d{8}(?:T\d{6}(?:\.\d{1,3})?Z?)?$/;
function isValidExdate(str) {
return exdateRegex.test(str);
}
//
// RFC 8607 Managed Attachments Constants
// <https://www.rfc-editor.org/rfc/rfc8607.html>
//
const MAX_ATTACHMENT_SIZE = 10 * 1024 * 1024; // 10 MB
const MAX_ATTACHMENTS_PER_RESOURCE = 10;
const DAV_HEADER_VALUE =
'1, 3, calendar-access, calendar-schedule, calendar-auto-schedule, calendar-managed-attachments, calendar-managed-attachments-no-recurrence';
//
// Reminders (DEFAULT_TASK_CALENDAR_NAME)
//
const I18N_SET_REMINDERS = new Set([
...Object.values({
ar: 'تذكيرات', // (tadhkīrāt) - No capitalization in Arabic script
cs: 'Připomínky',
da: 'Påmindelser',
de: 'Erinnerungen',
en: 'Reminders',
es: 'Recordatorios',
fi: 'Muistutukset',
fr: 'Rappels',
he: 'תזכורות', // (tazkorot) - No capitalization in Hebrew script
hu: 'Emlékeztetők',
id: 'Pengingat',
it: 'Promemoria',
ja: 'リマインダー', // (rimaindā) - No capitalization in Japanese script
ko: '리마인더', // (rimaideo) or '알림' (allim) - No capitalization in Korean script
nl: 'Herinneringen',
no: 'Påminnelser',
pl: 'Przypomnienia',
pt: 'Lembretes',
ru: 'Напоминания', // (Napominaniya)
sv: 'Påminnelser',
th: 'การแจ้งเตือน', // (kān jâeng dtôn) - No capitalization in Thai script
tr: 'Hatırlatıcılar',
uk: 'Нагадування', // (Nahaduvannya)
vi: 'Lời nhắc',
zh: '提醒' // (tíxǐng) - No capitalization in Chinese script
}),
//
// Alternates
//
// ko
'알림' // (allim) No capitalization in Korean script
]);
//
// Tasks
//
const I18N_SET_TASKS = new Set([
...Object.values({
ar: 'مهام', // (mahām) - No capitalization in Arabic script
cs: 'Úkoly',
da: 'Opgaver',
de: 'Aufgaben',
en: 'Tasks',
es: 'Tareas',
fi: 'Tehtävät',
fr: 'Tâches',
he: 'משימות', // (mesimot) - No capitalization in Hebrew script
hu: 'Feladatok',
id: 'Tugas',
it: 'Attività', // or 'Compiti'
ja: 'タスク', // (tasuku) or '任務' (ninmu) - No capitalization in Japanese script
ko: '작업', // (jageop) or '태스크' (taeseukeu) - No capitalization in Korean script
nl: 'Taken',
no: 'Oppgaver',
pl: 'Zadania',
pt: 'Tarefas',
ru: 'Задачи', // (Zadachi)
sv: 'Uppgifter',
th: 'งาน', // (ngān) - No capitalization in Thai script
tr: 'Görevler',
uk: 'Завдання', // (Zavdannya)
vi: 'Nhiệm vụ',
zh: '任务' // (rènwù) - No capitalization in Chinese script
}),
//
// Alternates
//
// it
'Compiti',
// ja
'任務', // (ninmu)
// ko
'태스크' // (taeseukeu)
]);
//
// Appointments
//
const I18N_SET_APPOINTMENTS = new Set([
...Object.values({
ar: 'مواعيد', // (mawāʿīd) - No capitalization in Arabic script
cs: 'Schůzky',
da: 'Aftaler',
de: 'Termine',
en: 'Appointments',
es: 'Citas',
fi: 'Tapaamiset',
fr: 'Rendez-vous',
he: 'פגישות', // (pgishot) - No capitalization in Hebrew script
hu: 'Találkozók',
id: 'Janji temu',
it: 'Appuntamenti',
ja: '予定', // (yotei) or 'アポイントメント' (apointomento) - No capitalization in Japanese script
ko: '약속', // (yaksok) or '예약' (yeyak) - No capitalization in Korean script
nl: 'Afspraken',
no: 'Avtaler',
pl: 'Spotkania', // or 'Terminy'
pt: 'Compromissos',
ru: 'Встречи', // (Vstrechi) or 'Назначения' (Naznacheniya)
sv: 'Möten', // or 'Bokningar'
th: 'นัดหมาย', // (nat māi) - No capitalization in Thai script
tr: 'Randevular',
uk: 'Зустрічі', // (Zustrichi) or 'Призначення' (Pryznachennya)
vi: 'Cuộc hẹn',
zh: '预约' // (yùyuē) - No capitalization in Chinese script
}),
//
// Alternates
//
// ja
'アポイントメント', // (apointomento)
// ko
'예약', // (yeyak)
// pl
'Terminy',
// ru
'Назначения', // (Naznacheniya)
// sv
'Bokningar', // Already capitalized as provided, correct as is
// uk
'Призначення' // (Pryznachennya)
]);
// Events
const I18N_SET_EVENTS = new Set([
...Object.values({
ar: 'أحداث', // (aḥdāth) - No capitalization in Arabic script
cs: 'Události',
da: 'Begivenheder',
de: 'Ereignisse', // or 'Veranstaltungen'
en: 'Events',
es: 'Eventos',
fi: 'Tapahtumat',
fr: 'Événements',
he: 'אירועים', // (irua’im) - No capitalization in Hebrew script
hu: 'Események',
id: 'Acara',
it: 'Eventi',
ja: 'イベント', // (ibento) or '行事' (gyōji) - No capitalization in Japanese script
ko: '이벤트', // (ibenteu) or '행사' (haengsa) - No capitalization in Korean script
nl: 'Evenementen',
no: 'Hendelser', // or 'Arrangementer'
pl: 'Wydarzenia',
pt: 'Eventos',
ru: 'События', // (Sobytiya)
sv: 'Evenemang',
th: 'เหตุการณ์', // (hētukān) or 'งาน' (ngān) - No capitalization in Thai script
tr: 'Etkinlikler',
uk: 'Події', // (Podiyi)
vi: 'Sự kiện',
zh: '活动' // (huódòng) or '事件' (shìjiàn) - No capitalization in Chinese script
}),
//
// Alternates
//
// de
'Veranstaltungen',
// ja
'行事', // (gyōji) - No capitalization in Japanese script
// ko
'행사', // (haengsa) - No capitalization in Korean script
// no
'Arrangementer',
// th
'งาน', // (ngān) - No capitalization in Thai script
// zh
'事件' // (shìjiàn) - No capitalization in Chinese script
]);
// Default
const I18N_SET_DEFAULT = new Set(
Object.values({
ar: 'افتراضي', // (iftirāḍī) - No capitalization in Arabic script
cs: 'Výchozí',
da: 'Standard',
de: 'Standard',
en: 'Default',
es: 'Predeterminado',
fi: 'Oletus',
fr: 'Par défaut',
he: 'ברירת מחדל', // (brerat machdal) - No capitalization in Hebrew script
hu: 'Alapértelmezett',
id: 'Bawaan',
it: 'Predefinito',
ja: 'デフォルト', // (deforuto) - No capitalization in Japanese script
ko: '기본', // (gibon) - No capitalization in Korean script
nl: 'Standaard',
no: 'Standard',
pl: 'Domyślny',
pt: 'Padrão',
ru: 'По умолчанию', // (Po umolchaniyu)
sv: 'Standard',
th: 'ค่าเริ่มต้น', // (khâ rûem dtôn) - No capitalization in Thai script
tr: 'Varsayılan',
uk: 'За замовчуванням', // (Za zamovchuvannyam)
vi: 'Mặc định',
zh: '默认' // (mòrèn) - No capitalization in Chinese script
})
);
// Calendar
const I18N_CALENDAR = {
ar: 'تقويم', // (taqwīm) - No capitalization in Arabic script
cs: 'Kalendář',
da: 'Kalender',
de: 'Kalender',
en: 'Calendar',
es: 'Calendario',
fi: 'Kalenteri',
fr: 'Calendrier',
he: 'לוח שנה', // (luach shana) - No capitalization in Hebrew script
hu: 'Naptár',
id: 'Kalender',
it: 'Calendario',
ja: 'カレンダー', // (karendā) - No capitalization in Japanese script
ko: '달력', // (dallyeok) - No capitalization in Korean script
nl: 'Kalender',
no: 'Kalender',
pl: 'Kalendarz',
pt: 'Calendário',
ru: 'Календарь', // (Kalendar)
sv: 'Kalender',
th: 'ปฏิทิน', // (patithin) - No capitalization in Thai script
tr: 'Takvim',
uk: 'Календар', // (Kalendar)
vi: 'Lịch',
zh: '日历' // (rìlì) - No capitalization in Chinese script
};
const I18N_SET_CALENDAR = new Set(Object.values(I18N_CALENDAR));
// DEFAULT_CALENDAR_NAME
const I18N_SET_DEFAULT_CALENDAR_NAME = new Set([
...I18N_SET_CALENDAR,
...I18N_SET_EVENTS,
...I18N_SET_DEFAULT
]);
async function ensureDefaultCalendars(ctx) {
//
// this only gets run if there are *zero* calendars on Android/Windows/etc
// otherwise if on Apple this ensures that there
// is a "Calendar" (DEFAULT_CALENDAR_NAME) and "Reminders" (DEFAULT_TASK_CALENDAR_NAME) created
//
const calendarDefaults = {
// db virtual helper
instance: this,
session: ctx.state.session,
//
// calendar obj
//
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`
};
const count = await Calendars.countDocuments(this, ctx.state.session, {});
if (count > 0) return;
if (!ctx.state.isApple) {
await Calendars.create({
...calendarDefaults,
calendarId: randomUUID(),
color: '#0000FF', // blue
//
// NOTE: Android uses "Events" and most others use "Calendar" as default calendar name
//
// create "Calendar" in localized string
//
name: I18N_CALENDAR[ctx.locale] || ctx.translate('CALENDAR'),
has_vevent: true, // Support both events and tasks
has_vtodo: true
});
// return early since Apple check is up next
return;
}
//
// NOTE: we detect user-agent and if we're on macOS/iOS then ensure created:
// - DEFAULT_CALENDAR_NAME <-> Calendar
// - DEFAULT_TASK_CALENDAR_NAME <-> Reminders
//
// (or similar variants that would be fetched via subsequent MKCALENDAR call)
//
let [defaultCalendar, defaultTaskCalendar] = await Promise.all([
Calendars.findOne(this, ctx.state.session, {
name: 'DEFAULT_CALENDAR_NAME'
}),
Calendars.findOne(this, ctx.state.session, {
name: 'DEFAULT_TASK_CALENDAR_NAME'
})
]);
[defaultCalendar, defaultTaskCalendar] = await Promise.all([
defaultCalendar
? Promise.resolve(defaultCalendar)
: Calendars.findOne(this, ctx.state.session, {
name: {
$in: [...I18N_SET_CALENDAR]
}
}),
defaultTaskCalendar
? Promise.resolve(defaultTaskCalendar)
: Calendars.findOne(this, ctx.state.session, {
name: {
$in: [...I18N_SET_REMINDERS]
}
})
]);
if (!defaultCalendar)
defaultCalendar = await Calendars.findOne(this, ctx.state.session, {
name: { $in: [...I18N_SET_DEFAULT_CALENDAR_NAME] }
});
// Create a single unified calendar that supports both events and tasks
if (!defaultCalendar) {
defaultCalendar = await Calendars.create({
...calendarDefaults,
calendarId: randomUUID(),
color: '#0000FF', // blue
name: 'DEFAULT_CALENDAR_NAME', // Calendar
has_vevent: true, // Support both events and tasks
has_vtodo: true
});
}
// For backward compatibility, if a separate task calendar exists, keep it
// but we won't create a new one by default
if (!defaultTaskCalendar) {
defaultTaskCalendar = defaultCalendar; // Use the same calendar for tasks
}
ctx.logger.debug('defaultCalendar', { defaultCalendar });
ctx.logger.debug('defaultTaskCalendar', { defaultTaskCalendar });
}
//
// NOTE: google's implementation is available at the following link:
// <https://developers.google.com/calendar/caldav/v2/guide>
//
// NOTE: to debug iCal on macOS see Console and run these commands
// <https://sabre.io/dav/clients/ical/#:~:text=Technical%20information-,Debugging,-To%20enable%20the>
//
// TODO: DNS SRV records <https://sabre.io/dav/service-discovery/#dns-srv-records>
function bumpSyncToken(synctoken) {
//
// synctoken must be a valid URL like:
// https://forwardemail.net/ns/sync-token/1
//
// If the synctoken is corrupted (e.g. just a number, or a partial
// path like "/7"), we reset to the default base URL to prevent
// mongoose validation failures (isURL check).
//
const DEFAULT_SYNC_BASE = `${config.urls.web}/ns/sync-token`;
if (typeof synctoken !== 'string' || synctoken.trim() === '') {
return `${DEFAULT_SYNC_BASE}/1`;
}
const parts = synctoken.split('/');
const lastPart = parts[parts.length - 1];
const num = Number.parseInt(lastPart, 10);
// If the last part is not a valid number, reset
if (Number.isNaN(num)) {
return `${DEFAULT_SYNC_BASE}/1`;
}
const base = parts.slice(0, -1).join('/');
// If the base is empty or not a valid URL prefix, reset with the bumped number
if (!base || !base.startsWith('http')) {
return `${DEFAULT_SYNC_BASE}/${num + 1}`;
}
return `${base}/${num + 1}`;
}
// Helper function to detect component type from ICS data
function getComponentType(icsData) {
try {
const parsed = ICAL.parse(icsData);
if (!parsed || parsed.length === 0) return null;
const comp = new ICAL.Component(parsed);
if (!comp) return null;
const vevent = comp.getFirstSubcomponent('vevent');
const vtodo = comp.getFirstSubcomponent('vtodo');
if (vevent && !vtodo) return 'VEVENT';
if (vtodo && !vevent) return 'VTODO';
if (vevent && vtodo) return 'VEVENT'; // Prioritize VEVENT for mixed content
return null;
} catch {
return null;
}
}
// Helper function to determine if calendar supports specific component type
function calendarSupportsComponent(calendar, componentType) {
if (!calendar) {
// Default behavior: support both VEVENT and VTODO
return componentType === 'VEVENT' || componentType === 'VTODO';
}
if (componentType === 'VEVENT') {
return calendar.has_vevent !== false; // Default to true if not set
}
if (componentType === 'VTODO') {
return calendar.has_vtodo !== false; // Default to true if not set
}
return false;
}
//
// Helper function to get eventId variants for flexible lookup.
// This ensures backwards compatibility by searching for both
// eventId with and without .ics extension.
//
// For example, if eventId is "abc123", it will search for:
// - "abc123"
// - "abc123.ics"
//
// If eventId is "abc123.ics", it will search for:
// - "abc123.ics"
// - "abc123"
//
function getEventIdVariants(eventId) {
if (typeof eventId !== 'string') return [eventId];
if (eventId.endsWith('.ics')) {
return [eventId, eventId.slice(0, -4)];
}
return [eventId, `${eventId}.ics`];
}
// 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(...args) {
super(...args);
this.resolver = createTangerine(this.client, this.logger);
this.wsp = this.config.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.handleManagedAttachment = this.handleManagedAttachment.bind(this);
this.handleAttachmentGet = this.handleAttachmentGet.bind(this);
//
// Wrap the caldav-adapter middleware with error handling.
// Without this wrapper, any error thrown in CalDAV handlers
// (createEvent, updateEvent, etc.) bubbles up to koa-better-error-handler,
// which calls `ctx.accepts(['text', 'json', 'html'])`. CalDAV clients
// (Thunderbird, Apple Calendar, etc.) send Accept headers like
// `text/xml` or `*/*` that don't match those three types, so the error
// handler overrides the status to 406 Not Acceptable — masking the real
// error and confusing clients.
//
// This wrapper catches errors and returns a proper WebDAV/CalDAV XML
// error response so the client sees the actual HTTP status code and
// error message, and the real error is logged server-side.
//
const caldavMiddleware = 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
}
});
this.app.use(async (ctx, next) => {