From 710c9fa269938975b75b9eeac0941600578d65a6 Mon Sep 17 00:00:00 2001 From: Audric Ackermann Date: Fri, 30 Apr 2021 09:57:24 +1000 Subject: [PATCH] fix http request over onion --- config/default.json | 12 +- js/background.js | 7 +- libloki/crypto.d.ts | 5 +- libloki/crypto.js | 5 +- libloki/storage.js | 19 --- preload.js | 4 +- .../session/SessionJoinableDefaultRooms.tsx | 4 +- ts/data/data.ts | 14 +-- ts/models/conversation.ts | 1 - ts/opengroup/opengroupV2/ApiUtil.ts | 21 ++-- ts/opengroup/opengroupV2/JoinOpenGroupV2.ts | 6 +- ts/opengroup/opengroupV2/OpenGroupAPIV2.ts | 17 +-- .../opengroupV2/OpenGroupAPIV2CompactPoll.ts | 5 - .../opengroupV2/OpenGroupManagerV2.ts | 2 - .../opengroupV2/OpenGroupServerPoller.ts | 1 - ts/opengroup/utils/OpenGroupUtils.ts | 2 +- ts/session/onions/index.ts | 4 +- ts/session/onions/onionSend.ts | 35 ++++-- ts/session/snode_api/onions.ts | 115 +++++++++--------- ts/session/snode_api/serviceNodeAPI.ts | 1 - ts/session/snode_api/swarmPolling.ts | 3 +- 21 files changed, 130 insertions(+), 153 deletions(-) delete mode 100644 libloki/storage.js diff --git a/config/default.json b/config/default.json index ecceca01e..3b0de9452 100644 --- a/config/default.json +++ b/config/default.json @@ -5,16 +5,8 @@ "contentProxyUrl": "", "seedNodeList": [ { - "ip_url": "http://116.203.53.213:4433/", - "url": "https://storage.seed1.loki.network:4433/" - }, - { - "ip_url": "http://212.199.114.66:4433/", - "url": "https://storage.seed3.loki.network:4433/" - }, - { - "ip_url": "http://144.76.164.202:4433/", - "url": "https://public.loki.foundation:4433/" + "url": "http://public.loki.foundation:38157/", + "ip_url": "http://144.76.164.202:38157/" } ], "updatesEnabled": false, diff --git a/js/background.js b/js/background.js index de74ed7e8..8ddff19e7 100644 --- a/js/background.js +++ b/js/background.js @@ -126,9 +126,10 @@ // If already exists we registered as a secondary device if (!window.lokiFileServerAPI) { window.lokiFileServerAPIFactory = new window.LokiFileServerAPI(ourKey); - window.lokiFileServerAPI = window.lokiFileServerAPIFactory.establishHomeConnection( - window.getDefaultFileServer() - ); + // FIXME audric + // window.lokiFileServerAPI = window.lokiFileServerAPIFactory.establishHomeConnection( + // window.getDefaultFileServer() + // ); } window.initialisedAPI = true; diff --git a/libloki/crypto.d.ts b/libloki/crypto.d.ts index 2de3701fe..fdd17e1d0 100644 --- a/libloki/crypto.d.ts +++ b/libloki/crypto.d.ts @@ -6,7 +6,10 @@ export interface CryptoInterface { EncryptAESGCM: any; // AES-GCM _decodeSnodeAddressToPubKey: any; decryptToken: any; - encryptForPubkey: any; + encryptForPubkey: ( + publicKey: string, + data: Uint8Array + ) => Promise<{ ciphertext: Uint8Array; symmetricKey: ArrayBuffer; ephemeralKey: ArrayBuffer }>; generateEphemeralKeyPair: any; sha512: any; } diff --git a/libloki/crypto.js b/libloki/crypto.js index 54d089878..95ebced13 100644 --- a/libloki/crypto.js +++ b/libloki/crypto.js @@ -50,13 +50,11 @@ return symmetricKey; } + // encryptForPubkey: string, payloadBytes: Uint8Array async function encryptForPubkey(pubkeyX25519, payloadBytes) { const ephemeral = await libloki.crypto.generateEphemeralKeyPair(); - const snPubkey = StringView.hexToArrayBuffer(pubkeyX25519); - const symmetricKey = await deriveSymmetricKey(snPubkey, ephemeral.privKey); - const ciphertext = await EncryptAESGCM(symmetricKey, payloadBytes); return { ciphertext, symmetricKey, ephemeralKey: ephemeral.pubKey }; @@ -86,7 +84,6 @@ async function DecryptAESGCM(symmetricKey, ivAndCiphertext) { const nonce = ivAndCiphertext.slice(0, NONCE_LENGTH); const ciphertext = ivAndCiphertext.slice(NONCE_LENGTH); - const key = await crypto.subtle.importKey('raw', symmetricKey, { name: 'AES-GCM' }, false, [ 'decrypt', ]); diff --git a/libloki/storage.js b/libloki/storage.js deleted file mode 100644 index 2f886c21e..000000000 --- a/libloki/storage.js +++ /dev/null @@ -1,19 +0,0 @@ -/* global window */ - -// eslint-disable-next-line func-names -(function() { - window.libloki = window.libloki || {}; - - function getGuardNodes() { - return window.Signal.Data.getGuardNodes(); - } - - function updateGuardNodes(nodes) { - return window.Signal.Data.updateGuardNodes(nodes); - } - - window.libloki.storage = { - getGuardNodes, - updateGuardNodes, - }; -})(); diff --git a/preload.js b/preload.js index 064f224c6..ea93ff531 100644 --- a/preload.js +++ b/preload.js @@ -49,7 +49,9 @@ window.getServerTrustRoot = () => config.serverTrustRoot; window.JobQueue = JobQueue; window.isBehindProxy = () => Boolean(config.proxyUrl); -window.getStoragePubKey = key => (window.isDev() ? key.substring(0, key.length - 2) : key); +// FIXME audric +window.getStoragePubKey = key => + window.isDev() ? key.substring(0, key.length - 2) : key.substring(0, key.length - 2); window.getDefaultFileServer = () => config.defaultFileServer; window.initialisedAPI = false; diff --git a/ts/components/session/SessionJoinableDefaultRooms.tsx b/ts/components/session/SessionJoinableDefaultRooms.tsx index db150d1a6..74ae4ac49 100644 --- a/ts/components/session/SessionJoinableDefaultRooms.tsx +++ b/ts/components/session/SessionJoinableDefaultRooms.tsx @@ -36,7 +36,7 @@ const SessionJoinableRoomAvatar = (props: JoinableRoomProps) => { }); } } catch (e) { - console.warn(e); + window.log.warn(e); } }, [props.imageId, props.completeUrl]); return ( @@ -72,7 +72,7 @@ export const SessionJoinableRooms = () => { const joinableRooms = useSelector((state: StateType) => state.defaultRooms); if (!joinableRooms?.length) { - console.warn('no default joinable rooms yet'); + window.log.info('no default joinable rooms yet'); return <>; } diff --git a/ts/data/data.ts b/ts/data/data.ts index c8fa878d2..d87f130b8 100644 --- a/ts/data/data.ts +++ b/ts/data/data.ts @@ -288,13 +288,13 @@ function _updateJob(id: number, data: any) { ...data, resolve: (value: any) => { _removeJob(id); - // const end = Date.now(); - // const delta = end - start; - // if (delta > 10) { - // window.log.debug( - // `SQL channel job ${id} (${fnName}) succeeded in ${end - start}ms` - // ); - // } + if (_DEBUG) { + const end = Date.now(); + const delta = end - start; + if (delta > 10) { + window.log.debug(`SQL channel job ${id} (${fnName}) succeeded in ${end - start}ms`); + } + } return resolve(value); }, reject: (error: any) => { diff --git a/ts/models/conversation.ts b/ts/models/conversation.ts index 57f82a5d8..850ffec3f 100644 --- a/ts/models/conversation.ts +++ b/ts/models/conversation.ts @@ -1046,7 +1046,6 @@ export class ConversationModel extends Backbone.Model { read = read.filter(item => !item.hasErrors); if (this.isPublic()) { - window.log.debug('public conversation... No need to send read receipt'); return; } if (this.isPrivate() && read.length && options.sendReadReceipts) { diff --git a/ts/opengroup/opengroupV2/ApiUtil.ts b/ts/opengroup/opengroupV2/ApiUtil.ts index c6edb32fb..721411d3f 100644 --- a/ts/opengroup/opengroupV2/ApiUtil.ts +++ b/ts/opengroup/opengroupV2/ApiUtil.ts @@ -8,10 +8,6 @@ import { parseOpenGroupV2 } from './JoinOpenGroupV2'; import { getAllRoomInfos } from './OpenGroupAPIV2'; import { OpenGroupMessageV2 } from './OpenGroupMessageV2'; -export const defaultServer = 'https://sessionopengroup.com'; -export const defaultServerPublicKey = - '658d29b91892a2389505596b135e76a53db6e11d613a51dbd3d0816adffb231b'; - export type OpenGroupRequestCommonType = { serverUrl: string; roomId: string; @@ -107,12 +103,21 @@ export const parseMessages = async ( ); return _.compact(messages); }; +// tslint:disable: no-http-string + +// FIXME audric change this to +// const defaultRoom = +// 'https://opengroup.bilb.us/main?public_key=1352534ba73d4265973280431dbc72e097a3e43275d1ada984f9805b4943047d'; + +// const defaultRoom = +// 'http://opengroup.bilb.us:9861/main?public_key=1352534ba73d4265973280431dbc72e097a3e43275d1ada984f9805b4943047d'; -// 'http://sessionopengroup.com/main?public_key=658d29b91892a2389505596b135e76a53db6e11d613a51dbd3d0816adffb231b' +// const defaultRoom = +// 'https://sog.ibolpap.finance/main?public_key=b464aa186530c97d6bcf663a3a3b7465a5f782beaa67c83bee99468824b4aa10'; -// FIXME audric change this to sessionopengroup.com once http is fixed -const defaultRoom = - 'https://opengroup.bilb.us/main?public_key=1352534ba73d4265973280431dbc72e097a3e43275d1ada984f9805b4943047d'; +const defaultServerUrl = 'http://116.203.70.33'; +const defaultServerPublicKey = 'a03c383cf63c3c4efe67acc52112a6dd734b3a946b9545f488aaa93da7991238'; +const defaultRoom = `${defaultServerUrl}/main?public_key=${defaultServerPublicKey}`; const loadDefaultRoomsSingle = () => allowOnlyOneAtATime( diff --git a/ts/opengroup/opengroupV2/JoinOpenGroupV2.ts b/ts/opengroup/opengroupV2/JoinOpenGroupV2.ts index d9ee4cb36..898569abb 100644 --- a/ts/opengroup/opengroupV2/JoinOpenGroupV2.ts +++ b/ts/opengroup/opengroupV2/JoinOpenGroupV2.ts @@ -33,10 +33,8 @@ export function parseOpenGroupV2(urlWithPubkey: string): OpenGroupV2Room | undef // new URL fails if the protocol is not explicit const url = new URL(prefixedUrl); - let serverUrl = `${url.protocol}//${url.host}`; - if (url.port) { - serverUrl += `:${url.port}`; - } + // the port (if any is set) is already in the url.host so no need to += url.port + const serverUrl = `${url.protocol}//${url.host}`; const room: OpenGroupV2Room = { serverUrl, diff --git a/ts/opengroup/opengroupV2/OpenGroupAPIV2.ts b/ts/opengroup/opengroupV2/OpenGroupAPIV2.ts index 03ea7013b..edcfb7ed1 100644 --- a/ts/opengroup/opengroupV2/OpenGroupAPIV2.ts +++ b/ts/opengroup/opengroupV2/OpenGroupAPIV2.ts @@ -50,7 +50,7 @@ async function sendOpenGroupV2Request(request: OpenGroupV2Request): Promise { try { - console.warn('TRIGGERING NEW AUTH TOKEN WITH', { serverUrl, roomId }); + window.log.info('TRIGGERING NEW AUTH TOKEN WITH', { serverUrl, roomId }); const token = await requestNewAuthToken({ serverUrl, roomId }); if (!token) { window.log.warn('invalid new auth token', token); @@ -363,7 +362,6 @@ export const banUser = async ( }; const banResult = await sendOpenGroupV2Request(request); const isOk = parseStatusCodeFromOnionRequest(banResult) === 200; - console.warn('banResult', banResult); return isOk; }; @@ -380,7 +378,6 @@ export const unbanUser = async ( }; const unbanResult = await sendOpenGroupV2Request(request); const isOk = parseStatusCodeFromOnionRequest(unbanResult) === 200; - console.warn('unbanResult', unbanResult); return isOk; }; @@ -636,7 +633,6 @@ export const addModerator = async ( }; const addModResult = await sendOpenGroupV2Request(request); const isOk = parseStatusCodeFromOnionRequest(addModResult) === 200; - console.warn('addModResult', addModResult); return isOk; }; @@ -653,6 +649,5 @@ export const removeModerator = async ( }; const removeModResult = await sendOpenGroupV2Request(request); const isOk = parseStatusCodeFromOnionRequest(removeModResult) === 200; - console.warn('removeModResult', removeModResult); return isOk; }; diff --git a/ts/opengroup/opengroupV2/OpenGroupAPIV2CompactPoll.ts b/ts/opengroup/opengroupV2/OpenGroupAPIV2CompactPoll.ts index 8bdaf4b0a..beede23b6 100644 --- a/ts/opengroup/opengroupV2/OpenGroupAPIV2CompactPoll.ts +++ b/ts/opengroup/opengroupV2/OpenGroupAPIV2CompactPoll.ts @@ -57,13 +57,8 @@ const getCompactPollRequest = async ( room_id: roomId, auth_token: token || '', }; - // if (lastMessageDeletedServerID) { roomRequestContent.from_deletion_server_id = lastMessageDeletedServerID; - // } - // if (lastMessageFetchedServerID) { roomRequestContent.from_message_server_id = lastMessageFetchedServerID; - // } - console.warn('compactPoll, ', roomRequestContent); return roomRequestContent; } catch (e) { diff --git a/ts/opengroup/opengroupV2/OpenGroupManagerV2.ts b/ts/opengroup/opengroupV2/OpenGroupManagerV2.ts index 67f9f2ee3..8610da583 100644 --- a/ts/opengroup/opengroupV2/OpenGroupManagerV2.ts +++ b/ts/opengroup/opengroupV2/OpenGroupManagerV2.ts @@ -184,8 +184,6 @@ export class OpenGroupManagerV2 { room.roomName = roomInfos.name || undefined; await saveV2OpenGroupRoom(room); - console.warn('openGroupRoom info', roomInfos); - // mark active so it's not in the contacts list but in the conversation list conversation.set({ active_at: Date.now(), diff --git a/ts/opengroup/opengroupV2/OpenGroupServerPoller.ts b/ts/opengroup/opengroupV2/OpenGroupServerPoller.ts index a84a89c0f..7446cb54a 100644 --- a/ts/opengroup/opengroupV2/OpenGroupServerPoller.ts +++ b/ts/opengroup/opengroupV2/OpenGroupServerPoller.ts @@ -156,7 +156,6 @@ export class OpenGroupServerPoller { compactFetchResults = compactFetchResults.filter(result => this.roomIdsToPoll.has(result.roomId) ); - // window.log.debug(`compactFetchResults for ${this.serverUrl}:`, compactFetchResults); // ==> At this point all those results need to trigger conversation updates, so update what we have to update await handleCompactPollResults(this.serverUrl, compactFetchResults); diff --git a/ts/opengroup/utils/OpenGroupUtils.ts b/ts/opengroup/utils/OpenGroupUtils.ts index f24eaf964..c3bc1802a 100644 --- a/ts/opengroup/utils/OpenGroupUtils.ts +++ b/ts/opengroup/utils/OpenGroupUtils.ts @@ -24,7 +24,7 @@ export const openGroupV2ServerUrlRegex = new RegExp( * Regex to use to check if a string is a v2open completeURL with pubkey. * Be aware that the /g flag is not set as .test() will otherwise return alternating result * - * @see https://stackoverflow.com/a/9275499/1680951 + * see https://stackoverflow.com/a/9275499/1680951 */ export const openGroupV2CompleteURLRegex = new RegExp( `${openGroupV2ServerUrlRegex.source}\/${roomIdV2Regex}${qMark}${publicKeyParam}${publicKeyRegex}`, diff --git a/ts/session/onions/index.ts b/ts/session/onions/index.ts index ae974161d..8ac3d491d 100644 --- a/ts/session/onions/index.ts +++ b/ts/session/onions/index.ts @@ -1,4 +1,4 @@ -import { getGuardNodes } from '../../../ts/data/data'; +import { getGuardNodes, updateGuardNodes } from '../../../ts/data/data'; import * as SnodePool from '../snode_api/snodePool'; import _ from 'lodash'; import { default as insecureNodeFetch } from 'node-fetch'; @@ -217,7 +217,7 @@ export class OnionPaths { const edKeys = guardNodes.map(n => n.pubkey_ed25519); - await window.libloki.storage.updateGuardNodes(edKeys); + await updateGuardNodes(edKeys); return guardNodes; } diff --git a/ts/session/onions/onionSend.ts b/ts/session/onions/onionSend.ts index 2f10d445b..921cf6602 100644 --- a/ts/session/onions/onionSend.ts +++ b/ts/session/onions/onionSend.ts @@ -9,8 +9,10 @@ import { SnodeResponse, } from '../snode_api/onions'; import { Snode } from '../snode_api/snodePool'; -import _ from 'lodash'; +import _, { toNumber } from 'lodash'; import { default as insecureNodeFetch } from 'node-fetch'; +import { PROTOCOLS } from '../constants'; +import { toHex } from '../utils/String'; // FIXME: replace with something on urlPubkeyMap... const FILESERVER_HOSTS = [ @@ -111,7 +113,7 @@ export const getOnionPathForSending = async (requestNumber: number) => { } catch (e) { window.log.error(`sendViaOnion #${requestNumber} - getOnionPath Error ${e.code} ${e.message}`); } - if (!pathNodes || !pathNodes.length) { + if (!pathNodes?.length) { window.log.warn(`sendViaOnion #${requestNumber} - failing, no path available`); // should we retry? return null; @@ -132,7 +134,7 @@ const initOptionsWithDefaults = (options: OnionFetchBasicOptions) => { * result is status_code and whatever the body should be */ export const sendViaOnion = async ( - srvPubKey: string, + destinationX25519Key: string, url: URL, fetchOptions: OnionFetchOptions, options: OnionFetchBasicOptions = {}, @@ -142,9 +144,11 @@ export const sendViaOnion = async ( txtResponse: string; response: string; } | null> => { - if (!srvPubKey) { - window.log.error('sendViaOnion - called without a server public key'); - return null; + const castedDestinationX25519Key = + typeof destinationX25519Key !== 'string' ? toHex(destinationX25519Key) : destinationX25519Key; + // FIXME audric looks like this might happen for opengroupv1 + if (!destinationX25519Key || typeof destinationX25519Key !== 'string') { + window.log.error('sendViaOnion - called without a server public key or not a string key'); } const defaultedOptions = initOptionsWithDefaults(options); @@ -158,19 +162,24 @@ export const sendViaOnion = async ( // do the request let result: SnodeResponse | RequestError; try { + // if protocol is forced to 'http:' => just use http (without the ':'). + // otherwise use https as protocol (this is the default) + const forcedHttp = url.protocol === PROTOCOLS.HTTP; const finalRelayOptions: FinalRelayOptions = { - host: url.host, - // FIXME http open groups v2 are not working - // protocol: url.protocol, - // port: url.port, + host: url.hostname, }; - // window.log.debug('sendViaOnion payloadObj ==> ', payloadObj); + if (forcedHttp) { + finalRelayOptions.protocol = 'http'; + } + if (forcedHttp) { + finalRelayOptions.port = url.port ? toNumber(url.port) : 80; + } result = await sendOnionRequestLsrpcDest( 0, pathNodes, - srvPubKey, + castedDestinationX25519Key, finalRelayOptions, payloadObj, defaultedOptions.requestNumber, @@ -190,7 +199,7 @@ export const sendViaOnion = async ( const retriedResult = await handleSendViaOnionRetry( result, defaultedOptions, - srvPubKey, + castedDestinationX25519Key, url, fetchOptions, abortSignal diff --git a/ts/session/snode_api/onions.ts b/ts/session/snode_api/onions.ts index 20e526d2b..f35667b51 100644 --- a/ts/session/snode_api/onions.ts +++ b/ts/session/snode_api/onions.ts @@ -5,7 +5,7 @@ import { Snode } from './snodePool'; import ByteBuffer from 'bytebuffer'; import { StringUtils } from '../utils'; import { OnionPaths } from '../onions'; -import Long from 'long'; +import { fromBase64ToArrayBuffer, toHex } from '../utils/String'; export enum RequestError { BAD_PATH = 'BAD_PATH', @@ -36,9 +36,22 @@ async function encryptForPubKey(pubKeyX25519hex: string, reqObj: any): Promise +): Uint8Array { const payloadStr = JSON.stringify(payloadJson); const bufferJson = ByteBuffer.wrap(payloadStr, 'utf8'); - const len = ciphertext.length as number; + const len = ciphertext.length; const arrayLen = bufferJson.buffer.length + 4 + len; const littleEndian = true; const buffer = new ByteBuffer(arrayLen, littleEndian); @@ -72,19 +88,10 @@ function encodeCiphertextPlusJson(ciphertext: any, payloadJson: any): Uint8Array return new Uint8Array(buffer.buffer); } -// New "semi-binary" encoding -function makeGuardPayloadV2(guardCtx: any): Uint8Array { - const guardPayloadObj = { - ephemeral_key: StringUtils.decode(guardCtx.ephemeralKey, 'hex'), - }; - - return encodeCiphertextPlusJson(guardCtx.ciphertext, guardPayloadObj); -} - async function buildOnionCtxs( nodePath: Array, destCtx: DestinationContext, - targetED25519Hex: string, + targetED25519Hex?: string, finalRelayOptions?: FinalRelayOptions, id = '' ) { @@ -95,14 +102,7 @@ async function buildOnionCtxs( const firstPos = nodePath.length - 1; for (let i = firstPos; i > -1; i -= 1) { - let dest: { - host?: string; - protocol?: string; - port?: string; - destination?: string; - method?: string; - target?: string; - }; + let dest: DestinationRelayV2; const relayingToFinalDestination = i === firstPos; // if last position if (relayingToFinalDestination && finalRelayOptions) { @@ -120,10 +120,10 @@ async function buildOnionCtxs( }; // FIXME http open groups v2 are not working // tslint:disable-next-line: no-http-string - // if (finalRelayOptions?.protocol === 'http:') { - // dest.protocol = 'http'; - // dest.port = '80'; - // } + if (finalRelayOptions?.protocol === 'http') { + dest.protocol = finalRelayOptions.protocol; + dest.port = finalRelayOptions.port || 80; + } } else { // set x25519 if destination snode let pubkeyHex = targetED25519Hex; // relayingToFinalDestination @@ -132,7 +132,7 @@ async function buildOnionCtxs( pubkeyHex = nodePath[i + 1].pubkey_ed25519; if (!pubkeyHex) { log.error( - `loki_rpc:::buildOnionRequest ${id} - no ed25519 for`, + `loki_rpc:::buildOnionGuardNodePayload ${id} - no ed25519 for`, nodePath[i + 1], 'path node', i + 1 @@ -150,7 +150,7 @@ async function buildOnionCtxs( ctxes.push(ctx); } catch (e) { log.error( - `loki_rpc:::buildOnionRequest ${id} - encryptForRelayV2 failure`, + `loki_rpc:::buildOnionGuardNodePayload ${id} - encryptForRelayV2 failure`, e.code, e.message ); @@ -163,19 +163,26 @@ async function buildOnionCtxs( // we just need the targetNode.pubkey_ed25519 for the encryption // targetPubKey is ed25519 if snode is the target -async function buildOnionRequest( +async function buildOnionGuardNodePayload( nodePath: Array, destCtx: DestinationContext, - targetED25519Hex: string, + targetED25519Hex?: string, finalRelayOptions?: FinalRelayOptions, id = '' ) { const ctxes = await buildOnionCtxs(nodePath, destCtx, targetED25519Hex, finalRelayOptions, id); + // this is the OUTER side of the onion, the one encoded with multiple layer + // So the one we will send to the first guard node. const guardCtx = ctxes[ctxes.length - 1]; // last ctx - // all these requests should use AesGcm - return makeGuardPayloadV2(guardCtx); + // New "semi-binary" encoding + + const guardPayloadObj = { + ephemeral_key: toHex(guardCtx.ephemeralKey), + }; + + return encodeCiphertextPlusJson(guardCtx.ciphertext, guardPayloadObj); } // Process a response as it arrives from `fetch`, handling @@ -184,11 +191,11 @@ async function buildOnionRequest( const processOnionResponse = async ( reqIdx: number, response: any, - sharedKey: ArrayBuffer, + symmetricKey: ArrayBuffer, debug: boolean, abortSignal?: AbortSignal ): Promise => { - const { log, libloki, dcodeIO, StringView } = window; + const { log, libloki } = window; if (abortSignal?.aborted) { log.warn(`(${reqIdx}) [path] Call aborted`); @@ -230,7 +237,7 @@ const processOnionResponse = async ( return RequestError.OTHER; } - let ciphertext = await response.text(); + let ciphertext = (await response.text()) as string; if (!ciphertext) { log.warn( `(${reqIdx}) [path] lokiRpc::processOnionResponse - Target node return empty ciphertext` @@ -251,16 +258,16 @@ const processOnionResponse = async ( // just try to get a json object from what is inside (for PN requests), if it fails, continue () } try { - ciphertextBuffer = dcodeIO.ByteBuffer.wrap(ciphertext, 'base64').toArrayBuffer(); + ciphertextBuffer = fromBase64ToArrayBuffer(ciphertext); if (debug) { log.debug( `(${reqIdx}) [path] lokiRpc::processOnionResponse - ciphertextBuffer`, - StringView.arrayBufferToHex(ciphertextBuffer) + toHex(ciphertextBuffer) ); } - const plaintextBuffer = await libloki.crypto.DecryptAESGCM(sharedKey, ciphertextBuffer); + const plaintextBuffer = await libloki.crypto.DecryptAESGCM(symmetricKey, ciphertextBuffer); if (debug) { log.debug('lokiRpc::processOnionResponse - plaintextBuffer', plaintextBuffer.toString()); } @@ -269,13 +276,13 @@ const processOnionResponse = async ( } catch (e) { log.error(`(${reqIdx}) [path] lokiRpc::processOnionResponse - decode error`, e); log.error( - `(${reqIdx}) [path] lokiRpc::processOnionResponse - symKey`, - StringView.arrayBufferToHex(sharedKey) + `(${reqIdx}) [path] lokiRpc::processOnionResponse - symmetricKey`, + toHex(symmetricKey) ); if (ciphertextBuffer) { log.error( `(${reqIdx}) [path] lokiRpc::processOnionResponse - ciphertextBuffer`, - StringView.arrayBufferToHex(ciphertextBuffer) + toHex(ciphertextBuffer) ); } return RequestError.OTHER; @@ -308,9 +315,8 @@ export const snodeHttpsAgent = new https.Agent({ export type FinalRelayOptions = { host: string; - // FIXME http open groups v2 are not working - // protocol?: string; // default to https - // port?: string; // default to 443 + protocol?: 'http' | 'https'; // default to https + port?: number; // default to 443 }; export type DestinationContext = { @@ -346,10 +352,10 @@ const sendOnionRequest = async ( body?: string; }, finalRelayOptions?: FinalRelayOptions, - lsrpcIdx?: any, + lsrpcIdx?: number, abortSignal?: AbortSignal ): Promise => { - const { log, StringView } = window; + const { log } = window; let id = ''; if (lsrpcIdx !== undefined) { @@ -363,7 +369,8 @@ const sendOnionRequest = async ( let destX25519hex = destX25519Any; if (typeof destX25519hex !== 'string') { // convert AB to hex - destX25519hex = StringView.arrayBufferToHex(destX25519Any as any); + window.log.warn('destX25519hex was not a string'); + destX25519hex = toHex(destX25519Any as any); } // safely build destination @@ -378,9 +385,7 @@ const sendOnionRequest = async ( const options = finalDestOptions; // lint // do we need this? - if (options.headers === undefined) { - options.headers = {}; - } + options.headers = options.headers || {}; const isLsrpc = !!finalRelayOptions; @@ -413,10 +418,10 @@ const sendOnionRequest = async ( throw e; } - const payload = await buildOnionRequest( + const payload = await buildOnionGuardNodePayload( nodePath, destCtx, - targetEd25519hex as string, // FIXME + targetEd25519hex, finalRelayOptions, id ); @@ -436,7 +441,6 @@ const sendOnionRequest = async ( // window.log.info('insecureNodeFetch => plaintext for sendOnionRequest'); const response = await insecureNodeFetch(guardUrl, guardFetchOptions); - return processOnionResponse(reqIdx, response, destCtx.symmetricKey, false, abortSignal); }; @@ -460,7 +464,6 @@ async function sendOnionRequestSnodeDest( } // need relay node's pubkey_x25519_hex -// always the same target: /loki/v1/lsrpc export async function sendOnionRequestLsrpcDest( reqIdx: number, nodePath: Array, diff --git a/ts/session/snode_api/serviceNodeAPI.ts b/ts/session/snode_api/serviceNodeAPI.ts index 877181975..75f16d82b 100644 --- a/ts/session/snode_api/serviceNodeAPI.ts +++ b/ts/session/snode_api/serviceNodeAPI.ts @@ -347,7 +347,6 @@ export async function storeOnNode(targetNode: Snode, params: SendParams): Promis await sleepFor(successiveFailures * 500); try { const result = await snodeRpc('store', params, targetNode); - console.warn('snode storeOnNode result', result); // do not return true if we get false here... if (result === false) { diff --git a/ts/session/snode_api/swarmPolling.ts b/ts/session/snode_api/swarmPolling.ts index 8a798a4b6..03f4d9579 100644 --- a/ts/session/snode_api/swarmPolling.ts +++ b/ts/session/snode_api/swarmPolling.ts @@ -53,7 +53,8 @@ export class SwarmPolling { public start(): void { this.loadGroupIds(); - void this.pollForAllKeys(); + // FIXME audric + // void this.pollForAllKeys(); } public addGroupId(pubkey: PubKey) {