import { randomBytes, timingSafeEqual } from 'node:crypto';

export function isLoopbackAddress(value?: string | null) {
  if (!value) return false;
  const normalized = value.replace(/^::ffff:/, '');
  return normalized === '127.0.0.1' || normalized === '::1' || normalized === 'localhost';
}

export function validateRuntimeSecret(expected?: string, actual?: string | null) {
  if (!expected || !actual) return false;
  const left = Buffer.from(expected);
  const right = Buffer.from(actual);
  return left.length === right.length && timingSafeEqual(left, right);
}

export function resolveTraySecret(argv: string[], env: NodeJS.ProcessEnv) {
  const index = argv.indexOf('--tray-secret');
  if (index > -1 && argv[index + 1]) return argv[index + 1];
  return env.GPU_GUARD_TRAY_SECRET || '';
}

export function createRuntimeSecret() {
  return randomBytes(24).toString('hex');
}
