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

main
ts 200 lines 8.45 KB
Raw
1 import { inflateRawSync } from "node:zlib";
2 import * as Bundle from "alchemy/Bundle/Bundle";
3 import * as TempRoot from "alchemy/Bundle/TempRoot";
4 import { moduleExtension } from "alchemy/Util/Node";
5 import { sha256 } from "alchemy/Util/sha256";
6 import { zipFiles, type ZipFile } from "alchemy/Util/zip";
7 import * as Data from "effect/Data";
8 import * as Effect from "effect/Effect";
9 import * as FileSystem from "effect/FileSystem";
10 import * as Path from "effect/Path";
11 import type { FunctionProps } from "./Function.ts";
12 import { nativeArtifactError } from "./NativeArtifact.ts";
13
14 export class FunctionArtifactError extends Data.TaggedError("FunctionArtifactError")<{
15 message: string;
16 }> {}
17
18 const safePath = (name: string) =>
19 name.length > 0 &&
20 !name.startsWith("/") &&
21 !name.includes("\\") &&
22 !name
23 .replace(/\/$/, "")
24 .split("/")
25 .some(
26 (part) =>
27 part.length === 0 ||
28 part === ".." ||
29 part === "." ||
30 part.startsWith(".env") ||
31 part === ".git" ||
32 part === ".alchemy",
33 ) &&
34 !/^[a-z]:/i.test(name);
35
36 /** Validate before extracting, including ZIP Unix mode bits and decompressed size. */
37 export const validateFunctionZip = (bytes: Uint8Array) =>
38 Effect.try({
39 try: () => {
40 if (bytes.byteLength > 100 * 1024 * 1024)
41 throw new Error("Archive exceeds 100 MiB safety limit");
42 const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
43 let end = bytes.length - 22;
44 for (; end >= Math.max(0, bytes.length - 65557); end--)
45 if (view.getUint32(end, true) === 0x06054b50) break;
46 if (end < 0 || view.getUint32(end, true) !== 0x06054b50)
47 throw new Error("Invalid ZIP directory");
48 const count = view.getUint16(end + 10, true);
49 let offset = view.getUint32(end + 16, true);
50 let size = 0;
51 const files: Record<string, Uint8Array> = Object.create(null);
52 for (let i = 0; i < count; i++) {
53 if (view.getUint32(offset, true) !== 0x02014b50) throw new Error("Invalid ZIP entry");
54 const length = view.getUint16(offset + 28, true);
55 const name = new TextDecoder().decode(bytes.subarray(offset + 46, offset + 46 + length));
56 const mode = view.getUint32(offset + 38, true) >>> 16;
57 if (!safePath(name) || name in files || (mode & 0xf000) === 0xa000)
58 throw new Error("Unsafe or duplicate archive entry");
59 const flags = view.getUint16(offset + 8, true);
60 const method = view.getUint16(offset + 10, true);
61 const compressedSize = view.getUint32(offset + 20, true);
62 const expandedSize = view.getUint32(offset + 24, true);
63 if ((flags & 1) !== 0 || (method !== 0 && method !== 8))
64 throw new Error("Unsupported ZIP encoding");
65 if (size + expandedSize > 250 * 1024 * 1024)
66 throw new Error("Expanded archive exceeds 250 MiB safety limit");
67 const local = view.getUint32(offset + 42, true);
68 if (
69 view.getUint32(local, true) !== 0x04034b50 ||
70 view.getUint16(local + 6, true) !== flags ||
71 view.getUint16(local + 8, true) !== method
72 )
73 throw new Error("ZIP local header mismatch");
74 const localCompressed = view.getUint32(local + 18, true);
75 const localExpanded = view.getUint32(local + 22, true);
76 if (
77 (((flags & 8) === 0 || localCompressed !== 0) && localCompressed !== compressedSize) ||
78 (((flags & 8) === 0 || localExpanded !== 0) && localExpanded !== expandedSize)
79 )
80 throw new Error("ZIP size mismatch");
81 const localNameLength = view.getUint16(local + 26, true);
82 if (
83 new TextDecoder().decode(bytes.subarray(local + 30, local + 30 + localNameLength)) !==
84 name
85 )
86 throw new Error("ZIP entry name mismatch");
87 const start = local + 30 + localNameLength + view.getUint16(local + 28, true);
88 if (start + compressedSize > view.getUint32(end + 16, true))
89 throw new Error("ZIP entry overlaps directory");
90 const compressed = bytes.subarray(start, start + compressedSize);
91 const content =
92 method === 0
93 ? compressed
94 : inflateRawSync(compressed, { maxOutputLength: expandedSize + 1 });
95 if (content.byteLength !== expandedSize) throw new Error("ZIP expanded size mismatch");
96 const nativeError = nativeArtifactError(name, content);
97 if (nativeError) throw new Error(nativeError);
98 size += content.byteLength;
99 files[name] = content;
100 offset +=
101 46 + length + view.getUint16(offset + 30, true) + view.getUint16(offset + 32, true);
102 }
103 if (!("index.mjs" in files)) throw new Error("Artifact requires root index.mjs");
104 if (offset !== view.getUint32(end + 16, true) + view.getUint32(end + 12, true))
105 throw new Error("ZIP directory mismatch");
106 return files;
107 },
108 catch: () =>
109 new FunctionArtifactError({
110 message:
111 "Invalid Function ZIP: require root index.mjs, safe relative paths, no symlinks/secrets, Linux ARM64 native files, and bounded size",
112 }),
113 });
114
115 export const buildFunctionArtifact = Effect.fn(function* (props: FunctionProps) {
116 const fs = yield* FileSystem.FileSystem;
117 const path = yield* Path.Path;
118 let files: ZipFile[] = [];
119 if (props.artifact?.zip !== undefined) {
120 const archive = yield* fs.readFile(props.artifact.zip);
121 yield* validateFunctionZip(archive);
122 return { archive, codeHash: yield* sha256(archive) };
123 }
124 if (props.artifact?.directory !== undefined) {
125 const root = yield* fs.realPath(props.artifact.directory);
126 const walk: (
127 relative: string,
128 ) => Effect.Effect<void, FunctionArtifactError | import("effect/PlatformError").PlatformError> =
129 Effect.fn(function* (relative) {
130 for (const entry of (yield* fs.readDirectory(path.join(root, relative))).sort()) {
131 const name = relative ? `${relative}/${entry}` : entry;
132 if (!safePath(name))
133 return yield* new FunctionArtifactError({
134 message: `Unsafe Function artifact entry: ${name}`,
135 });
136 const absolute = path.join(root, name);
137 if ((yield* fs.realPath(absolute)) !== absolute)
138 return yield* new FunctionArtifactError({
139 message: "Function artifacts must not contain symlinks",
140 });
141 const info = yield* fs.stat(absolute);
142 if (info.type === "Directory") yield* walk(name);
143 else if (info.type === "File")
144 files.push({ path: name, content: yield* fs.readFile(absolute) });
145 else
146 return yield* new FunctionArtifactError({
147 message: "Function artifacts support regular files only",
148 });
149 }
150 });
151 yield* walk("");
152 } else {
153 if (!props.main)
154 return yield* new FunctionArtifactError({
155 message: "Specify main or artifact",
156 });
157 const realMain = yield* TempRoot.resolveMainPath(props.main);
158 const virtual = yield* Bundle.virtualEntryPlugin;
159 const bridge = yield* Effect.sync(() =>
160 import.meta.resolve(`./FunctionBridge${moduleExtension(import.meta.url)}`),
161 );
162 const output = yield* Bundle.build(
163 {
164 ...props.bundle?.input,
165 input: realMain,
166 cwd: yield* TempRoot.findCwdForBundle(realMain),
167 platform: "node",
168 resolve: {
169 ...props.bundle?.input?.resolve,
170 conditionNames: [...Bundle.NODE_CONDITION_NAMES],
171 },
172 plugins: [
173 props.bundle?.input?.plugins,
174 props.isExternal
175 ? undefined
176 : virtual(
177 (entry) =>
178 `import { makeFunctionBridge } from ${JSON.stringify(bridge)};\nimport entrypoint from ${JSON.stringify(entry)};\nexport default makeFunctionBridge(entrypoint);`,
179 ),
180 ],
181 },
182 {
183 ...props.bundle?.output,
184 format: "esm",
185 entryFileNames: "index.mjs",
186 codeSplitting: false,
187 banner: `import { createRequire as __alchemyCreateRequire } from "node:module";\nconst require = __alchemyCreateRequire(import.meta.url);`,
188 },
189 props.bundle,
190 );
191 files = output.files.map(({ path, content }) => ({ path, content }));
192 }
193 if (!files.some((file) => file.path === "index.mjs"))
194 return yield* new FunctionArtifactError({
195 message: "Function artifact requires root index.mjs",
196 });
197 const archive = yield* zipFiles(files);
198 yield* validateFunctionZip(archive);
199 return { archive, codeHash: yield* sha256(archive) };
200 });