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

main
ts 230 lines 7.44 KB
Raw
1 import * as oslogin from "@distilled.cloud/gcp/oslogin_v1";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import * as Data from "effect/Data";
7 import * as Effect from "effect/Effect";
8 import { GcpEnvironment } from "../Environment.ts";
9 import type { Providers } from "../Providers.ts";
10 import {
11 DEFAULT_USER,
12 findKeyByText,
13 fingerprintOf,
14 getSshPublicKey,
15 ignoreMissing,
16 resourceName,
17 retryConflict,
18 sameText,
19 toUserId,
20 toUserParent,
21 } from "./internal.ts";
22
23 export type UsersSshPublicKeyProps = {
24 /**
25 * Google account that owns the key. Email, `"me"`, or
26 * `users/{user}`. `"me"` only works for user credentials; with a
27 * service account, pass its email (`users/me` fails with
28 * `UserCredentialMismatch`). Immutable — changing it replaces the key.
29 * @default "me"
30 */
31 user?: string;
32 /**
33 * Public key text in SSH format (RFC4253). The fingerprint covers the
34 * whole text (comment included), so any change replaces the key.
35 */
36 key: string;
37 /**
38 * Expiration time in microseconds since epoch. Omit for no expiry.
39 */
40 expirationTimeUsec?: string;
41 };
42
43 export type UsersSshPublicKey = Resource<
44 "GCP.OSLogin.UsersSshPublicKey",
45 UsersSshPublicKeyProps,
46 {
47 /** Canonical name `users/{user}/sshPublicKeys/{fingerprint}`. */
48 name: string;
49 /** User id used when the key was reconciled (`me` or email). */
50 user: string;
51 /** SHA-256 fingerprint of the SSH public key. */
52 fingerprint: string;
53 /** SSH public key text. */
54 key: string;
55 /** Expiration time in microseconds since epoch, if set. */
56 expirationTimeUsec: string | undefined;
57 /** Project id used when the key was reconciled. */
58 project: string;
59 },
60 never,
61 Providers
62 >;
63
64 /**
65 * An OS Login SSH public key on a Google account.
66 *
67 * SSH public keys have no labels field, so Alchemy tracks a key by the
68 * name in state; without state an identical key on the account is
69 * reported as unowned. `user` and the key text are identity — changing
70 * either replaces the key. Expiration updates in place. `"me"` works for
71 * user credentials; service accounts must pass their email as `user`.
72 *
73 * ### Creating a Key
74 * **Example:** Current user
75 * ```typescript
76 * const sshKey = yield* GCP.OSLogin.UsersSshPublicKey("Laptop", {
77 * key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAI... laptop",
78 * });
79 * ```
80 *
81 * **Example:** With expiration
82 * ```typescript
83 * const sshKey = yield* GCP.OSLogin.UsersSshPublicKey("Laptop", {
84 * user: "me",
85 * key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAI... laptop",
86 * expirationTimeUsec: "4102444800000000",
87 * });
88 * ```
89 *
90 * **Example:** Key for a service account
91 * ```typescript
92 * const sshKey = yield* GCP.OSLogin.UsersSshPublicKey("Deploy", {
93 * user: "deployer@my-project.iam.gserviceaccount.com",
94 * key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAI... deploy",
95 * });
96 * ```
97 *
98 * ### Updating a Key
99 * Change props on the same logical id; the engine keeps the physical id.
100 *
101 * **Example:** Extend expiration
102 * ```typescript
103 * const sshKey = yield* GCP.OSLogin.UsersSshPublicKey("Laptop", {
104 * key: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAI... laptop",
105 * expirationTimeUsec: "4133980800000000",
106 * });
107 * ```
108 *
109 * @resource
110 * @category OSLogin
111 */
112 export const UsersSshPublicKey = Resource<UsersSshPublicKey>("GCP.OSLogin.UsersSshPublicKey");
113
114 export class UsersSshPublicKeyNotResolved extends Data.TaggedError(
115 "GCP.OSLogin.UsersSshPublicKeyNotResolved",
116 )<{
117 resourceName: string;
118 }> {}
119
120 const toAttrs = (key: oslogin.SshPublicKey, user: string, project: string) => {
121 const name = key.name ?? "";
122 return {
123 name,
124 user,
125 fingerprint: key.fingerprint ?? fingerprintOf(name),
126 key: key.key ?? "",
127 expirationTimeUsec: key.expirationTimeUsec,
128 project,
129 };
130 };
131
132 export const UsersSshPublicKeyProvider = () =>
133 Provider.succeed(UsersSshPublicKey, {
134 stables: ["name", "user", "fingerprint", "project"],
135
136 diff: Effect.fn(function* ({ news, olds, output }) {
137 if (!isResolved(news)) return undefined;
138 const previousUser = olds?.user ?? output?.user ?? DEFAULT_USER;
139 const nextUser = toUserId(news.user, news.user);
140 const oldUser = toUserId(previousUser, previousUser);
141 if (
142 news.user !== undefined &&
143 nextUser !== oldUser &&
144 nextUser !== DEFAULT_USER &&
145 oldUser !== DEFAULT_USER
146 ) {
147 return { action: "replace" as const, deleteFirst: false };
148 }
149 const previousKey = olds?.key ?? output?.key;
150 if (
151 previousKey !== undefined &&
152 news.key !== undefined &&
153 !sameText(news.key.trim(), previousKey.trim())
154 ) {
155 return { action: "replace" as const, deleteFirst: false };
156 }
157 return undefined;
158 }),
159
160 read: Effect.fn(function* ({ olds, output }) {
161 const env = yield* GcpEnvironment.current;
162 const user = toUserId(olds?.user, output?.user);
163 const byName = yield* getSshPublicKey(
164 output?.name ?? (output?.fingerprint ? resourceName(user, output.fingerprint) : ""),
165 );
166 if (byName !== undefined) return toAttrs(byName, user, env.project);
167 if (olds === undefined) return undefined;
168 // No labels: an identical key without state may belong to anyone.
169 const found = yield* findKeyByText(user, olds.key, env.project);
170 return found === undefined ? undefined : Unowned(toAttrs(found, user, env.project));
171 }),
172
173 reconcile: Effect.fn(function* ({ news, output }) {
174 const env = yield* GcpEnvironment.current;
175 const user = toUserId(news.user, output?.user);
176 const desiredKey = news.key.trim();
177
178 let current = yield* getSshPublicKey(output?.name ?? "");
179 if (current === undefined) {
180 current = yield* findKeyByText(user, desiredKey, env.project);
181 }
182
183 if (current === undefined) {
184 const created = yield* retryConflict(
185 oslogin.createUsersSshPublicKeys({
186 parent: toUserParent(user),
187 body: {
188 key: desiredKey,
189 expirationTimeUsec: news.expirationTimeUsec,
190 },
191 }),
192 ).pipe(Effect.catchTag("Conflict", () => findKeyByText(user, desiredKey, env.project)));
193 current = created ?? undefined;
194 }
195
196 if (current === undefined) {
197 return yield* new UsersSshPublicKeyNotResolved({
198 resourceName: output?.name ?? resourceName(user, output?.fingerprint ?? ""),
199 });
200 }
201
202 const name =
203 current.name ?? resourceName(user, current.fingerprint ?? output?.fingerprint ?? "");
204 // The fingerprint covers the full key text, so `key` is never patched.
205 const expirationChanged =
206 (current.expirationTimeUsec ?? "") !== (news.expirationTimeUsec ?? "");
207
208 if (expirationChanged) {
209 current = yield* retryConflict(
210 oslogin.patchUsersSshPublicKeys({
211 name,
212 updateMask: "expirationTimeUsec",
213 body: {
214 expirationTimeUsec: news.expirationTimeUsec,
215 },
216 }),
217 );
218 }
219
220 return toAttrs(current, user, env.project);
221 }),
222
223 delete: Effect.fn(function* ({ output }) {
224 const name =
225 output.name ||
226 (output.fingerprint ? resourceName(output.user || DEFAULT_USER, output.fingerprint) : "");
227 if (name.length === 0) return;
228 yield* oslogin.deleteUsersSshPublicKeys({ name }).pipe(retryConflict, ignoreMissing);
229 }),
230 });