testirovanie-robot/src/config.ts

76 lines
3.0 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import { createHmac, randomBytes } from "node:crypto";
import { fileURLToPath } from "node:url";
import type { Account } from "./auth.ts";
export interface Config {
port: number;
/** Логин и пароль владельца; undefined — не заданы. */
account: Account | undefined;
/** Файл со списком пользователей (`USERS_FILE`, по умолчанию `data/users.json`). */
usersFile: string;
sessionSecret: Buffer;
cookieSecure: boolean;
sentry: { dsn: string | undefined; release: string | undefined; environment: string };
warnings: string[];
}
type Env = Record<string, string | undefined>;
const value = (env: Env, name: string) => env[name]?.trim() || undefined;
/** prod / staging / dev по адресу стенда: `<slug>-prod.…`, `<slug>-staging.…`, остальное — dev. */
export function environmentFromHost(host: string | undefined): string {
const name = host?.split(".")[0] ?? "";
if (name.endsWith("-prod")) return "prod";
if (name.endsWith("-staging")) return "staging";
return "dev";
}
export function loadConfig(env: Env = process.env): Config {
const warnings: string[] = [];
const login = value(env, "AUTH_LOGIN");
// Пароль не обрезаем: пробелы в нём значимы.
const password = env.AUTH_PASSWORD || undefined;
const configured = login !== undefined && password !== undefined;
if (!configured) {
const missing =
login !== undefined || password !== undefined
? "Задан только один из AUTH_LOGIN / AUTH_PASSWORD"
: "AUTH_LOGIN / AUTH_PASSWORD не заданы";
warnings.push(`${missing} — войти могут только пользователи из списка.`);
}
const account = configured ? { login, password } : undefined;
const explicitSecret = value(env, "SESSION_SECRET");
let sessionSecret: Buffer;
if (explicitSecret) sessionSecret = Buffer.from(explicitSecret, "utf8");
else if (configured)
// Производный ключ: смена пароля делает недействительными все прежние входы.
sessionSecret = createHmac("sha256", password).update(`session:${login}`).digest();
else sessionSecret = randomBytes(32);
const secureFlag = value(env, "COOKIE_SECURE");
const cookieSecure =
secureFlag !== undefined ? secureFlag !== "false" : env.NODE_ENV === "production";
const port = Number(value(env, "PORT") ?? 3000);
if (!Number.isInteger(port) || port < 0 || port > 65535) {
throw new Error(`PORT должен быть числом от 0 до 65535, получено: ${env.PORT}`);
}
return {
port,
account,
usersFile:
value(env, "USERS_FILE") ?? fileURLToPath(new URL("../data/users.json", import.meta.url)),
sessionSecret,
cookieSecure,
sentry: {
dsn: value(env, "SENTRY_DSN"),
release: value(env, "SENTRY_RELEASE"),
environment: value(env, "SENTRY_ENVIRONMENT") ?? environmentFromHost(value(env, "APP_HOST")),
},
warnings,
};
}