// runtime/subsystems/auth/backends/encryption-key/env.ts
import { createCipheriv, createDecipheriv, randomBytes } from "crypto";
var ALGO = "aes-256-gcm";
var NONCE_BYTES = 12;
var TAG_BYTES = 16;
var KEY_BYTES = 32;
var EnvEncryptionKey = class {
  key;
  constructor(opts = {}) {
    const env = opts.env ?? process.env;
    const envVar = opts.envVar ?? "INTEGRATION_TOKEN_ENCRYPTION_KEY";
    const raw = env[envVar];
    if (!raw) {
      throw new Error(
        `EnvEncryptionKey: ${envVar} is not set. Generate with: openssl rand -base64 32`
      );
    }
    const decoded = Buffer.from(raw, "base64");
    if (decoded.length !== KEY_BYTES) {
      throw new Error(
        `EnvEncryptionKey: ${envVar} must decode to ${KEY_BYTES} bytes (got ${decoded.length}). Use: openssl rand -base64 32`
      );
    }
    this.key = decoded;
  }
  async encrypt(plaintext) {
    const nonce = randomBytes(NONCE_BYTES);
    const cipher = createCipheriv(ALGO, this.key, nonce);
    const ciphertext = Buffer.concat([
      cipher.update(plaintext, "utf8"),
      cipher.final()
    ]);
    const authTag = cipher.getAuthTag();
    return Buffer.concat([nonce, ciphertext, authTag]).toString("base64");
  }
  async decrypt(ciphertext) {
    const buf = Buffer.from(ciphertext, "base64");
    if (buf.length < NONCE_BYTES + TAG_BYTES) {
      throw new Error("EnvEncryptionKey: ciphertext too short");
    }
    const nonce = buf.subarray(0, NONCE_BYTES);
    const authTag = buf.subarray(buf.length - TAG_BYTES);
    const body = buf.subarray(NONCE_BYTES, buf.length - TAG_BYTES);
    const decipher = createDecipheriv(ALGO, this.key, nonce);
    decipher.setAuthTag(authTag);
    const plain = Buffer.concat([decipher.update(body), decipher.final()]);
    return plain.toString("utf8");
  }
};

export {
  EnvEncryptionKey
};
//# sourceMappingURL=chunk-IP4OO26U.js.map