refactor: pre-M0 cleanup, core library hardening, and isolated dev/QA Docker stack
- Remove ~44k LOC of dead code, legacy v1 TS simulator/strategy stack, event-bus, analytics FastAPI prototype, legacy calculation archives, and unused deps (data-ingestion provider API handlers untouched) - Extract @stock-bot/di/http-security and isolate @stock-bot/browser to data-ingestion via ServiceContainerBuilder.withRegistrations() - Harden @stock-bot/mongodb read-only proxies, flatten @stock-bot/postgres with unified master+research migrations, and fix @stock-bot/config EnvLoader, ServiceApplication worker lifecycle, NamespacedCache.clear(), and BatchProcessor error propagation - Flatten workspace root (remove apps/stock/package.json) and collapse orchestrator re-export shims - Pin all Docker image versions, add shm_size/nofile/RAM caps and docker-compose.quant.yml, fix 05-add-visible-column.sql view recreation, and decouple dev/QA Compose project names for side-by-side execution - Update PLATFORM-PLAN, DATA-CONTRACTS (bars_1m PARTITION BY MONTH, Rust bulk ETL, DuckDB limits), MILESTONES, and servers docs
This commit is contained in:
parent
ce9e2df67c
commit
4cd6038063
432 changed files with 1247 additions and 44469 deletions
|
|
@ -1,175 +0,0 @@
|
|||
#!/usr/bin/env bun
|
||||
/* eslint-disable no-console */
|
||||
import { join } from 'path';
|
||||
import { parseArgs } from 'util';
|
||||
import { redactSecrets } from './utils/secrets';
|
||||
import {
|
||||
checkRequiredEnvVars,
|
||||
formatValidationResult,
|
||||
validateCompleteness,
|
||||
validateConfig,
|
||||
} from './utils/validation';
|
||||
import { ConfigManager } from './config-manager';
|
||||
import { baseAppSchema } from './schemas';
|
||||
import type { Environment } from './types';
|
||||
|
||||
interface CliOptions {
|
||||
config?: string;
|
||||
env?: string;
|
||||
validate?: boolean;
|
||||
show?: boolean;
|
||||
check?: boolean;
|
||||
json?: boolean;
|
||||
help?: boolean;
|
||||
}
|
||||
|
||||
const REQUIRED_PATHS = [
|
||||
'service.name',
|
||||
'service.port',
|
||||
'database.postgres.host',
|
||||
'database.postgres.database',
|
||||
];
|
||||
|
||||
const REQUIRED_ENV_VARS = ['NODE_ENV'];
|
||||
|
||||
const SECRET_PATHS = [
|
||||
'database.postgres.password',
|
||||
'database.mongodb.uri',
|
||||
'providers.quoteMedia.apiKey',
|
||||
'providers.interactiveBrokers.clientId',
|
||||
];
|
||||
|
||||
function printUsage() {
|
||||
console.log(`
|
||||
Stock Bot Configuration CLI
|
||||
|
||||
Usage: bun run config-cli [options]
|
||||
|
||||
Options:
|
||||
--config <path> Path to config directory (default: ./config)
|
||||
--env <env> Environment to use (development, test, production)
|
||||
--validate Validate configuration against schema
|
||||
--show Show current configuration (secrets redacted)
|
||||
--check Run all configuration checks
|
||||
--json Output in JSON format
|
||||
--help Show this help message
|
||||
|
||||
Examples:
|
||||
# Validate configuration
|
||||
bun run config-cli --validate
|
||||
|
||||
# Show configuration for production
|
||||
bun run config-cli --env production --show
|
||||
|
||||
# Run all checks
|
||||
bun run config-cli --check
|
||||
|
||||
# Output configuration as JSON
|
||||
bun run config-cli --show --json
|
||||
`);
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const { values } = parseArgs({
|
||||
args: process.argv.slice(2),
|
||||
options: {
|
||||
config: { type: 'string' },
|
||||
env: { type: 'string' },
|
||||
validate: { type: 'boolean' },
|
||||
show: { type: 'boolean' },
|
||||
check: { type: 'boolean' },
|
||||
json: { type: 'boolean' },
|
||||
help: { type: 'boolean' },
|
||||
},
|
||||
}) as { values: CliOptions };
|
||||
|
||||
if (values.help) {
|
||||
printUsage();
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
const configPath = values.config || join(process.cwd(), 'config');
|
||||
const environment = values.env as Environment;
|
||||
|
||||
try {
|
||||
const manager = new ConfigManager({
|
||||
configPath,
|
||||
environment,
|
||||
});
|
||||
|
||||
const config = await manager.initialize(baseAppSchema);
|
||||
|
||||
if (values.validate) {
|
||||
const result = validateConfig(config, baseAppSchema);
|
||||
|
||||
if (values.json) {
|
||||
console.log(JSON.stringify(result, null, 2));
|
||||
} else {
|
||||
console.log(formatValidationResult(result));
|
||||
}
|
||||
|
||||
process.exit(result.valid ? 0 : 1);
|
||||
}
|
||||
|
||||
if (values.show) {
|
||||
const redacted = redactSecrets(config, SECRET_PATHS);
|
||||
|
||||
if (values.json) {
|
||||
console.log(JSON.stringify(redacted, null, 2));
|
||||
} else {
|
||||
console.log('Current Configuration:');
|
||||
console.log(JSON.stringify(redacted, null, 2));
|
||||
}
|
||||
}
|
||||
|
||||
if (values.check) {
|
||||
console.log('Running configuration checks...\n');
|
||||
|
||||
// Schema validation
|
||||
console.log('1. Schema Validation:');
|
||||
const schemaResult = validateConfig(config, baseAppSchema);
|
||||
console.log(formatValidationResult(schemaResult));
|
||||
console.log();
|
||||
|
||||
// Environment variables
|
||||
console.log('2. Required Environment Variables:');
|
||||
const envResult = checkRequiredEnvVars(REQUIRED_ENV_VARS);
|
||||
console.log(formatValidationResult(envResult));
|
||||
console.log();
|
||||
|
||||
// Required paths
|
||||
console.log('3. Required Configuration Paths:');
|
||||
const pathResult = validateCompleteness(config, REQUIRED_PATHS);
|
||||
console.log(formatValidationResult(pathResult));
|
||||
console.log();
|
||||
|
||||
// Overall result
|
||||
const allValid = schemaResult.valid && envResult.valid && pathResult.valid;
|
||||
|
||||
if (allValid) {
|
||||
console.log('✅ All configuration checks passed!');
|
||||
process.exit(0);
|
||||
} else {
|
||||
console.log('❌ Some configuration checks failed');
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
if (!values.validate && !values.show && !values.check) {
|
||||
console.log('No action specified. Use --help for usage information.');
|
||||
process.exit(1);
|
||||
}
|
||||
} catch (error) {
|
||||
if (values.json) {
|
||||
console.error(JSON.stringify({ error: String(error) }));
|
||||
} else {
|
||||
console.error('Error:', error);
|
||||
}
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
// Run CLI
|
||||
if (import.meta.main) {
|
||||
main();
|
||||
}
|
||||
|
|
@ -1,9 +1,9 @@
|
|||
import { join } from 'path';
|
||||
import { z } from 'zod';
|
||||
import { getLogger } from '@stock-bot/logger';
|
||||
import { ConfigError, ConfigValidationError } from './errors';
|
||||
import { EnvLoader } from './loaders/env.loader';
|
||||
import { FileLoader } from './loaders/file.loader';
|
||||
import { ConfigError, ConfigValidationError } from './errors';
|
||||
import type {
|
||||
ConfigLoader,
|
||||
ConfigManagerOptions,
|
||||
|
|
@ -21,8 +21,9 @@ export class ConfigManager<T = Record<string, unknown>> {
|
|||
private environment: Environment;
|
||||
private schema?: ConfigSchema;
|
||||
|
||||
constructor(options: ConfigManagerOptions = {}) {
|
||||
constructor(options: ConfigManagerOptions = {}, defaultSchema?: ConfigSchema) {
|
||||
this.environment = options.environment || this.detectEnvironment();
|
||||
this.schema = defaultSchema;
|
||||
|
||||
if (options.loaders) {
|
||||
this.loaders = options.loaders;
|
||||
|
|
@ -32,20 +33,17 @@ export class ConfigManager<T = Record<string, unknown>> {
|
|||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize the configuration by loading from all sources
|
||||
*/
|
||||
initialize(schema?: ConfigSchema): T {
|
||||
if (this.config) {
|
||||
return this.config;
|
||||
}
|
||||
|
||||
this.schema = schema;
|
||||
if (schema) {
|
||||
this.schema = schema;
|
||||
}
|
||||
|
||||
// Sort loaders by priority (higher priority last)
|
||||
const sortedLoaders = [...this.loaders].sort((a, b) => a.priority - b.priority);
|
||||
|
||||
// Load configurations from all sources
|
||||
const configs: Record<string, unknown>[] = [];
|
||||
for (const loader of sortedLoaders) {
|
||||
const config = loader.load();
|
||||
|
|
@ -54,10 +52,8 @@ export class ConfigManager<T = Record<string, unknown>> {
|
|||
}
|
||||
}
|
||||
|
||||
// Merge all configurations
|
||||
const mergedConfig = this.merge(...configs) as T;
|
||||
|
||||
// Add environment if not present
|
||||
if (
|
||||
typeof mergedConfig === 'object' &&
|
||||
mergedConfig !== null &&
|
||||
|
|
@ -66,7 +62,6 @@ export class ConfigManager<T = Record<string, unknown>> {
|
|||
(mergedConfig as Record<string, unknown>)['environment'] = this.environment;
|
||||
}
|
||||
|
||||
// Validate if schema provided
|
||||
if (this.schema) {
|
||||
try {
|
||||
this.config = this.schema.parse(mergedConfig) as T;
|
||||
|
|
@ -90,9 +85,6 @@ export class ConfigManager<T = Record<string, unknown>> {
|
|||
return this.config;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the current configuration
|
||||
*/
|
||||
get(): T {
|
||||
if (!this.config) {
|
||||
throw new ConfigError('Configuration not initialized. Call initialize() first.');
|
||||
|
|
@ -100,9 +92,6 @@ export class ConfigManager<T = Record<string, unknown>> {
|
|||
return this.config;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a specific configuration value by path
|
||||
*/
|
||||
getValue<R = unknown>(path: string): R {
|
||||
const config = this.get();
|
||||
const keys = path.split('.');
|
||||
|
|
@ -119,9 +108,6 @@ export class ConfigManager<T = Record<string, unknown>> {
|
|||
return value as R;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a configuration path exists
|
||||
*/
|
||||
has(path: string): boolean {
|
||||
try {
|
||||
this.getValue(path);
|
||||
|
|
@ -131,9 +117,6 @@ export class ConfigManager<T = Record<string, unknown>> {
|
|||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update configuration at runtime
|
||||
*/
|
||||
set(updates: DeepPartial<T>): void {
|
||||
if (!this.config) {
|
||||
throw new ConfigError('Configuration not initialized. Call initialize() first.');
|
||||
|
|
@ -161,23 +144,14 @@ export class ConfigManager<T = Record<string, unknown>> {
|
|||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the current environment
|
||||
*/
|
||||
getEnvironment(): Environment {
|
||||
return this.environment;
|
||||
}
|
||||
|
||||
/**
|
||||
* Reset configuration
|
||||
*/
|
||||
reset(): void {
|
||||
this.config = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate configuration against a schema
|
||||
*/
|
||||
validate<S extends ConfigSchema>(schema: S): z.infer<S> {
|
||||
const config = this.get();
|
||||
return schema.parse(config);
|
||||
|
|
@ -201,11 +175,12 @@ export class ConfigManager<T = Record<string, unknown>> {
|
|||
}
|
||||
|
||||
/**
|
||||
* Deep merge with circular reference handling
|
||||
* Deep merge tracking only active ancestor objects so valid shared DAG references
|
||||
* (e.g. redis = database.dragonfly) are preserved rather than replaced with '[Circular]'.
|
||||
*/
|
||||
private merge(...objects: Record<string, unknown>[]): Record<string, unknown> {
|
||||
const seen = new WeakSet();
|
||||
|
||||
const ancestors = new WeakSet<object>();
|
||||
|
||||
const mergeRecursive = (...objs: Record<string, unknown>[]): Record<string, unknown> => {
|
||||
const result: Record<string, unknown> = {};
|
||||
|
||||
|
|
@ -219,17 +194,21 @@ export class ConfigManager<T = Record<string, unknown>> {
|
|||
!(value instanceof Date) &&
|
||||
!(value instanceof RegExp)
|
||||
) {
|
||||
// Check for circular reference
|
||||
if (seen.has(value)) {
|
||||
if (ancestors.has(value)) {
|
||||
result[key] = '[Circular]';
|
||||
continue;
|
||||
}
|
||||
seen.add(value);
|
||||
|
||||
result[key] = mergeRecursive(
|
||||
(result[key] as Record<string, unknown>) || {},
|
||||
value as Record<string, unknown>
|
||||
);
|
||||
ancestors.add(value);
|
||||
try {
|
||||
result[key] = mergeRecursive(
|
||||
(result[key] && typeof result[key] === 'object' && !Array.isArray(result[key])
|
||||
? (result[key] as Record<string, unknown>)
|
||||
: {}),
|
||||
value as Record<string, unknown>
|
||||
);
|
||||
} finally {
|
||||
ancestors.delete(value);
|
||||
}
|
||||
} else {
|
||||
result[key] = value;
|
||||
}
|
||||
|
|
@ -238,7 +217,7 @@ export class ConfigManager<T = Record<string, unknown>> {
|
|||
|
||||
return result;
|
||||
};
|
||||
|
||||
|
||||
return mergeRecursive(...objects);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,14 +1,10 @@
|
|||
import { ConfigManager, type ConfigManagerOptions } from './config-manager';
|
||||
import type { ConfigSchema } from './types';
|
||||
|
||||
// Export only what's actually used
|
||||
export { ConfigManager } from './config-manager';
|
||||
export type { ConfigManagerOptions } from './config-manager';
|
||||
export { toUnifiedConfig } from './schemas/unified-app.schema';
|
||||
|
||||
// Export used types
|
||||
export type { BaseAppConfig, UnifiedAppConfig } from './schemas';
|
||||
|
||||
// Export schemas that are used by apps
|
||||
export {
|
||||
baseAppSchema,
|
||||
dragonflyConfigSchema,
|
||||
|
|
@ -24,33 +20,13 @@ export {
|
|||
type ProviderName,
|
||||
} from './schemas';
|
||||
|
||||
// createAppConfig function for apps/stock
|
||||
export function createAppConfig<T>(
|
||||
schema: unknown,
|
||||
options?: ConfigManagerOptions
|
||||
): ConfigManager<T> {
|
||||
return new ConfigManager<T>(options);
|
||||
const zodSchema =
|
||||
schema && typeof schema === 'object' && 'parse' in schema
|
||||
? (schema as ConfigSchema)
|
||||
: undefined;
|
||||
return new ConfigManager<T>(options, zodSchema);
|
||||
}
|
||||
|
||||
// Export utilities
|
||||
export {
|
||||
SecretValue,
|
||||
secret,
|
||||
isSecret,
|
||||
isSecretEnvVar,
|
||||
COMMON_SECRET_PATTERNS,
|
||||
redactSecrets,
|
||||
wrapSecretEnvVars,
|
||||
secretSchema,
|
||||
secretStringSchema
|
||||
} from './utils/secrets';
|
||||
|
||||
export {
|
||||
checkRequiredEnvVars,
|
||||
createStrictSchema,
|
||||
formatValidationResult,
|
||||
mergeSchemas,
|
||||
validateConfig,
|
||||
validateCompleteness,
|
||||
type ValidationResult
|
||||
} from './utils/validation';
|
||||
|
|
|
|||
|
|
@ -10,7 +10,7 @@ interface EnvLoaderOptions {
|
|||
}
|
||||
|
||||
export class EnvLoader implements ConfigLoader {
|
||||
readonly priority = 100; // Highest priority
|
||||
readonly priority = 100;
|
||||
|
||||
constructor(
|
||||
private prefix = '',
|
||||
|
|
@ -27,10 +27,12 @@ export class EnvLoader implements ConfigLoader {
|
|||
|
||||
load(): Record<string, unknown> {
|
||||
try {
|
||||
// Load root .env file - try multiple possible locations
|
||||
// Stop on the first .env file found so repo-root runs never traverse into parent directories
|
||||
const possiblePaths = ['./.env', '../.env', '../../.env', '../../../.env'];
|
||||
for (const path of possiblePaths) {
|
||||
this.loadEnvFile(path);
|
||||
if (this.loadEnvFile(path)) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
const config: Record<string, unknown> = {};
|
||||
|
|
@ -44,10 +46,8 @@ export class EnvLoader implements ConfigLoader {
|
|||
const configKey = this.prefix ? key.slice(this.prefix.length) : key;
|
||||
|
||||
if (!this.options.convertCase && !this.options.nestedDelimiter) {
|
||||
// Simple case - just keep the key as is
|
||||
config[configKey] = this.parseValue(value || '');
|
||||
} else {
|
||||
// Handle nested structure or case conversion
|
||||
this.setConfigValue(config, configKey, value || '');
|
||||
}
|
||||
}
|
||||
|
|
@ -60,22 +60,19 @@ export class EnvLoader implements ConfigLoader {
|
|||
|
||||
private setConfigValue(config: Record<string, unknown>, key: string, value: string): void {
|
||||
try {
|
||||
// Handle provider-specific environment variables (only for application usage, not tests)
|
||||
if (!this.prefix && !this.options.convertCase) {
|
||||
const providerMapping = this.getProviderMapping(key);
|
||||
if (providerMapping) {
|
||||
// For certain fields, we need to preserve the string value
|
||||
const shouldPreserveString = this.shouldPreserveStringForKey(key);
|
||||
const parsedValue = shouldPreserveString ? value : this.parseValue(value);
|
||||
this.setNestedValue(config, providerMapping.path, parsedValue);
|
||||
this.setNestedValue(config, [...providerMapping.path], parsedValue);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const parsedValue = this.parseValue(value);
|
||||
const parsedValue = this.shouldPreserveStringForKey(key) ? value : this.parseValue(value);
|
||||
|
||||
if (this.options.convertCase) {
|
||||
// Convert to camelCase
|
||||
const camelKey = this.toCamelCase(key);
|
||||
config[camelKey] = parsedValue;
|
||||
} else if (
|
||||
|
|
@ -83,32 +80,26 @@ export class EnvLoader implements ConfigLoader {
|
|||
this.options.nestedDelimiter !== '_' &&
|
||||
key.includes(this.options.nestedDelimiter)
|
||||
) {
|
||||
// Handle nested delimiter (e.g., APP__NAME -> { APP: { NAME: value } })
|
||||
const parts = key.split(this.options.nestedDelimiter);
|
||||
this.setNestedValue(config, parts, parsedValue);
|
||||
} else if (key.includes('_')) {
|
||||
const path = key.toLowerCase().split('_');
|
||||
this.setNestedValue(config, path, parsedValue);
|
||||
} else {
|
||||
// Convert to nested structure based on underscores, or keep as-is if no underscores
|
||||
if (key.includes('_')) {
|
||||
const path = key.toLowerCase().split('_');
|
||||
this.setNestedValue(config, path, parsedValue);
|
||||
} else {
|
||||
// Single key without underscores - keep original case
|
||||
config[key] = parsedValue;
|
||||
}
|
||||
config[key] = parsedValue;
|
||||
}
|
||||
} catch {
|
||||
// Skip environment variables that can't be set (readonly properties)
|
||||
// This is expected behavior for system environment variables
|
||||
// Skip environment variables that cannot be set on readonly target keys
|
||||
}
|
||||
}
|
||||
|
||||
private setNestedValue(obj: Record<string, unknown>, path: string[], value: unknown): boolean {
|
||||
if (path.length === 0) {
|
||||
return false; // Cannot set value on empty path
|
||||
return false;
|
||||
}
|
||||
const lastKey = path.pop();
|
||||
if (!lastKey) {
|
||||
return false; // This should never happen due to length check above
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
|
|
@ -122,7 +113,6 @@ export class EnvLoader implements ConfigLoader {
|
|||
(target as Record<string, unknown>)[lastKey] = value;
|
||||
return true;
|
||||
} catch {
|
||||
// If we can't assign to any property (readonly), skip this env var silently
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
|
@ -132,22 +122,19 @@ export class EnvLoader implements ConfigLoader {
|
|||
}
|
||||
|
||||
private shouldPreserveStringForKey(key: string): boolean {
|
||||
// Keys that should preserve string values even if they look like numbers
|
||||
const preserveStringKeys = [
|
||||
'QM_WEBMASTER_ID',
|
||||
'IB_MARKET_DATA_TYPE',
|
||||
'MONGODB_URI',
|
||||
'MONGODB_READ_URI',
|
||||
'MONGODB_PASSWORD',
|
||||
'POSTGRES_PASSWORD',
|
||||
'DRAGONFLY_PASSWORD',
|
||||
'QUESTDB_PASSWORD',
|
||||
];
|
||||
return preserveStringKeys.includes(key);
|
||||
if (preserveStringKeys.includes(key)) {
|
||||
return true;
|
||||
}
|
||||
return /(?:^|_)(?:PASSWORD|SECRET|TOKEN|API_KEY|URI)$/i.test(key);
|
||||
}
|
||||
|
||||
private getProviderMapping(envKey: string): { path: string[] } | null {
|
||||
// Provider-specific and special environment variable mappings
|
||||
const providerMappings: Record<string, string[]> = {
|
||||
// Database mappings
|
||||
MONGODB_URI: ['database', 'mongodb', 'uri'],
|
||||
|
|
@ -167,8 +154,25 @@ export class EnvLoader implements ConfigLoader {
|
|||
DRAGONFLY_HOST: ['database', 'dragonfly', 'host'],
|
||||
DRAGONFLY_PORT: ['database', 'dragonfly', 'port'],
|
||||
DRAGONFLY_PASSWORD: ['database', 'dragonfly', 'password'],
|
||||
QUESTDB_ENABLED: ['database', 'questdb', 'enabled'],
|
||||
QUESTDB_HOST: ['database', 'questdb', 'host'],
|
||||
QUESTDB_PORT: ['database', 'questdb', 'httpPort'],
|
||||
QUESTDB_HTTP_PORT: ['database', 'questdb', 'httpPort'],
|
||||
QUESTDB_PG_PORT: ['database', 'questdb', 'pgPort'],
|
||||
QUESTDB_ILP_PORT: ['database', 'questdb', 'ilpPort'],
|
||||
QUESTDB_INFLUX_PORT: ['database', 'questdb', 'influxPort'],
|
||||
QUESTDB_USER: ['database', 'questdb', 'user'],
|
||||
QUESTDB_PASSWORD: ['database', 'questdb', 'password'],
|
||||
|
||||
// Queue mappings
|
||||
QUEUE_ENABLED: ['queue', 'enabled'],
|
||||
QUEUE_ENABLE_SCHEDULED_JOBS: ['queue', 'enableScheduledJobs'],
|
||||
QUEUE_WORKERS: ['queue', 'workers'],
|
||||
QUEUE_CONCURRENCY: ['queue', 'concurrency'],
|
||||
QUEUE_REDIS_HOST: ['queue', 'redis', 'host'],
|
||||
QUEUE_REDIS_PORT: ['queue', 'redis', 'port'],
|
||||
QUEUE_REDIS_PASSWORD: ['queue', 'redis', 'password'],
|
||||
QUEUE_REDIS_DB: ['queue', 'redis', 'db'],
|
||||
|
||||
// WebShare provider mappings
|
||||
WEBSHARE_API_KEY: ['webshare', 'apiKey'],
|
||||
|
|
@ -210,7 +214,7 @@ export class EnvLoader implements ConfigLoader {
|
|||
NAME: ['name'],
|
||||
VERSION: ['version'],
|
||||
|
||||
// Log mappings (using LOG_ prefix for all)
|
||||
// Log mappings
|
||||
LOG_LEVEL: ['log', 'level'],
|
||||
LOG_FORMAT: ['log', 'format'],
|
||||
LOG_HIDE_OBJECT: ['log', 'hideObject'],
|
||||
|
|
@ -218,7 +222,6 @@ export class EnvLoader implements ConfigLoader {
|
|||
LOG_LOKI_HOST: ['log', 'loki', 'host'],
|
||||
LOG_LOKI_PORT: ['log', 'loki', 'port'],
|
||||
|
||||
// Special mappings to avoid conflicts
|
||||
DEBUG_MODE: ['debug'],
|
||||
};
|
||||
|
||||
|
|
@ -231,12 +234,11 @@ export class EnvLoader implements ConfigLoader {
|
|||
return value;
|
||||
}
|
||||
|
||||
// Try to parse as JSON first if enabled
|
||||
if (this.options.parseJson) {
|
||||
try {
|
||||
return JSON.parse(value);
|
||||
} catch {
|
||||
// Not JSON, continue with other parsing
|
||||
// Not JSON, continue
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -244,7 +246,6 @@ export class EnvLoader implements ConfigLoader {
|
|||
return value;
|
||||
}
|
||||
|
||||
// Handle booleans
|
||||
if (value.toLowerCase() === 'true') {
|
||||
return true;
|
||||
}
|
||||
|
|
@ -252,7 +253,6 @@ export class EnvLoader implements ConfigLoader {
|
|||
return false;
|
||||
}
|
||||
|
||||
// Handle numbers (but preserve strings with leading zeros or plus signs)
|
||||
if (!/^[+-]/.test(value) && !/^0\d/.test(value)) {
|
||||
const num = Number(value);
|
||||
if (!isNaN(num) && value !== '') {
|
||||
|
|
@ -260,7 +260,6 @@ export class EnvLoader implements ConfigLoader {
|
|||
}
|
||||
}
|
||||
|
||||
// Handle null/undefined
|
||||
if (value.toLowerCase() === 'null') {
|
||||
return null;
|
||||
}
|
||||
|
|
@ -268,11 +267,10 @@ export class EnvLoader implements ConfigLoader {
|
|||
return undefined;
|
||||
}
|
||||
|
||||
// Return as string
|
||||
return value;
|
||||
}
|
||||
|
||||
private loadEnvFile(filePath: string): void {
|
||||
private loadEnvFile(filePath: string): boolean {
|
||||
try {
|
||||
const envContent = readFileSync(filePath, 'utf-8');
|
||||
const lines = envContent.split('\n');
|
||||
|
|
@ -280,18 +278,20 @@ export class EnvLoader implements ConfigLoader {
|
|||
for (const line of lines) {
|
||||
const trimmed = line.trim();
|
||||
if (!trimmed || trimmed.startsWith('#')) {
|
||||
continue; // Skip empty lines and comments
|
||||
continue;
|
||||
}
|
||||
|
||||
const equalIndex = trimmed.indexOf('=');
|
||||
if (equalIndex === -1) {
|
||||
continue; // Skip lines without =
|
||||
continue;
|
||||
}
|
||||
|
||||
const key = trimmed.substring(0, equalIndex).trim();
|
||||
if (!key) {
|
||||
continue;
|
||||
}
|
||||
let value = trimmed.substring(equalIndex + 1).trim();
|
||||
|
||||
// Remove surrounding quotes if present
|
||||
if (
|
||||
(value.startsWith('"') && value.endsWith('"')) ||
|
||||
(value.startsWith("'") && value.endsWith("'"))
|
||||
|
|
@ -299,13 +299,12 @@ export class EnvLoader implements ConfigLoader {
|
|||
value = value.slice(1, -1);
|
||||
}
|
||||
|
||||
// Only set if not already set (allows override precedence)
|
||||
if (!(key in process.env)) {
|
||||
process.env[key] = value;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
} catch (error: unknown) {
|
||||
// File not found is not an error (env files are optional)
|
||||
if (error && typeof error === 'object' && 'code' in error && error.code !== 'ENOENT') {
|
||||
// eslint-disable-next-line no-console
|
||||
console.warn(
|
||||
|
|
@ -313,6 +312,7 @@ export class EnvLoader implements ConfigLoader {
|
|||
error instanceof Error ? error.message : String(error)
|
||||
);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,178 +0,0 @@
|
|||
import { z } from 'zod';
|
||||
|
||||
/**
|
||||
* Secret value wrapper to prevent accidental logging
|
||||
*/
|
||||
export class SecretValue<T = string> {
|
||||
private readonly value: T;
|
||||
private readonly masked: string;
|
||||
|
||||
constructor(value: T, mask: string = '***') {
|
||||
this.value = value;
|
||||
this.masked = mask;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the actual secret value
|
||||
* @param reason - Required reason for accessing the secret
|
||||
*/
|
||||
reveal(reason: string): T {
|
||||
if (!reason) {
|
||||
throw new Error('Reason required for revealing secret value');
|
||||
}
|
||||
return this.value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get masked representation
|
||||
*/
|
||||
toString(): string {
|
||||
return this.masked;
|
||||
}
|
||||
|
||||
/**
|
||||
* Prevent JSON serialization of actual value
|
||||
*/
|
||||
toJSON(): string {
|
||||
return this.masked;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if value matches without revealing it
|
||||
*/
|
||||
equals(other: T): boolean {
|
||||
return this.value === other;
|
||||
}
|
||||
|
||||
/**
|
||||
* Transform the secret value
|
||||
*/
|
||||
map<R>(fn: (value: T) => R, reason: string): SecretValue<R> {
|
||||
return new SecretValue(fn(this.reveal(reason)));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Zod schema for secret values
|
||||
*/
|
||||
export const secretSchema = <T extends z.ZodTypeAny>(_schema: T) => {
|
||||
return z.custom<SecretValue<z.infer<T>>>(val => val instanceof SecretValue, {
|
||||
message: 'Expected SecretValue instance',
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Transform string to SecretValue in Zod schema
|
||||
*/
|
||||
export const secretStringSchema = z.string().transform(val => new SecretValue(val));
|
||||
|
||||
/**
|
||||
* Create a secret value
|
||||
*/
|
||||
export function secret<T = string>(value: T, mask?: string): SecretValue<T> {
|
||||
return new SecretValue(value, mask);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a value is a secret
|
||||
*/
|
||||
export function isSecret(value: unknown): value is SecretValue {
|
||||
return value instanceof SecretValue;
|
||||
}
|
||||
|
||||
/**
|
||||
* Redact secrets from an object
|
||||
*/
|
||||
export function redactSecrets<T extends Record<string, unknown>>(
|
||||
obj: T,
|
||||
secretPaths: string[] = []
|
||||
): T {
|
||||
const result = redactSecretValues(obj) as T;
|
||||
|
||||
// Redact known secret paths
|
||||
for (const path of secretPaths) {
|
||||
const keys = path.split('.');
|
||||
let current: Record<string, unknown> = result;
|
||||
|
||||
for (let i = 0; i < keys.length - 1; i++) {
|
||||
const key = keys[i];
|
||||
if (key && current[key] && typeof current[key] === 'object') {
|
||||
current = current[key] as Record<string, unknown>;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
const lastKey = keys[keys.length - 1];
|
||||
if (current && lastKey && lastKey in current) {
|
||||
current[lastKey] = '***REDACTED***';
|
||||
}
|
||||
}
|
||||
|
||||
// Recursively redact SecretValue instances
|
||||
function redactSecretValues(obj: unknown): unknown {
|
||||
if (obj === null || obj === undefined) {
|
||||
return obj;
|
||||
}
|
||||
|
||||
if (isSecret(obj)) {
|
||||
return obj.toString();
|
||||
}
|
||||
|
||||
if (Array.isArray(obj)) {
|
||||
return obj.map(redactSecretValues);
|
||||
}
|
||||
|
||||
if (typeof obj === 'object') {
|
||||
const result: Record<string, unknown> = {};
|
||||
for (const [key, value] of Object.entries(obj)) {
|
||||
result[key] = redactSecretValues(value);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
return obj;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Environment variable names that should be treated as secrets
|
||||
*/
|
||||
export const COMMON_SECRET_PATTERNS = [
|
||||
/password/i,
|
||||
/secret/i,
|
||||
/key/i,
|
||||
/token/i,
|
||||
/credential/i,
|
||||
/private/i,
|
||||
/auth/i,
|
||||
/api[-_]?key/i,
|
||||
];
|
||||
|
||||
/**
|
||||
* Check if an environment variable name indicates a secret
|
||||
*/
|
||||
export function isSecretEnvVar(name: string): boolean {
|
||||
return COMMON_SECRET_PATTERNS.some(pattern => pattern.test(name));
|
||||
}
|
||||
|
||||
/**
|
||||
* Wrap environment variables that look like secrets
|
||||
*/
|
||||
export function wrapSecretEnvVars(
|
||||
env: Record<string, string | undefined>
|
||||
): Record<string, string | SecretValue | undefined> {
|
||||
const result: Record<string, string | SecretValue | undefined> = {};
|
||||
|
||||
for (const [key, value] of Object.entries(env)) {
|
||||
if (value !== undefined && isSecretEnvVar(key)) {
|
||||
result[key] = new SecretValue(value, `***${key}***`);
|
||||
} else {
|
||||
result[key] = value;
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
|
@ -1,155 +0,0 @@
|
|||
import { z } from 'zod';
|
||||
import { defined } from '@stock-bot/invariants';
|
||||
|
||||
export interface ValidationResult {
|
||||
valid: boolean;
|
||||
errors?: Array<{
|
||||
path: string;
|
||||
message: string;
|
||||
expected?: string;
|
||||
received?: string;
|
||||
}>;
|
||||
warnings?: Array<{
|
||||
path: string;
|
||||
message: string;
|
||||
}>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate configuration against a schema
|
||||
*/
|
||||
export function validateConfig<T>(config: unknown, schema: z.ZodSchema<T>): ValidationResult {
|
||||
try {
|
||||
schema.parse(config);
|
||||
return { valid: true };
|
||||
} catch (error) {
|
||||
if (error instanceof z.ZodError) {
|
||||
const errors = error.errors.map(err => ({
|
||||
path: err.path.join('.'),
|
||||
message: err.message,
|
||||
expected: 'expected' in err ? String(err.expected) : undefined,
|
||||
received: 'received' in err ? String(err.received) : undefined,
|
||||
}));
|
||||
|
||||
return { valid: false, errors };
|
||||
}
|
||||
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check for required environment variables
|
||||
*/
|
||||
export function checkRequiredEnvVars(required: string[]): ValidationResult {
|
||||
const errors: ValidationResult['errors'] = [];
|
||||
|
||||
for (const envVar of required) {
|
||||
if (!process.env[envVar]) {
|
||||
errors.push({
|
||||
path: `env.${envVar}`,
|
||||
message: `Required environment variable ${envVar} is not set`,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
valid: errors.length === 0,
|
||||
errors: errors.length > 0 ? errors : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate configuration completeness
|
||||
*/
|
||||
export function validateCompleteness(
|
||||
config: Record<string, unknown>,
|
||||
required: string[]
|
||||
): ValidationResult {
|
||||
const errors: ValidationResult['errors'] = [];
|
||||
|
||||
for (const path of required) {
|
||||
const keys = path.split('.');
|
||||
let current: unknown = config;
|
||||
let found = true;
|
||||
|
||||
for (const key of keys) {
|
||||
if (current && typeof current === 'object' && key in current) {
|
||||
current = (current as Record<string, unknown>)[key];
|
||||
} else {
|
||||
found = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!found || current === undefined || current === null) {
|
||||
errors.push({
|
||||
path,
|
||||
message: `Required configuration value is missing`,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
valid: errors.length === 0,
|
||||
errors: errors.length > 0 ? errors : undefined,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Format validation result for display
|
||||
*/
|
||||
export function formatValidationResult(result: ValidationResult): string {
|
||||
const lines: string[] = [];
|
||||
|
||||
if (result.valid) {
|
||||
lines.push('✅ Configuration is valid');
|
||||
} else {
|
||||
lines.push('❌ Configuration validation failed');
|
||||
}
|
||||
|
||||
if (result.errors && result.errors.length > 0) {
|
||||
lines.push('\nErrors:');
|
||||
for (const error of result.errors) {
|
||||
lines.push(` - ${error.path}: ${error.message}`);
|
||||
if (error.expected && error.received) {
|
||||
lines.push(` Expected: ${error.expected}, Received: ${error.received}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (result.warnings && result.warnings.length > 0) {
|
||||
lines.push('\nWarnings:');
|
||||
for (const warning of result.warnings) {
|
||||
lines.push(` - ${warning.path}: ${warning.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a strict schema that doesn't allow extra properties
|
||||
*/
|
||||
export function createStrictSchema<T extends z.ZodRawShape>(shape: T): z.ZodObject<T, 'strict'> {
|
||||
return z.object(shape).strict();
|
||||
}
|
||||
|
||||
/**
|
||||
* Merge multiple schemas
|
||||
*/
|
||||
export function mergeSchemas<T extends z.ZodSchema[]>(
|
||||
...schemas: T
|
||||
): z.ZodIntersection<T[0], T[1]> {
|
||||
if (schemas.length < 2) {
|
||||
throw new Error('At least two schemas required for merge');
|
||||
}
|
||||
|
||||
let result: z.ZodTypeAny = defined(schemas[0]).and(defined(schemas[1]));
|
||||
|
||||
for (let i = 2; i < schemas.length; i++) {
|
||||
result = result.and(defined(schemas[i]));
|
||||
}
|
||||
|
||||
return result as z.ZodIntersection<T[0], T[1]>;
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue