web-dc-api 0.1.4 → 0.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (148) hide show
  1. package/dist/cjs/index.js +1 -1
  2. package/dist/dc.min.js +1 -1
  3. package/dist/esm/index.js +1 -1
  4. package/dist/index.d.ts +934 -878
  5. package/package.json +4 -8
  6. package/dist/cjs/helia-core-B1Xqha7a.js +0 -1
  7. package/dist/cjs/helia-core-D8Uv1KjQ.js +0 -1
  8. package/dist/cjs/polkadot-api-7PhQf3ws.js +0 -1
  9. package/dist/cjs/polkadot-api-CtrJVWuZ.js +0 -1
  10. package/dist/esm/chunks/helia-core-BxMqyK2Y.js +0 -1
  11. package/dist/esm/chunks/helia-core-DMXRpcO-.js +0 -1
  12. package/dist/esm/chunks/polkadot-api-5Y9Bw8VT.js +0 -1
  13. package/dist/esm/chunks/polkadot-api-D69Ioun_.js +0 -1
  14. package/lib/common/blowfish/block.ts +0 -259
  15. package/lib/common/blowfish/cipher.ts +0 -144
  16. package/lib/common/blowfish/const.ts +0 -195
  17. package/lib/common/chain.ts +0 -469
  18. package/lib/common/commonclient.ts +0 -202
  19. package/lib/common/constants.ts +0 -55
  20. package/lib/common/dc-key/ed25519.ts +0 -343
  21. package/lib/common/dc-key/keyManager.ts +0 -424
  22. package/lib/common/dcapi.ts +0 -98
  23. package/lib/common/dcutil.ts +0 -627
  24. package/lib/common/define.ts +0 -70
  25. package/lib/common/error.ts +0 -67
  26. package/lib/common/grpc-dc.ts +0 -104
  27. package/lib/common/module-system.ts +0 -184
  28. package/lib/common/service-worker.ts +0 -234
  29. package/lib/common/types/types.ts +0 -344
  30. package/lib/dc.ts +0 -701
  31. package/lib/implements/account/client.ts +0 -185
  32. package/lib/implements/account/manager.ts +0 -683
  33. package/lib/implements/aiproxy/client.ts +0 -357
  34. package/lib/implements/aiproxy/manager.ts +0 -670
  35. package/lib/implements/cache/client.ts +0 -105
  36. package/lib/implements/cache/manager.ts +0 -127
  37. package/lib/implements/comment/client.ts +0 -982
  38. package/lib/implements/comment/manager.ts +0 -1151
  39. package/lib/implements/dc/client.ts +0 -51
  40. package/lib/implements/dc/manager.ts +0 -33
  41. package/lib/implements/file/client.ts +0 -253
  42. package/lib/implements/file/file-cache-manager.ts +0 -142
  43. package/lib/implements/file/manager.ts +0 -1240
  44. package/lib/implements/file/seekableFileStream.ts +0 -344
  45. package/lib/implements/file/streamwriter.ts +0 -322
  46. package/lib/implements/keyvalue/client.ts +0 -376
  47. package/lib/implements/keyvalue/manager.ts +0 -759
  48. package/lib/implements/message/client.ts +0 -250
  49. package/lib/implements/message/manager.ts +0 -215
  50. package/lib/implements/threaddb/cbor/coding.ts +0 -62
  51. package/lib/implements/threaddb/cbor/event.ts +0 -336
  52. package/lib/implements/threaddb/cbor/node.ts +0 -542
  53. package/lib/implements/threaddb/cbor/record.ts +0 -398
  54. package/lib/implements/threaddb/common/AsyncMutex.ts +0 -24
  55. package/lib/implements/threaddb/common/addrinfo.ts +0 -135
  56. package/lib/implements/threaddb/common/dispatcher.ts +0 -81
  57. package/lib/implements/threaddb/common/idbstore-adapter.ts +0 -260
  58. package/lib/implements/threaddb/common/json-patcher.ts +0 -204
  59. package/lib/implements/threaddb/common/key.ts +0 -290
  60. package/lib/implements/threaddb/common/level-adapter.ts +0 -235
  61. package/lib/implements/threaddb/common/lineReader.ts +0 -79
  62. package/lib/implements/threaddb/common/logstore.ts +0 -215
  63. package/lib/implements/threaddb/common/transformed-datastore.ts +0 -308
  64. package/lib/implements/threaddb/core/app.ts +0 -206
  65. package/lib/implements/threaddb/core/core.ts +0 -230
  66. package/lib/implements/threaddb/core/db.ts +0 -249
  67. package/lib/implements/threaddb/core/event.ts +0 -54
  68. package/lib/implements/threaddb/core/head.ts +0 -89
  69. package/lib/implements/threaddb/core/identity.ts +0 -171
  70. package/lib/implements/threaddb/core/logstore.ts +0 -137
  71. package/lib/implements/threaddb/core/options.ts +0 -14
  72. package/lib/implements/threaddb/core/record.ts +0 -54
  73. package/lib/implements/threaddb/db/collection.ts +0 -1910
  74. package/lib/implements/threaddb/db/db.ts +0 -698
  75. package/lib/implements/threaddb/db/json2Query.ts +0 -192
  76. package/lib/implements/threaddb/db/query.ts +0 -524
  77. package/lib/implements/threaddb/dbclient.ts +0 -543
  78. package/lib/implements/threaddb/dbmanager.ts +0 -1906
  79. package/lib/implements/threaddb/lsstoreds/addr_book.ts +0 -549
  80. package/lib/implements/threaddb/lsstoreds/cache.ts +0 -36
  81. package/lib/implements/threaddb/lsstoreds/cyclic_batch.ts +0 -87
  82. package/lib/implements/threaddb/lsstoreds/global.ts +0 -151
  83. package/lib/implements/threaddb/lsstoreds/headbook.ts +0 -373
  84. package/lib/implements/threaddb/lsstoreds/keybook.ts +0 -297
  85. package/lib/implements/threaddb/lsstoreds/logstore.ts +0 -29
  86. package/lib/implements/threaddb/lsstoreds/metadata.ts +0 -223
  87. package/lib/implements/threaddb/net/define.ts +0 -149
  88. package/lib/implements/threaddb/net/grpcClient.ts +0 -589
  89. package/lib/implements/threaddb/net/grpcserver.ts +0 -146
  90. package/lib/implements/threaddb/net/net.ts +0 -2047
  91. package/lib/implements/threaddb/pb/lstore.proto +0 -38
  92. package/lib/implements/threaddb/pb/lstore.ts +0 -393
  93. package/lib/implements/threaddb/pb/lstore_pb.d.ts +0 -433
  94. package/lib/implements/threaddb/pb/lstore_pb.js +0 -1085
  95. package/lib/implements/threaddb/pb/net.proto +0 -194
  96. package/lib/implements/threaddb/pb/net_pb.d.ts +0 -2349
  97. package/lib/implements/threaddb/pb/net_pb.js +0 -5525
  98. package/lib/implements/threaddb/pb/proto-custom-types.ts +0 -212
  99. package/lib/implements/util/client.ts +0 -72
  100. package/lib/implements/util/manager.ts +0 -146
  101. package/lib/implements/wallet/manager.ts +0 -671
  102. package/lib/index.ts +0 -57
  103. package/lib/interfaces/DCContext.ts +0 -51
  104. package/lib/interfaces/aiproxy-interface.ts +0 -145
  105. package/lib/interfaces/auth-interface.ts +0 -118
  106. package/lib/interfaces/cache-interface.ts +0 -22
  107. package/lib/interfaces/client-interface.ts +0 -11
  108. package/lib/interfaces/comment-interface.ts +0 -167
  109. package/lib/interfaces/components/news-component.ts +0 -0
  110. package/lib/interfaces/database-interface.ts +0 -169
  111. package/lib/interfaces/file-interface.ts +0 -120
  112. package/lib/interfaces/index.ts +0 -10
  113. package/lib/interfaces/keyvalue-interface.ts +0 -156
  114. package/lib/interfaces/message-interface.ts +0 -22
  115. package/lib/interfaces/util-interface.ts +0 -31
  116. package/lib/modules/aiproxy-module.ts +0 -246
  117. package/lib/modules/auth-module.ts +0 -753
  118. package/lib/modules/cache-module.ts +0 -99
  119. package/lib/modules/client-module.ts +0 -71
  120. package/lib/modules/comment-module.ts +0 -429
  121. package/lib/modules/components/news-components.ts +0 -390
  122. package/lib/modules/database-module.ts +0 -598
  123. package/lib/modules/file-module.ts +0 -291
  124. package/lib/modules/index.ts +0 -13
  125. package/lib/modules/keyvalue-module.ts +0 -379
  126. package/lib/modules/message-module.ts +0 -107
  127. package/lib/modules/util-module.ts +0 -148
  128. package/lib/polyfills/process-env-browser.ts +0 -1
  129. package/lib/proto/datasource.ts +0 -93
  130. package/lib/proto/dcnet.proto +0 -1601
  131. package/lib/proto/dcnet_proto.d.ts +0 -22857
  132. package/lib/proto/dcnet_proto.js +0 -55204
  133. package/lib/proto/dcnet_proto_sparse.js +0 -55166
  134. package/lib/proto/oidfetch.proto +0 -25
  135. package/lib/proto/oidfetch_proto.d.ts +0 -585
  136. package/lib/proto/oidfetch_proto.js +0 -1247
  137. package/lib/serverless/babel-browser.ts +0 -39
  138. package/lib/serverless/base_entity.ts +0 -78
  139. package/lib/serverless/base_repository.ts +0 -414
  140. package/lib/serverless/browser_schema_extractor.ts +0 -283
  141. package/lib/serverless/decorator_factory.ts +0 -322
  142. package/lib/util/BrowserLineReader.ts +0 -73
  143. package/lib/util/base64.ts +0 -105
  144. package/lib/util/bcrypt.ts +0 -206
  145. package/lib/util/curve25519Encryption.ts +0 -418
  146. package/lib/util/dccrypt.ts +0 -73
  147. package/lib/util/logger.ts +0 -104
  148. package/lib/util/utils.ts +0 -289
@@ -1,418 +0,0 @@
1
-
2
- import { randomBytes } from '@stablelib/random';
3
- import { box } from 'tweetnacl';
4
- import { BigInteger } from 'jsbn';
5
- // import { webcrypto } from 'crypto';
6
-
7
- export class Encryption {
8
- private static readonly NONCE_LENGTH = 24;
9
- private static readonly PUBLIC_KEY_LENGTH = 32;
10
- private static readonly MAC_LENGTH = 16;
11
-
12
- // Curve25519的素数
13
- private static readonly CURVE25519_P = new BigInteger("57896044618658097711785492504343953926634992332820282019728792003956564819949");
14
-
15
- private static toHex(bytes: Uint8Array): string {
16
- return Array.from(bytes)
17
- .map(b => b.toString(16).padStart(2, '0'))
18
- .join('');
19
- }
20
-
21
- // 将字节数组转换为BigInteger
22
- private static bytesToBigInt(bytes: Uint8Array): BigInteger {
23
- let hex = Array.from(bytes)
24
- .map(b => b.toString(16).padStart(2, '0'))
25
- .join('');
26
- return new BigInteger(hex, 16);
27
- }
28
-
29
- // 将BigInteger转换为固定长度的字节数组
30
- private static bigIntToBytes(bn: BigInteger, length: number): Uint8Array {
31
- const hex = bn.toString(16).padStart(length * 2, '0');
32
- const bytes = new Uint8Array(length);
33
- for (let i = 0; i < length; i++) {
34
- bytes[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
35
- }
36
- return bytes;
37
- }
38
-
39
-
40
- // 扩展欧几里得算法计算模逆
41
- private static extendedEuclidean(a: BigInteger, b: BigInteger): [BigInteger, BigInteger, BigInteger] {
42
- if (b.equals(BigInteger.ZERO)) {
43
- return [a, new BigInteger("1"), new BigInteger("0")];
44
- }
45
-
46
- const [gcd, x1, y1] = this.extendedEuclidean(b, a.mod(b));
47
- const x = y1;
48
- const y = x1.subtract(a.divide(b).multiply(y1));
49
- return [gcd, x, y];
50
- }
51
-
52
- // 安全的模逆计算
53
- private static safeModInverse(a: BigInteger, m: BigInteger): BigInteger {
54
- // 确保a为正数
55
- let positiveA = a.mod(m);
56
- if (positiveA.compareTo(BigInteger.ZERO) < 0) {
57
- positiveA = positiveA.add(m);
58
- }
59
-
60
- // 计算GCD和模逆
61
- const [gcd, x] = this.extendedEuclidean(positiveA, m);
62
-
63
- // 检查是否存在模逆
64
- if (!gcd.equals(new BigInteger("1"))) {
65
- throw new Error('Modular inverse does not exist');
66
- }
67
-
68
- // 确保结果为正数
69
- let result = x.mod(m);
70
- if (result.compareTo(BigInteger.ZERO) < 0) {
71
- result = result.add(m);
72
- }
73
- return result;
74
- }
75
-
76
- // 修改转换函数中的模逆计算
77
- private static ed25519PublicKeyToCurve25519(publicKey: Uint8Array): Uint8Array {
78
-
79
- // 1. 转换为big endian
80
- const bigEndianY = new Uint8Array(32);
81
- for (let i = 0; i < 32; i++) {
82
- bigEndianY[31 - i] = publicKey[i];
83
- }
84
-
85
- // 2. 清除最高位
86
- bigEndianY[0] &= 0b0111_1111;
87
-
88
- // 3. 转换为BigInteger并计算 u = (1 + y) / (1 - y)
89
- const y = this.bytesToBigInt(bigEndianY);
90
- const one = new BigInteger("1");
91
-
92
- // 计算分子 (1 + y)
93
- const numerator = one.add(y);
94
-
95
- // 计算分母 (1 - y)
96
- const denominator = one.subtract(y);
97
-
98
- try {
99
- // 使用新的安全模逆计算
100
- const denominatorInv = this.safeModInverse(denominator, this.CURVE25519_P);
101
-
102
- // 计算 u
103
- let u = numerator.multiply(denominatorInv).mod(this.CURVE25519_P);
104
-
105
- // 4. 转换回little endian
106
- const result = this.bigIntToBytes(u, 32);
107
- const littleEndianResult = new Uint8Array(32);
108
- for (let i = 0; i < 32; i++) {
109
- littleEndianResult[i] = result[31 - i];
110
- }
111
-
112
- return littleEndianResult;
113
-
114
- } catch (error) {
115
- console.error('Error during conversion:', error);
116
- throw error;
117
- }
118
- }
119
-
120
-
121
- static async encrypt(recipientPublicKey: Uint8Array, message: Uint8Array): Promise<Uint8Array> {
122
- try {
123
- if (recipientPublicKey.length !== this.PUBLIC_KEY_LENGTH) {
124
- throw new Error(`Invalid public key length: ${recipientPublicKey.length}`);
125
- }
126
-
127
- const curve25519PublicKey = Encryption.ed25519PublicKeyToCurve25519(recipientPublicKey) //ed25519.getPublicKey(recipientPublicKey);
128
- const ephemeralKeyPair = box.keyPair();
129
- const nonce = randomBytes(this.NONCE_LENGTH);
130
-
131
- const encrypted = box(
132
- message,
133
- nonce,
134
- curve25519PublicKey,
135
- ephemeralKeyPair.secretKey
136
- );
137
-
138
- if (!encrypted) {
139
- throw new Error('Encryption failed');
140
- }
141
-
142
- const result = new Uint8Array(
143
- this.NONCE_LENGTH +
144
- this.PUBLIC_KEY_LENGTH +
145
- encrypted.length
146
- );
147
-
148
- let offset = 0;
149
- result.set(nonce, offset);
150
- offset += this.NONCE_LENGTH;
151
- result.set(ephemeralKeyPair.publicKey, offset);
152
- offset += this.PUBLIC_KEY_LENGTH;
153
- result.set(encrypted, offset);
154
-
155
- return result;
156
-
157
- } catch (error: any) {
158
- throw new Error(`Encryption failed: ${error.message}`);
159
- }
160
- }
161
-
162
- static async encryptWithDebug(recipientPublicKey: Uint8Array, message: Uint8Array): Promise<Uint8Array> {
163
- try {
164
- console.log('\n=== Encryption Debug Information ===');
165
- console.log('Input Data:');
166
- console.log('- Message:', new TextDecoder().decode(message));
167
- console.log('- Message (hex):', this.toHex(message));
168
- console.log('- Recipient Public Key:', this.toHex(recipientPublicKey));
169
-
170
- if (recipientPublicKey.length !== this.PUBLIC_KEY_LENGTH) {
171
- throw new Error(`Invalid public key length: ${recipientPublicKey.length}`);
172
- }
173
-
174
- const curve25519PublicKey = Encryption.ed25519PublicKeyToCurve25519(recipientPublicKey);
175
- console.log('\nKey Conversion:');
176
- console.log('- Ed25519 Public Key:', this.toHex(recipientPublicKey));
177
- console.log('- Curve25519 Public Key:', this.toHex(curve25519PublicKey));
178
-
179
- const ephemeralKeyPair = box.keyPair();
180
- console.log('\nEphemeral Key Pair:');
181
- console.log('- Public Key:', this.toHex(ephemeralKeyPair.publicKey));
182
- console.log('- Secret Key:', this.toHex(ephemeralKeyPair.secretKey));
183
-
184
- const nonce = randomBytes(this.NONCE_LENGTH);
185
- console.log('\nNonce:');
186
- console.log('- Value:', this.toHex(nonce));
187
- console.log('- Length:', nonce.length);
188
-
189
- const encrypted = box(
190
- message,
191
- nonce,
192
- curve25519PublicKey,
193
- ephemeralKeyPair.secretKey
194
- );
195
-
196
- if (!encrypted) {
197
- throw new Error('Encryption failed');
198
- }
199
-
200
- console.log('\nEncrypted Data:');
201
- console.log('- Length:', encrypted.length);
202
- console.log('- Value:', this.toHex(encrypted));
203
-
204
- const result = new Uint8Array(
205
- this.NONCE_LENGTH +
206
- this.PUBLIC_KEY_LENGTH +
207
- encrypted.length
208
- );
209
-
210
- let offset = 0;
211
- result.set(nonce, offset);
212
- offset += this.NONCE_LENGTH;
213
- result.set(ephemeralKeyPair.publicKey, offset);
214
- offset += this.PUBLIC_KEY_LENGTH;
215
- result.set(encrypted, offset);
216
-
217
- console.log('\nFinal Result:');
218
- console.log('- Total Length:', result.length);
219
- console.log('- Structure:');
220
- console.log(` * Nonce (${this.NONCE_LENGTH} bytes):`,
221
- this.toHex(result.slice(0, this.NONCE_LENGTH)));
222
- console.log(` * Ephemeral Public Key (${this.PUBLIC_KEY_LENGTH} bytes):`,
223
- this.toHex(result.slice(this.NONCE_LENGTH, this.NONCE_LENGTH + this.PUBLIC_KEY_LENGTH)));
224
- console.log(` * Encrypted Data (${encrypted.length} bytes):`,
225
- this.toHex(result.slice(this.NONCE_LENGTH + this.PUBLIC_KEY_LENGTH)));
226
- console.log('- Complete Data:', this.toHex(result));
227
-
228
- return result;
229
-
230
- } catch (error: any) {
231
- console.error('Encryption Debug Error:', error);
232
- throw error;
233
- }
234
- }
235
-
236
- //使用 Web Crypto API 实现 SHA-512
237
- private static async sha512Hash(data: Uint8Array): Promise<Uint8Array> {
238
- try {
239
- // 优先使用 Web Crypto API
240
- if (typeof window !== 'undefined' && window.crypto) {
241
- const buffer = await window.crypto.subtle.digest('SHA-512', data);
242
- return new Uint8Array(buffer);
243
- }
244
- // // Node.js 环境
245
- // else if (typeof webcrypto !== 'undefined') {
246
- // const buffer = await webcrypto.subtle.digest('SHA-512', data);
247
- // return new Uint8Array(buffer);
248
- // }
249
- throw new Error('No crypto implementation available');
250
- } catch (error) {
251
- console.error('SHA-512 hash failed:', error);
252
- throw error;
253
- }
254
- }
255
-
256
-
257
- private static async ed25519PrivateKeyToCurve25519(privateKey: Uint8Array): Promise<Uint8Array> {
258
-
259
- // 使用新的 SHA-512 实现
260
- const h = await this.sha512Hash(privateKey.slice(0, 32));
261
-
262
-
263
- // 清除特定位
264
- const result = new Uint8Array(h);
265
- result[0] &= 248; // Clear bits 0,1,2
266
- result[31] &= 127; // Clear bit 7
267
- result[31] |= 64; // Set bit 6
268
-
269
- // 只使用前32字节
270
- const curve25519PrivateKey = result.slice(0, 32);
271
-
272
- return curve25519PrivateKey;
273
- }
274
-
275
-
276
- static async decrypt(
277
- recipientPrivateKey: Uint8Array,
278
- encryptedData: Uint8Array,
279
- debug: boolean = false
280
- ): Promise<Uint8Array> {
281
- try {
282
- if (debug) {
283
- console.log('\n=== Starting Decryption Process ===');
284
- console.log('Input Private Key:', this.toHex(recipientPrivateKey));
285
- console.log('Encrypted Data Length:', encryptedData.length);
286
- console.log('Encrypted Data:', this.toHex(encryptedData));
287
- }
288
-
289
- // 验证输入数据长度
290
- const minLength = this.NONCE_LENGTH + this.PUBLIC_KEY_LENGTH + this.MAC_LENGTH;
291
- if (encryptedData.length < minLength) {
292
- throw new Error(
293
- `Invalid encrypted data length: ${encryptedData.length} < ${minLength}`
294
- );
295
- }
296
-
297
- // 解析加密数据的各个部分
298
- const nonce = encryptedData.slice(0, this.NONCE_LENGTH);
299
- const ephemeralPublicKey = encryptedData.slice(
300
- this.NONCE_LENGTH,
301
- this.NONCE_LENGTH + this.PUBLIC_KEY_LENGTH
302
- );
303
- const ciphertext = encryptedData.slice(
304
- this.NONCE_LENGTH + this.PUBLIC_KEY_LENGTH
305
- );
306
-
307
- if (debug) {
308
- console.log('\n--- Parsed Components ---');
309
- console.log('Nonce:', this.toHex(nonce));
310
- console.log('Ephemeral Public Key:', this.toHex(ephemeralPublicKey));
311
- console.log('Ciphertext:', this.toHex(ciphertext));
312
- }
313
-
314
- // 转换私钥(现在是异步的)
315
- const curve25519PrivateKey = await this.ed25519PrivateKeyToCurve25519(recipientPrivateKey);
316
-
317
- if (debug) {
318
- console.log('\n--- Key Conversion ---');
319
- console.log('Original Ed25519 Private Key:', this.toHex(recipientPrivateKey));
320
- console.log('Converted Curve25519 Private Key:', this.toHex(curve25519PrivateKey));
321
- }
322
-
323
- // 计算共享密钥
324
- const sharedKey = box.before(ephemeralPublicKey, curve25519PrivateKey);
325
- if (!sharedKey) {
326
- throw new Error('Failed to compute shared key');
327
- }
328
-
329
- if (debug) {
330
- console.log('\n--- Shared Key Computation ---');
331
- console.log('Computed Shared Key:', this.toHex(sharedKey));
332
- }
333
-
334
- // 解密数据
335
- const decrypted = box.open.after(ciphertext, nonce, sharedKey);
336
- if (!decrypted) {
337
- throw new Error('Decryption failed - invalid MAC');
338
- }
339
-
340
- if (debug) {
341
- console.log('\n--- Decryption Result ---');
342
- console.log('Decrypted Data Length:', decrypted.length);
343
- console.log('Decrypted Data:', this.toHex(decrypted));
344
- try {
345
- console.log('Decrypted Text:', new TextDecoder().decode(decrypted));
346
- } catch (e) {
347
- console.log('(Binary data - could not decode as text)');
348
- }
349
- }
350
-
351
- return decrypted;
352
-
353
- } catch (error: any) {
354
- console.error('Decryption error:', error);
355
- throw new Error(`Decryption failed: ${error.message}`);
356
- }
357
- }
358
-
359
- // 新增:解密调试辅助方法
360
- static async debugDecryptionProcess(
361
- recipientPrivateKey: Uint8Array,
362
- encryptedData: Uint8Array
363
- ): Promise<void> {
364
- console.log('\n======= Decryption Debug Process =======');
365
-
366
- // 1. 输入验证
367
- console.log('\n=== Input Validation ===');
368
- console.log('Private Key Length:', recipientPrivateKey.length);
369
- console.log('Encrypted Data Length:', encryptedData.length);
370
-
371
- // 2. 数据结构分析
372
- const structure = {
373
- nonce: encryptedData.slice(0, this.NONCE_LENGTH),
374
- ephemeralPublicKey: encryptedData.slice(
375
- this.NONCE_LENGTH,
376
- this.NONCE_LENGTH + this.PUBLIC_KEY_LENGTH
377
- ),
378
- ciphertext: encryptedData.slice(
379
- this.NONCE_LENGTH + this.PUBLIC_KEY_LENGTH
380
- )
381
- };
382
-
383
- console.log('\n=== Data Structure Analysis ===');
384
- Object.entries(structure).forEach(([key, value]) => {
385
- console.log(`${key}:`);
386
- console.log(` Length: ${value.length}`);
387
- console.log(` Hex: ${this.toHex(value)}`);
388
- });
389
-
390
- // 3. 私钥转换过程
391
- console.log('\n=== Private Key Conversion ===');
392
- try {
393
- const curve25519PrivateKey = await this.ed25519PrivateKeyToCurve25519(recipientPrivateKey);
394
- console.log('Conversion successful');
395
- console.log('Converted Key:', this.toHex(curve25519PrivateKey));
396
- } catch (error) {
397
- console.error('Private key conversion failed:', error);
398
- return;
399
- }
400
-
401
- // 4. 尝试解密
402
- console.log('\n=== Attempting Decryption ===');
403
- try {
404
- const decrypted = await this.decrypt(recipientPrivateKey, encryptedData, false);
405
- console.log('Decryption successful');
406
- console.log('Decrypted length:', decrypted.length);
407
- console.log('Decrypted hex:', this.toHex(decrypted));
408
- try {
409
- const text = new TextDecoder().decode(decrypted);
410
- console.log('Decrypted as text:', text);
411
- } catch (e) {
412
- console.log('(Data is not valid UTF-8 text)');
413
- }
414
- } catch (error) {
415
- console.error('Decryption failed:', error);
416
- }
417
- }
418
- }
@@ -1,73 +0,0 @@
1
-
2
- import { base32 } from "multiformats/bases/base32";
3
-
4
-
5
-
6
- async function decryptContent(
7
- encryptBuffer: Uint8Array,
8
- decryptKey: string | Uint8Array
9
- ): Promise<Uint8Array> {
10
- try {
11
- if (decryptKey === "" || encryptBuffer.length <= 28) {
12
- return encryptBuffer;
13
- }
14
-
15
- // 1. 准备数据
16
- const nonce = encryptBuffer.slice(0, 12);
17
- // 尝试不同的密文分割方式
18
- const ciphertext = encryptBuffer.slice(12);
19
-
20
- // 2. 准备密钥
21
- const inputKey = typeof decryptKey === "string"
22
- ? base32.decode(decryptKey)
23
- : decryptKey;
24
-
25
-
26
-
27
- // 3. 导入密钥
28
- const key = await window.crypto.subtle.importKey(
29
- "raw",
30
- inputKey,
31
- {
32
- name: "AES-GCM",
33
- length: 256
34
- },
35
- false,
36
- ["decrypt"]
37
- );
38
-
39
- // 4. 尝试不同的解密配置
40
- const configs = [
41
- { tagLength: 128, name: "标准模式" },
42
- { tagLength: 96, name: "96位标签模式" },
43
- { tagLength: 64, name: "64位标签模式" }
44
- ];
45
-
46
- for (const config of configs) {
47
- try {
48
- const decrypted = await window.crypto.subtle.decrypt(
49
- {
50
- name: "AES-GCM",
51
- iv: nonce,
52
- tagLength: config.tagLength
53
- },
54
- key,
55
- ciphertext
56
- );
57
- // 解密成功
58
- const result = new Uint8Array(decrypted);
59
- return result;
60
- } catch (e: any) {
61
- console.log(`${config.name} 失败:`, e.message);
62
- continue;
63
- }
64
- }
65
- throw new Error('decrypt failed');
66
- } catch (error) {
67
- throw error;
68
- }
69
- }
70
-
71
-
72
-
73
- export { decryptContent };
@@ -1,104 +0,0 @@
1
- // util/logger.ts
2
- // 提供统一的日志接口
3
-
4
- /**
5
- * 日志级别枚举
6
- */
7
- export enum LogLevel {
8
- DEBUG = 0,
9
- INFO = 1,
10
- WARN = 2,
11
- ERROR = 3
12
- }
13
-
14
- /**
15
- * 日志配置接口
16
- */
17
- export interface LogConfig {
18
- level: LogLevel;
19
- enableTimestamp: boolean;
20
- enableModuleName: boolean;
21
- }
22
-
23
- let globalConfig: LogConfig = {
24
- level: LogLevel.INFO,
25
- enableTimestamp: true,
26
- enableModuleName: true
27
- };
28
-
29
- /**
30
- * 设置全局日志配置
31
- * @param config 日志配置
32
- */
33
- export function configureLogger(config: Partial<LogConfig>): void {
34
- globalConfig = { ...globalConfig, ...config };
35
- }
36
-
37
- /**
38
- * 日志接口
39
- */
40
- export interface Logger {
41
- debug(message: string, ...args: any[]): void;
42
- info(message: string, ...args: any[]): void;
43
- warn(message: string, ...args: any[]): void;
44
- error(message: string, ...args: any[]): void;
45
- }
46
-
47
- /**
48
- * 创建日志记录器
49
- * @param module 模块名称
50
- * @returns 日志记录器对象
51
- */
52
- export function createLogger(module: string): Logger {
53
- return {
54
- debug(message: string, ...args: any[]): void {
55
- if (globalConfig.level <= LogLevel.DEBUG) {
56
- const prefix = buildPrefix('DEBUG', module);
57
- console.debug(prefix + message, ...args);
58
- }
59
- },
60
-
61
- info(message: string, ...args: any[]): void {
62
- if (globalConfig.level <= LogLevel.INFO) {
63
- const prefix = buildPrefix('INFO', module);
64
- console.info(prefix + message, ...args);
65
- }
66
- },
67
-
68
- warn(message: string, ...args: any[]): void {
69
- if (globalConfig.level <= LogLevel.WARN) {
70
- const prefix = buildPrefix('WARN', module);
71
- console.warn(prefix + message, ...args);
72
- }
73
- },
74
-
75
- error(message: string, ...args: any[]): void {
76
- if (globalConfig.level <= LogLevel.ERROR) {
77
- const prefix = buildPrefix('ERROR', module);
78
- console.error(prefix + message, ...args);
79
- }
80
- }
81
- };
82
- }
83
-
84
- /**
85
- * 构建日志前缀
86
- * @param level 日志级别
87
- * @param module 模块名称
88
- * @returns 格式化的前缀字符串
89
- */
90
- function buildPrefix(level: string, module: string): string {
91
- let prefix = '';
92
-
93
- if (globalConfig.enableTimestamp) {
94
- prefix += `[${new Date().toISOString()}] `;
95
- }
96
-
97
- if (globalConfig.enableModuleName) {
98
- prefix += `[${module}] `;
99
- }
100
-
101
- prefix += `[${level}] `;
102
-
103
- return prefix;
104
- }