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

main
ts 219 lines 8.25 KB
Raw
1 import * as ACM from "@alchemy.run/aws/ACM";
2 import * as Lambda from "@alchemy.run/aws/Lambda";
3 import * as Duration from "effect/Duration";
4 import * as Effect from "effect/Effect";
5 import { HttpServerRequest } from "effect/http/HttpServerRequest";
6 import * as HttpServerResponse from "effect/http/HttpServerResponse";
7 import * as Layer from "effect/Layer";
8 import * as Redacted from "effect/Redacted";
9 import * as Result from "effect/Result";
10 import * as Stream from "effect/Stream";
11 import path from "pathe";
12 import { IMPORT_CERTIFICATE_PEM, IMPORT_PRIVATE_KEY_PEM } from "./fixtures/import-cert.ts";
13
14 const main = path.resolve(import.meta.dirname, "handler.ts");
15
16 // NOT under example.com: ACM deny-lists high-profile domains — a request for
17 // *.example.com fails within seconds with FAILED /
18 // ADDITIONAL_VERIFICATION_REQUIRED. An unregistered domain we never validate
19 // stays PENDING_VALIDATION for the life of the test.
20 export const FIXTURE_DOMAIN = "alchemy-acm-bindings.alchemy-effect-tests.com";
21
22 /**
23 * Probe helper: run the bound operation and report either the success
24 * projection or the typed error tag, so the test can assert that gated
25 * operations fail with a TYPED tag (never an untyped catch-all) on the
26 * perpetually-pending fixture certificate.
27 */
28 const tagOr = <A, E extends { _tag: string }, R>(
29 effect: Effect.Effect<A, E, R>,
30 onSuccess: (value: A) => Record<string, unknown>,
31 ) =>
32 Effect.result(effect).pipe(
33 Effect.map((result) =>
34 Result.isSuccess(result) ? onSuccess(result.success) : { errorTag: result.failure._tag },
35 ),
36 );
37
38 export class AcmTestFunction extends Lambda.Function<Lambda.Function>()("AcmTestFunction") {}
39
40 export default AcmTestFunction.make(
41 {
42 main,
43 functionUrl: true,
44 // Above the 3s AWS default: distilled auto-retries retryable typed
45 // errors (RequestInProgressException on /get is patched retryable, ~3s
46 // of bounded backoff), which must complete within the invocation so the
47 // typed tag is returned instead of a function-URL 502 timeout.
48 timeout: Duration.seconds(30),
49 },
50 Effect.gen(function* () {
51 // A DNS-validated certificate on a domain we never validate stays
52 // PENDING_VALIDATION forever: describe/list/search succeed against it,
53 // while issuance-gated operations (get/export/renew) fail with typed
54 // errors — both directions prove the binding + IAM wiring.
55 const certificate = yield* ACM.Certificate("BindingsCertificate", {
56 domainName: FIXTURE_DOMAIN,
57 subjectAlternativeNames: [FIXTURE_DOMAIN],
58 });
59
60 const describeCertificate = yield* ACM.DescribeCertificate(certificate);
61 const getCertificate = yield* ACM.GetCertificate(certificate);
62 const exportCertificate = yield* ACM.ExportCertificate(certificate);
63 const renewCertificate = yield* ACM.RenewCertificate(certificate);
64 const resendValidationEmail = yield* ACM.ResendValidationEmail(certificate);
65 const revokeCertificate = yield* ACM.RevokeCertificate(certificate);
66 const listCertificates = yield* ACM.ListCertificates();
67 const searchCertificates = yield* ACM.SearchCertificates();
68 const importCertificate = yield* ACM.ImportCertificate();
69
70 // Expiry event source: ACM emits "ACM Certificate Approaching
71 // Expiration" daily per certificate nearing expiry — untriggerable on
72 // demand, so the deploy itself (EventBridge rule + invoke permission)
73 // is what this fixture verifies.
74 yield* ACM.consumeExpiryEvents({}, (events) =>
75 Stream.runForEach(events, (event) =>
76 Effect.log(
77 `acm expiry event: ${event.detail.CommonName} expires in ${event.detail.DaysToExpiry} days`,
78 ),
79 ),
80 );
81
82 return {
83 fetch: Effect.gen(function* () {
84 const request = yield* HttpServerRequest;
85 const url = new URL(request.originalUrl);
86 const pathname = url.pathname;
87
88 if (request.method === "GET" && pathname === "/describe") {
89 const result = yield* describeCertificate();
90 return yield* HttpServerResponse.json({
91 arn: result.Certificate?.CertificateArn,
92 domainName: result.Certificate?.DomainName,
93 status: result.Certificate?.Status,
94 });
95 }
96
97 if (request.method === "GET" && pathname === "/get") {
98 return yield* HttpServerResponse.json(
99 yield* tagOr(getCertificate(), (result) => ({
100 certificate: result.Certificate,
101 })),
102 );
103 }
104
105 if (request.method === "GET" && pathname === "/list") {
106 const result = yield* listCertificates({
107 CertificateStatuses: ["PENDING_VALIDATION", "ISSUED"],
108 });
109 return yield* HttpServerResponse.json({
110 arns: (result.CertificateSummaryList ?? []).map((summary) => summary.CertificateArn),
111 });
112 }
113
114 if (request.method === "GET" && pathname === "/search") {
115 const described = yield* describeCertificate();
116 const arn = described.Certificate?.CertificateArn;
117 if (!arn) {
118 return HttpServerResponse.text("certificate has no ARN", {
119 status: 500,
120 });
121 }
122 const result = yield* searchCertificates({
123 FilterStatement: { Filter: { CertificateArn: arn } },
124 });
125 return yield* HttpServerResponse.json({
126 arns: (result.Results ?? []).map((r) => r.CertificateArn),
127 });
128 }
129
130 if (request.method === "POST" && pathname === "/export") {
131 const passphrase = yield* Effect.sync(() =>
132 new TextEncoder().encode("alchemy-acm-test-passphrase"),
133 );
134 return yield* HttpServerResponse.json(
135 yield* tagOr(
136 exportCertificate({ Passphrase: Redacted.make(passphrase) }),
137 (result) => ({
138 certificate: result.Certificate,
139 hasPrivateKey: result.PrivateKey !== undefined,
140 }),
141 ),
142 );
143 }
144
145 if (request.method === "POST" && pathname === "/renew") {
146 return yield* HttpServerResponse.json(
147 yield* tagOr(renewCertificate(), () => ({ ok: true })),
148 );
149 }
150
151 if (request.method === "POST" && pathname === "/resend-email") {
152 return yield* HttpServerResponse.json(
153 yield* tagOr(
154 resendValidationEmail({
155 Domain: FIXTURE_DOMAIN,
156 // The registered-domain suffix of the fixture domain — the
157 // ValidationDomain must be the domain itself or a superdomain.
158 ValidationDomain: FIXTURE_DOMAIN.split(".").slice(1).join("."),
159 }),
160 () => ({ ok: true }),
161 ),
162 );
163 }
164
165 if (request.method === "POST" && pathname === "/revoke") {
166 return yield* HttpServerResponse.json(
167 yield* tagOr(revokeCertificate({ RevocationReason: "UNSPECIFIED" }), () => ({
168 ok: true,
169 })),
170 );
171 }
172
173 if (request.method === "POST" && pathname === "/import") {
174 const body = (yield* request.json) as unknown as {
175 reimportArn?: string;
176 };
177 const payload = yield* Effect.sync(() => {
178 const encoder = new TextEncoder();
179 return {
180 Certificate: encoder.encode(IMPORT_CERTIFICATE_PEM),
181 PrivateKey: Redacted.make(encoder.encode(IMPORT_PRIVATE_KEY_PEM)),
182 };
183 });
184 const result = yield* importCertificate({
185 CertificateArn: body.reimportArn,
186 ...payload,
187 });
188 return yield* HttpServerResponse.json({
189 arn: result.CertificateArn,
190 });
191 }
192
193 return yield* HttpServerResponse.json(
194 {
195 error: "Not found",
196 method: request.method,
197 pathname,
198 },
199 { status: 404 },
200 );
201 }).pipe(Effect.orDie),
202 };
203 }).pipe(
204 Effect.provide(
205 Layer.mergeAll(
206 Lambda.EventSource,
207 ACM.DescribeCertificateHttp,
208 ACM.GetCertificateHttp,
209 ACM.ExportCertificateHttp,
210 ACM.RenewCertificateHttp,
211 ACM.ResendValidationEmailHttp,
212 ACM.RevokeCertificateHttp,
213 ACM.ListCertificatesHttp,
214 ACM.SearchCertificatesHttp,
215 ACM.ImportCertificateHttp,
216 ),
217 ),
218 ),
219 );