credential-cipher.ts 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. import { createCipheriv, createDecipheriv, createHash, randomBytes } from "node:crypto";
  2. import { homedir, platform, userInfo } from "node:os";
  3. const ENCRYPTED_VALUE_PREFIX = "enc:v1:";
  4. const CREDENTIAL_CIPHER_ALGORITHM = "aes-256-gcm";
  5. const CREDENTIAL_CIPHER_IV_BYTES = 12;
  6. const CREDENTIAL_CIPHER_AUTH_TAG_BYTES = 16;
  7. const CREDENTIAL_SECRET_ENV_KEY = "ZCODE_CREDENTIAL_SECRET";
  8. export interface ZCodeCredentialCipher {
  9. decrypt(value: string): string;
  10. encrypt(value: string): string;
  11. }
  12. export interface ZCodeCredentialCipherOptions {
  13. env?: Record<string, string | undefined>;
  14. }
  15. export function createZCodeCredentialCipher(
  16. options: ZCodeCredentialCipherOptions = {},
  17. ): ZCodeCredentialCipher {
  18. const key = deriveCipherKey(resolveCredentialSecret(options.env ?? process.env));
  19. return {
  20. decrypt(value: string): string {
  21. if (!isEncryptedZCodeCredentialValue(value)) {
  22. return value;
  23. }
  24. const payload = value.slice(ENCRYPTED_VALUE_PREFIX.length);
  25. const parts = payload.split(".");
  26. const [ivRaw, authTagRaw, cipherRaw] = parts;
  27. if (!ivRaw || !authTagRaw || !cipherRaw || parts.length !== 3) {
  28. throw new Error("Credential decrypt failed: invalid ciphertext format");
  29. }
  30. const iv = Buffer.from(ivRaw, "base64url");
  31. const authTag = Buffer.from(authTagRaw, "base64url");
  32. const cipherText = Buffer.from(cipherRaw, "base64url");
  33. if (iv.length !== CREDENTIAL_CIPHER_IV_BYTES) {
  34. throw new Error("Credential decrypt failed: invalid IV length");
  35. }
  36. if (authTag.length !== CREDENTIAL_CIPHER_AUTH_TAG_BYTES) {
  37. throw new Error("Credential decrypt failed: invalid auth tag length");
  38. }
  39. try {
  40. const decipher = createDecipheriv(CREDENTIAL_CIPHER_ALGORITHM, key, iv);
  41. decipher.setAuthTag(authTag);
  42. const plainText = Buffer.concat([decipher.update(cipherText), decipher.final()]);
  43. return plainText.toString("utf-8");
  44. } catch (error) {
  45. throw new Error("Credential decrypt failed: key mismatch or corrupted ciphertext", {
  46. cause: error,
  47. });
  48. }
  49. },
  50. encrypt(value: string): string {
  51. const iv = randomBytes(CREDENTIAL_CIPHER_IV_BYTES);
  52. const cipher = createCipheriv(CREDENTIAL_CIPHER_ALGORITHM, key, iv);
  53. const encrypted = Buffer.concat([cipher.update(value, "utf-8"), cipher.final()]);
  54. const authTag = cipher.getAuthTag();
  55. return [
  56. ENCRYPTED_VALUE_PREFIX,
  57. iv.toString("base64url"),
  58. ".",
  59. authTag.toString("base64url"),
  60. ".",
  61. encrypted.toString("base64url"),
  62. ].join("");
  63. },
  64. };
  65. }
  66. export function isEncryptedZCodeCredentialValue(value: string): boolean {
  67. return value.startsWith(ENCRYPTED_VALUE_PREFIX);
  68. }
  69. function deriveCipherKey(secret: string): Buffer {
  70. return createHash("sha256").update(secret).digest();
  71. }
  72. function resolveCredentialSecret(env: Record<string, string | undefined>): string {
  73. const configuredSecret = env[CREDENTIAL_SECRET_ENV_KEY]?.trim();
  74. if (configuredSecret) {
  75. return configuredSecret;
  76. }
  77. let username = "unknown";
  78. try {
  79. username = userInfo().username;
  80. } catch {
  81. // Some packaged or sandboxed runtimes cannot resolve OS user info.
  82. }
  83. return `zcode-credential-fallback:${platform()}:${homedir()}:${username}`;
  84. }