FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
illgitthat.github.io/src/index.ts at main · illgitthat/illgitthat.github.io · GitHub
illgitthat
/
illgitthat.github.io
Public
Notifications
You must be signed in to change notification settings
Fork
0
Star
1
Code
Issues
0
Pull requests
0
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Issues
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
illgitthat.github.io
/
src
/
index.ts
Copy path
More file actions
More file actions
Latest commit
History
History
History
1080 lines (920 loc) · 34 KB
Breadcrumbs
illgitthat.github.io
/
src
/
index.ts
Copy path
File metadata and controls
1080 lines (920 loc) · 34 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
import
{
GENERATED_SITE_CSP
,
GALLERY_INDEX_KEY
,
MAX_GALLERY_SIZE
,
MODELS
,
RATE_LIMIT_CONFIG
,
SCREENSHOT_PREFIX
,
SCREENSHOT_PROPAGATION_DELAY_MS
,
SITE_TTL_SECONDS
,
SYSTEM_PROMPTS
,
}
from
'./constants'
;
interface
Env
{
ASSETS
:
Fetcher
;
ENVIRONMENT
:
string
;
CEREBRAS_API_KEY
:
string
;
CLOUDFLARE_ACCOUNT_ID
?:
string
;
CLOUDFLARE_API_TOKEN
?:
string
;
SITES
:
KVNamespace
;
SCREENSHOTS
:
R2Bucket
;
RATE_LIMIT
:
KVNamespace
;
}
interface
GalleryEntry
{
siteId
:
string
;
prompt
:
string
;
createdAt
:
number
;
screenshotUrl
?:
string
;
}
function
isAllowedOrigin
(
origin
:
string
)
:
boolean
{
if
(
!
origin
)
return
true
;
const
isLocalDev
=
/
^
h
t
t
p
s
?
:
\/
\/
(
l
o
c
a
l
h
o
s
t
|
1
2
7
\.
0
\.
0
\.
1
)
(
:
\d
+
)
?
$
/
.
test
(
origin
)
;
// Match *.adamcbloom.com (with or without subdomain, http or https)
const
isAllowedDomain
=
/
^
h
t
t
p
s
?
:
\/
\/
(
.
*
\.
)
?
a
d
a
m
c
b
l
o
o
m
\.
c
o
m
$
/
.
test
(
origin
)
;
return
isLocalDev
||
isAllowedDomain
;
}
function
getCorsHeaders
(
request
:
Request
)
:
Record
<
string
,
string
>
{
const
origin
=
request
.
headers
.
get
(
'Origin'
)
||
''
;
if
(
origin
&&
isAllowedOrigin
(
origin
)
)
{
return
{
'Access-Control-Allow-Origin'
:
origin
,
'Access-Control-Allow-Methods'
:
'GET, POST, OPTIONS'
,
'Access-Control-Allow-Headers'
:
'Content-Type'
,
'Access-Control-Allow-Credentials'
:
'true'
,
'Vary'
:
'Origin'
,
}
;
}
// No Origin header (non-browser or same-origin) or disallowed origin
return
{
'Access-Control-Allow-Methods'
:
'GET, POST, OPTIONS'
,
'Access-Control-Allow-Headers'
:
'Content-Type'
,
}
;
}
// ============================================================================
// HELPERS
// ============================================================================
/**
* Create a JSON response with CORS headers
*/
function
jsonResponse
(
data
:
unknown
,
status
=
200
,
extraHeaders
:
Record
<
string
,
string
>
=
{
}
)
:
Response
{
return
Response
.
json
(
data
,
{
status
,
headers
:
{
...
getSecurityHeaders
(
)
,
...
extraHeaders
}
,
}
)
;
}
/**
* Create a JSON response with request-specific CORS headers
*/
function
jsonResponseWithCors
(
request
:
Request
,
data
:
unknown
,
status
=
200
,
extraHeaders
:
Record
<
string
,
string
>
=
{
}
)
:
Response
{
return
Response
.
json
(
data
,
{
status
,
headers
:
{
...
getCorsHeaders
(
request
)
,
...
getSecurityHeaders
(
)
,
...
extraHeaders
}
,
}
)
;
}
function
getSecurityHeaders
(
)
:
Record
<
string
,
string
>
{
return
{
'Strict-Transport-Security'
:
'max-age=31536000; includeSubDomains; preload'
,
'Referrer-Policy'
:
'no-referrer'
,
'Permissions-Policy'
:
'camera=(), microphone=(), geolocation=(), payment=(), usb=()'
,
'X-Content-Type-Options'
:
'nosniff'
,
}
;
}
// ============================================================================
// STRUCTURED LOGGING
// ============================================================================
type
LogLevel
=
'debug'
|
'info'
|
'warn'
|
'error'
;
interface
LogContext
{
[
key
:
string
]
:
unknown
;
}
const
logger
=
{
_format
(
level
:
LogLevel
,
component
:
string
,
message
:
string
,
context
?:
LogContext
)
:
string
{
const
timestamp
=
new
Date
(
)
.
toISOString
(
)
;
const
contextStr
=
context
?
`
${
JSON
.
stringify
(
context
)
}
`
:
''
;
return
`[
${
timestamp
}
] [
${
level
.
toUpperCase
(
)
}
] [
${
component
}
]
${
message
}
${
contextStr
}
`
;
}
,
debug
(
component
:
string
,
message
:
string
,
context
?:
LogContext
)
:
void
{
console
.
log
(
this
.
_format
(
'debug'
,
component
,
message
,
context
)
)
;
}
,
info
(
component
:
string
,
message
:
string
,
context
?:
LogContext
)
:
void
{
console
.
log
(
this
.
_format
(
'info'
,
component
,
message
,
context
)
)
;
}
,
warn
(
component
:
string
,
message
:
string
,
context
?:
LogContext
)
:
void
{
console
.
warn
(
this
.
_format
(
'warn'
,
component
,
message
,
context
)
)
;
}
,
error
(
component
:
string
,
message
:
string
,
context
?:
LogContext
)
:
void
{
console
.
error
(
this
.
_format
(
'error'
,
component
,
message
,
context
)
)
;
}
,
}
;
// ============================================================================
// RATE LIMITING
// ============================================================================
interface
RateLimitResult
{
allowed
:
boolean
;
remaining
:
number
;
resetAt
:
number
;
}
function
getRateLimitHeaders
(
rateLimit
:
RateLimitResult
)
:
Record
<
string
,
string
>
{
return
{
'X-RateLimit-Limit'
:
String
(
RATE_LIMIT_CONFIG
.
MAX_REQUESTS
)
,
'X-RateLimit-Remaining'
:
String
(
Math
.
max
(
0
,
rateLimit
.
remaining
)
)
,
'X-RateLimit-Reset'
:
String
(
rateLimit
.
resetAt
)
,
}
;
}
/**
* Check and increment rate limit for an IP address
* Uses KV with TTL for automatic expiration
*/
async
function
checkRateLimit
(
env
:
Env
,
ip
:
string
)
:
Promise
<
RateLimitResult
>
{
if
(
!
env
.
RATE_LIMIT
)
{
// Rate limiting not configured, allow all requests
return
{
allowed
:
true
,
remaining
:
RATE_LIMIT_CONFIG
.
MAX_REQUESTS
,
resetAt
:
0
}
;
}
const
key
=
`
${
RATE_LIMIT_CONFIG
.
KEY_PREFIX
}
${
ip
}
`
;
const
now
=
Math
.
floor
(
Date
.
now
(
)
/
1000
)
;
try
{
const
data
=
await
env
.
RATE_LIMIT
.
get
(
key
)
;
let
count
=
0
;
let
windowStart
=
now
;
if
(
data
)
{
const
parsed
=
JSON
.
parse
(
data
)
as
{
count
:
number
;
windowStart
:
number
}
;
// Check if we're still in the same window
if
(
now
-
parsed
.
windowStart
<
RATE_LIMIT_CONFIG
.
WINDOW_SECONDS
)
{
count
=
parsed
.
count
;
windowStart
=
parsed
.
windowStart
;
}
}
const
resetAt
=
windowStart
+
RATE_LIMIT_CONFIG
.
WINDOW_SECONDS
;
const
remaining
=
Math
.
max
(
0
,
RATE_LIMIT_CONFIG
.
MAX_REQUESTS
-
count
-
1
)
;
if
(
count
>=
RATE_LIMIT_CONFIG
.
MAX_REQUESTS
)
{
logger
.
warn
(
'RateLimit'
,
'Rate limit exceeded'
,
{
ip
:
ip
.
slice
(
0
,
10
)
+
'...'
,
count
}
)
;
return
{
allowed
:
false
,
remaining
:
0
,
resetAt
}
;
}
// Increment counter
await
env
.
RATE_LIMIT
.
put
(
key
,
JSON
.
stringify
(
{
count
:
count
+
1
,
windowStart
}
)
,
{
expirationTtl
:
RATE_LIMIT_CONFIG
.
WINDOW_SECONDS
}
)
;
return
{
allowed
:
true
,
remaining
,
resetAt
}
;
}
catch
(
error
)
{
// On error, allow the request but log the issue
logger
.
error
(
'RateLimit'
,
'Failed to check rate limit'
,
{
error
:
error
instanceof
Error
?
error
.
message
:
'Unknown'
}
)
;
return
{
allowed
:
true
,
remaining
:
RATE_LIMIT_CONFIG
.
MAX_REQUESTS
,
resetAt
:
0
}
;
}
}
export
default
{
async
fetch
(
request
:
Request
,
env
:
Env
,
ctx
:
ExecutionContext
)
:
Promise
<
Response
>
{
const
url
=
new
URL
(
request
.
url
)
;
const
origin
=
request
.
headers
.
get
(
'Origin'
)
||
''
;
const
isApiRequest
=
url
.
pathname
.
startsWith
(
'/api/'
)
;
if
(
origin
&&
!
isAllowedOrigin
(
origin
)
&&
(
isApiRequest
||
request
.
method
===
'OPTIONS'
)
)
{
return
new
Response
(
'Forbidden'
,
{
status
:
403
,
headers
:
getSecurityHeaders
(
)
,
}
)
;
}
if
(
request
.
method
===
'OPTIONS'
)
{
return
new
Response
(
null
,
{
headers
:
{
...
getCorsHeaders
(
request
)
,
...
getSecurityHeaders
(
)
}
}
)
;
}
// Serve stored sites at /site/:id
const
siteMatch
=
url
.
pathname
.
match
(
/
^
\/
s
i
t
e
\/
(
[
a
-
z
A
-
Z
0
-
9
]
+
)
$
/
)
;
if
(
siteMatch
)
{
return
handleSiteView
(
siteMatch
[
1
]
,
env
)
;
}
const
screenshotMatch
=
url
.
pathname
.
match
(
/
^
\/
s
c
r
e
e
n
s
h
o
t
\/
(
[
a
-
z
A
-
Z
0
-
9
\-
_
.
]
+
)
$
/
)
;
if
(
screenshotMatch
)
{
return
handleScreenshotView
(
screenshotMatch
[
1
]
,
env
)
;
}
if
(
url
.
pathname
.
startsWith
(
'/api/'
)
)
{
return
handleApi
(
request
,
env
,
url
,
ctx
)
;
}
return
env
.
ASSETS
.
fetch
(
request
)
;
}
,
}
;
async
function
handleApi
(
request
:
Request
,
env
:
Env
,
url
:
URL
,
ctx
:
ExecutionContext
)
:
Promise
<
Response
>
{
if
(
url
.
pathname
===
'/api/health'
)
{
return
jsonResponseWithCors
(
request
,
{
status
:
'ok'
}
)
;
}
if
(
url
.
pathname
===
'/api/build'
&&
request
.
method
===
'POST'
)
{
return
handleBuild
(
request
,
env
,
ctx
)
;
}
if
(
url
.
pathname
===
'/api/build-stream'
&&
request
.
method
===
'POST'
)
{
return
handleBuildStream
(
request
,
env
,
ctx
)
;
}
if
(
url
.
pathname
===
'/api/surprise'
&&
request
.
method
===
'POST'
)
{
return
handleSurprise
(
request
,
env
)
;
}
if
(
url
.
pathname
===
'/api/gallery'
&&
request
.
method
===
'GET'
)
{
return
handleGallery
(
request
,
env
)
;
}
const
screenshotStatusMatch
=
url
.
pathname
.
match
(
/
^
\/
a
p
i
\/
s
c
r
e
e
n
s
h
o
t
-
s
t
a
t
u
s
\/
(
[
a
-
z
A
-
Z
0
-
9
]
+
)
$
/
)
;
if
(
screenshotStatusMatch
&&
request
.
method
===
'GET'
)
{
return
handleScreenshotStatus
(
request
,
screenshotStatusMatch
[
1
]
,
env
)
;
}
return
jsonResponseWithCors
(
request
,
{
error
:
'Not found'
}
,
404
)
;
}
async
function
handleBuild
(
request
:
Request
,
env
:
Env
,
ctx
:
ExecutionContext
)
:
Promise
<
Response
>
{
// Rate limiting check
const
clientIp
=
request
.
headers
.
get
(
'CF-Connecting-IP'
)
||
'unknown'
;
const
rateLimit
=
await
checkRateLimit
(
env
,
clientIp
)
;
const
rateLimitHeaders
=
getRateLimitHeaders
(
rateLimit
)
;
if
(
!
rateLimit
.
allowed
)
{
return
jsonResponseWithCors
(
request
,
{
error
:
'Rate limit exceeded. Please wait before making more requests.'
,
retryAfter
:
rateLimit
.
resetAt
-
Math
.
floor
(
Date
.
now
(
)
/
1000
)
}
,
429
,
{
'Retry-After'
:
String
(
rateLimit
.
resetAt
-
Math
.
floor
(
Date
.
now
(
)
/
1000
)
)
,
...
rateLimitHeaders
,
}
)
;
}
let
body
:
{
prompt
?:
string
}
;
try
{
body
=
(
await
request
.
json
(
)
)
as
{
prompt
?:
string
}
;
}
catch
{
return
jsonResponseWithCors
(
request
,
{
error
:
'Invalid JSON body'
}
,
400
,
rateLimitHeaders
)
;
}
const
prompt
=
body
.
prompt
?.
trim
(
)
;
if
(
!
prompt
)
{
return
jsonResponseWithCors
(
request
,
{
error
:
'Prompt required'
}
,
400
,
rateLimitHeaders
)
;
}
if
(
prompt
.
length
>
2000
)
{
return
jsonResponseWithCors
(
request
,
{
error
:
'Prompt too long'
}
,
400
,
rateLimitHeaders
)
;
}
const
messages
=
[
{
role
:
'system'
,
content
:
SYSTEM_PROMPTS
.
BUILD
}
,
{
role
:
'user'
,
content
:
`Brief:
${
prompt
}
\n\nProduce the final HTML document now.`
,
}
,
]
;
let
html
=
''
;
try
{
logger
.
info
(
'Build'
,
'Starting generation'
,
{
promptPreview
:
prompt
.
slice
(
0
,
100
)
}
)
;
const
jsonText
=
await
callCerebras
(
env
,
messages
,
{
model
:
MODELS
.
BUILD
,
maxTokens
:
16000
,
}
)
;
const
parsed
=
parseHtmlResponse
(
jsonText
)
;
html
=
parsed
;
logger
.
info
(
'Build'
,
'Generated HTML'
,
{
length
:
html
.
length
}
)
;
}
catch
(
error
)
{
const
errorMessage
=
error
instanceof
Error
?
error
.
message
:
'Unknown error'
;
logger
.
error
(
'Build'
,
'Generation failed'
,
{
error
:
errorMessage
}
)
;
// Detect rate limiting or server overload
const
isRateLimit
=
errorMessage
.
includes
(
'429'
)
||
errorMessage
.
toLowerCase
(
)
.
includes
(
'rate'
)
;
const
isServerBusy
=
errorMessage
.
includes
(
'503'
)
||
errorMessage
.
includes
(
'502'
)
||
errorMessage
.
toLowerCase
(
)
.
includes
(
'busy'
)
;
let
userMessage
=
'AI service error'
;
if
(
isRateLimit
)
{
userMessage
=
'The builder is busy. Please try again in a moment.'
;
}
else
if
(
isServerBusy
)
{
userMessage
=
'The AI service is temporarily unavailable. Please try again shortly.'
;
}
return
jsonResponseWithCors
(
request
,
{
error
:
userMessage
}
,
502
,
rateLimitHeaders
)
;
}
html
=
html
.
trim
(
)
;
if
(
!
html
)
{
logger
.
error
(
'Build'
,
'Empty response from AI - raw content was empty after parsing'
)
;
return
jsonResponseWithCors
(
request
,
{
error
:
'Empty response from AI. Please try again.'
}
,
502
,
rateLimitHeaders
)
;
}
const
normalizedHtml
=
normalizeHtml
(
html
)
;
// Store in KV with 24h TTL and return shareable URL
const
siteId
=
generateSiteId
(
)
;
try
{
await
env
.
SITES
.
put
(
siteId
,
normalizedHtml
,
{
expirationTtl
:
SITE_TTL_SECONDS
}
)
;
// Store prompt separately for regeneration on expiry (store longer than site)
await
env
.
SITES
.
put
(
`prompt:
${
siteId
}
`
,
prompt
,
{
expirationTtl
:
SITE_TTL_SECONDS
*
7
}
)
;
// 7 days
// Add to gallery index
await
addToGalleryIndex
(
env
,
{
siteId
,
prompt
,
createdAt
:
Date
.
now
(
)
}
)
;
}
catch
{
// KV storage failed, still return the HTML but without share URL
return
jsonResponseWithCors
(
request
,
{
html
:
normalizedHtml
}
,
200
,
rateLimitHeaders
)
;
}
const
shareUrl
=
`/site/
${
siteId
}
`
;
const
origin
=
new
URL
(
request
.
url
)
.
origin
;
ctx
.
waitUntil
(
generateScreenshotAndStore
(
{
env
,
siteId
,
origin
,
}
)
)
;
return
jsonResponseWithCors
(
request
,
{
html
:
normalizedHtml
,
shareUrl
,
siteId
}
,
200
,
rateLimitHeaders
)
;
}
/**
* Stream-based build endpoint using Server-Sent Events
* Provides real-time progress updates during site generation
*/
async
function
handleBuildStream
(
request
:
Request
,
env
:
Env
,
ctx
:
ExecutionContext
)
:
Promise
<
Response
>
{
// Rate limiting check
const
clientIp
=
request
.
headers
.
get
(
'CF-Connecting-IP'
)
||
'unknown'
;
const
rateLimit
=
await
checkRateLimit
(
env
,
clientIp
)
;
const
rateLimitHeaders
=
getRateLimitHeaders
(
rateLimit
)
;
if
(
!
rateLimit
.
allowed
)
{
return
jsonResponseWithCors
(
request
,
{
error
:
'Rate limit exceeded. Please wait before making more requests.'
,
retryAfter
:
rateLimit
.
resetAt
-
Math
.
floor
(
Date
.
now
(
)
/
1000
)
}
,
429
,
{
'Retry-After'
:
String
(
rateLimit
.
resetAt
-
Math
.
floor
(
Date
.
now
(
)
/
1000
)
)
,
...
rateLimitHeaders
,
}
)
;
}
let
body
:
{
prompt
?:
string
}
;
try
{
body
=
(
await
request
.
json
(
)
)
as
{
prompt
?:
string
}
;
}
catch
{
return
jsonResponseWithCors
(
request
,
{
error
:
'Invalid JSON body'
}
,
400
,
rateLimitHeaders
)
;
}
const
prompt
=
body
.
prompt
?.
trim
(
)
;
if
(
!
prompt
)
{
return
jsonResponseWithCors
(
request
,
{
error
:
'Prompt required'
}
,
400
,
rateLimitHeaders
)
;
}
if
(
prompt
.
length
>
2000
)
{
return
jsonResponseWithCors
(
request
,
{
error
:
'Prompt too long'
}
,
400
,
rateLimitHeaders
)
;
}
// Create a TransformStream for SSE
const
{
readable
,
writable
}
=
new
TransformStream
(
)
;
const
writer
=
writable
.
getWriter
(
)
;
const
encoder
=
new
TextEncoder
(
)
;
// Helper to send SSE events
const
sendEvent
=
async
(
event
:
string
,
data
:
unknown
)
=>
{
const
message
=
`event:
${
event
}
\ndata:
${
JSON
.
stringify
(
data
)
}
\n\n`
;
await
writer
.
write
(
encoder
.
encode
(
message
)
)
;
}
;
// Start the generation process in the background
ctx
.
waitUntil
(
(
async
(
)
=>
{
try
{
// Send initial progress
await
sendEvent
(
'progress'
,
{
stage
:
'started'
,
message
:
'Starting generation...'
,
estimatedTime
:
15
// seconds
}
)
;
const
messages
=
[
{
role
:
'system'
,
content
:
SYSTEM_PROMPTS
.
BUILD
}
,
{
role
:
'user'
,
content
:
`Brief:
${
prompt
}
\n\nProduce the final HTML document now.`
}
,
]
;
await
sendEvent
(
'progress'
,
{
stage
:
'generating'
,
message
:
'AI is generating your site...'
,
progress
:
20
}
)
;
logger
.
info
(
'BuildStream'
,
'Starting generation'
,
{
promptPreview
:
prompt
.
slice
(
0
,
100
)
}
)
;
const
jsonText
=
await
callCerebras
(
env
,
messages
,
{
model
:
MODELS
.
BUILD
,
maxTokens
:
16000
,
}
)
;
await
sendEvent
(
'progress'
,
{
stage
:
'processing'
,
message
:
'Processing generated content...'
,
progress
:
70
}
)
;
const
parsed
=
parseHtmlResponse
(
jsonText
)
;
let
html
=
parsed
.
trim
(
)
;
if
(
!
html
)
{
await
sendEvent
(
'error'
,
{
error
:
'Empty response from AI. Please try again.'
}
)
;
await
writer
.
close
(
)
;
return
;
}
const
normalizedHtml
=
normalizeHtml
(
html
)
;
await
sendEvent
(
'progress'
,
{
stage
:
'storing'
,
message
:
'Storing your site...'
,
progress
:
85
}
)
;
// Store in KV
const
siteId
=
generateSiteId
(
)
;
await
env
.
SITES
.
put
(
siteId
,
normalizedHtml
,
{
expirationTtl
:
SITE_TTL_SECONDS
}
)
;
await
env
.
SITES
.
put
(
`prompt:
${
siteId
}
`
,
prompt
,
{
expirationTtl
:
SITE_TTL_SECONDS
*
7
}
)
;
await
addToGalleryIndex
(
env
,
{
siteId
,
prompt
,
createdAt
:
Date
.
now
(
)
}
)
;
const
shareUrl
=
`/site/
${
siteId
}
`
;
const
origin
=
new
URL
(
request
.
url
)
.
origin
;
// Start screenshot generation in background
ctx
.
waitUntil
(
generateScreenshotAndStore
(
{
env
,
siteId
,
origin
}
)
)
;
await
sendEvent
(
'progress'
,
{
stage
:
'complete'
,
message
:
'Site ready!'
,
progress
:
100
}
)
;
// Send final result
await
sendEvent
(
'complete'
,
{
html
:
normalizedHtml
,
shareUrl
,
siteId
}
)
;
}
catch
(
error
)
{
const
errorMessage
=
error
instanceof
Error
?
error
.
message
:
'Unknown error'
;
logger
.
error
(
'BuildStream'
,
'Generation failed'
,
{
error
:
errorMessage
}
)
;
const
isRateLimit
=
errorMessage
.
includes
(
'429'
)
||
errorMessage
.
toLowerCase
(
)
.
includes
(
'rate'
)
;
const
isServerBusy
=
errorMessage
.
includes
(
'503'
)
||
errorMessage
.
includes
(
'502'
)
;
let
userMessage
=
'AI service error'
;
if
(
isRateLimit
)
{
userMessage
=
'The builder is busy. Please try again in a moment.'
;
}
else
if
(
isServerBusy
)
{
userMessage
=
'The AI service is temporarily unavailable. Please try again shortly.'
;
}
await
sendEvent
(
'error'
,
{
error
:
userMessage
}
)
;
}
finally
{
await
writer
.
close
(
)
;
}
}
)
(
)
)
;
// Return the SSE response immediately
return
new
Response
(
readable
,
{
headers
:
{
'Content-Type'
:
'text/event-stream'
,
'Cache-Control'
:
'no-cache'
,
'Connection'
:
'keep-alive'
,
...
getCorsHeaders
(
request
)
,
...
getSecurityHeaders
(
)
,
...
rateLimitHeaders
,
}
,
}
)
;
}
async
function
handleSurprise
(
request
:
Request
,
env
:
Env
)
:
Promise
<
Response
>
{
// Rate limiting check (shares limit with build)
const
clientIp
=
request
.
headers
.
get
(
'CF-Connecting-IP'
)
||
'unknown'
;
const
rateLimit
=
await
checkRateLimit
(
env
,
clientIp
)
;
const
rateLimitHeaders
=
getRateLimitHeaders
(
rateLimit
)
;
if
(
!
rateLimit
.
allowed
)
{
return
jsonResponseWithCors
(
request
,
{
error
:
'Rate limit exceeded. Please wait before making more requests.'
,
retryAfter
:
rateLimit
.
resetAt
-
Math
.
floor
(
Date
.
now
(
)
/
1000
)
}
,
429
,
{
'Retry-After'
:
String
(
rateLimit
.
resetAt
-
Math
.
floor
(
Date
.
now
(
)
/
1000
)
)
,
...
rateLimitHeaders
,
}
)
;
}
const
messages
=
[
{
role
:
'system'
,
content
:
SYSTEM_PROMPTS
.
SURPRISE
}
,
{
role
:
'user'
,
content
:
'Generate a fresh, creative website idea for me to build right now.'
}
,
]
;
try
{
const
idea
=
await
callCerebras
(
env
,
messages
,
{
model
:
MODELS
.
SURPRISE
,
maxTokens
:
400
,
temperature
:
1.2
,
}
)
;
return
jsonResponseWithCors
(
request
,
{
idea
:
idea
.
trim
(
)
}
,
200
,
rateLimitHeaders
)
;
}
catch
(
error
)
{
const
errorMessage
=
error
instanceof
Error
?
error
.
message
:
'Unknown error'
;
logger
.
error
(
'Surprise'
,
'Generation failed'
,
{
error
:
errorMessage
}
)
;
return
jsonResponseWithCors
(
request
,
{
error
:
'Could not generate idea. Try again!'
}
,
502
,
rateLimitHeaders
)
;
}
}
async
function
handleSiteView
(
siteId
:
string
,
env
:
Env
)
:
Promise
<
Response
>
{
const
html
=
await
env
.
SITES
.
get
(
siteId
)
;
if
(
!
html
)
{
// Check if we have the original prompt stored for regeneration
const
storedPrompt
=
await
env
.
SITES
.
get
(
`prompt:
${
siteId
}
`
)
;
const
encodedPrompt
=
storedPrompt
?
encodeURIComponent
(
storedPrompt
)
:
''
;
const
expiredHtml
=
`<!DOCTYPE html>
<html>
<head>
<title>Site Expired</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body {
font-family: system-ui, -apple-system, sans-serif;
background: #0b0d24;
color: #e5e7eb;
display: flex;
align-items: center;
justify-content: center;
min-height: 100vh;
margin: 0;
text-align: center;
}
.container {
max-width: 450px;
padding: 2rem;
}
h1 {
margin-bottom: 1rem;
font-size: 1.5rem;
}
p {
margin-bottom: 1rem;
opacity: 0.8;
}
.prompt-preview {
background: rgba(255,255,255,0.1);
padding: 1rem;
border-radius: 8px;
margin: 1.5rem 0;
font-size: 0.9rem;
text-align: left;
}
.prompt-preview strong {
display: block;
margin-bottom: 0.5rem;
opacity: 0.7;
}
a {
color: #74b0ff;
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
.btn {
display: inline-block;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
padding: 0.75rem 1.5rem;
border-radius: 8px;
text-decoration: none;
margin-top: 0.5rem;
}
.btn:hover {
opacity: 0.9;
text-decoration: none;
}
</style>
</head>
<body>
<div class="container">
<h1>This site has expired</h1>
<p>Generated sites are removed after newer creations.</p>
${
storedPrompt
?
`
<div class="prompt-preview">
<strong>Original prompt:</strong>
${
escapeHtml
(
storedPrompt
.
slice
(
0
,
200
)
)
}
${
storedPrompt
.
length
>
200
?
'...'
:
''
}
</div>
<a href="/?prompt=
${
encodedPrompt
}
" class="btn">Regenerate with same prompt →</a>
<p style="margin-top: 1.5rem;"><a href="/">Or create something new</a></p>
`
:
`
<p><a href="/">Create a new one →</a></p>
`
}
</div>
</body>
</html>`
;
return
new
Response
(
expiredHtml
,
{
status
:
404
,
headers
:
{
'Content-Type'
:
'text/html; charset=utf-8'
,
...
getSecurityHeaders
(
)
,
}
,
}
)
;
}
return
new
Response
(
html
,
{
headers
:
{
'Content-Type'
:
'text/html; charset=utf-8'
,
'Content-Security-Policy'
:
GENERATED_SITE_CSP
,
'X-Frame-Options'
:
'SAMEORIGIN'
,
...
getSecurityHeaders
(
)
,
}
}
)
;
}
async
function
handleScreenshotView
(
key
:
string
,
env
:
Env
)
:
Promise
<
Response
>
{
const
object
=
await
env
.
SCREENSHOTS
.
get
(
`
${
SCREENSHOT_PREFIX
}
${
key
}
`
)
;
if
(
!
object
)
{
return
new
Response
(
'Not found'
,
{
status
:
404
}
)
;
}
const
headers
=
new
Headers
(
)
;
headers
.
set
(
'Content-Type'
,
object
.
httpMetadata
?.
contentType
||
'image/png'
)
;
headers
.
set
(
'Cache-Control'
,
'public, max-age=2592000, immutable'
)
;
// 30 days, immutable content
Object
.
entries
(
getSecurityHeaders
(
)
)
.
forEach
(
(
[
keyName
,
value
]
)
=>
headers
.
set
(
keyName
,
value
)
)
;
return
new
Response
(
object
.
body
,
{
headers
}
)
;
}
async
function
handleScreenshotStatus
(
request
:
Request
,
siteId
:
string
,
env
:
Env
)
:
Promise
<
Response
>
{
try
{
// Check if R2 bucket is available (might not be in dev mode)
if
(
!
env
.
SCREENSHOTS
)
{
logger
.
info
(
'ScreenshotStatus'
,
'R2 bucket not available'
)
;
return
jsonResponseWithCors
(
request
,
{
ready
:
false
,
reason
:
'storage_unavailable'
}
)
;
}
const
screenshotKey
=
`
${
SCREENSHOT_PREFIX
}
${
siteId
}
.png`
;
const
object
=
await
env
.
SCREENSHOTS
.
head
(
screenshotKey
)
;
if
(
object
)
{
logger
.
info
(
'ScreenshotStatus'
,
'Found screenshot'
,
{
siteId
}
)
;
return
jsonResponseWithCors
(
request
,
{
ready
:
true
,
screenshotUrl
:
`/screenshot/
${
siteId
}
.png`
}
)
;
}
logger
.
debug
(
'ScreenshotStatus'
,
'Screenshot not ready'
,
{
siteId
}
)
;
return
jsonResponseWithCors
(
request
,
{
ready
:
false
}
)
;
}
catch
(
error
)
{
const
message
=
error
instanceof
Error
?
error
.
message
:
'Unknown'
;
logger
.
error
(
'ScreenshotStatus'
,
'Error checking status'
,
{
siteId
,
error
:
message
}
)
;
return
jsonResponseWithCors
(
request
,
{
ready
:
false
,
error
:
'Screenshot status unavailable'
}
)
;
}
}
async
function
handleGallery
(
request
:
Request
,
env
:
Env
)
:
Promise
<
Response
>
{
try
{
const
indexJson
=
await
env
.
SITES
.
get
(
GALLERY_INDEX_KEY
)
;
if
(
!
indexJson
)
{
return
jsonResponseWithCors
(
request
,
{
sites
:
[
]
}
,
200
,
{
'Cache-Control'
:
'public, max-age=60'
}
)
;
}
const
entries
:
GalleryEntry
[
]
=
JSON
.
parse
(
indexJson
)
;
// Verify sites still exist (in parallel)
const
checks
=
await
Promise
.
all
(
entries
.
map
(
async
entry
=>
{
const
exists
=
(
await
env
.
SITES
.
get
(
entry
.
siteId
)
)
!==
null
;
return
exists
?
entry
:
null
;
}
)
)
;
const
sites
=
checks
.
filter
(
(
e
)
:
e
is
GalleryEntry
=>
e
!==
null
)
;
return
jsonResponseWithCors
(
request
,
{
sites
}
,
200
,
{
'Cache-Control'
:
'public, max-age=60'
}
)
;
}
catch
{
return
jsonResponseWithCors
(
request
,
{
sites
:
[
]
}
,
200
,
{
'Cache-Control'
:
'public, max-age=60'
}
)
;
}
}
async
function
addToGalleryIndex
(
env
:
Env
,
entry
:
GalleryEntry
)
:
Promise
<
void
>
{
try
{
const
indexJson
=
await
env
.
SITES
.
get
(
GALLERY_INDEX_KEY
)
;
let
entries
:
GalleryEntry
[
]
=
indexJson
?
JSON
.
parse
(
indexJson
)
:
[
]
;
// Add new entry at the beginning
entries
.
unshift
(
entry
)
;
// Identify entries to remove (beyond MAX_GALLERY_SIZE)
const
entriesToRemove
=
entries
.
slice
(
MAX_GALLERY_SIZE
)
;
// Keep only the most recent entries
entries
=
entries
.
slice
(
0
,
MAX_GALLERY_SIZE
)
;
// Store index (with long TTL as fallback)
await
env
.
SITES
.
put
(
GALLERY_INDEX_KEY
,
JSON
.
stringify
(
entries
)
,
{
expirationTtl
:
SITE_TTL_SECONDS
}
)
;
// Clean up old entries (KV sites, prompts, and R2 screenshots)
for
(
const
old
of
entriesToRemove
)
{
try
{
await
Promise
.
all
(
[
env
.
SITES
.
delete
(
old
.
siteId
)
,
env
.
SITES
.
delete
(
`prompt:
${
old
.
siteId
}
`
)
,
env
.
SCREENSHOTS
?.
delete
(
`
${
SCREENSHOT_PREFIX
}
${
old
.
siteId
}
.png`
)
,
]
)
;
logger
.
info
(
'Gallery'
,
'Cleaned up old entry'
,
{
siteId
:
old
.
siteId
}
)
;
}
catch
{
// Best effort cleanup
}
}
}
catch
{
// Silently fail - gallery is non-critical
}
}
async
function
updateGalleryScreenshot
(
env
:
Env
,
siteId
:
string
,
screenshotUrl
:
string
)
:
Promise
<
void
>
{
try
{
const
indexJson
=
await
env
.
SITES
.
get
(
GALLERY_INDEX_KEY
)
;
if
(
!
indexJson
)
{
logger
.
info
(
'Gallery'
,
'No index found when updating screenshot'
)
;
return
;
}
const
entries
:
GalleryEntry
[
]
=
JSON
.
parse
(
indexJson
)
;
const
updated
=
entries
.
map
(
entry
=>
entry
.
siteId
===
siteId
?
{
...
entry
,
screenshotUrl
}
:
entry
)
;
await
env
.
SITES
.
put
(
GALLERY_INDEX_KEY
,
JSON
.
stringify
(
updated
)
,
{
expirationTtl
:
SITE_TTL_SECONDS
}
)
;
logger
.
info
(
'Gallery'
,
'Updated screenshot URL'
,
{
siteId
}
)
;
}
catch
(
error
)
{
const
message
=
error
instanceof
Error
?
error
.
message
:
'Unknown'
;
logger
.
error
(
'Gallery'
,
'Failed to update screenshot URL'
,
{
error
:
message
}
)
;
}
}
/**
* Attempt to take a screenshot with retry logic and exponential backoff
*/
async
function
takeScreenshotWithRetry
(
apiUrl
:
string
,
targetUrl
:
string
,
apiToken
:
string
,
maxRetries
=
3
)
:
Promise
<
ArrayBuffer
|
null
>
{
const
baseDelayMs
=
1000
;
// 1 second base delay
for
(
let
attempt
=
1
;
attempt
<=
maxRetries
;
attempt
++
)
{
try
{
logger
.
info
(
'Screenshot'
,
`Attempt
${
attempt
}
/
${
maxRetries
}
`
,
{
url
:
targetUrl
}
)
;
const
response
=
await
fetch
(
apiUrl
,
{
method
:
'POST'
,
headers
:
{
'Content-Type'
:
'application/json'
,
'Authorization'
:
`Bearer
${
apiToken
}
`
,
}
,
body
:
JSON
.
stringify
(
{
url
:
targetUrl
,
viewport
:
{
width
:
720
,
height
:
450
}
,
// Optimized for gallery display (360x225 @ 2x)
screenshotOptions
:
{
fullPage
:
false
}
,
gotoOptions
:
{
waitUntil
:
'networkidle0'
,
// Wait until no network connections for 500ms
}
,
waitForTimeout
:
300
,
// Additional .3s wait for animations/renders to settle
}
)
,
}
)
;
if
(
response
.
ok
)
{
const
imageBuffer
=
await
response
.
arrayBuffer
(
)
;
return
imageBuffer
;
}
const
errorText
=
await
safeResponseText
(
response
)
;
logger
.
warn
(
'Screenshot'
,
`Attempt
${
attempt
}
failed`
,
{
status
:
response
.
status
,
error
:
errorText
.
slice
(
0
,
200
)
}
)
;
// Don't retry on client errors (4xx), only on server errors (5xx)
if
(
response
.
status
<
500
)
{
logger
.
error
(
'Screenshot'
,
'Non-retryable error'
,
{
status
:
response
.
status
}
)
;
return
null
;
}
}
catch
(
error
)
{
const
message
=
error
instanceof
Error
?
error
.
message
:
'Unknown error'
;
logger
.
warn
(
'Screenshot'
,
`Attempt
${
attempt
}
threw error`
,
{
error
:
message
}
)
;
}
// Exponential backoff: 1s, 2s, 4s
if
(
attempt
<
maxRetries
)
{
const
delay
=
baseDelayMs
*
Math
.
pow
(
2
,
attempt
-
1
)
;
logger
.
info
(
'Screenshot'
,
`Retrying in
${
delay
}
ms`
)
;
await
new
Promise
(
resolve
=>
setTimeout
(
resolve
,
delay
)
)
;
}
}
logger
.
error
(
'Screenshot'
,
'All retry attempts exhausted'
)
;
return
null
;
}
async
function
generateScreenshotAndStore
(
params
:
{
env
:
Env
;
siteId
:
string
;
origin
:
string
;
}
)
:
Promise
<
void
>
{
const
{
env
,
siteId
,
origin
}
=
params
;
// Skip screenshot generation in dev mode (Browser Rendering can't access localhost)
if
(
origin
.
includes
(
'localhost'
)
||
origin
.
includes
(
'127.0.0.1'
)
)
{
logger
.
info
(
'Screenshot'
,
'Skipping - localhost not accessible by Browser Rendering API'
)
;
return
;
}
if
(
!
env
.
CLOUDFLARE_ACCOUNT_ID
||
!
env
.
CLOUDFLARE_API_TOKEN
)
{
logger
.
warn
(
'Screenshot'
,
'Missing Cloudflare Browser Rendering credentials'
)
;
return
;
}
// Small delay to ensure KV write has propagated
await
new
Promise
(
resolve
=>
setTimeout
(
resolve
,
SCREENSHOT_PROPAGATION_DELAY_MS
)
)
;
// Verify site exists before taking screenshot
const
siteHtml
=
await
env
.
SITES
.
get
(
siteId
)
;
if
(
!
siteHtml
)
{
logger
.
error
(
'Screenshot'
,
'Site not found in KV, skipping screenshot'
,
{
siteId
}
)
;
return
;
}
const
apiUrl
=
`https://api.cloudflare.com/client/v4/accounts/
${
env
.
CLOUDFLARE_ACCOUNT_ID
}
/browser-rendering/screenshot`
;
const
url
=
`
${
origin
}
/site/
${
siteId
}
`
;
const
imageBuffer
=
await
takeScreenshotWithRetry
(
apiUrl
,
url
,
env
.
CLOUDFLARE_API_TOKEN
)
;
if
(
!
imageBuffer
)
{
logger
.
error
(
'Screenshot'
,
'Failed to capture screenshot after retries'
,
{
siteId
}
)
;
return
;
}
try
{
const
screenshotKey
=
`
${
SCREENSHOT_PREFIX
}
${
siteId
}
.png`
;
logger
.
info
(
'Screenshot'
,
'Storing screenshot'
,
{
siteId
,
size
:
imageBuffer
.
byteLength
}
)
;
await
env
.
SCREENSHOTS
.
put
(
screenshotKey
,
imageBuffer
,
{
httpMetadata
:
{
contentType
:
'image/png'
}
,
}
)
;
logger
.
info
(
'Screenshot'
,
'Successfully stored screenshot'
,
{
siteId
}
)
;
await
updateGalleryScreenshot
(
env
,
siteId
,
`/screenshot/
${
siteId
}
.png`
)
;
}
catch
(
error
)
{
const
message
=
error
instanceof
Error
?
error
.
message
:
'Unknown error'
;
logger
.
error
(
'Screenshot'
,
'Failed to store screenshot'
,
{
error
:
message
}
)
;
}
}
function
generateSiteId
(
)
:
string
{
return
crypto
.
randomUUID
(
)
.
replace
(
/
-
/
g
,
''
)
.
slice
(
0
,
8
)
;
}
/**
* Sanitize HTML to prevent XSS attacks
* Removes dangerous patterns while preserving safe inline scripts/styles
*/
function
sanitizeHtml
(
html
:
string
)
:
string
{
let
sanitized
=
html
;
// Remove dangerous event handlers (onclick, onerror, onload, etc.)
sanitized
=
sanitized
.
replace
(
/
\s
+
o
n
\w
+
\s
*
=
\s
*
[
"
'
]
[
^
"
'
]
*
[
"
'
]
/
gi
,
''
)
;
sanitized
=
sanitized
.
replace
(
/
\s
+
o
n
\w
+
\s
*
=
\s
*
[
^
\s
>
]
+
/
gi
,
''
)
;
// Remove javascript: URLs
sanitized
=
sanitized
.
replace
(
/
h
r
e
f
\s
*
=
\s
*
[
"
'
]
j
a
v
a
s
c
r
i
p
t
:
[
^
"
'
]
*
[
"
'
]
/
gi
,
'href="#"'
)
;
sanitized
=
sanitized
.
replace
(
/
s
r
c
\s
*
=
\s
*
[
"
'
]
j
a
v
a
s
c
r
i
p
t
:
[
^
"
'
]
*
[
"
'
]
/
gi
,
''
)
;
// Remove data: URLs in src attributes (potential XSS vector, except for images)
sanitized
=
sanitized
.
replace
(
/
s
r
c
\s
*
=
\s
*
[
"
'
]
d
a
t
a
:
(?
!
i
m
a
g
e
\/
)
[
^
"
'
]
*
[
"
'
]
/
gi
,
''
)
;
// Remove external scripts (keep inline scripts only)
sanitized
=
sanitized
.
replace
(
/
<
s
c
r
i
p
t
[
^
>
]
+
s
r
c
\s
*
=
\s
*
[
"
'
]
[
^
"
'
]
+
[
"
'
]
[
^
>
]
*
>
[
\s
\S
]
*
?
<
\/
s
c
r
i
p
t
>
/
gi
,
''
)
;
// Remove iframes
sanitized
=
sanitized
.
replace
(
/
<
i
f
r
a
m
e
[
^
>
]
*
>
[
\s
\S
]
*
?
<
\/
i
f
r
a
m
e
>
/
gi
,
''
)
;
// Remove object/embed tags
sanitized
=
sanitized
.
replace
(
/
<
o
b
j
e
c
t
[
^
>
]
*
>
[
\s
\S
]
*
?
<
\/
o
b
j
e
c
t
>
/
gi
,
''
)
;
sanitized
=
sanitized
.
replace
(
/
<
e
m
b
e
d
[
^
>
]
*
>
/
gi
,
''
)
;
// Remove base tags (could redirect relative URLs)
sanitized
=
sanitized
.
replace
(
/
<
b
a
s
e
[
^
>
]
*
>
/
gi
,
''
)
;
// Remove meta refresh
sanitized
=
sanitized
.
replace
(
/
<
m
e
t
a
[
^
>
]
*
h
t
t
p
-
e
q
u
i
v
\s
*
=
\s
*
[
"
'
]
?
r
e
f
r
e
s
h
[
"
'
]
?
[
^
>
]
*
>
/
gi
,
''
)
;
return
sanitized
;
}
function
normalizeHtml
(
html
:
string
)
:
string
{
// First sanitize, then normalize
const
sanitized
=
sanitizeHtml
(
html
)
;
const
hasDoc
=
/
<
!
d
o
c
t
y
p
e
h
t
m
l
>
/
i
.
test
(
sanitized
)
;
if
(
hasDoc
)
return
sanitized
;
return
`<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n<title>Generated Site</title>\n</head>\n<body>\n
${
sanitized
}
\n</body>\n</html>`
;
}
/**
* Escape HTML special characters to prevent XSS in dynamic content
*/
function
escapeHtml
(
text
:
string
)
:
string
{
const
htmlEscapes
:
Record
<
string
,
string
>
=
{
'&'
:
'&'
,
'<'
:
'<'
,
'>'
:
'>'
,
'"'
:
'"'
,
"'"
:
'''
,
}
;
return
text
.
replace
(
/
[
&
<
>
"
'
]
/
g
,
char
=>
htmlEscapes
[
char
]
||
char
)
;
}
async
function
safeResponseText
(
response
:
Response
)
:
Promise
<
string
>
{
try
{
return
await
response
.
text
(
)
;
View remainder of file in raw view
Back
|
FazBrowse Home
|
New Git URL