@blackbelt-technology/pi-dashboard-gmail-plugin 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md ADDED
@@ -0,0 +1,82 @@
1
+ # @blackbelt-technology/pi-dashboard-gmail-plugin
2
+
3
+ Multi-account Gmail for pi agents, managed from the pi-dashboard.
4
+
5
+ - Guided Google Cloud setup (you bring your own OAuth client — Google offers no API to create one).
6
+ - Several Gmail accounts, each with its own **permission level**.
7
+ - Refresh tokens stay in the dashboard server; tools get a short-lived access token per call.
8
+ - Account-scoped tools; every write is confirmed by you.
9
+
10
+ ## Setup (Settings → General → Gmail)
11
+
12
+ The wizard walks through these steps. Each console link carries `?project=<id>`.
13
+
14
+ 1. **Project + Gmail API.** Create a Google Cloud project and enable the Gmail API — via the console links, or run the copyable commands yourself:
15
+ ```sh
16
+ gcloud projects create <project-id>
17
+ gcloud services enable gmail.googleapis.com --project <project-id>
18
+ ```
19
+ The dashboard never runs `gcloud`.
20
+ 2. **Branding.** Console → Google Auth Platform → Branding (older consoles: *APIs & Services → OAuth consent screen*). Fill in the app name and support email.
21
+ 3. **Audience.**
22
+ - Workspace organisation: **Internal**.
23
+ - Otherwise **External**, and add every Gmail address you will connect as a **test user**.
24
+ - For an **External** app in *Testing* status, Google expires refresh tokens after **7 days** (the panel shows a `testing: 7-day` badge). *Publish app* gives longer-lived tokens, with an "unverified app" warning at sign-in.
25
+ 4. **Client.** Clients → Create client → application type **Desktop app**. Download the JSON.
26
+ 5. **Upload** the `client_secret_*.json`. Only a Desktop (`installed`) client is accepted; a Web client is rejected.
27
+ 6. **Test sign-in** = add your first account.
28
+
29
+ Sign-in errors point back to the step that fixes them:
30
+
31
+ | Error | Fix in step |
32
+ |---|---|
33
+ | `access_denied` ("app not verified for this user") | 3 — add the address as a test user |
34
+ | `org_internal` | 3 — audience |
35
+ | `redirect_uri_mismatch`, Web client | 4 — create a **Desktop** client |
36
+ | `invalid_client` | 5 — re-upload the client JSON |
37
+
38
+ Remote dashboards: the sign-in listens on a `127.0.0.1` loopback port of the **dashboard host**. When your browser runs elsewhere, the redirect page fails to load — copy its full URL from the address bar and paste it into the flow view.
39
+
40
+ ## Permission levels
41
+
42
+ | Level | Google scopes requested | Tools allowed |
43
+ |---|---|---|
44
+ | `readonly` | `gmail.readonly` | `gmail_search`, `gmail_get`, `gmail_labels`, `gmail_attachments` |
45
+ | `draft` | `gmail.readonly gmail.compose` | + `gmail_draft` |
46
+ | `send` | `gmail.modify` | + `gmail_send`, `gmail_reply`, `gmail_modify`, `gmail_trash` |
47
+
48
+ - Raising a level re-consents with the new level's full scope set.
49
+ - Lowering a level applies immediately — the very next tool call is refused.
50
+
51
+ **Honest limit.** Levels are enforced by this plugin (the server refuses to lease a token for an operation above the level, and the tools re-check). They are **not** enforced by Google: an access token is valid for every scope Google granted — e.g. `gmail.compose` also permits sending. Levels control what the agent's tools may do, not what arbitrary in-process code could do with a token.
52
+
53
+ **Visibility.** Accounts are user-global: any pi session on this dashboard may use any connected account within its level. Every tool call must name its account (`account: "<alias or email>"`); there is no default.
54
+
55
+ ## Tools
56
+
57
+ | Tool | Level | Notes |
58
+ |---|---|---|
59
+ | `gmail_accounts` | — | Lists alias, email, level, status. |
60
+ | `gmail_search` | readonly | Gmail query syntax, metadata only, `maxResults` 1–50. |
61
+ | `gmail_get` | readonly | One message, or a thread (`thread: true`). |
62
+ | `gmail_labels` | readonly | Label ids + names. |
63
+ | `gmail_attachments` | readonly | List, or save one inside the session cwd (never overwrites; symlinked targets/parents refused — a parent directory swapped for a symlink mid-save by another local process is a documented residual race). |
64
+ | `gmail_draft` | draft | Confirmed. |
65
+ | `gmail_send` / `gmail_reply` | send | Confirmed; replies thread via `In-Reply-To` / `References` / `threadId`. |
66
+ | `gmail_modify` / `gmail_trash` | send | Confirmed. Archive = remove label `INBOX`. |
67
+
68
+ Writes need a UI to confirm: a headless session is blocked, and a dismissed or timed-out prompt counts as "no".
69
+
70
+ ## Prompt injection
71
+
72
+ Mail content is attacker-controlled. Mailbox-derived results are marked `details.untrusted = true` and declared to the optional `untrusted-content-guard` extension (reads untrusted, writes self-confirming). **Without the guard only the write confirmations protect you** — install it if agents read mail from strangers.
73
+
74
+ ## Storage and removal
75
+
76
+ - `~/.pi/agent/plugin-credentials.json`, namespace `gmail` (plaintext, mode 0600 — same posture as `auth.json`): the OAuth client and one record per account.
77
+ - **Revoke** in the panel calls Google's revoke endpoint (best effort) and deletes the local record. If Google cannot be reached, revoke manually at <https://myaccount.google.com/permissions>.
78
+ - Disabling or uninstalling the plugin does not revoke grants.
79
+
80
+ ## Testing
81
+
82
+ `PI_E2E_GOOGLE_BASE_URL` points every Google endpoint at a fake server. It is honoured **only** for `http://127.0.0.1:*` / `http://localhost:*`; any other value is ignored with a warning.
package/package.json ADDED
@@ -0,0 +1,75 @@
1
+ {
2
+ "name": "@blackbelt-technology/pi-dashboard-gmail-plugin",
3
+ "version": "0.8.0",
4
+ "description": "Multi-account Gmail for pi agents \u2014 guided Google OAuth setup, per-account permission levels, server-side token leasing and account-scoped Gmail tools with confirmed writes.",
5
+ "license": "MIT",
6
+ "publishConfig": {
7
+ "access": "public"
8
+ },
9
+ "type": "module",
10
+ "repository": {
11
+ "type": "git",
12
+ "url": "https://github.com/BlackBeltTechnology/pi-agent-dashboard",
13
+ "directory": "packages/gmail-plugin"
14
+ },
15
+ "exports": {
16
+ ".": {
17
+ "types": "./src/client/index.tsx",
18
+ "default": "./src/client/index.tsx"
19
+ },
20
+ "./client": {
21
+ "types": "./src/client/index.tsx",
22
+ "default": "./src/client/index.tsx"
23
+ },
24
+ "./server": {
25
+ "types": "./src/server/index.ts",
26
+ "default": "./src/server/index.ts"
27
+ },
28
+ "./bridge": {
29
+ "types": "./src/bridge/index.ts",
30
+ "default": "./src/bridge/index.ts"
31
+ }
32
+ },
33
+ "files": [
34
+ "src/",
35
+ "!**/AGENTS.md",
36
+ "!**/*.AGENTS.md",
37
+ "!**/__tests__",
38
+ "!**/*.test.ts",
39
+ "!**/*.test.tsx"
40
+ ],
41
+ "pi-dashboard-plugin": {
42
+ "id": "gmail",
43
+ "displayName": "Gmail",
44
+ "i18nCatalog": "catalog",
45
+ "priority": 210,
46
+ "client": "./src/client/index.tsx",
47
+ "server": "./src/server/index.ts",
48
+ "bridge": "./src/bridge/index.ts",
49
+ "configSchema": "./src/configSchema.json",
50
+ "claims": [
51
+ {
52
+ "slot": "settings-section",
53
+ "component": "GmailSettings",
54
+ "tab": "general"
55
+ }
56
+ ]
57
+ },
58
+ "peerDependencies": {
59
+ "fastify": "^5.0.0",
60
+ "react": ">=18.0.0",
61
+ "react-dom": ">=18.0.0"
62
+ },
63
+ "dependencies": {
64
+ "@blackbelt-technology/dashboard-plugin-runtime": "^0.8.0",
65
+ "@blackbelt-technology/pi-dashboard-shared": "^0.8.0",
66
+ "oauth4webapi": "^3.8.8",
67
+ "@fastify/rate-limit": "^11.2.0"
68
+ },
69
+ "devDependencies": {
70
+ "@types/react": "^19.0.0",
71
+ "@types/react-dom": "^19.0.0",
72
+ "react": "^19.0.0",
73
+ "react-dom": "^19.0.0"
74
+ }
75
+ }
@@ -0,0 +1,86 @@
1
+ /**
2
+ * Session-cwd confinement for attachment save / attach (design D6).
3
+ * - Windows device / UNC / drive forms rejected outright.
4
+ * - Containment via `isPathInside` on the REALPATH of the parent directory
5
+ * (a symlinked parent that escapes the cwd is refused).
6
+ * - Create with `wx` + `O_NOFOLLOW` where available: never overwrites, never
7
+ * follows a final-component symlink.
8
+ * Residual risk (documented, not prevented): a parent directory swapped for a
9
+ * symlink between the check and the create (TOCTOU).
10
+ * See change: add-gmail-plugin.
11
+ */
12
+ import { constants as fsc } from "node:fs";
13
+ import { open, readFile, realpath, stat } from "node:fs/promises";
14
+ import path from "node:path";
15
+ import { isPathInside } from "@blackbelt-technology/pi-dashboard-shared/path-containment.js";
16
+
17
+ export const MAX_ATTACH_BYTES = 20 * 1024 * 1024;
18
+
19
+ class PathRefusedError extends Error {
20
+ constructor(readonly code: "path_refused" | "exists" | "too_large") {
21
+ super(
22
+ code === "exists"
23
+ ? "path_refused: target already exists (attachments never overwrite)"
24
+ : code === "too_large"
25
+ ? "path_refused: file exceeds the 20 MiB attachment limit"
26
+ : "path_refused: path must stay inside the session working directory",
27
+ );
28
+ this.name = "PathRefusedError";
29
+ }
30
+ }
31
+
32
+ /** Device (`\\?\`, `\\.\`), UNC (`\\host`) and drive-letter (`C:`) forms. */
33
+ function isWindowsSpecial(p: string): boolean {
34
+ return /^[\\/]{2}/.test(p) || /^[a-zA-Z]:/.test(p) || p.includes("\0");
35
+ }
36
+
37
+ async function confined(cwd: string, target: string): Promise<{ realCwd: string; resolved: string }> {
38
+ if (!target || isWindowsSpecial(target)) throw new PathRefusedError("path_refused");
39
+ const realCwd = await realpath(cwd);
40
+ const resolved = path.resolve(realCwd, target);
41
+ if (!isPathInside(realCwd, resolved)) throw new PathRefusedError("path_refused");
42
+ return { realCwd, resolved };
43
+ }
44
+
45
+ /** Save `data` to `target` (relative to `cwd`), exclusive + no-follow. Returns the written path. */
46
+ export async function saveInsideCwd(cwd: string, target: string, data: Buffer): Promise<string> {
47
+ const { realCwd, resolved } = await confined(cwd, target);
48
+ let realParent: string;
49
+ try {
50
+ realParent = await realpath(path.dirname(resolved));
51
+ } catch {
52
+ throw new PathRefusedError("path_refused");
53
+ }
54
+ if (!isPathInside(realCwd, realParent)) throw new PathRefusedError("path_refused");
55
+ const finalPath = path.join(realParent, path.basename(resolved));
56
+ const flags = fsc.O_WRONLY | fsc.O_CREAT | fsc.O_EXCL | (fsc.O_NOFOLLOW ?? 0);
57
+ let fh: Awaited<ReturnType<typeof open>>;
58
+ try {
59
+ fh = await open(finalPath, flags, 0o600);
60
+ } catch (err) {
61
+ const code = (err as NodeJS.ErrnoException).code;
62
+ throw new PathRefusedError(code === "EEXIST" || code === "ELOOP" ? "exists" : "path_refused");
63
+ }
64
+ try {
65
+ await fh.writeFile(data);
66
+ } finally {
67
+ await fh.close();
68
+ }
69
+ return finalPath;
70
+ }
71
+
72
+ /** Read a file to attach; its realpath must stay inside `cwd`. */
73
+ export async function readInsideCwd(cwd: string, target: string): Promise<Buffer> {
74
+ const { realCwd, resolved } = await confined(cwd, target);
75
+ let real: string;
76
+ try {
77
+ real = await realpath(resolved);
78
+ } catch {
79
+ throw new PathRefusedError("path_refused");
80
+ }
81
+ if (!isPathInside(realCwd, real)) throw new PathRefusedError("path_refused");
82
+ const st = await stat(real);
83
+ if (!st.isFile()) throw new PathRefusedError("path_refused");
84
+ if (st.size > MAX_ATTACH_BYTES) throw new PathRefusedError("too_large");
85
+ return readFile(real);
86
+ }
@@ -0,0 +1,169 @@
1
+ /**
2
+ * Thin Gmail REST wrappers over `fetch` (design D6 — no `googleapis`).
3
+ * One access token per instance (one lease per tool call). 429 / 5xx surface
4
+ * as `rate_limited` / `gmail_unavailable` with Retry-After; NEVER retried here
5
+ * (no retry storm). Error messages never include the token.
6
+ * See change: add-gmail-plugin.
7
+ */
8
+ import { GmailToolError } from "./lease-client.js";
9
+
10
+ const GMAIL_TIMEOUT_MS = 30_000;
11
+
12
+ interface Header {
13
+ name: string;
14
+ value: string;
15
+ }
16
+
17
+ export interface GmailPart {
18
+ partId?: string;
19
+ mimeType?: string;
20
+ filename?: string;
21
+ headers?: Header[];
22
+ body?: { size?: number; data?: string; attachmentId?: string };
23
+ parts?: GmailPart[];
24
+ }
25
+
26
+ export interface GmailMessage {
27
+ id: string;
28
+ threadId: string;
29
+ snippet?: string;
30
+ labelIds?: string[];
31
+ payload?: GmailPart;
32
+ }
33
+
34
+ export class GmailApi {
35
+ constructor(
36
+ private readonly base: string,
37
+ private readonly token: string,
38
+ private readonly fetchImpl: typeof fetch = fetch,
39
+ ) {}
40
+
41
+ private async call<T>(method: string, pathAndQuery: string, body?: unknown): Promise<T> {
42
+ let res: Response;
43
+ try {
44
+ res = await this.fetchImpl(`${this.base}/users/me/${pathAndQuery}`, {
45
+ method,
46
+ headers: {
47
+ authorization: `Bearer ${this.token}`,
48
+ ...(body === undefined ? {} : { "content-type": "application/json" }),
49
+ },
50
+ body: body === undefined ? undefined : JSON.stringify(body),
51
+ signal: AbortSignal.timeout(GMAIL_TIMEOUT_MS),
52
+ });
53
+ } catch {
54
+ throw new GmailToolError("gmail_unavailable", "gmail_unavailable: could not reach the Gmail API");
55
+ }
56
+ if (res.ok) {
57
+ // batchModify / trash may answer 200 with an EMPTY body — not a failure.
58
+ const text = await res.text();
59
+ return (text.trim() ? JSON.parse(text) : {}) as T;
60
+ }
61
+ const retryAfter = res.headers.get("retry-after");
62
+ const after = retryAfter && /^\d{1,6}$/.test(retryAfter) ? ` retry after ${retryAfter} s` : "";
63
+ if (res.status === 429) {
64
+ throw new GmailToolError("rate_limited", `rate_limited: Gmail rate-limited the request;${after || " retry later"}`);
65
+ }
66
+ if (res.status >= 500) {
67
+ throw new GmailToolError("gmail_unavailable", `gmail_unavailable: Gmail returned ${res.status};${after || " retry later"}`);
68
+ }
69
+ if (res.status === 401) throw new GmailToolError("unauthorized", "unauthorized: Gmail rejected the access token");
70
+ if (res.status === 404) throw new GmailToolError("not_found", "not_found: no such message, thread or attachment");
71
+ throw new GmailToolError("gmail_error", `gmail_error: Gmail returned HTTP ${res.status}`);
72
+ }
73
+
74
+ list(q: string, maxResults: number) {
75
+ const qs = new URLSearchParams({ q, maxResults: String(maxResults) });
76
+ return this.call<{ messages?: { id: string; threadId: string }[] }>("GET", `messages?${qs}`);
77
+ }
78
+
79
+ getMessage(id: string, format: "full" | "metadata", metadataHeaders: string[] = []) {
80
+ const qs = new URLSearchParams({ format });
81
+ for (const h of metadataHeaders) qs.append("metadataHeaders", h);
82
+ return this.call<GmailMessage>("GET", `messages/${encodeURIComponent(id)}?${qs}`);
83
+ }
84
+
85
+ getThread(id: string) {
86
+ return this.call<{ id: string; messages?: GmailMessage[] }>("GET", `threads/${encodeURIComponent(id)}?format=full`);
87
+ }
88
+
89
+ labels() {
90
+ return this.call<{ labels?: { id: string; name: string; type?: string }[] }>("GET", "labels");
91
+ }
92
+
93
+ attachment(messageId: string, attachmentId: string) {
94
+ return this.call<{ data?: string; size?: number }>(
95
+ "GET",
96
+ `messages/${encodeURIComponent(messageId)}/attachments/${encodeURIComponent(attachmentId)}`,
97
+ );
98
+ }
99
+
100
+ createDraft(raw: string, threadId?: string) {
101
+ return this.call<{ id: string; message?: { id: string } }>("POST", "drafts", {
102
+ message: threadId ? { raw, threadId } : { raw },
103
+ });
104
+ }
105
+
106
+ send(raw: string, threadId?: string) {
107
+ return this.call<{ id: string; threadId: string }>("POST", "messages/send", threadId ? { raw, threadId } : { raw });
108
+ }
109
+
110
+ modify(ids: string[], addLabelIds: string[], removeLabelIds: string[]) {
111
+ return this.call<unknown>("POST", "messages/batchModify", { ids, addLabelIds, removeLabelIds });
112
+ }
113
+
114
+ trash(id: string) {
115
+ return this.call<unknown>("POST", `messages/${encodeURIComponent(id)}/trash`);
116
+ }
117
+ }
118
+
119
+ /** Case-insensitive header lookup. */
120
+ export function header(part: GmailPart | undefined, name: string): string | undefined {
121
+ const n = name.toLowerCase();
122
+ return part?.headers?.find((h) => h.name.toLowerCase() === n)?.value;
123
+ }
124
+
125
+ function decode(data: string | undefined): string {
126
+ return data ? Buffer.from(data, "base64url").toString("utf8") : "";
127
+ }
128
+
129
+ function walk(part: GmailPart | undefined, visit: (p: GmailPart) => void): void {
130
+ if (!part) return;
131
+ visit(part);
132
+ for (const p of part.parts ?? []) walk(p, visit);
133
+ }
134
+
135
+ /** Text body: first text/plain, else first text/html (flagged). */
136
+ export function extractBody(payload: GmailPart | undefined): { text: string; html: boolean } {
137
+ let plain: string | undefined;
138
+ let html: string | undefined;
139
+ walk(payload, (p) => {
140
+ if (p.filename) return;
141
+ if (plain === undefined && p.mimeType === "text/plain" && p.body?.data) plain = decode(p.body.data);
142
+ if (html === undefined && p.mimeType === "text/html" && p.body?.data) html = decode(p.body.data);
143
+ });
144
+ if (plain !== undefined) return { text: plain, html: false };
145
+ if (html !== undefined) return { text: html, html: true };
146
+ return { text: "", html: false };
147
+ }
148
+
149
+ export interface AttachmentInfo {
150
+ attachmentId: string;
151
+ filename: string;
152
+ mimeType: string;
153
+ size: number;
154
+ }
155
+
156
+ export function listAttachments(payload: GmailPart | undefined): AttachmentInfo[] {
157
+ const out: AttachmentInfo[] = [];
158
+ walk(payload, (p) => {
159
+ if (p.filename && p.body?.attachmentId) {
160
+ out.push({
161
+ attachmentId: p.body.attachmentId,
162
+ filename: p.filename,
163
+ mimeType: p.mimeType ?? "application/octet-stream",
164
+ size: p.body.size ?? 0,
165
+ });
166
+ }
167
+ });
168
+ return out;
169
+ }
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Gmail plugin bridge entry (pi extension). Registers the Gmail tools and
3
+ * declares them to the untrusted-content guard registry at load: reads →
4
+ * `untrusted`, writes → `selfConfirming` (they confirm themselves — no double
5
+ * prompt). Order-independent and inert without the guard (design D6).
6
+ * See change: add-gmail-plugin.
7
+ */
8
+ import { resolveGoogleEndpoints } from "../shared/endpoints.js";
9
+ import { LeaseClient } from "./lease-client.js";
10
+ import { createGmailTools, type GmailToolDef, READ_TOOLS, WRITE_TOOLS } from "./tools.js";
11
+
12
+ export const GUARD_REGISTRY_SYMBOL = Symbol.for("pi.untrusted-content-guard");
13
+
14
+ interface GuardRegistry {
15
+ declarations: Array<{ kind: "untrusted" | "selfConfirming"; names: string[] }>;
16
+ }
17
+
18
+ /** Push this plugin's declarations into the (possibly not-yet-loaded) guard registry. */
19
+ export function declareToGuard(host: Record<symbol, unknown> = globalThis as unknown as Record<symbol, unknown>): void {
20
+ const existing = host[GUARD_REGISTRY_SYMBOL] as GuardRegistry | undefined;
21
+ const reg: GuardRegistry =
22
+ existing && Array.isArray(existing.declarations) ? existing : { declarations: [] };
23
+ host[GUARD_REGISTRY_SYMBOL] = reg;
24
+ reg.declarations.push({ kind: "untrusted", names: [...READ_TOOLS] });
25
+ reg.declarations.push({ kind: "selfConfirming", names: [...WRITE_TOOLS] });
26
+ }
27
+
28
+ interface PiLike {
29
+ registerTool?: (tool: GmailToolDef) => void;
30
+ }
31
+
32
+ export default function activate(ctx: unknown): void {
33
+ const c = ctx as { pi?: PiLike } | PiLike;
34
+ const pi = ((c as { pi?: PiLike }).pi ?? c) as PiLike;
35
+ if (!pi || typeof pi.registerTool !== "function") return;
36
+ declareToGuard();
37
+ const tools = createGmailTools({ leases: new LeaseClient(), endpoints: resolveGoogleEndpoints() });
38
+ for (const tool of tools) pi.registerTool(tool);
39
+ }
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Bridge-side lease client (design D5). ONE lease per tool call over the
3
+ * private request lane — no bridge cache, so a lowered level refuses the very
4
+ * next call. The returned `tier` is re-checked against the op (defence in
5
+ * depth). Error codes from the server (`<code>: <detail>`) are parsed into
6
+ * `GmailToolError`. See change: add-gmail-plugin.
7
+ */
8
+ import {
9
+ type PluginLaneReply,
10
+ requestPluginServer,
11
+ } from "@blackbelt-technology/dashboard-plugin-runtime/bridge";
12
+ import { ACCOUNTS_TYPE, type AccountInfo, LEASE_TYPE, type LeaseReply, PLUGIN_ID } from "../shared/protocol.js";
13
+ import { isTier, type Op, tierAllows } from "../shared/scopes.js";
14
+
15
+ export type LaneRequest = (pluginId: string, type: string, payload?: unknown) => Promise<PluginLaneReply>;
16
+
17
+ export class GmailToolError extends Error {
18
+ constructor(
19
+ readonly code: string,
20
+ message: string,
21
+ ) {
22
+ super(message);
23
+ this.name = "GmailToolError";
24
+ }
25
+ }
26
+
27
+ function laneError(error: string): GmailToolError {
28
+ const m = /^([a-z_]{1,64}): ([\s\S]*)$/.exec(error);
29
+ if (m) return new GmailToolError(m[1] as string, `${m[1]}: ${m[2]}`);
30
+ if (error === "unavailable") {
31
+ return new GmailToolError("unavailable", "unavailable: the pi-dashboard is not connected; Gmail tools need it");
32
+ }
33
+ return new GmailToolError(error.slice(0, 64) || "lane_error", `Gmail lease failed: ${error.slice(0, 200)}`);
34
+ }
35
+
36
+ export class LeaseClient {
37
+ constructor(private readonly request: LaneRequest = requestPluginServer) {}
38
+
39
+ async lease(account: string, op: Op): Promise<LeaseReply> {
40
+ const reply = await this.request(PLUGIN_ID, LEASE_TYPE, { account, op });
41
+ if (!reply.ok) throw laneError(reply.error);
42
+ const r = reply.result as Partial<LeaseReply> | null;
43
+ if (!r || typeof r.accessToken !== "string" || !isTier(r.tier) || typeof r.email !== "string") {
44
+ throw new GmailToolError("bad_lease", "Gmail lease reply was malformed");
45
+ }
46
+ if (!tierAllows(r.tier, op)) {
47
+ throw new GmailToolError("tier_denied", `tier_denied: ${r.email} is at level "${r.tier}", which does not allow "${op}"`);
48
+ }
49
+ return r as LeaseReply;
50
+ }
51
+
52
+ async accounts(): Promise<AccountInfo[]> {
53
+ const reply = await this.request(PLUGIN_ID, ACCOUNTS_TYPE, {});
54
+ if (!reply.ok) throw laneError(reply.error);
55
+ return Array.isArray(reply.result) ? (reply.result as AccountInfo[]) : [];
56
+ }
57
+ }
@@ -0,0 +1,78 @@
1
+ /**
2
+ * Minimal RFC 2822 / MIME builder (design D6): UTF-8 headers (RFC 2047
3
+ * encoded-word), base64 bodies, optional multipart/mixed attachments, and the
4
+ * base64url `raw` Gmail expects. Header values are CR/LF-stripped (no header
5
+ * injection). See change: add-gmail-plugin.
6
+ */
7
+ import { randomBytes } from "node:crypto";
8
+
9
+ export interface MimeAttachment {
10
+ filename: string;
11
+ mimeType: string;
12
+ data: Buffer;
13
+ }
14
+
15
+ export interface MimeMessage {
16
+ to: string[];
17
+ cc?: string[];
18
+ bcc?: string[];
19
+ subject: string;
20
+ body: string;
21
+ inReplyTo?: string;
22
+ references?: string;
23
+ attachments?: MimeAttachment[];
24
+ }
25
+
26
+ const clean = (v: string): string => v.replace(/[\r\n]+/g, " ").trim();
27
+
28
+ /** RFC 2047 `=?UTF-8?B?…?=` when the value is not plain ASCII. */
29
+ function encodeHeaderWord(v: string): string {
30
+ const c = clean(v);
31
+ if (/^[\x20-\x7e]*$/.test(c)) return c;
32
+ return `=?UTF-8?B?${Buffer.from(c, "utf8").toString("base64")}?=`;
33
+ }
34
+
35
+ const wrap76 = (b64: string): string => b64.replace(/.{1,76}/g, "$&\r\n").trimEnd();
36
+
37
+ function textPart(body: string): string {
38
+ return [
39
+ "Content-Type: text/plain; charset=UTF-8",
40
+ "Content-Transfer-Encoding: base64",
41
+ "",
42
+ wrap76(Buffer.from(body, "utf8").toString("base64")),
43
+ ].join("\r\n");
44
+ }
45
+
46
+ function attachmentPart(a: MimeAttachment): string {
47
+ // `"` and `\` are quoted-string specials: a trailing `\` would escape the closing quote.
48
+ const name = encodeHeaderWord(a.filename).replace(/["\\]/g, "_");
49
+ const type = /^[\w.+-]+\/[\w.+-]+$/.test(a.mimeType) ? a.mimeType : "application/octet-stream";
50
+ return [
51
+ `Content-Type: ${type}; name="${name}"`,
52
+ `Content-Disposition: attachment; filename="${name}"`,
53
+ "Content-Transfer-Encoding: base64",
54
+ "",
55
+ wrap76(a.data.toString("base64")),
56
+ ].join("\r\n");
57
+ }
58
+
59
+ /** Build the RFC 2822 message text. */
60
+ export function buildMime(m: MimeMessage): string {
61
+ const headers = [`To: ${m.to.map(clean).join(", ")}`];
62
+ if (m.cc?.length) headers.push(`Cc: ${m.cc.map(clean).join(", ")}`);
63
+ if (m.bcc?.length) headers.push(`Bcc: ${m.bcc.map(clean).join(", ")}`);
64
+ headers.push(`Subject: ${encodeHeaderWord(m.subject)}`);
65
+ if (m.inReplyTo) headers.push(`In-Reply-To: ${clean(m.inReplyTo)}`);
66
+ if (m.references) headers.push(`References: ${clean(m.references)}`);
67
+ headers.push("MIME-Version: 1.0");
68
+ if (!m.attachments?.length) return `${headers.join("\r\n")}\r\n${textPart(m.body)}\r\n`;
69
+ const boundary = `pi-gmail-${randomBytes(12).toString("hex")}`;
70
+ headers.push(`Content-Type: multipart/mixed; boundary="${boundary}"`);
71
+ const parts = [textPart(m.body), ...m.attachments.map(attachmentPart)];
72
+ return `${headers.join("\r\n")}\r\n\r\n${parts.map((p) => `--${boundary}\r\n${p}\r\n`).join("")}--${boundary}--\r\n`;
73
+ }
74
+
75
+ /** Gmail `raw`: base64url of the RFC 2822 text. */
76
+ export function toRaw(mime: string): string {
77
+ return Buffer.from(mime, "utf8").toString("base64url");
78
+ }