-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathindex.js
More file actions
306 lines (260 loc) · 9.89 KB
/
index.js
File metadata and controls
306 lines (260 loc) · 9.89 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
/**
* MongoDB Database Route Plugin for JSS
*
* Adds /db/* routes backed by MongoDB.
* Documents are stored as JSON-LD and keyed by URI.
*/
import { connect, disconnect, findOne, upsertOne, deleteOne, listByPrefix } from './store.js';
import { getAllHeaders, getNotFoundHeaders } from '../ldp/headers.js';
import { generateContainerJsonLd, serializeJsonLd } from '../ldp/container.js';
import { checkIfMatch, checkIfNoneMatchForGet, checkIfNoneMatchForWrite } from '../utils/conditional.js';
import { emitChange } from '../notifications/events.js';
import { getWebIdFromRequestAsync } from '../auth/token.js';
/**
* Database route Fastify plugin
* @param {FastifyInstance} fastify
* @param {object} options
*/
export async function dbPlugin(fastify, options) {
await connect({
url: options.mongoUrl,
database: options.mongoDatabase || 'solid'
});
fastify.addHook('onClose', async () => {
await disconnect();
});
// Auth hook for /db/* routes
// WAC doesn't apply here — uses WebID-based ownership
fastify.addHook('preHandler', async (request, reply) => {
if (request.method === 'OPTIONS') return;
// Public mode — skip auth
if (request.config?.public) {
request.webId = null;
return;
}
const { webId } = await getWebIdFromRequestAsync(request);
request.webId = webId;
// Read is public
if (request.method === 'GET' || request.method === 'HEAD') return;
// Write requires authentication
if (!webId) {
return reply.code(401).send({ error: 'Unauthorized', message: 'Authentication required' });
}
// Single-user mode: any authenticated user is the owner
if (options.singleUser) return;
// Ownership check: only pod owner can write to /db/{podName}/...
const urlPath = request.url.split('?')[0];
const relative = urlPath.replace(/^\/db\//, '');
const podName = relative.split('/')[0];
if (podName) {
// Build expected WebID for both path and subdomain modes
const expectedWebId = request.subdomainsEnabled && request.baseDomain
? `${request.protocol}://${podName}.${request.baseDomain}/profile/card#me`
: `${request.protocol}://${request.hostname}/${podName}/profile/card#me`;
if (webId !== expectedWebId) {
return reply.code(403).send({ error: 'Forbidden', message: 'You can only write to your own /db/ space' });
}
}
});
// Routes
fastify.get('/db', handleDbGet);
fastify.get('/db/*', handleDbGet);
fastify.head('/db', handleDbHead);
fastify.head('/db/*', handleDbHead);
fastify.put('/db/*', handleDbPut);
fastify.delete('/db/*', handleDbDelete);
fastify.options('/db', handleDbOptions);
fastify.options('/db/*', handleDbOptions);
}
/**
* Build the full resource URL for a /db/ request
*/
function getResourceUrl(request) {
const urlPath = request.url.split('?')[0];
return `${request.protocol}://${request.hostname}${urlPath}`;
}
/**
* GET /db/* — read resource or container listing
*/
async function handleDbGet(request, reply) {
const urlPath = request.url.split('?')[0];
const resourceUrl = getResourceUrl(request);
const origin = request.headers.origin;
const connegEnabled = request.connegEnabled || false;
// Container request (treat /db as root container)
if (urlPath === '/db' || urlPath.endsWith('/')) {
const entries = await listByPrefix(resourceUrl);
const jsonLd = generateContainerJsonLd(resourceUrl, entries);
const content = serializeJsonLd(jsonLd);
const etag = `"container-${entries.length}"`;
const ifNoneMatch = request.headers['if-none-match'];
if (ifNoneMatch) {
const check = checkIfNoneMatchForGet(ifNoneMatch, etag);
if (!check.ok && check.notModified) {
return reply.code(304).send();
}
}
const headers = getAllHeaders({
isContainer: true, etag,
contentType: 'application/ld+json',
origin, resourceUrl, connegEnabled
});
Object.entries(headers).forEach(([k, v]) => reply.header(k, v));
return reply.send(content);
}
// Resource request
const doc = await findOne(resourceUrl);
if (!doc) {
const headers = getNotFoundHeaders({ resourceUrl, origin, connegEnabled });
Object.entries(headers).forEach(([k, v]) => reply.header(k, v));
return reply.code(404).send({ error: 'Not Found' });
}
const ifNoneMatch = request.headers['if-none-match'];
if (ifNoneMatch) {
const check = checkIfNoneMatchForGet(ifNoneMatch, doc.etag);
if (!check.ok && check.notModified) {
return reply.code(304).send();
}
}
const headers = getAllHeaders({
isContainer: false, etag: doc.etag,
contentType: doc.contentType,
origin, resourceUrl, connegEnabled
});
Object.entries(headers).forEach(([k, v]) => reply.header(k, v));
return reply.send(JSON.stringify(doc.data, null, 2));
}
/**
* HEAD /db/* — same as GET but no body
*/
async function handleDbHead(request, reply) {
const urlPath = request.url.split('?')[0];
const resourceUrl = getResourceUrl(request);
const origin = request.headers.origin;
const connegEnabled = request.connegEnabled || false;
if (urlPath === '/db' || urlPath.endsWith('/')) {
const entries = await listByPrefix(resourceUrl);
const etag = `"container-${entries.length}"`;
const headers = getAllHeaders({
isContainer: true, etag,
contentType: 'application/ld+json',
origin, resourceUrl, connegEnabled
});
Object.entries(headers).forEach(([k, v]) => reply.header(k, v));
return reply.code(200).send();
}
const doc = await findOne(resourceUrl);
if (!doc) {
const headers = getNotFoundHeaders({ resourceUrl, origin, connegEnabled });
Object.entries(headers).forEach(([k, v]) => reply.header(k, v));
return reply.code(404).send();
}
const headers = getAllHeaders({
isContainer: false, etag: doc.etag,
contentType: doc.contentType,
origin, resourceUrl, connegEnabled
});
Object.entries(headers).forEach(([k, v]) => reply.header(k, v));
return reply.code(200).send();
}
/**
* PUT /db/* — create or update resource
*/
async function handleDbPut(request, reply) {
if (request.config?.readOnly) {
return reply.code(405).send({ error: 'Method Not Allowed', message: 'Server is in read-only mode' });
}
const urlPath = request.url.split('?')[0];
const resourceUrl = getResourceUrl(request);
if (urlPath.endsWith('/')) {
return reply.code(409).send({ error: 'Conflict', message: 'Cannot PUT to a container' });
}
// Only accept JSON content types — stored as JSON-LD
const incomingType = (request.headers['content-type'] || '').split(';')[0].trim().toLowerCase();
if (incomingType && incomingType !== 'application/ld+json' && incomingType !== 'application/json') {
return reply.code(415).send({ error: 'Unsupported Media Type', message: 'Only application/ld+json and application/json are accepted' });
}
// Parse body
let data;
let body = request.body;
if (Buffer.isBuffer(body)) body = body.toString();
if (typeof body === 'string') {
try { data = JSON.parse(body); }
catch { return reply.code(400).send({ error: 'Bad Request', message: 'Invalid JSON' }); }
} else if (typeof body === 'object' && body !== null) {
data = body;
} else {
return reply.code(400).send({ error: 'Bad Request', message: 'Request body required' });
}
// Conditional headers
const existing = await findOne(resourceUrl);
const currentEtag = existing?.etag || null;
const ifMatch = request.headers['if-match'];
if (ifMatch) {
const check = checkIfMatch(ifMatch, currentEtag);
if (!check.ok) return reply.code(check.status).send({ error: check.error });
}
const ifNoneMatch = request.headers['if-none-match'];
if (ifNoneMatch) {
const check = checkIfNoneMatchForWrite(ifNoneMatch, currentEtag);
if (!check.ok) return reply.code(check.status).send({ error: check.error });
}
const { created, etag } = await upsertOne(resourceUrl, data, 'application/ld+json');
const origin = request.headers.origin;
const headers = getAllHeaders({
isContainer: false, etag,
origin, resourceUrl,
connegEnabled: request.connegEnabled || false
});
headers['Location'] = resourceUrl;
Object.entries(headers).forEach(([k, v]) => reply.header(k, v));
if (request.notificationsEnabled) {
emitChange(resourceUrl);
}
return reply.code(created ? 201 : 204).send();
}
/**
* DELETE /db/* — delete resource
*/
async function handleDbDelete(request, reply) {
if (request.config?.readOnly) {
return reply.code(405).send({ error: 'Method Not Allowed', message: 'Server is in read-only mode' });
}
const resourceUrl = getResourceUrl(request);
const origin = request.headers.origin;
const existing = await findOne(resourceUrl);
if (!existing) {
const headers = getNotFoundHeaders({ resourceUrl, origin, connegEnabled: request.connegEnabled || false });
Object.entries(headers).forEach(([k, v]) => reply.header(k, v));
return reply.code(404).send({ error: 'Not Found' });
}
const ifMatch = request.headers['if-match'];
if (ifMatch) {
const check = checkIfMatch(ifMatch, existing.etag);
if (!check.ok) return reply.code(check.status).send({ error: check.error });
}
await deleteOne(resourceUrl);
const headers = getAllHeaders({
isContainer: false, origin, resourceUrl
});
Object.entries(headers).forEach(([k, v]) => reply.header(k, v));
if (request.notificationsEnabled) {
emitChange(resourceUrl);
}
return reply.code(204).send();
}
/**
* OPTIONS /db/* — return allowed methods
*/
async function handleDbOptions(request, reply) {
const resourceUrl = getResourceUrl(request);
const origin = request.headers.origin;
const headers = getAllHeaders({
isContainer: request.url.split('?')[0] === '/db' || request.url.split('?')[0].endsWith('/'),
origin, resourceUrl,
connegEnabled: request.connegEnabled || false
});
Object.entries(headers).forEach(([k, v]) => reply.header(k, v));
return reply.code(204).send();
}
export default dbPlugin;