forked from JavaScriptSolidServer/JavaScriptSolidServer
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathresource.js
More file actions
1043 lines (908 loc) · 36.2 KB
/
Copy pathresource.js
File metadata and controls
1043 lines (908 loc) · 36.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import * as storage from '../storage/filesystem.js';
import { checkQuota, updateQuotaUsage } from '../storage/quota.js';
import { getAllHeaders, getNotFoundHeaders } from '../ldp/headers.js';
import { generateContainerJsonLd, serializeJsonLd } from '../ldp/container.js';
import { isContainer, getContentType, isRdfContentType, getEffectiveUrlPath, safeJsonParse, getPodName } from '../utils/url.js';
import { parseN3Patch, applyN3Patch, validatePatch } from '../patch/n3-patch.js';
import { parseSparqlUpdate, applySparqlUpdate } from '../patch/sparql-update.js';
import {
selectContentType,
canAcceptInput,
toJsonLd,
fromJsonLd,
RDF_TYPES
} from '../rdf/conneg.js';
import { emitChange } from '../notifications/events.js';
import { checkIfMatch, checkIfNoneMatchForGet, checkIfNoneMatchForWrite } from '../utils/conditional.js';
import { generateDatabrowserHtml, generateModuleDatabrowserHtml, shouldServeMashlib } from '../mashlib/index.js';
/**
* Live reload script - injected into HTML when --live-reload is enabled
*/
const LIVE_RELOAD_SCRIPT = `<script>(function(){var ws=new WebSocket((location.protocol==='https:'?'wss:':'ws:')+'//' +location.host+'/.notifications');ws.onopen=function(){ws.send('sub '+location.href)};ws.onmessage=function(e){if(e.data.startsWith('pub '))location.reload()};ws.onclose=function(){setTimeout(function(){location.reload()},1000)}})();</script>`;
// Cache-Control for RDF data responses: let clients keep the body but force
// revalidation via ETag on every use. This prevents stale bodies from leaking
// across auth-state changes (WAC) and closes the mashlib render-race window
// where a cached data variant was served on top-level navigation (#315).
const RDF_CACHE_CONTROL = 'private, no-cache, must-revalidate';
/**
* Inject live reload script into HTML content
*/
function injectLiveReload(content) {
const html = content.toString();
// Inject before </body> or at end
if (html.includes('</body>')) {
return Buffer.from(html.replace('</body>', LIVE_RELOAD_SCRIPT + '</body>'));
}
return Buffer.from(html + LIVE_RELOAD_SCRIPT);
}
/**
* Get the storage path and resource URL for a request
* In subdomain mode, storage path includes pod name, URL uses subdomain
*/
function getRequestPaths(request) {
const urlPath = request.url.split('?')[0];
// Storage path - includes pod name in subdomain mode
const storagePath = getEffectiveUrlPath(request);
// Resource URL - uses the actual request hostname (subdomain in subdomain mode)
const resourceUrl = `${request.protocol}://${request.hostname}${urlPath}`;
return { urlPath, storagePath, resourceUrl };
}
/**
* Parse HTTP Range header
* @param {string} rangeHeader - The Range header value (e.g., "bytes=0-1023")
* @param {number} fileSize - Total file size in bytes
* @returns {{ start: number, end: number } | null}
*/
function parseRangeHeader(rangeHeader, fileSize) {
if (!rangeHeader || !rangeHeader.startsWith('bytes=')) {
return null;
}
const range = rangeHeader.slice(6); // Remove 'bytes='
// Multi-range requests (e.g., "0-100,200-300") are not supported
// Per RFC 7233, ignore Range header and serve full content instead of 416
if (range.includes(',')) {
return null;
}
const parts = range.split('-');
if (parts.length !== 2) {
return null;
}
let start, end;
if (parts[0] === '') {
// Suffix range: bytes=-500 (last 500 bytes)
const suffix = parseInt(parts[1], 10);
if (isNaN(suffix) || suffix <= 0) return null;
start = Math.max(0, fileSize - suffix);
end = fileSize - 1;
} else if (parts[1] === '') {
// Open-ended range: bytes=1024- (from 1024 to end)
start = parseInt(parts[0], 10);
if (isNaN(start) || start < 0) return null;
end = fileSize - 1;
} else {
// Normal range: bytes=0-1023
start = parseInt(parts[0], 10);
end = parseInt(parts[1], 10);
if (isNaN(start) || isNaN(end) || start < 0 || end < start) return null;
}
// Clamp end to file size
if (end >= fileSize) {
end = fileSize - 1;
}
// Check if range is satisfiable
if (start > end || start >= fileSize) {
return null;
}
return { start, end };
}
/**
* Handle GET request
*/
export async function handleGet(request, reply) {
const { urlPath, storagePath, resourceUrl } = getRequestPaths(request);
const stats = await storage.stat(storagePath);
if (!stats) {
const origin = request.headers.origin;
const connegEnabled = request.connegEnabled || false;
const headers = getNotFoundHeaders({ resourceUrl, origin, connegEnabled });
Object.entries(headers).forEach(([k, v]) => reply.header(k, v));
return reply.code(404).send({ error: 'Not Found' });
}
// Check If-None-Match for conditional GET (304 Not Modified)
const ifNoneMatch = request.headers['if-none-match'];
if (ifNoneMatch) {
const check = checkIfNoneMatchForGet(ifNoneMatch, stats.etag);
if (!check.ok && check.notModified) {
return reply.code(304).send();
}
}
const origin = request.headers.origin;
// Handle container
if (stats.isDirectory) {
const connegEnabled = request.connegEnabled || false;
// Check for index.html (serves as both profile and container representation)
const indexPath = storagePath.endsWith('/') ? `${storagePath}index.html` : `${storagePath}/index.html`;
const indexExists = await storage.exists(indexPath);
if (indexExists) {
// Serve index.html (contains JSON-LD structured data)
const content = await storage.read(indexPath);
const indexStats = await storage.stat(indexPath);
// Pick the negotiated RDF type using q-aware Accept parsing. The
// naive `acceptHeader.includes('text/turtle')` we used to do here
// ignored q-weights — `Accept: application/ld+json, text/turtle;q=0.1`
// would still pick Turtle even though JSON-LD was preferred (#325).
const acceptHeader = request.headers.accept || '';
const negotiated = connegEnabled
? selectContentType(acceptHeader, true)
: null;
const wantsTurtle = negotiated === RDF_TYPES.TURTLE
|| negotiated === RDF_TYPES.N3
|| negotiated === 'application/n-triples';
const wantsJsonLd = negotiated === RDF_TYPES.JSON_LD;
if (wantsTurtle || wantsJsonLd) {
// Extract JSON-LD from HTML data island
try {
const htmlStr = content.toString();
const jsonLdMatch = htmlStr.match(/<script type="application\/ld\+json"[^>]*>([\s\S]*?)<\/script>/);
if (jsonLdMatch) {
const jsonLd = safeJsonParse(jsonLdMatch[1]);
if (wantsTurtle) {
// Convert to Turtle
const { content: turtleContent } = await fromJsonLd(
jsonLd,
'text/turtle',
resourceUrl,
true
);
const headers = getAllHeaders({
isContainer: true,
etag: indexStats?.etag || stats.etag,
contentType: 'text/turtle',
origin,
resourceUrl,
connegEnabled
});
headers['Cache-Control'] = RDF_CACHE_CONTROL;
Object.entries(headers).forEach(([k, v]) => reply.header(k, v));
return reply.send(turtleContent);
} else {
// Return JSON-LD directly
const headers = getAllHeaders({
isContainer: true,
etag: indexStats?.etag || stats.etag,
contentType: 'application/ld+json',
origin,
resourceUrl,
connegEnabled
});
headers['Cache-Control'] = RDF_CACHE_CONTROL;
Object.entries(headers).forEach(([k, v]) => reply.header(k, v));
return reply.send(JSON.stringify(jsonLd, null, 2));
}
}
} catch (err) {
// Fall through to serve HTML if conversion fails
console.error('Failed to convert profile to RDF:', err.message);
}
}
const headers = getAllHeaders({
isContainer: true,
etag: indexStats?.etag || stats.etag,
contentType: 'text/html',
origin,
resourceUrl,
connegEnabled
});
Object.entries(headers).forEach(([k, v]) => reply.header(k, v));
// Inject live reload script for index.html
if (request.liveReloadEnabled) {
reply.header('Cache-Control', 'no-store');
reply.removeHeader('ETag');
return reply.send(injectLiveReload(content));
}
return reply.send(content);
}
// No index.html, return JSON-LD container listing
const entries = await storage.listContainer(storagePath);
const jsonLd = generateContainerJsonLd(resourceUrl, entries || []);
// Check if we should serve Mashlib data browser for containers
if (shouldServeMashlib(request, request.mashlibEnabled, 'application/ld+json')) {
const html = request.mashlibModule
? generateModuleDatabrowserHtml(request.mashlibModule)
: generateDatabrowserHtml(resourceUrl, request.mashlibCdn ? request.mashlibVersion : null);
const headers = getAllHeaders({
isContainer: true,
etag: stats.etag,
contentType: 'text/html',
origin,
resourceUrl,
connegEnabled,
mashlibEnabled: request.mashlibEnabled
});
headers['X-Frame-Options'] = 'DENY';
headers['Content-Security-Policy'] = "frame-ancestors 'none'";
headers['Cache-Control'] = 'no-store';
Object.entries(headers).forEach(([k, v]) => reply.header(k, v));
return reply.type('text/html').send(html);
}
// Pick the negotiated RDF type using q-aware Accept parsing (#325).
const acceptHeader = request.headers.accept || '';
const negotiated = connegEnabled
? selectContentType(acceptHeader, true)
: null;
const wantsTurtle = negotiated === RDF_TYPES.TURTLE
|| negotiated === RDF_TYPES.N3
|| negotiated === 'application/n-triples';
if (wantsTurtle) {
// Convert container JSON-LD to Turtle
try {
const { content: turtleContent } = await fromJsonLd(
jsonLd,
'text/turtle',
resourceUrl,
true
);
const headers = getAllHeaders({
isContainer: true,
etag: stats.etag,
contentType: 'text/turtle',
origin,
resourceUrl,
connegEnabled,
mashlibEnabled: request.mashlibEnabled
});
headers['Cache-Control'] = RDF_CACHE_CONTROL;
Object.entries(headers).forEach(([k, v]) => reply.header(k, v));
return reply.send(turtleContent);
} catch (err) {
// Fall through to JSON-LD if conversion fails
console.error('Failed to convert container to Turtle:', err.message);
}
}
const headers = getAllHeaders({
isContainer: true,
etag: stats.etag,
contentType: 'application/ld+json',
origin,
resourceUrl,
connegEnabled,
mashlibEnabled: request.mashlibEnabled
});
headers['Cache-Control'] = RDF_CACHE_CONTROL;
Object.entries(headers).forEach(([k, v]) => reply.header(k, v));
return reply.send(serializeJsonLd(jsonLd));
}
// Handle resource
const storedContentType = getContentType(storagePath);
const connegEnabled = request.connegEnabled || false;
// Check if we should serve Mashlib data browser
// Only for RDF resources when Accept: text/html is requested
if (shouldServeMashlib(request, request.mashlibEnabled, storedContentType)) {
const html = request.mashlibModule
? generateModuleDatabrowserHtml(request.mashlibModule)
: generateDatabrowserHtml(resourceUrl, request.mashlibCdn ? request.mashlibVersion : null);
const headers = getAllHeaders({
isContainer: false,
etag: stats.etag,
contentType: 'text/html',
origin,
resourceUrl,
connegEnabled,
mashlibEnabled: request.mashlibEnabled
});
headers['X-Frame-Options'] = 'DENY';
headers['Content-Security-Policy'] = "frame-ancestors 'none'";
// Don't cache the HTML wrapper - always negotiate fresh
headers['Cache-Control'] = 'no-store';
Object.entries(headers).forEach(([k, v]) => reply.header(k, v));
return reply.type('text/html').send(html);
}
// Handle Range requests for media files (video, audio, etc.)
const rangeHeader = request.headers.range;
if (rangeHeader && !isRdfContentType(storedContentType)) {
const range = parseRangeHeader(rangeHeader, stats.size);
if (range) {
const { start, end } = range;
const chunkSize = end - start + 1;
const headers = getAllHeaders({
isContainer: false,
etag: stats.etag,
contentType: storedContentType,
origin,
resourceUrl,
connegEnabled
});
headers['Content-Range'] = `bytes ${start}-${end}/${stats.size}`;
headers['Content-Length'] = chunkSize;
Object.entries(headers).forEach(([k, v]) => reply.header(k, v));
const streamResult = storage.createReadStream(storagePath, { start, end });
if (!streamResult) {
return reply.code(500).send({ error: 'Stream error' });
}
// Handle stream errors that occur during response
streamResult.stream.on('error', (err) => {
console.error('Stream error during range response:', err.message);
});
return reply.code(206).send(streamResult.stream);
}
// If range is null (unsupported format or multi-range), fall through to serve full content
}
const content = await storage.read(storagePath);
if (content === null) {
return reply.code(500).send({ error: 'Read error' });
}
// Content negotiation for RDF resources (including HTML with JSON-LD data islands)
if (connegEnabled) {
const contentStr = content.toString();
const acceptHeader = request.headers.accept || '';
// Serve Turtle if: URL ends with .ttl OR Accept's q-weighted top
// RDF type is Turtle/N3 (#325 — naive substring matching ignored
// q-weights and would pick Turtle whenever it appeared in Accept).
const negotiated = selectContentType(acceptHeader, true);
const wantsTurtle = urlPath.endsWith('.ttl')
|| negotiated === RDF_TYPES.TURTLE
|| negotiated === RDF_TYPES.N3
|| negotiated === 'application/n-triples';
// Check if this is HTML with JSON-LD data island
const isHtmlWithDataIsland = contentStr.trimStart().startsWith('<!DOCTYPE') ||
contentStr.trimStart().startsWith('<html');
if (isHtmlWithDataIsland && wantsTurtle) {
// Extract JSON-LD from HTML data island and convert to Turtle
try {
const jsonLdMatch = contentStr.match(/<script\s+type=["']application\/ld\+json["']\s*>([\s\S]*?)<\/script>/i);
if (jsonLdMatch) {
const jsonLd = safeJsonParse(jsonLdMatch[1]);
const { content: turtleContent } = await fromJsonLd(jsonLd, 'text/turtle', resourceUrl, true);
const headers = getAllHeaders({
isContainer: false,
etag: stats.etag,
contentType: 'text/turtle',
origin,
resourceUrl,
connegEnabled,
mashlibEnabled: request.mashlibEnabled
});
headers['Cache-Control'] = RDF_CACHE_CONTROL;
Object.entries(headers).forEach(([k, v]) => reply.header(k, v));
return reply.send(turtleContent);
}
} catch (err) {
// Fall through to serve HTML if conversion fails
console.error('Failed to convert HTML data island to Turtle:', err.message);
}
} else if (isRdfContentType(storedContentType)) {
// Plain JSON-LD file
try {
const jsonLd = safeJsonParse(contentStr);
// Use Turtle if URL ends with .ttl, otherwise use Accept header preference
const targetType = wantsTurtle ? 'text/turtle' : selectContentType(acceptHeader, connegEnabled);
const { content: outputContent, contentType: outputType } = await fromJsonLd(
jsonLd,
targetType,
resourceUrl,
connegEnabled
);
const headers = getAllHeaders({
isContainer: false,
etag: stats.etag,
contentType: outputType,
origin,
resourceUrl,
connegEnabled,
mashlibEnabled: request.mashlibEnabled
});
headers['Cache-Control'] = RDF_CACHE_CONTROL;
Object.entries(headers).forEach(([k, v]) => reply.header(k, v));
return reply.send(outputContent);
} catch (e) {
// If not valid JSON-LD, serve as-is
}
}
}
// Serve content as-is (no conneg or non-RDF resource)
// For extensionless files (like profile/card), detect HTML by content
let actualContentType = storedContentType;
if (storedContentType === 'application/octet-stream') {
const contentStr = content.toString().trimStart();
if (contentStr.startsWith('<!DOCTYPE') || contentStr.startsWith('<html')) {
actualContentType = 'text/html';
}
}
const headers = getAllHeaders({
isContainer: false,
etag: stats.etag,
contentType: actualContentType,
origin,
resourceUrl,
connegEnabled,
mashlibEnabled: request.mashlibEnabled
});
if (isRdfContentType(actualContentType)) {
headers['Cache-Control'] = RDF_CACHE_CONTROL;
}
Object.entries(headers).forEach(([k, v]) => reply.header(k, v));
// Inject live reload script into HTML (disable caching since content is modified)
if (actualContentType === 'text/html' && request.liveReloadEnabled) {
reply.header('Cache-Control', 'no-store');
reply.removeHeader('ETag');
return reply.send(injectLiveReload(content));
}
return reply.send(content);
}
/**
* Handle HEAD request
*/
export async function handleHead(request, reply) {
const { storagePath, resourceUrl } = getRequestPaths(request);
const stats = await storage.stat(storagePath);
if (!stats) {
const origin = request.headers.origin;
const connegEnabled = request.connegEnabled || false;
const headers = getNotFoundHeaders({ resourceUrl, origin, connegEnabled });
Object.entries(headers).forEach(([k, v]) => reply.header(k, v));
return reply.code(404).send();
}
const origin = request.headers.origin;
const connegEnabled = request.connegEnabled || false;
let contentType;
if (stats.isDirectory) {
const indexPath = storagePath.endsWith('/') ? `${storagePath}index.html` : `${storagePath}/index.html`;
const indexExists = await storage.exists(indexPath);
const acceptHeader = request.headers.accept || '';
if (connegEnabled) {
// HEAD must mirror what GET would emit; otherwise client caches and
// RDF-aware tooling key off a content-type that doesn't match the
// body they'll see on the next GET (#325). Use q-aware Accept
// parsing for both the index.html and listing branches.
const negotiated = selectContentType(acceptHeader, true);
const wantsTurtle = negotiated === RDF_TYPES.TURTLE
|| negotiated === RDF_TYPES.N3
|| negotiated === 'application/n-triples';
const wantsJsonLd = negotiated === RDF_TYPES.JSON_LD;
if (wantsTurtle) {
contentType = 'text/turtle';
} else if (wantsJsonLd) {
// For an index.html container, only override to JSON-LD if the
// Accept header explicitly asked for JSON; otherwise fall back
// to text/html so HEAD matches the index.html that GET serves.
const explicitJson = /\b(application\/ld\+json|application\/json)\b/i.test(acceptHeader);
contentType = (indexExists && !explicitJson) ? 'text/html' : 'application/ld+json';
} else {
contentType = indexExists ? 'text/html' : 'application/ld+json';
}
} else if (indexExists) {
contentType = 'text/html';
} else {
contentType = 'application/ld+json';
}
} else {
contentType = getContentType(storagePath);
}
const headers = getAllHeaders({
isContainer: stats.isDirectory,
etag: stats.etag,
contentType,
origin,
resourceUrl,
connegEnabled
});
if (!stats.isDirectory) {
headers['Content-Length'] = stats.size;
}
Object.entries(headers).forEach(([k, v]) => reply.header(k, v));
return reply.code(200).send();
}
/**
* Handle PUT request
*/
export async function handlePut(request, reply) {
// Read-only mode - block all writes
if (request.config?.readOnly) {
return reply.code(405).send({ error: 'Method Not Allowed', message: 'Server is in read-only mode' });
}
const { urlPath, storagePath, resourceUrl } = getRequestPaths(request);
const connegEnabled = request.connegEnabled || false;
// Handle container creation via PUT
if (isContainer(urlPath)) {
const stats = await storage.stat(storagePath);
if (stats?.isDirectory) {
// If container has index.html and PUT sends HTML, rewrite URL to target the
// index document and delegate to the standard PUT pipeline. This mirrors GET
// behavior (line 138) which serves index.html for container URLs, and reuses
// If-Match/If-None-Match, quota checks, and notification handling.
const indexPath = storagePath.endsWith('/') ? `${storagePath}index.html` : `${storagePath}/index.html`;
const contentType = request.headers['content-type'] || '';
if (contentType.includes('text/html') && await storage.exists(indexPath)) {
const indexUrl = urlPath.endsWith('/') ? `${urlPath}index.html` : `${urlPath}/index.html`;
// Fastify request.url is a getter, so proxy it with the rewritten path
const proxied = Object.create(request, { url: { value: indexUrl } });
return handlePut(proxied, reply);
}
// Container exists but no index routing applies - reject
return reply.code(409).send({ error: 'Cannot PUT to existing container' });
}
// Create the container (and any intermediate containers)
const success = await storage.createContainer(storagePath);
if (!success) {
return reply.code(500).send({ error: 'Failed to create container' });
}
const origin = request.headers.origin;
const headers = getAllHeaders({
isContainer: true,
origin,
connegEnabled
});
headers['Location'] = resourceUrl;
Object.entries(headers).forEach(([k, v]) => reply.header(k, v));
emitChange(request.protocol + '://' + request.hostname, urlPath, 'created');
return reply.code(201).send();
}
const contentType = request.headers['content-type'] || '';
// Check if we can accept this input type
if (!canAcceptInput(contentType, connegEnabled)) {
return reply.code(415).send({
error: 'Unsupported Media Type',
message: connegEnabled
? 'Supported types: application/ld+json, text/turtle, text/n3'
: 'Supported type: application/ld+json (enable conneg for Turtle support)'
});
}
// Check if resource already exists and get current ETag
const stats = await storage.stat(storagePath);
const existed = stats !== null;
const currentEtag = stats?.etag || null;
// Check If-Match header (for safe updates)
const ifMatch = request.headers['if-match'];
if (ifMatch) {
const check = checkIfMatch(ifMatch, currentEtag);
if (!check.ok) {
return reply.code(check.status).send({ error: check.error });
}
}
// Check If-None-Match header (for create-only semantics)
const ifNoneMatch = request.headers['if-none-match'];
if (ifNoneMatch) {
const check = checkIfNoneMatchForWrite(ifNoneMatch, currentEtag);
if (!check.ok) {
return reply.code(check.status).send({ error: check.error });
}
}
// Get content from request body
let content = request.body;
// Handle raw body for non-JSON content types
if (Buffer.isBuffer(content)) {
// Already a buffer, use as-is
} else if (typeof content === 'string') {
content = Buffer.from(content);
} else if (content && typeof content === 'object') {
content = Buffer.from(JSON.stringify(content));
} else {
content = Buffer.from('');
}
// Convert Turtle/N3 to JSON-LD if conneg enabled
const inputType = contentType.split(';')[0].trim().toLowerCase();
if (connegEnabled && (inputType === RDF_TYPES.TURTLE || inputType === RDF_TYPES.N3)) {
try {
const jsonLd = await toJsonLd(content, contentType, resourceUrl, connegEnabled);
content = Buffer.from(JSON.stringify(jsonLd, null, 2));
} catch (e) {
return reply.code(400).send({
error: 'Bad Request',
message: 'Invalid Turtle/N3 format: ' + e.message
});
}
}
// Check storage quota before writing (skip in public mode - no pod structure)
const podName = request.config?.public ? null : getPodName(request);
const oldSize = stats?.size || 0;
const sizeDelta = content.length - oldSize;
if (podName && sizeDelta > 0) {
const { allowed, error } = await checkQuota(podName, sizeDelta, request.defaultQuota || 0);
if (!allowed) {
return reply.code(507).send({ error: 'Insufficient Storage', message: error });
}
}
const success = await storage.write(storagePath, content);
if (!success) {
return reply.code(500).send({ error: 'Write failed' });
}
// Update quota usage after successful write
if (podName && sizeDelta !== 0) {
await updateQuotaUsage(podName, sizeDelta);
}
const origin = request.headers.origin;
const headers = getAllHeaders({ isContainer: false, origin, resourceUrl, connegEnabled, mashlibEnabled: request.mashlibEnabled });
headers['Location'] = resourceUrl;
Object.entries(headers).forEach(([k, v]) => reply.header(k, v));
// Emit change notification for WebSocket subscribers
if (request.notificationsEnabled) {
emitChange(resourceUrl);
}
return reply.code(existed ? 204 : 201).send();
}
/**
* Handle DELETE request
*/
export async function handleDelete(request, reply) {
// Read-only mode - block all writes
if (request.config?.readOnly) {
return reply.code(405).send({ error: 'Method Not Allowed', message: 'Server is in read-only mode' });
}
const { storagePath, resourceUrl } = getRequestPaths(request);
// Check if resource exists and get current ETag
const stats = await storage.stat(storagePath);
if (!stats) {
const origin = request.headers.origin;
const connegEnabled = request.connegEnabled || false;
const headers = getNotFoundHeaders({ resourceUrl, origin, connegEnabled });
Object.entries(headers).forEach(([k, v]) => reply.header(k, v));
return reply.code(404).send({ error: 'Not Found' });
}
// Check If-Match header (for safe deletes)
const ifMatch = request.headers['if-match'];
if (ifMatch) {
const check = checkIfMatch(ifMatch, stats.etag);
if (!check.ok) {
return reply.code(check.status).send({ error: check.error });
}
}
// Get file size before deletion for quota update
const fileSize = stats.size || 0;
const success = await storage.remove(storagePath);
if (!success) {
return reply.code(500).send({ error: 'Delete failed' });
}
// Update quota usage (subtract deleted file size)
const podName = getPodName(request);
if (podName && fileSize > 0) {
await updateQuotaUsage(podName, -fileSize);
}
const origin = request.headers.origin;
const headers = getAllHeaders({ isContainer: false, origin, resourceUrl });
Object.entries(headers).forEach(([k, v]) => reply.header(k, v));
// Emit change notification for WebSocket subscribers
if (request.notificationsEnabled) {
emitChange(resourceUrl);
}
return reply.code(204).send();
}
/**
* Handle OPTIONS request
*/
export async function handleOptions(request, reply) {
const { urlPath, storagePath, resourceUrl } = getRequestPaths(request);
const stats = await storage.stat(storagePath);
const origin = request.headers.origin;
const connegEnabled = request.connegEnabled || false;
const headers = getAllHeaders({
isContainer: stats?.isDirectory || isContainer(urlPath),
origin,
resourceUrl,
connegEnabled
});
Object.entries(headers).forEach(([k, v]) => reply.header(k, v));
return reply.code(204).send();
}
/**
* Handle PATCH request
* Supports N3 Patch format (text/n3) and SPARQL Update for updating RDF resources
*/
export async function handlePatch(request, reply) {
// Read-only mode - block all writes
if (request.config?.readOnly) {
return reply.code(405).send({ error: 'Method Not Allowed', message: 'Server is in read-only mode' });
}
const { urlPath, storagePath, resourceUrl } = getRequestPaths(request);
// Don't allow PATCH to containers
if (isContainer(urlPath)) {
return reply.code(409).send({ error: 'Cannot PATCH containers' });
}
// Check content type
const contentType = request.headers['content-type'] || '';
const isN3Patch = contentType.includes('text/n3') || contentType.includes('application/n3');
const isSparqlUpdate = contentType.includes('application/sparql-update');
if (!isN3Patch && !isSparqlUpdate) {
return reply.code(415).send({
error: 'Unsupported Media Type',
message: 'PATCH requires Content-Type: text/n3 (N3 Patch) or application/sparql-update (SPARQL Update)'
});
}
// Check if resource exists - PATCH can create resources in Solid
const stats = await storage.stat(storagePath);
const resourceExists = !!stats;
// Check If-Match header (for safe updates) - only if resource exists
if (resourceExists) {
const ifMatch = request.headers['if-match'];
if (ifMatch) {
const check = checkIfMatch(ifMatch, stats.etag);
if (!check.ok) {
return reply.code(check.status).send({ error: check.error });
}
}
}
// Read existing content or start with empty JSON-LD document
let document;
let htmlWrapper = null; // Track HTML wrapper for data island re-embedding
if (resourceExists) {
const existingContent = await storage.read(storagePath);
if (existingContent === null) {
return reply.code(500).send({ error: 'Read error' });
}
const contentStr = existingContent.toString();
// Check if this is HTML with embedded JSON-LD data island
if (contentStr.trimStart().startsWith('<!DOCTYPE') || contentStr.trimStart().startsWith('<html')) {
// Extract JSON-LD from <script type="application/ld+json"> tag
const jsonLdMatch = contentStr.match(/<script\s+type=["']application\/ld\+json["']\s*>([\s\S]*?)<\/script>/i);
if (!jsonLdMatch) {
return reply.code(409).send({
error: 'Conflict',
message: 'HTML document does not contain a JSON-LD data island'
});
}
try {
document = safeJsonParse(jsonLdMatch[1]);
// Save the HTML parts for re-embedding after patch
const jsonLdStart = contentStr.indexOf(jsonLdMatch[0]) + jsonLdMatch[0].indexOf('>') + 1;
const jsonLdEnd = jsonLdStart + jsonLdMatch[1].length;
htmlWrapper = {
before: contentStr.substring(0, jsonLdStart),
after: contentStr.substring(jsonLdEnd)
};
} catch (e) {
return reply.code(409).send({
error: 'Conflict',
message: 'HTML data island contains invalid JSON-LD'
});
}
} else {
// Try to parse as JSON-LD first
try {
document = safeJsonParse(contentStr);
} catch (e) {
// Not JSON - might be Turtle, handle with RDF store for SPARQL Update
if (isSparqlUpdate) {
// Parse Turtle and apply SPARQL Update directly
const { Parser, Writer } = await import('n3');
const parser = new Parser({ baseIRI: resourceUrl });
let quads;
try {
quads = parser.parse(contentStr);
} catch (parseErr) {
return reply.code(409).send({
error: 'Conflict',
message: 'Resource is not valid Turtle: ' + parseErr.message
});
}
// Parse the SPARQL Update
const patchContent = Buffer.isBuffer(request.body) ? request.body.toString() : request.body;
let update;
try {
update = parseSparqlUpdate(patchContent, resourceUrl);
} catch (parseErr) {
return reply.code(400).send({
error: 'Bad Request',
message: 'Invalid SPARQL Update: ' + parseErr.message
});
}
// Apply deletes
for (const triple of update.deletes) {
quads = quads.filter(q => {
const matches = q.subject.value === triple.subject &&
q.predicate.value === triple.predicate &&
(q.object.value === (triple.object['@id'] || triple.object['@value'] || triple.object));
return !matches;
});
}
// Apply inserts
const { DataFactory } = await import('n3');
const { namedNode, literal } = DataFactory;
for (const triple of update.inserts) {
const subj = namedNode(triple.subject);
const pred = namedNode(triple.predicate);
let obj;
if (triple.object['@id']) {
obj = namedNode(triple.object['@id']);
} else if (typeof triple.object === 'string') {
obj = literal(triple.object);
} else {
obj = literal(triple.object['@value'] || triple.object);
}
quads.push(DataFactory.quad(subj, pred, obj));
}
// Serialize back to Turtle
const writer = new Writer({ prefixes: {} });
quads.forEach(q => writer.addQuad(q));
let turtleOutput;
writer.end((err, result) => { turtleOutput = result; });
const success = await storage.write(storagePath, Buffer.from(turtleOutput));
if (!success) {
return reply.code(500).send({ error: 'Write failed' });
}
const origin = request.headers.origin;
const headers = getAllHeaders({ isContainer: false, origin, resourceUrl });
Object.entries(headers).forEach(([k, v]) => reply.header(k, v));
if (request.notificationsEnabled) {
emitChange(resourceUrl);
}
return reply.code(resourceExists ? 204 : 201).send();
}
return reply.code(409).send({
error: 'Conflict',
message: 'Resource is not valid JSON-LD and cannot be patched'
});
}
}
} else {
// Create empty JSON-LD document for new resource
document = {
'@context': {},
'@graph': []
};
}
// Parse the patch
const patchContent = Buffer.isBuffer(request.body)
? request.body.toString()
: request.body;
let updatedDocument;
if (isSparqlUpdate) {
// Handle SPARQL Update
let update;
try {
update = parseSparqlUpdate(patchContent, resourceUrl);
} catch (e) {
return reply.code(400).send({
error: 'Bad Request',
message: 'Invalid SPARQL Update: ' + e.message
});
}
try {
updatedDocument = applySparqlUpdate(document, update, resourceUrl);
} catch (e) {
return reply.code(409).send({
error: 'Conflict',
message: 'Failed to apply SPARQL Update: ' + e.message
});
}
} else {
// Handle N3 Patch
let patch;
try {
patch = parseN3Patch(patchContent, resourceUrl);
} catch (e) {