@usejunior/provider-microsoft 0.4.0 → 0.5.1

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/dist/auth.js CHANGED
@@ -3,7 +3,8 @@ import { getEmailScopeProfile } from '@usejunior/email-core';
3
3
  import { DeviceCodeCredential, ClientSecretCredential, useIdentityPlugin } from '@azure/identity';
4
4
  import { cachePersistencePlugin } from '@azure/identity-cache-persistence';
5
5
  import { randomUUID } from 'node:crypto';
6
- import { readFile, writeFile, mkdir } from 'node:fs/promises';
6
+ import { renameSync } from 'node:fs';
7
+ import { readFile, writeFile, mkdir, unlink } from 'node:fs/promises';
7
8
  import { join, dirname } from 'node:path';
8
9
  import { homedir } from 'node:os';
9
10
  import { GraphApiError } from './email-graph-provider.js';
@@ -63,24 +64,15 @@ export function toFilesystemSafeKey(email) {
63
64
  .replace(/\./g, '-')
64
65
  .replace(/[^a-z0-9-]/g, '');
65
66
  }
66
- /**
67
- * Delegated OAuth auth manager — real device code flow with MSAL cache persistence.
68
- *
69
- * Tokens are stored in the OS keychain by MSAL.
70
- * Only the AuthenticationRecord (non-secret metadata) is saved to disk.
71
- */
72
67
  export class DelegatedAuthManager {
73
- credential = null;
74
- authRecord = null;
75
- cacheName = null;
68
+ state = { kind: 'disconnected', emailAddress: null };
69
+ generation = 0;
70
+ mutations = Promise.resolve();
71
+ reconnectFlight = null;
72
+ tokenFlight = null;
76
73
  config;
77
74
  mailboxName;
78
75
  scopes;
79
- _needsReauth = false;
80
- _lastInteractiveAuthAt = null;
81
- _emailAddress = null;
82
- _tokenExpiresAt = null;
83
- _reconnectPromise = null;
84
76
  constructor(config, mailboxName = 'default') {
85
77
  this.config = config;
86
78
  this.mailboxName = mailboxName;
@@ -88,121 +80,252 @@ export class DelegatedAuthManager {
88
80
  }
89
81
  /** Set the email address for this mailbox (called after profile fetch during configure). */
90
82
  setEmailAddress(email) {
91
- this._emailAddress = email;
83
+ // Compatibility setter used by configure before saving the fetched profile.
84
+ const state = this.stableState();
85
+ if (state.kind === 'disconnected')
86
+ state.emailAddress = email;
87
+ else if (state.session)
88
+ state.session.emailAddress = email;
92
89
  }
93
90
  /** Get the email address for this mailbox (may be null if not yet fetched). */
94
91
  get emailAddress() {
95
- return this._emailAddress;
92
+ const state = this.stableState();
93
+ return state.kind === 'disconnected' ? state.emailAddress : state.session?.emailAddress ?? null;
96
94
  }
97
- get needsReauth() { return this._needsReauth; }
98
- get lastInteractiveAuthAt() { return this._lastInteractiveAuthAt; }
99
- get tokenExpiresAt() { return this._tokenExpiresAt; }
95
+ get needsReauth() { return this.stableState().kind === 'reauth_required'; }
96
+ get lastInteractiveAuthAt() { return this.session()?.lastInteractiveAuthAt ?? null; }
97
+ get tokenExpiresAt() { return this.session()?.tokenExpiresAt ?? null; }
100
98
  get isTokenExpiringSoon() {
101
- if (this._needsReauth)
99
+ if (this.needsReauth)
102
100
  return true;
103
- if (!this._tokenExpiresAt)
101
+ if (!this.tokenExpiresAt)
104
102
  return false;
105
- return Date.now() > this._tokenExpiresAt - TOKEN_EXPIRY_BUFFER_MS;
103
+ return Date.now() > this.tokenExpiresAt - TOKEN_EXPIRY_BUFFER_MS;
104
+ }
105
+ stableState() {
106
+ switch (this.state.kind) {
107
+ case 'disconnected':
108
+ case 'connected':
109
+ case 'reauth_required': return this.state;
110
+ case 'connecting': return this.state.previous;
111
+ case 'refreshing': return this.state.previous;
112
+ case 'disconnecting': return { kind: 'disconnected', emailAddress: null };
113
+ }
114
+ }
115
+ session() {
116
+ const state = this.stableState();
117
+ return state.kind === 'disconnected' ? null : state.session;
118
+ }
119
+ assertCurrent(generation) {
120
+ if (generation !== this.generation)
121
+ throw new Error('Authentication operation cancelled by disconnect');
122
+ }
123
+ serialize(operation) {
124
+ const generation = this.generation;
125
+ const result = this.mutations.then(() => {
126
+ this.assertCurrent(generation);
127
+ return operation(generation);
128
+ });
129
+ this.mutations = result.catch(() => { });
130
+ return result;
131
+ }
132
+ terminal(err) {
133
+ return err instanceof Error && err.name !== 'AbortError' && (err.name === 'AuthenticationRequiredError'
134
+ || err.message.includes('interaction_required') || err.message.includes('invalid_grant'));
135
+ }
136
+ joinFlight(flight, signal) {
137
+ ++flight.waiters;
138
+ // Unsignalled callers retain the shared promise identity and own a waiter
139
+ // until settlement; they cannot be cancelled by another caller.
140
+ if (!signal)
141
+ return flight.promise;
142
+ return new Promise((resolve, reject) => {
143
+ let waiting = true;
144
+ const release = () => {
145
+ if (!waiting)
146
+ return false;
147
+ waiting = false;
148
+ signal.removeEventListener('abort', abort);
149
+ --flight.waiters;
150
+ return true;
151
+ };
152
+ const abort = () => {
153
+ if (!release())
154
+ return;
155
+ reject(signal.reason);
156
+ if (!flight.settled && flight.waiters === 0)
157
+ flight.controller.abort();
158
+ };
159
+ signal.addEventListener('abort', abort, { once: true });
160
+ if (signal.aborted)
161
+ abort();
162
+ void flight.promise.then(value => {
163
+ if (release())
164
+ resolve(value);
165
+ }, error => {
166
+ if (release())
167
+ reject(error);
168
+ });
169
+ });
170
+ }
171
+ failed(err, previous, generation) {
172
+ this.assertCurrent(generation);
173
+ this.state = this.terminal(err)
174
+ ? { kind: 'reauth_required', reason: err, session: previous.kind === 'disconnected' ? null : previous.session }
175
+ : previous;
106
176
  }
107
177
  /**
108
178
  * Interactive device code flow — prints URL + code to stderr.
109
179
  * Call this from `email-agent-mcp configure`, NOT from MCP serve.
110
180
  */
111
- async connect(_credentials) {
112
- this.cacheName = this.createCacheName();
113
- this.credential = this.createPersistentCredential({
114
- clientId: this.config.clientId,
115
- tenantId: this.config.tenantId,
116
- cacheName: this.cacheName,
117
- disableAutomaticAuthentication: true, // Force interactive in connect()
118
- userPromptCallback: (info) => {
119
- console.error('\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
120
- console.error(' To sign in, open this URL in your browser:');
121
- console.error(` ${info.verificationUri}`);
122
- console.error(` Enter code: ${info.userCode}`);
123
- console.error('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n');
124
- },
181
+ connect(_credentials) {
182
+ return this.serialize(async (generation) => {
183
+ const previous = this.stableState();
184
+ const emailAddress = this.emailAddress;
185
+ this.state = { kind: 'connecting', previous };
186
+ const cacheName = this.createCacheName();
187
+ try {
188
+ const credential = this.createPersistentCredential({
189
+ clientId: this.config.clientId,
190
+ tenantId: this.config.tenantId,
191
+ cacheName,
192
+ disableAutomaticAuthentication: true, // Force interactive in connect()
193
+ userPromptCallback: (info) => {
194
+ console.error('\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
195
+ console.error(' To sign in, open this URL in your browser:');
196
+ console.error(` ${info.verificationUri}`);
197
+ console.error(` Enter code: ${info.userCode}`);
198
+ console.error('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n');
199
+ },
200
+ });
201
+ const authRecord = await credential.authenticate(this.scopes);
202
+ this.assertCurrent(generation);
203
+ if (!authRecord)
204
+ throw new Error('Authentication failed — no record received');
205
+ this.state = { kind: 'connected', session: {
206
+ credential, authRecord, cacheName, emailAddress,
207
+ lastInteractiveAuthAt: new Date().toISOString(), tokenExpiresAt: null,
208
+ } };
209
+ }
210
+ catch (err) {
211
+ this.failed(err, previous, generation);
212
+ throw err;
213
+ }
214
+ // Persistence failure is distinct: retain the valid runtime session.
215
+ await this.persistMetadata(this.session(), generation);
125
216
  });
126
- this.authRecord = (await this.credential.authenticate(this.scopes)) ?? null;
127
- if (!this.authRecord)
128
- throw new Error('Authentication failed — no record received');
129
- this._lastInteractiveAuthAt = new Date().toISOString();
130
- this._needsReauth = false;
131
- // Persist metadata (not the tokens — those are in OS keychain via MSAL)
132
- await this.saveMetadata();
133
217
  }
134
218
  /**
135
219
  * Reconnect from a saved AuthenticationRecord (silent, no user interaction).
136
220
  */
137
- async reconnect() {
138
- const metadata = await this.loadMetadata();
139
- if (!metadata) {
140
- throw new Error(`No saved credentials for mailbox "${this.mailboxName}". Run: email-agent-mcp configure --mailbox ${this.mailboxName}`);
141
- }
142
- this.authRecord = metadata.authenticationRecord;
143
- this.cacheName = metadata.cacheName ?? this.getLegacyCacheName();
144
- this._lastInteractiveAuthAt = metadata.lastInteractiveAuthAt;
145
- this._emailAddress = metadata.emailAddress ?? null;
146
- this.credential = this.createPersistentCredential({
147
- clientId: metadata.clientId,
148
- tenantId: metadata.tenantId,
149
- authenticationRecord: this.authRecord,
150
- cacheName: this.cacheName,
151
- // This is the `serve` path. Without this, a cache that does not cover the
152
- // requested scopes makes DeviceCodeCredential silently start an interactive
153
- // device flow: it blocks for the whole polling window while the server sits
154
- // in `connecting`, and its default prompt callback writes to stdout — which
155
- // on an stdio MCP server is the JSON-RPC channel. Fail fast instead.
156
- disableAutomaticAuthentication: true,
157
- // Belt-and-braces: if a device prompt is ever reached here, keep it off stdout.
158
- userPromptCallback: (info) => {
159
- console.error(`[email-agent-mcp] Interactive sign-in required: ${info.verificationUri} code ${info.userCode}`);
160
- },
161
- });
162
- // Verify the token still works
163
- try {
164
- const token = await this.credential.getToken(this.scopes);
165
- this._tokenExpiresAt = token.expiresOnTimestamp;
166
- this._needsReauth = false;
221
+ reconnect(signal) {
222
+ if (signal?.aborted)
223
+ return Promise.reject(signal.reason);
224
+ if (this.reconnectFlight?.generation === this.generation && !this.reconnectFlight.controller.signal.aborted) {
225
+ return this.joinFlight(this.reconnectFlight, signal);
167
226
  }
168
- catch (err) {
169
- const message = err instanceof Error ? err.message : String(err);
170
- const name = err instanceof Error ? err.name : '';
171
- // AuthenticationRequiredError is what disableAutomaticAuthentication raises
172
- // when the cached token cannot satisfy `this.scopes` — the normal signal for
173
- // "this profile's scopes were never consented", not just an expired token.
174
- if (name === 'AuthenticationRequiredError'
175
- || message.includes('interaction_required')
176
- || message.includes('invalid_grant')) {
177
- this._needsReauth = true;
178
- throw new Error(`Cached credentials do not cover the scopes required by mailbox "${this.mailboxName}" `
179
- + `(scope profile "${this.config.scopeProfile ?? getEmailScopeProfile()}"). `
180
- + `Run: email-agent-mcp configure --mailbox ${this.mailboxName}`);
227
+ const controller = new AbortController();
228
+ const acquisitionSignal = controller.signal;
229
+ const promise = this.serialize(async (generation) => {
230
+ acquisitionSignal.throwIfAborted();
231
+ const previous = this.stableState();
232
+ this.state = { kind: 'connecting', previous };
233
+ try {
234
+ const metadata = await this.loadMetadata();
235
+ this.assertCurrent(generation);
236
+ acquisitionSignal.throwIfAborted();
237
+ if (!metadata) {
238
+ throw new Error(`No saved credentials for mailbox "${this.mailboxName}". Run: email-agent-mcp configure --mailbox ${this.mailboxName}`);
239
+ }
240
+ const cacheName = metadata.cacheName ?? this.getLegacyCacheName();
241
+ const credential = this.createPersistentCredential({
242
+ clientId: metadata.clientId,
243
+ tenantId: metadata.tenantId,
244
+ authenticationRecord: metadata.authenticationRecord,
245
+ cacheName,
246
+ // Serve must fail fast when the cache cannot satisfy the scopes.
247
+ // MSAL still handles silent cache hits and refresh-token redemption.
248
+ disableAutomaticAuthentication: true,
249
+ userPromptCallback: (info) => {
250
+ console.error(`[email-agent-mcp] Interactive sign-in required: ${info.verificationUri} code ${info.userCode}`);
251
+ },
252
+ });
253
+ const token = await credential.getToken(this.scopes, { abortSignal: acquisitionSignal });
254
+ this.assertCurrent(generation);
255
+ acquisitionSignal.throwIfAborted();
256
+ if (!token)
257
+ throw new Error('Failed to acquire token');
258
+ this.state = { kind: 'connected', session: {
259
+ credential, authRecord: metadata.authenticationRecord, cacheName,
260
+ lastInteractiveAuthAt: metadata.lastInteractiveAuthAt,
261
+ emailAddress: metadata.emailAddress ?? null, tokenExpiresAt: token.expiresOnTimestamp,
262
+ } };
181
263
  }
182
- throw err;
183
- }
264
+ catch (err) {
265
+ if (acquisitionSignal.aborted)
266
+ err = acquisitionSignal.reason;
267
+ this.failed(err, previous, generation);
268
+ // AuthenticationRequiredError also covers scopes never consented.
269
+ if (this.terminal(err)) {
270
+ throw new Error(`Cached credentials do not cover the scopes required by mailbox "${this.mailboxName}" `
271
+ + `(scope profile "${this.config.scopeProfile ?? getEmailScopeProfile()}"). `
272
+ + `Run: email-agent-mcp configure --mailbox ${this.mailboxName}`, { cause: err });
273
+ }
274
+ throw err;
275
+ }
276
+ });
277
+ const flight = { generation: this.generation, promise, controller, waiters: 0, settled: false };
278
+ this.reconnectFlight = flight;
279
+ void promise.finally(() => {
280
+ flight.settled = true;
281
+ if (this.reconnectFlight === flight)
282
+ this.reconnectFlight = null;
283
+ }).catch(() => { });
284
+ return this.joinFlight(flight, signal);
184
285
  }
185
286
  /**
186
287
  * Get a valid access token (refreshes automatically via MSAL cache).
187
288
  */
188
- async getAccessToken() {
189
- if (!this.credential) {
190
- throw new Error('Not connected. Call connect() or reconnect() first.');
289
+ getAccessToken(signal) {
290
+ if (signal?.aborted)
291
+ return Promise.reject(signal.reason);
292
+ if (this.tokenFlight?.generation === this.generation && !this.tokenFlight.controller.signal.aborted) {
293
+ return this.joinFlight(this.tokenFlight, signal);
191
294
  }
192
- try {
193
- const token = await this.credential.getToken(this.scopes);
194
- if (!token)
195
- throw new Error('Failed to acquire token');
196
- this._tokenExpiresAt = token.expiresOnTimestamp;
197
- return token.token;
198
- }
199
- catch (err) {
200
- const message = err instanceof Error ? err.message : String(err);
201
- if (message.includes('interaction_required') || message.includes('invalid_grant')) {
202
- this._needsReauth = true;
295
+ const controller = new AbortController();
296
+ const acquisitionSignal = controller.signal;
297
+ const promise = this.serialize(async (generation) => {
298
+ acquisitionSignal.throwIfAborted();
299
+ const previous = this.stableState();
300
+ const session = this.session();
301
+ if (!session) {
302
+ throw new Error('Not connected. Call connect() or reconnect() first.');
203
303
  }
204
- throw err;
205
- }
304
+ this.state = { kind: 'refreshing', session, previous, promise };
305
+ try {
306
+ const token = await session.credential.getToken(this.scopes, { abortSignal: acquisitionSignal });
307
+ this.assertCurrent(generation);
308
+ acquisitionSignal.throwIfAborted();
309
+ if (!token)
310
+ throw new Error('Failed to acquire token');
311
+ this.state = { kind: 'connected', session: { ...session, tokenExpiresAt: token.expiresOnTimestamp } };
312
+ return token.token;
313
+ }
314
+ catch (err) {
315
+ if (acquisitionSignal.aborted)
316
+ err = acquisitionSignal.reason;
317
+ this.failed(err, previous, generation);
318
+ throw err;
319
+ }
320
+ });
321
+ const flight = { generation: this.generation, promise, controller, waiters: 0, settled: false };
322
+ this.tokenFlight = flight;
323
+ void promise.finally(() => {
324
+ flight.settled = true;
325
+ if (this.tokenFlight === flight)
326
+ this.tokenFlight = null;
327
+ }).catch(() => { });
328
+ return this.joinFlight(flight, signal);
206
329
  }
207
330
  async refresh() {
208
331
  // MSAL handles refresh automatically via getToken() / cache
@@ -212,37 +335,35 @@ export class DelegatedAuthManager {
212
335
  * Attempt reconnect with single-flight guard — safe for concurrent callers.
213
336
  * Returns true if reconnect succeeded, false if it failed.
214
337
  */
215
- async tryReconnect() {
216
- if (this._reconnectPromise)
217
- return this._reconnectPromise;
218
- this._reconnectPromise = (async () => {
219
- try {
220
- console.error(`[email-agent-mcp] Attempting reconnect for mailbox "${this.mailboxName}"...`);
221
- await this.reconnect();
222
- console.error(`[email-agent-mcp] Reconnect succeeded for mailbox "${this.mailboxName}"`);
223
- return true;
224
- }
225
- catch (err) {
226
- console.error(`[email-agent-mcp] Reconnect failed for mailbox "${this.mailboxName}": ${err instanceof Error ? err.message : err}`);
227
- return false;
228
- }
229
- finally {
230
- this._reconnectPromise = null;
231
- }
232
- })();
233
- return this._reconnectPromise;
338
+ async tryReconnect(signal) {
339
+ try {
340
+ console.error(`[email-agent-mcp] Attempting reconnect for mailbox "${this.mailboxName}"...`);
341
+ await this.reconnect(signal);
342
+ console.error(`[email-agent-mcp] Reconnect succeeded for mailbox "${this.mailboxName}"`);
343
+ return true;
344
+ }
345
+ catch (err) {
346
+ console.error(`[email-agent-mcp] Reconnect failed for mailbox "${this.mailboxName}": ${err instanceof Error ? err.message : err}`);
347
+ return false;
348
+ }
234
349
  }
235
- async disconnect() {
236
- this.credential = null;
237
- this.authRecord = null;
238
- this.cacheName = null;
239
- this._tokenExpiresAt = null;
240
- this._reconnectPromise = null;
350
+ disconnect() {
351
+ const generation = ++this.generation;
352
+ this.state = { kind: 'disconnecting' };
353
+ const cancelled = new Error('Authentication operation cancelled by disconnect');
354
+ this.tokenFlight?.controller.abort(cancelled);
355
+ this.reconnectFlight?.controller.abort(cancelled);
356
+ const result = this.mutations.then(() => {
357
+ if (generation === this.generation)
358
+ this.state = { kind: 'disconnected', emailAddress: null };
359
+ });
360
+ this.mutations = result;
361
+ return result;
241
362
  }
242
363
  isTokenExpired() {
243
- if (this._needsReauth)
364
+ if (this.needsReauth)
244
365
  return true;
245
- if (this._tokenExpiresAt && Date.now() >= this._tokenExpiresAt)
366
+ if (this.tokenExpiresAt && Date.now() >= this.tokenExpiresAt)
246
367
  return true;
247
368
  return false;
248
369
  }
@@ -250,23 +371,23 @@ export class DelegatedAuthManager {
250
371
  * Check token health: returns a warning if approaching expiry.
251
372
  */
252
373
  getTokenHealthWarning() {
253
- if (this._needsReauth) {
374
+ if (this.needsReauth) {
254
375
  return `Authentication expired. Run: email-agent-mcp configure --mailbox ${this.mailboxName}`;
255
376
  }
256
- if (this._tokenExpiresAt && Date.now() > this._tokenExpiresAt) {
377
+ if (this.tokenExpiresAt && Date.now() > this.tokenExpiresAt) {
257
378
  return `Access token expired — next API call will attempt refresh`;
258
379
  }
259
- if (this._lastInteractiveAuthAt) {
260
- const daysSinceAuth = (Date.now() - new Date(this._lastInteractiveAuthAt).getTime()) / (1000 * 60 * 60 * 24);
380
+ if (this.lastInteractiveAuthAt) {
381
+ const daysSinceAuth = (Date.now() - new Date(this.lastInteractiveAuthAt).getTime()) / (1000 * 60 * 60 * 24);
261
382
  if (daysSinceAuth > 80) {
262
383
  return `Token may expire soon (last authenticated ${Math.round(daysSinceAuth)} days ago). Run: email-agent-mcp configure --mailbox ${this.mailboxName}`;
263
384
  }
264
385
  }
265
386
  return undefined;
266
387
  }
267
- getMetadataPath() {
268
- if (this._emailAddress) {
269
- return join(getConfigDir(), `${toFilesystemSafeKey(this._emailAddress)}.json`);
388
+ getMetadataPath(emailAddress) {
389
+ if (emailAddress) {
390
+ return join(getConfigDir(), `${toFilesystemSafeKey(emailAddress)}.json`);
270
391
  }
271
392
  return join(getConfigDir(), `${this.mailboxName}.json`);
272
393
  }
@@ -290,20 +411,43 @@ export class DelegatedAuthManager {
290
411
  },
291
412
  });
292
413
  }
293
- async saveMetadata() {
294
- const path = this.getMetadataPath();
295
- await mkdir(dirname(path), { recursive: true });
414
+ saveMetadata() {
415
+ return this.serialize(async (generation) => {
416
+ const session = this.session();
417
+ if (!session)
418
+ throw new Error('Not connected. Cannot save metadata.');
419
+ await this.persistMetadata(session, generation);
420
+ });
421
+ }
422
+ async persistMetadata(session, generation) {
423
+ const path = this.getMetadataPath(session.emailAddress);
296
424
  const metadata = {
297
425
  provider: 'microsoft',
298
- authenticationRecord: this.authRecord,
299
- cacheName: this.cacheName ?? undefined,
300
- lastInteractiveAuthAt: this._lastInteractiveAuthAt,
426
+ authenticationRecord: session.authRecord,
427
+ cacheName: session.cacheName,
428
+ lastInteractiveAuthAt: session.lastInteractiveAuthAt,
301
429
  clientId: this.config.clientId,
302
430
  tenantId: this.config.tenantId,
303
431
  mailboxName: this.mailboxName,
304
- emailAddress: this._emailAddress ?? undefined,
432
+ emailAddress: session.emailAddress ?? undefined,
305
433
  };
306
- await writeFile(path, JSON.stringify(metadata, null, 2), 'utf-8');
434
+ const temporary = `${path}.${randomUUID()}.tmp`;
435
+ try {
436
+ await mkdir(dirname(path), { recursive: true });
437
+ this.assertCurrent(generation);
438
+ await writeFile(temporary, JSON.stringify(metadata, null, 2), { encoding: 'utf-8', mode: 0o600 });
439
+ this.assertCurrent(generation);
440
+ // No await between the generation check and publication. A disconnect
441
+ // cannot interleave here; MSAL remains the sole owner of cached tokens.
442
+ renameSync(temporary, path);
443
+ }
444
+ catch (err) {
445
+ this.assertCurrent(generation);
446
+ throw new Error('Authenticated, but failed to persist Microsoft mailbox metadata', { cause: err });
447
+ }
448
+ finally {
449
+ await unlink(temporary).catch(() => { });
450
+ }
307
451
  }
308
452
  async loadMetadata() {
309
453
  // Use the public loadMailboxMetadata which handles both old-style (name-based)
@@ -344,57 +488,127 @@ export function isAuthError(err) {
344
488
  }
345
489
  return false;
346
490
  }
347
- /**
348
- * Client credentials auth manager (app-only / daemon).
349
- * Uses ClientSecretCredential from @azure/identity for real Azure AD authentication.
350
- */
351
491
  export class ClientCredentialsAuthManager {
352
- credential = null;
353
- accessToken;
354
- expiresAt;
492
+ state = { kind: 'disconnected' };
493
+ generation = 0;
494
+ mutations = Promise.resolve();
495
+ refreshFlight = null;
355
496
  config;
356
497
  static GRAPH_SCOPE = 'https://graph.microsoft.com/.default';
357
498
  constructor(config) {
358
499
  this.config = config;
359
500
  }
360
- async connect(_credentials) {
361
- if (!this.config.clientSecret || !this.config.tenantId) {
362
- throw new Error('Client credentials require clientSecret and tenantId');
501
+ stableState() {
502
+ switch (this.state.kind) {
503
+ case 'disconnected':
504
+ case 'connected':
505
+ case 'reauth_required': return this.state;
506
+ case 'connecting':
507
+ case 'refreshing': return this.state.previous;
508
+ case 'disconnecting': return { kind: 'disconnected' };
363
509
  }
364
- this.credential = new ClientSecretCredential(this.config.tenantId, this.config.clientId, this.config.clientSecret);
365
- const tokenResponse = await this.credential.getToken(ClientCredentialsAuthManager.GRAPH_SCOPE);
366
- if (!tokenResponse)
367
- throw new Error('Failed to acquire token via client credentials');
368
- this.accessToken = tokenResponse.token;
369
- this.expiresAt = tokenResponse.expiresOnTimestamp;
370
510
  }
371
- async refresh() {
372
- if (!this.credential) {
373
- throw new Error('Not connected. Call connect() first.');
374
- }
375
- const tokenResponse = await this.credential.getToken(ClientCredentialsAuthManager.GRAPH_SCOPE);
376
- if (!tokenResponse)
377
- throw new Error('Failed to refresh token via client credentials');
378
- this.accessToken = tokenResponse.token;
379
- this.expiresAt = tokenResponse.expiresOnTimestamp;
511
+ assertCurrent(generation) {
512
+ if (generation !== this.generation)
513
+ throw new Error('Authentication operation cancelled by disconnect');
380
514
  }
381
- async disconnect() {
382
- this.credential = null;
383
- this.accessToken = undefined;
384
- this.expiresAt = undefined;
515
+ serialize(operation) {
516
+ const generation = this.generation;
517
+ const result = this.mutations.then(() => {
518
+ this.assertCurrent(generation);
519
+ return operation(generation);
520
+ });
521
+ this.mutations = result.catch(() => { });
522
+ return result;
523
+ }
524
+ failed(err, previous, generation) {
525
+ this.assertCurrent(generation);
526
+ const terminal = err instanceof Error && (err.name === 'AuthenticationRequiredError'
527
+ || /invalid_client|invalid_grant|unauthorized_client|interaction_required/.test(err.message));
528
+ this.state = terminal
529
+ ? { kind: 'reauth_required', reason: err, session: previous.kind === 'disconnected' ? null : previous.session }
530
+ : previous;
531
+ }
532
+ connect(_credentials) {
533
+ return this.serialize(async (generation) => {
534
+ const previous = this.stableState();
535
+ this.state = { kind: 'connecting', previous };
536
+ if (!this.config.clientSecret || !this.config.tenantId || !this.config.clientId) {
537
+ this.state = { kind: 'reauth_required', reason: 'Missing client credentials', session: null };
538
+ throw new Error('Client credentials require clientSecret and tenantId (and clientId)');
539
+ }
540
+ try {
541
+ const credential = new ClientSecretCredential(this.config.tenantId, this.config.clientId, this.config.clientSecret);
542
+ const token = await credential.getToken(ClientCredentialsAuthManager.GRAPH_SCOPE);
543
+ this.assertCurrent(generation);
544
+ if (!token)
545
+ throw new Error('Failed to acquire token via client credentials');
546
+ this.state = { kind: 'connected', session: { credential, accessToken: token.token, expiresAt: token.expiresOnTimestamp } };
547
+ }
548
+ catch (err) {
549
+ this.failed(err, previous, generation);
550
+ throw err;
551
+ }
552
+ });
553
+ }
554
+ refresh() {
555
+ if (this.refreshFlight?.generation === this.generation)
556
+ return this.refreshFlight.promise;
557
+ const promise = this.serialize(async (generation) => {
558
+ const previous = this.stableState();
559
+ const session = previous.kind === 'disconnected' ? null : previous.session;
560
+ if (!session)
561
+ throw new Error('Not connected. Call connect() first.');
562
+ this.state = { kind: 'refreshing', session, previous, promise };
563
+ try {
564
+ const token = await session.credential.getToken(ClientCredentialsAuthManager.GRAPH_SCOPE);
565
+ this.assertCurrent(generation);
566
+ if (!token)
567
+ throw new Error('Failed to refresh token via client credentials');
568
+ this.state = { kind: 'connected', session: { ...session, accessToken: token.token, expiresAt: token.expiresOnTimestamp } };
569
+ }
570
+ catch (err) {
571
+ this.failed(err, previous, generation);
572
+ throw err;
573
+ }
574
+ });
575
+ const flight = { generation: this.generation, promise };
576
+ this.refreshFlight = flight;
577
+ void promise.finally(() => {
578
+ if (this.refreshFlight === flight)
579
+ this.refreshFlight = null;
580
+ }).catch(() => { });
581
+ return promise;
582
+ }
583
+ disconnect() {
584
+ const generation = ++this.generation;
585
+ this.state = { kind: 'disconnecting' };
586
+ const result = this.mutations.then(() => {
587
+ if (generation === this.generation)
588
+ this.state = { kind: 'disconnected' };
589
+ });
590
+ this.mutations = result;
591
+ return result;
385
592
  }
386
593
  isTokenExpired() {
387
- if (!this.expiresAt)
388
- return true;
389
- return Date.now() >= this.expiresAt;
594
+ const state = this.stableState();
595
+ return state.kind !== 'connected' || Date.now() >= state.session.expiresAt;
390
596
  }
391
597
  async getAccessToken() {
392
- if (!this.credential)
598
+ if (this.state.kind === 'disconnecting')
599
+ return undefined;
600
+ const generation = this.generation;
601
+ await (this.refreshFlight?.generation === generation ? this.refreshFlight.promise : this.mutations);
602
+ this.assertCurrent(generation);
603
+ const prior = this.stableState();
604
+ if (prior.kind === 'disconnected' || !prior.session)
393
605
  return undefined;
394
606
  if (this.isTokenExpired()) {
395
607
  await this.refresh();
396
608
  }
397
- return this.accessToken;
609
+ this.assertCurrent(generation);
610
+ const state = this.stableState();
611
+ return state.kind === 'connected' ? state.session.accessToken : undefined;
398
612
  }
399
613
  }
400
614
  /**