@undefineds.co/xpod 0.4.32 → 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 (108) hide show
  1. package/dist/api/auth/SolidTokenAuthenticator.d.ts +4 -1
  2. package/dist/api/auth/SolidTokenAuthenticator.js +43 -25
  3. package/dist/api/container/common.js +1 -0
  4. package/dist/api/container/index.js +1 -0
  5. package/dist/api/container/types.d.ts +2 -0
  6. package/dist/http/SubgraphSparqlHttpHandler.d.ts +32 -0
  7. package/dist/http/SubgraphSparqlHttpHandler.js +448 -1
  8. package/dist/http/SubgraphSparqlHttpHandler.jsonld +36 -0
  9. package/dist/storage/rdf/QleverSparqlEngine.d.ts +15 -0
  10. package/dist/storage/rdf/QleverSparqlEngine.js +40 -0
  11. package/dist/storage/rdf/QleverSparqlEngine.jsonld +8 -0
  12. package/dist/storage/rdf/RdfAccessScope.d.ts +12 -0
  13. package/dist/storage/rdf/RdfAccessScope.js +63 -3
  14. package/dist/storage/rdf/RdfQuerySparqlEngine.d.ts +7 -0
  15. package/dist/storage/rdf/RdfQuerySparqlEngine.js +30 -0
  16. package/dist/storage/rdf/RdfQuerySparqlEngine.jsonld +8 -0
  17. package/dist/storage/rdf/index.d.ts +1 -1
  18. package/dist/storage/rdf/index.js +6 -2
  19. package/dist/storage/sparql/SubgraphQueryEngine.d.ts +5 -0
  20. package/dist/storage/sparql/SubgraphQueryEngine.js +9 -0
  21. package/dist/storage/sparql/SubgraphQueryEngine.jsonld +16 -0
  22. package/node_modules/@undefineds.co/ai-connections/dist/AiBuiltinProvidersSection.d.ts +32 -0
  23. package/node_modules/@undefineds.co/ai-connections/dist/AiBuiltinProvidersSection.js +8 -0
  24. package/node_modules/@undefineds.co/ai-connections/dist/AiConnectionsPanel.js +35 -1
  25. package/node_modules/@undefineds.co/ai-connections/dist/AiGatewayKeysSection.d.ts +9 -1
  26. package/node_modules/@undefineds.co/ai-connections/dist/AiGatewayKeysSection.js +32 -6
  27. package/node_modules/@undefineds.co/ai-connections/dist/index.d.ts +1 -0
  28. package/node_modules/@undefineds.co/ai-connections/dist/index.js +1 -0
  29. package/node_modules/@undefineds.co/ai-connections/package.json +2 -2
  30. package/node_modules/@undefineds.co/ai-connections-runtime/dist/contract/ai-connections-client.d.ts +1 -1
  31. package/node_modules/@undefineds.co/ai-connections-runtime/dist/contract/client/normalize.d.ts +16 -1
  32. package/node_modules/@undefineds.co/ai-connections-runtime/dist/contract/client/normalize.js +80 -2
  33. package/node_modules/@undefineds.co/ai-connections-runtime/dist/contract/client/request.js +19 -1
  34. package/node_modules/@undefineds.co/ai-connections-runtime/dist/contract/client/types.d.ts +31 -0
  35. package/node_modules/@undefineds.co/ai-connections-runtime/dist/materials/build-provenance.json +4 -4
  36. package/node_modules/@undefineds.co/ai-connections-runtime/dist/materials/index.json +15 -15
  37. package/node_modules/@undefineds.co/ai-connections-runtime/dist/materials/javascript/provider-catalog/index.json +2 -2
  38. package/node_modules/@undefineds.co/ai-connections-runtime/dist/materials/javascript/service-access-resources/index.json +2 -2
  39. package/node_modules/@undefineds.co/ai-connections-runtime/dist/materials/source/package.json +1 -1
  40. package/node_modules/@undefineds.co/ai-connections-runtime/dist/materials/source-inventory.json +11 -11
  41. package/node_modules/@undefineds.co/ai-connections-runtime/dist/provider-catalog-inputs.json +1 -1
  42. package/node_modules/@undefineds.co/ai-connections-runtime/dist/service-access-resources-inputs.json +1 -1
  43. package/node_modules/@undefineds.co/ai-connections-runtime/package.json +1 -1
  44. package/node_modules/@undefineds.co/extension-host-contracts/dist/materials/build-provenance.json +1 -1
  45. package/node_modules/@undefineds.co/extension-host-contracts/dist/materials/index.json +3 -3
  46. package/node_modules/@undefineds.co/extension-host-contracts/dist/materials/source-inventory.json +1 -1
  47. package/node_modules/@undefineds.co/xpod-afs/dist/licenses/cli-producer-original-binding.json +1 -1
  48. package/node_modules/@undefineds.co/xpod-cli/dist/producer-materials/index.json +1 -1
  49. package/package.json +4 -4
  50. package/static/dashboard/assets/{AccountAuthBoundary-D2peXpst.js → AccountAuthBoundary-DXBGmvsI.js} +1 -1
  51. package/static/dashboard/assets/{DesktopOidcCallback-DXWArav6.js → DesktopOidcCallback-p24MYq1P.js} +1 -1
  52. package/static/dashboard/assets/{DevicePages-BULFk95K.js → DevicePages-DbvhTnse.js} +1 -1
  53. package/static/dashboard/assets/ModelsPage-UMDnRyLA.js +12 -0
  54. package/static/dashboard/assets/{PaneListHeader-BSfEbecP.js → PaneListHeader-DkEH0TT_.js} +1 -1
  55. package/static/dashboard/assets/{PodDeletionAuthorizationPanel-CH-Sx18g.js → PodDeletionAuthorizationPanel-CzrI8Pgw.js} +3 -3
  56. package/static/dashboard/assets/{PodPage-BMpejIra.js → PodPage-TaiWqMBx.js} +1 -1
  57. package/static/dashboard/assets/{SystemSettingsPage-H_Jj6WfF.js → SystemSettingsPage-D4gQjDt1.js} +1 -1
  58. package/static/dashboard/assets/{TasksPage-CTDxlQra.js → TasksPage-CmkiMYil.js} +1 -1
  59. package/static/dashboard/assets/{WebDesktopEntry-Ch7-0C9a.js → WebDesktopEntry-D9kEfhbz.js} +1 -1
  60. package/static/dashboard/assets/{XpodAiConnectionsPodStore-ggRE9fmE.js → XpodAiConnectionsPodStore-orY8vQFl.js} +2 -2
  61. package/static/dashboard/assets/{XpodShellApp-Bwf9UmeJ.js → XpodShellApp-DR65DMOb.js} +4 -4
  62. package/static/dashboard/assets/{account-session-CVzooxS2.js → account-session-BZ2ttIdq.js} +1 -1
  63. package/static/dashboard/assets/{button-DGh2QVt2.js → button-_rwfCMMH.js} +1 -1
  64. package/static/dashboard/assets/{collection-runtime-DwV_9rt2.js → collection-runtime-C74icLtf.js} +1 -1
  65. package/static/dashboard/assets/{createLucideIcon-yLhAxnfL.js → createLucideIcon-DrgScGhc.js} +1 -1
  66. package/static/dashboard/assets/{dashboard-xbXlitKr.js → dashboard--DWjqkYt.js} +2 -2
  67. package/static/dashboard/assets/{index-CMigfjqD.js → index-D6dB-UNq.js} +1 -1
  68. package/static/dashboard/assets/{index-BSiKqEdo.js → index-dx5sc4rE.js} +1 -1
  69. package/static/dashboard/assets/{label-CrDv_y1q.js → label-D02Jpvm9.js} +1 -1
  70. package/static/dashboard/assets/{list-BJM0nqti.js → list-DpFAisnq.js} +1 -1
  71. package/static/dashboard/assets/{nav-item-style-CQbGyYLb.js → nav-item-style-B1-0JkON.js} +1 -1
  72. package/static/dashboard/assets/{safe-continuation-ZTBQTFWB.js → safe-continuation-DUTIOFe5.js} +1 -1
  73. package/static/dashboard/assets/{section-header-CWHRWGXl.js → section-header-CtBnllbG.js} +1 -1
  74. package/static/dashboard/assets/{setting-row-qWtxYGK1.js → setting-row-D_JPuHAJ.js} +1 -1
  75. package/static/dashboard/assets/{xpod-remembered-login-DPMxurVN.js → xpod-remembered-login-CtmMI8xG.js} +3 -3
  76. package/static/dashboard/dashboard.html +1 -1
  77. package/static/settings/assets/{AccountAuthBoundary-4Ywjpb8o.js → AccountAuthBoundary-njIhHpLf.js} +1 -1
  78. package/static/settings/assets/{DesktopOidcCallback-CAmwMT_J.js → DesktopOidcCallback-BjjNwTxc.js} +1 -1
  79. package/static/settings/assets/{DevicePages-DvuHyfHo.js → DevicePages-FFJMu_zL.js} +1 -1
  80. package/static/settings/assets/ModelsPage-6567dZKQ.js +12 -0
  81. package/static/settings/assets/{PaneListHeader-CuFgIbhe.js → PaneListHeader-CuPah5aC.js} +1 -1
  82. package/static/settings/assets/{PodDeletionAuthorizationPanel-DdNgDHH5.js → PodDeletionAuthorizationPanel-aJCKasGz.js} +3 -3
  83. package/static/settings/assets/{PodPage-DnWCNGTO.js → PodPage-BA0DQ3AB.js} +1 -1
  84. package/static/settings/assets/{SystemSettingsPage-k9P_wQcl.js → SystemSettingsPage-BNPH4VWf.js} +1 -1
  85. package/static/settings/assets/{TasksPage-Dk7gUH3J.js → TasksPage-B5m82wjD.js} +1 -1
  86. package/static/settings/assets/{WebDesktopEntry-DJwPVVnU.js → WebDesktopEntry-DgwwIUhg.js} +1 -1
  87. package/static/settings/assets/{XpodAiConnectionsPodStore-BtJQiJsx.js → XpodAiConnectionsPodStore-BJm-rFPs.js} +2 -2
  88. package/static/settings/assets/{XpodShellApp-B47vEQJp.js → XpodShellApp-BwvekJJR.js} +4 -4
  89. package/static/settings/assets/{XpodThemeProvider-Ciuwo_yl.js → XpodThemeProvider-DyX0rUID.js} +2 -2
  90. package/static/settings/assets/{account-session-CMc10iEj.js → account-session-D6vibAra.js} +1 -1
  91. package/static/settings/assets/auth-callback-DXxmF0-p.js +1 -0
  92. package/static/settings/assets/{button-D1dGKY1f.js → button-CV4KJ59A.js} +1 -1
  93. package/static/settings/assets/{collection-runtime-hK37-47o.js → collection-runtime-CARp4Cii.js} +1 -1
  94. package/static/settings/assets/{createLucideIcon-nEiQH43b.js → createLucideIcon-BIwq0vQx.js} +1 -1
  95. package/static/settings/assets/{index-DNdvma6J.js → index-D-LgcKAb.js} +1 -1
  96. package/static/settings/assets/{label-C3EGk_2E.js → label-CFTl2bC_.js} +1 -1
  97. package/static/settings/assets/{list-BensBGZp.js → list-D2aO7Nu-.js} +1 -1
  98. package/static/settings/assets/{nav-item-style-BOKCPNz8.js → nav-item-style-BKpK5_1m.js} +1 -1
  99. package/static/settings/assets/{safe-continuation-BPwW6jdq.js → safe-continuation-DRRY_t4F.js} +1 -1
  100. package/static/settings/assets/{section-header-DOSj5RvJ.js → section-header-COECjyL5.js} +1 -1
  101. package/static/settings/assets/{setting-row-C9k4cGNM.js → setting-row-cGgL78vR.js} +1 -1
  102. package/static/settings/assets/{settings-DtP5C8hi.js → settings-Bvrm5N-k.js} +1 -1
  103. package/static/settings/assets/{xpod-remembered-login-DKFG-zi3.js → xpod-remembered-login-YAmn8ZiP.js} +3 -3
  104. package/static/settings/auth-callback.html +2 -2
  105. package/static/settings/settings.html +2 -2
  106. package/static/dashboard/assets/ModelsPage-xvsVzhGZ.js +0 -12
  107. package/static/settings/assets/ModelsPage-BDXqetwk.js +0 -12
  108. package/static/settings/assets/auth-callback-fcOBaX2w.js +0 -1
@@ -6,6 +6,8 @@ export interface SolidTokenAuthenticatorOptions {
6
6
  */
7
7
  resolveAccountId?: (webId: string) => Promise<string | undefined>;
8
8
  publicBaseUrl?: string;
9
+ /** Published API endpoint for this Cloud deployment, independent of its identity origin. */
10
+ apiBaseUrl?: string;
9
11
  internalBaseUrl?: string;
10
12
  }
11
13
  /**
@@ -16,13 +18,14 @@ export declare class SolidTokenAuthenticator implements Authenticator {
16
18
  private readonly verify;
17
19
  private readonly resolveAccountId?;
18
20
  private readonly publicOrigin?;
21
+ private readonly canonicalOrigins;
19
22
  constructor(options?: SolidTokenAuthenticatorOptions);
20
23
  canAuthenticate(request: IncomingMessage): boolean;
21
24
  authenticate(request: IncomingMessage): Promise<AuthResult>;
22
25
  private buildRequestUrl;
23
26
  private verifyRequest;
24
27
  private trustedCanonicalRouteUrl;
25
- private configuredCanonicalRequestUrl;
28
+ private configuredCanonicalRequestUrls;
26
29
  private hasLocalRouteHeader;
27
30
  private firstHeaderValue;
28
31
  private pathAndSearch;
@@ -7,6 +7,20 @@ const SolidTokenCaches_1 = require("../../authentication/SolidTokenCaches");
7
7
  const ConfiguredLoopbackSolidTokenVerifier_1 = require("../../authentication/ConfiguredLoopbackSolidTokenVerifier");
8
8
  const SOLID_LOCAL_ROUTE_CANONICAL_URL_HEADER = 'x-xpod-canonical-url';
9
9
  const SOLID_LOCAL_ROUTE_LOCAL_URL_HEADER = 'x-xpod-local-route-url';
10
+ function configuredApiOrigin(value) {
11
+ if (!value?.trim())
12
+ return undefined;
13
+ try {
14
+ const url = new URL(value);
15
+ if (url.protocol !== 'https:' || url.username || url.password || url.search || url.hash) {
16
+ return undefined;
17
+ }
18
+ return url.origin;
19
+ }
20
+ catch {
21
+ return undefined;
22
+ }
23
+ }
10
24
  /**
11
25
  * Parse one Solid Authorization header value into its canonical scheme and token.
12
26
  *
@@ -40,6 +54,12 @@ class SolidTokenAuthenticator {
40
54
  this.resolveAccountId = options.resolveAccountId;
41
55
  const { issuerKeySetCache, webIdIssuersCache, publicOrigin } = (0, SolidTokenCaches_1.createRoutedSolidTokenCaches)(options);
42
56
  this.publicOrigin = publicOrigin;
57
+ // Discovery and trusted local-route hints still use the identity authority.
58
+ // Only the no-hint retry also accepts this deployment's configured API origin.
59
+ this.canonicalOrigins = [...new Set([
60
+ publicOrigin,
61
+ configuredApiOrigin(options.apiBaseUrl),
62
+ ].filter((origin) => origin !== undefined))];
43
63
  const loopbackOrigin = (0, ConfiguredLoopbackSolidTokenVerifier_1.configuredHttpLoopbackOrigin)(publicOrigin);
44
64
  this.verify = loopbackOrigin
45
65
  ? (0, ConfiguredLoopbackSolidTokenVerifier_1.createConfiguredLoopbackSolidTokenVerifier)({
@@ -143,22 +163,20 @@ class SolidTokenAuthenticator {
143
163
  if (!dpopHeader) {
144
164
  throw error;
145
165
  }
146
- const configuredCanonicalUrl = this.configuredCanonicalRequestUrl(request, url);
147
- if (!configuredCanonicalUrl) {
148
- throw error;
149
- }
150
- try {
151
- return await this.verify(authorization, {
152
- header: dpopHeader,
153
- method,
154
- url: configuredCanonicalUrl,
155
- });
156
- }
157
- catch {
158
- // Retain the primary diagnostic when both attempts fail: reporting the
159
- // retry's htu mismatch would hide the reason the caller actually failed.
160
- throw error;
166
+ for (const configuredCanonicalUrl of this.configuredCanonicalRequestUrls(request, url)) {
167
+ try {
168
+ return await this.verify(authorization, {
169
+ header: dpopHeader,
170
+ method,
171
+ url: configuredCanonicalUrl,
172
+ });
173
+ }
174
+ catch {
175
+ // Every retry performs full verification. Preserve the primary error
176
+ // if none of the deployment's configured authorities verifies it.
177
+ }
161
178
  }
179
+ throw error;
162
180
  }
163
181
  }
164
182
  trustedCanonicalRouteUrl(request) {
@@ -194,20 +212,20 @@ class SolidTokenAuthenticator {
194
212
  }
195
213
  return canonicalUrl.href;
196
214
  }
197
- configuredCanonicalRequestUrl(request, primaryUrl) {
198
- if (!this.publicOrigin || this.hasLocalRouteHeader(request)) {
199
- return undefined;
200
- }
201
- const publicUrl = new URL(this.publicOrigin);
202
- if (publicUrl.protocol !== 'https:') {
203
- return undefined;
215
+ configuredCanonicalRequestUrls(request, primaryUrl) {
216
+ if (this.hasLocalRouteHeader(request)) {
217
+ return [];
204
218
  }
205
219
  const requestPath = this.pathAndSearch(request.url ?? '/');
206
220
  if (!requestPath) {
207
- return undefined;
221
+ return [];
208
222
  }
209
- const configuredUrl = new URL(requestPath, this.publicOrigin).href;
210
- return configuredUrl === primaryUrl ? undefined : configuredUrl;
223
+ return this.canonicalOrigins.flatMap((origin) => {
224
+ if (new URL(origin).protocol !== 'https:')
225
+ return [];
226
+ const configuredUrl = new URL(requestPath, origin).href;
227
+ return configuredUrl === primaryUrl ? [] : [configuredUrl];
228
+ });
211
229
  }
212
230
  hasLocalRouteHeader(request) {
213
231
  return this.firstHeaderValue(request.headers[SOLID_LOCAL_ROUTE_CANONICAL_URL_HEADER]) !== undefined ||
@@ -574,6 +574,7 @@ function registerCommonServices(container) {
574
574
  publicBaseUrl: config.edition === 'local' && config.publicUrl
575
575
  ? (0, storage_base_url_1.resolveLocalStorageProviderBaseUrl)(config)
576
576
  : config.solidBaseUrl,
577
+ apiBaseUrl: config.edition === 'cloud' ? config.apiBaseUrl : undefined,
577
578
  // Token discovery is a public OIDC concern. WebID/JWKS verification is
578
579
  // an internal service call and must not hairpin through public ingress.
579
580
  internalBaseUrl: resolveHostedPodCssBaseUrl(config),
@@ -179,6 +179,7 @@ function loadConfigFromEnv() {
179
179
  corsOrigins: process.env.CORS_ORIGINS?.split(',').map(s => s.trim()) ?? ['*'],
180
180
  cssTokenEndpoint: resolveCssTokenEndpoint(),
181
181
  solidBaseUrl,
182
+ apiBaseUrl: normalizeOptionalUrl(process.env.XPOD_API_BASE_URL),
182
183
  solidRootFilePath: path.resolve(rootDir),
183
184
  aiConnectionInvocationSecret: process.env.XPOD_AI_CONNECTION_INVOCATION_SECRET,
184
185
  aiConnectionInvocationKeyId: process.env.XPOD_AI_CONNECTION_INVOCATION_KEY_ID,
@@ -117,6 +117,8 @@ export interface ApiContainerConfig {
117
117
  /** CSS Token 端点 */
118
118
  cssTokenEndpoint: string;
119
119
  solidBaseUrl?: string;
120
+ /** Published API endpoint from XPOD_API_BASE_URL; distinct from the Solid identity origin. */
121
+ apiBaseUrl?: string;
120
122
  /** Captured CSS filesystem root for this runtime, independent of later process.env changes. */
121
123
  solidRootFilePath?: string;
122
124
  /** Stateless AI Connections invocation token signing config. */
@@ -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