iterate.com / kernel

git clone https://git.iterate.com/repos/kernel

kernel / core / alchemy / src / config.tsmain at 949894f

// config.ts — THE ONE INPUT of the stack (./stack.ts): what `iterate deploy` learned from
// the person and from Cloudflare. A JSON file, named in ITERATE_MIND_CONFIG. No field is optional
// for a reason of history, and no variable of the environment changes what it means.
import { readFileSync } from "node:fs";
import { domainOfOwnerEmailPattern, OwnerEmailPattern } from "iterate/mind-config";
import { z } from "zod";

const hostname = z
  .string()
  .toLowerCase()
  .regex(/^(?=.{4,253}$)([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/, "a hostname");

const repoPath = z.string().regex(/^\/repos\/[a-z0-9][a-z0-9-]*$/, "a repo path: /repos/<name>");

export const MindConfig = z
  .strictObject({
    /** The mind's id: the SHA-256 of its signed genesis, 64 lowercase hex characters
     *  (iterate/mind-identity). `iterate deploy` signs the genesis before the deploy and posts it
     *  after: the stack does no identity cryptography. */
    mindId: z.string().regex(/^[0-9a-f]{64}$/, "a mind id: 64 lowercase hex characters"),
    /** Where the mind's control plane answers: its sign-in, its API and its MCP server. A zone of
     *  the mind, or one label under one. Every other hostname of the zones is the mind's own. */
    controlPlaneHostname: hostname,
    /** The mind's owners, each by email address: a member from the first deploy, who signs in
     *  with a code mailed to that address and then adds a passkey. An owner may remove another
     *  member's passkeys. Members added later are in the mind, not here. */
    ownerEmails: z.array(z.email().toLowerCase()).min(1),
    /** MORE OWNERS, BY PATTERN: each `*@<domain>` makes every address at exactly that domain an
     *  owner, with all that an owner may do (iterate/mind-config `isOwnerEmail`). Such a person
     *  proves the address through Cloudflare Access, as any owner does, and then adds a passkey:
     *  so whoever holds a mailbox at the domain, or runs its mail, can become an owner. Name a
     *  domain only when its mail is the company's own. A person who left keeps the passkey they
     *  added: an owner's block of that address on `/members` ends that one person
     *  (core/auth-worker/src/members.ts `isMember`). Absent: no pattern. */
    ownerEmailPatterns: z.array(OwnerEmailPattern).optional(),
    /** The method of the config worker's class that answers the mind's part of its own MCP
     *  server (iterate/mind-config `mcpTarget`): "mcp" in the default config. Absent: the
     *  platform's defaults answer. */
    mcpTarget: z.string().optional(),
    /** Where the mind Worker runs: in the stack, or elsewhere, connecting in through the
     *  boundary. */
    topology: z.enum(["full-cloudflare", "external-mind-connects-into-cloudflare-boundary"]),
    /** THE REPOS THAT A DEPLOY NAMES FOR THE MIND, each directly under `/repos`: the kernel's
     *  and the one that holds the mind's code. At its first wake the mind makes each one that it
     *  does not have yet: one with an `origin` is cloned from that public git URL, with its
     *  history, and one whose `origin` is null is made empty and gets its first commit by a
     *  push. The mind's other repos are named by the entry repo's own package.json, and the mind
     *  clones those at its birth from beside the entry repo's origin. A later deploy never
     *  touches a repo that exists. The stack also asks Cloudflare to tell the mind of every push
     *  to one of the repos listed here; a push to any other reaches the mind through its own git
     *  app, which says so. */
    repos: z
      .array(z.strictObject({ path: repoPath, origin: z.url().nullable() }))
      .min(1),
    /** THE MIND'S CODE: `module` of the repo `repo`, one of `repos`, answers every request, mail
     *  and event. It names a file of another repo as `@repos/<repo>/<path>`. */
    entry: z.strictObject({ repo: repoPath, module: z.string().min(1) }),
    alchemy: z.strictObject({
      /** The Alchemy stage, and the middle of every resource's name: `iterate-<stageName>-auth`.
       *  `iterate deploy` infers it from the first zone. At most 32 characters: the state store's
       *  name, `iterate-<stageName>-state`, may have 54. */
      stageName: z.string().regex(/^[a-z][a-z0-9-]{0,31}$/, "lower case, digits and -, at most 32"),
    }),
    cloudflare: z.strictObject({
      accountId: z.string().regex(/^[0-9a-f]{32}$/, "a Cloudflare account id: 32 hex characters"),
      /** The zones the mind takes, each whole: its sites, its mail. `sub.example.com` when that
       *  is a zone of its own. Nothing else may use them. */
      zones: z.array(hostname).min(1),
      /** An image in the account's registry that sandboxes start. Absent: Cloudflare's own small
       *  image. Only iterate's own mind sets it. */
      containerImage: z.string().min(1).optional(),
      /** THE STACK'S EGRESS GATEWAY: a Worker of this account, by name. The vault and the
       *  boundary get it as `EGRESS_GATEWAY` and send through its fetch, with no other way out
       *  (iterate/lib `fetchLeavingTheStack`), each request with its secret in. So whoever deploys
       *  names it, and nothing in a mind can. One gateway Worker serves one stack.
       *    - THROUGH IT: what a mind sends by `itx.fetch` to a host outside its zones (a script,
       *      an agent, loaded code, a sandbox), with a secret or without; a secret's token
       *      refresh and its exchange code; a request signed for another mind.
       *    - NOT THROUGH IT: the vault's calls to an iterate Cloud; the auth, mind and telemetry
       *      Workers' own fetches (other minds' identity, module downloads, Git, Cloudflare's
       *      API); the managed bindings (AI, Browser, Images, mail).
       *  Absent: no binding, and the platform's fetch sends. */
      egressGatewayWorker: z.string().min(1).optional(),
    }),
    /** A FORWARD BY THE STACK, beside the forwards that the mind's config asks for by event
     *  (iterate/email `email/forward-requested`). Absent: the config's requests alone decide
     *  where a mail goes. `forwardTo`: each mail is also forwarded there as it arrived (a team's
     *  mailbox or group), before the config's requests. The address must be a verified destination address of the
     *  account's Email Routing, which a person confirms once by the link Cloudflare mails to it. */
    mail: z.strictObject({ forwardTo: z.email() }).optional(),
    /** THE MIND'S TELEMETRY in Cloudflare's own store. `traceSampling` is the share of requests
     *  whose trace Cloudflare keeps, for every Worker of the stack, from 0 (no trace) to 1 (each
     *  one): the head sampling rate of Workers traces
     *  (https://developers.cloudflare.com/workers/observability/traces/). Log lines are always
     *  kept whole. Absent: 1, every trace. `iterate deploy --trace-sampling` sets it. */
    telemetry: z.strictObject({ traceSampling: z.number().min(0).max(1) }).optional(),
  })
  // One label, because Cloudflare's certificate for a zone covers the zone and `*.<zone>` alone.
  .refine(
    ({ controlPlaneHostname, cloudflare }) =>
      cloudflare.zones.some(
        (zone) =>
          controlPlaneHostname === zone ||
          controlPlaneHostname.split(".").slice(1).join(".") === zone,
      ),
    {
      path: ["controlPlaneHostname"],
      error:
        "a zone of the mind, or one label under one: Cloudflare's certificate for a zone covers the zone and *.<zone> alone, so a deeper name would get a route and no certificate",
    },
  )
  .refine(({ repos, entry }) => repos.some((repo) => repo.path === entry.repo), {
    path: ["entry", "repo"],
    error: "one of repos: the mind cannot load code from a repo it is not born with",
  })
  .refine(
    ({ ownerEmails, cloudflare }) =>
      ownerEmails.every((email) =>
        cloudflare.zones.every((zone) => !`.${email.split("@")[1]}`.endsWith(`.${zone}`)),
      ),
    {
      path: ["ownerEmails"],
      error: "no address at a zone of the mind: the mind takes that mail",
    },
  )
  .refine(
    ({ ownerEmailPatterns, cloudflare }) =>
      (ownerEmailPatterns || []).every((pattern) =>
        cloudflare.zones.every(
          (zone) => !`.${domainOfOwnerEmailPattern(pattern)}`.endsWith(`.${zone}`),
        ),
      ),
    {
      path: ["ownerEmailPatterns"],
      error: "no pattern at a zone of the mind: the mind takes that mail",
    },
  )
  .refine(
    ({ mail, cloudflare }) =>
      !mail ||
      cloudflare.zones.every(
        (zone) => !`.${mail.forwardTo.split("@")[1]}`.toLowerCase().endsWith(`.${zone}`),
      ),
    {
      path: ["mail", "forwardTo"],
      error:
        "not an address at a zone of the mind: its mail comes to the mind, so the forward would come back",
    },
  );
export type MindConfig = z.infer<typeof MindConfig>;

/** The config of this deploy, from the JSON file that ITERATE_MIND_CONFIG names. */
export function loadMindConfig(): MindConfig {
  const file = process.env.ITERATE_MIND_CONFIG;
  if (!file)
    throw new Error("ITERATE_MIND_CONFIG names no file: the stack has one input, its config");
  return MindConfig.parse(JSON.parse(readFileSync(file, "utf8")));
}

/** Every name the stack gives a resource of the account. */
export const namesOf = ({ alchemy }: { alchemy: { stageName: string } }) => {
  const prefix = `iterate-${alchemy.stageName}`;
  return {
    state: `${prefix}-state`,
    auth: `${prefix}-auth`,
    authDb: `${prefix}-auth-db`,
    authKv: `${prefix}-auth-kv`,
    secrets: `${prefix}-secrets`,
    realtimeSfu: `${prefix}-realtime-sfu`,
    turnKey: `${prefix}-turn`,
    mind: `${prefix}-mind`,
    mindKv: `${prefix}-mind-kv`,
    files: `${prefix}-files`,
    repos: `${prefix}-repos`,
    boundary: `${prefix}-boundary`,
    cloudflareEvents: `${prefix}-events`,
    telemetry: `${prefix}-telemetry`,
    telemetryBucket: `${prefix}-telemetry`,
    // Analytics Engine and Pipelines take no `-` in a name
    telemetryMetrics: `${prefix.replaceAll("-", "_")}_metrics`,
    telemetryTables: `${prefix.replaceAll("-", "_")}_telemetry`,
  };
};