-
Notifications
You must be signed in to change notification settings - Fork 55
/
message.js
321 lines (293 loc) · 9.43 KB
/
message.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
import BufferUtils from 'platform-bufferutils';
import Utils from '../util/utils';
import Logger from '../util/logger';
import Crypto from 'platform-crypto';
import ErrorInfo from './errorinfo';
var Message = (function() {
function Message() {
this.name = undefined;
this.id = undefined;
this.timestamp = undefined;
this.clientId = undefined;
this.connectionId = undefined;
this.connectionKey = undefined;
this.data = undefined;
this.encoding = undefined;
this.extras = undefined;
this.size = undefined;
}
/**
* Overload toJSON() to intercept JSON.stringify()
* @return {*}
*/
Message.prototype.toJSON = function() {
var result = {
name: this.name,
id: this.id,
clientId: this.clientId,
connectionId: this.connectionId,
connectionKey: this.connectionKey,
encoding: this.encoding,
extras: this.extras
};
/* encode data to base64 if present and we're returning real JSON;
* although msgpack calls toJSON(), we know it is a stringify()
* call if it has a non-empty arguments list */
var data = this.data;
if(data && BufferUtils.isBuffer(data)) {
if(arguments.length > 0) {
/* stringify call */
var encoding = this.encoding;
result.encoding = encoding ? (encoding + '/base64') : 'base64';
data = BufferUtils.base64Encode(data);
} else {
/* Called by msgpack. toBuffer returns a datatype understandable by
* that platform's msgpack implementation (Buffer in node, Uint8Array
* in browsers) */
data = BufferUtils.toBuffer(data);
}
}
result.data = data;
return result;
};
Message.prototype.toString = function() {
var result = '[Message';
if(this.name)
result += '; name=' + this.name;
if(this.id)
result += '; id=' + this.id;
if(this.timestamp)
result += '; timestamp=' + this.timestamp;
if(this.clientId)
result += '; clientId=' + this.clientId;
if(this.connectionId)
result += '; connectionId=' + this.connectionId;
if(this.encoding)
result += '; encoding=' + this.encoding;
if(this.extras)
result += '; extras =' + JSON.stringify(this.extras);
if(this.data) {
if (typeof(this.data) == 'string')
result += '; data=' + this.data;
else if (BufferUtils.isBuffer(this.data))
result += '; data (buffer)=' + BufferUtils.base64Encode(this.data);
else
result += '; data (json)=' + JSON.stringify(this.data);
}
if(this.extras)
result += '; extras=' + JSON.stringify(this.extras);
result += ']';
return result;
};
Message.encrypt = function(msg, options, callback) {
var data = msg.data,
encoding = msg.encoding,
cipher = options.channelCipher;
encoding = encoding ? (encoding + '/') : '';
if(!BufferUtils.isBuffer(data)) {
data = BufferUtils.utf8Encode(String(data));
encoding = encoding + 'utf-8/';
}
cipher.encrypt(data, function(err, data) {
if (err) {
callback(err);
return;
}
msg.data = data;
msg.encoding = encoding + 'cipher+' + cipher.algorithm;
callback(null, msg);
});
};
Message.encode = function(msg, options, callback) {
var data = msg.data, encoding,
nativeDataType = typeof(data) == 'string' || BufferUtils.isBuffer(data) || data === null || data === undefined;
if (!nativeDataType) {
if (Utils.isObject(data) || Utils.isArray(data)) {
msg.data = JSON.stringify(data);
msg.encoding = (encoding = msg.encoding) ? (encoding + '/json') : 'json';
} else {
throw new ErrorInfo('Data type is unsupported', 40013, 400);
}
}
if(options != null && options.cipher) {
Message.encrypt(msg, options, callback);
} else {
callback(null, msg);
}
};
Message.encodeArray = function(messages, options, callback) {
var processed = 0;
for (var i = 0; i < messages.length; i++) {
Message.encode(messages[i], options, function(err, msg) {
if (err) {
callback(err);
return;
}
processed++;
if (processed == messages.length) {
callback(null, messages);
}
});
}
};
Message.serialize = Utils.encodeBody;
Message.decode = function(message, context) {
/* The second argument could be either EncodingDecodingContext that contains ChannelOptions or ChannelOptions */
if(!context || !context.channelOptions) {
var channelOptions = context;
context = {
channelOptions: channelOptions,
plugins: { },
baseEncodedPreviousPayload: undefined
};
}
var lastPayload = message.data;
var encoding = message.encoding;
if(encoding) {
var xforms = encoding.split('/'),
lastProcessedEncodingIndex, encodingsToProcess = xforms.length,
data = message.data;
try {
while((lastProcessedEncodingIndex = encodingsToProcess) > 0) {
var match = xforms[--encodingsToProcess].match(/([\-\w]+)(\+([\w\-]+))?/);
if(!match) break;
var xform = match[1];
switch(xform) {
case 'base64':
data = BufferUtils.base64Decode(String(data));
if(lastProcessedEncodingIndex == xforms.length) {
lastPayload = data;
}
continue;
case 'utf-8':
data = BufferUtils.utf8Decode(data);
continue;
case 'json':
data = JSON.parse(data);
continue;
case 'cipher':
if(context.channelOptions != null && context.channelOptions.cipher) {
var xformAlgorithm = match[3], cipher = context.channelOptions.channelCipher;
/* don't attempt to decrypt unless the cipher params are compatible */
if(xformAlgorithm != cipher.algorithm) {
throw new Error('Unable to decrypt message with given cipher; incompatible cipher params');
}
data = cipher.decrypt(data);
continue;
} else {
throw new Error('Unable to decrypt message; not an encrypted channel');
}
case 'vcdiff':
if(!context.plugins || !context.plugins.vcdiff) {
throw new ErrorInfo('Missing Vcdiff decoder (https://github.com/ably-forks/vcdiff-decoder)', 40019, 400);
}
if(typeof Uint8Array === 'undefined') {
throw new ErrorInfo('Delta decoding not supported on this browser (need ArrayBuffer & Uint8Array)', 40020, 400);
}
try {
var deltaBase = context.baseEncodedPreviousPayload;
if(typeof deltaBase === 'string') {
deltaBase = BufferUtils.utf8Encode(deltaBase);
}
/* vcdiff expects Uint8Arrays, can't copy with ArrayBuffers. (also, if we
* don't have a TextDecoder, deltaBase might be a WordArray here, so need
* to process it into a buffer anyway) */
deltaBase = BufferUtils.toBuffer(deltaBase);
data = BufferUtils.toBuffer(data);
data = BufferUtils.typedArrayToBuffer(context.plugins.vcdiff.decode(data, deltaBase));
lastPayload = data;
} catch(e) {
throw new ErrorInfo('Vcdiff delta decode failed with ' + e, 40018, 400);
}
continue;
default:
throw new Error("Unknown encoding");
}
break;
}
} catch(e) {
throw new ErrorInfo('Error processing the ' + xform + ' encoding, decoder returned ‘' + e.message + '’', e.code || 40013, 400);
} finally {
message.encoding = (lastProcessedEncodingIndex <= 0) ? null : xforms.slice(0, lastProcessedEncodingIndex).join('/');
message.data = data;
}
}
context.baseEncodedPreviousPayload = lastPayload;
};
Message.fromResponseBody = function(body, options, format) {
if(format) {
body = Utils.decodeBody(body, format);
}
for(var i = 0; i < body.length; i++) {
var msg = body[i] = Message.fromValues(body[i]);
try {
Message.decode(msg, options);
} catch (e) {
Logger.logAction(Logger.LOG_ERROR, 'Message.fromResponseBody()', e.toString());
}
}
return body;
};
Message.fromValues = function(values) {
return Utils.mixin(new Message(), values);
};
Message.fromValuesArray = function(values) {
var count = values.length, result = new Array(count);
for(var i = 0; i < count; i++) result[i] = Message.fromValues(values[i]);
return result;
};
function normalizeCipherOptions(options) {
if(options && options.cipher && !options.cipher.channelCipher) {
if(!Crypto) throw new Error('Encryption not enabled; use ably.encryption.js instead');
var cipher = Crypto.getCipher(options.cipher);
options.cipher = cipher.cipherParams;
options.channelCipher = cipher.cipher;
}
}
Message.fromEncoded = function(encoded, options) {
var msg = Message.fromValues(encoded);
normalizeCipherOptions(options);
/* if decoding fails at any point, catch and return the message decoded to
* the fullest extent possible */
try {
Message.decode(msg, options);
} catch(e) {
Logger.logAction(Logger.LOG_ERROR, 'Message.fromEncoded()', e.toString());
}
return msg;
};
Message.fromEncodedArray = function(encodedArray, options) {
normalizeCipherOptions(options);
return Utils.arrMap(encodedArray, function(encoded) {
return Message.fromEncoded(encoded, options);
});
};
function getMessageSize(msg) {
var size = 0;
if(msg.name) {
size += msg.name.length;
}
if(msg.clientId) {
size += msg.clientId.length;
}
if(msg.extras) {
size += JSON.stringify(msg.extras).length;
}
if(msg.data) {
size += Utils.dataSizeBytes(msg.data);
}
return size;
};
/* This should be called on encode()d (and encrypt()d) Messages (as it
* assumes the data is a string or buffer) */
Message.getMessagesSize = function(messages) {
var msg, total = 0;
for(var i=0; i<messages.length; i++) {
msg = messages[i];
total += (msg.size || (msg.size = getMessageSize(msg)))
}
return total;
};
return Message;
})();
export default Message;