cloud / internal-packages / cloud-clients / scripts / production-clients.tsmain at aacbc74
// scripts/production-clients.ts — THE PRODUCTION CLOUD'S CLIENTS, made from iterate's existing apps
// at GitHub, Google, X and Slack: the ones os.iterate.com uses, whose values production's Doppler
// config holds (`ITERATE`, its `integrations`, and `ITERATE__INTEGRATIONS__X`, whose optional
// `appBearerToken` is the X app's app-only Bearer Token for public post subscriptions). It writes
// one file for `wrangler secret bulk`, with `CLOUD_CLIENTS` and `CLOUD_CLIENT_SECRETS`, and prints
// the clients' names and nothing else. From internal-packages/installer:
//
// doppler run --project os --config prd --only-secrets ITERATE --only-secrets ITERATE__INTEGRATIONS__X -- \
// node <this file> --out <file> [--clients github,google,x,slack] [--pass-on https://os.iterate.com] \
// [--gmail-push <topic>,<the push subscription's address>,<its service account>]
// pnpm exec wrangler secret bulk <file> -c wrangler.jsonc --env prd && rm <file>
//
// `--gmail-push` names what was made in Google's console for Gmail's push (README.md, "Gmail's
// push"): the Pub/Sub topic in the OAuth client's own project, the address its one push
// subscription delivers to (which is also the audience of its token), and the service account the
// subscription signs as. All three or none: the Cloud takes no push from a client that does not
// name all of them. The token's issuer and the address of its keys are never written here: they
// are Google's own, and only a fake on dev names others.
//
// A RUN WRITES ALL OF `CLOUD_CLIENTS`, and nothing records the flags of the last one. A run that
// leaves out `--gmail-push` ends Gmail's push; one that leaves out `--pass-on` ends the passing on.
// The live `/.well-known/iterate-cloud` shows the topic (`gmailTopic`), not the subscription's
// service account, which is in Google's console (Pub/Sub, the push subscription). Before the
// bulk, compare the file's `CLOUD_CLIENTS` with the live document: only what you meant may differ.
//
// `--pass-on` names the platform these apps served before the Cloud, which keeps working: a
// callback the Cloud did not begin is sent to it, and every webhook delivery is also sent on to
// it, unchanged (src/worker.ts `passOn`). Leave it out until the Worker that understands it is
// deployed.
import { createPrivateKey } from "node:crypto";
import { writeFileSync } from "node:fs";
import { parseArgs } from "node:util";
const { values } = parseArgs({
options: {
out: { type: "string" },
clients: { type: "string", default: "github,google,x" },
"pass-on": { type: "string" },
"gmail-push": { type: "string" },
},
});
if (!values.out) throw new Error("usage: production-clients.ts --out <file>");
const { integrations } = JSON.parse(process.env.ITERATE!);
const { github, google, slack } = integrations;
const x = JSON.parse(process.env.ITERATE__INTEGRATIONS__X!);
const passOn = values["pass-on"] && new URL(values["pass-on"]).origin;
const [topic = "", audience = "", serviceAccount = ""] = (values["gmail-push"] || "").split(",");
const gmailPushNamed =
/^projects\/[^/]+\/topics\/[^/]+$/.test(topic) &&
/^https:\/\/[^/]+\/clients\/google\/webhook$/.test(audience) &&
/^[^@\s]+@[^@\s]+\.iam\.gserviceaccount\.com$/.test(serviceAccount);
if (values["gmail-push"] && !gmailPushNamed)
throw new Error(
"--gmail-push is projects/<id>/topics/<topic>,https://<cloud>/clients/google/webhook,<name>@<id>.iam.gserviceaccount.com",
);
/** os.iterate.com's own address for a provider's callback or webhook (core/os src/integrations). */
const there = (provider: string, route: string) =>
`${passOn}/api/integrations/${provider}/${route}`;
const clients = {
github: {
kind: "github",
clientId: github.oauthClientId,
authorizationEndpoint: "https://github.com/login/oauth/authorize",
tokenEndpoint: "https://github.com/login/oauth/access_token",
api: "https://api.github.com",
urls: ["https://api.github.com", "https://github.com"],
appId: github.appId,
installUrl: `https://github.com/apps/${github.appSlug}/installations/new`,
...(passOn && {
passOn: { callback: there("github", "callback"), webhook: there("github", "webhook") },
}),
},
google: {
kind: "google",
clientId: google.oauthClientId,
// offline and consent: Google hands out a refresh token only then
authorizationEndpoint:
"https://accounts.google.com/o/oauth2/v2/auth?access_type=offline&prompt=consent",
tokenEndpoint: "https://oauth2.googleapis.com/token",
api: "https://www.googleapis.com",
urls: [
"https://gmail.googleapis.com",
"https://www.googleapis.com",
"https://docs.googleapis.com",
],
// mail and the calendar by default, of the scopes the client's consent screen is verified for
// (Google shows its normal consent page for each); a connect that wants more names its own
// (a mind's cloud-scopes.ts): Drive is on www.googleapis.com, Docs on docs.googleapis.com
scopes: [
"openid",
"https://www.googleapis.com/auth/userinfo.email",
"https://www.googleapis.com/auth/gmail.modify",
"https://www.googleapis.com/auth/gmail.send",
"https://www.googleapis.com/auth/gmail.labels",
"https://www.googleapis.com/auth/calendar",
],
...(gmailPushNamed && { gmailPush: { topic, audience, serviceAccount } }),
},
x: {
kind: "x",
clientId: x.oauthClientId,
authorizationEndpoint: "https://x.com/i/oauth2/authorize",
tokenEndpoint: "https://api.x.com/2/oauth2/token",
api: "https://api.x.com",
urls: ["https://api.x.com"],
scopes: ["tweet.read", "users.read", "dm.read", "offline.access"],
},
slack: {
kind: "slack",
clientId: slack.oauthClientId,
authorizationEndpoint: "https://slack.com/oauth/v2/authorize",
tokenEndpoint: "https://slack.com/api/oauth.v2.access",
api: "https://slack.com",
// files.slack.com serves a shared file's download
urls: ["https://slack.com", "https://files.slack.com"],
// The bot scopes iterate's Slack app is registered with (core/os iterate-config.ts
// DEFAULT_SLACK_BOT_SCOPES), as ONE element: Slack reads a comma-separated list, and a vault
// joins a client's scopes with spaces.
scopes: [
[
"channels:history",
"channels:join",
"channels:manage",
"channels:read",
"chat:write",
"chat:write.public",
"files:read",
"files:write",
"groups:history",
"groups:read",
"im:history",
"im:read",
"im:write",
"mpim:history",
"mpim:read",
"reactions:read",
"reactions:write",
"users.profile:read",
"users:read",
"users:read.email",
"assistant:write",
"conversations.connect:write",
// not in core/os's list, and needed for the `app_mention` event the app subscribes to
"app_mentions:read",
].join(","),
],
...(passOn && {
passOn: {
callback: there("slack", "callback"),
webhook: there("slack", "webhook"),
"interactivity-webhook": there("slack", "interactivity-webhook"),
},
}),
},
};
const secrets = {
github: {
clientSecret: github.oauthClientSecret,
webhookSecret: github.webhookSecret,
// GitHub hands out PKCS#1; the Cloud signs with WebCrypto, which takes PKCS#8
appPrivateKey: createPrivateKey(github.privateKey).export({ type: "pkcs8", format: "pem" }),
},
google: { clientSecret: google.oauthClientSecret },
x: {
clientSecret: x.oauthClientSecret,
// not in Doppler: no field once JSON writes it, and no public post subscriptions
bearerToken: x.appBearerToken,
},
slack: { clientSecret: slack.oauthClientSecret, webhookSecret: slack.webhookSigningSecret },
};
const names = values.clients!.split(",").map((name) => name.trim());
const only = <T>(all: Record<string, T>) =>
Object.fromEntries(
names.map((name) => {
if (!all[name]) throw new Error(`no client named ${name}`);
return [name, all[name]];
}),
);
writeFileSync(
values.out,
JSON.stringify({
CLOUD_CLIENTS: JSON.stringify(only(clients)),
CLOUD_CLIENT_SECRETS: JSON.stringify(only(secrets)),
}),
{ mode: 0o600 },
);
console.log(
`wrote ${names.join(", ")}${passOn ? `, passed on to ${passOn}` : ""}${gmailPushNamed ? `, Gmail's push on ${topic}` : ""}`,
);