fluxmail 0.24.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 (64) 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 -12
  10. package/dist/cli.d.ts.map +1 -1
  11. package/dist/cli.js +92 -90
  12. package/dist/cli.js.map +1 -1
  13. package/dist/cliMailBackend.d.ts.map +1 -1
  14. package/dist/cliMailBackend.js +2 -1
  15. package/dist/cliMailBackend.js.map +1 -1
  16. package/dist/context.d.ts +6 -0
  17. package/dist/context.d.ts.map +1 -1
  18. package/dist/context.js +29 -0
  19. package/dist/context.js.map +1 -1
  20. package/dist/http/admin.d.ts.map +1 -1
  21. package/dist/http/admin.js +28 -7
  22. package/dist/http/admin.js.map +1 -1
  23. package/dist/http/app.d.ts.map +1 -1
  24. package/dist/http/app.js +7 -2
  25. package/dist/http/app.js.map +1 -1
  26. package/dist/http/identity.d.ts +4 -0
  27. package/dist/http/identity.d.ts.map +1 -1
  28. package/dist/http/identity.js +110 -46
  29. package/dist/http/identity.js.map +1 -1
  30. package/dist/http/rest.d.ts.map +1 -1
  31. package/dist/http/rest.js +3 -9
  32. package/dist/http/rest.js.map +1 -1
  33. package/dist/lifecycle.d.ts +1 -1
  34. package/dist/lifecycle.d.ts.map +1 -1
  35. package/dist/lifecycle.js +2 -20
  36. package/dist/lifecycle.js.map +1 -1
  37. package/dist/mcp/buildServer.d.ts.map +1 -1
  38. package/dist/mcp/buildServer.js +33 -44
  39. package/dist/mcp/buildServer.js.map +1 -1
  40. package/dist/permissions.d.ts +2 -2
  41. package/dist/permissions.d.ts.map +1 -1
  42. package/dist/permissions.js +2 -7
  43. package/dist/permissions.js.map +1 -1
  44. package/dist/service/emailService.d.ts +1 -1
  45. package/dist/service/emailService.d.ts.map +1 -1
  46. package/dist/service/emailService.js +4 -2
  47. package/dist/service/emailService.js.map +1 -1
  48. package/dist/stdioShutdown.d.ts +27 -0
  49. package/dist/stdioShutdown.d.ts.map +1 -0
  50. package/dist/stdioShutdown.js +65 -0
  51. package/dist/stdioShutdown.js.map +1 -0
  52. package/dist/storage/apiKeys.d.ts +15 -3
  53. package/dist/storage/apiKeys.d.ts.map +1 -1
  54. package/dist/storage/apiKeys.js +34 -7
  55. package/dist/storage/apiKeys.js.map +1 -1
  56. package/dist/storage/db.d.ts +21 -2
  57. package/dist/storage/db.d.ts.map +1 -1
  58. package/dist/storage/db.js +15 -2
  59. package/dist/storage/db.js.map +1 -1
  60. package/dist/storage/members.d.ts +8 -3
  61. package/dist/storage/members.d.ts.map +1 -1
  62. package/dist/storage/members.js +36 -7
  63. package/dist/storage/members.js.map +1 -1
  64. 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,36 +411,6 @@ export async function shutdownTelemetryAndLogging() {
401
411
  await shutdownLogging();
402
412
  }
403
413
  }
404
- /** How long stdio waits for its last handles to close before exiting anyway. */
405
- const STDIO_EXIT_GRACE_MS = 2_000;
406
- /**
407
- * When the client closes stdin, flush telemetry and logs, which waits for tool calls still running, then
408
- * release what the server holds. An IMAP account keeps its connection open after a read, so without the
409
- * release the process never exits and the client's next signal may reach only a wrapper script.
410
- */
411
- export function installStdioShutdownHandler(stream, options = {}) {
412
- installTelemetryStreamEndHandler(stream, async () => {
413
- await shutdownTelemetryThenLogging();
414
- if (!options.release)
415
- return;
416
- await options.release().catch(() => { });
417
- // Nothing is left to serve, so a handle that is still open must not keep the process running.
418
- setTimeout(options.exit ?? (() => process.exit(0)), STDIO_EXIT_GRACE_MS).unref();
419
- });
420
- }
421
- /** Stops background work and closes the server, provider connections and database of a stdio session. */
422
- async function closeStdioContext(context, server) {
423
- await Promise.allSettled([
424
- Promise.resolve().then(() => context.scheduler.stop()),
425
- Promise.resolve().then(() => context.licenseController.stop()),
426
- Promise.resolve().then(() => server?.close()),
427
- ]);
428
- await context.registry.close().catch(() => { });
429
- try {
430
- context.db.$client.close();
431
- }
432
- catch { }
433
- }
434
414
  /** Build the command tree without parsing arguments or running command actions. */
435
415
  export function createCliProgram(options = {}) {
436
416
  const program = new Command();
@@ -555,6 +535,7 @@ export function createCliProgram(options = {}) {
555
535
  const [group, action] = command.split(' ');
556
536
  const alreadyStructured = ['folders', 'labels', 'emails', 'threads', 'drafts', 'scheduled', 'attachments'].includes(group ?? '') ||
557
537
  command === 'accounts list' ||
538
+ command === 'apikey list' ||
558
539
  command === 'status';
559
540
  const interactive = ['setup', 'login', 'serve', 'stdio', 'scheduled run'].includes(command) ||
560
541
  group === 'auth' ||
@@ -964,6 +945,9 @@ export function createCliProgram(options = {}) {
964
945
  const startupPhase = (phase) => recordCliOperationProperties(program, { startup_phase: phase });
965
946
  let ctx;
966
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())]));
967
951
  try {
968
952
  recordCliOperationProperties(program, {
969
953
  startup_data_dir_source: process.env.FLUXMAIL_DATA_DIR ? 'environment' : 'default',
@@ -999,17 +983,30 @@ export function createCliProgram(options = {}) {
999
983
  };
1000
984
  installTelemetrySignalHandlers();
1001
985
  const context = ctx;
1002
- installStdioShutdownHandler(process.stdin, { release: () => closeStdioContext(context, server) });
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
+ });
1003
1002
  server = serveStdio(() => buildMcpServer(scopedService, mcpOptions), {
1004
- transport: new StdioServerTransport(process.stdin, process.stdout, {
1005
- // Allow base64 attachments plus the body and JSON envelope, as HTTP does.
1006
- maxBufferSize: Math.ceil((ctx.config.maxAttachmentBytes * 4) / 3) + 2 * 1024 * 1024,
1007
- }),
1003
+ transport,
1008
1004
  onerror: (error) => logFailure(mcpOptions.logger, 'mcp.transport_failed', error, {
1009
1005
  productSurface: 'mcp',
1010
1006
  operation: 'request',
1011
1007
  }),
1012
1008
  });
1009
+ shutDownOnClose(transport, shutdown);
1013
1010
  ctx.telemetry.capture('mcp server started', {
1014
1011
  ...instanceUsageProperties(ctx.db),
1015
1012
  product_surface: 'mcp',
@@ -1038,7 +1035,7 @@ export function createCliProgram(options = {}) {
1038
1035
  catch (error) {
1039
1036
  finishCliOperation(program, 'error', apiErrorCode(error), error);
1040
1037
  if (ctx)
1041
- await closeStdioContext(ctx, server);
1038
+ await release(ctx);
1042
1039
  throw error;
1043
1040
  }
1044
1041
  });
@@ -1322,9 +1319,8 @@ export function createCliProgram(options = {}) {
1322
1319
  }
1323
1320
  const owner = findMember(ctx.db, principal.memberId);
1324
1321
  const existing = opts.reauthorize ? ctx.registry.getAccount(opts.reauthorize) : undefined;
1325
- if (existing && !canManageOwnedAccount(principal, existing)) {
1326
- throw new EmailError('permission_denied', 'Only the mailbox owner or an administrator can reauthorize it.');
1327
- }
1322
+ if (existing)
1323
+ requireConnectionChange(principal, existing);
1328
1324
  if (existing && existing.provider !== provider) {
1329
1325
  throw new EmailError('invalid_request', `Account ${existing.id} uses ${existing.provider}, not ${provider}.`);
1330
1326
  }
@@ -1366,9 +1362,8 @@ export function createCliProgram(options = {}) {
1366
1362
  const duplicate = ctx.registry
1367
1363
  .listAccounts()
1368
1364
  .find((candidate) => candidate.email.toLowerCase() === result.email.toLowerCase());
1369
- if (duplicate && !canManageOwnedAccount(principal, duplicate)) {
1370
- throw new EmailError('permission_denied', 'Only the mailbox owner or an administrator can reauthorize it.');
1371
- }
1365
+ if (duplicate)
1366
+ requireConnectionChange(principal, duplicate);
1372
1367
  if (existing && result.email.toLowerCase() !== existing.email.toLowerCase()) {
1373
1368
  throw new EmailError('invalid_request', `Microsoft authorized ${result.email}, but account ${existing.id} belongs to ${existing.email}. ` +
1374
1369
  'Try again and choose the matching Microsoft account.');
@@ -1405,9 +1400,8 @@ export function createCliProgram(options = {}) {
1405
1400
  const duplicate = ctx.registry
1406
1401
  .listAccounts()
1407
1402
  .find((candidate) => candidate.email.toLowerCase() === result.email.toLowerCase());
1408
- if (duplicate && !canManageOwnedAccount(principal, duplicate)) {
1409
- throw new EmailError('permission_denied', 'Only the mailbox owner or an administrator can reauthorize it.');
1410
- }
1403
+ if (duplicate)
1404
+ requireConnectionChange(principal, duplicate);
1411
1405
  if (existing && result.email !== existing.email) {
1412
1406
  throw new EmailError('invalid_request', `Google authorized ${result.email}, but account ${existing.id} belongs to ${existing.email}. ` +
1413
1407
  'Try again and choose the matching Google account.');
@@ -1513,10 +1507,10 @@ export function createCliProgram(options = {}) {
1513
1507
  .command('assign')
1514
1508
  .argument('<accountId>')
1515
1509
  .requiredOption('--owner <member>', 'Member id or email to own the mailbox')
1516
- .description('Change mailbox ownership')
1510
+ .description('Hand a mailbox you own to another member')
1517
1511
  .action(async (accountId, opts) => {
1518
1512
  try {
1519
- 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`, {
1520
1514
  method: 'PATCH',
1521
1515
  headers: { 'content-type': 'application/json' },
1522
1516
  body: JSON.stringify({ ownerMemberId: opts.owner }),
@@ -1533,14 +1527,14 @@ export function createCliProgram(options = {}) {
1533
1527
  .option('--owner-only', 'Only the owner can access the mailbox')
1534
1528
  .option('--shared', 'Share the mailbox with every member')
1535
1529
  .option('--share-with <member>', 'Replace selected access with this member; repeat as needed', collectOption, [])
1536
- .description('Set who can access a mailbox')
1530
+ .description('Set who can access a mailbox you own')
1537
1531
  .action(async (accountId, opts) => {
1538
1532
  try {
1539
1533
  const choices = Number(Boolean(opts.ownerOnly)) + Number(Boolean(opts.shared)) + Number(opts.shareWith.length > 0);
1540
1534
  if (choices !== 1) {
1541
1535
  throw new EmailError('invalid_request', 'Pass exactly one of --owner-only, --shared, or one or more --share-with options.');
1542
1536
  }
1543
- 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`, {
1544
1538
  method: 'PATCH',
1545
1539
  headers: { 'content-type': 'application/json' },
1546
1540
  body: JSON.stringify({ sharedWithAll: opts.shared === true, grantedMemberIds: opts.shareWith }),
@@ -1597,13 +1591,15 @@ export function createCliProgram(options = {}) {
1597
1591
  membersCmd
1598
1592
  .command('remove')
1599
1593
  .argument('<memberId>')
1600
- .description('Remove a member after reassigning or removing their mailboxes')
1601
- .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) => {
1602
1597
  try {
1603
- await instanceClient(selectedInstance()).json(`/api/v1/admin/members/${encodeURIComponent(memberId)}`, {
1604
- method: 'DELETE',
1605
- });
1606
- 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}.`);
1607
1603
  }
1608
1604
  catch (err) {
1609
1605
  failCliOperation(program, err);
@@ -1762,18 +1758,24 @@ export function createCliProgram(options = {}) {
1762
1758
  const client = instanceClient(selectedInstance());
1763
1759
  const me = await client.json('/api/v1/me');
1764
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
+ }
1765
1773
  if (!keys.length) {
1766
1774
  console.log('No API keys. Run "fluxmail apikey create --name <name>".');
1767
1775
  return;
1768
1776
  }
1769
- for (const k of keys) {
1770
- const lastUsed = k.lastUsedAt ? new Date(k.lastUsedAt).toISOString() : 'never';
1771
- const accountScope = k.accountIds === null ? 'all granted' : k.accountIds.join(',') || 'none';
1772
- console.log(`${k.id} ${k.name} member=${k.memberId} accounts=${accountScope} profile=${k.permissionProfile}` +
1773
- (k.permissionProfile === 'custom' ? ` allows=${k.capabilities.join(',')}` : '') +
1774
- (k.supplementalCapabilities.length ? ` admin=${k.supplementalCapabilities.join(',')}` : '') +
1775
- ` created=${new Date(k.createdAt).toISOString()} lastUsed=${lastUsed}`);
1776
- }
1777
+ for (const key of keys)
1778
+ console.log(apiKeyLine(key));
1777
1779
  }
1778
1780
  catch (err) {
1779
1781
  failCliOperation(program, err);
@@ -1877,8 +1879,8 @@ export function createCliProgram(options = {}) {
1877
1879
  }
1878
1880
  for (const connection of connections) {
1879
1881
  const lastUsed = connection.lastUsedAt ? new Date(connection.lastUsedAt).toISOString() : 'never';
1880
- const accountScope = connection.accountIds === null ? 'all granted' : connection.accountIds.join(',');
1881
- 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)}` +
1882
1884
  ` allows=${connection.scopes.join(',')} created=${new Date(connection.createdAt).toISOString()}` +
1883
1885
  ` expires=${new Date(connection.expiresAt).toISOString()} lastUsed=${lastUsed}`);
1884
1886
  }