fluxmail 0.24.0 → 0.26.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 (89) 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 +1 -2
  8. package/dist/accounts/registry.js.map +1 -1
  9. package/dist/auth.d.ts +2 -0
  10. package/dist/auth.d.ts.map +1 -1
  11. package/dist/auth.js +1 -0
  12. package/dist/auth.js.map +1 -1
  13. package/dist/authorization.d.ts +52 -4
  14. package/dist/authorization.d.ts.map +1 -1
  15. package/dist/authorization.js +106 -6
  16. package/dist/authorization.js.map +1 -1
  17. package/dist/cli.d.ts +0 -12
  18. package/dist/cli.d.ts.map +1 -1
  19. package/dist/cli.js +143 -101
  20. package/dist/cli.js.map +1 -1
  21. package/dist/cliInstances.d.ts +1 -0
  22. package/dist/cliInstances.d.ts.map +1 -1
  23. package/dist/cliInstances.js +3 -0
  24. package/dist/cliInstances.js.map +1 -1
  25. package/dist/cliMailBackend.d.ts.map +1 -1
  26. package/dist/cliMailBackend.js +2 -1
  27. package/dist/cliMailBackend.js.map +1 -1
  28. package/dist/context.d.ts +6 -0
  29. package/dist/context.d.ts.map +1 -1
  30. package/dist/context.js +29 -0
  31. package/dist/context.js.map +1 -1
  32. package/dist/http/admin.d.ts.map +1 -1
  33. package/dist/http/admin.js +28 -7
  34. package/dist/http/admin.js.map +1 -1
  35. package/dist/http/app.d.ts.map +1 -1
  36. package/dist/http/app.js +7 -2
  37. package/dist/http/app.js.map +1 -1
  38. package/dist/http/identity.d.ts +4 -0
  39. package/dist/http/identity.d.ts.map +1 -1
  40. package/dist/http/identity.js +110 -50
  41. package/dist/http/identity.js.map +1 -1
  42. package/dist/http/rest.d.ts.map +1 -1
  43. package/dist/http/rest.js +3 -9
  44. package/dist/http/rest.js.map +1 -1
  45. package/dist/lifecycle.d.ts +1 -1
  46. package/dist/lifecycle.d.ts.map +1 -1
  47. package/dist/lifecycle.js +2 -20
  48. package/dist/lifecycle.js.map +1 -1
  49. package/dist/mcp/attachmentContent.d.ts +1 -1
  50. package/dist/mcp/attachmentContent.js +1 -1
  51. package/dist/mcp/buildServer.d.ts.map +1 -1
  52. package/dist/mcp/buildServer.js +33 -44
  53. package/dist/mcp/buildServer.js.map +1 -1
  54. package/dist/permissions.d.ts +2 -2
  55. package/dist/permissions.d.ts.map +1 -1
  56. package/dist/permissions.js +2 -7
  57. package/dist/permissions.js.map +1 -1
  58. package/dist/service/emailService.d.ts +1 -1
  59. package/dist/service/emailService.d.ts.map +1 -1
  60. package/dist/service/emailService.js +4 -2
  61. package/dist/service/emailService.js.map +1 -1
  62. package/dist/service/publicErrors.d.ts +4 -0
  63. package/dist/service/publicErrors.d.ts.map +1 -1
  64. package/dist/service/publicErrors.js +10 -1
  65. package/dist/service/publicErrors.js.map +1 -1
  66. package/dist/stdioSetupRequired.d.ts +16 -0
  67. package/dist/stdioSetupRequired.d.ts.map +1 -0
  68. package/dist/stdioSetupRequired.js +53 -0
  69. package/dist/stdioSetupRequired.js.map +1 -0
  70. package/dist/stdioShutdown.d.ts +27 -0
  71. package/dist/stdioShutdown.d.ts.map +1 -0
  72. package/dist/stdioShutdown.js +65 -0
  73. package/dist/stdioShutdown.js.map +1 -0
  74. package/dist/storage/apiKeys.d.ts +15 -3
  75. package/dist/storage/apiKeys.d.ts.map +1 -1
  76. package/dist/storage/apiKeys.js +34 -7
  77. package/dist/storage/apiKeys.js.map +1 -1
  78. package/dist/storage/db.d.ts +21 -2
  79. package/dist/storage/db.d.ts.map +1 -1
  80. package/dist/storage/db.js +15 -2
  81. package/dist/storage/db.js.map +1 -1
  82. package/dist/storage/members.d.ts +8 -3
  83. package/dist/storage/members.d.ts.map +1 -1
  84. package/dist/storage/members.js +36 -7
  85. package/dist/storage/members.js.map +1 -1
  86. package/dist/telemetry.d.ts.map +1 -1
  87. package/dist/telemetry.js +14 -5
  88. package/dist/telemetry.js.map +1 -1
  89. package/package.json +15 -16
package/dist/cli.js CHANGED
@@ -11,7 +11,10 @@ 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';
16
+ import { newInstallationStore, setupRequiredMessage, setupRequiredService } from './stdioSetupRequired.js';
17
+ import { DEFAULT_MAX_ATTACHMENT_BYTES } from './deploymentConfig.js';
15
18
  import { RuntimeLifecycle } from './lifecycle.js';
16
19
  import { configTomlPath, createConfigurationService, deploymentToml, readLoggingSettings, resolveDataDir, resolveStoreLocation, writeDeploymentConfig, } from './config.js';
17
20
  import { migrateConfigurationFile, parseEnvContent, recognizedMigrationSettings } from './configMigration.js';
@@ -29,7 +32,7 @@ import { checkLicenseState, getEntitlements } from './licensing/entitlements.js'
29
32
  import { VERSION } from './version.js';
30
33
  import { inspectStoreCompatibility, MIN_SUPPORTED_STORE_FORMAT, openDb, openReadonlyDb, } from './storage/db.js';
31
34
  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';
35
+ import { captureOperation, getTelemetry, isTelemetryEnabled, setTelemetryEnabled, shutdownTelemetry, telemetryDisabledInAnyEnvironment, } from './telemetry.js';
33
36
  import { cloudManagementError, apiErrorCode, CliCanceledError, apiRequestId, clearSessionToken, instanceClient, loadInstanceConfig, removeInstance, resolveInstance, resolveStdioInstance, saveLocalInstance, saveRemoteInstance, saveSessionToken, setRequestDeadlineMs, useInstance, validateRemoteServerUrl, } from './cliInstances.js';
34
37
  import { DEFAULT_CLOUD_ORIGIN, loginToCloud, logoutOfCloud, openInBrowser, replaceCloudSession, } from './cliCloudAuth.js';
35
38
  import { CloudMailBackend, mailBackend } from './cliMailBackend.js';
@@ -37,11 +40,39 @@ import { cliExitCode, parseOutputFormat, printOutput } from './cliOutput.js';
37
40
  import { CliStartupError, cliStartupDiagnostics } from './cliStartupDiagnostics.js';
38
41
  import { authenticateBearer, isBootstrapComplete, normalizeAndValidatePassword, recoverAdminPassword, setupInitialAdmin, } from './auth.js';
39
42
  import { recordAdminAuditEvent } from './storage/adminAudit.js';
40
- import { canManageOwnedAccount } from './authorization.js';
43
+ import { requireConnectionChange } from './authorization.js';
41
44
  import { createCliUpdateNotifier, startMcpUpdateCheck, } from './updateNotifier.js';
42
45
  import { registerMailCommands } from './cliMail.js';
43
46
  import { accountInventoryProperties, connectionFailureKind, configuredOAuthAppKind, connectionProperties, instanceUsageProperties, } from './accounts/telemetry.js';
44
47
  import { flushLogging, escapeLogTextForConsole, getLogger, logCodedFailure, logFailure, readLocalLogs, shutdownLogging, } from './logging.js';
48
+ /** Serves one stdio MCP session and releases it when the client disconnects. */
49
+ function serveStdioSession(service, options, release) {
50
+ const shutdown = createStdioShutdown({
51
+ flushTelemetry: shutdownTelemetry,
52
+ release,
53
+ report: (failures) => {
54
+ for (const failure of failures)
55
+ logFailure(options.logger, 'stdio.shutdown_failed', failure, {
56
+ productSurface: 'mcp',
57
+ operation: 'shutdown',
58
+ });
59
+ },
60
+ flushLogs: shutdownLogging,
61
+ });
62
+ const transport = new StdioServerTransport(process.stdin, process.stdout, {
63
+ // Allow base64 attachments plus the body and JSON envelope, as HTTP does.
64
+ maxBufferSize: Math.ceil((options.maxAttachmentBytes * 4) / 3) + 2 * 1024 * 1024,
65
+ });
66
+ const handle = serveStdio(() => buildMcpServer(service, options), {
67
+ transport,
68
+ onerror: (error) => logFailure(options.logger, 'mcp.transport_failed', error, {
69
+ productSurface: 'mcp',
70
+ operation: 'request',
71
+ }),
72
+ });
73
+ shutDownOnClose(transport, shutdown);
74
+ return handle;
75
+ }
45
76
  function collectOption(value, previous) {
46
77
  return [...previous, value];
47
78
  }
@@ -85,6 +116,34 @@ export function permissionPolicyForUpdate(opts, existing) {
85
116
  }
86
117
  return permissionPolicyForProfile(existing.permissionProfile, supplemental);
87
118
  }
119
+ /**
120
+ * The mailboxes a key or OAuth connection may use. A key someone else created reaches
121
+ * only mailboxes both its owner and its creator can read.
122
+ */
123
+ function accountScopeLabel(accountIds, limitedToCreator = false) {
124
+ if (accountIds === null)
125
+ return limitedToCreator ? 'all granted to both' : 'all granted';
126
+ if (!accountIds.length)
127
+ return 'none';
128
+ const ids = accountIds.join(',');
129
+ return limitedToCreator ? `${ids} if granted to both` : ids;
130
+ }
131
+ function apiKeyLine(key) {
132
+ const lastUsed = key.lastUsedAt ? new Date(key.lastUsedAt).toISOString() : 'never';
133
+ // Servers before 0.25.0 don't return issuedByMemberId.
134
+ const delegated = Boolean(key.issuedByMemberId);
135
+ let issuer = '';
136
+ if (delegated) {
137
+ issuer = ` issuedBy=${key.issuedByEmail ?? key.issuedByMemberId}`;
138
+ if (key.issuedByStatus && key.issuedByStatus !== 'active')
139
+ issuer += ` (${key.issuedByStatus}, key disabled)`;
140
+ }
141
+ return (`${key.id} ${key.name} member=${key.memberId}${issuer}` +
142
+ ` accounts=${accountScopeLabel(key.accountIds, delegated)} profile=${key.permissionProfile}` +
143
+ (key.permissionProfile === 'custom' ? ` allows=${key.capabilities.join(',')}` : '') +
144
+ (key.supplementalCapabilities.length ? ` admin=${key.supplementalCapabilities.join(',')}` : '') +
145
+ ` created=${new Date(key.createdAt).toISOString()} lastUsed=${lastUsed}`);
146
+ }
88
147
  function connectionPort(value, option) {
89
148
  const port = Number(value);
90
149
  if (!Number.isInteger(port) || port < 1 || port > 65_535) {
@@ -260,20 +319,9 @@ async function inspectLocalRegistry(inspect) {
260
319
  return undefined;
261
320
  }
262
321
  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
- }
322
+ // Cleanup failures must not affect the command, so they are dropped.
323
+ if (context)
324
+ await closeAppContext(context);
277
325
  }
278
326
  }
279
327
  function finishCliOperation(program, outcome, errorCode, error,
@@ -383,14 +431,6 @@ export function waitForServerListening(server) {
383
431
  server.once('listening', onListening);
384
432
  });
385
433
  }
386
- async function shutdownTelemetryThenLogging() {
387
- try {
388
- await shutdownTelemetry();
389
- }
390
- finally {
391
- await shutdownLogging();
392
- }
393
- }
394
434
  export async function shutdownTelemetryAndLogging() {
395
435
  const initialLogFlush = flushLogging().catch(() => { });
396
436
  try {
@@ -401,36 +441,6 @@ export async function shutdownTelemetryAndLogging() {
401
441
  await shutdownLogging();
402
442
  }
403
443
  }
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
444
  /** Build the command tree without parsing arguments or running command actions. */
435
445
  export function createCliProgram(options = {}) {
436
446
  const program = new Command();
@@ -555,6 +565,7 @@ export function createCliProgram(options = {}) {
555
565
  const [group, action] = command.split(' ');
556
566
  const alreadyStructured = ['folders', 'labels', 'emails', 'threads', 'drafts', 'scheduled', 'attachments'].includes(group ?? '') ||
557
567
  command === 'accounts list' ||
568
+ command === 'apikey list' ||
558
569
  command === 'status';
559
570
  const interactive = ['setup', 'login', 'serve', 'stdio', 'scheduled run'].includes(command) ||
560
571
  group === 'auth' ||
@@ -962,8 +973,20 @@ export function createCliProgram(options = {}) {
962
973
  .option('--allow <capability>', 'Allow one MCP capability, or add it to --profile; repeat as needed', collectOption, [])
963
974
  .action(async (opts) => {
964
975
  const startupPhase = (phase) => recordCliOperationProperties(program, { startup_phase: phase });
976
+ const warnDefaultReadOnly = () => {
977
+ if (!opts.profile && !opts.allow.length) {
978
+ console.error('No permission profile selected, so this connection is read-only. ' +
979
+ 'Add --profile or --allow to enable drafts, organizing, or sending: https://fluxmail.ai/docs/permissions');
980
+ }
981
+ };
965
982
  let ctx;
966
983
  let server;
984
+ // The startup error path and the client's disconnect both release the session, so it closes once.
985
+ let released;
986
+ const closeServer = () => Promise.resolve().then(() => server?.close());
987
+ const release = (context) => (released ??= context
988
+ ? closeAppContext(context, [closeServer()])
989
+ : closeServer().then(() => [], (error) => [error]));
967
990
  try {
968
991
  recordCliOperationProperties(program, {
969
992
  startup_data_dir_source: process.env.FLUXMAIL_DATA_DIR ? 'environment' : 'default',
@@ -972,6 +995,34 @@ export function createCliProgram(options = {}) {
972
995
  startupPhase('permissions');
973
996
  const permissions = permissionPolicyFromOptions(opts);
974
997
  startupPhase('instance');
998
+ // A data directory without profiles or a database has never been set up. Serve the tool list so
999
+ // clients and catalogs can start, and answer every call with the setup steps. Nothing is written
1000
+ // here, so a later "fluxmail setup" still sees a new installation.
1001
+ const newStore = selectedInstance() === undefined ? newInstallationStore() : undefined;
1002
+ if (newStore) {
1003
+ startupPhase('transport');
1004
+ const operation = activeCliOperations.get(program);
1005
+ const logger = operation?.logger ?? getLogger(newStore.dataDir, 'stdio', { level: 'info', destination: 'both' });
1006
+ installTelemetrySignalHandlers();
1007
+ server = serveStdioSession(setupRequiredService(setupRequiredMessage()), {
1008
+ permissions,
1009
+ feedback: {
1010
+ enabled: newStore.deployment?.feedbackEnabled,
1011
+ cloudOrigin: newStore.deployment?.feedbackCloudOrigin,
1012
+ },
1013
+ maxAttachmentBytes: newStore.deployment?.maxAttachmentBytes ?? DEFAULT_MAX_ATTACHMENT_BYTES,
1014
+ telemetry: operation?.telemetry ?? getTelemetry(newStore.dataDir),
1015
+ transport: 'stdio',
1016
+ logger,
1017
+ ...(program.opts().updateNotifier
1018
+ ? { availableUpdate: startMcpUpdateCheck() }
1019
+ : {}),
1020
+ }, () => release());
1021
+ console.error(setupRequiredMessage(newStore.dataDir));
1022
+ warnDefaultReadOnly();
1023
+ startupPhase('setup_required');
1024
+ return;
1025
+ }
975
1026
  const selected = resolveStdioInstance(selectedInstance());
976
1027
  startupPhase('authentication');
977
1028
  if (!selected.token)
@@ -999,17 +1050,7 @@ export function createCliProgram(options = {}) {
999
1050
  };
1000
1051
  installTelemetrySignalHandlers();
1001
1052
  const context = ctx;
1002
- installStdioShutdownHandler(process.stdin, { release: () => closeStdioContext(context, server) });
1003
- 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
- }),
1008
- onerror: (error) => logFailure(mcpOptions.logger, 'mcp.transport_failed', error, {
1009
- productSurface: 'mcp',
1010
- operation: 'request',
1011
- }),
1012
- });
1053
+ server = serveStdioSession(scopedService, mcpOptions, () => release(context));
1013
1054
  ctx.telemetry.capture('mcp server started', {
1014
1055
  ...instanceUsageProperties(ctx.db),
1015
1056
  product_surface: 'mcp',
@@ -1023,10 +1064,7 @@ export function createCliProgram(options = {}) {
1023
1064
  // stdout belongs to the MCP protocol; log to stderr only.
1024
1065
  ctx.licenseController.start();
1025
1066
  console.error('Fluxmail MCP server running on stdio');
1026
- if (!opts.profile && !opts.allow.length) {
1027
- console.error('No permission profile selected, so this connection is read-only. ' +
1028
- 'Add --profile or --allow to enable drafts, organizing, or sending: https://fluxmail.ai/docs/permissions');
1029
- }
1067
+ warnDefaultReadOnly();
1030
1068
  warnLicense(ctx.db);
1031
1069
  const pending = permissions.capabilities.includes('mail.read')
1032
1070
  ? scopedService.listScheduled().filter((send) => send.status === 'pending').length
@@ -1037,8 +1075,7 @@ export function createCliProgram(options = {}) {
1037
1075
  }
1038
1076
  catch (error) {
1039
1077
  finishCliOperation(program, 'error', apiErrorCode(error), error);
1040
- if (ctx)
1041
- await closeStdioContext(ctx, server);
1078
+ await release(ctx);
1042
1079
  throw error;
1043
1080
  }
1044
1081
  });
@@ -1322,9 +1359,8 @@ export function createCliProgram(options = {}) {
1322
1359
  }
1323
1360
  const owner = findMember(ctx.db, principal.memberId);
1324
1361
  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
- }
1362
+ if (existing)
1363
+ requireConnectionChange(principal, existing);
1328
1364
  if (existing && existing.provider !== provider) {
1329
1365
  throw new EmailError('invalid_request', `Account ${existing.id} uses ${existing.provider}, not ${provider}.`);
1330
1366
  }
@@ -1366,9 +1402,8 @@ export function createCliProgram(options = {}) {
1366
1402
  const duplicate = ctx.registry
1367
1403
  .listAccounts()
1368
1404
  .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
- }
1405
+ if (duplicate)
1406
+ requireConnectionChange(principal, duplicate, { byAddress: true });
1372
1407
  if (existing && result.email.toLowerCase() !== existing.email.toLowerCase()) {
1373
1408
  throw new EmailError('invalid_request', `Microsoft authorized ${result.email}, but account ${existing.id} belongs to ${existing.email}. ` +
1374
1409
  'Try again and choose the matching Microsoft account.');
@@ -1405,9 +1440,8 @@ export function createCliProgram(options = {}) {
1405
1440
  const duplicate = ctx.registry
1406
1441
  .listAccounts()
1407
1442
  .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
- }
1443
+ if (duplicate)
1444
+ requireConnectionChange(principal, duplicate, { byAddress: true });
1411
1445
  if (existing && result.email !== existing.email) {
1412
1446
  throw new EmailError('invalid_request', `Google authorized ${result.email}, but account ${existing.id} belongs to ${existing.email}. ` +
1413
1447
  'Try again and choose the matching Google account.');
@@ -1513,10 +1547,10 @@ export function createCliProgram(options = {}) {
1513
1547
  .command('assign')
1514
1548
  .argument('<accountId>')
1515
1549
  .requiredOption('--owner <member>', 'Member id or email to own the mailbox')
1516
- .description('Change mailbox ownership')
1550
+ .description('Hand a mailbox you own to another member')
1517
1551
  .action(async (accountId, opts) => {
1518
1552
  try {
1519
- const account = await instanceClient(selectedInstance()).json(`/api/v1/admin/accounts/${encodeURIComponent(accountId)}`, {
1553
+ const account = await instanceClient(selectedInstance()).json(`/api/v1/accounts/${encodeURIComponent(accountId)}/access`, {
1520
1554
  method: 'PATCH',
1521
1555
  headers: { 'content-type': 'application/json' },
1522
1556
  body: JSON.stringify({ ownerMemberId: opts.owner }),
@@ -1533,14 +1567,14 @@ export function createCliProgram(options = {}) {
1533
1567
  .option('--owner-only', 'Only the owner can access the mailbox')
1534
1568
  .option('--shared', 'Share the mailbox with every member')
1535
1569
  .option('--share-with <member>', 'Replace selected access with this member; repeat as needed', collectOption, [])
1536
- .description('Set who can access a mailbox')
1570
+ .description('Set who can access a mailbox you own')
1537
1571
  .action(async (accountId, opts) => {
1538
1572
  try {
1539
1573
  const choices = Number(Boolean(opts.ownerOnly)) + Number(Boolean(opts.shared)) + Number(opts.shareWith.length > 0);
1540
1574
  if (choices !== 1) {
1541
1575
  throw new EmailError('invalid_request', 'Pass exactly one of --owner-only, --shared, or one or more --share-with options.');
1542
1576
  }
1543
- const account = await instanceClient(selectedInstance()).json(`/api/v1/admin/accounts/${encodeURIComponent(accountId)}`, {
1577
+ const account = await instanceClient(selectedInstance()).json(`/api/v1/accounts/${encodeURIComponent(accountId)}/access`, {
1544
1578
  method: 'PATCH',
1545
1579
  headers: { 'content-type': 'application/json' },
1546
1580
  body: JSON.stringify({ sharedWithAll: opts.shared === true, grantedMemberIds: opts.shareWith }),
@@ -1597,13 +1631,15 @@ export function createCliProgram(options = {}) {
1597
1631
  membersCmd
1598
1632
  .command('remove')
1599
1633
  .argument('<memberId>')
1600
- .description('Remove a member after reassigning or removing their mailboxes')
1601
- .action(async (memberId) => {
1634
+ .option('--reassign-to <member>', "Member id or email to receive the removed member's mailboxes")
1635
+ .description('Remove a member, handing their mailboxes to another member')
1636
+ .action(async (memberId, opts) => {
1602
1637
  try {
1603
- await instanceClient(selectedInstance()).json(`/api/v1/admin/members/${encodeURIComponent(memberId)}`, {
1604
- method: 'DELETE',
1605
- });
1606
- console.log(`Removed ${memberId}.`);
1638
+ const query = opts.reassignTo ? `?${new URLSearchParams({ reassignTo: opts.reassignTo })}` : '';
1639
+ const result = await instanceClient(selectedInstance()).json(`/api/v1/admin/members/${encodeURIComponent(memberId)}${query}`, { method: 'DELETE' });
1640
+ console.log(result.reassignedAccounts > 0
1641
+ ? `Removed ${memberId}. ${result.reassignedAccounts === 1 ? '1 mailbox now belongs' : `${result.reassignedAccounts} mailboxes now belong`} to ${opts.reassignTo}.`
1642
+ : `Removed ${memberId}.`);
1607
1643
  }
1608
1644
  catch (err) {
1609
1645
  failCliOperation(program, err);
@@ -1762,18 +1798,24 @@ export function createCliProgram(options = {}) {
1762
1798
  const client = instanceClient(selectedInstance());
1763
1799
  const me = await client.json('/api/v1/me');
1764
1800
  const keys = await client.json(me.role === 'admin' ? '/api/v1/admin/api-keys' : '/api/v1/me/api-keys');
1801
+ if (selectedFormat() !== 'table') {
1802
+ // The member route returns epoch milliseconds and the admin route ISO strings; print one shape.
1803
+ const isoTime = (value) => (value === null ? null : new Date(value).toISOString());
1804
+ printOutput({
1805
+ data: keys.map((key) => ({
1806
+ ...key,
1807
+ createdAt: isoTime(key.createdAt),
1808
+ lastUsedAt: isoTime(key.lastUsedAt),
1809
+ })),
1810
+ }, selectedFormat());
1811
+ return;
1812
+ }
1765
1813
  if (!keys.length) {
1766
1814
  console.log('No API keys. Run "fluxmail apikey create --name <name>".');
1767
1815
  return;
1768
1816
  }
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
- }
1817
+ for (const key of keys)
1818
+ console.log(apiKeyLine(key));
1777
1819
  }
1778
1820
  catch (err) {
1779
1821
  failCliOperation(program, err);
@@ -1877,8 +1919,8 @@ export function createCliProgram(options = {}) {
1877
1919
  }
1878
1920
  for (const connection of connections) {
1879
1921
  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}` +
1922
+ console.log(`${connection.id} ${connection.clientName} member=${connection.memberId}` +
1923
+ ` accounts=${accountScopeLabel(connection.accountIds)}` +
1882
1924
  ` allows=${connection.scopes.join(',')} created=${new Date(connection.createdAt).toISOString()}` +
1883
1925
  ` expires=${new Date(connection.expiresAt).toISOString()} lastUsed=${lastUsed}`);
1884
1926
  }