Files
khb_microservices/packages/accounting_automation/src/google.test.ts

129 lines
7.4 KiB
TypeScript

import { generateKeyPairSync, createVerify } from "node:crypto";
import { describe, expect, it } from "vitest";
import { GoogleAuth, buildServiceAccountJwt } from "./google.js";
import { GMAIL_SCOPE, GmailClient, parseGmailMessage } from "./gmail.js";
import { DriveClient } from "./drive.js";
const { privateKey, publicKey } = generateKeyPairSync("rsa", {
modulusLength: 2048,
privateKeyEncoding: { type: "pkcs8", format: "pem" },
publicKeyEncoding: { type: "spki", format: "pem" },
});
const key = { client_email: "sa@proj.iam.gserviceaccount.com", private_key: privateKey };
const dec = (s: string) => JSON.parse(Buffer.from(s, "base64url").toString("utf8"));
describe("GoogleAuth", () => {
it("JWT: структура, claims и подпись RS256", () => {
const jwt = buildServiceAccountJwt(key, ["a", "b"], "invoices@khbuild.pro", 1000);
const [h, c, s] = jwt.split(".");
expect(dec(h)).toEqual({ alg: "RS256", typ: "JWT" });
expect(dec(c)).toEqual({ iss: key.client_email, scope: "a b", aud: "https://oauth2.googleapis.com/token", iat: 1000, exp: 4600, sub: "invoices@khbuild.pro" });
expect(createVerify("RSA-SHA256").update(`${h}.${c}`).verify(publicKey, Buffer.from(s, "base64url"))).toBe(true);
});
it("без subject claim sub отсутствует", () => {
expect(dec(buildServiceAccountJwt(key, ["a"], undefined, 1).split(".")[1])).not.toHaveProperty("sub");
});
it("обмен на токен, кэш и обновление по истечении", async () => {
let calls = 0;
let t = new Date("2026-01-01T00:00:00Z");
const fetchFn = (async (url: string, init: RequestInit) => {
calls++;
expect(url).toBe("https://oauth2.googleapis.com/token");
const body = init.body as URLSearchParams;
expect(body.get("grant_type")).toBe("urn:ietf:params:oauth:grant-type:jwt-bearer");
expect(body.get("assertion")!.split(".")).toHaveLength(3);
return new Response(JSON.stringify({ access_token: `tok${calls}`, expires_in: 3600 }), { status: 200 });
}) as unknown as typeof fetch;
const auth = new GoogleAuth(key, { fetchFn, now: () => t });
expect(await auth.getAccessToken(["s"], "u@x")).toBe("tok1");
expect(await auth.getAccessToken(["s"], "u@x")).toBe("tok1");
expect(await auth.getAccessToken(["s"])).toBe("tok2"); // другой subject - другой токен
t = new Date(t.getTime() + 3600_000);
expect(await auth.getAccessToken(["s"], "u@x")).toBe("tok3");
});
it("ошибка обмена токена - исключение", async () => {
const fetchFn = (async () => new Response("bad", { status: 400 })) as unknown as typeof fetch;
await expect(new GoogleAuth(key, { fetchFn }).getAccessToken(["s"])).rejects.toThrow(/400/);
});
});
describe("Gmail: разбор ответов", () => {
const msgJson = {
id: "m1",
internalDate: "1767225600000",
payload: {
headers: [{ name: "From", value: "Bob <bob@vendor.com>" }, { name: "Subject", value: "Invoice 42" }],
parts: [
{ mimeType: "text/plain", body: { data: "aGk" } },
{ filename: "inv.pdf", mimeType: "application/pdf", body: { attachmentId: "att1" } },
{ filename: "photo.jpg", mimeType: "image/jpeg", body: { attachmentId: "att2" } },
{ mimeType: "multipart/mixed", parts: [{ filename: "inline.PDF", mimeType: "application/octet-stream", body: { data: Buffer.from("PDFDATA").toString("base64url") } }] },
],
},
};
it("parseGmailMessage: заголовки, PDF-вложения, дата", async () => {
const m = parseGmailMessage(msgJson, async (id) => Buffer.from(`bytes-${id}`));
expect(m).toMatchObject({ id: "m1", from: "Bob <bob@vendor.com>", subject: "Invoice 42" });
expect(m.receivedAt.toISOString()).toBe("2026-01-01T00:00:00.000Z");
expect(m.attachments.map((a) => a.filename)).toEqual(["inv.pdf", "inline.PDF"]);
expect((await m.attachments[0].getBytes()).toString()).toBe("bytes-att1");
expect((await m.attachments[1].getBytes()).toString()).toBe("PDFDATA");
});
it("GmailClient.listUnprocessed: пропускает обработанные, сторонние письма без PDF и берёт вложения", async () => {
const urls: string[] = [];
const fetchFn = (async (url: string, init: RequestInit) => {
urls.push(url);
expect((init.headers as Record<string, string>).authorization).toBe("Bearer T");
if (url.includes("/messages?")) return new Response(JSON.stringify({ messages: [{ id: "m0" }, { id: "m1" }, { id: "m2" }] }));
if (url.includes("/messages/m1/attachments/att1")) return new Response(JSON.stringify({ data: Buffer.from("PDF1").toString("base64url") }));
if (url.includes("/messages/m1")) return new Response(JSON.stringify(msgJson));
if (url.includes("/messages/m2")) return new Response(JSON.stringify({ id: "m2", payload: { headers: [], parts: [] } }));
throw new Error("unexpected " + url);
}) as unknown as typeof fetch;
const auth = { getAccessToken: async (scopes: string[], subject?: string) => {
expect(scopes).toEqual([GMAIL_SCOPE]);
expect(subject).toBe("invoices@khbuild.pro");
return "T";
} } as unknown as GoogleAuth;
const c = new GmailClient({ auth, user: "invoices@khbuild.pro", processedIds: async () => new Set(["m0"]), fetchFn });
const list = await c.listUnprocessed(10);
expect(list.map((m) => m.id)).toEqual(["m1"]);
expect((await list[0].attachments[0].getBytes()).toString()).toBe("PDF1");
expect(decodeURIComponent(urls[0])).toContain("q=has:attachment+filename:pdf".replace(/\+/g, "+"));
});
});
describe("Drive: запросы", () => {
it("ensureFolder ищет и создаёт папки, upload шлёт multipart, exportDocText берёт text/plain", async () => {
const calls: { url: string; method: string; body?: unknown }[] = [];
const fetchFn = (async (url: string, init: RequestInit = {}) => {
calls.push({ url, method: init.method ?? "GET", body: init.body });
if (url.includes("/files?q=")) {
const found = decodeURIComponent(url).includes("name='Инвойсы'");
return new Response(JSON.stringify({ files: found ? [{ id: "F1" }] : [] }));
}
if (url.includes("/files?supportsAllDrives=true&fields=id")) return new Response(JSON.stringify({ id: "F2" }));
if (url.includes("uploadType=multipart")) return new Response(JSON.stringify({ id: "FILE" }));
if (url.includes("/export")) return new Response("текст документа");
throw new Error("unexpected " + url);
}) as unknown as typeof fetch;
const auth = { getAccessToken: async () => "T" } as unknown as GoogleAuth;
const d = new DriveClient({ auth, rootFolderId: "ROOT", fetchFn });
expect(await d.ensureFolder(["Инвойсы", "ACME"])).toBe("F2");
expect(calls.every((c) => c.url.includes("supportsAllDrives=true"))).toBe(true);
const n = calls.length;
expect(await d.ensureFolder(["Инвойсы", "ACME"])).toBe("F2"); // из кэша
expect(calls.length).toBe(n);
expect(JSON.parse(calls[2].body as string)).toMatchObject({ name: "ACME", parents: ["F1"] });
expect(await d.upload("a.pdf", "application/pdf", Buffer.from("PDF"), "F2")).toEqual({ id: "FILE" });
const up = calls.find((c) => c.url.includes("uploadType=multipart"))!;
expect(Buffer.from(up.body as Buffer).toString()).toContain('"parents":["F2"]');
expect(await d.exportDocText("DOC")).toBe("текст документа");
});
});