GithubHelp home page GithubHelp logo

aws-mqtt's People

Contributors

kmamykin avatar liqwid avatar valdeci-dev avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

aws-mqtt's Issues

Make the `will` parameter works to send a message by the broker automatically when the client disconnect badly

On the MQTT doc, we have the option to use the will parameter to send a message by the broker automatically when the client disconnect badly.

I'm trying to make this work with aws-mqtt, but I can't.

My client example:

const client = AWSMqtt.connect({
 WebSocket: WebSocket,
 region: AWS.config.region,
 credentials: AWS.config.credentials,
 endpoint: config.aws.iot.endpoint,
 clientId: 'mqtt-time-publisher-' + (Math.floor((Math.random() * 100000) + 1)),
 will: {
       topic: `MY-TOPIC`,
       payload: 'disconected',
       qos: 0,
       retain: false
     }
})

Is there any way to do this works?

Code 1005 is reserved and may not be used in React Native

This is my code:

import Aws from 'aws-sdk/dist/aws-sdk-react-native'
import AwsIot from 'aws-iot-device-sdk'

AWS_REGION = 'us-east-1' // Change if needed.
AWS_COGNITO_IDENTITY_POOL = 'us-east-1:******-******-******-******-******' 
AWS_IOT_ENDPOINT = '******-ats.iot.us-east-1.amazonaws.com' // Fill in.

Aws.config.region = AWS_REGION
Aws.config.credentials = new Aws.CognitoIdentityCredentials({
  IdentityPoolId: AWS_COGNITO_IDENTITY_POOL
})

Aws.config.credentials.get(() => {
const config = {}
let client

config.host = AWS_IOT_ENDPOINT
config.protocol = 'wss'
config.clientId = `client-${Math.floor((Math.random() * 100000) + 1)}`
config.accessKeyId = Aws.config.credentials.accessKeyId
config.secretKey = Aws.config.credentials.secretAccessKey
config.sessionToken = Aws.config.credentials.sessionToken

client = AwsIot.device(config)

client.on('connect', () => {
    client.subscribe('some_topic')
})

client.on('message', (topic, message) => {
    console.log("topic", topic)
    console.log("message", message)
})

client.on('error', error => {
    console.log("error", error)
})
})

Then it gives me an error:

Event {
  "isTrusted": false,
  "message": "Code 1005 is reserved and may not be used.",
}

crypto could not be found within the project.

Failed building JavaScript bundle.
Unable to resolve module crypto from C:\Users+\IoTApp\node_modules\aws-mqtt\lib\urlSigner.js: crypto could not be found within the project.

I have crypto installed but it gives this error

Not working with ws version 5.2.1

Can not connect to the MQTT broker over WebSocket when using the current version of ws, version 5.2.1. It works with 1.1.1 which is used in the examples.

Feature request - Support for custom authorizers

AWS supports custom authentication/authorization through custom authorizers. This involves the client sending in an optional authorizer name, an auth token, and digest for the token based on a cert. These must be sent in the Websocket headers. Apparently web browsers won't permit this (?) but CLI nodejs environment will.

This mqtt library is very simple and straightforward in syntax. If it supported custom authorizers it would do everything I need.

Issue with last will message

Hi,
I have used this module for AWS mqtt iot connection, but the lwt topic inside will that we passed in AWSMqtt.connect() method is not calling when we turn off the device or network disconnect.

Below is the code snippet:

var AWS = require('aws-sdk');
var AWSMqtt = require('aws-mqtt');

var params = {
IdentityPoolId: 'xxxxxx-xxxxx-xxxxxxx'
};

cognitoService=Utils.mqttSetup();
cognitoService.getId(params, function (err, data) {
CONFIG.IdentityId = data.IdentityId;
});

AWS.config.region = 'xx-xxxx-x';
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
IdentityId: CONFIG.IdentityId
});

var mqttClient = AWSMqtt.connect({
WebSocket: window.WebSocket,
region: AWS.config.region,
credentials: AWS.config.credentials,
endpoint: 'xxxxxxxxxx.iot.xxxxxxxx',
clientId: 'mqttjs_' + (Math.floor((Math.random() * 100000) + 1)),
will: {
topic: '/lwt',
payload: 'hello',
qos: 0,
retain: false
}
});

Error in Angular 8+

Uncaught TypeError: Cannot read property 'slice' of undefined
    at Object../node_modules/aws-mqtt/node_modules/readable-stream/lib/_stream_writable.js (_stream_writable.js:57)
    at __webpack_require__ (bootstrap:79)
    at Object../node_modules/aws-mqtt/node_modules/readable-stream/readable-browser.js (readable-browser.js:4)
    at __webpack_require__ (bootstrap:79)
    at Object../node_modules/aws-mqtt/node_modules/mqtt/lib/store.js (store.js:8)
    at __webpack_require__ (bootstrap:79)
    at Object../node_modules/aws-mqtt/node_modules/mqtt/lib/client.js (client.js:7)
    at __webpack_require__ (bootstrap:79)
    at Object../node_modules/aws-mqtt/lib/BrowserClient.js (BrowserClient.js:7)
    at __webpack_require__ (bootstrap:79)

process.version.split is not a function

Uncaught TypeError: process.version.split is not a function
at Object../node_modules/pbkdf2/lib/default-encoding.js (default-encoding.js:6)
at webpack_require (bootstrap:79)
at Object../node_modules/pbkdf2/lib/async.js (async.js:2)
at webpack_require (bootstrap:79)
at Object../node_modules/pbkdf2/browser.js (browser.js:1)
at webpack_require (bootstrap:79)
at Object../node_modules/crypto-browserify/index.js (index.js:14)
at webpack_require (bootstrap:79)
at Object../node_modules/aws-signature-v4/index.js (index.js:8)
at webpack_require (bootstrap:79)

Code fails on import:
Angular 8.2.3

If I comment out your module it loads fine.

import AWSMqttClient from 'aws-mqtt'

The problem of reconnection of web end network

How do you do? I'd like to ask you a question.

When using aws-mqtt, the browser closes the network. When we open the network again, we can see that the information displayed on the console has been linked, closed, offline, linked, closed and offline, and it has been recycled. I want to ask how to solve such a problem.

I look forward to your answer and thank you first.
image

Upon connecting, cannot subscribe without setting client.connected = true

After doing extensive testing and debugging, I found that client.connected is set to false after connecting, and that subscriptions simply fail silently -- without even calling the callback -- if client.connected is false.

I had to force it to true, before subscriptions worked as expected.

    client.on('connect', (ack) => {
            console.log("Connected to MQTT", ack);
            // I shouldn't have to manually set connected to true!!!
            client.connected = true;
            client.subscribe("/ATopic", {}, (err, granted) => {
                ...
            });
            ...
    });

This took me nearly three hours of wasted time to debug. FIX THIS PLEASE.

severity vulnerabilities due to dependencies

Please, update dependencies.

npm audit report

glob-parent <5.1.2
Severity: high
glob-parent before 5.1.2 vulnerable to Regular Expression Denial of Service in enclosure regex - GHSA-ww39-953v-wcq6
No fix available
node_modules/glob-stream/node_modules/glob-parent
glob-stream 5.3.0 - 6.1.0
Depends on vulnerable versions of glob-parent
node_modules/glob-stream
help-me 1.0.0 - 1.1.0
Depends on vulnerable versions of glob-stream
node_modules/aws-mqtt/node_modules/help-me
mqtt 1.14.1 - 4.2.6
Depends on vulnerable versions of help-me
node_modules/aws-mqtt/node_modules/mqtt
aws-mqtt *
Depends on vulnerable versions of mqtt
node_modules/aws-mqtt

5 high severity vulnerabilities

Microsoft Edge Browser and message event

It looks like the message event is not being fired on the Microsoft Edge Browser, even after successfully connecting and subscribing to a topic. Browser version is Microsoft Edge 38.14393.0.0.

Works great otherwise, on Firefox and Chrome.

Edit: Looks like the packet for subscribe gets sent but no suback is returned.

Memory Leak

There is a memory leak problem here. I'm not sure why it's happening. Here's what's going on.

I have been logging events emitted, and every several seconds, I'm receiving an "offline" event. I've been trying to figure it out. It is causing the MQTT client to reconnect. But, it's in the reconnect that we have issues.

Every time you reconnect, it creates another client listener. This creates an exponential problem.

For instance, here's some debugging:

super(() => createWebSocketStream(WebSocket, aws), mqtt)

In this super() method, this callback get's called every time it tries to reconnect. This is creating a lot of listeners.

Right now, from the client created, I'm doing some debugging like:

client.on('packetReceive', () => console.log('packetReceive'))

Every reconnect, the number of these messages grows exponentially.

Risk: over-authorization of AWS IoT policy

We are a security research team and we recently discovered that there is an over-authorization security issue with this project's IoT policy.
The affected file is as following:

1. aws-mqtt/README.md

mqttClient.end() result with clientInitiatedDisconnect = False

We have a rule for unplanned disconnections for our IoT devices
And its picking up our automation which uses this Lib
We use the .end to disconnect the client after it finished its job (under each handler)
Which result with this JSON on the disconnection:

{
 "clientId": "a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6",
 "timestamp": 1460065214626,
 "eventType": "connected",
 "sessionIdentifier": "00000000-0000-0000-0000-000000000000",
 "principalIdentifier": "000000000000/ABCDEFGHIJKLMNOPQRSTU:some-user/
ABCDEFGHIJKLMNOPQRSTU:some-user",
 "clientInitiatedDisconnect": false
}

This is how we setup each client :

`var mqttClient = this.AWSIoTData.device({
  region: this.regionData,
  host:this.host,
  clientId: this.myclientId,
  protocol: 'wss',
  maximumReconnectTimeMs: 8000,
  debug: true,
  accessKeyId: cards.Data.AccessKeyId,   
     secretKey: cards.Data.SecretAccessKey, 
     sessionToken: cards.Data.Token   });`

how can we close and kill a client with "clientInitiatedDisconnect": true ?
Or is it a bug?

Socket Closing Abruptly

Hello,

I did the basic setup for the frontend as per documentation. I created CognitoIdentityCredentials with an identity pool that allows both unauthenticated users and the unauthenticated users have been given the correct access to use iot in the respective IAM policy. Now, that setup is working fine. The connection is established and the user is able to subscribe and get the response. I wanted to integrate authentication/authorization into this process as my architecture involves multi tenancy (i.e. there are a lot of user/identity pools and I want the current logged in user to only have access to its resources). I know for sure that the policies are setup correctly (as the access that is given to both authenticated and unauthenticated user is the same).

However, my socket keeps on disconnecting when I am trying to do the authenticated connection. I gives me a premature close error. I tried to dig deep into this issue and ran a debugger. The urlSigner is working fine so there shouldn't be any issues on the aws side.

For the authenticated connection, I am adding Logins field to the AWS.CognitoIdentityCredentials constructor which I found in this document

Working with AWS EC2MetadataCredentials Provider

When using the library on an EC2 instance (which has sufficient privileges through IAM) the library never seems to connect. As soon as the application starts I seem to end in an endless loop of the following.

{"level":50,"time":1566245540498,"pid":3823,"hostname":"ip-x","msg":"Error: Connection was closed abnormally","v":1}
{"level":40,"time":1566245540498,"pid":3823,"hostname":"ip-x","msg":"Connection to MQTT broker closed","v":1}
{"level":50,"time":1566245545502,"pid":3823,"hostname":"ip-x","msg":"Error: Connection was closed abnormally","v":1}
{"level":40,"time":1566245545502,"pid":3823,"hostname":"ip-x","msg":"Connection to MQTT broker closed","v":1}

I've used the same code on my local machine which resolves the credentials from the SharedIni file provider (Rather than the metadata service) and it works as expected.

I presume it's perhaps to do with the fact that the Metadata Credentials provider as async?

I've tried resolving the credentials myself rather than just passing in AWS.config.credentials which does work, but not without its own issue. For example

AWS.config.credentialProvider.resolve(
  (_, credentials): void => {
    if (credentials) {
      console.log(
        'Resolved AWS Credentials from',
        credentials.constructor.name
      );

      AWS.config.credentials = credentials;
    
      const client = new AWSMqttClient({
        expires: 86400,
        rejectUnauthorized: process.env.NODE_ENV === 'production',
        region: process.env.AWS_REGION,
        credentials: AWS.config.credentials,
        endpoint: endpoint,
        reconnectPeriod: Number(process.env.RECONNECT_WAIT) || 5000,
      });

      const error = (err) => console.error(err.toString());
      const close = () => console.warn('Connection to MQTT broker closed');
      const reconnect = () => console.info('Reconnecting to MQTT broker');
      const offline = () => console.warn('Connection to MQTT broker offline');
      const connect = () => console.log('Established connection with MQTT broker (AWS)');
  
      client.on('connect', connect);
      client.on('error', error);
      client.on('close', close);
      client.on('reconnect', reconnect);
      client.on('offline', offline);
    }
  }
);

This works both locally (SharedIni) and on EC2 (EC2Metadata) but fails to reconnect once the session expires. After a while, the library seems to send in an endless loop of the following.

image

Presumably I'm doing something not quite right as opposed to it being a bug/unexpected behaviour?

[Question, Feature] Use sts.AssumeRole credentials possible?

Hi!

Using this awesome client as a PubSub broker for Apollo GraphQL. While doing so I initially tried to make it work using sts.AssumeRole but noticed that there needs to be compatible refresh and get methods on the credentials object passed in, like the Cognito example.

I've tried to implement them but with little success, getting errors with invalid/missing credentials, and I'm wondering if this even possible at all. I can't seem to find anything to confirm or deny this in the IoT docs or what the expected shape should be for those invocations.

With some pointers I'd be able to add this functionality to the client I think, if its feasible at all :)

Error when publishing msg.

I just tried to send a simple msg to AWSIoT

const publish = AWSMqtt.publisher({
WebSocket: WebSocket,
region: AWS.config.region,
credentials: AWS.config.credentials,
endpoint: 'xxxxxxxxx.iot.eu-west-1.amazonaws.com'
})

publish('/myTopic', 'Hello World').then(() => console.log('Success'), console.error)

Error: MQTT went offline
at Client. (/var/app/current/node_modules/aws-mqtt/lib/publisher.js:32:16)
at Client.g (events.js:291:16)
at emitNone (events.js:86:13)
at Client.emit (events.js:185:7)
at Client.MqttClient._setupReconnect (/var/app/current/node_modules/mqtt/lib/client.js:590:12)
at emitOne (events.js:101:20)
at Client.emit (events.js:188:7)
at WebSocketStream.f (/var/app/current/node_modules/once/once.js:25:25)
at emitOne (events.js:101:20)
at WebSocketStream.emit (events.js:188:7)

Please advice me.

Messages show as being published yet do not appear in MQTT

Title is self-descripting. I am trying to publish messages to MQTT, it connects successfully and appears to publish successfully however nothing appears when subscribed to the MQTT topic.

I am fairly new to AWS IoT so I am guessing I am missing something simple. Could this be a permission issue, and if so how can I tell? Any advice would be helpful, thanks!

Cognito Auth tokens and long running websocket

I am using the websocket with both cognito auth and unauth and it is working great! Except, that cognito auth tokens expire every hour. This cannot be extended. In one use case the websocket needs to be open for about 2 hours. I understand how to refresh the token, but the websocket throws what seems to be an uncatchable error. Wondering if there is something I'm missing.

The error is: UncaughtException NotAuthorizedException: Invalid login token. Token expired: [epoch time] >= [epoch time]

The on('error') listener doesn't get called when this happens. It does come thru the error listener if you try to refresh but there's no error event if you're just listening that I can see.

Can add a timeout to just refresh at some other point in the app but seems like it should come thru the error listener.

Outdated version on npm

Hi,
Could you update aws-mqtt on npm? Npm's version is missing some key features such as last will testament.
Cheers!

Error in connection establishment

Followed the in-browser usage and got the following error on localhost.

BrowserClient.js:68 WebSocket connection to 'wss://...' failed: Error in connection establishment: net::ERR_CERT_REVOKED

My dev app server is behind an Nginx web server with a self-signed SSL certificate. I'm suspecting this is the reason why it failed to connect, but how do I fix it?

I'm new to the whole message broker, web socket, SSL stuff. Any help is appreciated

How can I end correctly the connection?

I'm using the browser client and calling client.end() to disconnect the client,
but the callback of connected are calling each time I reconnect...
So for example, I initialize the connection and all good, then I close the connection (or at least I thougth I was closing it) and initialize another connection and my callbacks are excuting twice.. I tried starting a new connection with a new id, because if try to reconnect, the client is connectin and reconnecting, so it seems like it's trying to connect using the same connection id...
Any idea of what could be the problem..? Thank you.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.