tool-db 2.6.2 → 2.6.6

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.
Files changed (84) hide show
  1. package/bundle.js +1 -1
  2. package/dist/adapters-base/storageAdapter.js +1 -1
  3. package/dist/adapters-base/userAdapter.js +1 -1
  4. package/dist/crdt/counterCrdt.d.ts +2 -2
  5. package/dist/crdt/listCrdt.d.ts +2 -2
  6. package/dist/crdt/mapCrdt.d.ts +2 -2
  7. package/dist/messageHandlers/handlePut.js +101 -12
  8. package/dist/messageHandlers/handlePut.js.map +1 -1
  9. package/dist/toolDbAnonSignIn.js +1 -1
  10. package/dist/toolDbCheckSignupConflicts.d.ts +7 -0
  11. package/dist/toolDbCheckSignupConflicts.js +123 -0
  12. package/dist/toolDbCheckSignupConflicts.js.map +1 -0
  13. package/dist/toolDbKeysSignIn.js +1 -1
  14. package/dist/toolDbSignIn.js +1 -1
  15. package/dist/toolDbSignUp.d.ts +10 -0
  16. package/dist/toolDbSignUp.js +83 -54
  17. package/dist/toolDbSignUp.js.map +1 -1
  18. package/dist/toolDbVerificationWrapper.js +1 -1
  19. package/dist/tooldb.d.ts +18 -0
  20. package/dist/tooldb.js +120 -32
  21. package/dist/tooldb.js.map +1 -1
  22. package/dist/types/message.d.ts +2 -2
  23. package/dist/types/tooldb.d.ts +7 -7
  24. package/dist/utils/verifyMessage.js +11 -3
  25. package/dist/utils/verifyMessage.js.map +1 -1
  26. package/package.json +3 -3
  27. package/lib/adapters-base/networkAdapter.ts +0 -218
  28. package/lib/adapters-base/storageAdapter.ts +0 -57
  29. package/lib/adapters-base/userAdapter.ts +0 -49
  30. package/lib/crdt/baseCrdt.ts +0 -21
  31. package/lib/crdt/counterCrdt.ts +0 -112
  32. package/lib/crdt/listCrdt.ts +0 -190
  33. package/lib/crdt/mapCrdt.ts +0 -121
  34. package/lib/index.ts +0 -49
  35. package/lib/logger.ts +0 -30
  36. package/lib/messageHandlers/handleCrdtGet.ts +0 -34
  37. package/lib/messageHandlers/handleCrdtPut.ts +0 -133
  38. package/lib/messageHandlers/handleFunction.ts +0 -59
  39. package/lib/messageHandlers/handleGet.ts +0 -34
  40. package/lib/messageHandlers/handlePing.ts +0 -40
  41. package/lib/messageHandlers/handlePong.ts +0 -37
  42. package/lib/messageHandlers/handlePut.ts +0 -59
  43. package/lib/messageHandlers/handleQuery.ts +0 -30
  44. package/lib/messageHandlers/handleSubscribe.ts +0 -46
  45. package/lib/server.ts +0 -7
  46. package/lib/shared.ts +0 -5
  47. package/lib/toolDbAnonSignIn.ts +0 -5
  48. package/lib/toolDbClientOnMessage.ts +0 -79
  49. package/lib/toolDbCrdtGet.ts +0 -83
  50. package/lib/toolDbCrdtPut.ts +0 -78
  51. package/lib/toolDbFunction.ts +0 -49
  52. package/lib/toolDbGet.ts +0 -81
  53. package/lib/toolDbKeysSignIn.ts +0 -13
  54. package/lib/toolDbPut.ts +0 -84
  55. package/lib/toolDbQueryKeys.ts +0 -71
  56. package/lib/toolDbSignIn.ts +0 -37
  57. package/lib/toolDbSignUp.ts +0 -72
  58. package/lib/toolDbSubscribe.ts +0 -54
  59. package/lib/toolDbVerificationWrapper.ts +0 -55
  60. package/lib/tooldb.ts +0 -343
  61. package/lib/types/message.ts +0 -154
  62. package/lib/types/tooldb.ts +0 -140
  63. package/lib/utils/catchReturn.ts +0 -4
  64. package/lib/utils/encoding/arrayBufferToHex.ts +0 -18
  65. package/lib/utils/encoding/arrayBufferToString.ts +0 -4
  66. package/lib/utils/encoding/base64ToUint8.ts +0 -13
  67. package/lib/utils/encoding/fromBase64.ts +0 -4
  68. package/lib/utils/encoding/hexToArrayBuffer.ts +0 -13
  69. package/lib/utils/encoding/hexToString.ts +0 -8
  70. package/lib/utils/encoding/hexToUint8.ts +0 -5
  71. package/lib/utils/encoding/stringToArrayBuffer.ts +0 -4
  72. package/lib/utils/encoding/toBase64.ts +0 -4
  73. package/lib/utils/encoding/uint8ToBase64.ts +0 -11
  74. package/lib/utils/generateGroupKey.ts +0 -11
  75. package/lib/utils/getPeerSignature.ts +0 -12
  76. package/lib/utils/getTimestamp.ts +0 -3
  77. package/lib/utils/proofOfWork.ts +0 -31
  78. package/lib/utils/randomAnimal.ts +0 -77
  79. package/lib/utils/sha1.ts +0 -7
  80. package/lib/utils/sha256.ts +0 -7
  81. package/lib/utils/textRandom.ts +0 -11
  82. package/lib/utils/uniq.ts +0 -3
  83. package/lib/utils/verifyMessage.ts +0 -88
  84. package/lib/utils/verifyPeer.ts +0 -15
@@ -1,78 +0,0 @@
1
- import {
2
- ToolDb,
3
- CrdtPutMessage,
4
- textRandom,
5
- VerificationData,
6
- proofOfWork,
7
- BaseCrdt,
8
- } from ".";
9
-
10
- /**
11
- * Triggers a PUT request to other peers.
12
- * @param key key where we want to put the data at.
13
- * @param value Data we want to any (any type)
14
- * @param userNamespaced If this key bolongs to a user or its public. Making it private will enforce validation for our address and signatures.
15
- * @returns Promise<Data | null>
16
- */
17
- export default function toolDbCrdtPut<T = any>(
18
- this: ToolDb,
19
- key: string,
20
- crdt: BaseCrdt<T, any, any>,
21
- userNamespaced = false,
22
- to?: string[]
23
- ): Promise<CrdtPutMessage | null> {
24
- return new Promise((resolve, reject) => {
25
- if (key.includes(".")) {
26
- // Dots are used as a delimitator character between bublic keys and the key of the user's data
27
- reject(new Error(`Key cannot include dots!; ${key}`));
28
- return;
29
- }
30
-
31
- if (!this.userAccount.getAddress()) {
32
- reject(new Error("You need to log in before you can PUT."));
33
- return;
34
- }
35
-
36
- const timestamp = new Date().getTime();
37
-
38
- const crdtChanges = crdt.getChanges();
39
-
40
- const encodedData = JSON.stringify(crdtChanges);
41
-
42
- const dataString = `${encodedData}${this.userAccount.getAddress()}${timestamp}`;
43
-
44
- // WORK
45
- proofOfWork(dataString, this.options.pow)
46
- .then(({ hash, nonce }) => {
47
- this.userAccount.signData(hash).then((signature) => {
48
- if (signature && this.userAccount.getAddress()) {
49
- // Compose the message
50
- const data: VerificationData<any> = {
51
- k: userNamespaced
52
- ? `:${this.userAccount.getAddress()}.${key}`
53
- : key,
54
- a: this.userAccount.getAddress() || "",
55
- n: nonce,
56
- t: timestamp,
57
- h: hash,
58
- s: signature,
59
- v: crdtChanges,
60
- c: crdt.type,
61
- };
62
-
63
- this.logger("PUT CRDT", key, data);
64
-
65
- const finalMessage: CrdtPutMessage<any> = {
66
- type: "crdtPut",
67
- id: textRandom(10),
68
- to: to || [],
69
- data,
70
- };
71
- this.network.sendToAll(finalMessage);
72
- resolve(finalMessage);
73
- }
74
- });
75
- })
76
- .catch(reject);
77
- });
78
- }
@@ -1,49 +0,0 @@
1
- import {
2
- AllowedFunctionArguments,
3
- FunctionReturn,
4
- GenericObject,
5
- textRandom,
6
- ToolDb,
7
- } from ".";
8
-
9
- /**
10
- * Triggers a FUNCTION request to other peers. If the function executes sucessfully it will return code "OK"
11
- * @param function function name
12
- * @param args arguments for the function
13
- * @param timeout Max time to wait for remote.
14
- * @returns Promise<FunctionReturn>
15
- */
16
- export default function toolDbFunction<R, A = GenericObject>(
17
- this: ToolDb,
18
- fName: string,
19
- args: AllowedFunctionArguments<A>,
20
- timeoutMs = 10000
21
- ): Promise<FunctionReturn<R>> {
22
- return new Promise((resolve, reject) => {
23
- this.logger("FUNCTION > " + fName);
24
-
25
- const msgId = textRandom(10);
26
-
27
- const cancelTimeout = setTimeout(() => {
28
- resolve({ return: "Timed out", code: "ERR" });
29
- }, timeoutMs);
30
-
31
- this.addIdListener(msgId, (msg) => {
32
- this.logger("FUNCTION RECV > " + fName, msg);
33
-
34
- clearTimeout(cancelTimeout);
35
- if (msg.type === "functionReturn") {
36
- resolve({ return: msg.return, code: msg.code });
37
- }
38
- });
39
-
40
- // Do get
41
- this.network.sendToAll({
42
- type: "function",
43
- to: [],
44
- function: fName,
45
- args: args,
46
- id: msgId,
47
- });
48
- });
49
- }
package/lib/toolDbGet.ts DELETED
@@ -1,81 +0,0 @@
1
- import { ToolDb, textRandom } from ".";
2
-
3
- /**
4
- * Triggers a GET request to other peers. If the data is available locally it will return that instead.
5
- * @param key key of the data
6
- * @param userNamespaced If this key bolongs to a user or its public. Making it private will enforce validation for our address and signatures.
7
- * @param timeout Max time to wait for remote.
8
- * @returns Promise<Data>
9
- */
10
- export default function toolDbGet<T = any>(
11
- this: ToolDb,
12
- key: string,
13
- userNamespaced = false,
14
- timeoutMs = 1000,
15
- to?: string[]
16
- ): Promise<T | null> {
17
- return new Promise((resolve, reject) => {
18
- if (userNamespaced && this.userAccount.getAddress() === undefined) {
19
- reject(new Error("You are not authorized yet!"));
20
- return;
21
- }
22
- const finalKey = userNamespaced
23
- ? `:${this.userAccount.getAddress()}.${key}`
24
- : key;
25
- this.logger("GET", finalKey);
26
-
27
- const msgId = textRandom(10);
28
-
29
- const cancelTimeout = setTimeout(() => {
30
- this.store
31
- .get(finalKey)
32
- .then((data) => {
33
- try {
34
- const message = JSON.parse(data);
35
- this.emit("data", message);
36
- resolve(message.v);
37
- } catch (e) {
38
- resolve(null);
39
- }
40
- })
41
- .catch((e) => {
42
- resolve(null);
43
- });
44
- }, timeoutMs);
45
-
46
- this.addIdListener(msgId, (msg) => {
47
- this.logger("GET RECV", finalKey);
48
-
49
- clearTimeout(cancelTimeout);
50
- if (msg.type === "put") {
51
- resolve(msg.data.v);
52
- }
53
- });
54
-
55
- this.store
56
- .get(finalKey)
57
- .then((data) => {
58
- try {
59
- const parsed = JSON.parse(data);
60
- const val = parsed.v;
61
- clearTimeout(cancelTimeout);
62
- this.removeIdListener(msgId);
63
- this.emit("data", parsed);
64
- resolve(val);
65
- } catch (e) {
66
- // do nothing
67
- }
68
- })
69
- .catch((e) => {
70
- // do nothing
71
- });
72
-
73
- // Do get
74
- this.network.sendToAll({
75
- type: "get",
76
- to: to || [],
77
- key: finalKey,
78
- id: msgId,
79
- });
80
- });
81
- }
@@ -1,13 +0,0 @@
1
- import { ToolDb, randomAnimal } from ".";
2
-
3
- export default async function toolDbKeysSignIn(
4
- this: ToolDb,
5
- privateKey: string,
6
- username?: string
7
- ): Promise<unknown> {
8
- if (!this.userAccount) return Promise.resolve(undefined);
9
-
10
- const newAccount = await this.userAccount.getAccountFromPrivate(privateKey);
11
- await this.userAccount.setUser(newAccount, username || randomAnimal());
12
- return newAccount;
13
- }
package/lib/toolDbPut.ts DELETED
@@ -1,84 +0,0 @@
1
- import {
2
- ToolDb,
3
- PutMessage,
4
- textRandom,
5
- VerificationData,
6
- proofOfWork,
7
- } from ".";
8
-
9
- /**
10
- * Triggers a PUT request to other peers.
11
- * @param key key where we want to put the data at.
12
- * @param value Data we want to any (any type)
13
- * @param userNamespaced If this key bolongs to a user or its public. Making it private will enforce validation for our address and signatures.
14
- * @returns Promise<Data | null>
15
- */
16
- export default function toolDbPut<T = any>(
17
- this: ToolDb,
18
- key: string,
19
- value: T,
20
- userNamespaced = false,
21
- to?: string[]
22
- ): Promise<PutMessage<T> | null> {
23
- return new Promise((resolve, reject) => {
24
- if (key.includes(".")) {
25
- // Dots are used as a delimitator character between bublic keys and the key of the user's data
26
- reject(new Error(`Key cannot include dots!; ${key}`));
27
- return;
28
- }
29
-
30
- if (!this.userAccount || !this.userAccount.getAddress()) {
31
- reject(new Error("You need to log in before you can PUT."));
32
- return;
33
- }
34
-
35
- const timestamp = new Date().getTime();
36
- const dataString = `${JSON.stringify(
37
- value
38
- )}${this.userAccount.getAddress()}${timestamp}`;
39
-
40
- // WORK
41
- proofOfWork(dataString, this.options.pow)
42
- .then(({ hash, nonce }) => {
43
- this.userAccount.signData(hash).then((signature) => {
44
- if (signature && this.userAccount.getAddress()) {
45
- const finalKey = userNamespaced
46
- ? `:${this.userAccount.getAddress()}.${key}`
47
- : key;
48
-
49
- // Compose the message
50
- const data: VerificationData = {
51
- k: finalKey,
52
- a: this.userAccount.getAddress() || "",
53
- n: nonce,
54
- t: timestamp,
55
- h: hash,
56
- s: signature,
57
- v: value,
58
- c: null,
59
- };
60
-
61
- this.logger("PUT", key, data);
62
-
63
- const finalMessage: PutMessage = {
64
- type: "put",
65
- id: textRandom(10),
66
- to: to || [],
67
- data,
68
- };
69
-
70
- this.network.sendToAll(finalMessage);
71
- this.store
72
- .put(finalKey, JSON.stringify(data))
73
- .catch((e) => {
74
- // do nothing
75
- })
76
- .finally(() => {
77
- resolve(finalMessage);
78
- });
79
- }
80
- });
81
- })
82
- .catch(reject);
83
- });
84
- }
@@ -1,71 +0,0 @@
1
- import { ToolDb, textRandom, uniq } from ".";
2
-
3
- /**
4
- * Triggers a QUERY request to other peers.
5
- * @param key start of the key
6
- * @param userNamespaced If this key bolongs to a user or its public.
7
- * @returns Promise<Data>
8
- */
9
- export default function toolDbQueryKeys(
10
- this: ToolDb,
11
- key: string,
12
- userNamespaced = false,
13
- timeoutMs = 1000,
14
- to?: string[]
15
- ): Promise<string[] | null> {
16
- const user = this.userAccount;
17
-
18
- return new Promise((resolve, reject) => {
19
- if (userNamespaced && user.getAddress() === undefined) {
20
- reject(new Error("You are not authorized yet!"));
21
- return;
22
- }
23
- const finalKey = userNamespaced ? `:${user.getAddress()}.${key}` : key;
24
- this.logger("QUERY", finalKey);
25
-
26
- const msgId = textRandom(10);
27
- let foundKeys: string[] = [];
28
- let timeout: NodeJS.Timeout | undefined;
29
-
30
- let gotLocalKeys = false;
31
-
32
- this.store
33
- .query(finalKey)
34
- .then((localKeys) => {
35
- foundKeys = [...foundKeys, ...localKeys];
36
- gotLocalKeys = true;
37
- timeout = setTimeout(finishListening, timeoutMs);
38
- })
39
- .catch((e) => {
40
- gotLocalKeys = true;
41
- timeout = setTimeout(finishListening, timeoutMs);
42
- });
43
-
44
- const finishListening = () => {
45
- resolve(uniq(foundKeys));
46
- };
47
-
48
- this.addIdListener(msgId, (msg) => {
49
- this.logger("QUERY RECV", finalKey);
50
-
51
- if (msg.type === "queryAck") {
52
- foundKeys = [...foundKeys, ...msg.keys];
53
-
54
- if (timeout) {
55
- clearTimeout(timeout);
56
- }
57
- if (gotLocalKeys) {
58
- timeout = setTimeout(finishListening, timeoutMs);
59
- }
60
- }
61
- });
62
-
63
- // Do get
64
- this.network.sendToAll({
65
- type: "query",
66
- to: to || [],
67
- key: finalKey,
68
- id: msgId,
69
- });
70
- });
71
- }
@@ -1,37 +0,0 @@
1
- import { ToolDb, sha256, randomAnimal } from ".";
2
-
3
- export default function toolDbSignIn(
4
- this: ToolDb,
5
- user: string,
6
- password: string,
7
- to?: string[]
8
- ): Promise<unknown | undefined> {
9
- return new Promise((resolve, reject) => {
10
- this.getData<unknown>(`==${user}`, false, 2000, to).then((_user) => {
11
- if (!_user) {
12
- reject("Could not find user");
13
- return;
14
- }
15
-
16
- try {
17
- this.userAccount
18
- .decryptAccount(_user, sha256(password))
19
- .then(async (newAccount) => {
20
- await this.userAccount.setUser(
21
- newAccount,
22
- user || `Anonymous ${randomAnimal()}`
23
- );
24
-
25
- resolve(_user);
26
- })
27
- .catch((e) => {
28
- reject(e);
29
- });
30
- } catch (e) {
31
- reject(e);
32
- }
33
- }).catch((e) => {
34
- reject(e);
35
- });
36
- });
37
- }
@@ -1,72 +0,0 @@
1
- import {
2
- ToolDb,
3
- PutMessage,
4
- textRandom,
5
- VerificationData,
6
- proofOfWork,
7
- sha256,
8
- } from ".";
9
-
10
- export default async function toolDbSignUp(
11
- this: ToolDb,
12
- user: string,
13
- password: string,
14
- to?: string[]
15
- ): Promise<PutMessage<any>> {
16
- const userRoot = `==${user}`;
17
- return new Promise((resolve, reject) => {
18
- this.getData(userRoot, false, 3000, to)
19
- .then((data) => {
20
- if (data === null) {
21
- const account = new this.options.userAdapter(this);
22
- account.encryptAccount(sha256(password)).then((userData) => {
23
- const timestamp = new Date().getTime();
24
- const userDataString = `${JSON.stringify(
25
- userData
26
- )}${account.getAddress()}${timestamp}`;
27
-
28
- proofOfWork(userDataString, this.options.pow)
29
- .then(({ hash, nonce }) => {
30
- account.signData(hash).then((signature) => {
31
- const signupMessage: VerificationData = {
32
- k: userRoot,
33
- a: account.getAddress() || "",
34
- n: nonce,
35
- t: timestamp,
36
- h: hash,
37
- s: signature,
38
- v: userData,
39
- c: null,
40
- };
41
-
42
- this.logger("SIGNUP PUT", userRoot, signupMessage);
43
-
44
- const finalMsg = {
45
- type: "put",
46
- id: textRandom(10),
47
- to: to || [],
48
- data: signupMessage,
49
- } as PutMessage;
50
-
51
- this.network.sendToAll(finalMsg);
52
- this.store
53
- .put(userRoot, JSON.stringify(signupMessage))
54
- .catch((e) => {
55
- // do nothing
56
- })
57
- .finally(() => {
58
- resolve(finalMsg);
59
- });
60
- });
61
- })
62
- .catch(reject);
63
- });
64
- } else {
65
- reject(new Error("User already exists!"));
66
- }
67
- })
68
- .catch(() => {
69
- reject(new Error("Could not fetch user"));
70
- });
71
- });
72
- }
@@ -1,54 +0,0 @@
1
- import { ToolDb, textRandom } from ".";
2
-
3
- /**
4
- * Subscribe to all PUT updates for this key.
5
- * @param key key of the data
6
- * @param userNamespaced If this key bolongs to a user or its public. Making it
7
- * private will enforce validation for our address and signatures.
8
- * @returns Promise<Data>
9
- */
10
- export default function toolDbSubscribe(
11
- this: ToolDb,
12
- key: string,
13
- userNamespaced = false,
14
- to?: string[]
15
- ): Promise<void> {
16
- return new Promise((resolve, reject) => {
17
- if (userNamespaced && this.userAccount.getAddress() === undefined) {
18
- reject(new Error("You are not authorized yet!"));
19
- return;
20
- }
21
-
22
- const finalKey = userNamespaced
23
- ? `:${this.userAccount.getAddress()}.${key}`
24
- : key;
25
-
26
- this.logger("SUBSCRIBE", finalKey);
27
-
28
- const msgId = textRandom(10);
29
-
30
- this.network.sendToAll({
31
- type: "subscribe",
32
- key: finalKey,
33
- to: to || [],
34
- id: msgId,
35
- });
36
-
37
- this.store
38
- .get(finalKey)
39
- .then((data) => {
40
- try {
41
- const message = JSON.parse(data);
42
- this.triggerKeyListener(finalKey, message);
43
- } catch (e) {
44
- // do nothing
45
- }
46
- })
47
- .catch((e) => {
48
- // do nothing
49
- })
50
- .finally(() => {
51
- resolve();
52
- });
53
- });
54
- }
@@ -1,55 +0,0 @@
1
- import { ToolDb, VerificationData, VerifyResult } from ".";
2
-
3
- export default function toolDbVerificationWrapper(
4
- this: ToolDb,
5
- data: VerificationData<any>
6
- ) {
7
- // This wrapper function adds our custom verification functions to all messages.
8
- return new Promise((resolve) => {
9
- this.verifyMessage(data, this.options.pow).then(async (verified) => {
10
- if (verified) {
11
- let skipCustom = true;
12
- this._customVerificator.forEach((listener) => {
13
- if (listener && data.k && data.k.startsWith(listener.key)) {
14
- skipCustom = false;
15
-
16
- let previousData: any = undefined;
17
- // Get the previously stored value of this key
18
- this.store
19
- .get(data.k)
20
- .then((prev) => {
21
- try {
22
- previousData = JSON.parse(prev);
23
- } catch (e) {
24
- // do nothing
25
- }
26
- })
27
- .catch((e) => {
28
- // do nothing
29
- })
30
- .finally(() => {
31
- listener
32
- .fn(data, previousData)
33
- .then((verified: boolean) => {
34
- if (verified) {
35
- resolve(VerifyResult.Verified);
36
- } else {
37
- resolve(VerifyResult.CustomVerificationFailed);
38
- }
39
- })
40
- .catch((e) => {
41
- resolve(VerifyResult.CustomVerificationFailed);
42
- });
43
- });
44
- }
45
- });
46
-
47
- if (skipCustom) {
48
- resolve(verified);
49
- }
50
- } else {
51
- resolve(VerifyResult.InvalidVerification);
52
- }
53
- });
54
- });
55
- }