@push.rocks/smartnetwork 4.5.2 → 4.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,659 @@
1
+ import { domainToASCII } from 'node:url';
2
+ import * as plugins from './smartnetwork.plugins.js';
3
+ import { getLogger } from './logging.js';
4
+
5
+ /** Type alias for a Smartdns client instance */
6
+ type TSmartdnsClient = InstanceType<typeof plugins.smartdns.dnsClientMod.Smartdns>;
7
+ /** Type alias for a single DNS record returned by Smartdns */
8
+ type TDnsRecord = Awaited<ReturnType<TSmartdnsClient['getRecordsA']>>[number];
9
+
10
+ /**
11
+ * Unified result from a domain RDAP intelligence lookup.
12
+ */
13
+ export interface IDomainIntelligenceResult {
14
+ /** Normalized ASCII (punycode) form of the queried domain */
15
+ domain: string | null;
16
+ /** Registry handle / identifier */
17
+ handle: string | null;
18
+ /** EPP status values, e.g. ["active", "client transfer prohibited"] */
19
+ status: string[] | null;
20
+
21
+ // Registration lifecycle (ISO 8601 timestamps from RDAP events)
22
+ registrationDate: string | null;
23
+ expirationDate: string | null;
24
+ lastChangedDate: string | null;
25
+
26
+ // Sponsoring registrar
27
+ registrarName: string | null;
28
+ registrarIanaId: number | null;
29
+
30
+ // Registrant (often redacted under GDPR)
31
+ registrantOrg: string | null;
32
+ registrantCountry: string | null;
33
+
34
+ // Abuse contact (commonly nested under the registrar entity)
35
+ abuseEmail: string | null;
36
+ abusePhone: string | null;
37
+
38
+ // Technical
39
+ nameservers: string[] | null;
40
+ dnssec: boolean | null;
41
+
42
+ /** Which layer populated the nameservers field */
43
+ nameserversSource: 'rdap' | 'dns' | null;
44
+
45
+ // DNS enrichment (from smartdns)
46
+ /** IPv4 A records */
47
+ resolvedIpv4: string[] | null;
48
+ /** IPv6 AAAA records */
49
+ resolvedIpv6: string[] | null;
50
+ /** Parsed MX records with priority and exchange */
51
+ mxRecords: { priority: number | null; exchange: string }[] | null;
52
+ /** TXT records (SPF, DKIM, site verification, etc.) */
53
+ txtRecords: string[] | null;
54
+ /** Raw serialized SOA record value */
55
+ soaRecord: string | null;
56
+ }
57
+
58
+ /**
59
+ * Options for DomainIntelligence
60
+ */
61
+ export interface IDomainIntelligenceOptions {
62
+ /** Timeout (ms) for RDAP/bootstrap/DNS requests. Default: 5000 */
63
+ timeout?: number;
64
+ /**
65
+ * Optional injected smartdns client. When provided, DomainIntelligence
66
+ * will not create or destroy its own client (the owner — typically
67
+ * SmartNetwork — manages lifecycle). When omitted, a short-lived client
68
+ * is created per DNS-layer query and destroyed in finally.
69
+ */
70
+ dnsClient?: TSmartdnsClient;
71
+ }
72
+
73
+ // IANA bootstrap for domain RDAP
74
+ const IANA_BOOTSTRAP_DNS_URL = 'https://data.iana.org/rdap/dns.json';
75
+ const DEFAULT_TIMEOUT = 5000;
76
+
77
+ /**
78
+ * Build an empty result object with all fields nulled.
79
+ */
80
+ function emptyResult(domain: string | null = null): IDomainIntelligenceResult {
81
+ return {
82
+ domain,
83
+ handle: null,
84
+ status: null,
85
+ registrationDate: null,
86
+ expirationDate: null,
87
+ lastChangedDate: null,
88
+ registrarName: null,
89
+ registrarIanaId: null,
90
+ registrantOrg: null,
91
+ registrantCountry: null,
92
+ abuseEmail: null,
93
+ abusePhone: null,
94
+ nameservers: null,
95
+ dnssec: null,
96
+ nameserversSource: null,
97
+ resolvedIpv4: null,
98
+ resolvedIpv6: null,
99
+ mxRecords: null,
100
+ txtRecords: null,
101
+ soaRecord: null,
102
+ };
103
+ }
104
+
105
+ /**
106
+ * DomainIntelligence performs RDAP lookups for domain names using the
107
+ * IANA DNS bootstrap to discover the correct registry RDAP endpoint per TLD.
108
+ */
109
+ export class DomainIntelligence {
110
+ private readonly logger = getLogger();
111
+ private readonly timeout: number;
112
+
113
+ // Bootstrap cache: tld (lowercased) -> RDAP base URL (without trailing slash)
114
+ private bootstrapEntries: Map<string, string> | null = null;
115
+ private bootstrapPromise: Promise<void> | null = null;
116
+
117
+ // Optional injected smartdns client (shared by SmartNetwork)
118
+ private readonly sharedDnsClient: TSmartdnsClient | null;
119
+
120
+ constructor(options?: IDomainIntelligenceOptions) {
121
+ this.timeout = options?.timeout ?? DEFAULT_TIMEOUT;
122
+ this.sharedDnsClient = options?.dnsClient ?? null;
123
+ }
124
+
125
+ /**
126
+ * Get comprehensive domain intelligence. Runs RDAP and DNS lookups in
127
+ * parallel, then merges the results. Returns an all-null result (rather
128
+ * than throwing) for malformed input, unknown TLDs, or total failure.
129
+ *
130
+ * - RDAP provides: registrar, registrant, events (registration/expiration),
131
+ * nameservers (registry/parent), status, DNSSEC, abuse contact
132
+ * - DNS provides: A/AAAA records, MX, TXT, SOA, and a nameservers fallback
133
+ * when RDAP is unavailable (closes the ccTLD gap)
134
+ */
135
+ public async getIntelligence(domain: string): Promise<IDomainIntelligenceResult> {
136
+ const normalized = this.normalizeDomain(domain);
137
+ if (!normalized) return emptyResult(null);
138
+
139
+ const [rdapSettled, dnsSettled] = await Promise.allSettled([
140
+ this.queryRdapLayer(normalized),
141
+ this.queryDnsLayer(normalized),
142
+ ]);
143
+
144
+ const result = emptyResult(normalized);
145
+
146
+ // Merge RDAP fields (if any) — start with the parsed RDAP result as the base
147
+ if (rdapSettled.status === 'fulfilled' && rdapSettled.value) {
148
+ Object.assign(result, rdapSettled.value);
149
+ if (result.nameservers && result.nameservers.length > 0) {
150
+ result.nameserversSource = 'rdap';
151
+ }
152
+ }
153
+
154
+ // Merge DNS fields (if any)
155
+ if (dnsSettled.status === 'fulfilled' && dnsSettled.value) {
156
+ const dns = dnsSettled.value;
157
+ result.resolvedIpv4 = dns.resolvedIpv4;
158
+ result.resolvedIpv6 = dns.resolvedIpv6;
159
+ result.mxRecords = dns.mxRecords;
160
+ result.txtRecords = dns.txtRecords;
161
+ result.soaRecord = dns.soaRecord;
162
+ // Nameserver fallback: only from DNS when RDAP didn't populate it
163
+ if ((!result.nameservers || result.nameservers.length === 0) && dns.nameservers) {
164
+ result.nameservers = dns.nameservers;
165
+ result.nameserversSource = 'dns';
166
+ }
167
+ }
168
+
169
+ return result;
170
+ }
171
+
172
+ // ─── RDAP Layer (existing logic, wrapped) ───────────────────────────
173
+
174
+ /**
175
+ * Run the full RDAP lookup flow for a pre-normalized domain: extract TLD,
176
+ * load bootstrap, match registry, query, and parse. Returns the parsed
177
+ * RDAP fields (as a full IDomainIntelligenceResult) or null if any step
178
+ * fails or the TLD has no RDAP support.
179
+ */
180
+ private async queryRdapLayer(domain: string): Promise<IDomainIntelligenceResult | null> {
181
+ const tld = this.extractTld(domain);
182
+ if (!tld) return null;
183
+
184
+ await this.ensureBootstrap();
185
+ const baseUrl = this.matchTld(tld);
186
+ if (!baseUrl) return null;
187
+
188
+ const rdapData = await this.queryRdap(domain, baseUrl);
189
+ if (!rdapData) return null;
190
+
191
+ return this.parseRdapResponse(domain, rdapData);
192
+ }
193
+
194
+ // ─── Normalization & TLD extraction ─────────────────────────────────
195
+
196
+ /**
197
+ * Normalize a domain to lowercased ASCII punycode form. Returns null for
198
+ * obviously invalid input.
199
+ */
200
+ private normalizeDomain(input: string): string | null {
201
+ if (typeof input !== 'string') return null;
202
+ let trimmed = input.trim().toLowerCase();
203
+ if (!trimmed) return null;
204
+ // Strip a single trailing dot (FQDN form)
205
+ if (trimmed.endsWith('.')) trimmed = trimmed.slice(0, -1);
206
+ if (!trimmed) return null;
207
+ // Reject inputs that contain whitespace, slashes, or other URL noise
208
+ if (/[\s/\\?#]/.test(trimmed)) return null;
209
+
210
+ // Convert IDN to ASCII (punycode). Returns '' for invalid input.
211
+ const ascii = domainToASCII(trimmed);
212
+ if (!ascii) return null;
213
+
214
+ // Must contain at least one dot to have a TLD
215
+ if (!ascii.includes('.')) return null;
216
+
217
+ return ascii;
218
+ }
219
+
220
+ /**
221
+ * Extract the TLD as the last dot-separated label.
222
+ */
223
+ private extractTld(domain: string): string | null {
224
+ const idx = domain.lastIndexOf('.');
225
+ if (idx < 0 || idx === domain.length - 1) return null;
226
+ return domain.slice(idx + 1);
227
+ }
228
+
229
+ // ─── Bootstrap Subsystem ────────────────────────────────────────────
230
+
231
+ /**
232
+ * Load and cache the IANA DNS bootstrap file.
233
+ */
234
+ private async ensureBootstrap(): Promise<void> {
235
+ if (this.bootstrapEntries) return;
236
+ if (this.bootstrapPromise) {
237
+ await this.bootstrapPromise;
238
+ return;
239
+ }
240
+
241
+ this.bootstrapPromise = (async () => {
242
+ try {
243
+ const controller = new AbortController();
244
+ const timeoutId = setTimeout(() => controller.abort(), this.timeout);
245
+ try {
246
+ const response = await fetch(IANA_BOOTSTRAP_DNS_URL, {
247
+ signal: controller.signal,
248
+ headers: { 'User-Agent': '@push.rocks/smartnetwork' },
249
+ });
250
+ if (!response.ok) throw new Error(`HTTP ${response.status}`);
251
+ const data = (await response.json()) as { services: [string[], string[]][] };
252
+
253
+ const entries = new Map<string, string>();
254
+ for (const [tlds, urls] of data.services) {
255
+ const baseUrl = urls[0]; // first URL is preferred
256
+ if (!baseUrl) continue;
257
+ const cleanBase = baseUrl.replace(/\/$/, ''); // strip trailing slash
258
+ for (const tld of tlds) {
259
+ entries.set(tld.toLowerCase(), cleanBase);
260
+ }
261
+ }
262
+ this.bootstrapEntries = entries;
263
+ } finally {
264
+ clearTimeout(timeoutId);
265
+ }
266
+ } catch (err: any) {
267
+ this.logger.debug?.(`Failed to load DNS RDAP bootstrap: ${err.message}`);
268
+ this.bootstrapEntries = new Map(); // empty = all RDAP lookups will skip
269
+ }
270
+ })();
271
+
272
+ await this.bootstrapPromise;
273
+ this.bootstrapPromise = null;
274
+ }
275
+
276
+ /**
277
+ * Find the RDAP base URL for a given TLD via direct lookup.
278
+ */
279
+ private matchTld(tld: string): string | null {
280
+ if (!this.bootstrapEntries || this.bootstrapEntries.size === 0) return null;
281
+ return this.bootstrapEntries.get(tld.toLowerCase()) ?? null;
282
+ }
283
+
284
+ // ─── RDAP Query ─────────────────────────────────────────────────────
285
+
286
+ /**
287
+ * Perform the RDAP HTTP query for a domain.
288
+ */
289
+ private async queryRdap(domain: string, baseUrl: string): Promise<any | null> {
290
+ const controller = new AbortController();
291
+ const timeoutId = setTimeout(() => controller.abort(), this.timeout);
292
+ try {
293
+ const response = await fetch(`${baseUrl}/domain/${encodeURIComponent(domain)}`, {
294
+ signal: controller.signal,
295
+ headers: {
296
+ 'Accept': 'application/rdap+json',
297
+ 'User-Agent': '@push.rocks/smartnetwork',
298
+ },
299
+ });
300
+ if (!response.ok) return null;
301
+ return await response.json();
302
+ } catch (err: any) {
303
+ this.logger.debug?.(`RDAP query failed for ${domain}: ${err.message}`);
304
+ return null;
305
+ } finally {
306
+ clearTimeout(timeoutId);
307
+ }
308
+ }
309
+
310
+ // ─── RDAP Response Parsing ──────────────────────────────────────────
311
+
312
+ private parseRdapResponse(domain: string, data: any): IDomainIntelligenceResult {
313
+ const result = emptyResult(domain);
314
+
315
+ if (typeof data.handle === 'string') result.handle = data.handle;
316
+
317
+ if (Array.isArray(data.status) && data.status.length > 0) {
318
+ result.status = data.status.filter((s: any): s is string => typeof s === 'string');
319
+ }
320
+
321
+ // Events: registration / expiration / last changed
322
+ if (Array.isArray(data.events)) {
323
+ const events = this.extractEvents(data.events);
324
+ result.registrationDate = events.registration;
325
+ result.expirationDate = events.expiration;
326
+ result.lastChangedDate = events.lastChanged;
327
+ }
328
+
329
+ // Registrar (sponsor) and registrant from entities
330
+ if (Array.isArray(data.entities)) {
331
+ const registrar = this.extractRegistrar(data.entities);
332
+ result.registrarName = registrar.name;
333
+ result.registrarIanaId = registrar.ianaId;
334
+ result.abuseEmail = registrar.abuseEmail;
335
+ result.abusePhone = registrar.abusePhone;
336
+
337
+ const registrant = this.extractRegistrant(data.entities);
338
+ result.registrantOrg = registrant.org;
339
+ result.registrantCountry = registrant.country;
340
+ }
341
+
342
+ // Nameservers
343
+ if (Array.isArray(data.nameservers)) {
344
+ result.nameservers = this.extractNameservers(data.nameservers);
345
+ }
346
+
347
+ // DNSSEC: secureDNS.delegationSigned
348
+ if (data.secureDNS && typeof data.secureDNS.delegationSigned === 'boolean') {
349
+ result.dnssec = data.secureDNS.delegationSigned;
350
+ }
351
+
352
+ return result;
353
+ }
354
+
355
+ /**
356
+ * Pull registration / expiration / last changed timestamps from an
357
+ * RDAP `events` array.
358
+ */
359
+ private extractEvents(events: any[]): {
360
+ registration: string | null;
361
+ expiration: string | null;
362
+ lastChanged: string | null;
363
+ } {
364
+ let registration: string | null = null;
365
+ let expiration: string | null = null;
366
+ let lastChanged: string | null = null;
367
+
368
+ for (const ev of events) {
369
+ const action = typeof ev?.eventAction === 'string' ? ev.eventAction.toLowerCase() : '';
370
+ const date = typeof ev?.eventDate === 'string' ? ev.eventDate : null;
371
+ if (!date) continue;
372
+ if (action === 'registration') registration = date;
373
+ else if (action === 'expiration') expiration = date;
374
+ else if (action === 'last changed') lastChanged = date;
375
+ }
376
+
377
+ return { registration, expiration, lastChanged };
378
+ }
379
+
380
+ /**
381
+ * Extract registrar identity (name, IANA ID) and a nested abuse contact.
382
+ */
383
+ private extractRegistrar(entities: any[]): {
384
+ name: string | null;
385
+ ianaId: number | null;
386
+ abuseEmail: string | null;
387
+ abusePhone: string | null;
388
+ } {
389
+ let name: string | null = null;
390
+ let ianaId: number | null = null;
391
+ let abuseEmail: string | null = null;
392
+ let abusePhone: string | null = null;
393
+
394
+ for (const entity of entities) {
395
+ const roles: string[] = Array.isArray(entity?.roles) ? entity.roles : [];
396
+ if (!roles.includes('registrar')) continue;
397
+
398
+ name = this.extractVcardFn(entity);
399
+
400
+ // IANA Registrar ID lives in publicIds[]
401
+ if (Array.isArray(entity.publicIds)) {
402
+ for (const pid of entity.publicIds) {
403
+ if (pid && typeof pid === 'object' && pid.type === 'IANA Registrar ID') {
404
+ const parsed = parseInt(String(pid.identifier), 10);
405
+ if (!isNaN(parsed)) ianaId = parsed;
406
+ }
407
+ }
408
+ }
409
+
410
+ // Abuse contact: nested entity with role "abuse"
411
+ if (Array.isArray(entity.entities)) {
412
+ for (const sub of entity.entities) {
413
+ const subRoles: string[] = Array.isArray(sub?.roles) ? sub.roles : [];
414
+ if (subRoles.includes('abuse')) {
415
+ if (!abuseEmail) abuseEmail = this.extractVcardEmail(sub);
416
+ if (!abusePhone) abusePhone = this.extractVcardTel(sub);
417
+ }
418
+ }
419
+ }
420
+
421
+ break; // first registrar wins
422
+ }
423
+
424
+ return { name, ianaId, abuseEmail, abusePhone };
425
+ }
426
+
427
+ /**
428
+ * Extract registrant org/country from entities array.
429
+ */
430
+ private extractRegistrant(entities: any[]): {
431
+ org: string | null;
432
+ country: string | null;
433
+ } {
434
+ for (const entity of entities) {
435
+ const roles: string[] = Array.isArray(entity?.roles) ? entity.roles : [];
436
+ if (!roles.includes('registrant')) continue;
437
+ const org = this.extractVcardFn(entity);
438
+ const country = this.extractVcardCountry(entity);
439
+ return { org, country };
440
+ }
441
+ return { org: null, country: null };
442
+ }
443
+
444
+ /**
445
+ * Map an RDAP nameservers[] array to a list of lowercased ldhName strings.
446
+ */
447
+ private extractNameservers(nameservers: any[]): string[] | null {
448
+ const out: string[] = [];
449
+ for (const ns of nameservers) {
450
+ const ldh = ns?.ldhName;
451
+ if (typeof ldh === 'string' && ldh.length > 0) {
452
+ out.push(ldh.toLowerCase());
453
+ }
454
+ }
455
+ return out.length > 0 ? out : null;
456
+ }
457
+
458
+ // ─── DNS Layer ──────────────────────────────────────────────────────
459
+
460
+ /**
461
+ * Run DNS record lookups for the given domain using smartdns. Queries
462
+ * NS/A/AAAA/MX/TXT/SOA in parallel via Promise.allSettled — failures in
463
+ * one record type do not affect the others. Returns an object with each
464
+ * field either populated or null.
465
+ *
466
+ * If a shared dnsClient was injected via constructor options, it is
467
+ * reused and NOT destroyed (ownership stays with the injector). Otherwise
468
+ * a short-lived client is created and destroyed in finally.
469
+ */
470
+ private async queryDnsLayer(domain: string): Promise<{
471
+ nameservers: string[] | null;
472
+ resolvedIpv4: string[] | null;
473
+ resolvedIpv6: string[] | null;
474
+ mxRecords: { priority: number | null; exchange: string }[] | null;
475
+ txtRecords: string[] | null;
476
+ soaRecord: string | null;
477
+ } | null> {
478
+ const external = this.sharedDnsClient !== null;
479
+ let dnsClient: TSmartdnsClient | null = this.sharedDnsClient;
480
+ try {
481
+ if (!dnsClient) {
482
+ dnsClient = new plugins.smartdns.dnsClientMod.Smartdns({
483
+ strategy: 'prefer-system',
484
+ allowDohFallback: true,
485
+ timeoutMs: this.timeout,
486
+ });
487
+ }
488
+
489
+ const [nsRes, aRes, aaaaRes, mxRes, txtRes, soaRes] = await Promise.allSettled([
490
+ dnsClient.getNameServers(domain),
491
+ dnsClient.getRecordsA(domain),
492
+ dnsClient.getRecordsAAAA(domain),
493
+ dnsClient.getRecords(domain, 'MX'),
494
+ dnsClient.getRecordsTxt(domain),
495
+ // 'SOA' is in smartdns's runtime dnsTypeMap but missing from the
496
+ // TDnsRecordType union in @tsclass/tsclass — cast to bypass the
497
+ // stale type definition.
498
+ dnsClient.getRecords(domain, 'SOA' as any),
499
+ ]);
500
+
501
+ return {
502
+ nameservers: this.parseNsResult(nsRes),
503
+ resolvedIpv4: this.dnsValuesOrNull(aRes),
504
+ resolvedIpv6: this.dnsValuesOrNull(aaaaRes),
505
+ mxRecords: this.parseMxRecords(mxRes),
506
+ txtRecords: this.dnsValuesOrNull(txtRes),
507
+ soaRecord: this.dnsFirstValueOrNull(soaRes),
508
+ };
509
+ } catch (err: any) {
510
+ this.logger.debug?.(`DNS layer failed for ${domain}: ${err.message}`);
511
+ return null;
512
+ } finally {
513
+ // Only destroy clients we created ourselves; leave injected ones alone.
514
+ if (!external && dnsClient) {
515
+ dnsClient.destroy();
516
+ }
517
+ }
518
+ }
519
+
520
+ /**
521
+ * Extract normalized nameserver hostnames from a getNameServers() result.
522
+ */
523
+ private parseNsResult(res: PromiseSettledResult<string[]>): string[] | null {
524
+ if (res.status !== 'fulfilled' || !Array.isArray(res.value) || res.value.length === 0) {
525
+ return null;
526
+ }
527
+ const out = res.value
528
+ .map((ns) => (typeof ns === 'string' ? ns.toLowerCase().replace(/\.$/, '') : ''))
529
+ .filter((ns) => ns.length > 0);
530
+ return out.length > 0 ? out : null;
531
+ }
532
+
533
+ /**
534
+ * Extract `value` strings from a settled DNS lookup result.
535
+ */
536
+ private dnsValuesOrNull(res: PromiseSettledResult<TDnsRecord[]>): string[] | null {
537
+ if (res.status !== 'fulfilled' || !Array.isArray(res.value) || res.value.length === 0) {
538
+ return null;
539
+ }
540
+ const values = res.value
541
+ .map((r) => r.value)
542
+ .filter((v): v is string => typeof v === 'string' && v.length > 0);
543
+ return values.length > 0 ? values : null;
544
+ }
545
+
546
+ /**
547
+ * First non-empty value from a settled DNS lookup result.
548
+ */
549
+ private dnsFirstValueOrNull(res: PromiseSettledResult<TDnsRecord[]>): string | null {
550
+ const values = this.dnsValuesOrNull(res);
551
+ return values?.[0] ?? null;
552
+ }
553
+
554
+ /**
555
+ * Parse MX records into {priority, exchange} pairs. smartdns returns MX
556
+ * values as serialized strings (typically "10 mail.example.com"). We
557
+ * best-effort parse the priority; if parsing fails we store the whole
558
+ * value as the exchange with priority=null so the result is still useful.
559
+ */
560
+ private parseMxRecords(
561
+ res: PromiseSettledResult<TDnsRecord[]>,
562
+ ): { priority: number | null; exchange: string }[] | null {
563
+ if (res.status !== 'fulfilled' || !Array.isArray(res.value) || res.value.length === 0) {
564
+ return null;
565
+ }
566
+ const out: { priority: number | null; exchange: string }[] = [];
567
+ for (const r of res.value) {
568
+ if (typeof r.value !== 'string' || !r.value.trim()) continue;
569
+ const match = r.value.trim().match(/^(\d+)\s+(.+?)\.?$/);
570
+ if (match) {
571
+ out.push({ priority: parseInt(match[1], 10), exchange: match[2].toLowerCase() });
572
+ } else {
573
+ out.push({ priority: null, exchange: r.value.toLowerCase().replace(/\.$/, '') });
574
+ }
575
+ }
576
+ return out.length > 0 ? out : null;
577
+ }
578
+
579
+ // ─── vCard helpers (duplicated from IpIntelligence) ─────────────────
580
+
581
+ /**
582
+ * Extract the 'fn' (formatted name) from an entity's vcardArray
583
+ */
584
+ private extractVcardFn(entity: any): string | null {
585
+ if (!entity?.vcardArray || !Array.isArray(entity.vcardArray)) return null;
586
+ const properties = entity.vcardArray[1];
587
+ if (!Array.isArray(properties)) return null;
588
+
589
+ for (const prop of properties) {
590
+ if (Array.isArray(prop) && prop[0] === 'fn') {
591
+ return prop[3] || null;
592
+ }
593
+ }
594
+ return null;
595
+ }
596
+
597
+ /**
598
+ * Extract email from an entity's vcardArray
599
+ */
600
+ private extractVcardEmail(entity: any): string | null {
601
+ if (!entity?.vcardArray || !Array.isArray(entity.vcardArray)) return null;
602
+ const properties = entity.vcardArray[1];
603
+ if (!Array.isArray(properties)) return null;
604
+
605
+ for (const prop of properties) {
606
+ if (Array.isArray(prop) && prop[0] === 'email') {
607
+ return prop[3] || null;
608
+ }
609
+ }
610
+ return null;
611
+ }
612
+
613
+ /**
614
+ * Extract telephone number from an entity's vcardArray
615
+ */
616
+ private extractVcardTel(entity: any): string | null {
617
+ if (!entity?.vcardArray || !Array.isArray(entity.vcardArray)) return null;
618
+ const properties = entity.vcardArray[1];
619
+ if (!Array.isArray(properties)) return null;
620
+
621
+ for (const prop of properties) {
622
+ if (Array.isArray(prop) && prop[0] === 'tel') {
623
+ // tel value can be a string or a uri like "tel:+1.5555555555"
624
+ const value = prop[3];
625
+ if (typeof value === 'string') {
626
+ return value.startsWith('tel:') ? value.slice(4) : value;
627
+ }
628
+ }
629
+ }
630
+ return null;
631
+ }
632
+
633
+ /**
634
+ * Extract country from an entity's vcardArray address field
635
+ */
636
+ private extractVcardCountry(entity: any): string | null {
637
+ if (!entity?.vcardArray || !Array.isArray(entity.vcardArray)) return null;
638
+ const properties = entity.vcardArray[1];
639
+ if (!Array.isArray(properties)) return null;
640
+
641
+ for (const prop of properties) {
642
+ if (Array.isArray(prop) && prop[0] === 'adr') {
643
+ // The label parameter often contains the full address with country at the end
644
+ const label = prop[1]?.label;
645
+ if (typeof label === 'string') {
646
+ const lines = label.split('\n');
647
+ const lastLine = lines[lines.length - 1]?.trim();
648
+ if (lastLine && lastLine.length > 1) return lastLine;
649
+ }
650
+ // Also check the structured value (7-element array, last element is country)
651
+ const value = prop[3];
652
+ if (Array.isArray(value) && value.length >= 7 && value[6]) {
653
+ return value[6];
654
+ }
655
+ }
656
+ }
657
+ return null;
658
+ }
659
+ }