import { describe, expect, test } from "vitest"; import { ApiConfigError, loadApiConfig, loadRequiredApiConfig } from "./index.js"; const REQUIRED_PRODUCTION_ENV = { APP_NAME: "Production API", DATABASE_URL: "postgres://example.invalid/app", APP_BASE_DOMAIN: "example.com", WEB_APP_HOST: "app.example.com", ADMIN_APP_HOST: "admin.example.com", API_HOST: "api.example.com", SESSION_SECRET: "session-secret-value", CRYPTO_SECRET: "crypto-secret-value", API_ACCESS_TOKEN: "api-access-token-value", JWT_SECRET: "jwt-secret-value", ANALYTICS_TOKEN: "analytics-token-value", }; describe("loadRequiredApiConfig", () => { test("returns production API config when required values are valid", () => { const config = loadRequiredApiConfig( { ...REQUIRED_PRODUCTION_ENV, API_PORT: "8081", APP_PROTOCOL: "https", }, { nodeEnv: "production" } ); expect(config).toMatchObject({ appName: "Production API", nodeEnv: "production", listen: { port: 8081 }, routing: { appBaseDomain: "example.com", apiHost: "api.example.com", protocol: "https", }, apiAccessToken: "api-access-token-value", jwtSecret: "jwt-secret-value", }); }); test("throws redacted ApiConfigError for missing required API_ACCESS_TOKEN", () => { const secretValues = ["session-secret-value", "crypto-secret-value", "jwt-secret-value", "analytics-token-value"]; expect(() => loadRequiredApiConfig( { ...REQUIRED_PRODUCTION_ENV, API_ACCESS_TOKEN: undefined, }, { nodeEnv: "production" } ) ).toThrow(ApiConfigError); try { loadRequiredApiConfig( { ...REQUIRED_PRODUCTION_ENV, API_ACCESS_TOKEN: undefined, }, { nodeEnv: "production" } ); } catch (error) { expect(error).toBeInstanceOf(ApiConfigError); const apiConfigError = error as ApiConfigError; expect(apiConfigError.message).toBe("Invalid API configuration (API_ACCESS_TOKEN:missing-required)."); expect(apiConfigError.diagnostics).toContainEqual( expect.objectContaining({ code: "missing-required", name: "API_ACCESS_TOKEN", classification: "required-per-app", }) ); const errorText = JSON.stringify({ message: apiConfigError.message, details: apiConfigError.details }); for (const secretValue of secretValues) { expect(errorText).not.toContain(secretValue); } } }); test("throws redacted ApiConfigError for invalid API_PORT", () => { const invalidPort = "secret-like-invalid-port-value"; const secretValues = ["session-secret-value", "crypto-secret-value", "api-access-token-value", "jwt-secret-value", "analytics-token-value"]; try { loadRequiredApiConfig( { ...REQUIRED_PRODUCTION_ENV, API_PORT: invalidPort, }, { nodeEnv: "production" } ); } catch (error) { expect(error).toBeInstanceOf(ApiConfigError); const apiConfigError = error as ApiConfigError; expect(apiConfigError.message).toBe("Invalid API configuration (API_PORT:invalid-port)."); expect(apiConfigError.details.diagnostics).toEqual([ expect.objectContaining({ code: "invalid-port", name: "API_PORT", }), ]); const errorText = JSON.stringify({ message: apiConfigError.message, details: apiConfigError.details }); expect(errorText).not.toContain(invalidPort); for (const secretValue of secretValues) { expect(errorText).not.toContain(secretValue); } } }); test("preserves default development failure behavior by throwing diagnostics", () => { expect(() => loadRequiredApiConfig({})).toThrow(ApiConfigError); }); }); describe("loadApiConfig", () => { test("returns local defaults and API listen defaults", () => { const result = loadApiConfig({}); expect(result.ok).toBe(false); expect(result.config).toMatchObject({ appName: "HiveGrid", nodeEnv: "development", listen: { port: 3001, }, routing: { appBaseDomain: "localhost", webAppHost: "app.localhost", adminAppHost: "admin.localhost", apiHost: "api.localhost", protocol: "http", }, origins: {}, analytics: {}, mailjet: {}, storage: {}, }); }); test("reports missing production requirements including analytics token with redacted diagnostics", () => { const result = loadApiConfig( { ...REQUIRED_PRODUCTION_ENV, API_ACCESS_TOKEN: undefined, ANALYTICS_TOKEN: undefined, }, { nodeEnv: "production" } ); expect(result.ok).toBe(false); expect(result.diagnostics).toEqual( expect.arrayContaining([ expect.objectContaining({ code: "missing-required", name: "API_ACCESS_TOKEN", classification: "required-per-app" }), expect.objectContaining({ code: "missing-required", name: "ANALYTICS_TOKEN", classification: "required-per-app" }), ]) ); expect(JSON.stringify(result.diagnostics)).not.toContain("api-access-token-value"); expect(JSON.stringify(result.diagnostics)).not.toContain("analytics-token-value"); }); test("prefers API_PORT over PORT and falls back to PORT when API_PORT is empty", () => { expect(loadApiConfig({ API_PORT: "4001", PORT: "4000" }).config.listen.port).toBe(4001); expect(loadApiConfig({ API_PORT: " ", PORT: "4000" }).config.listen.port).toBe(4000); expect(loadApiConfig({ PORT: "4000" }).config.listen.port).toBe(4000); }); test("falls back for invalid API_PORT without leaking configured secrets", () => { const secretValues = ["api-access-token-value", "jwt-secret-value", "analytics-token-value"]; const result = loadApiConfig({ API_ACCESS_TOKEN: secretValues[0], JWT_SECRET: secretValues[1], ANALYTICS_TOKEN: secretValues[2], API_PORT: "not-a-port", PORT: "4000", }); expect(result.ok).toBe(false); expect(result.config.listen.port).toBe(3001); expect(result.diagnostics).toContainEqual( expect.objectContaining({ code: "invalid-port", name: "API_PORT", }) ); const diagnosticText = JSON.stringify(result.diagnostics); for (const secretValue of secretValues) { expect(diagnosticText).not.toContain(secretValue); } }); test("normalizes provider values and trims empty strings to undefined", () => { const result = loadApiConfig({ ...REQUIRED_PRODUCTION_ENV, NODE_ENV: "production", API_PORT: "8081", APP_PROTOCOL: "https", WEB_ORIGIN: " ", ADMIN_ORIGIN: "\t", API_ACCESS_TOKEN: " api-access-token-value ", JWT_SECRET: " jwt-secret-value ", ANALYTICS_TOKEN: " analytics-token-value ", MAILJET_WEBHOOK_SECRET: " mailjet-webhook-secret-value ", LAGO_API_URL: " http://lago.internal:3000 ", LAGO_API_KEY: " lago-api-key-value ", LAGO_WEBHOOK_SECRET: " lago-webhook-secret-value ", LAGO_TIMEOUT_MS: " 5000 ", MOLLIE_API_KEY: " mollie-api-key-value ", MOLLIE_PROFILE_ID: " mollie-profile-id-value ", MOLLIE_TIMEOUT_MS: " 6000 ", STORAGE_ENDPOINT: " https://storage.example.com ", STORAGE_REGION: " us-east-1 ", STORAGE_BUCKET: " uploads ", STORAGE_ACCESS_KEY_ID: " storage-access-key-id-value ", STORAGE_SECRET_ACCESS_KEY: " storage-secret-access-key-value ", STORAGE_SESSION_TOKEN: " storage-session-token-value ", STORAGE_PUBLIC_BASE_URL: " https://cdn.example.com/files ", STORAGE_FORCE_PATH_STYLE: " true ", }); expect(result.ok).toBe(true); expect(result.diagnostics).toEqual([]); expect(result.config).toMatchObject({ appName: "Production API", nodeEnv: "production", listen: { port: 8081 }, routing: { appBaseDomain: "example.com", webAppHost: "app.example.com", adminAppHost: "admin.example.com", apiHost: "api.example.com", protocol: "https", }, origins: {}, apiAccessToken: "api-access-token-value", jwtSecret: "jwt-secret-value", analytics: { token: "analytics-token-value", }, mailjet: { webhookSecret: "mailjet-webhook-secret-value", }, lago: { apiUrl: "http://lago.internal:3000", apiKey: "lago-api-key-value", webhookSecret: "lago-webhook-secret-value", timeoutMs: 5000, }, mollie: { apiKey: "mollie-api-key-value", profileId: "mollie-profile-id-value", timeoutMs: 6000, }, storage: { endpoint: "https://storage.example.com", region: "us-east-1", bucket: "uploads", accessKeyId: "storage-access-key-id-value", secretAccessKey: "storage-secret-access-key-value", sessionToken: "storage-session-token-value", publicBaseUrl: "https://cdn.example.com/files", forcePathStyle: "true", }, apiKeys: { allowLegacyPlaintextFallback: false, }, }); }); test("parses API key legacy plaintext fallback cutover flag", () => { expect(loadApiConfig({}).config.apiKeys.allowLegacyPlaintextFallback).toBe(false); expect(loadApiConfig({ API_KEY_LEGACY_PLAINTEXT_FALLBACK: "false" }).config.apiKeys.allowLegacyPlaintextFallback).toBe(false); expect(loadApiConfig({ API_KEY_LEGACY_PLAINTEXT_FALLBACK: "0" }).config.apiKeys.allowLegacyPlaintextFallback).toBe(false); expect(loadApiConfig({ API_KEY_LEGACY_PLAINTEXT_FALLBACK: "true" }).config.apiKeys.allowLegacyPlaintextFallback).toBe(true); expect(loadApiConfig({ API_KEY_LEGACY_PLAINTEXT_FALLBACK: "invalid" }).config.apiKeys.allowLegacyPlaintextFallback).toBe(false); }); test("defaults invalid Lago timeout without leaking Lago secrets into diagnostics", () => { const result = loadApiConfig({ API_PORT: "not-a-port", LAGO_API_URL: " https://lago.example.test ", LAGO_API_KEY: " lago-secret-value ", LAGO_WEBHOOK_SECRET: " lago-webhook-secret-value ", LAGO_TIMEOUT_MS: "invalid", }); expect(result.config.lago).toEqual({ apiUrl: "https://lago.example.test", apiKey: "lago-secret-value", webhookSecret: "lago-webhook-secret-value", timeoutMs: 10_000, }); const diagnosticText = JSON.stringify(result.diagnostics); expect(diagnosticText).not.toContain("lago-secret-value"); expect(diagnosticText).not.toContain("lago-webhook-secret-value"); }); test("defaults invalid Mollie timeout without leaking Mollie secrets into diagnostics", () => { const result = loadApiConfig({ API_PORT: "not-a-port", MOLLIE_API_KEY: " mollie-secret-value ", MOLLIE_PROFILE_ID: " mollie-profile-value ", MOLLIE_TIMEOUT_MS: "invalid", }); expect(result.config.mollie).toEqual({ apiKey: "mollie-secret-value", profileId: "mollie-profile-value", timeoutMs: 10_000, }); const diagnosticText = JSON.stringify(result.diagnostics); expect(diagnosticText).not.toContain("mollie-secret-value"); }); test("normalizes empty storage strings to undefined and redacts storage secrets from diagnostics", () => { const storageSecretValues = ["storage-access-key-id-value", "storage-secret-access-key-value", "storage-session-token-value"]; const result = loadApiConfig({ API_PORT: "not-a-port", STORAGE_ENDPOINT: " ", STORAGE_REGION: "\t", STORAGE_BUCKET: " ", STORAGE_ACCESS_KEY_ID: ` ${storageSecretValues[0]} `, STORAGE_SECRET_ACCESS_KEY: ` ${storageSecretValues[1]} `, STORAGE_SESSION_TOKEN: ` ${storageSecretValues[2]} `, STORAGE_PUBLIC_BASE_URL: "", STORAGE_FORCE_PATH_STYLE: " ", }); expect(result.ok).toBe(false); expect(result.config.storage).toEqual({ accessKeyId: "storage-access-key-id-value", secretAccessKey: "storage-secret-access-key-value", sessionToken: "storage-session-token-value", }); const diagnosticText = JSON.stringify(result.diagnostics); for (const secretValue of storageSecretValues) { expect(diagnosticText).not.toContain(secretValue); } }); test("preserves explicit API origins while routing hosts remain host-only", () => { const result = loadApiConfig({ ...REQUIRED_PRODUCTION_ENV, NODE_ENV: "production", APP_PROTOCOL: "https", WEB_ORIGIN: " https://app.example.com ", ADMIN_ORIGIN: " https://admin.example.com ", WEB_APP_HOST: "web-routing.example.com", ADMIN_APP_HOST: "admin-routing.example.com", }); expect(result.ok).toBe(true); expect(result.diagnostics).toEqual([]); expect(result.config).toMatchObject({ routing: { webAppHost: "web-routing.example.com", adminAppHost: "admin-routing.example.com", }, origins: { web: "https://app.example.com", admin: "https://admin.example.com", }, }); }); });