@powerhousedao/reactor-workflow 6.2.3-dev.94 → 6.2.3-dev.96

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.js CHANGED
@@ -1,4 +1,4 @@
1
- import { $ as PieceWorkerPool, A as builtinPiece, At as isIndeterminateError, B as shapeConnection, C as flowsHandlers, Ct as unsupportedAuth, D as blockLabel, Dt as npmRegistryBaseUrl, E as storeHandlers, F as AttachmentCache, G as SecretCreatorMismatchError, H as expressionsIn, I as BoundConnectionResolver, J as SecretOwnerMismatchError, K as SecretDeletedError, M as CORE_PIECE_NAME, N as CORE_PIECE_VERSION, O as unpinnedNote, Ot as pieceRegistrySource, P as loopItems, Q as triggerBlock, R as declaredConnectionIds, S as CompositeBlockExecutor, St as authMethodFor, T as resolvedBlock, U as unavailableValue, V as resolveStepInput, X as secretRefFromId, Y as parseSecretRef, Z as stepBlock, _ as stepConfigHash, _t as bundleResolver, a as PieceRegistry, at as redact, b as effectiveRetryPolicy, c as packagePieces, ct as secretsFor, d as runWorkflow, dt as parseAddress, et as PieceWorker, f as isLoopStep, ft as extractDedupeKey, g as hashOf, gt as HOST_ORIGIN, h as canonicalJson, ht as FLOWS_LIST, i as tracedSteps, it as containsRedactedMarker, j as describeBuiltinPiece, k as blockPorts, kt as setPieceRegistryUrl, lt as DEFAULT_EGRESS_POLICY, m as loopStructure, mt as maxFileBytes, n as WorkflowTelemetry, nt as PieceWorkerError, o as installedPiece, ot as redactMessage, p as loopConfigHash, pt as FileTooLargeError, q as SecretNotFoundError, r as tracedMethods, rt as PieceWorkerTimeoutError, s as installedPieces, st as rememberSecrets, t as TELEMETRY_SCOPE, tt as PieceWorkerDisposedError, u as errorNameOf, ut as isPrivateAddress, v as DynamicPropertiesError, vt as pieceModuleRef, w as isHostBound, wt as unsupportedTrigger, x as ActivepiecesBlockExecutor, xt as UnsupportedPieceFeatureError, y as checkDynamicProperties, yt as sourcedResolver, z as declaredReactorConnectionIds } from "./telemetry-BJdHIsCa.js";
1
+ import { $ as PieceWorkerPool, A as builtinPiece, At as isIndeterminateError, B as shapeConnection, C as flowsHandlers, Ct as unsupportedAuth, D as blockLabel, Dt as npmRegistryBaseUrl, E as storeHandlers, F as AttachmentCache, G as SecretCreatorMismatchError, H as expressionsIn, I as BoundConnectionResolver, J as SecretOwnerMismatchError, K as SecretDeletedError, M as CORE_PIECE_NAME, N as CORE_PIECE_VERSION, O as unpinnedNote, Ot as pieceRegistrySource, P as loopItems, Q as triggerBlock, R as declaredConnectionIds, S as CompositeBlockExecutor, St as authMethodFor, T as resolvedBlock, U as unavailableValue, V as resolveStepInput, X as secretRefFromId, Y as parseSecretRef, Z as stepBlock, _ as stepConfigHash, _t as bundleResolver, a as PieceRegistry, at as redact, b as effectiveRetryPolicy, c as packagePieces, ct as secretsFor, d as runWorkflow, dt as parseAddress, et as PieceWorker, f as isLoopStep, ft as extractDedupeKey, g as hashOf, gt as HOST_ORIGIN, h as canonicalJson, ht as FLOWS_LIST, i as tracedSteps, it as containsRedactedMarker, j as describeBuiltinPiece, k as blockPorts, kt as setPieceRegistryUrl, lt as DEFAULT_EGRESS_POLICY, m as loopStructure, mt as maxFileBytes, n as WorkflowTelemetry, nt as PieceWorkerError, o as installedPiece, ot as redactMessage, p as loopConfigHash, pt as FileTooLargeError, q as SecretNotFoundError, r as tracedMethods, rt as PieceWorkerTimeoutError, s as installedPieces, st as rememberSecrets, t as TELEMETRY_SCOPE, tt as PieceWorkerDisposedError, u as errorNameOf, ut as isPrivateAddress, v as DynamicPropertiesError, vt as pieceModuleRef, w as isHostBound, wt as unsupportedTrigger, x as ActivepiecesBlockExecutor, xt as UnsupportedPieceFeatureError, y as checkDynamicProperties, yt as sourcedResolver, z as declaredReactorConnectionIds } from "./telemetry-CFvEcs_9.js";
2
2
  import { DENIED_ACTION_INDEXES, ReactorAccessDeniedError, ReactorAccessDeniedError as ReactorAccessDeniedError$1, ReactorJobFailedError, ReactorJobPendingError as ReactorJobPendingError$1, WebhookHandshakeStrategy, assertActionsApplied } from "@powerhousedao/pieces-framework";
3
3
  import { mkdirSync, openAsBlob, readFileSync, writeFileSync } from "node:fs";
4
4
  import { open, readFile, readdir, rm, stat } from "node:fs/promises";
@@ -200,11 +200,19 @@ const TOKEN_TIMEOUT_MS = 15e3;
200
200
  const TOKEN_MAX_BYTES = 1048576;
201
201
  const oauthLogger = childLogger(["workflow", "oauth"]);
202
202
  var OAuthError = class extends Error {
203
- constructor(message) {
203
+ code;
204
+ constructor(message, code) {
204
205
  super(message);
206
+ this.code = code;
205
207
  this.name = "OAuthError";
206
208
  }
207
209
  };
210
+ var OAuthSignInRefusedError = class extends OAuthError {
211
+ constructor(message, code) {
212
+ super(message, code);
213
+ this.name = "OAuthSignInRefused";
214
+ }
215
+ };
208
216
  async function up$2(db) {
209
217
  await db.schema.createTable("oauth_attempt").addColumn("state", "text", (col) => col.primaryKey()).addColumn("connection_id", "text", (col) => col.notNull()).addColumn("client_id", "text", (col) => col.notNull()).addColumn("client_secret_ref", "text").addColumn("code_verifier", "text").addColumn("redirect_uri", "text", (col) => col.notNull()).addColumn("token_url", "text", (col) => col.notNull()).addColumn("authorization_method", "text").addColumn("return_url", "text").addColumn("created_by", "text").addColumn("status", "text", (col) => col.notNull()).addColumn("error", "text").addColumn("created_at", "text", (col) => col.notNull()).addColumn("expires_at", "text", (col) => col.notNull()).ifNotExists().execute();
210
218
  try {
@@ -392,7 +400,7 @@ async function postTokenForm(url, form, headers, egress) {
392
400
  const error = parsed.error ?? (parsed.ok === false ? "error" : void 0);
393
401
  if (status < 200 || status >= 300 || error !== void 0) {
394
402
  const description = typeof parsed.error_description === "string" ? `: ${parsed.error_description}` : "";
395
- throw new OAuthError(`Token endpoint refused (${typeof error === "string" ? error : status})${description}`);
403
+ throw new OAuthError(`Token endpoint refused (${typeof error === "string" ? error : status})${description}`, typeof error === "string" ? error : void 0);
396
404
  }
397
405
  if (typeof parsed.access_token !== "string") throw new OAuthError("Token endpoint answered without an access_token");
398
406
  return parsed;
@@ -468,7 +476,7 @@ async function exchangeCode(attempt, code, clientSecret, egress, fromRegistry =
468
476
  }
469
477
  function parseTokenSet(value) {
470
478
  const parsed = JSON.parse(value);
471
- if (typeof parsed.access_token !== "string") throw new OAuthError("Stored OAuth2 token is malformed; reconnect");
479
+ if (typeof parsed.access_token !== "string") throw new OAuthSignInRefusedError("Stored OAuth2 token is malformed; reconnect");
472
480
  return parsed;
473
481
  }
474
482
  function tokenExpired(tokens, nowSeconds) {
@@ -483,10 +491,12 @@ function tokenDue(tokens, nowSeconds) {
483
491
  var StoreTokenRefresher = class {
484
492
  secrets;
485
493
  egress;
494
+ onSignInRefused;
486
495
  inFlight = /* @__PURE__ */ new Map();
487
- constructor(secrets, egress) {
496
+ constructor(secrets, egress, onSignInRefused) {
488
497
  this.secrets = secrets;
489
498
  this.egress = egress;
499
+ this.onSignInRefused = onSignInRefused;
490
500
  }
491
501
  refreshIfDue(source, connectionId) {
492
502
  const refOf = (name) => source.secretRefs?.find((entry) => entry.name === name)?.ref;
@@ -512,7 +522,13 @@ var StoreTokenRefresher = class {
512
522
  async refresh(tokenRef, own, owner) {
513
523
  const store = await this.secrets();
514
524
  const read = (ref) => store.get(ref, owner);
515
- const tokens = parseTokenSet(await read(tokenRef));
525
+ let tokens;
526
+ try {
527
+ tokens = parseTokenSet(await read(tokenRef));
528
+ } catch (error) {
529
+ if (error instanceof OAuthSignInRefusedError) await this.signInRefused(owner.documentId, error);
530
+ throw error;
531
+ }
516
532
  if (!tokenDue(tokens, Math.round(Date.now() / 1e3))) return;
517
533
  let auth;
518
534
  if (tokens.relayed) {
@@ -533,16 +549,27 @@ var StoreTokenRefresher = class {
533
549
  }, auth.headers, tokens.relayed ? relayEgress(this.egress) : this.egress);
534
550
  } catch (error) {
535
551
  const detail = error instanceof Error ? error.message : String(error);
552
+ const message = `Refreshing the OAuth2 token failed; reconnect: ${detail}`;
553
+ const refused = error instanceof OAuthError && error.code === "invalid_grant" ? new OAuthSignInRefusedError(message, error.code) : void 0;
554
+ if (refused) await this.signInRefused(owner.documentId, refused);
536
555
  if (!tokenExpired(tokens, Math.round(Date.now() / 1e3))) {
537
556
  oauthLogger.warn(`Refreshing an OAuth2 token failed; using it until it expires: ${detail}`);
538
557
  return;
539
558
  }
540
- throw new OAuthError(`Refreshing the OAuth2 token failed; reconnect: ${detail}`);
559
+ throw refused ?? new OAuthError(message);
541
560
  }
542
561
  const current = parseTokenSet(await read(tokenRef));
543
562
  if (current.access_token !== tokens.access_token || current.claimed_at !== tokens.claimed_at) return;
544
563
  await store.rotate(tokenRef, JSON.stringify(tokenSetFrom(response, tokens, tokens)));
545
564
  }
565
+ async signInRefused(connectionId, error) {
566
+ if (!this.onSignInRefused) return;
567
+ try {
568
+ await this.onSignInRefused(connectionId, error);
569
+ } catch (cause) {
570
+ oauthLogger.warn(`Recording the refused OAuth2 sign-in of connection ${connectionId} failed: ${cause instanceof Error ? cause.message : String(cause)}`);
571
+ }
572
+ }
546
573
  };
547
574
  //#endregion
548
575
  //#region src/reactor/reactor-piece.ts
@@ -11543,7 +11570,17 @@ var WorkflowRuntimeService = class {
11543
11570
  return this.oauthAppsPromise;
11544
11571
  }
11545
11572
  oauthRefresher() {
11546
- return this.tokenRefresher ??= new StoreTokenRefresher(() => this.secrets(), this.designEgress);
11573
+ return this.tokenRefresher ??= new StoreTokenRefresher(() => this.secrets(), this.designEgress, (connectionId, error) => this.recordSignInRefused(connectionId, error));
11574
+ }
11575
+ async recordSignInRefused(connectionId, error) {
11576
+ const state = (await this.connectionDocument(connectionId)).state.global;
11577
+ if (state.status === "REVOKED") return;
11578
+ if (state.status === "ERROR" && state.lastError === error.message) return;
11579
+ await this.host.reactorClient.execute(connectionId, "main", [actions.recordCheckResult({
11580
+ status: "ERROR",
11581
+ checkedAt: (/* @__PURE__ */ new Date()).toISOString(),
11582
+ error: error.message
11583
+ })]);
11547
11584
  }
11548
11585
  /** The seeding failure a restart is needed to clear, or undefined while the
11549
11586
  * registry is seeded. Resolves once seeding has finished either way. */