javascript-solid-server 0.0.225 → 0.0.227

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/SECURITY.md ADDED
@@ -0,0 +1,8 @@
1
+ # Security
2
+
3
+ JSS is pre-alpha. Reports are handled in the open unless you ask otherwise.
4
+
5
+ - **Report a problem:** open an issue at https://github.com/JavaScriptSolidServer/JavaScriptSolidServer/issues. If you would rather report privately, email the maintainer (see `MAINTAINERS.md`) or use GitHub's private vulnerability reporting on this repository when it is enabled.
6
+ - **What to include:** the version (`jss --version` or `package.json`), the request or steps that show the problem, and the fix you would make if you have one.
7
+ - **What happens next:** we confirm against the code, open an issue, fix it in a pull request that names the reporter (unless you ask not to be named), and release. Past audits are in `SECURITY-AUDIT-*.md`.
8
+ - **Scope:** anything in this repository. Deployments, plugins and client libraries have their own repositories.
package/bin/jss.js CHANGED
@@ -10,6 +10,7 @@
10
10
  */
11
11
 
12
12
  import { Command } from 'commander';
13
+ import { sortPanes } from '../src/mashlib/index.js';
13
14
  import { createServer } from '../src/server.js';
14
15
  import { loadConfig, saveConfig, printConfig, defaults, parsePluginFlag } from '../src/config.js';
15
16
  import { createInvite, listInvites, revokeInvite } from '../src/idp/invites.js';
@@ -106,6 +107,7 @@ program
106
107
  .option('--mashlib-module <url>', 'Enable ES module data browser from a URL')
107
108
  .option('--no-mashlib', 'Disable Mashlib data browser')
108
109
  .option('--mashlib-version <version>', 'Mashlib version for CDN mode (default: 2.0.0)')
110
+ .option('--panes <urls>', 'Comma-separated pane module URLs the data browser loads at start-up')
109
111
  .option('--git', 'Enable Git HTTP backend (clone/push support)')
110
112
  .option('--no-git', 'Disable Git HTTP backend')
111
113
  .option('--cors-proxy', 'Enable CORS proxy at /proxy?url=... for browser apps (WAC-gated)')
@@ -241,6 +243,7 @@ program
241
243
  mashlibCdn: config.mashlibCdn,
242
244
  mashlibVersion: config.mashlibVersion,
243
245
  mashlibModule: config.mashlibModule,
246
+ panes: config.panes,
244
247
  git: config.git,
245
248
  corsProxy: config.corsProxy,
246
249
  corsProxyMaxBytes: config.corsProxyMaxBytes,
@@ -303,6 +306,17 @@ program
303
306
  console.log(` Mashlib: local (data browser enabled)`);
304
307
  }
305
308
  if (config.mashlibModule) console.log(` Mashlib module: ${config.mashlibModule}`);
309
+ {
310
+ const { urls, dropped } = sortPanes(config.panes);
311
+ const paneMode = config.mashlibCdn && !config.mashlibModule;
312
+ if (urls.length && paneMode) console.log(` Panes: ${urls.join(', ')}`);
313
+ if (urls.length && !paneMode) {
314
+ console.log(config.mashlibModule
315
+ ? ' Panes: ignored (--panes does not apply to --mashlib-module yet)'
316
+ : ' Panes: ignored (--panes needs --mashlib-cdn)');
317
+ }
318
+ for (const d of dropped) console.log(` Panes: ignored "${d}" (not an http(s) URL or an absolute path)`);
319
+ }
306
320
  if (config.git) console.log(' Git: enabled (clone/push support)');
307
321
  if (config.corsProxy) console.log(' CORS proxy: enabled (/proxy?url=..., WAC-gated)');
308
322
  if (config.nostr) console.log(` Nostr: enabled (${config.nostrPath})`);
@@ -97,6 +97,12 @@ jss start --idp
97
97
  - Account must have a `did:nostr:<pubkey>` WebID linked
98
98
  - User needs a NIP-07 compatible browser extension
99
99
 
100
+ **What the server checks in a NIP-98 event** (`Authorization: Nostr <base64 event>`, kind 27235):
101
+ - `u` must equal the request URL (query string optional); `method` must be present and equal the HTTP method
102
+ - a PUT, POST or PATCH with a body must carry `payload` = sha256 of the exact body bytes
103
+ - `created_at` within ±60 s of the server clock, and each event id is accepted once
104
+ - Git smart-HTTP requests are the exception, and only while the server runs with `--git`: the ref-discovery GET (`/info/refs?service=git-…-pack`) and the pack-service POSTs. There `method` may be `*` or omitted, `u` may be the repo base URL, no `payload` is required, and the same event id may be reused, so a credential helper can sign once per git operation
105
+
100
106
  **Benefits:**
101
107
  - No passwords - cryptographic authentication
102
108
  - Works with existing Nostr identity
@@ -147,6 +147,7 @@ Server: pub http://localhost:4443/alice/public/data.json (on change)
147
147
  | `--mashlib-cdn` | Enable Mashlib (CDN mode) | false |
148
148
  | `--mashlib-module <url>` | Enable ES module data browser from a URL | - |
149
149
  | `--mashlib-version <ver>` | Mashlib CDN version | 2.0.0 |
150
+ | `--panes <urls>` | Comma-separated pane module URLs the data browser loads at start-up | - |
150
151
  | `--solidos-ui` | Enable modern SolidOS UI (requires --mashlib) | false |
151
152
  | `--git` | Enable Git HTTP backend | false |
152
153
  | `--nostr` | Enable Nostr relay | false |
package/docs/mashlib.md CHANGED
@@ -35,6 +35,27 @@ Loads an ES module-based data browser from any URL. Uses `<script type="module">
35
35
 
36
36
  **Note:** Mashlib works best with `--conneg` enabled for Turtle support.
37
37
 
38
+ ## Extra panes at start-up
39
+
40
+ ```bash
41
+ jss start --mashlib-cdn --conneg --panes https://melvincarvalho.github.io/pane-loader/examples/meetings-pane.js
42
+ ```
43
+
44
+ `--panes` (env `JSS_PANES`, config `panes`) takes a comma-separated list of pane module URLs. Each is an ES module whose default export is a SolidOS pane (`name`, `label`, `render`). The data browser page loads and registers them before it starts SolidOS, so they are in the registry at first render. Mashlib is not changed or rebuilt.
45
+
46
+ - A URL is an `http(s)` address or an absolute path on this server (`/public/panes/my-pane.js`); anything else is ignored.
47
+ - A pane that fails to load, or is not a pane, is skipped with a console warning, and the data browser still starts.
48
+ - Panes are fetched at the same time and registered in the order listed. The page waits at most 5 seconds for them. A pane slower than that is registered when it arrives and is offered from the next view drawn; the view already on show is not redrawn.
49
+ - It applies to `--mashlib-cdn`. It does not apply to `--mashlib-module` yet: a module entry point starts itself, so that mode needs its own design. The server says so at start-up.
50
+ - On the command line and in `JSS_PANES` the list is split on commas. A pane URL that contains a comma has to go in the config file, as an array.
51
+ - Entries that are not usable are listed at start-up, not silently ignored.
52
+ - A loaded pane is registered after the built-in ones, so it is offered alongside them and does not replace the default view.
53
+ - With no `--panes`, the page is exactly as before.
54
+
55
+ The loader is [pane-loader](https://github.com/melvincarvalho/pane-loader), shipped with JSS and served at `/.well-known/jss/pane-loader.js` when panes are configured. The shipped copy leaves out the upstream `?pane=URL` shortcut, so the only panes loaded are the ones in this list. Background: [SolidOS Panes, section 7](https://melvincarvalho.github.io/solidos-panes/#dynamic).
56
+
57
+ **Trust:** a pane runs in the page with the logged-in session and can do whatever the person can. This list is set by whoever runs the server; add only panes you would install for every user. Signing and consent are tracked in https://github.com/JavaScriptSolidServer/JavaScriptSolidServer/issues/651.
58
+
38
59
  ## Modern UI (SolidOS UI)
39
60
 
40
61
  ```bash
package/docs/security.md CHANGED
@@ -69,6 +69,10 @@ data directory. Two clients racing with the same, still valid, ETag get one `2xx
69
69
  `412`; the loser's write is never silently overwritten. A request that cannot take the lock
70
70
  within 30 seconds gets `503` with `Retry-After: 1`.
71
71
 
72
+ ### Identity document fetches are bounded
73
+
74
+ Authentication can make the server fetch a document it does not control: a CID document for LWS-CID tokens, a DID document and WebID back-link for did:nostr, or a WebID profile for WebID-TLS. Every such fetch runs under one deadline that covers the connection, the response headers **and** the body read, plus a byte cap. The CID and did:nostr fetchers follow redirects themselves and apply the 5-second deadline per hop; the WebID-TLS profile fetch lets `fetch` follow redirects and applies one 5-second deadline to the whole chain. In addition, the CID and did:nostr fetches also go through the SSRF guard (`validateExternalUrl`) on the original URL and on every redirect hop, with cross-origin redirects refused. A host that answers promptly and then trickles the body cannot hold an authentication attempt, or the outbound socket, open beyond the deadline: the fetch fails, the failure is cached (1 minute for CID and did:nostr lookups, 5 minutes for a WebID-TLS verification), and the request is answered as unauthenticated. Responses that are not read (redirect hops, error statuses, oversized bodies) are cancelled so the socket is released at once.
75
+
72
76
  ## Subdomain Mode (XSS Protection)
73
77
 
74
78
  By default, JSS uses **path-based pods** (`/alice/`, `/bob/`). This is simple but has a security limitation: all pods share the same origin, making cross-site scripting (XSS) attacks possible between pods.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "javascript-solid-server",
3
- "version": "0.0.225",
3
+ "version": "0.0.227",
4
4
  "description": "A minimal, fast Solid server",
5
5
  "main": "src/index.js",
6
6
  "type": "module",
@@ -18,7 +18,9 @@
18
18
  * - Body size cap enforced via Content-Length up front AND a
19
19
  * streaming reader cap (cancel on overage), so untrusted hosts
20
20
  * can't OOM us with a large payload.
21
- * - 5-second timeout per request via AbortController.
21
+ * - 5-second timeout per request via AbortController, covering the
22
+ * connection, the headers AND the body read, so a host that
23
+ * trickles the body cannot hold the auth attempt open (#641).
22
24
  *
23
25
  * Throws on any failure; callers convert to whatever they want
24
26
  * (LWS-CID surfaces the error string, the NIP-98 path treats
@@ -26,6 +28,7 @@
26
28
  */
27
29
 
28
30
  import { validateExternalUrl } from '../utils/ssrf.js';
31
+ import { readBodyWithCap, discardBody } from '../utils/bounded-body.js';
29
32
 
30
33
  // Default body cap (256 KB) — CID documents are tiny in practice.
31
34
  const DEFAULT_MAX_BYTES = 256 * 1024;
@@ -73,6 +76,8 @@ export function _clearProfileCacheForTests() {
73
76
  * claims or is derived from a request).
74
77
  * @param {object} [opts]
75
78
  * @param {number} [opts.maxBytes=DEFAULT_MAX_BYTES]
79
+ * @param {number} [opts.timeoutMs=FETCH_TIMEOUT_MS] - deadline per hop,
80
+ * covering headers and body
76
81
  * @returns {Promise<object>} parsed JSON
77
82
  * @throws on any validation, network, redirect, size, or parse failure
78
83
  */
@@ -118,6 +123,7 @@ function setCached(url, entry) {
118
123
 
119
124
  async function fetchCidDocumentNoCache(docUrl, opts = {}) {
120
125
  const maxBytes = opts.maxBytes ?? DEFAULT_MAX_BYTES;
126
+ const timeoutMs = opts.timeoutMs ?? FETCH_TIMEOUT_MS;
121
127
  const originalOrigin = new URL(docUrl).origin;
122
128
  let currentUrl = docUrl;
123
129
 
@@ -132,8 +138,11 @@ async function fetchCidDocumentNoCache(docUrl, opts = {}) {
132
138
  throw new Error(`SSRF protection: ${validation.error}`);
133
139
  }
134
140
 
141
+ // One deadline covers the connection, the headers AND the body
142
+ // read (#641). The timer is only cleared in the finally, after
143
+ // the body has been consumed or the hop has been abandoned.
135
144
  const controller = new AbortController();
136
- const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
145
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
137
146
  let res;
138
147
  try {
139
148
  res = await fetch(currentUrl, {
@@ -141,62 +150,46 @@ async function fetchCidDocumentNoCache(docUrl, opts = {}) {
141
150
  redirect: 'manual',
142
151
  signal: controller.signal,
143
152
  });
144
- } finally {
145
- clearTimeout(timer);
146
- }
147
153
 
148
- if (res.status >= 300 && res.status < 400) {
149
- if (isLastAllowedHop) {
150
- throw new Error(`too many redirects (>${MAX_REDIRECTS})`);
154
+ if (res.status >= 300 && res.status < 400) {
155
+ if (isLastAllowedHop) {
156
+ throw new Error(`too many redirects (>${MAX_REDIRECTS})`);
157
+ }
158
+ const loc = res.headers.get('location');
159
+ if (!loc) throw new Error(`redirect ${res.status} without Location`);
160
+ const nextUrl = new URL(loc, currentUrl).toString();
161
+ const nextOrigin = new URL(nextUrl).origin;
162
+ if (nextOrigin !== originalOrigin) {
163
+ throw new Error(`cross-origin redirect refused: ${originalOrigin} → ${nextOrigin}`);
164
+ }
165
+ currentUrl = nextUrl;
166
+ continue;
151
167
  }
152
- const loc = res.headers.get('location');
153
- if (!loc) throw new Error(`redirect ${res.status} without Location`);
154
- const nextUrl = new URL(loc, currentUrl).toString();
155
- const nextOrigin = new URL(nextUrl).origin;
156
- if (nextOrigin !== originalOrigin) {
157
- throw new Error(`cross-origin redirect refused: ${originalOrigin} → ${nextOrigin}`);
158
- }
159
- currentUrl = nextUrl;
160
- continue;
161
- }
162
168
 
163
- if (!res.ok) throw new Error(`HTTP ${res.status}`);
169
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
164
170
 
165
- const ct = (res.headers.get('content-type') || '').toLowerCase();
166
- if (!ct.includes('json')) {
167
- throw new Error(`unexpected content-type: ${ct || '(none)'}`);
168
- }
171
+ const ct = (res.headers.get('content-type') || '').toLowerCase();
172
+ if (!ct.includes('json')) {
173
+ throw new Error(`unexpected content-type: ${ct || '(none)'}`);
174
+ }
169
175
 
170
- const declared = Number(res.headers.get('content-length'));
171
- if (Number.isFinite(declared) && declared > maxBytes) {
172
- throw new Error(`CID document too large (Content-Length=${declared} > ${maxBytes})`);
176
+ const declared = Number(res.headers.get('content-length'));
177
+ if (Number.isFinite(declared) && declared > maxBytes) {
178
+ throw new Error(`CID document too large (Content-Length=${declared} > ${maxBytes})`);
179
+ }
180
+ const text = await readBodyWithCap(res, {
181
+ maxBytes,
182
+ signal: controller.signal,
183
+ label: 'CID document',
184
+ });
185
+ return JSON.parse(text);
186
+ } finally {
187
+ clearTimeout(timer);
188
+ // Every exit that did not consume the body (redirect hop, error
189
+ // status, bad content-type, oversize, abort) releases the socket.
190
+ discardBody(res);
173
191
  }
174
- const text = await readBodyWithCap(res, maxBytes);
175
- return JSON.parse(text);
176
192
  }
177
193
  throw new Error('profile fetch loop exited unexpectedly');
178
194
  }
179
195
 
180
- async function readBodyWithCap(res, maxBytes) {
181
- const reader = res.body?.getReader?.();
182
- if (!reader) {
183
- const text = await res.text();
184
- if (Buffer.byteLength(text, 'utf8') > maxBytes) {
185
- throw new Error(`CID document too large (>${maxBytes} bytes)`);
186
- }
187
- return text;
188
- }
189
- const chunks = [];
190
- let total = 0;
191
- for (;;) {
192
- const { value, done } = await reader.read();
193
- if (done) break;
194
- total += value.byteLength;
195
- if (total > maxBytes) {
196
- try { await reader.cancel(); } catch { /* noop */ }
197
- throw new Error(`CID document too large (>${maxBytes} bytes)`);
198
- }
199
- chunks.push(value);
200
- }
201
- return Buffer.concat(chunks.map((c) => Buffer.from(c.buffer, c.byteOffset, c.byteLength))).toString('utf8');
202
- }
@@ -8,6 +8,7 @@
8
8
  */
9
9
 
10
10
  import { validateExternalUrl } from '../utils/ssrf.js';
11
+ import { readBodyWithCap, discardBody } from '../utils/bounded-body.js';
11
12
  import { extractNostrPubkeysFromProfile } from './nostr-keys.js';
12
13
 
13
14
  // Default DID resolver endpoint
@@ -68,6 +69,7 @@ function rateLimitedError(key, message) {
68
69
  // bypass the initial validateExternalUrl check)
69
70
  // - cross-origin redirects refused (open-redirect → arbitrary host)
70
71
  // - response size cap before reading the body
72
+ // - the per-hop timeout covers the body read too (#641)
71
73
  const MAX_REDIRECTS = 5;
72
74
  const DEFAULT_FETCH_TIMEOUT_MS = 5000;
73
75
  const DEFAULT_MAX_BYTES = 1 * 1024 * 1024; // 1 MB — DID docs / WebID profiles are tiny
@@ -75,7 +77,8 @@ const DEFAULT_MAX_BYTES = 1 * 1024 * 1024; // 1 MB — DID docs / WebID profiles
75
77
  /**
76
78
  * Fetch with a timeout, manual redirect following, SSRF re-validation
77
79
  * per hop, and a body-size cap. Returns `{ url, status, headers, body }`
78
- * — `body` is a string (caller decides whether to JSON-parse).
80
+ * — `body` is a string (caller decides whether to JSON-parse), and is
81
+ * empty on a non-2xx status: error bodies are not read.
79
82
  *
80
83
  * Throws on validation, network, redirect, or size failures so the
81
84
  * resolver can swallow them uniformly into a null/false return.
@@ -109,6 +112,8 @@ export async function fetchWithRedirectGuard(initialUrl, {
109
112
  if (!validation.valid) {
110
113
  throw new Error(`SSRF protection: ${validation.error}`);
111
114
  }
115
+ // One deadline covers the connection, the headers AND the body
116
+ // read (#641); the timer is cleared only after the body is in.
112
117
  const controller = new AbortController();
113
118
  const timer = setTimeout(() => controller.abort(), timeout);
114
119
  let res;
@@ -118,51 +123,39 @@ export async function fetchWithRedirectGuard(initialUrl, {
118
123
  redirect: 'manual',
119
124
  signal: controller.signal,
120
125
  });
121
- } finally {
122
- clearTimeout(timer);
123
- }
124
- if (res.status >= 300 && res.status < 400) {
125
- if (isLastAllowedHop) throw new Error(`too many redirects (>${MAX_REDIRECTS})`);
126
- const loc = res.headers.get('location');
127
- if (!loc) throw new Error(`redirect ${res.status} without Location`);
128
- const nextUrl = new URL(loc, currentUrl).toString();
129
- const nextOrigin = new URL(nextUrl).origin;
130
- if (nextOrigin !== originalOrigin) {
131
- throw new Error(`cross-origin redirect refused: ${originalOrigin} → ${nextOrigin}`);
126
+ if (res.status >= 300 && res.status < 400) {
127
+ if (isLastAllowedHop) throw new Error(`too many redirects (>${MAX_REDIRECTS})`);
128
+ const loc = res.headers.get('location');
129
+ if (!loc) throw new Error(`redirect ${res.status} without Location`);
130
+ const nextUrl = new URL(loc, currentUrl).toString();
131
+ const nextOrigin = new URL(nextUrl).origin;
132
+ if (nextOrigin !== originalOrigin) {
133
+ throw new Error(`cross-origin redirect refused: ${originalOrigin} → ${nextOrigin}`);
134
+ }
135
+ currentUrl = nextUrl;
136
+ continue;
132
137
  }
133
- currentUrl = nextUrl;
134
- continue;
135
- }
136
- // Cap the body before reading. Content-Length pre-check rejects
137
- // a server that advertises an oversized response; the streaming
138
- // cap rejects servers that lie about Content-Length.
139
- const declared = Number(res.headers.get('content-length'));
140
- if (Number.isFinite(declared) && declared > maxBytes) {
141
- throw new Error(`response too large (Content-Length=${declared} > ${maxBytes})`);
142
- }
143
- const reader = res.body?.getReader?.();
144
- let body = '';
145
- if (!reader) {
146
- body = await res.text();
147
- if (Buffer.byteLength(body, 'utf8') > maxBytes) {
148
- throw new Error(`response too large (>${maxBytes} bytes)`);
138
+ // Error statuses fail fast with an empty body: callers only use
139
+ // `body` on 2xx, and returning here lets discardBody() in the
140
+ // finally cancel a trickling error page at once instead of
141
+ // reading it until the deadline.
142
+ if (!res.ok) {
143
+ return { url: currentUrl, status: res.status, headers: res.headers, body: '' };
149
144
  }
150
- } else {
151
- const chunks = [];
152
- let total = 0;
153
- for (;;) {
154
- const { value, done } = await reader.read();
155
- if (done) break;
156
- total += value.byteLength;
157
- if (total > maxBytes) {
158
- try { await reader.cancel(); } catch { /* noop */ }
159
- throw new Error(`response too large (>${maxBytes} bytes)`);
160
- }
161
- chunks.push(value);
145
+ // Cap the body before reading. Content-Length pre-check rejects
146
+ // a server that advertises an oversized response; the streaming
147
+ // cap rejects servers that lie about Content-Length.
148
+ const declared = Number(res.headers.get('content-length'));
149
+ if (Number.isFinite(declared) && declared > maxBytes) {
150
+ throw new Error(`response too large (Content-Length=${declared} > ${maxBytes})`);
162
151
  }
163
- body = Buffer.concat(chunks).toString('utf8');
152
+ const body = await readBodyWithCap(res, { maxBytes, signal: controller.signal });
153
+ return { url: currentUrl, status: res.status, headers: res.headers, body };
154
+ } finally {
155
+ clearTimeout(timer);
156
+ // Redirect hops and error exits never read the body; release the socket.
157
+ discardBody(res);
164
158
  }
165
- return { url: currentUrl, status: res.status, headers: res.headers, body };
166
159
  }
167
160
  throw new Error('fetch loop exited unexpectedly');
168
161
  }
@@ -181,7 +181,7 @@ export function handleUnauthorized(request, reply, isAuthenticated, wacAllow, au
181
181
  if (request.mashlibEnabled) {
182
182
  const html = request.mashlibModule
183
183
  ? generateModuleDatabrowserHtml(request.mashlibModule)
184
- : generateDatabrowserHtml(request.url, request.mashlibCdn ? request.mashlibVersion : null);
184
+ : generateDatabrowserHtml(request.url, request.mashlibCdn ? request.mashlibVersion : null, { panes: request.panes });
185
185
  return reply.code(statusCode).type('text/html').send(html);
186
186
  }
187
187
  return reply.code(statusCode).type('text/html').send(getErrorPage(statusCode, isAuthenticated, request));
package/src/auth/nostr.js CHANGED
@@ -43,6 +43,53 @@ const HTTP_AUTH_KIND = 27235;
43
43
  // Timestamp tolerance in seconds
44
44
  const TIMESTAMP_TOLERANCE = 60;
45
45
 
46
+ // Git smart-HTTP routes keep the lenient rules (missing or `*` method, URL
47
+ // prefix match, no payload tag): git credential helpers sign once for the
48
+ // repo base URL and git sends the pack bodies. Everywhere else the NIP-98
49
+ // MUSTs apply, or a captured header could be replayed as a different method
50
+ // against any sub-path (#643).
51
+ const WRITE_METHODS = new Set(['PUT', 'POST', 'PATCH']);
52
+
53
+ // A git smart-HTTP request, recognised by its shape (the ref discovery GET
54
+ // with a service query, or a pack-service POST with the git content type),
55
+ // and only while the server has git enabled. A plain resource whose path
56
+ // happens to end in /info/refs or /git-receive-pack gets the strict rules.
57
+ function isGitSmartHttp(request) {
58
+ if (request.server?.gitEnabled !== true) return false;
59
+ const [path, query = ''] = request.url.split('?');
60
+ const method = request.method.toUpperCase();
61
+ if (path.endsWith('/info/refs')) {
62
+ return method === 'GET' && /(^|&)service=git-(upload|receive)-pack(&|$)/.test(query);
63
+ }
64
+ if (/\/git-(upload|receive)-pack$/.test(path)) {
65
+ const type = request.headers['content-type'] || '';
66
+ return method === 'POST' && /^application\/x-git-(upload|receive)-pack-request/.test(type);
67
+ }
68
+ return false;
69
+ }
70
+
71
+ // Replay cache: event ids accepted inside the timestamp window (#643). An
72
+ // event is valid for ±TIMESTAMP_TOLERANCE, so an id older than twice that
73
+ // can never verify again and is dropped by a periodic sweep, as the DPoP
74
+ // jti cache in solid-oidc.js does; noteEventId itself is O(1). Not applied
75
+ // on git routes: git reuses the credential helper's one token for every
76
+ // request of an operation (info/refs, then the pack service).
77
+ const seenEventIds = new Map();
78
+ const REPLAY_WINDOW = TIMESTAMP_TOLERANCE * 2;
79
+ const REPLAY_SWEEP_INTERVAL = 60 * 1000;
80
+ function sweepEventIds() {
81
+ const now = Math.floor(Date.now() / 1000);
82
+ for (const [id, at] of seenEventIds) {
83
+ if (now - at > REPLAY_WINDOW) seenEventIds.delete(id);
84
+ }
85
+ }
86
+ setInterval(sweepEventIds, REPLAY_SWEEP_INTERVAL).unref();
87
+ function noteEventId(id, now) {
88
+ if (seenEventIds.has(id)) return false;
89
+ seenEventIds.set(id, now);
90
+ return true;
91
+ }
92
+
46
93
  // Profile-fetch body-size cap. Matches the LWS-CID verifier; both
47
94
  // callers go through the shared fetchCidDocument helper.
48
95
  const MAX_PROFILE_BYTES = 256 * 1024;
@@ -222,9 +269,10 @@ export async function verifyNostrAuth(request) {
222
269
  let urlMatches = normalizedEventUrl === normalizedRequestUrl ||
223
270
  normalizedEventUrl === normalizedRequestUrlNoQuery;
224
271
 
225
- // For git clients: allow prefix matching (event URL is base of request URL)
226
- // This enables git credential helpers that sign for the repo base URL
227
- if (!urlMatches && normalizedRequestUrlNoQuery.startsWith(normalizedEventUrl + '/')) {
272
+ // Git routes only: allow prefix matching (event URL is base of request
273
+ // URL), for git credential helpers that sign for the repo base URL.
274
+ const gitRoute = isGitSmartHttp(request);
275
+ if (!urlMatches && gitRoute && normalizedRequestUrlNoQuery.startsWith(normalizedEventUrl + '/')) {
228
276
  urlMatches = true;
229
277
  }
230
278
 
@@ -232,11 +280,14 @@ export async function verifyNostrAuth(request) {
232
280
  return { webId: null, error: `URL mismatch: event URL "${eventUrl}" does not match request URL "${fullUrl}"` };
233
281
  }
234
282
 
235
- // Validate method tag matches request method
236
- // For git clients: allow '*' as wildcard method
237
- // If method tag is missing, infer from HTTP request (lenient mode)
283
+ // Validate method tag matches request method (NIP-98: MUST). Git routes
284
+ // only: a missing tag is inferred from the request and '*' is a wildcard.
238
285
  const eventMethod = getTagValue(event, 'method');
239
- if (eventMethod && eventMethod !== '*' && eventMethod.toUpperCase() !== request.method.toUpperCase()) {
286
+ if (!eventMethod) {
287
+ if (!gitRoute) return { webId: null, error: 'Missing method tag in event' };
288
+ } else if (eventMethod === '*') {
289
+ if (!gitRoute) return { webId: null, error: 'Wildcard method is only accepted on git routes' };
290
+ } else if (eventMethod.toUpperCase() !== request.method.toUpperCase()) {
240
291
  return { webId: null, error: `Method mismatch: expected ${request.method}, got ${eventMethod}` };
241
292
  }
242
293
 
@@ -247,6 +298,12 @@ export async function verifyNostrAuth(request) {
247
298
  // to a falsy value (`null`, `false`, `0`, `""`) is still hash-checked
248
299
  // rather than silently skipping the integrity guard (Copilot review on
249
300
  // #573). Fastify leaves request.body `undefined` when no body was sent.
301
+ // A write with a body must carry the payload tag (git routes excepted:
302
+ // the pack bodies are not signed), or a replayed header would authorize
303
+ // whatever body the replayer attaches.
304
+ if (!payloadTag && !gitRoute && request.body !== undefined && WRITE_METHODS.has(request.method.toUpperCase())) {
305
+ return { webId: null, error: 'Missing payload tag for request with body' };
306
+ }
250
307
  if (payloadTag && request.body !== undefined) {
251
308
  // Hash the EXACT bytes the client signed. NIP-98's `payload` tag is
252
309
  // sha256(request body) over the wire bytes. crypto.update() accepts a
@@ -300,6 +357,12 @@ export async function verifyNostrAuth(request) {
300
357
  return { webId: null, error: 'Invalid Schnorr signature' };
301
358
  }
302
359
 
360
+ // Each signed event authorizes one request (#643), except on git routes,
361
+ // where one token covers the requests of a git operation.
362
+ if (!gitRoute && !noteEventId(event.id, now)) {
363
+ return { webId: null, error: 'Replayed event id' };
364
+ }
365
+
303
366
  // First lookup: the resource's owner WebID profile. If the pod owner
304
367
  // declared this pubkey as a verificationMethod (CID v1 / LWS-CID
305
368
  // shape — produced by the doctor's B.2 path), authenticate as the
@@ -12,6 +12,7 @@
12
12
  */
13
13
 
14
14
  import { turtleToJsonLd } from '../rdf/turtle.js';
15
+ import { readBodyWithCap, discardBody } from '../utils/bounded-body.js';
15
16
 
16
17
  // cert: ontology namespace
17
18
  const CERT_NS = 'http://www.w3.org/ns/auth/cert#';
@@ -20,19 +21,35 @@ const CERT_NS = 'http://www.w3.org/ns/auth/cert#';
20
21
  const cache = new Map();
21
22
  const CACHE_TTL = 5 * 60 * 1000; // 5 minutes
22
23
 
24
+ const PROFILE_FETCH_TIMEOUT_MS = 5000;
25
+ const PROFILE_MAX_BYTES = 1024 * 1024; // 1 MB — profiles are tiny
26
+
23
27
  /**
24
- * Fetch with timeout
28
+ * Fetch a profile document as text under one deadline that covers
29
+ * the connection, the headers AND the body read (#641), plus a byte
30
+ * cap. Returns `{ contentType, text }`; throws on HTTP error, timeout
31
+ * or overage.
25
32
  */
26
- async function fetchWithTimeout(url, options = {}, timeout = 5000) {
33
+ async function fetchProfileText(url, options = {}, timeout = PROFILE_FETCH_TIMEOUT_MS) {
27
34
  const controller = new AbortController();
28
- const id = setTimeout(() => controller.abort(), timeout);
35
+ const timer = setTimeout(() => controller.abort(), timeout);
36
+ let response;
29
37
  try {
30
- const response = await fetch(url, { ...options, signal: controller.signal });
31
- clearTimeout(id);
32
- return response;
33
- } catch (err) {
34
- clearTimeout(id);
35
- throw err;
38
+ response = await fetch(url, { ...options, signal: controller.signal });
39
+ if (!response.ok) {
40
+ throw new Error(`Failed to fetch WebID profile: ${response.status}`);
41
+ }
42
+ const contentType = response.headers.get('content-type') || '';
43
+ const text = await readBodyWithCap(response, {
44
+ maxBytes: PROFILE_MAX_BYTES,
45
+ signal: controller.signal,
46
+ label: 'WebID profile',
47
+ });
48
+ return { contentType, text };
49
+ } finally {
50
+ clearTimeout(timer);
51
+ // An error status or abort leaves the body unread; release the socket.
52
+ discardBody(response);
36
53
  }
37
54
  }
38
55
 
@@ -134,21 +151,16 @@ function parseKeyObject(keyObj) {
134
151
  /**
135
152
  * Fetch and parse WebID profile
136
153
  * @param {string} webId - WebID URI to fetch
154
+ * @param {object} [opts]
155
+ * @param {number} [opts.timeout] - deadline in ms covering headers and body
137
156
  * @returns {Promise<Array<{modulus: string, exponent: string}>>}
138
157
  */
139
- async function fetchProfileKeys(webId) {
140
- const response = await fetchWithTimeout(webId, {
158
+ async function fetchProfileKeys(webId, { timeout } = {}) {
159
+ const { contentType, text } = await fetchProfileText(webId, {
141
160
  headers: {
142
161
  'Accept': 'application/ld+json, text/turtle, application/json'
143
162
  }
144
- });
145
-
146
- if (!response.ok) {
147
- throw new Error(`Failed to fetch WebID profile: ${response.status}`);
148
- }
149
-
150
- const contentType = response.headers.get('content-type') || '';
151
- const text = await response.text();
163
+ }, timeout);
152
164
 
153
165
  let jsonLd;
154
166
 
@@ -175,9 +187,11 @@ async function fetchProfileKeys(webId) {
175
187
  * Verify certificate against WebID profile
176
188
  * @param {object} certificate - Node.js TLS certificate object
177
189
  * @param {string} webId - WebID URI
190
+ * @param {object} [opts]
191
+ * @param {number} [opts.timeout] - profile fetch deadline in ms (tests)
178
192
  * @returns {Promise<boolean>} True if certificate matches profile
179
193
  */
180
- export async function verifyWebIdTls(certificate, webId) {
194
+ export async function verifyWebIdTls(certificate, webId, { timeout } = {}) {
181
195
  if (!certificate.modulus || !certificate.exponent) {
182
196
  throw new Error('Certificate missing modulus or exponent');
183
197
  }
@@ -195,7 +209,7 @@ export async function verifyWebIdTls(certificate, webId) {
195
209
  }
196
210
 
197
211
  try {
198
- const profileKeys = await fetchProfileKeys(webId);
212
+ const profileKeys = await fetchProfileKeys(webId, { timeout });
199
213
 
200
214
  // Check if any key matches
201
215
  const verified = profileKeys.some(key =>
package/src/config.js CHANGED
@@ -49,6 +49,9 @@ export const defaults = {
49
49
  mashlibCdn: false,
50
50
  mashlibVersion: '2.0.0',
51
51
  mashlibModule: false,
52
+ // Pane module URLs the data browser loads at start-up (#652):
53
+ // an array, or a comma-separated string. Empty: off.
54
+ panes: null,
52
55
 
53
56
  // Git HTTP backend
54
57
  git: false,
@@ -169,6 +172,7 @@ const envMap = {
169
172
  JSS_MASHLIB_CDN: 'mashlibCdn',
170
173
  JSS_MASHLIB_VERSION: 'mashlibVersion',
171
174
  JSS_MASHLIB_MODULE: 'mashlibModule',
175
+ JSS_PANES: 'panes',
172
176
  JSS_GIT: 'git',
173
177
  JSS_CORS_PROXY: 'corsProxy',
174
178
  JSS_CORS_PROXY_MAX_BYTES: 'corsProxyMaxBytes',
@@ -317,7 +317,7 @@ export async function handleGet(request, reply) {
317
317
  : generateDatabrowserHtml(
318
318
  resourceUrl,
319
319
  request.mashlibCdn ? request.mashlibVersion : null,
320
- { embedJsonLd }
320
+ { embedJsonLd, panes: request.panes }
321
321
  );
322
322
  const headers = getAllHeaders({
323
323
  isContainer: true,
@@ -454,7 +454,7 @@ export async function handleGet(request, reply) {
454
454
  : generateDatabrowserHtml(
455
455
  resourceUrl,
456
456
  request.mashlibCdn ? request.mashlibVersion : null,
457
- { embedJsonLd }
457
+ { embedJsonLd, panes: request.panes }
458
458
  );
459
459
  const headers = getAllHeaders({
460
460
  isContainer: false,