File size: 5,425 Bytes
6111b2b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
import { z } from "zod";

import { validateSecrets } from "@/shared/utils/secretsValidator";

const NODE_ENV_VALUES = ["development", "production", "test"] as const;
const BOOLEAN_ENV_VALUES = ["true", "false"] as const;

type RuntimeEnvIssue = {
  name: string;
  issue: string;
  hint?: string;
};

export type RuntimeEnvValidationResult = {
  valid: boolean;
  errors: RuntimeEnvIssue[];
  warnings: RuntimeEnvIssue[];
  data?: WebRuntimeEnv;
};

function normalizeOptionalString(value: unknown): string | undefined {
  if (typeof value !== "string") return undefined;
  const trimmed = value.trim();
  return trimmed === "" ? undefined : trimmed;
}

const optionalTrimmedString = z.preprocess(normalizeOptionalString, z.string().min(1).optional());

const optionalBooleanEnv = z.preprocess(
  normalizeOptionalString,
  z.enum(BOOLEAN_ENV_VALUES).optional()
);

const optionalHttpUrl = z.preprocess(
  normalizeOptionalString,
  z
    .string()
    .url()
    .refine((value) => value.startsWith("http://") || value.startsWith("https://"), {
      message: "must start with http:// or https://",
    })
    .optional()
);

const optionalPortEnv = z.preprocess(
  normalizeOptionalString,
  z
    .string()
    .regex(/^\d+$/, "must be an integer between 1 and 65535")
    .refine((value) => {
      const parsed = Number.parseInt(value, 10);
      return Number.isFinite(parsed) && parsed >= 1 && parsed <= 65535;
    }, "must be an integer between 1 and 65535")
    .optional()
);

export const webRuntimeEnvSchema = z.object({
  NODE_ENV: z.preprocess(normalizeOptionalString, z.enum(NODE_ENV_VALUES).optional()),
  DATA_DIR: optionalTrimmedString,
  JWT_SECRET: optionalTrimmedString,
  API_KEY_SECRET: optionalTrimmedString,
  INITIAL_PASSWORD: optionalTrimmedString,
  AUTH_COOKIE_SECURE: optionalBooleanEnv,
  PRICING_SYNC_ENABLED: optionalBooleanEnv,
  OMNIROUTE_DISABLE_BACKGROUND_SERVICES: optionalBooleanEnv,
  CLOUD_URL: optionalHttpUrl,
  NEXT_PUBLIC_CLOUD_URL: optionalHttpUrl,
  OMNIROUTE_PUBLIC_BASE_URL: optionalHttpUrl,
  OMNIROUTE_BASE_URL: optionalHttpUrl,
  BASE_URL: optionalHttpUrl,
  NEXT_PUBLIC_BASE_URL: optionalHttpUrl,
  OMNIROUTE_PORT: optionalPortEnv,
  API_PORT: optionalPortEnv,
  DASHBOARD_PORT: optionalPortEnv,
});

export type WebRuntimeEnv = z.infer<typeof webRuntimeEnvSchema>;

function formatZodPath(path: Array<string | number>): string {
  return path.length > 0 ? String(path[0]) : "env";
}

function getSchemaIssues(error: z.ZodError): RuntimeEnvIssue[] {
  return error.issues.map((issue) => ({
    name: formatZodPath(issue.path),
    issue: `Invalid environment variable "${formatZodPath(issue.path)}": ${issue.message}.`,
  }));
}

export function validateWebRuntimeEnv(

  env: NodeJS.ProcessEnv = process.env

): RuntimeEnvValidationResult {
  const secretValidation = validateSecrets(env);
  const schemaValidation = webRuntimeEnvSchema.safeParse(env);
  const errors = [...secretValidation.errors];
  const warnings = [...secretValidation.warnings];

  if (!schemaValidation.success) {
    errors.push(...getSchemaIssues(schemaValidation.error));
  }

  return {
    valid: errors.length === 0,
    errors,
    warnings,
    data: schemaValidation.success ? schemaValidation.data : undefined,
  };
}

export function formatRuntimeEnvValidationErrors(

  errors: RuntimeEnvIssue[],

  warnings: RuntimeEnvIssue[] = []

): string {
  const lines = ["Invalid web runtime environment configuration:"];

  for (const error of errors) {
    lines.push(`- ${error.issue}`);
    if (error.hint) {
      lines.push(`  hint: ${error.hint}`);
    }
  }

  for (const warning of warnings) {
    lines.push(`- Warning: ${warning.issue}`);
  }

  return lines.join("\n");
}

export function getWebRuntimeEnv(env: NodeJS.ProcessEnv = process.env): WebRuntimeEnv {
  const result = validateWebRuntimeEnv(env);
  if (!result.valid || !result.data) {
    throw new Error(formatRuntimeEnvValidationErrors(result.errors, result.warnings));
  }
  return result.data;
}

export function enforceWebRuntimeEnv(

  env: NodeJS.ProcessEnv = process.env,

  logger: Pick<Console, "error" | "warn"> = console

): void {
  const result = validateWebRuntimeEnv(env);

  for (const warning of result.warnings) {
    logger.warn(`[STARTUP] ${warning.issue}`);
  }

  if (result.valid) return;

  logger.error("");
  logger.error("═══════════════════════════════════════════════════");
  logger.error("  ❌  STARTUP: Invalid web runtime environment");
  logger.error("═══════════════════════════════════════════════════");
  for (const error of result.errors) {
    logger.error(`  β€’ ${error.issue}`);
    if (error.hint) {
      logger.error(`    β†’ ${error.hint}`);
    }
  }
  logger.error("");
  logger.error("  Fix the environment and restart the server.");
  logger.error("  Secrets are intentionally not printed.");
  logger.error("═══════════════════════════════════════════════════");
  logger.error("");
  process.exit(1);
}