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

main
ts 196 lines 7.86 KB
Raw
1 import type * as Binding from "alchemy/Binding";
2 import type { Input } from "alchemy/Input";
3 import * as Output from "alchemy/Output";
4 import * as Effect from "effect/Effect";
5 import * as Layer from "effect/Layer";
6 import * as AWSBindings from "../AWSBindings.ts";
7 import type { PolicyStatement } from "../IAM/Policy.ts";
8 import { regionFromArn } from "./BindingHttp.ts";
9 import type { MicrovmImage } from "./MicrovmImage.ts";
10
11 // Shared scaffolding for the MicroVM runtime bindings. Every `*Http` impl is
12 // identical except for the distilled operation, the IAM action(s), the policy
13 // scope, and whether the bound image's identifier is injected into the request.
14 // NOT exported from `index.ts` — it only backs the per-operation `*Http` files.
15
16 /** The distilled operation method, yielded to its request callable. */
17 type Operation<Res, Err> = Effect.Effect<(req: any) => Effect.Effect<Res, Err, any>, never, any>;
18
19 export interface ImageBindingOptions<Req, Res, Err, Self> {
20 /** The `Binding.Service` contract this layer implements. */
21 binding: Binding.Service<
22 Self,
23 string,
24 (image: MicrovmImage) => Effect.Effect<(req: Req) => Effect.Effect<Res, Err>>
25 >;
26 /** Operation name, used for the SID label and tracing, e.g. `"RunMicrovm"`. */
27 name: string;
28 /** IAM action(s) the host Function needs, e.g. `["lambda:RunMicrovm"]`. */
29 actions: string[];
30 /** The distilled operation, e.g. `microvms.runMicrovm`. */
31 operation: Operation<Res, Err>;
32 /**
33 * Policy scope (always limited to the bound image's identity — never `["*"]`):
34 * - `"image"` (default) scopes to the exact image ARN (e.g. `RunMicrovm`,
35 * image-read ops).
36 * - `"microvm"` scopes to the MicroVM instances launched from this image via
37 * a `microvm:*` glob derived from the image ARN (same partition, region,
38 * and account). MicroVM instance ARNs are minted at runtime, so an exact
39 * ARN can't be known at deploy time, but the action stays bounded to this
40 * account/region's MicroVMs rather than `["*"]`.
41 * - `"account"` uses `["*"]`. Reserved for collection-level list actions
42 * (e.g. `ListMicrovms`) that AWS only authorizes against `*` and cannot be
43 * resource-scoped, analogous to `ec2:DescribeInstances`.
44 */
45 scope?: "image" | "microvm" | "account";
46 /** Inject `imageIdentifier: <imageArn>` into each request. */
47 injectImageIdentifier?: boolean;
48 /**
49 * Also grant `lambda:PassNetworkConnector` on network connectors in the
50 * image's region — both the account's own connectors and the AWS-managed
51 * ones (e.g. `INTERNET_EGRESS`). Required by `RunMicrovm`, which passes a
52 * network connector (defaulting to the managed `INTERNET_EGRESS`) to the
53 * launched MicroVM.
54 */
55 passNetworkConnector?: boolean;
56 }
57
58 /**
59 * Derive the `microvm:*` instance-ARN glob from an image ARN by swapping the
60 * `microvm-image:<name>` resource segment for `microvm:*`, keeping the same
61 * `arn:<partition>:lambda:<region>:<account>:` prefix.
62 */
63 const microvmGlob = (imageArn: string): string =>
64 `${imageArn.replace(/:microvm-image[:/].*$/, "")}:microvm:*`;
65
66 /**
67 * Derive the network-connector ARN globs from an image ARN: the account's own
68 * connectors (`arn:<partition>:lambda:<region>:<account>:network-connector:*`)
69 * and the AWS-managed connectors (same prefix but account `aws`).
70 */
71 const networkConnectorGlobs = (imageArn: string): string[] => {
72 // arn:<partition>:lambda:<region>:<account>
73 const prefix = imageArn.replace(/:microvm-image[:/].*$/, "");
74 // arn:<partition>:lambda:<region>
75 const regionPrefix = prefix.replace(/:[^:]*$/, "");
76 return [`${prefix}:network-connector:*`, `${regionPrefix}:aws:network-connector:*`];
77 };
78
79 /** The IAM policy statements an image-scoped MicroVM operation requires. */
80 const imagePolicyStatements = <Req, Res, Err, Self>(
81 image: MicrovmImage,
82 options: ImageBindingOptions<Req, Res, Err, Self>,
83 ): Input<PolicyStatement>[] => [
84 {
85 Effect: "Allow",
86 Action: options.actions,
87 Resource:
88 options.scope === "account"
89 ? // Collection-level list actions only authorize on `*`.
90 ["*"]
91 : options.scope === "microvm"
92 ? [
93 // Instance ops (GetMicrovm, TerminateMicrovm, CreateAuthToken,
94 // …) are authorized by AWS against the image ARN as well as the
95 // instance ARN, so grant both: the exact image and the
96 // `microvm:*` instance glob derived from it.
97 Output.interpolate`${image.imageArn}`,
98 image.imageArn.pipe(Output.map(microvmGlob)),
99 ]
100 : [Output.interpolate`${image.imageArn}`],
101 },
102 ...(options.passNetworkConnector
103 ? [
104 {
105 Effect: "Allow" as const,
106 Action: ["lambda:PassNetworkConnector"],
107 Resource: [
108 image.imageArn.pipe(Output.map((a) => networkConnectorGlobs(a)[0]!)),
109 image.imageArn.pipe(Output.map((a) => networkConnectorGlobs(a)[1]!)),
110 ],
111 },
112 ]
113 : []),
114 ];
115
116 /**
117 * Build a MicroVM runtime binding bound to a {@link MicrovmImage}. At deploy it
118 * grants the IAM statements to the host via `AWSBindings.Bind`: the host's
119 * own role, or the Role Alchemy creates for it. At runtime it calls the
120 * distilled operation resolved with `AWSBindings.withCredentials`, signing in
121 * the image's region on a host with a created key.
122 */
123 export const makeImageBinding = <Req, Res, Err, Self>(
124 options: ImageBindingOptions<Req, Res, Err, Self>,
125 ): Layer.Layer<Self> =>
126 Layer.effect(
127 options.binding as any,
128 Effect.gen(function* () {
129 const bind = yield* AWSBindings.Bind;
130 return Effect.fn(function* (image: MicrovmImage) {
131 // Accessors (registered on the host at deploy, resolved at runtime).
132 const imageArn = yield* image.imageArn;
133 // Region is derived from the resolved image ARN — via `Effect.map` of
134 // the accessor, NOT a second Output binding (whose env key would embed
135 // the mapper's source text and is brittle).
136 // resolved per bind because a host with a created key signs in the image's own region
137 const run = yield* AWSBindings.withCredentials(
138 options.operation,
139 Effect.succeed(Effect.map(imageArn, regionFromArn)),
140 );
141
142 if (!globalThis.__ALCHEMY_RUNTIME__) {
143 yield* bind`AWS.Lambda.${options.name}(${image})`({
144 policyStatements: imagePolicyStatements(image, options),
145 });
146 }
147
148 return Effect.fn(`AWS.Lambda.${options.name}(${image.LogicalId})`)(function* (
149 request: Req,
150 ) {
151 return yield* run(
152 options.injectImageIdentifier
153 ? { ...(request as object), imageIdentifier: yield* imageArn }
154 : request,
155 );
156 });
157 });
158 }),
159 ) as unknown as Layer.Layer<Self>;
160
161 export interface AccountBindingOptions<Req, Res, Err, Self> {
162 binding: Binding.Service<
163 Self,
164 string,
165 () => Effect.Effect<(req: Req) => Effect.Effect<Res, Err>>
166 >;
167 name: string;
168 actions: string[];
169 operation: Operation<Res, Err>;
170 }
171
172 /**
173 * Build an account-scoped MicroVM binding (no resource argument), e.g. for
174 * listing AWS-managed base images. IAM `Resource` is `["*"]`.
175 */
176 export const makeAccountBinding = <Req, Res, Err, Self>(
177 options: AccountBindingOptions<Req, Res, Err, Self>,
178 ): Layer.Layer<Self> =>
179 Layer.effect(
180 options.binding as any,
181 Effect.gen(function* () {
182 const bind = yield* AWSBindings.Bind;
183 const run = yield* AWSBindings.withCredentials(options.operation);
184 return Effect.fn(function* () {
185 if (!globalThis.__ALCHEMY_RUNTIME__) {
186 yield* bind`AWS.Lambda.${options.name}()`({
187 policyStatements: [{ Effect: "Allow", Action: options.actions, Resource: ["*"] }],
188 });
189 }
190
191 return Effect.fn(`AWS.Lambda.${options.name}()`)(function* (request: Req) {
192 return yield* run(request);
193 });
194 });
195 }),
196 ) as unknown as Layer.Layer<Self>;