-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
3130 lines (2885 loc) · 115 KB
/
app.js
File metadata and controls
3130 lines (2885 loc) · 115 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 2026 ToppyMicroServices OÜ
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const form = document.getElementById('quick-check-form');
const report = document.getElementById('report');
const goDeepBtn = document.getElementById('go-deep-btn');
const subdomainScan = document.getElementById('subdomain-scan');
const dnsblCheck = document.getElementById('dnsbl-check');
const consentCheckbox = document.getElementById('consent');
const langSelect = document.getElementById('lang-select');
const langChoiceButtons = Array.from(document.querySelectorAll('[data-lang-choice]'));
const ENTERPRISE_MODE = document.documentElement.dataset.enterprise === 'true';
const resolverSelect = document.getElementById('resolver-select');
const resolverCustom = document.getElementById('resolver-custom');
const resolverCustomWrap = document.getElementById('resolver-custom-wrap');
const resolverNote = document.getElementById('resolver-note');
const resolverError = document.getElementById('resolver-error');
let forceDeep = false;
let lastDiagnosisRun = null;
let languageRerunInProgress = false;
// Go-deep is now the only submit action.
const DOH_PROVIDERS = [
{ id: 'cloudflare', labelKey: 'form.resolver.cloudflare', url: 'https://cloudflare-dns.com/dns-query', kind: 'doh-json' },
{ id: 'quad9', labelKey: 'form.resolver.quad9', url: 'https://dns.quad9.net/dns-query', kind: 'doh-json' },
{ id: 'google', labelKey: 'form.resolver.google', url: 'https://dns.google/resolve', kind: 'doh-json' },
{ id: 'custom', labelKey: 'form.resolver.custom', url: '', kind: 'custom' }
];
const DOH_STORAGE_KEY = 'toppy-doh-resolver';
const DOH_CUSTOM_KEY = 'toppy-doh-custom';
const DEFAULT_DOH_ID = 'cloudflare';
const RESOLVER_MODE = document.documentElement.dataset.resolverMode || 'manual';
let activeDohEndpoint = null;
const DKIM_SELECTOR_CANDIDATES = [
'selector1',
'selector2',
'default',
'google',
's1',
's2',
'k1',
'k2',
'mail',
'dkim',
'protonmail',
'protonmail2'
];
function esc(s) {
return String(s)
.replaceAll('&', '&')
.replaceAll('<', '<')
.replaceAll('>', '>')
.replaceAll('"', '"')
.replaceAll("'", ''');
}
function sanitizeUrl(rawUrl) {
try {
const u = new URL(String(rawUrl ?? ''));
if (u.protocol === 'https:' || u.protocol === 'http:') return u.href;
} catch {
// ignore
}
return '';
}
function sanitizeHtml(html) {
const s = String(html ?? '');
if (window.DOMPurify && typeof window.DOMPurify.sanitize === 'function') {
return window.DOMPurify.sanitize(s, {
ALLOWED_TAGS: ['div', 'span', 'strong', 'p', 'br', 'ul', 'li', 'a', 'h1', 'h2', 'h3', 'section', 'img', 'button'],
ALLOWED_ATTR: ['class', 'style', 'href', 'target', 'rel', 'aria-label', 'aria-live', 'src', 'alt', 'loading', 'referrerpolicy', 'type'],
ALLOW_DATA_ATTR: false
});
}
// Fallback: already escaped everywhere we interpolate; keep as-is.
return s;
}
function setSafeInnerHTML(el, html) {
if (!el) return;
el.innerHTML = sanitizeHtml(html);
}
// --------------------
// i18n (scaffold)
// --------------------
const LANG_KEY = 'toppy-lang';
const SUPPORTED_LANGS = ['ja', 'en', 'vi', 'th', 'km', 'my', 'id', 'et', 'zh', 'ru', 'es', 'de', 'ko'];
let currentLang = 'ja';
const I18N = window.I18N || {};
function t(key) {
const langMap = I18N[currentLang] || I18N.en || I18N.ja;
return langMap[key] || I18N.en?.[key] || I18N.ja[key] || key;
}
function isJa() {
return currentLang === 'ja';
}
const EXTRA_TR = window.EXTRA_TR || {};
function translateExtra(lang, enText, jaText) {
const dict = EXTRA_TR[lang] || I18N[`${lang}_extra`];
const s = String(enText ?? '');
if (dict?.[s]) return dict[s];
// Pattern-based fallbacks for dynamic messages
let m;
if (lang === 'my') {
m = s.match(/^Logo image load: OK \((\d+)x(\d+)\)$/);
if (m) return `လိုဂိုပုံ တင်ယူခြင်း: OK (${m[1]}x${m[2]})`;
m = s.match(/^Logo URL returned HTTP (\d+)$/);
if (m) return `လိုဂို URL မှ HTTP ${m[1]} ပြန်လာသည်`;
m = s.match(/^a= URL returned HTTP (\d+)$/);
if (m) return `a= URL မှ HTTP ${m[1]} ပြန်လာသည်`;
m = s.match(/^SVG viewBox: (.+)$/);
if (m) return `SVG viewBox: ${m[1]}`;
}
if (lang === 'ko') {
m = s.match(/^Logo image load: OK \((\d+)x(\d+)\)$/);
if (m) return `로고 이미지 로드: OK (${m[1]}x${m[2]})`;
m = s.match(/^Logo URL returned HTTP (\d+)$/);
if (m) return `로고 URL에서 HTTP ${m[1]} 응답`;
m = s.match(/^a= URL returned HTTP (\d+)$/);
if (m) return `a= URL에서 HTTP ${m[1]} 응답`;
m = s.match(/^SVG viewBox: (.+)$/);
if (m) return `SVG viewBox: ${m[1]}`;
m = s.match(/^DKIM: (.+)$/);
if (m) return `DKIM: ${m[1]}`;
m = s.match(/^DMARC: p=(.+)$/);
if (m) return `DMARC: p=${m[1]}`;
}
// If we can't translate, fall back to English to avoid hiding meaning.
return String(enText ?? jaText ?? '');
}
function tr(jaText, enText) {
if (isJa()) return jaText;
if (currentLang === 'en') return enText;
return translateExtra(currentLang, enText, jaText);
}
function trf(jaTpl, enTpl, vars) {
const base = tr(jaTpl, enTpl);
return String(base).replace(/\{(\w+)\}/g, (_, k) => {
const v = vars && Object.prototype.hasOwnProperty.call(vars, k) ? vars[k] : '';
return String(v);
});
}
function tFormat(key, vars) {
const base = t(key);
return String(base).replace(/\{(\w+)\}/g, (_, k) => {
const v = vars && Object.prototype.hasOwnProperty.call(vars, k) ? vars[k] : '';
return String(v);
});
}
function statusText(key) {
const k = `status.${key}`;
const v = t(k);
return v === k ? String(key) : v;
}
function detectLang() {
const nav = (navigator.languages && navigator.languages[0]) || navigator.language || '';
const prefix = String(nav || '').slice(0, 2).toLowerCase();
if (SUPPORTED_LANGS.includes(prefix)) return prefix;
return 'ja';
}
function setLang(lang) {
currentLang = SUPPORTED_LANGS.includes(lang) ? lang : 'ja';
try {
localStorage.setItem(LANG_KEY, currentLang);
} catch {
// ignore
}
applyI18n();
// Results are rendered as localized HTML strings at diagnosis-time.
// If the user changes language after running a check, re-run the last diagnosis
// to regenerate findings in the selected language.
if (lastDiagnosisRun && !languageRerunInProgress) {
void rerunLastDiagnosisForLanguage();
}
}
async function rerunLastDiagnosisForLanguage() {
if (!lastDiagnosisRun) return;
if (languageRerunInProgress) return;
languageRerunInProgress = true;
try {
const { domain, options, deepFlag } = lastDiagnosisRun;
setSafeInnerHTML(report, `
<div class="status">${esc(t('report.checking'))}: ${esc(domain)}</div>
<p class="muted m-8-0-0">${esc(t('report.querying'))}${deepFlag ? ` ${esc(t('report.deepEnabled'))}` : ''}</p>
`);
const r = await runDiagnosis(domain, options);
renderResults(r);
lastDiagnosisRun.results = r;
} catch (e) {
// Avoid breaking language switching; keep previous report if rerun fails.
console.warn('[i18n] Failed to rerun diagnosis after language change:', e);
} finally {
languageRerunInProgress = false;
}
}
function validateI18n() {
const base = I18N.en || I18N.ja || {};
const baseKeys = Object.keys(base);
for (const lang of SUPPORTED_LANGS) {
const langMap = I18N[lang] || {};
const missing = baseKeys.filter(k => !(k in langMap));
if (missing.length) console.warn(`[i18n] Missing keys for ${lang}:`, missing);
}
}
function applyI18n() {
const lang = currentLang;
document.documentElement.lang = lang;
if (langSelect) langSelect.value = lang;
if (langChoiceButtons.length) {
langChoiceButtons.forEach(btn => {
const v = btn.getAttribute('data-lang-choice');
btn.classList.toggle('active', v === lang);
});
}
const nodes = document.querySelectorAll('[data-i18n]');
nodes.forEach(el => {
const key = el.getAttribute('data-i18n');
if (!key) return;
el.textContent = t(key);
});
const placeholders = document.querySelectorAll('[data-i18n-placeholder]');
placeholders.forEach(el => {
const key = el.getAttribute('data-i18n-placeholder');
if (!key) return;
el.setAttribute('placeholder', t(key));
});
updateResolverUi();
}
function initI18n() {
try {
const saved = localStorage.getItem(LANG_KEY);
currentLang = (saved && SUPPORTED_LANGS.includes(saved)) ? saved : detectLang();
} catch {
currentLang = detectLang();
}
if (langSelect) {
langSelect.value = currentLang;
langSelect.addEventListener('change', (e) => setLang(e.target.value));
}
if (langChoiceButtons.length) {
langChoiceButtons.forEach(btn => {
btn.addEventListener('click', () => setLang(btn.getAttribute('data-lang-choice')));
});
}
validateI18n();
applyI18n();
initResolverSelection();
}
initI18n();
async function probeHttps(host) {
const url = `https://${host}/`;
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), 6000);
try {
await fetch(url, { method: 'GET', mode: 'no-cors', redirect: 'follow', signal: controller.signal });
return { host, ok: true, evidence: url, note: '応答あり (no-cors のためステータス/ヘッダは未取得)' };
} catch (e) {
return { host, ok: false, evidence: url, error: String(e) };
} finally {
clearTimeout(timer);
}
}
function normalizeDomain(input) {
const d = (input || '').trim().toLowerCase();
if (!/^[a-z0-9.-]+$/.test(d)) return '';
if (!d.includes('.')) return '';
if (d.startsWith('.') || d.endsWith('.')) return '';
return d;
}
function dkimLookupHints(domain) {
const base = `_domainkey.${domain}`;
return [
`dig +short TXT <selector>.${base}`,
`dig +short CNAME <selector>.${base}`
].join('\n');
}
function normalizeDohUrl(raw) {
const trimmed = String(raw || '').trim();
if (!trimmed) return '';
try {
const url = new URL(trimmed);
if (url.protocol !== 'https:') return '';
return url.href;
} catch {
return '';
}
}
function getDohProviderById(id) {
return DOH_PROVIDERS.find(p => p.id === id) || DOH_PROVIDERS[0];
}
function getSelectedDohEndpoint() {
const defaultProvider = getDohProviderById(DEFAULT_DOH_ID);
if (RESOLVER_MODE === 'auto') {
return {
id: defaultProvider.id,
name: t(defaultProvider.labelKey),
url: defaultProvider.url,
kind: defaultProvider.kind
};
}
if (!resolverSelect) return defaultProvider;
const id = resolverSelect.value || DEFAULT_DOH_ID;
if (id === 'custom') {
const url = normalizeDohUrl(resolverCustom ? resolverCustom.value : '');
if (!url) return { error: t('form.resolver.customError') };
return { id: 'custom', name: url, url, kind: 'custom' };
}
const provider = getDohProviderById(id);
return {
id: provider.id,
name: t(provider.labelKey),
url: provider.url,
kind: provider.kind
};
}
function updateResolverUi() {
const defaultProvider = getDohProviderById(DEFAULT_DOH_ID);
if (RESOLVER_MODE === 'auto' || !resolverSelect) {
if (resolverCustomWrap) resolverCustomWrap.classList.add('hidden');
if (resolverNote) resolverNote.textContent = tFormat('form.resolverNotice', { resolver: t(defaultProvider.labelKey) });
if (resolverError) resolverError.textContent = '';
return;
}
const id = resolverSelect.value || DEFAULT_DOH_ID;
if (resolverCustomWrap) resolverCustomWrap.classList.toggle('hidden', id !== 'custom');
const provider = getDohProviderById(id);
const customUrl = normalizeDohUrl(resolverCustom ? resolverCustom.value : '');
const label = id === 'custom' ? (customUrl || t('form.resolver.custom')) : t(provider.labelKey);
if (resolverNote) resolverNote.textContent = tFormat('form.resolverNotice', { resolver: label });
if (resolverError) resolverError.textContent = '';
}
function initResolverSelection() {
if (RESOLVER_MODE === 'auto') {
updateResolverUi();
return;
}
if (!resolverSelect) {
updateResolverUi();
return;
}
const saved = (() => {
try { return localStorage.getItem(DOH_STORAGE_KEY); } catch { return ''; }
})();
const savedCustom = (() => {
try { return localStorage.getItem(DOH_CUSTOM_KEY); } catch { return ''; }
})();
const valid = DOH_PROVIDERS.some(p => p.id === saved) ? saved : DEFAULT_DOH_ID;
resolverSelect.value = valid;
if (resolverCustom) resolverCustom.value = savedCustom || '';
updateResolverUi();
resolverSelect.addEventListener('change', () => {
try { localStorage.setItem(DOH_STORAGE_KEY, resolverSelect.value); } catch { /* ignore */ }
updateResolverUi();
});
if (resolverCustom) {
resolverCustom.addEventListener('input', () => {
try { localStorage.setItem(DOH_CUSTOM_KEY, resolverCustom.value); } catch { /* ignore */ }
updateResolverUi();
});
}
}
async function dohQuery(name, type) {
const errs = [];
const ep = (activeDohEndpoint && activeDohEndpoint.url) ? activeDohEndpoint : getDohProviderById(DEFAULT_DOH_ID);
const url = `${ep.url}?name=${encodeURIComponent(name)}&type=${encodeURIComponent(type)}`;
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), 6500);
try {
const headers = { 'accept': 'application/dns-json' };
const res = await fetch(url, { signal: controller.signal, headers });
if (!res.ok) throw new Error(`${ep.id || ep.name || 'doh'}: HTTP ${res.status}`);
const json = await res.json();
if (!json || typeof json !== 'object') throw new Error(`${ep.id || ep.name || 'doh'}: invalid json`);
return json;
} catch (e) {
errs.push(String(e));
} finally {
clearTimeout(timer);
}
throw new Error(`DoH query failed: ${errs.join(' | ')}`);
}
function extractTXT(json) {
const ans = (json && Array.isArray(json.Answer)) ? json.Answer : [];
const txts = ans
.filter(a => a && (a.type === 16 || a.type === 'TXT') && typeof a.data === 'string')
.map(a => a.data);
return txts.map(t => normalizeTxtData(t));
}
function extractTXTRecords(json) {
const ans = (json && Array.isArray(json.Answer)) ? json.Answer : [];
return ans
.filter(a => a && (a.type === 16 || a.type === 'TXT') && typeof a.data === 'string')
.map(a => ({
data: normalizeTxtData(a.data),
ttl: Number.isFinite(a.TTL) ? a.TTL : null
}));
}
function normalizeTxtData(data) {
const raw = String(data ?? '').trim();
// DoH JSON often returns either:
// - "single string"
// - "part1" "part2" "part3" (multiple quoted segments)
const segs = raw.match(/"([^"\\]*(?:\\.[^"\\]*)*)"/g);
if (segs && segs.length) {
return segs
.map(s => s.replace(/^"|"$/g, ''))
.map(s => s.replace(/\\"/g, '"'))
.join('');
}
if (raw.startsWith('"') && raw.endsWith('"')) return raw.slice(1, -1);
return raw;
}
function extractCNAME(json) {
const ans = (json && Array.isArray(json.Answer)) ? json.Answer : [];
const names = ans
.filter(a => a && (a.type === 5 || a.type === 'CNAME') && typeof a.data === 'string')
.map(a => a.data);
return names.map(n => String(n).trim().replace(/\.$/, ''));
}
function extractCNAMERecords(json) {
const ans = (json && Array.isArray(json.Answer)) ? json.Answer : [];
return ans
.filter(a => a && (a.type === 5 || a.type === 'CNAME') && typeof a.data === 'string')
.map(a => ({
data: String(a.data).trim().replace(/\.$/, ''),
ttl: Number.isFinite(a.TTL) ? a.TTL : null
}));
}
async function resolveCnameChain(name, opts = {}) {
const maxDepth = Number.isFinite(opts.maxDepth) ? opts.maxDepth : 3;
const chain = [];
const seen = new Set([name]);
let current = name;
let loop = false;
let truncated = false;
for (let i = 0; i < maxDepth; i += 1) {
let records = [];
try {
const json = await dohQuery(current, 'CNAME');
records = extractCNAMERecords(json);
} catch (_) {
records = [];
}
if (!records.length) break;
const next = records[0];
chain.push({ from: current, to: next.data, ttl: next.ttl });
if (seen.has(next.data)) {
loop = true;
break;
}
seen.add(next.data);
current = next.data;
}
if (chain.length && !loop && chain.length >= maxDepth) truncated = true;
return {
chain,
target: chain.length ? chain[chain.length - 1].to : '',
loop,
truncated
};
}
function formatCnameChain(chain) {
return (chain || []).map(x => `CNAME ${x.from} -> ${x.to}`).join('\n');
}
function extractA(json) {
const ans = (json && Array.isArray(json.Answer)) ? json.Answer : [];
const recs = ans
.filter(a => a && (a.type === 1 || a.type === 'A') && typeof a.data === 'string')
.map(a => a.data);
return recs.map(x => String(x).trim());
}
function extractAAAA(json) {
const ans = (json && Array.isArray(json.Answer)) ? json.Answer : [];
const recs = ans
.filter(a => a && (a.type === 28 || a.type === 'AAAA') && typeof a.data === 'string')
.map(a => a.data);
return recs.map(x => String(x).trim());
}
function extractMX(json) {
const ans = (json && Array.isArray(json.Answer)) ? json.Answer : [];
const recs = ans
.filter(a => a && (a.type === 15 || a.type === 'MX') && typeof a.data === 'string')
.map(a => a.data);
return recs.map(x => String(x).trim());
}
function extractNS(json) {
const ans = (json && Array.isArray(json.Answer)) ? json.Answer : [];
const recs = ans
.filter(a => a && (a.type === 2 || a.type === 'NS') && typeof a.data === 'string')
.map(a => a.data);
return recs.map(x => String(x).trim().replace(/\.$/, ''));
}
function extractPTR(json) {
const ans = (json && Array.isArray(json.Answer)) ? json.Answer : [];
const recs = ans
.filter(a => a && (a.type === 12 || a.type === 'PTR') && typeof a.data === 'string')
.map(a => a.data);
return recs.map(x => String(x).trim().replace(/\.$/, ''));
}
function extractCAA(json) {
const ans = (json && Array.isArray(json.Answer)) ? json.Answer : [];
const recs = ans
.filter(a => a && (a.type === 257 || a.type === 'CAA') && typeof a.data === 'string')
.map(a => a.data);
return recs.map(x => String(x).trim());
}
function extractDS(json) {
const ans = (json && Array.isArray(json.Answer)) ? json.Answer : [];
const recs = ans
.filter(a => a && (a.type === 43 || a.type === 'DS') && typeof a.data === 'string')
.map(a => a.data);
return recs.map(x => String(x).trim());
}
function extractDNSKEY(json) {
const ans = (json && Array.isArray(json.Answer)) ? json.Answer : [];
const recs = ans
.filter(a => a && (a.type === 48 || a.type === 'DNSKEY') && typeof a.data === 'string')
.map(a => a.data);
return recs.map(x => String(x).trim());
}
// --------------------
// DNSBL quick check (public DNS only)
// --------------------
function dnsblUniq(arr) {
return Array.from(new Set((arr || []).filter(Boolean)));
}
function dnsblReverseIpv4(ip) {
const m = /^\s*(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\s*$/.exec(ip || '');
if (!m) return null;
return `${m[4]}.${m[3]}.${m[2]}.${m[1]}`;
}
async function dnsblResolvePtr(ip) {
const rev = dnsblReverseIpv4(ip);
if (!rev) return [];
try {
const j = await dohQuery(`${rev}.in-addr.arpa`, 'PTR');
return extractPTR(j) || [];
} catch (_) {
return [];
}
}
async function dnsblResolveTxtStrings(name) {
const j = await dohQuery(name, 'TXT');
return extractTXT(j);
}
async function dnsblResolveA(name) {
const j = await dohQuery(name, 'A');
return extractA(j);
}
async function dnsblResolveMxHosts(name) {
const j = await dohQuery(name, 'MX');
const mx = extractMX(j);
return mx
.map(a => {
const parts = String(a || '').trim().split(/\s+/);
return (parts[1] || '').replace(/\.$/, '');
})
.filter(Boolean);
}
function dnsblExtractSpfIpv4Singles(txtStrings) {
const joined = (txtStrings || []).join(' ');
const m = joined.match(/\bv=spf1\b[\s\S]*$/i);
if (!m) return [];
const tokens = m[0].split(/\s+/).map(t => t.trim()).filter(Boolean);
const out = [];
for (const t of tokens) {
if (t.toLowerCase().startsWith('ip4:')) {
const v = t.slice(4);
if (v.includes('/')) continue; // skip CIDR in quick mode
out.push(v);
}
}
return out;
}
async function dnsblLookupIpv4(ip, zone) {
const rev = dnsblReverseIpv4(ip);
if (!rev) return { zone, listed: false, detail: 'invalid-ip' };
const qname = `${rev}.${zone}`;
try {
const j = await dohQuery(qname, 'A');
const ans = (j.Answer || []).filter(a => a.type === 1 || a.type === 'A');
if (ans.length > 0) {
return { zone, listed: true, detail: ans.map(a => a.data).join(', ') };
}
return { zone, listed: false, detail: '' };
} catch (e) {
return { zone, listed: null, detail: String(e && e.message ? e.message : e) };
}
}
async function runDnsblQuick(domain) {
const txt = await dnsblResolveTxtStrings(domain);
const spfIps = dnsblExtractSpfIpv4Singles(txt);
const mxHosts = await dnsblResolveMxHosts(domain);
const mxIps = [];
for (const h of mxHosts) {
try {
mxIps.push(...await dnsblResolveA(h));
} catch (_) { /* ignore */ }
}
const ips = dnsblUniq([...spfIps, ...mxIps]);
const ZONES = ['bl.spamcop.net', 'b.barracudacentral.org', 'psbl.surriel.com'];
const results = [];
for (const ip of ips) {
const ptrs = await dnsblResolvePtr(ip);
const perZone = [];
for (const z of ZONES) perZone.push(await dnsblLookupIpv4(ip, z));
results.push({ ip, ptrs, perZone });
}
return { ips, results };
}
function ensureDnsblContainer(reportEl) {
const id = 'toppy-dnsbl-section';
let el = document.getElementById(id);
if (!el && reportEl) {
el = document.createElement('div');
el.id = id;
el.className = 'card';
reportEl.appendChild(el);
}
return el;
}
function renderDnsbl(el, dnsbl) {
if (!el) return;
const dnsblTitle = t('dnsbl.title');
if (!dnsbl || !dnsbl.ips || dnsbl.ips.length === 0) {
setSafeInnerHTML(el, `
<div class="mini-title">${esc(dnsblTitle)}</div>
<div class="muted">${esc(t('dnsbl.noCandidateIps'))}</div>
`);
return;
}
const rows = dnsbl.results.map(r => {
const listed = r.perZone.filter(z => z.listed === true);
const unknown = r.perZone.filter(z => z.listed === null);
let cls = 'low';
let summary = tr('未掲載の可能性が高い', 'Likely not listed');
if (listed.length > 0) {
cls = 'high';
summary = isJa()
? `掲載の可能性あり(${listed.map(x => esc(x.zone)).join(', ')})`
: `Possibly listed (${listed.map(x => esc(x.zone)).join(', ')})`;
} else if (unknown.length > 0) {
cls = 'med';
summary = isJa()
? `一部照会不可(${unknown.map(x => esc(x.zone)).join(', ')})`
: `Some lookups failed (${unknown.map(x => esc(x.zone)).join(', ')})`;
}
const detail = r.perZone.map(z => {
if (z.listed === true) return `<li><strong>${esc(z.zone)}</strong>: LISTED (${esc(z.detail || 'A')})</li>`;
if (z.listed === false) return `<li><strong>${esc(z.zone)}</strong>: not listed</li>`;
return `<li><strong>${esc(z.zone)}</strong>: unknown (${esc(String(z.detail || ''))})</li>`;
}).join('');
const ptrLine = (r.ptrs && r.ptrs.length)
? `<div class="tiny muted">PTR: ${esc(r.ptrs.join(', '))}</div>`
: '';
return `
<div class="finding ${cls}">
<div class="mini-title">IP: <span class="mono mono-inline">${esc(r.ip)}</span></div>
<div class="muted">${summary}</div>
${ptrLine}
<ul class="list mt-8">${detail}</ul>
</div>
`;
}).join('');
setSafeInnerHTML(el, `
<div class="mini-title">${esc(dnsblTitle)}</div>
<div class="muted">${esc(t('dnsbl.about'))}</div>
${rows}
`);
}
function firstRecordMatching(records, re) {
const rx = (re instanceof RegExp) ? re : new RegExp(String(re), 'i');
return (records || []).find(r => rx.test(String(r))) || '';
}
function firstRecordStartingWith(records, prefix) {
const p = prefix.toLowerCase();
return (records || []).find(r => String(r).toLowerCase().startsWith(p)) || '';
}
function firstTxtRecordStartingWith(records, prefix) {
const p = prefix.toLowerCase();
return (records || []).find(r => r && typeof r.data === 'string' && r.data.toLowerCase().startsWith(p)) || null;
}
function longestTxtSegment(txt) {
const parts = String(txt).split(/\s+/);
let max = 0;
for (const part of parts) {
max = Math.max(max, part.length);
}
return max;
}
function isIPv4(ip) {
return /^((25[0-5]|2[0-4]\d|[01]?\d?\d)\.){3}(25[0-5]|2[0-4]\d|[01]?\d?\d)$/.test(ip);
}
function isIPv6(ip) {
return /^[0-9a-f:]+$/i.test(ip) && ip.includes(':');
}
function toPtrName(ip) {
if (isIPv4(ip)) {
return ip.split('.').reverse().join('.') + '.in-addr.arpa';
}
if (isIPv6(ip)) {
const expanded = ip.toLowerCase();
const hex = expanded.replace(/:/g, '');
if (!/^[0-9a-f]+$/.test(hex)) return '';
return hex.split('').reverse().join('.') + '.ip6.arpa';
}
return '';
}
async function reverseLookup(ip) {
const ptrName = toPtrName(ip);
if (!ptrName) return null;
try {
const json = await dohQuery(ptrName, 'PTR');
const ptrs = extractPTR(json);
return ptrs && ptrs.length ? ptrs[0] : null;
} catch (_) {
return null;
}
}
function parseTagValue(record, key) {
const parts = String(record).split(';').map(x => x.trim()).filter(Boolean);
for (const part of parts) {
const [k, v] = part.split('=');
if (!k || v === undefined) continue;
if (k.trim().toLowerCase() === key.toLowerCase()) return v.trim();
}
return '';
}
function parseDmarcTags(record) {
const out = {};
const parts = String(record).split(';').map(x => x.trim()).filter(Boolean);
for (const part of parts) {
const [k, v] = part.split('=');
if (!k) continue;
const key = k.trim().toLowerCase();
const val = (v === undefined) ? '' : v.trim();
if (key) out[key] = val;
}
return out;
}
function getRuaMailto(domain) {
const cfg = window.RUA_CONFIG || {};
const direct = String(cfg.RUA_MAILTO || '').trim();
const normalizedDomain = normalizeDomain(domain || '');
const applyDomain = (value) => {
if (!normalizedDomain) return value;
return String(value).replace(/YOUR-ID/g, normalizedDomain);
};
if (direct) {
const replaced = applyDomain(direct);
return replaced.toLowerCase().startsWith('mailto:') ? replaced : `mailto:${replaced}`;
}
const email = String(cfg.RUA_EMAIL || '').trim();
if (email) return `mailto:${applyDomain(email)}`;
if (normalizedDomain) return `mailto:${normalizedDomain}@dmarc4all.toppymicros.com`;
return 'mailto:example.com@dmarc4all.toppymicros.com';
}
function mergeRuaValue(existingValue, ruaMailto) {
const base = String(existingValue || '').trim();
if (!base) return ruaMailto;
const items = base.split(',').map(x => x.trim()).filter(Boolean);
const target = ruaMailto.toLowerCase();
const has = items.some(x => x.toLowerCase() === target);
return has ? items.join(',') : items.concat([ruaMailto]).join(',');
}
function updateDmarcRuaRecord(record, ruaMailto) {
const parts = String(record || '').split(';').map(x => x.trim()).filter(Boolean);
if (!parts.length) return '';
let found = false;
const updated = parts.map(part => {
const idx = part.indexOf('=');
if (idx === -1) return part;
const key = part.slice(0, idx).trim();
if (key.toLowerCase() !== 'rua') return part;
found = true;
const value = part.slice(idx + 1).trim();
return `rua=${mergeRuaValue(value, ruaMailto)}`;
});
if (!found) updated.push(`rua=${ruaMailto}`);
return updated.join('; ');
}
function buildDmarcRuaExampleHtml() {
const whyText = t('rua.card.why');
const specLabel = esc(t('rua.link.spec'));
const specUrl = 'rua_service.html';
const summaryHtml = t('rua.example.summary.html');
const noteHtml = t('rua.example.note.html');
const exampleText = esc(t('rua.example.block'));
const specLink = `<a href="${esc(specUrl)}">${specLabel}</a>`;
const linksHtml = `
<div class="tiny muted mt-6">
${specLink}
</div>
`;
const exampleHtml = `
<div class="mini-title mt-10">${summaryHtml}</div>
<div class="mono tiny">${exampleText}</div>
<div class="tiny muted">${noteHtml}</div>
`;
const detailHtml = `<div class="tiny">${esc(whyText)}</div>${linksHtml}${exampleHtml}`;
const detail = detailJaOr(
mkDetail(
'RUA集約レポートの受信設定',
whyText,
'',
{ adviceHtml: `${linksHtml}${exampleHtml}` }
),
detailHtml
);
return mkFindingRich('low', tr('RUA集約レポート(DMARC)', 'RUA aggregate reports (DMARC)'), detail, '', false);
}
function spfHasAllQualifier(spf, q) {
return new RegExp(`\\${q}all(\\s|$)`, 'i').test(spf);
}
function spfEstimateLookupRisk(spf) {
const s = String(spf);
const tokens = s.split(/\s+/).filter(Boolean);
let count = 0;
for (const t of tokens) {
const x = t.toLowerCase();
if (x.startsWith('include:')) count++;
else if (x === 'a' || x.startsWith('a:') || x.startsWith('a/')) count++;
else if (x === 'mx' || x.startsWith('mx:') || x.startsWith('mx/')) count++;
else if (x.startsWith('exists:')) count++;
else if (x.startsWith('redirect=')) count++;
else if (x === 'ptr' || x.startsWith('ptr:')) count++;
}
return count;
}
function spfStripQualifier(token) {
if (!token) return '';
const ch = token[0];
if (ch === '+' || ch === '-' || ch === '~' || ch === '?') return token.slice(1);
return token;
}
function spfParseTokens(spf) {
const tokens = String(spf || '').trim().split(/\s+/).filter(Boolean);
if (!tokens.length) return [];
if (tokens[0].toLowerCase() === 'v=spf1') return tokens.slice(1);
return tokens;
}
function normalizeSpfDomain(name) {
return String(name || '').trim().replace(/\.$/, '').toLowerCase();
}
async function fetchSpfRecord(domain, cache) {
const d = normalizeSpfDomain(domain);
if (!d) return '';
if (cache.has(d)) return cache.get(d);
try {
const json = await dohQuery(d, 'TXT');
const txt = extractTXT(json);
const rec = firstRecordStartingWith(txt, 'v=spf1') || '';
cache.set(d, rec);
return rec;
} catch (_) {
cache.set(d, '');
return '';
}
}
async function buildSpfExpansion(domain, spf, opts = {}) {
const maxDepth = Number.isFinite(opts.maxDepth) ? opts.maxDepth : 4;
const maxNodes = Number.isFinite(opts.maxNodes) ? opts.maxNodes : 24;
const cache = new Map();
const lines = [];
const loops = new Set();
let truncated = false;
let nodes = 0;
async function expandNode(name, record, depth, seen) {
if (nodes >= maxNodes) { truncated = true; return; }
const indent = ' '.repeat(depth);
const lookup = record ? spfEstimateLookupRisk(record) : 0;
const recText = record || t('spf.tree.noRecord');
lines.push(`${indent}${name} (lookup~${lookup}): ${recText}`);
nodes += 1;
if (!record) return;
if (depth >= maxDepth) { truncated = true; return; }
const tokens = spfParseTokens(record);
for (const raw of tokens) {
const term = spfStripQualifier(raw).toLowerCase();
let target = '';
let label = '';
if (term.startsWith('include:')) {
target = term.slice('include:'.length);