javascript-solid-server 0.0.208 → 0.0.210
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/jss.js +22 -2
- package/package.json +2 -1
- package/src/auth/nostr.js +31 -7
- package/src/idp/well-known-did-nostr.js +1 -1
- package/src/mcp/tools.js +58 -14
- package/src/server.js +37 -0
- package/src/utils/port.js +66 -0
- package/test/mcp.test.js +38 -1
- package/test/nip98-payload-hash.test.js +182 -0
- package/test/port-shift-cli.test.js +114 -0
- package/test/port.test.js +98 -0
- package/test/well-known-did-nostr.test.js +1 -1
package/bin/jss.js
CHANGED
|
@@ -16,6 +16,7 @@ import { createInvite, listInvites, revokeInvite } from '../src/idp/invites.js';
|
|
|
16
16
|
import { findByUsername, updatePassword, deleteAccount } from '../src/idp/accounts.js';
|
|
17
17
|
import { setQuotaLimit, getQuotaInfo, reconcileQuota, formatBytes } from '../src/storage/quota.js';
|
|
18
18
|
import { parseSize } from '../src/config.js';
|
|
19
|
+
import { findFreePort, formatUrl } from '../src/utils/port.js';
|
|
19
20
|
import crypto from 'crypto';
|
|
20
21
|
import fs from 'fs-extra';
|
|
21
22
|
import path from 'path';
|
|
@@ -176,10 +177,29 @@ program
|
|
|
176
177
|
process.exit(0);
|
|
177
178
|
}
|
|
178
179
|
|
|
180
|
+
// If the requested port is busy, shift up to the next free one
|
|
181
|
+
// (Vite-style), rather than dying on a raw EADDRINUSE — a common
|
|
182
|
+
// first-run papercut when a stale instance is still running (#557).
|
|
183
|
+
// Must run BEFORE the issuer/baseUrl are derived so they reflect
|
|
184
|
+
// the port we actually bind. The notice goes to stderr so it
|
|
185
|
+
// surfaces even under --quiet (a port change the operator didn't
|
|
186
|
+
// ask for is operationally significant).
|
|
187
|
+
const requestedPort = config.port;
|
|
188
|
+
const boundPort = await findFreePort(requestedPort, config.host);
|
|
189
|
+
if (boundPort === null) {
|
|
190
|
+
console.error(
|
|
191
|
+
`Error: no free port found in ${requestedPort}–${requestedPort + 9} on ${config.host}.`
|
|
192
|
+
);
|
|
193
|
+
process.exit(1);
|
|
194
|
+
}
|
|
195
|
+
if (boundPort !== requestedPort) {
|
|
196
|
+
console.error(` Port ${requestedPort} is in use — using ${boundPort} instead.`);
|
|
197
|
+
config.port = boundPort;
|
|
198
|
+
}
|
|
199
|
+
|
|
179
200
|
// Determine IdP issuer URL
|
|
180
201
|
const protocol = config.ssl ? 'https' : 'http';
|
|
181
|
-
const
|
|
182
|
-
const baseUrl = `${protocol}://${serverHost}:${config.port}`;
|
|
202
|
+
const baseUrl = formatUrl(config.host, config.port, protocol);
|
|
183
203
|
// Ensure issuer has trailing slash for CTH compatibility
|
|
184
204
|
let idpIssuer = config.idpIssuer || baseUrl;
|
|
185
205
|
if (idpIssuer && !idpIssuer.endsWith('/')) {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "javascript-solid-server",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.210",
|
|
4
4
|
"description": "A minimal, fast Solid server",
|
|
5
5
|
"main": "src/index.js",
|
|
6
6
|
"type": "module",
|
|
@@ -39,6 +39,7 @@
|
|
|
39
39
|
"mime-types": "^2.1.35",
|
|
40
40
|
"n3": "^1.26.0",
|
|
41
41
|
"oidc-provider": "^9.6.0",
|
|
42
|
+
"secure-json-parse": "^2.7.0",
|
|
42
43
|
"sql.js": "^1.13.0",
|
|
43
44
|
"tar-stream": "^3.2.0"
|
|
44
45
|
},
|
package/src/auth/nostr.js
CHANGED
|
@@ -243,17 +243,41 @@ export async function verifyNostrAuth(request) {
|
|
|
243
243
|
|
|
244
244
|
// Validate payload hash if present and request has body
|
|
245
245
|
const payloadTag = getTagValue(event, 'payload');
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
246
|
+
// Validate whenever a payload tag is present AND a body was provided —
|
|
247
|
+
// keyed on `!== undefined`, not truthiness, so a JSON body that parses
|
|
248
|
+
// to a falsy value (`null`, `false`, `0`, `""`) is still hash-checked
|
|
249
|
+
// rather than silently skipping the integrity guard (Copilot review on
|
|
250
|
+
// #573). Fastify leaves request.body `undefined` when no body was sent.
|
|
251
|
+
if (payloadTag && request.body !== undefined) {
|
|
252
|
+
// Hash the EXACT bytes the client signed. NIP-98's `payload` tag is
|
|
253
|
+
// sha256(request body) over the wire bytes. crypto.update() accepts a
|
|
254
|
+
// string (encoded UTF-8) or a Buffer (raw bytes), so we pass each
|
|
255
|
+
// through in its native form — never a lossy conversion.
|
|
256
|
+
let bodyData;
|
|
257
|
+
if (typeof request.rawBody === 'string') {
|
|
258
|
+
// application/json raw wire string captured by the parser (#565),
|
|
259
|
+
// because by this point request.body is already a parsed object and
|
|
260
|
+
// the original bytes are gone. Re-serializing the object (the old
|
|
261
|
+
// fallback) only matched when the client happened to send minified
|
|
262
|
+
// JSON in Node's exact key order — pretty-printed or differently-
|
|
263
|
+
// escaped bodies 401'd despite a valid signature. (JSON is UTF-8 by
|
|
264
|
+
// spec, so the captured string round-trips losslessly.)
|
|
265
|
+
bodyData = request.rawBody;
|
|
266
|
+
} else if (typeof request.body === 'string') {
|
|
267
|
+
bodyData = request.body;
|
|
250
268
|
} else if (Buffer.isBuffer(request.body)) {
|
|
251
|
-
|
|
269
|
+
// Hash the Buffer DIRECTLY. A .toString() round-trip UTF-8-mangles
|
|
270
|
+
// binary / non-UTF-8 bodies (e.g. an image PUT) and would cause
|
|
271
|
+
// false mismatches against the raw-byte hash the client signed.
|
|
272
|
+
bodyData = request.body;
|
|
252
273
|
} else {
|
|
253
|
-
|
|
274
|
+
// No raw bytes captured (shouldn't happen for HTTP requests:
|
|
275
|
+
// application/json sets rawBody, other types stay a Buffer). Keep a
|
|
276
|
+
// deterministic fallback rather than throwing.
|
|
277
|
+
bodyData = JSON.stringify(request.body);
|
|
254
278
|
}
|
|
255
279
|
|
|
256
|
-
const expectedHash = crypto.createHash('sha256').update(
|
|
280
|
+
const expectedHash = crypto.createHash('sha256').update(bodyData).digest('hex');
|
|
257
281
|
if (payloadTag.toLowerCase() !== expectedHash.toLowerCase()) {
|
|
258
282
|
return { webId: null, error: 'Payload hash mismatch' };
|
|
259
283
|
}
|
|
@@ -498,7 +498,7 @@ function buildDidDocument({ pubkey, webId }) {
|
|
|
498
498
|
const multikey = `f` + `e701` + `02` + pubkey.toLowerCase();
|
|
499
499
|
const vmId = `${did}#key1`;
|
|
500
500
|
return {
|
|
501
|
-
'@context': ['https://
|
|
501
|
+
'@context': ['https://www.w3.org/ns/cid/v1', 'https://w3id.org/nostr/context'],
|
|
502
502
|
'id': did,
|
|
503
503
|
'type': 'DIDNostr',
|
|
504
504
|
'alsoKnownAs': [webId],
|
package/src/mcp/tools.js
CHANGED
|
@@ -300,12 +300,22 @@ async function read_acl({ path }, ctx) {
|
|
|
300
300
|
});
|
|
301
301
|
}
|
|
302
302
|
|
|
303
|
-
function buildAclDoc(structured) {
|
|
303
|
+
function buildAclDoc(structured, targetRef, isContainer) {
|
|
304
304
|
const graph = structured.authorizations.map((auth, i) => {
|
|
305
305
|
const node = {
|
|
306
306
|
'@id': `#auth${i}`,
|
|
307
307
|
'@type': 'acl:Authorization',
|
|
308
|
-
|
|
308
|
+
// accessTo is a *relative* IRI; the parser resolves it against the
|
|
309
|
+
// ACL's base URL (parser.js getBaseUrl()), which is the parent
|
|
310
|
+
// container directory for BOTH container and resource ACLs. So './'
|
|
311
|
+
// resolves to that container — correct for a container ACL, but for a
|
|
312
|
+
// *resource* ACL it points at the parent container, not the resource,
|
|
313
|
+
// leaving checkAuthorizations() (which requires an exact accessTo
|
|
314
|
+
// match) with zero authorizations and locking out even the owner who
|
|
315
|
+
// just granted themselves Control (#575). targetRef is therefore './'
|
|
316
|
+
// for a container and './<basename>' for a resource. Relative IRIs
|
|
317
|
+
// keep stored ACLs host-portable across origins (#428).
|
|
318
|
+
'acl:accessTo': { '@id': targetRef },
|
|
309
319
|
'acl:mode': (auth.modes || []).map(m => ({ '@id': `acl:${m}` }))
|
|
310
320
|
};
|
|
311
321
|
if (auth.agents && auth.agents.length) {
|
|
@@ -316,8 +326,10 @@ function buildAclDoc(structured) {
|
|
|
316
326
|
'@id': fullAgentClass(c)
|
|
317
327
|
}));
|
|
318
328
|
}
|
|
319
|
-
|
|
320
|
-
|
|
329
|
+
// acl:default only has meaning on a container ACL (it supplies the
|
|
330
|
+
// defaults inherited by contained resources), where targetRef is './'.
|
|
331
|
+
if (auth.isDefault && isContainer) {
|
|
332
|
+
node['acl:default'] = { '@id': targetRef };
|
|
321
333
|
}
|
|
322
334
|
return node;
|
|
323
335
|
});
|
|
@@ -340,26 +352,50 @@ async function write_acl({ path, authorizations }, ctx) {
|
|
|
340
352
|
return toolError(`access denied: control ${path}`);
|
|
341
353
|
}
|
|
342
354
|
const aclPath = aclUrlFor(path);
|
|
343
|
-
const
|
|
355
|
+
const isContainer = path.endsWith('/');
|
|
356
|
+
// Relative target IRI for the stored ACL (host-portable, #428): './' for
|
|
357
|
+
// a container, './<basename>' for a resource. The parser resolves it
|
|
358
|
+
// against the ACL base URL (the parent container directory), so the
|
|
359
|
+
// basename lands on the resource.
|
|
360
|
+
const targetRef = isContainer
|
|
361
|
+
? './'
|
|
362
|
+
: './' + path.replace(/\/+$/, '').split('/').pop();
|
|
363
|
+
const targetUrl = buildUrl(ctx, path); // absolute, for the lockout check below
|
|
364
|
+
const doc = buildAclDoc({ authorizations }, targetRef, isContainer);
|
|
344
365
|
const serialized = serializeAcl(doc);
|
|
345
366
|
|
|
346
367
|
// Safety: refuse to write an ACL that would lock the caller out of
|
|
347
|
-
// future Control.
|
|
348
|
-
//
|
|
349
|
-
//
|
|
350
|
-
//
|
|
351
|
-
//
|
|
352
|
-
//
|
|
368
|
+
// future Control. Two footguns are covered:
|
|
369
|
+
// 1. relative WebID paths in `agents` resolving against the .acl URL
|
|
370
|
+
// to a different absolute URI than the caller's actual WebID;
|
|
371
|
+
// 2. an authorization whose `accessTo` does not actually cover this
|
|
372
|
+
// resource (e.g. #575), which the checker would skip entirely.
|
|
373
|
+
// Parse the proposed ACL with its real URL so relative refs resolve
|
|
374
|
+
// correctly, then require an authorization that both grants Control to
|
|
375
|
+
// the caller *and* applies to this target.
|
|
353
376
|
const aclAbsUrl = buildUrl(ctx, aclPath);
|
|
354
377
|
const proposed = await parseAcl(serialized, aclAbsUrl);
|
|
355
|
-
const
|
|
378
|
+
const normUrl = u => String(u).replace(/\/$/, '');
|
|
379
|
+
const grantsCallerControl = auth => {
|
|
356
380
|
if (!(auth.modes || []).includes(AccessMode.CONTROL)) return false;
|
|
357
381
|
if (ctx.webId && (auth.agents || []).includes(ctx.webId)) return true;
|
|
358
382
|
if ((auth.agentClasses || []).includes(FOAF_AGENT)) return true;
|
|
359
383
|
if (ctx.webId && (auth.agentClasses || []).includes(ACL_AUTH_AGENT)) return true;
|
|
360
384
|
return false;
|
|
361
|
-
}
|
|
362
|
-
|
|
385
|
+
};
|
|
386
|
+
const appliesToTarget = auth => {
|
|
387
|
+
const t = normUrl(targetUrl);
|
|
388
|
+
return (auth.accessTo || []).some(a => normUrl(a) === t) ||
|
|
389
|
+
(auth.default || []).some(d => {
|
|
390
|
+
const p = normUrl(d);
|
|
391
|
+
return t === p || t.startsWith(p + '/');
|
|
392
|
+
});
|
|
393
|
+
};
|
|
394
|
+
// Distinguish the two failure modes so the caller can fix the right thing:
|
|
395
|
+
// (a) no authorization grants Control to the caller at all, vs
|
|
396
|
+
// (b) one does, but its accessTo/default does not cover this target.
|
|
397
|
+
const controlAuths = proposed.filter(grantsCallerControl);
|
|
398
|
+
if (controlAuths.length === 0) {
|
|
363
399
|
return toolError(
|
|
364
400
|
`write_acl refused: the proposed ACL would not grant Control to the caller (${ctx.webId || 'anonymous'}). ` +
|
|
365
401
|
'This is typically caused by relative WebID paths in agents resolving against the .acl URL — use absolute WebIDs. ' +
|
|
@@ -367,6 +403,14 @@ async function write_acl({ path, authorizations }, ctx) {
|
|
|
367
403
|
'first grant Control to the new owner, then have the new owner write_acl without you.'
|
|
368
404
|
);
|
|
369
405
|
}
|
|
406
|
+
if (!controlAuths.some(appliesToTarget)) {
|
|
407
|
+
return toolError(
|
|
408
|
+
`write_acl refused: the proposed ACL grants Control to the caller (${ctx.webId || 'anonymous'}) ` +
|
|
409
|
+
`but none of those authorizations apply to ${path} — their accessTo/default targets a different ` +
|
|
410
|
+
'resource (commonly the parent container), so the resource would be left with no effective Control. ' +
|
|
411
|
+
'Ensure each authorization\'s accessTo covers this resource.'
|
|
412
|
+
);
|
|
413
|
+
}
|
|
370
414
|
|
|
371
415
|
await storage.write(aclPath, Buffer.from(serialized, 'utf8'), {
|
|
372
416
|
contentType: 'application/ld+json'
|
package/src/server.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import Fastify from 'fastify';
|
|
2
|
+
import sjson from 'secure-json-parse';
|
|
2
3
|
import rateLimit from '@fastify/rate-limit';
|
|
3
4
|
import { readFile } from 'fs/promises';
|
|
4
5
|
import { readFileSync } from 'fs';
|
|
@@ -269,7 +270,43 @@ export function createServer(options = {}) {
|
|
|
269
270
|
done(null, body);
|
|
270
271
|
});
|
|
271
272
|
|
|
273
|
+
// Override the default application/json parser so the NIP-98 payload-hash
|
|
274
|
+
// check (src/auth/nostr.js) can verify against the EXACT bytes the client
|
|
275
|
+
// signed, not a re-serialization of the parsed object (#565). The default
|
|
276
|
+
// parser discards the raw bytes once it produces an object, so capturing
|
|
277
|
+
// req.rawBody here is the only point they still exist. Behaviour otherwise
|
|
278
|
+
// mirrors Fastify 4's defaultJsonParser exactly — empty body → 400,
|
|
279
|
+
// secure-json-parse (same prototype-pollution protection JSS gets today),
|
|
280
|
+
// 400 on malformed — so no other request path changes. (Must
|
|
281
|
+
// removeContentTypeParser first: Fastify throws on a duplicate type.)
|
|
282
|
+
fastify.removeContentTypeParser('application/json');
|
|
283
|
+
fastify.addContentTypeParser('application/json', { parseAs: 'string' }, (req, body, done) => {
|
|
284
|
+
req.rawBody = body;
|
|
285
|
+
if (body === '' || body == null) {
|
|
286
|
+
// Match Fastify's FST_ERR_CTP_EMPTY_JSON_BODY exactly (code +
|
|
287
|
+
// message + status), so the error-response shape — which surfaces
|
|
288
|
+
// err.code — is identical to the default parser's.
|
|
289
|
+
const err = new Error("Body cannot be empty when content-type is set to 'application/json'");
|
|
290
|
+
err.code = 'FST_ERR_CTP_EMPTY_JSON_BODY';
|
|
291
|
+
err.statusCode = 400;
|
|
292
|
+
return done(err, undefined);
|
|
293
|
+
}
|
|
294
|
+
let json;
|
|
295
|
+
try {
|
|
296
|
+
// The malformed-JSON path already mirrors Fastify's default: it
|
|
297
|
+
// sets statusCode 400 on the raw parser error without adding an FST
|
|
298
|
+
// code (the default does the same), so no code is set here.
|
|
299
|
+
json = sjson.parse(body);
|
|
300
|
+
} catch (err) {
|
|
301
|
+
err.statusCode = 400;
|
|
302
|
+
return done(err, undefined);
|
|
303
|
+
}
|
|
304
|
+
done(null, json);
|
|
305
|
+
});
|
|
306
|
+
|
|
272
307
|
// Attach server config to requests
|
|
308
|
+
// Raw request body for the application/json parser to stash (#565).
|
|
309
|
+
fastify.decorateRequest('rawBody', null);
|
|
273
310
|
fastify.decorateRequest('connegEnabled', null);
|
|
274
311
|
fastify.decorateRequest('notificationsEnabled', null);
|
|
275
312
|
fastify.decorateRequest('idpEnabled', null);
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Port + URL helpers for `jss start` (#557).
|
|
3
|
+
*
|
|
4
|
+
* Ported from jspod's lib/start.js, where both have been proven in
|
|
5
|
+
* production. Kept in a standalone module (not inline in bin/jss.js) so
|
|
6
|
+
* they're unit-testable without executing the CLI.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import { createServer } from 'net';
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Format a host + port into an URL a human can actually open, for the
|
|
13
|
+
* startup banner. Wildcard bind addresses (0.0.0.0, ::, *) aren't
|
|
14
|
+
* connectable, so show `localhost`; a bare IPv6 literal gets bracketed.
|
|
15
|
+
*
|
|
16
|
+
* @param {string} host - the bind host
|
|
17
|
+
* @param {number} port - the bound port
|
|
18
|
+
* @param {string} [protocol] - 'http' (default) or 'https'
|
|
19
|
+
* @returns {string}
|
|
20
|
+
*/
|
|
21
|
+
export function formatUrl(host, port, protocol = 'http') {
|
|
22
|
+
if (host === '0.0.0.0' || host === '::' || host === '*') {
|
|
23
|
+
return `${protocol}://localhost:${port}`;
|
|
24
|
+
}
|
|
25
|
+
if (host.includes(':')) {
|
|
26
|
+
// IPv6 literal — must be bracketed in a URL authority.
|
|
27
|
+
return `${protocol}://[${host}]:${port}`;
|
|
28
|
+
}
|
|
29
|
+
return `${protocol}://${host}:${port}`;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Find a free port at or above `startPort` on `host`. Mirrors Vite's
|
|
34
|
+
* behaviour: probe one port at a time, up to `maxTries`, returning the
|
|
35
|
+
* first bindable one — or `null` if every port in the range is taken.
|
|
36
|
+
*
|
|
37
|
+
* Only EADDRINUSE counts as "busy" (try the next port). Any other
|
|
38
|
+
* bind failure — EACCES on a privileged port, EADDRNOTAVAIL for an
|
|
39
|
+
* invalid host — is a real error and is re-thrown, so the caller
|
|
40
|
+
* surfaces the actual cause instead of a misleading "no free port".
|
|
41
|
+
*
|
|
42
|
+
* Uses a throwaway net server to test bindability without committing the
|
|
43
|
+
* real server. (There is an inherent TOCTOU window between this probe
|
|
44
|
+
* and the real listen; the caller falls back to its normal listen-error
|
|
45
|
+
* path if the chosen port is grabbed in between.)
|
|
46
|
+
*
|
|
47
|
+
* @param {number} startPort
|
|
48
|
+
* @param {string} host
|
|
49
|
+
* @param {number} [maxTries]
|
|
50
|
+
* @returns {Promise<number|null>}
|
|
51
|
+
*/
|
|
52
|
+
export async function findFreePort(startPort, host, maxTries = 10) {
|
|
53
|
+
for (let p = startPort; p < startPort + maxTries; p++) {
|
|
54
|
+
const free = await new Promise((resolve, reject) => {
|
|
55
|
+
const srv = createServer();
|
|
56
|
+
srv.once('error', (err) => {
|
|
57
|
+
if (err.code === 'EADDRINUSE') resolve(false); // busy — try the next port
|
|
58
|
+
else reject(err); // real failure — surface it
|
|
59
|
+
});
|
|
60
|
+
srv.once('listening', () => srv.close(() => resolve(true)));
|
|
61
|
+
srv.listen(p, host);
|
|
62
|
+
});
|
|
63
|
+
if (free) return p;
|
|
64
|
+
}
|
|
65
|
+
return null;
|
|
66
|
+
}
|
package/test/mcp.test.js
CHANGED
|
@@ -22,6 +22,7 @@ import {
|
|
|
22
22
|
import { emitChange } from '../src/notifications/events.js';
|
|
23
23
|
|
|
24
24
|
let token;
|
|
25
|
+
let ownerWebId;
|
|
25
26
|
|
|
26
27
|
async function rpc(body, opts = {}) {
|
|
27
28
|
const headers = { 'Content-Type': 'application/json' };
|
|
@@ -39,8 +40,9 @@ async function rpc(body, opts = {}) {
|
|
|
39
40
|
describe('MCP server (--mcp enabled)', () => {
|
|
40
41
|
before(async () => {
|
|
41
42
|
await startTestServer({ mcp: true });
|
|
42
|
-
await createTestPod('mcptest');
|
|
43
|
+
const pod = await createTestPod('mcptest');
|
|
43
44
|
token = getPodToken('mcptest');
|
|
45
|
+
ownerWebId = pod.webId;
|
|
44
46
|
});
|
|
45
47
|
|
|
46
48
|
after(async () => {
|
|
@@ -322,6 +324,41 @@ describe('MCP server (--mcp enabled)', () => {
|
|
|
322
324
|
assert.match(body.result.content[0].text, /control/i);
|
|
323
325
|
});
|
|
324
326
|
|
|
327
|
+
it('write_acl on a resource does not lock the owner out (#575)', async () => {
|
|
328
|
+
// Regression: write_acl on a non-container resource used to set
|
|
329
|
+
// accessTo='./', which resolves to the *parent container* rather than
|
|
330
|
+
// the resource, leaving the resource with zero matching authorizations
|
|
331
|
+
// and locking out even the owner who just granted themselves Control.
|
|
332
|
+
const resPath = '/mcptest/public/acl575.txt';
|
|
333
|
+
const cr = await rpc({
|
|
334
|
+
jsonrpc: '2.0', id: 220, method: 'tools/call',
|
|
335
|
+
params: { name: 'write_resource', arguments: { path: resPath, content: 'secret', contentType: 'text/plain' } }
|
|
336
|
+
}, { token });
|
|
337
|
+
assert.strictEqual(cr.body.result.isError, false, cr.body.result.content?.[0]?.text);
|
|
338
|
+
|
|
339
|
+
// Grant the owner Read/Write/Control on the resource itself.
|
|
340
|
+
const wr = await rpc({
|
|
341
|
+
jsonrpc: '2.0', id: 221, method: 'tools/call',
|
|
342
|
+
params: { name: 'write_acl', arguments: {
|
|
343
|
+
path: resPath,
|
|
344
|
+
authorizations: [{ agents: [ownerWebId], modes: ['Read', 'Write', 'Control'] }]
|
|
345
|
+
} }
|
|
346
|
+
}, { token });
|
|
347
|
+
assert.strictEqual(wr.body.result.isError, false, wr.body.result.content?.[0]?.text);
|
|
348
|
+
|
|
349
|
+
// read_acl requires Control on the resource. Before the fix the owner
|
|
350
|
+
// was locked out and this was denied; it must now succeed.
|
|
351
|
+
const rd = await rpc({
|
|
352
|
+
jsonrpc: '2.0', id: 222, method: 'tools/call',
|
|
353
|
+
params: { name: 'read_acl', arguments: { path: resPath } }
|
|
354
|
+
}, { token });
|
|
355
|
+
assert.strictEqual(rd.body.result.isError, false,
|
|
356
|
+
'owner locked out of resource ACL (#575): ' + rd.body.result.content?.[0]?.text);
|
|
357
|
+
const payload = JSON.parse(rd.body.result.content[0].text);
|
|
358
|
+
assert.ok(payload.authorizations.some(a => a.modes.includes('Control')),
|
|
359
|
+
'resource ACL should grant the owner Control');
|
|
360
|
+
});
|
|
361
|
+
|
|
325
362
|
// --- call_remote_pod (#495) ---
|
|
326
363
|
|
|
327
364
|
it('call_remote_pod denied without federation gate access', async () => {
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* NIP-98 payload-hash verifies the RAW request bytes, not a re-serialization
|
|
3
|
+
* of the parsed body (#565).
|
|
4
|
+
*
|
|
5
|
+
* The bug: src/auth/nostr.js hashed `JSON.stringify(request.body)` — the
|
|
6
|
+
* parsed-then-recompacted body — so a NIP-98 client that sent pretty-printed
|
|
7
|
+
* (or otherwise non-minified) JSON 401'd with "Payload hash mismatch" even
|
|
8
|
+
* though signature/URL/method/timestamp were all valid. NIP-98's `payload`
|
|
9
|
+
* tag is sha256 over the exact body bytes on the wire.
|
|
10
|
+
*
|
|
11
|
+
* The fix has two halves, tested here:
|
|
12
|
+
* 1. server.js captures the raw application/json bytes as request.rawBody
|
|
13
|
+
* (the default parser discards them once it produces an object), while
|
|
14
|
+
* otherwise mirroring Fastify's default parser — empty → 400,
|
|
15
|
+
* secure-json-parse (prototype-pollution safe), 400 on malformed.
|
|
16
|
+
* 2. nostr.js hashes request.rawBody when present, never a re-serialization.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import { describe, it, before, after } from 'node:test';
|
|
20
|
+
import assert from 'node:assert';
|
|
21
|
+
import { createServer } from '../src/server.js';
|
|
22
|
+
import { verifyNostrAuth } from '../src/auth/nostr.js';
|
|
23
|
+
import { generateSecretKey, getPublicKey, nip98Token } from '../src/nostr/event.js';
|
|
24
|
+
import fs from 'fs-extra';
|
|
25
|
+
|
|
26
|
+
const DATA_DIR = './test-data-nip98-payload';
|
|
27
|
+
|
|
28
|
+
describe('application/json parser: rawBody capture + preserved semantics (#565)', () => {
|
|
29
|
+
let server;
|
|
30
|
+
let originalDataRoot;
|
|
31
|
+
|
|
32
|
+
before(async () => {
|
|
33
|
+
originalDataRoot = process.env.DATA_ROOT;
|
|
34
|
+
await fs.remove(DATA_DIR);
|
|
35
|
+
await fs.ensureDir(DATA_DIR);
|
|
36
|
+
server = createServer({
|
|
37
|
+
logger: false,
|
|
38
|
+
root: DATA_DIR,
|
|
39
|
+
public: true, // open writes so we exercise the parser without auth
|
|
40
|
+
forceCloseConnections: true,
|
|
41
|
+
});
|
|
42
|
+
await server.ready();
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
after(async () => {
|
|
46
|
+
if (server) await server.close();
|
|
47
|
+
if (originalDataRoot === undefined) delete process.env.DATA_ROOT;
|
|
48
|
+
else process.env.DATA_ROOT = originalDataRoot;
|
|
49
|
+
await fs.remove(DATA_DIR);
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
it('accepts a valid (pretty-printed) JSON body — parser stays functional', async () => {
|
|
53
|
+
const res = await server.inject({
|
|
54
|
+
method: 'PUT',
|
|
55
|
+
url: '/public/pretty.json',
|
|
56
|
+
headers: { 'content-type': 'application/json' },
|
|
57
|
+
payload: JSON.stringify({ a: 1, b: 'two' }, null, 2),
|
|
58
|
+
});
|
|
59
|
+
assert.ok(res.statusCode === 200 || res.statusCode === 201 || res.statusCode === 204,
|
|
60
|
+
`pretty JSON PUT should succeed, got ${res.statusCode}`);
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
it('rejects malformed JSON with 400 (mirrors Fastify default, not 500)', async () => {
|
|
64
|
+
const res = await server.inject({
|
|
65
|
+
method: 'PUT',
|
|
66
|
+
url: '/public/bad.json',
|
|
67
|
+
headers: { 'content-type': 'application/json' },
|
|
68
|
+
payload: '{ not valid json',
|
|
69
|
+
});
|
|
70
|
+
assert.strictEqual(res.statusCode, 400);
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
it('empty JSON body errors with Fastify\'s FST_ERR_CTP_EMPTY_JSON_BODY code (response-shape fidelity)', async () => {
|
|
74
|
+
const res = await server.inject({
|
|
75
|
+
method: 'PUT',
|
|
76
|
+
url: '/public/empty.json',
|
|
77
|
+
headers: { 'content-type': 'application/json' },
|
|
78
|
+
payload: '',
|
|
79
|
+
});
|
|
80
|
+
assert.strictEqual(res.statusCode, 400);
|
|
81
|
+
assert.strictEqual(res.json().code, 'FST_ERR_CTP_EMPTY_JSON_BODY',
|
|
82
|
+
'empty-body error must carry Fastify\'s standard code so the response shape matches the default parser');
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
it('blocks __proto__ prototype pollution (secure-json-parse preserved)', async () => {
|
|
86
|
+
const res = await server.inject({
|
|
87
|
+
method: 'PUT',
|
|
88
|
+
url: '/public/proto.json',
|
|
89
|
+
headers: { 'content-type': 'application/json' },
|
|
90
|
+
payload: '{ "__proto__": { "polluted": true } }',
|
|
91
|
+
});
|
|
92
|
+
// secure-json-parse throws on __proto__ → our parser surfaces 400.
|
|
93
|
+
assert.strictEqual(res.statusCode, 400, 'a __proto__ payload must be rejected');
|
|
94
|
+
assert.strictEqual({}.polluted, undefined, 'Object.prototype must not be polluted');
|
|
95
|
+
});
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
describe('NIP-98 payload hash uses the raw request bytes (#565)', () => {
|
|
99
|
+
const sk = generateSecretKey();
|
|
100
|
+
const pk = getPublicKey(sk);
|
|
101
|
+
|
|
102
|
+
// A pretty-printed body whose minified re-serialization differs byte-for-byte.
|
|
103
|
+
const entry = { name: 'alice', nested: { x: 1, y: 2 }, tags: ['a', 'b'] };
|
|
104
|
+
const prettyBody = JSON.stringify(entry, null, 2);
|
|
105
|
+
const compactBody = JSON.stringify(entry);
|
|
106
|
+
const parsed = JSON.parse(prettyBody);
|
|
107
|
+
|
|
108
|
+
const url = 'http://localhost:9999/pool/entries/' + pk + '.json';
|
|
109
|
+
|
|
110
|
+
// Build a mock Fastify request whose URL/host/method match what was signed,
|
|
111
|
+
// so verification reaches the payload-hash check.
|
|
112
|
+
function mockRequest(token, { rawBody, body }) {
|
|
113
|
+
return {
|
|
114
|
+
method: 'PUT',
|
|
115
|
+
url: '/pool/entries/' + pk + '.json',
|
|
116
|
+
protocol: 'http',
|
|
117
|
+
hostname: 'localhost:9999',
|
|
118
|
+
headers: { host: 'localhost:9999', authorization: `Nostr ${token}` },
|
|
119
|
+
rawBody,
|
|
120
|
+
body,
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
it('a pretty-printed body with rawBody captured passes the payload check', async () => {
|
|
125
|
+
// Client signed sha256(prettyBody) — exactly the bytes it sent.
|
|
126
|
+
const token = nip98Token(url, 'PUT', sk, prettyBody);
|
|
127
|
+
const result = await verifyNostrAuth(mockRequest(token, { rawBody: prettyBody, body: parsed }));
|
|
128
|
+
assert.notStrictEqual(result.error, 'Payload hash mismatch',
|
|
129
|
+
`pretty body should pass the payload check; got error: ${result.error}`);
|
|
130
|
+
assert.ok(result.webId && result.webId.startsWith('did:nostr:'),
|
|
131
|
+
`should resolve to the did:nostr identity; got ${JSON.stringify(result)}`);
|
|
132
|
+
});
|
|
133
|
+
|
|
134
|
+
it('control: the same body WITHOUT rawBody (object only) still mismatches — proves rawBody is the fix', async () => {
|
|
135
|
+
const token = nip98Token(url, 'PUT', sk, prettyBody);
|
|
136
|
+
// No rawBody → the old code path hashes JSON.stringify(parsed) = compact.
|
|
137
|
+
const result = await verifyNostrAuth(mockRequest(token, { rawBody: undefined, body: parsed }));
|
|
138
|
+
assert.strictEqual(result.error, 'Payload hash mismatch',
|
|
139
|
+
'without the captured raw bytes, a pretty body must still fail (the bug)');
|
|
140
|
+
});
|
|
141
|
+
|
|
142
|
+
it('a compact body still verifies (no regression for already-working clients)', async () => {
|
|
143
|
+
const token = nip98Token(url, 'PUT', sk, compactBody);
|
|
144
|
+
const result = await verifyNostrAuth(mockRequest(token, { rawBody: compactBody, body: parsed }));
|
|
145
|
+
assert.notStrictEqual(result.error, 'Payload hash mismatch',
|
|
146
|
+
`compact body should still pass; got error: ${result.error}`);
|
|
147
|
+
});
|
|
148
|
+
|
|
149
|
+
it('a falsy JSON body (false) is still hash-checked, not skipped (Copilot review on #573)', async () => {
|
|
150
|
+
// The body literally parses to `false`. A WRONG payload tag must still
|
|
151
|
+
// be caught — under the old `&& request.body` truthiness guard this
|
|
152
|
+
// validation was skipped entirely for falsy bodies.
|
|
153
|
+
const falsyRaw = 'false';
|
|
154
|
+
const wrongToken = nip98Token(url, 'PUT', sk, 'a-different-body');
|
|
155
|
+
const mismatch = await verifyNostrAuth(mockRequest(wrongToken, { rawBody: falsyRaw, body: false }));
|
|
156
|
+
assert.strictEqual(mismatch.error, 'Payload hash mismatch',
|
|
157
|
+
'a falsy body with a wrong payload tag must be rejected, not skipped');
|
|
158
|
+
|
|
159
|
+
// And the matching payload for the same falsy body passes.
|
|
160
|
+
const goodToken = nip98Token(url, 'PUT', sk, falsyRaw);
|
|
161
|
+
const ok = await verifyNostrAuth(mockRequest(goodToken, { rawBody: falsyRaw, body: false }));
|
|
162
|
+
assert.notStrictEqual(ok.error, 'Payload hash mismatch',
|
|
163
|
+
`a falsy body with the correct payload should pass; got ${ok.error}`);
|
|
164
|
+
});
|
|
165
|
+
|
|
166
|
+
it('a binary / non-UTF-8 Buffer body hashes the raw bytes (Copilot review on #573)', async () => {
|
|
167
|
+
// Bytes that are NOT valid UTF-8 — a .toString() round-trip would
|
|
168
|
+
// mangle them (replacement chars) and break the hash. The client
|
|
169
|
+
// signs sha256 over the raw bytes; the server must do the same.
|
|
170
|
+
const binary = Buffer.from([0xff, 0xfe, 0x00, 0x01, 0x80, 0xc3, 0x28]);
|
|
171
|
+
// Sanity: this fixture genuinely changes bytes under a UTF-8 string
|
|
172
|
+
// round-trip, so the old `.toString()` path WOULD have mismatched.
|
|
173
|
+
assert.ok(!Buffer.from(binary.toString('utf8'), 'utf8').equals(binary),
|
|
174
|
+
'fixture must be lossy under a UTF-8 round-trip');
|
|
175
|
+
const token = nip98Token(url, 'PUT', sk, binary);
|
|
176
|
+
// Non-JSON body → no rawBody; request.body is the raw Buffer (the `*`
|
|
177
|
+
// content-type parser keeps it as a Buffer).
|
|
178
|
+
const result = await verifyNostrAuth(mockRequest(token, { rawBody: undefined, body: binary }));
|
|
179
|
+
assert.notStrictEqual(result.error, 'Payload hash mismatch',
|
|
180
|
+
`binary body must hash raw bytes, not a UTF-8 round-trip; got error: ${result.error}`);
|
|
181
|
+
});
|
|
182
|
+
});
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* CLI wiring for the busy-port shift (#557).
|
|
3
|
+
*
|
|
4
|
+
* test/port.test.js covers findFreePort/formatUrl directly; this spawns
|
|
5
|
+
* `bin/jss.js start` on an occupied port and asserts the real user-facing
|
|
6
|
+
* behaviour: instead of dying on EADDRINUSE, jss shifts to the next free
|
|
7
|
+
* port (Vite-style), prints a notice to stderr (so it surfaces even under
|
|
8
|
+
* --quiet), and actually serves there.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { describe, it, afterEach } from 'node:test';
|
|
12
|
+
import assert from 'node:assert';
|
|
13
|
+
import { spawn } from 'node:child_process';
|
|
14
|
+
import { createServer as createNetServer } from 'node:net';
|
|
15
|
+
import { fileURLToPath } from 'node:url';
|
|
16
|
+
import path from 'node:path';
|
|
17
|
+
import fs from 'fs-extra';
|
|
18
|
+
|
|
19
|
+
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
20
|
+
const BIN = path.join(__dirname, '..', 'bin', 'jss.js');
|
|
21
|
+
const TEST_DATA_DIR = './test-data-port-shift-cli';
|
|
22
|
+
const HOST = '127.0.0.1';
|
|
23
|
+
|
|
24
|
+
let child;
|
|
25
|
+
let blocker;
|
|
26
|
+
|
|
27
|
+
function freePort() {
|
|
28
|
+
return new Promise((resolve, reject) => {
|
|
29
|
+
const srv = createNetServer();
|
|
30
|
+
srv.once('error', reject);
|
|
31
|
+
srv.listen(0, HOST, () => {
|
|
32
|
+
const { port } = srv.address();
|
|
33
|
+
srv.close(() => resolve(port));
|
|
34
|
+
});
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function occupy(port) {
|
|
39
|
+
return new Promise((resolve, reject) => {
|
|
40
|
+
const srv = createNetServer();
|
|
41
|
+
srv.once('error', reject);
|
|
42
|
+
srv.listen(port, HOST, () => resolve(srv));
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
async function stopCli() {
|
|
47
|
+
if (!child) return;
|
|
48
|
+
const c = child;
|
|
49
|
+
child = null;
|
|
50
|
+
if (c.exitCode !== null || c.signalCode !== null) return;
|
|
51
|
+
const gone = new Promise((r) => c.once('exit', r));
|
|
52
|
+
c.kill('SIGTERM');
|
|
53
|
+
await Promise.race([gone, new Promise((r) => setTimeout(r, 3000))]);
|
|
54
|
+
if (c.exitCode === null && c.signalCode === null) c.kill('SIGKILL');
|
|
55
|
+
await Promise.race([gone, new Promise((r) => setTimeout(r, 2000))]);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
describe('bin/jss.js — busy-port shift (#557)', () => {
|
|
59
|
+
afterEach(async () => {
|
|
60
|
+
await stopCli();
|
|
61
|
+
if (blocker) {
|
|
62
|
+
await new Promise((r) => blocker.close(r));
|
|
63
|
+
blocker = null;
|
|
64
|
+
}
|
|
65
|
+
await fs.remove(TEST_DATA_DIR);
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
it('shifts to the next free port and serves there when the requested port is busy', async () => {
|
|
69
|
+
await fs.emptyDir(TEST_DATA_DIR);
|
|
70
|
+
const busy = await freePort();
|
|
71
|
+
blocker = await occupy(busy); // hold `busy` so jss can't bind it
|
|
72
|
+
|
|
73
|
+
let stderr = '';
|
|
74
|
+
child = spawn(process.execPath, [
|
|
75
|
+
BIN, 'start',
|
|
76
|
+
'--port', String(busy),
|
|
77
|
+
'--host', HOST,
|
|
78
|
+
'--root', TEST_DATA_DIR,
|
|
79
|
+
'--quiet', // banner suppressed; the shift notice still goes to stderr
|
|
80
|
+
], { env: { ...process.env }, stdio: ['ignore', 'pipe', 'pipe'] });
|
|
81
|
+
child.stderr.on('data', (d) => { stderr += d; });
|
|
82
|
+
|
|
83
|
+
const deadline = Date.now() + 15_000;
|
|
84
|
+
let exited = false;
|
|
85
|
+
child.once('exit', () => { exited = true; });
|
|
86
|
+
|
|
87
|
+
// 1. The shift notice (which carries the chosen port) must appear.
|
|
88
|
+
let shifted = null;
|
|
89
|
+
while (Date.now() < deadline) {
|
|
90
|
+
const m = stderr.match(/using (\d+) instead/);
|
|
91
|
+
if (m) { shifted = Number(m[1]); break; }
|
|
92
|
+
if (exited) throw new Error(`jss exited before shifting. stderr: ${stderr}`);
|
|
93
|
+
await new Promise((r) => setTimeout(r, 100));
|
|
94
|
+
}
|
|
95
|
+
assert.ok(shifted, `expected a port-shift notice on stderr; got: ${stderr || '(empty)'}`);
|
|
96
|
+
assert.ok(stderr.includes(`Port ${busy} is in use`), 'notice should name the busy port');
|
|
97
|
+
assert.notStrictEqual(shifted, busy);
|
|
98
|
+
|
|
99
|
+
// 2. The server must actually serve on the shifted port.
|
|
100
|
+
const url = `http://${HOST}:${shifted}`;
|
|
101
|
+
let ready = false;
|
|
102
|
+
while (Date.now() < deadline) {
|
|
103
|
+
if (exited) throw new Error(`jss exited before serving. stderr: ${stderr}`);
|
|
104
|
+
try {
|
|
105
|
+
await fetch(url, { signal: AbortSignal.timeout(1000) });
|
|
106
|
+
ready = true;
|
|
107
|
+
break;
|
|
108
|
+
} catch {
|
|
109
|
+
await new Promise((r) => setTimeout(r, 200));
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
assert.ok(ready, `jss should serve on the shifted port ${shifted}`);
|
|
113
|
+
});
|
|
114
|
+
});
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Port + URL helpers for `jss start` (#557): findFreePort shifts off a
|
|
3
|
+
* busy port (Vite-style); formatUrl turns a bind host into an openable
|
|
4
|
+
* banner URL.
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { describe, it } from 'node:test';
|
|
8
|
+
import assert from 'node:assert';
|
|
9
|
+
import { createServer } from 'net';
|
|
10
|
+
import { findFreePort, formatUrl } from '../src/utils/port.js';
|
|
11
|
+
|
|
12
|
+
const HOST = '127.0.0.1';
|
|
13
|
+
|
|
14
|
+
function listen(port, host) {
|
|
15
|
+
return new Promise((resolve, reject) => {
|
|
16
|
+
const srv = createServer();
|
|
17
|
+
srv.once('error', reject);
|
|
18
|
+
srv.listen(port, host, () => resolve(srv));
|
|
19
|
+
});
|
|
20
|
+
}
|
|
21
|
+
function close(srv) {
|
|
22
|
+
return new Promise((resolve) => srv.close(resolve));
|
|
23
|
+
}
|
|
24
|
+
function freePort(host) {
|
|
25
|
+
return new Promise((resolve, reject) => {
|
|
26
|
+
const srv = createServer();
|
|
27
|
+
srv.once('error', reject);
|
|
28
|
+
srv.listen(0, host, () => {
|
|
29
|
+
const { port } = srv.address();
|
|
30
|
+
srv.close(() => resolve(port));
|
|
31
|
+
});
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
describe('formatUrl (#557)', () => {
|
|
36
|
+
it('rewrites wildcard bind addresses to localhost', () => {
|
|
37
|
+
assert.strictEqual(formatUrl('0.0.0.0', 4443), 'http://localhost:4443');
|
|
38
|
+
assert.strictEqual(formatUrl('::', 4443), 'http://localhost:4443');
|
|
39
|
+
assert.strictEqual(formatUrl('*', 4443), 'http://localhost:4443');
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
it('passes a normal host through unchanged', () => {
|
|
43
|
+
assert.strictEqual(formatUrl('example.com', 8080), 'http://example.com:8080');
|
|
44
|
+
assert.strictEqual(formatUrl('127.0.0.1', 3000), 'http://127.0.0.1:3000');
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
it('brackets an IPv6 literal', () => {
|
|
48
|
+
assert.strictEqual(formatUrl('::1', 4443), 'http://[::1]:4443');
|
|
49
|
+
assert.strictEqual(formatUrl('fe80::1', 4443), 'http://[fe80::1]:4443');
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
it('honours the protocol argument', () => {
|
|
53
|
+
assert.strictEqual(formatUrl('example.com', 443, 'https'), 'https://example.com:443');
|
|
54
|
+
assert.strictEqual(formatUrl('0.0.0.0', 4443, 'https'), 'https://localhost:4443');
|
|
55
|
+
});
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
describe('findFreePort (#557)', () => {
|
|
59
|
+
it('returns the requested port when it is free', async () => {
|
|
60
|
+
const p = await freePort(HOST);
|
|
61
|
+
assert.strictEqual(await findFreePort(p, HOST), p);
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
it('shifts to the next free port when the requested one is busy', async () => {
|
|
65
|
+
const p = await freePort(HOST);
|
|
66
|
+
const blocker = await listen(p, HOST);
|
|
67
|
+
try {
|
|
68
|
+
const got = await findFreePort(p, HOST);
|
|
69
|
+
assert.ok(got > p, `expected a port above ${p}, got ${got}`);
|
|
70
|
+
assert.ok(got < p + 10, 'should stay within the probe window');
|
|
71
|
+
} finally {
|
|
72
|
+
await close(blocker);
|
|
73
|
+
}
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
it('returns null when every port in the window is taken', async () => {
|
|
77
|
+
const p = await freePort(HOST);
|
|
78
|
+
const a = await listen(p, HOST);
|
|
79
|
+
const b = await listen(p + 1, HOST);
|
|
80
|
+
try {
|
|
81
|
+
// window of 2 — both taken → no free port
|
|
82
|
+
assert.strictEqual(await findFreePort(p, HOST, 2), null);
|
|
83
|
+
} finally {
|
|
84
|
+
await close(a);
|
|
85
|
+
await close(b);
|
|
86
|
+
}
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
it('re-throws a non-EADDRINUSE bind error instead of reporting "no free port"', async () => {
|
|
90
|
+
// 192.0.2.0/24 (TEST-NET-1) isn't a local interface → EADDRNOTAVAIL,
|
|
91
|
+
// which is a real failure, not a busy port. Must propagate so the CLI
|
|
92
|
+
// surfaces the actual cause rather than "no free port found".
|
|
93
|
+
await assert.rejects(
|
|
94
|
+
() => findFreePort(40000, '192.0.2.1', 1),
|
|
95
|
+
(err) => err && err.code !== undefined && err.code !== 'EADDRINUSE',
|
|
96
|
+
);
|
|
97
|
+
});
|
|
98
|
+
});
|
|
@@ -129,7 +129,7 @@ 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://
|
|
132
|
+
assert.deepStrictEqual(doc['@context'], ['https://www.w3.org/ns/cid/v1', 'https://w3id.org/nostr/context']);
|
|
133
133
|
assert.strictEqual(doc.id, `did:nostr:${alicePk}`);
|
|
134
134
|
assert.strictEqual(doc.type, 'DIDNostr');
|
|
135
135
|
assert.ok(Array.isArray(doc.alsoKnownAs));
|