@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 210 lines 7.27 KB
Raw
1 import * as appsync from "@distilled.cloud/aws/appsync";
2 import { isResolved } from "alchemy/Diff";
3 import type { Input } from "alchemy/Input";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import * as Effect from "effect/Effect";
7 import * as Redacted from "effect/Redacted";
8 import * as Stream from "effect/Stream";
9 import type { Providers } from "../Providers.ts";
10 import { retryConcurrentModification } from "./common.ts";
11 import type { GraphqlApi } from "./GraphqlApi.ts";
12
13 export interface ApiKeyProps {
14 /**
15 * ID of the GraphQL API. Usually derived from `api.apiId` by the
16 * {@link ApiKey} wrapper.
17 */
18 apiId: string;
19 /** Description of the key. */
20 description?: string;
21 /**
22 * Expiry as epoch seconds, between 1 and 365 days from creation. AWS
23 * rounds the value **down to the nearest hour**. When omitted, the key
24 * expires 7 days after creation and expiry is left unmanaged.
25 */
26 expires?: number;
27 }
28
29 export interface AppSyncApiKey extends Resource<
30 "AWS.AppSync.ApiKey",
31 ApiKeyProps,
32 {
33 /** The API this key belongs to. */
34 apiId: string;
35 /**
36 * The API key ID — this IS the secret key value (`da2-…`) clients send
37 * in the `x-api-key` header. Wrapped in `Redacted` — unwrap with
38 * `Redacted.value(key.id)` where the raw header value is needed.
39 */
40 id: Redacted.Redacted<string>;
41 /** The key's expiry (epoch seconds, rounded down to the hour). */
42 expires: number | undefined;
43 /** The key's description. */
44 description: string | undefined;
45 },
46 never,
47 Providers
48 > {}
49
50 /**
51 * An AppSync API key for `API_KEY`-authenticated GraphQL APIs.
52 *
53 * The key's `id` attribute is the secret value (`da2-…`) sent in the
54 * `x-api-key` request header. It is wrapped in `Redacted`; unwrap with
55 * `Redacted.value(key.id)` where the raw header value is needed.
56 * ### Creating API Keys
57 * **Example:** Key with the default 7-day expiry
58 * ```typescript
59 * const key = yield* AppSync.ApiKey("Key", { api });
60 * // Redacted.value(key.id) → "da2-…" — send as the x-api-key header
61 * ```
62 *
63 * **Example:** Key with a managed expiry
64 * ```typescript
65 * const key = yield* AppSync.ApiKey("Key", {
66 * api,
67 * description: "mobile clients",
68 * expires: 1893456000, // rounded down to the hour by AWS
69 * });
70 * ```
71 *
72 * @resource
73 */
74 export const ApiKeyResource = Resource<AppSyncApiKey>("AWS.AppSync.ApiKey");
75
76 export interface ApiKeyInputProps extends Omit<
77 {
78 [K in keyof ApiKeyProps]?: Input<ApiKeyProps[K]>;
79 },
80 "apiId"
81 > {
82 /**
83 * The `GraphqlApi` this key belongs to (preferred). Alternatively pass a
84 * raw `apiId`.
85 */
86 api?: GraphqlApi;
87 apiId?: Input<string>;
88 }
89
90 /**
91 * User-facing wrapper for the ApiKey resource. Accepts `api: GraphqlApi`
92 * as the idiomatic way to mint a key for an API.
93 */
94 export const ApiKey = (id: string, props: ApiKeyInputProps = {}) =>
95 Effect.gen(function* () {
96 const { api, ...rest } = props;
97 const apiId = rest.apiId ?? api?.apiId;
98 if (!apiId) {
99 return yield* Effect.die("ApiKey requires either `api` (preferred) or an explicit `apiId`.");
100 }
101 return yield* ApiKeyResource(id, { ...rest, apiId } as any);
102 });
103
104 /** AWS rounds key expiry down to the nearest hour. */
105 const floorToHour = (epochSeconds: number): number => Math.floor(epochSeconds / 3600) * 3600;
106
107 export const ApiKeyProvider = () =>
108 Provider.effect(
109 ApiKeyResource,
110 Effect.gen(function* () {
111 /** Find a key by its ID (keys have no other stable identity). */
112 const findKey = Effect.fn(function* (apiId: string, keyId: string) {
113 const pages = yield* appsync.listApiKeys.pages({ apiId }).pipe(
114 Stream.runCollect,
115 Effect.catchTag("NotFoundException", () => Effect.succeed([])),
116 );
117 return Array.from(pages)
118 .flatMap((page) => page.apiKeys ?? [])
119 .find((key) => key.id === keyId);
120 });
121
122 const toAttributes = (apiId: string, key: appsync.ApiKey): AppSyncApiKey["Attributes"] => ({
123 apiId,
124 // The key id doubles as the secret `x-api-key` header value.
125 id: Redacted.make(key.id!),
126 expires: key.expires,
127 description: key.description,
128 });
129
130 return ApiKeyResource.Provider.of({
131 stables: ["apiId", "id"],
132
133 // Sub-resource keyed entirely by its GraphQL API (apiId) with no global
134 // enumeration API of its own — nuke reaches it through the parent's
135 // deletion, so enumeration returns empty per the ProviderService
136 // doctrine.
137 list: () => Effect.succeed([]),
138
139 read: Effect.fn(function* ({ output }) {
140 // Keys carry no deterministic identity — without the cached id
141 // there is nothing to look up (a fresh reconcile will mint one).
142 if (output?.id === undefined) return undefined;
143 const key = yield* findKey(output.apiId, Redacted.value(output.id));
144 if (key?.id == null) return undefined;
145 return toAttributes(output.apiId, key);
146 }),
147
148 diff: Effect.fn(function* ({ news, olds }) {
149 if (!isResolved(news)) return undefined;
150 if (news.apiId !== olds.apiId) {
151 return { action: "replace" } as const;
152 }
153 // description/expires converge via updateApiKey
154 }),
155
156 reconcile: Effect.fn(function* ({ news, output, session }) {
157 const apiId = output?.apiId ?? news.apiId;
158
159 // 1. OBSERVE — the cached key id is the only handle.
160 let observed =
161 output?.id !== undefined ? yield* findKey(apiId, Redacted.value(output.id)) : undefined;
162
163 if (observed?.id == null) {
164 // 2. ENSURE
165 const created = yield* retryConcurrentModification(
166 appsync.createApiKey({
167 apiId,
168 description: news.description,
169 expires: news.expires,
170 }),
171 );
172 observed = created.apiKey!;
173 yield* session.note(`Created API key for ${apiId}`);
174 } else {
175 // 3. SYNC — update description/expiry on drift (expiry only
176 // when managed by props; AWS floors it to the hour).
177 const expiresDrifted =
178 news.expires !== undefined && observed.expires !== floorToHour(news.expires);
179 const descriptionDrifted =
180 news.description !== undefined && observed.description !== news.description;
181 if (expiresDrifted || descriptionDrifted) {
182 const updated = yield* retryConcurrentModification(
183 appsync.updateApiKey({
184 apiId,
185 id: observed.id,
186 description: news.description,
187 expires: news.expires,
188 }),
189 );
190 observed = updated.apiKey ?? observed;
191 yield* session.note(`Updated API key ${observed.id}`);
192 }
193 }
194
195 return toAttributes(apiId, observed);
196 }),
197
198 delete: Effect.fn(function* ({ output }) {
199 yield* retryConcurrentModification(
200 appsync
201 .deleteApiKey({
202 apiId: output.apiId,
203 id: Redacted.value(output.id),
204 })
205 .pipe(Effect.catchTag("NotFoundException", () => Effect.void)),
206 );
207 }),
208 });
209 }),
210 );