-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathpeeringdb-fp-consolidated-tools.src.js
More file actions
3655 lines (3224 loc) · 134 KB
/
Copy pathpeeringdb-fp-consolidated-tools.src.js
File metadata and controls
3655 lines (3224 loc) · 134 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
// ==UserScript==
// @name PeeringDB FP - Consolidated Tools
// @namespace https://www.peeringdb.com/
// @version 1.1.32
// @description Consolidated FP userscript for PeeringDB frontend (Net/Org/Fac/IX/Carrier)
// @author <chriztoffer@peeringdb.com>
// @match https://www.peeringdb.com/*
// @match https://beta.peeringdb.com/*
// @exclude https://www.peeringdb.com/cp/*
// @exclude https://beta.peeringdb.com/cp/*
// @icon https://icons.duckduckgo.com/ip2/peeringdb.com.ico
// @grant GM_registerMenuCommand
// @grant GM_unregisterMenuCommand
// @grant GM_notification
// @run-at document-end
// @updateURL https://raw.githubusercontent.com/peeringdb/admincom/master/user.js/peeringdb-fp-consolidated-tools.meta.js
// @downloadURL https://raw.githubusercontent.com/peeringdb/admincom/master/user.js/peeringdb-fp-consolidated-tools.user.js
// @supportURL https://github.com/peeringdb/admincom/issues
// ==/UserScript==
// AI Maintenance Notes (Copilot/Claude):
// - Preserve existing route matching and module boundaries.
// - Prefer minimal, localized edits; avoid broad refactors.
// - Keep grants/connect metadata aligned with actual usage.
// - Preserve shared storage key names and cache namespace compatibility.
// - Validate with syntax checks after edits.
// FP scope:
// - This script owns frontend toolbar and safe read/triage helpers.
// - Do not add RDAP client logic here; RDAP fallback is CP-only.
(function () {
"use strict";
const MODULE_PREFIX = "pdbFpConsolidated";
const SCRIPT_VERSION = "1.1.32";
// RDAP fallback client is intentionally CP-only; FP does not implement RDAP lookups.
// Shared cross-script storage keys — must stay identical across DP, FP, and CP.
const SHARED_USER_AGENT_STORAGE_KEY = "pdbAdmincom.userAgent";
const SESSION_UUID_STORAGE_KEY = "pdbAdmincom.sessionUuid";
// DIAGNOSTICS_STORAGE_KEY is provided by the admincom-common.js include below.
const TRUSTED_DOMAINS_FOR_UA = [
"peeringdb.com",
"*.peeringdb.com",
"api.peeringdb.com",
"127.0.0.1",
"::1",
"localhost",
];
const DUMMY_ORG_ID = 20525;
const FEATURE_FLAGS_STORAGE_KEY = `${MODULE_PREFIX}.featureFlags`;
/**
* Runtime feature flags for FP consolidated behavior.
*
* `debugMode`:
* Enables debug logging gates (`dbg`) when diagnostics localStorage is also enabled.
*
* `moduleDispatch`:
* Master switch for running FP modules in `dispatchModules`.
* Disable to prevent module execution while keeping the script loaded.
*
* `adminOpsMode`:
* Enables Admin Ops mode pathways guarded by `isAdminOpsModeEnabled()`.
* Disable to force Admin Ops features off even if storage toggle is set.
*/
const FEATURE_FLAGS = Object.freeze({
debugMode: false,
moduleDispatch: true,
adminOpsMode: true,
});
const DISABLED_MODULES_STORAGE_KEY = `${MODULE_PREFIX}.disabledModules`;
const ADMIN_OPS_MODE_STORAGE_KEY = `${MODULE_PREFIX}.adminOpsMode`;
const DEFAULT_REQUEST_USER_AGENT = "PeeringDB-Admincom-FP-Consolidated";
const OBSERVER_IDLE_DISCONNECT_MS = 2000;
// How long to wait after the last DOM mutation before re-running init.
// Gives PeeringDB's framework time to settle before we inject our buttons.
const INIT_OBSERVER_DEBOUNCE_MS = 500;
const UI_NEXT_ACTION_ROW_GAP_PX = 8;
const UI_NEXT_ACTION_COLUMN_GAP_PX = 8;
const UI_NEXT_ACTION_MARGIN_TOP_PX = 8;
const API_PAYLOAD_CACHE_STORAGE_PREFIX = `${MODULE_PREFIX}.apiPayloadCache.`;
const API_PAYLOAD_TAB_CACHE_STORAGE_PREFIX = `${MODULE_PREFIX}.apiPayloadTabCache.`;
const API_PAYLOAD_CACHE_TTL_MS = 10 * 60 * 1000;
const API_PAYLOAD_TAB_CACHE_TTL_MS = 2 * 60 * 1000;
const API_PAYLOAD_CACHE_SCHEMA_VERSION = 1;
/**
* Hard-excluded entity IDs for Example Organization records.
* Extend by appending IDs to the relevant Set.
*/
const HARD_EXCLUDED_ENTITY_IDS = {
net: new Set(["32281", "666", "31754", "29032", "14185", "2858", "24084", "10664"]),
ix: new Set(["4095"]),
org: new Set(["25554", "34028", String(DUMMY_ORG_ID), "31503"]),
fac: new Set(["13346", "13399"]),
carrier: new Set(["66"]),
campus: new Set(["25"]),
};
const HARD_EXCLUDED_ENTITY_ALIASES = {
net: "net",
asn: "net",
ix: "ix",
org: "org",
fac: "fac",
carrier: "carrier",
campus: "campus",
};
const displayTypeMap = {
fac: "fac",
facility: "fac",
net: "net",
network: "net",
asn: "net",
org: "org",
organization: "org",
carrier: "carrier",
ix: "ix",
internetexchange: "ix",
campus: "campus",
user: "user",
oauthapplication: "oauth",
};
const activeActionLocks = new Set();
const pendingDomUpdates = new Map();
const lastFetchFailureByUrl = new Map();
const openDropdownActionItems = new Set();
// Registry for document-level delegated click handlers on FP action buttons.
// Keyed by actionId; values are { onClick, href, target }.
// Using delegation instead of direct element listeners means handlers survive when
// PeeringDB's framework replaces the DOM nodes that contain our buttons.
const fpActionDelegateRegistry = new Map();
let dropdownGlobalCloseListenerBound = false;
let isDomUpdateScheduled = false;
let fetchInstrumentationInstalled = false;
let selfCheckHasRun = false;
/**
* Reads JSON feature-flag overrides from localStorage.
* @ai Keep behavior stable and prefer minimal, localized edits.
* @returns {object} Parsed override map, or empty object when unavailable/invalid.
*/
function getFeatureFlagOverrides() {
try {
const raw = String(window.localStorage?.getItem(FEATURE_FLAGS_STORAGE_KEY) || "").trim();
if (!raw) return {};
const parsed = JSON.parse(raw);
return parsed && typeof parsed === "object" ? parsed : {};
} catch (_error) {
return {};
}
}
/**
* Returns resolved feature-flag value using defaults plus localStorage overrides.
* @ai Keep behavior stable and prefer minimal, localized edits.
* @param {string} flagName - Flag key inside FEATURE_FLAGS.
* @returns {boolean} Resolved boolean state.
*/
function isFeatureEnabled(flagName) {
const defaultValue = FEATURE_FLAGS[flagName];
if (typeof defaultValue !== "boolean") return false;
const overrides = getFeatureFlagOverrides();
const overrideValue = overrides[flagName];
if (typeof overrideValue === "boolean") return overrideValue;
return defaultValue;
}
/**
* Returns feature-flag default/override/resolved state.
* @ai Keep behavior stable and prefer minimal, localized edits.
* @param {string} flagName - Flag key inside FEATURE_FLAGS.
* @returns {{ defaultValue: boolean, overrideValue: boolean|null, enabled: boolean }|null} Flag state.
*/
function getFeatureFlagState(flagName) {
const defaultValue = FEATURE_FLAGS[flagName];
if (typeof defaultValue !== "boolean") return null;
const overrides = getFeatureFlagOverrides();
const overrideValue = typeof overrides[flagName] === "boolean" ? overrides[flagName] : null;
const enabled = overrideValue === null ? defaultValue : overrideValue;
return { defaultValue, overrideValue, enabled };
}
/**
* Sets a feature-flag override and removes redundant entries.
* @ai Keep behavior stable and prefer minimal, localized edits.
* @param {string} flagName - Flag key inside FEATURE_FLAGS.
* @param {boolean} enabled - Resolved target state.
*/
function setFeatureFlagEnabled(flagName, enabled) {
const state = getFeatureFlagState(flagName);
if (!state) return;
const overrides = getFeatureFlagOverrides();
if (enabled === state.defaultValue) {
delete overrides[flagName];
} else {
overrides[flagName] = Boolean(enabled);
}
try {
if (Object.keys(overrides).length === 0) {
window.localStorage?.removeItem(FEATURE_FLAGS_STORAGE_KEY);
} else {
window.localStorage?.setItem(FEATURE_FLAGS_STORAGE_KEY, JSON.stringify(overrides));
}
} catch (_error) {
// Ignore localStorage write failures.
}
}
/**
* Removes all feature-flag overrides and restores defaults.
* @ai Keep behavior stable and prefer minimal, localized edits.
*/
function resetFeatureFlagOverrides() {
try {
window.localStorage?.removeItem(FEATURE_FLAGS_STORAGE_KEY);
} catch (_error) {
// Ignore localStorage write failures.
}
}
/* @include admincom-common.js */
// Mirrored request/session helper block:
// Keep this section structurally aligned with the CP consolidated script
// where practical, while preserving FP's tab-scoped session UUID behavior.
/**
* Retrieves the set of disabled module IDs from localStorage.
* Purpose: Allows individual modules to be toggled on/off without code changes.
* Necessity: Provides user-level module control for the modular architecture.
* Supports both JSON array and comma-separated formats for backward compatibility.
* @ai Preserve execution ordering, locks, and route/module boundaries.
*/
function getDisabledModules() {
const raw = String(window.localStorage?.getItem(DISABLED_MODULES_STORAGE_KEY) || "").trim();
if (!raw) return new Set();
try {
const parsed = JSON.parse(raw);
if (Array.isArray(parsed)) {
return new Set(parsed.map((item) => String(item || "").trim()).filter(Boolean));
}
} catch (_error) {
// fallback to comma-separated format
}
return new Set(
raw
.split(",")
.map((item) => String(item || "").trim())
.filter(Boolean),
);
}
/**
* Checks if a module is enabled (not in the disabled set).
* Purpose: Gate-keeper for module execution in dispatchModules().
* Necessity: Implements selective module control without removing code.
* @ai Preserve execution ordering, locks, and route/module boundaries.
*/
function isModuleEnabled(moduleId, disabledModules) {
if (!moduleId) return false;
if (!isFeatureEnabled("moduleDispatch")) return false;
return !disabledModules.has(moduleId);
}
/**
* Returns true when Admin Ops mode is enabled via localStorage.
* @ai Keep behavior stable and prefer minimal, localized edits.
*/
function isAdminOpsModeEnabled() {
if (!isFeatureEnabled("adminOpsMode")) return false;
return window.localStorage?.getItem(ADMIN_OPS_MODE_STORAGE_KEY) === "1";
}
/**
* Shows a user-facing notification with a console fallback.
* @ai Keep behavior stable and prefer minimal, localized edits.
*/
function notifyUser({ title, text, timeout = 2500 }) {
if (typeof GM_notification === "function") {
GM_notification({
title: String(title || "PeeringDB FP"),
text: String(text || ""),
timeout,
});
return;
}
console.info(`[${MODULE_PREFIX}:notify]`, String(title || "PeeringDB FP"), String(text || ""));
}
/**
* Returns storage for domain-scoped persistent values.
* Purpose: Centralize guarded access to localStorage for shared helper logic.
* Necessity: Keeps FP storage access patterns aligned with CP helper structure.
* @ai Preserve shared storage/cache key contracts and TTL behavior.
*/
function getDomainCacheStorage() {
try {
if (window.localStorage) return window.localStorage;
} catch (_error) {
// Ignore; persistent storage may be unavailable.
}
return null;
}
/**
* Returns storage for tab-scoped transient values.
* @ai Preserve shared storage/cache key contracts and TTL behavior.
*/
function getTabSessionStorage() {
try {
if (window.sessionStorage) return window.sessionStorage;
} catch (_error) {
// Ignore; session storage may be unavailable.
}
return null;
}
/**
* Builds a stable cache identity for API payload URLs.
* @ai Preserve normalization/parsing rules and backward-compatible output formats.
* @param {string} url - Absolute or relative API URL.
* @returns {string} Stable cache identity token.
*/
function buildApiPayloadCacheIdentity(url) {
return String(url || "").trim();
}
/**
* Reads a cached API payload entry from a storage object.
* @ai Preserve shared storage/cache key contracts and TTL behavior.
* @param {Storage|null} storage - localStorage or sessionStorage.
* @param {string} storageKey - Namespaced cache key.
* @returns {object|null} Cached payload object or null.
*/
function readCachedApiPayloadEntry(storage, storageKey) {
if (!storage || !storageKey) return null;
try {
const raw = storage.getItem(storageKey);
if (!raw) return null;
const parsed = JSON.parse(raw);
const expiresAt = Number(parsed?.expiresAt || 0);
const schemaVersion = Number(parsed?.v ?? -1);
const payload = parsed?.payload;
if (
!Number.isFinite(expiresAt) ||
expiresAt <= Date.now() ||
schemaVersion !== API_PAYLOAD_CACHE_SCHEMA_VERSION ||
!payload ||
typeof payload !== "object"
) {
storage.removeItem(storageKey);
return null;
}
return payload;
} catch (_error) {
return null;
}
}
/**
* Stores API payload entry into a storage object.
* @ai Preserve shared storage/cache key contracts and TTL behavior.
* @param {Storage|null} storage - localStorage or sessionStorage.
* @param {string} storageKey - Namespaced cache key.
* @param {object} payload - API payload to store.
* @param {number} ttlMs - Cache TTL in milliseconds.
*/
function writeCachedApiPayloadEntry(storage, storageKey, payload, ttlMs) {
if (!storage || !storageKey || !payload || typeof payload !== "object") return;
try {
storage.setItem(
storageKey,
JSON.stringify({
v: API_PAYLOAD_CACHE_SCHEMA_VERSION,
expiresAt: Date.now() + ttlMs,
payload,
}),
);
} catch (_error) {
// Ignore cache write failures.
}
}
/**
* Resolves API JSON payload with strict cache-chain order.
* Order: global cache -> tab cache -> API call -> null fallback.
* @ai Preserve request retries/timeouts/error classification and payload assumptions.
* @param {string} apiUrl - Same-origin API endpoint URL.
* @returns {Promise<object|null>} Resolved payload object or null.
*/
async function resolveApiPayloadWithCacheChain(apiUrl) {
const cacheIdentity = buildApiPayloadCacheIdentity(apiUrl);
if (!cacheIdentity) return null;
const globalStorageKey = `${API_PAYLOAD_CACHE_STORAGE_PREFIX}${cacheIdentity}`;
const tabStorageKey = `${API_PAYLOAD_TAB_CACHE_STORAGE_PREFIX}${cacheIdentity}`;
const globalCachedPayload = readCachedApiPayloadEntry(getDomainCacheStorage(), globalStorageKey);
if (globalCachedPayload) return globalCachedPayload;
const tabCachedPayload = readCachedApiPayloadEntry(getTabSessionStorage(), tabStorageKey);
if (tabCachedPayload) {
writeCachedApiPayloadEntry(
getDomainCacheStorage(),
globalStorageKey,
tabCachedPayload,
API_PAYLOAD_CACHE_TTL_MS,
);
return tabCachedPayload;
}
try {
const response = await fetch(apiUrl, { credentials: "same-origin" });
if (!response.ok) return null;
const raw = await response.json();
const payload = raw?.data?.[0] || raw || null;
if (!payload || typeof payload !== "object") return null;
writeCachedApiPayloadEntry(
getDomainCacheStorage(),
globalStorageKey,
payload,
API_PAYLOAD_CACHE_TTL_MS,
);
writeCachedApiPayloadEntry(
getTabSessionStorage(),
tabStorageKey,
payload,
API_PAYLOAD_TAB_CACHE_TTL_MS,
);
return payload;
} catch (_error) {
return null;
}
}
/**
* Generates or retrieves a persistent session UUID for the browser session.
* Purpose: Provides a unique identifier for correlating requests within a session.
* Necessity: Enables server-side analytics and request tracking without exposing device fingerprint.
* UUID persists across reloads and tabs via shared domain storage.
* @ai Preserve shared storage/cache key contracts and TTL behavior.
*/
function getSessionUuid() {
const sessionKey = SESSION_UUID_STORAGE_KEY;
const storage = getDomainCacheStorage();
let uuid = storage?.getItem(sessionKey);
if (!uuid) {
uuid = `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
if (storage) {
storage.setItem(sessionKey, uuid);
}
}
return uuid;
}
/**
* Computes a stable client fingerprint from browser/device attributes.
* Purpose: Creates a privacy-preserving identifier for requests from untrusted domains.
* Necessity: Balances analytics tracking with user privacy for non-trusted networks.
* Returns a 16-character hex string derived from UA, platform, language, CPU count, memory.
* @ai Keep behavior stable and prefer minimal, localized edits.
*/
function computeClientFingerprint() {
const parts = [
navigator.userAgent,
navigator.platform,
navigator.language,
navigator.hardwareConcurrency || "unknown",
navigator.deviceMemory || "unknown",
].join("|");
let hash = 0;
for (let i = 0; i < parts.length; i++) {
const char = parts.charCodeAt(i);
hash = (hash << 5) - hash + char;
hash = hash & hash;
}
return Math.abs(hash).toString(16).padStart(16, "0").substr(0, 16);
}
/**
* Determines if a domain is in the trusted domain list.
* Purpose: Implement domain-based trust policy for User-Agent header generation.
* Necessity: Distinguishes between trusted (localhost, peeringdb.com) and untrusted domains
* to decide whether to use full browser info or privacy-preserving fingerprint.
* Also normalizes IPv6 URIs with bracket notation ([::1]) for transparent matching.
* @ai Preserve selector contracts and idempotent DOM mutation behavior.
*/
function isDomainTrusted(domain) {
if (!domain) return false;
// Normalize: trim, lowercase, and strip IPv6 URI brackets (e.g., [::1] → ::1)
let domainText = String(domain).trim().toLowerCase();
if (domainText.startsWith("[") && domainText.endsWith("]")) {
domainText = domainText.slice(1, -1);
}
if (!domainText) return false;
for (const pattern of TRUSTED_DOMAINS_FOR_UA) {
const patternLower = pattern.toLowerCase();
if (patternLower === domainText) return true;
if (patternLower.startsWith("*.")) {
const baseDomain = patternLower.slice(2);
if (domainText === baseDomain || domainText.endsWith("." + baseDomain)) {
return true;
}
}
}
return false;
}
/**
* Constructs a User-Agent string based on domain trust level.
* Purpose: Provide contextual information to backend while respecting user privacy.
* Necessity: For trusted domains (development, peeringdb.com), includes browser/platform for debugging;
* for untrusted domains, uses fingerprint only to minimize data exposure.
* Includes session UUID in both cases for request correlation.
* @ai Keep behavior stable and prefer minimal, localized edits.
*/
function buildTrustBasedUserAgent(domain) {
const isTrusted = isDomainTrusted(domain);
const sessionUuid = getSessionUuid();
if (isTrusted) {
const browserInfo = `${navigator.userAgent.split(" ").slice(-1)[0]} ${navigator.platform}`;
return `${DEFAULT_REQUEST_USER_AGENT} (${browserInfo} uuid/${sessionUuid})`;
}
const fingerprint = computeClientFingerprint();
return `${DEFAULT_REQUEST_USER_AGENT} (fingerprint/${fingerprint} uuid/${sessionUuid})`;
}
/**
* Retrieves explicit or auto-computed User-Agent for this session.
* Purpose: Provide flexible UA configuration with fallback to trust-based generation.
* Necessity: Allows manual override via localStorage while auto-computing from domain trust.
* @ai Preserve request retries/timeouts/error classification and payload assumptions.
*/
function getCustomRequestUserAgent() {
const sharedConfigured = String(window.localStorage?.getItem(SHARED_USER_AGENT_STORAGE_KEY) || "").trim();
if (sharedConfigured) return sharedConfigured;
return buildTrustBasedUserAgent(window.location.hostname);
}
/**
* Emits current User-Agent details when diagnostics are enabled.
* @ai Keep behavior stable and prefer minimal, localized edits.
* @returns {boolean} True when emitted.
*/
function logCurrentUserAgentDebug() {
if (!isDebugEnabled()) return false;
const sharedConfigured = String(window.localStorage?.getItem(SHARED_USER_AGENT_STORAGE_KEY) || "").trim();
const host = String(window.location?.hostname || "").trim().toLowerCase();
const source = sharedConfigured ? "shared" : "auto";
const payload = {
source,
trustedDomain: isDomainTrusted(host),
host,
userAgent: getCustomRequestUserAgent(),
};
console.info(`[${MODULE_PREFIX}:ua] effective User-Agent`, payload);
dbg("ua", "effective User-Agent", payload);
return true;
}
/**
* Emits debug diagnostics for outbound requests.
* @ai Preserve request retries/timeouts/error classification and payload assumptions.
*/
function logExternalRequestUserAgent(meta) {
if (!isDebugEnabled()) return;
const url = String(meta?.url || "").trim();
if (!url) return;
let hostname = "";
try {
hostname = new URL(url).hostname;
} catch (_error) {
return;
}
const method = String(meta?.method || "GET").toUpperCase();
const attempt = Number(meta?.attempt || 1);
const retries = Number(meta?.retries || 1);
const mode = String(meta?.mode || "external");
const userAgent = String(meta?.headers?.["User-Agent"] || "").trim() || "<none>";
dbgInfo("ua", "request", {
method,
url,
host: hostname,
mode,
attempt,
retries,
userAgent,
});
}
/**
* Stores the latest fetch failure details by URL for diagnostics.
* @ai Preserve request retries/timeouts/error classification and payload assumptions.
*/
function recordFetchFailure(url, details) {
const key = String(url || "").trim();
if (!key) return;
lastFetchFailureByUrl.set(key, {
...(details || {}),
at: new Date().toISOString(),
});
dbg("fetch", "failure", key, lastFetchFailureByUrl.get(key));
}
/**
* Clears any stored fetch failure details for URL.
* @ai Preserve request retries/timeouts/error classification and payload assumptions.
*/
function clearFetchFailure(url) {
const key = String(url || "").trim();
if (!key) return;
lastFetchFailureByUrl.delete(key);
}
/**
* Constructs HTTP headers for Tampermonkey requests with User-Agent.
* Purpose: Centralize header building for all script-initiated requests.
* Necessity: Ensures consistent User-Agent and other important headers across all API calls.
* @ai Preserve shared storage/cache key contracts and TTL behavior.
*/
function buildTampermonkeyRequestHeaders(baseHeaders = {}) {
const headers = { ...baseHeaders };
const userAgent = getCustomRequestUserAgent();
if (userAgent) {
headers["User-Agent"] = userAgent;
if (!headers["X-PDB-Request-UA"] && !headers["x-pdb-request-ua"]) {
headers["X-PDB-Request-UA"] = userAgent;
}
}
return headers;
}
/**
* Installs lightweight fetch instrumentation for debug diagnostics.
* @ai Preserve request retries/timeouts/error classification and payload assumptions.
*/
function installFetchDiagnostics() {
if (fetchInstrumentationInstalled || typeof window.fetch !== "function") return;
fetchInstrumentationInstalled = true;
const originalFetch = window.fetch.bind(window);
window.fetch = async (...args) => {
const input = args[0];
const init = args[1] || {};
const method = String(init?.method || input?.method || "GET").toUpperCase();
const url = String(input?.url || input || "");
const normalizedHeaders = {};
try {
const sourceHeaders = new Headers(init?.headers || input?.headers || undefined);
sourceHeaders.forEach((value, key) => {
normalizedHeaders[key] = value;
});
} catch (_error) {
// Ignore headers extraction failures.
}
logExternalRequestUserAgent({
url,
method,
headers: normalizedHeaders,
mode: "fetch",
});
try {
const response = await originalFetch(...args);
if (!response.ok) {
recordFetchFailure(url, {
reason: "http",
status: response.status,
statusText: response.statusText,
method,
});
} else {
clearFetchFailure(url);
}
return response;
} catch (error) {
const reason =
error?.name === "AbortError"
? "timeout"
: error instanceof SyntaxError
? "parse"
: error instanceof TypeError
? "error"
: "exception";
recordFetchFailure(url, {
reason,
message: String(error?.message || "fetch failed"),
method,
});
throw error;
}
};
}
/**
* Attempts to acquire a named action lock.
* @ai Preserve execution ordering, locks, and route/module boundaries.
*/
function tryBeginActionLock(lockKey) {
const normalizedKey = String(lockKey || "").trim();
if (!normalizedKey || activeActionLocks.has(normalizedKey)) {
return false;
}
activeActionLocks.add(normalizedKey);
return true;
}
/**
* Releases a previously acquired action lock.
* @ai Preserve execution ordering, locks, and route/module boundaries.
*/
function endActionLock(lockKey) {
const normalizedKey = String(lockKey || "").trim();
if (!normalizedKey) return;
activeActionLocks.delete(normalizedKey);
}
/**
* Runs async action while holding an action lock.
* @ai Preserve execution ordering, locks, and route/module boundaries.
*/
async function withActionLock(lockKey, fn) {
if (!tryBeginActionLock(lockKey)) {
dbg("lock", `action already running: ${lockKey}`);
return false;
}
try {
await fn();
return true;
} finally {
endActionLock(lockKey);
}
}
/**
* Schedules keyed DOM updates and coalesces multiple writes into one frame.
* @ai Preserve selector contracts and idempotent DOM mutation behavior.
*/
function scheduleDomUpdate(key, fn) {
const normalizedKey = String(key || "").trim();
if (!normalizedKey || typeof fn !== "function") return;
pendingDomUpdates.set(normalizedKey, fn);
if (isDomUpdateScheduled) return;
isDomUpdateScheduled = true;
requestAnimationFrame(() => {
isDomUpdateScheduled = false;
const updates = Array.from(pendingDomUpdates.values());
pendingDomUpdates.clear();
updates.forEach((updateFn) => {
try {
updateFn();
} catch (error) {
console.warn(`[${MODULE_PREFIX}] scheduled DOM update failed`, error);
}
});
});
}
/**
* Parses the current URL to extract route context (entity type, ID, page kind).
* Purpose: Provide route info to modules for conditional execution.
* Necessity: Enables modules to match specific pages (e.g., /net/1234) and determine
* whether to run. Used by all modules' match() function.
* @ai Preserve execution ordering, locks, and route/module boundaries.
*/
function getRouteContext() {
const path = window.location.pathname;
// Split and filter empty strings to handle leading/trailing slashes robustly
const parts = path.split("/").filter((p) => p.length > 0);
const type = parts[0] || "";
const id = parts[1] || "";
const isCpEntityChangePage =
parts[0] === "cp" &&
parts[1] === "peeringdb_server" &&
/^\d+$/.test(parts[3] || "") &&
parts[4] === "change";
return {
path,
parts,
type, // e.g., 'net', 'org', 'fac'
id, // e.g., '1234'
isEntityPage: parts.length >= 2 && /^\d+$/.test(id),
isCpEntityChangePage,
cpEntity: isCpEntityChangePage ? parts[2] || "" : "",
cpEntityId: isCpEntityChangePage ? parts[3] || "" : "",
};
}
/**
* Convenience wrapper for querySelector.
* Purpose: Reduce boilerplate for DOM querying throughout the script.
* Necessity: Used extensively for finding form fields and toolbar elements.
* @ai Preserve selector contracts and idempotent DOM mutation behavior.
*/
function qs(selector, root = document) {
if (!root || typeof root.querySelector !== "function") {
return null;
}
return root.querySelector(selector);
}
/**
* Convenience wrapper for querySelectorAll returning an array.
* Purpose: Reduce repeated Array.from(querySelectorAll(...)) patterns in FP modules.
* Necessity: Keeps small DOM iteration helpers aligned with CP utility parity.
* @ai Preserve selector contracts and idempotent DOM mutation behavior.
*/
function qsa(selector, root = document) {
try {
return Array.from(root.querySelectorAll(selector));
} catch (_error) {
return [];
}
}
/**
* Retrieves trimmed innerText from a selected element.
* Purpose: Safe extraction of display text for form fields and data fields.
* Necessity: Provides consistent empty-string fallback vs. throwing on missing elements.
* @ai Keep behavior stable and prefer minimal, localized edits.
*/
function getText(selector, root = document) {
const el = qs(selector, root);
return el ? el.innerText.trim() : "";
}
/**
* Retrieves trimmed value from form input elements (input, select, textarea).
* Purpose: Unified value extraction that handles both .value property and data attributes.
* Necessity: Normalizes form field reading across different input types.
* @ai Keep behavior stable and prefer minimal, localized edits.
*/
function getInputValue(selector, root = document) {
const el = qs(selector, root);
if (!el) return "";
if ("value" in el) {
return String(el.value || "").trim();
}
return String(el.getAttribute("value") || "").trim();
}
/**
* Reads a normalized value from a data-edit field in the current page.
* @ai Keep behavior stable and prefer minimal, localized edits.
*/
function getDataEditValue(name, root = document) {
const el = qs(`[data-edit-name="${name}"]`, root);
if (!el) return "";
return String(el.getAttribute("data-edit-value") || el.textContent || "").trim();
}
/**
* Parses a value into a finite number, returning null when invalid.
* @ai Keep behavior stable and prefer minimal, localized edits.
*/
function toNumeric(value) {
const n = Number(String(value || "").replace(/[^\d.-]/g, ""));
return Number.isFinite(n) ? n : null;
}
/**
* Resolves current entity type/id from route context, with ASN->network fallback.
* @ai Keep behavior stable and prefer minimal, localized edits.
*/
function getCurrentEntityTypeAndId(ctx = null) {
const route = ctx || getRouteContext();
if (!route?.isEntityPage) return { type: "", id: "" };
let type = String(route.type || "").trim().toLowerCase();
let id = String(route.id || "").trim();
if (type === "asn") {
type = "net";
id = String(getDataEditValue("net_id") || id).trim();
}
return { type, id };
}
/**
* Normalizes frontend route entity aliases to canonical hard-exclude keys.
* @ai Preserve normalization/parsing rules and backward-compatible output formats.
*/
function normalizeEntityTypeForHardExclude(type) {
const normalized = String(type || "").trim().toLowerCase();
return HARD_EXCLUDED_ENTITY_ALIASES[normalized] || "";
}
/**
* Returns hard-exclusion metadata for the current entity, or null.
* @ai Keep behavior stable and prefer minimal, localized edits.
*/
function getHardExcludedEntityInfo(ctx = null) {
const { type, id } = getCurrentEntityTypeAndId(ctx);
if (!type || !id) return null;
const canonicalType = normalizeEntityTypeForHardExclude(type);
if (!canonicalType) return null;
const excludedIds = HARD_EXCLUDED_ENTITY_IDS[canonicalType];
if (!excludedIds || !excludedIds.has(String(id).trim())) return null;
return { type: canonicalType, id: String(id).trim() };
}
/**
* Attempts to resolve the parent organization ID from route, fields, or links.
* @ai Keep behavior stable and prefer minimal, localized edits.
*/
function getParentOrgId(ctx = null) {
const route = ctx || getRouteContext();
const { type, id } = getCurrentEntityTypeAndId(route);
if (type === "org" && id) return id;
const direct =
getDataEditValue("org_id") ||
getDataEditValue("org") ||
getInputValue("#id_org") ||
getInputValue("#id_org_id");
if (/^\d+$/.test(String(direct || "").trim())) {
return String(direct).trim();
}
const orgLink = qs('a[href*="/org/"]');
const linkMatch = String(orgLink?.getAttribute("href") || "").match(/\/org\/(\d+)/);
if (linkMatch?.[1]) return linkMatch[1];
const canonical = qs('link[rel="canonical"]')?.getAttribute("href") || "";
const canonicalMatch = String(canonical).match(/\/org\/(\d+)/);
return canonicalMatch?.[1] || "";
}
/**
* Builds the API URL for the current entity context.
* @ai Preserve request retries/timeouts/error classification and payload assumptions.
*/
function getCurrentEntityApiUrl(ctx = null) {
const { type, id } = getCurrentEntityTypeAndId(ctx);
if (!type || !id) return "";
return `${window.location.origin}/api/${type}/${id}`;
}
/**
* Maps frontend entity slugs to CP model names.
* @ai Keep behavior stable and prefer minimal, localized edits.
*/
function getCpEntityNameByType(type) {
const map = {
org: "organization",
net: "network",
fac: "facility",
ix: "internetexchange",
carrier: "carrier",
};
return map[String(type || "").trim().toLowerCase()] || "";
}