forked from nodeSolidServer/node-solid-server
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.js
More file actions
321 lines (270 loc) · 10.6 KB
/
middleware.js
File metadata and controls
321 lines (270 loc) · 10.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
import { Router } from 'express'
import fs from 'fs/promises'
import { HttpError } from './error.js'
import { ACLChecker, wacAllowHeader } from './acl.js'
import { applyPatch, patchPermissions } from './patch.js'
import * as rdf from './rdf.js'
import { isRdfMime, isAuxiliary, debugAuth } from './utils.js'
export function createMiddleware ({ ldp, rootUrl, skipAuth }) {
const router = Router()
const acl = new ACLChecker({ ldp, rootUrl })
// Extract user identity from request
function getUser (req) {
// Bearer token: expect the WebID as the token value for simplicity
// In production, this would validate a DPoP/OIDC token
const auth = req.headers.authorization
if (auth && auth.startsWith('Bearer ')) {
return auth.slice(7).trim()
}
// Dev mode: User header
if (req.headers.user) {
return req.headers.user
}
return null
}
async function checkPermission (req, resourceUrl, mode, isContainer) {
if (skipAuth) return
const user = getUser(req)
await acl.can(user, resourceUrl, mode, isContainer)
}
// HEAD
router.head('/*', async (req, res, next) => {
try {
const pathname = decodeURIComponent(req.path)
const resourceUrl = rootUrl + pathname
const isContainer = await ldp.isContainer(pathname)
await checkPermission(req, resourceUrl, 'Read', isContainer)
const result = await ldp.get(pathname)
setCommonHeaders(res, pathname, resourceUrl, isContainer)
await setWacHeader(res, req, resourceUrl, isContainer, acl, getUser)
res.set('Content-Type', result.contentType)
if (result.stat) {
res.set('Last-Modified', result.stat.mtime.toUTCString())
res.set('ETag', `"${result.stat.mtime.getTime()}"`)
if (!isContainer) res.set('Content-Length', String(result.stat.size))
}
res.status(200).end()
} catch (e) { next(e) }
})
// GET
router.get('/*', async (req, res, next) => {
try {
const pathname = decodeURIComponent(req.path)
// Redirect containers to trailing slash
if (!pathname.endsWith('/') && await ldp.isContainer(pathname)) {
return res.redirect(301, pathname + '/')
}
const resourceUrl = rootUrl + pathname
const isContainer = pathname.endsWith('/') && await ldp.isContainer(pathname)
await checkPermission(req, resourceUrl, 'Read', isContainer)
const result = await ldp.get(pathname)
setCommonHeaders(res, pathname, resourceUrl, isContainer)
await setWacHeader(res, req, resourceUrl, isContainer, acl, getUser)
if (result.stat) {
res.set('Last-Modified', result.stat.mtime.toUTCString())
res.set('ETag', `"${result.stat.mtime.getTime()}"`)
}
if (result.isContainer) {
// Content negotiation for containers
const accept = rdf.negotiateType(req.headers.accept)
if (accept && accept !== 'text/turtle' && isRdfMime(accept)) {
const translated = await rdf.translate(result.body, resourceUrl, 'text/turtle', accept)
res.set('Content-Type', accept)
return res.send(translated)
}
res.set('Content-Type', 'text/turtle')
return res.send(result.body)
}
// Content negotiation for RDF resources
const sourceType = result.contentType
if (isRdfMime(sourceType)) {
const accept = rdf.negotiateType(req.headers.accept)
if (accept && accept !== 'text/html' && accept !== sourceType && isRdfMime(accept)) {
const body = await streamToString(result.stream)
const translated = await rdf.translate(body, resourceUrl, sourceType, accept)
res.set('Content-Type', accept)
return res.send(translated)
}
if (accept === null) {
throw new HttpError(406, 'Not Acceptable')
}
} else {
// Non-RDF: check Accept compatibility
const accept = req.headers.accept
if (accept && !accept.includes('*/*') && !accept.includes(sourceType)) {
throw new HttpError(406, 'Not Acceptable')
}
}
res.set('Content-Type', sourceType)
result.stream.pipe(res)
} catch (e) { next(e) }
})
// PUT
router.put('/*', async (req, res, next) => {
try {
const pathname = decodeURIComponent(req.path)
const resourceUrl = rootUrl + pathname
const contentType = req.headers['content-type']
const existed = await ldp.exists(pathname)
const isContainer = await ldp.isContainer(pathname)
const mode = existed ? 'Write' : 'Append'
await checkPermission(req, resourceUrl, mode, isContainer)
// If-None-Match: * check
if (req.headers['if-none-match'] === '*' && existed) {
throw new HttpError(412, 'Resource already exists')
}
// Check for reserved path segments
if (hasReservedPathSegment(pathname)) {
throw new HttpError(400, 'Path contains reserved suffix')
}
const body = await collectBody(req)
const ct = contentType ? contentType.split(';')[0].trim() : ''
const result = await ldp.put(pathname, body, ct || undefined)
setCommonHeaders(res, pathname, resourceUrl, false)
res.status(result.status).end()
} catch (e) { next(e) }
})
// POST
router.post('/*', async (req, res, next) => {
try {
const pathname = decodeURIComponent(req.path)
const resourceUrl = rootUrl + pathname
await checkPermission(req, resourceUrl, 'Append', true)
// Check if SPARQL-UPDATE POST (route to PATCH logic)
const contentType = req.headers['content-type']
if (contentType && contentType.includes('application/sparql-update')) {
return handlePatch(req, res, next, pathname)
}
const slug = req.headers.slug
const link = req.headers.link
const body = await collectBody(req)
const result = await ldp.post(pathname, body, contentType, slug, link)
res.set('Location', result.location)
setCommonHeaders(res, pathname, resourceUrl, true)
res.status(result.status).end()
} catch (e) { next(e) }
})
// PATCH
router.patch('/*', handlePatch)
async function handlePatch (req, res, next) {
try {
const pathname = decodeURIComponent(req.path)
const resourceUrl = rootUrl + pathname
const patchType = req.headers['content-type']
if (!patchType) {
throw new HttpError(400, 'Content-Type required for PATCH')
}
if (hasReservedPathSegment(pathname)) {
throw new HttpError(400, 'Path contains reserved suffix')
}
const patchBody = await collectBody(req)
const perms = patchPermissions(patchBody, patchType)
// Check permissions based on patch content
if (perms.write) {
await checkPermission(req, resourceUrl, 'Write', false)
await checkPermission(req, resourceUrl, 'Read', false)
} else if (perms.read) {
await checkPermission(req, resourceUrl, 'Read', false)
await checkPermission(req, resourceUrl, 'Append', false)
} else if (perms.append) {
await checkPermission(req, resourceUrl, 'Append', false)
}
// Read current resource
let currentBody = null
let contentType = 'text/turtle'
let existed = false
try {
const filePath = ldp.resolve(pathname)
currentBody = await fs.readFile(filePath, 'utf8')
contentType = ldp.mapper.getContentType(filePath)
existed = true
} catch { /* new resource */ }
const newBody = await applyPatch(resourceUrl, currentBody, contentType, patchBody, patchType)
await ldp.put(pathname, newBody, contentType)
setCommonHeaders(res, pathname, resourceUrl, false)
res.status(existed ? 200 : 201).end()
} catch (e) { next(e) }
}
// DELETE
router.delete('/*', async (req, res, next) => {
try {
const pathname = decodeURIComponent(req.path)
const resourceUrl = rootUrl + pathname
const isContainer = await ldp.isContainer(pathname)
await checkPermission(req, resourceUrl, 'Write', isContainer)
const result = await ldp.delete(pathname)
res.status(result.status).end()
} catch (e) { next(e) }
})
// OPTIONS
router.options('/*', async (req, res, next) => {
try {
const pathname = decodeURIComponent(req.path)
const resourceUrl = rootUrl + pathname
const isContainer = await ldp.isContainer(pathname)
setCommonHeaders(res, pathname, resourceUrl, isContainer)
await setWacHeader(res, req, resourceUrl, isContainer, acl, getUser)
res.status(204).end()
} catch (e) { next(e) }
})
return router
}
function setCommonHeaders (res, pathname, resourceUrl, isContainer) {
res.set('Accept-Patch', 'text/n3, application/sparql-update')
res.set('Accept-Post', '*/*')
if (!isContainer) {
res.set('Accept-Put', '*/*')
}
res.set('Allow', 'OPTIONS, HEAD, GET, PATCH, POST, PUT, DELETE')
res.set('MS-Author-Via', 'SPARQL')
// Link headers
const links = ['<http://www.w3.org/ns/ldp#Resource>; rel="type"']
if (isContainer) {
links.push('<http://www.w3.org/ns/ldp#BasicContainer>; rel="type"')
links.push('<http://www.w3.org/ns/ldp#Container>; rel="type"')
}
if (pathname === '/' || pathname === '') {
links.push('<http://www.w3.org/ns/pim/space#Storage>; rel="type"')
}
// ACL and meta links
const aclLink = resourceUrl.endsWith('/') ? resourceUrl + '.acl' : resourceUrl + '.acl'
const metaLink = resourceUrl.endsWith('/') ? resourceUrl + '.meta' : resourceUrl + '.meta'
links.push(`<${aclLink}>; rel="acl"`)
links.push(`<${metaLink}>; rel="describedby"`)
res.set('Link', links.join(', '))
}
async function setWacHeader (res, req, resourceUrl, isContainer, acl, getUser) {
try {
const user = getUser(req)
const perms = await acl.getPermissions(user, resourceUrl, isContainer)
res.set('WAC-Allow', wacAllowHeader(perms))
} catch {
// If ACL check fails, skip WAC-Allow
}
}
function hasReservedPathSegment (pathname) {
const segments = pathname.split('/')
// Check intermediate segments (not the last one) for .acl/.meta
for (let i = 0; i < segments.length - 1; i++) {
if (segments[i].endsWith('.acl') || segments[i].endsWith('.meta')) {
return true
}
}
return false
}
function collectBody (req) {
return new Promise((resolve, reject) => {
const chunks = []
req.on('data', chunk => chunks.push(chunk))
req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')))
req.on('error', reject)
})
}
function streamToString (stream) {
return new Promise((resolve, reject) => {
const chunks = []
stream.on('data', chunk => chunks.push(chunk))
stream.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')))
stream.on('error', reject)
})
}