11import bodyParser from "body-parser" ;
22import express , { Request , Response } from "express" ;
3- import { BASE_ONION_ROUTER_PORT } from "../config" ;
3+ import { BASE_ONION_ROUTER_PORT , REGISTRY_PORT } from "../config" ;
4+ import { generateRsaKeyPair , exportPubKey , exportPrvKey } from "../crypto" ;
5+ import { webcrypto } from "node:crypto" ;
6+
7+ type CK = webcrypto . CryptoKey ;
48
59export async function simpleOnionRouter ( nodeId : number ) {
610 const onionRouter = express ( ) ;
711 onionRouter . use ( express . json ( ) ) ;
812 onionRouter . use ( bodyParser . json ( ) ) ;
913
14+ let privateKey : CK ;
15+ let publicKey : CK ;
16+ let privateKeyStr : string ;
17+ let publicKeyStr : string ;
18+
1019 // Store the last received messages and destination (default: null)
1120 let lastReceivedEncryptedMessage : string | null = null ;
1221 let lastReceivedDecryptedMessage : string | null = null ;
1322 let lastMessageDestination : number | null = null ;
1423
24+ try {
25+ const keyPair = await generateRsaKeyPair ( ) ;
26+ privateKey = keyPair . privateKey ;
27+ publicKey = keyPair . publicKey ;
28+
29+ // Convert keys to base64
30+ publicKeyStr = await exportPubKey ( publicKey ) ;
31+ privateKeyStr = await exportPrvKey ( privateKey ) ;
32+
33+ // Register with the registry
34+ const response = await fetch ( `http://localhost:${ REGISTRY_PORT } /registerNode` , {
35+ method : "POST" ,
36+ headers : { "Content-Type" : "application/json" } ,
37+ body : JSON . stringify ( { nodeId, pubKey : publicKeyStr } ) ,
38+ } ) ;
39+
40+ if ( ! response . ok ) {
41+ throw new Error ( `Failed to register node ${ nodeId } ` ) ;
42+ }
43+
44+ console . log ( `Node ${ nodeId } registered successfully` ) ;
45+ } catch ( error ) {
46+ console . error ( "Failed to initialize node:" , error ) ;
47+ throw error ;
48+ }
49+
1550 // Status route
1651 onionRouter . get ( "/status" , ( req : Request , res : Response ) => {
1752 res . send ( "live" ) ;
@@ -32,10 +67,13 @@ export async function simpleOnionRouter(nodeId: number) {
3267 res . json ( { result : lastMessageDestination } ) ;
3368 } ) ;
3469
70+ // Provide private key for testing purposes
71+ onionRouter . get ( "/getPrivateKey" , ( req : Request , res : Response ) => {
72+ res . json ( { result : privateKeyStr } ) ;
73+ } ) ;
74+
3575 const server = onionRouter . listen ( BASE_ONION_ROUTER_PORT + nodeId , ( ) => {
36- console . log (
37- `Onion router ${ nodeId } is listening on port ${ BASE_ONION_ROUTER_PORT + nodeId } `
38- ) ;
76+ console . log ( `Onion router ${ nodeId } is listening on port ${ BASE_ONION_ROUTER_PORT + nodeId } ` ) ;
3977 } ) ;
4078
4179 return server ;
0 commit comments