chore: lint

pull/2873/head
Audric Ackermann 2 years ago
parent 1a18054fae
commit cd17a08c2e

@ -1,5 +1,6 @@
/* eslint-disable @typescript-eslint/no-var-requires */
const path = require('path');
const isProd = process.env.NODE_ENV === 'production';
module.exports = {

@ -3,6 +3,7 @@
*/
import { compact, uniq } from 'lodash';
import { GroupPubkeyType } from 'libsession_util_nodejs';
import {
CONFIG_DUMP_TABLE,
ConfigDumpDataNode,
@ -12,7 +13,6 @@ import {
// eslint-disable-next-line import/no-unresolved, import/extensions
import { ConfigWrapperObjectTypesMeta } from '../../webworker/workers/browser/libsession_worker_functions';
import { assertGlobalInstance } from '../sqlInstance';
import { GroupPubkeyType } from 'libsession_util_nodejs';
function parseRow(
row: Pick<ConfigDumpRow, 'data' | 'publicKey' | 'variant'>

@ -33,7 +33,7 @@ import {
ConfigWrapperUser,
getGroupPubkeyFromWrapperType,
isUserConfigWrapperType,
} from '../../ts/webworker/workers/browser/libsession_worker_functions';
} from '../webworker/workers/browser/libsession_worker_functions';
import { UserConfigKind, isUserKind } from '../types/ProtobufKind';
import {
ContactsWrapperActions,
@ -115,7 +115,7 @@ async function mergeUserConfigsWithIncomingUpdates(
hash: msg.messageHash,
}));
if (window.sessionFeatureFlags.debug.debugLibsessionDumps) {
printDumpForDebug(`printDumpsForDebugging: before merge of ${variant}:`, variant);
await printDumpForDebug(`printDumpsForDebugging: before merge of ${variant}:`, variant);
}
const mergedCount = await GenericWrapperActions.merge(variant, toMerge);
@ -129,7 +129,7 @@ async function mergeUserConfigsWithIncomingUpdates(
);
if (window.sessionFeatureFlags.debug.debugLibsessionDumps) {
printDumpForDebug(`printDumpsForDebugging: after merge of ${variant}:`, variant);
await printDumpForDebug(`printDumpsForDebugging: after merge of ${variant}:`, variant);
}
const incomingConfResult: IncomingUserResult = {
needsDump,

@ -60,14 +60,12 @@ export async function handleSwarmContentMessage(envelope: EnvelopePlus, messageH
async function decryptForGroupV2(envelope: EnvelopePlus) {
window?.log?.info('received closed group message v2');
// try {
const groupPk = envelope.source;
if (!PubKey.isClosedGroupV2(groupPk)) {
throw new PreConditionFailed('decryptForGroupV2: not a 03 prefixed group');
}
return await MetaGroupWrapperActions.decryptMessage(groupPk, envelope.content);
// } catch (e) {}
return MetaGroupWrapperActions.decryptMessage(groupPk, envelope.content);
}
async function decryptForClosedGroup(envelope: EnvelopePlus) {

@ -131,9 +131,9 @@ function isGroupConfigNamespace(
assertUnreachable(namespace, `isGroupConfigNamespace case not handled: ${namespace}`);
} catch (e) {
window.log.warn(`isGroupConfigNamespace case not handled: ${namespace}: ${e.message}`);
return false;
}
}
return false;
}
/**
@ -164,6 +164,7 @@ function isGroupNamespace(namespace: SnodeNamespaces): namespace is SnodeNamespa
return false;
}
}
return false;
}
function namespacePriority(namespace: SnodeNamespaces): 10 | 1 {
@ -189,6 +190,7 @@ function namespacePriority(namespace: SnodeNamespaces): 10 | 1 {
return 1;
}
}
return 1;
}
function maxSizeMap(namespaces: Array<SnodeNamespaces>) {

@ -1,11 +1,11 @@
import { isEmpty, isNil, omit } from 'lodash';
import { GroupPubkeyType } from 'libsession_util_nodejs';
import { Snode } from '../../../data/data';
import { updateIsOnline } from '../../../state/ducks/onion';
import { doSnodeBatchRequest } from './batchRequest';
import { GetNetworkTime } from './getNetworkTime';
import { SnodeNamespace, SnodeNamespaces } from './namespaces';
import { GroupPubkeyType } from 'libsession_util_nodejs';
import { UserGroupsWrapperActions } from '../../../webworker/workers/browser/libsession_worker_interface';
import { DURATION } from '../../constants';
import { PubKey } from '../../types';

@ -1,6 +1,7 @@
import https from 'https';
// eslint-disable-next-line import/no-named-default
import { clone } from 'lodash';
// eslint-disable-next-line import/no-named-default
import { default as insecureNodeFetch } from 'node-fetch';
import pRetry from 'p-retry';

@ -1,4 +1,5 @@
import { FixedSizeUint8Array, GroupPubkeyType } from 'libsession_util_nodejs';
import { isEmpty } from 'lodash';
import { getSodiumRenderer } from '../../crypto';
import { StringUtils, UserUtils } from '../../utils';
import { fromHexToArray, fromUInt8ArrayToBase64 } from '../../utils/String';
@ -7,7 +8,6 @@ import { SnodeNamespaces } from './namespaces';
import { PubKey } from '../../types';
import { toFixedUint8ArrayOfLength } from '../../../types/sqlSharedTypes';
import { PreConditionFailed } from '../../utils/errors';
import { isEmpty } from 'lodash';
export type SnodeSignatureResult = {
timestamp: number;
@ -184,7 +184,7 @@ async function generateUpdateExpirySignature({
const signature = sodium.crypto_sign_detached(message, ed25519Privkey as Uint8Array);
const signatureBase64 = fromUInt8ArrayToBase64(signature);
if (!isEmpty(signatureBase64) || isEmpty(ed25519Pubkey)) {
if (isEmpty(signatureBase64) || isEmpty(ed25519Pubkey)) {
throw new Error('generateUpdateExpirySignature: failed to build signature');
}

@ -172,7 +172,6 @@ export class SwarmPolling {
setTimeout(this.pollForAllKeys.bind(this), SWARM_POLLING_TIMEOUT.ACTIVE);
return;
}
window.log.warn('############################ pollForAllKeys ############################');
// we always poll as often as possible for our pubkey
const ourPubkey = UserUtils.getOurPubKeyStrFromCache();
const directPromise = this.pollOnceForKey([ourPubkey, ConversationTypeEnum.PRIVATE]);
@ -318,32 +317,30 @@ export class SwarmPolling {
!allLegacyGroupsInWrapper.some(m => m.pubkeyHex === pubkey) // just check if a legacy group with that pubkey exists
) {
// not tracked anymore in the wrapper. Discard messages and stop polling
this.notPollingForGroupAsNotInWrapper(pubkey, 'not in wrapper after poll');
await this.notPollingForGroupAsNotInWrapper(pubkey, 'not in wrapper after poll');
return;
}
if (PubKey.isClosedGroupV2(pubkey) && allGroupsInWrapper.some(m => m.pubkeyHex === pubkey)) {
// not tracked anymore in the wrapper. Discard messages and stop polling
this.notPollingForGroupAsNotInWrapper(pubkey, 'not in wrapper after poll');
await this.notPollingForGroupAsNotInWrapper(pubkey, 'not in wrapper after poll');
return;
}
{
// trigger the handling of all the other messages, not shared config related
newMessages.forEach(m => {
const content = extractWebSocketContent(m.data, m.hash);
if (!content) {
return;
}
// trigger the handling of all the other messages, not shared config related
newMessages.forEach(m => {
const content = extractWebSocketContent(m.data, m.hash);
if (!content) {
return;
}
Receiver.handleRequest(
content.body,
type === ConversationTypeEnum.GROUP || type === ConversationTypeEnum.GROUPV3
? pubkey
: null,
content.messageHash
);
});
}
Receiver.handleRequest(
content.body,
type === ConversationTypeEnum.GROUP || type === ConversationTypeEnum.GROUPV3
? pubkey
: null,
content.messageHash
);
});
}
private async getHashesToBump(
@ -364,12 +361,12 @@ export class SwarmPolling {
window.log.warn(`failed to get currentHashes for user variant ${variant}`);
}
}
window.log.debug(`configHashesToBump: ${configHashesToBump}`);
window.log.debug(`configHashesToBump private: ${configHashesToBump}`);
return configHashesToBump;
}
if (type === ConversationTypeEnum.GROUPV3 && PubKey.isClosedGroupV2(pubkey)) {
const toBump = await MetaGroupWrapperActions.currentHashes(pubkey);
window.log.debug(`configHashesToBump: ${toBump}`);
window.log.debug(`configHashesToBump group: ${toBump}`);
return toBump;
}
return [];
@ -498,6 +495,7 @@ export class SwarmPolling {
return newMessages;
}
// eslint-disable-next-line consistent-return
private getNamespacesToPollFrom(type: ConversationTypeEnum): Array<SnodeNamespaces> {
if (type === ConversationTypeEnum.PRIVATE) {
return [
@ -578,7 +576,7 @@ export class SwarmPolling {
}
}
function retrieveItemWithNamespace(results: RetrieveRequestResult[]) {
function retrieveItemWithNamespace(results: Array<RetrieveRequestResult>) {
return flatten(
compact(
results.map(

@ -29,6 +29,7 @@ async function decryptSharedConfigMessages(
try {
const envelope: EnvelopePlus = SignalService.Envelope.decode(groupConfigMessage.body) as any;
// eslint-disable-next-line no-await-in-loop
const decryptedEnvelope = await decryptEnvelope(envelope);
if (!decryptedEnvelope?.byteLength) {
continue;

@ -54,6 +54,7 @@ async function encryptForLegacyGroup(destination: PubKey, plainText: Uint8Array)
* @param encryptionType The type of encryption.
* @returns The envelope type and the base64 encoded cipher text
*/
// eslint-disable-next-line consistent-return
export async function encrypt(
destination: PubKey,
plainTextBuffer: Uint8Array,
@ -64,23 +65,11 @@ export async function encrypt(
switch (encryptionType) {
case SESSION_MESSAGE: {
// if (destination.isPrivate || destination.isUS) {
const cipherText = await MessageEncrypter.encryptUsingSessionProtocol(
PubKey.cast(destination.key),
plainTextPadded
);
return { envelopeType: SESSION_MESSAGE, cipherText };
// }
// if (destination.isGroupV2 || destination.isLegacyGroup) {
// throw new PreConditionFailed(
// 'Encryption with SESSION_MESSAGE only work with destination private or us'
// );
// }
// assertUnreachable(
// destination,
// 'Encryption with SESSION_MESSAGE only work with destination private or us'
// );
}
case CLOSED_GROUP_MESSAGE: {
@ -92,26 +81,10 @@ export async function encrypt(
};
}
// if (destination.isLegacyGroup) {
return encryptForLegacyGroup(destination, plainTextPadded); // not padding it again, it is already done by libsession
// }
// if (
// destination.isBlinded ||
// destination.isBlinded ||
// destination.isPrivate ||
// destination.isUS
// ) {
// throw new PreConditionFailed(
// 'Encryption with CLOSED_GROUP_MESSAGE only work with destination groupv2 or legacy group'
// );
// }
// assertUnreachable(
// destination,
// 'Encryption with CLOSED_GROUP_MESSAGE only work with destination groupv2 or legacy group'
// );
}
default:
assertUnreachable(encryptionType, '');
assertUnreachable(encryptionType, 'MessageEncrypter encrypt unreachable case');
}
}

@ -1,4 +1,4 @@
import _, { isNumber } from 'lodash';
import _, { isFinite, isNumber } from 'lodash';
import { v4 as uuidv4 } from 'uuid';
import { PubKey } from '../types';

@ -1,10 +1,10 @@
import { GroupPubkeyType } from 'libsession_util_nodejs';
import { SignalService } from '../../../../protobuf';
import { PubKey } from '../../../types';
import { StringUtils } from '../../../utils';
import { VisibleMessage } from './VisibleMessage';
import { ClosedGroupMessage } from '../controlMessage/group/ClosedGroupMessage';
import { DataMessage } from '../DataMessage';
import { GroupPubkeyType } from 'libsession_util_nodejs';
import { SnodeNamespaces } from '../../../apis/snode_api/namespaces';
interface ClosedGroupVisibleMessageParams {

@ -68,11 +68,9 @@ export class HTTPError extends Error {
}
class BaseError extends Error {
public readonly context?: Object;
constructor(message: string, context?: Object) {
constructor(message: string) {
super(message);
this.name = this.constructor.name;
this.context = context;
}
}

@ -28,6 +28,7 @@ import {
PersistedJob,
RunJobResult,
} from '../PersistedJob';
import { assertUnreachable } from '../../../../types/sqlSharedTypes';
const defaultMsBetweenRetries = 15000; // a long time between retries, to avoid running multiple jobs at the same time, when one was postponed at the same time as one already planned (5s)
const defaultMaxAttempts = 2;
@ -96,8 +97,8 @@ async function buildAndSaveDumpsToDB(
for (let i = 0; i < changes.length; i++) {
const change = changes[i];
switch (change.pushed.namespace) {
const namespace = change.pushed.namespace;
switch (namespace) {
case SnodeNamespaces.ClosedGroupInfo: {
if ((change.pushed as any).seqno) {
toConfirm[1].groupInfo = [change.pushed.seqno.toNumber(), change.updatedHash];
@ -108,6 +109,11 @@ async function buildAndSaveDumpsToDB(
toConfirm[1].groupMember = [change.pushed.seqno.toNumber(), change.updatedHash];
break;
}
case SnodeNamespaces.ClosedGroupKeys: {
break;
}
default:
assertUnreachable(namespace, 'buildAndSaveDumpsToDB assertUnreachable');
}
}

@ -308,6 +308,7 @@ async function pendingChangesForGroup(
return { messages: results, allOldHashes };
}
// eslint-disable-next-line consistent-return
function userKindToVariant(kind: UserConfigKind): ConfigWrapperUser {
switch (kind) {
case SignalService.SharedConfigMessage.Kind.USER_PROFILE:
@ -323,6 +324,7 @@ function userKindToVariant(kind: UserConfigKind): ConfigWrapperUser {
}
}
// eslint-disable-next-line consistent-return
function userVariantToUserKind(variant: ConfigWrapperUser) {
switch (variant) {
case 'UserConfig':

@ -1,3 +1,4 @@
/* eslint-disable no-await-in-loop */
import { PayloadAction, createAsyncThunk, createSlice } from '@reduxjs/toolkit';
import { GroupInfoGet, GroupMemberGet, GroupPubkeyType } from 'libsession_util_nodejs';
import { isEmpty, uniq } from 'lodash';
@ -49,86 +50,80 @@ const initNewGroupInWrapper = createAsyncThunk(
throw new PreConditionFailed('initNewGroupInWrapper needs us to be a member');
}
const uniqMembers = uniq(members);
try {
const newGroup = await UserGroupsWrapperActions.createGroup();
const groupPk = newGroup.pubkeyHex;
newGroup.name = groupName; // this will be used by the linked devices until they fetch the info from the groups swarm
const newGroup = await UserGroupsWrapperActions.createGroup();
const groupPk = newGroup.pubkeyHex;
newGroup.name = groupName; // this will be used by the linked devices until they fetch the info from the groups swarm
await UserGroupsWrapperActions.setGroup(newGroup);
await UserGroupsWrapperActions.setGroup(newGroup);
const ourEd25519KeypairBytes = await UserUtils.getUserED25519KeyPairBytes();
if (!ourEd25519KeypairBytes) {
throw new Error('Current user has no priv ed25519 key?');
}
const userEd25519Secretkey = ourEd25519KeypairBytes.privKeyBytes;
const groupEd2519Pk = HexString.fromHexString(groupPk).slice(1); // remove the 03 prefix (single byte once in hex form)
// dump is always empty when creating a new groupInfo
await MetaGroupWrapperActions.init(groupPk, {
metaDumped: null,
userEd25519Secretkey: toFixedUint8ArrayOfLength(userEd25519Secretkey, 64),
groupEd25519Secretkey: newGroup.secretKey,
groupEd25519Pubkey: toFixedUint8ArrayOfLength(groupEd2519Pk, 32),
});
for (let index = 0; index < uniqMembers.length; index++) {
const member = uniqMembers[index];
const created = await MetaGroupWrapperActions.memberGetOrConstruct(groupPk, member);
if (created.pubkeyHex === us) {
await MetaGroupWrapperActions.memberSetPromoted(groupPk, created.pubkeyHex, false);
} else {
await MetaGroupWrapperActions.memberSetInvited(groupPk, created.pubkeyHex, false);
}
}
const ourEd25519KeypairBytes = await UserUtils.getUserED25519KeyPairBytes();
if (!ourEd25519KeypairBytes) {
throw new Error('Current user has no priv ed25519 key?');
}
const userEd25519Secretkey = ourEd25519KeypairBytes.privKeyBytes;
const groupEd2519Pk = HexString.fromHexString(groupPk).slice(1); // remove the 03 prefix (single byte once in hex form)
// dump is always empty when creating a new groupInfo
await MetaGroupWrapperActions.init(groupPk, {
metaDumped: null,
userEd25519Secretkey: toFixedUint8ArrayOfLength(userEd25519Secretkey, 64),
groupEd25519Secretkey: newGroup.secretKey,
groupEd25519Pubkey: toFixedUint8ArrayOfLength(groupEd2519Pk, 32),
});
const infos = await MetaGroupWrapperActions.infoGet(groupPk);
if (!infos) {
throw new Error(`getInfos of ${groupPk} returned empty result even if it was just init.`);
for (let index = 0; index < uniqMembers.length; index++) {
const member = uniqMembers[index];
const created = await MetaGroupWrapperActions.memberGetOrConstruct(groupPk, member);
if (created.pubkeyHex === us) {
await MetaGroupWrapperActions.memberSetPromoted(groupPk, created.pubkeyHex, false);
} else {
await MetaGroupWrapperActions.memberSetInvited(groupPk, created.pubkeyHex, false);
}
infos.name = groupName;
await MetaGroupWrapperActions.infoSet(groupPk, infos);
}
const membersFromWrapper = await MetaGroupWrapperActions.memberGetAll(groupPk);
if (!membersFromWrapper || isEmpty(membersFromWrapper)) {
throw new Error(
`memberGetAll of ${groupPk} returned empty result even if it was just init.`
);
}
const infos = await MetaGroupWrapperActions.infoGet(groupPk);
if (!infos) {
throw new Error(`getInfos of ${groupPk} returned empty result even if it was just init.`);
}
infos.name = groupName;
await MetaGroupWrapperActions.infoSet(groupPk, infos);
const convo = await getConversationController().getOrCreateAndWait(
groupPk,
ConversationTypeEnum.GROUPV3
);
await convo.setIsApproved(true, false);
// console.warn('store the v3 identityPrivatekeypair as part of the wrapper only?');
// // the sync below will need the secretKey of the group to be saved in the wrapper. So save it!
await UserGroupsWrapperActions.setGroup(newGroup);
await GroupSync.queueNewJobIfNeeded(groupPk);
// const updateGroupDetails: ClosedGroup.GroupInfo = {
// id: newGroup.pubkeyHex,
// name: groupDetails.groupName,
// members,
// admins: [us],
// activeAt: Date.now(),
// expireTimer: 0,
// };
// // be sure to call this before sending the message.
// // the sending pipeline needs to know from GroupUtils when a message is for a medium group
// await ClosedGroup.updateOrCreateClosedGroup(updateGroupDetails);
await convo.unhideIfNeeded();
convo.set({ active_at: Date.now() });
await convo.commit();
convo.updateLastMessage();
return { groupPk: newGroup.pubkeyHex, infos, members: membersFromWrapper };
} catch (e) {
throw e;
const membersFromWrapper = await MetaGroupWrapperActions.memberGetAll(groupPk);
if (!membersFromWrapper || isEmpty(membersFromWrapper)) {
throw new Error(`memberGetAll of ${groupPk} returned empty result even if it was just init.`);
}
const convo = await getConversationController().getOrCreateAndWait(
groupPk,
ConversationTypeEnum.GROUPV3
);
await convo.setIsApproved(true, false);
// console.warn('store the v3 identityPrivatekeypair as part of the wrapper only?');
// // the sync below will need the secretKey of the group to be saved in the wrapper. So save it!
await UserGroupsWrapperActions.setGroup(newGroup);
await GroupSync.queueNewJobIfNeeded(groupPk);
// const updateGroupDetails: ClosedGroup.GroupInfo = {
// id: newGroup.pubkeyHex,
// name: groupDetails.groupName,
// members,
// admins: [us],
// activeAt: Date.now(),
// expireTimer: 0,
// };
// // be sure to call this before sending the message.
// // the sending pipeline needs to know from GroupUtils when a message is for a medium group
// await ClosedGroup.updateOrCreateClosedGroup(updateGroupDetails);
await convo.unhideIfNeeded();
convo.set({ active_at: Date.now() });
await convo.commit();
convo.updateLastMessage();
return { groupPk: newGroup.pubkeyHex, infos, members: membersFromWrapper };
}
);

@ -278,7 +278,9 @@ export function toFixedUint8ArrayOfLength<T extends number>(
data: Uint8Array,
length: T
): FixedSizeUint8Array<T> {
if (data.length === length) return data as any as FixedSizeUint8Array<T>;
if (data.length === length) {
return data as any as FixedSizeUint8Array<T>;
}
throw new Error(
`toFixedUint8ArrayOfLength invalid. Expected length ${length} but got: ${data.length}`
);

@ -71,7 +71,7 @@ export function isMetaWrapperType(config: ConfigWrapperObjectTypesMeta): config
}
export function getGroupPubkeyFromWrapperType(type: ConfigWrapperGroup): GroupPubkeyType {
if (!type.startsWith(MetaGroupConfigValue + '03')) {
if (!type.startsWith(`${MetaGroupConfigValue}03`)) {
throw new Error(`not a metagroup variant: ${type}`);
}
return type.substring(type.indexOf('-03') + 1) as GroupPubkeyType; // typescript is not yet smart enough

Loading…
Cancel
Save