-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathworker.js
More file actions
4299 lines (3739 loc) · 132 KB
/
worker.js
File metadata and controls
4299 lines (3739 loc) · 132 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
/**
* SwiftDrop - P2P File Transfer with R2 Fallback
* Cloudflare Worker + Durable Object + WebRTC + R2
*/
export default {
async fetch(request, env) {
const url = new URL(request.url);
// Manual cleanup trigger (protected with API key)
if (url.pathname === '/cleanup' && request.method === 'POST') {
// Require API key for manual cleanup
const apiKey = request.headers.get('X-API-Key');
const expectedKey = env.CLEANUP_API_KEY;
if (!expectedKey) {
return new Response(JSON.stringify({
error: 'Cleanup endpoint disabled (CLEANUP_API_KEY not configured)'
}), {
status: 503,
headers: { 'Content-Type': 'application/json' }
});
}
if (!apiKey || apiKey !== expectedKey) {
return new Response(JSON.stringify({
error: 'Unauthorized - Invalid or missing API key'
}), {
status: 401,
headers: { 'Content-Type': 'application/json' }
});
}
const deleted = await cleanupExpiredFiles(env);
return new Response(JSON.stringify({
success: true,
deletedCount: deleted,
message: `Cleaned up ${deleted} expired files`
}), {
headers: { 'Content-Type': 'application/json' }
});
}
// TURN credentials endpoint — reads secret, never exposes it in source
if (url.pathname === '/api/turn-credentials') {
if (!env.METERED_TURN_CREDENTIALS) {
return new Response(JSON.stringify([]), {
headers: { 'Content-Type': 'application/json' }
});
}
try {
const creds = JSON.parse(env.METERED_TURN_CREDENTIALS);
return new Response(JSON.stringify(creds), {
headers: { 'Content-Type': 'application/json' }
});
} catch {
return new Response(JSON.stringify([]), {
headers: { 'Content-Type': 'application/json' }
});
}
}
// Serve the UI
if (url.pathname === '/' || url.pathname === '/index.html') {
return new Response(getHTML(env), {
headers: {
'Content-Type': 'text/html;charset=UTF-8',
'Access-Control-Allow-Origin': '*'
}
});
}
// PWA manifest (Android Web Share Target needs same-origin manifest + SW)
if (url.pathname === '/manifest.webmanifest' && request.method === 'GET') {
return new Response(getManifest(), {
headers: {
'Content-Type': 'application/manifest+json;charset=UTF-8',
'Cache-Control': 'public, max-age=3600'
}
});
}
// Service worker (must be served from same origin with scope /)
if (url.pathname === '/sw.js' && request.method === 'GET') {
return new Response(getServiceWorker(), {
headers: {
'Content-Type': 'application/javascript;charset=UTF-8',
// Browsers require a short-lived SW response so updates are picked up
'Cache-Control': 'no-cache',
'Service-Worker-Allowed': '/'
}
});
}
// Same-origin icon proxy for PWA install + share target
if (url.pathname.startsWith('/icons/') && request.method === 'GET') {
return serveIcon(url.pathname);
}
// POST /share is only hit when the installed PWA's service worker is NOT yet
// controlling the page (e.g. first launch after install). The SW normally
// intercepts it and stashes the files in Cache Storage. As a graceful
// fallback we redirect to the home page so the user can still send manually.
if (url.pathname === '/share' && request.method === 'POST') {
return Response.redirect(new URL('/?shared=unavailable', request.url).toString(), 303);
}
// WebSocket upgrade for signaling
if (url.pathname === '/ws') {
// Validate Origin to prevent Cross-Site WebSocket Hijacking (CSWSH).
// Browsers always send an Origin header on WebSocket handshakes; a missing
// or unlisted Origin from a browser context indicates a cross-site attempt.
if (!isAllowedWebSocketOrigin(request, env)) {
return new Response('Forbidden: origin not allowed', { status: 403 });
}
const roomCode = url.searchParams.get('room');
if (!roomCode || roomCode.length !== 6) {
return new Response('Invalid room code', { status: 400 });
}
// Get or create Durable Object for this room
const id = env.ROOMS.idFromName(roomCode.toUpperCase());
const room = env.ROOMS.get(id);
// Forward WebSocket connection to the Durable Object
return room.fetch(request);
}
// R2 Fallback: Upload file or URL
if (url.pathname === '/upload' && request.method === 'POST') {
try {
const contentType = request.headers.get('content-type') || '';
// Handle URL upload (JSON)
if (contentType.includes('application/json')) {
const data = await request.json();
const { urlId, url: targetUrl, roomCode, timestamp, turnstileToken } = data;
if (!urlId || !targetUrl || !roomCode) {
return new Response(JSON.stringify({ error: 'Missing required fields' }), {
status: 400,
headers: { 'Content-Type': 'application/json' }
});
}
// Server-side URL protocol validation (whitelist http/https only)
try {
const urlObj = new URL(targetUrl);
if (urlObj.protocol !== 'http:' && urlObj.protocol !== 'https:') {
return new Response(JSON.stringify({
error: 'Invalid URL protocol (only http/https allowed)'
}), {
status: 400,
headers: { 'Content-Type': 'application/json' }
});
}
} catch (e) {
return new Response(JSON.stringify({ error: 'Invalid URL' }), {
status: 400,
headers: { 'Content-Type': 'application/json' }
});
}
// Verify Turnstile token
const isValid = await verifyTurnstile(turnstileToken, env);
if (!isValid) {
return new Response(JSON.stringify({ error: 'Bot verification failed' }), {
status: 403,
headers: { 'Content-Type': 'application/json' }
});
}
// Store URL in R2
await env.FILE_STORAGE.put(urlId, targetUrl, {
httpMetadata: {
contentType: 'text/plain',
},
customMetadata: {
roomCode,
type: 'url',
uploadedAt: timestamp.toString(),
expiresAt: (timestamp + 20 * 60 * 1000).toString() // 20 minutes
}
});
// Analytics: Track URL share via cloud relay
console.log(JSON.stringify({
event: 'url_shared',
method: 'cloud_relay',
roomCode,
timestamp: new Date().toISOString()
}));
return new Response(JSON.stringify({
success: true,
urlId,
redirectUrl: `/url-redirect/${urlId}`
}), {
headers: {
'Content-Type': 'application/json',
...getCorsHeaders(request, env)
}
});
}
// Handle file upload (FormData)
const formData = await request.formData();
const file = formData.get('file');
const roomCode = formData.get('roomCode');
const fileName = formData.get('fileName');
const turnstileToken = formData.get('turnstileToken');
if (!file || !roomCode) {
return new Response(JSON.stringify({ error: 'Missing file or room code' }), {
status: 400,
headers: { 'Content-Type': 'application/json' }
});
}
// Verify Turnstile token
const isValid = await verifyTurnstile(turnstileToken, env);
if (!isValid) {
return new Response(JSON.stringify({ error: 'Bot verification failed' }), {
status: 403,
headers: { 'Content-Type': 'application/json' }
});
}
// Server-side file size validation (20MB limit)
const MAX_FILE_SIZE = 20 * 1024 * 1024; // 20MB
if (file.size > MAX_FILE_SIZE) {
return new Response(JSON.stringify({
error: 'File too large (max 20MB). P2P mode supports larger files when both peers are connected.'
}), {
status: 413, // Payload Too Large
headers: { 'Content-Type': 'application/json' }
});
}
// Generate unique file ID
const fileId = crypto.randomUUID();
const timestamp = Date.now();
// Store file in R2
await env.FILE_STORAGE.put(fileId, file, {
httpMetadata: {
contentType: file.type || 'application/octet-stream',
},
customMetadata: {
roomCode,
fileName: sanitizeFilename(fileName || file.name),
uploadedAt: timestamp.toString(),
expiresAt: (timestamp + 20 * 60 * 1000).toString() // 20 minutes
}
});
// Analytics: Track file upload via cloud relay
console.log(JSON.stringify({
event: 'file_upload',
method: 'cloud_relay',
fileSize: file.size,
fileType: file.type || 'unknown',
roomCode,
timestamp: new Date().toISOString()
}));
return new Response(JSON.stringify({
success: true,
fileId,
downloadUrl: `/download/${fileId}`
}), {
headers: {
'Content-Type': 'application/json',
...getCorsHeaders(request, env)
}
});
} catch (error) {
console.error('Upload error:', error);
return new Response(JSON.stringify({ error: 'Upload failed' }), {
status: 500,
headers: { 'Content-Type': 'application/json' }
});
}
}
// R2 Fallback: URL redirect (for URL sharing fallback)
if (url.pathname.startsWith('/url-redirect/') && request.method === 'GET') {
const urlId = url.pathname.split('/url-redirect/')[1];
if (!urlId) {
return new Response('URL ID required', { status: 400 });
}
try {
const object = await env.FILE_STORAGE.get(urlId);
if (!object) {
return new Response('URL not found or expired', { status: 404 });
}
// Check expiration
const expiresAt = parseInt(object.customMetadata?.expiresAt || '0');
if (expiresAt && Date.now() > expiresAt) {
await env.FILE_STORAGE.delete(urlId);
console.log(`[R2] Deleted expired URL: ${urlId}`);
return new Response('URL expired', { status: 410 });
}
// Read the URL from the object
const redirectUrl = await object.text();
// Analytics: Track URL redirect (successful download)
console.log(JSON.stringify({
event: 'url_redirect',
method: 'cloud_relay',
roomCode: object.customMetadata?.roomCode,
timestamp: new Date().toISOString()
}));
// Delete the URL object after use
try {
await env.FILE_STORAGE.delete(urlId);
console.log(`[R2] Deleted URL after redirect: ${urlId}`);
} catch (deleteError) {
console.error(`[R2] Failed to delete URL ${urlId}:`, deleteError);
}
// Redirect to the URL
return Response.redirect(redirectUrl, 302);
} catch (error) {
console.error('URL redirect error:', error);
return new Response('Redirect failed', { status: 500 });
}
}
// R2 Fallback: Download file
if (url.pathname.startsWith('/download/') && request.method === 'GET') {
const fileId = url.pathname.split('/download/')[1];
if (!fileId) {
return new Response('File ID required', { status: 400 });
}
try {
const object = await env.FILE_STORAGE.get(fileId);
if (!object) {
return new Response('File not found or expired', { status: 404 });
}
// Check expiration
const expiresAt = parseInt(object.customMetadata?.expiresAt || '0');
if (expiresAt && Date.now() > expiresAt) {
await env.FILE_STORAGE.delete(fileId);
console.log(`[R2] Deleted expired file: ${fileId}`);
return new Response('File expired', { status: 410 });
}
const headers = new Headers();
object.writeHttpMetadata(headers);
headers.set('Content-Disposition', `attachment; filename="${sanitizeFilename(object.customMetadata?.fileName || 'download')}"`);
// Add CORS headers for allowed origins
const corsHeaders = getCorsHeaders(request, env);
Object.entries(corsHeaders).forEach(([key, value]) => {
headers.set(key, value);
});
// Read the entire file into array buffer (files are < 20MB so this is safe)
const arrayBuffer = await object.arrayBuffer();
// Analytics: Track file download via cloud relay
console.log(JSON.stringify({
event: 'file_download',
method: 'cloud_relay',
fileSize: arrayBuffer.byteLength,
fileName: object.customMetadata?.fileName || 'unknown',
roomCode: object.customMetadata?.roomCode,
timestamp: new Date().toISOString()
}));
// Now delete the file from R2 (properly awaited)
try {
await env.FILE_STORAGE.delete(fileId);
console.log(`[R2] Deleted file after download: ${fileId}`);
} catch (deleteError) {
console.error(`[R2] Failed to delete file ${fileId}:`, deleteError);
// Continue serving the file even if deletion fails
}
// Return the file content
return new Response(arrayBuffer, { headers });
} catch (error) {
console.error('Download error:', error);
return new Response('Download failed', { status: 500 });
}
}
// CORS preflight
if (request.method === 'OPTIONS') {
return new Response(null, {
headers: getCorsHeaders(request, env)
});
}
return new Response('Not Found', { status: 404 });
},
// Scheduled cleanup (runs every 5 minutes via cron trigger)
async scheduled(event, env, ctx) {
console.log('[Cleanup] Starting scheduled cleanup...');
const deleted = await cleanupExpiredFiles(env);
console.log(`[Cleanup] Finished. Deleted ${deleted} expired files.`);
}
};
/**
* Get CORS headers for allowed origins only
*/
function getCorsHeaders(request, env) {
const origin = request.headers.get('Origin');
const allowedOrigins = (env.ALLOWED_ORIGINS || '').split(',').map(o => o.trim()).filter(Boolean);
// Check if origin is in allowed list
if (origin && allowedOrigins.includes(origin)) {
return {
'Access-Control-Allow-Origin': origin,
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type, X-API-Key'
};
}
// No CORS headers if origin not allowed (will block cross-origin requests)
return {};
}
/**
* Decide whether a WebSocket upgrade request comes from an allowed Origin.
*
* This blocks Cross-Site WebSocket Hijacking (CSWSH): the same-origin policy
* does not apply to WebSocket handshakes, so any site a victim visits could
* otherwise open a WS to our worker and speak as that user.
*
* Rules:
* - If ALLOWED_ORIGINS is configured, the Origin header MUST be present and
* MUST match one of the configured origins.
* - If ALLOWED_ORIGINS is not configured, allow the request but match the
* worker's origin (same-origin) when an Origin header is present. Requests
* without an Origin header (non-browser clients) are allowed in this mode
* to preserve current behavior for local/dev setups.
*/
function isAllowedWebSocketOrigin(request, env) {
const origin = request.headers.get('Origin');
const allowedOrigins = (env.ALLOWED_ORIGINS || '')
.split(',')
.map(o => o.trim())
.filter(Boolean);
if (allowedOrigins.length > 0) {
return Boolean(origin) && allowedOrigins.includes(origin);
}
// No explicit allowlist configured: fall back to same-origin check.
if (!origin) return true;
try {
const requestOrigin = new URL(request.url).origin;
return origin === requestOrigin;
} catch {
return false;
}
}
/**
* Sanitize filename to prevent XSS and path traversal attacks
*/
function sanitizeFilename(filename) {
if (!filename) return 'download';
return filename
.replace(/[/\\]/g, '') // Remove path separators
.replace(/\.\./g, '') // Remove parent directory references
.replace(/[^a-zA-Z0-9._-]/g, '_') // Only allow safe chars
.substring(0, 255); // Limit length
}
/**
* Verify Turnstile token for bot protection
*/
async function verifyTurnstile(token, env) {
if (!token) {
console.log('[Turnstile] No token provided');
return false;
}
if (!env.TURNSTILE_SECRET) {
console.warn('[Turnstile] TURNSTILE_SECRET not configured, skipping verification');
return true; // Allow requests when Turnstile is not configured
}
try {
const response = await fetch('https://challenges.cloudflare.com/turnstile/v0/siteverify', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
secret: env.TURNSTILE_SECRET,
response: token
})
});
const result = await response.json();
console.log('[Turnstile] Verification result:', result.success);
return result.success;
} catch (error) {
console.error('[Turnstile] Verification error:', error);
return false;
}
}
/**
* Cleanup expired files from R2 storage
*/
async function cleanupExpiredFiles(env) {
try {
const now = Date.now();
let deletedCount = 0;
let cursor;
let truncated = true;
// List all objects in R2 bucket with metadata (efficient - no extra get() calls)
do {
const listed = await env.FILE_STORAGE.list({
cursor: cursor,
limit: 1000,
include: ['customMetadata'] // Include metadata in list response
});
// Check each object for expiration
for (const object of listed.objects) {
try {
// Read metadata directly from list() response (no get() needed!)
const expiresAt = parseInt(object.customMetadata?.expiresAt || '0');
if (expiresAt && now > expiresAt) {
// File has expired, delete it
await env.FILE_STORAGE.delete(object.key);
deletedCount++;
console.log(`[Cleanup] Deleted expired file: ${object.key} (expired at ${new Date(expiresAt).toISOString()})`);
}
} catch (err) {
console.error(`[Cleanup] Error processing object ${object.key}:`, err);
}
}
cursor = listed.cursor;
truncated = listed.truncated;
} while (truncated);
return deletedCount;
} catch (error) {
console.error('[Cleanup] Error during cleanup:', error);
return 0;
}
}
/**
* PWA manifest. share_target tells Android to offer SwiftDrop in the system
* share sheet; the matching POST is intercepted by sw.js below.
*/
function getManifest() {
return JSON.stringify({
name: 'SwiftDrop',
short_name: 'SwiftDrop',
description: 'P2P file transfer with cloud fallback',
start_url: '/',
scope: '/',
display: 'standalone',
orientation: 'portrait',
theme_color: '#667eea',
background_color: '#ffffff',
icons: [
{ src: '/icons/icon-192.png', sizes: '192x192', type: 'image/png', purpose: 'any' },
{ src: '/icons/icon-512.png', sizes: '512x512', type: 'image/png', purpose: 'any' },
{ src: '/icons/icon-512.png', sizes: '512x512', type: 'image/png', purpose: 'maskable' }
],
share_target: {
action: '/share',
method: 'POST',
enctype: 'multipart/form-data',
params: {
title: 'title',
text: 'text',
url: 'url',
files: [
{ name: 'files', accept: ['*/*'] }
]
}
}
});
}
/**
* Minimal service worker. Its only job is to intercept the share_target POST
* to /share, stash the incoming files in Cache Storage, and redirect the
* launched window to /?shared=1 which reads them back on load.
*
* Keep this tiny: it purposefully does NOT cache app shell. SwiftDrop is a
* single-page Worker-rendered app and we do not want stale HTML.
*/
function getServiceWorker() {
return `// SwiftDrop service worker — share_target handler only.
const SHARE_CACHE = 'swiftdrop-share-v1';
self.addEventListener('install', (event) => {
self.skipWaiting();
});
self.addEventListener('activate', (event) => {
event.waitUntil(self.clients.claim());
});
self.addEventListener('fetch', (event) => {
const req = event.request;
const url = new URL(req.url);
if (req.method === 'POST' && url.pathname === '/share') {
event.respondWith(handleShare(event));
return;
}
// Everything else: let the network handle it (no app-shell caching).
});
async function handleShare(event) {
const redirect = Response.redirect('/?shared=1', 303);
try {
const formData = await event.request.formData();
const files = formData.getAll('files').filter((f) => f && typeof f === 'object' && 'name' in f && 'size' in f);
const title = formData.get('title') || '';
const text = formData.get('text') || '';
const sharedUrl = formData.get('url') || '';
const cache = await caches.open(SHARE_CACHE);
// Clear any previous shared payload so we never surface stale files.
const keys = await cache.keys();
await Promise.all(keys.map((k) => cache.delete(k)));
const manifest = {
ts: Date.now(),
title: String(title),
text: String(text),
url: String(sharedUrl),
files: []
};
for (let i = 0; i < files.length; i++) {
const f = files[i];
const key = '/__shared__/' + i + '/' + encodeURIComponent(f.name || ('file-' + i));
await cache.put(
new Request(key),
new Response(f, {
headers: {
'Content-Type': f.type || 'application/octet-stream',
'X-Shared-Name': encodeURIComponent(f.name || ('file-' + i))
}
})
);
manifest.files.push({
key,
name: f.name || ('file-' + i),
type: f.type || 'application/octet-stream',
size: typeof f.size === 'number' ? f.size : 0
});
}
await cache.put(
new Request('/__shared__/manifest.json'),
new Response(JSON.stringify(manifest), {
headers: { 'Content-Type': 'application/json' }
})
);
return redirect;
} catch (err) {
return Response.redirect('/?shared=error', 303);
}
}
`;
}
/**
* Serve same-origin icons. Android's share target + install prompt only
* advertise icons listed in the manifest, and Chrome fetches them from the
* manifest's origin. We proxy the existing hosted favicons so we don't have
* to check binary assets into the repo.
*/
async function serveIcon(pathname) {
const map = {
'/icons/icon-192.png': 'https://faviconser.pages.dev/swiftdrop/icon-192.png',
'/icons/icon-512.png': 'https://faviconser.pages.dev/swiftdrop/icon-512.png',
'/icons/apple-touch-icon.png': 'https://faviconser.pages.dev/swiftdrop/apple-touch-icon.png',
'/icons/favicon-16.png': 'https://faviconser.pages.dev/swiftdrop/favicon-16.png',
'/icons/favicon-32.png': 'https://faviconser.pages.dev/swiftdrop/favicon-32.png',
'/icons/favicon.ico': 'https://faviconser.pages.dev/swiftdrop/favicon.ico'
};
const upstream = map[pathname];
if (!upstream) return new Response('Not Found', { status: 404 });
const upstreamRes = await fetch(upstream, {
cf: { cacheTtl: 86400, cacheEverything: true }
});
if (!upstreamRes.ok) {
return new Response('Icon fetch failed', { status: 502 });
}
const headers = new Headers();
const ct = upstreamRes.headers.get('Content-Type');
if (ct) headers.set('Content-Type', ct);
headers.set('Cache-Control', 'public, max-age=86400, immutable');
return new Response(upstreamRes.body, { status: 200, headers });
}
/**
* Durable Object: SignalingRoom
* Manages WebSocket connections and WebRTC signaling for a room.
* Uses the Hibernation API so the DO sleeps between messages and only
* charges wall time while actively processing — not while connections sit idle.
*/
export class SignalingRoom {
constructor(state, env) {
this.state = state;
this.env = env;
}
async fetch(request) {
// Upgrade to WebSocket
const upgradeHeader = request.headers.get('Upgrade');
if (!upgradeHeader || upgradeHeader !== 'websocket') {
return new Response('Expected WebSocket', { status: 426 });
}
const webSocketPair = new WebSocketPair();
const [client, server] = Object.values(webSocketPair);
// Generate unique session ID and attach it to the socket so it survives hibernation
const sessionId = crypto.randomUUID();
server.serializeAttachment({ sessionId, joinedAt: Date.now() });
// Hibernation API: DO can sleep between messages; connections stay open
this.state.acceptWebSocket(server, [sessionId]);
// Cancel any pending eviction alarm — room is active again
await this.state.storage.deleteAlarm();
const allPeers = this.state.getWebSockets();
console.log(`[Room] New peer: ${sessionId}. Total: ${allPeers.length}`);
// Analytics: Track P2P connection attempt
console.log(JSON.stringify({
event: 'peer_connected',
method: 'p2p',
peersInRoom: allPeers.length,
timestamp: new Date().toISOString()
}));
// Send connection confirmation
server.send(JSON.stringify({
type: 'connected',
sessionId,
peersCount: allPeers.length - 1
}));
// Notify other peers
this.broadcast({
type: 'peer-joined',
sessionId,
peersCount: allPeers.length
}, sessionId);
return new Response(null, {
status: 101,
webSocket: client
});
}
// Called by the runtime when a message arrives (DO wakes from hibernation if needed)
webSocketMessage(ws, message) {
try {
const { sessionId } = ws.deserializeAttachment();
const data = JSON.parse(message);
this.handleMessage(sessionId, data, ws);
} catch (error) {
console.error('[Room] Invalid message:', error);
}
}
// Called by the runtime when a connection closes
async webSocketClose(ws, code, reason, wasClean) {
const { sessionId } = ws.deserializeAttachment();
// getWebSockets() still includes the closing socket during this handler
const remaining = this.state.getWebSockets().length - 1;
console.log(`[Room] Peer left: ${sessionId}. Remaining: ${remaining}`);
this.broadcast({
type: 'peer-left',
sessionId,
peersCount: remaining
}, sessionId);
if (remaining === 0) {
await this.state.storage.setAlarm(Date.now() + 5 * 60 * 1000);
console.log('[Room] Room empty. Alarm set for 5 minutes.');
}
}
// Called by the runtime on WebSocket error
webSocketError(ws, error) {
console.error('[Room] WebSocket error:', error);
}
handleMessage(fromSessionId, data, fromWs) {
console.log(`[Room] Message: ${data.type} from ${fromSessionId.substring(0, 8)}`);
switch (data.type) {
case 'offer':
case 'answer':
case 'ice-candidate':
// Route WebRTC signaling messages
if (data.target) {
// Send to specific peer
this.sendTo(data.target, {
...data,
from: fromSessionId
});
} else {
// Broadcast to all other peers
this.broadcast({
...data,
from: fromSessionId
}, fromSessionId);
}
break;
case 'fallback-link':
// Relay fallback download link to other peer
this.broadcast({
type: 'fallback-link',
fileId: data.fileId,
downloadUrl: data.downloadUrl,
fileName: data.fileName,
fileIndex: data.fileIndex,
fileCount: data.fileCount,
from: fromSessionId
}, fromSessionId);
break;
case 'url-fallback':
// Relay URL redirect link to other peer
this.broadcast({
type: 'url-fallback',
urlId: data.urlId,
redirectUrl: data.redirectUrl,
from: fromSessionId
}, fromSessionId);
break;
case 'text-fallback':
// Relay plain text directly to other peer (no R2 needed, text is small)
this.broadcast({
type: 'text-fallback',
content: data.content,
from: fromSessionId
}, fromSessionId);
break;
case 'ping':
// Keep-alive
fromWs.send(JSON.stringify({ type: 'pong' }));
break;
default:
console.log(`[Room] Unknown message type: ${data.type}`);
}
}
sendTo(sessionId, message) {
// Tags let us look up a specific WebSocket directly
const [ws] = this.state.getWebSockets(sessionId);
if (ws) {
try {
ws.send(JSON.stringify(message));
} catch (error) {
console.error('[Room] Send error:', error);
}
}
}
broadcast(message, excludeSessionId = null) {
const payload = JSON.stringify(message);
for (const ws of this.state.getWebSockets()) {
const { sessionId } = ws.deserializeAttachment();
if (sessionId !== excludeSessionId) {
try {
ws.send(payload);
} catch (error) {
console.error('[Room] Broadcast error:', error);
}
}
}
}
// Called when the eviction alarm fires (5 min after last peer left)
async alarm() {
const peers = this.state.getWebSockets();
if (peers.length > 0) {
// A peer rejoined between the alarm being set and firing — nothing to do
console.log(`[Room] Alarm fired but ${peers.length} peer(s) still present. Skipping.`);
return;
}
console.log('[Room] Alarm fired: room confirmed empty. DO will evict naturally.');
}
}
/**
* HTML UI for SwiftDrop
* Preserves existing design, adds WebRTC + R2 fallback logic
*/
function getHTML(env) {
const turnstileSiteKey = env.TURNSTILE_SITE_ID || '';
return `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="theme-color" content="#667eea">
<title>SwiftDrop - P2P File Transfer</title>
<link rel="manifest" href="/manifest.webmanifest">
<link rel="icon" href="https://faviconser.pages.dev/swiftdrop/favicon.ico">
<link rel="icon" type="image/png" sizes="16x16" href="https://faviconser.pages.dev/swiftdrop/favicon-16.png">
<link rel="icon" type="image/png" sizes="32x32" href="https://faviconser.pages.dev/swiftdrop/favicon-32.png">
<link rel="apple-touch-icon" sizes="180x180" href="https://faviconser.pages.dev/swiftdrop/apple-touch-icon.png">
<link rel="icon" type="image/png" sizes="192x192" href="https://faviconser.pages.dev/swiftdrop/icon-192.png">
<link rel="icon" type="image/png" sizes="512x512" href="https://faviconser.pages.dev/swiftdrop/icon-512.png">
<script src="https://cdnjs.cloudflare.com/ajax/libs/qrcodejs/1.0.0/qrcode.min.js"></script>
<script src="https://unpkg.com/feather-icons/dist/feather.min.js"></script>
<script src="https://challenges.cloudflare.com/turnstile/v0/api.js" async defer></script>
<style>
:root {
--bg-gradient-start: #667eea;
--bg-gradient-end: #764ba2;
--container-bg: #ffffff;
--text-primary: #333333;
--text-secondary: #666666;
--text-tertiary: #999999;
--border-color: #dddddd;
--input-bg: #ffffff;
--status-bg: #f0f9ff;
--status-border: #7dd3fc;
--status-connected-bg: #f0fdf4;
--status-connected-border: #86efac;
--status-relay-bg: #dbeafe;
--status-relay-border: #3b82f6;
--status-connecting-bg: #fef3c7;
--status-connecting-border: #fbbf24;
--upload-area-hover: #f8f9ff;
--file-info-bg: #f9fafb;
--shadow-color: rgba(0, 0, 0, 0.3);
}
body.dark-mode {
--bg-gradient-start: #1e1b4b;
--bg-gradient-end: #312e81;
--container-bg: #1f2937;
--text-primary: #f3f4f6;
--text-secondary: #d1d5db;
--text-tertiary: #9ca3af;
--border-color: #374151;
--input-bg: #111827;
--status-bg: #1e3a5f;
--status-border: #3b82f6;
--status-connected-bg: #1e4d2b;
--status-connected-border: #22c55e;
--status-relay-bg: #1e3a5f;
--status-relay-border: #60a5fa;
--status-connecting-bg: #422006;
--status-connecting-border: #fbbf24;
--upload-area-hover: #374151;
--file-info-bg: #374151;
--shadow-color: rgba(0, 0, 0, 0.6);
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
background: linear-gradient(135deg, var(--bg-gradient-start) 0%, var(--bg-gradient-end) 100%);