javascript-solid-server 0.0.188 → 0.0.189

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/jss.js CHANGED
@@ -95,6 +95,8 @@ program
95
95
  .option('--no-notifications', 'Disable WebSocket notifications')
96
96
  .option('--idp', 'Enable built-in Identity Provider')
97
97
  .option('--no-idp', 'Disable built-in Identity Provider')
98
+ .option('--provision-keys', 'Generate a Schnorr secp256k1 owner key on pod creation, written to <pod>/private/privkey.jsonld in W3C CID v1.0 Multikey format (off by default)')
99
+ .option('--no-provision-keys', 'Do not auto-generate an owner key on pod creation')
98
100
  .option('--idp-issuer <url>', 'IdP issuer URL (defaults to server URL)')
99
101
  .option('--subdomains', 'Enable subdomain-based pods (XSS protection)')
100
102
  .option('--no-subdomains', 'Disable subdomain-based pods')
@@ -218,6 +220,7 @@ program
218
220
  singleUser: config.singleUser,
219
221
  singleUserName: config.singleUserName,
220
222
  singleUserPassword: config.singleUserPassword,
223
+ provisionKeys: config.provisionKeys,
221
224
  public: config.public,
222
225
  readOnly: config.readOnly,
223
226
  liveReload: config.liveReload,
@@ -0,0 +1,157 @@
1
+ # Owner-key provisioning (`--provision-keys`)
2
+
3
+ Phase 1 of [#437](https://github.com/JavaScriptSolidServer/JavaScriptSolidServer/issues/437). Generates a Schnorr secp256k1 keypair on pod creation and writes it as a W3C [Controlled Identifiers v1.0 Multikey](https://www.w3.org/TR/cid-1.0/) document at `<pod>/private/privkey.jsonld`.
4
+
5
+ The same key is intended to serve, over time, as: a Solid signing identity, a Nostr identity (same curve), and a `did:nostr:` DID controller (Phase 2). One CLI flag → pod-resident self-sovereign identity ready for both Solid and Nostr / agentic use cases.
6
+
7
+ ## Usage
8
+
9
+ ### Single-user mode (CLI flag)
10
+
11
+ ```bash
12
+ jss start --single-user --provision-keys
13
+ ```
14
+
15
+ On first start the server creates the pod and writes the key file. Subsequent starts re-use the existing pod and don't touch the key (skip-if-exists semantics, like the rest of the seeded structure).
16
+
17
+ ### Multi-user mode (HTTP body field)
18
+
19
+ ```bash
20
+ curl -X POST http://localhost:4444/.pods \
21
+ -H "Content-Type: application/json" \
22
+ -d '{ "name": "alice", "provisionKeys": true }'
23
+ ```
24
+
25
+ Response includes the public side of the key under `ownerKey`:
26
+
27
+ ```json
28
+ {
29
+ "name": "alice",
30
+ "webId": "http://localhost:4444/alice/profile/card.jsonld#me",
31
+ "podUri": "http://localhost:4444/alice/",
32
+ "token": "…",
33
+ "ownerKey": {
34
+ "keyDocument": "http://localhost:4444/alice/private/privkey.jsonld",
35
+ "publicKeyMultibase": "fe70102…"
36
+ }
37
+ }
38
+ ```
39
+
40
+ The secret is **never** echoed in the response — it lives only at the `keyDocument` path on disk, behind the pod's owner-only WAC.
41
+
42
+ ### Environment variable
43
+
44
+ ```bash
45
+ JSS_PROVISION_KEYS=true jss start --single-user
46
+ ```
47
+
48
+ Same effect as the CLI flag; useful in containerised deployments.
49
+
50
+ ## What gets written
51
+
52
+ `<pod>/private/privkey.jsonld`:
53
+
54
+ ```json
55
+ {
56
+ "@context": "https://www.w3.org/ns/cid/v1",
57
+ "type": "Multikey",
58
+ "controller": "https://your.example/profile/card.jsonld#me",
59
+ "publicKeyMultibase": "fe7010287a1b…",
60
+ "secretKeyMultibase": "f81260a1b2c…"
61
+ }
62
+ ```
63
+
64
+ - **`@context` + `type`** — W3C CID v1.0 conformant Multikey document. CID-aware tools recognise the shape natively.
65
+ - **`controller`** — In Phase 1 this is the pod owner's WebID. Phase 2 will swap in a `did:nostr:` controller once the resolver lands; the document is self-consistent at every phase.
66
+ - **`publicKeyMultibase`** — f-form (multibase `f` + multicodec `e701` for secp256k1-pub + parity byte + 32-byte x-only pubkey, all base16-lower). Round-trips through jss's existing `decodeFFormSecp256k1` decoder.
67
+ - **`secretKeyMultibase`** — f-form (multibase `f` + multicodec `8126` for secp256k1-priv + 32-byte secret scalar). The secret IS this scalar; no parity byte.
68
+
69
+ The file mode is set to `0o600` on POSIX. WAC restricts HTTP access to the pod owner via `<pod>/private/.acl` (the standard private-folder ACL JSS writes anyway).
70
+
71
+ ## Incompatible with `--public`
72
+
73
+ JSS refuses to provision keys when `--public` mode is on. `--public` tells JSS to skip WAC entirely and grant unauthenticated access to every resource — including `/private/privkey.jsonld`. Combined with `--provision-keys`, that would write a plaintext secret straight to a publicly-readable URL.
74
+
75
+ The two flags are explicitly incompatible:
76
+
77
+ - **At server start**: `jss start --single-user --provision-keys --public` throws at server-create time with a clear error. The server doesn't start.
78
+ - **At pod creation over HTTP**: `POST /.pods` with `provisionKeys: true` returns **400 Bad Request** when the server is in `--public` mode.
79
+
80
+ If you genuinely want both behaviours, you don't actually want both: either pick `--public` (no auth, no secrets on disk) or pick `--provision-keys` (WAC-protected secrets). There's no middle ground that's safe.
81
+
82
+ ## Threat model and protection
83
+
84
+ The web user (pod owner) reads the key over HTTP, authenticated against their WebID. WAC checks the request and serves the file:
85
+
86
+ ```bash
87
+ curl -H "Authorization: Bearer <owner-token>" \
88
+ http://localhost:4444/alice/private/privkey.jsonld
89
+ ```
90
+
91
+ That path is fully protected by ACL. **What WAC cannot protect against is filesystem access.** Anyone with read on the data directory bypasses WAC entirely:
92
+
93
+ - `root` on the host
94
+ - Container layer dumps and exfiltrated images
95
+ - Backup tapes / snapshots that copy file contents
96
+ - Other unix users on a shared box (mitigated by the `0o600` mode)
97
+
98
+ For any pod that matters, layer in **filesystem-level protection**:
99
+
100
+ | Mechanism | What it adds |
101
+ |---|---|
102
+ | Full-disk encryption (LUKS / FileVault / BitLocker) | Protects offline copies of the disk |
103
+ | Encrypted volume / per-directory encryption | Protects against host-level snapshots |
104
+ | OS keyring (gnome-keyring, macOS Keychain) | Out-of-process secret storage; bigger lift |
105
+ | Restrictive `umask` + container user namespacing | Stops other users on a shared host |
106
+ | Filesystem ACLs (`setfacl`) | Fine-grained per-user limits |
107
+
108
+ Phase 4 of [#437](https://github.com/JavaScriptSolidServer/JavaScriptSolidServer/issues/437) will add encrypted-at-rest and hardware-wallet support. Until then, treat the file as a credential and protect it accordingly.
109
+
110
+ ## Credible exit
111
+
112
+ Phase 1 ships the simplest workable model: plaintext key on disk, owner-only WAC, `0o600`. This is intentional — it lets you start now and migrate later without losing the underlying identity:
113
+
114
+ | Phase | What changes | What stays |
115
+ |---|---|---|
116
+ | 1 (now) | plaintext on disk, WAC + 0o600 | the keypair, the WebID |
117
+ | 3 | optional `--key-passphrase` wraps the secret with scrypt+aesgcm | the keypair |
118
+ | 4 | hardware wallet / KMS / encrypted at rest | the keypair |
119
+
120
+ Each upgrade is a wrapper around the same secret material. You're not picking a final answer when you turn `--provision-keys` on — you're picking a starting point that can move with your security posture. ActivityPub took the same path: instances managed keys themselves at first, then later layered hardware-backed signing on top once the ecosystem matured.
121
+
122
+ ## Backup
123
+
124
+ This is not optional.
125
+
126
+ ```bash
127
+ # Authenticate as owner via HTTP (preferred — works even on a remote host).
128
+ # For a single-user / root pod the key is at <pod>/private/privkey.jsonld;
129
+ # for a named pod (multi-user) it's at <pod>/<name>/private/privkey.jsonld.
130
+ curl -H "Authorization: Bearer <owner-token>" \
131
+ http://your.example/private/privkey.jsonld \
132
+ -o pod-key-backup.jsonld
133
+ # named-pod variant:
134
+ curl -H "Authorization: Bearer <owner-token>" \
135
+ http://your.example/alice/private/privkey.jsonld \
136
+ -o pod-key-backup.jsonld
137
+ chmod 600 pod-key-backup.jsonld
138
+
139
+ # Or copy from disk if you have local access (preserves perms).
140
+ # Root pod (single-user, default since #348):
141
+ cp -p <DATA_ROOT>/private/privkey.jsonld pod-key-backup.jsonld
142
+ # Named pod (multi-user, or single-user with --single-user-name=alice):
143
+ cp -p <DATA_ROOT>/alice/private/privkey.jsonld pod-key-backup.jsonld
144
+ ```
145
+
146
+ Store the backup somewhere that survives the pod's host: another machine, encrypted cloud storage, a hardware token, a sealed envelope in a safe — whatever you'd use for an SSH key you actually care about. Losing this file means losing this identity permanently. There is no recovery flow in Phase 1.
147
+
148
+ ## Why opt-in by default
149
+
150
+ Keys-on-disk is a real security tradeoff. Defaulting `--provision-keys` on would mean every `jss start --single-user` ships a plaintext secret to disk silently — a bad surprise for an operator who only meant to spin up a server. Opt-in keeps the choice visible. (See [#437 design resolution #6](https://github.com/JavaScriptSolidServer/JavaScriptSolidServer/issues/437).)
151
+
152
+ ## See also
153
+
154
+ - [#437](https://github.com/JavaScriptSolidServer/JavaScriptSolidServer/issues/437) — the umbrella issue and design resolutions
155
+ - [W3C Controlled Identifiers v1.0 (REC)](https://www.w3.org/TR/cid-1.0/)
156
+ - [`src/auth/nostr-keys.js`](../src/auth/nostr-keys.js) — the existing f-form Multikey decoder this code aligns with
157
+ - [BIP-340 (Schnorr signatures over secp256k1)](https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "javascript-solid-server",
3
- "version": "0.0.188",
3
+ "version": "0.0.189",
4
4
  "description": "A minimal, fast Solid server",
5
5
  "main": "src/index.js",
6
6
  "type": "module",
package/src/config.js CHANGED
@@ -92,6 +92,12 @@ export const defaults = {
92
92
  // is not yet loggable until a password is set).
93
93
  singleUserPassword: null,
94
94
 
95
+ // Provision a Schnorr secp256k1 owner key on pod creation, written
96
+ // to <pod>/private/privkey.jsonld in W3C CID v1.0 Multikey format
97
+ // (Phase 1 of #437). Off by default — keys-on-disk is a security
98
+ // tradeoff and we want operators to opt in deliberately.
99
+ provisionKeys: false,
100
+
95
101
  // WebID-TLS client certificate authentication
96
102
  webidTls: false,
97
103
 
@@ -175,6 +181,7 @@ const envMap = {
175
181
  JSS_SINGLE_USER: 'singleUser',
176
182
  JSS_SINGLE_USER_NAME: 'singleUserName',
177
183
  JSS_SINGLE_USER_PASSWORD: 'singleUserPassword',
184
+ JSS_PROVISION_KEYS: 'provisionKeys',
178
185
  JSS_WEBID_TLS: 'webidTls',
179
186
  JSS_DEFAULT_QUOTA: 'defaultQuota',
180
187
  JSS_PUBLIC: 'public',
@@ -228,6 +235,7 @@ const BOOLEAN_KEYS = new Set([
228
235
  'inviteOnly',
229
236
  'multiuser',
230
237
  'singleUser',
238
+ 'provisionKeys',
231
239
  'webidTls',
232
240
  'public',
233
241
  'readOnly',
@@ -4,6 +4,7 @@ import { getAllHeaders } from '../ldp/headers.js';
4
4
  import { isContainer, getEffectiveUrlPath, getPodName } from '../utils/url.js';
5
5
  import { generateProfile, generatePreferences, generateTypeIndex, serialize } from '../webid/profile.js';
6
6
  import { generateOwnerAcl, generatePrivateAcl, generateInboxAcl, generatePublicFolderAcl, serializeAcl, relativizeOwnerWebId } from '../wac/parser.js';
7
+ import { provisionOwnerKey, assertProvisionKeysCompatible } from '../keys/provision.js';
7
8
  import { createToken } from '../auth/token.js';
8
9
  import { canAcceptInput, toJsonLd, RDF_TYPES } from '../rdf/conneg.js';
9
10
  import { emitChange } from '../notifications/events.js';
@@ -165,8 +166,19 @@ export async function handlePost(request, reply) {
165
166
  * @param {string} podUri - Pod root URI (e.g., https://alice.example.com/ or https://example.com/alice/)
166
167
  * @param {string} issuer - OIDC issuer URI
167
168
  * @param {number} defaultQuota - Default storage quota in bytes (optional)
169
+ * @param {object} [options]
170
+ * @param {boolean} [options.provisionKeys=false] - When true, generate a
171
+ * Schnorr secp256k1 keypair and write it to `<pod>/private/privkey.jsonld`
172
+ * in W3C CID v1.0 Multikey format. Phase 1 of #437. The secret lands on
173
+ * disk in plaintext under owner-only WAC + file mode 0600 — operators
174
+ * should add filesystem-level protection (FDE / OS keyring) for any pod
175
+ * that matters.
176
+ * @returns {Promise<{ podPath, podUri, ownerKey?: { document, publicHex, secretHex, publicMultibase } }>}
177
+ * When `provisionKeys` is true, the return value includes the freshly
178
+ * minted key material so the caller can surface the public side in CLI
179
+ * output (the secret should NOT be displayed or logged).
168
180
  */
169
- export async function createPodStructure(name, webId, podUri, issuer, defaultQuota = 0) {
181
+ export async function createPodStructure(name, webId, podUri, issuer, defaultQuota = 0, options = {}) {
170
182
  const podPath = `/${name}/`;
171
183
 
172
184
  // Create pod directory structure
@@ -236,7 +248,31 @@ export async function createPodStructure(name, webId, podUri, issuer, defaultQuo
236
248
  await initializeQuota(name, defaultQuota);
237
249
  }
238
250
 
239
- return { podPath, podUri };
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.
256
+ //
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 });
263
+ const ok = await storage.write(
264
+ `${podPath}private/privkey.jsonld`,
265
+ JSON.stringify(ownerKey.document, null, 2),
266
+ { mode: 0o600 }
267
+ );
268
+ if (!ok) {
269
+ throw new Error(
270
+ `Failed to write owner key file at ${podPath}private/privkey.jsonld`
271
+ );
272
+ }
273
+ }
274
+
275
+ return { podPath, podUri, ownerKey };
240
276
  }
241
277
 
242
278
  /**
@@ -260,7 +296,7 @@ export async function handleCreatePod(request, reply) {
260
296
  return reply.code(405).send({ error: 'Method Not Allowed', message: 'Server is in read-only mode' });
261
297
  }
262
298
 
263
- const { name, email, password } = request.body || {};
299
+ const { name, email, password, provisionKeys } = request.body || {};
264
300
  const idpEnabled = request.idpEnabled;
265
301
 
266
302
  if (!name || typeof name !== 'string') {
@@ -282,6 +318,25 @@ export async function handleCreatePod(request, reply) {
282
318
  return reply.code(400).send({ error: 'Invalid pod name. Use alphanumeric, dash, or underscore only.' });
283
319
  }
284
320
 
321
+ // Refuse provisionKeys + --public: WAC would be bypassed, exposing the
322
+ // freshly written secret to anyone. Use the same assertion helper as
323
+ // createServer's startup-time check so the error message stays in
324
+ // one place — converted to a 400 here because we're in an HTTP
325
+ // request context, not the constructor.
326
+ if (provisionKeys === true) {
327
+ try {
328
+ assertProvisionKeysCompatible({
329
+ provisionKeys: true,
330
+ isPublic: !!request.config?.public
331
+ });
332
+ } catch (err) {
333
+ return reply.code(400).send({
334
+ error: 'provisionKeys cannot be used in --public mode',
335
+ message: err.message
336
+ });
337
+ }
338
+ }
339
+
285
340
  const podPath = `/${name}/`;
286
341
 
287
342
  // Check if pod already exists
@@ -310,9 +365,14 @@ export async function handleCreatePod(request, reply) {
310
365
  // Issuer needs trailing slash for CTH compatibility
311
366
  const issuer = baseUri + '/';
312
367
 
368
+ let podCreation;
313
369
  try {
314
- // Use shared pod creation function
315
- await createPodStructure(name, webId, podUri, issuer);
370
+ // Use shared pod creation function. Coerce provisionKeys to a
371
+ // strict boolean so a JSON `null` / missing value defaults to off.
372
+ podCreation = await createPodStructure(
373
+ name, webId, podUri, issuer, 0,
374
+ { provisionKeys: provisionKeys === true }
375
+ );
316
376
  } catch (err) {
317
377
  console.error('Pod creation error:', err);
318
378
  // Cleanup on failure
@@ -326,6 +386,16 @@ export async function handleCreatePod(request, reply) {
326
386
 
327
387
  Object.entries(headers).forEach(([k, v]) => reply.header(k, v));
328
388
 
389
+ // Surface a summary of any provisioned key so callers can display
390
+ // the public side. The secret is NEVER echoed in the response —
391
+ // it lives only on disk under the pod's owner-only ACL.
392
+ const keyInfo = podCreation?.ownerKey
393
+ ? {
394
+ keyDocument: `${podUri}private/privkey.jsonld`,
395
+ publicKeyMultibase: podCreation.ownerKey.publicMultibase
396
+ }
397
+ : null;
398
+
329
399
  // If IdP is enabled, create account and return token + login URL
330
400
  if (idpEnabled) {
331
401
  try {
@@ -340,6 +410,7 @@ export async function handleCreatePod(request, reply) {
340
410
  token,
341
411
  idpIssuer: issuer,
342
412
  loginUrl: `${baseUri}/idp/auth`,
413
+ ...(keyInfo && { ownerKey: keyInfo })
343
414
  });
344
415
  } catch (err) {
345
416
  console.error('Account creation error:', err);
@@ -356,6 +427,7 @@ export async function handleCreatePod(request, reply) {
356
427
  name,
357
428
  webId,
358
429
  podUri,
359
- token
430
+ token,
431
+ ...(keyInfo && { ownerKey: keyInfo })
360
432
  });
361
433
  }
@@ -0,0 +1,157 @@
1
+ /**
2
+ * Owner-key provisioning for new pods.
3
+ *
4
+ * Generates a Schnorr secp256k1 keypair and serialises it as a
5
+ * W3C Controlled Identifiers (CID) v1.0 Multikey document. The same
6
+ * curve serves as a Solid signing identity, a Nostr identity, and a
7
+ * future did:nostr DID controller (Phase 2).
8
+ *
9
+ * Phase 1 of #437 — see the issue for design resolutions:
10
+ * - controller in Phase 1: the pod owner's WebID (did:nostr in Phase 2)
11
+ * - secret key on disk: plaintext, owner-only ACL, file mode 0600;
12
+ * filesystem-level protection (FDE / LUKS / OS keyring) recommended;
13
+ * wrapped-secret support deferred to Phase 3
14
+ * - encoding: multibase `f` (base16-lower) + multicodec; matches the
15
+ * style already used in src/auth/nostr-keys.js for did:nostr
16
+ * Multikey verification methods. Pure hex with ~5 bytes of
17
+ * self-describing metadata at the front, no new deps.
18
+ * - no `nostr` extension block: bech32 npub is a one-line derivation
19
+ * in any Nostr-aware tool, not worth the additional secret-on-disk
20
+ * surface area or a new dependency.
21
+ */
22
+
23
+ import { schnorr } from '@noble/curves/secp256k1';
24
+
25
+ /**
26
+ * Multicodec varints (lower-hex). The CCG / W3C CID v1.0 Multikey
27
+ * registry uses these to identify the algorithm of a key blob inside
28
+ * a multibase-encoded value.
29
+ * secp256k1-pub → 0xe7 → varint "e701"
30
+ * secp256k1-priv → 0x1301 → varint "8126"
31
+ */
32
+ const MULTICODEC_SECP256K1_PUB_HEX = 'e701';
33
+ const MULTICODEC_SECP256K1_PRIV_HEX = '8126';
34
+
35
+ /**
36
+ * Compressed-SEC1 parity byte for the *even-y* canonical point. BIP-340
37
+ * (Schnorr / Nostr) keys are x-only and pick the even-y point at each
38
+ * x; pairing the f-form prefix with `02` makes the Multikey value
39
+ * round-trip with src/auth/nostr-keys.js's decoder.
40
+ */
41
+ const EVEN_Y_PARITY_HEX = '02';
42
+
43
+ /**
44
+ * Generate a fresh secp256k1 keypair suitable for Schnorr signing.
45
+ *
46
+ * @returns {{ secretHex: string, publicHex: string }}
47
+ * `secretHex` — 32-byte secret scalar, lower-hex.
48
+ * `publicHex` — 32-byte x-only Schnorr pubkey, lower-hex (BIP-340).
49
+ */
50
+ export function generateOwnerKeypair() {
51
+ const secretBytes = schnorr.utils.randomPrivateKey();
52
+ const publicBytes = schnorr.getPublicKey(secretBytes);
53
+ return {
54
+ secretHex: bytesToHex(secretBytes),
55
+ publicHex: bytesToHex(publicBytes)
56
+ };
57
+ }
58
+
59
+ /**
60
+ * Encode a 32-byte hex value as an f-form Multikey value.
61
+ * For pub keys we prepend the parity byte (BIP-340 convention: 02);
62
+ * for priv keys the secret scalar IS the 32-byte payload — no parity.
63
+ */
64
+ export function publicKeyMultibase(publicHex) {
65
+ if (!/^[0-9a-f]{64}$/.test(publicHex)) {
66
+ throw new Error('publicKeyMultibase: expected 64-char lower-hex pubkey');
67
+ }
68
+ return 'f' + MULTICODEC_SECP256K1_PUB_HEX + EVEN_Y_PARITY_HEX + publicHex;
69
+ }
70
+
71
+ export function secretKeyMultibase(secretHex) {
72
+ if (!/^[0-9a-f]{64}$/.test(secretHex)) {
73
+ throw new Error('secretKeyMultibase: expected 64-char lower-hex secret');
74
+ }
75
+ return 'f' + MULTICODEC_SECP256K1_PRIV_HEX + secretHex;
76
+ }
77
+
78
+ /**
79
+ * 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).
83
+ *
84
+ * @param {object} args
85
+ * @param {string} args.controllerWebId - Absolute owner WebID URI.
86
+ * @param {string} args.publicHex - 32-byte x-only Schnorr pubkey hex.
87
+ * @param {string} args.secretHex - 32-byte secret scalar hex.
88
+ * @returns {object} JSON-LD Multikey document, ready for `JSON.stringify`.
89
+ */
90
+ export function buildOwnerKeyDocument({ controllerWebId, publicHex, secretHex }) {
91
+ if (typeof controllerWebId !== 'string' || !controllerWebId) {
92
+ throw new Error('buildOwnerKeyDocument: controllerWebId required');
93
+ }
94
+ return {
95
+ '@context': 'https://www.w3.org/ns/cid/v1',
96
+ type: 'Multikey',
97
+ controller: controllerWebId,
98
+ publicKeyMultibase: publicKeyMultibase(publicHex),
99
+ secretKeyMultibase: secretKeyMultibase(secretHex)
100
+ };
101
+ }
102
+
103
+ /**
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).
107
+ *
108
+ * The returned `secretHex` should be considered sensitive and not
109
+ * logged; the public `multibase` IS safe to print.
110
+ */
111
+ export function provisionOwnerKey({ controllerWebId }) {
112
+ const { publicHex, secretHex } = generateOwnerKeypair();
113
+ const document = buildOwnerKeyDocument({ controllerWebId, publicHex, secretHex });
114
+ return {
115
+ document,
116
+ publicHex,
117
+ secretHex,
118
+ publicMultibase: document.publicKeyMultibase
119
+ };
120
+ }
121
+
122
+ /**
123
+ * Refuse to provision keys when WAC is being bypassed.
124
+ *
125
+ * `--public` (and `request.config.public`) tells JSS to skip WAC and
126
+ * grant unauthenticated access to everything. Combined with
127
+ * `--provision-keys`, it would mean a plaintext secret at
128
+ * `/private/privkey.jsonld` is readable by anyone over HTTP — the
129
+ * exact opposite of what the seeded owner-only ACL is supposed to do.
130
+ *
131
+ * Throws a clear error so the operator hits the contradiction at
132
+ * startup (or pod-creation) rather than discovering it by reading
133
+ * their own server logs after a key leak.
134
+ *
135
+ * @param {object} args
136
+ * @param {boolean} args.provisionKeys
137
+ * @param {boolean} args.isPublic - jss `--public` mode
138
+ * @throws {Error} when both flags are true
139
+ */
140
+ export function assertProvisionKeysCompatible({ provisionKeys, isPublic }) {
141
+ if (provisionKeys && isPublic) {
142
+ throw new Error(
143
+ '--provision-keys cannot be combined with --public. --public bypasses ' +
144
+ 'WAC, which would make /private/privkey.jsonld readable by anyone over ' +
145
+ 'HTTP. Use --provision-keys with WAC enforcement (the default), or drop ' +
146
+ '--public.'
147
+ );
148
+ }
149
+ }
150
+
151
+ function bytesToHex(bytes) {
152
+ let s = '';
153
+ for (let i = 0; i < bytes.length; i++) {
154
+ s += bytes[i].toString(16).padStart(2, '0');
155
+ }
156
+ return s;
157
+ }
package/src/server.js CHANGED
@@ -29,6 +29,7 @@ import { tunnelPlugin } from './tunnel/index.js';
29
29
  import { terminalPlugin } from './terminal/index.js';
30
30
  import { registerErrorHandler } from './utils/error-handler.js';
31
31
  import { seedServerRoot } from './ui/server-root.js';
32
+ import { assertProvisionKeysCompatible } from './keys/provision.js';
32
33
 
33
34
  const __dirname = dirname(fileURLToPath(import.meta.url));
34
35
 
@@ -137,6 +138,26 @@ export function createServer(options = {}) {
137
138
  const liveReloadEnabled = options.liveReload ?? false;
138
139
  // MongoDB-backed /db/ route is OFF by default
139
140
  const mongoEnabled = options.mongo ?? false;
141
+ // Provision a Schnorr secp256k1 owner key in /private/privkey.jsonld
142
+ // when a single-user pod is first created. Phase 1 of #437. Off by
143
+ // default: keys-on-disk is a real security tradeoff, opt-in keeps
144
+ // the choice visible to the operator.
145
+ //
146
+ // Refuse the --provision-keys + --public combination at server-create
147
+ // time so the operator hits the contradiction immediately rather than
148
+ // by reading a leaked key from logs / the public web. See #442 review.
149
+ //
150
+ // Strict `=== true` (not `?? false`) coerces a misconfigured truthy
151
+ // non-boolean (e.g. JSON config / env coercion handing in `'true'`
152
+ // as a string) to false at the boundary. Without this, the root-pod
153
+ // branch's `if (provisionKeysEnabled)` would activate while the
154
+ // named-pod path's strict check downstream would not, leaving the
155
+ // two pod shapes behaving differently for the same input.
156
+ const provisionKeysEnabled = options.provisionKeys === true;
157
+ assertProvisionKeysCompatible({
158
+ provisionKeys: provisionKeysEnabled,
159
+ isPublic: !!options.public
160
+ });
140
161
  const mongoUrl = options.mongoUrl ?? 'mongodb://localhost:27017';
141
162
  const mongoDatabase = options.mongoDatabase ?? 'solid';
142
163
  // HTTP 402 paid /pay/ routes are OFF by default
@@ -840,14 +861,37 @@ export function createServer(options = {}) {
840
861
  if (!profileExists) {
841
862
  fastify.log.info(`Creating single-user pod at ${podUri}...`);
842
863
 
864
+ let creation;
843
865
  if (isRootPod) {
844
866
  // Root-level pod - create structure directly at /
845
- await createRootPodStructure(webId, podUri, issuer, displayName);
867
+ creation = await createRootPodStructure(webId, podUri, issuer, displayName);
846
868
  } else {
847
869
  // Named pod at /{name}/
848
- await createPodStructure(singleUserName, webId, podUri, issuer, defaultQuota);
870
+ creation = await createPodStructure(
871
+ singleUserName, webId, podUri, issuer, defaultQuota,
872
+ { provisionKeys: provisionKeysEnabled }
873
+ );
849
874
  }
850
875
  fastify.log.info(`Single-user pod created at ${podUri}`);
876
+
877
+ // Surface the public side of any provisioned owner key, plus
878
+ // a prominent backup reminder. The secret is NOT logged — it
879
+ // lives on disk only, under /private/privkey.jsonld with
880
+ // owner-only WAC and file mode 0o600.
881
+ if (creation?.ownerKey) {
882
+ // `podUri` already includes the trailing slash + any pod
883
+ // name segment, so the same expression covers root and
884
+ // named single-user pods.
885
+ const keyPath = `${podUri}private/privkey.jsonld`;
886
+ fastify.log.info(`Provisioned Schnorr secp256k1 owner key`);
887
+ fastify.log.info(` Public key file: ${keyPath}`);
888
+ fastify.log.info(` publicKeyMultibase: ${creation.ownerKey.publicMultibase}`);
889
+ fastify.log.warn(
890
+ `BACK UP ${keyPath} — losing this file means losing this identity. ` +
891
+ 'Filesystem reads bypass WAC; use FDE / OS keyring / restrictive umask ' +
892
+ 'for any pod that matters. See docs/provision-keys.md.'
893
+ );
894
+ }
851
895
  }
852
896
 
853
897
  // Seed an IDP account so the operator can actually log in. Without
@@ -980,11 +1024,19 @@ export function createServer(options = {}) {
980
1024
  }
981
1025
 
982
1026
  /**
983
- * Create root-level pod structure (for single-user mode with pod at /)
1027
+ * Create root-level pod structure (for single-user mode with pod at /).
1028
+ * When --provision-keys is set, returns `{ ownerKey }` so the caller
1029
+ * can surface the public side in the startup banner. The returned
1030
+ * `ownerKey` includes secretHex and secretKeyMultibase — needed by
1031
+ * tests, present in case a future caller needs to perform a one-shot
1032
+ * sign before the file is read back via WAC. **Callers must not log
1033
+ * the secret.** The secret's only durable home is the on-disk file
1034
+ * under /private/ (mode 0o600, owner-only WAC).
984
1035
  */
985
1036
  async function createRootPodStructure(webId, podUri, issuer, displayName) {
986
1037
  const { generateProfile, generatePreferences, generateTypeIndex, serialize } = await import('./webid/profile.js');
987
1038
  const { generateOwnerAcl, generatePrivateAcl, generateInboxAcl, generatePublicFolderAcl, serializeAcl, relativizeOwnerWebId } = await import('./wac/parser.js');
1039
+ const { provisionOwnerKey } = await import('./keys/provision.js');
988
1040
 
989
1041
  // Create directories at root
990
1042
  await storage.createContainer('/inbox/');
@@ -1038,7 +1090,27 @@ export function createServer(options = {}) {
1038
1090
  const profileAcl = generatePublicFolderAcl('./', owner('profile/'));
1039
1091
  await storage.write('/profile/.acl', serializeAcl(profileAcl));
1040
1092
 
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 });
1100
+ const ok = await storage.write(
1101
+ '/private/privkey.jsonld',
1102
+ JSON.stringify(ownerKey.document, null, 2),
1103
+ { mode: 0o600 }
1104
+ );
1105
+ if (!ok) {
1106
+ throw new Error(
1107
+ 'Failed to write owner key file at /private/privkey.jsonld'
1108
+ );
1109
+ }
1110
+ }
1111
+
1041
1112
  // Note: Quota not initialized for root-level pods (no user directory)
1113
+ return { ownerKey };
1042
1114
  }
1043
1115
 
1044
1116
  // Start file watcher for live reload (watches filesystem for external changes)
@@ -74,18 +74,57 @@ export function createReadStream(urlPath, options = {}) {
74
74
  }
75
75
 
76
76
  /**
77
- * Write resource content
78
- * @param {string} urlPath
79
- * @param {Buffer | string} content
80
- * @returns {Promise<boolean>}
77
+ * Write resource content.
78
+ *
79
+ * @param {string} urlPath - URL path of the resource being written
80
+ * (translated to a filesystem path internally).
81
+ * @param {Buffer | string} content - Bytes / text to write. Replaces
82
+ * the file if it already exists.
83
+ * @param {object} [options]
84
+ * @param {number} [options.mode] - POSIX file mode (e.g. `0o600`) to
85
+ * apply to the created file. Passed to `fs.writeFile` at create
86
+ * time so the file is never visible to other unix users with a
87
+ * looser default; an additional `chmod` runs afterward to tighten
88
+ * the file when overwriting an existing path that was created with
89
+ * a wider mode. On Windows, NTFS approximates POSIX modes coarsely
90
+ * (effectively read-only flag based on owner perms) — `chmod` is
91
+ * still attempted there but should not be relied on for
92
+ * cross-platform secrecy. See #437 for the secret-material use case.
93
+ * @returns {Promise<boolean>} `true` on success, `false` on write
94
+ * failure (chmod failures are logged but do not fail the write).
81
95
  */
82
- export async function write(urlPath, content) {
96
+ export async function write(urlPath, content, options = {}) {
83
97
  const filePath = urlToPath(urlPath);
84
98
 
85
99
  try {
86
100
  // Ensure parent directory exists
87
101
  await fs.ensureDir(path.dirname(filePath));
88
- await fs.writeFile(filePath, content);
102
+
103
+ // Pass `mode` to writeFile so the file is *created* with the
104
+ // requested permissions, closing the race window where another
105
+ // local process could read a freshly created secret-material
106
+ // file before a follow-up `chmod` ran. (Node only honours `mode`
107
+ // at create time, never on overwrite.)
108
+ if (typeof options.mode === 'number') {
109
+ await fs.writeFile(filePath, content, { mode: options.mode });
110
+ } else {
111
+ await fs.writeFile(filePath, content);
112
+ }
113
+
114
+ // Belt-and-braces: when overwriting an existing file, writeFile
115
+ // does NOT change the existing mode — apply chmod so a stale 0644
116
+ // file gets tightened to 0600 on subsequent writes. Logged but
117
+ // non-fatal: chmod is attempted on every platform (incl. Windows,
118
+ // where NTFS approximates POSIX modes coarsely) but callers that
119
+ // care about strict permissions should also rely on filesystem-
120
+ // level protection (FDE / OS keyring / container user namespacing).
121
+ if (typeof options.mode === 'number') {
122
+ try {
123
+ await fs.chmod(filePath, options.mode);
124
+ } catch (chmodErr) {
125
+ console.warn(`chmod ${options.mode.toString(8)} on ${filePath} failed:`, chmodErr.message);
126
+ }
127
+ }
89
128
  return true;
90
129
  } catch (err) {
91
130
  console.error('Write error:', err);
@@ -62,7 +62,7 @@
62
62
  <p class="explainer">This is a Solid pod server. Solid is an open standard for personal data — your data lives in pods you own, and apps connect to it.</p>
63
63
 
64
64
  <div class="actions">
65
- <a href="https://jss.live/docs/getting-started/introduction" class="btn btn-primary">Get started →</a>
65
+ <a href="https://jss.live/docs/getting-started/first-run" class="btn btn-primary">Get started →</a>
66
66
  <!-- IdP links are written page-relative (no leading slash) so they
67
67
  resolve against document base, surviving reverse-proxy mounts
68
68
  at a path prefix (e.g. https://example/jss/). Origin-root
@@ -0,0 +1,266 @@
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
+ assert.strictEqual(doc.controller, body.webId,
75
+ 'Phase 1 controller is the pod owner WebID (did:nostr lands in Phase 2)');
76
+ assert.match(doc.publicKeyMultibase, /^fe70102[0-9a-f]{64}$/);
77
+ assert.match(doc.secretKeyMultibase, /^f8126[0-9a-f]{64}$/);
78
+ // Round-trip the public side through jss's existing decoder.
79
+ const xonly = decodeFFormSecp256k1(doc.publicKeyMultibase);
80
+ assert.match(xonly, /^[0-9a-f]{64}$/);
81
+ });
82
+
83
+ it('writes the secret with file mode 0o600 (POSIX defence-in-depth)', { skip: process.platform === 'win32' }, async () => {
84
+ const filePath = path.join('./data', 'keyowner', 'private', 'privkey.jsonld');
85
+ const stat = await fs.stat(filePath);
86
+ // Strip the file-type bits (0o170000) and assert the perm bits.
87
+ const mode = stat.mode & 0o777;
88
+ assert.strictEqual(mode, 0o600,
89
+ `Expected 0o600 on the secret key file, got 0o${mode.toString(8)}`);
90
+ });
91
+
92
+ it('blocks unauthenticated reads of the secret key (WAC)', async () => {
93
+ const res = await request('/keyowner/private/privkey.jsonld');
94
+ assertStatus(res, 401);
95
+ });
96
+
97
+ it('serves the secret to the authenticated owner (WAC)', async () => {
98
+ assert.ok(ownerToken, 'pod owner token captured from the create response');
99
+ const res = await fetch(`${getBaseUrl()}/keyowner/private/privkey.jsonld`, {
100
+ headers: { Authorization: `Bearer ${ownerToken}` }
101
+ });
102
+ assertStatus(res, 200);
103
+ const doc = await res.json();
104
+ // The web user (pod owner) reads via HTTP/WAC — file mode 0o600
105
+ // restricts unix-user-on-the-box access only, never this path.
106
+ assert.strictEqual(doc.type, 'Multikey');
107
+ assert.match(doc.secretKeyMultibase, /^f8126[0-9a-f]{64}$/);
108
+ });
109
+
110
+ it('does NOT write a key file when provisionKeys is omitted (opt-in)', async () => {
111
+ const res = await fetch(`${getBaseUrl()}/.pods`, {
112
+ method: 'POST',
113
+ headers: { 'Content-Type': 'application/json' },
114
+ body: JSON.stringify({ name: 'nokeys' })
115
+ });
116
+ assertStatus(res, 201);
117
+ const body = await res.json();
118
+ assert.strictEqual(body.ownerKey, undefined,
119
+ 'opt-in: response must not include ownerKey when flag is omitted');
120
+ const filePath = path.join('./data', 'nokeys', 'private', 'privkey.jsonld');
121
+ assert.strictEqual(await fs.pathExists(filePath), false,
122
+ 'opt-in: file must not be written when flag is omitted');
123
+ });
124
+
125
+ it('does NOT write a key file when provisionKeys is false (explicit opt-out)', async () => {
126
+ const res = await fetch(`${getBaseUrl()}/.pods`, {
127
+ method: 'POST',
128
+ headers: { 'Content-Type': 'application/json' },
129
+ body: JSON.stringify({ name: 'nokeys2', provisionKeys: false })
130
+ });
131
+ assertStatus(res, 201);
132
+ const body = await res.json();
133
+ assert.strictEqual(body.ownerKey, undefined);
134
+ const filePath = path.join('./data', 'nokeys2', 'private', 'privkey.jsonld');
135
+ assert.strictEqual(await fs.pathExists(filePath), false);
136
+ });
137
+
138
+ it('does NOT trigger on truthy non-true values (e.g. string "true")', async () => {
139
+ // Defensive: only literal `true` activates the flag — keeps an
140
+ // accidentally-string-coerced value from silently turning it on.
141
+ const res = await fetch(`${getBaseUrl()}/.pods`, {
142
+ method: 'POST',
143
+ headers: { 'Content-Type': 'application/json' },
144
+ body: JSON.stringify({ name: 'stringtrue', provisionKeys: 'true' })
145
+ });
146
+ assertStatus(res, 201);
147
+ const body = await res.json();
148
+ assert.strictEqual(body.ownerKey, undefined,
149
+ 'string "true" must not trigger key provisioning');
150
+ const filePath = path.join('./data', 'stringtrue', 'private', 'privkey.jsonld');
151
+ assert.strictEqual(await fs.pathExists(filePath), false);
152
+ });
153
+ });
154
+
155
+ describe('POST /.pods — provisionKeys + --public (footgun guard)', () => {
156
+ // --public mode bypasses WAC: every resource becomes publicly
157
+ // readable. Combined with provisionKeys, /private/privkey.jsonld
158
+ // would be the world's worst secret store. Refuse the combination
159
+ // at request time with 400 so the operator hits the contradiction
160
+ // immediately. See #442 review.
161
+ let server;
162
+ let baseUrl;
163
+ let savedDataRoot;
164
+ const DATA_DIR = './test-data-provision-public';
165
+
166
+ before(async () => {
167
+ savedDataRoot = process.env.DATA_ROOT;
168
+ await fs.remove(DATA_DIR);
169
+ await fs.ensureDir(DATA_DIR);
170
+ const { createServer } = await import('../src/server.js');
171
+ server = createServer({
172
+ logger: false,
173
+ forceCloseConnections: true,
174
+ root: DATA_DIR,
175
+ public: true
176
+ });
177
+ await server.listen({ port: 0, host: '127.0.0.1' });
178
+ baseUrl = `http://127.0.0.1:${server.server.address().port}`;
179
+ });
180
+ after(async () => {
181
+ await server.close();
182
+ await fs.remove(DATA_DIR);
183
+ if (savedDataRoot === undefined) delete process.env.DATA_ROOT;
184
+ else process.env.DATA_ROOT = savedDataRoot;
185
+ });
186
+
187
+ it('rejects POST /.pods with provisionKeys: true on a --public server (400)', async () => {
188
+ const res = await fetch(`${baseUrl}/.pods`, {
189
+ method: 'POST',
190
+ headers: { 'Content-Type': 'application/json' },
191
+ body: JSON.stringify({ name: 'shouldnotexist', provisionKeys: true })
192
+ });
193
+ assert.strictEqual(res.status, 400);
194
+ const body = await res.json();
195
+ assert.match(body.message || body.error || '', /public/i,
196
+ 'error must explain why provisionKeys is rejected');
197
+ // Pod must not have been created.
198
+ assert.strictEqual(await fs.pathExists(`${DATA_DIR}/shouldnotexist/`), false);
199
+ });
200
+
201
+ it('still allows POST /.pods without provisionKeys on a --public server', async () => {
202
+ const res = await fetch(`${baseUrl}/.pods`, {
203
+ method: 'POST',
204
+ headers: { 'Content-Type': 'application/json' },
205
+ body: JSON.stringify({ name: 'publicpod' })
206
+ });
207
+ assert.strictEqual(res.status, 201);
208
+ });
209
+ });
210
+
211
+ describe('createServer — provisionKeys + --public refused at start', () => {
212
+ it('throws synchronously when both options are set', async () => {
213
+ const { createServer } = await import('../src/server.js');
214
+ assert.throws(
215
+ () => createServer({ logger: false, provisionKeys: true, public: true }),
216
+ /cannot be combined with --public/
217
+ );
218
+ });
219
+ });
220
+
221
+ describe('createPodStructure — provisionKeys option (direct call)', () => {
222
+ before(async () => {
223
+ await startTestServer();
224
+ });
225
+ after(async () => {
226
+ await stopTestServer();
227
+ });
228
+
229
+ it('returns ownerKey when provisionKeys is true', async () => {
230
+ const podUri = 'http://127.0.0.1:0/direct1/';
231
+ const webId = `${podUri}profile/card.jsonld#me`;
232
+ const result = await createPodStructure(
233
+ 'direct1', webId, podUri, podUri.replace(/\/$/, '/'), 0,
234
+ { provisionKeys: true }
235
+ );
236
+ assert.ok(result.ownerKey, 'createPodStructure must return ownerKey when provisionKeys is true');
237
+ assert.match(result.ownerKey.publicHex, /^[0-9a-f]{64}$/);
238
+ assert.match(result.ownerKey.secretHex, /^[0-9a-f]{64}$/);
239
+ assert.strictEqual(result.ownerKey.publicMultibase, result.ownerKey.document.publicKeyMultibase);
240
+ assert.strictEqual(result.ownerKey.document.controller, webId);
241
+ });
242
+
243
+ it('returns no ownerKey when the option is omitted', async () => {
244
+ const podUri = 'http://127.0.0.1:0/direct2/';
245
+ const webId = `${podUri}profile/card.jsonld#me`;
246
+ const result = await createPodStructure(
247
+ 'direct2', webId, podUri, podUri.replace(/\/$/, '/'), 0
248
+ );
249
+ assert.strictEqual(result.ownerKey, undefined);
250
+ });
251
+
252
+ it('requires strict boolean true (a truthy non-boolean does not trigger)', async () => {
253
+ // Defensive: matches the HTTP-side check on the request body so a
254
+ // misconfigured caller passing 'true' / 1 / etc. through the
255
+ // direct API doesn't silently provision a plaintext secret.
256
+ const podUri = 'http://127.0.0.1:0/direct3/';
257
+ const webId = `${podUri}profile/card.jsonld#me`;
258
+ const result = await createPodStructure(
259
+ 'direct3', webId, podUri, podUri.replace(/\/$/, '/'), 0,
260
+ { provisionKeys: 'true' } // intentionally string, not boolean
261
+ );
262
+ assert.strictEqual(result.ownerKey, undefined,
263
+ 'string "true" must not activate provisioning at the direct entry');
264
+ assert.strictEqual(await fs.pathExists('./data/direct3/private/privkey.jsonld'), false);
265
+ });
266
+ });
@@ -0,0 +1,172 @@
1
+ /**
2
+ * Unit tests for owner-key provisioning (Phase 1 of #437).
3
+ */
4
+
5
+ import { describe, it } from 'node:test';
6
+ import assert from 'node:assert';
7
+ import { schnorr } from '@noble/curves/secp256k1';
8
+ import {
9
+ generateOwnerKeypair,
10
+ publicKeyMultibase,
11
+ secretKeyMultibase,
12
+ buildOwnerKeyDocument,
13
+ provisionOwnerKey,
14
+ assertProvisionKeysCompatible
15
+ } from '../src/keys/provision.js';
16
+ import { decodeFFormSecp256k1 } from '../src/auth/nostr-keys.js';
17
+
18
+ describe('generateOwnerKeypair', () => {
19
+ it('produces a 32-byte x-only pubkey and a 32-byte secret', () => {
20
+ const { publicHex, secretHex } = generateOwnerKeypair();
21
+ assert.match(publicHex, /^[0-9a-f]{64}$/);
22
+ assert.match(secretHex, /^[0-9a-f]{64}$/);
23
+ });
24
+
25
+ it('produces a working Schnorr keypair (sign + verify)', () => {
26
+ const { publicHex, secretHex } = generateOwnerKeypair();
27
+ const message = new TextEncoder().encode('jss provision-keys roundtrip');
28
+ const sig = schnorr.sign(message, hexToBytes(secretHex));
29
+ assert.strictEqual(
30
+ schnorr.verify(sig, message, hexToBytes(publicHex)),
31
+ true,
32
+ 'signature must verify under the generated pubkey'
33
+ );
34
+ });
35
+
36
+ it('produces a different keypair on every call', () => {
37
+ const a = generateOwnerKeypair();
38
+ const b = generateOwnerKeypair();
39
+ assert.notStrictEqual(a.publicHex, b.publicHex);
40
+ assert.notStrictEqual(a.secretHex, b.secretHex);
41
+ });
42
+ });
43
+
44
+ describe('publicKeyMultibase / secretKeyMultibase', () => {
45
+ // Fixed test vectors so the encoding format is pinned (any change to
46
+ // multicodec/multibase would shift these values and fail the assertion).
47
+ const publicHex = '87a1c6f0e9b3d2456789abcdef0123456789abcdef0123456789abcdef012345';
48
+ const secretHex = '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef';
49
+
50
+ it('encodes a public key as f + e701 + 02 + 64-hex-pubkey', () => {
51
+ const mb = publicKeyMultibase(publicHex);
52
+ // f (multibase) + e701 (multicodec varint for secp256k1-pub) +
53
+ // 02 (BIP-340 even-y parity) + 64-char pubkey hex
54
+ assert.strictEqual(mb, 'fe70102' + publicHex);
55
+ });
56
+
57
+ it('encodes a secret key as f + 8126 + 64-hex-secret', () => {
58
+ const mb = secretKeyMultibase(secretHex);
59
+ // f (multibase) + 8126 (multicodec varint for secp256k1-priv) +
60
+ // 64-char secret hex (no parity byte — secret IS the scalar)
61
+ assert.strictEqual(mb, 'f8126' + secretHex);
62
+ });
63
+
64
+ it('round-trips through src/auth/nostr-keys decoder for the public side', () => {
65
+ // The Multikey value we write must be readable by jss's existing
66
+ // f-form decoder (used by the did:nostr verifier). This pins the
67
+ // shape so a future change to either side fails loud.
68
+ const mb = publicKeyMultibase(publicHex);
69
+ const decoded = decodeFFormSecp256k1(mb);
70
+ assert.strictEqual(decoded, publicHex);
71
+ });
72
+
73
+ it('rejects non-hex / wrong-length inputs', () => {
74
+ assert.throws(() => publicKeyMultibase('not-hex'), /64-char lower-hex/);
75
+ assert.throws(() => publicKeyMultibase(publicHex.slice(0, 63)), /64-char/);
76
+ assert.throws(() => secretKeyMultibase(''), /64-char/);
77
+ assert.throws(() => secretKeyMultibase(publicHex.toUpperCase()), /64-char lower-hex/);
78
+ });
79
+ });
80
+
81
+ describe('buildOwnerKeyDocument', () => {
82
+ const args = {
83
+ controllerWebId: 'https://alice.example/profile/card.jsonld#me',
84
+ publicHex: '87a1c6f0e9b3d2456789abcdef0123456789abcdef0123456789abcdef012345',
85
+ secretHex: '0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef'
86
+ };
87
+
88
+ it('emits a W3C CID v1.0 Multikey JSON-LD document', () => {
89
+ const doc = buildOwnerKeyDocument(args);
90
+ assert.strictEqual(doc['@context'], 'https://www.w3.org/ns/cid/v1');
91
+ assert.strictEqual(doc.type, 'Multikey');
92
+ });
93
+
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);
99
+ assert.strictEqual(doc.controller, args.controllerWebId);
100
+ assert.doesNotMatch(doc.controller, /^did:nostr:/);
101
+ });
102
+
103
+ it('embeds both the public and secret Multikey values', () => {
104
+ const doc = buildOwnerKeyDocument(args);
105
+ assert.strictEqual(doc.publicKeyMultibase, publicKeyMultibase(args.publicHex));
106
+ assert.strictEqual(doc.secretKeyMultibase, secretKeyMultibase(args.secretHex));
107
+ });
108
+
109
+ it('does NOT include a `nostr` extension block (npub etc.)', () => {
110
+ // Resolution #2 of #437: bech32 npub is derivable from the public
111
+ // multibase value in any Nostr-aware tool. Including it would
112
+ // double the secret-on-disk surface for log/error/dump leaks
113
+ // (the symmetric `nsec` field was originally proposed alongside).
114
+ const doc = buildOwnerKeyDocument(args);
115
+ assert.strictEqual(doc.nostr, undefined);
116
+ });
117
+
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/);
121
+ });
122
+ });
123
+
124
+ describe('provisionOwnerKey', () => {
125
+ it('returns the document together with raw key material for CLI display', () => {
126
+ const out = provisionOwnerKey({ controllerWebId: 'https://alice.example/profile/card.jsonld#me' });
127
+ assert.match(out.publicHex, /^[0-9a-f]{64}$/);
128
+ assert.match(out.secretHex, /^[0-9a-f]{64}$/);
129
+ assert.strictEqual(out.publicMultibase, out.document.publicKeyMultibase);
130
+ assert.strictEqual(out.document.type, 'Multikey');
131
+ assert.strictEqual(out.document.controller, 'https://alice.example/profile/card.jsonld#me');
132
+ });
133
+ });
134
+
135
+ describe('assertProvisionKeysCompatible', () => {
136
+ // Refuse the provisionKeys + --public combination — public mode
137
+ // bypasses WAC, which would expose the freshly-written secret on
138
+ // /private/privkey.jsonld to anyone over HTTP.
139
+ it('throws when both provisionKeys and isPublic are true', () => {
140
+ assert.throws(
141
+ () => assertProvisionKeysCompatible({ provisionKeys: true, isPublic: true }),
142
+ /cannot be combined with --public/
143
+ );
144
+ });
145
+
146
+ it('does NOT throw for provisionKeys alone (the supported case)', () => {
147
+ assert.doesNotThrow(() =>
148
+ assertProvisionKeysCompatible({ provisionKeys: true, isPublic: false })
149
+ );
150
+ });
151
+
152
+ it('does NOT throw for --public alone (no secrets being written)', () => {
153
+ assert.doesNotThrow(() =>
154
+ assertProvisionKeysCompatible({ provisionKeys: false, isPublic: true })
155
+ );
156
+ });
157
+
158
+ it('does NOT throw when neither flag is set', () => {
159
+ assert.doesNotThrow(() =>
160
+ assertProvisionKeysCompatible({ provisionKeys: false, isPublic: false })
161
+ );
162
+ });
163
+ });
164
+
165
+ function hexToBytes(hex) {
166
+ if (hex.length % 2 !== 0) throw new Error('hex length must be even');
167
+ const out = new Uint8Array(hex.length / 2);
168
+ for (let i = 0; i < out.length; i++) {
169
+ out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
170
+ }
171
+ return out;
172
+ }
@@ -132,12 +132,12 @@ describe('renderServerRoot', () => {
132
132
  assert.doesNotMatch(html, /class="info"/);
133
133
  });
134
134
 
135
- it('always emits the Get started button pointing at the docs introduction', () => {
135
+ it('always emits the Get started button pointing at the docs First Run page', () => {
136
136
  const html = renderServerRoot({ version: '1.0.0' });
137
- // The canonical URL is the introduction page, not the category.
138
- // Docusaurus 3 doesn't auto-generate a category index page, so
139
- // /docs/getting-started/ would 404. Link to the real document.
140
- assert.match(html, /href="https:\/\/jss\.live\/docs\/getting-started\/introduction"/);
137
+ // First Run is the friendly "you just installed it, now what?"
138
+ // walkthrough — better destination for a first-time installer than
139
+ // the encyclopedic Introduction page. See #440.
140
+ assert.match(html, /href="https:\/\/jss\.live\/docs\/getting-started\/first-run"/);
141
141
  assert.match(html, /Get started/);
142
142
  });
143
143