You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
325 lines
9.9 KiB
TypeScript
325 lines
9.9 KiB
TypeScript
2 years ago
|
/* eslint-disable no-restricted-syntax */
|
||
2 years ago
|
import { isEmpty, sample } from 'lodash';
|
||
2 years ago
|
import pRetry from 'p-retry';
|
||
2 years ago
|
import { Snode } from '../../../data/data';
|
||
|
import { getSodiumRenderer } from '../../crypto';
|
||
|
import { StringUtils, UserUtils } from '../../utils';
|
||
|
import { fromBase64ToArray, fromHexToArray } from '../../utils/String';
|
||
|
import { EmptySwarmError } from '../../utils/errors';
|
||
2 years ago
|
import { UpdateExpiryOnNodeSubRequest } from './SnodeRequestTypes';
|
||
2 years ago
|
import { doSnodeBatchRequest } from './batchRequest';
|
||
|
import { GetNetworkTime } from './getNetworkTime';
|
||
|
import { getSwarmFor } from './snodePool';
|
||
|
import { SnodeSignature } from './snodeSignatures';
|
||
2 years ago
|
import { ExpireMessageResultItem, ExpireMessagesResultsContent } from './types';
|
||
2 years ago
|
import { SeedNodeAPI } from '../seed_node_api';
|
||
2 years ago
|
|
||
2 years ago
|
async function verifyExpireMsgsResponseSignature({
|
||
2 years ago
|
pubkey,
|
||
|
snodePubkey,
|
||
|
messageHashes,
|
||
2 years ago
|
expiry,
|
||
|
signature,
|
||
|
updated,
|
||
|
unchanged,
|
||
|
}: ExpireMessageResultItem & {
|
||
2 years ago
|
pubkey: string;
|
||
|
snodePubkey: any;
|
||
|
messageHashes: Array<string>;
|
||
|
}): Promise<boolean> {
|
||
2 years ago
|
if (!expiry || isEmpty(messageHashes) || isEmpty(signature)) {
|
||
|
window.log.warn('WIP: [verifyExpireMsgsSignature] missing argument');
|
||
2 years ago
|
return false;
|
||
|
}
|
||
|
|
||
|
const edKeyPrivBytes = fromHexToArray(snodePubkey);
|
||
2 years ago
|
const hashes = [...messageHashes, ...updated];
|
||
|
if (unchanged && Object.keys(unchanged).length > 0) {
|
||
2 years ago
|
hashes.push(
|
||
2 years ago
|
...Object.entries(unchanged)
|
||
|
.map(([key, value]: [string, number]) => {
|
||
2 years ago
|
return `${key}${value}`;
|
||
|
})
|
||
|
.sort()
|
||
|
);
|
||
|
}
|
||
|
|
||
2 years ago
|
const verificationString = `${pubkey}${expiry}${hashes.join('')}`;
|
||
2 years ago
|
const verificationData = StringUtils.encode(verificationString, 'utf8');
|
||
2 years ago
|
// window.log.debug('WIP: [verifyExpireMsgsSignature] verificationString', verificationString);
|
||
2 years ago
|
|
||
|
const sodium = await getSodiumRenderer();
|
||
|
try {
|
||
|
const isValid = sodium.crypto_sign_verify_detached(
|
||
|
fromBase64ToArray(signature),
|
||
|
new Uint8Array(verificationData),
|
||
|
edKeyPrivBytes
|
||
|
);
|
||
|
|
||
|
return isValid;
|
||
|
} catch (e) {
|
||
2 years ago
|
window.log.warn('WIP: [verifyExpireMsgsSignature] failed with: ', e.message);
|
||
2 years ago
|
return false;
|
||
|
}
|
||
|
}
|
||
|
|
||
2 years ago
|
type ExpireRequestResponseResults = Record<string, { hashes: Array<string>; expiry: number }>;
|
||
|
|
||
|
async function processExpireRequestResponse(
|
||
2 years ago
|
pubkey: string,
|
||
|
targetNode: Snode,
|
||
2 years ago
|
swarm: ExpireMessagesResultsContent,
|
||
2 years ago
|
messageHashes: Array<string>
|
||
2 years ago
|
): Promise<ExpireRequestResponseResults> {
|
||
2 years ago
|
if (isEmpty(swarm)) {
|
||
2 years ago
|
throw Error(`[expireOnNodes] failed! ${messageHashes}`);
|
||
2 years ago
|
}
|
||
|
|
||
2 years ago
|
const results: ExpireRequestResponseResults = {};
|
||
2 years ago
|
// window.log.debug(`WIP: [processExpireRequestResponse] initial results: `, swarm, messageHashes);
|
||
2 years ago
|
|
||
|
for (const nodeKey of Object.keys(swarm)) {
|
||
|
if (!isEmpty(swarm[nodeKey].failed)) {
|
||
|
const reason = 'Unknown';
|
||
|
const statusCode = '404';
|
||
|
window?.log?.warn(
|
||
2 years ago
|
`WIP: loki_message:::expireMessage - Couldn't delete data from: ${
|
||
2 years ago
|
targetNode.pubkey_ed25519
|
||
|
}${reason && statusCode && ` due to an error ${reason} (${statusCode})`}`
|
||
|
);
|
||
2 years ago
|
// Make sure to clear the result since it failed
|
||
2 years ago
|
results[nodeKey] = { hashes: [], expiry: 0 };
|
||
|
}
|
||
|
|
||
|
const updatedHashes = swarm[nodeKey].updated;
|
||
|
const unchangedHashes = swarm[nodeKey].unchanged;
|
||
2 years ago
|
const expiry = swarm[nodeKey].expiry;
|
||
2 years ago
|
const signature = swarm[nodeKey].signature;
|
||
|
|
||
2 years ago
|
// eslint-disable-next-line no-await-in-loop
|
||
2 years ago
|
const isValid = await verifyExpireMsgsResponseSignature({
|
||
2 years ago
|
pubkey,
|
||
|
snodePubkey: nodeKey,
|
||
|
messageHashes,
|
||
2 years ago
|
expiry,
|
||
|
signature,
|
||
|
updated: updatedHashes,
|
||
|
unchanged: unchangedHashes,
|
||
2 years ago
|
});
|
||
|
|
||
|
if (!isValid) {
|
||
|
window.log.warn(
|
||
2 years ago
|
'WIP: loki_message:::expireMessage - Signature verification failed!',
|
||
2 years ago
|
messageHashes
|
||
|
);
|
||
|
}
|
||
2 years ago
|
results[nodeKey] = { hashes: updatedHashes, expiry };
|
||
2 years ago
|
}
|
||
|
|
||
|
return results;
|
||
|
}
|
||
|
|
||
2 years ago
|
async function expireOnNodes(
|
||
|
targetNode: Snode,
|
||
|
expireRequest: UpdateExpiryOnNodeSubRequest
|
||
|
): Promise<number | null> {
|
||
2 years ago
|
try {
|
||
|
const result = await doSnodeBatchRequest(
|
||
2 years ago
|
[expireRequest],
|
||
2 years ago
|
targetNode,
|
||
|
4000,
|
||
2 years ago
|
expireRequest.params.pubkey,
|
||
2 years ago
|
'batch'
|
||
|
);
|
||
|
|
||
2 years ago
|
if (!result || result.length !== 1) {
|
||
2 years ago
|
window?.log?.warn(
|
||
2 years ago
|
`WIP: [expireOnNodes] There was an issue with the results. sessionRpc ${targetNode.ip}:${
|
||
2 years ago
|
targetNode.port
|
||
|
} expireRequest ${JSON.stringify(expireRequest)}`
|
||
2 years ago
|
);
|
||
2 years ago
|
return null;
|
||
2 years ago
|
}
|
||
|
|
||
2 years ago
|
// TODOLATER make sure that this code still works once disappearing messages is merged
|
||
|
// do a basic check to know if we have something kind of looking right (status 200 should always be there for a retrieve)
|
||
|
const firstResult = result[0];
|
||
|
|
||
|
if (firstResult.code !== 200) {
|
||
|
window?.log?.warn(`WIP: [expireOnNods] result is not 200 but ${firstResult.code}`);
|
||
2 years ago
|
return null;
|
||
2 years ago
|
}
|
||
|
|
||
2 years ago
|
try {
|
||
2 years ago
|
const bodyFirstResult = firstResult.body;
|
||
|
const expirationResults = await processExpireRequestResponse(
|
||
2 years ago
|
expireRequest.params.pubkey,
|
||
2 years ago
|
targetNode,
|
||
2 years ago
|
bodyFirstResult.swarm as ExpireMessagesResultsContent,
|
||
2 years ago
|
expireRequest.params.messages
|
||
|
);
|
||
2 years ago
|
const firstExpirationResult = Object.entries(expirationResults).at(0);
|
||
2 years ago
|
if (!firstExpirationResult) {
|
||
|
window?.log?.warn(
|
||
|
'WIP: [expireOnNodes] failed to parse "swarm" result. firstExpirationResult is null'
|
||
|
);
|
||
|
throw new Error('firstExpirationResult is null');
|
||
|
}
|
||
|
|
||
|
const messageHash = firstExpirationResult[0];
|
||
|
const expiry = firstExpirationResult[1].expiry;
|
||
|
|
||
2 years ago
|
window.log.debug(
|
||
2 years ago
|
`WIP: [expireOnNodes] Success!\nHere are the results from one of the snodes.\nmessageHash: ${messageHash} \nexpiry: ${expiry} \nexpires at: ${new Date(
|
||
|
expiry
|
||
|
).toUTCString()}\nnow: ${new Date(GetNetworkTime.getNowWithNetworkOffset()).toUTCString()}`
|
||
2 years ago
|
);
|
||
|
|
||
2 years ago
|
return expiry;
|
||
2 years ago
|
} catch (e) {
|
||
2 years ago
|
window?.log?.warn('WIP: [expireOnNodes] Failed to parse "swarm" result: ', e.msg);
|
||
2 years ago
|
}
|
||
2 years ago
|
return null;
|
||
2 years ago
|
} catch (e) {
|
||
2 years ago
|
window?.log?.warn(
|
||
2 years ago
|
'WIP: [expireOnNodes] - send error:',
|
||
2 years ago
|
e,
|
||
|
`destination ${targetNode.ip}:${targetNode.port}`
|
||
|
);
|
||
2 years ago
|
throw e;
|
||
|
}
|
||
|
}
|
||
|
|
||
2 years ago
|
type GetExpiriesFromSnodeProps = {
|
||
|
messageHashes: Array<string>;
|
||
|
timestamp: number;
|
||
2 years ago
|
};
|
||
|
|
||
2 years ago
|
async function buildGetExpiriesRequest(
|
||
|
props: GetExpiriesFromSnodeProps
|
||
2 years ago
|
): Promise<UpdateExpiryOnNodeSubRequest | null> {
|
||
2 years ago
|
const { messageHashes, timestamp } = props;
|
||
2 years ago
|
|
||
|
const ourPubKey = UserUtils.getOurPubKeyStrFromCache();
|
||
|
if (!ourPubKey) {
|
||
2 years ago
|
window.log.error('WIP: [buildGetExpiriesRequest] No pubkey found', messageHashes);
|
||
2 years ago
|
return null;
|
||
2 years ago
|
}
|
||
|
|
||
2 years ago
|
window.log.debug(
|
||
2 years ago
|
`WIP: [buildGetExpiriesRequest] gettig expiries for messageHashes: ${messageHashes} from ${new Date(
|
||
|
timestamp
|
||
2 years ago
|
).toUTCString()}`
|
||
|
);
|
||
2 years ago
|
|
||
|
const signResult = await SnodeSignature.generateGetExpiriesSignature({
|
||
|
timestamp,
|
||
|
messageHashes,
|
||
2 years ago
|
});
|
||
|
|
||
|
if (!signResult) {
|
||
2 years ago
|
window.log.error(
|
||
2 years ago
|
`WIP: [buildGetExpiriesRequest] SnodeSignature.generateUpdateExpirySignature returned an empty result ${messageHashes}`
|
||
2 years ago
|
);
|
||
|
return null;
|
||
2 years ago
|
}
|
||
|
|
||
2 years ago
|
const expireParams: UpdateExpiryOnNodeSubRequest = {
|
||
|
method: 'expire',
|
||
|
params: {
|
||
|
pubkey: ourPubKey,
|
||
|
pubkey_ed25519: signResult.pubkey_ed25519.toUpperCase(),
|
||
|
// TODO better testing for failed case
|
||
2 years ago
|
messages: [messageHashes],
|
||
2 years ago
|
expiry,
|
||
|
extend: extend || undefined,
|
||
|
shorten: shorten || undefined,
|
||
|
signature: signResult?.signature,
|
||
|
},
|
||
2 years ago
|
};
|
||
|
|
||
2 years ago
|
window.log.debug(
|
||
|
`WIP: [buildGetExpiriesRequest] ${messageHashes}\n${JSON.stringify(expireParams)}`
|
||
|
);
|
||
2 years ago
|
|
||
|
return expireParams;
|
||
|
}
|
||
|
|
||
2 years ago
|
/**
|
||
|
* Sends an 'expire' request to the user's swarm for a specific message.
|
||
|
* This supports both extending and shortening a message's TTL.
|
||
2 years ago
|
* The returned TTL should be assigned to the message to expire.
|
||
2 years ago
|
* @param messageHashes the hashes of the messages we want the current expiries for
|
||
|
* @param timestamp the time (ms) the request was initiated, must be within ±60s of the current time so using the server time is recommended.
|
||
2 years ago
|
* @returns the TTL of the message as set by the server
|
||
2 years ago
|
*/
|
||
2 years ago
|
export async function getExpiriesFromSnode(props: GetExpiriesFromSnodeProps) {
|
||
|
const { messageHashes } = props;
|
||
2 years ago
|
|
||
|
const ourPubKey = UserUtils.getOurPubKeyStrFromCache();
|
||
|
if (!ourPubKey) {
|
||
2 years ago
|
window.log.error('WIP: [getExpiriesFromSnode] No pubkey found', messageHashes);
|
||
2 years ago
|
return null;
|
||
2 years ago
|
}
|
||
|
|
||
2 years ago
|
let snode: Snode | undefined;
|
||
2 years ago
|
|
||
2 years ago
|
await pRetry(
|
||
|
async () => {
|
||
|
const swarm = await getSwarmFor(ourPubKey);
|
||
|
snode = sample(swarm);
|
||
|
if (!snode) {
|
||
|
throw new EmptySwarmError(ourPubKey, 'Ran out of swarm nodes to query');
|
||
|
}
|
||
|
},
|
||
|
{
|
||
|
retries: 3,
|
||
|
factor: 2,
|
||
|
minTimeout: SeedNodeAPI.getMinTimeout(),
|
||
|
onFailedAttempt: e => {
|
||
|
window?.log?.warn(
|
||
2 years ago
|
`WIP: [getExpiriesFromSnode] get snode attempt #${e.attemptNumber} failed. ${e.retriesLeft} retries left... Error: ${e.message}`
|
||
2 years ago
|
);
|
||
|
},
|
||
|
}
|
||
|
);
|
||
2 years ago
|
|
||
2 years ago
|
try {
|
||
2 years ago
|
const expireRequestParams = await buildGetExpiriesRequest(props);
|
||
2 years ago
|
if (!expireRequestParams) {
|
||
|
throw new Error(`Failed to build expire request ${JSON.stringify(props)}`);
|
||
|
}
|
||
|
|
||
2 years ago
|
let newTTL = null;
|
||
|
|
||
2 years ago
|
await pRetry(
|
||
|
async () => {
|
||
|
if (!snode) {
|
||
|
throw new Error(`No snode found.\n${JSON.stringify(props)}`);
|
||
|
}
|
||
2 years ago
|
newTTL = await expireOnNodes(snode, expireRequestParams);
|
||
2 years ago
|
},
|
||
|
{
|
||
|
retries: 3,
|
||
|
factor: 2,
|
||
|
minTimeout: SeedNodeAPI.getMinTimeout(),
|
||
|
onFailedAttempt: e => {
|
||
|
window?.log?.warn(
|
||
2 years ago
|
`WIP: [getExpiriesFromSnode] expire message on snode attempt #${e.attemptNumber} failed. ${e.retriesLeft} retries left... Error: ${e.message}`
|
||
2 years ago
|
);
|
||
|
},
|
||
|
}
|
||
|
);
|
||
2 years ago
|
|
||
|
return newTTL;
|
||
2 years ago
|
} catch (e) {
|
||
|
const snodeStr = snode ? `${snode.ip}:${snode.port}` : 'null';
|
||
|
window?.log?.warn(
|
||
2 years ago
|
`WIP: loki_message:::expireMessage - ${e.code ? `${e.code} ` : ''}${
|
||
2 years ago
|
e.message
|
||
2 years ago
|
} by ${ourPubKey} for ${messageHashes} via snode:${snodeStr}`
|
||
2 years ago
|
);
|
||
|
throw e;
|
||
|
}
|
||
|
}
|