@powerhousedao/reactor-api 6.2.3-dev.57 → 6.2.3-dev.59

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/dist/index.mjs CHANGED
@@ -1,7 +1,7 @@
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]="5a6cd51c-1122-5d95-9bcf-8cf26e403d05")}catch(e){}}();
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]="061cb7f9-bbbc-55da-a218-225c0b3c993d")}catch(e){}}();
3
3
  import { t as __exportAll } from "./rolldown-runtime-8H4AJuhK.mjs";
4
- import { A as createAuthorizationService, C as manifestDeclaredSubgraphs, D as createCanonicalDocumentIdResolver, E as CanonicalDocumentIdResolutionError, F as RefusalNotRecordedError, M as AuthenticationRequiredError, N as ForbiddenError, O as AuthorizationPolicy, P as MalformedStoredOperationError, S as loadSubgraphs, T as callerSubject, _ as debounce, b as loadDocumentModels, c as piecesFromListModule, d as buildGraphQlDriveDocument, f as buildGraphqlOperation, g as runDetached, h as reportFailure, i as PIECE_SOURCE_LIST, j as AuthEvaluationUnsupportedError, k as AuthorizedDocumentHandle, l as extractDocumentModels, m as isSubgraphClass, o as pieceListLocation, p as buildGraphqlOperations, s as piecesFromCdnList, t as extractSubgraphs, u as buildGraphQlDocument, v as extractUpgradeManifests, w as BaseSubgraph, x as loadProcessors } from "./subgraph-extraction-CPtTeQAT.mjs";
4
+ import { A as AuthorizationPolicy, C as manifestDeclaredSubgraphs, D as createCredentialInvalidator, E as AuthService, F as ForbiddenError, I as MalformedStoredOperationError, L as RefusalNotRecordedError, M as createAuthorizationService, N as AuthEvaluationUnsupportedError, O as CanonicalDocumentIdResolutionError, P as AuthenticationRequiredError, S as loadSubgraphs, T as callerSubject, _ as debounce, b as loadDocumentModels, c as piecesFromListModule, d as buildGraphQlDriveDocument, f as buildGraphqlOperation, g as runDetached, h as reportFailure, i as PIECE_SOURCE_LIST, j as AuthorizedDocumentHandle, k as createCanonicalDocumentIdResolver, l as extractDocumentModels, m as isSubgraphClass, o as pieceListLocation, p as buildGraphqlOperations, s as piecesFromCdnList, t as extractSubgraphs, u as buildGraphQlDocument, v as extractUpgradeManifests, w as BaseSubgraph, x as loadProcessors } from "./subgraph-extraction-CcgWd0De.mjs";
5
5
  import { C as hasOperationSchemas, D as schema_default$1, E as typeDefinitionNames, S as getGeneratedDocumentModelTypes, T as reservedTypeNamesTaken, _ as generateDocumentModelSchema, a as collectSubgraphClaims, b as getDocumentModelSubgraphName, c as DocumentModelSchemaCache, d as buildDocumentModelSchema, f as buildSubgraphSchemaModule, g as findSubgraphTypeCollisions, h as documentModelSubgraphTypes, i as inspectionTypeDefs, l as SubgraphTypeCollisionError, m as createSchema, n as systemTypeDefs, o as describeOwnershipConflicts, p as createMergedSchema, r as schema_default$2, s as resolveClaimOwnership, t as baseDocumentModels, u as assembleSubgraphTypeDefs, v as generatedTypesOf, w as reservedTypeNames, x as getDocumentModelTypeDefs, y as getDocumentModelSchemaName } from "./base-document-models-69WRTSfH.mjs";
6
6
  import { n as filterBuildableSubgraphs, r as mergeSubgraphSchemas } from "./adapter-gateway-stitching-ClVkjojb.mjs";
7
7
  import { l as createDurableNodeFs, n as openCurrentPgliteForVerify, r as preparePgliteDataDir, u as resolvePgliteFsync } from "./pglite-node-Ow9i5Rb4.mjs";
@@ -12,6 +12,7 @@ import { gql } from "graphql-tag";
12
12
  import { GraphQLError, Kind, OperationTypeNode, parse, print, valueFromASTUntyped, visit } from "graphql";
13
13
  import { AuthEnforcementDisabledError, BareReadGate, BatchJobFailedError, ChannelError, ChannelErrorSource, DEFAULT_DRIVE_CONTAINER_TYPES, DriveCollectionId, DriveInspection, InvalidDeadLetterCursorError, JOB_NOT_FOUND_ERROR_NAME, JobStatus, ModelReadGate, PropagationMode as PropagationMode$1, READ_ONLY_ACCESS, SyncOperation, SyncScopeGate, consolidateSyncOperations, createReactorHostModuleBase, createReactorInspector, driveIdFromUrl, envelopesToSyncOperations, parseDriveUrl, readDecisionModel, supportsPurgeRefusals, syncOperationErrorType, toWireDeadLetter, toWireQueueState } from "@powerhousedao/reactor";
14
14
  import { deserializeSignature, readPeerManifest, serializeSignature, setName, withSignaturePolicy } from "@powerhousedao/shared/document-model";
15
+ import { fetchDelegationCredential, resolveSwitchboardEndpoint } from "@renown/sdk";
15
16
  import { ConsoleLogger, childLogger } from "document-model";
16
17
  import { AsyncLocalStorage } from "node:async_hooks";
17
18
  import path, { isAbsolute, join } from "node:path";
@@ -43,7 +44,6 @@ import { WebSocketServer } from "ws";
43
44
  import { createRelationalDb } from "@powerhousedao/shared/processors";
44
45
  import { isAttachmentHash, readGateAllowsAttachmentRead, scopeGateAllowsAttachmentRead } from "@powerhousedao/reactor-attachments/replication";
45
46
  import { Kysely, Migrator, sql } from "kysely";
46
- import { fetchDelegationCredential, resolveSwitchboardEndpoint, verifyAuthBearerToken } from "@renown/sdk";
47
47
  import { PGlite } from "@electric-sql/pglite";
48
48
  import { NodeFS } from "@electric-sql/pglite/nodefs";
49
49
  import knex from "knex";
@@ -384,8 +384,14 @@ async function createHttpAdapter(type) {
384
384
  const WS_CLOSE_REASON_AUTHENTICATION_REQUIRED = "authentication-required";
385
385
  /** A bearer was sent and could not be verified. */
386
386
  const WS_CLOSE_REASON_BEARER_REJECTED = "bearer-rejected";
387
+ /** An admitted connection's credential was revoked or no longer verifies. */
388
+ const WS_CLOSE_REASON_CREDENTIAL_REVOKED = "credential-revoked";
387
389
  /** Every reason a refusal closes with, for a client matching on the set. */
388
- const WS_AUTH_CLOSE_REASONS = [WS_CLOSE_REASON_AUTHENTICATION_REQUIRED, WS_CLOSE_REASON_BEARER_REJECTED];
390
+ const WS_AUTH_CLOSE_REASONS = [
391
+ WS_CLOSE_REASON_AUTHENTICATION_REQUIRED,
392
+ WS_CLOSE_REASON_BEARER_REJECTED,
393
+ WS_CLOSE_REASON_CREDENTIAL_REVOKED
394
+ ];
389
395
  //#endregion
390
396
  //#region src/http/namespace.ts
391
397
  /**
@@ -4318,6 +4324,105 @@ var DriveOwnershipCache = class {
4318
4324
  }
4319
4325
  };
4320
4326
  //#endregion
4327
+ //#region src/graphql/ws-credential-monitor.ts
4328
+ /** Default interval between credential re-checks of open WebSockets. */
4329
+ const DEFAULT_WS_CREDENTIAL_RECHECK_INTERVAL_MS = 6e4;
4330
+ /**
4331
+ * Re-verifies the credentials of authenticated WebSocket connections.
4332
+ *
4333
+ * A WebSocket is authenticated once, at `ConnectionInit`, so a credential
4334
+ * revoked afterwards would otherwise keep every subscription it opened alive
4335
+ * for as long as the socket stays up. The monitor re-checks each tracked
4336
+ * connection on an interval and, at once, the connections of an identity whose
4337
+ * credential a package invalidated; a connection whose credential no longer
4338
+ * verifies is closed 4403 with {@link WS_CLOSE_REASON_CREDENTIAL_REVOKED}.
4339
+ *
4340
+ * A check that throws (a verifier outage) leaves the connection open: admission
4341
+ * fails closed on the next connect, but an outage should not drop every live
4342
+ * subscription at once.
4343
+ */
4344
+ var WsCredentialMonitor = class {
4345
+ #connections = /* @__PURE__ */ new Map();
4346
+ #options;
4347
+ #timer;
4348
+ #unsubscribe;
4349
+ #sweeping = false;
4350
+ constructor(options) {
4351
+ this.#options = options;
4352
+ }
4353
+ get size() {
4354
+ return this.#connections.size;
4355
+ }
4356
+ /** Begin the periodic sweep and listen for invalidations. Idempotent. */
4357
+ start() {
4358
+ this.#unsubscribe ??= this.#options.authService.onCredentialInvalidated((invalidation) => {
4359
+ this.recheck(invalidation);
4360
+ });
4361
+ if (this.#options.intervalMs > 0 && !this.#timer) {
4362
+ this.#timer = setInterval(() => {
4363
+ if (this.#sweeping) return;
4364
+ this.#sweeping = true;
4365
+ this.recheck().finally(() => {
4366
+ this.#sweeping = false;
4367
+ });
4368
+ }, this.#options.intervalMs);
4369
+ this.#timer.unref?.();
4370
+ }
4371
+ }
4372
+ dispose() {
4373
+ if (this.#timer) clearInterval(this.#timer);
4374
+ this.#timer = void 0;
4375
+ this.#unsubscribe?.();
4376
+ this.#unsubscribe = void 0;
4377
+ this.#connections.clear();
4378
+ }
4379
+ /** Track an admitted, authenticated connection until its socket closes. */
4380
+ track(connection, user) {
4381
+ const { socket } = connection;
4382
+ this.#connections.set(connection, {
4383
+ user,
4384
+ socket
4385
+ });
4386
+ socket?.once?.("close", () => {
4387
+ this.#connections.delete(connection);
4388
+ });
4389
+ }
4390
+ /**
4391
+ * Re-verify tracked connections (those matching `filter`, or all) and close
4392
+ * the ones whose credential no longer holds. Resolves to the number closed.
4393
+ */
4394
+ async recheck(filter) {
4395
+ const targets = [...this.#connections].filter(([, tracked]) => !filter || matches(tracked.user, filter));
4396
+ let closed = 0;
4397
+ await Promise.all(targets.map(async ([connection, tracked]) => {
4398
+ let valid;
4399
+ try {
4400
+ valid = await this.#options.authService.isCredentialValid(tracked.user);
4401
+ } catch (error) {
4402
+ this.#options.logger.warn("Could not re-verify the credential of a WebSocket connection; keeping it open: @error", error instanceof Error ? error.message : error);
4403
+ return;
4404
+ }
4405
+ if (valid || !this.#connections.has(connection)) return;
4406
+ this.#connections.delete(connection);
4407
+ this.#options.logger.info("Closing WebSocket connection of @address: credential no longer valid", tracked.user.address);
4408
+ tracked.socket?.close?.(4403, WS_CLOSE_REASON_CREDENTIAL_REVOKED);
4409
+ closed++;
4410
+ }));
4411
+ return closed;
4412
+ }
4413
+ };
4414
+ function matches(user, filter) {
4415
+ return user.address.toLowerCase() === filter.address && (filter.chainId === void 0 || user.chainId === filter.chainId) && (filter.appDid === void 0 || user.appKey === filter.appDid);
4416
+ }
4417
+ /** Parse `WS_CREDENTIAL_RECHECK_INTERVAL_MS`; invalid values warn and fall back to the default. */
4418
+ function resolveWsCredentialRecheckIntervalMs(raw, logger) {
4419
+ if (raw === void 0) return DEFAULT_WS_CREDENTIAL_RECHECK_INTERVAL_MS;
4420
+ const parsed = Number(raw);
4421
+ if (raw.trim() !== "" && Number.isFinite(parsed) && parsed >= 0) return parsed;
4422
+ logger.warn(`Ignoring invalid WS_CREDENTIAL_RECHECK_INTERVAL_MS="${raw}" (expected a non-negative number of milliseconds; 0 disables the periodic re-check) — using ${DEFAULT_WS_CREDENTIAL_RECHECK_INTERVAL_MS}`);
4423
+ return DEFAULT_WS_CREDENTIAL_RECHECK_INTERVAL_MS;
4424
+ }
4425
+ //#endregion
4321
4426
  //#region src/graphql/sse.ts
4322
4427
  /**
4323
4428
  * Create a Fetch-API-compatible SSE handler for GraphQL subscriptions
@@ -4485,6 +4590,7 @@ function createWsAuthHandlers(opts) {
4485
4590
  return refuseConnection(connection, WS_CLOSE_REASON_AUTHENTICATION_REQUIRED);
4486
4591
  }
4487
4592
  resolved.set(connection, user ?? void 0);
4593
+ if (user) opts.credentialMonitor?.track(connection, user);
4488
4594
  return true;
4489
4595
  },
4490
4596
  context: (connectionParams, connection) => Promise.resolve(opts.buildContext(connectionParams, resolved.get(connection)))
@@ -4571,6 +4677,7 @@ var GraphQLManager = class {
4571
4677
  httpAdapter;
4572
4678
  gatewayAdapter;
4573
4679
  authService;
4680
+ #credentialMonitor;
4574
4681
  documentPermissionService;
4575
4682
  featureFlags;
4576
4683
  port;
@@ -4591,6 +4698,14 @@ var GraphQLManager = class {
4591
4698
  this.httpAdapter = options.httpAdapter;
4592
4699
  this.gatewayAdapter = options.gatewayAdapter;
4593
4700
  this.authService = options.authService;
4701
+ if (options.authService) {
4702
+ this.#credentialMonitor = new WsCredentialMonitor({
4703
+ authService: options.authService,
4704
+ intervalMs: options.wsCredentialRecheckIntervalMs ?? 6e4,
4705
+ logger: options.logger
4706
+ });
4707
+ this.#credentialMonitor.start();
4708
+ }
4594
4709
  this.documentPermissionService = options.documentPermissionService;
4595
4710
  this.featureFlags = options.featureFlags ?? DefaultFeatureFlags;
4596
4711
  const subgraph = !!this.featureFlags.enableDocumentModelSubgraphs;
@@ -5121,7 +5236,8 @@ var GraphQLManager = class {
5121
5236
  authorizationService: this.authorizationService,
5122
5237
  syncServingGate: this.syncServingGate,
5123
5238
  attachments: this.attachments,
5124
- inspection: this.inspection
5239
+ inspection: this.inspection,
5240
+ credentials: createCredentialInvalidator(this.authService)
5125
5241
  });
5126
5242
  }
5127
5243
  /**
@@ -5300,6 +5416,7 @@ var GraphQLManager = class {
5300
5416
  #makeWsContextFactory() {
5301
5417
  return createWsAuthHandlers({
5302
5418
  authService: this.authService,
5419
+ credentialMonitor: this.#credentialMonitor,
5303
5420
  requireAuthenticatedCaller: () => this.#requireAuthMiddleware !== void 0,
5304
5421
  logger: this.logger,
5305
5422
  buildContext: (connectionParams, user) => ({
@@ -5327,6 +5444,7 @@ var GraphQLManager = class {
5327
5444
  }
5328
5445
  async shutdown() {
5329
5446
  this.logger.info("Shutting down GraphQL Manager");
5447
+ this.#credentialMonitor?.dispose();
5330
5448
  for (const disposer of this.subgraphWsDisposers.values()) await disposer.dispose();
5331
5449
  this.subgraphWsDisposers.clear();
5332
5450
  await this.gatewayAdapter.stop();
@@ -7323,10 +7441,10 @@ const ADMIN_USERS = getAdminUsers();
7323
7441
  //#endregion
7324
7442
  //#region src/graphql/system/version.ts
7325
7443
  function getVersion() {
7326
- return "6.2.3-dev.57";
7444
+ return "6.2.3-dev.59";
7327
7445
  }
7328
7446
  function getGitHash() {
7329
- return "a516b51ba40d84f56a55df04d1eecef5afba4972";
7447
+ return "ce4ccc24b1efe5d61859e5fbdcb1e73f457769ba";
7330
7448
  }
7331
7449
  function getGitUrl() {
7332
7450
  return buildTreeUrl(getGitHash());
@@ -9203,165 +9321,6 @@ function setupEventListeners(pkgManager, graphqlManager, reactorProcessorManager
9203
9321
  });
9204
9322
  }
9205
9323
  //#endregion
9206
- //#region src/services/auth.service.ts
9207
- const DEFAULT_CREDENTIAL_CACHE_TTL_MS = 6e4;
9208
- const CREDENTIAL_CACHE_MAX_ENTRIES = 1e3;
9209
- var AuthService = class {
9210
- config;
9211
- credentialCache = /* @__PURE__ */ new Map();
9212
- constructor(config) {
9213
- this.config = config;
9214
- }
9215
- /**
9216
- * Whether this service reads the bearer at all. Defaults to `enabled`, so a
9217
- * config written before `resolveIdentity` existed behaves exactly as it did.
9218
- */
9219
- get resolvesIdentity() {
9220
- return this.config.resolveIdentity ?? this.config.enabled;
9221
- }
9222
- /** The context an unresolved request gets: no user, and no admin list to match against. */
9223
- anonymousContext() {
9224
- return {
9225
- user: void 0,
9226
- admins: [],
9227
- auth_enabled: this.config.enabled
9228
- };
9229
- }
9230
- async authenticateRequest(request) {
9231
- if (!this.resolvesIdentity) return this.anonymousContext();
9232
- if (request.method === "OPTIONS") return {
9233
- user: void 0,
9234
- admins: this.config.admins,
9235
- auth_enabled: this.config.enabled
9236
- };
9237
- return this.verifyBearer(request.headers.get("authorization") ?? void 0);
9238
- }
9239
- /**
9240
- * Verify a Bearer token regardless of HTTP method. Use this from non-GraphQL
9241
- * middleware that must enforce authentication on every request.
9242
- */
9243
- async verifyBearer(authorization) {
9244
- if (!this.resolvesIdentity) return this.anonymousContext();
9245
- const token = authorization?.split(" ")[1];
9246
- if (!token) return {
9247
- user: void 0,
9248
- admins: this.config.admins,
9249
- auth_enabled: this.config.enabled
9250
- };
9251
- try {
9252
- const verified = await this.verifyToken(token);
9253
- if (!verified) return new Response(JSON.stringify({ error: "Verification failed" }), { status: 401 });
9254
- const user = this.extractUserFromVerification(verified);
9255
- if (!user) return new Response(JSON.stringify({ error: "Missing credentials" }), { status: 401 });
9256
- if (!this.config.skipCredentialVerification) {
9257
- if (!await this.verifyCredentialExists(user.address, user.chainId, verified.issuer)) return new Response(JSON.stringify({ error: "Credentials no longer valid" }), { status: 401 });
9258
- }
9259
- return {
9260
- user,
9261
- admins: this.config.admins,
9262
- auth_enabled: this.config.enabled
9263
- };
9264
- } catch {
9265
- return new Response(JSON.stringify({ error: "Authentication failed" }), { status: 401 });
9266
- }
9267
- }
9268
- /** Throws only for a bearer that is present and unusable, as HTTP 401s it. */
9269
- async authenticateWebSocketConnection(connectionParams) {
9270
- if (!this.resolvesIdentity) return null;
9271
- const authHeader = connectionParams.authorization;
9272
- if (!authHeader) return null;
9273
- const token = authHeader.split(" ")[1];
9274
- if (!token) throw new Error("Invalid authorization format");
9275
- const verified = await this.verifyToken(token);
9276
- if (!verified) throw new Error("Token verification failed");
9277
- const user = this.extractUserFromVerification(verified);
9278
- if (!user) throw new Error("Invalid credentials");
9279
- if (!this.config.skipCredentialVerification) {
9280
- if (!await this.verifyCredentialExists(user.address, user.chainId, verified.issuer)) throw new Error("Credentials no longer valid");
9281
- }
9282
- return user;
9283
- }
9284
- /**
9285
- * Verify the auth bearer token
9286
- */
9287
- async verifyToken(token) {
9288
- return await verifyAuthBearerToken(token);
9289
- }
9290
- /**
9291
- * Extract user information from verification result.
9292
- *
9293
- * The issuer is required along with the credential subject. A credential that
9294
- * verified must carry one -- resolving it is how the signature was checked --
9295
- * so this rejects a shape that cannot have come from verification rather than
9296
- * admitting a keyless principal.
9297
- */
9298
- extractUserFromVerification(verified) {
9299
- try {
9300
- const { address, chainId, networkId } = verified.verifiableCredential.credentialSubject;
9301
- const appKey = verified.issuer;
9302
- if (!address || !chainId || !networkId || !appKey) return null;
9303
- return {
9304
- address,
9305
- chainId,
9306
- networkId,
9307
- appKey
9308
- };
9309
- } catch {
9310
- return null;
9311
- }
9312
- }
9313
- /**
9314
- * Verify that the credential still exists on the Renown API.
9315
- *
9316
- * Results are cached per (address, chainId, issuer) for a short TTL so the
9317
- * blocking external round-trip is not paid on every request. Concurrent
9318
- * checks for the same key share a single in-flight request, and entries
9319
- * that resolve to false are evicted immediately so failed or revoked
9320
- * credentials are re-checked on the next request.
9321
- */
9322
- verifyCredentialExists(address, chainId, appId) {
9323
- const ttlMs = this.config.credentialVerificationCacheTtlMs ?? DEFAULT_CREDENTIAL_CACHE_TTL_MS;
9324
- if (ttlMs <= 0) return this.fetchCredentialExists(address, chainId, appId);
9325
- const key = `${address.toLowerCase()}:${chainId}:${appId}`;
9326
- const now = Date.now();
9327
- const cached = this.credentialCache.get(key);
9328
- if (cached && cached.expiresAt > now) return cached.exists;
9329
- this.pruneCredentialCache(now);
9330
- const entry = {
9331
- exists: this.fetchCredentialExists(address, chainId, appId).then((exists) => {
9332
- if (!exists && this.credentialCache.get(key) === entry) this.credentialCache.delete(key);
9333
- return exists;
9334
- }),
9335
- expiresAt: now + ttlMs
9336
- };
9337
- this.credentialCache.set(key, entry);
9338
- return entry.exists;
9339
- }
9340
- /**
9341
- * Enforce the cache size cap before inserting a new entry: drop expired
9342
- * entries first, then evict oldest-inserted entries (insertion order
9343
- * matches expiry order since the TTL is constant) until under the cap, so
9344
- * a flood of distinct keys cannot grow the map without bound.
9345
- */
9346
- pruneCredentialCache(now) {
9347
- if (this.credentialCache.size < CREDENTIAL_CACHE_MAX_ENTRIES) return;
9348
- for (const [key, entry] of this.credentialCache) if (entry.expiresAt <= now) this.credentialCache.delete(key);
9349
- while (this.credentialCache.size >= CREDENTIAL_CACHE_MAX_ENTRIES) {
9350
- const oldestKey = this.credentialCache.keys().next().value;
9351
- if (oldestKey === void 0) break;
9352
- this.credentialCache.delete(oldestKey);
9353
- }
9354
- }
9355
- async fetchCredentialExists(address, chainId, appId) {
9356
- if (!this.config.verifyCredential) throw new Error("AuthService: credential verification is enabled but no verifyCredential was provided");
9357
- return this.config.verifyCredential({
9358
- address,
9359
- chainId,
9360
- appId
9361
- });
9362
- }
9363
- };
9364
- //#endregion
9365
9324
  //#region src/services/renown-credential-verifier.ts
9366
9325
  async function createRenownCredentialVerifier(config = {}) {
9367
9326
  const switchboardUrl = await resolveSwitchboardEndpoint({
@@ -9785,6 +9744,23 @@ function resolveRenownSource(value, logger) {
9785
9744
  logger.warn(`Ignoring invalid renown source "${value}" (expected "self" or "remote") — using "remote"`);
9786
9745
  return "remote";
9787
9746
  }
9747
+ /**
9748
+ * The credential-verification cache TTL for `AuthService`.
9749
+ *
9750
+ * `CREDENTIAL_VERIFICATION_CACHE_TTL_MS` wins when it is a non-negative number.
9751
+ * Otherwise the default depends on the source: with `"self"` the check is an
9752
+ * in-process read-model query, so caching buys little and only delays a
9753
+ * revocation — it defaults to `0` (no cache). A `"remote"` source returns
9754
+ * `undefined`, leaving AuthService's own default TTL in place.
9755
+ */
9756
+ function resolveCredentialCacheTtlMs(raw, source, logger) {
9757
+ const fallback = source === "self" ? 0 : void 0;
9758
+ if (raw === void 0) return fallback;
9759
+ const parsed = Number(raw);
9760
+ if (raw.trim() !== "" && Number.isFinite(parsed) && parsed >= 0) return parsed;
9761
+ logger.warn(`Ignoring invalid CREDENTIAL_VERIFICATION_CACHE_TTL_MS="${raw}" (expected a non-negative number of milliseconds; 0 disables caching) — using the ${source === "self" ? "renown source=self default (0, no cache)" : "default TTL"}`);
9762
+ return fallback;
9763
+ }
9788
9764
  //#endregion
9789
9765
  //#region src/utils/db.ts
9790
9766
  const logger = childLogger(["reactor-api", "db"]);
@@ -10054,6 +10030,7 @@ function resolveGatewayAdapterType(logger) {
10054
10030
  */
10055
10031
  async function setupGraphQLManager({ httpAdapter, authFetchMiddleware, requireAuthFetchMiddleware, httpServer, wsServer, client, relationalDb, analyticsStore, syncManager, subgraphs, logger, authorizationService, authService, documentPermissionService, enableDocumentModelSubgraphs, port, reactorDriveClient, syncServingGate, httpRoutes, attachments, inspection, driveStore, reportError }) {
10056
10032
  const graphqlManager = new GraphQLManager({
10033
+ wsCredentialRecheckIntervalMs: resolveWsCredentialRecheckIntervalMs(process.env.WS_CREDENTIAL_RECHECK_INTERVAL_MS, logger),
10057
10034
  path: config.basePath,
10058
10035
  httpServer,
10059
10036
  wsServer,
@@ -10189,12 +10166,6 @@ async function _setupCommonInfrastructure(options) {
10189
10166
  if (DEFAULT_PROTECTION !== void 0) defaultProtection = DEFAULT_PROTECTION.toLowerCase() === "true";
10190
10167
  let skipCredentialVerification = false;
10191
10168
  if (SKIP_CREDENTIAL_VERIFICATION !== void 0) skipCredentialVerification = SKIP_CREDENTIAL_VERIFICATION === "true";
10192
- let credentialVerificationCacheTtlMs;
10193
- if (CREDENTIAL_VERIFICATION_CACHE_TTL_MS !== void 0) {
10194
- const parsed = Number(CREDENTIAL_VERIFICATION_CACHE_TTL_MS);
10195
- if (CREDENTIAL_VERIFICATION_CACHE_TTL_MS.trim() !== "" && Number.isFinite(parsed) && parsed >= 0) credentialVerificationCacheTtlMs = parsed;
10196
- else logger.warn(`Ignoring invalid CREDENTIAL_VERIFICATION_CACHE_TTL_MS="${CREDENTIAL_VERIFICATION_CACHE_TTL_MS}" (expected a non-negative number of milliseconds; 0 disables caching) — using the default TTL`);
10197
- }
10198
10169
  const documentPermissionsRequested = options.documentPermissionService !== void 0 || DOCUMENT_PERMISSIONS_ENABLED === "true";
10199
10170
  assertAuthRequiredForDocumentPermissions(authEnabled, documentPermissionsRequested);
10200
10171
  assertSkipCredentialVerificationAllowed(resolveCallerIdentity, skipCredentialVerification, process.env);
@@ -10226,7 +10197,7 @@ async function _setupCommonInfrastructure(options) {
10226
10197
  resolveIdentity: resolveCallerIdentity,
10227
10198
  admins,
10228
10199
  skipCredentialVerification,
10229
- credentialVerificationCacheTtlMs,
10200
+ credentialVerificationCacheTtlMs: resolveCredentialCacheTtlMs(CREDENTIAL_VERIFICATION_CACHE_TTL_MS, renown.source, logger),
10230
10201
  verifyCredential: options.verifyCredential ?? await createRenownCredentialVerifier({
10231
10202
  renownUrl: renown.url,
10232
10203
  switchboardUrl: renown.switchboardUrl
@@ -10679,7 +10650,7 @@ var PackageManagementService = class {
10679
10650
  }
10680
10651
  };
10681
10652
  //#endregion
10682
- export { ADMIN_USERS, ActionCandidateInputSchema, ActionContextInputSchema, ActionInputSchema, AddRelationshipDocument, AnalyticsSubgraph, AttachmentAccessFailed, AttachmentAccessService, AttachmentAccessUnavailable, AttachmentClientProvider, AuthDecision, AuthDecisionSchema, AuthEvaluationUnsupportedError, AuthService, AuthSubgraph, AuthenticationRequiredError, AuthorizationPolicy, AuthorizedAttachmentService, AuthorizedDocumentHandle, BaseSubgraph, CORE_PACKAGE_NAME, CanonicalDocumentIdResolutionError, ChannelMetaInputSchema, CreateDocumentDocument, CreateEmptyDocumentDocument, DEFAULT_INSPECTION_THROTTLE, DeleteDocumentDocument, DeleteDocumentsDocument, DocumentChangeType, DocumentChangeTypeSchema, DocumentChangesDocument, DocumentModelSchemaCache, DocumentOperationsFilterInputSchema, DocumentPermissionService, DocumentRelationshipFieldsFragmentDoc, EvaluateActionsDocument, ExecuteBatchDocument, ExecutionJobInputSchema, FindDocumentsDocument, ForbiddenError, GetCreateDefaultsDocument, GetDocumentDocument, GetDocumentIncomingRelationshipEdgesDocument, GetDocumentIncomingRelationshipsDocument, GetDocumentModelsDocument, GetDocumentOperationsDocument, GetDocumentOutgoingRelationshipEdgesDocument, GetDocumentOutgoingRelationshipsDocument, GetDocumentServedDocument, GetDocumentWithOperationsDocument, GetJobStatusDocument, GraphQLManager, HttpDocumentModelLoader, HttpPackageLoader, HttpRouteService, ImportPackageLoader, InMemoryPackageStorage, InspectionSubgraph, InspectionThrottle, InspectionThrottledError, InvalidNamespaceError, JobChangesDocument, JobInfoFieldsFragmentDoc, MalformedStoredOperationError, MemoryWebhookStore, MoveRelationshipDocument, MutateDocumentAsyncDocument, MutateDocumentDocument, OperationContextInputSchema, OperationInputSchema, OperationWithContextInputSchema, OperationsFilterInputSchema, PACKAGE_ROUTE_SEGMENT, PGLITE_UTC_PARSERS, PackageManagementService, PackageManager, PackagesSubgraph, PagingInputSchema, PhDocumentFieldsFragmentDoc, PollSyncEnvelopesDocument, PrivacyPermissionAdapter, PropagationMode, PropagationModeSchema, PushSyncEnvelopesDocument, ReactorSignerAppInputSchema, ReactorSignerInputSchema, ReactorSignerUserInputSchema, ReactorSubgraph, RefusalNotRecordedError, RelationalWebhookStore, RemoteCursorInputSchema, RemoteFilterInputSchema, RemoveRelationshipDocument, RenameDocumentDocument, SearchFilterInputSchema, SetPreferredEditorDocument, SubgraphTypeCollisionError, SyncEnvelopeInputSchema, SyncEnvelopeType, SyncEnvelopeTypeSchema, SyncRefusalInputSchema, SystemSubgraph, TouchChannelDocument, TouchChannelInputSchema, UpdateRelationshipDocument, ViewFilterInputSchema, WEBHOOK_SEGMENT, WS_AUTH_CLOSE_REASONS, WS_CLOSE_REASON_AUTHENTICATION_REQUIRED, WS_CLOSE_REASON_BEARER_REJECTED, WebhookService, assembleSubgraphTypeDefs, assertAttachmentPolicyReadsAllowed, assertAuthRequiredForDocumentPermissions, assertCredentialVerifierForSource, assertHostMountPath, assertRequireAuthenticatedCallerAllowed, assertSkipCredentialVerificationAllowed, baseDocumentModels, buildDocumentModelSchema, buildGraphQlDocument, buildGraphQlDriveDocument, buildGraphqlOperation, buildGraphqlOperations, buildSubgraphSchemaModule, callerSubject, createAuthFetchMiddleware, createCanonicalDocumentIdResolver, createGatewayAdapter, createHttpAdapter, createInspectionResolvers, createMergedSchema, createReactorGraphQLClient, createReactorInspectionSource, createRenownCredentialVerifier, createSchema, createWsAuthHandlers, decodeExplorerUrlState, definedNonNullAnySchema, documentModelSubgraphTypes, driveIdFromUrl, extractSubgraphs, extractSubgraphsFromModule, findSubgraphTypeCollisions, generateDocumentModelSchema, generatedTypesOf, getAuthContext, getDbClient, getDocumentModelSchemaName, getDocumentModelSubgraphName, getDocumentModelTypeDefs, getExplorerPrefix, getGeneratedDocumentModelTypes, getGitHash, getGitUrl, getSdk, getUniqueDocumentModels, getUniqueUpgradeManifests, getVersion, hasOperationSchemas, initAnalyticsStoreSql, initializeAndStartAPI, inspectionTypeDefs, isDefinedNonNullAny, isExpectedLoaderMiss, isListedAdmin, isPostgresConnectionString, isSubgraphClass, namespacePath, namespaceSegments, newWebhookToken, parseDriveUrl, parseWebhookBody, piecesBaseUrl, redactHeaders, renderGraphqlPlayground, reportFailure, reservedTypeNames, reservedTypeNamesTaken, resolvePackageName, resolveRenownConfig, runDetached, typeDefinitionNames, verifyWebhook };
10653
+ export { ADMIN_USERS, ActionCandidateInputSchema, ActionContextInputSchema, ActionInputSchema, AddRelationshipDocument, AnalyticsSubgraph, AttachmentAccessFailed, AttachmentAccessService, AttachmentAccessUnavailable, AttachmentClientProvider, AuthDecision, AuthDecisionSchema, AuthEvaluationUnsupportedError, AuthService, AuthSubgraph, AuthenticationRequiredError, AuthorizationPolicy, AuthorizedAttachmentService, AuthorizedDocumentHandle, BaseSubgraph, CORE_PACKAGE_NAME, CanonicalDocumentIdResolutionError, ChannelMetaInputSchema, CreateDocumentDocument, CreateEmptyDocumentDocument, DEFAULT_INSPECTION_THROTTLE, DeleteDocumentDocument, DeleteDocumentsDocument, DocumentChangeType, DocumentChangeTypeSchema, DocumentChangesDocument, DocumentModelSchemaCache, DocumentOperationsFilterInputSchema, DocumentPermissionService, DocumentRelationshipFieldsFragmentDoc, EvaluateActionsDocument, ExecuteBatchDocument, ExecutionJobInputSchema, FindDocumentsDocument, ForbiddenError, GetCreateDefaultsDocument, GetDocumentDocument, GetDocumentIncomingRelationshipEdgesDocument, GetDocumentIncomingRelationshipsDocument, GetDocumentModelsDocument, GetDocumentOperationsDocument, GetDocumentOutgoingRelationshipEdgesDocument, GetDocumentOutgoingRelationshipsDocument, GetDocumentServedDocument, GetDocumentWithOperationsDocument, GetJobStatusDocument, GraphQLManager, HttpDocumentModelLoader, HttpPackageLoader, HttpRouteService, ImportPackageLoader, InMemoryPackageStorage, InspectionSubgraph, InspectionThrottle, InspectionThrottledError, InvalidNamespaceError, JobChangesDocument, JobInfoFieldsFragmentDoc, MalformedStoredOperationError, MemoryWebhookStore, MoveRelationshipDocument, MutateDocumentAsyncDocument, MutateDocumentDocument, OperationContextInputSchema, OperationInputSchema, OperationWithContextInputSchema, OperationsFilterInputSchema, PACKAGE_ROUTE_SEGMENT, PGLITE_UTC_PARSERS, PackageManagementService, PackageManager, PackagesSubgraph, PagingInputSchema, PhDocumentFieldsFragmentDoc, PollSyncEnvelopesDocument, PrivacyPermissionAdapter, PropagationMode, PropagationModeSchema, PushSyncEnvelopesDocument, ReactorSignerAppInputSchema, ReactorSignerInputSchema, ReactorSignerUserInputSchema, ReactorSubgraph, RefusalNotRecordedError, RelationalWebhookStore, RemoteCursorInputSchema, RemoteFilterInputSchema, RemoveRelationshipDocument, RenameDocumentDocument, SearchFilterInputSchema, SetPreferredEditorDocument, SubgraphTypeCollisionError, SyncEnvelopeInputSchema, SyncEnvelopeType, SyncEnvelopeTypeSchema, SyncRefusalInputSchema, SystemSubgraph, TouchChannelDocument, TouchChannelInputSchema, UpdateRelationshipDocument, ViewFilterInputSchema, WEBHOOK_SEGMENT, WS_AUTH_CLOSE_REASONS, WS_CLOSE_REASON_AUTHENTICATION_REQUIRED, WS_CLOSE_REASON_BEARER_REJECTED, WS_CLOSE_REASON_CREDENTIAL_REVOKED, WebhookService, assembleSubgraphTypeDefs, assertAttachmentPolicyReadsAllowed, assertAuthRequiredForDocumentPermissions, assertCredentialVerifierForSource, assertHostMountPath, assertRequireAuthenticatedCallerAllowed, assertSkipCredentialVerificationAllowed, baseDocumentModels, buildDocumentModelSchema, buildGraphQlDocument, buildGraphQlDriveDocument, buildGraphqlOperation, buildGraphqlOperations, buildSubgraphSchemaModule, callerSubject, createAuthFetchMiddleware, createCanonicalDocumentIdResolver, createCredentialInvalidator, createGatewayAdapter, createHttpAdapter, createInspectionResolvers, createMergedSchema, createReactorGraphQLClient, createReactorInspectionSource, createRenownCredentialVerifier, createSchema, createWsAuthHandlers, decodeExplorerUrlState, definedNonNullAnySchema, documentModelSubgraphTypes, driveIdFromUrl, extractSubgraphs, extractSubgraphsFromModule, findSubgraphTypeCollisions, generateDocumentModelSchema, generatedTypesOf, getAuthContext, getDbClient, getDocumentModelSchemaName, getDocumentModelSubgraphName, getDocumentModelTypeDefs, getExplorerPrefix, getGeneratedDocumentModelTypes, getGitHash, getGitUrl, getSdk, getUniqueDocumentModels, getUniqueUpgradeManifests, getVersion, hasOperationSchemas, initAnalyticsStoreSql, initializeAndStartAPI, inspectionTypeDefs, isDefinedNonNullAny, isExpectedLoaderMiss, isListedAdmin, isPostgresConnectionString, isSubgraphClass, namespacePath, namespaceSegments, newWebhookToken, parseDriveUrl, parseWebhookBody, piecesBaseUrl, redactHeaders, renderGraphqlPlayground, reportFailure, reservedTypeNames, reservedTypeNamesTaken, resolveCredentialCacheTtlMs, resolvePackageName, resolveRenownConfig, runDetached, typeDefinitionNames, verifyWebhook };
10683
10654
 
10684
10655
  //# sourceMappingURL=index.mjs.map
10685
- //# debugId=5a6cd51c-1122-5d95-9bcf-8cf26e403d05
10656
+ //# debugId=061cb7f9-bbbc-55da-a218-225c0b3c993d