@powerhousedao/reactor-workflow 6.2.3-dev.27 → 6.2.3-dev.29

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
@@ -5,7 +5,7 @@ import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
5
5
  import { open, readFile, rm } from "node:fs/promises";
6
6
  import { dirname, join } from "node:path";
7
7
  import { childLogger, createAction, withSignaturePolicy } from "document-model";
8
- import { createCipheriv, createDecipheriv, createHash, randomBytes, randomUUID } from "node:crypto";
8
+ import { createCipheriv, createDecipheriv, createHash, createHmac, randomBytes, randomUUID } from "node:crypto";
9
9
  import { Cron } from "croner";
10
10
  import { AsyncLocalStorage } from "node:async_hooks";
11
11
  import { actions } from "@powerhousedao/workflow/document-models/connection";
@@ -422,6 +422,7 @@ function toSummaries(raw) {
422
422
  triggerCount: typeof entry.triggers === "number" ? entry.triggers : 0,
423
423
  categories: entry.categories ?? [],
424
424
  auth: entry.auth ?? null,
425
+ ...entry.deprecated === true ? { deprecated: true } : {},
425
426
  ...reasonOf(unsupportedAuth(entry.auth))
426
427
  }));
427
428
  }
@@ -1377,15 +1378,36 @@ function coreBlockDescriptor(blockType) {
1377
1378
  //#region src/reactor/secret-store.ts
1378
1379
  const IV_BYTES = 12;
1379
1380
  const KEY_BYTES = 32;
1381
+ const MASTER_KEY_ENV = "PH_WORKFLOWS_SECRETS_MASTER_KEY";
1382
+ const LEGACY_MASTER_KEY_ENV = "PH_SECRETS_MASTER_KEY";
1383
+ const KEY_CHECK_ID = "master";
1384
+ const KEY_CHECK_LABEL = "reactor-workflow/secrets/key-check/v1";
1380
1385
  async function up$1(db) {
1381
1386
  await db.schema.createTable("secret").addColumn("id", "text", (col) => col.primaryKey()).addColumn("label", "text").addColumn("version", "integer", (col) => col.notNull()).addColumn("enc", "text").addColumn("status", "text", (col) => col.notNull()).addColumn("created_at", "text", (col) => col.notNull()).addColumn("updated_at", "text", (col) => col.notNull()).ifNotExists().execute();
1387
+ await db.schema.createTable("secret_key_check").addColumn("id", "text", (col) => col.primaryKey()).addColumn("fingerprint", "text", (col) => col.notNull()).addColumn("created_at", "text", (col) => col.notNull()).ifNotExists().execute();
1382
1388
  }
1389
+ function legacyKeyHint() {
1390
+ return process.env[LEGACY_MASTER_KEY_ENV] !== void 0 ? ` ${LEGACY_MASTER_KEY_ENV} is set but no longer read; rename it to ${MASTER_KEY_ENV}.` : "";
1391
+ }
1392
+ var MasterKeyRequiredError = class extends Error {
1393
+ constructor() {
1394
+ super(`${MASTER_KEY_ENV} must be set: this host's secrets outlive its working directory, so a generated key would be lost on restart.${legacyKeyHint()}`);
1395
+ this.name = "MasterKeyRequiredError";
1396
+ }
1397
+ };
1398
+ var MasterKeyMismatchError = class extends Error {
1399
+ constructor() {
1400
+ super(`The secrets master key is not the one this database's secrets were stored with. Set ${MASTER_KEY_ENV} to that key; if it is lost, the stored secrets cannot be recovered.${legacyKeyHint()}`);
1401
+ this.name = "MasterKeyMismatchError";
1402
+ }
1403
+ };
1383
1404
  function loadKey(options) {
1384
- const hex = options.masterKeyHex ?? process.env.PH_WORKFLOWS_SECRETS_MASTER_KEY;
1405
+ const hex = options.masterKeyHex ?? process.env[MASTER_KEY_ENV];
1385
1406
  if (hex !== void 0) {
1386
1407
  if (!/^[0-9a-f]{64}$/i.test(hex)) throw new Error("Secrets master key must be 64 hex chars (32 bytes)");
1387
1408
  return Buffer.from(hex, "hex");
1388
1409
  }
1410
+ if (options.keyFile === false) throw new MasterKeyRequiredError();
1389
1411
  const file = options.keyFile ?? join(process.cwd(), ".ph", "secrets.key");
1390
1412
  try {
1391
1413
  const key = Buffer.from(readFileSync(file, "utf8").trim(), "hex");
@@ -1399,6 +1421,50 @@ function loadKey(options) {
1399
1421
  writeFileSync(file, key.toString("hex") + "\n", { mode: 384 });
1400
1422
  return key;
1401
1423
  }
1424
+ function encrypt(key, value) {
1425
+ const iv = randomBytes(IV_BYTES);
1426
+ const cipher = createCipheriv("aes-256-gcm", key, iv);
1427
+ const ciphertext = Buffer.concat([cipher.update(value, "utf8"), cipher.final()]);
1428
+ return Buffer.concat([
1429
+ iv,
1430
+ cipher.getAuthTag(),
1431
+ ciphertext
1432
+ ]).toString("base64");
1433
+ }
1434
+ function decrypt(key, enc) {
1435
+ const raw = Buffer.from(enc, "base64");
1436
+ const iv = raw.subarray(0, IV_BYTES);
1437
+ const tag = raw.subarray(IV_BYTES, 28);
1438
+ const decipher = createDecipheriv("aes-256-gcm", key, iv);
1439
+ decipher.setAuthTag(tag);
1440
+ return Buffer.concat([decipher.update(raw.subarray(28)), decipher.final()]).toString("utf8");
1441
+ }
1442
+ function decrypts(key, enc) {
1443
+ try {
1444
+ decrypt(key, enc);
1445
+ return true;
1446
+ } catch {
1447
+ return false;
1448
+ }
1449
+ }
1450
+ async function storedFingerprint(db) {
1451
+ return (await db.selectFrom("secret_key_check").select("fingerprint").where("id", "=", KEY_CHECK_ID).executeTakeFirst())?.fingerprint;
1452
+ }
1453
+ async function verifyKey(db, key) {
1454
+ const fingerprint = createHmac("sha256", key).update(KEY_CHECK_LABEL).digest("hex");
1455
+ let stored = await storedFingerprint(db);
1456
+ if (stored === void 0) {
1457
+ const newest = await db.selectFrom("secret").select("enc").where("enc", "is not", null).orderBy("updated_at", "desc").limit(1).executeTakeFirst();
1458
+ if (newest?.enc && !decrypts(key, newest.enc)) throw new MasterKeyMismatchError();
1459
+ await db.insertInto("secret_key_check").values({
1460
+ id: KEY_CHECK_ID,
1461
+ fingerprint,
1462
+ created_at: (/* @__PURE__ */ new Date()).toISOString()
1463
+ }).onConflict((oc) => oc.column("id").doNothing()).execute();
1464
+ stored = await storedFingerprint(db);
1465
+ }
1466
+ if (stored !== fingerprint) throw new MasterKeyMismatchError();
1467
+ }
1402
1468
  var LocalEncryptedSecretStore = class LocalEncryptedSecretStore {
1403
1469
  db;
1404
1470
  key;
@@ -1409,25 +1475,15 @@ var LocalEncryptedSecretStore = class LocalEncryptedSecretStore {
1409
1475
  static async create(relationalDb, options = {}) {
1410
1476
  const db = await relationalDb.createNamespace("secrets");
1411
1477
  await up$1(db);
1412
- return new LocalEncryptedSecretStore(db, loadKey(options));
1478
+ const key = loadKey(options);
1479
+ await verifyKey(db, key);
1480
+ return new LocalEncryptedSecretStore(db, key);
1413
1481
  }
1414
1482
  encrypt(value) {
1415
- const iv = randomBytes(IV_BYTES);
1416
- const cipher = createCipheriv("aes-256-gcm", this.key, iv);
1417
- const ciphertext = Buffer.concat([cipher.update(value, "utf8"), cipher.final()]);
1418
- return Buffer.concat([
1419
- iv,
1420
- cipher.getAuthTag(),
1421
- ciphertext
1422
- ]).toString("base64");
1483
+ return encrypt(this.key, value);
1423
1484
  }
1424
1485
  decrypt(enc) {
1425
- const raw = Buffer.from(enc, "base64");
1426
- const iv = raw.subarray(0, IV_BYTES);
1427
- const tag = raw.subarray(IV_BYTES, 28);
1428
- const decipher = createDecipheriv("aes-256-gcm", this.key, iv);
1429
- decipher.setAuthTag(tag);
1430
- return Buffer.concat([decipher.update(raw.subarray(28)), decipher.final()]).toString("utf8");
1486
+ return decrypt(this.key, enc);
1431
1487
  }
1432
1488
  async row(ref) {
1433
1489
  const id = parseSecretRef(ref);
@@ -2847,7 +2903,7 @@ var WorkflowRuntimeService = class {
2847
2903
  }
2848
2904
  }
2849
2905
  secrets() {
2850
- this.secretsPromise ??= this.host.secrets !== void 0 ? Promise.resolve(this.host.secrets) : LocalEncryptedSecretStore.create(this.host.relationalDb);
2906
+ this.secretsPromise ??= this.host.secrets !== void 0 ? Promise.resolve(this.host.secrets) : LocalEncryptedSecretStore.create(this.host.relationalDb, { keyFile: this.host.secretsKeyFile });
2851
2907
  return this.secretsPromise;
2852
2908
  }
2853
2909
  secretProvider() {
@@ -3854,7 +3910,7 @@ var WorkflowRuntimeService = class {
3854
3910
  if (!ctx) throw new Error("Connection access requires an authenticated request");
3855
3911
  await this.host.assertCanWrite(documentId, ctx);
3856
3912
  }
3857
- async blockOptions(blockType, propName, input, connectionId, ctx) {
3913
+ async blockOptions(blockType, propName, input, connectionId, ctx, searchValue) {
3858
3914
  const parsed = await this.resolvedBlock(blockType);
3859
3915
  if (!parsed) throw new Error(`Not a piece block type: "${blockType}"`);
3860
3916
  let auth;
@@ -3873,6 +3929,7 @@ var WorkflowRuntimeService = class {
3873
3929
  kind: parsed.kind,
3874
3930
  propName,
3875
3931
  refresherValues: input ?? {},
3932
+ ...searchValue !== void 0 ? { searchValue } : {},
3876
3933
  auth,
3877
3934
  projectId: PROJECT_SCOPE_KEY,
3878
3935
  ...servesReactorPort(parsed.packageName) ? { reactorAccess: true } : {},