javascript-solid-server 0.0.187 → 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.187",
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)