@byoky/bridge 0.3.0 → 0.4.1

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 byoky contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/dist/host.js CHANGED
@@ -3,18 +3,29 @@ import { createServer } from "http";
3
3
  var MAX_PENDING_REQUESTS = 100;
4
4
  var pendingRequests = /* @__PURE__ */ new Map();
5
5
  function handleProxyResponse(msg) {
6
- if (msg.type === "proxy_http_response") {
7
- const pending = pendingRequests.get(msg.requestId);
8
- if (pending) {
9
- pending.resolve(msg);
10
- pendingRequests.delete(msg.requestId);
11
- }
6
+ const pending = pendingRequests.get(msg.requestId);
7
+ if (!pending) return;
8
+ if (msg.type === "proxy_http_response_meta") {
9
+ const headers = { ...msg.headers };
10
+ delete headers["transfer-encoding"];
11
+ delete headers["content-encoding"];
12
+ delete headers["content-length"];
13
+ delete headers["set-cookie"];
14
+ delete headers["set-cookie2"];
15
+ pending.res.writeHead(msg.status, headers);
16
+ } else if (msg.type === "proxy_http_response_chunk") {
17
+ pending.res.write(msg.chunk);
18
+ } else if (msg.type === "proxy_http_response_done") {
19
+ pending.res.end();
20
+ clearTimeout(pending.timeout);
21
+ pendingRequests.delete(msg.requestId);
12
22
  } else if (msg.type === "proxy_http_error") {
13
- const pending = pendingRequests.get(msg.requestId);
14
- if (pending) {
15
- pending.reject(new Error(msg.error));
16
- pendingRequests.delete(msg.requestId);
23
+ if (!pending.res.headersSent) {
24
+ pending.res.writeHead(502, { "Content-Type": "application/json" });
17
25
  }
26
+ pending.res.end(JSON.stringify({ error: msg.error }));
27
+ clearTimeout(pending.timeout);
28
+ pendingRequests.delete(msg.requestId);
18
29
  }
19
30
  }
20
31
  function startProxyServer(config) {
@@ -37,6 +48,11 @@ function startProxyServer(config) {
37
48
  res.end(JSON.stringify({ status: "ok", providers }));
38
49
  return;
39
50
  }
51
+ if ((req.url?.length ?? 0) > MAX_URI_LENGTH) {
52
+ res.writeHead(414, { "Content-Type": "application/json" });
53
+ res.end(JSON.stringify({ error: "URI too long" }));
54
+ return;
55
+ }
40
56
  const match = req.url?.match(/^\/([^/]+)(\/.*)?$/);
41
57
  if (!match) {
42
58
  res.writeHead(404, { "Content-Type": "application/json" });
@@ -50,6 +66,12 @@ function startProxyServer(config) {
50
66
  res.end(JSON.stringify({ error: `Provider "${providerId}" not available in this session` }));
51
67
  return;
52
68
  }
69
+ const declaredLength = parseInt(req.headers["content-length"] || "0", 10);
70
+ if (declaredLength > MAX_BODY_SIZE) {
71
+ res.writeHead(413, { "Content-Type": "application/json" });
72
+ res.end(JSON.stringify({ error: "Payload too large" }));
73
+ return;
74
+ }
53
75
  const body = await readBody(req);
54
76
  const providerUrls = {
55
77
  anthropic: "https://api.anthropic.com",
@@ -76,9 +98,17 @@ function startProxyServer(config) {
76
98
  }
77
99
  const realUrl = `${baseUrl}${path}`;
78
100
  const requestId = `proxy-${crypto.randomUUID()}`;
101
+ const STRIP_HEADERS = /* @__PURE__ */ new Set([
102
+ "host",
103
+ "connection",
104
+ "cookie",
105
+ "authorization",
106
+ "proxy-authorization",
107
+ "proxy-connection"
108
+ ]);
79
109
  const headers = {};
80
110
  for (const [key, value] of Object.entries(req.headers)) {
81
- if (key === "host" || key === "connection") continue;
111
+ if (STRIP_HEADERS.has(key)) continue;
82
112
  if (typeof value === "string") headers[key] = value;
83
113
  }
84
114
  const proxyMsg = {
@@ -96,25 +126,17 @@ function startProxyServer(config) {
96
126
  res.end(JSON.stringify({ error: "Too many concurrent requests" }));
97
127
  return;
98
128
  }
99
- try {
100
- const response = await new Promise((resolve, reject) => {
101
- pendingRequests.set(requestId, { resolve, reject });
102
- setTimeout(() => {
103
- if (pendingRequests.has(requestId)) {
104
- pendingRequests.delete(requestId);
105
- reject(new Error("Request timed out"));
106
- }
107
- }, 12e4);
108
- sendToExtension(proxyMsg);
109
- });
110
- const responseHeaders = { ...response.headers };
111
- delete responseHeaders["transfer-encoding"];
112
- res.writeHead(response.status, responseHeaders);
113
- res.end(response.body);
114
- } catch (err) {
115
- res.writeHead(502, { "Content-Type": "application/json" });
116
- res.end(JSON.stringify({ error: err.message }));
117
- }
129
+ const timeout = setTimeout(() => {
130
+ if (pendingRequests.has(requestId)) {
131
+ pendingRequests.delete(requestId);
132
+ if (!res.headersSent) {
133
+ res.writeHead(504, { "Content-Type": "application/json" });
134
+ }
135
+ res.end(JSON.stringify({ error: "Request timed out" }));
136
+ }
137
+ }, 12e4);
138
+ pendingRequests.set(requestId, { res, timeout });
139
+ sendToExtension(proxyMsg);
118
140
  });
119
141
  server.listen(port, "127.0.0.1", () => {
120
142
  process.stderr.write(`Byoky proxy listening on http://127.0.0.1:${port}
@@ -123,6 +145,7 @@ function startProxyServer(config) {
123
145
  return server;
124
146
  }
125
147
  var MAX_BODY_SIZE = 10 * 1024 * 1024;
148
+ var MAX_URI_LENGTH = 8192;
126
149
  function readBody(req) {
127
150
  return new Promise((resolve, reject) => {
128
151
  let body = "";
@@ -206,12 +229,17 @@ async function handleMessage(msg) {
206
229
  if (!msg || typeof msg !== "object") return;
207
230
  const message = msg;
208
231
  if (message.type === "ping") {
209
- writeMessage({ type: "pong", version: "0.2.0" });
232
+ writeMessage({ type: "pong", version: "0.3.0" });
210
233
  return;
211
234
  }
212
235
  if (message.type === "proxy") {
213
236
  const req = msg;
214
- await handleSetupTokenProxy(req);
237
+ await handleStreamingFetch(req.requestId, req.url, req.method, req.headers, req.body, "bridge");
238
+ return;
239
+ }
240
+ if (message.type === "proxy_direct_fetch") {
241
+ const req = msg;
242
+ await handleStreamingFetch(req.requestId, req.url, req.method, req.headers, req.body, "proxy_http");
215
243
  return;
216
244
  }
217
245
  if (message.type === "start-proxy") {
@@ -219,36 +247,49 @@ async function handleMessage(msg) {
219
247
  handleStartProxy(req);
220
248
  return;
221
249
  }
222
- if (message.type === "proxy_http_response" || message.type === "proxy_http_error") {
250
+ if (msg && typeof msg === "object" && "type" in msg && (msg.type === "proxy_http_response_meta" || msg.type === "proxy_http_response_chunk" || msg.type === "proxy_http_response_done" || msg.type === "proxy_http_error")) {
223
251
  handleProxyResponse(msg);
224
252
  return;
225
253
  }
226
254
  }
227
- async function handleSetupTokenProxy(req) {
255
+ async function handleStreamingFetch(requestId, url, method, headers, body, mode) {
256
+ const send = (msg) => {
257
+ if (mode === "bridge") {
258
+ writeMessage(msg);
259
+ } else {
260
+ handleProxyResponse(msg);
261
+ }
262
+ };
263
+ const prefix = mode === "bridge" ? "proxy_response" : "proxy_http_response";
264
+ const errorType = mode === "bridge" ? "proxy_error" : "proxy_http_error";
265
+ const controller = new AbortController();
266
+ const fetchTimeout = setTimeout(() => controller.abort(), 12e4);
228
267
  try {
229
- const res = await fetch(req.url, {
230
- method: req.method,
231
- headers: req.headers,
232
- body: req.body || void 0
268
+ const res = await fetch(url, {
269
+ method,
270
+ headers,
271
+ body: body || void 0,
272
+ signal: controller.signal
233
273
  });
234
- const body = await res.text();
235
- const headers = {};
274
+ const resHeaders = {};
236
275
  res.headers.forEach((v, k) => {
237
- headers[k] = v;
238
- });
239
- writeMessage({
240
- type: "proxy_response",
241
- requestId: req.requestId,
242
- status: res.status,
243
- headers,
244
- body
276
+ resHeaders[k] = v;
245
277
  });
278
+ send({ type: `${prefix}_meta`, requestId, status: res.status, headers: resHeaders });
279
+ if (res.body) {
280
+ const reader = res.body.getReader();
281
+ const decoder = new TextDecoder();
282
+ for (; ; ) {
283
+ const { done, value } = await reader.read();
284
+ if (done) break;
285
+ send({ type: `${prefix}_chunk`, requestId, chunk: decoder.decode(value, { stream: true }) });
286
+ }
287
+ }
288
+ send({ type: `${prefix}_done`, requestId });
246
289
  } catch (e) {
247
- writeMessage({
248
- type: "proxy_error",
249
- requestId: req.requestId,
250
- error: e.message
251
- });
290
+ send({ type: errorType, requestId, error: "Fetch request failed" });
291
+ } finally {
292
+ clearTimeout(fetchTimeout);
252
293
  }
253
294
  }
254
295
  function handleStartProxy(req) {
@@ -267,7 +308,7 @@ function handleStartProxy(req) {
267
308
  writeMessage({
268
309
  type: "proxy_error",
269
310
  requestId: "start-proxy",
270
- error: e.message
311
+ error: "Failed to start proxy server"
271
312
  });
272
313
  }
273
314
  }
package/dist/installer.js CHANGED
@@ -2,11 +2,11 @@
2
2
  import { writeFileSync, mkdirSync, unlinkSync, existsSync, chmodSync } from "fs";
3
3
  import { dirname, resolve } from "path";
4
4
  import { homedir, platform } from "os";
5
- import { execSync } from "child_process";
5
+ import { execFileSync } from "child_process";
6
6
  var HOST_NAME = "com.byoky.bridge";
7
7
  function getHostPath() {
8
8
  try {
9
- return execSync("which byoky-bridge", { encoding: "utf-8" }).trim();
9
+ return execFileSync("/usr/bin/which", ["byoky-bridge"], { encoding: "utf-8", timeout: 5e3 }).trim();
10
10
  } catch {
11
11
  return resolve(dirname(new URL(import.meta.url).pathname), "../bin/byoky-bridge.js");
12
12
  }
@@ -14,16 +14,19 @@ function getHostPath() {
14
14
  function createNativeWrapper(hostPath, manifestDir) {
15
15
  const nodePath = process.execPath;
16
16
  const wrapperPath = resolve(manifestDir, "byoky-bridge-host");
17
- const userPath = process.env.PATH || "";
18
- const script = `#!/bin/bash
19
- export PATH="${userPath}"
20
- exec "${nodePath}" "${hostPath}" host "$@"
21
- `;
17
+ const nodeDir = dirname(nodePath);
18
+ const safePath = `${nodeDir}:/usr/local/bin:/usr/bin:/bin`;
19
+ const script = [
20
+ "#!/bin/bash",
21
+ `export PATH='${safePath}'`,
22
+ `exec '${nodePath.replace(/'/g, "'\\''")}' '${hostPath.replace(/'/g, "'\\''")}' host "$@"`,
23
+ ""
24
+ ].join("\n");
22
25
  writeFileSync(wrapperPath, script);
23
26
  chmodSync(wrapperPath, 493);
24
27
  return wrapperPath;
25
28
  }
26
- var DEFAULT_EXTENSION_ID = "ahhecmfcclkjdgjnmackoacldnmgmipl";
29
+ var DEFAULT_EXTENSION_ID = process.env.BYOKY_EXTENSION_ID || "ahhecmfcclkjdgjnmackoacldnmgmipl";
27
30
  function buildManifest(hostPath, browserType, extensionId) {
28
31
  const base = {
29
32
  name: HOST_NAME,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@byoky/bridge",
3
- "version": "0.3.0",
3
+ "version": "0.4.1",
4
4
  "description": "Native messaging bridge for Byoky — routes setup token requests through Claude Code CLI",
5
5
  "type": "module",
6
6
  "main": "dist/host.js",
@@ -11,10 +11,6 @@
11
11
  "dist",
12
12
  "bin"
13
13
  ],
14
- "scripts": {
15
- "build": "tsup",
16
- "dev": "tsup --watch"
17
- },
18
14
  "keywords": [
19
15
  "byoky",
20
16
  "claude",
@@ -31,5 +27,9 @@
31
27
  "@types/node": "25.5.0",
32
28
  "tsup": "^8.0.0",
33
29
  "typescript": "^5.5.0"
30
+ },
31
+ "scripts": {
32
+ "build": "tsup",
33
+ "dev": "tsup --watch"
34
34
  }
35
- }
35
+ }