javascript-solid-server 0.0.205 → 0.0.206

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.
@@ -22,7 +22,37 @@
22
22
  "Bash(git commit -q -m 'fix\\(rdf\\): preserve blank-node SUBJECTS through Turtle ↔ JSON-LD \\(#536\\) *)",
23
23
  "Bash(npm view *)",
24
24
  "Bash(git branch *)",
25
- "Bash(git commit -q -m 'bump version to 0.0.205 *)"
25
+ "Bash(git commit -q -m 'bump version to 0.0.205 *)",
26
+ "Bash(gh repo *)",
27
+ "Bash(curl -sL https://raw.githubusercontent.com/JavaScriptSolidServer/solid-oidc/gh-pages/example.html)",
28
+ "Bash(curl -sL https://raw.githubusercontent.com/JavaScriptSolidServer/solid-oidc/gh-pages/solid-oidc.js)",
29
+ "Bash(mkdir -p /tmp/jss-sanity-23)",
30
+ "Read(//tmp/**)",
31
+ "Bash(DATA_ROOT=. node /home/melvin/remote/github.com/JavaScriptSolidServer/JavaScriptSolidServer/bin/jss.js start --idp --conneg --port 4901 --quiet)",
32
+ "Bash(curl -si -c /tmp/jss-sanity-cookies.txt -b /tmp/jss-sanity-cookies.txt \"http://localhost:4901/idp/interaction/Qp-9Nn6O9Rv79dlCsI9YWGlXNZZswTi4UUJ2PjXt4x3\")",
33
+ "Bash(curl -s -c /tmp/jss-sanity-cookies.txt -b /tmp/jss-sanity-cookies.txt \"http://localhost:4901/idp/interaction/Qp-9Nn6O9Rv79dlCsI9YWGlXNZZswTi4UUJ2PjXt4x3\")",
34
+ "Bash(kill bx5n5fpi1 *)",
35
+ "Bash(pkill -f \"jss.js start --idp --port 4901\")",
36
+ "Bash(rm -f /tmp/jss-sanity-cookies.txt)",
37
+ "Bash(rm -rf /tmp/jss-sanity-23)",
38
+ "Bash(gh label *)",
39
+ "Bash(git commit -q -m 'fix\\(idp\\): handleSchnorrComplete recovers from interactionFinished throw — no more 504 hang \\(#412\\) *)",
40
+ "Bash(sed -n '163,170p' src/idp/interactions.js)",
41
+ "Bash(sed -n '283,295p' src/idp/interactions.js)",
42
+ "Bash(sed -n '600,610p' src/idp/interactions.js)",
43
+ "Bash(sed -n '638,650p' src/idp/interactions.js)",
44
+ "Bash(wait)",
45
+ "Bash(node --test --test-concurrency=1 test/schnorr-complete-defensive.test.js)",
46
+ "Bash(git commit -q -m 'review fixes \\(#539\\): stop leaking err.message + add regression tests *)",
47
+ "Bash(git commit -q -m 'review pass-3 \\(#539\\): log payload preserves stack + mock matches Node behaviour *)",
48
+ "Bash(git commit -q -m 'refactor\\(idp\\): sweep hijack-then-throw defensive pattern across all 5 interaction handlers \\(#526\\) *)",
49
+ "Bash(npm audit *)",
50
+ "Bash(node --check src/index.js)",
51
+ "Bash(node --check src/server.js)",
52
+ "Bash(node --test --test-concurrency=1 test/body-limit.test.js)",
53
+ "Bash(git commit -q -m 'feat: configurable bodyLimit via createServer / --body-limit / JSS_BODY_LIMIT \\(#474\\) *)",
54
+ "Bash(git commit -q -m 'review fixes \\(#543\\): unused imports + DATA_ROOT pollution + clearer comment *)",
55
+ "Bash(node --test --test-concurrency=1 test/ssrf.test.js)"
26
56
  ]
27
57
  }
28
58
  }
package/bin/jss.js CHANGED
@@ -112,6 +112,7 @@ program
112
112
  .option('--cors-proxy-max-bytes <n>', 'CORS proxy upstream response size cap (default 50MB)', parseInt)
113
113
  .option('--cors-proxy-timeout-ms <ms>', 'CORS proxy upstream request timeout (default 30s)', parseInt)
114
114
  .option('--cors-proxy-max-redirects <n>', 'CORS proxy max redirect hops, each re-validated (default 5)', parseInt)
115
+ .option('--body-limit <size>', 'Maximum request body size, e.g. 100MB or 1GB (default 10MB). Raise to accept larger `git push`; lower for tighter memory-DoS protection.')
115
116
  .option('--nostr', 'Enable Nostr relay')
116
117
  .option('--no-nostr', 'Disable Nostr relay')
117
118
  .option('--nostr-path <path>', 'Nostr relay WebSocket path (default: /relay)')
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "javascript-solid-server",
3
- "version": "0.0.205",
3
+ "version": "0.0.206",
4
4
  "description": "A minimal, fast Solid server",
5
5
  "main": "src/index.js",
6
6
  "type": "module",
package/src/config.js CHANGED
@@ -19,6 +19,12 @@ export const defaults = {
19
19
  port: 4443,
20
20
  host: '0.0.0.0',
21
21
  root: './data',
22
+ // Maximum request body size in bytes (or a size string when supplied
23
+ // via CLI / config file, e.g. "100MB"). Default 10 MiB matches the
24
+ // previous hard-coded Fastify limit. Operators hosting personal pods
25
+ // may want to raise this so that large `git push` of an established
26
+ // app repo doesn't 413 — see #474.
27
+ bodyLimit: 10 * 1024 * 1024,
22
28
 
23
29
  // SSL
24
30
  sslKey: null,
@@ -167,6 +173,7 @@ const envMap = {
167
173
  JSS_CORS_PROXY_MAX_BYTES: 'corsProxyMaxBytes',
168
174
  JSS_CORS_PROXY_TIMEOUT_MS: 'corsProxyTimeoutMs',
169
175
  JSS_CORS_PROXY_MAX_REDIRECTS: 'corsProxyMaxRedirects',
176
+ JSS_BODY_LIMIT: 'bodyLimit',
170
177
  JSS_NOSTR: 'nostr',
171
178
  JSS_NOSTR_PATH: 'nostrPath',
172
179
  JSS_NOSTR_MAX_EVENTS: 'nostrMaxEvents',
@@ -278,8 +285,8 @@ function parseEnvValue(value, key) {
278
285
  return parseInt(value, 10);
279
286
  }
280
287
 
281
- // Size values (quota)
282
- if (key === 'defaultQuota') {
288
+ // Size values (quota, body limit)
289
+ if (key === 'defaultQuota' || key === 'bodyLimit') {
283
290
  return parseSize(value);
284
291
  }
285
292
 
@@ -14,6 +14,70 @@ import { expireSessionCookies } from './cookies.js';
14
14
  // Security: Maximum body size for IdP form submissions (1MB)
15
15
  const MAX_BODY_SIZE = 1024 * 1024;
16
16
 
17
+ /**
18
+ * Defensive wrapper around provider.interactionFinished for handlers
19
+ * that hijack the reply and let oidc-provider write the continuation
20
+ * redirect directly to the raw socket.
21
+ *
22
+ * The naive pattern is:
23
+ *
24
+ * reply.hijack();
25
+ * return provider.interactionFinished(request.raw, reply.raw, result, opts);
26
+ *
27
+ * If interactionFinished throws (most commonly `SessionNotFound` from
28
+ * oidc-provider's `#getInteraction` when the `_interaction` cookie is
29
+ * missing — URL pasted into a different browser, third-party cookies
30
+ * blocked, long idle past the cookie TTL), the hijacked reply can no
31
+ * longer be written by Fastify and the connection hangs until the
32
+ * gateway 504s. This helper turns that hang into a bounded 4xx instead.
33
+ *
34
+ * - SessionNotFound → 400 with a "session expired, please restart
35
+ * login from the beginning" page.
36
+ * - Anything else → 500 with a generic message. Raw err.message is
37
+ * never surfaced — adapter / provider error strings on an auth
38
+ * endpoint are a soft info-leak (mirrors handleSwitchAccount).
39
+ * - The full Error (including stack) is logged via request.log.warn
40
+ * under the `err` key so Pino serializes it properly.
41
+ *
42
+ * If interactionFinished managed a partial write before throwing
43
+ * (`reply.raw.headersSent === true`), the socket is past recovery —
44
+ * the error is re-thrown so the caller's outer catch logs it.
45
+ *
46
+ * Foundation work for #526. The auto-healing 303-to-retry behaviour
47
+ * that #526 ultimately wants can layer on top of this helper without
48
+ * touching the five call sites again.
49
+ *
50
+ * @param {object} request - Fastify request (uses .raw and .log)
51
+ * @param {object} reply - Fastify reply; will be hijacked
52
+ * @param {object} provider - oidc-provider instance
53
+ * @param {object} result - the interaction result to commit
54
+ * @param {object} opts - forwarded to interactionFinished
55
+ * (e.g. { mergeWithLastSubmission: true } for consent)
56
+ * @param {object} [logContext] - extra structured fields for the warn
57
+ * log on failure (e.g. { uid, accountId })
58
+ */
59
+ async function finishInteractionDefensively(request, reply, provider, result, opts, logContext = {}) {
60
+ reply.hijack();
61
+ try {
62
+ await provider.interactionFinished(request.raw, reply.raw, result, opts);
63
+ return;
64
+ } catch (err) {
65
+ if (reply.raw.headersSent) throw err;
66
+ // Spread logContext first so a caller-supplied `err` field can't
67
+ // clobber the real Error — Pino needs the actual Error under `err`
68
+ // to serialize name/message/stack/structured fields.
69
+ request.log.warn({ ...logContext, err }, 'interactionFinished failed after hijack');
70
+ const isSessionMissing = err.name === 'SessionNotFound';
71
+ const status = isSessionMissing ? 400 : 500;
72
+ const title = isSessionMissing ? 'Session expired' : 'Login error';
73
+ const message = isSessionMissing
74
+ ? 'Your login session cookie is missing or expired. This usually means the link was opened in a different browser, third-party cookies are blocked, or too much time passed between steps. Please restart the login from the beginning.'
75
+ : 'Unexpected error completing login. Please try signing in again.';
76
+ reply.raw.writeHead(status, { 'Content-Type': 'text/html; charset=utf-8' });
77
+ reply.raw.end(errorPage(title, message));
78
+ }
79
+ }
80
+
17
81
  /**
18
82
  * Handle GET /idp/interaction/:uid
19
83
  * Shows login or consent page based on interaction state
@@ -160,10 +224,11 @@ export async function handleLogin(request, reply, provider) {
160
224
  interaction.result = result;
161
225
  await interaction.save(interaction.exp - Math.floor(Date.now() / 1000));
162
226
 
163
- // For browsers (mashlib, etc): do a proper HTTP redirect
227
+ // For browsers (mashlib, etc): do a proper HTTP redirect.
228
+ // Defensive wrapper guards against SessionNotFound / other throws
229
+ // after hijack — see finishInteractionDefensively at top of file.
164
230
  if (wantsBrowserRedirect) {
165
- reply.hijack();
166
- return provider.interactionFinished(request.raw, reply.raw, result, { mergeWithLastSubmission: false });
231
+ return finishInteractionDefensively(request, reply, provider, result, { mergeWithLastSubmission: false }, { uid });
167
232
  }
168
233
 
169
234
  // For CTH and programmatic clients: return JSON with location
@@ -282,16 +347,10 @@ export async function handleConsent(request, reply, provider) {
282
347
  },
283
348
  };
284
349
 
285
- // Mark reply as sent since interactionFinished will handle the response
286
- reply.hijack();
287
-
288
- // Use interactionFinished which handles the redirect directly
289
- return provider.interactionFinished(
290
- request.raw,
291
- reply.raw,
292
- result,
293
- { mergeWithLastSubmission: true }
294
- );
350
+ // Defensive wrapper guards against SessionNotFound / other throws
351
+ // after hijack — see finishInteractionDefensively at top of file.
352
+ // `mergeWithLastSubmission: true` is consent-specific.
353
+ return finishInteractionDefensively(request, reply, provider, result, { mergeWithLastSubmission: true }, { uid });
295
354
  } catch (err) {
296
355
  request.log.error(err, 'Consent error');
297
356
  return reply.code(500).type('text/html').send(errorPage('Consent failed', err.message));
@@ -602,8 +661,8 @@ export async function handlePasskeyComplete(request, reply, provider) {
602
661
 
603
662
  request.log.info({ accountId: account.id, uid }, 'Passkey login completed');
604
663
 
605
- reply.hijack();
606
- return provider.interactionFinished(request.raw, reply.raw, result, { mergeWithLastSubmission: false });
664
+ // Defensive wrapper — see finishInteractionDefensively at top of file.
665
+ return finishInteractionDefensively(request, reply, provider, result, { mergeWithLastSubmission: false }, { uid, accountId: account.id });
607
666
  } catch (err) {
608
667
  request.log.error(err, 'Passkey complete error');
609
668
  return reply.code(500).type('text/html').send(errorPage('Error', err.message));
@@ -639,9 +698,9 @@ export async function handlePasskeySkip(request, reply, provider) {
639
698
 
640
699
  request.log.info({ accountId: result.login.accountId, uid }, 'Passkey prompt skipped');
641
700
 
642
- // Complete the OIDC interaction
643
- reply.hijack();
644
- return provider.interactionFinished(request.raw, reply.raw, result, { mergeWithLastSubmission: false });
701
+ // Complete the OIDC interaction. Defensive wrapper — see
702
+ // finishInteractionDefensively at top of file.
703
+ return finishInteractionDefensively(request, reply, provider, result, { mergeWithLastSubmission: false }, { uid, accountId: result.login.accountId });
645
704
  } catch (err) {
646
705
  request.log.error(err, 'Passkey skip error');
647
706
  return reply.code(500).type('text/html').send(errorPage('Error', err.message));
@@ -819,8 +878,11 @@ export async function handleSchnorrComplete(request, reply, provider) {
819
878
 
820
879
  request.log.info({ accountId: account.id, uid }, 'Schnorr login completed');
821
880
 
822
- reply.hijack();
823
- return provider.interactionFinished(request.raw, reply.raw, interaction.result, { mergeWithLastSubmission: false });
881
+ // Defensive wrapper — see finishInteractionDefensively at top of
882
+ // file. Originally inlined in #539 to fix #412 (the 504 hang on
883
+ // missing _interaction cookie); now shared with the four other
884
+ // hijack-then-throw sites in this module.
885
+ return finishInteractionDefensively(request, reply, provider, interaction.result, { mergeWithLastSubmission: false }, { uid, accountId: account.id });
824
886
  } catch (err) {
825
887
  request.log.error(err, 'Schnorr complete error');
826
888
  return reply.code(500).type('text/html').send(errorPage('Error', err.message));
@@ -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
@@ -23,6 +23,7 @@ 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') {
@@ -875,7 +886,7 @@ export function createServer(options = {}) {
875
886
  // Determine base URL for pod URIs
876
887
  const protocol = options.ssl ? 'https' : 'http';
877
888
  const host = options.host === '0.0.0.0' ? 'localhost' : (options.host || 'localhost');
878
- const port = options.port || 3000;
889
+ const port = options.port || defaults.port;
879
890
  const baseUrl = idpIssuer?.replace(/\/$/, '') || `${protocol}://${host}:${port}`;
880
891
  const issuer = idpIssuer || `${baseUrl}/`;
881
892
 
@@ -1220,7 +1231,7 @@ export function createServer(options = {}) {
1220
1231
  const dataRoot = options.root || process.env.DATA_ROOT || './data';
1221
1232
  const protocol = options.ssl ? 'https' : 'http';
1222
1233
  // Use configured port, or default; actual URL will be localhost
1223
- const port = options.port || 3000;
1234
+ const port = options.port || defaults.port;
1224
1235
  const baseUrl = `${protocol}://localhost:${port}`;
1225
1236
  startFileWatcher(dataRoot, baseUrl);
1226
1237
  }
@@ -1231,7 +1242,7 @@ export function createServer(options = {}) {
1231
1242
  /**
1232
1243
  * Start the server
1233
1244
  */
1234
- export async function startServer(port = 3000, host = '0.0.0.0') {
1245
+ export async function startServer(port = defaults.port, host = '0.0.0.0') {
1235
1246
  const server = createServer();
1236
1247
 
1237
1248
  try {
@@ -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
+ });
@@ -0,0 +1,163 @@
1
+ /**
2
+ * Regression test for #412 — handleSchnorrComplete must not hang the
3
+ * connection (→ gateway 504) when `provider.interactionFinished` throws
4
+ * after `reply.hijack()`. The common trigger is `SessionNotFound` from
5
+ * oidc-provider's `#getInteraction` when the `_interaction` cookie is
6
+ * missing (cross-browser URL paste, third-party cookies blocked, long
7
+ * idle past the cookie TTL).
8
+ *
9
+ * Strategy: direct unit-test of the handler with a real account on a
10
+ * fixture DATA_ROOT (so `findById` returns a hit) plus a stub provider
11
+ * that throws SessionNotFound from `interactionFinished`. Captures the
12
+ * post-hijack write to `reply.raw` and asserts a bounded 400 response
13
+ * with the "session expired, restart login" page — instead of hanging.
14
+ */
15
+
16
+ import { describe, it, before, after } from 'node:test';
17
+ import assert from 'node:assert';
18
+ import fs from 'fs-extra';
19
+ import path from 'path';
20
+ import { handleSchnorrComplete } from '../src/idp/interactions.js';
21
+ import { createAccount } from '../src/idp/accounts.js';
22
+
23
+ const DATA_DIR = path.resolve('./test-data-schnorr-complete-defensive');
24
+
25
+ function makeFakeReplyAndCapture() {
26
+ let hijacked = false;
27
+ let status = null;
28
+ let headers = null;
29
+ const bodyChunks = [];
30
+ // Mirror Node's http.ServerResponse: `headersSent` flips to true the
31
+ // moment writeHead() commits the status line + headers to the socket,
32
+ // not only after end(). Modelling it any other way would let the
33
+ // `if (reply.raw.headersSent) throw err;` guard pass when it shouldn't.
34
+ let headersWritten = false;
35
+ return {
36
+ reply: {
37
+ hijack: () => { hijacked = true; },
38
+ code: () => { throw new Error('reply.code called after hijack — should not happen'); },
39
+ raw: {
40
+ get headersSent() { return headersWritten; },
41
+ writeHead: (s, h) => { status = s; headers = h; headersWritten = true; },
42
+ end: (body) => { headersWritten = true; if (body) bodyChunks.push(body); },
43
+ },
44
+ },
45
+ captured: () => ({ hijacked, status, headers, body: bodyChunks.join('') }),
46
+ };
47
+ }
48
+
49
+ function makeFakeRequest({ uid, accountId }) {
50
+ const logs = [];
51
+ return {
52
+ params: { uid },
53
+ query: { accountId },
54
+ raw: {},
55
+ log: {
56
+ info: (...args) => logs.push(['info', args]),
57
+ warn: (...args) => logs.push(['warn', args]),
58
+ error: (...args) => logs.push(['error', args]),
59
+ },
60
+ _logs: logs,
61
+ };
62
+ }
63
+
64
+ describe('handleSchnorrComplete defensive recovery (#412)', () => {
65
+ let originalDataRoot;
66
+ let account;
67
+
68
+ before(async () => {
69
+ originalDataRoot = process.env.DATA_ROOT;
70
+ process.env.DATA_ROOT = DATA_DIR;
71
+ await fs.remove(DATA_DIR);
72
+ await fs.ensureDir(DATA_DIR);
73
+ account = await createAccount({
74
+ username: 'schnorrtest',
75
+ email: 'schnorr@example.org',
76
+ password: 'test12345',
77
+ webId: 'https://example.org/schnorrtest/profile/card#me',
78
+ });
79
+ });
80
+
81
+ after(async () => {
82
+ await fs.remove(DATA_DIR);
83
+ if (originalDataRoot === undefined) delete process.env.DATA_ROOT;
84
+ else process.env.DATA_ROOT = originalDataRoot;
85
+ });
86
+
87
+ it('returns 400 with a "session expired" page (not 504) when interactionFinished throws SessionNotFound', async () => {
88
+ const sessionErr = new Error('invalid_request — interaction session id cookie not found');
89
+ sessionErr.name = 'SessionNotFound';
90
+
91
+ const provider = {
92
+ Interaction: {
93
+ find: async () => ({
94
+ result: { login: { accountId: account.id } },
95
+ exp: Math.floor(Date.now() / 1000) + 600,
96
+ }),
97
+ },
98
+ interactionFinished: async () => { throw sessionErr; },
99
+ };
100
+
101
+ const { reply, captured } = makeFakeReplyAndCapture();
102
+ const request = makeFakeRequest({ uid: 'fake-uid', accountId: account.id });
103
+
104
+ await handleSchnorrComplete(request, reply, provider);
105
+
106
+ const c = captured();
107
+ assert.strictEqual(c.hijacked, true, 'must hijack before calling interactionFinished');
108
+ assert.strictEqual(c.status, 400, 'SessionNotFound must produce 400, not a hang');
109
+ assert.ok(c.headers && /text\/html/.test(c.headers['Content-Type']), 'response must be HTML');
110
+ assert.ok(/Session expired/.test(c.body), 'page title should be "Session expired"');
111
+ assert.ok(/restart the login/i.test(c.body), 'page should tell the user to restart');
112
+ });
113
+
114
+ it('returns 500 with a generic message (no err.message leak) when interactionFinished throws an unknown error', async () => {
115
+ // Soft info-leak guard — mirrors handleSwitchAccount's pattern.
116
+ // The internal error message must NOT appear in the response body.
117
+ const internalErr = new Error('INTERNAL_DETAIL_xyz123_should_not_leak');
118
+
119
+ const provider = {
120
+ Interaction: {
121
+ find: async () => ({
122
+ result: { login: { accountId: account.id } },
123
+ exp: Math.floor(Date.now() / 1000) + 600,
124
+ }),
125
+ },
126
+ interactionFinished: async () => { throw internalErr; },
127
+ };
128
+
129
+ const { reply, captured } = makeFakeReplyAndCapture();
130
+ const request = makeFakeRequest({ uid: 'fake-uid', accountId: account.id });
131
+
132
+ await handleSchnorrComplete(request, reply, provider);
133
+
134
+ const c = captured();
135
+ assert.strictEqual(c.status, 500, 'unknown error must produce 500');
136
+ assert.ok(!/INTERNAL_DETAIL_xyz123_should_not_leak/.test(c.body),
137
+ 'response body must not surface the raw err.message');
138
+ assert.ok(/Login error/.test(c.body), 'page title should be the generic "Login error"');
139
+ });
140
+
141
+ it('completes successfully (no error response) when interactionFinished resolves', async () => {
142
+ let interactionFinishedCalled = false;
143
+ const provider = {
144
+ Interaction: {
145
+ find: async () => ({
146
+ result: { login: { accountId: account.id } },
147
+ exp: Math.floor(Date.now() / 1000) + 600,
148
+ }),
149
+ },
150
+ interactionFinished: async () => { interactionFinishedCalled = true; /* oidc-provider would write to reply.raw here */ },
151
+ };
152
+
153
+ const { reply, captured } = makeFakeReplyAndCapture();
154
+ const request = makeFakeRequest({ uid: 'fake-uid', accountId: account.id });
155
+
156
+ await handleSchnorrComplete(request, reply, provider);
157
+
158
+ const c = captured();
159
+ assert.strictEqual(interactionFinishedCalled, true, 'interactionFinished must be called');
160
+ assert.strictEqual(c.hijacked, true, 'reply must be hijacked');
161
+ assert.strictEqual(c.status, null, 'no error response should be written when interactionFinished succeeds');
162
+ });
163
+ });
@@ -806,6 +806,69 @@ describe('profilePathCandidates — deployment-shape coverage (#411)', () => {
806
806
  assert.deepStrictEqual(paths, [path.join(DATA_ROOT, 'profile', 'card.jsonld')]);
807
807
  });
808
808
 
809
+ // Root-path WebIDs (#451): pathname `/` yields an empty pathnameRel,
810
+ // so the plain candidates resolve to directories (dataRoot itself /
811
+ // the pod dir) and the indexer ENOENT/not-a-regular-file'd every
812
+ // account shaped like `https://melvin.solid.social/#me`. The fix
813
+ // additionally probes the conventional `profile/card.jsonld`
814
+ // location under each directory candidate.
815
+
816
+ it('root-path WebID probes <dataRoot>/profile/card.jsonld (#451)', () => {
817
+ const { paths } = profilePathCandidates(DATA_ROOT, 'https://example.com/#me');
818
+ const expected = path.join(DATA_ROOT, 'profile', 'card.jsonld');
819
+ assert.ok(paths.includes(expected),
820
+ `expected ${expected}; got ${paths.join(', ')}`);
821
+ });
822
+
823
+ it('root-path WebID in subdomain mode probes <dataRoot>/<podName>/profile/card.jsonld (#451)', () => {
824
+ // The exact solid.social scenario from the issue: account `melvin`
825
+ // with WebID https://melvin.solid.social/#me, profile on disk at
826
+ // <dataRoot>/melvin/profile/card.jsonld.
827
+ const { paths } = profilePathCandidates(DATA_ROOT, 'https://melvin.solid.social/#me', 'melvin');
828
+ const expected = path.join(DATA_ROOT, 'melvin', 'profile', 'card.jsonld');
829
+ assert.ok(paths.includes(expected),
830
+ `expected ${expected}; got ${paths.join(', ')}`);
831
+ });
832
+
833
+ it('root-path WebID in subdomain mode does NOT probe the root pod profile (#451 cross-account guard)', () => {
834
+ // When the subdomain gate matches, <dataRoot>/profile/card.jsonld
835
+ // is the ROOT pod's document — a different account. A relative
836
+ // subject there ("@id": "#me") would absolutize against the
837
+ // probing account's WebID and pass the rebuild loop's @id check,
838
+ // binding the root pod's pubkeys to the subdomain account. The
839
+ // root-level fallback must therefore be suppressed when the gate
840
+ // matches.
841
+ const { paths } = profilePathCandidates(DATA_ROOT, 'https://melvin.solid.social/#me', 'melvin');
842
+ const rootPodProfile = path.join(DATA_ROOT, 'profile', 'card.jsonld');
843
+ assert.ok(!paths.includes(rootPodProfile),
844
+ `cross-account window: ${rootPodProfile} must not be probed for a subdomain account; got ${paths.join(', ')}`);
845
+ });
846
+
847
+ it('pod-root WebID with trailing slash probes <pod>/profile/card.jsonld (#451)', () => {
848
+ // Path-mode sibling of the root-path case: pathname `/alice/`
849
+ // also resolves to a directory without the fallback.
850
+ const { paths } = profilePathCandidates(DATA_ROOT, 'https://example.com/alice/#me');
851
+ const expected = path.join(DATA_ROOT, 'alice', 'profile', 'card.jsonld');
852
+ assert.ok(paths.includes(expected),
853
+ `expected ${expected}; got ${paths.join(', ')}`);
854
+ });
855
+
856
+ it('root-path WebID does NOT probe a podName dir when the host label does not match (#451)', () => {
857
+ // The subdomain gate must keep applying to the fallback candidate;
858
+ // otherwise a root-pod WebID could probe another account's pod dir.
859
+ const { paths } = profilePathCandidates(DATA_ROOT, 'https://melvin.solid.social/#me', 'other');
860
+ const leaked = path.join(DATA_ROOT, 'other', 'profile', 'card.jsonld');
861
+ assert.ok(!paths.includes(leaked),
862
+ `gate bypassed: ${leaked} should not be a candidate; got ${paths.join(', ')}`);
863
+ });
864
+
865
+ it('non-root WebIDs gain NO extra fallback candidates (#451)', () => {
866
+ // A document-shaped pathname must produce exactly the same
867
+ // candidate list as before the #451 fix.
868
+ const { paths } = profilePathCandidates(DATA_ROOT, 'https://example.com/alice/profile/card.jsonld#me');
869
+ assert.deepStrictEqual(paths, [path.join(DATA_ROOT, 'alice', 'profile', 'card.jsonld')]);
870
+ });
871
+
809
872
  it('returns empty paths for an unparseable webId', () => {
810
873
  assert.deepStrictEqual(profilePathCandidates(DATA_ROOT, 'not a url'), { paths: [], skipped: [] });
811
874
  assert.deepStrictEqual(profilePathCandidates(DATA_ROOT, null), { paths: [], skipped: [] });