javascript-solid-server 0.0.205 → 0.0.207

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.
@@ -310,6 +310,10 @@ export function profilePathFromWebId(dataRoot, webId, accountId = 'unknown') {
310
310
  * → `<dataRoot>/profile/card.jsonld`
311
311
  * 3. Subdomain-mode pod (host=`alice.example.com`, path=`/profile/card.jsonld`)
312
312
  * → `<dataRoot>/alice/profile/card.jsonld`
313
+ * 4. Root-path WebID (path=`/` or `/alice/`, e.g. `https://melvin.solid.social/#me`)
314
+ * → additionally probes `profile/card.jsonld` under the
315
+ * otherwise-directory candidate(s), e.g.
316
+ * `<dataRoot>/melvin/profile/card.jsonld` (#451)
313
317
  *
314
318
  * The subdomain candidate (3) is gated on `podName` matching the
315
319
  * WebID host's first DNS label — without that gate, a root-pod
@@ -343,15 +347,48 @@ export function profilePathCandidates(dataRoot, webId, podName = null) {
343
347
  }
344
348
  if (!paths.includes(r)) paths.push(r);
345
349
  };
350
+ // Subdomain gate: the WebID host's first DNS label must match the
351
+ // account's podName (case-insensitive — DNS is). Computed up front
352
+ // because the root-path fallback below keys off it too.
353
+ const subdomainMatch =
354
+ typeof podName === 'string' && podName.length > 0 &&
355
+ url.hostname.toLowerCase().startsWith(podName.toLowerCase() + '.');
356
+ // Pod-root WebID shape (#451): pathname `/` (→ pathnameRel '') or a
357
+ // trailing slash like `/alice/`.
358
+ const isPodRoot = pathnameRel === '' || pathnameRel.endsWith('/');
359
+
346
360
  // Path-mode named pod OR root pod.
347
361
  consider(pathnameRel);
348
- // Subdomain mode: only when the WebID host's first DNS label
349
- // matches the account's podName (case-insensitive — DNS is).
350
- if (typeof podName === 'string' && podName.length > 0) {
351
- const host = url.hostname.toLowerCase();
352
- const expected = podName.toLowerCase() + '.';
353
- if (host.startsWith(expected)) {
354
- consider(podName, pathnameRel);
362
+ // Root-path / pod-root WebID (#451): a WebID like
363
+ // `https://melvin.solid.social/#me` (pathname `/`) or
364
+ // `https://example.com/alice/#me` (pathname `/alice/`) makes the
365
+ // candidate above resolve to a DIRECTORY (dataRoot itself, or the
366
+ // pod dir) — never a profile document. Probe the conventional
367
+ // profile location underneath it. Only `profile/card.jsonld`: the
368
+ // rebuild loop reads candidates with JSON.parse, so the Turtle
369
+ // conventions (`profile/card`, `profile/card.ttl`) could never
370
+ // match anyway.
371
+ //
372
+ // Gated on !subdomainMatch: when the host carries the account's
373
+ // podName label, the profile lives under the pod dir (the
374
+ // subdomain fallback below) and `<dataRoot>/profile/card.jsonld`
375
+ // is a DIFFERENT account's document — the root pod's. The rebuild
376
+ // loop's @id check absolutizes a relative subject (`"@id": "#me"`,
377
+ // a supported shape — see collectAuthenticationIds) against the
378
+ // PROBING account's WebID, so the root pod's profile could pass
379
+ // the check and bind the root pod's pubkeys to the subdomain
380
+ // account. Suppressing the root-level fallback here closes that
381
+ // cross-account window; no legitimate deployment serves a
382
+ // subdomain account's profile from the dataRoot root.
383
+ if (isPodRoot && !subdomainMatch) {
384
+ // path.resolve skips empty segments, so pathnameRel === '' lands
385
+ // on `<dataRoot>/profile/card.jsonld` (root pod) as intended.
386
+ consider(pathnameRel, 'profile/card.jsonld');
387
+ }
388
+ if (subdomainMatch) {
389
+ consider(podName, pathnameRel);
390
+ if (isPodRoot) {
391
+ consider(podName, pathnameRel, 'profile/card.jsonld');
355
392
  }
356
393
  }
357
394
  return { paths, skipped };
package/src/index.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { startServer } from './server.js';
2
+ import { defaults } from './config.js';
2
3
 
3
- const PORT = process.env.PORT || 3000;
4
+ const PORT = process.env.PORT || defaults.port;
4
5
  const HOST = process.env.HOST || '0.0.0.0';
5
6
 
6
7
  startServer(PORT, HOST).then(() => {
package/src/server.js CHANGED
@@ -17,12 +17,13 @@ import { idpPlugin } from './idp/index.js';
17
17
  // below so non-IdP deployments don't pull in the IdP accounts module
18
18
  // (bcryptjs etc.) just to register Fastify routes. The same lazy-load
19
19
  // pattern is used in src/auth/nostr.js for the NIP-98 verifier.
20
- import { isGitRequest, isGitWriteOperation, handleGit } from './handlers/git.js';
20
+ import { isGitRequest, isGitWriteOperation, handleGit, setGitCorsHeaders } from './handlers/git.js';
21
21
  import { handleCorsProxy, isCorsProxyRequest, setProxyCorsHeaders } from './handlers/cors-proxy.js';
22
22
  import { AccessMode } from './wac/parser.js';
23
23
  import { registerNostrRelay } from './nostr/relay.js';
24
24
  import { createPayHandler, isPayRequest } from './handlers/pay.js';
25
25
  import { activityPubPlugin, getActorHandler } from './ap/index.js';
26
+ import { defaults, parseSize } from './config.js';
26
27
  import { remoteStoragePlugin } from './remotestorage.js';
27
28
  import { dbPlugin } from './db/index.js';
28
29
  import { mcpPlugin } from './mcp/index.js';
@@ -182,14 +183,24 @@ export function createServer(options = {}) {
182
183
 
183
184
  // Fastify options
184
185
  const loggerEnabled = options.logger ?? true;
186
+ // Resolve bodyLimit from options. Numbers (programmatic, or env values
187
+ // already coerced by parseEnvValue) pass through unchanged; strings
188
+ // ("100MB" from CLI / config files) go through parseSize for
189
+ // size-shorthand support. The typeof check matters because parseSize
190
+ // calls `.match` on its input and would throw on a raw number. Default
191
+ // matches the previous hard-coded 10 MiB cap. See #474.
192
+ const bodyLimit = options.bodyLimit == null
193
+ ? defaults.bodyLimit
194
+ : (typeof options.bodyLimit === 'number' ? options.bodyLimit : parseSize(options.bodyLimit));
185
195
  const fastifyOptions = {
186
196
  logger: loggerEnabled ? { level: options.logLevel || 'info' } : false,
187
197
  disableRequestLogging: true,
188
198
  trustProxy: true,
189
199
  // Force close connections on server.close() (useful for tests with WebSockets)
190
200
  forceCloseConnections: options.forceCloseConnections ?? false,
191
- // Handle raw body for non-JSON content
192
- bodyLimit: 10 * 1024 * 1024, // 10MB
201
+ // Cap raw body size (see resolution above; configurable via
202
+ // --body-limit / JSS_BODY_LIMIT / createServer({ bodyLimit })).
203
+ bodyLimit,
193
204
  // Gracefully handle client TCP errors (ECONNRESET, EPIPE, etc.)
194
205
  clientErrorHandler: (err, socket) => {
195
206
  if (err.code === 'ECONNRESET' || err.code === 'EPIPE' || err.code === 'ECONNABORTED') {
@@ -522,11 +533,20 @@ export function createServer(options = {}) {
522
533
  request.wacAllow = wacAllow;
523
534
 
524
535
  if (paymentRequired) {
536
+ // Git CORS headers on the early return — same reasoning as the
537
+ // 401/403 below: a browser git client must see the 402, not a
538
+ // generic CORS/network error. See #548 / #371.
539
+ setGitCorsHeaders(reply);
525
540
  return reply.code(402).send({ type: 'PaymentRequired', ...paymentRequired });
526
541
  }
527
542
 
528
543
  if (!authorized) {
529
544
  const message = needsWrite ? 'Write access required for push' : 'Read access required for clone';
545
+ // Without the git CORS headers, browser-based git clients (e.g.
546
+ // jss.live/git/) hitting an auth-gated repo saw a generic CORS
547
+ // error instead of this 401/403 — the same failure mode #371
548
+ // fixed inside handleGit. See #548.
549
+ setGitCorsHeaders(reply);
530
550
  reply.header('WAC-Allow', wacAllow);
531
551
  if (!webId) {
532
552
  // No authentication - request Basic auth for git clients
@@ -875,7 +895,7 @@ export function createServer(options = {}) {
875
895
  // Determine base URL for pod URIs
876
896
  const protocol = options.ssl ? 'https' : 'http';
877
897
  const host = options.host === '0.0.0.0' ? 'localhost' : (options.host || 'localhost');
878
- const port = options.port || 3000;
898
+ const port = options.port || defaults.port;
879
899
  const baseUrl = idpIssuer?.replace(/\/$/, '') || `${protocol}://${host}:${port}`;
880
900
  const issuer = idpIssuer || `${baseUrl}/`;
881
901
 
@@ -1220,7 +1240,7 @@ export function createServer(options = {}) {
1220
1240
  const dataRoot = options.root || process.env.DATA_ROOT || './data';
1221
1241
  const protocol = options.ssl ? 'https' : 'http';
1222
1242
  // Use configured port, or default; actual URL will be localhost
1223
- const port = options.port || 3000;
1243
+ const port = options.port || defaults.port;
1224
1244
  const baseUrl = `${protocol}://localhost:${port}`;
1225
1245
  startFileWatcher(dataRoot, baseUrl);
1226
1246
  }
@@ -1231,7 +1251,7 @@ export function createServer(options = {}) {
1231
1251
  /**
1232
1252
  * Start the server
1233
1253
  */
1234
- export async function startServer(port = 3000, host = '0.0.0.0') {
1254
+ export async function startServer(port = defaults.port, host = '0.0.0.0') {
1235
1255
  const server = createServer();
1236
1256
 
1237
1257
  try {
@@ -10,13 +10,70 @@
10
10
  * Public URL: https://your.pod/tunnel/{name}/path
11
11
  *
12
12
  * Tunnel client protocol (JSON over WebSocket):
13
- * → { type: "register", name: "myapp" }
14
- * ← { type: "registered", name: "myapp", url: "/tunnel/myapp/" }
13
+ * → { type: "register", name: "myapp", passthrough?: true }
14
+ * ← { type: "registered", name: "myapp", url: "/tunnel/myapp/", passthrough: true|false }
15
15
  * ← { type: "request", id: "<uuid>", method: "GET", path: "/api/hello", headers: {...}, body: "..." }
16
16
  * → { type: "response", id: "<uuid>", status: 200, headers: {...}, body: "..." }
17
17
  * ← { type: "error", message: "..." }
18
+ *
19
+ * Credential passthrough (#530): by default the proxy strips
20
+ * `Cookie` / `Authorization` from inbound requests and `Set-Cookie`
21
+ * from outbound responses, so a tunnel exposes PUBLIC content only.
22
+ * A client may opt in per-registration with `passthrough: true`,
23
+ * which forwards those three headers and makes authenticated access
24
+ * (bearer/DPoP, cookie sessions) work through the tunnel. Opting in
25
+ * means visitor credentials bound for the tunnelled service are
26
+ * handed to the registered client — safe exactly when the registrant
27
+ * owns the tunnelled service (the normal "my own pod through my own
28
+ * relay" case), which is why it is per-tunnel, owner-asserted, and
29
+ * off by default. `Proxy-Authorization` is always stripped — it is
30
+ * addressed to this relay, never to the tunnelled service.
31
+ *
32
+ * Even with passthrough on, the relay's OWN IdP session/interaction
33
+ * cookies are stripped from the forwarded Cookie header. oidc-provider
34
+ * sets them with `path: '/'`, so a browser attaches them to
35
+ * `/tunnel/...` requests too — but they authenticate the visitor to
36
+ * THE RELAY, not to the tunnelled service. Forwarding them would let a
37
+ * tunnel client capture a visitor's relay `_session` and replay it
38
+ * against the relay's `/idp/*` endpoints (session hijack). See #530.
18
39
  */
19
40
 
41
+ // Cookie names reserved by the relay's own oidc-provider IdP
42
+ // (`_session`, `_session.sig`, `_session.legacy[.sig]`, `_interaction`,
43
+ // `_interaction.sig`, `_interaction_resume[.sig]`). They share two
44
+ // prefixes; we match the prefix plus a `.`/`_` boundary so a tunnelled
45
+ // service's unrelated cookie (e.g. `_sessionsLeft`) isn't stripped.
46
+ const RELAY_COOKIE_PREFIXES = ['_session', '_interaction'];
47
+
48
+ function isRelayCookieName(name) {
49
+ return RELAY_COOKIE_PREFIXES.some(
50
+ (p) => name === p || name.startsWith(`${p}.`) || name.startsWith(`${p}_`),
51
+ );
52
+ }
53
+
54
+ /**
55
+ * Remove the relay's own IdP cookies from a forwarded Cookie header,
56
+ * keeping the visitor's cookies bound for the tunnelled service.
57
+ * Returns '' when nothing remains (caller then drops the header).
58
+ */
59
+ function stripRelayCookies(cookieHeader) {
60
+ // Node folds duplicate Cookie headers into one string, but Fastify
61
+ // can surface string[] — normalize so passthrough doesn't drop every
62
+ // cookie when an array arrives. Cookies join with '; '.
63
+ const raw = Array.isArray(cookieHeader) ? cookieHeader.join('; ') : cookieHeader;
64
+ if (typeof raw !== 'string') return '';
65
+ return raw
66
+ .split(';')
67
+ .map((s) => s.trim())
68
+ .filter(Boolean)
69
+ .filter((pair) => {
70
+ const eq = pair.indexOf('=');
71
+ const name = (eq === -1 ? pair : pair.slice(0, eq)).trim();
72
+ return !isRelayCookieName(name);
73
+ })
74
+ .join('; ');
75
+ }
76
+
20
77
  import websocket from '@fastify/websocket';
21
78
  import { getWebIdFromRequestAsync } from '../auth/token.js';
22
79
  import { randomUUID } from 'crypto';
@@ -109,9 +166,15 @@ export async function tunnelPlugin(fastify, options = {}) {
109
166
  existing.socket.close();
110
167
  }
111
168
 
169
+ // Per-tunnel credential passthrough (#530) — strict boolean so a
170
+ // truthy-but-wrong value ("false", 1) can't silently enable
171
+ // credential forwarding. Echoed in the ack so the client knows
172
+ // which mode the relay actually applied.
173
+ const passthrough = msg.passthrough === true;
174
+
112
175
  tunnelName = name;
113
- tunnels.set(name, { socket, webId });
114
- socket.send(JSON.stringify({ type: 'registered', name, url: `/tunnel/${name}/` }));
176
+ tunnels.set(name, { socket, webId, passthrough });
177
+ socket.send(JSON.stringify({ type: 'registered', name, url: `/tunnel/${name}/`, passthrough }));
115
178
 
116
179
  } else if (msg.type === 'response') {
117
180
  // Tunnel client returning an HTTP response
@@ -167,12 +230,27 @@ export async function tunnelPlugin(fastify, options = {}) {
167
230
  tunnelReq.method = request.method;
168
231
  tunnelReq.path = fullPath;
169
232
  tunnelReq.headers = Object.create(null);
170
- // Forward relevant headers (skip hop-by-hop)
171
- const skipHeaders = new Set(['host', 'connection', 'upgrade', 'transfer-encoding', 'cookie', 'authorization', 'proxy-authorization']);
233
+ // Forward relevant headers. Hop-by-hop headers are always skipped;
234
+ // credentials (cookie / authorization) are skipped UNLESS the tunnel
235
+ // registered with passthrough (#530 — owner opted in to receive
236
+ // visitor credentials). Proxy-Authorization is always stripped: it
237
+ // is addressed to this relay, never to the tunnelled service.
238
+ const skipHeaders = new Set(['host', 'connection', 'upgrade', 'transfer-encoding', 'proxy-authorization']);
239
+ if (!tunnel.passthrough) {
240
+ skipHeaders.add('cookie');
241
+ skipHeaders.add('authorization');
242
+ }
172
243
  for (const [k, v] of Object.entries(request.headers)) {
173
- if (!skipHeaders.has(k.toLowerCase())) {
174
- tunnelReq.headers[k] = v;
244
+ const lower = k.toLowerCase();
245
+ if (skipHeaders.has(lower)) continue;
246
+ if (lower === 'cookie' && tunnel.passthrough) {
247
+ // Forward the visitor's cookies for the tunnelled service, but
248
+ // never the relay's own IdP session cookies (#530 security).
249
+ const filtered = stripRelayCookies(v);
250
+ if (filtered) tunnelReq.headers[k] = filtered;
251
+ continue;
175
252
  }
253
+ tunnelReq.headers[k] = v;
176
254
  }
177
255
  // Forward body if present
178
256
  if (request.body) {
@@ -201,8 +279,15 @@ export async function tunnelPlugin(fastify, options = {}) {
201
279
 
202
280
  const res = await responsePromise;
203
281
 
204
- // Set response headers
205
- const hopHeaders = new Set(['connection', 'transfer-encoding', 'keep-alive', 'set-cookie']);
282
+ // Set response headers. Set-Cookie is stripped by default so a
283
+ // tunnelled service can't set cookies on the relay's origin; with
284
+ // passthrough (#530) the owner opted in and session flows (e.g.
285
+ // OIDC login cookies) must survive the proxy. Fastify accepts an
286
+ // array value for set-cookie, which JSON serialization preserves.
287
+ const hopHeaders = new Set(['connection', 'transfer-encoding', 'keep-alive']);
288
+ if (!tunnel.passthrough) {
289
+ hopHeaders.add('set-cookie');
290
+ }
206
291
  for (const [k, v] of Object.entries(res.headers)) {
207
292
  if (!hopHeaders.has(k.toLowerCase())) {
208
293
  reply.header(k, v);
@@ -0,0 +1,105 @@
1
+ /**
2
+ * Configurable bodyLimit (#474).
3
+ *
4
+ * Before #474 the per-request body cap was hard-coded to 10 MiB inside
5
+ * createServer's fastifyOptions, so any operator who wanted to accept
6
+ * larger `git push` payloads (e.g. an established app repo with several
7
+ * MB of history) had no way to raise it.
8
+ *
9
+ * The fix exposes `bodyLimit` as a createServer option / CLI flag
10
+ * (`--body-limit`) / env var (`JSS_BODY_LIMIT`) / config key, accepting
11
+ * either a number (bytes) or a size string ("100MB", "1GB", …).
12
+ *
13
+ * Tests here verify the surface end-to-end — server actually rejects
14
+ * over-size requests with 413, AND the size-string parsing path works
15
+ * the same as the numeric path. The default (10 MiB) is covered
16
+ * implicitly by every other test in the suite continuing to pass.
17
+ */
18
+
19
+ import { describe, it, before, after, afterEach } from 'node:test';
20
+ import assert from 'node:assert';
21
+ import { createServer } from '../src/server.js';
22
+ import fs from 'fs-extra';
23
+
24
+ const TEST_DATA_DIR = './test-data-body-limit';
25
+
26
+ let server;
27
+ let baseUrl;
28
+ let originalDataRoot;
29
+
30
+ async function startWith(bodyLimit) {
31
+ await fs.emptyDir(TEST_DATA_DIR);
32
+ server = createServer({
33
+ logger: false,
34
+ forceCloseConnections: true,
35
+ root: TEST_DATA_DIR,
36
+ bodyLimit,
37
+ });
38
+ await server.listen({ port: 0, host: '127.0.0.1' });
39
+ const address = server.server.address();
40
+ baseUrl = `http://127.0.0.1:${address.port}`;
41
+ }
42
+
43
+ describe('configurable bodyLimit (#474)', () => {
44
+ before(() => {
45
+ // createServer({ root }) mutates process.env.DATA_ROOT
46
+ // (src/server.js:180). Snapshot the previous value so we can
47
+ // restore it after the suite — otherwise the test directory
48
+ // leaks into any subsequent test that reads DATA_ROOT.
49
+ originalDataRoot = process.env.DATA_ROOT;
50
+ });
51
+
52
+ afterEach(async () => {
53
+ if (server) {
54
+ await server.close();
55
+ server = null;
56
+ }
57
+ await fs.remove(TEST_DATA_DIR);
58
+ });
59
+
60
+ after(() => {
61
+ if (originalDataRoot === undefined) delete process.env.DATA_ROOT;
62
+ else process.env.DATA_ROOT = originalDataRoot;
63
+ });
64
+
65
+ it('rejects requests larger than a numeric bodyLimit with 413', async () => {
66
+ await startWith(100); // 100 bytes
67
+ // Body well over the cap — Fastify's body parser fires the 413
68
+ // before any route handler (or auth) runs.
69
+ const oversized = 'x'.repeat(500);
70
+ const res = await fetch(`${baseUrl}/anywhere`, {
71
+ method: 'PUT',
72
+ headers: { 'Content-Type': 'text/plain' },
73
+ body: oversized,
74
+ });
75
+ assert.strictEqual(res.status, 413,
76
+ `expected 413 for 500-byte body against a 100-byte limit, got ${res.status}`);
77
+ });
78
+
79
+ it('parses string bodyLimit ("100B") via parseSize (same behaviour as numeric)', async () => {
80
+ await startWith('100B');
81
+ const oversized = 'x'.repeat(500);
82
+ const res = await fetch(`${baseUrl}/anywhere`, {
83
+ method: 'PUT',
84
+ headers: { 'Content-Type': 'text/plain' },
85
+ body: oversized,
86
+ });
87
+ assert.strictEqual(res.status, 413,
88
+ `expected 413 from string-parsed bodyLimit "100B"; got ${res.status}`);
89
+ });
90
+
91
+ it('accepts requests within the configured bodyLimit (no 413)', async () => {
92
+ await startWith('10KB');
93
+ // Small body, well under the 10KB cap — must NOT 413. (We don't care
94
+ // which downstream status fires — auth/404/etc. are fine; only that
95
+ // the body-parser doesn't reject.)
96
+ const small = 'x'.repeat(100);
97
+ const res = await fetch(`${baseUrl}/anywhere`, {
98
+ method: 'PUT',
99
+ headers: { 'Content-Type': 'text/plain' },
100
+ body: small,
101
+ });
102
+ assert.notStrictEqual(res.status, 413,
103
+ `100-byte body under a 10KB cap should not 413; got ${res.status}`);
104
+ });
105
+ });
@@ -141,6 +141,14 @@ describe('Git auto-init on first push', () => {
141
141
  await fs.ensureDir(DATA_DIR_AUTH);
142
142
  const port = await getAvailablePort();
143
143
  const authBaseUrl = `http://${TEST_HOST}:${port}`;
144
+ // createServer({ root }) mutates process.env.DATA_ROOT globally, and
145
+ // handleGit resolves the data root PER REQUEST via getDataRoot().
146
+ // Without restoring the env afterwards, every later test in this
147
+ // file silently runs against DATA_DIR_AUTH instead of DATA_DIR —
148
+ // auto-initing repos in the wrong tree and leaving the authcheck
149
+ // directory behind after the suite's cleanup (which only removes
150
+ // DATA_DIR). Same pollution class as the #543 review finding.
151
+ const originalDataRoot = process.env.DATA_ROOT;
144
152
  const authServer = createServer({
145
153
  logger: false,
146
154
  root: DATA_DIR_AUTH,
@@ -162,6 +170,8 @@ describe('Git auto-init on first push', () => {
162
170
  'auto-init MUST NOT create a directory for an unauthenticated request');
163
171
  } finally {
164
172
  await authServer.close();
173
+ if (originalDataRoot === undefined) delete process.env.DATA_ROOT;
174
+ else process.env.DATA_ROOT = originalDataRoot;
165
175
  await fs.remove(DATA_DIR_AUTH);
166
176
  }
167
177
  });