@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 06:00 UTC

main
ts 334 lines 12.4 KB
Raw
1 import * as agw2 from "@distilled.cloud/aws/apigatewayv2";
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 type { Providers } from "../Providers.ts";
11 import type { Api } from "./Api.ts";
12 import { collectAllPages, retryOnTooManyRequests } from "./common.ts";
13
14 export interface AuthorizerProps {
15 /**
16 * ID of the API this authorizer belongs to. Usually derived from
17 * `api.apiId` by the {@link Authorizer} wrapper.
18 */
19 apiId: string;
20 /**
21 * The authorizer type: `JWT` (HTTP APIs — validate a JWT issued by an
22 * OIDC/OAuth2 provider) or `REQUEST` (Lambda authorizer, both
23 * protocols).
24 */
25 authorizerType: "JWT" | "REQUEST";
26 /**
27 * Name of the authorizer. If omitted, Alchemy generates a deterministic
28 * physical name.
29 */
30 name?: string;
31 /**
32 * The identity source(s):
33 *
34 * - JWT — where to find the token, e.g. `["$request.header.Authorization"]`.
35 * - REQUEST (HTTP APIs) — the caching identity sources.
36 * - REQUEST (WebSocket APIs) — e.g. `["route.request.header.Auth"]`.
37 */
38 identitySource?: string[];
39 /**
40 * JWT configuration (`JWT` authorizers only): the token `Issuer` URL and
41 * accepted `Audience` values.
42 */
43 jwtConfiguration?: agw2.JWTConfiguration;
44 /**
45 * The authorizer's Lambda invocation URI (`REQUEST` authorizers only):
46 * `arn:aws:apigateway:{region}:lambda:path/2015-03-31/functions/{functionArn}/invocations`.
47 */
48 authorizerUri?: string;
49 /**
50 * The payload format version the Lambda authorizer receives (`REQUEST`
51 * on HTTP APIs only): `1.0` or `2.0`.
52 */
53 authorizerPayloadFormatVersion?: string;
54 /**
55 * Whether a `REQUEST` authorizer (HTTP APIs, payload 2.0) returns simple
56 * `{ isAuthorized: boolean }` responses instead of IAM policies.
57 */
58 enableSimpleResponses?: boolean;
59 /**
60 * TTL for cached authorizer results (`REQUEST` only), e.g. `"5 minutes"`
61 * or `Duration.seconds(300)` (a bare number is milliseconds). Rounded to
62 * whole seconds on the wire (`AuthorizerResultTtlInSeconds`).
63 * @default 300 seconds
64 */
65 authorizerResultTtl?: Duration.Input;
66 /**
67 * IAM role ARN API Gateway assumes to invoke the authorizer Lambda.
68 * Omit to use a Lambda resource policy (`Lambda.Permission`) instead.
69 */
70 authorizerCredentialsArn?: string;
71 /**
72 * Validation expression for the incoming identity (WebSocket `REQUEST`
73 * authorizers only).
74 */
75 identityValidationExpression?: string;
76 }
77
78 export interface AuthorizerType extends Resource<
79 "AWS.ApiGatewayV2.Authorizer",
80 AuthorizerProps,
81 {
82 /** The API this authorizer belongs to. */
83 apiId: string;
84 /** The authorizer identifier — referenced by `Route.authorizerId`. */
85 authorizerId: string;
86 /** The authorizer name. */
87 name: string;
88 authorizerType: string;
89 identitySource: string[] | undefined;
90 jwtConfiguration: agw2.JWTConfiguration | undefined;
91 authorizerUri: string | undefined;
92 authorizerPayloadFormatVersion: string | undefined;
93 enableSimpleResponses: boolean | undefined;
94 authorizerResultTtlInSeconds: number | undefined;
95 authorizerCredentialsArn: string | undefined;
96 identityValidationExpression: string | undefined;
97 },
98 never,
99 Providers
100 > {}
101
102 /**
103 * An API Gateway v2 Authorizer — controls access to HTTP/WebSocket API
104 * routes via JWT validation or a Lambda (`REQUEST`) authorizer.
105 * ### JWT authorizers
106 * The common HTTP API authorizer: API Gateway validates the caller's JWT
107 * against the issuer's JWKS and matches the audience — no Lambda invoked.
108 *
109 * **Example:** JWT authorizer for a Cognito user pool
110 * ```typescript
111 * const authorizer = yield* ApiGatewayV2.Authorizer("Jwt", {
112 * api,
113 * authorizerType: "JWT",
114 * identitySource: ["$request.header.Authorization"],
115 * jwtConfiguration: {
116 * Issuer: `https://cognito-idp.us-west-2.amazonaws.com/${userPoolId}`,
117 * Audience: [clientId],
118 * },
119 * });
120 *
121 * yield* ApiGatewayV2.Route("Secure", {
122 * api,
123 * routeKey: "GET /me",
124 * integration,
125 * authorizationType: "JWT",
126 * authorizerId: authorizer.authorizerId,
127 * });
128 * ```
129 *
130 * ### Lambda (REQUEST) authorizers
131 * **Example:** Simple-response Lambda authorizer
132 * ```typescript
133 * const authorizer = yield* ApiGatewayV2.Authorizer("Lambda", {
134 * api,
135 * authorizerType: "REQUEST",
136 * identitySource: ["$request.header.Authorization"],
137 * authorizerUri: invocationUri,
138 * authorizerPayloadFormatVersion: "2.0",
139 * enableSimpleResponses: true,
140 * });
141 * ```
142 *
143 * @resource
144 */
145 export const AuthorizerResource = Resource<AuthorizerType>("AWS.ApiGatewayV2.Authorizer");
146
147 export interface AuthorizerInputProps extends Omit<
148 {
149 [K in keyof AuthorizerProps]?: Input<AuthorizerProps[K]>;
150 },
151 "apiId" | "authorizerType"
152 > {
153 /**
154 * The `Api` this authorizer belongs to (preferred). Alternatively pass a
155 * raw `apiId`.
156 */
157 api?: Api;
158 apiId?: Input<string>;
159 authorizerType: Input<"JWT" | "REQUEST">;
160 }
161
162 /**
163 * User-facing wrapper for the Authorizer resource. Accepts `api: Api` as
164 * the idiomatic way to attach an authorizer to an API.
165 */
166 export const Authorizer = (id: string, props: AuthorizerInputProps) =>
167 Effect.gen(function* () {
168 const { api, ...rest } = props;
169 const apiId = rest.apiId ?? api?.apiId;
170 if (!apiId) {
171 return yield* Effect.die(
172 "Authorizer requires either `api` (preferred) or an explicit `apiId`.",
173 );
174 }
175 return yield* AuthorizerResource(id, { ...rest, apiId } as any);
176 });
177
178 const snapshotFromAuthorizer = (
179 apiId: string,
180 auth: agw2.GetAuthorizerResponse,
181 ): AuthorizerType["Attributes"] => ({
182 apiId,
183 authorizerId: auth.AuthorizerId!,
184 name: auth.Name ?? "",
185 authorizerType: auth.AuthorizerType ?? "JWT",
186 identitySource: auth.IdentitySource,
187 jwtConfiguration: auth.JwtConfiguration,
188 authorizerUri: auth.AuthorizerUri,
189 authorizerPayloadFormatVersion: auth.AuthorizerPayloadFormatVersion,
190 enableSimpleResponses: auth.EnableSimpleResponses,
191 authorizerResultTtlInSeconds: auth.AuthorizerResultTtlInSeconds,
192 authorizerCredentialsArn: auth.AuthorizerCredentialsArn,
193 identityValidationExpression: auth.IdentityValidationExpression,
194 });
195
196 export const AuthorizerProvider = () =>
197 Provider.effect(
198 AuthorizerResource,
199 Effect.gen(function* () {
200 const createName = Effect.fn(function* (id: string, props: Pick<AuthorizerProps, "name">) {
201 return props.name ?? (yield* createPhysicalName({ id, maxLength: 128 }));
202 });
203
204 const getAuthorizerSafe = (apiId: string, authorizerId: string) =>
205 agw2
206 .getAuthorizer({ ApiId: apiId, AuthorizerId: authorizerId })
207 .pipe(Effect.catchTag("NotFoundException", () => Effect.undefined));
208
209 return AuthorizerResource.Provider.of({
210 stables: ["apiId", "authorizerId"],
211
212 list: () =>
213 Effect.gen(function* () {
214 const apis = yield* collectAllPages((NextToken) => agw2.getApis({ NextToken }));
215 const perApi = yield* Effect.forEach(
216 apis.filter((api) => api.ApiId != null),
217 (api) =>
218 collectAllPages((NextToken) =>
219 agw2.getAuthorizers({ ApiId: api.ApiId!, NextToken }),
220 ).pipe(
221 Effect.map((items) =>
222 items
223 .filter((auth) => auth.AuthorizerId != null)
224 .map((auth) => snapshotFromAuthorizer(api.ApiId!, auth)),
225 ),
226 Effect.catchTag("NotFoundException", () =>
227 Effect.succeed([] as AuthorizerType["Attributes"][]),
228 ),
229 ),
230 { concurrency: 5 },
231 );
232 return perApi.flat();
233 }),
234
235 read: Effect.fn(function* ({ output }) {
236 if (!output?.apiId || !output.authorizerId) return undefined;
237 const auth = yield* getAuthorizerSafe(output.apiId, output.authorizerId);
238 if (!auth?.AuthorizerId) return undefined;
239 return snapshotFromAuthorizer(output.apiId, auth);
240 }),
241
242 diff: Effect.fn(function* ({ news, olds }) {
243 if (!isResolved(news)) return undefined;
244 if (news.apiId !== olds.apiId) {
245 return { action: "replace" } as const;
246 }
247 }),
248
249 reconcile: Effect.fn(function* ({ id, news, output, session }) {
250 const apiId = output?.apiId ?? news.apiId;
251 const name = yield* createName(id, news);
252
253 // 1. OBSERVE
254 let observed = output?.authorizerId
255 ? yield* getAuthorizerSafe(apiId, output.authorizerId)
256 : undefined;
257
258 // 2. ENSURE
259 if (!observed?.AuthorizerId) {
260 observed = yield* retryOnTooManyRequests(
261 agw2.createAuthorizer({
262 ApiId: apiId,
263 Name: name,
264 AuthorizerType: news.authorizerType,
265 IdentitySource: news.identitySource,
266 JwtConfiguration: news.jwtConfiguration,
267 AuthorizerUri: news.authorizerUri,
268 AuthorizerPayloadFormatVersion: news.authorizerPayloadFormatVersion,
269 EnableSimpleResponses: news.enableSimpleResponses,
270 AuthorizerResultTtlInSeconds: toWireSeconds(news.authorizerResultTtl),
271 AuthorizerCredentialsArn: news.authorizerCredentialsArn,
272 IdentityValidationExpression: news.identityValidationExpression,
273 }),
274 );
275 yield* session.note(`Created authorizer ${observed.AuthorizerId}`);
276 return snapshotFromAuthorizer(apiId, observed);
277 }
278
279 // 3. SYNC — update on drift.
280 const snapshot = snapshotFromAuthorizer(apiId, observed);
281 const desiredTtlSeconds = toWireSeconds(news.authorizerResultTtl);
282 const drift =
283 snapshot.name !== name ||
284 snapshot.authorizerType !== news.authorizerType ||
285 (news.identitySource !== undefined &&
286 !deepEqual(snapshot.identitySource, news.identitySource)) ||
287 (news.jwtConfiguration !== undefined &&
288 !deepEqual(snapshot.jwtConfiguration, news.jwtConfiguration)) ||
289 snapshot.authorizerUri !== news.authorizerUri ||
290 snapshot.authorizerPayloadFormatVersion !== news.authorizerPayloadFormatVersion ||
291 (news.enableSimpleResponses !== undefined &&
292 snapshot.enableSimpleResponses !== news.enableSimpleResponses) ||
293 (desiredTtlSeconds !== undefined &&
294 snapshot.authorizerResultTtlInSeconds !== desiredTtlSeconds) ||
295 snapshot.authorizerCredentialsArn !== news.authorizerCredentialsArn ||
296 snapshot.identityValidationExpression !== news.identityValidationExpression;
297 if (drift) {
298 const updated = yield* retryOnTooManyRequests(
299 agw2.updateAuthorizer({
300 ApiId: apiId,
301 AuthorizerId: snapshot.authorizerId,
302 Name: name,
303 AuthorizerType: news.authorizerType,
304 IdentitySource: news.identitySource,
305 JwtConfiguration: news.jwtConfiguration,
306 AuthorizerUri: news.authorizerUri,
307 AuthorizerPayloadFormatVersion: news.authorizerPayloadFormatVersion,
308 EnableSimpleResponses: news.enableSimpleResponses,
309 AuthorizerResultTtlInSeconds: desiredTtlSeconds,
310 AuthorizerCredentialsArn: news.authorizerCredentialsArn,
311 IdentityValidationExpression: news.identityValidationExpression,
312 }),
313 );
314 yield* session.note(`Updated authorizer ${snapshot.authorizerId}`);
315 return snapshotFromAuthorizer(apiId, updated);
316 }
317
318 return snapshot;
319 }),
320
321 delete: Effect.fn(function* ({ output, session }) {
322 yield* retryOnTooManyRequests(
323 agw2
324 .deleteAuthorizer({
325 ApiId: output.apiId,
326 AuthorizerId: output.authorizerId,
327 })
328 .pipe(Effect.catchTag("NotFoundException", () => Effect.void)),
329 );
330 yield* session.note(`Deleted authorizer ${output.authorizerId}`);
331 }),
332 });
333 }),
334 );