javascript-solid-server 0.0.207 → 0.0.209
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 +27 -3
- package/package.json +2 -1
- package/src/auth/nostr.js +31 -7
- package/src/config.js +6 -5
- package/src/handlers/git.js +9 -1
- package/src/idp/well-known-did-nostr.js +1 -1
- package/src/server.js +39 -2
- package/src/utils/port.js +66 -0
- package/test/body-limit-cli.test.js +130 -0
- package/test/body-limit.test.js +12 -2
- 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';
|
|
@@ -112,7 +113,7 @@ program
|
|
|
112
113
|
.option('--cors-proxy-max-bytes <n>', 'CORS proxy upstream response size cap (default 50MB)', parseInt)
|
|
113
114
|
.option('--cors-proxy-timeout-ms <ms>', 'CORS proxy upstream request timeout (default 30s)', parseInt)
|
|
114
115
|
.option('--cors-proxy-max-redirects <n>', 'CORS proxy max redirect hops, each re-validated (default 5)', parseInt)
|
|
115
|
-
.option('--body-limit <size>', 'Maximum request body size, e.g. 100MB or 1GB (default
|
|
116
|
+
.option('--body-limit <size>', 'Maximum request body size, e.g. 100MB or 1GB (default 20MB). Raise to accept larger `git push`; lower for tighter memory-DoS protection.')
|
|
116
117
|
.option('--nostr', 'Enable Nostr relay')
|
|
117
118
|
.option('--no-nostr', 'Disable Nostr relay')
|
|
118
119
|
.option('--nostr-path <path>', 'Nostr relay WebSocket path (default: /relay)')
|
|
@@ -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('/')) {
|
|
@@ -190,6 +210,10 @@ program
|
|
|
190
210
|
const server = createServer({
|
|
191
211
|
port: config.port,
|
|
192
212
|
host: config.host,
|
|
213
|
+
// Wire the parsed --body-limit / JSS_BODY_LIMIT value through —
|
|
214
|
+
// omitting it here silently pinned every CLI-started server to
|
|
215
|
+
// the 10MB default and made the #474 knob dead wiring (#561).
|
|
216
|
+
bodyLimit: config.bodyLimit,
|
|
193
217
|
logger: config.logger,
|
|
194
218
|
conneg: config.conneg,
|
|
195
219
|
notifications: config.notifications,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "javascript-solid-server",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.209",
|
|
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
|
}
|
package/src/config.js
CHANGED
|
@@ -20,11 +20,12 @@ export const defaults = {
|
|
|
20
20
|
host: '0.0.0.0',
|
|
21
21
|
root: './data',
|
|
22
22
|
// Maximum request body size in bytes (or a size string when supplied
|
|
23
|
-
// via CLI / config file, e.g. "100MB").
|
|
24
|
-
//
|
|
25
|
-
//
|
|
26
|
-
//
|
|
27
|
-
|
|
23
|
+
// via CLI / config file, e.g. "100MB"). 20 MiB default (#563) — a
|
|
24
|
+
// generous out-of-the-box limit for common workloads (larger `git
|
|
25
|
+
// push`, media uploads, bigger RDF documents). Raise via --body-limit
|
|
26
|
+
// / JSS_BODY_LIMIT for established app repos (#474); lower it for
|
|
27
|
+
// tighter memory-DoS protection.
|
|
28
|
+
bodyLimit: 20 * 1024 * 1024,
|
|
28
29
|
|
|
29
30
|
// SSL
|
|
30
31
|
sslKey: null,
|
package/src/handlers/git.js
CHANGED
|
@@ -279,7 +279,15 @@ export async function handleGit(request, reply) {
|
|
|
279
279
|
CONTENT_TYPE: request.headers['content-type'] || '',
|
|
280
280
|
QUERY_STRING: queryString,
|
|
281
281
|
REMOTE_USER: request.webId || '', // Pass authenticated user
|
|
282
|
-
|
|
282
|
+
// Use the buffered body's real length, not the Content-Length header:
|
|
283
|
+
// git sends packs larger than http.postBuffer (1 MiB default) with
|
|
284
|
+
// Transfer-Encoding: chunked and NO Content-Length, so the header
|
|
285
|
+
// fallback told http-backend "0 bytes" and receive-pack died with
|
|
286
|
+
// "the remote end hung up unexpectedly" on any push > 1 MiB (#561).
|
|
287
|
+
// Fastify has already buffered the full body either way.
|
|
288
|
+
CONTENT_LENGTH: request.body?.length
|
|
289
|
+
? String(request.body.length)
|
|
290
|
+
: (request.headers['content-length'] || '0'),
|
|
283
291
|
};
|
|
284
292
|
|
|
285
293
|
// For regular repositories, set GIT_DIR
|
|
@@ -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/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';
|
|
@@ -187,8 +188,8 @@ export function createServer(options = {}) {
|
|
|
187
188
|
// already coerced by parseEnvValue) pass through unchanged; strings
|
|
188
189
|
// ("100MB" from CLI / config files) go through parseSize for
|
|
189
190
|
// size-shorthand support. The typeof check matters because parseSize
|
|
190
|
-
// calls `.match` on its input and would throw on a raw number.
|
|
191
|
-
//
|
|
191
|
+
// calls `.match` on its input and would throw on a raw number. Falls
|
|
192
|
+
// back to defaults.bodyLimit (20 MiB, #563) when unset. See #474.
|
|
192
193
|
const bodyLimit = options.bodyLimit == null
|
|
193
194
|
? defaults.bodyLimit
|
|
194
195
|
: (typeof options.bodyLimit === 'number' ? options.bodyLimit : parseSize(options.bodyLimit));
|
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* CLI wiring for --body-limit / JSS_BODY_LIMIT (#561).
|
|
3
|
+
*
|
|
4
|
+
* test/body-limit.test.js covers createServer({ bodyLimit }) — the
|
|
5
|
+
* programmatic path — but the CLI start command builds its createServer
|
|
6
|
+
* options object by hand, and originally omitted `bodyLimit`. Result:
|
|
7
|
+
* the #474 knob parsed fine and was then silently dropped, pinning every
|
|
8
|
+
* CLI-started server to the 10 MiB default. git pushes of packs over the
|
|
9
|
+
* default failed with 413 no matter what the operator passed (#561).
|
|
10
|
+
*
|
|
11
|
+
* These tests spawn `bin/jss.js start` as a real subprocess (same
|
|
12
|
+
* pattern as cli-flag-like-values.test.js) and assert the limit
|
|
13
|
+
* actually reaches Fastify:
|
|
14
|
+
*
|
|
15
|
+
* - `--body-limit 1KB` → a 2 KiB PUT is rejected with 413
|
|
16
|
+
* - `--body-limit 5MB` → the same PUT is NOT rejected with 413
|
|
17
|
+
* - `JSS_BODY_LIMIT=1KB` (env, no flag) → 413, same as the flag
|
|
18
|
+
*
|
|
19
|
+
* The over-limit assertions are deliberately status-exact (413) while
|
|
20
|
+
* the under-limit assertion is only "not 413": body parsing runs before
|
|
21
|
+
* auth/WAC, so an under-limit request may still be refused later in the
|
|
22
|
+
* pipeline — that's fine, the wiring under test is the parser cap.
|
|
23
|
+
*/
|
|
24
|
+
|
|
25
|
+
import { describe, it, afterEach } from 'node:test';
|
|
26
|
+
import assert from 'node:assert';
|
|
27
|
+
import { spawn } from 'node:child_process';
|
|
28
|
+
import { createServer as createNetServer } from 'node:net';
|
|
29
|
+
import { fileURLToPath } from 'node:url';
|
|
30
|
+
import path from 'node:path';
|
|
31
|
+
import fs from 'fs-extra';
|
|
32
|
+
|
|
33
|
+
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
34
|
+
const BIN = path.join(__dirname, '..', 'bin', 'jss.js');
|
|
35
|
+
const TEST_DATA_DIR = './test-data-body-limit-cli';
|
|
36
|
+
|
|
37
|
+
let child;
|
|
38
|
+
|
|
39
|
+
function freePort() {
|
|
40
|
+
return new Promise((resolve, reject) => {
|
|
41
|
+
const srv = createNetServer();
|
|
42
|
+
srv.once('error', reject);
|
|
43
|
+
srv.listen(0, '127.0.0.1', () => {
|
|
44
|
+
const { port } = srv.address();
|
|
45
|
+
srv.close(() => resolve(port));
|
|
46
|
+
});
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
async function startCli({ args = [], env = {} }) {
|
|
51
|
+
await fs.emptyDir(TEST_DATA_DIR);
|
|
52
|
+
const port = await freePort();
|
|
53
|
+
child = spawn(process.execPath, [
|
|
54
|
+
BIN, 'start',
|
|
55
|
+
'--port', String(port),
|
|
56
|
+
'--host', '127.0.0.1',
|
|
57
|
+
'--root', TEST_DATA_DIR,
|
|
58
|
+
...args,
|
|
59
|
+
], {
|
|
60
|
+
env: { ...process.env, ...env },
|
|
61
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
62
|
+
});
|
|
63
|
+
const baseUrl = `http://127.0.0.1:${port}`;
|
|
64
|
+
|
|
65
|
+
// Poll until the server answers (or the child dies / 15 s passes).
|
|
66
|
+
const deadline = Date.now() + 15_000;
|
|
67
|
+
let exited = false;
|
|
68
|
+
child.once('exit', () => { exited = true; });
|
|
69
|
+
while (Date.now() < deadline) {
|
|
70
|
+
if (exited) throw new Error('jss CLI exited before becoming ready');
|
|
71
|
+
try {
|
|
72
|
+
await fetch(baseUrl, { signal: AbortSignal.timeout(1000) });
|
|
73
|
+
return baseUrl;
|
|
74
|
+
} catch {
|
|
75
|
+
await new Promise(r => setTimeout(r, 250));
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
throw new Error('jss CLI did not become ready within 15s');
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
async function stopCli() {
|
|
82
|
+
if (!child) return;
|
|
83
|
+
const c = child;
|
|
84
|
+
child = null;
|
|
85
|
+
// The exitCode check and the once('exit') attach below are in the
|
|
86
|
+
// same synchronous block — Node can't emit 'exit' between two
|
|
87
|
+
// synchronous statements, so the listener can't miss the event (if
|
|
88
|
+
// it already fired, exitCode is non-null and we return here).
|
|
89
|
+
if (c.exitCode !== null || c.signalCode !== null) return;
|
|
90
|
+
const gone = new Promise(r => c.once('exit', r));
|
|
91
|
+
c.kill('SIGTERM');
|
|
92
|
+
await Promise.race([gone, new Promise(r => setTimeout(r, 3000))]);
|
|
93
|
+
if (c.exitCode === null && c.signalCode === null) c.kill('SIGKILL');
|
|
94
|
+
// SIGKILL can't be caught, so 'exit' follows promptly. The cap is a
|
|
95
|
+
// belt-and-braces bound so the suite can never hang on a pathological
|
|
96
|
+
// unkillable child (e.g. stuck in uninterruptible I/O).
|
|
97
|
+
await Promise.race([gone, new Promise(r => setTimeout(r, 2000))]);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
async function putTwoKiB(baseUrl) {
|
|
101
|
+
const res = await fetch(`${baseUrl}/body-limit-probe.bin`, {
|
|
102
|
+
method: 'PUT',
|
|
103
|
+
headers: { 'Content-Type': 'application/octet-stream' },
|
|
104
|
+
body: Buffer.alloc(2048, 0x61),
|
|
105
|
+
signal: AbortSignal.timeout(5000),
|
|
106
|
+
});
|
|
107
|
+
return res.status;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
describe('bin/jss.js — --body-limit reaches Fastify (#561)', () => {
|
|
111
|
+
afterEach(async () => {
|
|
112
|
+
await stopCli();
|
|
113
|
+
await fs.remove(TEST_DATA_DIR);
|
|
114
|
+
});
|
|
115
|
+
|
|
116
|
+
it('--body-limit 1KB rejects a 2KiB PUT with 413', async () => {
|
|
117
|
+
const baseUrl = await startCli({ args: ['--body-limit', '1KB'] });
|
|
118
|
+
assert.strictEqual(await putTwoKiB(baseUrl), 413);
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
it('--body-limit 5MB does not 413 a 2KiB PUT', async () => {
|
|
122
|
+
const baseUrl = await startCli({ args: ['--body-limit', '5MB'] });
|
|
123
|
+
assert.notStrictEqual(await putTwoKiB(baseUrl), 413);
|
|
124
|
+
});
|
|
125
|
+
|
|
126
|
+
it('JSS_BODY_LIMIT=1KB (env, no flag) rejects a 2KiB PUT with 413', async () => {
|
|
127
|
+
const baseUrl = await startCli({ env: { JSS_BODY_LIMIT: '1KB' } });
|
|
128
|
+
assert.strictEqual(await putTwoKiB(baseUrl), 413);
|
|
129
|
+
});
|
|
130
|
+
});
|
package/test/body-limit.test.js
CHANGED
|
@@ -12,8 +12,8 @@
|
|
|
12
12
|
*
|
|
13
13
|
* Tests here verify the surface end-to-end — server actually rejects
|
|
14
14
|
* over-size requests with 413, AND the size-string parsing path works
|
|
15
|
-
* the same as the numeric path. The default (
|
|
16
|
-
*
|
|
15
|
+
* the same as the numeric path. The out-of-the-box default (20 MiB
|
|
16
|
+
* since #563) is pinned explicitly via Fastify's initialConfig.
|
|
17
17
|
*/
|
|
18
18
|
|
|
19
19
|
import { describe, it, before, after, afterEach } from 'node:test';
|
|
@@ -102,4 +102,14 @@ describe('configurable bodyLimit (#474)', () => {
|
|
|
102
102
|
assert.notStrictEqual(res.status, 413,
|
|
103
103
|
`100-byte body under a 10KB cap should not 413; got ${res.status}`);
|
|
104
104
|
});
|
|
105
|
+
|
|
106
|
+
it('defaults to a 20 MiB body limit when none is configured (#563)', async () => {
|
|
107
|
+
await fs.emptyDir(TEST_DATA_DIR);
|
|
108
|
+
server = createServer({ logger: false, forceCloseConnections: true, root: TEST_DATA_DIR });
|
|
109
|
+
// Pin the EFFECTIVE wired default, not the constant in isolation:
|
|
110
|
+
// Fastify freezes resolved options into initialConfig, so this
|
|
111
|
+
// exercises config.defaults.bodyLimit → createServer → Fastify.
|
|
112
|
+
assert.strictEqual(server.initialConfig.bodyLimit, 20 * 1024 * 1024,
|
|
113
|
+
`expected the out-of-the-box default to be 20 MiB; got ${server.initialConfig.bodyLimit}`);
|
|
114
|
+
});
|
|
105
115
|
});
|
|
@@ -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));
|