@powerhousedao/reactor-api 6.2.3-dev.6 → 6.2.3-dev.61
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +7 -2
- package/dist/{adapter-gateway-apollo-DowrX6E_.mjs → adapter-gateway-apollo-DTcAJpfN.mjs} +3 -3
- package/dist/{adapter-gateway-apollo-CxJNBVyD.mjs → adapter-gateway-apollo-DwAmdCYz.mjs} +17 -15
- package/dist/{adapter-gateway-apollo-CxJNBVyD.mjs.map → adapter-gateway-apollo-DwAmdCYz.mjs.map} +1 -1
- package/dist/{adapter-gateway-mercurius-CZVy88Za.mjs → adapter-gateway-mercurius-BhO0nwH_.mjs} +5 -5
- package/dist/{adapter-gateway-mercurius-CZVy88Za.mjs.map → adapter-gateway-mercurius-BhO0nwH_.mjs.map} +1 -1
- package/dist/adapter-gateway-stitching-969ZPot-.mjs +4 -0
- package/dist/{adapter-gateway-stitching-CaZjvRzx.mjs → adapter-gateway-stitching-ClVkjojb.mjs} +31 -14
- package/dist/adapter-gateway-stitching-ClVkjojb.mjs.map +1 -0
- package/dist/{adapter-http-express-B39rPhqH.mjs → adapter-http-express-P0t-mdMV.mjs} +10 -10
- package/dist/adapter-http-express-P0t-mdMV.mjs.map +1 -0
- package/dist/{adapter-http-fastify-BwXO6rqE.mjs → adapter-http-fastify-D0OP5q9K.mjs} +13 -12
- package/dist/adapter-http-fastify-D0OP5q9K.mjs.map +1 -0
- package/dist/base-document-models-69WRTSfH.mjs +1243 -0
- package/dist/base-document-models-69WRTSfH.mjs.map +1 -0
- package/dist/create-schema-DLTPkNpK.d.mts +138 -0
- package/dist/create-schema-DLTPkNpK.d.mts.map +1 -0
- package/dist/index.d.mts +2021 -732
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +3900 -1548
- package/dist/index.mjs.map +1 -1
- package/dist/pglite-node-Ow9i5Rb4.mjs +573 -0
- package/dist/pglite-node-Ow9i5Rb4.mjs.map +1 -0
- package/dist/rolldown-runtime-8H4AJuhK.mjs +16 -0
- package/dist/run-node-handler-CQjyjOuN.mjs +52 -0
- package/dist/run-node-handler-CQjyjOuN.mjs.map +1 -0
- package/dist/src/graphql/subgraph-types.d.mts +37 -0
- package/dist/src/graphql/subgraph-types.d.mts.map +1 -0
- package/dist/src/graphql/subgraph-types.mjs +105 -0
- package/dist/src/graphql/subgraph-types.mjs.map +1 -0
- package/dist/src/packages/https-hooks.d.mts +4 -4
- package/dist/src/packages/https-hooks.d.mts.map +1 -1
- package/dist/src/packages/https-hooks.mjs +2 -2
- package/dist/src/packages/https-hooks.mjs.map +1 -1
- package/dist/src/packages/vite-loader.d.mts +21 -10
- package/dist/src/packages/vite-loader.d.mts.map +1 -1
- package/dist/src/packages/vite-loader.mjs +121 -59
- package/dist/src/packages/vite-loader.mjs.map +1 -1
- package/dist/src/pglite/pglite-node.d.mts +130 -0
- package/dist/src/pglite/pglite-node.d.mts.map +1 -0
- package/dist/src/pglite/pglite-node.mjs +4 -0
- package/dist/{utils-XWVecaNn.mjs → subgraph-extraction-CcgWd0De.mjs} +540 -17
- package/dist/subgraph-extraction-CcgWd0De.mjs.map +1 -0
- package/dist/{types-DcYyNcHJ.d.mts → types-D3pD6fvQ.d.mts} +40 -5
- package/dist/types-D3pD6fvQ.d.mts.map +1 -0
- package/dist/{websocket-DncAB9XK.mjs → websocket-_SH5aBcy.mjs} +3 -3
- package/dist/{websocket-DncAB9XK.mjs.map → websocket-_SH5aBcy.mjs.map} +1 -1
- package/package.json +29 -19
- package/dist/adapter-gateway-stitching-CaZjvRzx.mjs.map +0 -1
- package/dist/adapter-http-express-B39rPhqH.mjs.map +0 -1
- package/dist/adapter-http-fastify-BwXO6rqE.mjs.map +0 -1
- package/dist/path-normalize-BOQwY9wR.mjs +0 -23
- package/dist/path-normalize-BOQwY9wR.mjs.map +0 -1
- package/dist/types-DcYyNcHJ.d.mts.map +0 -1
- package/dist/utils-XWVecaNn.mjs.map +0 -1
|
@@ -1,11 +1,16 @@
|
|
|
1
1
|
|
|
2
|
-
!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="
|
|
2
|
+
!function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="d6234293-3f1d-5df1-88ba-9b5137f78e24")}catch(e){}}();
|
|
3
|
+
import { createRequire } from "node:module";
|
|
3
4
|
import { gql } from "graphql-tag";
|
|
4
5
|
import { GraphQLError } from "graphql";
|
|
5
6
|
import { DRIVE_AUTH_ERROR_MESSAGES, RECOVERABLE_GRAPHQL_ERROR_CODES } from "@powerhousedao/reactor";
|
|
7
|
+
import { PURGE_DOCUMENT } from "@powerhousedao/shared/document-model";
|
|
8
|
+
import { verifyAuthBearerToken } from "@renown/sdk";
|
|
6
9
|
import { childLogger } from "document-model";
|
|
7
|
-
import path from "node:path";
|
|
10
|
+
import path, { dirname, isAbsolute, join } from "node:path";
|
|
11
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
8
12
|
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
13
|
+
import { packageJsonExports } from "@powerhousedao/shared/clis/constants";
|
|
9
14
|
//#region src/graphql/errors.ts
|
|
10
15
|
/** Caller (authenticated or anonymous) lacks permission for the document. */
|
|
11
16
|
var ForbiddenError = class extends GraphQLError {
|
|
@@ -60,6 +65,18 @@ var MalformedStoredOperationError = class extends GraphQLError {
|
|
|
60
65
|
super(`Stored operation cannot be served: ${detail}`, { extensions: { code: RECOVERABLE_GRAPHQL_ERROR_CODES.malformedStoredOperation } });
|
|
61
66
|
}
|
|
62
67
|
};
|
|
68
|
+
/**
|
|
69
|
+
* The marker refusals a poll carried were not recorded, so the poll fails.
|
|
70
|
+
* The code is recoverable: the client keeps polling and reports them again.
|
|
71
|
+
*/
|
|
72
|
+
var RefusalNotRecordedError = class extends GraphQLError {
|
|
73
|
+
constructor(cause) {
|
|
74
|
+
super("A reported marker refusal was not recorded; report it again", {
|
|
75
|
+
originalError: cause instanceof Error ? cause : new Error(String(cause)),
|
|
76
|
+
extensions: { code: RECOVERABLE_GRAPHQL_ERROR_CODES.refusalNotRecorded }
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
};
|
|
63
80
|
//#endregion
|
|
64
81
|
//#region src/services/authorization.service.ts
|
|
65
82
|
/**
|
|
@@ -68,6 +85,8 @@ var MalformedStoredOperationError = class extends GraphQLError {
|
|
|
68
85
|
* identifier when the check was skipped for a policy-wide caller.
|
|
69
86
|
*/
|
|
70
87
|
var AuthorizedDocumentHandle = class AuthorizedDocumentHandle {
|
|
88
|
+
fetchIdentifier;
|
|
89
|
+
isResolved;
|
|
71
90
|
constructor(fetchIdentifier, isResolved) {
|
|
72
91
|
this.fetchIdentifier = fetchIdentifier;
|
|
73
92
|
this.isResolved = isResolved;
|
|
@@ -91,6 +110,7 @@ const AuthorizationPolicy = {
|
|
|
91
110
|
};
|
|
92
111
|
/** Shared config holder and admin-list check for the policy strategies. */
|
|
93
112
|
var BaseAuthorizationService = class {
|
|
113
|
+
config;
|
|
94
114
|
constructor(config) {
|
|
95
115
|
this.config = config;
|
|
96
116
|
}
|
|
@@ -174,6 +194,7 @@ var DocumentPermissionsAuthorizationService = class extends BaseAuthorizationSer
|
|
|
174
194
|
}
|
|
175
195
|
async canMutate(documentId, operationType, userAddress) {
|
|
176
196
|
if (this.isSupremeAdmin(userAddress)) return true;
|
|
197
|
+
if (operationType === PURGE_DOCUMENT) return this.#isDocumentAdmin(documentId, userAddress);
|
|
177
198
|
if (await this.#permissions.isOperationRestricted(documentId, operationType)) {
|
|
178
199
|
if (!userAddress) return false;
|
|
179
200
|
if (await this.#isDocumentAdmin(documentId, userAddress)) return true;
|
|
@@ -267,7 +288,217 @@ function createCanonicalDocumentIdResolver(client) {
|
|
|
267
288
|
};
|
|
268
289
|
}
|
|
269
290
|
//#endregion
|
|
291
|
+
//#region src/services/auth.service.ts
|
|
292
|
+
const DEFAULT_CREDENTIAL_CACHE_TTL_MS = 6e4;
|
|
293
|
+
const CREDENTIAL_CACHE_MAX_ENTRIES = 1e3;
|
|
294
|
+
/** The invalidator a subgraph receives: forwards to `authService`, or does
|
|
295
|
+
* nothing when the host runs without one. */
|
|
296
|
+
function createCredentialInvalidator(authService) {
|
|
297
|
+
return { invalidateCredential: (address, chainId, appDid) => authService?.invalidateCredential(address, chainId, appDid) ?? 0 };
|
|
298
|
+
}
|
|
299
|
+
var AuthService = class {
|
|
300
|
+
config;
|
|
301
|
+
credentialCache = /* @__PURE__ */ new Map();
|
|
302
|
+
invalidationListeners = /* @__PURE__ */ new Set();
|
|
303
|
+
constructor(config) {
|
|
304
|
+
this.config = config;
|
|
305
|
+
}
|
|
306
|
+
/**
|
|
307
|
+
* Whether this service reads the bearer at all. Defaults to `enabled`, so a
|
|
308
|
+
* config written before `resolveIdentity` existed behaves exactly as it did.
|
|
309
|
+
*/
|
|
310
|
+
get resolvesIdentity() {
|
|
311
|
+
return this.config.resolveIdentity ?? this.config.enabled;
|
|
312
|
+
}
|
|
313
|
+
/** The context an unresolved request gets: no user, and no admin list to match against. */
|
|
314
|
+
anonymousContext() {
|
|
315
|
+
return {
|
|
316
|
+
user: void 0,
|
|
317
|
+
admins: [],
|
|
318
|
+
auth_enabled: this.config.enabled
|
|
319
|
+
};
|
|
320
|
+
}
|
|
321
|
+
async authenticateRequest(request) {
|
|
322
|
+
if (!this.resolvesIdentity) return this.anonymousContext();
|
|
323
|
+
if (request.method === "OPTIONS") return {
|
|
324
|
+
user: void 0,
|
|
325
|
+
admins: this.config.admins,
|
|
326
|
+
auth_enabled: this.config.enabled
|
|
327
|
+
};
|
|
328
|
+
return this.verifyBearer(request.headers.get("authorization") ?? void 0);
|
|
329
|
+
}
|
|
330
|
+
/**
|
|
331
|
+
* Verify a Bearer token regardless of HTTP method. Use this from non-GraphQL
|
|
332
|
+
* middleware that must enforce authentication on every request.
|
|
333
|
+
*/
|
|
334
|
+
async verifyBearer(authorization) {
|
|
335
|
+
if (!this.resolvesIdentity) return this.anonymousContext();
|
|
336
|
+
const token = authorization?.split(" ")[1];
|
|
337
|
+
if (!token) return {
|
|
338
|
+
user: void 0,
|
|
339
|
+
admins: this.config.admins,
|
|
340
|
+
auth_enabled: this.config.enabled
|
|
341
|
+
};
|
|
342
|
+
try {
|
|
343
|
+
const verified = await this.verifyToken(token);
|
|
344
|
+
if (!verified) return new Response(JSON.stringify({ error: "Verification failed" }), { status: 401 });
|
|
345
|
+
const user = this.extractUserFromVerification(verified);
|
|
346
|
+
if (!user) return new Response(JSON.stringify({ error: "Missing credentials" }), { status: 401 });
|
|
347
|
+
if (!this.config.skipCredentialVerification) {
|
|
348
|
+
if (!await this.verifyCredentialExists(user.address, user.chainId, verified.issuer)) return new Response(JSON.stringify({ error: "Credentials no longer valid" }), { status: 401 });
|
|
349
|
+
}
|
|
350
|
+
return {
|
|
351
|
+
user,
|
|
352
|
+
admins: this.config.admins,
|
|
353
|
+
auth_enabled: this.config.enabled
|
|
354
|
+
};
|
|
355
|
+
} catch {
|
|
356
|
+
return new Response(JSON.stringify({ error: "Authentication failed" }), { status: 401 });
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
/** Throws only for a bearer that is present and unusable, as HTTP 401s it. */
|
|
360
|
+
async authenticateWebSocketConnection(connectionParams) {
|
|
361
|
+
if (!this.resolvesIdentity) return null;
|
|
362
|
+
const authHeader = connectionParams.authorization;
|
|
363
|
+
if (!authHeader) return null;
|
|
364
|
+
const token = authHeader.split(" ")[1];
|
|
365
|
+
if (!token) throw new Error("Invalid authorization format");
|
|
366
|
+
const verified = await this.verifyToken(token);
|
|
367
|
+
if (!verified) throw new Error("Token verification failed");
|
|
368
|
+
const user = this.extractUserFromVerification(verified);
|
|
369
|
+
if (!user) throw new Error("Invalid credentials");
|
|
370
|
+
if (!this.config.skipCredentialVerification) {
|
|
371
|
+
if (!await this.verifyCredentialExists(user.address, user.chainId, verified.issuer)) throw new Error("Credentials no longer valid");
|
|
372
|
+
}
|
|
373
|
+
return user;
|
|
374
|
+
}
|
|
375
|
+
/** {@inheritDoc ICredentialInvalidator.invalidateCredential} */
|
|
376
|
+
invalidateCredential(address, chainId, appDid) {
|
|
377
|
+
const normalized = address.toLowerCase();
|
|
378
|
+
let evicted = 0;
|
|
379
|
+
for (const [key, entry] of this.credentialCache) if (entry.address === normalized && (chainId === void 0 || entry.chainId === chainId) && (appDid === void 0 || entry.appId === appDid)) {
|
|
380
|
+
this.credentialCache.delete(key);
|
|
381
|
+
evicted++;
|
|
382
|
+
}
|
|
383
|
+
const invalidation = { address: normalized };
|
|
384
|
+
if (chainId !== void 0) invalidation.chainId = chainId;
|
|
385
|
+
if (appDid !== void 0) invalidation.appDid = appDid;
|
|
386
|
+
for (const listener of this.invalidationListeners) try {
|
|
387
|
+
listener(invalidation);
|
|
388
|
+
} catch {}
|
|
389
|
+
return evicted;
|
|
390
|
+
}
|
|
391
|
+
/** Called after every `invalidateCredential`; returns an unsubscribe. */
|
|
392
|
+
onCredentialInvalidated(listener) {
|
|
393
|
+
this.invalidationListeners.add(listener);
|
|
394
|
+
return () => {
|
|
395
|
+
this.invalidationListeners.delete(listener);
|
|
396
|
+
};
|
|
397
|
+
}
|
|
398
|
+
/**
|
|
399
|
+
* Whether an already-authenticated principal's credential still holds, for
|
|
400
|
+
* re-checking long-lived connections. Goes through the same cache as
|
|
401
|
+
* admission, so it costs at most one verifier call per identity per TTL.
|
|
402
|
+
*/
|
|
403
|
+
async isCredentialValid(user) {
|
|
404
|
+
if (this.config.skipCredentialVerification) return true;
|
|
405
|
+
return this.verifyCredentialExists(user.address, user.chainId, user.appKey);
|
|
406
|
+
}
|
|
407
|
+
/**
|
|
408
|
+
* Verify the auth bearer token
|
|
409
|
+
*/
|
|
410
|
+
async verifyToken(token) {
|
|
411
|
+
return await verifyAuthBearerToken(token);
|
|
412
|
+
}
|
|
413
|
+
/**
|
|
414
|
+
* Extract user information from verification result.
|
|
415
|
+
*
|
|
416
|
+
* The issuer is required along with the credential subject. A credential that
|
|
417
|
+
* verified must carry one -- resolving it is how the signature was checked --
|
|
418
|
+
* so this rejects a shape that cannot have come from verification rather than
|
|
419
|
+
* admitting a keyless principal.
|
|
420
|
+
*/
|
|
421
|
+
extractUserFromVerification(verified) {
|
|
422
|
+
try {
|
|
423
|
+
const { address, chainId, networkId } = verified.verifiableCredential.credentialSubject;
|
|
424
|
+
const appKey = verified.issuer;
|
|
425
|
+
if (!address || !chainId || !networkId || !appKey) return null;
|
|
426
|
+
return {
|
|
427
|
+
address,
|
|
428
|
+
chainId,
|
|
429
|
+
networkId,
|
|
430
|
+
appKey
|
|
431
|
+
};
|
|
432
|
+
} catch {
|
|
433
|
+
return null;
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
/**
|
|
437
|
+
* Verify that the credential still exists on the Renown API.
|
|
438
|
+
*
|
|
439
|
+
* Results are cached per (address, chainId, issuer) for a short TTL so the
|
|
440
|
+
* blocking external round-trip is not paid on every request. Concurrent
|
|
441
|
+
* checks for the same key share a single in-flight request, and entries
|
|
442
|
+
* that resolve to false are evicted immediately so failed or revoked
|
|
443
|
+
* credentials are re-checked on the next request.
|
|
444
|
+
*/
|
|
445
|
+
verifyCredentialExists(address, chainId, appId) {
|
|
446
|
+
const ttlMs = this.config.credentialVerificationCacheTtlMs ?? DEFAULT_CREDENTIAL_CACHE_TTL_MS;
|
|
447
|
+
if (ttlMs <= 0) return this.fetchCredentialExists(address, chainId, appId);
|
|
448
|
+
const key = `${address.toLowerCase()}:${chainId}:${appId}`;
|
|
449
|
+
const now = Date.now();
|
|
450
|
+
const cached = this.credentialCache.get(key);
|
|
451
|
+
if (cached && cached.expiresAt > now) return cached.exists;
|
|
452
|
+
this.pruneCredentialCache(now);
|
|
453
|
+
const entry = {
|
|
454
|
+
exists: this.fetchCredentialExists(address, chainId, appId).then((exists) => {
|
|
455
|
+
if (!exists && this.credentialCache.get(key) === entry) this.credentialCache.delete(key);
|
|
456
|
+
return exists;
|
|
457
|
+
}),
|
|
458
|
+
expiresAt: now + ttlMs,
|
|
459
|
+
address: address.toLowerCase(),
|
|
460
|
+
chainId,
|
|
461
|
+
appId
|
|
462
|
+
};
|
|
463
|
+
this.credentialCache.set(key, entry);
|
|
464
|
+
return entry.exists;
|
|
465
|
+
}
|
|
466
|
+
/**
|
|
467
|
+
* Enforce the cache size cap before inserting a new entry: drop expired
|
|
468
|
+
* entries first, then evict oldest-inserted entries (insertion order
|
|
469
|
+
* matches expiry order since the TTL is constant) until under the cap, so
|
|
470
|
+
* a flood of distinct keys cannot grow the map without bound.
|
|
471
|
+
*/
|
|
472
|
+
pruneCredentialCache(now) {
|
|
473
|
+
if (this.credentialCache.size < CREDENTIAL_CACHE_MAX_ENTRIES) return;
|
|
474
|
+
for (const [key, entry] of this.credentialCache) if (entry.expiresAt <= now) this.credentialCache.delete(key);
|
|
475
|
+
while (this.credentialCache.size >= CREDENTIAL_CACHE_MAX_ENTRIES) {
|
|
476
|
+
const oldestKey = this.credentialCache.keys().next().value;
|
|
477
|
+
if (oldestKey === void 0) break;
|
|
478
|
+
this.credentialCache.delete(oldestKey);
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
async fetchCredentialExists(address, chainId, appId) {
|
|
482
|
+
if (!this.config.verifyCredential) throw new Error("AuthService: credential verification is enabled but no verifyCredential was provided");
|
|
483
|
+
return this.config.verifyCredential({
|
|
484
|
+
address,
|
|
485
|
+
chainId,
|
|
486
|
+
appId
|
|
487
|
+
});
|
|
488
|
+
}
|
|
489
|
+
};
|
|
490
|
+
//#endregion
|
|
270
491
|
//#region src/graphql/base-subgraph.ts
|
|
492
|
+
/**
|
|
493
|
+
* The subject a request reads as: its address and the app key its token
|
|
494
|
+
* carries. Anonymous is an empty subject, never the host's signer.
|
|
495
|
+
*/
|
|
496
|
+
function callerSubject(user) {
|
|
497
|
+
return {
|
|
498
|
+
address: user?.address,
|
|
499
|
+
key: user?.appKey
|
|
500
|
+
};
|
|
501
|
+
}
|
|
271
502
|
var BaseSubgraph = class {
|
|
272
503
|
name = "example";
|
|
273
504
|
path = "";
|
|
@@ -287,12 +518,22 @@ var BaseSubgraph = class {
|
|
|
287
518
|
authorizationService;
|
|
288
519
|
syncServingGate;
|
|
289
520
|
/**
|
|
521
|
+
* The host's credential cache, for a package that revokes credentials:
|
|
522
|
+
* call `this.credentials.invalidateCredential(address, chainId?, appDid?)`
|
|
523
|
+
* right after the revocation is stored, so this host refuses the credential
|
|
524
|
+
* on the next request and closes WebSocket connections that rely on it.
|
|
525
|
+
* A no-op on a host without authentication.
|
|
526
|
+
*/
|
|
527
|
+
credentials;
|
|
528
|
+
/**
|
|
290
529
|
* Per-request memo of raw identifier to canonical document id, keyed on the
|
|
291
530
|
* request context object so entries are released when the request ends. Lets
|
|
292
531
|
* batch resolvers resolve each distinct identifier at most once.
|
|
293
532
|
*/
|
|
294
533
|
#canonicalIdMemo = /* @__PURE__ */ new WeakMap();
|
|
295
534
|
#resolveCanonical;
|
|
535
|
+
#attachments;
|
|
536
|
+
#attachmentClientMemo = /* @__PURE__ */ new WeakMap();
|
|
296
537
|
constructor(args) {
|
|
297
538
|
this.#resolveCanonical = createCanonicalDocumentIdResolver(args.reactorClient);
|
|
298
539
|
this.http = args.http;
|
|
@@ -304,6 +545,22 @@ var BaseSubgraph = class {
|
|
|
304
545
|
this.authorizationService = args.authorizationService;
|
|
305
546
|
this.syncServingGate = args.syncServingGate;
|
|
306
547
|
this.path = args.path ?? "";
|
|
548
|
+
this.#attachments = args.attachments;
|
|
549
|
+
this.credentials = args.credentials ?? createCredentialInvalidator(void 0);
|
|
550
|
+
}
|
|
551
|
+
/**
|
|
552
|
+
* An attachment client bound to this request's caller, memoized per request.
|
|
553
|
+
*
|
|
554
|
+
* @throws Error when the host provides no attachment client to subgraphs.
|
|
555
|
+
*/
|
|
556
|
+
attachmentsFor(ctx) {
|
|
557
|
+
if (!this.#attachments) throw new Error("This host provides no attachment client to subgraphs");
|
|
558
|
+
let client = this.#attachmentClientMemo.get(ctx);
|
|
559
|
+
if (!client) {
|
|
560
|
+
client = this.#attachments.forSubject(callerSubject(ctx.user));
|
|
561
|
+
this.#attachmentClientMemo.set(ctx, client);
|
|
562
|
+
}
|
|
563
|
+
return client;
|
|
307
564
|
}
|
|
308
565
|
async onSetup() {}
|
|
309
566
|
async onDisconnect() {}
|
|
@@ -361,6 +618,13 @@ var BaseSubgraph = class {
|
|
|
361
618
|
async canReadDocument(documentId, ctx) {
|
|
362
619
|
return this.authorizationService.canRead(documentId, ctx.user?.address);
|
|
363
620
|
}
|
|
621
|
+
/** Drops the items the host's own ACL refuses the caller. */
|
|
622
|
+
async readableByHost(items, ctx) {
|
|
623
|
+
if (this.authorizationService.isSupremeAdmin(ctx.user?.address)) return [...items];
|
|
624
|
+
const readable = [];
|
|
625
|
+
for (const item of items) if (await this.canReadDocument(item.id, ctx)) readable.push(item);
|
|
626
|
+
return readable;
|
|
627
|
+
}
|
|
364
628
|
/**
|
|
365
629
|
* The principal a request decides as: the authenticated caller's address, and
|
|
366
630
|
* the did:key of the app instance whose token authenticated it.
|
|
@@ -372,10 +636,33 @@ var BaseSubgraph = class {
|
|
|
372
636
|
* carries the same key. Anonymous callers supply neither.
|
|
373
637
|
*/
|
|
374
638
|
viewSubject(ctx) {
|
|
375
|
-
return
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
639
|
+
return callerSubject(ctx.user);
|
|
640
|
+
}
|
|
641
|
+
/** Whether a listing would serve the document to the caller; fails closed. */
|
|
642
|
+
async servesDocument(documentId, ctx) {
|
|
643
|
+
if (!documentId) return false;
|
|
644
|
+
try {
|
|
645
|
+
return await this.servesDocumentOrThrows(documentId, ctx);
|
|
646
|
+
} catch {
|
|
647
|
+
return false;
|
|
648
|
+
}
|
|
649
|
+
}
|
|
650
|
+
/** {@link servesDocument}, but a reactor that cannot answer throws. */
|
|
651
|
+
servesDocumentOrThrows(identifier, ctx, view) {
|
|
652
|
+
return this.reactorClient.isServed(identifier, {
|
|
653
|
+
...view,
|
|
654
|
+
subject: this.viewSubject(ctx)
|
|
655
|
+
});
|
|
656
|
+
}
|
|
657
|
+
/**
|
|
658
|
+
* Whether a listing would serve the document to the caller: the reactor read
|
|
659
|
+
* gate, then the host's legacy layer, as `findDocuments` applies them. Absent
|
|
660
|
+
* or withheld is `false`; a failure to decide throws.
|
|
661
|
+
*/
|
|
662
|
+
async listsDocument(identifier, ctx, view) {
|
|
663
|
+
if (!await this.servesDocumentOrThrows(identifier, ctx, view)) return false;
|
|
664
|
+
if (this.authorizationService.isSupremeAdmin(ctx.user?.address)) return true;
|
|
665
|
+
return this.canReadDocument(await this.resolveCanonicalDocumentId(identifier, ctx), ctx);
|
|
379
666
|
}
|
|
380
667
|
/**
|
|
381
668
|
* Asserts read access, resolving a slug first. Returns a handle whose
|
|
@@ -555,6 +842,30 @@ async function loadDependency(packageName, subPath) {
|
|
|
555
842
|
throw e;
|
|
556
843
|
}
|
|
557
844
|
}
|
|
845
|
+
/**
|
|
846
|
+
* The subgraphs a package's `powerhouse.manifest.json` declares, when the
|
|
847
|
+
* manifest is reachable — which it is for a package identified by an
|
|
848
|
+
* absolute path (how every local project reaches the loaders). Lets the
|
|
849
|
+
* package manager warn when a manifest promises subgraphs and the loaders
|
|
850
|
+
* deliver none, instead of failing silently. For a bare package name the
|
|
851
|
+
* manifest would have to be resolved through the module system; until a
|
|
852
|
+
* caller needs that, a bare name answers [] rather than guessing.
|
|
853
|
+
*/
|
|
854
|
+
function manifestDeclaredSubgraphs(identifier) {
|
|
855
|
+
if (!path.isAbsolute(identifier)) return [];
|
|
856
|
+
try {
|
|
857
|
+
const raw = readFileSync(path.join(identifier, "powerhouse.manifest.json"), "utf-8");
|
|
858
|
+
const manifest = JSON.parse(raw);
|
|
859
|
+
if (!Array.isArray(manifest.subgraphs)) return [];
|
|
860
|
+
return manifest.subgraphs.map((subgraph) => {
|
|
861
|
+
if (typeof subgraph !== "object" || subgraph === null) return;
|
|
862
|
+
const { id, name } = subgraph;
|
|
863
|
+
return id ?? name;
|
|
864
|
+
}).filter((value) => typeof value === "string" && value.length > 0);
|
|
865
|
+
} catch {
|
|
866
|
+
return [];
|
|
867
|
+
}
|
|
868
|
+
}
|
|
558
869
|
function isUpgradeManifest(value) {
|
|
559
870
|
return typeof value === "object" && value !== null && "documentType" in value && "supportedVersions" in value && "upgrades" in value;
|
|
560
871
|
}
|
|
@@ -572,15 +883,30 @@ function extractUpgradeManifests(namespace) {
|
|
|
572
883
|
else add(value);
|
|
573
884
|
return Array.from(manifests.values());
|
|
574
885
|
}
|
|
886
|
+
/** Calls superseded before the timer fires settle with the run that follows. */
|
|
575
887
|
function debounce(func, delay = 250) {
|
|
576
888
|
let timer;
|
|
577
|
-
|
|
578
|
-
|
|
889
|
+
let waiting = [];
|
|
890
|
+
const run = async () => {
|
|
891
|
+
timer = void 0;
|
|
892
|
+
const callers = waiting;
|
|
893
|
+
waiting = [];
|
|
894
|
+
try {
|
|
895
|
+
const value = await func();
|
|
896
|
+
callers.forEach((caller) => caller.resolve(value));
|
|
897
|
+
} catch (error) {
|
|
898
|
+
callers.forEach((caller) => caller.reject(error));
|
|
899
|
+
}
|
|
900
|
+
};
|
|
901
|
+
return (immediate = false) => {
|
|
902
|
+
clearTimeout(timer);
|
|
579
903
|
return new Promise((resolve, reject) => {
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
}
|
|
904
|
+
waiting.push({
|
|
905
|
+
resolve,
|
|
906
|
+
reject
|
|
907
|
+
});
|
|
908
|
+
if (immediate) run();
|
|
909
|
+
else timer = setTimeout(() => void run(), delay);
|
|
584
910
|
});
|
|
585
911
|
};
|
|
586
912
|
}
|
|
@@ -589,12 +915,32 @@ function isSubpath(parent, dir) {
|
|
|
589
915
|
return relative && !relative.startsWith("..") && !path.isAbsolute(relative);
|
|
590
916
|
}
|
|
591
917
|
//#endregion
|
|
918
|
+
//#region src/utils/detached.ts
|
|
919
|
+
/** Logs `error` as the message's last replacement and reports it. */
|
|
920
|
+
function reportFailure({ logger, report }, error, message, ...args) {
|
|
921
|
+
logger.error(message, ...args, error);
|
|
922
|
+
try {
|
|
923
|
+
report?.(error);
|
|
924
|
+
} catch (reportError) {
|
|
925
|
+
logger.error("Reporting a failure failed: @error", reportError);
|
|
926
|
+
}
|
|
927
|
+
}
|
|
928
|
+
/** Runs work nobody awaits: a failure is logged and reported, never thrown. */
|
|
929
|
+
async function runDetached(label, task, options) {
|
|
930
|
+
try {
|
|
931
|
+
await task();
|
|
932
|
+
} catch (error) {
|
|
933
|
+
reportFailure(options, error, "@label failed: @error", label);
|
|
934
|
+
}
|
|
935
|
+
}
|
|
936
|
+
//#endregion
|
|
592
937
|
//#region src/graphql/utils.ts
|
|
593
938
|
function isSubgraphClass(candidate) {
|
|
594
939
|
if (typeof candidate !== "function") return false;
|
|
595
940
|
let proto = Object.getPrototypeOf(candidate);
|
|
596
|
-
while (proto) {
|
|
597
|
-
if (
|
|
941
|
+
while (typeof proto === "function") {
|
|
942
|
+
if (proto === BaseSubgraph) return true;
|
|
943
|
+
if (proto.name === "BaseSubgraph") return true;
|
|
598
944
|
proto = Object.getPrototypeOf(proto);
|
|
599
945
|
}
|
|
600
946
|
return false;
|
|
@@ -647,7 +993,184 @@ function buildGraphQlDriveDocument(doc) {
|
|
|
647
993
|
};
|
|
648
994
|
}
|
|
649
995
|
//#endregion
|
|
650
|
-
|
|
996
|
+
//#region src/packages/document-model-detection.ts
|
|
997
|
+
/**
|
|
998
|
+
* The one acceptance rule for a package's `document-models` module.
|
|
999
|
+
*
|
|
1000
|
+
* The three package loaders duck-typed this independently and disagreed on
|
|
1001
|
+
* one case: the http loader required `documentModel` to be non-null, while
|
|
1002
|
+
* the import and vite loaders accepted any object merely carrying the key,
|
|
1003
|
+
* so an export shaped `{ documentModel: null }` registered as a model under
|
|
1004
|
+
* two loaders and vanished under the third. The strict rule is the correct
|
|
1005
|
+
* one — a module without its documentModel cannot define a document type —
|
|
1006
|
+
* and this predicate is now the single rule all three share, the same way
|
|
1007
|
+
* extractSubgraphs unified the subgraph rule.
|
|
1008
|
+
*/
|
|
1009
|
+
function isDocumentModelModule(candidate) {
|
|
1010
|
+
if (candidate === null || typeof candidate !== "object") return false;
|
|
1011
|
+
if (!("documentModel" in candidate)) return false;
|
|
1012
|
+
const model = candidate.documentModel;
|
|
1013
|
+
return model !== null && model !== void 0;
|
|
1014
|
+
}
|
|
1015
|
+
/** Collects the document-model modules among a namespace's exports. */
|
|
1016
|
+
function extractDocumentModels(namespace) {
|
|
1017
|
+
return Object.values(namespace).filter(isDocumentModelModule);
|
|
1018
|
+
}
|
|
1019
|
+
//#endregion
|
|
1020
|
+
//#region src/packages/pieces.ts
|
|
1021
|
+
/** The sub-entry every loader asks a package for its pieces through. */
|
|
1022
|
+
const PIECES_SUBPATH = "pieces";
|
|
1023
|
+
const BUILT_PIECE_LIST = packageJsonExports["./pieces"].node;
|
|
1024
|
+
/** Where a package keeps its piece sources, for telling unbuilt from absent. */
|
|
1025
|
+
const PIECE_SOURCE_LIST = join(PIECES_SUBPATH, "index.ts");
|
|
1026
|
+
/** The nearest enclosing package.json, which `exports` usually hides. */
|
|
1027
|
+
function packageRootOf(dir) {
|
|
1028
|
+
let current = dir;
|
|
1029
|
+
while (!existsSync(join(current, "package.json"))) {
|
|
1030
|
+
const parent = dirname(current);
|
|
1031
|
+
if (parent === current) return void 0;
|
|
1032
|
+
current = parent;
|
|
1033
|
+
}
|
|
1034
|
+
return current;
|
|
1035
|
+
}
|
|
1036
|
+
function resolvePieceList(specifier, hostDir) {
|
|
1037
|
+
try {
|
|
1038
|
+
return fileURLToPath(import.meta.resolve(specifier));
|
|
1039
|
+
} catch (error) {
|
|
1040
|
+
try {
|
|
1041
|
+
return createRequire(join(hostDir, "package.json")).resolve(specifier);
|
|
1042
|
+
} catch {
|
|
1043
|
+
throw error;
|
|
1044
|
+
}
|
|
1045
|
+
}
|
|
1046
|
+
}
|
|
1047
|
+
function pieceListLocation(identifier, hostDir = process.cwd()) {
|
|
1048
|
+
if (isAbsolute(identifier)) return {
|
|
1049
|
+
root: identifier,
|
|
1050
|
+
listPath: join(identifier, BUILT_PIECE_LIST)
|
|
1051
|
+
};
|
|
1052
|
+
const listPath = resolvePieceList(`${identifier}/${PIECES_SUBPATH}`, hostDir);
|
|
1053
|
+
const root = packageRootOf(dirname(listPath));
|
|
1054
|
+
if (!root) throw new Error(`No package.json above ${listPath}`);
|
|
1055
|
+
return {
|
|
1056
|
+
root,
|
|
1057
|
+
listPath
|
|
1058
|
+
};
|
|
1059
|
+
}
|
|
1060
|
+
function packageVersionAt(root) {
|
|
1061
|
+
try {
|
|
1062
|
+
const pkg = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
|
|
1063
|
+
return typeof pkg.version === "string" && pkg.version !== "" ? pkg.version : void 0;
|
|
1064
|
+
} catch {
|
|
1065
|
+
return;
|
|
1066
|
+
}
|
|
1067
|
+
}
|
|
1068
|
+
function locatePieces(declared, context) {
|
|
1069
|
+
const { root, identifier, logger, version } = context;
|
|
1070
|
+
const located = [];
|
|
1071
|
+
for (const piece of declared) {
|
|
1072
|
+
const where = piece.entry ?? piece.bundle;
|
|
1073
|
+
if (typeof where !== "string" || where === "") {
|
|
1074
|
+
logger.warn("Piece @piece of @pkg declares neither a bundle nor an entry", piece.name, identifier);
|
|
1075
|
+
continue;
|
|
1076
|
+
}
|
|
1077
|
+
const path = isAbsolute(where) ? where : join(root, where);
|
|
1078
|
+
if (!(piece.entry ? existsSync(path) : existsSync(join(path, "package.json")))) {
|
|
1079
|
+
logger.warn("Piece @piece of @pkg is declared but not built at @path", piece.name, identifier, path);
|
|
1080
|
+
continue;
|
|
1081
|
+
}
|
|
1082
|
+
located.push({
|
|
1083
|
+
name: piece.name,
|
|
1084
|
+
version,
|
|
1085
|
+
...piece.entry ? { entryPath: path } : { bundleDir: path }
|
|
1086
|
+
});
|
|
1087
|
+
}
|
|
1088
|
+
return located;
|
|
1089
|
+
}
|
|
1090
|
+
function declaredPieces(module, identifier, logger) {
|
|
1091
|
+
const namespace = module ?? {};
|
|
1092
|
+
const declared = namespace.pieces ?? namespace.default;
|
|
1093
|
+
if (!Array.isArray(declared)) {
|
|
1094
|
+
logger.warn("The pieces list of @pkg exports no \"pieces\" array; it contributes none", identifier);
|
|
1095
|
+
return;
|
|
1096
|
+
}
|
|
1097
|
+
return declared;
|
|
1098
|
+
}
|
|
1099
|
+
function piecesFromCdnList(module, baseUrl, identifier, logger, version) {
|
|
1100
|
+
const declared = declaredPieces(module, identifier, logger);
|
|
1101
|
+
if (!declared) return [];
|
|
1102
|
+
const located = [];
|
|
1103
|
+
for (const piece of declared) {
|
|
1104
|
+
const where = piece.entry ?? piece.bundle;
|
|
1105
|
+
if (typeof where !== "string" || where === "") {
|
|
1106
|
+
logger.warn("Piece @piece of @pkg declares neither a bundle nor an entry", piece.name, identifier);
|
|
1107
|
+
continue;
|
|
1108
|
+
}
|
|
1109
|
+
located.push({
|
|
1110
|
+
name: piece.name,
|
|
1111
|
+
version,
|
|
1112
|
+
entryUrl: `${baseUrl}${where.replace(/^dist\/node\/pieces\//, "")}`
|
|
1113
|
+
});
|
|
1114
|
+
}
|
|
1115
|
+
return located;
|
|
1116
|
+
}
|
|
1117
|
+
function piecesFromListModule(module, context) {
|
|
1118
|
+
const namespace = module ?? {};
|
|
1119
|
+
const declared = namespace.pieces ?? namespace.default;
|
|
1120
|
+
if (!Array.isArray(declared)) {
|
|
1121
|
+
context.logger.warn("The pieces list of @pkg exports no \"pieces\" array; it contributes none", context.identifier);
|
|
1122
|
+
return [];
|
|
1123
|
+
}
|
|
1124
|
+
const version = packageVersionAt(context.root);
|
|
1125
|
+
if (!version) {
|
|
1126
|
+
context.logger.warn("@pkg has no version in @root/package.json, and a piece takes its package's version; its pieces contribute none", context.identifier, context.root);
|
|
1127
|
+
return [];
|
|
1128
|
+
}
|
|
1129
|
+
return locatePieces(declared, {
|
|
1130
|
+
...context,
|
|
1131
|
+
version
|
|
1132
|
+
});
|
|
1133
|
+
}
|
|
1134
|
+
//#endregion
|
|
1135
|
+
//#region src/packages/subgraph-extraction.ts
|
|
1136
|
+
/**
|
|
1137
|
+
* The one acceptance rule for a package's `subgraphs` module.
|
|
1138
|
+
*
|
|
1139
|
+
* All three package loaders (vite, import, http) consume the same generated
|
|
1140
|
+
* `subgraphs/index` file, and each used to apply its own rule — the vite
|
|
1141
|
+
* loader required a namespace whose alias equalled the class name inside it,
|
|
1142
|
+
* the http loader took any function one level deep, and the import loader
|
|
1143
|
+
* took every nested value. An export that registered under one loader could
|
|
1144
|
+
* silently vanish under another (the codegen-does-not-register-subgraphs
|
|
1145
|
+
* report). This is now the single rule they all share:
|
|
1146
|
+
*
|
|
1147
|
+
* - an export that is itself a subgraph class is accepted (named or default
|
|
1148
|
+
* export of the class);
|
|
1149
|
+
* - any subgraph class among the values of an exported object is accepted
|
|
1150
|
+
* (a `export * as Alias from ...` namespace under any alias, or a
|
|
1151
|
+
* default-exported object of classes);
|
|
1152
|
+
* - everything else — constants, configs, functions and classes that do not
|
|
1153
|
+
* extend BaseSubgraph — is dropped.
|
|
1154
|
+
*
|
|
1155
|
+
* Codegen emits `export * as <ClassName> from "./<dir>/index.js"`
|
|
1156
|
+
* (makeSubgraphsIndexFile in packages/codegen), which the namespace branch
|
|
1157
|
+
* accepts regardless of the alias; hand-written packages may re-export a
|
|
1158
|
+
* class directly, which the direct branch accepts. A class reached through
|
|
1159
|
+
* both branches is returned once.
|
|
1160
|
+
*/
|
|
1161
|
+
function extractSubgraphs(namespace) {
|
|
1162
|
+
const found = [];
|
|
1163
|
+
const add = (candidate) => {
|
|
1164
|
+
if (isSubgraphClass(candidate) && !found.includes(candidate)) found.push(candidate);
|
|
1165
|
+
};
|
|
1166
|
+
for (const value of Object.values(namespace)) {
|
|
1167
|
+
add(value);
|
|
1168
|
+
if (value !== null && typeof value === "object") for (const inner of Object.values(value)) add(inner);
|
|
1169
|
+
}
|
|
1170
|
+
return found;
|
|
1171
|
+
}
|
|
1172
|
+
//#endregion
|
|
1173
|
+
export { AuthorizationPolicy as A, manifestDeclaredSubgraphs as C, createCredentialInvalidator as D, AuthService as E, ForbiddenError as F, MalformedStoredOperationError as I, RefusalNotRecordedError as L, createAuthorizationService as M, AuthEvaluationUnsupportedError as N, CanonicalDocumentIdResolutionError as O, AuthenticationRequiredError as P, loadSubgraphs as S, callerSubject as T, debounce as _, packageRootOf as a, loadDocumentModels as b, piecesFromListModule as c, buildGraphQlDriveDocument as d, buildGraphqlOperation as f, runDetached as g, reportFailure as h, PIECE_SOURCE_LIST as i, AuthorizedDocumentHandle as j, createCanonicalDocumentIdResolver as k, extractDocumentModels as l, isSubgraphClass as m, BUILT_PIECE_LIST as n, pieceListLocation as o, buildGraphqlOperations as p, PIECES_SUBPATH as r, piecesFromCdnList as s, extractSubgraphs as t, buildGraphQlDocument as u, extractUpgradeManifests as v, BaseSubgraph as w, loadProcessors as x, isSubpath as y };
|
|
651
1174
|
|
|
652
|
-
//# sourceMappingURL=
|
|
653
|
-
//# debugId=
|
|
1175
|
+
//# sourceMappingURL=subgraph-extraction-CcgWd0De.mjs.map
|
|
1176
|
+
//# debugId=d6234293-3f1d-5df1-88ba-9b5137f78e24
|