javascript-solid-server 0.0.188 → 0.0.190

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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.190",
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
@@ -178,9 +190,20 @@ export async function createPodStructure(name, webId, podUri, issuer, defaultQuo
178
190
  await storage.createContainer(`${podPath}settings/`);
179
191
  await storage.createContainer(`${podPath}profile/`);
180
192
 
181
- // Generate and write WebID profile at /profile/card.jsonld
182
- const profile = generateProfile({ webId, name, podUri, issuer });
183
- 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.
184
207
 
185
208
  // Generate and write preferences
186
209
  const prefs = generatePreferences({ webId, podUri });
@@ -236,7 +259,49 @@ export async function createPodStructure(name, webId, podUri, issuer, defaultQuo
236
259
  await initializeQuota(name, defaultQuota);
237
260
  }
238
261
 
239
- return { podPath, podUri };
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.
271
+ //
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) {
280
+ const ok = await storage.write(
281
+ `${podPath}private/privkey.jsonld`,
282
+ JSON.stringify(ownerKey.document, null, 2),
283
+ { mode: 0o600 }
284
+ );
285
+ if (!ok) {
286
+ throw new Error(
287
+ `Failed to write owner key file at ${podPath}private/privkey.jsonld`
288
+ );
289
+ }
290
+ }
291
+
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 }) };
240
305
  }
241
306
 
242
307
  /**
@@ -260,7 +325,7 @@ export async function handleCreatePod(request, reply) {
260
325
  return reply.code(405).send({ error: 'Method Not Allowed', message: 'Server is in read-only mode' });
261
326
  }
262
327
 
263
- const { name, email, password } = request.body || {};
328
+ const { name, email, password, provisionKeys } = request.body || {};
264
329
  const idpEnabled = request.idpEnabled;
265
330
 
266
331
  if (!name || typeof name !== 'string') {
@@ -282,6 +347,25 @@ export async function handleCreatePod(request, reply) {
282
347
  return reply.code(400).send({ error: 'Invalid pod name. Use alphanumeric, dash, or underscore only.' });
283
348
  }
284
349
 
350
+ // Refuse provisionKeys + --public: WAC would be bypassed, exposing the
351
+ // freshly written secret to anyone. Use the same assertion helper as
352
+ // createServer's startup-time check so the error message stays in
353
+ // one place — converted to a 400 here because we're in an HTTP
354
+ // request context, not the constructor.
355
+ if (provisionKeys === true) {
356
+ try {
357
+ assertProvisionKeysCompatible({
358
+ provisionKeys: true,
359
+ isPublic: !!request.config?.public
360
+ });
361
+ } catch (err) {
362
+ return reply.code(400).send({
363
+ error: 'provisionKeys cannot be used in --public mode',
364
+ message: err.message
365
+ });
366
+ }
367
+ }
368
+
285
369
  const podPath = `/${name}/`;
286
370
 
287
371
  // Check if pod already exists
@@ -310,9 +394,14 @@ export async function handleCreatePod(request, reply) {
310
394
  // Issuer needs trailing slash for CTH compatibility
311
395
  const issuer = baseUri + '/';
312
396
 
397
+ let podCreation;
313
398
  try {
314
- // Use shared pod creation function
315
- await createPodStructure(name, webId, podUri, issuer);
399
+ // Use shared pod creation function. Coerce provisionKeys to a
400
+ // strict boolean so a JSON `null` / missing value defaults to off.
401
+ podCreation = await createPodStructure(
402
+ name, webId, podUri, issuer, 0,
403
+ { provisionKeys: provisionKeys === true }
404
+ );
316
405
  } catch (err) {
317
406
  console.error('Pod creation error:', err);
318
407
  // Cleanup on failure
@@ -326,6 +415,16 @@ export async function handleCreatePod(request, reply) {
326
415
 
327
416
  Object.entries(headers).forEach(([k, v]) => reply.header(k, v));
328
417
 
418
+ // Surface a summary of any provisioned key so callers can display
419
+ // the public side. The secret is NEVER echoed in the response —
420
+ // it lives only on disk under the pod's owner-only ACL.
421
+ const keyInfo = podCreation?.ownerKey
422
+ ? {
423
+ keyDocument: `${podUri}private/privkey.jsonld`,
424
+ publicKeyMultibase: podCreation.ownerKey.publicMultibase
425
+ }
426
+ : null;
427
+
329
428
  // If IdP is enabled, create account and return token + login URL
330
429
  if (idpEnabled) {
331
430
  try {
@@ -340,6 +439,7 @@ export async function handleCreatePod(request, reply) {
340
439
  token,
341
440
  idpIssuer: issuer,
342
441
  loginUrl: `${baseUri}/idp/auth`,
442
+ ...(keyInfo && { ownerKey: keyInfo })
343
443
  });
344
444
  } catch (err) {
345
445
  console.error('Account creation error:', err);
@@ -356,6 +456,7 @@ export async function handleCreatePod(request, reply) {
356
456
  name,
357
457
  webId,
358
458
  podUri,
359
- token
459
+ token,
460
+ ...(keyInfo && { ownerKey: keyInfo })
360
461
  });
361
462
  }