-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
560 lines (507 loc) · 15.5 KB
/
index.js
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
import { verifySignature } from 'nostr-tools'
import http from 'http'
import https from 'https'
import fs from 'fs'
import url from 'url'
import path from 'path'
/**
* Manages invites for pubkeys to access the server.
* Invites are stored in a JSON file in the root directory.
*/
const INVITES_FILE = 'invites.json'
/**
* Initializes the invites file if it doesn't exist.
*
* @returns {void}
*/
function initInvitesFile () {
if (!fs.existsSync(INVITES_FILE)) {
fs.writeFileSync(INVITES_FILE, JSON.stringify({ invites: [] }, null, 2))
console.log(`Created ${INVITES_FILE}`)
}
}
/**
* Gets the list of invited pubkeys.
*
* @returns {Array<string>} Array of invited pubkeys
*/
function getInvites () {
try {
initInvitesFile()
const data = fs.readFileSync(INVITES_FILE, 'utf8')
return JSON.parse(data).invites || []
} catch (error) {
console.error('Error reading invites file:', error)
return []
}
}
/**
* Checks if a pubkey has been invited.
*
* @param {string} pubkey - The pubkey to check
* @returns {boolean} True if the pubkey is invited, false otherwise
*/
function isInvited (pubkey) {
const invites = getInvites()
return invites.includes(pubkey)
}
/**
* Adds a pubkey to the invites list.
*
* @param {string} pubkey - The pubkey to invite
* @returns {boolean} True if the pubkey was added, false if it was already invited
*/
function addInvite (pubkey) {
try {
const invites = getInvites()
if (invites.includes(pubkey)) {
return false
}
invites.push(pubkey)
fs.writeFileSync(INVITES_FILE, JSON.stringify({ invites }, null, 2))
return true
} catch (error) {
console.error('Error adding invite:', error)
return false
}
}
/**
* Removes a pubkey from the invites list.
*
* @param {string} pubkey - The pubkey to remove
* @returns {boolean} True if the pubkey was removed, false if it wasn't in the list
*/
function removeInvite (pubkey) {
try {
const invites = getInvites()
const index = invites.indexOf(pubkey)
if (index === -1) {
return false
}
invites.splice(index, 1)
fs.writeFileSync(INVITES_FILE, JSON.stringify({ invites }, null, 2))
return true
} catch (error) {
console.error('Error removing invite:', error)
return false
}
}
/**
* Creates a request handler function with the given rootDir, mode, and owners.
*
* @param {string} rootDir - The root directory for all files.
* @param {string} mode - The server mode ('singleuser' or 'multiuser').
* @param {Array<string>} owners - The public keys of the owners (used in 'singleuser' mode).
* @param {boolean} invitesEnabled - Whether the invite system is enabled.
* @returns {function} A request handler function that handles incoming HTTP requests based on the specified rootDir, mode, and owners.
*/
function createRequestHandler (rootDir, mode, owners, invitesEnabled = true) {
return function handleRequest (req, res) {
const { method, url: reqUrl, headers } = req
const { pathname } = url.parse(reqUrl)
const adjustedPathname = pathname.endsWith('/') ? `${pathname}index.html` : pathname
// const targetDir = path.dirname(pathname)
const targetDir = path.dirname(pathname).split(path.sep)[1]
console.log('targetDir', targetDir)
// Set CORS headers
setCorsHeaders(res)
// Handle preflight requests
if (req.method === 'OPTIONS') {
handleOptions(req, res)
} else if (method === 'PUT') {
handlePut(req, res, headers, targetDir, rootDir, pathname, mode, owners, invitesEnabled)
} else if (method === 'GET') {
handleGet(req, res, rootDir, adjustedPathname)
} else if (method === 'POST' && pathname === '/api/invites') {
// Only handle invite management if invites are enabled
if (invitesEnabled) {
handleInviteManagement(req, res, headers, owners)
} else {
res.statusCode = 404
res.end('Not Found: Invite system is disabled')
}
} else {
res.statusCode = 405
res.end('Method not allowed')
console.log('Method not allowed')
}
}
}
/**
* Returns the content type based on the given file extension.
*
* @param {string} ext - The file extension.
* @returns {string} The corresponding content type.
*/
const getContentType = (ext) => {
switch (ext) {
// Text
case '.txt':
return 'text/plain'
case '.html':
case '.htm':
return 'text/html'
case '.json':
return 'application/json'
case '.css':
return 'text/css'
case '.js':
return 'application/javascript'
// Images
case '.jpeg':
case '.jpg':
return 'image/jpeg'
case '.png':
return 'image/png'
case '.gif':
return 'image/gif'
case '.bmp':
return 'image/bmp'
case '.svg':
return 'image/svg+xml'
case '.ico':
return 'image/x-icon'
case '.webp':
return 'image/webp'
// Audio
case '.mp3':
return 'audio/mpeg'
case '.wav':
return 'audio/wav'
case '.ogg':
return 'audio/ogg'
case '.m4a':
return 'audio/mp4'
case '.flac':
return 'audio/flac'
case '.m3u':
return 'audio/x-mpegurl'
case '.m3u8':
return 'application/vnd.apple.mpegurl'
case '.pls':
return 'audio/x-scpls'
case '.xspf':
return 'application/xspf+xml'
case '.asx':
return 'video/x-ms-asf'
case '.wpl':
return 'application/vnd.ms-wpl'
// Video
case '.mp4':
return 'video/mp4'
case '.webm':
return 'video/webm'
case '.ogv':
return 'video/ogg'
case '.mov':
return 'video/quicktime'
case '.avi':
return 'video/x-msvideo'
// Other
case '.ttl':
return 'text/turtle'
case '.jsonld':
return 'application/ld+json'
case '.md':
return 'text/markdown'
// this is for the my-mind mindmapping app
case '.mymind':
return 'application/json'
// Default
default:
return 'text/html'
}
}
/**
* Checks if the target directory is valid based on the given nostr value.
*
* @param {string} targetDir - The target directory.
* @param {string} nostr - The nostr value.
* @param {string} mode - The server mode ('singleuser' or 'multiuser').
* @returns {boolean} True if the target directory is valid, false otherwise.
*/
const isValidTargetDir = (targetDir, nostr, mode) => {
if (mode === 'singleuser') {
// In single user mode, use a fixed subdirectory to store all files
return true
} else {
// In multiuser mode, each user has their own subdirectory
const targetSegments = targetDir
.split('/')
.filter(segment => segment !== '')
return targetSegments.length === 1 && targetSegments[0] === nostr
}
}
/**
* Sets CORS headers for the given response object.
*
* @param {http.ServerResponse} res - The response object.
*/
function setCorsHeaders (res) {
res.setHeader('Access-Control-Allow-Origin', '*')
res.setHeader('Access-Control-Allow-Methods', 'GET, PUT, OPTIONS')
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization')
// Set the X-Powered-By header
res.setHeader('X-Powered-By', 'nosdav/alpha')
}
/**
* Validates the authorization header and returns the public key if valid.
*
* @param {string} authorization - The authorization header value.
* @returns {(string|null)} The public key if the header is valid, null otherwise.
*/
function isValidAuthorizationHeader (authorization) {
console.log('authorization', authorization)
const base64String = authorization.replace('Nostr ', '')
// Decode the base64-encoded string and parse the JSON object
const decodedString = Buffer.from(base64String, 'base64').toString('utf-8')
const event = JSON.parse(decodedString)
// Print the object
console.log(event)
const isVerified = verifySignature(event)
if (isVerified) {
return event.pubkey
}
}
/**
* Handles preflight OPTIONS requests and sets CORS options.
*
* @param {http.IncomingMessage} req - The request object.
* @param {http.ServerResponse} res - The response object.
*/
function handleOptions (req, res) {
// Set CORS options
const corsOptions = {
origin: 'https://example.com',
methods: ['GET', 'PUT'],
allowedHeaders: ['Content-Type']
}
res.writeHead(204, corsOptions)
res.end()
}
/**
* Handles PUT requests to save a file to the server.
*
* @param {http.IncomingMessage} req - The request object.
* @param {http.ServerResponse} res - The response object.
* @param {Object} headers - The request headers.
* @param {string} targetDir - The target directory for saving the file.
* @param {string} rootDir - The root directory for all files.
* @param {string} pathname - The target file's path.
* @param {string} mode - The server mode ('singleuser' or 'multiuser').
* @param {Array<string>} owners - The public keys of the owners (used in 'singleuser' mode).
* @param {boolean} invitesEnabled - Whether the invite system is enabled.
*/
function handlePut (
req,
res,
headers,
targetDir,
rootDir,
pathname,
mode,
owners,
invitesEnabled = true
) {
const nostr = headers?.authorization?.replace('Nostr ', '')
console.log('nostr auth header', nostr)
const pubkey = isValidAuthorizationHeader(headers.authorization)
if (!nostr || !pubkey) {
res.statusCode = 401
res.end(
'Unauthorized: "nostr" header must a signed nostr event base64 encoded'
)
console.log(
'Unauthorized: "nostr" header must a signed nostr event base64 encoded'
)
return
}
// check pubkey
if (mode === 'singleuser') {
if (!owners.includes(pubkey)) {
res.statusCode = 403
res.end('Forbidden: wrong owner')
console.error('Forbidden: wrong owner', owners, pubkey)
return
}
} else {
if (targetDir !== pubkey) {
res.statusCode = 403
res.end('Forbidden: wrong pubkey')
console.error('Forbidden: wrong pubkey', targetDir, pubkey)
return
}
// Check if the pubkey is invited for multiuser mode
// Only check when creating a top-level directory and invites are enabled
const pubkeyDirPath = path.join(rootDir, pubkey)
const isCreatingPubkeyDir = !fs.existsSync(pubkeyDirPath)
if (invitesEnabled && isCreatingPubkeyDir && !isInvited(pubkey) && !owners.includes(pubkey)) {
res.statusCode = 403
res.end('Forbidden: You need an invite to create a directory')
console.error('Forbidden: Uninvited pubkey', pubkey)
return
}
}
// Check if the target directory is valid
if (!isValidTargetDir(targetDir, pubkey, mode)) {
res.statusCode = 403
res.end('Forbidden: Target directory structure is invalid')
console.log(
'Forbidden: Target directory structure is invalid',
targetDir,
nostr
)
return
}
const targetPath = path.isAbsolute(rootDir)
? path.join(rootDir, pathname)
: path.join('.', rootDir, pathname)
// Check if the target path is within the root directory
const resolvedRootDir = path.resolve(rootDir)
if (mode === 'singleuser') {
if (!path.resolve(targetPath).startsWith(resolvedRootDir)) {
res.statusCode = 403
res.end('Forbidden: Target path is outside the root directory')
console.log('Forbidden: Target path is outside the root directory', targetPath, rootDir, mode)
return
}
} else if (mode === 'multiuser') {
const resolvedPubKeyDir = path.resolve(rootDir, pubkey)
if (!path.resolve(targetPath).startsWith(resolvedPubKeyDir)) {
res.statusCode = 403
res.end('Forbidden: Target path is outside the user directory')
console.log('Forbidden: Target path is outside the user directory', targetPath, resolvedPubKeyDir, mode)
return
}
}
// Ensure target directory exists
fs.mkdir(path.dirname(targetPath), { recursive: true }, err => {
if (err) {
console.error(err)
res.statusCode = 500
res.end('Error creating directory')
console.log('Error creating directory')
return
}
// Save the file
const writeStream = fs.createWriteStream(targetPath)
req.pipe(writeStream)
writeStream.on('finish', () => {
res.statusCode = 201
res.end('File created')
console.log('File created', targetPath)
})
writeStream.on('error', err => {
console.error(err)
res.statusCode = 500
res.end('Error writing file')
console.log('Error writing file')
})
})
}
/**
* Handles GET requests to read and return the contents of a file.
*
* @param {http.IncomingMessage} req - The request object.
* @param {http.ServerResponse} res - The response object.
* @param {string} pathname - The requested file's path.
* @param {string} rootDir - The root directory for all files.
*/
function handleGet (req, res, rootDir, pathname) {
const targetPath = rootDir.startsWith('/')
? path.join(rootDir, pathname)
: path.join('.', rootDir, pathname)
// Read the file
fs.readFile(targetPath, (err, data) => {
if (err) {
console.error(err)
res.statusCode = 404
res.end('File not found')
console.log('File not found')
} else {
const contentType = getContentType(path.extname(targetPath))
res.setHeader('Content-Type', contentType)
res.statusCode = 200
res.end(data)
}
})
}
/**
* Handles invite management API requests.
*
* @param {http.IncomingMessage} req - The request object.
* @param {http.ServerResponse} res - The response object.
* @param {Object} headers - The request headers.
* @param {Array<string>} owners - The public keys of the owners.
*/
function handleInviteManagement (req, res, headers, owners) {
const pubkey = isValidAuthorizationHeader(headers.authorization)
if (!pubkey) {
res.statusCode = 401
res.end('Unauthorized: Valid authorization header required')
console.log('Unauthorized: Valid authorization header required')
return
}
// Only owners can manage invites
if (!owners.includes(pubkey)) {
res.statusCode = 403
res.end('Forbidden: Only owners can manage invites')
console.error('Forbidden: Non-owner tried to manage invites', pubkey)
return
}
// Parse the request body
let body = ''
req.on('data', chunk => {
body += chunk.toString()
})
req.on('end', () => {
try {
const data = JSON.parse(body)
const { action, targetPubkey } = data
if (!targetPubkey) {
res.statusCode = 400
res.end('Bad Request: targetPubkey is required')
return
}
let result = false
let message = ''
switch (action) {
case 'add':
result = addInvite(targetPubkey)
message = result ? 'Invite added' : 'Pubkey already invited'
break
case 'remove':
result = removeInvite(targetPubkey)
message = result ? 'Invite removed' : 'Pubkey not found in invites'
break
case 'list':
const invites = getInvites()
res.statusCode = 200
res.setHeader('Content-Type', 'application/json')
res.end(JSON.stringify({ invites }))
return
default:
res.statusCode = 400
res.end('Bad Request: Invalid action')
return
}
res.statusCode = 200
res.setHeader('Content-Type', 'application/json')
res.end(JSON.stringify({ success: result, message }))
} catch (error) {
console.error('Error processing invite management request:', error)
res.statusCode = 400
res.end('Bad Request: Invalid JSON')
}
})
}
export {
getContentType,
setCorsHeaders,
isValidAuthorizationHeader,
isValidTargetDir,
handleOptions,
handlePut,
handleGet,
createRequestHandler
}