javascript-solid-server 0.0.188 → 0.0.190

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,337 @@
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, secp256k1 } 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
+ * The secret is normalized so that `G * secret` has *even* y (BIP-340
47
+ * convention). Without normalization, ECDSA signatures made with the
48
+ * raw secret would verify against the natural y of the public point —
49
+ * even half the time, odd half the time — while the corresponding JWK
50
+ * we publish in the WebID profile is always derived from the even-y
51
+ * x-only Schnorr pubkey. The two would disagree on ~50% of generated
52
+ * secrets, breaking Phase 2's LWS-CID round-trip non-deterministically.
53
+ *
54
+ * Normalizing once at generation time means a single secret-on-disk
55
+ * works under both Schnorr (Nostr) and ECDSA (LWS-CID JWT) without
56
+ * parity gymnastics in either signing path.
57
+ *
58
+ * @returns {{ secretHex: string, publicHex: string }}
59
+ * `secretHex` — 32-byte secret scalar, lower-hex, normalized so the
60
+ * corresponding public point has even y.
61
+ * `publicHex` — 32-byte x-only Schnorr pubkey, lower-hex (BIP-340).
62
+ */
63
+ export function generateOwnerKeypair() {
64
+ let secretBytes = schnorr.utils.randomPrivateKey();
65
+ // Compressed SEC1 starts with 02 (even y) or 03 (odd y).
66
+ const compressed = secp256k1.getPublicKey(secretBytes, /*compressed=*/true);
67
+ if (compressed[0] === 0x03) {
68
+ // Negate the secret (mod n) so the resulting point flips to even y.
69
+ const n = secp256k1.CURVE.n;
70
+ const original = BigInt('0x' + bytesToHex(secretBytes));
71
+ const negated = (n - original) % n;
72
+ secretBytes = hexToBytes(negated.toString(16).padStart(64, '0'));
73
+ }
74
+ const publicBytes = schnorr.getPublicKey(secretBytes);
75
+ return {
76
+ secretHex: bytesToHex(secretBytes),
77
+ publicHex: bytesToHex(publicBytes)
78
+ };
79
+ }
80
+
81
+ /**
82
+ * Encode a 32-byte hex value as an f-form Multikey value.
83
+ * For pub keys we prepend the parity byte (BIP-340 convention: 02);
84
+ * for priv keys the secret scalar IS the 32-byte payload — no parity.
85
+ */
86
+ export function publicKeyMultibase(publicHex) {
87
+ if (!/^[0-9a-f]{64}$/.test(publicHex)) {
88
+ throw new Error('publicKeyMultibase: expected 64-char lower-hex pubkey');
89
+ }
90
+ return 'f' + MULTICODEC_SECP256K1_PUB_HEX + EVEN_Y_PARITY_HEX + publicHex;
91
+ }
92
+
93
+ export function secretKeyMultibase(secretHex) {
94
+ if (!/^[0-9a-f]{64}$/.test(secretHex)) {
95
+ throw new Error('secretKeyMultibase: expected 64-char lower-hex secret');
96
+ }
97
+ return 'f' + MULTICODEC_SECP256K1_PRIV_HEX + secretHex;
98
+ }
99
+
100
+ /**
101
+ * Compute the canonical did:nostr identifier for a Schnorr secp256k1
102
+ * pubkey. Lower-hex form (matches the rest of jss — see
103
+ * src/idp/well-known-did-nostr.js's resolveDidNostrLocally(pubkeyHex)
104
+ * and src/auth/did-nostr.js's `did:nostr:${pubkey.toLowerCase()}`).
105
+ * Phase 2 of #437 (#443) flips the Multikey document's `controller`
106
+ * field to this form now that jss's resolver round-trips it.
107
+ *
108
+ * @param {string} publicHex - 32-byte x-only Schnorr pubkey hex.
109
+ * @returns {string} `did:nostr:<lower-hex pubkey>`.
110
+ */
111
+ export function didNostrFromPublicHex(publicHex) {
112
+ if (!/^[0-9a-f]{64}$/.test(publicHex)) {
113
+ throw new Error('didNostrFromPublicHex: expected 64-char lower-hex pubkey');
114
+ }
115
+ return `did:nostr:${publicHex}`;
116
+ }
117
+
118
+ /**
119
+ * Build the W3C CID v1.0 Multikey JSON-LD document for a fresh pod
120
+ * owner key.
121
+ *
122
+ * Phase 2 default controller: `did:nostr:<hex>`. The previous Phase 1
123
+ * shape used the pod owner's WebID — both are valid CID v1.0
124
+ * controllers, but did:nostr lets the keypair self-identify via jss's
125
+ * existing resolver. Callers can still pass an explicit `controller`
126
+ * (the legacy WebID form is what existing test fixtures use).
127
+ *
128
+ * @param {object} args
129
+ * @param {string} args.publicHex - 32-byte x-only Schnorr pubkey hex.
130
+ * @param {string} args.secretHex - 32-byte secret scalar hex.
131
+ * @param {string} [args.controller] - Override the controller field.
132
+ * Defaults to `did:nostr:<publicHex>` (Phase 2 of #437 / #443).
133
+ * @returns {object} JSON-LD Multikey document, ready for `JSON.stringify`.
134
+ */
135
+ export function buildOwnerKeyDocument({ publicHex, secretHex, controller }) {
136
+ const ctrl = controller ?? didNostrFromPublicHex(publicHex);
137
+ if (typeof ctrl !== 'string' || !ctrl) {
138
+ throw new Error('buildOwnerKeyDocument: controller required');
139
+ }
140
+ return {
141
+ '@context': 'https://www.w3.org/ns/cid/v1',
142
+ type: 'Multikey',
143
+ controller: ctrl,
144
+ publicKeyMultibase: publicKeyMultibase(publicHex),
145
+ secretKeyMultibase: secretKeyMultibase(secretHex)
146
+ };
147
+ }
148
+
149
+ /**
150
+ * Compute the BIP-340 even-y JWK (kty=EC, crv=secp256k1) for an
151
+ * x-only Schnorr pubkey hex. Phase 2 needs this for the VM that
152
+ * lands in the WebID profile — the LWS-CID verifier currently reads
153
+ * `publicKeyJwk` only (Multikey-only VMs aren't yet handled there
154
+ * per `src/auth/lws-cid.js`'s docstring), so the VM ships both
155
+ * `publicKeyMultibase` (CID v1.0 conformance) and `publicKeyJwk`
156
+ * (LWS-CID compat).
157
+ *
158
+ * The y coordinate is computed against the canonical even-y point at
159
+ * `x` — same convention `src/auth/nostr-keys.js`'s
160
+ * `pubkeyFromValidatedJwk` checks against on the verifier side, so
161
+ * the VM we mint round-trips through the existing extractor without
162
+ * being rejected as "wrong y".
163
+ *
164
+ * @param {string} publicHex - 32-byte x-only Schnorr pubkey hex.
165
+ * @returns {{ kty: 'EC', crv: 'secp256k1', x: string, y: string }}
166
+ */
167
+ export function publicKeyJwkFromHex(publicHex) {
168
+ if (!/^[0-9a-f]{64}$/.test(publicHex)) {
169
+ throw new Error('publicKeyJwkFromHex: expected 64-char lower-hex pubkey');
170
+ }
171
+ // Compressed SEC1 with parity 02 = the canonical even-y point at x.
172
+ const point = secp256k1.ProjectivePoint.fromHex('02' + publicHex);
173
+ const yHex = point.toAffine().y.toString(16).padStart(64, '0');
174
+ return {
175
+ kty: 'EC',
176
+ crv: 'secp256k1',
177
+ x: hexToBase64Url(publicHex),
178
+ y: hexToBase64Url(yHex)
179
+ };
180
+ }
181
+
182
+ /**
183
+ * Build the verificationMethod entry for the seeded WebID profile.
184
+ *
185
+ * The VM wires the Phase 1 keypair into the existing LWS-CID auth
186
+ * loop: an agent signs a JWT with the on-disk secret + `kid` set to
187
+ * this VM's `id`, the verifier (already merged in `src/auth/lws-cid.js`)
188
+ * fetches the WebID profile, finds this VM, decodes the JWK, verifies
189
+ * the signature, and returns the WebID as the authenticated identity.
190
+ *
191
+ * Both forms are emitted: `publicKeyMultibase` for CID v1.0 readers
192
+ * (and round-trip with `decodeFFormSecp256k1` in `src/auth/nostr-keys.js`),
193
+ * `publicKeyJwk` for the LWS-CID verifier and any tool that prefers JOSE.
194
+ *
195
+ * @param {object} args
196
+ * @param {string} args.webId - Pod owner's WebID; used to derive both
197
+ * the `controller` and the document URL the VM `id` sits in.
198
+ * @param {string} args.publicHex - 32-byte x-only Schnorr pubkey hex.
199
+ * @param {string} [args.fragment='owner-key'] - Fragment id for the VM;
200
+ * appended to the WebID document URL to form `vm.id`.
201
+ * @returns {object} JSON-LD verificationMethod entry.
202
+ */
203
+ export function buildOwnerVerificationMethod({ webId, publicHex, fragment = 'owner-key' }) {
204
+ if (typeof webId !== 'string' || !webId) {
205
+ throw new Error('buildOwnerVerificationMethod: webId required');
206
+ }
207
+ const docUrl = webId.split('#')[0];
208
+ return {
209
+ '@id': `${docUrl}#${fragment}`,
210
+ '@type': 'Multikey',
211
+ controller: webId,
212
+ publicKeyMultibase: publicKeyMultibase(publicHex),
213
+ publicKeyJwk: publicKeyJwkFromHex(publicHex)
214
+ };
215
+ }
216
+
217
+ /**
218
+ * One-shot helper: generate a fresh keypair and produce the Multikey
219
+ * document, the verificationMethod entry for the WebID profile, and
220
+ * the raw key material (for log lines / CLI output that wants to
221
+ * display the pubkey).
222
+ *
223
+ * The returned `secretHex` should be considered sensitive and not
224
+ * logged; the public `publicMultibase` IS safe to print.
225
+ *
226
+ * Single canonical input shape — `webId` for VM controller + VM `@id`
227
+ * derivation, `documentController` to override the Multikey document's
228
+ * controller (defaults to `did:nostr:<publicHex>` per Phase 2 of #437).
229
+ * The previous `controllerWebId` legacy alias was removed in #443
230
+ * because it created surprising precedence interactions with the new
231
+ * `documentController` and asymmetric document/VM controllers.
232
+ *
233
+ * **Two controllers, on purpose.** `vm.controller` lives inside the
234
+ * WebID profile and always tracks `webId` — it identifies who in
235
+ * WebID-land can present this VM (the pod owner). `document.controller`
236
+ * lives in /private/privkey.jsonld and identifies the key in its own
237
+ * right (default did:nostr, overridable). They're decoupled by design;
238
+ * `documentController` does NOT propagate to the VM. If a caller wants
239
+ * both to point at, say, a custom DID, they should construct the VM
240
+ * separately via `buildOwnerVerificationMethod` and merge.
241
+ *
242
+ * @param {object} args
243
+ * @param {string} args.webId - Pod owner's WebID. Used as the VM
244
+ * controller and to derive the VM's `@id` fragment.
245
+ * @param {string} [args.documentController] - Override the Multikey
246
+ * document's controller. Defaults to `did:nostr:<publicHex>`.
247
+ * @returns {{
248
+ * document: object,
249
+ * vm: object,
250
+ * publicHex: string,
251
+ * secretHex: string,
252
+ * publicMultibase: string,
253
+ * didNostr: string
254
+ * }}
255
+ */
256
+ export function provisionOwnerKey({ webId, documentController }) {
257
+ if (typeof webId !== 'string' || !webId) {
258
+ throw new Error('provisionOwnerKey: webId required');
259
+ }
260
+ const { publicHex, secretHex } = generateOwnerKeypair();
261
+ // Pass `documentController` through verbatim — buildOwnerKeyDocument
262
+ // already defaults to `did:nostr:<publicHex>` when none is given, so
263
+ // duplicating the fallback here would just create two sources of
264
+ // truth for the default controller.
265
+ const document = buildOwnerKeyDocument({
266
+ publicHex,
267
+ secretHex,
268
+ controller: documentController
269
+ });
270
+ const vm = buildOwnerVerificationMethod({ webId, publicHex });
271
+ return {
272
+ document,
273
+ vm,
274
+ publicHex,
275
+ secretHex,
276
+ publicMultibase: document.publicKeyMultibase,
277
+ didNostr: didNostrFromPublicHex(publicHex)
278
+ };
279
+ }
280
+
281
+ /**
282
+ * Refuse to provision keys when WAC is being bypassed.
283
+ *
284
+ * `--public` (and `request.config.public`) tells JSS to skip WAC and
285
+ * grant unauthenticated access to everything. Combined with
286
+ * `--provision-keys`, it would mean a plaintext secret at
287
+ * `/private/privkey.jsonld` is readable by anyone over HTTP — the
288
+ * exact opposite of what the seeded owner-only ACL is supposed to do.
289
+ *
290
+ * Throws a clear error so the operator hits the contradiction at
291
+ * startup (or pod-creation) rather than discovering it by reading
292
+ * their own server logs after a key leak.
293
+ *
294
+ * @param {object} args
295
+ * @param {boolean} args.provisionKeys
296
+ * @param {boolean} args.isPublic - jss `--public` mode
297
+ * @throws {Error} when both flags are true
298
+ */
299
+ export function assertProvisionKeysCompatible({ provisionKeys, isPublic }) {
300
+ if (provisionKeys && isPublic) {
301
+ throw new Error(
302
+ '--provision-keys cannot be combined with --public. --public bypasses ' +
303
+ 'WAC, which would make /private/privkey.jsonld readable by anyone over ' +
304
+ 'HTTP. Use --provision-keys with WAC enforcement (the default), or drop ' +
305
+ '--public.'
306
+ );
307
+ }
308
+ }
309
+
310
+ function bytesToHex(bytes) {
311
+ let s = '';
312
+ for (let i = 0; i < bytes.length; i++) {
313
+ s += bytes[i].toString(16).padStart(2, '0');
314
+ }
315
+ return s;
316
+ }
317
+
318
+ function hexToBase64Url(hex) {
319
+ if (!/^[0-9a-f]+$/i.test(hex) || hex.length % 2 !== 0) {
320
+ throw new Error('hexToBase64Url: expected even-length hex');
321
+ }
322
+ return Buffer.from(hex, 'hex').toString('base64url');
323
+ }
324
+
325
+ function hexToBytes(hex) {
326
+ // Validate up front — without this, `parseInt('zz', 16)` returns
327
+ // NaN and silently writes 0 into the byte slot. Today the only
328
+ // caller passes freshly-generated 32-byte hex, but the helper is
329
+ // shared infrastructure: every sibling helper (`publicKeyJwkFromHex`,
330
+ // `didNostrFromPublicHex`, `hexToBase64Url`) validates the same way.
331
+ if (typeof hex !== 'string' || !/^[0-9a-fA-F]+$/.test(hex) || hex.length % 2 !== 0) {
332
+ throw new Error('hexToBytes: expected even-length hex');
333
+ }
334
+ const out = new Uint8Array(hex.length / 2);
335
+ for (let i = 0; i < out.length; i++) out[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
336
+ return out;
337
+ }
package/src/server.js CHANGED
@@ -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/');
@@ -993,9 +1045,16 @@ export function createServer(options = {}) {
993
1045
  await storage.createContainer('/settings/');
994
1046
  await storage.createContainer('/profile/');
995
1047
 
996
- // Generate profile
997
- const profile = generateProfile({ webId, name: displayName, podUri, issuer });
998
- await storage.write('/profile/card.jsonld', serialize(profile));
1048
+ // Generate the owner key in memory up-front (when --provision-keys
1049
+ // is set) so its VM can be injected into the WebID profile that
1050
+ // gets written last. On-disk persistence of the secret happens
1051
+ // *after* the ACL tree is in place — see the ordering block
1052
+ // further below.
1053
+ const ownerKey = provisionKeysEnabled
1054
+ ? provisionOwnerKey({ webId })
1055
+ : null;
1056
+
1057
+ // Profile is written last (see the ACL/privkey block below).
999
1058
 
1000
1059
  // Preferences and type indexes
1001
1060
  const prefs = generatePreferences({ webId, podUri });
@@ -1038,7 +1097,48 @@ export function createServer(options = {}) {
1038
1097
  const profileAcl = generatePublicFolderAcl('./', owner('profile/'));
1039
1098
  await storage.write('/profile/.acl', serializeAcl(profileAcl));
1040
1099
 
1041
- // Note: Quota not initialized for root-level pods (no user directory)
1100
+ // Owner-key persistence + profile write (when --provision-keys is
1101
+ // on). Order is load-bearing for two distinct concerns
1102
+ // (#444 review):
1103
+ //
1104
+ // 1. WAC vacuum: write privkey *after* the ACL tree is in place
1105
+ // so the secret file is born under owner-only WAC. Without
1106
+ // this, there's a window where the file exists but no
1107
+ // /private/.acl protects it; deny-by-default since #f43ecdf
1108
+ // would mitigate to 401, but defence-in-depth beats relying
1109
+ // on a security default holding. The single-user root pod is
1110
+ // especially exposed since the URL is the server origin.
1111
+ //
1112
+ // 2. Orphan-VM: write privkey *before* the profile so a crash
1113
+ // between the two leaves an orphan secret file (easy to
1114
+ // delete) rather than an orphan VM in a published WebID
1115
+ // profile that forever advertises an authentication method
1116
+ // whose secret was never persisted.
1117
+ //
1118
+ // Combined: ACLs (above) → privkey (here) → profile (next).
1119
+ if (ownerKey) {
1120
+ const ok = await storage.write(
1121
+ '/private/privkey.jsonld',
1122
+ JSON.stringify(ownerKey.document, null, 2),
1123
+ { mode: 0o600 }
1124
+ );
1125
+ if (!ok) {
1126
+ throw new Error(
1127
+ 'Failed to write owner key file at /private/privkey.jsonld'
1128
+ );
1129
+ }
1130
+ }
1131
+
1132
+ // Generate profile (with the owner key's VM landed in
1133
+ // verificationMethod when --provision-keys is on). Written last —
1134
+ // see ordering rationale above.
1135
+ const profile = generateProfile({ webId, name: displayName, podUri, issuer, ownerVm: ownerKey?.vm });
1136
+ await storage.write('/profile/card.jsonld', serialize(profile));
1137
+
1138
+ // Note: Quota not initialized for root-level pods (no user directory).
1139
+ // Spread `ownerKey` only when set so the field is genuinely absent
1140
+ // (not `null`) on the no-provisioning path.
1141
+ return { ...(ownerKey && { ownerKey }) };
1042
1142
  }
1043
1143
 
1044
1144
  // 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
@@ -16,15 +16,31 @@ const CID = 'https://www.w3.org/ns/cid/v1#';
16
16
  const LWS = 'https://www.w3.org/ns/lws#';
17
17
 
18
18
  /**
19
- * Generate JSON-LD data for a WebID profile
19
+ * Generate JSON-LD data for a WebID profile.
20
+ *
20
21
  * @param {object} options
21
22
  * @param {string} options.webId - Full WebID URI (e.g., https://example.com/alice/profile/card#me)
22
23
  * @param {string} options.name - Display name
23
24
  * @param {string} options.podUri - Pod root URI (e.g., https://example.com/alice/)
24
25
  * @param {string} options.issuer - OIDC issuer URI
26
+ * @param {object} [options.ownerVm] - Optional verificationMethod
27
+ * entry for an owner-held key (Phase 2 of #437 / #443). Build via
28
+ * `src/keys/provision.js#buildOwnerVerificationMethod`.
29
+ *
30
+ * **Fresh-pod-only when `ownerVm` is set.** The helper unconditionally
31
+ * overwrites `verificationMethod`, `authentication`, and
32
+ * `assertionMethod` with single-element arrays referencing this VM.
33
+ * That's correct for the only current caller (fresh pod creation,
34
+ * nothing to overwrite), but a future "rotate-keys" / re-provisioning
35
+ * command using this helper to regenerate an existing profile would
36
+ * silently drop any VMs / proof-purpose references the operator
37
+ * added by hand. Either pass the existing profile through a merge
38
+ * step before calling this, or treat the helper as fresh-pod-only.
39
+ * See #444 review.
40
+ *
25
41
  * @returns {object} JSON-LD profile data
26
42
  */
27
- export function generateProfileJsonLd({ webId, name, podUri, issuer }) {
43
+ export function generateProfileJsonLd({ webId, name, podUri, issuer, ownerVm = null }) {
28
44
  const pod = podUri.endsWith('/') ? podUri : podUri + '/';
29
45
  // Document URL is the WebID without its fragment; service entries use
30
46
  // fragment ids resolved against it.
@@ -114,7 +130,24 @@ export function generateProfileJsonLd({ webId, name, podUri, issuer }) {
114
130
  '@type': 'lws:OpenIdProvider',
115
131
  'serviceEndpoint': issuer
116
132
  }
117
- ]
133
+ ],
134
+ // Optional: a verificationMethod for an owner-held key, populated
135
+ // when the pod was created with `--provision-keys` (Phase 2 of
136
+ // #437 / #443). The VM lands the public side of the owner key
137
+ // into the profile so the existing LWS-CID verifier in
138
+ // src/auth/lws-cid.js can authenticate JWTs signed with the
139
+ // matching secret. Both `publicKeyMultibase` (CID v1.0
140
+ // conformance) and `publicKeyJwk` (LWS-CID compat) are emitted by
141
+ // src/keys/provision.js's buildOwnerVerificationMethod helper.
142
+ //
143
+ // The VM is also referenced from `authentication` and
144
+ // `assertionMethod` so the same key counts as an authentication
145
+ // factor without an app needing to PATCH those arrays separately.
146
+ ...(ownerVm && {
147
+ verificationMethod: [ownerVm],
148
+ authentication: [ownerVm['@id']],
149
+ assertionMethod: [ownerVm['@id']]
150
+ })
118
151
  };
119
152
  }
120
153
 
@@ -131,10 +164,15 @@ export function generateProfileJsonLd({ webId, name, podUri, issuer }) {
131
164
  * @param {string} options.name - Display name
132
165
  * @param {string} options.podUri - Pod root URI
133
166
  * @param {string} options.issuer - OIDC issuer URI
167
+ * @param {object} [options.ownerVm] - Optional verificationMethod entry
168
+ * for an owner-held key (Phase 2 of #437 / #443). When set, lands
169
+ * the VM in `verificationMethod` and references it from
170
+ * `authentication` + `assertionMethod`. Build via
171
+ * `src/keys/provision.js#buildOwnerVerificationMethod`.
134
172
  * @returns {object} JSON-LD profile document
135
173
  */
136
- export function generateProfile({ webId, name, podUri, issuer }) {
137
- return generateProfileJsonLd({ webId, name, podUri, issuer });
174
+ export function generateProfile({ webId, name, podUri, issuer, ownerVm = null }) {
175
+ return generateProfileJsonLd({ webId, name, podUri, issuer, ownerVm });
138
176
  }
139
177
 
140
178
  /**