@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 136 lines 5.49 KB
Raw
1 import * as crypto from "node:crypto";
2 import type { HttpEffect } from "alchemy/Http";
3 import { RPC_PATH_PREFIX, serveRpc } from "alchemy/Rpc";
4 import * as Effect from "effect/Effect";
5 import * as FileSystem from "effect/FileSystem";
6 import { HttpServerRequest } from "effect/http/HttpServerRequest";
7 import * as HttpServerResponse from "effect/http/HttpServerResponse";
8
9 /** Machine env var holding the Service's caller token. */
10 export const RPC_TOKEN_ENV = "ALCHEMY_FLY_RPC_TOKEN";
11 /** Machine env var holding the organization callers must belong to. */
12 export const RPC_ORG_ENV = "ALCHEMY_FLY_ORG";
13 /**
14 * Machine env var holding the published port Alchemy added for bindings.
15 * Requests on it must come from Fly's private network.
16 */
17 export const BINDING_PORT_ENV = "ALCHEMY_FLY_BINDING_PORT";
18 /** Request header carrying the caller token. */
19 export const RPC_TOKEN_HEADER = "x-alchemy-rpc-token";
20 /** Published port Alchemy adds when a Service has no plain-HTTP port. */
21 export const DEFAULT_BINDING_PORT = 7780;
22
23 /** Fly's signed origin header on Flycast requests, and its public key. */
24 const FLY_SRC_HEADER = "fly-src";
25 const FLY_SRC_SIGNATURE_HEADER = "fly-src-signature";
26 const FLY_SRC_PUBLIC_KEY = "/.fly/fly-src.pub";
27 /** DER prefix that wraps a raw 32-byte ed25519 key as SubjectPublicKeyInfo. */
28 const ED25519_SPKI_PREFIX = "302a300506032b6570032100";
29 /** Oldest accepted `Fly-Src` timestamp, in seconds. */
30 const MAX_FLY_SRC_AGE_SECONDS = 300;
31
32 const header = (headers: Record<string, string | undefined>, name: string): string =>
33 headers[name] ?? "";
34
35 const tokensEqual = (left: string, right: string): boolean => {
36 if (left.length !== right.length) return false;
37 let mismatch = 0;
38 for (let i = 0; i < left.length; i++) {
39 mismatch |= left.charCodeAt(i) ^ right.charCodeAt(i);
40 }
41 return mismatch === 0;
42 };
43
44 let publicKey: crypto.KeyObject | undefined;
45
46 /** Load Fly's `Fly-Src` verification key once per instance. */
47 const loadPublicKey = Effect.gen(function* () {
48 if (publicKey !== undefined) return publicKey;
49 const fs = yield* FileSystem.FileSystem;
50 const hex = yield* fs.readFileString(FLY_SRC_PUBLIC_KEY).pipe(
51 Effect.map((text) => text.trim()),
52 Effect.orElseSucceed(() => ""),
53 );
54 if (hex.length === 0) return undefined;
55 const key = yield* Effect.try(() =>
56 crypto.createPublicKey({
57 key: Buffer.from(`${ED25519_SPKI_PREFIX}${hex}`, "hex"),
58 format: "der",
59 type: "spki",
60 }),
61 ).pipe(Effect.orElseSucceed(() => undefined));
62 publicKey = key;
63 return key;
64 });
65
66 /**
67 * Whether the request carries a valid `Fly-Src` signature from Fly's proxy
68 * for a caller in `org`. Fly adds the header only to requests that arrive
69 * over its private network, so a public request can never pass.
70 */
71 export const verifyFlySrc = (headers: Record<string, string | undefined>, org: string) =>
72 Effect.gen(function* () {
73 const source = header(headers, FLY_SRC_HEADER);
74 const signature = header(headers, FLY_SRC_SIGNATURE_HEADER);
75 if (source.length === 0 || signature.length === 0 || org.length === 0) return false;
76 const key = yield* loadPublicKey;
77 if (key === undefined) return false;
78 const valid = yield* Effect.try(() =>
79 crypto.verify(null, Buffer.from(source), key, Buffer.from(signature, "base64")),
80 ).pipe(Effect.orElseSucceed(() => false));
81 if (!valid) return false;
82 const fields = Object.fromEntries(
83 source.split(";").map((pair) => {
84 const at = pair.indexOf("=");
85 return [pair.slice(0, at), pair.slice(at + 1)];
86 }),
87 );
88 const now = yield* Effect.sync(() => Date.now() / 1000);
89 const age = now - Number(fields.ts);
90 return fields.org === org && age >= -60 && age <= MAX_FLY_SRC_AGE_SECONDS;
91 });
92
93 const unauthorized = HttpServerResponse.text("Unauthorized", { status: 401 });
94
95 /**
96 * Serve a Service's RPC methods on `/__rpc__/*` and everything else with
97 * `fallback`. RPC calls must carry the Service's caller token and a valid
98 * `Fly-Src` signature from the Service's organization. Every request on the
99 * port Alchemy added for bindings must carry the `Fly-Src` signature, so
100 * that port never answers the public internet.
101 */
102 export const serveFlyRpc = <Req = never>(
103 shape: Record<string, unknown>,
104 fallback: HttpEffect<Req>,
105 ): HttpEffect<Req | FileSystem.FileSystem> =>
106 Effect.gen(function* () {
107 const request = yield* HttpServerRequest;
108 const headers = request.headers as Record<string, string | undefined>;
109 const isRpc = request.url.includes(RPC_PATH_PREFIX);
110 const env = yield* Effect.sync(() => ({
111 bindingPort: process.env[BINDING_PORT_ENV] ?? "",
112 org: process.env[RPC_ORG_ENV] ?? "",
113 token: process.env[RPC_TOKEN_ENV] ?? "",
114 }));
115 const bindingPort = env.bindingPort;
116 const onBindingPort =
117 bindingPort.length > 0 && header(headers, "fly-forwarded-port") === bindingPort;
118 if (!isRpc && !onBindingPort) return yield* fallback;
119 if (!(yield* verifyFlySrc(headers, env.org))) return unauthorized;
120 if (isRpc) {
121 const expected = env.token;
122 const provided = header(headers, RPC_TOKEN_HEADER);
123 if (expected.length === 0 || provided.length === 0 || !tokensEqual(provided, expected)) {
124 return unauthorized;
125 }
126 }
127 return yield* serveRpc(shape, fallback);
128 });
129
130 /** Methods on an impl shape that are served as RPC. */
131 export const rpcMethodsOf = (shape: Record<string, unknown> | undefined) =>
132 Object.fromEntries(
133 Object.entries(shape ?? {}).filter(
134 ([key, value]) => key !== "fetch" && key !== "run" && typeof value === "function",
135 ),
136 );