iterate.com / cloud

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

cloud / internal-packages / installer / worker / service.jsmain at aacbc74

// service.js — WHAT THE CLOUD'S APP MAY ASK OF THIS WORKER. The Cloud's chat and its installation
// agent are an app in the iterate mind (userspace): that app talks to anybody, so it holds no
// Cloudflare token, no client secret and no signing key. This Worker holds them, and the app
// reaches it through the few operations below, each with one fixed effect. The app calls the
// same operations (`operations`) in one of two ways:
//
// - The `Service` entrypoint (main.js), which the mind's stack binds and calls as
//   `itx.services.cloud.<method>(…)`; the mind Worker puts who calls first
//   (iterate/principal `ServiceCaller`), and the method refuses any mind but SERVICE_MIND.
// - The bearer routes below, for SERVICE_TOKEN's holder.
//
//   method (Service)        route (bearer)
//   installationCreate      POST  /service/installations                 `{ deployment, owner: { email, userId } }`:
//                                                 the installation of one of the app's
//                                                 deployments, the same one on every call; at
//                                                 most MAX_PER_OWNER for one owner
//   installationStatus      GET   /service/installations/:id             its status (installation.js `statusOf`)
//   installationChoose      PATCH /service/installations/:id/choices     name, account, domain, owner email, telemetry
//   installationLink        POST  /service/installations/:id/links       `{ kind }` (`owner-link` is
//                                                 `owner`): a single-use link to a page of the
//                                                 Cloud's own (index.js `/i/*`), for a button
//   installationPoke        POST  /service/installations/:id/poke        look at the waits now
//   installationResources   GET   /service/installations/:id/resources   what the deploy made, from its log
//   deploymentAt            GET   /service/installation?domain=          what the Cloud itself knows of the
//                                                 deployment at a domain: `{ enrolled, handedOver }`
//   handover                POST  /service/handover                      `{ deployment | installation, summary }`:
//                                                 hands the finished installation to the
//                                                 deployment's onboarding agent, once (access.js
//                                                 `handOver`)
//   installationDeployedAt  POST  /service/installations/:id/deployed    `{ domain }`: ties an enrolled
//                                                 deployment made elsewhere (the app's own
//                                                 Alchemy run) to the installation, so that the
//                                                 handover can go to it
//   ownerInstallations      GET   /service/installations?owner=          `{ email }`: the ids of an owner's
//                                                 installations at this mind
//   installationForget      DELETE /service/installations/:id            forgets an installation with
//                                                 no running phase, and frees the owner's place;
//                                                 the deployment is not touched
//   enrol                   POST  /service/enrol                         `{ domain }`: the Cloud enrols the
//                                                 deployment (access.js `enrol`): `{ ok, key }`
//   cloudKey                GET   /service/cloud-key                     the key a deployment trusts the
//                                                 Cloud by (access.js `trustOf`): `{ keys }`
//   forgetEnrolment         POST  /service/forget-enrolment              `{ domain }`: forgets the
//                                                 enrolment of a deployment that is gone (access.js
//                                                 `isGone`)
//
// A method names the installation by `{ deployment }` or `{ installation }`.
//
// No operation answers a token, a ticket or a key, and none takes an address to call: the
// deployment is always `iterate.<domain>` of the domain of an installation the Cloud deployed and
// enrolled. Whatever spends the person's money, picks for them, or gives the owner's ticket is a
// page that their own browser opens, never an operation here.
//
// The caller is one app, of one mind: SERVICE_MIND (a var, "iterate.com" when unset) names it,
// and an installation is that mind's deployment. The consent must come from the Cloudflare user
// with the owner's email (index.js `installationConsent`).
//
// Bindings: SERVICE_TOKEN (secret), the bearer: without it every route here answers 404.
// CLOUD_ORIGIN (var), this Worker's public origin, for the links and the enrolment of a Service
// call, which has no request to read it from. A browser never calls the routes: a request that
// carries `Origin` or a cookie is refused, so no page can make a signed-in person's browser send
// one.
import { z } from "zod";
import { enrol, forget, handOver, isGone, mindAt, same, trustOf } from "./access.js";
import { INSTALLATION_ID, MAX_PER_OWNER, installationIdOf } from "./installation.js";

const DOMAIN = /^[a-z0-9-]+(\.[a-z0-9-]+)+$/;
const json = (value, status = 200) =>
  new Response(JSON.stringify(value), {
    status,
    headers: { "content-type": "application/json", "cache-control": "no-store" },
  });
const notFound = () => new Response("Not found\n", { status: 404 });

const DEPLOYMENT = z.string().regex(/^[A-Za-z0-9_-]{1,64}$/);
const NewInstallation = z.object({
  deployment: DEPLOYMENT,
  owner: z.object({
    email: z
      .string()
      .trim()
      .toLowerCase()
      .regex(/^[^@\s]+@[^@\s]+\.[^@\s]+$/)
      .max(200),
    userId: z.string().min(1).max(200),
  }),
});
const Choices = z
  .object({
    name: z.string(),
    accountId: z.string(),
    domain: z.object({ zone: z.string() }).nullable(),
    ownerEmail: z.string(),
    telemetry: z.boolean(),
    cloudflareConnection: z.boolean(),
  })
  .partial()
  .strict();
const LinkAsked = z.object({ kind: z.string() });
const Named = z
  .object({
    deployment: DEPLOYMENT.optional(),
    installation: z.string().regex(INSTALLATION_ID).optional(),
  })
  .refine((body) => body.deployment || body.installation, {
    message: "name the deployment",
    path: ["deployment"],
  });
const OwnerAsked = z.object({ email: NewInstallation.shape.owner.shape.email });
const DomainAsked = z.object({ domain: z.string().regex(DOMAIN, "not a domain") });
const HandoverAsked = z
  .object({
    deployment: DEPLOYMENT.optional(),
    installation: z.string().regex(INSTALLATION_ID).optional(),
    summary: z.unknown(),
  })
  .refine((body) => body.deployment || body.installation, {
    message: "name the deployment",
    path: ["deployment"],
  });

/** The mind whose app may ask. */
const serviceMindOf = (env) => String(env.SERVICE_MIND || "iterate.com");

/** An operation's refusal: what the route answers, and the code a Service method throws. */
class Refusal extends Error {
  /** @param {number} status @param {string} message @param {string} [field] */
  constructor(status, message, field) {
    super(message);
    this.status = status;
    this.field = field;
  }
}

/** The installation's object (deploy-run.js `Deployer.install`). */
const installationStub = (env, id) => env.DEPLOYER.getByName(`inst:${id}`);
const ask = (env, id, op, args) => installationStub(env, id).install(op, args);

/** `value` as `schema` takes it, or a refusal naming the field at fault. */
function parsed(schema, value) {
  const result = schema.safeParse(value);
  if (result.success) return result.data;
  const issue = result.error.issues[0];
  const field = issue?.path?.[0];
  throw new Refusal(
    400,
    value === undefined
      ? "The body is JSON."
      : `${field ? `${String(field)}: ` : ""}${issue?.message || "not a valid body"}`,
    field === undefined ? undefined : String(field),
  );
}

/** Whether the Cloud enrolled the deployment at `zone`: null where this Cloud has no key (the
 *  pretend Cloud has none, and its deployments are stand-ins: they count as enrolled). */
async function enrolledAt(env, origin, zone, { enrol: tryEnrol = true } = {}) {
  if (env.CF_SITE) return true;
  if (!env.CLOUD_KEY) return null;
  if (await env.SESSIONS.get(`enrolled:${zone}`)) return true;
  if (!tryEnrol) return false;
  return !!(await enrol(env, origin, zone).catch(() => null))?.ok;
}

/** The operations of the app on `origin` (this Worker's), for `mind`. `asker`, when given, is
 *  noted in the installation's who-asked log (`Installation.noteAsker`). Each answers its value
 *  or throws a Refusal. */
function operations(env, origin, mind, asker) {
  const unrefused = (value) => {
    if (value?.refused)
      throw new Refusal(value.refused.status, value.refused.error, value.refused.field);
    return value;
  };
  /** The installation's id, after a check that it exists, and a note of who asked. */
  const existing = async (asked) => {
    const named = parsed(Named, asked);
    const id = named.installation ?? (await installationIdOf(mind, String(named.deployment)));
    const status = await ask(env, id, "status");
    if (!status) throw new Refusal(404, "No such installation.");
    if (asker) await ask(env, id, "noteAsker", asker);
    return { id, status };
  };
  /** The status with what the Worker knows of the deployment: whether it is enrolled. */
  const withEnrolment = async (id, status) => {
    unrefused(status);
    if (!status?.result) return status;
    const zone = await ask(env, id, "deployedZone");
    return {
      ...status,
      result: { ...status.result, enrolled: await enrolledAt(env, origin, zone) },
    };
  };

  return {
    async create(args) {
      const { deployment, owner } = parsed(NewInstallation, args);
      const installation = await installationIdOf(mind, deployment);
      const was = await ask(env, installation, "expectedUser");
      if (was && was.email !== owner.email)
        throw new Refusal(409, "That deployment has another owner.", "owner");
      const owners = env.DEPLOYER.getByName(`owner:${mind}:${owner.email}`);
      if (!was) {
        // one place per installation on the owner's own object; with no answer, nothing is made
        const slot = await owners.install("claimSlot", { id: installation }).catch(() => null);
        if (!slot) throw new Refusal(503, "The Cloud could not count the owner's installations.");
        if (!slot.ok)
          throw new Refusal(409, `An owner has at most ${MAX_PER_OWNER} installations.`, "owner");
      }
      const made = await ask(env, installation, "create", {
        id: installation,
        mind,
        deployment,
        owner,
      });
      if (made.refused) {
        // being forgotten: no installation of this id lives, so its place is nobody's
        if (!was) await owners.install("releaseSlot", { id: installation });
        unrefused(made);
      }
      if (made.email !== owner.email) {
        // another owner made it first: the place claimed for it goes back
        if (!was) await owners.install("releaseSlot", { id: installation });
        throw new Refusal(409, "That deployment has another owner.", "owner");
      }
      if (asker) await ask(env, installation, "noteAsker", asker);
      return { installation, deployment, created: made.created };
    },
    async status(named) {
      const { id } = await existing(named);
      return withEnrolment(id, await ask(env, id, "status"));
    },
    async choose(named, choices) {
      const { id } = await existing(named);
      return withEnrolment(id, await ask(env, id, "choose", parsed(Choices, choices)));
    },
    async link(named, asked) {
      const { id } = await existing(named);
      const body = parsed(LinkAsked, asked);
      const kind = body.kind === "owner-link" ? "owner" : body.kind;
      const link = unrefused(await ask(env, id, "link", kind));
      return { url: `${origin}/i/${id}/${kind}?n=${link.nonce}`, expiresAt: link.expiresAt };
    },
    async poke(named) {
      const { id } = await existing(named);
      return withEnrolment(id, await ask(env, id, "poke"));
    },
    async resources(named) {
      const { id } = await existing(named);
      return { resources: await ask(env, id, "resources") };
    },
    async deploymentAt(domain) {
      if (!DOMAIN.test(String(domain || ""))) throw new Refusal(400, "not a domain", "domain");
      const [enrolled, handover] = await Promise.all([
        env.SESSIONS.get(`enrolled:${domain}`),
        env.SESSIONS.get(`handover:${domain}`),
      ]);
      return {
        domain,
        enrolled: Boolean(enrolled),
        handedOver: Boolean(handover && JSON.parse(handover).accepted),
      };
    },
    async deployedAt(named, asked) {
      const { id } = await existing(named);
      const { domain } = parsed(DomainAsked, asked);
      // the deployment trusts the Cloud by its own config: it accepted a statement of the Cloud's key
      if (!(await enrolledAt(env, origin, domain, { enrol: false })))
        throw new Refusal(409, `${domain} is not enrolled: enrol it first.`, "domain");
      const zones = env.DEPLOYER.getByName(`zone:${domain}`);
      const claim = await zones.install("claimZone", { id });
      if (!claim.ok) throw new Refusal(409, `Another installation holds ${domain}.`, "domain");
      const tied = await ask(env, id, "deployedElsewhere", {
        zone: domain,
        by: asker ?? { call: "POST /service/installations/:id/deployed", via: "bearer" },
      });
      if (tied?.refused) await zones.install("releaseZone", { id });
      unrefused(tied);
      return withEnrolment(id, await ask(env, id, "status"));
    },
    async ownerInstallations(asked) {
      const { email } = parsed(OwnerAsked, asked);
      const installations = await env.DEPLOYER.getByName(`owner:${mind}:${email}`).install("slots");
      return { email, installations };
    },
    async forget(asked) {
      const named = parsed(Named, asked);
      const id = named.installation ?? (await installationIdOf(mind, String(named.deployment)));
      // a forget that stopped half way is finished by asking again: so no `existing` here
      const gone = unrefused(await ask(env, id, "forget"));
      await env.DEPLOYER.getByName(`owner:${gone.mind}:${gone.email}`).install("releaseSlot", {
        id,
      });
      if (gone.zone) {
        await env.DEPLOYER.getByName(`zone:${gone.zone}`).install("releaseZone", { id });
        // its handover goes with it: an installation made again may hand over again
        const handover = JSON.parse((await env.SESSIONS.get(`handover:${gone.zone}`)) || "null");
        if (handover?.installation === id) await env.SESSIONS.delete(`handover:${gone.zone}`);
      }
      await ask(env, id, "forgotten");
      return { ok: true, installation: id };
    },
    async enrol(asked) {
      const { domain } = parsed(DomainAsked, asked);
      if (!env.CLOUD_KEY) throw new Refusal(503, "This Cloud has no key to enrol with.");
      const result = await enrol(env, origin, domain);
      if (!result.ok) throw new Refusal(409, result.detail, "domain");
      // a deployment that just enrolled gets what the Cloud held for it (index.js does the same)
      await env.OUTBOX?.get(env.OUTBOX.idFromName(result.record.mind)).wake();
      return { ok: true, domain, key: result.record.key };
    },
    async cloudKey() {
      if (!env.CLOUD_KEY) throw new Refusal(503, "This Cloud has no key.");
      return { keys: await trustOf(env) };
    },
    async forgetEnrolment(asked) {
      const { domain } = parsed(DomainAsked, asked);
      if (!(await env.SESSIONS.get(`enrolled:${domain}`)))
        throw new Refusal(404, `${domain} is not enrolled.`, "domain");
      if (!(await isGone(await mindAt(env, domain))))
        throw new Refusal(
          409,
          `${domain} still answers, or did not answer in time: the Cloud forgets only a deployment that is gone (its key answers 404, or its host is gone).`,
          "domain",
        );
      await forget(env, domain);
      return { ok: true, domain };
    },
    async handover(args) {
      const body = parsed(HandoverAsked, args);
      const installation =
        body.installation ?? (await installationIdOf(mind, String(body.deployment)));
      if (asker && (await ask(env, installation, "status")))
        await ask(env, installation, "noteAsker", asker);
      // the domain is the installation's own, never the caller's
      const zone = await ask(env, installation, "deployedZone");
      if (!zone) throw new Refusal(409, "That installation has not deployed a mind.");
      const enrolled = await enrolledAt(env, origin, zone);
      if (!enrolled) throw new Refusal(409, "The deployment is not enrolled yet.");
      if (env.CF_SITE) {
        // the pretend Cloud: its deployment is a stand-in, with nobody to hand over to
        const ok =
          typeof body.summary === "string" && body.summary.trim() && body.summary.length <= 8_000;
        if (!ok) throw new Refusal(400, "The summary is text of 1 to 8000 characters.", "summary");
        return { ok: true, handover: `pretend-${installation}`, sent: false, pretend: true };
      }
      const result = await handOver(env, origin, zone, { installation, summary: body.summary });
      if (!result.ok) throw new Refusal(result.status, result.detail);
      return result;
    },
  };
}

export const handles = (url) => url.pathname.startsWith("/service/");

/** The request's JSON body: undefined when it is not JSON. */
const bodyOf = (request) => request.json().catch(() => undefined);

/** The answer of an operation, or of its refusal. */
async function answered(work, status = 200) {
  try {
    return json(await work(), status);
  } catch (error) {
    if (!(error instanceof Refusal)) throw error;
    // JSON leaves out a field that is undefined
    return json({ error: error.message, field: error.field }, error.status);
  }
}

export async function handle(request, env) {
  const url = new URL(request.url);
  if (!env.SERVICE_TOKEN) return notFound();
  if (request.headers.has("origin") || request.headers.has("cookie"))
    return json({ error: "this path is not for a browser" }, 403);
  const bearer = /^Bearer (.+)$/.exec(request.headers.get("authorization") || "")?.[1] || "";
  if (!(await same(bearer, env.SERVICE_TOKEN))) return json({ error: "not the app's token" }, 401);
  const ops = operations(env, url.origin, serviceMindOf(env));
  const route = `${request.method} ${url.pathname}`;

  if (route === "GET /service/installations")
    return answered(() =>
      ops.ownerInstallations({ email: url.searchParams.get("owner") ?? undefined }),
    );
  if (route === "POST /service/installations")
    return answered(async () => ops.create(await bodyOf(request)));

  const one = /^\/service\/installations\/(inst_[a-z2-7]{26})(\/[a-z]+)?$/.exec(url.pathname);
  if (one) {
    const [, id, rest = ""] = one;
    const named = { installation: id };
    switch (`${request.method} ${rest}`) {
      case "GET ":
        return answered(() => ops.status(named));
      case "PATCH /choices":
        return answered(async () => ops.choose(named, await bodyOf(request)));
      case "POST /links":
        return answered(async () => ops.link(named, await bodyOf(request)));
      case "POST /poke":
        return answered(() => ops.poke(named), 202);
      case "GET /resources":
        return answered(() => ops.resources(named));
      case "POST /deployed":
        return answered(async () => ops.deployedAt(named, await bodyOf(request)));
      case "DELETE ":
        return answered(() => ops.forget(named));
    }
    return notFound();
  }

  if (route === "GET /service/installation")
    return answered(() => ops.deploymentAt(String(url.searchParams.get("domain") || "")));
  if (route === "POST /service/handover")
    return answered(async () => ops.handover(await bodyOf(request)));
  if (route === "POST /service/enrol")
    return answered(async () => ops.enrol(await bodyOf(request)));
  if (route === "GET /service/cloud-key") return answered(() => ops.cloudKey());
  if (route === "POST /service/forget-enrolment")
    return answered(async () => ops.forgetEnrolment(await bodyOf(request)));
  return notFound();
}

// ── the Service entrypoint's methods (main.js `Service`) ───────────────────────────────────────

/** The code a refusal's status crosses Workers RPC as (iterate/lib `codedError`). */
const CODES = {
  400: "INVALID_INPUT",
  403: "FORBIDDEN",
  404: "NOT_FOUND",
  409: "CONFLICT",
  502: "UNAVAILABLE",
  503: "UNAVAILABLE",
};
const coded = (code, message, data) => Object.assign(new Error(message), { code, data });

/** Runs `work` with the operations of the mind that called, after the check that it may: the
 *  mind is SERVICE_MIND, and the call came through its `itx.services` (`caller`). A refusal
 *  crosses as a coded error with `data: { status, field }`. */
export async function serviceCall(env, caller, check, work) {
  const who = check(caller);
  if (who.mind !== serviceMindOf(env))
    throw coded(
      "FORBIDDEN",
      `The Cloud's service is for the mind ${serviceMindOf(env)}, not ${who.mind}.`,
    );
  if (!env.CLOUD_ORIGIN)
    throw coded("UNAVAILABLE", "The Cloud has no CLOUD_ORIGIN: its links would name no page.");
  const asker = {
    call: who.call,
    path: who.path,
    principal: who.principal ?? null,
    onBehalfOf: who.onBehalfOf?.principal ?? null,
  };
  try {
    return await work(
      operations(env, String(env.CLOUD_ORIGIN).replace(/\/$/, ""), who.mind, asker),
    );
  } catch (error) {
    if (!(error instanceof Refusal)) throw error;
    throw coded(CODES[error.status] || "UNAVAILABLE", error.message, {
      status: error.status,
      field: error.field,
    });
  }
}