javascript-solid-server 0.0.224 → 0.0.226

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,145 @@
1
+ /**
2
+ * NIP-98 verifier: a signed header authorizes one request, one method, one
3
+ * URL (#643). Reported privately by Kraig Parkinson against v0.0.225.
4
+ *
5
+ * Before: the method tag was optional and `*` a wildcard, the `u` tag matched
6
+ * by prefix, and nothing remembered an event id, so an Authorization header
7
+ * captured from a GET of the pod root could be replayed within 60 s as a PUT
8
+ * or DELETE on any sub-path. The git smart-HTTP routes keep the lenient rules
9
+ * (credential helpers sign once for the repo base); everywhere else the
10
+ * NIP-98 MUSTs apply and a reused event id is rejected.
11
+ */
12
+
13
+ import { describe, it } from 'node:test';
14
+ import assert from 'node:assert';
15
+ import { createHash } from 'node:crypto';
16
+ import { verifyNostrAuth } from '../src/auth/nostr.js';
17
+ import { generateSecretKey, finalizeEvent, nip98Token } from '../src/nostr/event.js';
18
+
19
+ const HOST = 'pod.example';
20
+ const sk = generateSecretKey();
21
+
22
+ function tokenFromTags(tags) {
23
+ const event = finalizeEvent({ kind: 27235, tags, content: '' }, sk);
24
+ return Buffer.from(JSON.stringify(event)).toString('base64');
25
+ }
26
+
27
+ function req({ url, method = 'GET', token, body, git = false, type }) {
28
+ const r = { url, method, protocol: 'http', hostname: HOST, headers: { host: HOST, authorization: `Nostr ${token}` }, server: { gitEnabled: git } };
29
+ if (type) r.headers['content-type'] = type;
30
+ if (body !== undefined) { r.body = body; r.rawBody = body; }
31
+ return r;
32
+ }
33
+ const PACK = 'application/x-git-receive-pack-request';
34
+
35
+ // Every path here is unowned, so the resolver chain ends at did:nostr:<pubkey>.
36
+ const isAuthed = (r) => r.error === null && typeof r.webId === 'string' && r.webId.startsWith('did:nostr:');
37
+
38
+ describe('NIP-98 verifier: one header, one request (#643)', () => {
39
+ it('a correctly signed GET verifies', async () => {
40
+ const token = nip98Token(`http://${HOST}/alice/notes/`, 'GET', sk);
41
+ assert.ok(isAuthed(await verifyNostrAuth(req({ url: '/alice/notes/', token }))));
42
+ });
43
+
44
+ it('the same event id a second time is rejected', async () => {
45
+ const token = nip98Token(`http://${HOST}/alice/again/`, 'GET', sk);
46
+ assert.ok(isAuthed(await verifyNostrAuth(req({ url: '/alice/again/', token }))));
47
+ const again = await verifyNostrAuth(req({ url: '/alice/again/', token }));
48
+ assert.strictEqual(again.webId, null);
49
+ assert.match(again.error, /Replayed event id/);
50
+ });
51
+
52
+ it('a missing method tag is rejected outside git routes', async () => {
53
+ const token = tokenFromTags([['u', `http://${HOST}/alice/`]]);
54
+ const r = await verifyNostrAuth(req({ url: '/alice/', method: 'DELETE', token }));
55
+ assert.strictEqual(r.webId, null);
56
+ assert.match(r.error, /Missing method tag/);
57
+ });
58
+
59
+ it('a wildcard method is rejected outside git routes', async () => {
60
+ const token = tokenFromTags([['u', `http://${HOST}/alice/`], ['method', '*']]);
61
+ const r = await verifyNostrAuth(req({ url: '/alice/', method: 'DELETE', token }));
62
+ assert.strictEqual(r.webId, null);
63
+ assert.match(r.error, /Wildcard method/);
64
+ });
65
+
66
+ it('a signature for the base URL does not cover a sub-path outside git routes', async () => {
67
+ const token = nip98Token(`http://${HOST}/alice/`, 'GET', sk);
68
+ const r = await verifyNostrAuth(req({ url: '/alice/secret.json', token }));
69
+ assert.strictEqual(r.webId, null);
70
+ assert.match(r.error, /URL mismatch/);
71
+ });
72
+
73
+ it('a GET token replayed as a PUT with a body is rejected twice over', async () => {
74
+ const token = nip98Token(`http://${HOST}/alice/notes/`, 'GET', sk);
75
+ const r = await verifyNostrAuth(req({ url: '/alice/notes/', method: 'PUT', token, body: '{"owned":true}' }));
76
+ assert.strictEqual(r.webId, null);
77
+ assert.match(r.error, /Method mismatch/);
78
+ });
79
+
80
+ it('a PUT with a body needs the payload tag', async () => {
81
+ const token = nip98Token(`http://${HOST}/alice/doc.json`, 'PUT', sk);
82
+ const r = await verifyNostrAuth(req({ url: '/alice/doc.json', method: 'PUT', token, body: '{"a":1}' }));
83
+ assert.strictEqual(r.webId, null);
84
+ assert.match(r.error, /Missing payload tag/);
85
+ });
86
+
87
+ it('a PUT with a matching payload tag verifies', async () => {
88
+ const body = '{"a":1}';
89
+ const token = nip98Token(`http://${HOST}/alice/doc2.json`, 'PUT', sk, body);
90
+ assert.ok(isAuthed(await verifyNostrAuth(req({ url: '/alice/doc2.json', method: 'PUT', token, body }))));
91
+ });
92
+
93
+ it('a PUT with a mismatching payload tag is still rejected', async () => {
94
+ const token = nip98Token(`http://${HOST}/alice/doc3.json`, 'PUT', sk, '{"a":1}');
95
+ const r = await verifyNostrAuth(req({ url: '/alice/doc3.json', method: 'PUT', token, body: '{"a":2}' }));
96
+ assert.match(r.error, /Payload hash mismatch/);
97
+ });
98
+
99
+ it('git routes keep the lenient rules: wildcard method and base-URL prefix', async () => {
100
+ const token = tokenFromTags([['u', `http://${HOST}/alice/repo`], ['method', '*']]);
101
+ const r = await verifyNostrAuth(req({ url: '/alice/repo/info/refs?service=git-receive-pack', token, git: true }));
102
+ assert.ok(isAuthed(r), r.error);
103
+ const push = tokenFromTags([['u', `http://${HOST}/alice/repo`]]);
104
+ const r2 = await verifyNostrAuth(req({ url: '/alice/repo/git-receive-pack', method: 'POST', token: push, body: Buffer.from('0000'), git: true, type: PACK }));
105
+ assert.ok(isAuthed(r2), r2.error);
106
+ });
107
+
108
+ it('a git-looking path is strict when git is off, or when the request is not git-shaped', async () => {
109
+ const off = tokenFromTags([['u', `http://${HOST}/alice/notes/git-receive-pack`], ['method', '*']]);
110
+ const r = await verifyNostrAuth(req({ url: '/alice/notes/git-receive-pack', method: 'POST', token: off, body: 'x', git: false, type: PACK }));
111
+ assert.match(r.error, /Wildcard method/);
112
+ const plainGet = tokenFromTags([['u', `http://${HOST}/alice/notes/info/refs`], ['method', '*']]);
113
+ const r2 = await verifyNostrAuth(req({ url: '/alice/notes/info/refs', token: plainGet, git: true })); // no service query
114
+ assert.match(r2.error, /Wildcard method/);
115
+ const putPack = tokenFromTags([['u', `http://${HOST}/alice/notes/git-upload-pack`]]);
116
+ const r3 = await verifyNostrAuth(req({ url: '/alice/notes/git-upload-pack', method: 'PUT', token: putPack, body: 'x', git: true, type: 'text/plain' }));
117
+ assert.match(r3.error, /Missing method tag/);
118
+ });
119
+
120
+ it('git routes accept the same token for every request of one operation', async () => {
121
+ const token = tokenFromTags([['u', `http://${HOST}/alice/twice`], ['method', '*']]);
122
+ const r1 = await verifyNostrAuth(req({ url: '/alice/twice/info/refs?service=git-receive-pack', token, git: true }));
123
+ assert.ok(isAuthed(r1), r1.error);
124
+ const r2 = await verifyNostrAuth(req({ url: '/alice/twice/git-receive-pack', method: 'POST', token, body: Buffer.from('0000'), git: true, type: PACK }));
125
+ assert.ok(isAuthed(r2), r2.error);
126
+ });
127
+
128
+ it('the replay cache forgets an id once it can no longer verify', async () => {
129
+ const token = nip98Token(`http://${HOST}/alice/old/`, 'GET', sk);
130
+ assert.ok(isAuthed(await verifyNostrAuth(req({ url: '/alice/old/', token }))));
131
+ const event = JSON.parse(Buffer.from(token, 'base64').toString());
132
+ const stale = { ...event, created_at: event.created_at - 200 }; // outside ±60 s, so rejected on time, never on replay
133
+ const staleToken = Buffer.from(JSON.stringify(stale)).toString('base64');
134
+ const r = await verifyNostrAuth(req({ url: '/alice/old/', token: staleToken }));
135
+ assert.match(r.error, /timestamp/);
136
+ assert.ok(!/Replayed/.test(r.error));
137
+ });
138
+
139
+ it('a payload hash is computed over the raw bytes (unchanged)', async () => {
140
+ const body = Buffer.from([0xff, 0x00, 0x10]);
141
+ const token = tokenFromTags([['u', `http://${HOST}/alice/bin`], ['method', 'PUT'], ['payload', createHash('sha256').update(body).digest('hex')]]);
142
+ const r = { url: '/alice/bin', method: 'PUT', protocol: 'http', hostname: HOST, headers: { host: HOST, authorization: `Nostr ${token}` }, body };
143
+ assert.ok(isAuthed(await verifyNostrAuth(r)));
144
+ });
145
+ });
@@ -175,6 +175,17 @@ describe('api.reservePath (#602)', () => {
175
175
  assert.ok([401, 403].includes(put.status), `expected WAC rejection, got ${put.status}`);
176
176
  });
177
177
 
178
+ // #611 residual after #607: a widened method at a path the shim did NOT
179
+ // register must not fall through to the WAC-skipped LDP wildcard.
180
+ it('a widened method at an unhandled reserved path is 404, not a storage write', async () => {
181
+ await start([{ id: 'writer', module: path.join(FIXTURE_DIR, 'write-shim.js'), prefix: '/w' }]);
182
+ await fs.ensureDir(path.join(TEST_DATA_DIR, 'api'));
183
+ const res = await fetch(`${baseUrl}/api/unhandled`, { method: 'POST', headers: { 'Content-Type': 'text/plain' }, body: 'planted' });
184
+ assert.strictEqual(res.status, 404);
185
+ const planted = await fs.readdir(path.join(TEST_DATA_DIR, 'api'));
186
+ assert.deepStrictEqual(planted, [], `nothing may be written: ${planted.join(', ')}`);
187
+ });
188
+
178
189
  it('WAC still guards unreserved paths', async () => {
179
190
  await start(MAIN());
180
191
  const res = await fetch(`${baseUrl}/somepod/private/x`, { method: 'PUT', body: 'data' });
@@ -0,0 +1,81 @@
1
+ /**
2
+ * storage.withLock: a slow holder keeps its lock, a dead holder loses it (#600)
3
+ */
4
+
5
+ import { describe, it, before, after } from 'node:test';
6
+ import assert from 'node:assert';
7
+ import fs from 'fs-extra';
8
+ import os from 'os';
9
+ import path from 'path';
10
+ import { withLock, lockPathFor } from '../src/storage/filesystem.js';
11
+
12
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
13
+ let ROOT, originalDataRoot;
14
+
15
+ describe('withLock', () => {
16
+ before(async () => {
17
+ originalDataRoot = process.env.DATA_ROOT;
18
+ ROOT = await fs.mkdtemp(path.join(os.tmpdir(), 'jss-lock-'));
19
+ process.env.DATA_ROOT = ROOT;
20
+ await fs.ensureDir(path.join(ROOT, 'pod'));
21
+ });
22
+
23
+ after(async () => {
24
+ if (originalDataRoot === undefined) delete process.env.DATA_ROOT; else process.env.DATA_ROOT = originalDataRoot;
25
+ await fs.remove(ROOT);
26
+ });
27
+
28
+ it('a holder slower than the stale timeout keeps the lock: the second writer waits for it', async () => {
29
+ const log = [];
30
+ const opts = { staleMs: 100, waitMs: 5000 };
31
+ const a = withLock('/pod/slow.json', async () => { await sleep(400); log.push('A done'); }, opts);
32
+ await sleep(20);
33
+ const b = withLock('/pod/slow.json', async () => { log.push('B start'); }, opts);
34
+ await Promise.all([a, b]);
35
+ assert.deepStrictEqual(log, ['A done', 'B start']);
36
+ });
37
+
38
+ it('a lock left by a dead holder is broken after the stale timeout', async () => {
39
+ const lockPath = lockPathFor('/pod/dead.json');
40
+ await fs.writeFile(lockPath, '');
41
+ const old = new Date(Date.now() - 60_000);
42
+ await fs.utimes(lockPath, old, old);
43
+ const started = Date.now();
44
+ let ran = false;
45
+ await withLock('/pod/dead.json', async () => { ran = true; }, { staleMs: 100, waitMs: 5000 });
46
+ assert.ok(ran, 'fn ran');
47
+ assert.ok(Date.now() - started < 1000, 'acquired without waiting out the timeout');
48
+ assert.ok(!await fs.pathExists(lockPath), 'lock removed afterwards');
49
+ });
50
+
51
+ it('many contenders on a dead lock: all run, never two at once, no lock left behind', async () => {
52
+ const lockPath = lockPathFor('/pod/crowd.json');
53
+ await fs.writeFile(lockPath, '');
54
+ const old = new Date(Date.now() - 60_000);
55
+ await fs.utimes(lockPath, old, old);
56
+ let inside = 0, peak = 0, ran = 0;
57
+ const opts = { staleMs: 100, waitMs: 5000 };
58
+ await Promise.all(Array.from({ length: 8 }, () => withLock('/pod/crowd.json', async () => {
59
+ inside++; peak = Math.max(peak, inside); ran++;
60
+ await sleep(30);
61
+ inside--;
62
+ }, opts)));
63
+ assert.strictEqual(ran, 8, 'every contender ran');
64
+ assert.strictEqual(peak, 1, 'never two holders at once');
65
+ assert.ok(!await fs.pathExists(lockPath), 'lock removed afterwards');
66
+ const leftovers = (await fs.readdir(path.join(ROOT, 'pod'))).filter((n) => n.startsWith('.crowd.json.lock'));
67
+ assert.deepStrictEqual(leftovers, [], 'no moved-aside lock files left');
68
+ });
69
+
70
+ it('a live lock that is never released ends in ELOCKED after waitMs', async () => {
71
+ const lockPath = lockPathFor('/pod/held.json');
72
+ await fs.writeFile(lockPath, '');
73
+ const keep = setInterval(() => { const n = new Date(); fs.utimes(lockPath, n, n).catch(() => {}); }, 20);
74
+ try {
75
+ await assert.rejects(withLock('/pod/held.json', async () => {}, { staleMs: 100, waitMs: 300 }), (e) => e.code === 'ELOCKED');
76
+ } finally {
77
+ clearInterval(keep);
78
+ await fs.remove(lockPath);
79
+ }
80
+ });
81
+ });