import {readFileSync} from 'fs';
import {parseEncryptionKey} from './auth/token-encryption.js';
import type {OAuthCredentials} from './auth/oauth.js';
export type {OAuthCredentials};
export interface Config {
port: number;
host: string;
tls: {
keyPath: string;
certPath: string;
};
oauth: OAuthCredentials;
tokenEncryptionKey: Uint8Array;
sessionTtl: number;
}
interface CredentialsFile {
web: {
client_id: string;
client_secret: string;
redirect_uris: string[];
};
}
export function requireEnv(name: string): string {
const value = process.env[name];
if (!value) {
throw new Error(`Missing required environment variable: ${name}`);
}
return value;
}
export function loadOAuthCredentials(path: string): OAuthCredentials {
const file: CredentialsFile = JSON.parse(readFileSync(path, 'utf-8'));
return {
client_id: file.web.client_id,
client_secret: file.web.client_secret,
redirect_uri: file.web.redirect_uris[0],
};
}
export function loadEncryptionKey(path: string): Uint8Array {
const keyString = readFileSync(path, 'utf-8').trim();
return parseEncryptionKey(keyString);
}
export function loadConfig(): Config {
return {
port: parseInt(process.env.PORT || '3000', 10),
host: process.env.HOST || 'localhost',
tls: {
keyPath: requireEnv('TLS_KEY_PATH'),
certPath: requireEnv('TLS_CERT_PATH'),
},
oauth: loadOAuthCredentials(requireEnv('OAUTH_CREDENTIALS_PATH')),
tokenEncryptionKey: loadEncryptionKey(requireEnv('TOKEN_ENCRYPTION_PATH')),
sessionTtl: parseInt(process.env.SESSION_TTL || '86400', 10),
};
}