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.
@@ -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);
@@ -3,68 +3,129 @@
3
3
  <head>
4
4
  <meta charset="UTF-8">
5
5
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
- <title>{{title}}</title>
7
- <meta name="description" content="A personal data server powered by JSS">
6
+ <title>JSS Solid pod</title>
7
+ <meta name="description" content="A Solid pod server powered by JSS">
8
8
  <style>
9
9
  * { margin: 0; padding: 0; box-sizing: border-box; }
10
10
  body {
11
- font-family: Georgia, 'Times New Roman', serif;
11
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif;
12
12
  background: #fafaf8;
13
13
  color: #2c2c2c;
14
- line-height: 1.7;
14
+ line-height: 1.6;
15
15
  min-height: 100vh;
16
16
  display: flex;
17
17
  align-items: center;
18
18
  justify-content: center;
19
19
  padding: 2rem;
20
20
  }
21
- .container { max-width: 560px; width: 100%; }
22
- h1 { font-size: 2.2rem; font-weight: 400; margin-bottom: 0.25rem; }
23
- .subtitle { color: #666; font-size: 1.05rem; margin-bottom: 2rem; padding-bottom: 1.5rem; border-bottom: 1px solid #ddd; }
24
- p { margin-bottom: 1.25rem; }
25
- .actions { display: flex; gap: 0.75rem; margin: 1.5rem 0 2rem; flex-wrap: wrap; }
21
+ .container { max-width: 600px; width: 100%; }
22
+ h1 { font-size: 2.2rem; font-weight: 500; margin-bottom: 1rem; }
23
+ .lede { font-size: 1.05rem; margin-bottom: 1rem; color: #2c2c2c; }
24
+ .lede a { color: #2c2c2c; text-decoration: none; border-bottom: 1px dashed #aaa; }
25
+ .lede a:hover { border-bottom-color: #2c2c2c; }
26
+ .explainer { color: #666; font-size: 0.95rem; margin-bottom: 2rem; padding-bottom: 1.5rem; border-bottom: 1px solid #ddd; }
27
+ .actions { display: flex; gap: 0.75rem; margin: 0 0 2rem; flex-wrap: wrap; }
26
28
  .btn {
27
29
  display: inline-block;
28
30
  padding: 0.6rem 1.2rem;
29
31
  border-radius: 4px;
30
32
  text-decoration: none;
31
- font-family: Georgia, serif;
32
33
  font-size: 0.95rem;
33
34
  border: 1px solid transparent;
34
35
  cursor: pointer;
35
- transition: all 0.1s;
36
+ transition: background 0.1s, border-color 0.1s;
36
37
  }
37
- .btn-primary { background: #7c3aed; color: #fff; }
38
- .btn-primary:hover { background: #6025c0; }
38
+ /* The .btn { display: inline-block } above otherwise overrides the
39
+ browser's UA `[hidden] { display: none }` rule (equal specificity,
40
+ author rule wins because it's later in the cascade). Without this,
41
+ the Sign up / Sign in buttons would flash visible before the HEAD
42
+ probe runs. !important keeps the [hidden] attribute authoritative. */
43
+ [hidden] { display: none !important; }
44
+ .btn-primary { background: #2c2c2c; color: #fff; }
45
+ .btn-primary:hover { background: #000; }
39
46
  .btn-secondary { background: #fff; color: #2c2c2c; border-color: #ccc; }
40
47
  .btn-secondary:hover { background: #f0efeb; }
41
- .info { background: #f5f4f0; border-radius: 4px; padding: 1rem; font-size: 0.85rem; color: #666; margin-top: 1.5rem; }
42
- .info .row { display: flex; justify-content: space-between; padding: 0.2rem 0; }
43
- .info .label { color: #999; }
44
- .info code { font-family: 'SFMono-Regular', Consolas, monospace; font-size: 0.9em; color: #555; }
45
48
  footer { margin-top: 2rem; padding-top: 1rem; border-top: 1px solid #ddd; color: #999; font-size: 0.8rem; text-align: center; }
46
49
  footer a { color: #888; }
47
- .features { font-size: 0.85rem; color: #666; margin-top: 0.5rem; }
48
- .features span { display: inline-block; background: #eee; padding: 0.15rem 0.5rem; border-radius: 3px; margin-right: 0.3rem; margin-bottom: 0.3rem; font-family: 'SFMono-Regular', Consolas, monospace; font-size: 0.8rem; }
50
+ footer small { display: block; margin-top: 0.5rem; }
51
+ footer code { font-family: "SFMono-Regular", Consolas, "Liberation Mono", Menlo, monospace; }
49
52
  </style>
50
53
  </head>
51
54
  <body>
52
55
  <div class="container">
53
- <h1>{{heading}}</h1>
54
- <div class="subtitle">{{subtitle}}</div>
55
- <p>{{description}}</p>
56
+ <h1>Welcome</h1>
57
+ <!-- The fallback href="./" is page-relative so it stays inside any
58
+ reverse-proxy mount even if the script below doesn't run
59
+ (CSP, JS disabled). The script will replace it with the
60
+ absolute URL of the document base on load. -->
61
+ <p class="lede">Your JSS Solid pod is running at <a id="server-url" href="./">this server</a>.</p>
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>
56
63
 
57
- {{actions}}
58
-
59
- <div class="info">
60
- <div class="row"><span class="label">Version</span><code>{{version}}</code></div>
61
- <div class="row"><span class="label">Mode</span><code>{{mode}}</code></div>
62
- <div class="features">{{features}}</div>
64
+ <div class="actions">
65
+ <a href="https://jss.live/docs/getting-started/first-run" class="btn btn-primary">Get started →</a>
66
+ <!-- IdP links are written page-relative (no leading slash) so they
67
+ resolve against document base, surviving reverse-proxy mounts
68
+ at a path prefix (e.g. https://example/jss/). Origin-root
69
+ absolute paths like /idp would jump out of the mount point.
70
+ Same rationale as the relative ACL targets from #428. -->
71
+ <a href="./idp/register" class="btn btn-secondary" data-cond="register" hidden>Sign up</a>
72
+ <a href="./idp" class="btn btn-secondary" data-cond="login" hidden>Sign in</a>
63
73
  </div>
64
74
 
75
+ <!-- Version, mode, and enabled-feature pills used to live here.
76
+ All three would go stale on the next mode change or upgrade
77
+ because the seed is skip-if-exists. The CLI banner already
78
+ lists them at startup. Surface them via a runtime probe in
79
+ a follow-up if needed. See #435. -->
80
+
81
+
65
82
  <footer>
66
- Powered by <a href="https://jss.live">JSS</a>
83
+ Powered by <a href="https://jss.live">JSS</a> · <a href="https://github.com/JavaScriptSolidServer/JavaScriptSolidServer">GitHub</a>
84
+ <small>Customise this page: edit <code>/index.html</code> in your data dir</small>
67
85
  </footer>
68
86
  </div>
87
+
88
+ <script>
89
+ // Render the live server URL the visitor actually used. Adapts to
90
+ // whichever hostname/port they hit (localhost / 127.0.0.1 / LAN-IP
91
+ // / public domain) and — importantly — preserves any reverse-proxy
92
+ // path prefix the server is mounted under. `window.location.origin`
93
+ // alone would drop a /jss/ mount and display the proxy origin
94
+ // instead. `new URL('./', window.location.href)` resolves to the
95
+ // current document's directory, which is the JSS server root.
96
+ (function () {
97
+ var el = document.getElementById('server-url');
98
+ if (!el) return;
99
+ var base = new URL('./', window.location.href).href;
100
+ el.textContent = base;
101
+ el.href = base;
102
+ })();
103
+
104
+ // HEAD-adaptive Sign up / Sign in. Reveals each button based on what
105
+ // the IDP currently exposes — the same seeded HTML works for
106
+ // single-user, multi-user-with-IDP, and no-IDP modes without
107
+ // regeneration on mode change.
108
+ // 200 → registration open: show both Sign up and Sign in
109
+ // 403 → IDP enabled but registration disabled (single-user mode):
110
+ // Sign in only
111
+ // 404 / network error → no IDP: hide both
112
+ (function () {
113
+ // Relative URL resolves against document base, same as the
114
+ // anchor hrefs above — preserves the path-prefix mount point.
115
+ fetch('./idp/register', { method: 'HEAD', cache: 'no-store' })
116
+ .then(function (res) {
117
+ var register = document.querySelector('[data-cond="register"]');
118
+ var login = document.querySelector('[data-cond="login"]');
119
+ if (res.status === 200) {
120
+ if (register) register.hidden = false;
121
+ if (login) login.hidden = false;
122
+ } else if (res.status === 403) {
123
+ if (login) login.hidden = false;
124
+ }
125
+ // 404 / other / network error: leave both hidden
126
+ })
127
+ .catch(function () { /* network error: leave both hidden */ });
128
+ })();
129
+ </script>
69
130
  </body>
70
131
  </html>
@@ -18,100 +18,49 @@ const __dirname = dirname(fileURLToPath(import.meta.url));
18
18
  const TEMPLATE_PATH = join(__dirname, 'server-root.html');
19
19
 
20
20
  /**
21
- * Collect the list of enabled features for display on the landing page.
22
- */
23
- function listFeatures(options = {}) {
24
- const f = [];
25
- if (options.idp) f.push('idp');
26
- if (options.nostr) f.push('nostr');
27
- if (options.webrtc) f.push('webrtc');
28
- if (options.activitypub) f.push('activitypub');
29
- if (options.git) f.push('git');
30
- if (options.pay) f.push('payments');
31
- if (options.notifications) f.push('notifications');
32
- if (options.mashlib) f.push('mashlib');
33
- if (options.mongo) f.push('mongo');
34
- if (options.tunnel) f.push('tunnel');
35
- if (options.terminal) f.push('terminal');
36
- return f;
37
- }
38
-
39
- /**
40
- * Build an HTML snippet of action buttons based on server mode.
21
+ * Read the landing page template and return it as an HTML string.
22
+ *
23
+ * The seeded HTML is fully static — no template substitution. Anything
24
+ * we used to render in (mode, enabled features, version) would have
25
+ * gone stale on the next mode change or upgrade because the seed is
26
+ * skip-if-exists. They've been dropped from the template; the CLI
27
+ * banner lists them at startup, and Sign up / Sign in adapt at load
28
+ * time via the inline HEAD probe (see decideRevealForRegisterStatus
29
+ * below for the matrix that the inline script implements).
30
+ *
31
+ * The function still takes (and ignores) a `_ctx` arg for forward
32
+ * compatibility — callers (seedServerRoot, server.js) pass one.
33
+ *
34
+ * @param {object} [_ctx] - Reserved; currently unused.
35
+ * @returns {string} HTML
41
36
  */
42
- function renderActions({ singleUser, idp }) {
43
- const buttons = [];
44
- if (!singleUser && idp) {
45
- buttons.push('<a href="/idp/register" class="btn btn-primary">Create a pod</a>');
46
- buttons.push('<a href="/idp" class="btn btn-secondary">Sign in</a>');
47
- } else if (singleUser && idp) {
48
- buttons.push('<a href="/idp" class="btn btn-primary">Sign in</a>');
49
- }
50
- buttons.push('<a href="https://javascriptsolidserver.github.io/docs/" class="btn btn-secondary">Docs</a>');
51
- return `<div class="actions">${buttons.join('\n ')}</div>`;
37
+ // eslint-disable-next-line no-unused-vars
38
+ export function renderServerRoot(_ctx = {}) {
39
+ return readFileSync(TEMPLATE_PATH, 'utf8');
52
40
  }
53
41
 
54
42
  /**
55
- * Render the landing page as an HTML string.
43
+ * Decide which conditional buttons (Sign up, Sign in) to reveal based
44
+ * on the response status of `HEAD /idp/register`. Pure function so the
45
+ * 200 / 403 / 404 matrix can be unit-tested without DOM. The inline
46
+ * script in server-root.html implements the same matrix literally;
47
+ * keep them in sync.
56
48
  *
57
- * @param {object} ctx
58
- * @param {string} ctx.version - JSS version
59
- * @param {boolean} [ctx.singleUser]
60
- * @param {boolean} [ctx.idp]
61
- * @param {string} [ctx.singleUserName]
62
- * @param {object} [ctx.enabled] - Map of feature flags
63
- * @returns {string} HTML
49
+ * 200 → registration open: reveal both Sign up and Sign in
50
+ * 403 → IDP enabled but registration disabled (single-user mode):
51
+ * reveal Sign in only
52
+ * anything else (404, network error) → reveal neither (no IDP)
53
+ *
54
+ * @param {number|undefined} status - HTTP status code, or undefined for
55
+ * network error.
56
+ * @returns {{ register: boolean, login: boolean }}
64
57
  */
65
- export function renderServerRoot(ctx = {}) {
66
- const { version = 'unknown', singleUser = false, idp = false, singleUserName, enabled = {} } = ctx;
67
-
68
- const tpl = readFileSync(TEMPLATE_PATH, 'utf8');
69
- const mode = singleUser ? 'single-user' : 'multi-user';
70
- const features = listFeatures(enabled)
71
- .map(f => `<span>${f}</span>`)
72
- .join(' ');
73
-
74
- const heading = 'JSS';
75
- const subtitle = singleUser
76
- ? `Personal pod${singleUserName && singleUserName !== '/' ? ` for ${escape(singleUserName)}` : ''}`
77
- : 'A personal data server';
78
- const description = singleUser
79
- ? 'This server hosts a personal data pod. Apps come to the data rather than the other way around.'
80
- : 'This server hosts personal data pods on the web. Each pod is a space you own, with your own identity and access control.';
81
-
82
- // Single-pass token substitution. Sequential .replace() calls would
83
- // re-scan already-substituted values, so a `singleUserName` of e.g.
84
- // `{{actions}}` would land inside `subtitle`, then get expanded by
85
- // the later `.replace(/{{actions}}/g, …)` — letting a pod owner
86
- // inject other template fragments via their name. With a single
87
- // pass over the original template, each {{token}} is matched once
88
- // and replaced with its value; `$` inside any value is also harmless
89
- // because the function form of replace skips substitution patterns.
90
- // See #433 review thread.
91
- const values = {
92
- title: heading,
93
- heading,
94
- subtitle,
95
- description,
96
- actions: renderActions({ singleUser, idp }),
97
- version: escape(version),
98
- mode,
99
- features
100
- };
101
- return tpl.replace(/{{(\w+)}}/g, (match, key) =>
102
- Object.prototype.hasOwnProperty.call(values, key) ? values[key] : match
103
- );
104
- }
105
-
106
- function escape(s = '') {
107
- return String(s)
108
- .replace(/&/g, '&amp;')
109
- .replace(/</g, '&lt;')
110
- .replace(/>/g, '&gt;')
111
- .replace(/"/g, '&quot;');
58
+ export function decideRevealForRegisterStatus(status) {
59
+ if (status === 200) return { register: true, login: true };
60
+ if (status === 403) return { register: false, login: true };
61
+ return { register: false, login: false };
112
62
  }
113
63
 
114
-
115
64
  /**
116
65
  * Seed DATA_ROOT/index.html, DATA_ROOT/.acl and DATA_ROOT/index.html.acl
117
66
  * if they don't already exist. Operator's own files are never overwritten.
@@ -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
+ });