shogun-core 3.0.4 → 3.0.5

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 (95) hide show
  1. package/dist/browser/shogun-core.js +92134 -0
  2. package/dist/browser/shogun-core.js.map +1 -0
  3. package/dist/config/simplified-config.js +230 -0
  4. package/dist/core.js +338 -0
  5. package/dist/gundb/crypto.js +268 -0
  6. package/dist/gundb/db.js +1833 -0
  7. package/dist/gundb/derive.js +229 -0
  8. package/dist/gundb/errors.js +66 -0
  9. package/dist/gundb/index.js +6 -0
  10. package/dist/gundb/restricted-put.js +81 -0
  11. package/dist/gundb/rxjs.js +445 -0
  12. package/dist/gundb/simple-api.js +438 -0
  13. package/dist/gundb/types.js +4 -0
  14. package/dist/index.js +16 -0
  15. package/dist/interfaces/common.js +1 -0
  16. package/dist/interfaces/events.js +36 -0
  17. package/dist/interfaces/plugin.js +1 -0
  18. package/dist/interfaces/shogun.js +34 -0
  19. package/dist/managers/AuthManager.js +225 -0
  20. package/dist/managers/CoreInitializer.js +240 -0
  21. package/dist/managers/EventManager.js +67 -0
  22. package/dist/managers/PluginManager.js +296 -0
  23. package/dist/migration-test.js +91 -0
  24. package/dist/plugins/base.js +47 -0
  25. package/dist/plugins/index.js +15 -0
  26. package/dist/plugins/nostr/index.js +4 -0
  27. package/dist/plugins/nostr/nostrConnector.js +413 -0
  28. package/dist/plugins/nostr/nostrConnectorPlugin.js +446 -0
  29. package/dist/plugins/nostr/nostrSigner.js +313 -0
  30. package/dist/plugins/nostr/types.js +1 -0
  31. package/dist/plugins/oauth/index.js +3 -0
  32. package/dist/plugins/oauth/oauthConnector.js +753 -0
  33. package/dist/plugins/oauth/oauthPlugin.js +396 -0
  34. package/dist/plugins/oauth/types.js +1 -0
  35. package/dist/plugins/web3/index.js +4 -0
  36. package/dist/plugins/web3/types.js +1 -0
  37. package/dist/plugins/web3/web3Connector.js +528 -0
  38. package/dist/plugins/web3/web3ConnectorPlugin.js +448 -0
  39. package/dist/plugins/web3/web3Signer.js +308 -0
  40. package/dist/plugins/webauthn/index.js +3 -0
  41. package/dist/plugins/webauthn/types.js +11 -0
  42. package/dist/plugins/webauthn/webauthn.js +478 -0
  43. package/dist/plugins/webauthn/webauthnPlugin.js +398 -0
  44. package/dist/plugins/webauthn/webauthnSigner.js +304 -0
  45. package/dist/storage/storage.js +147 -0
  46. package/dist/types/config/simplified-config.d.ts +114 -0
  47. package/dist/types/core.d.ts +305 -0
  48. package/dist/types/gundb/crypto.d.ts +95 -0
  49. package/dist/types/gundb/db.d.ts +404 -0
  50. package/dist/types/gundb/derive.d.ts +21 -0
  51. package/dist/types/gundb/errors.d.ts +42 -0
  52. package/dist/types/gundb/index.d.ts +3 -0
  53. package/dist/types/gundb/restricted-put.d.ts +15 -0
  54. package/dist/types/gundb/rxjs.d.ts +110 -0
  55. package/dist/types/gundb/simple-api.d.ts +90 -0
  56. package/dist/types/gundb/types.d.ts +264 -0
  57. package/dist/types/index.d.ts +14 -0
  58. package/dist/types/interfaces/common.d.ts +85 -0
  59. package/dist/types/interfaces/events.d.ts +131 -0
  60. package/dist/types/interfaces/plugin.d.ts +162 -0
  61. package/dist/types/interfaces/shogun.d.ts +215 -0
  62. package/dist/types/managers/AuthManager.d.ts +72 -0
  63. package/dist/types/managers/CoreInitializer.d.ts +40 -0
  64. package/dist/types/managers/EventManager.d.ts +49 -0
  65. package/dist/types/managers/PluginManager.d.ts +145 -0
  66. package/dist/types/migration-test.d.ts +16 -0
  67. package/dist/types/plugins/base.d.ts +35 -0
  68. package/dist/types/plugins/index.d.ts +14 -0
  69. package/dist/types/plugins/nostr/index.d.ts +4 -0
  70. package/dist/types/plugins/nostr/nostrConnector.d.ts +119 -0
  71. package/dist/types/plugins/nostr/nostrConnectorPlugin.d.ts +163 -0
  72. package/dist/types/plugins/nostr/nostrSigner.d.ts +105 -0
  73. package/dist/types/plugins/nostr/types.d.ts +122 -0
  74. package/dist/types/plugins/oauth/index.d.ts +3 -0
  75. package/dist/types/plugins/oauth/oauthConnector.d.ts +110 -0
  76. package/dist/types/plugins/oauth/oauthPlugin.d.ts +91 -0
  77. package/dist/types/plugins/oauth/types.d.ts +114 -0
  78. package/dist/types/plugins/web3/index.d.ts +4 -0
  79. package/dist/types/plugins/web3/types.d.ts +107 -0
  80. package/dist/types/plugins/web3/web3Connector.d.ts +129 -0
  81. package/dist/types/plugins/web3/web3ConnectorPlugin.d.ts +160 -0
  82. package/dist/types/plugins/web3/web3Signer.d.ts +114 -0
  83. package/dist/types/plugins/webauthn/index.d.ts +3 -0
  84. package/dist/types/plugins/webauthn/types.d.ts +162 -0
  85. package/dist/types/plugins/webauthn/webauthn.d.ts +129 -0
  86. package/dist/types/plugins/webauthn/webauthnPlugin.d.ts +158 -0
  87. package/dist/types/plugins/webauthn/webauthnSigner.d.ts +91 -0
  88. package/dist/types/storage/storage.d.ts +50 -0
  89. package/dist/types/utils/errorHandler.d.ts +119 -0
  90. package/dist/types/utils/eventEmitter.d.ts +39 -0
  91. package/dist/types/utils/validation.d.ts +27 -0
  92. package/dist/utils/errorHandler.js +241 -0
  93. package/dist/utils/eventEmitter.js +76 -0
  94. package/dist/utils/validation.js +72 -0
  95. package/package.json +1 -1
@@ -0,0 +1,229 @@
1
+ import { p256 } from "@noble/curves/p256";
2
+ import { secp256k1 } from "@noble/curves/secp256k1";
3
+ import { sha256 } from "@noble/hashes/sha256";
4
+ import { keccak_256 } from "@noble/hashes/sha3";
5
+ import { ripemd160 } from "@noble/hashes/ripemd160";
6
+ export default async function (pwd, extra, options = {}) {
7
+ const TEXT_ENCODER = new TextEncoder();
8
+ const pwdBytes = pwd
9
+ ? typeof pwd === "string"
10
+ ? TEXT_ENCODER.encode(normalizeString(pwd))
11
+ : pwd
12
+ : crypto.getRandomValues(new Uint8Array(32));
13
+ // Mix extra into password bytes to ensure different results for different inputs
14
+ const extras = extra
15
+ ? (Array.isArray(extra) ? extra : [extra]).map((e) => normalizeString(e.toString()))
16
+ : [];
17
+ const extraBuf = TEXT_ENCODER.encode(extras.join("|"));
18
+ const combinedInput = new Uint8Array(pwdBytes.length + extraBuf.length);
19
+ combinedInput.set(pwdBytes);
20
+ combinedInput.set(extraBuf, pwdBytes.length);
21
+ if (combinedInput.length < 16) {
22
+ throw new Error(`Insufficient input entropy (${combinedInput.length})`);
23
+ }
24
+ const version = "v1";
25
+ const result = {};
26
+ // Mantieni comportamento esistente (P-256) come default
27
+ const { includeP256 = true, includeSecp256k1Bitcoin = true, includeSecp256k1Ethereum = true, } = options;
28
+ if (includeP256) {
29
+ const salts = [
30
+ { label: "signing", type: "pub/priv" },
31
+ { label: "encryption", type: "epub/epriv" },
32
+ ];
33
+ const [signingKeys, encryptionKeys] = await Promise.all(salts.map(async ({ label }) => {
34
+ const salt = TEXT_ENCODER.encode(`${label}-${version}`);
35
+ const privateKey = await stretchKey(combinedInput, salt);
36
+ if (!p256.utils.isValidPrivateKey(privateKey)) {
37
+ throw new Error(`Invalid private key for ${label}`);
38
+ }
39
+ const publicKey = p256.getPublicKey(privateKey, false);
40
+ return {
41
+ pub: keyBufferToJwk(publicKey),
42
+ priv: arrayBufToBase64UrlEncode(privateKey),
43
+ };
44
+ }));
45
+ // Chiavi P-256 esistenti
46
+ result.pub = signingKeys.pub;
47
+ result.priv = signingKeys.priv;
48
+ result.epub = encryptionKeys.pub;
49
+ result.epriv = encryptionKeys.priv;
50
+ }
51
+ // Derivazione Bitcoin P2PKH (secp256k1 + SHA256 + RIPEMD160 + Base58)
52
+ if (includeSecp256k1Bitcoin) {
53
+ const bitcoinSalt = TEXT_ENCODER.encode(`secp256k1-bitcoin-${version}`);
54
+ const bitcoinPrivateKey = await stretchKey(combinedInput, bitcoinSalt);
55
+ if (!secp256k1.utils.isValidPrivateKey(bitcoinPrivateKey)) {
56
+ throw new Error("Invalid secp256k1 private key for Bitcoin");
57
+ }
58
+ const bitcoinPublicKey = secp256k1.getPublicKey(bitcoinPrivateKey, true); // Compressed
59
+ result.secp256k1Bitcoin = {
60
+ privateKey: bytesToHex(bitcoinPrivateKey),
61
+ publicKey: bytesToHex(bitcoinPublicKey),
62
+ address: deriveP2PKHAddress(bitcoinPublicKey),
63
+ };
64
+ }
65
+ // Derivazione Ethereum (secp256k1 + Keccak256)
66
+ if (includeSecp256k1Ethereum) {
67
+ const ethereumSalt = TEXT_ENCODER.encode(`secp256k1-ethereum-${version}`);
68
+ const ethereumPrivateKey = await stretchKey(combinedInput, ethereumSalt);
69
+ if (!secp256k1.utils.isValidPrivateKey(ethereumPrivateKey)) {
70
+ throw new Error("Invalid secp256k1 private key for Ethereum");
71
+ }
72
+ const ethereumPublicKey = secp256k1.getPublicKey(ethereumPrivateKey, false); // Uncompressed
73
+ result.secp256k1Ethereum = {
74
+ privateKey: "0x" + bytesToHex(ethereumPrivateKey),
75
+ publicKey: "0x" + bytesToHex(ethereumPublicKey),
76
+ address: deriveKeccak256Address(ethereumPublicKey),
77
+ };
78
+ }
79
+ return result;
80
+ }
81
+ function arrayBufToBase64UrlEncode(buf) {
82
+ return btoa(String.fromCharCode(...buf))
83
+ .replace(/\//g, "_")
84
+ .replace(/=/g, "")
85
+ .replace(/\+/g, "-");
86
+ }
87
+ function keyBufferToJwk(publicKeyBuffer) {
88
+ if (publicKeyBuffer[0] !== 4)
89
+ throw new Error("Invalid uncompressed public key format");
90
+ return [
91
+ arrayBufToBase64UrlEncode(publicKeyBuffer.slice(1, 33)), // x
92
+ arrayBufToBase64UrlEncode(publicKeyBuffer.slice(33, 65)), // y
93
+ ].join(".");
94
+ }
95
+ function normalizeString(str) {
96
+ return str.normalize("NFC").trim();
97
+ }
98
+ async function stretchKey(input, salt, iterations = 300_000) {
99
+ try {
100
+ const baseKey = await crypto.subtle.importKey("raw", input, { name: "PBKDF2" }, false, ["deriveBits"]);
101
+ const keyBits = await crypto.subtle.deriveBits({
102
+ name: "PBKDF2",
103
+ salt: salt,
104
+ iterations,
105
+ hash: "SHA-256",
106
+ }, baseKey, 256);
107
+ const keyBytes = new Uint8Array(keyBits);
108
+ // Ensure the key is valid for secp256k1
109
+ return ensureValidSecp256k1Key(keyBytes);
110
+ }
111
+ catch (error) {
112
+ // Fallback: generate a deterministic key from input and salt
113
+ const fallbackKey = generateFallbackKey(input, salt);
114
+ return ensureValidSecp256k1Key(fallbackKey);
115
+ }
116
+ }
117
+ function generateFallbackKey(input, salt) {
118
+ // Simple deterministic key generation as fallback
119
+ const key = new Uint8Array(32);
120
+ for (let i = 0; i < 32; i++) {
121
+ key[i] = (i * 7 + salt[i % salt.length]) % 256;
122
+ }
123
+ return key;
124
+ }
125
+ function ensureValidSecp256k1Key(keyBytes) {
126
+ // Ensure the key is not all zeros
127
+ if (keyBytes.every((byte) => byte === 0)) {
128
+ keyBytes[0] = 1;
129
+ }
130
+ // secp256k1 curve order is approximately 2^256 - 2^32 - 2^9 - 2^8 - 2^7 - 2^6 - 2^4 - 1
131
+ const maxValidKey = new Uint8Array([
132
+ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
133
+ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
134
+ 0xff, 0xff, 0xff, 0xfe, 0xba, 0xae, 0xdc, 0xe6,
135
+ ]);
136
+ // If the key is greater than or equal to the curve order, reduce it
137
+ let isGreaterOrEqual = true;
138
+ for (let i = 0; i < 32; i++) {
139
+ if (keyBytes[i] < maxValidKey[i]) {
140
+ isGreaterOrEqual = false;
141
+ break;
142
+ }
143
+ else if (keyBytes[i] > maxValidKey[i]) {
144
+ break;
145
+ }
146
+ }
147
+ if (isGreaterOrEqual) {
148
+ // Reduce the key by setting it to a safe value
149
+ keyBytes[31] = 0xe5; // Set to a value less than the curve order
150
+ }
151
+ // Additional validation: ensure the key is not too small
152
+ if (keyBytes.every((byte) => byte === 0) ||
153
+ keyBytes.every((byte) => byte === 1)) {
154
+ // Set to a safe default value
155
+ keyBytes.fill(0);
156
+ keyBytes[0] = 0x01;
157
+ keyBytes[31] = 0xff;
158
+ }
159
+ return keyBytes;
160
+ }
161
+ function bytesToHex(bytes) {
162
+ return Array.from(bytes)
163
+ .map((b) => b.toString(16).padStart(2, "0"))
164
+ .join("");
165
+ }
166
+ // Base58 encoding per Bitcoin
167
+ const BASE58_ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
168
+ function base58Encode(bytes) {
169
+ if (bytes.length === 0)
170
+ return "";
171
+ // Count leading zeros
172
+ let zeros = 0;
173
+ for (let i = 0; i < bytes.length && bytes[i] === 0; i++) {
174
+ zeros++;
175
+ }
176
+ // Convert to base58
177
+ const digits = [0];
178
+ for (let i = zeros; i < bytes.length; i++) {
179
+ let carry = bytes[i];
180
+ for (let j = 0; j < digits.length; j++) {
181
+ carry += digits[j] << 8;
182
+ digits[j] = carry % 58;
183
+ carry = (carry / 58) | 0;
184
+ }
185
+ while (carry > 0) {
186
+ digits.push(carry % 58);
187
+ carry = (carry / 58) | 0;
188
+ }
189
+ }
190
+ // Convert to string
191
+ let result = "";
192
+ for (let i = 0; i < zeros; i++) {
193
+ result += BASE58_ALPHABET[0];
194
+ }
195
+ for (let i = digits.length - 1; i >= 0; i--) {
196
+ result += BASE58_ALPHABET[digits[i]];
197
+ }
198
+ return result;
199
+ }
200
+ function deriveP2PKHAddress(publicKey) {
201
+ // Bitcoin P2PKH address derivation
202
+ // 1. SHA256 hash del public key
203
+ const sha256Hash = sha256(publicKey);
204
+ // 2. RIPEMD160 hash del risultato
205
+ const ripemd160Hash = ripemd160(sha256Hash);
206
+ // 3. Aggiungi version byte (0x00 per mainnet P2PKH)
207
+ const versionedHash = new Uint8Array(21);
208
+ versionedHash[0] = 0x00; // Mainnet P2PKH version
209
+ versionedHash.set(ripemd160Hash, 1);
210
+ // 4. Double SHA256 per checksum
211
+ const checksum = sha256(sha256(versionedHash));
212
+ // 5. Aggiungi i primi 4 byte del checksum
213
+ const addressBytes = new Uint8Array(25);
214
+ addressBytes.set(versionedHash);
215
+ addressBytes.set(checksum.slice(0, 4), 21);
216
+ // 6. Base58 encode
217
+ return base58Encode(addressBytes);
218
+ }
219
+ function deriveKeccak256Address(publicKey) {
220
+ // Ethereum address derivation usando Keccak256
221
+ // 1. Rimuovi il prefix byte (0x04) dalla chiave pubblica non compressa
222
+ const publicKeyWithoutPrefix = publicKey.slice(1);
223
+ // 2. Calcola Keccak256 hash
224
+ const hash = keccak_256(publicKeyWithoutPrefix);
225
+ // 3. Prendi gli ultimi 20 byte
226
+ const address = hash.slice(-20);
227
+ // 4. Aggiungi '0x' prefix e converti in hex
228
+ return "0x" + bytesToHex(address);
229
+ }
@@ -0,0 +1,66 @@
1
+ /**
2
+ * Error classes for Gun and Auth
3
+ */
4
+ /**
5
+ * Base error for Gun
6
+ */
7
+ export class GunError extends Error {
8
+ constructor(message) {
9
+ super(message);
10
+ this.name = "GunError";
11
+ }
12
+ }
13
+ /**
14
+ * Generic authentication error
15
+ */
16
+ export class AuthError extends GunError {
17
+ constructor(message) {
18
+ super(message);
19
+ this.name = "AuthError";
20
+ }
21
+ }
22
+ /**
23
+ * Invalid credentials error
24
+ */
25
+ export class InvalidCredentials extends AuthError {
26
+ constructor(message = "Credenziali non valide") {
27
+ super(message);
28
+ this.name = "InvalidCredentials";
29
+ }
30
+ }
31
+ /**
32
+ * User already exists error
33
+ */
34
+ export class UserExists extends AuthError {
35
+ constructor(message = "Utente già esistente") {
36
+ super(message);
37
+ this.name = "UserExists";
38
+ }
39
+ }
40
+ /**
41
+ * Timeout error
42
+ */
43
+ export class TimeoutError extends GunError {
44
+ constructor(message = "Timeout durante l'operazione") {
45
+ super(message);
46
+ this.name = "TimeoutError";
47
+ }
48
+ }
49
+ /**
50
+ * Multiple authentication error
51
+ */
52
+ export class MultipleAuthError extends AuthError {
53
+ constructor(message = "Autenticazione multipla in corso") {
54
+ super(message);
55
+ this.name = "MultipleAuthError";
56
+ }
57
+ }
58
+ /** Base error related to the network. */
59
+ export class NetworkError extends GunError {
60
+ }
61
+ const withDefaultMessage = (args, defaultMessage) => {
62
+ if (args.length === 0 || (args.length === 1 && !args[0])) {
63
+ args = [defaultMessage];
64
+ }
65
+ return args;
66
+ };
@@ -0,0 +1,6 @@
1
+ // Export the main class
2
+ export * from "./db";
3
+ // Export improved types
4
+ export * from "./types";
5
+ // Export simplified API
6
+ export * from "./simple-api";
@@ -0,0 +1,81 @@
1
+ // Functional programming style implementation
2
+ const gunHeaderModule = (Gun) => {
3
+ // Closure for token state
4
+ const tokenState = {
5
+ value: undefined,
6
+ };
7
+ // Pure function to create a new token state
8
+ const setToken = (newToken) => {
9
+ tokenState.value = newToken;
10
+ setupTokenMiddleware();
11
+ return tokenState.value;
12
+ };
13
+ // Pure function to retrieve token
14
+ const getToken = () => tokenState.value;
15
+ // Function to add token to headers
16
+ const addTokenToHeaders = (msg) => ({
17
+ ...msg,
18
+ headers: {
19
+ ...msg.headers,
20
+ token: tokenState.value,
21
+ },
22
+ });
23
+ // Setup middleware
24
+ const setupTokenMiddleware = () => {
25
+ Gun.on("opt", function (ctx) {
26
+ if (ctx.once)
27
+ return;
28
+ ctx.on("out", function (msg) {
29
+ const to = this.to;
30
+ // Apply pure function to add headers
31
+ const msgWithHeaders = addTokenToHeaders(msg);
32
+ //console.log('[PUT HEADERS]', msgWithHeaders)
33
+ to.next(msgWithHeaders); // pass to next middleware
34
+ });
35
+ });
36
+ };
37
+ // Initialize middleware
38
+ setupTokenMiddleware();
39
+ // Expose public API
40
+ return {
41
+ setToken,
42
+ getToken,
43
+ };
44
+ };
45
+ // Module instance and exports
46
+ let moduleInstance;
47
+ /**
48
+ * Initialize the Gun headers module with Gun instance and optional token
49
+ * @param Gun - Gun instance
50
+ * @param token - Optional authentication token
51
+ */
52
+ export const restrictedPut = (Gun, token) => {
53
+ moduleInstance = gunHeaderModule(Gun);
54
+ if (token) {
55
+ moduleInstance.setToken(token);
56
+ }
57
+ };
58
+ /**
59
+ * Set the authentication token for Gun requests
60
+ * @param newToken - Token to set
61
+ */
62
+ export const setToken = (newToken) => {
63
+ if (!moduleInstance) {
64
+ throw new Error("Gun headers module not initialized. Call init(Gun, token) first.");
65
+ }
66
+ return moduleInstance.setToken(newToken);
67
+ };
68
+ /**
69
+ * Get the current authentication token
70
+ */
71
+ export const getToken = () => {
72
+ if (!moduleInstance) {
73
+ throw new Error("Gun headers module not initialized. Call init(Gun, token) first.");
74
+ }
75
+ return moduleInstance.getToken();
76
+ };
77
+ // Export the functions to global window (if in browser environment)
78
+ if (typeof window !== "undefined") {
79
+ window.setToken = setToken;
80
+ window.getToken = getToken;
81
+ }