mosquito-transport-js 0.3.1 → 0.3.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mosquito-transport-js",
3
- "version": "0.3.1",
3
+ "version": "0.3.2",
4
4
  "description": "Javascript web sdk for mosquito-transport (https://github.com/deflexable/mosquito-transport)",
5
5
  "main": "src/index.js",
6
6
  "type": "module",
@@ -103,7 +103,7 @@ export const decryptString = (txt, password, iv) => {
103
103
  return decrypt(txt, `${password || ''}${iv || ''}`).toString(Utf8Encoder);
104
104
  };
105
105
 
106
- export const serializeE2E = (data, auth_token, serverPublicKey) => {
106
+ export const serializeE2E = async (data, auth_token, serverPublicKey) => {
107
107
  const inputData = new Uint8Array(Buffer.from(JSON.stringify([data, auth_token]), 'utf8'));
108
108
 
109
109
  if (inputData.byteLength > 10240) {
@@ -136,7 +136,7 @@ export const serializeE2E = (data, auth_token, serverPublicKey) => {
136
136
  ];
137
137
  };
138
138
 
139
- export const deserializeE2E = (data = '', serverPublicKey, clientPrivateKey) => {
139
+ export const deserializeE2E = async (data = '', serverPublicKey, clientPrivateKey) => {
140
140
  const [binaryNonce, binaryData] = data.split('.').map(v => new Uint8Array(Buffer.from(v, 'base64')));
141
141
  let baseArray;
142
142
 
@@ -116,9 +116,9 @@ export const getReachableServer = (projectUrl) => new Promise(resolve => {
116
116
  }, true);
117
117
  });
118
118
 
119
- export const buildFetchInterface = ({ body, accessKey, authToken, method, uglify, serverE2E_PublicKey }) => {
119
+ export const buildFetchInterface = async ({ body, accessKey, authToken, method, uglify, serverE2E_PublicKey }) => {
120
120
  if (!uglify) body = JSON.stringify({ ...body });
121
- const [plate, keyPair] = uglify ? serializeE2E(body, authToken, serverE2E_PublicKey) : [undefined, []];
121
+ const [plate, keyPair] = uglify ? await serializeE2E(body, authToken, serverE2E_PublicKey) : [undefined, []];
122
122
 
123
123
  return [{
124
124
  body: uglify ? plate : body,
package/src/index.d.ts CHANGED
@@ -115,7 +115,7 @@ interface MTSocket {
115
115
  emitWithAck: (...args: any) => Promise<any>;
116
116
  });
117
117
  emit: (...args: any) => void;
118
- emitWithAck: () => Promise<any>;
118
+ emitWithAck: (...args: any) => Promise<any>;
119
119
  on: (route: string, callback?: () => any) => void;
120
120
  once: (route: string, callback?: () => any) => void;
121
121
  destroy: () => void;
package/src/index.js CHANGED
@@ -1,3 +1,4 @@
1
+ import './polyfill';
1
2
  import { deserializeE2E, listenReachableServer, serializeE2E } from "./helpers/peripherals";
2
3
  import { releaseCacheStore, awaitStore } from "./helpers/utils";
3
4
  import { CacheStore, Scoped } from "./helpers/variables";
@@ -15,6 +16,7 @@ import { parse, stringify } from 'json-buffer';
15
16
  import { Validator } from 'guard-object';
16
17
  import sendMessage from "./helpers/broadcaster";
17
18
  import cloneDeep from "lodash.clonedeep";
19
+ import { Buffer } from "buffer";
18
20
 
19
21
  const {
20
22
  _listenCollection,
@@ -177,7 +179,7 @@ export class MosquitoTransport {
177
179
  tokenListener,
178
180
  clientPrivateKey;
179
181
 
180
- const listenerCallback = (route, callback) => function () {
182
+ const listenerCallback = (route, callback) => async function () {
181
183
  if (reservedEventName.includes(route)) {
182
184
  callback?.(...[...arguments]);
183
185
  return;
@@ -187,15 +189,15 @@ export class MosquitoTransport {
187
189
  let res;
188
190
 
189
191
  if (uglify) {
190
- res = parse(deserializeE2E(args, serverE2E_PublicKey, clientPrivateKey));
192
+ res = parse(await deserializeE2E(args, serverE2E_PublicKey, clientPrivateKey));
191
193
  } else res = args;
192
194
 
193
- callback?.(...res || [], ...typeof emitable === 'function' ? [function () {
195
+ callback?.(...res || [], ...typeof emitable === 'function' ? [async function () {
194
196
  const args = [...arguments];
195
197
  let res;
196
198
 
197
199
  if (uglify) {
198
- res = serializeE2E(stringify(args), undefined, serverE2E_PublicKey)[0];
200
+ res = (await serializeE2E(stringify(args), undefined, serverE2E_PublicKey))[0];
199
201
  } else res = args;
200
202
 
201
203
  emitable(res);
@@ -229,26 +231,26 @@ export class MosquitoTransport {
229
231
  const hasEmitable = typeof lastEmit === 'function';
230
232
  const mit = hasEmitable ? emittion.slice(0, -1) : emittion;
231
233
 
232
- const [reqBuilder, [privateKey]] = uglify ? serializeE2E(stringify(mit), undefined, serverE2E_PublicKey) : [undefined, []];
234
+ const [reqBuilder, [privateKey]] = uglify ? await serializeE2E(stringify(mit), undefined, serverE2E_PublicKey) : [undefined, []];
233
235
 
234
236
  if (hasEmitable && promise)
235
237
  throw 'emitWithAck cannot have function in it argument';
236
238
 
237
239
  const result = await thisSocket[promise ? 'emitWithAck' : 'emit'](route,
238
240
  uglify ? reqBuilder : mit,
239
- ...hasEmitable ? [function () {
241
+ ...hasEmitable ? [async function () {
240
242
  const [args] = [...arguments];
241
243
  let res;
242
244
 
243
245
  if (uglify) {
244
- res = parse(deserializeE2E(args, serverE2E_PublicKey, privateKey));
246
+ res = parse(await deserializeE2E(args, serverE2E_PublicKey, privateKey));
245
247
  } else res = args;
246
248
 
247
249
  lastEmit(...res || []);
248
250
  }] : []
249
251
  );
250
252
 
251
- resolve((promise && result) ? uglify ? parse(deserializeE2E(result, serverE2E_PublicKey, privateKey))[0] : result[0] : undefined);
253
+ resolve((promise && result) ? uglify ? parse(await deserializeE2E(result, serverE2E_PublicKey, privateKey))[0] : result[0] : undefined);
252
254
  } catch (e) {
253
255
  reject(e);
254
256
  }
@@ -257,7 +259,7 @@ export class MosquitoTransport {
257
259
  const init = async () => {
258
260
  if (hasCancelled) return;
259
261
  const mtoken = disableAuth ? undefined : Scoped.AuthJWTToken[projectUrl];
260
- const [reqBuilder, [privateKey]] = uglify ? serializeE2E({ accessKey, a_extras: authHandshake }, mtoken, serverE2E_PublicKey) : [null, []];
262
+ const [reqBuilder, [privateKey]] = uglify ? await serializeE2E({ accessKey, a_extras: authHandshake }, mtoken, serverE2E_PublicKey) : [null, []];
261
263
 
262
264
  socket = io(`${wsPrefix}://${projectUrl.split('://')[1]}`, {
263
265
  transports: ['websocket', 'polling', 'flashsocket'],
@@ -0,0 +1,3 @@
1
+ import { Buffer } from "buffer";
2
+
3
+ if (!globalThis.Buffer) globalThis.Buffer = Buffer;
@@ -81,7 +81,7 @@ const refreshToken = (builder, processRef, remainRetries = 7, initialRetries = 7
81
81
  try {
82
82
  const { token, refreshToken: r_token } = CacheStore.AuthStore[projectUrl];
83
83
 
84
- const [reqBuilder, [privateKey]] = buildFetchInterface({
84
+ const [reqBuilder, [privateKey]] = await buildFetchInterface({
85
85
  body: { token, r_token },
86
86
  accessKey,
87
87
  uglify,
@@ -96,7 +96,7 @@ const refreshToken = (builder, processRef, remainRetries = 7, initialRetries = 7
96
96
  }
97
97
  if (r.simpleError) throw r;
98
98
 
99
- const f = uglify ? deserializeE2E(r.e2e, serverE2E_PublicKey, privateKey) : r;
99
+ const f = uglify ? await deserializeE2E(r.e2e, serverE2E_PublicKey, privateKey) : r;
100
100
 
101
101
  if (CacheStore.AuthStore[projectUrl]) {
102
102
  CacheStore.AuthStore[projectUrl].token = f.result.token;
@@ -61,7 +61,7 @@ export class MTAuth {
61
61
  }
62
62
  if (processID !== lastInitRef) return;
63
63
  const mtoken = Scoped.AuthJWTToken[projectUrl],
64
- [reqBuilder, [privateKey]] = uglify ? serializeE2E({ mtoken }, undefined, serverE2E_PublicKey) : [null, []];
64
+ [reqBuilder, [privateKey]] = uglify ? await serializeE2E({ mtoken }, undefined, serverE2E_PublicKey) : [null, []];
65
65
 
66
66
  socket = io(`${wsPrefix}://${baseUrl}`, {
67
67
  transports: ['websocket', 'polling', 'flashsocket'],
@@ -74,11 +74,11 @@ export class MTAuth {
74
74
 
75
75
  socket.emit(_listenUserVerification(uglify));
76
76
 
77
- socket.on("onVerificationChanged", ([err, verified]) => {
77
+ socket.on("onVerificationChanged", async ([err, verified]) => {
78
78
  if (err) {
79
79
  onError?.(simplifyCaughtError(err).simpleError);
80
80
  } else {
81
- callback?.(uglify ? deserializeE2E(verified, serverE2E_PublicKey, privateKey) : verified);
81
+ callback?.(uglify ? await deserializeE2E(verified, serverE2E_PublicKey, privateKey) : verified);
82
82
  }
83
83
  });
84
84
 
@@ -171,7 +171,7 @@ const doCustomSignin = (builder, email, password) => new Promise(async (resolve,
171
171
 
172
172
  try {
173
173
  await awaitStore();
174
- const [reqBuilder, [privateKey]] = buildFetchInterface({
174
+ const [reqBuilder, [privateKey]] = await buildFetchInterface({
175
175
  body: { data: `${encodeBinary(email)}.${encodeBinary(password)}` },
176
176
  accessKey,
177
177
  serverE2E_PublicKey,
@@ -181,7 +181,7 @@ const doCustomSignin = (builder, email, password) => new Promise(async (resolve,
181
181
  const f = await (await fetch(_customSignin(projectUrl, uglify), reqBuilder)).json();
182
182
  if (f.simpleError) throw f;
183
183
 
184
- const r = uglify ? deserializeE2E(f.e2e, serverE2E_PublicKey, privateKey) : f;
184
+ const r = uglify ? await deserializeE2E(f.e2e, serverE2E_PublicKey, privateKey) : f;
185
185
 
186
186
  resolve({
187
187
  user: parseToken(r.result.token),
@@ -199,7 +199,7 @@ const doCustomSignup = (builder, email, password, name, metadata) => new Promise
199
199
 
200
200
  try {
201
201
  await awaitStore();
202
- const [reqBuilder, [privateKey]] = buildFetchInterface({
202
+ const [reqBuilder, [privateKey]] = await buildFetchInterface({
203
203
  body: {
204
204
  data: `${encodeBinary(email)}.${encodeBinary(password)}.${(encodeBinary((name || '').trim()))}`,
205
205
  metadata,
@@ -212,7 +212,7 @@ const doCustomSignup = (builder, email, password, name, metadata) => new Promise
212
212
  const f = await (await fetch(_customSignup(projectUrl, uglify), reqBuilder)).json();
213
213
  if (f.simpleError) throw f;
214
214
 
215
- const r = uglify ? deserializeE2E(f.e2e, serverE2E_PublicKey, privateKey) : f;
215
+ const r = uglify ? await deserializeE2E(f.e2e, serverE2E_PublicKey, privateKey) : f;
216
216
 
217
217
  resolve({
218
218
  user: parseToken(r.result.token),
@@ -249,7 +249,7 @@ export const doSignOut = async (builder) => {
249
249
  try {
250
250
  await awaitReachableServer(projectUrl);
251
251
 
252
- const [reqBuilder] = buildFetchInterface({
252
+ const [reqBuilder] = await buildFetchInterface({
253
253
  body: { token, r_token },
254
254
  accessKey,
255
255
  uglify,
@@ -269,7 +269,7 @@ const doGoogleSignin = (builder, token) => new Promise(async (resolve, reject) =
269
269
 
270
270
  try {
271
271
  await awaitStore();
272
- const [reqBuilder, [privateKey]] = buildFetchInterface({
272
+ const [reqBuilder, [privateKey]] = await buildFetchInterface({
273
273
  body: { token },
274
274
  accessKey,
275
275
  uglify,
@@ -279,7 +279,7 @@ const doGoogleSignin = (builder, token) => new Promise(async (resolve, reject) =
279
279
  const r = await (await fetch(_googleSignin(projectUrl, uglify), reqBuilder)).json();
280
280
  if (r.simpleError) throw r;
281
281
 
282
- const f = uglify ? deserializeE2E(r.e2e, serverE2E_PublicKey, privateKey) : r;
282
+ const f = uglify ? await deserializeE2E(r.e2e, serverE2E_PublicKey, privateKey) : r;
283
283
 
284
284
  resolve({
285
285
  user: parseToken(f.result.token),
@@ -197,7 +197,7 @@ const listenDocument = (callback, onError, builder, config) => {
197
197
  dbUrl
198
198
  };
199
199
 
200
- const [encPlate, [privateKey]] = uglify ? serializeE2E({ accessKey, _body: authObj }, mtoken, serverE2E_PublicKey) : ['', []];
200
+ const [encPlate, [privateKey]] = uglify ? await serializeE2E({ accessKey, _body: authObj }, mtoken, serverE2E_PublicKey) : ['', []];
201
201
 
202
202
  socket = io(`${wsPrefix}://${baseUrl}`, {
203
203
  transports: ['websocket', 'polling', 'flashsocket'],
@@ -218,7 +218,7 @@ const listenDocument = (callback, onError, builder, config) => {
218
218
  onError(simplifyCaughtError(err).simpleError);
219
219
  } else console.error('unhandled listen for:', { path, find }, ' error:', err);
220
220
  } else {
221
- if (uglify) snapshot = deserializeE2E(snapshot, serverE2E_PublicKey, privateKey);
221
+ if (uglify) snapshot = await deserializeE2E(snapshot, serverE2E_PublicKey, privateKey);
222
222
  snapshot = deserializeBSON(snapshot)._;
223
223
  dispatchSnapshot(snapshot);
224
224
 
@@ -290,7 +290,7 @@ const initOnDisconnectionTask = (builder, value, type) => {
290
290
  socket = io(`${wsPrefix}://${baseUrl}`, {
291
291
  transports: ['websocket', 'polling', 'flashsocket'],
292
292
  auth: uglify ? {
293
- e2e: serializeE2E({ accessKey, _body: authObj }, mtoken, serverE2E_PublicKey)[0],
293
+ e2e: (await serializeE2E({ accessKey, _body: authObj }, mtoken, serverE2E_PublicKey))[0],
294
294
  _m_internal: true
295
295
  } : {
296
296
  ...mtoken ? { mtoken } : {},
@@ -365,7 +365,7 @@ const countCollection = async (builder, config) => {
365
365
  if (!disableAuth && await getReachableServer(projectUrl))
366
366
  await awaitRefreshToken(projectUrl);
367
367
 
368
- const [reqBuilder, [privateKey]] = buildFetchInterface({
368
+ const [reqBuilder, [privateKey]] = await buildFetchInterface({
369
369
  body: {
370
370
  commands: { path, find: serializeToBase64(find) },
371
371
  dbName,
@@ -380,7 +380,7 @@ const countCollection = async (builder, config) => {
380
380
  const r = await (await fetch(_documentCount(projectUrl, uglify), reqBuilder)).json();
381
381
  if (r.simpleError) throw r;
382
382
 
383
- const f = uglify ? deserializeE2E(r.e2e, serverE2E_PublicKey, privateKey) : r;
383
+ const f = uglify ? await deserializeE2E(r.e2e, serverE2E_PublicKey, privateKey) : r;
384
384
 
385
385
  if (!disableCache)
386
386
  setLodash(CacheStore.DatabaseCountResult, [projectUrl, dbUrl, dbName, accessId], f.result);
@@ -497,7 +497,7 @@ const findObject = async (builder, config) => {
497
497
  if (!disableAuth && await getReachableServer(projectUrl))
498
498
  await awaitRefreshToken(projectUrl);
499
499
 
500
- const [reqBuilder, [privateKey]] = buildFetchInterface({
500
+ const [reqBuilder, [privateKey]] = await buildFetchInterface({
501
501
  body: {
502
502
  commands: {
503
503
  config: pureConfig && serializeToBase64(pureConfig),
@@ -520,7 +520,7 @@ const findObject = async (builder, config) => {
520
520
  const r = await (await fetch((findOne ? _readDocument : _queryCollection)(projectUrl, uglify), reqBuilder)).json();
521
521
  if (r.simpleError) throw r;
522
522
 
523
- const result = deserializeBSON((uglify ? deserializeE2E(r.e2e, serverE2E_PublicKey, privateKey) : r).result)._;
523
+ const result = deserializeBSON((uglify ? await deserializeE2E(r.e2e, serverE2E_PublicKey, privateKey) : r).result)._;
524
524
 
525
525
  if (shouldCache) insertRecord(builder, config, accessId, result);
526
526
  finalize({ liveResult: result || null });
@@ -634,7 +634,7 @@ const commitData = async (builder, value, type, config) => {
634
634
  if (!disableAuth && await getReachableServer(projectUrl))
635
635
  await awaitRefreshToken(projectUrl);
636
636
 
637
- const [reqBuilder, [privateKey]] = buildFetchInterface({
637
+ const [reqBuilder, [privateKey]] = await buildFetchInterface({
638
638
  body: {
639
639
  commands: {
640
640
  value: value && serializeToBase64({ _: value }),
@@ -656,7 +656,7 @@ const commitData = async (builder, value, type, config) => {
656
656
  const r = await (await fetch((isBatchWrite ? _writeMapDocument : _writeDocument)(projectUrl, uglify), reqBuilder)).json();
657
657
  if (r.simpleError) throw r;
658
658
 
659
- const f = uglify ? deserializeE2E(r.e2e, serverE2E_PublicKey, privateKey) : r;
659
+ const f = uglify ? await deserializeE2E(r.e2e, serverE2E_PublicKey, privateKey) : r;
660
660
 
661
661
  finalize({ ...f }, undefined, { removeCache: true });
662
662
  } catch (e) {
@@ -61,7 +61,7 @@ export const mfetch = async (input = '', init, config) => {
61
61
  if ('uglified' in rawHeader)
62
62
  throw '"uglified" in header is a reserved prop';
63
63
 
64
- if (!input.startsWith(projectUrl) && !rawApproach)
64
+ if (isBaseUrl && !rawApproach)
65
65
  throw `please set { rawApproach: true } if you're trying to access different endpoint at "${input}"`;
66
66
 
67
67
  if (body !== undefined) {
@@ -74,7 +74,7 @@ export const mfetch = async (input = '', init, config) => {
74
74
  ) throw `"body" must be any of string, buffer, object, File, Blob`;
75
75
  }
76
76
 
77
- const rawBody = stringify([(body instanceof File || body instanceof Blob) ? await body.arrayBuffer() : body]);
77
+ const rawBody = stringify([(body instanceof File || body instanceof Blob) ? Buffer.from(await body.arrayBuffer()) : body]);
78
78
 
79
79
  const reqId = await niceHash(
80
80
  JSON.stringify([
@@ -145,7 +145,7 @@ export const mfetch = async (input = '', init, config) => {
145
145
  const mtoken = Scoped.AuthJWTToken[projectUrl];
146
146
  const initType = rawHeader['content-type'];
147
147
 
148
- const [reqBuilder, [privateKey]] = uglified ? serializeE2E(rawBody, mtoken, serverE2E_PublicKey) : [null, []];
148
+ const [reqBuilder, [privateKey]] = uglified ? await serializeE2E(rawBody, mtoken, serverE2E_PublicKey) : [null, []];
149
149
 
150
150
  const f = await fetch(isBaseUrl ? input : `${projectUrl}/${normalizeRoute(input)}`, {
151
151
  ...isBaseUrl ? {} : { method: 'POST' },
@@ -170,7 +170,7 @@ export const mfetch = async (input = '', init, config) => {
170
170
  if (!isBaseUrl && simple) throw { simpleError: JSON.parse(simple) };
171
171
 
172
172
  const base64 = uglified ?
173
- Buffer.from(deserializeE2E(await f.text(), serverE2E_PublicKey, privateKey), 'base64') :
173
+ Buffer.from(await deserializeE2E(await f.text(), serverE2E_PublicKey, privateKey), 'base64') :
174
174
  Buffer.from(await f.arrayBuffer()).toString('base64');
175
175
 
176
176
  const resObj = {
@@ -105,7 +105,7 @@ const deleteContent = async (builder, path, isFolder) => {
105
105
  try {
106
106
  const r = await (await fetch(
107
107
  EngineApi[isFolder ? '_deleteFolder' : '_deleteFile'](projectUrl, uglify),
108
- buildFetchInterface({ path }, accessKey, Scoped.AuthJWTToken[projectUrl], 'DELETE')
108
+ await buildFetchInterface({ path }, accessKey, Scoped.AuthJWTToken[projectUrl], 'DELETE')
109
109
  )).json();
110
110
  if (r.simpleError) throw r;
111
111
  if (r.status !== 'success') throw 'operation not successful';