javascript-solid-server 0.0.218 → 0.0.220

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,9 +417,12 @@ 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)`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "javascript-solid-server",
3
- "version": "0.0.218",
3
+ "version": "0.0.220",
4
4
  "description": "A minimal, fast Solid server",
5
5
  "main": "src/index.js",
6
6
  "type": "module",
@@ -492,13 +492,26 @@ export async function resolveDidNostrLocally(pubkeyHex) {
492
492
  * Multikey value is computed deterministically from the pubkey via
493
493
  * the f-form recipe (multibase `f` + multicodec `e701` + parity byte
494
494
  * `02` + 32-byte xonly hex) — the same shape the doctor's B.2 emits.
495
+ *
496
+ * `@context` MUST lead with the DID Core context — DID Core requires
497
+ * the first value to be `https://www.w3.org/ns/did/v1`, and did:nostr
498
+ * 0.1.1 adopted that ordering (nostrcg/did-nostr#136, fixed by #139).
499
+ * `cid/v1` still follows it, because this document's Multikey
500
+ * verification method comes from the Controlled Identifiers
501
+ * vocabulary. The ordering is normative only for DID documents, so
502
+ * standalone CID resources (src/keys/provision.js) and WebID profiles
503
+ * (src/webid/profile.js) correctly keep `cid/v1` alone.
495
504
  */
496
505
  function buildDidDocument({ pubkey, webId }) {
497
506
  const did = `did:nostr:${pubkey.toLowerCase()}`;
498
507
  const multikey = `f` + `e701` + `02` + pubkey.toLowerCase();
499
508
  const vmId = `${did}#key1`;
500
509
  return {
501
- '@context': ['https://www.w3.org/ns/cid/v1', 'https://w3id.org/nostr/context'],
510
+ '@context': [
511
+ 'https://www.w3.org/ns/did/v1',
512
+ 'https://www.w3.org/ns/cid/v1',
513
+ 'https://w3id.org/nostr/context',
514
+ ],
502
515
  'id': did,
503
516
  'type': 'DIDNostr',
504
517
  'alsoKnownAs': [webId],
package/src/plugins.js CHANGED
@@ -123,11 +123,37 @@ export function normalizePrefix(p) {
123
123
  return trimmed.startsWith('/') && trimmed.length > 1 ? trimmed : '';
124
124
  }
125
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
+
126
151
  /**
127
152
  * Directory-safe plugin id: entry.id, or derived from the module spec.
128
153
  * Bare package specifiers keep their full path ('@scope/pkg/plugin.js' ->
129
154
  * 'scope-pkg-plugin') so same-named files in different packages don't
130
- * 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
131
157
  * directory prefix must not name the plugin's data dir (the id — and with
132
158
  * it pluginDir — would change whenever the deployment moves). The loader
133
159
  * additionally rejects duplicate ids, so any residual collision fails the
@@ -135,12 +161,17 @@ export function normalizePrefix(p) {
135
161
  */
136
162
  export function pluginId(spec) {
137
163
  const module = String(spec.module);
138
- const raw = typeof spec.id === 'string' && spec.id
139
- ? spec.id
140
- : (module.startsWith('.') || path.isAbsolute(module)
141
- ? path.basename(module)
142
- : module
143
- ).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
+ }
144
175
  const id = raw.toLowerCase().replace(/[^a-z0-9_-]+/g, '-').replace(/^-+|-+$/g, '');
145
176
  if (!id) throw new Error(`plugins: cannot derive an id from ${JSON.stringify(spec.module)}; set entry.id`);
146
177
  return id;
package/src/server.js CHANGED
@@ -578,6 +578,14 @@ export function createServer(options = {}) {
578
578
  return;
579
579
  }
580
580
 
581
+ // App plugins own their prefix (#206) — a plugin mounted at a dot path
582
+ // (e.g. the webrtc plugin at /.webrtc, matching core's historical URL)
583
+ // must stay reachable, exactly as the WAC hook already defers to
584
+ // appPaths. Read per request: plugin activation pushes entries.
585
+ if (appPaths.some(p => urlNoQuery === p || urlNoQuery.startsWith(p + '/'))) {
586
+ return;
587
+ }
588
+
581
589
  // Only inspect the path component — splitting the full URL on '/'
582
590
  // would catch dot-prefixed segments inside query-string values
583
591
  // (e.g. /proxy?url=https://example.com/.git/config), rejecting
@@ -177,6 +177,32 @@ describe('plugin loader (#206)', () => {
177
177
  assert.ok([401, 403].includes(res.status), `expected WAC rejection, got ${res.status}`);
178
178
  });
179
179
 
180
+ it('a plugin mounted at a dot prefix stays reachable (dotfile guard defers to the mount)', async () => {
181
+ // The webrtc plugin replaces core's wss://pod/.webrtc at the same URL,
182
+ // so a dot prefix must reach the app — HTTP and ws.route alike — while
183
+ // unrelated dotfiles keep the 403 guard.
184
+ await startWith([
185
+ { module: `${FIXTURE_DIR}/fixture-plugin.js`, prefix: '/.myapp' },
186
+ ]);
187
+ const res = await fetch(`${baseUrl}/.myapp/echo`, { method: 'POST' });
188
+ assert.strictEqual(res.status, 200);
189
+ assert.strictEqual((await res.json()).app, true);
190
+ const ws = new WebSocket(`${baseUrl.replace('http', 'ws')}/.myapp/ws`);
191
+ await new Promise((resolve, reject) => {
192
+ ws.on('open', resolve);
193
+ ws.on('error', reject);
194
+ });
195
+ const reply = await new Promise((resolve, reject) => {
196
+ ws.on('message', (data) => resolve(String(data)));
197
+ ws.on('error', reject);
198
+ ws.send('hello');
199
+ });
200
+ assert.strictEqual(reply, 'pong:hello');
201
+ ws.close();
202
+ const guarded = await fetch(`${baseUrl}/.env`);
203
+ assert.strictEqual(guarded.status, 403);
204
+ });
205
+
180
206
  it('a plugin that cannot be imported fails listen() loudly', async () => {
181
207
  await fs.emptyDir(TEST_DATA_DIR);
182
208
  server = createServer({
@@ -229,6 +255,53 @@ describe('plugin loader (#206)', () => {
229
255
  );
230
256
  });
231
257
 
258
+ it('a generic basename (plugin.js/index.js) derives the parent dir, not "plugin" (#596)', async () => {
259
+ // The near-universal '<name>/plugin.js' convention: without this fallback
260
+ // every such file collides on the id 'plugin' (and 'index' for index.js).
261
+ assert.strictEqual(pluginId({ module: './relay/plugin.js' }), 'relay');
262
+ assert.strictEqual(pluginId({ module: '/abs/path/dashboard/plugin.js' }), 'dashboard');
263
+ assert.strictEqual(pluginId({ module: './chat/index.js' }), 'chat');
264
+ assert.strictEqual(pluginId({ module: './My-App/Plugin.mjs' }), 'my-app');
265
+ // A non-generic basename is unchanged (still the basename).
266
+ assert.strictEqual(pluginId({ module: './relay/relay.js' }), 'relay');
267
+ assert.strictEqual(pluginId({ module: '/some/machine/path/foo.js' }), 'foo');
268
+ // No usable parent → falls back to the basename; an explicit id still wins.
269
+ assert.strictEqual(pluginId({ module: './plugin.js' }), 'plugin');
270
+ assert.strictEqual(pluginId({ module: './relay/plugin.js', id: 'custom' }), 'custom');
271
+ // A parent directory whose own name ends in .js keeps it (only the FILE's
272
+ // extension is stripped, never the directory name) — so 'foo.js/' and
273
+ // 'foo/' don't both collapse to the same 'foo'.
274
+ assert.strictEqual(pluginId({ module: './foo.js/plugin.js' }), 'foo-js');
275
+ assert.strictEqual(pluginId({ module: './foo/plugin.js' }), 'foo');
276
+ });
277
+
278
+ it('two <name>/plugin.js files load together with no explicit ids (#596)', async () => {
279
+ // The exact case that failed before: the CLI '--plugin' form (which can't
280
+ // set an id) loading two conventionally-named plugins.
281
+ await fs.emptyDir(`${FIXTURE_DIR}/alpha`);
282
+ await fs.emptyDir(`${FIXTURE_DIR}/beta`);
283
+ await fs.writeFile(`${FIXTURE_DIR}/alpha/plugin.js`,
284
+ `export async function activate(api) { api.fastify.get('/alpha/ping', async () => ({ id: 'alpha' })); }`);
285
+ await fs.writeFile(`${FIXTURE_DIR}/beta/plugin.js`,
286
+ `export async function activate(api) { api.fastify.get('/beta/ping', async () => ({ id: 'beta' })); }`);
287
+
288
+ await fs.emptyDir(TEST_DATA_DIR);
289
+ server = createServer({
290
+ logger: false,
291
+ forceCloseConnections: true,
292
+ root: TEST_DATA_DIR,
293
+ plugins: [
294
+ { module: `${FIXTURE_DIR}/alpha/plugin.js`, prefix: '/alpha' },
295
+ { module: `${FIXTURE_DIR}/beta/plugin.js`, prefix: '/beta' },
296
+ ],
297
+ });
298
+ // Boots (ids 'alpha' and 'beta', no collision) and both routes answer.
299
+ await server.listen({ port: 0, host: '127.0.0.1' });
300
+ const url = `http://127.0.0.1:${server.server.address().port}`;
301
+ assert.strictEqual((await (await fetch(`${url}/alpha/ping`)).json()).id, 'alpha');
302
+ assert.strictEqual((await (await fetch(`${url}/beta/ping`)).json()).id, 'beta');
303
+ });
304
+
232
305
  it('an invalid prefix fails listen() loudly', async () => {
233
306
  // Any provided prefix must validate — including falsy ones, which would
234
307
  // otherwise mount the app without its WAC exemption.
@@ -129,7 +129,11 @@ describe('GET /.well-known/did/nostr/:pubkey (#407)', () => {
129
129
  assert.ok(r.headers.get('last-modified'));
130
130
 
131
131
  const doc = await r.json();
132
- assert.deepStrictEqual(doc['@context'], ['https://www.w3.org/ns/cid/v1', 'https://w3id.org/nostr/context']);
132
+ assert.deepStrictEqual(doc['@context'], [
133
+ 'https://www.w3.org/ns/did/v1',
134
+ 'https://www.w3.org/ns/cid/v1',
135
+ 'https://w3id.org/nostr/context',
136
+ ]);
133
137
  assert.strictEqual(doc.id, `did:nostr:${alicePk}`);
134
138
  assert.strictEqual(doc.type, 'DIDNostr');
135
139
  assert.ok(Array.isArray(doc.alsoKnownAs));
@@ -139,6 +143,26 @@ describe('GET /.well-known/did/nostr/:pubkey (#407)', () => {
139
143
  assert.strictEqual(doc.authentication[0], `did:nostr:${alicePk}#key1`);
140
144
  });
141
145
 
146
+ it('leads @context with the DID Core context (did:nostr 0.1.1)', async () => {
147
+ // DID Core requires a DID document's @context to lead with
148
+ // https://www.w3.org/ns/did/v1; did:nostr 0.1.1 adopted that ordering
149
+ // (nostrcg/did-nostr#136 → #139). Asserted separately from the
150
+ // full-shape check above so a reordering regression names itself.
151
+ const r = await fetch(`${baseUrl}/.well-known/did/nostr/${alicePk}.json`);
152
+ assert.strictEqual(r.status, 200);
153
+ const doc = await r.json();
154
+ // Assert the shape before indexing, so a dropped @context fails with
155
+ // this message rather than a TypeError.
156
+ const ctx = doc['@context'];
157
+ assert.ok(Array.isArray(ctx), '@context must be present and an array');
158
+ assert.strictEqual(ctx[0], 'https://www.w3.org/ns/did/v1',
159
+ '@context must lead with the DID Core context');
160
+ // The CID context must still be present — the document's Multikey
161
+ // verification method is drawn from that vocabulary.
162
+ assert.ok(ctx.includes('https://www.w3.org/ns/cid/v1'),
163
+ '@context must still include the CID v1 context');
164
+ });
165
+
142
166
  it('accepts the .jsonld suffix (alias)', async () => {
143
167
  const r = await fetch(`${baseUrl}/.well-known/did/nostr/${alicePk}.jsonld`);
144
168
  assert.strictEqual(r.status, 200);