Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

refactor: replace the generated Gmail client with a small authenticated adapter (#12219)

[._.]/ Adam Eivyca37153a67ad
diff --git a/docs/DEPS.md b/docs/DEPS.md
index 0fbae410f4..e1275a1f42 100644
--- a/docs/DEPS.md
+++ b/docs/DEPS.md
@@ -28,7 +28,7 @@ Before removing a Tier 3 candidate, run a transitive-dep check (`npm ls <pkg>`).
| `pdf-lib` | — | REPLACED | PDF generation | 2026-09-02 → `@cantoo/pdf-lib` (issue #5672). Abandoned upstream: `1.17.1` is simultaneously the pinned and the latest published version, unchanged since 2022-05-12. Not deprecated and never flagged by `npm audit` — replaced ahead of an advisory, not in response to one |
| `@novnc/novnc` | 1 | KEEP | PortDeck remote desktop viewer | Mature RFB/VNC protocol implementation; replacing it would require owning multiple security types and framebuffer encodings |
| `@googleapis/calendar` | 1 | KEEP | Calendar integration | Scoped official Google SDK (replaced monolithic `googleapis`) |
-| `@googleapis/gmail` | 1 | KEEP | Messages/Gmail integration | Scoped official Google SDK |
+| `@googleapis/gmail` | — | REPLACED | Messages/Gmail integration | Issue #12219 → `server/services/gmailApi.js`, a six-operation adapter over the `@googleapis/calendar` OAuth client's `request()` (fixed Gmail v1 origin; auth, refresh and transport stay upstream). Calendar still retains `googleapis-common`, Google auth and their transport dependencies, so this trims a direct dependency and its update churn, not that transitive supply chain |
| `better-sqlite3-multiple-ciphers` | 2 | KEEP | `server/services/signalSnapshot.js` — read-only SQLCipher snapshot of the local Signal Desktop database | MIT build of better-sqlite3 with SQLCipher 4 compatibility. Ships prebuilds and sets `gypfile` false, so install does not compile it. `node:sqlite` cannot open SQLCipher, and a main-file copy misses committed WAL frames (#11149). A missing prebuild fails that sync closed |
| `chokidar` | 1 | KEEP | server file watching | Mature cross-platform file-system watcher used by server services |
| `compression` | 1 | KEEP | server HTTP responses | Express-maintained Brotli and gzip negotiation for API and built client responses; preserves streaming and backpressure |
@@ -149,7 +149,7 @@ Before removing a Tier 3 candidate, run a transitive-dep check (`npm ls <pkg>`).
If `/do:depfree --heavy` is run, the following Tier 1 entries would drop to Tier 2/3 and become replacement candidates regardless of popularity:
-- `@googleapis/calendar` / `@googleapis/gmail` — narrow surface used; could be replaced with direct REST calls + owned auth.
+- `@googleapis/calendar` — narrow surface used; could be replaced with direct REST calls + owned auth (Gmail already is, via `gmailApi.js`).
- Many of the `@dnd-kit/*`, `@xterm/*`, `lucide-react`, `recharts` deps would be re-evaluated.
- `pm2` would NOT be replaced (foundational process manager).
diff --git a/server/package-lock.json b/server/package-lock.json
index f51e919b4e..e52e01a04d 100644
--- a/server/package-lock.json
+++ b/server/package-lock.json
@@ -11,7 +11,6 @@
"@babel/parser": "8.0.7",
"@cantoo/pdf-lib": "2.11.1",
"@googleapis/calendar": "20.1.0",
- "@googleapis/gmail": "22.0.2",
"@novnc/novnc": "1.7.0",
"better-sqlite3-multiple-ciphers": "13.0.3",
"chokidar": "5.0.0",
@@ -341,18 +340,6 @@
"node": ">=22.0.0"
}
},
- "node_modules/@googleapis/gmail": {
- "version": "22.0.2",
- "resolved": "https://registry.npmjs.org/@googleapis/gmail/-/gmail-22.0.2.tgz",
- "integrity": "sha512-/Yg6UwLZaI74jY4Q8RhAFlEw4q+71c47oKlqr3ArGTG4HERa0S5NgzmTjECcV720tATnz9bpIvAnJ91VVnNHVA==",
- "license": "Apache-2.0",
- "dependencies": {
- "googleapis-common": "^9.0.0"
- },
- "engines": {
- "node": ">=22.0.0"
- }
- },
"node_modules/@img/colour": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/@img/colour/-/colour-1.1.0.tgz",
diff --git a/server/package.json b/server/package.json
index f66eba0dc3..ac0f993b82 100644
--- a/server/package.json
+++ b/server/package.json
@@ -25,7 +25,6 @@
"@babel/parser": "8.0.7",
"@cantoo/pdf-lib": "2.11.1",
"@googleapis/calendar": "20.1.0",
- "@googleapis/gmail": "22.0.2",
"@novnc/novnc": "1.7.0",
"better-sqlite3-multiple-ciphers": "13.0.3",
"chokidar": "5.0.0",
diff --git a/server/routes/messageGmailReply.test.js b/server/routes/messageGmailReply.test.js
index d16806468e..f621a965c3 100644
--- a/server/routes/messageGmailReply.test.js
+++ b/server/routes/messageGmailReply.test.js
@@ -29,7 +29,7 @@ vi.mock('../services/googleAuth.js', () => ({
GOOGLE_API_TIMEOUT_MS: 30_000,
getAuthenticatedClient: async () => doubles.auth
}));
-vi.mock('@googleapis/gmail', () => ({ gmail: () => ({ users: { messages: { get: doubles.metadata, send: doubles.submit } } }) }));
+vi.mock('../services/gmailApi.js', () => ({ createGmailApi: () => ({ getMessage: doubles.metadata, sendMessage: doubles.submit }) }));
vi.mock('../services/messagePlaywrightSync.js', () => ({ getSelectors: vi.fn(), updateSelectors: vi.fn(), testSelectors: vi.fn(), launchProvider: vi.fn() }));
vi.mock('../services/messageEvaluator.js', () => ({ evaluateMessages: vi.fn(), generateReplyBody: vi.fn() }));
vi.mock('../services/messageActions.js', () => ({ executeAction: vi.fn() }));
@@ -47,13 +47,13 @@ const observeError = () => {};
beforeAll(() => errorEvents.on('error', observeError));
afterAll(() => errorEvents.off('error', observeError));
let app;
-const metadata = () => ({ data: {
+const metadata = () => ({
id: 'gmail-message-1', threadId: 'gmail-thread-1', payload: { headers: [
{ name: 'Message-ID', value: '<[email protected]>' },
{ name: 'References', value: '<[email protected]>\r\n <[email protected]>' },
{ name: 'Subject', value: 'Example conversation' }
] }
-} });
+});
beforeEach(() => {
vi.resetAllMocks();
@@ -65,7 +65,7 @@ beforeEach(() => {
};
doubles.metadata.mockResolvedValue(metadata());
doubles.auth.getAccessToken.mockResolvedValue({ token: 'example-token' });
- doubles.submit.mockResolvedValue({ data: { id: 'gmail-reply-1' } });
+ doubles.submit.mockResolvedValue({ id: 'gmail-reply-1' });
app = express();
app.use(express.json());
app.use('/api/messages', messagesRoutes);
@@ -88,12 +88,12 @@ describe('HTTP Gmail reply identity', () => {
expect((await request(app).post(`/api/messages/drafts/${id}/send`)).body).toEqual({ success: true });
expect((await getDraft(id)).status).toBe('sent');
expect(doubles.metadata).toHaveBeenCalledTimes(1);
- expect(doubles.metadata).toHaveBeenCalledWith({
- userId: 'me', id: 'gmail-message-1', format: 'metadata',
+ expect(doubles.metadata).toHaveBeenCalledWith('gmail-message-1', {
+ format: 'metadata',
metadataHeaders: ['Message-ID', 'References', 'In-Reply-To', 'Subject']
}, { timeout: 10_000, retry: false });
expect(doubles.submit).toHaveBeenCalledTimes(1);
- const [{ requestBody }, options] = doubles.submit.mock.calls[0];
+ const [requestBody, options] = doubles.submit.mock.calls[0];
expect(requestBody.threadId).toBe('gmail-thread-1');
expect(options).toEqual({ retry: false });
const mime = Buffer.from(requestBody.raw, 'base64url').toString('utf8');
@@ -108,12 +108,12 @@ describe('HTTP Gmail reply identity', () => {
it('fills an empty reply subject and uses the parent In-Reply-To when References are absent', async () => {
const data = metadata();
- data.data.payload.headers = data.data.payload.headers.filter(h => h.name !== 'References');
- data.data.payload.headers.push({ name: 'In-Reply-To', value: '<[email protected]>' });
+ data.payload.headers = data.payload.headers.filter(h => h.name !== 'References');
+ data.payload.headers.push({ name: 'In-Reply-To', value: '<[email protected]>' });
doubles.metadata.mockResolvedValue(data);
const id = await approvedReply({ subject: '', threadId: null });
expect((await request(app).post(`/api/messages/drafts/${id}/send`)).status).toBe(200);
- const mime = Buffer.from(doubles.submit.mock.calls[0][0].requestBody.raw, 'base64url').toString('utf8');
+ const mime = Buffer.from(doubles.submit.mock.calls[0][0].raw, 'base64url').toString('utf8');
expect(mime).toContain('References: <[email protected]> <[email protected]>\r\n');
expect(mime).toContain('Subject: Example conversation\r\n');
});
@@ -123,9 +123,9 @@ describe('HTTP Gmail reply identity', () => {
['wrong account', () => {}, { accountId: OTHER_ACCOUNT_ID }, 'REPLY_TARGET_NOT_FOUND'],
['local thread mismatch', () => {}, { threadId: 'other-local-thread' }, 'THREAD_MISMATCH'],
['metadata lookup failure', () => { doubles.metadata.mockRejectedValue(new Error('Example lookup failure')); }, {}, 'GMAIL_REPLY_METADATA_UNAVAILABLE'],
- ['provider identity mismatch', () => { const data = metadata(); data.data.id = 'other-gmail-message'; doubles.metadata.mockResolvedValue(data); }, {}, 'GMAIL_REPLY_METADATA_UNAVAILABLE'],
- ['provider thread mismatch', () => { const data = metadata(); data.data.threadId = 'other-gmail-thread'; doubles.metadata.mockResolvedValue(data); }, {}, 'GMAIL_REPLY_METADATA_UNAVAILABLE'],
- ['missing RFC identity', () => { const data = metadata(); data.data.payload.headers = data.data.payload.headers.filter(h => h.name !== 'Message-ID'); doubles.metadata.mockResolvedValue(data); }, {}, 'GMAIL_REPLY_METADATA_INVALID'],
+ ['provider identity mismatch', () => { const data = metadata(); data.id = 'other-gmail-message'; doubles.metadata.mockResolvedValue(data); }, {}, 'GMAIL_REPLY_METADATA_UNAVAILABLE'],
+ ['provider thread mismatch', () => { const data = metadata(); data.threadId = 'other-gmail-thread'; doubles.metadata.mockResolvedValue(data); }, {}, 'GMAIL_REPLY_METADATA_UNAVAILABLE'],
+ ['missing RFC identity', () => { const data = metadata(); data.payload.headers = data.payload.headers.filter(h => h.name !== 'Message-ID'); doubles.metadata.mockResolvedValue(data); }, {}, 'GMAIL_REPLY_METADATA_INVALID'],
['incompatible subject', () => {}, { subject: 'Different conversation' }, 'GMAIL_REPLY_SUBJECT_MISMATCH']
])('refuses %s without submission, approval consumption or send attempts', async (_label, arrange, overrides, code) => {
arrange();
@@ -153,7 +153,7 @@ describe('HTTP Gmail reply identity', () => {
const id = await approvedReply({ replyToMessageId: null, threadId: null, subject: 'New message' });
expect((await request(app).post(`/api/messages/drafts/${id}/send`)).status).toBe(200);
expect(doubles.metadata).not.toHaveBeenCalled();
- const body = doubles.submit.mock.calls[0][0].requestBody;
+ const body = doubles.submit.mock.calls[0][0];
expect(Object.keys(body)).toEqual(['raw']);
const mime = Buffer.from(body.raw, 'base64url').toString('utf8');
expect(mime).toContain('Subject: New message\r\n');
diff --git a/server/services/README.md b/server/services/README.md
index 32307663bd..50114d395e 100644
--- a/server/services/README.md
+++ b/server/services/README.md
@@ -11,6 +11,7 @@ image-generation paths below are useful entry points when tracing render jobs.
| `databaseMaintenanceCutover.js` | Internal cutover worker body (transfer → forward-only `.env` mode commit → server restart with target proof → release → CoS restart) and `recoverDatabaseCutover(id)` same-operation recovery for the CLI/API. |
| `databaseMaintenanceProducers.js` | Internal one-use coordinator stage: retain producer identity, stop this install's PM2 CoS/server, and verify fresh readback while admission remains fenced. |
| `databaseMaintenanceQuiescence.js` | Internal coordinator stage after producer shutdown: terminate verified running detached-writer groups, prove every registry record quiescent from process-table evidence, archive it with the operation, and refuse pending, legacy, orphaned, ambiguous or unregistered writers. |
+| `gmailApi.js` | Six-operation Gmail v1 adapter (`createGmailApi(auth)`) over the shared OAuth client's `request()`: fixed origin, encoded IDs, URLSearchParams queries, explicit JSON bodies. Callers pass `{ retry: false }` for send; auth, refresh and transport stay in `googleAuth.js`. |
| `imageGen/prepareParams.js` | Shared image request preparation and the canonical local image model selector. Use `selectLocalImageModelFromSettings()` for model identity and `resolveLocalImageModel()` when the caller must also enforce local runtime, hardware, and edit-image requirements. |
| `musicVideo/renderCancellation.js` | Shared capture-abort and ffmpeg kill selection for full/excerpt renders; records explicit cancellation before signaling and classifies nonzero closes without releasing ownership. |
| `musicVideo/sharingCopy.js` | Source-hashed private sharing MP4s: queued 720p H.264/AAC export, strict decimal 100 MB cap, supervised cancellation, verified download and owned-file cleanup. |
diff --git a/server/services/gmailApi.js b/server/services/gmailApi.js
new file mode 100644
index 0000000000..131ec46eb3
--- /dev/null
+++ b/server/services/gmailApi.js
@@ -0,0 +1,57 @@
+import { GOOGLE_API_TIMEOUT_MS } from './googleAuth.js';
+
+// Fixed origin: the adapter never accepts a caller-supplied URL, so the OAuth
+// bearer token can only be sent to the Gmail v1 "me" mailbox.
+const GMAIL_ORIGIN = 'https://gmail.googleapis.com/gmail/v1/users/me';
+
+/**
+ * Small authenticated adapter over the six Gmail v1 operations PortOS uses.
+ * Transport, token refresh and the 30s deadline come from the shared OAuth
+ * client's `request()`; this module only owns paths, queries and JSON bodies.
+ * Every method resolves to the parsed response body and rejects with the
+ * client's error (`err.response?.status` carries the HTTP status).
+ *
+ * @param {{ request: Function }} auth - authenticated OAuth2 client
+ */
+export function createGmailApi(auth) {
+ const call = (method, path, { query, body, options } = {}) => {
+ const search = query?.toString();
+ return auth.request({
+ url: `${GMAIL_ORIGIN}${path}${search ? `?${search}` : ''}`,
+ method,
+ timeout: GOOGLE_API_TIMEOUT_MS,
+ ...(body !== undefined && { data: body }),
+ ...options
+ }).then((res) => res.data);
+ };
+ const messagePath = (id) => `/messages/${encodeURIComponent(id)}`;
+
+ return {
+ listSendAs: () => call('GET', '/settings/sendAs'),
+
+ listMessages: ({ q, maxResults, pageToken }) => {
+ const query = new URLSearchParams();
+ if (q !== undefined) query.set('q', q);
+ if (maxResults !== undefined) query.set('maxResults', String(maxResults));
+ if (pageToken) query.set('pageToken', pageToken);
+ return call('GET', '/messages', { query });
+ },
+
+ // `options` overrides per-request transport settings (e.g. a shorter
+ // `timeout`, `retry: false`) without widening the endpoint surface.
+ getMessage: (id, { format, metadataHeaders = [] } = {}, options) => {
+ const query = new URLSearchParams();
+ if (format) query.set('format', format);
+ for (const header of metadataHeaders) query.append('metadataHeaders', header);
+ return call('GET', messagePath(id), { query, options });
+ },
+
+ // No idempotency key exists for send: the caller passes `retry: false` so
+ // the transport never resubmits after a lost acknowledgement.
+ sendMessage: (body, options) => call('POST', '/messages/send', { body, options }),
+
+ trashMessage: (id) => call('POST', `${messagePath(id)}/trash`),
+
+ modifyMessage: (id, body) => call('POST', `${messagePath(id)}/modify`, { body })
+ };
+}
diff --git a/server/services/gmailApi.test.js b/server/services/gmailApi.test.js
new file mode 100644
index 0000000000..11eef01cf2
--- /dev/null
+++ b/server/services/gmailApi.test.js
@@ -0,0 +1,99 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { auth as googleAuth } from '@googleapis/calendar';
+import { createGmailApi } from './gmailApi.js';
+import { messageLogError } from '../lib/messageLogError.js';
+
+// Real OAuth client and request pipeline; only the network (fetch) is stubbed,
+// so each captured call is exactly what Gmail would receive.
+const ORIGIN = 'https://gmail.googleapis.com/gmail/v1/users/me';
+const json = (status, body) => new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } });
+
+let calls;
+let answer;
+function client({ expired = false } = {}) {
+ const oauth = new googleAuth.OAuth2({
+ clientId: 'example-client', clientSecret: 'example-secret',
+ transporterOptions: {
+ fetchImplementation: async (url, init) => {
+ const text = init?.body ? String(init.body) : '';
+ calls.push({ url: String(url), method: init?.method || 'GET', headers: new Headers(init?.headers), body: text && String(url).startsWith(ORIGIN) ? JSON.parse(text) : undefined });
+ return answer(String(url));
+ }
+ }
+ });
+ oauth.setCredentials({ access_token: 'example-token', refresh_token: 'example-refresh', expiry_date: expired ? 1 : Date.now() + 3_600_000 });
+ return oauth;
+}
+
+beforeEach(() => {
+ calls = [];
+ answer = () => json(200, { ok: true });
+});
+
+describe('Gmail adapter HTTP contract', () => {
+ it('lists send-as aliases with a bearer token', async () => {
+ answer = () => json(200, { sendAs: [{ sendAsEmail: '[email protected]' }] });
+ expect(await createGmailApi(client()).listSendAs()).toEqual({ sendAs: [{ sendAsEmail: '[email protected]' }] });
+ expect(calls).toHaveLength(1);
+ expect(calls[0]).toMatchObject({ url: `${ORIGIN}/settings/sendAs`, method: 'GET' });
+ expect(calls[0].headers.get('authorization')).toBe('Bearer example-token');
+ });
+
+ it('builds list queries with URLSearchParams and omits an absent page token', async () => {
+ const api = createGmailApi(client());
+ await api.listMessages({ q: 'in:sent newer_than:14d & x=1', maxResults: 100, pageToken: 'next/page+1' });
+ await api.listMessages({ q: 'in:inbox', maxResults: 5 });
+ const first = new URL(calls[0].url);
+ expect(first.origin + first.pathname).toBe(`${ORIGIN}/messages`);
+ expect(Object.fromEntries(first.searchParams)).toEqual({ q: 'in:sent newer_than:14d & x=1', maxResults: '100', pageToken: 'next/page+1' });
+ expect([...new URL(calls[1].url).searchParams.keys()]).toEqual(['q', 'maxResults']);
+ });
+
+ it('escapes message IDs and repeats metadataHeaders', async () => {
+ await createGmailApi(client()).getMessage('a/b?c#d', { format: 'metadata', metadataHeaders: ['Message-ID', 'Subject'] });
+ const url = new URL(calls[0].url);
+ expect(url.pathname).toBe('/gmail/v1/users/me/messages/a%2Fb%3Fc%23d');
+ expect(url.searchParams.get('format')).toBe('metadata');
+ expect(url.searchParams.getAll('metadataHeaders')).toEqual(['Message-ID', 'Subject']);
+ });
+
+ it('posts send, trash and modify with explicit methods and JSON bodies', async () => {
+ const api = createGmailApi(client());
+ await api.sendMessage({ raw: 'ZXhhbXBsZQ', threadId: 'thread-1' }, { retry: false });
+ await api.trashMessage('m/1');
+ await api.modifyMessage('m/1', { removeLabelIds: ['INBOX'] });
+ expect(calls.map(c => [c.method, new URL(c.url).pathname, c.body])).toEqual([
+ ['POST', '/gmail/v1/users/me/messages/send', { raw: 'ZXhhbXBsZQ', threadId: 'thread-1' }],
+ ['POST', '/gmail/v1/users/me/messages/m%2F1/trash', undefined],
+ ['POST', '/gmail/v1/users/me/messages/m%2F1/modify', { removeLabelIds: ['INBOX'] }]
+ ]);
+ expect(calls[0].headers.get('content-type')).toContain('application/json');
+ });
+
+ it('surfaces provider errors with their HTTP status and no credentials or bodies in diagnostics', async () => {
+ answer = () => json(403, { error: { code: 403, message: 'Example denied' } });
+ const failure = await createGmailApi(client()).sendMessage({ raw: 'c2VjcmV0LWJvZHk' }, { retry: false }).catch(err => err);
+ expect(failure.response.status).toBe(403);
+ const logged = messageLogError(failure);
+ expect(logged).toContain('403');
+ for (const secret of ['example-token', 'example-refresh', 'example-secret', 'c2VjcmV0LWJvZHk']) expect(logged).not.toContain(secret);
+ });
+
+ it('refreshes an expired token once and then issues exactly one request', async () => {
+ answer = (url) => url.includes('oauth2.googleapis.com')
+ ? json(200, { access_token: 'refreshed-token', expires_in: 3600 })
+ : json(200, { id: 'm1' });
+ await createGmailApi(client({ expired: true })).sendMessage({ raw: 'ZXhhbXBsZQ' }, { retry: false });
+ const gmailCalls = calls.filter(c => c.url.startsWith(ORIGIN));
+ expect(calls.filter(c => c.url.includes('oauth2.googleapis.com'))).toHaveLength(1);
+ expect(gmailCalls).toHaveLength(1);
+ expect(gmailCalls[0].headers.get('authorization')).toBe('Bearer refreshed-token');
+ });
+
+ it('never resubmits a send after a server error, even by default retry policy', async () => {
+ answer = () => json(503, { error: { code: 503, message: 'Example backend error' } });
+ const failure = await createGmailApi(client()).sendMessage({ raw: 'ZXhhbXBsZQ' }, { retry: false }).catch(err => err);
+ expect(failure.response.status).toBe(503);
+ expect(calls).toHaveLength(1);
+ });
+});
diff --git a/server/services/messageActions.js b/server/services/messageActions.js
index c78120fcb2..0d79437a13 100644
--- a/server/services/messageActions.js
+++ b/server/services/messageActions.js
@@ -108,23 +108,19 @@ export async function executeAction(accountId, messageId, action) {
* Archive = remove INBOX label. Delete = move to trash.
*/
async function executeGmailApiAction(message, action) {
- const { gmail } = await import('@googleapis/gmail');
- const { getAuthenticatedClient, GOOGLE_API_TIMEOUT_MS } = await import('./googleAuth.js');
+ const { getAuthenticatedClient } = await import('./googleAuth.js');
+ const { createGmailApi } = await import('./gmailApi.js');
const auth = await getAuthenticatedClient();
if (!auth) throw new Error('Google OAuth not configured');
- const gmailClient = gmail({ version: 'v1', auth, timeout: GOOGLE_API_TIMEOUT_MS });
+ const gmailClient = createGmailApi(auth);
if (action === 'delete') {
- await gmailClient.users.messages.trash({ userId: 'me', id: message.apiId });
+ await gmailClient.trashMessage(message.apiId);
console.log(`📧 Gmail API: trashed ${message.id}`);
} else if (action === 'archive') {
- await gmailClient.users.messages.modify({
- userId: 'me',
- id: message.apiId,
- requestBody: { removeLabelIds: ['INBOX'] }
- });
+ await gmailClient.modifyMessage(message.apiId, { removeLabelIds: ['INBOX'] });
console.log(`📧 Gmail API: archived ${message.id}`);
}
}
diff --git a/server/services/messageActions.test.js b/server/services/messageActions.test.js
index 9739cc52ed..7c671230a3 100644
--- a/server/services/messageActions.test.js
+++ b/server/services/messageActions.test.js
@@ -6,7 +6,7 @@ vi.mock('./messageSync.js', () => ({ getMessage: mocks.message, removeMessageFro
vi.mock('./messagePlaywrightSync.js', () => ({ findOrOpenPage: async () => ({}), getPages: async () => [], isAuthPage: () => false, evaluateOnPage: mocks.evaluate }));
vi.mock('./messageTriageRules.js', () => ({ recordCorrection: mocks.correction }));
vi.mock('./googleAuth.js', () => ({ getAuthenticatedClient: async () => ({}), GOOGLE_API_TIMEOUT_MS: 30_000 }));
-vi.mock('@googleapis/gmail', () => ({ gmail: () => ({ users: { messages: { trash: mocks.trash, modify: mocks.modify } } }) }));
+vi.mock('./gmailApi.js', () => ({ createGmailApi: () => ({ trashMessage: mocks.trash, modifyMessage: mocks.modify }) }));
import { executeAction } from './messageActions.js';
const accountId = '11111111-1111-1111-1111-111111111111';
const message = { id: 'requested', subject: 'Status update', from: { name: 'Example Sender', email: '[email protected]' }, date: '2026-09-26 10:30' };
@@ -97,8 +97,8 @@ for (const provider of ['gmail', 'outlook']) describe(`${provider} browser ident
it('preserves Gmail API-by-ID archive and delete without browser calls', async () => {
mocks.account.mockResolvedValue({ type: 'gmail' }); mocks.message.mockResolvedValue({ ...message, apiId: 'api-target' });
await executeAction(accountId, message.id, 'delete'); await executeAction(accountId, message.id, 'archive');
- expect(mocks.trash).toHaveBeenCalledWith({ userId: 'me', id: 'api-target' });
- expect(mocks.modify).toHaveBeenCalledWith({ userId: 'me', id: 'api-target', requestBody: { removeLabelIds: ['INBOX'] } });
+ expect(mocks.trash).toHaveBeenCalledWith('api-target');
+ expect(mocks.modify).toHaveBeenCalledWith('api-target', { removeLabelIds: ['INBOX'] });
expect(mocks.evaluate).not.toHaveBeenCalled();
});
diff --git a/server/services/messageGmailSync.js b/server/services/messageGmailSync.js
index 956b0e9ed0..53257d959b 100644
--- a/server/services/messageGmailSync.js
+++ b/server/services/messageGmailSync.js
@@ -4,10 +4,10 @@
*/
import { messageLogError } from '../lib/messageLogError.js';
-import { gmail } from '@googleapis/gmail';
import { v4 as uuidv4 } from '../lib/uuid.js';
import crypto from 'crypto';
-import { getAuthenticatedClient, GOOGLE_API_TIMEOUT_MS } from './googleAuth.js';
+import { getAuthenticatedClient } from './googleAuth.js';
+import { createGmailApi } from './gmailApi.js';
import { htmlToText as sharedHtmlToText } from '../lib/htmlToText.js';
import { ServerError } from '../lib/errorHandler.js';
@@ -27,12 +27,12 @@ function makeExternalId(gmailId) {
* is normally itself a `sendAs` entry, so a healthy account returns at least `[primary]`.
*/
export async function fetchSendAsAliases(gmailClient) {
- const res = await gmailClient.users.settings.sendAs.list({ userId: 'me' }).catch((err) => {
+ const res = await gmailClient.listSendAs().catch((err) => {
console.warn(`📧 Gmail send-as alias fetch failed: ${messageLogError(err)}`);
return null;
});
if (!res) return null; // sentinel: fetch failed — do not clobber the stored aliases
- const list = res?.data?.sendAs || [];
+ const list = res?.sendAs || [];
return list.map((a) => String(a?.sendAsEmail || '').trim().toLowerCase()).filter(Boolean);
}
@@ -236,7 +236,7 @@ export async function syncGmail(account, cache, io, options = {}) {
return { messages: [], status: 'not-configured' };
}
- const gmailClient = gmail({ version: 'v1', auth, timeout: GOOGLE_API_TIMEOUT_MS });
+ const gmailClient = createGmailApi(auth);
// Refresh the owner's send-as aliases opportunistically each sync (#2831) — one cheap
// settings call. Returned up to syncAccount so the activity timeline can exclude every
// owner address, not just the primary, from received-message participants. `null` on
@@ -257,13 +257,7 @@ export async function syncGmail(account, cache, io, options = {}) {
const { items: messageIds, truncated } = await collectMessageIds(
passes,
async ({ q, maxResults, pageToken }) => {
- const listResult = await gmailClient.users.messages.list({
- userId: 'me',
- q,
- maxResults,
- ...(pageToken && { pageToken }),
- });
- const data = listResult.data;
+ const data = await gmailClient.listMessages({ q, maxResults, pageToken });
// Gmail omits messages for an empty inbox, but a missing/malformed body
// cannot prove that the inbox is empty.
if (!data || typeof data !== 'object' || Array.isArray(data)
@@ -300,17 +294,17 @@ export async function syncGmail(account, cache, io, options = {}) {
const batch = messageIds.slice(i, i + BATCH_SIZE);
const results = await Promise.all(batch.map(({ id: gmailId }) =>
- gmailClient.users.messages.get({ userId: 'me', id: gmailId, format: 'full' })
+ gmailClient.getMessage(gmailId, { format: 'full' })
.catch(err => { console.warn(`📧 Gmail: failed to fetch message detail: ${messageLogError(err)}`); return null; })
));
for (let j = 0; j < results.length; j++) {
- if (!results[j]?.data || results[j].data.id !== batch[j].id
- || !Array.isArray(results[j].data.labelIds) || !results[j].data.payload) {
+ if (!results[j] || results[j].id !== batch[j].id
+ || !Array.isArray(results[j].labelIds) || !results[j].payload) {
detailFetchFailures++;
continue;
}
- const data = results[j].data;
+ const data = results[j];
const { id: gmailId, threadId: gmailThreadId } = batch[j];
const headers = data.payload?.headers || [];
const from = parseSender(getHeader(headers, 'From'));
@@ -416,11 +410,11 @@ export async function prepareGmailReply(account, draft, original) {
}
const auth = await getAuthenticatedClient();
if (!auth) return replyRefusal('GMAIL_NOT_CONFIGURED', 'Google OAuth is not configured. Connect Google before sending this reply.', 502);
- const gmailClient = gmail({ version: 'v1', auth, timeout: GOOGLE_API_TIMEOUT_MS });
- const metadata = await gmailClient.users.messages.get({
- userId: 'me', id: original.apiId, format: 'metadata',
+ const gmailClient = createGmailApi(auth);
+ const metadata = await gmailClient.getMessage(original.apiId, {
+ format: 'metadata',
metadataHeaders: ['Message-ID', 'References', 'In-Reply-To', 'Subject']
- }, { timeout: 10_000, retry: false }).then(res => res.data, () => null);
+ }, { timeout: 10_000, retry: false }).catch(() => null);
if (!metadata || metadata.id !== original.apiId || !metadata.threadId
|| (original.conversationId && metadata.threadId !== original.conversationId)) {
return replyRefusal('GMAIL_REPLY_METADATA_UNAVAILABLE', 'Gmail could not verify the original message and conversation. Sync the account or reconnect Google, then try again.', 502);
@@ -487,7 +481,7 @@ export async function sendGmail(account, draft, delivery = null) {
return { success: false, error: 'Google sign-in could not be refreshed — nothing was sent', status: 502, code: 'GMAIL_AUTH_FAILED' };
}
- const gmailClient = gmail({ version: 'v1', auth, timeout: GOOGLE_API_TIMEOUT_MS });
+ const gmailClient = createGmailApi(auth);
// Build RFC 2822 message
const toLine = Array.isArray(draft.to) ? draft.to.join(', ') : draft.to;
@@ -511,10 +505,10 @@ export async function sendGmail(account, draft, delivery = null) {
// `retry: false`: the client must never resubmit a send on its own — a retry
// after a lost acknowledgement is a duplicate message.
- const sendError = await gmailClient.users.messages.send({
- userId: 'me',
- requestBody: { raw, ...(draft.replyToMessageId ? { threadId: delivery.threadId } : {}) }
- }, { retry: false }).then(() => null, err => err);
+ const sendError = await gmailClient.sendMessage(
+ { raw, ...(draft.replyToMessageId ? { threadId: delivery.threadId } : {}) },
+ { retry: false }
+ ).then(() => null, err => err);
if (sendError) {
if (isDefinitiveRefusal(sendError.response?.status)) {
diff --git a/server/services/messageGmailSync.send.test.js b/server/services/messageGmailSync.send.test.js
index 02c7b23784..2e872d0b7c 100644
--- a/server/services/messageGmailSync.send.test.js
+++ b/server/services/messageGmailSync.send.test.js
@@ -1,6 +1,6 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { join } from 'path';
-import { auth as googleAuth } from '@googleapis/gmail';
+import { auth as googleAuth } from '@googleapis/calendar';
// Gmail send workflow through the REAL sender, draft store, Gmail adapter and
// Google API client. Only the network is stubbed (the auth client's fetch), so
diff --git a/server/services/messageGmailSync.test.js b/server/services/messageGmailSync.test.js
index eda9ef1074..e3ba0d1fe9 100644
--- a/server/services/messageGmailSync.test.js
+++ b/server/services/messageGmailSync.test.js
@@ -121,7 +121,7 @@ describe('collectMessageIds — full pagination', () => {
// excludable from participants, so the sync fetches the account's send-as addresses.
describe('fetchSendAsAliases', () => {
const clientReturning = (sendAs) => ({
- users: { settings: { sendAs: { list: async () => ({ data: { sendAs } }) } } },
+ listSendAs: async () => ({ sendAs }),
});
it('returns lowercased alias emails from the sendAs settings', async () => {
@@ -137,7 +137,7 @@ describe('fetchSendAsAliases', () => {
});
it('returns the null sentinel (keep stored aliases) when the API call fails', async () => {
- const client = { users: { settings: { sendAs: { list: async () => { throw new Error('boom'); } } } } };
+ const client = { listSendAs: async () => { throw new Error('boom'); } };
expect(await fetchSendAsAliases(client)).toBeNull();
});
});
diff --git a/server/services/messageLogging.test.js b/server/services/messageLogging.test.js
index 1598309d14..9790ed67b5 100644
--- a/server/services/messageLogging.test.js
+++ b/server/services/messageLogging.test.js
@@ -30,11 +30,12 @@ vi.mock('../lib/fileUtils.js', async (original) => ({
}));
vi.mock('./readinessNotify.js', () => ({ noteReadinessChanged: () => {} }));
vi.mock('./googleAuth.js', () => ({ getAuthenticatedClient: async () => ({ getAccessToken: async () => ({ token: 'synthetic-token' }) }), GOOGLE_API_TIMEOUT_MS: 30_000 }));
-vi.mock('@googleapis/gmail', () => ({
- gmail: () => ({ users: {
- messages: { send: doubles.send, list: doubles.list, get: doubles.get, trash: doubles.trash, modify: doubles.modify },
- settings: { sendAs: { list: async () => ({ data: { sendAs: [] } }) } }
- } })
+vi.mock('./gmailApi.js', () => ({
+ createGmailApi: () => ({
+ sendMessage: doubles.send, listMessages: doubles.list, getMessage: doubles.get,
+ trashMessage: doubles.trash, modifyMessage: doubles.modify,
+ listSendAs: async () => ({ sendAs: [] })
+ })
}));
vi.mock('../lib/fetchWithTimeout.js', () => ({ fetchWithTimeout: doubles.fetch }));
vi.mock('./messageTokenExtractor.js', () => ({ getToken: doubles.token, clearTokenCache: () => {} }));
@@ -82,9 +83,9 @@ function seedMessage(account) {
beforeEach(() => {
vi.clearAllMocks();
doubles.files.clear();
- doubles.send.mockResolvedValue({ data: { id: 'api-message-1' } });
- doubles.list.mockResolvedValue({ data: { messages: [] } });
- doubles.get.mockResolvedValue({ data: {} });
+ doubles.send.mockResolvedValue({ id: 'api-message-1' });
+ doubles.list.mockResolvedValue({ messages: [] });
+ doubles.get.mockResolvedValue({});
doubles.token.mockResolvedValue({ token: 'synthetic-token' });
doubles.evaluate.mockResolvedValue({ notInInbox: true, error: 'Not found' });
logs = ['log', 'warn', 'error'].map(method => vi.spyOn(console, method).mockImplementation(() => {}));
diff --git a/server/services/messageSync.test.js b/server/services/messageSync.test.js
index 0207c316fe..75a3f0958b 100644
--- a/server/services/messageSync.test.js
+++ b/server/services/messageSync.test.js
@@ -40,11 +40,12 @@ vi.mock('./messageAccounts.js', () => ({
}));
const gmailApi = vi.hoisted(() => ({ list: vi.fn(), get: vi.fn() }));
-vi.mock('@googleapis/gmail', () => ({
- gmail: () => ({ users: {
- messages: gmailApi,
- settings: { sendAs: { list: async () => ({ data: { sendAs: [] } }) } },
- } }),
+vi.mock('./gmailApi.js', () => ({
+ createGmailApi: () => ({
+ listMessages: gmailApi.list,
+ getMessage: gmailApi.get,
+ listSendAs: async () => ({ sendAs: [] }),
+ }),
}));
vi.mock('./googleAuth.js', () => ({ getAuthenticatedClient: async () => ({}), GOOGLE_API_TIMEOUT_MS: 30_000 }));
@@ -1130,10 +1131,10 @@ describe('full inbox coverage contract', () => {
getAccount.mockResolvedValue({ id: VALID_UUID, name: 'Example inbox', email: '[email protected]', type: 'gmail', enabled: true });
syncGmail.mockImplementation((await vi.importActual('./messageGmailSync.js')).syncGmail);
gmailApi.list.mockImplementation(async ({ q }) => ({
- data: { messages: q === 'in:inbox' ? [{ id: 'a' }, { id: 'b' }] : [] },
+ messages: q === 'in:inbox' ? [{ id: 'a' }, { id: 'b' }] : [],
}));
- gmailApi.get.mockImplementation(async ({ id }) => ({
- data: { id, labelIds: ['INBOX'], payload: { headers: [] } },
+ gmailApi.get.mockImplementation(async (id) => ({
+ id, labelIds: ['INBOX'], payload: { headers: [] },
}));
});
@@ -1148,14 +1149,14 @@ describe('full inbox coverage contract', () => {
gmailApi.list.mockImplementation(async ({ q, pageToken, maxResults }) => {
const start = Number(pageToken || 0);
const end = Math.min(start + maxResults, count);
- return { data: q === 'in:inbox' ? {
+ return q === 'in:inbox' ? {
messages: Array.from({ length: end - start }, (_, i) => ({ id: `synthetic-${start + i}` })),
...(end < count ? { nextPageToken: String(end) } : {}),
- } : {} };
+ } : {};
});
- gmailApi.get.mockImplementation(async ({ id }) => ({ data: {
+ gmailApi.get.mockImplementation(async (id) => ({
id, labelIds: ['INBOX'], payload: { headers: [], mimeType: 'text/plain', body: { data: Buffer.from(body).toString('base64url') } },
- } }));
+ }));
expect(await syncAccount(VALID_UUID, io, { mode: 'full' })).toMatchObject({ newMessages: count });
expect(io.emit).toHaveBeenCalledWith('messages:sync:completed', expect.objectContaining({ newMessages: count }));
@@ -1165,7 +1166,7 @@ describe('full inbox coverage contract', () => {
it('preserves identity and evaluation through failure and retry, then reconciles complete snapshots', async () => {
gmailApi.get.mockImplementationOnce(async () => ({
- data: { id: 'a', labelIds: ['INBOX', 'UNREAD'], payload: { headers: [] } },
+ id: 'a', labelIds: ['INBOX', 'UNREAD'], payload: { headers: [] },
})).mockRejectedValueOnce(new Error('temporary detail failure'));
await syncAccount(VALID_UUID, null, { mode: 'full' });
expect(saved.messages).toHaveLength(3);
@@ -1174,21 +1175,21 @@ describe('full inbox coverage contract', () => {
expect(markSentIngested).toHaveBeenLastCalledWith(VALID_UUID, expect.objectContaining({ partial: true }));
await syncAccount(VALID_UUID, null, { mode: 'full' });
expect(saved.messages[1]).toMatchObject({ id: 'local-b', evaluation: { priority: 'high' } });
- gmailApi.list.mockResolvedValue({ data: { messages: [{ id: 'b' }] } });
+ gmailApi.list.mockResolvedValue({ messages: [{ id: 'b' }] });
await syncAccount(VALID_UUID, null, { mode: 'full' });
expect(saved.messages.map(m => m.id)).toEqual(['local-b', 'local-only']);
- gmailApi.list.mockResolvedValue({ data: {} });
+ gmailApi.list.mockResolvedValue({});
await syncAccount(VALID_UUID, null, { mode: 'full' });
expect(saved.messages).toEqual([{ id: 'local-only' }]);
});
it('retains unseen mail when the Gmail inbox reaches its cap', async () => {
- gmailApi.list.mockImplementation(async ({ q, maxResults, pageToken }) => ({
- data: q === 'in:inbox' ? {
+ gmailApi.list.mockImplementation(async ({ q, maxResults, pageToken }) => (
+ q === 'in:inbox' ? {
messages: Array.from({ length: maxResults }, (_, i) => ({ id: 'new-' + (Number(pageToken || 0) + i) })),
nextPageToken: String(Number(pageToken || 0) + maxResults),
- } : {},
- }));
+ } : {}
+ ));
await syncAccount(VALID_UUID, null, { mode: 'full' });
expect(saved.messages.find(m => m.id === 'local-b')).toMatchObject({ evaluation: { priority: 'high' } });
expect(saved.messages).toHaveLength(203);
@@ -1213,10 +1214,10 @@ describe('full inbox coverage contract', () => {
});
it('does not certify malformed details or listings', async () => {
- gmailApi.get.mockResolvedValue({ data: {} });
+ gmailApi.get.mockResolvedValue({});
await syncAccount(VALID_UUID, null, { mode: 'full' });
expect(saved.messages).toHaveLength(3);
- gmailApi.list.mockResolvedValue({ data: { messages: 'invalid' } });
+ gmailApi.list.mockResolvedValue({ messages: 'invalid' });
expect(await syncAccount(VALID_UUID, null, { mode: 'full' })).toMatchObject({ status: 502 });
expect(saved.messages).toHaveLength(3);
});