@undefineds.co/xpod 0.4.33 → 0.4.34

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.
Files changed (103) hide show
  1. package/dist/http/SubgraphSparqlHttpHandler.d.ts +32 -0
  2. package/dist/http/SubgraphSparqlHttpHandler.js +448 -1
  3. package/dist/http/SubgraphSparqlHttpHandler.jsonld +36 -0
  4. package/dist/storage/rdf/QleverSparqlEngine.d.ts +15 -0
  5. package/dist/storage/rdf/QleverSparqlEngine.js +40 -0
  6. package/dist/storage/rdf/QleverSparqlEngine.jsonld +8 -0
  7. package/dist/storage/rdf/RdfAccessScope.d.ts +12 -0
  8. package/dist/storage/rdf/RdfAccessScope.js +63 -3
  9. package/dist/storage/rdf/RdfQuerySparqlEngine.d.ts +7 -0
  10. package/dist/storage/rdf/RdfQuerySparqlEngine.js +30 -0
  11. package/dist/storage/rdf/RdfQuerySparqlEngine.jsonld +8 -0
  12. package/dist/storage/rdf/index.d.ts +1 -1
  13. package/dist/storage/rdf/index.js +6 -2
  14. package/dist/storage/sparql/SubgraphQueryEngine.d.ts +5 -0
  15. package/dist/storage/sparql/SubgraphQueryEngine.js +9 -0
  16. package/dist/storage/sparql/SubgraphQueryEngine.jsonld +16 -0
  17. package/node_modules/@undefineds.co/ai-connections/dist/AiBuiltinProvidersSection.d.ts +32 -0
  18. package/node_modules/@undefineds.co/ai-connections/dist/AiBuiltinProvidersSection.js +8 -0
  19. package/node_modules/@undefineds.co/ai-connections/dist/AiConnectionsPanel.js +35 -1
  20. package/node_modules/@undefineds.co/ai-connections/dist/AiGatewayKeysSection.d.ts +9 -1
  21. package/node_modules/@undefineds.co/ai-connections/dist/AiGatewayKeysSection.js +32 -6
  22. package/node_modules/@undefineds.co/ai-connections/dist/index.d.ts +1 -0
  23. package/node_modules/@undefineds.co/ai-connections/dist/index.js +1 -0
  24. package/node_modules/@undefineds.co/ai-connections/package.json +2 -2
  25. package/node_modules/@undefineds.co/ai-connections-runtime/dist/contract/ai-connections-client.d.ts +1 -1
  26. package/node_modules/@undefineds.co/ai-connections-runtime/dist/contract/client/normalize.d.ts +16 -1
  27. package/node_modules/@undefineds.co/ai-connections-runtime/dist/contract/client/normalize.js +80 -2
  28. package/node_modules/@undefineds.co/ai-connections-runtime/dist/contract/client/request.js +19 -1
  29. package/node_modules/@undefineds.co/ai-connections-runtime/dist/contract/client/types.d.ts +31 -0
  30. package/node_modules/@undefineds.co/ai-connections-runtime/dist/materials/build-provenance.json +4 -4
  31. package/node_modules/@undefineds.co/ai-connections-runtime/dist/materials/index.json +15 -15
  32. package/node_modules/@undefineds.co/ai-connections-runtime/dist/materials/javascript/provider-catalog/index.json +2 -2
  33. package/node_modules/@undefineds.co/ai-connections-runtime/dist/materials/javascript/service-access-resources/index.json +2 -2
  34. package/node_modules/@undefineds.co/ai-connections-runtime/dist/materials/source/package.json +1 -1
  35. package/node_modules/@undefineds.co/ai-connections-runtime/dist/materials/source-inventory.json +11 -11
  36. package/node_modules/@undefineds.co/ai-connections-runtime/dist/provider-catalog-inputs.json +1 -1
  37. package/node_modules/@undefineds.co/ai-connections-runtime/dist/service-access-resources-inputs.json +1 -1
  38. package/node_modules/@undefineds.co/ai-connections-runtime/package.json +1 -1
  39. package/node_modules/@undefineds.co/extension-host-contracts/dist/materials/build-provenance.json +1 -1
  40. package/node_modules/@undefineds.co/extension-host-contracts/dist/materials/index.json +3 -3
  41. package/node_modules/@undefineds.co/extension-host-contracts/dist/materials/source-inventory.json +1 -1
  42. package/node_modules/@undefineds.co/xpod-afs/dist/licenses/cli-producer-original-binding.json +1 -1
  43. package/node_modules/@undefineds.co/xpod-cli/dist/producer-materials/index.json +1 -1
  44. package/package.json +4 -4
  45. package/static/dashboard/assets/{AccountAuthBoundary-D2peXpst.js → AccountAuthBoundary-DXBGmvsI.js} +1 -1
  46. package/static/dashboard/assets/{DesktopOidcCallback-DXWArav6.js → DesktopOidcCallback-p24MYq1P.js} +1 -1
  47. package/static/dashboard/assets/{DevicePages-BULFk95K.js → DevicePages-DbvhTnse.js} +1 -1
  48. package/static/dashboard/assets/ModelsPage-UMDnRyLA.js +12 -0
  49. package/static/dashboard/assets/{PaneListHeader-BSfEbecP.js → PaneListHeader-DkEH0TT_.js} +1 -1
  50. package/static/dashboard/assets/{PodDeletionAuthorizationPanel-CH-Sx18g.js → PodDeletionAuthorizationPanel-CzrI8Pgw.js} +3 -3
  51. package/static/dashboard/assets/{PodPage-BMpejIra.js → PodPage-TaiWqMBx.js} +1 -1
  52. package/static/dashboard/assets/{SystemSettingsPage-H_Jj6WfF.js → SystemSettingsPage-D4gQjDt1.js} +1 -1
  53. package/static/dashboard/assets/{TasksPage-CTDxlQra.js → TasksPage-CmkiMYil.js} +1 -1
  54. package/static/dashboard/assets/{WebDesktopEntry-Ch7-0C9a.js → WebDesktopEntry-D9kEfhbz.js} +1 -1
  55. package/static/dashboard/assets/{XpodAiConnectionsPodStore-ggRE9fmE.js → XpodAiConnectionsPodStore-orY8vQFl.js} +2 -2
  56. package/static/dashboard/assets/{XpodShellApp-Bwf9UmeJ.js → XpodShellApp-DR65DMOb.js} +4 -4
  57. package/static/dashboard/assets/{account-session-CVzooxS2.js → account-session-BZ2ttIdq.js} +1 -1
  58. package/static/dashboard/assets/{button-DGh2QVt2.js → button-_rwfCMMH.js} +1 -1
  59. package/static/dashboard/assets/{collection-runtime-DwV_9rt2.js → collection-runtime-C74icLtf.js} +1 -1
  60. package/static/dashboard/assets/{createLucideIcon-yLhAxnfL.js → createLucideIcon-DrgScGhc.js} +1 -1
  61. package/static/dashboard/assets/{dashboard-xbXlitKr.js → dashboard--DWjqkYt.js} +2 -2
  62. package/static/dashboard/assets/{index-CMigfjqD.js → index-D6dB-UNq.js} +1 -1
  63. package/static/dashboard/assets/{index-BSiKqEdo.js → index-dx5sc4rE.js} +1 -1
  64. package/static/dashboard/assets/{label-CrDv_y1q.js → label-D02Jpvm9.js} +1 -1
  65. package/static/dashboard/assets/{list-BJM0nqti.js → list-DpFAisnq.js} +1 -1
  66. package/static/dashboard/assets/{nav-item-style-CQbGyYLb.js → nav-item-style-B1-0JkON.js} +1 -1
  67. package/static/dashboard/assets/{safe-continuation-ZTBQTFWB.js → safe-continuation-DUTIOFe5.js} +1 -1
  68. package/static/dashboard/assets/{section-header-CWHRWGXl.js → section-header-CtBnllbG.js} +1 -1
  69. package/static/dashboard/assets/{setting-row-qWtxYGK1.js → setting-row-D_JPuHAJ.js} +1 -1
  70. package/static/dashboard/assets/{xpod-remembered-login-DPMxurVN.js → xpod-remembered-login-CtmMI8xG.js} +3 -3
  71. package/static/dashboard/dashboard.html +1 -1
  72. package/static/settings/assets/{AccountAuthBoundary-4Ywjpb8o.js → AccountAuthBoundary-njIhHpLf.js} +1 -1
  73. package/static/settings/assets/{DesktopOidcCallback-CAmwMT_J.js → DesktopOidcCallback-BjjNwTxc.js} +1 -1
  74. package/static/settings/assets/{DevicePages-DvuHyfHo.js → DevicePages-FFJMu_zL.js} +1 -1
  75. package/static/settings/assets/ModelsPage-6567dZKQ.js +12 -0
  76. package/static/settings/assets/{PaneListHeader-CuFgIbhe.js → PaneListHeader-CuPah5aC.js} +1 -1
  77. package/static/settings/assets/{PodDeletionAuthorizationPanel-DdNgDHH5.js → PodDeletionAuthorizationPanel-aJCKasGz.js} +3 -3
  78. package/static/settings/assets/{PodPage-DnWCNGTO.js → PodPage-BA0DQ3AB.js} +1 -1
  79. package/static/settings/assets/{SystemSettingsPage-k9P_wQcl.js → SystemSettingsPage-BNPH4VWf.js} +1 -1
  80. package/static/settings/assets/{TasksPage-Dk7gUH3J.js → TasksPage-B5m82wjD.js} +1 -1
  81. package/static/settings/assets/{WebDesktopEntry-DJwPVVnU.js → WebDesktopEntry-DgwwIUhg.js} +1 -1
  82. package/static/settings/assets/{XpodAiConnectionsPodStore-BtJQiJsx.js → XpodAiConnectionsPodStore-BJm-rFPs.js} +2 -2
  83. package/static/settings/assets/{XpodShellApp-B47vEQJp.js → XpodShellApp-BwvekJJR.js} +4 -4
  84. package/static/settings/assets/{XpodThemeProvider-Ciuwo_yl.js → XpodThemeProvider-DyX0rUID.js} +2 -2
  85. package/static/settings/assets/{account-session-CMc10iEj.js → account-session-D6vibAra.js} +1 -1
  86. package/static/settings/assets/auth-callback-DXxmF0-p.js +1 -0
  87. package/static/settings/assets/{button-D1dGKY1f.js → button-CV4KJ59A.js} +1 -1
  88. package/static/settings/assets/{collection-runtime-hK37-47o.js → collection-runtime-CARp4Cii.js} +1 -1
  89. package/static/settings/assets/{createLucideIcon-nEiQH43b.js → createLucideIcon-BIwq0vQx.js} +1 -1
  90. package/static/settings/assets/{index-DNdvma6J.js → index-D-LgcKAb.js} +1 -1
  91. package/static/settings/assets/{label-C3EGk_2E.js → label-CFTl2bC_.js} +1 -1
  92. package/static/settings/assets/{list-BensBGZp.js → list-D2aO7Nu-.js} +1 -1
  93. package/static/settings/assets/{nav-item-style-BOKCPNz8.js → nav-item-style-BKpK5_1m.js} +1 -1
  94. package/static/settings/assets/{safe-continuation-BPwW6jdq.js → safe-continuation-DRRY_t4F.js} +1 -1
  95. package/static/settings/assets/{section-header-DOSj5RvJ.js → section-header-COECjyL5.js} +1 -1
  96. package/static/settings/assets/{setting-row-C9k4cGNM.js → setting-row-cGgL78vR.js} +1 -1
  97. package/static/settings/assets/{settings-DtP5C8hi.js → settings-Bvrm5N-k.js} +1 -1
  98. package/static/settings/assets/{xpod-remembered-login-DKFG-zi3.js → xpod-remembered-login-YAmn8ZiP.js} +3 -3
  99. package/static/settings/auth-callback.html +2 -2
  100. package/static/settings/settings.html +2 -2
  101. package/static/dashboard/assets/ModelsPage-xvsVzhGZ.js +0 -12
  102. package/static/settings/assets/ModelsPage-BDXqetwk.js +0 -12
  103. package/static/settings/assets/auth-callback-fcOBaX2w.js +0 -1
@@ -35,6 +35,38 @@ export declare class SubgraphSparqlHttpHandler extends HttpHandler {
35
35
  handle({ request, response }: HttpHandlerInput): Promise<void>;
36
36
  private sendErrorResponse;
37
37
  private acceptsJson;
38
+ private classifyMetadataRead;
39
+ /**
40
+ * Detect metadata access in a query shape that has no per-subject authorization
41
+ * (ASK/CONSTRUCT/DESCRIBE, or a SELECT the metadata classifier rejected).
42
+ * Returning a reason makes the request fail closed with an explicit 400 rather
43
+ * than silently evaluating against data graphs only.
44
+ */
45
+ private unsupportedMetadataSignal;
46
+ /**
47
+ * Derive the subject variable structurally: the first variable that appears in
48
+ * the subject slot of a triple inside the metadata GRAPH, preferring one that
49
+ * also occurs in the projected variables. Variable names carry no semantics.
50
+ */
51
+ private resolveMetadataSubjectVariable;
52
+ /**
53
+ * Compatible query-level binding form: BIND(IRI(CONCAT("meta:", STR(?s))) AS
54
+ * ?expected) plus FILTER(?graph = ?expected), still evaluated before
55
+ * ORDER/LIMIT/OFFSET. Root's canonical form is the STRAFTER filter; this alias
56
+ * is accepted so an existing ORM builder does not have to rewrite first.
57
+ */
58
+ private hasMetadataGraphExpectedBind;
59
+ private hasBoundedMetadataGraphFilter;
60
+ /**
61
+ * Root requires graph<->subject binding to be enforced by the query before
62
+ * ORDER/LIMIT/OFFSET, not only by a post-filter. Accept the exact
63
+ * `FILTER(STR(?subject) = STRAFTER(STR(?metadataGraph), "meta:"))` form and
64
+ * fail closed if a collection query omits it.
65
+ */
66
+ private hasMetadataGraphSubjectBinding;
67
+ private executeMetadataSelect;
68
+ private metadataResourceForGraph;
69
+ private metadataRowAllowed;
38
70
  private executeSelect;
39
71
  private executeAsk;
40
72
  private executeConstruct;
@@ -10,6 +10,7 @@ const policy_engine_1 = require("@solidlab/policy-engine");
10
10
  const n3_1 = require("n3");
11
11
  const sparqljs_1 = require("sparqljs");
12
12
  const RdfSparqlBoundary_1 = require("../storage/rdf/RdfSparqlBoundary");
13
+ const RdfAccessScope_1 = require("../storage/rdf/RdfAccessScope");
13
14
  const db_1 = require("../identity/drizzle/db");
14
15
  const PodLookupRepository_1 = require("../identity/drizzle/PodLookupRepository");
15
16
  const UsageRepository_1 = require("../storage/quota/UsageRepository");
@@ -96,9 +97,27 @@ class SubgraphSparqlHttpHandler extends community_server_1.HttpHandler {
96
97
  return;
97
98
  }
98
99
  const queryType = parsed.queryType ?? 'SELECT';
100
+ const metadataPlan = queryType === 'SELECT'
101
+ ? this.classifyMetadataRead(parsed, queryRequest.baseUrl)
102
+ : undefined;
103
+ // Only the explicit SELECT path authorizes each facet's subject resource.
104
+ // Every other shape (ASK/CONSTRUCT/DESCRIBE, or a SELECT the classifier did
105
+ // not accept) must fail closed instead of falling through to ordinary
106
+ // execution, where the metadata alias has no ACL decision behind it.
107
+ if (!metadataPlan) {
108
+ const unsupported = this.unsupportedMetadataSignal(parsed, queryRequest.baseUrl);
109
+ if (unsupported) {
110
+ throw new community_server_2.BadRequestHttpError(unsupported);
111
+ }
112
+ }
99
113
  switch (queryType) {
100
114
  case 'SELECT':
101
- await this.executeSelect(request, queryRequest, response, context);
115
+ if (metadataPlan) {
116
+ await this.executeMetadataSelect(request, queryRequest, metadataPlan, response, context);
117
+ }
118
+ else {
119
+ await this.executeSelect(request, queryRequest, response, context);
120
+ }
102
121
  break;
103
122
  case 'ASK':
104
123
  await this.executeAsk(request, queryRequest, response, context);
@@ -181,6 +200,434 @@ class SubgraphSparqlHttpHandler extends community_server_1.HttpHandler {
181
200
  const values = Array.isArray(accept) ? accept : [accept];
182
201
  return values.some(value => typeof value === 'string' && /\bapplication\/json\b/i.test(value));
183
202
  }
203
+ classifyMetadataRead(parsed, baseUrl) {
204
+ const metadataPrefix = `${RdfAccessScope_1.METADATA_GRAPH_PREFIX}${baseUrl}`;
205
+ if ((parsed.from?.default?.length ?? 0) > 0 || (parsed.from?.named?.length ?? 0) > 0) {
206
+ return undefined;
207
+ }
208
+ const graphIris = [];
209
+ const graphVariables = new Set();
210
+ const filters = [];
211
+ const topLevelFilters = [];
212
+ const graphTriples = [];
213
+ let unNamed = false;
214
+ let unsupportedShape;
215
+ const visit = (patterns, insideGraph, branchDepth = 0) => {
216
+ for (const pattern of patterns ?? []) {
217
+ if (!pattern || typeof pattern !== 'object') {
218
+ continue;
219
+ }
220
+ if (pattern.type === 'graph') {
221
+ if (insideGraph) {
222
+ unsupportedShape ??= 'Nested GRAPH patterns are not supported for metadata reads.';
223
+ continue;
224
+ }
225
+ if (pattern.name?.termType === 'NamedNode') {
226
+ graphIris.push(pattern.name.value);
227
+ }
228
+ else if (pattern.name?.termType === 'Variable') {
229
+ graphVariables.add(pattern.name.value);
230
+ }
231
+ else {
232
+ unsupportedShape ??= 'Metadata reads require a named or variable GRAPH.';
233
+ continue;
234
+ }
235
+ visit(pattern.patterns, true, branchDepth);
236
+ continue;
237
+ }
238
+ if (pattern.type === 'bgp') {
239
+ if (!insideGraph) {
240
+ unNamed = true;
241
+ }
242
+ else if (pattern.triples) {
243
+ for (const triple of pattern.triples) {
244
+ graphTriples.push({ ...triple, pattern });
245
+ }
246
+ }
247
+ continue;
248
+ }
249
+ if (pattern.type === 'optional' || pattern.type === 'group' || pattern.type === 'union') {
250
+ if (!insideGraph)
251
+ unNamed = true;
252
+ const nested = pattern.type === 'union'
253
+ ? (pattern.patterns ?? []).flatMap((branch) => branch.patterns ?? [branch])
254
+ : pattern.patterns;
255
+ // A filter inside a UNION/OPTIONAL branch constrains only that branch, so it
256
+ // cannot prove ownership for the other branches. Only a filter that applies
257
+ // to the whole pattern group (branchDepth 0) may satisfy the check.
258
+ visit(nested, insideGraph, pattern.type === 'group' ? branchDepth : branchDepth + 1);
259
+ continue;
260
+ }
261
+ if (pattern.type === 'filter') {
262
+ filters.push(pattern);
263
+ if (branchDepth === 0) {
264
+ topLevelFilters.push(pattern);
265
+ }
266
+ continue;
267
+ }
268
+ if (pattern.type === 'bind') {
269
+ // A top-level BIND computes a term; it does not read the data namespace.
270
+ continue;
271
+ }
272
+ if (!insideGraph && (pattern.type === 'minus' || pattern.type === 'exists' || pattern.type === 'values')) {
273
+ unNamed = true;
274
+ }
275
+ }
276
+ };
277
+ visit(parsed.where, false);
278
+ // Ordinary SELECTs (including ordinary GRAPH/?g data queries) never enter the
279
+ // metadata path. Shape errors are only reported after a metadata signal was found.
280
+ const namedMetadata = graphIris.filter((iri) => (0, RdfAccessScope_1.isMetadataGraphIri)(iri) && iri.startsWith(metadataPrefix));
281
+ const graphVariable = graphVariables.size === 1 ? [...graphVariables][0] : undefined;
282
+ const boundedVariable = graphVariable !== undefined
283
+ && this.hasBoundedMetadataGraphFilter(topLevelFilters, graphVariable, metadataPrefix);
284
+ const metadataSignal = namedMetadata.length > 0 || boundedVariable;
285
+ if (!metadataSignal) {
286
+ const outOfBaseMetadata = graphIris.find((iri) => (0, RdfAccessScope_1.isMetadataGraphIri)(iri));
287
+ if (graphIris.length === 0 && graphVariables.size === 0) {
288
+ return undefined;
289
+ }
290
+ if (outOfBaseMetadata) {
291
+ throw new community_server_2.BadRequestHttpError(`Metadata graph ${outOfBaseMetadata} is outside ${metadataPrefix}.`);
292
+ }
293
+ return undefined;
294
+ }
295
+ if (unsupportedShape) {
296
+ throw new community_server_2.BadRequestHttpError(unsupportedShape);
297
+ }
298
+ const subjectVariable = graphVariable
299
+ ? this.resolveMetadataSubjectVariable(graphTriples, parsed.where, filters, graphVariable)
300
+ : undefined;
301
+ if (unNamed) {
302
+ throw new community_server_2.BadRequestHttpError('Metadata graph patterns cannot be mixed with un-named data patterns; issue a metadata-only query.');
303
+ }
304
+ if (graphIris.length > 0) {
305
+ if (graphVariables.size > 0) {
306
+ throw new community_server_2.BadRequestHttpError('Metadata reads cannot mix explicit graphs with a graph variable.');
307
+ }
308
+ for (const iri of graphIris) {
309
+ if (!(0, RdfAccessScope_1.isMetadataGraphIri)(iri)) {
310
+ throw new community_server_2.BadRequestHttpError('Metadata graph reads cannot be mixed with data graph reads.');
311
+ }
312
+ if (!iri.startsWith(metadataPrefix)) {
313
+ throw new community_server_2.BadRequestHttpError(`Metadata graph ${iri} is outside ${metadataPrefix}.`);
314
+ }
315
+ }
316
+ return { kind: 'explicit', basePath: baseUrl, graphIris, rowGuard: false };
317
+ }
318
+ if (!graphVariable) {
319
+ throw new community_server_2.BadRequestHttpError('Metadata reads support at most one graph variable.');
320
+ }
321
+ if (!subjectVariable) {
322
+ throw new community_server_2.BadRequestHttpError('Metadata collection reads require a subject variable bound inside GRAPH.');
323
+ }
324
+ const projected = new Set((parsed.variables ?? [])
325
+ .map((variable) => variable?.termType === 'Variable' ? variable.value : undefined)
326
+ .filter((value) => typeof value === 'string'));
327
+ // Grouped/aggregate SELECTs legitimately project neither the graph nor the
328
+ // subject (SPARQL requires every projected variable to be grouped). The
329
+ // ownership correlation is required in the query text regardless, and the
330
+ // physical scope is pinned to the authorized graph snapshot, so an aggregate
331
+ // still only sees own facets.
332
+ const rowGuard = projected.has(graphVariable) && projected.has(subjectVariable);
333
+ if (!this.hasMetadataGraphSubjectBinding(topLevelFilters, graphVariable, subjectVariable)
334
+ && !this.hasMetadataGraphExpectedBind(parsed.where, topLevelFilters, graphVariable, subjectVariable)) {
335
+ throw new community_server_2.BadRequestHttpError('Metadata collection reads must bind graph to subject in the query: '
336
+ + `FILTER(STR(?${subjectVariable}) = STRAFTER(STR(?${graphVariable}), "meta:")) `
337
+ + 'or BIND(IRI(CONCAT("meta:", STR(?subject))) AS ?expected) + FILTER(?graph = ?expected) before ORDER/LIMIT.');
338
+ }
339
+ return { kind: 'collection', basePath: baseUrl, graphIris: [], graphVariable, subjectVariable, rowGuard };
340
+ }
341
+ /**
342
+ * Detect metadata access in a query shape that has no per-subject authorization
343
+ * (ASK/CONSTRUCT/DESCRIBE, or a SELECT the metadata classifier rejected).
344
+ * Returning a reason makes the request fail closed with an explicit 400 rather
345
+ * than silently evaluating against data graphs only.
346
+ */
347
+ unsupportedMetadataSignal(parsed, baseUrl) {
348
+ const metadataPrefix = `${RdfAccessScope_1.METADATA_GRAPH_PREFIX}${baseUrl}`;
349
+ const graphVariables = new Set();
350
+ const filters = [];
351
+ let explicit;
352
+ const visit = (patterns) => {
353
+ for (const pattern of patterns ?? []) {
354
+ if (!pattern || typeof pattern !== 'object') {
355
+ continue;
356
+ }
357
+ if (pattern.type === 'graph') {
358
+ if (pattern.name?.termType === 'NamedNode' && (0, RdfAccessScope_1.isMetadataGraphIri)(pattern.name.value)) {
359
+ explicit ??= pattern.name.value;
360
+ }
361
+ else if (pattern.name?.termType === 'Variable') {
362
+ graphVariables.add(pattern.name.value);
363
+ }
364
+ visit(pattern.patterns);
365
+ continue;
366
+ }
367
+ if (pattern.type === 'bgp' || pattern.type === 'values' || pattern.type === 'bind') {
368
+ continue;
369
+ }
370
+ if (pattern.type === 'filter') {
371
+ filters.push(pattern);
372
+ continue;
373
+ }
374
+ if (pattern.type === 'union' || pattern.type === 'optional' || pattern.type === 'group') {
375
+ visit(pattern.patterns);
376
+ continue;
377
+ }
378
+ if (pattern.type === 'query') {
379
+ // A nested SELECT/ASK reads the same store; descend so a facet inside a
380
+ // subquery is rejected here instead of quietly evaluating to empty.
381
+ visit(pattern.where);
382
+ continue;
383
+ }
384
+ if (pattern.type === 'service') {
385
+ visit(pattern.patterns);
386
+ continue;
387
+ }
388
+ }
389
+ };
390
+ visit(parsed.where);
391
+ if (explicit) {
392
+ return `Metadata graph ${explicit} is only readable through an explicit metadata SELECT; `
393
+ + 'this query shape has no per-resource authorization.';
394
+ }
395
+ for (const graphVariable of graphVariables) {
396
+ if (this.hasBoundedMetadataGraphFilter(filters, graphVariable, metadataPrefix)) {
397
+ return 'Metadata collection reads are only supported as SELECT with the graph-to-subject binding; '
398
+ + 'this query shape has no per-resource authorization.';
399
+ }
400
+ }
401
+ return undefined;
402
+ }
403
+ /**
404
+ * Derive the subject variable structurally: the first variable that appears in
405
+ * the subject slot of a triple inside the metadata GRAPH, preferring one that
406
+ * also occurs in the projected variables. Variable names carry no semantics.
407
+ */
408
+ resolveMetadataSubjectVariable(graphTriples, where, filters, graphVariable) {
409
+ const subjects = [];
410
+ for (const triple of graphTriples) {
411
+ const subject = triple.subject;
412
+ if (subject?.termType === 'Variable'
413
+ && subject.value !== graphVariable
414
+ && !subjects.includes(subject.value)) {
415
+ subjects.push(subject.value);
416
+ }
417
+ }
418
+ // Prefer the subject the query explicitly ties to the graph.
419
+ const bound = subjects.find((candidate) => this.hasMetadataGraphSubjectBinding(filters, graphVariable, candidate));
420
+ if (bound) {
421
+ return bound;
422
+ }
423
+ if (subjects.length > 0) {
424
+ return subjects[0];
425
+ }
426
+ // A query may bind the metadata subject through IRI(CONCAT("meta:", STR(?s)))
427
+ // instead of a subject-slot triple; accept exactly one such structural bind.
428
+ const dynamicSubjects = new Set();
429
+ for (const pattern of where ?? []) {
430
+ if (pattern?.type !== 'bind' || pattern.variable?.termType !== 'Variable') {
431
+ continue;
432
+ }
433
+ const expr = pattern.expression;
434
+ const boundExpr = expr?.type === 'operation' && expr.operator === 'iri' ? expr.args?.[0] : expr;
435
+ const concat = boundExpr?.type === 'operation' && boundExpr.operator === 'concat' ? boundExpr.args ?? [] : [];
436
+ for (const arg of concat) {
437
+ if (arg?.type === 'operation' && arg.operator === 'str' && arg.args?.[0]?.termType === 'Variable') {
438
+ dynamicSubjects.add(arg.args[0].value);
439
+ }
440
+ }
441
+ }
442
+ return dynamicSubjects.size === 1 ? [...dynamicSubjects][0] : undefined;
443
+ }
444
+ /**
445
+ * Compatible query-level binding form: BIND(IRI(CONCAT("meta:", STR(?s))) AS
446
+ * ?expected) plus FILTER(?graph = ?expected), still evaluated before
447
+ * ORDER/LIMIT/OFFSET. Root's canonical form is the STRAFTER filter; this alias
448
+ * is accepted so an existing ORM builder does not have to rewrite first.
449
+ */
450
+ hasMetadataGraphExpectedBind(where, filters, graphVariable, subjectVariable) {
451
+ const expected = new Set();
452
+ for (const pattern of where ?? []) {
453
+ if (pattern?.type !== 'bind' || pattern.variable?.termType !== 'Variable') {
454
+ continue;
455
+ }
456
+ const expr = pattern.expression;
457
+ const bound = expr?.type === 'operation' && expr.operator === 'iri' ? expr.args?.[0] : expr;
458
+ if (bound?.type !== 'operation' || bound.operator !== 'concat') {
459
+ continue;
460
+ }
461
+ const args = bound.args ?? [];
462
+ const prefix = args[0];
463
+ const strArg = args[1];
464
+ const inner = strArg?.type === 'operation' && strArg.operator === 'str' ? strArg.args?.[0] : undefined;
465
+ if (prefix?.termType === 'Literal'
466
+ && prefix.value === RdfAccessScope_1.METADATA_GRAPH_PREFIX
467
+ && inner?.termType === 'Variable'
468
+ && inner.value === subjectVariable) {
469
+ expected.add(pattern.variable.value);
470
+ }
471
+ }
472
+ if (expected.size === 0) {
473
+ return false;
474
+ }
475
+ return filters.some((filter) => {
476
+ const expression = filter.expression;
477
+ if (expression?.type !== 'operation' || expression.operator !== '=') {
478
+ return false;
479
+ }
480
+ const [left, right] = expression.args ?? [];
481
+ const vars = [left, right].filter((arg) => arg?.termType === 'Variable').map((arg) => arg.value);
482
+ return vars.length === 2
483
+ && vars.includes(graphVariable)
484
+ && vars.some((name) => expected.has(name));
485
+ });
486
+ }
487
+ hasBoundedMetadataGraphFilter(filters, graphVariable, metadataPrefix) {
488
+ return filters.some((filter) => {
489
+ const expression = filter.expression;
490
+ if (expression?.type !== 'operation' || expression.operator !== 'strstarts') {
491
+ return false;
492
+ }
493
+ const [left, right] = expression.args ?? [];
494
+ const inner = left?.type === 'operation' && left.operator === 'str' ? left.args?.[0] : undefined;
495
+ return inner?.termType === 'Variable'
496
+ && inner.value === graphVariable
497
+ && right?.termType === 'Literal'
498
+ && right.value === metadataPrefix;
499
+ });
500
+ }
501
+ /**
502
+ * Root requires graph<->subject binding to be enforced by the query before
503
+ * ORDER/LIMIT/OFFSET, not only by a post-filter. Accept the exact
504
+ * `FILTER(STR(?subject) = STRAFTER(STR(?metadataGraph), "meta:"))` form and
505
+ * fail closed if a collection query omits it.
506
+ */
507
+ hasMetadataGraphSubjectBinding(filters, graphVariable, subjectVariable) {
508
+ return filters.some((filter) => {
509
+ const expression = filter.expression;
510
+ if (expression?.type !== 'operation' || expression.operator !== '=') {
511
+ return false;
512
+ }
513
+ const [left, right] = expression.args ?? [];
514
+ const isSubjectStr = left?.type === 'operation'
515
+ && left.operator === 'str'
516
+ && left.args?.[0]?.termType === 'Variable'
517
+ && left.args[0].value === subjectVariable;
518
+ const isStrafter = right?.type === 'operation'
519
+ && right.operator === 'strafter'
520
+ && right.args?.[0]?.type === 'operation'
521
+ && right.args[0].operator === 'str'
522
+ && right.args[0].args?.[0]?.termType === 'Variable'
523
+ && right.args[0].args[0].value === graphVariable
524
+ && right.args?.[1]?.termType === 'Literal'
525
+ && right.args[1].value === RdfAccessScope_1.METADATA_GRAPH_PREFIX;
526
+ return isSubjectStr && isStrafter;
527
+ });
528
+ }
529
+ async executeMetadataSelect(request, queryRequest, plan, response, context) {
530
+ if (typeof this.engine.queryMetadataBindings !== 'function') {
531
+ throw new RdfSparqlBoundary_1.UnsupportedSparqlQueryError('This SPARQL engine does not expose metadata facet reads.');
532
+ }
533
+ const credentials = await this.credentialsExtractor.handleSafe(request);
534
+ const memo = new Map();
535
+ const allowed = new Map();
536
+ const authorize = async (resource) => {
537
+ if (!allowed.has(resource)) {
538
+ allowed.set(resource, await this.canAuthorizeFor(resource, credentials, [policy_engine_1.PERMISSIONS.Read], memo));
539
+ }
540
+ };
541
+ let existingGraphs;
542
+ if (plan.kind === 'explicit') {
543
+ // A metadata graph that was never written is a valid empty range, not an
544
+ // error: only authorize (and later pin) graphs that the index actually has.
545
+ existingGraphs = await this.engine.listMetadataGraphs(queryRequest.baseUrl, {
546
+ basePath: `${RdfAccessScope_1.METADATA_GRAPH_PREFIX}${queryRequest.baseUrl}`,
547
+ mode: 'read',
548
+ });
549
+ for (const graph of plan.graphIris) {
550
+ if (!existingGraphs.has(graph)) {
551
+ continue;
552
+ }
553
+ await authorize(this.metadataResourceForGraph(graph, plan.basePath));
554
+ }
555
+ }
556
+ else {
557
+ const listed = await this.engine.listMetadataGraphs(queryRequest.baseUrl, {
558
+ basePath: `${RdfAccessScope_1.METADATA_GRAPH_PREFIX}${queryRequest.baseUrl}`,
559
+ mode: 'read',
560
+ });
561
+ for (const graph of listed) {
562
+ let resource;
563
+ try {
564
+ resource = this.metadataResourceForGraph(graph, plan.basePath);
565
+ }
566
+ catch {
567
+ continue;
568
+ }
569
+ await authorize(resource);
570
+ }
571
+ }
572
+ // Pin the physical graph scope to the snapshot that was actually authorized.
573
+ // A graph created after listing/authorization is therefore excluded by the
574
+ // engine before ORDER/LIMIT/aggregates, not merely by the row post-filter.
575
+ // An empty authorized snapshot fails closed without a query round trip.
576
+ const authorizedGraphs = [...allowed.entries()]
577
+ .filter(([, value]) => value)
578
+ .map(([resource]) => `${RdfAccessScope_1.METADATA_GRAPH_PREFIX}${resource}`)
579
+ .filter((graph) => plan.kind !== 'explicit' || (existingGraphs?.has(graph) ?? false))
580
+ .sort();
581
+ if (authorizedGraphs.length === 0) {
582
+ await this.sendPayload(response, JSON.stringify({ head: { vars: [] }, results: { bindings: [] } }), 'application/sparql-results+json; charset=utf-8', context);
583
+ return;
584
+ }
585
+ const scope = {
586
+ basePath: `${RdfAccessScope_1.METADATA_GRAPH_PREFIX}${queryRequest.baseUrl}`,
587
+ mode: 'read',
588
+ ...(credentials.agent?.webId ? { principal: credentials.agent.webId } : {}),
589
+ allowedGraphUrls: authorizedGraphs,
590
+ };
591
+ const results = [];
592
+ const seenVars = new Set();
593
+ const explicitDenied = plan.kind === 'explicit'
594
+ && [...allowed.values()].some((value) => !value);
595
+ if (explicitDenied) {
596
+ await this.sendPayload(response, JSON.stringify({ head: { vars: [] }, results: { bindings: [] } }), 'application/sparql-results+json; charset=utf-8', context);
597
+ return;
598
+ }
599
+ const stream = await this.engine.queryMetadataBindings(queryRequest.query, queryRequest.baseUrl, scope);
600
+ for await (const binding of stream) {
601
+ if (plan.rowGuard && !this.metadataRowAllowed(binding, plan, allowed)) {
602
+ continue;
603
+ }
604
+ const row = {};
605
+ for (const [variable, term] of binding) {
606
+ const name = typeof variable === 'string' ? variable : variable.value;
607
+ row[name] = this.termToJson(term);
608
+ seenVars.add(name);
609
+ }
610
+ results.push(row);
611
+ }
612
+ const payload = { head: { vars: [...seenVars] }, results: { bindings: results } };
613
+ await this.sendPayload(response, JSON.stringify(payload), 'application/sparql-results+json; charset=utf-8', context);
614
+ }
615
+ metadataResourceForGraph(graph, baseUrl) {
616
+ if (!(0, RdfAccessScope_1.isMetadataGraphIri)(graph) || !graph.startsWith(`${RdfAccessScope_1.METADATA_GRAPH_PREFIX}${baseUrl}`)) {
617
+ throw new community_server_2.BadRequestHttpError(`Metadata graph ${graph} is outside ${baseUrl}.`);
618
+ }
619
+ return graph.slice(RdfAccessScope_1.METADATA_GRAPH_PREFIX.length);
620
+ }
621
+ metadataRowAllowed(binding, plan, allowed) {
622
+ const graphTerm = binding.get(plan.graphVariable);
623
+ const resourceTerm = binding.get(plan.subjectVariable);
624
+ if (graphTerm?.termType !== 'NamedNode' || resourceTerm?.termType !== 'NamedNode') {
625
+ return false;
626
+ }
627
+ return graphTerm.value === `${RdfAccessScope_1.METADATA_GRAPH_PREFIX}${resourceTerm.value}`
628
+ && resourceTerm.value.startsWith(plan.basePath)
629
+ && allowed.get(resourceTerm.value) === true;
630
+ }
184
631
  async executeSelect(request, { query, basePath, baseUrl, sourceUri, defaultDataset }, response, context, trusted = false) {
185
632
  // Trusted internal requests bypass user credentials and ACL lookups, but they
186
633
  // still need an owner-scoped RDF access boundary. Without this scope the
@@ -224,6 +224,42 @@
224
224
  "@id": "undefineds:dist/http/SubgraphSparqlHttpHandler.jsonld#SubgraphSparqlHttpHandler__member_acceptsJson",
225
225
  "memberFieldName": "acceptsJson"
226
226
  },
227
+ {
228
+ "@id": "undefineds:dist/http/SubgraphSparqlHttpHandler.jsonld#SubgraphSparqlHttpHandler__member_classifyMetadataRead",
229
+ "memberFieldName": "classifyMetadataRead"
230
+ },
231
+ {
232
+ "@id": "undefineds:dist/http/SubgraphSparqlHttpHandler.jsonld#SubgraphSparqlHttpHandler__member_unsupportedMetadataSignal",
233
+ "memberFieldName": "unsupportedMetadataSignal"
234
+ },
235
+ {
236
+ "@id": "undefineds:dist/http/SubgraphSparqlHttpHandler.jsonld#SubgraphSparqlHttpHandler__member_resolveMetadataSubjectVariable",
237
+ "memberFieldName": "resolveMetadataSubjectVariable"
238
+ },
239
+ {
240
+ "@id": "undefineds:dist/http/SubgraphSparqlHttpHandler.jsonld#SubgraphSparqlHttpHandler__member_hasMetadataGraphExpectedBind",
241
+ "memberFieldName": "hasMetadataGraphExpectedBind"
242
+ },
243
+ {
244
+ "@id": "undefineds:dist/http/SubgraphSparqlHttpHandler.jsonld#SubgraphSparqlHttpHandler__member_hasBoundedMetadataGraphFilter",
245
+ "memberFieldName": "hasBoundedMetadataGraphFilter"
246
+ },
247
+ {
248
+ "@id": "undefineds:dist/http/SubgraphSparqlHttpHandler.jsonld#SubgraphSparqlHttpHandler__member_hasMetadataGraphSubjectBinding",
249
+ "memberFieldName": "hasMetadataGraphSubjectBinding"
250
+ },
251
+ {
252
+ "@id": "undefineds:dist/http/SubgraphSparqlHttpHandler.jsonld#SubgraphSparqlHttpHandler__member_executeMetadataSelect",
253
+ "memberFieldName": "executeMetadataSelect"
254
+ },
255
+ {
256
+ "@id": "undefineds:dist/http/SubgraphSparqlHttpHandler.jsonld#SubgraphSparqlHttpHandler__member_metadataResourceForGraph",
257
+ "memberFieldName": "metadataResourceForGraph"
258
+ },
259
+ {
260
+ "@id": "undefineds:dist/http/SubgraphSparqlHttpHandler.jsonld#SubgraphSparqlHttpHandler__member_metadataRowAllowed",
261
+ "memberFieldName": "metadataRowAllowed"
262
+ },
227
263
  {
228
264
  "@id": "undefineds:dist/http/SubgraphSparqlHttpHandler.jsonld#SubgraphSparqlHttpHandler__member_executeSelect",
229
265
  "memberFieldName": "executeSelect"
@@ -18,6 +18,21 @@ export declare class QleverSparqlEngine implements SparqlEngine {
18
18
  private readonly rdfEngine;
19
19
  constructor(rdfEngine: RdfEngineLike);
20
20
  queryBindings(query: string, basePath: string, accessScope?: RdfAccessScope, options?: SparqlQueryOptions): Promise<QleverBindingsStream>;
21
+ /**
22
+ * Explicit metadata facet read.
23
+ *
24
+ * The native runtime derives BOTH its graph prefix and its source URI prefix
25
+ * from `basePath`. Metadata quads are written without a source attribution
26
+ * (`SolidRdfDataAccessor.replaceMetadata` -> `rdfEngine.put` with no source),
27
+ * so a `meta:` basePath would make the physical scan join `rdf_sources` and
28
+ * drop every metadata row. A metadata-only query therefore runs with no
29
+ * basePath (graph scope ALL) and a mandatory finite ACL scope whose
30
+ * `basePath` is `meta:{base}`; the backend applies that allowed-graph-prefix
31
+ * to every scan. Callers must supply the scope: this method throws rather
32
+ * than fall back to an unscoped read.
33
+ */
34
+ queryMetadataBindings(query: string, basePath: string, accessScope?: RdfAccessScope, options?: SparqlQueryOptions): Promise<QleverBindingsStream>;
35
+ listMetadataGraphs(basePath: string, accessScope?: RdfAccessScope): Promise<Set<string>>;
21
36
  queryBoolean(query: string, basePath: string, accessScope?: RdfAccessScope, options?: SparqlQueryOptions): Promise<boolean>;
22
37
  queryQuads(query: string, basePath: string, accessScope?: RdfAccessScope, options?: SparqlQueryOptions): Promise<AsyncIterator<Quad>>;
23
38
  queryVoid(_query: string, _basePath: string, _accessScope?: RdfAccessScope, _options?: SparqlVoidOptions): Promise<void>;
@@ -4,6 +4,7 @@ exports.QleverSparqlEngine = void 0;
4
4
  const asynciterator_1 = require("asynciterator");
5
5
  const n3_1 = require("n3");
6
6
  const rdf_data_factory_1 = require("rdf-data-factory");
7
+ const RdfAccessScope_1 = require("./RdfAccessScope");
7
8
  const RdfSparqlBoundary_1 = require("./RdfSparqlBoundary");
8
9
  const RdfSparqlSerialization_1 = require("./RdfSparqlSerialization");
9
10
  const rdfDataFactory = new rdf_data_factory_1.DataFactory();
@@ -35,6 +36,45 @@ class QleverSparqlEngine {
35
36
  });
36
37
  return iterator;
37
38
  }
39
+ /**
40
+ * Explicit metadata facet read.
41
+ *
42
+ * The native runtime derives BOTH its graph prefix and its source URI prefix
43
+ * from `basePath`. Metadata quads are written without a source attribution
44
+ * (`SolidRdfDataAccessor.replaceMetadata` -> `rdfEngine.put` with no source),
45
+ * so a `meta:` basePath would make the physical scan join `rdf_sources` and
46
+ * drop every metadata row. A metadata-only query therefore runs with no
47
+ * basePath (graph scope ALL) and a mandatory finite ACL scope whose
48
+ * `basePath` is `meta:{base}`; the backend applies that allowed-graph-prefix
49
+ * to every scan. Callers must supply the scope: this method throws rather
50
+ * than fall back to an unscoped read.
51
+ */
52
+ async queryMetadataBindings(query, basePath, accessScope, options) {
53
+ const metadataBase = `${RdfAccessScope_1.METADATA_GRAPH_PREFIX}${basePath}`;
54
+ if (!accessScope?.basePath?.startsWith(metadataBase)) {
55
+ throw new RdfSparqlBoundary_1.UnsupportedSparqlQueryError('Native metadata reads require a finite meta: access scope.');
56
+ }
57
+ return this.queryBindings(query, '', {
58
+ ...accessScope,
59
+ basePath: metadataBase,
60
+ mode: 'read',
61
+ }, { ...options, defaultDataset: 'physical' });
62
+ }
63
+ async listMetadataGraphs(basePath, accessScope) {
64
+ const metadataBase = `${RdfAccessScope_1.METADATA_GRAPH_PREFIX}${basePath}`;
65
+ if (!accessScope?.basePath?.startsWith(metadataBase)) {
66
+ throw new RdfSparqlBoundary_1.UnsupportedSparqlQueryError('Native metadata reads require a finite meta: access scope.');
67
+ }
68
+ const stream = await this.queryBindings('SELECT DISTINCT ?g WHERE { GRAPH ?g { ?s ?p ?o } }', '', { ...accessScope, basePath: metadataBase, mode: 'read' }, { defaultDataset: 'physical' });
69
+ const graphs = new Set();
70
+ for await (const binding of stream) {
71
+ const graph = binding.get('g');
72
+ if (graph?.termType === 'NamedNode' && graph.value.startsWith(metadataBase)) {
73
+ graphs.add(graph.value);
74
+ }
75
+ }
76
+ return graphs;
77
+ }
38
78
  async queryBoolean(query, basePath, accessScope, options) {
39
79
  const result = await this.execute(query, basePath, 'queryBoolean', 'application/sparql-results+json', accessScope, options);
40
80
  const payload = parseSparqlJson(result);
@@ -31,6 +31,14 @@
31
31
  "@id": "undefineds:dist/storage/rdf/QleverSparqlEngine.jsonld#QleverSparqlEngine__member_queryBindings",
32
32
  "memberFieldName": "queryBindings"
33
33
  },
34
+ {
35
+ "@id": "undefineds:dist/storage/rdf/QleverSparqlEngine.jsonld#QleverSparqlEngine__member_queryMetadataBindings",
36
+ "memberFieldName": "queryMetadataBindings"
37
+ },
38
+ {
39
+ "@id": "undefineds:dist/storage/rdf/QleverSparqlEngine.jsonld#QleverSparqlEngine__member_listMetadataGraphs",
40
+ "memberFieldName": "listMetadataGraphs"
41
+ },
34
42
  {
35
43
  "@id": "undefineds:dist/storage/rdf/QleverSparqlEngine.jsonld#QleverSparqlEngine__member_queryBoolean",
36
44
  "memberFieldName": "queryBoolean"
@@ -22,5 +22,17 @@ export interface RdfAccessScope {
22
22
  export declare function isRestrictiveRdfAccessScope(scope?: RdfAccessScope): boolean;
23
23
  export declare function rdfAccessCacheScope(scope?: RdfAccessScope): RdfQueryCacheScope | undefined;
24
24
  export declare function applyRdfAccessScope(query: RdfQuery, scope?: RdfAccessScope): RdfQuery;
25
+ /** Metadata facets are stored under the literal scheme prefix `meta:`. */
26
+ export declare const METADATA_GRAPH_PREFIX = "meta:";
27
+ export declare function isMetadataGraphIri(graph: string): boolean;
28
+ /** The subject resource a metadata facet graph belongs to. */
29
+ export declare function metadataResourceForGraph(graph: string): string | undefined;
25
30
  export declare function filterRdfAccessGraphs(graphs: Iterable<string>, scope?: RdfAccessScope): Set<string>;
31
+ /**
32
+ * Read-side graph permission. A metadata facet graph is readable exactly when
33
+ * its subject resource is readable; the alias never widens the subject ACL.
34
+ * This is deliberately separate from {@link rdfAccessGraphAllowed}, which stays
35
+ * the literal write guard.
36
+ */
37
+ export declare function rdfReadGraphAllowed(graph: string, scope: RdfAccessScope): boolean;
26
38
  export declare function rdfAccessGraphAllowed(graph: string, scope: RdfAccessScope): boolean;