2024-01-03 17:32:10 +07:00
const { version } = require ( "./package.json" ) ;
2023-10-31 14:02:14 +07:00
const WebSocket = require ( "ws" ) ;
const config = require ( "./config" ) ;
const http = require ( "http" ) ;
2023-11-18 16:49:20 +07:00
const bouncer = require ( ` ./bouncer.js ` ) ;
2023-10-31 14:02:14 +07:00
// For log
const curD = _ => ( new Date ( ) ) . toLocaleString ( "ia" ) ;
const log = _ => console . log ( process . pid , curD ( ) , "-" , _ ) ;
// Server
2024-01-04 13:36:14 +07:00
const server = http . createServer ( { noDelay : true } )
2023-10-31 14:02:14 +07:00
const wss = new WebSocket . WebSocketServer ( { noServer : true } ) ;
server . on ( 'request' , ( req , res ) => {
log ( ` ${ req . headers [ "x-forwarded-for" ] ? . split ( "," ) [ 0 ] || req . socket . address ( ) ? . address } - ${ req . method } ${ req . url } ` )
2023-11-13 18:32:29 +07:00
if ( req . headers . accept ? . includes ( "application/nostr+json" ) )
2023-10-31 14:02:14 +07:00
return res . writeHead ( 200 , {
2023-11-13 18:32:29 +07:00
"Content-Type" : "application/json" ,
"Access-Control-Allow-Origin" : "*"
2023-10-31 14:02:14 +07:00
} ) . end ( JSON . stringify ( config . server _meta ) ) ;
if ( req . url === "/" ) {
2023-11-13 18:35:50 +07:00
res . writeHead ( 200 , {
"Content-Type" : "text/plain"
} ) ;
2023-10-31 14:02:14 +07:00
res . write ( "Hello. This nostr bouncer (bostr) is bouncing the following relays:\n\n" ) ;
config . relays . forEach ( _ => {
res . write ( "- " + _ + "\n" ) ;
} ) ;
2023-10-31 20:01:22 +07:00
2023-10-31 20:09:03 +07:00
res . write ( ` \n I have ${ wss . clients . size } clients currently connected to this bouncer ${ ( process . env . CLUSTERS || config . clusters ) > 1 ? " on this cluster" : "" } . \n ` ) ;
2023-11-16 21:53:58 +07:00
if ( config ? . authorized _keys ? . length ) res . write ( "\nNOTE: This relay has configured for personal use only. Only authorized users could use this bostr relay.\n" ) ;
2023-11-21 15:15:11 +07:00
res . write ( ` \n Connect to this bouncer with nostr client: ws:// ${ req . headers . host } ${ req . url } or wss:// ${ req . headers . host } ${ req . url } \n \n --- \n ` ) ;
2024-01-03 17:32:10 +07:00
res . end ( ` Powered by Bostr ( ${ version } ) - Open source Nostr bouncer \n https://github.com/Yonle/bostr ` ) ;
2023-10-31 14:02:14 +07:00
} else {
res . writeHead ( 404 ) . end ( "What are you looking for?" ) ;
}
} ) ;
server . on ( 'upgrade' , ( req , sock , head ) => {
2023-11-18 16:49:20 +07:00
wss . handleUpgrade ( req , sock , head , _ => bouncer ( _ , req ) ) ;
2023-10-31 14:02:14 +07:00
} ) ;
const listened = server . listen ( process . env . PORT || config . port , config . address || "0.0.0.0" , _ => {
log ( "Bostr is now listening on " + "ws://" + ( config . address || "0.0.0.0" ) + ":" + config . port ) ;
} ) ;