{"version":3,"sources":["../src/reflection-config.ts"],"sourcesContent":["/**\n * Copyright 2026 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n *     http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { createHash, timingSafeEqual } from 'crypto';\n\n/** Header carrying the reflection secret on v1 requests. */\nexport const REFLECTION_SECRET_HEADER = 'x-genkit-reflection-secret';\n\n/** Default interface for the v1 server. */\nexport const DEFAULT_REFLECTION_HOST = '127.0.0.1';\n\n/** First port tried when no exact port is configured. */\nexport const DEFAULT_REFLECTION_PORT = 3100;\n\n/**\n * JSON-RPC error code the CLI returns when a v2 `register` fails auth.\n * Terminal: the runtime must not reconnect, the secret will not change.\n */\nexport const REFLECTION_AUTH_ERROR_CODE = -32001;\n\n/**\n * Either an exact port (0 lets the OS pick) or a probe upward from\n * {@link DEFAULT_REFLECTION_PORT}, used only when nobody chose a port.\n */\nexport type ReflectionPort =\n  | { kind: 'pinned'; port: number }\n  | { kind: 'probe' };\n\n/**\n * How the reflection API runs, if at all.\n *\n * `disabled` and `off` differ by who decided. `disabled` is an explicit kill\n * switch (`GENKIT_REFLECTION_ENABLED=false`) that even a direct\n * `ReflectionServer.start()` honours. `off` only means nothing in the\n * environment asked for a server, so an explicit start still runs one with\n * defaults.\n */\nexport type ReflectionConfig =\n  | { kind: 'disabled' }\n  | { kind: 'off' }\n  | ReflectionServerConfig;\n\n/** How a running reflection API connects: dial out (v2) or listen (v1). */\nexport type ReflectionServerConfig =\n  | { kind: 'v2'; url: string; secret?: string }\n  | {\n      kind: 'v1';\n      host: string;\n      port: ReflectionPort;\n      secret?: string;\n    };\n\n/** Minimal view of the environment, so this stays testable and platform-free. */\nexport type ReflectionEnv = Record<string, string | undefined>;\n\n/**\n * Parses `GENKIT_REFLECTION_PORT`.\n *\n * Anything that is not an integer in 0..65535 throws rather than falling back\n * to probing: a typo in a deployment config should fail loudly, not quietly\n * bind a port nobody published.\n */\nfunction parsePort(raw: string | undefined): number | undefined {\n  if (raw === undefined || raw === '') {\n    return undefined;\n  }\n  // Plain decimal digits only: Number() alone would accept \"0x10\", \"1e3\",\n  // \"+7\" and surrounding whitespace, silently binding a different port.\n  const port = /^[0-9]+$/.test(raw) ? Number(raw) : NaN;\n  if (!Number.isInteger(port) || port < 0 || port > 65535) {\n    throw new Error(\n      `GENKIT_REFLECTION_PORT must be an integer between 0 and 65535, got \"${raw}\".`\n    );\n  }\n  return port;\n}\n\n/**\n * Parses `GENKIT_REFLECTION_ENABLED`: `true`, `false`, or unset (empty counts\n * as unset). Anything else throws, for the same reason as {@link parsePort}.\n */\nfunction parseEnabled(raw: string | undefined): boolean | undefined {\n  if (raw === undefined || raw === '') {\n    return undefined;\n  }\n  if (raw === 'true' || raw === 'false') {\n    return raw === 'true';\n  }\n  throw new Error(\n    `GENKIT_REFLECTION_ENABLED must be \"true\" or \"false\", got \"${raw}\".`\n  );\n}\n\n/**\n * Resolves the port for the v1 server. Whoever chose a port, the environment\n * or the code, gets exactly that port; only an unchosen port is probed.\n *\n * Code values: `undefined` is unset, `0` lets the OS pick (same as\n * `GENKIT_REFLECTION_PORT=0` and `net.Server.listen`), 1..65535 is exact.\n * Anything else throws, even when the environment port wins, so a bad value\n * fails regardless of deployment.\n */\nexport function resolveReflectionPort(\n  envPort: number | undefined,\n  optionPort: number | undefined\n): ReflectionPort {\n  const fromOption = resolveOptionPort(optionPort);\n  return envPort !== undefined ? { kind: 'pinned', port: envPort } : fromOption;\n}\n\nfunction resolveOptionPort(optionPort: number | undefined): ReflectionPort {\n  if (optionPort === undefined) {\n    return { kind: 'probe' };\n  }\n  if (!Number.isInteger(optionPort) || optionPort < 0 || optionPort > 65535) {\n    throw new Error(\n      `reflectionPort must be an integer between 0 and 65535, got ${optionPort}.`\n    );\n  }\n  return { kind: 'pinned', port: optionPort };\n}\n\n/**\n * Resolves how the reflection API should run.\n *\n * Whether it runs:\n * - `GENKIT_REFLECTION_ENABLED=false` turns it off, even under dev.\n * - `GENKIT_REFLECTION_ENABLED=true` turns it on in any environment.\n * - Unset, it runs only under `GENKIT_ENV=dev`, as it always has.\n *\n * How it runs, once on: `GENKIT_REFLECTION_V2_SERVER` dials out; otherwise the\n * v1 server listens on `GENKIT_REFLECTION_HOST`/`GENKIT_REFLECTION_PORT`.\n * Those are settings, not on-switches: a stray value in a production env does\n * not expose the API, and is not even parsed while reflection is off.\n *\n * The environment port beats `options.port` on purpose: whoever set the\n * variable is typically the supervisor that already published that port.\n * `options.port` is validated even when unused so a bad value fails early.\n *\n * @hidden\n */\nexport function resolveReflectionConfig(\n  env: ReflectionEnv,\n  options: { port?: number } = {}\n): ReflectionConfig {\n  // Validated before the on/off check so a bad value fails early.\n  resolveOptionPort(options.port);\n  const enabled = parseEnabled(env.GENKIT_REFLECTION_ENABLED);\n  if (enabled === false) {\n    return { kind: 'disabled' };\n  }\n  if (enabled === undefined && env.GENKIT_ENV !== 'dev') {\n    return { kind: 'off' };\n  }\n  return resolveReflectionServerConfig(env, options);\n}\n\n/**\n * The \"how it runs\" half of {@link resolveReflectionConfig}, without the\n * on/off decision. For callers that already decided to run a server, such as\n * a direct `ReflectionServer.start()`.\n */\nexport function resolveReflectionServerConfig(\n  env: ReflectionEnv,\n  options: { port?: number } = {}\n): ReflectionServerConfig {\n  // Validated even for v2, which has no port, so a bad value always fails.\n  resolveOptionPort(options.port);\n  const secret = env.GENKIT_REFLECTION_SECRET_TOKEN || undefined;\n  if (env.GENKIT_REFLECTION_V2_SERVER) {\n    return { kind: 'v2', url: env.GENKIT_REFLECTION_V2_SERVER, secret };\n  }\n  return {\n    kind: 'v1',\n    host: env.GENKIT_REFLECTION_HOST || DEFAULT_REFLECTION_HOST,\n    port: resolveReflectionPort(\n      parsePort(env.GENKIT_REFLECTION_PORT),\n      options.port\n    ),\n    secret,\n  };\n}\n\n/**\n * Host to advertise in the runtime discovery file for a server bound to\n * `host`. A wildcard bind is reachable on loopback, and `0.0.0.0` is not a\n * valid destination everywhere, so it is advertised as `127.0.0.1`. IPv6\n * literals are bracketed for use in a URL.\n */\nexport function advertisedReflectionHost(host: string): string {\n  if (host === '0.0.0.0' || host === '::' || host === '[::]') {\n    return '127.0.0.1';\n  }\n  return host.includes(':') && !host.startsWith('[') ? `[${host}]` : host;\n}\n\n/**\n * Whether a host is loopback, and so unreachable from other machines. Only\n * `localhost` and literal loopback IPs count; a hostname like\n * `127.internal.example` may resolve anywhere.\n */\nexport function isLoopbackHost(host: string): boolean {\n  const bracketed =\n    host.includes(':') && !host.startsWith('[') ? `[${host}]` : host;\n  let hostname: string;\n  try {\n    // URL normalizes IP literals the way Node's listen() reads them: 127.1 and\n    // 0x7f.1 become 127.0.0.1, any spelling of ::1 becomes [::1]. Invalid\n    // literals (e.g. 127.300.400.500) throw.\n    hostname = new URL(`http://${bracketed}`).hostname;\n  } catch {\n    return false;\n  }\n  if (hostname === 'localhost' || hostname === '[::1]') {\n    return true;\n  }\n  // Only a parsed IPv4 literal comes back as four decimal labels; a hostname\n  // like 127.a.b.c or 127.0.0.1.nip.io stays as written.\n  const labels = hostname.split('.');\n  return (\n    labels.length === 4 &&\n    labels.every((l) => /^\\d+$/.test(l)) &&\n    labels[0] === '127'\n  );\n}\n\n/**\n * Constant-time secret comparison over sha256 digests, which gives equal-length\n * inputs without leaking the expected length.\n */\nexport function secretsEqual(a: string, b: string): boolean {\n  const ha = createHash('sha256').update(a).digest();\n  const hb = createHash('sha256').update(b).digest();\n  return timingSafeEqual(ha, hb);\n}\n"],"mappings":"AAgBA,SAAS,YAAY,uBAAuB;AAGrC,MAAM,2BAA2B;AAGjC,MAAM,0BAA0B;AAGhC,MAAM,0BAA0B;AAMhC,MAAM,6BAA6B;AA4C1C,SAAS,UA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