import fs from 'node:fs'; import path from 'node:path'; import type { z } from 'zod'; const LOOPBACK_HOSTS = new Set(['127.0.0.1', '::1', '[::1]', 'localhost']); const ENV_TEMPLATE_REGEX = /\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g; const DEFAULT_FETCH_TIMEOUT_MS = 30_000; function parseEnvFile(content: string): Record { const parsed: Record = {}; for (const rawLine of content.split(/\r?\n/)) { const trimmed = rawLine.trim(); if (!trimmed || trimmed.startsWith('#')) continue; const line = trimmed.startsWith('export ') ? trimmed.slice('export '.length).trim() : trimmed; const eqIdx = line.indexOf('='); if (eqIdx <= 0) continue; const key = line.slice(0, eqIdx).trim(); if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key)) continue; let value = line.slice(eqIdx + 1).trim(); if ( (value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'")) ) { value = value.slice(1, -1); } else { const commentIdx = value.search(/\s+#/); if (commentIdx !== -1) { value = value.slice(0, commentIdx).trim(); } } parsed[key] = value; } return parsed; } export function loadProjectEnv( cwd: string ): Record { const merged: Record = {}; for (const filename of ['.env', '.env.local']) { const filePath = path.join(cwd, filename); if (!fs.existsSync(filePath)) continue; try { Object.assign(merged, parseEnvFile(fs.readFileSync(filePath, 'utf-8'))); } catch { // Ignore unreadable optional env files. } } for (const [key, value] of Object.entries(process.env)) { if (value !== undefined) { merged[key] = value; } } return merged; } export function assertSecureUrl(rawUrl: string): URL { let url: URL; try { url = new URL(rawUrl); } catch { throw new Error('Invalid URL configured for registry request.'); } if (url.username || url.password) { throw new Error( `Refusing URL with embedded credentials (${url.origin}${url.pathname}). Use --token-env instead.` ); } if (url.protocol === 'https:') { return url; } if (url.protocol === 'http:' && LOOPBACK_HOSTS.has(url.hostname)) { return url; } throw new Error( `Refusing insecure non-HTTPS URL: ${url.origin}${url.pathname}. Only https:// (or http:// on localhost/127.0.0.1/::1) is allowed.` ); } export function normalizeSourceUrl(rawUrl: string): string { const url = assertSecureUrl(rawUrl); return `${url.origin}${url.pathname.replace(/\/+$/, '')}`; } export function expandEnvTemplate( template: string, env: Readonly>, contextLabel: string ): string { return template.replace(ENV_TEMPLATE_REGEX, (_match, varName: string) => { const value = env[varName]?.trim(); if (!value) { throw new Error( `Missing required environment variable ${varName} referenced by ${contextLabel}.` ); } return value; }); } export function readRequiredEnvToken( tokenEnv: string, env: Readonly> ): string { if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(tokenEnv)) { throw new Error(`Invalid environment variable name: ${tokenEnv}`); } const value = env[tokenEnv]?.trim(); if (!value) { throw new Error( `Environment variable ${tokenEnv} is not set. Export ${tokenEnv} before syncing.` ); } return value; } export async function secureFetchJson( rawUrl: string, options: Readonly<{ fetchImpl?: typeof fetch; headers?: Readonly>; schema: z.ZodType; }> ): Promise { const url = assertSecureUrl(rawUrl); const fetchFn = options.fetchImpl ?? globalThis.fetch; const response = await fetchFn(url.toString(), { headers: { Accept: 'application/json', ...options.headers, }, redirect: 'error', signal: AbortSignal.timeout(DEFAULT_FETCH_TIMEOUT_MS), }); if (!response.ok) { const hint = response.status === 401 ? 'Check your Bearer API key.' : response.status === 403 ? 'Your API key does not have access to this resource.' : ''; throw new Error( `Request to ${url.origin}${url.pathname} failed with HTTP ${response.status}.${hint ? ` ${hint}` : ''}` ); } let json: unknown; try { json = await response.json(); } catch { throw new Error( `Response from ${url.origin}${url.pathname} was not valid JSON.` ); } const parsed = options.schema.safeParse(json); if (!parsed.success) { throw new Error( `Response from ${url.origin}${url.pathname} failed schema validation: ${parsed.error.issues[0]?.message ?? 'invalid payload'}` ); } return parsed.data; }