@powerhousedao/switchboard 6.2.3-dev.79 → 6.2.3-dev.80

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 (38) hide show
  1. package/.tsbuild/test/boot-helpers.d.ts +2 -2
  2. package/.tsbuild/test/boot-helpers.d.ts.map +1 -1
  3. package/.tsbuild/test/boot-mcp-auth.test.d.ts +2 -0
  4. package/.tsbuild/test/boot-mcp-auth.test.d.ts.map +1 -0
  5. package/.tsbuild/test/served-schemas.test.d.ts +2 -0
  6. package/.tsbuild/test/served-schemas.test.d.ts.map +1 -0
  7. package/.tsbuild/test/workflow/runtime-host.test.d.ts +2 -0
  8. package/.tsbuild/test/workflow/runtime-host.test.d.ts.map +1 -0
  9. package/.tsbuild/tsconfig.tsbuildinfo +1 -1
  10. package/CHANGELOG.md +27 -0
  11. package/dist/from-env-BO0n9R02.mjs +2 -2
  12. package/dist/from-env-BO0n9R02.mjs.map +1 -1
  13. package/dist/index.mjs +1 -1
  14. package/dist/plugins/attachments.mjs +3 -3
  15. package/dist/plugins/workflows.mjs +3 -3
  16. package/dist/{server-CtGBZlTg.mjs → server-eNNf230W.mjs} +58 -9
  17. package/dist/server-eNNf230W.mjs.map +1 -0
  18. package/dist/server.d.mts +10 -0
  19. package/dist/server.d.mts.map +1 -1
  20. package/dist/server.mjs +3 -3
  21. package/dist/workflow-runtime-7GaJ13c9.d.mts.map +1 -1
  22. package/dist/{workflows-QY9Y2eoD.mjs → workflows-5Chwj98o.mjs} +72 -3
  23. package/dist/workflows-5Chwj98o.mjs.map +1 -0
  24. package/package.json +16 -16
  25. package/test/boot-helpers.ts +3 -2
  26. package/test/boot-mcp-auth.test.ts +449 -0
  27. package/test/goldens/packages.graphql +797 -0
  28. package/test/goldens/privacy.graphql +853 -0
  29. package/test/goldens/reactor-drive-nodes.graphql +827 -0
  30. package/test/goldens/resolvers.json +321 -0
  31. package/test/goldens/supergraph.graphql +5636 -0
  32. package/test/goldens/workflow-runtime.graphql +1403 -0
  33. package/test/served-schemas.test.ts +134 -0
  34. package/test/workflow/runtime-host.test.ts +20 -0
  35. package/test/workflow-runtime.test.ts +70 -0
  36. package/vitest.config.ts +14 -4
  37. package/dist/server-CtGBZlTg.mjs.map +0 -1
  38. package/dist/workflows-QY9Y2eoD.mjs.map +0 -1
@@ -0,0 +1,449 @@
1
+ // /mcp on a booted Switchboard with document permissions: the official MCP
2
+ // client over HTTP and GraphQL, as callers holding real did:key bearers.
3
+ import { mkdtemp, rm } from "node:fs/promises";
4
+ import { createRequire } from "node:module";
5
+ import { tmpdir } from "node:os";
6
+ import { join } from "node:path";
7
+ import { addFolder } from "@powerhousedao/shared/document-drive";
8
+ import { MemoryKeyStorage, RenownCryptoBuilder } from "@renown/sdk/node";
9
+ import type { ILogger } from "document-model";
10
+ import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
11
+ import type { SwitchboardReactor } from "../src/types.js";
12
+ import { bootSwitchboard } from "./boot-helpers.js";
13
+
14
+ // The SDK is reactor-mcp's dependency; the switchboard does not declare it.
15
+ const sdk = createRequire(
16
+ new URL("../../../packages/reactor-mcp/package.json", import.meta.url),
17
+ );
18
+ type ToolResult = {
19
+ structuredContent?: unknown;
20
+ isError?: boolean;
21
+ content?: unknown;
22
+ };
23
+ type McpClient = {
24
+ connect(transport: unknown): Promise<void>;
25
+ listTools(): Promise<{ tools: { name: string }[] }>;
26
+ callTool(request: {
27
+ name: string;
28
+ arguments: Record<string, unknown>;
29
+ }): Promise<ToolResult>;
30
+ close(): Promise<void>;
31
+ };
32
+ const { Client } = sdk("@modelcontextprotocol/sdk/client/index.js") as {
33
+ Client: new (info: { name: string; version: string }) => McpClient;
34
+ };
35
+ const { StreamableHTTPClientTransport } = sdk(
36
+ "@modelcontextprotocol/sdk/client/streamableHttp.js",
37
+ ) as {
38
+ StreamableHTTPClientTransport: new (
39
+ url: URL,
40
+ options: { requestInit: RequestInit },
41
+ ) => unknown;
42
+ };
43
+
44
+ const ADMIN = "0x1111111111111111111111111111111111111111";
45
+ const READER = "0x2222222222222222222222222222222222222222";
46
+ const WRITER = "0x3333333333333333333333333333333333333333";
47
+ const OUTSIDER = "0x4444444444444444444444444444444444444444";
48
+ const USERS = [ADMIN, READER, WRITER, OUTSIDER] as const;
49
+ type Caller = (typeof USERS)[number] | "anonymous";
50
+ const CALLERS: Caller[] = [...USERS, "anonymous"];
51
+
52
+ const ENV_KEYS = [
53
+ "PH_REACTOR_DATABASE_URL",
54
+ "MCP_ENABLED",
55
+ "FEATURE_PLUGIN_HOST_ENABLED",
56
+ "AUTH_ENABLED",
57
+ "ADMINS",
58
+ "RESOLVE_CALLER_IDENTITY",
59
+ "SKIP_CREDENTIAL_VERIFICATION",
60
+ ] as const;
61
+
62
+ const logger = {
63
+ verbose: vi.fn(),
64
+ debug: vi.fn(),
65
+ info: vi.fn(),
66
+ warn: vi.fn(),
67
+ error: vi.fn(),
68
+ child: () => logger,
69
+ } as unknown as ILogger;
70
+
71
+ // A Renown login's bearer: a JWT signed by a fresh did:key, naming `address`.
72
+ async function bearerFor(address: string): Promise<string> {
73
+ const crypto = await new RenownCryptoBuilder()
74
+ .withKeyPairStorage(new MemoryKeyStorage())
75
+ .build();
76
+ return crypto.getBearerToken(address);
77
+ }
78
+
79
+ let tempRoot = "";
80
+ let previous: [string, string | undefined][] = [];
81
+ let switchboard: SwitchboardReactor | undefined;
82
+ let tokens: Record<string, string> = {};
83
+ let shared = "";
84
+ let open = "";
85
+
86
+ const base = () => `http://127.0.0.1:${switchboard!.port}`;
87
+ const authorization = (caller: Caller): Record<string, string> =>
88
+ caller === "anonymous" ? {} : { authorization: `Bearer ${tokens[caller]}` };
89
+
90
+ type GraphqlResult = {
91
+ status: number;
92
+ errors?: { extensions?: { code?: string } }[];
93
+ data?: Record<string, unknown>;
94
+ };
95
+
96
+ async function graphql(
97
+ caller: Caller,
98
+ query: string,
99
+ variables: Record<string, unknown> = {},
100
+ ): Promise<GraphqlResult> {
101
+ const response = await fetch(`${base()}/graphql`, {
102
+ method: "POST",
103
+ headers: { "content-type": "application/json", ...authorization(caller) },
104
+ body: JSON.stringify({ query, variables }),
105
+ });
106
+ const body = (await response.json()) as Omit<GraphqlResult, "status">;
107
+ return { status: response.status, ...body };
108
+ }
109
+
110
+ async function graphqlOk(caller: Caller, query: string, variables = {}) {
111
+ const result = await graphql(caller, query, variables);
112
+ expect(result.errors, JSON.stringify(result.errors)).toBeUndefined();
113
+ return result.data!;
114
+ }
115
+
116
+ beforeAll(async () => {
117
+ tempRoot = await mkdtemp(join(tmpdir(), "switchboard-mcp-auth-"));
118
+ previous = ENV_KEYS.map((name) => [name, process.env[name]]);
119
+ for (const name of ENV_KEYS) delete process.env[name];
120
+ process.env.PH_REACTOR_DATABASE_URL = join(tempRoot, "reactor-storage");
121
+
122
+ switchboard = await bootSwitchboard(
123
+ {
124
+ server: { port: 0 },
125
+ storage: { readModel: { url: join(tempRoot, "read-model") } },
126
+ features: { workflows: false, mcp: true },
127
+ packages: { disableLocal: true },
128
+ identity: { keypairPath: join(tempRoot, "identity.json") },
129
+ protocol: {
130
+ featureFlags: { documentDecisions: true, authEnforcement: true },
131
+ },
132
+ auth: {
133
+ enabled: true,
134
+ admins: [ADMIN],
135
+ documentPermissions: { enabled: true },
136
+ // The bearer's signature is still verified; only the Renown lookup
137
+ // of its credential is skipped, as the boot allows under vitest.
138
+ skipCredentialVerification: true,
139
+ // No discovery request: every write here is the host's own.
140
+ renown: { switchboardUrl: "http://127.0.0.1:9/graphql" },
141
+ },
142
+ },
143
+ { logger },
144
+ );
145
+
146
+ tokens = Object.fromEntries(
147
+ await Promise.all(
148
+ USERS.map(
149
+ async (address) => [address, await bearerFor(address)] as const,
150
+ ),
151
+ ),
152
+ );
153
+
154
+ const { reactor } = switchboard;
155
+ const drive = async (name: string) => {
156
+ const handle = await reactor.write.drives.create({ global: { name } });
157
+ await handle.readable;
158
+ return handle.documentId;
159
+ };
160
+ shared = await drive("Shared");
161
+ open = await drive("Open");
162
+ // The ACL GraphQL decides with, set through GraphQL by the admin.
163
+ await graphqlOk(
164
+ ADMIN,
165
+ `mutation ($id: String!) { setDocumentProtection(documentIdOrSlug: $id, protected: true) { documentId } }`,
166
+ { id: shared },
167
+ );
168
+ for (const [user, permission] of [
169
+ [READER, "READ"],
170
+ [WRITER, "WRITE"],
171
+ ]) {
172
+ await graphqlOk(
173
+ ADMIN,
174
+ `mutation ($id: String!, $user: String!, $permission: DocumentPermissionLevel!) {
175
+ grantDocumentPermission(documentIdOrSlug: $id, userAddress: $user, permission: $permission) { documentId }
176
+ }`,
177
+ { id: shared, user, permission },
178
+ );
179
+ }
180
+ }, 60_000);
181
+
182
+ afterAll(async () => {
183
+ await switchboard?.shutdown();
184
+ for (const [name, value] of previous) {
185
+ if (value === undefined) delete process.env[name];
186
+ else process.env[name] = value;
187
+ }
188
+ await rm(tempRoot, { recursive: true, force: true });
189
+ });
190
+
191
+ async function withClient<T>(
192
+ caller: Caller,
193
+ run: (
194
+ call: (name: string, args?: object) => Promise<ToolResult>,
195
+ ) => Promise<T>,
196
+ ): Promise<T> {
197
+ const client = new Client({ name: "boot-mcp-auth", version: "1.0.0" });
198
+ await client.connect(
199
+ new StreamableHTTPClientTransport(new URL(`${base()}/mcp`), {
200
+ requestInit: { headers: authorization(caller) },
201
+ }),
202
+ );
203
+ try {
204
+ return await run((name, args = {}) =>
205
+ client.callTool({ name, arguments: args as Record<string, unknown> }),
206
+ );
207
+ } finally {
208
+ await client.close();
209
+ }
210
+ }
211
+
212
+ const forbiddenTool = (result: ToolResult) =>
213
+ result.isError === true &&
214
+ JSON.stringify(result.content).includes("FORBIDDEN");
215
+
216
+ const forbiddenGraphql = (result: GraphqlResult) =>
217
+ result.errors?.some((e) => e.extensions?.code === "FORBIDDEN") ?? false;
218
+
219
+ async function postPing(header?: string): Promise<number> {
220
+ const response = await fetch(`${base()}/mcp`, {
221
+ method: "POST",
222
+ headers: {
223
+ "content-type": "application/json",
224
+ accept: "application/json, text/event-stream",
225
+ ...(header ? { authorization: header } : {}),
226
+ },
227
+ body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "ping" }),
228
+ });
229
+ await response.body?.cancel();
230
+ return response.status;
231
+ }
232
+
233
+ describe("Switchboard's /mcp authorizes as its GraphQL API does", () => {
234
+ it("admits the callers GraphQL admits and refuses a bad bearer", async () => {
235
+ for (const caller of CALLERS) {
236
+ expect(await postPing(authorization(caller).authorization)).toBe(200);
237
+ }
238
+ expect(await postPing("Bearer not-a-jwt")).toBe(401);
239
+ expect((await graphql(READER, "{ __typename }")).status).toBe(200);
240
+ const bad = await fetch(`${base()}/graphql`, {
241
+ method: "POST",
242
+ headers: {
243
+ "content-type": "application/json",
244
+ authorization: "Bearer not-a-jwt",
245
+ },
246
+ body: JSON.stringify({ query: "{ __typename }" }),
247
+ });
248
+ expect(bad.status).toBe(401);
249
+ });
250
+
251
+ it("refuses and allows each caller the same read", async () => {
252
+ const decisions = await Promise.all(
253
+ CALLERS.map(async (caller) => {
254
+ const viaGraphql = await graphql(
255
+ caller,
256
+ `
257
+ query ($id: String!) {
258
+ document(idOrSlug: $id) {
259
+ document {
260
+ id
261
+ }
262
+ }
263
+ }
264
+ `,
265
+ { id: shared },
266
+ );
267
+ const viaMcp = await withClient(caller, (call) =>
268
+ call("getDrive", { driveId: shared }),
269
+ );
270
+ return {
271
+ caller,
272
+ graphql: forbiddenGraphql(viaGraphql) ? "forbidden" : "allowed",
273
+ mcp: forbiddenTool(viaMcp) ? "forbidden" : "allowed",
274
+ };
275
+ }),
276
+ );
277
+
278
+ const allowed = [ADMIN, READER, WRITER];
279
+ for (const decision of decisions) {
280
+ const expected = allowed.includes(decision.caller)
281
+ ? "allowed"
282
+ : "forbidden";
283
+ expect(decision).toEqual({
284
+ caller: decision.caller,
285
+ graphql: expected,
286
+ mcp: expected,
287
+ });
288
+ }
289
+ });
290
+
291
+ it("lists the same drives to each caller", async () => {
292
+ for (const caller of [READER, OUTSIDER] as const) {
293
+ const data = await graphqlOk(
294
+ caller,
295
+ `{ findDocuments(search: { type: "powerhouse/document-drive" }) { items { id } } }`,
296
+ );
297
+ const viaGraphql = (
298
+ data.findDocuments as { items: { id: string }[] }
299
+ ).items.map((d) => d.id);
300
+ const viaMcp = await withClient(caller, async (call) =>
301
+ (
302
+ (await call("getDrives")).structuredContent as {
303
+ drives: { id: string }[];
304
+ }
305
+ ).drives.map((d) => d.id),
306
+ );
307
+ expect(viaMcp.sort()).toEqual(viaGraphql.sort());
308
+ expect(viaMcp.includes(shared)).toBe(caller === READER);
309
+ expect(viaMcp).toContain(open);
310
+ }
311
+ });
312
+
313
+ it("refuses and allows each caller the same write", async () => {
314
+ for (const caller of CALLERS) {
315
+ const folder = (via: string) => {
316
+ const { id, type, input, scope, timestampUtcMs } = addFolder({
317
+ id: `${via}-${caller}`,
318
+ name: `${via}-${caller}`,
319
+ });
320
+ return { id, type, input, scope, timestampUtcMs };
321
+ };
322
+ const viaGraphql = await graphql(
323
+ caller,
324
+ `
325
+ mutation ($id: String!, $actions: [ActionInput!]!) {
326
+ execute(documentIdOrSlug: $id, actions: $actions) {
327
+ id
328
+ }
329
+ }
330
+ `,
331
+ { id: shared, actions: [folder("graphql")] },
332
+ );
333
+ const { type, input } = folder("mcp");
334
+ const viaMcp = await withClient(caller, (call) =>
335
+ call("addActions", { documentId: shared, actions: [{ type, input }] }),
336
+ );
337
+ const mayWrite = caller === ADMIN || caller === WRITER;
338
+
339
+ expect(forbiddenGraphql(viaGraphql), caller).toBe(!mayWrite);
340
+ if (mayWrite) {
341
+ expect(viaMcp.structuredContent, caller).toMatchObject({
342
+ success: true,
343
+ });
344
+ } else if (caller !== READER) {
345
+ // addActions reads its target first, so a non-reader is refused there.
346
+ expect(forbiddenTool(viaMcp), caller).toBe(true);
347
+ } else {
348
+ expect(viaMcp.structuredContent, caller).toMatchObject({
349
+ success: false,
350
+ results: [{ index: 0, error: { kind: "denied" } }],
351
+ });
352
+ }
353
+ }
354
+ const drive = await switchboard!.reactor.read.get(shared);
355
+ const nodes = (
356
+ drive.state as unknown as { global: { nodes: { id: string }[] } }
357
+ ).global.nodes.map((n) => n.id);
358
+ expect(nodes.sort()).toEqual(
359
+ [
360
+ `graphql-${ADMIN}`,
361
+ `graphql-${WRITER}`,
362
+ `mcp-${ADMIN}`,
363
+ `mcp-${WRITER}`,
364
+ ].sort(),
365
+ );
366
+ });
367
+
368
+ it("refuses and allows each caller the same creates", async () => {
369
+ for (const caller of CALLERS) {
370
+ const inDrive = await graphql(
371
+ caller,
372
+ `
373
+ mutation ($parent: String!) {
374
+ createEmptyDocument(
375
+ documentType: "powerhouse/document-model"
376
+ parentIdOrSlug: $parent
377
+ ) {
378
+ id
379
+ }
380
+ }
381
+ `,
382
+ { parent: shared },
383
+ );
384
+ const loose = await graphql(
385
+ caller,
386
+ `
387
+ mutation {
388
+ createEmptyDocument(documentType: "powerhouse/document-model") {
389
+ id
390
+ }
391
+ }
392
+ `,
393
+ );
394
+ const viaMcp = await withClient(caller, async (call) => ({
395
+ inDrive: await call("createDocument", {
396
+ documentType: "powerhouse/document-model",
397
+ driveId: shared,
398
+ }),
399
+ loose: await call("createDocument", {
400
+ documentType: "powerhouse/document-model",
401
+ }),
402
+ }));
403
+
404
+ expect(viaMcp.inDrive.isError === true, caller).toBe(
405
+ forbiddenGraphql(inDrive),
406
+ );
407
+ expect(viaMcp.loose.isError === true, caller).toBe(
408
+ (loose.errors?.length ?? 0) > 0,
409
+ );
410
+ }
411
+ });
412
+
413
+ it("makes an MCP creator the owner GraphQL then lets manage the document", async () => {
414
+ const documentId = await withClient(OUTSIDER, async (call) => {
415
+ const created = await call("createDocument", {
416
+ documentType: "powerhouse/document-model",
417
+ });
418
+ return (created.structuredContent as { documentId: string }).documentId;
419
+ });
420
+ const data = await graphqlOk(
421
+ OUTSIDER,
422
+ `mutation ($id: String!) { setDocumentProtection(documentIdOrSlug: $id, protected: true) { documentId } }`,
423
+ { id: documentId },
424
+ );
425
+ expect(data.setDocumentProtection).toEqual({ documentId });
426
+ const refused = await withClient(READER, (call) =>
427
+ call("getDocument", { documentId }),
428
+ );
429
+ expect(forbiddenTool(refused)).toBe(true);
430
+ });
431
+
432
+ it("refuses a delete the caller may not make, as GraphQL does", async () => {
433
+ const viaGraphql = await graphql(
434
+ READER,
435
+ `
436
+ mutation ($id: String!) {
437
+ deleteDocument(idOrSlug: $id)
438
+ }
439
+ `,
440
+ { id: shared },
441
+ );
442
+ const viaMcp = await withClient(READER, (call) =>
443
+ call("deleteDrive", { documentId: shared }),
444
+ );
445
+ expect(forbiddenGraphql(viaGraphql)).toBe(true);
446
+ expect(forbiddenTool(viaMcp)).toBe(true);
447
+ await expect(switchboard!.reactor.read.get(shared)).resolves.toBeDefined();
448
+ });
449
+ });