-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathnodeico-fastify.js
More file actions
383 lines (323 loc) · 11 KB
/
nodeico-fastify.js
File metadata and controls
383 lines (323 loc) · 11 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
import path from 'path'
import fs from 'fs'
import Fastify from 'fastify'
import bole from 'bole'
import { fileURLToPath } from 'url'
import { randomUUID } from 'crypto'
// Modern route implementations
import optionParser from './lib/option-parser.js'
import validName from './lib/valid-name.js'
import pkginfo from './lib/pkginfo.js'
import calculateParams from './lib/badge-params.js'
import npmRegistry from './lib/npm-registry.js'
import { renderBadge, renderIndex, renderUser } from './lib/templates.js'
const __dirname = path.dirname(fileURLToPath(import.meta.url))
const reqLog = bole('server:request')
const start = new Date()
// No template engine needed - using native template strings
export default function createServer () {
const fastify = Fastify({
logger: false // We use bole for logging
})
// Security headers
fastify.addHook('onSend', async (request, reply) => {
reply.header('X-Content-Type-Options', 'nosniff')
reply.header('X-Frame-Options', 'DENY')
reply.header('X-XSS-Protection', '1; mode=block')
reply.header('Referrer-Policy', 'no-referrer')
// CSP for HTML pages
if (reply.getHeader('content-type')?.includes('text/html')) {
reply.header('Content-Security-Policy', "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'self'")
}
})
// Request logging middleware
fastify.addHook('onRequest', async (request, reply) => {
request.reqLog = reqLog(randomUUID())
// Log request details
request.reqLog.info({
method: request.method,
url: request.url,
ip: request.ip,
userAgent: request.headers['user-agent']
})
reply.header('x-startup', start)
reply.header('x-powered-by', 'whatevs')
})
// Response logging
fastify.addHook('onResponse', async (request, reply) => {
request.reqLog.info({
statusCode: reply.statusCode,
responseTime: reply.elapsedTime
})
})
// Static file serving
fastify.register(import('@fastify/static'), {
root: path.join(__dirname, 'public'),
prefix: '/'
})
// Health check
fastify.get('/_status', async (request, reply) => {
return 'OK'
})
// Main index page
fastify.get('/', async (request, reply) => {
reply.type('text/html')
return renderIndex()
})
// Script route
fastify.get('/js/script.js', async (request, reply) => {
const scriptPath = path.join(__dirname, 'public/badge-generator.js')
const content = await fs.promises.readFile(scriptPath, 'utf8')
reply.type('text/javascript')
reply.header('cache-control', 'no-cache')
return content
})
// NPM package info API - supports scoped packages
fastify.get('/api/npm/info/:scope/:pkg', async (request, reply) => {
const pkg = `${request.params.scope}/${request.params.pkg}`
if (!validName(pkg)) {
reply.code(400)
return { error: `Invalid package name: ${pkg}` }
}
try {
const data = await npmRegistry.getPackageInfo(pkg, {})
if (!data) {
reply.code(404)
return { error: `Package not found: ${pkg}` }
}
reply.header('cache-control', 'no-cache')
return data
} catch (error) {
request.reqLog.error({
error: error.message,
package: pkg,
route: 'api-info-scoped'
})
if (error.message.includes('404')) {
reply.code(404)
return { error: `Package not found: ${pkg}` }
}
reply.code(500)
return { error: error.message }
}
})
// NPM package info API - for regular packages
fastify.get('/api/npm/info/:pkg', async (request, reply) => {
const { pkg } = request.params
if (!validName(pkg)) {
reply.code(400)
return { error: `Invalid package name: ${pkg}` }
}
try {
const data = await npmRegistry.getPackageInfo(pkg, {})
if (!data) {
reply.code(404)
return { error: `Package not found: ${pkg}` }
}
reply.header('cache-control', 'no-cache')
return data
} catch (error) {
request.reqLog.error({
error: error.message,
package: pkg,
route: 'api-info'
})
if (error.message.includes('404')) {
reply.code(404)
return { error: `Package not found: ${pkg}` }
}
reply.code(500)
return { error: error.message }
}
})
// Legacy download histogram routes - return transparent 1x1 pixel
const transparent1x1PNG = Buffer.from(
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==',
'base64'
)
// Handle /npm-dl/* routes for backwards compatibility
fastify.get('/npm-dl/:pkg.png', async (request, reply) => {
const { pkg } = request.params
request.reqLog.info({
message: 'Legacy download histogram request',
package: pkg,
route: 'npm-dl'
})
reply.type('image/png')
reply.header('cache-control', 'public, max-age=86400') // Cache for 1 day
reply.header('x-deprecated', 'Download histograms are no longer available. This endpoint returns a transparent 1x1 pixel for backwards compatibility.')
return transparent1x1PNG
})
// Handle scoped packages in download routes
fastify.get('/npm-dl/:scope/:pkg.png', async (request, reply) => {
const pkg = `${request.params.scope}/${request.params.pkg}`
request.reqLog.info({
message: 'Legacy download histogram request',
package: pkg,
route: 'npm-dl-scoped'
})
reply.type('image/png')
reply.header('cache-control', 'public, max-age=86400') // Cache for 1 day
reply.header('x-deprecated', 'Download histograms are no longer available. This endpoint returns a transparent 1x1 pixel for backwards compatibility.')
return transparent1x1PNG
})
// Badge route (SVG and PNG) - supports scoped packages like @org/package
fastify.get('/npm/:scope/:pkg.svg', async (request, reply) => {
const pkg = `${request.params.scope}/${request.params.pkg}`
return handleBadgeRequest({ ...request, params: { pkg } }, reply, 'svg')
})
fastify.get('/npm/:scope/:pkg.png', async (request, reply) => {
const pkg = `${request.params.scope}/${request.params.pkg}`
return handleBadgeRequest({ ...request, params: { pkg } }, reply, 'png')
})
// Badge route (SVG and PNG) - for regular packages
fastify.get('/npm/:pkg.svg', async (request, reply) => {
return handleBadgeRequest(request, reply, 'svg')
})
fastify.get('/npm/:pkg.png', async (request, reply) => {
return handleBadgeRequest(request, reply, 'png')
})
// User packages route
fastify.get('/~:user', async (request, reply) => {
const { user } = request.params
// Validate username - npm usernames are similar to package names
if (!user || !/^[a-z0-9._-]+$/i.test(user) || user.length > 100) {
reply.code(400)
return { error: `Invalid username: ${user}` }
}
try {
const packages = await npmRegistry.getUserPackagesWithDetails(user)
if (!packages || !packages.length) {
reply.code(404)
return { error: `No packages found for user: ${user}` }
}
const html = renderUser(user, packages)
reply.type('text/html')
reply.header('cache-control', 'no-cache')
return html
} catch (error) {
request.reqLog.error({
error: error.message,
user,
route: 'user-packages'
})
if (error.message.includes('404')) {
reply.code(404)
return { error: `No packages found for user: ${user}` }
}
reply.code(500)
return { error: error.message }
}
})
// Package info page - supports scoped packages
fastify.get('/npm/:scope/:pkg/', async (request, reply) => {
const pkg = `${request.params.scope}/${request.params.pkg}`
if (!validName(pkg)) {
reply.code(400)
return { error: `Invalid package name: ${pkg}` }
}
try {
const data = await npmRegistry.getPackageInfo(pkg, {})
if (!data) {
reply.code(404)
return { error: `Package not found: ${pkg}` }
}
// Simple redirect to main page with hash
reply.redirect(`/#${encodeURIComponent(pkg)}`, 302)
} catch (error) {
request.reqLog.error({
error: error.message,
package: pkg,
route: 'package-redirect-scoped'
})
if (error.message.includes('404')) {
reply.code(404)
return { error: `Package not found: ${pkg}` }
}
reply.code(500)
return { error: error.message }
}
})
// Package info page - for regular packages
fastify.get('/npm/:pkg/', async (request, reply) => {
const { pkg } = request.params
if (!validName(pkg)) {
reply.code(400)
return { error: `Invalid package name: ${pkg}` }
}
try {
const data = await npmRegistry.getPackageInfo(pkg, {})
if (!data) {
reply.code(404)
return { error: `Package not found: ${pkg}` }
}
// Simple redirect to main page with hash
reply.redirect(`/#${pkg}`, 302)
} catch (error) {
request.reqLog.error({
error: error.message,
package: pkg,
route: 'package-redirect'
})
if (error.message.includes('404')) {
reply.code(404)
return { error: `Package not found: ${pkg}` }
}
reply.code(500)
return { error: error.message }
}
})
// Badge request handler
async function handleBadgeRequest (request, reply, format) {
const { pkg } = request.params
const options = optionParser(request.raw)
if (!validName(pkg)) {
reply.code(400)
return { error: `Invalid package name: ${pkg}` }
}
try {
const packageInfo = await pkginfo(request.reqLog, pkg, options)
// For shields/flat styles, we need to handle dimensions differently
const styleName = options.style || 'standard'
let params
if (['shields', 'flat', 'flat-square'].includes(styleName)) {
// These styles calculate their own dimensions
const { getBadgeStyle } = await import('./lib/badge-styles/index.js')
const style = getBadgeStyle(styleName)
if (style.calculateDimensions) {
params = style.calculateDimensions(packageInfo, options)
} else {
params = {} // Minimal params for new styles
}
} else {
// Legacy styles use calculateParams
params = calculateParams(options, packageInfo)
}
const ctx = {
options,
pkginfo: packageInfo,
params
}
reply.header('cache-control', 'no-cache')
reply.type('image/svg+xml')
// Add deprecation header for PNG requests
if (format === 'png') {
reply.header('x-deprecated', 'PNG badges are deprecated. Please use .svg extension instead.')
}
return renderBadge(ctx)
} catch (error) {
request.reqLog.error({
error: error.message,
package: pkg,
route: 'badge'
})
if (error.message.includes('404')) {
reply.code(404)
return { error: `Package not found: ${pkg}` }
}
reply.code(500)
return { error: error.message }
}
}
return fastify
}