Google Drive под ключами сервисных аккаунтов вместо rclone: клиент Drive API, папка приёма и выгрузка материалов; команда khb-drive для агентов (builder - строителям и проектным чатам, полный - руководителю); rclone удалён; промты; тесты
All checks were successful
ci / test (push) Successful in 25s
ci / deploy (push) Successful in 3m13s

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-22 09:41:33 +03:00
parent c1f7c7b269
commit bfce62d66f
22 changed files with 805 additions and 103 deletions

View File

@@ -0,0 +1,191 @@
import { createReadStream, createWriteStream, statSync, readFileSync } from "node:fs";
import { Readable } from "node:stream";
import { pipeline } from "node:stream/promises";
const API = "https://www.googleapis.com/drive/v3";
const UPLOAD = "https://www.googleapis.com/upload/drive/v3";
const FIELDS = "id,name,mimeType,parents,modifiedTime,size,driveId,webViewLink";
export const FOLDER_MIME = "application/vnd.google-apps.folder";
const SMALL_UPLOAD = 8 * 1024 * 1024;
export interface DriveFile {
id: string;
name: string;
mimeType: string;
parents?: string[];
modifiedTime?: string;
size?: string;
driveId?: string;
webViewLink?: string;
}
export class DriveError extends Error {
constructor(
message: string,
readonly status: number,
) {
super(message);
}
}
/** Экранирование значения в запросе Drive (одинарные кавычки и обратные косые). */
export const q = (s: string): string => `'${s.replace(/\\/g, "\\\\").replace(/'/g, "\\'")}'`;
export const fileLink = (id: string): string => `https://drive.google.com/file/d/${id}/view`;
/**
* Минимальный клиент Google Drive API v3 под сервисным аккаунтом (общие диски поддерживаются во всех вызовах).
* Повторяет запросы при 429 и 5xx с нарастающей паузой.
*/
export class DriveClient {
constructor(
private token: () => Promise<string>,
private fetchFn: typeof fetch = fetch,
private sleep: (ms: number) => Promise<void> = (ms) => new Promise((r) => setTimeout(r, ms)),
) {}
private async request(method: string, url: string, init: { headers?: Record<string, string>; body?: BodyInit; duplex?: "half" } = {}, tries = 4): Promise<Response> {
for (let attempt = 1; ; attempt++) {
const res = await this.fetchFn(url, { method, headers: { authorization: `Bearer ${await this.token()}`, ...(init.headers ?? {}) }, body: init.body, ...(init.duplex ? { duplex: init.duplex } : {}) } as RequestInit);
if (res.ok) return res;
const retriable = res.status === 429 || res.status >= 500 || (res.status === 403 && /rateLimit|userRateLimit/i.test(await res.clone().text().catch(() => "")));
if (retriable && attempt < tries && !(init.body && typeof init.body === "object" && "getReader" in (init.body as object))) {
await this.sleep(500 * 2 ** (attempt - 1));
continue;
}
let msg = `${res.status}`;
try {
const j = (await res.json()) as { error?: { message?: string } };
msg = `${res.status} ${j.error?.message ?? ""}`.trim();
} catch {
/* тело не JSON */
}
throw new DriveError(`Google Drive: ${method} ${url.split("?")[0]?.replace(/^https:\/\/www\.googleapis\.com/, "")}: ${msg}`, res.status);
}
}
private async json<T>(method: string, url: string, body?: unknown): Promise<T> {
const res = await this.request(method, url, body === undefined ? {} : { headers: { "content-type": "application/json" }, body: JSON.stringify(body) });
return (await res.json()) as T;
}
/** Файлы по запросу (синтаксис Drive `q`), по всем доступным дискам, до limit штук. */
async list(query: string, opts: { limit?: number; orderBy?: string } = {}): Promise<DriveFile[]> {
const limit = opts.limit ?? 200;
const out: DriveFile[] = [];
let page = "";
do {
const u = new URL(`${API}/files`);
u.searchParams.set("q", query);
u.searchParams.set("corpora", "allDrives");
u.searchParams.set("includeItemsFromAllDrives", "true");
u.searchParams.set("supportsAllDrives", "true");
u.searchParams.set("pageSize", String(Math.min(limit - out.length, 200)));
u.searchParams.set("fields", `nextPageToken,files(${FIELDS})`);
if (opts.orderBy) u.searchParams.set("orderBy", opts.orderBy);
if (page) u.searchParams.set("pageToken", page);
const r = await this.json<{ files?: DriveFile[]; nextPageToken?: string }>("GET", u.toString());
out.push(...(r.files ?? []));
page = r.nextPageToken ?? "";
} while (page && out.length < limit);
return out.slice(0, limit);
}
async get(id: string): Promise<DriveFile> {
return this.json<DriveFile>("GET", `${API}/files/${encodeURIComponent(id)}?supportsAllDrives=true&fields=${FIELDS}`);
}
/** Содержимое папки (без удалённого в корзину). */
children(parentId: string, opts: { limit?: number; orderBy?: string } = {}): Promise<DriveFile[]> {
return this.list(`${q(parentId)} in parents and trashed = false`, opts);
}
async findChild(parentId: string, name: string, mimeType?: string): Promise<DriveFile | null> {
const r = await this.list(`${q(parentId)} in parents and name = ${q(name)} and trashed = false${mimeType ? ` and mimeType = ${q(mimeType)}` : ""}`, { limit: 1 });
return r[0] ?? null;
}
async createFolder(parentId: string, name: string): Promise<DriveFile> {
return this.json<DriveFile>("POST", `${API}/files?supportsAllDrives=true&fields=${FIELDS}`, { name, mimeType: FOLDER_MIME, parents: [parentId] });
}
async ensureFolder(parentId: string, name: string): Promise<DriveFile> {
return (await this.findChild(parentId, name, FOLDER_MIME)) ?? (await this.createFolder(parentId, name));
}
private async resumable(method: "POST" | "PATCH", path: string, meta: object | null, localPath: string, mimeType: string): Promise<DriveFile> {
const size = statSync(localPath).size;
const start = await this.request(method, `${UPLOAD}${path}${path.includes("?") ? "&" : "?"}uploadType=resumable&supportsAllDrives=true&fields=${FIELDS}`, {
headers: { "content-type": "application/json; charset=UTF-8", "x-upload-content-type": mimeType, "x-upload-content-length": String(size) },
body: JSON.stringify(meta ?? {}),
});
const location = start.headers.get("location");
if (!location) throw new DriveError("Google Drive: не получен адрес загрузки", 500);
const body: BodyInit = size <= SMALL_UPLOAD ? new Uint8Array(readFileSync(localPath)) : (Readable.toWeb(createReadStream(localPath)) as unknown as BodyInit);
const res = await this.request("PUT", location, { headers: { "content-length": String(size), "content-type": mimeType }, body, ...(size > SMALL_UPLOAD ? { duplex: "half" as const } : {}) });
return (await res.json()) as DriveFile;
}
/** Загружает локальный файл в папку (новый файл). */
uploadFile(localPath: string, parentId: string, name: string, mimeType = "application/octet-stream"): Promise<DriveFile> {
return this.resumable("POST", "/files", { name, parents: [parentId] }, localPath, mimeType);
}
/** Заменяет содержимое существующего файла. */
updateContent(id: string, localPath: string, mimeType = "application/octet-stream"): Promise<DriveFile> {
return this.resumable("PATCH", `/files/${encodeURIComponent(id)}`, null, localPath, mimeType);
}
/** Загрузка с заменой: если в папке уже есть файл с таким именем и другим размером - обновляется, с тем же размером - пропускается. */
async upsertFile(localPath: string, parentId: string, name: string, mimeType?: string): Promise<{ file: DriveFile; action: "created" | "updated" | "same" }> {
const existing = await this.findChild(parentId, name);
if (!existing) return { file: await this.uploadFile(localPath, parentId, name, mimeType), action: "created" };
if (existing.size !== undefined && Number(existing.size) === statSync(localPath).size) return { file: existing, action: "same" };
return { file: await this.updateContent(existing.id, localPath, mimeType), action: "updated" };
}
async downloadTo(id: string, destPath: string): Promise<void> {
const res = await this.request("GET", `${API}/files/${encodeURIComponent(id)}?alt=media&supportsAllDrives=true`);
if (!res.body) throw new DriveError("Google Drive: пустой ответ при скачивании", 500);
await pipeline(Readable.fromWeb(res.body as never), createWriteStream(destPath));
}
/** Экспорт документа Google (Docs, Sheets, Slides) в текстовый формат. */
async exportText(id: string, mimeType: string): Promise<string> {
const res = await this.request("GET", `${API}/files/${encodeURIComponent(id)}/export?mimeType=${encodeURIComponent(mimeType)}`);
return res.text();
}
async downloadText(id: string): Promise<string> {
const res = await this.request("GET", `${API}/files/${encodeURIComponent(id)}?alt=media&supportsAllDrives=true`);
return res.text();
}
async copy(id: string, parentId?: string, name?: string): Promise<DriveFile> {
return this.json<DriveFile>("POST", `${API}/files/${encodeURIComponent(id)}/copy?supportsAllDrives=true&fields=${FIELDS}`, { ...(parentId ? { parents: [parentId] } : {}), ...(name ? { name } : {}) });
}
/** Перенос в другую папку (и, при необходимости, переименование). */
async move(id: string, newParentId: string, newName?: string): Promise<DriveFile> {
const cur = await this.get(id);
const remove = (cur.parents ?? []).filter((p) => p !== newParentId).join(",");
const u = `${API}/files/${encodeURIComponent(id)}?supportsAllDrives=true&addParents=${encodeURIComponent(newParentId)}${remove ? `&removeParents=${encodeURIComponent(remove)}` : ""}&fields=${FIELDS}`;
return this.json<DriveFile>("PATCH", u, newName ? { name: newName } : {});
}
async rename(id: string, name: string): Promise<DriveFile> {
return this.json<DriveFile>("PATCH", `${API}/files/${encodeURIComponent(id)}?supportsAllDrives=true&fields=${FIELDS}`, { name });
}
/** В корзину (не удаление навсегда). */
async trash(id: string): Promise<void> {
await this.json("PATCH", `${API}/files/${encodeURIComponent(id)}?supportsAllDrives=true&fields=id`, { trashed: true });
}
/** Поиск по названию и тексту; folderId - только внутри папки (прямые потомки). */
async search(text: string, opts: { folderId?: string; limit?: number } = {}): Promise<DriveFile[]> {
const t = q(text);
const where = `(name contains ${t} or fullText contains ${t}) and trashed = false${opts.folderId ? ` and ${q(opts.folderId)} in parents` : ""}`;
return this.list(where, { limit: opts.limit ?? 20, orderBy: "modifiedTime desc" });
}
}

View File

@@ -0,0 +1,238 @@
import { createVerify, generateKeyPairSync } from "node:crypto";
import { mkdtempSync, readFileSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { describe, expect, it } from "vitest";
import { DriveClient, DriveError, FOLDER_MIME, q, type DriveFile } from "./client.js";
import { createTokenProvider, parseServiceAccountKey } from "./service-account.js";
import { createGoogleDrive } from "../slack/drive.js";
import { DriveInbox } from "../slack/drive-inbox.js";
import { formatFiles, parseArgs, runKhbDrive } from "../tools/khb-drive.js";
const { privateKey, publicKey } = generateKeyPairSync("rsa", { modulusLength: 2048 });
const keyJson = { client_email: "sa@example.iam.gserviceaccount.com", private_key: privateKey.export({ type: "pkcs8", format: "pem" }).toString() };
const json = (body: unknown, init: ResponseInit = {}) => new Response(JSON.stringify(body), { status: 200, headers: { "content-type": "application/json" }, ...init });
describe("сервисный аккаунт Google: токен", () => {
it("ключ разбирается из строки и объекта, неполный отклоняется", () => {
expect(parseServiceAccountKey(JSON.stringify(keyJson)).client_email).toBe(keyJson.client_email);
expect(parseServiceAccountKey(keyJson).private_key).toContain("BEGIN PRIVATE KEY");
expect(() => parseServiceAccountKey({ client_email: "x" })).toThrow(/private_key/);
});
it("JWT подписан ключом, токен кэшируется и обновляется после истечения", async () => {
let calls = 0;
let now = 1_000_000;
const fetchFn = (async (_url: string, init: RequestInit) => {
calls++;
const assertion = new URLSearchParams(init.body as URLSearchParams).get("assertion")!;
const [h, c, s] = assertion.split(".");
expect(createVerify("RSA-SHA256").update(`${h}.${c}`).verify(publicKey, s!, "base64url")).toBe(true);
const claim = JSON.parse(Buffer.from(c!, "base64url").toString());
expect(claim).toMatchObject({ iss: keyJson.client_email, scope: "https://www.googleapis.com/auth/drive" });
return json({ access_token: `tok${calls}`, expires_in: 3600 });
}) as unknown as typeof fetch;
const token = createTokenProvider(parseServiceAccountKey(keyJson), { fetchFn, now: () => now });
expect(await token()).toBe("tok1");
expect(await token()).toBe("tok1");
expect(calls).toBe(1);
now += 3_600_000; // токен истёк
expect(await token()).toBe("tok2");
});
it("ошибка токена понятна", async () => {
const fetchFn = (async () => json({ error: "invalid_grant", error_description: "Invalid JWT" }, { status: 400 })) as unknown as typeof fetch;
await expect(createTokenProvider(parseServiceAccountKey(keyJson), { fetchFn })()).rejects.toThrow(/invalid_grant/);
});
});
/** Фейковый Google Drive API: журнал запросов и ответы по порядку. */
function fakeApi(responses: Array<(url: string, init: RequestInit) => Response>) {
const log: Array<{ method: string; url: string; body?: string }> = [];
let i = 0;
const fetchFn = (async (url: string, init: RequestInit = {}) => {
log.push({ method: init.method ?? "GET", url: String(url), body: typeof init.body === "string" ? init.body : undefined });
const r = responses[Math.min(i++, responses.length - 1)]!;
return r(String(url), init);
}) as unknown as typeof fetch;
const client = new DriveClient(async () => "T", fetchFn, async () => undefined);
return { client, log };
}
describe("DriveClient", () => {
it("экранирование запроса", () => {
expect(q("it's a \\ test")).toBe("'it\\'s a \\\\ test'");
});
it("list: все диски, постраничное чтение", async () => {
const { client, log } = fakeApi([() => json({ files: [{ id: "1", name: "a", mimeType: "x" }], nextPageToken: "P2" }), () => json({ files: [{ id: "2", name: "b", mimeType: "x" }] })]);
const files = await client.list("trashed = false", { limit: 50 });
expect(files.map((f) => f.id)).toEqual(["1", "2"]);
expect(log[0]!.url).toContain("corpora=allDrives");
expect(log[0]!.url).toContain("supportsAllDrives=true");
expect(log[1]!.url).toContain("pageToken=P2");
});
it("повтор при 503 и 429, затем успех; обычная ошибка 403 не повторяется и содержит текст Google", async () => {
const ok = () => json({ files: [] });
const a = fakeApi([() => json({}, { status: 503 }), () => json({}, { status: 429 }), ok]);
expect(await a.client.list("x")).toEqual([]);
expect(a.log).toHaveLength(3);
const b = fakeApi([() => json({ error: { message: "The caller does not have permission" } }, { status: 403 })]);
await expect(b.client.get("zzz")).rejects.toThrow(/does not have permission/);
expect(b.log).toHaveLength(1);
await expect(fakeApi([() => json({ error: { message: "nf" } }, { status: 404 })]).client.get("zzz")).rejects.toBeInstanceOf(DriveError);
});
it("ensureFolder: существующая папка не создаётся заново, отсутствующая создаётся", async () => {
const existing = fakeApi([() => json({ files: [{ id: "F1", name: "n", mimeType: FOLDER_MIME }] })]);
expect((await existing.client.ensureFolder("P", "n")).id).toBe("F1");
expect(existing.log).toHaveLength(1);
const created = fakeApi([() => json({ files: [] }), () => json({ id: "F2", name: "n", mimeType: FOLDER_MIME })]);
expect((await created.client.ensureFolder("P", "n")).id).toBe("F2");
expect(created.log[1]).toMatchObject({ method: "POST" });
expect(JSON.parse(created.log[1]!.body!)).toEqual({ name: "n", mimeType: FOLDER_MIME, parents: ["P"] });
});
it("upsertFile: новый файл загружается, одинакового размера пропускается, изменившийся обновляется", async () => {
const dir = mkdtempSync(join(tmpdir(), "llmtest-gd-"));
const path = join(dir, "t.txt");
writeFileSync(path, "12345");
const start = () => new Response(null, { status: 200, headers: { location: "https://upload.example/session1" } });
const done = () => json({ id: "NEW", name: "t.txt", mimeType: "text/plain" });
const created = fakeApi([() => json({ files: [] }), start, done]);
expect((await created.client.upsertFile(path, "P", "t.txt", "text/plain")).action).toBe("created");
expect(created.log[1]!.url).toContain("uploadType=resumable");
expect(created.log[2]).toMatchObject({ method: "PUT", url: "https://upload.example/session1" });
const same = fakeApi([() => json({ files: [{ id: "E", name: "t.txt", mimeType: "text/plain", size: "5" }] })]);
expect((await same.client.upsertFile(path, "P", "t.txt")).action).toBe("same");
expect(same.log).toHaveLength(1);
const upd = fakeApi([() => json({ files: [{ id: "E", name: "t.txt", mimeType: "text/plain", size: "3" }] }), start, () => json({ id: "E", name: "t.txt", mimeType: "text/plain" })]);
expect((await upd.client.upsertFile(path, "P", "t.txt")).action).toBe("updated");
expect(upd.log[1]).toMatchObject({ method: "PATCH" });
expect(upd.log[1]!.url).toContain("/files/E?");
});
it("move: добавляет новую папку и убирает прежние; downloadTo пишет файл", async () => {
const m = fakeApi([() => json({ id: "X", name: "f", mimeType: "x", parents: ["OLD"] }), () => json({ id: "X", name: "new", mimeType: "x", parents: ["NEW"] })]);
await m.client.move("X", "NEW", "new");
expect(m.log[1]!.url).toContain("addParents=NEW");
expect(m.log[1]!.url).toContain("removeParents=OLD");
expect(JSON.parse(m.log[1]!.body!)).toEqual({ name: "new" });
const dir = mkdtempSync(join(tmpdir(), "llmtest-gd-"));
const d = fakeApi([() => new Response("содержимое файла")]);
await d.client.downloadTo("X", join(dir, "o.txt"));
expect(readFileSync(join(dir, "o.txt"), "utf8")).toBe("содержимое файла");
});
it("search: по названию и тексту, в папке, без корзины", async () => {
const s = fakeApi([() => json({ files: [] })]);
await s.client.search("Boca Ciega", { folderId: "FOLD" });
const qs = decodeURIComponent(new URL(s.log[0]!.url).searchParams.get("q")!);
expect(qs).toContain("name contains 'Boca Ciega'");
expect(qs).toContain("fullText contains 'Boca Ciega'");
expect(qs).toContain("'FOLD' in parents");
expect(qs).toContain("trashed = false");
});
});
/** Фейковый клиент для сервиса (загрузка материалов, папка приёма). */
function memClient() {
const calls: string[] = [];
const client = {
ensureFolder: async (parent: string, name: string) => (calls.push(`ensureFolder ${parent}/${name}`), { id: `F_${name}`, name, mimeType: FOLDER_MIME } as DriveFile),
upsertFile: async (_p: string, parent: string, name: string) => (calls.push(`upsert ${parent}/${name}`), { file: { id: `ID_${name}`, name, mimeType: "x" } as DriveFile, action: "created" as const }),
};
return { client: client as unknown as DriveClient, calls };
}
describe("материалы чата и папка приёма на Google Drive", () => {
it("upload: подпапка в корне материалов, файлы по именам, ссылки на файлы", async () => {
const dir = mkdtempSync(join(tmpdir(), "llmtest-up-"));
writeFileSync(join(dir, "voice.m4a"), "a");
writeFileSync(join(dir, "voice.txt"), "t");
const { client, calls } = memClient();
const links = await createGoogleDrive(client, "ROOT").upload(dir, "2026-10-21_C1");
expect(calls[0]).toBe("ensureFolder ROOT/2026-10-21_C1");
expect(Object.keys(links).sort()).toEqual(["voice.m4a", "voice.txt"]);
expect(links["voice.m4a"]).toBe("https://drive.google.com/file/d/ID_voice.m4a/view");
});
it("DriveInbox: файлы папки канала скачиваются, принимаются и переносятся в _processed; папки и служебные файлы пропускаются", async () => {
const accepted: string[] = [];
const moved: string[] = [];
let listing: DriveFile[] = [
{ id: "idnote0001xx", name: "note.txt", mimeType: "text/plain", modifiedTime: "2026-01-01T10:00:00Z" },
{ id: "idvoice002xx", name: "voice.m4a", mimeType: "audio/mp4", modifiedTime: "2026-01-01T10:00:05Z" },
{ id: "x", name: "_processed", mimeType: FOLDER_MIME },
{ id: "y", name: ".hidden", mimeType: "text/plain" },
];
const client = {
findChild: async (_p: string, name: string) => (name === "CLLMTEST" ? ({ id: "CHAN", name } as DriveFile) : null),
children: async () => listing,
ensureFolder: async () => ({ id: "PROC", name: "_processed", mimeType: FOLDER_MIME }) as DriveFile,
downloadTo: async (id: string, dest: string) => writeFileSync(dest, id.startsWith("idnote") ? " текст сообщения " : "audio"),
move: async (id: string, parent: string, name?: string) => (moved.push(`${id}->${parent}:${name}`), (listing = listing.filter((f) => f.id !== id)), {} as DriveFile),
} as unknown as DriveClient;
const inbox = new DriveInbox({ client, rootFolderId: "ROOT", localRoot: mkdtempSync(join(tmpdir(), "llmtest-inbox-")), channels: async () => ["CLLMTEST", "CNONE"], accept: async (f) => (accepted.push(`${f.name}|${f.text ?? ""}`), true) });
expect(await inbox.scan()).toBe(2);
expect(accepted).toEqual(["note.txt|текст сообщения", "voice.m4a|"]);
expect(moved).toEqual(["idnote0001xx->PROC:idnote00_note.txt", "idvoice002xx->PROC:idvoice0_voice.m4a"]);
expect(await inbox.scan()).toBe(0);
});
});
describe("khb-drive (команда агента)", () => {
const run = async (argv: string[], client?: DriveClient, env: NodeJS.ProcessEnv = {}) => {
const out: string[] = [];
const err: string[] = [];
const code = await runKhbDrive(argv, env, (s) => out.push(s), (s) => err.push(s), client);
return { code, out: out.join("\n"), err: err.join("\n") };
};
it("разбор аргументов и таблица", () => {
expect(parseArgs(["search", "Boca", "Ciega", "--in", "F1", "--limit", "5", "--json"])).toEqual({ cmd: "search", args: ["Boca", "Ciega"], flags: { in: "F1", limit: "5" }, json: true });
const t = formatFiles([{ id: "1", name: "a\tb", mimeType: FOLDER_MIME, parents: ["P"] }, { id: "2", name: "Смета", mimeType: "application/vnd.google-apps.document", modifiedTime: "2026-01-01" }]);
expect(t.split("\n")[1]).toBe("1\ta b\tпапка\t\tP");
expect(t.split("\n")[2]).toContain("google-document");
});
it("без ключа - понятная ошибка; help и неизвестная команда", async () => {
expect((await run(["search", "x"])).err).toMatch(/KHB_DRIVE_KEY/);
expect((await run(["help"])).out).toContain("khb-drive search");
const u = await run(["fly"], {} as DriveClient);
expect(u.code).toBe(2);
expect(u.err).toContain("неизвестная команда");
});
it("search, ls, read (Google Docs, Sheets, текст), mkdir, move, ошибки API", async () => {
const doc = { id: "D", name: "doc", mimeType: "application/vnd.google-apps.document" } as DriveFile;
const sheet = { id: "S", name: "sheet", mimeType: "application/vnd.google-apps.spreadsheet" } as DriveFile;
const txt = { id: "T", name: "t.txt", mimeType: "text/plain" } as DriveFile;
const png = { id: "I", name: "i.png", mimeType: "image/png" } as DriveFile;
const client = {
search: async (text: string, o: { folderId?: string }) => [{ id: "1", name: `найдено ${text} ${o.folderId ?? ""}`.trim(), mimeType: "x" }],
children: async () => [txt],
get: async (id: string) => ({ D: doc, S: sheet, T: txt, I: png })[id] ?? Promise.reject(new DriveError("Google Drive: GET /files/zz: 404 File not found", 404)),
exportText: async (_id: string, mime: string) => `export ${mime}`,
downloadText: async () => "обычный текст",
ensureFolder: async (parent: string, name: string) => ({ id: "NF", name, mimeType: FOLDER_MIME, parents: [parent] }),
move: async (id: string, parent: string, name?: string) => ({ id, name: name ?? "same", mimeType: "x", parents: [parent] }),
} as unknown as DriveClient;
expect((await run(["search", "Boca", "--in", "F"], client)).out).toContain("найдено Boca F");
expect((await run(["ls", "FOLDER"], client)).out).toContain("t.txt");
expect((await run(["read", "D"], client)).out).toBe("export text/plain");
expect((await run(["read", "S"], client)).out).toBe("export text/csv");
expect((await run(["read", "T"], client)).out).toBe("обычный текст");
const bin = await run(["read", "I"], client);
expect(bin.code).toBe(1);
expect(bin.err).toMatch(/не читается напрямую/);
expect((await run(["mkdir", "Папка", "проекта", "--parent", "P"], client)).out).toContain("NF\tПапка проекта");
expect((await run(["move", "X", "--parent", "P", "--name", "n"], client)).out).toContain("X\tn");
expect((await run(["move", "X"], client)).code).toBe(2); // нужен --parent
const missing = await run(["info", "zz"], client);
expect(missing.code).toBe(1);
expect(missing.err).toMatch(/404/);
});
});

View File

@@ -0,0 +1,51 @@
import { createSign } from "node:crypto";
/** Ключ сервисного аккаунта Google (JSON-файл ключа). */
export interface ServiceAccountKey {
client_email: string;
private_key: string;
token_uri?: string;
}
export const DRIVE_SCOPE = "https://www.googleapis.com/auth/drive";
/** Разбирает ключ из JSON-строки или объекта; проверяет обязательные поля. */
export function parseServiceAccountKey(raw: unknown): ServiceAccountKey {
const o = typeof raw === "string" ? (JSON.parse(raw) as unknown) : raw;
const k = o as Partial<ServiceAccountKey> | null;
if (!k || typeof k.client_email !== "string" || typeof k.private_key !== "string") throw new Error("ключ сервисного аккаунта: нужны client_email и private_key");
return { client_email: k.client_email, private_key: k.private_key, token_uri: k.token_uri };
}
const b64 = (x: string) => Buffer.from(x).toString("base64url");
/** Провайдер access-токена по ключу сервисного аккаунта (JWT -> токен, с кэшем до истечения). */
export function createTokenProvider(key: ServiceAccountKey, opts: { scope?: string; fetchFn?: typeof fetch; now?: () => number } = {}): () => Promise<string> {
const fetchFn = opts.fetchFn ?? fetch;
const now = opts.now ?? (() => Date.now());
let cached: { token: string; expiresAt: number } | null = null;
let pending: Promise<string> | null = null;
async function fetchToken(): Promise<string> {
const iat = Math.floor(now() / 1000);
const uri = key.token_uri ?? "https://oauth2.googleapis.com/token";
const head = b64(JSON.stringify({ alg: "RS256", typ: "JWT" }));
const claim = b64(JSON.stringify({ iss: key.client_email, scope: opts.scope ?? DRIVE_SCOPE, aud: uri, iat, exp: iat + 3000 }));
const sig = createSign("RSA-SHA256").update(`${head}.${claim}`).sign(key.private_key, "base64url");
const res = await fetchFn(uri, {
method: "POST",
headers: { "content-type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({ grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer", assertion: `${head}.${claim}.${sig}` }),
});
const j = (await res.json()) as { access_token?: string; expires_in?: number; error?: string; error_description?: string };
if (!j.access_token) throw new Error(`токен Google не получен: ${j.error ?? res.status} ${j.error_description ?? ""}`.trim());
cached = { token: j.access_token, expiresAt: now() + (j.expires_in ?? 3600) * 1000 };
return j.access_token;
}
return async () => {
if (cached && cached.expiresAt - now() > 60_000) return cached.token;
pending ??= fetchToken().finally(() => (pending = null));
return pending;
};
}