javascript-solid-server 0.0.217 → 0.0.219

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.
@@ -417,19 +417,68 @@ Each entry:
417
417
  the app owns authentication below it (see the section above). Must start
418
418
  with `/`; invalid prefixes fail startup.
419
419
  - `config` — passed to the plugin verbatim as `api.config`.
420
- - `id` — optional stable identifier (defaults to a name derived from
421
- `module`); names the plugin's private data dir, so set it explicitly if
422
- you load two plugins whose specifiers reduce to the same name.
420
+ - `id` — optional stable identifier that names the plugin's private data
421
+ dir. Defaults to a name derived from `module`: the file's basename, or —
422
+ for a generic basename like `plugin.js`/`index.js` — its parent directory
423
+ (`relay/plugin.js` → `relay`), so the conventional `<name>/plugin.js`
424
+ layout yields distinct ids with none set. Set it explicitly only if two
425
+ specifiers still reduce to the same name.
423
426
 
424
427
  `activate(api)` receives: `api.fastify` (register routes here),
425
428
  `api.prefix`, `api.config`, `api.log`, `api.auth.getAgent(request)`
426
429
  (identity, as above), `api.storage.pluginDir()` (a private server-side
427
- directory under the data root, never served over HTTP), and
428
- `api.ws.route(path, (socket, request) => {})` for WebSocket endpoints —
430
+ directory under the data root, never served over HTTP),
431
+ `api.serverInfo()` → `{ baseUrl, protocol, host, port, listening }` (the
432
+ server's own origin, for minting absolute URLs and loopback calls — call
433
+ it lazily, e.g. per request: with `port: 0` the real port exists only once
434
+ the server is listening, and an explicit `idpIssuer` wins as `baseUrl`),
435
+ `api.plugins` → `[{ id, prefix, module }]` for every loaded entry (a
436
+ read-only, frozen boot-time snapshot, so a plugin can enumerate its
437
+ co-loaded siblings instead of being handed a copy of the operator's
438
+ plugins array — it includes the plugin itself, so consumers filter),
439
+ and `api.ws.route(path, (socket, request) => {})` for WebSocket endpoints —
429
440
  routed through the same upgrade path as the built-in realtime features, so
430
441
  plugins never attach their own `'upgrade'` listener. Return
431
442
  `{ deactivate }` to run teardown (state saves, timers) on server close.
432
443
 
444
+ A plugin whose protocol **pins absolute paths** outside its prefix can
445
+ claim them with `api.reservePath(path)`:
446
+
447
+ ```js
448
+ api.reservePath('/xrpc', { methods: ['GET', 'POST'] }); // fixed root — subtree, methods opted in
449
+ api.reservePath('/:user/did.json'); // pinned document — exact shape, read-only
450
+ ```
451
+
452
+ Both kinds are **read-only by default** (`GET`/`HEAD`/`OPTIONS`; widen with
453
+ `{ methods: [...] }`) — a reserved path is WAC-exempt and the LDP write
454
+ wildcards sit beneath it, so exempting a write method the plugin hasn't
455
+ implemented would let that write fall through to storage unauthenticated.
456
+ Literal reservations claim their whole subtree; parameterized reservations
457
+ (`:name` matches one segment) match only the exact path shape, since they
458
+ exist for pinned documents inside the pod's WAC-governed namespace. Claims
459
+ are cross-plugin: a second plugin reserving the same path fails the boot
460
+ naming both claimants. Registering routes on the reserved paths remains the
461
+ plugin's job via `api.fastify`.
462
+
463
+ To mount an **existing node-style app** — a `(req, res)` handler, a reverse
464
+ proxy, or a framework adapter — use `api.mountApp(handler, { prefix })`:
465
+
466
+ ```js
467
+ export async function activate(api) {
468
+ const app = createMyNodeApp();
469
+ await api.mountApp((req, res) => app.handle(req, res));
470
+ }
471
+ ```
472
+
473
+ `mountApp` bundles the four things a wrapped-app plugin needs and would
474
+ otherwise rediscover: the appPaths WAC exemption, a **scoped pass-through
475
+ content parser** (so the wrapped app receives an unconsumed body stream
476
+ instead of one Fastify already drained — the failure that hangs any
477
+ body-reading app), `reply.hijack()` so Fastify releases the response, and
478
+ registration on both the bare prefix and its subtree. It defaults to the
479
+ entry's `prefix`; pass `{ prefix }` to mount a second app elsewhere (that
480
+ prefix is WAC-exempted too).
481
+
433
482
  A plugin that fails to import or activate fails `listen()` loudly rather
434
483
  than booting a server silently missing an app.
435
484
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "javascript-solid-server",
3
- "version": "0.0.217",
3
+ "version": "0.0.219",
4
4
  "description": "A minimal, fast Solid server",
5
5
  "main": "src/index.js",
6
6
  "type": "module",
package/src/plugins.js CHANGED
@@ -19,6 +19,9 @@
19
19
  * api.log server logger
20
20
  * api.auth.getAgent(req) -> agent id string | null (#584)
21
21
  * api.storage.pluginDir() -> private server-side data dir for this plugin
22
+ * api.serverInfo() -> { baseUrl, protocol, host, port, listening } (#601)
23
+ * api.reservePath(path) claim + WAC-exempt a protocol-pinned path (#602)
24
+ * api.plugins -> [{ id, prefix, module }] of every loaded entry (#610)
22
25
  * api.ws.route(path, (socket, request) => {}) (#588)
23
26
  *
24
27
  * The entry's `prefix` is added to appPaths automatically (#582), so the
@@ -60,6 +63,59 @@ export function makePluginLog(base) {
60
63
  return { log: call('info'), info: call('info'), warn: call('warn'), error: call('error'), debug: call('debug') };
61
64
  }
62
65
 
66
+ /**
67
+ * Compile a parameterized reservation like '/:user/did.json' (#602) to a
68
+ * matcher. ':name' segments match one path segment; everything else is
69
+ * literal. Parameterized reservations match the exact path shape (plus an
70
+ * optional query string) — NOT a subtree — because they exist for pinned
71
+ * documents inside otherwise WAC-governed namespaces (did:web), where
72
+ * exempting a whole subtree would be a WAC bypass.
73
+ */
74
+ // Only a segment that is ENTIRELY ':name' is a parameter. '/:user.json'
75
+ // is literal (its own segment mixes a param sigil with literal text) —
76
+ // treating it as a wildcard would exempt a far broader set of URLs than
77
+ // the ':name'-per-segment contract promises.
78
+ const PARAM_SEGMENT = /^:[A-Za-z_][A-Za-z0-9_]*$/;
79
+
80
+ export function isParamPath(p) {
81
+ return p.split('/').some((seg) => PARAM_SEGMENT.test(seg));
82
+ }
83
+
84
+ export function compilePathPattern(p) {
85
+ const pattern = p
86
+ .split('/')
87
+ // Exclude '?' as well as '/': a param must be a single PATH segment,
88
+ // so it must not swallow the query delimiter — otherwise a query
89
+ // containing '/' (e.g. /alice?x=a/b) would fail to match a shape the
90
+ // path part satisfies, making matching depend on query contents.
91
+ .map((seg) => (PARAM_SEGMENT.test(seg)
92
+ ? '[^/?]+'
93
+ : seg.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')))
94
+ .join('/');
95
+ return new RegExp(`^${pattern}(?:\\?.*)?$`);
96
+ }
97
+
98
+ /**
99
+ * A literal reservation ('/xrpc') claims its whole subtree — the path
100
+ * itself, everything under it, and either plus a query string.
101
+ */
102
+ export function compileSubtreePattern(p) {
103
+ const esc = p.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
104
+ return new RegExp(`^${esc}(?:/.*)?(?:\\?.*)?$`);
105
+ }
106
+
107
+ // Collision key: two reservations conflict when they exempt the same
108
+ // URLs, so parameter NAMES don't matter — '/:user/did.json' and
109
+ // '/:acct/did.json' are the same claim. Each segment is tagged by TYPE
110
+ // (param vs literal) so a canonicalized param can't alias a literal
111
+ // segment that happens to be the placeholder text (e.g. a literal '/:/…').
112
+ // '\x00' never occurs in a real path, so it's a safe framing prefix.
113
+ export function reservationKey(p) {
114
+ return p.split('/')
115
+ .map((seg) => (PARAM_SEGMENT.test(seg) ? '\x00P' : `\x00L${seg}`))
116
+ .join('/');
117
+ }
118
+
63
119
  /** Same normalization appPaths applies: no trailing slash, must be '/x…'. */
64
120
  export function normalizePrefix(p) {
65
121
  if (typeof p !== 'string') return '';
@@ -67,11 +123,37 @@ export function normalizePrefix(p) {
67
123
  return trimmed.startsWith('/') && trimmed.length > 1 ? trimmed : '';
68
124
  }
69
125
 
126
+ // Basenames too generic to name a plugin: the near-universal
127
+ // '<name>/plugin.js' convention means every such file would derive the same
128
+ // id and collide. For these, the id falls back to the parent directory (#596).
129
+ const GENERIC_BASENAMES = new Set(['plugin', 'index']);
130
+
131
+ /**
132
+ * The distinguishing name of a plugin FILE: its basename, unless that is
133
+ * generic ('plugin.js', 'index.js'), in which case the immediate parent
134
+ * directory ('relay/plugin.js' -> 'relay'). The parent directory
135
+ * distinguishes '<name>/plugin.js' files from each other WITHOUT pinning the
136
+ * machine-specific path prefix (which would move the id — and pluginDir —
137
+ * with the deployment). Falls back to the basename when there is no usable
138
+ * parent (e.g. './plugin.js' at the cwd root). (#596)
139
+ */
140
+ export function fileStem(module) {
141
+ const withoutExt = path.basename(module).replace(/\.[cm]?js$/, '');
142
+ if (GENERIC_BASENAMES.has(withoutExt.toLowerCase())) {
143
+ const parent = path.basename(path.dirname(module));
144
+ // The parent directory name is returned AS-IS — a directory legitimately
145
+ // named 'foo.js' must stay 'foo.js', not be extension-stripped to 'foo'.
146
+ if (parent && parent !== '.' && parent !== '..') return parent;
147
+ }
148
+ return withoutExt;
149
+ }
150
+
70
151
  /**
71
152
  * Directory-safe plugin id: entry.id, or derived from the module spec.
72
153
  * Bare package specifiers keep their full path ('@scope/pkg/plugin.js' ->
73
154
  * 'scope-pkg-plugin') so same-named files in different packages don't
74
- * collide; file paths use the basename, because a machine-specific
155
+ * collide; file paths use the basename — or, for a generic basename, the
156
+ * parent directory (see fileStem, #596) — because a machine-specific
75
157
  * directory prefix must not name the plugin's data dir (the id — and with
76
158
  * it pluginDir — would change whenever the deployment moves). The loader
77
159
  * additionally rejects duplicate ids, so any residual collision fails the
@@ -79,12 +161,17 @@ export function normalizePrefix(p) {
79
161
  */
80
162
  export function pluginId(spec) {
81
163
  const module = String(spec.module);
82
- const raw = typeof spec.id === 'string' && spec.id
83
- ? spec.id
84
- : (module.startsWith('.') || path.isAbsolute(module)
85
- ? path.basename(module)
86
- : module
87
- ).replace(/\.[cm]?js$/, '');
164
+ // The extension is stripped where it applies — the file basename (via
165
+ // fileStem) and a bare specifier's tail — but NOT a parent directory name
166
+ // that fileStem may return for a generic basename.
167
+ let raw;
168
+ if (typeof spec.id === 'string' && spec.id) {
169
+ raw = spec.id.replace(/\.[cm]?js$/, '');
170
+ } else if (module.startsWith('.') || path.isAbsolute(module)) {
171
+ raw = fileStem(module);
172
+ } else {
173
+ raw = module.replace(/\.[cm]?js$/, '');
174
+ }
88
175
  const id = raw.toLowerCase().replace(/[^a-z0-9_-]+/g, '-').replace(/^-+|-+$/g, '');
89
176
  if (!id) throw new Error(`plugins: cannot derive an id from ${JSON.stringify(spec.module)}; set entry.id`);
90
177
  return id;
@@ -102,6 +189,35 @@ export function pluginId(spec) {
102
189
  export async function loadPlugins(fastify, entries, ctx) {
103
190
  const log = makePluginLog(ctx.log);
104
191
  const seenIds = new Set();
192
+ // reservePath claims (#602), shared across all entries of this load so
193
+ // two plugins reserving the same pinned path fail the boot with both
194
+ // names — loud beats the silent-loser outcome witnessed with webfinger
195
+ // vs remotestorage.
196
+ const reservations = new Map();
197
+
198
+ // Read-only roster of every loaded entry (#610): { id, prefix, module }
199
+ // for each. Computed up front, before any activate() runs, so a plugin
200
+ // whose job is describing the deployment (a status dashboard, an admin
201
+ // console) sees the FULL set regardless of load order — rather than being
202
+ // hand-fed a duplicate of the operator's plugins array that silently
203
+ // drifts. Frozen so one plugin can't mutate another's view; it includes
204
+ // the plugin itself (consumers filter). Lenient here (never throws) — the
205
+ // load loop below owns validation and fails the boot on a bad entry, so
206
+ // on any successful boot every id/prefix matches what the loop derives.
207
+ // A boot-time snapshot: there is no runtime add/remove yet.
208
+ const roster = Object.freeze(entries.map((entry) => {
209
+ const spec = typeof entry === 'string' ? { module: entry } : (entry ?? {});
210
+ // Only surface a well-formed module — a non-string/empty one makes the
211
+ // load loop below fail the boot, so don't fabricate a coerced value
212
+ // (e.g. "[object Object]") for the transient pre-failure window. Mirrors
213
+ // the loop's own `typeof spec.module === 'string'` gate; id is derived
214
+ // only from a valid module.
215
+ const module = typeof spec.module === 'string' && spec.module ? spec.module : null;
216
+ let id = null;
217
+ try { if (module) id = pluginId(spec); } catch { /* the loop reports it */ }
218
+ return Object.freeze({ id, prefix: normalizePrefix(spec.prefix), module });
219
+ }));
220
+
105
221
  for (const entry of entries) {
106
222
  const spec = typeof entry === 'string' ? { module: entry } : entry;
107
223
  if (!spec || typeof spec.module !== 'string' || !spec.module) {
@@ -152,6 +268,153 @@ export async function loadPlugins(fastify, entries, ctx) {
152
268
  return dir;
153
269
  },
154
270
  },
271
+ // The server's own origin (#601) — for minting absolute URLs and
272
+ // loopback calls, so plugins stop repeating baseUrl in config where
273
+ // a wrong value fails quietly. A function, not a snapshot: with
274
+ // port 0 the real port exists only once the server is listening,
275
+ // so call it lazily (per request, or in an onListen hook via
276
+ // api.fastify) rather than caching the result during activate.
277
+ // An explicit idpIssuer is the deployment's canonical public origin
278
+ // and wins over the host:port derivation, mirroring the pod-seeding
279
+ // logic in server.js.
280
+ // Reserve a path the protocol pins outside the plugin's prefix
281
+ // (#602): fixed roots like /xrpc or /_matrix (literal — exempts the
282
+ // subtree), or parameterized documents like /:user/did.json
283
+ // (exact-shape match only; see compilePathPattern). Both are
284
+ // read-only by default and method-gated ({ methods } to widen) —
285
+ // see the exemption note below. The claim is deliberate and
286
+ // cross-plugin: a second plugin reserving the same path fails the
287
+ // boot naming both claimants, instead of one silently losing.
288
+ // Registering the routes is still the plugin's job via api.fastify.
289
+ reservePath(p, opts = {}) {
290
+ // Tolerate a null/garbage opts (treat as omitted), but a provided
291
+ // non-array `methods` is a caller mistake worth a targeted error
292
+ // rather than an opaque TypeError from .map deep in activate.
293
+ const options = opts && typeof opts === 'object' ? opts : {};
294
+ if (options.methods !== undefined && !Array.isArray(options.methods)) {
295
+ throw new Error(`plugin ${id}: reservePath { methods } must be an array, got ${JSON.stringify(options.methods)}`);
296
+ }
297
+ // Validate AFTER normalization: '//' or '/ ' normalize to '',
298
+ // and an empty string in appPaths would match every URL in the
299
+ // WAC hook — a one-call total WAC bypass.
300
+ const key = typeof p === 'string' ? p.trim().replace(/\/+$/, '') : '';
301
+ if (!key.startsWith('/') || key.length < 2) {
302
+ throw new Error(`plugin ${id}: reservePath needs an absolute path, got ${JSON.stringify(p)}`);
303
+ }
304
+ // A reservation is a pathname, not a URL: '?'/'#' don't belong.
305
+ // A query in the string would be escaped into the matcher (tying
306
+ // the exemption to that exact query), and fragments never reach
307
+ // request.url — both silently produce a reservation that matches
308
+ // nothing real.
309
+ if (key.includes('?') || key.includes('#')) {
310
+ throw new Error(`plugin ${id}: reservePath must be a pathname without '?' or '#', got ${JSON.stringify(p)}`);
311
+ }
312
+ // Track by the shape, not the raw string: '/:user/did.json' and
313
+ // '/:acct/did.json' exempt the same URLs, so they're the same
314
+ // claim and must collide loudly like two literal reservations.
315
+ const claim = reservationKey(key);
316
+ const holder = reservations.get(claim);
317
+ if (holder === id) {
318
+ return; // idempotent re-claim — the matcher is already installed
319
+ }
320
+ if (holder) {
321
+ throw new Error(`plugin ${id}: path '${key}' is already reserved by plugin '${holder}'`);
322
+ }
323
+ reservations.set(claim, id);
324
+ // Read-only by default for BOTH lanes: a reserved path is
325
+ // WAC-exempt, and the LDP write wildcards (PUT/POST/PATCH/DELETE
326
+ // '/*') sit underneath it. Exempting a write method the plugin
327
+ // has NOT implemented would let that write fall through to the
328
+ // LDP handlers as an unauthenticated storage write — the exact
329
+ // trap core installs 405 blocks for under /.well-known/*. Widen
330
+ // with { methods } when the protocol genuinely needs writes.
331
+ const methods = new Set((options.methods ?? ['GET', 'HEAD', 'OPTIONS'])
332
+ .map((m) => String(m).toUpperCase()));
333
+ // Parameterized shapes match exactly (they live inside a
334
+ // WAC-governed pod namespace); literals claim their subtree.
335
+ const re = isParamPath(key) ? compilePathPattern(key) : compileSubtreePattern(key);
336
+ ctx.appPathPatterns?.push({ re, methods });
337
+ log.info(`plugin ${id} reserved ${key} [${[...methods].join(', ')}]`);
338
+ },
339
+ serverInfo() {
340
+ const o = ctx.origin ?? {};
341
+ const addr = fastify.server?.listening ? fastify.server.address() : null;
342
+ const live = addr && typeof addr === 'object' ? addr : null;
343
+ // Once listening, the live bind wins over configured values —
344
+ // listen() may be called with a different host/port than
345
+ // createServer() was given (tests do exactly this).
346
+ const port = live?.port ?? o.port ?? null;
347
+ const rawHost = live?.address ?? o.host;
348
+ // Unspecified binds aren't callable addresses; report the
349
+ // loopback name instead. IPv6 literals need brackets in URLs.
350
+ const host = !rawHost || rawHost === '0.0.0.0' || rawHost === '::' ? 'localhost' : rawHost;
351
+ const protocol = o.ssl ? 'https' : 'http';
352
+ const urlHost = host.includes(':') ? `[${host}]` : host;
353
+ const baseUrl = o.baseUrl || `${protocol}://${urlHost}:${port}`;
354
+ return { baseUrl, protocol, host, port, listening: !!live };
355
+ },
356
+ // Every loaded plugin's { id, prefix, module } (#610), read-only — so
357
+ // a plugin can enumerate its co-loaded siblings instead of being
358
+ // handed a copy of the operator's plugins array. Includes this
359
+ // plugin; consumers filter themselves out. A frozen boot-time
360
+ // snapshot (see `roster` above).
361
+ plugins: roster,
362
+ // Mount a node-style (req, res) handler — a wrapped HTTP app, reverse
363
+ // proxy, or framework adapter — under the plugin's prefix (#583). This
364
+ // bundles the four things every such plugin needs and otherwise
365
+ // rediscovers: the appPaths WAC exemption (already applied above), a
366
+ // scoped pass-through content parser so the wrapped app receives an
367
+ // unconsumed body stream, reply.hijack() so Fastify releases the
368
+ // response, and registration on both the bare prefix and its subtree.
369
+ // Without the scoped parser, Fastify drains the request stream before
370
+ // the handler runs and any body-reading app hangs forever.
371
+ async mountApp(handler, opts = {}) {
372
+ if (typeof handler !== 'function') {
373
+ throw new Error(`plugin ${id}: mountApp(handler) needs a (req, res) function`);
374
+ }
375
+ // Any provided prefix must validate — same rule as entry.prefix: a
376
+ // falsy normalization silently falling back to the entry prefix
377
+ // would mount the app (and WAC-exempt it) somewhere unexpected.
378
+ const secondary = normalizePrefix(opts.prefix);
379
+ if (opts.prefix !== undefined && !secondary) {
380
+ throw new Error(`plugin ${id}: mountApp invalid prefix ${JSON.stringify(opts.prefix)} (must start with '/'; omit to use the entry prefix)`);
381
+ }
382
+ const mountPrefix = secondary || prefix;
383
+ if (!mountPrefix) {
384
+ throw new Error(`plugin ${id}: mountApp needs a prefix (entry.prefix or opts.prefix)`);
385
+ }
386
+ if (mountPrefix !== prefix && !ctx.appPaths.includes(mountPrefix)) {
387
+ ctx.appPaths.push(mountPrefix); // exempt a secondary mount too
388
+ }
389
+ await fastify.register(async (scope) => {
390
+ scope.removeAllContentTypeParsers();
391
+ scope.addContentTypeParser('*', (req, payload, done) => done(null, payload));
392
+ // After hijack() Fastify sends nothing, so a handler bug must not
393
+ // hang the client or become an unhandled rejection (same contract
394
+ // as ws.route below): log, answer 500 if nothing went out yet,
395
+ // else drop the one affected socket.
396
+ const fail = (res, err) => {
397
+ log.error({ err }, `plugin ${id}: mounted app handler failed`);
398
+ if (!res.headersSent && !res.writableEnded) {
399
+ res.statusCode = 500;
400
+ res.end();
401
+ } else {
402
+ res.destroy();
403
+ }
404
+ };
405
+ const wrapped = (request, reply) => {
406
+ reply.hijack();
407
+ try {
408
+ Promise.resolve(handler(request.raw, reply.raw))
409
+ .catch((err) => fail(reply.raw, err));
410
+ } catch (err) {
411
+ fail(reply.raw, err);
412
+ }
413
+ };
414
+ scope.all(mountPrefix, wrapped);
415
+ scope.all(mountPrefix + '/*', wrapped);
416
+ });
417
+ },
155
418
  ws: {
156
419
  async route(wsPath, handler) {
157
420
  if (typeof wsPath !== 'string' || !wsPath.startsWith('/')) {
@@ -168,11 +431,11 @@ export async function loadPlugins(fastify, entries, ctx) {
168
431
  // takes the host down: log it and close the one affected socket.
169
432
  try {
170
433
  Promise.resolve(handler(socket, request)).catch((err) => {
171
- log.error(`plugin ${id}: ws handler failed: ${err.message}`);
434
+ log.error({ err }, `plugin ${id}: ws handler failed`);
172
435
  socket.terminate?.();
173
436
  });
174
437
  } catch (err) {
175
- log.error(`plugin ${id}: ws handler failed: ${err.message}`);
438
+ log.error({ err }, `plugin ${id}: ws handler failed`);
176
439
  socket.terminate?.();
177
440
  }
178
441
  });
package/src/server.js CHANGED
@@ -124,6 +124,10 @@ export function createServer(options = {}) {
124
124
  // appPaths. The WAC hook reads the array per request, so pushes made
125
125
  // during plugin activation are honored.
126
126
  const pluginEntries = Array.isArray(options.plugins) ? options.plugins : [];
127
+ // Parameterized reservations from api.reservePath (#602): compiled
128
+ // matchers for path shapes like /:user/did.json that literal appPaths
129
+ // prefixes cannot express. Same per-request read as appPaths.
130
+ const appPathPatterns = [];
127
131
  // ActivityPub federation is OFF by default
128
132
  const activitypubEnabled = options.activitypub ?? false;
129
133
  const apUsername = options.apUsername ?? 'me';
@@ -426,8 +430,17 @@ export function createServer(options = {}) {
426
430
  const { loadPlugins } = await import('./plugins.js');
427
431
  await loadPlugins(instance, pluginEntries, {
428
432
  appPaths,
433
+ appPathPatterns,
429
434
  root: options.root || process.env.DATA_ROOT || './data',
430
435
  log: fastify.log,
436
+ // api.serverInfo inputs (#601). ?? keeps an explicit port 0 —
437
+ // "resolved at listen" — instead of masking it with the default.
438
+ origin: {
439
+ ssl: !!options.ssl,
440
+ host: options.host,
441
+ port: options.port ?? defaults.port,
442
+ baseUrl: idpIssuer?.replace(/\/$/, '') || null,
443
+ },
431
444
  });
432
445
  });
433
446
  }
@@ -751,6 +764,7 @@ export function createServer(options = {}) {
751
764
  (terminalEnabled && (request.url === '/.terminal' || request.url.startsWith('/.terminal?'))) ||
752
765
  (tunnelEnabled && (request.url === tunnelPath || request.url.startsWith(tunnelPath + '?') || request.url.startsWith('/tunnel/'))) ||
753
766
  appPaths.some(p => request.url === p || request.url.startsWith(p + '/') || request.url.startsWith(p + '?')) ||
767
+ appPathPatterns.some(m => m.methods.has(request.method) && m.re.test(request.url)) ||
754
768
  mashlibPaths.some(p => request.url === p || request.url.startsWith(p + '.'))) {
755
769
  return;
756
770
  }
@@ -0,0 +1,165 @@
1
+ /**
2
+ * api.mountApp (#583) — a plugin mounting a node-style (req, res) handler
3
+ * receives unconsumed request bodies, the exact shape the Tideholm and
4
+ * bridge adapters hand-rolled. Verifies the scoped pass-through parser lets
5
+ * a body-reading app work, host parsing stays intact outside the mount, and
6
+ * a secondary mount prefix is WAC-exempted too.
7
+ */
8
+
9
+ import { describe, it, before, after, afterEach } from 'node:test';
10
+ import assert from 'node:assert';
11
+ import fs from 'fs-extra';
12
+ import path from 'path';
13
+ import os from 'os';
14
+
15
+ const TEST_DATA_DIR = './test-data-mountapp';
16
+ const FIXTURE_DIR = path.join(os.tmpdir(), 'jss-mountapp-fixture');
17
+
18
+ // A plugin that mounts a plain node handler which reads the whole body and
19
+ // echoes it back — the app that hangs if Fastify drained the stream first.
20
+ const FIXTURE = `
21
+ export async function activate(api) {
22
+ await api.mountApp((req, res) => {
23
+ let body = '';
24
+ req.on('data', (c) => { body += c; });
25
+ req.on('end', () => {
26
+ res.writeHead(200, { 'content-type': 'application/json' });
27
+ res.end(JSON.stringify({ echoed: body, method: req.method, url: req.url }));
28
+ });
29
+ });
30
+ // A second mount under a different prefix, to prove secondary exemption.
31
+ await api.mountApp((req, res) => {
32
+ res.writeHead(200, { 'content-type': 'text/plain' });
33
+ res.end('secondary');
34
+ }, { prefix: '/wrapped2' });
35
+ // Handlers that fail — sync throw and async rejection — to prove a
36
+ // handler bug after hijack() answers 500 instead of hanging the client.
37
+ await api.mountApp(() => { throw new Error('sync boom'); }, { prefix: '/boom' });
38
+ await api.mountApp(async () => { throw new Error('async boom'); }, { prefix: '/boom-async' });
39
+ // Non-Error throw: the failure guard itself must not throw on err.message.
40
+ await api.mountApp(() => { throw 'string boom'; }, { prefix: '/boom-raw' });
41
+ await api.mountApp(async () => Promise.reject(undefined), { prefix: '/boom-undef' });
42
+ }
43
+ `;
44
+
45
+ // A plugin whose secondary mount prefix is invalid — must fail the boot.
46
+ const BAD_PREFIX_FIXTURE = `
47
+ export async function activate(api) {
48
+ await api.mountApp((req, res) => res.end('x'), { prefix: 'chat' });
49
+ }
50
+ `;
51
+
52
+ let server;
53
+ let baseUrl;
54
+ let originalDataRoot;
55
+
56
+ async function start() {
57
+ await fs.emptyDir(TEST_DATA_DIR);
58
+ const { createServer } = await import('../src/server.js');
59
+ server = createServer({
60
+ logger: false,
61
+ forceCloseConnections: true,
62
+ root: TEST_DATA_DIR,
63
+ plugins: [
64
+ { id: 'wrapped', module: path.join(FIXTURE_DIR, 'plugin.js'), prefix: '/wrapped' },
65
+ ],
66
+ });
67
+ await server.listen({ port: 0, host: '127.0.0.1' });
68
+ baseUrl = `http://127.0.0.1:${server.server.address().port}`;
69
+ }
70
+
71
+ describe('api.mountApp (#583)', () => {
72
+ before(async () => {
73
+ originalDataRoot = process.env.DATA_ROOT;
74
+ await fs.emptyDir(FIXTURE_DIR);
75
+ await fs.writeFile(path.join(FIXTURE_DIR, 'plugin.js'), FIXTURE);
76
+ });
77
+ after(async () => {
78
+ await fs.remove(FIXTURE_DIR);
79
+ if (originalDataRoot === undefined) delete process.env.DATA_ROOT;
80
+ else process.env.DATA_ROOT = originalDataRoot;
81
+ });
82
+ afterEach(async () => {
83
+ if (server) { await server.close(); server = null; }
84
+ await fs.remove(TEST_DATA_DIR);
85
+ });
86
+
87
+ it('a JSON POST body round-trips through the wrapped node handler', async () => {
88
+ await start();
89
+ const res = await fetch(`${baseUrl}/wrapped/api/thing`, {
90
+ method: 'POST',
91
+ headers: { 'content-type': 'application/json' },
92
+ body: JSON.stringify({ hello: 'world' }),
93
+ });
94
+ assert.strictEqual(res.status, 200);
95
+ const body = await res.json();
96
+ assert.strictEqual(body.echoed, JSON.stringify({ hello: 'world' }));
97
+ assert.strictEqual(body.method, 'POST');
98
+ });
99
+
100
+ it('serves the bare prefix and the subtree, unauthenticated (WAC-exempt)', async () => {
101
+ await start();
102
+ const bare = await fetch(`${baseUrl}/wrapped`, { method: 'GET' });
103
+ assert.strictEqual(bare.status, 200);
104
+ const deep = await fetch(`${baseUrl}/wrapped/a/b/c`, { method: 'GET' });
105
+ assert.strictEqual(deep.status, 200);
106
+ });
107
+
108
+ it('a secondary mount prefix is also served and WAC-exempt', async () => {
109
+ await start();
110
+ const res = await fetch(`${baseUrl}/wrapped2/anything`);
111
+ assert.strictEqual(res.status, 200);
112
+ assert.strictEqual(await res.text(), 'secondary');
113
+ });
114
+
115
+ it('host body parsing is unaffected outside the mount (LDP PUT still WAC-guarded)', async () => {
116
+ await start();
117
+ const res = await fetch(`${baseUrl}/somepod/private/x`, { method: 'PUT', body: 'data' });
118
+ assert.ok([401, 403].includes(res.status), `expected WAC rejection, got ${res.status}`);
119
+ });
120
+
121
+ it('a handler that throws sync answers 500 and the server survives', async () => {
122
+ await start();
123
+ const res = await fetch(`${baseUrl}/boom`);
124
+ assert.strictEqual(res.status, 500);
125
+ // Process and server still alive: a healthy mount keeps answering.
126
+ const ok = await fetch(`${baseUrl}/wrapped2/still-up`);
127
+ assert.strictEqual(ok.status, 200);
128
+ });
129
+
130
+ it('a handler that rejects async answers 500 instead of leaking the rejection', async () => {
131
+ await start();
132
+ const res = await fetch(`${baseUrl}/boom-async`);
133
+ assert.strictEqual(res.status, 500);
134
+ const ok = await fetch(`${baseUrl}/wrapped2/still-up`);
135
+ assert.strictEqual(ok.status, 200);
136
+ });
137
+
138
+ it('a handler that throws a non-Error still answers 500 (guard must not throw on err.message)', async () => {
139
+ await start();
140
+ const raw = await fetch(`${baseUrl}/boom-raw`);
141
+ assert.strictEqual(raw.status, 500);
142
+ const undef = await fetch(`${baseUrl}/boom-undef`);
143
+ assert.strictEqual(undef.status, 500);
144
+ const ok = await fetch(`${baseUrl}/wrapped2/still-up`);
145
+ assert.strictEqual(ok.status, 200);
146
+ });
147
+
148
+ it('a provided-but-invalid secondary prefix fails the boot instead of mounting at the entry prefix', async () => {
149
+ await fs.writeFile(path.join(FIXTURE_DIR, 'bad-prefix.js'), BAD_PREFIX_FIXTURE);
150
+ await fs.emptyDir(TEST_DATA_DIR);
151
+ const { createServer } = await import('../src/server.js');
152
+ server = createServer({
153
+ logger: false,
154
+ forceCloseConnections: true,
155
+ root: TEST_DATA_DIR,
156
+ plugins: [
157
+ { id: 'bad', module: path.join(FIXTURE_DIR, 'bad-prefix.js'), prefix: '/ok' },
158
+ ],
159
+ });
160
+ await assert.rejects(
161
+ server.listen({ port: 0, host: '127.0.0.1' }),
162
+ /invalid prefix "chat"/,
163
+ );
164
+ });
165
+ });
@@ -0,0 +1,326 @@
1
+ /**
2
+ * api.reservePath (#602) — a plugin can claim protocol-pinned paths
3
+ * outside its prefix: fixed roots (/xrpc) as WAC-exempt subtrees, and
4
+ * parameterized documents (/:user/did.json) as exact-shape, read-only
5
+ * exemptions inside the pod's WAC-governed namespace. Claims are
6
+ * cross-plugin: a second claimant fails the boot naming both.
7
+ */
8
+
9
+ import { describe, it, before, after, afterEach } from 'node:test';
10
+ import assert from 'node:assert';
11
+ import fs from 'fs-extra';
12
+ import path from 'path';
13
+ import os from 'os';
14
+
15
+ const TEST_DATA_DIR = './test-data-reservepath';
16
+ const FIXTURE_DIR = path.join(os.tmpdir(), 'jss-reservepath-fixture');
17
+
18
+ // An xrpc-style shim (fixed root) plus a did:web-style pinned document.
19
+ const FIXTURE = `
20
+ export async function activate(api) {
21
+ api.reservePath('/xrpc');
22
+ api.fastify.get('/xrpc/ping', async () => ({ pong: true }));
23
+
24
+ api.reservePath('/:user/did.json');
25
+ // A second identical claim by the same plugin is an idempotent no-op —
26
+ // no duplicate matcher, no self-collision error.
27
+ api.reservePath('/:user/did.json');
28
+ api.fastify.get('/:user/did.json', async (req) => ({ id: 'did:web:' + req.params.user }));
29
+ }
30
+ `;
31
+
32
+ // A rival that claims the same fixed root — must fail the boot.
33
+ const RIVAL_FIXTURE = `
34
+ export async function activate(api) {
35
+ api.reservePath('/xrpc');
36
+ }
37
+ `;
38
+
39
+ // A shim that legitimately needs writes widens the method set explicitly.
40
+ const WRITE_SHIM_FIXTURE = `
41
+ export async function activate(api) {
42
+ api.reservePath('/api', { methods: ['GET', 'POST'] });
43
+ api.fastify.post('/api/echo', async (req) => ({ ok: true }));
44
+ }
45
+ `;
46
+
47
+ // '//' normalizes to '' — pushed to appPaths it would match every URL
48
+ // and disable WAC wholesale. Must be rejected at activate.
49
+ const SLASHES_FIXTURE = `
50
+ export async function activate(api) {
51
+ api.reservePath('//');
52
+ }
53
+ `;
54
+
55
+ // A reservation carrying a query is malformed — must be rejected.
56
+ const QUERY_FIXTURE = `
57
+ export async function activate(api) {
58
+ api.reservePath('/xrpc?x=1');
59
+ }
60
+ `;
61
+
62
+ // A non-array { methods } is a caller mistake — targeted error, not a
63
+ // TypeError. And null opts is tolerated as "omitted" (read-only default).
64
+ const BAD_METHODS_FIXTURE = `
65
+ export async function activate(api) {
66
+ api.reservePath('/x', { methods: 'GET' });
67
+ }
68
+ `;
69
+ const NULL_OPTS_FIXTURE = `
70
+ export async function activate(api) {
71
+ api.reservePath('/nullopts', null);
72
+ api.fastify.get('/nullopts/ping', async () => ({ ok: true }));
73
+ }
74
+ `;
75
+
76
+ // Same shape as the main plugin's /:user/did.json, different param name —
77
+ // exempts the same URLs, so it's the same claim and must collide.
78
+ const SHAPE_RIVAL_FIXTURE = `
79
+ export async function activate(api) {
80
+ api.reservePath('/:acct/did.json');
81
+ }
82
+ `;
83
+
84
+ // '/:user.json' is NOT a param segment (mixes sigil with literal text);
85
+ // only the exact literal path is exempt, a sibling like /alice.json isn't.
86
+ const LITERALISH_FIXTURE = `
87
+ export async function activate(api) {
88
+ api.reservePath('/:user.json');
89
+ api.fastify.get('/:user.json', async () => ({ literal: true }));
90
+ }
91
+ `;
92
+
93
+ // A literal ':' segment ('/:/x') must NOT collide with the param shape
94
+ // '/:user/x' — different claim types that only alias if the collision
95
+ // key throws away the param-vs-literal distinction.
96
+ const LITERAL_COLON_FIXTURE = `
97
+ export async function activate(api) {
98
+ api.reservePath('/:user/x'); // param
99
+ api.fastify.get('/:user/x', async () => ({ param: true }));
100
+ }
101
+ `;
102
+ const COLON_SEG_FIXTURE = `
103
+ export async function activate(api) {
104
+ api.reservePath('/:/x'); // literal ':' segment
105
+ }
106
+ `;
107
+
108
+ let server;
109
+ let baseUrl;
110
+ let originalDataRoot;
111
+
112
+ async function start(plugins) {
113
+ await fs.emptyDir(TEST_DATA_DIR);
114
+ const { createServer } = await import('../src/server.js');
115
+ server = createServer({
116
+ logger: false,
117
+ forceCloseConnections: true,
118
+ root: TEST_DATA_DIR,
119
+ plugins,
120
+ });
121
+ await server.listen({ port: 0, host: '127.0.0.1' });
122
+ baseUrl = `http://127.0.0.1:${server.server.address().port}`;
123
+ }
124
+
125
+ const MAIN = () => [{ id: 'shim', module: path.join(FIXTURE_DIR, 'plugin.js'), prefix: '/shim' }];
126
+
127
+ describe('api.reservePath (#602)', () => {
128
+ before(async () => {
129
+ originalDataRoot = process.env.DATA_ROOT;
130
+ await fs.emptyDir(FIXTURE_DIR);
131
+ await fs.writeFile(path.join(FIXTURE_DIR, 'plugin.js'), FIXTURE);
132
+ await fs.writeFile(path.join(FIXTURE_DIR, 'rival.js'), RIVAL_FIXTURE);
133
+ await fs.writeFile(path.join(FIXTURE_DIR, 'write-shim.js'), WRITE_SHIM_FIXTURE);
134
+ await fs.writeFile(path.join(FIXTURE_DIR, 'query.js'), QUERY_FIXTURE);
135
+ await fs.writeFile(path.join(FIXTURE_DIR, 'bad-methods.js'), BAD_METHODS_FIXTURE);
136
+ await fs.writeFile(path.join(FIXTURE_DIR, 'null-opts.js'), NULL_OPTS_FIXTURE);
137
+ await fs.writeFile(path.join(FIXTURE_DIR, 'shape-rival.js'), SHAPE_RIVAL_FIXTURE);
138
+ await fs.writeFile(path.join(FIXTURE_DIR, 'literalish.js'), LITERALISH_FIXTURE);
139
+ await fs.writeFile(path.join(FIXTURE_DIR, 'literal-colon.js'), LITERAL_COLON_FIXTURE);
140
+ await fs.writeFile(path.join(FIXTURE_DIR, 'colon-seg.js'), COLON_SEG_FIXTURE);
141
+ });
142
+ after(async () => {
143
+ await fs.remove(FIXTURE_DIR);
144
+ if (originalDataRoot === undefined) delete process.env.DATA_ROOT;
145
+ else process.env.DATA_ROOT = originalDataRoot;
146
+ });
147
+ afterEach(async () => {
148
+ if (server) { await server.close(); server = null; }
149
+ await fs.remove(TEST_DATA_DIR);
150
+ });
151
+
152
+ it('a reserved fixed root serves unauthenticated', async () => {
153
+ await start(MAIN());
154
+ const res = await fetch(`${baseUrl}/xrpc/ping`);
155
+ assert.strictEqual(res.status, 200);
156
+ assert.deepStrictEqual(await res.json(), { pong: true });
157
+ });
158
+
159
+ it('a write under a read-only literal reservation stays WAC-guarded', async () => {
160
+ await start(MAIN());
161
+ // /xrpc is reserved read-only; the plugin only handles GET /xrpc/ping.
162
+ // Without the method gate this PUT would skip WAC and fall through to
163
+ // the LDP write wildcard as an unauthenticated storage write.
164
+ const res = await fetch(`${baseUrl}/xrpc/ping`, { method: 'PUT', body: 'x' });
165
+ assert.ok([401, 403].includes(res.status), `expected WAC rejection, got ${res.status}`);
166
+ });
167
+
168
+ it('a shim can widen its reservation to serve writes', async () => {
169
+ await start([{ id: 'writer', module: path.join(FIXTURE_DIR, 'write-shim.js'), prefix: '/w' }]);
170
+ // POST is in the widened set and handled → serves unauthenticated.
171
+ const ok = await fetch(`${baseUrl}/api/echo`, { method: 'POST', body: '{}' });
172
+ assert.strictEqual(ok.status, 200);
173
+ // PUT is NOT in the set → still WAC-guarded, no LDP fall-through.
174
+ const put = await fetch(`${baseUrl}/api/echo`, { method: 'PUT', body: '{}' });
175
+ assert.ok([401, 403].includes(put.status), `expected WAC rejection, got ${put.status}`);
176
+ });
177
+
178
+ it('WAC still guards unreserved paths', async () => {
179
+ await start(MAIN());
180
+ const res = await fetch(`${baseUrl}/somepod/private/x`, { method: 'PUT', body: 'data' });
181
+ assert.ok([401, 403].includes(res.status), `expected WAC rejection, got ${res.status}`);
182
+ });
183
+
184
+ it('a parameterized reservation serves the pinned document shape', async () => {
185
+ await start(MAIN());
186
+ const res = await fetch(`${baseUrl}/alice/did.json`);
187
+ assert.strictEqual(res.status, 200);
188
+ assert.deepStrictEqual(await res.json(), { id: 'did:web:alice' });
189
+ });
190
+
191
+ it('a query string (even one containing /) does not affect shape matching', async () => {
192
+ await start(MAIN());
193
+ // The param class must not swallow '?': a '/' inside the query would
194
+ // otherwise break the match for a path shape that is satisfied.
195
+ const res = await fetch(`${baseUrl}/alice/did.json?redirect=/a/b`);
196
+ assert.strictEqual(res.status, 200);
197
+ assert.deepStrictEqual(await res.json(), { id: 'did:web:alice' });
198
+ });
199
+
200
+ it('parameterized reservations are read-only: writes to the shape stay WAC-guarded', async () => {
201
+ await start(MAIN());
202
+ // Without the method gate this PUT would skip WAC and fall through
203
+ // to the LDP wildcard as an unauthenticated pod write.
204
+ const res = await fetch(`${baseUrl}/alice/did.json`, { method: 'PUT', body: '{}' });
205
+ assert.ok([401, 403].includes(res.status), `expected WAC rejection, got ${res.status}`);
206
+ });
207
+
208
+ it("reservePath('//') fails the boot instead of exempting every URL from WAC", async () => {
209
+ await fs.writeFile(path.join(FIXTURE_DIR, 'slashes.js'), SLASHES_FIXTURE);
210
+ await fs.emptyDir(TEST_DATA_DIR);
211
+ const { createServer } = await import('../src/server.js');
212
+ server = createServer({
213
+ logger: false,
214
+ forceCloseConnections: true,
215
+ root: TEST_DATA_DIR,
216
+ plugins: [
217
+ { id: 'slashes', module: path.join(FIXTURE_DIR, 'slashes.js'), prefix: '/slashes' },
218
+ ],
219
+ });
220
+ await assert.rejects(
221
+ server.listen({ port: 0, host: '127.0.0.1' }),
222
+ /reservePath needs an absolute path/,
223
+ );
224
+ });
225
+
226
+ it('same shape with a different param name is the same claim and collides', async () => {
227
+ await fs.emptyDir(TEST_DATA_DIR);
228
+ const { createServer } = await import('../src/server.js');
229
+ server = createServer({
230
+ logger: false,
231
+ forceCloseConnections: true,
232
+ root: TEST_DATA_DIR,
233
+ plugins: [
234
+ ...MAIN(),
235
+ { id: 'shaperival', module: path.join(FIXTURE_DIR, 'shape-rival.js'), prefix: '/sr' },
236
+ ],
237
+ });
238
+ await assert.rejects(
239
+ server.listen({ port: 0, host: '127.0.0.1' }),
240
+ /already reserved by plugin 'shim'/,
241
+ );
242
+ });
243
+
244
+ it("'/:user.json' is literal, not a wildcard — a sibling stays WAC-guarded", async () => {
245
+ await start([{ id: 'lit', module: path.join(FIXTURE_DIR, 'literalish.js'), prefix: '/lit' }]);
246
+ // The exact reserved path serves...
247
+ const exact = await fetch(`${baseUrl}/:user.json`);
248
+ assert.strictEqual(exact.status, 200);
249
+ // ...but a real single-segment sibling is NOT exempted (would be, if
250
+ // the segment had been treated as a param).
251
+ const sibling = await fetch(`${baseUrl}/alice.json`, { method: 'PUT', body: 'x' });
252
+ assert.ok([401, 403].includes(sibling.status), `expected WAC rejection, got ${sibling.status}`);
253
+ });
254
+
255
+ it("a literal ':' segment does not alias a param shape (no false collision)", async () => {
256
+ await start([
257
+ { id: 'litcolon', module: path.join(FIXTURE_DIR, 'literal-colon.js'), prefix: '/lc' },
258
+ { id: 'colonseg', module: path.join(FIXTURE_DIR, 'colon-seg.js'), prefix: '/cs' },
259
+ ]);
260
+ // Booted cleanly — the two reservations are distinct claims. The
261
+ // param route still serves its shape.
262
+ const res = await fetch(`${baseUrl}/alice/x`);
263
+ assert.strictEqual(res.status, 200);
264
+ assert.deepStrictEqual(await res.json(), { param: true });
265
+ });
266
+
267
+ it("reservePath with a query ('/xrpc?x=1') fails the boot as malformed", async () => {
268
+ await fs.emptyDir(TEST_DATA_DIR);
269
+ const { createServer } = await import('../src/server.js');
270
+ server = createServer({
271
+ logger: false,
272
+ forceCloseConnections: true,
273
+ root: TEST_DATA_DIR,
274
+ plugins: [
275
+ { id: 'q', module: path.join(FIXTURE_DIR, 'query.js'), prefix: '/q' },
276
+ ],
277
+ });
278
+ await assert.rejects(
279
+ server.listen({ port: 0, host: '127.0.0.1' }),
280
+ /must be a pathname without '\?' or '#'/,
281
+ );
282
+ });
283
+
284
+ it('a non-array { methods } fails the boot with a targeted error', async () => {
285
+ await fs.emptyDir(TEST_DATA_DIR);
286
+ const { createServer } = await import('../src/server.js');
287
+ server = createServer({
288
+ logger: false,
289
+ forceCloseConnections: true,
290
+ root: TEST_DATA_DIR,
291
+ plugins: [
292
+ { id: 'bm', module: path.join(FIXTURE_DIR, 'bad-methods.js'), prefix: '/bm' },
293
+ ],
294
+ });
295
+ await assert.rejects(
296
+ server.listen({ port: 0, host: '127.0.0.1' }),
297
+ /reservePath \{ methods \} must be an array/,
298
+ );
299
+ });
300
+
301
+ it('null opts is tolerated as omitted (read-only default)', async () => {
302
+ await start([{ id: 'no', module: path.join(FIXTURE_DIR, 'null-opts.js'), prefix: '/no' }]);
303
+ const ok = await fetch(`${baseUrl}/nullopts/ping`);
304
+ assert.strictEqual(ok.status, 200);
305
+ const put = await fetch(`${baseUrl}/nullopts/ping`, { method: 'PUT', body: 'x' });
306
+ assert.ok([401, 403].includes(put.status), `expected WAC rejection, got ${put.status}`);
307
+ });
308
+
309
+ it('two plugins claiming the same path fail the boot naming both', async () => {
310
+ await fs.emptyDir(TEST_DATA_DIR);
311
+ const { createServer } = await import('../src/server.js');
312
+ server = createServer({
313
+ logger: false,
314
+ forceCloseConnections: true,
315
+ root: TEST_DATA_DIR,
316
+ plugins: [
317
+ ...MAIN(),
318
+ { id: 'rival', module: path.join(FIXTURE_DIR, 'rival.js'), prefix: '/rival' },
319
+ ],
320
+ });
321
+ await assert.rejects(
322
+ server.listen({ port: 0, host: '127.0.0.1' }),
323
+ /rival: path '\/xrpc' is already reserved by plugin 'shim'/,
324
+ );
325
+ });
326
+ });
@@ -0,0 +1,114 @@
1
+ /**
2
+ * api.plugins (#610) — a plugin can enumerate its co-loaded siblings
3
+ * instead of being hand-fed a duplicate of the operator's plugins array
4
+ * (which silently drifts). A read-only, frozen boot-time snapshot of
5
+ * every entry's { id, prefix, module }, computed before any activate()
6
+ * runs so it is complete regardless of load order.
7
+ */
8
+
9
+ import { describe, it, before, after, afterEach } from 'node:test';
10
+ import assert from 'node:assert';
11
+ import fs from 'fs-extra';
12
+ import path from 'path';
13
+ import os from 'os';
14
+
15
+ const TEST_DATA_DIR = './test-data-roster';
16
+ const FIXTURE_DIR = path.join(os.tmpdir(), 'jss-roster-fixture');
17
+
18
+ // The FIRST plugin captures api.plugins at activate time and serves it.
19
+ // Because the roster is computed up front, it must already list the
20
+ // siblings that activate AFTER this one — the load-order-independence
21
+ // the seam exists to guarantee.
22
+ const REPORTER = `
23
+ export async function activate(api) {
24
+ const atActivate = api.plugins;
25
+ api.fastify.get('/a/roster', async () => ({
26
+ plugins: atActivate,
27
+ frozen: Object.isFrozen(atActivate),
28
+ entryFrozen: atActivate.length > 0 ? Object.isFrozen(atActivate[0]) : null,
29
+ self: atActivate.find((p) => p.id === 'roster-a') ?? null,
30
+ }));
31
+ }
32
+ `;
33
+
34
+ // A sibling that registers no routes — it only needs to exist in the roster.
35
+ const NOOP = `export async function activate() {}`;
36
+
37
+ let server;
38
+ let baseUrl;
39
+ let originalDataRoot;
40
+
41
+ async function start(plugins) {
42
+ await fs.emptyDir(TEST_DATA_DIR);
43
+ const { createServer } = await import('../src/server.js');
44
+ server = createServer({
45
+ logger: false,
46
+ forceCloseConnections: true,
47
+ root: TEST_DATA_DIR,
48
+ plugins,
49
+ });
50
+ await server.listen({ port: 0, host: '127.0.0.1' });
51
+ baseUrl = `http://127.0.0.1:${server.server.address().port}`;
52
+ }
53
+
54
+ describe('api.plugins (#610)', () => {
55
+ before(async () => {
56
+ originalDataRoot = process.env.DATA_ROOT;
57
+ await fs.emptyDir(FIXTURE_DIR);
58
+ await fs.writeFile(path.join(FIXTURE_DIR, 'reporter.js'), REPORTER);
59
+ await fs.writeFile(path.join(FIXTURE_DIR, 'noop.js'), NOOP);
60
+ });
61
+ after(async () => {
62
+ await fs.remove(FIXTURE_DIR);
63
+ if (originalDataRoot === undefined) delete process.env.DATA_ROOT;
64
+ else process.env.DATA_ROOT = originalDataRoot;
65
+ });
66
+ afterEach(async () => {
67
+ if (server) { await server.close(); server = null; }
68
+ await fs.remove(TEST_DATA_DIR);
69
+ });
70
+
71
+ const reporter = path.join(FIXTURE_DIR, 'reporter.js');
72
+ const noop = path.join(FIXTURE_DIR, 'noop.js');
73
+
74
+ it('lists every loaded entry — including siblings that activate later', async () => {
75
+ await start([
76
+ { id: 'roster-a', module: reporter, prefix: '/a' },
77
+ { id: 'roster-b', module: noop, prefix: '/b' },
78
+ { id: 'roster-c', module: noop }, // no prefix
79
+ ]);
80
+ const res = await fetch(`${baseUrl}/a/roster`);
81
+ assert.strictEqual(res.status, 200);
82
+ const { plugins } = await res.json();
83
+
84
+ // The reporter is entry 0 yet sees b and c (activated after it) —
85
+ // the roster is complete up front, not accumulated during the loop.
86
+ assert.deepStrictEqual(plugins.map((p) => p.id), ['roster-a', 'roster-b', 'roster-c']);
87
+ const b = plugins.find((p) => p.id === 'roster-b');
88
+ assert.strictEqual(b.prefix, '/b');
89
+ assert.strictEqual(b.module, noop);
90
+ // A no-prefix entry reports '' (same normalization the loader applies).
91
+ assert.strictEqual(plugins.find((p) => p.id === 'roster-c').prefix, '');
92
+ });
93
+
94
+ it('includes the plugin itself', async () => {
95
+ await start([
96
+ { id: 'roster-a', module: reporter, prefix: '/a' },
97
+ { id: 'roster-b', module: noop, prefix: '/b' },
98
+ ]);
99
+ const { self } = await (await fetch(`${baseUrl}/a/roster`)).json();
100
+ assert.ok(self, 'the roster includes the reporting plugin');
101
+ assert.strictEqual(self.prefix, '/a');
102
+ assert.strictEqual(self.module, reporter);
103
+ });
104
+
105
+ it('is a frozen, read-only snapshot at both levels', async () => {
106
+ await start([
107
+ { id: 'roster-a', module: reporter, prefix: '/a' },
108
+ { id: 'roster-b', module: noop, prefix: '/b' },
109
+ ]);
110
+ const { frozen, entryFrozen } = await (await fetch(`${baseUrl}/a/roster`)).json();
111
+ assert.strictEqual(frozen, true, 'the array is frozen');
112
+ assert.strictEqual(entryFrozen, true, 'each entry object is frozen');
113
+ });
114
+ });
@@ -0,0 +1,110 @@
1
+ /**
2
+ * api.serverInfo (#601) — a plugin can learn the server's own origin
3
+ * instead of being told it via config (where a wrong value fails
4
+ * quietly). Lazy by design: with port 0 the real port exists only once
5
+ * the server is listening, so serverInfo() is a call, not a snapshot.
6
+ */
7
+
8
+ import { describe, it, before, after, afterEach } from 'node:test';
9
+ import assert from 'node:assert';
10
+ import fs from 'fs-extra';
11
+ import path from 'path';
12
+ import os from 'os';
13
+
14
+ const TEST_DATA_DIR = './test-data-serverinfo';
15
+ const FIXTURE_DIR = path.join(os.tmpdir(), 'jss-serverinfo-fixture');
16
+
17
+ // Captures serverInfo at activate time and serves the live value per
18
+ // request — the two moments the seam has to be honest about.
19
+ const FIXTURE = `
20
+ export async function activate(api) {
21
+ const atActivate = api.serverInfo();
22
+ api.fastify.get('/info-app/now', async () => ({
23
+ atActivate,
24
+ now: api.serverInfo(),
25
+ }));
26
+ }
27
+ `;
28
+
29
+ let server;
30
+ let baseUrl;
31
+ let originalDataRoot;
32
+
33
+ async function start(extraOptions = {}, listenHost) {
34
+ await fs.emptyDir(TEST_DATA_DIR);
35
+ const { createServer } = await import('../src/server.js');
36
+ server = createServer({
37
+ logger: false,
38
+ forceCloseConnections: true,
39
+ root: TEST_DATA_DIR,
40
+ plugins: [
41
+ { id: 'info', module: path.join(FIXTURE_DIR, 'plugin.js'), prefix: '/info-app' },
42
+ ],
43
+ ...extraOptions,
44
+ });
45
+ // Bind to the host under test — serverInfo must reflect the real bind,
46
+ // not just the configured value.
47
+ await server.listen({ port: 0, host: listenHost ?? extraOptions.host ?? '127.0.0.1' });
48
+ baseUrl = `http://127.0.0.1:${server.server.address().port}`;
49
+ }
50
+
51
+ describe('api.serverInfo (#601)', () => {
52
+ before(async () => {
53
+ originalDataRoot = process.env.DATA_ROOT;
54
+ await fs.emptyDir(FIXTURE_DIR);
55
+ await fs.writeFile(path.join(FIXTURE_DIR, 'plugin.js'), FIXTURE);
56
+ });
57
+ after(async () => {
58
+ await fs.remove(FIXTURE_DIR);
59
+ if (originalDataRoot === undefined) delete process.env.DATA_ROOT;
60
+ else process.env.DATA_ROOT = originalDataRoot;
61
+ });
62
+ afterEach(async () => {
63
+ if (server) { await server.close(); server = null; }
64
+ await fs.remove(TEST_DATA_DIR);
65
+ });
66
+
67
+ it('resolves the real port once listening, even when booted with port 0', async () => {
68
+ await start({ port: 0, host: '127.0.0.1' });
69
+ const boundPort = server.server.address().port;
70
+ const res = await fetch(`${baseUrl}/info-app/now`);
71
+ assert.strictEqual(res.status, 200);
72
+ const { atActivate, now } = await res.json();
73
+ assert.strictEqual(now.listening, true);
74
+ assert.strictEqual(now.port, boundPort);
75
+ assert.strictEqual(now.baseUrl, `http://127.0.0.1:${boundPort}`);
76
+ assert.strictEqual(now.protocol, 'http');
77
+ // At activate time the server wasn't listening yet; the configured
78
+ // port 0 is reported as-is rather than masked by a default.
79
+ assert.strictEqual(atActivate.listening, false);
80
+ assert.strictEqual(atActivate.port, 0);
81
+ });
82
+
83
+ it('0.0.0.0 binds report localhost as the callable host', async () => {
84
+ await start({ port: 0, host: '0.0.0.0' });
85
+ const boundPort = server.server.address().port;
86
+ const res = await fetch(`http://127.0.0.1:${boundPort}/info-app/now`);
87
+ const { now } = await res.json();
88
+ assert.strictEqual(now.host, 'localhost');
89
+ assert.strictEqual(now.baseUrl, `http://localhost:${boundPort}`);
90
+ });
91
+
92
+ it('the live bind wins over the configured host once listening', async () => {
93
+ // Configured 0.0.0.0 but actually bound to 127.0.0.1 — the live
94
+ // address is the one a caller can use, so it must win.
95
+ await start({ host: '0.0.0.0' }, '127.0.0.1');
96
+ const res = await fetch(`${baseUrl}/info-app/now`);
97
+ const { now } = await res.json();
98
+ assert.strictEqual(now.host, '127.0.0.1');
99
+ assert.strictEqual(now.baseUrl, `http://127.0.0.1:${server.server.address().port}`);
100
+ });
101
+
102
+ it('an explicit idpIssuer wins as the canonical public baseUrl', async () => {
103
+ await start({ port: 0, host: '127.0.0.1', idpIssuer: 'https://pods.example/' });
104
+ const res = await fetch(`${baseUrl}/info-app/now`);
105
+ const { now } = await res.json();
106
+ assert.strictEqual(now.baseUrl, 'https://pods.example');
107
+ // The live bind details stay available alongside the override.
108
+ assert.strictEqual(now.port, server.server.address().port);
109
+ });
110
+ });
@@ -229,6 +229,53 @@ describe('plugin loader (#206)', () => {
229
229
  );
230
230
  });
231
231
 
232
+ it('a generic basename (plugin.js/index.js) derives the parent dir, not "plugin" (#596)', async () => {
233
+ // The near-universal '<name>/plugin.js' convention: without this fallback
234
+ // every such file collides on the id 'plugin' (and 'index' for index.js).
235
+ assert.strictEqual(pluginId({ module: './relay/plugin.js' }), 'relay');
236
+ assert.strictEqual(pluginId({ module: '/abs/path/dashboard/plugin.js' }), 'dashboard');
237
+ assert.strictEqual(pluginId({ module: './chat/index.js' }), 'chat');
238
+ assert.strictEqual(pluginId({ module: './My-App/Plugin.mjs' }), 'my-app');
239
+ // A non-generic basename is unchanged (still the basename).
240
+ assert.strictEqual(pluginId({ module: './relay/relay.js' }), 'relay');
241
+ assert.strictEqual(pluginId({ module: '/some/machine/path/foo.js' }), 'foo');
242
+ // No usable parent → falls back to the basename; an explicit id still wins.
243
+ assert.strictEqual(pluginId({ module: './plugin.js' }), 'plugin');
244
+ assert.strictEqual(pluginId({ module: './relay/plugin.js', id: 'custom' }), 'custom');
245
+ // A parent directory whose own name ends in .js keeps it (only the FILE's
246
+ // extension is stripped, never the directory name) — so 'foo.js/' and
247
+ // 'foo/' don't both collapse to the same 'foo'.
248
+ assert.strictEqual(pluginId({ module: './foo.js/plugin.js' }), 'foo-js');
249
+ assert.strictEqual(pluginId({ module: './foo/plugin.js' }), 'foo');
250
+ });
251
+
252
+ it('two <name>/plugin.js files load together with no explicit ids (#596)', async () => {
253
+ // The exact case that failed before: the CLI '--plugin' form (which can't
254
+ // set an id) loading two conventionally-named plugins.
255
+ await fs.emptyDir(`${FIXTURE_DIR}/alpha`);
256
+ await fs.emptyDir(`${FIXTURE_DIR}/beta`);
257
+ await fs.writeFile(`${FIXTURE_DIR}/alpha/plugin.js`,
258
+ `export async function activate(api) { api.fastify.get('/alpha/ping', async () => ({ id: 'alpha' })); }`);
259
+ await fs.writeFile(`${FIXTURE_DIR}/beta/plugin.js`,
260
+ `export async function activate(api) { api.fastify.get('/beta/ping', async () => ({ id: 'beta' })); }`);
261
+
262
+ await fs.emptyDir(TEST_DATA_DIR);
263
+ server = createServer({
264
+ logger: false,
265
+ forceCloseConnections: true,
266
+ root: TEST_DATA_DIR,
267
+ plugins: [
268
+ { module: `${FIXTURE_DIR}/alpha/plugin.js`, prefix: '/alpha' },
269
+ { module: `${FIXTURE_DIR}/beta/plugin.js`, prefix: '/beta' },
270
+ ],
271
+ });
272
+ // Boots (ids 'alpha' and 'beta', no collision) and both routes answer.
273
+ await server.listen({ port: 0, host: '127.0.0.1' });
274
+ const url = `http://127.0.0.1:${server.server.address().port}`;
275
+ assert.strictEqual((await (await fetch(`${url}/alpha/ping`)).json()).id, 'alpha');
276
+ assert.strictEqual((await (await fetch(`${url}/beta/ping`)).json()).id, 'beta');
277
+ });
278
+
232
279
  it('an invalid prefix fails listen() loudly', async () => {
233
280
  // Any provided prefix must validate — including falsy ones, which would
234
281
  // otherwise mount the app without its WAC exemption.