@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 223 lines 7.57 KB
Raw
1 import * as iam from "@distilled.cloud/aws/iam";
2 import { isResolved } from "alchemy/Diff";
3 import * as Provider from "alchemy/Provider";
4 import { Resource } from "alchemy/Resource";
5 import * as Data from "effect/Data";
6 import * as Effect from "effect/Effect";
7 import * as Stream from "effect/Stream";
8 import type { Providers } from "../Providers.ts";
9
10 export class SSHPublicKeyUnexpectedResponse extends Data.TaggedError(
11 "SSHPublicKeyUnexpectedResponse",
12 )<{
13 readonly message: string;
14 readonly cause?: unknown;
15 }> {}
16
17 export interface SSHPublicKeyProps {
18 /**
19 * User that owns the SSH public key.
20 */
21 userName: string;
22 /**
23 * SSH public key body.
24 */
25 sshPublicKeyBody: string;
26 /**
27 * Desired key status.
28 * @default "Active"
29 */
30 status?: iam.StatusType;
31 }
32
33 export interface SSHPublicKey extends Resource<
34 "AWS.IAM.SSHPublicKey",
35 SSHPublicKeyProps,
36 {
37 /** The IAM user the SSH public key belongs to. */
38 userName: string;
39 /** The unique ID of the SSH public key. */
40 sshPublicKeyId: string;
41 /** The MD5 fingerprint of the SSH public key. */
42 fingerprint: string;
43 /** The SSH public key material. */
44 sshPublicKeyBody: string;
45 /** Whether the key is `Active` or `Inactive`. */
46 status: iam.StatusType;
47 /** When the key was uploaded. */
48 uploadDate: Date | undefined;
49 },
50 never,
51 Providers
52 > {}
53
54 /**
55 * An IAM SSH public key for CodeCommit-compatible workflows.
56 *
57 * `SSHPublicKey` uploads and manages a user's public key for services such as
58 * AWS CodeCommit that authenticate through IAM-backed SSH credentials.
59 * ### Managing SSH Keys
60 * **Example:** Upload an SSH Public Key
61 * ```typescript
62 * const user = yield* User("GitUser", {
63 * userName: "codecommit-user",
64 * });
65 *
66 * const key = yield* SSHPublicKey("GitKey", {
67 * userName: user.userName,
68 * sshPublicKeyBody: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIExample codecommit-user",
69 * });
70 * ```
71 *
72 * @resource
73 */
74 export const SSHPublicKey = Resource<SSHPublicKey>("AWS.IAM.SSHPublicKey");
75
76 export const SSHPublicKeyProvider = () =>
77 Provider.succeed(SSHPublicKey, {
78 stables: ["sshPublicKeyId"],
79 diff: Effect.fn(function* ({ olds, news }) {
80 if (!isResolved(news)) return;
81 if (olds.userName !== news.userName || olds.sshPublicKeyBody !== news.sshPublicKeyBody) {
82 return { action: "replace" } as const;
83 }
84 }),
85 read: Effect.fn(function* ({ output }) {
86 if (!output) {
87 return undefined;
88 }
89 const response = yield* iam
90 .getSSHPublicKey({
91 UserName: output.userName,
92 SSHPublicKeyId: output.sshPublicKeyId,
93 Encoding: "SSH",
94 })
95 .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.undefined));
96 if (!response?.SSHPublicKey?.SSHPublicKeyId) {
97 return undefined;
98 }
99 return {
100 userName: response.SSHPublicKey.UserName,
101 sshPublicKeyId: response.SSHPublicKey.SSHPublicKeyId,
102 fingerprint: response.SSHPublicKey.Fingerprint,
103 sshPublicKeyBody: response.SSHPublicKey.SSHPublicKeyBody,
104 status: response.SSHPublicKey.Status,
105 uploadDate: response.SSHPublicKey.UploadDate,
106 };
107 }),
108 reconcile: Effect.fn(function* ({ news, output, session }) {
109 // Observe — SSH key ids are AWS-generated; we can only locate the
110 // existing key when we have its id from a prior output. The body
111 // and identity are immutable (`diff` triggers replacement on body
112 // change), so a missing key always means we need to upload.
113 const observed = output
114 ? yield* iam
115 .getSSHPublicKey({
116 UserName: output.userName,
117 SSHPublicKeyId: output.sshPublicKeyId,
118 Encoding: "SSH",
119 })
120 .pipe(
121 Effect.map((r) => r.SSHPublicKey),
122 Effect.catchTag("NoSuchEntityException", () => Effect.undefined),
123 )
124 : undefined;
125
126 // Ensure — upload when missing.
127 let key = observed;
128 if (!key?.SSHPublicKeyId) {
129 const uploaded = yield* iam.uploadSSHPublicKey({
130 UserName: news.userName,
131 SSHPublicKeyBody: news.sshPublicKeyBody,
132 });
133 if (!uploaded.SSHPublicKey?.SSHPublicKeyId) {
134 return yield* new SSHPublicKeyUnexpectedResponse({
135 message: `uploadSSHPublicKey returned no key id`,
136 });
137 }
138 key = uploaded.SSHPublicKey;
139 }
140
141 // Sync — apply the desired status when it differs from observed.
142 const desiredStatus = news.status ?? key.Status;
143 if (desiredStatus !== key.Status) {
144 yield* iam.updateSSHPublicKey({
145 UserName: news.userName,
146 SSHPublicKeyId: key.SSHPublicKeyId!,
147 Status: desiredStatus,
148 });
149 }
150
151 yield* session.note(key.SSHPublicKeyId!);
152 return {
153 userName: key.UserName,
154 sshPublicKeyId: key.SSHPublicKeyId!,
155 fingerprint: key.Fingerprint,
156 sshPublicKeyBody: key.SSHPublicKeyBody,
157 status: desiredStatus,
158 uploadDate: key.UploadDate,
159 };
160 }),
161 delete: Effect.fn(function* ({ output }) {
162 yield* iam
163 .deleteSSHPublicKey({
164 UserName: output.userName,
165 SSHPublicKeyId: output.sshPublicKeyId,
166 })
167 .pipe(Effect.catchTag("NoSuchEntityException", () => Effect.void));
168 }),
169 // IAM is a global service. `listSSHPublicKeys` requires a `UserName`, so we
170 // enumerate every IAM user first (paginated) and then list each user's keys
171 // (also paginated) with bounded concurrency. The list metadata omits the
172 // fingerprint and key body, so each key is hydrated with `getSSHPublicKey`
173 // to produce the full `Attributes` shape that `read` returns.
174 list: Effect.fn(function* () {
175 const users = yield* iam.listUsers.pages({}).pipe(
176 Stream.runCollect,
177 Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.Users)),
178 );
179 const perUser = yield* Effect.forEach(
180 users,
181 (user) =>
182 iam.listSSHPublicKeys.pages({ UserName: user.UserName }).pipe(
183 Stream.runCollect,
184 Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.SSHPublicKeys ?? [])),
185 Effect.flatMap((metas) =>
186 Effect.forEach(
187 metas,
188 (meta) =>
189 iam
190 .getSSHPublicKey({
191 UserName: meta.UserName,
192 SSHPublicKeyId: meta.SSHPublicKeyId,
193 Encoding: "SSH",
194 })
195 .pipe(
196 Effect.map((r) => r.SSHPublicKey),
197 // The key may be deleted between enumeration and
198 // hydration.
199 Effect.catchTag("NoSuchEntityException", () => Effect.undefined),
200 ),
201 { concurrency: 10 },
202 ),
203 ),
204 Effect.map((keys) =>
205 keys
206 .filter((key): key is iam.SSHPublicKey => key?.SSHPublicKeyId != null)
207 .map((key) => ({
208 userName: key.UserName,
209 sshPublicKeyId: key.SSHPublicKeyId,
210 fingerprint: key.Fingerprint,
211 sshPublicKeyBody: key.SSHPublicKeyBody,
212 status: key.Status,
213 uploadDate: key.UploadDate,
214 })),
215 ),
216 // The user may be deleted between enumeration and per-user list.
217 Effect.catchTag("NoSuchEntityException", () => Effect.succeed([])),
218 ),
219 { concurrency: 10 },
220 );
221 return perUser.flat();
222 }),
223 });