javascript-solid-server 0.0.188 → 0.0.190

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,284 @@
1
+ /**
2
+ * Integration tests for the wired --provision-keys / `provisionKeys: true`
3
+ * pod-creation flow (Phase 1 of #437).
4
+ *
5
+ * Covers:
6
+ * - POST /.pods with provisionKeys: true writes a Multikey doc
7
+ * to <pod>/private/privkey.jsonld
8
+ * - The seeded ACL on /private/ keeps the file private (401 unauth,
9
+ * 200 with the owner token) — defence-in-depth alongside the
10
+ * 0o600 file mode set by storage.write.
11
+ * - The HTTP response surfaces the public side (publicKeyMultibase)
12
+ * and the file URL, but never echoes the secret.
13
+ * - Default behaviour (no flag) does NOT write the file — opt-in
14
+ * stays opt-in.
15
+ * - createPodStructure called directly with provisionKeys returns
16
+ * the freshly-minted key material so a CLI caller can display it.
17
+ * - createPodStructure with provisionKeys=false returns no ownerKey.
18
+ */
19
+
20
+ import { describe, it, before, after } from 'node:test';
21
+ import assert from 'node:assert';
22
+ import fs from 'fs-extra';
23
+ import path from 'path';
24
+ import {
25
+ startTestServer,
26
+ stopTestServer,
27
+ request,
28
+ assertStatus,
29
+ getBaseUrl
30
+ } from './helpers.js';
31
+
32
+ // Local token stash — the createTestPod helper hardwires its own
33
+ // fetch call so we can't use it for the provisionKeys-true variant;
34
+ // just keep the token returned by our manual POST around for the
35
+ // authenticated WAC test below.
36
+ let ownerToken = null;
37
+ import { createPodStructure } from '../src/handlers/container.js';
38
+ import { decodeFFormSecp256k1 } from '../src/auth/nostr-keys.js';
39
+
40
+ describe('POST /.pods — provisionKeys: true (Phase 1 of #437)', () => {
41
+ before(async () => {
42
+ await startTestServer();
43
+ });
44
+ after(async () => {
45
+ await stopTestServer();
46
+ });
47
+
48
+ it('creates the pod and writes /private/privkey.jsonld', async () => {
49
+ const res = await fetch(`${getBaseUrl()}/.pods`, {
50
+ method: 'POST',
51
+ headers: { 'Content-Type': 'application/json' },
52
+ body: JSON.stringify({ name: 'keyowner', provisionKeys: true })
53
+ });
54
+ assertStatus(res, 201);
55
+ const body = await res.json();
56
+ ownerToken = body.token;
57
+
58
+ // Response surfaces the public side, never the secret.
59
+ assert.ok(body.ownerKey, 'response should include ownerKey summary');
60
+ assert.strictEqual(body.ownerKey.keyDocument, `${body.podUri}private/privkey.jsonld`);
61
+ assert.match(body.ownerKey.publicKeyMultibase, /^fe70102[0-9a-f]{64}$/,
62
+ 'publicKeyMultibase should be the f-form secp256k1-pub Multikey');
63
+ // No secret key on the wire under any field name.
64
+ const flat = JSON.stringify(body);
65
+ assert.doesNotMatch(flat, /secretKey|secret_key|nsec|privateKey/i,
66
+ 'response must not echo any secret material');
67
+
68
+ // The file exists on disk and parses as the expected Multikey doc.
69
+ const filePath = path.join('./data', 'keyowner', 'private', 'privkey.jsonld');
70
+ assert.ok(await fs.pathExists(filePath), '/private/privkey.jsonld must exist');
71
+ const doc = JSON.parse(await fs.readFile(filePath, 'utf8'));
72
+ assert.strictEqual(doc['@context'], 'https://www.w3.org/ns/cid/v1');
73
+ assert.strictEqual(doc.type, 'Multikey');
74
+ // Phase 2 of #437 (#443): controller is now did:nostr:<hex>,
75
+ // computed from the freshly-minted publicHex. Round-trips through
76
+ // jss's existing did:nostr resolver.
77
+ assert.match(doc.controller, /^did:nostr:[0-9a-f]{64}$/,
78
+ 'Phase 2 controller is did:nostr:<hex>');
79
+ assert.match(doc.publicKeyMultibase, /^fe70102[0-9a-f]{64}$/);
80
+ assert.match(doc.secretKeyMultibase, /^f8126[0-9a-f]{64}$/);
81
+ // Round-trip the public side through jss's existing decoder.
82
+ const xonly = decodeFFormSecp256k1(doc.publicKeyMultibase);
83
+ assert.match(xonly, /^[0-9a-f]{64}$/);
84
+ });
85
+
86
+ it('writes the secret with file mode 0o600 (POSIX defence-in-depth)', { skip: process.platform === 'win32' }, async () => {
87
+ const filePath = path.join('./data', 'keyowner', 'private', 'privkey.jsonld');
88
+ const stat = await fs.stat(filePath);
89
+ // Strip the file-type bits (0o170000) and assert the perm bits.
90
+ const mode = stat.mode & 0o777;
91
+ assert.strictEqual(mode, 0o600,
92
+ `Expected 0o600 on the secret key file, got 0o${mode.toString(8)}`);
93
+ });
94
+
95
+ it('blocks unauthenticated reads of the secret key (WAC)', async () => {
96
+ const res = await request('/keyowner/private/privkey.jsonld');
97
+ assertStatus(res, 401);
98
+ });
99
+
100
+ it('serves the secret to the authenticated owner (WAC)', async () => {
101
+ assert.ok(ownerToken, 'pod owner token captured from the create response');
102
+ const res = await fetch(`${getBaseUrl()}/keyowner/private/privkey.jsonld`, {
103
+ headers: { Authorization: `Bearer ${ownerToken}` }
104
+ });
105
+ assertStatus(res, 200);
106
+ const doc = await res.json();
107
+ // The web user (pod owner) reads via HTTP/WAC — file mode 0o600
108
+ // restricts unix-user-on-the-box access only, never this path.
109
+ assert.strictEqual(doc.type, 'Multikey');
110
+ assert.match(doc.secretKeyMultibase, /^f8126[0-9a-f]{64}$/);
111
+ });
112
+
113
+ it('does NOT write a key file when provisionKeys is omitted (opt-in)', async () => {
114
+ const res = await fetch(`${getBaseUrl()}/.pods`, {
115
+ method: 'POST',
116
+ headers: { 'Content-Type': 'application/json' },
117
+ body: JSON.stringify({ name: 'nokeys' })
118
+ });
119
+ assertStatus(res, 201);
120
+ const body = await res.json();
121
+ assert.strictEqual(body.ownerKey, undefined,
122
+ 'opt-in: response must not include ownerKey when flag is omitted');
123
+ const filePath = path.join('./data', 'nokeys', 'private', 'privkey.jsonld');
124
+ assert.strictEqual(await fs.pathExists(filePath), false,
125
+ 'opt-in: file must not be written when flag is omitted');
126
+ });
127
+
128
+ it('does NOT write a key file when provisionKeys is false (explicit opt-out)', async () => {
129
+ const res = await fetch(`${getBaseUrl()}/.pods`, {
130
+ method: 'POST',
131
+ headers: { 'Content-Type': 'application/json' },
132
+ body: JSON.stringify({ name: 'nokeys2', provisionKeys: false })
133
+ });
134
+ assertStatus(res, 201);
135
+ const body = await res.json();
136
+ assert.strictEqual(body.ownerKey, undefined);
137
+ const filePath = path.join('./data', 'nokeys2', 'private', 'privkey.jsonld');
138
+ assert.strictEqual(await fs.pathExists(filePath), false);
139
+ });
140
+
141
+ it('does NOT trigger on truthy non-true values (e.g. string "true")', async () => {
142
+ // Defensive: only literal `true` activates the flag — keeps an
143
+ // accidentally-string-coerced value from silently turning it on.
144
+ const res = await fetch(`${getBaseUrl()}/.pods`, {
145
+ method: 'POST',
146
+ headers: { 'Content-Type': 'application/json' },
147
+ body: JSON.stringify({ name: 'stringtrue', provisionKeys: 'true' })
148
+ });
149
+ assertStatus(res, 201);
150
+ const body = await res.json();
151
+ assert.strictEqual(body.ownerKey, undefined,
152
+ 'string "true" must not trigger key provisioning');
153
+ const filePath = path.join('./data', 'stringtrue', 'private', 'privkey.jsonld');
154
+ assert.strictEqual(await fs.pathExists(filePath), false);
155
+ });
156
+ });
157
+
158
+ describe('POST /.pods — provisionKeys + --public (footgun guard)', () => {
159
+ // --public mode bypasses WAC: every resource becomes publicly
160
+ // readable. Combined with provisionKeys, /private/privkey.jsonld
161
+ // would be the world's worst secret store. Refuse the combination
162
+ // at request time with 400 so the operator hits the contradiction
163
+ // immediately. See #442 review.
164
+ let server;
165
+ let baseUrl;
166
+ let savedDataRoot;
167
+ const DATA_DIR = './test-data-provision-public';
168
+
169
+ before(async () => {
170
+ savedDataRoot = process.env.DATA_ROOT;
171
+ await fs.remove(DATA_DIR);
172
+ await fs.ensureDir(DATA_DIR);
173
+ const { createServer } = await import('../src/server.js');
174
+ server = createServer({
175
+ logger: false,
176
+ forceCloseConnections: true,
177
+ root: DATA_DIR,
178
+ public: true
179
+ });
180
+ await server.listen({ port: 0, host: '127.0.0.1' });
181
+ baseUrl = `http://127.0.0.1:${server.server.address().port}`;
182
+ });
183
+ after(async () => {
184
+ await server.close();
185
+ await fs.remove(DATA_DIR);
186
+ if (savedDataRoot === undefined) delete process.env.DATA_ROOT;
187
+ else process.env.DATA_ROOT = savedDataRoot;
188
+ });
189
+
190
+ it('rejects POST /.pods with provisionKeys: true on a --public server (400)', async () => {
191
+ const res = await fetch(`${baseUrl}/.pods`, {
192
+ method: 'POST',
193
+ headers: { 'Content-Type': 'application/json' },
194
+ body: JSON.stringify({ name: 'shouldnotexist', provisionKeys: true })
195
+ });
196
+ assert.strictEqual(res.status, 400);
197
+ const body = await res.json();
198
+ assert.match(body.message || body.error || '', /public/i,
199
+ 'error must explain why provisionKeys is rejected');
200
+ // Pod must not have been created.
201
+ assert.strictEqual(await fs.pathExists(`${DATA_DIR}/shouldnotexist/`), false);
202
+ });
203
+
204
+ it('still allows POST /.pods without provisionKeys on a --public server', async () => {
205
+ const res = await fetch(`${baseUrl}/.pods`, {
206
+ method: 'POST',
207
+ headers: { 'Content-Type': 'application/json' },
208
+ body: JSON.stringify({ name: 'publicpod' })
209
+ });
210
+ assert.strictEqual(res.status, 201);
211
+ });
212
+ });
213
+
214
+ describe('createServer — provisionKeys + --public refused at start', () => {
215
+ it('throws synchronously when both options are set', async () => {
216
+ const { createServer } = await import('../src/server.js');
217
+ assert.throws(
218
+ () => createServer({ logger: false, provisionKeys: true, public: true }),
219
+ /cannot be combined with --public/
220
+ );
221
+ });
222
+ });
223
+
224
+ describe('createPodStructure — provisionKeys option (direct call)', () => {
225
+ before(async () => {
226
+ await startTestServer();
227
+ });
228
+ after(async () => {
229
+ await stopTestServer();
230
+ });
231
+
232
+ it('returns ownerKey when provisionKeys is true', async () => {
233
+ const podUri = 'http://127.0.0.1:0/direct1/';
234
+ const webId = `${podUri}profile/card.jsonld#me`;
235
+ const result = await createPodStructure(
236
+ 'direct1', webId, podUri, podUri.replace(/\/$/, '/'), 0,
237
+ { provisionKeys: true }
238
+ );
239
+ assert.ok(result.ownerKey, 'createPodStructure must return ownerKey when provisionKeys is true');
240
+ assert.match(result.ownerKey.publicHex, /^[0-9a-f]{64}$/);
241
+ assert.match(result.ownerKey.secretHex, /^[0-9a-f]{64}$/);
242
+ assert.strictEqual(result.ownerKey.publicMultibase, result.ownerKey.document.publicKeyMultibase);
243
+ // Phase 2 default controller — did:nostr:<hex>.
244
+ assert.strictEqual(
245
+ result.ownerKey.document.controller,
246
+ `did:nostr:${result.ownerKey.publicHex}`
247
+ );
248
+ // Phase 2 surfaces the VM and the did:nostr identifier alongside
249
+ // the document for callers that want to display the public side.
250
+ assert.strictEqual(result.ownerKey.vm.controller, webId);
251
+ assert.strictEqual(
252
+ result.ownerKey.vm['@id'],
253
+ `${podUri}profile/card.jsonld#owner-key`
254
+ );
255
+ assert.strictEqual(
256
+ result.ownerKey.didNostr,
257
+ `did:nostr:${result.ownerKey.publicHex}`
258
+ );
259
+ });
260
+
261
+ it('returns no ownerKey when the option is omitted', async () => {
262
+ const podUri = 'http://127.0.0.1:0/direct2/';
263
+ const webId = `${podUri}profile/card.jsonld#me`;
264
+ const result = await createPodStructure(
265
+ 'direct2', webId, podUri, podUri.replace(/\/$/, '/'), 0
266
+ );
267
+ assert.strictEqual(result.ownerKey, undefined);
268
+ });
269
+
270
+ it('requires strict boolean true (a truthy non-boolean does not trigger)', async () => {
271
+ // Defensive: matches the HTTP-side check on the request body so a
272
+ // misconfigured caller passing 'true' / 1 / etc. through the
273
+ // direct API doesn't silently provision a plaintext secret.
274
+ const podUri = 'http://127.0.0.1:0/direct3/';
275
+ const webId = `${podUri}profile/card.jsonld#me`;
276
+ const result = await createPodStructure(
277
+ 'direct3', webId, podUri, podUri.replace(/\/$/, '/'), 0,
278
+ { provisionKeys: 'true' } // intentionally string, not boolean
279
+ );
280
+ assert.strictEqual(result.ownerKey, undefined,
281
+ 'string "true" must not activate provisioning at the direct entry');
282
+ assert.strictEqual(await fs.pathExists('./data/direct3/private/privkey.jsonld'), false);
283
+ });
284
+ });
@@ -0,0 +1,170 @@
1
+ /**
2
+ * End-to-end: a JWT signed with the on-disk Phase 1 owner secret,
3
+ * with `kid` pointing at the Phase 2 verificationMethod that lands
4
+ * in the seeded WebID profile, authenticates as the pod owner via
5
+ * the existing LWS-CID verifier (src/auth/lws-cid.js).
6
+ *
7
+ * This is the single test that proves Phase 2 of #437 (#443) closes
8
+ * the loop: keypair on disk → public side in profile → JWT signed
9
+ * with the secret → verifier accepts → WebID returned.
10
+ *
11
+ * Builds the JWT inline (signing primitives from @noble/curves are
12
+ * already a jss dep). Stubs global.fetch so the verifier's profile
13
+ * GET is served from an in-memory profile produced by the actual
14
+ * generateProfile helper — no test fixtures, no second source of
15
+ * truth for the profile shape.
16
+ */
17
+
18
+ import { describe, it, before, after, beforeEach } from 'node:test';
19
+ import assert from 'node:assert';
20
+ import { sha256 } from '@noble/hashes/sha2';
21
+ import { secp256k1 } from '@noble/curves/secp256k1';
22
+ import { provisionOwnerKey } from '../src/keys/provision.js';
23
+ import { generateProfile } from '../src/webid/profile.js';
24
+ import { verifyLwsCidAuth, _clearProfileCacheForTests } from '../src/auth/lws-cid.js';
25
+
26
+ const POD_ORIGIN = 'https://alice.example';
27
+ const POD_URI = `${POD_ORIGIN}/`;
28
+ const WEBID = `${POD_URI}profile/card.jsonld#me`;
29
+ const DOC_URL = `${POD_URI}profile/card.jsonld`;
30
+ const ISSUER = `${POD_ORIGIN}/`;
31
+
32
+ function b64u(bytes) {
33
+ return Buffer.from(bytes).toString('base64')
34
+ .replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
35
+ }
36
+
37
+ function makeEs256kJwt({ secretHex, header, payload }) {
38
+ const h64 = b64u(Buffer.from(JSON.stringify(header)));
39
+ const p64 = b64u(Buffer.from(JSON.stringify(payload)));
40
+ const signingInput = Buffer.from(`${h64}.${p64}`, 'utf8');
41
+ const msgHash = sha256(signingInput);
42
+ const sig = secp256k1.sign(msgHash, hexToBytes(secretHex));
43
+ return `${h64}.${p64}.${b64u(sig.toCompactRawBytes())}`;
44
+ }
45
+
46
+ function hexToBytes(hex) {
47
+ const out = new Uint8Array(hex.length / 2);
48
+ for (let i = 0; i < out.length; i++) out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
49
+ return out;
50
+ }
51
+
52
+ function makeRequest(token, { host = 'alice.example', proto = 'https' } = {}) {
53
+ return {
54
+ headers: { authorization: `Bearer ${token}`, host },
55
+ protocol: proto
56
+ };
57
+ }
58
+
59
+ describe('Phase 2: LWS-CID round-trip with provisioned owner key (#443)', () => {
60
+ let realFetch;
61
+ let servedProfile = null;
62
+
63
+ before(() => {
64
+ realFetch = global.fetch;
65
+ global.fetch = async (url) => {
66
+ const u = String(url);
67
+ if (u === DOC_URL && servedProfile) {
68
+ return new Response(JSON.stringify(servedProfile), {
69
+ status: 200,
70
+ headers: { 'content-type': 'application/ld+json' }
71
+ });
72
+ }
73
+ return new Response('not found', { status: 404 });
74
+ };
75
+ });
76
+
77
+ after(() => {
78
+ global.fetch = realFetch;
79
+ });
80
+
81
+ beforeEach(() => {
82
+ servedProfile = null;
83
+ _clearProfileCacheForTests();
84
+ });
85
+
86
+ it('verifies a JWT signed with the on-disk secret against the seeded profile', async () => {
87
+ // 1. Provision an owner key (same call site as createPodStructure /
88
+ // createRootPodStructure use during pod creation).
89
+ const owner = provisionOwnerKey({ webId: WEBID });
90
+
91
+ // 2. Build the seeded WebID profile with the owner VM injected
92
+ // (same call as createPodStructure makes after #443).
93
+ servedProfile = generateProfile({
94
+ webId: WEBID,
95
+ name: 'me',
96
+ podUri: POD_URI,
97
+ issuer: ISSUER,
98
+ ownerVm: owner.vm
99
+ });
100
+
101
+ // Sanity: the profile should carry the VM and reference it from
102
+ // authentication / assertionMethod (the last two are what lets the
103
+ // VM count as an auth factor without a separate PATCH).
104
+ assert.strictEqual(servedProfile.verificationMethod.length, 1);
105
+ assert.strictEqual(servedProfile.verificationMethod[0]['@id'], owner.vm['@id']);
106
+ assert.deepStrictEqual(servedProfile.authentication, [owner.vm['@id']]);
107
+ assert.deepStrictEqual(servedProfile.assertionMethod, [owner.vm['@id']]);
108
+
109
+ // 3. Sign an LWS-CID JWT with the on-disk secret. `kid` points at
110
+ // the VM's `@id` — that's how the verifier locates the public
111
+ // key in the profile.
112
+ const now = Math.floor(Date.now() / 1000);
113
+ const token = makeEs256kJwt({
114
+ secretHex: owner.secretHex,
115
+ header: { alg: 'ES256K', typ: 'JWT', kid: owner.vm['@id'] },
116
+ payload: {
117
+ iss: WEBID,
118
+ sub: WEBID,
119
+ aud: POD_ORIGIN,
120
+ client_id: WEBID,
121
+ iat: now,
122
+ exp: now + 60
123
+ }
124
+ });
125
+
126
+ // 4. Verify via the existing LWS-CID verifier (no changes to
127
+ // src/auth/lws-cid.js — Phase 2 only landed the profile wire).
128
+ const result = await verifyLwsCidAuth(makeRequest(token));
129
+ assert.strictEqual(result.error, null,
130
+ `LWS-CID verification should succeed; got error: ${result.error}`);
131
+ assert.strictEqual(result.webId, WEBID,
132
+ 'verifier should return the pod owner WebID as the authenticated identity');
133
+ });
134
+
135
+ it('rejects a JWT signed with a different secret (sanity)', async () => {
136
+ // Provision the real owner key and seed the profile with its VM,
137
+ // but sign the JWT with an UNRELATED secret. The verifier should
138
+ // refuse — proves the signature check is doing real work, not
139
+ // just rubber-stamping anything addressed to the right kid.
140
+ const owner = provisionOwnerKey({ webId: WEBID });
141
+ servedProfile = generateProfile({
142
+ webId: WEBID,
143
+ name: 'me',
144
+ podUri: POD_URI,
145
+ issuer: ISSUER,
146
+ ownerVm: owner.vm
147
+ });
148
+
149
+ const wrongSecret = provisionOwnerKey({ webId: WEBID }).secretHex;
150
+ const now = Math.floor(Date.now() / 1000);
151
+ const token = makeEs256kJwt({
152
+ secretHex: wrongSecret,
153
+ header: { alg: 'ES256K', typ: 'JWT', kid: owner.vm['@id'] },
154
+ payload: {
155
+ iss: WEBID, sub: WEBID, aud: POD_ORIGIN, client_id: WEBID,
156
+ iat: now, exp: now + 60
157
+ }
158
+ });
159
+
160
+ const result = await verifyLwsCidAuth(makeRequest(token));
161
+ assert.strictEqual(result.webId, null,
162
+ 'mismatched secret must not authenticate');
163
+ // Match the specific verifier error prefix, not just any string
164
+ // containing "signature" — JWS-related errors (expired, malformed,
165
+ // bad nbf, etc.) also mention "signature" but for the wrong
166
+ // reasons. We want to prove the signature *check* did real work.
167
+ assert.match(result.error || '', /signature verification failed/,
168
+ 'error should be the signature-verification path, not some other JWT failure');
169
+ });
170
+ });