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

main
ts 170 lines 5.99 KB
Raw
1 import * as logs from "@distilled.cloud/aws/cloudwatch-logs";
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 Schedule from "effect/Schedule";
8 import type { PolicyDocument } from "../IAM/Policy.ts";
9 import type { Providers } from "../Providers.ts";
10
11 export interface ResourcePolicyProps {
12 /**
13 * Name of the resource policy. The policy name is the identity of the
14 * policy within the account and region (put semantics upsert by name).
15 * If omitted, a unique name is generated. Changing this value replaces
16 * the policy.
17 */
18 policyName?: string;
19 /**
20 * The policy document granting an AWS service principal (e.g.
21 * `route53.amazonaws.com`, `es.amazonaws.com`) permission to write to
22 * CloudWatch Logs, either as a JSON string or a structured document.
23 */
24 policyDocument: PolicyDocument | string;
25 }
26
27 export interface ResourcePolicy extends Resource<
28 "AWS.Logs.ResourcePolicy",
29 ResourcePolicyProps,
30 {
31 policyName: string;
32 policyDocument: string;
33 },
34 never,
35 Providers
36 > {}
37
38 /**
39 * An account-scoped CloudWatch Logs resource policy — grants AWS service
40 * principals (Route 53 query logging, API Gateway execution logs, OpenSearch
41 * slow logs, ...) permission to deliver logs into your account.
42 *
43 * :::warning
44 * AWS allows at most **10 resource policies per region per account** and the
45 * quota cannot be raised. Always use a deterministic `policyName` and destroy
46 * policies you no longer need.
47 * :::
48 * ### Granting Log Delivery
49 * **Example:** Allow Route 53 Query Logging
50 * ```typescript
51 * const policy = yield* ResourcePolicy("Route53QueryLogging", {
52 * policyName: "route53-query-logging",
53 * policyDocument: {
54 * Version: "2012-10-17",
55 * Statement: [
56 * {
57 * Effect: "Allow",
58 * Principal: { Service: "route53.amazonaws.com" },
59 * Action: ["logs:CreateLogStream", "logs:PutLogEvents"],
60 * Resource: `arn:aws:logs:us-east-1:${accountId}:log-group:/aws/route53/*`,
61 * },
62 * ],
63 * },
64 * });
65 * ```
66 *
67 * @resource
68 */
69 export const ResourcePolicy = Resource<ResourcePolicy>("AWS.Logs.ResourcePolicy");
70
71 export const ResourcePolicyProvider = () =>
72 Provider.effect(
73 ResourcePolicy,
74 Effect.gen(function* () {
75 const toPolicyName = (id: string, props: { policyName?: string } = {}) =>
76 props.policyName
77 ? Effect.succeed(props.policyName)
78 : createPhysicalName({ id, maxLength: 255 });
79
80 const toDocumentString = (document: PolicyDocument | string) =>
81 typeof document === "string" ? document : JSON.stringify(document);
82
83 // The account quota is 10 policies per region, so a single describe
84 // call (limit 50) is always exhaustive — no pagination needed.
85 const describeAll = logs
86 .describeResourcePolicies({ limit: 50 })
87 .pipe(Effect.map((response) => response.resourcePolicies ?? []));
88
89 const observe = Effect.fn(function* (policyName: string) {
90 const policies = yield* describeAll;
91 return policies.find((policy) => policy.policyName === policyName);
92 });
93
94 return {
95 stables: ["policyName"],
96 list: () =>
97 describeAll.pipe(
98 Effect.map((policies) =>
99 policies
100 .filter(
101 (policy): policy is logs.ResourcePolicy & { policyName: string } =>
102 policy.policyName != null,
103 )
104 .map((policy) => ({
105 policyName: policy.policyName,
106 policyDocument: policy.policyDocument ?? "",
107 })),
108 ),
109 ),
110 diff: Effect.fn(function* ({ id, olds, news }) {
111 if (!isResolved(news)) return;
112 if ((yield* toPolicyName(id, olds)) !== (yield* toPolicyName(id, news))) {
113 return { action: "replace" } as const;
114 }
115 }),
116 read: Effect.fn(function* ({ id, olds, output }) {
117 const policyName = output?.policyName ?? (yield* toPolicyName(id, olds ?? {}));
118 const observed = yield* observe(policyName);
119 if (!observed) return undefined;
120 return {
121 policyName,
122 policyDocument: observed.policyDocument ?? "",
123 };
124 }),
125 reconcile: Effect.fn(function* ({ id, news, output, session }) {
126 const policyName = output?.policyName ?? (yield* toPolicyName(id, news));
127 const desiredDocument = toDocumentString(news.policyDocument);
128
129 // Observe — putResourcePolicy upserts by name; skip the put when the
130 // live document already matches the desired one.
131 const observed = yield* observe(policyName);
132 if (observed?.policyDocument !== desiredDocument) {
133 yield* logs
134 .putResourcePolicy({
135 policyName,
136 policyDocument: desiredDocument,
137 })
138 .pipe(
139 Effect.retry({
140 while: (error) =>
141 error._tag === "OperationAbortedException" ||
142 error._tag === "ServiceUnavailableException",
143 schedule: Schedule.exponential(100),
144 times: 8,
145 }),
146 );
147 }
148
149 yield* session.note(policyName);
150
151 return {
152 policyName,
153 policyDocument: desiredDocument,
154 };
155 }),
156 delete: Effect.fn(function* ({ output }) {
157 yield* logs.deleteResourcePolicy({ policyName: output.policyName }).pipe(
158 Effect.retry({
159 while: (error) =>
160 error._tag === "OperationAbortedException" ||
161 error._tag === "ServiceUnavailableException",
162 schedule: Schedule.exponential(100),
163 times: 8,
164 }),
165 Effect.catchTag("ResourceNotFoundException", () => Effect.void),
166 );
167 }),
168 };
169 }),
170 );