matrix-org / matrix-js-sdk

Matrix Client-Server SDK for JavaScript
Apache License 2.0
1.61k stars 589 forks source link

When I'm receiving message from simulator I'm getting these error and decryptEvent not working but from element I'm not getting any error and decryptEvent is working #1770

Open mmeksasi opened 3 years ago

mmeksasi commented 3 years ago

Describe the bug When I'm receiving message from simulator I'm getting these errors and decryptEvent is not working but from element I'm not getting any error and decryptEvent is working

- backend.js:12506 Error decrypting event (id=$MA4iyvrb4CTzsvssSyEWtdSGrvBCnHcMCO-NHtVdf6A): DecryptionError[msg: The secure channel with the sender was corrupted. Trying to create a new secure channel and re-requesting the keys., session: Xt9jl1f8mvnBwk2ot7p5sd836vf2XWZQGjZ/HyAlhDY|bUv6ow4zFTz6a4qQbjpHxdTJPjASul8In2N0qKKGgmg]

- ExceptionsManager.js:179 RECEIVE MESSAGE ERROR DecryptionError: The secure channel with the sender was corrupted. Trying to create a new secure channel and re-requesting the keys.

- backend.js:12506 No one-time keys (alg=signed_curve25519) for device @test15:kubernetesMaster.dtp.ae:JXMAFXJLSO

import React, { useEffect } from 'react';
  import { StyleSheet, Text, View } from 'react-native';
  import matrixSdk, { MemoryStore, MatrixEvent } from 'matrix-js-sdk';
  import request from 'xmlhttp-request';
  import AsyncStorage from '@react-native-async-storage/async-storage';
  import AsyncCryptoStore from './lib/AsyncCryptoStore';

const BASE_URL = 'http://192.168.102.121:30808';
export const MATRIX_CLIENT_START_OPTIONS = {
  initialSyncLimit: 10,
  request: request,
  lazyLoadMembers: true,
  pendingEventOrdering: 'detached',
  timelineSupport: true,
  unstableClientRelationAggregation: true,
  store: new MemoryStore({
    localStorage: AsyncStorage,
  }),
  cryptoStore: new AsyncCryptoStore(AsyncStorage),
  sessionStore: {
    getLocalTrustedBackupPubKey: () => null,
  }, // js-sdk complains if this isn't supplied but it's only used for remembering a local trusted backup key
};
export var matrixAlias = {};

export const LoginToChat = async ({ register = false, callBack }) => {
  try {
    const username = 'dtp18';
    const chatPassword = 'Midomek@1';
    const registrationClient = await matrixSdk.createClient(BASE_URL);
    if (username && chatPassword) {
      try {
        userRegisterResult = await registrationClient.login(
          'm.login.password',
          {
            user: username,
            password: chatPassword,
          }
        );
      } catch (e) {
        console.log('error login', e);
      }
    } else {
      return;
    }

    const matrixClient = await matrixSdk.createClient({
      baseUrl: BASE_URL,
      userId: userRegisterResult.user_id,
      accessToken: userRegisterResult.access_token,
      deviceId: userRegisterResult.device_id,
      ...MATRIX_CLIENT_START_OPTIONS,
    });
    await matrixClient.initCrypto();
    await matrixClient.startClient();
    matrixAlias = matrixClient;
    matrixAlias.once('sync', async function (state, prevState, res) {
      // after client is ready
      if (state === 'PREPARED') {
        await matrixClient.uploadKeys();
        matrixClient.exportRoomKeys();
        getTimeline();
        callBack && callBack();
      }
    });
  } catch (e) {
    printError(e);
  }
};

export const sendMessageChat = async ({ message, roomID }) => {
  autoVerify(roomID);

  const content = {
    body: message,
    msgtype: 'm.text',
  };

  try {
    const result = await matrixAlias.sendEvent(
      roomID,
      'm.room.message',
      content
    );
  } catch (err) {
    console.log('SEND MESSAGE ERROR ', err);
    alert('sending error');
  }
};

export const getTimeline = () => {
  matrixAlias.on('Room.timeline', async (message, room, toStartOfTimeline) => {
    let body = '';
    let event;

    try {
      if (message.event.type === 'm.room.encrypted') {
        autoVerify(message.event.room_id);

        event = await matrixAlias._crypto.decryptEvent(message);
        ({ body } = event?.clearEvent?.content ?? '');
      } else {
        ({ body } = message.event.content);
      }

      if (body) {
        console.log(body);
      }
    } catch (error) {
      console.error('RECEIVE MESSAGE ERROR ', error);
    }
  });
};

export const autoVerify = async (room_id) => {
  let room = matrixAlias.getRoom(room_id);
 let members = (await room.getEncryptionTargetMembers()).map(
    (x) => x['userId']
  );
  let memberkeys = await matrixAlias.downloadKeys(members);
     await matrixAlias.claimOneTimeKeys({
      one_time_keys: memberkeys,
    });
  const e2eMembers = await room.getEncryptionTargetMembers();
  for (const member of e2eMembers) {
    const devices = matrixAlias.getStoredDevicesForUser(member.userId);
    for (const device of devices) {
      if (device.isUnverified()) {
        await verifyDevice(member.userId, device.deviceId);
      }
    }
  }
};

export async function verifyDevice(userId, deviceId) {
  if (!userId || typeof userId !== 'string') {
    throw new Error('"userId" is required and must be a string.');
  }
  if (!deviceId || typeof deviceId !== 'string') {
    throw new Error('"deviceId" is required and must be a string.');
  }
  await matrixAlias.setDeviceKnown(userId, deviceId, true);
  await matrixAlias.setDeviceVerified(userId, deviceId, true);
}

const testingChat = () => {
  useEffect(() => {
    LoginToChat({
      callBack: () => {
        sendMessageChat({
          message: 'hello',
          roomID: '!NrNMsmxdVaSDSnhzYc:kubernetesMaster.dtp.ae',
        });
      },
    });
  }, []);
  return  null
};

export default testingChat;
samerdernaika commented 3 years ago

same here , any solution for this !!

samikoja commented 3 years ago

same here !!

maciejjanawa commented 3 years ago

same situation here, exactly the same error message. At the beginning I thought it's a problem with debug mode and network inspector on React Native but it works on real android device (in debug mode also). The issue only occurs on iOS simulator. Any thought on this? It's not a blocker issue but it makes development much more harder

maciejjanawa commented 3 years ago

@mmeksasi did you manage to solve it somehow? On my side currently it stopped working at all, both on device and simulator and I have no idea why because nothing has changed

mmeksasi commented 3 years ago

@t3chguy if you can help please

maciejjanawa commented 3 years ago

btw, which version of sdk do you have? I'm currently playing with 8.5.0 because on higher I'm getting addSharedHistoryInboundGroupSession is not a function error when sending messages in encrypted rooms. Could you share your AsyncCryptoStore implementation? I'm using one from this link and it looks like addSharedHistoryInboundGroupSession method is missing

mmeksasi commented 3 years ago

I'm using 10.1.0 and I'm also using the same implementation for AsyncCryptoStore and sometimes get this error also addSharedHistoryInboundGroupSession is not a function SEND KEYS ERROR TypeError: _this23._cryptoStore.getSharedHistoryInboundGroupSessions is not a function at OlmDevice.js:1271 at AsyncCryptoStore.doTxn (AsyncCryptoStore.js:151) at OlmDevice._callee24$ (OlmDevice.js:1270) at tryCatch (runtime.js:63) at Generator.invoke [as _invoke] (runtime.js:293) at Generator.next (runtime.js:118) at tryCatch (runtime.js:63) at invoke (runtime.js:154) at runtime.js:189 at tryCallTwo (core.js:45)

Electrofenster commented 3 years ago

any news on this error?