The best way to control Claude Code, Codex and more from any computer or phone

main
ts 257 lines 8.95 KB
Raw
1 import * as Actions from "@distilled.cloud/github/actions";
2 import { isResolved } from "alchemy/Diff";
3 import * as Provider from "alchemy/Provider";
4 import { Resource } from "alchemy/Resource";
5 import * as Effect from "effect/Effect";
6 import * as Redacted from "effect/Redacted";
7 import { withBaseUrl, gitHubBaseUrlChanged } from "./BaseUrl.ts";
8 import { type Environment, resolveEnvironmentName } from "./Environment.ts";
9 import type * as GitHub from "./Providers.ts";
10
11 export interface SecretProps {
12 /**
13 * Repository owner (user or organization).
14 */
15 owner: string;
16
17 /**
18 * Repository name.
19 */
20 repository: string;
21
22 /**
23 * Secret name (e.g. `AWS_ROLE_ARN`).
24 */
25 name: string;
26
27 /**
28 * Secret value. Wrap with `Redacted.make` to prevent the value from
29 * appearing in logs or state.
30 */
31 value: Redacted.Redacted;
32
33 /**
34 * Optional environment. When set the secret is scoped to that GitHub
35 * Actions environment instead of the whole repository. Accepts an
36 * environment name or a `GitHub.Environment` resource.
37 */
38 environment?: string | Environment;
39
40 /**
41 * Override the GitHub host or API base URL for this resource only (e.g.
42 * `github.example.com` for GitHub Enterprise). Falls back to
43 * `GitHub.providers({ baseUrl })`, then to the host resolved by the auth
44 * provider. Changing it replaces the resource — the same name on a
45 * different GitHub instance is a different physical resource.
46 */
47 baseUrl?: string;
48 }
49
50 export interface Secret extends Resource<
51 "GitHub.Secret",
52 SecretProps,
53 {
54 /**
55 * ISO-8601 timestamp of the last update.
56 */
57 updatedAt: string;
58 },
59 never,
60 GitHub.Providers
61 > {}
62
63 /**
64 * A GitHub Actions repository or environment secret.
65 *
66 * `Secret` manages the lifecycle of an encrypted secret in GitHub Actions.
67 * Secrets are encrypted using the repository's (or environment's) public
68 * key via `libsodium` before being stored. The resource is idempotent —
69 * calling it with the same name will update the secret value in place.
70 *
71 * Authentication is resolved via the GitHub `Credentials` service supplied
72 * by `GitHub.providers()` (which uses the Alchemy AuthProvider — env,
73 * stored PAT, `gh` CLI, or OAuth). The token needs `repo` scope for
74 * private repositories or `public_repo` for public ones.
75 * ### Repository Secrets
76 * Store secrets accessible to all GitHub Actions workflows in the
77 * repository.
78 *
79 * **Example:** Create a Repository Secret
80 * ```typescript
81 * yield* GitHub.Secret("aws-role", {
82 * owner: "my-org",
83 * repository: "my-repo",
84 * name: "AWS_ROLE_ARN",
85 * value: Redacted.make(role.roleArn),
86 * });
87 * ```
88 *
89 * ### Environment Secrets
90 * Scope a secret to a specific GitHub Actions environment (e.g.
91 * `production`, `staging`). Environment secrets require environment
92 * protection rules to be satisfied before workflows can access them.
93 *
94 * **Example:** Create an Environment Secret
95 * ```typescript
96 * yield* GitHub.Secret("deploy-key", {
97 * owner: "my-org",
98 * repository: "my-repo",
99 * environment: "production",
100 * name: "DEPLOY_KEY",
101 * value: Redacted.make("my-secret-value"),
102 * });
103 * ```
104 *
105 * ### Wiring with Other Resources
106 * A common pattern is wiring the output of another resource — like an
107 * IAM role ARN or a database URL — directly into a GitHub secret so
108 * that CI workflows can use it.
109 *
110 * **Example:** Store an IAM Role ARN for CI
111 * ```typescript
112 * const role = yield* AWS.IAM.Role("ci-role", { ... });
113 *
114 * yield* GitHub.Secret("ci-role-arn", {
115 * owner: "my-org",
116 * repository: "my-repo",
117 * name: "AWS_ROLE_ARN",
118 * value: Redacted.make(role.roleArn),
119 * });
120 * ```
121 *
122 * **Example:** Store Multiple Secrets
123 * ```typescript
124 * yield* GitHub.Secret("db-url", {
125 * owner: "my-org",
126 * repository: "my-repo",
127 * environment: "production",
128 * name: "DATABASE_URL",
129 * value: Redacted.make(database.connectionString),
130 * });
131 *
132 * yield* GitHub.Secret("api-key", {
133 * owner: "my-org",
134 * repository: "my-repo",
135 * environment: "production",
136 * name: "API_KEY",
137 * value: Redacted.make(apiKey),
138 * });
139 * ```
140 *
141 * @resource
142 * @product Actions
143 */
144 export const Secret = Resource<Secret>("GitHub.Secret");
145
146 async function encryptValue(plaintext: string, publicKey: string): Promise<string> {
147 const mod = await import("libsodium-wrappers");
148 // Bun/ESM interop: the actual sodium API lives on `.default` when the
149 // CJS module is wrapped, but is the module itself under other loaders.
150 const sodium: typeof import("libsodium-wrappers") = (mod as any).default ?? mod;
151 await sodium.ready;
152 const binKey = sodium.from_base64(publicKey, sodium.base64_variants.ORIGINAL);
153 const binMessage = sodium.from_string(plaintext);
154 const encrypted = sodium.crypto_box_seal(binMessage, binKey);
155 return sodium.to_base64(encrypted, sodium.base64_variants.ORIGINAL);
156 }
157
158 export const SecretProvider = () =>
159 Provider.succeed(Secret, {
160 // A secret's entire identity is (host, owner, repository, environment,
161 // name) — GitHub has no rename/move API for secrets, so changing any of
162 // them replaces the resource: the engine upserts the new secret first,
163 // then `delete` removes the old one from its old location. Replacement
164 // is safe here — a secret is declarative config that is fully
165 // re-creatable from props.
166 diff: Effect.fn(function* ({ news, olds }) {
167 if (!isResolved(news)) return;
168 if (olds === undefined) return;
169 if (
170 news.owner !== olds.owner ||
171 news.repository !== olds.repository ||
172 news.name !== olds.name ||
173 resolveEnvironmentName(news.environment) !== resolveEnvironmentName(olds.environment) ||
174 (yield* gitHubBaseUrlChanged(olds, news))
175 ) {
176 return { action: "replace" };
177 }
178 }),
179
180 // Non-listable: a GitHub Actions secret is keyed entirely by its parent
181 // (owner, repository[, environment], name) which arrive as props — there is
182 // no ambient owner/repo scope to enumerate from, `list()` takes no input,
183 // and the `Attributes` shape carries no identifying keys (only `updatedAt`).
184 // GitHub only exposes list-secrets *within* a specific repo/environment, so
185 // there is no account-wide enumeration API. Return an empty array.
186 list: () => Effect.succeed([]),
187
188 reconcile: Effect.fn(function* ({ news, olds }) {
189 // Observe — there's no API to read a secret's value back, so we can
190 // only observe its location (repo vs. environment, environment name).
191 // A location change normally arrives as a replacement (see `diff`);
192 // this guard is the safety net for the plan-time path where `news`
193 // contained unresolved outputs and diff could not compare — delete the
194 // orphaned secret from its old location before upserting the new one.
195 if (
196 olds !== undefined &&
197 resolveEnvironmentName(olds.environment) !== resolveEnvironmentName(news.environment)
198 ) {
199 yield* deleteSecret(olds);
200 }
201
202 // Ensure & Sync — `createOrUpdate*Secret` is upsert-style: it
203 // creates the secret if absent and overwrites it if present. The
204 // value is encrypted client-side with the repo/environment public
205 // key, so we re-encrypt and re-upload on every reconcile (Redacted
206 // values can't be diffed across runs anyway).
207 yield* upsertSecret(news);
208 return { updatedAt: new Date().toISOString() };
209 }),
210
211 delete: Effect.fn(function* ({ olds }) {
212 yield* deleteSecret(olds);
213 }),
214 });
215
216 const upsertSecret = Effect.fn(
217 function* (props: SecretProps) {
218 const plaintext = Redacted.value(props.value);
219 const environment = resolveEnvironmentName(props.environment);
220 const scope = { owner: props.owner, repo: props.repository };
221
222 const publicKey = yield* environment !== undefined
223 ? Actions.getEnvironmentPublicKey({ ...scope, environment_name: environment })
224 : Actions.getRepoPublicKey(scope);
225
226 const encrypted = yield* Effect.tryPromise(() => encryptValue(plaintext, publicKey.key));
227
228 yield* environment !== undefined
229 ? Actions.createOrUpdateEnvironmentSecret({
230 ...scope,
231 environment_name: environment,
232 secret_name: props.name,
233 encrypted_value: encrypted,
234 key_id: publicKey.key_id,
235 })
236 : Actions.createOrUpdateRepoSecret({
237 ...scope,
238 secret_name: props.name,
239 encrypted_value: encrypted,
240 key_id: publicKey.key_id,
241 });
242 },
243 (effect, props) => effect.pipe(withBaseUrl(props.baseUrl)),
244 );
245
246 const deleteSecret = Effect.fn(
247 function* (props: SecretProps) {
248 const environment = resolveEnvironmentName(props.environment);
249 const scope = { owner: props.owner, repo: props.repository, secret_name: props.name };
250 yield* (
251 environment !== undefined
252 ? Actions.deleteEnvironmentSecret({ ...scope, environment_name: environment })
253 : Actions.deleteRepoSecret(scope)
254 ).pipe(Effect.catchTag("NotFound", () => Effect.void));
255 },
256 (effect, props) => effect.pipe(withBaseUrl(props.baseUrl)),
257 );