1
+ import { escapeCSS } from "@bots-gg/markup" ;
2
+
1
3
const parseHex = ( hex : string ) => {
2
4
const buf = new ArrayBuffer ( hex . length / 2 ) ;
3
5
const bufView = new Uint8Array ( buf ) ;
@@ -24,6 +26,11 @@ const parseB64 = (b64: string) => {
24
26
return buf ;
25
27
}
26
28
29
+ const getMimeType = ( contentType : string | undefined ) =>
30
+ contentType ?. includes ( ";" )
31
+ ? contentType . split ( ";" ) [ 0 ] . trim ( )
32
+ : contentType ?. trim ( ) ;
33
+
27
34
export default {
28
35
async fetch ( request : Request , { PUBLIC_KEY } : { PUBLIC_KEY : string } ) : Promise < Response > {
29
36
const userAgent = request . headers . get ( 'User-Agent' ) ;
@@ -68,8 +75,42 @@ export default {
68
75
const requestedUrl = new URL ( subUrl , url . origin ) ;
69
76
70
77
const resp = await fetch ( requestedUrl . toString ( ) , { headers : new Headers ( { 'User-Agent' : userAgent } ) } ) ;
71
- const newResp = new Response ( resp . body , resp ) ; // ??
72
- newResp . headers . set ( "Content-Security-Policy" , "default-src: 'self';" )
78
+
79
+ let body : Response [ 'body' ] | string = resp . body ;
80
+ console . log ( { "content-type" : resp . headers . get ( "Content-Type" ) ?. toLowerCase ( ) } ) ;
81
+ if ( getMimeType ( resp . headers . get ( "Content-Type" ) ?. toLowerCase ( ) ) === "text/css" ) {
82
+ // this sucks...
83
+ const text = await resp . text ( ) ;
84
+ const urls : string [ ] = [ ] ;
85
+ escapeCSS ( text , ( url : string ) => {
86
+ urls . push ( url ) ;
87
+ return url ;
88
+ } ) ;
89
+
90
+ let giveUp = false ;
91
+ const responses = await Promise . all ( urls . map ( async ( url ) => {
92
+ const otherResp = await fetch ( ( new URL ( url , request . url ) ) ) ;
93
+ const mimeType = getMimeType ( otherResp . headers . get ( "Content-Type" ) ?. toLowerCase ( ) ) ;
94
+ if ( mimeType === "text/css" ) {
95
+ giveUp = true ;
96
+ }
97
+ // *smug smirk*
98
+ return `data:${ mimeType } ;base64,${ btoa ( await otherResp . text ( ) ) } ` ;
99
+ } ) ) ;
100
+
101
+ if ( giveUp ) {
102
+ return new Response ( "You suck." ) ;
103
+ }
104
+
105
+ const urlMap = Object . fromEntries ( urls . map ( ( url , i ) => [ url , i ] ) ) ;
106
+
107
+ body = escapeCSS ( text , ( url : string ) => responses [ urlMap [ url ] ] ) ;
108
+ }
109
+
110
+ const newResp = new Response ( body , resp ) ; // :(
111
+ newResp . headers . set ( "Content-Security-Policy" , "default-src: 'self';" ) ;
112
+ newResp . headers . set ( "X-Content-Type-Options" , "nosniff" ) ;
113
+
73
114
return newResp ;
74
115
}
75
116
} ;
0 commit comments