-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathindex.js
More file actions
1111 lines (978 loc) · 38.6 KB
/
index.js
File metadata and controls
1111 lines (978 loc) · 38.6 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
// ABOUTME: Fastly Compute entry point for divine-web static site
// ABOUTME: Handles www redirects, external redirects, NIP-05 from KV, subdomain profiles, dynamic OG tags, and SPA fallback
/// <reference types="@fastly/js-compute" />
import { env } from 'fastly:env';
import { KVStore } from 'fastly:kv-store';
import { SecretStore } from 'fastly:secret-store';
import { PublisherServer } from '@fastly/compute-js-static-publish';
import rc from '../static-publish.rc.js';
const publisherServer = PublisherServer.fromStaticPublishRc(rc);
// Funnelcake API URL — edge worker calls origin directly (not via api.divine.video cache
// to avoid Fastly→Fastly loops). Client-side code uses api.divine.video for caching.
const FUNNELCAKE_API_URL = 'https://relay.divine.video';
// Apex domains we serve (used to detect subdomains)
const APEX_DOMAINS = ['dvine.video', 'divine.video'];
// External redirects - always redirect to about.divine.video (Option A)
const EXTERNAL_REDIRECTS = {
'/press': { url: 'https://about.divine.video/press/', status: 301 },
'/news': { url: 'https://about.divine.video/news/', status: 301 },
'/media-resources': { url: 'https://about.divine.video/media-resources/', status: 301 },
'/news/vine-revisited': { url: 'https://about.divine.video/vine-revisited-a-return-to-the-halcyon-days-of-the-internet/', status: 301 },
'/discord': { url: 'https://discord.gg/d6HpB6XnHp', status: 302 },
};
// eslint-disable-next-line no-restricted-globals
addEventListener("fetch", (event) => event.respondWith(handleRequest(event)));
async function handleRequest(event) {
const version = env('FASTLY_SERVICE_VERSION');
console.log('FASTLY_SERVICE_VERSION', version);
const request = event.request;
const url = new URL(request.url);
// Check for original host passed by divine-router
const originalHost = request.headers.get('X-Original-Host');
const hostnameToUse = originalHost || url.hostname;
console.log('Request hostname:', url.hostname, 'original:', originalHost, 'path:', url.pathname);
// 1. Redirect www.* to apex domain (e.g., www.divine.video -> divine.video)
if (hostnameToUse.startsWith('www.')) {
const newUrl = new URL(url);
newUrl.hostname = hostnameToUse.slice(4); // remove 'www.'
return Response.redirect(newUrl.toString(), 301);
}
// 2. Check if this is a subdomain request (e.g., alice.dvine.video)
const subdomain = getSubdomain(hostnameToUse);
if (subdomain) {
// Subdomain .well-known requests
if (url.pathname.startsWith('/.well-known/')) {
if (url.pathname === '/.well-known/nostr.json') {
console.log('Handling subdomain NIP-05 for:', subdomain);
try {
return await handleSubdomainNip05(subdomain);
} catch (err) {
console.error('Subdomain NIP-05 error:', err.message, err.stack);
return jsonResponse({ error: 'Handler error' }, 500);
}
}
// Other .well-known files (apple-app-site-association, assetlinks.json)
console.log('Handling subdomain .well-known file:', url.pathname);
const wkResponse = await publisherServer.serveRequest(request);
// Guard: if publisher returns text/html, it's the SPA fallback, not the real file
if (wkResponse != null && wkResponse.status === 200 && !wkResponse.headers.get('Content-Type')?.includes('text/html')) {
const headers = new Headers(wkResponse.headers);
const contentType = url.pathname.endsWith('.json') || url.pathname.endsWith('/apple-app-site-association')
? 'application/json'
: headers.get('Content-Type') || 'application/octet-stream';
headers.set('Content-Type', contentType);
headers.set('Cache-Control', 'public, max-age=3600');
return new Response(wkResponse.body, { status: 200, headers });
}
return new Response('Not Found', { status: 404 });
}
// Subdomain profile - serve SPA with injected user data
console.log('Handling subdomain profile for:', subdomain);
try {
return await handleSubdomainProfile(subdomain, url, request, hostnameToUse);
} catch (err) {
console.error('Subdomain profile error:', err.message, err.stack);
return new Response('Profile not found', { status: 404 });
}
}
// 3. Handle external redirects
const redirect = EXTERNAL_REDIRECTS[url.pathname];
if (redirect) {
return Response.redirect(redirect.url, redirect.status);
}
// 3b. Handle /@username paths on apex domain (e.g., divine.video/@samuelgrubbs)
const atUsernameMatch = url.pathname.match(/^\/@([a-zA-Z0-9_-]+)$/);
if (atUsernameMatch) {
const username = atUsernameMatch[1].toLowerCase();
console.log('Handling @username profile for:', username);
try {
return await handleSubdomainProfile(username, url, request, hostnameToUse);
} catch (err) {
console.error('@username profile error:', err.message, err.stack);
// Fall through to SPA handler which will render the client-side @username route
}
}
// 4. Handle .well-known requests
if (url.pathname.startsWith('/.well-known/')) {
// 4a. NIP-05 from KV store
if (url.pathname === '/.well-known/nostr.json') {
console.log('Handling NIP-05 request');
try {
return await handleNip05(url);
} catch (err) {
console.error('NIP-05 handler error:', err.message, err.stack);
return jsonResponse({ error: 'Handler error', details: err.message }, 500);
}
}
// 4b. Serve other .well-known files (apple-app-site-association, assetlinks.json)
// These must be served as JSON, not the SPA fallback.
// apple-app-site-association has no file extension, so the static publisher
// cannot detect its content type - we handle it explicitly here.
console.log('Handling .well-known file:', url.pathname);
const wkResponse = await publisherServer.serveRequest(request);
// Guard: if publisher returns text/html, it's the SPA fallback, not the real file
if (wkResponse != null && wkResponse.status === 200 && !wkResponse.headers.get('Content-Type')?.includes('text/html')) {
const headers = new Headers(wkResponse.headers);
// Ensure correct content type for app association files
const contentType = url.pathname.endsWith('.json') || url.pathname.endsWith('/apple-app-site-association')
? 'application/json'
: headers.get('Content-Type') || 'application/octet-stream';
headers.set('Content-Type', contentType);
headers.set('Cache-Control', 'public, max-age=3600');
headers.append('Vary', 'X-Original-Host');
return new Response(wkResponse.body, {
status: 200,
headers,
});
}
// File not found in KV - return 404 instead of SPA fallback
return new Response('Not Found', { status: 404 });
}
// 5. Handle dynamic OG meta tags for video pages (for social media crawlers)
if (url.pathname.startsWith('/video/') && isSocialMediaCrawler(request)) {
console.log('Handling video OG tags for crawler, path:', url.pathname);
const videoId = url.pathname.split('/video/')[1]?.split('?')[0];
console.log('Video ID:', videoId);
if (videoId) {
const ogResponse = await handleVideoOgTags(request, videoId, url);
if (ogResponse) {
return ogResponse;
}
}
console.log('Falling through to SPA handler');
}
// 6. Serve sw.js with no-cache to ensure browsers always get the latest service worker
if (url.pathname === '/sw.js') {
const response = await publisherServer.serveRequest(request);
if (response != null) {
const headers = new Headers(response.headers);
headers.set('Cache-Control', 'no-cache');
headers.set('Vary', 'X-Original-Host');
return new Response(response.body, {
status: response.status,
headers,
});
}
}
// 7. Content report API (creates Zendesk tickets)
if (url.pathname === '/api/report') {
return await handleReport(request);
}
// 7b. Proxy RSS feed requests to the relay backend (serves application/rss+xml)
if (url.pathname.startsWith('/feed/') || url.pathname === '/feed') {
console.log('Proxying RSS feed request to relay:', url.pathname);
const feedUrl = `${FUNNELCAKE_API_URL}${url.pathname}${url.search}`;
return fetch(feedUrl, {
backend: 'funnelcake',
method: request.method,
headers: {
'Accept': request.headers.get('Accept') || '*/*',
'Host': 'relay.divine.video',
},
});
}
// 8. Serve static content with SPA fallback (handled by PublisherServer config)
// Detect pages that benefit from edge-injected feed data
const isApexDomain = APEX_DOMAINS.includes(hostnameToUse);
const isApexLanding = isApexDomain && (url.pathname === '/' || url.pathname === '/index.html');
const discoveryFeedType = isApexDomain ? getDiscoveryFeedType(url.pathname) : null;
const shouldInjectFeed = isApexLanding || discoveryFeedType;
const response = await publisherServer.serveRequest(request);
if (response != null) {
// Add Vary: X-Original-Host so CDN doesn't mix subdomain and apex cached responses
const headers = new Headers(response.headers);
headers.append('Vary', 'X-Original-Host');
// Inject feed data into HTML pages for faster LCP
if (shouldInjectFeed && response.headers.get('Content-Type')?.includes('text/html')) {
try {
let html = await response.text();
const feedType = discoveryFeedType || 'trending';
const feedData = await fetchFeedData(feedType);
if (feedData) {
let injection = `<script>window.__DIVINE_FEED__=${JSON.stringify(feedData)};window.__DIVINE_FEED_TYPE__="${feedType}";</script>`;
const firstVideo = feedData.videos?.[0] || feedData[0];
const firstVideoUrl = firstVideo?.video_url;
const firstThumbnail = firstVideo?.thumbnail;
if (firstVideoUrl) {
injection += `\n<link rel="preload" href="${escapeHtml(firstVideoUrl)}" as="video" type="video/mp4">`;
}
if (firstThumbnail) {
injection += `\n<link rel="preload" href="${escapeHtml(firstThumbnail)}" as="image" fetchpriority="high">`;
}
html = html.replace('</head>', injection + '</head>');
}
return new Response(html, { status: response.status, headers });
} catch (err) {
console.error('Feed injection error:', err.message);
// Fall through to serve unmodified response
}
}
return new Response(response.body, {
status: response.status,
headers,
});
}
return new Response('Not Found', { status: 404 });
}
/**
* Map discovery route to feed type and API params.
*/
function getDiscoveryFeedType(pathname) {
const match = pathname.match(/^\/discovery\/(new|hot|classics|top)$/);
if (!match) return null;
const tab = match[1];
if (tab === 'new') return 'recent';
if (tab === 'hot') return 'trending';
if (tab === 'classics' || tab === 'top') return 'classics';
return null;
}
/**
* Get Funnelcake API URL for a given feed type.
*/
function getFeedApiUrl(feedType) {
switch (feedType) {
case 'trending': return '/api/videos?sort=trending&limit=10';
case 'recent': return '/api/videos?sort=recent&limit=10';
case 'classics': return '/api/videos?sort=loops&limit=10';
default: return '/api/videos?sort=trending&limit=10';
}
}
/**
* Fetch feed data with KV cache (stale-while-revalidate pattern).
* Returns cached data if fresh (<60s), otherwise fetches from Funnelcake API
* and updates the cache for the next request.
*/
async function fetchFeedData(feedType = 'trending') {
const CACHE_KEY = `cache:feed:${feedType}`;
const CACHE_TTL_SECONDS = 60;
const contentStore = new KVStore('divine-web-content');
// 1. Check KV cache
try {
const cached = await contentStore.get(CACHE_KEY);
if (cached) {
const parsed = JSON.parse(await cached.text());
const ageSeconds = Math.floor(Date.now() / 1000) - parsed.timestamp;
if (ageSeconds < CACHE_TTL_SECONDS) {
console.log(`Feed ${feedType} cache hit, age:`, ageSeconds, 's');
return parsed.data;
}
console.log(`Feed ${feedType} cache stale, age:`, ageSeconds, 's');
}
} catch (e) {
console.error('KV cache read error:', e.message);
}
// 2. Fetch from Funnelcake backend
let feedData = null;
try {
const apiPath = getFeedApiUrl(feedType);
const resp = await fetch(`https://relay.divine.video${apiPath}`, {
backend: 'funnelcake',
method: 'GET',
headers: {
'Accept': 'application/json',
'Host': 'relay.divine.video',
},
});
if (resp.ok) {
feedData = await resp.json();
// 3. Update KV cache (fire and forget)
try {
await contentStore.put(CACHE_KEY, JSON.stringify({
data: feedData,
timestamp: Math.floor(Date.now() / 1000),
}));
console.log(`Feed ${feedType} cached in KV`);
} catch (e) {
console.error('KV cache write error:', e.message);
}
} else {
console.error(`Funnelcake ${feedType} fetch failed:`, resp.status);
}
} catch (e) {
console.error(`Funnelcake ${feedType} fetch error:`, e.message);
}
return feedData;
}
/**
* Handle NIP-05 requests by looking up usernames in the divine-names KV store.
* Returns JSON in NIP-05 format: { "names": { "username": "pubkey" }, "relays": { "pubkey": [...] } }
*/
async function handleNip05(url) {
const name = url.searchParams.get('name');
// NIP-05 requires a name parameter
if (!name) {
return jsonResponse({ error: 'Name is required.' }, 400);
}
try {
const store = new KVStore('divine-names');
const entry = await store.get(`user:${name.toLowerCase()}`);
if (!entry) {
// User not found - return empty names object per NIP-05
return jsonResponse({ names: {} });
}
const userData = JSON.parse(await entry.text());
// Build NIP-05 response
const response = {
names: {
[name.toLowerCase()]: userData.pubkey
}
};
// Include relays if available
if (userData.relays && userData.relays.length > 0) {
response.relays = {
[userData.pubkey]: userData.relays
};
}
return jsonResponse(response);
} catch (error) {
console.error('NIP-05 KV error:', error);
return jsonResponse({ error: 'Internal server error' }, 500);
}
}
/**
* Handle content report API requests.
* Ported from functions/api/report.ts (CF Pages Function) for Fastly Compute.
* Creates Zendesk tickets for content reports from the web client.
*/
async function handleReport(req) {
const REPORT_ALLOWED_ORIGINS = [
'https://divine.video',
'https://www.divine.video',
'https://staging.divine.video',
'http://localhost:5173',
'http://localhost:4173',
'http://localhost:8080',
'https://localhost:8080',
];
const PAGES_PREVIEW_RE = /^https:\/\/[a-z0-9-]+\.divine-web-fm8\.pages\.dev$/;
const origin = req.headers.get('Origin') || '';
const isAllowed = REPORT_ALLOWED_ORIGINS.includes(origin) || PAGES_PREVIEW_RE.test(origin);
const corsHeaders = {
'Access-Control-Allow-Origin': isAllowed ? origin : '',
'Access-Control-Allow-Methods': 'POST, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type',
'Access-Control-Max-Age': '86400',
};
// OPTIONS preflight
if (req.method === 'OPTIONS') {
return new Response(null, { status: 204, headers: corsHeaders });
}
// POST only
if (req.method !== 'POST') {
return new Response(JSON.stringify({ error: 'Method not allowed' }), {
status: 405,
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
});
}
// Reject disallowed origins
if (!isAllowed) {
return new Response(JSON.stringify({ error: 'Origin not allowed' }), {
status: 403,
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
});
}
try {
// Read credentials from Fastly Secret Store
const store = new SecretStore('divine_web_secrets');
const [subdomain, email, token] = await Promise.all([
store.get('ZENDESK_SUBDOMAIN').then(s => s?.plaintext()),
store.get('ZENDESK_API_EMAIL').then(s => s?.plaintext()),
store.get('ZENDESK_API_TOKEN').then(s => s?.plaintext()),
]);
if (!subdomain || !email || !token) {
console.error('[report] Missing Zendesk secret store keys');
return new Response(JSON.stringify({ error: 'Server configuration error' }), {
status: 500,
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
});
}
let body;
try {
body = await req.json();
} catch {
return new Response(JSON.stringify({ error: 'Invalid JSON body' }), {
status: 400,
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
});
}
const { contentType, reason, timestamp, eventId, pubkey, reporterPubkey, reporterEmail, details, contentUrl } = body;
// Validate required fields
if (!contentType || !reason || !timestamp) {
return new Response(JSON.stringify({ error: 'Missing required fields: contentType, reason, timestamp' }), {
status: 400,
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
});
}
if (!eventId && !pubkey) {
return new Response(JSON.stringify({ error: 'Must provide either eventId or pubkey' }), {
status: 400,
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
});
}
// Determine requester identity
let requesterEmail;
let isAuthenticated;
if (reporterPubkey) {
requesterEmail = `${reporterPubkey}@reports.divine.video`;
isAuthenticated = true;
} else if (reporterEmail) {
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(reporterEmail)) {
return new Response(JSON.stringify({ error: 'Invalid email format' }), {
status: 400,
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
});
}
requesterEmail = reporterEmail;
isAuthenticated = false;
} else {
return new Response(JSON.stringify({ error: 'Must provide either reporterPubkey or reporterEmail' }), {
status: 400,
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
});
}
// Determine priority based on reason
let priority = 'normal';
if (reason === 'csam' || reason === 'illegal') priority = 'urgent';
else if (reason === 'violence' || reason === 'harassment' || reason === 'impersonation') priority = 'high';
// Build ticket
const subject = `[Content Report] ${reason} - ${contentType}`;
const tags = [
'content-report',
'client-divine-web',
`reason-${reason}`,
`type-${contentType}`,
isAuthenticated ? 'authenticated' : 'anonymous',
];
const bodyParts = [
`**Content Type:** ${contentType}`,
`**Reason:** ${reason}`,
];
if (eventId) bodyParts.push(`**Event ID:** ${eventId}`);
if (pubkey) bodyParts.push(`**Reported Pubkey:** ${pubkey}`);
if (contentUrl) bodyParts.push(`**Content URL:** ${contentUrl}`);
if (details) bodyParts.push(`\n**Details:**\n${details}`);
bodyParts.push(`\n**Reported at:** ${new Date(timestamp).toISOString()}`);
bodyParts.push(`**Reporter:** ${isAuthenticated ? `Authenticated user (${reporterPubkey})` : `Anonymous (${reporterEmail})`}`);
const ticketPayload = {
ticket: {
subject,
comment: { body: bodyParts.join('\n') },
requester: { email: requesterEmail },
tags,
priority,
},
};
// Create Zendesk ticket via named backend.
// The 'zendesk' backend must be created in the Fastly console pointing to
// {subdomain}.zendesk.com. ZENDESK_SUBDOMAIN must match the backend address —
// Fastly pins TLS to the declared backend host.
const zendeskUrl = `https://${subdomain}.zendesk.com/api/v2/tickets.json`;
const authHeader = btoa(`${email}/token:${token}`);
const zendeskResponse = await fetch(zendeskUrl, {
backend: 'zendesk',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Basic ${authHeader}`,
},
body: JSON.stringify(ticketPayload),
});
if (!zendeskResponse.ok) {
const errorText = await zendeskResponse.text();
console.error('[report] Zendesk API error:', zendeskResponse.status, errorText);
return new Response(JSON.stringify({ error: 'Failed to create ticket' }), {
status: 502,
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
});
}
const result = await zendeskResponse.json();
return new Response(JSON.stringify({ success: true, ticketId: result.ticket?.id }), {
status: 201,
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
});
} catch (err) {
console.error('[report] Error:', err);
return new Response(JSON.stringify({ error: 'Internal server error' }), {
status: 500,
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
});
}
}
/**
* Helper to create JSON responses with proper headers
*/
function jsonResponse(data, status = 200) {
return new Response(JSON.stringify(data), {
status,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Cache-Control': 'public, max-age=300', // Cache for 5 minutes
},
});
}
/**
* Extract subdomain from hostname if it's a user subdomain.
* Returns null for apex domains, www, or other reserved subdomains.
*/
function getSubdomain(hostname) {
for (const apex of APEX_DOMAINS) {
if (hostname === apex) {
return null; // Apex domain, no subdomain
}
if (hostname.endsWith('.' + apex)) {
const subdomain = hostname.slice(0, -(apex.length + 1));
// Skip reserved subdomains
if (subdomain === 'www' || subdomain === 'admin' || subdomain === 'api') {
return null;
}
// Skip multi-level subdomains (e.g., names.admin.divine.video)
if (subdomain.includes('.')) {
return null;
}
return subdomain.toLowerCase();
}
}
return null; // Unknown domain
}
/**
* Handle subdomain NIP-05 requests (e.g., alice.dvine.video/.well-known/nostr.json)
* Returns { "names": { "_": "pubkey" }, "relays": { "pubkey": [...] } }
*/
async function handleSubdomainNip05(subdomain) {
const store = new KVStore('divine-names');
const entry = await store.get(`user:${subdomain}`);
if (!entry) {
return new Response('Not Found', { status: 404 });
}
const userData = JSON.parse(await entry.text());
if (userData.status !== 'active') {
return new Response('Not Found', { status: 404 });
}
// Build NIP-05 response with underscore name for subdomain format
const response = {
names: {
'_': userData.pubkey
}
};
// Include relays if available
if (userData.relays && userData.relays.length > 0) {
response.relays = {
[userData.pubkey]: userData.relays
};
}
return jsonResponse(response);
}
/**
* Handle subdomain profile requests (e.g., alice.dvine.video/)
* Serves the SPA directly with injected user data instead of redirecting.
*/
async function handleSubdomainProfile(subdomain, url, request, originalHostname) {
// Check if this is a static asset request - let publisherServer handle it
const assetExtensions = ['.js', '.css', '.png', '.jpg', '.jpeg', '.gif', '.svg', '.ico', '.webp', '.avif', '.woff', '.woff2', '.ttf', '.otf', '.json', '.webmanifest', '.map'];
const isAsset = assetExtensions.some(ext => url.pathname.endsWith(ext)) || url.pathname.startsWith('/assets/');
// Use original hostname if provided (from divine-router), otherwise use url.hostname
const hostnameToUse = originalHostname || url.hostname;
if (isAsset) {
// Serve static assets normally via publisherServer
const response = await publisherServer.serveRequest(request);
if (response != null) {
return response;
}
return new Response('Not Found', { status: 404 });
}
// Look up user data from KV store
const namesStore = new KVStore('divine-names');
const entry = await namesStore.get(`user:${subdomain}`);
if (!entry) {
return new Response('Profile not found', { status: 404 });
}
const userData = JSON.parse(await entry.text());
if (userData.status !== 'active' || !userData.pubkey) {
return new Response('Profile not found', { status: 404 });
}
// Convert hex pubkey to npub for the profile URL
const npub = hexToNpub(userData.pubkey);
// Try to fetch user profile from Funnelcake for richer data
let profileData = null;
try {
const profileResponse = await fetch(`https://relay.divine.video/api/users/${userData.pubkey}`, {
backend: 'funnelcake',
method: 'GET',
headers: {
'Accept': 'application/json',
'Host': 'relay.divine.video',
},
});
if (profileResponse.ok) {
profileData = await profileResponse.json();
}
} catch (e) {
console.error('Failed to fetch profile from Funnelcake:', e.message);
}
// Find the apex domain from the current hostname (use hostnameToUse for subdomain requests)
let apexDomain = 'dvine.video';
for (const apex of APEX_DOMAINS) {
if (hostnameToUse.endsWith(apex)) {
apexDomain = apex;
break;
}
}
// Read index.html directly from KV store
// (PublisherServer.serveRequest returns empty body for synthetic requests)
let html;
try {
const contentStore = new KVStore('divine-web-content');
// Read the file index: publishId_index_collectionName
const indexEntry = await contentStore.get('default_index_live');
if (!indexEntry) {
throw new Error('Content index not found in KV');
}
const kvIndex = JSON.parse(await indexEntry.text());
// Find index.html in the index and get its content hash
const htmlAsset = kvIndex['/index.html'];
if (!htmlAsset) {
throw new Error('index.html not in content index');
}
// Asset format: { key: "sha256:<hash>", size, contentType, variants }
// KV content key format: default_files_sha256_<hash>
const assetKey = htmlAsset.key; // e.g. "sha256:abc123..."
const sha256 = assetKey.replace('sha256:', '');
const contentKey = `default_files_sha256_${sha256}`;
console.log('Reading index.html from KV, sha256:', sha256.slice(0, 16) + '...');
const contentEntry = await contentStore.get(contentKey);
if (!contentEntry) {
throw new Error(`Content not found: ${contentKey}`);
}
html = await contentEntry.text();
console.log('Got index.html from KV, length:', html.length);
} catch (err) {
console.error('KV read error:', err.message);
const profileUrl = `https://${apexDomain}/profile/${npub}`;
return Response.redirect(profileUrl, 302);
}
// Detect NIP-05 mismatch: the profile's NIP-05 doesn't match this subdomain,
// which means the KV store may be pointing to a stale (old) pubkey.
const profileNip05 = profileData?.profile?.nip05 || null;
const nip05Stale = profileNip05
? !isNip05MatchForSubdomain(profileNip05, subdomain, apexDomain)
: false; // No NIP-05 on profile = can't determine, assume OK
if (nip05Stale) {
console.log(`NIP-05 mismatch detected: subdomain=${subdomain}, profile nip05=${profileNip05}, expected _@${subdomain}.${apexDomain}`);
}
// Build the user data object to inject
const divineUser = {
subdomain: subdomain,
pubkey: userData.pubkey,
npub: npub,
username: subdomain,
displayName: profileData?.profile?.display_name || profileData?.profile?.name || subdomain,
picture: profileData?.profile?.picture || null,
banner: profileData?.profile?.banner || null,
about: profileData?.profile?.about || null,
nip05: profileData?.profile?.nip05 || `${subdomain}@${apexDomain}`,
nip05Stale: nip05Stale,
followersCount: profileData?.social?.follower_count || 0,
followingCount: profileData?.social?.following_count || 0,
videoCount: profileData?.stats?.video_count || 0,
apexDomain: apexDomain,
};
// Inject the user data as a global variable before the main script
const userScript = `<script>window.__DIVINE_USER__ = ${JSON.stringify(divineUser)};</script>`;
// Update OG tags for the profile
const ogTitle = divineUser.displayName + ' on Divine';
const ogDescription = divineUser.about || `Watch ${divineUser.displayName}'s videos on Divine`;
const ogImage = divineUser.picture || 'https://divine.video/og.png';
const ogUrl = `https://${subdomain}.${apexDomain}/`;
// Replace OG tags in HTML
html = html.replace(/<meta property="og:title" content="[^"]*" \/>/, `<meta property="og:title" content="${escapeHtml(ogTitle)}" />`);
html = html.replace(/<meta property="og:description" content="[^"]*" \/>/, `<meta property="og:description" content="${escapeHtml(ogDescription)}" />`);
html = html.replace(/<meta property="og:image" content="[^"]*" \/>/, `<meta property="og:image" content="${escapeHtml(ogImage)}" />`);
html = html.replace(/<meta property="og:url" content="[^"]*" \/>/, `<meta property="og:url" content="${escapeHtml(ogUrl)}" />`);
html = html.replace(/<meta name="twitter:title" content="[^"]*" \/>/, `<meta name="twitter:title" content="${escapeHtml(ogTitle)}" />`);
html = html.replace(/<meta name="twitter:description" content="[^"]*" \/>/, `<meta name="twitter:description" content="${escapeHtml(ogDescription)}" />`);
html = html.replace(/<meta name="twitter:image" content="[^"]*" \/>/, `<meta name="twitter:image" content="${escapeHtml(ogImage)}" />`);
html = html.replace(/<title>[^<]*<\/title>/, `<title>${escapeHtml(ogTitle)}</title>`);
// Add a debug comment and inject the script before the closing </head> tag
const debugComment = `<!-- DIVINE_SUBDOMAIN_PROFILE: ${subdomain} -->`;
html = html.replace('</head>', debugComment + userScript + '</head>');
return new Response(html, {
status: 200,
headers: {
'Content-Type': 'text/html; charset=utf-8',
'Cache-Control': 'public, max-age=60', // Short cache for profile pages
'Vary': 'X-Original-Host', // Cache varies by original hostname (from divine-router)
'X-Divine-Subdomain': subdomain, // Debug header to verify subdomain handling
},
});
}
/**
* Convert hex pubkey to npub (Bech32) format
*/
function hexToNpub(hex) {
// Bech32 character set
const CHARSET = 'qpzry9x8gf2tvdw0s3jn54khce6mua7l';
// Convert hex to 5-bit groups
const data = [];
for (let i = 0; i < hex.length; i += 2) {
data.push(parseInt(hex.slice(i, i + 2), 16));
}
// Convert 8-bit to 5-bit
const converted = convertBits(data, 8, 5, true);
// Compute checksum
const hrp = 'npub';
const checksumData = hrpExpand(hrp).concat(converted);
const checksum = createChecksum(checksumData);
// Encode
let result = hrp + '1';
for (const b of converted.concat(checksum)) {
result += CHARSET[b];
}
return result;
}
function convertBits(data, fromBits, toBits, pad) {
let acc = 0;
let bits = 0;
const result = [];
const maxv = (1 << toBits) - 1;
for (const value of data) {
acc = (acc << fromBits) | value;
bits += fromBits;
while (bits >= toBits) {
bits -= toBits;
result.push((acc >> bits) & maxv);
}
}
if (pad && bits > 0) {
result.push((acc << (toBits - bits)) & maxv);
}
return result;
}
function hrpExpand(hrp) {
const result = [];
for (const c of hrp) {
result.push(c.charCodeAt(0) >> 5);
}
result.push(0);
for (const c of hrp) {
result.push(c.charCodeAt(0) & 31);
}
return result;
}
function polymod(values) {
const GEN = [0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3];
let chk = 1;
for (const v of values) {
const top = chk >> 25;
chk = ((chk & 0x1ffffff) << 5) ^ v;
for (let i = 0; i < 5; i++) {
if ((top >> i) & 1) {
chk ^= GEN[i];
}
}
}
return chk;
}
function createChecksum(data) {
const values = data.concat([0, 0, 0, 0, 0, 0]);
const mod = polymod(values) ^ 1;
const result = [];
for (let i = 0; i < 6; i++) {
result.push((mod >> (5 * (5 - i))) & 31);
}
return result;
}
/**
* Detect if request is from a social media crawler (for OG tag injection)
*/
function isSocialMediaCrawler(request) {
const userAgent = (request.headers.get('User-Agent') || '').toLowerCase();
// Common social media and link preview crawlers
const crawlerPatterns = [
'facebookexternalhit',
'twitterbot',
'linkedinbot',
'slackbot',
'discordbot',
'telegrambot',
'whatsapp',
'signal',
'embedly',
'quora link preview',
'showyoubot',
'outbrain',
'pinterest',
'vkshare',
'w3c_validator',
'baiduspider',
'facebot',
'ia_archiver',
];
return crawlerPatterns.some(pattern => userAgent.includes(pattern));
}
/**
* Fetch video metadata from Funnelcake API using Fastly backend
*/
async function fetchVideoMetadata(videoId) {
try {
// Use the /api/videos/{id} endpoint
const response = await fetch(`https://relay.divine.video/api/videos/${videoId}`, {
backend: 'funnelcake',
method: 'GET',
headers: {
'Accept': 'application/json',
'Host': 'relay.divine.video',
},
});
if (!response.ok) {
console.log('Funnelcake API returned:', response.status);
return null;
}
const result = await response.json();
if (!result.event) {
console.log('Video not found:', videoId);
return null;
}
const event = result.event;
const stats = result.stats || {};
// Extract data from tags
const getTag = (name) => event.tags?.find(t => t[0] === name)?.[1];
// Parse imeta tag for thumbnail and video URL
const imetaTag = event.tags?.find(t => t[0] === 'imeta');
const imeta = {};
if (imetaTag) {
for (let i = 1; i < imetaTag.length; i++) {
const parts = imetaTag[i].split(' ');
if (parts.length >= 2) {
imeta[parts[0]] = parts.slice(1).join(' ');
}
}
}
const thumbnail = imeta.image || null;
const title = getTag('title') || null;
const content = event.content || '';
// Build a rich description with engagement stats
const statsList = [];
if (stats.reactions > 0) statsList.push(`${stats.reactions} ❤️`);
if (stats.comments > 0) statsList.push(`${stats.comments} 💬`);
if (stats.reposts > 0) statsList.push(`${stats.reposts} 🔁`);
let description;
if (content && content.trim()) {
// Use the content/caption if available
description = content.trim();
} else if (statsList.length > 0) {
// Show engagement stats
description = `${statsList.join(' • ')} on Divine`;
} else {
description = 'Watch this short video on Divine';
}
console.log('Fetched video metadata - title:', title, 'thumbnail:', thumbnail);
return {
title: title || 'Video on Divine',
description: description,
thumbnail: thumbnail || 'https://divine.video/og.avif',
authorName: getTag('author') || '',
reactions: stats.reactions || 0,
comments: stats.comments || 0,
};
} catch (err) {