The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as agentidentity from "@distilled.cloud/gcp/agentidentity_v1"; |
| 2 | import { createPhysicalName } from "alchemy/PhysicalName"; |
| 3 | import { tagRecord } from "alchemy/Tags"; |
| 4 | import * as Data from "effect/Data"; |
| 5 | import * as Effect from "effect/Effect"; |
| 6 | import * as Stream from "effect/Stream"; |
| 7 | import { ALCHEMY_LABEL_PREFIX, stripInternalLabels } from "../Labels.ts"; |
| 8 | |
| 9 | export const MAX_NAME_LENGTH = 63; |
| 10 | export const MAX_DESCRIPTION_LENGTH = 256; |
| 11 | export const COLLECTION = "authProviders"; |
| 12 | |
| 13 | export class AuthProviderNotResolved extends Data.TaggedError( |
| 14 | "GCP.AgentIdentity.AuthProviderNotResolved", |
| 15 | )<{ |
| 16 | resourceName: string; |
| 17 | }> {} |
| 18 | |
| 19 | export const lastSegment = (value: string) => { |
| 20 | const trimmed = value.replace(/\/+$/, ""); |
| 21 | const parts = trimmed.split("/"); |
| 22 | return parts[parts.length - 1] || trimmed; |
| 23 | }; |
| 24 | |
| 25 | export const rfc1035 = (name: string, fallback = "auth"): string => { |
| 26 | let next = name |
| 27 | .toLowerCase() |
| 28 | .replace(/[^a-z0-9-]/g, "-") |
| 29 | .replace(/-+/g, "-") |
| 30 | .replace(/^-+|-+$/g, ""); |
| 31 | if (!/^[a-z]/.test(next)) next = `${fallback[0] ?? "a"}${next}`; |
| 32 | next = next.slice(0, MAX_NAME_LENGTH).replace(/-+$/g, ""); |
| 33 | if (next.length === 0) return fallback; |
| 34 | if (!/[a-z0-9]$/.test(next)) next = `${next.slice(0, MAX_NAME_LENGTH - 1)}0`; |
| 35 | return next.slice(0, MAX_NAME_LENGTH); |
| 36 | }; |
| 37 | |
| 38 | export const normalizeLocation = (location: string | undefined, fallback: string) => |
| 39 | lastSegment(location ?? fallback).toLowerCase(); |
| 40 | |
| 41 | export const parentOf = (project: string, location: string) => |
| 42 | `projects/${project}/locations/${lastSegment(location).toLowerCase()}`; |
| 43 | |
| 44 | export const resourceName = (project: string, location: string, authProviderId: string) => |
| 45 | `${parentOf(project, location)}/${COLLECTION}/${authProviderId}`; |
| 46 | |
| 47 | export const toPhysicalId = ( |
| 48 | id: string, |
| 49 | explicit: string | undefined, |
| 50 | existing: string | undefined, |
| 51 | ) => |
| 52 | Effect.gen(function* () { |
| 53 | if (explicit !== undefined) return explicit; |
| 54 | if (existing !== undefined) return existing; |
| 55 | return rfc1035( |
| 56 | yield* createPhysicalName({ |
| 57 | id, |
| 58 | maxLength: MAX_NAME_LENGTH, |
| 59 | lowercase: true, |
| 60 | }), |
| 61 | "auth", |
| 62 | ); |
| 63 | }); |
| 64 | |
| 65 | export const parseName = (name: string, fallbackLocation: string) => { |
| 66 | const parts = name.split("/").filter((part) => part.length > 0); |
| 67 | const collectionAt = parts.lastIndexOf(COLLECTION); |
| 68 | const locationsAt = parts.lastIndexOf("locations"); |
| 69 | const projectsAt = parts.lastIndexOf("projects"); |
| 70 | return { |
| 71 | project: projectsAt >= 0 && parts[projectsAt + 1] ? parts[projectsAt + 1]! : "", |
| 72 | location: |
| 73 | locationsAt >= 0 && parts[locationsAt + 1] ? parts[locationsAt + 1]! : fallbackLocation, |
| 74 | authProviderId: |
| 75 | collectionAt >= 0 && parts[collectionAt + 1] ? parts[collectionAt + 1]! : lastSegment(name), |
| 76 | }; |
| 77 | }; |
| 78 | |
| 79 | export const userLabels = ( |
| 80 | labels: Record<string, string | undefined> | null | undefined, |
| 81 | ): Record<string, string> => stripInternalLabels(tagRecord(labels)); |
| 82 | |
| 83 | export const hasAlchemyLabelMap = (labels: Record<string, string | undefined> | null | undefined) => |
| 84 | Object.keys(labels ?? {}).some((key) => key.startsWith(ALCHEMY_LABEL_PREFIX)); |
| 85 | |
| 86 | export const sameText = (left: string | undefined, right: string | undefined) => |
| 87 | (left ?? "") === (right ?? ""); |
| 88 | |
| 89 | const canonical = (value: unknown): unknown => { |
| 90 | if (value === undefined || value === null) return undefined; |
| 91 | if (typeof value === "boolean" || typeof value === "number") return value; |
| 92 | if (typeof value === "string") { |
| 93 | return value.length === 0 ? undefined : value; |
| 94 | } |
| 95 | if (Array.isArray(value)) { |
| 96 | const items = value.map(canonical).filter((item) => item !== undefined); |
| 97 | return items.length === 0 ? undefined : items; |
| 98 | } |
| 99 | if (typeof value === "object") { |
| 100 | const entries = Object.entries(value as Record<string, unknown>) |
| 101 | .map(([key, item]) => [key, canonical(item)] as const) |
| 102 | .filter(([, item]) => item !== undefined) |
| 103 | .sort(([left], [right]) => left.localeCompare(right)); |
| 104 | if (entries.length === 0) return undefined; |
| 105 | return Object.fromEntries(entries); |
| 106 | } |
| 107 | return undefined; |
| 108 | }; |
| 109 | |
| 110 | export const fingerprint = (value: unknown): string => JSON.stringify(canonical(value) ?? null); |
| 111 | |
| 112 | export const sameStringList = ( |
| 113 | left: readonly string[] | undefined, |
| 114 | right: readonly string[] | undefined, |
| 115 | ) => |
| 116 | fingerprint([...(left ?? [])].slice().sort()) === fingerprint([...(right ?? [])].slice().sort()); |
| 117 | |
| 118 | export const fieldMask = (fields: Array<string | false | undefined>) => |
| 119 | fields.filter((field): field is string => typeof field === "string").join(","); |
| 120 | |
| 121 | export const clipDescription = (description: string | undefined) => { |
| 122 | if (description === undefined) return undefined; |
| 123 | return description.slice(0, MAX_DESCRIPTION_LENGTH); |
| 124 | }; |
| 125 | |
| 126 | export type ThreeLeggedOAuthParams = { |
| 127 | clientId?: string; |
| 128 | clientSecret?: string; |
| 129 | authorizationUrl?: string; |
| 130 | tokenUrl?: string; |
| 131 | defaultContinueUri?: string; |
| 132 | enablePkce?: boolean; |
| 133 | }; |
| 134 | |
| 135 | export type TwoLeggedOAuthParams = { |
| 136 | clientId?: string; |
| 137 | clientSecret?: string; |
| 138 | tokenUrl?: string; |
| 139 | }; |
| 140 | |
| 141 | export type ApiKeyParams = { |
| 142 | apiKey?: string; |
| 143 | }; |
| 144 | |
| 145 | export type AuthProviderTypeParams = { |
| 146 | threeLeggedOauth?: ThreeLeggedOAuthParams; |
| 147 | twoLeggedOauth?: TwoLeggedOAuthParams; |
| 148 | apiKey?: ApiKeyParams; |
| 149 | geAuthProvider?: Record<string, never> | {}; |
| 150 | }; |
| 151 | |
| 152 | const publicThreeLegged = (value: ThreeLeggedOAuthParams | undefined) => |
| 153 | value === undefined |
| 154 | ? undefined |
| 155 | : { |
| 156 | clientId: value.clientId, |
| 157 | authorizationUrl: value.authorizationUrl, |
| 158 | tokenUrl: value.tokenUrl, |
| 159 | defaultContinueUri: value.defaultContinueUri, |
| 160 | enablePkce: value.enablePkce, |
| 161 | }; |
| 162 | |
| 163 | const publicTwoLegged = (value: TwoLeggedOAuthParams | undefined) => |
| 164 | value === undefined |
| 165 | ? undefined |
| 166 | : { |
| 167 | clientId: value.clientId, |
| 168 | tokenUrl: value.tokenUrl, |
| 169 | }; |
| 170 | |
| 171 | export const typeKind = (params: AuthProviderTypeParams | undefined) => { |
| 172 | if (params?.threeLeggedOauth !== undefined) return "threeLeggedOauth"; |
| 173 | if (params?.twoLeggedOauth !== undefined) return "twoLeggedOauth"; |
| 174 | if (params?.apiKey !== undefined) return "apiKey"; |
| 175 | if (params?.geAuthProvider !== undefined) return "geAuthProvider"; |
| 176 | return undefined; |
| 177 | }; |
| 178 | |
| 179 | export const publicTypeParams = (params: AuthProviderTypeParams | undefined) => { |
| 180 | if (params === undefined || typeKind(params) === undefined) return undefined; |
| 181 | return { |
| 182 | kind: typeKind(params), |
| 183 | threeLeggedOauth: publicThreeLegged(params.threeLeggedOauth), |
| 184 | twoLeggedOauth: publicTwoLegged(params.twoLeggedOauth), |
| 185 | }; |
| 186 | }; |
| 187 | |
| 188 | export const hasSecretUpdate = ( |
| 189 | news: AuthProviderTypeParams | undefined, |
| 190 | olds: AuthProviderTypeParams | undefined, |
| 191 | ) => { |
| 192 | if (news === undefined || olds === undefined) return false; |
| 193 | const apiKeyChanged = |
| 194 | news.apiKey?.apiKey !== undefined && news.apiKey.apiKey !== olds.apiKey?.apiKey; |
| 195 | const threeSecretChanged = |
| 196 | news.threeLeggedOauth?.clientSecret !== undefined && |
| 197 | news.threeLeggedOauth.clientSecret !== olds.threeLeggedOauth?.clientSecret; |
| 198 | const twoSecretChanged = |
| 199 | news.twoLeggedOauth?.clientSecret !== undefined && |
| 200 | news.twoLeggedOauth.clientSecret !== olds.twoLeggedOauth?.clientSecret; |
| 201 | return apiKeyChanged || threeSecretChanged || twoSecretChanged; |
| 202 | }; |
| 203 | |
| 204 | export const toTypeParams = ( |
| 205 | params: agentidentity.AuthProviderTypeParams | AuthProviderTypeParams | undefined, |
| 206 | ): AuthProviderTypeParams | undefined => { |
| 207 | if (params === undefined) return undefined; |
| 208 | const three = params.threeLeggedOauth; |
| 209 | const two = params.twoLeggedOauth; |
| 210 | const apiKey = params.apiKey; |
| 211 | const ge = params.geAuthProvider; |
| 212 | if (three === undefined && two === undefined && apiKey === undefined && ge === undefined) { |
| 213 | return undefined; |
| 214 | } |
| 215 | return { |
| 216 | threeLeggedOauth: |
| 217 | three === undefined |
| 218 | ? undefined |
| 219 | : { |
| 220 | clientId: three.clientId, |
| 221 | authorizationUrl: three.authorizationUrl, |
| 222 | tokenUrl: three.tokenUrl, |
| 223 | defaultContinueUri: three.defaultContinueUri, |
| 224 | enablePkce: three.enablePkce, |
| 225 | }, |
| 226 | twoLeggedOauth: |
| 227 | two === undefined |
| 228 | ? undefined |
| 229 | : { |
| 230 | clientId: two.clientId, |
| 231 | tokenUrl: two.tokenUrl, |
| 232 | }, |
| 233 | apiKey: apiKey === undefined ? undefined : {}, |
| 234 | geAuthProvider: ge === undefined ? undefined : {}, |
| 235 | }; |
| 236 | }; |
| 237 | |
| 238 | export const typeParamsBody = ( |
| 239 | params: AuthProviderTypeParams | undefined, |
| 240 | ): agentidentity.AuthProviderTypeParams | undefined => { |
| 241 | if (params === undefined) return undefined; |
| 242 | return { |
| 243 | threeLeggedOauth: params.threeLeggedOauth, |
| 244 | twoLeggedOauth: params.twoLeggedOauth, |
| 245 | apiKey: params.apiKey, |
| 246 | geAuthProvider: params.geAuthProvider === undefined ? undefined : {}, |
| 247 | }; |
| 248 | }; |
| 249 | |
| 250 | export const getByName = (name: string) => |
| 251 | name.length === 0 |
| 252 | ? Effect.undefined |
| 253 | : agentidentity |
| 254 | .getProjectsLocationsAuthProviders({ name }) |
| 255 | .pipe(Effect.catchTag("NotFound", () => Effect.undefined)); |
| 256 | |
| 257 | const listPages = (parent: string) => |
| 258 | agentidentity.listProjectsLocationsAuthProviders |
| 259 | .pages({ |
| 260 | parent, |
| 261 | pageSize: 1000, |
| 262 | }) |
| 263 | .pipe( |
| 264 | Stream.flatMap((page) => Stream.fromIterable(page.authProviders ?? [])), |
| 265 | Stream.filter((item) => item.deleted !== true && hasAlchemyLabelMap(item.labels)), |
| 266 | Stream.runCollect, |
| 267 | Effect.map((chunk) => Array.from(chunk)), |
| 268 | Effect.catchTag("NotFound", () => Effect.succeed([] as agentidentity.AuthProvider[])), |
| 269 | ); |
| 270 | |
| 271 | const listLocationIds = (project: string, region: string) => |
| 272 | agentidentity.listProjectsLocations |
| 273 | .pages({ |
| 274 | name: `projects/${project}`, |
| 275 | pageSize: 200, |
| 276 | }) |
| 277 | .pipe( |
| 278 | Stream.flatMap((page) => Stream.fromIterable(page.locations ?? [])), |
| 279 | Stream.map((location) => location.locationId ?? lastSegment(location.name ?? "")), |
| 280 | Stream.filter((id) => id.length > 0), |
| 281 | Stream.runCollect, |
| 282 | Effect.map((chunk) => { |
| 283 | const ids = new Set(Array.from(chunk)); |
| 284 | ids.add(region); |
| 285 | return [...ids]; |
| 286 | }), |
| 287 | Effect.catchTag("NotFound", () => Effect.succeed([region])), |
| 288 | ); |
| 289 | |
| 290 | export const listOwned = (project: string, region: string) => |
| 291 | Effect.gen(function* () { |
| 292 | const wildcard = yield* listPages(`projects/${project}/locations/-`); |
| 293 | if (wildcard.length > 0) return wildcard; |
| 294 | const locations = yield* listLocationIds(project, region); |
| 295 | const pages = yield* Effect.forEach( |
| 296 | locations, |
| 297 | (location) => listPages(parentOf(project, location)), |
| 298 | { concurrency: "unbounded" }, |
| 299 | ); |
| 300 | const byName = new Map<string, agentidentity.AuthProvider>(); |
| 301 | for (const item of pages.flat()) { |
| 302 | if (item.name) byName.set(item.name, item); |
| 303 | } |
| 304 | return [...byName.values()]; |
| 305 | }); |