javascript-solid-server 0.0.189 → 0.0.191

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "javascript-solid-server",
3
- "version": "0.0.189",
3
+ "version": "0.0.191",
4
4
  "description": "A minimal, fast Solid server",
5
5
  "main": "src/index.js",
6
6
  "type": "module",
@@ -190,9 +190,20 @@ export async function createPodStructure(name, webId, podUri, issuer, defaultQuo
190
190
  await storage.createContainer(`${podPath}settings/`);
191
191
  await storage.createContainer(`${podPath}profile/`);
192
192
 
193
- // Generate and write WebID profile at /profile/card.jsonld
194
- const profile = generateProfile({ webId, name, podUri, issuer });
195
- await storage.write(`${podPath}profile/card.jsonld`, serialize(profile));
193
+ // Optional: provision a Schnorr secp256k1 owner key. The keypair is
194
+ // generated in memory up-front so its VM can be injected into the
195
+ // WebID profile that gets written last. The on-disk persistence of
196
+ // the secret is deferred to *after* the ACL tree is in place — see
197
+ // the ordering block further below. Strict `=== true` (not just
198
+ // truthy) so a misconfigured caller passing `'true'` / `1` / etc.
199
+ // doesn't silently activate; matches handleCreatePod's HTTP-side
200
+ // check on the body field.
201
+ const ownerKey = options.provisionKeys === true
202
+ ? provisionOwnerKey({ webId })
203
+ : null;
204
+
205
+ // Profile is written last (see the ACL/privkey block below). Skip
206
+ // the write here; we'll do it after privkey lands on disk.
196
207
 
197
208
  // Generate and write preferences
198
209
  const prefs = generatePreferences({ webId, podUri });
@@ -248,18 +259,24 @@ export async function createPodStructure(name, webId, podUri, issuer, defaultQuo
248
259
  await initializeQuota(name, defaultQuota);
249
260
  }
250
261
 
251
- // Optional: provision a Schnorr secp256k1 owner key in /private/.
252
- // Phase 1 of #437. See src/keys/provision.js for the design notes.
253
- // Throw on write failure so the caller's cleanup path runs and the
254
- // pod isn't left with a phantom `ownerKey` in the response that
255
- // doesn't correspond to any on-disk file.
262
+ // Owner-key persistence + profile write (when --provision-keys is on).
263
+ // Order is load-bearing for two distinct concerns (#444 review):
264
+ //
265
+ // 1. WAC vacuum: write privkey *after* the ACL tree is in place so
266
+ // the secret file is born under owner-only WAC. Without this,
267
+ // there's a window where the file exists but no /private/.acl
268
+ // protects it; jss's deny-by-default since #f43ecdf would
269
+ // mitigate to 401, but defence-in-depth beats relying on a
270
+ // security default holding.
256
271
  //
257
- // Strict `=== true` (not just truthy) so a misconfigured caller
258
- // passing `'true'` / `1` / etc. doesn't silently activate. Matches
259
- // handleCreatePod's HTTP-side check on the body field.
260
- let ownerKey;
261
- if (options.provisionKeys === true) {
262
- ownerKey = provisionOwnerKey({ controllerWebId: webId });
272
+ // 2. Orphan-VM: write privkey *before* the profile so a crash
273
+ // between the two leaves an orphan secret file (easy to delete)
274
+ // rather than an orphan VM in a published WebID profile that
275
+ // forever advertises an authentication method whose secret was
276
+ // never persisted.
277
+ //
278
+ // Combined: ACLs (above) → privkey (here) → profile (next).
279
+ if (ownerKey) {
263
280
  const ok = await storage.write(
264
281
  `${podPath}private/privkey.jsonld`,
265
282
  JSON.stringify(ownerKey.document, null, 2),
@@ -272,7 +289,19 @@ export async function createPodStructure(name, webId, podUri, issuer, defaultQuo
272
289
  }
273
290
  }
274
291
 
275
- return { podPath, podUri, ownerKey };
292
+ // Generate and write WebID profile at /profile/card.jsonld. When an
293
+ // owner key was provisioned, its VM lands in the profile so the
294
+ // existing LWS-CID verifier (src/auth/lws-cid.js) can authenticate
295
+ // JWTs signed with the matching secret. Profile is intentionally
296
+ // written last — see ordering rationale above.
297
+ const profile = generateProfile({ webId, name, podUri, issuer, ownerVm: ownerKey?.vm });
298
+ await storage.write(`${podPath}profile/card.jsonld`, serialize(profile));
299
+
300
+ // Spread `ownerKey` only when set so the field is genuinely absent
301
+ // (not `null`) on the no-provisioning path — matches the existing
302
+ // test expectation that `result.ownerKey === undefined` when the
303
+ // flag was omitted.
304
+ return { podPath, podUri, ...(ownerKey && { ownerKey }) };
276
305
  }
277
306
 
278
307
  /**
@@ -20,7 +20,7 @@
20
20
  * surface area or a new dependency.
21
21
  */
22
22
 
23
- import { schnorr } from '@noble/curves/secp256k1';
23
+ import { schnorr, secp256k1 } from '@noble/curves/secp256k1';
24
24
 
25
25
  /**
26
26
  * Multicodec varints (lower-hex). The CCG / W3C CID v1.0 Multikey
@@ -43,12 +43,34 @@ const EVEN_Y_PARITY_HEX = '02';
43
43
  /**
44
44
  * Generate a fresh secp256k1 keypair suitable for Schnorr signing.
45
45
  *
46
+ * The secret is normalized so that `G * secret` has *even* y (BIP-340
47
+ * convention). Without normalization, ECDSA signatures made with the
48
+ * raw secret would verify against the natural y of the public point —
49
+ * even half the time, odd half the time — while the corresponding JWK
50
+ * we publish in the WebID profile is always derived from the even-y
51
+ * x-only Schnorr pubkey. The two would disagree on ~50% of generated
52
+ * secrets, breaking Phase 2's LWS-CID round-trip non-deterministically.
53
+ *
54
+ * Normalizing once at generation time means a single secret-on-disk
55
+ * works under both Schnorr (Nostr) and ECDSA (LWS-CID JWT) without
56
+ * parity gymnastics in either signing path.
57
+ *
46
58
  * @returns {{ secretHex: string, publicHex: string }}
47
- * `secretHex` — 32-byte secret scalar, lower-hex.
59
+ * `secretHex` — 32-byte secret scalar, lower-hex, normalized so the
60
+ * corresponding public point has even y.
48
61
  * `publicHex` — 32-byte x-only Schnorr pubkey, lower-hex (BIP-340).
49
62
  */
50
63
  export function generateOwnerKeypair() {
51
- const secretBytes = schnorr.utils.randomPrivateKey();
64
+ let secretBytes = schnorr.utils.randomPrivateKey();
65
+ // Compressed SEC1 starts with 02 (even y) or 03 (odd y).
66
+ const compressed = secp256k1.getPublicKey(secretBytes, /*compressed=*/true);
67
+ if (compressed[0] === 0x03) {
68
+ // Negate the secret (mod n) so the resulting point flips to even y.
69
+ const n = secp256k1.CURVE.n;
70
+ const original = BigInt('0x' + bytesToHex(secretBytes));
71
+ const negated = (n - original) % n;
72
+ secretBytes = hexToBytes(negated.toString(16).padStart(64, '0'));
73
+ }
52
74
  const publicBytes = schnorr.getPublicKey(secretBytes);
53
75
  return {
54
76
  secretHex: bytesToHex(secretBytes),
@@ -75,47 +97,184 @@ export function secretKeyMultibase(secretHex) {
75
97
  return 'f' + MULTICODEC_SECP256K1_PRIV_HEX + secretHex;
76
98
  }
77
99
 
100
+ /**
101
+ * Compute the canonical did:nostr identifier for a Schnorr secp256k1
102
+ * pubkey. Lower-hex form (matches the rest of jss — see
103
+ * src/idp/well-known-did-nostr.js's resolveDidNostrLocally(pubkeyHex)
104
+ * and src/auth/did-nostr.js's `did:nostr:${pubkey.toLowerCase()}`).
105
+ * Phase 2 of #437 (#443) flips the Multikey document's `controller`
106
+ * field to this form now that jss's resolver round-trips it.
107
+ *
108
+ * @param {string} publicHex - 32-byte x-only Schnorr pubkey hex.
109
+ * @returns {string} `did:nostr:<lower-hex pubkey>`.
110
+ */
111
+ export function didNostrFromPublicHex(publicHex) {
112
+ if (!/^[0-9a-f]{64}$/.test(publicHex)) {
113
+ throw new Error('didNostrFromPublicHex: expected 64-char lower-hex pubkey');
114
+ }
115
+ return `did:nostr:${publicHex}`;
116
+ }
117
+
78
118
  /**
79
119
  * Build the W3C CID v1.0 Multikey JSON-LD document for a fresh pod
80
- * owner key. The `controller` is the pod owner's WebID — Phase 1
81
- * keeps the document self-consistent at every phase (Phase 2 will
82
- * swap in a `did:nostr:` controller once the resolver lands).
120
+ * owner key.
121
+ *
122
+ * Phase 2 default controller: `did:nostr:<hex>`. The previous Phase 1
123
+ * shape used the pod owner's WebID — both are valid CID v1.0
124
+ * controllers, but did:nostr lets the keypair self-identify via jss's
125
+ * existing resolver. Callers can still pass an explicit `controller`
126
+ * (the legacy WebID form is what existing test fixtures use).
83
127
  *
84
128
  * @param {object} args
85
- * @param {string} args.controllerWebId - Absolute owner WebID URI.
86
129
  * @param {string} args.publicHex - 32-byte x-only Schnorr pubkey hex.
87
130
  * @param {string} args.secretHex - 32-byte secret scalar hex.
131
+ * @param {string} [args.controller] - Override the controller field.
132
+ * Defaults to `did:nostr:<publicHex>` (Phase 2 of #437 / #443).
88
133
  * @returns {object} JSON-LD Multikey document, ready for `JSON.stringify`.
89
134
  */
90
- export function buildOwnerKeyDocument({ controllerWebId, publicHex, secretHex }) {
91
- if (typeof controllerWebId !== 'string' || !controllerWebId) {
92
- throw new Error('buildOwnerKeyDocument: controllerWebId required');
135
+ export function buildOwnerKeyDocument({ publicHex, secretHex, controller }) {
136
+ const ctrl = controller ?? didNostrFromPublicHex(publicHex);
137
+ if (typeof ctrl !== 'string' || !ctrl) {
138
+ throw new Error('buildOwnerKeyDocument: controller required');
93
139
  }
94
140
  return {
95
141
  '@context': 'https://www.w3.org/ns/cid/v1',
96
142
  type: 'Multikey',
97
- controller: controllerWebId,
143
+ controller: ctrl,
98
144
  publicKeyMultibase: publicKeyMultibase(publicHex),
99
145
  secretKeyMultibase: secretKeyMultibase(secretHex)
100
146
  };
101
147
  }
102
148
 
103
149
  /**
104
- * One-shot helper: generate a fresh keypair and produce both the
105
- * Multikey document and the raw key material (for log lines / CLI
106
- * output that wants to display the pubkey).
150
+ * Compute the BIP-340 even-y JWK (kty=EC, crv=secp256k1) for an
151
+ * x-only Schnorr pubkey hex. Phase 2 needs this for the VM that
152
+ * lands in the WebID profile — the LWS-CID verifier currently reads
153
+ * `publicKeyJwk` only (Multikey-only VMs aren't yet handled there
154
+ * per `src/auth/lws-cid.js`'s docstring), so the VM ships both
155
+ * `publicKeyMultibase` (CID v1.0 conformance) and `publicKeyJwk`
156
+ * (LWS-CID compat).
157
+ *
158
+ * The y coordinate is computed against the canonical even-y point at
159
+ * `x` — same convention `src/auth/nostr-keys.js`'s
160
+ * `pubkeyFromValidatedJwk` checks against on the verifier side, so
161
+ * the VM we mint round-trips through the existing extractor without
162
+ * being rejected as "wrong y".
163
+ *
164
+ * @param {string} publicHex - 32-byte x-only Schnorr pubkey hex.
165
+ * @returns {{ kty: 'EC', crv: 'secp256k1', x: string, y: string }}
166
+ */
167
+ export function publicKeyJwkFromHex(publicHex) {
168
+ if (!/^[0-9a-f]{64}$/.test(publicHex)) {
169
+ throw new Error('publicKeyJwkFromHex: expected 64-char lower-hex pubkey');
170
+ }
171
+ // Compressed SEC1 with parity 02 = the canonical even-y point at x.
172
+ const point = secp256k1.ProjectivePoint.fromHex('02' + publicHex);
173
+ const yHex = point.toAffine().y.toString(16).padStart(64, '0');
174
+ return {
175
+ kty: 'EC',
176
+ crv: 'secp256k1',
177
+ x: hexToBase64Url(publicHex),
178
+ y: hexToBase64Url(yHex)
179
+ };
180
+ }
181
+
182
+ /**
183
+ * Build the verificationMethod entry for the seeded WebID profile.
184
+ *
185
+ * The VM wires the Phase 1 keypair into the existing LWS-CID auth
186
+ * loop: an agent signs a JWT with the on-disk secret + `kid` set to
187
+ * this VM's `id`, the verifier (already merged in `src/auth/lws-cid.js`)
188
+ * fetches the WebID profile, finds this VM, decodes the JWK, verifies
189
+ * the signature, and returns the WebID as the authenticated identity.
190
+ *
191
+ * Both forms are emitted: `publicKeyMultibase` for CID v1.0 readers
192
+ * (and round-trip with `decodeFFormSecp256k1` in `src/auth/nostr-keys.js`),
193
+ * `publicKeyJwk` for the LWS-CID verifier and any tool that prefers JOSE.
194
+ *
195
+ * @param {object} args
196
+ * @param {string} args.webId - Pod owner's WebID; used to derive both
197
+ * the `controller` and the document URL the VM `id` sits in.
198
+ * @param {string} args.publicHex - 32-byte x-only Schnorr pubkey hex.
199
+ * @param {string} [args.fragment='owner-key'] - Fragment id for the VM;
200
+ * appended to the WebID document URL to form `vm.id`.
201
+ * @returns {object} JSON-LD verificationMethod entry.
202
+ */
203
+ export function buildOwnerVerificationMethod({ webId, publicHex, fragment = 'owner-key' }) {
204
+ if (typeof webId !== 'string' || !webId) {
205
+ throw new Error('buildOwnerVerificationMethod: webId required');
206
+ }
207
+ const docUrl = webId.split('#')[0];
208
+ return {
209
+ '@id': `${docUrl}#${fragment}`,
210
+ '@type': 'Multikey',
211
+ controller: webId,
212
+ publicKeyMultibase: publicKeyMultibase(publicHex),
213
+ publicKeyJwk: publicKeyJwkFromHex(publicHex)
214
+ };
215
+ }
216
+
217
+ /**
218
+ * One-shot helper: generate a fresh keypair and produce the Multikey
219
+ * document, the verificationMethod entry for the WebID profile, and
220
+ * the raw key material (for log lines / CLI output that wants to
221
+ * display the pubkey).
107
222
  *
108
223
  * The returned `secretHex` should be considered sensitive and not
109
- * logged; the public `multibase` IS safe to print.
224
+ * logged; the public `publicMultibase` IS safe to print.
225
+ *
226
+ * Single canonical input shape — `webId` for VM controller + VM `@id`
227
+ * derivation, `documentController` to override the Multikey document's
228
+ * controller (defaults to `did:nostr:<publicHex>` per Phase 2 of #437).
229
+ * The previous `controllerWebId` legacy alias was removed in #443
230
+ * because it created surprising precedence interactions with the new
231
+ * `documentController` and asymmetric document/VM controllers.
232
+ *
233
+ * **Two controllers, on purpose.** `vm.controller` lives inside the
234
+ * WebID profile and always tracks `webId` — it identifies who in
235
+ * WebID-land can present this VM (the pod owner). `document.controller`
236
+ * lives in /private/privkey.jsonld and identifies the key in its own
237
+ * right (default did:nostr, overridable). They're decoupled by design;
238
+ * `documentController` does NOT propagate to the VM. If a caller wants
239
+ * both to point at, say, a custom DID, they should construct the VM
240
+ * separately via `buildOwnerVerificationMethod` and merge.
241
+ *
242
+ * @param {object} args
243
+ * @param {string} args.webId - Pod owner's WebID. Used as the VM
244
+ * controller and to derive the VM's `@id` fragment.
245
+ * @param {string} [args.documentController] - Override the Multikey
246
+ * document's controller. Defaults to `did:nostr:<publicHex>`.
247
+ * @returns {{
248
+ * document: object,
249
+ * vm: object,
250
+ * publicHex: string,
251
+ * secretHex: string,
252
+ * publicMultibase: string,
253
+ * didNostr: string
254
+ * }}
110
255
  */
111
- export function provisionOwnerKey({ controllerWebId }) {
256
+ export function provisionOwnerKey({ webId, documentController }) {
257
+ if (typeof webId !== 'string' || !webId) {
258
+ throw new Error('provisionOwnerKey: webId required');
259
+ }
112
260
  const { publicHex, secretHex } = generateOwnerKeypair();
113
- const document = buildOwnerKeyDocument({ controllerWebId, publicHex, secretHex });
261
+ // Pass `documentController` through verbatim — buildOwnerKeyDocument
262
+ // already defaults to `did:nostr:<publicHex>` when none is given, so
263
+ // duplicating the fallback here would just create two sources of
264
+ // truth for the default controller.
265
+ const document = buildOwnerKeyDocument({
266
+ publicHex,
267
+ secretHex,
268
+ controller: documentController
269
+ });
270
+ const vm = buildOwnerVerificationMethod({ webId, publicHex });
114
271
  return {
115
272
  document,
273
+ vm,
116
274
  publicHex,
117
275
  secretHex,
118
- publicMultibase: document.publicKeyMultibase
276
+ publicMultibase: document.publicKeyMultibase,
277
+ didNostr: didNostrFromPublicHex(publicHex)
119
278
  };
120
279
  }
121
280
 
@@ -155,3 +314,24 @@ function bytesToHex(bytes) {
155
314
  }
156
315
  return s;
157
316
  }
317
+
318
+ function hexToBase64Url(hex) {
319
+ if (!/^[0-9a-f]+$/i.test(hex) || hex.length % 2 !== 0) {
320
+ throw new Error('hexToBase64Url: expected even-length hex');
321
+ }
322
+ return Buffer.from(hex, 'hex').toString('base64url');
323
+ }
324
+
325
+ function hexToBytes(hex) {
326
+ // Validate up front — without this, `parseInt('zz', 16)` returns
327
+ // NaN and silently writes 0 into the byte slot. Today the only
328
+ // caller passes freshly-generated 32-byte hex, but the helper is
329
+ // shared infrastructure: every sibling helper (`publicKeyJwkFromHex`,
330
+ // `didNostrFromPublicHex`, `hexToBase64Url`) validates the same way.
331
+ if (typeof hex !== 'string' || !/^[0-9a-fA-F]+$/.test(hex) || hex.length % 2 !== 0) {
332
+ throw new Error('hexToBytes: expected even-length hex');
333
+ }
334
+ const out = new Uint8Array(hex.length / 2);
335
+ for (let i = 0; i < out.length; i++) out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
336
+ return out;
337
+ }
package/src/server.js CHANGED
@@ -743,6 +743,14 @@ export function createServer(options = {}) {
743
743
  '/.well-known/did/nostr/',
744
744
  '/.well-known/did/nostr/:pubkeyAndExt',
745
745
  '/.well-known/did/nostr/*',
746
+ // /.well-known/nostr.json — NIP-05 mapping (#446). Same WAC-bypass
747
+ // concern as /.well-known/did/nostr/*: the global preHandler skips
748
+ // auth for /.well-known/* (the spec-mandated public namespace),
749
+ // so without 405 blocks the wildcard write handlers would let
750
+ // anyone PUT/DELETE/PATCH this file and hijack the pod's NIP-05
751
+ // identity. GET/HEAD reach the LDP layer normally and serve the
752
+ // file written by --provision-keys.
753
+ '/.well-known/nostr.json',
746
754
  ]) {
747
755
  fastify.put(pat, methodNotAllowed);
748
756
  fastify.post(pat, methodNotAllowed);
@@ -891,6 +899,30 @@ export function createServer(options = {}) {
891
899
  'Filesystem reads bypass WAC; use FDE / OS keyring / restrictive umask ' +
892
900
  'for any pod that matters. See docs/provision-keys.md.'
893
901
  );
902
+
903
+ // NIP-05 mapping for the bare domain (#446). Lives at the
904
+ // server root regardless of whether the pod is at / or
905
+ // /<name>/ — `.well-known/` is per-origin, not per-pod.
906
+ // This branch covers BOTH single-user shapes (root pod via
907
+ // createRootPodStructure, named pod via createPodStructure)
908
+ // because the file is logically server-level identity, not
909
+ // pod-internal data. Multi-user aggregation is the next
910
+ // slice of #445. WAC bypass on /.well-known/* is balanced
911
+ // by the 405 method-not-allowed guards registered earlier
912
+ // so an attacker can't PUT-overwrite this mapping.
913
+ await storage.createContainer('/.well-known/');
914
+ const nip05Ok = await storage.write(
915
+ '/.well-known/nostr.json',
916
+ JSON.stringify({ names: { _: creation.ownerKey.publicHex } }, null, 2)
917
+ );
918
+ if (!nip05Ok) {
919
+ fastify.log.warn(
920
+ 'Failed to write /.well-known/nostr.json — pod is provisioned ' +
921
+ 'but NIP-05 verification will not resolve to this server.'
922
+ );
923
+ } else {
924
+ fastify.log.info(`NIP-05 mapping at ${baseUrl}/.well-known/nostr.json`);
925
+ }
894
926
  }
895
927
  }
896
928
 
@@ -1045,9 +1077,16 @@ export function createServer(options = {}) {
1045
1077
  await storage.createContainer('/settings/');
1046
1078
  await storage.createContainer('/profile/');
1047
1079
 
1048
- // Generate profile
1049
- const profile = generateProfile({ webId, name: displayName, podUri, issuer });
1050
- await storage.write('/profile/card.jsonld', serialize(profile));
1080
+ // Generate the owner key in memory up-front (when --provision-keys
1081
+ // is set) so its VM can be injected into the WebID profile that
1082
+ // gets written last. On-disk persistence of the secret happens
1083
+ // *after* the ACL tree is in place — see the ordering block
1084
+ // further below.
1085
+ const ownerKey = provisionKeysEnabled
1086
+ ? provisionOwnerKey({ webId })
1087
+ : null;
1088
+
1089
+ // Profile is written last (see the ACL/privkey block below).
1051
1090
 
1052
1091
  // Preferences and type indexes
1053
1092
  const prefs = generatePreferences({ webId, podUri });
@@ -1090,13 +1129,26 @@ export function createServer(options = {}) {
1090
1129
  const profileAcl = generatePublicFolderAcl('./', owner('profile/'));
1091
1130
  await storage.write('/profile/.acl', serializeAcl(profileAcl));
1092
1131
 
1093
- // Optional: provision a Schnorr secp256k1 owner key in /private/.
1094
- // Phase 1 of #437. See src/keys/provision.js for the design notes.
1095
- // Throw on write failure so single-user startup fails loud rather
1096
- // than logging "Provisioned …" against a missing on-disk file.
1097
- let ownerKey;
1098
- if (provisionKeysEnabled) {
1099
- ownerKey = provisionOwnerKey({ controllerWebId: webId });
1132
+ // Owner-key persistence + profile write (when --provision-keys is
1133
+ // on). Order is load-bearing for two distinct concerns
1134
+ // (#444 review):
1135
+ //
1136
+ // 1. WAC vacuum: write privkey *after* the ACL tree is in place
1137
+ // so the secret file is born under owner-only WAC. Without
1138
+ // this, there's a window where the file exists but no
1139
+ // /private/.acl protects it; deny-by-default since #f43ecdf
1140
+ // would mitigate to 401, but defence-in-depth beats relying
1141
+ // on a security default holding. The single-user root pod is
1142
+ // especially exposed since the URL is the server origin.
1143
+ //
1144
+ // 2. Orphan-VM: write privkey *before* the profile so a crash
1145
+ // between the two leaves an orphan secret file (easy to
1146
+ // delete) rather than an orphan VM in a published WebID
1147
+ // profile that forever advertises an authentication method
1148
+ // whose secret was never persisted.
1149
+ //
1150
+ // Combined: ACLs (above) → privkey (here) → profile (next).
1151
+ if (ownerKey) {
1100
1152
  const ok = await storage.write(
1101
1153
  '/private/privkey.jsonld',
1102
1154
  JSON.stringify(ownerKey.document, null, 2),
@@ -1108,9 +1160,21 @@ export function createServer(options = {}) {
1108
1160
  );
1109
1161
  }
1110
1162
  }
1163
+ // NIP-05 mapping is written outside this function (in the
1164
+ // single-user onReady block) so it covers both root pods and
1165
+ // named single-user pods (which take the createPodStructure
1166
+ // path), not just the root case. See #446.
1167
+
1168
+ // Generate profile (with the owner key's VM landed in
1169
+ // verificationMethod when --provision-keys is on). Written last —
1170
+ // see ordering rationale above.
1171
+ const profile = generateProfile({ webId, name: displayName, podUri, issuer, ownerVm: ownerKey?.vm });
1172
+ await storage.write('/profile/card.jsonld', serialize(profile));
1111
1173
 
1112
- // Note: Quota not initialized for root-level pods (no user directory)
1113
- return { ownerKey };
1174
+ // Note: Quota not initialized for root-level pods (no user directory).
1175
+ // Spread `ownerKey` only when set so the field is genuinely absent
1176
+ // (not `null`) on the no-provisioning path.
1177
+ return { ...(ownerKey && { ownerKey }) };
1114
1178
  }
1115
1179
 
1116
1180
  // Start file watcher for live reload (watches filesystem for external changes)
@@ -16,15 +16,31 @@ const CID = 'https://www.w3.org/ns/cid/v1#';
16
16
  const LWS = 'https://www.w3.org/ns/lws#';
17
17
 
18
18
  /**
19
- * Generate JSON-LD data for a WebID profile
19
+ * Generate JSON-LD data for a WebID profile.
20
+ *
20
21
  * @param {object} options
21
22
  * @param {string} options.webId - Full WebID URI (e.g., https://example.com/alice/profile/card#me)
22
23
  * @param {string} options.name - Display name
23
24
  * @param {string} options.podUri - Pod root URI (e.g., https://example.com/alice/)
24
25
  * @param {string} options.issuer - OIDC issuer URI
26
+ * @param {object} [options.ownerVm] - Optional verificationMethod
27
+ * entry for an owner-held key (Phase 2 of #437 / #443). Build via
28
+ * `src/keys/provision.js#buildOwnerVerificationMethod`.
29
+ *
30
+ * **Fresh-pod-only when `ownerVm` is set.** The helper unconditionally
31
+ * overwrites `verificationMethod`, `authentication`, and
32
+ * `assertionMethod` with single-element arrays referencing this VM.
33
+ * That's correct for the only current caller (fresh pod creation,
34
+ * nothing to overwrite), but a future "rotate-keys" / re-provisioning
35
+ * command using this helper to regenerate an existing profile would
36
+ * silently drop any VMs / proof-purpose references the operator
37
+ * added by hand. Either pass the existing profile through a merge
38
+ * step before calling this, or treat the helper as fresh-pod-only.
39
+ * See #444 review.
40
+ *
25
41
  * @returns {object} JSON-LD profile data
26
42
  */
27
- export function generateProfileJsonLd({ webId, name, podUri, issuer }) {
43
+ export function generateProfileJsonLd({ webId, name, podUri, issuer, ownerVm = null }) {
28
44
  const pod = podUri.endsWith('/') ? podUri : podUri + '/';
29
45
  // Document URL is the WebID without its fragment; service entries use
30
46
  // fragment ids resolved against it.
@@ -114,7 +130,24 @@ export function generateProfileJsonLd({ webId, name, podUri, issuer }) {
114
130
  '@type': 'lws:OpenIdProvider',
115
131
  'serviceEndpoint': issuer
116
132
  }
117
- ]
133
+ ],
134
+ // Optional: a verificationMethod for an owner-held key, populated
135
+ // when the pod was created with `--provision-keys` (Phase 2 of
136
+ // #437 / #443). The VM lands the public side of the owner key
137
+ // into the profile so the existing LWS-CID verifier in
138
+ // src/auth/lws-cid.js can authenticate JWTs signed with the
139
+ // matching secret. Both `publicKeyMultibase` (CID v1.0
140
+ // conformance) and `publicKeyJwk` (LWS-CID compat) are emitted by
141
+ // src/keys/provision.js's buildOwnerVerificationMethod helper.
142
+ //
143
+ // The VM is also referenced from `authentication` and
144
+ // `assertionMethod` so the same key counts as an authentication
145
+ // factor without an app needing to PATCH those arrays separately.
146
+ ...(ownerVm && {
147
+ verificationMethod: [ownerVm],
148
+ authentication: [ownerVm['@id']],
149
+ assertionMethod: [ownerVm['@id']]
150
+ })
118
151
  };
119
152
  }
120
153
 
@@ -131,10 +164,15 @@ export function generateProfileJsonLd({ webId, name, podUri, issuer }) {
131
164
  * @param {string} options.name - Display name
132
165
  * @param {string} options.podUri - Pod root URI
133
166
  * @param {string} options.issuer - OIDC issuer URI
167
+ * @param {object} [options.ownerVm] - Optional verificationMethod entry
168
+ * for an owner-held key (Phase 2 of #437 / #443). When set, lands
169
+ * the VM in `verificationMethod` and references it from
170
+ * `authentication` + `assertionMethod`. Build via
171
+ * `src/keys/provision.js#buildOwnerVerificationMethod`.
134
172
  * @returns {object} JSON-LD profile document
135
173
  */
136
- export function generateProfile({ webId, name, podUri, issuer }) {
137
- return generateProfileJsonLd({ webId, name, podUri, issuer });
174
+ export function generateProfile({ webId, name, podUri, issuer, ownerVm = null }) {
175
+ return generateProfileJsonLd({ webId, name, podUri, issuer, ownerVm });
138
176
  }
139
177
 
140
178
  /**
@@ -71,8 +71,11 @@ describe('POST /.pods — provisionKeys: true (Phase 1 of #437)', () => {
71
71
  const doc = JSON.parse(await fs.readFile(filePath, 'utf8'));
72
72
  assert.strictEqual(doc['@context'], 'https://www.w3.org/ns/cid/v1');
73
73
  assert.strictEqual(doc.type, 'Multikey');
74
- assert.strictEqual(doc.controller, body.webId,
75
- 'Phase 1 controller is the pod owner WebID (did:nostr lands in Phase 2)');
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>');
76
79
  assert.match(doc.publicKeyMultibase, /^fe70102[0-9a-f]{64}$/);
77
80
  assert.match(doc.secretKeyMultibase, /^f8126[0-9a-f]{64}$/);
78
81
  // Round-trip the public side through jss's existing decoder.
@@ -237,7 +240,22 @@ describe('createPodStructure — provisionKeys option (direct call)', () => {
237
240
  assert.match(result.ownerKey.publicHex, /^[0-9a-f]{64}$/);
238
241
  assert.match(result.ownerKey.secretHex, /^[0-9a-f]{64}$/);
239
242
  assert.strictEqual(result.ownerKey.publicMultibase, result.ownerKey.document.publicKeyMultibase);
240
- assert.strictEqual(result.ownerKey.document.controller, webId);
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
+ );
241
259
  });
242
260
 
243
261
  it('returns no ownerKey when the option is omitted', async () => {
@@ -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
+ });
@@ -4,7 +4,7 @@
4
4
 
5
5
  import { describe, it } from 'node:test';
6
6
  import assert from 'node:assert';
7
- import { schnorr } from '@noble/curves/secp256k1';
7
+ import { schnorr, secp256k1 } from '@noble/curves/secp256k1';
8
8
  import {
9
9
  generateOwnerKeypair,
10
10
  publicKeyMultibase,
@@ -39,6 +39,21 @@ describe('generateOwnerKeypair', () => {
39
39
  assert.notStrictEqual(a.publicHex, b.publicHex);
40
40
  assert.notStrictEqual(a.secretHex, b.secretHex);
41
41
  });
42
+
43
+ it('always normalizes the secret so G*secret has even y (BIP-340)', () => {
44
+ // Without normalization, ECDSA signatures made with the raw secret
45
+ // would verify against the natural y of G*secret — even/odd ~50/50
46
+ // — while the JWK we publish in the WebID profile is derived from
47
+ // the even-y x-only Schnorr pubkey. Phase 2's LWS-CID round-trip
48
+ // would flake non-deterministically. Generate many keypairs and
49
+ // assert every secret's natural public point is even-y.
50
+ for (let i = 0; i < 64; i++) {
51
+ const { secretHex } = generateOwnerKeypair();
52
+ const compressed = secp256k1.getPublicKey(hexToBytes(secretHex), /*compressed=*/true);
53
+ assert.strictEqual(compressed[0], 0x02,
54
+ `secret #${i} produced odd-y point; normalization is broken`);
55
+ }
56
+ });
42
57
  });
43
58
 
44
59
  describe('publicKeyMultibase / secretKeyMultibase', () => {
@@ -91,11 +106,28 @@ describe('buildOwnerKeyDocument', () => {
91
106
  assert.strictEqual(doc.type, 'Multikey');
92
107
  });
93
108
 
94
- it('uses the WebID as controller in Phase 1 (not did:nostr)', () => {
95
- // Phase 1 keeps the document self-consistent. did:nostr controllers
96
- // require the Phase 2 resolver to be useful; until then a CID
97
- // consumer would dereference an unresolvable URI.
98
- const doc = buildOwnerKeyDocument(args);
109
+ it('defaults the controller to did:nostr:<hex> in Phase 2', () => {
110
+ // Phase 2 of #437 (#443) flipped the default controller to
111
+ // `did:nostr:<publicHex>` now that jss's resolver round-trips
112
+ // it. Phase 1 had used the WebID; the swap was anticipated in
113
+ // the Phase 1 design log and ships here.
114
+ const doc = buildOwnerKeyDocument({
115
+ publicHex: args.publicHex,
116
+ secretHex: args.secretHex
117
+ });
118
+ assert.strictEqual(doc.controller, `did:nostr:${args.publicHex}`);
119
+ });
120
+
121
+ it('accepts an explicit controller override (e.g. WebID, urn:, custom DID method)', () => {
122
+ // The forward-looking knob — operators or future callers that
123
+ // want to pin the document's controller to something other than
124
+ // did:nostr (a WebID, a urn:, a custom DID method) pass
125
+ // `controller` explicitly. Defaults still fire when omitted.
126
+ const doc = buildOwnerKeyDocument({
127
+ publicHex: args.publicHex,
128
+ secretHex: args.secretHex,
129
+ controller: args.controllerWebId
130
+ });
99
131
  assert.strictEqual(doc.controller, args.controllerWebId);
100
132
  assert.doesNotMatch(doc.controller, /^did:nostr:/);
101
133
  });
@@ -115,20 +147,75 @@ describe('buildOwnerKeyDocument', () => {
115
147
  assert.strictEqual(doc.nostr, undefined);
116
148
  });
117
149
 
118
- it('rejects a missing or empty controller WebID', () => {
119
- assert.throws(() => buildOwnerKeyDocument({ ...args, controllerWebId: '' }), /controllerWebId required/);
120
- assert.throws(() => buildOwnerKeyDocument({ ...args, controllerWebId: undefined }), /controllerWebId required/);
150
+ it('rejects an explicit empty controller override', () => {
151
+ // The default did:nostr controller is computed from publicHex, so
152
+ // missing inputs are caught upstream (see publicKeyMultibase
153
+ // validation tests). When a caller *explicitly* passes an empty
154
+ // string, that's a misconfiguration we surface loudly.
155
+ assert.throws(
156
+ () => buildOwnerKeyDocument({
157
+ publicHex: args.publicHex,
158
+ secretHex: args.secretHex,
159
+ controller: ''
160
+ }),
161
+ /controller required/
162
+ );
121
163
  });
122
164
  });
123
165
 
124
166
  describe('provisionOwnerKey', () => {
167
+ const webId = 'https://alice.example/profile/card.jsonld#me';
168
+
125
169
  it('returns the document together with raw key material for CLI display', () => {
126
- const out = provisionOwnerKey({ controllerWebId: 'https://alice.example/profile/card.jsonld#me' });
170
+ const out = provisionOwnerKey({ webId });
127
171
  assert.match(out.publicHex, /^[0-9a-f]{64}$/);
128
172
  assert.match(out.secretHex, /^[0-9a-f]{64}$/);
129
173
  assert.strictEqual(out.publicMultibase, out.document.publicKeyMultibase);
130
174
  assert.strictEqual(out.document.type, 'Multikey');
131
- assert.strictEqual(out.document.controller, 'https://alice.example/profile/card.jsonld#me');
175
+ // Phase 2 of #437 (#443): controller defaults to did:nostr:<hex>.
176
+ assert.strictEqual(out.document.controller, `did:nostr:${out.publicHex}`);
177
+ assert.strictEqual(out.didNostr, `did:nostr:${out.publicHex}`);
178
+ });
179
+
180
+ it('returns a verificationMethod entry suitable for the WebID profile', () => {
181
+ // Phase 2 wires the public side into the profile's
182
+ // verificationMethod array so the existing LWS-CID verifier
183
+ // (src/auth/lws-cid.js) can authenticate JWTs signed with the
184
+ // matching secret. Both Multikey and JWK forms ship — Multikey
185
+ // for CID v1.0 conformance, JWK for LWS-CID compat.
186
+ const out = provisionOwnerKey({ webId });
187
+ assert.strictEqual(out.vm['@type'], 'Multikey');
188
+ assert.strictEqual(out.vm.controller, webId);
189
+ assert.strictEqual(out.vm['@id'], 'https://alice.example/profile/card.jsonld#owner-key');
190
+ assert.strictEqual(out.vm.publicKeyMultibase, out.publicMultibase);
191
+ assert.strictEqual(out.vm.publicKeyJwk.kty, 'EC');
192
+ assert.strictEqual(out.vm.publicKeyJwk.crv, 'secp256k1');
193
+ assert.match(out.vm.publicKeyJwk.x, /^[A-Za-z0-9_-]+$/);
194
+ assert.match(out.vm.publicKeyJwk.y, /^[A-Za-z0-9_-]+$/);
195
+ });
196
+
197
+ it('honours an explicit documentController override', () => {
198
+ // The legacy controllerWebId alias was removed in #443 review —
199
+ // the canonical way to pin the document controller is
200
+ // documentController.
201
+ const out = provisionOwnerKey({ webId, documentController: webId });
202
+ assert.strictEqual(out.document.controller, webId);
203
+ assert.strictEqual(out.vm.controller, webId,
204
+ 'VM controller still uses webId regardless of documentController');
205
+ });
206
+
207
+ it('keeps document.controller and vm.controller decoupled by design', () => {
208
+ // Asymmetric on purpose: vm.controller lives inside the WebID
209
+ // profile and identifies who in WebID-land can present this VM
210
+ // (always the pod owner = webId). document.controller lives in
211
+ // /private/privkey.jsonld and identifies the key in its own right
212
+ // (defaults to did:nostr, can be overridden to any custom DID
213
+ // method or URI). The two are distinct semantically; the JSDoc
214
+ // on provisionOwnerKey spells this out.
215
+ const out = provisionOwnerKey({ webId, documentController: 'urn:example:custom' });
216
+ assert.strictEqual(out.document.controller, 'urn:example:custom');
217
+ assert.strictEqual(out.vm.controller, webId,
218
+ 'vm.controller intentionally tracks webId, not documentController');
132
219
  });
133
220
  });
134
221
 
@@ -0,0 +1,173 @@
1
+ /**
2
+ * NIP-05 MVP — /.well-known/nostr.json on single-user pods (#446).
3
+ *
4
+ * Implementation is a static file written during pod creation, not
5
+ * a server-side handler. JSS already exposes /.well-known/* as a
6
+ * public namespace (WAC bypass + dotfile allow-list); the LDP GET
7
+ * handler serves the file like any other resource.
8
+ *
9
+ * Acceptance:
10
+ * - single-user + --provision-keys → 200 { names: { _: <hex> } }
11
+ * served at /.well-known/nostr.json, publicly readable, with
12
+ * CORS open for browser-based NIP-05 verifiers.
13
+ * - single-user without --provision-keys → no file written.
14
+ * - multi-user → no file written (next slice of #445 aggregates).
15
+ */
16
+
17
+ import { describe, it, before, after } from 'node:test';
18
+ import assert from 'node:assert';
19
+ import fs from 'fs-extra';
20
+ import { createServer } from '../src/server.js';
21
+
22
+ // Per-describe DATA_DIR suffixes so the three suites in this file
23
+ // don't collide if --test-concurrency is ever raised above 1.
24
+ // Currently 1 per the npm test script, but the latent risk was
25
+ // flagged in the #447 review.
26
+ async function startServer(dataDir, options = {}) {
27
+ await fs.remove(dataDir);
28
+ await fs.ensureDir(dataDir);
29
+ const server = createServer({
30
+ logger: false,
31
+ forceCloseConnections: true,
32
+ root: dataDir,
33
+ ...options
34
+ });
35
+ await server.listen({ port: 0, host: '127.0.0.1' });
36
+ const baseUrl = `http://127.0.0.1:${server.server.address().port}`;
37
+ return { server, baseUrl };
38
+ }
39
+
40
+ async function stopServer(server, dataDir) {
41
+ await server.close();
42
+ await fs.remove(dataDir);
43
+ }
44
+
45
+ describe('NIP-05 MVP — single-user with provisioned key', () => {
46
+ const DATA_DIR = './test-data-nip05-with-key';
47
+ let server, baseUrl;
48
+ let savedDataRoot;
49
+
50
+ before(async () => {
51
+ savedDataRoot = process.env.DATA_ROOT;
52
+ ({ server, baseUrl } = await startServer(DATA_DIR, {
53
+ singleUser: true,
54
+ provisionKeys: true
55
+ }));
56
+ });
57
+
58
+ after(async () => {
59
+ await stopServer(server, DATA_DIR);
60
+ if (savedDataRoot === undefined) delete process.env.DATA_ROOT;
61
+ else process.env.DATA_ROOT = savedDataRoot;
62
+ });
63
+
64
+ it('writes the NIP-05 mapping with the reserved `_` name', async () => {
65
+ const onDisk = JSON.parse(
66
+ await fs.readFile(`${DATA_DIR}/.well-known/nostr.json`, 'utf8')
67
+ );
68
+ assert.deepStrictEqual(Object.keys(onDisk.names), ['_'],
69
+ 'MVP emits exactly one mapping (the `_` reserved name)');
70
+ assert.match(onDisk.names._, /^[0-9a-f]{64}$/,
71
+ 'the `_` mapping must be a 32-byte hex pubkey');
72
+ });
73
+
74
+ it('serves the mapping over HTTP without auth (NIP-05 verifiers are unauth)', async () => {
75
+ const res = await fetch(`${baseUrl}/.well-known/nostr.json`);
76
+ assert.strictEqual(res.status, 200);
77
+ const body = await res.json();
78
+ assert.match(body.names._, /^[0-9a-f]{64}$/);
79
+ });
80
+
81
+ it('matches the same pubkey landed in the WebID profile VM', async () => {
82
+ // Cross-check: the NIP-05 pubkey and the profile's
83
+ // verificationMethod publicKeyMultibase should describe the
84
+ // same key. If they ever diverge, an LWS-CID verifier would
85
+ // accept the profile's VM but a NIP-05 verifier would attest
86
+ // to a different identity for the same domain.
87
+ const onDisk = JSON.parse(
88
+ await fs.readFile(`${DATA_DIR}/.well-known/nostr.json`, 'utf8')
89
+ );
90
+ const profile = JSON.parse(
91
+ await fs.readFile(`${DATA_DIR}/profile/card.jsonld`, 'utf8')
92
+ );
93
+ const vm = profile.verificationMethod[0];
94
+ assert.ok(vm.publicKeyMultibase.includes(onDisk.names._),
95
+ 'NIP-05 pubkey hex must appear in the profile VM publicKeyMultibase');
96
+ });
97
+ });
98
+
99
+ describe('NIP-05 MVP — single-user without a provisioned key', () => {
100
+ const DATA_DIR = './test-data-nip05-no-key';
101
+ let server;
102
+ let savedDataRoot;
103
+
104
+ before(async () => {
105
+ savedDataRoot = process.env.DATA_ROOT;
106
+ ({ server } = await startServer(DATA_DIR, { singleUser: true }));
107
+ });
108
+
109
+ after(async () => {
110
+ await stopServer(server, DATA_DIR);
111
+ if (savedDataRoot === undefined) delete process.env.DATA_ROOT;
112
+ else process.env.DATA_ROOT = savedDataRoot;
113
+ });
114
+
115
+ it('does not create the file (nothing to publish)', async () => {
116
+ assert.strictEqual(
117
+ await fs.pathExists(`${DATA_DIR}/.well-known/nostr.json`),
118
+ false,
119
+ 'no key → no NIP-05 mapping → no file'
120
+ );
121
+ });
122
+ });
123
+
124
+ describe('NIP-05 MVP — multi-user mode', () => {
125
+ const DATA_DIR = './test-data-nip05-multiuser';
126
+ let server, baseUrl;
127
+ let savedDataRoot;
128
+
129
+ before(async () => {
130
+ savedDataRoot = process.env.DATA_ROOT;
131
+ // No singleUser → multi-user. The MVP only writes the NIP-05
132
+ // file in single-user mode; aggregation across multi-user pods
133
+ // is the next slice of #445.
134
+ ({ server, baseUrl } = await startServer(DATA_DIR, {}));
135
+ });
136
+
137
+ after(async () => {
138
+ await stopServer(server, DATA_DIR);
139
+ if (savedDataRoot === undefined) delete process.env.DATA_ROOT;
140
+ else process.env.DATA_ROOT = savedDataRoot;
141
+ });
142
+
143
+ it('still does not write a server-level NIP-05 file when a pod is provisioned with keys', async () => {
144
+ // Actually exercise the code path that *could* have written the
145
+ // file — provision a multi-user pod with provisionKeys: true via
146
+ // POST /.pods. The pod's own /<name>/private/privkey.jsonld
147
+ // lands as expected, but the server-level /.well-known/nostr.json
148
+ // must remain absent because this is multi-user mode.
149
+ const res = await fetch(`${baseUrl}/.pods`, {
150
+ method: 'POST',
151
+ headers: { 'Content-Type': 'application/json' },
152
+ body: JSON.stringify({ name: 'alice', provisionKeys: true })
153
+ });
154
+ assert.strictEqual(res.status, 201, 'pod creation must succeed');
155
+ const body = await res.json();
156
+ assert.ok(body.ownerKey, 'pod-level owner key must still be provisioned');
157
+
158
+ // The pod's own privkey IS on disk — sanity check the multi-user
159
+ // provisioning path still ran.
160
+ assert.strictEqual(
161
+ await fs.pathExists(`${DATA_DIR}/alice/private/privkey.jsonld`),
162
+ true,
163
+ 'multi-user pod provisioning still writes the pod-internal privkey'
164
+ );
165
+
166
+ // …but no server-level NIP-05 file.
167
+ assert.strictEqual(
168
+ await fs.pathExists(`${DATA_DIR}/.well-known/nostr.json`),
169
+ false,
170
+ 'multi-user mode must not write a server-level NIP-05 mapping'
171
+ );
172
+ });
173
+ });