-
Notifications
You must be signed in to change notification settings - Fork 39
/
Copy pathassets.ts
137 lines (116 loc) · 3.94 KB
/
assets.ts
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
import type { BaseServer } from '@logux/server'
import { createHash } from 'node:crypto'
import { existsSync, statSync } from 'node:fs'
import { readFile } from 'node:fs/promises'
import type { ServerResponse } from 'node:http'
import { extname, join, normalize } from 'node:path'
import { config } from '../lib/config.ts'
interface Asset {
contentType: string
data: Buffer
headers: Record<string, string>
}
const ASSETS_DIR = join(import.meta.dirname, '..', '..', 'web', 'dist')
const ROUTES = join(import.meta.dirname, '..', '..', 'web', 'routes.regexp')
const MIME_TYPES: Record<string, string> = {
'.avif': 'image/avif',
'.css': 'text/css',
'.html': 'text/html',
'.ico': 'image/x-icon',
'.jpg': 'image/jpeg',
'.js': 'application/javascript',
'.json': 'application/json',
'.png': 'image/png',
'.svg': 'image/svg+xml',
'.txt': 'text/plain',
'.webmanifest': 'application/manifest+json',
'.woff2': 'font/woff2'
}
const CONTENT_SECURITY_POLICIES: Record<string, string> = {
'base-uri': "'none'",
'form-action': "'none'",
'frame-ancestors': "'none'",
'object-src': "'none'",
'script-src': "'self'",
'style-src': "'self'"
}
const HASHED = /-[\w]{8}\.\w+$/
function hash(body: string): string {
return `'sha256-${createHash('sha256').update(body).digest('base64')}'`
}
function getPageHeaders(data: Buffer): Asset['headers'] {
let headers: Asset['headers'] = {
'Strict-Transport-Security': 'max-age=31536000; includeSubDomains; preload',
'X-Content-Type-Options': 'nosniff'
}
let html = data.toString()
let csp = { ...CONTENT_SECURITY_POLICIES }
let css = html.match(/<style>([\s\S]*?)<\/style>/)
if (css) csp['style-src'] += ' ' + hash(css[1]!)
let js = html.match(/<script>([\s\S]*?)<\/script>/)
if (js) csp['script-src'] += ' ' + hash(js[1]!)
headers['Content-Security-Policy'] = Object.entries(csp)
.map(([k, v]) => `${k} ${v}`)
.join('; ')
return headers
}
function send(res: ServerResponse, asset: Asset): void {
for (let [header, value] of Object.entries(asset.headers)) {
res.setHeader(header, value)
}
res.writeHead(200, { 'Content-Type': asset.contentType })
res.end(asset.data)
}
export default async (
server: BaseServer,
{ assets } = config,
assetsDir = ASSETS_DIR,
routes = ROUTES
): Promise<void> => {
if (!assets) return
server.logger.info('Assets serving is enabled')
// Headers/redirect logics is duplicated between this file and web/nginx.conf.
// If you change anything here, change the second place too.
let CACHE: Record<string, Asset> = {}
let html = await readFile(join(assetsDir, 'index.html'))
let appHtml: Asset = {
contentType: 'text/html',
data: html,
headers: getPageHeaders(html)
}
let routesData = await readFile(routes)
let routesRegexp = new RegExp(routesData.toString())
server.http(async (req, res) => {
if (req.method !== 'GET') return false
let url = new URL(req.url!, `https://${req.headers.host}`)
let pathname = url.pathname.replace(/\/$/, '')
let safe = normalize(url.pathname).replace(/^(\.\.[/\\])+/, '')
let cacheKey = safe
let path = join(assetsDir, safe)
if (routesRegexp.test(pathname)) {
send(res, appHtml)
return true
}
if (!CACHE[cacheKey]) {
if (!existsSync(path)) return false
if (statSync(path).isDirectory()) {
path = join(path, 'index.html')
}
let contentType = MIME_TYPES[extname(path)] || 'application/octet-stream'
let data = await readFile(path)
let headers: Asset['headers'] = {}
if (pathname.includes('/assets/') && HASHED.test(path)) {
headers['Cache-Control'] = 'public, max-age=31536000, immutable'
}
if (contentType === 'text/html' && !pathname.includes('/ui')) {
headers = getPageHeaders(data)
}
CACHE[cacheKey] = { contentType, data, headers }
}
send(res, CACHE[cacheKey])
return true
})
server.http('GET', '/', (req, res) => {
send(res, appHtml)
})
}