@mosadd/mcp 3.0.0-alpha.49 → 3.0.0-alpha.50

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.
@@ -0,0 +1,310 @@
1
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
2
+ import { z } from 'zod';
3
+ import { DmProvider, VoiceProvider } from '@mosadd/providers';
4
+ import { RatchetState, DhRatchetState, SessionRole } from '@mosadd/crypto';
5
+
6
+ /**
7
+ * mDM end-to-end encryption — session layer (LINEAR-2357).
8
+ *
9
+ * Sits ABOVE the DmProvider. The provider moves opaque bytes; THIS module
10
+ * decides what those bytes are: an X3DH handshake + Double Ratchet ciphertext
11
+ * envelope, produced from `@mosadd/crypto` primitives.
12
+ *
13
+ * Flow (decision "1a" — prekey distribution rides the DmProvider):
14
+ * - Each peer publishes a prekey bundle via `dm.publishPrekeyBundle(bytes)`.
15
+ * - First contact: sender `dm.fetchPrekeyBundle(peer)` → X3DH (initiator) →
16
+ * Double Ratchet. The first ciphertext carries a handshake header
17
+ * (initiator IK + EK + consumed one-time-prekey id) so the recipient can
18
+ * run X3DH (responder) and derive the SAME root key.
19
+ * - Subsequent messages reuse the stored ratchet session (no header).
20
+ *
21
+ * SCOPE / known follow-ups (tracked on LINEAR-2357, NOT silently hidden):
22
+ * - Ratchet is strict in-order (no skipped-message keys) — fine for a single
23
+ * ordered thread; out-of-order/lossy transports need skipped-key handling.
24
+ * - Signed-prekey signature is carried but NOT yet verified (auth follow-up).
25
+ * - Initiator "glare" (both sides open simultaneously) not resolved.
26
+ * - Default keystore is in-memory (per-process); file/OS-keychain backing is
27
+ * a follow-up. The MdmKeyStore seam makes that a drop-in.
28
+ */
29
+
30
+ interface X25519Pair {
31
+ publicKey: Uint8Array;
32
+ privateKey: Uint8Array;
33
+ }
34
+ /** The local peer's long-term identity + prekeys (private halves included). */
35
+ interface OwnPrekeyMaterial {
36
+ /** X25519 DH identity — used in X3DH. */
37
+ identity: X25519Pair;
38
+ /**
39
+ * Ed25519 SIGNING identity — the long-term key a peer pins out-of-band
40
+ * (the "safety number"). Signs the bundle so a network/radio MITM can't swap
41
+ * the signed prekey or DH identity in transit.
42
+ */
43
+ signingIdentity: {
44
+ publicKey: Uint8Array;
45
+ privateKey: Uint8Array;
46
+ };
47
+ signedPrekey: {
48
+ id: number;
49
+ pair: X25519Pair;
50
+ };
51
+ oneTimePrekeys: Array<{
52
+ id: number;
53
+ pair: X25519Pair;
54
+ }>;
55
+ }
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
+ */
61
+ interface MdmSessionRecord {
62
+ ratchet?: RatchetState;
63
+ ratchet2?: DhRatchetState;
64
+ role: SessionRole;
65
+ /** Handshake header still owed to the peer (initiator only, until first send). */
66
+ pendingHandshake?: {
67
+ ik: Uint8Array;
68
+ ek: Uint8Array;
69
+ opkId?: number;
70
+ };
71
+ }
72
+ /**
73
+ * Local custody of private key material + ratchet sessions. The default impl
74
+ * is in-memory; a host may inject a file- or keychain-backed implementation.
75
+ */
76
+ interface MdmKeyStore {
77
+ /** Own identity + prekeys. Generated lazily on first access, then stable. */
78
+ getOwnMaterial(): Promise<OwnPrekeyMaterial>;
79
+ /** Consume (one-time) a prekey private by id. Returns undefined if unknown. */
80
+ takeOneTimePrekey(id: number): Promise<Uint8Array | undefined>;
81
+ getSession(peerId: string): Promise<MdmSessionRecord | undefined>;
82
+ putSession(peerId: string, record: MdmSessionRecord): Promise<void>;
83
+ /**
84
+ * OPTIONAL local "sent items" cache. The Double Ratchet is forward-secret and
85
+ * asymmetric: once we seal a message for a peer we cannot re-derive its
86
+ * plaintext from our own ratchet on read. So mDM_list cannot show the sender
87
+ * their OWN outgoing text unless we keep a local copy. These two methods are
88
+ * that copy — keyed by the provider-assigned message id.
89
+ *
90
+ * Honesty note: this is a LOCAL plaintext cache, not synced across devices.
91
+ * A second device (or a fresh process) won't have it and will fall back to a
92
+ * "<encrypted · sent by you>" marker. Cross-device sent-history sync is a
93
+ * tracked follow-up (would need an encrypt-to-self session). Optional so
94
+ * existing MdmKeyStore implementations keep compiling.
95
+ */
96
+ putSentMessage?(messageId: string, plaintext: Uint8Array): Promise<void>;
97
+ getSentMessage?(messageId: string): Promise<Uint8Array | undefined>;
98
+ }
99
+
100
+ /**
101
+ * Internal types for the mosadd MCP server.
102
+ */
103
+
104
+ type Mode = "cloud" | "local" | "self-host";
105
+ /**
106
+ * Transport backends per channel. The server fills any missing entry with its
107
+ * default network adapter; a host (e.g. cymru-os) injects alternatives —
108
+ * notably a radio DmProvider — via `MosaddServerOptions.providers`. This is
109
+ * the DI seam that keeps mosadd-os transport-agnostic.
110
+ *
111
+ * `keys` is LOCAL crypto custody (identity + prekeys + ratchet sessions) for
112
+ * mDM E2EE — distinct from transport. Defaults to an in-process keystore; a
113
+ * host may inject a file/keychain-backed one.
114
+ */
115
+ interface ProviderRegistry {
116
+ dm: DmProvider;
117
+ keys: MdmKeyStore;
118
+ /**
119
+ * mTALK push-to-talk transport. Defaults to the network provider (LiveKit
120
+ * media + authoritative floor state). A radio host injects a provider that
121
+ * maps the floor onto a physical RF channel.
122
+ */
123
+ voice: VoiceProvider;
124
+ }
125
+ interface MosaddServerOptions {
126
+ /** API key for hosted mode. Required if mode === "cloud". */
127
+ apiKey?: string;
128
+ /** Override the default hub URL (https://mcp.mosadd.com). */
129
+ hubUrl?: string;
130
+ /** Operating mode. Defaults to "cloud" if apiKey is present, else "local". */
131
+ mode?: Mode;
132
+ /** Log level. */
133
+ logLevel?: "debug" | "info" | "warn" | "error";
134
+ /**
135
+ * Host-injected channel providers. Any omitted channel uses the default
136
+ * network adapter. A carrier-aware host supplies e.g. a radio DmProvider here.
137
+ */
138
+ providers?: Partial<ProviderRegistry>;
139
+ /**
140
+ * When true, publish this identity's mDM prekey bundle once on startup
141
+ * (best-effort, non-fatal) so peers can open an E2EE session without the user
142
+ * manually running mDM_publish_keys first. Fixes the cold-start where mDM_send
143
+ * fails for every recipient because nobody has published keys. Used by the
144
+ * stdio binary; the hosted per-request transport leaves this off (it publishes
145
+ * per authenticated session instead).
146
+ */
147
+ autoPublishKeys?: boolean;
148
+ }
149
+ interface MosaddToolContext {
150
+ options: Required<Pick<MosaddServerOptions, "mode" | "hubUrl">> & MosaddServerOptions;
151
+ /** Resolved channel providers (defaults merged with host-injected ones). */
152
+ providers: ProviderRegistry;
153
+ /** Per-request logger. */
154
+ log: (level: "debug" | "info" | "warn" | "error", msg: string, extra?: unknown) => void;
155
+ }
156
+ /**
157
+ * Transport capability a tool requires to function. This is the ONE contract
158
+ * string shared with consuming hosts. e.g. cymru-os gates tools by carrier
159
+ * availability via this flag (cymru-os RFC 0002 D-Bus "Capability-flag bridge").
160
+ * The enum is FINAL and normalized with the cymru-os host; changing these
161
+ * values must be coordinated (Linear label `requires:cymru-input`).
162
+ *
163
+ * - "any" works over any transport, incl. off-grid radio (small,
164
+ * packet-friendly payloads). e.g. text DM.
165
+ * - "radio" radio-specific path (e.g. Codec2 audio frames). Off-grid OK.
166
+ * - "network" needs IP connectivity (server-hosted channels, email, public
167
+ * join links, bridges). NOT available off-grid.
168
+ */
169
+ type CapabilityRequirement = "any" | "radio" | "network";
170
+ /**
171
+ * MCP tool annotations (spec `ToolAnnotations`, minus `title` which lives on the
172
+ * tool itself). Connector UIs — Claude's included — group and gate tools by these
173
+ * hints: `readOnlyHint: true` lands the tool in the read-only bucket (bulk-approvable),
174
+ * `destructiveHint: true` marks it as destroying/overwriting user data at approval
175
+ * time, and tools with NO annotations all fall into one flat "Other tools" bucket —
176
+ * which is exactly how the mosADD connector looked until 2026-08-26 (84 tools, one
177
+ * undifferentiated list; founder order: fix it).
178
+ */
179
+ interface MosaddToolAnnotations {
180
+ /** Tool does not mutate anything. list/get/search/state/metrics class. */
181
+ readOnlyHint?: boolean;
182
+ /** Tool destroys or irreversibly overwrites data (delete/ban/revoke/edit-in-place). */
183
+ destructiveHint?: boolean;
184
+ /** Calling twice with the same args has no additional effect. */
185
+ idempotentHint?: boolean;
186
+ /** Tool reaches outside the mosADD closed world (e.g. sends external email). */
187
+ openWorldHint?: boolean;
188
+ }
189
+ interface MosaddTool<TInput = unknown, TOutput = unknown> {
190
+ /** Tool name. MUST follow the m{MODULE}_{operation} convention. */
191
+ name: string;
192
+ /**
193
+ * Human title for connector UIs (e.g. "Send encrypted DM"). The `name` stays the
194
+ * model-facing handle; this is what a PERSON sees in the permissions list.
195
+ */
196
+ title?: string;
197
+ /** Short human-readable description. Shown to the model. */
198
+ description: string;
199
+ /** MCP annotations; see MosaddToolAnnotations. Every registered tool SHOULD set them. */
200
+ annotations?: MosaddToolAnnotations;
201
+ /**
202
+ * Transport this tool requires. Consuming hosts read this to gate tools by
203
+ * available carriers. Every tool MUST declare it explicitly.
204
+ */
205
+ requires: CapabilityRequirement;
206
+ /** Zod schema for input. */
207
+ inputSchema: z.ZodType<TInput>;
208
+ /** Tool handler. */
209
+ handler: (input: TInput, ctx: MosaddToolContext) => Promise<TOutput>;
210
+ }
211
+
212
+ /**
213
+ * Build a McpServer instance with all mosadd tools registered.
214
+ */
215
+
216
+ /**
217
+ * Resolve the channel ProviderRegistry: default network adapters merged with
218
+ * anything the host injects. A carrier-aware host (cymru-os) passes its own
219
+ * radio DmProvider via `injected.dm`. This is the single place the default
220
+ * adapters are named — both `createMosaddServer` and the `@mosadd/ai` adapters
221
+ * build their context through it so they stay in lockstep.
222
+ */
223
+ declare function defaultProviders(injected?: Partial<ProviderRegistry>): ProviderRegistry;
224
+ declare function createMosaddServer(options?: MosaddServerOptions): McpServer;
225
+
226
+ /**
227
+ * Tool registry. Each m* module contributes a set of tools.
228
+ *
229
+ * User-facing modules (4): mDM, mIRC, mURL, mAYL — the re-arch (LINEAR-3938)
230
+ * mAYL replaces the old mp0st name (mp0st_* still registered as back-compat
231
+ * aliases via mail-aliases.ts; will be removed in a later alpha).
232
+ *
233
+ * Capabilities (not modules — cross-cutting agent tooling): mRAG, comms_.
234
+ * mTALK = voice tier inside mIRC, still its own tools for now; folding into
235
+ * mIRC_voice_* in a follow-up release. threat_* (threat_catalog + threat_classify)
236
+ * are REGISTERED (2026-07-15, founder directive + LINEAR-3498): pure/offline
237
+ * defensive classification over the threat taxonomy — the surveillance-era
238
+ * *marketing* was killed, the classification engine is real and wanted.
239
+ *
240
+ * 85 callable tools registered — the exact live count is exported as TOOL_COUNT
241
+ * (= allTools.length) below; ALWAYS reference that, never re-hard-code a number that drifts.
242
+ * Breakdown (2026-09-03, from allTools in this tree; the live tools/list on mcp.mosadd.com catches up
243
+ * when the alpha carrying mIRC_invite is published and the gateway redeployed):
244
+ * modules mDM 16 · mIRC 25 · mURL 7 · mAYL 16 = 64; capabilities mTALK 6 · mRAG 8 ·
245
+ * comms 5 (action_create/action_frame_get/embed_create/capabilities/session_attach) · Irondome/threat 2
246
+ * = 21. 64 + 21 = 85. (mIRC 25 = 24 + mIRC_invite added 2026-09-03 (LINEAR-5870): mIRC_join adds the KEY's
247
+ * identity while channel posts are signed by the AGENT, so every channel created from the toolkit was mute
248
+ * until its agent was added from the app — mIRC_invite wraps channel-members-manage `invite`: own agent →
249
+ * auto_joined, anyone else → invite code. mDM 16 = 14 + mDM_send_as_agent/mDM_list_my_agents added 2026-08-17: an MCP key
250
+ * is bound to a USER, so an agent runtime wired up with its owner's key spoke AS THE OWNER — these
251
+ * 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.
252
+ * comms_session_attach added 2026-08-14: a live agent session claims the account's reply lane so
253
+ * the cloud stand-in defers to it — the front door that used to be a script on one PC.)
254
+ * (History of this line drifting: the 2026-07-17 breakdown ended "= 69"
255
+ * — wrong twice over, its own terms summed to 71; the 07-30 rewrite said 73 and still had
256
+ * mAYL at 12 after mAYL_send_as_agent had been re-registered, so it stayed wrong through the
257
+ * four mAYL_agentbox_* tools landing on 08-06. Arithmetic in comments drifts; TOOL_COUNT
258
+ * doesn't — and since 08-11 the anti-drift gate checks the PER-MODULE numbers too, not just
259
+ * the total, so this comment cannot rot alone any more.)
260
+ * (mDM/mIRC each include their 2 attachment tools from attachments.ts.)
261
+ * Modules (4): mDM, mIRC, mURL, mAYL. Capabilities: mTALK (voice/PTT), mRAG, comms_, Irondome (threat_*).
262
+ * mp0st_* stay as DEPRECATED back-compat aliases for mAYL_* (removed in a later alpha).
263
+ * mAYL_send_as_agent + mTALK_ingest_ptt were RE-REGISTERED 2026-07-29: both had been disabled
264
+ * on 07-14 notes that had since become false, and both were re-verified on authenticated calls.
265
+ * comms_embed_create RE-REGISTERED 2026-07-17 (embed.mosadd.com/v1.js live — P3 of mURL→mIRC).
266
+ * mROOM was KILLED (LINEAR-3414, channel re-cut → ephemeral private mIRC): its tools
267
+ * live in tools/mroom.ts + mroom-messages.ts but are NOT registered here.
268
+ * Plus action links: comms_action_create (agent → user one-link browser action,
269
+ * incl. screen_share) + comms_action_frame_get (see the recipient's shared screen).
270
+ * mURL is a FULL registered dev module (revived, founder 2026-06-27) — IRC-for-URLs,
271
+ * agent-native; backends live (mosadd-edge + murl-channels EF). tools/murl.ts.
272
+ * mURL now has full lifecycle: read/post/presence/list_channels (hub-key) PLUS owner-side
273
+ * create/claim + update(branding/status) + delete (mURL_create/update/delete → murl-manage
274
+ * EF, owner-scoped via user JWT — same auth as mURL_list_channels action='mine').
275
+ * mCALL is carrier-pending (no telephony carrier live yet): its tools live in
276
+ * tools/mcall.ts but are NOT registered here, so an agent only ever discovers
277
+ * tools that actually work. Re-register the one line below when a carrier ships.
278
+ */
279
+
280
+ declare const allTools: MosaddTool[];
281
+ /**
282
+ * The exact, live number of callable tools this server registers. Reference THIS
283
+ * (import { TOOL_COUNT }) in any code/doc surface that shows a tool count, instead
284
+ * of hard-coding a number that silently drifts (the "70+/65/68" inconsistency that
285
+ * bit us). Mirrors @mosadd/threat-engine's THREAT_EVENT_COUNT pattern.
286
+ */
287
+ declare const TOOL_COUNT: number;
288
+
289
+ /**
290
+ * Supabase provider for the alpha MCP server.
291
+ *
292
+ * Local BYOK mode: user supplies their own Supabase URL + anon key + user JWT
293
+ * via env vars. The MCP server creates a per-request Supabase client and
294
+ * invokes the mosadd Edge Functions on the user's behalf.
295
+ *
296
+ * In Phase 2 this is replaced by the hosted gateway (mcp.mosadd.com) which
297
+ * holds keys server-side via the BYOK broker.
298
+ */
299
+
300
+ interface SupabaseEnv {
301
+ url: string;
302
+ anonKey: string;
303
+ userJwt?: string;
304
+ /** Stabilna tożsamość sesji dla bramy hostowanej (per klucz API) — patrz sessionId(). */
305
+ sessionKey?: string;
306
+ }
307
+ /** Run `fn` (and every tool call it triggers) with a per-request Supabase session. */
308
+ declare function runWithSupabaseEnv<T>(env: SupabaseEnv, fn: () => T): T;
309
+
310
+ export { type MosaddServerOptions, type MosaddTool, type MosaddToolContext, type ProviderRegistry, type SupabaseEnv, TOOL_COUNT, allTools, createMosaddServer, defaultProviders, runWithSupabaseEnv };
package/dist/index.js CHANGED
@@ -4,7 +4,7 @@ import {
4
4
  createMosaddServer,
5
5
  defaultProviders,
6
6
  runWithSupabaseEnv
7
- } from "./chunk-MGF7BV3M.js";
7
+ } from "./chunk-L4PB6A6Z.js";
8
8
  import "./chunk-Z7WR52GE.js";
9
9
  export {
10
10
  TOOL_COUNT,
package/package.json CHANGED
@@ -1,73 +1,73 @@
1
- {
2
- "name": "@mosadd/mcp",
3
- "version": "3.0.0-alpha.49",
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",
7
- "repository": {
8
- "type": "git",
9
- "url": "https://github.com/Hei33enberg/mosADD-OS.git",
10
- "directory": "packages/mcp"
11
- },
12
- "license": "Apache-2.0",
13
- "type": "module",
14
- "main": "./dist/index.js",
15
- "module": "./dist/index.js",
16
- "types": "./dist/index.d.ts",
17
- "exports": {
18
- ".": {
19
- "types": "./dist/index.d.ts",
20
- "import": "./dist/index.js"
21
- }
22
- },
23
- "bin": {
24
- "mosadd-mcp": "./dist/bin/mcp.js",
25
- "mosadd": "./dist/bin/mcp.js"
26
- },
27
- "files": [
28
- "dist",
29
- "src",
30
- "README.md",
31
- "CHANGELOG.md",
32
- "LICENSE"
33
- ],
34
- "publishConfig": {
35
- "access": "public"
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
- },
44
- "dependencies": {
45
- "@modelcontextprotocol/sdk": "^1.0.4",
46
- "@supabase/supabase-js": "^2.48.0",
47
- "zod": "^4.3.6",
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"
52
- },
53
- "devDependencies": {
54
- "tsup": "^8.3.5",
55
- "tsx": "^4.19.2",
56
- "typescript": "^5.7.2",
57
- "vitest": "^2.1.8"
58
- },
59
- "keywords": [
60
- "mosadd",
61
- "mcp",
62
- "model-context-protocol",
63
- "agent",
64
- "claude",
65
- "cursor",
66
- "anthropic",
67
- "communication",
68
- "messaging"
69
- ],
70
- "engines": {
71
- "node": ">=18"
72
- }
73
- }
1
+ {
2
+ "name": "@mosadd/mcp",
3
+ "version": "3.0.0-alpha.50",
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",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "https://github.com/Hei33enberg/mosADD-OS.git",
10
+ "directory": "packages/mcp"
11
+ },
12
+ "license": "Apache-2.0",
13
+ "type": "module",
14
+ "main": "./dist/index.js",
15
+ "module": "./dist/index.js",
16
+ "types": "./dist/index.d.ts",
17
+ "exports": {
18
+ ".": {
19
+ "types": "./dist/index.d.ts",
20
+ "import": "./dist/index.js"
21
+ }
22
+ },
23
+ "bin": {
24
+ "mosadd-mcp": "./dist/bin/mcp.js",
25
+ "mosadd": "./dist/bin/mcp.js"
26
+ },
27
+ "files": [
28
+ "dist",
29
+ "src",
30
+ "README.md",
31
+ "CHANGELOG.md",
32
+ "LICENSE"
33
+ ],
34
+ "publishConfig": {
35
+ "access": "public"
36
+ },
37
+ "dependencies": {
38
+ "@modelcontextprotocol/sdk": "^1.0.4",
39
+ "@supabase/supabase-js": "^2.48.0",
40
+ "zod": "^4.3.6",
41
+ "@mosadd/protocol": "3.0.0-alpha.28",
42
+ "@mosadd/crypto": "3.0.0-alpha.27",
43
+ "@mosadd/providers": "3.0.0-alpha.27",
44
+ "@mosadd/threat-engine": "3.0.0-alpha.28"
45
+ },
46
+ "devDependencies": {
47
+ "tsup": "^8.3.5",
48
+ "tsx": "^4.19.2",
49
+ "typescript": "^5.7.2",
50
+ "vitest": "^2.1.8"
51
+ },
52
+ "keywords": [
53
+ "mosadd",
54
+ "mcp",
55
+ "model-context-protocol",
56
+ "agent",
57
+ "claude",
58
+ "cursor",
59
+ "anthropic",
60
+ "communication",
61
+ "messaging"
62
+ ],
63
+ "engines": {
64
+ "node": ">=18"
65
+ },
66
+ "scripts": {
67
+ "build": "tsup src/index.ts src/bin/mcp.ts src/bin/login.ts --format esm --dts --clean --shims",
68
+ "dev": "tsx src/bin/mcp.ts",
69
+ "test": "vitest run",
70
+ "typecheck": "tsc -p tsconfig.json --noEmit",
71
+ "clean": "rm -rf dist .turbo"
72
+ }
73
+ }
@@ -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
+ });
@@ -24,6 +24,7 @@ const AGENT_ID = "0489d4c6-8727-442f-bf83-68747a469492";
24
24
  const calls = {
25
25
  upserts: [] as Record<string, unknown>[],
26
26
  deletes: [] as string[],
27
+ rpcs: [] as { name: string; args: Record<string, unknown> }[],
27
28
  };
28
29
 
29
30
  /**
@@ -78,6 +79,12 @@ vi.mock("../providers/supabase.js", () => ({
78
79
  getSupabase: () => ({
79
80
  auth: { getUser: () => Promise.resolve({ data: { user: { id: USER_ID } }, error: null }) },
80
81
  from: (table: string) => makeBuilder(table),
82
+ // release/as_agent path: presence.ts woła mosadd_gateway_binding_release/claim przez rpc —
83
+ // atrapa nagrywa wywołania, żeby asercje czytały się jak prawdziwy wire.
84
+ rpc: (name: string, args: Record<string, unknown>) => {
85
+ calls.rpcs.push({ name, args });
86
+ return Promise.resolve({ error: null, data: { took_over: false, previous_session_id: null } });
87
+ },
81
88
  }),
82
89
  }));
83
90
 
@@ -152,12 +159,11 @@ describe("comms_session_attach", () => {
152
159
  await call({});
153
160
  const out = await call({ release: true });
154
161
  expect(out.attached).toBe(false);
155
- // Two deletes since 2026-08-26: the heartbeat row (by identity) AND the as_agent
156
- // declaration in mosadd_gateway_agent_binding (by user) — a finishing session hands
157
- // back EVERYTHING it could hold, so no stale declaration keeps signing later posts.
158
- // Zwolnienie kasuje: puls linii + deklarację TEJ sesji (konto ORAZ sesja). Trzeci element to
159
- // dowód, że nie kasujemy po samym koncie — bo to zabierało linię wszystkim innym generałom.
160
- expect(calls.deletes).toEqual([IDENTITY_ID, USER_ID, TEST_SESSION]);
162
+ // Zwolnienie kasuje puls linii (po identity) i puszcza deklarację TEJ sesji RPC-em
163
+ // (konto ORAZ sesja po stronie SQL — nie kasujemy po samym koncie, bo to zabierało
164
+ // linię wszystkim innym generałom na tym samym kluczu).
165
+ expect(calls.deletes).toEqual([IDENTITY_ID]);
166
+ expect(calls.rpcs).toEqual([{ name: "mosadd_gateway_binding_release", args: { p_session_id: TEST_SESSION } }]);
161
167
  calls.upserts = [];
162
168
  await vi.advanceTimersByTimeAsync(180_000);
163
169
  expect(calls.upserts).toHaveLength(0);
@@ -168,14 +174,17 @@ describe("comms_session_attach", () => {
168
174
  expect(out.attached).toBe(true);
169
175
  expect(out.identity_id).toBe(AGENT_ID);
170
176
  expect((out.speaking_as as { address: string }).address).toBe("dispatcher@mosadd.com");
171
- // The signing declaration message-send reads (migration 20260826210000)…
172
- expect(calls.upserts).toContainEqual(
173
- expect.objectContaining({
174
- table: "mosadd_gateway_agent_binding",
175
- user_id: USER_ID,
176
- agent_identity_id: AGENT_ID,
177
- }),
178
- );
177
+ // The signing declaration message-send reads — arbitrowana w SQL (LINEAR-5879):
178
+ // claim RPC-em, nie surowym upsertem.
179
+ expect(calls.rpcs).toContainEqual({
180
+ name: "mosadd_gateway_binding_claim",
181
+ args: {
182
+ p_session_id: TEST_SESSION,
183
+ p_agent_identity_id: AGENT_ID,
184
+ p_agent_address: "dispatcher@mosadd.com",
185
+ p_host: "dispatcher — Cowork",
186
+ },
187
+ });
179
188
  // …and the AGENT's liveness row, so ITS cloud stand-in defers to this session.
180
189
  expect(calls.upserts).toContainEqual(
181
190
  expect.objectContaining({