@iobroker/socket-classes 0.1.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2020-2022 bluefox <dogafox@gmail.com>
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,96 @@
1
+ # @iobroker/socket-classes
2
+
3
+ This library is used for following adapters:
4
+ - [iobroker.admin](https://github.com/ioBroker/ioBroker.admin)
5
+ - [iobroker.cloud](https://github.com/ioBroker/ioBroker.cloud)
6
+ - [iobroker.socketio](https://github.com/ioBroker/ioBroker.socketio)
7
+ - [iobroker.ws](https://github.com/ioBroker/ioBroker.ws)
8
+ - [iobroker.rest-api](https://github.com/ioBroker/ioBroker.rest-api)
9
+ - [iobroker.iot](https://github.com/ioBroker/ioBroker.iot)
10
+
11
+ ## Usage as admin
12
+ ```
13
+ const TTL_SEC = 3600;
14
+
15
+ const SocketAdmin = require('./lib/socketAdmin');
16
+ const ws = require('@iobroker/ws-server');
17
+ const session = require('express-session');
18
+ const utils = require('@iobroker/adapter-core'); // Get common adapter utils
19
+ const AdapterStore = require(utils.controllerDir + '/lib/session.js')(session, TTL_SEC);
20
+
21
+ const store = new AdapterStore({adapter});
22
+
23
+ const io = new SocketAdmin(adapter.config, adapter, objects);
24
+ io.start(
25
+ server,
26
+ ws,
27
+ {
28
+ userKey: 'connect.sid',
29
+ store,
30
+ secret: adapter.config.secret
31
+ }
32
+ );
33
+
34
+ // subscribe on all object changes
35
+ io.subscribe('objectChange', '*');
36
+
37
+
38
+ // later
39
+ io.close();
40
+ ```
41
+
42
+ ## Usage as socket (ws or socketio)
43
+ ```
44
+ const TTL_SEC = 3600;
45
+
46
+ const ws = require('@iobroker/ws-server');
47
+ const SocketWS = require('./lib/socketWS.js');
48
+ const session = require('express-session');
49
+ const utils = require('@iobroker/adapter-core'); // Get common adapter utils
50
+ const AdapterStore = require(utils.controllerDir + '/lib/session.js')(session, TTL_SEC);
51
+
52
+ const store = new AdapterStore({adapter});
53
+
54
+ const settings = adapter.config;
55
+ settings.crossDomain = true;
56
+ settings.ttl = settings.ttl || TTL_SEC;
57
+
58
+ const io = new SocketWS(settings, adapter);
59
+ io.start(server.server, ws, {userKey: 'connect.sid', checkUser, store, secret: adapter.config.secret});
60
+
61
+
62
+ // later
63
+ io.close();
64
+ ```
65
+
66
+ <!--
67
+ Placeholder for the next version (at the beginning of the line):
68
+ ### **WORK IN PROGRESS**
69
+ -->
70
+
71
+ ## Changelog
72
+ ### 0.1.2 (2022-04-24)
73
+ * (bluefox) initial commit
74
+
75
+ ## License
76
+ The MIT License (MIT)
77
+
78
+ Copyright (c) 2020-2022 Bluefox <dogafox@gmail.com>
79
+
80
+ Permission is hereby granted, free of charge, to any person obtaining a copy
81
+ of this software and associated documentation files (the "Software"), to deal
82
+ in the Software without restriction, including without limitation the rights
83
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
84
+ copies of the Software, and to permit persons to whom the Software is
85
+ furnished to do so, subject to the following conditions:
86
+
87
+ The above copyright notice and this permission notice shall be included in
88
+ all copies or substantial portions of the Software.
89
+
90
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
91
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
92
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
93
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
94
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
95
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
96
+ THE SOFTWARE.
package/index.js ADDED
@@ -0,0 +1,11 @@
1
+ const SocketAdmin = require('./lib/socketAdmin');
2
+ const SocketCommon = require('./lib/socketCommon');
3
+ const SocketCommands = require('./lib/socketCommands');
4
+ const SocketCommandsAdmin = require('./lib/socketCommandsAdmin');
5
+
6
+ module.exports = {
7
+ SocketAdmin,
8
+ SocketCommon,
9
+ SocketCommands,
10
+ SocketCommandsAdmin
11
+ };
@@ -0,0 +1,100 @@
1
+ // Originally taken from here: https://github.com/jfromaniello/passport.socketio/blob/master/lib/index.js
2
+ // Copyright Licensed under the MIT-License. 2012-2013 José F. Romaniello.
3
+
4
+ function parseCookie(auth, cookieHeader) {
5
+ const cookieParser = auth.cookieParser(auth.secret);
6
+ const req = {
7
+ headers: {
8
+ cookie: cookieHeader
9
+ }
10
+ };
11
+
12
+ let result;
13
+
14
+ cookieParser(req, {}, err => {
15
+ if (err) {
16
+ throw err;
17
+ }
18
+ result = req.signedCookies || req.cookies;
19
+ });
20
+
21
+ return result;
22
+ }
23
+
24
+ function getQuery(url) {
25
+ const query = url.split('?')[1] || '';
26
+ const parts = query.split('&');
27
+ const result = {};
28
+ for (let p = 0; p < parts.length; p++) {
29
+ const parts1 = parts[p].split('=');
30
+ result[parts1[0]] = parts1[1];
31
+ }
32
+ return result;
33
+ }
34
+
35
+ function authorize(options) {
36
+ const defaults = {
37
+ key: 'connect.sid',
38
+ secret: null,
39
+ store: null,
40
+ userProperty: 'user'
41
+ };
42
+
43
+ const auth = Object.assign({}, defaults, options);
44
+
45
+ if (!auth.passport) {
46
+ throw new Error('passport is required to use require(\'passport\'), please install passport');
47
+ }
48
+
49
+ if (!auth.cookieParser) {
50
+ throw new Error('cookieParser is required use require(\'cookie-parser\'), connect.cookieParser or express.cookieParser');
51
+ }
52
+
53
+ return function (data, accept) {
54
+ data.query = getQuery(data.url);
55
+
56
+ if (options.checkUser && data.query.user && data.query.pass) {
57
+ return options.checkUser(data.query.user, data.query.pass, (error, result) => {
58
+ if (error) {
59
+ return auth.fail(data, 'Cannot check user', false, accept);
60
+ } else if (!result) {
61
+ return auth.fail(data, 'User not found', false, accept);
62
+ } else {
63
+ data[auth.userProperty] = result;
64
+ data[auth.userProperty].logged_in = true;
65
+ auth.success(data, accept);
66
+ }
67
+ });
68
+ }
69
+
70
+ data.cookie = parseCookie(auth, data.headers.cookie || '');
71
+ data.sessionID = data.cookie[auth.key] || '';
72
+ data[auth.userProperty] = {
73
+ logged_in: false
74
+ };
75
+
76
+ auth.store.get(data.sessionID, (err, session) => {
77
+ if (err) {
78
+ return auth.fail(data, 'Error in session store:\n' + err.message, true, accept);
79
+ } else
80
+ if (!session) {
81
+ return auth.fail(data, 'No session found', false, accept);
82
+ } else
83
+ if (!session[auth.passport._key]) {
84
+ return auth.fail(data, 'Passport was not initialized', true, accept);
85
+ }
86
+
87
+ const userKey = session[auth.passport._key].user;
88
+
89
+ if (typeof userKey === 'undefined') {
90
+ return auth.fail(data, 'User not authorized through passport. (User Property not found)', false, accept);
91
+ }
92
+
93
+ data[auth.userProperty] = userKey;
94
+ data[auth.userProperty].logged_in = true;
95
+ auth.success(data, accept);
96
+ });
97
+ };
98
+ }
99
+
100
+ exports.authorize = authorize;
@@ -0,0 +1,178 @@
1
+ /**
2
+ * Class Socket
3
+ *
4
+ * Copyright 2014-2022 bluefox <dogafox@gmail.com>,
5
+ * MIT License
6
+ *
7
+ */
8
+ const SocketCommon = require('./socketCommon');
9
+ const SocketCommandsAdmin = require('./socketCommandsAdmin');
10
+ let passport; // require('passport') - only if auth is activated
11
+ let cookieParser; // require('cookie-parser') - only if auth is activated
12
+ let passportSocketIo; // require('./passportSocket') - only if auth is activated
13
+
14
+ class SocketAdmin extends SocketCommon {
15
+ constructor(settings, adapter, objects) {
16
+ super(settings, adapter);
17
+
18
+ // user another set of commands for admin
19
+ this.commands = new SocketCommandsAdmin(adapter, socket => this.__updateSession(socket), objects);
20
+ }
21
+
22
+ __getIsNoDisconnect() {
23
+ // ws does not require disconnect
24
+ return true;
25
+ }
26
+
27
+ _onAuthorizeSuccess = (data, accept) => {
28
+ this.adapter.log.debug(`successful connection to socket.io from ${data.connection.remoteAddress}`);
29
+ accept();
30
+ }
31
+
32
+ _onAuthorizeFail = (data, message, error, accept) => {
33
+ setTimeout(() => data.socket.emit(SocketCommon.COMMAND_RE_AUTHENTICATE), 100);
34
+
35
+ error && this.adapter.log.info(`failed connection to socket.io from ${data.connection.remoteAddress}: ${message}`);
36
+
37
+ if (error) {
38
+ accept(new Error(message));
39
+ } else {
40
+ accept(new Error(`failed connection to socket.io: ${message}`));//null, false);
41
+ }
42
+ // this error will be sent to the user as a special error-package
43
+ // see: http://socket.io/docs/client-api/#socket > error-object
44
+ }
45
+
46
+ __initAuthentication(authOptions) {
47
+ passportSocketIo = passportSocketIo || require('./passportSocket');
48
+ passport = passport || require('passport');
49
+ cookieParser = cookieParser || require('cookie-parser');
50
+
51
+ this.store = authOptions.store;
52
+
53
+ this.server.use(passportSocketIo.authorize({
54
+ passport,
55
+ cookieParser,
56
+ key: authOptions.userKey, // the name of the cookie where express/connect stores its session_id
57
+ secret: authOptions.secret, // the session_secret to parse the cookie
58
+ store: authOptions.store, // we NEED to use a sessionstore. no memorystore please
59
+ success: this._onAuthorizeSuccess, // *optional* callback on success - read more below
60
+ fail: this._onAuthorizeFail // *optional* callback on fail/error - read more below
61
+ }));
62
+ }
63
+
64
+ // Extract username from socket
65
+ __getUserFromSocket(socket, callback) {
66
+ if (socket.conn.request.sessionID) {
67
+ socket._secure = true;
68
+ socket._sessionID = socket.conn.request.sessionID;
69
+ // Get user for session
70
+ return this.adapter.getSession(socket.conn.request.sessionID, obj => {
71
+ if (!obj || !obj.passport) {
72
+ socket._acl.user = '';
73
+ socket.emit(SocketCommon.COMMAND_RE_AUTHENTICATE);
74
+ callback('Cannot detect user');
75
+ } else {
76
+ callback(null, obj.passport.user ? `system.user.${obj.passport.user}` : '');
77
+ }
78
+ });
79
+ }
80
+ callback('Cannot detect user');
81
+ }
82
+
83
+ __getClientAddress(socket) {
84
+ let address;
85
+ if (socket.connection) {
86
+ address = socket.connection && socket.connection.remoteAddress;
87
+ } else {
88
+ address = socket.ws._socket.remoteAddress;
89
+ }
90
+
91
+ if (!address && socket.handshake) {
92
+ address = socket.handshake.address;
93
+ }
94
+ if (!address && socket.conn.request && socket.conn.request.connection) {
95
+ address = socket.conn.request.connection.remoteAddress;
96
+ }
97
+ return address;
98
+ }
99
+
100
+ // update session ID, but not ofter than 60 seconds
101
+ __updateSession(socket) {
102
+ if (socket._sessionID) {
103
+ const time = Date.now();
104
+ if (socket._lastActivity && time - socket._lastActivity > this.settings.ttl * 1000) {
105
+ this.adapter.log.warn('REAUTHENTICATE!');
106
+ socket.emit(SocketCommon.COMMAND_RE_AUTHENTICATE);
107
+ return false;
108
+ }
109
+ socket._lastActivity = time;
110
+ socket._sessionTimer = socket._sessionTimer || setTimeout(() => {
111
+ socket._sessionTimer = null;
112
+ this.adapter.getSession(socket._sessionID, obj => {
113
+ if (obj) {
114
+ this.adapter.setSession(socket._sessionID, this.settings.ttl, obj);
115
+ } else {
116
+ this.adapter.log.warn('REAUTHENTICATE!');
117
+ socket.emit(SocketCommon.COMMAND_RE_AUTHENTICATE);
118
+ }
119
+ });
120
+ }, 60000);
121
+ }
122
+
123
+ return true;
124
+ }
125
+
126
+ __getSessionID(socket) {
127
+ return this.settings.auth && socket.conn.request.sessionID;
128
+ }
129
+
130
+ start(server, socketClass, authOptions, socketOptions) {
131
+ super.start(server, socketClass, authOptions, socketOptions);
132
+
133
+ this.commands.start(thresholdEnabled => this.onThresholdChanged(thresholdEnabled));
134
+ }
135
+
136
+ onThresholdChanged(enabled) {
137
+ this.server && this.server.sockets && this.server.sockets.emit('eventsThreshold', enabled);
138
+ }
139
+
140
+ stateChange(id, state) {
141
+ this.commands.stateChange(id, state);
142
+
143
+ this.server.sockets.connected.forEach(socket =>
144
+ this.__updateSession(socket));
145
+
146
+ this.server.sockets.emit('stateChange', id, state);
147
+ }
148
+
149
+ repoUpdated() {
150
+ if (this.server && this.server.sockets) {
151
+ this.server.sockets.emit('repoUpdated');
152
+ }
153
+ }
154
+
155
+ objectChange(id, obj) {
156
+ const clients = this.server.sockets.connected;
157
+
158
+ for (const i in clients) {
159
+ if (clients.hasOwnProperty(i)) {
160
+ this.__updateSession(clients[i]);
161
+ }
162
+ }
163
+
164
+ this.server.sockets.emit('objectChange', id, obj);
165
+ }
166
+
167
+ subscribe(type, pattern) {
168
+ this.commands.subscribe(null, type, pattern);
169
+ }
170
+
171
+ sendCommand(obj) {
172
+ if (this.commands.sendCommand(obj) && this.server) {
173
+ this.server.sockets.emit(obj.command, obj.message.id, obj.message.data);
174
+ }
175
+ }
176
+ }
177
+
178
+ module.exports = SocketAdmin;