javascript-solid-server 0.0.200 → 0.0.202

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/src/mcp/tools.js CHANGED
@@ -11,13 +11,38 @@
11
11
 
12
12
  import * as storage from '../storage/filesystem.js';
13
13
  import { checkAccess } from '../wac/checker.js';
14
- import { AccessMode } from '../wac/parser.js';
14
+ import { AccessMode, parseAcl, serializeAcl } from '../wac/parser.js';
15
+ import { resourceEvents, emitChange } from '../notifications/events.js';
15
16
  import { toolText, toolError, toolJson } from './protocol.js';
16
17
  import { discoverSkills, readSkill, readPodSkill } from './skills.js';
17
18
  import { readFile, readdir, stat as fsStat } from 'fs/promises';
18
19
  import { join, dirname, resolve as pathResolve } from 'path';
19
20
  import { fileURLToPath } from 'url';
20
21
 
22
+ const ACL_NS = 'http://www.w3.org/ns/auth/acl#';
23
+ const FOAF_AGENT = 'http://xmlns.com/foaf/0.1/Agent';
24
+ const ACL_AUTH_AGENT = 'http://www.w3.org/ns/auth/acl#AuthenticatedAgent';
25
+ const SHORT_MODE = {
26
+ [`${ACL_NS}Read`]: 'Read',
27
+ [`${ACL_NS}Write`]: 'Write',
28
+ [`${ACL_NS}Append`]: 'Append',
29
+ [`${ACL_NS}Control`]: 'Control'
30
+ };
31
+ const SHORT_AGENT_CLASS = {
32
+ [FOAF_AGENT]: 'foaf:Agent',
33
+ [ACL_AUTH_AGENT]: 'acl:AuthenticatedAgent'
34
+ };
35
+ const FULL_MODE = {
36
+ Read: `${ACL_NS}Read`,
37
+ Write: `${ACL_NS}Write`,
38
+ Append: `${ACL_NS}Append`,
39
+ Control: `${ACL_NS}Control`
40
+ };
41
+ const FULL_AGENT_CLASS = {
42
+ 'foaf:Agent': FOAF_AGENT,
43
+ 'acl:AuthenticatedAgent': ACL_AUTH_AGENT
44
+ };
45
+
21
46
  const __dirname = dirname(fileURLToPath(import.meta.url));
22
47
  const JSS_DOCS_DIR = pathResolve(__dirname, '..', '..', 'docs');
23
48
 
@@ -114,6 +139,7 @@ async function write_resource({ path, content, contentType }, ctx) {
114
139
  await storage.write(path, Buffer.from(content, 'utf8'), {
115
140
  contentType: contentType || 'text/plain'
116
141
  });
142
+ emitChange(buildUrl(ctx, path));
117
143
  return toolText(`wrote ${path} (${Buffer.byteLength(content, 'utf8')} bytes)`);
118
144
  }
119
145
 
@@ -131,11 +157,13 @@ async function create_resource({ container, slug, content, contentType, isContai
131
157
  const childPath = `${container}${name}${isContainer ? '/' : ''}`;
132
158
  if (isContainer) {
133
159
  await storage.createContainer(childPath);
160
+ emitChange(buildUrl(ctx, childPath));
134
161
  return toolText(`created container ${childPath}`);
135
162
  }
136
163
  await storage.write(childPath, Buffer.from(content || '', 'utf8'), {
137
164
  contentType: contentType || 'text/plain'
138
165
  });
166
+ emitChange(buildUrl(ctx, childPath));
139
167
  return toolText(`created ${childPath}`);
140
168
  }
141
169
 
@@ -148,6 +176,7 @@ async function delete_resource({ path }, ctx) {
148
176
  return toolError(`not found: ${path}`);
149
177
  }
150
178
  await storage.remove(path);
179
+ emitChange(buildUrl(ctx, path));
151
180
  return toolText(`deleted ${path}`);
152
181
  }
153
182
 
@@ -220,6 +249,296 @@ async function read_docs({ name }, _ctx) {
220
249
  }
221
250
  }
222
251
 
252
+ // --- ACL tools (#496) ---
253
+
254
+ function aclUrlFor(path) {
255
+ // For containers, ACL is <container>.acl
256
+ // For resources, ACL is <resource>.acl
257
+ if (path.endsWith('/')) return path + '.acl';
258
+ return path + '.acl';
259
+ }
260
+
261
+ function shortMode(mode) {
262
+ return SHORT_MODE[mode] || mode;
263
+ }
264
+
265
+ function shortAgentClass(uri) {
266
+ return SHORT_AGENT_CLASS[uri] || uri;
267
+ }
268
+
269
+ function fullMode(mode) {
270
+ return FULL_MODE[mode] || mode;
271
+ }
272
+
273
+ function fullAgentClass(value) {
274
+ return FULL_AGENT_CLASS[value] || value;
275
+ }
276
+
277
+ async function read_acl({ path }, ctx) {
278
+ if (!path) return toolError('path required');
279
+ // Reading the ACL document itself requires Control on the resource.
280
+ if (!(await wac(ctx, path, AccessMode.CONTROL))) {
281
+ return toolError(`access denied: control ${path}`);
282
+ }
283
+ const aclPath = aclUrlFor(path);
284
+ if (!(await storage.exists(aclPath))) {
285
+ return toolJson({ path, aclPath, exists: false, authorizations: [] });
286
+ }
287
+ const content = await storage.read(aclPath);
288
+ const aclUrl = buildUrl(ctx, aclPath);
289
+ const auths = await parseAcl(content.toString('utf8'), aclUrl);
290
+ return toolJson({
291
+ path,
292
+ aclPath,
293
+ exists: true,
294
+ authorizations: auths.map(a => ({
295
+ agents: a.agents || [],
296
+ agentClasses: (a.agentClasses || []).map(shortAgentClass),
297
+ modes: (a.modes || []).map(shortMode),
298
+ isDefault: !!a.default
299
+ }))
300
+ });
301
+ }
302
+
303
+ function buildAclDoc(structured) {
304
+ const graph = structured.authorizations.map((auth, i) => {
305
+ const node = {
306
+ '@id': `#auth${i}`,
307
+ '@type': 'acl:Authorization',
308
+ 'acl:accessTo': { '@id': './' },
309
+ 'acl:mode': (auth.modes || []).map(m => ({ '@id': `acl:${m}` }))
310
+ };
311
+ if (auth.agents && auth.agents.length) {
312
+ node['acl:agent'] = auth.agents.map(a => ({ '@id': a }));
313
+ }
314
+ if (auth.agentClasses && auth.agentClasses.length) {
315
+ node['acl:agentClass'] = auth.agentClasses.map(c => ({
316
+ '@id': fullAgentClass(c)
317
+ }));
318
+ }
319
+ if (auth.isDefault) {
320
+ node['acl:default'] = { '@id': './' };
321
+ }
322
+ return node;
323
+ });
324
+ return {
325
+ '@context': {
326
+ acl: ACL_NS,
327
+ foaf: 'http://xmlns.com/foaf/0.1/'
328
+ },
329
+ '@graph': graph
330
+ };
331
+ }
332
+
333
+ async function write_acl({ path, authorizations }, ctx) {
334
+ if (!path) return toolError('path required');
335
+ if (!Array.isArray(authorizations)) {
336
+ return toolError('authorizations must be an array');
337
+ }
338
+ // Writing the ACL document requires Control on the resource.
339
+ if (!(await wac(ctx, path, AccessMode.CONTROL))) {
340
+ return toolError(`access denied: control ${path}`);
341
+ }
342
+ const aclPath = aclUrlFor(path);
343
+ const doc = buildAclDoc({ authorizations });
344
+ const serialized = serializeAcl(doc);
345
+
346
+ // Safety: refuse to write an ACL that would lock the caller out of
347
+ // future Control. This is the most common write_acl footgun —
348
+ // typically caused by relative WebID paths in `agents` resolving
349
+ // against the .acl URL to a different absolute URI than the caller's
350
+ // actual WebID. Parse the proposed ACL with its real URL so relative
351
+ // agents resolve correctly, then check whether any authorization
352
+ // grants Control to the caller.
353
+ const aclAbsUrl = buildUrl(ctx, aclPath);
354
+ const proposed = await parseAcl(serialized, aclAbsUrl);
355
+ const callerHasControl = proposed.some(auth => {
356
+ if (!(auth.modes || []).includes(AccessMode.CONTROL)) return false;
357
+ if (ctx.webId && (auth.agents || []).includes(ctx.webId)) return true;
358
+ if ((auth.agentClasses || []).includes(FOAF_AGENT)) return true;
359
+ if (ctx.webId && (auth.agentClasses || []).includes(ACL_AUTH_AGENT)) return true;
360
+ return false;
361
+ });
362
+ if (!callerHasControl) {
363
+ return toolError(
364
+ `write_acl refused: the proposed ACL would not grant Control to the caller (${ctx.webId || 'anonymous'}). ` +
365
+ 'This is typically caused by relative WebID paths in agents resolving against the .acl URL — use absolute WebIDs. ' +
366
+ 'If you really want to remove your own access (e.g. transferring ownership), do it in two steps: ' +
367
+ 'first grant Control to the new owner, then have the new owner write_acl without you.'
368
+ );
369
+ }
370
+
371
+ await storage.write(aclPath, Buffer.from(serialized, 'utf8'), {
372
+ contentType: 'application/ld+json'
373
+ });
374
+ emitChange(buildUrl(ctx, aclPath));
375
+ return toolText(`wrote ${aclPath} (${authorizations.length} authorization${authorizations.length === 1 ? '' : 's'})`);
376
+ }
377
+
378
+ // --- subscribe (#494) ---
379
+ //
380
+ // `subscribe` is a streaming tool. The handler signals its streaming
381
+ // shape by returning { stream: true, init, run }. The MCP plugin
382
+ // switches the HTTP response to SSE when it sees this shape and calls
383
+ // `init` first (for the initial event) then `run(send, signal)` to push
384
+ // notifications until the client disconnects.
385
+
386
+ function pathMatchesScope(eventUrl, scopePath, origin) {
387
+ if (!eventUrl.startsWith(origin)) return false;
388
+ const eventPath = eventUrl.slice(origin.length);
389
+ if (scopePath === '/') return true;
390
+ if (scopePath.endsWith('/')) return eventPath.startsWith(scopePath);
391
+ return eventPath === scopePath;
392
+ }
393
+
394
+ function subscribe({ path }, ctx) {
395
+ const scope = path || '/';
396
+ return {
397
+ stream: true,
398
+ async init() {
399
+ return {
400
+ type: 'subscribed',
401
+ scope,
402
+ origin: ctx.origin,
403
+ identity: ctx.webId || null
404
+ };
405
+ },
406
+ async run(send, signal) {
407
+ const onChange = async (eventUrl) => {
408
+ if (signal.aborted) return;
409
+ if (!pathMatchesScope(eventUrl, scope, ctx.origin)) return;
410
+
411
+ // Per-event WAC filter — don't leak resources the subscriber
412
+ // can't see. The check is best-effort: if the resource was just
413
+ // deleted we may not have storage to read its ACL from, so we
414
+ // err on the side of not emitting.
415
+ const eventPath = eventUrl.slice(ctx.origin.length);
416
+ try {
417
+ const allowed = await wac(ctx, eventPath, AccessMode.READ);
418
+ if (!allowed) return;
419
+ } catch {
420
+ return;
421
+ }
422
+ send({
423
+ type: 'resource_changed',
424
+ path: eventPath,
425
+ url: eventUrl
426
+ });
427
+ };
428
+ resourceEvents.on('change', onChange);
429
+ const cleanup = () => resourceEvents.off('change', onChange);
430
+ signal.addEventListener('abort', cleanup, { once: true });
431
+ // Resolve when aborted — keeps the stream open until client disconnect
432
+ await new Promise(resolve => signal.addEventListener('abort', resolve, { once: true }));
433
+ cleanup();
434
+ }
435
+ };
436
+ }
437
+
438
+ // --- federation (#495) ---
439
+
440
+ // Conservative defaults locked in for v1. Future PRs may add more flexibility.
441
+ //
442
+ // 1. Federation gate is `<agent-pod>/private/federation/` — caller must
443
+ // have acl:Write there to initiate outbound federation. The agent's
444
+ // pod is derived from their WebID. Foreign WebIDs are denied (no
445
+ // local path to gate against).
446
+ // 2. No pod-resident credential storage — every call carries its own
447
+ // credentials in the `auth` argument (or none for anonymous reads).
448
+ // 3. Depth cap via MCP-Federation-Depth header, max 3.
449
+ const MAX_FEDERATION_DEPTH = 3;
450
+
451
+ function federationGatePathFor(webId, origin) {
452
+ if (!webId || !origin) return null;
453
+ if (!webId.startsWith(origin)) return null; // foreign WebID — deny
454
+ const localPath = webId.slice(origin.length);
455
+ // Extract pod root: everything up to and including the segment before /profile/
456
+ const profileIdx = localPath.indexOf('/profile/');
457
+ const podPath = profileIdx > 0 ? localPath.slice(0, profileIdx + 1) : '/';
458
+ return podPath + 'private/federation/';
459
+ }
460
+
461
+ async function call_remote_pod({ pod_url, tool, arguments: remoteArgs, auth }, ctx) {
462
+ if (!pod_url || typeof pod_url !== 'string') {
463
+ return toolError('pod_url required');
464
+ }
465
+ if (!tool || typeof tool !== 'string') {
466
+ return toolError('tool required');
467
+ }
468
+ try {
469
+ new URL(pod_url);
470
+ } catch {
471
+ return toolError(`pod_url is not a valid URL: ${pod_url}`);
472
+ }
473
+
474
+ // Local WAC gate — derived from the agent's WebID. Foreign or
475
+ // anonymous identities can't federate.
476
+ const gatePath = federationGatePathFor(ctx.webId, ctx.origin);
477
+ if (!gatePath) {
478
+ return toolError(
479
+ 'access denied: federation requires a local WebID identity (anonymous and foreign identities cannot initiate outbound federation)'
480
+ );
481
+ }
482
+ if (!(await wac(ctx, gatePath, AccessMode.WRITE))) {
483
+ return toolError(
484
+ `access denied: write ${gatePath} (federation gate). Owner must grant acl:Write at this path to delegate outbound federation.`
485
+ );
486
+ }
487
+
488
+ // Depth cap
489
+ const depth = (ctx.federationDepth ?? 0) + 1;
490
+ if (depth > MAX_FEDERATION_DEPTH) {
491
+ return toolError(`federation depth exceeded (max ${MAX_FEDERATION_DEPTH})`);
492
+ }
493
+
494
+ // Build remote MCP request
495
+ const remoteEndpoint = pod_url.replace(/\/+$/, '') + '/mcp';
496
+ const body = {
497
+ jsonrpc: '2.0',
498
+ id: 1,
499
+ method: 'tools/call',
500
+ params: { name: tool, arguments: remoteArgs || {} }
501
+ };
502
+
503
+ const headers = {
504
+ 'Content-Type': 'application/json',
505
+ 'MCP-Federation-Depth': String(depth)
506
+ };
507
+ if (auth && typeof auth === 'object') {
508
+ if (auth.type === 'bearer' && auth.token) {
509
+ headers.Authorization = `Bearer ${auth.token}`;
510
+ } else if (auth.type === 'header' && auth.name && auth.value) {
511
+ headers[auth.name] = auth.value;
512
+ }
513
+ }
514
+
515
+ let response, payload;
516
+ try {
517
+ response = await fetch(remoteEndpoint, {
518
+ method: 'POST',
519
+ headers,
520
+ body: JSON.stringify(body),
521
+ signal: AbortSignal.timeout(30_000)
522
+ });
523
+ } catch (e) {
524
+ return toolError(`remote pod unreachable: ${e.message}`);
525
+ }
526
+ try {
527
+ payload = await response.json();
528
+ } catch (e) {
529
+ return toolError(`remote response not JSON (${response.status}): ${e.message}`);
530
+ }
531
+ if (payload.error) {
532
+ return toolError(`remote MCP error ${payload.error.code}: ${payload.error.message}`);
533
+ }
534
+ return toolJson({
535
+ pod_url,
536
+ tool,
537
+ depth,
538
+ remote_result: payload.result || null
539
+ });
540
+ }
541
+
223
542
  // --- pod info ---
224
543
 
225
544
  async function pod_info(_args, ctx) {
@@ -345,6 +664,72 @@ export const TOOLS = {
345
664
  description: 'Basic pod identity and MCP capabilities.',
346
665
  inputSchema: { type: 'object', properties: {} },
347
666
  handler: pod_info
667
+ },
668
+ read_acl: {
669
+ description: 'Read the WAC ACL for a resource as a structured list of authorizations. Requires acl:Control.',
670
+ inputSchema: {
671
+ type: 'object',
672
+ properties: { path: { type: 'string' } },
673
+ required: ['path']
674
+ },
675
+ handler: read_acl
676
+ },
677
+ write_acl: {
678
+ description: 'Write a structured ACL for a resource. authorizations: [{ agents?, agentClasses?, modes, isDefault? }]. Requires acl:Control.',
679
+ inputSchema: {
680
+ type: 'object',
681
+ properties: {
682
+ path: { type: 'string' },
683
+ authorizations: {
684
+ type: 'array',
685
+ items: {
686
+ type: 'object',
687
+ properties: {
688
+ agents: { type: 'array', items: { type: 'string' } },
689
+ agentClasses: { type: 'array', items: { type: 'string', enum: ['foaf:Agent', 'acl:AuthenticatedAgent'] } },
690
+ modes: { type: 'array', items: { type: 'string', enum: ['Read', 'Write', 'Append', 'Control'] } },
691
+ isDefault: { type: 'boolean' }
692
+ },
693
+ required: ['modes']
694
+ }
695
+ }
696
+ },
697
+ required: ['path', 'authorizations']
698
+ },
699
+ handler: write_acl
700
+ },
701
+ subscribe: {
702
+ description: 'Subscribe to change events on a resource or container subtree. Returns an SSE stream of MCP notifications as resources change. WAC-filtered per event.',
703
+ inputSchema: {
704
+ type: 'object',
705
+ properties: {
706
+ path: { type: 'string', description: 'Container path (with trailing /) to watch a subtree, or exact resource path. Default: / (whole pod, filtered by Read access).' }
707
+ }
708
+ },
709
+ handler: subscribe
710
+ },
711
+ call_remote_pod: {
712
+ description: 'Invoke an MCP tool on another pod. Caller must have acl:Write on /private/federation/ on this pod. Depth-capped at 3.',
713
+ inputSchema: {
714
+ type: 'object',
715
+ properties: {
716
+ pod_url: { type: 'string', description: 'Origin of the remote pod (e.g. https://alice.example.com)' },
717
+ tool: { type: 'string', description: 'Tool name to invoke on the remote' },
718
+ arguments: { type: 'object', description: 'Arguments to pass to the remote tool' },
719
+ auth: {
720
+ type: 'object',
721
+ description: 'Auth for the remote call. Currently { type: "bearer", token } or { type: "header", name, value }. Omit for anonymous.',
722
+ properties: {
723
+ type: { type: 'string', enum: ['bearer', 'header'] },
724
+ token: { type: 'string' },
725
+ name: { type: 'string' },
726
+ value: { type: 'string' }
727
+ }
728
+ }
729
+ },
730
+ required: ['pod_url', 'tool']
731
+ },
732
+ handler: call_remote_pod
348
733
  }
349
734
  };
350
735
 
package/src/server.js CHANGED
@@ -1067,12 +1067,15 @@ export function createServer(options = {}) {
1067
1067
  password = password.slice(0, -1);
1068
1068
  return;
1069
1069
  }
1070
- // Only accept printable input — \P{C} excludes control codes,
1071
- // so escape sequences from arrow keys, function keys, etc. don't
1072
- // sneak invisible bytes into the password buffer.
1070
+ // Only accept printable input — reject C0/C1 control codes, so
1071
+ // escape sequences from arrow keys, function keys, etc. don't
1072
+ // sneak invisible bytes into the password buffer. Uses an explicit
1073
+ // ASCII/C1 control range rather than the \p{C} Unicode property
1074
+ // escape, which requires a full-ICU build and throws at parse time
1075
+ // on no-ICU runtimes (e.g. nodejs-mobile). See #520.
1073
1076
  if (!key.ctrl && !key.meta &&
1074
1077
  typeof str === 'string' && str.length > 0 &&
1075
- /^\P{C}+$/u.test(str)) {
1078
+ /^[^\u0000-\u001f\u007f-\u009f]+$/.test(str)) {
1076
1079
  password += str;
1077
1080
  }
1078
1081
  };
@@ -57,6 +57,14 @@ export async function tunnelPlugin(fastify, options = {}) {
57
57
  fastify.get(wsPath, { websocket: true }, async (connection, request) => {
58
58
  const socket = connection.socket;
59
59
 
60
+ // Browser WebSockets can't set an Authorization header, so accept the
61
+ // bearer token as a ?token= query param too — mirrors the /.webrtc
62
+ // endpoint. Lets browser-based tunnel clients authenticate. (#528)
63
+ const queryToken = request.query?.token;
64
+ if (queryToken && !request.headers.authorization) {
65
+ request.headers.authorization = `Bearer ${queryToken}`;
66
+ }
67
+
60
68
  // Authenticate
61
69
  const { webId } = await getWebIdFromRequestAsync(request);
62
70
  if (!webId) {