javascript-solid-server 0.0.224 → 0.0.226

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.
@@ -0,0 +1,38 @@
1
+ {
2
+ "permissions": {
3
+ "allow": [
4
+ "Bash(gh issue *)",
5
+ "WebFetch(domain:did-nostr.com)",
6
+ "WebFetch(domain:nostrcg.github.io)",
7
+ "Bash(node --test test/nostr-key-parity.test.js)",
8
+ "Bash(node --test test/nostr-cid-vm.test.js test/well-known-did-nostr.test.js test/keys-provision.test.js test/keys-provision-integration.test.js test/nostr-event.test.js test/well-known-nostr-json.test.js)",
9
+ "Bash(npm test *)",
10
+ "Bash(git checkout *)",
11
+ "Bash(git add *)",
12
+ "Bash(cd *)",
13
+ "Bash(git push *)",
14
+ "Bash(gh pr create --base gh-pages --title 'fix\\(nostr\\): reconcile JWK key path to accept both Y-parities \\(#571\\)' --body ' *)",
15
+ "Bash(gh pr create --repo JavaScriptSolidServer/JavaScriptSolidServer --base gh-pages --head issue-571-multikey-jwk-parity-consistency --title 'fix\\(nostr\\): reconcile JWK key path to accept both Y-parities \\(#571\\)' --body ' *)",
16
+ "Bash(gh pr *)",
17
+ "Bash(gh api *)",
18
+ "Bash(node --test test/nostr-key-parity.test.js test/nostr-cid-vm.test.js test/well-known-did-nostr.test.js)",
19
+ "Bash(git commit *)",
20
+ "Bash(git config *)",
21
+ "Bash(FILTER_BRANCH_SQUELCH_WARNING=1 git filter-branch -f --msg-filter 'grep -v -e \"^Co-Authored-By: Claude\" -e \"Generated with \\\\[Claude Code\\\\]\"' gh-pages..HEAD)",
22
+ "Bash(git fetch *)",
23
+ "Bash(git ls-remote *)",
24
+ "Bash(echo \"exit=$?\")",
25
+ "Bash(cd /home/melvin/.claude/projects/-home-melvin-remote-github-com-JavaScriptSolidServer-JavaScriptSolidServer/memory/)",
26
+ "Bash(cat MEMORY.md)",
27
+ "Bash(FILTER_BRANCH_SQUELCH_WARNING=1 git filter-branch -f --env-filter ' *)",
28
+ "Bash(git pull *)",
29
+ "Bash(git branch *)",
30
+ "Bash(git remote *)",
31
+ "Bash(node --check src/handlers/container.js)",
32
+ "Bash(node --test /tmp/claude-1000/-home-melvin-remote-github-com-JavaScriptSolidServer-JavaScriptSolidServer/47629faf-bc8f-4e26-9878-091c550812d5/scratchpad/repro.test.js)",
33
+ "Bash(node --test test/auth.test.js)",
34
+ "Bash(git stash *)",
35
+ "Bash(node --check src/wac/checker.js)"
36
+ ]
37
+ }
38
+ }
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.
@@ -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
@@ -372,6 +372,14 @@ built-in `/storage/` and `/db/` routes. Everything outside the declared
372
372
  prefixes keeps full WAC enforcement. Entries must start with `/` and be
373
373
  longer than `/`; anything else is ignored.
374
374
 
375
+ A path under an app prefix that the application did **not** register is a
376
+ 404 inside the app's namespace
377
+ ([#611](https://github.com/JavaScriptSolidServer/JavaScriptSolidServer/issues/611)):
378
+ the LDP handlers never read or write pod storage below an app path, since
379
+ WAC has already been skipped there. Files an app wants served from the pod
380
+ belong outside its prefix (for example `/public/apps/<name>/`), where WAC
381
+ applies.
382
+
375
383
  Because the WAC hook is also what populates `request.webId`, requests under
376
384
  an app path never carry it — don't rely on `request.webId` in app handlers.
377
385
  Resolve identity with the public accessor
package/docs/security.md CHANGED
@@ -43,6 +43,36 @@ Save this as `data/.acl` (replacing `your-domain.com` with your actual domain).
43
43
 
44
44
  See [Issue #32](https://github.com/JavaScriptSolidServer/JavaScriptSolidServer/issues/32) for background.
45
45
 
46
+ ### Dotfiles
47
+
48
+ Paths whose segments start with a dot are refused with `403` unless the
49
+ segment is one of the Solid-specific names (`.well-known`, `.acl`, `.meta`,
50
+ `.pods`, `.notifications`, `.account`). This keeps `.git/`, `.env`,
51
+ `.htpasswd` and similar files out of reach over HTTP even when they sit
52
+ inside a pod. Git smart-HTTP, the pay routes and app plugins mounted at a
53
+ dot prefix are allowed through on their own terms.
54
+
55
+ The check runs on the percent-decoded path, segment by segment, and the
56
+ storage lookup applies the same rule, so `%2Egit` is `.git` on both sides
57
+ and neither can be talked past the other (#639). A dot has to be literal
58
+ in the request: a segment that only starts with a dot after decoding is
59
+ refused even for the allowed names. A path that cannot be decoded, or that
60
+ hides a path separator behind `%2F`, is refused with `400` instead of
61
+ being passed on.
62
+
63
+ ### Conditional writes are atomic
64
+
65
+ `If-Match` and `If-None-Match` on PUT, DELETE and PATCH are checked and acted on as one
66
+ step. Writes to a resource are queued within the process and held under a lock file next
67
+ to the resource (`.<name>.lock`, never listed or served) across processes that share the
68
+ data directory. Two clients racing with the same, still valid, ETag get one `2xx` and one
69
+ `412`; the loser's write is never silently overwritten. A request that cannot take the lock
70
+ within 30 seconds gets `503` with `Retry-After: 1`.
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
+
46
76
  ## Subdomain Mode (XSS Protection)
47
77
 
48
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.224",
3
+ "version": "0.0.226",
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
  }
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 =>