@mosadd/mcp 3.0.0-alpha.53 → 3.0.0-alpha.55

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 (51) hide show
  1. package/CHANGELOG.md +53 -0
  2. package/README.md +150 -150
  3. package/dist/bin/mcp.js +1 -1
  4. package/dist/{chunk-AWKITPZQ.js → chunk-IWUGKLDX.js} +144 -33
  5. package/dist/index.js +1 -1
  6. package/package.json +1 -1
  7. package/src/__tests__/blob-upload.test.ts +93 -93
  8. package/src/__tests__/channel-e2ee.test.ts +62 -62
  9. package/src/__tests__/flota-jawnie.test.ts +244 -0
  10. package/src/__tests__/golden-path.test.ts +139 -139
  11. package/src/__tests__/integration.test.ts +182 -182
  12. package/src/__tests__/mdm-e2ee.test.ts +212 -212
  13. package/src/__tests__/mdm-mcp-readable.test.ts +390 -284
  14. package/src/__tests__/mirc-invite.test.ts +112 -112
  15. package/src/__tests__/mtalk.test.ts +122 -122
  16. package/src/__tests__/server.test.ts +71 -71
  17. package/src/__tests__/tool-count-consistency.test.ts +199 -199
  18. package/src/bin/login.ts +138 -138
  19. package/src/bin/mcp.ts +145 -145
  20. package/src/config.ts +66 -66
  21. package/src/crypto/channel-e2ee.ts +288 -288
  22. package/src/crypto/mdm-session.ts +842 -798
  23. package/src/index.ts +19 -19
  24. package/src/observability/sentry.ts +79 -79
  25. package/src/providers/memory-voice.ts +79 -79
  26. package/src/providers/supabase-dm.ts +202 -174
  27. package/src/providers/supabase-voice.ts +91 -91
  28. package/src/server.ts +195 -186
  29. package/src/tools/actions.ts +166 -166
  30. package/src/tools/attachments.ts +276 -276
  31. package/src/tools/capabilities.ts +70 -70
  32. package/src/tools/channel-payload.ts +69 -0
  33. package/src/tools/embed.ts +110 -110
  34. package/src/tools/index.ts +181 -181
  35. package/src/tools/knowledge.ts +344 -344
  36. package/src/tools/mail-aliases.ts +25 -25
  37. package/src/tools/mail-provenance.ts +137 -137
  38. package/src/tools/mail.ts +403 -403
  39. package/src/tools/mdm-as-agent.ts +126 -126
  40. package/src/tools/mdm.ts +140 -45
  41. package/src/tools/mirc-edge.ts +196 -196
  42. package/src/tools/mirc-members.ts +287 -287
  43. package/src/tools/mirc-messages.ts +9 -13
  44. package/src/tools/mirc.ts +308 -308
  45. package/src/tools/mroom-messages.ts +4 -12
  46. package/src/tools/mroom.ts +221 -221
  47. package/src/tools/mtalk.ts +131 -131
  48. package/src/tools/presence.ts +442 -442
  49. package/src/tools/voice-format.ts +28 -28
  50. package/src/types.ts +121 -121
  51. package/src/voice/floor.ts +132 -132
@@ -385,7 +385,16 @@ function sameBytes(a, b) {
385
385
  for (let i = 0; i < a.length; i += 1) if (a[i] !== b[i]) return false;
386
386
  return true;
387
387
  }
388
- async function ensureOwnBundlePublished(keystore, dm, selfId, opts) {
388
+ function bundlePolicyForKind(kind, opts) {
389
+ if (kind === "agent") {
390
+ return opts.explicit ? { mayPublishWhenEmpty: true, mayReplaceForeign: true } : { mayPublishWhenEmpty: false, mayReplaceForeign: false };
391
+ }
392
+ if (kind === "human") {
393
+ return { mayPublishWhenEmpty: opts.explicit, mayReplaceForeign: false };
394
+ }
395
+ return { mayPublishWhenEmpty: true, mayReplaceForeign: opts.explicit };
396
+ }
397
+ async function ensureOwnBundlePublished(keystore, dm, selfId, policy) {
389
398
  const own = await keystore.getOwnMaterial();
390
399
  const raw = await dm.fetchPrekeyBundle(selfId);
391
400
  if (raw) {
@@ -398,7 +407,9 @@ async function ensureOwnBundlePublished(keystore, dm, selfId, opts) {
398
407
  if (published && sameBytes(published.identityPublicKey, own.identity.publicKey) && sameBytes(published.signingIdentityPublicKey, own.signingIdentity.publicKey) && sameBytes(published.signedPrekey.publicKey, own.signedPrekey.pair.publicKey)) {
399
408
  return "consistent";
400
409
  }
401
- if (!opts.mayReplaceForeign) return "foreign";
410
+ if (!policy.mayReplaceForeign) return "foreign";
411
+ } else if (!policy.mayPublishWhenEmpty) {
412
+ return "absent";
402
413
  }
403
414
  await dm.publishPrekeyBundle(serializePublicBundle(own));
404
415
  return "published";
@@ -481,11 +492,6 @@ function parseEnvelopeV2(bytes) {
481
492
  if (obj?.v !== E2EE_ENVELOPE_VERSION_V2) throw new Error(`Unsupported mDM envelope version: ${obj?.v}`);
482
493
  return obj;
483
494
  }
484
- async function publishOwnPrekeys(keystore, dm) {
485
- const material = await keystore.getOwnMaterial();
486
- await dm.publishPrekeyBundle(serializePublicBundle(material));
487
- return { oneTimePrekeyCount: material.oneTimePrekeys.length };
488
- }
489
495
  async function encryptForPeer(keystore, dm, peerId, plaintext) {
490
496
  let session = await keystore.getSession(peerId);
491
497
  if (!session) {
@@ -627,6 +633,7 @@ async function decryptFromPeer(keystore, peerId, envelopeBytes) {
627
633
  // src/providers/supabase-dm.ts
628
634
  var PROTOCOL_VERSION = "mosadd.chat.v1";
629
635
  var MDM_TEXT_MESSAGE_TYPE = "txt";
636
+ var MDM_MCP_SEALED_MESSAGE_TYPE = "text";
630
637
  var SupabaseDmProvider = class {
631
638
  cachedSelfId = null;
632
639
  cachedSelfKind = null;
@@ -639,6 +646,22 @@ var SupabaseDmProvider = class {
639
646
  await this.selfId();
640
647
  return this.cachedSelfKind;
641
648
  }
649
+ /**
650
+ * `identities.kind` of a PEER, or null when it cannot be read (RLS can_see_identity scopes rows
651
+ * to contacts / thread co-members; a miss is not an error). mDM_send uses it exactly like the
652
+ * app's ChatPanel `peerIsAgent` (theirIdent.kind === 'agent' || iAmAgent): a DM to an agent
653
+ * line is sent in the clear, because the line must read it (rozkaz Króla 20.09).
654
+ */
655
+ async peerKind(peerId) {
656
+ try {
657
+ const sb = getSupabase();
658
+ const { data, error } = await sb.from("identities").select("kind").eq("id", peerId).limit(1).maybeSingle();
659
+ if (error || !data) return null;
660
+ return typeof data.kind === "string" ? data.kind : null;
661
+ } catch {
662
+ return null;
663
+ }
664
+ }
642
665
  async selfId() {
643
666
  if (this.cachedSelfId) return this.cachedSelfId;
644
667
  readSupabaseEnv();
@@ -783,24 +806,63 @@ async function selfKindOf(dm) {
783
806
  const f = dm.selfKind;
784
807
  return typeof f === "function" ? await f.call(dm) : null;
785
808
  }
809
+ async function peerKindOf(dm, peerId) {
810
+ const f = dm.peerKind;
811
+ if (typeof f !== "function") return null;
812
+ try {
813
+ return await f.call(dm, peerId);
814
+ } catch {
815
+ return null;
816
+ }
817
+ }
786
818
  async function mDM_send(input, ctx) {
787
819
  const dm = ctx.providers.dm;
788
820
  const selfId = await dm.selfId();
789
821
  const threadId = dmThreadId(selfId, input.to, input.thread_label);
790
822
  const keys = ctx.providers.keys;
823
+ const selfKind = await selfKindOf(dm);
824
+ const noteToSelf = input.to === selfId;
825
+ const peerKind = selfKind === "agent" || noteToSelf ? selfKind : await peerKindOf(dm, input.to);
826
+ if (selfKind === "agent" || peerKind === "agent" || noteToSelf) {
827
+ const payload = packPlaintextPayload(input.text);
828
+ ctx.log("debug", "mDM_send fleet plaintext (rozkaz Krola 20.09 + 28.09)", {
829
+ thread_id: threadId,
830
+ self_kind: selfKind,
831
+ peer_kind: peerKind,
832
+ note_to_self: noteToSelf
833
+ });
834
+ const plainArgs = {
835
+ to: input.to,
836
+ threadId,
837
+ payload,
838
+ replyToId: input.reply_to_id,
839
+ messageType: MDM_TEXT_MESSAGE_TYPE
840
+ };
841
+ const result2 = await dm.send(plainArgs);
842
+ return {
843
+ message_id: result2.id,
844
+ delivered_at: result2.deliveredAt,
845
+ thread_id: threadId,
846
+ encrypted: false,
847
+ mode: "plaintext_agent_lane",
848
+ reason: "fleet_plaintext",
849
+ sender_copy: true,
850
+ recipient_copy: true,
851
+ identity: "untouched"
852
+ };
853
+ }
791
854
  let identity = "foreign";
792
855
  try {
793
- identity = await ensureOwnBundlePublished(keys, dm, selfId, {
794
- mayReplaceForeign: await selfKindOf(dm) === "agent"
795
- });
856
+ identity = await ensureOwnBundlePublished(keys, dm, selfId, bundlePolicyForKind(selfKind, { explicit: false }));
796
857
  } catch (err) {
797
858
  ctx.log("warn", "mDM_send could not reconcile own prekey bundle", { error: String(err) });
798
859
  }
860
+ const ourIdentityIsPublished = identity === "consistent" || identity === "published";
799
861
  const inner = packPlaintextPayload(input.text);
800
862
  const sealed = await encryptForPeer(keys, dm, input.to, inner);
801
- const selfPayload = await sealForSelf(keys, inner);
863
+ const selfPayload = selfKind !== "human" && ourIdentityIsPublished ? await sealForSelf(keys, inner) : null;
802
864
  let recipientSelfPayload = null;
803
- if (identity !== "foreign" && input.to !== selfId) {
865
+ if (ourIdentityIsPublished && input.to !== selfId) {
804
866
  try {
805
867
  const peer = await fetchVerifiedBundle(dm, input.to);
806
868
  if (peer) recipientSelfPayload = await sealForPeerRecoverable(keys, peer, inner);
@@ -820,7 +882,7 @@ async function mDM_send(input, ctx) {
820
882
  threadId,
821
883
  payload: sealed,
822
884
  replyToId: input.reply_to_id,
823
- messageType: MDM_TEXT_MESSAGE_TYPE,
885
+ messageType: MDM_MCP_SEALED_MESSAGE_TYPE,
824
886
  selfPayload,
825
887
  recipientSelfPayload
826
888
  };
@@ -833,6 +895,8 @@ async function mDM_send(input, ctx) {
833
895
  delivered_at: result.deliveredAt,
834
896
  thread_id: threadId,
835
897
  encrypted: true,
898
+ mode: "e2ee",
899
+ reason: "human_to_human",
836
900
  sender_copy: !!selfPayload,
837
901
  recipient_copy: !!recipientSelfPayload,
838
902
  identity
@@ -843,7 +907,7 @@ async function mDM_send_unencrypted(input, ctx) {
843
907
  const selfId = await dm.selfId();
844
908
  const threadId = dmThreadId(selfId, input.to, input.thread_label);
845
909
  const payload = packPlaintextPayload(input.text);
846
- ctx.log("warn", "mDM_send_unencrypted (deprecated, plaintext) via DmProvider", {
910
+ ctx.log("debug", "mDM_send_unencrypted (plaintext) via DmProvider", {
847
911
  thread_id: threadId,
848
912
  bytes: payload.byteLength
849
913
  });
@@ -863,9 +927,26 @@ async function mDM_send_unencrypted(input, ctx) {
863
927
  };
864
928
  }
865
929
  async function mDM_publish_keys(_input, ctx) {
866
- const { oneTimePrekeyCount } = await publishOwnPrekeys(ctx.providers.keys, ctx.providers.dm);
867
- ctx.log("debug", "mDM_publish_keys", { one_time_prekeys: oneTimePrekeyCount });
868
- return { published: true, one_time_prekeys: oneTimePrekeyCount };
930
+ const dm = ctx.providers.dm;
931
+ const keys = ctx.providers.keys;
932
+ const selfId = await dm.selfId();
933
+ const identity = await ensureOwnBundlePublished(
934
+ keys,
935
+ dm,
936
+ selfId,
937
+ bundlePolicyForKind(await selfKindOf(dm), { explicit: true })
938
+ );
939
+ const { oneTimePrekeys } = await keys.getOwnMaterial();
940
+ ctx.log("debug", "mDM_publish_keys", { identity, one_time_prekeys: oneTimePrekeys.length });
941
+ if (identity === "foreign") {
942
+ return {
943
+ published: false,
944
+ identity,
945
+ one_time_prekeys: 0,
946
+ note: "This identity already has keys published by the mosADD app. They were left untouched: replacing them from an API key would make every conversation with you unreadable in the app."
947
+ };
948
+ }
949
+ return { published: identity === "published", identity, one_time_prekeys: oneTimePrekeys.length };
869
950
  }
870
951
  async function mDM_list(input, ctx) {
871
952
  const dm = ctx.providers.dm;
@@ -1026,19 +1107,19 @@ var mdmTools = [
1026
1107
  },
1027
1108
  {
1028
1109
  name: "mDM_send",
1029
- title: "Send encrypted DM",
1110
+ title: "Send DM",
1030
1111
  annotations: { readOnlyHint: false },
1031
1112
  requires: "any",
1032
- description: "Send an END-TO-END-ENCRYPTED direct message via mosadd mDM. Pass `to` as the recipient's mosadd identity_id (look it up with mDM_list_contacts). Establishes an X3DH + Double Ratchet session on first contact (the recipient must have run mDM_publish_keys). Optional thread_label puts the message in a named thread \u2014 mosadd USP: multiple threads per contact, unlike WhatsApp/Telegram. If the recipient has no published keys yet, use mDM_send_unencrypted.",
1113
+ description: 'Send a direct message via mosadd mDM. Conversations with fleet lines and with the King: ALWAYS in the clear \u2014 when either side is an agent line, or you write to yourself, the message goes as plain text (result `encrypted: false, reason: "fleet_plaintext"`), exactly like the mosadd app. Only between two PEOPLE is it END-TO-END-ENCRYPTED (X3DH + Double Ratchet; the recipient must have published keys). Pass `to` as the recipient\'s mosadd identity_id (look it up with mDM_list_contacts). Optional thread_label puts the message in a named thread \u2014 mosadd USP: multiple threads per contact, unlike WhatsApp/Telegram.',
1033
1114
  inputSchema: mDM_send_input,
1034
1115
  handler: mDM_send
1035
1116
  },
1036
1117
  {
1037
1118
  name: "mDM_send_unencrypted",
1038
- title: "Send unencrypted DM",
1119
+ title: "Send plain-text DM",
1039
1120
  annotations: { readOnlyHint: false },
1040
1121
  requires: "any",
1041
- description: "DEPRECATED migration-window fallback: send a direct message WITHOUT end-to-end encryption (plaintext envelope). Only use when the recipient has not yet published prekeys (mDM_send fails with that hint). Prefer mDM_send. Will be removed once E2EE is universal.",
1122
+ description: "Send a direct message as plain text, never encrypted. Conversations with fleet lines and with the King: ALWAYS in the clear \u2014 this is the path for every agent line writing to the King, to another line or to itself, and it is permanent. Pass `to` as the recipient's mosadd identity_id (look it up with mDM_list_contacts); optional thread_label puts it in a named thread. mDM_send picks the same plain-text path by itself whenever a fleet line is a party.",
1042
1123
  inputSchema: mDM_send_input,
1043
1124
  handler: mDM_send_unencrypted
1044
1125
  },
@@ -1813,6 +1894,44 @@ async function decryptChannelPayload(channelId, payloadB64) {
1813
1894
  return decryptWithGroupKey(groupKey, payloadB64);
1814
1895
  }
1815
1896
 
1897
+ // src/tools/channel-payload.ts
1898
+ var CIPHERTEXT_MARKER = "<ciphertext>";
1899
+ var STRICT_BASE64 = /^[A-Za-z0-9+/]*={0,2}$/;
1900
+ var CONTROL_CHARS = /[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/;
1901
+ function isSealedEnvelope(obj) {
1902
+ if (!obj || typeof obj !== "object") return false;
1903
+ const o = obj;
1904
+ if (typeof o.iv === "string" && typeof o.ciphertext === "string") return true;
1905
+ if (typeof o.v === "string" && o.v.startsWith("mosadd.e2ee")) return true;
1906
+ return false;
1907
+ }
1908
+ function decodeStoredPayloadText(payload) {
1909
+ if (typeof payload !== "string" || payload.length === 0) return "";
1910
+ let raw;
1911
+ const compact = payload.replace(/\s+/g, "");
1912
+ if (compact.length % 4 === 0 && STRICT_BASE64.test(compact)) {
1913
+ try {
1914
+ raw = new TextDecoder("utf-8", { fatal: true }).decode(Buffer.from(compact, "base64"));
1915
+ } catch {
1916
+ return CIPHERTEXT_MARKER;
1917
+ }
1918
+ } else {
1919
+ raw = payload;
1920
+ }
1921
+ if (raw.startsWith("{")) {
1922
+ try {
1923
+ const obj = JSON.parse(raw);
1924
+ if (isSealedEnvelope(obj)) return CIPHERTEXT_MARKER;
1925
+ const text = obj?.text;
1926
+ if (typeof text === "string") return text;
1927
+ return raw;
1928
+ } catch {
1929
+ }
1930
+ }
1931
+ if (CONTROL_CHARS.test(raw)) return CIPHERTEXT_MARKER;
1932
+ return raw;
1933
+ }
1934
+
1816
1935
  // src/tools/mirc-messages.ts
1817
1936
  var PROTOCOL_VERSION4 = "mosadd.chat.v1";
1818
1937
  var ChannelId3 = z6.string().min(1).max(120).describe("Channel id (UUID). From mIRC_create / mIRC_list.");
@@ -1841,18 +1960,10 @@ function buildPlaintextEnvelope(text, replyToId) {
1841
1960
  };
1842
1961
  return JSON.stringify(envelope);
1843
1962
  }
1844
- function unpackPayload2(payload) {
1845
- try {
1846
- const obj = JSON.parse(Buffer.from(payload, "base64").toString("utf8"));
1847
- if (typeof obj?.text === "string") return obj;
1848
- } catch {
1849
- }
1850
- return { text: "<ciphertext>" };
1851
- }
1852
1963
  async function payloadToText(channelId, payload) {
1853
1964
  const decrypted = await decryptChannelPayload(channelId, payload);
1854
1965
  if (decrypted !== null) return unwrapEnvelopeText(decrypted);
1855
- return unpackPayload2(payload).text;
1966
+ return decodeStoredPayloadText(payload);
1856
1967
  }
1857
1968
  async function resolveLinkedSpaceId(channelId) {
1858
1969
  const data = await invokeFunction("channel-manage", { action: "get", channel_id: channelId });
@@ -1934,7 +2045,7 @@ var mircMessagesTools = [
1934
2045
  title: "Read channel messages",
1935
2046
  annotations: { readOnlyHint: true },
1936
2047
  requires: "network",
1937
- description: "List recent text messages in a persistent channel (mIRC), newest first, cursor-paginated. Pass channel_id; the backing space is resolved automatically. ENCRYPTION: messages your line can decrypt (group-key channels \u2014 auto-provisioned key material) come back as readable text; anything else falls back to the legacy envelope/plaintext decode.",
2048
+ description: "List recent text messages in a persistent channel (mIRC), newest first, cursor-paginated. Pass channel_id; the backing space is resolved automatically. ENCRYPTION: messages your line can decrypt (group-key channels \u2014 auto-provisioned key material) come back as readable text; everything else is decoded as written: the app's plain text and the toolkit's JSON envelope both come back as readable text (open channels such as #adm and #command are never encrypted). Only a sealed group-key envelope your line holds no key for reads <ciphertext>.",
1938
2049
  inputSchema: mIRC_list_messages_input,
1939
2050
  handler: mIRC_list_messages
1940
2051
  }
@@ -3849,7 +3960,7 @@ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
3849
3960
  // package.json
3850
3961
  var package_default = {
3851
3962
  name: "@mosadd/mcp",
3852
- version: "3.0.0-alpha.53",
3963
+ version: "3.0.0-alpha.55",
3853
3964
  mcpName: "io.github.hei33enberg/mosadd-mcp",
3854
3965
  description: "Model Context Protocol server for mosadd. Exposes 4 modules (mDM, mIRC, mURL, mAYL) and capabilities (mTALK, mRAG) plus comms agent-actions \u2014 85 tools \u2014 to any agent runtime (Claude Code, Cursor, Windsurf, Cline, ChatGPT Apps, Lovable, Bolt, Goose, Manus, custom).",
3855
3966
  homepage: "https://github.com/Hei33enberg/mosADD-OS/tree/main/packages/mcp",
@@ -4012,7 +4123,7 @@ function createMosaddServer(options = {}) {
4012
4123
  void (async () => {
4013
4124
  const selfId = await providers.dm.selfId();
4014
4125
  const kind = await providers.dm.selfKind?.();
4015
- return ensureOwnBundlePublished(providers.keys, providers.dm, selfId, { mayReplaceForeign: kind === "agent" });
4126
+ return ensureOwnBundlePublished(providers.keys, providers.dm, selfId, bundlePolicyForKind(kind, { explicit: false }));
4016
4127
  })().then((state) => ctx.log("debug", "auto-ensure mDM prekeys", { state })).catch((err) => ctx.log("debug", "auto-publish mDM prekeys skipped", { error: String(err) }));
4017
4128
  }
4018
4129
  const server = new McpServer(
package/dist/index.js CHANGED
@@ -4,7 +4,7 @@ import {
4
4
  createMosaddServer,
5
5
  defaultProviders,
6
6
  runWithSupabaseEnv
7
- } from "./chunk-AWKITPZQ.js";
7
+ } from "./chunk-IWUGKLDX.js";
8
8
  import "./chunk-Z7WR52GE.js";
9
9
  export {
10
10
  TOOL_COUNT,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mosadd/mcp",
3
- "version": "3.0.0-alpha.53",
3
+ "version": "3.0.0-alpha.55",
4
4
  "mcpName": "io.github.hei33enberg/mosadd-mcp",
5
5
  "description": "Model Context Protocol server for mosadd. Exposes 4 modules (mDM, mIRC, mURL, mAYL) and capabilities (mTALK, mRAG) plus comms agent-actions — 85 tools — to any agent runtime (Claude Code, Cursor, Windsurf, Cline, ChatGPT Apps, Lovable, Bolt, Goose, Manus, custom).",
6
6
  "homepage": "https://github.com/Hei33enberg/mosADD-OS/tree/main/packages/mcp",
@@ -1,93 +1,93 @@
1
- /**
2
- * LANA PLIKOW — ŻYWA, NIE DOPISANA Z PAMIĘCI (16.09).
3
- *
4
- * Zmierzone PRZED poprawką, na żywym MCP (mcp.mosadd.com), 1 KB text/plain:
5
- * mDM_send_file → "blob upload to file-blobs/dm-…/….txt failed: Bucket not found"
6
- * mDM_send_voice → "blob upload to voice-blobs/dm-…/….webm failed: Bucket not found"
7
- * Buckety `file-blobs` i `voice-blobs` NIE ISTNIEJĄ w projekcie — lista bucketów
8
- * (16.09) to: secure_vault, brand_assets, chat-files, gemstone-models, voice-messages,
9
- * chat-attachments, odyssey-media, raydio-media, voice-samples, mayl-attachments,
10
- * rag-uploads, ptt-recordings, avatars, downloads, orb-media, founder-archive, krol-wrzutki.
11
- *
12
- * Dwa zamki, każdy pilnuje jednej połowy kontraktu z polityką RLS:
13
- * 1. bucket, który istnieje I przyjmie ten JWT (chat-files / voice-messages);
14
- * 2. ścieżka z `auth.uid()` jako PIERWSZYM segmentem, bo obie polityki INSERT
15
- * sprawdzają dokładnie `(storage.foldername(name))[1] = auth.uid()`.
16
- * Ścieżka bez segmentu użytkownika to wysyłka, która ZAWSZE padnie — i padnie
17
- * komunikatem, który nie mówi dlaczego.
18
- */
19
- import { describe, expect, it, vi, beforeEach } from "vitest";
20
-
21
- const SUB = "05261c7d-f34a-4fb2-a0e0-0f85149eb0ce";
22
- const THREAD = "dm-dbe85c4e-ec79-4e9a-a55d-7274e0e3296e-4cd1894d-b878-4fe4-b221-084419f7d225";
23
-
24
- function jwt(sub: string | null): string {
25
- const b64 = (o: unknown) => Buffer.from(JSON.stringify(o)).toString("base64url");
26
- return `${b64({ alg: "HS256", typ: "JWT" })}.${b64(sub ? { sub, role: "authenticated" } : { role: "authenticated" })}.sig`;
27
- }
28
-
29
- /** Co dokładnie poszło do magazynu — jedno miejsce prawdy dla obu zamków. */
30
- let lastCall: { bucket: string; path: string; mime: string } | null = null;
31
- let userJwt: string | undefined = jwt(SUB);
32
-
33
- vi.mock("../providers/supabase.js", () => ({
34
- readSupabaseEnv: () => ({ url: "https://x.supabase.co", anonKey: "anon", userJwt }),
35
- getSupabase: () => ({
36
- storage: {
37
- from: (bucket: string) => ({
38
- upload: async (path: string, _bytes: Uint8Array, opts: { contentType: string }) => {
39
- lastCall = { bucket, path, mime: opts.contentType };
40
- return { error: null };
41
- },
42
- }),
43
- },
44
- }),
45
- }));
46
-
47
- const { uploadBlob, decodeBase64Body } = await import("../providers/blob-upload.js");
48
-
49
- beforeEach(() => { lastCall = null; userJwt = jwt(SUB); });
50
-
51
- describe("blob-upload — bucket i ścieżka, które polityka RLS naprawdę przyjmie", () => {
52
- it("plik idzie do chat-files, a ścieżka zaczyna się od auth.uid()", async () => {
53
- const desc = await uploadBlob({
54
- kind: "file",
55
- bytes: new Uint8Array([1, 2, 3]),
56
- mime: "text/plain",
57
- prefix: THREAD,
58
- filename: "lana-plikow-test.txt",
59
- });
60
-
61
- expect(lastCall!.bucket).toBe("chat-files");
62
- expect(desc.bucket).toBe("chat-files");
63
- const [uid, thread, file] = lastCall!.path.split("/");
64
- expect(uid).toBe(SUB); // ← to sprawdza polityka INSERT
65
- expect(thread).toBe(THREAD);
66
- expect(file).toMatch(/^[0-9a-f-]{36}\.txt$/);
67
- expect(desc.path).toBe(lastCall!.path);
68
- });
69
-
70
- it("głos idzie do voice-messages (nie do nieistniejącego voice-blobs)", async () => {
71
- const desc = await uploadBlob({ kind: "voice", bytes: new Uint8Array([1]), mime: "audio/webm", prefix: THREAD });
72
- expect(lastCall!.bucket).toBe("voice-messages");
73
- expect(desc.bucket).toBe("voice-messages");
74
- expect(lastCall!.path.split("/")[0]).toBe(SUB);
75
- });
76
-
77
- it("ptt też ląduje w buckecie, który istnieje i ma politykę INSERT", async () => {
78
- await uploadBlob({ kind: "ptt", bytes: new Uint8Array([1]), mime: "audio/ogg", prefix: "chat-abc" });
79
- expect(lastCall!.bucket).toBe("voice-messages");
80
- expect(lastCall!.path).toMatch(new RegExp(`^${SUB}/chat-abc/[0-9a-f-]{36}\\.ogg$`));
81
- });
82
-
83
- it("bez JWT użytkownika upload jest ODRZUCONY, zanim poleci bajt", async () => {
84
- userJwt = undefined;
85
- await expect(uploadBlob({ kind: "file", bytes: new Uint8Array([1]), mime: "text/plain" }))
86
- .rejects.toThrow(/auth\.uid\(\)/);
87
- expect(lastCall).toBeNull(); // nic nie poszło do magazynu
88
- });
89
-
90
- it("ścieżka z pamięci przechodzi przez ten sam dekoder base64 (kontrakt narzędzi)", () => {
91
- expect(new TextDecoder().decode(decodeBase64Body("VEVTVCAxNg=="))).toBe("TEST 16");
92
- });
93
- });
1
+ /**
2
+ * LANA PLIKOW — ŻYWA, NIE DOPISANA Z PAMIĘCI (16.09).
3
+ *
4
+ * Zmierzone PRZED poprawką, na żywym MCP (mcp.mosadd.com), 1 KB text/plain:
5
+ * mDM_send_file → "blob upload to file-blobs/dm-…/….txt failed: Bucket not found"
6
+ * mDM_send_voice → "blob upload to voice-blobs/dm-…/….webm failed: Bucket not found"
7
+ * Buckety `file-blobs` i `voice-blobs` NIE ISTNIEJĄ w projekcie — lista bucketów
8
+ * (16.09) to: secure_vault, brand_assets, chat-files, gemstone-models, voice-messages,
9
+ * chat-attachments, odyssey-media, raydio-media, voice-samples, mayl-attachments,
10
+ * rag-uploads, ptt-recordings, avatars, downloads, orb-media, founder-archive, krol-wrzutki.
11
+ *
12
+ * Dwa zamki, każdy pilnuje jednej połowy kontraktu z polityką RLS:
13
+ * 1. bucket, który istnieje I przyjmie ten JWT (chat-files / voice-messages);
14
+ * 2. ścieżka z `auth.uid()` jako PIERWSZYM segmentem, bo obie polityki INSERT
15
+ * sprawdzają dokładnie `(storage.foldername(name))[1] = auth.uid()`.
16
+ * Ścieżka bez segmentu użytkownika to wysyłka, która ZAWSZE padnie — i padnie
17
+ * komunikatem, który nie mówi dlaczego.
18
+ */
19
+ import { describe, expect, it, vi, beforeEach } from "vitest";
20
+
21
+ const SUB = "05261c7d-f34a-4fb2-a0e0-0f85149eb0ce";
22
+ const THREAD = "dm-dbe85c4e-ec79-4e9a-a55d-7274e0e3296e-4cd1894d-b878-4fe4-b221-084419f7d225";
23
+
24
+ function jwt(sub: string | null): string {
25
+ const b64 = (o: unknown) => Buffer.from(JSON.stringify(o)).toString("base64url");
26
+ return `${b64({ alg: "HS256", typ: "JWT" })}.${b64(sub ? { sub, role: "authenticated" } : { role: "authenticated" })}.sig`;
27
+ }
28
+
29
+ /** Co dokładnie poszło do magazynu — jedno miejsce prawdy dla obu zamków. */
30
+ let lastCall: { bucket: string; path: string; mime: string } | null = null;
31
+ let userJwt: string | undefined = jwt(SUB);
32
+
33
+ vi.mock("../providers/supabase.js", () => ({
34
+ readSupabaseEnv: () => ({ url: "https://x.supabase.co", anonKey: "anon", userJwt }),
35
+ getSupabase: () => ({
36
+ storage: {
37
+ from: (bucket: string) => ({
38
+ upload: async (path: string, _bytes: Uint8Array, opts: { contentType: string }) => {
39
+ lastCall = { bucket, path, mime: opts.contentType };
40
+ return { error: null };
41
+ },
42
+ }),
43
+ },
44
+ }),
45
+ }));
46
+
47
+ const { uploadBlob, decodeBase64Body } = await import("../providers/blob-upload.js");
48
+
49
+ beforeEach(() => { lastCall = null; userJwt = jwt(SUB); });
50
+
51
+ describe("blob-upload — bucket i ścieżka, które polityka RLS naprawdę przyjmie", () => {
52
+ it("plik idzie do chat-files, a ścieżka zaczyna się od auth.uid()", async () => {
53
+ const desc = await uploadBlob({
54
+ kind: "file",
55
+ bytes: new Uint8Array([1, 2, 3]),
56
+ mime: "text/plain",
57
+ prefix: THREAD,
58
+ filename: "lana-plikow-test.txt",
59
+ });
60
+
61
+ expect(lastCall!.bucket).toBe("chat-files");
62
+ expect(desc.bucket).toBe("chat-files");
63
+ const [uid, thread, file] = lastCall!.path.split("/");
64
+ expect(uid).toBe(SUB); // ← to sprawdza polityka INSERT
65
+ expect(thread).toBe(THREAD);
66
+ expect(file).toMatch(/^[0-9a-f-]{36}\.txt$/);
67
+ expect(desc.path).toBe(lastCall!.path);
68
+ });
69
+
70
+ it("głos idzie do voice-messages (nie do nieistniejącego voice-blobs)", async () => {
71
+ const desc = await uploadBlob({ kind: "voice", bytes: new Uint8Array([1]), mime: "audio/webm", prefix: THREAD });
72
+ expect(lastCall!.bucket).toBe("voice-messages");
73
+ expect(desc.bucket).toBe("voice-messages");
74
+ expect(lastCall!.path.split("/")[0]).toBe(SUB);
75
+ });
76
+
77
+ it("ptt też ląduje w buckecie, który istnieje i ma politykę INSERT", async () => {
78
+ await uploadBlob({ kind: "ptt", bytes: new Uint8Array([1]), mime: "audio/ogg", prefix: "chat-abc" });
79
+ expect(lastCall!.bucket).toBe("voice-messages");
80
+ expect(lastCall!.path).toMatch(new RegExp(`^${SUB}/chat-abc/[0-9a-f-]{36}\\.ogg$`));
81
+ });
82
+
83
+ it("bez JWT użytkownika upload jest ODRZUCONY, zanim poleci bajt", async () => {
84
+ userJwt = undefined;
85
+ await expect(uploadBlob({ kind: "file", bytes: new Uint8Array([1]), mime: "text/plain" }))
86
+ .rejects.toThrow(/auth\.uid\(\)/);
87
+ expect(lastCall).toBeNull(); // nic nie poszło do magazynu
88
+ });
89
+
90
+ it("ścieżka z pamięci przechodzi przez ten sam dekoder base64 (kontrakt narzędzi)", () => {
91
+ expect(new TextDecoder().decode(decodeBase64Body("VEVTVCAxNg=="))).toBe("TEST 16");
92
+ });
93
+ });
@@ -1,62 +1,62 @@
1
- import { describe, expect, it } from "vitest";
2
- import { generateGroupKey } from "@mosadd/crypto";
3
- import {
4
- decryptWithGroupKey,
5
- encryptWithGroupKey,
6
- signCiphertext,
7
- unwrapEnvelopeText,
8
- } from "../crypto/channel-e2ee.js";
9
-
10
- const envelope = (text: string) =>
11
- JSON.stringify({ v: "mosadd.chat.v1", type: "text", text, reply_to: null, sent_at: new Date().toISOString() });
12
-
13
- describe("channel-e2ee pure core", () => {
14
- it("roundtrip: encrypt → decrypt returns the original text", async () => {
15
- const key = generateGroupKey();
16
- const plain = envelope("Fala 4 żyje");
17
- const payload = await encryptWithGroupKey(key, plain);
18
- expect(typeof payload).toBe("string");
19
- const out = await decryptWithGroupKey(key, payload);
20
- expect(out).toBe(plain);
21
- });
22
-
23
- it("decrypt of a legacy (non-JSON) payload returns null", async () => {
24
- const key = generateGroupKey();
25
- const legacy = Buffer.from(envelope("stara wiadomość"), "utf8").toString("base64");
26
- expect(await decryptWithGroupKey(key, legacy)).toBeNull();
27
- });
28
-
29
- it("tampered ciphertext fails the HMAC check and returns null", async () => {
30
- const key = generateGroupKey();
31
- const payload = await encryptWithGroupKey(key, envelope("nie ruszaj"));
32
- const parsed = JSON.parse(Buffer.from(payload, "base64").toString("utf8")) as {
33
- iv: string;
34
- ciphertext: string;
35
- hmac: string;
36
- };
37
- // flip one character of the ciphertext
38
- parsed.ciphertext = (parsed.ciphertext[0] === "A" ? "B" : "A") + parsed.ciphertext.slice(1);
39
- const tampered = Buffer.from(JSON.stringify(parsed), "utf8").toString("base64");
40
- expect(await decryptWithGroupKey(key, tampered)).toBeNull();
41
- });
42
-
43
- it("wrong key does not decrypt", async () => {
44
- const keyA = generateGroupKey();
45
- const keyB = generateGroupKey();
46
- const payload = await encryptWithGroupKey(keyA, envelope("sekret"));
47
- expect(await decryptWithGroupKey(keyB, payload)).toBeNull();
48
- });
49
-
50
- it("HMAC is over the base64 ciphertext string (app parity 2C)", async () => {
51
- const key = generateGroupKey();
52
- const payload = await encryptWithGroupKey(key, "abc");
53
- const parsed = JSON.parse(Buffer.from(payload, "base64").toString("utf8")) as { ciphertext: string; hmac: string };
54
- expect(parsed.hmac).toBe(signCiphertext(key, parsed.ciphertext));
55
- });
56
-
57
- it("unwrapEnvelopeText unwraps toolkit envelopes and leaves raw text", () => {
58
- expect(unwrapEnvelopeText(envelope("witaj"))).toBe("witaj");
59
- expect(unwrapEnvelopeText("zwykły tekst")).toBe("zwykły tekst");
60
- expect(unwrapEnvelopeText('{"audio":"AAAA"}')).toBe('{"audio":"AAAA"}');
61
- });
62
- });
1
+ import { describe, expect, it } from "vitest";
2
+ import { generateGroupKey } from "@mosadd/crypto";
3
+ import {
4
+ decryptWithGroupKey,
5
+ encryptWithGroupKey,
6
+ signCiphertext,
7
+ unwrapEnvelopeText,
8
+ } from "../crypto/channel-e2ee.js";
9
+
10
+ const envelope = (text: string) =>
11
+ JSON.stringify({ v: "mosadd.chat.v1", type: "text", text, reply_to: null, sent_at: new Date().toISOString() });
12
+
13
+ describe("channel-e2ee pure core", () => {
14
+ it("roundtrip: encrypt → decrypt returns the original text", async () => {
15
+ const key = generateGroupKey();
16
+ const plain = envelope("Fala 4 żyje");
17
+ const payload = await encryptWithGroupKey(key, plain);
18
+ expect(typeof payload).toBe("string");
19
+ const out = await decryptWithGroupKey(key, payload);
20
+ expect(out).toBe(plain);
21
+ });
22
+
23
+ it("decrypt of a legacy (non-JSON) payload returns null", async () => {
24
+ const key = generateGroupKey();
25
+ const legacy = Buffer.from(envelope("stara wiadomość"), "utf8").toString("base64");
26
+ expect(await decryptWithGroupKey(key, legacy)).toBeNull();
27
+ });
28
+
29
+ it("tampered ciphertext fails the HMAC check and returns null", async () => {
30
+ const key = generateGroupKey();
31
+ const payload = await encryptWithGroupKey(key, envelope("nie ruszaj"));
32
+ const parsed = JSON.parse(Buffer.from(payload, "base64").toString("utf8")) as {
33
+ iv: string;
34
+ ciphertext: string;
35
+ hmac: string;
36
+ };
37
+ // flip one character of the ciphertext
38
+ parsed.ciphertext = (parsed.ciphertext[0] === "A" ? "B" : "A") + parsed.ciphertext.slice(1);
39
+ const tampered = Buffer.from(JSON.stringify(parsed), "utf8").toString("base64");
40
+ expect(await decryptWithGroupKey(key, tampered)).toBeNull();
41
+ });
42
+
43
+ it("wrong key does not decrypt", async () => {
44
+ const keyA = generateGroupKey();
45
+ const keyB = generateGroupKey();
46
+ const payload = await encryptWithGroupKey(keyA, envelope("sekret"));
47
+ expect(await decryptWithGroupKey(keyB, payload)).toBeNull();
48
+ });
49
+
50
+ it("HMAC is over the base64 ciphertext string (app parity 2C)", async () => {
51
+ const key = generateGroupKey();
52
+ const payload = await encryptWithGroupKey(key, "abc");
53
+ const parsed = JSON.parse(Buffer.from(payload, "base64").toString("utf8")) as { ciphertext: string; hmac: string };
54
+ expect(parsed.hmac).toBe(signCiphertext(key, parsed.ciphertext));
55
+ });
56
+
57
+ it("unwrapEnvelopeText unwraps toolkit envelopes and leaves raw text", () => {
58
+ expect(unwrapEnvelopeText(envelope("witaj"))).toBe("witaj");
59
+ expect(unwrapEnvelopeText("zwykły tekst")).toBe("zwykły tekst");
60
+ expect(unwrapEnvelopeText('{"audio":"AAAA"}')).toBe('{"audio":"AAAA"}');
61
+ });
62
+ });