The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as cloudidentity from "@distilled.cloud/gcp/cloudidentity_v1"; |
| 2 | import { createPhysicalName } from "alchemy/PhysicalName"; |
| 3 | import * as Effect from "effect/Effect"; |
| 4 | import * as Stream from "effect/Stream"; |
| 5 | import { alchemyLabelKeys, createInternalLabels, hasAlchemyLabels } from "../Labels.ts"; |
| 6 | |
| 7 | export const DEFAULT_CUSTOMER = "customers/my_customer"; |
| 8 | export const DISCUSSION_FORUM_LABEL = "cloudidentity.googleapis.com/groups.discussion_forum"; |
| 9 | export const MAX_DISPLAY_NAME_LENGTH = 128; |
| 10 | export const MAX_DESCRIPTION_LENGTH = 4096; |
| 11 | export const MAX_ASSET_TAG_LENGTH = 100; |
| 12 | export const MAX_GROUP_KEY_LOCAL_LENGTH = 32; |
| 13 | |
| 14 | export const lastSegment = (value: string) => { |
| 15 | const trimmed = value.replace(/\/+$/, ""); |
| 16 | const parts = trimmed.split("/"); |
| 17 | return parts[parts.length - 1] || trimmed; |
| 18 | }; |
| 19 | |
| 20 | export const sameText = (left: string | undefined, right: string | undefined) => |
| 21 | (left ?? "") === (right ?? ""); |
| 22 | |
| 23 | export const sameJson = (left: unknown, right: unknown) => |
| 24 | JSON.stringify(left ?? null) === JSON.stringify(right ?? null); |
| 25 | |
| 26 | export const updateMaskOf = (...fields: Array<string | undefined>) => |
| 27 | fields.filter((field): field is string => field !== undefined).join(","); |
| 28 | |
| 29 | export const normalizeCustomer = (value: string | undefined) => { |
| 30 | const trimmed = value?.trim(); |
| 31 | if (trimmed === undefined || trimmed.length === 0) { |
| 32 | return DEFAULT_CUSTOMER; |
| 33 | } |
| 34 | if (trimmed.startsWith("customers/") || trimmed.startsWith("identitysources/")) { |
| 35 | return trimmed; |
| 36 | } |
| 37 | return `customers/${trimmed}`; |
| 38 | }; |
| 39 | |
| 40 | export const expandName = (value: string, collection: string) => { |
| 41 | const trimmed = value.replace(/\/+$/, ""); |
| 42 | if (trimmed.includes("/")) return trimmed; |
| 43 | return `${collection}/${trimmed}`; |
| 44 | }; |
| 45 | |
| 46 | export const expandGroup = (value: string) => expandName(value, "groups"); |
| 47 | |
| 48 | export const replaceOnIdentity = (input: { |
| 49 | previousId?: string; |
| 50 | nextId?: string; |
| 51 | previousParent?: string; |
| 52 | nextParent?: string; |
| 53 | extra?: boolean; |
| 54 | }) => { |
| 55 | if (input.extra === true) { |
| 56 | return { action: "replace" as const, deleteFirst: false }; |
| 57 | } |
| 58 | if ( |
| 59 | input.previousId !== undefined && |
| 60 | input.nextId !== undefined && |
| 61 | input.previousId !== input.nextId |
| 62 | ) { |
| 63 | return { action: "replace" as const, deleteFirst: false }; |
| 64 | } |
| 65 | if ( |
| 66 | input.previousParent !== undefined && |
| 67 | input.nextParent !== undefined && |
| 68 | input.previousParent !== input.nextParent |
| 69 | ) { |
| 70 | return { action: "replace" as const, deleteFirst: false }; |
| 71 | } |
| 72 | return undefined; |
| 73 | }; |
| 74 | |
| 75 | const markerOf = (_labels: Record<string, string>, stack: string, stage: string, id: string) => |
| 76 | `[alchemy ${alchemyLabelKeys.stack}=${stack} ${alchemyLabelKeys.stage}=${stage} ${alchemyLabelKeys.id}=${id}]`; |
| 77 | |
| 78 | const fitMarker = (labels: Record<string, string>, maxLength: number) => { |
| 79 | let stack = labels[alchemyLabelKeys.stack] ?? "x"; |
| 80 | let stage = labels[alchemyLabelKeys.stage] ?? "x"; |
| 81 | let id = labels[alchemyLabelKeys.id] ?? "x"; |
| 82 | let marker = markerOf(labels, stack, stage, id); |
| 83 | while (marker.length > maxLength && (stack.length > 1 || stage.length > 1 || id.length > 1)) { |
| 84 | if (stack.length >= stage.length && stack.length >= id.length) { |
| 85 | stack = stack.slice(0, -1); |
| 86 | } else if (stage.length >= id.length) { |
| 87 | stage = stage.slice(0, -1); |
| 88 | } else { |
| 89 | id = id.slice(0, -1); |
| 90 | } |
| 91 | marker = markerOf(labels, stack, stage, id); |
| 92 | } |
| 93 | return marker.slice(0, maxLength); |
| 94 | }; |
| 95 | |
| 96 | export const encodeOwnership = ( |
| 97 | labels: Record<string, string>, |
| 98 | text: string | undefined, |
| 99 | ): string => { |
| 100 | const marker = fitMarker(labels, Math.min(8000, MAX_DESCRIPTION_LENGTH)); |
| 101 | const trimmed = text?.trim(); |
| 102 | const combined = trimmed && trimmed.length > 0 ? `${marker}\n${trimmed}` : marker; |
| 103 | return combined.slice(0, MAX_DESCRIPTION_LENGTH); |
| 104 | }; |
| 105 | |
| 106 | export const encodeOwnershipLine = ( |
| 107 | labels: Record<string, string>, |
| 108 | text: string | undefined, |
| 109 | maxLength = MAX_DISPLAY_NAME_LENGTH, |
| 110 | ): string => { |
| 111 | const trimmed = text?.replace(/[\r\n]+/g, " ").trim(); |
| 112 | if (!trimmed) return fitMarker(labels, maxLength); |
| 113 | const minMarker = 24; |
| 114 | const reserved = Math.min(trimmed.length + 1, Math.max(0, maxLength - minMarker)); |
| 115 | const marker = fitMarker(labels, maxLength - reserved); |
| 116 | return `${marker} ${trimmed}`.slice(0, maxLength); |
| 117 | }; |
| 118 | |
| 119 | export const parseOwnership = ( |
| 120 | text: string | undefined, |
| 121 | ): { |
| 122 | labels: Record<string, string>; |
| 123 | text: string | undefined; |
| 124 | } => { |
| 125 | if (!text?.startsWith("[alchemy ")) { |
| 126 | return { labels: {}, text }; |
| 127 | } |
| 128 | const end = text.indexOf("]"); |
| 129 | if (end < 0) return { labels: {}, text }; |
| 130 | const labels: Record<string, string> = {}; |
| 131 | for (const part of text.slice("[alchemy ".length, end).split(/\s+/)) { |
| 132 | const eq = part.indexOf("="); |
| 133 | if (eq > 0) { |
| 134 | labels[part.slice(0, eq)] = part.slice(eq + 1); |
| 135 | } |
| 136 | } |
| 137 | const rest = text.slice(end + 1).replace(/^[\s\n]+/, ""); |
| 138 | return { labels, text: rest.length > 0 ? rest : undefined }; |
| 139 | }; |
| 140 | |
| 141 | export const hasOwnershipMarker = (text: string | undefined) => { |
| 142 | if (Object.keys(parseOwnership(text).labels).some((key) => key.startsWith("alchemy-"))) { |
| 143 | return true; |
| 144 | } |
| 145 | return (text ?? "").toLowerCase().includes("alchemy-"); |
| 146 | }; |
| 147 | |
| 148 | const prefixMatch = (expected: string, observed: string) => |
| 149 | expected === observed || expected.startsWith(observed) || observed.startsWith(expected); |
| 150 | |
| 151 | export const ownedByAlchemy = (id: string, text: string | undefined) => |
| 152 | Effect.gen(function* () { |
| 153 | const expected = yield* createInternalLabels(id); |
| 154 | const { labels } = parseOwnership(text); |
| 155 | if (!hasOwnershipMarker(text)) return false; |
| 156 | const exact = yield* hasAlchemyLabels(id, labels); |
| 157 | if (exact) return true; |
| 158 | return ( |
| 159 | prefixMatch(expected[alchemyLabelKeys.stack] ?? "", labels[alchemyLabelKeys.stack] ?? "") && |
| 160 | prefixMatch(expected[alchemyLabelKeys.stage] ?? "", labels[alchemyLabelKeys.stage] ?? "") && |
| 161 | prefixMatch(expected[alchemyLabelKeys.id] ?? "", labels[alchemyLabelKeys.id] ?? "") |
| 162 | ); |
| 163 | }); |
| 164 | |
| 165 | export const ownershipLabels = (id: string) => createInternalLabels(id); |
| 166 | |
| 167 | export const toPhysicalId = ( |
| 168 | id: string, |
| 169 | requested: string | undefined, |
| 170 | existing: string | undefined, |
| 171 | maxLength = MAX_GROUP_KEY_LOCAL_LENGTH, |
| 172 | ) => |
| 173 | Effect.gen(function* () { |
| 174 | if (requested !== undefined && requested.length > 0) return requested; |
| 175 | if (existing !== undefined && existing.length > 0) return existing; |
| 176 | return yield* createPhysicalName({ |
| 177 | id, |
| 178 | maxLength, |
| 179 | lowercase: true, |
| 180 | }); |
| 181 | }); |
| 182 | |
| 183 | export const toGroupKeyId = ( |
| 184 | id: string, |
| 185 | requested: string | undefined, |
| 186 | existing: string | undefined, |
| 187 | domain: string | undefined, |
| 188 | ) => |
| 189 | Effect.gen(function* () { |
| 190 | if (requested !== undefined && requested.length > 0) return requested; |
| 191 | if (existing !== undefined && existing.length > 0) return existing; |
| 192 | const local = yield* createPhysicalName({ |
| 193 | id, |
| 194 | maxLength: MAX_GROUP_KEY_LOCAL_LENGTH, |
| 195 | lowercase: true, |
| 196 | }); |
| 197 | const host = domain?.trim(); |
| 198 | return host && host.length > 0 ? `${local}@${host}` : local; |
| 199 | }); |
| 200 | |
| 201 | export const typeLabels = (labels: Record<string, string> | undefined): Record<string, string> => { |
| 202 | const next = { ...labels }; |
| 203 | if (Object.keys(next).length === 0) { |
| 204 | next[DISCUSSION_FORUM_LABEL] = ""; |
| 205 | } |
| 206 | return next; |
| 207 | }; |
| 208 | |
| 209 | export const compactStringMap = ( |
| 210 | labels: Record<string, string | undefined> | null | undefined, |
| 211 | ): Record<string, string> => |
| 212 | Object.fromEntries( |
| 213 | Object.entries(labels ?? {}).filter( |
| 214 | (entry): entry is [string, string] => typeof entry[1] === "string" && entry[1] !== undefined, |
| 215 | ), |
| 216 | ); |
| 217 | |
| 218 | const emptyList = <A>() => Effect.succeed([] as A[]); |
| 219 | |
| 220 | export const getGroup = (name: string) => |
| 221 | name.length === 0 |
| 222 | ? Effect.undefined |
| 223 | : cloudidentity |
| 224 | .getGroups({ name: expandGroup(name) }) |
| 225 | .pipe(Effect.catchTag("NotFound", () => Effect.undefined)); |
| 226 | |
| 227 | export const lookupGroupName = (groupKeyId: string, namespace: string | undefined) => |
| 228 | groupKeyId.length === 0 |
| 229 | ? Effect.undefined |
| 230 | : cloudidentity |
| 231 | .lookupGroups({ |
| 232 | "groupKey.id": groupKeyId, |
| 233 | "groupKey.namespace": namespace, |
| 234 | }) |
| 235 | .pipe( |
| 236 | Effect.map((result) => result.name), |
| 237 | Effect.catchTag("NotFound", () => Effect.undefined), |
| 238 | ); |
| 239 | |
| 240 | export const getGroupByKey = (groupKeyId: string, namespace: string | undefined) => |
| 241 | Effect.gen(function* () { |
| 242 | const name = yield* lookupGroupName(groupKeyId, namespace); |
| 243 | if (name === undefined) return undefined; |
| 244 | return yield* getGroup(name); |
| 245 | }); |
| 246 | |
| 247 | export const listGroups = (parent?: string) => |
| 248 | cloudidentity.listGroups |
| 249 | .pages({ |
| 250 | parent: normalizeCustomer(parent), |
| 251 | view: "FULL", |
| 252 | pageSize: 200, |
| 253 | }) |
| 254 | .pipe( |
| 255 | Stream.flatMap((page) => Stream.fromIterable(page.groups ?? [])), |
| 256 | Stream.runCollect, |
| 257 | Effect.map((chunk) => Array.from(chunk)), |
| 258 | Effect.catchTag("NotFound", () => emptyList<cloudidentity.Group>()), |
| 259 | ); |
| 260 | |
| 261 | export const isOwnedGroup = (group: cloudidentity.Group) => |
| 262 | hasOwnershipMarker(group.description) || hasOwnershipMarker(group.displayName); |
| 263 | |
| 264 | export const listOwnedGroups = (parent?: string) => |
| 265 | listGroups(parent).pipe(Effect.map((groups) => groups.filter(isOwnedGroup))); |
| 266 | |
| 267 | export const findOwnedGroup = (id: string, parent?: string) => |
| 268 | Effect.gen(function* () { |
| 269 | const groups = yield* listGroups(parent); |
| 270 | for (const group of groups) { |
| 271 | if ( |
| 272 | (yield* ownedByAlchemy(id, group.description)) || |
| 273 | (yield* ownedByAlchemy(id, group.displayName)) |
| 274 | ) { |
| 275 | return group; |
| 276 | } |
| 277 | } |
| 278 | return undefined; |
| 279 | }); |
| 280 | |
| 281 | export const getMembership = (name: string) => |
| 282 | name.length === 0 |
| 283 | ? Effect.undefined |
| 284 | : cloudidentity |
| 285 | .getGroupsMemberships({ name }) |
| 286 | .pipe(Effect.catchTag("NotFound", () => Effect.undefined)); |
| 287 | |
| 288 | export const lookupMembershipName = ( |
| 289 | parent: string, |
| 290 | memberKeyId: string, |
| 291 | namespace: string | undefined, |
| 292 | ) => |
| 293 | parent.length === 0 || memberKeyId.length === 0 |
| 294 | ? Effect.undefined |
| 295 | : cloudidentity |
| 296 | .lookupGroupsMemberships({ |
| 297 | parent: expandGroup(parent), |
| 298 | "memberKey.id": memberKeyId, |
| 299 | "memberKey.namespace": namespace, |
| 300 | }) |
| 301 | .pipe( |
| 302 | Effect.map((result) => result.name), |
| 303 | Effect.catchTag("NotFound", () => Effect.undefined), |
| 304 | ); |
| 305 | |
| 306 | export const getMembershipByKey = ( |
| 307 | parent: string, |
| 308 | memberKeyId: string, |
| 309 | namespace: string | undefined, |
| 310 | ) => |
| 311 | Effect.gen(function* () { |
| 312 | const name = yield* lookupMembershipName(parent, memberKeyId, namespace); |
| 313 | if (name === undefined) return undefined; |
| 314 | return yield* getMembership(name); |
| 315 | }); |
| 316 | |
| 317 | export const listMemberships = (parent: string) => |
| 318 | parent.length === 0 |
| 319 | ? emptyList<cloudidentity.Membership>() |
| 320 | : cloudidentity.listGroupsMemberships |
| 321 | .pages({ |
| 322 | parent: expandGroup(parent), |
| 323 | view: "FULL", |
| 324 | pageSize: 200, |
| 325 | }) |
| 326 | .pipe( |
| 327 | Stream.flatMap((page) => Stream.fromIterable(page.memberships ?? [])), |
| 328 | Stream.runCollect, |
| 329 | Effect.map((chunk) => Array.from(chunk)), |
| 330 | Effect.catchTag("NotFound", () => emptyList<cloudidentity.Membership>()), |
| 331 | ); |
| 332 | |
| 333 | export const getDevice = (name: string, customer?: string) => |
| 334 | name.length === 0 |
| 335 | ? Effect.undefined |
| 336 | : cloudidentity |
| 337 | .getDevices({ |
| 338 | name: expandName(name, "devices"), |
| 339 | customer: customer ? normalizeCustomer(customer) : undefined, |
| 340 | }) |
| 341 | .pipe(Effect.catchTag("NotFound", () => Effect.undefined)); |
| 342 | |
| 343 | export const listDevices = (customer?: string) => |
| 344 | cloudidentity.listDevices |
| 345 | .pages({ |
| 346 | customer: normalizeCustomer(customer), |
| 347 | view: "COMPANY_INVENTORY", |
| 348 | pageSize: 100, |
| 349 | }) |
| 350 | .pipe( |
| 351 | Stream.flatMap((page) => Stream.fromIterable(page.devices ?? [])), |
| 352 | Stream.runCollect, |
| 353 | Effect.map((chunk) => Array.from(chunk)), |
| 354 | Effect.catchTag("NotFound", () => |
| 355 | emptyList<cloudidentity.GoogleAppsCloudidentityDevicesV1Device>(), |
| 356 | ), |
| 357 | ); |
| 358 | |
| 359 | export const findOwnedDevice = (id: string, serialNumber: string | undefined, customer?: string) => |
| 360 | Effect.gen(function* () { |
| 361 | const devices = yield* listDevices(customer); |
| 362 | for (const device of devices) { |
| 363 | if ( |
| 364 | serialNumber !== undefined && |
| 365 | serialNumber.length > 0 && |
| 366 | sameText(device.serialNumber, serialNumber) |
| 367 | ) { |
| 368 | return device; |
| 369 | } |
| 370 | if (yield* ownedByAlchemy(id, device.assetTag)) { |
| 371 | return device; |
| 372 | } |
| 373 | } |
| 374 | return undefined; |
| 375 | }); |
| 376 | |
| 377 | export const getOidcProfile = (name: string) => |
| 378 | name.length === 0 |
| 379 | ? Effect.undefined |
| 380 | : cloudidentity |
| 381 | .getInboundOidcSsoProfiles({ |
| 382 | name: expandName(name, "inboundOidcSsoProfiles"), |
| 383 | }) |
| 384 | .pipe(Effect.catchTag("NotFound", () => Effect.undefined)); |
| 385 | |
| 386 | export const listOidcProfiles = () => |
| 387 | cloudidentity.listInboundOidcSsoProfiles.pages({ pageSize: 100 }).pipe( |
| 388 | Stream.flatMap((page) => Stream.fromIterable(page.inboundOidcSsoProfiles ?? [])), |
| 389 | Stream.runCollect, |
| 390 | Effect.map((chunk) => Array.from(chunk)), |
| 391 | Effect.catchTag("NotFound", () => emptyList<cloudidentity.InboundOidcSsoProfile>()), |
| 392 | ); |
| 393 | |
| 394 | export const findOwnedOidcProfile = (id: string) => |
| 395 | Effect.gen(function* () { |
| 396 | const profiles = yield* listOidcProfiles(); |
| 397 | for (const profile of profiles) { |
| 398 | if (yield* ownedByAlchemy(id, profile.displayName)) { |
| 399 | return profile; |
| 400 | } |
| 401 | } |
| 402 | return undefined; |
| 403 | }); |
| 404 | |
| 405 | export const getSamlProfile = (name: string) => |
| 406 | name.length === 0 |
| 407 | ? Effect.undefined |
| 408 | : cloudidentity |
| 409 | .getInboundSamlSsoProfiles({ |
| 410 | name: expandName(name, "inboundSamlSsoProfiles"), |
| 411 | }) |
| 412 | .pipe(Effect.catchTag("NotFound", () => Effect.undefined)); |
| 413 | |
| 414 | export const listSamlProfiles = () => |
| 415 | cloudidentity.listInboundSamlSsoProfiles.pages({ pageSize: 100 }).pipe( |
| 416 | Stream.flatMap((page) => Stream.fromIterable(page.inboundSamlSsoProfiles ?? [])), |
| 417 | Stream.runCollect, |
| 418 | Effect.map((chunk) => Array.from(chunk)), |
| 419 | Effect.catchTag("NotFound", () => emptyList<cloudidentity.InboundSamlSsoProfile>()), |
| 420 | ); |
| 421 | |
| 422 | export const findOwnedSamlProfile = (id: string) => |
| 423 | Effect.gen(function* () { |
| 424 | const profiles = yield* listSamlProfiles(); |
| 425 | for (const profile of profiles) { |
| 426 | if (yield* ownedByAlchemy(id, profile.displayName)) { |
| 427 | return profile; |
| 428 | } |
| 429 | } |
| 430 | return undefined; |
| 431 | }); |
| 432 | |
| 433 | export const getSsoAssignment = (name: string) => |
| 434 | name.length === 0 |
| 435 | ? Effect.undefined |
| 436 | : cloudidentity |
| 437 | .getInboundSsoAssignments({ |
| 438 | name: expandName(name, "inboundSsoAssignments"), |
| 439 | }) |
| 440 | .pipe(Effect.catchTag("NotFound", () => Effect.undefined)); |
| 441 | |
| 442 | export const listSsoAssignments = () => |
| 443 | cloudidentity.listInboundSsoAssignments.pages({ pageSize: 100 }).pipe( |
| 444 | Stream.flatMap((page) => Stream.fromIterable(page.inboundSsoAssignments ?? [])), |
| 445 | Stream.runCollect, |
| 446 | Effect.map((chunk) => Array.from(chunk)), |
| 447 | Effect.catchTag("NotFound", () => emptyList<cloudidentity.InboundSsoAssignment>()), |
| 448 | ); |
| 449 | |
| 450 | export const findSsoAssignment = (input: { |
| 451 | name?: string; |
| 452 | targetGroup?: string; |
| 453 | targetOrgUnit?: string; |
| 454 | ssoMode?: string; |
| 455 | }) => |
| 456 | Effect.gen(function* () { |
| 457 | if (input.name !== undefined && input.name.length > 0) { |
| 458 | const existing = yield* getSsoAssignment(input.name); |
| 459 | if (existing !== undefined) return existing; |
| 460 | } |
| 461 | const assignments = yield* listSsoAssignments(); |
| 462 | return assignments.find((assignment) => { |
| 463 | if ( |
| 464 | input.targetGroup !== undefined && |
| 465 | !sameText(assignment.targetGroup, expandGroup(input.targetGroup)) |
| 466 | ) { |
| 467 | return false; |
| 468 | } |
| 469 | if ( |
| 470 | input.targetOrgUnit !== undefined && |
| 471 | !sameText(assignment.targetOrgUnit, input.targetOrgUnit) |
| 472 | ) { |
| 473 | return false; |
| 474 | } |
| 475 | if (input.ssoMode !== undefined && !sameText(assignment.ssoMode, input.ssoMode)) { |
| 476 | return false; |
| 477 | } |
| 478 | return input.targetGroup !== undefined || input.targetOrgUnit !== undefined; |
| 479 | }); |
| 480 | }); |