@agentvault/secure-channel 0.6.12 → 0.6.13

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
@@ -2,6 +2,9 @@
2
2
  import { EventEmitter } from "node:events";
3
3
  import { createServer } from "node:http";
4
4
  import { randomUUID } from "node:crypto";
5
+ import { writeFile as writeFile2, mkdir as mkdir2 } from "node:fs/promises";
6
+ import { join as join2 } from "node:path";
7
+ import { readFile as readFile2 } from "node:fs/promises";
5
8
 
6
9
  // ../../node_modules/libsodium-sumo/dist/modules-sumo-esm/libsodium-sumo.mjs
7
10
  var __filename;
@@ -44918,6 +44921,39 @@ var DoubleRatchet = class _DoubleRatchet {
44918
44921
  }
44919
44922
  };
44920
44923
 
44924
+ // ../crypto/dist/file-crypto.js
44925
+ function encryptFile(plainData) {
44926
+ const fileKey = libsodium_wrappers_default.randombytes_buf(libsodium_wrappers_default.crypto_aead_xchacha20poly1305_ietf_KEYBYTES);
44927
+ const fileNonce = libsodium_wrappers_default.randombytes_buf(libsodium_wrappers_default.crypto_aead_xchacha20poly1305_ietf_NPUBBYTES);
44928
+ const encryptedData = libsodium_wrappers_default.crypto_aead_xchacha20poly1305_ietf_encrypt(
44929
+ plainData,
44930
+ null,
44931
+ // no additional data
44932
+ null,
44933
+ // secret nonce (unused)
44934
+ fileNonce,
44935
+ fileKey
44936
+ );
44937
+ const digestBytes = libsodium_wrappers_default.crypto_generichash(32, encryptedData);
44938
+ const digest = libsodium_wrappers_default.to_hex(digestBytes);
44939
+ return { encryptedData, fileKey, fileNonce, digest };
44940
+ }
44941
+ function decryptFile(encryptedData, fileKey, fileNonce) {
44942
+ return libsodium_wrappers_default.crypto_aead_xchacha20poly1305_ietf_decrypt(
44943
+ null,
44944
+ // secret nonce (unused)
44945
+ encryptedData,
44946
+ null,
44947
+ // no additional data
44948
+ fileNonce,
44949
+ fileKey
44950
+ );
44951
+ }
44952
+ function computeFileDigest(data) {
44953
+ const digestBytes = libsodium_wrappers_default.crypto_generichash(32, data);
44954
+ return libsodium_wrappers_default.to_hex(digestBytes);
44955
+ }
44956
+
44921
44957
  // src/crypto-helpers.ts
44922
44958
  function hexToBytes(hex) {
44923
44959
  return libsodium_wrappers_default.from_hex(hex);
@@ -45239,7 +45275,11 @@ var SecureChannel = class _SecureChannel extends EventEmitter {
45239
45275
  res.end(JSON.stringify({ ok: false, error: "Missing 'text' field" }));
45240
45276
  return;
45241
45277
  }
45242
- await this.send(text, { topicId: parsed.topicId });
45278
+ if (parsed.file_path && typeof parsed.file_path === "string") {
45279
+ await this.sendWithAttachment(text, parsed.file_path, { topicId: parsed.topicId });
45280
+ } else {
45281
+ await this.send(text, { topicId: parsed.topicId });
45282
+ }
45243
45283
  res.writeHead(200, { "Content-Type": "application/json" });
45244
45284
  res.end(JSON.stringify({ ok: true }));
45245
45285
  } catch (err) {
@@ -45592,10 +45632,14 @@ var SecureChannel = class _SecureChannel extends EventEmitter {
45592
45632
  }
45593
45633
  let messageText;
45594
45634
  let messageType;
45635
+ let attachmentInfo = null;
45595
45636
  try {
45596
45637
  const parsed = JSON.parse(plaintext);
45597
45638
  messageType = parsed.type || "message";
45598
45639
  messageText = parsed.text || plaintext;
45640
+ if (parsed.attachment) {
45641
+ attachmentInfo = parsed.attachment;
45642
+ }
45599
45643
  } catch {
45600
45644
  messageType = "message";
45601
45645
  messageText = plaintext;
@@ -45608,15 +45652,29 @@ var SecureChannel = class _SecureChannel extends EventEmitter {
45608
45652
  }
45609
45653
  if (messageType === "message") {
45610
45654
  const topicId = msgData.topic_id;
45655
+ let attachmentPath;
45656
+ if (attachmentInfo) {
45657
+ try {
45658
+ attachmentPath = await this._downloadAndDecryptAttachment(attachmentInfo);
45659
+ } catch (err) {
45660
+ console.error(`[SecureChannel] Failed to download attachment:`, err);
45661
+ }
45662
+ }
45611
45663
  this._appendHistory("owner", messageText, topicId);
45664
+ let emitText = messageText;
45665
+ if (attachmentPath) {
45666
+ emitText = `[Attachment: ${attachmentInfo.filename} saved to ${attachmentPath}]
45667
+
45668
+ ${messageText}`;
45669
+ }
45612
45670
  const metadata = {
45613
45671
  messageId: msgData.message_id,
45614
45672
  conversationId: convId,
45615
45673
  timestamp: msgData.created_at,
45616
45674
  topicId
45617
45675
  };
45618
- this.emit("message", messageText, metadata);
45619
- this.config.onMessage?.(messageText, metadata);
45676
+ this.emit("message", emitText, metadata);
45677
+ this.config.onMessage?.(emitText, metadata);
45620
45678
  await this._relaySyncToSiblings(convId, session.ownerDeviceId, messageText, topicId);
45621
45679
  }
45622
45680
  if (this._persisted) {
@@ -45624,6 +45682,111 @@ var SecureChannel = class _SecureChannel extends EventEmitter {
45624
45682
  }
45625
45683
  await this._persistState();
45626
45684
  }
45685
+ /**
45686
+ * Download an encrypted attachment blob, decrypt it, verify integrity,
45687
+ * and save the plaintext file to disk.
45688
+ */
45689
+ async _downloadAndDecryptAttachment(info) {
45690
+ const attachDir = join2(this.config.dataDir, "attachments");
45691
+ await mkdir2(attachDir, { recursive: true });
45692
+ const url = `${this.config.apiUrl}${info.blobUrl}`;
45693
+ const res = await fetch(url, {
45694
+ headers: { Authorization: `Bearer ${this._deviceJwt}` }
45695
+ });
45696
+ if (!res.ok) {
45697
+ throw new Error(`Attachment download failed: ${res.status}`);
45698
+ }
45699
+ const buffer = await res.arrayBuffer();
45700
+ const encryptedData = new Uint8Array(buffer);
45701
+ const digest = computeFileDigest(encryptedData);
45702
+ if (digest !== info.digest) {
45703
+ throw new Error("Attachment digest mismatch \u2014 possible tampering");
45704
+ }
45705
+ const fileKey = base64ToBytes(info.fileKey);
45706
+ const fileNonce = base64ToBytes(info.fileNonce);
45707
+ const decrypted = decryptFile(encryptedData, fileKey, fileNonce);
45708
+ const filePath = join2(attachDir, info.filename);
45709
+ await writeFile2(filePath, decrypted);
45710
+ console.log(`[SecureChannel] Attachment saved: ${filePath} (${decrypted.length} bytes)`);
45711
+ return filePath;
45712
+ }
45713
+ /**
45714
+ * Upload an attachment file: encrypt, upload to server, return metadata
45715
+ * for inclusion in the message envelope.
45716
+ */
45717
+ async _uploadAttachment(filePath, conversationId) {
45718
+ const data = await readFile2(filePath);
45719
+ const plainData = new Uint8Array(data);
45720
+ const result = encryptFile(plainData);
45721
+ const { Blob: NodeBlob, FormData: NodeFormData } = await import("node:buffer").then(
45722
+ () => globalThis
45723
+ );
45724
+ const formData = new FormData();
45725
+ formData.append("conversation_id", conversationId);
45726
+ formData.append(
45727
+ "file",
45728
+ new Blob([result.encryptedData.buffer], { type: "application/octet-stream" }),
45729
+ "attachment.bin"
45730
+ );
45731
+ const res = await fetch(`${this.config.apiUrl}/api/v1/attachments/upload`, {
45732
+ method: "POST",
45733
+ headers: { Authorization: `Bearer ${this._deviceJwt}` },
45734
+ body: formData
45735
+ });
45736
+ if (!res.ok) {
45737
+ const detail = await res.text();
45738
+ throw new Error(`Attachment upload failed (${res.status}): ${detail}`);
45739
+ }
45740
+ const resp = await res.json();
45741
+ const filename = filePath.split("/").pop() || "file";
45742
+ return {
45743
+ blobId: resp.blob_id,
45744
+ blobUrl: resp.blob_url,
45745
+ fileKey: bytesToBase64(result.fileKey),
45746
+ fileNonce: bytesToBase64(result.fileNonce),
45747
+ digest: result.digest,
45748
+ filename,
45749
+ mime: "application/octet-stream",
45750
+ size: plainData.length
45751
+ };
45752
+ }
45753
+ /**
45754
+ * Send a message with an attached file. Encrypts the file, uploads it,
45755
+ * then sends the envelope with attachment metadata via Double Ratchet.
45756
+ */
45757
+ async sendWithAttachment(plaintext, filePath, options) {
45758
+ if (this._state !== "ready" || this._sessions.size === 0 || !this._ws) {
45759
+ throw new Error("Channel is not ready");
45760
+ }
45761
+ const topicId = options?.topicId ?? this._persisted?.defaultTopicId;
45762
+ const attachMeta = await this._uploadAttachment(filePath, this._primaryConversationId);
45763
+ const envelope = JSON.stringify({
45764
+ type: "message",
45765
+ text: plaintext,
45766
+ topicId,
45767
+ attachment: attachMeta
45768
+ });
45769
+ this._appendHistory("agent", plaintext, topicId);
45770
+ const messageGroupId = randomUUID();
45771
+ for (const [convId, session] of this._sessions) {
45772
+ if (!session.activated) continue;
45773
+ const encrypted = session.ratchet.encrypt(envelope);
45774
+ const transport = encryptedMessageToTransport(encrypted);
45775
+ this._ws.send(
45776
+ JSON.stringify({
45777
+ event: "message",
45778
+ data: {
45779
+ conversation_id: convId,
45780
+ header_blob: transport.header_blob,
45781
+ ciphertext: transport.ciphertext,
45782
+ message_group_id: messageGroupId,
45783
+ topic_id: topicId
45784
+ }
45785
+ })
45786
+ );
45787
+ }
45788
+ await this._persistState();
45789
+ }
45627
45790
  /**
45628
45791
  * Relay an owner's message to all sibling sessions as encrypted sync messages.
45629
45792
  * This allows all owner devices to see messages from any single device.