@mosadd/mcp 3.0.0-alpha.55 → 3.0.0-alpha.56
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/CHANGELOG.md +5 -11
- package/LICENSE +21 -0
- package/README.md +151 -150
- package/dist/bin/mcp.js +1 -1
- package/dist/{chunk-IWUGKLDX.js → chunk-T3KDVUAT.js} +14 -10
- package/dist/index.js +1 -1
- package/package.json +10 -10
- package/src/__tests__/blob-upload.test.ts +93 -93
- package/src/__tests__/channel-e2ee.test.ts +62 -62
- package/src/__tests__/flota-jawnie.test.ts +2 -2
- package/src/__tests__/golden-path.test.ts +139 -139
- package/src/__tests__/integration.test.ts +209 -182
- package/src/__tests__/mdm-e2ee.test.ts +212 -212
- package/src/__tests__/mdm-mcp-readable.test.ts +390 -390
- package/src/__tests__/mirc-invite.test.ts +112 -112
- package/src/__tests__/mtalk.test.ts +122 -122
- package/src/__tests__/presence.test.ts +199 -199
- package/src/__tests__/server.test.ts +71 -71
- package/src/__tests__/tool-count-consistency.test.ts +255 -199
- package/src/bin/login.ts +138 -138
- package/src/bin/mcp.ts +145 -145
- package/src/config.ts +66 -66
- package/src/crypto/channel-e2ee.ts +288 -288
- package/src/crypto/mdm-session.ts +842 -842
- package/src/index.ts +19 -19
- package/src/observability/sentry.ts +79 -79
- package/src/providers/blob-upload.ts +162 -162
- package/src/providers/memory-voice.ts +79 -79
- package/src/providers/supabase-dm.ts +202 -202
- package/src/providers/supabase-voice.ts +91 -91
- package/src/server.ts +195 -195
- package/src/tools/actions.ts +166 -166
- package/src/tools/attachments.ts +276 -276
- package/src/tools/capabilities.ts +70 -70
- package/src/tools/channel-payload.ts +2 -2
- package/src/tools/embed.ts +110 -110
- package/src/tools/index.ts +181 -181
- package/src/tools/knowledge.ts +344 -344
- package/src/tools/mail-aliases.ts +25 -25
- package/src/tools/mail-provenance.ts +137 -137
- package/src/tools/mail.ts +403 -403
- package/src/tools/mdm-as-agent.ts +138 -126
- package/src/tools/mdm.ts +3 -3
- package/src/tools/mirc-edge.ts +196 -196
- package/src/tools/mirc-members.ts +287 -287
- package/src/tools/mirc-messages.ts +1 -1
- package/src/tools/mirc.ts +308 -308
- package/src/tools/mroom.ts +221 -221
- package/src/tools/mtalk.ts +131 -131
- package/src/tools/presence.ts +442 -442
- package/src/tools/voice-format.ts +28 -28
- package/src/types.ts +121 -121
- package/src/voice/floor.ts +132 -132
package/src/index.ts
CHANGED
|
@@ -1,19 +1,19 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* @mosadd/mcp — Model Context Protocol server for mosadd
|
|
3
|
-
*
|
|
4
|
-
* Exposes mosadd OS modules (m*) as MCP tools to any agent runtime
|
|
5
|
-
* (Claude Code, Cursor, Windsurf, Cline, ChatGPT Apps, Lovable, etc.).
|
|
6
|
-
*
|
|
7
|
-
* License: Apache-2.0
|
|
8
|
-
*/
|
|
9
|
-
|
|
10
|
-
export { createMosaddServer, defaultProviders } from "./server.js";
|
|
11
|
-
export type {
|
|
12
|
-
MosaddServerOptions,
|
|
13
|
-
MosaddTool,
|
|
14
|
-
MosaddToolContext,
|
|
15
|
-
ProviderRegistry,
|
|
16
|
-
} from "./types.js";
|
|
17
|
-
export { allTools, TOOL_COUNT } from "./tools/index.js";
|
|
18
|
-
// Per-request session context for the hosted HTTP gateway (mcp.mosadd.com).
|
|
19
|
-
export { runWithSupabaseEnv, type SupabaseEnv } from "./providers/supabase.js";
|
|
1
|
+
/**
|
|
2
|
+
* @mosadd/mcp — Model Context Protocol server for mosadd
|
|
3
|
+
*
|
|
4
|
+
* Exposes mosadd OS modules (m*) as MCP tools to any agent runtime
|
|
5
|
+
* (Claude Code, Cursor, Windsurf, Cline, ChatGPT Apps, Lovable, etc.).
|
|
6
|
+
*
|
|
7
|
+
* License: MIT (releases before 2026-09-29: Apache-2.0)
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
export { createMosaddServer, defaultProviders } from "./server.js";
|
|
11
|
+
export type {
|
|
12
|
+
MosaddServerOptions,
|
|
13
|
+
MosaddTool,
|
|
14
|
+
MosaddToolContext,
|
|
15
|
+
ProviderRegistry,
|
|
16
|
+
} from "./types.js";
|
|
17
|
+
export { allTools, TOOL_COUNT } from "./tools/index.js";
|
|
18
|
+
// Per-request session context for the hosted HTTP gateway (mcp.mosadd.com).
|
|
19
|
+
export { runWithSupabaseEnv, type SupabaseEnv } from "./providers/supabase.js";
|
|
@@ -1,79 +1,79 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Sentry init for @mosadd/mcp.
|
|
3
|
-
*
|
|
4
|
-
* Optional. The MCP server runs entirely as user-supplied stdio — most
|
|
5
|
-
* operators won't want their tool errors phoning home. We expose an opt-in
|
|
6
|
-
* env var (MOSADD_SENTRY_DSN) so power users / hub-operators can attach.
|
|
7
|
-
*
|
|
8
|
-
* Setup (one-time, hub operators):
|
|
9
|
-
* 1. Create a project in https://papugai.sentry.io named "mosadd-mcp"
|
|
10
|
-
* with platform = Node.
|
|
11
|
-
* 2. Export MOSADD_SENTRY_DSN before running the server.
|
|
12
|
-
*
|
|
13
|
-
* Without the env var, this module is an inert no-op.
|
|
14
|
-
*/
|
|
15
|
-
|
|
16
|
-
const DSN = process.env.MOSADD_SENTRY_DSN;
|
|
17
|
-
const ENV =
|
|
18
|
-
process.env.MOSADD_SENTRY_ENVIRONMENT ??
|
|
19
|
-
process.env.NODE_ENV ??
|
|
20
|
-
"production";
|
|
21
|
-
const RELEASE = process.env.MOSADD_SENTRY_RELEASE;
|
|
22
|
-
|
|
23
|
-
let initialized = false;
|
|
24
|
-
// @sentry/node is an OPTIONAL peer — operators install it only if they opt in
|
|
25
|
-
// via MOSADD_SENTRY_DSN. Typed as `any` + loaded via a non-literal specifier so
|
|
26
|
-
// the package compiles and ships without the dependency present.
|
|
27
|
-
let sentryRef: any = null;
|
|
28
|
-
|
|
29
|
-
export async function initSentry(): Promise<void> {
|
|
30
|
-
if (initialized || !DSN) return;
|
|
31
|
-
try {
|
|
32
|
-
// Lazy, optional import (variable specifier => tsc won't require the module).
|
|
33
|
-
const spec = "@sentry/node";
|
|
34
|
-
const Sentry: any = await import(spec).catch(() => null);
|
|
35
|
-
if (!Sentry) return;
|
|
36
|
-
Sentry.init({
|
|
37
|
-
dsn: DSN,
|
|
38
|
-
environment: ENV,
|
|
39
|
-
release: RELEASE,
|
|
40
|
-
tracesSampleRate: 0.1,
|
|
41
|
-
sendDefaultPii: false,
|
|
42
|
-
beforeSend(event: any) {
|
|
43
|
-
// Strip Authorization header / BYOK env values if they sneak in.
|
|
44
|
-
if (event.extra) {
|
|
45
|
-
for (const k of Object.keys(event.extra)) {
|
|
46
|
-
if (/auth|token|key|secret/i.test(k)) {
|
|
47
|
-
event.extra[k] = "[redacted]";
|
|
48
|
-
}
|
|
49
|
-
}
|
|
50
|
-
}
|
|
51
|
-
return event;
|
|
52
|
-
},
|
|
53
|
-
});
|
|
54
|
-
sentryRef = Sentry;
|
|
55
|
-
initialized = true;
|
|
56
|
-
} catch {
|
|
57
|
-
// Init failures are non-fatal. MCP servers must keep serving.
|
|
58
|
-
}
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
/**
|
|
62
|
-
* Capture an exception with optional tool context. Safe to call before init —
|
|
63
|
-
* no-ops when DSN is unset.
|
|
64
|
-
*/
|
|
65
|
-
export function captureToolError(
|
|
66
|
-
err: unknown,
|
|
67
|
-
ctx: { tool?: string; user_id?: string } = {}
|
|
68
|
-
): void {
|
|
69
|
-
if (!sentryRef) return;
|
|
70
|
-
try {
|
|
71
|
-
sentryRef.withScope((scope: any) => {
|
|
72
|
-
if (ctx.tool) scope.setTag("tool", ctx.tool);
|
|
73
|
-
if (ctx.user_id) scope.setUser({ id: ctx.user_id });
|
|
74
|
-
sentryRef!.captureException(err);
|
|
75
|
-
});
|
|
76
|
-
} catch {
|
|
77
|
-
// ignore
|
|
78
|
-
}
|
|
79
|
-
}
|
|
1
|
+
/**
|
|
2
|
+
* Sentry init for @mosadd/mcp.
|
|
3
|
+
*
|
|
4
|
+
* Optional. The MCP server runs entirely as user-supplied stdio — most
|
|
5
|
+
* operators won't want their tool errors phoning home. We expose an opt-in
|
|
6
|
+
* env var (MOSADD_SENTRY_DSN) so power users / hub-operators can attach.
|
|
7
|
+
*
|
|
8
|
+
* Setup (one-time, hub operators):
|
|
9
|
+
* 1. Create a project in https://papugai.sentry.io named "mosadd-mcp"
|
|
10
|
+
* with platform = Node.
|
|
11
|
+
* 2. Export MOSADD_SENTRY_DSN before running the server.
|
|
12
|
+
*
|
|
13
|
+
* Without the env var, this module is an inert no-op.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
const DSN = process.env.MOSADD_SENTRY_DSN;
|
|
17
|
+
const ENV =
|
|
18
|
+
process.env.MOSADD_SENTRY_ENVIRONMENT ??
|
|
19
|
+
process.env.NODE_ENV ??
|
|
20
|
+
"production";
|
|
21
|
+
const RELEASE = process.env.MOSADD_SENTRY_RELEASE;
|
|
22
|
+
|
|
23
|
+
let initialized = false;
|
|
24
|
+
// @sentry/node is an OPTIONAL peer — operators install it only if they opt in
|
|
25
|
+
// via MOSADD_SENTRY_DSN. Typed as `any` + loaded via a non-literal specifier so
|
|
26
|
+
// the package compiles and ships without the dependency present.
|
|
27
|
+
let sentryRef: any = null;
|
|
28
|
+
|
|
29
|
+
export async function initSentry(): Promise<void> {
|
|
30
|
+
if (initialized || !DSN) return;
|
|
31
|
+
try {
|
|
32
|
+
// Lazy, optional import (variable specifier => tsc won't require the module).
|
|
33
|
+
const spec = "@sentry/node";
|
|
34
|
+
const Sentry: any = await import(spec).catch(() => null);
|
|
35
|
+
if (!Sentry) return;
|
|
36
|
+
Sentry.init({
|
|
37
|
+
dsn: DSN,
|
|
38
|
+
environment: ENV,
|
|
39
|
+
release: RELEASE,
|
|
40
|
+
tracesSampleRate: 0.1,
|
|
41
|
+
sendDefaultPii: false,
|
|
42
|
+
beforeSend(event: any) {
|
|
43
|
+
// Strip Authorization header / BYOK env values if they sneak in.
|
|
44
|
+
if (event.extra) {
|
|
45
|
+
for (const k of Object.keys(event.extra)) {
|
|
46
|
+
if (/auth|token|key|secret/i.test(k)) {
|
|
47
|
+
event.extra[k] = "[redacted]";
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
return event;
|
|
52
|
+
},
|
|
53
|
+
});
|
|
54
|
+
sentryRef = Sentry;
|
|
55
|
+
initialized = true;
|
|
56
|
+
} catch {
|
|
57
|
+
// Init failures are non-fatal. MCP servers must keep serving.
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Capture an exception with optional tool context. Safe to call before init —
|
|
63
|
+
* no-ops when DSN is unset.
|
|
64
|
+
*/
|
|
65
|
+
export function captureToolError(
|
|
66
|
+
err: unknown,
|
|
67
|
+
ctx: { tool?: string; user_id?: string } = {}
|
|
68
|
+
): void {
|
|
69
|
+
if (!sentryRef) return;
|
|
70
|
+
try {
|
|
71
|
+
sentryRef.withScope((scope: any) => {
|
|
72
|
+
if (ctx.tool) scope.setTag("tool", ctx.tool);
|
|
73
|
+
if (ctx.user_id) scope.setUser({ id: ctx.user_id });
|
|
74
|
+
sentryRef!.captureException(err);
|
|
75
|
+
});
|
|
76
|
+
} catch {
|
|
77
|
+
// ignore
|
|
78
|
+
}
|
|
79
|
+
}
|
|
@@ -1,162 +1,162 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Voice/file blob upload helper.
|
|
3
|
-
*
|
|
4
|
-
* The `message-send` contract carries voice/ptt/file bodies via an
|
|
5
|
-
* `attachments[]` array of `{ kind, bucket, path, mime, duration_ms, key_ref }`
|
|
6
|
-
* descriptors. The actual bytes must be uploaded to Supabase Storage FIRST; the
|
|
7
|
-
* message row only references them by `{ bucket, path }`.
|
|
8
|
-
*
|
|
9
|
-
* This module centralises that upload so every channel's voice/file/ptt tool
|
|
10
|
-
* (mDM, mIRC) produces an identical attachment descriptor.
|
|
11
|
-
*
|
|
12
|
-
* STATUS: scaffold. The Storage upload path below is real (supabase-js
|
|
13
|
-
* `storage.from(bucket).upload`), but two things are TODO and gated on the
|
|
14
|
-
* Lane A / CTO backend contract:
|
|
15
|
-
* - DONE 2026-09-16: bucket names + write policy CONFIRMED against the live
|
|
16
|
-
* project (see defaultBucket()/ownerFolder()). The old defaults
|
|
17
|
-
* ('file-blobs', 'voice-blobs') did not exist in the project, so EVERY
|
|
18
|
-
* file/voice send from MCP died with `Bucket not found` — reproduced on
|
|
19
|
-
* mDM_send_file, mIRC_send_file and mDM_send_voice before the fix.
|
|
20
|
-
* - TODO(Lane A): mDM voice is CLIENT-ENCRYPTED — the bytes must be sealed
|
|
21
|
-
* (per-recipient, via @mosadd/crypto) before upload and `key_ref` must point
|
|
22
|
-
* at the wrapped content key. Today this helper uploads the bytes as-is and
|
|
23
|
-
* sets key_ref:null. Do NOT use for mDM voice until the seal step lands.
|
|
24
|
-
*/
|
|
25
|
-
|
|
26
|
-
import { getSupabase, readSupabaseEnv } from "./supabase.js";
|
|
27
|
-
|
|
28
|
-
export type AttachmentKind = "voice" | "file" | "ptt";
|
|
29
|
-
|
|
30
|
-
/** The descriptor shape `message-send` expects inside `attachments[]`. */
|
|
31
|
-
export interface AttachmentDescriptor {
|
|
32
|
-
kind: AttachmentKind;
|
|
33
|
-
bucket: string;
|
|
34
|
-
path: string;
|
|
35
|
-
mime: string;
|
|
36
|
-
duration_ms?: number | null;
|
|
37
|
-
/** Reference to the wrapped content-encryption key (E2EE channels only). */
|
|
38
|
-
key_ref?: string | null;
|
|
39
|
-
/** Original filename, for `kind:'file'`. */
|
|
40
|
-
filename?: string | null;
|
|
41
|
-
size_bytes?: number | null;
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
export interface UploadBlobArgs {
|
|
45
|
-
kind: AttachmentKind;
|
|
46
|
-
/** Raw bytes to upload. Caller is responsible for any E2EE sealing first. */
|
|
47
|
-
bytes: Uint8Array;
|
|
48
|
-
mime: string;
|
|
49
|
-
/** Storage bucket. Defaults: voice/ptt → 'voice-blobs', file → 'file-blobs'. */
|
|
50
|
-
bucket?: string;
|
|
51
|
-
/** Sub-path prefix inside the bucket (e.g. the thread id). */
|
|
52
|
-
prefix?: string;
|
|
53
|
-
duration_ms?: number | null;
|
|
54
|
-
filename?: string | null;
|
|
55
|
-
/** Reference to the wrapped content key, when the caller pre-sealed the bytes. */
|
|
56
|
-
key_ref?: string | null;
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
function defaultBucket(kind: AttachmentKind): string {
|
|
60
|
-
// ⛔ TYLKO BUCKETY, KTÓRE ISTNIEJĄ I PRZYJMĄ TEN JWT (potwierdzone na żywym
|
|
61
|
-
// projekcie rooffhgbxafyjcwmwpsy, 16.09):
|
|
62
|
-
// chat-files → bucket istnieje (limit 100 MB). INSERT policy
|
|
63
|
-
// "Users upload chat files": (storage.foldername(name))[1] = auth.uid()
|
|
64
|
-
// SELECT policy dopuszcza też członka wątku: is_thread_member(auth.uid(), foldername[2])
|
|
65
|
-
// voice-messages → bucket istnieje. INSERT policy
|
|
66
|
-
// "Users can upload voice messages": foldername(name)[1] = auth.uid()
|
|
67
|
-
// Poprzednie domyślne ('file-blobs' dla file, 'voice-blobs' dla voice/ptt) NIE
|
|
68
|
-
// ISTNIEJĄ w projekcie — stąd "Bucket not found" na mDM_send_file, mIRC_send_file
|
|
69
|
-
// i mDM_send_voice. Nazwy są tu jednym źródłem prawdy: gdy bucket zniknie,
|
|
70
|
-
// zawodzi JAWNIE, a nie po cichu ląduje w innym miejscu.
|
|
71
|
-
return kind === "file" ? "chat-files" : "voice-messages";
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
/** `sub` z JWT tej sesji, czyli `auth.uid()` — PIERWSZY segment ścieżki.
|
|
75
|
-
*
|
|
76
|
-
* ⛔ NIE OZDOBA I NIE OPCJA. Jedyny segment, który sprawdzają polityki INSERT obu
|
|
77
|
-
* bucketów: `(storage.foldername(name))[1] = auth.uid()`. Ścieżka bez segmentu
|
|
78
|
-
* użytkownika (`<thread>/<uuid>.ext`, jak było) przechodzi upload do momentu,
|
|
79
|
-
* w którym baza odrzuca wiersz — czyli wysyłka pliku jest ZAWSZE martwa, i to
|
|
80
|
-
* komunikatem, który nie mówi dlaczego. Ta sama konwencja co w aplikacji:
|
|
81
|
-
* `apps/web/src/lib/ircApi.ts: uploadChatFile()` → `<user.id>/<thread>/<ts>_<nazwa>`.
|
|
82
|
-
*/
|
|
83
|
-
function jwtSub(jwt: string): string | null {
|
|
84
|
-
const part = jwt.split(".")[1];
|
|
85
|
-
if (!part) return null;
|
|
86
|
-
try {
|
|
87
|
-
const json = JSON.parse(Buffer.from(part.replace(/-/g, "+").replace(/_/g, "/"), "base64").toString("utf8"));
|
|
88
|
-
return typeof json?.sub === "string" && json.sub ? json.sub : null;
|
|
89
|
-
} catch {
|
|
90
|
-
return null;
|
|
91
|
-
}
|
|
92
|
-
}
|
|
93
|
-
|
|
94
|
-
function ownerFolder(userJwt: string | undefined): string {
|
|
95
|
-
const sub = userJwt ? jwtSub(userJwt) : null;
|
|
96
|
-
if (!sub) {
|
|
97
|
-
throw new Error(
|
|
98
|
-
"blob upload refused: no user id in the session JWT — bucket policy requires foldername[1] = auth.uid(); run `mosadd login` (or set MOSADD_USER_JWT) and retry",
|
|
99
|
-
);
|
|
100
|
-
}
|
|
101
|
-
return sub;
|
|
102
|
-
}
|
|
103
|
-
|
|
104
|
-
function randomId(): string {
|
|
105
|
-
// crypto.randomUUID is available on Node >=18 (package engines floor).
|
|
106
|
-
return globalThis.crypto?.randomUUID?.() ?? `${Date.now()}-${Math.random().toString(36).slice(2)}`;
|
|
107
|
-
}
|
|
108
|
-
|
|
109
|
-
/**
|
|
110
|
-
* Upload bytes to Supabase Storage and return the attachment descriptor to embed
|
|
111
|
-
* in `message-send`'s `attachments[]`.
|
|
112
|
-
*/
|
|
113
|
-
export async function uploadBlob(args: UploadBlobArgs): Promise<AttachmentDescriptor> {
|
|
114
|
-
const env = readSupabaseEnv();
|
|
115
|
-
const sb = getSupabase();
|
|
116
|
-
const bucket = args.bucket ?? defaultBucket(args.kind);
|
|
117
|
-
const ext = args.filename?.split(".").pop() ?? mimeExt(args.mime);
|
|
118
|
-
// ⛔ KOLEJNOŚĆ SEGMENTÓW JEST CZĘŚCIĄ KONTRAKTU Z POLITYKĄ: <auth.uid()>/<wątek>/<uuid>.<ext>.
|
|
119
|
-
const folder = args.prefix ? args.prefix.replace(/[^a-zA-Z0-9._/-]/g, "-").replace(/^\/+|\/+$/g, "") : "";
|
|
120
|
-
const path = [ownerFolder(env.userJwt), folder, `${randomId()}${ext ? "." + ext : ""}`]
|
|
121
|
-
.filter(Boolean).join("/");
|
|
122
|
-
|
|
123
|
-
const { error } = await sb.storage.from(bucket).upload(path, args.bytes, {
|
|
124
|
-
contentType: args.mime,
|
|
125
|
-
upsert: false,
|
|
126
|
-
});
|
|
127
|
-
if (error) {
|
|
128
|
-
throw new Error(`blob upload to ${bucket}/${path} failed: ${error.message}`);
|
|
129
|
-
}
|
|
130
|
-
|
|
131
|
-
return {
|
|
132
|
-
kind: args.kind,
|
|
133
|
-
bucket,
|
|
134
|
-
path,
|
|
135
|
-
mime: args.mime,
|
|
136
|
-
duration_ms: args.duration_ms ?? null,
|
|
137
|
-
key_ref: args.key_ref ?? null,
|
|
138
|
-
filename: args.filename ?? null,
|
|
139
|
-
size_bytes: args.bytes.byteLength,
|
|
140
|
-
};
|
|
141
|
-
}
|
|
142
|
-
|
|
143
|
-
function mimeExt(mime: string): string {
|
|
144
|
-
const map: Record<string, string> = {
|
|
145
|
-
"audio/ogg": "ogg",
|
|
146
|
-
"audio/mpeg": "mp3",
|
|
147
|
-
"audio/mp4": "m4a",
|
|
148
|
-
"audio/wav": "wav",
|
|
149
|
-
"audio/webm": "webm",
|
|
150
|
-
};
|
|
151
|
-
return map[mime] ?? "";
|
|
152
|
-
}
|
|
153
|
-
|
|
154
|
-
/**
|
|
155
|
-
* Decode a base64 / data-URL string into bytes. Agents hand us audio/file
|
|
156
|
-
* content as base64 (MCP is JSON-only — no binary channel), so every voice/file
|
|
157
|
-
* tool funnels through this.
|
|
158
|
-
*/
|
|
159
|
-
export function decodeBase64Body(b64: string): Uint8Array {
|
|
160
|
-
const cleaned = b64.includes(",") && b64.startsWith("data:") ? b64.slice(b64.indexOf(",") + 1) : b64;
|
|
161
|
-
return new Uint8Array(Buffer.from(cleaned, "base64"));
|
|
162
|
-
}
|
|
1
|
+
/**
|
|
2
|
+
* Voice/file blob upload helper.
|
|
3
|
+
*
|
|
4
|
+
* The `message-send` contract carries voice/ptt/file bodies via an
|
|
5
|
+
* `attachments[]` array of `{ kind, bucket, path, mime, duration_ms, key_ref }`
|
|
6
|
+
* descriptors. The actual bytes must be uploaded to Supabase Storage FIRST; the
|
|
7
|
+
* message row only references them by `{ bucket, path }`.
|
|
8
|
+
*
|
|
9
|
+
* This module centralises that upload so every channel's voice/file/ptt tool
|
|
10
|
+
* (mDM, mIRC) produces an identical attachment descriptor.
|
|
11
|
+
*
|
|
12
|
+
* STATUS: scaffold. The Storage upload path below is real (supabase-js
|
|
13
|
+
* `storage.from(bucket).upload`), but two things are TODO and gated on the
|
|
14
|
+
* Lane A / CTO backend contract:
|
|
15
|
+
* - DONE 2026-09-16: bucket names + write policy CONFIRMED against the live
|
|
16
|
+
* project (see defaultBucket()/ownerFolder()). The old defaults
|
|
17
|
+
* ('file-blobs', 'voice-blobs') did not exist in the project, so EVERY
|
|
18
|
+
* file/voice send from MCP died with `Bucket not found` — reproduced on
|
|
19
|
+
* mDM_send_file, mIRC_send_file and mDM_send_voice before the fix.
|
|
20
|
+
* - TODO(Lane A): mDM voice is CLIENT-ENCRYPTED — the bytes must be sealed
|
|
21
|
+
* (per-recipient, via @mosadd/crypto) before upload and `key_ref` must point
|
|
22
|
+
* at the wrapped content key. Today this helper uploads the bytes as-is and
|
|
23
|
+
* sets key_ref:null. Do NOT use for mDM voice until the seal step lands.
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
import { getSupabase, readSupabaseEnv } from "./supabase.js";
|
|
27
|
+
|
|
28
|
+
export type AttachmentKind = "voice" | "file" | "ptt";
|
|
29
|
+
|
|
30
|
+
/** The descriptor shape `message-send` expects inside `attachments[]`. */
|
|
31
|
+
export interface AttachmentDescriptor {
|
|
32
|
+
kind: AttachmentKind;
|
|
33
|
+
bucket: string;
|
|
34
|
+
path: string;
|
|
35
|
+
mime: string;
|
|
36
|
+
duration_ms?: number | null;
|
|
37
|
+
/** Reference to the wrapped content-encryption key (E2EE channels only). */
|
|
38
|
+
key_ref?: string | null;
|
|
39
|
+
/** Original filename, for `kind:'file'`. */
|
|
40
|
+
filename?: string | null;
|
|
41
|
+
size_bytes?: number | null;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export interface UploadBlobArgs {
|
|
45
|
+
kind: AttachmentKind;
|
|
46
|
+
/** Raw bytes to upload. Caller is responsible for any E2EE sealing first. */
|
|
47
|
+
bytes: Uint8Array;
|
|
48
|
+
mime: string;
|
|
49
|
+
/** Storage bucket. Defaults: voice/ptt → 'voice-blobs', file → 'file-blobs'. */
|
|
50
|
+
bucket?: string;
|
|
51
|
+
/** Sub-path prefix inside the bucket (e.g. the thread id). */
|
|
52
|
+
prefix?: string;
|
|
53
|
+
duration_ms?: number | null;
|
|
54
|
+
filename?: string | null;
|
|
55
|
+
/** Reference to the wrapped content key, when the caller pre-sealed the bytes. */
|
|
56
|
+
key_ref?: string | null;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function defaultBucket(kind: AttachmentKind): string {
|
|
60
|
+
// ⛔ TYLKO BUCKETY, KTÓRE ISTNIEJĄ I PRZYJMĄ TEN JWT (potwierdzone na żywym
|
|
61
|
+
// projekcie rooffhgbxafyjcwmwpsy, 16.09):
|
|
62
|
+
// chat-files → bucket istnieje (limit 100 MB). INSERT policy
|
|
63
|
+
// "Users upload chat files": (storage.foldername(name))[1] = auth.uid()
|
|
64
|
+
// SELECT policy dopuszcza też członka wątku: is_thread_member(auth.uid(), foldername[2])
|
|
65
|
+
// voice-messages → bucket istnieje. INSERT policy
|
|
66
|
+
// "Users can upload voice messages": foldername(name)[1] = auth.uid()
|
|
67
|
+
// Poprzednie domyślne ('file-blobs' dla file, 'voice-blobs' dla voice/ptt) NIE
|
|
68
|
+
// ISTNIEJĄ w projekcie — stąd "Bucket not found" na mDM_send_file, mIRC_send_file
|
|
69
|
+
// i mDM_send_voice. Nazwy są tu jednym źródłem prawdy: gdy bucket zniknie,
|
|
70
|
+
// zawodzi JAWNIE, a nie po cichu ląduje w innym miejscu.
|
|
71
|
+
return kind === "file" ? "chat-files" : "voice-messages";
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** `sub` z JWT tej sesji, czyli `auth.uid()` — PIERWSZY segment ścieżki.
|
|
75
|
+
*
|
|
76
|
+
* ⛔ NIE OZDOBA I NIE OPCJA. Jedyny segment, który sprawdzają polityki INSERT obu
|
|
77
|
+
* bucketów: `(storage.foldername(name))[1] = auth.uid()`. Ścieżka bez segmentu
|
|
78
|
+
* użytkownika (`<thread>/<uuid>.ext`, jak było) przechodzi upload do momentu,
|
|
79
|
+
* w którym baza odrzuca wiersz — czyli wysyłka pliku jest ZAWSZE martwa, i to
|
|
80
|
+
* komunikatem, który nie mówi dlaczego. Ta sama konwencja co w aplikacji:
|
|
81
|
+
* `apps/web/src/lib/ircApi.ts: uploadChatFile()` → `<user.id>/<thread>/<ts>_<nazwa>`.
|
|
82
|
+
*/
|
|
83
|
+
function jwtSub(jwt: string): string | null {
|
|
84
|
+
const part = jwt.split(".")[1];
|
|
85
|
+
if (!part) return null;
|
|
86
|
+
try {
|
|
87
|
+
const json = JSON.parse(Buffer.from(part.replace(/-/g, "+").replace(/_/g, "/"), "base64").toString("utf8"));
|
|
88
|
+
return typeof json?.sub === "string" && json.sub ? json.sub : null;
|
|
89
|
+
} catch {
|
|
90
|
+
return null;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function ownerFolder(userJwt: string | undefined): string {
|
|
95
|
+
const sub = userJwt ? jwtSub(userJwt) : null;
|
|
96
|
+
if (!sub) {
|
|
97
|
+
throw new Error(
|
|
98
|
+
"blob upload refused: no user id in the session JWT — bucket policy requires foldername[1] = auth.uid(); run `mosadd login` (or set MOSADD_USER_JWT) and retry",
|
|
99
|
+
);
|
|
100
|
+
}
|
|
101
|
+
return sub;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function randomId(): string {
|
|
105
|
+
// crypto.randomUUID is available on Node >=18 (package engines floor).
|
|
106
|
+
return globalThis.crypto?.randomUUID?.() ?? `${Date.now()}-${Math.random().toString(36).slice(2)}`;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Upload bytes to Supabase Storage and return the attachment descriptor to embed
|
|
111
|
+
* in `message-send`'s `attachments[]`.
|
|
112
|
+
*/
|
|
113
|
+
export async function uploadBlob(args: UploadBlobArgs): Promise<AttachmentDescriptor> {
|
|
114
|
+
const env = readSupabaseEnv();
|
|
115
|
+
const sb = getSupabase();
|
|
116
|
+
const bucket = args.bucket ?? defaultBucket(args.kind);
|
|
117
|
+
const ext = args.filename?.split(".").pop() ?? mimeExt(args.mime);
|
|
118
|
+
// ⛔ KOLEJNOŚĆ SEGMENTÓW JEST CZĘŚCIĄ KONTRAKTU Z POLITYKĄ: <auth.uid()>/<wątek>/<uuid>.<ext>.
|
|
119
|
+
const folder = args.prefix ? args.prefix.replace(/[^a-zA-Z0-9._/-]/g, "-").replace(/^\/+|\/+$/g, "") : "";
|
|
120
|
+
const path = [ownerFolder(env.userJwt), folder, `${randomId()}${ext ? "." + ext : ""}`]
|
|
121
|
+
.filter(Boolean).join("/");
|
|
122
|
+
|
|
123
|
+
const { error } = await sb.storage.from(bucket).upload(path, args.bytes, {
|
|
124
|
+
contentType: args.mime,
|
|
125
|
+
upsert: false,
|
|
126
|
+
});
|
|
127
|
+
if (error) {
|
|
128
|
+
throw new Error(`blob upload to ${bucket}/${path} failed: ${error.message}`);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
return {
|
|
132
|
+
kind: args.kind,
|
|
133
|
+
bucket,
|
|
134
|
+
path,
|
|
135
|
+
mime: args.mime,
|
|
136
|
+
duration_ms: args.duration_ms ?? null,
|
|
137
|
+
key_ref: args.key_ref ?? null,
|
|
138
|
+
filename: args.filename ?? null,
|
|
139
|
+
size_bytes: args.bytes.byteLength,
|
|
140
|
+
};
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
function mimeExt(mime: string): string {
|
|
144
|
+
const map: Record<string, string> = {
|
|
145
|
+
"audio/ogg": "ogg",
|
|
146
|
+
"audio/mpeg": "mp3",
|
|
147
|
+
"audio/mp4": "m4a",
|
|
148
|
+
"audio/wav": "wav",
|
|
149
|
+
"audio/webm": "webm",
|
|
150
|
+
};
|
|
151
|
+
return map[mime] ?? "";
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* Decode a base64 / data-URL string into bytes. Agents hand us audio/file
|
|
156
|
+
* content as base64 (MCP is JSON-only — no binary channel), so every voice/file
|
|
157
|
+
* tool funnels through this.
|
|
158
|
+
*/
|
|
159
|
+
export function decodeBase64Body(b64: string): Uint8Array {
|
|
160
|
+
const cleaned = b64.includes(",") && b64.startsWith("data:") ? b64.slice(b64.indexOf(",") + 1) : b64;
|
|
161
|
+
return new Uint8Array(Buffer.from(cleaned, "base64"));
|
|
162
|
+
}
|