fluxmail 0.25.0 → 0.27.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/dist/accounts/googleAuth.d.ts +1 -1
  2. package/dist/accounts/googleAuth.d.ts.map +1 -1
  3. package/dist/accounts/googleAuth.js +1 -2
  4. package/dist/accounts/googleAuth.js.map +1 -1
  5. package/dist/accounts/registry.d.ts +1 -1
  6. package/dist/accounts/registry.d.ts.map +1 -1
  7. package/dist/accounts/registry.js +3 -2
  8. package/dist/accounts/registry.js.map +1 -1
  9. package/dist/accounts/timedImapFlow.d.ts +11 -0
  10. package/dist/accounts/timedImapFlow.d.ts.map +1 -0
  11. package/dist/accounts/timedImapFlow.js +49 -0
  12. package/dist/accounts/timedImapFlow.js.map +1 -0
  13. package/dist/authorization.d.ts +14 -4
  14. package/dist/authorization.d.ts.map +1 -1
  15. package/dist/authorization.js +18 -6
  16. package/dist/authorization.js.map +1 -1
  17. package/dist/cli.d.ts.map +1 -1
  18. package/dist/cli.js +88 -47
  19. package/dist/cli.js.map +1 -1
  20. package/dist/cliCloudAuth.d.ts +4 -3
  21. package/dist/cliCloudAuth.d.ts.map +1 -1
  22. package/dist/cliCloudAuth.js +4 -3
  23. package/dist/cliCloudAuth.js.map +1 -1
  24. package/dist/cliCloudClient.d.ts.map +1 -1
  25. package/dist/cliCloudClient.js +5 -3
  26. package/dist/cliCloudClient.js.map +1 -1
  27. package/dist/cliInstances.d.ts +8 -5
  28. package/dist/cliInstances.d.ts.map +1 -1
  29. package/dist/cliInstances.js +19 -10
  30. package/dist/cliInstances.js.map +1 -1
  31. package/dist/cliMail.d.ts.map +1 -1
  32. package/dist/cliMail.js +12 -3
  33. package/dist/cliMail.js.map +1 -1
  34. package/dist/http/admin.js +1 -1
  35. package/dist/http/admin.js.map +1 -1
  36. package/dist/http/identity.d.ts.map +1 -1
  37. package/dist/http/identity.js +4 -8
  38. package/dist/http/identity.js.map +1 -1
  39. package/dist/http/rest.d.ts.map +1 -1
  40. package/dist/http/rest.js +4 -1
  41. package/dist/http/rest.js.map +1 -1
  42. package/dist/mcp/attachmentContent.d.ts +1 -1
  43. package/dist/mcp/attachmentContent.js +1 -1
  44. package/dist/mcp/buildServer.d.ts.map +1 -1
  45. package/dist/mcp/buildServer.js +5 -3
  46. package/dist/mcp/buildServer.js.map +1 -1
  47. package/dist/mcp/outputSchemas.d.ts +3 -0
  48. package/dist/mcp/outputSchemas.d.ts.map +1 -1
  49. package/dist/mcp/outputSchemas.js +1 -1
  50. package/dist/mcp/outputSchemas.js.map +1 -1
  51. package/dist/operationTiming.d.ts +18 -0
  52. package/dist/operationTiming.d.ts.map +1 -0
  53. package/dist/operationTiming.js +42 -0
  54. package/dist/operationTiming.js.map +1 -0
  55. package/dist/permissions.d.ts +1 -1
  56. package/dist/permissions.d.ts.map +1 -1
  57. package/dist/permissions.js +2 -2
  58. package/dist/permissions.js.map +1 -1
  59. package/dist/service/deliveryCoordinator.d.ts +1 -0
  60. package/dist/service/deliveryCoordinator.d.ts.map +1 -1
  61. package/dist/service/deliveryCoordinator.js +4 -2
  62. package/dist/service/deliveryCoordinator.js.map +1 -1
  63. package/dist/service/emailService.d.ts +1 -0
  64. package/dist/service/emailService.d.ts.map +1 -1
  65. package/dist/service/emailService.js +2 -2
  66. package/dist/service/emailService.js.map +1 -1
  67. package/dist/service/publicErrors.d.ts +6 -0
  68. package/dist/service/publicErrors.d.ts.map +1 -1
  69. package/dist/service/publicErrors.js +21 -1
  70. package/dist/service/publicErrors.js.map +1 -1
  71. package/dist/stdioSetupRequired.d.ts +16 -0
  72. package/dist/stdioSetupRequired.d.ts.map +1 -0
  73. package/dist/stdioSetupRequired.js +53 -0
  74. package/dist/stdioSetupRequired.js.map +1 -0
  75. package/dist/telemetry.d.ts.map +1 -1
  76. package/dist/telemetry.js +17 -5
  77. package/dist/telemetry.js.map +1 -1
  78. package/package.json +16 -17
package/dist/cli.js CHANGED
@@ -13,6 +13,8 @@ import { EmailError, isEmailError } from '@fluxmail/core';
13
13
  import { PERMISSION_PRESET_NAMES } from '@fluxmail/core/mcp';
14
14
  import { closeAppContext, createContext } from './context.js';
15
15
  import { createStdioShutdown, shutDownOnClose } from './stdioShutdown.js';
16
+ import { newInstallationStore, setupRequiredMessage, setupRequiredService } from './stdioSetupRequired.js';
17
+ import { DEFAULT_MAX_ATTACHMENT_BYTES } from './deploymentConfig.js';
16
18
  import { RuntimeLifecycle } from './lifecycle.js';
17
19
  import { configTomlPath, createConfigurationService, deploymentToml, readLoggingSettings, resolveDataDir, resolveStoreLocation, writeDeploymentConfig, } from './config.js';
18
20
  import { migrateConfigurationFile, parseEnvContent, recognizedMigrationSettings } from './configMigration.js';
@@ -21,7 +23,6 @@ import { oauthIssuer } from './http/oauth.js';
21
23
  import { buildMcpServer } from './mcp/buildServer.js';
22
24
  import { runLoopbackFlow } from './accounts/googleAuth.js';
23
25
  import { runMicrosoftLoopbackFlow } from './accounts/microsoftAuth.js';
24
- import { IMAP_CONNECTION_TEST_TIMEOUT_MS } from './accounts/registry.js';
25
26
  import { assertHostedConnectionReady, prepareHostedGmailConnection, prepareHostedOutlookConnection, selectGmailConnectionMode, validateAccountConnectionFlags, } from './accounts/gmailConnection.js';
26
27
  import { listApiKeys } from './storage/apiKeys.js';
27
28
  import { findMember } from './storage/members.js';
@@ -43,6 +44,34 @@ import { createCliUpdateNotifier, startMcpUpdateCheck, } from './updateNotifier.
43
44
  import { registerMailCommands } from './cliMail.js';
44
45
  import { accountInventoryProperties, connectionFailureKind, configuredOAuthAppKind, connectionProperties, instanceUsageProperties, } from './accounts/telemetry.js';
45
46
  import { flushLogging, escapeLogTextForConsole, getLogger, logCodedFailure, logFailure, readLocalLogs, shutdownLogging, } from './logging.js';
47
+ /** Serves one stdio MCP session and releases it when the client disconnects. */
48
+ function serveStdioSession(service, options, release) {
49
+ const shutdown = createStdioShutdown({
50
+ flushTelemetry: shutdownTelemetry,
51
+ release,
52
+ report: (failures) => {
53
+ for (const failure of failures)
54
+ logFailure(options.logger, 'stdio.shutdown_failed', failure, {
55
+ productSurface: 'mcp',
56
+ operation: 'shutdown',
57
+ });
58
+ },
59
+ flushLogs: shutdownLogging,
60
+ });
61
+ const transport = new StdioServerTransport(process.stdin, process.stdout, {
62
+ // Allow base64 attachments plus the body and JSON envelope, as HTTP does.
63
+ maxBufferSize: Math.ceil((options.maxAttachmentBytes * 4) / 3) + 2 * 1024 * 1024,
64
+ });
65
+ const handle = serveStdio(() => buildMcpServer(service, options), {
66
+ transport,
67
+ onerror: (error) => logFailure(options.logger, 'mcp.transport_failed', error, {
68
+ productSurface: 'mcp',
69
+ operation: 'request',
70
+ }),
71
+ });
72
+ shutDownOnClose(transport, shutdown);
73
+ return handle;
74
+ }
46
75
  function collectOption(value, previous) {
47
76
  return [...previous, value];
48
77
  }
@@ -420,7 +449,7 @@ export function createCliProgram(options = {}) {
420
449
  .option('--instance <name>', 'Use a named local, remote, or Fluxmail Cloud instance')
421
450
  .option('-a, --mail-account <id-or-email>', 'Use an email account by ID or address')
422
451
  .option('--format <format>', 'Output format: json, table, or ndjson', 'json')
423
- .option('--timeout <seconds>', 'Request deadline in seconds (1 to 300)', '30')
452
+ .option('--timeout <seconds>', 'Request deadline in seconds, 1 to 300 (default: 45; mail commands on Fluxmail Cloud: 105)')
424
453
  .option('--no-update-notifier', 'Skip the automatic update check for this command')
425
454
  .version(VERSION, '-v, --version');
426
455
  const selectedInstance = () => program.opts().instance;
@@ -466,7 +495,8 @@ export function createCliProgram(options = {}) {
466
495
  }
467
496
  program.hook('preAction', (_command, actionCommand) => {
468
497
  selectedFormat();
469
- setRequestDeadlineMs(Number(program.opts().timeout) * 1000);
498
+ const timeout = program.opts().timeout;
499
+ setRequestDeadlineMs(timeout === undefined ? undefined : Number(timeout) * 1000);
470
500
  const command = commandPath(actionCommand);
471
501
  const updateNotifierEnabled = program.opts().updateNotifier;
472
502
  // Servers run their own update checks.
@@ -943,11 +973,21 @@ export function createCliProgram(options = {}) {
943
973
  .option('--allow <capability>', 'Allow one MCP capability, or add it to --profile; repeat as needed', collectOption, [])
944
974
  .action(async (opts) => {
945
975
  const startupPhase = (phase) => recordCliOperationProperties(program, { startup_phase: phase });
976
+ const noteDefaultPermissions = (usesDefault) => {
977
+ if (usesDefault) {
978
+ console.error(`No permission profile selected, so this connection uses the "${DEFAULT_PERMISSION_PROFILE}" profile ` +
979
+ `(${DEFAULT_PERMISSION_POLICY.capabilities.join(', ')}). ` +
980
+ 'Pass --profile read-only or --profile read-write to limit it: https://fluxmail.ai/docs/permissions');
981
+ }
982
+ };
946
983
  let ctx;
947
984
  let server;
948
985
  // The startup error path and the client's disconnect both release the session, so it closes once.
949
986
  let released;
950
- const release = (context) => (released ??= closeAppContext(context, [Promise.resolve().then(() => server?.close())]));
987
+ const closeServer = () => Promise.resolve().then(() => server?.close());
988
+ const release = (context) => (released ??= context
989
+ ? closeAppContext(context, [closeServer()])
990
+ : closeServer().then(() => [], (error) => [error]));
951
991
  try {
952
992
  recordCliOperationProperties(program, {
953
993
  startup_data_dir_source: process.env.FLUXMAIL_DATA_DIR ? 'environment' : 'default',
@@ -955,7 +995,43 @@ export function createCliProgram(options = {}) {
955
995
  });
956
996
  startupPhase('permissions');
957
997
  const permissions = permissionPolicyFromOptions(opts);
998
+ // The profile name only: "custom" stands in for any --allow list, so capabilities are never sent.
999
+ // The parser returns the shared default policy only when the launch chose nothing, including an
1000
+ // empty --profile from catalogs that fill "--profile={{setting}}" when nothing is set.
1001
+ const permissionProperties = {
1002
+ permission_profile: permissions.profile,
1003
+ permission_default: permissions === DEFAULT_PERMISSION_POLICY,
1004
+ };
1005
+ recordCliOperationProperties(program, permissionProperties);
958
1006
  startupPhase('instance');
1007
+ // A data directory without profiles or a database has never been set up. Serve the tool list so
1008
+ // clients and catalogs can start, and answer every call with the setup steps. Nothing is written
1009
+ // here, so a later "fluxmail setup" still sees a new installation.
1010
+ const newStore = selectedInstance() === undefined ? newInstallationStore() : undefined;
1011
+ if (newStore) {
1012
+ startupPhase('transport');
1013
+ const operation = activeCliOperations.get(program);
1014
+ const logger = operation?.logger ?? getLogger(newStore.dataDir, 'stdio', { level: 'info', destination: 'both' });
1015
+ installTelemetrySignalHandlers();
1016
+ server = serveStdioSession(setupRequiredService(setupRequiredMessage()), {
1017
+ permissions,
1018
+ feedback: {
1019
+ enabled: newStore.deployment?.feedbackEnabled,
1020
+ cloudOrigin: newStore.deployment?.feedbackCloudOrigin,
1021
+ },
1022
+ maxAttachmentBytes: newStore.deployment?.maxAttachmentBytes ?? DEFAULT_MAX_ATTACHMENT_BYTES,
1023
+ telemetry: operation?.telemetry ?? getTelemetry(newStore.dataDir),
1024
+ transport: 'stdio',
1025
+ logger,
1026
+ ...(program.opts().updateNotifier
1027
+ ? { availableUpdate: startMcpUpdateCheck() }
1028
+ : {}),
1029
+ }, () => release());
1030
+ console.error(setupRequiredMessage(newStore.dataDir));
1031
+ noteDefaultPermissions(permissionProperties.permission_default);
1032
+ startupPhase('setup_required');
1033
+ return;
1034
+ }
959
1035
  const selected = resolveStdioInstance(selectedInstance());
960
1036
  startupPhase('authentication');
961
1037
  if (!selected.token)
@@ -983,34 +1059,12 @@ export function createCliProgram(options = {}) {
983
1059
  };
984
1060
  installTelemetrySignalHandlers();
985
1061
  const context = ctx;
986
- const shutdown = createStdioShutdown({
987
- flushTelemetry: shutdownTelemetry,
988
- release: () => release(context),
989
- report: (failures) => {
990
- for (const failure of failures)
991
- logFailure(context.logger, 'stdio.shutdown_failed', failure, {
992
- productSurface: 'mcp',
993
- operation: 'shutdown',
994
- });
995
- },
996
- flushLogs: shutdownLogging,
997
- });
998
- const transport = new StdioServerTransport(process.stdin, process.stdout, {
999
- // Allow base64 attachments plus the body and JSON envelope, as HTTP does.
1000
- maxBufferSize: Math.ceil((ctx.config.maxAttachmentBytes * 4) / 3) + 2 * 1024 * 1024,
1001
- });
1002
- server = serveStdio(() => buildMcpServer(scopedService, mcpOptions), {
1003
- transport,
1004
- onerror: (error) => logFailure(mcpOptions.logger, 'mcp.transport_failed', error, {
1005
- productSurface: 'mcp',
1006
- operation: 'request',
1007
- }),
1008
- });
1009
- shutDownOnClose(transport, shutdown);
1062
+ server = serveStdioSession(scopedService, mcpOptions, () => release(context));
1010
1063
  ctx.telemetry.capture('mcp server started', {
1011
1064
  ...instanceUsageProperties(ctx.db),
1012
1065
  product_surface: 'mcp',
1013
1066
  transport: 'stdio',
1067
+ ...permissionProperties,
1014
1068
  });
1015
1069
  ctx.logger.info('server.started', 'Fluxmail stdio MCP server started', {
1016
1070
  productSurface: 'mcp',
@@ -1020,10 +1074,7 @@ export function createCliProgram(options = {}) {
1020
1074
  // stdout belongs to the MCP protocol; log to stderr only.
1021
1075
  ctx.licenseController.start();
1022
1076
  console.error('Fluxmail MCP server running on stdio');
1023
- if (!opts.profile && !opts.allow.length) {
1024
- console.error('No permission profile selected, so this connection is read-only. ' +
1025
- 'Add --profile or --allow to enable drafts, organizing, or sending: https://fluxmail.ai/docs/permissions');
1026
- }
1077
+ noteDefaultPermissions(permissionProperties.permission_default);
1027
1078
  warnLicense(ctx.db);
1028
1079
  const pending = permissions.capabilities.includes('mail.read')
1029
1080
  ? scopedService.listScheduled().filter((send) => send.status === 'pending').length
@@ -1034,8 +1085,7 @@ export function createCliProgram(options = {}) {
1034
1085
  }
1035
1086
  catch (error) {
1036
1087
  finishCliOperation(program, 'error', apiErrorCode(error), error);
1037
- if (ctx)
1038
- await release(ctx);
1088
+ await release(ctx);
1039
1089
  throw error;
1040
1090
  }
1041
1091
  });
@@ -1250,16 +1300,7 @@ export function createCliProgram(options = {}) {
1250
1300
  },
1251
1301
  };
1252
1302
  }
1253
- // The server's IMAP connection check has its own 30-second limit. Give
1254
- // its response a small margin so the CLI reports the server's result.
1255
- const requestTimeoutMs = provider === 'imap' && program.getOptionValueSource('timeout') === 'default'
1256
- ? IMAP_CONNECTION_TEST_TIMEOUT_MS + 5_000
1257
- : undefined;
1258
- const requestTimeoutClass = program.getOptionValueSource('timeout') !== 'default'
1259
- ? 'custom'
1260
- : requestTimeoutMs
1261
- ? 'imap_margin'
1262
- : 'default';
1303
+ const requestTimeoutClass = program.opts().timeout === undefined ? 'default' : 'custom';
1263
1304
  const requestId = randomUUID();
1264
1305
  recordCliOperationProperties(program, {
1265
1306
  connection_stage: 'connection_request',
@@ -1268,7 +1309,7 @@ export function createCliProgram(options = {}) {
1268
1309
  const requestStartedAt = performance.now();
1269
1310
  let result;
1270
1311
  try {
1271
- result = await instanceClient(selected.name, true, requestTimeoutMs).json('/api/v1/accounts/connections', {
1312
+ result = await instanceClient(selected.name, true).json('/api/v1/accounts/connections', {
1272
1313
  method: 'POST',
1273
1314
  headers: { 'content-type': 'application/json', 'x-request-id': requestId },
1274
1315
  body: JSON.stringify(request),
@@ -1363,7 +1404,7 @@ export function createCliProgram(options = {}) {
1363
1404
  .listAccounts()
1364
1405
  .find((candidate) => candidate.email.toLowerCase() === result.email.toLowerCase());
1365
1406
  if (duplicate)
1366
- requireConnectionChange(principal, duplicate);
1407
+ requireConnectionChange(principal, duplicate, { byAddress: true });
1367
1408
  if (existing && result.email.toLowerCase() !== existing.email.toLowerCase()) {
1368
1409
  throw new EmailError('invalid_request', `Microsoft authorized ${result.email}, but account ${existing.id} belongs to ${existing.email}. ` +
1369
1410
  'Try again and choose the matching Microsoft account.');
@@ -1401,7 +1442,7 @@ export function createCliProgram(options = {}) {
1401
1442
  .listAccounts()
1402
1443
  .find((candidate) => candidate.email.toLowerCase() === result.email.toLowerCase());
1403
1444
  if (duplicate)
1404
- requireConnectionChange(principal, duplicate);
1445
+ requireConnectionChange(principal, duplicate, { byAddress: true });
1405
1446
  if (existing && result.email !== existing.email) {
1406
1447
  throw new EmailError('invalid_request', `Google authorized ${result.email}, but account ${existing.id} belongs to ${existing.email}. ` +
1407
1448
  'Try again and choose the matching Google account.');