mqtt 5.13.1 → 5.13.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,159 +0,0 @@
1
- // Other Socket Errors: EADDRINUSE, ECONNRESET, ENOTFOUND, ETIMEDOUT.
2
-
3
- import { type PacketHandler, ErrorWithReasonCode } from '../shared'
4
-
5
- export const ReasonCodes = {
6
- 0: '',
7
- 1: 'Unacceptable protocol version',
8
- 2: 'Identifier rejected',
9
- 3: 'Server unavailable',
10
- 4: 'Bad username or password',
11
- 5: 'Not authorized',
12
- 16: 'No matching subscribers',
13
- 17: 'No subscription existed',
14
- 128: 'Unspecified error',
15
- 129: 'Malformed Packet',
16
- 130: 'Protocol Error',
17
- 131: 'Implementation specific error',
18
- 132: 'Unsupported Protocol Version',
19
- 133: 'Client Identifier not valid',
20
- 134: 'Bad User Name or Password',
21
- 135: 'Not authorized',
22
- 136: 'Server unavailable',
23
- 137: 'Server busy',
24
- 138: 'Banned',
25
- 139: 'Server shutting down',
26
- 140: 'Bad authentication method',
27
- 141: 'Keep Alive timeout',
28
- 142: 'Session taken over',
29
- 143: 'Topic Filter invalid',
30
- 144: 'Topic Name invalid',
31
- 145: 'Packet identifier in use',
32
- 146: 'Packet Identifier not found',
33
- 147: 'Receive Maximum exceeded',
34
- 148: 'Topic Alias invalid',
35
- 149: 'Packet too large',
36
- 150: 'Message rate too high',
37
- 151: 'Quota exceeded',
38
- 152: 'Administrative action',
39
- 153: 'Payload format invalid',
40
- 154: 'Retain not supported',
41
- 155: 'QoS not supported',
42
- 156: 'Use another server',
43
- 157: 'Server moved',
44
- 158: 'Shared Subscriptions not supported',
45
- 159: 'Connection rate exceeded',
46
- 160: 'Maximum connect time',
47
- 161: 'Subscription Identifiers not supported',
48
- 162: 'Wildcard Subscriptions not supported',
49
- }
50
-
51
- const handleAck: PacketHandler = (client, packet) => {
52
- /* eslint no-fallthrough: "off" */
53
- const { messageId } = packet
54
- const type = packet.cmd
55
- let response = null
56
- const cb = client.outgoing[messageId] ? client.outgoing[messageId].cb : null
57
- let err = null
58
-
59
- // Checking `!cb` happens to work, but it's not technically "correct".
60
- //
61
- // Why? client code assumes client "no callback" is the same as client "we're not
62
- // waiting for responses" (puback, pubrec, pubcomp, suback, or unsuback).
63
- //
64
- // It would be better to check `if (!client.outgoing[messageId])` here, but
65
- // there's no reason to change it and risk (another) regression.
66
- //
67
- // The only reason client code works is becaues code in MqttClient.publish,
68
- // MqttClinet.subscribe, and MqttClient.unsubscribe ensures client we will
69
- // have a callback even if the user doesn't pass one in.)
70
- if (!cb) {
71
- client.log('_handleAck :: Server sent an ack in error. Ignoring.')
72
- // Server sent an ack in error, ignore it.
73
- return
74
- }
75
-
76
- // Process
77
- client.log('_handleAck :: packet type', type)
78
- switch (type) {
79
- case 'pubcomp':
80
- // same thing as puback for QoS 2
81
- case 'puback': {
82
- const pubackRC = packet.reasonCode
83
- // Callback - we're done
84
- if (pubackRC && pubackRC > 0 && pubackRC !== 16) {
85
- err = new ErrorWithReasonCode(
86
- `Publish error: ${ReasonCodes[pubackRC]}`,
87
- pubackRC,
88
- )
89
- client['_removeOutgoingAndStoreMessage'](messageId, () => {
90
- cb(err, packet)
91
- })
92
- } else {
93
- client['_removeOutgoingAndStoreMessage'](messageId, cb)
94
- }
95
-
96
- break
97
- }
98
- case 'pubrec': {
99
- response = {
100
- cmd: 'pubrel',
101
- qos: 2,
102
- messageId,
103
- }
104
- const pubrecRC = packet.reasonCode
105
-
106
- if (pubrecRC && pubrecRC > 0 && pubrecRC !== 16) {
107
- err = new ErrorWithReasonCode(
108
- `Publish error: ${ReasonCodes[pubrecRC]}`,
109
- pubrecRC,
110
- )
111
- client['_removeOutgoingAndStoreMessage'](messageId, () => {
112
- cb(err, packet)
113
- })
114
- } else {
115
- client['_sendPacket'](response)
116
- }
117
- break
118
- }
119
- case 'suback': {
120
- delete client.outgoing[messageId]
121
- client.messageIdProvider.deallocate(messageId)
122
- const granted = packet.granted as number[]
123
- for (let grantedI = 0; grantedI < granted.length; grantedI++) {
124
- const subackRC = granted[grantedI]
125
- if ((subackRC & 0x80) !== 0) {
126
- err = new Error(`Subscribe error: ${ReasonCodes[subackRC]}`)
127
- err.code = subackRC
128
-
129
- // suback with Failure status
130
- const topics = client.messageIdToTopic[messageId]
131
- if (topics) {
132
- topics.forEach((topic) => {
133
- delete client['_resubscribeTopics'][topic]
134
- })
135
- }
136
- }
137
- }
138
- delete client.messageIdToTopic[messageId]
139
- client['_invokeStoreProcessingQueue']()
140
- cb(err, packet)
141
- break
142
- }
143
- case 'unsuback': {
144
- delete client.outgoing[messageId]
145
- client.messageIdProvider.deallocate(messageId)
146
- client['_invokeStoreProcessingQueue']()
147
- cb(null, packet)
148
- break
149
- }
150
- default:
151
- client.emit('error', new Error('unrecognized packet type'))
152
- }
153
-
154
- if (client.disconnecting && Object.keys(client.outgoing).length === 0) {
155
- client.emit('outgoingEmpty')
156
- }
157
- }
158
-
159
- export default handleAck
@@ -1,44 +0,0 @@
1
- import { type IAuthPacket } from 'mqtt-packet'
2
- import { ErrorWithReasonCode, type PacketHandler } from '../shared'
3
- import { ReasonCodes } from './ack'
4
-
5
- const handleAuth: PacketHandler = (
6
- client,
7
- packet: IAuthPacket & { returnCode: number },
8
- ) => {
9
- const { options } = client
10
- const version = options.protocolVersion
11
- const rc = version === 5 ? packet.reasonCode : packet.returnCode
12
-
13
- if (version !== 5) {
14
- const err = new ErrorWithReasonCode(
15
- `Protocol error: Auth packets are only supported in MQTT 5. Your version:${version}`,
16
- rc,
17
- )
18
- client.emit('error', err)
19
- return
20
- }
21
-
22
- client.handleAuth(
23
- packet,
24
- (err: ErrorWithReasonCode, packet2: IAuthPacket) => {
25
- if (err) {
26
- client.emit('error', err)
27
- return
28
- }
29
-
30
- if (rc === 24) {
31
- client.reconnecting = false
32
- client['_sendPacket'](packet2)
33
- } else {
34
- const error = new ErrorWithReasonCode(
35
- `Connection refused: ${ReasonCodes[rc]}`,
36
- rc,
37
- )
38
- client.emit('error', error)
39
- }
40
- },
41
- )
42
- }
43
-
44
- export default handleAuth
@@ -1,58 +0,0 @@
1
- import { ReasonCodes } from './ack'
2
- import TopicAliasSend from '../topic-alias-send'
3
- import { ErrorWithReasonCode, type PacketHandler } from '../shared'
4
- import { type IConnackPacket } from 'mqtt-packet'
5
-
6
- const handleConnack: PacketHandler = (client, packet: IConnackPacket) => {
7
- client.log('_handleConnack')
8
- const { options } = client
9
- const version = options.protocolVersion
10
- const rc = version === 5 ? packet.reasonCode : packet.returnCode
11
-
12
- clearTimeout(client['connackTimer'])
13
- delete client['topicAliasSend']
14
-
15
- if (packet.properties) {
16
- if (packet.properties.topicAliasMaximum) {
17
- if (packet.properties.topicAliasMaximum > 0xffff) {
18
- client.emit(
19
- 'error',
20
- new Error('topicAliasMaximum from broker is out of range'),
21
- )
22
- return
23
- }
24
- if (packet.properties.topicAliasMaximum > 0) {
25
- client['topicAliasSend'] = new TopicAliasSend(
26
- packet.properties.topicAliasMaximum,
27
- )
28
- }
29
- }
30
- if (packet.properties.serverKeepAlive && options.keepalive) {
31
- options.keepalive = packet.properties.serverKeepAlive
32
- }
33
-
34
- if (packet.properties.maximumPacketSize) {
35
- if (!options.properties) {
36
- options.properties = {}
37
- }
38
- options.properties.maximumPacketSize =
39
- packet.properties.maximumPacketSize
40
- }
41
- }
42
-
43
- if (rc === 0) {
44
- client.reconnecting = false
45
- client['_onConnect'](packet)
46
- } else if (rc > 0) {
47
- const err = new ErrorWithReasonCode(
48
- `Connection refused: ${ReasonCodes[rc]}`,
49
- rc,
50
- )
51
- client.emit('error', err)
52
- if (client.options.reconnectOnConnackError) {
53
- client['_cleanUp'](true)
54
- }
55
- }
56
- }
57
-
58
- export default handleConnack
@@ -1,74 +0,0 @@
1
- import handlePublish from './publish'
2
- import handleAuth from './auth'
3
- import handleConnack from './connack'
4
- import handleAck from './ack'
5
- import handlePubrel from './pubrel'
6
- import { type PacketHandler } from '../shared'
7
-
8
- const handle: PacketHandler = (client, packet, done) => {
9
- const { options } = client
10
-
11
- if (
12
- options.protocolVersion === 5 &&
13
- options.properties &&
14
- options.properties.maximumPacketSize &&
15
- options.properties.maximumPacketSize < packet.length
16
- ) {
17
- client.emit('error', new Error(`exceeding packets size ${packet.cmd}`))
18
- client.end({
19
- reasonCode: 149,
20
- properties: { reasonString: 'Maximum packet size was exceeded' },
21
- })
22
- return client
23
- }
24
-
25
- client.log('_handlePacket :: emitting packetreceive')
26
- client.emit('packetreceive', packet)
27
-
28
- switch (packet.cmd) {
29
- case 'publish':
30
- // DO NOT SHIFT PING HERE, this would lead to https://github.com/mqttjs/MQTT.js/issues/1861
31
- handlePublish(client, packet, done)
32
- break
33
- case 'puback':
34
- case 'pubrec':
35
- case 'pubcomp':
36
- case 'suback':
37
- case 'unsuback':
38
- client.reschedulePing()
39
- handleAck(client, packet)
40
- done()
41
- break
42
- case 'pubrel':
43
- client.reschedulePing()
44
- handlePubrel(client, packet, done)
45
- break
46
- case 'connack':
47
- // no need to reschedule ping here as keepalive manager is created after successll connect
48
- // (when onConnect is called at the end of handleConnack)
49
- handleConnack(client, packet)
50
- done()
51
- break
52
- case 'auth':
53
- client.reschedulePing()
54
- handleAuth(client, packet)
55
- done()
56
- break
57
- case 'pingresp':
58
- client.log('_handlePacket :: received pingresp')
59
- client.reschedulePing(true)
60
- done()
61
- break
62
- case 'disconnect':
63
- client.emit('disconnect', packet)
64
- done()
65
- break
66
- default:
67
- // TODO: unknown packet received. Should we emit an error?
68
- client.log('_handlePacket :: unknown command')
69
- done()
70
- break
71
- }
72
- }
73
-
74
- export default handle
@@ -1,183 +0,0 @@
1
- import { type IPublishPacket } from 'mqtt-packet'
2
- import { type PacketHandler } from '../shared'
3
-
4
- const validReasonCodes = [0, 16, 128, 131, 135, 144, 145, 151, 153]
5
-
6
- /*
7
- those late 2 case should be rewrite to comply with coding style:
8
-
9
- case 1:
10
- case 0:
11
- // do not wait sending a puback
12
- // no callback passed
13
- if (1 === qos) {
14
- this._sendPacket({
15
- cmd: 'puback',
16
- messageId: messageId
17
- });
18
- }
19
- // emit the message event for both qos 1 and 0
20
- this.emit('message', topic, message, packet);
21
- this.handleMessage(packet, done);
22
- break;
23
- default:
24
- // do nothing but every switch mus have a default
25
- // log or throw an error about unknown qos
26
- break;
27
-
28
- for now i just suppressed the warnings
29
- */
30
- const handlePublish: PacketHandler = (client, packet: IPublishPacket, done) => {
31
- client.log('handlePublish: packet %o', packet)
32
- done = typeof done !== 'undefined' ? done : client.noop
33
- let topic = packet.topic.toString()
34
- const message = packet.payload
35
- const { qos } = packet
36
- const { messageId } = packet
37
- const { options } = client
38
- if (client.options.protocolVersion === 5) {
39
- let alias: number
40
- if (packet.properties) {
41
- alias = packet.properties.topicAlias
42
- }
43
- if (typeof alias !== 'undefined') {
44
- if (topic.length === 0) {
45
- if (alias > 0 && alias <= 0xffff) {
46
- const gotTopic =
47
- client['topicAliasRecv'].getTopicByAlias(alias)
48
- if (gotTopic) {
49
- topic = gotTopic
50
- client.log(
51
- 'handlePublish :: topic complemented by alias. topic: %s - alias: %d',
52
- topic,
53
- alias,
54
- )
55
- } else {
56
- client.log(
57
- 'handlePublish :: unregistered topic alias. alias: %d',
58
- alias,
59
- )
60
- client.emit(
61
- 'error',
62
- new Error('Received unregistered Topic Alias'),
63
- )
64
- return
65
- }
66
- } else {
67
- client.log(
68
- 'handlePublish :: topic alias out of range. alias: %d',
69
- alias,
70
- )
71
- client.emit(
72
- 'error',
73
- new Error('Received Topic Alias is out of range'),
74
- )
75
- return
76
- }
77
- } else if (client['topicAliasRecv'].put(topic, alias)) {
78
- client.log(
79
- 'handlePublish :: registered topic: %s - alias: %d',
80
- topic,
81
- alias,
82
- )
83
- } else {
84
- client.log(
85
- 'handlePublish :: topic alias out of range. alias: %d',
86
- alias,
87
- )
88
- client.emit(
89
- 'error',
90
- new Error('Received Topic Alias is out of range'),
91
- )
92
- return
93
- }
94
- }
95
- }
96
- client.log('handlePublish: qos %d', qos)
97
- switch (qos) {
98
- case 2: {
99
- options.customHandleAcks(
100
- topic,
101
- message as Buffer,
102
- packet,
103
- (error, code) => {
104
- if (typeof error === 'number') {
105
- code = error
106
- error = null
107
- }
108
- if (error) {
109
- return client.emit('error', error as Error)
110
- }
111
- if (validReasonCodes.indexOf(code) === -1) {
112
- return client.emit(
113
- 'error',
114
- new Error('Wrong reason code for pubrec'),
115
- )
116
- }
117
- if (code) {
118
- client['_sendPacket'](
119
- { cmd: 'pubrec', messageId, reasonCode: code },
120
- done,
121
- )
122
- } else {
123
- client.incomingStore.put(packet, () => {
124
- client['_sendPacket'](
125
- { cmd: 'pubrec', messageId },
126
- done,
127
- )
128
- })
129
- }
130
- },
131
- )
132
- break
133
- }
134
- case 1: {
135
- // emit the message event
136
- options.customHandleAcks(
137
- topic,
138
- message as Buffer,
139
- packet,
140
- (error, code) => {
141
- if (typeof error === 'number') {
142
- code = error
143
- error = null
144
- }
145
- if (error) {
146
- return client.emit('error', error as Error)
147
- }
148
- if (validReasonCodes.indexOf(code) === -1) {
149
- return client.emit(
150
- 'error',
151
- new Error('Wrong reason code for puback'),
152
- )
153
- }
154
- if (!code) {
155
- client.emit('message', topic, message as Buffer, packet)
156
- }
157
- client.handleMessage(packet, (err) => {
158
- if (err) {
159
- return done && done(err)
160
- }
161
- client['_sendPacket'](
162
- { cmd: 'puback', messageId, reasonCode: code },
163
- done,
164
- )
165
- })
166
- },
167
- )
168
- break
169
- }
170
- case 0:
171
- // emit the message event
172
- client.emit('message', topic, message as Buffer, packet)
173
- client.handleMessage(packet, done)
174
- break
175
- default:
176
- // do nothing
177
- client.log('handlePublish: unknown QoS. Doing nothing.')
178
- // log or throw an error about unknown qos
179
- break
180
- }
181
- }
182
-
183
- export default handlePublish
@@ -1,31 +0,0 @@
1
- import {
2
- type IPubcompPacket,
3
- type IPublishPacket,
4
- type IPubrelPacket,
5
- } from 'mqtt-packet'
6
- import { type PacketHandler } from '../shared'
7
-
8
- const handlePubrel: PacketHandler = (client, packet: IPubrelPacket, done) => {
9
- client.log('handling pubrel packet')
10
- const callback = typeof done !== 'undefined' ? done : client.noop
11
- const { messageId } = packet
12
-
13
- const comp: IPubcompPacket = { cmd: 'pubcomp', messageId }
14
-
15
- client.incomingStore.get(packet, (err, pub: IPublishPacket) => {
16
- if (!err) {
17
- client.emit('message', pub.topic, pub.payload as Buffer, pub)
18
- client.handleMessage(pub, (err2) => {
19
- if (err2) {
20
- return callback(err2)
21
- }
22
- client.incomingStore.del(pub, client.noop)
23
- client['_sendPacket'](comp, callback)
24
- })
25
- } else {
26
- client['_sendPacket'](comp, callback)
27
- }
28
- })
29
- }
30
-
31
- export default handlePubrel
@@ -1,46 +0,0 @@
1
- const isStandardBrowserEnv = () => {
2
- // window is only defined when it is a browser
3
- if (typeof window !== 'undefined') {
4
- // Is the process an electron application
5
- // check if we are in electron `renderer`
6
- const electronRenderCheck =
7
- typeof navigator !== 'undefined' &&
8
- navigator.userAgent?.toLowerCase().indexOf(' electron/') > -1
9
- if (electronRenderCheck && process?.versions) {
10
- const electronMainCheck = Object.prototype.hasOwnProperty.call(
11
- process.versions,
12
- 'electron',
13
- )
14
- // Both electron checks are only true if the following webPreferences are set in the main electron BrowserWindow()
15
- // webPreferences: {
16
- // sandbox: false,
17
- // nodeIntegration: true
18
- // contextIsolation: false
19
- // }
20
- return !electronMainCheck
21
- }
22
- return typeof window.document !== 'undefined'
23
- }
24
- // return false if nothing is detected
25
- return false
26
- }
27
-
28
- const isWebWorkerEnv = () =>
29
- Boolean(
30
- // eslint-disable-next-line no-restricted-globals
31
- typeof self === 'object' &&
32
- // eslint-disable-next-line no-restricted-globals
33
- self?.constructor?.name?.includes('WorkerGlobalScope'),
34
- )
35
-
36
- const isReactNativeEnv = () =>
37
- typeof navigator !== 'undefined' && navigator.product === 'ReactNative'
38
-
39
- const isBrowser =
40
- isStandardBrowserEnv() || isWebWorkerEnv() || isReactNativeEnv()
41
-
42
- export const isWebWorker = isWebWorkerEnv()
43
-
44
- export const isReactNativeBrowser = isReactNativeEnv()
45
-
46
- export default isBrowser
package/src/lib/shared.ts DELETED
@@ -1,100 +0,0 @@
1
- import type { Packet, ISubackPacket } from 'mqtt-packet'
2
- import type { Duplex } from 'stream'
3
- import type MqttClient from './client'
4
- import type { IClientOptions } from './client'
5
-
6
- export type DoneCallback = (error?: Error) => void
7
-
8
- export type GenericCallback<T> = (error?: Error, result?: T) => void
9
-
10
- export type VoidCallback = () => void
11
-
12
- export type IStream = Duplex & {
13
- /** only set on browsers, it's a [WebSocket](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket) */
14
- socket?: any
15
- }
16
-
17
- export type StreamBuilder = (
18
- client: MqttClient,
19
- opts?: IClientOptions,
20
- ) => IStream
21
-
22
- export type Callback = () => void
23
-
24
- export type PacketHandler = (
25
- client: MqttClient,
26
- packet: Packet,
27
- done?: DoneCallback,
28
- ) => void
29
-
30
- export type TimerVariant = 'auto' | 'worker' | 'native'
31
-
32
- export class ErrorWithReasonCode extends Error {
33
- public code: number
34
-
35
- public constructor(message: string, code: number) {
36
- super(message)
37
- this.code = code
38
-
39
- // We need to set the prototype explicitly
40
- Object.setPrototypeOf(this, ErrorWithReasonCode.prototype)
41
- Object.getPrototypeOf(this).name = 'ErrorWithReasonCode'
42
- }
43
- }
44
-
45
- export class ErrorWithSubackPacket extends Error {
46
- public packet: ISubackPacket
47
-
48
- public constructor(message: string, packet: ISubackPacket) {
49
- super(message)
50
- this.packet = packet
51
-
52
- // We need to set the prototype explicitly
53
- Object.setPrototypeOf(this, ErrorWithSubackPacket.prototype)
54
- Object.getPrototypeOf(this).name = 'ErrorWithSubackPacket'
55
- }
56
- }
57
-
58
- // eslint-disable-next-line @typescript-eslint/ban-types
59
- export type Constructor<T = {}> = new (...args: any[]) => T
60
-
61
- export function applyMixin(
62
- target: Constructor,
63
- mixin: Constructor,
64
- includeConstructor = false,
65
- ): void {
66
- // Figure out the inheritance chain of the mixin
67
- const inheritanceChain: Constructor[] = [mixin]
68
- // eslint-disable-next-line no-constant-condition
69
- while (true) {
70
- const current = inheritanceChain[0]
71
- const base = Object.getPrototypeOf(current)
72
- if (base?.prototype) {
73
- inheritanceChain.unshift(base)
74
- } else {
75
- break
76
- }
77
- }
78
- for (const ctor of inheritanceChain) {
79
- for (const prop of Object.getOwnPropertyNames(ctor.prototype)) {
80
- // Do not override the constructor
81
- if (includeConstructor || prop !== 'constructor') {
82
- Object.defineProperty(
83
- target.prototype,
84
- prop,
85
- Object.getOwnPropertyDescriptor(ctor.prototype, prop) ??
86
- Object.create(null),
87
- )
88
- }
89
- }
90
- }
91
- }
92
- export const nextTick =
93
- typeof process?.nextTick === 'function'
94
- ? process.nextTick
95
- : (callback: () => void) => {
96
- setTimeout(callback, 0)
97
- }
98
-
99
- // eslint-disable-next-line @typescript-eslint/no-var-requires
100
- export const MQTTJS_VERSION = require('../../package.json').version