/home/techb158/cosmic.abdallabala.com/src/security
NameSizeModeActions
accessControl.js121430666editdlrm
securityHeaders.js23410666editdlrm
tokenVault.js19670666editdlrm
Edit: /home/techb158/cosmic.abdallabala.com/src/security/tokenVault.js (1967B)
const crypto = require("crypto"); const ALGORITHM = "aes-256-gcm"; function hasEncryptionSecret(env = process.env) { return Boolean(env.COSMIC_TOKEN_ENCRYPTION_KEY && env.COSMIC_TOKEN_ENCRYPTION_KEY.trim()); } function deriveKey(secret) { return crypto.createHash("sha256").update(String(secret)).digest(); } function encryptToken(token, env = process.env) { if (!token) return null; if (!hasEncryptionSecret(env)) { throw new Error("COSMIC_TOKEN_ENCRYPTION_KEY is required before OAuth tokens can be stored"); } const iv = crypto.randomBytes(12); const key = deriveKey(env.COSMIC_TOKEN_ENCRYPTION_KEY); const cipher = crypto.createCipheriv(ALGORITHM, key, iv); const encrypted = Buffer.concat([cipher.update(String(token), "utf8"), cipher.final()]); const tag = cipher.getAuthTag(); return ["v1", iv.toString("base64"), tag.toString("base64"), encrypted.toString("base64")].join(":"); } function decryptToken(payload, env = process.env) { if (!payload) return null; if (!hasEncryptionSecret(env)) { throw new Error("COSMIC_TOKEN_ENCRYPTION_KEY is required before OAuth tokens can be read"); } const [version, ivB64, tagB64, encryptedB64] = String(payload).split(":"); if (version !== "v1" || !ivB64 || !tagB64 || !encryptedB64) { throw new Error("Unsupported encrypted token format"); } const key = deriveKey(env.COSMIC_TOKEN_ENCRYPTION_KEY); const decipher = crypto.createDecipheriv(ALGORITHM, key, Buffer.from(ivB64, "base64")); decipher.setAuthTag(Buffer.from(tagB64, "base64")); return Buffer.concat([decipher.update(Buffer.from(encryptedB64, "base64")), decipher.final()]).toString("utf8"); } function redactToken(token) { if (!token) return null; const text = String(token); if (text.length <= 10) return `${text.slice(0, 2)}***${text.slice(-2)}`; return `${text.slice(0, 6)}***${text.slice(-4)}`; } module.exports = { encryptToken, decryptToken, redactToken, hasEncryptionSecret };