@certalis/agent-smith 0.1.6 → 0.1.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +13 -11
- package/dist/bin.js +91 -19
- package/dist/edge.js +150 -0
- package/dist/server.js +81 -9
- package/package.json +2 -1
package/README.md
CHANGED
|
@@ -85,24 +85,26 @@ startServer({
|
|
|
85
85
|
|
|
86
86
|
Codex works the same way with an OpenAI API key and an `openai-responses` pool.
|
|
87
87
|
|
|
88
|
-
## Connect an authorized
|
|
88
|
+
## Connect an authorized caller to a shared pool
|
|
89
89
|
|
|
90
|
-
The agents
|
|
91
|
-
|
|
92
|
-
|
|
90
|
+
The agents service and laptops can use one server-side pool through the
|
|
91
|
+
[authenticated HTTPS entrance](docs/https-edge.md) on managed HTTP hosts such as
|
|
92
|
+
Render. HTTPS needs no VPN or extra server: an existing web service forwards
|
|
93
|
+
only inference to the pool's private socket. Each device has its own revocable
|
|
94
|
+
key; provider tokens and the single database stay on the server.
|
|
93
95
|
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
distribute it team-wide until the B2/W7 tenancy work exists.
|
|
96
|
+
Device keys allow independent revocation and cannot read management data.
|
|
97
|
+
This does not add per-client fairness or budgets.
|
|
97
98
|
|
|
98
|
-
Copy [`
|
|
99
|
-
Agent-smith config. Put the
|
|
99
|
+
Copy [`https-client.json`](examples/config/https-client.json) into your private
|
|
100
|
+
Agent-smith config. Put the device key in the owner-only file named by
|
|
100
101
|
`proxy_key_file`, not in the JSON or a shell profile. `base_url` is the endpoint
|
|
101
102
|
visible to your machine, not a second pool. The key can spend from the pool, but
|
|
102
103
|
cannot administer it.
|
|
103
104
|
|
|
104
|
-
|
|
105
|
-
|
|
105
|
+
An SSH tunnel remains an option for development. Use
|
|
106
|
+
[`team-client.json`](examples/config/team-client.json) and forward its local port
|
|
107
|
+
to the private server:
|
|
106
108
|
|
|
107
109
|
```bash
|
|
108
110
|
ssh -N -L 18181:127.0.0.1:8080 agent-smith-pool
|
package/dist/bin.js
CHANGED
|
@@ -11670,8 +11670,71 @@ var init_src10 = __esm(() => {
|
|
|
11670
11670
|
init_websocket_proxy();
|
|
11671
11671
|
});
|
|
11672
11672
|
|
|
11673
|
+
// ../../packages/runtime-server/src/device-keys.ts
|
|
11674
|
+
import { createHash as createHash3, timingSafeEqual } from "crypto";
|
|
11675
|
+
import {
|
|
11676
|
+
closeSync,
|
|
11677
|
+
constants,
|
|
11678
|
+
fstatSync,
|
|
11679
|
+
openSync,
|
|
11680
|
+
readFileSync as readFileSync2
|
|
11681
|
+
} from "fs";
|
|
11682
|
+
import { isAbsolute as isAbsolute2 } from "path";
|
|
11683
|
+
function deviceKeyMatches(key, path) {
|
|
11684
|
+
if (!key || !path || !isAbsolute2(path) || !/^[\x21-\x7e]{32,512}$/.test(key))
|
|
11685
|
+
return false;
|
|
11686
|
+
let fd;
|
|
11687
|
+
try {
|
|
11688
|
+
fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
11689
|
+
const stat = fstatSync(fd);
|
|
11690
|
+
if (!stat.isFile() || stat.size > MAX_REGISTRY_BYTES || (stat.mode & 63) !== 0 || stat.uid !== process.getuid?.() && stat.uid !== 0)
|
|
11691
|
+
return false;
|
|
11692
|
+
const registry = JSON.parse(readFileSync2(fd, "utf8"));
|
|
11693
|
+
if (!registry || typeof registry !== "object" || Array.isArray(registry))
|
|
11694
|
+
return false;
|
|
11695
|
+
const entries = Object.entries(registry);
|
|
11696
|
+
if (entries.length > MAX_DEVICES || entries.some(([name, digest2]) => !/^[-a-zA-Z0-9_]{1,64}$/.test(name) || typeof digest2 !== "string" || !/^[a-f0-9]{64}$/.test(digest2)))
|
|
11697
|
+
return false;
|
|
11698
|
+
const digest = createHash3("sha256").update(key).digest();
|
|
11699
|
+
return entries.some(([, expected]) => timingSafeEqual(digest, Buffer.from(expected, "hex")));
|
|
11700
|
+
} catch {
|
|
11701
|
+
return false;
|
|
11702
|
+
} finally {
|
|
11703
|
+
if (fd !== undefined)
|
|
11704
|
+
closeSync(fd);
|
|
11705
|
+
}
|
|
11706
|
+
}
|
|
11707
|
+
var MAX_REGISTRY_BYTES, MAX_DEVICES = 128;
|
|
11708
|
+
var init_device_keys = __esm(() => {
|
|
11709
|
+
MAX_REGISTRY_BYTES = 32 * 1024;
|
|
11710
|
+
});
|
|
11711
|
+
|
|
11712
|
+
// ../../packages/runtime-server/src/inference-routes.ts
|
|
11713
|
+
function isInferenceRoute(method, path) {
|
|
11714
|
+
return INFERENCE_ROUTES.has(`${method} ${path}`);
|
|
11715
|
+
}
|
|
11716
|
+
function isDeviceRoute(method, path) {
|
|
11717
|
+
return method === "GET" && path === "/health" || isInferenceRoute(method, path);
|
|
11718
|
+
}
|
|
11719
|
+
var INFERENCE_ROUTES;
|
|
11720
|
+
var init_inference_routes = __esm(() => {
|
|
11721
|
+
INFERENCE_ROUTES = new Set([
|
|
11722
|
+
"POST /v1/claude-code/v1/messages",
|
|
11723
|
+
"POST /v1/claude-code/v1/messages/count_tokens",
|
|
11724
|
+
"POST /v1/pool/anthropic-messages/v1/messages",
|
|
11725
|
+
"POST /v1/pool/anthropic-messages/v1/messages/count_tokens",
|
|
11726
|
+
"POST /v1/codex/responses",
|
|
11727
|
+
"POST /v1/pool/openai-responses/responses"
|
|
11728
|
+
]);
|
|
11729
|
+
for (const route of [...INFERENCE_ROUTES]) {
|
|
11730
|
+
if (route.endsWith("/messages") || route.endsWith("/count_tokens")) {
|
|
11731
|
+
INFERENCE_ROUTES.add(`${route}?beta=true`);
|
|
11732
|
+
}
|
|
11733
|
+
}
|
|
11734
|
+
});
|
|
11735
|
+
|
|
11673
11736
|
// ../../packages/runtime-server/src/exposure.ts
|
|
11674
|
-
import { timingSafeEqual } from "crypto";
|
|
11737
|
+
import { timingSafeEqual as timingSafeEqual2 } from "crypto";
|
|
11675
11738
|
function requestAddress(server, req) {
|
|
11676
11739
|
if (!server || typeof server.requestIP !== "function") {
|
|
11677
11740
|
return { address: undefined, hasRequestIp: false };
|
|
@@ -11691,6 +11754,7 @@ function createExposureConfig(config) {
|
|
|
11691
11754
|
adminKey: configuredKey(process.env.CF_ADMIN_KEY),
|
|
11692
11755
|
bindHost: configuredHost ?? "127.0.0.1",
|
|
11693
11756
|
proxyKey: configuredKey(process.env.CF_PROXY_KEY),
|
|
11757
|
+
clientKeysFile: configuredKey(process.env.CF_CLIENT_KEYS_FILE),
|
|
11694
11758
|
trustLoopback: configuredTrustLoopback === undefined ? config.get("trust_loopback") !== false : configuredTrustLoopback !== "false"
|
|
11695
11759
|
};
|
|
11696
11760
|
}
|
|
@@ -11704,10 +11768,10 @@ function isLoopbackAddress(address) {
|
|
|
11704
11768
|
return address === "127.0.0.1" || address === "::1" || address === "::ffff:127.0.0.1";
|
|
11705
11769
|
}
|
|
11706
11770
|
function safeKeyEqual(candidate, expected) {
|
|
11707
|
-
if (!candidate || !expected || candidate
|
|
11771
|
+
if (!candidate || !expected || Buffer.byteLength(candidate) !== Buffer.byteLength(expected)) {
|
|
11708
11772
|
return false;
|
|
11709
11773
|
}
|
|
11710
|
-
return
|
|
11774
|
+
return timingSafeEqual2(Buffer.from(candidate), Buffer.from(expected));
|
|
11711
11775
|
}
|
|
11712
11776
|
function bearerToken(req) {
|
|
11713
11777
|
const authorization = req.headers.get("authorization");
|
|
@@ -11728,6 +11792,9 @@ function keyRole(req, url, config) {
|
|
|
11728
11792
|
if (isResponsesInferenceRoute(url.pathname) && safeKeyEqual(bearerToken(req), config.proxyKey)) {
|
|
11729
11793
|
return "proxy";
|
|
11730
11794
|
}
|
|
11795
|
+
if (deviceKeyMatches(apiKey, config.clientKeysFile) || isResponsesInferenceRoute(url.pathname) && deviceKeyMatches(bearerToken(req), config.clientKeysFile)) {
|
|
11796
|
+
return "device";
|
|
11797
|
+
}
|
|
11731
11798
|
return null;
|
|
11732
11799
|
}
|
|
11733
11800
|
function hostnameFromHostHeader(host) {
|
|
@@ -11766,6 +11833,9 @@ function exposureFailure(req, url, server, config) {
|
|
|
11766
11833
|
const remote = requestAddress(server, req);
|
|
11767
11834
|
const loopbackExempt = config.trustLoopback && (remote.hasRequestIp ? isLoopbackAddress(remote.address) : isLocalHostHeader(url.host, config.bindHost)) && !isForwardedRequest(req.headers);
|
|
11768
11835
|
const role = keyRole(req, url, config);
|
|
11836
|
+
if (role === "device" && !isDeviceRoute(req.method, url.pathname + url.search)) {
|
|
11837
|
+
return jsonError(403, "Device keys only allow health and inference");
|
|
11838
|
+
}
|
|
11769
11839
|
if (!role && !loopbackExempt) {
|
|
11770
11840
|
return jsonError(401, "A proxy key is required for this request");
|
|
11771
11841
|
}
|
|
@@ -11786,6 +11856,8 @@ function exposureFailure(req, url, server, config) {
|
|
|
11786
11856
|
}
|
|
11787
11857
|
var FORWARDED_HEADERS, LOOPBACK_HOSTS, MUTATING_METHODS;
|
|
11788
11858
|
var init_exposure = __esm(() => {
|
|
11859
|
+
init_device_keys();
|
|
11860
|
+
init_inference_routes();
|
|
11789
11861
|
FORWARDED_HEADERS = [
|
|
11790
11862
|
"forwarded",
|
|
11791
11863
|
"x-forwarded-for",
|
|
@@ -11939,10 +12011,10 @@ var init_bootstrap_runtime = __esm(() => {
|
|
|
11939
12011
|
});
|
|
11940
12012
|
|
|
11941
12013
|
// ../../packages/runtime-server/src/dashboard-assets.ts
|
|
11942
|
-
import { readFileSync as
|
|
11943
|
-
import { dirname as dirname3, isAbsolute as
|
|
12014
|
+
import { readFileSync as readFileSync3 } from "fs";
|
|
12015
|
+
import { dirname as dirname3, isAbsolute as isAbsolute3, join as join7, resolve as resolve2 } from "path";
|
|
11944
12016
|
function resolveConfiguredPath(configuredPath) {
|
|
11945
|
-
return
|
|
12017
|
+
return isAbsolute3(configuredPath) ? configuredPath : resolve2(process.cwd(), configuredPath);
|
|
11946
12018
|
}
|
|
11947
12019
|
function resolveDashboardManifestPath() {
|
|
11948
12020
|
const configuredManifestPath = process.env[DASHBOARD_MANIFEST_PATH_ENV]?.trim();
|
|
@@ -11964,7 +12036,7 @@ function loadDashboardAssets() {
|
|
|
11964
12036
|
}
|
|
11965
12037
|
const manifestPath = resolveDashboardManifestPath();
|
|
11966
12038
|
dashboardAssets = {
|
|
11967
|
-
manifest: JSON.parse(
|
|
12039
|
+
manifest: JSON.parse(readFileSync3(manifestPath, "utf8")),
|
|
11968
12040
|
distDir: dirname3(manifestPath)
|
|
11969
12041
|
};
|
|
11970
12042
|
return dashboardAssets;
|
|
@@ -12173,7 +12245,7 @@ var init_startup_maintenance = __esm(() => {
|
|
|
12173
12245
|
});
|
|
12174
12246
|
|
|
12175
12247
|
// ../../packages/runtime-server/src/index.ts
|
|
12176
|
-
import { isAbsolute as
|
|
12248
|
+
import { isAbsolute as isAbsolute4 } from "path";
|
|
12177
12249
|
var {serve } = globalThis.Bun;
|
|
12178
12250
|
function stopRetentionMaintenance() {
|
|
12179
12251
|
if (stopRetentionJob) {
|
|
@@ -12244,7 +12316,7 @@ async function stopServerRuntime() {
|
|
|
12244
12316
|
}
|
|
12245
12317
|
}
|
|
12246
12318
|
function startServer(options) {
|
|
12247
|
-
if (options?.additionalUnixSocket !== undefined && !
|
|
12319
|
+
if (options?.additionalUnixSocket !== undefined && !isAbsolute4(options.additionalUnixSocket)) {
|
|
12248
12320
|
throw new Error("Additional Unix socket must be an absolute path");
|
|
12249
12321
|
}
|
|
12250
12322
|
if (serverInstance) {
|
|
@@ -13957,10 +14029,10 @@ var init_args = () => {};
|
|
|
13957
14029
|
import {
|
|
13958
14030
|
accessSync,
|
|
13959
14031
|
chmodSync as chmodSync2,
|
|
13960
|
-
constants as
|
|
14032
|
+
constants as constants3,
|
|
13961
14033
|
existsSync as existsSync3,
|
|
13962
14034
|
mkdirSync as mkdirSync4,
|
|
13963
|
-
readFileSync as
|
|
14035
|
+
readFileSync as readFileSync4,
|
|
13964
14036
|
statSync as statSync3,
|
|
13965
14037
|
unlinkSync as unlinkSync2,
|
|
13966
14038
|
writeFileSync as writeFileSync2
|
|
@@ -13991,7 +14063,7 @@ function validateProxyKeyFile(proxyKeyFile) {
|
|
|
13991
14063
|
if ((metadata.mode & 63) !== 0) {
|
|
13992
14064
|
throw new Error("Agent-smith forwarding-key file must be owner-only");
|
|
13993
14065
|
}
|
|
13994
|
-
const key =
|
|
14066
|
+
const key = readFileSync4(resolvedPath, "utf8").trim();
|
|
13995
14067
|
if (!/^[\x21-\x7e]{1,512}$/.test(key)) {
|
|
13996
14068
|
throw new Error("Agent-smith forwarding-key file is invalid");
|
|
13997
14069
|
}
|
|
@@ -14077,7 +14149,7 @@ function getLocalRoutingPaths() {
|
|
|
14077
14149
|
}
|
|
14078
14150
|
function isExecutable(path) {
|
|
14079
14151
|
try {
|
|
14080
|
-
accessSync(path,
|
|
14152
|
+
accessSync(path, constants3.X_OK);
|
|
14081
14153
|
return true;
|
|
14082
14154
|
} catch {
|
|
14083
14155
|
return false;
|
|
@@ -14097,7 +14169,7 @@ function readSavedClientPaths(statePath) {
|
|
|
14097
14169
|
if (!existsSync3(statePath))
|
|
14098
14170
|
return null;
|
|
14099
14171
|
try {
|
|
14100
|
-
const saved = JSON.parse(
|
|
14172
|
+
const saved = JSON.parse(readFileSync4(statePath, "utf8"));
|
|
14101
14173
|
if (typeof saved === "object" && saved !== null) {
|
|
14102
14174
|
const { claudePath, codexPath } = saved;
|
|
14103
14175
|
const validClaude = typeof claudePath === "string" && isExecutable(claudePath) ? claudePath : undefined;
|
|
@@ -14115,7 +14187,7 @@ function getLocalRoutingStatus(paths2 = {}) {
|
|
|
14115
14187
|
const shellProfile = paths2.shellProfile ?? defaults.shellProfile;
|
|
14116
14188
|
let shellProfileHasRouting = false;
|
|
14117
14189
|
try {
|
|
14118
|
-
shellProfileHasRouting = existsSync3(shellProfile) &&
|
|
14190
|
+
shellProfileHasRouting = existsSync3(shellProfile) && readFileSync4(shellProfile, "utf8").includes(ROUTING_BEGIN);
|
|
14119
14191
|
} catch {}
|
|
14120
14192
|
return {
|
|
14121
14193
|
enabled: shellProfileHasRouting && (existsSync3(join8(binDir, "claude")) || existsSync3(join8(binDir, "codex"))),
|
|
@@ -14151,7 +14223,7 @@ async function enableLocalClientRouting(options) {
|
|
|
14151
14223
|
proxyKeyFile: options.proxyKeyFile,
|
|
14152
14224
|
providerPoolWires: options.providerPoolWires ?? Object.keys(new Config().getProviderPools())
|
|
14153
14225
|
});
|
|
14154
|
-
const existingProfile = existsSync3(shellProfile) ?
|
|
14226
|
+
const existingProfile = existsSync3(shellProfile) ? readFileSync4(shellProfile, "utf8") : "";
|
|
14155
14227
|
writeFileSync2(shellProfile, updateShellProfileForRouting(existingProfile, binDir), { encoding: "utf8", mode: 384 });
|
|
14156
14228
|
mkdirSync4(dirname4(statePath), { recursive: true, mode: 448 });
|
|
14157
14229
|
writeFileSync2(statePath, JSON.stringify({ claudePath, codexPath }), {
|
|
@@ -14167,7 +14239,7 @@ function disableLocalClientRouting(paths2 = {}) {
|
|
|
14167
14239
|
const shellProfile = paths2.shellProfile ?? defaults.shellProfile;
|
|
14168
14240
|
const statePath = paths2.statePath ?? defaults.statePath;
|
|
14169
14241
|
if (existsSync3(shellProfile)) {
|
|
14170
|
-
writeFileSync2(shellProfile, removeRoutingFromShellProfile(
|
|
14242
|
+
writeFileSync2(shellProfile, removeRoutingFromShellProfile(readFileSync4(shellProfile, "utf8")), { encoding: "utf8", mode: 384 });
|
|
14171
14243
|
}
|
|
14172
14244
|
for (const name of ["claude", "codex"]) {
|
|
14173
14245
|
const wrapper = join8(binDir, name);
|
|
@@ -14427,13 +14499,13 @@ __export(exports_theme, {
|
|
|
14427
14499
|
NAV_ITEMS: () => NAV_ITEMS,
|
|
14428
14500
|
C: () => C
|
|
14429
14501
|
});
|
|
14430
|
-
import { existsSync as existsSync4, mkdirSync as mkdirSync5, readFileSync as
|
|
14502
|
+
import { existsSync as existsSync4, mkdirSync as mkdirSync5, readFileSync as readFileSync5, writeFileSync as writeFileSync3 } from "fs";
|
|
14431
14503
|
import { homedir as homedir3 } from "os";
|
|
14432
14504
|
import { join as join9 } from "path";
|
|
14433
14505
|
function loadPersistedThemeId() {
|
|
14434
14506
|
try {
|
|
14435
14507
|
if (existsSync4(CONFIG_FILE)) {
|
|
14436
|
-
const data = JSON.parse(
|
|
14508
|
+
const data = JSON.parse(readFileSync5(CONFIG_FILE, "utf-8"));
|
|
14437
14509
|
if (data?.themeId && getThemeById(data.themeId)) {
|
|
14438
14510
|
return data.themeId;
|
|
14439
14511
|
}
|
package/dist/edge.js
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
// ../../packages/runtime-server/src/proxy-edge.ts
|
|
2
|
+
import {
|
|
3
|
+
request
|
|
4
|
+
} from "node:http";
|
|
5
|
+
import { isAbsolute } from "node:path";
|
|
6
|
+
|
|
7
|
+
// ../../packages/runtime-server/src/inference-routes.ts
|
|
8
|
+
var INFERENCE_ROUTES = new Set([
|
|
9
|
+
"POST /v1/claude-code/v1/messages",
|
|
10
|
+
"POST /v1/claude-code/v1/messages/count_tokens",
|
|
11
|
+
"POST /v1/pool/anthropic-messages/v1/messages",
|
|
12
|
+
"POST /v1/pool/anthropic-messages/v1/messages/count_tokens",
|
|
13
|
+
"POST /v1/codex/responses",
|
|
14
|
+
"POST /v1/pool/openai-responses/responses"
|
|
15
|
+
]);
|
|
16
|
+
for (const route of [...INFERENCE_ROUTES]) {
|
|
17
|
+
if (route.endsWith("/messages") || route.endsWith("/count_tokens")) {
|
|
18
|
+
INFERENCE_ROUTES.add(`${route}?beta=true`);
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
function isInferenceRoute(method, path) {
|
|
22
|
+
return INFERENCE_ROUTES.has(`${method} ${path}`);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
// ../../packages/runtime-server/src/proxy-edge.ts
|
|
26
|
+
var REQUEST_HEADERS = [
|
|
27
|
+
"content-type",
|
|
28
|
+
"accept",
|
|
29
|
+
"accept-encoding",
|
|
30
|
+
"anthropic-version",
|
|
31
|
+
"anthropic-beta",
|
|
32
|
+
"x-api-key",
|
|
33
|
+
"authorization",
|
|
34
|
+
"x-claude-code-session-id",
|
|
35
|
+
"session-id",
|
|
36
|
+
"openai-beta",
|
|
37
|
+
"x-client-request-id",
|
|
38
|
+
"user-agent"
|
|
39
|
+
];
|
|
40
|
+
var RESPONSE_HEADERS = [
|
|
41
|
+
"content-type",
|
|
42
|
+
"content-encoding",
|
|
43
|
+
"retry-after",
|
|
44
|
+
"request-id",
|
|
45
|
+
"x-request-id",
|
|
46
|
+
"anthropic-ratelimit-requests-limit",
|
|
47
|
+
"anthropic-ratelimit-requests-remaining",
|
|
48
|
+
"anthropic-ratelimit-requests-reset",
|
|
49
|
+
"anthropic-ratelimit-tokens-limit",
|
|
50
|
+
"anthropic-ratelimit-tokens-remaining",
|
|
51
|
+
"anthropic-ratelimit-tokens-reset"
|
|
52
|
+
];
|
|
53
|
+
function selectHeaders(headers, names) {
|
|
54
|
+
return Object.fromEntries(names.flatMap((name) => typeof headers[name] === "string" ? [[name, headers[name]]] : []));
|
|
55
|
+
}
|
|
56
|
+
function requestFailure(req, origin, maxBodyBytes) {
|
|
57
|
+
const health = req.method === "GET" && req.url === "/pool-health";
|
|
58
|
+
if (!health && !isInferenceRoute(req.method ?? "", req.url ?? ""))
|
|
59
|
+
return 404;
|
|
60
|
+
if (req.headers.host !== new URL(origin).host || req.headers.origin !== undefined && req.headers.origin !== origin || req.headers["sec-fetch-site"] !== undefined && !["none", "same-origin"].includes(String(req.headers["sec-fetch-site"])))
|
|
61
|
+
return 403;
|
|
62
|
+
if (req.headers.upgrade || req.headers.expect)
|
|
63
|
+
return 400;
|
|
64
|
+
if (req.headers["content-length"] !== undefined && (!/^\d+$/.test(req.headers["content-length"]) || Number(req.headers["content-length"]) > maxBodyBytes))
|
|
65
|
+
return 413;
|
|
66
|
+
if (!req.headers["x-api-key"] && !req.headers.authorization)
|
|
67
|
+
return 401;
|
|
68
|
+
return null;
|
|
69
|
+
}
|
|
70
|
+
function createProxyEdgeHandler({
|
|
71
|
+
origin,
|
|
72
|
+
socketPath,
|
|
73
|
+
maxBodyBytes = 64 * 1024 * 1024,
|
|
74
|
+
timeoutMs = 300000
|
|
75
|
+
}) {
|
|
76
|
+
const url = new URL(origin);
|
|
77
|
+
if (url.protocol !== "https:" || url.origin !== origin || !isAbsolute(socketPath) || !Number.isSafeInteger(maxBodyBytes) || maxBodyBytes < 1 || !Number.isSafeInteger(timeoutMs) || timeoutMs < 1) {
|
|
78
|
+
throw new Error("Proxy edge requires an exact HTTPS origin, an absolute socket path and positive limits");
|
|
79
|
+
}
|
|
80
|
+
return (req, res) => {
|
|
81
|
+
const finish = (status) => {
|
|
82
|
+
if (res.writableEnded || res.destroyed)
|
|
83
|
+
return;
|
|
84
|
+
if (res.headersSent) {
|
|
85
|
+
res.destroy();
|
|
86
|
+
return;
|
|
87
|
+
}
|
|
88
|
+
res.writeHead(status, {
|
|
89
|
+
"cache-control": "no-store",
|
|
90
|
+
connection: "close"
|
|
91
|
+
});
|
|
92
|
+
res.end();
|
|
93
|
+
};
|
|
94
|
+
const rejected = requestFailure(req, origin, maxBodyBytes);
|
|
95
|
+
if (rejected)
|
|
96
|
+
return finish(rejected);
|
|
97
|
+
const path = req.method === "GET" && req.url === "/pool-health" ? "/health" : req.url ?? "";
|
|
98
|
+
const headers = selectHeaders(req.headers, REQUEST_HEADERS);
|
|
99
|
+
headers.host = "localhost";
|
|
100
|
+
headers["x-forwarded-for"] = "proxy-edge";
|
|
101
|
+
let upstreamResponse;
|
|
102
|
+
const upstream = request({ socketPath, path, method: req.method, headers, agent: false }, (response) => {
|
|
103
|
+
upstreamResponse = response;
|
|
104
|
+
if (res.writableEnded || res.destroyed) {
|
|
105
|
+
response.destroy();
|
|
106
|
+
return;
|
|
107
|
+
}
|
|
108
|
+
const status = response.statusCode ?? 502;
|
|
109
|
+
if (status >= 300 && status < 400) {
|
|
110
|
+
response.destroy();
|
|
111
|
+
finish(502);
|
|
112
|
+
return;
|
|
113
|
+
}
|
|
114
|
+
res.writeHead(status, {
|
|
115
|
+
...selectHeaders(response.headers, RESPONSE_HEADERS),
|
|
116
|
+
"cache-control": "no-store",
|
|
117
|
+
"x-content-type-options": "nosniff"
|
|
118
|
+
});
|
|
119
|
+
response.once("error", () => res.destroy());
|
|
120
|
+
response.once("aborted", () => res.destroy());
|
|
121
|
+
response.pipe(res);
|
|
122
|
+
});
|
|
123
|
+
const timer = setTimeout(() => {
|
|
124
|
+
upstreamResponse?.destroy();
|
|
125
|
+
upstream.destroy();
|
|
126
|
+
finish(504);
|
|
127
|
+
}, timeoutMs);
|
|
128
|
+
res.once("close", () => {
|
|
129
|
+
clearTimeout(timer);
|
|
130
|
+
upstreamResponse?.destroy();
|
|
131
|
+
upstream.destroy();
|
|
132
|
+
});
|
|
133
|
+
upstream.once("error", () => finish(502));
|
|
134
|
+
req.once("aborted", () => upstream.destroy());
|
|
135
|
+
req.once("error", () => upstream.destroy());
|
|
136
|
+
let bytes = 0;
|
|
137
|
+
req.on("data", (chunk) => {
|
|
138
|
+
bytes += chunk.length;
|
|
139
|
+
if (bytes > maxBodyBytes) {
|
|
140
|
+
req.unpipe(upstream);
|
|
141
|
+
upstream.destroy();
|
|
142
|
+
finish(413);
|
|
143
|
+
}
|
|
144
|
+
});
|
|
145
|
+
req.pipe(upstream);
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
export {
|
|
149
|
+
createProxyEdgeHandler
|
|
150
|
+
};
|
package/dist/server.js
CHANGED
|
@@ -11669,8 +11669,71 @@ var init_src10 = __esm(() => {
|
|
|
11669
11669
|
init_websocket_proxy();
|
|
11670
11670
|
});
|
|
11671
11671
|
|
|
11672
|
+
// ../../packages/runtime-server/src/device-keys.ts
|
|
11673
|
+
import { createHash as createHash3, timingSafeEqual } from "crypto";
|
|
11674
|
+
import {
|
|
11675
|
+
closeSync,
|
|
11676
|
+
constants,
|
|
11677
|
+
fstatSync,
|
|
11678
|
+
openSync,
|
|
11679
|
+
readFileSync as readFileSync2
|
|
11680
|
+
} from "fs";
|
|
11681
|
+
import { isAbsolute as isAbsolute2 } from "path";
|
|
11682
|
+
function deviceKeyMatches(key, path) {
|
|
11683
|
+
if (!key || !path || !isAbsolute2(path) || !/^[\x21-\x7e]{32,512}$/.test(key))
|
|
11684
|
+
return false;
|
|
11685
|
+
let fd;
|
|
11686
|
+
try {
|
|
11687
|
+
fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
|
|
11688
|
+
const stat = fstatSync(fd);
|
|
11689
|
+
if (!stat.isFile() || stat.size > MAX_REGISTRY_BYTES || (stat.mode & 63) !== 0 || stat.uid !== process.getuid?.() && stat.uid !== 0)
|
|
11690
|
+
return false;
|
|
11691
|
+
const registry = JSON.parse(readFileSync2(fd, "utf8"));
|
|
11692
|
+
if (!registry || typeof registry !== "object" || Array.isArray(registry))
|
|
11693
|
+
return false;
|
|
11694
|
+
const entries = Object.entries(registry);
|
|
11695
|
+
if (entries.length > MAX_DEVICES || entries.some(([name, digest2]) => !/^[-a-zA-Z0-9_]{1,64}$/.test(name) || typeof digest2 !== "string" || !/^[a-f0-9]{64}$/.test(digest2)))
|
|
11696
|
+
return false;
|
|
11697
|
+
const digest = createHash3("sha256").update(key).digest();
|
|
11698
|
+
return entries.some(([, expected]) => timingSafeEqual(digest, Buffer.from(expected, "hex")));
|
|
11699
|
+
} catch {
|
|
11700
|
+
return false;
|
|
11701
|
+
} finally {
|
|
11702
|
+
if (fd !== undefined)
|
|
11703
|
+
closeSync(fd);
|
|
11704
|
+
}
|
|
11705
|
+
}
|
|
11706
|
+
var MAX_REGISTRY_BYTES, MAX_DEVICES = 128;
|
|
11707
|
+
var init_device_keys = __esm(() => {
|
|
11708
|
+
MAX_REGISTRY_BYTES = 32 * 1024;
|
|
11709
|
+
});
|
|
11710
|
+
|
|
11711
|
+
// ../../packages/runtime-server/src/inference-routes.ts
|
|
11712
|
+
function isInferenceRoute(method, path) {
|
|
11713
|
+
return INFERENCE_ROUTES.has(`${method} ${path}`);
|
|
11714
|
+
}
|
|
11715
|
+
function isDeviceRoute(method, path) {
|
|
11716
|
+
return method === "GET" && path === "/health" || isInferenceRoute(method, path);
|
|
11717
|
+
}
|
|
11718
|
+
var INFERENCE_ROUTES;
|
|
11719
|
+
var init_inference_routes = __esm(() => {
|
|
11720
|
+
INFERENCE_ROUTES = new Set([
|
|
11721
|
+
"POST /v1/claude-code/v1/messages",
|
|
11722
|
+
"POST /v1/claude-code/v1/messages/count_tokens",
|
|
11723
|
+
"POST /v1/pool/anthropic-messages/v1/messages",
|
|
11724
|
+
"POST /v1/pool/anthropic-messages/v1/messages/count_tokens",
|
|
11725
|
+
"POST /v1/codex/responses",
|
|
11726
|
+
"POST /v1/pool/openai-responses/responses"
|
|
11727
|
+
]);
|
|
11728
|
+
for (const route of [...INFERENCE_ROUTES]) {
|
|
11729
|
+
if (route.endsWith("/messages") || route.endsWith("/count_tokens")) {
|
|
11730
|
+
INFERENCE_ROUTES.add(`${route}?beta=true`);
|
|
11731
|
+
}
|
|
11732
|
+
}
|
|
11733
|
+
});
|
|
11734
|
+
|
|
11672
11735
|
// ../../packages/runtime-server/src/exposure.ts
|
|
11673
|
-
import { timingSafeEqual } from "crypto";
|
|
11736
|
+
import { timingSafeEqual as timingSafeEqual2 } from "crypto";
|
|
11674
11737
|
function requestAddress(server, req) {
|
|
11675
11738
|
if (!server || typeof server.requestIP !== "function") {
|
|
11676
11739
|
return { address: undefined, hasRequestIp: false };
|
|
@@ -11690,6 +11753,7 @@ function createExposureConfig(config) {
|
|
|
11690
11753
|
adminKey: configuredKey(process.env.CF_ADMIN_KEY),
|
|
11691
11754
|
bindHost: configuredHost ?? "127.0.0.1",
|
|
11692
11755
|
proxyKey: configuredKey(process.env.CF_PROXY_KEY),
|
|
11756
|
+
clientKeysFile: configuredKey(process.env.CF_CLIENT_KEYS_FILE),
|
|
11693
11757
|
trustLoopback: configuredTrustLoopback === undefined ? config.get("trust_loopback") !== false : configuredTrustLoopback !== "false"
|
|
11694
11758
|
};
|
|
11695
11759
|
}
|
|
@@ -11703,10 +11767,10 @@ function isLoopbackAddress(address) {
|
|
|
11703
11767
|
return address === "127.0.0.1" || address === "::1" || address === "::ffff:127.0.0.1";
|
|
11704
11768
|
}
|
|
11705
11769
|
function safeKeyEqual(candidate, expected) {
|
|
11706
|
-
if (!candidate || !expected || candidate
|
|
11770
|
+
if (!candidate || !expected || Buffer.byteLength(candidate) !== Buffer.byteLength(expected)) {
|
|
11707
11771
|
return false;
|
|
11708
11772
|
}
|
|
11709
|
-
return
|
|
11773
|
+
return timingSafeEqual2(Buffer.from(candidate), Buffer.from(expected));
|
|
11710
11774
|
}
|
|
11711
11775
|
function bearerToken(req) {
|
|
11712
11776
|
const authorization = req.headers.get("authorization");
|
|
@@ -11727,6 +11791,9 @@ function keyRole(req, url, config) {
|
|
|
11727
11791
|
if (isResponsesInferenceRoute(url.pathname) && safeKeyEqual(bearerToken(req), config.proxyKey)) {
|
|
11728
11792
|
return "proxy";
|
|
11729
11793
|
}
|
|
11794
|
+
if (deviceKeyMatches(apiKey, config.clientKeysFile) || isResponsesInferenceRoute(url.pathname) && deviceKeyMatches(bearerToken(req), config.clientKeysFile)) {
|
|
11795
|
+
return "device";
|
|
11796
|
+
}
|
|
11730
11797
|
return null;
|
|
11731
11798
|
}
|
|
11732
11799
|
function hostnameFromHostHeader(host) {
|
|
@@ -11765,6 +11832,9 @@ function exposureFailure(req, url, server, config) {
|
|
|
11765
11832
|
const remote = requestAddress(server, req);
|
|
11766
11833
|
const loopbackExempt = config.trustLoopback && (remote.hasRequestIp ? isLoopbackAddress(remote.address) : isLocalHostHeader(url.host, config.bindHost)) && !isForwardedRequest(req.headers);
|
|
11767
11834
|
const role = keyRole(req, url, config);
|
|
11835
|
+
if (role === "device" && !isDeviceRoute(req.method, url.pathname + url.search)) {
|
|
11836
|
+
return jsonError(403, "Device keys only allow health and inference");
|
|
11837
|
+
}
|
|
11768
11838
|
if (!role && !loopbackExempt) {
|
|
11769
11839
|
return jsonError(401, "A proxy key is required for this request");
|
|
11770
11840
|
}
|
|
@@ -11785,6 +11855,8 @@ function exposureFailure(req, url, server, config) {
|
|
|
11785
11855
|
}
|
|
11786
11856
|
var FORWARDED_HEADERS, LOOPBACK_HOSTS, MUTATING_METHODS;
|
|
11787
11857
|
var init_exposure = __esm(() => {
|
|
11858
|
+
init_device_keys();
|
|
11859
|
+
init_inference_routes();
|
|
11788
11860
|
FORWARDED_HEADERS = [
|
|
11789
11861
|
"forwarded",
|
|
11790
11862
|
"x-forwarded-for",
|
|
@@ -11938,10 +12010,10 @@ var init_bootstrap_runtime = __esm(() => {
|
|
|
11938
12010
|
});
|
|
11939
12011
|
|
|
11940
12012
|
// ../../packages/runtime-server/src/dashboard-assets.ts
|
|
11941
|
-
import { readFileSync as
|
|
11942
|
-
import { dirname as dirname3, isAbsolute as
|
|
12013
|
+
import { readFileSync as readFileSync3 } from "fs";
|
|
12014
|
+
import { dirname as dirname3, isAbsolute as isAbsolute3, join as join7, resolve as resolve2 } from "path";
|
|
11943
12015
|
function resolveConfiguredPath(configuredPath) {
|
|
11944
|
-
return
|
|
12016
|
+
return isAbsolute3(configuredPath) ? configuredPath : resolve2(process.cwd(), configuredPath);
|
|
11945
12017
|
}
|
|
11946
12018
|
function resolveDashboardManifestPath() {
|
|
11947
12019
|
const configuredManifestPath = process.env[DASHBOARD_MANIFEST_PATH_ENV]?.trim();
|
|
@@ -11963,7 +12035,7 @@ function loadDashboardAssets() {
|
|
|
11963
12035
|
}
|
|
11964
12036
|
const manifestPath = resolveDashboardManifestPath();
|
|
11965
12037
|
dashboardAssets = {
|
|
11966
|
-
manifest: JSON.parse(
|
|
12038
|
+
manifest: JSON.parse(readFileSync3(manifestPath, "utf8")),
|
|
11967
12039
|
distDir: dirname3(manifestPath)
|
|
11968
12040
|
};
|
|
11969
12041
|
return dashboardAssets;
|
|
@@ -12172,7 +12244,7 @@ var init_startup_maintenance = __esm(() => {
|
|
|
12172
12244
|
});
|
|
12173
12245
|
|
|
12174
12246
|
// ../../packages/runtime-server/src/index.ts
|
|
12175
|
-
import { isAbsolute as
|
|
12247
|
+
import { isAbsolute as isAbsolute4 } from "path";
|
|
12176
12248
|
var {serve } = globalThis.Bun;
|
|
12177
12249
|
function stopRetentionMaintenance() {
|
|
12178
12250
|
if (stopRetentionJob) {
|
|
@@ -12243,7 +12315,7 @@ async function stopServerRuntime() {
|
|
|
12243
12315
|
}
|
|
12244
12316
|
}
|
|
12245
12317
|
function startServer(options) {
|
|
12246
|
-
if (options?.additionalUnixSocket !== undefined && !
|
|
12318
|
+
if (options?.additionalUnixSocket !== undefined && !isAbsolute4(options.additionalUnixSocket)) {
|
|
12247
12319
|
throw new Error("Additional Unix socket must be an absolute path");
|
|
12248
12320
|
}
|
|
12249
12321
|
if (serverInstance) {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@certalis/agent-smith",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.8",
|
|
4
4
|
"description": "PROOF OF CONCEPT for ideation only: an experimental local proxy and provider pool for Claude Code and Codex",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "Certalis",
|
|
@@ -16,6 +16,7 @@
|
|
|
16
16
|
"agent-smith": "dist/bin.js"
|
|
17
17
|
},
|
|
18
18
|
"exports": {
|
|
19
|
+
"./edge": "./dist/edge.js",
|
|
19
20
|
"./server": "./dist/server.js",
|
|
20
21
|
"./package.json": "./package.json"
|
|
21
22
|
},
|