fluxmail 0.23.0 → 0.25.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 (74) hide show
  1. package/dist/auth.d.ts +2 -0
  2. package/dist/auth.d.ts.map +1 -1
  3. package/dist/auth.js +1 -0
  4. package/dist/auth.js.map +1 -1
  5. package/dist/authorization.d.ts +42 -4
  6. package/dist/authorization.d.ts.map +1 -1
  7. package/dist/authorization.js +94 -6
  8. package/dist/authorization.js.map +1 -1
  9. package/dist/cli.d.ts +0 -4
  10. package/dist/cli.d.ts.map +1 -1
  11. package/dist/cli.js +94 -75
  12. package/dist/cli.js.map +1 -1
  13. package/dist/cliMail.d.ts.map +1 -1
  14. package/dist/cliMail.js +8 -2
  15. package/dist/cliMail.js.map +1 -1
  16. package/dist/cliMailBackend.d.ts.map +1 -1
  17. package/dist/cliMailBackend.js +56 -6
  18. package/dist/cliMailBackend.js.map +1 -1
  19. package/dist/context.d.ts +6 -0
  20. package/dist/context.d.ts.map +1 -1
  21. package/dist/context.js +29 -0
  22. package/dist/context.js.map +1 -1
  23. package/dist/http/admin.d.ts.map +1 -1
  24. package/dist/http/admin.js +28 -7
  25. package/dist/http/admin.js.map +1 -1
  26. package/dist/http/app.d.ts.map +1 -1
  27. package/dist/http/app.js +7 -2
  28. package/dist/http/app.js.map +1 -1
  29. package/dist/http/identity.d.ts +4 -0
  30. package/dist/http/identity.d.ts.map +1 -1
  31. package/dist/http/identity.js +110 -46
  32. package/dist/http/identity.js.map +1 -1
  33. package/dist/http/rest.d.ts.map +1 -1
  34. package/dist/http/rest.js +25 -18
  35. package/dist/http/rest.js.map +1 -1
  36. package/dist/lifecycle.d.ts +1 -1
  37. package/dist/lifecycle.d.ts.map +1 -1
  38. package/dist/lifecycle.js +2 -20
  39. package/dist/lifecycle.js.map +1 -1
  40. package/dist/mcp/buildServer.d.ts.map +1 -1
  41. package/dist/mcp/buildServer.js +219 -135
  42. package/dist/mcp/buildServer.js.map +1 -1
  43. package/dist/mcp/outputSchemas.d.ts +1 -37
  44. package/dist/mcp/outputSchemas.d.ts.map +1 -1
  45. package/dist/mcp/outputSchemas.js +1 -2
  46. package/dist/mcp/outputSchemas.js.map +1 -1
  47. package/dist/permissions.d.ts +2 -2
  48. package/dist/permissions.d.ts.map +1 -1
  49. package/dist/permissions.js +2 -7
  50. package/dist/permissions.js.map +1 -1
  51. package/dist/service/emailService.d.ts +21 -5
  52. package/dist/service/emailService.d.ts.map +1 -1
  53. package/dist/service/emailService.js +86 -42
  54. package/dist/service/emailService.js.map +1 -1
  55. package/dist/stdioShutdown.d.ts +27 -0
  56. package/dist/stdioShutdown.d.ts.map +1 -0
  57. package/dist/stdioShutdown.js +65 -0
  58. package/dist/stdioShutdown.js.map +1 -0
  59. package/dist/storage/apiKeys.d.ts +15 -3
  60. package/dist/storage/apiKeys.d.ts.map +1 -1
  61. package/dist/storage/apiKeys.js +34 -7
  62. package/dist/storage/apiKeys.js.map +1 -1
  63. package/dist/storage/db.d.ts +21 -2
  64. package/dist/storage/db.d.ts.map +1 -1
  65. package/dist/storage/db.js +15 -2
  66. package/dist/storage/db.js.map +1 -1
  67. package/dist/storage/imapState.d.ts.map +1 -1
  68. package/dist/storage/imapState.js +9 -0
  69. package/dist/storage/imapState.js.map +1 -1
  70. package/dist/storage/members.d.ts +8 -3
  71. package/dist/storage/members.d.ts.map +1 -1
  72. package/dist/storage/members.js +36 -7
  73. package/dist/storage/members.js.map +1 -1
  74. package/package.json +5 -5
package/dist/cli.js CHANGED
@@ -11,7 +11,8 @@ import { serve } from '@hono/node-server';
11
11
  import { serveStdio, StdioServerTransport } from '@modelcontextprotocol/server/stdio';
12
12
  import { EmailError, isEmailError } from '@fluxmail/core';
13
13
  import { PERMISSION_PRESET_NAMES } from '@fluxmail/core/mcp';
14
- import { createContext } from './context.js';
14
+ import { closeAppContext, createContext } from './context.js';
15
+ import { createStdioShutdown, shutDownOnClose } from './stdioShutdown.js';
15
16
  import { RuntimeLifecycle } from './lifecycle.js';
16
17
  import { configTomlPath, createConfigurationService, deploymentToml, readLoggingSettings, resolveDataDir, resolveStoreLocation, writeDeploymentConfig, } from './config.js';
17
18
  import { migrateConfigurationFile, parseEnvContent, recognizedMigrationSettings } from './configMigration.js';
@@ -29,7 +30,7 @@ import { checkLicenseState, getEntitlements } from './licensing/entitlements.js'
29
30
  import { VERSION } from './version.js';
30
31
  import { inspectStoreCompatibility, MIN_SUPPORTED_STORE_FORMAT, openDb, openReadonlyDb, } from './storage/db.js';
31
32
  import { customPermissionPolicy, ADMIN_CAPABILITIES, DEFAULT_PERMISSION_POLICY, DEFAULT_PERMISSION_PROFILE, isNamedPermissionProfile, MCP_CAPABILITIES, NAMED_PERMISSION_PROFILES, permissionPolicyForProfile, } from './permissions.js';
32
- import { captureOperation, getTelemetry, installTelemetryStreamEndHandler, isTelemetryEnabled, setTelemetryEnabled, shutdownTelemetry, telemetryDisabledInAnyEnvironment, } from './telemetry.js';
33
+ import { captureOperation, getTelemetry, isTelemetryEnabled, setTelemetryEnabled, shutdownTelemetry, telemetryDisabledInAnyEnvironment, } from './telemetry.js';
33
34
  import { cloudManagementError, apiErrorCode, CliCanceledError, apiRequestId, clearSessionToken, instanceClient, loadInstanceConfig, removeInstance, resolveInstance, resolveStdioInstance, saveLocalInstance, saveRemoteInstance, saveSessionToken, setRequestDeadlineMs, useInstance, validateRemoteServerUrl, } from './cliInstances.js';
34
35
  import { DEFAULT_CLOUD_ORIGIN, loginToCloud, logoutOfCloud, openInBrowser, replaceCloudSession, } from './cliCloudAuth.js';
35
36
  import { CloudMailBackend, mailBackend } from './cliMailBackend.js';
@@ -37,7 +38,7 @@ import { cliExitCode, parseOutputFormat, printOutput } from './cliOutput.js';
37
38
  import { CliStartupError, cliStartupDiagnostics } from './cliStartupDiagnostics.js';
38
39
  import { authenticateBearer, isBootstrapComplete, normalizeAndValidatePassword, recoverAdminPassword, setupInitialAdmin, } from './auth.js';
39
40
  import { recordAdminAuditEvent } from './storage/adminAudit.js';
40
- import { canManageOwnedAccount } from './authorization.js';
41
+ import { requireConnectionChange } from './authorization.js';
41
42
  import { createCliUpdateNotifier, startMcpUpdateCheck, } from './updateNotifier.js';
42
43
  import { registerMailCommands } from './cliMail.js';
43
44
  import { accountInventoryProperties, connectionFailureKind, configuredOAuthAppKind, connectionProperties, instanceUsageProperties, } from './accounts/telemetry.js';
@@ -85,6 +86,34 @@ export function permissionPolicyForUpdate(opts, existing) {
85
86
  }
86
87
  return permissionPolicyForProfile(existing.permissionProfile, supplemental);
87
88
  }
89
+ /**
90
+ * The mailboxes a key or OAuth connection may use. A key someone else created reaches
91
+ * only mailboxes both its owner and its creator can read.
92
+ */
93
+ function accountScopeLabel(accountIds, limitedToCreator = false) {
94
+ if (accountIds === null)
95
+ return limitedToCreator ? 'all granted to both' : 'all granted';
96
+ if (!accountIds.length)
97
+ return 'none';
98
+ const ids = accountIds.join(',');
99
+ return limitedToCreator ? `${ids} if granted to both` : ids;
100
+ }
101
+ function apiKeyLine(key) {
102
+ const lastUsed = key.lastUsedAt ? new Date(key.lastUsedAt).toISOString() : 'never';
103
+ // Servers before 0.25.0 don't return issuedByMemberId.
104
+ const delegated = Boolean(key.issuedByMemberId);
105
+ let issuer = '';
106
+ if (delegated) {
107
+ issuer = ` issuedBy=${key.issuedByEmail ?? key.issuedByMemberId}`;
108
+ if (key.issuedByStatus && key.issuedByStatus !== 'active')
109
+ issuer += ` (${key.issuedByStatus}, key disabled)`;
110
+ }
111
+ return (`${key.id} ${key.name} member=${key.memberId}${issuer}` +
112
+ ` accounts=${accountScopeLabel(key.accountIds, delegated)} profile=${key.permissionProfile}` +
113
+ (key.permissionProfile === 'custom' ? ` allows=${key.capabilities.join(',')}` : '') +
114
+ (key.supplementalCapabilities.length ? ` admin=${key.supplementalCapabilities.join(',')}` : '') +
115
+ ` created=${new Date(key.createdAt).toISOString()} lastUsed=${lastUsed}`);
116
+ }
88
117
  function connectionPort(value, option) {
89
118
  const port = Number(value);
90
119
  if (!Number.isInteger(port) || port < 1 || port > 65_535) {
@@ -260,20 +289,9 @@ async function inspectLocalRegistry(inspect) {
260
289
  return undefined;
261
290
  }
262
291
  finally {
263
- if (context) {
264
- try {
265
- await context.registry.close();
266
- }
267
- catch {
268
- // Telemetry cleanup must not affect the command.
269
- }
270
- try {
271
- context.db.$client.close();
272
- }
273
- catch {
274
- // Telemetry cleanup must not affect the command.
275
- }
276
- }
292
+ // Cleanup failures must not affect the command, so they are dropped.
293
+ if (context)
294
+ await closeAppContext(context);
277
295
  }
278
296
  }
279
297
  function finishCliOperation(program, outcome, errorCode, error,
@@ -383,14 +401,6 @@ export function waitForServerListening(server) {
383
401
  server.once('listening', onListening);
384
402
  });
385
403
  }
386
- async function shutdownTelemetryThenLogging() {
387
- try {
388
- await shutdownTelemetry();
389
- }
390
- finally {
391
- await shutdownLogging();
392
- }
393
- }
394
404
  export async function shutdownTelemetryAndLogging() {
395
405
  const initialLogFlush = flushLogging().catch(() => { });
396
406
  try {
@@ -401,9 +411,6 @@ export async function shutdownTelemetryAndLogging() {
401
411
  await shutdownLogging();
402
412
  }
403
413
  }
404
- export function installStdioShutdownHandler(stream) {
405
- installTelemetryStreamEndHandler(stream, shutdownTelemetryThenLogging);
406
- }
407
414
  /** Build the command tree without parsing arguments or running command actions. */
408
415
  export function createCliProgram(options = {}) {
409
416
  const program = new Command();
@@ -528,6 +535,7 @@ export function createCliProgram(options = {}) {
528
535
  const [group, action] = command.split(' ');
529
536
  const alreadyStructured = ['folders', 'labels', 'emails', 'threads', 'drafts', 'scheduled', 'attachments'].includes(group ?? '') ||
530
537
  command === 'accounts list' ||
538
+ command === 'apikey list' ||
531
539
  command === 'status';
532
540
  const interactive = ['setup', 'login', 'serve', 'stdio', 'scheduled run'].includes(command) ||
533
541
  group === 'auth' ||
@@ -937,6 +945,9 @@ export function createCliProgram(options = {}) {
937
945
  const startupPhase = (phase) => recordCliOperationProperties(program, { startup_phase: phase });
938
946
  let ctx;
939
947
  let server;
948
+ // The startup error path and the client's disconnect both release the session, so it closes once.
949
+ let released;
950
+ const release = (context) => (released ??= closeAppContext(context, [Promise.resolve().then(() => server?.close())]));
940
951
  try {
941
952
  recordCliOperationProperties(program, {
942
953
  startup_data_dir_source: process.env.FLUXMAIL_DATA_DIR ? 'environment' : 'default',
@@ -971,17 +982,31 @@ export function createCliProgram(options = {}) {
971
982
  : {}),
972
983
  };
973
984
  installTelemetrySignalHandlers();
974
- installStdioShutdownHandler(process.stdin);
985
+ 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
+ });
975
1002
  server = serveStdio(() => buildMcpServer(scopedService, mcpOptions), {
976
- transport: new StdioServerTransport(process.stdin, process.stdout, {
977
- // Allow base64 attachments plus the body and JSON envelope, as HTTP does.
978
- maxBufferSize: Math.ceil((ctx.config.maxAttachmentBytes * 4) / 3) + 2 * 1024 * 1024,
979
- }),
1003
+ transport,
980
1004
  onerror: (error) => logFailure(mcpOptions.logger, 'mcp.transport_failed', error, {
981
1005
  productSurface: 'mcp',
982
1006
  operation: 'request',
983
1007
  }),
984
1008
  });
1009
+ shutDownOnClose(transport, shutdown);
985
1010
  ctx.telemetry.capture('mcp server started', {
986
1011
  ...instanceUsageProperties(ctx.db),
987
1012
  product_surface: 'mcp',
@@ -1009,19 +1034,8 @@ export function createCliProgram(options = {}) {
1009
1034
  }
1010
1035
  catch (error) {
1011
1036
  finishCliOperation(program, 'error', apiErrorCode(error), error);
1012
- if (ctx) {
1013
- const context = ctx;
1014
- await Promise.allSettled([
1015
- Promise.resolve().then(() => context.scheduler.stop()),
1016
- Promise.resolve().then(() => context.licenseController.stop()),
1017
- Promise.resolve().then(() => server?.close()),
1018
- ]);
1019
- await context.registry.close().catch(() => { });
1020
- try {
1021
- context.db.$client.close();
1022
- }
1023
- catch { }
1024
- }
1037
+ if (ctx)
1038
+ await release(ctx);
1025
1039
  throw error;
1026
1040
  }
1027
1041
  });
@@ -1305,9 +1319,8 @@ export function createCliProgram(options = {}) {
1305
1319
  }
1306
1320
  const owner = findMember(ctx.db, principal.memberId);
1307
1321
  const existing = opts.reauthorize ? ctx.registry.getAccount(opts.reauthorize) : undefined;
1308
- if (existing && !canManageOwnedAccount(principal, existing)) {
1309
- throw new EmailError('permission_denied', 'Only the mailbox owner or an administrator can reauthorize it.');
1310
- }
1322
+ if (existing)
1323
+ requireConnectionChange(principal, existing);
1311
1324
  if (existing && existing.provider !== provider) {
1312
1325
  throw new EmailError('invalid_request', `Account ${existing.id} uses ${existing.provider}, not ${provider}.`);
1313
1326
  }
@@ -1349,9 +1362,8 @@ export function createCliProgram(options = {}) {
1349
1362
  const duplicate = ctx.registry
1350
1363
  .listAccounts()
1351
1364
  .find((candidate) => candidate.email.toLowerCase() === result.email.toLowerCase());
1352
- if (duplicate && !canManageOwnedAccount(principal, duplicate)) {
1353
- throw new EmailError('permission_denied', 'Only the mailbox owner or an administrator can reauthorize it.');
1354
- }
1365
+ if (duplicate)
1366
+ requireConnectionChange(principal, duplicate);
1355
1367
  if (existing && result.email.toLowerCase() !== existing.email.toLowerCase()) {
1356
1368
  throw new EmailError('invalid_request', `Microsoft authorized ${result.email}, but account ${existing.id} belongs to ${existing.email}. ` +
1357
1369
  'Try again and choose the matching Microsoft account.');
@@ -1388,9 +1400,8 @@ export function createCliProgram(options = {}) {
1388
1400
  const duplicate = ctx.registry
1389
1401
  .listAccounts()
1390
1402
  .find((candidate) => candidate.email.toLowerCase() === result.email.toLowerCase());
1391
- if (duplicate && !canManageOwnedAccount(principal, duplicate)) {
1392
- throw new EmailError('permission_denied', 'Only the mailbox owner or an administrator can reauthorize it.');
1393
- }
1403
+ if (duplicate)
1404
+ requireConnectionChange(principal, duplicate);
1394
1405
  if (existing && result.email !== existing.email) {
1395
1406
  throw new EmailError('invalid_request', `Google authorized ${result.email}, but account ${existing.id} belongs to ${existing.email}. ` +
1396
1407
  'Try again and choose the matching Google account.');
@@ -1496,10 +1507,10 @@ export function createCliProgram(options = {}) {
1496
1507
  .command('assign')
1497
1508
  .argument('<accountId>')
1498
1509
  .requiredOption('--owner <member>', 'Member id or email to own the mailbox')
1499
- .description('Change mailbox ownership')
1510
+ .description('Hand a mailbox you own to another member')
1500
1511
  .action(async (accountId, opts) => {
1501
1512
  try {
1502
- const account = await instanceClient(selectedInstance()).json(`/api/v1/admin/accounts/${encodeURIComponent(accountId)}`, {
1513
+ const account = await instanceClient(selectedInstance()).json(`/api/v1/accounts/${encodeURIComponent(accountId)}/access`, {
1503
1514
  method: 'PATCH',
1504
1515
  headers: { 'content-type': 'application/json' },
1505
1516
  body: JSON.stringify({ ownerMemberId: opts.owner }),
@@ -1516,14 +1527,14 @@ export function createCliProgram(options = {}) {
1516
1527
  .option('--owner-only', 'Only the owner can access the mailbox')
1517
1528
  .option('--shared', 'Share the mailbox with every member')
1518
1529
  .option('--share-with <member>', 'Replace selected access with this member; repeat as needed', collectOption, [])
1519
- .description('Set who can access a mailbox')
1530
+ .description('Set who can access a mailbox you own')
1520
1531
  .action(async (accountId, opts) => {
1521
1532
  try {
1522
1533
  const choices = Number(Boolean(opts.ownerOnly)) + Number(Boolean(opts.shared)) + Number(opts.shareWith.length > 0);
1523
1534
  if (choices !== 1) {
1524
1535
  throw new EmailError('invalid_request', 'Pass exactly one of --owner-only, --shared, or one or more --share-with options.');
1525
1536
  }
1526
- const account = await instanceClient(selectedInstance()).json(`/api/v1/admin/accounts/${encodeURIComponent(accountId)}`, {
1537
+ const account = await instanceClient(selectedInstance()).json(`/api/v1/accounts/${encodeURIComponent(accountId)}/access`, {
1527
1538
  method: 'PATCH',
1528
1539
  headers: { 'content-type': 'application/json' },
1529
1540
  body: JSON.stringify({ sharedWithAll: opts.shared === true, grantedMemberIds: opts.shareWith }),
@@ -1580,13 +1591,15 @@ export function createCliProgram(options = {}) {
1580
1591
  membersCmd
1581
1592
  .command('remove')
1582
1593
  .argument('<memberId>')
1583
- .description('Remove a member after reassigning or removing their mailboxes')
1584
- .action(async (memberId) => {
1594
+ .option('--reassign-to <member>', "Member id or email to receive the removed member's mailboxes")
1595
+ .description('Remove a member, handing their mailboxes to another member')
1596
+ .action(async (memberId, opts) => {
1585
1597
  try {
1586
- await instanceClient(selectedInstance()).json(`/api/v1/admin/members/${encodeURIComponent(memberId)}`, {
1587
- method: 'DELETE',
1588
- });
1589
- console.log(`Removed ${memberId}.`);
1598
+ const query = opts.reassignTo ? `?${new URLSearchParams({ reassignTo: opts.reassignTo })}` : '';
1599
+ const result = await instanceClient(selectedInstance()).json(`/api/v1/admin/members/${encodeURIComponent(memberId)}${query}`, { method: 'DELETE' });
1600
+ console.log(result.reassignedAccounts > 0
1601
+ ? `Removed ${memberId}. ${result.reassignedAccounts === 1 ? '1 mailbox now belongs' : `${result.reassignedAccounts} mailboxes now belong`} to ${opts.reassignTo}.`
1602
+ : `Removed ${memberId}.`);
1590
1603
  }
1591
1604
  catch (err) {
1592
1605
  failCliOperation(program, err);
@@ -1745,18 +1758,24 @@ export function createCliProgram(options = {}) {
1745
1758
  const client = instanceClient(selectedInstance());
1746
1759
  const me = await client.json('/api/v1/me');
1747
1760
  const keys = await client.json(me.role === 'admin' ? '/api/v1/admin/api-keys' : '/api/v1/me/api-keys');
1761
+ if (selectedFormat() !== 'table') {
1762
+ // The member route returns epoch milliseconds and the admin route ISO strings; print one shape.
1763
+ const isoTime = (value) => (value === null ? null : new Date(value).toISOString());
1764
+ printOutput({
1765
+ data: keys.map((key) => ({
1766
+ ...key,
1767
+ createdAt: isoTime(key.createdAt),
1768
+ lastUsedAt: isoTime(key.lastUsedAt),
1769
+ })),
1770
+ }, selectedFormat());
1771
+ return;
1772
+ }
1748
1773
  if (!keys.length) {
1749
1774
  console.log('No API keys. Run "fluxmail apikey create --name <name>".');
1750
1775
  return;
1751
1776
  }
1752
- for (const k of keys) {
1753
- const lastUsed = k.lastUsedAt ? new Date(k.lastUsedAt).toISOString() : 'never';
1754
- const accountScope = k.accountIds === null ? 'all granted' : k.accountIds.join(',') || 'none';
1755
- console.log(`${k.id} ${k.name} member=${k.memberId} accounts=${accountScope} profile=${k.permissionProfile}` +
1756
- (k.permissionProfile === 'custom' ? ` allows=${k.capabilities.join(',')}` : '') +
1757
- (k.supplementalCapabilities.length ? ` admin=${k.supplementalCapabilities.join(',')}` : '') +
1758
- ` created=${new Date(k.createdAt).toISOString()} lastUsed=${lastUsed}`);
1759
- }
1777
+ for (const key of keys)
1778
+ console.log(apiKeyLine(key));
1760
1779
  }
1761
1780
  catch (err) {
1762
1781
  failCliOperation(program, err);
@@ -1860,8 +1879,8 @@ export function createCliProgram(options = {}) {
1860
1879
  }
1861
1880
  for (const connection of connections) {
1862
1881
  const lastUsed = connection.lastUsedAt ? new Date(connection.lastUsedAt).toISOString() : 'never';
1863
- const accountScope = connection.accountIds === null ? 'all granted' : connection.accountIds.join(',');
1864
- console.log(`${connection.id} ${connection.clientName} member=${connection.memberId} accounts=${accountScope}` +
1882
+ console.log(`${connection.id} ${connection.clientName} member=${connection.memberId}` +
1883
+ ` accounts=${accountScopeLabel(connection.accountIds)}` +
1865
1884
  ` allows=${connection.scopes.join(',')} created=${new Date(connection.createdAt).toISOString()}` +
1866
1885
  ` expires=${new Date(connection.expiresAt).toISOString()} lastUsed=${lastUsed}`);
1867
1886
  }