javascript-solid-server 0.0.212 → 0.0.214

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/auth.js ADDED
@@ -0,0 +1,50 @@
1
+ /**
2
+ * Public authentication api (#584).
3
+ *
4
+ * The stable import path for applications that authenticate their own
5
+ * traffic — app plugins mounted via `appPaths` (#582), external Fastify
6
+ * compositions, MCP-adjacent tooling. Everything in src/ is internal and
7
+ * may move; this file is the contract.
8
+ *
9
+ * import { getAgent } from 'javascript-solid-server/auth.js';
10
+ *
11
+ * const agent = await getAgent(request); // string | null
12
+ *
13
+ * Covers every credential scheme the server itself accepts, uniformly:
14
+ * IdP-issued Bearer tokens, Solid-OIDC DPoP, Nostr NIP-98 signatures,
15
+ * LWS10-CID, and WebID-TLS client certificates.
16
+ * The returned identifier is usually an HTTP(S) WebID;
17
+ * for NIP-98 it can be a `did:nostr:...` DID when no WebID mapping
18
+ * exists — DID agents are first-class here, which is why this is
19
+ * getAgent and not getWebId. Key your app's users on the string.
20
+ *
21
+ * Authentication only — deliberately not authorization:
22
+ * apps under an appPaths prefix own their own permissioning (WAC stays
23
+ * out of their jurisdiction, and `request.webId` is never set there).
24
+ *
25
+ * This is the pre-loader shape of the seam; when the plugin loader (#206)
26
+ * lands, `api.auth.getAgent` will be this same function handed to
27
+ * `activate(api)`.
28
+ */
29
+
30
+ import { getWebIdFromRequestAsync } from './src/auth/token.js';
31
+
32
+ /**
33
+ * Resolve the authenticated agent of a request.
34
+ * @param {object} request - a Fastify request. Pass the real request object:
35
+ * Bearer verification only reads `headers`, but DPoP (Solid-OIDC),
36
+ * NIP-98 and LWS-CID verification also read `method`, `url`, `protocol`
37
+ * and `hostname` to check what the credential was signed over.
38
+ * @returns {Promise<string|null>} the verified agent identifier — an
39
+ * HTTP(S) WebID, or a `did:nostr:` DID for NIP-98 agents without a
40
+ * WebID mapping — or null when anonymous / invalid. Never throws on
41
+ * bad credentials.
42
+ */
43
+ export async function getAgent(request) {
44
+ try {
45
+ const { webId } = await getWebIdFromRequestAsync(request);
46
+ return webId || null;
47
+ } catch {
48
+ return null;
49
+ }
50
+ }
@@ -350,6 +350,45 @@ When `--invite-only` is enabled:
350
350
 
351
351
  Invite codes are stored in `.server/invites.json` in your data directory.
352
352
 
353
+ ## Application Mount Points (appPaths)
354
+
355
+ Programmatic compositions can mount whole applications beside the pod
356
+ (the plugin-zero pattern from
357
+ [#206](https://github.com/JavaScriptSolidServer/JavaScriptSolidServer/issues/206)):
358
+
359
+ ```js
360
+ import { createServer } from 'javascript-solid-server/src/server.js';
361
+
362
+ const fastify = createServer({ appPaths: ['/myapp'] });
363
+ // Register both forms: fastify wildcards don't match the bare prefix.
364
+ fastify.all('/myapp', myAppHandler);
365
+ fastify.all('/myapp/*', myAppHandler); // the app owns auth below its prefix
366
+ await fastify.listen({ port: 4443 });
367
+ ```
368
+
369
+ Requests at or below an app path skip the WAC authorization hook — the
370
+ application authenticates and authorizes its own traffic, exactly like the
371
+ built-in `/storage/` and `/db/` routes. Everything outside the declared
372
+ prefixes keeps full WAC enforcement. Entries must start with `/` and be
373
+ longer than `/`; anything else is ignored.
374
+
375
+ Because the WAC hook is also what populates `request.webId`, requests under
376
+ an app path never carry it — don't rely on `request.webId` in app handlers.
377
+ Resolve identity with the public accessor
378
+ ([#584](https://github.com/JavaScriptSolidServer/JavaScriptSolidServer/issues/584)):
379
+
380
+ ```js
381
+ import { getAgent } from 'javascript-solid-server/auth.js';
382
+
383
+ const agent = await getAgent(request); // WebID or did:nostr DID, null if anonymous
384
+ ```
385
+
386
+ See [#582](https://github.com/JavaScriptSolidServer/JavaScriptSolidServer/issues/582)
387
+ for the design discussion and
388
+ [melvincarvalho/tideholm](https://github.com/melvincarvalho/tideholm/tree/gh-pages/jss-plugin)
389
+ for a complete example (a multiplayer game where pod WebIDs are the player
390
+ accounts).
391
+
353
392
  ## Storage Quotas
354
393
 
355
394
  Limit storage per pod to prevent abuse and manage resources:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "javascript-solid-server",
3
- "version": "0.0.212",
3
+ "version": "0.0.214",
4
4
  "description": "A minimal, fast Solid server",
5
5
  "main": "src/index.js",
6
6
  "type": "module",
package/src/server.js CHANGED
@@ -107,6 +107,16 @@ export function createServer(options = {}) {
107
107
  // Tunnel proxy is OFF by default
108
108
  const tunnelEnabled = options.tunnel ?? false;
109
109
  const tunnelPath = options.tunnelPath ?? '/.tunnel';
110
+ // Application mount points (plugin seam, #206): URL prefixes owned by
111
+ // registered apps (e.g. a game mounted at /tideholm). Requests below an
112
+ // app path skip the WAC hook — the app owns authentication and
113
+ // authorization under its prefix, like /storage/ and /db/ already do.
114
+ const appPaths = Array.isArray(options.appPaths)
115
+ ? options.appPaths
116
+ .filter((p) => typeof p === 'string')
117
+ .map((p) => p.trim().replace(/\/+$/, '')) // '/myapp/' matches like '/myapp'
118
+ .filter((p) => p.startsWith('/') && p.length > 1)
119
+ : [];
110
120
  // ActivityPub federation is OFF by default
111
121
  const activitypubEnabled = options.activitypub ?? false;
112
122
  const apUsername = options.apUsername ?? 'me';
@@ -719,6 +729,7 @@ export function createServer(options = {}) {
719
729
  (webrtcEnabled && (request.url === webrtcPath || request.url.startsWith(webrtcPath + '?'))) ||
720
730
  (terminalEnabled && (request.url === '/.terminal' || request.url.startsWith('/.terminal?'))) ||
721
731
  (tunnelEnabled && (request.url === tunnelPath || request.url.startsWith(tunnelPath + '?') || request.url.startsWith('/tunnel/'))) ||
732
+ appPaths.some(p => request.url === p || request.url.startsWith(p + '/') || request.url.startsWith(p + '?')) ||
722
733
  mashlibPaths.some(p => request.url === p || request.url.startsWith(p + '.'))) {
723
734
  return;
724
735
  }
@@ -0,0 +1,151 @@
1
+ /**
2
+ * appPaths — WAC-exempt application mount points (#582).
3
+ *
4
+ * The global WAC preHandler authorizes every URL against pod ACLs and
5
+ * rejects before routes run; the only escapes are its hardcoded prefix
6
+ * list (/storage/, /db, /mcp, …). That means a third-party app plugin
7
+ * registering routes on the returned fastify instance (#206's plugin-zero
8
+ * pattern, e.g. a game mounted at /tideholm) has its POSTs swallowed by
9
+ * WAC with no way to opt out.
10
+ *
11
+ * createServer({ appPaths: ['/myapp'] }) declares URL prefixes owned by
12
+ * registered applications: requests at or below an app path skip the WAC
13
+ * hook, and the app owns authentication and authorization under its
14
+ * prefix — exactly the deal the bundled pseudo-plugins already have.
15
+ *
16
+ * Tests verify the seam end-to-end: an app route mounted on the returned
17
+ * instance receives unauthenticated requests (WAC stays out), sibling LDP
18
+ * paths keep full WAC enforcement, and malformed appPaths entries are
19
+ * dropped rather than becoming accidental holes.
20
+ */
21
+
22
+ import { describe, it, before, after, afterEach } from 'node:test';
23
+ import assert from 'node:assert';
24
+ import { createServer } from '../src/server.js';
25
+ import fs from 'fs-extra';
26
+
27
+ const TEST_DATA_DIR = './test-data-app-paths';
28
+
29
+ let server;
30
+ let baseUrl;
31
+ let originalDataRoot;
32
+
33
+ async function startWith(appPaths) {
34
+ await fs.emptyDir(TEST_DATA_DIR);
35
+ server = createServer({
36
+ logger: false,
37
+ forceCloseConnections: true,
38
+ root: TEST_DATA_DIR,
39
+ appPaths,
40
+ });
41
+ // An app in the #206 plugin-zero shape: routes registered on the returned
42
+ // instance, answering with its own status codes (its own "auth").
43
+ server.all('/myapp', echo);
44
+ server.all('/myapp/*', echo);
45
+ async function echo(request, reply) {
46
+ reply.code(200).send({
47
+ app: true,
48
+ method: request.method,
49
+ url: request.url,
50
+ webId: request.webId ?? null, // hook skipped -> never set
51
+ });
52
+ }
53
+ await server.listen({ port: 0, host: '127.0.0.1' });
54
+ const address = server.server.address();
55
+ baseUrl = `http://127.0.0.1:${address.port}`;
56
+ }
57
+
58
+ describe('appPaths application mount points (#582)', () => {
59
+ before(() => {
60
+ // createServer({ root }) mutates process.env.DATA_ROOT; snapshot so the
61
+ // test dir doesn't leak into later suites.
62
+ originalDataRoot = process.env.DATA_ROOT;
63
+ });
64
+
65
+ afterEach(async () => {
66
+ if (server) {
67
+ await server.close();
68
+ server = null;
69
+ }
70
+ await fs.remove(TEST_DATA_DIR);
71
+ });
72
+
73
+ after(() => {
74
+ if (originalDataRoot === undefined) delete process.env.DATA_ROOT;
75
+ else process.env.DATA_ROOT = originalDataRoot;
76
+ });
77
+
78
+ it('unauthenticated POST below an app path reaches the app handler', async () => {
79
+ await startWith(['/myapp']);
80
+ const res = await fetch(`${baseUrl}/myapp/api/action`, {
81
+ method: 'POST',
82
+ headers: { 'Content-Type': 'application/json' },
83
+ body: JSON.stringify({ hello: 'world' }),
84
+ });
85
+ assert.strictEqual(res.status, 200);
86
+ const body = await res.json();
87
+ assert.strictEqual(body.app, true);
88
+ assert.strictEqual(body.method, 'POST');
89
+ });
90
+
91
+ it('the bare app path and query-string forms are exempt too', async () => {
92
+ await startWith(['/myapp']);
93
+ for (const path of ['/myapp', '/myapp?tab=map']) {
94
+ const res = await fetch(`${baseUrl}${path}`, { method: 'POST' });
95
+ assert.strictEqual(res.status, 200, `${path} should reach the app`);
96
+ }
97
+ });
98
+
99
+ it('the WAC hook never sets request.webId on app-path requests', async () => {
100
+ await startWith(['/myapp']);
101
+ const res = await fetch(`${baseUrl}/myapp/whoami`);
102
+ const body = await res.json();
103
+ assert.strictEqual(body.webId, null);
104
+ });
105
+
106
+ it('sibling LDP paths keep full WAC enforcement', async () => {
107
+ await startWith(['/myapp']);
108
+ // Writing outside the app prefix without auth must still be rejected.
109
+ const res = await fetch(`${baseUrl}/notes.jsonld`, {
110
+ method: 'PUT',
111
+ headers: { 'Content-Type': 'application/ld+json' },
112
+ body: JSON.stringify({ '@id': '', name: 'x' }),
113
+ });
114
+ assert.ok(res.status === 401 || res.status === 403,
115
+ `expected WAC rejection, got ${res.status}`);
116
+ });
117
+
118
+ it('a prefix match is a path-segment match, not a string prefix', async () => {
119
+ await startWith(['/myapp']);
120
+ // /myapplication must NOT be exempt just because it shares characters.
121
+ const res = await fetch(`${baseUrl}/myapplication.jsonld`, {
122
+ method: 'PUT',
123
+ headers: { 'Content-Type': 'application/ld+json' },
124
+ body: JSON.stringify({ '@id': '', name: 'x' }),
125
+ });
126
+ assert.ok(res.status === 401 || res.status === 403,
127
+ `expected WAC rejection, got ${res.status}`);
128
+ });
129
+
130
+ it('trailing-slash entries are normalized, children still exempt', async () => {
131
+ await startWith(['/myapp/']);
132
+ const res = await fetch(`${baseUrl}/myapp/api/action`, { method: 'POST' });
133
+ assert.strictEqual(res.status, 200);
134
+ });
135
+
136
+ it('malformed appPaths entries are dropped, not accidental holes', async () => {
137
+ // No leading slash and bare '/' are both invalid; with them filtered out
138
+ // the route registrations still exist but WAC fires first.
139
+ await startWith(['myapp', '/', '///', ' ']);
140
+ const res = await fetch(`${baseUrl}/myapp/api/action`, { method: 'POST' });
141
+ assert.ok(res.status === 401 || res.status === 403,
142
+ `expected WAC rejection (invalid entries dropped), got ${res.status}`);
143
+ });
144
+
145
+ it('omitting appPaths changes nothing (default off)', async () => {
146
+ await startWith(undefined);
147
+ const res = await fetch(`${baseUrl}/myapp/api/action`, { method: 'POST' });
148
+ assert.ok(res.status === 401 || res.status === 403,
149
+ `expected WAC rejection with no appPaths, got ${res.status}`);
150
+ });
151
+ });
@@ -0,0 +1,100 @@
1
+ /**
2
+ * getAgent — public request → agent-identifier accessor (#584).
3
+ *
4
+ * Apps that own their own auth (appPaths mounts, #582) need to ask "who is
5
+ * this?" without reaching into src/auth internals. auth.js at the package
6
+ * root is the stable contract; these tests pin its shape so auth refactors
7
+ * keep the seam:
8
+ *
9
+ * - anonymous / malformed credentials -> null, never a throw
10
+ * - a real IdP-issued Bearer token -> the account's WebID
11
+ *
12
+ * The identifier is an HTTP(S) WebID or, for NIP-98 agents without a WebID
13
+ * mapping, a did:nostr DID. The individual credential schemes (Bearer,
14
+ * DPoP, NIP-98, LWS10-CID, WebID-TLS) are exercised by their own suites;
15
+ * this one pins the public wrapper.
16
+ */
17
+
18
+ import { describe, it, before, after, afterEach } from 'node:test';
19
+ import assert from 'node:assert';
20
+ import { createServer } from '../src/server.js';
21
+ import { getAgent } from '../auth.js';
22
+ import fs from 'fs-extra';
23
+
24
+ const TEST_DATA_DIR = './test-data-auth-agent';
25
+
26
+ let server;
27
+ let baseUrl;
28
+ let originalDataRoot;
29
+
30
+ describe('public getAgent accessor (#584)', () => {
31
+ before(() => {
32
+ originalDataRoot = process.env.DATA_ROOT;
33
+ });
34
+
35
+ afterEach(async () => {
36
+ if (server) {
37
+ await server.close();
38
+ server = null;
39
+ }
40
+ await fs.remove(TEST_DATA_DIR);
41
+ });
42
+
43
+ after(() => {
44
+ if (originalDataRoot === undefined) delete process.env.DATA_ROOT;
45
+ else process.env.DATA_ROOT = originalDataRoot;
46
+ });
47
+
48
+ it('returns null for anonymous requests', async () => {
49
+ assert.strictEqual(await getAgent({ headers: {} }), null);
50
+ });
51
+
52
+ it('returns null (not a throw) for malformed credentials', async () => {
53
+ assert.strictEqual(await getAgent({ headers: { authorization: 'Bearer garbage' } }), null);
54
+ assert.strictEqual(await getAgent({ headers: { authorization: 'Nonsense scheme' } }), null);
55
+ assert.strictEqual(await getAgent({ headers: { authorization: '' } }), null);
56
+ });
57
+
58
+ it('resolves a real IdP Bearer token to the account WebID', async () => {
59
+ await fs.emptyDir(TEST_DATA_DIR);
60
+ // The IdP needs its real issuer up front — reserve a port first (same
61
+ // pattern as test/well-known-did-nostr.test.js).
62
+ const net = await import('node:net');
63
+ const port = await new Promise((resolve, reject) => {
64
+ const probe = net.createServer();
65
+ probe.once('error', reject); // fail loudly, don't hang, if listen errors
66
+ probe.listen(0, '127.0.0.1', () => {
67
+ const p = probe.address().port;
68
+ probe.close(() => resolve(p));
69
+ });
70
+ });
71
+ baseUrl = `http://127.0.0.1:${port}`;
72
+ server = createServer({
73
+ logger: false,
74
+ forceCloseConnections: true,
75
+ root: TEST_DATA_DIR,
76
+ idp: true,
77
+ idpIssuer: baseUrl,
78
+ });
79
+ await server.listen({ port, host: '127.0.0.1' });
80
+
81
+ let res = await fetch(`${baseUrl}/idp/register`, {
82
+ method: 'POST',
83
+ headers: { 'Content-Type': 'application/json' },
84
+ body: JSON.stringify({ username: 'agent', password: 'secret-word', confirmPassword: 'secret-word' }),
85
+ });
86
+ assert.ok(res.status < 400, `register failed: ${res.status}`);
87
+
88
+ res = await fetch(`${baseUrl}/idp/credentials`, {
89
+ method: 'POST',
90
+ headers: { 'Content-Type': 'application/json' },
91
+ body: JSON.stringify({ username: 'agent', password: 'secret-word' }),
92
+ });
93
+ assert.strictEqual(res.status, 200, `credentials failed: ${res.status}`);
94
+ const cred = await res.json();
95
+ assert.ok(cred.access_token, 'no token issued');
96
+
97
+ const webId = await getAgent({ headers: { authorization: `Bearer ${cred.access_token}` } });
98
+ assert.strictEqual(webId, cred.webid);
99
+ });
100
+ });