javascript-solid-server 0.0.206 → 0.0.208

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/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  [![npm version](https://img.shields.io/npm/v/javascript-solid-server)](https://www.npmjs.com/package/javascript-solid-server)
4
4
 
5
- A minimal, fast, JSON-LD native Solid server.
5
+ A minimal, fast, JSON-LD native Solid server for the agentic web.
6
6
 
7
7
  **[Documentation](https://javascriptsolidserver.github.io/docs/)** | **[GitHub](https://github.com/JavaScriptSolidServer/JavaScriptSolidServer)**
8
8
 
@@ -18,6 +18,7 @@ A minimal, fast, JSON-LD native Solid server.
18
18
  - **JSON-LD Native** — Stores and serves JSON-LD by default, Turtle via `--conneg`
19
19
  - **Web Access Control** — `.acl` file-based authorization
20
20
  - **Solid-OIDC** — Built-in Identity Provider with DPoP, passkeys, Schnorr SSO
21
+ - **Programmatic Auth** — `POST /idp/credentials` issues tokens from email/password; agents and headless clients authenticate with no browser flow
21
22
  - **WebSocket Notifications** — Real-time updates (solid-0.1 protocol)
22
23
  - **Content Negotiation** — Turtle ↔ JSON-LD conversion (optional)
23
24
  - **Multi-user Pods** — Path-based (`/alice/`) or subdomain-based (`alice.example.com`)
package/bin/jss.js CHANGED
@@ -112,7 +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
+ .option('--body-limit <size>', 'Maximum request body size, e.g. 100MB or 1GB (default 20MB). Raise to accept larger `git push`; lower for tighter memory-DoS protection.')
116
116
  .option('--nostr', 'Enable Nostr relay')
117
117
  .option('--no-nostr', 'Disable Nostr relay')
118
118
  .option('--nostr-path <path>', 'Nostr relay WebSocket path (default: /relay)')
@@ -190,6 +190,10 @@ program
190
190
  const server = createServer({
191
191
  port: config.port,
192
192
  host: config.host,
193
+ // Wire the parsed --body-limit / JSS_BODY_LIMIT value through —
194
+ // omitting it here silently pinned every CLI-started server to
195
+ // the 10MB default and made the #474 knob dead wiring (#561).
196
+ bodyLimit: config.bodyLimit,
193
197
  logger: config.logger,
194
198
  conneg: config.conneg,
195
199
  notifications: config.notifications,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "javascript-solid-server",
3
- "version": "0.0.206",
3
+ "version": "0.0.208",
4
4
  "description": "A minimal, fast Solid server",
5
5
  "main": "src/index.js",
6
6
  "type": "module",
@@ -52,7 +52,12 @@
52
52
  "decentralized",
53
53
  "activitypub",
54
54
  "fediverse",
55
- "nostr"
55
+ "nostr",
56
+ "json-ld",
57
+ "webid",
58
+ "mcp",
59
+ "agent",
60
+ "agentic"
56
61
  ],
57
62
  "license": "AGPL-3.0-only",
58
63
  "optionalDependencies": {
package/src/config.js CHANGED
@@ -20,11 +20,12 @@ export const defaults = {
20
20
  host: '0.0.0.0',
21
21
  root: './data',
22
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,
23
+ // via CLI / config file, e.g. "100MB"). 20 MiB default (#563) — a
24
+ // generous out-of-the-box limit for common workloads (larger `git
25
+ // push`, media uploads, bigger RDF documents). Raise via --body-limit
26
+ // / JSS_BODY_LIMIT for established app repos (#474); lower it for
27
+ // tighter memory-DoS protection.
28
+ bodyLimit: 20 * 1024 * 1024,
28
29
 
29
30
  // SSL
30
31
  sslKey: null,
@@ -167,16 +167,18 @@ function tryAutoInitRepo(repoAbs, log) {
167
167
 
168
168
  // CORS headers for git responses. Single source of truth — used by the
169
169
  // success path (Fastify reply on the OPTIONS preflight, raw stream on
170
- // http-backend output) and by every 4xx early-return. Without these,
171
- // browser-based git clients (e.g. jss.live/git/) see a generic
172
- // CORS/network error instead of the actual status, undermining #371.
170
+ // http-backend output), by every 4xx early-return in this module, and
171
+ // by the WAC preHandler's 401/402/403 returns in src/server.js (#548).
172
+ // Without these, browser-based git clients (e.g. jss.live/git/) see a
173
+ // generic CORS/network error instead of the actual status,
174
+ // undermining #371.
173
175
  const GIT_CORS_HEADERS = {
174
176
  'Access-Control-Allow-Origin': '*',
175
177
  'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
176
178
  'Access-Control-Allow-Headers': 'Content-Type, Authorization, Git-Protocol',
177
179
  };
178
180
 
179
- function setGitCorsHeaders(reply) {
181
+ export function setGitCorsHeaders(reply) {
180
182
  for (const [k, v] of Object.entries(GIT_CORS_HEADERS)) {
181
183
  reply.header(k, v);
182
184
  }
@@ -277,7 +279,15 @@ export async function handleGit(request, reply) {
277
279
  CONTENT_TYPE: request.headers['content-type'] || '',
278
280
  QUERY_STRING: queryString,
279
281
  REMOTE_USER: request.webId || '', // Pass authenticated user
280
- CONTENT_LENGTH: request.headers['content-length'] || '0',
282
+ // Use the buffered body's real length, not the Content-Length header:
283
+ // git sends packs larger than http.postBuffer (1 MiB default) with
284
+ // Transfer-Encoding: chunked and NO Content-Length, so the header
285
+ // fallback told http-backend "0 bytes" and receive-pack died with
286
+ // "the remote end hung up unexpectedly" on any push > 1 MiB (#561).
287
+ // Fastify has already buffered the full body either way.
288
+ CONTENT_LENGTH: request.body?.length
289
+ ? String(request.body.length)
290
+ : (request.headers['content-length'] || '0'),
281
291
  };
282
292
 
283
293
  // For regular repositories, set GIT_DIR
@@ -622,11 +622,163 @@ export async function handleGet(request, reply) {
622
622
  return reply.send(content);
623
623
  }
624
624
 
625
+ // Cap on how many bytes HEAD will FULLY read to decide a content type.
626
+ // GET reads the whole file regardless (it has to send the body anyway),
627
+ // but a HEAD on a multi-GB file must not slurp it into memory just to
628
+ // report a header. Above the cap, HEAD degrades gracefully per-case
629
+ // (see negotiateHeadFileContentType) instead of reading. Bounded
630
+ // first-bytes sniffs (HEAD_SNIFF_CHUNK_BYTES via a ranged read) are
631
+ // allowed at ANY size — they cost O(1).
632
+ const HEAD_FULL_READ_MAX_BYTES = 1024 * 1024;
633
+ const HEAD_SNIFF_CHUNK_BYTES = 1024;
634
+
635
+ // Read the first `bytes` of a file via a ranged stream — O(1) cost
636
+ // regardless of file size. Used by HEAD to run GET's "does it look
637
+ // like HTML?" sniffs without reading whole files.
638
+ function readFirstBytes(storagePath, bytes) {
639
+ return new Promise((resolve) => {
640
+ const result = storage.createReadStream(storagePath, { start: 0, end: bytes - 1 });
641
+ if (!result) return resolve(null);
642
+ const chunks = [];
643
+ result.stream.on('data', (c) => chunks.push(c));
644
+ result.stream.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
645
+ result.stream.on('error', () => resolve(null));
646
+ });
647
+ }
648
+
649
+ /**
650
+ * Mirror handleGet's content-type decision for a FILE so HEAD emits the
651
+ * same Content-Type a GET with the same Accept header would (#552 —
652
+ * RFC 9110 §9.3.2: HEAD should send the same header fields as GET).
653
+ *
654
+ * GET's decision depends on file CONTENT in three places — the
655
+ * HTML-data-island sniff, the JSON-parse-success gate before conneg
656
+ * conversion, and the extensionless-file HTML sniff — so this may read
657
+ * the file, but only when the stored type makes content relevant and
658
+ * the file is within HEAD_FULL_READ_MAX_BYTES.
659
+ *
660
+ * Returns `{ contentType, converted }`. `converted: true` means GET
661
+ * would RE-SERIALIZE the body (Turtle conversion, or JSON-LD
662
+ * re-serialization through fromJsonLd) — its Content-Length would NOT
663
+ * be the on-disk size, so HEAD must omit Content-Length rather than
664
+ * claim stats.size for a body GET never sends. The extensionless HTML
665
+ * sniff only relabels the bytes (served as-is), so it is NOT a
666
+ * conversion.
667
+ *
668
+ * Large files (> HEAD_FULL_READ_MAX_BYTES) degrade per-case instead of
669
+ * being read in full:
670
+ * - RDF-stored: return the negotiated type WITHOUT the parse gate
671
+ * (optimistic). The gate only mirrors GET's corrupt-file fallback;
672
+ * a corrupt >1 MiB RDF document is far rarer than a valid one, so
673
+ * optimism keeps parity for the common case and confines the
674
+ * divergence to that corner.
675
+ * - HTML-looking content (any stored type) + Turtle-preferring
676
+ * Accept: stay at the stored type (conservative) — the data
677
+ * island can sit anywhere in the file, so its presence can't be
678
+ * checked without the full read this cap exists to avoid.
679
+ * - Extensionless: the HTML sniff only needs the first bytes, so it
680
+ * runs at ANY size via a bounded ranged read.
681
+ *
682
+ * Known residual divergences (deliberate, all need unusual documents):
683
+ * a parseable-but-unconvertible document (GET's fromJsonLd fails after
684
+ * JSON.parse succeeds → GET falls back to raw bytes), a corrupt
685
+ * >1 MiB RDF file (optimistic path above), and a >1 MiB HTML-looking
686
+ * file carrying a data island (conservative path above).
687
+ */
688
+ async function negotiateHeadFileContentType({ storagePath, urlPath, stats, acceptHeader, connegEnabled }) {
689
+ const storedContentType = getContentType(storagePath);
690
+ const fitsFullRead = stats.size <= HEAD_FULL_READ_MAX_BYTES;
691
+
692
+ if (connegEnabled) {
693
+ // Same negotiation as handleGet's file branch (#325 q-aware).
694
+ const negotiated = selectContentType(acceptHeader, true);
695
+ const wantsTurtle = urlPath.endsWith('.ttl')
696
+ || negotiated === RDF_TYPES.TURTLE
697
+ || negotiated === RDF_TYPES.N3
698
+ || negotiated === 'application/n-triples';
699
+
700
+ if (isRdfContentType(storedContentType)) {
701
+ const targetType = wantsTurtle ? 'text/turtle' : selectContentType(acceptHeader, connegEnabled);
702
+ if (!fitsFullRead) {
703
+ // Optimistic large-file path — see docstring.
704
+ return { contentType: targetType, converted: true };
705
+ }
706
+ const content = await storage.read(storagePath);
707
+ if (content !== null) {
708
+ try {
709
+ JSON.parse(content.toString()); // GET only converts when the body parses
710
+ return { contentType: targetType, converted: true };
711
+ } catch { /* not valid JSON-LD → GET serves as-is; fall through */ }
712
+ }
713
+ return { contentType: storedContentType, converted: false };
714
+ }
715
+
716
+ // GET's data-island branch is gated on CONTENT ONLY — any file
717
+ // whose body starts with <!DOCTYPE/<html gets the island→Turtle
718
+ // conversion, regardless of stored type (.html, extensionless,
719
+ // .xhtml, …). Mirror that: a 1 KiB ranged sniff decides HTML-ness
720
+ // for O(1) cost on any file, and only HTML-looking content pays
721
+ // the full read for the island check.
722
+ if (wantsTurtle && fitsFullRead) {
723
+ const head = await readFirstBytes(storagePath, HEAD_SNIFF_CHUNK_BYTES);
724
+ const headTrimmed = head === null ? '' : head.trimStart();
725
+ let looksHtml = headTrimmed.startsWith('<!DOCTYPE') || headTrimmed.startsWith('<html');
726
+ let contentStr = null;
727
+ if (!looksHtml && head !== null && headTrimmed === '' && stats.size > HEAD_SNIFF_CHUNK_BYTES) {
728
+ // The chunk was entirely whitespace and the file continues past
729
+ // it — GET trims the FULL body, so the HTML marker may sit
730
+ // beyond the chunk. The file already fits the full-read budget;
731
+ // read it and decide exactly like GET does.
732
+ const content = await storage.read(storagePath);
733
+ if (content !== null) {
734
+ contentStr = content.toString();
735
+ const trimmed = contentStr.trimStart();
736
+ looksHtml = trimmed.startsWith('<!DOCTYPE') || trimmed.startsWith('<html');
737
+ }
738
+ }
739
+ if (looksHtml) {
740
+ // GET converts an HTML data island to Turtle only when the
741
+ // island exists AND its JSON parses; otherwise it serves the
742
+ // document as-is.
743
+ if (contentStr === null) {
744
+ const content = await storage.read(storagePath);
745
+ contentStr = content === null ? null : content.toString();
746
+ }
747
+ if (contentStr !== null) {
748
+ const jsonLdMatch = contentStr.match(/<script\s+type=["']application\/ld\+json["']\s*>([\s\S]*?)<\/script>/i);
749
+ if (jsonLdMatch) {
750
+ try {
751
+ JSON.parse(jsonLdMatch[1]);
752
+ return { contentType: 'text/turtle', converted: true };
753
+ } catch { /* unparseable island → GET serves as-is; fall through */ }
754
+ }
755
+ }
756
+ }
757
+ // No island conversion → fall through to the as-is path below
758
+ // (HTML-looking extensionless files still get the relabel sniff).
759
+ }
760
+ }
761
+
762
+ // As-is path: GET sniffs extensionless files for HTML by content.
763
+ // Only the first bytes matter, so the sniff runs at any file size
764
+ // via a bounded ranged read. Relabel only — no conversion.
765
+ if (storedContentType === 'application/octet-stream') {
766
+ const head = await readFirstBytes(storagePath, HEAD_SNIFF_CHUNK_BYTES);
767
+ if (head !== null) {
768
+ const t = head.trimStart();
769
+ if (t.startsWith('<!DOCTYPE') || t.startsWith('<html')) {
770
+ return { contentType: 'text/html', converted: false };
771
+ }
772
+ }
773
+ }
774
+ return { contentType: storedContentType, converted: false };
775
+ }
776
+
625
777
  /**
626
778
  * Handle HEAD request
627
779
  */
628
780
  export async function handleHead(request, reply) {
629
- const { storagePath, resourceUrl } = getRequestPaths(request);
781
+ const { urlPath, storagePath, resourceUrl } = getRequestPaths(request);
630
782
  const stats = await storage.stat(storagePath);
631
783
 
632
784
  if (!stats) {
@@ -687,7 +839,9 @@ export async function handleHead(request, reply) {
687
839
  const { willServeMashlib, effectiveEtag } = getMashlibEtag(request, stats, storagePath);
688
840
  headEtag = effectiveEtag;
689
841
  isMashlibResponse = willServeMashlib;
690
- contentType = willServeMashlib ? 'text/html' : getContentType(storagePath);
842
+ // contentType for files is negotiated AFTER the If-None-Match check
843
+ // below — negotiation may read the file (#552), and GET 304s files
844
+ // before any read, so HEAD must not pay I/O a 304 will discard.
691
845
  }
692
846
 
693
847
  // Check If-None-Match using the final ETag (#456)
@@ -701,6 +855,26 @@ export async function handleHead(request, reply) {
701
855
  }
702
856
  }
703
857
 
858
+ let negotiationConverted = false;
859
+ if (!stats.isDirectory) {
860
+ // Mirror GET's content-type for files — including the negotiated
861
+ // Turtle/JSON-LD forms and the extensionless HTML sniff — so HEAD
862
+ // and GET agree (#552, RFC 9110 §9.3.2).
863
+ if (isMashlibResponse) {
864
+ contentType = 'text/html';
865
+ } else {
866
+ const negotiation = await negotiateHeadFileContentType({
867
+ storagePath,
868
+ urlPath,
869
+ stats,
870
+ acceptHeader: request.headers.accept || '',
871
+ connegEnabled,
872
+ });
873
+ contentType = negotiation.contentType;
874
+ negotiationConverted = negotiation.converted;
875
+ }
876
+ }
877
+
704
878
  const headers = getAllHeaders({
705
879
  isContainer: stats.isDirectory,
706
880
  etag: headEtag,
@@ -711,9 +885,19 @@ export async function handleHead(request, reply) {
711
885
  mashlibEnabled: request.mashlibEnabled
712
886
  });
713
887
 
888
+ // Mirror GET's Cache-Control for RDF responses (#552 header parity).
889
+ // GET applies RDF_CACHE_CONTROL uniformly wherever the response
890
+ // content type is RDF — container listings (Turtle/JSON-LD) and
891
+ // files (converted or as-is) alike; HTML responses don't get it.
892
+ if (isRdfContentType(contentType)) {
893
+ headers['Cache-Control'] = RDF_CACHE_CONTROL;
894
+ }
895
+
714
896
  // Content-Length: only set when the file size matches the response body.
715
- // Mashlib HTML and containers are dynamically generated.
716
- if (!stats.isDirectory && !isMashlibResponse) {
897
+ // Mashlib HTML and containers are dynamically generated, and a
898
+ // conneg-converted body (Turtle / re-serialized JSON-LD, #552) has a
899
+ // different length than the on-disk file — omit rather than lie.
900
+ if (!stats.isDirectory && !isMashlibResponse && !negotiationConverted) {
717
901
  headers['Content-Length'] = stats.size;
718
902
  }
719
903
 
package/src/idp/index.js CHANGED
@@ -219,7 +219,11 @@ export async function idpPlugin(fastify, options) {
219
219
 
220
220
  // /.well-known/openid-configuration
221
221
  fastify.get('/.well-known/openid-configuration', async (request, reply) => {
222
- // Ensure issuer has trailing slash for CTH compatibility
222
+ // Ensure issuer has trailing slash for CTH compatibility. Must stay
223
+ // in sync with createProvider's normalization (src/idp/provider.js)
224
+ // — the RFC 9207 `iss` authorization-response parameter and token
225
+ // `iss` claims come from the provider's issuer, and strict clients
226
+ // byte-compare them against this discovery field. See #524.
223
227
  const normalizedIssuer = issuer.endsWith('/') ? issuer : issuer + '/';
224
228
  // Base URL without trailing slash for building endpoint URLs
225
229
  const baseUrl = issuer.endsWith('/') ? issuer.slice(0, -1) : issuer;
@@ -95,7 +95,7 @@ export async function handleInteractionGet(request, reply, provider) {
95
95
 
96
96
  // If we need login
97
97
  if (prompt.name === 'login') {
98
- return reply.type('text/html').send(loginPage(uid, params.client_id, interaction.lastError));
98
+ return reply.type('text/html').send(loginPage(uid, params.client_id, interaction.lastSubmission?.lastError));
99
99
  }
100
100
 
101
101
  // If we need consent
@@ -173,9 +173,17 @@ export async function handleLogin(request, reply, provider) {
173
173
  return reply.code(404).type('text/html').send(errorPage('Session expired', 'Please try logging in again.'));
174
174
  }
175
175
 
176
- // Validate input
176
+ // Validate input.
177
+ //
178
+ // The error must live inside `lastSubmission` — oidc-provider's
179
+ // Interaction.save() persists ONLY the fields in the model's
180
+ // IN_PAYLOAD list (lib/models/interaction.js), and `lastSubmission`
181
+ // is the designated slot for form re-render state. A bare
182
+ // `interaction.lastError = …` survives in memory but is silently
183
+ // DROPPED on save, so the redirected GET re-rendered the form with
184
+ // no error and users retried blind (#514).
177
185
  if (!identifier || !password) {
178
- interaction.lastError = 'Username and password are required';
186
+ interaction.lastSubmission = { lastError: 'Username and password are required' };
179
187
  await interaction.save(interaction.exp - Math.floor(Date.now() / 1000));
180
188
  return reply.redirect(`/idp/interaction/${uid}`);
181
189
  }
@@ -183,7 +191,8 @@ export async function handleLogin(request, reply, provider) {
183
191
  // Authenticate
184
192
  const account = await authenticate(identifier, password);
185
193
  if (!account) {
186
- interaction.lastError = 'Invalid username or password';
194
+ // See the IN_PAYLOAD note above — must ride in lastSubmission.
195
+ interaction.lastSubmission = { lastError: 'Invalid username or password' };
187
196
  await interaction.save(interaction.exp - Math.floor(Date.now() / 1000));
188
197
  return reply.redirect(`/idp/interaction/${uid}`);
189
198
  }
@@ -404,7 +413,7 @@ export async function handleSwitchAccount(request, reply, provider) {
404
413
  interaction.session = undefined;
405
414
  interaction.result = undefined;
406
415
  interaction.prompt = { name: 'login', reasons: ['no_session'], details: {} };
407
- interaction.lastError = undefined;
416
+ interaction.lastSubmission = undefined;
408
417
  const ttl = Math.max(1, interaction.exp - Math.floor(Date.now() / 1000));
409
418
  await interaction.save(ttl);
410
419
 
@@ -91,6 +91,17 @@ async function fetchClientDocument(clientId) {
91
91
  * @returns {Promise<Provider>} - Configured oidc-provider instance
92
92
  */
93
93
  export async function createProvider(issuer) {
94
+ // Normalize to the trailing-slash form — the SAME normalization the
95
+ // discovery handler applies to the `issuer` field of
96
+ // /.well-known/openid-configuration (src/idp/index.js, "Ensure
97
+ // issuer has trailing slash"). The provider's issuer feeds the
98
+ // RFC 9207 `iss` authorization-response parameter and the `iss`
99
+ // claim in issued tokens; RFC 9207 requires the param to be
100
+ // byte-identical to the advertised issuer, and strict clients
101
+ // (e.g. solid-oidc's handleRedirectFromLogin) reject the callback
102
+ // on mismatch — sign-in silently bounces before the token request
103
+ // ever fires. Keep the two normalizations in sync. See #524.
104
+ issuer = issuer.endsWith('/') ? issuer : issuer + '/';
94
105
  const jwks = await getJwks();
95
106
  const cookieKeys = await getCookieKeys();
96
107
 
package/src/idp/views.js CHANGED
@@ -265,12 +265,26 @@ export function loginPage(uid, clientId, error = null, passkeyEnabled = true, sc
265
265
  var INTERACTION_UID = '${safeUid}';
266
266
 
267
267
  async function loginWithPasskey() {
268
+ // Passkeys require WebAuthn + a secure context. Stale Android
269
+ // System WebViews (common on de-Googled phones, #556) and plain
270
+ // http origins lack it. Detect up front and steer the user to the
271
+ // password form right below instead of failing deep in the
272
+ // ceremony with a cryptic error.
273
+ if (!window.isSecureContext || !window.PublicKeyCredential ||
274
+ !(navigator.credentials && navigator.credentials.get)) {
275
+ alert('Passkeys aren\\'t available in this browser. Please sign in with your username and password below.');
276
+ return;
277
+ }
268
278
  try {
269
- // Get authentication options
279
+ // Get authentication options. No client-side correlation id is
280
+ // sent — the server mints the challengeKey (always-available
281
+ // Node crypto) and returns it; we echo options.challengeKey on
282
+ // verify. This deliberately avoids a browser crypto.randomUUID
283
+ // call that old WebViews lack (#556).
270
284
  const optionsRes = await fetch('/idp/passkey/login/options', {
271
285
  method: 'POST',
272
286
  headers: { 'Content-Type': 'application/json' },
273
- body: JSON.stringify({ visitorId: crypto.randomUUID() })
287
+ body: JSON.stringify({})
274
288
  });
275
289
  const options = await optionsRes.json();
276
290
  if (options.error) {
@@ -1032,6 +1046,15 @@ export function passkeyPromptPage(uid, accountId) {
1032
1046
  var PASSKEY_ICON = '${passkeyIconEscaped}';
1033
1047
 
1034
1048
  async function registerPasskey() {
1049
+ // Same WebAuthn / secure-context gate as the login page (#556):
1050
+ // on a stale WebView the create() ceremony would fail cryptically.
1051
+ // Steer to "Skip for now" instead of disabling the button on a
1052
+ // path that can't succeed.
1053
+ if (!window.isSecureContext || !window.PublicKeyCredential ||
1054
+ !(navigator.credentials && navigator.credentials.create)) {
1055
+ alert('Passkeys aren\\'t available in this browser. Tap "Skip for now" to continue.');
1056
+ return;
1057
+ }
1035
1058
  const btn = document.getElementById('addBtn');
1036
1059
  btn.disabled = true;
1037
1060
  btn.textContent = 'Setting up...';
package/src/server.js CHANGED
@@ -17,7 +17,7 @@ import { idpPlugin } from './idp/index.js';
17
17
  // below so non-IdP deployments don't pull in the IdP accounts module
18
18
  // (bcryptjs etc.) just to register Fastify routes. The same lazy-load
19
19
  // pattern is used in src/auth/nostr.js for the NIP-98 verifier.
20
- import { isGitRequest, isGitWriteOperation, handleGit } from './handlers/git.js';
20
+ import { isGitRequest, isGitWriteOperation, handleGit, setGitCorsHeaders } from './handlers/git.js';
21
21
  import { handleCorsProxy, isCorsProxyRequest, setProxyCorsHeaders } from './handlers/cors-proxy.js';
22
22
  import { AccessMode } from './wac/parser.js';
23
23
  import { registerNostrRelay } from './nostr/relay.js';
@@ -187,8 +187,8 @@ export function createServer(options = {}) {
187
187
  // already coerced by parseEnvValue) pass through unchanged; strings
188
188
  // ("100MB" from CLI / config files) go through parseSize for
189
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.
190
+ // calls `.match` on its input and would throw on a raw number. Falls
191
+ // back to defaults.bodyLimit (20 MiB, #563) when unset. See #474.
192
192
  const bodyLimit = options.bodyLimit == null
193
193
  ? defaults.bodyLimit
194
194
  : (typeof options.bodyLimit === 'number' ? options.bodyLimit : parseSize(options.bodyLimit));
@@ -533,11 +533,20 @@ export function createServer(options = {}) {
533
533
  request.wacAllow = wacAllow;
534
534
 
535
535
  if (paymentRequired) {
536
+ // Git CORS headers on the early return — same reasoning as the
537
+ // 401/403 below: a browser git client must see the 402, not a
538
+ // generic CORS/network error. See #548 / #371.
539
+ setGitCorsHeaders(reply);
536
540
  return reply.code(402).send({ type: 'PaymentRequired', ...paymentRequired });
537
541
  }
538
542
 
539
543
  if (!authorized) {
540
544
  const message = needsWrite ? 'Write access required for push' : 'Read access required for clone';
545
+ // Without the git CORS headers, browser-based git clients (e.g.
546
+ // jss.live/git/) hitting an auth-gated repo saw a generic CORS
547
+ // error instead of this 401/403 — the same failure mode #371
548
+ // fixed inside handleGit. See #548.
549
+ setGitCorsHeaders(reply);
541
550
  reply.header('WAC-Allow', wacAllow);
542
551
  if (!webId) {
543
552
  // No authentication - request Basic auth for git clients
@@ -10,13 +10,70 @@
10
10
  * Public URL: https://your.pod/tunnel/{name}/path
11
11
  *
12
12
  * Tunnel client protocol (JSON over WebSocket):
13
- * → { type: "register", name: "myapp" }
14
- * ← { type: "registered", name: "myapp", url: "/tunnel/myapp/" }
13
+ * → { type: "register", name: "myapp", passthrough?: true }
14
+ * ← { type: "registered", name: "myapp", url: "/tunnel/myapp/", passthrough: true|false }
15
15
  * ← { type: "request", id: "<uuid>", method: "GET", path: "/api/hello", headers: {...}, body: "..." }
16
16
  * → { type: "response", id: "<uuid>", status: 200, headers: {...}, body: "..." }
17
17
  * ← { type: "error", message: "..." }
18
+ *
19
+ * Credential passthrough (#530): by default the proxy strips
20
+ * `Cookie` / `Authorization` from inbound requests and `Set-Cookie`
21
+ * from outbound responses, so a tunnel exposes PUBLIC content only.
22
+ * A client may opt in per-registration with `passthrough: true`,
23
+ * which forwards those three headers and makes authenticated access
24
+ * (bearer/DPoP, cookie sessions) work through the tunnel. Opting in
25
+ * means visitor credentials bound for the tunnelled service are
26
+ * handed to the registered client — safe exactly when the registrant
27
+ * owns the tunnelled service (the normal "my own pod through my own
28
+ * relay" case), which is why it is per-tunnel, owner-asserted, and
29
+ * off by default. `Proxy-Authorization` is always stripped — it is
30
+ * addressed to this relay, never to the tunnelled service.
31
+ *
32
+ * Even with passthrough on, the relay's OWN IdP session/interaction
33
+ * cookies are stripped from the forwarded Cookie header. oidc-provider
34
+ * sets them with `path: '/'`, so a browser attaches them to
35
+ * `/tunnel/...` requests too — but they authenticate the visitor to
36
+ * THE RELAY, not to the tunnelled service. Forwarding them would let a
37
+ * tunnel client capture a visitor's relay `_session` and replay it
38
+ * against the relay's `/idp/*` endpoints (session hijack). See #530.
18
39
  */
19
40
 
41
+ // Cookie names reserved by the relay's own oidc-provider IdP
42
+ // (`_session`, `_session.sig`, `_session.legacy[.sig]`, `_interaction`,
43
+ // `_interaction.sig`, `_interaction_resume[.sig]`). They share two
44
+ // prefixes; we match the prefix plus a `.`/`_` boundary so a tunnelled
45
+ // service's unrelated cookie (e.g. `_sessionsLeft`) isn't stripped.
46
+ const RELAY_COOKIE_PREFIXES = ['_session', '_interaction'];
47
+
48
+ function isRelayCookieName(name) {
49
+ return RELAY_COOKIE_PREFIXES.some(
50
+ (p) => name === p || name.startsWith(`${p}.`) || name.startsWith(`${p}_`),
51
+ );
52
+ }
53
+
54
+ /**
55
+ * Remove the relay's own IdP cookies from a forwarded Cookie header,
56
+ * keeping the visitor's cookies bound for the tunnelled service.
57
+ * Returns '' when nothing remains (caller then drops the header).
58
+ */
59
+ function stripRelayCookies(cookieHeader) {
60
+ // Node folds duplicate Cookie headers into one string, but Fastify
61
+ // can surface string[] — normalize so passthrough doesn't drop every
62
+ // cookie when an array arrives. Cookies join with '; '.
63
+ const raw = Array.isArray(cookieHeader) ? cookieHeader.join('; ') : cookieHeader;
64
+ if (typeof raw !== 'string') return '';
65
+ return raw
66
+ .split(';')
67
+ .map((s) => s.trim())
68
+ .filter(Boolean)
69
+ .filter((pair) => {
70
+ const eq = pair.indexOf('=');
71
+ const name = (eq === -1 ? pair : pair.slice(0, eq)).trim();
72
+ return !isRelayCookieName(name);
73
+ })
74
+ .join('; ');
75
+ }
76
+
20
77
  import websocket from '@fastify/websocket';
21
78
  import { getWebIdFromRequestAsync } from '../auth/token.js';
22
79
  import { randomUUID } from 'crypto';
@@ -109,9 +166,15 @@ export async function tunnelPlugin(fastify, options = {}) {
109
166
  existing.socket.close();
110
167
  }
111
168
 
169
+ // Per-tunnel credential passthrough (#530) — strict boolean so a
170
+ // truthy-but-wrong value ("false", 1) can't silently enable
171
+ // credential forwarding. Echoed in the ack so the client knows
172
+ // which mode the relay actually applied.
173
+ const passthrough = msg.passthrough === true;
174
+
112
175
  tunnelName = name;
113
- tunnels.set(name, { socket, webId });
114
- socket.send(JSON.stringify({ type: 'registered', name, url: `/tunnel/${name}/` }));
176
+ tunnels.set(name, { socket, webId, passthrough });
177
+ socket.send(JSON.stringify({ type: 'registered', name, url: `/tunnel/${name}/`, passthrough }));
115
178
 
116
179
  } else if (msg.type === 'response') {
117
180
  // Tunnel client returning an HTTP response
@@ -167,12 +230,27 @@ export async function tunnelPlugin(fastify, options = {}) {
167
230
  tunnelReq.method = request.method;
168
231
  tunnelReq.path = fullPath;
169
232
  tunnelReq.headers = Object.create(null);
170
- // Forward relevant headers (skip hop-by-hop)
171
- const skipHeaders = new Set(['host', 'connection', 'upgrade', 'transfer-encoding', 'cookie', 'authorization', 'proxy-authorization']);
233
+ // Forward relevant headers. Hop-by-hop headers are always skipped;
234
+ // credentials (cookie / authorization) are skipped UNLESS the tunnel
235
+ // registered with passthrough (#530 — owner opted in to receive
236
+ // visitor credentials). Proxy-Authorization is always stripped: it
237
+ // is addressed to this relay, never to the tunnelled service.
238
+ const skipHeaders = new Set(['host', 'connection', 'upgrade', 'transfer-encoding', 'proxy-authorization']);
239
+ if (!tunnel.passthrough) {
240
+ skipHeaders.add('cookie');
241
+ skipHeaders.add('authorization');
242
+ }
172
243
  for (const [k, v] of Object.entries(request.headers)) {
173
- if (!skipHeaders.has(k.toLowerCase())) {
174
- tunnelReq.headers[k] = v;
244
+ const lower = k.toLowerCase();
245
+ if (skipHeaders.has(lower)) continue;
246
+ if (lower === 'cookie' && tunnel.passthrough) {
247
+ // Forward the visitor's cookies for the tunnelled service, but
248
+ // never the relay's own IdP session cookies (#530 security).
249
+ const filtered = stripRelayCookies(v);
250
+ if (filtered) tunnelReq.headers[k] = filtered;
251
+ continue;
175
252
  }
253
+ tunnelReq.headers[k] = v;
176
254
  }
177
255
  // Forward body if present
178
256
  if (request.body) {
@@ -201,8 +279,15 @@ export async function tunnelPlugin(fastify, options = {}) {
201
279
 
202
280
  const res = await responsePromise;
203
281
 
204
- // Set response headers
205
- const hopHeaders = new Set(['connection', 'transfer-encoding', 'keep-alive', 'set-cookie']);
282
+ // Set response headers. Set-Cookie is stripped by default so a
283
+ // tunnelled service can't set cookies on the relay's origin; with
284
+ // passthrough (#530) the owner opted in and session flows (e.g.
285
+ // OIDC login cookies) must survive the proxy. Fastify accepts an
286
+ // array value for set-cookie, which JSON serialization preserves.
287
+ const hopHeaders = new Set(['connection', 'transfer-encoding', 'keep-alive']);
288
+ if (!tunnel.passthrough) {
289
+ hopHeaders.add('set-cookie');
290
+ }
206
291
  for (const [k, v] of Object.entries(res.headers)) {
207
292
  if (!hopHeaders.has(k.toLowerCase())) {
208
293
  reply.header(k, v);