javascript-solid-server 0.0.222 → 0.0.224
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 +122 -166
- package/src/nostr/relay.js +50 -29
- 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/test/nostr-relay-nip11.test.js +65 -0
- package/test/patch.test.js +202 -1
- package/.claude/settings.local.json +0 -38
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,7 @@ 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';
|
|
20
19
|
import { parseAcl, grantsAccess } from '../wac/parser.js';
|
|
21
20
|
|
|
22
21
|
// Shared by the PUT and PATCH guards for .acl resources (#631).
|
|
@@ -1181,10 +1180,41 @@ export async function handleOptions(request, reply) {
|
|
|
1181
1180
|
}
|
|
1182
1181
|
|
|
1183
1182
|
/**
|
|
1184
|
-
*
|
|
1185
|
-
*
|
|
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.
|
|
1186
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
|
+
|
|
1187
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) {
|
|
1188
1218
|
// Read-only mode - block all writes
|
|
1189
1219
|
if (request.config?.readOnly) {
|
|
1190
1220
|
return reply.code(405).send({ error: 'Method Not Allowed', message: 'Server is in read-only mode' });
|
|
@@ -1224,203 +1254,129 @@ export async function handlePatch(request, reply) {
|
|
|
1224
1254
|
}
|
|
1225
1255
|
}
|
|
1226
1256
|
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
|
|
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
|
|
1230
1280
|
|
|
1231
1281
|
if (resourceExists) {
|
|
1232
1282
|
const existingContent = await storage.read(storagePath);
|
|
1233
1283
|
if (existingContent === null) {
|
|
1234
1284
|
return reply.code(500).send({ error: 'Read error' });
|
|
1235
1285
|
}
|
|
1236
|
-
|
|
1237
1286
|
const contentStr = existingContent.toString();
|
|
1287
|
+
let document = null;
|
|
1238
1288
|
|
|
1239
|
-
// Check if this is HTML with embedded JSON-LD data island
|
|
1240
1289
|
if (contentStr.trimStart().startsWith('<!DOCTYPE') || contentStr.trimStart().startsWith('<html')) {
|
|
1241
|
-
// Extract JSON-LD from <script type="application/ld+json"> tag
|
|
1242
1290
|
const jsonLdMatch = contentStr.match(/<script\s+type=["']application\/ld\+json["']\s*>([\s\S]*?)<\/script>/i);
|
|
1243
|
-
|
|
1244
1291
|
if (!jsonLdMatch) {
|
|
1245
|
-
return reply.code(409).send({
|
|
1246
|
-
error: 'Conflict',
|
|
1247
|
-
message: 'HTML document does not contain a JSON-LD data island'
|
|
1248
|
-
});
|
|
1292
|
+
return reply.code(409).send({ error: 'Conflict', message: 'HTML document does not contain a JSON-LD data island' });
|
|
1249
1293
|
}
|
|
1250
|
-
|
|
1251
1294
|
try {
|
|
1252
1295
|
document = safeJsonParse(jsonLdMatch[1]);
|
|
1253
|
-
// Save the HTML parts for re-embedding after patch
|
|
1254
|
-
const jsonLdStart = contentStr.indexOf(jsonLdMatch[0]) + jsonLdMatch[0].indexOf('>') + 1;
|
|
1255
|
-
const jsonLdEnd = jsonLdStart + jsonLdMatch[1].length;
|
|
1256
|
-
htmlWrapper = {
|
|
1257
|
-
before: contentStr.substring(0, jsonLdStart),
|
|
1258
|
-
after: contentStr.substring(jsonLdEnd)
|
|
1259
|
-
};
|
|
1260
1296
|
} catch (e) {
|
|
1261
|
-
return reply.code(409).send({
|
|
1262
|
-
error: 'Conflict',
|
|
1263
|
-
message: 'HTML data island contains invalid JSON-LD'
|
|
1264
|
-
});
|
|
1297
|
+
return reply.code(409).send({ error: 'Conflict', message: 'HTML data island contains invalid JSON-LD' });
|
|
1265
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) };
|
|
1266
1301
|
} else {
|
|
1267
|
-
// Try to parse as JSON-LD first
|
|
1268
1302
|
try {
|
|
1269
1303
|
document = safeJsonParse(contentStr);
|
|
1270
1304
|
} catch (e) {
|
|
1271
|
-
// Not JSON
|
|
1272
|
-
|
|
1273
|
-
|
|
1274
|
-
|
|
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 {
|
|
1275
1309
|
const parser = new Parser({ baseIRI: resourceUrl });
|
|
1276
|
-
|
|
1277
|
-
|
|
1278
|
-
|
|
1279
|
-
|
|
1280
|
-
return reply.code(409).send({
|
|
1281
|
-
error: 'Conflict',
|
|
1282
|
-
message: 'Resource is not valid Turtle: ' + parseErr.message
|
|
1283
|
-
});
|
|
1284
|
-
}
|
|
1285
|
-
|
|
1286
|
-
// Parse the SPARQL Update
|
|
1287
|
-
const patchContent = Buffer.isBuffer(request.body) ? request.body.toString() : request.body;
|
|
1288
|
-
let update;
|
|
1289
|
-
try {
|
|
1290
|
-
update = parseSparqlUpdate(patchContent, resourceUrl);
|
|
1291
|
-
} catch (parseErr) {
|
|
1292
|
-
return reply.code(400).send({
|
|
1293
|
-
error: 'Bad Request',
|
|
1294
|
-
message: 'Invalid SPARQL Update: ' + parseErr.message
|
|
1295
|
-
});
|
|
1296
|
-
}
|
|
1297
|
-
|
|
1298
|
-
// Apply deletes
|
|
1299
|
-
for (const triple of update.deletes) {
|
|
1300
|
-
quads = quads.filter(q => {
|
|
1301
|
-
const matches = q.subject.value === triple.subject &&
|
|
1302
|
-
q.predicate.value === triple.predicate &&
|
|
1303
|
-
(q.object.value === (triple.object['@id'] || triple.object['@value'] || triple.object));
|
|
1304
|
-
return !matches;
|
|
1305
|
-
});
|
|
1306
|
-
}
|
|
1307
|
-
|
|
1308
|
-
// Apply inserts
|
|
1309
|
-
const { DataFactory } = await import('n3');
|
|
1310
|
-
const { namedNode, literal } = DataFactory;
|
|
1311
|
-
for (const triple of update.inserts) {
|
|
1312
|
-
const subj = namedNode(triple.subject);
|
|
1313
|
-
const pred = namedNode(triple.predicate);
|
|
1314
|
-
let obj;
|
|
1315
|
-
if (triple.object['@id']) {
|
|
1316
|
-
obj = namedNode(triple.object['@id']);
|
|
1317
|
-
} else if (typeof triple.object === 'string') {
|
|
1318
|
-
obj = literal(triple.object);
|
|
1319
|
-
} else {
|
|
1320
|
-
obj = literal(triple.object['@value'] || triple.object);
|
|
1321
|
-
}
|
|
1322
|
-
quads.push(DataFactory.quad(subj, pred, obj));
|
|
1323
|
-
}
|
|
1324
|
-
|
|
1325
|
-
// Serialize back to Turtle
|
|
1326
|
-
const writer = new Writer({ prefixes: {} });
|
|
1327
|
-
quads.forEach(q => writer.addQuad(q));
|
|
1328
|
-
let turtleOutput;
|
|
1329
|
-
writer.end((err, result) => { turtleOutput = result; });
|
|
1330
|
-
|
|
1331
|
-
const success = await storage.write(storagePath, Buffer.from(turtleOutput));
|
|
1332
|
-
if (!success) {
|
|
1333
|
-
return reply.code(500).send({ error: 'Write failed' });
|
|
1334
|
-
}
|
|
1335
|
-
|
|
1336
|
-
const origin = request.headers.origin;
|
|
1337
|
-
const headers = getAllHeaders({ isContainer: false, origin, resourceUrl });
|
|
1338
|
-
Object.entries(headers).forEach(([k, v]) => reply.header(k, v));
|
|
1339
|
-
|
|
1340
|
-
if (request.notificationsEnabled) {
|
|
1341
|
-
emitChange(resourceUrl);
|
|
1342
|
-
}
|
|
1343
|
-
|
|
1344
|
-
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' });
|
|
1345
1314
|
}
|
|
1315
|
+
}
|
|
1316
|
+
}
|
|
1346
1317
|
|
|
1347
|
-
|
|
1348
|
-
|
|
1349
|
-
|
|
1350
|
-
|
|
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' });
|
|
1351
1342
|
}
|
|
1352
1343
|
}
|
|
1353
|
-
} else {
|
|
1354
|
-
// Create empty JSON-LD document for new resource
|
|
1355
|
-
document = {
|
|
1356
|
-
'@context': {},
|
|
1357
|
-
'@graph': []
|
|
1358
|
-
};
|
|
1359
1344
|
}
|
|
1360
1345
|
|
|
1361
|
-
|
|
1362
|
-
|
|
1363
|
-
|
|
1364
|
-
|
|
1365
|
-
|
|
1366
|
-
|
|
1367
|
-
|
|
1368
|
-
if (isSparqlUpdate) {
|
|
1369
|
-
// Handle SPARQL Update
|
|
1370
|
-
let update;
|
|
1371
|
-
try {
|
|
1372
|
-
update = parseSparqlUpdate(patchContent, resourceUrl);
|
|
1373
|
-
} catch (e) {
|
|
1374
|
-
return reply.code(400).send({
|
|
1375
|
-
error: 'Bad Request',
|
|
1376
|
-
message: 'Invalid SPARQL Update: ' + e.message
|
|
1377
|
-
});
|
|
1378
|
-
}
|
|
1346
|
+
let updatedQuads;
|
|
1347
|
+
try {
|
|
1348
|
+
updatedQuads = applyPatch(quads, patch);
|
|
1349
|
+
} catch (e) {
|
|
1350
|
+
return patchError(e);
|
|
1351
|
+
}
|
|
1379
1352
|
|
|
1380
|
-
|
|
1381
|
-
|
|
1382
|
-
|
|
1383
|
-
|
|
1384
|
-
|
|
1385
|
-
|
|
1386
|
-
|
|
1387
|
-
|
|
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))));
|
|
1388
1361
|
} else {
|
|
1389
|
-
|
|
1390
|
-
|
|
1391
|
-
|
|
1392
|
-
|
|
1393
|
-
|
|
1394
|
-
|
|
1395
|
-
|
|
1396
|
-
message: 'Invalid N3 Patch format: ' + e.message
|
|
1397
|
-
});
|
|
1398
|
-
}
|
|
1399
|
-
|
|
1400
|
-
try {
|
|
1401
|
-
updatedDocument = applyN3Patch(document, patch, resourceUrl);
|
|
1402
|
-
} catch (e) {
|
|
1403
|
-
return reply.code(409).send({
|
|
1404
|
-
error: 'Conflict',
|
|
1405
|
-
message: 'Failed to apply patch: ' + e.message
|
|
1406
|
-
});
|
|
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) };
|
|
1407
1369
|
}
|
|
1370
|
+
updatedDocument = doc;
|
|
1371
|
+
const jsonLdStr = JSON.stringify(doc, null, 2);
|
|
1372
|
+
updatedContent = htmlWrapper ? htmlWrapper.before + '\n' + jsonLdStr + '\n ' + htmlWrapper.after : jsonLdStr;
|
|
1408
1373
|
}
|
|
1409
1374
|
|
|
1410
1375
|
// A patch must not leave an ACL that grants nobody access (#631).
|
|
1411
|
-
if (urlPath.endsWith('.acl') && !grantsAccess(await parseAcl(updatedDocument, resourceUrl))) {
|
|
1376
|
+
if (urlPath.endsWith('.acl') && updatedDocument && !grantsAccess(await parseAcl(updatedDocument, resourceUrl))) {
|
|
1412
1377
|
return reply.code(409).send({ error: 'Conflict', message: ACL_GRANTS_NOTHING });
|
|
1413
1378
|
}
|
|
1414
1379
|
|
|
1415
|
-
// Write updated document
|
|
1416
|
-
let updatedContent;
|
|
1417
|
-
if (htmlWrapper) {
|
|
1418
|
-
// Re-embed JSON-LD into HTML wrapper
|
|
1419
|
-
const jsonLdStr = JSON.stringify(updatedDocument, null, 2);
|
|
1420
|
-
updatedContent = htmlWrapper.before + '\n' + jsonLdStr + '\n ' + htmlWrapper.after;
|
|
1421
|
-
} else {
|
|
1422
|
-
updatedContent = JSON.stringify(updatedDocument, null, 2);
|
|
1423
|
-
}
|
|
1424
1380
|
const success = await storage.write(storagePath, Buffer.from(updatedContent));
|
|
1425
1381
|
|
|
1426
1382
|
if (!success) {
|
package/src/nostr/relay.js
CHANGED
|
@@ -233,34 +233,11 @@ export async function registerNostrRelay(fastify, options = {}) {
|
|
|
233
233
|
await fastify.register(websocket);
|
|
234
234
|
}
|
|
235
235
|
|
|
236
|
-
//
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
try {
|
|
242
|
-
const message = JSON.parse(data.toString());
|
|
243
|
-
const [type, value, ...rest] = message;
|
|
244
|
-
await processMessage(type, value, rest, socket);
|
|
245
|
-
} catch (e) {
|
|
246
|
-
socket.send(JSON.stringify(['NOTICE', `Error: ${e.message}`]));
|
|
247
|
-
}
|
|
248
|
-
});
|
|
249
|
-
|
|
250
|
-
socket.on('close', () => {
|
|
251
|
-
subscribers.delete(socket);
|
|
252
|
-
rateLimits.delete(socket);
|
|
253
|
-
});
|
|
254
|
-
|
|
255
|
-
socket.on('error', () => {
|
|
256
|
-
subscribers.delete(socket);
|
|
257
|
-
rateLimits.delete(socket);
|
|
258
|
-
});
|
|
259
|
-
});
|
|
260
|
-
|
|
261
|
-
// NIP-11: Relay Information Document at /relay/info
|
|
262
|
-
fastify.get(path + '/info', (request, reply) => {
|
|
263
|
-
const relayInfo = {
|
|
236
|
+
// NIP-11 relay information document. Served at the relay URL itself when
|
|
237
|
+
// the client sends `Accept: application/nostr+json` (what the spec and
|
|
238
|
+
// tools such as `nak relay` expect), and at <path>/info for older callers.
|
|
239
|
+
function relayInfo() {
|
|
240
|
+
return {
|
|
264
241
|
name: 'JSS Nostr Relay',
|
|
265
242
|
description: 'Nostr relay integrated with JavaScript Solid Server',
|
|
266
243
|
pubkey: '',
|
|
@@ -269,11 +246,55 @@ export async function registerNostrRelay(fastify, options = {}) {
|
|
|
269
246
|
software: 'https://github.com/JavaScriptSolidServer/JavaScriptSolidServer',
|
|
270
247
|
version: '0.0.1'
|
|
271
248
|
};
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
function wantsRelayInfo(request) {
|
|
252
|
+
return (request.headers.accept || '').toLowerCase().includes('application/nostr+json');
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
// Register the relay route: WebSocket upgrades go to wsHandler, plain HTTP
|
|
256
|
+
// GETs to handler (NIP-11 when asked for, 404 otherwise, as before).
|
|
257
|
+
fastify.route({
|
|
258
|
+
method: 'GET',
|
|
259
|
+
url: path,
|
|
260
|
+
handler: (request, reply) => {
|
|
261
|
+
if (!wantsRelayInfo(request)) return reply.code(404).send();
|
|
262
|
+
return reply
|
|
263
|
+
.header('Access-Control-Allow-Origin', '*')
|
|
264
|
+
.header('Content-Type', 'application/nostr+json')
|
|
265
|
+
.send(JSON.stringify(relayInfo()));
|
|
266
|
+
},
|
|
267
|
+
wsHandler: (connection, request) => {
|
|
268
|
+
const socket = connection.socket;
|
|
269
|
+
|
|
270
|
+
socket.on('message', async (data) => {
|
|
271
|
+
try {
|
|
272
|
+
const message = JSON.parse(data.toString());
|
|
273
|
+
const [type, value, ...rest] = message;
|
|
274
|
+
await processMessage(type, value, rest, socket);
|
|
275
|
+
} catch (e) {
|
|
276
|
+
socket.send(JSON.stringify(['NOTICE', `Error: ${e.message}`]));
|
|
277
|
+
}
|
|
278
|
+
});
|
|
279
|
+
|
|
280
|
+
socket.on('close', () => {
|
|
281
|
+
subscribers.delete(socket);
|
|
282
|
+
rateLimits.delete(socket);
|
|
283
|
+
});
|
|
272
284
|
|
|
285
|
+
socket.on('error', () => {
|
|
286
|
+
subscribers.delete(socket);
|
|
287
|
+
rateLimits.delete(socket);
|
|
288
|
+
});
|
|
289
|
+
}
|
|
290
|
+
});
|
|
291
|
+
|
|
292
|
+
// NIP-11 at <path>/info, kept for existing callers
|
|
293
|
+
fastify.get(path + '/info', (request, reply) => {
|
|
273
294
|
return reply
|
|
274
295
|
.header('Access-Control-Allow-Origin', '*')
|
|
275
296
|
.header('Content-Type', 'application/json')
|
|
276
|
-
.send(relayInfo);
|
|
297
|
+
.send(relayInfo());
|
|
277
298
|
});
|
|
278
299
|
|
|
279
300
|
return {
|
|
@@ -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
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Nostr relay NIP-11 tests
|
|
3
|
+
*
|
|
4
|
+
* NIP-11 says the relay information document is served at the relay's own
|
|
5
|
+
* URL when the client sends `Accept: application/nostr+json`. Tools such as
|
|
6
|
+
* `nak relay` only ask there, so serving it at <path>/info alone made the
|
|
7
|
+
* relay look non-compliant. The WebSocket relay on the same path must keep
|
|
8
|
+
* working.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { describe, it, before, after } from 'node:test';
|
|
12
|
+
import assert from 'node:assert';
|
|
13
|
+
import { mkdtempSync } from 'node:fs';
|
|
14
|
+
import { tmpdir } from 'node:os';
|
|
15
|
+
import { join } from 'node:path';
|
|
16
|
+
import { WebSocket } from 'ws';
|
|
17
|
+
import { createServer } from '../src/server.js';
|
|
18
|
+
|
|
19
|
+
describe('Nostr relay NIP-11', () => {
|
|
20
|
+
let fastify;
|
|
21
|
+
let base;
|
|
22
|
+
|
|
23
|
+
before(async () => {
|
|
24
|
+
const root = mkdtempSync(join(tmpdir(), 'jss-nip11-'));
|
|
25
|
+
fastify = createServer({ root, port: 0, logger: false, nostr: true });
|
|
26
|
+
await fastify.listen({ port: 0, host: '127.0.0.1' });
|
|
27
|
+
base = `127.0.0.1:${fastify.server.address().port}`;
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
after(async () => {
|
|
31
|
+
await fastify.close();
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
it('serves the info document at the relay URL for Accept: application/nostr+json', async () => {
|
|
35
|
+
const res = await fetch(`http://${base}/relay`, { headers: { Accept: 'application/nostr+json' } });
|
|
36
|
+
assert.strictEqual(res.status, 200);
|
|
37
|
+
assert.match(res.headers.get('content-type'), /application\/nostr\+json/);
|
|
38
|
+
assert.strictEqual(res.headers.get('access-control-allow-origin'), '*');
|
|
39
|
+
const info = await res.json();
|
|
40
|
+
assert.ok(info.supported_nips.includes(11));
|
|
41
|
+
});
|
|
42
|
+
|
|
43
|
+
it('still returns 404 for a plain GET of the relay URL', async () => {
|
|
44
|
+
const res = await fetch(`http://${base}/relay`);
|
|
45
|
+
assert.strictEqual(res.status, 404);
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
it('keeps serving the document at /relay/info', async () => {
|
|
49
|
+
const res = await fetch(`http://${base}/relay/info`);
|
|
50
|
+
assert.strictEqual(res.status, 200);
|
|
51
|
+
const info = await res.json();
|
|
52
|
+
assert.ok(info.supported_nips.includes(11));
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
it('still accepts WebSocket subscriptions on the relay URL', async () => {
|
|
56
|
+
const ws = new WebSocket(`ws://${base}/relay`);
|
|
57
|
+
const msg = await new Promise((resolve, reject) => {
|
|
58
|
+
ws.on('open', () => ws.send(JSON.stringify(['REQ', 'sub1', { kinds: [1], limit: 1 }])));
|
|
59
|
+
ws.on('message', (data) => resolve(JSON.parse(data.toString())));
|
|
60
|
+
ws.on('error', reject);
|
|
61
|
+
});
|
|
62
|
+
ws.close();
|
|
63
|
+
assert.deepStrictEqual(msg, ['EOSE', 'sub1']);
|
|
64
|
+
});
|
|
65
|
+
});
|
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
|
|
@@ -1,38 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"permissions": {
|
|
3
|
-
"allow": [
|
|
4
|
-
"Bash(gh issue *)",
|
|
5
|
-
"WebFetch(domain:did-nostr.com)",
|
|
6
|
-
"WebFetch(domain:nostrcg.github.io)",
|
|
7
|
-
"Bash(node --test test/nostr-key-parity.test.js)",
|
|
8
|
-
"Bash(node --test test/nostr-cid-vm.test.js test/well-known-did-nostr.test.js test/keys-provision.test.js test/keys-provision-integration.test.js test/nostr-event.test.js test/well-known-nostr-json.test.js)",
|
|
9
|
-
"Bash(npm test *)",
|
|
10
|
-
"Bash(git checkout *)",
|
|
11
|
-
"Bash(git add *)",
|
|
12
|
-
"Bash(cd *)",
|
|
13
|
-
"Bash(git push *)",
|
|
14
|
-
"Bash(gh pr create --base gh-pages --title 'fix\\(nostr\\): reconcile JWK key path to accept both Y-parities \\(#571\\)' --body ' *)",
|
|
15
|
-
"Bash(gh pr create --repo JavaScriptSolidServer/JavaScriptSolidServer --base gh-pages --head issue-571-multikey-jwk-parity-consistency --title 'fix\\(nostr\\): reconcile JWK key path to accept both Y-parities \\(#571\\)' --body ' *)",
|
|
16
|
-
"Bash(gh pr *)",
|
|
17
|
-
"Bash(gh api *)",
|
|
18
|
-
"Bash(node --test test/nostr-key-parity.test.js test/nostr-cid-vm.test.js test/well-known-did-nostr.test.js)",
|
|
19
|
-
"Bash(git commit *)",
|
|
20
|
-
"Bash(git config *)",
|
|
21
|
-
"Bash(FILTER_BRANCH_SQUELCH_WARNING=1 git filter-branch -f --msg-filter 'grep -v -e \"^Co-Authored-By: Claude\" -e \"Generated with \\\\[Claude Code\\\\]\"' gh-pages..HEAD)",
|
|
22
|
-
"Bash(git fetch *)",
|
|
23
|
-
"Bash(git ls-remote *)",
|
|
24
|
-
"Bash(echo \"exit=$?\")",
|
|
25
|
-
"Bash(cd /home/melvin/.claude/projects/-home-melvin-remote-github-com-JavaScriptSolidServer-JavaScriptSolidServer/memory/)",
|
|
26
|
-
"Bash(cat MEMORY.md)",
|
|
27
|
-
"Bash(FILTER_BRANCH_SQUELCH_WARNING=1 git filter-branch -f --env-filter ' *)",
|
|
28
|
-
"Bash(git pull *)",
|
|
29
|
-
"Bash(git branch *)",
|
|
30
|
-
"Bash(git remote *)",
|
|
31
|
-
"Bash(node --check src/handlers/container.js)",
|
|
32
|
-
"Bash(node --test /tmp/claude-1000/-home-melvin-remote-github-com-JavaScriptSolidServer-JavaScriptSolidServer/47629faf-bc8f-4e26-9878-091c550812d5/scratchpad/repro.test.js)",
|
|
33
|
-
"Bash(node --test test/auth.test.js)",
|
|
34
|
-
"Bash(git stash *)",
|
|
35
|
-
"Bash(node --check src/wac/checker.js)"
|
|
36
|
-
]
|
|
37
|
-
}
|
|
38
|
-
}
|