javascript-solid-server 0.0.221 → 0.0.223
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 +1 -1
- package/src/handlers/resource.js +147 -164
- package/src/patch/quads.js +166 -0
- package/src/rdf/turtle.js +0 -0
- package/src/server.js +18 -2
- package/src/storage/filesystem.js +46 -0
- package/src/wac/parser.js +96 -19
- package/test/patch.test.js +202 -1
- package/test/wac.test.js +226 -4
package/package.json
CHANGED
package/src/handlers/resource.js
CHANGED
|
@@ -3,8 +3,7 @@ import { reserveQuota, updateQuotaUsage } from '../storage/quota.js';
|
|
|
3
3
|
import { getAllHeaders, getNotFoundHeaders } from '../ldp/headers.js';
|
|
4
4
|
import { generateContainerJsonLd, serializeJsonLd } from '../ldp/container.js';
|
|
5
5
|
import { isContainer, getContentType, isRdfContentType, getEffectiveUrlPath, safeJsonParse, getPodName } from '../utils/url.js';
|
|
6
|
-
import {
|
|
7
|
-
import { parseSparqlUpdate, applySparqlUpdate } from '../patch/sparql-update.js';
|
|
6
|
+
import { parsePatch, applyPatch } from '../patch/quads.js';
|
|
8
7
|
import {
|
|
9
8
|
selectContentType,
|
|
10
9
|
canAcceptInput,
|
|
@@ -16,7 +15,11 @@ import {
|
|
|
16
15
|
import { emitChange } from '../notifications/events.js';
|
|
17
16
|
import { checkIfMatch, checkIfNoneMatchForGet, checkIfNoneMatchForWrite } from '../utils/conditional.js';
|
|
18
17
|
import { generateDatabrowserHtml, generateModuleDatabrowserHtml, shouldServeMashlib, DATA_ISLAND_MAX_BYTES } from '../mashlib/index.js';
|
|
19
|
-
import { turtleToJsonLd } from '../rdf/turtle.js';
|
|
18
|
+
import { turtleToJsonLd, jsonLdToQuads, quadsToJsonLd } from '../rdf/turtle.js';
|
|
19
|
+
import { parseAcl, grantsAccess } from '../wac/parser.js';
|
|
20
|
+
|
|
21
|
+
// Shared by the PUT and PATCH guards for .acl resources (#631).
|
|
22
|
+
const ACL_GRANTS_NOTHING = 'ACL document has no authorization that grants a mode to an agent, agent class or group; refusing to store it, as it would grant nobody access.';
|
|
20
23
|
|
|
21
24
|
/**
|
|
22
25
|
* Live reload script - injected into HTML when --live-reload is enabled
|
|
@@ -974,6 +977,24 @@ export async function handlePut(request, reply) {
|
|
|
974
977
|
});
|
|
975
978
|
}
|
|
976
979
|
|
|
980
|
+
// An ACL that parses to no authorizations would lock everyone out of the
|
|
981
|
+
// resource (and of the .acl itself, so it couldn't be repaired over HTTP).
|
|
982
|
+
// Refuse it up front instead of storing it. See #631.
|
|
983
|
+
if (urlPath.endsWith('.acl')) {
|
|
984
|
+
let aclDoc = request.body;
|
|
985
|
+
if (Buffer.isBuffer(aclDoc)) aclDoc = aclDoc.toString('utf8');
|
|
986
|
+
if (typeof aclDoc === 'string') {
|
|
987
|
+
try {
|
|
988
|
+
aclDoc = safeJsonParse(aclDoc);
|
|
989
|
+
} catch (e) {
|
|
990
|
+
return reply.code(400).send({ error: 'Bad Request', message: 'ACL body is not valid JSON: ' + e.message });
|
|
991
|
+
}
|
|
992
|
+
}
|
|
993
|
+
if (!grantsAccess(await parseAcl(aclDoc, resourceUrl))) {
|
|
994
|
+
return reply.code(400).send({ error: 'Bad Request', message: ACL_GRANTS_NOTHING });
|
|
995
|
+
}
|
|
996
|
+
}
|
|
997
|
+
|
|
977
998
|
// Check if we can accept this input type
|
|
978
999
|
if (!canAcceptInput(contentType, connegEnabled)) {
|
|
979
1000
|
const acceptValue = connegEnabled
|
|
@@ -1159,10 +1180,41 @@ export async function handleOptions(request, reply) {
|
|
|
1159
1180
|
}
|
|
1160
1181
|
|
|
1161
1182
|
/**
|
|
1162
|
-
*
|
|
1163
|
-
*
|
|
1183
|
+
* PATCH handler: N3 Patch (text/n3) and SPARQL Update (application/sparql-update).
|
|
1184
|
+
*
|
|
1185
|
+
* The resource is loaded as quads (from its stored JSON-LD, an HTML data
|
|
1186
|
+
* island, or raw Turtle), the patch is applied to the quads
|
|
1187
|
+
* (src/patch/quads.js), and the result is stored again in the same form.
|
|
1188
|
+
* Going through quads instead of editing the JSON-LD tree keeps every
|
|
1189
|
+
* predicate and literal intact whatever prefixes the client used.
|
|
1164
1190
|
*/
|
|
1191
|
+
// PATCH is read-modify-write. Two patches to the same resource at once (two people
|
|
1192
|
+
// posting in a chat) must not interleave, or one of them is lost and the file can be
|
|
1193
|
+
// left with the tail of a longer earlier write. Patches to one resource run one at a
|
|
1194
|
+
// time: queued within this process, and under a lock file on disk across processes
|
|
1195
|
+
// that share the data directory (storage.withLock).
|
|
1196
|
+
const patchQueues = new Map(); // storagePath -> tail promise
|
|
1197
|
+
|
|
1165
1198
|
export async function handlePatch(request, reply) {
|
|
1199
|
+
const { storagePath } = getRequestPaths(request);
|
|
1200
|
+
const previous = patchQueues.get(storagePath) ?? Promise.resolve();
|
|
1201
|
+
let release;
|
|
1202
|
+
const mine = new Promise((resolve) => { release = resolve; });
|
|
1203
|
+
const tail = previous.then(() => mine);
|
|
1204
|
+
patchQueues.set(storagePath, tail);
|
|
1205
|
+
await previous;
|
|
1206
|
+
try {
|
|
1207
|
+
return await storage.withLock(storagePath, () => applyPatchRequest(request, reply));
|
|
1208
|
+
} catch (err) {
|
|
1209
|
+
if (err.code === 'ELOCKED') return reply.code(503).header('Retry-After', '1').send({ error: 'Service Unavailable', message: 'The resource is being written by another request; retry shortly' });
|
|
1210
|
+
throw err;
|
|
1211
|
+
} finally {
|
|
1212
|
+
release();
|
|
1213
|
+
if (patchQueues.get(storagePath) === tail) patchQueues.delete(storagePath);
|
|
1214
|
+
}
|
|
1215
|
+
}
|
|
1216
|
+
|
|
1217
|
+
async function applyPatchRequest(request, reply) {
|
|
1166
1218
|
// Read-only mode - block all writes
|
|
1167
1219
|
if (request.config?.readOnly) {
|
|
1168
1220
|
return reply.code(405).send({ error: 'Method Not Allowed', message: 'Server is in read-only mode' });
|
|
@@ -1202,198 +1254,129 @@ export async function handlePatch(request, reply) {
|
|
|
1202
1254
|
}
|
|
1203
1255
|
}
|
|
1204
1256
|
|
|
1205
|
-
|
|
1206
|
-
|
|
1207
|
-
|
|
1257
|
+
const patchError = (e) => reply.code(e.status || 400).send({
|
|
1258
|
+
error: e.status === 409 ? 'Conflict' : 'Bad Request',
|
|
1259
|
+
message: e.message
|
|
1260
|
+
});
|
|
1261
|
+
|
|
1262
|
+
// Parse the patch (the authorization hook may already have done so to
|
|
1263
|
+
// decide between Append and Write).
|
|
1264
|
+
let patch = request.parsedPatch;
|
|
1265
|
+
if (!patch) {
|
|
1266
|
+
const patchContent = Buffer.isBuffer(request.body) ? request.body.toString() : String(request.body ?? '');
|
|
1267
|
+
try {
|
|
1268
|
+
patch = parsePatch(patchContent, contentType, resourceUrl);
|
|
1269
|
+
} catch (e) {
|
|
1270
|
+
return patchError(e);
|
|
1271
|
+
}
|
|
1272
|
+
}
|
|
1273
|
+
|
|
1274
|
+
// Load the resource as quads, remembering how it is stored.
|
|
1275
|
+
let quads = [];
|
|
1276
|
+
let storedAs = 'jsonld'; // 'jsonld' | 'turtle'
|
|
1277
|
+
let htmlWrapper = null; // HTML data island: { before, after }
|
|
1278
|
+
let prefixes = {}; // the document's own prefix map, kept for compaction
|
|
1279
|
+
let hadGraph = false; // the document used @graph (or was an array): keep that shape
|
|
1208
1280
|
|
|
1209
1281
|
if (resourceExists) {
|
|
1210
1282
|
const existingContent = await storage.read(storagePath);
|
|
1211
1283
|
if (existingContent === null) {
|
|
1212
1284
|
return reply.code(500).send({ error: 'Read error' });
|
|
1213
1285
|
}
|
|
1214
|
-
|
|
1215
1286
|
const contentStr = existingContent.toString();
|
|
1287
|
+
let document = null;
|
|
1216
1288
|
|
|
1217
|
-
// Check if this is HTML with embedded JSON-LD data island
|
|
1218
1289
|
if (contentStr.trimStart().startsWith('<!DOCTYPE') || contentStr.trimStart().startsWith('<html')) {
|
|
1219
|
-
// Extract JSON-LD from <script type="application/ld+json"> tag
|
|
1220
1290
|
const jsonLdMatch = contentStr.match(/<script\s+type=["']application\/ld\+json["']\s*>([\s\S]*?)<\/script>/i);
|
|
1221
|
-
|
|
1222
1291
|
if (!jsonLdMatch) {
|
|
1223
|
-
return reply.code(409).send({
|
|
1224
|
-
error: 'Conflict',
|
|
1225
|
-
message: 'HTML document does not contain a JSON-LD data island'
|
|
1226
|
-
});
|
|
1292
|
+
return reply.code(409).send({ error: 'Conflict', message: 'HTML document does not contain a JSON-LD data island' });
|
|
1227
1293
|
}
|
|
1228
|
-
|
|
1229
1294
|
try {
|
|
1230
1295
|
document = safeJsonParse(jsonLdMatch[1]);
|
|
1231
|
-
// Save the HTML parts for re-embedding after patch
|
|
1232
|
-
const jsonLdStart = contentStr.indexOf(jsonLdMatch[0]) + jsonLdMatch[0].indexOf('>') + 1;
|
|
1233
|
-
const jsonLdEnd = jsonLdStart + jsonLdMatch[1].length;
|
|
1234
|
-
htmlWrapper = {
|
|
1235
|
-
before: contentStr.substring(0, jsonLdStart),
|
|
1236
|
-
after: contentStr.substring(jsonLdEnd)
|
|
1237
|
-
};
|
|
1238
1296
|
} catch (e) {
|
|
1239
|
-
return reply.code(409).send({
|
|
1240
|
-
error: 'Conflict',
|
|
1241
|
-
message: 'HTML data island contains invalid JSON-LD'
|
|
1242
|
-
});
|
|
1297
|
+
return reply.code(409).send({ error: 'Conflict', message: 'HTML data island contains invalid JSON-LD' });
|
|
1243
1298
|
}
|
|
1299
|
+
const jsonLdStart = contentStr.indexOf(jsonLdMatch[0]) + jsonLdMatch[0].indexOf('>') + 1;
|
|
1300
|
+
htmlWrapper = { before: contentStr.substring(0, jsonLdStart), after: contentStr.substring(jsonLdStart + jsonLdMatch[1].length) };
|
|
1244
1301
|
} else {
|
|
1245
|
-
// Try to parse as JSON-LD first
|
|
1246
1302
|
try {
|
|
1247
1303
|
document = safeJsonParse(contentStr);
|
|
1248
1304
|
} catch (e) {
|
|
1249
|
-
// Not JSON
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
|
|
1305
|
+
// Not JSON: Turtle (or N3) stored as-is is patched as Turtle. Anything
|
|
1306
|
+
// else is not RDF and cannot be patched.
|
|
1307
|
+
const { Parser } = await import('n3');
|
|
1308
|
+
try {
|
|
1253
1309
|
const parser = new Parser({ baseIRI: resourceUrl });
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
return reply.code(409).send({
|
|
1259
|
-
error: 'Conflict',
|
|
1260
|
-
message: 'Resource is not valid Turtle: ' + parseErr.message
|
|
1261
|
-
});
|
|
1262
|
-
}
|
|
1263
|
-
|
|
1264
|
-
// Parse the SPARQL Update
|
|
1265
|
-
const patchContent = Buffer.isBuffer(request.body) ? request.body.toString() : request.body;
|
|
1266
|
-
let update;
|
|
1267
|
-
try {
|
|
1268
|
-
update = parseSparqlUpdate(patchContent, resourceUrl);
|
|
1269
|
-
} catch (parseErr) {
|
|
1270
|
-
return reply.code(400).send({
|
|
1271
|
-
error: 'Bad Request',
|
|
1272
|
-
message: 'Invalid SPARQL Update: ' + parseErr.message
|
|
1273
|
-
});
|
|
1274
|
-
}
|
|
1275
|
-
|
|
1276
|
-
// Apply deletes
|
|
1277
|
-
for (const triple of update.deletes) {
|
|
1278
|
-
quads = quads.filter(q => {
|
|
1279
|
-
const matches = q.subject.value === triple.subject &&
|
|
1280
|
-
q.predicate.value === triple.predicate &&
|
|
1281
|
-
(q.object.value === (triple.object['@id'] || triple.object['@value'] || triple.object));
|
|
1282
|
-
return !matches;
|
|
1283
|
-
});
|
|
1284
|
-
}
|
|
1285
|
-
|
|
1286
|
-
// Apply inserts
|
|
1287
|
-
const { DataFactory } = await import('n3');
|
|
1288
|
-
const { namedNode, literal } = DataFactory;
|
|
1289
|
-
for (const triple of update.inserts) {
|
|
1290
|
-
const subj = namedNode(triple.subject);
|
|
1291
|
-
const pred = namedNode(triple.predicate);
|
|
1292
|
-
let obj;
|
|
1293
|
-
if (triple.object['@id']) {
|
|
1294
|
-
obj = namedNode(triple.object['@id']);
|
|
1295
|
-
} else if (typeof triple.object === 'string') {
|
|
1296
|
-
obj = literal(triple.object);
|
|
1297
|
-
} else {
|
|
1298
|
-
obj = literal(triple.object['@value'] || triple.object);
|
|
1299
|
-
}
|
|
1300
|
-
quads.push(DataFactory.quad(subj, pred, obj));
|
|
1301
|
-
}
|
|
1302
|
-
|
|
1303
|
-
// Serialize back to Turtle
|
|
1304
|
-
const writer = new Writer({ prefixes: {} });
|
|
1305
|
-
quads.forEach(q => writer.addQuad(q));
|
|
1306
|
-
let turtleOutput;
|
|
1307
|
-
writer.end((err, result) => { turtleOutput = result; });
|
|
1308
|
-
|
|
1309
|
-
const success = await storage.write(storagePath, Buffer.from(turtleOutput));
|
|
1310
|
-
if (!success) {
|
|
1311
|
-
return reply.code(500).send({ error: 'Write failed' });
|
|
1312
|
-
}
|
|
1313
|
-
|
|
1314
|
-
const origin = request.headers.origin;
|
|
1315
|
-
const headers = getAllHeaders({ isContainer: false, origin, resourceUrl });
|
|
1316
|
-
Object.entries(headers).forEach(([k, v]) => reply.header(k, v));
|
|
1317
|
-
|
|
1318
|
-
if (request.notificationsEnabled) {
|
|
1319
|
-
emitChange(resourceUrl);
|
|
1320
|
-
}
|
|
1321
|
-
|
|
1322
|
-
return reply.code(resourceExists ? 204 : 201).send();
|
|
1310
|
+
quads = parser.parse(contentStr, null, (prefix, iri) => { prefixes[prefix] = iri.value; });
|
|
1311
|
+
storedAs = 'turtle';
|
|
1312
|
+
} catch (parseErr) {
|
|
1313
|
+
return reply.code(409).send({ error: 'Conflict', message: 'Resource is not valid JSON-LD or Turtle and cannot be patched' });
|
|
1323
1314
|
}
|
|
1315
|
+
}
|
|
1316
|
+
}
|
|
1324
1317
|
|
|
1325
|
-
|
|
1326
|
-
|
|
1327
|
-
|
|
1328
|
-
|
|
1318
|
+
if (document !== null) {
|
|
1319
|
+
if (typeof document !== 'object' || document === null) {
|
|
1320
|
+
return reply.code(409).send({ error: 'Conflict', message: 'Resource is not valid JSON-LD and cannot be patched' });
|
|
1321
|
+
}
|
|
1322
|
+
// jsonLdToQuads walks documents with an @id; spread a @graph into nodes
|
|
1323
|
+
// that each carry the document's context.
|
|
1324
|
+
const docs = Array.isArray(document) ? document : [document];
|
|
1325
|
+
if (Array.isArray(document)) hadGraph = true;
|
|
1326
|
+
const nodes = [];
|
|
1327
|
+
for (const doc of docs) {
|
|
1328
|
+
const context = doc['@context'];
|
|
1329
|
+
if (context && typeof context === 'object' && !Array.isArray(context)) {
|
|
1330
|
+
for (const [k, v] of Object.entries(context)) if (typeof v === 'string' && k && !k.startsWith('@')) prefixes[k] = v;
|
|
1331
|
+
}
|
|
1332
|
+
if (Array.isArray(doc['@graph'])) {
|
|
1333
|
+
hadGraph = true;
|
|
1334
|
+
for (const node of doc['@graph']) nodes.push(context ? { '@context': context, ...node } : node);
|
|
1335
|
+
}
|
|
1336
|
+
if (doc['@id'] !== undefined || doc.id !== undefined) nodes.push(doc);
|
|
1337
|
+
}
|
|
1338
|
+
try {
|
|
1339
|
+
quads = jsonLdToQuads(nodes, resourceUrl);
|
|
1340
|
+
} catch (e) {
|
|
1341
|
+
return reply.code(409).send({ error: 'Conflict', message: 'Resource is not valid JSON-LD and cannot be patched' });
|
|
1329
1342
|
}
|
|
1330
1343
|
}
|
|
1331
|
-
} else {
|
|
1332
|
-
// Create empty JSON-LD document for new resource
|
|
1333
|
-
document = {
|
|
1334
|
-
'@context': {},
|
|
1335
|
-
'@graph': []
|
|
1336
|
-
};
|
|
1337
1344
|
}
|
|
1338
1345
|
|
|
1339
|
-
|
|
1340
|
-
|
|
1341
|
-
|
|
1342
|
-
|
|
1343
|
-
|
|
1344
|
-
|
|
1345
|
-
|
|
1346
|
-
if (isSparqlUpdate) {
|
|
1347
|
-
// Handle SPARQL Update
|
|
1348
|
-
let update;
|
|
1349
|
-
try {
|
|
1350
|
-
update = parseSparqlUpdate(patchContent, resourceUrl);
|
|
1351
|
-
} catch (e) {
|
|
1352
|
-
return reply.code(400).send({
|
|
1353
|
-
error: 'Bad Request',
|
|
1354
|
-
message: 'Invalid SPARQL Update: ' + e.message
|
|
1355
|
-
});
|
|
1356
|
-
}
|
|
1346
|
+
let updatedQuads;
|
|
1347
|
+
try {
|
|
1348
|
+
updatedQuads = applyPatch(quads, patch);
|
|
1349
|
+
} catch (e) {
|
|
1350
|
+
return patchError(e);
|
|
1351
|
+
}
|
|
1357
1352
|
|
|
1358
|
-
|
|
1359
|
-
|
|
1360
|
-
|
|
1361
|
-
|
|
1362
|
-
|
|
1363
|
-
|
|
1364
|
-
|
|
1365
|
-
|
|
1353
|
+
// Serialize in the stored form.
|
|
1354
|
+
let updatedContent;
|
|
1355
|
+
let updatedDocument = null;
|
|
1356
|
+
if (storedAs === 'turtle') {
|
|
1357
|
+
const { Writer } = await import('n3');
|
|
1358
|
+
const writer = new Writer({ prefixes });
|
|
1359
|
+
for (const q of updatedQuads) writer.addQuad(q);
|
|
1360
|
+
updatedContent = await new Promise((resolve, reject) => writer.end((err, result) => (err ? reject(err) : resolve(result))));
|
|
1366
1361
|
} else {
|
|
1367
|
-
|
|
1368
|
-
|
|
1369
|
-
|
|
1370
|
-
|
|
1371
|
-
|
|
1372
|
-
|
|
1373
|
-
|
|
1374
|
-
message: 'Invalid N3 Patch format: ' + e.message
|
|
1375
|
-
});
|
|
1376
|
-
}
|
|
1377
|
-
|
|
1378
|
-
try {
|
|
1379
|
-
updatedDocument = applyN3Patch(document, patch, resourceUrl);
|
|
1380
|
-
} catch (e) {
|
|
1381
|
-
return reply.code(409).send({
|
|
1382
|
-
error: 'Conflict',
|
|
1383
|
-
message: 'Failed to apply patch: ' + e.message
|
|
1384
|
-
});
|
|
1362
|
+
let doc = quadsToJsonLd(updatedQuads, resourceUrl, prefixes);
|
|
1363
|
+
if (Array.isArray(doc) || (hadGraph && !Array.isArray(doc['@graph']))) {
|
|
1364
|
+
// Several subjects (or a document that was a @graph to begin with): one
|
|
1365
|
+
// document with a shared @context and a @graph.
|
|
1366
|
+
const list = Array.isArray(doc) ? doc : updatedQuads.length ? [doc] : [];
|
|
1367
|
+
const context = list[0]?.['@context'] ?? doc['@context'] ?? {};
|
|
1368
|
+
doc = { '@context': context, '@graph': list.map(({ '@context': _, ...node }) => node) };
|
|
1385
1369
|
}
|
|
1370
|
+
updatedDocument = doc;
|
|
1371
|
+
const jsonLdStr = JSON.stringify(doc, null, 2);
|
|
1372
|
+
updatedContent = htmlWrapper ? htmlWrapper.before + '\n' + jsonLdStr + '\n ' + htmlWrapper.after : jsonLdStr;
|
|
1386
1373
|
}
|
|
1387
1374
|
|
|
1388
|
-
//
|
|
1389
|
-
|
|
1390
|
-
|
|
1391
|
-
// Re-embed JSON-LD into HTML wrapper
|
|
1392
|
-
const jsonLdStr = JSON.stringify(updatedDocument, null, 2);
|
|
1393
|
-
updatedContent = htmlWrapper.before + '\n' + jsonLdStr + '\n ' + htmlWrapper.after;
|
|
1394
|
-
} else {
|
|
1395
|
-
updatedContent = JSON.stringify(updatedDocument, null, 2);
|
|
1375
|
+
// A patch must not leave an ACL that grants nobody access (#631).
|
|
1376
|
+
if (urlPath.endsWith('.acl') && updatedDocument && !grantsAccess(await parseAcl(updatedDocument, resourceUrl))) {
|
|
1377
|
+
return reply.code(409).send({ error: 'Conflict', message: ACL_GRANTS_NOTHING });
|
|
1396
1378
|
}
|
|
1379
|
+
|
|
1397
1380
|
const success = await storage.write(storagePath, Buffer.from(updatedContent));
|
|
1398
1381
|
|
|
1399
1382
|
if (!success) {
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Quad-based PATCH application.
|
|
3
|
+
*
|
|
4
|
+
* Both patch formats are parsed with N3.js and applied to the resource as a
|
|
5
|
+
* set of quads, so every Turtle construct a client can write (typed and
|
|
6
|
+
* language-tagged literals, prefixed names, lists, blank nodes, multi-line
|
|
7
|
+
* strings) survives the round trip. The earlier hand-rolled parsers lost
|
|
8
|
+
* triples whose predicates were not in a fixed prefix table (#).
|
|
9
|
+
*
|
|
10
|
+
* N3 Patch (https://solid.github.io/specification/protocol#n3-patch):
|
|
11
|
+
* _:p a solid:InsertDeletePatch;
|
|
12
|
+
* solid:where { ?a ex:p ?b }; # optional; must match exactly once
|
|
13
|
+
* solid:deletes { ?a ex:p ?b }; # optional
|
|
14
|
+
* solid:inserts { ?a ex:q "new" }. # optional
|
|
15
|
+
*
|
|
16
|
+
* SPARQL Update: INSERT DATA / DELETE DATA / DELETE INSERT WHERE / DELETE WHERE
|
|
17
|
+
* (see ./sparql-update.js for the parsing).
|
|
18
|
+
*/
|
|
19
|
+
import { Parser, DataFactory } from 'n3';
|
|
20
|
+
import { parseSparqlUpdate } from './sparql-update.js';
|
|
21
|
+
|
|
22
|
+
const { namedNode, literal, blankNode, quad, defaultGraph } = DataFactory;
|
|
23
|
+
const SOLID = 'http://www.w3.org/ns/solid/terms#';
|
|
24
|
+
const RDF_TYPE = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#type';
|
|
25
|
+
|
|
26
|
+
export class PatchError extends Error {
|
|
27
|
+
constructor(message, status = 400) {
|
|
28
|
+
super(message);
|
|
29
|
+
this.status = status;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Parse an N3 Patch document into { inserts, deletes, where } quads (default graph).
|
|
35
|
+
* @param {string} text
|
|
36
|
+
* @param {string} baseUri - the resource URL; relative IRIs resolve against it
|
|
37
|
+
*/
|
|
38
|
+
export function parseN3PatchQuads(text, baseUri) {
|
|
39
|
+
const parser = new Parser({ format: 'text/n3', baseIRI: baseUri });
|
|
40
|
+
let quads;
|
|
41
|
+
try {
|
|
42
|
+
quads = parser.parse(text);
|
|
43
|
+
} catch (e) {
|
|
44
|
+
throw new PatchError(`Invalid N3 Patch: ${e.message}`);
|
|
45
|
+
}
|
|
46
|
+
const top = quads.filter((q) => q.subject && q.predicate && q.object && q.graph.termType === 'DefaultGraph');
|
|
47
|
+
// The patch resource: typed solid:InsertDeletePatch, or any subject with a patch property.
|
|
48
|
+
const isPatchProp = (p) => [`${SOLID}inserts`, `${SOLID}deletes`, `${SOLID}where`].includes(p);
|
|
49
|
+
const patchSubjects = new Set(
|
|
50
|
+
top.filter((q) => (q.predicate.value === RDF_TYPE && q.object.value === `${SOLID}InsertDeletePatch`) || isPatchProp(q.predicate.value))
|
|
51
|
+
.map((q) => q.subject.value),
|
|
52
|
+
);
|
|
53
|
+
if (!patchSubjects.size) throw new PatchError('Invalid N3 Patch: no solid:InsertDeletePatch found');
|
|
54
|
+
const formula = (prop) => {
|
|
55
|
+
const graphs = top.filter((q) => patchSubjects.has(q.subject.value) && q.predicate.value === `${SOLID}${prop}`).map((q) => q.object);
|
|
56
|
+
return quads
|
|
57
|
+
// An empty formula `{ }` comes out of N3.js as a quad with null terms: nothing to apply.
|
|
58
|
+
.filter((q) => q.subject && q.predicate && q.object && graphs.some((g) => g.equals(q.graph)))
|
|
59
|
+
.map((q) => quad(q.subject, q.predicate, q.object, defaultGraph()));
|
|
60
|
+
};
|
|
61
|
+
return { inserts: formula('inserts'), deletes: formula('deletes'), where: formula('where') };
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** A parsed SPARQL Update triple ({ subject, predicate, object }) as a quad. */
|
|
65
|
+
function tripleToQuad(t) {
|
|
66
|
+
const node = (v) => (v.startsWith('_:') ? blankNode(v.slice(2)) : namedNode(v));
|
|
67
|
+
let o;
|
|
68
|
+
if (typeof t.object === 'string') o = literal(t.object);
|
|
69
|
+
else if (t.object['@id']) o = node(t.object['@id']);
|
|
70
|
+
else if (t.object['@language']) o = literal(String(t.object['@value']), t.object['@language']);
|
|
71
|
+
else if (t.object['@type']) o = literal(String(t.object['@value']), namedNode(t.object['@type']));
|
|
72
|
+
else o = literal(String(t.object['@value'] ?? t.object));
|
|
73
|
+
return quad(node(t.subject), namedNode(t.predicate), o, defaultGraph());
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export function parseSparqlUpdateQuads(text, baseUri) {
|
|
77
|
+
let update;
|
|
78
|
+
try {
|
|
79
|
+
update = parseSparqlUpdate(text, baseUri);
|
|
80
|
+
} catch (e) {
|
|
81
|
+
throw new PatchError(`Invalid SPARQL Update: ${e.message}`);
|
|
82
|
+
}
|
|
83
|
+
return { inserts: update.inserts.map(tripleToQuad), deletes: update.deletes.map(tripleToQuad), where: [] };
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export function parsePatch(text, contentType, baseUri) {
|
|
87
|
+
return contentType.includes('sparql-update') ? parseSparqlUpdateQuads(text, baseUri) : parseN3PatchQuads(text, baseUri);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** True when the patch only adds triples, so acl:Append is enough to apply it. */
|
|
91
|
+
export const isInsertOnly = (patch) => patch.deletes.length === 0 && patch.where.length === 0;
|
|
92
|
+
|
|
93
|
+
// ---------- Applying ----------
|
|
94
|
+
|
|
95
|
+
const isVar = (t) => t.termType === 'Variable';
|
|
96
|
+
|
|
97
|
+
function matchTerm(pattern, term, bindings) {
|
|
98
|
+
if (!isVar(pattern)) return pattern.equals(term);
|
|
99
|
+
const bound = bindings.get(pattern.value);
|
|
100
|
+
if (bound) return bound.equals(term);
|
|
101
|
+
bindings.set(pattern.value, term);
|
|
102
|
+
return true;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// Every binding of the where pattern's variables against the document.
|
|
106
|
+
function solutions(where, quads) {
|
|
107
|
+
let partial = [new Map()];
|
|
108
|
+
for (const pattern of where) {
|
|
109
|
+
const next = [];
|
|
110
|
+
for (const bindings of partial)
|
|
111
|
+
for (const q of quads) {
|
|
112
|
+
const b = new Map(bindings);
|
|
113
|
+
if (matchTerm(pattern.subject, q.subject, b) && matchTerm(pattern.predicate, q.predicate, b) && matchTerm(pattern.object, q.object, b)) next.push(b);
|
|
114
|
+
}
|
|
115
|
+
partial = next;
|
|
116
|
+
if (!partial.length) break;
|
|
117
|
+
}
|
|
118
|
+
// Distinct solutions (the same quad can satisfy a pattern more than once).
|
|
119
|
+
const seen = new Set();
|
|
120
|
+
return partial.filter((b) => {
|
|
121
|
+
const key = [...b].map(([k, v]) => `${k}=${v.termType}:${v.value}`).sort().join('|');
|
|
122
|
+
return !seen.has(key) && seen.add(key);
|
|
123
|
+
});
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function substitute(q, bindings, blankMap) {
|
|
127
|
+
const term = (t) => {
|
|
128
|
+
if (isVar(t)) {
|
|
129
|
+
const bound = bindings.get(t.value);
|
|
130
|
+
if (!bound) throw new PatchError(`Unbound variable ?${t.value} in patch`, 409);
|
|
131
|
+
return bound;
|
|
132
|
+
}
|
|
133
|
+
// Blank nodes from the patch are fresh: never collide with the document's own.
|
|
134
|
+
if (t.termType === 'BlankNode') {
|
|
135
|
+
if (!blankMap.has(t.value)) blankMap.set(t.value, blankNode(`p${blankMap.size}_${Date.now().toString(36)}`));
|
|
136
|
+
return blankMap.get(t.value);
|
|
137
|
+
}
|
|
138
|
+
return t;
|
|
139
|
+
};
|
|
140
|
+
return quad(term(q.subject), term(q.predicate), term(q.object), defaultGraph());
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* Apply a parsed patch to the document's quads. Returns the new quad list.
|
|
145
|
+
* Throws PatchError(409) when the where clause does not match exactly once or a
|
|
146
|
+
* triple to delete is absent (both per the Solid protocol).
|
|
147
|
+
*/
|
|
148
|
+
export function applyPatch(quads, patch) {
|
|
149
|
+
let bindings = new Map();
|
|
150
|
+
if (patch.where.length) {
|
|
151
|
+
const found = solutions(patch.where, quads);
|
|
152
|
+
if (found.length !== 1) throw new PatchError(found.length ? 'The patch where clause matches more than once' : 'The patch where clause does not match the resource', 409);
|
|
153
|
+
bindings = found[0];
|
|
154
|
+
}
|
|
155
|
+
const blankMap = new Map();
|
|
156
|
+
const deletes = patch.deletes.map((q) => substitute(q, bindings, blankMap));
|
|
157
|
+
const inserts = patch.inserts.map((q) => substitute(q, bindings, blankMap));
|
|
158
|
+
let result = [...quads];
|
|
159
|
+
for (const d of deletes) {
|
|
160
|
+
const at = result.findIndex((q) => q.equals(d));
|
|
161
|
+
if (at < 0) throw new PatchError(`Triple to delete not found: ${d.subject.value} ${d.predicate.value}`, 409);
|
|
162
|
+
result.splice(at, 1);
|
|
163
|
+
}
|
|
164
|
+
for (const i of inserts) if (!result.some((q) => q.equals(i))) result.push(i);
|
|
165
|
+
return result;
|
|
166
|
+
}
|
package/src/rdf/turtle.js
CHANGED
|
Binary file
|
package/src/server.js
CHANGED
|
@@ -8,10 +8,11 @@ import { STATUS_CODES } from 'node:http';
|
|
|
8
8
|
import { join, dirname } from 'path';
|
|
9
9
|
import { fileURLToPath } from 'url';
|
|
10
10
|
import { handleGet, handleHead, handlePut, handleDelete, handleOptions, handlePatch } from './handlers/resource.js';
|
|
11
|
+
import { parsePatch, isInsertOnly } from './patch/quads.js';
|
|
11
12
|
import { handlePost, handleCreatePod, createPodStructure } from './handlers/container.js';
|
|
12
13
|
import * as storage from './storage/filesystem.js';
|
|
13
14
|
import { getCorsHeaders } from './ldp/headers.js';
|
|
14
|
-
import { authorize, handleUnauthorized } from './auth/middleware.js';
|
|
15
|
+
import { authorize, handleUnauthorized, buildResourceUrl } from './auth/middleware.js';
|
|
15
16
|
import { notificationsPlugin } from './notifications/index.js';
|
|
16
17
|
import { startFileWatcher } from './notifications/events.js';
|
|
17
18
|
import { idpPlugin } from './idp/index.js';
|
|
@@ -804,7 +805,22 @@ export function createServer(options = {}) {
|
|
|
804
805
|
return;
|
|
805
806
|
}
|
|
806
807
|
|
|
807
|
-
|
|
808
|
+
// A PATCH that only adds triples (no deletes, no where clause) needs
|
|
809
|
+
// acl:Append, not acl:Write: Solid Protocol §Writing Resources. This is
|
|
810
|
+
// what lets a chat room grant the public Append so anyone can post but
|
|
811
|
+
// nobody can rewrite or remove what others wrote.
|
|
812
|
+
const authOptions = {};
|
|
813
|
+
if (request.method === 'PATCH') {
|
|
814
|
+
try {
|
|
815
|
+
const body = Buffer.isBuffer(request.body) ? request.body.toString() : String(request.body ?? '');
|
|
816
|
+
const parsed = parsePatch(body, request.headers['content-type'] || '', buildResourceUrl(request, request.url.split('?')[0]));
|
|
817
|
+
request.parsedPatch = parsed;
|
|
818
|
+
if (isInsertOnly(parsed)) authOptions.requiredMode = AccessMode.APPEND;
|
|
819
|
+
} catch {
|
|
820
|
+
// Malformed patches are reported by the handler; authorize as Write.
|
|
821
|
+
}
|
|
822
|
+
}
|
|
823
|
+
const { authorized, webId, wacAllow, authError, paymentRequired, paid, balance, currency } = await authorize(request, reply, authOptions);
|
|
808
824
|
|
|
809
825
|
// Store webId and wacAllow on request for handlers to use
|
|
810
826
|
request.webId = webId;
|
|
@@ -132,6 +132,52 @@ export async function write(urlPath, content, options = {}) {
|
|
|
132
132
|
}
|
|
133
133
|
}
|
|
134
134
|
|
|
135
|
+
// ---------- Cross-process resource locks ----------
|
|
136
|
+
// A read-modify-write (PATCH) must not interleave with another on the same file. The
|
|
137
|
+
// in-process queue in the PATCH handler covers one Node process; this lock file covers
|
|
138
|
+
// several processes sharing the data directory (PM2 cluster, instances behind a proxy).
|
|
139
|
+
// The lock is `.<name>.lock` next to the file (a dotfile, so never listed or served),
|
|
140
|
+
// created with O_EXCL. A lock older than LOCK_STALE_MS belongs to a crashed process and
|
|
141
|
+
// is broken.
|
|
142
|
+
const LOCK_STALE_MS = 15000;
|
|
143
|
+
const LOCK_WAIT_MS = 30000;
|
|
144
|
+
|
|
145
|
+
export function lockPathFor(urlPath) {
|
|
146
|
+
const filePath = urlToPath(urlPath);
|
|
147
|
+
return path.join(path.dirname(filePath), `.${path.basename(filePath)}.lock`);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
export async function withLock(urlPath, fn) {
|
|
151
|
+
const lockPath = lockPathFor(urlPath);
|
|
152
|
+
await fs.ensureDir(path.dirname(lockPath));
|
|
153
|
+
const started = Date.now();
|
|
154
|
+
for (;;) {
|
|
155
|
+
try {
|
|
156
|
+
const fd = await fs.open(lockPath, 'wx');
|
|
157
|
+
await fs.close(fd);
|
|
158
|
+
break;
|
|
159
|
+
} catch (err) {
|
|
160
|
+
if (err.code !== 'EEXIST') throw err;
|
|
161
|
+
const stat = await fs.stat(lockPath).catch(() => null);
|
|
162
|
+
if (stat && Date.now() - stat.mtimeMs > LOCK_STALE_MS) {
|
|
163
|
+
await fs.remove(lockPath).catch(() => {});
|
|
164
|
+
continue;
|
|
165
|
+
}
|
|
166
|
+
if (Date.now() - started > LOCK_WAIT_MS) {
|
|
167
|
+
const e = new Error('Resource is locked by another writer');
|
|
168
|
+
e.code = 'ELOCKED';
|
|
169
|
+
throw e;
|
|
170
|
+
}
|
|
171
|
+
await new Promise((resolve) => setTimeout(resolve, 10 + Math.random() * 40));
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
try {
|
|
175
|
+
return await fn();
|
|
176
|
+
} finally {
|
|
177
|
+
await fs.remove(lockPath).catch(() => {});
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
135
181
|
/**
|
|
136
182
|
* Delete resource
|
|
137
183
|
* @param {string} urlPath
|
package/src/wac/parser.js
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
* Parses ACL files (JSON-LD or Turtle) into authorization rules
|
|
4
4
|
*/
|
|
5
5
|
|
|
6
|
-
import { turtleToJsonLd } from '../rdf/turtle.js';
|
|
6
|
+
import { turtleToJsonLd, expandUri } from '../rdf/turtle.js';
|
|
7
7
|
import { safeJsonParse } from '../utils/url.js';
|
|
8
8
|
|
|
9
9
|
const ACL = 'http://www.w3.org/ns/auth/acl#';
|
|
@@ -57,9 +57,17 @@ export async function parseAcl(content, aclUrl) {
|
|
|
57
57
|
// Handle @graph array or single object
|
|
58
58
|
const nodes = Array.isArray(doc) ? doc : (doc['@graph'] || [doc]);
|
|
59
59
|
|
|
60
|
+
// The document's @context (plus any node-level @context) decides what the
|
|
61
|
+
// keys mean. Contexts are merged leniently across the whole document, as
|
|
62
|
+
// jsonLdToTurtle does; remote context URLs are never fetched (#389).
|
|
63
|
+
const docContext = mergeContext({}, Array.isArray(doc) ? undefined : doc['@context']);
|
|
64
|
+
|
|
60
65
|
for (const node of nodes) {
|
|
61
|
-
if (
|
|
62
|
-
|
|
66
|
+
if (!node || typeof node !== 'object') continue;
|
|
67
|
+
const context = mergeContext(docContext, node['@context']);
|
|
68
|
+
const expanded = expandNode(node, context);
|
|
69
|
+
if (isAuthorization(expanded, context)) {
|
|
70
|
+
const auth = parseAuthorization(expanded, context, aclUrl);
|
|
63
71
|
if (auth) {
|
|
64
72
|
authorizations.push(auth);
|
|
65
73
|
}
|
|
@@ -69,18 +77,89 @@ export async function parseAcl(content, aclUrl) {
|
|
|
69
77
|
return authorizations;
|
|
70
78
|
}
|
|
71
79
|
|
|
80
|
+
/**
|
|
81
|
+
* Merge a JSON-LD @context value (object, or array of objects / strings) into
|
|
82
|
+
* an accumulated context object. String entries (remote contexts) are skipped
|
|
83
|
+
* on purpose — JSS never dereferences contexts at parse time (#389).
|
|
84
|
+
*/
|
|
85
|
+
function mergeContext(base, ctx) {
|
|
86
|
+
if (!ctx) return base;
|
|
87
|
+
const entries = Array.isArray(ctx) ? ctx : [ctx];
|
|
88
|
+
let merged = base;
|
|
89
|
+
for (const entry of entries) {
|
|
90
|
+
if (entry && typeof entry === 'object' && !Array.isArray(entry)) {
|
|
91
|
+
merged = { ...merged, ...entry };
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
return merged;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Expand a property key or @type value to a full IRI. Falls back to @vocab
|
|
99
|
+
* for bare terms the context doesn't define.
|
|
100
|
+
*/
|
|
101
|
+
function expandTerm(term, context) {
|
|
102
|
+
if (typeof term !== 'string' || !term) return term;
|
|
103
|
+
const expanded = expandUri(term, context);
|
|
104
|
+
if (expanded === term && !term.includes(':') && typeof context['@vocab'] === 'string') {
|
|
105
|
+
return context['@vocab'] + term;
|
|
106
|
+
}
|
|
107
|
+
return expanded;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Return a view of the node keyed by full predicate IRIs (#631). Keyword
|
|
112
|
+
* entries (`@id`, `@type`, …) are kept as-is. Keys that expand to the same
|
|
113
|
+
* IRI (e.g. `acl:mode` and the expanded form in one node) are concatenated.
|
|
114
|
+
*/
|
|
115
|
+
function expandNode(node, context) {
|
|
116
|
+
const out = {};
|
|
117
|
+
for (const [key, value] of Object.entries(node)) {
|
|
118
|
+
const iri = key.startsWith('@') ? key : expandTerm(key, context);
|
|
119
|
+
if (iri in out && !key.startsWith('@')) {
|
|
120
|
+
out[iri] = [].concat(out[iri], value);
|
|
121
|
+
} else {
|
|
122
|
+
out[iri] = value;
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
return out;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* Read an ACL property from an expanded node. The full IRI is what a
|
|
130
|
+
* correctly-expanded key becomes; the `acl:`-prefixed and bare forms are
|
|
131
|
+
* kept as fallbacks for documents without any usable context.
|
|
132
|
+
*/
|
|
133
|
+
function aclProp(node, term) {
|
|
134
|
+
return node[`${ACL}${term}`] ?? node[`acl:${term}`] ?? node[term];
|
|
135
|
+
}
|
|
136
|
+
|
|
72
137
|
/**
|
|
73
138
|
* Check if node is an Authorization
|
|
74
139
|
*/
|
|
75
|
-
function isAuthorization(node) {
|
|
140
|
+
function isAuthorization(node, context = {}) {
|
|
76
141
|
const type = node['@type'];
|
|
77
142
|
if (!type) return false;
|
|
78
143
|
|
|
79
144
|
const types = Array.isArray(type) ? type : [type];
|
|
80
|
-
return types.some(t =>
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
145
|
+
return types.some(t => {
|
|
146
|
+
const full = expandTerm(t, context);
|
|
147
|
+
return full === `${ACL}Authorization` || t === 'Authorization';
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* True when at least one authorization can grant something: it names a mode
|
|
153
|
+
* and an agent, agent class or group. An ACL for which this is false grants
|
|
154
|
+
* nobody access, including the writer, so writes that would leave a resource
|
|
155
|
+
* with such an ACL are refused (#631).
|
|
156
|
+
* @param {Array<Authorization>} authorizations
|
|
157
|
+
* @returns {boolean}
|
|
158
|
+
*/
|
|
159
|
+
export function grantsAccess(authorizations) {
|
|
160
|
+
return authorizations.some(a =>
|
|
161
|
+
a.modes.length > 0 &&
|
|
162
|
+
(a.agents.length > 0 || a.agentClasses.length > 0 || a.agentGroups.length > 0)
|
|
84
163
|
);
|
|
85
164
|
}
|
|
86
165
|
|
|
@@ -123,8 +202,9 @@ function resolveUri(uri, baseUrl) {
|
|
|
123
202
|
/**
|
|
124
203
|
* Parse a single Authorization node
|
|
125
204
|
*/
|
|
126
|
-
function parseAuthorization(node, aclUrl) {
|
|
205
|
+
function parseAuthorization(node, context, aclUrl) {
|
|
127
206
|
const baseUrl = getBaseUrl(aclUrl);
|
|
207
|
+
const uris = term => parseUriArray(aclProp(node, term)).map(u => expandUri(u, context));
|
|
128
208
|
|
|
129
209
|
const auth = {
|
|
130
210
|
id: node['@id'],
|
|
@@ -138,28 +218,25 @@ function parseAuthorization(node, aclUrl) {
|
|
|
138
218
|
};
|
|
139
219
|
|
|
140
220
|
// Parse accessTo - resolve relative URLs
|
|
141
|
-
auth.accessTo =
|
|
142
|
-
.map(uri => resolveUri(uri, baseUrl));
|
|
221
|
+
auth.accessTo = uris('accessTo').map(uri => resolveUri(uri, baseUrl));
|
|
143
222
|
|
|
144
223
|
// Parse default (for containers) - resolve relative URLs
|
|
145
|
-
auth.default =
|
|
146
|
-
.map(uri => resolveUri(uri, baseUrl));
|
|
224
|
+
auth.default = uris('default').map(uri => resolveUri(uri, baseUrl));
|
|
147
225
|
|
|
148
226
|
// Parse agents (WebIDs can be relative too) - resolve against ACL URL
|
|
149
|
-
auth.agents =
|
|
150
|
-
.map(uri => resolveUri(uri, aclUrl));
|
|
227
|
+
auth.agents = uris('agent').map(uri => resolveUri(uri, aclUrl));
|
|
151
228
|
|
|
152
229
|
// Parse agentClass
|
|
153
|
-
auth.agentClasses =
|
|
230
|
+
auth.agentClasses = uris('agentClass');
|
|
154
231
|
|
|
155
232
|
// Parse agentGroup
|
|
156
|
-
auth.agentGroups =
|
|
233
|
+
auth.agentGroups = uris('agentGroup');
|
|
157
234
|
|
|
158
235
|
// Parse modes
|
|
159
|
-
auth.modes =
|
|
236
|
+
auth.modes = uris('mode').map(normalizeMode);
|
|
160
237
|
|
|
161
238
|
// Parse conditions
|
|
162
|
-
auth.conditions = parseConditions(node
|
|
239
|
+
auth.conditions = parseConditions(aclProp(node, 'condition'));
|
|
163
240
|
|
|
164
241
|
return auth;
|
|
165
242
|
}
|
package/test/patch.test.js
CHANGED
|
@@ -4,6 +4,8 @@
|
|
|
4
4
|
|
|
5
5
|
import { describe, it, before, after } from 'node:test';
|
|
6
6
|
import assert from 'node:assert';
|
|
7
|
+
import fs from 'fs-extra';
|
|
8
|
+
import path from 'path';
|
|
7
9
|
import {
|
|
8
10
|
startTestServer,
|
|
9
11
|
stopTestServer,
|
|
@@ -228,7 +230,7 @@ describe('PATCH Operations', () => {
|
|
|
228
230
|
assert.ok(node, 'Should have the reg1 node');
|
|
229
231
|
|
|
230
232
|
// Check rdf:type value (from 'a' keyword)
|
|
231
|
-
const rdfType = node['rdf:type'] || node['http://www.w3.org/1999/02/22-rdf-syntax-ns#type'];
|
|
233
|
+
const rdfType = node['@type'] || node['rdf:type'] || node['http://www.w3.org/1999/02/22-rdf-syntax-ns#type'];
|
|
232
234
|
assert.ok(rdfType, 'Should have rdf:type (from "a" keyword)');
|
|
233
235
|
const typeId = rdfType['@id'] || rdfType;
|
|
234
236
|
assert.ok(String(typeId).includes('TypeRegistration'), `rdf:type should be TypeRegistration, got ${typeId}`);
|
|
@@ -248,6 +250,205 @@ describe('PATCH Operations', () => {
|
|
|
248
250
|
});
|
|
249
251
|
});
|
|
250
252
|
|
|
253
|
+
describe('Quad-based patching (chat files)', () => {
|
|
254
|
+
const base = () => `${getBaseUrl()}/patchtest/public/chat.ttl`;
|
|
255
|
+
|
|
256
|
+
it('creates a resource with typed literals, prefixed names and multi-line strings intact', async () => {
|
|
257
|
+
const patch = `
|
|
258
|
+
@prefix solid: <http://www.w3.org/ns/solid/terms#>.
|
|
259
|
+
@prefix dct: <http://purl.org/dc/terms/>.
|
|
260
|
+
@prefix sioc: <http://rdfs.org/sioc/ns#>.
|
|
261
|
+
@prefix foaf: <http://xmlns.com/foaf/0.1/>.
|
|
262
|
+
@prefix wf: <http://www.w3.org/2005/01/wf/flow#>.
|
|
263
|
+
@prefix xsd: <http://www.w3.org/2001/XMLSchema#>.
|
|
264
|
+
_:p a solid:InsertDeletePatch; solid:inserts {
|
|
265
|
+
<index.ttl#this> wf:message <#m1>.
|
|
266
|
+
<#m1> dct:created "2026-10-22T10:00:00Z"^^xsd:dateTime;
|
|
267
|
+
sioc:content \"\"\"two lines; with a dot.
|
|
268
|
+
and a "quote" end\"\"\";
|
|
269
|
+
foaf:maker <did:nostr:5a3f1927662535ffee11f2457200f0fe6ea3fcd7b00aee4771855eda74944ede>.
|
|
270
|
+
}.`;
|
|
271
|
+
const res = await request('/patchtest/public/chat.ttl', {
|
|
272
|
+
method: 'PATCH', headers: { 'Content-Type': 'text/n3' }, body: patch, auth: 'patchtest'
|
|
273
|
+
});
|
|
274
|
+
assertStatus(res, 201);
|
|
275
|
+
|
|
276
|
+
// The test server runs without conneg, so read the stored JSON-LD.
|
|
277
|
+
const json = await (await request('/patchtest/public/chat.ttl')).json();
|
|
278
|
+
const nodes = json['@graph'] || [json];
|
|
279
|
+
const node = nodes.find(n => String(n['@id']).includes('#m1'));
|
|
280
|
+
assert.ok(node, 'message node stored');
|
|
281
|
+
assert.deepStrictEqual(node['dc:created'], { '@value': '2026-10-22T10:00:00Z', '@type': 'xsd:dateTime' }, 'typed literal kept');
|
|
282
|
+
assert.strictEqual(node['http://rdfs.org/sioc/ns#content'], 'two lines; with a dot.\nand a "quote" end', 'multi-line content kept');
|
|
283
|
+
assert.strictEqual(node['foaf:maker']['@id'], 'did:nostr:5a3f1927662535ffee11f2457200f0fe6ea3fcd7b00aee4771855eda74944ede', 'maker kept');
|
|
284
|
+
const chat = nodes.find(n => String(n['@id']).includes('index.ttl#this'));
|
|
285
|
+
assert.ok(chat && chat['http://www.w3.org/2005/01/wf/flow#message'], 'relative IRI resolved against the resource and link kept');
|
|
286
|
+
});
|
|
287
|
+
|
|
288
|
+
it('appends to an existing day file without touching other messages', async () => {
|
|
289
|
+
const patch = `
|
|
290
|
+
@prefix solid: <http://www.w3.org/ns/solid/terms#>.
|
|
291
|
+
@prefix sioc: <http://rdfs.org/sioc/ns#>.
|
|
292
|
+
_:p a solid:InsertDeletePatch; solid:inserts { <#m2> sioc:content "second" }.`;
|
|
293
|
+
const res = await request('/patchtest/public/chat.ttl', {
|
|
294
|
+
method: 'PATCH', headers: { 'Content-Type': 'text/n3' }, body: patch, auth: 'patchtest'
|
|
295
|
+
});
|
|
296
|
+
assertStatus(res, 204);
|
|
297
|
+
const text = JSON.stringify(await (await request('/patchtest/public/chat.ttl')).json());
|
|
298
|
+
assert.ok(text.includes('"second"'), 'new message present');
|
|
299
|
+
assert.ok(text.includes('2026-10-22T10:00:00Z'), 'earlier message still present');
|
|
300
|
+
});
|
|
301
|
+
|
|
302
|
+
it('applies a where clause once and rejects a non-matching one with 409', async () => {
|
|
303
|
+
const edit = (old, text) => `
|
|
304
|
+
@prefix solid: <http://www.w3.org/ns/solid/terms#>.
|
|
305
|
+
@prefix sioc: <http://rdfs.org/sioc/ns#>.
|
|
306
|
+
_:p a solid:InsertDeletePatch;
|
|
307
|
+
solid:where { <#m2> sioc:content ?old };
|
|
308
|
+
solid:deletes { <#m2> sioc:content ?old };
|
|
309
|
+
solid:inserts { <#m2> sioc:content "${text}" }.`;
|
|
310
|
+
const res = await request('/patchtest/public/chat.ttl', {
|
|
311
|
+
method: 'PATCH', headers: { 'Content-Type': 'text/n3' }, body: edit('second', 'second, edited'), auth: 'patchtest'
|
|
312
|
+
});
|
|
313
|
+
assertStatus(res, 204);
|
|
314
|
+
const text = JSON.stringify(await (await request('/patchtest/public/chat.ttl')).json());
|
|
315
|
+
assert.ok(text.includes('"second, edited"') && !text.includes('"second"'), 'content replaced');
|
|
316
|
+
|
|
317
|
+
const miss = `
|
|
318
|
+
@prefix solid: <http://www.w3.org/ns/solid/terms#>.
|
|
319
|
+
@prefix sioc: <http://rdfs.org/sioc/ns#>.
|
|
320
|
+
_:p a solid:InsertDeletePatch;
|
|
321
|
+
solid:where { <#nope> sioc:content ?old };
|
|
322
|
+
solid:deletes { <#nope> sioc:content ?old }.`;
|
|
323
|
+
const bad = await request('/patchtest/public/chat.ttl', {
|
|
324
|
+
method: 'PATCH', headers: { 'Content-Type': 'text/n3' }, body: miss, auth: 'patchtest'
|
|
325
|
+
});
|
|
326
|
+
assertStatus(bad, 409);
|
|
327
|
+
});
|
|
328
|
+
|
|
329
|
+
it('rejects a delete of a triple that is not there with 409', async () => {
|
|
330
|
+
const patch = `
|
|
331
|
+
@prefix solid: <http://www.w3.org/ns/solid/terms#>.
|
|
332
|
+
@prefix sioc: <http://rdfs.org/sioc/ns#>.
|
|
333
|
+
_:p a solid:InsertDeletePatch; solid:deletes { <#m2> sioc:content "never" }.`;
|
|
334
|
+
const res = await request('/patchtest/public/chat.ttl', {
|
|
335
|
+
method: 'PATCH', headers: { 'Content-Type': 'text/n3' }, body: patch, auth: 'patchtest'
|
|
336
|
+
});
|
|
337
|
+
assertStatus(res, 409);
|
|
338
|
+
});
|
|
339
|
+
|
|
340
|
+
it('lets the public append (insert-only) under acl:Append but not delete', async () => {
|
|
341
|
+
const acl = {
|
|
342
|
+
'@context': { acl: 'http://www.w3.org/ns/auth/acl#', foaf: 'http://xmlns.com/foaf/0.1/' },
|
|
343
|
+
'@graph': [
|
|
344
|
+
{ '@id': '#owner', '@type': 'acl:Authorization', 'acl:agent': { '@id': `${getBaseUrl()}/patchtest/profile/card.jsonld#me` },
|
|
345
|
+
'acl:accessTo': { '@id': './' }, 'acl:default': { '@id': './' },
|
|
346
|
+
'acl:mode': [{ '@id': 'acl:Read' }, { '@id': 'acl:Write' }, { '@id': 'acl:Control' }] },
|
|
347
|
+
{ '@id': '#public', '@type': 'acl:Authorization', 'acl:agentClass': { '@id': 'foaf:Agent' },
|
|
348
|
+
'acl:accessTo': { '@id': './' }, 'acl:default': { '@id': './' },
|
|
349
|
+
'acl:mode': [{ '@id': 'acl:Read' }, { '@id': 'acl:Append' }] }
|
|
350
|
+
]
|
|
351
|
+
};
|
|
352
|
+
let res = await request('/patchtest/public/room/.acl', {
|
|
353
|
+
method: 'PUT', headers: { 'Content-Type': 'application/ld+json' }, body: JSON.stringify(acl), auth: 'patchtest'
|
|
354
|
+
});
|
|
355
|
+
assert.ok([200, 201, 204].includes(res.status), `acl stored: ${res.status}`);
|
|
356
|
+
|
|
357
|
+
const insert = `
|
|
358
|
+
@prefix solid: <http://www.w3.org/ns/solid/terms#>.
|
|
359
|
+
@prefix sioc: <http://rdfs.org/sioc/ns#>.
|
|
360
|
+
_:p a solid:InsertDeletePatch; solid:inserts { <#a1> sioc:content "anonymous append" }.`;
|
|
361
|
+
res = await request('/patchtest/public/room/2026/10/22/chat.ttl', {
|
|
362
|
+
method: 'PATCH', headers: { 'Content-Type': 'text/n3' }, body: insert
|
|
363
|
+
});
|
|
364
|
+
assertStatus(res, 201, 'public append creates the day file');
|
|
365
|
+
res = await request('/patchtest/public/room/2026/10/22/chat.ttl', {
|
|
366
|
+
method: 'PATCH', headers: { 'Content-Type': 'text/n3' }, body: insert.replace('#a1', '#a2')
|
|
367
|
+
});
|
|
368
|
+
assertStatus(res, 204, 'public append to an existing day file');
|
|
369
|
+
|
|
370
|
+
const remove = `
|
|
371
|
+
@prefix solid: <http://www.w3.org/ns/solid/terms#>.
|
|
372
|
+
@prefix sioc: <http://rdfs.org/sioc/ns#>.
|
|
373
|
+
_:p a solid:InsertDeletePatch; solid:deletes { <#a1> sioc:content "anonymous append" }.`;
|
|
374
|
+
res = await request('/patchtest/public/room/2026/10/22/chat.ttl', {
|
|
375
|
+
method: 'PATCH', headers: { 'Content-Type': 'text/n3' }, body: remove
|
|
376
|
+
});
|
|
377
|
+
assertStatus(res, 401, 'deleting needs Write');
|
|
378
|
+
const text = JSON.stringify(await (await request('/patchtest/public/room/2026/10/22/chat.ttl')).json());
|
|
379
|
+
assert.ok(text.includes('#a1') && text.includes('#a2'), 'both appends kept');
|
|
380
|
+
});
|
|
381
|
+
});
|
|
382
|
+
|
|
383
|
+
describe('Concurrent patches', () => {
|
|
384
|
+
it('applies simultaneous appends to one resource without losing any', async () => {
|
|
385
|
+
const patch = (i) => `
|
|
386
|
+
@prefix solid: <http://www.w3.org/ns/solid/terms#>.
|
|
387
|
+
@prefix sioc: <http://rdfs.org/sioc/ns#>.
|
|
388
|
+
_:p a solid:InsertDeletePatch; solid:inserts { <#c${i}> sioc:content "message ${i}" }.`;
|
|
389
|
+
const results = await Promise.all(Array.from({ length: 12 }, (_, i) => request('/patchtest/public/concurrent.ttl', {
|
|
390
|
+
method: 'PATCH', headers: { 'Content-Type': 'text/n3' }, body: patch(i), auth: 'patchtest'
|
|
391
|
+
})));
|
|
392
|
+
for (const res of results) assert.ok([201, 204].includes(res.status), `status ${res.status}`);
|
|
393
|
+
const text = await (await request('/patchtest/public/concurrent.ttl')).text();
|
|
394
|
+
const doc = JSON.parse(text); // a half-overwritten file would not parse
|
|
395
|
+
const ids = (doc['@graph'] || [doc]).map(n => n['@id']);
|
|
396
|
+
for (let i = 0; i < 12; i++) assert.ok(ids.some(id => id.endsWith(`#c${i}`)), `message ${i} kept`);
|
|
397
|
+
});
|
|
398
|
+
});
|
|
399
|
+
|
|
400
|
+
describe('Empty formulas', () => {
|
|
401
|
+
it('treats an empty solid:deletes block as a no-op instead of failing', async () => {
|
|
402
|
+
const patch = `
|
|
403
|
+
@prefix solid: <http://www.w3.org/ns/solid/terms#>.
|
|
404
|
+
_:p a solid:InsertDeletePatch; solid:deletes { } ; solid:inserts { <#e1> <http://example.org/p> "x" }.`;
|
|
405
|
+
const res = await request('/patchtest/public/empty-formula.ttl', {
|
|
406
|
+
method: 'PATCH', headers: { 'Content-Type': 'text/n3' }, body: patch, auth: 'patchtest'
|
|
407
|
+
});
|
|
408
|
+
assertStatus(res, 201);
|
|
409
|
+
const empty = `
|
|
410
|
+
@prefix solid: <http://www.w3.org/ns/solid/terms#>.
|
|
411
|
+
_:p a solid:InsertDeletePatch; solid:deletes {
|
|
412
|
+
}.`;
|
|
413
|
+
const again = await request('/patchtest/public/empty-formula.ttl', {
|
|
414
|
+
method: 'PATCH', headers: { 'Content-Type': 'text/n3' }, body: empty, auth: 'patchtest'
|
|
415
|
+
});
|
|
416
|
+
assertStatus(again, 204);
|
|
417
|
+
});
|
|
418
|
+
});
|
|
419
|
+
|
|
420
|
+
describe('Cross-process lock file', () => {
|
|
421
|
+
const lockFile = path.join('./data', 'patchtest', 'public', '.locked.ttl.lock');
|
|
422
|
+
const patch = (i) => `
|
|
423
|
+
@prefix solid: <http://www.w3.org/ns/solid/terms#>.
|
|
424
|
+
_:p a solid:InsertDeletePatch; solid:inserts { <#l${i}> <http://example.org/p> "x" }.`;
|
|
425
|
+
const send = (i) => request('/patchtest/public/locked.ttl', {
|
|
426
|
+
method: 'PATCH', headers: { 'Content-Type': 'text/n3' }, body: patch(i), auth: 'patchtest'
|
|
427
|
+
});
|
|
428
|
+
|
|
429
|
+
it('waits for a lock held by another writer and proceeds once it is released', async () => {
|
|
430
|
+
await fs.ensureFile(lockFile);
|
|
431
|
+
const pending = send(1).then(res => ({ res }));
|
|
432
|
+
const early = await Promise.race([pending, new Promise(r => setTimeout(() => r('still waiting'), 400))]);
|
|
433
|
+
assert.strictEqual(early, 'still waiting', 'the patch does not run while the lock is held');
|
|
434
|
+
await fs.remove(lockFile);
|
|
435
|
+
const { res } = await pending;
|
|
436
|
+
assertStatus(res, 201);
|
|
437
|
+
await new Promise(r => setTimeout(r, 100)); // the handler releases just after replying
|
|
438
|
+
assert.ok(!(await fs.pathExists(lockFile)), 'the lock is released afterwards');
|
|
439
|
+
});
|
|
440
|
+
|
|
441
|
+
it('breaks a stale lock left by a crashed process', async () => {
|
|
442
|
+
await fs.ensureFile(lockFile);
|
|
443
|
+
const old = new Date(Date.now() - 60000);
|
|
444
|
+
await fs.utimes(lockFile, old, old);
|
|
445
|
+
const res = await send(2);
|
|
446
|
+
assertStatus(res, 204);
|
|
447
|
+
await new Promise(r => setTimeout(r, 100));
|
|
448
|
+
assert.ok(!(await fs.pathExists(lockFile)), 'the stale lock is gone');
|
|
449
|
+
});
|
|
450
|
+
});
|
|
451
|
+
|
|
251
452
|
describe('PATCH Error Handling', () => {
|
|
252
453
|
it('should return 415 for unsupported content type', async () => {
|
|
253
454
|
// Create a resource first
|
package/test/wac.test.js
CHANGED
|
@@ -81,7 +81,7 @@ describe('WAC Parser', () => {
|
|
|
81
81
|
assert.ok(ownerAuth.modes.includes(AccessMode.WRITE));
|
|
82
82
|
assert.ok(ownerAuth.modes.includes(AccessMode.CONTROL));
|
|
83
83
|
// Check public authorization
|
|
84
|
-
const publicAuth = auths.find(a => a.agentClasses.includes('foaf
|
|
84
|
+
const publicAuth = auths.find(a => a.agentClasses.includes('http://xmlns.com/foaf/0.1/Agent'));
|
|
85
85
|
assert.ok(publicAuth, 'Should have public authorization');
|
|
86
86
|
assert.ok(publicAuth.modes.includes(AccessMode.READ));
|
|
87
87
|
});
|
|
@@ -101,7 +101,7 @@ describe('WAC Parser', () => {
|
|
|
101
101
|
const auths = await parseAcl(JSON.stringify(acl), 'https://alice.example/public/.acl');
|
|
102
102
|
|
|
103
103
|
assert.strictEqual(auths.length, 1);
|
|
104
|
-
assert.ok(auths[0].agentClasses.includes('foaf
|
|
104
|
+
assert.ok(auths[0].agentClasses.includes('http://xmlns.com/foaf/0.1/Agent'));
|
|
105
105
|
assert.ok(auths[0].modes.includes(AccessMode.READ));
|
|
106
106
|
});
|
|
107
107
|
|
|
@@ -444,8 +444,8 @@ describe('WAC Parser', () => {
|
|
|
444
444
|
const auths1 = await parseAcl(wire, 'http://localhost:4444/.acl');
|
|
445
445
|
const auths2 = await parseAcl(wire, 'http://0.0.0.0:4444/.acl');
|
|
446
446
|
|
|
447
|
-
const pub1 = auths1.find(a => a.agentClasses.includes('foaf
|
|
448
|
-
const pub2 = auths2.find(a => a.agentClasses.includes('foaf
|
|
447
|
+
const pub1 = auths1.find(a => a.agentClasses.includes('http://xmlns.com/foaf/0.1/Agent'));
|
|
448
|
+
const pub2 = auths2.find(a => a.agentClasses.includes('http://xmlns.com/foaf/0.1/Agent'));
|
|
449
449
|
assert.ok(pub1.accessTo.includes('http://localhost:4444/'),
|
|
450
450
|
`Expected localhost resolution, got: ${JSON.stringify(pub1.accessTo)}`);
|
|
451
451
|
assert.ok(pub2.accessTo.includes('http://0.0.0.0:4444/'),
|
|
@@ -788,3 +788,225 @@ describe('WAC PaymentCondition noDebit (secondary/guard checks must not charge)'
|
|
|
788
788
|
assert.strictEqual(await balanceNow(), 100, 'balance must be unchanged');
|
|
789
789
|
});
|
|
790
790
|
});
|
|
791
|
+
|
|
792
|
+
describe('WAC Parser: JSON-LD expansion (#631)', () => {
|
|
793
|
+
const ACL = 'http://www.w3.org/ns/auth/acl#';
|
|
794
|
+
const aclUrl = 'http://127.0.0.1:8732/me/public/doc.ttl.acl';
|
|
795
|
+
const webId = 'http://127.0.0.1:8732/me/profile/card.jsonld#me';
|
|
796
|
+
const target = 'http://127.0.0.1:8732/me/public/doc.ttl';
|
|
797
|
+
|
|
798
|
+
function expectOwner(auths) {
|
|
799
|
+
assert.strictEqual(auths.length, 1, `expected one authorization, got ${JSON.stringify(auths)}`);
|
|
800
|
+
assert.deepStrictEqual(auths[0].agents, [webId]);
|
|
801
|
+
assert.deepStrictEqual(auths[0].accessTo, [target]);
|
|
802
|
+
assert.deepStrictEqual(auths[0].modes.sort(), [AccessMode.CONTROL, AccessMode.READ, AccessMode.WRITE].sort());
|
|
803
|
+
}
|
|
804
|
+
|
|
805
|
+
it('reads an ACL in expanded form (full IRIs, no @context)', async () => {
|
|
806
|
+
const acl = [{
|
|
807
|
+
'@id': '#owner',
|
|
808
|
+
'@type': [`${ACL}Authorization`],
|
|
809
|
+
[`${ACL}agent`]: [{ '@id': webId }],
|
|
810
|
+
[`${ACL}accessTo`]: [{ '@id': target }],
|
|
811
|
+
[`${ACL}mode`]: [{ '@id': `${ACL}Read` }, { '@id': `${ACL}Write` }, { '@id': `${ACL}Control` }]
|
|
812
|
+
}];
|
|
813
|
+
expectOwner(await parseAcl(JSON.stringify(acl), aclUrl));
|
|
814
|
+
});
|
|
815
|
+
|
|
816
|
+
it('reads an ACL that uses a different prefix than acl:', async () => {
|
|
817
|
+
const acl = {
|
|
818
|
+
'@context': { wac: ACL },
|
|
819
|
+
'@graph': [{
|
|
820
|
+
'@id': '#owner',
|
|
821
|
+
'@type': 'wac:Authorization',
|
|
822
|
+
'wac:agent': { '@id': webId },
|
|
823
|
+
'wac:accessTo': { '@id': target },
|
|
824
|
+
'wac:mode': [{ '@id': 'wac:Read' }, { '@id': 'wac:Write' }, { '@id': 'wac:Control' }]
|
|
825
|
+
}]
|
|
826
|
+
};
|
|
827
|
+
expectOwner(await parseAcl(JSON.stringify(acl), aclUrl));
|
|
828
|
+
});
|
|
829
|
+
|
|
830
|
+
it('reads an ACL whose @context is an array with a remote entry', async () => {
|
|
831
|
+
const acl = {
|
|
832
|
+
'@context': ['https://www.w3.org/ns/solid/context', { auth: ACL }],
|
|
833
|
+
'@graph': [{
|
|
834
|
+
'@id': '#owner',
|
|
835
|
+
'@type': 'auth:Authorization',
|
|
836
|
+
'auth:agent': { '@id': webId },
|
|
837
|
+
'auth:accessTo': { '@id': target },
|
|
838
|
+
'auth:mode': [{ '@id': 'auth:Read' }, { '@id': 'auth:Write' }, { '@id': 'auth:Control' }]
|
|
839
|
+
}]
|
|
840
|
+
};
|
|
841
|
+
expectOwner(await parseAcl(JSON.stringify(acl), aclUrl));
|
|
842
|
+
});
|
|
843
|
+
|
|
844
|
+
it('reads an ACL that relies on @vocab and term definitions', async () => {
|
|
845
|
+
const acl = {
|
|
846
|
+
'@context': {
|
|
847
|
+
'@vocab': ACL,
|
|
848
|
+
agent: { '@id': `${ACL}agent`, '@type': '@id' },
|
|
849
|
+
accessTo: { '@id': `${ACL}accessTo`, '@type': '@id' },
|
|
850
|
+
mode: { '@id': `${ACL}mode`, '@type': '@id' }
|
|
851
|
+
},
|
|
852
|
+
'@id': '#owner',
|
|
853
|
+
'@type': 'Authorization',
|
|
854
|
+
agent: webId,
|
|
855
|
+
accessTo: target,
|
|
856
|
+
mode: ['Read', 'Write', 'Control']
|
|
857
|
+
};
|
|
858
|
+
expectOwner(await parseAcl(JSON.stringify(acl), aclUrl));
|
|
859
|
+
});
|
|
860
|
+
|
|
861
|
+
it('reads a Turtle ACL that declares a non-acl prefix', async () => {
|
|
862
|
+
const ttl = `@prefix wac: <${ACL}> .
|
|
863
|
+
<#owner> a wac:Authorization ;
|
|
864
|
+
wac:agent <${webId}> ;
|
|
865
|
+
wac:accessTo <${target}> ;
|
|
866
|
+
wac:mode wac:Read, wac:Write, wac:Control .`;
|
|
867
|
+
expectOwner(await parseAcl(ttl, aclUrl));
|
|
868
|
+
});
|
|
869
|
+
|
|
870
|
+
it('normalises agent classes to full IRIs', async () => {
|
|
871
|
+
const acl = {
|
|
872
|
+
'@context': { wac: ACL, people: 'http://xmlns.com/foaf/0.1/' },
|
|
873
|
+
'@id': '#public',
|
|
874
|
+
'@type': 'wac:Authorization',
|
|
875
|
+
'wac:agentClass': { '@id': 'people:Agent' },
|
|
876
|
+
'wac:accessTo': { '@id': target },
|
|
877
|
+
'wac:mode': { '@id': 'wac:Read' }
|
|
878
|
+
};
|
|
879
|
+
const auths = await parseAcl(JSON.stringify(acl), aclUrl);
|
|
880
|
+
assert.deepStrictEqual(auths[0].agentClasses, ['http://xmlns.com/foaf/0.1/Agent']);
|
|
881
|
+
});
|
|
882
|
+
});
|
|
883
|
+
|
|
884
|
+
describe('WAC Integration: ACL PUT guard (#631)', () => {
|
|
885
|
+
let baseUrl;
|
|
886
|
+
|
|
887
|
+
before(async () => {
|
|
888
|
+
const result = await startTestServer();
|
|
889
|
+
baseUrl = result.baseUrl;
|
|
890
|
+
await createTestPod('aclguard');
|
|
891
|
+
});
|
|
892
|
+
|
|
893
|
+
after(async () => {
|
|
894
|
+
await stopTestServer();
|
|
895
|
+
});
|
|
896
|
+
|
|
897
|
+
const ACL = 'http://www.w3.org/ns/auth/acl#';
|
|
898
|
+
|
|
899
|
+
it('accepts an expanded-form ACL and the owner keeps access', async () => {
|
|
900
|
+
const put = await request('/aclguard/public/exp.jsonld', {
|
|
901
|
+
method: 'PUT', auth: 'aclguard',
|
|
902
|
+
headers: { 'Content-Type': 'application/ld+json' },
|
|
903
|
+
body: JSON.stringify({ '@id': '', 'http://schema.org/name': 'x' })
|
|
904
|
+
});
|
|
905
|
+
assert.ok(put.status === 201 || put.status === 204, `PUT resource: ${put.status}`);
|
|
906
|
+
|
|
907
|
+
const webId = `${baseUrl}/aclguard/profile/card.jsonld#me`;
|
|
908
|
+
const acl = [{
|
|
909
|
+
'@id': '#owner',
|
|
910
|
+
'@type': [`${ACL}Authorization`],
|
|
911
|
+
[`${ACL}agent`]: [{ '@id': webId }],
|
|
912
|
+
[`${ACL}accessTo`]: [{ '@id': `${baseUrl}/aclguard/public/exp.jsonld` }],
|
|
913
|
+
[`${ACL}mode`]: [{ '@id': `${ACL}Read` }, { '@id': `${ACL}Write` }, { '@id': `${ACL}Control` }]
|
|
914
|
+
}];
|
|
915
|
+
const putAcl = await request('/aclguard/public/exp.jsonld.acl', {
|
|
916
|
+
method: 'PUT', auth: 'aclguard',
|
|
917
|
+
headers: { 'Content-Type': 'application/ld+json' },
|
|
918
|
+
body: JSON.stringify(acl)
|
|
919
|
+
});
|
|
920
|
+
assert.ok(putAcl.status === 201 || putAcl.status === 204, `PUT acl: ${putAcl.status}`);
|
|
921
|
+
|
|
922
|
+
assertStatus(await request('/aclguard/public/exp.jsonld', { auth: 'aclguard' }), 200);
|
|
923
|
+
assertStatus(await request('/aclguard/public/exp.jsonld.acl', { auth: 'aclguard' }), 200);
|
|
924
|
+
// The expanded ACL grants nothing to the public.
|
|
925
|
+
assertStatus(await request('/aclguard/public/exp.jsonld'), 401);
|
|
926
|
+
});
|
|
927
|
+
|
|
928
|
+
it('rejects an ACL document that yields no authorizations', async () => {
|
|
929
|
+
const res = await request('/aclguard/public/exp.jsonld.acl', {
|
|
930
|
+
method: 'PUT', auth: 'aclguard',
|
|
931
|
+
headers: { 'Content-Type': 'application/ld+json' },
|
|
932
|
+
body: JSON.stringify({ '@context': { acl: ACL }, '@id': '#owner', 'acl:agent': { '@id': 'x' } })
|
|
933
|
+
});
|
|
934
|
+
assertStatus(res, 400);
|
|
935
|
+
const body = await res.json();
|
|
936
|
+
assert.match(body.message, /authorization/i);
|
|
937
|
+
// The previous ACL is still in place.
|
|
938
|
+
assertStatus(await request('/aclguard/public/exp.jsonld', { auth: 'aclguard' }), 200);
|
|
939
|
+
});
|
|
940
|
+
|
|
941
|
+
it('rejects an ACL whose authorizations name an agent but no mode', async () => {
|
|
942
|
+
const res = await request('/aclguard/public/exp.jsonld.acl', {
|
|
943
|
+
method: 'PUT', auth: 'aclguard',
|
|
944
|
+
headers: { 'Content-Type': 'application/ld+json' },
|
|
945
|
+
body: JSON.stringify({
|
|
946
|
+
'@context': { acl: ACL },
|
|
947
|
+
'@id': '#owner',
|
|
948
|
+
'@type': 'acl:Authorization',
|
|
949
|
+
'acl:agent': { '@id': `${baseUrl}/aclguard/profile/card.jsonld#me` },
|
|
950
|
+
'acl:accessTo': { '@id': `${baseUrl}/aclguard/public/exp.jsonld` }
|
|
951
|
+
})
|
|
952
|
+
});
|
|
953
|
+
assertStatus(res, 400);
|
|
954
|
+
assertStatus(await request('/aclguard/public/exp.jsonld', { auth: 'aclguard' }), 200);
|
|
955
|
+
});
|
|
956
|
+
|
|
957
|
+
it('rejects an ACL whose authorizations name a mode but no agent', async () => {
|
|
958
|
+
const res = await request('/aclguard/public/exp.jsonld.acl', {
|
|
959
|
+
method: 'PUT', auth: 'aclguard',
|
|
960
|
+
headers: { 'Content-Type': 'application/ld+json' },
|
|
961
|
+
body: JSON.stringify({
|
|
962
|
+
'@context': { acl: ACL },
|
|
963
|
+
'@id': '#owner',
|
|
964
|
+
'@type': 'acl:Authorization',
|
|
965
|
+
'acl:accessTo': { '@id': `${baseUrl}/aclguard/public/exp.jsonld` },
|
|
966
|
+
'acl:mode': [{ '@id': 'acl:Read' }, { '@id': 'acl:Control' }]
|
|
967
|
+
})
|
|
968
|
+
});
|
|
969
|
+
assertStatus(res, 400);
|
|
970
|
+
assertStatus(await request('/aclguard/public/exp.jsonld', { auth: 'aclguard' }), 200);
|
|
971
|
+
});
|
|
972
|
+
|
|
973
|
+
it('rejects a PATCH that would leave the ACL granting nobody access', async () => {
|
|
974
|
+
const webId = `${baseUrl}/aclguard/profile/card.jsonld#me`;
|
|
975
|
+
// Single expanded node (the N3 patch engine matches full-IRI keys and
|
|
976
|
+
// does not handle top-level arrays), so the delete below is applied.
|
|
977
|
+
const put = await request('/aclguard/public/exp.jsonld.acl', {
|
|
978
|
+
method: 'PUT', auth: 'aclguard',
|
|
979
|
+
headers: { 'Content-Type': 'application/ld+json' },
|
|
980
|
+
body: JSON.stringify({
|
|
981
|
+
'@id': '#owner',
|
|
982
|
+
'@type': `${ACL}Authorization`,
|
|
983
|
+
[`${ACL}agent`]: { '@id': webId },
|
|
984
|
+
[`${ACL}accessTo`]: { '@id': `${baseUrl}/aclguard/public/exp.jsonld` },
|
|
985
|
+
[`${ACL}mode`]: [{ '@id': `${ACL}Read` }, { '@id': `${ACL}Write` }, { '@id': `${ACL}Control` }]
|
|
986
|
+
})
|
|
987
|
+
});
|
|
988
|
+
assertStatus(put, 204);
|
|
989
|
+
const patch = `
|
|
990
|
+
@prefix solid: <http://www.w3.org/ns/solid/terms#>.
|
|
991
|
+
@prefix acl: <${ACL}>.
|
|
992
|
+
_:patch a solid:InsertDeletePatch;
|
|
993
|
+
solid:deletes { <#owner> acl:agent <${webId}> }.
|
|
994
|
+
`;
|
|
995
|
+
const res = await request('/aclguard/public/exp.jsonld.acl', {
|
|
996
|
+
method: 'PATCH', auth: 'aclguard',
|
|
997
|
+
headers: { 'Content-Type': 'text/n3' },
|
|
998
|
+
body: patch
|
|
999
|
+
});
|
|
1000
|
+
assertStatus(res, 409);
|
|
1001
|
+
assertStatus(await request('/aclguard/public/exp.jsonld', { auth: 'aclguard' }), 200);
|
|
1002
|
+
});
|
|
1003
|
+
|
|
1004
|
+
it('rejects an ACL body that is not valid JSON', async () => {
|
|
1005
|
+
const res = await request('/aclguard/public/exp.jsonld.acl', {
|
|
1006
|
+
method: 'PUT', auth: 'aclguard',
|
|
1007
|
+
headers: { 'Content-Type': 'application/ld+json' },
|
|
1008
|
+
body: '{not json'
|
|
1009
|
+
});
|
|
1010
|
+
assertStatus(res, 400);
|
|
1011
|
+
});
|
|
1012
|
+
});
|