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

main
ts 382 lines 14.2 KB
Raw
1 import * as eventbridge from "@distilled.cloud/aws/eventbridge";
2 import { isResolved } from "alchemy/Diff";
3 import { createPhysicalName } from "alchemy/PhysicalName";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import * as Effect from "effect/Effect";
7 import type * as Redacted from "effect/Redacted";
8 import * as Schedule from "effect/Schedule";
9 import type { AccountID } from "../Environment.ts";
10 import type { Providers } from "../Providers.ts";
11 import type { RegionID } from "../Region.ts";
12
13 export type {
14 ConnectionAuthorizationType,
15 ConnectionHttpParameters,
16 ConnectionOAuthHttpMethod,
17 ConnectionState,
18 } from "@distilled.cloud/aws/eventbridge";
19
20 export type ConnectionName = string;
21 export type ConnectionArn =
22 `arn:aws:events:${RegionID}:${AccountID}:connection/${ConnectionName}/${string}`;
23
24 export interface ConnectionApiKeyAuthParameters {
25 /** Header name the API key is sent under (e.g. `x-api-key`). */
26 apiKeyName: string;
27 /** The API key value. Wrap with `Redacted.make(...)` — stored by EventBridge in Secrets Manager. */
28 apiKeyValue: Redacted.Redacted<string>;
29 }
30
31 export interface ConnectionBasicAuthParameters {
32 /** Username for HTTP Basic authorization. */
33 username: string;
34 /** Password for HTTP Basic authorization. Wrap with `Redacted.make(...)`. */
35 password: Redacted.Redacted<string>;
36 }
37
38 export interface ConnectionOAuthClientParameters {
39 /** OAuth client ID. */
40 clientId: string;
41 /** OAuth client secret. Wrap with `Redacted.make(...)`. */
42 clientSecret: Redacted.Redacted<string>;
43 }
44
45 export interface ConnectionOAuthParameters {
46 /** The client credentials exchanged for a token. */
47 clientParameters: ConnectionOAuthClientParameters;
48 /** URL of the OAuth authorization (token) endpoint. */
49 authorizationEndpoint: string;
50 /** HTTP method used against the authorization endpoint. */
51 httpMethod: eventbridge.ConnectionOAuthHttpMethod;
52 /** Additional parameters included in the token request. */
53 oauthHttpParameters?: eventbridge.ConnectionHttpParameters;
54 }
55
56 export interface ConnectionAuthParameters {
57 /** API-key authorization (`authorizationType: "API_KEY"`). */
58 apiKeyAuthParameters?: ConnectionApiKeyAuthParameters;
59 /** Basic authorization (`authorizationType: "BASIC"`). */
60 basicAuthParameters?: ConnectionBasicAuthParameters;
61 /** OAuth client-credentials authorization (`authorizationType: "OAUTH_CLIENT_CREDENTIALS"`). */
62 oauthParameters?: ConnectionOAuthParameters;
63 /** Additional header/query/body parameters included in every invocation. */
64 invocationHttpParameters?: eventbridge.ConnectionHttpParameters;
65 }
66
67 export interface ConnectionProps {
68 /**
69 * Name of the connection. Must match [\.\-_A-Za-z0-9]+, 1-64 characters.
70 * If omitted, a unique name will be generated.
71 */
72 name?: ConnectionName;
73
74 /**
75 * Description of the connection. Max 512 characters.
76 */
77 description?: string;
78
79 /**
80 * The type of authorization to use for the connection.
81 */
82 authorizationType: eventbridge.ConnectionAuthorizationType;
83
84 /**
85 * The authorization parameters matching `authorizationType`. Secret values
86 * (`apiKeyValue`, `password`, `clientSecret`) are `Redacted` end-to-end and
87 * stored by EventBridge in Secrets Manager.
88 */
89 authParameters: ConnectionAuthParameters;
90
91 /**
92 * The identifier of the KMS customer managed key to encrypt the connection
93 * secret.
94 */
95 kmsKeyIdentifier?: string;
96
97 /**
98 * Invoke a private HTTPS endpoint (in a VPC or on premises) through a VPC
99 * Lattice resource configuration instead of the public internet. Removing
100 * it replaces the connection, since EventBridge cannot turn a private
101 * connection back into a public one.
102 */
103 invocationConnectivityParameters?: {
104 /** ARN of the VPC Lattice resource configuration for the endpoint. */
105 resourceConfigurationArn: string;
106 };
107 }
108
109 const toConnectivityParameters = (props: ConnectionProps) =>
110 props.invocationConnectivityParameters
111 ? {
112 ResourceParameters: {
113 ResourceConfigurationArn: props.invocationConnectivityParameters.resourceConfigurationArn,
114 },
115 }
116 : undefined;
117
118 /**
119 * An Amazon EventBridge connection holding the authorization used to invoke
120 * an HTTP endpoint through an {@link ApiDestination}. EventBridge stores the
121 * secret half of the connection in Secrets Manager on your behalf.
122 *
123 * Connections do not support tags, so ownership is tracked by the
124 * deterministic physical name.
125 * ### Connecting to APIs
126 * **Example:** API-Key Connection
127 * ```typescript
128 * import * as Redacted from "effect/Redacted";
129 *
130 * const connection = yield* AWS.EventBridge.Connection("PartnerApi", {
131 * authorizationType: "API_KEY",
132 * authParameters: {
133 * apiKeyAuthParameters: {
134 * apiKeyName: "x-api-key",
135 * apiKeyValue: Redacted.make(process.env.PARTNER_API_KEY!),
136 * },
137 * },
138 * });
139 * ```
140 *
141 * **Example:** OAuth Client-Credentials Connection
142 * ```typescript
143 * const connection = yield* AWS.EventBridge.Connection("OAuthApi", {
144 * authorizationType: "OAUTH_CLIENT_CREDENTIALS",
145 * authParameters: {
146 * oauthParameters: {
147 * clientParameters: {
148 * clientId: "my-client",
149 * clientSecret: Redacted.make(process.env.OAUTH_SECRET!),
150 * },
151 * authorizationEndpoint: "https://auth.example.com/oauth/token",
152 * httpMethod: "POST",
153 * },
154 * },
155 * });
156 * ```
157 *
158 * ### Connecting to Private APIs
159 * **Example:** Invoke an API Inside a VPC
160 * ```typescript
161 * const connection = yield* AWS.EventBridge.Connection("PrivateApi", {
162 * authorizationType: "API_KEY",
163 * authParameters: {
164 * apiKeyAuthParameters: {
165 * apiKeyName: "x-api-key",
166 * apiKeyValue: Redacted.make(process.env.API_KEY!),
167 * },
168 * },
169 * invocationConnectivityParameters: {
170 * resourceConfigurationArn: "arn:aws:vpc-lattice:us-east-1:123456789012:resourceconfiguration/rcfg-0123456789abcdef0",
171 * },
172 * });
173 * ```
174 *
175 * @resource
176 */
177 export interface Connection extends Resource<
178 "AWS.EventBridge.Connection",
179 ConnectionProps,
180 {
181 /** The name of the connection. */
182 connectionName: ConnectionName;
183 /** The ARN of the connection. */
184 connectionArn: ConnectionArn;
185 /** The state of the connection (e.g. `AUTHORIZED`). */
186 connectionState: eventbridge.ConnectionState;
187 /** ARN of the Secrets Manager secret EventBridge created for the connection. */
188 secretArn?: string;
189 },
190 never,
191 Providers
192 > {}
193 export const Connection = Resource<Connection>("AWS.EventBridge.Connection");
194
195 const toCreateAuthParameters = (
196 auth: ConnectionAuthParameters,
197 ): eventbridge.CreateConnectionAuthRequestParameters => ({
198 ApiKeyAuthParameters: auth.apiKeyAuthParameters
199 ? {
200 ApiKeyName: auth.apiKeyAuthParameters.apiKeyName,
201 ApiKeyValue: auth.apiKeyAuthParameters.apiKeyValue,
202 }
203 : undefined,
204 BasicAuthParameters: auth.basicAuthParameters
205 ? {
206 Username: auth.basicAuthParameters.username,
207 Password: auth.basicAuthParameters.password,
208 }
209 : undefined,
210 OAuthParameters: auth.oauthParameters
211 ? {
212 ClientParameters: {
213 ClientID: auth.oauthParameters.clientParameters.clientId,
214 ClientSecret: auth.oauthParameters.clientParameters.clientSecret,
215 },
216 AuthorizationEndpoint: auth.oauthParameters.authorizationEndpoint,
217 HttpMethod: auth.oauthParameters.httpMethod,
218 OAuthHttpParameters: auth.oauthParameters.oauthHttpParameters,
219 }
220 : undefined,
221 InvocationHttpParameters: auth.invocationHttpParameters,
222 });
223
224 export const ConnectionProvider = () =>
225 Provider.effect(
226 Connection,
227 Effect.gen(function* () {
228 const createConnectionName = (id: string, props: { name?: string } = {}) =>
229 props.name
230 ? Effect.succeed(props.name)
231 : createPhysicalName({
232 id,
233 maxLength: 64,
234 });
235
236 /**
237 * Poll until the connection settles out of its transitional state
238 * (CREATING/UPDATING/AUTHORIZING). API-key and basic connections
239 * authorize in seconds; the wait is bounded so a slow OAuth handshake
240 * surfaces the last observed state instead of hanging.
241 */
242 const awaitSettled = (name: string) =>
243 eventbridge.describeConnection({ Name: name }).pipe(
244 // A describe fired immediately after create can be eventually
245 // consistent — absorb NotFound briefly before polling the state.
246 Effect.retry({
247 while: (e): boolean => e._tag === "ResourceNotFoundException",
248 schedule: Schedule.spaced("1 second"),
249 times: 5,
250 }),
251 Effect.repeat({
252 schedule: Schedule.spaced("2 seconds"),
253 until: (r): boolean =>
254 r.ConnectionState !== "CREATING" &&
255 r.ConnectionState !== "UPDATING" &&
256 r.ConnectionState !== "AUTHORIZING",
257 times: 15,
258 }),
259 );
260
261 return {
262 stables: ["connectionName", "connectionArn"],
263 diff: Effect.fn(function* ({ id, news, olds }) {
264 if (!isResolved(news)) return;
265 const oldName = yield* createConnectionName(id, olds);
266 const newName = yield* createConnectionName(id, news);
267 if (oldName !== newName) {
268 return { action: "replace" } as const;
269 }
270 if (olds.invocationConnectivityParameters && !news.invocationConnectivityParameters) {
271 return { action: "replace" } as const;
272 }
273 }),
274 read: Effect.fn(function* ({ id, olds, output }) {
275 // Connections don't support tags; the deterministic physical name
276 // is the ownership signal (it embeds app/stage/logical id).
277 const connectionName =
278 output?.connectionName ?? (yield* createConnectionName(id, olds ?? {}));
279 const described = yield* eventbridge
280 .describeConnection({ Name: connectionName })
281 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
282 if (!described?.Name || !described.ConnectionArn) {
283 return undefined;
284 }
285 return {
286 connectionName: described.Name,
287 connectionArn: described.ConnectionArn as ConnectionArn,
288 connectionState: described.ConnectionState ?? "AUTHORIZED",
289 secretArn: described.SecretArn,
290 };
291 }),
292 list: () =>
293 Effect.gen(function* () {
294 const attrs: {
295 connectionName: ConnectionName;
296 connectionArn: ConnectionArn;
297 connectionState: eventbridge.ConnectionState;
298 secretArn?: string;
299 }[] = [];
300 let nextToken: string | undefined;
301 do {
302 const page = yield* eventbridge.listConnections({
303 NextToken: nextToken,
304 });
305 for (const connection of page.Connections ?? []) {
306 if (!connection.Name || !connection.ConnectionArn) {
307 continue;
308 }
309 attrs.push({
310 connectionName: connection.Name,
311 connectionArn: connection.ConnectionArn as ConnectionArn,
312 connectionState: connection.ConnectionState ?? "AUTHORIZED",
313 });
314 }
315 nextToken = page.NextToken;
316 } while (nextToken);
317 return attrs;
318 }),
319 reconcile: Effect.fn(function* ({ id, news, output, session }) {
320 const connectionName = output?.connectionName ?? (yield* createConnectionName(id, news));
321
322 // Observe — live cloud state is authoritative; a vanished
323 // connection falls through to create.
324 const observed = yield* eventbridge
325 .describeConnection({ Name: connectionName })
326 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
327
328 if (!observed?.ConnectionArn) {
329 // Ensure — create the connection; tolerate an AlreadyExists race
330 // with a peer reconciler and converge via the update below.
331 yield* eventbridge
332 .createConnection({
333 Name: connectionName,
334 Description: news.description,
335 AuthorizationType: news.authorizationType,
336 AuthParameters: toCreateAuthParameters(news.authParameters),
337 KmsKeyIdentifier: news.kmsKeyIdentifier,
338 InvocationConnectivityParameters: toConnectivityParameters(news),
339 })
340 .pipe(Effect.catchTag("ResourceAlreadyExistsException", () => Effect.void));
341 } else {
342 // Sync — updateConnection overwrites description, authorization
343 // type/parameters, and KMS key in one shot. The update-parameter
344 // shape is structurally compatible with the create shape (all
345 // fields optional).
346 yield* eventbridge.updateConnection({
347 Name: connectionName,
348 Description: news.description,
349 AuthorizationType: news.authorizationType,
350 AuthParameters: toCreateAuthParameters(news.authParameters),
351 KmsKeyIdentifier: news.kmsKeyIdentifier,
352 InvocationConnectivityParameters: toConnectivityParameters(news),
353 });
354 }
355
356 const settled = yield* awaitSettled(connectionName);
357 const connectionArn = (settled.ConnectionArn ?? observed?.ConnectionArn) as ConnectionArn;
358
359 yield* session.note(connectionArn);
360 return {
361 connectionName,
362 connectionArn,
363 connectionState: settled.ConnectionState ?? "AUTHORIZED",
364 secretArn: settled.SecretArn,
365 };
366 }),
367 delete: Effect.fn(function* ({ output }) {
368 // Deleting a connection that ApiDestinations still reference fails
369 // until the destinations are gone; the engine deletes dependents
370 // first, so a bounded retry absorbs eventual consistency.
371 yield* eventbridge.deleteConnection({ Name: output.connectionName }).pipe(
372 Effect.retry({
373 while: (e): boolean => e._tag === "ConcurrentModificationException",
374 schedule: Schedule.spaced("2 seconds"),
375 times: 8,
376 }),
377 Effect.catchTag("ResourceNotFoundException", () => Effect.void),
378 );
379 }),
380 };
381 }),
382 );