@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, 06:00 UTC

main
ts 324 lines 12.6 KB
Raw
1 import { randomUUID } from "node:crypto";
2 import * as Lambda from "@alchemy.run/aws/Lambda";
3 import * as LicenseManager from "@alchemy.run/aws/LicenseManager";
4 import * as Duration from "effect/Duration";
5 import * as Effect from "effect/Effect";
6 import { HttpServerRequest } from "effect/http/HttpServerRequest";
7 import * as HttpServerResponse from "effect/http/HttpServerResponse";
8 import * as Layer from "effect/Layer";
9 import * as Schedule from "effect/Schedule";
10 import path from "pathe";
11
12 const main = path.resolve(import.meta.dirname, "seller-handler.ts");
13
14 // Deterministic fixture identifiers — the lifecycle route sweeps stale
15 // licenses left by a crashed prior run before issuing a fresh one.
16 const FIXTURE_LICENSE_NAME = "alchemy-lm-seller-e2e";
17 const FIXTURE_PRODUCT_SKU = "alchemy-lm-seller-sku";
18 const FIXTURE_PRODUCT_NAME = "Alchemy LicenseManager Fixture";
19
20 // Well-formed-but-nonexistent grant — drives the typed error path of
21 // CreateGrantVersion (a genuine IAM gap would 500 with AccessDenied).
22 const BOGUS_GRANT_ARN =
23 "arn:aws:license-manager::111111111111:grant:g-00000000000000000000000000000000";
24
25 export class LicenseManagerSellerFunction extends Lambda.Function<Lambda.Function>()(
26 "LicenseManagerSellerFunction",
27 ) {}
28
29 export default LicenseManagerSellerFunction.make(
30 {
31 main,
32 functionUrl: true,
33 timeout: Duration.seconds(60),
34 },
35 Effect.gen(function* () {
36 // --- seller-issued license / grant / token data plane (account-level) ---
37 const createLicense = yield* LicenseManager.CreateLicense();
38 const createLicenseVersion = yield* LicenseManager.CreateLicenseVersion();
39 const deleteLicense = yield* LicenseManager.DeleteLicense();
40 const createGrant = yield* LicenseManager.CreateGrant();
41 const createGrantVersion = yield* LicenseManager.CreateGrantVersion();
42 const deleteGrant = yield* LicenseManager.DeleteGrant();
43 const createToken = yield* LicenseManager.CreateToken();
44 const deleteToken = yield* LicenseManager.DeleteToken();
45 const listTokens = yield* LicenseManager.ListTokens();
46
47 // --- consumer half of the loop (already-covered bindings, re-used here
48 // to drive the seller-issued license end-to-end) ---
49 const getLicense = yield* LicenseManager.GetLicense();
50 const listLicenses = yield* LicenseManager.ListLicenses();
51 const getAccessToken = yield* LicenseManager.GetAccessToken();
52 const checkoutLicense = yield* LicenseManager.CheckoutLicense();
53 const extendLicenseConsumption = yield* LicenseManager.ExtendLicenseConsumption();
54 const checkInLicense = yield* LicenseManager.CheckInLicense();
55
56 const bound = {
57 createLicense,
58 createLicenseVersion,
59 deleteLicense,
60 createGrant,
61 createGrantVersion,
62 deleteGrant,
63 createToken,
64 deleteToken,
65 listTokens,
66 };
67
68 const uuid = Effect.sync(() => randomUUID());
69
70 // Delete a seller license, tolerating the typed rejections a stale or
71 // already-deleted ARN surfaces.
72 const deleteLicenseQuietly = (arn: string, version: string) =>
73 deleteLicense({ LicenseArn: arn, SourceVersion: version }).pipe(
74 Effect.map(() => undefined),
75 Effect.catchTag(["InvalidParameterValueException", "ConflictException"], () =>
76 Effect.succeed(undefined),
77 ),
78 );
79
80 return {
81 fetch: Effect.gen(function* () {
82 const request = yield* HttpServerRequest;
83 const url = new URL(request.originalUrl);
84 const pathname = url.pathname;
85
86 if (request.method === "GET" && pathname === "/bindings") {
87 return yield* HttpServerResponse.json({
88 bound: Object.keys(bound),
89 });
90 }
91
92 // Full seller data plane: issue -> version -> token mint/exchange ->
93 // checkout/extend/checkin -> grant create/delete -> delete.
94 if (request.method === "POST" && pathname === "/lifecycle") {
95 const beneficiary = url.searchParams.get("account");
96 if (beneficiary === null) {
97 return yield* HttpServerResponse.json({ error: "missing ?account=" }, { status: 400 });
98 }
99 const region = yield* Effect.sync(() => process.env.AWS_REGION!);
100 const now = yield* Effect.sync(() => Date.now());
101 const begin = new Date(now - 24 * 3600 * 1000).toISOString();
102 const end = new Date(now + 365 * 24 * 3600 * 1000).toISOString();
103 const bumpedEnd = new Date(now + 2 * 365 * 24 * 3600 * 1000).toISOString();
104 const entitlements = [
105 {
106 Name: "seats",
107 MaxCount: 10,
108 Unit: "Count",
109 AllowCheckIn: true,
110 Overage: false,
111 },
112 ];
113 const consumption = {
114 RenewType: "None",
115 ProvisionalConfiguration: { MaxTimeToLiveInMinutes: 60 },
116 };
117
118 // Zero-orphan: sweep stale fixture licenses from crashed runs.
119 const stale = yield* listLicenses();
120 yield* Effect.forEach(
121 (stale.Licenses ?? []).filter(
122 (l): boolean =>
123 l.LicenseName === FIXTURE_LICENSE_NAME &&
124 l.Status === "AVAILABLE" &&
125 l.LicenseArn !== undefined &&
126 l.Version !== undefined,
127 ),
128 (l) => deleteLicenseQuietly(l.LicenseArn!, l.Version!),
129 );
130
131 // 1. Issue the license.
132 const created = yield* createLicense({
133 LicenseName: FIXTURE_LICENSE_NAME,
134 ProductName: FIXTURE_PRODUCT_NAME,
135 ProductSKU: FIXTURE_PRODUCT_SKU,
136 Issuer: { Name: "alchemy" },
137 HomeRegion: region,
138 Validity: { Begin: begin, End: end },
139 Entitlements: entitlements,
140 Beneficiary: beneficiary,
141 ConsumptionConfiguration: consumption,
142 ClientToken: yield* uuid,
143 });
144 const licenseArn = created.LicenseArn!;
145
146 // 2. Observe until AVAILABLE (bounded), capture issuer fingerprint.
147 const { License } = yield* getLicense({
148 LicenseArn: licenseArn,
149 }).pipe(
150 Effect.repeat({
151 schedule: Schedule.spaced("2 seconds"),
152 until: (r): boolean => r.License?.Status === "AVAILABLE",
153 times: 8,
154 }),
155 );
156 const fingerprint = License!.Issuer!.KeyFingerprint!;
157
158 // 3. Publish a new version (extended validity).
159 const bumped = yield* createLicenseVersion({
160 LicenseArn: licenseArn,
161 LicenseName: FIXTURE_LICENSE_NAME,
162 ProductName: FIXTURE_PRODUCT_NAME,
163 Issuer: { Name: "alchemy" },
164 HomeRegion: region,
165 Validity: { Begin: begin, End: bumpedEnd },
166 Entitlements: entitlements,
167 ConsumptionConfiguration: consumption,
168 Status: "AVAILABLE",
169 SourceVersion: License!.Version!,
170 ClientToken: yield* uuid,
171 });
172 const version = bumped.Version ?? License!.Version!;
173
174 // 4. Mint an activation token, exchange + revoke it. The exchange
175 // result stays Redacted; only its presence is reported.
176 const token = yield* createToken({
177 LicenseArn: licenseArn,
178 ClientToken: yield* uuid,
179 });
180 const tokens = yield* listTokens({ TokenIds: [token.TokenId!] });
181 const accessToken = yield* getAccessToken({
182 Token: token.Token!,
183 }).pipe(
184 Effect.map((r) => (r.AccessToken !== undefined ? "Ok" : "Empty")),
185 Effect.catchTag(
186 [
187 "AuthorizationException",
188 "ValidationException",
189 "AccessDeniedException",
190 "InvalidParameterValueException",
191 ],
192 (e) => Effect.succeed(e._tag),
193 ),
194 );
195 yield* deleteToken({ TokenId: token.TokenId! });
196
197 // 5. Check out the license as the beneficiary account, extend the
198 // provisional consumption, and check it back in. Retry through
199 // issuance propagation with a bounded typed retry.
200 const checkout = yield* checkoutLicense({
201 ProductSKU: FIXTURE_PRODUCT_SKU,
202 CheckoutType: "PROVISIONAL",
203 KeyFingerprint: fingerprint,
204 Entitlements: [{ Name: "seats", Value: "1", Unit: "Count" }],
205 ClientToken: yield* uuid,
206 Beneficiary: beneficiary,
207 }).pipe(
208 Effect.retry({
209 while: (e): boolean =>
210 e._tag === "ResourceNotFoundException" ||
211 e._tag === "NoEntitlementsAllowedException",
212 schedule: Schedule.exponential("1 second"),
213 times: 5,
214 }),
215 );
216 const consumptionToken = checkout.LicenseConsumptionToken!;
217 const extended = yield* extendLicenseConsumption({
218 LicenseConsumptionToken: consumptionToken,
219 });
220 yield* checkInLicense({
221 LicenseConsumptionToken: consumptionToken,
222 });
223
224 // 6. Grant lifecycle — a self-account grant may be rejected with a
225 // typed validation error; either outcome proves grant + wiring.
226 const grant = yield* createGrant({
227 GrantName: "alchemy-lm-seller-grant",
228 LicenseArn: licenseArn,
229 HomeRegion: region,
230 Principals: [`arn:aws:iam::${beneficiary}:root`],
231 AllowedOperations: [
232 "CheckoutLicense",
233 "CheckInLicense",
234 "ExtendConsumptionLicense",
235 "ListPurchasedLicenses",
236 ],
237 ClientToken: yield* uuid,
238 }).pipe(
239 Effect.flatMap((g) =>
240 deleteGrant({ GrantArn: g.GrantArn!, Version: g.Version! }).pipe(
241 Effect.map(() => "CreatedAndDeleted"),
242 ),
243 ),
244 Effect.catchTag(
245 [
246 "InvalidParameterValueException",
247 "ValidationException",
248 "AuthorizationException",
249 "ResourceLimitExceededException",
250 ],
251 (e) => Effect.succeed(e._tag),
252 ),
253 );
254
255 // 7. Delete the license (retry through a lingering consumption).
256 const deletion = yield* deleteLicense({
257 LicenseArn: licenseArn,
258 SourceVersion: version,
259 }).pipe(
260 Effect.retry({
261 while: (e): boolean => e._tag === "ConflictException",
262 schedule: Schedule.exponential("1 second"),
263 times: 4,
264 }),
265 );
266
267 return yield* HttpServerResponse.json({
268 licenseArn,
269 licenseStatus: License?.Status ?? null,
270 bumpedVersion: bumped.Version ?? null,
271 tokenListed: (tokens.Tokens ?? []).length,
272 accessToken,
273 checkedOut: checkout.LicenseConsumptionToken !== undefined,
274 extended: extended.LicenseConsumptionToken !== undefined,
275 grant,
276 deletionStatus: deletion.Status ?? null,
277 });
278 }
279
280 // Typed probe: CreateGrantVersion on a nonexistent grant surfaces a
281 // typed rejection (an IAM gap would 500 with AccessDenied instead).
282 if (request.method === "GET" && pathname === "/grant-version-invalid") {
283 const result = yield* createGrantVersion({
284 GrantArn: BOGUS_GRANT_ARN,
285 ClientToken: "00000000-0000-4000-8000-000000000001",
286 }).pipe(
287 Effect.map(() => "Ok"),
288 Effect.catchTag(
289 ["InvalidParameterValueException", "ValidationException", "AuthorizationException"],
290 (e) => Effect.succeed(e._tag),
291 ),
292 );
293 return yield* HttpServerResponse.json({ tag: result });
294 }
295
296 return yield* HttpServerResponse.json(
297 { error: "Not found", method: request.method, pathname },
298 { status: 404 },
299 );
300 }).pipe(Effect.orDie),
301 };
302 }).pipe(
303 Effect.provide(
304 Layer.mergeAll(
305 Lambda.EventSource,
306 LicenseManager.CreateLicenseHttp,
307 LicenseManager.CreateLicenseVersionHttp,
308 LicenseManager.DeleteLicenseHttp,
309 LicenseManager.CreateGrantHttp,
310 LicenseManager.CreateGrantVersionHttp,
311 LicenseManager.DeleteGrantHttp,
312 LicenseManager.CreateTokenHttp,
313 LicenseManager.DeleteTokenHttp,
314 LicenseManager.ListTokensHttp,
315 LicenseManager.GetLicenseHttp,
316 LicenseManager.ListLicensesHttp,
317 LicenseManager.GetAccessTokenHttp,
318 LicenseManager.CheckoutLicenseHttp,
319 LicenseManager.ExtendLicenseConsumptionHttp,
320 LicenseManager.CheckInLicenseHttp,
321 ),
322 ),
323 ),
324 );