iterate.com / cloud

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

cloud / internal-packages / cloud-clients / scripts / dev-petshop.tsmain at aacbc74

// scripts/dev-petshop.ts — THE DEV CLOUD'S GITHUB APP AT THE PET SHOP'S FAKE. The dev Cloud's
// clients point at the fakes (internal-packages/dummy-petshop), where a GitHub App installation is
// a registration that the shop drops once enough newer ones exist. This registers it again, from
// the same three secrets the Worker runs with, so nothing about the Cloud changes:
//
//   op run --env-file <dev.env> -- node internal-packages/cloud-clients/scripts/dev-petshop.ts <cloud origin>
//
// Then `fire <deployment's account>` asks the shop to deliver one webhook to the Cloud, signed as
// GitHub signs: the repeatable check that a delivery reaches a deployment.
import { createPublicKey } from "node:crypto";

const [origin, command] = process.argv.slice(2);
if (!origin) throw new Error("usage: dev-petshop.ts <cloud origin> [fire]");
const { github } = JSON.parse(process.env.CLOUD_CLIENTS!);
const secrets = JSON.parse(process.env.CLOUD_CLIENT_SECRETS!).github;
const install = new URL(github.installUrl);
const installationId = install.searchParams.get("installation_id")!;
const login = new URL(github.authorizationEndpoint).searchParams.get("login")!;

const shop = async (path: string, body: unknown) => {
  const answer = await fetch(new URL(path, github.api), {
    method: "POST",
    headers: { "content-type": "application/json" },
    body: JSON.stringify(body),
  });
  if (!answer.ok) throw new Error(`the pet shop answered ${answer.status} for ${path}`);
  return answer.json();
};

if (command === "fire") {
  const delivered = await shop("/__test-controls/apps/fire-webhook", {
    installationId,
    url: `${origin}/clients/github/webhook`,
    eventName: "ping",
    event: {
      zen: "A webhook through iterate Cloud.",
      installation: { id: Number(installationId) },
    },
  });
  console.log(JSON.stringify(delivered));
} else {
  await shop("/__test-controls/apps", {
    publicKeyPem: createPublicKey(secrets.appPrivateKey).export({ type: "spki", format: "pem" }),
    appId: github.appId,
    installationId,
    webhookSecret: secrets.webhookSecret,
    appSlug: install.pathname.split("/")[2],
    callbackUrl: `${origin}/clients/github/callback`,
    account: { login: `${login}-org`, type: "Organization" },
    users: [{ login, role: "admin" }],
    oauthClientId: github.clientId,
  });
  console.log(`registered installation ${installationId} of app ${github.appId} for ${login}`);
}