File size: 4,038 Bytes
1fe7075
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import type { AppConfig, Environment } from './app-config.interface.js';

export const APP_CONFIG = Symbol('APP_CONFIG');

const ENVIRONMENTS: Environment[] = ['development', 'test', 'staging', 'production'];

export function loadConfig(env: NodeJS.ProcessEnv = process.env): AppConfig {
  const problems: string[] = [];
  const required = (name: string) => {
    const value = env[name]?.trim();
    if (!value) problems.push(`${name} is required`);
    return value ?? '';
  };
  const integer = (name: string, fallback: number) => {
    const raw = env[name]?.trim();
    if (!raw) return fallback;
    const value = Number(raw);
    if (!Number.isInteger(value) || value < 0) problems.push(`${name} must be a whole number`);
    return value;
  };

  const environment = (env.ENVIRONMENT ?? 'development') as Environment;
  if (!ENVIRONMENTS.includes(environment)) problems.push(`ENVIRONMENT must be one of ${ENVIRONMENTS.join(', ')}`);

  let allowedOriginRegex: RegExp | null = null;
  const regex = env.PREVISION_ALLOWED_ORIGIN_REGEX?.trim();
  if (regex) {
    try {
      allowedOriginRegex = new RegExp(`^(?:${regex.replace(/^\^|\$$/g, '')})$`);
    } catch {
      problems.push('PREVISION_ALLOWED_ORIGIN_REGEX is not a valid regular expression');
    }
  }

  const config: AppConfig = {
    environment,
    port: integer('PREVISION_API_PORT', 8001),
    databaseUrl: required('PREVISION_DATABASE_URL'),
    allowedOrigins: (env.PREVISION_ALLOWED_ORIGINS ?? 'http://localhost:5173')
      .split(',')
      .map((origin) => origin.trim().replace(/\/$/, ''))
      .filter(Boolean),
    allowedOriginRegex,
    clerk: {
      secretKeys: required('CLERK_SECRET_KEY')
        .split(',')
        .map((key) => key.trim())
        .filter(Boolean),
      jwtKey: env.CLERK_JWT_KEY?.trim() || undefined,
    },
    processingToken: {
      secret: required('PROCESSING_TOKEN_SECRET'),
      ttlSeconds: integer('PROCESSING_TOKEN_TTL_SECONDS', 600),
      audience: env.PROCESSING_TOKEN_AUDIENCE?.trim() || 'prevision-processing',
      issuer: 'prevision-api',
    },
    internalTokenAudience: 'prevision-internal',
    freeGenerations: integer('FREE_GENERATIONS', 10),
    appUrl: (env.PREVISION_APP_URL?.trim() || 'http://localhost:5173').replace(/\/$/, ''),
    stripe: {
      secretKey: required('STRIPE_SECRET_KEY'),
      webhookSecret: required('STRIPE_WEBHOOK_SECRET'),
      plans: {
        starter: { priceId: required('STRIPE_PRICE_STARTER'), monthlyGenerations: integer('STARTER_MONTHLY_GENERATIONS', 150) },
        growth: { priceId: required('STRIPE_PRICE_GROWTH'), monthlyGenerations: integer('GROWTH_MONTHLY_GENERATIONS', 600) },
      },
      logoUrl: env.STRIPE_LOGO_URL?.trim() || undefined,
      portalConfigurationId: env.STRIPE_PORTAL_CONFIGURATION_ID?.trim() || undefined,
    },
  };

  if (environment === 'staging' || environment === 'production') {
    if (config.processingToken.secret.length < 32) problems.push('PROCESSING_TOKEN_SECRET must be at least 32 characters');
    if (config.allowedOrigins.some((origin) => origin.includes('*'))) problems.push('PREVISION_ALLOWED_ORIGINS must list exact origins');
    if (!config.clerk.secretKeys.every((key) => key.startsWith('sk_'))) problems.push('CLERK_SECRET_KEY must list Clerk secret keys');
    if (!/^(sk|rk)_/.test(config.stripe.secretKey)) problems.push('STRIPE_SECRET_KEY must be a Stripe secret key');
    if (!config.stripe.webhookSecret.startsWith('whsec_')) problems.push('STRIPE_WEBHOOK_SECRET must be a webhook signing secret');
    if (!config.appUrl.startsWith('https://')) problems.push('PREVISION_APP_URL must be an https URL');
  }
  if (problems.length) throw new Error(`Invalid configuration: ${problems.join('; ')}`);
  return config;
}

export function isOriginAllowed(config: AppConfig, origin: string | null | undefined): boolean {
  if (!origin) return false;
  const normalized = origin.replace(/\/$/, '');
  return config.allowedOrigins.includes(normalized) || Boolean(config.allowedOriginRegex?.test(normalized));
}