-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlapsed.js
More file actions
787 lines (687 loc) · 27.9 KB
/
Copy pathlapsed.js
File metadata and controls
787 lines (687 loc) · 27.9 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
(() => {
const params = new URLSearchParams(window.location.search);
const domainInfo = createDomainInfo(params);
const state = { historyStatus: null, historyLabel: null, copyTimeout: null };
let rdapRegistry = new Set();
let sessionActive = true;
const RDAP_BOOTSTRAP_URL = 'https://data.iana.org/rdap/dns.json';
const RDAP_BOOTSTRAP_CACHE_KEY = 'rdapBootstrapCache';
const RDAP_BOOTSTRAP_TTL = 7 * 24 * 60 * 60 * 1000; // 7 days
const ui = mapElements([
'domainDisplay', 'copyHint', 'retryBtn', 'statusDot', 'statusHeadline',
'statusSub', 'rdapWarn', 'rdapSection', 'rdapTable', 'actionSection',
'actionLabel', 'actionLinks', 'actionNote', 'dropDate', 'waybackSection',
'waybackBlock', 'dnsSection', 'dnsTable', 'dnsInsight'
]);
const STATUS_KEYS = {
CHECKING: 'status-checking',
AVAILABLE: 'status-available',
PREMIUM: 'status-premium',
DROPPING: 'status-dropping',
GRACE: 'status-grace',
TAKEN: 'status-taken',
RESTRICTED: 'status-restricted',
ERROR: 'status-error'
};
const LINK_SETS = {
register: [
linkDef('Spaceship', d => `https://spaceship.sjv.io/c/7037939/1794549/21274?query=${d}`, 'primary', d => `Register ${d} on Spaceship`),
linkDef('Namecheap', d => `https://www.namecheap.com/domains/registration/results/?domain=${d}`, 'primary', d => `Register ${d} on Namecheap`),
linkDef('GoDaddy', d => `https://www.godaddy.com/domainsearch/find?domainToCheck=${d}`, 'primary', d => `Register ${d} on GoDaddy`),
linkDef('Dynadot', d => `https://www.dynadot.com/domain/search?q=${d}`, 'primary', d => `Register ${d} on Dynadot`),
linkDef('Porkbun', d => `https://porkbun.com/checkout/search?q=${d}`, 'primary', d => `Register ${d} on Porkbun`),
linkDef('NameSilo', d => `https://www.namesilo.com/domain/search-domains?query=${d}`, 'primary', d => `Register ${d} on NameSilo`)
],
dropAuction: [
linkDef('DropCatch', d => `https://www.dropcatch.com/domain/${d}`, 'default', d => `Check if ${d} is listed on DropCatch`),
linkDef('NameJet', d => `https://www.namejet.com/store/basic.action?dom=${d}`, 'default', d => `Check NameJet auction for ${d}`)
],
dropBackorder: [
linkDef('DropCatch', d => `https://www.dropcatch.com/domain/${d}`, 'default', d => `Backorder ${d} on DropCatch`),
linkDef('NameJet', d => `https://www.namejet.com/store/basic.action?dom=${d}`, 'default', d => `Backorder ${d} on NameJet`),
linkDef('Dynadot', d => `https://www.dynadot.com/market/backorder?domain=${d}`, 'default', d => `Backorder ${d} on Dynadot`),
linkDef('Sedo', d => `https://sedo.com/search/?keyword=${d}`, 'default', d => `Check ${d} on Sedo marketplace`)
],
expiredSale: [
linkDef('Sedo', d => `https://sedo.com/search/?keyword=${d}`, 'default', d => `Search for ${d} on Sedo`),
linkDef('Afternic', d => `https://www.afternic.com/forsale/${d}`, 'default', d => `Search for ${d} on Afternic`),
linkDef('Dynadot', d => `https://www.dynadot.com/market/backorder?domain=${d}`, 'default', d => `Backorder ${d} on Dynadot`)
],
sale: [
linkDef('Sedo', d => `https://sedo.com/search/?keyword=${d}`, 'default', d => `Search for ${d} on Sedo`),
linkDef('Afternic', d => `https://www.afternic.com/forsale/${d}`, 'default', d => `Search for ${d} on Afternic`)
]
};
init().catch((err) => console.error('Failed to initialize Lapsed:', err));
function init() {
renderDomain();
bindInteractions();
window.addEventListener('beforeunload', markInactive, { once: true });
window.addEventListener('pagehide', markInactive, { once: true });
if (!isValidDomainLabel(domainInfo.displayName)) {
setStatus(STATUS_KEYS.ERROR, 'Invalid Domain', 'The domain name contains invalid characters.');
return;
}
return loadRdapRegistry().then((registry) => {
rdapRegistry = registry;
runLookups();
});
}
function runLookups() {
checkRDAP();
checkWayback(domainInfo.ascii);
checkDNS(domainInfo.ascii);
}
function renderDomain() {
ui.domainDisplay.innerHTML = `${domainInfo.displayName}<span class="ext">${domainInfo.displayExt}</span>`;
document.title = `Lapsed · ${domainInfo.display}`;
}
function bindInteractions() {
ui.retryBtn.addEventListener('click', () => window.location.href = domainInfo.originalUrl);
ui.domainDisplay.addEventListener('click', copyDomain);
ui.domainDisplay.addEventListener('keydown', (e) => {
if (e.key === 'Enter' || e.key === ' ') copyDomain();
});
}
function copyDomain() {
navigator.clipboard.writeText(domainInfo.ascii).then(() => {
if (!isActive()) return;
ui.copyHint.textContent = 'Copied!';
ui.copyHint.classList.add('copied');
clearTimeout(state.copyTimeout);
state.copyTimeout = setTimeout(() => {
if (!isActive()) return;
ui.copyHint.textContent = 'Click to copy';
ui.copyHint.classList.remove('copied');
}, 2000);
});
}
async function checkRDAP() {
if (!isActive()) return;
if (!hasRdapCoverage(domainInfo.tld)) {
renderNoRdap(domainInfo.tld);
return;
}
const snapshot = await fetchRdapOrg(domainInfo.ascii);
if (!isActive()) return;
if (snapshot.type === 'available') {
renderAvailability();
return;
}
if (snapshot.type === 'error') {
setStatus(STATUS_KEYS.ERROR, 'Lookup failed', snapshot.message);
return;
}
if (!snapshot.data) {
setStatus(STATUS_KEYS.ERROR, 'No data', 'Could not retrieve domain information.');
return;
}
renderRegistered(snapshot.data);
}
function renderAvailability() {
setStatus(STATUS_KEYS.AVAILABLE, 'Available', 'No registration found in the registry');
showRegisterLinks();
}
function renderNoRdap(tld) {
const suffix = tld ? `.${tld}` : 'this TLD';
ui.rdapWarn.textContent = `We are unable to perform a lookup for ${suffix}. Please verify availability directly with the registry.`;
ui.rdapWarn.style.display = '';
setStatus(STATUS_KEYS.ERROR, 'Unsupported TLD', `It appears to be an invalid or unsupported TLD.`);
}
function renderRegistered(data) {
const statuses = getStatuses(data);
const expires = data.events?.find(e => e.eventAction === 'expiration')?.eventDate;
const created = data.events?.find(e => e.eventAction === 'registration')?.eventDate;
const updated = data.events?.find(e => e.eventAction === 'last changed')?.eventDate;
const expiryInfo = getExpiryInfo(expires);
const statusState = buildStatusState(statuses, expiryInfo, data);
setStatus(statusState.stateKey, statusState.headline, statusState.subtext);
if (statusState.blockMessage) {
ui.rdapWarn.textContent = statusState.blockMessage;
ui.rdapWarn.style.display = 'block';
} else {
ui.rdapWarn.style.display = 'none';
}
renderRdapTable({ data, statuses, created, updated, expires, expiryInfo });
renderActionSection({ state: statusState, expires, expiryInfo });
}
function renderRdapTable({ data, statuses, created, updated, expires, expiryInfo }) {
const rows = [];
const registrant = data.entities?.find(e => e.roles?.includes('registrant'));
if (registrant) {
const vcard = registrant.vcardArray?.[1];
const org = vcard?.find(v => v[0] === 'org')?.[3];
const fn = vcard?.find(v => v[0] === 'fn')?.[3];
if (org) rows.push(row('Registrant', org));
else if (fn && fn !== 'REDACTED FOR PRIVACY') rows.push(row('Registrant', fn));
}
const registrar = data.entities?.find(e => e.roles?.includes('registrar'));
if (registrar) {
const fn = registrar.vcardArray?.[1]?.find(v => v[0] === 'fn')?.[3];
if (fn) rows.push(row('Registrar', fn));
}
if (created) {
const age = getDomainAge(created);
rows.push(row('Created', `${formatDate(created)}${age ? ` (${age})` : ''}`));
}
if (expires) {
let cls = 'expiry-row';
if (expiryInfo?.isExpired) cls += expiryInfo.daysExpired > 30 ? ' expiry-danger' : ' expiry-warn';
else if (expiryInfo?.daysUntil <= 30) cls += ' expiry-warn';
else cls += ' expiry-ok';
const rel = expiryInfo?.isExpired
? `${formatDate(expires)} (${expiryInfo.daysExpired}d ago)`
: `${formatDate(expires)} (${relativeTime(expires)})`;
rows.push(row('Expires', rel, cls));
}
if (updated) rows.push(row('Updated', `${formatDate(updated)} (${relativeTime(updated)})`));
if (statuses.length) rows.push(row('Status', statuses.slice(0, 3).join(', ')));
const ns = data.nameservers?.slice(0, 3).map(n => n.ldhName?.toLowerCase()).filter(Boolean);
if (ns?.length) rows.push(row('Nameservers', ns.join('<br>')));
const whois = data.whois || {};
if (whois.createdDate && !created) rows.push(row('Created', whois.createdDate));
if (whois.expiryDate && !expires) rows.push(row('Expires', whois.expiryDate));
if (whois.registrar && !registrar) rows.push(row('Registrar', whois.registrar));
if (!rows.length) return;
ui.rdapSection.style.display = '';
ui.rdapTable.innerHTML = rows.map(renderRow).join('');
}
function renderActionSection({ state, expires, expiryInfo }) {
const { isDropping, isExpired } = state;
ui.actionSection.style.display = '';
ui.dropDate.style.display = 'none';
if (isDropping && expires) {
renderDropSection({ expires, expiryInfo, state });
return;
}
if (isExpired) {
ui.actionLabel.textContent = 'Check if for sale';
ui.actionLinks.innerHTML = buildLinks('expiredSale');
ui.actionNote.innerHTML = affiliateNote();
return;
}
ui.actionLabel.textContent = 'Check if for sale';
ui.actionLinks.innerHTML = buildLinks('sale');
ui.actionNote.innerHTML = affiliateNote();
}
function renderDropSection({ expires, expiryInfo, state }) {
const estimatedDrop = new Date(new Date(expires).getTime() + 75 * 86400000);
const isEstimate = !state.pendingDelete;
const today = new Date();
today.setHours(0, 0, 0, 0);
const alreadyDropped = estimatedDrop < today;
ui.dropDate.style.display = '';
if (alreadyDropped) {
const daysAgo = Math.floor((today - estimatedDrop) / 86400000);
setStatus(STATUS_KEYS.DROPPING, 'Past Drop Window', 'Estimated drop date has passed - may already be available');
ui.actionLabel.textContent = 'May have already dropped - check now';
ui.dropDate.textContent = `Estimated drop was ${formatDate(estimatedDrop.toISOString(), true)} (${daysAgo}d ago)${isEstimate ? ' - estimated' : ''}`;
ui.actionLinks.innerHTML = buildLinks('register') + buildLinks('dropAuction');
ui.actionNote.innerHTML = dropNote();
return;
}
const daysUntil = Math.ceil((estimatedDrop - today) / 86400000);
ui.actionLabel.textContent = 'Domain dropping soon - backorder now';
ui.dropDate.textContent = `Estimated drop: ${formatDate(estimatedDrop.toISOString(), true)} (in ${daysUntil}d)${isEstimate ? ' - estimated' : ''}`;
ui.actionLinks.innerHTML = buildLinks('dropBackorder');
ui.actionNote.innerHTML = 'Timelines vary by registrar and TLD. Links may include affiliate referrals - supports Lapsed.';
}
function showRegisterLinks() {
ui.actionSection.style.display = '';
ui.actionLabel.textContent = 'Register this domain';
ui.dropDate.style.display = 'none';
ui.actionLinks.innerHTML = buildLinks('register');
ui.actionNote.innerHTML = affiliateNote();
}
function buildLinks(setName) {
const defs = LINK_SETS[setName] || [];
return defs.map(def => linkButton(def.label, def.href(domainInfo.ascii), {
variant: def.variant,
title: typeof def.title === 'function' ? def.title(domainInfo.ascii) : def.title
})).join('');
}
function linkDef(label, hrefFn, variant = 'default', titleFn) {
return { label, href: hrefFn, variant, title: titleFn };
}
function linkButton(label, href, { variant = 'default', title } = {}) {
const cls = variant === 'primary' ? 'pill primary' : 'pill';
const safeTitle = title || label;
return `<a href="${href}" target="_blank" rel="noopener" class="${cls}" title="${safeTitle}">${label}</a>`;
}
function affiliateNote() {
return 'Links may include affiliate referrals - supports Lapsed.';
}
function dropNote() {
return 'If not available to register, it may have been caught at auction. Links may include affiliate referrals - supports Lapsed.';
}
function renderWayback(dateStr, url) {
ui.waybackSection.style.display = '';
ui.waybackBlock.innerHTML = `<span>Last snapshot ${dateStr}</span>${linkButton('View snapshot', url, { title: `View ${domainInfo.ascii} on Wayback` })}`;
}
async function checkWayback(domain) {
if (!isActive()) return;
try {
const res = await fetch(`https://archive.org/wayback/available?url=${domain}`);
const data = await res.json();
const snap = data?.archived_snapshots?.closest;
if (!snap?.available || !isActive()) return;
const ts = snap.timestamp;
const date = `${ts.slice(0, 4)}-${ts.slice(4, 6)}-${ts.slice(6, 8)}`;
const url = `https://web.archive.org/web/${ts}/https://${domain}`;
if (!isActive()) return;
renderWayback(date, url);
} catch (e) {
// ignore
}
}
async function checkDNS(domain) {
const types = ['A', 'MX', 'NS'];
const results = {};
await Promise.all(types.map(async (type) => {
try {
if (!isActive()) return;
const res = await fetch(`https://cloudflare-dns.com/dns-query?name=${encodeURIComponent(domain)}&type=${type}`, {
headers: { 'Accept': 'application/dns-json' }
});
if (!res.ok) return;
const data = await res.json();
if (data.Status !== 0 || !data.Answer?.length) return;
results[type] = data.Answer.map(r => r.data).filter(Boolean);
} catch (e) {
// ignore
}
}));
if (!isActive() || !Object.keys(results).length) return;
ui.dnsSection.style.display = '';
ui.dnsTable.innerHTML = Object.entries(results).map(([type, values]) =>
values.slice(0, 3).map((val, index) => `<tr><td>${index === 0 ? type : ''}</td><td>${val}</td></tr>`).join('')
).join('');
if (results.A?.length) {
ui.dnsInsight.innerHTML = `<div class="dns-insight alive">DNS resolves to ${results.A[0]} - server is reachable but the site is down. Domain is actively owned.</div>`;
} else if (results.MX?.length) {
ui.dnsInsight.innerHTML = '<div class="dns-insight alive">Has mail servers but no web presence. Domain is used for email - actively owned.</div>';
} else if (results.NS?.length) {
ui.dnsInsight.innerHTML = '<div class="dns-insight parked">NS records exist but no A or MX - domain may be parked or unconfigured.</div>';
}
}
function setStatus(stateKey, headline, subtext = '') {
const key = typeof stateKey === 'string' && stateKey.trim() ? stateKey.trim() : 'status-error';
ui.statusDot.className = `status-dot ${key}`;
ui.statusHeadline.className = `status-headline ${key}`;
ui.statusHeadline.innerHTML = headline;
ui.statusSub.innerHTML = subtext || '';
syncHistoryStatus(key, headline);
}
function syncHistoryStatus(stateKey, label) {
if (!stateKey || !label) return;
state.historyStatus = stateKey;
state.historyLabel = label;
if (typeof chrome === 'undefined' || !chrome.runtime?.sendMessage) return;
try {
chrome.runtime.sendMessage({ type: 'lapsedStatus', domain: domainInfo.ascii, status: stateKey, label });
} catch (e) {
// ignore
}
}
function buildStatusState(statuses, expiryInfo, data) {
const normalized = statuses.map(s => s.toLowerCase());
const has = (value) => normalized.some(status => status.includes(value));
const indicators = getNoticeIndicators(data);
const hasIndicator = (value) => indicators.some(s => s.toLowerCase().includes(value));
if (has('pending delete')) {
return {
stateKey: STATUS_KEYS.DROPPING,
headline: 'Pending Delete',
subtext: expiryInfo?.isExpired ? `Expired ${expiryInfo.daysExpired} days ago · cannot be renewed · dropping soon` : 'Cannot be renewed · dropping soon',
pendingDelete: true,
isDropping: true,
isExpired: true
};
}
if (has('redemption period')) {
return {
stateKey: STATUS_KEYS.GRACE,
headline: 'Redemption Period',
subtext: expiryInfo?.isExpired ? `Expired ${expiryInfo.daysExpired} days ago · expensive to reclaim` : 'Registry has locked this domain after expiration',
pendingDelete: false,
isDropping: false,
isExpired: true
};
}
if (has('auto renew period')) {
return {
stateKey: STATUS_KEYS.GRACE,
headline: 'Auto Renew Period',
subtext: 'Registrar has auto-renewed this domain temporarily.',
pendingDelete: false,
isDropping: false,
isExpired: false
};
}
if (has('premium')) {
return {
stateKey: STATUS_KEYS.PREMIUM,
headline: 'Premium Domain',
subtext: 'Costs more than standard pricing · check registrars for availability',
pendingDelete: false,
isDropping: false,
isExpired: false
};
}
if (has('client hold')) {
return {
stateKey: STATUS_KEYS.TAKEN,
headline: 'On Hold',
subtext: 'Suspended by registrar · owner may have billing issues',
pendingDelete: false,
isDropping: false,
isExpired: false
};
}
if (has('server hold')) {
return {
stateKey: STATUS_KEYS.TAKEN,
headline: 'Suspended',
subtext: 'Suspended by registry',
pendingDelete: false,
isDropping: false,
isExpired: false
};
}
if (has('reserved') || has('associated') || hasIndicator('reserved') || hasIndicator('restricted')) {
return {
stateKey: STATUS_KEYS.RESTRICTED,
headline: 'Registry Reserved',
subtext: 'This domain cannot be registered by the public.',
pendingDelete: false,
isDropping: false,
isExpired: false
};
}
if (has('blocked') || hasIndicator('blocked')) {
const detailedMsg = indicators.find(s => s.toLowerCase().includes('blocked by'));
const fallbackMsg = indicators.find(s => s.toLowerCase().includes('blocked'));
return {
stateKey: STATUS_KEYS.RESTRICTED,
headline: 'Domain Blocked',
subtext: 'This name has been blocked by a brand safety or protection service.',
blockMessage: detailedMsg || fallbackMsg,
pendingDelete: false,
isDropping: false,
isExpired: false
};
}
const registrar = data.entities?.find(e => e.roles?.includes('registrar'));
const registrarName = registrar?.vcardArray?.[1]?.find(v => v[0] === 'fn')?.[3] || '';
if (registrarName.toUpperCase().includes('RESERVED-INTERNET ASSIGNED NUMBERS AUTHORITY')) {
return {
stateKey: STATUS_KEYS.RESTRICTED,
headline: 'Registry Reserved',
subtext: 'This domain is reserved by IANA and cannot be registered.',
pendingDelete: false,
isDropping: false,
isExpired: false
};
}
if (expiryInfo?.isExpired) {
const days = expiryInfo.daysExpired;
if (days > 60) {
return {
stateKey: STATUS_KEYS.DROPPING,
headline: 'Pending Delete',
subtext: `Expired ${days} days ago · cannot be renewed · dropping soon`,
pendingDelete: true,
isDropping: true,
isExpired: true
};
}
if (days > 30) {
return {
stateKey: STATUS_KEYS.GRACE,
headline: 'Redemption Period',
subtext: `Expired ${days} days ago · expensive to reclaim`,
pendingDelete: false,
isDropping: false,
isExpired: true
};
}
return {
stateKey: STATUS_KEYS.GRACE,
headline: 'Expired',
subtext: `Expired ${days} days ago · owner can still renew`,
pendingDelete: false,
isDropping: false,
isExpired: true
};
}
if (expiryInfo && expiryInfo.daysUntil <= 30) {
return {
stateKey: STATUS_KEYS.TAKEN,
headline: 'Registered',
subtext: `Expires in ${expiryInfo.daysUntil} days`,
pendingDelete: false,
isDropping: false,
isExpired: false
};
}
return {
stateKey: STATUS_KEYS.TAKEN,
headline: 'Registered',
subtext: 'Owned and registered',
pendingDelete: false,
isDropping: false,
isExpired: false
};
}
function getStatuses(data) {
return data.status || data.whois?.status || [];
}
function getNoticeIndicators(data) {
const indicators = [];
if (data.notices) {
data.notices.forEach(n => {
if (n.title) indicators.push(n.title);
if (n.description) indicators.push(...(Array.isArray(n.description) ? n.description : [n.description]));
});
}
if (data.description) {
indicators.push(...(Array.isArray(data.description) ? data.description : [data.description]));
}
return indicators;
}
function row(key, value, cls = '') {
return { key, value, cls };
}
function renderRow({ key, value, cls }) {
return `<tr class="${cls}"><td>${key}</td><td>${value}</td></tr>`;
}
function formatDate(iso, utc = false) {
if (!iso) return '';
try {
return new Date(iso).toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: 'numeric', ...(utc ? { timeZone: 'UTC' } : {}) });
} catch { return iso; }
}
function relativeTime(iso) {
try {
const diff = new Date(iso) - Date.now();
const days = Math.round(Math.abs(diff) / 86400000);
const past = diff < 0;
if (days === 0) return 'today';
if (days < 31) return past ? `${days}d ago` : `in ${days}d`;
if (days < 365) {
const months = Math.round(days / 30);
return past ? `${months}mo ago` : `in ${months}mo`;
}
const years = Math.round(days / 365);
return past ? `${years}y ago` : `in ${years}y`;
} catch { return ''; }
}
function getExpiryInfo(isoDate) {
if (!isoDate) return null;
try {
const diff = new Date(isoDate) - Date.now();
const days = Math.ceil(diff / 86400000);
if (days >= 0) return { daysUntil: days, targetDate: isoDate };
return { isExpired: true, daysExpired: Math.abs(days), targetDate: isoDate };
} catch { return null; }
}
function getDomainAge(isoDate) {
try {
const delta = Date.now() - new Date(isoDate);
const years = Math.floor(delta / (86400000 * 365));
const months = Math.floor(delta / (86400000 * 30));
if (years >= 1) return `${years}y old`;
if (months >= 1) return `${months}mo old`;
return 'just registered';
} catch { return null; }
}
function createDomainInfo(params) {
const ascii = params.get('domain') || 'unknown.com';
const originalUrl = params.get('originalUrl') || `https://${ascii}`;
const display = decodePunycode(ascii);
const displayParts = display.split('.');
const displayExt = displayParts.length > 1 ? '.' + displayParts.slice(1).join('.') : (ascii.includes('.') ? '.' + ascii.split('.').slice(1).join('.') : '');
const tld = ascii.split('.').slice(1).join('.') || '';
return {
ascii,
display,
displayName: displayParts[0],
displayExt: displayExt || '',
tld,
originalUrl
};
}
function isValidDomainLabel(label) {
if (!label || label.length > 63) return false;
return /^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?$/.test(label);
}
function decodePunycode(domain) {
try {
return new URL(`https://${domain}`).hostname;
} catch {
return domain;
}
}
function mapElements(ids) {
return ids.reduce((acc, id) => {
acc[id] = document.getElementById(id);
return acc;
}, {});
}
function markInactive() {
if (!sessionActive) return;
sessionActive = false;
clearTimeout(state.copyTimeout);
}
function isActive() {
return sessionActive;
}
function hasRdapCoverage(tld) {
return !!(tld && rdapRegistry.has(tld.toLowerCase()));
}
async function fetchRdapOrg(domain) {
try {
const res = await fetch(`https://rdap.org/domain/${domain}`, { cache: 'no-store' });
if (res.status === 404) {
const text = await res.text();
if (text) {
try {
const parsed = JSON.parse(text);
if (isBlockedOrReserved(parsed)) {
return { type: 'registered', data: parsed };
}
} catch (e) { /* ignore parse errors */ }
}
return { type: 'available' };
}
if (!res.ok) {
return { type: 'error', message: describeRdapFailure(res.status) };
}
const data = await res.json();
return { type: 'registered', data };
} catch (err) {
const aborted = err?.name === 'AbortError';
return {
type: 'error',
message: aborted
? 'Lookup timed out. Please try again.'
: 'Could not reach registry. Please check your connection.'
};
}
}
function isBlockedOrReserved(data) {
const statuses = getStatuses(data).map(s => s.toLowerCase());
const indicators = getNoticeIndicators(data).map(s => s.toLowerCase());
const all = [...statuses, ...indicators];
return all.some(s => s.includes('blocked') || s.includes('reserved') || s.includes('restricted'));
}
function describeRdapFailure(status) {
if (status === 429) return 'Too many requests. Please try again in a moment.';
if (status === 400) return 'Invalid domain name. Please double check the domain name.';
if (status >= 500) return 'Registry is unavailable right now. Please try again later.';
return `Registry returned status ${status}. Please try again.`;
}
async function loadRdapRegistry() {
const cached = await getCachedBootstrap();
if (cached && !isBootstrapStale(cached.fetchedAt)) {
return buildRdapSet(cached.data);
}
const fetched = await fetchBootstrapRegistry();
if (fetched) {
await saveBootstrapCache(fetched);
return buildRdapSet(fetched.data);
}
if (cached) {
console.warn('Using stale RDAP bootstrap cache.');
ui.rdapWarn.textContent = 'Network issue; using cached data.';
ui.rdapWarn.style.display = '';
return buildRdapSet(cached.data);
}
ui.rdapWarn.textContent = 'Unable to load coverage data. Availability checks may be incomplete.';
ui.rdapWarn.style.display = '';
return new Set();
}
function isBootstrapStale(timestamp) {
return !timestamp || (Date.now() - timestamp) > RDAP_BOOTSTRAP_TTL;
}
function getCachedBootstrap() {
if (!chrome?.storage?.local) return Promise.resolve(null);
return new Promise(resolve => {
chrome.storage.local.get([RDAP_BOOTSTRAP_CACHE_KEY], (data) => {
resolve(data[RDAP_BOOTSTRAP_CACHE_KEY] || null);
});
});
}
function saveBootstrapCache(payload) {
if (!chrome?.storage?.local) return Promise.resolve();
return new Promise(resolve => {
chrome.storage.local.set({ [RDAP_BOOTSTRAP_CACHE_KEY]: payload }, () => resolve());
});
}
async function fetchBootstrapRegistry() {
try {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 5000);
const res = await fetch(RDAP_BOOTSTRAP_URL, { cache: 'no-store', signal: controller.signal });
clearTimeout(timeout);
if (!res.ok) throw new Error('Failed to fetch RDAP bootstrap');
const json = await res.json();
return { data: json, fetchedAt: Date.now() };
} catch (err) {
console.error('Unable to fetch RDAP bootstrap:', err);
return null;
}
}
function buildRdapSet(json) {
const set = new Set();
const services = json?.services || [];
for (const entry of services) {
const tlds = entry?.[0] || [];
tlds.forEach(tld => {
if (!tld) return;
set.add(tld.toLowerCase());
});
}
return set;
}
})();