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

main
ts 308 lines 11.8 KB
Raw
1 import * as AWSBindings from "@alchemy.run/aws/AWSBindings";
2 import * as Lambda from "@alchemy.run/aws/Lambda";
3 import * as S3 from "@alchemy.run/aws/S3";
4 import * as Signer from "@alchemy.run/aws/Signer";
5 import * as Duration from "effect/Duration";
6 import * as Effect from "effect/Effect";
7 import { HttpServerRequest } from "effect/http/HttpServerRequest";
8 import * as HttpServerResponse from "effect/http/HttpServerResponse";
9 import * as Layer from "effect/Layer";
10 import * as Stream from "effect/Stream";
11 import path from "pathe";
12
13 const main = path.resolve(import.meta.dirname, "handler.ts");
14
15 /**
16 * A deterministic one-file zip (`index.js` with a no-op handler) — the code
17 * artifact the AWSLambda platform signs. Generated once and checked in.
18 */
19 const CODE_ZIP_BASE64 =
20 "UEsDBBQAAAAAAAAAIVyGZ4n3JAAAACQAAAAIAAAAaW5kZXguanNleHBvcnRzLmhhbmRsZXIgPSBhc3luYyAoKSA9PiAoe30pOwpQSwECFAMUAAAAAAAAACFchmeJ9yQAAAAkAAAACAAAAAAAAAAAAAAAgAEAAAAAaW5kZXguanNQSwUGAAAAAAEAAQA2AAAASgAAAAAA";
21 const CODE_ZIP = Uint8Array.from(Buffer.from(CODE_ZIP_BASE64, "base64"));
22
23 /** A syntactically valid Notary payload for `SignPayload`. */
24 const NOTARY_PAYLOAD = new TextEncoder().encode(
25 JSON.stringify({
26 targetArtifact: {
27 mediaType: "application/vnd.oci.image.manifest.v1+json",
28 digest: "sha256:73c803930ea3ba1e54bc25c2bdc53edd0284c62ed651fe7b00369da519a3c333",
29 size: 1024,
30 },
31 }),
32 );
33
34 const SOURCE_KEY = "code.zip";
35
36 export class SignerTestFunction extends Lambda.Function<Lambda.Function>()("SignerTestFunction") {}
37
38 export default SignerTestFunction.make(
39 {
40 main,
41 functionUrl: true,
42 timeout: Duration.seconds(60),
43 // The default 128 MB pins at the ceiling (~123 MB used) once the S3 +
44 // Signer clients are warm and 500s under load — give it headroom.
45 memorySize: 512,
46 },
47 Effect.gen(function* () {
48 const bind = yield* AWSBindings.Bind;
49 // The profile under test: AWS-managed Lambda code-signing material.
50 const profile = yield* Signer.SigningProfile("BindingsProfile", {
51 platformId: "AWSLambda-SHA384-ECDSA",
52 });
53 // A Notation profile for the synchronous SignPayload path.
54 const notationProfile = yield* Signer.SigningProfile("NotationProfile", {
55 platformId: "Notation-OCI-SHA384-ECDSA",
56 });
57
58 // StartSigningJob reads the versioned source object and writes the
59 // signed artifact with the CALLER's credentials — bind the S3 access.
60 const src = yield* S3.Bucket("SignerSrc", {
61 versioning: "Enabled",
62 forceDestroy: true,
63 });
64 const dst = yield* S3.Bucket("SignerDst", { forceDestroy: true });
65 // Outputs yield a DEFERRED effect — resolve again per invocation below.
66 const SrcName = yield* src.bucketName;
67 const DstName = yield* dst.bucketName;
68
69 // Event source: subscribe the host to signing-job status changes. The
70 // deploy proves the EventBridge rule + invoke permission wiring.
71 yield* Signer.consumeSigningJobEvents({}, (events) =>
72 Stream.runForEach(events, (event) =>
73 Effect.log(`signer job ${event.detail.job_id}: ${event.detail.status}`),
74 ),
75 );
76
77 const putObject = yield* S3.PutObject(src);
78 yield* S3.GetObject(src); // grants s3:GetObject(Version) for the signing job
79 yield* S3.PutObject(dst); // grants s3:PutObject on the destination
80
81 // Signer validates BUCKET-level access on both buckets when starting a
82 // job ("S3 bucket … not accessible") — grant the documented signing-
83 // caller set the object-level bindings above don't cover.
84 if (!globalThis.__ALCHEMY_RUNTIME__) {
85 yield* bind`SignerSourceDestinationBucketAccess`({
86 policyStatements: [
87 {
88 Effect: "Allow",
89 Action: [
90 "s3:GetBucketLocation",
91 "s3:GetBucketVersioning",
92 "s3:ListBucket",
93 "s3:ListBucketVersions",
94 ],
95 Resource: [src.bucketArn, dst.bucketArn],
96 },
97 ],
98 });
99 }
100
101 const startSigningJob = yield* Signer.StartSigningJob(profile);
102 const signPayload = yield* Signer.SignPayload(notationProfile);
103 const revokeSigningProfile = yield* Signer.RevokeSigningProfile(notationProfile);
104 const describeSigningJob = yield* Signer.DescribeSigningJob();
105 const listSigningJobs = yield* Signer.ListSigningJobs();
106 const revokeSignature = yield* Signer.RevokeSignature();
107 const getRevocationStatus = yield* Signer.GetRevocationStatus();
108 const getSigningPlatform = yield* Signer.GetSigningPlatform();
109 const listSigningPlatforms = yield* Signer.ListSigningPlatforms();
110
111 const bound = {
112 startSigningJob,
113 signPayload,
114 revokeSigningProfile,
115 describeSigningJob,
116 listSigningJobs,
117 revokeSignature,
118 getRevocationStatus,
119 getSigningPlatform,
120 listSigningPlatforms,
121 };
122
123 return {
124 fetch: Effect.gen(function* () {
125 const request = yield* HttpServerRequest;
126 const url = new URL(request.originalUrl);
127 const pathname = url.pathname;
128 const id = url.searchParams.get("id");
129
130 if (request.method === "GET" && pathname === "/bindings") {
131 return yield* HttpServerResponse.json({
132 bound: Object.keys(bound),
133 });
134 }
135
136 if (request.method === "GET" && pathname === "/platforms") {
137 // The catalog paginates with a small page size — walk it (bounded).
138 const ids: (string | undefined)[] = [];
139 let nextToken: string | undefined;
140 let pages = 0;
141 do {
142 const page = yield* listSigningPlatforms({
143 maxResults: 25,
144 nextToken,
145 });
146 ids.push(...(page.platforms ?? []).map((p) => p.platformId));
147 nextToken = page.nextToken;
148 pages += 1;
149 } while (nextToken !== undefined && pages < 10);
150 return yield* HttpServerResponse.json({ ids });
151 }
152
153 if (request.method === "GET" && pathname === "/platform") {
154 const platform = yield* getSigningPlatform({
155 platformId: id ?? "AWSLambda-SHA384-ECDSA",
156 });
157 return yield* HttpServerResponse.json({
158 platformId: platform.platformId,
159 revocationSupported: platform.revocationSupported ?? false,
160 });
161 }
162
163 // Upload the code zip (capturing the object version) and start a
164 // signing job over it — the profileName is injected by the binding.
165 if (request.method === "POST" && pathname === "/start") {
166 const uploaded = yield* putObject({
167 Key: SOURCE_KEY,
168 Body: CODE_ZIP,
169 ContentType: "application/zip",
170 });
171 if (uploaded.VersionId === undefined) {
172 // Bucket versioning still propagating — the test re-polls.
173 return yield* HttpServerResponse.json({
174 ok: false,
175 tag: "NoVersionId",
176 });
177 }
178 const started = yield* startSigningJob({
179 // Required idempotency token — a fresh UUID per request so each
180 // POST /start begins a new signing job.
181 clientRequestToken: yield* Effect.sync(() => crypto.randomUUID()),
182 source: {
183 s3: {
184 bucketName: yield* SrcName,
185 key: SOURCE_KEY,
186 version: uploaded.VersionId!,
187 },
188 },
189 destination: {
190 s3: { bucketName: yield* DstName, prefix: "signed/" },
191 },
192 }).pipe(Effect.result);
193 return yield* HttpServerResponse.json(
194 started._tag === "Success"
195 ? { ok: true, jobId: started.success.jobId }
196 : {
197 ok: false,
198 tag: started.failure._tag,
199 message: started.failure.message,
200 },
201 );
202 }
203
204 if (request.method === "GET" && pathname === "/jobs") {
205 const { jobs } = yield* listSigningJobs({ maxResults: 25 });
206 return yield* HttpServerResponse.json({
207 jobIds: (jobs ?? []).map((j) => j.jobId),
208 });
209 }
210
211 // Synchronous Notation signing — reports the typed rejection tag if
212 // Signer refuses the payload so the test can assert the round-trip.
213 if (request.method === "POST" && pathname === "/sign") {
214 const signed = yield* signPayload({
215 payload: NOTARY_PAYLOAD,
216 payloadFormat: "application/vnd.cncf.notary.payload.v1+json",
217 }).pipe(Effect.result);
218 return yield* HttpServerResponse.json(
219 signed._tag === "Success"
220 ? {
221 ok: true,
222 jobId: signed.success.jobId,
223 hasSignature: (signed.success.signature?.length ?? 0) > 0,
224 }
225 : { ok: false, tag: signed.failure._tag },
226 );
227 }
228
229 if (id === null) {
230 return yield* HttpServerResponse.json({ error: "missing id" }, { status: 400 });
231 }
232
233 if (request.method === "GET" && pathname === "/job") {
234 // A freshly-started job can 404 for a few seconds (eventual
235 // consistency) — report the typed tag so the test keeps polling.
236 const job = yield* describeSigningJob({ jobId: id }).pipe(Effect.result);
237 return yield* HttpServerResponse.json(
238 job._tag === "Success"
239 ? {
240 status: job.success.status,
241 signedKey: job.success.signedObject?.s3?.key,
242 }
243 : { status: "Pending", tag: job.failure._tag },
244 );
245 }
246
247 if (request.method === "POST" && pathname === "/revoke-job") {
248 const revoked = yield* revokeSignature({
249 jobId: id,
250 reason: "alchemy-test",
251 }).pipe(Effect.result);
252 return yield* HttpServerResponse.json(
253 revoked._tag === "Success"
254 ? { revoked: true }
255 : { revoked: false, tag: revoked.failure._tag },
256 );
257 }
258
259 // Revocation-status check for a completed job. ARNs are derived from
260 // the job's own metadata; empty certificateHashes may be rejected
261 // with a typed ValidationException — the route reports the tag so
262 // the test can assert the binding round-trips with IAM intact.
263 if (request.method === "GET" && pathname === "/revocation") {
264 const job = yield* describeSigningJob({ jobId: id });
265 const region = yield* Effect.sync(() => process.env.AWS_REGION);
266 const arnBase = `arn:aws:signer:${region}:${job.jobOwner}`;
267 const checked = yield* getRevocationStatus({
268 signatureTimestamp: job.completedAt ?? new Date(),
269 platformId: job.platformId!,
270 profileVersionArn: `${arnBase}:/signing-profiles/${job.profileName}/${job.profileVersion}`,
271 jobArn: `${arnBase}:/signing-jobs/${job.jobId}`,
272 certificateHashes: [],
273 }).pipe(Effect.result);
274 return yield* HttpServerResponse.json(
275 checked._tag === "Success"
276 ? {
277 ok: true,
278 revokedEntities: checked.success.revokedEntities ?? [],
279 }
280 : { ok: false, tag: checked.failure._tag },
281 );
282 }
283
284 return yield* HttpServerResponse.json(
285 { error: "Not found", method: request.method, pathname },
286 { status: 404 },
287 );
288 }).pipe(Effect.orDie),
289 };
290 }).pipe(
291 Effect.provide(
292 Layer.mergeAll(
293 Lambda.EventSource,
294 S3.PutObjectHttp,
295 S3.GetObjectHttp,
296 Signer.StartSigningJobHttp,
297 Signer.SignPayloadHttp,
298 Signer.RevokeSigningProfileHttp,
299 Signer.DescribeSigningJobHttp,
300 Signer.ListSigningJobsHttp,
301 Signer.RevokeSignatureHttp,
302 Signer.GetRevocationStatusHttp,
303 Signer.GetSigningPlatformHttp,
304 Signer.ListSigningPlatformsHttp,
305 ),
306 ),
307 ),
308 );