M001: add secure admin foundation

This commit is contained in:
illusia committed 2026-09-01 08:00:24 +08:00
1 parent 960be106bb
commit 31f320d4c1
32 files changed
+2518 -679

No files matched your search

+65
View File
@@ -0,0 +1,65 @@
import { randomBytes, scrypt, timingSafeEqual } from "node:crypto";
const KEY_LENGTH = 64;
const SCRYPT_PARAMETERS = Object.freeze({ N: 32768, r: 8, p: 1, maxmem: 64 * 1024 * 1024 });
export interface AdminCredential {
version: 1;
salt: string;
hash: string;
parameters: {
N: number;
r: number;
p: number;
};
}
export function validateAdminPassword(password: string): string | null {
if (password.length < 12) return "Admin password must contain at least 12 characters";
if (password.length > 1024) return "Admin password is too long";
return null;
}
export async function hashAdminPassword(password: string): Promise<AdminCredential> {
const validationError = validateAdminPassword(password);
if (validationError) throw new Error(validationError);
const salt = randomBytes(16);
const hash = await derive(password, salt, SCRYPT_PARAMETERS);
return {
version: 1,
salt: salt.toString("base64url"),
hash: hash.toString("base64url"),
parameters: {
N: SCRYPT_PARAMETERS.N,
r: SCRYPT_PARAMETERS.r,
p: SCRYPT_PARAMETERS.p,
},
};
}
export async function verifyAdminPassword(password: string, credential: AdminCredential): Promise<boolean> {
if (credential.version !== 1 || typeof password !== "string" || password.length > 1024) return false;
try {
const expected = Buffer.from(credential.hash, "base64url");
const actual = await derive(password, Buffer.from(credential.salt, "base64url"), {
...credential.parameters,
maxmem: 64 * 1024 * 1024,
});
return expected.length === actual.length && timingSafeEqual(expected, actual);
} catch {
return false;
}
}
async function derive(
password: string,
salt: Buffer,
parameters: { N: number; r: number; p: number; maxmem: number },
): Promise<Buffer> {
return new Promise((resolve, reject) => {
scrypt(password, salt, KEY_LENGTH, parameters, (error, result) => {
if (error) reject(error);
else resolve(Buffer.from(result));
});
});
}
+54
View File
@@ -0,0 +1,54 @@
import { chmodSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
import { dirname } from "node:path";
import { randomBytes, timingSafeEqual } from "node:crypto";
export class BootstrapManager {
private code: string | null = null;
constructor(private readonly path: string) {}
ensure(): string {
if (this.code) return this.code;
try {
const stored = readFileSync(this.path, "utf8").trim();
if (normalize(stored).length >= 20) {
this.code = stored;
return stored;
}
} catch {
// A missing or invalid bootstrap file is replaced below.
}
const raw = randomBytes(16).toString("hex").toUpperCase();
this.code = raw.match(/.{1,4}/g)!.join("-");
mkdirSync(dirname(this.path), { recursive: true });
writeFileSync(this.path, `${this.code}\n`, { encoding: "utf8", mode: 0o600 });
try {
chmodSync(this.path, 0o600);
} catch {
// POSIX permissions are best-effort on non-POSIX filesystems.
}
return this.code;
}
verify(candidate: string): boolean {
const expected = normalize(this.ensure());
const actual = normalize(candidate);
const expectedBytes = Buffer.from(expected, "utf8");
const actualBytes = Buffer.from(actual, "utf8");
return expectedBytes.length === actualBytes.length && timingSafeEqual(expectedBytes, actualBytes);
}
consume(): void {
this.code = null;
try {
unlinkSync(this.path);
} catch (error: unknown) {
if (!(error instanceof Error && "code" in error && error.code === "ENOENT")) throw error;
}
}
}
function normalize(value: string): string {
return value.replace(/[^a-fA-F0-9]/g, "").toUpperCase();
}
+42
View File
@@ -0,0 +1,42 @@
import {
chmodSync,
closeSync,
mkdirSync,
openSync,
readFileSync,
writeFileSync,
} from "node:fs";
import { dirname } from "node:path";
import { randomBytes } from "node:crypto";
const MASTER_KEY_BYTES = 32;
/** Create or load the installation-local key used to protect secrets at rest. */
export function loadOrCreateMasterSecret(path: string): Buffer {
mkdirSync(dirname(path), { recursive: true });
try {
const descriptor = openSync(path, "wx", 0o600);
try {
writeFileSync(descriptor, randomBytes(MASTER_KEY_BYTES));
} finally {
closeSync(descriptor);
}
} catch (error: unknown) {
if (!isAlreadyExistsError(error)) throw error;
}
const key = readFileSync(path);
if (key.length !== MASTER_KEY_BYTES) {
throw new Error(`Invalid WebSpeak master secret: expected ${MASTER_KEY_BYTES} bytes`);
}
try {
chmodSync(path, 0o600);
} catch {
// Windows and some container filesystems do not expose POSIX permissions.
}
return key;
}
function isAlreadyExistsError(error: unknown): boolean {
return error instanceof Error && "code" in error && error.code === "EEXIST";
}
+68
View File
@@ -0,0 +1,68 @@
import { isIP } from "node:net";
import { lookup } from "node:dns/promises";
import type { TeamSpeakTarget } from "../domain/teamspeak-target.js";
export class UnsafeTeamSpeakTargetError extends Error {
constructor(message = "This TeamSpeak target is not allowed in open mode") {
super(message);
this.name = "UnsafeTeamSpeakTargetError";
}
}
/** Resolve and reject addresses that could turn a public gateway into an internal network probe. */
export async function assertSafeOpenTarget(target: TeamSpeakTarget): Promise<void> {
await resolveSafeOpenTarget(target);
}
export async function resolveSafeOpenTarget(target: TeamSpeakTarget): Promise<TeamSpeakTarget> {
const literalVersion = isIP(target.host);
const addresses = literalVersion
? [{ address: target.host, family: literalVersion }]
: await lookup(target.host, { all: true, verbatim: true });
if (!addresses.length || addresses.some(({ address }) => isRestrictedAddress(address))) {
throw new UnsafeTeamSpeakTargetError();
}
// Use the address that was actually validated so a second DNS lookup cannot
// rebind the gateway connection to a private network.
return { host: addresses[0]!.address, port: target.port };
}
export function isRestrictedAddress(address: string): boolean {
const version = isIP(address);
if (version === 4) return isRestrictedIpv4(address);
if (version !== 6) return true;
const normalized = address.toLocaleLowerCase();
if (normalized === "::" || normalized === "::1") return true;
if (normalized.startsWith("::ffff:")) {
const mapped = normalized.slice("::ffff:".length);
return isIP(mapped) !== 4 || isRestrictedIpv4(mapped);
}
if (normalized.startsWith("::")) return true; // IPv4-compatible and other special compressed forms
const first = Number.parseInt(normalized.split(":", 1)[0] || "0", 16);
if ((first & 0xfe00) === 0xfc00) return true; // unique-local fc00::/7
if ((first & 0xffc0) === 0xfe80) return true; // link-local fe80::/10
if ((first & 0xffc0) === 0xfec0) return true; // deprecated site-local fec0::/10
if ((first & 0xff00) === 0xff00) return true; // multicast ff00::/8
if (normalized.startsWith("2001:db8:")) return true; // documentation range
return false;
}
function isRestrictedIpv4(address: string): boolean {
const parts = address.split(".").map(Number);
if (parts.length !== 4 || parts.some((part) => !Number.isInteger(part) || part < 0 || part > 255)) return true;
const [a, b] = parts as [number, number, number, number];
return a === 0
|| a === 10
|| a === 127
|| (a === 100 && b >= 64 && b <= 127)
|| (a === 169 && b === 254)
|| (a === 172 && b >= 16 && b <= 31)
|| (a === 192 && b === 0)
|| (a === 192 && b === 168)
|| (a === 192 && b === 0 && parts[2] === 2)
|| (a === 198 && (b === 18 || b === 19))
|| (a === 198 && b === 51 && parts[2] === 100)
|| (a === 203 && b === 0 && parts[2] === 113)
|| a >= 224;
}
+36
View File
@@ -0,0 +1,36 @@
import { createCipheriv, createDecipheriv, randomBytes } from "node:crypto";
const ALGORITHM = "aes-256-gcm";
const VERSION = "v1";
const AAD = Buffer.from("webspeak:teamspeak-password:v1", "utf8");
export function encryptSecret(value: string, masterKey: Buffer): string {
if (!value) return "";
assertMasterKey(masterKey);
const nonce = randomBytes(12);
const cipher = createCipheriv(ALGORITHM, masterKey, nonce);
cipher.setAAD(AAD);
const ciphertext = Buffer.concat([cipher.update(value, "utf8"), cipher.final()]);
const tag = cipher.getAuthTag();
return [VERSION, nonce.toString("base64url"), tag.toString("base64url"), ciphertext.toString("base64url")].join(":");
}
export function decryptSecret(payload: string | null | undefined, masterKey: Buffer): string {
if (!payload) return "";
assertMasterKey(masterKey);
const [version, nonceText, tagText, ciphertextText, ...extra] = payload.split(":");
if (version !== VERSION || !nonceText || !tagText || ciphertextText === undefined || extra.length) {
throw new Error("Unsupported encrypted secret format");
}
const decipher = createDecipheriv(ALGORITHM, masterKey, Buffer.from(nonceText, "base64url"));
decipher.setAAD(AAD);
decipher.setAuthTag(Buffer.from(tagText, "base64url"));
return Buffer.concat([
decipher.update(Buffer.from(ciphertextText, "base64url")),
decipher.final(),
]).toString("utf8");
}
function assertMasterKey(masterKey: Buffer): void {
if (masterKey.length !== 32) throw new Error("Invalid master key length");
}