@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, 04:45 UTC

main
ts 129 lines 5.17 KB
Raw
1 import { Credentials } from "@distilled.cloud/cloudflare/Credentials";
2 import * as Binding from "alchemy/Binding";
3 import type { RuntimeContext } from "alchemy/RuntimeContext";
4 import * as Effect from "effect/Effect";
5 import * as FetchHttpClient from "effect/http/FetchHttpClient";
6 import type * as HttpClient from "effect/http/HttpClient";
7 import * as Layer from "effect/Layer";
8 import * as Option from "effect/Option";
9 import { AccountApiToken } from "../ApiToken/AccountApiToken.ts";
10 import type { PermissionGroupRef } from "../ApiToken/Common.ts";
11 import { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
12 import { authorizeWith } from "../HttpClientUtils.ts";
13 import { isWorker } from "../Workers/Worker.ts";
14 import { type FindIdentityProviderOptions, GetIdentityProvider } from "./GetIdentityProvider.ts";
15 import { findFirst, toAttributes } from "./IdentityProviderLookup.ts";
16
17 const PERMISSION_GROUPS: PermissionGroupRef[] = [
18 "Access: Organizations, Identity Providers, and Groups Read",
19 ];
20
21 /**
22 * Injectable auth for the lookup client: `authorize` provides
23 * `Credentials` + `HttpClient` to the raw zero-trust list op, so the
24 * client is agnostic to whether creds come from a bound scoped token
25 * (Worker host) or the ambient plan-time credentials (data source).
26 */
27 interface AccessIdpAuth {
28 authorize: <A, E>(
29 eff: Effect.Effect<A, E, Credentials | HttpClient.HttpClient>,
30 ) => Effect.Effect<A, E, RuntimeContext>;
31 accountId: Effect.Effect<string>;
32 }
33
34 /**
35 * HTTP implementation of the {@link GetIdentityProvider} binding.
36 *
37 * When bound inside a Worker, it mints a scoped {@link AccountApiToken}
38 * with the `Access: Organizations, Identity Providers, and Groups Read`
39 * permission and binds its outputs into the Worker so runtime code can
40 * call the Access API. Hostless — the plan-time `execute` data source
41 * ({@link getIdentityProvider}) or an Action — it runs with the ambient
42 * current credentials instead; no token is minted.
43 */
44 export const GetIdentityProviderHttp = Layer.effect(
45 GetIdentityProvider,
46 Effect.gen(function* () {
47 const Token = yield* AccountApiToken;
48 const ambientCredentials = yield* Effect.serviceOption(Credentials).pipe(
49 Effect.map(Option.getOrUndefined),
50 );
51
52 return Effect.fn(function* (options: FindIdentityProviderOptions) {
53 // Resolved per call, NOT at layer build: the callable runs in the
54 // caller's context, so a Worker host is visible here during the
55 // Worker's init phase (plan and runtime) even though the layer
56 // itself may have been built (and memoized) hostless by
57 // `providers()`. Hostless callers — the plan-time `execute` data
58 // source — resolve `undefined`.
59 const host = yield* Binding.Host;
60 if (isWorker(host)) {
61 // Worker-hosted: mint the scoped token, attach the read policy
62 // (a no-op once deployed), and bind the token's outputs into the
63 // Worker so the client can authenticate at runtime.
64 const token = yield* Token(`${host.LogicalId}Token`);
65 if (!globalThis.__ALCHEMY_RUNTIME__) {
66 const { accountId } = yield* CloudflareEnvironment.current;
67 yield* token.bind("Cloudflare.Access.GetIdentityProvider", {
68 policies: [
69 {
70 effect: "allow",
71 permissionGroups: PERMISSION_GROUPS,
72 resources: {
73 [`com.cloudflare.api.account.${accountId}`]: "*",
74 },
75 },
76 ],
77 });
78 }
79 const bound = {
80 value: yield* token.value,
81 accountId: yield* token.accountId,
82 };
83 return makeGetIdentityProviderClient(
84 { authorize: authorizeWith(bound), accountId: bound.accountId },
85 options,
86 );
87 }
88
89 // Hostless — plan-time data source: run with the ambient credentials
90 // (refresh-aware, provided by the stack's providers layer).
91 if (ambientCredentials === undefined) {
92 return yield* Effect.die(
93 new Error(
94 "Cloudflare.Access.GetIdentityProvider requires either a Worker " +
95 "host (runtime binding) or ambient Cloudflare credentials " +
96 "(plan-time data source).",
97 ),
98 );
99 }
100 const { accountId } = yield* CloudflareEnvironment.current;
101 return makeGetIdentityProviderClient(
102 {
103 authorize: (eff) =>
104 eff.pipe(
105 Effect.provideService(Credentials, ambientCredentials),
106 Effect.provide(FetchHttpClient.layer),
107 ),
108 accountId: Effect.succeed(accountId),
109 },
110 options,
111 );
112 });
113 }),
114 );
115
116 const makeGetIdentityProviderClient = (auth: AccessIdpAuth, options: FindIdentityProviderOptions) =>
117 Effect.fn("Cloudflare.Access.GetIdentityProvider")(function* () {
118 const accountId = yield* auth.accountId;
119 const match = yield* auth.authorize(
120 findFirst(
121 options.zoneId,
122 accountId,
123 (idp) =>
124 (options.name === undefined || idp.name === options.name) &&
125 (options.type === undefined || idp.type === options.type),
126 ),
127 );
128 return match ? toAttributes(match, options.zoneId, accountId, undefined) : undefined;
129 });