File size: 14,202 Bytes
488aedf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
import { describe, it, expect, afterEach } from "bun:test";
import net from "node:net";
import { Readable } from "node:stream";
import {
  handleControlRequestForTest,
  handleControlRequestWithHooksForTest,
  LogBuffer,
  type ControlState,
  type HandlerContext,
} from "./control.js";
import { BigmodelOAuthClient } from "../auth/oauth.js";

function makeStubRequest(opts: {
  method?: string;
  url?: string;
  body?: string;
  remoteAddress?: string;
}): import("node:http").IncomingMessage {
  const body = opts.body ?? "";
  const stream = Readable.from([Buffer.from(body, "utf-8")]) as unknown as import("node:http").IncomingMessage;
  stream.method = opts.method ?? "POST";
  stream.url = opts.url ?? "/control";
  stream.headers = { "content-type": "application/json", "content-length": String(Buffer.byteLength(body)) };
  stream.socket = { remoteAddress: opts.remoteAddress ?? "127.0.0.1" } as never;
  return stream;
}

async function post(body: unknown, state: ControlState, ctx?: HandlerContext) {
  const req = makeStubRequest({ body: JSON.stringify(body) });
  return ctx
    ? handleControlRequestWithHooksForTest(req, state, ctx)
    : handleControlRequestForTest(req, state);
}

describe("android control listener", () => {
  const baseState: ControlState = {
    provider: "bigmodel",
    plan: "coding-plan",
    proxyPort: 8080,
  };

  it("returns running status for {cmd:status} from loopback", async () => {
    const req = makeStubRequest({
      body: JSON.stringify({ cmd: "status" }),
      remoteAddress: "127.0.0.1",
    });
    const result = await handleControlRequestForTest(req, baseState);
    expect(result.status).toBe(200);
    expect(result.body.ok).toBe(true);
    if (result.body.ok && "state" in result.body) {
      expect(result.body.state).toBe("running");
      expect(result.body.provider).toBe("bigmodel");
      expect(result.body.plan).toBe("coding-plan");
      expect(result.body.proxyPort).toBe(8080);
    }
  });

  it("rejects non-loopback remoteAddress with HTTP 403", async () => {
    const req = makeStubRequest({
      body: JSON.stringify({ cmd: "status" }),
      remoteAddress: "192.168.1.5",
    });
    const result = await handleControlRequestForTest(req, baseState);
    expect(result.status).toBe(403);
    expect(result.body.ok).toBe(false);
    if (!result.body.ok) {
      expect(result.body.error).toContain("forbidden");
    }
  });

  it("rejects IPv6 non-loopback (::ffff:8.8.8.8)", async () => {
    const req = makeStubRequest({
      body: JSON.stringify({ cmd: "status" }),
      remoteAddress: "::ffff:8.8.8.8",
    });
    const result = await handleControlRequestForTest(req, baseState);
    expect(result.status).toBe(403);
  });

  it("accepts IPv6 loopback (::1)", async () => {
    const req = makeStubRequest({
      body: JSON.stringify({ cmd: "status" }),
      remoteAddress: "::1",
    });
    const result = await handleControlRequestForTest(req, baseState);
    expect(result.status).toBe(200);
  });

  it("returns 404 for non-/control paths", async () => {
    const req = makeStubRequest({
      url: "/v1/chat/completions",
      body: JSON.stringify({ cmd: "status" }),
    });
    const result = await handleControlRequestForTest(req, baseState);
    expect(result.status).toBe(404);
  });

  it("returns 400 for malformed JSON body", async () => {
    const req = makeStubRequest({ body: "not-json{" });
    const result = await handleControlRequestForTest(req, baseState);
    expect(result.status).toBe(400);
    expect(result.body.ok).toBe(false);
  });

  it("returns error for unknown cmd", async () => {
    const req = makeStubRequest({ body: JSON.stringify({ cmd: "bogus" }) });
    const result = await handleControlRequestForTest(req, baseState);
    expect(result.status).toBe(200);
    expect(result.body.ok).toBe(false);
    if (!result.body.ok) {
      expect(result.body.error).toContain("unknown_cmd");
    }
  });

  it("returns error for deliverOAuthCode without an active flow", async () => {
    const req = makeStubRequest({
      body: JSON.stringify({ cmd: "deliverOAuthCode", provider: "bigmodel", code: "x", state: "y" }),
    });
    const result = await handleControlRequestForTest(req, baseState);
    expect(result.status).toBe(200);
    expect(result.body.ok).toBe(false);
    if (!result.body.ok) {
      expect(result.body.error).toContain("no_matching_oauth_flow");
    }
  });
});

describe("android control listener — lifecycle commands", () => {
  const state: ControlState = {
    provider: "bigmodel",
    plan: "coding-plan",
    proxyPort: 0,
  };

  it("startProxy calls hook and updates state.proxyPort", async () => {
    const ctx: HandlerContext = {
      logBuffer: new LogBuffer(),
      onStartProxy: async () => ({ ok: true, port: 9999 }),
    };
    const result = await post({ cmd: "startProxy" }, state, ctx);
    expect(result.body.ok).toBe(true);
    if (result.body.ok && "port" in result.body) {
      expect(result.body.port).toBe(9999);
    }
    expect(state.proxyPort).toBe(9999);
  });

  it("startProxy surfaces hook errors", async () => {
    const ctx: HandlerContext = {
      logBuffer: new LogBuffer(),
      onStartProxy: async () => ({ ok: false, error: "not_logged_in" }),
    };
    const result = await post({ cmd: "startProxy" }, state, ctx);
    expect(result.body.ok).toBe(false);
    if (!result.body.ok) {
      expect(result.body.error).toBe("not_logged_in");
    }
  });

  it("startProxy returns error when hook missing", async () => {
    const result = await post({ cmd: "startProxy" }, state);
    expect(result.body.ok).toBe(false);
    if (!result.body.ok) {
      expect(result.body.error).toBe("proxy_lifecycle_unavailable");
    }
  });

  it("stopProxy resets state.proxyPort to 0", async () => {
    state.proxyPort = 8080;
    const ctx: HandlerContext = {
      logBuffer: new LogBuffer(),
      onStopProxy: async () => ({ ok: true }),
    };
    const result = await post({ cmd: "stopProxy" }, state, ctx);
    expect(result.body.ok).toBe(true);
    expect(state.proxyPort).toBe(0);
  });
});

describe("android control listener — setConfig", () => {
  it("updates provider and plan via hook and syncs state", async () => {
    const state: ControlState = { provider: "bigmodel", plan: "coding-plan", proxyPort: 0 };
    const ctx: HandlerContext = {
      logBuffer: new LogBuffer(),
      onSetConfig: async (changes) => ({
        ok: true,
        provider: changes.provider ?? state.provider,
        plan: changes.plan ?? state.plan,
      }),
    };
    const result = await post({ cmd: "setConfig", provider: "zai", plan: "start-plan" }, state, ctx);
    expect(result.body.ok).toBe(true);
    if (result.body.ok && "plan" in result.body) {
      expect(result.body.provider).toBe("zai");
      expect(result.body.plan).toBe("start-plan");
    }
    expect(state.provider).toBe("zai");
    expect(state.plan).toBe("start-plan");
  });

  it("returns config_update_unavailable when hook missing", async () => {
    const state: ControlState = { provider: "zai", plan: "coding-plan", proxyPort: 0 };
    const result = await post({ cmd: "setConfig", provider: "bigmodel" }, state);
    expect(result.body.ok).toBe(false);
    if (!result.body.ok) {
      expect(result.body.error).toBe("config_update_unavailable");
    }
  });
});

describe("android control listener — getLogs", () => {
  it("returns all lines when since=0", async () => {
    const logBuffer = new LogBuffer();
    logBuffer.push("[INFO] line one");
    logBuffer.push("[INFO] line two");
    const ctx: HandlerContext = { logBuffer };
    const result = await post({ cmd: "getLogs" }, { provider: "bigmodel", plan: "coding-plan", proxyPort: 0 }, ctx);
    expect(result.body.ok).toBe(true);
    if (result.body.ok && "lines" in result.body) {
      expect(result.body.lines).toEqual(["[INFO] line one", "[INFO] line two"]);
      expect(result.body.nextSince).toBe(2);
    }
  });

  it("returns only lines after `since`", async () => {
    const logBuffer = new LogBuffer();
    logBuffer.push("a");
    logBuffer.push("b");
    logBuffer.push("c");
    const ctx: HandlerContext = { logBuffer };
    const result = await post({ cmd: "getLogs", since: 1 }, { provider: "bigmodel", plan: "coding-plan", proxyPort: 0 }, ctx);
    expect(result.body.ok).toBe(true);
    if (result.body.ok && "lines" in result.body) {
      expect(result.body.lines).toEqual(["b", "c"]);
    }
  });

  it("returns empty when since is at cursor", async () => {
    const logBuffer = new LogBuffer();
    logBuffer.push("only");
    const ctx: HandlerContext = { logBuffer };
    const result = await post({ cmd: "getLogs", since: 1 }, { provider: "bigmodel", plan: "coding-plan", proxyPort: 0 }, ctx);
    expect(result.body.ok).toBe(true);
    if (result.body.ok && "lines" in result.body) {
      expect(result.body.lines).toEqual([]);
    }
  });
});

describe("android control listener — quota", () => {
  const state: ControlState = { provider: "bigmodel", plan: "coding-plan", proxyPort: 0 };
  const snapshot = {
    provider: "bigmodel",
    serverTime: 1759195200,
    jwt: null,
    balances: [],
    claimablePlans: [],
    codingPlan: { level: "max", limits: [{ type: "TIME_LIMIT", remaining: 3894 }] },
    errors: [],
  };

  it("returns the snapshot from the onQuota hook", async () => {
    const ctx: HandlerContext = {
      logBuffer: new LogBuffer(),
      onQuota: async () => snapshot,
    };
    const result = await post({ cmd: "quota" }, state, ctx);
    expect(result.status).toBe(200);
    expect(result.body.ok).toBe(true);
    if (result.body.ok && "quota" in result.body) {
      expect(result.body.quota).toEqual(snapshot);
      expect(result.body.quota.codingPlan?.level).toBe("max");
    }
  });

  it("returns quota_unavailable when the hook is missing", async () => {
    const result = await post({ cmd: "quota" }, state);
    expect(result.body.ok).toBe(false);
    if (!result.body.ok) {
      expect(result.body.error).toBe("quota_unavailable");
    }
  });

  it("surfaces hook failures verbatim (not-logged-in message)", async () => {
    const ctx: HandlerContext = {
      logBuffer: new LogBuffer(),
      onQuota: async () => {
        throw new Error("not logged in (run: zcode-proxy auth login)");
      },
    };
    const result = await post({ cmd: "quota" }, state, ctx);
    expect(result.body.ok).toBe(false);
    if (!result.body.ok) {
      expect(result.body.error).toContain("not logged in");
    }
  });
});

describe("android control startOAuth callback-port lifecycle", () => {
  /** Find a free loopback TCP port (bind port 0, read back, close). */
  async function freePort(): Promise<number> {
    
    return new Promise((resolve, reject) => {
      const srv = net.createServer();
      srv.on("error", reject);
      srv.listen(0, "127.0.0.1", () => {
        const { port } = srv.address() as net.AddressInfo;
        srv.close(() => resolve(port));
      });
    });
  }

  /** True when nothing is listening on `port` anymore. */
  async function portIsFree(port: number): Promise<boolean> {
    
    return new Promise((resolve) => {
      const srv = net.createServer();
      srv.once("error", () => resolve(false));
      srv.listen(port, "127.0.0.1", () => srv.close(() => resolve(true)));
    });
  }

  afterEach(() => {
    delete process.env.ZCODE_OAUTH_CALLBACK_PORT;
  });

  it("releases the callback port when the flow is rejected (abandoned login)", async () => {
    const port = await freePort();
    process.env.ZCODE_OAUTH_CALLBACK_PORT = String(port);
    const state: ControlState = { provider: "bigmodel", plan: "coding-plan", proxyPort: 0 };
    // Inject the classic (localhost-callback) client: the port-lifecycle
    // guarantee is a callback-flow property; the default bigmodel login is
    // the network-bound poll flow, which binds nothing.
    const ctx: HandlerContext = {
      logBuffer: new LogBuffer(),
      createLoginClient: () => new BigmodelOAuthClient(),
    };

    const started = await post({ cmd: "startOAuth", provider: "bigmodel" }, state, ctx);
    expect(started.body.ok).toBe(true);
    expect(state.activeOauth).toBeDefined();

    // Simulate the user abandoning the flow: a callback with a bad state
    // rejects every waitForCallback waiter.
    const resp = await fetch(`http://127.0.0.1:${port}/oauth/callback/bigmodel?state=bad&code=x`);
    expect(resp.status).toBe(400);
    await Bun.sleep(50);

    expect(state.activeOauth).toBeUndefined();
    expect(await portIsFree(port)).toBe(true);
  });

  it("a second startOAuth tears down the previous flow instead of hitting EADDRINUSE", async () => {
    const port = await freePort();
    process.env.ZCODE_OAUTH_CALLBACK_PORT = String(port);
    const state: ControlState = { provider: "bigmodel", plan: "coding-plan", proxyPort: 0 };
    const ctx: HandlerContext = {
      logBuffer: new LogBuffer(),
      createLoginClient: () => new BigmodelOAuthClient(),
    };

    const first = await post({ cmd: "startOAuth", provider: "bigmodel" }, state, ctx);
    expect(first.body.ok).toBe(true);

    // Previously this threw EADDRINUSE (500) because the first flow still
    // held the fixed callback port.
    const second = await post({ cmd: "startOAuth", provider: "bigmodel" }, state, ctx);
    expect(second.body.ok).toBe(true);

    // Clean up the flow started by the second command.
    state.activeOauth?.client.close().catch(() => {});
    state.activeOauth = undefined;
    await Bun.sleep(50);
  });
});

describe("LogBuffer", () => {
  it("evicts oldest lines past capacity", () => {
    const buf = new LogBuffer(3);
    buf.push("a");
    buf.push("b");
    buf.push("c");
    buf.push("d");
    expect([...buf.snapshot()]).toEqual(["b", "c", "d"]);
    expect(buf.cursor).toBe(4);
  });

  it("since() with stale cursor returns all surviving lines", () => {
    const buf = new LogBuffer(2);
    buf.push("a");
    buf.push("b");
    buf.push("c");
    // "a" was evicted; since=0 still returns only surviving lines.
    const result = buf.since(0);
    expect(result.lines).toEqual(["b", "c"]);
    expect(result.nextSince).toBe(3);
  });
});