Initial upload to Gitea

This commit is contained in:
antonn committed 2026-11-30 16:32:37 +00:00
1 parent 78193254ad
commit 8478998cae
1485 files changed
+461025 -42348

No files matched your search

+146
View File
@@ -0,0 +1,146 @@
"use strict";
// Node-token protection at rest (audit finding C2).
//
// Node bearer tokens previously lived as plaintext in the `nodes.token`
// column, so any DB dump / backup / log leak meant instant takeover of that
// node. Tokens are now stored as AES-256-GCM ciphertext in the format
//
// enc:v1:<iv_b64>:<tag_b64>:<ciphertext_b64>
//
// The key is derived from SESSION_SECRET via scrypt with a fixed salt, so no
// extra key material needs to be provisioned. When the NODE_TOKEN_SEALING_KEY
// override is set (see getKey below), it replaces the KDF INPUT only — same
// scrypt, same salt, same 32-byte output — so rotating SESSION_SECRET no
// longer invalidates every sealed node token. Decryption is transparent:
// values without the "enc:v1:" prefix (legacy plaintext rows) are returned
// as-is, which also powers the one-time startup migration. Legacy plaintext
// rows must not linger in that state, though — the startup integrity gate
// (utils/node-token-integrity.js) classifies every stored value via
// classifyStoredNodeToken() and forces rotation of anything that cannot pass
// GCM auth-tag verification.
const crypto = require("crypto");
const ENC_PREFIX = "enc:v1:";
const SALT = "adpanel-node-token-v1";
// Lifecycle state of the stored credential, persisted in nodes.token_status.
// ok — AES-256-GCM ciphertext that decrypts cleanly
// rotate_required — credential was exposed at rest (pre-migration plaintext),
// is corrupt/unverifiable, or was invalidated; the admin
// must rotate it (surfaced as a "rotate required" badge)
const TOKEN_STATUS_OK = "ok";
const TOKEN_STATUS_ROTATE_REQUIRED = "rotate_required";
let _keyCache = null;
function getKey() {
if (_keyCache) return _keyCache;
// adpanel:node-token-sealing-key-override — the KDF INPUT is the ONLY change
// the override makes: same scryptSync, same node-token SALT, same 32-byte
// output; every parameter and the cache discipline stay exactly as before.
// With the override unset or empty ("" is falsy in this ||-fallback and is
// treated as unset by the boot check's `override !== ""` guard, so the two
// agree) the input is process.env.SESSION_SECRET — byte-identical to the
// pre-override algorithm, so every existing seal stays decryptable. With it
// set, SESSION_SECRET rotation stops invalidating every node bearer token
// (a rotated-away key makes sealed tokens fail GCM verification and the
// startup integrity gate would flag them corrupt → rotate_required → every
// node re-paired). There is deliberately NO derivation fallback beyond this
// one lookup: a token that fails GCM verification under the effective key
// fails CLOSED (decryptNodeToken returns null / classifyStoredNodeToken
// returns "corrupt") — never a silent re-derivation under some other input,
// which would convert key rotation/tampering into a node-takeover primitive.
// Introducing the override AFTER tokens are stored bricks those seals by
// design (fail-closed): they were minted under the previously derived key
// and require re-pairing — index.js says so once at boot
// (NODE_TOKEN_SEALING_KEY advisory), so set the override once and keep it
// stable.
const secret = String(process.env.NODE_TOKEN_SEALING_KEY || process.env.SESSION_SECRET || "");
if (!secret) {
throw new Error("node-token-crypto: SESSION_SECRET is not set; cannot encrypt node tokens");
}
_keyCache = crypto.scryptSync(secret, SALT, 32);
return _keyCache;
}
function isEncryptedNodeToken(value) {
return typeof value === "string" && value.startsWith(ENC_PREFIX);
}
function encryptNodeToken(plaintext) {
const value = String(plaintext || "");
if (!value || isEncryptedNodeToken(value)) return value;
const iv = crypto.randomBytes(12);
// authTagLength: 16 pins GCM to full-length tags on both sides of the
// envelope: the decipher's setAuthTag then rejects truncated tags instead
// of decrypting under a partial MAC (tag-truncation forgery).
const cipher = crypto.createCipheriv("aes-256-gcm", getKey(), iv, { authTagLength: 16 });
const ct = Buffer.concat([cipher.update(value, "utf8"), cipher.final()]);
const tag = cipher.getAuthTag();
return `${ENC_PREFIX}${iv.toString("base64")}:${tag.toString("base64")}:${ct.toString("base64")}`;
}
// Decrypts stored values. Legacy plaintext values pass through unchanged
// (migration handles them); corrupted ciphertext decrypts to null so callers
// can log and treat the node token as unset rather than crashing.
function decryptNodeToken(stored) {
const value = String(stored || "");
if (!value) return value;
if (!isEncryptedNodeToken(value)) return value;
try {
const parts = value.slice(ENC_PREFIX.length).split(":");
if (parts.length !== 3) return null;
const iv = Buffer.from(parts[0], "base64");
const tag = Buffer.from(parts[1], "base64");
const ct = Buffer.from(parts[2], "base64");
const decipher = crypto.createDecipheriv("aes-256-gcm", getKey(), iv, { authTagLength: 16 });
decipher.setAuthTag(tag);
return Buffer.concat([decipher.update(ct), decipher.final()]).toString("utf8");
} catch (err) {
// Most common cause: SESSION_SECRET changed since the token was stored.
return null;
}
}
// Verifies a stored value WITHOUT trusting the legacy pass-through: the
// plaintext branch is how pre-migration rows survive, so callers that care
// about the at-rest state (startup integrity gate) must classify instead of
// blindly decrypting. States:
// empty — nothing stored (nothing to verify; still unusable for auth)
// encrypted — "enc:v1:" value whose GCM auth tag verifies
// corrupt — "enc:v1:" value that fails GCM verification (key rotated
// since storage, truncated, or tampered row)
// plaintext — legacy pre-migration value with no prefix
// `plaintext` is only populated for states where the panel genuinely holds
// the working credential (encrypted/plaintext), never for corrupt values.
function classifyStoredNodeToken(stored) {
const value = String(stored || "");
if (!value) return { state: "empty" };
if (!isEncryptedNodeToken(value)) return { state: "plaintext", plaintext: value };
let plaintext = null;
try {
const parts = value.slice(ENC_PREFIX.length).split(":");
if (parts.length !== 3) return { state: "corrupt" };
const iv = Buffer.from(parts[0], "base64");
const tag = Buffer.from(parts[1], "base64");
const ct = Buffer.from(parts[2], "base64");
const decipher = crypto.createDecipheriv("aes-256-gcm", getKey(), iv, { authTagLength: 16 });
decipher.setAuthTag(tag);
plaintext = Buffer.concat([decipher.update(ct), decipher.final()]).toString("utf8");
} catch (err) {
return { state: "corrupt" };
}
return { state: "encrypted", plaintext };
}
module.exports = {
ENC_PREFIX,
TOKEN_STATUS_OK,
TOKEN_STATUS_ROTATE_REQUIRED,
isEncryptedNodeToken,
encryptNodeToken,
decryptNodeToken,
classifyStoredNodeToken,
};