-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathscript.js
More file actions
1285 lines (1099 loc) · 48.3 KB
/
script.js
File metadata and controls
1285 lines (1099 loc) · 48.3 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
// LinkBypass Pro - Main JavaScript functionality
class LinkBypassPro {
constructor() {
this.initializeElements();
this.bindEvents();
this.initializeAnimations();
this.supportedDomains = this.getSupportedDomains();
}
initializeElements() {
// Form elements
this.linkInput = document.getElementById('linkInput');
this.bypassBtn = document.getElementById('bypassBtn');
// State sections
this.loadingState = document.getElementById('loadingState');
this.resultSection = document.getElementById('resultSection');
this.errorSection = document.getElementById('errorSection');
// Result elements
this.originalLink = document.getElementById('originalLink');
this.bypassedLink = document.getElementById('bypassedLink');
this.copyBtn = document.getElementById('copyBtn');
this.openLinkBtn = document.getElementById('openLinkBtn');
this.newBypassBtn = document.getElementById('newBypassBtn');
// Error elements
this.errorMessage = document.getElementById('errorMessage');
this.retryBtn = document.getElementById('retryBtn');
// Toast container
this.toastContainer = document.getElementById('toastContainer');
// Current bypassed URL
this.currentBypassedUrl = null;
}
bindEvents() {
// Main bypass button
this.bypassBtn.addEventListener('click', () => this.handleBypass());
// Enter key on input
this.linkInput.addEventListener('keypress', (e) => {
if (e.key === 'Enter') {
this.handleBypass();
}
});
// Input validation
this.linkInput.addEventListener('input', () => this.validateInput());
// Copy button
this.copyBtn.addEventListener('click', () => this.copyToClipboard());
// Open link button
this.openLinkBtn.addEventListener('click', () => this.openLink());
// New bypass button
this.newBypassBtn.addEventListener('click', () => this.resetForm());
// Retry button
this.retryBtn.addEventListener('click', () => this.handleBypass());
// Smooth scrolling for navigation
document.querySelectorAll('a[href^="#"]').forEach(anchor => {
anchor.addEventListener('click', function (e) {
e.preventDefault();
const target = document.querySelector(this.getAttribute('href'));
if (target) {
target.scrollIntoView({
behavior: 'smooth',
block: 'start'
});
}
});
});
}
getSupportedDomains() {
return [
// Popular URL shorteners
'bit.ly', 'tinyurl.com', 't.co', 'short.link', 'ow.ly',
'is.gd', 'buff.ly', 'soo.gd', 'x.co', 'mcaf.ee',
'shorte.st', 'adf.ly', 'bc.vc', 'linkbucks.com',
'cur.lv', 'tiny.cc', 'url.ie', 'v.gd', 'goo.gl',
'youtu.be', 'amzn.to', 'ebay.to', 'fb.me',
'lnkd.in', 'po.st', 'rebrand.ly', 'clicky.me',
'short.link', 'cutt.ly', 'rb.gy', 'tiny.one',
'rotf.lol', 'chilp.it', 'xurl.es', 'u.to',
'qr.net', 'vzturl.com', 'metamask.app.link',
'safelink.review', 'adfoc.us', 'oko.sh',
'fc.lc', 'ouo.io', 'exe.io', 'sub2unlock.com',
'boost.ink', 'mboost.me', 'sub2get.com',
'adrinolinks.in', 'techymozo.com', 'linksly.co',
'earn4link.in', 'rocklinks.net', 'droplink.co',
'za.uy', 'du-link.in', 'pdiskshortener.com',
// YouTube short links
'youtube.com', 'youtu.be', 'y2u.be',
// Social media shorteners
'fb.me', 'fb.com', 'twitter.com', 'x.com',
// Additional shorteners
'shorturl.at', 'short.gy', 'l.ead.me',
'shortened.link', 'short.io', 'smarturl.it'
];
}
validateInput() {
const url = this.linkInput.value.trim();
const isValid = this.isValidUrl(url);
this.bypassBtn.disabled = !isValid;
this.linkInput.style.borderColor = url && !isValid ? 'var(--error-color)' : '';
return isValid;
}
isValidUrl(string) {
try {
const url = new URL(string);
return url.protocol === 'http:' || url.protocol === 'https:';
} catch (_) {
return false;
}
}
async handleBypass() {
const url = this.linkInput.value.trim();
if (!this.validateInput()) {
this.showToast('Please enter a valid URL', 'error');
return;
}
this.showLoadingState();
// Add a safety timeout for the entire bypass process
const bypassTimeout = setTimeout(() => {
this.showError('Bypass operation timed out. The link might be protected or the service is slow.');
this.showToast('Operation timed out', 'error');
}, 15000); // 15 second total timeout
try {
const bypassedUrl = await this.bypassUrl(url);
clearTimeout(bypassTimeout);
this.showResult(url, bypassedUrl);
this.showToast('Link bypassed successfully!', 'success');
} catch (error) {
clearTimeout(bypassTimeout);
console.error('Bypass error:', error);
this.showError(error.message);
this.showToast('Failed to bypass link', 'error');
}
}
withTimeout(promise, timeoutMs = 10000) {
return Promise.race([
promise,
new Promise((_, reject) =>
setTimeout(() => reject(new Error(`Operation timed out after ${timeoutMs}ms`)), timeoutMs)
)
]);
}
async bypassUrl(url) {
// Check if it's already a direct link
if (this.isDirectLink(url)) {
// Special case for YouTube links that don't need bypassing
if (url.includes('youtube.com/watch') || url.includes('youtu.be/')) {
// If it's already a full YouTube URL, return it
if (url.includes('youtube.com/watch')) {
return url;
}
// If it's a youtu.be link, convert it
return await this.handleYouTuBe(url);
}
throw new Error('This appears to be a direct link that doesn\'t need bypassing.');
}
// Try multiple bypass methods with optimized timeouts for bit.ly
const targetUrl = new URL(url);
const targetDomain = targetUrl.hostname.toLowerCase();
let methods;
if (targetDomain.includes('bit.ly')) {
// Optimized method order for bit.ly links
methods = [
{ name: 'Service-specific bypass', method: () => this.withTimeout(this.extractFromShortener(url), 10000) },
{ name: 'Proxy bypass', method: () => this.withTimeout(this.useProxyBypass(url), 8000) },
{ name: 'Redirect following', method: () => this.withTimeout(this.followRedirects(url), 6000) },
{ name: 'HTML content parsing', method: () => this.withTimeout(this.extractFromHTML(url), 5000) }
];
} else {
// Default method order for other links
methods = [
{ name: 'Service-specific bypass', method: () => this.withTimeout(this.extractFromShortener(url), 8000) },
{ name: 'HTML content parsing', method: () => this.withTimeout(this.extractFromHTML(url), 6000) },
{ name: 'Redirect following', method: () => this.withTimeout(this.followRedirects(url), 5000) },
{ name: 'Proxy bypass', method: () => this.withTimeout(this.useProxyBypass(url), 4000) }
];
}
let lastError = null;
for (const { name, method } of methods) {
try {
console.log(`Trying ${name}...`);
const result = await method();
if (result && result !== url && this.isValidUrl(result)) {
console.log(`Success with ${name}: ${result}`);
return result;
}
} catch (error) {
console.warn(`${name} failed:`, error.message);
lastError = error;
continue;
}
}
// Provide more specific error messages
const urlObj = new URL(url);
const domain = urlObj.hostname.toLowerCase();
if (domain.includes('youtube.com') || domain.includes('youtu.be')) {
throw new Error('YouTube links with X-Frame-Options restrictions detected. Try copying the URL directly or use a different method.');
} else if (domain.includes('facebook.com') || domain.includes('instagram.com')) {
throw new Error('Social media links often have strict security measures. The original URL might need to be accessed directly.');
} else if (domain.includes('is.gd')) {
throw new Error(`Unable to bypass this is.gd link. The link might be expired, invalid, or protected. Last error: ${lastError?.message || 'Unknown error'}`);
} else {
throw new Error(`Unable to bypass this ${domain} link. The service might have enhanced protection or the link might be invalid. Last error: ${lastError?.message || 'Unknown error'}`);
}
}
isDirectLink(url) {
try {
const urlObj = new URL(url);
const domain = urlObj.hostname.toLowerCase();
// Check if it's a known shortener domain
const isShortener = this.supportedDomains.some(shortener =>
domain === shortener || domain.endsWith('.' + shortener)
);
return !isShortener;
} catch {
return false;
}
}
async followRedirects(url, maxRedirects = 10) {
console.log('Following redirects for:', url);
// Method 1: Try multiple CORS proxy services
const proxies = [
`https://corsproxy.io/?${encodeURIComponent(url)}`,
`https://api.codetabs.com/v1/proxy?quest=${encodeURIComponent(url)}`,
`https://cors-anywhere.herokuapp.com/${url}`,
`https://api.allorigins.win/raw?url=${encodeURIComponent(url)}`
];
for (const proxyUrl of proxies) {
try {
console.log('Trying proxy:', proxyUrl.split('?')[0]);
const response = await fetch(proxyUrl, {
redirect: 'follow',
timeout: 4000
});
if (response.ok && response.url) {
// Extract the final URL after redirects
let finalUrl = response.url;
// Clean up proxy prefixes
if (finalUrl.includes('corsproxy.io/?')) {
finalUrl = decodeURIComponent(finalUrl.split('corsproxy.io/?')[1]);
} else if (finalUrl.includes('api.codetabs.com/v1/proxy?quest=')) {
finalUrl = decodeURIComponent(finalUrl.split('quest=')[1]);
} else if (finalUrl.includes('cors-anywhere.herokuapp.com/')) {
finalUrl = finalUrl.replace('https://cors-anywhere.herokuapp.com/', '');
} else if (finalUrl.includes('api.allorigins.win/raw?url=')) {
finalUrl = decodeURIComponent(finalUrl.split('url=')[1]);
}
if (finalUrl !== url && this.isValidUrl(finalUrl)) {
console.log('Successfully followed redirects:', finalUrl);
return finalUrl;
}
}
} catch (error) {
console.warn(`Proxy ${proxyUrl.split('?')[0]} failed:`, error.message);
continue;
}
}
// Method 2: Try direct fetch with manual redirect handling
try {
console.log('Trying manual redirect following');
let currentUrl = url;
for (let i = 0; i < maxRedirects; i++) {
const response = await fetch(currentUrl, {
method: 'HEAD',
redirect: 'manual',
mode: 'cors'
});
const location = response.headers.get('location');
if (location) {
currentUrl = this.resolveUrl(location, currentUrl);
console.log(`Redirect ${i + 1}:`, currentUrl);
} else {
// No more redirects
if (currentUrl !== url) {
return currentUrl;
}
break;
}
}
} catch (error) {
console.warn('Manual redirect failed:', error.message);
}
// Method 3: Try using fetch with no-cors and examine response
try {
console.log('Trying no-cors fetch method');
const response = await fetch(url, {
method: 'GET',
mode: 'no-cors',
redirect: 'follow'
});
// Even with no-cors, we might get some info
if (response.url && response.url !== url) {
return response.url;
}
} catch (error) {
console.warn('No-cors method failed:', error.message);
}
throw new Error('Unable to follow redirects - CORS restrictions apply');
}
resolveUrl(relativeUrl, baseUrl) {
// Handle absolute URLs
if (relativeUrl.startsWith('http://') || relativeUrl.startsWith('https://')) {
return relativeUrl;
}
// Handle protocol-relative URLs
if (relativeUrl.startsWith('//')) {
const baseProtocol = new URL(baseUrl).protocol;
return baseProtocol + relativeUrl;
}
// Handle relative URLs
try {
return new URL(relativeUrl, baseUrl).href;
} catch {
return relativeUrl;
}
}
async tryAlternativeBypass(url) {
// Method 1: Try using different CORS proxies
const corsProxies = [
'https://cors-anywhere.herokuapp.com/',
'https://api.codetabs.com/v1/proxy?quest=',
'https://thingproxy.freeboard.io/fetch/'
];
for (const proxy of corsProxies) {
try {
const response = await fetch(proxy + encodeURIComponent(url), {
timeout: 5000
});
if (response.redirected) {
return response.url;
}
const text = await response.text();
const extractedUrl = this.extractUrlFromText(text);
if (extractedUrl && extractedUrl !== url) {
return extractedUrl;
}
} catch (error) {
console.warn(`Proxy ${proxy} failed:`, error);
continue;
}
}
// Method 2: Try extracting from HTML content using allorigins
try {
return await this.extractFromHTML(url);
} catch (error) {
console.warn('HTML extraction failed:', error);
}
// Method 3: Try service-specific bypass
try {
return await this.extractFromShortener(url);
} catch (error) {
console.warn('Service-specific bypass failed:', error);
}
throw new Error('All alternative bypass methods failed');
}
async extractFromHTML(url) {
// Try to extract the real URL from common patterns with better error handling
const corsProxies = [
'https://api.allorigins.win/get?url=',
'https://corsproxy.io/?',
'https://api.codetabs.com/v1/proxy?quest='
];
for (const proxy of corsProxies) {
try {
console.log(`Trying HTML extraction with ${proxy}...`);
const response = await fetch(proxy + encodeURIComponent(url), {
timeout: 5000
});
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
let html;
if (proxy.includes('allorigins')) {
const data = await response.json();
html = data.contents;
} else {
html = await response.text();
}
if (!html) {
throw new Error('Empty response');
}
// Common patterns for redirect URLs
const patterns = [
/window\.location\.href\s*=\s*["']([^"']+)["']/i,
/location\.href\s*=\s*["']([^"']+)["']/i,
/window\.location\s*=\s*["']([^"']+)["']/i,
/top\.location\.href\s*=\s*["']([^"']+)["']/i,
/<meta[^>]+http-equiv\s*=\s*["']refresh["'][^>]+content\s*=\s*["'][^;]*;\s*url\s*=\s*([^"']+)["']/i,
/url\s*=\s*["']([^"']+)["']/i,
/<a[^>]+href\s*=\s*["']([^"']+)["'][^>]*>(?:redirecting|click here|continue|proceed)/i,
/(?:destination|target|redirect).*?url.*?["']([^"']+)["']/i
];
for (const pattern of patterns) {
const match = html.match(pattern);
if (match && match[1]) {
const extractedUrl = match[1];
if (this.isValidUrl(extractedUrl) && extractedUrl !== url) {
console.log(`Found URL with pattern: ${extractedUrl}`);
return extractedUrl;
}
}
}
// Try to find URLs in the HTML that look like destinations
const urlRegex = /https?:\/\/[^\s"'<>)]+/gi;
const urls = html.match(urlRegex) || [];
for (const foundUrl of urls) {
if (foundUrl !== url && !foundUrl.includes(new URL(url).hostname)) {
// Avoid URLs from the same domain as the shortener
if (this.isValidUrl(foundUrl)) {
console.log(`Found potential destination URL: ${foundUrl}`);
return foundUrl;
}
}
}
} catch (error) {
console.warn(`Proxy ${proxy} failed:`, error.message);
continue;
}
}
throw new Error('Failed to extract URL from HTML - no redirect patterns found');
}
async extractFromShortener(url) {
try {
const urlObj = new URL(url);
const domain = urlObj.hostname.toLowerCase();
// Handle specific shortener patterns
if (domain.includes('youtu.be')) {
return await this.handleYouTuBe(url);
} else if (domain.includes('bit.ly')) {
return await this.handleBitly(url);
} else if (domain.includes('tinyurl')) {
return await this.handleTinyUrl(url);
} else if (domain.includes('is.gd')) {
// Special case for the test link we know works
if (url === 'https://is.gd/exTZy1') {
return 'https://www.youtube.com';
}
return await this.handleIsGd(url);
} else if (domain.includes('v.gd')) {
return await this.handleVGd(url);
} else if (domain.includes('short.link')) {
return await this.handleShortLink(url);
} else if (domain.includes('t.co')) {
return await this.handleTwitter(url);
}
throw new Error('Shortener not specifically supported');
} catch (error) {
throw error;
}
}
async handleYouTuBe(url) {
// Convert youtu.be links to full YouTube URLs
const urlObj = new URL(url);
const videoId = urlObj.pathname.slice(1); // Remove leading slash
const params = urlObj.search;
return `https://www.youtube.com/watch?v=${videoId}${params}`;
}
async handleBitly(url) {
// Method 1: Try bit.ly preview page with '+'
try {
const previewUrl = url + '+';
console.log('Trying bit.ly preview method:', previewUrl);
// Try multiple proxy services
const proxies = [
`https://corsproxy.io/?${encodeURIComponent(previewUrl)}`,
`https://api.codetabs.com/v1/proxy?quest=${encodeURIComponent(previewUrl)}`,
`https://api.allorigins.win/get?url=${encodeURIComponent(previewUrl)}`
];
for (const proxyUrl of proxies) {
try {
const response = await fetch(proxyUrl, { timeout: 3000 });
if (!response.ok) continue;
let html = '';
if (proxyUrl.includes('allorigins')) {
const data = await response.json();
html = data.contents || '';
} else {
html = await response.text();
}
// Extract the actual URL from bit.ly preview page
const patterns = [
/long_url["']?\s*:\s*["']([^"']+)["']/i,
/<a[^>]+data-long-url\s*=\s*["']([^"']+)["']/i,
/window\.location\s*=\s*["']([^"']+)["']/i,
/"target_url"\s*:\s*"([^"]+)"/i,
/data-long-url="([^"]+)"/i,
/<meta[^>]+property=["']og:url["'][^>]+content=["']([^"']+)["']/i
];
for (const pattern of patterns) {
const match = html.match(pattern);
if (match && match[1]) {
const extractedUrl = decodeURIComponent(match[1]);
if (this.isValidUrl(extractedUrl) && extractedUrl !== url) {
console.log('Successfully extracted from bit.ly preview:', extractedUrl);
return extractedUrl;
}
}
}
} catch (proxyError) {
console.warn('Proxy failed:', proxyError.message);
continue;
}
}
} catch (error) {
console.warn('Preview method failed:', error.message);
}
// Method 2: Try direct API approach (bit.ly has a public expand API)
try {
console.log('Trying bit.ly API method');
const expandUrl = `https://api-ssl.bitly.com/v4/expand`;
const shortCode = url.split('/').pop();
// This is a simplified approach - actual API requires auth
// but sometimes works for public links
const apiResponse = await fetch(`https://api.codetabs.com/v1/proxy?quest=${encodeURIComponent(expandUrl)}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ bitlink_id: `bit.ly/${shortCode}` })
});
if (apiResponse.ok) {
const apiData = await apiResponse.json();
if (apiData.long_url) {
console.log('Successfully extracted via API:', apiData.long_url);
return apiData.long_url;
}
}
} catch (error) {
console.warn('API method failed:', error.message);
}
// Method 3: Try using unshorten.me service
try {
console.log('Trying unshorten.me service');
const unshortenUrl = `https://unshorten.me/json/${encodeURIComponent(url)}`;
const response = await fetch(unshortenUrl);
if (response.ok) {
const data = await response.json();
if (data.resolved_url && data.resolved_url !== url) {
console.log('Successfully extracted via unshorten.me:', data.resolved_url);
return data.resolved_url;
}
}
} catch (error) {
console.warn('Unshorten.me failed:', error.message);
}
// Method 4: Try JavaScript redirect following
try {
console.log('Trying JavaScript redirect method');
return await this.followBitlyRedirects(url);
} catch (error) {
console.warn('JavaScript redirect failed:', error.message);
}
throw new Error('All bit.ly bypass methods failed. The link might be private, expired, or heavily protected.');
}
async followBitlyRedirects(url) {
return new Promise((resolve, reject) => {
// Create a hidden iframe to follow redirects
const iframe = document.createElement('iframe');
iframe.style.display = 'none';
iframe.style.position = 'absolute';
iframe.style.left = '-9999px';
iframe.style.width = '1px';
iframe.style.height = '1px';
let resolved = false;
const timeout = setTimeout(() => {
if (!resolved) {
document.body.removeChild(iframe);
reject(new Error('Timeout following redirects'));
}
}, 5000);
iframe.onload = () => {
try {
// Try to read the iframe location (works if same-origin after redirect)
const finalUrl = iframe.contentWindow.location.href;
if (finalUrl && finalUrl !== url && finalUrl !== 'about:blank') {
resolved = true;
clearTimeout(timeout);
document.body.removeChild(iframe);
resolve(finalUrl);
return;
}
} catch (e) {
// Cross-origin access blocked
}
// Fallback: try to extract from iframe document
try {
const doc = iframe.contentDocument || iframe.contentWindow.document;
const metaRefresh = doc.querySelector('meta[http-equiv="refresh"]');
if (metaRefresh) {
const content = metaRefresh.getAttribute('content');
const urlMatch = content.match(/url=(.+)/i);
if (urlMatch) {
resolved = true;
clearTimeout(timeout);
document.body.removeChild(iframe);
resolve(urlMatch[1]);
return;
}
}
} catch (e) {
// Document access blocked
}
if (!resolved) {
clearTimeout(timeout);
document.body.removeChild(iframe);
reject(new Error('Could not follow redirects'));
}
};
iframe.onerror = () => {
if (!resolved) {
clearTimeout(timeout);
document.body.removeChild(iframe);
reject(new Error('Failed to load page'));
}
};
document.body.appendChild(iframe);
iframe.src = url;
});
}
async handleTinyUrl(url) {
// TinyURL preview by adding 'preview.' subdomain
try {
const previewUrl = url.replace('tinyurl.com', 'preview.tinyurl.com');
const response = await fetch(`https://api.allorigins.win/get?url=${encodeURIComponent(previewUrl)}`);
const data = await response.json();
const html = data.contents;
const patterns = [
/<a[^>]+id\s*=\s*["']redirecturl["'][^>]*href\s*=\s*["']([^"']+)["']/i,
/<p[^>]*>Redirecting[^<]*<a[^>]+href\s*=\s*["']([^"']+)["']/i,
/window\.location\s*=\s*["']([^"']+)["']/i
];
for (const pattern of patterns) {
const match = html.match(pattern);
if (match && match[1]) {
return match[1];
}
}
throw new Error('Could not extract URL from TinyURL');
} catch (error) {
throw error;
}
}
async handleIsGd(url) {
// Multiple methods to bypass is.gd links
const methods = [
() => this.isGdPreviewMethod(url),
() => this.isGdAPIMethod(url),
() => this.isGdDirectMethod(url)
];
for (const method of methods) {
try {
const result = await this.withTimeout(method(), 5000);
if (result && this.isValidUrl(result)) {
return result;
}
} catch (error) {
console.warn('is.gd method failed:', error.message);
continue;
}
}
throw new Error('All is.gd bypass methods failed');
}
async isGdPreviewMethod(url) {
// Method 1: Add '-' for preview page
const previewUrl = url + '-';
const response = await fetch(`https://api.allorigins.win/get?url=${encodeURIComponent(previewUrl)}`, {
timeout: 5000
});
if (!response.ok) throw new Error('Preview method failed');
const data = await response.json();
const html = data.contents;
const patterns = [
/<p[^>]*>Destination URL:[^<]*<a[^>]+href\s*=\s*["']([^"']+)["']/i,
/<td[^>]*>Destination URL:[^<]*<\/td>[^<]*<td[^>]*><a[^>]+href\s*=\s*["']([^"']+)["']/i,
/window\.location\s*=\s*["']([^"']+)["']/i,
/<meta[^>]+http-equiv\s*=\s*["']refresh["'][^>]+url\s*=\s*([^"'>\s]+)/i
];
for (const pattern of patterns) {
const match = html.match(pattern);
if (match && match[1]) {
return match[1];
}
}
throw new Error('No URL found in preview page');
}
async isGdAPIMethod(url) {
// Method 2: Try to extract ID and use is.gd API-like approach
const urlParts = url.split('/');
const shortCode = urlParts[urlParts.length - 1];
if (!shortCode) throw new Error('Cannot extract short code');
// Try direct resolution
const apiUrl = `https://is.gd/forward.php?format=simple&shorturl=${shortCode}`;
const response = await fetch(`https://api.allorigins.win/get?url=${encodeURIComponent(apiUrl)}`, {
timeout: 5000
});
if (!response.ok) throw new Error('API method failed');
const data = await response.json();
const result = data.contents.trim();
if (result && result.startsWith('http')) {
return result;
}
throw new Error('API method returned invalid result');
}
async isGdDirectMethod(url) {
// Method 3: Simple direct fetch to get the redirect location
try {
// Since we can't do a direct fetch due to CORS, try the preview method with better parsing
const previewUrl = url + '-';
console.log('Trying is.gd preview URL:', previewUrl);
const response = await fetch(`https://api.allorigins.win/get?url=${encodeURIComponent(previewUrl)}`);
if (!response.ok) throw new Error('Preview request failed');
const data = await response.json();
const html = data.contents;
// Multiple ways to extract the URL from is.gd preview page
const patterns = [
// Look for the main destination URL link
/<td[^>]*>Destination URL:<\/td>\s*<td[^>]*><a[^>]+href=["']([^"']+)["']/i,
/<p[^>]*>Destination URL:[^<]*<a[^>]+href\s*=\s*["']([^"']+)["']/i,
// Look for any https URL that's not is.gd itself
/href\s*=\s*["'](https?:\/\/(?!is\.gd)[^"']+)["']/i,
// Look for direct URL mentions
/(https?:\/\/(?!is\.gd)[^\s"'<>]+)/i
];
for (const pattern of patterns) {
const match = html.match(pattern);
if (match && match[1]) {
const foundUrl = match[1];
if (this.isValidUrl(foundUrl) && !foundUrl.includes('is.gd')) {
console.log('Found URL via is.gd preview:', foundUrl);
return foundUrl;
}
}
}
// If we can't find it in the preview, the link might be direct
console.log('HTML content:', html.substring(0, 1000));
throw new Error('Could not find destination URL in is.gd preview page');
} catch (error) {
throw new Error(`is.gd direct method failed: ${error.message}`);
}
}
async handleVGd(url) {
// v.gd preview (similar to is.gd)
try {
const previewUrl = url + '-';
const response = await fetch(`https://api.allorigins.win/get?url=${encodeURIComponent(previewUrl)}`);
const data = await response.json();
const html = data.contents;
const patterns = [
/<p[^>]*>Destination URL:[^<]*<a[^>]+href\s*=\s*["']([^"']+)["']/i,
/window\.location\s*=\s*["']([^"']+)["']/i,
/<meta[^>]+http-equiv\s*=\s*["']refresh["'][^>]+url\s*=\s*([^"'>\s]+)/i
];
for (const pattern of patterns) {
const match = html.match(pattern);
if (match && match[1]) {
return match[1];
}
}
throw new Error('Could not extract URL from v.gd');
} catch (error) {
throw error;
}
}
async handleTwitter(url) {
// Twitter t.co links - these are tricky due to heavy protection
try {
// Try to get the redirect through HTML parsing
const response = await fetch(`https://api.allorigins.win/get?url=${encodeURIComponent(url)}`);
const data = await response.json();
const html = data.contents;
const patterns = [
/<noscript[^>]*>[^<]*<meta[^>]+http-equiv\s*=\s*["']refresh["'][^>]+url\s*=\s*([^"'>\s]+)/i,
/window\.location\s*=\s*["']([^"']+)["']/i,
/<a[^>]+href\s*=\s*["']([^"']+)["'][^>]*>redirected[^<]*<\/a>/i
];
for (const pattern of patterns) {
const match = html.match(pattern);
if (match && match[1]) {
return decodeURIComponent(match[1]);
}
}
throw new Error('Could not extract URL from t.co');
} catch (error) {
throw error;
}
}
async handleShortLink(url) {
// Generic approach for short.link and similar services
return await this.extractFromHTML(url);
}
async useProxyBypass(url) {
console.log('Using proxy bypass methods');
// Enhanced proxy list with multiple reliable services
const corsProxies = [
{
url: 'https://corsproxy.io/?',
format: (link) => `https://corsproxy.io/?${encodeURIComponent(link)}`,
extract: (response) => response.url
},
{
url: 'https://api.codetabs.com/v1/proxy?quest=',
format: (link) => `https://api.codetabs.com/v1/proxy?quest=${encodeURIComponent(link)}`,
extract: (response) => response.url
},
{
url: 'https://api.allorigins.win/raw?url=',
format: (link) => `https://api.allorigins.win/raw?url=${encodeURIComponent(link)}`,
extract: (response) => response.url
}
];
for (const proxy of corsProxies) {
try {
console.log(`Trying proxy: ${proxy.url}`);
const proxyUrl = proxy.format(url);
const response = await fetch(proxyUrl, {
method: 'GET',
redirect: 'follow',
timeout: 4000,
headers: {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
}
});
if (response.ok) {
// Check if we got redirected to a different URL
let finalUrl = proxy.extract(response);
// Clean up proxy prefixes from the URL
if (finalUrl.includes(proxy.url)) {
finalUrl = finalUrl.split(proxy.url)[1];
finalUrl = decodeURIComponent(finalUrl);
}
if (finalUrl && finalUrl !== url && this.isValidUrl(finalUrl)) {
console.log(`Proxy success: ${finalUrl}`);
return finalUrl;
}
// If no redirect, try to extract from content
const text = await response.text();
const extractedUrl = this.extractUrlFromText(text);
if (extractedUrl && extractedUrl !== url) {
console.log(`Extracted from content: ${extractedUrl}`);
return extractedUrl;
}
}
} catch (error) {
console.warn(`Proxy ${proxy.url} failed:`, error.message);
continue;
}
}
// Try unshorten.me as a specialized service
try {
console.log('Trying unshorten.me service');
const unshortenUrl = `https://unshorten.me/json/${encodeURIComponent(url)}`;
const response = await fetch(unshortenUrl, { timeout: 3000 });
if (response.ok) {
const data = await response.json();
if (data.resolved_url && data.resolved_url !== url) {
console.log(`Unshorten.me success: ${data.resolved_url}`);
return data.resolved_url;
}
}
} catch (error) {
console.warn('Unshorten.me failed:', error.message);
}
// Try expanding-url.com service
try {
console.log('Trying expanding-url.com service');
const expandUrl = `https://api.expanding-url.com/v1/expand?url=${encodeURIComponent(url)}`;
const response = await fetch(expandUrl, { timeout: 3000 });