@fileverse/api 0.0.20 → 0.0.22

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -116,12 +116,7 @@ var init_config = __esm({
116
116
  init_constants();
117
117
  projectEnvPath = path2.join(process.cwd(), "config", ".env");
118
118
  userEnvPath = path2.join(os.homedir(), ".fileverse", ".env");
119
- if (typeof globalThis.process !== "undefined" && typeof globalThis.process.cwd === "function") {
120
- try {
121
- loadConfig(false);
122
- } catch {
123
- }
124
- }
119
+ loadConfig(false);
125
120
  config = {
126
121
  ...STATIC_CONFIG,
127
122
  get SERVICE_NAME() {
@@ -669,9 +664,7 @@ var init_files_model = __esm({
669
664
  linkKey: fileRaw.linkKey,
670
665
  linkKeyNonce: fileRaw.linkKeyNonce,
671
666
  commentKey: fileRaw.commentKey,
672
- link: fileRaw.link,
673
- derivedKey: fileRaw.derivedKey,
674
- secretKey: fileRaw.secretKey
667
+ link: fileRaw.link
675
668
  };
676
669
  }
677
670
  static async findAll(portalAddress, limit, skip) {
@@ -755,20 +748,10 @@ var init_files_model = __esm({
755
748
  const _id = uuidv7();
756
749
  const sql = `
757
750
  INSERT INTO ${this.TABLE}
758
- (_id, title, content, ddocId, portalAddress, linkKey, linkKeyNonce, derivedKey, secretKey)
759
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
751
+ (_id, title, content, ddocId, portalAddress)
752
+ VALUES (?, ?, ?, ?, ?)
760
753
  `;
761
- await QueryBuilder.execute(sql, [
762
- _id,
763
- input.title,
764
- input.content,
765
- input.ddocId,
766
- input.portalAddress,
767
- input.linkKey ?? null,
768
- input.linkKeyNonce ?? null,
769
- input.derivedKey ?? null,
770
- input.secretKey ?? null
771
- ]);
754
+ await QueryBuilder.execute(sql, [_id, input.title, input.content, input.ddocId, input.portalAddress]);
772
755
  const created = await this.findById(_id, input.portalAddress);
773
756
  if (!created) {
774
757
  throw new Error("Failed to create file");
@@ -1148,29 +1131,6 @@ var init_events_model = __esm({
1148
1131
  `;
1149
1132
  await QueryBuilder.execute(sql, [Date.now(), _id]);
1150
1133
  }
1151
- static async markSubmitted(_id) {
1152
- const sql = `
1153
- UPDATE ${this.TABLE}
1154
- SET status = 'submitted',
1155
- lockedAt = NULL
1156
- WHERE _id = ?
1157
- `;
1158
- await QueryBuilder.execute(sql, [_id]);
1159
- }
1160
- static async findNextSubmitted(lockedFileIds) {
1161
- const exclusionClause = lockedFileIds.length > 0 ? `AND fileId NOT IN (${lockedFileIds.map(() => "?").join(", ")})` : "";
1162
- const sql = `
1163
- SELECT * FROM ${this.TABLE}
1164
- WHERE status = 'submitted'
1165
- AND userOpHash IS NOT NULL
1166
- ${exclusionClause}
1167
- ORDER BY timestamp ASC
1168
- LIMIT 1
1169
- `;
1170
- const params = [...lockedFileIds];
1171
- const row = await QueryBuilder.selectOne(sql, params);
1172
- return row ? this.parseEvent(row) : void 0;
1173
- }
1174
1134
  static async markProcessed(_id) {
1175
1135
  const sql = `
1176
1136
  UPDATE ${this.TABLE}
@@ -1373,114 +1333,13 @@ var init_key_store = __esm({
1373
1333
  }
1374
1334
  });
1375
1335
 
1376
- // src/sdk/ucan.ts
1377
- import { sign, extractPublicKeyFromSecretKey } from "@stablelib/ed25519";
1378
- import { toUint8Array } from "js-base64";
1379
- function base58btcEncode(bytes) {
1380
- const digits = [0];
1381
- for (const byte of bytes) {
1382
- let carry = byte;
1383
- for (let j = 0; j < digits.length; j++) {
1384
- carry += digits[j] << 8;
1385
- digits[j] = carry % 58;
1386
- carry = carry / 58 | 0;
1387
- }
1388
- while (carry > 0) {
1389
- digits.push(carry % 58);
1390
- carry = carry / 58 | 0;
1391
- }
1392
- }
1393
- let result = "";
1394
- for (let i = 0; i < bytes.length && bytes[i] === 0; i++) {
1395
- result += BASE58_ALPHABET[0];
1396
- }
1397
- for (let i = digits.length - 1; i >= 0; i--) {
1398
- result += BASE58_ALPHABET[digits[i]];
1399
- }
1400
- return result;
1401
- }
1402
- function base64urlEncode(data) {
1403
- const bytes = typeof data === "string" ? new TextEncoder().encode(data) : data;
1404
- let binary = "";
1405
- for (let i = 0; i < bytes.length; i++) {
1406
- binary += String.fromCharCode(bytes[i]);
1407
- }
1408
- return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
1409
- }
1410
- async function buildAndEncode(params) {
1411
- const {
1412
- issuer,
1413
- audience,
1414
- capabilities = [],
1415
- lifetimeInSeconds = 30,
1416
- expiration,
1417
- notBefore,
1418
- facts,
1419
- proofs = []
1420
- } = params;
1421
- const currentTime = Math.floor(Date.now() / 1e3);
1422
- const exp = expiration ?? currentTime + lifetimeInSeconds;
1423
- const header = { alg: issuer.jwtAlg, typ: "JWT", ucv: "0.8.1" };
1424
- const att = capabilities.map((cap) => ({
1425
- with: `${cap.with.scheme}:${cap.with.hierPart}`,
1426
- can: [cap.can.namespace, ...cap.can.segments].join("/")
1427
- }));
1428
- const payload = {
1429
- iss: issuer.did(),
1430
- aud: audience,
1431
- exp,
1432
- att,
1433
- prf: proofs
1434
- };
1435
- if (notBefore !== void 0) payload.nbf = notBefore;
1436
- if (facts !== void 0) payload.fct = facts;
1437
- const encodedHeader = base64urlEncode(JSON.stringify(header));
1438
- const encodedPayload = base64urlEncode(JSON.stringify(payload));
1439
- const signedData = `${encodedHeader}.${encodedPayload}`;
1440
- const sig = await issuer.sign(new TextEncoder().encode(signedData));
1441
- const signature = base64urlEncode(sig);
1442
- return `${signedData}.${signature}`;
1443
- }
1444
- var BASE58_ALPHABET, EDWARDS_DID_PREFIX, EdKeypair;
1445
- var init_ucan = __esm({
1446
- "src/sdk/ucan.ts"() {
1447
- "use strict";
1448
- init_esm_shims();
1449
- BASE58_ALPHABET = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
1450
- EDWARDS_DID_PREFIX = new Uint8Array([237, 1]);
1451
- EdKeypair = class _EdKeypair {
1452
- jwtAlg = "EdDSA";
1453
- secretKey;
1454
- publicKey;
1455
- constructor(secretKey, publicKey) {
1456
- this.secretKey = secretKey;
1457
- this.publicKey = publicKey;
1458
- }
1459
- static fromSecretKey(key) {
1460
- const secretKey = toUint8Array(key);
1461
- const publicKey = extractPublicKeyFromSecretKey(secretKey);
1462
- return new _EdKeypair(secretKey, publicKey);
1463
- }
1464
- did() {
1465
- const bytes = new Uint8Array(EDWARDS_DID_PREFIX.length + this.publicKey.length);
1466
- bytes.set(EDWARDS_DID_PREFIX);
1467
- bytes.set(this.publicKey, EDWARDS_DID_PREFIX.length);
1468
- return "did:key:z" + base58btcEncode(bytes);
1469
- }
1470
- async sign(msg) {
1471
- return sign(this.secretKey, msg);
1472
- }
1473
- };
1474
- }
1475
- });
1476
-
1477
1336
  // src/sdk/auth-token-provider.ts
1337
+ import * as ucans from "@ucans/ucans";
1478
1338
  var AuthTokenProvider;
1479
1339
  var init_auth_token_provider = __esm({
1480
1340
  "src/sdk/auth-token-provider.ts"() {
1481
1341
  "use strict";
1482
1342
  init_esm_shims();
1483
- init_ucan();
1484
1343
  AuthTokenProvider = class {
1485
1344
  DEFAULT_OPTIONS = {
1486
1345
  namespace: "file",
@@ -1494,7 +1353,7 @@ var init_auth_token_provider = __esm({
1494
1353
  this.portalAddress = portalAddress;
1495
1354
  }
1496
1355
  async getAuthToken(audienceDid, options = this.DEFAULT_OPTIONS) {
1497
- return buildAndEncode({
1356
+ const ucan = await ucans.build({
1498
1357
  audience: audienceDid,
1499
1358
  issuer: this.keyPair,
1500
1359
  lifetimeInSeconds: 7 * 86400,
@@ -1508,6 +1367,7 @@ var init_auth_token_provider = __esm({
1508
1367
  }
1509
1368
  ]
1510
1369
  });
1370
+ return ucans.encode(ucan);
1511
1371
  }
1512
1372
  };
1513
1373
  }
@@ -1839,29 +1699,19 @@ var init_pimlico_utils = __esm({
1839
1699
  version: "0.7"
1840
1700
  }
1841
1701
  });
1842
- signerToSmartAccount = async (signer) => {
1843
- console.log("[pimlico] creating public client");
1844
- const client = getPublicClient();
1845
- console.log("[pimlico] calling toSafeSmartAccount");
1846
- const account = await toSafeSmartAccount({
1847
- client,
1848
- owners: [signer],
1849
- entryPoint: {
1850
- address: entryPoint07Address,
1851
- version: "0.7"
1852
- },
1853
- version: "1.4.1"
1854
- });
1855
- console.log("[pimlico] safe smart account created");
1856
- return account;
1857
- };
1702
+ signerToSmartAccount = async (signer) => await toSafeSmartAccount({
1703
+ client: getPublicClient(),
1704
+ owners: [signer],
1705
+ entryPoint: {
1706
+ address: entryPoint07Address,
1707
+ version: "0.7"
1708
+ },
1709
+ version: "1.4.1"
1710
+ });
1858
1711
  getSmartAccountClient = async (signer, authToken, portalAddress) => {
1859
- console.log("[pimlico] signerToSmartAccount start");
1860
1712
  const smartAccount = await signerToSmartAccount(signer);
1861
- console.log("[pimlico] creating pimlico client");
1862
1713
  const pimlicoClient = getPimlicoClient(authToken, portalAddress, smartAccount.address);
1863
- console.log("[pimlico] creating smart account client");
1864
- const result = createSmartAccountClient({
1714
+ return createSmartAccountClient({
1865
1715
  account: smartAccount,
1866
1716
  chain: CHAIN,
1867
1717
  paymaster: pimlicoClient,
@@ -1879,8 +1729,6 @@ var init_pimlico_utils = __esm({
1879
1729
  estimateFeesPerGas: async () => (await pimlicoClient.getUserOperationGasPrice()).fast
1880
1730
  }
1881
1731
  });
1882
- console.log("[pimlico] smart account client created");
1883
- return result;
1884
1732
  };
1885
1733
  getNonce = () => hexToBigInt(
1886
1734
  toHex(toBytes(generatePrivateKey()).slice(0, 24), {
@@ -1916,17 +1764,13 @@ var init_smart_agent = __esm({
1916
1764
  MAX_CALL_GAS_LIMIT = 5e5;
1917
1765
  authOptions = { namespace: "proxy", segment: "ACCESS", scheme: "pimlico" };
1918
1766
  async initializeAgentClient(keyMaterial) {
1919
- console.log("[agent] creating account from key");
1920
1767
  const agentAccount = privateKeyToAccount(toHex2(keyMaterial));
1921
- console.log("[agent] getting auth token");
1922
1768
  const authToken = await this.authTokenProvider.getAuthToken(STATIC_CONFIG.PROXY_SERVER_DID, this.authOptions);
1923
- console.log("[agent] getting smart account client");
1924
1769
  const smartAccountClient = await getSmartAccountClient(
1925
1770
  agentAccount,
1926
1771
  authToken,
1927
1772
  this.authTokenProvider.portalAddress
1928
1773
  );
1929
- console.log("[agent] smart account client ready");
1930
1774
  this.smartAccountAgent = smartAccountClient;
1931
1775
  }
1932
1776
  getSmartAccountAgent() {
@@ -1966,19 +1810,17 @@ var init_smart_agent = __esm({
1966
1810
  ]);
1967
1811
  }
1968
1812
  async sendUserOperation(request, customGasLimit) {
1969
- const smartAccountAgent = this.getSmartAccountAgent();
1970
- console.log("[agent] encoding call data");
1971
- const callData = await this.getCallData(request);
1972
- console.log("[agent] generating nonce");
1973
- const nonce = getNonce();
1974
- console.log("[agent] sending user operation");
1975
- const hash2 = await smartAccountAgent.sendUserOperation({
1976
- callData,
1977
- callGasLimit: BigInt(customGasLimit || this.MAX_CALL_GAS_LIMIT),
1978
- nonce
1979
- });
1980
- console.log("[agent] user operation sent");
1981
- return hash2;
1813
+ try {
1814
+ const smartAccountAgent = this.getSmartAccountAgent();
1815
+ const callData = await this.getCallData(request);
1816
+ return await smartAccountAgent.sendUserOperation({
1817
+ callData,
1818
+ callGasLimit: BigInt(customGasLimit || this.MAX_CALL_GAS_LIMIT),
1819
+ nonce: getNonce()
1820
+ });
1821
+ } catch (error48) {
1822
+ throw error48;
1823
+ }
1982
1824
  }
1983
1825
  async executeUserOperationRequest(request, timeout, customGasLimit) {
1984
1826
  const userOpHash = await this.sendUserOperation(request, customGasLimit);
@@ -2693,20 +2535,60 @@ var init_file_encryption = __esm({
2693
2535
  });
2694
2536
 
2695
2537
  // src/sdk/file-utils.ts
2538
+ import { getArgon2idHash } from "@fileverse/crypto/argon";
2696
2539
  import { bytesToBase64, generateRandomBytes as generateRandomBytes2 } from "@fileverse/crypto/utils";
2697
2540
  import { derivePBKDF2Key, encryptAesCBC } from "@fileverse/crypto/kdf";
2698
2541
  import { secretBoxEncrypt } from "@fileverse/crypto/nacl";
2542
+ import hkdf from "futoin-hkdf";
2699
2543
  import tweetnacl from "tweetnacl";
2700
- import { fromUint8Array, toUint8Array as toUint8Array2 } from "js-base64";
2544
+ import { fromUint8Array, toUint8Array } from "js-base64";
2701
2545
  import { toAESKey, aesEncrypt } from "@fileverse/crypto/webcrypto";
2546
+ import axios from "axios";
2702
2547
  import { encodeFunctionData, parseEventLogs } from "viem";
2703
- var jsonToFile, appendAuthTagIvToBlob, encryptFile, getNonceAppendedCipherText, jsonToBytes, buildLinklock, encryptTitleWithFileKey, uploadFileToIPFS, getEditFileTrxCalldata, getAddFileTrxCalldata, prepareCallData, prepareDeleteFileCallData, createEncryptedContentFile, buildFileMetadata, parseFileEventLog, uploadAllFilesToIPFS;
2548
+ var deriveKeyFromAg2Hash, decryptSecretKey, getExistingEncryptionMaterial, getNaclSecretKey, generateLinkKeyMaterial, jsonToFile, appendAuthTagIvToBlob, encryptFile, getNonceAppendedCipherText, jsonToBytes, buildLinklock, encryptTitleWithFileKey, uploadFileToIPFS, getEditFileTrxCalldata, getAddFileTrxCalldata, prepareCallData, prepareDeleteFileCallData, createEncryptedContentFile, buildFileMetadata, parseFileEventLog, uploadAllFilesToIPFS;
2704
2549
  var init_file_utils = __esm({
2705
2550
  "src/sdk/file-utils.ts"() {
2706
2551
  "use strict";
2707
2552
  init_esm_shims();
2708
2553
  init_file_encryption();
2709
2554
  init_constants3();
2555
+ deriveKeyFromAg2Hash = async (pass, salt) => {
2556
+ const key = await getArgon2idHash(pass, salt);
2557
+ return hkdf(Buffer.from(key), tweetnacl.secretbox.keyLength, {
2558
+ info: Buffer.from("encryptionKey")
2559
+ });
2560
+ };
2561
+ decryptSecretKey = async (docId, nonce, encryptedSecretKey) => {
2562
+ const derivedKey = await deriveKeyFromAg2Hash(docId, toUint8Array(nonce));
2563
+ return tweetnacl.secretbox.open(toUint8Array(encryptedSecretKey), toUint8Array(nonce), derivedKey);
2564
+ };
2565
+ getExistingEncryptionMaterial = async (existingEncryptedSecretKey, existingNonce, docId) => {
2566
+ const secretKey = await decryptSecretKey(docId, existingNonce, existingEncryptedSecretKey);
2567
+ return {
2568
+ encryptedSecretKey: existingEncryptedSecretKey,
2569
+ nonce: toUint8Array(existingNonce),
2570
+ secretKey
2571
+ };
2572
+ };
2573
+ getNaclSecretKey = async (ddocId) => {
2574
+ const { secretKey } = tweetnacl.box.keyPair();
2575
+ const nonce = tweetnacl.randomBytes(tweetnacl.secretbox.nonceLength);
2576
+ const derivedKey = await deriveKeyFromAg2Hash(ddocId, nonce);
2577
+ const encryptedSecretKey = fromUint8Array(tweetnacl.secretbox(secretKey, nonce, derivedKey), true);
2578
+ return { nonce, encryptedSecretKey, secretKey };
2579
+ };
2580
+ generateLinkKeyMaterial = async (params) => {
2581
+ if (params.linkKeyNonce && params.linkKey) {
2582
+ const { encryptedSecretKey: encryptedSecretKey2, nonce: nonce2, secretKey: secretKey2 } = await getExistingEncryptionMaterial(
2583
+ params.linkKey,
2584
+ params.linkKeyNonce,
2585
+ params.ddocId
2586
+ );
2587
+ if (secretKey2) return { encryptedSecretKey: encryptedSecretKey2, nonce: nonce2, secretKey: secretKey2 };
2588
+ }
2589
+ const { secretKey, nonce, encryptedSecretKey } = await getNaclSecretKey(params.ddocId);
2590
+ return { secretKey, nonce, encryptedSecretKey };
2591
+ };
2710
2592
  jsonToFile = (json2, fileName) => {
2711
2593
  const blob = new Blob([JSON.stringify(json2)], {
2712
2594
  type: "application/json"
@@ -2736,8 +2618,8 @@ var init_file_utils = __esm({
2736
2618
  const encryptedBlob = new Blob([ciphertext], { type: file2.type });
2737
2619
  const encryptedBlobWithAuthTagIv = await appendAuthTagIvToBlob(
2738
2620
  encryptedBlob,
2739
- toUint8Array2(authTag),
2740
- toUint8Array2(iv)
2621
+ toUint8Array(authTag),
2622
+ toUint8Array(iv)
2741
2623
  );
2742
2624
  return {
2743
2625
  encryptedFile: new File([encryptedBlobWithAuthTagIv], file2.name),
@@ -2783,7 +2665,7 @@ var init_file_utils = __esm({
2783
2665
  };
2784
2666
  };
2785
2667
  encryptTitleWithFileKey = async (args) => {
2786
- const key = await toAESKey(toUint8Array2(args.key));
2668
+ const key = await toAESKey(toUint8Array(args.key));
2787
2669
  if (!key) throw new Error("Key is undefined");
2788
2670
  const titleBytes = new TextEncoder().encode(args.title);
2789
2671
  const encryptedTitle = await aesEncrypt(key, titleBytes, "base64");
@@ -2797,21 +2679,16 @@ var init_file_utils = __esm({
2797
2679
  body.append("ipfsType", ipfsType);
2798
2680
  body.append("appFileId", appFileId);
2799
2681
  body.append("sourceApp", "ddoc");
2800
- const response = await fetch(UPLOAD_SERVER_URL + "upload", {
2801
- method: "POST",
2682
+ const uploadEndpoint = UPLOAD_SERVER_URL + "upload";
2683
+ const response = await axios.post(uploadEndpoint, body, {
2802
2684
  headers: {
2803
2685
  Authorization: `Bearer ${token}`,
2804
2686
  contract: contractAddress,
2805
2687
  invoker,
2806
- chain: NETWORK_NAME
2807
- },
2808
- body
2688
+ chain: process.env.chainId
2689
+ }
2809
2690
  });
2810
- if (!response.ok) {
2811
- throw new Error(`Upload failed: ${response.status} ${response.statusText}`);
2812
- }
2813
- const data = await response.json();
2814
- return data.ipfsHash;
2691
+ return response.data.ipfsHash;
2815
2692
  };
2816
2693
  getEditFileTrxCalldata = (args) => {
2817
2694
  return encodeFunctionData({
@@ -2906,7 +2783,7 @@ var init_file_utils = __esm({
2906
2783
  });
2907
2784
 
2908
2785
  // src/sdk/file-manager.ts
2909
- import { fromUint8Array as fromUint8Array2, toUint8Array as toUint8Array3 } from "js-base64";
2786
+ import { fromUint8Array as fromUint8Array2, toUint8Array as toUint8Array2 } from "js-base64";
2910
2787
  import { generateAESKey, exportAESKey } from "@fileverse/crypto/webcrypto";
2911
2788
  import { markdownToYjs } from "@fileverse/content-processor";
2912
2789
  var FileManager;
@@ -2927,8 +2804,8 @@ var init_file_manager = __esm({
2927
2804
  }
2928
2805
  createLocks(key, encryptedSecretKey, commentKey) {
2929
2806
  const appLock = {
2930
- lockedFileKey: this.keyStore.encryptData(toUint8Array3(key)),
2931
- lockedLinkKey: this.keyStore.encryptData(toUint8Array3(encryptedSecretKey)),
2807
+ lockedFileKey: this.keyStore.encryptData(toUint8Array2(key)),
2808
+ lockedLinkKey: this.keyStore.encryptData(toUint8Array2(encryptedSecretKey)),
2932
2809
  lockedChatKey: this.keyStore.encryptData(commentKey)
2933
2810
  };
2934
2811
  return { appLock, ownerLock: { ...appLock } };
@@ -2962,28 +2839,22 @@ var init_file_manager = __esm({
2962
2839
  return this.agentClient.getAuthParams();
2963
2840
  }
2964
2841
  async submitAddFileTrx(file2) {
2965
- console.log("Submitting add file trx");
2966
2842
  logger.debug(`Preparing to add file ${file2.ddocId}`);
2967
- const encryptedSecretKey = file2.linkKey;
2968
- const nonce = toUint8Array3(file2.linkKeyNonce);
2969
- const secretKey = toUint8Array3(file2.secretKey);
2970
- console.log("Got encrypted secret key, nonce, and secret key");
2843
+ const { encryptedSecretKey, nonce, secretKey } = await generateLinkKeyMaterial({
2844
+ ddocId: file2.ddocId,
2845
+ linkKey: file2.linkKey,
2846
+ linkKeyNonce: file2.linkKeyNonce
2847
+ });
2971
2848
  const yJSContent = markdownToYjs(file2.content);
2972
- console.log("Generated yjs content");
2973
2849
  const { encryptedFile, key } = await createEncryptedContentFile(yJSContent);
2974
- console.log("Generated encrypted content file");
2975
2850
  logger.debug(`Generated encrypted content file for file ${file2.ddocId}`);
2976
2851
  const commentKey = await exportAESKey(await generateAESKey(128));
2977
- console.log("Generated comment key");
2978
2852
  const { appLock, ownerLock } = this.createLocks(key, encryptedSecretKey, commentKey);
2979
- console.log("Built app lock and owner lock");
2980
- const linkLock = buildLinklock(secretKey, toUint8Array3(key), commentKey);
2981
- console.log("Built link lock");
2853
+ const linkLock = buildLinklock(secretKey, toUint8Array2(key), commentKey);
2982
2854
  const encryptedTitle = await encryptTitleWithFileKey({
2983
2855
  title: file2.title || "Untitled",
2984
2856
  key
2985
2857
  });
2986
- console.log("Built encrypted title");
2987
2858
  const metadata = buildFileMetadata({
2988
2859
  encryptedTitle,
2989
2860
  encryptedFileSize: encryptedFile.size,
@@ -2993,15 +2864,11 @@ var init_file_manager = __esm({
2993
2864
  nonce: fromUint8Array2(nonce),
2994
2865
  owner: this.agentClient.getAgentAddress()
2995
2866
  });
2996
- console.log("Built metadata");
2997
2867
  const authParams = await this.getAuthParams();
2998
- console.log("Got auth params");
2999
- console.log("Uploading files to IPFS");
3000
2868
  const { metadataHash, contentHash, gateHash } = await uploadAllFilesToIPFS(
3001
2869
  { metadata, encryptedFile, linkLock, ddocId: file2.ddocId },
3002
2870
  authParams
3003
2871
  );
3004
- console.log("Uploaded files to IPFS");
3005
2872
  logger.debug(`Uploaded files to IPFS for file ${file2.ddocId}`);
3006
2873
  const callData = prepareCallData({
3007
2874
  metadataHash,
@@ -3010,10 +2877,8 @@ var init_file_manager = __esm({
3010
2877
  appFileId: file2.ddocId,
3011
2878
  fileId: file2.fileId
3012
2879
  });
3013
- console.log("Prepared call data");
3014
2880
  logger.debug(`Prepared call data for file ${file2.ddocId}`);
3015
2881
  const userOpHash = await this.sendFileOperation(callData);
3016
- console.log("Submitted user op");
3017
2882
  logger.debug(`Submitted user op for file ${file2.ddocId}`);
3018
2883
  return {
3019
2884
  userOpHash,
@@ -3023,65 +2888,19 @@ var init_file_manager = __esm({
3023
2888
  metadata
3024
2889
  };
3025
2890
  }
3026
- async submitUpdateFile(file2) {
3027
- logger.debug(`Submitting update for file ${file2.ddocId} with onChainFileId ${file2.onChainFileId}`);
3028
- const encryptedSecretKey = file2.linkKey;
3029
- const nonce = toUint8Array3(file2.linkKeyNonce);
3030
- const secretKey = toUint8Array3(file2.secretKey);
3031
- const yjsContent = markdownToYjs(file2.content);
3032
- const { encryptedFile, key } = await createEncryptedContentFile(yjsContent);
3033
- const commentKey = toUint8Array3(file2.commentKey);
3034
- const { appLock, ownerLock } = this.createLocks(key, encryptedSecretKey, commentKey);
3035
- const linkLock = buildLinklock(secretKey, toUint8Array3(key), commentKey);
3036
- const encryptedTitle = await encryptTitleWithFileKey({
3037
- title: file2.title || "Untitled",
3038
- key
3039
- });
3040
- const metadata = buildFileMetadata({
3041
- encryptedTitle,
3042
- encryptedFileSize: encryptedFile.size,
3043
- appLock,
3044
- ownerLock,
3045
- ddocId: file2.ddocId,
3046
- nonce: fromUint8Array2(nonce),
3047
- owner: this.agentClient.getAgentAddress()
3048
- });
3049
- const authParams = await this.getAuthParams();
3050
- const { metadataHash, contentHash, gateHash } = await uploadAllFilesToIPFS(
3051
- { metadata, encryptedFile, linkLock, ddocId: file2.ddocId },
3052
- authParams
3053
- );
3054
- const callData = prepareCallData({
3055
- metadataHash,
3056
- contentHash,
3057
- gateHash,
3058
- appFileId: file2.ddocId,
3059
- fileId: file2.onChainFileId
3060
- });
3061
- const userOpHash = await this.sendFileOperation(callData);
3062
- logger.debug(`Submitted update user op for file ${file2.ddocId}`);
3063
- return { userOpHash, metadata };
3064
- }
3065
- async submitDeleteFile(file2) {
3066
- logger.debug(`Submitting delete for file ${file2.ddocId} with onChainFileId ${file2.onChainFileId}`);
3067
- const callData = prepareDeleteFileCallData({
3068
- onChainFileId: file2.onChainFileId
3069
- });
3070
- const userOpHash = await this.sendFileOperation(callData);
3071
- logger.debug(`Submitted delete user op for file ${file2.ddocId}`);
3072
- return { userOpHash };
3073
- }
3074
2891
  async updateFile(file2) {
3075
2892
  logger.debug(`Updating file ${file2.ddocId} with onChainFileId ${file2.onChainFileId}`);
3076
- const encryptedSecretKey = file2.linkKey;
3077
- const nonce = toUint8Array3(file2.linkKeyNonce);
3078
- const secretKey = toUint8Array3(file2.secretKey);
2893
+ const { encryptedSecretKey, nonce, secretKey } = await generateLinkKeyMaterial({
2894
+ ddocId: file2.ddocId,
2895
+ linkKey: file2.linkKey,
2896
+ linkKeyNonce: file2.linkKeyNonce
2897
+ });
3079
2898
  logger.debug(`Generating encrypted content file for file ${file2.ddocId} with onChainFileId ${file2.onChainFileId}`);
3080
2899
  const yjsContent = markdownToYjs(file2.content);
3081
2900
  const { encryptedFile, key } = await createEncryptedContentFile(yjsContent);
3082
- const commentKey = toUint8Array3(file2.commentKey);
2901
+ const commentKey = toUint8Array2(file2.commentKey);
3083
2902
  const { appLock, ownerLock } = this.createLocks(key, encryptedSecretKey, commentKey);
3084
- const linkLock = buildLinklock(secretKey, toUint8Array3(key), commentKey);
2903
+ const linkLock = buildLinklock(secretKey, toUint8Array2(key), commentKey);
3085
2904
  const encryptedTitle = await encryptTitleWithFileKey({
3086
2905
  title: file2.title || "Untitled",
3087
2906
  key
@@ -3133,10 +2952,11 @@ var init_file_manager = __esm({
3133
2952
  });
3134
2953
 
3135
2954
  // src/domain/portal/publish.ts
3136
- import { fromUint8Array as fromUint8Array3, toUint8Array as toUint8Array4 } from "js-base64";
2955
+ import { fromUint8Array as fromUint8Array3, toUint8Array as toUint8Array3 } from "js-base64";
3137
2956
  import { stringToBytes } from "viem";
3138
2957
  import { deriveHKDFKey } from "@fileverse/crypto/kdf";
3139
2958
  import { generateKeyPairFromSeed } from "@stablelib/ed25519";
2959
+ import * as ucans2 from "@ucans/ucans";
3140
2960
  async function getPortalData(fileId) {
3141
2961
  const file2 = await FilesModel.findByIdIncludingDeleted(fileId);
3142
2962
  if (!file2) {
@@ -3168,23 +2988,17 @@ var init_publish = __esm({
3168
2988
  init_infra();
3169
2989
  init_key_store();
3170
2990
  init_auth_token_provider();
3171
- init_ucan();
3172
2991
  init_smart_agent();
3173
2992
  init_file_manager();
3174
2993
  init_config();
3175
- init_pimlico_utils();
3176
2994
  createFileManager = async (portalSeed, portalAddress, ucanSecret, privateAccountKey) => {
3177
- console.log("Creating file manager");
3178
- const keyPair = EdKeypair.fromSecretKey(fromUint8Array3(ucanSecret));
3179
- console.log("Created key pair");
2995
+ const keyPair = ucans2.EdKeypair.fromSecretKey(fromUint8Array3(ucanSecret), {
2996
+ exportable: true
2997
+ });
3180
2998
  const authTokenProvider = new AuthTokenProvider(keyPair, portalAddress);
3181
- console.log("Created auth token provider");
3182
- const keyStore = new KeyStore(toUint8Array4(portalSeed), portalAddress, authTokenProvider);
3183
- console.log("Created key store");
2999
+ const keyStore = new KeyStore(toUint8Array3(portalSeed), portalAddress, authTokenProvider);
3184
3000
  const agentClient = new AgentClient(authTokenProvider);
3185
- console.log("Created agent client");
3186
3001
  await agentClient.initializeAgentClient(privateAccountKey);
3187
- console.log("Initialized agent client");
3188
3002
  return new FileManager(keyStore, agentClient);
3189
3003
  };
3190
3004
  executeOperation = async (fileManager, file2, operation) => {
@@ -3201,7 +3015,7 @@ var init_publish = __esm({
3201
3015
  handleExistingFileOp = async (fileId, operation) => {
3202
3016
  try {
3203
3017
  const { file: file2, portalDetails, apiKey } = await getPortalData(fileId);
3204
- const apiKeySeed = toUint8Array4(apiKey);
3018
+ const apiKeySeed = toUint8Array3(apiKey);
3205
3019
  const { privateAccountKey, ucanSecret } = deriveCollaboratorKeys(apiKeySeed);
3206
3020
  const fileManager = await createFileManager(
3207
3021
  portalDetails.portalSeed,
@@ -3217,22 +3031,19 @@ var init_publish = __esm({
3217
3031
  };
3218
3032
  handleNewFileOp = async (fileId) => {
3219
3033
  const { file: file2, portalDetails, apiKey } = await getPortalData(fileId);
3220
- console.log("Got portal data");
3221
- const apiKeySeed = toUint8Array4(apiKey);
3034
+ const apiKeySeed = toUint8Array3(apiKey);
3222
3035
  const { privateAccountKey, ucanSecret } = deriveCollaboratorKeys(apiKeySeed);
3223
- console.log("Derived collaborator keys");
3224
3036
  const fileManager = await createFileManager(
3225
3037
  portalDetails.portalSeed,
3226
3038
  portalDetails.portalAddress,
3227
3039
  ucanSecret,
3228
3040
  privateAccountKey
3229
3041
  );
3230
- console.log("Created file manager");
3231
3042
  return fileManager.submitAddFileTrx(file2);
3232
3043
  };
3233
3044
  getProxyAuthParams = async (fileId) => {
3234
3045
  const { portalDetails, apiKey } = await getPortalData(fileId);
3235
- const apiKeySeed = toUint8Array4(apiKey);
3046
+ const apiKeySeed = toUint8Array3(apiKey);
3236
3047
  const { privateAccountKey, ucanSecret } = deriveCollaboratorKeys(apiKeySeed);
3237
3048
  const fileManager = await createFileManager(
3238
3049
  portalDetails.portalSeed,
@@ -3754,9 +3565,7 @@ CREATE TABLE IF NOT EXISTS files (
3754
3565
  commentKey TEXT,
3755
3566
  linkKey TEXT,
3756
3567
  linkKeyNonce TEXT,
3757
- link TEXT,
3758
- derivedKey TEXT,
3759
- secretKey TEXT
3568
+ link TEXT
3760
3569
  );
3761
3570
  CREATE INDEX IF NOT EXISTS idx_files_createdAt ON files(createdAt);
3762
3571
  CREATE INDEX IF NOT EXISTS idx_files_syncStatus ON files(syncStatus);
@@ -3787,7 +3596,7 @@ CREATE TABLE IF NOT EXISTS events (
3787
3596
  type TEXT NOT NULL CHECK (type IN ('create', 'update', 'delete')),
3788
3597
  timestamp BIGINT NOT NULL,
3789
3598
  fileId TEXT NOT NULL,
3790
- status TEXT NOT NULL DEFAULT 'pending' CHECK (status IN ('pending', 'processing', 'submitted', 'processed', 'failed')),
3599
+ status TEXT NOT NULL DEFAULT 'pending' CHECK (status IN ('pending', 'processing', 'processed', 'failed')),
3791
3600
  retryCount INTEGER NOT NULL DEFAULT 0,
3792
3601
  lastError TEXT,
3793
3602
  lockedAt BIGINT,
@@ -3837,17 +3646,30 @@ init_esm_shims();
3837
3646
  // src/cli/fetch-api-key.ts
3838
3647
  init_esm_shims();
3839
3648
  init_constants();
3840
- import { toUint8Array as toUint8Array5 } from "js-base64";
3649
+ import axios2 from "axios";
3650
+ import { toUint8Array as toUint8Array4 } from "js-base64";
3841
3651
  import { sha256 } from "viem";
3842
3652
  var fetchApiKeyData = async (apiKey) => {
3843
3653
  try {
3844
- const keyHash = sha256(toUint8Array5(apiKey));
3654
+ const keyHash = sha256(toUint8Array4(apiKey));
3845
3655
  const fullUrl = BASE_CONFIG.API_URL + `api-access/${keyHash}`;
3846
- const response = await fetch(fullUrl);
3847
- const { encryptedKeyMaterial, encryptedAppMaterial, id } = await response.json();
3656
+ const response = await axios2.get(fullUrl);
3657
+ const { encryptedKeyMaterial, encryptedAppMaterial, id } = response.data;
3848
3658
  return { encryptedKeyMaterial, encryptedAppMaterial, id };
3849
3659
  } catch (error48) {
3850
- throw new Error(`Server error: ${error48.message}`);
3660
+ if (axios2.isAxiosError(error48)) {
3661
+ if (error48.response?.status === 401) {
3662
+ throw new Error("Invalid API key");
3663
+ }
3664
+ if (error48.response?.status === 404) {
3665
+ throw new Error("API key not found");
3666
+ }
3667
+ if (error48.code === "ECONNREFUSED") {
3668
+ throw new Error(`Cannot connect to server at ${BASE_CONFIG.API_URL}`);
3669
+ }
3670
+ throw new Error(`Server error: ${error48.response?.data?.message || error48.message}`);
3671
+ }
3672
+ throw error48;
3851
3673
  }
3852
3674
  };
3853
3675
 
@@ -3857,7 +3679,7 @@ init_saveApiKey();
3857
3679
  init_apikeys_model();
3858
3680
  init_infra();
3859
3681
  import { deriveHKDFKey as deriveHKDFKey2 } from "@fileverse/crypto/hkdf";
3860
- import { toUint8Array as toUint8Array6 } from "js-base64";
3682
+ import { toUint8Array as toUint8Array5 } from "js-base64";
3861
3683
  import { stringToBytes as stringToBytes2 } from "viem";
3862
3684
  import { toAESKey as toAESKey2, aesDecrypt } from "@fileverse/crypto/webcrypto";
3863
3685
  var SAVED_DATA_ENCRYPTION_KEY_INFO = "SAVED_DATA_ENCRYPTION_KEY";
@@ -3882,7 +3704,7 @@ async function initializeWithData(data) {
3882
3704
  }
3883
3705
  var getAesKeyFromApiKey = async (apiKey) => {
3884
3706
  const rawSecret = deriveHKDFKey2(
3885
- toUint8Array6(apiKey),
3707
+ toUint8Array5(apiKey),
3886
3708
  new Uint8Array([0]),
3887
3709
  stringToBytes2(SAVED_DATA_ENCRYPTION_KEY_INFO)
3888
3710
  );
@@ -3893,7 +3715,7 @@ var bytestToJSON = (bytes) => {
3893
3715
  };
3894
3716
  var decryptSavedData = async (apiKey, encryptedData) => {
3895
3717
  const aesKey = await getAesKeyFromApiKey(apiKey);
3896
- const decryptedBytes = await aesDecrypt(aesKey, toUint8Array6(encryptedData));
3718
+ const decryptedBytes = await aesDecrypt(aesKey, toUint8Array5(encryptedData));
3897
3719
  const data = bytestToJSON(decryptedBytes);
3898
3720
  return data;
3899
3721
  };
@@ -3938,60 +3760,6 @@ init_esm_shims();
3938
3760
  init_models();
3939
3761
  init_constants2();
3940
3762
  import { generate } from "short-uuid";
3941
- import { fromUint8Array as fromUint8Array5 } from "js-base64";
3942
-
3943
- // src/sdk/link-key-utils.ts
3944
- init_esm_shims();
3945
- import { getArgon2idHash } from "@fileverse/crypto/argon";
3946
- import hkdf from "futoin-hkdf";
3947
- import tweetnacl2 from "tweetnacl";
3948
- import { fromUint8Array as fromUint8Array4, toUint8Array as toUint8Array7 } from "js-base64";
3949
- var deriveKeyFromAg2Hash = async (pass, salt) => {
3950
- const key = await getArgon2idHash(pass, salt, void 0, {
3951
- t: 2,
3952
- m: 4096,
3953
- p: 8,
3954
- dkLen: 32
3955
- });
3956
- return hkdf(Buffer.from(key), tweetnacl2.secretbox.keyLength, {
3957
- info: Buffer.from("encryptionKey")
3958
- });
3959
- };
3960
- var getExistingEncryptionMaterial = async (existingEncryptedSecretKey, existingNonce, docId) => {
3961
- const derivedKey = await deriveKeyFromAg2Hash(docId, toUint8Array7(existingNonce));
3962
- const secretKey = tweetnacl2.secretbox.open(
3963
- toUint8Array7(existingEncryptedSecretKey),
3964
- toUint8Array7(existingNonce),
3965
- derivedKey
3966
- );
3967
- return {
3968
- encryptedSecretKey: existingEncryptedSecretKey,
3969
- nonce: toUint8Array7(existingNonce),
3970
- secretKey,
3971
- derivedKey: new Uint8Array(derivedKey)
3972
- };
3973
- };
3974
- var getNaclSecretKey = async (ddocId) => {
3975
- const { secretKey } = tweetnacl2.box.keyPair();
3976
- const nonce = tweetnacl2.randomBytes(tweetnacl2.secretbox.nonceLength);
3977
- const derivedKey = await deriveKeyFromAg2Hash(ddocId, nonce);
3978
- const encryptedSecretKey = fromUint8Array4(tweetnacl2.secretbox(secretKey, nonce, derivedKey), true);
3979
- return { nonce, encryptedSecretKey, secretKey, derivedKey: new Uint8Array(derivedKey) };
3980
- };
3981
- var generateLinkKeyMaterial = async (params) => {
3982
- if (params.linkKeyNonce && params.linkKey) {
3983
- const { encryptedSecretKey: encryptedSecretKey2, nonce: nonce2, secretKey: secretKey2, derivedKey: derivedKey2 } = await getExistingEncryptionMaterial(
3984
- params.linkKey,
3985
- params.linkKeyNonce,
3986
- params.ddocId
3987
- );
3988
- if (secretKey2) return { encryptedSecretKey: encryptedSecretKey2, nonce: nonce2, secretKey: secretKey2, derivedKey: derivedKey2 };
3989
- }
3990
- const { secretKey, nonce, encryptedSecretKey, derivedKey } = await getNaclSecretKey(params.ddocId);
3991
- return { secretKey, nonce, encryptedSecretKey, derivedKey };
3992
- };
3993
-
3994
- // src/domain/file/index.ts
3995
3763
  async function listFiles(params) {
3996
3764
  const { limit, skip, portalAddress } = params;
3997
3765
  const effectiveLimit = limit || DEFAULT_LIST_LIMIT;
@@ -4044,20 +3812,11 @@ var createFile = async (input) => {
4044
3812
  throw new Error("title, content, and portalAddress are required");
4045
3813
  }
4046
3814
  const ddocId = generate();
4047
- const { encryptedSecretKey, nonce, secretKey, derivedKey } = await generateLinkKeyMaterial({
4048
- ddocId,
4049
- linkKey: void 0,
4050
- linkKeyNonce: void 0
4051
- });
4052
3815
  const file2 = await FilesModel.create({
4053
3816
  title: input.title,
4054
3817
  content: input.content,
4055
3818
  ddocId,
4056
- portalAddress: input.portalAddress,
4057
- linkKey: encryptedSecretKey,
4058
- linkKeyNonce: fromUint8Array5(nonce),
4059
- derivedKey: fromUint8Array5(derivedKey),
4060
- secretKey: fromUint8Array5(secretKey)
3819
+ portalAddress: input.portalAddress
4061
3820
  });
4062
3821
  await EventsModel.create({ type: "create", fileId: file2._id, portalAddress: file2.portalAddress });
4063
3822
  return file2;
@@ -4869,7 +4628,7 @@ __export(external_exports, {
4869
4628
  e164: () => e1642,
4870
4629
  email: () => email2,
4871
4630
  emoji: () => emoji2,
4872
- encode: () => encode2,
4631
+ encode: () => encode3,
4873
4632
  encodeAsync: () => encodeAsync2,
4874
4633
  endsWith: () => _endsWith,
4875
4634
  enum: () => _enum2,
@@ -5243,7 +5002,7 @@ __export(core_exports2, {
5243
5002
  decode: () => decode,
5244
5003
  decodeAsync: () => decodeAsync,
5245
5004
  describe: () => describe,
5246
- encode: () => encode,
5005
+ encode: () => encode2,
5247
5006
  encodeAsync: () => encodeAsync,
5248
5007
  extractDefs: () => extractDefs,
5249
5008
  finalize: () => finalize,
@@ -6230,7 +5989,7 @@ var _encode = (_Err) => (schema, value, _ctx) => {
6230
5989
  const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" };
6231
5990
  return _parse(_Err)(schema, value, ctx);
6232
5991
  };
6233
- var encode = /* @__PURE__ */ _encode($ZodRealError);
5992
+ var encode2 = /* @__PURE__ */ _encode($ZodRealError);
6234
5993
  var _decode = (_Err) => (schema, value, _ctx) => {
6235
5994
  return _parse(_Err)(schema, value, _ctx);
6236
5995
  };
@@ -16994,7 +16753,7 @@ var parse2 = /* @__PURE__ */ _parse(ZodRealError);
16994
16753
  var parseAsync2 = /* @__PURE__ */ _parseAsync(ZodRealError);
16995
16754
  var safeParse2 = /* @__PURE__ */ _safeParse(ZodRealError);
16996
16755
  var safeParseAsync2 = /* @__PURE__ */ _safeParseAsync(ZodRealError);
16997
- var encode2 = /* @__PURE__ */ _encode(ZodRealError);
16756
+ var encode3 = /* @__PURE__ */ _encode(ZodRealError);
16998
16757
  var decode2 = /* @__PURE__ */ _decode(ZodRealError);
16999
16758
  var encodeAsync2 = /* @__PURE__ */ _encodeAsync(ZodRealError);
17000
16759
  var decodeAsync2 = /* @__PURE__ */ _decodeAsync(ZodRealError);
@@ -17038,7 +16797,7 @@ var ZodType = /* @__PURE__ */ $constructor("ZodType", (inst, def) => {
17038
16797
  inst.parseAsync = async (data, params) => parseAsync2(inst, data, params, { callee: inst.parseAsync });
17039
16798
  inst.safeParseAsync = async (data, params) => safeParseAsync2(inst, data, params);
17040
16799
  inst.spa = inst.safeParseAsync;
17041
- inst.encode = (data, params) => encode2(inst, data, params);
16800
+ inst.encode = (data, params) => encode3(inst, data, params);
17042
16801
  inst.decode = (data, params) => decode2(inst, data, params);
17043
16802
  inst.encodeAsync = async (data, params) => encodeAsync2(inst, data, params);
17044
16803
  inst.decodeAsync = async (data, params) => decodeAsync2(inst, data, params);