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

main
ts 311 lines 12 KB
Raw
1 import type { Input } from "alchemy/Input";
2 import * as Output from "alchemy/Output";
3 import * as Effect from "effect/Effect";
4 import * as AWSBindings from "../AWSBindings.ts";
5 import { AWSEnvironment } from "../Environment.ts";
6 import type { ConfigurationSet } from "./ConfigurationSet.ts";
7 import type { EmailIdentity } from "./EmailIdentity.ts";
8 import type { EmailTemplate } from "./EmailTemplate.ts";
9
10 /**
11 * Shared scaffolding for Amazon SES v2 HTTP bindings.
12 *
13 * NOT exported from `index.ts` — every thin `{Op}Http.ts` in this service is
14 * a `Layer.effect(Cap, make…HttpBinding({ … }))` over one of the builders
15 * below. Everything except the operation, the IAM action list, and the
16 * injected identifier is boilerplate.
17 */
18
19 /**
20 * Build the impl Effect for an account-level SES operation (account status,
21 * account suppression list). These IAM actions do not support resource-level
22 * permissions, so the deploy-time half grants `actions` on `*` and the
23 * runtime callable passes the caller's request through as-is.
24 */
25 export const makeSESHttpBinding = <I, A, E, R>(options: {
26 /** Fully-qualified binding tag, e.g. `AWS.SES.GetAccount`. */
27 tag: string;
28 /** The distilled operation, invoked with the caller's request as-is. */
29 operation: Effect.Effect<(input: I) => Effect.Effect<A, E>, never, R>;
30 /** IAM actions granted on `*`. */
31 actions: readonly string[];
32 }) =>
33 Effect.gen(function* () {
34 const bind = yield* AWSBindings.Bind;
35 const op = yield* AWSBindings.withCredentials(options.operation);
36
37 return Effect.fn(function* () {
38 if (!globalThis.__ALCHEMY_RUNTIME__) {
39 yield* bind`${options.tag}()`({
40 policyStatements: [
41 {
42 Effect: "Allow",
43 Action: [...options.actions],
44 Resource: ["*"],
45 },
46 ],
47 });
48 }
49 return Effect.fn(options.tag)(function* (request?: I) {
50 return yield* op((request ?? {}) as I);
51 });
52 });
53 });
54
55 /**
56 * Build the impl Effect for a template-scoped SES operation. The runtime
57 * callable injects the bound {@link EmailTemplate}'s name as the request's
58 * `TemplateName`; the deploy-time half grants `actions` on the template ARN.
59 */
60 export const makeTemplateScopedHttpBinding = <
61 I extends { TemplateName: string },
62 A,
63 E,
64 R,
65 >(options: {
66 /** Fully-qualified binding tag, e.g. `AWS.SES.RenderEmailTemplate`. */
67 tag: string;
68 /** The distilled operation; `TemplateName` is injected from the resource. */
69 operation: Effect.Effect<(input: I) => Effect.Effect<A, E>, never, R>;
70 /** IAM actions granted on the template ARN. */
71 actions: readonly string[];
72 }) =>
73 Effect.gen(function* () {
74 const bind = yield* AWSBindings.Bind;
75 const op = yield* AWSBindings.withCredentials(options.operation);
76
77 return Effect.fn(function* (template: EmailTemplate) {
78 const TemplateName = yield* template.templateName;
79 if (!globalThis.__ALCHEMY_RUNTIME__) {
80 yield* bind`${options.tag}(${template})`({
81 policyStatements: [
82 {
83 Effect: "Allow",
84 Action: [...options.actions],
85 Resource: [template.templateArn],
86 },
87 ],
88 });
89 }
90 return Effect.fn(`${options.tag}(${template.LogicalId})`)(function* (
91 request: Omit<I, "TemplateName">,
92 ) {
93 return yield* op({
94 ...request,
95 TemplateName: yield* TemplateName,
96 } as I);
97 });
98 });
99 });
100
101 /**
102 * An SES identity referenced by address or domain, used ONLY to scope an IAM
103 * grant.
104 *
105 * Unlike passing an {@link EmailIdentity} resource this creates no resource
106 * edge and no ownership: nothing is created, adopted, or destroyed. That
107 * matters when the identity is managed outside the stack — binding to a
108 * resource would mean owning it, and owning it would mean `destroy` deleting
109 * it.
110 */
111 export interface EmailIdentityRef {
112 /** The verified email address or domain, e.g. `"sender@example.com"`. */
113 emailIdentity: string;
114 }
115
116 // Discriminate on the REF side: a resource's `emailIdentity` is an Output, not
117 // a string. Testing for a resource key with `in` does not work — the resource
118 // is an Output proxy, so every property "exists".
119 const isEmailIdentityRef = (
120 identity: EmailIdentity | EmailIdentityRef,
121 ): identity is EmailIdentityRef => typeof (identity as EmailIdentityRef).emailIdentity === "string";
122
123 /**
124 * Build the impl Effect for `SendCustomVerificationEmail`, scoped to the
125 * identity being VERIFIED.
126 *
127 * Unlike the send bindings, SES authorizes this action against the identity
128 * of the address in the request — the recipient the verification email starts
129 * verification for — not against the template's FROM identity. Confirmed
130 * live: a policy granting only the sender identity is refused with
131 * "not authorized to perform: ses:SendCustomVerificationEmail on resource:
132 * arn:aws:ses:<region>:<account>:identity/<RECIPIENT>".
133 *
134 * So the bound identity names what the function is allowed to verify: a
135 * single address, or a domain, in which case addresses at that domain are
136 * covered. That is the constraint worth enforcing — it stops a leaked binding
137 * being used to send verification mail to arbitrary addresses.
138 *
139 * Accepts a managed {@link EmailIdentity} or an {@link EmailIdentityRef}; the
140 * reference form derives the ARNs from the ambient account and region without
141 * taking ownership. An optional {@link ConfigurationSet} is injected into the
142 * request and added to the grant.
143 */
144 export const makeVerificationScopedHttpBinding = <
145 I extends { ConfigurationSetName?: string },
146 A,
147 E,
148 R,
149 >(options: {
150 /** Fully-qualified binding tag, e.g. `AWS.SES.SendCustomVerificationEmail`. */
151 tag: string;
152 /** The distilled operation. */
153 operation: Effect.Effect<(input: I) => Effect.Effect<A, E>, never, R>;
154 /** IAM actions granted on the identity/address/template ARNs. */
155 actions: readonly string[];
156 }) =>
157 Effect.gen(function* () {
158 const bind = yield* AWSBindings.Bind;
159 const op = yield* AWSBindings.withCredentials(options.operation);
160
161 return Effect.fn(function* (
162 identity: EmailIdentity | EmailIdentityRef,
163 configurationSet?: ConfigurationSet,
164 ) {
165 const ConfigurationSetName = configurationSet
166 ? yield* configurationSet.configurationSetName
167 : undefined;
168 const label = isEmailIdentityRef(identity) ? identity.emailIdentity : identity.LogicalId;
169 if (!globalThis.__ALCHEMY_RUNTIME__) {
170 // Authorize the identity being verified: the address itself, or
171 // every address at the domain when a domain is bound. The account's
172 // custom verification email templates are granted alongside, since
173 // the request also names one.
174 const resources: Input<string>[] = [];
175 if (isEmailIdentityRef(identity)) {
176 const { accountId, region } = yield* AWSEnvironment.current as unknown as Effect.Effect<{
177 accountId: string;
178 region: string;
179 }>;
180 const base = `arn:aws:ses:${region}:${accountId}`;
181 const name = identity.emailIdentity;
182 resources.push(
183 `${base}:identity/${name}`,
184 // A domain reference also authorizes addresses at that domain.
185 name.includes("@") ? `${base}:identity/${name}` : `${base}:identity/*@${name}`,
186 `${base}:custom-verification-email-template/*`,
187 );
188 } else {
189 resources.push(
190 identity.identityArn,
191 Output.all(identity.identityArn).pipe(
192 Output.map(([identityArn]) =>
193 identityArn.includes("@")
194 ? identityArn
195 : identityArn.replace(/:identity\//, ":identity/*@"),
196 ),
197 ),
198 Output.all(identity.identityArn).pipe(
199 Output.map(([identityArn]) =>
200 identityArn.replace(/:identity\/.*$/, ":custom-verification-email-template/*"),
201 ),
202 ),
203 );
204 }
205 if (configurationSet) {
206 resources.push(configurationSet.configurationSetArn);
207 }
208 yield* bind`${options.tag}(${label}, ${configurationSet ?? "none"})`({
209 policyStatements: [
210 {
211 Effect: "Allow",
212 Action: [...options.actions],
213 Resource: resources,
214 },
215 ],
216 });
217 }
218 return Effect.fn(`${options.tag}(${label})`)(function* (
219 request: Omit<I, "ConfigurationSetName">,
220 ) {
221 const configurationSetName = ConfigurationSetName ? yield* ConfigurationSetName : undefined;
222 return yield* op({
223 ...request,
224 ConfigurationSetName: configurationSetName,
225 } as I);
226 });
227 });
228 });
229
230 /**
231 * Build the impl Effect for an identity-scoped send operation (`SendEmail`,
232 * `SendBulkEmail`). The binding resolves the bound {@link EmailIdentity}
233 * (and optional {@link ConfigurationSet}) and:
234 *
235 * - grants `actions` on the identity ARN, on addresses at the identity's
236 * domain (SES authorizes a send against the identity of the FROM address,
237 * not the domain identity ARN), on the account's templates (templated
238 * sends are authorized against the template resource), and on the
239 * configuration set ARN when one is bound;
240 * - at runtime defaults `FromEmailAddress` to the identity and injects the
241 * bound configuration set's name.
242 */
243 export const makeSendScopedHttpBinding = <
244 I extends { FromEmailAddress?: string; ConfigurationSetName?: string },
245 A,
246 E,
247 R,
248 >(options: {
249 /** Fully-qualified binding tag, e.g. `AWS.SES.SendEmail`. */
250 tag: string;
251 /** The distilled send operation. */
252 operation: Effect.Effect<(input: I) => Effect.Effect<A, E>, never, R>;
253 /** IAM actions granted on the identity/address/template/config-set ARNs. */
254 actions: readonly string[];
255 }) =>
256 Effect.gen(function* () {
257 const bind = yield* AWSBindings.Bind;
258 const op = yield* AWSBindings.withCredentials(options.operation);
259
260 return Effect.fn(function* <Identity extends EmailIdentity>(
261 identity: Identity,
262 configurationSet?: ConfigurationSet,
263 ) {
264 const FromIdentity = yield* identity.emailIdentity;
265 const ConfigurationSetName = configurationSet
266 ? yield* configurationSet.configurationSetName
267 : undefined;
268 if (!globalThis.__ALCHEMY_RUNTIME__) {
269 // Templated sends are authorized against the template resource, so
270 // grant the account's templates alongside the bound identity.
271 const templateArns = Output.all(identity.identityArn).pipe(
272 Output.map(([identityArn]) => identityArn.replace(/:identity\/.*$/, ":template/*")),
273 );
274 // For a domain identity, SES authorizes the send against the
275 // identity ARN of the FROM address (identity/user@domain), not the
276 // domain identity ARN — grant addresses at the domain too.
277 const addressArns = Output.all(identity.identityArn).pipe(
278 Output.map(([identityArn]) =>
279 identityArn.includes("@")
280 ? identityArn
281 : identityArn.replace(/:identity\//, ":identity/*@"),
282 ),
283 );
284 yield* bind`${options.tag}(${identity}, ${configurationSet ?? "none"})`({
285 policyStatements: [
286 {
287 Effect: "Allow",
288 Action: [...options.actions],
289 Resource: [
290 identity.identityArn,
291 addressArns,
292 templateArns,
293 ...(configurationSet ? [configurationSet.configurationSetArn] : []),
294 ],
295 },
296 ],
297 });
298 }
299 return Effect.fn(`${options.tag}(${identity.LogicalId})`)(function* (
300 request: Omit<I, "ConfigurationSetName">,
301 ) {
302 const fromIdentity = yield* FromIdentity;
303 const configurationSetName = ConfigurationSetName ? yield* ConfigurationSetName : undefined;
304 return yield* op({
305 ...request,
306 FromEmailAddress: (request as I).FromEmailAddress ?? fromIdentity,
307 ConfigurationSetName: configurationSetName,
308 } as I);
309 });
310 });
311 });