@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 06:00 UTC

main
ts 322 lines 11.6 KB
Raw
1 import * as iam from "@distilled.cloud/aws/iam";
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 { createInternalTags, createTagsList, diffTags } from "alchemy/Tags";
7 import * as Data from "effect/Data";
8 import * as Effect from "effect/Effect";
9 import * as Option from "effect/Option";
10 import * as Redacted from "effect/Redacted";
11 import * as Stream from "effect/Stream";
12 import type { Providers } from "../Providers.ts";
13 import { toRedactedBytes, toTagRecord } from "./common.ts";
14
15 export class VirtualMFADeviceUnexpectedResponse extends Data.TaggedError(
16 "VirtualMFADeviceUnexpectedResponse",
17 )<{
18 readonly message: string;
19 readonly cause?: unknown;
20 }> {}
21
22 export interface VirtualMFADeviceProps {
23 /**
24 * Name of the virtual MFA device. If omitted, a deterministic name is generated.
25 */
26 virtualMFADeviceName?: string;
27 /**
28 * Optional IAM path prefix.
29 * @default "/"
30 */
31 path?: string;
32 /**
33 * Optional user to activate the device for.
34 */
35 userName?: string;
36 /**
37 * First authentication code used when activating the device.
38 */
39 authenticationCode1?: string;
40 /**
41 * Second authentication code used when activating the device.
42 */
43 authenticationCode2?: string;
44 /**
45 * User-defined tags.
46 */
47 tags?: Record<string, string>;
48 }
49
50 export interface VirtualMFADevice extends Resource<
51 "AWS.IAM.VirtualMFADevice",
52 VirtualMFADeviceProps,
53 {
54 /** The serial number (ARN) of the virtual MFA device. */
55 serialNumber: string;
56 /** The user the device is enabled for, if activated. */
57 userName: string | undefined;
58 /** When the device was activated, if activated. */
59 enableDate: Date | undefined;
60 /** The base32 seed for configuring an authenticator app. AWS only returns it at creation. */
61 base32StringSeed: Redacted.Redacted<Uint8Array<ArrayBufferLike>> | undefined;
62 /** A QR-code PNG encoding the seed. AWS only returns it at creation. */
63 qrCodePNG: Redacted.Redacted<Uint8Array<ArrayBufferLike>> | undefined;
64 /** The tags applied to the device. */
65 tags: Record<string, string>;
66 },
67 never,
68 Providers
69 > {}
70
71 /**
72 * An IAM virtual MFA device.
73 *
74 * `VirtualMFADevice` creates a software MFA device and can optionally activate
75 * it for a user during creation when the initial authentication codes are
76 * provided.
77 * ### Managing MFA Devices
78 * **Example:** Create and Activate a Virtual MFA Device
79 * ```typescript
80 * const user = yield* User("AdminUser", {
81 * userName: "admin-user",
82 * });
83 *
84 * const device = yield* VirtualMFADevice("AdminMfa", {
85 * userName: user.userName,
86 * authenticationCode1: "123456",
87 * authenticationCode2: "654321",
88 * });
89 * ```
90 *
91 * @resource
92 */
93 export const VirtualMFADevice = Resource<VirtualMFADevice>("AWS.IAM.VirtualMFADevice");
94
95 export const VirtualMFADeviceProvider = () =>
96 Provider.effect(
97 VirtualMFADevice,
98 Effect.gen(function* () {
99 const toName = (id: string, props: VirtualMFADeviceProps) =>
100 props.virtualMFADeviceName
101 ? Effect.succeed(props.virtualMFADeviceName)
102 : createPhysicalName({ id, maxLength: 226 });
103
104 const readDevice = Effect.fn(function* ({
105 serialNumber,
106 userName,
107 }: {
108 serialNumber: string;
109 userName: string | undefined;
110 }) {
111 if (!userName) {
112 const device = yield* iam.listVirtualMFADevices
113 .items({ AssignmentStatus: "Unassigned" })
114 .pipe(
115 Stream.filter((entry) => entry.SerialNumber === serialNumber),
116 Stream.runHead,
117 Effect.map(Option.getOrUndefined),
118 );
119 return device
120 ? {
121 SerialNumber: device.SerialNumber,
122 UserName: device.User?.UserName,
123 EnableDate: device.EnableDate,
124 }
125 : undefined;
126 }
127 return yield* iam
128 .getMFADevice({
129 SerialNumber: serialNumber,
130 UserName: userName,
131 })
132 .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.undefined));
133 });
134
135 return {
136 stables: ["serialNumber"],
137 list: () =>
138 Effect.gen(function* () {
139 // Enumerate every virtual MFA device in the account. The list op
140 // does not return tags, so hydrate them per-device via
141 // listMFADeviceTags (matching the exact shape `read` returns).
142 const devices = yield* iam.listVirtualMFADevices.pages({}).pipe(
143 Stream.runCollect,
144 Effect.map((chunk) =>
145 Array.from(chunk).flatMap((page) => page.VirtualMFADevices ?? []),
146 ),
147 );
148 return yield* Effect.forEach(
149 devices,
150 (device) =>
151 Effect.gen(function* () {
152 const tags = yield* iam
153 .listMFADeviceTags({
154 SerialNumber: device.SerialNumber,
155 })
156 .pipe(
157 Effect.map((resp) => resp.Tags),
158 // The device may vanish between listing and tag lookup.
159 Effect.catchTag("NoSuchEntityException", () => Effect.succeed<iam.Tag[]>([])),
160 );
161 return {
162 serialNumber: device.SerialNumber,
163 userName: device.User?.UserName,
164 enableDate: device.EnableDate,
165 // The seed and QR code are only returned at creation time
166 // and are never available from enumeration.
167 base32StringSeed: undefined,
168 qrCodePNG: undefined,
169 tags: toTagRecord(tags),
170 };
171 }),
172 { concurrency: 10 },
173 );
174 }),
175 diff: Effect.fn(function* ({ id, olds, news }) {
176 if (!isResolved(news)) return;
177 if (
178 (yield* toName(id, olds ?? ({} as VirtualMFADeviceProps))) !==
179 (yield* toName(id, news)) ||
180 (olds.path ?? "/") !== (news.path ?? "/") ||
181 (olds.userName ?? undefined) !== (news.userName ?? undefined) ||
182 (olds.authenticationCode1 ?? undefined) !== (news.authenticationCode1 ?? undefined) ||
183 (olds.authenticationCode2 ?? undefined) !== (news.authenticationCode2 ?? undefined)
184 ) {
185 return { action: "replace" } as const;
186 }
187 }),
188 read: Effect.fn(function* ({ output }) {
189 if (!output) {
190 return undefined;
191 }
192 const response = yield* readDevice({
193 serialNumber: output.serialNumber,
194 userName: output.userName,
195 });
196 if (!response?.SerialNumber) {
197 return undefined;
198 }
199 const tags = yield* iam.listMFADeviceTags({
200 SerialNumber: output.serialNumber,
201 });
202 return {
203 serialNumber: response.SerialNumber,
204 userName: response.UserName ?? output.userName,
205 enableDate: response.EnableDate,
206 base32StringSeed: output.base32StringSeed,
207 qrCodePNG: output.qrCodePNG,
208 tags: toTagRecord(tags.Tags),
209 };
210 }),
211 reconcile: Effect.fn(function* ({ id, news, output, session }) {
212 const desiredTags = {
213 ...(yield* createInternalTags(id)),
214 ...news.tags,
215 };
216
217 // Observe — virtual MFA devices have AWS-generated serial
218 // numbers, so we can only locate the existing device when we
219 // already have its serial from a prior output.
220 const observed = output
221 ? yield* readDevice({
222 serialNumber: output.serialNumber,
223 userName: output.userName,
224 })
225 : undefined;
226
227 // Ensure — create the device when missing. The seed and QR
228 // code are only returned on creation, so on adoption the best
229 // we can do is preserve the existing redacted values.
230 let serialNumber = observed?.SerialNumber ?? output?.serialNumber;
231 let base32StringSeed = output?.base32StringSeed;
232 let qrCodePNG = output?.qrCodePNG;
233
234 if (!observed?.SerialNumber) {
235 const deviceName = yield* toName(id, news);
236 const created = yield* iam.createVirtualMFADevice({
237 Path: news.path,
238 VirtualMFADeviceName: deviceName,
239 Tags: createTagsList(desiredTags),
240 });
241 if (!created.VirtualMFADevice.SerialNumber) {
242 return yield* new VirtualMFADeviceUnexpectedResponse({
243 message: `createVirtualMFADevice returned no serial number`,
244 });
245 }
246 serialNumber = created.VirtualMFADevice.SerialNumber;
247 base32StringSeed = toRedactedBytes(created.VirtualMFADevice.Base32StringSeed);
248 qrCodePNG = toRedactedBytes(created.VirtualMFADevice.QRCodePNG);
249
250 // The device was just created, so it is unassigned. Activate
251 // it for the user when activation codes are provided. After
252 // first activation the codes lose their meaning (`diff`
253 // triggers replacement on code change).
254 if (news.userName && news.authenticationCode1 && news.authenticationCode2) {
255 yield* iam.enableMFADevice({
256 UserName: news.userName,
257 SerialNumber: serialNumber,
258 AuthenticationCode1: news.authenticationCode1,
259 AuthenticationCode2: news.authenticationCode2,
260 });
261 }
262 }
263
264 if (!serialNumber) {
265 return yield* new VirtualMFADeviceUnexpectedResponse({
266 message: `Virtual MFA device has no serial number`,
267 });
268 }
269
270 // Sync tags against the cloud's actual tags.
271 const observedTagsResp = yield* iam.listMFADeviceTags({
272 SerialNumber: serialNumber,
273 });
274 const observedTags = toTagRecord(observedTagsResp.Tags);
275 const { removed, upsert } = diffTags(observedTags, desiredTags);
276 if (upsert.length > 0) {
277 yield* iam.tagMFADevice({
278 SerialNumber: serialNumber,
279 Tags: upsert,
280 });
281 }
282 if (removed.length > 0) {
283 yield* iam.untagMFADevice({
284 SerialNumber: serialNumber,
285 TagKeys: removed,
286 });
287 }
288
289 // Re-read for fresh `EnableDate` / `UserName` after activation.
290 const fresh = yield* readDevice({
291 serialNumber,
292 userName: news.userName ?? output?.userName,
293 });
294
295 yield* session.note(serialNumber);
296 return {
297 serialNumber,
298 userName: fresh?.UserName ?? news.userName ?? output?.userName,
299 enableDate: fresh?.EnableDate ?? output?.enableDate,
300 base32StringSeed,
301 qrCodePNG,
302 tags: desiredTags,
303 };
304 }),
305 delete: Effect.fn(function* ({ output }) {
306 if (output.userName) {
307 yield* iam
308 .deactivateMFADevice({
309 UserName: output.userName,
310 SerialNumber: output.serialNumber,
311 })
312 .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.void));
313 }
314 yield* iam
315 .deleteVirtualMFADevice({
316 SerialNumber: output.serialNumber,
317 })
318 .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.void));
319 }),
320 };
321 }),
322 );