@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 295 lines 9.03 KB
Raw
1 import * as cloudidentity from "@distilled.cloud/gcp/cloudidentity_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 type { Providers } from "../Providers.ts";
9 import {
10 encodeOwnershipLine,
11 findOwnedDevice,
12 getDevice,
13 hasOwnershipMarker,
14 lastSegment,
15 listDevices,
16 MAX_ASSET_TAG_LENGTH,
17 normalizeCustomer,
18 ownedByAlchemy,
19 ownershipLabels,
20 parseOwnership,
21 replaceOnIdentity,
22 toPhysicalId,
23 } from "./internal.ts";
24 import { resourceNameFromOperation, waitForOperation, waitUntilPresent } from "./operations.ts";
25
26 export type DeviceProps = {
27 /**
28 * Customer that owns the device (`customers/my_customer` or
29 * `customers/{customer}`). Immutable — changing it replaces the
30 * device.
31 * @default "customers/my_customer"
32 */
33 customer?: string;
34 /**
35 * Serial number. If omitted, a unique value is generated. Immutable
36 * — changing it replaces the device. Only company-owned devices can
37 * be created.
38 */
39 serialNumber?: string;
40 /**
41 * Device type. Immutable — changing it replaces the device.
42 * @default "LINUX"
43 */
44 deviceType?: cloudidentity.GoogleAppsCloudidentityDevicesV1DeviceDeviceTypeEnum | (string & {});
45 /**
46 * Asset tag. Devices have no labels field, so Alchemy stores
47 * ownership in a `[alchemy …]` prefix and strips it from attributes.
48 */
49 assetTag?: string;
50 /**
51 * Host name.
52 */
53 hostname?: string;
54 /**
55 * WiFi MAC addresses.
56 */
57 wifiMacAddresses?: string[];
58 /**
59 * Partner-specified unique device identifier.
60 */
61 deviceId?: string;
62 };
63
64 export type Device = Resource<
65 "GCP.CloudIdentity.Device",
66 DeviceProps,
67 {
68 /** Resource name `devices/{device}`. */
69 name: string;
70 /** Device id (last path segment). */
71 deviceResourceId: string;
72 /** Customer used on create. */
73 customer: string;
74 /** Serial number. */
75 serialNumber: string | undefined;
76 /** Device type. */
77 deviceType: string | undefined;
78 /** Asset tag with the Alchemy ownership prefix stripped. */
79 assetTag: string | undefined;
80 /** Host name. */
81 hostname: string | undefined;
82 /** WiFi MAC addresses. */
83 wifiMacAddresses: string[] | undefined;
84 /** Partner device id. */
85 deviceId: string | undefined;
86 /** Owner type (`COMPANY` or `BYOD`). */
87 ownerType: string | undefined;
88 /** Management state. */
89 managementState: string | undefined;
90 /** Compromised state. */
91 compromisedState: string | undefined;
92 /** Encryption state. */
93 encryptionState: string | undefined;
94 /** RFC3339 import timestamp. */
95 createTime: string | undefined;
96 /** Last sync time. */
97 lastSyncTime: string | undefined;
98 },
99 never,
100 Providers
101 >;
102
103 /**
104 * A Cloud Identity company-owned device.
105 *
106 * Device create is limited to company-owned inventory (Enterprise /
107 * Cloud Identity Premium). There is no update API — serial number,
108 * type, and customer are identity. Alchemy stamps ownership into
109 * `assetTag` for `list` / nuke.
110 *
111 * ### Creating a Device
112 * **Example:** Generated serial
113 * ```typescript
114 * const device = yield* GCP.CloudIdentity.Device("Laptop", {
115 * deviceType: "LINUX",
116 * hostname: "eng-laptop",
117 * });
118 * ```
119 *
120 * **Example:** Explicit serial and asset tag
121 * ```typescript
122 * const device = yield* GCP.CloudIdentity.Device("Laptop", {
123 * serialNumber: "HT82V1A01076",
124 * deviceType: "LINUX",
125 * assetTag: "desk-14",
126 * });
127 * ```
128 *
129 * @resource
130 * @category CloudIdentity
131 */
132 export const Device = Resource<Device>("GCP.CloudIdentity.Device");
133
134 export class DeviceNotResolved extends Data.TaggedError("GCP.CloudIdentity.DeviceNotResolved")<{
135 resourceName: string;
136 }> {}
137
138 const DEFAULT_DEVICE_TYPE = "LINUX";
139
140 const toAttrs = (
141 device: cloudidentity.GoogleAppsCloudidentityDevicesV1Device,
142 customer: string,
143 ) => {
144 const name = device.name ?? "";
145 return {
146 name,
147 deviceResourceId: lastSegment(name),
148 customer,
149 serialNumber: device.serialNumber,
150 deviceType: device.deviceType,
151 assetTag: parseOwnership(device.assetTag).text,
152 hostname: device.hostname,
153 wifiMacAddresses: device.wifiMacAddresses,
154 deviceId: device.deviceId,
155 ownerType: device.ownerType,
156 managementState: device.managementState,
157 compromisedState: device.compromisedState,
158 encryptionState: device.encryptionState,
159 createTime: device.createTime,
160 lastSyncTime: device.lastSyncTime,
161 };
162 };
163
164 const observeDevice = (input: {
165 id: string;
166 name?: string;
167 serialNumber?: string;
168 customer: string;
169 }) =>
170 Effect.gen(function* () {
171 const byName = yield* getDevice(input.name ?? "", input.customer);
172 if (byName !== undefined) return byName;
173 return yield* findOwnedDevice(input.id, input.serialNumber, input.customer);
174 });
175
176 export const DeviceProvider = () =>
177 Provider.succeed(Device, {
178 stables: ["name", "deviceResourceId", "customer", "serialNumber", "createTime"],
179
180 diff: Effect.fn(function* ({ news, olds, output }) {
181 if (!isResolved(news)) return undefined;
182 const previousCustomer = olds?.customer ?? output?.customer;
183 const nextCustomer =
184 news.customer !== undefined ? normalizeCustomer(news.customer) : previousCustomer;
185 const previousType = olds?.deviceType ?? output?.deviceType;
186 const nextType = news.deviceType ?? DEFAULT_DEVICE_TYPE;
187 return replaceOnIdentity({
188 previousId: olds?.serialNumber ?? output?.serialNumber,
189 nextId: news.serialNumber,
190 previousParent: previousCustomer,
191 nextParent: nextCustomer,
192 extra: previousType !== undefined && previousType !== nextType,
193 });
194 }),
195
196 read: Effect.fn(function* ({ id, olds, output }) {
197 const customer = normalizeCustomer(olds?.customer ?? output?.customer);
198 const existing = yield* observeDevice({
199 id,
200 name: output?.name,
201 serialNumber: olds?.serialNumber ?? output?.serialNumber,
202 customer,
203 });
204 if (existing === undefined) return undefined;
205 const attrs = toAttrs(existing, customer);
206 return (yield* ownedByAlchemy(id, existing.assetTag)) ? attrs : Unowned(attrs);
207 }),
208
209 list: () =>
210 Effect.gen(function* () {
211 const devices = yield* listDevices();
212 return devices
213 .filter((device) => hasOwnershipMarker(device.assetTag))
214 .map((device) => toAttrs(device, DEFAULT_CUSTOMER_FALLBACK));
215 }),
216
217 reconcile: Effect.fn(function* ({ id, news, output }) {
218 const customer = normalizeCustomer(news.customer ?? output?.customer);
219 const ownership = yield* ownershipLabels(id);
220 const serialNumber = yield* toPhysicalId(id, news.serialNumber, output?.serialNumber, 20);
221 const assetTag = encodeOwnershipLine(ownership, news.assetTag, MAX_ASSET_TAG_LENGTH);
222 const deviceType = news.deviceType ?? DEFAULT_DEVICE_TYPE;
223 const desired: cloudidentity.GoogleAppsCloudidentityDevicesV1Device = {
224 serialNumber,
225 deviceType,
226 assetTag,
227 hostname: news.hostname,
228 wifiMacAddresses: news.wifiMacAddresses,
229 deviceId: news.deviceId,
230 };
231
232 let current = yield* observeDevice({
233 id,
234 name: output?.name,
235 serialNumber,
236 customer,
237 });
238
239 if (current === undefined) {
240 const created = yield* cloudidentity
241 .createDevices({
242 customer,
243 body: desired,
244 })
245 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
246 if (created !== undefined) {
247 yield* waitForOperation(created).pipe(
248 Effect.catchTag("GCP.CloudIdentity.OperationPending", () => Effect.void),
249 );
250 const createdName = resourceNameFromOperation(created);
251 if (createdName !== undefined) {
252 current = yield* getDevice(createdName, customer);
253 }
254 }
255 if (current === undefined) {
256 current = yield* waitUntilPresent(
257 observeDevice({
258 id,
259 name: output?.name,
260 serialNumber,
261 customer,
262 }),
263 serialNumber,
264 ).pipe(
265 Effect.catchTag("GCP.CloudIdentity.OperationPending", () =>
266 observeDevice({ id, serialNumber, customer }),
267 ),
268 );
269 }
270 }
271
272 if (current === undefined) {
273 return yield* new DeviceNotResolved({
274 resourceName: output?.name ?? serialNumber,
275 });
276 }
277
278 return toAttrs(current, customer);
279 }),
280
281 delete: Effect.fn(function* ({ output }) {
282 if (output.name.length === 0) return;
283 const deleted = yield* cloudidentity
284 .deleteDevices({
285 name: output.name,
286 customer: normalizeCustomer(output.customer),
287 })
288 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
289 if (deleted !== undefined) {
290 yield* waitForOperation(deleted, { notFoundOk: true });
291 }
292 }),
293 });
294
295 const DEFAULT_CUSTOMER_FALLBACK = "customers/my_customer";