-
Notifications
You must be signed in to change notification settings - Fork 198
Expand file tree
/
Copy pathindex.js
More file actions
1070 lines (911 loc) · 33 KB
/
Copy pathindex.js
File metadata and controls
1070 lines (911 loc) · 33 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 Boom = require('@hapi/boom');
const Router = require('@koa/router');
const basicAuth = require('basic-auth');
const AddressBooks = require('#models/address-books');
const CardDAVFilterParser = require('#helpers/carddav-filter-parser');
const Contacts = require('#models/contacts');
const config = require('#config');
const setupAuthSession = require('#helpers/setup-auth-session');
const ensureDefaultAddressBook = require('#helpers/ensure-default-address-book');
const xmlHelpers = require('#helpers/carddav-xml');
const { encodeXMLEntities } = xmlHelpers;
// TODO: PROPPATCH
function vcf(id) {
if (id.toLowerCase().endsWith('.vcf')) return '';
return '.vcf';
}
const router = new Router();
// status page crawlers often send `HEAD /` requests
router.get('/', (ctx) => {
ctx.body = 'OK';
});
// OPTIONS route for CORS and DAV discovery
router.options('(.*)', (ctx) => {
ctx.set('DAV', '1, 3, addressbook');
ctx.set(
'Allow',
'OPTIONS, GET, PUT, DELETE, PROPFIND, PROPPATCH, REPORT, MKCOL'
);
ctx.status = 200;
});
router.all('(.*)', async (ctx, next) => {
// if request is authenticated then redirect to principal
const creds = basicAuth(ctx);
if (creds) {
try {
ctx.logger.debug('authenticate', {
username: creds.name
});
await setupAuthSession.call(ctx.instance, ctx, creds.name, creds.pass);
} catch (err) {
ctx.response.set(
'WWW-Authenticate',
'Basic realm="forwardemail/carddav"'
);
throw err;
}
await ensureDefaultAddressBook.call(ctx.instance, ctx);
// Handle .well-known/carddav redirect (RFC 6764)
if (ctx.url.toLowerCase() === '/.well-known/carddav')
return ctx.redirect(`/dav/${ctx.state.session.user.username}/`);
return next();
}
// Handle .well-known/carddav redirect (RFC 6764)
if (ctx.url.toLowerCase() === '/.well-known/carddav')
return ctx.redirect('/dav/');
ctx.response.set('WWW-Authenticate', 'Basic realm="forwardemail/carddav"');
throw Boom.unauthorized();
});
const davRouter = new Router({
prefix: '/dav'
});
davRouter.all('/:user/addressbooks/:addressbook/:contact(.+)', async (ctx) => {
if (!['PROPFIND', 'GET', 'PUT', 'DELETE'].includes(ctx.method))
throw Boom.methodNotAllowed();
const { addressbook, contact: rawContact } = ctx.params;
// Normalize contact_id by removing .vcf extension if present
// macOS and other clients may or may not include the extension
const contact = rawContact.replace(/\.vcf$/i, '');
// Find address book
const addressBook = await AddressBooks.findOne(
ctx.instance,
ctx.state.session,
{
address_book_id: addressbook
}
);
if (!addressBook)
throw Boom.notFound(ctx.translateError('ADDRESS_BOOK_DOES_NOT_EXIST'));
// db virtual helper
addressBook.instance = ctx.instance;
addressBook.session = ctx.state.session;
// so we can call `save()`
addressBook.isNew = false;
switch (ctx.method) {
case 'PROPFIND': {
// Find contact
const contactObj = await Contacts.findOne(
ctx.instance,
ctx.state.session,
{
address_book: addressBook._id,
contact_id: contact
}
);
if (!contactObj)
throw Boom.notFound(ctx.translateError('CONTACT_DOES_NOT_EXIST'));
// Parse XML request body
const xmlBody = ctx.request.body
? await xmlHelpers.parseXML(ctx.request.body.toString())
: null;
const props = xmlHelpers.extractRequestedProps(xmlBody);
// Create response - include .vcf extension for client compatibility
const xml = xmlHelpers.getPropfindContactXML(
{
href: `/dav/${
ctx.params.user
}/addressbooks/${addressbook}/${contact}${vcf(contact)}`,
etag: contactObj.etag,
content: contactObj.content
},
props
);
ctx.type = 'application/xml';
ctx.status = 207;
ctx.body = xml;
break;
}
case 'GET': {
// Find contact
const contactObj = await Contacts.findOne(
ctx.instance,
ctx.state.session,
{
address_book: addressBook._id,
contact_id: contact
}
);
if (!contactObj)
throw Boom.notFound(ctx.translateError('CONTACT_DOES_NOT_EXIST'));
ctx.type = 'text/vcard; charset=utf-8';
ctx.set('ETag', contactObj.etag);
ctx.status = 200;
ctx.body = contactObj.content;
break;
}
case 'PUT': {
// Check if address book is read-only
if (addressBook.readonly)
throw Boom.forbidden(ctx.translateError('ADDRESS_BOOK_READONLY'));
// Get vCard content
const vCardContent = ctx.request.body.toString();
// Parse vCard to extract properties (this also validates the vCard)
const vCard = xmlHelpers.parseVCard(vCardContent);
// Check if contact already exists
const existingContact = await Contacts.findOne(
ctx.instance,
ctx.state.session,
{
address_book: addressBook._id,
contact_id: contact
}
);
// Check If-None-Match header (RFC 2616 Section 14.26)
const ifNoneMatch = ctx.request.headers['if-none-match'];
if (ifNoneMatch === '*' && existingContact) {
throw Boom.preconditionFailed(
ctx.translateError('RESOURCE_ALREADY_EXISTS')
);
}
// Generate ETag
const newEtag = xmlHelpers.generateETag(vCardContent);
if (existingContact) {
// Check If-Match header if present
const ifMatch = ctx.request.headers['if-match'];
if (ifMatch && ifMatch !== existingContact.etag)
throw Boom.preconditionFailed(
ctx.translateError('ETAG_DOES_NOT_MATCH')
);
// Update existing contact
existingContact.content = vCardContent;
existingContact.etag = newEtag;
existingContact.fullName = vCard.FN || '';
// Update other extracted fields as needed
if (vCard.EMAIL) {
existingContact.emails = Array.isArray(vCard.EMAIL)
? vCard.EMAIL.map((email) => ({ value: email, type: 'INTERNET' }))
: [{ value: vCard.EMAIL, type: 'INTERNET' }];
}
if (vCard.TEL) {
existingContact.phoneNumbers = Array.isArray(vCard.TEL)
? vCard.TEL.map((tel) => ({ value: tel, type: 'CELL' }))
: [{ value: vCard.TEL, type: 'CELL' }];
}
// db virtual helper
existingContact.instance = ctx.instance;
existingContact.session = ctx.state.session;
// so we can call `save()`
existingContact.isNew = false;
await existingContact.save();
// Update address book sync token
addressBook.synctoken = `${
config.urls.web
}/ns/sync-token/${Date.now()}`;
await addressBook.save();
ctx.set('ETag', newEtag);
ctx.status = 204;
} else {
// Create new contact
await Contacts.create({
// db virtual helper
instance: ctx.instance,
session: ctx.state.session,
address_book: addressBook._id,
contact_id: contact,
uid: vCard.UID || randomUUID(),
content: vCardContent,
etag: newEtag,
fullName: vCard.FN || '',
isGroup: vCard.KIND === 'group',
emails: vCard.EMAIL
? Array.isArray(vCard.EMAIL)
? vCard.EMAIL.map((email) => ({
value: email,
type: 'INTERNET'
}))
: [{ value: vCard.EMAIL, type: 'INTERNET' }]
: [],
phoneNumbers: vCard.TEL
? Array.isArray(vCard.TEL)
? vCard.TEL.map((tel) => ({ value: tel, type: 'CELL' }))
: [{ value: vCard.TEL, type: 'CELL' }]
: []
});
// Update address book sync token
addressBook.synctoken = `${
config.urls.web
}/ns/sync-token/${Date.now()}`;
await addressBook.save();
ctx.set('ETag', newEtag);
ctx.status = 201;
}
break;
}
case 'DELETE': {
// Check if address book is read-only
if (addressBook.readonly)
throw Boom.forbidden(ctx.translateError('ADDRESS_BOOK_READONLY'));
// Find contact
const contactObj = await Contacts.findOne(
ctx.instance,
ctx.state.session,
{
address_book: addressBook._id,
contact_id: contact
}
);
if (!contactObj)
throw Boom.notFound(ctx.translateError('CONTACT_DOES_NOT_EXIST'));
// Check If-Match header if present
const ifMatch = ctx.request.headers['if-match'];
if (ifMatch && ifMatch !== contactObj.etag)
throw Boom.preconditionFailed(
ctx.translateError('ETAG_DOES_NOT_MATCH')
);
// Delete contact
await Contacts.deleteOne(ctx.instance, ctx.state.session, {
_id: contactObj._id
});
// TODO: define $__remove in sqlite helper
// await contactObj.remove();
// Update address book sync token
addressBook.synctoken = `${config.urls.web}/ns/sync-token/${Date.now()}`;
await addressBook.save();
ctx.status = 204;
break;
}
default: {
throw Boom.methodNotAllowed();
}
}
});
davRouter.all('/:user/addressbooks/:addressbook', async (ctx) => {
if (
!['PROPFIND', 'MKCOL', 'DELETE', 'REPORT', 'PROPPATCH'].includes(ctx.method)
)
throw Boom.methodNotAllowed();
const { addressbook } = ctx.params;
// Find address book for methods that require it
let addressBook;
if (ctx.method !== 'MKCOL') {
addressBook = await AddressBooks.findOne(ctx.instance, ctx.state.session, {
address_book_id: addressbook
});
if (!addressBook)
throw Boom.notFound(ctx.translateError('ADDRESS_BOOK_DOES_NOT_EXIST'));
}
// Handle different methods
switch (ctx.method) {
case 'PROPFIND': {
const depth = ctx.request.headers.depth || '0';
// Parse XML request body
// const xmlBody = ctx.request.body
// ? await xmlHelpers.parseXML(ctx.request.body.toString())
// : null;
// const props = xmlHelpers.extractRequestedProps(xmlBody);
// Create response for address book
const responses = [
{
href: `/dav/${ctx.params.user}/addressbooks/${addressbook}/`,
propstat: [
{
props: [
{
name: 'd:displayname',
value: encodeXMLEntities(addressBook.name)
},
{
name: 'd:resourcetype',
value: '<d:collection/><card:addressbook/>'
},
{ name: 'd:sync-token', value: addressBook.synctoken },
{
name: 'card:addressbook-description',
value: encodeXMLEntities(addressBook.description || '')
},
{
name: 'card:supported-address-data',
value:
'<card:address-data-type content-type="text/vcard" version="3.0"/>'
}
],
status: '200 OK'
}
]
}
];
// If depth is 1, include contacts
if (depth === '1') {
const contacts = await Contacts.find(ctx.instance, ctx.state.session, {
address_book: addressBook._id
});
for (const contact of contacts) {
responses.push({
href: `/dav/${ctx.params.user}/addressbooks/${addressbook}/${
contact.contact_id
}${vcf(contact.contact_id)}`,
propstat: [
{
props: [
{ name: 'd:getetag', value: contact.etag },
{
name: 'd:getcontenttype',
value: 'text/vcard; charset=utf-8'
},
{ name: 'd:resourcetype', value: '' }
],
status: '200 OK'
}
]
});
}
}
const xml = xmlHelpers.getMultistatusXML(responses);
ctx.type = 'application/xml';
ctx.status = 207;
ctx.body = xml;
break;
}
case 'MKCOL': {
// Check if address book already exists
const existingAddressBook = await AddressBooks.findOne(
ctx.instance,
ctx.state.session,
{
address_book_id: addressbook
}
);
if (existingAddressBook)
throw Boom.conflict(ctx.translateError('ADDRESS_BOOK_ALREADY_EXISTS'));
// Parse XML request body
const xmlBody = ctx.request.body
? await xmlHelpers.parseXML(ctx.request.body.toString())
: null;
// Extract properties
let displayName = addressbook;
let description = '';
if (
xmlBody &&
xmlBody.mkcol &&
xmlBody.mkcol.set &&
xmlBody.mkcol.set.prop
) {
const props = xmlBody.mkcol.set.prop;
if (props.displayname) {
displayName = props.displayname;
}
if (props['addressbook-description']) {
description = props['addressbook-description'];
}
}
// Create new address book
await AddressBooks.create({
// db virtual helper
instance: ctx.instance,
session: ctx.state.session,
address_book_id: addressbook,
name: displayName,
description,
color: '#0000FF', // Default color
synctoken: `${config.urls.web}/ns/sync-token/1`,
timezone: ctx.state.session.user.timezone || 'UTC',
// TODO: fix port if 443 or 80 then don't render it (?)
url: `${ctx.instance.config.protocol}://${ctx.instance.config.host}:${ctx.instance.config.port}/dav/${ctx.params.user}/addressbooks/${addressbook}/`,
prodId: `//forwardemail.net//carddav//EN`
});
ctx.status = 201;
break;
}
case 'DELETE': {
// Delete all contacts in the address book
await Contacts.deleteMany(ctx.instance, ctx.state.session, {
address_book: addressBook._id
});
// Delete address book
await AddressBooks.deleteOne(ctx.instance, ctx.state.session, {
_id: addressBook._id
});
// TODO: define $__remove in sqlite helper
// await addressBook.remove();
ctx.status = 204;
break;
}
case 'REPORT': {
// Parse XML request body
const xmlBody = ctx.request.body
? await xmlHelpers.parseXML(ctx.request.body.toString())
: null;
if (!xmlBody)
throw Boom.badRequest(ctx.translateError('INVALID_XML_REQUEST_BODY'));
// const props = xmlHelpers.extractRequestedProps(xmlBody);
// Handle different report types
if (xmlBody['addressbook-query']) {
await handleAddressbookQuery(ctx, xmlBody, addressBook);
} else if (xmlBody['addressbook-multiget']) {
await handleAddressbookMultiget(ctx, xmlBody, addressBook);
} else if (xmlBody['sync-collection']) {
await handleSyncCollection(ctx, xmlBody, addressBook);
} else {
const err = Boom.badRequest(
ctx.translateError('UNSUPPORTED_REPORT_TYPE')
);
err.xmlBody = xmlBody;
err.requestBody = ctx.request.body;
throw err;
}
break;
}
case 'PROPPATCH': {
// Parse XML request body
const xmlBody = ctx.request.body
? await xmlHelpers.parseXML(ctx.request.body.toString())
: null;
if (!xmlBody || !xmlBody.propertyupdate)
throw Boom.badRequest(ctx.translateError('INVALID_XML_REQUEST_BODY'));
// db virtual helper
addressBook.instance = ctx.instance;
addressBook.session = ctx.state.session;
addressBook.isNew = false;
// Track which properties were successfully updated
const updatedProps = [];
const failedProps = [];
// Handle set operations
if (xmlBody.propertyupdate.set) {
const setOperations = Array.isArray(xmlBody.propertyupdate.set)
? xmlBody.propertyupdate.set
: [xmlBody.propertyupdate.set];
for (const setOp of setOperations) {
if (!setOp.prop) continue;
const props = setOp.prop;
// Update displayname
if (props.displayname) {
addressBook.name = props.displayname;
updatedProps.push('displayname');
}
// Update addressbook-description
if (props['addressbook-description']) {
addressBook.description = props['addressbook-description'];
updatedProps.push('addressbook-description');
}
// Update color (if provided)
if (props['calendar-color'] || props.color) {
addressBook.color = props['calendar-color'] || props.color;
updatedProps.push('calendar-color');
}
}
}
// Handle remove operations
if (xmlBody.propertyupdate.remove) {
const removeOperations = Array.isArray(xmlBody.propertyupdate.remove)
? xmlBody.propertyupdate.remove
: [xmlBody.propertyupdate.remove];
for (const removeOp of removeOperations) {
if (!removeOp.prop) continue;
const props = removeOp.prop;
// Remove description
if (props['addressbook-description']) {
addressBook.description = '';
updatedProps.push('addressbook-description');
}
}
}
// Save changes
if (updatedProps.length > 0) {
await addressBook.save();
// Update sync token
addressBook.synctoken = `${
config.urls.web
}/ns/sync-token/${Date.now()}`;
await addressBook.save();
}
// Build response
const responses = [
{
href: `/dav/${ctx.params.user}/addressbooks/${addressbook}/`,
propstat: []
}
];
// Add success propstat if there are updated props
if (updatedProps.length > 0) {
responses[0].propstat.push({
props: updatedProps.map((name) => ({ name, value: '' })),
status: '200 OK'
});
}
// Add failed propstat if there are failed props
if (failedProps.length > 0) {
responses[0].propstat.push({
props: failedProps.map((name) => ({ name, value: '' })),
status: '403 Forbidden'
});
}
const xml = xmlHelpers.getMultistatusXML(responses);
ctx.type = 'application/xml';
ctx.status = 207;
ctx.body = xml;
break;
}
default: {
throw Boom.methodNotAllowed();
}
}
});
davRouter.all('/:user/addressbooks', async (ctx) => {
if (ctx.method !== 'PROPFIND') throw Boom.methodNotAllowed();
try {
const depth = ctx.request.headers.depth || '0';
// Parse XML request body
// const xmlBody = ctx.request.body
// ? await xmlHelpers.parseXML(ctx.request.body.toString())
// : null;
// const props = xmlHelpers.extractRequestedProps(xmlBody);
// Create response
const responses = [
{
href: `/dav/${ctx.params.user}/addressbooks/`,
propstat: [
{
props: [
{ name: 'd:displayname', value: 'Address Books' },
{ name: 'd:resourcetype', value: '<d:collection/>' }
],
status: '200 OK'
}
]
}
];
// If depth is 1, include address books
if (depth === '1') {
const addressBooks = await AddressBooks.find(
ctx.instance,
ctx.state.session,
{}
);
for (const addressBook of addressBooks) {
responses.push({
href: `/dav/${ctx.params.user}/addressbooks/${addressBook.address_book_id}/`,
propstat: [
{
props: [
{
name: 'd:displayname',
value: encodeXMLEntities(addressBook.name)
},
{
name: 'd:resourcetype',
value: '<d:collection/><card:addressbook/>'
},
{ name: 'd:sync-token', value: addressBook.synctoken },
{
name: 'card:addressbook-description',
value: encodeXMLEntities(addressBook.description || '')
}
],
status: '200 OK'
}
]
});
}
}
const xml = xmlHelpers.getMultistatusXML(responses);
ctx.type = 'application/xml';
ctx.status = 207;
ctx.body = xml;
} catch (err) {
ctx.logger.error(err);
throw new TypeError('Error processing PROPFIND request');
}
});
// Helper functions for REPORT handling
//
// # CardDAV `addressbook-query` Filters and Testing with `tsdav`
//
// To ensure a CardDAV server complies with [RFC 6352](https://tools.ietf.org/html/rfc6352), it must support the `addressbook-query` REPORT for querying address book data, including all specified filters and their combinations. The `tsdav` package, a TypeScript/JavaScript library for WebDAV and CardDAV, provides a convenient way to test these queries using the `addressBookQuery` method. This document outlines the complete set of standard `addressbook-query` filters, provides example XML bodies, and shows how to structure them as arguments for `tsdav`'s `addressBookQuery`. It also includes considerations for testing server compliance.
//
// ## Overview of `addressbook-query` Filters
//
// Per RFC 6352, Section 8.6, a CardDAV server must support the `addressbook-query` REPORT with these filter elements:
//
// - **`<C:prop-filter>`**: Filters vCard objects based on a specific vCard property (e.g., `FN`, `EMAIL`, `TEL`).
// - **`<C:param-filter>`**: Filters based on parameters of a property (e.g., `TYPE=WORK` for an `EMAIL` property).
// - **`<C:text-match>`**: Matches text values in properties, with attributes:
// - `collation`: At least `i;ascii-casemap` (case-insensitive) must be supported; `i;unicode-casemap` is optional.
// - `match-type`: Supports `equals`, `contains`, `starts-with`, `ends-with`.
// - `negate-condition`: Optional boolean (`yes` or `no`) to invert the match.
// - **`<C:is-not-defined>`**: Matches vCards where a property or parameter is absent.
// - **`<C:filter test="anyof|allof">`**: Combines multiple `<C:prop-filter>` elements logically:
// - `anyof`: At least one condition must match.
// - `allof`: All conditions must match.
// - **`<D:prop>`**: Specifies which properties to return (e.g., `D:getetag`, `C:address-data`).
// - **`<C:address-data>`**: Optionally limits the vCard properties returned (e.g., only `FN` and `EMAIL`).
//
// A CardDAV server must handle these filters for common vCard properties (e.g., `FN`, `N`, `EMAIL`, `TEL`, `ADR`, `ORG`) and their parameters (e.g., `TYPE`, `VALUE`). It should also support returning partial vCard data and handle edge cases like empty results or invalid filters.
//
// ## Using `tsdav` for Testing
//
// The `tsdav` package provides a `DAVClient` with an `addressBookQuery` method to send `addressbook-query` REPORT requests. The method takes an options object with these relevant properties:
//
// - `url`: The URL of the address book collection.
// - `properties`: An array of WebDAV properties to retrieve (e.g., `['{DAV:}getetag', '{urn:ietf:params:xml:ns:carddav}address-data']`).
// - `filters`: An array of filter objects defining the query criteria.
// - `headers`: Optional headers for authentication or other purposes.
// - `depth`: Typically `1` for querying resources in the collection.
//
// The `filters` array corresponds to the `<C:filter>` element and can include nested `<C:prop-filter>`, `<C:param-filter>`, `<C:text-match>`, and `<C:is-not-defined>` elements. Below are examples of all supported filter combinations and their `tsdav` equivalents.
//
// ## Example Queries and `tsdav` Calls
//
// Below are examples of all standard `addressbook-query` filters that a CardDAV server should support, along with their XML representations and corresponding `tsdav` `addressBookQuery` calls. These cover all required filter types and combinations, suitable for testing server compliance.
//
// ### 1. Simple `prop-filter` with `text-match`
//
// **Purpose**: Search for contacts where the `FN` (Formatted Name) property contains "John".
//
// **XML Request**:
// ```xml
// <?xml version="1.0" encoding="utf-8" ?>
// <D:addressbook-query xmlns:D="DAV:" xmlns:C="urn:ietf:params:xml:ns:carddav">
// <D:prop>
// <D:getetag/>
// <C:address-data/>
// </D:prop>
// <C:filter>
// <C:prop-filter name="FN">
// <C:text-match collation="i;ascii-casemap" match-type="contains">John</C:text-match>
// </C:prop-filter>
// </C:filter>
// </D:addressbook-query>
/**
* Handle addressbook query with complete RFC 6352 filter support
* Updated to work with actual ForwardEmail Contacts model
* @param {Object} ctx - Koa context
* @param {Object} xmlBody - Parsed XML body
* @param {Object} addressBook - Address book object
* @returns {Promise<void>}
*/
async function handleAddressbookQuery(ctx, xmlBody, addressBook) {
const { addressbook } = ctx.params;
try {
// Initialize the filter parser
const filterParser = new CardDAVFilterParser();
// Validate the filter first
const validation = xmlHelpers.validateFilter(xmlBody);
if (!validation.isValid) {
ctx.type = 'application/xml';
ctx.status = 400;
ctx.body = xmlHelpers.getFilterErrorXML(validation.error);
return;
}
// Extract requested properties
const props = xmlHelpers.extractRequestedProps(xmlBody);
// Parse the filter and convert to MongoDB query
const filterQuery = filterParser.parseFilter(xmlBody);
// Build the base query using the actual model structure
// Note: address_book field is ObjectId reference to AddressBooks
const query = {
address_book: addressBook._id, // Use the ObjectId from the addressBook document
...filterQuery
};
// Log the generated query for debugging
ctx.logger.debug('Generated MongoDB query:', { query });
// Execute the query using the actual Contacts model
const contacts = await Contacts.find(
ctx.instance,
ctx.state.session,
query
);
// Format contacts for response using actual model fields
const formattedContacts = contacts.map((contact) => ({
href: `/dav/${ctx.params.user}/addressbooks/${addressbook}/${
contact.contact_id
}${vcf(contact.contact_id)}`,
etag: contact.etag,
vcard: contact.content, // Use 'content' field from actual model
fullName: contact.fullName, // Available for debugging/logging
uid: contact.uid
}));
// Generate XML response
const xml = xmlHelpers.getAddressbookQueryXML(formattedContacts, props);
ctx.type = 'application/xml';
ctx.status = 207;
ctx.body = xml;
} catch (err) {
ctx.logger.error('Error in handleAddressbookQuery:', err);
throw new TypeError('Error processing addressbook query request');
}
}
/**
* Handle addressbook multiget with complete RFC 6352 filter support
* Updated to work with actual ForwardEmail Contacts model
* @param {Object} ctx - Koa context
* @param {Object} xmlBody - Parsed XML body
* @param {Object} addressBook - Address book object
* @returns {Promise<void>}
*/
async function handleAddressbookMultiget(ctx, xmlBody, addressBook) {
const { addressbook } = ctx.params;
try {
// Extract requested properties
const props = xmlHelpers.extractRequestedProps(xmlBody);
// Extract hrefs
const hrefs = xmlHelpers.extractHrefs(xmlBody);
if (!hrefs || hrefs.length === 0) {
ctx.type = 'application/xml';
ctx.status = 207;
ctx.body = xmlHelpers.getMultistatusXML([]);
return;
}
// Get contact IDs from hrefs - normalize by removing .vcf extension
const contactIds = hrefs.map((href) => {
const parts = href.split('/');
const filename = parts[parts.length - 1];
// Remove .vcf extension if present for consistent lookups
return filename.replace(/\.vcf$/i, '');
});
// Build query for specific contacts using actual model structure
const query = {
address_book: addressBook._id, // Use ObjectId reference
contact_id: { $in: contactIds } // Use contact_id field from model
};
// Execute the query
const contacts = await Contacts.find(
ctx.instance,
ctx.state.session,
query
);
// Format contacts for response
const formattedContacts = contacts.map((contact) => ({
href: `/dav/${ctx.params.user}/addressbooks/${addressbook}/${
contact.contact_id
}${vcf(contact.contact_id)}`,
etag: contact.etag,
vcard: contact.content, // Use 'content' field from actual model
fullName: contact.fullName,
uid: contact.uid
}));
// Generate XML response
const xml = xmlHelpers.getAddressbookQueryXML(formattedContacts, props);
ctx.type = 'application/xml';
ctx.status = 207;
ctx.body = xml;
} catch (err) {
ctx.logger.error('Error in handleAddressbookMultiget:', err);
throw new TypeError('Error processing addressbook multiget request');
}
}
async function handleSyncCollection(ctx, xmlBody, addressBook) {
const { addressbook } = ctx.params;
// Extract sync token
let syncToken = null;
let syncTimestamp = null;
if (xmlBody['sync-collection']['sync-token']) {
syncToken = xmlBody['sync-collection']['sync-token'];
// Parse timestamp from sync token (format: http://domain.com/ns/sync-token/1234567890)
const match = syncToken.match(/\/sync-token\/(\d+)$/);
if (match && match[1]) {
syncTimestamp = new Date(Number.parseInt(match[1], 10));
}
}
// Extract props
const props = [];
if (xmlBody['sync-collection'].prop) {
for (const key of Object.keys(xmlBody['sync-collection'].prop)) {
props.push(key);
}
}
// Get changes since sync token
let changes = [];
if (syncTimestamp && !Number.isNaN(syncTimestamp.getTime())) {
// Return only contacts modified after the sync token timestamp
const modifiedContacts = await Contacts.find(
ctx.instance,
ctx.state.session,
{
address_book: addressBook._id,
updated_at: { $gt: syncTimestamp }
}
);
changes = modifiedContacts.map((contact) => ({
href: `/dav/${ctx.params.user}/addressbooks/${addressbook}/${
contact.contact_id
}${vcf(contact.contact_id)}`,
etag: contact.etag,
vcard: contact.content,
deleted: false
}));
// TODO: Track deleted contacts
// For now, we don't track deletions separately
// In a full implementation, you'd need a "deleted_contacts" table
// or a soft-delete flag with deleted_at timestamp
} else {
// If no sync token or invalid token, return all contacts (initial sync)
const contacts = await Contacts.find(ctx.instance, ctx.state.session, {
address_book: addressBook._id
});
changes = contacts.map((contact) => ({
href: `/dav/${ctx.params.user}/addressbooks/${addressbook}/${
contact.contact_id
}${vcf(contact.contact_id)}`,
etag: contact.etag,
vcard: contact.content,
deleted: false
}));
}
// Generate XML response with updated sync token
const xml = xmlHelpers.getSyncCollectionXML(addressBook, changes, props);