@nice-code/util 0.8.0 → 0.9.0

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 (41) hide show
  1. package/build/index.d.ts +765 -0
  2. package/build/index.js +966 -1080
  3. package/build/index.js.map +1 -0
  4. package/package.json +6 -18
  5. package/build/types/core/core_valibot_schemas.d.ts +0 -13
  6. package/build/types/core/createDataStringConverter_stringToObject.d.ts +0 -12
  7. package/build/types/crypto/aes_gcm/createAesGcmKeyFromX25519Keys.d.ts +0 -6
  8. package/build/types/crypto/aes_gcm/decryptBytesWithAesGcmKey.d.ts +0 -9
  9. package/build/types/crypto/aes_gcm/decryptTextDataWithAesGcmKey.d.ts +0 -5
  10. package/build/types/crypto/aes_gcm/encryptBytesWithAesGcmKey.d.ts +0 -10
  11. package/build/types/crypto/aes_gcm/encryptTextDataWithAesGcmKey.d.ts +0 -5
  12. package/build/types/crypto/client_key_link/ClientCryptoKeyLink.d.ts +0 -181
  13. package/build/types/crypto/client_key_link/buildVerifyKeyBoundInfoString.d.ts +0 -20
  14. package/build/types/crypto/crypto.converters.d.ts +0 -53
  15. package/build/types/crypto/crypto.schema.d.ts +0 -92
  16. package/build/types/crypto/ed25519/generateEd25519KeyPair.d.ts +0 -1
  17. package/build/types/crypto/ed25519/importEd25519Key.d.ts +0 -35
  18. package/build/types/crypto/ed25519/serializeEd25519Key_Jwk.d.ts +0 -2
  19. package/build/types/crypto/ed25519/serializeEd25519Key_Raw.d.ts +0 -2
  20. package/build/types/crypto/ed25519/signCombinedTextDataWithKeyEd25519.d.ts +0 -2
  21. package/build/types/crypto/ed25519/signTextDataWithKeyEd25519.d.ts +0 -1
  22. package/build/types/crypto/ed25519/verifyWithKeyEd25519.d.ts +0 -5
  23. package/build/types/crypto/index.d.ts +0 -21
  24. package/build/types/crypto/x25519/createSharedBitsFromX25519.d.ts +0 -4
  25. package/build/types/crypto/x25519/generateX25519KeyPair.d.ts +0 -1
  26. package/build/types/crypto/x25519/importX25519Key.d.ts +0 -35
  27. package/build/types/crypto/x25519/serializeX25519Key_Jwk.d.ts +0 -2
  28. package/build/types/crypto/x25519/serializeX25519Key_Raw.d.ts +0 -2
  29. package/build/types/data_type/index.d.ts +0 -1
  30. package/build/types/data_type/string/nullEmpty.d.ts +0 -3
  31. package/build/types/index.d.ts +0 -10
  32. package/build/types/storage_adapter/StorageAdapter.d.ts +0 -23
  33. package/build/types/storage_adapter/specific/browser/browser_storage.d.ts +0 -26
  34. package/build/types/storage_adapter/specific/cloudflare/durable_object/durable_object_storage.d.ts +0 -14
  35. package/build/types/storage_adapter/specific/cloudflare/durable_object/durable_object_storage.types.d.ts +0 -18
  36. package/build/types/storage_adapter/specific/cloudflare/kv/kv_storage.d.ts +0 -18
  37. package/build/types/storage_adapter/specific/cloudflare/kv/kv_storage.types.d.ts +0 -22
  38. package/build/types/storage_adapter/specific/memory/memory_storage.d.ts +0 -28
  39. package/build/types/storage_adapter/storage_adapter.types.d.ts +0 -21
  40. package/build/types/storage_adapter/typed_storage/createTypedStorage.d.ts +0 -16
  41. package/build/types/typescript/special_typescript_types.d.ts +0 -1
package/build/index.js CHANGED
@@ -1,1153 +1,1039 @@
1
- // src/data_type/string/nullEmpty.ts
2
- var notNullEmpty = (str) => {
3
- return str != null && str.length > 0;
1
+ import { base64 } from "@scure/base";
2
+ import * as v from "valibot";
3
+ //#region src/data_type/string/nullEmpty.ts
4
+ const notNullEmpty = (str) => {
5
+ return str != null && str.length > 0;
4
6
  };
5
-
6
- // src/crypto/x25519/createSharedBitsFromX25519.ts
7
- var createSharedBitsFromX25519 = async ({
8
- privateKey,
9
- publicKey
10
- }) => {
11
- return new Uint8Array(await crypto.subtle.deriveBits({ name: "X25519", public: publicKey }, privateKey, 256));
7
+ //#endregion
8
+ //#region src/crypto/x25519/createSharedBitsFromX25519.ts
9
+ const createSharedBitsFromX25519 = async ({ privateKey, publicKey }) => {
10
+ return new Uint8Array(await crypto.subtle.deriveBits({
11
+ name: "X25519",
12
+ public: publicKey
13
+ }, privateKey, 256));
12
14
  };
13
-
14
- // src/crypto/aes_gcm/createAesGcmKeyFromX25519Keys.ts
15
- var DEFAULT_INFO_STRING = "METEOR_BRIDGE_DEFAULT_INFO_STRING";
16
- var createAesGcmKeyFromX25519Keys = async ({
17
- externalX25519PublicKey,
18
- internalX25519PrivateKey,
19
- infoString,
20
- saltString
21
- }) => {
22
- const sharedBits = await createSharedBitsFromX25519({
23
- privateKey: internalX25519PrivateKey,
24
- publicKey: externalX25519PublicKey
25
- });
26
- const ikm = await crypto.subtle.importKey("raw", new Uint8Array(sharedBits), "HKDF", false, [
27
- "deriveKey"
28
- ]);
29
- const salt = notNullEmpty(saltString) ? new TextEncoder().encode(saltString) : new Uint8Array;
30
- const info = new TextEncoder().encode(notNullEmpty(infoString) ? infoString : DEFAULT_INFO_STRING);
31
- return await crypto.subtle.deriveKey({
32
- name: "HKDF",
33
- hash: "SHA-256",
34
- salt,
35
- info
36
- }, ikm, { name: "AES-GCM", length: 256 }, false, ["encrypt", "decrypt"]);
15
+ //#endregion
16
+ //#region src/crypto/aes_gcm/createAesGcmKeyFromX25519Keys.ts
17
+ const DEFAULT_INFO_STRING = "METEOR_BRIDGE_DEFAULT_INFO_STRING";
18
+ const createAesGcmKeyFromX25519Keys = async ({ externalX25519PublicKey, internalX25519PrivateKey, infoString, saltString }) => {
19
+ const sharedBits = await createSharedBitsFromX25519({
20
+ privateKey: internalX25519PrivateKey,
21
+ publicKey: externalX25519PublicKey
22
+ });
23
+ const ikm = await crypto.subtle.importKey("raw", new Uint8Array(sharedBits), "HKDF", false, ["deriveKey"]);
24
+ const salt = notNullEmpty(saltString) ? new TextEncoder().encode(saltString) : new Uint8Array();
25
+ const info = new TextEncoder().encode(notNullEmpty(infoString) ? infoString : DEFAULT_INFO_STRING);
26
+ return await crypto.subtle.deriveKey({
27
+ name: "HKDF",
28
+ hash: "SHA-256",
29
+ salt,
30
+ info
31
+ }, ikm, {
32
+ name: "AES-GCM",
33
+ length: 256
34
+ }, false, ["encrypt", "decrypt"]);
37
35
  };
38
- // src/crypto/aes_gcm/decryptBytesWithAesGcmKey.ts
39
- var decryptBytesWithAesGcmKey = async ({
40
- aesGcmKey,
41
- dataToDecrypt
42
- }) => {
43
- const decryptedData = await crypto.subtle.decrypt({ name: "AES-GCM", iv: new Uint8Array(dataToDecrypt.nonce) }, aesGcmKey, new Uint8Array(dataToDecrypt.ciphertext));
44
- return new Uint8Array(decryptedData);
36
+ //#endregion
37
+ //#region src/crypto/aes_gcm/decryptBytesWithAesGcmKey.ts
38
+ /**
39
+ * Decrypts a raw-bytes AES-GCM payload (binary nonce + ciphertext) back to bytes. The counterpart of
40
+ * {@link decryptTextDataWithAesGcmKey}. AES-GCM verifies integrity, so a tampered ciphertext throws.
41
+ */
42
+ const decryptBytesWithAesGcmKey = async ({ aesGcmKey, dataToDecrypt }) => {
43
+ const decryptedData = await crypto.subtle.decrypt({
44
+ name: "AES-GCM",
45
+ iv: new Uint8Array(dataToDecrypt.nonce)
46
+ }, aesGcmKey, new Uint8Array(dataToDecrypt.ciphertext));
47
+ return new Uint8Array(decryptedData);
45
48
  };
46
- // src/crypto/aes_gcm/decryptTextDataWithAesGcmKey.ts
47
- import { base64 } from "@scure/base";
48
- var decryptTextDataWithAesGcmKey = async ({
49
- aesGcmKey,
50
- dataToDecrypt
51
- }) => {
52
- const decryptedData = await crypto.subtle.decrypt({
53
- name: "AES-GCM",
54
- iv: new Uint8Array(base64.decode(dataToDecrypt.nonce))
55
- }, aesGcmKey, new Uint8Array(base64.decode(dataToDecrypt.ciphertext)));
56
- return new TextDecoder().decode(decryptedData);
49
+ //#endregion
50
+ //#region src/crypto/aes_gcm/decryptTextDataWithAesGcmKey.ts
51
+ const decryptTextDataWithAesGcmKey = async ({ aesGcmKey, dataToDecrypt }) => {
52
+ const decryptedData = await crypto.subtle.decrypt({
53
+ name: "AES-GCM",
54
+ iv: new Uint8Array(base64.decode(dataToDecrypt.nonce))
55
+ }, aesGcmKey, new Uint8Array(base64.decode(dataToDecrypt.ciphertext)));
56
+ return new TextDecoder().decode(decryptedData);
57
57
  };
58
- // src/crypto/aes_gcm/encryptBytesWithAesGcmKey.ts
59
- var encryptBytesWithAesGcmKey = async ({
60
- aesGcmKey,
61
- dataToEncrypt
62
- }) => {
63
- const nonce = crypto.getRandomValues(new Uint8Array(12));
64
- const encryptedData = await crypto.subtle.encrypt({ name: "AES-GCM", iv: nonce }, aesGcmKey, new Uint8Array(dataToEncrypt));
65
- return { nonce, ciphertext: new Uint8Array(encryptedData) };
58
+ //#endregion
59
+ //#region src/crypto/aes_gcm/encryptBytesWithAesGcmKey.ts
60
+ /**
61
+ * Encrypts raw bytes with an AES-GCM key, returning the binary nonce + ciphertext. The bytes
62
+ * counterpart of {@link encryptTextDataWithAesGcmKey} use it for binary channels (msgpack frames)
63
+ * to avoid base64 inflation. A fresh 12-byte nonce is generated per call (never reuse a nonce).
64
+ */
65
+ const encryptBytesWithAesGcmKey = async ({ aesGcmKey, dataToEncrypt }) => {
66
+ const nonce = crypto.getRandomValues(new Uint8Array(12));
67
+ const encryptedData = await crypto.subtle.encrypt({
68
+ name: "AES-GCM",
69
+ iv: nonce
70
+ }, aesGcmKey, new Uint8Array(dataToEncrypt));
71
+ return {
72
+ nonce,
73
+ ciphertext: new Uint8Array(encryptedData)
74
+ };
66
75
  };
67
- // src/crypto/aes_gcm/encryptTextDataWithAesGcmKey.ts
68
- import { base64 as base642 } from "@scure/base";
69
- var encryptTextDataWithAesGcmKey = async ({
70
- aesGcmKey,
71
- dataToEncrypt
72
- }) => {
73
- const nonce = crypto.getRandomValues(new Uint8Array(12));
74
- const encryptedData = await crypto.subtle.encrypt({
75
- name: "AES-GCM",
76
- iv: nonce
77
- }, aesGcmKey, new TextEncoder().encode(dataToEncrypt));
78
- return {
79
- nonce: base642.encode(nonce),
80
- ciphertext: base642.encode(new Uint8Array(encryptedData))
81
- };
76
+ //#endregion
77
+ //#region src/crypto/aes_gcm/encryptTextDataWithAesGcmKey.ts
78
+ const encryptTextDataWithAesGcmKey = async ({ aesGcmKey, dataToEncrypt }) => {
79
+ const nonce = crypto.getRandomValues(new Uint8Array(12));
80
+ const encryptedData = await crypto.subtle.encrypt({
81
+ name: "AES-GCM",
82
+ iv: nonce
83
+ }, aesGcmKey, new TextEncoder().encode(dataToEncrypt));
84
+ return {
85
+ nonce: base64.encode(nonce),
86
+ ciphertext: base64.encode(new Uint8Array(encryptedData))
87
+ };
82
88
  };
83
- // src/crypto/ed25519/signTextDataWithKeyEd25519.ts
84
- var signTextDataWithKeyEd25519 = async (data, cryptoKey) => {
85
- const dataBuffer = new TextEncoder().encode(data);
86
- const signature = await crypto.subtle.sign({
87
- name: "ED25519"
88
- }, cryptoKey, dataBuffer);
89
- return new Uint8Array(signature);
89
+ //#endregion
90
+ //#region src/crypto/ed25519/signTextDataWithKeyEd25519.ts
91
+ const signTextDataWithKeyEd25519 = async (data, cryptoKey) => {
92
+ const dataBuffer = new TextEncoder().encode(data);
93
+ const signature = await crypto.subtle.sign({ name: "ED25519" }, cryptoKey, dataBuffer);
94
+ return new Uint8Array(signature);
90
95
  };
91
-
92
- // src/crypto/ed25519/signCombinedTextDataWithKeyEd25519.ts
93
- var DEFAULT_COMBINED_TEXT_DATA_SEPARATOR = "::";
94
- var signCombinedTextDataWithKeyEd25519 = async (data, cryptoKey, separator = DEFAULT_COMBINED_TEXT_DATA_SEPARATOR) => {
95
- return await signTextDataWithKeyEd25519(data.join(separator), cryptoKey);
96
+ //#endregion
97
+ //#region src/crypto/ed25519/signCombinedTextDataWithKeyEd25519.ts
98
+ const DEFAULT_COMBINED_TEXT_DATA_SEPARATOR = "::";
99
+ const signCombinedTextDataWithKeyEd25519 = async (data, cryptoKey, separator = "::") => {
100
+ return await signTextDataWithKeyEd25519(data.join(separator), cryptoKey);
96
101
  };
97
-
98
- // src/crypto/client_key_link/buildVerifyKeyBoundInfoString.ts
99
- var buildVerifyKeyBoundInfoString = ({
100
- infoString,
101
- verifyPublicKeys
102
- }) => {
103
- const sortedKeys = [...verifyPublicKeys].sort();
104
- return [...infoString != null ? [infoString] : [], ...sortedKeys].join(DEFAULT_COMBINED_TEXT_DATA_SEPARATOR);
102
+ //#endregion
103
+ //#region src/crypto/client_key_link/buildVerifyKeyBoundInfoString.ts
104
+ /**
105
+ * The canonical HKDF `info` for a client-to-client shared key that binds both sides' verify
106
+ * public keys into the derivation.
107
+ *
108
+ * When the two keys are relayed through an intermediary, a tampered key produces mismatched AES
109
+ * keys on the two sides the very first decryption fails, so key substitution is detected without
110
+ * any extra signature ceremony.
111
+ *
112
+ * The keys are sorted lexicographically so the result is independent of which side is "local" —
113
+ * both ends of a link compute the identical string without coordinating an order. Used internally
114
+ * by ClientCryptoKeyLink (`bindVerifyKeysIntoDerivation`); exported for code that derives the same
115
+ * key outside the link.
116
+ */
117
+ const buildVerifyKeyBoundInfoString = ({ infoString, verifyPublicKeys }) => {
118
+ const sortedKeys = [...verifyPublicKeys].sort();
119
+ return [...infoString != null ? [infoString] : [], ...sortedKeys].join("::");
105
120
  };
106
- // src/crypto/client_key_link/ClientCryptoKeyLink.ts
107
- import { base64 as base649 } from "@scure/base";
108
-
109
- // src/storage_adapter/typed_storage/createTypedStorage.ts
110
- function createTypedStorage({
111
- storageAdapter
112
- }) {
113
- const getJson = async (key) => {
114
- return storageAdapter.getJson(key);
115
- };
116
- const getJsonOrDef = async (key, defVal) => {
117
- return await storageAdapter.getJson(key) ?? defVal;
118
- };
119
- const setJson = async (key, val) => {
120
- return storageAdapter.setJson(key, val);
121
- };
122
- const removeItem = async (key) => {
123
- await storageAdapter.removeItem(key);
124
- };
125
- const updateJson = async (key, updater) => {
126
- await storageAdapter.updateJson(key, updater);
127
- };
128
- const updateJsonWithDef = async (key, defaultVal, updater) => {
129
- await storageAdapter.updateJsonOrDef(key, defaultVal, updater);
130
- };
131
- return {
132
- getJson,
133
- getJsonOrDef,
134
- setJson,
135
- removeItem,
136
- updateJson,
137
- updateJsonWithDef,
138
- clearAll: async () => {
139
- await storageAdapter.clearAll();
140
- }
141
- };
121
+ //#endregion
122
+ //#region src/storage_adapter/typed_storage/createTypedStorage.ts
123
+ function createTypedStorage({ storageAdapter }) {
124
+ const getJson = async (key) => {
125
+ return storageAdapter.getJson(key);
126
+ };
127
+ const getJsonOrDef = async (key, defVal) => {
128
+ return await storageAdapter.getJson(key) ?? defVal;
129
+ };
130
+ const setJson = async (key, val) => {
131
+ return storageAdapter.setJson(key, val);
132
+ };
133
+ const removeItem = async (key) => {
134
+ await storageAdapter.removeItem(key);
135
+ };
136
+ const updateJson = async (key, updater) => {
137
+ await storageAdapter.updateJson(key, updater);
138
+ };
139
+ const updateJsonWithDef = async (key, defaultVal, updater) => {
140
+ await storageAdapter.updateJsonOrDef(key, defaultVal, updater);
141
+ };
142
+ return {
143
+ getJson,
144
+ getJsonOrDef,
145
+ setJson,
146
+ removeItem,
147
+ updateJson,
148
+ updateJsonWithDef,
149
+ clearAll: async () => {
150
+ await storageAdapter.clearAll();
151
+ }
152
+ };
142
153
  }
143
-
144
- // src/crypto/ed25519/generateEd25519KeyPair.ts
145
- var generateEd25519KeyPair = async () => {
146
- const keyPair = await crypto.subtle.generateKey({ name: "Ed25519" }, true, [
147
- "sign",
148
- "verify"
149
- ]);
150
- return keyPair;
154
+ //#endregion
155
+ //#region src/crypto/ed25519/generateEd25519KeyPair.ts
156
+ const generateEd25519KeyPair = async () => {
157
+ return await crypto.subtle.generateKey({ name: "Ed25519" }, true, ["sign", "verify"]);
151
158
  };
152
-
153
- // src/crypto/ed25519/importEd25519Key.ts
154
- import { base64 as base644 } from "@scure/base";
155
-
156
- // src/core/createDataStringConverter_stringToObject.ts
157
- var createDataStringConverter_stringToObject = ({
158
- transformJsonForFormats = [],
159
- transformJson = false
160
- } = {}) => (inputDataString) => {
161
- const [type, format, dataString] = inputDataString.split("::");
162
- let parsedData = dataString;
163
- if (transformJson || transformJsonForFormats.includes(format)) {
164
- try {
165
- parsedData = JSON.parse(dataString);
166
- } catch (error) {
167
- const err = new Error(`Failed to parse type and format data string. Given input: "${inputDataString}", expected JSON parsable "data" value in the format "${type}::${format}::data" ${error instanceof Error ? error.message : String(error)}`);
168
- err.cause = error;
169
- throw err;
170
- }
171
- }
172
- return {
173
- formattedString: inputDataString,
174
- type,
175
- format,
176
- data: parsedData
177
- };
159
+ //#endregion
160
+ //#region src/core/createDataStringConverter_stringToObject.ts
161
+ const createDataStringConverter_stringToObject = ({ transformJsonForFormats = [], transformJson = false } = {}) => (inputDataString) => {
162
+ const [type, format, dataString] = inputDataString.split("::");
163
+ let parsedData = dataString;
164
+ if (transformJson || transformJsonForFormats.includes(format)) try {
165
+ parsedData = JSON.parse(dataString);
166
+ } catch (error) {
167
+ const err = /* @__PURE__ */ new Error(`Failed to parse type and format data string. Given input: "${inputDataString}", expected JSON parsable "data" value in the format "${type}::${format}::data" ${error instanceof Error ? error.message : String(error)}`);
168
+ err.cause = error;
169
+ throw err;
170
+ }
171
+ return {
172
+ formattedString: inputDataString,
173
+ type,
174
+ format,
175
+ data: parsedData
176
+ };
178
177
  };
179
-
180
- // src/crypto/crypto.schema.ts
181
- import * as v2 from "valibot";
182
-
183
- // src/core/core_valibot_schemas.ts
184
- import * as v from "valibot";
185
- var vBase64 = v.pipe(v.string(), v.base64());
186
- var vCreateSchema_TypeAndFormatPrefixedDataString = ({
187
- type,
188
- format,
189
- typeKind,
190
- formatKind
191
- }) => {
192
- const _typeKind = typeKind ?? "data_type";
193
- const _formatKind = formatKind ?? "data_format";
194
- return v.pipe(v.custom((input) => {
195
- if (typeof input !== "string")
196
- return false;
197
- const [typePart, formatPart, dataPart] = input.split("::");
198
- return typePart === type && formatPart === format && typeof dataPart === "string";
199
- }, `Invalid format, expected '<${_typeKind}>::<${_formatKind}>::<value>' where "${_typeKind}" is "${type}", "${_formatKind}" is "${format}", and "value" is a string in the specified format`));
178
+ //#endregion
179
+ //#region src/core/core_valibot_schemas.ts
180
+ const vBase64 = v.pipe(v.string(), v.base64());
181
+ const vCreateSchema_TypeAndFormatPrefixedDataString = ({ type, format, typeKind, formatKind }) => {
182
+ const _typeKind = typeKind ?? "data_type";
183
+ const _formatKind = formatKind ?? "data_format";
184
+ return v.pipe(v.custom((input) => {
185
+ if (typeof input !== "string") return false;
186
+ const [typePart, formatPart, dataPart] = input.split("::");
187
+ return typePart === type && formatPart === format && typeof dataPart === "string";
188
+ }, `Invalid format, expected '<${_typeKind}>::<${_formatKind}>::<value>' where "${_typeKind}" is "${type}", "${_formatKind}" is "${format}", and "value" is a string in the specified format`));
200
189
  };
201
-
202
- // src/crypto/crypto.schema.ts
203
- var ECryptoKeyAlgo;
204
- ((ECryptoKeyAlgo2) => {
205
- ECryptoKeyAlgo2["ed25519"] = "ed25519";
206
- ECryptoKeyAlgo2["x25519"] = "x25519";
207
- })(ECryptoKeyAlgo ||= {});
208
- var ECryptoKeyFormat;
209
- ((ECryptoKeyFormat2) => {
210
- ECryptoKeyFormat2["raw_base64"] = "raw_base64";
211
- ECryptoKeyFormat2["jwk"] = "jwk";
212
- })(ECryptoKeyFormat ||= {});
213
- var vSerializedCryptoKeyDataEd25519_Raw = vCreateSchema_TypeAndFormatPrefixedDataString({
214
- format: "raw_base64" /* raw_base64 */,
215
- type: "ed25519" /* ed25519 */,
216
- typeKind: "algo"
190
+ //#endregion
191
+ //#region src/crypto/crypto.schema.ts
192
+ let ECryptoKeyAlgo = /* @__PURE__ */ function(ECryptoKeyAlgo) {
193
+ ECryptoKeyAlgo["ed25519"] = "ed25519";
194
+ ECryptoKeyAlgo["x25519"] = "x25519";
195
+ return ECryptoKeyAlgo;
196
+ }({});
197
+ let ECryptoKeyFormat = /* @__PURE__ */ function(ECryptoKeyFormat) {
198
+ ECryptoKeyFormat["raw_base64"] = "raw_base64";
199
+ ECryptoKeyFormat["jwk"] = "jwk";
200
+ return ECryptoKeyFormat;
201
+ }({});
202
+ const vSerializedCryptoKeyDataEd25519_Raw = vCreateSchema_TypeAndFormatPrefixedDataString({
203
+ format: "raw_base64",
204
+ type: "ed25519",
205
+ typeKind: "algo"
217
206
  });
218
- var vSerializedCryptoKeyDataEd25519_Jwk = vCreateSchema_TypeAndFormatPrefixedDataString({
219
- format: "jwk" /* jwk */,
220
- type: "ed25519" /* ed25519 */,
221
- typeKind: "algo",
222
- transformJson: true
207
+ const vSerializedCryptoKeyDataEd25519_Jwk = vCreateSchema_TypeAndFormatPrefixedDataString({
208
+ format: "jwk",
209
+ type: "ed25519",
210
+ typeKind: "algo",
211
+ transformJson: true
223
212
  });
224
- var vSerializedCryptoKeyDataX25519_Raw = vCreateSchema_TypeAndFormatPrefixedDataString({
225
- format: "raw_base64" /* raw_base64 */,
226
- type: "x25519" /* x25519 */,
227
- typeKind: "algo"
213
+ const vSerializedCryptoKeyDataX25519_Raw = vCreateSchema_TypeAndFormatPrefixedDataString({
214
+ format: "raw_base64",
215
+ type: "x25519",
216
+ typeKind: "algo"
228
217
  });
229
- var vSerializedCryptoKeyDataX25519_Jwk = vCreateSchema_TypeAndFormatPrefixedDataString({
230
- format: "jwk" /* jwk */,
231
- type: "x25519" /* x25519 */,
232
- typeKind: "algo",
233
- transformJson: true
218
+ const vSerializedCryptoKeyDataX25519_Jwk = vCreateSchema_TypeAndFormatPrefixedDataString({
219
+ format: "jwk",
220
+ type: "x25519",
221
+ typeKind: "algo",
222
+ transformJson: true
234
223
  });
235
- var vCryptoKeyPairDataX25519 = v2.object({
236
- publicKey: vSerializedCryptoKeyDataX25519_Raw,
237
- privateKey: vSerializedCryptoKeyDataX25519_Jwk
224
+ const vCryptoKeyPairDataX25519 = v.object({
225
+ publicKey: vSerializedCryptoKeyDataX25519_Raw,
226
+ privateKey: vSerializedCryptoKeyDataX25519_Jwk
238
227
  });
239
- var vCryptoKeyPairDataEd25519 = v2.object({
240
- publicKey: vSerializedCryptoKeyDataEd25519_Raw,
241
- privateKey: vSerializedCryptoKeyDataEd25519_Jwk
228
+ const vCryptoKeyPairDataEd25519 = v.object({
229
+ publicKey: vSerializedCryptoKeyDataEd25519_Raw,
230
+ privateKey: vSerializedCryptoKeyDataEd25519_Jwk
242
231
  });
243
- var vVerifyChallengeWithSignature_Input = v2.object({
244
- challenge: v2.string(),
245
- signatureBase64: vBase64
232
+ const vVerifyChallengeWithSignature_Input = v.object({
233
+ challenge: v.string(),
234
+ signatureBase64: vBase64
246
235
  });
247
- var vVerifyChallengeWithSignature_WithThrow_Input = v2.intersect([
248
- vVerifyChallengeWithSignature_Input,
249
- v2.object({
250
- throwOnInvalid: v2.optional(v2.boolean())
251
- })
252
- ]);
253
- var vEncryptedAesGcmPayload = v2.object({
254
- nonce: vBase64,
255
- ciphertext: vBase64
256
- });
257
-
258
- // src/crypto/crypto.converters.ts
259
- var convertEd25519RawDataStringToObject = createDataStringConverter_stringToObject();
260
- var convertEd25519JwkDataStringToObject = createDataStringConverter_stringToObject({ transformJson: true });
261
- var convertEd25519FormattedStringToObject = createDataStringConverter_stringToObject({
262
- transformJsonForFormats: ["jwk" /* jwk */]
236
+ const vVerifyChallengeWithSignature_WithThrow_Input = v.intersect([vVerifyChallengeWithSignature_Input, v.object({ throwOnInvalid: v.optional(v.boolean()) })]);
237
+ const vEncryptedAesGcmPayload = v.object({
238
+ nonce: vBase64,
239
+ ciphertext: vBase64
263
240
  });
264
- var convertEd25519RawDataStringToSerializedKeyData = (input) => {
265
- const transformed = convertEd25519RawDataStringToObject(input);
266
- return {
267
- prefixed: input,
268
- transformed
269
- };
241
+ //#endregion
242
+ //#region src/crypto/crypto.converters.ts
243
+ /**
244
+ *
245
+ * [CRYPTO ALGO] ED25519
246
+ *
247
+ */
248
+ const convertEd25519RawDataStringToObject = createDataStringConverter_stringToObject();
249
+ const convertEd25519JwkDataStringToObject = createDataStringConverter_stringToObject({ transformJson: true });
250
+ const convertEd25519FormattedStringToObject = createDataStringConverter_stringToObject({ transformJsonForFormats: ["jwk"] });
251
+ const convertEd25519RawDataStringToSerializedKeyData = (input) => {
252
+ return {
253
+ prefixed: input,
254
+ transformed: convertEd25519RawDataStringToObject(input)
255
+ };
270
256
  };
271
- var convertEd25519JwkDataStringToSerializedKeyData = (input) => {
272
- const transformed = convertEd25519JwkDataStringToObject(input);
273
- return {
274
- prefixed: input,
275
- transformed
276
- };
257
+ const convertEd25519JwkDataStringToSerializedKeyData = (input) => {
258
+ return {
259
+ prefixed: input,
260
+ transformed: convertEd25519JwkDataStringToObject(input)
261
+ };
277
262
  };
278
- var convertEd25519FormattedStringToSerializedKeyData = (input) => {
279
- return convertEd25519FormattedStringToObject(input);
263
+ const convertEd25519FormattedStringToSerializedKeyData = (input) => {
264
+ return convertEd25519FormattedStringToObject(input);
280
265
  };
281
- var convertX25519RawDataStringToObject = createDataStringConverter_stringToObject();
282
- var convertX25519JwkDataStringToObject = createDataStringConverter_stringToObject({ transformJson: true });
283
- var convertX25519FormattedStringToObject = createDataStringConverter_stringToObject({
284
- transformJsonForFormats: ["jwk" /* jwk */]
285
- });
286
- var convertX25519RawDataStringToSerializedKeyData = (input) => {
287
- const transformed = convertX25519RawDataStringToObject(input);
288
- return {
289
- prefixed: input,
290
- transformed
291
- };
266
+ /**
267
+ *
268
+ * [CRYPTO ALGO] X25519
269
+ *
270
+ */
271
+ const convertX25519RawDataStringToObject = createDataStringConverter_stringToObject();
272
+ const convertX25519JwkDataStringToObject = createDataStringConverter_stringToObject({ transformJson: true });
273
+ const convertX25519FormattedStringToObject = createDataStringConverter_stringToObject({ transformJsonForFormats: ["jwk"] });
274
+ const convertX25519RawDataStringToSerializedKeyData = (input) => {
275
+ return {
276
+ prefixed: input,
277
+ transformed: convertX25519RawDataStringToObject(input)
278
+ };
292
279
  };
293
- var convertX25519JwkDataStringToSerializedKeyData = (input) => {
294
- const transformed = convertX25519JwkDataStringToObject(input);
295
- return {
296
- prefixed: input,
297
- transformed
298
- };
280
+ const convertX25519JwkDataStringToSerializedKeyData = (input) => {
281
+ return {
282
+ prefixed: input,
283
+ transformed: convertX25519JwkDataStringToObject(input)
284
+ };
299
285
  };
300
- var convertX25519FormattedStringToSerializedKeyData = (input) => {
301
- return convertX25519FormattedStringToObject(input);
286
+ const convertX25519FormattedStringToSerializedKeyData = (input) => {
287
+ return convertX25519FormattedStringToObject(input);
302
288
  };
303
-
304
- // src/crypto/ed25519/importEd25519Key.ts
305
- var fromBase64 = async (dataBase64, keyUsage, extractable) => {
306
- const keyBuffer = Uint8Array.from(base644.decode(dataBase64));
307
- return await crypto.subtle.importKey("raw", keyBuffer, { name: "Ed25519" }, extractable, keyUsage);
289
+ //#endregion
290
+ //#region src/crypto/ed25519/importEd25519Key.ts
291
+ const fromBase64$1 = async (dataBase64, keyUsage, extractable) => {
292
+ const keyBuffer = Uint8Array.from(base64.decode(dataBase64));
293
+ return await crypto.subtle.importKey("raw", keyBuffer, { name: "Ed25519" }, extractable, keyUsage);
308
294
  };
309
- var fromJwk = async (jwk, keyUsage, extractable = true) => {
310
- return await crypto.subtle.importKey("jwk", jwk, { name: "Ed25519" }, extractable, keyUsage);
295
+ const fromJwk$1 = async (jwk, keyUsage, extractable = true) => {
296
+ return await crypto.subtle.importKey("jwk", jwk, { name: "Ed25519" }, extractable, keyUsage);
311
297
  };
312
- var fromSerializedObject = async (serialized, keyUsage, extractable = true) => {
313
- if (serialized.format === "jwk" /* jwk */) {
314
- return await fromJwk(serialized.data, keyUsage, extractable);
315
- }
316
- return await fromBase64(serialized.data, keyUsage, extractable);
298
+ const fromSerializedObject$1 = async (serialized, keyUsage, extractable = true) => {
299
+ if (serialized.format === "jwk") return await fromJwk$1(serialized.data, keyUsage, extractable);
300
+ return await fromBase64$1(serialized.data, keyUsage, extractable);
317
301
  };
318
- var fromFormattedString = async (dataString, keyUsage, extractable = true) => {
319
- const transformed = convertEd25519FormattedStringToSerializedKeyData(dataString);
320
- return await fromSerializedObject(transformed, keyUsage, extractable);
302
+ const fromFormattedString$1 = async (dataString, keyUsage, extractable = true) => {
303
+ return await fromSerializedObject$1(convertEd25519FormattedStringToSerializedKeyData(dataString), keyUsage, extractable);
321
304
  };
322
- var extractableOrNonExtractable = (keyUsage, func) => ({
323
- extractable: (input) => func(input, keyUsage, true),
324
- nonExtractable: (input) => func(input, keyUsage, false)
305
+ const extractableOrNonExtractable$1 = (keyUsage, func) => ({
306
+ extractable: (input) => func(input, keyUsage, true),
307
+ nonExtractable: (input) => func(input, keyUsage, false)
325
308
  });
326
- var importEd25519Key = {
327
- private: {
328
- fromFormattedString: extractableOrNonExtractable(["sign"], fromFormattedString),
329
- fromSerializedObject: extractableOrNonExtractable(["sign"], fromSerializedObject),
330
- fromJwk: extractableOrNonExtractable(["sign"], fromJwk)
331
- },
332
- public: {
333
- fromBase64: extractableOrNonExtractable(["verify"], fromBase64),
334
- fromFormattedString: extractableOrNonExtractable(["verify"], fromFormattedString),
335
- fromSerializedObject: extractableOrNonExtractable(["verify"], fromSerializedObject),
336
- fromJwk: extractableOrNonExtractable(["verify"], fromJwk)
337
- }
309
+ const importEd25519Key = {
310
+ private: {
311
+ fromFormattedString: extractableOrNonExtractable$1(["sign"], fromFormattedString$1),
312
+ fromSerializedObject: extractableOrNonExtractable$1(["sign"], fromSerializedObject$1),
313
+ fromJwk: extractableOrNonExtractable$1(["sign"], fromJwk$1)
314
+ },
315
+ public: {
316
+ fromBase64: extractableOrNonExtractable$1(["verify"], fromBase64$1),
317
+ fromFormattedString: extractableOrNonExtractable$1(["verify"], fromFormattedString$1),
318
+ fromSerializedObject: extractableOrNonExtractable$1(["verify"], fromSerializedObject$1),
319
+ fromJwk: extractableOrNonExtractable$1(["verify"], fromJwk$1)
320
+ }
338
321
  };
339
-
340
- // src/crypto/ed25519/serializeEd25519Key_Jwk.ts
341
- var serializeEd25519Key_Jwk = async (key) => {
342
- const keyJwk = await crypto.subtle.exportKey("jwk", key);
343
- const prefixed = `${"ed25519" /* ed25519 */}::${"jwk" /* jwk */}::${JSON.stringify(keyJwk)}`;
344
- const transformed = {
345
- formattedString: prefixed,
346
- type: "ed25519" /* ed25519 */,
347
- data: keyJwk,
348
- format: "jwk" /* jwk */
349
- };
350
- return { transformed, prefixed };
322
+ //#endregion
323
+ //#region src/crypto/ed25519/serializeEd25519Key_Jwk.ts
324
+ const serializeEd25519Key_Jwk = async (key) => {
325
+ const keyJwk = await crypto.subtle.exportKey("jwk", key);
326
+ const prefixed = `ed25519::jwk::${JSON.stringify(keyJwk)}`;
327
+ return {
328
+ transformed: {
329
+ formattedString: prefixed,
330
+ type: "ed25519",
331
+ data: keyJwk,
332
+ format: "jwk"
333
+ },
334
+ prefixed
335
+ };
351
336
  };
352
-
353
- // src/crypto/ed25519/serializeEd25519Key_Raw.ts
354
- import { base64 as base645 } from "@scure/base";
355
- var serializeEd25519Key_Raw = async (publicKey) => {
356
- const publicKeyBuffer = await crypto.subtle.exportKey("raw", publicKey);
357
- const publicKeyBase64 = base645.encode(new Uint8Array(publicKeyBuffer));
358
- const prefixed = `${"ed25519" /* ed25519 */}::${"raw_base64" /* raw_base64 */}::${publicKeyBase64}`;
359
- const transformed = {
360
- formattedString: prefixed,
361
- type: "ed25519" /* ed25519 */,
362
- data: publicKeyBase64,
363
- format: "raw_base64" /* raw_base64 */
364
- };
365
- return { transformed, prefixed };
337
+ //#endregion
338
+ //#region src/crypto/ed25519/serializeEd25519Key_Raw.ts
339
+ const serializeEd25519Key_Raw = async (publicKey) => {
340
+ const publicKeyBuffer = await crypto.subtle.exportKey("raw", publicKey);
341
+ const publicKeyBase64 = base64.encode(new Uint8Array(publicKeyBuffer));
342
+ const prefixed = `ed25519::raw_base64::${publicKeyBase64}`;
343
+ return {
344
+ transformed: {
345
+ formattedString: prefixed,
346
+ type: "ed25519",
347
+ data: publicKeyBase64,
348
+ format: "raw_base64"
349
+ },
350
+ prefixed
351
+ };
366
352
  };
367
-
368
- // src/crypto/ed25519/verifyWithKeyEd25519.ts
369
- import { base64 as base646 } from "@scure/base";
370
- var verifyWithKeyEd25519 = async ({
371
- challenge,
372
- signatureBase64,
373
- publicKey
374
- }) => {
375
- const signatureBuffer = Uint8Array.from(base646.decode(signatureBase64));
376
- const challengeBuffer = new TextEncoder().encode(challenge);
377
- return await crypto.subtle.verify({
378
- name: "ED25519"
379
- }, publicKey, signatureBuffer, challengeBuffer);
353
+ //#endregion
354
+ //#region src/crypto/ed25519/verifyWithKeyEd25519.ts
355
+ const verifyWithKeyEd25519 = async ({ challenge, signatureBase64, publicKey }) => {
356
+ const signatureBuffer = Uint8Array.from(base64.decode(signatureBase64));
357
+ const challengeBuffer = new TextEncoder().encode(challenge);
358
+ return await crypto.subtle.verify({ name: "ED25519" }, publicKey, signatureBuffer, challengeBuffer);
380
359
  };
381
-
382
- // src/crypto/x25519/generateX25519KeyPair.ts
383
- var generateX25519KeyPair = async () => {
384
- const keyPair = await crypto.subtle.generateKey({ name: "X25519" }, true, [
385
- "deriveKey",
386
- "deriveBits"
387
- ]);
388
- return keyPair;
360
+ //#endregion
361
+ //#region src/crypto/x25519/generateX25519KeyPair.ts
362
+ const generateX25519KeyPair = async () => {
363
+ return await crypto.subtle.generateKey({ name: "X25519" }, true, ["deriveKey", "deriveBits"]);
389
364
  };
390
-
391
- // src/crypto/x25519/importX25519Key.ts
392
- import { base64 as base647 } from "@scure/base";
393
- var fromBase642 = async (dataBase64, keyUsage, extractable) => {
394
- const keyBuffer = Uint8Array.from(base647.decode(dataBase64));
395
- return await crypto.subtle.importKey("raw", keyBuffer, { name: "X25519" }, extractable, keyUsage);
365
+ //#endregion
366
+ //#region src/crypto/x25519/importX25519Key.ts
367
+ const fromBase64 = async (dataBase64, keyUsage, extractable) => {
368
+ const keyBuffer = Uint8Array.from(base64.decode(dataBase64));
369
+ return await crypto.subtle.importKey("raw", keyBuffer, { name: "X25519" }, extractable, keyUsage);
396
370
  };
397
- var fromJwk2 = async (jwk, keyUsage, extractable = true) => {
398
- return await crypto.subtle.importKey("jwk", jwk, { name: "X25519" }, extractable, keyUsage);
371
+ const fromJwk = async (jwk, keyUsage, extractable = true) => {
372
+ return await crypto.subtle.importKey("jwk", jwk, { name: "X25519" }, extractable, keyUsage);
399
373
  };
400
- var fromSerializedObject2 = async (serialized, keyUsage, extractable = true) => {
401
- if (serialized.format === "jwk" /* jwk */) {
402
- return await fromJwk2(serialized.data, keyUsage, extractable);
403
- }
404
- return await fromBase642(serialized.data, keyUsage, extractable);
374
+ const fromSerializedObject = async (serialized, keyUsage, extractable = true) => {
375
+ if (serialized.format === "jwk") return await fromJwk(serialized.data, keyUsage, extractable);
376
+ return await fromBase64(serialized.data, keyUsage, extractable);
405
377
  };
406
- var fromFormattedString2 = async (dataString, keyUsage, extractable = true) => {
407
- const transformed = convertX25519FormattedStringToSerializedKeyData(dataString);
408
- return await fromSerializedObject2(transformed, keyUsage, extractable);
378
+ const fromFormattedString = async (dataString, keyUsage, extractable = true) => {
379
+ return await fromSerializedObject(convertX25519FormattedStringToSerializedKeyData(dataString), keyUsage, extractable);
409
380
  };
410
- var extractableOrNonExtractable2 = (keyUsage, func) => ({
411
- extractable: (input) => func(input, keyUsage, true),
412
- nonExtractable: (input) => func(input, keyUsage, false)
381
+ const extractableOrNonExtractable = (keyUsage, func) => ({
382
+ extractable: (input) => func(input, keyUsage, true),
383
+ nonExtractable: (input) => func(input, keyUsage, false)
413
384
  });
414
- var importX25519Key = {
415
- private: {
416
- fromFormattedString: extractableOrNonExtractable2(["deriveKey", "deriveBits"], fromFormattedString2),
417
- fromSerializedObject: extractableOrNonExtractable2(["deriveKey", "deriveBits"], fromSerializedObject2),
418
- fromJwk: extractableOrNonExtractable2(["deriveKey", "deriveBits"], fromJwk2)
419
- },
420
- public: {
421
- fromBase64: extractableOrNonExtractable2([], fromBase642),
422
- fromFormattedString: extractableOrNonExtractable2([], fromFormattedString2),
423
- fromSerializedObject: extractableOrNonExtractable2([], fromSerializedObject2),
424
- fromJwk: extractableOrNonExtractable2([], fromJwk2)
425
- }
385
+ const importX25519Key = {
386
+ private: {
387
+ fromFormattedString: extractableOrNonExtractable(["deriveKey", "deriveBits"], fromFormattedString),
388
+ fromSerializedObject: extractableOrNonExtractable(["deriveKey", "deriveBits"], fromSerializedObject),
389
+ fromJwk: extractableOrNonExtractable(["deriveKey", "deriveBits"], fromJwk)
390
+ },
391
+ public: {
392
+ fromBase64: extractableOrNonExtractable([], fromBase64),
393
+ fromFormattedString: extractableOrNonExtractable([], fromFormattedString),
394
+ fromSerializedObject: extractableOrNonExtractable([], fromSerializedObject),
395
+ fromJwk: extractableOrNonExtractable([], fromJwk)
396
+ }
426
397
  };
427
-
428
- // src/crypto/x25519/serializeX25519Key_Jwk.ts
429
- var serializeX25519Key_Jwk = async (key) => {
430
- const publicKeyJwk = await crypto.subtle.exportKey("jwk", key);
431
- const prefixed = `${"x25519" /* x25519 */}::${"jwk" /* jwk */}::${JSON.stringify(publicKeyJwk)}`;
432
- const transformed = {
433
- formattedString: prefixed,
434
- type: "x25519" /* x25519 */,
435
- data: publicKeyJwk,
436
- format: "jwk" /* jwk */
437
- };
438
- return { transformed, prefixed };
398
+ //#endregion
399
+ //#region src/crypto/x25519/serializeX25519Key_Jwk.ts
400
+ const serializeX25519Key_Jwk = async (key) => {
401
+ const publicKeyJwk = await crypto.subtle.exportKey("jwk", key);
402
+ const prefixed = `x25519::jwk::${JSON.stringify(publicKeyJwk)}`;
403
+ return {
404
+ transformed: {
405
+ formattedString: prefixed,
406
+ type: "x25519",
407
+ data: publicKeyJwk,
408
+ format: "jwk"
409
+ },
410
+ prefixed
411
+ };
439
412
  };
440
-
441
- // src/crypto/x25519/serializeX25519Key_Raw.ts
442
- import { base64 as base648 } from "@scure/base";
443
- var serializeX25519Key_Raw = async (key) => {
444
- const publicKeyBuffer = await crypto.subtle.exportKey("raw", key);
445
- const publicKeyBase64 = base648.encode(new Uint8Array(publicKeyBuffer));
446
- const prefixed = `${"x25519" /* x25519 */}::${"raw_base64" /* raw_base64 */}::${publicKeyBase64}`;
447
- const transformed = {
448
- formattedString: prefixed,
449
- type: "x25519" /* x25519 */,
450
- data: publicKeyBase64,
451
- format: "raw_base64" /* raw_base64 */
452
- };
453
- return { transformed, prefixed };
413
+ //#endregion
414
+ //#region src/crypto/x25519/serializeX25519Key_Raw.ts
415
+ const serializeX25519Key_Raw = async (key) => {
416
+ const publicKeyBuffer = await crypto.subtle.exportKey("raw", key);
417
+ const publicKeyBase64 = base64.encode(new Uint8Array(publicKeyBuffer));
418
+ const prefixed = `x25519::raw_base64::${publicKeyBase64}`;
419
+ return {
420
+ transformed: {
421
+ formattedString: prefixed,
422
+ type: "x25519",
423
+ data: publicKeyBase64,
424
+ format: "raw_base64"
425
+ },
426
+ prefixed
427
+ };
454
428
  };
455
-
456
- // src/crypto/client_key_link/ClientCryptoKeyLink.ts
457
- class ClientCryptoKeyLink {
458
- localExchangeKeyPair;
459
- localVerifyKeyPair;
460
- linkedClientKeys = new Map;
461
- storage;
462
- initialized = false;
463
- initializePromise;
464
- localExchangeKeyPairPromise;
465
- localVerifyKeyPairPromise;
466
- constructor({ storageAdapter } = {}) {
467
- if (storageAdapter != null) {
468
- this.storage = createTypedStorage({ storageAdapter });
469
- }
470
- }
471
- async initialize() {
472
- if (this.initialized) {
473
- return;
474
- }
475
- this.initializePromise ??= this.runInitialize();
476
- try {
477
- await this.initializePromise;
478
- } finally {
479
- this.initializePromise = undefined;
480
- }
481
- }
482
- async runInitialize() {
483
- await this.loadStoredLocalKeys();
484
- await this.loadLinkedClients();
485
- this.initialized = true;
486
- }
487
- async loadStoredLocalKeys() {
488
- const storedExchange = await this.storage?.getJson("localExchangeKeyPair");
489
- if (storedExchange != null) {
490
- this.localExchangeKeyPair = {
491
- privateKey: await importX25519Key.private.fromFormattedString.extractable(storedExchange.privateKey),
492
- publicKey: await importX25519Key.public.fromFormattedString.extractable(storedExchange.publicKey)
493
- };
494
- }
495
- const storedVerify = await this.storage?.getJson("localVerifyKeyPair");
496
- if (storedVerify != null) {
497
- this.localVerifyKeyPair = {
498
- privateKey: await importEd25519Key.private.fromFormattedString.extractable(storedVerify.privateKey),
499
- publicKey: await importEd25519Key.public.fromFormattedString.extractable(storedVerify.publicKey)
500
- };
501
- }
502
- }
503
- async ensureLocalExchangeKeyPair() {
504
- if (this.localExchangeKeyPair != null) {
505
- return this.localExchangeKeyPair;
506
- }
507
- this.localExchangeKeyPairPromise ??= (async () => {
508
- const keyPair = await generateX25519KeyPair();
509
- this.localExchangeKeyPair = keyPair;
510
- if (this.storage != null) {
511
- await this.storage.setJson("localExchangeKeyPair", await this.serializeExchangeKeyPair(keyPair));
512
- }
513
- return keyPair;
514
- })();
515
- try {
516
- return await this.localExchangeKeyPairPromise;
517
- } finally {
518
- this.localExchangeKeyPairPromise = undefined;
519
- }
520
- }
521
- async ensureLocalVerifyKeyPair() {
522
- if (this.localVerifyKeyPair != null) {
523
- return this.localVerifyKeyPair;
524
- }
525
- this.localVerifyKeyPairPromise ??= (async () => {
526
- const keyPair = await generateEd25519KeyPair();
527
- this.localVerifyKeyPair = keyPair;
528
- if (this.storage != null) {
529
- await this.storage.setJson("localVerifyKeyPair", await this.serializeVerifyKeyPair(keyPair));
530
- }
531
- return keyPair;
532
- })();
533
- try {
534
- return await this.localVerifyKeyPairPromise;
535
- } finally {
536
- this.localVerifyKeyPairPromise = undefined;
537
- }
538
- }
539
- async loadLinkedClients() {
540
- const storedLinkedClients = await this.storage?.getJson("linkedClientPublicKeys");
541
- if (storedLinkedClients == null) {
542
- return;
543
- }
544
- for (const [linkedClientId, publicKeys] of Object.entries(storedLinkedClients)) {
545
- await this.linkClient({
546
- linkedClientId,
547
- verifyPublicKey: publicKeys.verifyPublicKey,
548
- exchangePublicKey: publicKeys.exchangePublicKey,
549
- saltString: publicKeys.saltString,
550
- infoString: publicKeys.infoString,
551
- bindVerifyKeysIntoDerivation: publicKeys.bindVerifyKeysIntoDerivation
552
- });
553
- }
554
- }
555
- async serializeExchangeKeyPair(keyPair) {
556
- return {
557
- publicKey: (await serializeX25519Key_Raw(keyPair.publicKey)).prefixed,
558
- privateKey: (await serializeX25519Key_Jwk(keyPair.privateKey)).prefixed
559
- };
560
- }
561
- async serializeVerifyKeyPair(keyPair) {
562
- return {
563
- publicKey: (await serializeEd25519Key_Raw(keyPair.publicKey)).prefixed,
564
- privateKey: (await serializeEd25519Key_Jwk(keyPair.privateKey)).prefixed
565
- };
566
- }
567
- async getLocalPublicKeys() {
568
- return {
569
- verifyPublicKey: await this.getLocalVerifyPublicKey(),
570
- exchangePublicKey: await this.getLocalExchangePublicKey()
571
- };
572
- }
573
- async getLocalExchangePublicKey() {
574
- const exchangeKeyPair = await this.ensureLocalExchangeKeyPair();
575
- return (await serializeX25519Key_Raw(exchangeKeyPair.publicKey)).prefixed;
576
- }
577
- async getLocalVerifyPublicKey() {
578
- const verifyKeyPair = await this.ensureLocalVerifyKeyPair();
579
- return (await serializeEd25519Key_Raw(verifyKeyPair.publicKey)).prefixed;
580
- }
581
- async linkClient({
582
- linkedClientId,
583
- verifyPublicKey,
584
- exchangePublicKey,
585
- saltString,
586
- infoString,
587
- bindVerifyKeysIntoDerivation
588
- }) {
589
- const existing = this.linkedClientKeys.get(linkedClientId);
590
- const verify = verifyPublicKey != null ? {
591
- publicKey: await importEd25519Key.public.fromFormattedString.extractable(verifyPublicKey),
592
- publicKeySerialized: verifyPublicKey
593
- } : existing?.verify;
594
- const verifyKeyChanged = verifyPublicKey != null && verifyPublicKey !== existing?.verify?.publicKeySerialized;
595
- let exchange = existing?.exchange;
596
- const exchangeParamsProvided = exchangePublicKey != null || saltString !== undefined || infoString !== undefined || bindVerifyKeysIntoDerivation !== undefined;
597
- if (exchangeParamsProvided) {
598
- const nextPublicKeySerialized = exchangePublicKey ?? existing?.exchange?.publicKeySerialized;
599
- if (nextPublicKeySerialized == null) {
600
- throw new Error(`ClientCryptoKeyLink: Cannot set salt/info for ${linkedClientId} without an exchange public key`);
601
- }
602
- const nextSalt = saltString !== undefined ? saltString : existing?.exchange?.saltString;
603
- const nextInfo = infoString !== undefined ? infoString : existing?.exchange?.infoString;
604
- const nextBind = bindVerifyKeysIntoDerivation !== undefined ? bindVerifyKeysIntoDerivation : existing?.exchange?.bindVerifyKeysIntoDerivation;
605
- const publicKey = exchangePublicKey != null ? await importX25519Key.public.fromFormattedString.extractable(exchangePublicKey) : existing.exchange.publicKey;
606
- const unchanged = nextPublicKeySerialized === existing?.exchange?.publicKeySerialized && nextSalt === existing?.exchange?.saltString && nextInfo === existing?.exchange?.infoString && nextBind === existing?.exchange?.bindVerifyKeysIntoDerivation && !(nextBind === true && verifyKeyChanged);
607
- exchange = {
608
- publicKey,
609
- publicKeySerialized: nextPublicKeySerialized,
610
- saltString: nextSalt,
611
- infoString: nextInfo,
612
- bindVerifyKeysIntoDerivation: nextBind,
613
- sharedEncryptKey: unchanged ? existing?.exchange?.sharedEncryptKey : undefined
614
- };
615
- } else if (exchange?.bindVerifyKeysIntoDerivation === true && verifyKeyChanged && exchange.sharedEncryptKey != null) {
616
- exchange = { ...exchange, sharedEncryptKey: undefined };
617
- }
618
- this.linkedClientKeys.set(linkedClientId, { verify, exchange });
619
- }
620
- async linkClientAndStore(input) {
621
- await this.linkClient(input);
622
- if (this.storage == null) {
623
- return;
624
- }
625
- const {
626
- linkedClientId,
627
- verifyPublicKey,
628
- exchangePublicKey,
629
- saltString,
630
- infoString,
631
- bindVerifyKeysIntoDerivation
632
- } = input;
633
- await this.storage.updateJsonWithDef("linkedClientPublicKeys", {}, (current) => ({
634
- ...current,
635
- [linkedClientId]: {
636
- ...current[linkedClientId],
637
- ...verifyPublicKey != null ? { verifyPublicKey } : {},
638
- ...exchangePublicKey != null ? { exchangePublicKey } : {},
639
- ...saltString !== undefined ? { saltString } : {},
640
- ...infoString !== undefined ? { infoString } : {},
641
- ...bindVerifyKeysIntoDerivation !== undefined ? { bindVerifyKeysIntoDerivation } : {}
642
- }
643
- }));
644
- }
645
- hasLinkedClient(linkedClientId) {
646
- return this.linkedClientKeys.has(linkedClientId);
647
- }
648
- getLinkedClientPublicKeys(linkedClientId) {
649
- const linkedClient = this.linkedClientKeys.get(linkedClientId);
650
- if (linkedClient == null) {
651
- return;
652
- }
653
- return {
654
- verifyPublicKey: linkedClient.verify?.publicKeySerialized,
655
- exchangePublicKey: linkedClient.exchange?.publicKeySerialized
656
- };
657
- }
658
- async unlinkClient(linkedClientId) {
659
- this.linkedClientKeys.delete(linkedClientId);
660
- if (this.storage != null) {
661
- await this.storage.updateJson("linkedClientPublicKeys", (current) => {
662
- if (current == null) {
663
- return {};
664
- }
665
- const { [linkedClientId]: _removed, ...rest } = current;
666
- return rest;
667
- });
668
- }
669
- }
670
- async unlinkAllClients() {
671
- this.linkedClientKeys.clear();
672
- if (this.storage != null) {
673
- await this.storage.setJson("linkedClientPublicKeys", {});
674
- }
675
- }
676
- async reset() {
677
- this.linkedClientKeys.clear();
678
- this.localExchangeKeyPair = undefined;
679
- this.localVerifyKeyPair = undefined;
680
- this.initialized = false;
681
- if (this.storage != null) {
682
- await this.storage.removeItem("linkedClientPublicKeys");
683
- await this.storage.removeItem("localExchangeKeyPair");
684
- await this.storage.removeItem("localVerifyKeyPair");
685
- }
686
- }
687
- getLinkedClient(linkedClientId) {
688
- const linkedClient = this.linkedClientKeys.get(linkedClientId);
689
- if (linkedClient == null) {
690
- throw new Error(`ClientCryptoKeyLink: No linked client for ${linkedClientId}`);
691
- }
692
- return linkedClient;
693
- }
694
- async getAesGcmKeyForLinkedClient(externalClientSourceId) {
695
- const linkedClient = this.getLinkedClient(externalClientSourceId);
696
- if (linkedClient.exchange?.sharedEncryptKey != null) {
697
- return linkedClient.exchange.sharedEncryptKey;
698
- }
699
- if (linkedClient.exchange?.publicKey == null) {
700
- throw new Error(`ClientCryptoKeyLink: No public exchange key set for ${externalClientSourceId}`);
701
- }
702
- const localExchangeKeyPair = await this.ensureLocalExchangeKeyPair();
703
- let infoString = linkedClient.exchange.infoString;
704
- if (linkedClient.exchange.bindVerifyKeysIntoDerivation === true) {
705
- const linkedVerifyPublicKey = linkedClient.verify?.publicKeySerialized;
706
- if (linkedVerifyPublicKey == null) {
707
- throw new Error(`ClientCryptoKeyLink: Link for ${externalClientSourceId} binds verify keys into the derivation, but no verify public key is set`);
708
- }
709
- infoString = buildVerifyKeyBoundInfoString({
710
- infoString: linkedClient.exchange.infoString,
711
- verifyPublicKeys: [await this.getLocalVerifyPublicKey(), linkedVerifyPublicKey]
712
- });
713
- }
714
- const sharedEncryptKey = await createAesGcmKeyFromX25519Keys({
715
- internalX25519PrivateKey: localExchangeKeyPair.privateKey,
716
- externalX25519PublicKey: linkedClient.exchange.publicKey,
717
- saltString: linkedClient.exchange.saltString,
718
- infoString
719
- });
720
- this.linkedClientKeys.set(externalClientSourceId, {
721
- ...linkedClient,
722
- exchange: {
723
- ...linkedClient.exchange,
724
- sharedEncryptKey
725
- }
726
- });
727
- return sharedEncryptKey;
728
- }
729
- async encryptDataForLinkedClient({
730
- dataToEncrypt,
731
- linkedClientId
732
- }) {
733
- const key = await this.getAesGcmKeyForLinkedClient(linkedClientId);
734
- return await encryptTextDataWithAesGcmKey({
735
- dataToEncrypt,
736
- aesGcmKey: key
737
- });
738
- }
739
- async decryptDataFromLinkedClient({
740
- dataToDecrypt,
741
- linkedClientId
742
- }) {
743
- const key = await this.getAesGcmKeyForLinkedClient(linkedClientId);
744
- return await decryptTextDataWithAesGcmKey({
745
- dataToDecrypt,
746
- aesGcmKey: key
747
- });
748
- }
749
- async encryptBytesForLinkedClient({
750
- dataToEncrypt,
751
- linkedClientId
752
- }) {
753
- const key = await this.getAesGcmKeyForLinkedClient(linkedClientId);
754
- return await encryptBytesWithAesGcmKey({
755
- dataToEncrypt,
756
- aesGcmKey: key
757
- });
758
- }
759
- async decryptBytesFromLinkedClient({
760
- dataToDecrypt,
761
- linkedClientId
762
- }) {
763
- const key = await this.getAesGcmKeyForLinkedClient(linkedClientId);
764
- return await decryptBytesWithAesGcmKey({
765
- dataToDecrypt,
766
- aesGcmKey: key
767
- });
768
- }
769
- async signAndEncryptDataForLinkedClient({
770
- dataToEncrypt,
771
- linkedClientId
772
- }) {
773
- const { signatureBase64 } = await this.signChallenge([dataToEncrypt]);
774
- const encryptedData = await this.encryptDataForLinkedClient({
775
- dataToEncrypt,
776
- linkedClientId
777
- });
778
- return {
779
- encryptedData,
780
- signatureBase64
781
- };
782
- }
783
- async decryptAndVerifyDataFromLinkedClient({
784
- dataToDecrypt,
785
- linkedClientId,
786
- signatureBase64
787
- }) {
788
- const data = await this.decryptDataFromLinkedClient({
789
- dataToDecrypt,
790
- linkedClientId
791
- });
792
- const isValid = await this.verifyChallengeFromLinkedClient({
793
- linkedClientId,
794
- challenge: data,
795
- signatureBase64
796
- });
797
- return { data, isValid };
798
- }
799
- async signChallenge(challenge) {
800
- if (challenge.length === 0) {
801
- throw new Error("Challenge must contain at least one string");
802
- }
803
- const localVerifyKeyPair = await this.ensureLocalVerifyKeyPair();
804
- const signature = challenge.length > 1 ? await signCombinedTextDataWithKeyEd25519(challenge, localVerifyKeyPair.privateKey) : await signTextDataWithKeyEd25519(challenge[0], localVerifyKeyPair.privateKey);
805
- return {
806
- signatureBase64: base649.encode(signature)
807
- };
808
- }
809
- async verifyChallengeFromLinkedClient({
810
- linkedClientId,
811
- challenge,
812
- signatureBase64
813
- }) {
814
- const linkedClient = this.getLinkedClient(linkedClientId);
815
- if (linkedClient.verify?.publicKey == null) {
816
- throw new Error(`ClientCryptoKeyLink: No verify public key set for ${linkedClientId}`);
817
- }
818
- return await verifyWithKeyEd25519({
819
- challenge,
820
- signatureBase64,
821
- publicKey: linkedClient.verify.publicKey
822
- });
823
- }
824
- }
825
- // src/storage_adapter/storage_adapter.types.ts
826
- var EStorageAdapterType;
827
- ((EStorageAdapterType2) => {
828
- EStorageAdapterType2["string"] = "string";
829
- EStorageAdapterType2["json"] = "json";
830
- })(EStorageAdapterType ||= {});
831
-
832
- // src/storage_adapter/StorageAdapter.ts
833
- class StorageAdapter {
834
- implementation;
835
- keyPrefix;
836
- adapterStorage;
837
- constructor({ methods, keyPrefix, trackKeysForClearing: trackKeys }) {
838
- this.implementation = methods;
839
- this.keyPrefix = keyPrefix ?? "";
840
- const _trackKeys = trackKeys ?? true;
841
- this.adapterStorage = _trackKeys ? createTypedStorage({
842
- storageAdapter: new StorageAdapter({ methods, keyPrefix, trackKeysForClearing: false })
843
- }) : undefined;
844
- }
845
- getPrefixedKey(rawKey) {
846
- return `${this.keyPrefix}${rawKey}`;
847
- }
848
- async trackUsedKey(rawKey) {
849
- if (!this.adapterStorage)
850
- return;
851
- await this.adapterStorage.updateJsonWithDef("__usedKeys__", [], (currentKeys) => {
852
- if (!currentKeys.includes(rawKey)) {
853
- return [...currentKeys, rawKey];
854
- }
855
- return currentKeys;
856
- });
857
- }
858
- async untrackUsedKey(rawKey) {
859
- if (!this.adapterStorage)
860
- return;
861
- await this.adapterStorage.updateJsonWithDef("__usedKeys__", [], (currentKeys) => {
862
- return currentKeys.filter((k) => k !== rawKey);
863
- });
864
- }
865
- async clearAll() {
866
- if (!this.adapterStorage)
867
- return;
868
- const allKeys = await this.adapterStorage.getJsonOrDef("__usedKeys__", []) ?? [];
869
- await Promise.all(allKeys.map(async (key) => {
870
- await this.removeItem(key);
871
- }));
872
- await this.adapterStorage.setJson("__usedKeys__", []);
873
- }
874
- async removeItem(rawKey) {
875
- await this.implementation.removeItem(this.getPrefixedKey(rawKey));
876
- await this.untrackUsedKey(rawKey);
877
- }
878
- async setJson(rawKey, value) {
879
- const key = this.getPrefixedKey(rawKey);
880
- if (this.implementation.type === "string" /* string */) {
881
- await this.implementation.setItem(key, JSON.stringify(value));
882
- } else {
883
- await this.implementation.setItem(key, value);
884
- }
885
- await this.trackUsedKey(rawKey);
886
- }
887
- async getJson(rawKey) {
888
- const key = this.getPrefixedKey(rawKey);
889
- if (this.implementation.type === "string" /* string */) {
890
- const val = await this.implementation.getItem(key);
891
- if (val == null || val === "undefined" || val === "null") {
892
- return;
893
- }
894
- return JSON.parse(val);
895
- } else {
896
- const val = await this.implementation.getItem(key);
897
- if (val == null || val === "undefined" || val === "null") {
898
- return;
899
- }
900
- return val;
901
- }
902
- }
903
- async getJsonOrDef(rawKey, defVal) {
904
- if (this.implementation.type === "string" /* string */) {
905
- const val2 = await this.implementation.getItem(this.getPrefixedKey(rawKey));
906
- if (val2 == null || val2 === "undefined" || val2 === "null") {
907
- return defVal;
908
- }
909
- return JSON.parse(val2);
910
- }
911
- const val = await this.implementation.getItem(this.getPrefixedKey(rawKey));
912
- if (val == null || val === "undefined" || val === "null") {
913
- return defVal;
914
- }
915
- return val;
916
- }
917
- async updateJson(rawKey, updater) {
918
- const currentVal = await this.getJson(rawKey);
919
- const newVal = updater(currentVal);
920
- await this.setJson(rawKey, newVal);
921
- return newVal;
922
- }
923
- async updateJsonOrDef(rawKey, defVal, updater) {
924
- const currentVal = await this.getJsonOrDef(rawKey, defVal);
925
- const newVal = updater(currentVal);
926
- await this.setJson(rawKey, newVal);
927
- return newVal;
928
- }
929
- createJsonGetterSetter(rawKey) {
930
- return {
931
- get: () => this.getJson(rawKey),
932
- set: (value) => this.setJson(rawKey, value)
933
- };
934
- }
935
- }
936
- // src/storage_adapter/specific/browser/browser_storage.ts
429
+ //#endregion
430
+ //#region src/crypto/client_key_link/ClientCryptoKeyLink.ts
431
+ var ClientCryptoKeyLink = class {
432
+ localExchangeKeyPair;
433
+ localVerifyKeyPair;
434
+ linkedClientKeys = /* @__PURE__ */ new Map();
435
+ storage;
436
+ initialized = false;
437
+ initializePromise;
438
+ localExchangeKeyPairPromise;
439
+ localVerifyKeyPairPromise;
440
+ constructor({ storageAdapter } = {}) {
441
+ if (storageAdapter != null) this.storage = createTypedStorage({ storageAdapter });
442
+ }
443
+ /**
444
+ * Loads the local key pairs and any linked client public keys from storage (when a storage
445
+ * adapter was provided), generating and persisting fresh local key pairs if none exist yet.
446
+ *
447
+ * Must be called (and awaited) before any sign/verify/encrypt/decrypt operation.
448
+ */
449
+ async initialize() {
450
+ if (this.initialized) return;
451
+ this.initializePromise ??= this.runInitialize();
452
+ try {
453
+ await this.initializePromise;
454
+ } finally {
455
+ this.initializePromise = void 0;
456
+ }
457
+ }
458
+ async runInitialize() {
459
+ await this.loadStoredLocalKeys();
460
+ await this.loadLinkedClients();
461
+ this.initialized = true;
462
+ }
463
+ /**
464
+ * Loads the local key pairs from storage if they were previously persisted. Does NOT generate
465
+ * fresh keys — local identity is created lazily on first use (see {@link ensureLocalExchangeKeyPair}
466
+ * / {@link ensureLocalVerifyKeyPair}), so a verify-only or otherwise key-less consumer never
467
+ * generates or stores keys it does not need.
468
+ */
469
+ async loadStoredLocalKeys() {
470
+ const storedExchange = await this.storage?.getJson("localExchangeKeyPair");
471
+ if (storedExchange != null) this.localExchangeKeyPair = {
472
+ privateKey: await importX25519Key.private.fromFormattedString.extractable(storedExchange.privateKey),
473
+ publicKey: await importX25519Key.public.fromFormattedString.extractable(storedExchange.publicKey)
474
+ };
475
+ const storedVerify = await this.storage?.getJson("localVerifyKeyPair");
476
+ if (storedVerify != null) this.localVerifyKeyPair = {
477
+ privateKey: await importEd25519Key.private.fromFormattedString.extractable(storedVerify.privateKey),
478
+ publicKey: await importEd25519Key.public.fromFormattedString.extractable(storedVerify.publicKey)
479
+ };
480
+ }
481
+ /**
482
+ * Returns the local exchange (X25519) key pair, generating and persisting it on first use.
483
+ * Concurrent callers share a single generation.
484
+ */
485
+ async ensureLocalExchangeKeyPair() {
486
+ if (this.localExchangeKeyPair != null) return this.localExchangeKeyPair;
487
+ this.localExchangeKeyPairPromise ??= (async () => {
488
+ const keyPair = await generateX25519KeyPair();
489
+ this.localExchangeKeyPair = keyPair;
490
+ if (this.storage != null) await this.storage.setJson("localExchangeKeyPair", await this.serializeExchangeKeyPair(keyPair));
491
+ return keyPair;
492
+ })();
493
+ try {
494
+ return await this.localExchangeKeyPairPromise;
495
+ } finally {
496
+ this.localExchangeKeyPairPromise = void 0;
497
+ }
498
+ }
499
+ /**
500
+ * Returns the local verify (Ed25519) key pair, generating and persisting it on first use.
501
+ * Concurrent callers share a single generation.
502
+ */
503
+ async ensureLocalVerifyKeyPair() {
504
+ if (this.localVerifyKeyPair != null) return this.localVerifyKeyPair;
505
+ this.localVerifyKeyPairPromise ??= (async () => {
506
+ const keyPair = await generateEd25519KeyPair();
507
+ this.localVerifyKeyPair = keyPair;
508
+ if (this.storage != null) await this.storage.setJson("localVerifyKeyPair", await this.serializeVerifyKeyPair(keyPair));
509
+ return keyPair;
510
+ })();
511
+ try {
512
+ return await this.localVerifyKeyPairPromise;
513
+ } finally {
514
+ this.localVerifyKeyPairPromise = void 0;
515
+ }
516
+ }
517
+ async loadLinkedClients() {
518
+ const storedLinkedClients = await this.storage?.getJson("linkedClientPublicKeys");
519
+ if (storedLinkedClients == null) return;
520
+ for (const [linkedClientId, publicKeys] of Object.entries(storedLinkedClients)) await this.linkClient({
521
+ linkedClientId,
522
+ verifyPublicKey: publicKeys.verifyPublicKey,
523
+ exchangePublicKey: publicKeys.exchangePublicKey,
524
+ saltString: publicKeys.saltString,
525
+ infoString: publicKeys.infoString,
526
+ bindVerifyKeysIntoDerivation: publicKeys.bindVerifyKeysIntoDerivation
527
+ });
528
+ }
529
+ async serializeExchangeKeyPair(keyPair) {
530
+ return {
531
+ publicKey: (await serializeX25519Key_Raw(keyPair.publicKey)).prefixed,
532
+ privateKey: (await serializeX25519Key_Jwk(keyPair.privateKey)).prefixed
533
+ };
534
+ }
535
+ async serializeVerifyKeyPair(keyPair) {
536
+ return {
537
+ publicKey: (await serializeEd25519Key_Raw(keyPair.publicKey)).prefixed,
538
+ privateKey: (await serializeEd25519Key_Jwk(keyPair.privateKey)).prefixed
539
+ };
540
+ }
541
+ /**
542
+ * The local public keys that should be shared with a linked client so that it can verify this
543
+ * client's signatures and derive a shared encryption key. Generates the local identity on first
544
+ * use.
545
+ */
546
+ async getLocalPublicKeys() {
547
+ return {
548
+ verifyPublicKey: await this.getLocalVerifyPublicKey(),
549
+ exchangePublicKey: await this.getLocalExchangePublicKey()
550
+ };
551
+ }
552
+ /**
553
+ * The local exchange (X25519) public key, generating the exchange key pair on first use. Does not
554
+ * touch the verify key pair — useful for an exchange-only consumer (e.g. a bridge) that never
555
+ * signs.
556
+ */
557
+ async getLocalExchangePublicKey() {
558
+ return (await serializeX25519Key_Raw((await this.ensureLocalExchangeKeyPair()).publicKey)).prefixed;
559
+ }
560
+ /**
561
+ * The local verify (Ed25519) public key, generating the verify key pair on first use. Does not
562
+ * touch the exchange key pair.
563
+ */
564
+ async getLocalVerifyPublicKey() {
565
+ return (await serializeEd25519Key_Raw((await this.ensureLocalVerifyKeyPair()).publicKey)).prefixed;
566
+ }
567
+ /**
568
+ * Registers (or updates) the public keys of a linked client in memory only — nothing is written
569
+ * to storage. Use this for ephemeral links (e.g. a per-session bridge or end-to-end peer keyed by
570
+ * a session salt/info), so the derived shared key never outlives the process.
571
+ *
572
+ * Re-linking with a new exchange public key, salt, or info invalidates any previously cached
573
+ * shared key for the link.
574
+ */
575
+ async linkClient({ linkedClientId, verifyPublicKey, exchangePublicKey, saltString, infoString, bindVerifyKeysIntoDerivation }) {
576
+ const existing = this.linkedClientKeys.get(linkedClientId);
577
+ const verify = verifyPublicKey != null ? {
578
+ publicKey: await importEd25519Key.public.fromFormattedString.extractable(verifyPublicKey),
579
+ publicKeySerialized: verifyPublicKey
580
+ } : existing?.verify;
581
+ const verifyKeyChanged = verifyPublicKey != null && verifyPublicKey !== existing?.verify?.publicKeySerialized;
582
+ let exchange = existing?.exchange;
583
+ if (exchangePublicKey != null || saltString !== void 0 || infoString !== void 0 || bindVerifyKeysIntoDerivation !== void 0) {
584
+ const nextPublicKeySerialized = exchangePublicKey ?? existing?.exchange?.publicKeySerialized;
585
+ if (nextPublicKeySerialized == null) throw new Error(`ClientCryptoKeyLink: Cannot set salt/info for ${linkedClientId} without an exchange public key`);
586
+ const nextSalt = saltString !== void 0 ? saltString : existing?.exchange?.saltString;
587
+ const nextInfo = infoString !== void 0 ? infoString : existing?.exchange?.infoString;
588
+ const nextBind = bindVerifyKeysIntoDerivation !== void 0 ? bindVerifyKeysIntoDerivation : existing?.exchange?.bindVerifyKeysIntoDerivation;
589
+ exchange = {
590
+ publicKey: exchangePublicKey != null ? await importX25519Key.public.fromFormattedString.extractable(exchangePublicKey) : existing.exchange.publicKey,
591
+ publicKeySerialized: nextPublicKeySerialized,
592
+ saltString: nextSalt,
593
+ infoString: nextInfo,
594
+ bindVerifyKeysIntoDerivation: nextBind,
595
+ sharedEncryptKey: nextPublicKeySerialized === existing?.exchange?.publicKeySerialized && nextSalt === existing?.exchange?.saltString && nextInfo === existing?.exchange?.infoString && nextBind === existing?.exchange?.bindVerifyKeysIntoDerivation && !(nextBind === true && verifyKeyChanged) ? existing?.exchange?.sharedEncryptKey : void 0
596
+ };
597
+ } else if (exchange?.bindVerifyKeysIntoDerivation === true && verifyKeyChanged && exchange.sharedEncryptKey != null) exchange = {
598
+ ...exchange,
599
+ sharedEncryptKey: void 0
600
+ };
601
+ this.linkedClientKeys.set(linkedClientId, {
602
+ verify,
603
+ exchange
604
+ });
605
+ }
606
+ /**
607
+ * Like {@link linkClient}, but also persists the linked client's public keys (and salt/info) to
608
+ * storage so the link survives a reload.
609
+ *
610
+ * NOTE: salt/info are written in plaintext. When they are session secrets (e.g. a partner secret
611
+ * or bridge salt), prefer {@link linkClient} and re-establish the link per session instead.
612
+ */
613
+ async linkClientAndStore(input) {
614
+ await this.linkClient(input);
615
+ if (this.storage == null) return;
616
+ const { linkedClientId, verifyPublicKey, exchangePublicKey, saltString, infoString, bindVerifyKeysIntoDerivation } = input;
617
+ await this.storage.updateJsonWithDef("linkedClientPublicKeys", {}, (current) => ({
618
+ ...current,
619
+ [linkedClientId]: {
620
+ ...current[linkedClientId],
621
+ ...verifyPublicKey != null ? { verifyPublicKey } : {},
622
+ ...exchangePublicKey != null ? { exchangePublicKey } : {},
623
+ ...saltString !== void 0 ? { saltString } : {},
624
+ ...infoString !== void 0 ? { infoString } : {},
625
+ ...bindVerifyKeysIntoDerivation !== void 0 ? { bindVerifyKeysIntoDerivation } : {}
626
+ }
627
+ }));
628
+ }
629
+ /**
630
+ * Whether a linked client is currently registered (in memory) under this id.
631
+ */
632
+ hasLinkedClient(linkedClientId) {
633
+ return this.linkedClientKeys.has(linkedClientId);
634
+ }
635
+ /**
636
+ * The serialized public keys registered for a linked client, or undefined when the client is not
637
+ * linked. Useful when a holder needs to relay a linked client's keys onward (e.g. a backend
638
+ * relaying a wallet's verify key to a partner).
639
+ */
640
+ getLinkedClientPublicKeys(linkedClientId) {
641
+ const linkedClient = this.linkedClientKeys.get(linkedClientId);
642
+ if (linkedClient == null) return;
643
+ return {
644
+ verifyPublicKey: linkedClient.verify?.publicKeySerialized,
645
+ exchangePublicKey: linkedClient.exchange?.publicKeySerialized
646
+ };
647
+ }
648
+ /**
649
+ * Removes a single linked client from memory and, when storage is available, from persisted
650
+ * state. Any cached shared key for the link is dropped with it.
651
+ */
652
+ async unlinkClient(linkedClientId) {
653
+ this.linkedClientKeys.delete(linkedClientId);
654
+ if (this.storage != null) await this.storage.updateJson("linkedClientPublicKeys", (current) => {
655
+ if (current == null) return {};
656
+ const { [linkedClientId]: _removed, ...rest } = current;
657
+ return rest;
658
+ });
659
+ }
660
+ /**
661
+ * Removes all linked clients from memory and persisted state, while keeping the local identity
662
+ * key pairs intact.
663
+ */
664
+ async unlinkAllClients() {
665
+ this.linkedClientKeys.clear();
666
+ if (this.storage != null) await this.storage.setJson("linkedClientPublicKeys", {});
667
+ }
668
+ /**
669
+ * Wipes everything this instance owns — local identity key pairs and all linked clients, in
670
+ * memory and in storage. After a reset, {@link initialize} must be called again before use (it
671
+ * will generate a fresh local identity).
672
+ *
673
+ * Only the keys owned by this util are removed, so a shared storage adapter's other data is left
674
+ * untouched.
675
+ */
676
+ async reset() {
677
+ this.linkedClientKeys.clear();
678
+ this.localExchangeKeyPair = void 0;
679
+ this.localVerifyKeyPair = void 0;
680
+ this.initialized = false;
681
+ if (this.storage != null) {
682
+ await this.storage.removeItem("linkedClientPublicKeys");
683
+ await this.storage.removeItem("localExchangeKeyPair");
684
+ await this.storage.removeItem("localVerifyKeyPair");
685
+ }
686
+ }
687
+ getLinkedClient(linkedClientId) {
688
+ const linkedClient = this.linkedClientKeys.get(linkedClientId);
689
+ if (linkedClient == null) throw new Error(`ClientCryptoKeyLink: No linked client for ${linkedClientId}`);
690
+ return linkedClient;
691
+ }
692
+ async getAesGcmKeyForLinkedClient(externalClientSourceId) {
693
+ const linkedClient = this.getLinkedClient(externalClientSourceId);
694
+ if (linkedClient.exchange?.sharedEncryptKey != null) return linkedClient.exchange.sharedEncryptKey;
695
+ if (linkedClient.exchange?.publicKey == null) throw new Error(`ClientCryptoKeyLink: No public exchange key set for ${externalClientSourceId}`);
696
+ const localExchangeKeyPair = await this.ensureLocalExchangeKeyPair();
697
+ let infoString = linkedClient.exchange.infoString;
698
+ if (linkedClient.exchange.bindVerifyKeysIntoDerivation === true) {
699
+ const linkedVerifyPublicKey = linkedClient.verify?.publicKeySerialized;
700
+ if (linkedVerifyPublicKey == null) throw new Error(`ClientCryptoKeyLink: Link for ${externalClientSourceId} binds verify keys into the derivation, but no verify public key is set`);
701
+ infoString = buildVerifyKeyBoundInfoString({
702
+ infoString: linkedClient.exchange.infoString,
703
+ verifyPublicKeys: [await this.getLocalVerifyPublicKey(), linkedVerifyPublicKey]
704
+ });
705
+ }
706
+ const sharedEncryptKey = await createAesGcmKeyFromX25519Keys({
707
+ internalX25519PrivateKey: localExchangeKeyPair.privateKey,
708
+ externalX25519PublicKey: linkedClient.exchange.publicKey,
709
+ saltString: linkedClient.exchange.saltString,
710
+ infoString
711
+ });
712
+ this.linkedClientKeys.set(externalClientSourceId, {
713
+ ...linkedClient,
714
+ exchange: {
715
+ ...linkedClient.exchange,
716
+ sharedEncryptKey
717
+ }
718
+ });
719
+ return sharedEncryptKey;
720
+ }
721
+ async encryptDataForLinkedClient({ dataToEncrypt, linkedClientId }) {
722
+ return await encryptTextDataWithAesGcmKey({
723
+ dataToEncrypt,
724
+ aesGcmKey: await this.getAesGcmKeyForLinkedClient(linkedClientId)
725
+ });
726
+ }
727
+ async decryptDataFromLinkedClient({ dataToDecrypt, linkedClientId }) {
728
+ return await decryptTextDataWithAesGcmKey({
729
+ dataToDecrypt,
730
+ aesGcmKey: await this.getAesGcmKeyForLinkedClient(linkedClientId)
731
+ });
732
+ }
733
+ /**
734
+ * Bytes counterpart of {@link encryptDataForLinkedClient} — encrypts raw bytes with the shared
735
+ * AES-GCM key, returning a binary nonce + ciphertext. Use it for binary channels (e.g. msgpack
736
+ * WebSocket frames) to avoid base64 inflation.
737
+ */
738
+ async encryptBytesForLinkedClient({ dataToEncrypt, linkedClientId }) {
739
+ return await encryptBytesWithAesGcmKey({
740
+ dataToEncrypt,
741
+ aesGcmKey: await this.getAesGcmKeyForLinkedClient(linkedClientId)
742
+ });
743
+ }
744
+ /** Bytes counterpart of {@link decryptDataFromLinkedClient}. */
745
+ async decryptBytesFromLinkedClient({ dataToDecrypt, linkedClientId }) {
746
+ return await decryptBytesWithAesGcmKey({
747
+ dataToDecrypt,
748
+ aesGcmKey: await this.getAesGcmKeyForLinkedClient(linkedClientId)
749
+ });
750
+ }
751
+ async signAndEncryptDataForLinkedClient({ dataToEncrypt, linkedClientId }) {
752
+ const { signatureBase64 } = await this.signChallenge([dataToEncrypt]);
753
+ return {
754
+ encryptedData: await this.encryptDataForLinkedClient({
755
+ dataToEncrypt,
756
+ linkedClientId
757
+ }),
758
+ signatureBase64
759
+ };
760
+ }
761
+ /**
762
+ * Decrypts a payload from a linked client and verifies that the decrypted plaintext was signed
763
+ * by that client. Counterpart to {@link signAndEncryptDataForLinkedClient}.
764
+ *
765
+ * Returns the decrypted `data` alongside `isValid` — the caller decides how to handle an invalid
766
+ * signature. (A tampered ciphertext fails earlier at AES-GCM decryption.)
767
+ */
768
+ async decryptAndVerifyDataFromLinkedClient({ dataToDecrypt, linkedClientId, signatureBase64 }) {
769
+ const data = await this.decryptDataFromLinkedClient({
770
+ dataToDecrypt,
771
+ linkedClientId
772
+ });
773
+ return {
774
+ data,
775
+ isValid: await this.verifyChallengeFromLinkedClient({
776
+ linkedClientId,
777
+ challenge: data,
778
+ signatureBase64
779
+ })
780
+ };
781
+ }
782
+ async signChallenge(challenge) {
783
+ if (challenge.length === 0) throw new Error("Challenge must contain at least one string");
784
+ const localVerifyKeyPair = await this.ensureLocalVerifyKeyPair();
785
+ const signature = challenge.length > 1 ? await signCombinedTextDataWithKeyEd25519(challenge, localVerifyKeyPair.privateKey) : await signTextDataWithKeyEd25519(challenge[0], localVerifyKeyPair.privateKey);
786
+ return { signatureBase64: base64.encode(signature) };
787
+ }
788
+ /**
789
+ * Verifies a signature over `challenge` against the linked client's verify (Ed25519) public key.
790
+ */
791
+ async verifyChallengeFromLinkedClient({ linkedClientId, challenge, signatureBase64 }) {
792
+ const linkedClient = this.getLinkedClient(linkedClientId);
793
+ if (linkedClient.verify?.publicKey == null) throw new Error(`ClientCryptoKeyLink: No verify public key set for ${linkedClientId}`);
794
+ return await verifyWithKeyEd25519({
795
+ challenge,
796
+ signatureBase64,
797
+ publicKey: linkedClient.verify.publicKey
798
+ });
799
+ }
800
+ };
801
+ //#endregion
802
+ //#region src/storage_adapter/storage_adapter.types.ts
803
+ let EStorageAdapterType = /* @__PURE__ */ function(EStorageAdapterType) {
804
+ EStorageAdapterType["string"] = "string";
805
+ EStorageAdapterType["json"] = "json";
806
+ return EStorageAdapterType;
807
+ }({});
808
+ //#endregion
809
+ //#region src/storage_adapter/StorageAdapter.ts
810
+ var StorageAdapter = class StorageAdapter {
811
+ implementation;
812
+ keyPrefix;
813
+ adapterStorage;
814
+ constructor({ methods, keyPrefix, trackKeysForClearing: trackKeys }) {
815
+ this.implementation = methods;
816
+ this.keyPrefix = keyPrefix ?? "";
817
+ const _trackKeys = trackKeys ?? true;
818
+ this.adapterStorage = _trackKeys ? createTypedStorage({ storageAdapter: new StorageAdapter({
819
+ methods,
820
+ keyPrefix,
821
+ trackKeysForClearing: false
822
+ }) }) : void 0;
823
+ }
824
+ getPrefixedKey(rawKey) {
825
+ return `${this.keyPrefix}${rawKey}`;
826
+ }
827
+ async trackUsedKey(rawKey) {
828
+ if (!this.adapterStorage) return;
829
+ await this.adapterStorage.updateJsonWithDef("__usedKeys__", [], (currentKeys) => {
830
+ if (!currentKeys.includes(rawKey)) return [...currentKeys, rawKey];
831
+ return currentKeys;
832
+ });
833
+ }
834
+ async untrackUsedKey(rawKey) {
835
+ if (!this.adapterStorage) return;
836
+ await this.adapterStorage.updateJsonWithDef("__usedKeys__", [], (currentKeys) => {
837
+ return currentKeys.filter((k) => k !== rawKey);
838
+ });
839
+ }
840
+ async clearAll() {
841
+ if (!this.adapterStorage) return;
842
+ const allKeys = await this.adapterStorage.getJsonOrDef("__usedKeys__", []) ?? [];
843
+ await Promise.all(allKeys.map(async (key) => {
844
+ await this.removeItem(key);
845
+ }));
846
+ await this.adapterStorage.setJson("__usedKeys__", []);
847
+ }
848
+ async removeItem(rawKey) {
849
+ await this.implementation.removeItem(this.getPrefixedKey(rawKey));
850
+ await this.untrackUsedKey(rawKey);
851
+ }
852
+ async setJson(rawKey, value) {
853
+ const key = this.getPrefixedKey(rawKey);
854
+ if (this.implementation.type === "string") await this.implementation.setItem(key, JSON.stringify(value));
855
+ else await this.implementation.setItem(key, value);
856
+ await this.trackUsedKey(rawKey);
857
+ }
858
+ async getJson(rawKey) {
859
+ const key = this.getPrefixedKey(rawKey);
860
+ if (this.implementation.type === "string") {
861
+ const val = await this.implementation.getItem(key);
862
+ if (val == null || val === "undefined" || val === "null") return;
863
+ return JSON.parse(val);
864
+ } else {
865
+ const val = await this.implementation.getItem(key);
866
+ if (val == null || val === "undefined" || val === "null") return;
867
+ return val;
868
+ }
869
+ }
870
+ async getJsonOrDef(rawKey, defVal) {
871
+ if (this.implementation.type === "string") {
872
+ const val = await this.implementation.getItem(this.getPrefixedKey(rawKey));
873
+ if (val == null || val === "undefined" || val === "null") return defVal;
874
+ return JSON.parse(val);
875
+ }
876
+ const val = await this.implementation.getItem(this.getPrefixedKey(rawKey));
877
+ if (val == null || val === "undefined" || val === "null") return defVal;
878
+ return val;
879
+ }
880
+ async updateJson(rawKey, updater) {
881
+ const newVal = updater(await this.getJson(rawKey));
882
+ await this.setJson(rawKey, newVal);
883
+ return newVal;
884
+ }
885
+ async updateJsonOrDef(rawKey, defVal, updater) {
886
+ const newVal = updater(await this.getJsonOrDef(rawKey, defVal));
887
+ await this.setJson(rawKey, newVal);
888
+ return newVal;
889
+ }
890
+ createJsonGetterSetter(rawKey) {
891
+ return {
892
+ get: () => this.getJson(rawKey),
893
+ set: (value) => this.setJson(rawKey, value)
894
+ };
895
+ }
896
+ };
897
+ //#endregion
898
+ //#region src/storage_adapter/specific/browser/browser_storage.ts
937
899
  function createWebLocalStorageMethods(_localStorage) {
938
- return {
939
- type: "string" /* string */,
940
- getItem: async (key) => _localStorage.getItem(key),
941
- setItem: async (key, value) => {
942
- _localStorage.setItem(key, value);
943
- },
944
- removeItem: async (key) => {
945
- _localStorage.removeItem(key);
946
- }
947
- };
900
+ return {
901
+ type: "string",
902
+ getItem: async (key) => _localStorage.getItem(key),
903
+ setItem: async (key, value) => {
904
+ _localStorage.setItem(key, value);
905
+ },
906
+ removeItem: async (key) => {
907
+ _localStorage.removeItem(key);
908
+ }
909
+ };
948
910
  }
949
- var createWebLocalStorageAdapter = ({
950
- localStorage: _localStorage,
951
- ...options
952
- }) => {
953
- return new StorageAdapter({
954
- methods: createWebLocalStorageMethods(_localStorage),
955
- ...options
956
- });
911
+ const createWebLocalStorageAdapter = ({ localStorage: _localStorage, ...options }) => {
912
+ return new StorageAdapter({
913
+ methods: createWebLocalStorageMethods(_localStorage),
914
+ ...options
915
+ });
957
916
  };
958
917
  function createTypedWebLocalStorage(options) {
959
- return createTypedStorage({
960
- storageAdapter: createWebLocalStorageAdapter(options)
961
- });
918
+ return createTypedStorage({ storageAdapter: createWebLocalStorageAdapter(options) });
962
919
  }
963
920
  function createWebSessionStorageMethods(_sessionStorage) {
964
- return {
965
- type: "string" /* string */,
966
- getItem: async (key) => _sessionStorage.getItem(key),
967
- setItem: async (key, value) => {
968
- _sessionStorage.setItem(key, value);
969
- },
970
- removeItem: async (key) => {
971
- _sessionStorage.removeItem(key);
972
- }
973
- };
921
+ return {
922
+ type: "string",
923
+ getItem: async (key) => _sessionStorage.getItem(key),
924
+ setItem: async (key, value) => {
925
+ _sessionStorage.setItem(key, value);
926
+ },
927
+ removeItem: async (key) => {
928
+ _sessionStorage.removeItem(key);
929
+ }
930
+ };
974
931
  }
975
- var createWebSessionStorageAdapter = ({
976
- sessionStorage: _sessionStorage,
977
- ...options
978
- }) => {
979
- return new StorageAdapter({
980
- methods: createWebSessionStorageMethods(_sessionStorage),
981
- ...options
982
- });
932
+ const createWebSessionStorageAdapter = ({ sessionStorage: _sessionStorage, ...options }) => {
933
+ return new StorageAdapter({
934
+ methods: createWebSessionStorageMethods(_sessionStorage),
935
+ ...options
936
+ });
983
937
  };
984
938
  function createTypedWebSessionStorage(options) {
985
- return createTypedStorage({
986
- storageAdapter: createWebSessionStorageAdapter(options)
987
- });
939
+ return createTypedStorage({ storageAdapter: createWebSessionStorageAdapter(options) });
988
940
  }
989
- // src/storage_adapter/specific/cloudflare/durable_object/durable_object_storage.ts
941
+ //#endregion
942
+ //#region src/storage_adapter/specific/cloudflare/durable_object/durable_object_storage.ts
990
943
  function createDurableObjectStorageMethods(durableObjectStorage) {
991
- return {
992
- type: "json" /* json */,
993
- getItem: (key) => durableObjectStorage.get(key),
994
- setItem: (key, value) => durableObjectStorage.put(key, value),
995
- removeItem: async (key) => {
996
- await durableObjectStorage.delete(key);
997
- }
998
- };
944
+ return {
945
+ type: "json",
946
+ getItem: (key) => durableObjectStorage.get(key),
947
+ setItem: (key, value) => durableObjectStorage.put(key, value),
948
+ removeItem: async (key) => {
949
+ await durableObjectStorage.delete(key);
950
+ }
951
+ };
999
952
  }
1000
- var createDurableObjectStorageAdapter = ({
1001
- durableObjectStorage,
1002
- ...options
1003
- }) => {
1004
- return new StorageAdapter({
1005
- methods: createDurableObjectStorageMethods(durableObjectStorage),
1006
- ...options
1007
- });
953
+ /**
954
+ * Wraps a Durable Object's storage in the generic StorageAdapter interface, e.g. for handing to a
955
+ * ClientCryptoKeyLink so it can persist its keys inside the DO's own storage.
956
+ */
957
+ const createDurableObjectStorageAdapter = ({ durableObjectStorage, ...options }) => {
958
+ return new StorageAdapter({
959
+ methods: createDurableObjectStorageMethods(durableObjectStorage),
960
+ ...options
961
+ });
1008
962
  };
1009
963
  function createDurableObjectTypedStorage(options) {
1010
- return createTypedStorage({
1011
- storageAdapter: createDurableObjectStorageAdapter(options)
1012
- });
964
+ return createTypedStorage({ storageAdapter: createDurableObjectStorageAdapter(options) });
1013
965
  }
1014
- // src/storage_adapter/specific/cloudflare/kv/kv_storage.ts
1015
- function createKVStorageMethods({
1016
- kvNamespace,
1017
- defaultPutOptions
1018
- }) {
1019
- return {
1020
- type: "string" /* string */,
1021
- getItem: (key) => kvNamespace.get(key),
1022
- setItem: (key, value) => kvNamespace.put(key, value, defaultPutOptions),
1023
- removeItem: (key) => kvNamespace.delete(key)
1024
- };
966
+ //#endregion
967
+ //#region src/storage_adapter/specific/cloudflare/kv/kv_storage.ts
968
+ function createKVStorageMethods({ kvNamespace, defaultPutOptions }) {
969
+ return {
970
+ type: "string",
971
+ getItem: (key) => kvNamespace.get(key),
972
+ setItem: (key, value) => kvNamespace.put(key, value, defaultPutOptions),
973
+ removeItem: (key) => kvNamespace.delete(key)
974
+ };
1025
975
  }
1026
- var createKVStorageAdapter = ({
1027
- kvNamespace,
1028
- defaultPutOptions,
1029
- ...options
1030
- }) => {
1031
- return new StorageAdapter({
1032
- methods: createKVStorageMethods({ kvNamespace, defaultPutOptions }),
1033
- ...options
1034
- });
976
+ /**
977
+ * Wraps a Cloudflare KV namespace binding in the generic StorageAdapter interface, e.g. for handing
978
+ * to a ClientCryptoKeyLink so it can persist its keys inside KV.
979
+ */
980
+ const createKVStorageAdapter = ({ kvNamespace, defaultPutOptions, ...options }) => {
981
+ return new StorageAdapter({
982
+ methods: createKVStorageMethods({
983
+ kvNamespace,
984
+ defaultPutOptions
985
+ }),
986
+ ...options
987
+ });
1035
988
  };
1036
989
  function createKVTypedStorage(options) {
1037
- return createTypedStorage({
1038
- storageAdapter: createKVStorageAdapter(options)
1039
- });
990
+ return createTypedStorage({ storageAdapter: createKVStorageAdapter(options) });
1040
991
  }
1041
- // src/storage_adapter/specific/memory/memory_storage.ts
1042
- function createMemoryStorageMethods_string(memoryStorageMap = new Map) {
1043
- return {
1044
- type: "string" /* string */,
1045
- getItem: async (key) => memoryStorageMap.get(key) ?? null,
1046
- setItem: async (key, value) => {
1047
- memoryStorageMap.set(key, value);
1048
- },
1049
- removeItem: async (key) => {
1050
- memoryStorageMap.delete(key);
1051
- }
1052
- };
992
+ //#endregion
993
+ //#region src/storage_adapter/specific/memory/memory_storage.ts
994
+ function createMemoryStorageMethods_string(memoryStorageMap = /* @__PURE__ */ new Map()) {
995
+ return {
996
+ type: "string",
997
+ getItem: async (key) => memoryStorageMap.get(key) ?? null,
998
+ setItem: async (key, value) => {
999
+ memoryStorageMap.set(key, value);
1000
+ },
1001
+ removeItem: async (key) => {
1002
+ memoryStorageMap.delete(key);
1003
+ }
1004
+ };
1053
1005
  }
1054
- var createMemoryStorageAdapter_string = (options) => {
1055
- return new StorageAdapter({
1056
- methods: createMemoryStorageMethods_string(options?.memoryStorageMap),
1057
- ...options
1058
- });
1006
+ const createMemoryStorageAdapter_string = (options) => {
1007
+ return new StorageAdapter({
1008
+ methods: createMemoryStorageMethods_string(options?.memoryStorageMap),
1009
+ ...options
1010
+ });
1059
1011
  };
1060
1012
  function createTypedMemoryStorage_string(options) {
1061
- return createTypedStorage({
1062
- storageAdapter: createMemoryStorageAdapter_string(options)
1063
- });
1013
+ return createTypedStorage({ storageAdapter: createMemoryStorageAdapter_string(options) });
1064
1014
  }
1065
- function createMemoryStorageMethods_json(memoryStorageMap = new Map) {
1066
- return {
1067
- type: "json" /* json */,
1068
- getItem: async (key) => memoryStorageMap.get(key),
1069
- setItem: async (key, value) => {
1070
- memoryStorageMap.set(key, value);
1071
- },
1072
- removeItem: async (key) => {
1073
- memoryStorageMap.delete(key);
1074
- }
1075
- };
1015
+ function createMemoryStorageMethods_json(memoryStorageMap = /* @__PURE__ */ new Map()) {
1016
+ return {
1017
+ type: "json",
1018
+ getItem: async (key) => memoryStorageMap.get(key),
1019
+ setItem: async (key, value) => {
1020
+ memoryStorageMap.set(key, value);
1021
+ },
1022
+ removeItem: async (key) => {
1023
+ memoryStorageMap.delete(key);
1024
+ }
1025
+ };
1076
1026
  }
1077
- var createMemoryStorageAdapter_json = (options) => {
1078
- return new StorageAdapter({
1079
- methods: createMemoryStorageMethods_json(options?.memoryStorageMap),
1080
- ...options
1081
- });
1027
+ const createMemoryStorageAdapter_json = (options) => {
1028
+ return new StorageAdapter({
1029
+ methods: createMemoryStorageMethods_json(options?.memoryStorageMap),
1030
+ ...options
1031
+ });
1082
1032
  };
1083
1033
  function createTypedMemoryStorage_json(options) {
1084
- return createTypedStorage({
1085
- storageAdapter: createMemoryStorageAdapter_json(options)
1086
- });
1034
+ return createTypedStorage({ storageAdapter: createMemoryStorageAdapter_json(options) });
1087
1035
  }
1088
- export {
1089
- verifyWithKeyEd25519,
1090
- vVerifyChallengeWithSignature_WithThrow_Input,
1091
- vVerifyChallengeWithSignature_Input,
1092
- vSerializedCryptoKeyDataX25519_Raw,
1093
- vSerializedCryptoKeyDataX25519_Jwk,
1094
- vSerializedCryptoKeyDataEd25519_Raw,
1095
- vSerializedCryptoKeyDataEd25519_Jwk,
1096
- vEncryptedAesGcmPayload,
1097
- vCryptoKeyPairDataX25519,
1098
- vCryptoKeyPairDataEd25519,
1099
- signTextDataWithKeyEd25519,
1100
- signCombinedTextDataWithKeyEd25519,
1101
- serializeX25519Key_Raw,
1102
- serializeX25519Key_Jwk,
1103
- serializeEd25519Key_Raw,
1104
- serializeEd25519Key_Jwk,
1105
- importX25519Key,
1106
- importEd25519Key,
1107
- generateX25519KeyPair,
1108
- generateEd25519KeyPair,
1109
- encryptTextDataWithAesGcmKey,
1110
- encryptBytesWithAesGcmKey,
1111
- decryptTextDataWithAesGcmKey,
1112
- decryptBytesWithAesGcmKey,
1113
- createWebSessionStorageMethods,
1114
- createWebSessionStorageAdapter,
1115
- createWebLocalStorageMethods,
1116
- createWebLocalStorageAdapter,
1117
- createTypedWebSessionStorage,
1118
- createTypedWebLocalStorage,
1119
- createTypedStorage,
1120
- createTypedMemoryStorage_string,
1121
- createTypedMemoryStorage_json,
1122
- createSharedBitsFromX25519,
1123
- createMemoryStorageMethods_string,
1124
- createMemoryStorageMethods_json,
1125
- createMemoryStorageAdapter_string,
1126
- createMemoryStorageAdapter_json,
1127
- createKVTypedStorage,
1128
- createKVStorageMethods,
1129
- createKVStorageAdapter,
1130
- createDurableObjectTypedStorage,
1131
- createDurableObjectStorageMethods,
1132
- createDurableObjectStorageAdapter,
1133
- createAesGcmKeyFromX25519Keys,
1134
- convertX25519RawDataStringToSerializedKeyData,
1135
- convertX25519RawDataStringToObject,
1136
- convertX25519JwkDataStringToSerializedKeyData,
1137
- convertX25519JwkDataStringToObject,
1138
- convertX25519FormattedStringToSerializedKeyData,
1139
- convertX25519FormattedStringToObject,
1140
- convertEd25519RawDataStringToSerializedKeyData,
1141
- convertEd25519RawDataStringToObject,
1142
- convertEd25519JwkDataStringToSerializedKeyData,
1143
- convertEd25519JwkDataStringToObject,
1144
- convertEd25519FormattedStringToSerializedKeyData,
1145
- convertEd25519FormattedStringToObject,
1146
- buildVerifyKeyBoundInfoString,
1147
- StorageAdapter,
1148
- EStorageAdapterType,
1149
- ECryptoKeyFormat,
1150
- ECryptoKeyAlgo,
1151
- DEFAULT_COMBINED_TEXT_DATA_SEPARATOR,
1152
- ClientCryptoKeyLink
1153
- };
1036
+ //#endregion
1037
+ export { ClientCryptoKeyLink, DEFAULT_COMBINED_TEXT_DATA_SEPARATOR, ECryptoKeyAlgo, ECryptoKeyFormat, EStorageAdapterType, StorageAdapter, buildVerifyKeyBoundInfoString, convertEd25519FormattedStringToObject, convertEd25519FormattedStringToSerializedKeyData, convertEd25519JwkDataStringToObject, convertEd25519JwkDataStringToSerializedKeyData, convertEd25519RawDataStringToObject, convertEd25519RawDataStringToSerializedKeyData, convertX25519FormattedStringToObject, convertX25519FormattedStringToSerializedKeyData, convertX25519JwkDataStringToObject, convertX25519JwkDataStringToSerializedKeyData, convertX25519RawDataStringToObject, convertX25519RawDataStringToSerializedKeyData, createAesGcmKeyFromX25519Keys, createDurableObjectStorageAdapter, createDurableObjectStorageMethods, createDurableObjectTypedStorage, createKVStorageAdapter, createKVStorageMethods, createKVTypedStorage, createMemoryStorageAdapter_json, createMemoryStorageAdapter_string, createMemoryStorageMethods_json, createMemoryStorageMethods_string, createSharedBitsFromX25519, createTypedMemoryStorage_json, createTypedMemoryStorage_string, createTypedStorage, createTypedWebLocalStorage, createTypedWebSessionStorage, createWebLocalStorageAdapter, createWebLocalStorageMethods, createWebSessionStorageAdapter, createWebSessionStorageMethods, decryptBytesWithAesGcmKey, decryptTextDataWithAesGcmKey, encryptBytesWithAesGcmKey, encryptTextDataWithAesGcmKey, generateEd25519KeyPair, generateX25519KeyPair, importEd25519Key, importX25519Key, serializeEd25519Key_Jwk, serializeEd25519Key_Raw, serializeX25519Key_Jwk, serializeX25519Key_Raw, signCombinedTextDataWithKeyEd25519, signTextDataWithKeyEd25519, vCryptoKeyPairDataEd25519, vCryptoKeyPairDataX25519, vEncryptedAesGcmPayload, vSerializedCryptoKeyDataEd25519_Jwk, vSerializedCryptoKeyDataEd25519_Raw, vSerializedCryptoKeyDataX25519_Jwk, vSerializedCryptoKeyDataX25519_Raw, vVerifyChallengeWithSignature_Input, vVerifyChallengeWithSignature_WithThrow_Input, verifyWithKeyEd25519 };
1038
+
1039
+ //# sourceMappingURL=index.js.map