@mindstone/mcp-server-google-workspace 0.5.11 → 0.5.13

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.
Files changed (37) hide show
  1. package/README.md +28 -3
  2. package/dist/connectorRenewalClient.d.ts +162 -0
  3. package/dist/connectorRenewalClient.js +212 -0
  4. package/dist/modules/accounts/manager.js +24 -4
  5. package/dist/modules/accounts/oauth.js +5 -2
  6. package/dist/modules/accounts/token.d.ts +1 -0
  7. package/dist/modules/accounts/token.js +18 -8
  8. package/dist/modules/accounts/unauthorized.d.ts +4 -0
  9. package/dist/modules/accounts/unauthorized.js +46 -0
  10. package/dist/modules/calendar/service.js +2 -2
  11. package/dist/modules/docs/service.d.ts +1 -1
  12. package/dist/modules/docs/service.js +16 -8
  13. package/dist/modules/docs/types.d.ts +0 -1
  14. package/dist/oauth/coordinatedClient.d.ts +14 -0
  15. package/dist/oauth/coordinatedClient.js +103 -0
  16. package/dist/resources/compose-email-template.d.ts +1 -1
  17. package/dist/resources/compose-email-template.js +4 -0
  18. package/dist/tools/definitions/chat.js +1 -2
  19. package/dist/tools/definitions/docs.js +4 -8
  20. package/dist/tools/definitions/drive.js +0 -1
  21. package/dist/tools/docs-handlers.d.ts +0 -2
  22. package/dist/tools/docs-handlers.js +0 -2
  23. package/dist/tools/param-normalizer.js +0 -1
  24. package/dist/tools/server.js +8 -23
  25. package/dist/tools/type-guards.d.ts +0 -1
  26. package/dist/tools/type-guards.js +1 -3
  27. package/dist/utils/apiError.d.ts +4 -4
  28. package/dist/utils/apiError.js +7 -6
  29. package/dist/utils/google-retry.d.ts +6 -0
  30. package/dist/utils/google-retry.js +18 -1
  31. package/node_modules/cross-spawn/README.md +19 -3
  32. package/node_modules/cross-spawn/lib/parse.js +38 -10
  33. package/node_modules/cross-spawn/lib/util/escape.js +84 -25
  34. package/node_modules/cross-spawn/lib/util/readShebang.js +8 -2
  35. package/node_modules/cross-spawn/lib/util/resolveCommand.js +8 -1
  36. package/node_modules/cross-spawn/package.json +21 -24
  37. package/package.json +1 -1
package/README.md CHANGED
@@ -8,7 +8,7 @@ Google Workspace MCP server — Gmail, Calendar, Drive, Docs, Sheets, Slides, Co
8
8
 
9
9
  ## Status
10
10
 
11
- - **Version:** [0.5.11](./CHANGELOG.md) · npm: not yet published
11
+ - **Version:** [0.5.13](./CHANGELOG.md) · npm: not yet published
12
12
  - **Auth:** OAuth (host-orchestrated) ([`GOOGLE_CLIENT_SECRET`](./server.json))
13
13
  - **Tools:** [123](./src/tools/definitions/) (Gmail, Calendar, Drive, Docs, Sheets, Slides, Contacts, Chat, Meet, Tasks, Forms, Comments, Account)
14
14
  - **Surface:** cloud-api
@@ -114,6 +114,8 @@ This server is designed to run alongside a host application that performs the Go
114
114
 
115
115
  The connector does not run a callback server and does not generate OAuth URLs. The MCP host computes the Google OAuth URL and handles the callback. Once the host has written the account's token file under `CREDENTIALS_PATH/` and an entry into `ACCOUNTS_PATH`, the next tool call succeeds.
116
116
 
117
+ Across Google services, a request rejected with HTTP 401 or OAuth `invalid_grant` gets one final token-renewal attempt when refresh is enabled. If renewal confirms sign-in is required, the connector returns the same `auth_required` response, including when service or handler errors wrap the original refusal. File-permission refusals, quota errors, and network failures keep their ordinary error responses.
118
+
117
119
  ## Host configuration examples
118
120
 
119
121
  ### Claude Desktop / Cursor
@@ -237,7 +239,7 @@ A Google Doc can hold many tabs, nested up to a few levels deep. Every tab has a
237
239
  - Copied: text, heading and paragraph styles, character styles and links, bullets and numbering (mapped to Google Docs' preset list styles), tables (cell text, column widths, cell styles), page breaks and smart chips. A smart chip linking to a file you can't open becomes a titled link; people and date chips become their text. The result lists both.
238
240
  - Not copied: headers and footers, sub-tabs, images and other special elements (listed under "Not copied"; inline ones also leave a visible `[placeholder]`), and table cell merges (cells are copied unmerged; a table whose merged cells can't be copied is refused before anything is written).
239
241
  - Not copied faithfully: links to headings inside the copied tab still point at the original tab's headings, so after a reset they no longer resolve.
240
- - Which target: to archive or duplicate a tab, use `new_tab_title`. To reset a tab in place from a template tab (keeping its id, position and sub-tabs), use `target_tab_id` with `overwrite_existing: true`, which clears that tab first. Never delete a tab in order to replace it: deleting also deletes its sub-tabs.
242
+ - Which target: to archive or duplicate a tab, use `new_tab_title`. To reset a tab in place from a template tab (keeping its id, position and sub-tabs), use `target_tab_id`, which clears that tab first. Never delete a tab in order to replace it: deleting also deletes its sub-tabs.
241
243
  - The result starts with a `Verification:` line comparing text, heading types, paragraph formatting, bullets, list grouping and table shapes with the source. Before deleting or resetting the source, check both that it says `passed` and that the `Not copied` line lists nothing you can't lose: verification can pass while, say, a floating image was left out. A failed verification comes back as an error result.
242
244
  - The copy is not atomic. If it stops part-way, the connector tries to delete a new tab again and the result says whether that worked (if not, it names the tab to delete); an existing target may be left cleared or partly written (the document's version history can restore it). If it completes but verification finds differences, the tab is kept so it can be checked, and the result lists the first few places it differs. Long tabs can take 10-60 seconds.
243
245
 
@@ -246,7 +248,7 @@ A Google Doc can hold many tabs, nested up to a few levels deep. Every tab has a
246
248
  1. `list_workspace_document_tabs` to get the live and Template tab ids, then read the live tab with `tab_id: <live tab id>`. Note the date line and the out-of-office lines to keep **before** anything changes.
247
249
  2. `copy_workspace_document_tab` with `source_tab_id: <live tab id>`, `new_tab_title: "2031-10-13"`, `new_tab_parent_id: <live tab id>` and `new_tab_position: 0`, archiving it as its first sub-tab.
248
250
  3. Stop unless the result says `Verification: passed` and its `Not copied` line lists nothing the archive can't do without.
249
- 4. `copy_workspace_document_tab` with `source_tab_id: <Template tab id>`, `target_tab_id: <live tab id>` and `overwrite_existing: true`, resetting the live tab in place.
251
+ 4. `copy_workspace_document_tab` with `source_tab_id: <Template tab id>`, and `target_tab_id: <live tab id>`, resetting the live tab in place.
250
252
  5. `find_and_replace_workspace_document` the date placeholder **with `tab_id: <live tab id>`** (without it the Template's placeholder changes too), and check the result says `Replaced 1`.
251
253
  6. `insert_workspace_document_text` the kept out-of-office lines **with `tab_id: <live tab id>`** (without it the text goes into the first tab, which may be the Template) and `position: "next_paragraph_start"`, anchored on the line directly above the empty bullet.
252
254
 
@@ -281,3 +283,26 @@ list, stops the read.
281
283
  Clients that do not negotiate this extension keep the connector's existing
282
284
  standalone file restrictions. This extension changes input-read permissions;
283
285
  existing output destinations, upload formats, size limits and file checks apply.
286
+
287
+ ### Optional host renewal coordination
288
+
289
+ A host that coordinates credentials across processes may set
290
+ `GOOGLE_WORKSPACE_RENEWAL_COORDINATOR_STATE` to a regular JSON state file containing
291
+ `{"port": 12345, "token": "host-generated-bearer-token"}`. The connector sends authenticated
292
+ POST requests to `http://127.0.0.1:<port>/credentials/renewal`, asking `beforeRefresh` for
293
+ admission and reporting `publishRefresh` afterwards. This covers explicit refreshes and
294
+ Google's automatic refresh during API calls. Standalone hosts leave the setting unset;
295
+ refresh then works as before. `GOOGLE_WORKSPACE_DISABLE_REFRESH` still takes precedence.
296
+
297
+ The grant identity is `{provider: "google-workspace", relativePath}`. For
298
+ `CREDENTIALS_PATH=<provider-folder>/<instance>/credentials`, the relative path is
299
+ `<instance>/credentials/<sanitised-email>.token.json`; for a direct
300
+ `<google-workspace-mcp>/credentials` folder it is `credentials/<sanitised-email>.token.json`.
301
+ The host must use that same storage identity. Token files must first be loaded through
302
+ the account token manager before an OAuth client can refresh them in coordinated mode.
303
+
304
+ A configured coordinator that cannot be reached makes renewal wait. An access token that
305
+ is still usable may serve the request; otherwise the connector returns a temporary error,
306
+ without asking the person to reconnect or renewing independently. A `legacy` answer keeps
307
+ the ordinary provider refresh. Pending outcomes are published before another attempt;
308
+ operation IDs and pending publications are retained for the life of the connector process.
@@ -0,0 +1,162 @@
1
+ import { z } from 'zod';
2
+ declare const Tokens: z.ZodObject<{
3
+ accessToken: z.ZodString;
4
+ refreshToken: z.ZodOptional<z.ZodString>;
5
+ expiresAt: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
6
+ }, "strip", z.ZodTypeAny, {
7
+ accessToken: string;
8
+ refreshToken?: string | undefined;
9
+ expiresAt?: number | null | undefined;
10
+ }, {
11
+ accessToken: string;
12
+ refreshToken?: string | undefined;
13
+ expiresAt?: number | null | undefined;
14
+ }>;
15
+ declare const Permit: z.ZodObject<{
16
+ grantId: z.ZodString;
17
+ epoch: z.ZodString;
18
+ revision: z.ZodNumber;
19
+ opId: z.ZodString;
20
+ }, "strict", z.ZodTypeAny, {
21
+ grantId: string;
22
+ epoch: string;
23
+ revision: number;
24
+ opId: string;
25
+ }, {
26
+ grantId: string;
27
+ epoch: string;
28
+ revision: number;
29
+ opId: string;
30
+ }>;
31
+ declare const Outcome: z.ZodDiscriminatedUnion<"kind", [z.ZodObject<{
32
+ kind: z.ZodLiteral<"success">;
33
+ tokens: z.ZodObject<{
34
+ accessToken: z.ZodString;
35
+ refreshToken: z.ZodOptional<z.ZodString>;
36
+ expiresAt: z.ZodOptional<z.ZodNullable<z.ZodNumber>>;
37
+ }, "strip", z.ZodTypeAny, {
38
+ accessToken: string;
39
+ refreshToken?: string | undefined;
40
+ expiresAt?: number | null | undefined;
41
+ }, {
42
+ accessToken: string;
43
+ refreshToken?: string | undefined;
44
+ expiresAt?: number | null | undefined;
45
+ }>;
46
+ }, "strict", z.ZodTypeAny, {
47
+ kind: "success";
48
+ tokens: {
49
+ accessToken: string;
50
+ refreshToken?: string | undefined;
51
+ expiresAt?: number | null | undefined;
52
+ };
53
+ }, {
54
+ kind: "success";
55
+ tokens: {
56
+ accessToken: string;
57
+ refreshToken?: string | undefined;
58
+ expiresAt?: number | null | undefined;
59
+ };
60
+ }>, z.ZodObject<{
61
+ kind: z.ZodLiteral<"not_dispatched">;
62
+ }, "strict", z.ZodTypeAny, {
63
+ kind: "not_dispatched";
64
+ }, {
65
+ kind: "not_dispatched";
66
+ }>, z.ZodObject<{
67
+ kind: z.ZodLiteral<"rejected">;
68
+ }, "strict", z.ZodTypeAny, {
69
+ kind: "rejected";
70
+ }, {
71
+ kind: "rejected";
72
+ }>, z.ZodObject<{
73
+ kind: z.ZodLiteral<"uncertain">;
74
+ }, "strict", z.ZodTypeAny, {
75
+ kind: "uncertain";
76
+ }, {
77
+ kind: "uncertain";
78
+ }>]>;
79
+ type Identity = {
80
+ provider: 'google-workspace';
81
+ relativePath: string;
82
+ };
83
+ export type RenewalPermit = z.infer<typeof Permit>;
84
+ export type RenewalOutcome = z.infer<typeof Outcome>;
85
+ /** A configured but unavailable coordinator always waits; it never grants a local refresh. */
86
+ export declare function createConnectorRenewalClient(statePath: string): {
87
+ beforeRefresh(grant: {
88
+ identity: Identity;
89
+ tokens: z.infer<typeof Tokens>;
90
+ opId: string;
91
+ }): Promise<{
92
+ kind: "current";
93
+ tokens: {
94
+ accessToken: string;
95
+ refreshToken?: string | undefined;
96
+ expiresAt?: number | null | undefined;
97
+ };
98
+ } | {
99
+ kind: "permit";
100
+ tokens: {
101
+ accessToken?: string | undefined;
102
+ refreshToken?: string | undefined;
103
+ expiresAt?: number | null | undefined;
104
+ };
105
+ permit: {
106
+ grantId: string;
107
+ epoch: string;
108
+ revision: number;
109
+ opId: string;
110
+ };
111
+ } | {
112
+ kind: "wait";
113
+ publication?: {
114
+ grantId: string;
115
+ epoch: string;
116
+ revision: number;
117
+ opId: string;
118
+ outcome: {
119
+ kind: "success";
120
+ tokens: {
121
+ accessToken: string;
122
+ refreshToken?: string | undefined;
123
+ expiresAt?: number | null | undefined;
124
+ };
125
+ } | {
126
+ kind: "not_dispatched";
127
+ } | {
128
+ kind: "rejected";
129
+ } | {
130
+ kind: "uncertain";
131
+ };
132
+ } | undefined;
133
+ } | {
134
+ kind: "needs_re_sign_in";
135
+ } | {
136
+ kind: "legacy";
137
+ }>;
138
+ publishRefresh(identity: Identity, permit: RenewalPermit, outcome: RenewalOutcome): Promise<"wait" | "needs_re_sign_in" | "published" | "conflict" | "invalid">;
139
+ };
140
+ export type RenewalTokens = z.infer<typeof Tokens>;
141
+ export declare class RenewalWaitError extends Error {
142
+ readonly code = "TEMPORARY_AUTH_ERROR";
143
+ constructor();
144
+ }
145
+ export declare class RenewalRejectedError extends Error {
146
+ constructor();
147
+ }
148
+ export declare class RenewalAttemptError extends Error {
149
+ readonly outcome: 'rejected' | 'uncertain' | 'not_dispatched';
150
+ constructor(outcome: 'rejected' | 'uncertain' | 'not_dispatched');
151
+ }
152
+ /** One admission per provider attempt; receipts survive lost acknowledgements in this process. */
153
+ export declare class ConnectorRenewal {
154
+ private readonly client;
155
+ private readonly operations;
156
+ private readonly flights;
157
+ constructor(statePath: string);
158
+ refresh(identity: Identity, tokens: RenewalTokens, refresh: (tokens: RenewalTokens, dispatched: () => void) => Promise<RenewalTokens>, save: (tokens: RenewalTokens) => Promise<void>, legacy?: () => Promise<RenewalTokens>): Promise<RenewalTokens>;
159
+ private perform;
160
+ }
161
+ export {};
162
+ //# sourceMappingURL=connectorRenewalClient.d.ts.map
@@ -0,0 +1,212 @@
1
+ import fs from 'node:fs/promises';
2
+ import { constants } from 'node:fs';
3
+ import { randomUUID } from 'node:crypto';
4
+ import { z } from 'zod';
5
+ const Tokens = z.object({
6
+ accessToken: z.string().min(1), refreshToken: z.string().min(1).optional(),
7
+ expiresAt: z.number().finite().nullable().optional(),
8
+ });
9
+ const Permit = z.object({
10
+ grantId: z.string().min(1), epoch: z.string().min(1),
11
+ revision: z.number().int().nonnegative().safe(), opId: z.string().uuid(),
12
+ }).strict();
13
+ const Outcome = z.discriminatedUnion('kind', [
14
+ z.object({ kind: z.literal('success'), tokens: Tokens }).strict(),
15
+ z.object({ kind: z.literal('not_dispatched') }).strict(),
16
+ z.object({ kind: z.literal('rejected') }).strict(),
17
+ z.object({ kind: z.literal('uncertain') }).strict(),
18
+ ]);
19
+ const BeforeRefresh = z.discriminatedUnion('kind', [
20
+ z.object({ kind: z.literal('current'), tokens: Tokens }).strict(),
21
+ z.object({ kind: z.literal('permit'), permit: Permit, tokens: Tokens.partial() }).strict(),
22
+ z.object({ kind: z.literal('wait'), publication: Permit.extend({ outcome: Outcome }).optional() }).strict(),
23
+ z.object({ kind: z.literal('needs_re_sign_in') }).strict(),
24
+ z.object({ kind: z.literal('legacy') }).strict(),
25
+ ]);
26
+ /** A configured but unavailable coordinator always waits; it never grants a local refresh. */
27
+ export function createConnectorRenewalClient(statePath) {
28
+ const post = async (body) => {
29
+ if ((await fs.lstat(statePath)).isSymbolicLink())
30
+ throw new Error('Coordinator state refused');
31
+ const file = await fs.open(statePath, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0));
32
+ let state;
33
+ try {
34
+ const stat = await file.stat();
35
+ const target = await fs.stat(await fs.realpath(statePath));
36
+ if (!stat.isFile() || stat.dev !== target.dev || stat.ino !== target.ino)
37
+ throw new Error('Coordinator state refused');
38
+ const buffer = Buffer.alloc(65537);
39
+ const { bytesRead } = await file.read(buffer, 0, buffer.length, 0);
40
+ if (bytesRead > 65536)
41
+ throw new Error('Coordinator state refused');
42
+ state = z.object({ port: z.number().int().min(1).max(65535), token: z.string().regex(/^[\x21-\x7e]+$/) })
43
+ .parse(JSON.parse(buffer.toString('utf8', 0, bytesRead)));
44
+ }
45
+ finally {
46
+ await file.close();
47
+ }
48
+ const response = await globalThis.fetch(`http://127.0.0.1:${state.port}/credentials/renewal`, {
49
+ method: 'POST', redirect: 'error', signal: AbortSignal.timeout(35000),
50
+ headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${state.token}` }, body: JSON.stringify(body),
51
+ });
52
+ if (!response.ok)
53
+ throw new Error('Renewal coordinator unavailable');
54
+ return z.object({ success: z.literal(true), result: z.unknown() }).parse(await response.json()).result;
55
+ };
56
+ return {
57
+ async beforeRefresh(grant) {
58
+ try {
59
+ return BeforeRefresh.parse(await post({ op: 'beforeRefresh', grant }));
60
+ }
61
+ catch {
62
+ console.error('[google-workspace-mcp] Renewal coordinator admission unavailable; waiting.');
63
+ return { kind: 'wait' };
64
+ }
65
+ },
66
+ async publishRefresh(identity, permit, outcome) {
67
+ try {
68
+ return z.enum(['published', 'wait', 'needs_re_sign_in', 'conflict', 'invalid']).parse(await post({
69
+ op: 'publishRefresh', identity, publication: { ...permit, outcome },
70
+ }));
71
+ }
72
+ catch {
73
+ console.error('[google-workspace-mcp] Renewal coordinator publication unavailable; waiting.');
74
+ return 'wait';
75
+ }
76
+ },
77
+ };
78
+ }
79
+ export class RenewalWaitError extends Error {
80
+ code = 'TEMPORARY_AUTH_ERROR';
81
+ constructor() { super('Sign-in renewal is temporarily unavailable. Please try again.'); }
82
+ }
83
+ export class RenewalRejectedError extends Error {
84
+ constructor() { super('invalid_grant: sign-in renewal rejected'); }
85
+ }
86
+ export class RenewalAttemptError extends Error {
87
+ outcome;
88
+ constructor(outcome) {
89
+ super('Provider renewal failed');
90
+ this.outcome = outcome;
91
+ }
92
+ }
93
+ /** One admission per provider attempt; receipts survive lost acknowledgements in this process. */
94
+ export class ConnectorRenewal {
95
+ client;
96
+ operations = new Map();
97
+ flights = new Map();
98
+ constructor(statePath) { this.client = createConnectorRenewalClient(statePath); }
99
+ refresh(identity, tokens, refresh, save, legacy) {
100
+ const key = identity.relativePath;
101
+ const existing = this.flights.get(key);
102
+ if (existing)
103
+ return existing;
104
+ const flight = this.perform(identity, tokens, refresh, save, legacy).finally(() => { this.flights.delete(key); });
105
+ this.flights.set(key, flight);
106
+ return flight;
107
+ }
108
+ async perform(identity, tokens, refresh, save, legacy) {
109
+ const key = identity.relativePath;
110
+ const usable = () => {
111
+ if (tokens.expiresAt != null && tokens.expiresAt <= Date.now())
112
+ throw new RenewalWaitError();
113
+ return tokens;
114
+ };
115
+ const publish = async (operation) => {
116
+ const publication = operation.publication;
117
+ let superseded = false;
118
+ if (publication.outcome.kind === 'success') {
119
+ try {
120
+ await save(publication.outcome.tokens);
121
+ tokens = publication.outcome.tokens;
122
+ }
123
+ catch (error) {
124
+ if (!(error instanceof RenewalAttemptError))
125
+ throw error;
126
+ publication.outcome = { kind: 'uncertain' };
127
+ superseded = true;
128
+ }
129
+ }
130
+ const result = await this.client.publishRefresh(identity, publication.permit, publication.outcome);
131
+ if (result !== 'wait')
132
+ this.operations.delete(key);
133
+ if (superseded)
134
+ throw new RenewalWaitError();
135
+ if (result === 'needs_re_sign_in')
136
+ throw new RenewalRejectedError();
137
+ if (result === 'conflict' || result === 'invalid')
138
+ throw new RenewalWaitError();
139
+ return result;
140
+ };
141
+ let operation = this.operations.get(key);
142
+ if (operation?.publication) {
143
+ const sameCredential = (other) => tokens.accessToken === other.accessToken
144
+ && tokens.refreshToken === other.refreshToken;
145
+ if (!sameCredential(operation.baseline) && (operation.publication.outcome.kind !== 'success'
146
+ || !sameCredential(operation.publication.outcome.tokens))) {
147
+ // A replacement sign-in must never inherit an old pending success.
148
+ operation.publication.outcome = { kind: 'uncertain' };
149
+ }
150
+ const outcome = operation.publication.outcome;
151
+ const result = await publish(operation);
152
+ if (outcome.kind === 'rejected')
153
+ throw new RenewalRejectedError();
154
+ if (result === 'wait' || outcome.kind === 'success')
155
+ return usable();
156
+ operation = undefined;
157
+ }
158
+ if (!operation) {
159
+ operation = { opId: randomUUID(), baseline: tokens };
160
+ this.operations.set(key, operation);
161
+ }
162
+ const admission = await this.client.beforeRefresh({ identity, tokens, opId: operation.opId });
163
+ if (admission.kind === 'wait') {
164
+ if (admission.publication) {
165
+ const { outcome, ...permit } = admission.publication;
166
+ operation.publication = { permit, outcome };
167
+ }
168
+ return usable();
169
+ }
170
+ if (admission.kind !== 'permit')
171
+ this.operations.delete(key);
172
+ if (admission.kind === 'needs_re_sign_in')
173
+ throw new RenewalRejectedError();
174
+ if (admission.kind === 'current') {
175
+ const current = { ...admission.tokens, refreshToken: admission.tokens.refreshToken ?? tokens.refreshToken };
176
+ try {
177
+ await save(current);
178
+ }
179
+ catch (error) {
180
+ if (error instanceof RenewalAttemptError)
181
+ throw new RenewalWaitError();
182
+ throw error;
183
+ }
184
+ return current;
185
+ }
186
+ if (admission.kind === 'legacy') {
187
+ const result = legacy ? await legacy() : await refresh(tokens, () => { });
188
+ await save(result);
189
+ return result;
190
+ }
191
+ let outcome = { kind: 'not_dispatched' };
192
+ try {
193
+ if (!admission.tokens.refreshToken)
194
+ throw new RenewalWaitError();
195
+ const result = Tokens.parse(await refresh({ ...tokens, ...admission.tokens }, () => { outcome = { kind: 'uncertain' }; }));
196
+ outcome = { kind: 'success', tokens: result };
197
+ }
198
+ catch (error) {
199
+ if (error instanceof RenewalAttemptError)
200
+ outcome = { kind: error.outcome };
201
+ operation.publication = { permit: admission.permit, outcome };
202
+ await publish(operation);
203
+ if (outcome.kind === 'rejected')
204
+ throw new RenewalRejectedError();
205
+ throw new RenewalWaitError();
206
+ }
207
+ operation.publication = { permit: admission.permit, outcome };
208
+ await publish(operation);
209
+ return tokens;
210
+ }
211
+ }
212
+ //# sourceMappingURL=connectorRenewalClient.js.map
@@ -8,7 +8,8 @@ import { atomicCredentialWrite, sweepStaleTemps } from '../../utils/atomicCreden
8
8
  import { GoogleOAuthClient } from './oauth.js';
9
9
  import { CREDENTIAL_FILE_REFUSED_RESOLUTION, CredentialFileRefusedError, readCredentialFile, } from '../../utils/guardedCredentialRead.js';
10
10
  import logger from '../../utils/logger.js';
11
- import { isUnauthorizedError } from './unauthorized.js';
11
+ import { isGoogleAuthFailure, markSignInRenewed } from './unauthorized.js';
12
+ import { markMayHaveWritten, mayHaveWritten } from '../../utils/google-retry.js';
12
13
  export class AccountManager {
13
14
  accountsPath;
14
15
  accounts;
@@ -105,13 +106,32 @@ export class AccountManager {
105
106
  return await operation();
106
107
  }
107
108
  catch (error) {
108
- if (isUnauthorizedError(error)) {
109
+ if (error instanceof AccountError)
110
+ throw error;
111
+ if (isGoogleAuthFailure(error)) {
109
112
  if (isRefreshDisabled()) {
113
+ if (mayHaveWritten(error)) {
114
+ const message = (error instanceof Error ? error.message : String(error)).replace(/^MCP error -?\d+: /, '');
115
+ throw markMayHaveWritten(new AccountError(`Authentication required. ${message}`, 'AUTH_REQUIRED', 'Connect Google Workspace to continue', error));
116
+ }
110
117
  throw new AccountError('Authentication required', 'AUTH_REQUIRED', 'Connect Google Workspace to continue');
111
118
  }
112
- // If we get a 401 during operation, try one more token renewal
113
- logger.warn('Received 401 during operation, attempting final token renewal');
119
+ // If Google refuses authentication during the operation, try one final renewal.
120
+ logger.warn('Authentication refused during operation, attempting final token renewal');
114
121
  const finalRenewal = await this.tokenManager.autoRenewToken(email);
122
+ // A failure that may already have changed data is reported, never replayed.
123
+ if (mayHaveWritten(error)) {
124
+ const message = (error instanceof Error ? error.message : String(error)).replace(/^MCP error -?\d+: /, '');
125
+ // Only a real refresh proves the sign-in works again; `VALID` just means the saved
126
+ // token has not expired yet, and Google has refused it, so that still needs a sign-in.
127
+ if (finalRenewal.status === 'REFRESHED') {
128
+ throw markSignInRenewed(markMayHaveWritten(new Error(`${message} Google refused the saved sign-in partway through; it has been renewed, so check the result before trying again.`)));
129
+ }
130
+ if (!finalRenewal.success && finalRenewal.canRetry) {
131
+ throw markMayHaveWritten(new AccountError(`Token refresh failed temporarily. ${message} This request may already have partly run; check the result before trying it again.`, 'TEMPORARY_AUTH_ERROR', 'Please try again later', error));
132
+ }
133
+ throw markMayHaveWritten(new AccountError(`Authentication required. ${message}`, 'AUTH_REQUIRED', finalRenewal.reason || 'Please re-authenticate your account', error));
134
+ }
115
135
  if (finalRenewal.success) {
116
136
  // Retry the operation with renewed token
117
137
  return await operation();
@@ -1,4 +1,5 @@
1
- import { OAuth2Client } from 'google-auth-library';
1
+ import { RenewalWaitError, RenewalRejectedError } from '../../connectorRenewalClient.js';
2
+ import { CoordinatedOAuth2Client } from '../../oauth/coordinatedClient.js';
2
3
  import { AccountError } from './types.js';
3
4
  import logger from '../../utils/logger.js';
4
5
  export class GoogleOAuthClient {
@@ -24,7 +25,7 @@ export class GoogleOAuthClient {
24
25
  if (this.initialized && this.oauth2Client) {
25
26
  return;
26
27
  }
27
- this.oauth2Client = new OAuth2Client(this.clientId, this.clientSecret);
28
+ this.oauth2Client = new CoordinatedOAuth2Client(this.clientId, this.clientSecret);
28
29
  this.initialized = true;
29
30
  logger.info('OAuth client initialized for token refresh');
30
31
  }
@@ -96,6 +97,8 @@ export class GoogleOAuthClient {
96
97
  return credentials;
97
98
  }
98
99
  catch (error) {
100
+ if (error instanceof RenewalWaitError || error instanceof RenewalRejectedError)
101
+ throw error;
99
102
  // Preserve the underlying error message and chain via `cause`. Previously
100
103
  // this catch threw a hardcoded `'Failed to refresh token'`, which meant
101
104
  // TokenManager's substring detection for `invalid_grant` / `revoked` /
@@ -12,6 +12,7 @@ export declare class TokenManager {
12
12
  constructor(oauthClient?: GoogleOAuthClient);
13
13
  setOAuthClient(client: GoogleOAuthClient): void;
14
14
  private getTokenPath;
15
+ private registerCredential;
15
16
  saveToken(email: string, tokenData: any): Promise<void>;
16
17
  loadToken(email: string): Promise<any>;
17
18
  sweepStaleTemps(): Promise<void>;
@@ -5,6 +5,7 @@ import { AccountError } from './types.js';
5
5
  import logger from '../../utils/logger.js';
6
6
  import { atomicCredentialWrite, sweepStaleTemps } from '../../utils/atomicCredentialWrite.js';
7
7
  import { CREDENTIAL_FILE_REFUSED_RESOLUTION, CredentialFileRefusedError, readCredentialFile, } from '../../utils/guardedCredentialRead.js';
8
+ import { registerGoogleCredential } from '../../oauth/coordinatedClient.js';
8
9
  import { isRefreshTokenInvalidError } from './unauthorized.js';
9
10
  /**
10
11
  * Manages OAuth token operations.
@@ -28,27 +29,35 @@ export class TokenManager {
28
29
  const sanitizedEmail = email.replace(/[^a-zA-Z0-9]/g, '-');
29
30
  return path.join(this.credentialsPath, `${sanitizedEmail}.token.json`);
30
31
  }
32
+ registerCredential(email, token) {
33
+ registerGoogleCredential(this.getTokenPath(email), token, () => this.loadToken(email), credentials => this.saveToken(email, credentials));
34
+ }
31
35
  async saveToken(email, tokenData) {
32
- logger.info(`Saving token for account: ${email}`);
36
+ logger.info('Saving account token');
33
37
  try {
34
38
  // Ensure base credentials directory exists with restrictive permissions
35
39
  await fs.mkdir(this.credentialsPath, { recursive: true, mode: 0o700 });
36
40
  const tokenPath = this.getTokenPath(email);
37
41
  await atomicCredentialWrite(tokenPath, JSON.stringify(tokenData, null, 2), { mode: 0o600 });
38
- logger.debug(`Token saved successfully at: ${tokenPath}`);
42
+ this.registerCredential(email, tokenData);
43
+ logger.debug('Token saved successfully');
39
44
  }
40
45
  catch (error) {
41
46
  throw new AccountError('Failed to save token', 'TOKEN_SAVE_ERROR', 'Please ensure the credentials directory is writable', error);
42
47
  }
43
48
  }
44
49
  async loadToken(email) {
45
- logger.debug(`Loading token for account: ${email}`);
50
+ logger.debug('Loading account token');
46
51
  try {
47
52
  const data = await readCredentialFile(this.getTokenPath(email));
48
53
  // File doesn't exist - return null to trigger OAuth flow
49
- if (data === null)
54
+ if (data === null) {
55
+ this.registerCredential(email, null);
50
56
  return null;
51
- return JSON.parse(data);
57
+ }
58
+ const token = JSON.parse(data);
59
+ this.registerCredential(email, token);
60
+ return token;
52
61
  }
53
62
  catch (error) {
54
63
  if (error instanceof CredentialFileRefusedError) {
@@ -74,10 +83,11 @@ export class TokenManager {
74
83
  };
75
84
  }
76
85
  async deleteToken(email) {
77
- logger.info(`Deleting token for account: ${email}`);
86
+ logger.info('Deleting account token');
78
87
  try {
79
88
  const tokenPath = this.getTokenPath(email);
80
89
  await fs.unlink(tokenPath);
90
+ this.registerCredential(email, null);
81
91
  logger.debug('Token file deleted successfully');
82
92
  }
83
93
  catch (error) {
@@ -141,7 +151,7 @@ export class TokenManager {
141
151
  * Returns the renewal result and new token if successful
142
152
  */
143
153
  async autoRenewToken(email) {
144
- logger.debug(`Attempting auto-renewal for account: ${email}`);
154
+ logger.debug('Attempting token auto-renewal');
145
155
  try {
146
156
  const token = await this.loadToken(email);
147
157
  if (!token) {
@@ -217,7 +227,7 @@ export class TokenManager {
217
227
  }
218
228
  }
219
229
  async validateToken(email, skipValidationForNew = false) {
220
- logger.debug(`Validating token for account: ${email}`);
230
+ logger.debug('Validating account token');
221
231
  try {
222
232
  const token = await this.loadToken(email);
223
233
  if (!token) {
@@ -1,3 +1,7 @@
1
1
  export declare function isUnauthorizedError(error: unknown): boolean;
2
+ /** Marks a report whose refusal has been resolved by a renewal, so it is never read as a refusal again. */
3
+ export declare function markSignInRenewed<T extends object>(target: T): T;
4
+ /** Operation-time auth failures, including errors wrapped by services and handlers. */
5
+ export declare function isGoogleAuthFailure(error: unknown): boolean;
2
6
  export declare function isRefreshTokenInvalidError(error: unknown): boolean;
3
7
  //# sourceMappingURL=unauthorized.d.ts.map
@@ -1,3 +1,4 @@
1
+ import { AccountError } from './types.js';
1
2
  export function isUnauthorizedError(error) {
2
3
  if (!error || typeof error !== 'object')
3
4
  return false;
@@ -13,6 +14,51 @@ export function isUnauthorizedError(error) {
13
14
  || candidate.response?.data?.error === 'unauthorized'
14
15
  || candidate.errors?.some((entry) => entry.reason === 'authError') === true;
15
16
  }
17
+ const SIGN_IN_RENEWED = Symbol.for('google-workspace.sign-in-renewed');
18
+ /** Marks a report whose refusal has been resolved by a renewal, so it is never read as a refusal again. */
19
+ export function markSignInRenewed(target) {
20
+ Object.defineProperty(target, SIGN_IN_RENEWED, { value: true });
21
+ return target;
22
+ }
23
+ function signInRenewed(error) {
24
+ const seen = new Set();
25
+ let current = error;
26
+ for (let depth = 0; depth < 8; depth++) {
27
+ if (!current || typeof current !== 'object' || seen.has(current))
28
+ return false;
29
+ if (current[SIGN_IN_RENEWED] === true)
30
+ return true;
31
+ seen.add(current);
32
+ current = current.cause;
33
+ }
34
+ return false;
35
+ }
36
+ /** Operation-time auth failures, including errors wrapped by services and handlers. */
37
+ export function isGoogleAuthFailure(error) {
38
+ if (signInRenewed(error))
39
+ return false;
40
+ const seen = new Set();
41
+ let current = error;
42
+ for (let depth = 0; depth < 8; depth++) {
43
+ if (!current || typeof current !== 'object' || seen.has(current))
44
+ return false;
45
+ seen.add(current);
46
+ // The connector's own account verdict is final: a temporary refresh failure keeps the
47
+ // refusal as its cause for diagnosis, but it is a retry, not a sign-in.
48
+ if (current instanceof AccountError)
49
+ return current.code === 'AUTH_REQUIRED';
50
+ if (isUnauthorizedError(current))
51
+ return true;
52
+ const candidate = current;
53
+ if (candidate.error === 'invalid_grant'
54
+ || candidate.response?.data?.error === 'invalid_grant'
55
+ || (typeof candidate.message === 'string' && candidate.message.includes('invalid_grant'))) {
56
+ return true;
57
+ }
58
+ current = candidate.cause;
59
+ }
60
+ return false;
61
+ }
16
62
  export function isRefreshTokenInvalidError(error) {
17
63
  const values = [];
18
64
  if (error instanceof Error) {