javascript-solid-server 0.0.186 → 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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "javascript-solid-server",
3
- "version": "0.0.186",
3
+ "version": "0.0.187",
4
4
  "description": "A minimal, fast Solid server",
5
5
  "main": "src/index.js",
6
6
  "type": "module",
package/src/server.js CHANGED
@@ -28,6 +28,7 @@ import { webrtcPlugin } from './webrtc/index.js';
28
28
  import { tunnelPlugin } from './tunnel/index.js';
29
29
  import { terminalPlugin } from './terminal/index.js';
30
30
  import { registerErrorHandler } from './utils/error-handler.js';
31
+ import { seedServerRoot } from './ui/server-root.js';
31
32
 
32
33
  const __dirname = dirname(fileURLToPath(import.meta.url));
33
34
 
@@ -762,6 +763,48 @@ export function createServer(options = {}) {
762
763
  fastify.options('/', handleOptions);
763
764
  fastify.post('/', writeRateLimit, handlePost);
764
765
 
766
+ // Server-root landing page: seed /index.html and a public-read /.acl
767
+ // on first start (skip-if-exists, so operator-provided files are
768
+ // preserved). See #433 / #276. Skipped in read-only deployments so
769
+ // startup never mutates DATA_ROOT.
770
+ if (!options.readOnly) {
771
+ fastify.addHook('onReady', async () => {
772
+ // A missing or unreadable package.json (some production bundles
773
+ // omit it) shouldn't block seeding; fall back to "unknown".
774
+ let version = 'unknown';
775
+ try {
776
+ const pkg = await readFile(join(__dirname, '..', 'package.json'), 'utf8');
777
+ ({ version } = JSON.parse(pkg));
778
+ } catch (err) {
779
+ fastify.log.warn({ err }, 'Failed to read package.json version; seeding server root with version=unknown');
780
+ }
781
+
782
+ try {
783
+ await seedServerRoot({
784
+ version,
785
+ singleUser,
786
+ idp: idpEnabled,
787
+ singleUserName,
788
+ enabled: {
789
+ idp: idpEnabled,
790
+ nostr: nostrEnabled,
791
+ webrtc: webrtcEnabled,
792
+ activitypub: activitypubEnabled,
793
+ git: gitEnabled,
794
+ pay: payEnabled,
795
+ notifications: notificationsEnabled,
796
+ mashlib: mashlibEnabled,
797
+ mongo: mongoEnabled,
798
+ tunnel: tunnelEnabled,
799
+ terminal: terminalEnabled
800
+ }
801
+ });
802
+ } catch (err) {
803
+ fastify.log.warn({ err }, 'Failed to seed server root');
804
+ }
805
+ });
806
+ }
807
+
765
808
  // Single-user mode: create pod on startup if it doesn't exist
766
809
  if (singleUser) {
767
810
  fastify.addHook('onReady', async () => {
@@ -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
+ }
@@ -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
+ });