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

main
ts 288 lines 9.98 KB
Raw
1 import * as ag from "@distilled.cloud/aws/api-gateway";
2 import { deepEqual, isResolved } from "alchemy/Diff";
3 import type { Input } from "alchemy/Input";
4 import { createPhysicalName } from "alchemy/PhysicalName";
5 import * as Provider from "alchemy/Provider";
6 import { Resource } from "alchemy/Resource";
7 import { toWireSeconds } from "alchemy/Util/Duration";
8 import type * as Duration from "effect/Duration";
9 import * as Effect from "effect/Effect";
10 import * as Stream from "effect/Stream";
11 import type { Providers } from "../Providers.ts";
12
13 export interface AuthorizerProps {
14 /**
15 * REST API identifier that owns the authorizer.
16 */
17 restApiId: Input<string>;
18 /**
19 * Authorizer name.
20 *
21 * If omitted, Alchemy generates a deterministic physical name.
22 */
23 name?: string;
24 /**
25 * Authorizer type.
26 */
27 type: ag.AuthorizerType;
28 /**
29 * Cognito user pool ARNs for `COGNITO_USER_POOLS` authorizers.
30 */
31 providerARNs?: string[];
32 /**
33 * Custom authorization type label.
34 */
35 authType?: string;
36 /**
37 * Lambda invocation URI for `TOKEN` or `REQUEST` authorizers.
38 */
39 authorizerUri?: string;
40 /**
41 * IAM role ARN used by API Gateway to invoke the authorizer.
42 *
43 * This is not secret key material; API Gateway stores the role ARN.
44 */
45 authorizerCredentials?: string;
46 /**
47 * Identity source expression, e.g. `method.request.header.Authorization`.
48 */
49 identitySource?: string;
50 /**
51 * Validation regex for token authorizers.
52 */
53 identityValidationExpression?: string;
54 /**
55 * Cache TTL for authorizer results (e.g. `"5 minutes"` or
56 * `Duration.seconds(300)`; a bare number is milliseconds). Sent to the
57 * API as whole seconds (`authorizerResultTtlInSeconds`).
58 */
59 authorizerResultTtl?: Duration.Input;
60 }
61
62 /** @resource */
63 export interface Authorizer extends Resource<
64 "AWS.ApiGateway.Authorizer",
65 AuthorizerProps,
66 {
67 authorizerId: string;
68 restApiId: string;
69 name: string;
70 type: ag.AuthorizerType;
71 },
72 never,
73 Providers
74 > {}
75
76 /**
77 * REST API Lambda, Cognito, or gateway authorizer.
78 *
79 * ### Authorizers
80 * **Example:** Lambda TOKEN authorizer
81 * ```typescript
82 * const authorizer = yield* ApiGateway.Authorizer("Auth", {
83 * restApiId: api.restApiId,
84 * type: "TOKEN",
85 * authorizerUri: authorizerInvokeArn,
86 * identitySource: "method.request.header.Authorization",
87 * });
88 * ```
89 */
90 const AuthorizerResource = Resource<Authorizer>("AWS.ApiGateway.Authorizer");
91
92 export { AuthorizerResource as Authorizer };
93
94 const generatedName = (id: string, props: AuthorizerProps) =>
95 props.name
96 ? Effect.succeed(props.name)
97 : createPhysicalName({
98 id,
99 maxLength: 128,
100 });
101
102 export const AuthorizerProvider = () =>
103 Provider.effect(
104 AuthorizerResource,
105 Effect.gen(function* () {
106 return {
107 stables: ["authorizerId", "restApiId"] as const,
108 diff: Effect.fn(function* ({ news: newsIn, olds }) {
109 if (!isResolved(newsIn)) return;
110 const news = newsIn as AuthorizerProps;
111 if (
112 // These fields define the authorizer identity and kind; replacement
113 // avoids patching a different authorizer shape in place.
114 news.restApiId !== olds.restApiId ||
115 (news.name !== undefined && news.name !== olds.name) ||
116 news.type !== olds.type
117 ) {
118 return { action: "replace" } as const;
119 }
120 if (!deepEqual(news.providerARNs, olds.providerARNs)) {
121 return { action: "replace" } as const;
122 }
123 if (news.authType !== olds.authType) {
124 return { action: "replace" } as const;
125 }
126 }),
127 read: Effect.fn(function* ({ output }) {
128 if (!output?.authorizerId) return undefined;
129 const a = yield* ag
130 .getAuthorizer({
131 restApiId: output.restApiId,
132 authorizerId: output.authorizerId,
133 })
134 .pipe(Effect.catchTag("NotFoundException", () => Effect.undefined));
135 if (!a?.id) return undefined;
136 return {
137 authorizerId: a.id,
138 restApiId: output.restApiId,
139 name: a.name!,
140 type: a.type!,
141 };
142 }),
143 reconcile: Effect.fn(function* ({ id, news: newsIn, output, session }) {
144 if (!isResolved(newsIn)) {
145 return yield* Effect.die("Authorizer props were not resolved");
146 }
147 const news = newsIn as Input.ResolveProps<AuthorizerProps>;
148 const name = yield* generatedName(id, news);
149 const restApiId = (output?.restApiId ?? news.restApiId) as string;
150
151 // Observe — fetch the live authorizer if we have a cached id.
152 // The cached id is the only way to find the resource; on a stale
153 // delete out of band we re-create.
154 let observed = output?.authorizerId
155 ? yield* ag
156 .getAuthorizer({
157 restApiId,
158 authorizerId: output.authorizerId,
159 })
160 .pipe(Effect.catchTag("NotFoundException", () => Effect.undefined))
161 : undefined;
162
163 // Ensure — create if missing.
164 if (!observed?.id) {
165 const created = yield* ag.createAuthorizer({
166 restApiId: news.restApiId as string,
167 name,
168 type: news.type,
169 providerARNs: news.providerARNs,
170 authType: news.authType,
171 authorizerUri: news.authorizerUri,
172 authorizerCredentials: news.authorizerCredentials,
173 identitySource: news.identitySource,
174 identityValidationExpression: news.identityValidationExpression,
175 authorizerResultTtlInSeconds: toWireSeconds(news.authorizerResultTtl),
176 });
177 if (!created.id) return yield* Effect.die("createAuthorizer missing id");
178 yield* session.note(`Created authorizer ${created.id}`);
179 observed = yield* ag.getAuthorizer({
180 restApiId: news.restApiId as string,
181 authorizerId: created.id,
182 });
183 }
184
185 const authorizerId = observed.id!;
186
187 // Sync mutable fields — diff observed cloud state against desired.
188 const patches: ag.PatchOperation[] = [];
189 if (news.authorizerUri !== observed.authorizerUri) {
190 patches.push({
191 op: news.authorizerUri === undefined ? "remove" : "replace",
192 path: "/authorizerUri",
193 value: news.authorizerUri,
194 });
195 }
196 if (news.identitySource !== observed.identitySource) {
197 patches.push({
198 op: news.identitySource === undefined ? "remove" : "replace",
199 path: "/identitySource",
200 value: news.identitySource,
201 });
202 }
203 if (news.authorizerCredentials !== observed.authorizerCredentials) {
204 patches.push({
205 op: news.authorizerCredentials === undefined ? "remove" : "replace",
206 path: "/authorizerCredentials",
207 value: news.authorizerCredentials,
208 });
209 }
210 if (news.identityValidationExpression !== observed.identityValidationExpression) {
211 patches.push({
212 op: news.identityValidationExpression === undefined ? "remove" : "replace",
213 path: "/identityValidationExpression",
214 value: news.identityValidationExpression,
215 });
216 }
217 const desiredTtlSeconds = toWireSeconds(news.authorizerResultTtl);
218 if (desiredTtlSeconds !== observed.authorizerResultTtlInSeconds) {
219 patches.push({
220 op: desiredTtlSeconds === undefined ? "remove" : "replace",
221 path: "/authorizerResultTtlInSeconds",
222 value: desiredTtlSeconds === undefined ? undefined : String(desiredTtlSeconds),
223 });
224 }
225 if (patches.length > 0) {
226 yield* ag.updateAuthorizer({
227 restApiId,
228 authorizerId,
229 patchOperations: patches,
230 });
231 }
232
233 yield* session.note(`Reconciled authorizer ${authorizerId}`);
234 const final = yield* ag.getAuthorizer({
235 restApiId,
236 authorizerId,
237 });
238 return {
239 authorizerId,
240 restApiId,
241 name: final.name!,
242 type: final.type!,
243 };
244 }),
245 // Authorizers are sub-resources of a RestApi and can only be listed
246 // per-parent (`GET /restapis/{restApiId}/authorizers`). Enumerate every
247 // RestApi (paginated), then fan out the per-api authorizer list.
248 list: () =>
249 Effect.gen(function* () {
250 const restApiIds = yield* ag.getRestApis.pages({}).pipe(
251 Stream.runCollect,
252 Effect.map((chunk) =>
253 Array.from(chunk).flatMap((page) =>
254 (page.items ?? []).map((api) => api.id).filter((id): id is string => id != null),
255 ),
256 ),
257 );
258 const rows = yield* Effect.forEach(
259 restApiIds,
260 (restApiId) =>
261 ag.getAuthorizers({ restApiId }).pipe(
262 Effect.map((res) =>
263 (res.items ?? [])
264 .filter((a): a is ag.Authorizer & { id: string } => a.id != null)
265 .map((a) => ({
266 authorizerId: a.id,
267 restApiId,
268 name: a.name!,
269 type: a.type!,
270 })),
271 ),
272 ),
273 { concurrency: 10 },
274 );
275 return rows.flat();
276 }),
277 delete: Effect.fn(function* ({ output, session }) {
278 yield* ag
279 .deleteAuthorizer({
280 restApiId: output.restApiId,
281 authorizerId: output.authorizerId,
282 })
283 .pipe(Effect.catchTag("NotFoundException", () => Effect.void));
284 yield* session.note(`Deleted authorizer ${output.authorizerId}`);
285 }),
286 };
287 }),
288 );