substr/config.ts

91 lines
2.3 KiB
TypeScript

import { load } from "@std/dotenv";
import { parse as parseYaml } from "jsr:@std/yaml";
import { checkIfFileExists } from "./utils.ts";
import { log } from "./log.ts";
const dirname = Deno.cwd();
await load({ envPath: `${dirname}/.env`, export: true });
let userConfigPath: string = "";
let staticUsers: { [key: string]: string } = {};
const defaultUserConfigPaths = [
"/etc/substr/users.yaml",
`${dirname}/users.yaml`,
];
for (const path of defaultUserConfigPaths) {
const fileExists = await checkIfFileExists(path);
if (fileExists) {
userConfigPath = path;
break;
}
}
try {
const fileContent = await Deno.readTextFile(userConfigPath);
const parsedContent = parseYaml(fileContent);
if (parsedContent !== null && typeof parsedContent === "object") {
staticUsers = parsedContent as { [key: string]: string };
}
} catch {
// Nothing to do
}
const config = {
port: parseInt(Deno.env.get("PORT") || "30023"),
base_url: Deno.env.get("BASE_URL") || `http://localhost:30023`,
relay_urls: Deno.env.get("RELAY_URLS")?.split(",") || [],
staticUsers,
ldapEnabled: !!Deno.env.get("LDAP_URL"),
ldap: {
url: Deno.env.get("LDAP_URL"),
bindDN: Deno.env.get("LDAP_BIND_DN"),
password: Deno.env.get("LDAP_PASSWORD"),
searchDN: Deno.env.get("LDAP_SEARCH_DN"),
},
};
const staticUsersConfigured = Object.keys(staticUsers).length > 0;
export function ensureNecessaryConfigs() {
if (config.relay_urls.length === 0) {
log(
`No relays configured. Please add at least one relay to RELAY_URLS.`,
"yellow",
);
Deno.exit(1);
}
if (staticUsersConfigured) {
log(`Serving content for pubkeys in users.yaml`, "blue");
} else {
log(`Could not find or parse a users.yaml config`, "gray");
}
if (config.ldapEnabled) {
if (
config.ldap.url && config.ldap.bindDN && config.ldap.password &&
config.ldap.searchDN
) {
log(`Serving content for pubkeys from ${config.ldap.url}`, "blue");
} else {
log(`The LDAP config is incomplete`);
Deno.exit(1);
}
} else {
log(`LDAP not enabled`, "blue");
}
if (!staticUsersConfigured && !config.ldapEnabled) {
log(
`Neither static users nor LDAP configured. Nothing to serve.`,
"yellow",
);
Deno.exit(1);
}
}
export default config;