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

main
ts 201 lines 7.91 KB
Raw
1 import type * as scheduler from "@distilled.cloud/aws/scheduler";
2 /**
3 * Shared scaffolding for EventBridge Scheduler HTTP bindings.
4 *
5 * NOT exported from `index.ts` — every thin `{Op}Http.ts` in this service is
6 * a `Layer.effect(Cap, make…HttpBinding({ … }))` over one of the builders
7 * below. Everything except the operation and the IAM action list is
8 * boilerplate:
9 *
10 * - **Group-scoped operations** (`scheduler:GetSchedule`,
11 * `scheduler:DeleteSchedule`, `scheduler:ListSchedules`) inject the bound
12 * {@link ScheduleGroup}'s name as the request's `GroupName` and are granted
13 * on the group's schedule ARN pattern. Dynamic schedules are named at
14 * runtime, so the resource pattern is group-scoped rather than an exact
15 * ARN: the group (or the default group) is the least-privilege boundary.
16 * - **Write operations** (`scheduler:CreateSchedule`,
17 * `scheduler:UpdateSchedule`) additionally take the schedule **execution
18 * role** (the IAM role EventBridge Scheduler assumes to invoke the target)
19 * and contribute `iam:PassRole` on it — without the PassRole statement the
20 * write fails only at runtime. The bound role is injected as the target's
21 * `RoleArn` unless the request overrides it, and `FlexibleTimeWindow`
22 * defaults to `{ Mode: "OFF" }`.
23 */
24 import * as Output from "alchemy/Output";
25 import * as Effect from "effect/Effect";
26 import * as AWSBindings from "../AWSBindings.ts";
27 import { AWSEnvironment } from "../Environment.ts";
28 import type { Role } from "../IAM/Role.ts";
29 import type { ScheduleGroup } from "./ScheduleGroup.ts";
30
31 /**
32 * Resolve the group-scoped schedule ARN pattern the binding is granted on.
33 * Passes unresolved Outputs — binding data is resolved by the engine before
34 * the host reconciles.
35 */
36 const scheduleArnPattern = Effect.fn(function* (group: ScheduleGroup | undefined) {
37 const { accountId, region } = yield* AWSEnvironment.current as unknown as Effect.Effect<{
38 accountId: string;
39 region: string;
40 }>;
41 return group
42 ? Output.interpolate`arn:aws:scheduler:${region}:${accountId}:schedule/${group.scheduleGroupName}/*`
43 : (`arn:aws:scheduler:${region}:${accountId}:schedule/default/*` as const);
44 });
45
46 /**
47 * Account-wide schedule ARN pattern — the resource IAM evaluates
48 * `scheduler:ListSchedules` against, regardless of any `GroupName` filter in
49 * the request.
50 */
51 const allSchedulesArnPattern = Effect.gen(function* () {
52 const { accountId, region } = yield* AWSEnvironment.current as unknown as Effect.Effect<{
53 accountId: string;
54 region: string;
55 }>;
56 return `arn:aws:scheduler:${region}:${accountId}:schedule/*/*` as const;
57 });
58
59 /**
60 * Build the impl Effect for a group-scoped Scheduler operation: the
61 * deploy-time half grants `actions` on the group's schedule ARN pattern, and
62 * the runtime half injects the group's name as the request's `GroupName`.
63 */
64 export const makeScheduleGroupScopedHttpBinding = <
65 I extends { GroupName?: string },
66 A,
67 E,
68 R,
69 >(options: {
70 /** Fully-qualified binding tag, e.g. `AWS.Scheduler.GetSchedule`. */
71 tag: string;
72 /** The distilled operation; `GroupName` is injected from the bound group. */
73 operation: Effect.Effect<(input: I) => Effect.Effect<A, E>, never, R>;
74 /** IAM actions granted on the group's schedule ARN pattern. */
75 actions: readonly string[];
76 /**
77 * `GroupName` injected when no group is bound. Get/Delete leave it
78 * undefined (the API defaults to the `default` group); ListSchedules pins
79 * `"default"` explicitly because an absent `GroupName` there means "all
80 * groups".
81 */
82 fallbackGroupName?: string;
83 /**
84 * IAM resource scope. `"group"` (default) grants on the bound group's
85 * `schedule/{group}/*` pattern. `"all"` grants on `schedule/*​/*` —
86 * required for `scheduler:ListSchedules`, which IAM evaluates against the
87 * account-wide schedule pattern regardless of the request's `GroupName`
88 * filter (AccessDenied cites `schedule/*​/*`).
89 */
90 resourceScope?: "group" | "all";
91 }) =>
92 Effect.gen(function* () {
93 const bind = yield* AWSBindings.Bind;
94 const op = yield* AWSBindings.withCredentials(options.operation);
95
96 return Effect.fn(function* (group?: ScheduleGroup) {
97 const GroupName = group ? yield* group.scheduleGroupName : undefined;
98 if (!globalThis.__ALCHEMY_RUNTIME__) {
99 const pattern =
100 options.resourceScope === "all"
101 ? yield* allSchedulesArnPattern
102 : yield* scheduleArnPattern(group);
103 yield* bind`${options.tag}(${group ?? "default"})`({
104 policyStatements: [
105 {
106 Effect: "Allow",
107 Action: [...options.actions],
108 Resource: [pattern],
109 },
110 ],
111 });
112 }
113 return Effect.fn(`${options.tag}(${group?.LogicalId ?? "default"})`)(function* (
114 request?: Omit<I, "GroupName">,
115 ) {
116 const groupName = GroupName ? yield* GroupName : options.fallbackGroupName;
117 return yield* op({
118 ...request,
119 GroupName: groupName,
120 } as I);
121 });
122 });
123 });
124
125 /**
126 * Build the impl Effect for a Scheduler write operation
127 * (`CreateSchedule`/`UpdateSchedule`): constructed with the schedule
128 * execution role (plus an optional scoping {@link ScheduleGroup}), the
129 * deploy-time half grants `actions` on the group's schedule ARN pattern AND
130 * `iam:PassRole` on the execution role; the runtime half injects the group's
131 * name, defaults `FlexibleTimeWindow` to `{ Mode: "OFF" }`, and defaults the
132 * target's `RoleArn` to the bound execution role.
133 */
134 export const makeScheduleWriteHttpBinding = <
135 I extends {
136 GroupName?: string;
137 Target: scheduler.Target;
138 FlexibleTimeWindow: scheduler.FlexibleTimeWindow;
139 },
140 A,
141 E,
142 R,
143 >(options: {
144 /** Fully-qualified binding tag, e.g. `AWS.Scheduler.CreateSchedule`. */
145 tag: string;
146 /** The distilled operation; group, time window, and role are injected. */
147 operation: Effect.Effect<(input: I) => Effect.Effect<A, E>, never, R>;
148 /** IAM actions granted on the group's schedule ARN pattern. */
149 actions: readonly string[];
150 }) =>
151 Effect.gen(function* () {
152 const bind = yield* AWSBindings.Bind;
153 const op = yield* AWSBindings.withCredentials(options.operation);
154
155 return Effect.fn(function* <Ro extends Role>(executionRole: Ro, group?: ScheduleGroup) {
156 const RoleArn = yield* executionRole.roleArn;
157 const GroupName = group ? yield* group.scheduleGroupName : undefined;
158 if (!globalThis.__ALCHEMY_RUNTIME__) {
159 const pattern = yield* scheduleArnPattern(group);
160 yield* bind`${options.tag}(${executionRole}, ${group ?? "default"})`({
161 policyStatements: [
162 {
163 Effect: "Allow",
164 Action: [...options.actions],
165 Resource: [pattern],
166 },
167 // CRITICAL: without iam:PassRole on the execution role, the
168 // write fails only at runtime with an AccessDenied.
169 {
170 Effect: "Allow",
171 Action: ["iam:PassRole"],
172 Resource: [Output.interpolate`${executionRole.roleArn}`],
173 Condition: {
174 StringEquals: {
175 "iam:PassedToService": "scheduler.amazonaws.com",
176 },
177 },
178 },
179 ],
180 });
181 }
182 return Effect.fn(`${options.tag}(${executionRole.LogicalId})`)(function* (
183 request: Omit<I, "GroupName" | "Target" | "FlexibleTimeWindow"> & {
184 Target: Omit<scheduler.Target, "RoleArn"> & { RoleArn?: string };
185 FlexibleTimeWindow?: scheduler.FlexibleTimeWindow;
186 },
187 ) {
188 const roleArn = yield* RoleArn;
189 const groupName = GroupName ? yield* GroupName : undefined;
190 return yield* op({
191 ...request,
192 GroupName: groupName,
193 FlexibleTimeWindow: request.FlexibleTimeWindow ?? { Mode: "OFF" },
194 Target: {
195 ...request.Target,
196 RoleArn: request.Target.RoleArn ?? roleArn,
197 },
198 } as I);
199 });
200 });
201 });