-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathserver.js
More file actions
393 lines (352 loc) · 15.6 KB
/
Copy pathserver.js
File metadata and controls
393 lines (352 loc) · 15.6 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
import Fastify from 'fastify';
import rateLimit from '@fastify/rate-limit';
import { readFile } from 'fs/promises';
import { join, dirname } from 'path';
import { fileURLToPath } from 'url';
import { handleGet, handleHead, handlePut, handleDelete, handleOptions, handlePatch } from './handlers/resource.js';
import { handlePost, handleCreatePod } from './handlers/container.js';
import { getCorsHeaders } from './ldp/headers.js';
import { authorize, handleUnauthorized } from './auth/middleware.js';
import { notificationsPlugin } from './notifications/index.js';
import { idpPlugin } from './idp/index.js';
import { isGitRequest, isGitWriteOperation, handleGit } from './handlers/git.js';
import { AccessMode } from './wac/parser.js';
import { registerNostrRelay } from './nostr/relay.js';
import { activityPubPlugin } from './ap/index.js';
const __dirname = dirname(fileURLToPath(import.meta.url));
/**
* Create and configure Fastify server
* @param {object} options - Server options
* @param {boolean} options.logger - Enable logging (default true)
* @param {boolean} options.conneg - Enable content negotiation for RDF (default false)
* @param {boolean} options.notifications - Enable WebSocket notifications (default false)
* @param {boolean} options.idp - Enable built-in Identity Provider (default false)
* @param {string} options.idpIssuer - IdP issuer URL (default: server URL)
* @param {object} options.ssl - SSL configuration { key, cert } (default null)
* @param {string} options.root - Data directory path (default from env or ./data)
* @param {boolean} options.subdomains - Enable subdomain-based pods for XSS protection (default false)
* @param {string} options.baseDomain - Base domain for subdomain pods (e.g., "example.com")
* @param {boolean} options.git - Enable Git HTTP backend for clone/push (default false)
* @param {boolean} options.nostr - Enable Nostr relay (default false)
* @param {string} options.nostrPath - Nostr relay WebSocket path (default '/relay')
* @param {number} options.nostrMaxEvents - Max events in relay memory (default 1000)
* @param {boolean} options.activitypub - Enable ActivityPub federation (default false)
* @param {string} options.apUsername - ActivityPub username (default 'me')
* @param {string} options.apDisplayName - ActivityPub display name
* @param {string} options.apSummary - ActivityPub bio/summary
* @param {string} options.apNostrPubkey - Nostr pubkey for identity linking
*/
export function createServer(options = {}) {
// Content negotiation is OFF by default - we're a JSON-LD native server
const connegEnabled = options.conneg ?? false;
// WebSocket notifications are OFF by default
const notificationsEnabled = options.notifications ?? false;
// Identity Provider is OFF by default
const idpEnabled = options.idp ?? false;
const idpIssuer = options.idpIssuer;
// Subdomain mode is OFF by default - use path-based pods
const subdomainsEnabled = options.subdomains ?? false;
const baseDomain = options.baseDomain || null;
// Mashlib data browser is OFF by default
// mashlibCdn: if true, load from CDN; if false, serve locally
const mashlibEnabled = options.mashlib ?? false;
const mashlibCdn = options.mashlibCdn ?? false;
const mashlibVersion = options.mashlibVersion ?? '2.0.0';
// Git HTTP backend is OFF by default - enables clone/push via git protocol
const gitEnabled = options.git ?? false;
// Nostr relay is OFF by default
const nostrEnabled = options.nostr ?? false;
const nostrPath = options.nostrPath ?? '/relay';
const nostrMaxEvents = options.nostrMaxEvents ?? 1000;
// ActivityPub federation is OFF by default
const activitypubEnabled = options.activitypub ?? false;
const apUsername = options.apUsername ?? 'me';
const apDisplayName = options.apDisplayName ?? options.apUsername ?? 'Anonymous';
const apSummary = options.apSummary ?? '';
const apNostrPubkey = options.apNostrPubkey ?? null;
// Invite-only registration is OFF by default - open registration
const inviteOnly = options.inviteOnly ?? false;
// Default storage quota per pod (50MB default, 0 = unlimited)
const defaultQuota = options.defaultQuota ?? 50 * 1024 * 1024;
// Set data root via environment variable if provided
if (options.root) {
process.env.DATA_ROOT = options.root;
}
// Fastify options
const fastifyOptions = {
logger: options.logger ?? true,
trustProxy: true,
// Handle raw body for non-JSON content
bodyLimit: 10 * 1024 * 1024 // 10MB
};
// Add HTTPS support if SSL config provided
if (options.ssl && options.ssl.key && options.ssl.cert) {
fastifyOptions.https = {
key: options.ssl.key,
cert: options.ssl.cert,
};
}
const fastify = Fastify(fastifyOptions);
// Add raw body parser for all content types
fastify.addContentTypeParser('*', { parseAs: 'buffer' }, (req, body, done) => {
done(null, body);
});
// Git content types need explicit handling (binary data)
fastify.addContentTypeParser('application/x-git-receive-pack-request', { parseAs: 'buffer' }, (req, body, done) => {
done(null, body);
});
fastify.addContentTypeParser('application/x-git-upload-pack-request', { parseAs: 'buffer' }, (req, body, done) => {
done(null, body);
});
// Attach server config to requests
fastify.decorateRequest('connegEnabled', null);
fastify.decorateRequest('notificationsEnabled', null);
fastify.decorateRequest('idpEnabled', null);
fastify.decorateRequest('subdomainsEnabled', null);
fastify.decorateRequest('baseDomain', null);
fastify.decorateRequest('podName', null);
fastify.decorateRequest('mashlibEnabled', null);
fastify.decorateRequest('mashlibCdn', null);
fastify.decorateRequest('mashlibVersion', null);
fastify.decorateRequest('defaultQuota', null);
fastify.addHook('onRequest', async (request) => {
request.connegEnabled = connegEnabled;
request.notificationsEnabled = notificationsEnabled;
request.idpEnabled = idpEnabled;
request.subdomainsEnabled = subdomainsEnabled;
request.baseDomain = baseDomain;
request.mashlibEnabled = mashlibEnabled;
request.mashlibCdn = mashlibCdn;
request.mashlibVersion = mashlibVersion;
request.defaultQuota = defaultQuota;
// Extract pod name from subdomain if enabled
if (subdomainsEnabled && baseDomain) {
const host = request.hostname;
// Check if host is a subdomain of baseDomain
if (host !== baseDomain && host.endsWith('.' + baseDomain)) {
// Extract subdomain (e.g., "alice.example.com" -> "alice")
const subdomain = host.slice(0, -(baseDomain.length + 1));
// Only single-level subdomains (no dots)
if (!subdomain.includes('.')) {
request.podName = subdomain;
}
}
}
});
// Register WebSocket notifications plugin if enabled
if (notificationsEnabled) {
fastify.register(notificationsPlugin);
}
// Register Identity Provider plugin if enabled
if (idpEnabled) {
fastify.register(idpPlugin, { issuer: idpIssuer, inviteOnly });
}
// Register Nostr relay if enabled
if (nostrEnabled) {
fastify.register(async (instance) => {
await registerNostrRelay(instance, {
path: nostrPath,
maxEvents: nostrMaxEvents
});
});
}
// Register ActivityPub plugin if enabled
if (activitypubEnabled) {
fastify.register(activityPubPlugin, {
username: apUsername,
displayName: apDisplayName,
summary: apSummary,
nostrPubkey: apNostrPubkey
});
}
// Register rate limiting plugin
// Protects against brute force attacks and resource exhaustion
fastify.register(rateLimit, {
global: false, // Don't apply globally, only to specific routes
max: 100, // Default max requests per window
timeWindow: '1 minute',
// Custom error response
errorResponseBuilder: (request, context) => ({
error: 'Too Many Requests',
message: `Rate limit exceeded. Try again in ${Math.ceil(context.after / 1000)} seconds.`,
retryAfter: Math.ceil(context.after / 1000)
})
});
// Global CORS preflight
fastify.addHook('onRequest', async (request, reply) => {
// Add CORS headers to all responses
const corsHeaders = getCorsHeaders(request.headers.origin);
Object.entries(corsHeaders).forEach(([k, v]) => reply.header(k, v));
// Add Updates-Via header for WebSocket notification discovery
if (notificationsEnabled) {
const wsProtocol = request.protocol === 'https' ? 'wss' : 'ws';
reply.header('Updates-Via', `${wsProtocol}://${request.hostname}/.notifications`);
}
// Note: OPTIONS requests are handled by handleOptions to include Accept-* headers
});
// Security: Block access to dotfiles except allowed Solid-specific ones
// This prevents exposure of .git/, .env, .htpasswd, etc.
// Git protocol requests bypass this check when git is enabled
const ALLOWED_DOTFILES = ['.well-known', '.acl', '.meta', '.pods', '.notifications'];
fastify.addHook('onRequest', async (request, reply) => {
// Allow git protocol requests through when git is enabled
if (gitEnabled && isGitRequest(request.url)) {
return;
}
const segments = request.url.split('/').map(s => s.split('?')[0]); // Remove query strings
const hasForbiddenDotfile = segments.some(seg =>
seg.startsWith('.') &&
seg.length > 1 &&
!ALLOWED_DOTFILES.includes(seg)
);
if (hasForbiddenDotfile) {
return reply.code(403).send({ error: 'Forbidden', message: 'Dotfile access is not allowed' });
}
});
// Git HTTP backend handler - uses git http-backend CGI
// Authorization: Read for clone/fetch, Write for push
if (gitEnabled) {
fastify.addHook('preHandler', async (request, reply) => {
if (!isGitRequest(request.url)) {
return;
}
// Determine required mode: Write for push, Read for clone/fetch
const needsWrite = isGitWriteOperation(request.url);
const requiredMode = needsWrite ? AccessMode.WRITE : AccessMode.READ;
// Run WAC authorization with the correct mode for git operations
const { authorized, webId, wacAllow, authError } = await authorize(request, reply, { requiredMode });
request.webId = webId;
request.wacAllow = wacAllow;
if (!authorized) {
const message = needsWrite ? 'Write access required for push' : 'Read access required for clone';
reply.header('WAC-Allow', wacAllow);
if (!webId) {
// No authentication - request Basic auth for git clients
reply.header('WWW-Authenticate', 'Basic realm="Solid"');
}
return reply.code(webId ? 403 : 401).send({ error: message });
}
// Handle the git request directly
return handleGit(request, reply);
});
}
// Authorization hook - check WAC permissions
// Skip for pod creation endpoint (needs special handling)
fastify.addHook('preHandler', async (request, reply) => {
// Skip auth for pod creation, OPTIONS, IdP routes, mashlib, well-known, notifications, nostr, git, and AP
const mashlibPaths = ['/mashlib.min.js', '/mash.css', '/841.mashlib.min.js'];
const apPaths = ['/inbox', '/profile/card/inbox', '/profile/card/outbox', '/profile/card/followers', '/profile/card/following'];
// Check if request wants ActivityPub content for profile
const accept = request.headers.accept || '';
const wantsAP = accept.includes('activity+json') || accept.includes('ld+json; profile="https://www.w3.org/ns/activitystreams"');
const isProfileAP = activitypubEnabled && wantsAP && (request.url === '/profile/card' || request.url.startsWith('/profile/card?'));
if (request.url === '/.pods' ||
request.url === '/.notifications' ||
request.method === 'OPTIONS' ||
request.url.startsWith('/idp/') ||
request.url.startsWith('/.well-known/') ||
(nostrEnabled && request.url.startsWith(nostrPath)) ||
(gitEnabled && isGitRequest(request.url)) ||
(activitypubEnabled && apPaths.some(p => request.url === p || request.url.startsWith(p + '?'))) ||
isProfileAP ||
mashlibPaths.some(p => request.url === p || request.url.startsWith(p + '.'))) {
return;
}
const { authorized, webId, wacAllow, authError } = await authorize(request, reply);
// Store webId and wacAllow on request for handlers to use
request.webId = webId;
request.wacAllow = wacAllow;
// Set WAC-Allow header for all responses (handlers may override)
reply.header('WAC-Allow', wacAllow);
if (!authorized) {
return handleUnauthorized(reply, webId !== null, wacAllow, authError);
}
});
// Pod creation endpoint with rate limiting
// Limit: 1 pod per IP per day to prevent resource exhaustion and namespace squatting
fastify.post('/.pods', {
config: {
rateLimit: {
max: 1,
timeWindow: '1 day',
keyGenerator: (request) => request.ip
}
}
}, handleCreatePod);
// Mashlib static files (served from root like NSS does)
if (mashlibEnabled) {
if (mashlibCdn) {
// CDN mode: redirect chunk requests to CDN
// Mashlib uses code splitting, so it loads chunks like 789.mashlib.min.js
const cdnBase = `https://unpkg.com/mashlib@${mashlibVersion}/dist`;
const chunkPattern = /^\/\d+\.mashlib\.min\.js(\.map)?$/;
fastify.addHook('onRequest', async (request, reply) => {
if (chunkPattern.test(request.url)) {
const filename = request.url.split('/').pop();
return reply.redirect(302, `${cdnBase}/${filename}`);
}
});
} else {
// Local mode: serve from local files
const mashlibDir = join(__dirname, 'mashlib-local', 'dist');
const mashlibFiles = {
'/mashlib.min.js': { file: 'mashlib.min.js', type: 'application/javascript' },
'/mashlib.min.js.map': { file: 'mashlib.min.js.map', type: 'application/json' },
'/mash.css': { file: 'mash.css', type: 'text/css' },
'/mash.css.map': { file: 'mash.css.map', type: 'application/json' },
'/841.mashlib.min.js': { file: '841.mashlib.min.js', type: 'application/javascript' },
'/841.mashlib.min.js.map': { file: '841.mashlib.min.js.map', type: 'application/json' }
};
for (const [path, config] of Object.entries(mashlibFiles)) {
fastify.get(path, async (request, reply) => {
try {
const content = await readFile(join(mashlibDir, config.file));
return reply.type(config.type).send(content);
} catch {
return reply.code(404).send({ error: 'Not Found' });
}
});
}
}
}
// Rate limit configuration for write operations
// Protects against resource exhaustion and abuse
const writeRateLimit = {
config: {
rateLimit: {
max: 60,
timeWindow: '1 minute',
keyGenerator: (request) => request.webId || request.ip
}
}
};
// LDP routes - using wildcard routing
// Read operations - no rate limit (handled by bodyLimit)
fastify.get('/*', handleGet);
fastify.head('/*', handleHead);
fastify.options('/*', handleOptions);
// Write operations - rate limited
fastify.put('/*', writeRateLimit, handlePut);
fastify.delete('/*', writeRateLimit, handleDelete);
fastify.post('/*', writeRateLimit, handlePost);
fastify.patch('/*', writeRateLimit, handlePatch);
// Root route
fastify.get('/', handleGet);
fastify.head('/', handleHead);
fastify.options('/', handleOptions);
fastify.post('/', writeRateLimit, handlePost);
return fastify;
}
/**
* Start the server
*/
export async function startServer(port = 3000, host = '0.0.0.0') {
const server = createServer();
try {
await server.listen({ port, host });
return server;
} catch (err) {
server.log.error(err);
process.exit(1);
}
}