javascript-solid-server 0.0.206 → 0.0.208

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.
@@ -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
+ });
@@ -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 (10 MiB) is covered
16
- * implicitly by every other test in the suite continuing to pass.
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
  });
@@ -141,6 +141,14 @@ describe('Git auto-init on first push', () => {
141
141
  await fs.ensureDir(DATA_DIR_AUTH);
142
142
  const port = await getAvailablePort();
143
143
  const authBaseUrl = `http://${TEST_HOST}:${port}`;
144
+ // createServer({ root }) mutates process.env.DATA_ROOT globally, and
145
+ // handleGit resolves the data root PER REQUEST via getDataRoot().
146
+ // Without restoring the env afterwards, every later test in this
147
+ // file silently runs against DATA_DIR_AUTH instead of DATA_DIR —
148
+ // auto-initing repos in the wrong tree and leaving the authcheck
149
+ // directory behind after the suite's cleanup (which only removes
150
+ // DATA_DIR). Same pollution class as the #543 review finding.
151
+ const originalDataRoot = process.env.DATA_ROOT;
144
152
  const authServer = createServer({
145
153
  logger: false,
146
154
  root: DATA_DIR_AUTH,
@@ -162,6 +170,8 @@ describe('Git auto-init on first push', () => {
162
170
  'auto-init MUST NOT create a directory for an unauthenticated request');
163
171
  } finally {
164
172
  await authServer.close();
173
+ if (originalDataRoot === undefined) delete process.env.DATA_ROOT;
174
+ else process.env.DATA_ROOT = originalDataRoot;
165
175
  await fs.remove(DATA_DIR_AUTH);
166
176
  }
167
177
  });
@@ -0,0 +1,239 @@
1
+ /**
2
+ * Git handler HTTP contract (#375).
3
+ *
4
+ * src/handlers/git.js previously had no automated coverage — the #371
5
+ * (CORS) and #373 (multi-slash) fixes were verified by hand. These
6
+ * tests pin the HTTP-level contract:
7
+ *
8
+ * - OPTIONS preflight carries the canonical git CORS headers
9
+ * - info/refs advertise works through single/double/triple-slash
10
+ * URLs (#373 regression — git http-backend rejects "aliased"
11
+ * paths, so JSS collapses multi-slash before forwarding)
12
+ * - missing repo → 404 WITH CORS headers (#374 regression — without
13
+ * them a browser git client sees a CORS error, not the 404)
14
+ * - path traversal attempts are blocked (never 200, never 500)
15
+ * with CORS headers
16
+ * - unauthenticated push advertise → 401 + WWW-Authenticate + the
17
+ * git CORS headers (the preHandler's 401/403 path lacked them
18
+ * until #548; this 401 is emitted by the server.js WAC
19
+ * preHandler, not by handleGit)
20
+ * - a real end-to-end `git push` succeeds and the pushed file is
21
+ * served as a static resource (receive-pack POST through
22
+ * http-backend + updateInstead extraction)
23
+ *
24
+ * Boot pattern mirrors test/git-auto-init.test.js: temp data dir,
25
+ * `git: true, public: true` so WAC is open and the handler logic is
26
+ * exercised in isolation. The 401 case boots a second, non-public
27
+ * server and snapshots/restores process.env.DATA_ROOT around it
28
+ * (createServer({ root }) mutates it globally).
29
+ */
30
+
31
+ import { describe, it, before, after } from 'node:test';
32
+ import assert from 'node:assert';
33
+ import { createServer } from '../src/server.js';
34
+ import { createServer as createNetServer } from 'net';
35
+ import { spawn, spawnSync } from 'child_process';
36
+ import fs from 'fs-extra';
37
+ import path from 'path';
38
+
39
+ const TEST_HOST = 'localhost';
40
+ const DATA_DIR = './test-data-git-handler';
41
+ const LOCAL_REPO = './test-data-git-handler-local';
42
+
43
+ function getAvailablePort() {
44
+ return new Promise((resolve, reject) => {
45
+ const srv = createNetServer();
46
+ srv.on('error', reject);
47
+ srv.listen(0, TEST_HOST, () => {
48
+ const port = srv.address().port;
49
+ srv.close(() => resolve(port));
50
+ });
51
+ });
52
+ }
53
+
54
+ // Synchronous git for purely-LOCAL operations (init/add/commit). Fine
55
+ // to block the event loop because no in-process server is involved.
56
+ function git(args, cwd) {
57
+ const res = spawnSync('git', args, { cwd, stdio: ['ignore', 'pipe', 'pipe'] });
58
+ return {
59
+ status: res.status,
60
+ stdout: res.stdout?.toString() || '',
61
+ stderr: res.stderr?.toString() || '',
62
+ };
63
+ }
64
+
65
+ // Async git for operations that talk to the in-process test server
66
+ // (push). spawnSync would block the event loop, the server could never
67
+ // respond, and the test would deadlock until the runner times out.
68
+ //
69
+ // GIT_TERMINAL_PROMPT=0 makes git fail fast instead of waiting on a
70
+ // credential prompt if the remote unexpectedly challenges (stdin is
71
+ // 'ignore', so a prompt could otherwise wedge the test in CI). The
72
+ // `error` listener covers spawn-level failures (e.g. git missing from
73
+ // PATH), where `close` may never fire and the promise would hang.
74
+ function gitAsync(args, cwd) {
75
+ return new Promise((resolve) => {
76
+ const child = spawn('git', args, {
77
+ cwd,
78
+ stdio: ['ignore', 'pipe', 'pipe'],
79
+ env: { ...process.env, GIT_TERMINAL_PROMPT: '0' },
80
+ });
81
+ let stdout = '';
82
+ let stderr = '';
83
+ child.stdout.on('data', (d) => { stdout += d; });
84
+ child.stderr.on('data', (d) => { stderr += d; });
85
+ child.on('error', (err) => resolve({ status: -1, stdout, stderr: `spawn failed: ${err.message}` }));
86
+ child.on('close', (status) => resolve({ status, stdout, stderr }));
87
+ });
88
+ }
89
+
90
+ function assertGitCors(res, label) {
91
+ assert.strictEqual(res.headers.get('access-control-allow-origin'), '*',
92
+ `${label}: Access-Control-Allow-Origin must be *`);
93
+ assert.strictEqual(res.headers.get('access-control-allow-methods'), 'GET, POST, OPTIONS',
94
+ `${label}: Access-Control-Allow-Methods mismatch`);
95
+ assert.strictEqual(res.headers.get('access-control-allow-headers'), 'Content-Type, Authorization, Git-Protocol',
96
+ `${label}: Access-Control-Allow-Headers must include Git-Protocol (#371)`);
97
+ }
98
+
99
+ describe('git handler HTTP contract (#375)', () => {
100
+ let server;
101
+ let baseUrl;
102
+ // Repo created once in before() via a real receive-pack advertise
103
+ // (auto-init), then reused by the advertise/slash tests below.
104
+ const REPO = 'public/site';
105
+
106
+ before(async () => {
107
+ await fs.remove(DATA_DIR);
108
+ await fs.ensureDir(DATA_DIR);
109
+
110
+ const port = await getAvailablePort();
111
+ baseUrl = `http://${TEST_HOST}:${port}`;
112
+
113
+ server = createServer({
114
+ logger: false,
115
+ root: DATA_DIR,
116
+ git: true,
117
+ public: true,
118
+ });
119
+ await server.listen({ port, host: TEST_HOST });
120
+
121
+ // Materialize a repo at REPO via the auto-init path so the
122
+ // upload-pack advertise tests have something real to talk to.
123
+ const res = await fetch(`${baseUrl}/${REPO}/info/refs?service=git-receive-pack`);
124
+ assert.strictEqual(res.status, 200, 'prereq: auto-init advertise must succeed');
125
+ });
126
+
127
+ after(async () => {
128
+ if (server) await server.close();
129
+ await fs.remove(DATA_DIR);
130
+ await fs.remove(LOCAL_REPO);
131
+ });
132
+
133
+ it('OPTIONS preflight returns 200 with the canonical git CORS headers', async () => {
134
+ const res = await fetch(`${baseUrl}/${REPO}/info/refs?service=git-upload-pack`, {
135
+ method: 'OPTIONS',
136
+ });
137
+ assert.strictEqual(res.status, 200, 'preflight must be 200');
138
+ assertGitCors(res, 'OPTIONS preflight');
139
+ });
140
+
141
+ it('single-slash info/refs advertise returns 200 with the advertisement content type', async () => {
142
+ const res = await fetch(`${baseUrl}/${REPO}/info/refs?service=git-upload-pack`);
143
+ assert.strictEqual(res.status, 200);
144
+ assert.strictEqual(res.headers.get('content-type'),
145
+ 'application/x-git-upload-pack-advertisement');
146
+ });
147
+
148
+ it('double-slash //info/refs returns 200 (#373 regression)', async () => {
149
+ // git http-backend rejects "aliased" multi-slash paths; JSS must
150
+ // collapse them before forwarding or the request 500s.
151
+ const res = await fetch(`${baseUrl}/${REPO}//info/refs?service=git-upload-pack`);
152
+ assert.strictEqual(res.status, 200,
153
+ `double slash must not break the advertise; got ${res.status}`);
154
+ });
155
+
156
+ it('triple-slash ///info/refs returns 200 (#373 regression)', async () => {
157
+ const res = await fetch(`${baseUrl}/${REPO}///info/refs?service=git-upload-pack`);
158
+ assert.strictEqual(res.status, 200,
159
+ `triple slash must not break the advertise; got ${res.status}`);
160
+ });
161
+
162
+ it('missing repo returns 404 with CORS headers (#374 regression)', async () => {
163
+ // upload-pack (fetch) on a non-existent path: no auto-init, plain 404.
164
+ const res = await fetch(`${baseUrl}/public/no-such-repo/info/refs?service=git-upload-pack`);
165
+ assert.strictEqual(res.status, 404);
166
+ assertGitCors(res, 'missing-repo 404');
167
+ });
168
+
169
+ it('path traversal attempt is blocked, never 200/500, with CORS headers', async () => {
170
+ // Percent-encoded so fetch() doesn't normalize the dots away
171
+ // client-side. handleGit decodes, strips `..`, and containment-
172
+ // checks the result — depending on what survives sanitization the
173
+ // response is 403 (escape detected) or 404 (sanitized path has no
174
+ // repo). Both are acceptable; 200 (leak) and 500 (crash) are not.
175
+ const res = await fetch(
176
+ `${baseUrl}/%2e%2e/%2e%2e/%2e%2e/etc/info/refs?service=git-upload-pack`);
177
+ assert.ok(res.status === 403 || res.status === 404,
178
+ `traversal must be blocked with 403/404, got ${res.status}`);
179
+ assertGitCors(res, 'traversal block');
180
+ });
181
+
182
+ it('unauthenticated push advertise returns 401 with WWW-Authenticate and git CORS headers (non-public server, #548)', async () => {
183
+ // Second server WITHOUT public:true so the WAC preHandler gates
184
+ // the push. Snapshot/restore DATA_ROOT — createServer({ root })
185
+ // mutates it process-wide and the main suite's server reads it
186
+ // per-request.
187
+ const DATA_DIR_AUTH = './test-data-git-handler-auth';
188
+ await fs.remove(DATA_DIR_AUTH);
189
+ await fs.ensureDir(DATA_DIR_AUTH);
190
+ const port = await getAvailablePort();
191
+ const originalDataRoot = process.env.DATA_ROOT;
192
+ const authServer = createServer({ logger: false, root: DATA_DIR_AUTH, git: true });
193
+ try {
194
+ await authServer.listen({ port, host: TEST_HOST });
195
+ const res = await fetch(
196
+ `http://${TEST_HOST}:${port}/public/x/info/refs?service=git-receive-pack`);
197
+ assert.strictEqual(res.status, 401,
198
+ `unauthenticated push advertise must be 401, got ${res.status}`);
199
+ assert.ok(res.headers.get('www-authenticate'),
200
+ 'WWW-Authenticate must be present so git CLI clients prompt for credentials');
201
+ // #548: the WAC preHandler's 401/403 path must carry the git
202
+ // CORS headers, or browser git clients see a generic CORS error
203
+ // instead of the auth challenge.
204
+ assertGitCors(res, 'unauthenticated push 401');
205
+ } finally {
206
+ await authServer.close();
207
+ if (originalDataRoot === undefined) delete process.env.DATA_ROOT;
208
+ else process.env.DATA_ROOT = originalDataRoot;
209
+ await fs.remove(DATA_DIR_AUTH);
210
+ }
211
+ });
212
+
213
+ it('end-to-end push succeeds and the pushed file is served as a static resource', async () => {
214
+ // Build a local repo with one file and push it. Auto-init pins the
215
+ // server-side HEAD to refs/heads/main (#471), so pushing HEAD:main
216
+ // triggers receive.denyCurrentBranch=updateInstead extraction and
217
+ // the file becomes a static resource at the pod URL.
218
+ await fs.remove(LOCAL_REPO);
219
+ await fs.ensureDir(LOCAL_REPO);
220
+ assert.strictEqual(git(['init', '--quiet'], LOCAL_REPO).status, 0, 'git init');
221
+ await fs.writeFile(path.join(LOCAL_REPO, 'index.html'), '<p>pushed-via-test</p>\n');
222
+ assert.strictEqual(git(['add', 'index.html'], LOCAL_REPO).status, 0, 'git add');
223
+ const commit = git([
224
+ '-c', 'user.email=test@example.invalid',
225
+ '-c', 'user.name=jss-test',
226
+ 'commit', '--quiet', '-m', 'test commit',
227
+ ], LOCAL_REPO);
228
+ assert.strictEqual(commit.status, 0, `git commit failed: ${commit.stderr}`);
229
+
230
+ const push = await gitAsync(['push', '--quiet', `${baseUrl}/public/pushed-site`, 'HEAD:main'], LOCAL_REPO);
231
+ assert.strictEqual(push.status, 0, `git push failed: ${push.stderr.slice(0, 400)}`);
232
+
233
+ // updateInstead extracted the working tree → file is now served.
234
+ const res = await fetch(`${baseUrl}/public/pushed-site/index.html`);
235
+ assert.strictEqual(res.status, 200, 'pushed file must be served over HTTP');
236
+ const body = await res.text();
237
+ assert.ok(body.includes('pushed-via-test'), 'served content must match the pushed file');
238
+ });
239
+ });
@@ -0,0 +1,249 @@
1
+ /**
2
+ * HEAD/GET content-type parity for files (#552).
3
+ *
4
+ * GET runs content negotiation on files (q-aware since #325), but HEAD's
5
+ * file branch reported the STORED content type regardless of the Accept
6
+ * header — an RFC 9110 §9.3.2 violation (HEAD should send the same
7
+ * header fields as GET). Clients that probe with HEAD before fetching
8
+ * saw a content type the subsequent GET never returned.
9
+ *
10
+ * The fix routes HEAD's file branch through the same decision tree GET
11
+ * uses (negotiateHeadFileContentType). The core pin here is the parity
12
+ * loop: for each Accept variant, HEAD's content-type must byte-equal
13
+ * GET's on the same resource.
14
+ *
15
+ * Also pinned: when the negotiated form is a CONVERSION (GET would
16
+ * re-serialize the body), HEAD must omit Content-Length rather than
17
+ * report the on-disk size of a body GET never sends.
18
+ */
19
+
20
+ import { describe, it, before, after } from 'node:test';
21
+ import assert from 'node:assert';
22
+ import { createServer } from '../src/server.js';
23
+ import { createServer as createNetServer } from 'net';
24
+ import fs from 'fs-extra';
25
+ import path from 'path';
26
+
27
+ const TEST_HOST = 'localhost';
28
+ const DATA_DIR = './test-data-head-conneg';
29
+
30
+ function getAvailablePort() {
31
+ return new Promise((resolve, reject) => {
32
+ const srv = createNetServer();
33
+ srv.on('error', reject);
34
+ srv.listen(0, TEST_HOST, () => {
35
+ const port = srv.address().port;
36
+ srv.close(() => resolve(port));
37
+ });
38
+ });
39
+ }
40
+
41
+ describe('HEAD/GET content-type parity (#552)', () => {
42
+ let server;
43
+ let baseUrl;
44
+ let originalDataRoot;
45
+
46
+ before(async () => {
47
+ originalDataRoot = process.env.DATA_ROOT;
48
+ await fs.remove(DATA_DIR);
49
+ await fs.ensureDir(DATA_DIR);
50
+
51
+ const port = await getAvailablePort();
52
+ baseUrl = `http://${TEST_HOST}:${port}`;
53
+
54
+ server = createServer({
55
+ logger: false,
56
+ root: DATA_DIR,
57
+ conneg: true,
58
+ public: true,
59
+ forceCloseConnections: true,
60
+ });
61
+ await server.listen({ port, host: TEST_HOST });
62
+
63
+ // JSON-LD resource (the #552 reproduction target)
64
+ const put = await fetch(`${baseUrl}/public/parity.jsonld`, {
65
+ method: 'PUT',
66
+ headers: { 'Content-Type': 'application/ld+json' },
67
+ body: JSON.stringify({
68
+ '@context': { name: 'http://xmlns.com/foaf/0.1/name' },
69
+ '@id': '#it',
70
+ name: 'head-parity-test',
71
+ }),
72
+ });
73
+ assert.strictEqual(put.status, 201, 'prereq: PUT must succeed');
74
+
75
+ // Extensionless HTML file — exercises GET's octet-stream HTML sniff.
76
+ // Written directly to disk: PUT would route content-type by extension.
77
+ await fs.writeFile(path.join(DATA_DIR, 'public', 'noext-html'),
78
+ '<!DOCTYPE html><html><body>sniff me</body></html>');
79
+ });
80
+
81
+ after(async () => {
82
+ if (server) await server.close();
83
+ if (originalDataRoot === undefined) delete process.env.DATA_ROOT;
84
+ else process.env.DATA_ROOT = originalDataRoot;
85
+ await fs.remove(DATA_DIR);
86
+ });
87
+
88
+ const ACCEPT_VARIANTS = [
89
+ ['application/ld+json, text/turtle, application/json', 'ld+json first'],
90
+ ['text/turtle, application/ld+json', 'turtle first'],
91
+ ['application/ld+json;q=0.5, text/turtle', 'turtle preferred via q'],
92
+ ['', 'no Accept header'],
93
+ ];
94
+
95
+ // Compare MEDIA TYPES (parameters stripped): Fastify appends
96
+ // `; charset=utf-8` when it serializes a string BODY, which HEAD
97
+ // never has — the charset parameter is a body-serialization
98
+ // artifact, not part of what negotiation decides.
99
+ const mediaType = (res) => (res.headers.get('content-type') || '').split(';')[0].trim();
100
+
101
+ it('HEAD media type and Cache-Control equal GET\'s for every Accept variant (RFC 9110 §9.3.2)', async () => {
102
+ for (const [accept, label] of ACCEPT_VARIANTS) {
103
+ const headers = accept ? { Accept: accept } : {};
104
+ const getRes = await fetch(`${baseUrl}/public/parity.jsonld`, { headers });
105
+ const headRes = await fetch(`${baseUrl}/public/parity.jsonld`, { method: 'HEAD', headers });
106
+ assert.strictEqual(getRes.status, 200, `${label}: GET must 200`);
107
+ assert.strictEqual(headRes.status, 200, `${label}: HEAD must 200`);
108
+ assert.strictEqual(mediaType(headRes), mediaType(getRes),
109
+ `${label}: HEAD media type must equal GET's`);
110
+ // GET applies RDF_CACHE_CONTROL to RDF responses; HEAD must agree.
111
+ assert.strictEqual(
112
+ headRes.headers.get('cache-control'),
113
+ getRes.headers.get('cache-control'),
114
+ `${label}: HEAD Cache-Control must equal GET's`,
115
+ );
116
+ }
117
+ });
118
+
119
+ it('HEAD Cache-Control matches GET on container listings too', async () => {
120
+ // GET applies RDF_CACHE_CONTROL uniformly wherever the response
121
+ // type is RDF — including container listings, not just files.
122
+ const getRes = await fetch(`${baseUrl}/public/`);
123
+ const headRes = await fetch(`${baseUrl}/public/`, { method: 'HEAD' });
124
+ assert.strictEqual(getRes.status, 200);
125
+ assert.strictEqual(headRes.status, 200);
126
+ assert.strictEqual(mediaType(headRes), mediaType(getRes),
127
+ 'container HEAD media type must equal GET\'s');
128
+ assert.strictEqual(
129
+ headRes.headers.get('cache-control'),
130
+ getRes.headers.get('cache-control'),
131
+ 'container HEAD Cache-Control must equal GET\'s',
132
+ );
133
+ });
134
+
135
+ it('HEAD honors a Turtle-preferring Accept on a stored-JSON-LD file (the #552 bug)', async () => {
136
+ const res = await fetch(`${baseUrl}/public/parity.jsonld`, {
137
+ method: 'HEAD',
138
+ headers: { Accept: 'text/turtle, application/ld+json' },
139
+ });
140
+ assert.strictEqual(res.status, 200);
141
+ assert.match(res.headers.get('content-type'), /text\/turtle/,
142
+ 'HEAD must report the negotiated Turtle, not the stored JSON-LD');
143
+ });
144
+
145
+ it('HEAD omits Content-Length when GET would convert the body', async () => {
146
+ // GET re-serializes JSON-LD → Turtle; its body length is not the
147
+ // on-disk size, so HEAD claiming stats.size would be a lie.
148
+ const res = await fetch(`${baseUrl}/public/parity.jsonld`, {
149
+ method: 'HEAD',
150
+ headers: { Accept: 'text/turtle' },
151
+ });
152
+ assert.strictEqual(res.headers.get('content-length'), null,
153
+ 'no Content-Length on a conneg-converted HEAD');
154
+ });
155
+
156
+ it('HEAD keeps Content-Length for as-is responses', async () => {
157
+ // Extensionless HTML: GET relabels (text/html) but serves the raw
158
+ // bytes, so the on-disk size IS the body length.
159
+ const res = await fetch(`${baseUrl}/public/noext-html`, { method: 'HEAD' });
160
+ assert.strictEqual(res.status, 200);
161
+ assert.match(res.headers.get('content-type'), /text\/html/,
162
+ 'extensionless HTML sniff must apply to HEAD like GET');
163
+ assert.ok(res.headers.get('content-length'),
164
+ 'as-is responses keep Content-Length');
165
+ });
166
+
167
+ it('HEAD negotiates large (>1 MiB) RDF files too — optimistic path, no full read', async () => {
168
+ // Copilot review case on the first draft: the full-read cap must
169
+ // not regress parity for large VALID RDF documents. Above the cap
170
+ // HEAD skips the parse gate and trusts the extension.
171
+ const big = {
172
+ '@context': { name: 'http://xmlns.com/foaf/0.1/name' },
173
+ '@id': '#it',
174
+ name: 'x'.repeat(1024 * 1024 + 1024), // > HEAD_FULL_READ_MAX_BYTES
175
+ };
176
+ await fs.writeFile(path.join(DATA_DIR, 'public', 'big.jsonld'), JSON.stringify(big));
177
+ const res = await fetch(`${baseUrl}/public/big.jsonld`, {
178
+ method: 'HEAD',
179
+ headers: { Accept: 'text/turtle, application/ld+json' },
180
+ });
181
+ assert.strictEqual(res.status, 200);
182
+ assert.match(res.headers.get('content-type'), /text\/turtle/,
183
+ 'large valid RDF must still negotiate on HEAD');
184
+ assert.strictEqual(res.headers.get('content-length'), null,
185
+ 'converted large-file HEAD must omit Content-Length');
186
+ });
187
+
188
+ it('HEAD sniffs large (>1 MiB) extensionless HTML via bounded ranged read', async () => {
189
+ const filler = '<!DOCTYPE html><html><body>' + 'y'.repeat(1024 * 1024 + 1024) + '</body></html>';
190
+ await fs.writeFile(path.join(DATA_DIR, 'public', 'big-noext'), filler);
191
+ const res = await fetch(`${baseUrl}/public/big-noext`, { method: 'HEAD' });
192
+ assert.strictEqual(res.status, 200);
193
+ assert.match(res.headers.get('content-type'), /text\/html/,
194
+ 'the HTML sniff only needs the first bytes — size must not disable it');
195
+ assert.ok(res.headers.get('content-length'),
196
+ 'as-is large file keeps Content-Length');
197
+ });
198
+
199
+ it('island negotiation keys off content, not stored type (.xhtml file, pass-3 review case)', async () => {
200
+ // GET's data-island branch is gated on CONTENT only — a .xhtml
201
+ // file (stored type application/xhtml+xml) whose body starts with
202
+ // <html and carries a parseable island converts to Turtle. HEAD
203
+ // must agree.
204
+ const xhtml = '<html xmlns="http://www.w3.org/1999/xhtml"><head>' +
205
+ '<script type="application/ld+json">' +
206
+ JSON.stringify({ '@context': { name: 'http://xmlns.com/foaf/0.1/name' }, '@id': '#it', name: 'xhtml-island' }) +
207
+ '</script></head><body/></html>';
208
+ await fs.writeFile(path.join(DATA_DIR, 'public', 'island.xhtml'), xhtml);
209
+
210
+ const headers = { Accept: 'text/turtle, application/ld+json' };
211
+ const getRes = await fetch(`${baseUrl}/public/island.xhtml`, { headers });
212
+ const headRes = await fetch(`${baseUrl}/public/island.xhtml`, { method: 'HEAD', headers });
213
+ assert.strictEqual(getRes.status, 200);
214
+ assert.strictEqual(headRes.status, 200);
215
+ assert.strictEqual(mediaType(headRes), mediaType(getRes),
216
+ `xhtml island: HEAD (${mediaType(headRes)}) must equal GET (${mediaType(getRes)})`);
217
+ });
218
+
219
+ it('island detection survives >1 KiB of leading whitespace (pass-4 review case)', async () => {
220
+ // GET trims the FULL body before its <!DOCTYPE/<html check, so a
221
+ // whitespace-padded island document still negotiates to Turtle.
222
+ // HEAD's 1 KiB sniff must escalate to the full read when the chunk
223
+ // is entirely whitespace, not silently miss the marker.
224
+ const padded = ' '.repeat(2048) + '<html><head>' +
225
+ '<script type="application/ld+json">' +
226
+ JSON.stringify({ '@context': { name: 'http://xmlns.com/foaf/0.1/name' }, '@id': '#it', name: 'padded' }) +
227
+ '</script></head><body/></html>';
228
+ await fs.writeFile(path.join(DATA_DIR, 'public', 'padded.xhtml'), padded);
229
+
230
+ const headers = { Accept: 'text/turtle, application/ld+json' };
231
+ const getRes = await fetch(`${baseUrl}/public/padded.xhtml`, { headers });
232
+ const headRes = await fetch(`${baseUrl}/public/padded.xhtml`, { method: 'HEAD', headers });
233
+ assert.strictEqual(getRes.status, 200);
234
+ assert.strictEqual(headRes.status, 200);
235
+ assert.strictEqual(mediaType(headRes), mediaType(getRes),
236
+ `whitespace-padded island: HEAD (${mediaType(headRes)}) must equal GET (${mediaType(getRes)})`);
237
+ });
238
+
239
+ it('HEAD with If-None-Match still returns 304 (negotiation must not break revalidation)', async () => {
240
+ const probe = await fetch(`${baseUrl}/public/parity.jsonld`, { method: 'HEAD' });
241
+ const etag = probe.headers.get('etag');
242
+ assert.ok(etag, 'prereq: ETag present');
243
+ const res = await fetch(`${baseUrl}/public/parity.jsonld`, {
244
+ method: 'HEAD',
245
+ headers: { 'If-None-Match': etag },
246
+ });
247
+ assert.strictEqual(res.status, 304);
248
+ });
249
+ });