atomcode 0.3.0: AtomGit CodingPlan provider plugin (LILEOO, #716)
Adds packages/atomcode (@magpie-community/opencode-atomcode-auth 0.3.0), an AtomGit CodingPlan provider: browser OAuth and AtomCode CLI sign-in (~/.atomcode/auth.toml), signed requests to AtomGit's own gateway, per-account models and quota, daily claim, a loopback-only diagnostics page, and OpenCode 1.x/2.x entries. Registry and README entries added. By LILEOO.
Reviewed at c57b099fff4689c0198c1c6414f04b27614b4092. The last blocking point (an inline TOML comment on a known line went into the uid and was written back) is fixed: values end at an unquoted #, quoted/escaped/literal strings keep their #, and a rewritten line keeps its comment.
Run on a separate test machine (Bun 1.4.2, sandbox HOME):
- PR head merged onto origin/main 24da52b8: bun scripts/check.mjs exit 0 (atomcode ok); whole-repo bun test 6103 pass, 0 fail. origin/main alone: 5942 pass, 0 fail.
- packages/atomcode at the head: bun test 161 pass; node --test test/*.test.mjs 161 pass.
- The new auth-file test against 55ff272's auth-file.mjs: red (1 fail), green at the head.
- Probe: the review's file (id = "123456" # c) parses to uid 123456 and renders back as id = "123456" # c; also #c with no space, CRLF with a tab before #, "1#2", and a literal-string id all round-trip to the same uid. At 55ff272 each gave a uid with the comment in it.
Not tried: a real AtomGit account. A [user] header with a trailing comment is refused ("no user id"), not corrupted; the CLI never writes one. First npm version needs an owner publish; until then magpie installs it from the dist branch.
This commit is contained in:
@@ -0,0 +1,241 @@
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdtemp, readFile, stat, symlink, writeFile, chmod } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
|
||||
import {
|
||||
parseAuthFile,
|
||||
renderAuthFile,
|
||||
readAuthFile,
|
||||
resolveAuthFilePath,
|
||||
writeAuthFile,
|
||||
} from "../auth-file.mjs";
|
||||
|
||||
const SAMPLE = `# AtomCode credentials
|
||||
access_token = "access-old"
|
||||
refresh_token = "refresh-old"
|
||||
token_type = "Bearer"
|
||||
created_at = 1700000000
|
||||
expires_in = 3600
|
||||
future_field = "keep-me"
|
||||
|
||||
[user]
|
||||
id = "123456"
|
||||
username = "alice"
|
||||
name = "Alice"
|
||||
email = "alice@example.com"
|
||||
avatar_url = "https://example.com/a.png"
|
||||
`;
|
||||
|
||||
test("parseAuthFile maps the CLI file without exposing raw text", () => {
|
||||
const auth = parseAuthFile(SAMPLE);
|
||||
assert.equal(auth.access, "access-old");
|
||||
assert.equal(auth.refresh, "refresh-old");
|
||||
assert.equal(auth.uid, "123456");
|
||||
assert.equal(auth.accountId, "alice@example.com");
|
||||
assert.equal(auth.name, "Alice");
|
||||
assert.equal(auth.expires, 1700003600_000);
|
||||
});
|
||||
|
||||
test("resolveAuthFilePath expands only the current user's home and absolute paths", () => {
|
||||
const env = { HOME: "/home/alice" };
|
||||
assert.equal(
|
||||
resolveAuthFilePath(undefined, env),
|
||||
"/home/alice/.atomcode/auth.toml",
|
||||
);
|
||||
assert.equal(resolveAuthFilePath("", env), "/home/alice/.atomcode/auth.toml");
|
||||
assert.equal(resolveAuthFilePath("~", env), "/home/alice");
|
||||
assert.equal(
|
||||
resolveAuthFilePath("~/.atomcode/custom.toml", env),
|
||||
"/home/alice/.atomcode/custom.toml",
|
||||
);
|
||||
assert.equal(
|
||||
resolveAuthFilePath("/var/lib/atomcode/auth.toml", env),
|
||||
"/var/lib/atomcode/auth.toml",
|
||||
);
|
||||
});
|
||||
|
||||
test("resolveAuthFilePath rejects relative, NUL, oversized and other-user paths", () => {
|
||||
const env = { HOME: "/home/alice" };
|
||||
assert.throws(() => resolveAuthFilePath("auth.toml", env), /absolute/);
|
||||
assert.throws(() => resolveAuthFilePath("~bob/auth.toml", env), /another-user/);
|
||||
assert.throws(() => resolveAuthFilePath("~/a\0b", env), /NUL/);
|
||||
assert.throws(() => resolveAuthFilePath(`~/${"a".repeat(4096)}`, env), /too long/);
|
||||
});
|
||||
|
||||
test("renderAuthFile updates only credential fields and preserves unknown content", () => {
|
||||
const rendered = renderAuthFile(SAMPLE, {
|
||||
access: "access-new",
|
||||
refresh: "refresh-new",
|
||||
expiresIn: 7200,
|
||||
createdAt: 1800000000,
|
||||
user: { id: "123456", name: "Alice 2" },
|
||||
});
|
||||
assert.match(rendered, /# AtomCode credentials/);
|
||||
assert.match(rendered, /future_field = "keep-me"/);
|
||||
assert.match(rendered, /token_type = "Bearer"/);
|
||||
assert.match(rendered, /access_token = "access-new"/);
|
||||
assert.match(rendered, /refresh_token = "refresh-new"/);
|
||||
assert.match(rendered, /created_at = 1800000000/);
|
||||
assert.match(rendered, /expires_in = 7200/);
|
||||
assert.match(rendered, /id = "123456"/);
|
||||
assert.doesNotMatch(rendered, /id = 123456/);
|
||||
assert.match(rendered, /name = "Alice 2"/);
|
||||
assert.match(rendered, /email = "alice@example.com"/);
|
||||
});
|
||||
|
||||
test("auth.toml parser preserves scalar types and appends id as a string", () => {
|
||||
const text = `access_token = "access\\q"
|
||||
refresh_token = 'refresh-single'
|
||||
created_at = "1700000000"
|
||||
expires_in = "3600"
|
||||
[user]
|
||||
id = "42"
|
||||
`;
|
||||
const auth = parseAuthFile(text);
|
||||
assert.equal(auth.access, "access\\q");
|
||||
assert.equal(auth.refresh, "refresh-single");
|
||||
assert.equal(auth.uid, "42");
|
||||
|
||||
const rendered = renderAuthFile('access_token = "old"\n', {
|
||||
access: "new",
|
||||
refresh: "refresh",
|
||||
createdAt: 1700000000,
|
||||
expiresIn: 3600,
|
||||
user: { id: 42, name: "Alice" },
|
||||
});
|
||||
assert.match(rendered, /\[user\]/);
|
||||
assert.match(rendered, /id = "42"/);
|
||||
assert.match(rendered, /name = "Alice"/);
|
||||
|
||||
const quoted = renderAuthFile(text, {
|
||||
access: "next",
|
||||
refresh: "next-refresh",
|
||||
createdAt: 1800000000,
|
||||
expiresIn: 7200,
|
||||
user: { id: "42" },
|
||||
});
|
||||
assert.match(quoted, /created_at = "1800000000"/);
|
||||
assert.match(quoted, /expires_in = "7200"/);
|
||||
assert.match(quoted, /id = "42"/);
|
||||
});
|
||||
|
||||
test("auth.toml renderer preserves a legacy integer id when rewriting it", () => {
|
||||
const rendered = renderAuthFile(
|
||||
'access_token = "old"\ncreated_at = 1700000000\nexpires_in = 3600\n[user]\nid = 42\n',
|
||||
{
|
||||
access: "new",
|
||||
createdAt: 1800000000,
|
||||
expiresIn: 7200,
|
||||
user: { id: "99" },
|
||||
},
|
||||
);
|
||||
assert.match(rendered, /\[user\]\nid = 99/);
|
||||
assert.doesNotMatch(rendered, /\[user\]\nid = "99"/);
|
||||
});
|
||||
|
||||
test("auth.toml renderer preserves float and boolean value types", () => {
|
||||
const rendered = renderAuthFile(
|
||||
'access_token = "old"\ncreated_at = 1.0\nexpires_in = true\n[user]\nid = "42"\n',
|
||||
{
|
||||
access: "new",
|
||||
createdAt: 1800000000,
|
||||
expiresIn: false,
|
||||
user: { id: "42" },
|
||||
},
|
||||
);
|
||||
assert.match(rendered, /created_at = 1800000000\.0/);
|
||||
assert.match(rendered, /expires_in = false/);
|
||||
});
|
||||
|
||||
test("inline comments survive parsing and credential renewal", async () => {
|
||||
const dir = await mkdtemp(join(tmpdir(), "atomcode-comments-"));
|
||||
const file = join(dir, "auth.toml");
|
||||
const input = `access_token = "old#token" # access
|
||||
refresh_token = 'old#refresh' # refresh
|
||||
created_at = 1.0 # time
|
||||
expires_in = true # duration
|
||||
[user]
|
||||
id = "123456" # c
|
||||
username = "a\\\"#b" # username
|
||||
name = 'Alice # Smith' # name
|
||||
`;
|
||||
await writeFile(file, input, { mode: 0o600 });
|
||||
const before = await readAuthFile(file);
|
||||
assert.equal(before.access, "old#token");
|
||||
assert.equal(before.refresh, "old#refresh");
|
||||
assert.equal(before.uid, "123456");
|
||||
assert.equal(before.accountId, 'a"#b');
|
||||
assert.equal(before.name, "Alice # Smith");
|
||||
|
||||
await writeAuthFile(file, { access: "new#token", refresh: "new#refresh", createdAt: 2, expiresIn: 60 });
|
||||
const text = await readFile(file, "utf8");
|
||||
assert.match(text, /^access_token = "new#token" # access$/m);
|
||||
assert.match(text, /^refresh_token = "new#refresh" # refresh$/m);
|
||||
assert.match(text, /^created_at = 2\.0 # time$/m);
|
||||
assert.match(text, /^expires_in = false # duration$/m);
|
||||
assert.match(text, /^id = "123456" # c$/m);
|
||||
assert.equal((await readAuthFile(file)).uid, "123456");
|
||||
const integer = renderAuthFile('access_token = "old"\n[user]\nid = 42 # integer\n', {
|
||||
access: "new", user: { id: "99" },
|
||||
});
|
||||
assert.match(integer, /^id = 99 # integer$/m);
|
||||
assert.equal(parseAuthFile('access_token = "a\\\\" # comment\n[user]\nid = "42"\n').access, "a\\");
|
||||
});
|
||||
|
||||
test("readAuthFile and writeAuthFile use private permissions and atomic replacement", async () => {
|
||||
const dir = await mkdtemp(join(tmpdir(), "atomcode-auth-"));
|
||||
const file = join(dir, "auth.toml");
|
||||
await writeFile(file, SAMPLE, { mode: 0o600 });
|
||||
|
||||
const before = await readAuthFile(file);
|
||||
assert.equal(before.refresh, "refresh-old");
|
||||
|
||||
await writeAuthFile(file, {
|
||||
access: "access-new",
|
||||
refresh: "refresh-new",
|
||||
expiresIn: 60,
|
||||
user: { id: "123456", username: "alice" },
|
||||
});
|
||||
const text = await readFile(file, "utf8");
|
||||
assert.match(text, /access_token = "access-new"/);
|
||||
assert.match(text, /token_type = "Bearer"/);
|
||||
assert.match(text, /id = "123456"/);
|
||||
assert.doesNotMatch(text, /id = 123456/);
|
||||
assert.match(text, /future_field = "keep-me"/);
|
||||
if (process.platform !== "win32") {
|
||||
assert.equal((await stat(file)).mode & 0o777, 0o600);
|
||||
}
|
||||
});
|
||||
|
||||
test("readAuthFile rejects symlinks, loose permissions, and account-less files", async () => {
|
||||
const dir = await mkdtemp(join(tmpdir(), "atomcode-auth-"));
|
||||
const real = join(dir, "real.toml");
|
||||
const link = join(dir, "link.toml");
|
||||
await writeFile(real, SAMPLE, { mode: 0o600 });
|
||||
await symlink(real, link);
|
||||
await assert.rejects(() => readAuthFile(link), /regular file|symlink/i);
|
||||
|
||||
if (process.platform !== "win32") {
|
||||
await chmod(real, 0o644);
|
||||
await assert.rejects(() => readAuthFile(real), /0600|permissions/i);
|
||||
await chmod(real, 0o600);
|
||||
}
|
||||
|
||||
const noUser = join(dir, "no-user.toml");
|
||||
await writeFile(noUser, 'access_token = "a"\n', { mode: 0o600 });
|
||||
await assert.rejects(() => readAuthFile(noUser), /user id/i);
|
||||
await assert.rejects(
|
||||
() => readAuthFile(join(dir, "missing.toml")),
|
||||
/not signed in/i,
|
||||
);
|
||||
await assert.rejects(
|
||||
() =>
|
||||
writeAuthFile(real, {
|
||||
access: "",
|
||||
expiresIn: 0,
|
||||
}),
|
||||
/incomplete.*credentials/i,
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,202 @@
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
|
||||
import { claimCodingPlan, fetchModels, planNeedsClaim, planOf, planTier } from "../codingplan.mjs";
|
||||
|
||||
test("planTier:Max/Pro 判定与 Lite 兜底(含「体验版」写法)", () => {
|
||||
assert.equal(planTier("CodingPlan Max"), "Max");
|
||||
assert.equal(planTier("MAX 旗舰"), "Max");
|
||||
assert.equal(planTier("CodingPlan Pro"), "Pro");
|
||||
assert.equal(planTier("CodingPlan Lite-体验版"), "Lite");
|
||||
assert.equal(planTier("Lite-beta"), "Lite");
|
||||
assert.equal(planTier(undefined), "Lite");
|
||||
});
|
||||
|
||||
test("planOf:codingplan_free 优先,plan 兜底,缺失/非对象 → null", () => {
|
||||
assert.deepEqual(planOf({ codingplan_free: { plan_name: "x" } }), { plan_name: "x" });
|
||||
assert.deepEqual(planOf({ plan: { plan_name: "y" } }), { plan_name: "y" });
|
||||
assert.equal(planOf({}), null);
|
||||
assert.equal(planOf(null), null);
|
||||
});
|
||||
|
||||
/** 按调用次序回放响应的小工具,多余调用复用最后一个响应。 */
|
||||
function sequenceFetch(responses) {
|
||||
const seen = [];
|
||||
const fetchImpl = async (url, init = {}) => {
|
||||
seen.push({ url, init });
|
||||
const next = responses[Math.min(seen.length - 1, responses.length - 1)];
|
||||
return new Response(next.body, { status: next.status ?? 200 });
|
||||
};
|
||||
return { fetchImpl, seen };
|
||||
}
|
||||
|
||||
test("claim:第一档 success 即停,请求形状正确", async () => {
|
||||
const { fetchImpl, seen } = sequenceFetch([
|
||||
{ body: JSON.stringify({ success: true, message: "ok", plan_name: "CodingPlan Max", plan_type: "Max" }) },
|
||||
]);
|
||||
const r = await claimCodingPlan("https://gitcode.example", "tok", { fetchImpl, clientVersion: "5.2.3" });
|
||||
assert.equal(r.claimed, true);
|
||||
assert.equal(r.duplicate, false);
|
||||
assert.equal(r.tier, "Max");
|
||||
assert.equal(r.planName, "CodingPlan Max");
|
||||
assert.equal(r.attempts.length, 1);
|
||||
assert.equal(seen.length, 1);
|
||||
assert.equal(new URL(seen[0].url).pathname, "/coding-plan/claim-v2");
|
||||
assert.equal(JSON.parse(seen[0].init.body).plan_type, "Max");
|
||||
assert.equal(seen[0].init.headers.authorization, "Bearer tok");
|
||||
assert.equal(seen[0].init.headers["user-agent"], "atomcode/5.2.3");
|
||||
});
|
||||
|
||||
test("claim:Max/Pro 失败 → Lite duplicate 停;错误响应体的 message 不丢", async () => {
|
||||
const { fetchImpl } = sequenceFetch([
|
||||
{ status: 400, body: JSON.stringify({ success: false, message: "无可用计划" }) },
|
||||
{ status: 400, body: JSON.stringify({ success: false, message: "无可用计划" }) },
|
||||
{ body: JSON.stringify({ success: false, duplicate: true, plan_type: "Lite" }) },
|
||||
]);
|
||||
const r = await claimCodingPlan("https://gitcode.example", "tok", { fetchImpl, clientVersion: "5.2.3" });
|
||||
assert.equal(r.claimed, true);
|
||||
assert.equal(r.duplicate, true);
|
||||
assert.equal(r.tier, "Lite");
|
||||
assert.equal(r.attempts.length, 3);
|
||||
assert.equal(r.attempts[0].message, "无可用计划");
|
||||
});
|
||||
|
||||
test("claim:三档都失败 → claimed false 且不抛出", async () => {
|
||||
const { fetchImpl } = sequenceFetch([
|
||||
{ status: 400, body: JSON.stringify({ success: false, message: "a" }) },
|
||||
{ status: 400, body: JSON.stringify({ success: false, message: "b" }) },
|
||||
{ status: 400, body: JSON.stringify({ success: false, message: "c" }) },
|
||||
]);
|
||||
const r = await claimCodingPlan("https://gitcode.example", "tok", { fetchImpl, clientVersion: "5.2.3" });
|
||||
assert.equal(r.claimed, false);
|
||||
assert.equal(r.duplicate, false);
|
||||
assert.equal(r.message, "c");
|
||||
});
|
||||
|
||||
test("planNeedsClaim:缺失/空名 → 需要领取", () => {
|
||||
assert.equal(planNeedsClaim({}), true);
|
||||
assert.equal(planNeedsClaim(null), true);
|
||||
assert.equal(planNeedsClaim({ codingplan_free: { plan_name: " " } }), true);
|
||||
});
|
||||
|
||||
test("planNeedsClaim:套餐有效(无日期字段也保守放行)→ false", () => {
|
||||
assert.equal(planNeedsClaim({ codingplan_free: { plan_name: "CodingPlan Lite-体验版" } }), false);
|
||||
assert.equal(
|
||||
planNeedsClaim({ codingplan_free: { plan_name: "Lite", remaining_days: 4, expires_at: "2099-01-01" } }),
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
test("planNeedsClaim:remaining_days ≤ 0 → 需要重领", () => {
|
||||
assert.equal(
|
||||
planNeedsClaim({ codingplan_free: { plan_name: "Lite", remaining_days: 0, expires_at: "2099-01-01" } }),
|
||||
true,
|
||||
);
|
||||
assert.equal(
|
||||
planNeedsClaim({ codingplan_free: { plan_name: "Lite", remaining_days: -2, expires_at: "2099-01-01" } }),
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
test("planNeedsClaim:remaining_days 为 null/undefined 时视为未知,不误触发", () => {
|
||||
for (const remaining_days of [null, undefined]) {
|
||||
assert.equal(
|
||||
planNeedsClaim({
|
||||
codingplan_free: {
|
||||
plan_name: "CodingPlan Pro",
|
||||
remaining_days,
|
||||
expires_at: "2099-01-01",
|
||||
},
|
||||
}),
|
||||
false,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test("planNeedsClaim:expires_at 过期超 24h → 需要重领;24h 宽限内 → false", () => {
|
||||
const now = Date.parse("2026-10-16T12:00:00Z");
|
||||
assert.equal(
|
||||
planNeedsClaim({ codingplan_free: { plan_name: "Lite", expires_at: "2026-10-14T00:00:00Z" } }, now),
|
||||
true,
|
||||
);
|
||||
assert.equal(
|
||||
planNeedsClaim({ codingplan_free: { plan_name: "Lite", expires_at: "2026-10-16T00:00:00Z" } }, now),
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
planNeedsClaim({ codingplan_free: { plan_name: "Lite", expires_at: "2099-01-01T00:00:00Z" } }, now),
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
test("claim:网络异常只尝试一次,不把三档当三次重试", async () => {
|
||||
let calls = 0;
|
||||
const r = await claimCodingPlan("https://gitcode.example", "tok", {
|
||||
fetchImpl: async () => {
|
||||
calls += 1;
|
||||
throw new Error("boom");
|
||||
},
|
||||
clientVersion: "5.2.3",
|
||||
});
|
||||
assert.equal(r.claimed, false);
|
||||
assert.equal(calls, 1);
|
||||
assert.equal(r.attempts.length, 1);
|
||||
assert.match(r.message, /boom/);
|
||||
});
|
||||
|
||||
test("claim:429/5xx/401 不继续尝试其他档位", async () => {
|
||||
for (const status of [401, 429, 503]) {
|
||||
let calls = 0;
|
||||
const r = await claimCodingPlan("https://gitcode.example", "tok", {
|
||||
fetchImpl: async () => {
|
||||
calls += 1;
|
||||
return new Response(JSON.stringify({ message: "stop" }), { status });
|
||||
},
|
||||
clientVersion: "5.2.3",
|
||||
});
|
||||
assert.equal(calls, 1, `HTTP ${status} should stop the cascade`);
|
||||
assert.equal(r.claimed, false);
|
||||
}
|
||||
});
|
||||
|
||||
test("fetchModels:plan_type 编码进 query,过滤空名/不可用/弃用行", async () => {
|
||||
const good = { display_model_name: "ok/model", context_window: 100, plan_available: true };
|
||||
const { fetchImpl, seen } = sequenceFetch([
|
||||
{
|
||||
body: JSON.stringify([
|
||||
good,
|
||||
{ display_model_name: " " },
|
||||
{ display_model_name: "hidden", plan_available: false },
|
||||
{ display_model_name: "old", status: "deprecated" },
|
||||
]),
|
||||
},
|
||||
]);
|
||||
const rows = await fetchModels("https://gitcode.example", "tok", "Lite/dark", {
|
||||
fetchImpl,
|
||||
clientVersion: "5.2.3",
|
||||
});
|
||||
assert.equal(rows.length, 1);
|
||||
assert.deepEqual(rows[0], good);
|
||||
const u = new URL(seen[0].url);
|
||||
assert.equal(u.pathname, "/coding-plan/models-v2");
|
||||
assert.equal(u.searchParams.get("plan_type"), "Lite/dark");
|
||||
assert.equal(seen[0].init.headers.authorization, "Bearer tok");
|
||||
});
|
||||
|
||||
test("fetchModels:非数组响应抛错", async () => {
|
||||
const { fetchImpl } = sequenceFetch([{ body: JSON.stringify({ nope: 1 }) }]);
|
||||
await assert.rejects(
|
||||
() => fetchModels("https://x", "t", "Lite", { fetchImpl, clientVersion: "5.2.3" }),
|
||||
/did not return a list/,
|
||||
);
|
||||
});
|
||||
|
||||
test("CodingPlan 401/403 标记 signIn expired", async () => {
|
||||
const { fetchImpl } = sequenceFetch([{ status: 401, body: "{}" }]);
|
||||
const error = await fetchModels("https://x", "t", "Lite", { fetchImpl, clientVersion: "5.2.3" }).then(
|
||||
() => null,
|
||||
(e) => e,
|
||||
);
|
||||
assert.ok(error);
|
||||
assert.equal(error.signIn, "expired");
|
||||
});
|
||||
@@ -0,0 +1,362 @@
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { createServer, request as httpRequest } from "node:http";
|
||||
import { mkdtemp, readFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { MASTER_KEY_HEX } from "../sign.mjs";
|
||||
import { createStateStore } from "../state.mjs";
|
||||
import {
|
||||
DIAGNOSTICS_TOKEN_HEADER,
|
||||
diagnosticsPort,
|
||||
diagnosticsSnapshot,
|
||||
hostAllowed,
|
||||
originAllowed,
|
||||
runSelfCheck,
|
||||
startDiagnosticsService,
|
||||
} from "../diagnostics.mjs";
|
||||
|
||||
async function freePort() {
|
||||
const server = createServer();
|
||||
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
|
||||
const port = server.address().port;
|
||||
await new Promise((resolve) => server.close(resolve));
|
||||
return port;
|
||||
}
|
||||
|
||||
function rawRequest(port, path, { method = "GET", headers = {}, body } = {}) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const req = httpRequest(
|
||||
{ hostname: "127.0.0.1", port, path, method, headers },
|
||||
(res) => {
|
||||
let text = "";
|
||||
res.on("data", (chunk) => {
|
||||
text += chunk;
|
||||
});
|
||||
res.on("end", () =>
|
||||
resolve({ status: res.statusCode, headers: res.headers, text }),
|
||||
);
|
||||
},
|
||||
);
|
||||
req.on("error", reject);
|
||||
req.end(body);
|
||||
});
|
||||
}
|
||||
|
||||
test("diagnostics port, Host and Origin rules are loopback-only", () => {
|
||||
assert.equal(diagnosticsPort(3478), 3478);
|
||||
assert.equal(diagnosticsPort("4567"), 4567);
|
||||
assert.equal(diagnosticsPort(80), 3478);
|
||||
assert.equal(diagnosticsPort("bad"), 3478);
|
||||
assert.equal(hostAllowed("127.0.0.1:3478", 3478), true);
|
||||
assert.equal(hostAllowed("localhost:3478", 3478), true);
|
||||
assert.equal(hostAllowed("127.0.0.1:3479", 3478), false);
|
||||
assert.equal(hostAllowed("evil.example:3478", 3478), false);
|
||||
assert.equal(originAllowed(undefined, 3478), true);
|
||||
assert.equal(originAllowed(undefined, 3478, { required: true }), false);
|
||||
assert.equal(originAllowed("null", 3478, { required: true }), true);
|
||||
assert.equal(originAllowed("http://127.0.0.1:3478", 3478, { required: true }), true);
|
||||
assert.equal(originAllowed("https://127.0.0.1:3478", 3478, { required: true }), false);
|
||||
});
|
||||
|
||||
test("diagnostics page uses flat backgrounds without decorative gradients", async () => {
|
||||
const css = await readFile(new URL("../page/app.css", import.meta.url), "utf8");
|
||||
const html = await readFile(
|
||||
new URL("../page/diagnostics.html", import.meta.url),
|
||||
"utf8",
|
||||
);
|
||||
assert.doesNotMatch(css, /(?:radial|linear)-gradient/i);
|
||||
assert.doesNotMatch(css, /\.ambient\b/);
|
||||
assert.doesNotMatch(html, /class="ambient"/);
|
||||
});
|
||||
|
||||
test("offline self-check exercises signing without network access", () => {
|
||||
const ok = runSelfCheck({ clientVersion: "5.2.3", masterKeyHex: MASTER_KEY_HEX });
|
||||
assert.equal(ok.ok, true);
|
||||
assert.equal(ok.checks.signature, true);
|
||||
assert.equal(ok.checks.version, true);
|
||||
assert.equal(ok.checks.configuration, true);
|
||||
|
||||
const failed = runSelfCheck({ clientVersion: "", masterKeyHex: "bad" });
|
||||
assert.equal(failed.ok, false);
|
||||
assert.equal(failed.checks.version, false);
|
||||
assert.equal(failed.checks.configuration, false);
|
||||
});
|
||||
|
||||
test("snapshot exposes only redacted persisted account data", async () => {
|
||||
const snapshot = await diagnosticsSnapshot({
|
||||
state: {
|
||||
version: 1,
|
||||
accounts: {
|
||||
abcdef0123456789: {
|
||||
digest: "abcdef0123456789",
|
||||
loginSource: "atomcode-cli",
|
||||
models: [{ id: "model-a" }, { id: "model-b" }],
|
||||
modelSource: "live",
|
||||
modelUpdatedAt: new Date(1000).toISOString(),
|
||||
quota: {
|
||||
plan: "Plan",
|
||||
windows: [{ name: "5h", used: 10, unit: "calls" }],
|
||||
},
|
||||
quotaUpdatedAt: new Date(2000).toISOString(),
|
||||
lastError: { category: "network", message: "masked" },
|
||||
},
|
||||
},
|
||||
},
|
||||
version: { version: "5.2.3", source: "manifest" },
|
||||
config: { locale: "en", diagnosticsPort: 3478 },
|
||||
});
|
||||
assert.equal(snapshot.account.digest, "abcdef0123456789");
|
||||
assert.equal(snapshot.models.count, 2);
|
||||
assert.equal(snapshot.quota.stale, true);
|
||||
assert.equal(snapshot.config.readOnly, true);
|
||||
assert.doesNotMatch(JSON.stringify(snapshot), /access|refresh|email/i);
|
||||
});
|
||||
|
||||
test("loopback service serves a read-only page and token-gated APIs", async () => {
|
||||
const directory = await mkdtemp(join(tmpdir(), "atomcode-diagnostics-"));
|
||||
const stateStore = createStateStore({ directory });
|
||||
await stateStore.recordLogin("42", "atomcode-cli");
|
||||
await stateStore.recordQuota("42", {
|
||||
plan: "CodingPlan Lite",
|
||||
windows: [{ name: "5h", used: 12, unit: "calls" }],
|
||||
});
|
||||
|
||||
const port = await freePort();
|
||||
const versionSource = { status: () => ({ version: "5.2.3", source: "manifest" }) };
|
||||
const service = startDiagnosticsService({
|
||||
port,
|
||||
stateStore,
|
||||
versionSource,
|
||||
locale: "en",
|
||||
config: { locale: "en", diagnosticsPort: port, autoClaim: true, autoVersion: false },
|
||||
selfCheckConfig: { clientVersion: "5.2.3", masterKeyHex: MASTER_KEY_HEX },
|
||||
});
|
||||
try {
|
||||
assert.equal(await service.ready, service);
|
||||
assert.equal(startDiagnosticsService({ port }), service);
|
||||
|
||||
const page = await fetch(`http://127.0.0.1:${port}/`);
|
||||
assert.equal(page.status, 200);
|
||||
const policy = page.headers.get("content-security-policy");
|
||||
const loopback = `http://127.0.0.1:${port} http://localhost:${port}`;
|
||||
for (const directive of ["style-src", "script-src", "img-src", "connect-src"]) {
|
||||
assert.ok(
|
||||
policy.includes(`${directive} 'self' ${loopback}`),
|
||||
`${directive} names both loopback origins: ${policy}`,
|
||||
);
|
||||
}
|
||||
assert.ok(
|
||||
policy.includes(
|
||||
"frame-ancestors 'self' wails://localhost http://wails.localhost",
|
||||
),
|
||||
policy,
|
||||
);
|
||||
const nonceMatch = policy.match(/'nonce-([^']+)'/);
|
||||
assert.ok(nonceMatch, `script-src has a nonce: ${policy}`);
|
||||
assert.match(nonceMatch[1], /^[A-Za-z0-9+/]+={0,2}$/);
|
||||
assert.doesNotMatch(
|
||||
policy,
|
||||
/frame-ancestors 'none'|'unsafe-inline'|'unsafe-eval'|\*/,
|
||||
);
|
||||
assert.equal(page.headers.get("cache-control"), "no-store");
|
||||
assert.equal(
|
||||
page.headers.get("cross-origin-resource-policy"),
|
||||
"cross-origin",
|
||||
);
|
||||
const html = await page.text();
|
||||
assert.match(html, /name="atomcode-token" content="[a-f0-9]{64}"/);
|
||||
assert.ok(html.includes(`<script nonce="${nonceMatch[1]}" src="./app.js"></script>`));
|
||||
assert.doesNotMatch(html, /\{\{CSP_NONCE\}\}/);
|
||||
assert.match(html, /Read-only/);
|
||||
assert.match(html, /<html lang="en" data-theme="">/);
|
||||
assert.match(html, /href="\.\/icon\.svg"/);
|
||||
assert.match(html, /href="\.\/app\.css"/);
|
||||
assert.match(html, /src="\.\/app\.js"/);
|
||||
assert.doesNotMatch(html, /person@example\.com|Bearer/);
|
||||
|
||||
// Every reference stays relative, so the same page works at the origin root
|
||||
// and behind a reverse proxy that mounts it under a prefix.
|
||||
const proxyBase = `http://127.0.0.1:${port}/plugins/atomcode/`;
|
||||
for (const [, reference] of html.matchAll(/(?:href|src)="([^"]+)"/g)) {
|
||||
assert.ok(!reference.startsWith("/"), `${reference} must stay relative`);
|
||||
assert.ok(
|
||||
new URL(reference, proxyBase).pathname.startsWith("/plugins/atomcode/"),
|
||||
`${reference} resolves under the proxy prefix`,
|
||||
);
|
||||
}
|
||||
assert.equal(
|
||||
new URL("api/state", proxyBase).pathname,
|
||||
"/plugins/atomcode/api/state",
|
||||
);
|
||||
|
||||
const css = await fetch(`http://127.0.0.1:${port}/app.css`);
|
||||
assert.equal(css.status, 200);
|
||||
assert.equal(
|
||||
css.headers.get("cross-origin-resource-policy"),
|
||||
"cross-origin",
|
||||
);
|
||||
assert.match(await css.text(), /--accent/);
|
||||
const app = await fetch(`http://127.0.0.1:${port}/app.js`);
|
||||
assert.equal(app.status, 200);
|
||||
assert.equal(
|
||||
app.headers.get("cross-origin-resource-policy"),
|
||||
"cross-origin",
|
||||
);
|
||||
const script = await app.text();
|
||||
assert.match(script, /api\("api\/state"\)/);
|
||||
assert.match(script, /api\("api\/self-check"/);
|
||||
assert.equal((await fetch(`http://127.0.0.1:${port}/icon.svg`)).status, 200);
|
||||
assert.equal((await fetch(`http://127.0.0.1:${port}/missing`)).status, 404);
|
||||
|
||||
assert.equal((await fetch(`http://127.0.0.1:${port}/api/state`)).status, 403);
|
||||
|
||||
const statePreflight = await fetch(`http://127.0.0.1:${port}/api/state`, {
|
||||
method: "OPTIONS",
|
||||
headers: {
|
||||
origin: "null",
|
||||
"access-control-request-method": "GET",
|
||||
"access-control-request-headers": DIAGNOSTICS_TOKEN_HEADER,
|
||||
},
|
||||
});
|
||||
assert.equal(statePreflight.status, 204);
|
||||
assert.equal(statePreflight.headers.get("access-control-allow-origin"), "null");
|
||||
assert.match(statePreflight.headers.get("access-control-allow-methods"), /GET/);
|
||||
assert.equal(
|
||||
statePreflight.headers.get("access-control-allow-headers"),
|
||||
DIAGNOSTICS_TOKEN_HEADER,
|
||||
);
|
||||
assert.match(statePreflight.headers.get("vary"), /Origin/i);
|
||||
|
||||
const checkPreflight = await fetch(
|
||||
`http://127.0.0.1:${port}/api/self-check`,
|
||||
{
|
||||
method: "OPTIONS",
|
||||
headers: {
|
||||
origin: `http://127.0.0.1:${port}`,
|
||||
"access-control-request-method": "POST",
|
||||
"access-control-request-headers": DIAGNOSTICS_TOKEN_HEADER,
|
||||
},
|
||||
},
|
||||
);
|
||||
assert.equal(checkPreflight.status, 204);
|
||||
assert.equal(
|
||||
checkPreflight.headers.get("access-control-allow-origin"),
|
||||
`http://127.0.0.1:${port}`,
|
||||
);
|
||||
assert.match(
|
||||
checkPreflight.headers.get("access-control-allow-methods"),
|
||||
/POST/,
|
||||
);
|
||||
assert.equal(
|
||||
(await fetch(`http://127.0.0.1:${port}/api/state`, {
|
||||
method: "OPTIONS",
|
||||
headers: {
|
||||
origin: "http://evil.example",
|
||||
"access-control-request-method": "GET",
|
||||
},
|
||||
})).status,
|
||||
403,
|
||||
);
|
||||
|
||||
const state = await fetch(`http://127.0.0.1:${port}/api/state`, {
|
||||
headers: {
|
||||
[DIAGNOSTICS_TOKEN_HEADER]: service.token,
|
||||
origin: "null",
|
||||
},
|
||||
});
|
||||
assert.equal(state.status, 200);
|
||||
assert.equal(state.headers.get("access-control-allow-origin"), "null");
|
||||
assert.match(state.headers.get("vary"), /Origin/i);
|
||||
assert.doesNotMatch(state.headers.get("access-control-allow-origin"), /\*/);
|
||||
const snapshot = await state.json();
|
||||
assert.equal(snapshot.account.loginSource, "atomcode-cli");
|
||||
assert.equal(snapshot.quota.plan, "CodingPlan Lite");
|
||||
assert.equal(snapshot.config.autoVersion, false);
|
||||
|
||||
assert.equal(
|
||||
(await fetch(`http://127.0.0.1:${port}/api/state`, {
|
||||
headers: {
|
||||
[DIAGNOSTICS_TOKEN_HEADER]: service.token,
|
||||
origin: "http://evil.example",
|
||||
},
|
||||
})).status,
|
||||
403,
|
||||
);
|
||||
|
||||
const wrongOrigin = await fetch(`http://127.0.0.1:${port}/api/self-check`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
[DIAGNOSTICS_TOKEN_HEADER]: service.token,
|
||||
origin: "http://evil.example",
|
||||
},
|
||||
});
|
||||
assert.equal(wrongOrigin.status, 403);
|
||||
|
||||
const checked = await fetch(`http://127.0.0.1:${port}/api/self-check`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
[DIAGNOSTICS_TOKEN_HEADER]: service.token,
|
||||
origin: `http://127.0.0.1:${port}`,
|
||||
},
|
||||
});
|
||||
assert.equal(checked.status, 200);
|
||||
assert.equal(
|
||||
checked.headers.get("access-control-allow-origin"),
|
||||
`http://127.0.0.1:${port}`,
|
||||
);
|
||||
assert.equal((await checked.json()).ok, true);
|
||||
const stateAfterCheck = await fetch(`http://127.0.0.1:${port}/api/state`, {
|
||||
headers: {
|
||||
[DIAGNOSTICS_TOKEN_HEADER]: service.token,
|
||||
origin: "null",
|
||||
},
|
||||
});
|
||||
assert.equal(stateAfterCheck.status, 200);
|
||||
assert.equal((await stateAfterCheck.json()).selfCheck.ok, true);
|
||||
|
||||
const withBody = await fetch(`http://127.0.0.1:${port}/api/self-check`, {
|
||||
method: "POST",
|
||||
body: "{}",
|
||||
headers: {
|
||||
[DIAGNOSTICS_TOKEN_HEADER]: service.token,
|
||||
origin: `http://127.0.0.1:${port}`,
|
||||
},
|
||||
});
|
||||
assert.equal(withBody.status, 400);
|
||||
|
||||
const forbiddenHost = await rawRequest(port, "/", {
|
||||
headers: { host: `evil.example:${port}` },
|
||||
});
|
||||
assert.equal(forbiddenHost.status, 403);
|
||||
|
||||
const localized = await fetch(
|
||||
`http://127.0.0.1:${port}/?lang=zh-CN&theme=dark`,
|
||||
);
|
||||
assert.equal(localized.status, 200);
|
||||
assert.match(await localized.text(), /<html lang="zh" data-theme="dark">/);
|
||||
const localizedPolicy = localized.headers.get("content-security-policy");
|
||||
assert.notEqual(localizedPolicy, policy);
|
||||
} finally {
|
||||
await service.stop();
|
||||
}
|
||||
});
|
||||
|
||||
test("a foreign listener fails with an actionable port-conflict error", async () => {
|
||||
const port = await freePort();
|
||||
const blocker = createServer((_req, res) => res.end("blocked"));
|
||||
await new Promise((resolve) => blocker.listen(port, "127.0.0.1", resolve));
|
||||
const service = startDiagnosticsService({ port });
|
||||
try {
|
||||
await assert.rejects(
|
||||
service.ready,
|
||||
(error) =>
|
||||
error.code === "EADDRINUSE" &&
|
||||
new RegExp(`127\\.0\\.0\\.1:${port}`).test(error.message),
|
||||
);
|
||||
} finally {
|
||||
await service.stop();
|
||||
await new Promise((resolve) => blocker.close(resolve));
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,98 @@
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
|
||||
import {
|
||||
FAILURE,
|
||||
annotateError,
|
||||
classifyError,
|
||||
isCredentialFailure,
|
||||
isTransientFailure,
|
||||
keptResponseHeaders,
|
||||
} from "../errors.mjs";
|
||||
|
||||
test("classifyError separates credential, entitlement and generic 403s", () => {
|
||||
assert.equal(
|
||||
classifyError({ status: 403, message: "session token expired" }).category,
|
||||
FAILURE.CREDENTIAL_FORBIDDEN,
|
||||
);
|
||||
assert.equal(
|
||||
classifyError({ status: 403, message: "CodingPlan quota exhausted" }).category,
|
||||
FAILURE.ENTITLEMENT_FORBIDDEN,
|
||||
);
|
||||
const generic = classifyError({ status: 403, message: "Forbidden" });
|
||||
assert.equal(generic.category, FAILURE.FORBIDDEN);
|
||||
assert.equal(generic.refresh, false);
|
||||
assert.equal(generic.signInExpired, false);
|
||||
});
|
||||
|
||||
test("classifyError maps transport, HTTP, signing and account-change failures", () => {
|
||||
assert.equal(
|
||||
classifyError(new TypeError("fetch failed")).category,
|
||||
FAILURE.NETWORK,
|
||||
);
|
||||
assert.equal(
|
||||
classifyError(Object.assign(new Error("aborted"), { name: "AbortError" })).category,
|
||||
FAILURE.TIMEOUT,
|
||||
);
|
||||
assert.equal(classifyError({ status: 401 }).category, FAILURE.UNAUTHORIZED);
|
||||
assert.equal(classifyError({ status: 429 }).category, FAILURE.RATE_LIMIT);
|
||||
assert.equal(classifyError({ status: 503 }).category, FAILURE.SERVER);
|
||||
assert.equal(
|
||||
classifyError(new Error("invalid X-AtomCode signature")).category,
|
||||
FAILURE.SIGNING,
|
||||
);
|
||||
assert.equal(
|
||||
classifyError(new Error("client version requires upgrade")).category,
|
||||
FAILURE.VERSION,
|
||||
);
|
||||
const changed = classifyError(new Error("auth.toml changed accounts"));
|
||||
assert.equal(changed.category, FAILURE.CLI_ACCOUNT_CHANGED);
|
||||
assert.equal(changed.signInExpired, true);
|
||||
});
|
||||
|
||||
test("failure predicates are conservative", () => {
|
||||
assert.equal(isCredentialFailure({ status: 401 }), true);
|
||||
assert.equal(isCredentialFailure({ status: 403, message: "invalid token" }), true);
|
||||
assert.equal(isCredentialFailure({ status: 403, message: "usage limit" }), false);
|
||||
assert.equal(isTransientFailure({ status: 500 }), true);
|
||||
assert.equal(isTransientFailure({ status: 403 }), false);
|
||||
});
|
||||
|
||||
test("annotateError fixes an incorrect expired mark and attaches status", () => {
|
||||
const entitlement = annotateError(
|
||||
Object.assign(new Error("quota exhausted"), {
|
||||
status: 403,
|
||||
signIn: "expired",
|
||||
}),
|
||||
);
|
||||
assert.equal(entitlement.category, FAILURE.ENTITLEMENT_FORBIDDEN);
|
||||
assert.equal(entitlement.signIn, undefined);
|
||||
|
||||
const unauthorized = annotateError(new Error("no"));
|
||||
assert.equal(unauthorized.category, FAILURE.UNKNOWN);
|
||||
|
||||
const credential = annotateError({ message: "invalid token", status: 403 });
|
||||
assert.equal(credential instanceof Error, true);
|
||||
assert.equal(credential.signIn, "expired");
|
||||
});
|
||||
|
||||
test("403 entitlement responses are cloned with the kept sign-in header", async () => {
|
||||
const original = Response.json(
|
||||
{ message: "quota exhausted" },
|
||||
{ status: 403 },
|
||||
);
|
||||
const marked = keptResponseHeaders(original, {
|
||||
category: FAILURE.ENTITLEMENT_FORBIDDEN,
|
||||
});
|
||||
assert.notEqual(marked, original);
|
||||
assert.equal(marked.headers.get("x-magpie-sign-in"), "kept");
|
||||
assert.deepEqual(await marked.json(), { message: "quota exhausted" });
|
||||
|
||||
const credential = new Response("{}", { status: 403 });
|
||||
assert.equal(
|
||||
keptResponseHeaders(credential, { category: FAILURE.CREDENTIAL_FORBIDDEN }),
|
||||
credential,
|
||||
);
|
||||
const ordinary = new Response("{}", { status: 401 });
|
||||
assert.equal(keptResponseHeaders(ordinary, { category: FAILURE.UNAUTHORIZED }), ordinary);
|
||||
});
|
||||
@@ -0,0 +1,33 @@
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
|
||||
import { LOCALES, fill, resolveLocale, strings } from "../i18n.mjs";
|
||||
|
||||
test("zh and en expose the same keys and placeholders", () => {
|
||||
const zh = strings("zh");
|
||||
const en = strings("en");
|
||||
assert.deepEqual(Object.keys(zh).sort(), Object.keys(en).sort());
|
||||
|
||||
for (const key of Object.keys(zh)) {
|
||||
if (key === "locale") continue;
|
||||
const placeholders = (value) => [...String(value).matchAll(/\{(\w+)\}/g)].map((match) => match[1]).sort();
|
||||
assert.deepEqual(placeholders(zh[key]), placeholders(en[key]), `placeholder mismatch for ${key}`);
|
||||
}
|
||||
});
|
||||
|
||||
test("plan-aware check-in copy uses locale-appropriate punctuation", () => {
|
||||
assert.equal(fill(strings("en").checkinDoneWithPlan, { plan: "Lite" }), "The plan is still active; nothing to claim (Lite)");
|
||||
assert.equal(fill(strings("zh").checkinDoneWithPlan, { plan: "Lite" }), "套餐仍有效,无需重领(Lite)");
|
||||
});
|
||||
|
||||
test("fill leaves unknown placeholders visible", () => {
|
||||
assert.equal(fill("{known}-{missing}", { known: "ok" }), "ok-{missing}");
|
||||
});
|
||||
|
||||
test("resolveLocale follows explicit option, Intl and environment", () => {
|
||||
assert.deepEqual(LOCALES, ["zh", "en"]);
|
||||
assert.equal(resolveLocale("zh-CN", {}, "en-US"), "zh");
|
||||
assert.equal(resolveLocale("auto", {}, "en-GB"), "en");
|
||||
assert.equal(resolveLocale("auto", { LANG: "zh_CN.UTF-8" }, "fr-FR"), "zh");
|
||||
assert.equal(resolveLocale("auto", { LANG: "C" }, "fr-FR"), "en");
|
||||
});
|
||||
@@ -0,0 +1,134 @@
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
|
||||
import {
|
||||
credentialsOf,
|
||||
originOf,
|
||||
readCappedResponseText,
|
||||
redactText,
|
||||
trustedServiceURL,
|
||||
trustedURL,
|
||||
} from "../internal.mjs";
|
||||
|
||||
/**
|
||||
* 这两个校验函数是"地址不许乱跑"的统一收口点:模型地址、端点配置、请求目标
|
||||
* 都走同一套判定。用例钉住它的边界,改动时不会悄悄放宽。
|
||||
*/
|
||||
|
||||
test("trustedURL:https + 白名单域名(含子域)被采纳", () => {
|
||||
const domains = ["atomgit.com", "gitcode.com"];
|
||||
assert.equal(trustedURL("https://llm-api.atomgit.com/v1", { domains }), "https://llm-api.atomgit.com/v1");
|
||||
assert.equal(trustedURL("https://api.gitcode.com/api/v5", { domains }), "https://api.gitcode.com/api/v5");
|
||||
assert.equal(trustedURL("https://atomgit.com", { domains }), "https://atomgit.com");
|
||||
assert.equal(trustedURL(" https://acs.atomgit.com ", { domains }), "https://acs.atomgit.com");
|
||||
});
|
||||
|
||||
test("trustedURL:明文、内嵌凭证、相近域名、非法输入一律拒绝", () => {
|
||||
const domains = ["atomgit.com", "gitcode.com"];
|
||||
assert.equal(trustedURL("http://acs.atomgit.com", { domains }), undefined);
|
||||
assert.equal(trustedURL("https://user:pass@acs.atomgit.com", { domains }), undefined);
|
||||
assert.equal(trustedURL("https://evil.example", { domains }), undefined);
|
||||
assert.equal(trustedURL("https://evil-atomgit.com", { domains }), undefined);
|
||||
assert.equal(trustedURL("https://acs.atomgit.com.evil.example", { domains }), undefined);
|
||||
assert.equal(trustedURL("", { domains }), undefined);
|
||||
assert.equal(trustedURL(undefined, { domains }), undefined);
|
||||
assert.equal(trustedURL(123, { domains }), undefined);
|
||||
assert.equal(trustedURL("https://acs.atomgit.com", {}), undefined, "没有白名单时不得放行");
|
||||
assert.equal(
|
||||
trustedURL("https://acs.atomgit.com:8443", { domains }),
|
||||
undefined,
|
||||
"非 443 端口必须拒绝",
|
||||
);
|
||||
});
|
||||
|
||||
test("trustedURL:基础端点默认拒绝 query/hash,登录跳转可显式放行", () => {
|
||||
const domains = ["atomgit.com"];
|
||||
assert.equal(trustedURL("https://atomgit.com/login?state=1", { domains }), undefined);
|
||||
assert.equal(
|
||||
trustedURL("https://atomgit.com/login?state=1", { domains, allowSearch: true }),
|
||||
"https://atomgit.com/login?state=1",
|
||||
);
|
||||
});
|
||||
|
||||
test("trustedServiceURL:合法覆盖被采纳", () => {
|
||||
assert.equal(
|
||||
trustedServiceURL("https://api.gitcode.com/api/v6", { fallback: "https://api.gitcode.com/api/v5" }),
|
||||
"https://api.gitcode.com/api/v6",
|
||||
);
|
||||
});
|
||||
|
||||
test("trustedServiceURL:非法值回退默认端点并上报", () => {
|
||||
const rejected = [];
|
||||
const fallback = "https://acs.atomgit.com";
|
||||
const out = trustedServiceURL("https://evil.example", { fallback, onReject: (v) => rejected.push(v) });
|
||||
assert.equal(out, fallback);
|
||||
assert.deepEqual(rejected, ["https://evil.example"]);
|
||||
});
|
||||
|
||||
test("trustedServiceURL:未配置时不当作被拒,直接给默认值", () => {
|
||||
const rejected = [];
|
||||
const fallback = "https://acs.atomgit.com";
|
||||
assert.equal(trustedServiceURL(undefined, { fallback, onReject: (v) => rejected.push(v) }), fallback);
|
||||
assert.equal(trustedServiceURL("", { fallback, onReject: (v) => rejected.push(v) }), fallback);
|
||||
assert.deepEqual(rejected, []);
|
||||
});
|
||||
|
||||
test("trustedServiceURL:上报回调自己抛错也不影响返回值", () => {
|
||||
const out = trustedServiceURL("https://evil.example", {
|
||||
fallback: "https://acs.atomgit.com",
|
||||
onReject: () => {
|
||||
throw new Error("logger exploded");
|
||||
},
|
||||
});
|
||||
assert.equal(out, "https://acs.atomgit.com");
|
||||
});
|
||||
|
||||
test("originOf:协议与端口进入比较,非法输入 → undefined", () => {
|
||||
assert.equal(originOf("https://llm-api.atomgit.com/v1/chat/completions"), "https://llm-api.atomgit.com");
|
||||
assert.notEqual(
|
||||
originOf("http://llm-api.atomgit.com/v1"),
|
||||
originOf("https://llm-api.atomgit.com/v1"),
|
||||
"明文降级必须与 https 判定不同",
|
||||
);
|
||||
assert.notEqual(
|
||||
originOf("https://llm-api.atomgit.com:8443/v1"),
|
||||
originOf("https://llm-api.atomgit.com/v1"),
|
||||
"不同端口是不同来源",
|
||||
);
|
||||
assert.equal(originOf("not a url"), undefined);
|
||||
assert.equal(originOf(undefined), undefined);
|
||||
});
|
||||
|
||||
test("credentialsOf:缺少 access 时无法签名,uid 统一转字符串", () => {
|
||||
assert.equal(credentialsOf({}), undefined);
|
||||
assert.equal(credentialsOf({ access: "" }), undefined);
|
||||
assert.equal(credentialsOf(null), undefined);
|
||||
assert.equal(credentialsOf({ access: "tok", uid: 42 }).uid, "42");
|
||||
});
|
||||
|
||||
test("redactText:令牌、邮箱和长密钥都不会进入日志", () => {
|
||||
const secret = "a".repeat(64);
|
||||
const text = redactText(
|
||||
`access_token=access-secret refresh_token: refresh-secret Bearer bearer-secret alice@example.com ${secret}`,
|
||||
);
|
||||
assert.match(text, /access_token=\[redacted\]/);
|
||||
assert.match(text, /refresh_token=\[redacted\]/);
|
||||
assert.doesNotMatch(text, /access-secret|refresh-secret|bearer-secret|alice@example\.com/);
|
||||
assert.doesNotMatch(text, new RegExp(secret));
|
||||
});
|
||||
|
||||
test("readCappedResponseText:流式读取超过上限时立即取消", async () => {
|
||||
let pulls = 0;
|
||||
const chunk = new Uint8Array(64 * 1024);
|
||||
const stream = new ReadableStream({
|
||||
pull(controller) {
|
||||
pulls += 1;
|
||||
controller.enqueue(chunk);
|
||||
},
|
||||
});
|
||||
await assert.rejects(
|
||||
() => readCappedResponseText(new Response(stream), { label: "metadata" }),
|
||||
/metadata exceeds 1 MiB/,
|
||||
);
|
||||
assert.ok(pulls <= 30, `read too far: ${pulls} chunks`);
|
||||
});
|
||||
@@ -0,0 +1,182 @@
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
|
||||
import {
|
||||
DEFAULT_BASE_URL,
|
||||
DEFAULT_CONTEXT,
|
||||
DEFAULT_OUTPUT,
|
||||
normalizeCodingPlanModel,
|
||||
sanitizeModelKey,
|
||||
toConfigModel,
|
||||
toProviderModel,
|
||||
trustedModelBaseURL,
|
||||
} from "../models.mjs";
|
||||
|
||||
/**
|
||||
* `base_url` 来自上游 `models-v2`(服务端可控数据)。这些用例钉住白名单:
|
||||
* 只有 https、无内嵌凭证、且落在 atomgit 域上的地址才被采纳,其余一律回退
|
||||
* 官方网关——否则上游响应就能决定这个账号的 bearer token 发往哪里。
|
||||
*/
|
||||
|
||||
test("trustedModelBaseURL:只采纳 loader 实际允许的网关 origin", () => {
|
||||
assert.equal(trustedModelBaseURL("https://llm-api.atomgit.com/v1"), "https://llm-api.atomgit.com/v1");
|
||||
assert.equal(trustedModelBaseURL("https://raw.atomgit.com/x"), undefined);
|
||||
assert.equal(trustedModelBaseURL("https://atomgit.com"), undefined);
|
||||
assert.equal(trustedModelBaseURL("https://llm-api.atomgit.com:8443/v1"), undefined);
|
||||
assert.equal(trustedModelBaseURL(" https://llm-api.atomgit.com/v1 "), "https://llm-api.atomgit.com/v1");
|
||||
});
|
||||
|
||||
test("trustedModelBaseURL:域名不在白名单 → 拒绝", () => {
|
||||
assert.equal(trustedModelBaseURL("https://evil.example/v1"), undefined);
|
||||
assert.equal(trustedModelBaseURL("https://evil-atomgit.com/v1"), undefined, "相近域名不得蒙混过关");
|
||||
assert.equal(
|
||||
trustedModelBaseURL("https://llm-api.atomgit.com.evil.example/v1"),
|
||||
undefined,
|
||||
"把白名单域名当前缀同样不行",
|
||||
);
|
||||
});
|
||||
|
||||
test("trustedModelBaseURL:明文降级与内嵌凭证 → 拒绝", () => {
|
||||
assert.equal(trustedModelBaseURL("http://llm-api.atomgit.com/v1"), undefined);
|
||||
assert.equal(trustedModelBaseURL("https://user:pass@llm-api.atomgit.com/v1"), undefined);
|
||||
});
|
||||
|
||||
test("trustedModelBaseURL:非 URL 与非法类型 → 拒绝", () => {
|
||||
assert.equal(trustedModelBaseURL("not a url"), undefined);
|
||||
assert.equal(trustedModelBaseURL(""), undefined);
|
||||
assert.equal(trustedModelBaseURL(" "), undefined);
|
||||
assert.equal(trustedModelBaseURL(undefined), undefined);
|
||||
assert.equal(trustedModelBaseURL(null), undefined);
|
||||
assert.equal(trustedModelBaseURL(42), undefined);
|
||||
assert.equal(trustedModelBaseURL({}), undefined);
|
||||
});
|
||||
|
||||
test("normalizeCodingPlanModel:非法 base_url 被丢弃并上报原始值", () => {
|
||||
const rejected = [];
|
||||
const model = normalizeCodingPlanModel(
|
||||
{ display_model_name: "m1", base_url: "https://evil.example/v1" },
|
||||
{ onReject: (value) => rejected.push(value) },
|
||||
);
|
||||
assert.equal(model.baseURL, undefined, "非法地址不得进入模型描述");
|
||||
assert.deepEqual(rejected, ["https://evil.example/v1"]);
|
||||
});
|
||||
|
||||
test("normalizeCodingPlanModel:合法 base_url 原样保留,且不触发上报", () => {
|
||||
let rejected = 0;
|
||||
const model = normalizeCodingPlanModel(
|
||||
{ display_model_name: "m1", base_url: "https://llm-api.atomgit.com/v1" },
|
||||
{
|
||||
onReject: () => {
|
||||
rejected += 1;
|
||||
},
|
||||
},
|
||||
);
|
||||
assert.equal(model.baseURL, "https://llm-api.atomgit.com/v1");
|
||||
assert.equal(rejected, 0);
|
||||
});
|
||||
|
||||
test("normalizeCodingPlanModel:没有 base_url 时静默,不当作被拒", () => {
|
||||
let rejected = 0;
|
||||
const model = normalizeCodingPlanModel(
|
||||
{ display_model_name: "m1" },
|
||||
{
|
||||
onReject: () => {
|
||||
rejected += 1;
|
||||
},
|
||||
},
|
||||
);
|
||||
assert.equal(model.baseURL, undefined);
|
||||
assert.equal(rejected, 0);
|
||||
});
|
||||
|
||||
test("normalizeCodingPlanModel:上报回调自己抛错也不影响模型", () => {
|
||||
const model = normalizeCodingPlanModel(
|
||||
{ display_model_name: "m1", base_url: "https://evil.example/v1" },
|
||||
{
|
||||
onReject: () => {
|
||||
throw new Error("logger exploded");
|
||||
},
|
||||
},
|
||||
);
|
||||
assert.equal(model.id, "m1");
|
||||
assert.equal(model.baseURL, undefined);
|
||||
});
|
||||
|
||||
test("toProviderModel:模型没有可用 base_url 时落到调用方给的官方网关", () => {
|
||||
const model = normalizeCodingPlanModel({ display_model_name: "m1", base_url: "https://evil.example" });
|
||||
const providerModel = toProviderModel(model, "atomcode", { baseURL: DEFAULT_BASE_URL });
|
||||
assert.equal(providerModel.api.url, DEFAULT_BASE_URL);
|
||||
assert.equal(providerModel.api.id, "m1");
|
||||
});
|
||||
|
||||
test("reasoning variants carry the request option agents merge", () => {
|
||||
const m = normalizeCodingPlanModel({
|
||||
display_model_name: "qwen3.8-27b",
|
||||
context_window: 262144,
|
||||
reasoning_effort_levels: ["low", "medium", "xhigh"],
|
||||
});
|
||||
assert.deepEqual(toConfigModel(m).variants, {
|
||||
low: { reasoningEffort: "low" },
|
||||
medium: { reasoningEffort: "medium" },
|
||||
xhigh: { reasoningEffort: "xhigh" },
|
||||
});
|
||||
assert.deepEqual(toProviderModel(m, "atomcode").variants, {
|
||||
low: { reasoningEffort: "low" },
|
||||
medium: { reasoningEffort: "medium" },
|
||||
xhigh: { reasoningEffort: "xhigh" },
|
||||
});
|
||||
});
|
||||
|
||||
test("model output limit honours upstream declarations before the plugin fallback", () => {
|
||||
const declared = normalizeCodingPlanModel(
|
||||
{ display_model_name: "declared", max_output_tokens: 64000 },
|
||||
{ output: 32768 },
|
||||
);
|
||||
const fallback = normalizeCodingPlanModel({ display_model_name: "fallback" }, { output: 32768 });
|
||||
assert.equal(declared.output, 64000);
|
||||
assert.equal(fallback.output, 32768);
|
||||
});
|
||||
|
||||
test("catalog rows tolerate malformed optional fields", () => {
|
||||
assert.equal(normalizeCodingPlanModel(), null);
|
||||
assert.equal(normalizeCodingPlanModel({ display_model_name: 42 }), null);
|
||||
|
||||
const model = normalizeCodingPlanModel({
|
||||
display_model_name: " unsafe/model ",
|
||||
reasoning_effort_levels: [" low ", "", null, 7, "high"],
|
||||
context_window: "not-a-number",
|
||||
max_output_tokens: null,
|
||||
max_completion_tokens: null,
|
||||
output_token_limit: "invalid",
|
||||
base_url: 42,
|
||||
supports_vision: false,
|
||||
type: "",
|
||||
});
|
||||
assert.deepEqual(model, {
|
||||
id: "unsafe/model",
|
||||
key: "unsafe_model",
|
||||
context: DEFAULT_CONTEXT,
|
||||
output: DEFAULT_OUTPUT,
|
||||
levels: ["low", "high"],
|
||||
vision: false,
|
||||
type: "openai",
|
||||
baseURL: undefined,
|
||||
});
|
||||
});
|
||||
|
||||
test("model factories provide stable defaults for empty rows", () => {
|
||||
assert.equal(sanitizeModelKey(), "");
|
||||
const configModel = toConfigModel();
|
||||
assert.equal(configModel.name, undefined);
|
||||
assert.equal(configModel.reasoning, false);
|
||||
assert.equal(configModel.limit.context, DEFAULT_CONTEXT);
|
||||
assert.equal(configModel.limit.output, DEFAULT_OUTPUT);
|
||||
assert.equal(Object.hasOwn(configModel, "variants"), false);
|
||||
|
||||
const providerModel = toProviderModel();
|
||||
assert.equal(providerModel.id, undefined);
|
||||
assert.equal(providerModel.name, undefined);
|
||||
assert.equal(providerModel.api.url, DEFAULT_BASE_URL);
|
||||
assert.equal(providerModel.capabilities.reasoning, false);
|
||||
assert.deepEqual(providerModel.variants, {});
|
||||
});
|
||||
@@ -0,0 +1,114 @@
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
|
||||
import {
|
||||
checkLogin,
|
||||
refreshTokens,
|
||||
startLogin,
|
||||
stripForceLogin,
|
||||
tokenFor,
|
||||
} from "../oauth.mjs";
|
||||
|
||||
function sequenceFetch(responses) {
|
||||
const calls = [];
|
||||
const fetchImpl = async (url, init = {}) => {
|
||||
calls.push({ url, init });
|
||||
const next = responses[Math.min(calls.length - 1, responses.length - 1)];
|
||||
if (next.error) throw next.error;
|
||||
return new Response(next.body ?? "", { status: next.status ?? 200 });
|
||||
};
|
||||
return { fetchImpl, calls };
|
||||
}
|
||||
|
||||
test("startLogin strips force_login and validates the returned URL", async () => {
|
||||
const { fetchImpl, calls } = sequenceFetch([
|
||||
{
|
||||
body: JSON.stringify({
|
||||
login_url: "https://atomgit.com/login?force_login=true&next=%2Fhome",
|
||||
state: "state-1",
|
||||
}),
|
||||
},
|
||||
]);
|
||||
const result = await startLogin("https://acs.atomgit.com", { fetchImpl });
|
||||
|
||||
assert.equal(result.loginUrl, "https://atomgit.com/login?next=%2Fhome");
|
||||
assert.equal(result.state, "state-1");
|
||||
assert.equal(calls[0].init.redirect, "error");
|
||||
});
|
||||
|
||||
test("startLogin refuses a broker-supplied login URL outside AtomGit", async () => {
|
||||
const { fetchImpl } = sequenceFetch([
|
||||
{ body: JSON.stringify({ login_url: "https://evil.example/login", state: "state-1" }) },
|
||||
]);
|
||||
|
||||
await assert.rejects(() => startLogin("https://acs.atomgit.com", { fetchImpl }), /untrusted login URL/);
|
||||
});
|
||||
|
||||
test("checkLogin encodes state and only accepts a strict true", async () => {
|
||||
const { fetchImpl, calls } = sequenceFetch([{ body: JSON.stringify({ valid: true }) }]);
|
||||
assert.equal(await checkLogin("https://acs.atomgit.com", "a/b c", { fetchImpl }), true);
|
||||
assert.equal(new URL(calls[0].url).searchParams.get("state"), "a/b c");
|
||||
});
|
||||
|
||||
test("tokenFor validates and maps the credential response", async () => {
|
||||
const { fetchImpl } = sequenceFetch([
|
||||
{
|
||||
body: JSON.stringify({
|
||||
access_token: "access",
|
||||
refresh_token: "refresh",
|
||||
expires_in: 3600,
|
||||
token_type: "Bearer",
|
||||
user: { id: 42, email: "u@example.com" },
|
||||
}),
|
||||
},
|
||||
]);
|
||||
const token = await tokenFor("https://acs.atomgit.com", "state", { fetchImpl });
|
||||
assert.equal(token.accessToken, "access");
|
||||
assert.equal(token.refreshToken, "refresh");
|
||||
assert.equal(token.expiresIn, 3600);
|
||||
assert.equal(token.user.id, 42);
|
||||
});
|
||||
|
||||
test("refreshTokens keeps the old refresh token when upstream does not rotate", async () => {
|
||||
const { fetchImpl, calls } = sequenceFetch([
|
||||
{ body: JSON.stringify({ access_token: "new-access", expires_in: 7200 }) },
|
||||
]);
|
||||
const token = await refreshTokens("https://acs.atomgit.com", "old-refresh", { fetchImpl });
|
||||
|
||||
assert.equal(token.accessToken, "new-access");
|
||||
assert.equal(token.refreshToken, "old-refresh");
|
||||
assert.equal(token.expiresIn, 7200);
|
||||
assert.equal(JSON.parse(calls[0].init.body).refresh_token, "old-refresh");
|
||||
assert.equal(calls[0].init.redirect, "error");
|
||||
});
|
||||
|
||||
test("refreshTokens marks only credential failures as expired", async () => {
|
||||
for (const status of [400, 401, 403]) {
|
||||
const { fetchImpl } = sequenceFetch([{ status, body: "{}" }]);
|
||||
await assert.rejects(
|
||||
() => refreshTokens("https://acs.atomgit.com", "refresh", { fetchImpl }),
|
||||
(error) => error.signIn === "expired",
|
||||
);
|
||||
}
|
||||
|
||||
const { fetchImpl } = sequenceFetch([{ status: 503, body: "unavailable" }]);
|
||||
await assert.rejects(
|
||||
() => refreshTokens("https://acs.atomgit.com", "refresh", { fetchImpl }),
|
||||
(error) => error.status === 503 && error.signIn === undefined,
|
||||
);
|
||||
});
|
||||
|
||||
test("OAuth responses are bounded before JSON parsing", async () => {
|
||||
const chunk = new Uint8Array(64 * 1024);
|
||||
const stream = new ReadableStream({
|
||||
pull(controller) {
|
||||
controller.enqueue(chunk);
|
||||
},
|
||||
});
|
||||
const { fetchImpl } = sequenceFetch([{ body: stream }]);
|
||||
await assert.rejects(() => checkLogin("https://acs.atomgit.com", "state", { fetchImpl }), /exceeds 1 MiB/);
|
||||
});
|
||||
|
||||
test("stripForceLogin tolerates malformed URLs with the legacy fallback", () => {
|
||||
assert.equal(stripForceLogin("not a url&force_login=true"), "not a url");
|
||||
});
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,246 @@
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
|
||||
import { strings } from "../i18n.mjs";
|
||||
import { quotaFromStatus } from "../quota.mjs";
|
||||
|
||||
const t = strings("en");
|
||||
|
||||
test("quotaFromStatus maps every rate-limit window", () => {
|
||||
const usage = quotaFromStatus(
|
||||
{
|
||||
codingplan_free: {
|
||||
plan_name: "CodingPlan Pro",
|
||||
expires_at: "2026-12-01",
|
||||
},
|
||||
current_usage: {
|
||||
usage_percent: 99,
|
||||
reset_at: "2026-11-01T10:00:00Z",
|
||||
},
|
||||
rate_limit_windows: [
|
||||
{
|
||||
window_hours: 5,
|
||||
call_limit: 200,
|
||||
calls_used: 50,
|
||||
usage_percent: 25,
|
||||
seconds_until_reset: 1200,
|
||||
},
|
||||
{
|
||||
window_size_seconds: 86400,
|
||||
call_limit: 1000,
|
||||
calls_used: 250,
|
||||
usage_percent: 25,
|
||||
},
|
||||
],
|
||||
},
|
||||
t,
|
||||
{ user: "alice" },
|
||||
);
|
||||
|
||||
assert.equal(usage.plan, "CodingPlan Pro");
|
||||
assert.equal(usage.user, "alice");
|
||||
assert.equal(usage.until, "2026-12-01T15:59:59.999Z");
|
||||
assert.equal(usage.windows.length, 2);
|
||||
assert.deepEqual(usage.windows[0], {
|
||||
name: "5h window",
|
||||
used: 25,
|
||||
span: 18000,
|
||||
amount: 50,
|
||||
unit: "calls",
|
||||
limit: 200,
|
||||
display: "50 / 200 calls",
|
||||
resetSecs: 1200,
|
||||
});
|
||||
assert.equal(usage.windows[1].name, "24h window");
|
||||
assert.equal(usage.windows[1].display, "250 / 1000 calls");
|
||||
});
|
||||
|
||||
test("quotaFromStatus falls back to current_usage when no window rows exist", () => {
|
||||
const usage = quotaFromStatus(
|
||||
{
|
||||
codingplan_free: { plan_name: "CodingPlan Lite" },
|
||||
current_usage: {
|
||||
usage_percent: 120,
|
||||
window_hours: 3,
|
||||
seconds_until_reset: 60,
|
||||
},
|
||||
},
|
||||
t,
|
||||
);
|
||||
assert.deepEqual(usage.windows, [
|
||||
{
|
||||
name: "3h window",
|
||||
used: 120,
|
||||
span: 10800,
|
||||
unit: "calls",
|
||||
resetSecs: 60,
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
test("quotaFromStatus returns a stable empty shape for malformed status", () => {
|
||||
assert.deepEqual(quotaFromStatus(null, t), {
|
||||
plan: "AtomCode CodingPlan",
|
||||
windows: [],
|
||||
});
|
||||
});
|
||||
|
||||
test("quotaFromStatus keeps unknown shares unknown and trusts each window's own data", () => {
|
||||
const usage = quotaFromStatus(
|
||||
{
|
||||
codingplan_free: { plan_name: "Plan", remaining_days: null, expires_at: "2099-12-31" },
|
||||
current_usage: { usage_percent: 99, window_hours: 5, reset_at: "2099-12-31T10:00:00" },
|
||||
rate_limit_windows: [
|
||||
{ window_hours: 5, call_limit: 100, usage_percent: 12, reset_at: "2099-12-31T10:00:00" },
|
||||
{ window_hours: 24 },
|
||||
],
|
||||
},
|
||||
t,
|
||||
);
|
||||
assert.equal(usage.windows[0].used, 12);
|
||||
assert.equal(usage.windows[0].amount, undefined);
|
||||
assert.equal(usage.windows[1].used, undefined);
|
||||
assert.equal(usage.windows[1].amount, undefined);
|
||||
});
|
||||
|
||||
test("quotaFromStatus adds a token window when the current window declares tokens", () => {
|
||||
const usage = quotaFromStatus(
|
||||
{
|
||||
codingplan_free: { plan_name: "Plan" },
|
||||
current_usage: {
|
||||
unit: "tokens",
|
||||
window_hours: 5,
|
||||
window_tokens_used: 250000,
|
||||
window_token_limit: 1000000,
|
||||
seconds_until_reset: 60,
|
||||
},
|
||||
rate_limit_windows: [],
|
||||
},
|
||||
t,
|
||||
);
|
||||
assert.equal(usage.windows.length, 1);
|
||||
assert.equal(usage.windows[0].unit, "tokens");
|
||||
assert.equal(usage.windows[0].used, 25);
|
||||
assert.equal(usage.windows[0].amount, 250000);
|
||||
assert.equal(usage.windows[0].limit, 1000000);
|
||||
});
|
||||
|
||||
test("quotaFromStatus ignores legacy token-named call counters in current_usage", () => {
|
||||
const usage = quotaFromStatus(
|
||||
{
|
||||
codingplan_free: { plan_name: "Plan" },
|
||||
current_usage: {
|
||||
window_hours: 5,
|
||||
window_tokens_used: 237,
|
||||
window_token_limit: 1600,
|
||||
usage_percent: 14,
|
||||
seconds_until_reset: 60,
|
||||
},
|
||||
rate_limit_windows: [
|
||||
{
|
||||
window_size_seconds: 18000,
|
||||
window_hours: 5,
|
||||
call_limit: 1600,
|
||||
calls_used: 237,
|
||||
usage_percent: 14,
|
||||
seconds_until_reset: 60,
|
||||
},
|
||||
],
|
||||
},
|
||||
t,
|
||||
);
|
||||
assert.equal(usage.windows.length, 1);
|
||||
assert.equal(usage.windows[0].unit, "calls");
|
||||
assert.equal(usage.windows[0].amount, 237);
|
||||
assert.equal(usage.windows[0].limit, 1600);
|
||||
});
|
||||
|
||||
test("quotaFromStatus separates token and call rows and honours explicit units", () => {
|
||||
const usage = quotaFromStatus(
|
||||
{
|
||||
codingplan_free: { plan_name: "Plan" },
|
||||
current_usage: {
|
||||
usage_percent: 20,
|
||||
window_tokens_used: 500,
|
||||
window_token_limit: 1000,
|
||||
window_hours: 5,
|
||||
},
|
||||
rate_limit_windows: [
|
||||
{
|
||||
unit: "tokens",
|
||||
window_hours: 24,
|
||||
tokens_used: 400,
|
||||
token_limit: 2000,
|
||||
token_usage_percent: 20,
|
||||
},
|
||||
{
|
||||
unit: "calls",
|
||||
window_hours: 5,
|
||||
requests_used: 10,
|
||||
requests_limit: 100,
|
||||
},
|
||||
{
|
||||
window_hours: 7,
|
||||
call_limit: 50,
|
||||
calls_used: 5,
|
||||
},
|
||||
],
|
||||
},
|
||||
t,
|
||||
);
|
||||
assert.deepEqual(
|
||||
usage.windows.map((window) => [window.unit, window.span, window.used]),
|
||||
[
|
||||
["tokens", 86400, 20],
|
||||
["calls", 18000, 10],
|
||||
["calls", 25200, 10],
|
||||
],
|
||||
);
|
||||
assert.equal(usage.windows[0].display, "400 / 2000 tokens");
|
||||
assert.equal(usage.windows[1].display, "10 / 100 calls");
|
||||
});
|
||||
|
||||
test("quotaFromStatus deduplicates current_usage by unit, not span alone", () => {
|
||||
const usage = quotaFromStatus(
|
||||
{
|
||||
codingplan_free: { plan_name: "Plan" },
|
||||
current_usage: {
|
||||
usage_percent: 30,
|
||||
window_hours: 5,
|
||||
window_tokens_used: 300,
|
||||
window_token_limit: 1000,
|
||||
},
|
||||
rate_limit_windows: [
|
||||
{
|
||||
unit: "tokens",
|
||||
window_hours: 5,
|
||||
tokens_used: 300,
|
||||
token_limit: 1000,
|
||||
},
|
||||
],
|
||||
},
|
||||
t,
|
||||
);
|
||||
assert.deepEqual(
|
||||
usage.windows.map((window) => [window.unit, window.span, window.used]),
|
||||
[
|
||||
["tokens", 18000, 30],
|
||||
["calls", 18000, 30],
|
||||
],
|
||||
);
|
||||
});
|
||||
|
||||
test("quotaFromStatus keeps an explicit token window unknown instead of inventing zero", () => {
|
||||
const usage = quotaFromStatus(
|
||||
{
|
||||
codingplan_free: { plan_name: "Plan" },
|
||||
current_usage: {},
|
||||
rate_limit_windows: [{ unit: "tokens", window_hours: 3 }],
|
||||
},
|
||||
t,
|
||||
);
|
||||
assert.equal(usage.windows.length, 1);
|
||||
assert.equal(usage.windows[0].unit, "tokens");
|
||||
assert.equal(usage.windows[0].used, undefined);
|
||||
assert.equal(usage.windows[0].amount, undefined);
|
||||
});
|
||||
@@ -0,0 +1,139 @@
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
|
||||
import {
|
||||
includeStreamUsage,
|
||||
normalizeRequestBody,
|
||||
} from "../request-body.mjs";
|
||||
|
||||
test("normalizeRequestBody accepts replayable fetch bodies", async () => {
|
||||
const cases = [
|
||||
"hello",
|
||||
Buffer.from("buffer"),
|
||||
new TextEncoder().encode("view"),
|
||||
new TextEncoder().encode("array").buffer,
|
||||
new Blob(["blob"], { type: "application/json" }),
|
||||
];
|
||||
for (const body of cases) {
|
||||
const normalized = await normalizeRequestBody(body);
|
||||
assert.ok(normalized.body !== undefined);
|
||||
assert.ok(normalized.signBody !== undefined);
|
||||
}
|
||||
const empty = await normalizeRequestBody(undefined, {
|
||||
request: new Request("https://example.test/"),
|
||||
fromRequest: true,
|
||||
});
|
||||
assert.equal(empty.signBody, "");
|
||||
});
|
||||
|
||||
test("normalizeRequestBody rejects bodies that cannot be signed exactly", async () => {
|
||||
for (const body of [
|
||||
new URLSearchParams({ a: "1" }),
|
||||
new FormData(),
|
||||
new ReadableStream(),
|
||||
]) {
|
||||
await assert.rejects(() => normalizeRequestBody(body), /unsupported request body/i);
|
||||
}
|
||||
});
|
||||
|
||||
test("normalizeRequestBody caps Request bodies before buffering", async () => {
|
||||
const request = new Request("https://example.test/", {
|
||||
method: "POST",
|
||||
body: "too large",
|
||||
});
|
||||
await assert.rejects(
|
||||
() =>
|
||||
normalizeRequestBody(undefined, {
|
||||
request,
|
||||
fromRequest: true,
|
||||
maxBytes: 4,
|
||||
}),
|
||||
/exceeds 4 bytes/i,
|
||||
);
|
||||
});
|
||||
|
||||
test("normalizeRequestBody enforces the cap for every replayable type", async () => {
|
||||
const bodies = [
|
||||
"too large",
|
||||
Buffer.from("too large"),
|
||||
new TextEncoder().encode("too large"),
|
||||
new TextEncoder().encode("too large").buffer,
|
||||
new Blob(["too large"]),
|
||||
];
|
||||
for (const body of bodies) {
|
||||
await assert.rejects(
|
||||
() => normalizeRequestBody(body, { maxBytes: 4 }),
|
||||
/exceeds 4 bytes/i,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test("normalizeRequestBody reads each Request stream chunk shape", async () => {
|
||||
const stream = new ReadableStream({
|
||||
start(controller) {
|
||||
controller.enqueue(new TextEncoder().encode("a"));
|
||||
controller.enqueue(
|
||||
new TextEncoder().encode("b").buffer,
|
||||
);
|
||||
controller.enqueue(new DataView(new TextEncoder().encode("c").buffer));
|
||||
controller.close();
|
||||
},
|
||||
});
|
||||
const request = new Request("https://example.test/", {
|
||||
method: "POST",
|
||||
body: stream,
|
||||
duplex: "half",
|
||||
});
|
||||
const normalized = await normalizeRequestBody(undefined, {
|
||||
request,
|
||||
fromRequest: true,
|
||||
});
|
||||
assert.equal(new TextDecoder().decode(normalized.body), "abc");
|
||||
});
|
||||
|
||||
test("includeStreamUsage only fills an absent Chat Completions option", () => {
|
||||
const absent = JSON.stringify({ model: "m", stream: true });
|
||||
const added = includeStreamUsage(absent, {
|
||||
pathname: "/v1/chat/completions",
|
||||
contentType: "application/json",
|
||||
});
|
||||
assert.equal(added.changed, true);
|
||||
assert.equal(JSON.parse(added.body).stream_options.include_usage, true);
|
||||
|
||||
for (const body of [
|
||||
JSON.stringify({ model: "m", stream: false }),
|
||||
JSON.stringify({
|
||||
model: "m",
|
||||
stream: true,
|
||||
stream_options: { include_usage: false },
|
||||
}),
|
||||
absent,
|
||||
]) {
|
||||
const result = includeStreamUsage(body, {
|
||||
pathname: body === absent ? "/v1/embeddings" : "/v1/chat/completions",
|
||||
contentType: "application/json",
|
||||
});
|
||||
assert.equal(result.changed, false);
|
||||
assert.equal(result.body, body);
|
||||
}
|
||||
|
||||
const nonJson = includeStreamUsage(absent, {
|
||||
pathname: "/v1/chat/completions",
|
||||
contentType: "text/plain",
|
||||
});
|
||||
assert.equal(nonJson.changed, false);
|
||||
|
||||
for (const body of [
|
||||
"not json",
|
||||
"null",
|
||||
JSON.stringify({ stream: true, stream_options: null }),
|
||||
JSON.stringify({ stream: true, stream_options: [] }),
|
||||
]) {
|
||||
const result = includeStreamUsage(body, {
|
||||
pathname: "/v1/chat/completions",
|
||||
contentType: "application/json",
|
||||
});
|
||||
assert.equal(result.changed, false);
|
||||
assert.equal(result.body, body);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,58 @@
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
|
||||
import { MASTER_KEY_HEX, signAtomGitRequest } from "../sign.mjs";
|
||||
|
||||
/**
|
||||
* Atom2Api's independent signing fixture. This is the compatibility contract
|
||||
* for every model request; a plugin release must never change it silently.
|
||||
*/
|
||||
test("signing fixture matches Atom2Api", () => {
|
||||
const headers = signAtomGitRequest({
|
||||
method: "POST",
|
||||
path: "/v1/chat/completions",
|
||||
body: '{"model":"deepseek-v4-flash"}',
|
||||
oauthToken: "token-fixture",
|
||||
userId: "user-fixture",
|
||||
clientVersion: "5.0.2",
|
||||
timestamp: 1767225600,
|
||||
nonce: Buffer.from("000102030405060708090a0b0c0d0e0f", "hex"),
|
||||
});
|
||||
|
||||
assert.equal(
|
||||
headers["X-AtomCode-Sig"],
|
||||
"v1:c5bafa716c0fdc31a6e2738412d0b21a9d9e9d1ca09cc44eb17949a1b4fa4bdd",
|
||||
);
|
||||
assert.equal(headers["X-AtomCode-Ts"], "1767225600");
|
||||
assert.equal(headers["X-AtomCode-Nonce"], "000102030405060708090a0b0c0d0e0f");
|
||||
assert.equal(headers["X-AtomCode-Alg"], "1");
|
||||
assert.equal(headers["X-AtomCode-Ver"], "5.0.2");
|
||||
});
|
||||
|
||||
test("signature covers token, user, version and raw body bytes", () => {
|
||||
const base = {
|
||||
method: "POST",
|
||||
path: "/v1/chat/completions",
|
||||
body: new TextEncoder().encode("{}"),
|
||||
oauthToken: "token",
|
||||
userId: "user",
|
||||
clientVersion: "5.2.3",
|
||||
timestamp: 1767225600,
|
||||
nonce: Buffer.alloc(16, 7),
|
||||
};
|
||||
const signature = (overrides = {}) => signAtomGitRequest({ ...base, ...overrides })["X-AtomCode-Sig"];
|
||||
|
||||
assert.notEqual(signature(), signature({ oauthToken: "other-token" }));
|
||||
assert.notEqual(signature(), signature({ userId: "other-user" }));
|
||||
assert.notEqual(signature(), signature({ clientVersion: "5.2.4" }));
|
||||
assert.notEqual(signature(), signature({ body: new TextEncoder().encode('{"x":1}') }));
|
||||
});
|
||||
|
||||
test("signing rejects incomplete inputs instead of producing a partial signature", () => {
|
||||
assert.throws(() => signAtomGitRequest({ method: "", path: "/v1", oauthToken: "t", userId: "u", clientVersion: "v" }), /method/);
|
||||
assert.throws(() => signAtomGitRequest({ method: "GET", path: "v1", oauthToken: "t", userId: "u", clientVersion: "v" }), /path/);
|
||||
assert.throws(() => signAtomGitRequest({ method: "GET", path: "/v1", oauthToken: "", userId: "u", clientVersion: "v" }), /token/);
|
||||
assert.throws(() => signAtomGitRequest({ method: "GET", path: "/v1", oauthToken: "t", userId: "", clientVersion: "v" }), /user id/);
|
||||
assert.throws(() => signAtomGitRequest({ method: "GET", path: "/v1", oauthToken: "t", userId: "u", clientVersion: "" }), /version/);
|
||||
assert.match(MASTER_KEY_HEX, /^[0-9a-f]{64}$/);
|
||||
});
|
||||
@@ -0,0 +1,177 @@
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdtemp, readFile, stat, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
|
||||
import {
|
||||
STATE_FILE_NAME,
|
||||
accountDigest,
|
||||
createStateStore,
|
||||
emptyState,
|
||||
sanitizeState,
|
||||
stateFilePath,
|
||||
} from "../state.mjs";
|
||||
|
||||
test("accountDigest is stable, non-reversible and separates accounts", () => {
|
||||
const first = accountDigest("user-42");
|
||||
assert.match(first, /^[a-f0-9]{16}$/);
|
||||
assert.equal(first, accountDigest("user-42"));
|
||||
assert.notEqual(first, accountDigest("user-43"));
|
||||
assert.equal(accountDigest(undefined), "anonymous");
|
||||
});
|
||||
|
||||
test("sanitizeState keeps only the documented diagnostics schema", () => {
|
||||
const forbiddenTokenKey = ["to", "ken"].join("");
|
||||
const forbiddenSecretKey = ["top", "Level", "Secret"].join("");
|
||||
const state = sanitizeState({
|
||||
version: 99,
|
||||
accounts: {
|
||||
[accountDigest("42")]: {
|
||||
digest: accountDigest("42"),
|
||||
uid: "42",
|
||||
email: "person@example.com",
|
||||
access: "secret-token",
|
||||
prompt: "private prompt",
|
||||
rawResponse: "raw upstream",
|
||||
loginSource: "atomcode-cli",
|
||||
models: [
|
||||
{
|
||||
id: "model-a",
|
||||
key: "model-a",
|
||||
context: 1000,
|
||||
output: 100,
|
||||
levels: ["low"],
|
||||
vision: true,
|
||||
type: "openai",
|
||||
[forbiddenTokenKey]: "must-not-survive",
|
||||
},
|
||||
],
|
||||
modelSource: "live",
|
||||
quota: {
|
||||
plan: "Plan",
|
||||
user: "person@example.com",
|
||||
windows: [{ name: "5h", used: 12, unit: "calls" }],
|
||||
},
|
||||
lastError: {
|
||||
category: "network",
|
||||
message: "Bearer abc person@example.com",
|
||||
at: 1,
|
||||
stack: "secret",
|
||||
},
|
||||
},
|
||||
"../escape": { digest: "../escape" },
|
||||
},
|
||||
versionSource: {
|
||||
version: "5.2.3",
|
||||
source: "manifest",
|
||||
checkedAt: 2,
|
||||
[forbiddenTokenKey]: "x",
|
||||
},
|
||||
[forbiddenSecretKey]: "top-level-secret",
|
||||
});
|
||||
assert.equal(state.version, 1);
|
||||
const account = state.accounts[accountDigest("42")];
|
||||
assert.equal(account.uid, undefined);
|
||||
assert.equal(account.email, undefined);
|
||||
assert.equal(account.access, undefined);
|
||||
assert.equal(account.prompt, undefined);
|
||||
assert.equal(account.rawResponse, undefined);
|
||||
assert.equal(account.models[0][forbiddenTokenKey], undefined);
|
||||
assert.equal(account.quota.user, undefined);
|
||||
assert.doesNotMatch(account.lastError.message, /abc|person@example\.com/);
|
||||
assert.equal(state.accounts["../escape"], undefined);
|
||||
assert.equal(state[forbiddenSecretKey], undefined);
|
||||
assert.equal(state.versionSource[forbiddenTokenKey], undefined);
|
||||
});
|
||||
|
||||
test("state store persists models, quota, errors and a private atomic file", async () => {
|
||||
const directory = await mkdtemp(join(tmpdir(), "atomcode-state-"));
|
||||
const store = createStateStore({ directory });
|
||||
await store.recordLogin("42", "atomcode-cli");
|
||||
await store.recordModels(
|
||||
"42",
|
||||
[{ id: "m", key: "m", context: 100, output: 50, levels: [], vision: false, type: "openai" }],
|
||||
{ source: "live" },
|
||||
);
|
||||
await store.recordQuota("42", {
|
||||
plan: "Plan",
|
||||
user: "person@example.com",
|
||||
windows: [{ name: "5h", used: 30, unit: "calls" }],
|
||||
});
|
||||
await store.recordError("42", {
|
||||
category: "network",
|
||||
message: "Bearer secret person@example.com",
|
||||
status: 503,
|
||||
at: Date.now(),
|
||||
});
|
||||
await store.recordSelfCheck("42", {
|
||||
ok: true,
|
||||
at: Date.now(),
|
||||
ms: 1,
|
||||
checks: { signature: true, version: true, configuration: true },
|
||||
});
|
||||
await store.recordSelfCheckForDigest(accountDigest("42"), {
|
||||
ok: true,
|
||||
at: Date.now(),
|
||||
ms: 2,
|
||||
checks: { signature: true, version: true, configuration: true },
|
||||
});
|
||||
await store.recordVersion({
|
||||
version: "5.4.0",
|
||||
source: "manifest",
|
||||
checkedAt: Date.now(),
|
||||
});
|
||||
|
||||
const path = join(directory, STATE_FILE_NAME);
|
||||
const text = await readFile(path, "utf8");
|
||||
const info = await stat(path);
|
||||
assert.equal(info.mode & 0o777, 0o600);
|
||||
assert.doesNotMatch(text, /person@example\.com|secret|"uid"|"access"/);
|
||||
assert.match(text, /"digest": "[a-f0-9]{16}"/);
|
||||
assert.match(text, /"version": "5\.4\.0"/);
|
||||
|
||||
const reloaded = createStateStore({ directory });
|
||||
assert.equal((await reloaded.cachedModels("42"))[0].id, "m");
|
||||
assert.equal((await reloaded.cachedQuota("42")).plan, "Plan");
|
||||
const account = await reloaded.account(accountDigest("42"));
|
||||
assert.equal(account.lastError.status, 503);
|
||||
assert.equal(account.selfCheck.ok, true);
|
||||
assert.equal(account.selfCheck.ms, 2);
|
||||
});
|
||||
|
||||
test("a corrupt state file is ignored and replaced by the next write", async () => {
|
||||
const directory = await mkdtemp(join(tmpdir(), "atomcode-state-corrupt-"));
|
||||
const path = join(directory, STATE_FILE_NAME);
|
||||
await writeFile(path, "{ definitely not json", "utf8");
|
||||
const errors = [];
|
||||
const store = createStateStore({ directory, onError: (error) => errors.push(error) });
|
||||
const recovered = await store.read();
|
||||
assert.equal(recovered.version, emptyState().version);
|
||||
assert.deepEqual({ ...recovered.accounts }, {});
|
||||
assert.equal(errors.length, 1);
|
||||
await store.recordQuota("42", { plan: "Recovered", windows: [] });
|
||||
const reloaded = createStateStore({ directory });
|
||||
assert.equal((await reloaded.cachedQuota("42")).plan, "Recovered");
|
||||
});
|
||||
|
||||
test("stores without a directory stay in memory and report no path", async () => {
|
||||
const store = createStateStore();
|
||||
assert.equal(store.path, undefined);
|
||||
assert.equal(stateFilePath(undefined), undefined);
|
||||
await store.recordQuota("42", { plan: "Memory", windows: [] });
|
||||
assert.equal((await store.cachedQuota("42")).plan, "Memory");
|
||||
});
|
||||
|
||||
test("concurrent updates serialize rather than losing accounts", async () => {
|
||||
const directory = await mkdtemp(join(tmpdir(), "atomcode-state-concurrent-"));
|
||||
const store = createStateStore({ directory });
|
||||
await Promise.all([
|
||||
store.recordLogin("a", "atomcode-browser"),
|
||||
store.recordLogin("b", "atomcode-cli"),
|
||||
store.recordQuota("a", { plan: "A", windows: [] }),
|
||||
]);
|
||||
const state = await store.read();
|
||||
assert.ok(state.accounts[accountDigest("a")]);
|
||||
assert.ok(state.accounts[accountDigest("b")]);
|
||||
});
|
||||
@@ -0,0 +1,146 @@
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
|
||||
import { createVersionSource, extractVersionFromManifest, fetchAtomCodeVersion } from "../version.mjs";
|
||||
|
||||
const MANIFEST = '[package]\nname = "atomcode"\nversion = "9.9.9"\n\n[workspace.package]\nversion = "5.2.3"\nedition = "2021"\n';
|
||||
|
||||
test("只认 [workspace.package] 的 version,忽略 [package] 的", () => {
|
||||
assert.equal(extractVersionFromManifest(MANIFEST), "5.2.3");
|
||||
});
|
||||
|
||||
test("缺段 / 缺字段 / 非语义版本 → null", () => {
|
||||
assert.equal(extractVersionFromManifest('[package]\nversion = "1.2.3"\n'), null);
|
||||
assert.equal(extractVersionFromManifest('[workspace.package]\nedition = "2021"\n'), null);
|
||||
assert.equal(extractVersionFromManifest('[workspace.package]\nversion = "nightly"\n'), null);
|
||||
assert.equal(extractVersionFromManifest(""), null);
|
||||
assert.equal(extractVersionFromManifest(undefined), null);
|
||||
});
|
||||
|
||||
test("CRLF / 缩进 / 前导空白容忍", () => {
|
||||
assert.equal(extractVersionFromManifest('[workspace.package]\r\n version = "6.0.1" \r\n'), "6.0.1");
|
||||
});
|
||||
|
||||
test("fetchAtomCodeVersion:正常返回版本,非 2xx 抛错", async () => {
|
||||
const version = await fetchAtomCodeVersion({
|
||||
fetchImpl: async () => new Response(MANIFEST, { status: 200 }),
|
||||
});
|
||||
assert.equal(version, "5.2.3");
|
||||
await assert.rejects(
|
||||
fetchAtomCodeVersion({ fetchImpl: async () => new Response("nope", { status: 404 }) }),
|
||||
/manifest returned 404/,
|
||||
);
|
||||
});
|
||||
|
||||
test("版本源:冷启动 ensure 立即返回兜底,后台完成后再升级", async () => {
|
||||
let finish;
|
||||
const pending = new Promise((resolve) => {
|
||||
finish = resolve;
|
||||
});
|
||||
const src = createVersionSource({
|
||||
fallback: "5.2.3",
|
||||
fetchImpl: async () => {
|
||||
await pending;
|
||||
return new Response('[workspace.package]\nversion = "6.0.1"\n');
|
||||
},
|
||||
});
|
||||
assert.equal(src.get(), "5.2.3");
|
||||
assert.equal(await src.ensure(), "5.2.3");
|
||||
finish();
|
||||
await waitFor(() => src.get() === "6.0.1");
|
||||
assert.equal(src.get(), "6.0.1");
|
||||
});
|
||||
|
||||
test("TTL 内不重复拉取", async () => {
|
||||
let calls = 0;
|
||||
const src = createVersionSource({
|
||||
fallback: "5.2.3",
|
||||
fetchImpl: async () => {
|
||||
calls++;
|
||||
return new Response('[workspace.package]\nversion = "6.0.1"\n');
|
||||
},
|
||||
});
|
||||
await src.ensure();
|
||||
await src.ensure();
|
||||
assert.equal(calls, 1);
|
||||
});
|
||||
|
||||
test("拉取失败:退回兜底、标记 quiet,失败窗口内不再碰网、只回调一次 onError", async () => {
|
||||
let calls = 0;
|
||||
const logs = [];
|
||||
const src = createVersionSource({
|
||||
fallback: "5.2.3",
|
||||
failTtlMs: 60_000,
|
||||
fetchImpl: async () => {
|
||||
calls++;
|
||||
throw new Error("offline");
|
||||
},
|
||||
onError: (e) => logs.push(e.message),
|
||||
});
|
||||
assert.equal(await src.ensure(), "5.2.3");
|
||||
assert.equal(await src.ensure(), "5.2.3");
|
||||
assert.equal(calls, 1);
|
||||
assert.deepEqual(logs, ["offline"]);
|
||||
});
|
||||
|
||||
test("fetchAtomCodeVersion:超过 1 MiB 的清单边读边停,不会先整块吃下", async () => {
|
||||
let pulls = 0;
|
||||
const chunk = new Uint8Array(64 * 1024);
|
||||
const stream = new ReadableStream({
|
||||
pull(controller) {
|
||||
pulls += 1;
|
||||
if (pulls > 200) return controller.close();
|
||||
controller.enqueue(chunk);
|
||||
return undefined;
|
||||
},
|
||||
});
|
||||
await assert.rejects(
|
||||
fetchAtomCodeVersion({ fetchImpl: async () => new Response(stream, { status: 200 }) }),
|
||||
/exceeds 1 MiB/,
|
||||
);
|
||||
// 1 MiB / 64 KiB = 16 块;读到第 17 块就该中止,远不到 200。
|
||||
assert.ok(pulls <= 30, `应在越过上限时立刻停止读取,实际读了 ${pulls} 块`);
|
||||
});
|
||||
|
||||
test("fetchAtomCodeVersion:上限之内的较大清单仍能解析出真实版本", async () => {
|
||||
const padding = "#".repeat(200 * 1024);
|
||||
const text = `[workspace.package]\nversion = "6.1.0"\n${padding}\n`;
|
||||
const version = await fetchAtomCodeVersion({
|
||||
fetchImpl: async () => new Response(text, { status: 200 }),
|
||||
});
|
||||
assert.equal(version, "6.1.0");
|
||||
});
|
||||
|
||||
test("poke:后台拉取完成后 get() 升级(宿主常驻场景)", async () => {
|
||||
const src = createVersionSource({
|
||||
fallback: "5.2.3",
|
||||
fetchImpl: async () => new Response('[workspace.package]\nversion = "6.0.0"\n'),
|
||||
});
|
||||
assert.equal(src.get(), "5.2.3");
|
||||
src.poke();
|
||||
await new Promise((resolve) => setTimeout(resolve, 10));
|
||||
assert.equal(src.get(), "6.0.0");
|
||||
});
|
||||
|
||||
test("版本源报告来源并通过 onChange 通知持久化观察者", async () => {
|
||||
const changes = [];
|
||||
const src = createVersionSource({
|
||||
fallback: "5.2.3",
|
||||
fetchImpl: async () => new Response('[workspace.package]\nversion = "6.2.0"\n'),
|
||||
onChange: (status) => changes.push(status),
|
||||
});
|
||||
assert.equal(src.status().source, "fallback");
|
||||
src.poke();
|
||||
await waitFor(() => src.get() === "6.2.0");
|
||||
assert.equal(src.status().source, "manifest");
|
||||
assert.equal(changes.at(-1).version, "6.2.0");
|
||||
assert.equal(changes.at(-1).live, true);
|
||||
});
|
||||
|
||||
async function waitFor(predicate, timeoutMs = 1000) {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
while (!predicate()) {
|
||||
if (Date.now() >= deadline) throw new Error("condition was not met before timeout");
|
||||
await new Promise((resolve) => setTimeout(resolve, 5));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user