Merge branch 'qb1'

Co-Authored-By: Claude Fable 5.1 <[email protected]>
This commit is contained in:
rootandClaude Fable 5.1 committed 2026-09-29 21:05:25 +08:00
commit 8e47d8715b
36 files changed
+2053 -89

No files matched your search

+99 -20
View File
@@ -17,8 +17,13 @@ export interface QbInstanceConfig {
baseUrl: string;
username?: string;
password?: string;
/** qB 5.2+ WebUI API Key;有则走 Bearer,不登录 */
/** qB 5.2+ WebUI API Key(WebUI 生成,形如 qbt_…);有则走 Authorization: Bearer,不调 /auth/login */
apiKey?: string;
/**
* 认证方式(对照 MP / qbittorrent-api):password 走 /auth/login 会话 cookie;api_key 只发 Bearer 头;
* none 不认证(qB 设了"对白名单子网跳过认证"的内网)。缺省按是否给了 apiKey 推断。
*/
authMode?: QbAuthMode;
/** 单次请求超时,默认 15000 */
timeoutMs?: number;
/** 幂等读请求的重试次数(不含首次),默认 2;写请求不自动重试 */
@@ -36,6 +41,30 @@ export interface QbInstanceConfig {
fetch?: typeof fetch;
}
export type QbAuthMode = "password" | "api_key" | "none";
/**
* 实例配置 → 认证参数(服务端各处构造客户端共用)。
* authKind 显式给出时按它;缺省兼容旧数据:有用户名 → 账密,无用户名但有凭证 → API Key,否则无认证。
*/
export function qbAuthConfig(i: {
authKind?: unknown;
username?: string | null;
secret?: string | null;
}): Pick<QbInstanceConfig, "authMode" | "username" | "password" | "apiKey"> {
const kind: QbAuthMode =
i.authKind === "password" || i.authKind === "api_key" || i.authKind === "none"
? i.authKind
: i.username
? "password"
: i.secret
? "api_key"
: "none";
if (kind === "api_key") return { authMode: kind, ...(i.secret ? { apiKey: i.secret } : {}) };
if (kind === "none") return { authMode: kind };
return { authMode: kind, username: i.username ?? "", ...(i.secret ? { password: i.secret } : {}) };
}
export interface QbTorrent {
instanceId: string;
hash: string;
@@ -201,6 +230,23 @@ function str(v: unknown): string | null {
return typeof v === "string" && v !== "" ? v : null;
}
/**
* 从登录响应的 Set-Cookie 中取会话 cookie,返回可直接放进 Cookie 头的 "name=value"。
* 优先 SID / QBT_SID_<port> / 名字含 SID 的;否则取第一个有值的 cookie。
*/
export function pickSessionCookie(setCookies: readonly string[]): string | null {
const pairs = setCookies
.map((c) => /^\s*([^=;\s]+)=([^;]*)/.exec(c))
.filter((m): m is RegExpExecArray => m !== null && m[2] !== "")
.map((m) => ({ name: m[1]!, value: m[2]! }));
const hit =
pairs.find((p) => p.name === "SID") ??
pairs.find((p) => /^QBT_SID(_\d+)?$/i.test(p.name)) ??
pairs.find((p) => /sid/i.test(p.name)) ??
pairs[0];
return hit ? `${hit.name}=${hit.value}` : null;
}
export function normalizeTorrent(instanceId: string, r: Record<string, unknown>): QbTorrent {
const rawState = typeof r.state === "string" ? r.state : "";
const progress = num(r.progress) ?? 0;
@@ -253,8 +299,11 @@ export class QbClient implements DownloaderClient {
/** qB 5.x 把 pause/resume 改名为 stop/start;探测到后缓存 */
private legacyPauseApi: boolean | null = null;
private readonly authMode: QbAuthMode;
constructor(private readonly cfg: QbInstanceConfig) {
this.instanceId = cfg.instanceId;
this.authMode = cfg.authMode ?? (cfg.apiKey ? "api_key" : "password");
this.base = cfg.baseUrl.replace(/\/+$/, "");
this.timeoutMs = cfg.timeoutMs ?? 15_000;
this.retries = cfg.retries ?? 2;
@@ -290,7 +339,7 @@ export class QbClient implements DownloaderClient {
/** 登录;并发调用合并为一次。 */
async login(): Promise<void> {
if (this.cfg.apiKey) return;
if (this.authMode !== "password") return;
if (!this.loginInFlight) {
this.loginInFlight = this.doLogin().finally(() => {
this.loginInFlight = null;
@@ -299,6 +348,13 @@ export class QbClient implements DownloaderClient {
return this.loginInFlight;
}
/**
* 登录判定(对照 qbittorrent-api auth_log_in,覆盖 v4 / v5.0–5.2):
* - 成功:HTTP 200 且体为 "Ok."(≤5.1),或 204 空体(5.2+);
* - 会话 cookie 名不固定:≤5.1 为 SID,5.2+ 为 QBT_SID_<WebUI 端口>(容器内端口,不一定等于映射端口),
* 也可能被自定义 —— 一律取 Set-Cookie 里的会话 cookie 原名原值回传;
* - 失败:200 "Fails." / 401 → 凭据错误(auth);403 被封禁 / 429 → 限流(rate);5xx → protocol。
*/
private async doLogin(): Promise<void> {
const endpoint = "auth/login";
const res = await this.rawFetch(endpoint, {
@@ -306,18 +362,30 @@ export class QbClient implements DownloaderClient {
headers: { "content-type": "application/x-www-form-urlencoded", referer: this.base },
body: new URLSearchParams({ username: this.cfg.username ?? "", password: this.cfg.password ?? "" }),
});
const text = await res.text();
if (res.status === 403) throw this.err("auth", "login forbidden (IP banned after failed attempts?)", endpoint, 403);
if (res.status === 429) throw this.err("rate", "login rate limited", endpoint, 429);
if (!res.ok)
throw this.err(res.status >= 500 ? "protocol" : "auth", `login HTTP ${res.status}`, endpoint, res.status);
if (!text.trim().startsWith("Ok")) throw this.err("auth", "login rejected (bad credentials)", endpoint, res.status);
const cookie = res.headers
.getSetCookie()
.map((c) => /^SID=([^;]*)/.exec(c)?.[1])
.find((v) => v !== undefined);
// 关闭鉴权或白名单 IP 时 qB 可能不下发 cookie,仍视为成功
this.sid = cookie ?? "";
const text = (await res.text()).trim();
const s = res.status;
if (s === 204 || (s === 200 && /^ok\.?$/i.test(text))) {
// 关闭鉴权或白名单 IP 时 qB 可能不下发 cookie,仍视为成功
this.sid = pickSessionCookie(res.headers.getSetCookie()) ?? "";
return;
}
if (s === 200 && /^fails\.?$/i.test(text))
throw this.err("auth", "login rejected: bad username or password", endpoint, s);
if (s === 429) throw this.err("rate", "login rate limited", endpoint, s);
if (s === 403) {
if (/ban/i.test(text))
throw this.err("rate", "login blocked: IP banned after too many failed attempts", endpoint, s);
throw this.err("auth", `login forbidden (HTTP 403${text ? `: ${text.slice(0, 80)}` : ""})`, endpoint, s);
}
if (s === 401)
throw this.err(
"auth",
"login rejected (HTTP 401): bad username or password; for a port-mapped container also check that WEBUI_PORT equals the published port (qB rejects mismatched Host)",
endpoint,
s,
);
if (s >= 500) throw this.err("protocol", `login HTTP ${s}`, endpoint, s);
throw this.err("protocol", `unexpected login response: HTTP ${s} ${text.slice(0, 80)}`, endpoint, s);
}
private async send(endpoint: string, opts: ReqOpts): Promise<Response> {
@@ -338,10 +406,13 @@ export class QbClient implements DownloaderClient {
}
private async sendOnce(endpoint: string, opts: ReqOpts, relogged: boolean): Promise<Response> {
if (!this.cfg.apiKey && this.sid === null) await this.login();
const session = this.authMode === "password";
if (session && this.sid === null) await this.login();
const headers: Record<string, string> = { referer: this.base };
if (this.cfg.apiKey) headers.authorization = `Bearer ${this.cfg.apiKey}`;
else if (this.sid) headers.cookie = `SID=${this.sid}`;
if (this.authMode === "api_key") {
if (!this.cfg.apiKey) throw this.err("auth", "API Key auth selected but no API Key configured", endpoint);
headers.authorization = `Bearer ${this.cfg.apiKey}`;
} else if (session && this.sid) headers.cookie = this.sid;
let body: RequestInit["body"] | undefined;
if (opts.body?.kind === "form") {
headers["content-type"] = "application/x-www-form-urlencoded";
@@ -355,13 +426,21 @@ export class QbClient implements DownloaderClient {
const res = await this.rawFetch(path, { method: body ? "POST" : "GET", headers, ...(body ? { body } : {}) });
const s = res.status;
if (s === 401 || s === 403) {
await res.body?.cancel();
if (!this.cfg.apiKey && !relogged) {
const t = (await res.text().catch(() => "")).trim();
if (s === 403 && /ban/i.test(t))
throw this.err("rate", "IP banned after too many failed authentication attempts", endpoint, s);
if (session && !relogged) {
this.sid = null;
await this.login();
return this.sendOnce(endpoint, opts, true);
}
throw this.err("auth", `unauthorized (HTTP ${s})`, endpoint, s);
const why =
this.authMode === "api_key"
? "API Key rejected (check the key; API Key needs qBittorrent 5.2+)"
: this.authMode === "none"
? "WebUI requires authentication (use username/password or API Key, or whitelist this subnet in qB)"
: "session rejected after re-login";
throw this.err("auth", `unauthorized (HTTP ${s}): ${why}`, endpoint, s);
}
if (s === 404) {
const t = await res.text();
@@ -0,0 +1,227 @@
/**
* 真 qBittorrent 兼容性测试(默认跳过)。设置 QB_REAL 后对每个实例、每种认证方式跑一遍
* 登录 / 添加 / 查询 / 标签 / 暂停恢复 / 删除(不删数据),以及失败分类(错密码 → auth,IP 封禁 → rate)。
*
* QB_REAL='[{"label":"5.2.4","url":"http://127.0.0.1:18082","hostDir":"/tmp/qb52/downloads","qbDir":"/downloads",
* "username":"admin","password":"adminadmin","apiKey":"qbt_…"}]'
* hostDir 是 qB 保存目录在本机的路径(测试先把真实内容写进去,qB 校验通过即完成)。
* 容器做了端口映射时 WEBUI_PORT 必须等于映射端口,否则 qB 按 Host 头拒绝(一律 401)。
*/
import { existsSync } from "node:fs";
import { mkdir, rm, writeFile } from "node:fs/promises";
import { dirname, join } from "node:path";
import { makeTorrent } from "@umt/testkit";
import { describe, expect, it } from "vitest";
import { createQbClient, type DownloaderClient, DownloaderError, qbAuthConfig } from "./index.ts";
interface Target {
label: string;
url: string;
hostDir: string;
qbDir: string;
username: string;
password: string;
apiKey?: string | null;
}
const targets: Target[] = (() => {
try {
return JSON.parse(process.env.QB_REAL ?? "[]") as Target[];
} catch {
return [];
}
})();
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
const fast = { retries: 1, retryBaseMs: 200, lookup: { attempts: 10, intervalMs: 500 }, timeoutMs: 10_000 };
async function waitFor<T>(fn: () => Promise<T | null | undefined | false>, ms = 30_000): Promise<T> {
const end = Date.now() + ms;
for (;;) {
const v = await fn();
if (v) return v;
if (Date.now() > end) throw new Error("waitFor timeout");
await sleep(300);
}
}
async function roundTrip(qb: DownloaderClient, t: Target, tag: string) {
const v = await qb.version();
expect(v.app).toMatch(new RegExp(`^v?${t.label.replace(/\./g, "\\.")}`));
const dir = `umt-real-${tag}-${Date.now().toString(36)}`;
const made = makeTorrent({
name: `Real.Compat.${tag}.2024.1080p`,
pieceLength: 16384,
files: [
{ path: "Real.Compat.2024.1080p.mkv", length: 150_000 },
{ path: "Real.Compat.2024.1080p.chs.srt", length: 4_000 },
],
realPieces: true,
});
for (const c of made.contents!) {
const p = join(t.hostDir, dir, c.path);
await mkdir(dirname(p), { recursive: true });
await writeFile(p, c.bytes);
}
try {
const out = await qb.submit({
source: { kind: "file", bytes: made.bytes, filename: "real.torrent" },
savePath: `${t.qbDir}/${dir}`,
tags: ["umt-real"],
});
expect(out.kind).toBe("added");
// qB 对已有数据做校验:内容正确 → 完成(必要时手动 recheck)
let rechecked = false;
const done = await waitFor(async () => {
const x = await qb.findByHash(made.hash);
if (x && !x.complete && !rechecked && /^(stopped|paused)/.test(x.rawState)) {
rechecked = true;
await qb.recheck([made.hash]);
}
return x?.complete ? x : null;
});
expect(done.progress).toBe(1);
expect((await qb.files(made.hash)).map((f) => f.size).sort((a, b) => a - b)).toEqual([4_000, 150_000]);
await qb.addTags([made.hash], ["umt-real-extra"]);
expect((await qb.list({ tags: ["umt-real", "umt-real-extra"] })).map((x) => x.hash)).toContain(made.hash);
await qb.removeTags([made.hash], ["umt-real-extra"]);
await qb.deleteTagDefinitions(["umt-real-extra"]);
expect((await qb.findByHash(made.hash))?.tags).toEqual(["umt-real"]);
await qb.pause([made.hash]);
await waitFor(async () => (await qb.findByHash(made.hash))?.state === "completed_paused");
await qb.resume([made.hash]);
await waitFor(async () => (await qb.findByHash(made.hash))?.state !== "completed_paused");
await qb.delete([made.hash], { deleteFiles: false });
await waitFor(async () => (await qb.findByHash(made.hash)) === null);
// 不删数据
for (const c of made.contents!) expect(existsSync(join(t.hostDir, dir, c.path))).toBe(true);
} finally {
await qb.delete([made.hash], { deleteFiles: false }).catch(() => {});
await rm(join(t.hostDir, dir), { recursive: true, force: true }).catch(() => {});
}
}
/** 测试夹具:直接调 WebUI 读写偏好(客户端本身对偏好只读) */
async function sessionCookie(t: Target): Promise<string> {
const login = await fetch(`${t.url}/api/v2/auth/login`, {
method: "POST",
body: new URLSearchParams({ username: t.username, password: t.password }),
});
await login.body?.cancel();
return login.headers.getSetCookie()[0]!.split(";")[0]!;
}
async function getPrefs(t: Target, cookie: string): Promise<Record<string, unknown>> {
return (await (await fetch(`${t.url}/api/v2/app/preferences`, { headers: { cookie } })).json()) as Record<
string,
unknown
>;
}
async function setPrefs(t: Target, cookie: string, json: Record<string, unknown>): Promise<void> {
const r = await fetch(`${t.url}/api/v2/app/setPreferences`, {
method: "POST",
headers: { cookie, "content-type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({ json: JSON.stringify(json) }),
});
await r.body?.cancel();
expect(r.ok).toBe(true);
}
describe.skipIf(targets.length === 0)("真 qBittorrent 兼容性", () => {
for (const t of targets) {
it(`${t.label} 账密:登录 / 添加 / 查询 / 标签 / 暂停恢复 / 删除(不删数据)`, async () => {
const qb = createQbClient({
instanceId: `real-${t.label}`,
baseUrl: t.url,
...qbAuthConfig({ authKind: "password", username: t.username, secret: t.password }),
...fast,
});
await roundTrip(qb, t, "pw");
}, 90_000);
it.skipIf(!t.apiKey)(
`${t.label} API Key:不登录,全流程`,
async () => {
const qb = createQbClient({
instanceId: `real-${t.label}-key`,
baseUrl: t.url,
...qbAuthConfig({ authKind: "api_key", secret: t.apiKey ?? null }),
...fast,
});
await roundTrip(qb, t, "key");
const bad = createQbClient({
instanceId: "bad-key",
baseUrl: t.url,
...qbAuthConfig({ authKind: "api_key", secret: "qbt_definitely_wrong" }),
...fast,
});
const e = await bad.version().catch((x) => x);
expect(e).toBeInstanceOf(DownloaderError);
expect(e.kind).toBe("auth");
},
90_000,
);
it(`${t.label} 无认证(白名单子网跳过认证):不登录也能查询与添加`, async () => {
const qb = createQbClient({
instanceId: `real-${t.label}-pw`,
baseUrl: t.url,
...qbAuthConfig({ authKind: "password", username: t.username, secret: t.password }),
...fast,
});
await qb.version();
const cookie = await sessionCookie(t);
const prefs = await getPrefs(t, cookie);
await setPrefs(t, cookie, {
bypass_auth_subnet_whitelist_enabled: true,
bypass_auth_subnet_whitelist: "0.0.0.0/0",
});
try {
const none = createQbClient({
instanceId: "none-ok",
baseUrl: t.url,
...qbAuthConfig({ authKind: "none" }),
...fast,
});
await roundTrip(none, t, "none");
} finally {
await setPrefs(t, cookie, {
bypass_auth_subnet_whitelist_enabled: prefs.bypass_auth_subnet_whitelist_enabled,
bypass_auth_subnet_whitelist: prefs.bypass_auth_subnet_whitelist,
});
}
}, 90_000);
it(`${t.label} 失败分类:错密码 → auth;连续失败被封禁 → rate;无认证 → auth`, async () => {
// 临时把封禁阈值调小(测试结束恢复),避免把本机 IP 封一小时
const cookie = await sessionCookie(t);
const prefs = await getPrefs(t, cookie);
await setPrefs(t, cookie, { web_ui_max_auth_fail_count: 2, web_ui_ban_duration: 3 });
try {
const none = createQbClient({ instanceId: "none", baseUrl: t.url, authMode: "none", ...fast });
expect((await none.version().catch((x) => x)).kind).toBe("auth");
const bad = createQbClient({
instanceId: "bad",
baseUrl: t.url,
username: t.username,
password: "wrong-password",
...fast,
retries: 0,
});
expect((await bad.version().catch((x) => x)).kind).toBe("auth");
expect((await bad.version().catch((x) => x)).kind).toBe("auth");
const banned = await bad.version().catch((x) => x);
expect(banned.kind).toBe("rate");
expect(banned.detail.status).toBe(403);
} finally {
await sleep(4_000);
await setPrefs(t, cookie, {
web_ui_max_auth_fail_count: prefs.web_ui_max_auth_fail_count,
web_ui_ban_duration: prefs.web_ui_ban_duration,
});
}
}, 60_000);
}
});
@@ -8,6 +8,8 @@ import {
mapQbState,
parseMagnet,
parseTorrent,
pickSessionCookie,
qbAuthConfig,
} from "./index.ts";
import { fromDownloaderPath, toDownloaderPath } from "./paths.ts";
@@ -94,6 +96,104 @@ describe("QbClient 鉴权与错误分类", () => {
expect(e.kind).toBe("auth");
});
it("5.2:登录 204 空体 + QBT_SID_<port> 视为成功,会话 cookie 原名回传;过期 401 重登", async () => {
mock = await createMockQb({ version: "5.2.4", webUiPort: 18082 });
const qb = createQbClient({
instanceId: "qb-52",
baseUrl: mock.url,
username: "admin",
password: "adminadmin",
...fast,
});
expect((await qb.version()).webApi).toBe("2.11.4");
await qb.list();
expect(mock.callsTo("auth/login")).toHaveLength(1);
mock.expireSessions();
await expect(qb.list()).resolves.toEqual([]);
expect(mock.callsTo("auth/login")).toHaveLength(2);
});
it("失败分类:Fails./401 → auth;IP 封禁 403 / 429 → rate", async () => {
for (const version of ["4.6.7", "5.2.4"] as const) {
const m = await createMockQb({ version, banAfterFailures: 2 });
const bad = createQbClient({
instanceId: "qb-b",
baseUrl: m.url,
username: "admin",
password: "x",
...fast,
retries: 0,
});
expect((await bad.version().catch((e) => e)).kind).toBe("auth");
expect((await bad.version().catch((e) => e)).kind).toBe("auth");
const banned = await bad.version().catch((e) => e);
expect(banned.kind).toBe("rate");
expect(banned.detail.status).toBe(403);
await m.close();
}
mock = await createMockQb();
mock.fault("auth/login", { status: 429 });
const qb = createQbClient({
instanceId: "qb-r",
baseUrl: mock.url,
username: "admin",
password: "adminadmin",
...fast,
retries: 0,
});
expect((await qb.version().catch((e) => e)).kind).toBe("rate");
});
it("认证方式三选一:API Key 不登录、错 Key → auth 不重登;none 不登录,需要认证时 → auth", async () => {
mock = await createMockQb({ version: "5.2.4", apiKey: "qbt_good" });
const bad = createQbClient({
instanceId: "k",
baseUrl: mock.url,
...qbAuthConfig({ authKind: "api_key", secret: "qbt_bad" }),
...fast,
});
const e = await bad.version().catch((x) => x);
expect(e.kind).toBe("auth");
expect(e.message).toContain("API Key");
const none = createQbClient({ instanceId: "n", baseUrl: mock.url, ...qbAuthConfig({ authKind: "none" }), ...fast });
expect((await none.version().catch((x) => x)).kind).toBe("auth");
expect(mock.callsTo("auth/login")).toHaveLength(0);
await mock.close();
mock = await createMockQb({ version: "5.2.4", bypassAuth: true });
const open = createQbClient({
instanceId: "n2",
baseUrl: mock.url,
...qbAuthConfig({ authKind: "none" }),
...fast,
});
expect((await open.version()).webApi).toBe("2.11.4");
expect(mock.callsTo("auth/login")).toHaveLength(0);
});
it("qbAuthConfig:显式 authKind 优先;缺省按旧数据推断", () => {
expect(qbAuthConfig({ authKind: "api_key", username: "admin", secret: "k" })).toEqual({
authMode: "api_key",
apiKey: "k",
});
expect(qbAuthConfig({ authKind: "none", username: "admin", secret: "p" })).toEqual({ authMode: "none" });
expect(qbAuthConfig({ username: "admin", secret: "p" })).toEqual({
authMode: "password",
username: "admin",
password: "p",
});
expect(qbAuthConfig({ username: null, secret: "k" })).toEqual({ authMode: "api_key", apiKey: "k" });
expect(qbAuthConfig({})).toEqual({ authMode: "none" });
});
it("pickSessionCookie:SID / QBT_SID_<port> / 自定义名都能取到", () => {
expect(pickSessionCookie(["SID=abc; HttpOnly; path=/"])).toBe("SID=abc");
expect(pickSessionCookie(["foo=1; path=/", "QBT_SID_8080=xyz; HttpOnly"])).toBe("QBT_SID_8080=xyz");
expect(pickSessionCookie(["MY_QB_SID=q; path=/"])).toBe("MY_QB_SID=q");
expect(pickSessionCookie(["session=zz"])).toBe("session=zz");
expect(pickSessionCookie(["SID=; Max-Age=0"])).toBeNull();
expect(pickSessionCookie([])).toBeNull();
});
it("会话过期 403 → 自动重登一次后成功", async () => {
const { mock, qb } = await setup();
await qb.list();
+2
View File
@@ -189,6 +189,8 @@ export const DownloadTask = EntityBase.extend({
infohashV2: z.string().nullable(),
acquisitionPlanId: Id.nullable(),
sourceReleaseId: Id.nullable(),
/** 关联作品:计划 / 站点资源 / 接管任务按文件名识别 / 手动指定 / 手动整理后回填(QB-1) */
mediaEntityId: Id.nullable().optional(),
name: z.string(),
savePath: z.string().nullable(),
contentPath: z.string().nullable(),
+12 -1
View File
@@ -50,6 +50,13 @@ const Credential = z.string().min(1).max(4096);
export const DownloaderKind = z.enum(["qbittorrent"]);
export type DownloaderKind = z.infer<typeof DownloaderKind>;
/**
* 下载器认证方式(存 settings.authKind):password 账密登录(凭证=密码);api_key qB 5.2+ WebUI 生成的 API Key
* (凭证=Key,走 Authorization: Bearer,不登录);none 无认证(qB 对内网白名单跳过认证)。
*/
export const DownloaderAuthKind = z.enum(["password", "api_key", "none"]);
export type DownloaderAuthKind = z.infer<typeof DownloaderAuthKind>;
export const DownloaderInstance = EntityBase.extend({
name: z.string().min(1),
kind: DownloaderKind,
@@ -78,7 +85,11 @@ export const DownloaderInstanceCreate = DownloaderInstance.pick({
settings: true,
})
.partial({ kind: true, username: true, managedTag: true, cacheVolumeKey: true, enabled: true, settings: true })
.extend({ credential: Credential.optional() });
.extend({
credential: Credential.optional(),
/** 认证方式,写入 settings.authKind;缺省按"有用户名 → 账密,否则有凭证 → API Key,否则无认证"推断 */
authKind: DownloaderAuthKind.optional(),
});
export type DownloaderInstanceCreate = z.infer<typeof DownloaderInstanceCreate>;
export const DownloaderInstanceUpdate = DownloaderInstanceCreate.partial();
export type DownloaderInstanceUpdate = z.infer<typeof DownloaderInstanceUpdate>;
+21
View File
@@ -374,6 +374,27 @@ export const LibraryDetail = z.object({
slots: z.array(AcquisitionSlot),
candidates: z.array(CandidateEvaluation),
downloads: z.array(LibraryDownloadView),
/**
* 该作品的整理记录(最近 100 条,新→旧):含没有下载任务的手动整理(文件管理按路径整理)。
* 下载历史里已按下载任务列出的记录也在这里,前端按 downloadTaskId 去重展示。
*/
organizationRecords: z
.array(
z.object({
id: Id,
status: OrganizationStatus,
action: OrganizationAction,
trigger: OrganizationTrigger,
downloadTaskId: Id.nullable(),
sourcePath: z.string().nullable(),
targetPath: z.string().nullable(),
fileSucceeded: NonNegInt,
fileTotal: NonNegInt,
createdAt: Timestamp,
finishedAt: Timestamp.nullable(),
}),
)
.optional(),
});
export type LibraryDetail = z.infer<typeof LibraryDetail>;
@@ -0,0 +1,29 @@
import type { Kysely } from "kysely";
import { execDdl } from "../src/migration-helpers.ts";
// QB-1:下载任务直接记关联作品(接管任务按文件名识别 / 手动指定 / 手动整理后回填),作品详情"下载历史"据此列出
// 没有计划与站点资源的接管任务。已有行按 计划 Slot → 站点资源 → 最近一次整理记录 回填。
// biome-ignore lint/suspicious/noExplicitAny: 迁移不依赖应用表类型
export async function up(db: Kysely<any>): Promise<void> {
await execDdl(
db,
`alter table download_task add column if not exists media_entity_id uuid references media_entity (id) on delete set null;
create index if not exists download_task_media_entity_idx on download_task (media_entity_id) where media_entity_id is not null;
update download_task dt set media_entity_id = coalesce(
(select s.media_entity_id from acquisition_plan p join acquisition_slot s on s.id = p.slot_id where p.id = dt.acquisition_plan_id),
(select sr.media_entity_id from source_release sr where sr.id = dt.source_release_id),
(select r.media_entity_id from organization_record r
where r.download_task_id = dt.id and r.media_entity_id is not null order by r.created_at desc limit 1))
where dt.media_entity_id is null;`,
);
}
// biome-ignore lint/suspicious/noExplicitAny: 同上
export async function down(db: Kysely<any>): Promise<void> {
await execDdl(
db,
`drop index if exists download_task_media_entity_idx;
alter table download_task drop column if exists media_entity_id;`,
);
}
+1
View File
@@ -703,6 +703,7 @@ export interface DownloadTaskTable {
last_error: Json | null;
created_at: GeneratedTimestamptz;
updated_at: GeneratedTimestamptz;
media_entity_id: string | null;
}
export interface DownloaderInstanceTable {
+63 -5
View File
@@ -65,8 +65,14 @@ export interface MakeTorrentInput {
pieceLength?: number;
private?: boolean;
announce?: string;
/** 改变伪 pieces 内容,用于构造同名同大小但 infohash 不同的种子 */
/** 改变伪 pieces 内容,用于构造同名同大小但 infohash 不同的种子(realPieces 时也参与确定性内容生成) */
pieceSeed?: number;
/**
* 生成真实 piece hash(可被真 qB 校验通过):true 时按 pieceSeed + 文件路径生成确定性内容,
* 也可传函数自定义每个文件的内容(长度须等于 length)。内容随返回值 contents 给出,调用方写盘后 qB 重新校验即完成。
* 默认 false:pieces 为伪值,不可真正下载(旧行为)。
*/
realPieces?: boolean | ((path: string, length: number) => Uint8Array);
}
export interface MadeTorrent {
@@ -75,9 +81,28 @@ export interface MadeTorrent {
name: string;
totalSize: number;
files: { path: string; length: number }[];
/** realPieces 时:每个文件的内容(path 同 files[].path,含种子根目录) */
contents?: { path: string; bytes: Uint8Array }[];
}
/** 构造一个合法的 v1 .torrent(pieces 为伪值,不可真正下载)。 */
/** 确定性伪随机内容(xorshift32),同 seed + path 得到同样字节 */
export function deterministicContent(seedKey: string, length: number): Uint8Array {
let x = 2166136261;
for (let i = 0; i < seedKey.length; i++) x = Math.imul(x ^ seedKey.charCodeAt(i), 16777619) >>> 0;
if (x === 0) x = 1;
const out = new Uint8Array(length);
for (let i = 0; i < length; i++) {
x ^= x << 13;
x >>>= 0;
x ^= x >>> 17;
x ^= x << 5;
x >>>= 0;
out[i] = x & 0xff;
}
return out;
}
/** 构造一个合法的 v1 .torrent;realPieces 时 pieces 为按内容计算的真实 SHA-1,否则为伪值。 */
export function makeTorrent(input: MakeTorrentInput): MadeTorrent {
const pieceLength = input.pieceLength ?? 4 * 1024 * 1024;
const info: { [k: string]: BVal } = { name: input.name, "piece length": pieceLength };
@@ -90,13 +115,46 @@ export function makeTorrent(input: MakeTorrentInput): MadeTorrent {
files = [{ path: input.name, length: info.length as number }];
}
const total = files.reduce((a, f) => a + f.length, 0);
const pieces = Math.max(1, Math.ceil(total / pieceLength));
info.pieces = Buffer.alloc(20 * Math.min(pieces, 4), input.pieceSeed ?? 7);
let contents: MadeTorrent["contents"];
if (input.realPieces) {
const gen =
typeof input.realPieces === "function"
? input.realPieces
: (path: string, length: number) => deterministicContent(`${input.pieceSeed ?? 7}:${path}`, length);
contents = files.map((f) => {
const bytes = gen(f.path, f.length);
if (bytes.length !== f.length) throw new Error(`realPieces: ${f.path} 内容长度 ${bytes.length} ≠ ${f.length}`);
return { path: f.path, bytes };
});
// v1:所有文件按顺序拼成一个字节流,按 piece length 切片逐片 SHA-1
const hashes: Buffer[] = [];
let h = createHash("sha1");
let filled = 0;
for (const c of contents) {
let off = 0;
while (off < c.bytes.length) {
const n = Math.min(pieceLength - filled, c.bytes.length - off);
h.update(c.bytes.subarray(off, off + n));
off += n;
filled += n;
if (filled === pieceLength) {
hashes.push(h.digest());
h = createHash("sha1");
filled = 0;
}
}
}
if (filled > 0 || hashes.length === 0) hashes.push(h.digest());
info.pieces = Buffer.concat(hashes);
} else {
const pieces = Math.max(1, Math.ceil(total / pieceLength));
info.pieces = Buffer.alloc(20 * Math.min(pieces, 4), input.pieceSeed ?? 7);
}
if (input.private) info.private = 1;
const root: { [k: string]: BVal } = { announce: input.announce ?? "https://tracker.example.invalid/announce", info };
const bytes = bencode(root);
const hash = createHash("sha1").update(bencode(info)).digest("hex");
return { bytes, hash, name: input.name, totalSize: total, files };
return { bytes, hash, name: input.name, totalSize: total, files, ...(contents ? { contents } : {}) };
}
export function makeMagnet(hash: string, name?: string): string {
@@ -1,4 +1,5 @@
export {
deterministicContent,
inspectTorrent as inspectTorrentFixture,
type MadeTorrent,
type MakeTorrentInput,
+27 -6
View File
@@ -70,7 +70,17 @@ export interface MockQbFault {
}
export interface MockQbOptions {
version?: "4.6.7" | "5.1.0";
/**
* 登录行为随版本:≤5.1 成功 200 "Ok." + SID、失败 200 "Fails.";
* 5.2.x 成功 204 空体 + QBT_SID_<port>、失败 401 "Unauthorized"。
*/
version?: "4.6.7" | "5.1.0" | "5.2.4";
/** 模拟 qB"对白名单子网跳过认证":不带会话/Key 的请求也放行 */
bypassAuth?: boolean;
/** 连续登录失败达到该次数后封禁(403 "Your IP address has been banned…"),默认不封禁 */
banAfterFailures?: number;
/** 5.2.x 会话 cookie 名里的端口(真实 qB 用容器内 WebUI 端口),默认 8080 */
webUiPort?: number;
username?: string;
password?: string;
apiKey?: string;
@@ -136,6 +146,9 @@ export async function createMockQb(opts: MockQbOptions = {}): Promise<MockQb> {
const faults = new Map<string, MockQbFault[]>();
const calls: MockQbCall[] = [];
let rid = 0;
const v52 = version.startsWith("5.2");
const cookieName = v52 ? `QBT_SID_${opts.webUiPort ?? 8080}` : "SID";
let loginFailures = 0;
const pausedState = (done: boolean) => (v5 ? (done ? "stoppedUP" : "stoppedDL") : done ? "pausedUP" : "pausedDL");
@@ -557,17 +570,25 @@ export async function createMockQb(opts: MockQbOptions = {}): Promise<MockQb> {
}
if (endpoint === "auth/login") {
if (opts.banAfterFailures !== undefined && loginFailures >= opts.banAfterFailures)
return send(403, "Your IP address has been banned after too many failed authentication attempts.");
if (form.username === user && form.password === pass) {
loginFailures = 0;
const sid = randomBytes(16).toString("hex");
sessions.add(sid);
return send(200, "Ok.", { "set-cookie": `SID=${sid}; HttpOnly; path=/` });
return v52
? send(204, "", { "set-cookie": `${cookieName}=${sid}; HttpOnly; SameSite=Lax; path=/` })
: send(200, "Ok.", { "set-cookie": `SID=${sid}; HttpOnly; path=/` });
}
return send(200, "Fails.");
loginFailures++;
return v52 ? send(401, "Unauthorized") : send(200, "Fails.");
}
const bearer = /^Bearer (.+)$/.exec(req.headers.authorization ?? "")?.[1];
const sid = parseCookies(req.headers.cookie).SID;
const authed = (opts.apiKey && bearer === opts.apiKey) || (sid !== undefined && sessions.has(sid));
if (!authed) return send(403, "Forbidden");
const sid = parseCookies(req.headers.cookie)[cookieName];
const authed =
opts.bypassAuth === true || (opts.apiKey && bearer === opts.apiKey) || (sid !== undefined && sessions.has(sid));
// 真 qB 5.2:错误的 Bearer Key → 403;没有会话 → 401
if (!authed) return v52 && !bearer ? send(401, "Unauthorized") : send(403, "Forbidden");
const h = handlers[endpoint];
if (!h) return send(404, "Not Found");
+45 -1
View File
@@ -3,7 +3,8 @@ import { mkdtemp, readFile, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import { createMockQb, type MockQb } from "../src/index.ts";
import { createMockQb, type MockQb, makeTorrent } from "../src/index.ts";
import { bdecodeLoose } from "../src/qbittorrent/bencode.ts";
let mock: MockQb | null = null;
let dir: string | null = null;
@@ -88,3 +89,46 @@ describe("mock qB 落盘(B8)", () => {
expect(readdirSync(dir)).toEqual([]);
});
});
describe("makeTorrent realPieces", () => {
it("按内容计算真实 piece hash:跨文件切片,片数正确,内容确定", async () => {
const { createHash } = await import("node:crypto");
const t = makeTorrent({
name: "Real.Pieces",
pieceLength: 16384,
files: [
{ path: "a.mkv", length: 20000 },
{ path: "Subs/a.ass", length: 30000 },
],
realPieces: true,
});
expect(t.contents?.map((c) => [c.path, c.bytes.length])).toEqual([
["Real.Pieces/a.mkv", 20000],
["Real.Pieces/Subs/a.ass", 30000],
]);
const all = Buffer.concat(t.contents!.map((c) => Buffer.from(c.bytes)));
const want = Buffer.concat(
[0, 1, 2, 3].map((i) =>
createHash("sha1")
.update(all.subarray(i * 16384, (i + 1) * 16384))
.digest(),
),
);
const info = (bdecodeLoose(t.bytes) as { info: { pieces: Buffer } }).info;
expect(info.pieces.equals(want)).toBe(true);
const again = makeTorrent({
name: "Real.Pieces",
pieceLength: 16384,
files: [
{ path: "a.mkv", length: 20000 },
{ path: "Subs/a.ass", length: 30000 },
],
realPieces: true,
});
expect(again.hash).toBe(t.hash);
expect(
makeTorrent({ name: "x", length: 10, realPieces: () => new Uint8Array(10) }).contents?.[0]?.bytes,
).toHaveLength(10);
expect(() => makeTorrent({ name: "x", length: 10, realPieces: () => new Uint8Array(3) })).toThrow();
});
});