javascript-solid-server 0.0.217 → 0.0.218

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.
@@ -424,12 +424,58 @@ Each entry:
424
424
  `activate(api)` receives: `api.fastify` (register routes here),
425
425
  `api.prefix`, `api.config`, `api.log`, `api.auth.getAgent(request)`
426
426
  (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 —
427
+ directory under the data root, never served over HTTP),
428
+ `api.serverInfo()` → `{ baseUrl, protocol, host, port, listening }` (the
429
+ server's own origin, for minting absolute URLs and loopback calls — call
430
+ it lazily, e.g. per request: with `port: 0` the real port exists only once
431
+ the server is listening, and an explicit `idpIssuer` wins as `baseUrl`),
432
+ `api.plugins` → `[{ id, prefix, module }]` for every loaded entry (a
433
+ read-only, frozen boot-time snapshot, so a plugin can enumerate its
434
+ co-loaded siblings instead of being handed a copy of the operator's
435
+ plugins array — it includes the plugin itself, so consumers filter),
436
+ and `api.ws.route(path, (socket, request) => {})` for WebSocket endpoints —
429
437
  routed through the same upgrade path as the built-in realtime features, so
430
438
  plugins never attach their own `'upgrade'` listener. Return
431
439
  `{ deactivate }` to run teardown (state saves, timers) on server close.
432
440
 
441
+ A plugin whose protocol **pins absolute paths** outside its prefix can
442
+ claim them with `api.reservePath(path)`:
443
+
444
+ ```js
445
+ api.reservePath('/xrpc', { methods: ['GET', 'POST'] }); // fixed root — subtree, methods opted in
446
+ api.reservePath('/:user/did.json'); // pinned document — exact shape, read-only
447
+ ```
448
+
449
+ Both kinds are **read-only by default** (`GET`/`HEAD`/`OPTIONS`; widen with
450
+ `{ methods: [...] }`) — a reserved path is WAC-exempt and the LDP write
451
+ wildcards sit beneath it, so exempting a write method the plugin hasn't
452
+ implemented would let that write fall through to storage unauthenticated.
453
+ Literal reservations claim their whole subtree; parameterized reservations
454
+ (`:name` matches one segment) match only the exact path shape, since they
455
+ exist for pinned documents inside the pod's WAC-governed namespace. Claims
456
+ are cross-plugin: a second plugin reserving the same path fails the boot
457
+ naming both claimants. Registering routes on the reserved paths remains the
458
+ plugin's job via `api.fastify`.
459
+
460
+ To mount an **existing node-style app** — a `(req, res)` handler, a reverse
461
+ proxy, or a framework adapter — use `api.mountApp(handler, { prefix })`:
462
+
463
+ ```js
464
+ export async function activate(api) {
465
+ const app = createMyNodeApp();
466
+ await api.mountApp((req, res) => app.handle(req, res));
467
+ }
468
+ ```
469
+
470
+ `mountApp` bundles the four things a wrapped-app plugin needs and would
471
+ otherwise rediscover: the appPaths WAC exemption, a **scoped pass-through
472
+ content parser** (so the wrapped app receives an unconsumed body stream
473
+ instead of one Fastify already drained — the failure that hangs any
474
+ body-reading app), `reply.hijack()` so Fastify releases the response, and
475
+ registration on both the bare prefix and its subtree. It defaults to the
476
+ entry's `prefix`; pass `{ prefix }` to mount a second app elsewhere (that
477
+ prefix is WAC-exempted too).
478
+
433
479
  A plugin that fails to import or activate fails `listen()` loudly rather
434
480
  than booting a server silently missing an app.
435
481
 
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.218",
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 '';
@@ -102,6 +158,35 @@ export function pluginId(spec) {
102
158
  export async function loadPlugins(fastify, entries, ctx) {
103
159
  const log = makePluginLog(ctx.log);
104
160
  const seenIds = new Set();
161
+ // reservePath claims (#602), shared across all entries of this load so
162
+ // two plugins reserving the same pinned path fail the boot with both
163
+ // names — loud beats the silent-loser outcome witnessed with webfinger
164
+ // vs remotestorage.
165
+ const reservations = new Map();
166
+
167
+ // Read-only roster of every loaded entry (#610): { id, prefix, module }
168
+ // for each. Computed up front, before any activate() runs, so a plugin
169
+ // whose job is describing the deployment (a status dashboard, an admin
170
+ // console) sees the FULL set regardless of load order — rather than being
171
+ // hand-fed a duplicate of the operator's plugins array that silently
172
+ // drifts. Frozen so one plugin can't mutate another's view; it includes
173
+ // the plugin itself (consumers filter). Lenient here (never throws) — the
174
+ // load loop below owns validation and fails the boot on a bad entry, so
175
+ // on any successful boot every id/prefix matches what the loop derives.
176
+ // A boot-time snapshot: there is no runtime add/remove yet.
177
+ const roster = Object.freeze(entries.map((entry) => {
178
+ const spec = typeof entry === 'string' ? { module: entry } : (entry ?? {});
179
+ // Only surface a well-formed module — a non-string/empty one makes the
180
+ // load loop below fail the boot, so don't fabricate a coerced value
181
+ // (e.g. "[object Object]") for the transient pre-failure window. Mirrors
182
+ // the loop's own `typeof spec.module === 'string'` gate; id is derived
183
+ // only from a valid module.
184
+ const module = typeof spec.module === 'string' && spec.module ? spec.module : null;
185
+ let id = null;
186
+ try { if (module) id = pluginId(spec); } catch { /* the loop reports it */ }
187
+ return Object.freeze({ id, prefix: normalizePrefix(spec.prefix), module });
188
+ }));
189
+
105
190
  for (const entry of entries) {
106
191
  const spec = typeof entry === 'string' ? { module: entry } : entry;
107
192
  if (!spec || typeof spec.module !== 'string' || !spec.module) {
@@ -152,6 +237,153 @@ export async function loadPlugins(fastify, entries, ctx) {
152
237
  return dir;
153
238
  },
154
239
  },
240
+ // The server's own origin (#601) — for minting absolute URLs and
241
+ // loopback calls, so plugins stop repeating baseUrl in config where
242
+ // a wrong value fails quietly. A function, not a snapshot: with
243
+ // port 0 the real port exists only once the server is listening,
244
+ // so call it lazily (per request, or in an onListen hook via
245
+ // api.fastify) rather than caching the result during activate.
246
+ // An explicit idpIssuer is the deployment's canonical public origin
247
+ // and wins over the host:port derivation, mirroring the pod-seeding
248
+ // logic in server.js.
249
+ // Reserve a path the protocol pins outside the plugin's prefix
250
+ // (#602): fixed roots like /xrpc or /_matrix (literal — exempts the
251
+ // subtree), or parameterized documents like /:user/did.json
252
+ // (exact-shape match only; see compilePathPattern). Both are
253
+ // read-only by default and method-gated ({ methods } to widen) —
254
+ // see the exemption note below. The claim is deliberate and
255
+ // cross-plugin: a second plugin reserving the same path fails the
256
+ // boot naming both claimants, instead of one silently losing.
257
+ // Registering the routes is still the plugin's job via api.fastify.
258
+ reservePath(p, opts = {}) {
259
+ // Tolerate a null/garbage opts (treat as omitted), but a provided
260
+ // non-array `methods` is a caller mistake worth a targeted error
261
+ // rather than an opaque TypeError from .map deep in activate.
262
+ const options = opts && typeof opts === 'object' ? opts : {};
263
+ if (options.methods !== undefined && !Array.isArray(options.methods)) {
264
+ throw new Error(`plugin ${id}: reservePath { methods } must be an array, got ${JSON.stringify(options.methods)}`);
265
+ }
266
+ // Validate AFTER normalization: '//' or '/ ' normalize to '',
267
+ // and an empty string in appPaths would match every URL in the
268
+ // WAC hook — a one-call total WAC bypass.
269
+ const key = typeof p === 'string' ? p.trim().replace(/\/+$/, '') : '';
270
+ if (!key.startsWith('/') || key.length < 2) {
271
+ throw new Error(`plugin ${id}: reservePath needs an absolute path, got ${JSON.stringify(p)}`);
272
+ }
273
+ // A reservation is a pathname, not a URL: '?'/'#' don't belong.
274
+ // A query in the string would be escaped into the matcher (tying
275
+ // the exemption to that exact query), and fragments never reach
276
+ // request.url — both silently produce a reservation that matches
277
+ // nothing real.
278
+ if (key.includes('?') || key.includes('#')) {
279
+ throw new Error(`plugin ${id}: reservePath must be a pathname without '?' or '#', got ${JSON.stringify(p)}`);
280
+ }
281
+ // Track by the shape, not the raw string: '/:user/did.json' and
282
+ // '/:acct/did.json' exempt the same URLs, so they're the same
283
+ // claim and must collide loudly like two literal reservations.
284
+ const claim = reservationKey(key);
285
+ const holder = reservations.get(claim);
286
+ if (holder === id) {
287
+ return; // idempotent re-claim — the matcher is already installed
288
+ }
289
+ if (holder) {
290
+ throw new Error(`plugin ${id}: path '${key}' is already reserved by plugin '${holder}'`);
291
+ }
292
+ reservations.set(claim, id);
293
+ // Read-only by default for BOTH lanes: a reserved path is
294
+ // WAC-exempt, and the LDP write wildcards (PUT/POST/PATCH/DELETE
295
+ // '/*') sit underneath it. Exempting a write method the plugin
296
+ // has NOT implemented would let that write fall through to the
297
+ // LDP handlers as an unauthenticated storage write — the exact
298
+ // trap core installs 405 blocks for under /.well-known/*. Widen
299
+ // with { methods } when the protocol genuinely needs writes.
300
+ const methods = new Set((options.methods ?? ['GET', 'HEAD', 'OPTIONS'])
301
+ .map((m) => String(m).toUpperCase()));
302
+ // Parameterized shapes match exactly (they live inside a
303
+ // WAC-governed pod namespace); literals claim their subtree.
304
+ const re = isParamPath(key) ? compilePathPattern(key) : compileSubtreePattern(key);
305
+ ctx.appPathPatterns?.push({ re, methods });
306
+ log.info(`plugin ${id} reserved ${key} [${[...methods].join(', ')}]`);
307
+ },
308
+ serverInfo() {
309
+ const o = ctx.origin ?? {};
310
+ const addr = fastify.server?.listening ? fastify.server.address() : null;
311
+ const live = addr && typeof addr === 'object' ? addr : null;
312
+ // Once listening, the live bind wins over configured values —
313
+ // listen() may be called with a different host/port than
314
+ // createServer() was given (tests do exactly this).
315
+ const port = live?.port ?? o.port ?? null;
316
+ const rawHost = live?.address ?? o.host;
317
+ // Unspecified binds aren't callable addresses; report the
318
+ // loopback name instead. IPv6 literals need brackets in URLs.
319
+ const host = !rawHost || rawHost === '0.0.0.0' || rawHost === '::' ? 'localhost' : rawHost;
320
+ const protocol = o.ssl ? 'https' : 'http';
321
+ const urlHost = host.includes(':') ? `[${host}]` : host;
322
+ const baseUrl = o.baseUrl || `${protocol}://${urlHost}:${port}`;
323
+ return { baseUrl, protocol, host, port, listening: !!live };
324
+ },
325
+ // Every loaded plugin's { id, prefix, module } (#610), read-only — so
326
+ // a plugin can enumerate its co-loaded siblings instead of being
327
+ // handed a copy of the operator's plugins array. Includes this
328
+ // plugin; consumers filter themselves out. A frozen boot-time
329
+ // snapshot (see `roster` above).
330
+ plugins: roster,
331
+ // Mount a node-style (req, res) handler — a wrapped HTTP app, reverse
332
+ // proxy, or framework adapter — under the plugin's prefix (#583). This
333
+ // bundles the four things every such plugin needs and otherwise
334
+ // rediscovers: the appPaths WAC exemption (already applied above), a
335
+ // scoped pass-through content parser so the wrapped app receives an
336
+ // unconsumed body stream, reply.hijack() so Fastify releases the
337
+ // response, and registration on both the bare prefix and its subtree.
338
+ // Without the scoped parser, Fastify drains the request stream before
339
+ // the handler runs and any body-reading app hangs forever.
340
+ async mountApp(handler, opts = {}) {
341
+ if (typeof handler !== 'function') {
342
+ throw new Error(`plugin ${id}: mountApp(handler) needs a (req, res) function`);
343
+ }
344
+ // Any provided prefix must validate — same rule as entry.prefix: a
345
+ // falsy normalization silently falling back to the entry prefix
346
+ // would mount the app (and WAC-exempt it) somewhere unexpected.
347
+ const secondary = normalizePrefix(opts.prefix);
348
+ if (opts.prefix !== undefined && !secondary) {
349
+ throw new Error(`plugin ${id}: mountApp invalid prefix ${JSON.stringify(opts.prefix)} (must start with '/'; omit to use the entry prefix)`);
350
+ }
351
+ const mountPrefix = secondary || prefix;
352
+ if (!mountPrefix) {
353
+ throw new Error(`plugin ${id}: mountApp needs a prefix (entry.prefix or opts.prefix)`);
354
+ }
355
+ if (mountPrefix !== prefix && !ctx.appPaths.includes(mountPrefix)) {
356
+ ctx.appPaths.push(mountPrefix); // exempt a secondary mount too
357
+ }
358
+ await fastify.register(async (scope) => {
359
+ scope.removeAllContentTypeParsers();
360
+ scope.addContentTypeParser('*', (req, payload, done) => done(null, payload));
361
+ // After hijack() Fastify sends nothing, so a handler bug must not
362
+ // hang the client or become an unhandled rejection (same contract
363
+ // as ws.route below): log, answer 500 if nothing went out yet,
364
+ // else drop the one affected socket.
365
+ const fail = (res, err) => {
366
+ log.error({ err }, `plugin ${id}: mounted app handler failed`);
367
+ if (!res.headersSent && !res.writableEnded) {
368
+ res.statusCode = 500;
369
+ res.end();
370
+ } else {
371
+ res.destroy();
372
+ }
373
+ };
374
+ const wrapped = (request, reply) => {
375
+ reply.hijack();
376
+ try {
377
+ Promise.resolve(handler(request.raw, reply.raw))
378
+ .catch((err) => fail(reply.raw, err));
379
+ } catch (err) {
380
+ fail(reply.raw, err);
381
+ }
382
+ };
383
+ scope.all(mountPrefix, wrapped);
384
+ scope.all(mountPrefix + '/*', wrapped);
385
+ });
386
+ },
155
387
  ws: {
156
388
  async route(wsPath, handler) {
157
389
  if (typeof wsPath !== 'string' || !wsPath.startsWith('/')) {
@@ -168,11 +400,11 @@ export async function loadPlugins(fastify, entries, ctx) {
168
400
  // takes the host down: log it and close the one affected socket.
169
401
  try {
170
402
  Promise.resolve(handler(socket, request)).catch((err) => {
171
- log.error(`plugin ${id}: ws handler failed: ${err.message}`);
403
+ log.error({ err }, `plugin ${id}: ws handler failed`);
172
404
  socket.terminate?.();
173
405
  });
174
406
  } catch (err) {
175
- log.error(`plugin ${id}: ws handler failed: ${err.message}`);
407
+ log.error({ err }, `plugin ${id}: ws handler failed`);
176
408
  socket.terminate?.();
177
409
  }
178
410
  });
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
+ });