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

main
ts 207 lines 7.21 KB
Raw
1 import * as Fly from "@alchemy.run/fly";
2 import * as Effect from "effect/Effect";
3 import { HttpServerRequest } from "effect/http/HttpServerRequest";
4 import * as HttpServerResponse from "effect/http/HttpServerResponse";
5 import * as Redacted from "effect/Redacted";
6 import { API_PORT, BoxKey, Marker, SignKey, Site } from "./bindings-shared.ts";
7 import Box from "./bindings-sprite.ts";
8
9 const bytesToB64 = (bytes: Uint8Array) => Buffer.from(bytes).toString("base64");
10 const b64ToBytes = (value: string) => Uint8Array.from(Buffer.from(value, "base64"));
11
12 /**
13 * HTTP Service that exercises Secret, SecretKey, and Sprite bindings.
14 * Cryptographic operations run inside the deployed Machine.
15 */
16 export default class BindingsApi extends Fly.Service<BindingsApi>()(
17 "BindingsApi",
18 {
19 app: Site,
20 main: import.meta.url,
21 region: "iad",
22 port: API_PORT,
23 guest: { cpuKind: "shared", cpus: 1, memoryMb: 256 },
24 },
25 Effect.gen(function* () {
26 const site = yield* Site;
27 const marker = yield* Marker;
28 const appName = yield* site.appName;
29 const secretName = yield* marker.name;
30 const get = yield* Fly.GetSecret(marker);
31 const list = yield* Fly.ListSecrets(Site);
32 const write = yield* Fly.WriteSecret(Marker);
33 const encrypt = yield* Fly.Encrypt(BoxKey);
34 const decrypt = yield* Fly.Decrypt(BoxKey);
35 const sign = yield* Fly.Sign(SignKey);
36 const verify = yield* Fly.Verify(SignKey);
37 const exec = yield* Fly.Exec(Box);
38
39 return {
40 fetch: Effect.gen(function* () {
41 const request = yield* HttpServerRequest;
42 const url = new URL(request.url, "http://service");
43 const path = url.pathname;
44
45 const fail = (error: unknown) => {
46 const tagged =
47 typeof error === "object" && error !== null && "_tag" in error
48 ? (error as { _tag: string; message?: unknown })
49 : undefined;
50 const message =
51 tagged !== undefined
52 ? `${tagged._tag}${tagged.message === undefined ? "" : `: ${String(tagged.message)}`}`
53 : error instanceof Error
54 ? `${error.name}: ${error.message}`
55 : String(error);
56 return HttpServerResponse.json({ error: message }, { status: 500 });
57 };
58
59 if (path === "/health") {
60 const resolvedApp = yield* appName;
61 const resolvedSecret = yield* secretName;
62 const token = process.env.FLY_API_TOKEN ?? "";
63 return yield* HttpServerResponse.json({
64 ok: true,
65 appName: resolvedApp,
66 secretName: resolvedSecret,
67 hasFlySecretMarkerEnv: process.env.FLY_SECRET_Marker !== undefined,
68 hasToken: token.length > 0,
69 tokenKind: token.startsWith("{")
70 ? "marker"
71 : token.startsWith("FlyV1")
72 ? "flyv1"
73 : token.length > 0
74 ? "other"
75 : "missing",
76 });
77 }
78
79 if (path === "/sprite" && request.method === "GET") {
80 return yield* exec({ cmd: ["echo", "sprite-runtime-binding"] }).pipe(
81 Effect.flatMap((result) =>
82 HttpServerResponse.json({
83 stdout: result.stdout,
84 exitCode: result.exit_code,
85 }),
86 ),
87 Effect.catch(fail),
88 );
89 }
90
91 if (path === "/secret" && request.method === "GET") {
92 const got = yield* get().pipe(
93 Effect.catch((error) =>
94 Effect.succeed({
95 name: undefined as string | undefined,
96 value: undefined as string | undefined,
97 error: error instanceof Error ? `${error.name}: ${error.message}` : String(error),
98 }),
99 ),
100 );
101 if ("error" in got) {
102 return yield* HttpServerResponse.json(got, { status: 500 });
103 }
104 return yield* HttpServerResponse.json({
105 ok: true,
106 name: got.name,
107 hasValue: typeof got.value === "string" && got.value.length > 0,
108 });
109 }
110
111 if (path === "/secrets" && request.method === "GET") {
112 return yield* list().pipe(
113 Effect.flatMap((listed) =>
114 HttpServerResponse.json({
115 names: (listed.secrets ?? []).flatMap((row) =>
116 row.name === undefined ? [] : [row.name],
117 ),
118 }),
119 ),
120 Effect.catch((error) => fail(error)),
121 );
122 }
123
124 if (path === "/secret" && request.method === "POST") {
125 const body = (yield* request.json) as {
126 name?: string;
127 value?: string;
128 };
129 const name = body.name ?? "BINDING_CREATED";
130 return yield* write.create(name, Redacted.make(body.value ?? "created")).pipe(
131 Effect.flatMap(() => HttpServerResponse.json({ ok: true, name })),
132 Effect.catch((error) => fail(error)),
133 );
134 }
135
136 if (path === "/encrypt" && request.method === "POST") {
137 const body = (yield* request.json) as { text?: string };
138 return yield* encrypt({
139 plaintext: new TextEncoder().encode(body.text ?? ""),
140 }).pipe(
141 Effect.flatMap((enc) =>
142 HttpServerResponse.json({
143 ciphertext: bytesToB64(enc.ciphertext),
144 }),
145 ),
146 Effect.catch((error) => fail(error)),
147 );
148 }
149
150 if (path === "/decrypt" && request.method === "POST") {
151 const body = (yield* request.json) as { ciphertext?: string };
152 return yield* decrypt({
153 ciphertext: b64ToBytes(body.ciphertext ?? ""),
154 }).pipe(
155 Effect.flatMap((dec) =>
156 HttpServerResponse.json({
157 text: new TextDecoder().decode(Redacted.value(dec.plaintext)),
158 }),
159 ),
160 Effect.catch((error) => fail(error)),
161 );
162 }
163
164 if (path === "/sign" && request.method === "POST") {
165 const body = (yield* request.json) as { text?: string };
166 return yield* sign({
167 plaintext: new TextEncoder().encode(body.text ?? ""),
168 }).pipe(
169 Effect.flatMap((signed) =>
170 HttpServerResponse.json({
171 signature: bytesToB64(signed.signature),
172 }),
173 ),
174 Effect.catch((error) => fail(error)),
175 );
176 }
177
178 if (path === "/verify" && request.method === "POST") {
179 const body = (yield* request.json) as {
180 text?: string;
181 signature?: string;
182 };
183 return yield* verify({
184 plaintext: new TextEncoder().encode(body.text ?? ""),
185 signature: b64ToBytes(body.signature ?? ""),
186 }).pipe(
187 Effect.flatMap((checked) => HttpServerResponse.json({ valid: checked.valid })),
188 Effect.catch((error) => fail(error)),
189 );
190 }
191
192 return yield* HttpServerResponse.json({ ok: false }, { status: 404 });
193 }),
194 };
195 }).pipe(
196 Effect.provide([
197 Fly.GetSecretHttp,
198 Fly.ListSecretsHttp,
199 Fly.WriteSecretHttp,
200 Fly.EncryptHttp,
201 Fly.DecryptHttp,
202 Fly.SignHttp,
203 Fly.VerifyHttp,
204 Fly.ExecHttp,
205 ]),
206 ),
207 ) {}