@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 237 lines 9.22 KB
Raw
1 import type { Input } from "alchemy/Input";
2 import type * as Output from "alchemy/Output";
3 import * as Effect from "effect/Effect";
4 import * as AWSBindings from "../AWSBindings.ts";
5 import type { PolicyStatement } from "../IAM/Policy.ts";
6 import { regionFromArn } from "../Lambda/BindingHttp.ts";
7 import type { Table } from "./Table.ts";
8
9 /**
10 * Shared scaffolding for AWS DynamoDB HTTP bindings.
11 *
12 * NOT exported from `index.ts` — every near-identical `{Op}Http.ts` in this
13 * service is a thin `Layer.effect(Cap, make…HttpBinding({ … }))` over one of
14 * the builders below. Everything except the operation, the IAM action list,
15 * and the granted ARNs is boilerplate. Genuinely-different bindings
16 * (multi-table batches/transactions, restores, the batched sink) stay
17 * bespoke but share {@link grantTables} / {@link tablesRegion}.
18 *
19 * Every binding works on any host (see `AWSBindings.ts`):
20 *
21 * - on a host that runs as an IAM role the deploy-time grant goes on that
22 * role and requests use the ambient `Credentials` / `Region`;
23 * - on any other host the grant goes on the Role Alchemy creates for it, and
24 * each operation is resolved with `AWSBindings.withCredentials` to sign
25 * with that Role in the bound table's region (parsed from its ARN).
26 */
27
28 /**
29 * Grant the host `policyStatements` under `label`, recorded as
30 * `Allow(<host>, <label>)` (see `AWSBindings.Bind`). Deploy-only: the grant
31 * sits behind the `__ALCHEMY_RUNTIME__` guard so the bundler drops it.
32 */
33 export const GrantTables = Effect.gen(function* () {
34 const bind = yield* AWSBindings.Bind;
35 return Effect.fn(function* (label: string, policyStatements: () => Input<PolicyStatement>[]) {
36 if (!globalThis.__ALCHEMY_RUNTIME__) {
37 yield* bind`${label}`({ policyStatements: policyStatements() });
38 }
39 });
40 });
41
42 /**
43 * The region a host with a created key signs requests in, for
44 * `AWSBindings.withCredentials`: the region of the bound tables, parsed from
45 * their ARNs (which this binds onto the host). Tables bound together must
46 * share one region.
47 *
48 * The ARN is used rather than `Table.region` because tables whose state
49 * predates that attribute keep their old attributes until their next update.
50 */
51 export const tablesRegion = Effect.fn(function* (tables: readonly Table[]) {
52 const arns: Effect.Effect<string>[] = [];
53 for (const table of tables) {
54 arns.push(yield* table.tableArn);
55 }
56 return Effect.gen(function* () {
57 const regions = [...new Set((yield* Effect.all(arns)).map(regionFromArn))];
58 if (regions.length !== 1) {
59 return yield* Effect.die(
60 new Error(
61 `DynamoDB tables bound together must share one AWS region, got: ${regions.join(", ")}`,
62 ),
63 );
64 }
65 return regions[0]!;
66 });
67 });
68
69 /**
70 * Build the impl Effect for an account-level operation (`ListTables`,
71 * `DescribeLimits`): the runtime callable passes the caller's request
72 * through unchanged and the deploy-time half grants `actions` on `*`
73 * (these DynamoDB actions do not support resource-level permissions).
74 */
75 export const makeAccountHttpBinding = <I, A, E, R>(options: {
76 /** Fully-qualified binding tag, e.g. `AWS.DynamoDB.ListTables`. */
77 tag: string;
78 /**
79 * The distilled operation, invoked with the caller's request as-is.
80 * Resolved with the host's credentials (see `AWSBindings.withCredentials`),
81 * signing in the stack's region on a host with a created key.
82 */
83 operation: Effect.Effect<(input: I) => Effect.Effect<A, E>, never, R>;
84 /** IAM actions granted on `*`. */
85 actions: readonly string[];
86 }) =>
87 Effect.gen(function* () {
88 const grantTables = yield* GrantTables;
89 const op = yield* AWSBindings.withCredentials(options.operation);
90
91 return Effect.fn(function* () {
92 yield* grantTables(`${options.tag}()`, () => [
93 {
94 Effect: "Allow",
95 Action: [...options.actions],
96 Resource: ["*"],
97 },
98 ]);
99 return Effect.fn(options.tag)(function* (request?: I) {
100 return yield* op((request ?? {}) as I);
101 });
102 });
103 });
104
105 /**
106 * Build the impl Effect for a table-scoped operation: the runtime callable
107 * injects the bound {@link Table}'s physical name as `TableName` and the
108 * deploy-time half grants `actions` on `resources` (default: the table ARN).
109 */
110 export const makeTableHttpBinding = <I extends { TableName?: string }, A, E, R>(options: {
111 /** Fully-qualified binding tag, e.g. `AWS.DynamoDB.GetItem`. */
112 tag: string;
113 /**
114 * The distilled operation; `TableName` is injected from the table.
115 * Resolved with the host's credentials (see `AWSBindings.withCredentials`),
116 * signing in the table's region on a host with a created key.
117 */
118 operation: Effect.Effect<(input: I) => Effect.Effect<A, E>, never, R>;
119 /** IAM actions granted on `resources`. */
120 actions: readonly string[];
121 /** ARNs the actions are granted on. @default the table ARN */
122 resources?: (table: Table) => (string | Output.Output<string>)[];
123 }) =>
124 Effect.gen(function* () {
125 const grantTables = yield* GrantTables;
126 return Effect.fn(function* (table: Table) {
127 const TableName = yield* table.tableName;
128 // resolved per bind because a host with a created key signs in the table's own region
129 const op = yield* AWSBindings.withCredentials(options.operation, tablesRegion([table]));
130 yield* grantTables(`${options.tag}(${table.LogicalId})`, () => [
131 {
132 Effect: "Allow",
133 Action: [...options.actions],
134 Resource: options.resources?.(table) ?? [table.tableArn],
135 },
136 ]);
137 return Effect.fn(`${options.tag}(${table.LogicalId})`)(function* (
138 request?: Omit<I, "TableName">,
139 ) {
140 return yield* op({
141 ...request,
142 TableName: yield* TableName,
143 } as I);
144 });
145 });
146 });
147
148 /**
149 * Build the impl Effect for an ARN-scoped operation: the runtime callable
150 * injects the bound {@link Table}'s ARN under `key` (`ResourceArn` for the
151 * tagging APIs, `TableArn` for the export APIs) and the deploy-time half
152 * grants `actions` on `resources` (default: the table ARN).
153 */
154 export const makeTableArnHttpBinding = <
155 K extends "ResourceArn" | "TableArn",
156 I extends { [P in K]?: string },
157 A,
158 E,
159 R,
160 >(options: {
161 /** Fully-qualified binding tag, e.g. `AWS.DynamoDB.ListTagsOfResource`. */
162 tag: string;
163 /** The request field the table ARN is injected under. */
164 key: K;
165 /**
166 * The distilled operation; the table ARN is injected under `key`.
167 * Resolved with the host's credentials (see `AWSBindings.withCredentials`),
168 * signing in the table's region on a host with a created key.
169 */
170 operation: Effect.Effect<(input: I) => Effect.Effect<A, E>, never, R>;
171 /** IAM actions granted on `resources`. */
172 actions: readonly string[];
173 /** ARNs the actions are granted on. @default the table ARN */
174 resources?: (table: Table) => (string | Output.Output<string>)[];
175 }) =>
176 Effect.gen(function* () {
177 const grantTables = yield* GrantTables;
178 return Effect.fn(function* (table: Table) {
179 const TableArn = yield* table.tableArn;
180 // resolved per bind because a host with a created key signs in the table's own region
181 const op = yield* AWSBindings.withCredentials(
182 options.operation,
183 Effect.succeed(Effect.map(TableArn, regionFromArn)),
184 );
185 yield* grantTables(`${options.tag}(${table.LogicalId})`, () => [
186 {
187 Effect: "Allow",
188 Action: [...options.actions],
189 Resource: options.resources?.(table) ?? [table.tableArn],
190 },
191 ]);
192 return Effect.fn(`${options.tag}(${table.LogicalId})`)(function* (request?: Omit<I, K>) {
193 return yield* op({
194 ...request,
195 [options.key]: yield* TableArn,
196 } as I);
197 });
198 });
199 });
200
201 /**
202 * Build the impl Effect for an operation whose request carries its own
203 * identifiers (a PartiQL statement, a backup or export ARN): the bound
204 * {@link Table} only scopes the deploy-time IAM grant (and, on an external
205 * host, the signing region); the request passes through unchanged.
206 */
207 export const makeTableIamHttpBinding = <I, A, E, R>(options: {
208 /** Fully-qualified binding tag, e.g. `AWS.DynamoDB.ExecuteStatement`. */
209 tag: string;
210 /**
211 * The distilled operation, invoked with the caller's request as-is.
212 * Resolved with the host's credentials (see `AWSBindings.withCredentials`),
213 * signing in the table's region on a host with a created key.
214 */
215 operation: Effect.Effect<(input: I) => Effect.Effect<A, E>, never, R>;
216 /** IAM actions granted on `resources`. */
217 actions: readonly string[];
218 /** ARNs the actions are granted on. */
219 resources: (table: Table) => (string | Output.Output<string>)[];
220 }) =>
221 Effect.gen(function* () {
222 const grantTables = yield* GrantTables;
223 return Effect.fn(function* (table: Table) {
224 // resolved per bind because a host with a created key signs in the table's own region
225 const op = yield* AWSBindings.withCredentials(options.operation, tablesRegion([table]));
226 yield* grantTables(`${options.tag}(${table.LogicalId})`, () => [
227 {
228 Effect: "Allow",
229 Action: [...options.actions],
230 Resource: options.resources(table),
231 },
232 ]);
233 return Effect.fn(`${options.tag}(${table.LogicalId})`)(function* (request: I) {
234 return yield* op(request);
235 });
236 });
237 });