-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathconfig.js
More file actions
462 lines (406 loc) · 13.4 KB
/
config.js
File metadata and controls
462 lines (406 loc) · 13.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
/**
* Configuration Loading
*
* Loads config from (in order of precedence):
* 1. CLI arguments (highest)
* 2. Environment variables (JSS_*)
* 3. Config file (config.json)
* 4. Defaults (lowest)
*/
import fs from 'fs-extra';
import path from 'path';
/**
* Default configuration values
*/
export const defaults = {
// Server
port: 4443,
host: '0.0.0.0',
root: './data',
// SSL
sslKey: null,
sslCert: null,
// Features
multiuser: true,
conneg: false,
notifications: false,
// Identity Provider
idp: false,
idpIssuer: null,
// Subdomain mode (XSS protection)
subdomains: false,
baseDomain: null,
// Mashlib data browser
mashlib: false,
mashlibCdn: false,
mashlibVersion: '2.0.0',
mashlibModule: false,
// Git HTTP backend
git: false,
// CORS proxy (#378) — pod-hosted, WAC-gated proxy for browser apps to
// fetch arbitrary upstreams that don't return CORS headers.
corsProxy: false,
corsProxyMaxBytes: 50 * 1024 * 1024, // 50 MB ceiling on upstream response size
corsProxyTimeoutMs: 30_000, // 30 s deadline for upstream to send headers (504 if exceeded). The timeout does not apply during body streaming — body size is capped by corsProxyMaxBytes; see follow-up for streaming-phase timeout.
corsProxyMaxRedirects: 5, // each redirect re-validated for SSRF
// Nostr relay
nostr: false,
nostrPath: '/relay',
nostrMaxEvents: 1000,
// WebRTC signaling
webrtc: false,
webrtcPath: '/.webrtc',
// Terminal (WebSocket shell access)
terminal: false,
// Tunnel (decentralized ngrok)
tunnel: false,
tunnelPath: '/.tunnel',
// ActivityPub federation
activitypub: false,
apUsername: 'me',
apDisplayName: null,
apSummary: null,
apNostrPubkey: null,
// Invite-only registration
inviteOnly: false,
// Single-user mode (personal pod server)
singleUser: false,
// null = root pod (mounted at server origin, WebID at
// /profile/card.jsonld#me). A string mounts the pod at /<name>/ —
// useful when more than one Solid identity coexists on the same
// origin, or when the operator wants the pre-#348 /me/ shape.
singleUserName: null,
// Initial IDP password seeded on first single-user pod creation. If
// unset and --idp is enabled, the server prompts on a TTY or logs a
// warning and continues startup on non-TTY (so the pod is created but
// is not yet loggable until a password is set).
singleUserPassword: null,
// Provision a Schnorr secp256k1 owner key on pod creation, written
// to <pod>/private/privkey.jsonld in W3C CID v1.0 Multikey format
// (Phase 1 of #437). Off by default — keys-on-disk is a security
// tradeoff and we want operators to opt in deliberately.
provisionKeys: false,
// WebID-TLS client certificate authentication
webidTls: false,
// Storage quota (bytes) - 50MB default
defaultQuota: 50 * 1024 * 1024,
// Public mode - skip WAC, allow unauthenticated access
public: false,
// Read-only mode - disable PUT/DELETE/PATCH
readOnly: false,
// Live reload - inject script to auto-refresh browser on file changes
liveReload: false,
// HTTP 402 paid access
pay: false,
payCost: 1,
payMempoolUrl: 'https://mempool.space/testnet4',
payAddress: null,
payToken: null,
payRate: 1,
payChains: null, // comma-separated chain IDs, e.g. "tbtc3,tbtc4"
// MongoDB-backed /db/ route
mongo: false,
mongoUrl: 'mongodb://localhost:27017',
mongoDatabase: 'solid',
// MCP (Model Context Protocol) server — pod as a tool surface for agents (#490)
mcp: false,
// Logging
logger: true,
quiet: false,
logLevel: 'info',
// Paths
configPath: './.jss',
};
/**
* Map of environment variable names to config keys
*/
const envMap = {
JSS_PORT: 'port',
JSS_HOST: 'host',
JSS_ROOT: 'root',
JSS_SSL_KEY: 'sslKey',
JSS_SSL_CERT: 'sslCert',
JSS_MULTIUSER: 'multiuser',
JSS_CONNEG: 'conneg',
JSS_NOTIFICATIONS: 'notifications',
JSS_QUIET: 'quiet',
JSS_LOG_LEVEL: 'logLevel',
JSS_CONFIG_PATH: 'configPath',
JSS_IDP: 'idp',
JSS_IDP_ISSUER: 'idpIssuer',
JSS_SUBDOMAINS: 'subdomains',
JSS_BASE_DOMAIN: 'baseDomain',
JSS_MASHLIB: 'mashlib',
JSS_MASHLIB_CDN: 'mashlibCdn',
JSS_MASHLIB_VERSION: 'mashlibVersion',
JSS_MASHLIB_MODULE: 'mashlibModule',
JSS_GIT: 'git',
JSS_CORS_PROXY: 'corsProxy',
JSS_CORS_PROXY_MAX_BYTES: 'corsProxyMaxBytes',
JSS_CORS_PROXY_TIMEOUT_MS: 'corsProxyTimeoutMs',
JSS_CORS_PROXY_MAX_REDIRECTS: 'corsProxyMaxRedirects',
JSS_NOSTR: 'nostr',
JSS_NOSTR_PATH: 'nostrPath',
JSS_NOSTR_MAX_EVENTS: 'nostrMaxEvents',
JSS_WEBRTC: 'webrtc',
JSS_WEBRTC_PATH: 'webrtcPath',
JSS_TERMINAL: 'terminal',
JSS_TUNNEL: 'tunnel',
JSS_TUNNEL_PATH: 'tunnelPath',
JSS_ACTIVITYPUB: 'activitypub',
JSS_AP_USERNAME: 'apUsername',
JSS_AP_DISPLAY_NAME: 'apDisplayName',
JSS_AP_SUMMARY: 'apSummary',
JSS_AP_NOSTR_PUBKEY: 'apNostrPubkey',
JSS_INVITE_ONLY: 'inviteOnly',
JSS_SINGLE_USER: 'singleUser',
JSS_SINGLE_USER_NAME: 'singleUserName',
JSS_SINGLE_USER_PASSWORD: 'singleUserPassword',
JSS_PROVISION_KEYS: 'provisionKeys',
JSS_WEBID_TLS: 'webidTls',
JSS_DEFAULT_QUOTA: 'defaultQuota',
JSS_PUBLIC: 'public',
JSS_READ_ONLY: 'readOnly',
JSS_LIVE_RELOAD: 'liveReload',
JSS_PAY: 'pay',
JSS_PAY_COST: 'payCost',
JSS_PAY_MEMPOOL_URL: 'payMempoolUrl',
JSS_PAY_ADDRESS: 'payAddress',
JSS_PAY_TOKEN: 'payToken',
JSS_PAY_RATE: 'payRate',
JSS_PAY_CHAINS: 'payChains',
JSS_MONGO: 'mongo',
JSS_MONGO_URL: 'mongoUrl',
JSS_MONGO_DATABASE: 'mongoDatabase',
JSS_MCP: 'mcp',
};
/**
* Parse a size string like "50MB" or "1GB" to bytes
*/
export function parseSize(str) {
const match = str.match(/^(\d+(?:\.\d+)?)\s*(B|KB|MB|GB|TB)?$/i);
if (!match) return parseInt(str, 10) || 0;
const num = parseFloat(match[1]);
const unit = (match[2] || 'B').toUpperCase();
const multipliers = { B: 1, KB: 1024, MB: 1024**2, GB: 1024**3, TB: 1024**4 };
return Math.floor(num * (multipliers[unit] || 1));
}
/**
* Config keys whose values are genuinely boolean. Only these get the
* "true"/"false" string coercion below — otherwise a user-supplied
* password (or any other string-valued option) like "true"/"false"
* would silently turn into a boolean and break downstream code (e.g.
* bcrypt hashing).
*/
const BOOLEAN_KEYS = new Set([
'ssl',
'conneg',
'subdomains',
'mashlib',
'mashlibCdn',
'git',
'corsProxy',
'nostr',
'webrtc',
'terminal',
'tunnel',
'activitypub',
'inviteOnly',
'multiuser',
'singleUser',
'provisionKeys',
'webidTls',
'public',
'readOnly',
'liveReload',
'pay',
'mongo',
'mcp',
'idp',
'notifications',
'logger',
'quiet'
]);
/**
* Parse a value from environment variable string
*/
function parseEnvValue(value, key) {
if (value === undefined) return undefined;
// Boolean values — only for known boolean keys; everything else
// stays a string so passwords / tokens / arbitrary text aren't
// silently coerced to booleans.
if (BOOLEAN_KEYS.has(key)) {
if (value.toLowerCase() === 'true') return true;
if (value.toLowerCase() === 'false') return false;
}
// Numeric values for known numeric keys
if ((key === 'port' ||
key === 'nostrMaxEvents' ||
key === 'payCost' ||
key === 'payRate' ||
key === 'corsProxyMaxBytes' ||
key === 'corsProxyTimeoutMs' ||
key === 'corsProxyMaxRedirects') && !isNaN(value)) {
return parseInt(value, 10);
}
// Size values (quota)
if (key === 'defaultQuota') {
return parseSize(value);
}
return value;
}
/**
* Load configuration from environment variables
*/
function loadEnvConfig() {
const config = {};
for (const [envVar, configKey] of Object.entries(envMap)) {
const value = process.env[envVar];
if (value !== undefined) {
config[configKey] = parseEnvValue(value, configKey);
}
}
return config;
}
/**
* Load configuration from a JSON file
*/
async function loadFileConfig(configFile) {
if (!configFile) return {};
try {
const fullPath = path.resolve(configFile);
if (await fs.pathExists(fullPath)) {
const content = await fs.readFile(fullPath, 'utf8');
return JSON.parse(content);
}
} catch (e) {
console.error(`Warning: Failed to load config file: ${e.message}`);
}
return {};
}
/**
* Merge configuration sources
* @param {object} cliOptions - Options from command line
* @param {string} configFile - Path to config file (optional)
* @returns {Promise<object>} Merged configuration
*/
export async function loadConfig(cliOptions = {}, configFile = null) {
// Load from file first
const fileConfig = await loadFileConfig(configFile || cliOptions.config);
// Load from environment
const envConfig = loadEnvConfig();
// Merge in order: defaults < file < env < cli
const config = {
...defaults,
...fileConfig,
...envConfig,
...filterUndefined(cliOptions),
};
// Derive additional settings
if (config.quiet) {
config.logger = false;
}
// Validate log level
const validLevels = ['fatal', 'error', 'warn', 'info', 'debug', 'trace'];
if (!validLevels.includes(config.logLevel)) {
console.warn(`Invalid log level '${config.logLevel}', falling back to 'info'. Valid levels: ${validLevels.join(', ')}`);
config.logLevel = 'info';
}
// Mashlib requires content negotiation for Turtle support
if (config.mashlib || config.mashlibCdn || config.mashlibModule) {
config.conneg = true;
}
// Single-user mode strongly implies the built-in IdP. Operators seeding
// a password for `me` on localhost almost always want the IdP enabled
// so clients can authenticate. Imply --idp unless the user explicitly
// disabled it from any config source — CLI, env, or config file (see #331).
if (config.singleUser && !config.idp) {
const idpExplicitlyDisabled =
cliOptions.idp === false ||
envConfig.idp === false ||
fileConfig.idp === false;
if (idpExplicitlyDisabled) {
// Respect the explicit disable. Warn only when there is no external
// --idp-issuer either: without the built-in IdP and without an
// external issuer, /.well-known/openid-configuration returns 404
// and clients fail with confusing OIDC discovery errors. If the
// operator pointed JSS at an external issuer, no footgun applies.
if (!config.idpIssuer) {
console.warn('⚠️ --single-user is enabled but --idp is disabled and no --idp-issuer is set. Clients won\'t be able to authenticate. Use --idp, or pass an external --idp-issuer.');
}
} else {
config.idp = true;
}
}
// Validate SSL config
if ((config.sslKey && !config.sslCert) || (!config.sslKey && config.sslCert)) {
throw new Error('Both --ssl-key and --ssl-cert must be provided together');
}
config.ssl = !!(config.sslKey && config.sslCert);
return config;
}
/**
* Filter out undefined values from an object
*/
function filterUndefined(obj) {
const result = {};
for (const [key, value] of Object.entries(obj)) {
if (value !== undefined) {
result[key] = value;
}
}
return result;
}
/**
* Save configuration to a file
*/
export async function saveConfig(config, configFile) {
const toSave = { ...config };
// Remove derived/runtime values
delete toSave.ssl;
delete toSave.logger;
// Never persist secrets to a static config file. The password is
// expected to come from --single-user-password or
// JSS_SINGLE_USER_PASSWORD at runtime, not be written into .jss/config.
delete toSave.singleUserPassword;
await fs.ensureDir(path.dirname(configFile));
await fs.writeFile(configFile, JSON.stringify(toSave, null, 2));
}
/**
* Print configuration (for debugging)
*/
export function printConfig(config) {
console.log('\nConfiguration:');
console.log('─'.repeat(40));
console.log(` Port: ${config.port}`);
console.log(` Host: ${config.host}`);
console.log(` Root: ${path.resolve(config.root)}`);
console.log(` SSL: ${config.ssl ? 'enabled' : 'disabled'}`);
console.log(` Multi-user: ${config.multiuser}`);
if (config.singleUser) {
const isRootPod = config.singleUserName === '/' || !config.singleUserName;
let details = isRootPod ? '/ (root pod)' : config.singleUserName;
// The "login as me" hint and password line only make sense when
// the built-in IdP is on. With --no-idp / external issuer there's
// no built-in login form, so don't imply one exists.
if (config.idp) {
if (isRootPod) details += ', login as "me"';
const pwSource = config.singleUserPassword
? 'provided'
: (process.stdin.isTTY ? 'will prompt at startup' : 'missing — login disabled');
details += ` (password: ${pwSource})`;
}
console.log(` Single-user: ${details}`);
}
console.log(` Conneg: ${config.conneg}`);
console.log(` Notifications: ${config.notifications}`);
console.log(` IdP: ${config.idp ? (config.idpIssuer || 'enabled') : 'disabled'}`);
console.log(` Subdomains: ${config.subdomains ? (config.baseDomain || 'enabled') : 'disabled'}`);
console.log(` Mashlib: ${config.mashlibModule ? `module (${config.mashlibModule})` : config.mashlibCdn ? `CDN v${config.mashlibVersion}` : 'disabled'}`);
if (config.pay) {
console.log(` Pay: ${config.payCost} sat/req`);
if (config.payToken) console.log(` Token: ${config.payToken} @ ${config.payRate} sat/token`);
}
if (config.mongo) console.log(` MongoDB: ${config.mongoUrl} (${config.mongoDatabase})`);
console.log('─'.repeat(40));
}