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

main
ts 177 lines 6.82 KB
Raw
1 import type * as cf from "@cloudflare/workers-types";
2 import type { RuntimeContext } from "alchemy/RuntimeContext";
3 import * as Data from "effect/Data";
4 import * as Effect from "effect/Effect";
5 import type { Application, ApplicationProps } from "../Access/Application.ts";
6
7 /**
8 * Protect this Worker with Cloudflare Access (`access` prop). Two forms:
9 *
10 * - a `Cloudflare.Access.Application` — enroll into a **shared**
11 * application (one policy set across several Workers). Note Access
12 * policies are application-wide: every Worker enrolled in the
13 * application is gated by the same policies.
14 * - `{ policies, ... }` — a **dedicated** application owned by this
15 * Worker, created/updated/deleted with it. Access configuration
16 * (policies, session duration, IdPs) lives on applications, so
17 * per-Worker configuration means a per-Worker application — this form
18 * declares one for you, namespaced under the Worker (`<Worker>/Access`).
19 *
20 * Either way, enrolling pushes this Worker's `worker` destination (and a
21 * `preview_worker` destination unless `previews: false`) onto the
22 * application through its binding contract, so the application deploys
23 * with — and converges on — the destinations of every enrolled Worker.
24 * Removing the prop (or the Worker) un-enrolls it on the application's
25 * next reconcile.
26 */
27 export type WorkerAccessConfig = Application | WorkerAccessApplication;
28
29 /**
30 * A dedicated Access application owned by this Worker — per-Worker
31 * policies without declaring the application yourself.
32 */
33 export interface WorkerAccessApplication {
34 /**
35 * Policies gating access to this Worker — inline bodies, reusable
36 * `Cloudflare.Access.Policy` resources, or policy ids (see
37 * `ApplicationProps["policies"]`).
38 */
39 policies: NonNullable<ApplicationProps["policies"]>;
40 /** Display name for the application. Auto-generated when omitted. */
41 name?: string;
42 /** Session lifetime, e.g. `"24h"`. */
43 sessionDuration?: string;
44 /** Allowed identity-provider UUIDs. */
45 allowedIdps?: string[];
46 /** Skip the IdP picker when exactly one IdP is allowed. */
47 autoRedirectToIdentity?: boolean;
48 /** Show the application in the App Launcher dashboard. */
49 appLauncherVisible?: boolean;
50 /**
51 * Also protect the Worker's version preview URLs.
52 * @default true
53 */
54 previews?: boolean;
55 }
56
57 export class WorkerAccessIdentityError extends Data.TaggedError("WorkerAccessIdentityError")<{
58 message: string;
59 cause?: unknown;
60 }> {}
61
62 /**
63 * The identity Cloudflare Access authenticated for the current request,
64 * as resolved by `ctx.access.getIdentity()`. Field names follow the wire
65 * format of Access's identity payload (snake_case); identity providers can
66 * attach additional fields, captured by the index signature.
67 */
68 export interface WorkerAccessIdentity {
69 /** The user's email address, if the identity provider supplies one. */
70 readonly email?: string;
71 /** The user's display name. */
72 readonly name?: string;
73 /** The user's unique identifier. */
74 readonly user_uuid?: string;
75 /** The Cloudflare account id the Access organization belongs to. */
76 readonly account_id?: string;
77 /** Login timestamp (Unix epoch seconds). */
78 readonly iat?: number;
79 /** The user's IP address at authentication time. */
80 readonly ip?: string;
81 /** Authentication methods used (e.g. `"pwd"`). */
82 readonly amr?: string[];
83 /** Identity-provider information. */
84 readonly idp?: { id: string; type: string };
85 /** Where the user authenticated from. */
86 readonly geo?: { country: string };
87 /** Group memberships from the identity provider. */
88 readonly groups?: Array<{ id: string; name: string; email?: string }>;
89 /** Device posture check results, keyed by check id. */
90 readonly devicePosture?: Record<string, unknown>;
91 /** True when the user connected via Cloudflare WARP. */
92 readonly is_warp?: boolean;
93 /** True when the user is authenticated via Cloudflare Gateway. */
94 readonly is_gateway?: boolean;
95 /** Service-token client id, when authenticated via a service token. */
96 readonly service_token_id?: string;
97 /** True when the request authenticated with a service token. */
98 readonly service_token_status?: boolean;
99 readonly [key: string]: unknown;
100 }
101
102 /**
103 * Effect-native view of the Cloudflare Access runtime API on the execution
104 * context (`ctx.access`). Present only when the request was admitted by a
105 * Cloudflare Access policy (see the `access` prop on `Cloudflare.Worker`),
106 * or when simulated locally via the Worker's `dev.access` config.
107 */
108 export interface WorkerExecutionContextAccess {
109 /** The Access application audience (AUD) tag that admitted this request. */
110 readonly aud: string;
111 /**
112 * Resolve the authenticated identity — email, name, groups, device
113 * posture, etc. Resolves `undefined` when Access has no identity for the
114 * request (e.g. some service-token flows).
115 */
116 getIdentity(): Effect.Effect<
117 WorkerAccessIdentity | undefined,
118 WorkerAccessIdentityError,
119 RuntimeContext
120 >;
121 }
122
123 /**
124 * The shape workerd exposes on `ctx.access` (typed locally — this package's
125 * workers-types predates it) and that the local dev simulation mirrors.
126 */
127 interface RawAccessContext {
128 readonly aud: string;
129 getIdentity(): Promise<WorkerAccessIdentity | undefined>;
130 }
131
132 const makeAccessContext = (raw: RawAccessContext): WorkerExecutionContextAccess => ({
133 aud: raw.aud,
134 getIdentity: () =>
135 Effect.tryPromise({
136 try: () => raw.getIdentity(),
137 catch: (cause) =>
138 new WorkerAccessIdentityError({
139 message:
140 cause instanceof Error ? cause.message : "Unknown Access identity resolution error",
141 cause,
142 }),
143 }),
144 });
145
146 /** The env key `dev.access` is lowered into by the local worker provider. */
147 export const DEV_ACCESS_ENV_KEY = "ALCHEMY_DEV_ACCESS";
148
149 /**
150 * Resolve the current request's Access context: workerd's native
151 * `ctx.access` when the request came through Cloudflare Access, the
152 * `dev.access` simulation under `alchemy dev`, and `undefined` (an
153 * unauthenticated request) otherwise. Backs the `access` member of the
154 * per-event `WorkerExecutionContext`.
155 */
156 export const resolveAccessContext = (
157 ctx: cf.ExecutionContext,
158 env: Record<string, unknown> | undefined,
159 ): WorkerExecutionContextAccess | undefined => {
160 // Deployed behind Access: workerd populates ctx.access natively.
161 const native = (ctx as cf.ExecutionContext & { access?: RawAccessContext }).access;
162 if (native !== undefined) {
163 return makeAccessContext(native);
164 }
165 // Local dev: the Worker's `dev.access` config is lowered into an env
166 // binding; absent config simulates an unauthenticated request.
167 const dev = env?.[DEV_ACCESS_ENV_KEY] as
168 | { aud?: string; identity?: WorkerAccessIdentity }
169 | undefined;
170 if (dev !== undefined) {
171 return {
172 aud: dev.aud ?? "dev",
173 getIdentity: () => Effect.succeed(dev.identity),
174 };
175 }
176 return undefined;
177 };