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

main
ts 275 lines 9.56 KB
Raw
1 import * as sesv2 from "@distilled.cloud/aws/sesv2";
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 * as Stream from "effect/Stream";
8 import {
9 normalizePolicyDocument,
10 stringifyPolicyDocument,
11 type PolicyDocument,
12 } from "../IAM/Policy.ts";
13 import type { Providers } from "../Providers.ts";
14
15 export interface EmailIdentityPolicyProps {
16 /**
17 * The email address or domain identity the sending-authorization policy is
18 * attached to. Typically the `emailIdentity` output of a
19 * `SES.EmailIdentity`. Changing it replaces the policy.
20 */
21 emailIdentity: string;
22 /**
23 * Name of the policy. May contain letters, numbers, dashes and underscores,
24 * up to 64 characters. If omitted, a deterministic physical name is
25 * generated from the app, stage, and logical ID. Changing it replaces the
26 * policy.
27 */
28 policyName?: string;
29 /**
30 * The IAM policy document that grants sending authorization. Equivalent
31 * document representations are ignored when detecting drift.
32 */
33 policy: PolicyDocument;
34 }
35
36 export interface EmailIdentityPolicy extends Resource<
37 "AWS.SES.EmailIdentityPolicy",
38 EmailIdentityPolicyProps,
39 {
40 /** The identity the policy is attached to. */
41 emailIdentity: string;
42 /** Name of the policy. */
43 policyName: string;
44 },
45 never,
46 Providers
47 > {}
48
49 /**
50 * An Amazon SES v2 sending-authorization policy attached to an email identity —
51 * lets the identity owner authorize other AWS accounts or IAM principals to
52 * send email using the identity.
53 *
54 * SES stores the policy document as JSON; Alchemy serializes the typed IAM
55 * policy at the API boundary and compares its normalized content for drift.
56 * ### Attaching a Policy
57 * **Example:** Authorize Another Account to Send
58 * ```typescript
59 * import * as SES from "@alchemy.run/aws/SES";
60 *
61 * const identity = yield* SES.EmailIdentity("Sender", {
62 * emailIdentity: "mail.example.com",
63 * });
64 *
65 * const policy = yield* SES.EmailIdentityPolicy("AllowPartner", {
66 * emailIdentity: identity.emailIdentity,
67 * policy: {
68 * Version: "2012-10-17",
69 * Statement: [
70 * {
71 * Effect: "Allow",
72 * Principal: { AWS: "arn:aws:iam::111122223333:root" },
73 * Action: ["ses:SendEmail"],
74 * Resource: identity.identityArn,
75 * },
76 * ],
77 * },
78 * });
79 * ```
80 *
81 * **Example:** Explicit Policy Name
82 * ```typescript
83 * // Without policyName a deterministic name is derived from app/stage/id.
84 * const policy = yield* SES.EmailIdentityPolicy("AllowPartner", {
85 * emailIdentity: identity.emailIdentity,
86 * policyName: "partner-send",
87 * policy: {
88 * Version: "2012-10-17",
89 * Statement: [
90 * {
91 * Effect: "Allow",
92 * Principal: { AWS: "arn:aws:iam::111122223333:root" },
93 * Action: ["ses:SendEmail"],
94 * Resource: identity.identityArn,
95 * },
96 * ],
97 * },
98 * });
99 * ```
100 *
101 * **Example:** Restrict the Grant with Conditions
102 * ```typescript
103 * const policy = yield* SES.EmailIdentityPolicy("AllowPartnerScoped", {
104 * emailIdentity: identity.emailIdentity,
105 * policy: {
106 * Version: "2012-10-17",
107 * Statement: [
108 * {
109 * Effect: "Allow",
110 * Principal: { AWS: "arn:aws:iam::111122223333:root" },
111 * Action: ["ses:SendEmail", "ses:SendRawEmail"],
112 * Resource: identity.identityArn,
113 * Condition: {
114 * StringEquals: { "ses:FromAddress": "noreply@mail.example.com" },
115 * },
116 * },
117 * ],
118 * },
119 * });
120 * ```
121 *
122 * **Example:** Several Policies on One Identity
123 * ```typescript
124 * // Each policy is a separate resource keyed by its own name.
125 * for (const partner of ["111122223333", "444455556666"]) {
126 * yield* SES.EmailIdentityPolicy(`Allow${partner}`, {
127 * emailIdentity: identity.emailIdentity,
128 * policyName: `partner-${partner}`,
129 * policy: {
130 * Version: "2012-10-17",
131 * Statement: [
132 * {
133 * Effect: "Allow",
134 * Principal: { AWS: `arn:aws:iam::${partner}:root` },
135 * Action: ["ses:SendEmail"],
136 * Resource: identity.identityArn,
137 * },
138 * ],
139 * },
140 * });
141 * }
142 * ```
143 *
144 * @resource
145 */
146 export const EmailIdentityPolicy = Resource<EmailIdentityPolicy>("AWS.SES.EmailIdentityPolicy");
147
148 export const EmailIdentityPolicyProvider = () =>
149 Provider.effect(
150 EmailIdentityPolicy,
151 Effect.gen(function* () {
152 const createName = Effect.fn(function* (
153 id: string,
154 props: Pick<EmailIdentityPolicyProps, "policyName">,
155 ) {
156 return props.policyName ?? (yield* createPhysicalName({ id, maxLength: 64 }));
157 });
158
159 // Returns the policy-name -> document map for the identity, or undefined
160 // when the identity itself no longer exists.
161 const getPolicies = Effect.fn(function* (emailIdentity: string) {
162 return yield* sesv2.getEmailIdentityPolicies({ EmailIdentity: emailIdentity }).pipe(
163 Effect.map((response) => response.Policies ?? {}),
164 Effect.catchTag("NotFoundException", () => Effect.undefined),
165 );
166 });
167
168 return EmailIdentityPolicy.Provider.of({
169 // Deleting a policy requires its parent identity to still exist, so
170 // the identity must outlive every policy nuke tears down.
171 nuke: { dependsOn: ["AWS.SES.EmailIdentity"] },
172 stables: ["emailIdentity", "policyName"],
173
174 // Policies are keyed by their parent identity, so enumeration walks
175 // every identity and reads its policy map. getPolicies already treats
176 // a vanished identity as "no policies".
177 list: Effect.fn(function* () {
178 const pages = yield* sesv2.listEmailIdentities.pages({}).pipe(Stream.runCollect);
179 const identities = Array.from(pages)
180 .flatMap((page) => page.EmailIdentities ?? [])
181 .flatMap((info) => (info.IdentityName ? [info.IdentityName] : []));
182 const nested = yield* Effect.forEach(
183 identities,
184 (emailIdentity) =>
185 getPolicies(emailIdentity).pipe(
186 Effect.map((policies) =>
187 Object.keys(policies ?? {}).map((policyName) => ({
188 emailIdentity,
189 policyName,
190 })),
191 ),
192 ),
193 { concurrency: 2 },
194 );
195 return nested.flat();
196 }),
197
198 read: Effect.fn(function* ({ id, olds, output }) {
199 const emailIdentity = output?.emailIdentity ?? olds?.emailIdentity;
200 if (emailIdentity === undefined) return undefined;
201 const policyName = output?.policyName ?? (yield* createName(id, olds ?? {}));
202 const policies = yield* getPolicies(emailIdentity);
203 if (policies === undefined || policies[policyName] === undefined) {
204 return undefined;
205 }
206 // Policies carry no tags, so existence at our deterministic name is
207 // treated as ownership.
208 return { emailIdentity, policyName };
209 }),
210
211 diff: Effect.fn(function* ({ id, news, olds }) {
212 if (!isResolved(news)) return undefined;
213 const oldName = yield* createName(id, olds);
214 const newName = yield* createName(id, news);
215 if (oldName !== newName || olds.emailIdentity !== news.emailIdentity) {
216 return { action: "replace" } as const;
217 }
218 }),
219
220 reconcile: Effect.fn(function* ({ id, news, output }) {
221 const emailIdentity = output?.emailIdentity ?? news.emailIdentity;
222 const policyName = output?.policyName ?? (yield* createName(id, news));
223
224 // 1. OBSERVE — cloud state is authoritative.
225 const policies = yield* getPolicies(emailIdentity);
226 const existing = policies?.[policyName];
227 const desiredPolicy = stringifyPolicyDocument(news.policy);
228
229 if (existing === undefined) {
230 // 2. ENSURE — create; AlreadyExists is a race → converge via update.
231 yield* sesv2
232 .createEmailIdentityPolicy({
233 EmailIdentity: emailIdentity,
234 PolicyName: policyName,
235 Policy: desiredPolicy,
236 })
237 .pipe(
238 Effect.catchTag("AlreadyExistsException", () =>
239 sesv2.updateEmailIdentityPolicy({
240 EmailIdentity: emailIdentity,
241 PolicyName: policyName,
242 Policy: desiredPolicy,
243 }),
244 ),
245 );
246 } else {
247 // 3. SYNC — update only when the stored document differs.
248 const changed = yield* Effect.sync(
249 () => normalizePolicyDocument(existing) !== normalizePolicyDocument(news.policy),
250 );
251 if (changed) {
252 yield* sesv2.updateEmailIdentityPolicy({
253 EmailIdentity: emailIdentity,
254 PolicyName: policyName,
255 Policy: desiredPolicy,
256 });
257 }
258 }
259
260 return { emailIdentity, policyName };
261 }),
262
263 delete: Effect.fn(function* ({ output }) {
264 // deleteEmailIdentityPolicy succeeds even if the policy is absent; a
265 // missing identity means the policy is already gone.
266 yield* sesv2
267 .deleteEmailIdentityPolicy({
268 EmailIdentity: output.emailIdentity,
269 PolicyName: output.policyName,
270 })
271 .pipe(Effect.catchTag("NotFoundException", () => Effect.void));
272 }),
273 });
274 }),
275 );