Письма подрядчикам: шаблон Артура, код письма, отправка через Gmail API от имени менеджера (делегирование домена)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -20,7 +20,7 @@ export function parseServiceAccountKey(raw: unknown): ServiceAccountKey {
|
||||
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> {
|
||||
export function createTokenProvider(key: ServiceAccountKey, opts: { scope?: string; subject?: 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;
|
||||
@@ -30,7 +30,7 @@ export function createTokenProvider(key: ServiceAccountKey, opts: { scope?: stri
|
||||
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 claim = b64(JSON.stringify({ iss: key.client_email, scope: opts.scope ?? DRIVE_SCOPE, ...(opts.subject ? { sub: opts.subject } : {}), 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",
|
||||
|
||||
87
packages/khbuild_assistant_prep/src/mail/gmail.ts
Normal file
87
packages/khbuild_assistant_prep/src/mail/gmail.ts
Normal file
@@ -0,0 +1,87 @@
|
||||
import { randomBytes } from "node:crypto";
|
||||
import { createTokenProvider, type ServiceAccountKey } from "../gdrive/service-account.js";
|
||||
|
||||
export const GMAIL_SEND_SCOPE = "https://www.googleapis.com/auth/gmail.send";
|
||||
|
||||
export interface Mailbox {
|
||||
email: string;
|
||||
name?: string;
|
||||
}
|
||||
|
||||
export interface OutgoingMail {
|
||||
from: Mailbox;
|
||||
to: Mailbox[];
|
||||
cc?: Mailbox[];
|
||||
subject: string;
|
||||
text: string;
|
||||
html: string;
|
||||
/** Message-ID без угловых скобок; по умолчанию генерируется. */
|
||||
messageId?: string;
|
||||
}
|
||||
|
||||
export interface SentMail {
|
||||
messageId: string;
|
||||
gmailId: string;
|
||||
threadId: string;
|
||||
sentAt: Date;
|
||||
}
|
||||
|
||||
const b64 = (s: string) => Buffer.from(s, "utf8").toString("base64");
|
||||
const wrap = (s: string) => s.replace(/(.{76})/g, "$1\r\n");
|
||||
/** Заголовок с не-ASCII символами - в кодировке RFC 2047. */
|
||||
const hdr = (s: string) => (/^[\x20-\x7e]*$/.test(s) ? s : `=?UTF-8?B?${b64(s)}?=`);
|
||||
const addr = (m: Mailbox) => (m.name ? `${hdr(m.name.replace(/["<>]/g, ""))} <${m.email}>` : m.email);
|
||||
|
||||
/** Собирает MIME (text + html) для отправки; адреса и заголовки без переводов строк. */
|
||||
export function buildMime(m: OutgoingMail, messageId: string, date: Date): string {
|
||||
for (const v of [m.subject, m.from.email, ...m.to.map((x) => x.email), ...(m.cc ?? []).map((x) => x.email)]) if (/[\r\n]/.test(v)) throw new Error("перевод строки в заголовке письма");
|
||||
const boundary = `khb_${randomBytes(8).toString("hex")}`;
|
||||
const part = (type: string, body: string) => `--${boundary}\r\nContent-Type: ${type}; charset=UTF-8\r\nContent-Transfer-Encoding: base64\r\n\r\n${wrap(b64(body))}\r\n`;
|
||||
return [
|
||||
`From: ${addr(m.from)}`,
|
||||
`To: ${m.to.map(addr).join(", ")}`,
|
||||
...(m.cc?.length ? [`Cc: ${m.cc.map(addr).join(", ")}`] : []),
|
||||
`Subject: ${hdr(m.subject)}`,
|
||||
`Date: ${date.toUTCString().replace("GMT", "+0000")}`,
|
||||
`Message-ID: <${messageId}>`,
|
||||
"MIME-Version: 1.0",
|
||||
`Content-Type: multipart/alternative; boundary="${boundary}"`,
|
||||
"",
|
||||
part("text/plain", m.text) + part("text/html", m.html) + `--${boundary}--`,
|
||||
].join("\r\n");
|
||||
}
|
||||
|
||||
export interface GmailSenderOpts {
|
||||
key: ServiceAccountKey;
|
||||
fetchFn?: typeof fetch;
|
||||
now?: () => Date;
|
||||
/** Домен для Message-ID. */
|
||||
domain?: string;
|
||||
}
|
||||
|
||||
/** Отправка через Gmail API от имени пользователя домена (делегирование на уровне домена, scope gmail.send). */
|
||||
export class GmailSender {
|
||||
private providers = new Map<string, () => Promise<string>>();
|
||||
constructor(private o: GmailSenderOpts) {}
|
||||
|
||||
private token(user: string): Promise<string> {
|
||||
let p = this.providers.get(user);
|
||||
if (!p) this.providers.set(user, (p = createTokenProvider(this.o.key, { scope: GMAIL_SEND_SCOPE, subject: user, fetchFn: this.o.fetchFn })));
|
||||
return p();
|
||||
}
|
||||
|
||||
async send(m: OutgoingMail): Promise<SentMail> {
|
||||
const now = (this.o.now ?? (() => new Date()))();
|
||||
const messageId = m.messageId ?? `${randomBytes(12).toString("hex")}@${this.o.domain ?? "khbuild.pro"}`;
|
||||
const raw = Buffer.from(buildMime(m, messageId, now), "utf8").toString("base64url");
|
||||
const f = this.o.fetchFn ?? fetch;
|
||||
const res = await f("https://gmail.googleapis.com/gmail/v1/users/me/messages/send", {
|
||||
method: "POST",
|
||||
headers: { authorization: `Bearer ${await this.token(m.from.email)}`, "content-type": "application/json" },
|
||||
body: JSON.stringify({ raw }),
|
||||
});
|
||||
const j = (await res.json()) as { id?: string; threadId?: string; error?: { message?: string } };
|
||||
if (!res.ok || !j.id) throw new Error(`Gmail: письмо не отправлено (${res.status}) ${j.error?.message ?? ""}`.trim());
|
||||
return { messageId, gmailId: j.id, threadId: j.threadId ?? "", sentAt: now };
|
||||
}
|
||||
}
|
||||
51
packages/khbuild_assistant_prep/src/mail/mail.test.ts
Normal file
51
packages/khbuild_assistant_prep/src/mail/mail.test.ts
Normal file
@@ -0,0 +1,51 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { GmailSender, buildMime } from "./gmail.js";
|
||||
import { longDate, newRef, renderStartEmail } from "./template.js";
|
||||
|
||||
const P = { ref: "KHB-261116-ABCD", contractor: "Tampa General", address: "1807 Pass a Grille Way, St. Pete Beach, FL 33706", date: "2026-11-16", managerName: "Walt Walker", managerPhone: "313-400-0090", managerEmail: "walter@khbuild.pro" };
|
||||
|
||||
describe("письмо подрядчику", () => {
|
||||
it("шаблон Артура: дата, адрес, подпись, код в теме и мелким шрифтом в конце", () => {
|
||||
const m = renderStartEmail(P);
|
||||
expect(m.subject).toBe("[KHB-261116-ABCD] Start of work at 1807 Pass a Grille Way, St. Pete Beach, FL 33706 on Monday, November 16, 2026");
|
||||
expect(m.text).toContain("Dear Tampa General Team,");
|
||||
expect(m.text).toContain("on Monday, November 16, 2026.");
|
||||
expect(m.text).toContain("Send invoices to invoice@khbuild.pro.");
|
||||
expect(m.text).toContain("For any questions, call me at 313-400-0090 or email walter@khbuild.pro.");
|
||||
expect(m.text.trim().endsWith("Ref: KHB-261116-ABCD")).toBe(true);
|
||||
expect(m.html).toContain("font-size:10px");
|
||||
expect(renderStartEmail({ ...P, work: "foundation pour" }).text).toContain("Scope: foundation pour.");
|
||||
});
|
||||
it("нет данных менеджера - письмо не строится", () => {
|
||||
expect(() => renderStartEmail({ ...P, managerPhone: "" })).toThrow();
|
||||
expect(() => longDate("16.11.2026")).toThrow();
|
||||
});
|
||||
it("код письма: KHB-ГГММДД-XXXX", () => {
|
||||
expect(newRef(new Date("2026-11-10T12:00:00Z"), () => "7F3A")).toBe("KHB-261110-7F3A");
|
||||
});
|
||||
it("MIME: заголовки, Cc, кодирование не-ASCII имени, защита от инъекции заголовков", () => {
|
||||
const base = { from: { email: "walter@khbuild.pro", name: "Walter Wálker" }, to: [{ email: "a@x.com", name: "A" }], cc: [{ email: "agents@khbuild.pro" }], subject: "s", text: "t", html: "<p>t</p>" };
|
||||
const mime = buildMime(base, "id1@khbuild.pro", new Date("2026-11-10T12:00:00Z"));
|
||||
expect(mime).toContain("Cc: agents@khbuild.pro");
|
||||
expect(mime).toContain("Message-ID: <id1@khbuild.pro>");
|
||||
expect(mime).toMatch(/From: =\?UTF-8\?B\?.+\?= <walter@khbuild.pro>/);
|
||||
expect(() => buildMime({ ...base, subject: "x\r\nBcc: evil@x.com" }, "i", new Date())).toThrow();
|
||||
});
|
||||
it("отправка: токен от имени отправителя (sub), запрос send с raw", async () => {
|
||||
const calls: { url: string; body: string }[] = [];
|
||||
const fetchFn = (async (url: string, init?: { body?: unknown }) => {
|
||||
const body = String(init?.body ?? "");
|
||||
calls.push({ url: String(url), body });
|
||||
if (String(url).includes("oauth2")) return new Response(JSON.stringify({ access_token: "tok", expires_in: 3600 }));
|
||||
return new Response(JSON.stringify({ id: "g1", threadId: "t1" }));
|
||||
}) as unknown as typeof fetch;
|
||||
const { generateKeyPairSync } = await import("node:crypto");
|
||||
const pem = generateKeyPairSync("rsa", { modulusLength: 2048 }).privateKey.export({ type: "pkcs8", format: "pem" }) as string;
|
||||
const s = new GmailSender({ key: { client_email: "sa@p.iam", private_key: pem }, fetchFn });
|
||||
const r = await s.send({ from: { email: "walter@khbuild.pro" }, to: [{ email: "a@x.com" }], subject: "s", text: "t", html: "h" });
|
||||
expect(r).toMatchObject({ gmailId: "g1", threadId: "t1" });
|
||||
const jwt = new URLSearchParams(calls[0]!.body).get("assertion")!.split(".")[1]!;
|
||||
expect(JSON.parse(Buffer.from(jwt, "base64url").toString()).sub).toBe("walter@khbuild.pro");
|
||||
expect(calls[1]!.url).toContain("/messages/send");
|
||||
});
|
||||
});
|
||||
71
packages/khbuild_assistant_prep/src/mail/template.ts
Normal file
71
packages/khbuild_assistant_prep/src/mail/template.ts
Normal file
@@ -0,0 +1,71 @@
|
||||
import { randomBytes } from "node:crypto";
|
||||
|
||||
/** Версия шаблона письма (пишется в журнал отправок). */
|
||||
export const TEMPLATE_VERSION = "contractor-start-v1";
|
||||
|
||||
export interface StartEmailParams {
|
||||
/** Код письма (KHB-ГГММДД-XXXX). */
|
||||
ref: string;
|
||||
/** Название подрядчика как в JobTread (для обращения «Dear X Team»). */
|
||||
contractor: string;
|
||||
/** Адрес объекта (job.location.address). */
|
||||
address: string;
|
||||
/** Дата начала работ, YYYY-MM-DD. */
|
||||
date: string;
|
||||
/** Необязательная фраза про вид работ, английский (например "foundation pour"). */
|
||||
work?: string;
|
||||
managerName: string;
|
||||
managerPhone: string;
|
||||
managerEmail: string;
|
||||
}
|
||||
|
||||
export interface RenderedEmail {
|
||||
subject: string;
|
||||
text: string;
|
||||
html: string;
|
||||
}
|
||||
|
||||
/** Код письма: KHB-ГГММДД-XXXX (дата отправки в UTC, 4 символа 0-9A-F). */
|
||||
export function newRef(now: Date = new Date(), rnd: () => string = () => randomBytes(2).toString("hex").toUpperCase()): string {
|
||||
const d = now.toISOString().slice(2, 10).replace(/-/g, "");
|
||||
return `KHB-${d}-${rnd()}`;
|
||||
}
|
||||
|
||||
/** «Monday, November 16, 2026» из YYYY-MM-DD (без зависимости от часового пояса сервера). */
|
||||
export function longDate(date: string): string {
|
||||
if (!/^\d{4}-\d{2}-\d{2}$/.test(date)) throw new Error(`дата должна быть YYYY-MM-DD: ${date}`);
|
||||
return new Date(`${date}T12:00:00Z`).toLocaleDateString("en-US", { weekday: "long", year: "numeric", month: "long", day: "numeric", timeZone: "UTC" });
|
||||
}
|
||||
|
||||
const esc = (s: string) => s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
||||
const clean = (s: string) => s.replace(/[\r\n\t]+/g, " ").trim();
|
||||
|
||||
/**
|
||||
* Шаблон Артура: вызов подрядчика на объект. Текст не придумывается агентом: только параметры.
|
||||
* Язык всегда английский. В конце мелким шрифтом код письма (для сопоставления ответов).
|
||||
*/
|
||||
export function renderStartEmail(p: StartEmailParams): RenderedEmail {
|
||||
const contractor = clean(p.contractor);
|
||||
const address = clean(p.address);
|
||||
const when = longDate(p.date);
|
||||
const work = p.work ? clean(p.work) : "";
|
||||
if (!contractor || !address || !p.managerName || !p.managerPhone || !p.managerEmail) throw new Error("не хватает данных для письма (подрядчик, адрес, имя/телефон/email менеджера)");
|
||||
const workLine = work ? ` Scope: ${work}.` : "";
|
||||
const paras = [
|
||||
`Dear ${contractor} Team,`,
|
||||
`You are scheduled to start work at ${address} on ${when}.${workLine}`,
|
||||
"Please work from the current approved plans, keep the site clean, and get any extra work approved in writing before you start it.",
|
||||
"Send invoices to invoice@khbuild.pro.",
|
||||
"Please reply to confirm.",
|
||||
`For any questions, call me at ${p.managerPhone} or email ${p.managerEmail}.`,
|
||||
];
|
||||
const sign = ["Thank you,", clean(p.managerName), "Project Manager, KH Build, LLC", `${p.managerPhone} | ${p.managerEmail}`];
|
||||
const subject = `[${p.ref}] Start of work at ${address} on ${when}`;
|
||||
const text = [...paras, `Thank you,\n\n${sign.slice(1).join("\n")}`, `Ref: ${p.ref}`].join("\n\n");
|
||||
const html =
|
||||
`<div style="font-family:Arial,Helvetica,sans-serif;font-size:14px;color:#222">` +
|
||||
paras.map((x) => `<p>${esc(x)}</p>`).join("") +
|
||||
`<p>Thank you,</p><p>${sign.slice(1).map(esc).join("<br>")}</p>` +
|
||||
`<p style="font-size:10px;color:#999">Ref: ${esc(p.ref)}</p></div>`;
|
||||
return { subject, text, html };
|
||||
}
|
||||
Reference in New Issue
Block a user