@cotal-ai/cli 0.173.0 → 0.174.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.
Files changed (166) hide show
  1. package/dist/command.d.ts.map +1 -1
  2. package/dist/command.js +17 -9
  3. package/dist/command.js.map +1 -1
  4. package/dist/commands/agents.d.ts.map +1 -1
  5. package/dist/commands/agents.js +22 -11
  6. package/dist/commands/agents.js.map +1 -1
  7. package/dist/commands/channel-members.d.ts.map +1 -1
  8. package/dist/commands/channel-members.js +29 -2
  9. package/dist/commands/channel-members.js.map +1 -1
  10. package/dist/commands/channels.js +5 -1
  11. package/dist/commands/channels.js.map +1 -1
  12. package/dist/commands/clean.d.ts +1 -0
  13. package/dist/commands/clean.d.ts.map +1 -1
  14. package/dist/commands/clean.js +19 -3
  15. package/dist/commands/clean.js.map +1 -1
  16. package/dist/commands/doctor.d.ts.map +1 -1
  17. package/dist/commands/doctor.js +31 -12
  18. package/dist/commands/doctor.js.map +1 -1
  19. package/dist/commands/ext.d.ts.map +1 -1
  20. package/dist/commands/ext.js +22 -5
  21. package/dist/commands/ext.js.map +1 -1
  22. package/dist/commands/help.d.ts +1 -1
  23. package/dist/commands/help.js +1 -1
  24. package/dist/commands/history.d.ts +10 -2
  25. package/dist/commands/history.d.ts.map +1 -1
  26. package/dist/commands/history.js +21 -9
  27. package/dist/commands/history.js.map +1 -1
  28. package/dist/commands/join.js +5 -1
  29. package/dist/commands/join.js.map +1 -1
  30. package/dist/commands/mint-endpoint-caller.d.ts.map +1 -1
  31. package/dist/commands/mint-endpoint-caller.js +13 -2
  32. package/dist/commands/mint-endpoint-caller.js.map +1 -1
  33. package/dist/commands/mint.d.ts.map +1 -1
  34. package/dist/commands/mint.js +10 -2
  35. package/dist/commands/mint.js.map +1 -1
  36. package/dist/commands/persona.js +3 -3
  37. package/dist/commands/persona.js.map +1 -1
  38. package/dist/commands/personas.js +1 -1
  39. package/dist/commands/personas.js.map +1 -1
  40. package/dist/commands/send.d.ts.map +1 -1
  41. package/dist/commands/send.js +10 -6
  42. package/dist/commands/send.js.map +1 -1
  43. package/dist/commands/setup.d.ts.map +1 -1
  44. package/dist/commands/setup.js +17 -1
  45. package/dist/commands/setup.js.map +1 -1
  46. package/dist/commands/space.js +1 -1
  47. package/dist/commands/space.js.map +1 -1
  48. package/dist/commands/spawn-managed-launch.d.ts.map +1 -1
  49. package/dist/commands/spawn-managed-launch.js +6 -4
  50. package/dist/commands/spawn-managed-launch.js.map +1 -1
  51. package/dist/commands/spawn-preview.d.ts.map +1 -1
  52. package/dist/commands/spawn-preview.js +3 -0
  53. package/dist/commands/spawn-preview.js.map +1 -1
  54. package/dist/commands/stack-up.d.ts.map +1 -1
  55. package/dist/commands/stack-up.js +13 -6
  56. package/dist/commands/stack-up.js.map +1 -1
  57. package/dist/commands/status-model.d.ts +402 -0
  58. package/dist/commands/status-model.d.ts.map +1 -0
  59. package/dist/commands/status-model.js +64 -0
  60. package/dist/commands/status-model.js.map +1 -0
  61. package/dist/commands/status.d.ts +4 -368
  62. package/dist/commands/status.d.ts.map +1 -1
  63. package/dist/commands/status.js +20 -77
  64. package/dist/commands/status.js.map +1 -1
  65. package/dist/commands/team-deploy-apply.d.ts.map +1 -1
  66. package/dist/commands/team-deploy-apply.js +0 -2
  67. package/dist/commands/team-deploy-apply.js.map +1 -1
  68. package/dist/commands/up-pending.d.ts +24 -0
  69. package/dist/commands/up-pending.d.ts.map +1 -0
  70. package/dist/commands/up-pending.js +5 -0
  71. package/dist/commands/up-pending.js.map +1 -0
  72. package/dist/commands/up-transport.d.ts +121 -0
  73. package/dist/commands/up-transport.d.ts.map +1 -0
  74. package/dist/commands/up-transport.js +348 -0
  75. package/dist/commands/up-transport.js.map +1 -0
  76. package/dist/commands/up.d.ts +1 -1
  77. package/dist/commands/up.d.ts.map +1 -1
  78. package/dist/commands/up.js +50 -391
  79. package/dist/commands/up.js.map +1 -1
  80. package/dist/commands/update-continuity.d.ts +47 -0
  81. package/dist/commands/update-continuity.d.ts.map +1 -0
  82. package/dist/commands/update-continuity.js +430 -0
  83. package/dist/commands/update-continuity.js.map +1 -0
  84. package/dist/commands/update-process.d.ts +26 -0
  85. package/dist/commands/update-process.d.ts.map +1 -0
  86. package/dist/commands/update-process.js +283 -0
  87. package/dist/commands/update-process.js.map +1 -0
  88. package/dist/commands/update-release.d.ts +32 -0
  89. package/dist/commands/update-release.d.ts.map +1 -0
  90. package/dist/commands/update-release.js +232 -0
  91. package/dist/commands/update-release.js.map +1 -0
  92. package/dist/commands/update.d.ts +6 -54
  93. package/dist/commands/update.d.ts.map +1 -1
  94. package/dist/commands/update.js +25 -949
  95. package/dist/commands/update.js.map +1 -1
  96. package/dist/commands/use.d.ts.map +1 -1
  97. package/dist/commands/use.js +4 -7
  98. package/dist/commands/use.js.map +1 -1
  99. package/dist/console/commands.js +2 -2
  100. package/dist/console/commands.js.map +1 -1
  101. package/dist/help.d.ts +1 -1
  102. package/dist/help.d.ts.map +1 -1
  103. package/dist/help.js +3 -1
  104. package/dist/help.js.map +1 -1
  105. package/dist/index.d.ts.map +1 -1
  106. package/dist/index.js +4 -3
  107. package/dist/index.js.map +1 -1
  108. package/dist/lib/choose-target.d.ts +2 -0
  109. package/dist/lib/choose-target.d.ts.map +1 -1
  110. package/dist/lib/choose-target.js +16 -1
  111. package/dist/lib/choose-target.js.map +1 -1
  112. package/dist/lib/credential-authority.d.ts +1 -1
  113. package/dist/lib/credential-authority.d.ts.map +1 -1
  114. package/dist/lib/credential-authority.js +8 -3
  115. package/dist/lib/credential-authority.js.map +1 -1
  116. package/dist/lib/foreground-hold.d.ts +2 -0
  117. package/dist/lib/foreground-hold.d.ts.map +1 -1
  118. package/dist/lib/foreground-hold.js +47 -1
  119. package/dist/lib/foreground-hold.js.map +1 -1
  120. package/dist/lib/mint-renewal.d.ts +5 -0
  121. package/dist/lib/mint-renewal.d.ts.map +1 -0
  122. package/dist/lib/mint-renewal.js +60 -0
  123. package/dist/lib/mint-renewal.js.map +1 -0
  124. package/dist/lib/persona-files.d.ts +1 -1
  125. package/dist/lib/persona-files.d.ts.map +1 -1
  126. package/dist/lib/persona-files.js +5 -5
  127. package/dist/lib/persona-files.js.map +1 -1
  128. package/dist/lib/restore-streams.d.ts +18 -0
  129. package/dist/lib/restore-streams.d.ts.map +1 -0
  130. package/dist/lib/restore-streams.js +275 -0
  131. package/dist/lib/restore-streams.js.map +1 -0
  132. package/dist/lib/restore.d.ts +2 -0
  133. package/dist/lib/restore.d.ts.map +1 -1
  134. package/dist/lib/restore.js +5 -273
  135. package/dist/lib/restore.js.map +1 -1
  136. package/dist/lib/self-exec.d.ts +5 -2
  137. package/dist/lib/self-exec.d.ts.map +1 -1
  138. package/dist/lib/self-exec.js +6 -3
  139. package/dist/lib/self-exec.js.map +1 -1
  140. package/dist/lib/stack-journal.d.ts +3 -1
  141. package/dist/lib/stack-journal.d.ts.map +1 -1
  142. package/dist/lib/stack-journal.js +10 -0
  143. package/dist/lib/stack-journal.js.map +1 -1
  144. package/dist/lib/update-connector-config.d.ts +2 -0
  145. package/dist/lib/update-connector-config.d.ts.map +1 -1
  146. package/dist/lib/update-connector-config.js +15 -1
  147. package/dist/lib/update-connector-config.js.map +1 -1
  148. package/dist/lib/update-managers.d.ts.map +1 -1
  149. package/dist/lib/update-managers.js +11 -3
  150. package/dist/lib/update-managers.js.map +1 -1
  151. package/dist/lib/update-recovery-state.d.ts +7 -0
  152. package/dist/lib/update-recovery-state.d.ts.map +1 -1
  153. package/dist/lib/update-recovery-state.js +55 -2
  154. package/dist/lib/update-recovery-state.js.map +1 -1
  155. package/dist/lib/update-snapshot.d.ts.map +1 -1
  156. package/dist/lib/update-snapshot.js +14 -7
  157. package/dist/lib/update-snapshot.js.map +1 -1
  158. package/dist/seed/lock.d.ts +1 -1
  159. package/dist/seed/lock.d.ts.map +1 -1
  160. package/dist/seed/lock.js +3 -2
  161. package/dist/seed/lock.js.map +1 -1
  162. package/dist/telemetry.d.ts +6 -0
  163. package/dist/telemetry.d.ts.map +1 -1
  164. package/dist/telemetry.js +11 -5
  165. package/dist/telemetry.js.map +1 -1
  166. package/package.json +5 -5
@@ -8,10 +8,10 @@ import { createConnection, createServer, isIP } from "node:net";
8
8
  import { homedir, hostname } from "node:os";
9
9
  import { accessSync, constants, mkdirSync, readFileSync, existsSync, statSync, closeSync, lstatSync, realpathSync, readdirSync, rmdirSync, } from "node:fs";
10
10
  import { basename, dirname, isAbsolute, join, resolve } from "node:path";
11
- import { isReachable, dialerFor, DEFAULT_SERVER, DEFAULT_SPACE, SERVICE_AUTHORITY_MAX_BYTES, SERVICE_CALLER_PAYLOAD_FLOOR, CONTRACT_ARTIFACT_MAX_BYTES, MANAGER_START_PAYLOAD_FLOOR, createSpaceAuth, serverConfig, openServerConfig, validateTlsMaterial, credsProblem, mintCreds, mintLifecycleUid, DEV_OWNER, mintConnectionEvictorCreds, mintMembershipObserverCreds, newIdentity, setupSpaceStreams, removeIssuedStoresBeforeRetention, IssuedStoreBeforeRetentionError, IssuedStoreRecreateRefusal, reconcileSpaceMemoryBuckets, recreateMembershipStore, membershipStoreDefinition, LEGACY_MEMBERSHIP_MAX_BYTES, MEMBERSHIP_MAX_VALUE_SIZE, ttlBuckets, standaloneConnectOpts, requireBrokerFloor, parseServerVersion, presenceBucket, spaceDeletionStreams, isJetStreamMissing, seedChannelRegistry, ensureDefaultDeliveryClass, UndecodableRegistryEntry, LEASE_TTL_MS, EpEnvelopeError, mkSecretDir, writeSecretFile, } from "@cotal-ai/core";
11
+ import { isReachable, dialerFor, DEFAULT_SERVER, DEFAULT_SPACE, SERVICE_AUTHORITY_MAX_BYTES, SERVICE_CALLER_PAYLOAD_FLOOR, CONTRACT_ARTIFACT_MAX_BYTES, MANAGER_START_PAYLOAD_FLOOR, createSpaceAuth, serverConfig, openServerConfig, credsProblem, mintCreds, mintLifecycleUid, DEV_OWNER, mintConnectionEvictorCreds, mintMembershipObserverCreds, newIdentity, setupSpaceStreams, removeIssuedStoresBeforeRetention, IssuedStoreBeforeRetentionError, IssuedStoreRecreateRefusal, reconcileSpaceMemoryBuckets, recreateMembershipStore, membershipStoreDefinition, LEGACY_MEMBERSHIP_MAX_BYTES, MEMBERSHIP_MAX_VALUE_SIZE, ttlBuckets, standaloneConnectOpts, requireBrokerFloor, parseServerVersion, presenceBucket, spaceDeletionStreams, isJetStreamMissing, seedChannelRegistry, ensureDefaultDeliveryClass, UndecodableRegistryEntry, LEASE_TTL_MS, EpEnvelopeError, mkSecretDir, writeSecretFile, } from "@cotal-ai/core";
12
12
  import { JetStreamApiCodes, jetstreamManager, StorageType } from "@nats-io/jetstream";
13
13
  import { Kvm } from "@nats-io/kv";
14
- import { assertManagerName, processStopped, readManagerName, readManagerSeatCap, recordManagerName, parseSeatCapFlag, seatCapText, CommandFailure, codeSpan, commandFailureReport, failureEnvelope, writeEnvelope, isCommandFailure, protectedLocalDirectory, jsonFlag, plainFlag, renderReport, assertSingleSpaceBroker, assertUserAuthInfo, authDir, brokerAddressForDisplay, brokerPolicyPath, getSoleSpaceAuth, soleSpaceOf, getSpaceAuth, hasUserAuthState, listSpaceAccounts, preloadSpaceAccounts, putSpaceAuth, brokerAddressKey, canonicalRoot, rootPathProblem, rootControlProblem, clearCurrent, findMesh, findPreparedSpace, homeCotalDir, legacyStackOtherHome, stackHomeRemedy, getCurrent, loadMeshes, preparedSpaceAt, removePreparedSpace, localMeshesForRoot, keepsRegistration, oneLine, presentationOf, writeResult, connectionEvictorCredsKey, membershipConfigPath, membershipObserverCredsKey, membershipRwCredsKey, MEMBERSHIP_CONFIG_KIND, MEMBERSHIP_RW_CREDS_KIND, WEB_CREDS_KIND, webCredsKey, parsePositiveIntegerFlag, recordMesh, retainedLegacyBroker, meshesForRoot, removeMesh, rotateSystemCreds, setAdoptedCurrent, staleSystemCreds, SYSTEM_CREDS_FILES, userAuthStateDir, userAuthSpacesOnDisk, workspaceSecretStore, acquireMaintenanceLock, assertStoreIdentity, assessMaintenanceClaim, assessRestoreClaim, beginOrdinaryResume, bindOrdinaryResumeListener, consumeRetiredMaintenance, markOrdinaryResumeActive, markOrdinaryResumeDegraded, replaceDeadOrdinaryResumeListener, localProcessOwnerStatus, readMaintenanceJournal, rootNamesNoSpace, readMaintenanceResumeDocument, readStoreIdentity, recordOrdinaryResumeManagerCommit, releaseMaintenanceLock, retireOrdinaryResume, settleTokenHandoff, sweepTokenHandoff, writeTokenHandoff, sameStoreIdentity, cutController, readBrokerPolicy, writeBrokerPolicy, brokerAccountResolver, removePidPair, writePidPair, verifyIdentityPin, processesNaming, isLoopbackHost, connectUserControlOrThrow, userViewAuth, recordOperationSpace, recordsElsewhereError, recordOperationWarning, retainSystemSigningSeed, restoreLeftOut, SPACE_NAME_MAX, spaceNameTooLong, NATS_PIDFILE, MANAGER_PIDFILE, DELIVERY_PIDFILE, AUTH_PIDFILE, localProcessPath, UNTRUSTED_CERTIFICATE, exitCode, canonicalLocalProcessPath, DELIVERY_LOGFILE, terminalWidth, } from "@cotal-ai/workspace";
14
+ import { assertManagerName, processStopped, readManagerName, readManagerSeatCap, recordManagerName, parseSeatCapFlag, seatCapText, CommandFailure, codeSpan, commandFailureReport, failureEnvelope, writeEnvelope, isCommandFailure, protectedLocalDirectory, jsonFlag, plainFlag, renderReport, assertSingleSpaceBroker, assertUserAuthInfo, authDir, brokerAddressForDisplay, getSoleSpaceAuth, soleSpaceOf, getSpaceAuth, hasUserAuthState, listSpaceAccounts, preloadSpaceAccounts, putSpaceAuth, brokerAddressKey, canonicalRoot, rootPathProblem, rootControlProblem, clearCurrent, findMesh, findPreparedSpace, homeCotalDir, legacyStackOtherHome, stackHomeRemedy, getCurrent, loadMeshes, preparedSpaceAt, removePreparedSpace, localMeshesForRoot, keepsRegistration, oneLine, presentationOf, writeResult, connectionEvictorCredsKey, membershipConfigPath, membershipObserverCredsKey, membershipRwCredsKey, MEMBERSHIP_CONFIG_KIND, MEMBERSHIP_RW_CREDS_KIND, WEB_CREDS_KIND, webCredsKey, parsePositiveIntegerFlag, recordMesh, retainedLegacyBroker, meshesForRoot, removeMesh, rotateSystemCreds, setAdoptedCurrent, staleSystemCreds, SYSTEM_CREDS_FILES, userAuthStateDir, userAuthSpacesOnDisk, workspaceSecretStore, acquireMaintenanceLock, assertStoreIdentity, assessMaintenanceClaim, assessRestoreClaim, beginOrdinaryResume, bindOrdinaryResumeListener, consumeRetiredMaintenance, markOrdinaryResumeActive, markOrdinaryResumeDegraded, replaceDeadOrdinaryResumeListener, localProcessOwnerStatus, readMaintenanceJournal, rootNamesNoSpace, readMaintenanceResumeDocument, readStoreIdentity, recordOrdinaryResumeManagerCommit, releaseMaintenanceLock, retireOrdinaryResume, settleTokenHandoff, sweepTokenHandoff, writeTokenHandoff, sameStoreIdentity, cutController, readBrokerPolicy, brokerAccountResolver, removePidPair, writePidPair, verifyIdentityPin, processesNaming, isLoopbackHost, connectUserControlOrThrow, userViewAuth, recordOperationSpace, recordOperationWarning, retainSystemSigningSeed, restoreLeftOut, SPACE_NAME_MAX, spaceNameTooLong, NATS_PIDFILE, MANAGER_PIDFILE, DELIVERY_PIDFILE, AUTH_PIDFILE, localProcessPath, UNTRUSTED_CERTIFICATE, exitCode, canonicalLocalProcessPath, DELIVERY_LOGFILE, terminalWidth, } from "@cotal-ai/workspace";
15
15
  import { FlagValueRefusal } from "../lib/flag-value-refusal.js";
16
16
  import { ensureAuthService, resolveAuthProvider, stopAuthService } from "../lib/auth-proc.js";
17
17
  import { resolveSpace } from "../lib/status.js";
@@ -19,7 +19,7 @@ import { c, hang, stderrLine } from "../ui.js";
19
19
  import { admitAndRestoreSeatCheckpoints } from "../lib/seat-resume.js";
20
20
  import { NATS_DEFAULT_MAX_PAYLOAD, natsServerLabel, resolveNatsServer, unreadVersion } from "../lib/nats-bin.js";
21
21
  import { cotalPath, cotalRoot, homeHoldsStack, linkedCotalRefusal } from "../lib/paths.js";
22
- import { channelsReads, readChannelsFile, readDefaultChannelsFile } from "../lib/channel-seed.js";
22
+ import { channelsReads, readChannelsFile } from "../lib/channel-seed.js";
23
23
  import { controllerManifestRemedy, detachedNext, renderDetachedSummary } from "../lib/up-report.js";
24
24
  import { seedDefaultPersona } from "../lib/default-persona.js";
25
25
  import { seedBeforeLaunch, seedMoveNote } from "../seed/launch.js";
@@ -46,8 +46,8 @@ import { checkLocalSpace } from "./space-registration.js";
46
46
  import { checkNewUpSpace, preparedUpRoot } from "./up-target.js";
47
47
  import { cleanedManifestStart, interruptedStartBroker, namedOpenConfig, retainedOpenSpace } from "../lib/legacy-start.js";
48
48
  import { bindReaches, canonicalServer, controllerStackApplies, recheckExistingStore, requestedStackMode, refuseForegroundStackHolder, requestsTls, stackUp, stackUpForegroundNotice, stackUpInterrupted, keptOnUp, selectedOnUp, unparsableDaemonCredsNotice, } from "./stack-up.js";
49
- import { handOverStartupNotice, noticeOnInterrupt, releaseStartupNotice } from "../lib/interrupt-notice.js";
50
- import { claimForegroundHold, foregroundHolder, releaseForegroundHold } from "../lib/foreground-hold.js";
49
+ import { exitInterrupted, handOverStartupNotice, noticeOnInterrupt, releaseStartupNotice } from "../lib/interrupt-notice.js";
50
+ import { claimForegroundHold, foregroundHolder, foregroundStackEnd, releaseForegroundHold } from "../lib/foreground-hold.js";
51
51
  import { settleInterruptedLaunches } from "../lib/service-process.js";
52
52
  import { assertUserStackTransport, preflightUserStack } from "./stack-user-auth.js";
53
53
  import { stackDown } from "./stack-down.js";
@@ -61,18 +61,19 @@ import { serviceSupervisorStore } from "../lib/service-supervision.js";
61
61
  import { serviceInstallIntents } from "../lib/service-install-intent.js";
62
62
  import { serviceUninstallIntents } from "../lib/service-uninstall-intent.js";
63
63
  import { serviceUnitActionStore } from "../lib/service-unit-action.js";
64
- import { assertStoreDirArgument, configuredStoreDir, lastServedStore, lastServedStores, missingStoreWarning, servedStore, sharedStoreAtStart, sharedStoreWarning, startupStoreProblem, warnForeignStoreEntries } from "../lib/store-dir.js";
64
+ import { assertStoreDirArgument, configuredStoreDir, startupStoreProblem, warnForeignStoreEntries } from "../lib/store-dir.js";
65
65
  import { extensionNames, preflightRuntime } from "../ext-loader.js";
66
66
  import { completingFlagValue } from "../lib/completion.js";
67
67
  import { metadataPositionals } from "../lib/command-path.js";
68
- import { bindPreparedRestoreListener, isManagerCommitResult, isManagerFinalizeResult, isManagerCommittedRestore, markPreparedRestoreActive, markPreparedRestoreDegraded, heldRestoreAttempt, heldClaim, movedFolderRefusal, prepareRestore, restoreArtifactPath, restoreLaunch, preservedSourceState, recordPreparedRestoreManagerCommit, rehydratePreparedRestore, journaledMaxFileStore, journaledRestoredStreams, leftOutNotes, rearmUnboundRestore, replacePreparedDeadRestoreListener, restoreComposition, restoreNextStep, restoreOnlyCopy, } from "../lib/restore.js";
68
+ import { bindPreparedRestoreListener, isManagerCommitResult, isManagerFinalizeResult, isManagerCommittedRestore, markPreparedRestoreActive, markPreparedRestoreDegraded, heldRestoreAttempt, heldClaim, movedFolderRefusal, prepareRestore, restoreArtifactPath, restoreLaunch, preservedSourceState, recordPreparedRestoreManagerCommit, rehydratePreparedRestore, journaledMaxFileStore, journaledRestoredStreams, leftOutNotes, rearmUnboundRestore, replacePreparedDeadRestoreListener, restoreComposition, restoreInterruptNotice, restoreNextStep, restoreOnlyCopy, } from "../lib/restore.js";
69
69
  import { attemptProcessesGone } from "../lib/isolated-broker.js";
70
70
  import { assertEndpointUnreachable } from "../lib/endpoint-cut.js";
71
71
  import { addressHolder, brokerListenAddress, listenerBindError } from "../lib/broker-service.js";
72
72
  import { freePort, freshStackServer, retryStackAddress, serverWithFreePort } from "../lib/up-broker-address.js";
73
73
  import { askManager } from "@cotal-ai/workspace/control";
74
74
  import { cliControl } from "../lib/control.js";
75
- const pendingRestores = new Map();
75
+ import { pendingRestores, pendingOrdinaryResumes } from "./up-pending.js";
76
+ import { parseMaxFileStore, parseAuthTimeout, parseMaxPayload, parseAccountResolver, authTimeoutArgs, loadChannelsFile, refuseRunningElsewhere, refuseRecordsElsewhere, resolveTransport, assertTlsIntentServed, assertTlsAddressServed, commitTransportPolicy, tlsAddress, announceTransport, liveListenerRequiresTls, assertServesDialHost, adoptedTlsRequired, refuseUnnamedLastStore, reopenLastStore, refuseMissingNamedStore, checkStartStore, } from "./up-transport.js";
76
77
  const restoreSinks = new Map();
77
78
  /** Run the guarded `up --restore` startup and return its result instead of printing it. The
78
79
  * restore inputs and fences are exactly `up --restore`'s; this adds no route, flag or authority. */
@@ -85,7 +86,6 @@ export async function startRestore(values) {
85
86
  }
86
87
  return returned;
87
88
  }
88
- const pendingOrdinaryResumes = new Map();
89
89
  /** `cotal up` flags — colocated with the command (like `spawnFlags`) so its completion can read them. */
90
90
  export const upFlags = [
91
91
  { name: "server", type: "string", value: "<url>", description: "listen URL; a stack's first up records it and later ups keep it" },
@@ -100,7 +100,7 @@ export const upFlags = [
100
100
  { name: "auth-timeout", type: "string", value: "<seconds>", description: "user-auth only: how long the broker waits for the auth callout, 1 to 60 seconds (default: nats-server's 2); the auth service answers inside it. Fixed at broker start and recorded for the next `up`" },
101
101
  { name: "max-payload", type: "string", value: "<bytes>", description: `broker-wide message size limit in bytes (default: nats-server's ${NATS_DEFAULT_MAX_PAYLOAD}). A manager-backed start needs at least 263168, and service endpoint caller grants need at least 2098176. Fixed at broker start and recorded for the next \`up\`` },
102
102
  { name: "account-resolver", type: "string", value: "<memory|full>", description: "how the broker resolves space accounts: memory (default) knows only the accounts its configuration lists, so adding one means a reload; full also keeps pushed account claims in .cotal/account-jwts, so a host can add and retire accounts on the running broker without a reload. Fixed at broker start and recorded for the next `up`" },
103
- { name: "channels", type: "string", value: "<path>", description: "channel-registry seed file (JSON; default .cotal/channels.json)" },
103
+ { name: "channels", type: "string", value: "<path>", description: "channel-registry seed file (JSON; default .cotal/channels.json); not used with -f" },
104
104
  { name: "tls-cert", type: "string", value: "<file>", description: "serve the broker over TLS with this certificate (requires --tls-key)" },
105
105
  { name: "tls-key", type: "string", value: "<file>", description: "the private key for --tls-cert" },
106
106
  { name: "restore", type: "string", value: "<dir>", description: "restore an offline backup before exposing the normal listener" },
@@ -602,7 +602,7 @@ function hangupForegroundStack(root) {
602
602
  * exits 129, naming `cotal down`. `start`, when given, is the startup this terminal already holds: a
603
603
  * signal during it lets the start settle, then a stop signal runs that stop and a hangup leaves what
604
604
  * the start left. A failed start still runs the stop, and its failure is thrown once the stop returns.
605
- * The hold's end sets the exit code: 0 when another command completed the stop or preserve, 129 after
605
+ * The hold exits 0 after a completed external stop or preserve, 5 after a broker crash, 129 after
606
606
  * a hangup, 130 or 143 after a stop signal, whatever the start receipt set. */
607
607
  export async function holdForegroundStack(root, start, releaseRestoreNotice) {
608
608
  claimForegroundHold(root);
@@ -653,29 +653,26 @@ async function holdStack(root, start, releaseRestoreNotice) {
653
653
  return;
654
654
  }
655
655
  return new Promise((resolveHold) => {
656
- // The hold ends on its own when another command completes a whole-stack stop or preserve of this
657
- // root: a later operation recorded as completed is that evidence. Any other later operation,
658
- // such as a refresh, keeps the hold. The poll also keeps Node alive, which a pending promise and
659
- // signal listeners alone do not.
660
- const recorded = () => { try {
661
- return readStackJournal(root)?.journal.operation;
656
+ // The poll keeps Node alive and observes the recorded broker and external stack operations.
657
+ const held = (() => { try {
658
+ return readStackJournal(root)?.journal.operation.id;
662
659
  }
663
660
  catch {
664
661
  return undefined;
665
- } };
666
- const held = recorded()?.id;
662
+ } })();
667
663
  let stopping = false;
668
664
  const lifetime = setInterval(() => {
669
- const operation = recorded();
670
- if (stopping || !operation || operation.id === held || operation.phase !== "completed" || operation.kind !== "down" && operation.kind !== "preserve")
665
+ if (stopping)
666
+ return;
667
+ const code = foregroundStackEnd(root, held);
668
+ if (code === undefined)
671
669
  return;
672
670
  stopping = true;
673
671
  process.off("SIGINT", interrupt);
674
672
  process.off("SIGTERM", terminate);
675
673
  process.off("SIGHUP", hangup);
676
674
  clearInterval(lifetime);
677
- process.stderr.write(`${renderReport({ sections: [{ title: "Foreground stack released", blocks: [{ kind: "lines", lines: [`Another command completed a ${operation.kind === "down" ? "stop" : "preserve"} of this stack (operation ${operation.id}). This terminal no longer holds it.`] }] }] }, "rich", process.stderr)}\n`);
678
- process.exitCode = 0;
675
+ process.exitCode = code;
679
676
  resolveHold();
680
677
  }, 1000);
681
678
  const stop = (signal) => {
@@ -751,9 +748,10 @@ export async function up(args, inheritedLock, freshTeamBoot = false, restoreSink
751
748
  const root = args.values.root === undefined ? undefined : preparedUpRoot(String(args.values.root));
752
749
  const fresh = args.values.root === undefined ? freshFolderRoot(args.values) : undefined;
753
750
  checkNewUpSpace(args.values.space, root ?? fresh);
754
- // The broker reads an explicit channels file only once it is being prepared, so a file it would
755
- // refuse is named here, before the stack journal or anything else is written.
756
- if (typeof args.values.channels === "string")
751
+ // Validate a seed before writing stack records only on the route that uses it.
752
+ if (typeof args.values.channels === "string" && args.values.file)
753
+ recordOperationWarning({ code: "MANIFEST_CHANNEL_SEED_IGNORED", target: null, message: "--channels is not used with -f. Set channels and defaults in the manifest." }, { echo: args.values.json !== true });
754
+ else if (typeof args.values.channels === "string")
757
755
  readChannelsFile(resolve(args.values.channels));
758
756
  const folderNamed = folderNamedSpace(args.values);
759
757
  if (folderNamed)
@@ -1486,7 +1484,7 @@ async function runUp(args, invokedFrom, inheritedLock, onAdopt, freshTeamBoot =
1486
1484
  return `${failure.message} ${failure.remedy}`;
1487
1485
  });
1488
1486
  try {
1489
- const stackLock = acquireStackOperationLock(meshRoot);
1487
+ const stackLock = acquireStackOperationLock(meshRoot, values.foreground ? "foreground up" : undefined);
1490
1488
  const native = controllerStackNative();
1491
1489
  // A foreground terminal holds the start as well, so a signal during it stops what it started.
1492
1490
  const start = async () => {
@@ -1524,34 +1522,33 @@ async function runUp(args, invokedFrom, inheritedLock, onAdopt, freshTeamBoot =
1524
1522
  // that name over, as `down` there does not stop it.
1525
1523
  if (!values.file && values.space === undefined)
1526
1524
  await refuseRecordsElsewhere(meshRoot);
1527
- if (values.json || values.plain) {
1528
- // `up -f` always takes the retained launcher, so the controller route is no remedy there. Its
1529
- // manifest is checked first, so a manifest that does not validate gets its own refusal.
1530
- if (values.file) {
1531
- const path = resolve(values.file);
1525
+ if (!values.file && (values.json || values.plain))
1526
+ throw retainedStartupPresentationRefusal(meshRoot);
1527
+ // `up -f cotal.yaml` is a distinct path: bring up a FRESH mesh described by a manifest (broker +
1528
+ // channels + booted agents). It owns the whole space; the additive team deploy route is separate.
1529
+ // CLI flags override the manifest (flag > manifest > default) so the same file runs at a different
1530
+ // port / runtime / auth without editing it. Its space is its target: `--space` may only repeat it.
1531
+ if (values.file) {
1532
+ const path = resolve(values.file);
1533
+ // Structured and plain manifest refusals report file errors before checking startup support.
1534
+ if (values.json || values.plain) {
1532
1535
  try {
1533
1536
  loadManifest(path);
1534
1537
  }
1535
1538
  catch (e) {
1536
1539
  throw manifestFileRefusal(e, path);
1537
1540
  }
1538
- throw new CommandFailure("refused", "UNSUPPORTED", "up -f starts its manifest on the retained native launcher, which has no structured or plain receipt; nothing was started", { target: { root: meshRoot, path }, remedy: `omit ${values.json ? "--json" : "--plain"}` });
1539
1541
  }
1540
- throw retainedStartupPresentationRefusal(meshRoot);
1541
- }
1542
- // `up -f cotal.yaml` is a distinct path: bring up a FRESH mesh described by a manifest (broker +
1543
- // channels + booted agents). It owns the whole space; the additive team deploy route is separate.
1544
- // CLI flags override the manifest (flag > manifest > default) so the same file runs at a different
1545
- // port / runtime / auth without editing it. Its space is its target: `--space` may only repeat it.
1546
- if (values.file) {
1547
1542
  // A manifest start takes the legacy launcher, which never runs beside a controller stack, running
1548
1543
  // or stopped, so a dry run refuses as the start would.
1549
1544
  const controller = freshTeamBoot ? undefined : readStackJournal(meshRoot);
1550
1545
  if (controller)
1551
1546
  throw new CommandFailure("refused", "CONFLICT", `this root holds the controller stack of space ${controller.journal.space}, and up -f does not start a manifest beside it; nothing was started`, {
1552
1547
  target: { root: meshRoot, space: controller.journal.space },
1553
- remedy: controllerManifestRemedy(meshRoot, controller.journal.space, resolve(values.file)),
1548
+ remedy: controllerManifestRemedy(meshRoot, controller.journal.space, path),
1554
1549
  });
1550
+ if (values.json || values.plain)
1551
+ throw new CommandFailure("refused", "UNSUPPORTED", "up -f starts its manifest on the retained native launcher, which has no structured or plain receipt; nothing was started", { target: { root: meshRoot, path }, remedy: `omit ${values.json ? "--json" : "--plain"}` });
1555
1552
  if (values["dry-run"]) {
1556
1553
  await upManifest(values.file, {
1557
1554
  transport,
@@ -2297,11 +2294,8 @@ async function runUp(args, invokedFrom, inheritedLock, onAdopt, freshTeamBoot =
2297
2294
  if (!resumeAttempt)
2298
2295
  process.exit(1);
2299
2296
  });
2300
- // The control plane is coupled to the broker: stop the detached manager AND the delivery daemon
2301
- // (AND the space's user-auth service) when this `up` stops (Ctrl-C), so none outlives the broker
2302
- // it serves — a surviving manager would reconnect-loop invisibly against the dead (or the NEXT)
2303
- // broker (the documented orphan-supervisor failure mode). All kill by pidfile, symmetric; the
2304
- // auth service's pid is space-scoped so no other space's daemon can ever be hit.
2297
+ // Stop the detached manager, delivery daemon and space's user-auth service before their broker,
2298
+ // so none outlives it. The auth service's process record is space-scoped.
2305
2299
  // The manager goes first, in `cotal down`'s order, through the stop `cotal down` runs (#1307): it
2306
2300
  // holds the stop reservation, asserts the exact manager can spare its seats before any signal,
2307
2301
  // reports the seats left behind, and escalates a wedged manager to SIGKILL. When that stop throws
@@ -2314,10 +2308,9 @@ async function runUp(args, invokedFrom, inheritedLock, onAdopt, freshTeamBoot =
2314
2308
  // the failure is logged, never swallowed silently. Teardown is AWAITED before the broker is
2315
2309
  // signalled, so it never races a broker that is already going away.
2316
2310
  let stopping = false;
2317
- // The signal that asked for the stop. The broker is then signalled SIGTERM, so its own exit
2318
- // status is not the command's: SIGINT exits 130 and SIGTERM exits 143, as a controller stack's
2319
- // foreground stop does.
2311
+ // The operator's signal sets the command's exit status, not the broker's SIGTERM.
2320
2312
  let stopSignal;
2313
+ let stoppedListener = false;
2321
2314
  let teardown;
2322
2315
  const stop = (signal) => {
2323
2316
  if (stopping)
@@ -2341,15 +2334,13 @@ async function runUp(args, invokedFrom, inheritedLock, onAdopt, freshTeamBoot =
2341
2334
  }
2342
2335
  await stopDelivery(space).catch((e) => console.error(`! delivery teardown: ${e.message}`));
2343
2336
  await stopAuthService(space).catch((e) => console.error(`! auth teardown: ${e.message}`));
2344
- child.kill("SIGTERM");
2337
+ stoppedListener = child.kill("SIGTERM");
2345
2338
  })();
2346
2339
  };
2347
2340
  process.on("SIGINT", () => stop("SIGINT"));
2348
2341
  process.on("SIGTERM", () => stop("SIGTERM"));
2349
2342
  restored?.releaseInterruptNotice?.();
2350
- // The broker is gone. Drop the registration this stop recorded, and the `current` pointer when it
2351
- // names that registration, so a later `cotal spawn` does not join a dead mesh. A space named after
2352
- // its folder keeps both, as `cotal down` does, so the name stays the folder's.
2343
+ // On exit, drop only this stop's registration and matching `current` pointer, unless folder-named.
2353
2344
  child.on("exit", async (code, signal) => {
2354
2345
  if (failedListeners.has(child))
2355
2346
  return;
@@ -2416,7 +2407,12 @@ async function runUp(args, invokedFrom, inheritedLock, onAdopt, freshTeamBoot =
2416
2407
  process.exit(exitCode("failed", "OPERATION_FAILED"));
2417
2408
  }
2418
2409
  });
2419
- await awaitSpawnedListener({ child, executable: natsServer, server, space, creds: setup?.creds, tls: transport.kind === "tls-required", log: brokerOutput, boundListener });
2410
+ await awaitSpawnedListener({ child, executable: natsServer, server, space, creds: setup?.creds, tls: transport.kind === "tls-required", log: brokerOutput, boundListener }).catch((error) => {
2411
+ if (!restored || !stoppedListener || !stopSignal || (child.exitCode === null && child.signalCode === null))
2412
+ throw error;
2413
+ releaseStartupLock();
2414
+ exitInterrupted(stopSignal, restoreInterruptNotice(restored.root, restored.attemptId));
2415
+ });
2420
2416
  listenerReady = true;
2421
2417
  {
2422
2418
  // A DAEMON THAT DIES UNDER THIS RUNNING BROKER IS RESTARTED HERE (#2469). It exits on its own once
@@ -5002,343 +4998,6 @@ async function recreateDeletedStreams(opts) {
5002
4998
  await postStart(opts.server, opts.space, setup, opts.seed ?? loadChannelsFile(opts.channels));
5003
4999
  return true;
5004
5000
  }
5005
- function parseMaxFileStore(raw) {
5006
- return parsePositiveIntegerFlag("--max-file-store", raw);
5007
- }
5008
- /** `--auth-timeout`, whole seconds from 1 to 60. nats-server warns above 60 that the value is
5009
- * probably a mistake, and a stalled callout holds every connect that long. */
5010
- function parseAuthTimeout(raw) {
5011
- const seconds = parsePositiveIntegerFlag("--auth-timeout", raw);
5012
- if (seconds !== undefined && seconds > MAX_AUTH_TIMEOUT_SECONDS)
5013
- throw new CommandFailure("refused", "USAGE_INVALID", `--auth-timeout ${seconds} is over ${MAX_AUTH_TIMEOUT_SECONDS} seconds; it is how long the broker holds a connect while the auth callout has not answered, and nothing was started`, { remedy: `pass --auth-timeout 1 to ${MAX_AUTH_TIMEOUT_SECONDS}, or omit it for nats-server's 2 seconds` });
5014
- return seconds;
5015
- }
5016
- const MAX_AUTH_TIMEOUT_SECONDS = 60;
5017
- /** `--max-payload`, a positive whole number of bytes. nats-server refuses to start above 64 MiB, so
5018
- * the refusal names that bound rather than letting the broker exit on its own configuration. */
5019
- function parseMaxPayload(raw) {
5020
- const bytes = parsePositiveIntegerFlag("--max-payload", raw);
5021
- if (bytes !== undefined && bytes > MAX_BROKER_PAYLOAD_BYTES)
5022
- throw new CommandFailure("refused", "USAGE_INVALID", `--max-payload ${bytes} is over ${MAX_BROKER_PAYLOAD_BYTES} bytes (64 MiB), which nats-server refuses to start on; nothing was started`, { remedy: `pass --max-payload ${MAX_BROKER_PAYLOAD_BYTES} or less` });
5023
- return bytes;
5024
- }
5025
- const MAX_BROKER_PAYLOAD_BYTES = 64 * 1024 * 1024;
5026
- /** `--account-resolver`, memory or full. */
5027
- function parseAccountResolver(raw) {
5028
- if (raw === undefined || raw === "memory" || raw === "full")
5029
- return raw;
5030
- throw new CommandFailure("refused", "USAGE_INVALID", `--account-resolver takes memory or full (got ${JSON.stringify(raw)}); nothing was started`, { remedy: "pass --account-resolver memory or --account-resolver full" });
5031
- }
5032
- /** The auth-service daemon argv that gives the callout the broker's timeout as its deadline. Built
5033
- * only from the value the broker configuration rendered, so the two never differ. */
5034
- function authTimeoutArgs(seconds) {
5035
- return seconds === undefined ? [] : ["--auth-timeout", String(seconds)];
5036
- }
5037
- /** Load the declarative channels-config file to seed the registry. An explicit `--channels`
5038
- * path that's missing is a hard error; the default `.cotal/channels.json` is optional (absent
5039
- * ⇒ nothing to seed). */
5040
- function loadChannelsFile(explicit) {
5041
- if (explicit)
5042
- return readChannelsFile(resolve(explicit));
5043
- return readDefaultChannelsFile(cotalRoot());
5044
- }
5045
- /** Refuse `up --space` of a space this machine started from another folder while its broker answers,
5046
- * naming that folder: the stack there is the one to use or stop. */
5047
- async function refuseRunningElsewhere(space, root) {
5048
- const owner = findMesh(space);
5049
- if (!owner || owner.origin === "manual" || owner.origin === "catalog" || !isAbsolute(owner.root) || canonicalRoot(owner.root) === canonicalRoot(root) || !(await isReachable(owner.server)))
5050
- return;
5051
- let controller = false;
5052
- try {
5053
- controller = readStackJournal(owner.root)?.journal.space === space;
5054
- }
5055
- catch { /* named with the legacy stop */ }
5056
- const rootExists = existsSync(owner.root);
5057
- const moved = !controller && !retainedLegacyBroker(owner.root) && recordsElsewhereError(root)?.details.stackSpace === space;
5058
- const remedy = moved
5059
- ? `${rootExists ? `move what is now at ${owner.root} aside, then ` : ""}move this folder back to ${owner.root} and run \`cotal down --yes\` there`
5060
- : !rootExists
5061
- ? `restore the original project at ${owner.root}, then run \`cotal down --yes\` there`
5062
- : `use it from here with --space ${space}, or stop it with \`cotal down${controller ? " --yes" : ""}\` in ${owner.root}`;
5063
- throw new CommandFailure("refused", "CONFLICT", `space "${space}" runs at ${owner.server}, started in ${owner.root}, so up did not start it again`, { target: { space, root: owner.root, server: owner.server }, remedy });
5064
- }
5065
- /** Refuses a bare `up` in a folder holding the records of a space this machine registers for another
5066
- * folder, as a copy, a moved folder and one whose name a later `up` took over keep them. The retained
5067
- * launcher writes no stack journal, so this is that launcher's form of the journal's refusal: it
5068
- * names that folder and the step reads there name. When that folder is gone and its broker does not
5069
- * answer, it also names the `--space` that takes the name over to run the stack from this folder. */
5070
- async function refuseRecordsElsewhere(root) {
5071
- const records = recordsElsewhereError(root)?.details;
5072
- if (!records?.lastRun || records.stackSpace === undefined || records.recordedRoot === undefined || records.stackRemedy === undefined)
5073
- return;
5074
- const space = records.stackSpace;
5075
- const takeover = !existsSync(records.recordedRoot) && !(await isReachable(findMesh(space)?.server ?? records.server ?? DEFAULT_SERVER));
5076
- throw new CommandFailure("refused", "CONFLICT", `this folder holds the records of "${space}", which is registered for ${records.recordedRoot}, not for this folder, so up did not start it here`, {
5077
- target: { root, space, recordedRoot: records.recordedRoot },
5078
- remedy: takeover ? `${records.stackRemedy}; or, to run it from this folder, take the name over with \`cotal up --space ${space}\`` : records.stackRemedy,
5079
- });
5080
- }
5081
- /**
5082
- * Turn the `--tls-cert`/`--tls-key` pair into a validated {@link BrokerTransport}, or `plaintext`
5083
- * when neither was given.
5084
- *
5085
- * REFUSES BEFORE LAUNCH, never after. Everything it rejects would otherwise become a running broker
5086
- * in some wrong state, and the two failure modes are not symmetrical: a broker that will not start
5087
- * is an operator reading an error, while a broker that starts wrong is an operator believing they
5088
- * have TLS. So the validation is deliberately ours and deliberately early.
5089
- *
5090
- * `validateTlsMaterial` does the substantive checks — readability, private-key mode, PEM pair
5091
- * match, validity window, dial-host SAN — because nats-server's are not sufficient. Missing,
5092
- * unreadable and mismatched pairs do stop it before it opens a listener, but an EXPIRED certificate
5093
- * does not: it reports the config valid, starts, logs "Server is ready" and "TLS required", and
5094
- * only the client then fails. An expired cert must never yield "mesh up".
5095
- *
5096
- * @param dialHost the hostname clients will verify against, which is NOT the bind host — a broker
5097
- * may bind `0.0.0.0` while clients dial `broker.example`.
5098
- */
5099
- function resolveTransport(values, dialHost, root,
5100
- /** `persist` defaults false (commit-after-apply). `quiet` suppresses serving/inheriting lines
5101
- * until the caller announces after a successful apply. */
5102
- opts = {}) {
5103
- const certFile = values["tls-cert"], keyFile = values["tls-key"];
5104
- const quiet = opts.quiet === true;
5105
- // NO FLAGS: inherit the RECORDED decision rather than defaulting to plaintext. This is the half
5106
- // that makes a bare `cotal up` after a `cotal down` keep serving TLS. Without it the decision
5107
- // lives only in the argv of whichever invocation first made it, and the most ordinary operator
5108
- // gesture there is - stop the mesh, start it again - silently downgrades a broker that was
5109
- // deliberately put on TLS. `readBrokerPolicy` refuses rather than degrading if the recorded
5110
- // material has gone missing, so a moved cert fails loud here instead of coming up in cleartext.
5111
- if (!certFile && !keyFile) {
5112
- let recorded;
5113
- try {
5114
- recorded = readBrokerPolicy(root);
5115
- }
5116
- catch (e) {
5117
- stderrLine("✗ ", `${e instanceof Error ? e.message : String(e)}`, c.red);
5118
- process.exit(1);
5119
- }
5120
- if (recorded?.transport.kind === "tls-required") {
5121
- if (!quiet)
5122
- console.log(c.dim("TLS: inheriting the recorded broker policy (no --tls-cert/--tls-key given)"));
5123
- return validateRecorded(recorded.transport, dialHost, { quiet });
5124
- }
5125
- return { kind: "plaintext" };
5126
- }
5127
- // Half a pair is a mistake, never a configuration. Refusing names the missing half rather than
5128
- // failing later inside nats-server with a message about a file the operator did not mention.
5129
- if (!certFile || !keyFile) {
5130
- stderrLine("✗ ", `--tls-cert and --tls-key must be given together (missing ${certFile ? "--tls-key" : "--tls-cert"})`, c.red);
5131
- process.exit(1);
5132
- }
5133
- const transport = { kind: "tls-required", certFile: resolve(certFile), keyFile: resolve(keyFile) };
5134
- const validated = validateRecorded(transport, dialHost, { quiet });
5135
- // RECORD only when the caller has already applied the transport (started a matching listener).
5136
- // Eager write here is S5: a refuse path cannot unwrite, and the next bare up inherits fiction.
5137
- if (opts.persist === true)
5138
- writeBrokerPolicy(root, { version: 1, transport: validated });
5139
- return validated;
5140
- }
5141
- /** A `tls://` broker address is recorded as required TLS, and every later dial through the record
5142
- * trusts it. Refuse it, before anything starts, when this start would serve plaintext. */
5143
- function assertTlsIntentServed(server, transport, source) {
5144
- const tls = server.split(",").some((url) => url.trim().toLowerCase().startsWith("tls://"));
5145
- if (tls && transport.kind !== "tls-required")
5146
- throw new CommandFailure("refused", "USAGE_INVALID", `${source} names a tls:// address, but no TLS certificate and key are configured, so the broker would serve plaintext; nothing was started`, { target: { server: brokerAddressForDisplay(server) ?? "not displayable" }, remedy: "serve TLS with --tls-cert <cert.pem> --tls-key <key.pem>, or use a nats:// address", selfContained: true });
5147
- }
5148
- /** A broker that serves TLS is dialed `tls://`, so an address naming `nats://` would be recorded,
5149
- * registered and handed to every later client as plaintext. Refuse it before anything starts,
5150
- * naming the recorded policy that serves TLS and the address to pass instead. */
5151
- function assertTlsAddressServed(server, transport, root) {
5152
- if (transport.kind !== "tls-required")
5153
- return;
5154
- if (!server.split(",").some((url) => /^nats:\/\//i.test(url.trim())))
5155
- return;
5156
- throw new CommandFailure("refused", "USAGE_INVALID", `this root serves the broker over TLS (${brokerPolicyPath(root)}), so --server must be a tls:// address; nothing was started or written`, {
5157
- target: { root, server: brokerAddressForDisplay(server) ?? "not displayable" },
5158
- remedy: `pass --server ${tlsAddress(server)}`,
5159
- selfContained: true,
5160
- });
5161
- }
5162
- /** Persist a transport, and the auth callout timeout, payload limit and account resolver the broker
5163
- * configuration rendered, after its listener starts; a structured boot leaves stdout to its receipt.
5164
- * An absent `accountResolver` keeps the recorded one, and a memory start replaces a recorded full
5165
- * one even when nothing else is left to record. */
5166
- function commitTransportPolicy(root, transport, quietBoot = false, server, limits) {
5167
- const { authTimeout, maxPayload } = limits ?? {};
5168
- const recordedResolver = readBrokerPolicy(root)?.accountResolver;
5169
- const full = (limits?.accountResolver ?? recordedResolver ?? "memory") === "full";
5170
- if (transport.kind !== "tls-required" && authTimeout === undefined && maxPayload === undefined && !full && recordedResolver === undefined)
5171
- return;
5172
- writeBrokerPolicy(root, { version: 1, transport, ...(authTimeout !== undefined ? { authTimeout } : {}), ...(maxPayload !== undefined ? { maxPayload } : {}),
5173
- ...(full ? { accountResolver: "full" } : {}) });
5174
- if (!quietBoot)
5175
- announceTransport(transport, server);
5176
- }
5177
- /** The `tls://` form of a broker URL, or of each URL in a list. */
5178
- const tlsAddress = (server) => server.split(",").map((url) => url.trim().replace(/^nats:/i, "tls:")).join(",");
5179
- function announceTransport(transport, server) {
5180
- if (transport.kind !== "tls-required")
5181
- return;
5182
- try {
5183
- const material = validateTlsMaterial(transport, {});
5184
- console.log(c.dim(`TLS: serving ${material.subject}${server ? ` at ${server}` : ""}, valid until ${material.notAfter.toISOString()}`));
5185
- }
5186
- catch {
5187
- // Already validated at decide-time; announce is best-effort display.
5188
- }
5189
- }
5190
- /** Read the live INFO greeting and report whether the listener requires TLS.
5191
- * `undefined` means no usable INFO (timeout / closed) — caller treats as unknown. */
5192
- async function liveListenerRequiresTls(server, timeoutMs = 2000) {
5193
- let host;
5194
- let port;
5195
- try {
5196
- const u = new URL(server);
5197
- host = u.hostname || "127.0.0.1";
5198
- port = Number(u.port) || 4222;
5199
- }
5200
- catch {
5201
- return undefined;
5202
- }
5203
- return await new Promise((res) => {
5204
- const sock = createConnection({ host, port });
5205
- let buf = "";
5206
- const done = (v) => {
5207
- try {
5208
- sock.destroy();
5209
- }
5210
- catch { /* */ }
5211
- res(v);
5212
- };
5213
- sock.setTimeout(timeoutMs, () => done(undefined));
5214
- sock.on("error", () => done(undefined));
5215
- sock.on("close", () => done(undefined));
5216
- sock.on("data", (d) => {
5217
- buf += d.toString("utf8");
5218
- const nl = buf.indexOf("\r\n");
5219
- if (nl < 0)
5220
- return;
5221
- const line = buf.slice(0, nl);
5222
- try {
5223
- const info = JSON.parse(line.replace(/^INFO\s+/, ""));
5224
- done(info.tls_required === true);
5225
- }
5226
- catch {
5227
- done(undefined);
5228
- }
5229
- });
5230
- });
5231
- }
5232
- /**
5233
- * Re-assert that `transport` is valid for the host clients will actually dial, and exit loudly if
5234
- * not. A no-op for plaintext.
5235
- *
5236
- * This exists because the transport is decided ONCE, early, before the route is known, so that no
5237
- * route can be reached without one — but the effective dial host is decided LATE and differs per
5238
- * route: a manifest may set `broker.host`, and a certificate valid for the flag-derived host is not
5239
- * thereby valid for that one. Deciding early and checking late is the only ordering that satisfies
5240
- * both, so the check is deliberately separate from the decision rather than folded into it.
5241
- *
5242
- * Quiet on success: `resolveTransport` already printed what is being served, and a second identical
5243
- * line reads like a second broker.
5244
- */
5245
- function assertServesDialHost(transport, dialHost) {
5246
- if (transport.kind !== "tls-required" || dialHost === undefined)
5247
- return transport;
5248
- try {
5249
- validateTlsMaterial(transport, { dialHost });
5250
- }
5251
- catch (e) {
5252
- stderrLine("✗ ", `${e instanceof Error ? e.message : String(e)}`, c.red);
5253
- process.exit(1);
5254
- }
5255
- return transport;
5256
- }
5257
- /**
5258
- * The client-side TLS requirement to persist for a listener THIS PROCESS DID NOT START — the
5259
- * restore and ordinary-resume paths, which adopt a broker that is already listening.
5260
- *
5261
- * They have no `transport` in scope because they never decided one, so the honest source is the
5262
- * recorded policy: the listener they are adopting was started from it. Reading it here is what stops
5263
- * a resume from writing a registry entry that says "plaintext" over a broker serving TLS — clients
5264
- * resolved from that entry would then connect without requiring it, which is the downgrade this
5265
- * feature exists to prevent, arriving by way of a recovery path rather than a launch.
5266
- *
5267
- * Fails loud on an unusable policy for the same reason `resolveTransport` does: a resume that cannot
5268
- * tell what it is adopting must not guess.
5269
- */
5270
- function adoptedTlsRequired(root) {
5271
- try {
5272
- return readBrokerPolicy(root)?.transport.kind === "tls-required";
5273
- }
5274
- catch (e) {
5275
- stderrLine("✗ ", `${e instanceof Error ? e.message : String(e)}`, c.red);
5276
- process.exit(1);
5277
- }
5278
- }
5279
- /** Validate a TLS pair and exit loudly on anything wrong. Shared by the flag path and the
5280
- * recorded-policy path so a cert that rots on disk is caught on the NEXT `up`, not only on the
5281
- * one that first configured it. */
5282
- function validateRecorded(transport, dialHost, opts = {}) {
5283
- try {
5284
- const material = validateTlsMaterial(transport, dialHost !== undefined ? { dialHost } : {});
5285
- if (!opts.quiet)
5286
- console.log(c.dim(`TLS: serving ${material.subject}, valid until ${material.notAfter.toISOString()}`));
5287
- }
5288
- catch (e) {
5289
- // Surface the CERTIFICATE cause. A TLS failure reported as a generic startup error invites the
5290
- // wrong remedy - operators go looking at ports and firewalls when the answer is the cert.
5291
- stderrLine("✗ ", `${e instanceof Error ? e.message : String(e)}`, c.red);
5292
- process.exit(1);
5293
- }
5294
- return transport;
5295
- }
5296
- /** A start that names no store would open an empty second store and leave the data where it was:
5297
- * while the last served store holds data and the default store holds none, refuse and name it. */
5298
- function refuseUnnamedLastStore(storeDir) {
5299
- if (existsSync(join(storeDir, "jetstream")))
5300
- return;
5301
- const last = lastServedStore(cotalRoot(), storeDir);
5302
- if (last !== undefined)
5303
- throw new CommandFailure("refused", "CONFLICT", `this root's last broker served the store ${last}, and this start names no store, so it would open a new empty one at ${storeDir}; nothing was started`, { target: { root: cotalRoot(), storeDir: last }, remedy: `reopen it with --store-dir ${last}, or move that store away to start empty` });
5304
- }
5305
- /** The store a bare start that names none opens: the store this root's last broker served, while
5306
- * it holds data and the default store holds none, since the default would open empty and leave the
5307
- * data where it was. When the broker configs name two such stores, the start refuses as
5308
- * {@link refuseUnnamedLastStore} does, because which one to reopen is the operator's choice. */
5309
- function reopenLastStore(storeDir) {
5310
- if (existsSync(join(storeDir, "jetstream")))
5311
- return undefined;
5312
- const last = lastServedStores(cotalRoot(), storeDir);
5313
- if (last.length > 1)
5314
- refuseUnnamedLastStore(storeDir);
5315
- if (last.length === 1)
5316
- for (const line of hang("", `reopening ${last[0]}, the store this root's last broker served`, terminalWidth(process.stdout), c.dim))
5317
- console.log(line);
5318
- return last[0];
5319
- }
5320
- /** A `--store-dir` that does not exist yet, while the last served store holds data, is taken for a
5321
- * mistyped path: the start would open a new empty store there. Creating the directory first names a
5322
- * new store on purpose. */
5323
- function refuseMissingNamedStore(storeDir) {
5324
- if (existsSync(storeDir))
5325
- return;
5326
- const last = lastServedStore(cotalRoot(), storeDir);
5327
- if (last !== undefined)
5328
- throw new CommandFailure("refused", "CONFLICT", `this root's last broker served the store ${last}, and --store-dir names ${storeDir}, which does not exist, so this start would open a new empty store there; nothing was started`, { target: { root: cotalRoot(), storeDir: last, requested: storeDir }, remedy: `reopen it with --store-dir ${last}, or create ${storeDir} first to start on a new empty store` });
5329
- }
5330
- /** A start's store against the other spaces that use it. A `--store-dir` this root's last broker did
5331
- * not serve refuses while another space uses it. The default or last served store starts with a
5332
- * warning, and one whose folder that broker served is missing starts empty with a warning. */
5333
- function checkStartStore(storeDir, space) {
5334
- const path = storeDir === undefined ? cotalPath("nats") : resolve(storeDir);
5335
- const served = servedStore(cotalRoot(), path);
5336
- const tenants = sharedStoreAtStart(path, space, storeDir === undefined || served);
5337
- if (tenants.length)
5338
- console.error(c.yellow(`! ${sharedStoreWarning(path, tenants)}`));
5339
- if (served && !existsSync(path))
5340
- console.error(c.yellow(`! ${missingStoreWarning(path)}`));
5341
- }
5342
5001
  /**
5343
5002
  * Render and write the config for an OPEN (no-auth) broker, returning its path. It names `space`,
5344
5003
  * because an open root holds no account that would ({@link namedOpenConfig}).