mirror of
https://github.com/JimLiu/baoyu-skills.git
synced 2026-07-12 05:51:44 +08:00
e0b861c148
The initial remote-api implementation (3b29f3c) relied on
`https.request({ agent: SocksProxyAgent })` to route token/upload/draft
calls through the SSH tunnel. Bun's `https.request` does not honor
Node's `http.Agent` contract, so the agent was silently bypassed and
requests still originated from the local IP — defeating the entire
IP-allowlist purpose. Two follow-on issues compounded it: tests read
the real `~/.baoyu-skills/.env` because Bun's `os.homedir()` ignores
test-time `process.env.HOME` mutations, and invalid config values were
silently coerced to defaults.
P1 — Bun-portable SOCKS routing:
- Drop `socks-proxy-agent` dependency. Add `socks` direct dep.
- New `wechat-socks-http.ts`: raw TCP via `SocksClient.createConnection`
+ `tls.connect({ socket, servername })` + hand-built HTTP/1.1 (status
line parser, case-insensitive headers, chunked & content-length body
framing). Works identically under Node and Bun because it avoids
`http.Agent` entirely.
- Rewrite `wechat-http.ts` as a fetch-based local client and expose
a `WechatClient = (url, init?) => Promise<WechatHttpResponse>`
functional abstraction.
- `wechat-api.ts`: replace `agent?: http.Agent` with
`client: WechatClient = wechatHttp` on the five HTTP-touching
functions; `withSshTunnel` now yields a `WechatClient`.
- New `wechat-socks-http.test.ts` stands up a real SOCKS5 server
stub + HTTP echo server and asserts `connectionCount === 1`,
proving bytes actually traverse the proxy under both runtimes.
P2 — `HOME` honored under Bun:
- `homeDir()` reads `process.env.HOME` / `USERPROFILE` first, falling
back to `os.homedir()`. `loadWechatExtendConfig` and `loadCredentials`
use it, restoring test isolation.
P3 — Strict config validation:
- Replace lenient `toOptional*` helpers with `parsePort` /
`parsePositiveInt` / `parseStrictHostKeyChecking` that throw with
the key name. `loadWechatExtendConfig` only catches file-read
errors so parse errors surface to the caller. Flip the corresponding
test cases.
Verification:
- `npm test`: 261/261 pass.
- `bun test` in `scripts/`: 39/39 pass.
Co-authored-by: Dame5211 <1079825614@qq.com>
139 lines
5.0 KiB
TypeScript
139 lines
5.0 KiB
TypeScript
import assert from "node:assert/strict";
|
|
import http from "node:http";
|
|
import test, { type TestContext } from "node:test";
|
|
|
|
import { buildMultipart, wechatHttp } from "./wechat-http.ts";
|
|
|
|
interface ReceivedRequest {
|
|
method: string;
|
|
url: string;
|
|
headers: http.IncomingHttpHeaders;
|
|
body: Buffer;
|
|
}
|
|
|
|
async function startEchoServer(t: TestContext): Promise<{ baseUrl: string; received: ReceivedRequest[] }> {
|
|
const received: ReceivedRequest[] = [];
|
|
const server = http.createServer((req, res) => {
|
|
const chunks: Buffer[] = [];
|
|
req.on("data", (chunk: Buffer) => chunks.push(chunk));
|
|
req.on("end", () => {
|
|
received.push({
|
|
method: req.method ?? "",
|
|
url: req.url ?? "",
|
|
headers: req.headers,
|
|
body: Buffer.concat(chunks),
|
|
});
|
|
res.statusCode = 200;
|
|
res.setHeader("Content-Type", "application/json");
|
|
res.end(JSON.stringify({ ok: true, echo: { url: req.url, method: req.method } }));
|
|
});
|
|
});
|
|
|
|
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
|
|
const address = server.address();
|
|
if (!address || typeof address === "string") {
|
|
throw new Error("Failed to start echo server");
|
|
}
|
|
const baseUrl = `http://127.0.0.1:${address.port}`;
|
|
|
|
t.after(async () => {
|
|
await new Promise<void>((resolve) => server.close(() => resolve()));
|
|
});
|
|
|
|
return { baseUrl, received };
|
|
}
|
|
|
|
test("wechatHttp performs a GET and passes through query string", async (t) => {
|
|
const { baseUrl, received } = await startEchoServer(t);
|
|
const res = await wechatHttp(`${baseUrl}/cgi-bin/token?grant_type=client_credential&appid=AID`);
|
|
assert.equal(res.status, 200);
|
|
const data = await res.json<{ ok: boolean; echo: { url: string; method: string } }>();
|
|
assert.equal(data.ok, true);
|
|
assert.equal(received.length, 1);
|
|
assert.equal(received[0]!.method, "GET");
|
|
assert.equal(received[0]!.url, "/cgi-bin/token?grant_type=client_credential&appid=AID");
|
|
assert.equal(received[0]!.body.length, 0);
|
|
});
|
|
|
|
test("wechatHttp POST sends JSON body with content-length header", async (t) => {
|
|
const { baseUrl, received } = await startEchoServer(t);
|
|
const body = JSON.stringify({ articles: [{ title: "hi" }] });
|
|
const res = await wechatHttp(`${baseUrl}/cgi-bin/draft/add?access_token=T`, {
|
|
method: "POST",
|
|
headers: { "Content-Type": "application/json" },
|
|
body,
|
|
});
|
|
assert.equal(res.status, 200);
|
|
assert.equal(received.length, 1);
|
|
assert.equal(received[0]!.method, "POST");
|
|
assert.equal(received[0]!.headers["content-type"], "application/json");
|
|
assert.equal(received[0]!.headers["content-length"], String(Buffer.byteLength(body)));
|
|
assert.equal(received[0]!.body.toString("utf-8"), body);
|
|
});
|
|
|
|
test("wechatHttp .text() returns the raw response body", async (t) => {
|
|
const { baseUrl } = await startEchoServer(t);
|
|
const res = await wechatHttp(`${baseUrl}/hello`);
|
|
const text = await res.text();
|
|
assert.match(text, /"ok":true/);
|
|
});
|
|
|
|
test("wechatHttp .buffer() returns a Buffer of the response body", async (t) => {
|
|
const { baseUrl } = await startEchoServer(t);
|
|
const res = await wechatHttp(`${baseUrl}/`);
|
|
const buf = await res.buffer();
|
|
assert.ok(Buffer.isBuffer(buf));
|
|
assert.ok(buf.length > 0);
|
|
});
|
|
|
|
test("buildMultipart produces a parsable multipart payload", () => {
|
|
const fileData = Buffer.from("ZZZ");
|
|
const { contentType, body } = buildMultipart([
|
|
{
|
|
name: "media",
|
|
filename: "image.png",
|
|
contentType: "image/png",
|
|
data: fileData,
|
|
},
|
|
]);
|
|
|
|
const boundaryMatch = contentType.match(/^multipart\/form-data; boundary=(.+)$/);
|
|
assert.ok(boundaryMatch, `expected boundary in Content-Type, got ${contentType}`);
|
|
const boundary = boundaryMatch![1]!;
|
|
const text = body.toString("binary");
|
|
assert.ok(text.startsWith(`--${boundary}\r\n`), "body must start with opening boundary");
|
|
assert.ok(
|
|
text.endsWith(`--${boundary}--\r\n`),
|
|
"body must end with closing boundary",
|
|
);
|
|
assert.match(
|
|
text,
|
|
/Content-Disposition: form-data; name="media"; filename="image\.png"\r\n/,
|
|
);
|
|
assert.match(text, /Content-Type: image\/png\r\n/);
|
|
// The raw file bytes must appear verbatim after a blank line.
|
|
assert.ok(
|
|
text.includes("\r\n\r\nZZZ\r\n"),
|
|
"body must contain the raw file bytes after the part headers",
|
|
);
|
|
});
|
|
|
|
test("wechatHttp accepts a multipart body produced by buildMultipart", async (t) => {
|
|
const { baseUrl, received } = await startEchoServer(t);
|
|
const fileData = Buffer.from("HELLO");
|
|
const multipart = buildMultipart([
|
|
{ name: "media", filename: "x.png", contentType: "image/png", data: fileData },
|
|
]);
|
|
const res = await wechatHttp(`${baseUrl}/cgi-bin/media/uploadimg?access_token=T`, {
|
|
method: "POST",
|
|
headers: { "Content-Type": multipart.contentType },
|
|
body: multipart.body,
|
|
});
|
|
assert.equal(res.status, 200);
|
|
assert.equal(received.length, 1);
|
|
assert.equal(received[0]!.method, "POST");
|
|
assert.match(received[0]!.headers["content-type"]!, /^multipart\/form-data; boundary=/);
|
|
assert.ok(received[0]!.body.includes(Buffer.from("HELLO")));
|
|
});
|
|
|