javascript-solid-server 0.0.185 → 0.0.187

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,70 @@
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8">
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">
8
+ <style>
9
+ * { margin: 0; padding: 0; box-sizing: border-box; }
10
+ body {
11
+ font-family: Georgia, 'Times New Roman', serif;
12
+ background: #fafaf8;
13
+ color: #2c2c2c;
14
+ line-height: 1.7;
15
+ min-height: 100vh;
16
+ display: flex;
17
+ align-items: center;
18
+ justify-content: center;
19
+ padding: 2rem;
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; }
26
+ .btn {
27
+ display: inline-block;
28
+ padding: 0.6rem 1.2rem;
29
+ border-radius: 4px;
30
+ text-decoration: none;
31
+ font-family: Georgia, serif;
32
+ font-size: 0.95rem;
33
+ border: 1px solid transparent;
34
+ cursor: pointer;
35
+ transition: all 0.1s;
36
+ }
37
+ .btn-primary { background: #7c3aed; color: #fff; }
38
+ .btn-primary:hover { background: #6025c0; }
39
+ .btn-secondary { background: #fff; color: #2c2c2c; border-color: #ccc; }
40
+ .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
+ footer { margin-top: 2rem; padding-top: 1rem; border-top: 1px solid #ddd; color: #999; font-size: 0.8rem; text-align: center; }
46
+ 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; }
49
+ </style>
50
+ </head>
51
+ <body>
52
+ <div class="container">
53
+ <h1>{{heading}}</h1>
54
+ <div class="subtitle">{{subtitle}}</div>
55
+ <p>{{description}}</p>
56
+
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>
63
+ </div>
64
+
65
+ <footer>
66
+ Powered by <a href="https://jss.live">JSS</a>
67
+ </footer>
68
+ </div>
69
+ </body>
70
+ </html>
@@ -0,0 +1,173 @@
1
+ /**
2
+ * Server-root landing page.
3
+ *
4
+ * Renders src/ui/server-root.html with runtime values, and seeds
5
+ * DATA_ROOT/index.html + DATA_ROOT/.acl on first start (skip-if-exists,
6
+ * so operator customisation is preserved).
7
+ *
8
+ * See issue #276.
9
+ */
10
+
11
+ import { readFileSync } from 'fs';
12
+ import { fileURLToPath } from 'url';
13
+ import { dirname, join } from 'path';
14
+ import * as storage from '../storage/filesystem.js';
15
+ import { generatePublicReadAcl, serializeAcl } from '../wac/parser.js';
16
+
17
+ const __dirname = dirname(fileURLToPath(import.meta.url));
18
+ const TEMPLATE_PATH = join(__dirname, 'server-root.html');
19
+
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.
41
+ */
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>`;
52
+ }
53
+
54
+ /**
55
+ * Render the landing page as an HTML string.
56
+ *
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
64
+ */
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;');
112
+ }
113
+
114
+
115
+ /**
116
+ * Seed DATA_ROOT/index.html, DATA_ROOT/.acl and DATA_ROOT/index.html.acl
117
+ * if they don't already exist. Operator's own files are never overwritten.
118
+ *
119
+ * Default ACL: public read. No write access — the operator edits
120
+ * /index.html on disk, not via the web.
121
+ *
122
+ * If the HTML write fails (permissions, full disk, read-only DATA_ROOT),
123
+ * ACL seeding is aborted to avoid leaving the server with a public-read
124
+ * root ACL and no index page.
125
+ *
126
+ * @param {object} ctx - Same context passed to renderServerRoot
127
+ * @returns {Promise<{seededHtml: boolean, seededAcl: boolean, seededPageAcl: boolean}>}
128
+ */
129
+ export async function seedServerRoot(ctx = {}) {
130
+ let seededHtml = false;
131
+ let seededAcl = false;
132
+ let seededPageAcl = false;
133
+
134
+ // Seed /index.html if operator hasn't written one.
135
+ if (!(await storage.exists('/index.html'))) {
136
+ const html = renderServerRoot(ctx);
137
+ const ok = await storage.write('/index.html', html);
138
+ if (!ok) {
139
+ // Don't proceed with ACLs if the page itself failed to write —
140
+ // leaves us in a consistent unchanged state.
141
+ return { seededHtml: false, seededAcl: false, seededPageAcl: false };
142
+ }
143
+ seededHtml = true;
144
+ }
145
+
146
+ // Seed /.acl if one doesn't already exist. Public read on the container
147
+ // itself — so GET / serves the landing page. Independent of index.html.
148
+ //
149
+ // Use './' (relative to the .acl's own URL) rather than '/' (the
150
+ // origin root). The two coincide when JSS is mounted at the origin
151
+ // root, but only the relative form survives reverse-proxy mounts at
152
+ // a path prefix (e.g. https://example/jss/). This matches the
153
+ // pattern used by createPodStructure / createRootPodStructure since
154
+ // #428 / #430.
155
+ //
156
+ // (createRootPodStructure in single-user mode writes its own ACL and
157
+ // runs in a later hook, which will overwrite this if needed.)
158
+ if (!(await storage.exists('/.acl'))) {
159
+ const ok = await storage.write('/.acl', serializeAcl(generatePublicReadAcl('./')));
160
+ if (ok) seededAcl = true;
161
+ }
162
+
163
+ // Dedicated ACL for the landing page itself — public read. The container
164
+ // ACL above has no acl:default (we don't want to implicitly publish all
165
+ // children), so /index.html needs its own rule when fetched directly.
166
+ // Same relative-form rationale as above.
167
+ if (!(await storage.exists('/index.html.acl'))) {
168
+ const ok = await storage.write('/index.html.acl', serializeAcl(generatePublicReadAcl('./index.html')));
169
+ if (ok) seededPageAcl = true;
170
+ }
171
+
172
+ return { seededHtml, seededAcl, seededPageAcl };
173
+ }
package/src/wac/parser.js CHANGED
@@ -210,9 +210,44 @@ function normalizeMode(mode) {
210
210
  return modeMap[mode] || mode;
211
211
  }
212
212
 
213
+ /**
214
+ * Express an absolute owner WebID as a path relative to a given .acl
215
+ * file's container, so the in-ACL `acl:agent` reference is host-portable.
216
+ * The parser resolves the relative IRI against the .acl URL at check
217
+ * time. See #430.
218
+ *
219
+ * If the WebID isn't hosted under this pod (foreign owner), the absolute
220
+ * URI is returned unchanged — there's no in-pod path to resolve to. This
221
+ * also means the helper degrades gracefully for any current or future
222
+ * profile layout (modern `profile/card.jsonld#me`, legacy `profile/card#me`,
223
+ * single-file `me#me`, etc.) — whatever path the WebID actually has under
224
+ * the pod is what gets emitted.
225
+ *
226
+ * @param {string} webId - Owner WebID, typically absolute.
227
+ * @param {string} podUri - Pod root URI (must end with `/`).
228
+ * @param {string} aclBaseInPod - The .acl file's container, expressed
229
+ * relative to the pod root, e.g. `''` for `<pod>/.acl`, `'private/'`
230
+ * for `<pod>/private/.acl`, `'settings/'` for the resource ACL
231
+ * `<pod>/settings/publicTypeIndex.jsonld.acl`.
232
+ * @returns {string} Relative IRI for use as `acl:agent`, or the original
233
+ * absolute WebID if it isn't hosted under `podUri`.
234
+ */
235
+ export function relativizeOwnerWebId(webId, podUri, aclBaseInPod = '') {
236
+ if (typeof webId !== 'string' || !webId) return webId;
237
+ if (typeof podUri !== 'string' || !podUri) return webId;
238
+ if (!webId.startsWith(podUri)) return webId;
239
+ const tail = webId.slice(podUri.length);
240
+ const depth = aclBaseInPod ? aclBaseInPod.split('/').filter(Boolean).length : 0;
241
+ const ups = depth === 0 ? './' : '../'.repeat(depth);
242
+ return ups + tail;
243
+ }
244
+
213
245
  /**
214
246
  * Generate a default public read ACL
215
- * @param {string} resourceUrl - URL of the resource
247
+ * @param {string} resourceUrl - URL of the resource. May be relative (e.g.
248
+ * './' for the .acl's own container) — the parser resolves it against
249
+ * the .acl's URL at check time, which keeps the document portable across
250
+ * hostnames. See #428.
216
251
  * @returns {object} JSON-LD ACL document
217
252
  */
218
253
  export function generatePublicReadAcl(resourceUrl) {
@@ -237,8 +272,12 @@ export function generatePublicReadAcl(resourceUrl) {
237
272
 
238
273
  /**
239
274
  * Generate a full owner ACL (owner has full control, public read)
240
- * @param {string} resourceUrl - URL of the resource
241
- * @param {string} ownerWebId - WebID of the owner
275
+ * @param {string} resourceUrl - URL of the resource. May be relative (see
276
+ * `generatePublicReadAcl`).
277
+ * @param {string} ownerWebId - WebID of the owner. May also be relative
278
+ * (e.g. './profile/card.jsonld#me' for an in-pod owner) — the parser
279
+ * resolves it against the .acl URL at check time. The profile document
280
+ * itself still publishes the absolute WebID. See #430.
242
281
  * @param {boolean} isContainer - Whether this is a container
243
282
  * @returns {object} JSON-LD ACL document
244
283
  */
@@ -285,8 +324,10 @@ export function generateOwnerAcl(resourceUrl, ownerWebId, isContainer = false) {
285
324
 
286
325
  /**
287
326
  * Generate a private ACL (owner only, no public access)
288
- * @param {string} resourceUrl - URL of the resource
289
- * @param {string} ownerWebId - WebID of the owner
327
+ * @param {string} resourceUrl - URL of the resource (may be relative — see
328
+ * `generatePublicReadAcl`).
329
+ * @param {string} ownerWebId - WebID of the owner (may be relative — see
330
+ * `generateOwnerAcl`).
290
331
  * @param {boolean} isContainer - Whether this is a container
291
332
  * @returns {object} JSON-LD ACL document
292
333
  */
@@ -318,8 +359,8 @@ export function generatePrivateAcl(resourceUrl, ownerWebId, isContainer = true)
318
359
 
319
360
  /**
320
361
  * Generate an inbox ACL (owner full control, public append)
321
- * @param {string} resourceUrl - URL of the inbox
322
- * @param {string} ownerWebId - WebID of the owner
362
+ * @param {string} resourceUrl - URL of the inbox (may be relative).
363
+ * @param {string} ownerWebId - WebID of the owner (may be relative).
323
364
  * @returns {object} JSON-LD ACL document
324
365
  */
325
366
  export function generateInboxAcl(resourceUrl, ownerWebId) {
@@ -358,8 +399,8 @@ export function generateInboxAcl(resourceUrl, ownerWebId) {
358
399
  /**
359
400
  * Generate a public folder ACL (owner full control, public read with inheritance)
360
401
  * Used for /public/ folders where content should be publicly readable
361
- * @param {string} resourceUrl - URL of the folder
362
- * @param {string} ownerWebId - WebID of the owner
402
+ * @param {string} resourceUrl - URL of the folder (may be relative).
403
+ * @param {string} ownerWebId - WebID of the owner (may be relative).
363
404
  * @returns {object} JSON-LD ACL document
364
405
  */
365
406
  export function generatePublicFolderAcl(resourceUrl, ownerWebId) {
@@ -81,3 +81,85 @@ describe('registerErrorHandler (#312)', () => {
81
81
  assert.strictEqual(unhandled.length, 0, '4xx must not produce a 5xx stack log');
82
82
  });
83
83
  });
84
+
85
+ // #376: Fastify-internal errors that fire BEFORE any user hook
86
+ // runs (notably FST_ERR_BAD_URL on malformed percent-encoding)
87
+ // previously bypassed every CORS-injecting handler in JSS, leaving
88
+ // the 400 response with no Access-Control-Allow-* headers — browsers
89
+ // surfaced the response as a CORS error instead of the real status.
90
+ // The fix uses Fastify's `frameworkErrors` option in createServer
91
+ // to attach the full CORS header set on EVERY framework-error
92
+ // response (matching the rest of the server, where the global
93
+ // onRequest hook sets CORS unconditionally). Allow-Origin mirrors
94
+ // the request's `Origin` if present, otherwise defaults to `*`.
95
+ describe('frameworkErrors injects CORS headers on FST_ERR_BAD_URL (#376)', () => {
96
+ let server;
97
+ let baseUrl;
98
+
99
+ before(async () => {
100
+ const { createServer } = await import('../src/server.js');
101
+ server = createServer({ logger: false, forceCloseConnections: true });
102
+ await server.listen({ port: 0, host: '127.0.0.1' });
103
+ const addr = server.server.address();
104
+ baseUrl = `http://127.0.0.1:${addr.port}`;
105
+ });
106
+
107
+ after(async () => {
108
+ await server.close();
109
+ });
110
+
111
+ it('returns 400 with full CORS headers for a malformed-percent URL + Origin', async () => {
112
+ // `%g1` is the canonical FST_ERR_BAD_URL trigger — `g` isn't a
113
+ // valid hex digit, so the percent-decode bails before any route
114
+ // handler is even resolved.
115
+ const r = await fetch(`${baseUrl}/foo%g1`, {
116
+ headers: { Origin: 'https://example.com' },
117
+ });
118
+ assert.strictEqual(r.status, 400);
119
+ // CORS headers are what was missing pre-fix. ACAO should mirror
120
+ // the request Origin (not `*`), since the request explicitly
121
+ // sent one — that's what getCorsHeaders does.
122
+ assert.strictEqual(r.headers.get('access-control-allow-origin'), 'https://example.com');
123
+ assert.match(r.headers.get('access-control-allow-methods') || '', /GET/);
124
+ assert.ok(r.headers.get('access-control-allow-headers'), 'ACAH must be set');
125
+ assert.ok(r.headers.get('access-control-expose-headers'), 'ACEH must be set');
126
+ // Body uses HTTP status text ("Bad Request"), not err.name
127
+ // ("FastifyError") — matches Fastify's default body shape so
128
+ // any pre-fix client parsing `error` keeps working.
129
+ const body = await r.json();
130
+ assert.strictEqual(body.error, 'Bad Request');
131
+ assert.strictEqual(body.code, 'FST_ERR_BAD_URL');
132
+ assert.strictEqual(body.statusCode, 400);
133
+ });
134
+
135
+ it('returns CORS headers (ACAO=*) and well-shaped JSON for the same bad URL without an Origin', async () => {
136
+ // Non-browser clients without an Origin still receive the full
137
+ // CORS header set — consistent with the rest of the server,
138
+ // where the global onRequest hook always sets CORS. ACAO
139
+ // defaults to `*` when no Origin was sent (per getCorsHeaders).
140
+ const r = await fetch(`${baseUrl}/foo%g1`);
141
+ assert.strictEqual(r.status, 400);
142
+ assert.strictEqual(r.headers.get('access-control-allow-origin'), '*');
143
+ assert.match(r.headers.get('access-control-allow-methods') || '', /GET/);
144
+ assert.ok(r.headers.get('access-control-allow-headers'), 'ACAH must be set');
145
+ const body = await r.json();
146
+ assert.strictEqual(body.error, 'Bad Request');
147
+ assert.strictEqual(body.code, 'FST_ERR_BAD_URL');
148
+ assert.strictEqual(body.statusCode, 400);
149
+ });
150
+
151
+ it('does NOT regress: a normal 404 still carries CORS via the wildcard handler', async () => {
152
+ // Belt-and-suspenders: the frameworkErrors hook shouldn't have
153
+ // displaced any existing CORS behavior on responses that go
154
+ // through the wildcard handler. Ask for a path that hits the
155
+ // LDP wildcard and 404s (no such resource), confirm CORS.
156
+ const r = await fetch(`${baseUrl}/nonexistent/deep/path`, {
157
+ headers: { Origin: 'https://example.com' },
158
+ });
159
+ // Could be 401 or 404 depending on auth defaults; in either case
160
+ // CORS must be present.
161
+ assert.ok([401, 404].includes(r.status), `expected 401 or 404, got ${r.status}`);
162
+ assert.ok(r.headers.get('access-control-allow-origin'),
163
+ 'ACAO must be set on the normal-handler error path too');
164
+ });
165
+ });
@@ -0,0 +1,192 @@
1
+ /**
2
+ * Server-root landing page seed (#276).
3
+ */
4
+
5
+ import { describe, it, before, after } from 'node:test';
6
+ import assert from 'node:assert';
7
+ import fs from 'fs-extra';
8
+ import { createServer } from '../src/server.js';
9
+ import { renderServerRoot } from '../src/ui/server-root.js';
10
+ import { startTestServer, stopTestServer, request, assertStatus } from './helpers.js';
11
+
12
+ describe('Server-root landing page', () => {
13
+ before(async () => {
14
+ await startTestServer();
15
+ });
16
+
17
+ after(async () => {
18
+ await stopTestServer();
19
+ });
20
+
21
+ it('seeds /index.html so GET / serves HTML', async () => {
22
+ const res = await request('/', { headers: { Accept: 'text/html' } });
23
+ assertStatus(res, 200);
24
+ const body = await res.text();
25
+ assert.match(body, /<title>JSS<\/title>/);
26
+ assert.match(body, /A personal data server/);
27
+ });
28
+
29
+ it('landing page is publicly readable (no auth required)', async () => {
30
+ const res = await request('/index.html');
31
+ assertStatus(res, 200);
32
+ });
33
+
34
+ // Portability regression: the seeded ACLs must use './' (resolved
35
+ // against the .acl's own URL) rather than '/' (the origin root).
36
+ // The two coincide when JSS sits at the origin root, so a request
37
+ // smoke-test would pass either way; only direct inspection of the
38
+ // serialized accessTo catches a regression to the absolute form.
39
+ // Without this, JSS mounted under a reverse-proxy path prefix would
40
+ // see the seeded ACL match the origin root rather than the prefix.
41
+ it('seeded ACLs use relative resourceUrl ("./" / "./index.html"), not absolute paths', async () => {
42
+ const rootAcl = JSON.parse(await fs.readFile('./data/.acl', 'utf8'));
43
+ const pageAcl = JSON.parse(await fs.readFile('./data/index.html.acl', 'utf8'));
44
+ const rootAccessTo = rootAcl['@graph'][0]['acl:accessTo']['@id'];
45
+ const pageAccessTo = pageAcl['@graph'][0]['acl:accessTo']['@id'];
46
+ assert.strictEqual(rootAccessTo, './',
47
+ `Expected /.acl accessTo to be relative './', got '${rootAccessTo}'`);
48
+ assert.strictEqual(pageAccessTo, './index.html',
49
+ `Expected /index.html.acl accessTo to be relative './index.html', got '${pageAccessTo}'`);
50
+ });
51
+ });
52
+
53
+ // Operator's existing /index.html is preserved — dedicated server + data dir.
54
+ describe('Server-root landing — operator override', () => {
55
+ let server;
56
+ let baseUrl;
57
+ let savedDataRoot;
58
+ const DATA_DIR = './test-data-server-root-override';
59
+ const CUSTOM_HTML = '<!doctype html><html><body>my custom page</body></html>';
60
+
61
+ before(async () => {
62
+ // Capture process.env.DATA_ROOT — createServer mutates it when options.root
63
+ // is provided. Restore in after() to avoid cross-test interference with
64
+ // suites that rely on the default ./data dir.
65
+ savedDataRoot = process.env.DATA_ROOT;
66
+
67
+ await fs.remove(DATA_DIR);
68
+ await fs.ensureDir(DATA_DIR);
69
+ await fs.writeFile(`${DATA_DIR}/index.html`, CUSTOM_HTML);
70
+
71
+ server = createServer({
72
+ logger: false,
73
+ root: DATA_DIR,
74
+ forceCloseConnections: true,
75
+ });
76
+ await server.listen({ port: 0, host: '127.0.0.1' });
77
+ baseUrl = `http://127.0.0.1:${server.server.address().port}`;
78
+ });
79
+
80
+ after(async () => {
81
+ await server.close();
82
+ await fs.remove(DATA_DIR);
83
+ if (savedDataRoot === undefined) delete process.env.DATA_ROOT;
84
+ else process.env.DATA_ROOT = savedDataRoot;
85
+ });
86
+
87
+ it('does not overwrite operator-provided /index.html', async () => {
88
+ const current = await fs.readFile(`${DATA_DIR}/index.html`, 'utf8');
89
+ assert.strictEqual(current, CUSTOM_HTML);
90
+ });
91
+
92
+ it('GET / serves operator custom page', async () => {
93
+ const res = await fetch(`${baseUrl}/`, { headers: { Accept: 'text/html' } });
94
+ assert.strictEqual(res.status, 200);
95
+ const body = await res.text();
96
+ assert.match(body, /my custom page/);
97
+ });
98
+ });
99
+
100
+ describe('renderServerRoot — mode-specific output', () => {
101
+ it('multi-user + IDP shows Create a pod + Sign in', () => {
102
+ const html = renderServerRoot({ version: '1.0.0', singleUser: false, idp: true });
103
+ assert.match(html, /Create a pod/);
104
+ assert.match(html, /href="\/idp\/register"/);
105
+ assert.match(html, /href="\/idp"/);
106
+ assert.match(html, /Sign in/);
107
+ });
108
+
109
+ it('single-user + IDP shows Sign in only (no Create a pod)', () => {
110
+ const html = renderServerRoot({ version: '1.0.0', singleUser: true, idp: true, singleUserName: 'alice' });
111
+ assert.doesNotMatch(html, /Create a pod/);
112
+ assert.match(html, /Sign in/);
113
+ });
114
+
115
+ it('multi-user without IDP shows only the Docs link', () => {
116
+ const html = renderServerRoot({ version: '1.0.0', singleUser: false, idp: false });
117
+ assert.doesNotMatch(html, /Create a pod/);
118
+ assert.doesNotMatch(html, /Sign in/);
119
+ assert.match(html, /Docs/);
120
+ });
121
+
122
+ it('single-user subtitle includes the pod name when provided', () => {
123
+ const html = renderServerRoot({ version: '1.0.0', singleUser: true, idp: false, singleUserName: 'alice' });
124
+ assert.match(html, /Personal pod for alice/);
125
+ });
126
+
127
+ it('lists enabled features', () => {
128
+ const html = renderServerRoot({
129
+ version: '1.0.0',
130
+ singleUser: false,
131
+ idp: true,
132
+ enabled: { idp: true, nostr: true, webrtc: true, terminal: true }
133
+ });
134
+ assert.match(html, /<span>idp<\/span>/);
135
+ assert.match(html, /<span>nostr<\/span>/);
136
+ assert.match(html, /<span>webrtc<\/span>/);
137
+ assert.match(html, /<span>terminal<\/span>/);
138
+ });
139
+
140
+ it('interpolates version', () => {
141
+ const html = renderServerRoot({ version: '9.9.9' });
142
+ assert.match(html, /<code>9\.9\.9<\/code>/);
143
+ });
144
+
145
+ it('escapes version to prevent injection', () => {
146
+ const html = renderServerRoot({ version: '<script>alert(1)</script>' });
147
+ assert.doesNotMatch(html, /<script>alert\(1\)<\/script>/);
148
+ assert.match(html, /&lt;script&gt;/);
149
+ });
150
+
151
+ // Regression for token re-scanning (#433 review thread): if the
152
+ // renderer ran a chain of sequential .replace() calls, a value
153
+ // containing a literal `{{actions}}` would land inside the subtitle
154
+ // and then get expanded by the later `.replace(/{{actions}}/g, ...)`,
155
+ // letting any pod owner inject other template fragments via their
156
+ // singleUserName. The single-pass substitution prevents that.
157
+ it('does not re-scan substituted values for further template tokens', () => {
158
+ const html = renderServerRoot({
159
+ version: '1.0.0',
160
+ singleUser: true,
161
+ idp: false,
162
+ // The HTML escape only touches & < > " — { } pass through, so the
163
+ // token would land in the output verbatim if the substitution were
164
+ // multi-pass.
165
+ singleUserName: 'evil{{actions}}name'
166
+ });
167
+ assert.match(html, /Personal pod for evil\{\{actions\}\}name/,
168
+ 'singleUserName containing a template token should appear as plain text, not be re-templated');
169
+ // Sanity: the real {{actions}} slot is still resolved (Docs link is always present).
170
+ assert.match(html, /href="https:\/\/javascriptsolidserver\.github\.io\/docs/);
171
+ });
172
+
173
+ // Regression for the `$&` substitution gotcha (#433): a string used as
174
+ // the second argument of String.prototype.replace interprets `$&`,
175
+ // `$1`, etc. as substitution patterns. Interpolated values can contain
176
+ // `$` (notably a singleUserName), so the renderer uses the function
177
+ // form of replace instead. Asserting the literal `$&` survives the
178
+ // round-trip would mean it survived as plain text.
179
+ it('preserves $-patterns in singleUserName instead of treating them as replacement specials', () => {
180
+ const html = renderServerRoot({
181
+ version: '1.0.0',
182
+ singleUser: true,
183
+ idp: false,
184
+ singleUserName: 'foo$&bar'
185
+ });
186
+ // The HTML escape converts `&` to `&amp;`; the rest must stay verbatim,
187
+ // not be replaced by the matched template token.
188
+ assert.match(html, /Personal pod for foo\$&amp;bar/,
189
+ 'singleUserName containing "$&" should land as-is, not trigger String.replace substitution');
190
+ assert.doesNotMatch(html, /\{\{subtitle\}\}/, 'subtitle token should be fully consumed');
191
+ });
192
+ });