gmail-reader-mcp 0.0.0-stage → 1.0.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/LICENSE +674 -0
- package/README.md +84 -2
- package/dist/auth.d.ts +36 -0
- package/dist/auth.js +328 -0
- package/dist/files.d.ts +8 -0
- package/dist/files.js +32 -0
- package/dist/format.d.ts +10 -0
- package/dist/format.js +53 -0
- package/dist/mail.d.ts +80 -0
- package/dist/mail.js +265 -0
- package/dist/mcp-server.d.ts +2 -0
- package/dist/mcp-server.js +37 -0
- package/dist/text.d.ts +8 -0
- package/dist/text.js +70 -0
- package/dist/tools/authenticate/definition.d.ts +8 -0
- package/dist/tools/authenticate/definition.js +19 -0
- package/dist/tools/authenticate/index.d.ts +2 -0
- package/dist/tools/authenticate/index.js +10 -0
- package/dist/tools/authenticate/key.d.ts +1 -0
- package/dist/tools/authenticate/key.js +4 -0
- package/dist/tools/authenticate/schema.d.ts +3 -0
- package/dist/tools/authenticate/schema.js +5 -0
- package/dist/tools/download-attachment/definition.d.ts +8 -0
- package/dist/tools/download-attachment/definition.js +20 -0
- package/dist/tools/download-attachment/index.d.ts +2 -0
- package/dist/tools/download-attachment/index.js +10 -0
- package/dist/tools/download-attachment/key.d.ts +1 -0
- package/dist/tools/download-attachment/key.js +4 -0
- package/dist/tools/download-attachment/schema.d.ts +7 -0
- package/dist/tools/download-attachment/schema.js +14 -0
- package/dist/tools/download-attachments/definition.d.ts +8 -0
- package/dist/tools/download-attachments/definition.js +50 -0
- package/dist/tools/download-attachments/index.d.ts +2 -0
- package/dist/tools/download-attachments/index.js +10 -0
- package/dist/tools/download-attachments/key.d.ts +1 -0
- package/dist/tools/download-attachments/key.js +4 -0
- package/dist/tools/download-attachments/schema.d.ts +8 -0
- package/dist/tools/download-attachments/schema.js +20 -0
- package/dist/tools/get-email/definition.d.ts +8 -0
- package/dist/tools/get-email/definition.js +10 -0
- package/dist/tools/get-email/index.d.ts +2 -0
- package/dist/tools/get-email/index.js +10 -0
- package/dist/tools/get-email/key.d.ts +1 -0
- package/dist/tools/get-email/key.js +4 -0
- package/dist/tools/get-email/schema.d.ts +5 -0
- package/dist/tools/get-email/schema.js +9 -0
- package/dist/tools/get-emails/definition.d.ts +8 -0
- package/dist/tools/get-emails/definition.js +16 -0
- package/dist/tools/get-emails/index.d.ts +2 -0
- package/dist/tools/get-emails/index.js +10 -0
- package/dist/tools/get-emails/key.d.ts +1 -0
- package/dist/tools/get-emails/key.js +4 -0
- package/dist/tools/get-emails/schema.d.ts +5 -0
- package/dist/tools/get-emails/schema.js +11 -0
- package/dist/tools/get-thread/definition.d.ts +8 -0
- package/dist/tools/get-thread/definition.js +15 -0
- package/dist/tools/get-thread/index.d.ts +2 -0
- package/dist/tools/get-thread/index.js +10 -0
- package/dist/tools/get-thread/key.d.ts +1 -0
- package/dist/tools/get-thread/key.js +4 -0
- package/dist/tools/get-thread/schema.d.ts +5 -0
- package/dist/tools/get-thread/schema.js +9 -0
- package/dist/tools/index.d.ts +2 -0
- package/dist/tools/index.js +27 -0
- package/dist/tools/list-attachments/definition.d.ts +8 -0
- package/dist/tools/list-attachments/definition.js +13 -0
- package/dist/tools/list-attachments/index.d.ts +2 -0
- package/dist/tools/list-attachments/index.js +10 -0
- package/dist/tools/list-attachments/key.d.ts +1 -0
- package/dist/tools/list-attachments/key.js +4 -0
- package/dist/tools/list-attachments/schema.d.ts +5 -0
- package/dist/tools/list-attachments/schema.js +9 -0
- package/dist/tools/list-emails/definition.d.ts +10 -0
- package/dist/tools/list-emails/definition.js +25 -0
- package/dist/tools/list-emails/index.d.ts +2 -0
- package/dist/tools/list-emails/index.js +10 -0
- package/dist/tools/list-emails/key.d.ts +1 -0
- package/dist/tools/list-emails/key.js +4 -0
- package/dist/tools/list-emails/schema.d.ts +8 -0
- package/dist/tools/list-emails/schema.js +27 -0
- package/dist/tools/list-labels/definition.d.ts +8 -0
- package/dist/tools/list-labels/definition.js +14 -0
- package/dist/tools/list-labels/index.d.ts +2 -0
- package/dist/tools/list-labels/index.js +10 -0
- package/dist/tools/list-labels/key.d.ts +1 -0
- package/dist/tools/list-labels/key.js +4 -0
- package/dist/tools/list-labels/schema.d.ts +3 -0
- package/dist/tools/list-labels/schema.js +5 -0
- package/dist/tools/search-emails/definition.d.ts +8 -0
- package/dist/tools/search-emails/definition.js +17 -0
- package/dist/tools/search-emails/index.d.ts +2 -0
- package/dist/tools/search-emails/index.js +10 -0
- package/dist/tools/search-emails/key.d.ts +1 -0
- package/dist/tools/search-emails/key.js +4 -0
- package/dist/tools/search-emails/schema.d.ts +8 -0
- package/dist/tools/search-emails/schema.js +27 -0
- package/dist/tools/sign-out/definition.d.ts +8 -0
- package/dist/tools/sign-out/definition.js +17 -0
- package/dist/tools/sign-out/index.d.ts +2 -0
- package/dist/tools/sign-out/index.js +10 -0
- package/dist/tools/sign-out/key.d.ts +1 -0
- package/dist/tools/sign-out/key.js +4 -0
- package/dist/tools/sign-out/schema.d.ts +3 -0
- package/dist/tools/sign-out/schema.js +5 -0
- package/dist/tools/wrap.d.ts +13 -0
- package/dist/tools/wrap.js +44 -0
- package/package.json +56 -4
package/README.md
CHANGED
|
@@ -1,3 +1,85 @@
|
|
|
1
|
-
#
|
|
1
|
+
# gmail-reader-mcp
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
MCP (Model Context Protocol) server for reading Gmail through the Gmail API. Read-only by design: list, search, and fetch emails and whole threads — single or batched — and download attachments safely to disk.
|
|
4
|
+
|
|
5
|
+
## Tools
|
|
6
|
+
|
|
7
|
+
| Tool | Description |
|
|
8
|
+
| ---------------------- | ------------------------------------------------------------------------------------ |
|
|
9
|
+
| `authenticate` | Sign in with a Google URL shown directly in the chat; reports current account |
|
|
10
|
+
| `sign_out` | Revoke access at Google and remove the saved session; cancels any pending sign-in |
|
|
11
|
+
| `list_emails` | List emails in a label (default `INBOX`), optionally narrowed by a Gmail query |
|
|
12
|
+
| `search_emails` | Search all mail with Gmail search syntax (`from:`, `has:attachment`, `after:`, …) |
|
|
13
|
+
| `get_email` | Full content of one email (plain-text body, HTML converted) plus its attachment list |
|
|
14
|
+
| `get_emails` | Full content of up to 50 emails in one call |
|
|
15
|
+
| `get_thread` | Every message of a conversation, in order |
|
|
16
|
+
| `list_labels` | System and user labels with IDs and unread/total counts |
|
|
17
|
+
| `list_attachments` | Attachment part IDs, names, sizes, types, and inline flag for an email |
|
|
18
|
+
| `download_attachment` | Save one attachment to disk |
|
|
19
|
+
| `download_attachments` | Save several (or all) attachments of an email in one call |
|
|
20
|
+
|
|
21
|
+
## Setup
|
|
22
|
+
|
|
23
|
+
### 1. Create a Google Cloud OAuth client
|
|
24
|
+
|
|
25
|
+
You need your own OAuth client of type **Desktop app** with the Gmail API enabled. Using the Gmail API is free; no billing account is required.
|
|
26
|
+
|
|
27
|
+
**Option A — personal mode (recommended).** Open Google Cloud's [personal mode onboarding](https://console.cloud.google.com/auth/overview/personal?apis=ws&clientType=desktop) (the link preselects a **Desktop app** client and enables the Google Workspace APIs, Gmail included). Choose **Create a new project**, give the client a name, accept the User Data Policy, and click **Continue**. Copy the **Client ID** and **Client secret** it shows. The client only works for your own Google account and needs no consent-screen setup, test users, or app verification, so sign-in shows no "unverified app" warning.
|
|
28
|
+
|
|
29
|
+
**Option B — standard project** (if you can't use personal mode).
|
|
30
|
+
|
|
31
|
+
1. In the [Google Cloud console](https://console.cloud.google.com/projectcreate), create a project.
|
|
32
|
+
2. Enable the [Gmail API](https://console.cloud.google.com/apis/library/gmail.googleapis.com) for it.
|
|
33
|
+
3. Open [Google Auth Platform](https://console.cloud.google.com/auth/overview) and configure it: any app name, your email as support/contact, audience **External**.
|
|
34
|
+
4. Under **Data Access**, add the scope `https://www.googleapis.com/auth/gmail.readonly`.
|
|
35
|
+
5. Under **Audience**, add your Google account as a **test user**.
|
|
36
|
+
6. Under **Clients**, create a client of type **Desktop app**, and copy its **Client ID** and **Client secret**.
|
|
37
|
+
|
|
38
|
+
> **Testing mode limits:** while a standard project's publishing status is _Testing_, Google expires refresh tokens after 7 days, so you will be asked to sign in again about once a week (the tools tell the assistant when). Publishing the app removes that limit but requires a homepage, a privacy-policy URL and authorized domains on the Branding page. Standard projects also show a "Google hasn't verified this app" screen at sign-in — choose **Continue**, since it is your own app.
|
|
39
|
+
|
|
40
|
+
### 2. Configure your MCP client
|
|
41
|
+
|
|
42
|
+
```json
|
|
43
|
+
{
|
|
44
|
+
"mcpServers": {
|
|
45
|
+
"gmail-reader": {
|
|
46
|
+
"command": "npx",
|
|
47
|
+
"args": ["-y", "gmail-reader-mcp"],
|
|
48
|
+
"env": {
|
|
49
|
+
"GOOGLE_CLIENT_ID": "your-client-id.apps.googleusercontent.com",
|
|
50
|
+
"GOOGLE_CLIENT_SECRET": "your-client-secret"
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
Optional: `GMAIL_ACCOUNT=you@gmail.com` pre-selects that account on the Google sign-in page.
|
|
58
|
+
|
|
59
|
+
### 3. First run
|
|
60
|
+
|
|
61
|
+
Ask your assistant to run the `authenticate` tool (or just ask it to read your mail — any tool that needs auth will tell it to). The chat shows a Google sign-in URL: open it in a browser on the same machine and grant read-only Gmail access. The browser redirects to a short-lived listener on `127.0.0.1`, which completes the sign-in. The session is saved, so this only happens once per machine.
|
|
62
|
+
|
|
63
|
+
Google's device-code flow does not allow Gmail scopes, so the server uses the loopback flow (authorization code + PKCE) recommended for desktop apps.
|
|
64
|
+
|
|
65
|
+
## Credentials & security
|
|
66
|
+
|
|
67
|
+
- The OAuth client secret is never bundled with the package: you provide it via environment variables. For "Desktop app" clients, Google does not treat it as confidential, but keep it out of version control anyway.
|
|
68
|
+
- The refresh token is stored in the OS credential store (Windows Credential Manager / macOS Keychain / Linux Secret Service). If none is available it falls back to a permission-restricted file in the per-user app-data directory (`%LOCALAPPDATA%\gmail-reader-mcp`, `~/Library/Application Support/gmail-reader-mcp`, or `$XDG_CONFIG_HOME/gmail-reader-mcp`) and warns on stderr.
|
|
69
|
+
- The only scope requested is `gmail.readonly`; this server cannot send, modify, or delete mail.
|
|
70
|
+
- Attachment filenames are sanitized (path traversal, reserved characters) before writing to disk, and existing files are never overwritten.
|
|
71
|
+
- `sign_out` revokes the token at Google and deletes it locally. You can also revoke access anytime at [myaccount.google.com/permissions](https://myaccount.google.com/permissions).
|
|
72
|
+
|
|
73
|
+
## Development
|
|
74
|
+
|
|
75
|
+
```bash
|
|
76
|
+
npm install
|
|
77
|
+
cp .env.example .env # fill in GOOGLE_CLIENT_ID / GOOGLE_CLIENT_SECRET
|
|
78
|
+
npm run mcp # run from source (tsx)
|
|
79
|
+
npm run build # compile to dist/
|
|
80
|
+
npm run format # prettier
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
## License
|
|
84
|
+
|
|
85
|
+
GPL-3.0
|
package/dist/auth.d.ts
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { OAuth2Client } from 'google-auth-library';
|
|
2
|
+
export declare function getConfig(): {
|
|
3
|
+
clientId: string;
|
|
4
|
+
clientSecret: string;
|
|
5
|
+
};
|
|
6
|
+
/**
|
|
7
|
+
* Thrown when a request needs the user to sign in. Tool handlers surface the
|
|
8
|
+
* message as tool output so the model can tell the user exactly what to do —
|
|
9
|
+
* auth must never silently block inside a tool call.
|
|
10
|
+
*/
|
|
11
|
+
export declare class AuthRequiredError extends Error {
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Starts the OAuth loopback flow (Authorization Code + PKCE, redirect to a
|
|
15
|
+
* one-shot listener on 127.0.0.1) and resolves as soon as the consent URL is
|
|
16
|
+
* ready, while the listener keeps waiting in the background. Google's device
|
|
17
|
+
* code flow does not allow Gmail scopes, so loopback is the only option for
|
|
18
|
+
* a local app. Calling again while a flow is pending returns the same URL.
|
|
19
|
+
*/
|
|
20
|
+
export declare function startLoopbackAuth(): Promise<string>;
|
|
21
|
+
/**
|
|
22
|
+
* Signs out: cancels any pending sign-in, revokes the refresh token at Google
|
|
23
|
+
* (best effort), and deletes it from local storage. Returns the account that
|
|
24
|
+
* was removed, or null if none was stored.
|
|
25
|
+
*/
|
|
26
|
+
export declare function clearAuth(): Promise<{
|
|
27
|
+
email: string | null;
|
|
28
|
+
revoked: boolean;
|
|
29
|
+
}>;
|
|
30
|
+
/** Email of the signed-in account, or null when not authenticated. */
|
|
31
|
+
export declare function getSignedInAccount(): Promise<string | null>;
|
|
32
|
+
/**
|
|
33
|
+
* Returns an OAuth2 client with a valid access token. google-auth-library
|
|
34
|
+
* caches the access token and refreshes it automatically before expiry.
|
|
35
|
+
*/
|
|
36
|
+
export declare function getAuthClient(): Promise<OAuth2Client>;
|
package/dist/auth.js
ADDED
|
@@ -0,0 +1,328 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.AuthRequiredError = void 0;
|
|
7
|
+
exports.getConfig = getConfig;
|
|
8
|
+
exports.startLoopbackAuth = startLoopbackAuth;
|
|
9
|
+
exports.clearAuth = clearAuth;
|
|
10
|
+
exports.getSignedInAccount = getSignedInAccount;
|
|
11
|
+
exports.getAuthClient = getAuthClient;
|
|
12
|
+
const crypto_1 = require("crypto");
|
|
13
|
+
const fs_1 = __importDefault(require("fs"));
|
|
14
|
+
const http_1 = __importDefault(require("http"));
|
|
15
|
+
const os_1 = require("os");
|
|
16
|
+
const path_1 = __importDefault(require("path"));
|
|
17
|
+
const keyring_1 = require("@napi-rs/keyring");
|
|
18
|
+
const google_auth_library_1 = require("google-auth-library");
|
|
19
|
+
// Read-only: this server can never send, modify, or delete mail.
|
|
20
|
+
const SCOPES = ['https://www.googleapis.com/auth/gmail.readonly'];
|
|
21
|
+
const APP_DIR_NAME = 'gmail-reader-mcp';
|
|
22
|
+
const KEYRING_ACCOUNT = 'oauth-refresh-token';
|
|
23
|
+
// How long the loopback listener waits for the browser redirect.
|
|
24
|
+
const AUTH_TIMEOUT_MS = 10 * 60_000;
|
|
25
|
+
function getConfig() {
|
|
26
|
+
const clientId = process.env.GOOGLE_CLIENT_ID;
|
|
27
|
+
const clientSecret = process.env.GOOGLE_CLIENT_SECRET;
|
|
28
|
+
if (!clientId || !clientSecret) {
|
|
29
|
+
throw new Error('GOOGLE_CLIENT_ID and GOOGLE_CLIENT_SECRET environment variables are required. ' +
|
|
30
|
+
'Create a Google Cloud OAuth client of type "Desktop app" with the Gmail API ' +
|
|
31
|
+
'enabled and set both values from it.');
|
|
32
|
+
}
|
|
33
|
+
return { clientId, clientSecret };
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Per-user OS data directory, used only for the plaintext fallback. Tokens
|
|
37
|
+
* must never live inside the package or a project folder: they would be
|
|
38
|
+
* world-shared on global installs and one `git add -f` away from publishing.
|
|
39
|
+
*/
|
|
40
|
+
function dataDir() {
|
|
41
|
+
if (process.platform === 'win32') {
|
|
42
|
+
return path_1.default.join(process.env.LOCALAPPDATA ?? path_1.default.join((0, os_1.homedir)(), 'AppData', 'Local'), APP_DIR_NAME);
|
|
43
|
+
}
|
|
44
|
+
if (process.platform === 'darwin') {
|
|
45
|
+
return path_1.default.join((0, os_1.homedir)(), 'Library', 'Application Support', APP_DIR_NAME);
|
|
46
|
+
}
|
|
47
|
+
return path_1.default.join(process.env.XDG_CONFIG_HOME ?? path_1.default.join((0, os_1.homedir)(), '.config'), APP_DIR_NAME);
|
|
48
|
+
}
|
|
49
|
+
class KeyringStore {
|
|
50
|
+
entry = new keyring_1.AsyncEntry(APP_DIR_NAME, KEYRING_ACCOUNT);
|
|
51
|
+
async load() {
|
|
52
|
+
const raw = await this.entry.getPassword();
|
|
53
|
+
return raw ? parseCredentials(raw) : null;
|
|
54
|
+
}
|
|
55
|
+
async save(creds) {
|
|
56
|
+
await this.entry.setPassword(JSON.stringify(creds));
|
|
57
|
+
}
|
|
58
|
+
async clear() {
|
|
59
|
+
await this.entry.deleteCredential();
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
class FileStore {
|
|
63
|
+
file = path_1.default.join(dataDir(), 'credentials.json');
|
|
64
|
+
async load() {
|
|
65
|
+
try {
|
|
66
|
+
return parseCredentials(fs_1.default.readFileSync(this.file, 'utf8'));
|
|
67
|
+
}
|
|
68
|
+
catch {
|
|
69
|
+
return null;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
async save(creds) {
|
|
73
|
+
fs_1.default.mkdirSync(path_1.default.dirname(this.file), { recursive: true });
|
|
74
|
+
fs_1.default.writeFileSync(this.file, JSON.stringify(creds), { mode: 0o600 });
|
|
75
|
+
if (process.platform !== 'win32')
|
|
76
|
+
fs_1.default.chmodSync(this.file, 0o600);
|
|
77
|
+
}
|
|
78
|
+
async clear() {
|
|
79
|
+
fs_1.default.rmSync(this.file, { force: true });
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
function parseCredentials(raw) {
|
|
83
|
+
try {
|
|
84
|
+
const c = JSON.parse(raw);
|
|
85
|
+
return c.email && c.refreshToken
|
|
86
|
+
? { email: c.email, refreshToken: c.refreshToken }
|
|
87
|
+
: null;
|
|
88
|
+
}
|
|
89
|
+
catch {
|
|
90
|
+
return null;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
let storePromise = null;
|
|
94
|
+
function getStore() {
|
|
95
|
+
storePromise ??= (async () => {
|
|
96
|
+
const keyring = new KeyringStore();
|
|
97
|
+
try {
|
|
98
|
+
// Probe: a missing entry resolves null; an unusable store rejects.
|
|
99
|
+
await keyring.load();
|
|
100
|
+
return keyring;
|
|
101
|
+
}
|
|
102
|
+
catch (err) {
|
|
103
|
+
const fallback = new FileStore();
|
|
104
|
+
console.error(`Warning: OS credential store unavailable (${err instanceof Error ? err.message : err}). ` +
|
|
105
|
+
`Falling back to a plaintext token file in ${dataDir()} — protect this directory.`);
|
|
106
|
+
return fallback;
|
|
107
|
+
}
|
|
108
|
+
})();
|
|
109
|
+
return storePromise;
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Thrown when a request needs the user to sign in. Tool handlers surface the
|
|
113
|
+
* message as tool output so the model can tell the user exactly what to do —
|
|
114
|
+
* auth must never silently block inside a tool call.
|
|
115
|
+
*/
|
|
116
|
+
class AuthRequiredError extends Error {
|
|
117
|
+
}
|
|
118
|
+
exports.AuthRequiredError = AuthRequiredError;
|
|
119
|
+
let authedClient = null;
|
|
120
|
+
let pendingAuth = null;
|
|
121
|
+
function newClient(redirectUri) {
|
|
122
|
+
const { clientId, clientSecret } = getConfig();
|
|
123
|
+
return new google_auth_library_1.OAuth2Client({ clientId, clientSecret, redirectUri });
|
|
124
|
+
}
|
|
125
|
+
async function fetchEmailAddress(client) {
|
|
126
|
+
const res = await client.request({
|
|
127
|
+
url: 'https://gmail.googleapis.com/gmail/v1/users/me/profile',
|
|
128
|
+
});
|
|
129
|
+
return res.data.emailAddress;
|
|
130
|
+
}
|
|
131
|
+
function closePending() {
|
|
132
|
+
pendingAuth?.server.close();
|
|
133
|
+
pendingAuth = null;
|
|
134
|
+
}
|
|
135
|
+
function htmlPage(title, message) {
|
|
136
|
+
const esc = (s) => s.replace(/[&<>"']/g, (c) => ({
|
|
137
|
+
'&': '&',
|
|
138
|
+
'<': '<',
|
|
139
|
+
'>': '>',
|
|
140
|
+
'"': '"',
|
|
141
|
+
"'": ''',
|
|
142
|
+
})[c]);
|
|
143
|
+
return (`<!DOCTYPE html><html><head><meta charset="utf-8"><title>${esc(title)}</title></head>` +
|
|
144
|
+
`<body style="font-family:system-ui,sans-serif;max-width:32rem;margin:4rem auto;padding:0 1rem">` +
|
|
145
|
+
`<h1>${esc(title)}</h1><p>${esc(message)}</p></body></html>`);
|
|
146
|
+
}
|
|
147
|
+
/**
|
|
148
|
+
* Starts the OAuth loopback flow (Authorization Code + PKCE, redirect to a
|
|
149
|
+
* one-shot listener on 127.0.0.1) and resolves as soon as the consent URL is
|
|
150
|
+
* ready, while the listener keeps waiting in the background. Google's device
|
|
151
|
+
* code flow does not allow Gmail scopes, so loopback is the only option for
|
|
152
|
+
* a local app. Calling again while a flow is pending returns the same URL.
|
|
153
|
+
*/
|
|
154
|
+
async function startLoopbackAuth() {
|
|
155
|
+
if (pendingAuth && Date.now() < pendingAuth.expiresAt) {
|
|
156
|
+
return pendingAuth.url;
|
|
157
|
+
}
|
|
158
|
+
closePending();
|
|
159
|
+
getConfig();
|
|
160
|
+
const server = http_1.default.createServer();
|
|
161
|
+
await new Promise((resolve, reject) => {
|
|
162
|
+
server.once('error', reject);
|
|
163
|
+
server.listen(0, '127.0.0.1', () => resolve());
|
|
164
|
+
});
|
|
165
|
+
const { port } = server.address();
|
|
166
|
+
const redirectUri = `http://127.0.0.1:${port}`;
|
|
167
|
+
const client = newClient(redirectUri);
|
|
168
|
+
const { codeVerifier, codeChallenge } = await client.generateCodeVerifierAsync();
|
|
169
|
+
const state = (0, crypto_1.randomBytes)(16).toString('hex');
|
|
170
|
+
const url = client.generateAuthUrl({
|
|
171
|
+
access_type: 'offline',
|
|
172
|
+
// Force consent so Google always returns a refresh token, even if the
|
|
173
|
+
// user granted access before (e.g. after sign_out or a cache wipe).
|
|
174
|
+
prompt: 'consent',
|
|
175
|
+
scope: SCOPES,
|
|
176
|
+
state,
|
|
177
|
+
code_challenge: codeChallenge,
|
|
178
|
+
code_challenge_method: google_auth_library_1.CodeChallengeMethod.S256,
|
|
179
|
+
// Omit entirely when unset: an empty login_hint still ends up in the URL.
|
|
180
|
+
...(process.env.GMAIL_ACCOUNT
|
|
181
|
+
? { login_hint: process.env.GMAIL_ACCOUNT }
|
|
182
|
+
: {}),
|
|
183
|
+
});
|
|
184
|
+
// Every request carries a fresh pending object; handlers compare against it
|
|
185
|
+
// so a superseded listener can never complete the flow.
|
|
186
|
+
const pending = { url, expiresAt: Date.now() + AUTH_TIMEOUT_MS, server };
|
|
187
|
+
pendingAuth = pending;
|
|
188
|
+
const timer = setTimeout(() => {
|
|
189
|
+
if (pendingAuth === pending)
|
|
190
|
+
closePending();
|
|
191
|
+
else
|
|
192
|
+
server.close();
|
|
193
|
+
}, AUTH_TIMEOUT_MS);
|
|
194
|
+
timer.unref();
|
|
195
|
+
server.on('close', () => clearTimeout(timer));
|
|
196
|
+
server.on('request', async (req, res) => {
|
|
197
|
+
const reqUrl = new URL(req.url ?? '/', redirectUri);
|
|
198
|
+
const send = (status, title, message) => {
|
|
199
|
+
res.writeHead(status, { 'Content-Type': 'text/html; charset=utf-8' });
|
|
200
|
+
res.end(htmlPage(title, message));
|
|
201
|
+
};
|
|
202
|
+
if (reqUrl.pathname !== '/')
|
|
203
|
+
return send(404, 'Not found', '');
|
|
204
|
+
// Ignore anything not carrying our state (stray requests, CSRF).
|
|
205
|
+
if (reqUrl.searchParams.get('state') !== state) {
|
|
206
|
+
return send(400, 'Invalid request', 'State mismatch.');
|
|
207
|
+
}
|
|
208
|
+
const error = reqUrl.searchParams.get('error');
|
|
209
|
+
const code = reqUrl.searchParams.get('code');
|
|
210
|
+
try {
|
|
211
|
+
if (error)
|
|
212
|
+
throw new Error(`Google returned "${error}".`);
|
|
213
|
+
if (!code)
|
|
214
|
+
throw new Error('No authorization code in the redirect.');
|
|
215
|
+
const { tokens } = await client.getToken({
|
|
216
|
+
code,
|
|
217
|
+
codeVerifier,
|
|
218
|
+
redirect_uri: redirectUri,
|
|
219
|
+
});
|
|
220
|
+
if (!tokens.refresh_token) {
|
|
221
|
+
throw new Error('Google did not return a refresh token.');
|
|
222
|
+
}
|
|
223
|
+
if (!tokens.scope?.split(' ').includes(SCOPES[0])) {
|
|
224
|
+
throw new Error('Gmail read access was not granted. Sign in again and tick the Gmail permission box.');
|
|
225
|
+
}
|
|
226
|
+
client.setCredentials(tokens);
|
|
227
|
+
const email = await fetchEmailAddress(client);
|
|
228
|
+
const store = await getStore();
|
|
229
|
+
await store.save({ email, refreshToken: tokens.refresh_token });
|
|
230
|
+
authedClient = {
|
|
231
|
+
email,
|
|
232
|
+
client: newClientWithToken(tokens.refresh_token),
|
|
233
|
+
};
|
|
234
|
+
console.error(`Signed in as ${email}.`);
|
|
235
|
+
send(200, 'Signed in', `Gmail access granted for ${email}. You can close this tab and return to your assistant.`);
|
|
236
|
+
}
|
|
237
|
+
catch (err) {
|
|
238
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
239
|
+
console.error(`Sign-in did not complete: ${msg}`);
|
|
240
|
+
send(400, 'Sign-in failed', `${msg} Ask your assistant to try again.`);
|
|
241
|
+
}
|
|
242
|
+
finally {
|
|
243
|
+
if (pendingAuth === pending)
|
|
244
|
+
pendingAuth = null;
|
|
245
|
+
server.close();
|
|
246
|
+
}
|
|
247
|
+
});
|
|
248
|
+
console.error(`Open this URL to sign in to Gmail: ${url}`);
|
|
249
|
+
return url;
|
|
250
|
+
}
|
|
251
|
+
function newClientWithToken(refreshToken) {
|
|
252
|
+
const client = newClient();
|
|
253
|
+
client.setCredentials({ refresh_token: refreshToken });
|
|
254
|
+
return client;
|
|
255
|
+
}
|
|
256
|
+
/**
|
|
257
|
+
* Signs out: cancels any pending sign-in, revokes the refresh token at Google
|
|
258
|
+
* (best effort), and deletes it from local storage. Returns the account that
|
|
259
|
+
* was removed, or null if none was stored.
|
|
260
|
+
*/
|
|
261
|
+
async function clearAuth() {
|
|
262
|
+
closePending();
|
|
263
|
+
authedClient = null;
|
|
264
|
+
const store = await getStore();
|
|
265
|
+
const creds = await store.load();
|
|
266
|
+
if (!creds)
|
|
267
|
+
return { email: null, revoked: false };
|
|
268
|
+
let revoked = false;
|
|
269
|
+
try {
|
|
270
|
+
await newClient().revokeToken(creds.refreshToken);
|
|
271
|
+
revoked = true;
|
|
272
|
+
}
|
|
273
|
+
catch (err) {
|
|
274
|
+
console.error(`Token revocation failed (removing it locally anyway): ${err instanceof Error ? err.message : err}`);
|
|
275
|
+
}
|
|
276
|
+
await store.clear();
|
|
277
|
+
return { email: creds.email, revoked };
|
|
278
|
+
}
|
|
279
|
+
/** Email of the signed-in account, or null when not authenticated. */
|
|
280
|
+
async function getSignedInAccount() {
|
|
281
|
+
if (authedClient)
|
|
282
|
+
return authedClient.email;
|
|
283
|
+
const creds = await (await getStore()).load();
|
|
284
|
+
return creds?.email ?? null;
|
|
285
|
+
}
|
|
286
|
+
function isInvalidGrant(err) {
|
|
287
|
+
const e = err;
|
|
288
|
+
return (e?.response?.data?.error === 'invalid_grant' ||
|
|
289
|
+
/invalid_grant/.test(e?.message ?? ''));
|
|
290
|
+
}
|
|
291
|
+
/**
|
|
292
|
+
* Returns an OAuth2 client with a valid access token. google-auth-library
|
|
293
|
+
* caches the access token and refreshes it automatically before expiry.
|
|
294
|
+
*/
|
|
295
|
+
async function getAuthClient() {
|
|
296
|
+
if (!authedClient) {
|
|
297
|
+
const creds = await (await getStore()).load();
|
|
298
|
+
if (!creds) {
|
|
299
|
+
if (pendingAuth && Date.now() < pendingAuth.expiresAt) {
|
|
300
|
+
throw new AuthRequiredError(`Sign-in is still pending. Open this URL to grant access: ${pendingAuth.url}\n` +
|
|
301
|
+
'Retry this request after signing in.');
|
|
302
|
+
}
|
|
303
|
+
throw new AuthRequiredError('Not signed in to a Google account. Run the authenticate tool first, ' +
|
|
304
|
+
'then retry this request.');
|
|
305
|
+
}
|
|
306
|
+
authedClient = {
|
|
307
|
+
email: creds.email,
|
|
308
|
+
client: newClientWithToken(creds.refreshToken),
|
|
309
|
+
};
|
|
310
|
+
}
|
|
311
|
+
const { email, client } = authedClient;
|
|
312
|
+
try {
|
|
313
|
+
await client.getAccessToken();
|
|
314
|
+
}
|
|
315
|
+
catch (err) {
|
|
316
|
+
if (!isInvalidGrant(err))
|
|
317
|
+
throw err;
|
|
318
|
+
// Refresh token expired or revoked: drop it so the next authenticate run
|
|
319
|
+
// starts clean instead of looping on refresh failures.
|
|
320
|
+
authedClient = null;
|
|
321
|
+
await (await getStore()).clear();
|
|
322
|
+
throw new AuthRequiredError(`The saved session for ${email} has expired or was revoked. ` +
|
|
323
|
+
'(Apps whose OAuth consent screen is in "Testing" mode get refresh tokens ' +
|
|
324
|
+
'that expire after 7 days.) Run the authenticate tool to sign in again, ' +
|
|
325
|
+
'then retry this request.');
|
|
326
|
+
}
|
|
327
|
+
return client;
|
|
328
|
+
}
|
package/dist/files.d.ts
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Attachment names come from the email sender, so they must be treated as
|
|
3
|
+
* untrusted input: strip any path components (prevents `..\` traversal),
|
|
4
|
+
* control characters, and characters Windows rejects in filenames.
|
|
5
|
+
*/
|
|
6
|
+
export declare function sanitizeFilename(name: string): string;
|
|
7
|
+
/** Returns a path in `dir` that doesn't collide with an existing file. */
|
|
8
|
+
export declare function uniquePath(dir: string, filename: string): string;
|
package/dist/files.js
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.sanitizeFilename = sanitizeFilename;
|
|
4
|
+
exports.uniquePath = uniquePath;
|
|
5
|
+
const fs_1 = require("fs");
|
|
6
|
+
const path_1 = require("path");
|
|
7
|
+
/**
|
|
8
|
+
* Attachment names come from the email sender, so they must be treated as
|
|
9
|
+
* untrusted input: strip any path components (prevents `..\` traversal),
|
|
10
|
+
* control characters, and characters Windows rejects in filenames.
|
|
11
|
+
*/
|
|
12
|
+
function sanitizeFilename(name) {
|
|
13
|
+
const base = Array.from((0, path_1.basename)(name ?? ''))
|
|
14
|
+
.filter((c) => c.charCodeAt(0) >= 32)
|
|
15
|
+
.join('')
|
|
16
|
+
.replace(/[<>:"/\\|?*]/g, '_')
|
|
17
|
+
.replace(/^[. ]+|[. ]+$/g, '');
|
|
18
|
+
return base || 'attachment';
|
|
19
|
+
}
|
|
20
|
+
/** Returns a path in `dir` that doesn't collide with an existing file. */
|
|
21
|
+
function uniquePath(dir, filename) {
|
|
22
|
+
let candidate = (0, path_1.join)(dir, filename);
|
|
23
|
+
if (!(0, fs_1.existsSync)(candidate))
|
|
24
|
+
return candidate;
|
|
25
|
+
const ext = (0, path_1.extname)(filename);
|
|
26
|
+
const stem = filename.slice(0, filename.length - ext.length);
|
|
27
|
+
for (let i = 1;; i++) {
|
|
28
|
+
candidate = (0, path_1.join)(dir, `${stem} (${i})${ext}`);
|
|
29
|
+
if (!(0, fs_1.existsSync)(candidate))
|
|
30
|
+
return candidate;
|
|
31
|
+
}
|
|
32
|
+
}
|
package/dist/format.d.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { AttachmentInfo, EmailDetail, EmailSummary } from './mail.js';
|
|
2
|
+
export declare function text(value: string): {
|
|
3
|
+
content: {
|
|
4
|
+
type: "text";
|
|
5
|
+
text: string;
|
|
6
|
+
}[];
|
|
7
|
+
};
|
|
8
|
+
export declare function formatSummary(m: EmailSummary, index: number): string;
|
|
9
|
+
export declare function formatAttachment(a: AttachmentInfo, index: number): string;
|
|
10
|
+
export declare function formatDetail(m: EmailDetail): string;
|
package/dist/format.js
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.text = text;
|
|
4
|
+
exports.formatSummary = formatSummary;
|
|
5
|
+
exports.formatAttachment = formatAttachment;
|
|
6
|
+
exports.formatDetail = formatDetail;
|
|
7
|
+
const text_js_1 = require("./text.js");
|
|
8
|
+
function text(value) {
|
|
9
|
+
return { content: [{ type: 'text', text: value }] };
|
|
10
|
+
}
|
|
11
|
+
function formatSummary(m, index) {
|
|
12
|
+
return [
|
|
13
|
+
`[${index}] ID: ${m.id}`,
|
|
14
|
+
` Thread: ${m.threadId}`,
|
|
15
|
+
` Subject: ${m.subject}`,
|
|
16
|
+
` From: ${m.from}`,
|
|
17
|
+
` Date: ${m.date}`,
|
|
18
|
+
` Unread: ${m.unread} | Attachments: ${m.hasAttachments}`,
|
|
19
|
+
` Labels: ${m.labels.join(', ')}`,
|
|
20
|
+
` Snippet: ${m.snippet.slice(0, 200)}`,
|
|
21
|
+
].join('\n');
|
|
22
|
+
}
|
|
23
|
+
function formatAttachment(a, index) {
|
|
24
|
+
return [
|
|
25
|
+
`[${index}] Part ID: ${a.partId}`,
|
|
26
|
+
` Name: ${a.filename}`,
|
|
27
|
+
` Size: ${(0, text_js_1.formatSize)(a.size)}`,
|
|
28
|
+
` Type: ${a.mimeType}`,
|
|
29
|
+
` Inline: ${a.isInline}`,
|
|
30
|
+
].join('\n');
|
|
31
|
+
}
|
|
32
|
+
function formatDetail(m) {
|
|
33
|
+
const attachments = m.attachments.length
|
|
34
|
+
? m.attachments
|
|
35
|
+
.map((a) => `${a.filename} (part ${a.partId}, ${a.mimeType}, ${(0, text_js_1.formatSize)(a.size)}${a.isInline ? ', inline' : ''})`)
|
|
36
|
+
.join('; ')
|
|
37
|
+
: 'none';
|
|
38
|
+
const lines = [
|
|
39
|
+
`ID: ${m.id}`,
|
|
40
|
+
`Thread: ${m.threadId}`,
|
|
41
|
+
`Subject: ${m.subject}`,
|
|
42
|
+
`From: ${m.from}`,
|
|
43
|
+
`To: ${m.to}`,
|
|
44
|
+
];
|
|
45
|
+
if (m.cc)
|
|
46
|
+
lines.push(`Cc: ${m.cc}`);
|
|
47
|
+
if (m.replyTo)
|
|
48
|
+
lines.push(`Reply-To: ${m.replyTo}`);
|
|
49
|
+
lines.push(`Date: ${m.headerDate || m.date}`, `Labels: ${m.labels.join(', ')}`, `Attachments: ${attachments}`, m.bodyFormat === 'html-converted'
|
|
50
|
+
? '--- (body converted from HTML)'
|
|
51
|
+
: '---', m.body || '(no text body)');
|
|
52
|
+
return lines.join('\n');
|
|
53
|
+
}
|
package/dist/mail.d.ts
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { gmail_v1 } from '@googleapis/gmail';
|
|
2
|
+
export interface AttachmentInfo {
|
|
3
|
+
partId: string;
|
|
4
|
+
filename: string;
|
|
5
|
+
mimeType: string;
|
|
6
|
+
size: number;
|
|
7
|
+
isInline: boolean;
|
|
8
|
+
}
|
|
9
|
+
export declare function attachmentsOf(message: gmail_v1.Schema$Message): AttachmentInfo[];
|
|
10
|
+
export interface EmailSummary {
|
|
11
|
+
id: string;
|
|
12
|
+
threadId: string;
|
|
13
|
+
subject: string;
|
|
14
|
+
from: string;
|
|
15
|
+
to: string;
|
|
16
|
+
date: string;
|
|
17
|
+
unread: boolean;
|
|
18
|
+
labels: string[];
|
|
19
|
+
hasAttachments: boolean;
|
|
20
|
+
snippet: string;
|
|
21
|
+
}
|
|
22
|
+
export interface ListEmailsOptions {
|
|
23
|
+
query?: string;
|
|
24
|
+
labelIds?: string[];
|
|
25
|
+
maxResults?: number;
|
|
26
|
+
pageToken?: string;
|
|
27
|
+
includeSpamTrash?: boolean;
|
|
28
|
+
}
|
|
29
|
+
export interface ListEmailsResult {
|
|
30
|
+
emails: EmailSummary[];
|
|
31
|
+
nextPageToken?: string;
|
|
32
|
+
resultSizeEstimate?: number;
|
|
33
|
+
}
|
|
34
|
+
export declare function listEmails(options?: ListEmailsOptions): Promise<ListEmailsResult>;
|
|
35
|
+
export interface EmailDetail extends EmailSummary {
|
|
36
|
+
cc: string;
|
|
37
|
+
replyTo: string;
|
|
38
|
+
headerDate: string;
|
|
39
|
+
body: string;
|
|
40
|
+
bodyFormat: 'text' | 'html-converted' | 'none';
|
|
41
|
+
attachments: AttachmentInfo[];
|
|
42
|
+
}
|
|
43
|
+
export declare function getEmail(id: string): Promise<EmailDetail>;
|
|
44
|
+
export type BatchEmailResult = {
|
|
45
|
+
ok: true;
|
|
46
|
+
email: EmailDetail;
|
|
47
|
+
} | {
|
|
48
|
+
ok: false;
|
|
49
|
+
id: string;
|
|
50
|
+
error: string;
|
|
51
|
+
};
|
|
52
|
+
export declare function getEmails(ids: string[]): Promise<BatchEmailResult[]>;
|
|
53
|
+
export declare function getThread(id: string): Promise<EmailDetail[]>;
|
|
54
|
+
export interface LabelInfo {
|
|
55
|
+
id: string;
|
|
56
|
+
name: string;
|
|
57
|
+
type: string;
|
|
58
|
+
messagesTotal: number;
|
|
59
|
+
messagesUnread: number;
|
|
60
|
+
threadsTotal: number;
|
|
61
|
+
threadsUnread: number;
|
|
62
|
+
}
|
|
63
|
+
export declare function listLabels(): Promise<LabelInfo[]>;
|
|
64
|
+
/**
|
|
65
|
+
* Gmail attachment IDs change on every fetch, so they are useless as
|
|
66
|
+
* handles across tool calls. Attachments are addressed by MIME part ID
|
|
67
|
+
* instead (stable for a given message), and the current attachment ID is
|
|
68
|
+
* resolved at download time.
|
|
69
|
+
*/
|
|
70
|
+
export declare function getMessage(messageId: string): Promise<gmail_v1.Schema$Message>;
|
|
71
|
+
export declare function listAttachments(messageId: string): Promise<AttachmentInfo[]>;
|
|
72
|
+
/**
|
|
73
|
+
* Downloads one attachment by part ID. Pass `message` (fetched with
|
|
74
|
+
* getMessage) to avoid re-fetching it when downloading several parts.
|
|
75
|
+
*/
|
|
76
|
+
export declare function downloadAttachment(messageId: string, partId: string, message?: gmail_v1.Schema$Message): Promise<{
|
|
77
|
+
filename: string;
|
|
78
|
+
mimeType: string;
|
|
79
|
+
data: Buffer;
|
|
80
|
+
}>;
|