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

main
ts 245 lines 8.45 KB
Raw
1 import * as iot from "@distilled.cloud/aws/iot";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import { createPhysicalName } from "alchemy/PhysicalName";
5 import * as Provider from "alchemy/Provider";
6 import { Resource } from "alchemy/Resource";
7 import { hasAlchemyTags } from "alchemy/Tags";
8 import * as Effect from "effect/Effect";
9 import * as Stream from "effect/Stream";
10 import type { Providers } from "../Providers.ts";
11 import { readIotTags, syncIotTags } from "./internal.ts";
12
13 /**
14 * An IoT policy statement. Structurally similar to an IAM statement but
15 * scopes IoT actions (`iot:Connect`, `iot:Publish`, `iot:Subscribe`,
16 * `iot:Receive`) to topic / client ARNs.
17 */
18 export interface IoTPolicyStatement {
19 Effect: "Allow" | "Deny";
20 Action: string | string[];
21 Resource: string | string[];
22 }
23
24 export interface IoTPolicyDocument {
25 Version?: string;
26 Statement: IoTPolicyStatement[];
27 }
28
29 export interface PolicyProps {
30 /**
31 * Name of the policy. If omitted, a unique name is generated.
32 * Changing it replaces the policy.
33 */
34 policyName?: string;
35
36 /**
37 * The JSON policy document, either as a string or a structured document.
38 */
39 policyDocument: string | IoTPolicyDocument;
40
41 /**
42 * User tags to attach to the policy.
43 */
44 tags?: Record<string, string>;
45 }
46
47 export interface Policy extends Resource<
48 "AWS.IoT.Policy",
49 PolicyProps,
50 {
51 /** The name of the policy. */
52 policyName: string;
53 /** The ARN of the policy. */
54 policyArn: string;
55 },
56 never,
57 Providers
58 > {}
59
60 /**
61 * An AWS IoT policy that grants MQTT permissions (connect, publish,
62 * subscribe, receive) to certificates and other principals.
63 *
64 * ### Creating a Policy
65 * **Example:** Allow Publish and Subscribe
66 * ```typescript
67 * const policy = yield* Policy("device-policy", {
68 * policyDocument: {
69 * Version: "2012-10-17",
70 * Statement: [
71 * { Effect: "Allow", Action: "iot:Connect", Resource: "*" },
72 * { Effect: "Allow", Action: ["iot:Publish", "iot:Receive"], Resource: "*" },
73 * ],
74 * },
75 * });
76 * ```
77 *
78 * @resource
79 */
80 export const Policy = Resource<Policy>("AWS.IoT.Policy");
81
82 const stringifyDocument = (doc: string | IoTPolicyDocument): string =>
83 typeof doc === "string" ? doc : JSON.stringify(doc);
84
85 // Normalize a policy document to a stable canonical JSON string for diffing.
86 const normalizeDocument = (doc: string | undefined): string => {
87 if (!doc) return "";
88 try {
89 return JSON.stringify(JSON.parse(doc));
90 } catch {
91 return doc;
92 }
93 };
94
95 export const PolicyProvider = () =>
96 Provider.effect(
97 Policy,
98 Effect.gen(function* () {
99 const createName = Effect.fn(function* (id: string, props: PolicyProps) {
100 return props.policyName ?? (yield* createPhysicalName({ id, maxLength: 128 }));
101 });
102
103 return Policy.Provider.of({
104 stables: ["policyName", "policyArn"],
105 list: () =>
106 iot.listPolicies.pages({}).pipe(
107 Stream.runCollect,
108 Effect.map((chunk) =>
109 Array.from(chunk).flatMap((page) =>
110 (page.policies ?? [])
111 .filter((p) => p.policyName != null && p.policyArn != null)
112 .map((p) => ({
113 policyName: p.policyName!,
114 policyArn: p.policyArn!,
115 })),
116 ),
117 ),
118 ),
119 read: Effect.fn(function* ({ id, olds, output }) {
120 const policyName = output?.policyName ?? (yield* createName(id, olds ?? {}));
121 const found = yield* iot
122 .getPolicy({ policyName })
123 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
124 if (!found) return undefined;
125 const attrs = {
126 policyName,
127 policyArn: found.policyArn!,
128 };
129 const tags = yield* readIotTags(found.policyArn!);
130 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
131 }),
132 diff: Effect.fn(function* ({ id, news, olds }) {
133 if (!isResolved(news)) return undefined;
134 const oldName = yield* createName(id, olds);
135 const newName = yield* createName(id, news);
136 if (oldName !== newName) return { action: "replace" } as const;
137 return undefined;
138 }),
139 reconcile: Effect.fn(function* ({ id, news, output, session }) {
140 const policyName = output?.policyName ?? (yield* createName(id, news));
141 const desiredDocument = stringifyDocument(news.policyDocument);
142
143 // OBSERVE
144 let live = yield* iot
145 .getPolicy({ policyName })
146 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
147
148 // ENSURE
149 if (live === undefined) {
150 yield* iot
151 .createPolicy({ policyName, policyDocument: desiredDocument })
152 .pipe(Effect.catchTag("ResourceAlreadyExistsException", () => Effect.void));
153 live = yield* iot.getPolicy({ policyName });
154 } else if (
155 normalizeDocument(live.policyDocument) !== normalizeDocument(desiredDocument)
156 ) {
157 // SYNC document — a new default version. IoT caps a policy at 5
158 // versions, so prune the oldest non-default version first.
159 const { policyVersions = [] } = yield* iot.listPolicyVersions({
160 policyName,
161 });
162 const nonDefault = policyVersions
163 .filter((v) => !v.isDefaultVersion && v.versionId)
164 .sort((a, b) => (a.versionId! < b.versionId! ? -1 : 1));
165 if (policyVersions.length >= 5 && nonDefault[0]?.versionId) {
166 yield* iot
167 .deletePolicyVersion({
168 policyName,
169 policyVersionId: nonDefault[0].versionId,
170 })
171 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
172 }
173 yield* iot.createPolicyVersion({
174 policyName,
175 policyDocument: desiredDocument,
176 setAsDefault: true,
177 });
178 live = yield* iot.getPolicy({ policyName });
179 }
180
181 // SYNC tags
182 yield* syncIotTags(live.policyArn!, id, news.tags);
183
184 yield* session.note(policyName);
185 return {
186 policyName,
187 policyArn: live.policyArn!,
188 };
189 }),
190 delete: Effect.fn(function* ({ output }) {
191 const policyName = output.policyName;
192 // Delete all non-default versions first — deletePolicy rejects a
193 // policy that still has extra versions.
194 const { policyVersions = [] } = yield* iot
195 .listPolicyVersions({ policyName })
196 .pipe(
197 Effect.catchTag("ResourceNotFoundException", () =>
198 Effect.succeed({ policyVersions: [] }),
199 ),
200 );
201 yield* Effect.forEach(
202 policyVersions.filter((v) => !v.isDefaultVersion && v.versionId),
203 (v) =>
204 iot
205 .deletePolicyVersion({
206 policyName,
207 policyVersionId: v.versionId!,
208 })
209 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void)),
210 );
211 // Detach any lingering targets (certificates/groups) before delete.
212 const detachTargets = Effect.gen(function* () {
213 const { targets = [] } = yield* iot
214 .listTargetsForPolicy({ policyName })
215 .pipe(
216 Effect.catchTag("ResourceNotFoundException", () => Effect.succeed({ targets: [] })),
217 );
218 yield* Effect.forEach(targets, (target) =>
219 iot
220 .detachPolicy({ policyName, target })
221 .pipe(Effect.catchTag("InvalidRequestException", () => Effect.void)),
222 );
223 });
224 yield* iot.deletePolicy({ policyName }).pipe(
225 Effect.catchTags({
226 ResourceNotFoundException: () => Effect.void,
227 DeleteConflictException: () =>
228 detachTargets.pipe(
229 Effect.andThen(
230 iot
231 .deletePolicy({ policyName })
232 .pipe(
233 Effect.catchTag(
234 ["ResourceNotFoundException", "DeleteConflictException"],
235 () => Effect.void,
236 ),
237 ),
238 ),
239 ),
240 }),
241 );
242 }),
243 });
244 }),
245 );