Skip to content

The micro-VM for AI agents — light enough to embed on your laptop, elastic enough to power an agentic cloud.

23.7 KB
Raw Blame
/*
 * What the API container reads.
 *
 * Assembled here rather than in `sst.config.ts` because none of it needs SST:
 * it is the stage's own configuration rearranged into the names the service
 * expects. A function handed its environment is one a test can run; one reading
 * `process.env` through an SST config is not, which is how a key stops being
 * passed without anything noticing. The incumbent `stack/api.ts` was the second
 * kind, which is why its two hundred lines of `envOr` had no test at all.
 *
 * Two channels come out of it, because a container reads a name the same way
 * whichever one carried it. `environment` is delivered as values; `secrets` is
 * delivered as addresses that the platform resolves before the container
 * starts, so those values never enter a task definition or a revision. Which
 * keys go which way is `mstage.config.json`'s answer, not this file's:
 * `env.selectGroup.api` names what the API reads, and `env.selectGroup.secret`
 * marks which of those are addresses.
 *
 * The database's, the cache's and the collector's own names are added by the
 * stack on top of this, because those modules own them.
 */

import { API_GROUP, serviceSecretsFrom, splitServiceChannels, type Environment, type GroupDeclaration } from './env.ts'
import { API_PORT, publicHostsFor, type PublicHosts } from '../stack/api.ts'
import { SECRET_GROUP } from 'mstage/secret-address'
import type { Cloud } from 'mstage/config'
import { FilestoreConfigurationError, parseFilestoreInstances } from '../../../shared/filestore-instances.ts'

export class ApiEnvironmentError extends Error {
  constructor(message: string) {
    super(message)
    this.name = 'ApiEnvironmentError'
  }
}

const optional = (environment: Environment, key: string): string | null => environment[key]?.trim() || null

/** A stage flag, rejected here rather than at the service's boot. */
const flag = (environment: Environment, key: string): boolean => {
  const value = optional(environment, key) ?? 'false'
  if (value !== 'true' && value !== 'false') throw new ApiEnvironmentError(`${key} must be true or false`)
  return value === 'true'
}

/**
 * A feature switched on by holding a credential, not by a second setting.
 *
 * Three of the API's features work this way — usage export, the status sync,
 * and the Auth0 management client — and each refuses to boot when its flag is
 * on and its credential is missing. Deriving the flag from the credential is
 * what stops a stage that was pointed at a service but never given the secret
 * from crash-looping instead of simply staying dark.
 *
 * Derived from *presence in the store* rather than from the value's text, and
 * that distinction is load-bearing: a credential delivered by reference is an
 * address here, so reading the text would ask whether an ARN is empty. Either
 * channel counts as held, which is the only answer that stays true when a
 * secret moves from one to the other.
 */
const held = (delivered: Record<string, string>, key: string): boolean => (delivered[key]?.trim() ?? '') !== ''

const CI_SECRET_KEYS = ['CI_GITHUB_APP_PRIVATE_KEY', 'CI_GITHUB_WEBHOOK_SECRET', 'CI_SECRET_ENCRYPTION_KEY']

/** CI is optional; once selected, every credential must use the workload secret channel. */
const validateCiChannels = (values: Record<string, string>, addresses: Record<string, string>): void => {
  for (const key of ['CI_GITHUB_APP_PRIVATE_KEY_FILE', 'CI_GITHUB_WEBHOOK_SECRET_FILE', 'CI_GITHUB_APPS_FILE'])
    if (key in values || key in addresses)
      throw new ApiEnvironmentError(`${key} is a self-hosted file input; hosted CI uses mstage secret refs`)
  const orgClient = 'CI_GITHUB_ORG_APP_CLIENT_ID',
    orgSlug = 'CI_GITHUB_ORG_APP_SLUG'
  const orgSecrets = ['CI_GITHUB_ORG_APP_PRIVATE_KEY', 'CI_GITHUB_ORG_WEBHOOK_SECRET']
  const orgKeys = [orgClient, orgSlug, ...orgSecrets, 'CI_GITHUB_ORG_APP_CLIENT_SECRET']
  if (orgKeys.some((key) => held(values, key) || held(addresses, key))) {
    if (!held(values, 'CI_GITHUB_APP_CLIENT_ID'))
      throw new ApiEnvironmentError('Personal App identity is required as the shared CI storage anchor')
    if (!/^[A-Za-z0-9_-]{1,128}$/.test(values[orgClient] || '') || values[orgClient] === values.CI_GITHUB_APP_CLIENT_ID)
      throw new ApiEnvironmentError('Organization App requires a distinct client ID')
    if (!/^[A-Za-z0-9-]+$/.test(values[orgSlug] || ''))
      throw new ApiEnvironmentError('Organization App slug is required')
    for (const key of orgSecrets)
      if (!held(addresses, key)) throw new ApiEnvironmentError(`${key} requires a mstage secret ref`)
  }
  for (const [webSecret, clientKey] of [
    ['CI_GITHUB_APP_CLIENT_SECRET', 'CI_GITHUB_APP_CLIENT_ID'],
    ['CI_GITHUB_ORG_APP_CLIENT_SECRET', orgClient],
  ]) {
    if (held(values, webSecret) || held(addresses, webSecret)) {
      if (!held(addresses, webSecret)) throw new ApiEnvironmentError(`${webSecret} requires a mstage secret ref`)
      if (!held(values, clientKey)) throw new ApiEnvironmentError(`${clientKey} is required for browser connect`)
    }
  }
  const oauthClient = 'CI_GITHUB_OAUTH_CLIENT_ID',
    oauthSecret = 'CI_GITHUB_OAUTH_CLIENT_SECRET'
  if ([oauthClient, oauthSecret].some((key) => held(values, key) || held(addresses, key))) {
    if (
      !/^[A-Za-z0-9_-]{1,128}$/.test(values[oauthClient] || '') ||
      held(addresses, oauthClient) ||
      [values.CI_GITHUB_APP_CLIENT_ID, values.CI_GITHUB_ORG_APP_CLIENT_ID].includes(values[oauthClient])
    )
      throw new ApiEnvironmentError('Identity OAuth requires a distinct plain client ID')
    if (!held(addresses, oauthSecret) || held(values, oauthSecret))
      throw new ApiEnvironmentError(`${oauthSecret} requires a mstage secret ref`)
    if (!held(values, 'CI_GITHUB_APP_CLIENT_ID'))
      throw new ApiEnvironmentError('Identity OAuth requires the hosted CI storage anchor')
  }
  const client = values.CI_GITHUB_APP_CLIENT_ID,
    slug = values.CI_GITHUB_APP_SLUG
  if (
    !client &&
    !slug &&
    !addresses.CI_GITHUB_APP_CLIENT_ID &&
    !addresses.CI_GITHUB_APP_SLUG &&
    !CI_SECRET_KEYS.some((key) => held(values, key) || held(addresses, key))
  )
    return
  if (!client || !/^[A-Za-z0-9_.-]{1,200}$/.test(client))
    throw new ApiEnvironmentError('CI_GITHUB_APP_CLIENT_ID is required for hosted CI')
  if (!slug || !/^[A-Za-z0-9-]+$/.test(slug))
    throw new ApiEnvironmentError('CI_GITHUB_APP_SLUG is required for hosted CI')
  for (const key of CI_SECRET_KEYS)
    if (!held(addresses, key))
      throw new ApiEnvironmentError(`${key} requires a mstage secret ref in both api and secret groups`)
}

/**
 * The names the billing read path only means anything as a set.
 *
 * Exported so a test can hold it against `env.selectGroup`: a name this
 * function expects but no group fetches would otherwise read as "billing not
 * configured" on every deploy, with nothing saying why.
 */
export const BILLING_KEYS = ['BILLING_API_URL', 'USAGE_EXPORT_URL', 'USAGE_EXPORT_TOKEN']

/** The same, for the incident.io status sync. */
export const STATUS_SYNC_KEYS = [
  'INCIDENT_IO_ALERT_SOURCE_CONFIG_ID',
  'INCIDENT_IO_HEARTBEAT_ID',
  'INCIDENT_IO_TOKEN',
  'STATUS_SYNC_DEDUP_PREFIX',
]

/**
 * The dashboard's two origins.
 *
 * They are different on purpose. Static assets are served through the CDN at
 * the dashboard's own host; the dashboard's API client talks to the control
 * plane directly, because CloudFront caps a WebSocket at ten minutes and times
 * an origin read out at sixty seconds — which breaks `/attach`, build-log
 * streaming and file uploads. Both are overridable, because a stage may put
 * either behind something else, and both have a default so a stage that
 * overrides neither is still correct.
 *
 * The defaults are `publicHostsFor`'s answer rather than this file's own
 * composition: the same two names are what the balancer's certificate covers
 * and what its records point at, and a second rule here is a dashboard told to
 * call a host nothing serves.
 */
const dashboardFrom = (environment: Environment, hosts: PublicHosts): Record<string, string> => ({
  DASHBOARD_URL: optional(environment, 'DASHBOARD_URL') ?? `https://${hosts.dashboard}`,
  DASHBOARD_BASE_API_URL: optional(environment, 'DASHBOARD_BASE_API_URL') ?? `https://${hosts.api}`,
  ...(optional(environment, 'APP_URL') ? { APP_URL: optional(environment, 'APP_URL') as string } : {}),
})

/**
 * The OIDC settings, and the management client the deploy may not be able to
 * configure.
 *
 * `OIDC_MANAGEMENT_API_ENABLED` is the one flag that is *not* derived from its
 * credential, and the asymmetry is deliberate: the audience it needs is a
 * setting rather than a secret, and a stage that turned the feature on without
 * one would have the API fail at its first account-link rather than at boot.
 * Refusing here names the missing key.
 */
const oidcFrom = (environment: Environment, hosts: PublicHosts): Record<string, string> => {
  const issuer = optional(environment, 'OIDC_ISSUER_BASE_URL')
  if (!issuer) {
    throw new ApiEnvironmentError(
      'OIDC_ISSUER_BASE_URL is required — every interactive login goes through it, and a placeholder ' +
        'would let the stack become healthy while nobody can sign in',
    )
  }
  const management = flag(environment, 'OIDC_MANAGEMENT_API_ENABLED')
  const audience = optional(environment, 'OIDC_MANAGEMENT_API_AUDIENCE')
  if (management && !audience) {
    throw new ApiEnvironmentError('OIDC_MANAGEMENT_API_AUDIENCE is required when OIDC_MANAGEMENT_API_ENABLED=true')
  }
  const passthrough = (key: string) =>
    optional(environment, key) ? { [key]: optional(environment, key) as string } : {}
  return {
    OIDC_ISSUER_BASE_URL: issuer,
    OIDC_AUDIENCE: optional(environment, 'OIDC_AUDIENCE') ?? 'boxlite',
    // Safe to set unconditionally: the API probes the issuer's discovery
    // document at boot and only offers this fallback to the dashboard when the
    // issuer itself advertises no end_session_endpoint.
    // On the dashboard's own origin: the browser is redirected here at the end
    // of a logout, so it is the name it is already on rather than the control
    // plane's — which a stage may publish somewhere else entirely.
    OIDC_END_SESSION_ENDPOINT:
      optional(environment, 'OIDC_END_SESSION_ENDPOINT') ?? `https://${hosts.dashboard}/api/auth/end-session`,
    ...passthrough('PUBLIC_OIDC_DOMAIN'),
    ...passthrough('OIDC_POST_LOGOUT_REDIRECT_ALLOWLIST'),
    // The MCP endpoint's OAuth resource: the URL clients connect to, on the
    // control plane's host as `DASHBOARD_BASE_API_URL` is. Browser sign-in also
    // needs `auth0:configure-mcp` on the tenant; API keys work without it.
    MCP_RESOURCE_URL: optional(environment, 'MCP_RESOURCE_URL') ?? `https://${hosts.api}/mcp`,
    ...(management
      ? {
          OIDC_MANAGEMENT_API_ENABLED: 'true',
          OIDC_MANAGEMENT_API_AUDIENCE: audience as string,
          ...passthrough('OIDC_MANAGEMENT_API_BASE_URL'),
          ...passthrough('OIDC_MANAGEMENT_API_TOKEN_URL'),
        }
      : {}),
  }
}

/**
 * Where the dashboard's billing surface calls, and where finalized usage goes.
 *
 * `USAGE_EXPORT_URL` explicitly selects the server-side base, including an
 * optional path prefix. When absent, it defaults to `BILLING_API_URL`'s origin;
 * clients append their internal routes to that base.
 *
 * No default for `BILLING_API_URL`: this stack deploys no billing service, so
 * a stage that names none keeps the dashboard's billing pages gated off, which
 * is the correct state rather than a broken one.
 */
const billingFrom = (environment: Environment, delivered: Record<string, string>): Record<string, string> => {
  const base = optional(environment, 'BILLING_API_URL')
  if (!base) return {}
  let origin: string
  try {
    origin = new URL(base).origin
  } catch {
    throw new ApiEnvironmentError(`BILLING_API_URL must be an absolute URL; got ${JSON.stringify(base)}`)
  }
  const exporting = held(delivered, 'USAGE_EXPORT_TOKEN')
  return {
    BILLING_API_URL: base,
    USAGE_EXPORT_URL: optional(environment, 'USAGE_EXPORT_URL') ?? origin,
    USAGE_EXPORT_ENABLED: String(exporting),
    // The same destination and credential carry the periodic snapshot the
    // billing service estimates still-open usage from.
    USAGE_ALLOCATION_SNAPSHOT_ENABLED: String(exporting),
  }
}

/** The status sync, gated on the alert source id so an unconfigured stage carries none of it. */
const statusSyncFrom = (
  environment: Environment,
  delivered: Record<string, string>,
  stage: string,
): Record<string, string> => {
  const source = optional(environment, 'INCIDENT_IO_ALERT_SOURCE_CONFIG_ID')
  if (!source) return {}
  return {
    INCIDENT_IO_ALERT_SOURCE_CONFIG_ID: source,
    ...(optional(environment, 'INCIDENT_IO_HEARTBEAT_ID')
      ? { INCIDENT_IO_HEARTBEAT_ID: optional(environment, 'INCIDENT_IO_HEARTBEAT_ID') as string }
      : {}),
    STATUS_SYNC_ENABLED: String(held(delivered, 'INCIDENT_IO_TOKEN')),
    // Every deployed stage reports ENVIRONMENT=production, so the per-stage
    // alert identity comes from the stage name instead.
    STATUS_SYNC_DEDUP_PREFIX: optional(environment, 'STATUS_SYNC_DEDUP_PREFIX') ?? `boxlite-${stage}`,
  }
}

/**
 * The registry boxes pull their system images from.
 *
 * All of nothing: a URL with no credential is a registry every box pull fails
 * against, and a credential with no URL configures nothing. Gated on the URL,
 * which is the value that says a stage meant to use one at all.
 */
const systemImagesFrom = (environment: Environment): Record<string, string> => {
  const passthrough = (key: string, fallback = '') => ({ [key]: optional(environment, key) ?? fallback })
  const registry = optional(environment, 'BOXLITE_SYSTEM_SOURCE_REGISTRY_URL')
  return {
    ...passthrough('BOXLITE_SYSTEM_BASE_IMAGE'),
    ...passthrough('BOXLITE_SYSTEM_NODE_IMAGE'),
    ...passthrough('BOXLITE_SYSTEM_PYTHON_IMAGE'),
    ...passthrough('BOXLITE_SYSTEM_IMAGE_TAG'),
    ...passthrough('BOXLITE_SYSTEM_IMAGES'),
    // Registries a tenant-supplied image may be pulled from. Unset leaves the
    // API on its built-in list, so an operator only sets this to widen or
    // narrow it, with no code change.
    ...passthrough('BOXLITE_IMAGE_REGISTRY_ALLOWLIST'),
    REGISTRY_PROXY_UPSTREAM_HOSTS: (optional(environment, 'REGISTRY_PROXY_UPSTREAM_HOSTS') ?? '')
      .split(',')
      .map((host) => host.trim().toLowerCase())
      .filter(Boolean)
      .join(','),
    // The per-organization cold-pull budget. Unset keeps the API's 6 per 60s.
    ...passthrough('BOXLITE_IMAGE_COLD_PULL_LIMIT'),
    ...passthrough('BOXLITE_IMAGE_COLD_PULL_WINDOW_SECONDS'),
    ...(registry
      ? {
          BOXLITE_SYSTEM_SOURCE_REGISTRY_URL: registry,
          ...passthrough('BOXLITE_SYSTEM_SOURCE_REGISTRY_NAME', 'BoxLite System Source Registry'),
          ...passthrough('BOXLITE_SYSTEM_SOURCE_REGISTRY_USERNAME'),
          ...passthrough('BOXLITE_SYSTEM_SOURCE_REGISTRY_PROJECT_ID'),
        }
      : {}),
  }
}

/**
 * The online disk-expansion switch and its cap, delivered only when the stage
 * set them.
 *
 * A key absent from the container's environment is the API's own default: the
 * switch off and the cap unset, which is exactly the behavior of every stage
 * before this mechanism existed. Delivering `false` unconditionally would
 * read the same but say more than the stage did — and the cap's absence is
 * load-bearing, because the controller skips uncapped runners loudly rather
 * than silently growing disks to wherever the default lands. A value that is
 * neither true nor false is refused here rather than left for the API to read
 * as off, which is how a typo'd switch would stay closed forever.
 */
const runnerDiskExpansionFrom = (environment: Environment): Record<string, string> => {
  const enabled = optional(environment, 'RUNNER_DISK_EXPANSION_ENABLED')
  const cap = optional(environment, 'RUNNER_DISK_EXPANSION_CAP_GIB')
  if (enabled !== null) flag(environment, 'RUNNER_DISK_EXPANSION_ENABLED')
  return {
    ...(enabled ? { RUNNER_DISK_EXPANSION_ENABLED: enabled } : {}),
    ...(cap ? { RUNNER_DISK_EXPANSION_CAP_GIB: cap } : {}),
  }
}

function filestoreProjectsFrom(raw: string | undefined, home: Cloud): string[] {
  if (home !== 'gcp' || !raw) return []

  try {
    return [...new Set(parseFilestoreInstances({ FILESTORE_INSTANCES: raw }).map((entry) => entry.projectId))].sort()
  } catch (error) {
    if (error instanceof FilestoreConfigurationError) {
      throw new ApiEnvironmentError(error.message)
    }
    throw error
  }
}

/**
 * The two channels the API reads, assembled from one stage's configuration.
 *
 * `region` is here because the object-storage endpoints are regional and the
 * API composes S3 and STS URLs from them; `stage` because the status sync's
 * alert identity is per stage. Neither is read from an ambient variable —
 * mstage already resolved both, and asking again is a second answer.
 */
export const apiEnvironmentFrom = ({
  environment,
  declaration,
  region,
  stage,
  home,
}: {
  environment: Environment
  declaration: GroupDeclaration
  region: string
  stage: string
  home: Cloud
}): { environment: Record<string, string>; secrets: Record<string, string>; filestoreProjects: string[] } => {
  const domain = optional(environment, 'STACK_DOMAIN')
  if (!domain) throw new ApiEnvironmentError('STACK_DOMAIN is required — every URL the API composes starts with it')
  const hosts = publicHostsFor({ domain, dashboardDomain: optional(environment, 'DASHBOARD_DOMAIN') })

  // The API's own group, before it is split by channel. Read once: `held`
  // below asks whether a credential arrived, and asking the raw environment
  // would miss one delivered as an address.
  const delivered = serviceSecretsFrom({ group: API_GROUP, declaration, environment })
  if (delivered.TURNSTILE_SITEKEY) {
    for (const key of ['TURNSTILE_SECRET_KEY', 'TURNSTILE_EXPECTED_HOSTNAMES']) {
      if (!delivered[key]) throw new ApiEnvironmentError(`${key} is required when TURNSTILE_SITEKEY is set`)
    }
  } else {
    for (const key of Object.keys(delivered)) {
      if (key.startsWith('TURNSTILE_')) delete delivered[key]
    }
  }
  const { values, addresses } = splitServiceChannels({ delivered, declaration, home })
  validateCiChannels(values, addresses)
  const configuredFilestoreInstances = environment.FILESTORE_INSTANCES?.trim()
  const filestoreInstances = configuredFilestoreInstances ?? (home === 'gcp' ? '[]' : undefined)
  const filestoreProjects = filestoreProjectsFrom(filestoreInstances, home)
  const apiValues =
    home === 'gcp'
      ? values
      : Object.fromEntries(Object.entries(values).filter(([key]) => key !== 'FILESTORE_INSTANCES'))

  return {
    filestoreProjects,
    environment: {
      // Constant on every deployed stage. The per-stage identity is the stage
      // name, which is what the status sync's dedup prefix uses.
      ENVIRONMENT: 'production',
      POSTHOG_ENVIRONMENT: stage,
      CLOUD_APP_PROCESS_ROLE: 'api',
      CLOUD_APP_PUBLIC_URL: `https://${hosts.api}/api/internal/apps`,
      ...(optional(environment, 'STACK_USER_DOMAIN')
        ? { CLOUD_APP_DOMAIN: optional(environment, 'STACK_USER_DOMAIN') as string }
        : {}),
      /*
       * The API applies its own schema at boot, on both clouds.
       *
       * Carried over from the incumbent stack (`stack/api.ts`), which sets it
       * unconditionally and always has. Dropping it in the port was invisible
       * against a database that already had a schema and fatal against one that
       * did not: the first deploy of a new stage comes up, connects, and exits
       * on `42P01 undefined_table` with nothing in the deploy having failed.
       */
      RUN_MIGRATIONS: 'true',
      /*
       * The container still requires `PORT`; only the channel differs.
       *
       * Cloud Run sets it itself, from the container port the service declares,
       * and refuses a revision that also declares it — `template.containers[0].
       * env: The following reserved env names were provided: PORT`, as a 400
       * before anything is created. ECS reserves nothing, so on AWS this is the
       * only thing that tells the task which port to listen on.
       */
      ...(home === 'aws' ? { PORT: String(API_PORT) } : {}),
      S3_REGION: region,
      /*
       * Which object store backs a managed volume. The API creates the bucket
       * the runner mounts, so the two have to name the same backend — which is
       * why this and the runner's own variable come from one decision, and why
       * only the GCP branch names anything.
       *
       * The API that reads these is not on this branch either: the GCS store is
       * #1468, and here the control plane builds an S3 client unconditionally,
       * so both variables are inert until it lands.
       *
       * GCS_LOCATION is the stage's own region. A bucket created without one
       * lands wherever the client defaults to, away from the runners that mount
       * it, and every file a box touches becomes a cross-region read.
       */
      ...(home === 'gcp' ? { VOLUME_STORAGE_BACKEND: 'gcs', GCS_LOCATION: region } : {}),
      FILESTORE_SUPPORTED: home === 'gcp' ? 'true' : 'false',
      ...(home === 'gcp' && filestoreInstances !== undefined ? { FILESTORE_INSTANCES: filestoreInstances } : {}),
      // On unless the stage says otherwise, and it says so through the api
      // group's own `OTEL_ENABLED`, which `...values` below lets win. There is
      // no second switch: an inverted one read here would come from whatever
      // shell ran the deploy, since no group can fetch it.
      OTEL_ENABLED: 'true',
      ...dashboardFrom(environment, hosts),
      ...oidcFrom(environment, hosts),
      ...billingFrom(environment, delivered),
      ...statusSyncFrom(environment, delivered, stage),
      ...systemImagesFrom(environment),
      ...runnerDiskExpansionFrom(environment),
      ...(optional(environment, 'POSTHOG_HOST')
        ? { POSTHOG_HOST: optional(environment, 'POSTHOG_HOST') as string }
        : {}),
      ...(optional(environment, 'SVIX_SERVER_URL')
        ? { SVIX_SERVER_URL: optional(environment, 'SVIX_SERVER_URL') as string }
        : {}),
      ...(optional(environment, 'BOX_MIGRATION_ARCHIVE_PREFIX')
        ? { BOX_MIGRATION_ARCHIVE_PREFIX: optional(environment, 'BOX_MIGRATION_ARCHIVE_PREFIX') as string }
        : {}),
      ...(optional(environment, 'DEFAULT_REGION_ID')
        ? { DEFAULT_REGION_ID: optional(environment, 'DEFAULT_REGION_ID') as string }
        : {}),
      ...(optional(environment, 'DEFAULT_TEMPLATE')
        ? { DEFAULT_TEMPLATE: optional(environment, 'DEFAULT_TEMPLATE') as string }
        : {}),
      /*
       * The first runner's registered name, which the API seeds at boot.
       *
       * One of two things the API and the runner module have to agree about,
       * and the only one composed here. The other is the token: the API seeds
       * that runner row's `apiKey` from `DEFAULT_RUNNER_API_KEY`, and the host
       * presents the same value as `BOXLITE_RUNNER_TOKEN` — pairing is
       * token-based, so a row seeded from a different value authenticates
       * nobody. That key reaches this service through the `api` group like any
       * other secret, which is why it is not named here; `stack/runners.ts`
       * says why the host reads it under another name.
       */
      DEFAULT_RUNNER_NAME: optional(environment, 'DEFAULT_RUNNER_NAME') ?? 'default',
      // The API's own group, as values. Last, so a name the store holds wins
      // over a default composed above — and `stack/index.ts` refuses any name
      // that a module also decides.
      ...apiValues,
    },
    secrets: addresses,
  }
}

/**
 * Whether a key reaches the API by reference on this stage.
 *
 * Exported for the composition root's benefit rather than used here: it is the
 * one question a caller asks that this module can answer without re-deriving
 * the split.
 */
export const isAddress = (declaration: GroupDeclaration, key: string): boolean =>
  (declaration.groups[SECRET_GROUP] ?? []).includes(key)