@mosadd/mcp 3.0.0-alpha.7 → 3.0.1

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 (68) hide show
  1. package/CHANGELOG.md +415 -0
  2. package/LICENSE +21 -201
  3. package/README.md +79 -40
  4. package/dist/bin/mcp.js +132 -8
  5. package/dist/chunk-J2S44U5R.js +4258 -0
  6. package/dist/index.d.ts +112 -8
  7. package/dist/index.js +3 -1
  8. package/package.json +19 -16
  9. package/src/__tests__/blob-upload.test.ts +93 -0
  10. package/src/__tests__/channel-e2ee.test.ts +62 -0
  11. package/src/__tests__/cli.test.ts +47 -0
  12. package/src/__tests__/fleet-plaintext.test.ts +243 -0
  13. package/src/__tests__/golden-path.test.ts +4 -2
  14. package/src/__tests__/integration.test.ts +50 -11
  15. package/src/__tests__/knowledge-ingest.test.ts +114 -0
  16. package/src/__tests__/label-room-owner.test.ts +22 -0
  17. package/src/__tests__/mdm-e2ee.test.ts +36 -2
  18. package/src/__tests__/mdm-mcp-readable.test.ts +390 -0
  19. package/src/__tests__/mirc-invite.test.ts +112 -0
  20. package/src/__tests__/mirc-voice.test.ts +82 -0
  21. package/src/__tests__/mrag-search-answer.test.ts +42 -0
  22. package/src/__tests__/mrag-search-diagnostics.test.ts +78 -0
  23. package/src/__tests__/no-dead-host.test.ts +37 -0
  24. package/src/__tests__/presence.test.ts +199 -0
  25. package/src/__tests__/server.test.ts +11 -7
  26. package/src/__tests__/serverJsonVersion.test.ts +45 -0
  27. package/src/__tests__/tool-count-consistency.test.ts +259 -0
  28. package/src/__tests__/voice-fields.test.ts +24 -0
  29. package/src/bin/mcp.ts +71 -6
  30. package/src/cli.ts +100 -0
  31. package/src/crypto/channel-e2ee.ts +288 -0
  32. package/src/crypto/mdm-session.ts +479 -40
  33. package/src/index.ts +2 -2
  34. package/src/providers/blob-upload.ts +162 -0
  35. package/src/providers/supabase-dm.ts +102 -7
  36. package/src/providers/supabase-voice.ts +13 -1
  37. package/src/providers/supabase.ts +121 -10
  38. package/src/server.ts +102 -12
  39. package/src/tools/__tests__/ragDeleteFoldsSourceId.test.ts +67 -0
  40. package/src/tools/actions.ts +166 -0
  41. package/src/tools/attachments.ts +276 -0
  42. package/src/tools/capabilities.ts +2 -0
  43. package/src/tools/channel-payload.ts +69 -0
  44. package/src/tools/embed.ts +110 -0
  45. package/src/tools/index.ts +136 -6
  46. package/src/tools/knowledge-graph.ts +186 -0
  47. package/src/tools/knowledge.ts +205 -12
  48. package/src/tools/mail-agentbox.ts +155 -0
  49. package/src/tools/mail-aliases.ts +25 -0
  50. package/src/tools/mail-provenance.ts +137 -0
  51. package/src/tools/mail.ts +214 -60
  52. package/src/tools/mdm-as-agent.ts +137 -0
  53. package/src/tools/mdm-voice.ts +17 -3
  54. package/src/tools/mdm.ts +306 -58
  55. package/src/tools/mirc-edge.ts +12 -6
  56. package/src/tools/mirc-members.ts +130 -20
  57. package/src/tools/mirc-messages.ts +109 -40
  58. package/src/tools/mirc.ts +149 -11
  59. package/src/tools/mroom-messages.ts +5 -13
  60. package/src/tools/mtalk.ts +11 -1
  61. package/src/tools/murl.ts +314 -0
  62. package/src/tools/presence.ts +442 -0
  63. package/src/tools/ptt-ingest.ts +99 -0
  64. package/src/tools/threat.ts +123 -0
  65. package/src/tools/voice-format.ts +66 -0
  66. package/src/types.ts +36 -0
  67. package/src/version.ts +8 -0
  68. package/dist/chunk-EFTB743G.js +0 -1924
package/dist/index.d.ts CHANGED
@@ -1,10 +1,10 @@
1
1
  import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
2
2
  import { z } from 'zod';
3
3
  import { DmProvider, VoiceProvider } from '@mosadd/providers';
4
- import { RatchetState, SessionRole } from '@mosadd/crypto';
4
+ import { RatchetState, DhRatchetState, SessionRole } from '@mosadd/crypto';
5
5
 
6
6
  /**
7
- * mDM end-to-end encryption — session layer (LINEAR-2357).
7
+ * mDM end-to-end encryption — session layer.
8
8
  *
9
9
  * Sits ABOVE the DmProvider. The provider moves opaque bytes; THIS module
10
10
  * decides what those bytes are: an X3DH handshake + Double Ratchet ciphertext
@@ -18,7 +18,7 @@ import { RatchetState, SessionRole } from '@mosadd/crypto';
18
18
  * run X3DH (responder) and derive the SAME root key.
19
19
  * - Subsequent messages reuse the stored ratchet session (no header).
20
20
  *
21
- * SCOPE / known follow-ups (tracked on LINEAR-2357, NOT silently hidden):
21
+ * SCOPE / known follow-ups (tracked, NOT silently hidden):
22
22
  * - Ratchet is strict in-order (no skipped-message keys) — fine for a single
23
23
  * ordered thread; out-of-order/lossy transports need skipped-key handling.
24
24
  * - Signed-prekey signature is carried but NOT yet verified (auth follow-up).
@@ -53,9 +53,14 @@ interface OwnPrekeyMaterial {
53
53
  pair: X25519Pair;
54
54
  }>;
55
55
  }
56
- /** Persisted per-peer ratchet session. Plain data → trivially serializable. */
56
+ /**
57
+ * Persisted per-peer ratchet session. Plain data → trivially serializable.
58
+ * A session is either v1 (`ratchet`, symmetric) or v2 (`ratchet2`, DH ratchet /
59
+ * PCS). New sessions are v2; an existing v1 session keeps running v1.
60
+ */
57
61
  interface MdmSessionRecord {
58
- ratchet: RatchetState;
62
+ ratchet?: RatchetState;
63
+ ratchet2?: DhRatchetState;
59
64
  role: SessionRole;
60
65
  /** Handshake header still owed to the peer (initiator only, until first send). */
61
66
  pendingHandshake?: {
@@ -90,6 +95,14 @@ interface MdmKeyStore {
90
95
  */
91
96
  putSentMessage?(messageId: string, plaintext: Uint8Array): Promise<void>;
92
97
  getSentMessage?(messageId: string): Promise<Uint8Array | undefined>;
98
+ /**
99
+ * OPTIONAL symmetric SELF-READ key (32 bytes), derived from the same recoverable
100
+ * seed as the identity. Present only on seed-backed keystores. With it the sender
101
+ * seals a copy of every outgoing DM to itself (`self_payload`, tag "s1.") that any
102
+ * process holding the same seed can open again — the cross-process answer to the
103
+ * "local sent-items cache only" note above. Null/absent = no self copy.
104
+ */
105
+ getSelfKeyBytes?(): Promise<Uint8Array | null>;
93
106
  }
94
107
 
95
108
  /**
@@ -131,6 +144,15 @@ interface MosaddServerOptions {
131
144
  * network adapter. A carrier-aware host supplies e.g. a radio DmProvider here.
132
145
  */
133
146
  providers?: Partial<ProviderRegistry>;
147
+ /**
148
+ * When true, publish this identity's mDM prekey bundle once on startup
149
+ * (best-effort, non-fatal) so peers can open an E2EE session without the user
150
+ * manually running mDM_publish_keys first. Fixes the cold-start where mDM_send
151
+ * fails for every recipient because nobody has published keys. Used by the
152
+ * stdio binary; the hosted per-request transport leaves this off (it publishes
153
+ * per authenticated session instead).
154
+ */
155
+ autoPublishKeys?: boolean;
134
156
  }
135
157
  interface MosaddToolContext {
136
158
  options: Required<Pick<MosaddServerOptions, "mode" | "hubUrl">> & MosaddServerOptions;
@@ -153,11 +175,37 @@ interface MosaddToolContext {
153
175
  * join links, bridges). NOT available off-grid.
154
176
  */
155
177
  type CapabilityRequirement = "any" | "radio" | "network";
178
+ /**
179
+ * MCP tool annotations (spec `ToolAnnotations`, minus `title` which lives on the
180
+ * tool itself). Connector UIs — Claude's included — group and gate tools by these
181
+ * hints: `readOnlyHint: true` lands the tool in the read-only bucket (bulk-approvable),
182
+ * `destructiveHint: true` marks it as destroying/overwriting user data at approval
183
+ * time, and tools with NO annotations all fall into one flat "Other tools" bucket —
184
+ * which is exactly how the mosADD connector looked until 2026-08-26 (84 tools, one
185
+ * undifferentiated list; founder order: fix it).
186
+ */
187
+ interface MosaddToolAnnotations {
188
+ /** Tool does not mutate anything. list/get/search/state/metrics class. */
189
+ readOnlyHint?: boolean;
190
+ /** Tool destroys or irreversibly overwrites data (delete/ban/revoke/edit-in-place). */
191
+ destructiveHint?: boolean;
192
+ /** Calling twice with the same args has no additional effect. */
193
+ idempotentHint?: boolean;
194
+ /** Tool reaches outside the mosADD closed world (e.g. sends external email). */
195
+ openWorldHint?: boolean;
196
+ }
156
197
  interface MosaddTool<TInput = unknown, TOutput = unknown> {
157
198
  /** Tool name. MUST follow the m{MODULE}_{operation} convention. */
158
199
  name: string;
200
+ /**
201
+ * Human title for connector UIs (e.g. "Send encrypted DM"). The `name` stays the
202
+ * model-facing handle; this is what a PERSON sees in the permissions list.
203
+ */
204
+ title?: string;
159
205
  /** Short human-readable description. Shown to the model. */
160
206
  description: string;
207
+ /** MCP annotations; see MosaddToolAnnotations. Every registered tool SHOULD set them. */
208
+ annotations?: MosaddToolAnnotations;
161
209
  /**
162
210
  * Transport this tool requires. Consuming hosts read this to gate tools by
163
211
  * available carriers. Every tool MUST declare it explicitly.
@@ -180,19 +228,73 @@ interface MosaddTool<TInput = unknown, TOutput = unknown> {
180
228
  * adapters are named — both `createMosaddServer` and the `@mosadd/ai` adapters
181
229
  * build their context through it so they stay in lockstep.
182
230
  */
183
- declare function defaultProviders(injected?: Partial<ProviderRegistry>): ProviderRegistry;
231
+ declare function defaultProviders(injected?: Partial<ProviderRegistry>, opts?: {
232
+ mdmSecret?: string;
233
+ }): ProviderRegistry;
184
234
  declare function createMosaddServer(options?: MosaddServerOptions): McpServer;
185
235
 
186
236
  /**
187
237
  * Tool registry. Each m* module contributes a set of tools.
188
238
  *
189
- * Live modules (6): mDM, mIRC, mROOM, mTALK, mAIL, mRAG — 57 tools + comms_capabilities.
239
+ * User-facing modules (4): mDM, mIRC, mURL, mAYL — the re-arch
240
+ * mAYL replaces the old mp0st name (mp0st_* still registered as back-compat
241
+ * aliases via mail-aliases.ts; will be removed in a later alpha).
242
+ *
243
+ * Capabilities (not modules — cross-cutting agent tooling): mRAG, comms_.
244
+ * mTALK = voice tier inside mIRC, still its own tools for now; folding into
245
+ * mIRC_voice_* in a follow-up release. threat_* (threat_catalog + threat_classify)
246
+ * are REGISTERED (2026-07-15, founder directive): pure/offline
247
+ * defensive classification over the threat taxonomy — the surveillance-era
248
+ * *marketing* was killed, the classification engine is real and wanted.
249
+ *
250
+ * 85 callable tools registered — the exact live count is exported as TOOL_COUNT
251
+ * (= allTools.length) below; ALWAYS reference that, never re-hard-code a number that drifts.
252
+ * Breakdown (2026-09-03, from allTools in this tree; the live tools/list on mcp.mosadd.com catches up
253
+ * when the alpha carrying mIRC_invite is published and the gateway redeployed):
254
+ * modules mDM 16 · mIRC 25 · mURL 7 · mAYL 16 = 64; capabilities mTALK 6 · mRAG 8 ·
255
+ * comms 5 (action_create/action_frame_get/embed_create/capabilities/session_attach) · Irondome/threat 2
256
+ * = 21. 64 + 21 = 85. (mIRC 25 = 24 + mIRC_invite added 2026-09-03: mIRC_join adds the KEY's
257
+ * identity while channel posts are signed by the AGENT, so every channel created from the toolkit was mute
258
+ * until its agent was added from the app — mIRC_invite wraps channel-members-manage `invite`: own agent →
259
+ * auto_joined, anyone else → invite code. mDM 16 = 14 + mDM_send_as_agent/mDM_list_my_agents added 2026-08-17: an MCP key
260
+ * is bound to a USER, so an agent runtime wired up with its owner's key spoke AS THE OWNER — these
261
+ * let it speak as an agent it OWNS instead, checked server-side. mRAG 8 = 4 search/ingest + 4 mRAG_graph_* traversal tools added 2026-08-11.
262
+ * comms_session_attach added 2026-08-14: a live agent session claims the account's reply lane so
263
+ * the cloud stand-in defers to it — the front door that used to be a script on one PC.)
264
+ * (History of this line drifting: the 2026-07-17 breakdown ended "= 69"
265
+ * — wrong twice over, its own terms summed to 71; the 07-30 rewrite said 73 and still had
266
+ * mAYL at 12 after mAYL_send_as_agent had been re-registered, so it stayed wrong through the
267
+ * four mAYL_agentbox_* tools landing on 08-06. Arithmetic in comments drifts; TOOL_COUNT
268
+ * doesn't — and since 08-11 the anti-drift gate checks the PER-MODULE numbers too, not just
269
+ * the total, so this comment cannot rot alone any more.)
270
+ * (mDM/mIRC each include their 2 attachment tools from attachments.ts.)
271
+ * Modules (4): mDM, mIRC, mURL, mAYL. Capabilities: mTALK (voice/PTT), mRAG, comms_, Irondome (threat_*).
272
+ * mp0st_* stay as DEPRECATED back-compat aliases for mAYL_* (removed in a later alpha).
273
+ * mAYL_send_as_agent + mTALK_ingest_ptt were RE-REGISTERED 2026-07-29: both had been disabled
274
+ * on 07-14 notes that had since become false, and both were re-verified on authenticated calls.
275
+ * comms_embed_create RE-REGISTERED 2026-07-17 (embed.mosadd.com/v1.js live — P3 of mURL→mIRC).
276
+ * mROOM was KILLED (channel re-cut → ephemeral private mIRC): its tools
277
+ * live in tools/mroom.ts + mroom-messages.ts but are NOT registered here.
278
+ * Plus action links: comms_action_create (agent → user one-link browser action,
279
+ * incl. screen_share) + comms_action_frame_get (see the recipient's shared screen).
280
+ * mURL is a FULL registered dev module (revived, founder 2026-06-27) — IRC-for-URLs,
281
+ * agent-native; backends live (mosadd-edge + murl-channels EF). tools/murl.ts.
282
+ * mURL now has full lifecycle: read/post/presence/list_channels (hub-key) PLUS owner-side
283
+ * create/claim + update(branding/status) + delete (mURL_create/update/delete → murl-manage
284
+ * EF, owner-scoped via user JWT — same auth as mURL_list_channels action='mine').
190
285
  * mCALL is carrier-pending (no telephony carrier live yet): its tools live in
191
286
  * tools/mcall.ts but are NOT registered here, so an agent only ever discovers
192
287
  * tools that actually work. Re-register the one line below when a carrier ships.
193
288
  */
194
289
 
195
290
  declare const allTools: MosaddTool[];
291
+ /**
292
+ * The exact, live number of callable tools this server registers. Reference THIS
293
+ * (import { TOOL_COUNT }) in any code/doc surface that shows a tool count, instead
294
+ * of hard-coding a number that silently drifts (the "70+/65/68" inconsistency that
295
+ * bit us). Mirrors @mosadd/threat-engine's THREAT_EVENT_COUNT pattern.
296
+ */
297
+ declare const TOOL_COUNT: number;
196
298
 
197
299
  /**
198
300
  * Supabase provider for the alpha MCP server.
@@ -209,8 +311,10 @@ interface SupabaseEnv {
209
311
  url: string;
210
312
  anonKey: string;
211
313
  userJwt?: string;
314
+ /** Stabilna tożsamość sesji dla bramy hostowanej (per klucz API) — patrz sessionId(). */
315
+ sessionKey?: string;
212
316
  }
213
317
  /** Run `fn` (and every tool call it triggers) with a per-request Supabase session. */
214
318
  declare function runWithSupabaseEnv<T>(env: SupabaseEnv, fn: () => T): T;
215
319
 
216
- export { type MosaddServerOptions, type MosaddTool, type MosaddToolContext, type ProviderRegistry, type SupabaseEnv, allTools, createMosaddServer, defaultProviders, runWithSupabaseEnv };
320
+ export { type MosaddServerOptions, type MosaddTool, type MosaddToolContext, type ProviderRegistry, type SupabaseEnv, TOOL_COUNT, allTools, createMosaddServer, defaultProviders, runWithSupabaseEnv };
package/dist/index.js CHANGED
@@ -1,11 +1,13 @@
1
1
  import {
2
+ TOOL_COUNT,
2
3
  allTools,
3
4
  createMosaddServer,
4
5
  defaultProviders,
5
6
  runWithSupabaseEnv
6
- } from "./chunk-EFTB743G.js";
7
+ } from "./chunk-J2S44U5R.js";
7
8
  import "./chunk-Z7WR52GE.js";
8
9
  export {
10
+ TOOL_COUNT,
9
11
  allTools,
10
12
  createMosaddServer,
11
13
  defaultProviders,
package/package.json CHANGED
@@ -1,14 +1,15 @@
1
1
  {
2
2
  "name": "@mosadd/mcp",
3
- "version": "3.0.0-alpha.7",
4
- "description": "Model Context Protocol server for mosadd. Exposes the 6 live m* modules (mDM, mIRC, mROOM, mTALK, mAIL, mRAG) — 57 tools — to any agent runtime (Claude Code, Cursor, Windsurf, Cline, ChatGPT Apps, Lovable, Bolt, Goose, Manus, custom).",
5
- "homepage": "https://github.com/Hei33enberg/mosadd-os/tree/main/packages/mcp",
3
+ "version": "3.0.1",
4
+ "mcpName": "io.github.hei33enberg/mosadd-mcp",
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
+ "homepage": "https://github.com/Hei33enberg/mosADD-OS/tree/main/packages/mcp",
6
7
  "repository": {
7
8
  "type": "git",
8
- "url": "https://github.com/Hei33enberg/mosadd-os.git",
9
+ "url": "https://github.com/Hei33enberg/mosADD-OS.git",
9
10
  "directory": "packages/mcp"
10
11
  },
11
- "license": "Apache-2.0",
12
+ "license": "MIT",
12
13
  "type": "module",
13
14
  "main": "./dist/index.js",
14
15
  "module": "./dist/index.js",
@@ -27,18 +28,27 @@
27
28
  "dist",
28
29
  "src",
29
30
  "README.md",
31
+ "CHANGELOG.md",
30
32
  "LICENSE"
31
33
  ],
32
34
  "publishConfig": {
33
35
  "access": "public"
34
36
  },
37
+ "scripts": {
38
+ "build": "tsup src/index.ts src/bin/mcp.ts src/bin/login.ts --format esm --dts --clean --shims",
39
+ "dev": "tsx src/bin/mcp.ts",
40
+ "test": "vitest run",
41
+ "typecheck": "tsc -p tsconfig.json --noEmit",
42
+ "clean": "rm -rf dist .turbo"
43
+ },
35
44
  "dependencies": {
36
45
  "@modelcontextprotocol/sdk": "^1.0.4",
37
46
  "@supabase/supabase-js": "^2.48.0",
38
47
  "zod": "^4.3.6",
39
- "@mosadd/crypto": "3.0.0-alpha.4",
40
- "@mosadd/protocol": "3.0.0-alpha.4",
41
- "@mosadd/providers": "3.0.0-alpha.4"
48
+ "@mosadd/protocol": "3.0.0-alpha.28",
49
+ "@mosadd/crypto": "3.0.0-alpha.27",
50
+ "@mosadd/providers": "3.0.0-alpha.27",
51
+ "@mosadd/threat-engine": "3.0.0-alpha.28"
42
52
  },
43
53
  "devDependencies": {
44
54
  "tsup": "^8.3.5",
@@ -59,12 +69,5 @@
59
69
  ],
60
70
  "engines": {
61
71
  "node": ">=18"
62
- },
63
- "scripts": {
64
- "build": "tsup src/index.ts src/bin/mcp.ts src/bin/login.ts --format esm --dts --clean --shims",
65
- "dev": "tsx src/bin/mcp.ts",
66
- "test": "vitest run",
67
- "typecheck": "tsc -p tsconfig.json --noEmit",
68
- "clean": "rm -rf dist .turbo"
69
72
  }
70
- }
73
+ }
@@ -0,0 +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 and one private bucket.
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
+ });
@@ -0,0 +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
+ });
@@ -0,0 +1,47 @@
1
+ import { describe, it, expect } from "vitest";
2
+ import { readFileSync } from "node:fs";
3
+ import { fileURLToPath } from "node:url";
4
+ import { dirname, resolve } from "node:path";
5
+ import { allTools, TOOL_COUNT } from "../tools/index.js";
6
+ import { PKG_VERSION } from "../version.js";
7
+ import { groupTools, moduleOf, parseCli, renderHelp, renderTools, renderVersion } from "../cli.js";
8
+
9
+ const here = dirname(fileURLToPath(import.meta.url));
10
+ const pkg = JSON.parse(readFileSync(resolve(here, "../../package.json"), "utf8")) as { version: string };
11
+
12
+ describe("CLI: parseCli", () => {
13
+ it("--version / -v / version print and never serve", () => {
14
+ for (const a of [["--version"], ["-v"], ["version"], ["tools", "--version"]]) expect(parseCli(a).kind).toBe("version");
15
+ });
16
+ it("--help / -h / help print and never serve", () => {
17
+ for (const a of [["--help"], ["-h"], ["help"]]) expect(parseCli(a).kind).toBe("help");
18
+ });
19
+ it("tools lists, auth subcommands keep their args, no args serves", () => {
20
+ expect(parseCli(["tools"]).kind).toBe("tools");
21
+ expect(parseCli(["login", "--email", "a@b.c"])).toEqual({ kind: "auth", sub: "login", rest: ["--email", "a@b.c"] });
22
+ expect(parseCli(["whoami"]).kind).toBe("auth");
23
+ expect(parseCli([]).kind).toBe("serve");
24
+ });
25
+ });
26
+
27
+ describe("CLI: output", () => {
28
+ it("version comes from package.json, not a hand-typed string", () => {
29
+ expect(PKG_VERSION).toBe(pkg.version);
30
+ expect(renderVersion(PKG_VERSION)).toBe(`${pkg.version}\n`);
31
+ expect(renderVersion(PKG_VERSION)).not.toContain("alpha.0");
32
+ });
33
+ it("help lists the commands and MOSADD_API_KEY", () => {
34
+ const h = renderHelp(PKG_VERSION);
35
+ for (const w of ["login", "logout", "whoami", "tools", "--version", "--help", "MOSADD_API_KEY"]) expect(h).toContain(w);
36
+ expect(h).toContain(pkg.version);
37
+ });
38
+ it("tools prints every registered tool exactly once, grouped by module", () => {
39
+ const out = renderTools(allTools);
40
+ expect(out.startsWith(`${TOOL_COUNT} tools in `)).toBe(true);
41
+ for (const t of allTools) expect(out).toContain(` ${t.name}`);
42
+ const groups = groupTools(allTools);
43
+ expect(groups.reduce((n, g) => n + g.tools.length, 0)).toBe(TOOL_COUNT);
44
+ expect(groups.map((g) => g.module)).toContain("mDM");
45
+ for (const g of groups) for (const t of g.tools) expect(moduleOf(t.name)).toBe(g.module);
46
+ });
47
+ });