aws-amplify / amplify-js

A declarative JavaScript library for application development using cloud services.
https://docs.amplify.aws/lib/q/platform/js
Apache License 2.0
9.4k stars 2.11k forks source link

Dependency on paho-mqtt should be removed - package is no longer maintained and contains bugs #9185

Closed ffxsam closed 1 year ago

ffxsam commented 2 years ago

Before opening, please confirm:

JavaScript Framework

Not applicable

Amplify APIs

PubSub

Amplify Categories

Not applicable

Environment information

``` # Put output below this line System: OS: macOS 11.6 CPU: (12) x64 Intel(R) Core(TM) i7-8700B CPU @ 3.20GHz Memory: 20.23 GB / 64.00 GB Shell: 5.8 - /bin/zsh Binaries: Node: 14.18.1 - ~/.volta/tools/image/node/14.18.1/bin/node Yarn: 2.4.1 - ~/.volta/tools/image/yarn/1.22.17/bin/yarn npm: 6.14.15 - ~/.volta/tools/image/node/14.18.1/bin/npm Watchman: 2021.11.01.00 - /usr/local/bin/watchman Browsers: Brave Browser: 91.1.26.74 Chrome: 95.0.4638.69 Firefox: 94.0.1 Safari: 15.0 npmPackages: @babel/core: ^7.15.5 => 7.15.5 (7.15.0, 7.14.3) @maxmind/geoip2-node: ^3.2.0 => 3.2.0 @nuxt/types: ~2.15.8 => 2.15.8 @nuxtjs/axios: ^5.13.6 => 5.13.6 @nuxtjs/eslint-config: ^5.0.0 => 5.0.0 @nuxtjs/eslint-module: ^3.0.2 => 3.0.2 @nuxtjs/sentry: ^5.1.4 => 5.1.4 @nuxtjs/vuetify: ^1.12.1 => 1.12.1 @vue/cli-plugin-babel: ^4.5.13 => 4.5.13 @vue/eslint-config-standard: ^6.1.0 => 6.1.0 aliyun-nodejs: 1.0.0 aws-alexa-typescript: 1.0.0 aws-amplify: ^4.3.1 => 4.3.1 aws-nodejs-ecma-script: 1.0.0 aws-nodejs-typescript: 1.0.0 azure-nodejs: 1.0.0 azure-nodejs-typescript: 1.0.0 azure-python: 1.0.0 babel-eslint: ^10.1.0 => 10.1.0 babel-jest: ^27.2.4 => 27.2.4 camelcase-keys: ^6.2.2 => 6.2.2 (7.0.0) change-case: ^4.1.2 => 4.1.2 cloudflare-workers: 1.0.0 cloudflare-workers-enterprise: 1.0.0 cloudflare-workers-rust: 1.0.0 cookie-universal-nuxt: ^2.1.5 => 2.1.5 core-js: ^3.18.1 => 3.18.1 (2.6.12, 3.16.1, 3.16.0) debug: ^4.3.2 => 4.3.2 (2.6.9, 3.1.0, 3.2.7) dev: 1.0.0 env-cmd: ^10.1.0 => 10.1.0 eslint: ^7.32.0 => 7.32.0 eslint-config-prettier: ^7.2.0 => 7.2.0 eslint-plugin-nuxt: ^2.0.0 => 2.0.0 eslint-plugin-prettier: ^3.4.1 => 3.4.1 eslint-plugin-vue: ^7.18.0 => 7.18.0 (7.10.0) fn-go: 1.0.0 fn-node: 1.0.0 google-nodejs: 0.1.0 google-nodejs-typescript: 1.0.0 google-python: 0.1.0 hellofn: 1.0.0 husky: ^4.3.8 => 4.3.8 jest: ^27.2.4 => 27.2.4 knative-docker: 1.0.0 konva: ^8.2.1 => 8.2.1 kubeless-nodejs: 1.0.0 kubeless-python: 1.0.0 lint-staged: ^10.5.4 => 10.5.4 lodash.debounce: ^4.0.8 => 4.0.8 nuxt: ^2.15.8 => 2.15.8 nuxt-start: ^2.15.8 => 2.15.8 openwhisk-java: 1.0.0 openwhisk-nodejs: 1.0.0 openwhisk-php: 1.0.0 openwhisk-python: 1.0.0 openwhisk-ruby: 1.0.0 openwhisk-swift: 1.0.0 plyr: ^3.6.8 => 3.6.8 prettier: ^2.4.1 => 2.4.1 (1.19.1) serverless: ^2.59.0 => 2.59.0 serverless-apigw-binary: ^0.4.4 => 0.4.4 serverless-domain-manager: ^5.1.5 => 5.1.5 serverless-google-hello-world: 0.1.0 serverless-nuxt: ^1.1.2 => 1.1.2 serverless-nuxt-plugin: ^1.5.0 => 1.5.0 serverless-openwhisk-hello-world: 0.1.0 serverless-plugin: 1.0.0 sls-csharp: 1.0.0 spotionst-java8: 1.0.0 spotionst-nodejs: 1.0.0 spotionst-python: 1.0.0 spotionst-ruby: 1.0.0 tencent-golang: 1.0.0 tencent-nodejs: 1.0.0 tencent-php: 1.0.0 tencent-python: 1.0.0 tinycolor2: ^1.4.2 => 1.4.2 twilio-nodejs-runtime-example: 1.0.0 validator: ^13.6.0 => 13.6.0 vue-linkify: ^1.0.1 => 1.0.1 vuetify: ^2.5.9 => 2.5.9 (2.5.3) vuetify-loader: ^1.7.3 => 1.7.3 (1.7.2) vuex: ^3.6.2 => 3.6.2 waveform-data: ^4.1.1 => 4.1.1 npmGlobalPackages: npm: 6.14.15 ```

Describe the bug

AWS Amplify should definitely consider replacing paho-mqtt with something else. It's a package that's no longer maintained, and has issues which are causing Amplify to break.

While there are workarounds like using patch-package to monkey patch it, this isn't ideal as many people don't know this is even possible (I didn't know until today!).

Expected behavior

N/A

Reproduction steps

N/A

Code Snippet

No response

Log output

No response

aws-exports.js

No response

Manual configuration

No response

Additional configuration

No response

Mobile Device

No response

Mobile Operating System

No response

Mobile Browser

No response

Mobile Browser Version

No response

Additional information and screenshots

No response

ashika01 commented 2 years ago

@ffxsam Whats the issue on amplify you are seeing as result of the paho-mqtt broken??

ffxsam commented 2 years ago

@ashika01 It's all detailed in the link above.

ashika01 commented 2 years ago

I am working on trying to reproduce the issue locally in a sample but I am having issues with just trying to connect. I keep getting websocket connection failed errors unlike the local storage issues in the link

marcelbecker commented 2 years ago

paho-mqtt is using an EPL license (Eclipse Public License) if I see it correctly. Can I use it in my JavaScript Browser application? Isn't it a problem when WebPack is modifying the code and distributing it to a huge number of devices via the internet? Is it compatible with the Apache license? -> Found an answer to this question that has already been discussed: https://github.com/aws/aws-iot-device-sdk-embedded-C/issues/142

yaquawa commented 2 years ago

Hi @ffxsam , I'm using Amplify.js and facing the same issue... Had you solved this problem eventually?

ffxsam commented 2 years ago

@yaquawa I sure did. The solution was to use Yarn's patch feature (make sure you're using Yarn 3.x). But I can save you most of the work.

In case you're using the old Yarn 1.x, the quickest way to switch to the latest version:

$ cd myproject
$ yarn set version berry
$ yarn config set nodeLinker node-modules

and add this to your .gitignore:

# Yarn 2
.yarn/*
!.yarn/patches
!.yarn/releases
!.yarn/plugins
!.yarn/sdks
!.yarn/versions
.pnp.*

Once that's all set up, copy this file into .yarn/patches:

paho-mqtt-npm-1.1.0-c2bf8169e8
``` diff --git a/paho-mqtt-min.js b/paho-mqtt-min.js index c24e9b7ba683ac70fefccac54c4bab7bb4719ccf..9b9753b9b39ea454ea1da509805a548f1c329951 100644 --- a/paho-mqtt-min.js +++ b/paho-mqtt-min.js @@ -1,75 +1 @@ -/******************************************************************************* - * Copyright (c) 2013, 2016 IBM Corp. - * - * All rights reserved. This program and the accompanying materials - * are made available under the terms of the Eclipse Public License v1.0 - * and Eclipse Distribution License v1.0 which accompany this distribution. - * - * The Eclipse Public License is available at - * http://www.eclipse.org/legal/epl-v10.html - * and the Eclipse Distribution License is available at - * http://www.eclipse.org/org/documents/edl-v10.php. - * - *******************************************************************************/ -(function(t,q){"object"===typeof exports&&"object"===typeof module?module.exports=q():"function"===typeof define&&define.amd?define(q):"object"===typeof exports?exports=q():t.Paho=q()})(this,function(){return function(t){function q(a,b,c){b[c++]=a>>8;b[c++]=a%256;return c}function r(a,b,c,k){k=q(b,c,k);E(a,c,k);return k+b}function n(a){for(var b=0,c=0;c=k&&(c++,b++),b+=3):127=e){var g=a.charCodeAt(++k);if(isNaN(g))throw Error(f(h.MALFORMED_UNICODE,[e,g]));e=(e-55296<<10)+(g-56320)+65536}127>=e?b[c++]=e:(2047>=e?b[c++]=e>>6&31|192:(65535>=e?b[c++]=e>>12&15|224:(b[c++]=e>>18&7|240,b[c++]=e>>12&63|128),b[c++]=e>>6&63|128),b[c++]=e&63|128)}return b}function F(a,b,c){for(var k="",e,g=b;ge)){var m=a[g++]-128;if(0>m)throw Error(f(h.MALFORMED_UTF,[e.toString(16),m.toString(16),""]));if(224>e)e=64*(e-192)+m;else{var d= - a[g++]-128;if(0>d)throw Error(f(h.MALFORMED_UTF,[e.toString(16),m.toString(16),d.toString(16)]));if(240>e)e=4096*(e-224)+64*m+d;else{var l=a[g++]-128;if(0>l)throw Error(f(h.MALFORMED_UTF,[e.toString(16),m.toString(16),d.toString(16),l.toString(16)]));if(248>e)e=262144*(e-240)+4096*m+64*d+l;else throw Error(f(h.MALFORMED_UTF,[e.toString(16),m.toString(16),d.toString(16),l.toString(16)]));}}}65535>10)),e=56320+(e&1023));k+=String.fromCharCode(e)}return k} - var s=t.localStorage||function(){var a={};return{setItem:function(b,c){a[b]=c},getItem:function(b){return a[b]},removeItem:function(b){delete a[b]}}}(),A=function(a,b){for(var c in a)if(a.hasOwnProperty(c))if(b.hasOwnProperty(c)){if(typeof a[c]!==b[c])throw Error(f(h.INVALID_TYPE,[typeof a[c],c]));}else{c="Unknown property, "+c+". Valid properties are:";for(var k in b)b.hasOwnProperty(k)&&(c=c+" "+k);throw Error(c);}},u=function(a,b){return function(){return a.apply(b,arguments)}},h={OK:{code:0,text:"AMQJSC0000I OK."}, - CONNECT_TIMEOUT:{code:1,text:"AMQJSC0001E Connect timed out."},SUBSCRIBE_TIMEOUT:{code:2,text:"AMQJS0002E Subscribe timed out."},UNSUBSCRIBE_TIMEOUT:{code:3,text:"AMQJS0003E Unsubscribe timed out."},PING_TIMEOUT:{code:4,text:"AMQJS0004E Ping timed out."},INTERNAL_ERROR:{code:5,text:"AMQJS0005E Internal error. Error Message: {0}, Stack trace: {1}"},CONNACK_RETURNCODE:{code:6,text:"AMQJS0006E Bad Connack return code:{0} {1}."},SOCKET_ERROR:{code:7,text:"AMQJS0007E Socket error:{0}."},SOCKET_CLOSE:{code:8, - text:"AMQJS0008I Socket closed."},MALFORMED_UTF:{code:9,text:"AMQJS0009E Malformed UTF data:{0} {1} {2}."},UNSUPPORTED:{code:10,text:"AMQJS0010E {0} is not supported by this browser."},INVALID_STATE:{code:11,text:"AMQJS0011E Invalid state {0}."},INVALID_TYPE:{code:12,text:"AMQJS0012E Invalid type {0} for {1}."},INVALID_ARGUMENT:{code:13,text:"AMQJS0013E Invalid argument {0} for {1}."},UNSUPPORTED_OPERATION:{code:14,text:"AMQJS0014E Unsupported operation."},INVALID_STORED_DATA:{code:15,text:"AMQJS0015E Invalid data in local storage key\x3d{0} value\x3d{1}."}, - INVALID_MQTT_MESSAGE_TYPE:{code:16,text:"AMQJS0016E Invalid MQTT message type {0}."},MALFORMED_UNICODE:{code:17,text:"AMQJS0017E Malformed Unicode string:{0} {1}."},BUFFER_FULL:{code:18,text:"AMQJS0018E Message buffer is full, maximum buffer size: {0}."}},H={0:"Connection Accepted",1:"Connection Refused: unacceptable protocol version",2:"Connection Refused: identifier rejected",3:"Connection Refused: server unavailable",4:"Connection Refused: bad user name or password",5:"Connection Refused: not authorized"}, - f=function(a,b){var c=a.text;if(b)for(var k,e,g=0;g>7;0d);f=g.length+1;b=new ArrayBuffer(b+f);d=new Uint8Array(b);d[0]=a;d.set(g,1);if(3==this.type)f=r(this.payloadMessage.destinationName, - k,d,f);else if(1==this.type){switch(this.mqttVersion){case 3:d.set(B,f);f+=B.length;break;case 4:d.set(C,f),f+=C.length}a=0;this.cleanSession&&(a=2);void 0!==this.willMessage&&(a=a|4|this.willMessage.qos<<3,this.willMessage.retained&&(a|=32));void 0!==this.userName&&(a|=128);void 0!==this.password&&(a|=64);d[f++]=a;f=q(this.keepAliveInterval,d,f)}void 0!==this.messageIdentifier&&(f=q(this.messageIdentifier,d,f));switch(this.type){case 1:f=r(this.clientId,n(this.clientId),d,f);void 0!==this.willMessage&& - (f=r(this.willMessage.destinationName,n(this.willMessage.destinationName),d,f),f=q(e.byteLength,d,f),d.set(e,f),f+=e.byteLength);void 0!==this.userName&&(f=r(this.userName,n(this.userName),d,f));void 0!==this.password&&r(this.password,n(this.password),d,f);break;case 3:d.set(h,f);break;case 8:for(g=0;gthis.disconnectedBufferSize)throw Error(f(h.BUFFER_FULL,[this.disconnectedBufferSize]));0this.connectOptions.mqttVersion?new WebSocket(a,["mqttv3.1"]):new WebSocket(a,["mqtt"]);this.socket.binaryType="arraybuffer";this.socket.onopen=u(this._on_socket_open,this);this.socket.onmessage=u(this._on_socket_message,this);this.socket.onerror=u(this._on_socket_error,this);this.socket.onclose=u(this._on_socket_close, - this);this.sendPinger=new G(this,this.connectOptions.keepAliveInterval);this.receivePinger=new G(this,this.connectOptions.keepAliveInterval);this._connectTimeout&&(this._connectTimeout.cancel(),this._connectTimeout=null);this._connectTimeout=new v(this,this.connectOptions.timeout,this._disconnected,[h.CONNECT_TIMEOUT.code,f(h.CONNECT_TIMEOUT)])};d.prototype._schedule_message=function(a){this._msg_queue.unshift(a);this.connected&&this._process_queue()};d.prototype.store=function(a,b){var c={type:b.type, - messageIdentifier:b.messageIdentifier,version:1};switch(b.type){case 3:b.pubRecReceived&&(c.pubRecReceived=!0);c.payloadMessage={};for(var d="",e=b.payloadMessage.payloadBytes,g=0;g=e[g]?d+"0"+e[g].toString(16):d+e[g].toString(16);c.payloadMessage.payloadHex=d;c.payloadMessage.qos=b.payloadMessage.qos;c.payloadMessage.destinationName=b.payloadMessage.destinationName;b.payloadMessage.duplicate&&(c.payloadMessage.duplicate=!0);b.payloadMessage.retained&&(c.payloadMessage.retained= - !0);0===a.indexOf("Sent:")&&(void 0===b.sequence&&(b.sequence=++this._sequence),c.sequence=b.sequence);break;default:throw Error(f(h.INVALID_STORED_DATA,[a+this._localKey+b.messageIdentifier,c]));}s.setItem(a+this._localKey+b.messageIdentifier,JSON.stringify(c))};d.prototype.restore=function(a){var b=s.getItem(a),c=JSON.parse(b),d=new p(c.type,c);switch(c.type){case 3:for(var b=c.payloadMessage.payloadHex,e=new ArrayBuffer(b.length/2),e=new Uint8Array(e),g=0;2<=b.length;){var m=parseInt(b.substring(0, - 2),16),b=b.substring(2,b.length);e[g++]=m}b=new w(e);b.qos=c.payloadMessage.qos;b.destinationName=c.payloadMessage.destinationName;c.payloadMessage.duplicate&&(b.duplicate=!0);c.payloadMessage.retained&&(b.retained=!0);d.payloadMessage=b;break;default:throw Error(f(h.INVALID_STORED_DATA,[a,b]));}0===a.indexOf("Sent:"+this._localKey)?(d.payloadMessage.duplicate=!0,this._sentMessages[d.messageIdentifier]=d):0===a.indexOf("Received:"+this._localKey)&&(this._receivedMessages[d.messageIdentifier]=d)}; - d.prototype._process_queue=function(){for(var a=null;a=this._msg_queue.pop();)this._socket_send(a),this._notify_msg_sent[a]&&(this._notify_msg_sent[a](),delete this._notify_msg_sent[a])};d.prototype._requires_ack=function(a){var b=Object.keys(this._sentMessages).length;if(b>this.maxMessageIdentifier)throw Error("Too many messages:"+b);for(;void 0!==this._sentMessages[this._message_identifier];)this._message_identifier++;a.messageIdentifier=this._message_identifier;this._sentMessages[a.messageIdentifier]= - a;3===a.type&&this.store("Sent:",a);this._message_identifier===this.maxMessageIdentifier&&(this._message_identifier=1)};d.prototype._on_socket_open=function(){var a=new p(1,this.connectOptions);a.clientId=this.clientId;this._socket_send(a)};d.prototype._on_socket_message=function(a){this._trace("Client._on_socket_message",a.data);a=this._deframeMessages(a.data);for(var b=0;b>4,z=n&15,g=g+1,x=void 0,D=0,q=1;do{if(g==e.length){d=[null,m];break a}x=e[g++];D+=(x&127)*q;q*=128}while(0!==(x&128));x=g+D;if(x>e.length)d=[null,m];else{var y=new p(l);switch(l){case 2:e[g++]&1&&(y.sessionPresent=!0);y.returnCode=e[g++];break;case 3:var m=z>>1&3,s=256*e[g]+e[g+1],g=g+2,t=F(e,g,s), - g=g+s;0this._reconnectInterval&&(this._reconnectInterval*=2),this.connectOptions.uris?(this.hostIndex=0,this._doConnect(this.connectOptions.uris[0])):this._doConnect(this.uri))};d.prototype._disconnected=function(a,b){this._trace("Client._disconnected",a,b);if(void 0!==a&&this._reconnecting)this._reconnectTimeout=new v(this,this._reconnectInterval,this._reconnect);else if(this.sendPinger.cancel(),this.receivePinger.cancel(),this._connectTimeout&& - (this._connectTimeout.cancel(),this._connectTimeout=null),this._msg_queue=[],this._buffered_msg_queue=[],this._notify_msg_sent={},this.socket&&(this.socket.onopen=null,this.socket.onmessage=null,this.socket.onerror=null,this.socket.onclose=null,1===this.socket.readyState&&this.socket.close(),delete this.socket),this.connectOptions.uris&&this.hostIndexb)throw Error(f(h.INVALID_TYPE,[typeof b,"port"]));if("string"!==typeof c)throw Error(f(h.INVALID_TYPE,[typeof c,"path"]));e="ws://"+(-1!==a.indexOf(":")&&"["!==a.slice(0,1)&&"]"!==a.slice(-1)?"["+a+"]":a)+":"+b+c}for(var m=g=0;m=n&&m++;g++}if("string"!==typeof k||65535a.mqttVersion)throw Error(f(h.INVALID_ARGUMENT,[a.mqttVersion,"connectOptions.mqttVersion"]));void 0===a.mqttVersion?(a.mqttVersionExplicit=!1,a.mqttVersion=4):a.mqttVersionExplicit=!0;if(void 0!==a.password&&void 0===a.userName)throw Error(f(h.INVALID_ARGUMENT,[a.password,"connectOptions.password"]));if(a.willMessage){if(!(a.willMessage instanceof - w))throw Error(f(h.INVALID_TYPE,[a.willMessage,"connectOptions.willMessage"]));a.willMessage.stringPayload=null;if("undefined"===typeof a.willMessage.destinationName)throw Error(f(h.INVALID_TYPE,[typeof a.willMessage.destinationName,"connectOptions.willMessage.destinationName"]));}"undefined"===typeof a.cleanSession&&(a.cleanSession=!0);if(a.hosts){if(!(a.hosts instanceof Array))throw Error(f(h.INVALID_ARGUMENT,[a.hosts,"connectOptions.hosts"]));if(1>a.hosts.length)throw Error(f(h.INVALID_ARGUMENT, - [a.hosts,"connectOptions.hosts"]));for(var b=!1,d=0;da.ports[d])throw Error(f(h.INVALID_TYPE,[typeof a.ports[d],"connectOptions.ports["+d+"]"]));var b=a.hosts[d],g=a.ports[d];e="ws://"+(-1!==b.indexOf(":")?"["+b+"]":b)+":"+g+c;a.uris.push(e)}}}l.connect(a)}; - this.subscribe=function(a,b){if("string"!==typeof a&&a.constructor!==Array)throw Error("Invalid argument:"+a);b=b||{};A(b,{qos:"number",invocationContext:"object",onSuccess:"function",onFailure:"function",timeout:"number"});if(b.timeout&&!b.onFailure)throw Error("subscribeOptions.timeout specified with no onFailure callback.");if("undefined"!==typeof b.qos&&0!==b.qos&&1!==b.qos&&2!==b.qos)throw Error(f(h.INVALID_ARGUMENT,[b.qos,"subscribeOptions.qos"]));l.subscribe(a,b)};this.unsubscribe=function(a, - b){if("string"!==typeof a&&a.constructor!==Array)throw Error("Invalid argument:"+a);b=b||{};A(b,{invocationContext:"object",onSuccess:"function",onFailure:"function",timeout:"number"});if(b.timeout&&!b.onFailure)throw Error("unsubscribeOptions.timeout specified with no onFailure callback.");l.unsubscribe(a,b)};this.send=function(a,b,c,d){var e;if(0===arguments.length)throw Error("Invalid argument.length");if(1==arguments.length){if(!(a instanceof w)&&"string"!==typeof a)throw Error("Invalid argument:"+ - typeof a);e=a;if("undefined"===typeof e.destinationName)throw Error(f(h.INVALID_ARGUMENT,[e.destinationName,"Message.destinationName"]));}else e=new w(b),e.destinationName=a,3<=arguments.length&&(e.qos=c),4<=arguments.length&&(e.retained=d);l.send(e)};this.publish=function(a,b,c,d){var e;if(0===arguments.length)throw Error("Invalid argument.length");if(1==arguments.length){if(!(a instanceof w)&&"string"!==typeof a)throw Error("Invalid argument:"+typeof a);e=a;if("undefined"===typeof e.destinationName)throw Error(f(h.INVALID_ARGUMENT, - [e.destinationName,"Message.destinationName"]));}else e=new w(b),e.destinationName=a,3<=arguments.length&&(e.qos=c),4<=arguments.length&&(e.retained=d);l.send(e)};this.disconnect=function(){l.disconnect()};this.getTraceLog=function(){return l.getTraceLog()};this.startTrace=function(){l.startTrace()};this.stopTrace=function(){l.stopTrace()};this.isConnected=function(){return l.connected}},Message:w}}("undefined"!==typeof global?global:"undefined"!==typeof self?self:"undefined"!==typeof window?window: - {})}); \ No newline at end of file +(function(R,y){typeof exports=="object"&&typeof module=="object"?module.exports=y():typeof define=="function"&&define.amd?define(y):typeof exports=="object"?exports=y():R.Paho=y()})(this,function(){var R=function(y){var F="@VERSION@-@BUILDLEVEL@",A=function(){var e={};return{setItem:function(t,n){e[t]=n},getItem:function(t){return e[t]},removeItem:function(t){delete e[t]}}}();try{y.localStorage&&(A=y.localStorage)}catch{}var _={CONNECT:1,CONNACK:2,PUBLISH:3,PUBACK:4,PUBREC:5,PUBREL:6,PUBCOMP:7,SUBSCRIBE:8,SUBACK:9,UNSUBSCRIBE:10,UNSUBACK:11,PINGREQ:12,PINGRESP:13,DISCONNECT:14},x=function(e,t){for(var n in e)if(e.hasOwnProperty(n))if(t.hasOwnProperty(n)){if(typeof e[n]!==t[n])throw new Error(c(a.INVALID_TYPE,[typeof e[n],n]))}else{var s="Unknown property, "+n+". Valid properties are:";for(var o in t)t.hasOwnProperty(o)&&(s=s+" "+o);throw new Error(s)}},w=function(e,t){return function(){return e.apply(t,arguments)}},a={OK:{code:0,text:"AMQJSC0000I OK."},CONNECT_TIMEOUT:{code:1,text:"AMQJSC0001E Connect timed out."},SUBSCRIBE_TIMEOUT:{code:2,text:"AMQJS0002E Subscribe timed out."},UNSUBSCRIBE_TIMEOUT:{code:3,text:"AMQJS0003E Unsubscribe timed out."},PING_TIMEOUT:{code:4,text:"AMQJS0004E Ping timed out."},INTERNAL_ERROR:{code:5,text:"AMQJS0005E Internal error. Error Message: {0}, Stack trace: {1}"},CONNACK_RETURNCODE:{code:6,text:"AMQJS0006E Bad Connack return code:{0} {1}."},SOCKET_ERROR:{code:7,text:"AMQJS0007E Socket error:{0}."},SOCKET_CLOSE:{code:8,text:"AMQJS0008I Socket closed."},MALFORMED_UTF:{code:9,text:"AMQJS0009E Malformed UTF data:{0} {1} {2}."},UNSUPPORTED:{code:10,text:"AMQJS0010E {0} is not supported by this browser."},INVALID_STATE:{code:11,text:"AMQJS0011E Invalid state {0}."},INVALID_TYPE:{code:12,text:"AMQJS0012E Invalid type {0} for {1}."},INVALID_ARGUMENT:{code:13,text:"AMQJS0013E Invalid argument {0} for {1}."},UNSUPPORTED_OPERATION:{code:14,text:"AMQJS0014E Unsupported operation."},INVALID_STORED_DATA:{code:15,text:"AMQJS0015E Invalid data in local storage key={0} value={1}."},INVALID_MQTT_MESSAGE_TYPE:{code:16,text:"AMQJS0016E Invalid MQTT message type {0}."},MALFORMED_UNICODE:{code:17,text:"AMQJS0017E Malformed Unicode string:{0} {1}."},BUFFER_FULL:{code:18,text:"AMQJS0018E Message buffer is full, maximum buffer size: {0}."}},O={0:"Connection Accepted",1:"Connection Refused: unacceptable protocol version",2:"Connection Refused: identifier rejected",3:"Connection Refused: server unavailable",4:"Connection Refused: bad user name or password",5:"Connection Refused: not authorized"},c=function(e,t){var n=e.text;if(t){for(var s,o,r=0;r0){var f=n.substring(0,o),v=n.substring(o+s.length);n=f+t[r]+v}}return n},P=[0,6,77,81,73,115,100,112,3],L=[0,4,77,81,84,84,4],m=function(e,t){this.type=e;for(var n in t)t.hasOwnProperty(n)&&(this[n]=t[n])};m.prototype.encode=function(){var e=(this.type&15)<<4,t=0,n=[],s=0,o;switch(this.messageIdentifier!==void 0&&(t+=2),this.type){case _.CONNECT:switch(this.mqttVersion){case 3:t+=P.length+3;break;case 4:t+=L.length+3;break}t+=p(this.clientId)+2,this.willMessage!==void 0&&(t+=p(this.willMessage.destinationName)+2,o=this.willMessage.payloadBytes,o instanceof Uint8Array||(o=new Uint8Array(f)),t+=o.byteLength+2),this.userName!==void 0&&(t+=p(this.userName)+2),this.password!==void 0&&(t+=p(this.password)+2);break;case _.SUBSCRIBE:e|=2;for(var r=0;r>4,r=s&=15;t+=1;var f,v=0,l=1;do{if(t==e.length)return[null,n];f=e[t++],v+=(f&127)*l,l*=128}while((f&128)!=0);var d=t+v;if(d>e.length)return[null,n];var h=new m(o);switch(o){case _.CONNACK:var i=e[t++];i&1&&(h.sessionPresent=!0),h.returnCode=e[t++];break;case _.PUBLISH:var E=r>>1&3,g=C(e,t);t+=2;var N=D(e,t,g);t+=g,E>0&&(h.messageIdentifier=C(e,t),t+=2);var I=new T(e.subarray(t,d));(r&1)==1&&(I.retained=!0),(r&8)==8&&(I.duplicate=!0),I.qos=E,I.destinationName=N,h.payloadMessage=I;break;case _.PUBACK:case _.PUBREC:case _.PUBREL:case _.PUBCOMP:case _.UNSUBACK:h.messageIdentifier=C(e,t);break;case _.SUBACK:h.messageIdentifier=C(e,t),t+=2,h.returnCode=e.subarray(t,d);break;default:break}return[h,d]}function M(e,t,n){return t[n++]=e>>8,t[n++]=e%256,n}function S(e,t,n,s){return s=M(t,n,s),k(e,n,s),s+t}function C(e,t){return 256*e[t]+e[t+1]}function b(e){var t=new Array(1),n=0;do{var s=e%128;e=e>>7,e>0&&(s|=128),t[n++]=s}while(e>0&&n<4);return t}function p(e){for(var t=0,n=0;n2047?(55296<=s&&s<=56319&&(n++,t++),t+=3):s>127?t+=2:t++}return t}function k(e,t,n){for(var s=n,o=0;o>6&31|192,t[s++]=r&63|128):r<=65535?(t[s++]=r>>12&15|224,t[s++]=r>>6&63|128,t[s++]=r&63|128):(t[s++]=r>>18&7|240,t[s++]=r>>12&63|128,t[s++]=r>>6&63|128,t[s++]=r&63|128)}return t}function D(e,t,n){for(var s="",o,r=t;r65535&&(o-=65536,s+=String.fromCharCode(55296+(o>>10)),o=56320+(o&1023)),s+=String.fromCharCode(o)}return s}var B=function(e,t){this._client=e,this._keepAliveInterval=t*1e3,this.isReset=!1;var n=new m(_.PINGREQ).encode(),s=function(r){return function(){return o.apply(r)}},o=function(){this.isReset?(this.isReset=!1,this._client._trace("Pinger.doPing","send PINGREQ"),this._client.socket.send(n),this.timeout=setTimeout(s(this),this._keepAliveInterval)):(this._client._trace("Pinger.doPing","Timed out"),this._client._disconnected(a.PING_TIMEOUT.code,c(a.PING_TIMEOUT)))};this.reset=function(){this.isReset=!0,clearTimeout(this.timeout),this._keepAliveInterval>0&&(this.timeout=setTimeout(s(this),this._keepAliveInterval))},this.cancel=function(){clearTimeout(this.timeout)}},U=function(e,t,n,s){t||(t=30);var o=function(r,f,v){return function(){return r.apply(f,v)}};this.timeout=setTimeout(o(n,e,s),t*1e3),this.cancel=function(){clearTimeout(this.timeout)}},u=function(e,t,n,s,o){if(!("WebSocket"in y&&y.WebSocket!==null))throw new Error(c(a.UNSUPPORTED,["WebSocket"]));if(!("ArrayBuffer"in y&&y.ArrayBuffer!==null))throw new Error(c(a.UNSUPPORTED,["ArrayBuffer"]));this._trace("Paho.Client",e,t,n,s,o),this.host=t,this.port=n,this.path=s,this.uri=e,this.clientId=o,this._wsuri=null,this._localKey=t+":"+n+(s!="/mqtt"?":"+s:"")+":"+o+":",this._msg_queue=[],this._buffered_msg_queue=[],this._sentMessages={},this._receivedMessages={},this._notify_msg_sent={},this._message_identifier=1,this._sequence=0;for(var r in A)(r.indexOf("Sent:"+this._localKey)===0||r.indexOf("Received:"+this._localKey)===0)&&this.restore(r)};u.prototype.host=null,u.prototype.port=null,u.prototype.path=null,u.prototype.uri=null,u.prototype.clientId=null,u.prototype.socket=null,u.prototype.connected=!1,u.prototype.maxMessageIdentifier=65536,u.prototype.connectOptions=null,u.prototype.hostIndex=null,u.prototype.onConnected=null,u.prototype.onConnectionLost=null,u.prototype.onMessageDelivered=null,u.prototype.onMessageArrived=null,u.prototype.traceFunction=null,u.prototype._msg_queue=null,u.prototype._buffered_msg_queue=null,u.prototype._connectTimeout=null,u.prototype.sendPinger=null,u.prototype.receivePinger=null,u.prototype._reconnectInterval=1,u.prototype._reconnecting=!1,u.prototype._reconnectTimeout=null,u.prototype.disconnectedPublishing=!1,u.prototype.disconnectedBufferSize=5e3,u.prototype.receiveBuffer=null,u.prototype._traceBuffer=null,u.prototype._MAX_TRACE_ENTRIES=100,u.prototype.connect=function(e){var t=this._traceMask(e,"password");if(this._trace("Client.connect",t,this.socket,this.connected),this.connected)throw new Error(c(a.INVALID_STATE,["already connected"]));if(this.socket)throw new Error(c(a.INVALID_STATE,["already connected"]));this._reconnecting&&(this._reconnectTimeout.cancel(),this._reconnectTimeout=null,this._reconnecting=!1),this.connectOptions=e,this._reconnectInterval=1,this._reconnecting=!1,e.uris?(this.hostIndex=0,this._doConnect(e.uris[0])):this._doConnect(this.uri)},u.prototype.subscribe=function(e,t){if(this._trace("Client.subscribe",e,t),!this.connected)throw new Error(c(a.INVALID_STATE,["not connected"]));var n=new m(_.SUBSCRIBE);n.topics=e.constructor===Array?e:[e],t.qos===void 0&&(t.qos=0),n.requestedQos=[];for(var s=0;s0?this._requires_ack(t):this.onMessageDelivered&&(this._notify_msg_sent[t]=this.onMessageDelivered(t.payloadMessage)),this._schedule_message(t);else if(this._reconnecting&&this.disconnectedPublishing){var n=Object.keys(this._sentMessages).length+this._buffered_msg_queue.length;if(n>this.disconnectedBufferSize)throw new Error(c(a.BUFFER_FULL,[this.disconnectedBufferSize]));e.qos>0?this._requires_ack(t):(t.sequence=++this._sequence,this._buffered_msg_queue.unshift(t))}else throw new Error(c(a.INVALID_STATE,["not connected"]))},u.prototype.disconnect=function(){if(this._trace("Client.disconnect"),this._reconnecting&&(this._reconnectTimeout.cancel(),this._reconnectTimeout=null,this._reconnecting=!1),!this.socket)throw new Error(c(a.INVALID_STATE,["not connecting or connected"]));var e=new m(_.DISCONNECT);this._notify_msg_sent[e]=w(this._disconnected,this),this._schedule_message(e)},u.prototype.getTraceLog=function(){if(this._traceBuffer!==null){this._trace("Client.getTraceLog",new Date),this._trace("Client.getTraceLog in flight messages",this._sentMessages.length);for(var e in this._sentMessages)this._trace("_sentMessages ",e,this._sentMessages[e]);for(var e in this._receivedMessages)this._trace("_receivedMessages ",e,this._receivedMessages[e]);return this._traceBuffer}},u.prototype.startTrace=function(){this._traceBuffer===null&&(this._traceBuffer=[]),this._trace("Client.startTrace",new Date,F)},u.prototype.stopTrace=function(){delete this._traceBuffer},u.prototype._doConnect=function(e){if(this.connectOptions.useSSL){var t=e.split(":");t[0]="wss",e=t.join(":")}this._wsuri=e,this.connected=!1,this.connectOptions.mqttVersion<4?this.socket=new WebSocket(e,["mqttv3.1"]):this.socket=new WebSocket(e,["mqtt"]),this.socket.binaryType="arraybuffer",this.socket.onopen=w(this._on_socket_open,this),this.socket.onmessage=w(this._on_socket_message,this),this.socket.onerror=w(this._on_socket_error,this),this.socket.onclose=w(this._on_socket_close,this),this.sendPinger=new B(this,this.connectOptions.keepAliveInterval),this.receivePinger=new B(this,this.connectOptions.keepAliveInterval),this._connectTimeout&&(this._connectTimeout.cancel(),this._connectTimeout=null),this._connectTimeout=new U(this,this.connectOptions.timeout,this._disconnected,[a.CONNECT_TIMEOUT.code,c(a.CONNECT_TIMEOUT)])},u.prototype._schedule_message=function(e){this._msg_queue.unshift(e),this.connected&&this._process_queue()},u.prototype.store=function(e,t){var n={type:t.type,messageIdentifier:t.messageIdentifier,version:1};switch(t.type){case _.PUBLISH:t.pubRecReceived&&(n.pubRecReceived=!0),n.payloadMessage={};for(var s="",o=t.payloadMessage.payloadBytes,r=0;r=2;){var l=parseInt(o.substring(0,2),16);o=o.substring(2,o.length),f[v++]=l}var d=new T(f);d.qos=n.payloadMessage.qos,d.destinationName=n.payloadMessage.destinationName,n.payloadMessage.duplicate&&(d.duplicate=!0),n.payloadMessage.retained&&(d.retained=!0),s.payloadMessage=d;break;default:throw Error(c(a.INVALID_STORED_DATA,[e,t]))}e.indexOf("Sent:"+this._localKey)===0?(s.payloadMessage.duplicate=!0,this._sentMessages[s.messageIdentifier]=s):e.indexOf("Received:"+this._localKey)===0&&(this._receivedMessages[s.messageIdentifier]=s)},u.prototype._process_queue=function(){for(var e=null;e=this._msg_queue.pop();)this._socket_send(e),this._notify_msg_sent[e]&&(this._notify_msg_sent[e](),delete this._notify_msg_sent[e])},u.prototype._requires_ack=function(e){var t=Object.keys(this._sentMessages).length;if(t>this.maxMessageIdentifier)throw Error("Too many messages:"+t);for(;this._sentMessages[this._message_identifier]!==void 0;)this._message_identifier++;e.messageIdentifier=this._message_identifier,this._sentMessages[e.messageIdentifier]=e,e.type===_.PUBLISH&&this.store("Sent:",e),this._message_identifier===this.maxMessageIdentifier&&(this._message_identifier=1)},u.prototype._on_socket_open=function(){var e=new m(_.CONNECT,this.connectOptions);e.clientId=this.clientId,this._socket_send(e)},u.prototype._on_socket_message=function(e){this._trace("Client._on_socket_message",e.data);for(var t=this._deframeMessages(e.data),n=0;n0)for(var o=null;o=this._buffered_msg_queue.pop();)n.push(o),this.onMessageDelivered&&(this._notify_msg_sent[o]=this.onMessageDelivered(o.payloadMessage));for(var n=n.sort(function(g,N){return g.sequence-N.sequence}),r=0,f=n.length;r65535)throw new Error(c(a.INVALID_ARGUMENT,[s,"clientId"]));var h=new u(o,e,t,n,s);Object.defineProperties(this,{host:{get:function(){return e},set:function(){throw new Error(c(a.UNSUPPORTED_OPERATION))}},port:{get:function(){return t},set:function(){throw new Error(c(a.UNSUPPORTED_OPERATION))}},path:{get:function(){return n},set:function(){throw new Error(c(a.UNSUPPORTED_OPERATION))}},uri:{get:function(){return o},set:function(){throw new Error(c(a.UNSUPPORTED_OPERATION))}},clientId:{get:function(){return h.clientId},set:function(){throw new Error(c(a.UNSUPPORTED_OPERATION))}},onConnected:{get:function(){return h.onConnected},set:function(i){if(typeof i=="function")h.onConnected=i;else throw new Error(c(a.INVALID_TYPE,[typeof i,"onConnected"]))}},disconnectedPublishing:{get:function(){return h.disconnectedPublishing},set:function(i){h.disconnectedPublishing=i}},disconnectedBufferSize:{get:function(){return h.disconnectedBufferSize},set:function(i){h.disconnectedBufferSize=i}},onConnectionLost:{get:function(){return h.onConnectionLost},set:function(i){if(typeof i=="function")h.onConnectionLost=i;else throw new Error(c(a.INVALID_TYPE,[typeof i,"onConnectionLost"]))}},onMessageDelivered:{get:function(){return h.onMessageDelivered},set:function(i){if(typeof i=="function")h.onMessageDelivered=i;else throw new Error(c(a.INVALID_TYPE,[typeof i,"onMessageDelivered"]))}},onMessageArrived:{get:function(){return h.onMessageArrived},set:function(i){if(typeof i=="function")h.onMessageArrived=i;else throw new Error(c(a.INVALID_TYPE,[typeof i,"onMessageArrived"]))}},trace:{get:function(){return h.traceFunction},set:function(i){if(typeof i=="function")h.traceFunction=i;else throw new Error(c(a.INVALID_TYPE,[typeof i,"onTrace"]))}}}),this.connect=function(i){if(i=i||{},x(i,{timeout:"number",userName:"string",password:"string",willMessage:"object",keepAliveInterval:"number",cleanSession:"boolean",useSSL:"boolean",invocationContext:"object",onSuccess:"function",onFailure:"function",hosts:"object",ports:"object",reconnect:"boolean",mqttVersion:"number",mqttVersionExplicit:"boolean",uris:"object"}),i.keepAliveInterval===void 0&&(i.keepAliveInterval=60),i.mqttVersion>4||i.mqttVersion<3)throw new Error(c(a.INVALID_ARGUMENT,[i.mqttVersion,"connectOptions.mqttVersion"]));if(i.mqttVersion===void 0?(i.mqttVersionExplicit=!1,i.mqttVersion=4):i.mqttVersionExplicit=!0,i.password!==void 0&&i.userName===void 0)throw new Error(c(a.INVALID_ARGUMENT,[i.password,"connectOptions.password"]));if(i.willMessage){if(!(i.willMessage instanceof T))throw new Error(c(a.INVALID_TYPE,[i.willMessage,"connectOptions.willMessage"]));if(i.willMessage.stringPayload=null,typeof i.willMessage.destinationName=="undefined")throw new Error(c(a.INVALID_TYPE,[typeof i.willMessage.destinationName,"connectOptions.willMessage.destinationName"]))}if(typeof i.cleanSession=="undefined"&&(i.cleanSession=!0),i.hosts){if(!(i.hosts instanceof Array))throw new Error(c(a.INVALID_ARGUMENT,[i.hosts,"connectOptions.hosts"]));if(i.hosts.length<1)throw new Error(c(a.INVALID_ARGUMENT,[i.hosts,"connectOptions.hosts"]));for(var E=!1,g=0;g=3&&(I.qos=g),arguments.length>=4&&(I.retained=N),h.send(I)},this.publish=function(i,E,g,N){var I;if(arguments.length===0)throw new Error("Invalid argument.length");if(arguments.length==1){if(!(i instanceof T)&&typeof i!="string")throw new Error("Invalid argument:"+typeof i);if(I=i,typeof I.destinationName=="undefined")throw new Error(c(a.INVALID_ARGUMENT,[I.destinationName,"Message.destinationName"]));h.send(I)}else I=new T(E),I.destinationName=i,arguments.length>=3&&(I.qos=g),arguments.length>=4&&(I.retained=N),h.send(I)},this.disconnect=function(){h.disconnect()},this.getTraceLog=function(){return h.getTraceLog()},this.startTrace=function(){h.startTrace()},this.stopTrace=function(){h.stopTrace()},this.isConnected=function(){return h.connected}},T=function(e){var t;if(typeof e=="string"||e instanceof ArrayBuffer||ArrayBuffer.isView(e)&&!(e instanceof DataView))t=e;else throw c(a.INVALID_ARGUMENT,[e,"newPayload"]);var n,s=0,o=!1,r=!1;Object.defineProperties(this,{payloadString:{enumerable:!0,get:function(){return typeof t=="string"?t:D(t,0,t.length)}},payloadBytes:{enumerable:!0,get:function(){if(typeof t=="string"){var f=new ArrayBuffer(p(t)),v=new Uint8Array(f);return k(t,v,0),v}else return t}},destinationName:{enumerable:!0,get:function(){return n},set:function(f){if(typeof f=="string")n=f;else throw new Error(c(a.INVALID_ARGUMENT,[f,"newDestinationName"]))}},qos:{enumerable:!0,get:function(){return s},set:function(f){if(f===0||f===1||f===2)s=f;else throw new Error("Invalid argument:"+f)}},retained:{enumerable:!0,get:function(){return o},set:function(f){if(typeof f=="boolean")o=f;else throw new Error(c(a.INVALID_ARGUMENT,[f,"newRetained"]))}},topic:{enumerable:!0,get:function(){return n},set:function(f){n=f}},duplicate:{enumerable:!0,get:function(){return r},set:function(f){r=f}}})};return{Client:K,Message:T}}(typeof global!="undefined"?global:typeof self!="undefined"?self:typeof window!="undefined"?window:{});return R}); diff --git a/paho-mqtt.js b/paho-mqtt.js index 9ca3d37bc9938f56e2618cced0476e19b330f7dc..aefa4fab58f02d4c25d403cf306c121d700f65c0 100644 --- a/paho-mqtt.js +++ b/paho-mqtt.js @@ -106,7 +106,7 @@ function onMessageArrived(message) { /** * @private */ - var localStorage = global.localStorage || (function () { + var localStorage = (function () { var data = {}; return { @@ -115,6 +115,14 @@ function onMessageArrived(message) { removeItem: function (key) { delete data[key]; }, }; })(); + try { + if (global.localStorage) { + localStorage = global.localStorage; + } + } catch (err) { + // in browsers localStorage access can be disabled / blocked and even + // reading the localStorage property will result in an Access denied error + } /** * Unique message type identifiers, with associated ```

Make sure paho-mqtt is installed. Then add this to your project's package.json:

  "resolutions": {
    "paho-mqtt": "patch:paho-mqtt@npm:1.1.0#.yarn/patches/paho-mqtt-npm-1.1.0-c2bf8169e8"
  }

Finally, run yarn to apply the patch and it's done! Anytime anyone clones your project and runs yarn, it'll take care of patching this for you.

ashika01 commented 2 years ago

@stocaaro would you be able to help here?

hisham commented 1 year ago

+1. I updated to the latest aws-amplify and just ran into these bugs. So it seems somehow we're even more exposed to paho-mqtt's issues than before.

ffxsam commented 1 year ago

Hey @abdallahshaban557! I could be way off base, but this seems like a somewhat critical issue? (is "somewhat" critical a thing? 😆)

abdallahshaban557 commented 1 year ago

Hi @ffxsam - We've had a couple of investigations on this that have not been fully completed, our issue has been identifying a dependency that we can use that can provide us with coverage to both Web and React Native. There is still some ground work for us to do - and we'll respond back with updates when we have them.

ffxsam commented 1 year ago

@abdallahshaban557 Thanks, much appreciated! At least it's easy enough to use yarn's or pnpm's patch feature to work around this.

Ashish-Nanda commented 1 year ago

@ffxsam We now have a PR up to address the issue and are working to get this out in the next release which will go out later this week.

Longer term we will look into moving to something other than paho-mqtt for customers using Amplify with IoT. We already do not depend on it for connecting to AppSync.

Thanks for raising this issue and your patience while we get this resolved.

ffxsam commented 1 year ago

@Ashish-Nanda Great news, thanks for the update! 💪

stocaaro commented 1 year ago

Hello @ffxsam,

The change that includes the paho-mqtt patch in Amplify was released today. If you upgrade to aws-amplify@5.0.10 or later, your application should support PubSub for users who have cookies disabled.

ffxsam commented 1 year ago

Awesome, thank you!