@powerhousedao/reactor-workflow 6.2.3-dev.28 → 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";
@@ -1378,15 +1378,36 @@ function coreBlockDescriptor(blockType) {
1378
1378
  //#region src/reactor/secret-store.ts
1379
1379
  const IV_BYTES = 12;
1380
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";
1381
1385
  async function up$1(db) {
1382
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();
1383
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
+ };
1384
1404
  function loadKey(options) {
1385
- const hex = options.masterKeyHex ?? process.env.PH_WORKFLOWS_SECRETS_MASTER_KEY;
1405
+ const hex = options.masterKeyHex ?? process.env[MASTER_KEY_ENV];
1386
1406
  if (hex !== void 0) {
1387
1407
  if (!/^[0-9a-f]{64}$/i.test(hex)) throw new Error("Secrets master key must be 64 hex chars (32 bytes)");
1388
1408
  return Buffer.from(hex, "hex");
1389
1409
  }
1410
+ if (options.keyFile === false) throw new MasterKeyRequiredError();
1390
1411
  const file = options.keyFile ?? join(process.cwd(), ".ph", "secrets.key");
1391
1412
  try {
1392
1413
  const key = Buffer.from(readFileSync(file, "utf8").trim(), "hex");
@@ -1400,6 +1421,50 @@ function loadKey(options) {
1400
1421
  writeFileSync(file, key.toString("hex") + "\n", { mode: 384 });
1401
1422
  return key;
1402
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
+ }
1403
1468
  var LocalEncryptedSecretStore = class LocalEncryptedSecretStore {
1404
1469
  db;
1405
1470
  key;
@@ -1410,25 +1475,15 @@ var LocalEncryptedSecretStore = class LocalEncryptedSecretStore {
1410
1475
  static async create(relationalDb, options = {}) {
1411
1476
  const db = await relationalDb.createNamespace("secrets");
1412
1477
  await up$1(db);
1413
- return new LocalEncryptedSecretStore(db, loadKey(options));
1478
+ const key = loadKey(options);
1479
+ await verifyKey(db, key);
1480
+ return new LocalEncryptedSecretStore(db, key);
1414
1481
  }
1415
1482
  encrypt(value) {
1416
- const iv = randomBytes(IV_BYTES);
1417
- const cipher = createCipheriv("aes-256-gcm", this.key, iv);
1418
- const ciphertext = Buffer.concat([cipher.update(value, "utf8"), cipher.final()]);
1419
- return Buffer.concat([
1420
- iv,
1421
- cipher.getAuthTag(),
1422
- ciphertext
1423
- ]).toString("base64");
1483
+ return encrypt(this.key, value);
1424
1484
  }
1425
1485
  decrypt(enc) {
1426
- const raw = Buffer.from(enc, "base64");
1427
- const iv = raw.subarray(0, IV_BYTES);
1428
- const tag = raw.subarray(IV_BYTES, 28);
1429
- const decipher = createDecipheriv("aes-256-gcm", this.key, iv);
1430
- decipher.setAuthTag(tag);
1431
- return Buffer.concat([decipher.update(raw.subarray(28)), decipher.final()]).toString("utf8");
1486
+ return decrypt(this.key, enc);
1432
1487
  }
1433
1488
  async row(ref) {
1434
1489
  const id = parseSecretRef(ref);
@@ -2848,7 +2903,7 @@ var WorkflowRuntimeService = class {
2848
2903
  }
2849
2904
  }
2850
2905
  secrets() {
2851
- 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 });
2852
2907
  return this.secretsPromise;
2853
2908
  }
2854
2909
  secretProvider() {