@cotal-ai/cli 0.174.3 → 0.175.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 (221) hide show
  1. package/dist/chat/stdio.js +1 -1
  2. package/dist/chat/stdio.js.map +1 -1
  3. package/dist/command.d.ts.map +1 -1
  4. package/dist/command.js +8 -5
  5. package/dist/command.js.map +1 -1
  6. package/dist/commands/agents.d.ts.map +1 -1
  7. package/dist/commands/agents.js +53 -24
  8. package/dist/commands/agents.js.map +1 -1
  9. package/dist/commands/channel-members.d.ts.map +1 -1
  10. package/dist/commands/channel-members.js +9 -7
  11. package/dist/commands/channel-members.js.map +1 -1
  12. package/dist/commands/channels.d.ts.map +1 -1
  13. package/dist/commands/channels.js +16 -7
  14. package/dist/commands/channels.js.map +1 -1
  15. package/dist/commands/chat.js +1 -1
  16. package/dist/commands/chat.js.map +1 -1
  17. package/dist/commands/clean.d.ts.map +1 -1
  18. package/dist/commands/clean.js +5 -3
  19. package/dist/commands/clean.js.map +1 -1
  20. package/dist/commands/config.d.ts.map +1 -1
  21. package/dist/commands/config.js +8 -1
  22. package/dist/commands/config.js.map +1 -1
  23. package/dist/commands/describe.d.ts.map +1 -1
  24. package/dist/commands/describe.js +11 -1
  25. package/dist/commands/describe.js.map +1 -1
  26. package/dist/commands/doctor.d.ts.map +1 -1
  27. package/dist/commands/doctor.js +21 -9
  28. package/dist/commands/doctor.js.map +1 -1
  29. package/dist/commands/down-preserve.d.ts.map +1 -1
  30. package/dist/commands/down-preserve.js +2 -1
  31. package/dist/commands/down-preserve.js.map +1 -1
  32. package/dist/commands/endpoint-authoring.d.ts.map +1 -1
  33. package/dist/commands/endpoint-authoring.js +20 -19
  34. package/dist/commands/endpoint-authoring.js.map +1 -1
  35. package/dist/commands/endpoint.d.ts.map +1 -1
  36. package/dist/commands/endpoint.js +7 -2
  37. package/dist/commands/endpoint.js.map +1 -1
  38. package/dist/commands/endpoints.d.ts.map +1 -1
  39. package/dist/commands/endpoints.js +12 -5
  40. package/dist/commands/endpoints.js.map +1 -1
  41. package/dist/commands/ext.d.ts +2 -6
  42. package/dist/commands/ext.d.ts.map +1 -1
  43. package/dist/commands/ext.js +19 -25
  44. package/dist/commands/ext.js.map +1 -1
  45. package/dist/commands/history-clear.d.ts.map +1 -1
  46. package/dist/commands/history-clear.js +5 -2
  47. package/dist/commands/history-clear.js.map +1 -1
  48. package/dist/commands/history.d.ts +2 -2
  49. package/dist/commands/history.d.ts.map +1 -1
  50. package/dist/commands/history.js +5 -6
  51. package/dist/commands/history.js.map +1 -1
  52. package/dist/commands/join.d.ts.map +1 -1
  53. package/dist/commands/join.js +36 -24
  54. package/dist/commands/join.js.map +1 -1
  55. package/dist/commands/meshes-add.d.ts.map +1 -1
  56. package/dist/commands/meshes-add.js +3 -2
  57. package/dist/commands/meshes-add.js.map +1 -1
  58. package/dist/commands/meshes.d.ts.map +1 -1
  59. package/dist/commands/meshes.js +17 -4
  60. package/dist/commands/meshes.js.map +1 -1
  61. package/dist/commands/persona-remote.d.ts.map +1 -1
  62. package/dist/commands/persona-remote.js +8 -4
  63. package/dist/commands/persona-remote.js.map +1 -1
  64. package/dist/commands/persona.d.ts.map +1 -1
  65. package/dist/commands/persona.js +38 -29
  66. package/dist/commands/persona.js.map +1 -1
  67. package/dist/commands/personas.js +1 -5
  68. package/dist/commands/personas.js.map +1 -1
  69. package/dist/commands/revoke-credential.d.ts.map +1 -1
  70. package/dist/commands/revoke-credential.js +5 -2
  71. package/dist/commands/revoke-credential.js.map +1 -1
  72. package/dist/commands/send.d.ts.map +1 -1
  73. package/dist/commands/send.js +4 -1
  74. package/dist/commands/send.js.map +1 -1
  75. package/dist/commands/service-actions.d.ts.map +1 -1
  76. package/dist/commands/service-actions.js +11 -4
  77. package/dist/commands/service-actions.js.map +1 -1
  78. package/dist/commands/service-registry.js +1 -1
  79. package/dist/commands/service-registry.js.map +1 -1
  80. package/dist/commands/setup.d.ts.map +1 -1
  81. package/dist/commands/setup.js +2 -2
  82. package/dist/commands/setup.js.map +1 -1
  83. package/dist/commands/space-delete.d.ts.map +1 -1
  84. package/dist/commands/space-delete.js +17 -10
  85. package/dist/commands/space-delete.js.map +1 -1
  86. package/dist/commands/space-registration.d.ts.map +1 -1
  87. package/dist/commands/space-registration.js +11 -9
  88. package/dist/commands/space-registration.js.map +1 -1
  89. package/dist/commands/space.d.ts.map +1 -1
  90. package/dist/commands/space.js +39 -9
  91. package/dist/commands/space.js.map +1 -1
  92. package/dist/commands/spawn-flags.d.ts +5 -7
  93. package/dist/commands/spawn-flags.d.ts.map +1 -1
  94. package/dist/commands/spawn-flags.js +42 -6
  95. package/dist/commands/spawn-flags.js.map +1 -1
  96. package/dist/commands/spawn-preview.d.ts.map +1 -1
  97. package/dist/commands/spawn-preview.js +5 -3
  98. package/dist/commands/spawn-preview.js.map +1 -1
  99. package/dist/commands/spawn.d.ts.map +1 -1
  100. package/dist/commands/spawn.js +9 -2
  101. package/dist/commands/spawn.js.map +1 -1
  102. package/dist/commands/stack-up.d.ts.map +1 -1
  103. package/dist/commands/stack-up.js +12 -6
  104. package/dist/commands/stack-up.js.map +1 -1
  105. package/dist/commands/status-health.d.ts +139 -0
  106. package/dist/commands/status-health.d.ts.map +1 -0
  107. package/dist/commands/status-health.js +651 -0
  108. package/dist/commands/status-health.js.map +1 -0
  109. package/dist/commands/status-meshes.d.ts +26 -0
  110. package/dist/commands/status-meshes.d.ts.map +1 -0
  111. package/dist/commands/status-meshes.js +468 -0
  112. package/dist/commands/status-meshes.js.map +1 -0
  113. package/dist/commands/status-render.d.ts +30 -0
  114. package/dist/commands/status-render.d.ts.map +1 -0
  115. package/dist/commands/status-render.js +782 -0
  116. package/dist/commands/status-render.js.map +1 -0
  117. package/dist/commands/status.d.ts +2 -16
  118. package/dist/commands/status.d.ts.map +1 -1
  119. package/dist/commands/status.js +20 -1877
  120. package/dist/commands/status.js.map +1 -1
  121. package/dist/commands/topology.d.ts.map +1 -1
  122. package/dist/commands/topology.js +4 -0
  123. package/dist/commands/topology.js.map +1 -1
  124. package/dist/commands/up-broker-auth.d.ts +78 -0
  125. package/dist/commands/up-broker-auth.d.ts.map +1 -0
  126. package/dist/commands/up-broker-auth.js +430 -0
  127. package/dist/commands/up-broker-auth.js.map +1 -0
  128. package/dist/commands/up-host.d.ts +19 -0
  129. package/dist/commands/up-host.d.ts.map +1 -0
  130. package/dist/commands/up-host.js +105 -0
  131. package/dist/commands/up-host.js.map +1 -0
  132. package/dist/commands/up-stores.d.ts +42 -0
  133. package/dist/commands/up-stores.d.ts.map +1 -0
  134. package/dist/commands/up-stores.js +242 -0
  135. package/dist/commands/up-stores.js.map +1 -0
  136. package/dist/commands/up-target.d.ts +2 -0
  137. package/dist/commands/up-target.d.ts.map +1 -1
  138. package/dist/commands/up-target.js +9 -0
  139. package/dist/commands/up-target.js.map +1 -1
  140. package/dist/commands/up.d.ts.map +1 -1
  141. package/dist/commands/up.js +31 -781
  142. package/dist/commands/up.js.map +1 -1
  143. package/dist/commands/update-process.d.ts.map +1 -1
  144. package/dist/commands/update-process.js +3 -15
  145. package/dist/commands/update-process.js.map +1 -1
  146. package/dist/commands/update.js +1 -1
  147. package/dist/commands/update.js.map +1 -1
  148. package/dist/commands/use.js +2 -2
  149. package/dist/commands/use.js.map +1 -1
  150. package/dist/console/app.js +5 -5
  151. package/dist/console/app.js.map +1 -1
  152. package/dist/console/commands.d.ts +1 -1
  153. package/dist/console/commands.d.ts.map +1 -1
  154. package/dist/console/commands.js +1 -1
  155. package/dist/console/commands.js.map +1 -1
  156. package/dist/console/ui/Feed.d.ts +2 -2
  157. package/dist/console/ui/Feed.d.ts.map +1 -1
  158. package/dist/console/ui/Feed.js +2 -2
  159. package/dist/console/ui/Feed.js.map +1 -1
  160. package/dist/console/ui/StatusBar.d.ts +1 -1
  161. package/dist/console/ui/StatusBar.d.ts.map +1 -1
  162. package/dist/console/ui/StatusBar.js +1 -1
  163. package/dist/console/ui/StatusBar.js.map +1 -1
  164. package/dist/console/ui/Tabs.d.ts +2 -2
  165. package/dist/console/ui/Tabs.d.ts.map +1 -1
  166. package/dist/console/ui/Tabs.js +4 -4
  167. package/dist/console/ui/Tabs.js.map +1 -1
  168. package/dist/ext-loader.d.ts.map +1 -1
  169. package/dist/ext-loader.js +1 -0
  170. package/dist/ext-loader.js.map +1 -1
  171. package/dist/lib/backup-artifact.d.ts.map +1 -1
  172. package/dist/lib/backup-artifact.js +19 -7
  173. package/dist/lib/backup-artifact.js.map +1 -1
  174. package/dist/lib/choose-target.d.ts +1 -1
  175. package/dist/lib/choose-target.d.ts.map +1 -1
  176. package/dist/lib/choose-target.js +7 -4
  177. package/dist/lib/choose-target.js.map +1 -1
  178. package/dist/lib/completion-install.js +7 -8
  179. package/dist/lib/completion-install.js.map +1 -1
  180. package/dist/lib/control.d.ts +8 -2
  181. package/dist/lib/control.d.ts.map +1 -1
  182. package/dist/lib/control.js +11 -4
  183. package/dist/lib/control.js.map +1 -1
  184. package/dist/lib/manager-choice.d.ts +2 -1
  185. package/dist/lib/manager-choice.d.ts.map +1 -1
  186. package/dist/lib/manager-choice.js +2 -2
  187. package/dist/lib/manager-choice.js.map +1 -1
  188. package/dist/lib/manifest/index.d.ts +1 -1
  189. package/dist/lib/manifest/index.d.ts.map +1 -1
  190. package/dist/lib/manifest/index.js +2 -2
  191. package/dist/lib/manifest/index.js.map +1 -1
  192. package/dist/lib/manifest/resolve.d.ts +1 -1
  193. package/dist/lib/manifest/resolve.d.ts.map +1 -1
  194. package/dist/lib/manifest/resolve.js +4 -4
  195. package/dist/lib/manifest/resolve.js.map +1 -1
  196. package/dist/lib/npm-invocation.d.ts +6 -0
  197. package/dist/lib/npm-invocation.d.ts.map +1 -0
  198. package/dist/lib/npm-invocation.js +18 -0
  199. package/dist/lib/npm-invocation.js.map +1 -0
  200. package/dist/lib/persona-files.d.ts +1 -0
  201. package/dist/lib/persona-files.d.ts.map +1 -1
  202. package/dist/lib/persona-files.js +6 -2
  203. package/dist/lib/persona-files.js.map +1 -1
  204. package/dist/lib/personas.d.ts +1 -2
  205. package/dist/lib/personas.d.ts.map +1 -1
  206. package/dist/lib/personas.js +12 -3
  207. package/dist/lib/personas.js.map +1 -1
  208. package/dist/lib/private-directory.d.ts +3 -3
  209. package/dist/lib/private-directory.d.ts.map +1 -1
  210. package/dist/lib/private-directory.js +17 -7
  211. package/dist/lib/private-directory.js.map +1 -1
  212. package/dist/lib/service-presets.d.ts.map +1 -1
  213. package/dist/lib/service-presets.js +10 -5
  214. package/dist/lib/service-presets.js.map +1 -1
  215. package/dist/lib/stack-journal.d.ts.map +1 -1
  216. package/dist/lib/stack-journal.js +7 -4
  217. package/dist/lib/stack-journal.js.map +1 -1
  218. package/dist/telemetry.d.ts.map +1 -1
  219. package/dist/telemetry.js +3 -2
  220. package/dist/telemetry.js.map +1 -1
  221. package/package.json +4 -4
@@ -4,14 +4,12 @@ import {} from "node:child_process";
4
4
  import { openBrokerLog, prepareForegroundBrokerLog } from "../lib/broker-log.js";
5
5
  import { spawnBroker } from "../lib/broker-spawn.js";
6
6
  import { randomUUID } from "node:crypto";
7
- import { createConnection, createServer, isIP } from "node:net";
7
+ import { createConnection, 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, 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
- import { JetStreamApiCodes, jetstreamManager, StorageType } from "@nats-io/jetstream";
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, 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";
11
+ import { isReachable, dialerFor, DEFAULT_SERVER, DEFAULT_SPACE, SERVICE_AUTHORITY_MAX_BYTES, SERVICE_CALLER_PAYLOAD_FLOOR, CONTRACT_ARTIFACT_MAX_BYTES, MANAGER_START_PAYLOAD_FLOOR, mintCreds, mintLifecycleUid, DEV_OWNER, newIdentity, reconcileSpaceMemoryBuckets, standaloneConnectOpts, parseServerVersion, LEASE_TTL_MS, EpEnvelopeError, writeSecretFile, } from "@cotal-ai/core";
12
+ import { assertManagerName, processStopped, readManagerName, readManagerSeatCap, DEFAULT_SEAT_CAP, recordManagerName, parseSeatCapFlag, seatCapText, CommandFailure, codeSpan, commandFailureReport, failureEnvelope, writeEnvelope, isCommandFailure, protectedLocalDirectory, jsonFlag, plainFlag, renderReport, assertSingleSpaceBroker, assertUserAuthInfo, authDir, brokerAddressForDisplay, getSoleSpaceAuth, soleSpaceOf, getSpaceAuth, hasUserAuthState, listSpaceAccounts, brokerAddressKey, canonicalRoot, rootPathProblem, rootControlProblem, clearCurrent, findMesh, findPreparedSpace, homeCotalDir, legacyStackOtherHome, stackHomeRemedy, getCurrent, loadMeshes, preparedSpaceAt, removePreparedSpace, localMeshesForRoot, keepsRegistration, oneLine, presentationOf, writeResult, parsePositiveIntegerFlag, recordMesh, retainedLegacyBroker, meshesForRoot, removeMesh, setAdoptedCurrent, 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, removePidPair, writePidPair, verifyIdentityPin, processesNaming, isLoopbackHost, connectUserControlOrThrow, userViewAuth, recordOperationSpace, recordOperationWarning, 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
13
  import { FlagValueRefusal } from "../lib/flag-value-refusal.js";
16
14
  import { ensureAuthService, resolveAuthProvider, stopAuthService } from "../lib/auth-proc.js";
17
15
  import { resolveSpace } from "../lib/status.js";
@@ -43,9 +41,9 @@ import { failManifest, refuseManifestSpaceMismatch } from "./topology.js";
43
41
  import { liveMeshProcesses } from "./clean.js";
44
42
  import { checkSpaceFlagValue, checkSpaceName } from "./meshes-add.js";
45
43
  import { checkLocalSpace } from "./space-registration.js";
46
- import { checkNewUpSpace, preparedUpRoot } from "./up-target.js";
47
- import { cleanedManifestStart, interruptedStartBroker, namedOpenConfig, retainedOpenSpace } from "../lib/legacy-start.js";
48
- import { bindReaches, canonicalServer, controllerStackApplies, recheckExistingStore, requestedStackMode, refuseForegroundStackHolder, requestsTls, stackUp, stackUpForegroundNotice, stackUpInterrupted, keptOnUp, selectedOnUp, unparsableDaemonCredsNotice, } from "./stack-up.js";
44
+ import { checkNewUpSpace, checkPublicExchangePort, preparedUpRoot } from "./up-target.js";
45
+ import { cleanedManifestStart, interruptedStartBroker, retainedOpenSpace } from "../lib/legacy-start.js";
46
+ import { bindReaches, canonicalServer, controllerStackApplies, recheckExistingStore, requestedStackMode, refuseForegroundStackHolder, requestsTls, stackUp, stackUpForegroundNotice, stackUpInterrupted, keptOnUp, selectedOnUp, } from "./stack-up.js";
49
47
  import { exitInterrupted, handOverStartupNotice, noticeOnInterrupt, releaseStartupNotice } from "../lib/interrupt-notice.js";
50
48
  import { claimForegroundHold, foregroundHolder, foregroundStackEnd, releaseForegroundHold } from "../lib/foreground-hold.js";
51
49
  import { settleInterruptedLaunches } from "../lib/service-process.js";
@@ -61,7 +59,7 @@ import { serviceSupervisorStore } from "../lib/service-supervision.js";
61
59
  import { serviceInstallIntents } from "../lib/service-install-intent.js";
62
60
  import { serviceUninstallIntents } from "../lib/service-uninstall-intent.js";
63
61
  import { serviceUnitActionStore } from "../lib/service-unit-action.js";
64
- import { assertStoreDirArgument, configuredStoreDir, startupStoreProblem, warnForeignStoreEntries } from "../lib/store-dir.js";
62
+ import { assertStoreDirArgument, startupStoreProblem, warnForeignStoreEntries } from "../lib/store-dir.js";
65
63
  import { extensionNames, preflightRuntime } from "../ext-loader.js";
66
64
  import { completingFlagValue } from "../lib/completion.js";
67
65
  import { metadataPositionals } from "../lib/command-path.js";
@@ -69,11 +67,14 @@ import { bindPreparedRestoreListener, isManagerCommitResult, isManagerFinalizeRe
69
67
  import { attemptProcessesGone } from "../lib/isolated-broker.js";
70
68
  import { assertEndpointUnreachable } from "../lib/endpoint-cut.js";
71
69
  import { brokerAddressConflict } from "../lib/broker-service.js";
72
- import { freePort, freshStackServer, retryStackAddress, serverWithFreePort } from "../lib/up-broker-address.js";
70
+ import { freshStackServer, retryStackAddress, serverWithFreePort } from "../lib/up-broker-address.js";
73
71
  import { askManager } from "@cotal-ai/workspace/control";
74
72
  import { cliControl } from "../lib/control.js";
75
73
  import { pendingRestores, pendingOrdinaryResumes } from "./up-pending.js";
76
74
  import { parseMaxFileStore, parseAuthTimeout, parseMaxPayload, assertManagerPayload, parseAccountResolver, authTimeoutArgs, loadChannelsFile, refuseRunningElsewhere, refuseRecordsElsewhere, resolveTransport, assertTlsIntentServed, assertTlsAddressServed, commitTransportPolicy, tlsAddress, announceTransport, liveListenerRequiresTls, assertServesDialHost, adoptedTlsRequired, refuseUnnamedLastStore, reopenLastStore, refuseMissingNamedStore, checkStartStore, } from "./up-transport.js";
75
+ import { WILDCARD_HOSTS, reconcileHostAndServer, assertFreshTeamBindAvailable } from "./up-host.js";
76
+ import { registeredAddressHolder, refuseRegisteredAddress, membershipConversionRefusal, fileMembershipStore, postStart, recreateMemoryBuckets, recreateAdoptedMemoryBuckets, recreateDeletedStreams, } from "./up-stores.js";
77
+ import { brokerVersion, writeOpenBrokerConf, authSetup, provisionWebCreds } from "./up-broker-auth.js";
77
78
  const restoreSinks = new Map();
78
79
  /** Run the guarded `up --restore` startup and return its result instead of printing it. The
79
80
  * restore inputs and fences are exactly `up --restore`'s; this adds no route, flag or authority. */
@@ -110,12 +111,12 @@ export const upFlags = [
110
111
  { name: "open", type: "boolean", description: "unauthenticated dev mesh (no JWT/ACLs)" },
111
112
  { name: "user-auth", type: "boolean", description: "per-USER auth: login + bearer through the space's auth service" },
112
113
  { name: "idp", type: "string", value: "<url>", description: "with --user-auth: the IdP auth base URL to pin (first enable)" },
113
- { name: "exchange-public-port", type: "string", value: "<n>", description: "with --user-auth: also serve the PUBLIC exchange face on this loopback port (TLS terminates at a reverse proxy)" },
114
- { name: "exchange-public-url", type: "string", value: "<https://…>", description: "with --exchange-public-port: the advertised public base URL (the reverse proxy's address)" },
115
- { name: "exchange-trusted-proxy", type: "boolean", description: "with --exchange-public-port: attribute peers by the last X-Forwarded-For hop (opt-in; default: socket address)" },
116
- { name: "advertised-server", type: "string", value: "<url>", description: "with --exchange-public-port: the broker address the public bundle advertises - what participants dial (default: --server)" },
114
+ { name: "exchange-public-port", type: "string", value: "<n>", description: "legacy user-auth startup only: public loopback port (0 to 65535) for an HTTPS reverse proxy" },
115
+ { name: "exchange-public-url", type: "string", value: "<https://…>", description: "legacy user-auth startup only, with --exchange-public-port: advertise the reverse proxy's HTTPS URL" },
116
+ { name: "exchange-trusted-proxy", type: "boolean", description: "legacy user-auth startup only, with --exchange-public-port: attribute peers by the last X-Forwarded-For hop (default: socket address)" },
117
+ { name: "advertised-server", type: "string", value: "<url>", description: "legacy user-auth startup only, with --exchange-public-port: broker address to advertise (default: --server)" },
117
118
  { name: "service-endpoints", type: "boolean", description: "with --user-auth: the auth service also hosts service endpoints (the registration door and the owner-decision host route)" },
118
- { name: "agent-provisioning-url", type: "string", value: "<https://…>", description: "with --exchange-public-port: the deployment's remote agent-provisioning endpoint the public bundle advertises" },
119
+ { name: "agent-provisioning-url", type: "string", value: "<https://…>", description: "legacy user-auth startup only, with --exchange-public-port: agent-provisioning endpoint to advertise" },
119
120
  { name: "rotate-sys", type: "boolean", description: "renew the expired/expiring $SYS creds by rotating the system account (agents, data and creds survive; needs a stopped mesh)" },
120
121
  { name: "recreate-membership-store", type: "boolean", description: "replace a stopped space's legacy File-backed derived membership feed with the current Memory-backed store" },
121
122
  { name: "recreate-issued-stores", type: "string", value: "<backup-dir>", description: "back up this space's issued-authority stores created before 0.111.0 into a new <backup-dir>, delete them and create them again (needs a stopped stack and every other issuer of the space stopped)" },
@@ -175,6 +176,8 @@ export function validateUpArguments(args) {
175
176
  publicExchangeArgs(args.values, false);
176
177
  serviceEndpointsArgs(args.values, false);
177
178
  }
179
+ else if (typeof args.values["exchange-public-port"] === "string")
180
+ checkPublicExchangePort(args.values["exchange-public-port"]);
178
181
  if (args.values.idp !== undefined && args.values["user-auth"] !== true && !args.values.file)
179
182
  throw new CommandFailure("refused", "USAGE_INVALID", '--idp is for user-auth spaces; pair it with --user-auth, or set broker.auth: "user" in a manifest', { remedy: "use --user-auth --idp <auth base URL>, without --open" });
180
183
  if (args.values.restore !== undefined && args.values["no-manager"] === true)
@@ -274,6 +277,8 @@ export function validateUpArguments(args) {
274
277
  throw new CommandFailure("refused", "USAGE_INVALID", `--restore-only takes registry (got ${JSON.stringify(restoreOnly)})`);
275
278
  if (!args.values.restore && (restoreOnly !== undefined || args.values["accept-missing-source"] === true))
276
279
  throw new CommandFailure("refused", "USAGE_INVALID", "--restore-only and --accept-missing-source require --restore <dir>");
280
+ if (args.values.file !== undefined && args.values["accept-stale-checkpoint"] === true)
281
+ throw new FlagValueRefusal("--accept-stale-checkpoint cannot be combined with --file/-f: a manifest starts a fresh mesh, not a preserved stack", "drop --accept-stale-checkpoint for a fresh start, or omit --file/-f to resume a preserved stack");
277
282
  if (args.values.restore && (args.values.file !== undefined || args.values.channels !== undefined))
278
283
  throw new CommandFailure("refused", "USAGE_INVALID", "--restore cannot be combined with --file/-f or --channels");
279
284
  if (args.values.restore && args.values["rotate-sys"] === true)
@@ -1366,7 +1371,7 @@ async function runUp(args, invokedFrom, inheritedLock, onAdopt, freshTeamBoot =
1366
1371
  // address never reaches the later pin in startMeshDetached, so the catch used to discard it.
1367
1372
  let prepared;
1368
1373
  try {
1369
- prepared = loadManifest(resolve(values.file));
1374
+ prepared = loadManifest(resolve(values.file), logFile);
1370
1375
  }
1371
1376
  catch {
1372
1377
  // Manifest errors are reported by the -f path with the same load; do not double-print.
@@ -1395,7 +1400,7 @@ async function runUp(args, invokedFrom, inheritedLock, onAdopt, freshTeamBoot =
1395
1400
  const managerSeatCap = parseSeatCapFlag("--seat-cap", values["seat-cap"]);
1396
1401
  if (managerSeatCap !== undefined) {
1397
1402
  const capped = { root: cotalRoot(), space: values.space ?? folderSpace() };
1398
- if (readManagerSeatCap(capped) !== managerSeatCap && managerRecordState(capped.space, capped.root).state === "alive")
1403
+ if ((readManagerSeatCap(capped) ?? DEFAULT_SEAT_CAP) !== managerSeatCap && managerRecordState(capped.space, capped.root).state === "alive")
1399
1404
  throw new CommandFailure("refused", "LIFECYCLE_BLOCKED", `a manager already runs for space ${capped.space}, and it keeps the seat cap it started with`, { target: { root: capped.root, space: capped.space }, remedy: `stop it with \`cotal down\`, then run \`cotal up --seat-cap ${seatCapText(managerSeatCap)}\`` });
1400
1405
  }
1401
1406
  // THE TRANSPORT IS DECIDED HERE, ABOVE EVERY BRANCH, AND THIS POSITION IS THE FIX.
@@ -1530,7 +1535,7 @@ async function runUp(args, invokedFrom, inheritedLock, onAdopt, freshTeamBoot =
1530
1535
  // Structured and plain manifest refusals report file errors before checking startup support.
1531
1536
  if (values.json || values.plain) {
1532
1537
  try {
1533
- loadManifest(path);
1538
+ loadManifest(path, logFile);
1534
1539
  }
1535
1540
  catch (e) {
1536
1541
  throw manifestFileRefusal(e, path);
@@ -3500,7 +3505,7 @@ function manifestFileRefusal(e, path) {
3500
3505
  async function upManifest(file, opts) {
3501
3506
  let prepared;
3502
3507
  try {
3503
- prepared = loadManifest(resolve(file));
3508
+ prepared = loadManifest(resolve(file), opts.logFile);
3504
3509
  }
3505
3510
  catch (e) {
3506
3511
  if (opts.freshTeamBoot)
@@ -3589,9 +3594,7 @@ async function upManifest(file, opts) {
3589
3594
  assertFreshTeamBootOwnership(cotalRoot(), m.space, open ? "open" : userAuth ? "user" : "auth");
3590
3595
  await assertFreshTeamBindAvailable(server, host, m.space);
3591
3596
  }
3592
- // A manifest's agents are booted BY the manager `up -f` starts with the mesh, so `--no-manager`
3593
- // against a manifest declaring agents asks for a boot that cannot deliver its own plan. Refused
3594
- // before the dry-run print and before anything boots.
3597
+ // A manifest needs its manager to boot declared agents.
3595
3598
  if (opts.noManager && eff.agents.length)
3596
3599
  throw new FlagValueRefusal(`--no-manager cannot launch this manifest: it declares ${eff.agents.length} agent(s), and a manifest's agents are booted by its manager (which --no-manager omits)`, "drop --no-manager, or use a broker-only manifest with no agents");
3597
3600
  const effectiveNoManager = Boolean(opts.noManager);
@@ -3610,9 +3613,10 @@ async function upManifest(file, opts) {
3610
3613
  if (userAuth)
3611
3614
  await preflightUserStack(cotalRoot(), m.space, userAuth.idpUrl);
3612
3615
  checkStartStore(opts.storeDir, m.space);
3613
- // Preview and apply resolve and probe the same runtime before showing a plan or starting a broker.
3616
+ // Preview and apply only probe a runtime when starting a manager.
3614
3617
  try {
3615
- await preflightRuntime(runtime);
3618
+ if (!effectiveNoManager)
3619
+ await preflightRuntime(runtime);
3616
3620
  }
3617
3621
  catch (error) {
3618
3622
  throw new CommandFailure("refused", "DEPENDENCY_UNAVAILABLE", `the requested runtime did not pass preflight; ${opts.freshTeamBoot ? "no fresh boot intent or broker was started" : "no broker was started"}`, { target: { space: m.space, runtime }, remedy: error instanceof Error ? error.message : "inspect the selected runtime provider" });
@@ -4265,14 +4269,14 @@ function ensureRootForSpace(space) {
4265
4269
  remedy: gone ? `forget it with \`cotal space forget ${space}\`, then start it here` : `start it in its folder with \`cotal up --root ${shellWord(prepared.root)} --space ${space}\`, or \`cotal space forget ${space}\` to start it here`,
4266
4270
  });
4267
4271
  }
4268
- // What spaces does this root already host? Prefer auth material; fall back to a live MeshEntry
4269
- // whose root is this directory (open meshes have no auth dir).
4272
+ // Auth material, a locally started registration, or a preparation names what this root hosts.
4273
+ // A remote registration uses the root as a connection folder, not as a stack root.
4270
4274
  const hosted = listSpaceAccounts(authDir(root));
4271
4275
  if (hosted.includes(space))
4272
4276
  return;
4273
4277
  const existing = hosted.length
4274
4278
  ? hosted
4275
- : [loadMeshes().find((m) => m.root === root || realpathSafe(m.root) === realpathSafe(root))?.space ?? preparedSpaceAt(root)?.space].filter((s) => !!s);
4279
+ : [localMeshesForRoot(root)[0]?.space ?? preparedSpaceAt(root)?.space].filter((s) => !!s);
4276
4280
  if (existing.length === 0 || existing.includes(space))
4277
4281
  return;
4278
4282
  const names = existing.map((s) => `"${s}"`).join(", ");
@@ -4332,14 +4336,6 @@ function assertSelectionNotMoved(root, space) {
4332
4336
  remedy: `if this is that folder moved, forget it with \`cotal space forget ${current}\`, then prepare it here with \`cotal space create ${current}\` and run \`cotal up\`; to start "${space}" here, pass --space ${space}`,
4333
4337
  });
4334
4338
  }
4335
- function realpathSafe(p) {
4336
- try {
4337
- return realpathSync(p);
4338
- }
4339
- catch {
4340
- return p;
4341
- }
4342
- }
4343
4339
  /** The remedy for a hand-registered (`origin === "manual"`) space `claimSpace` refuses to touch.
4344
4340
  * Branches on whether the REGISTERED server is loopback, the one authority for that being
4345
4341
  * `isLoopbackHost` (`@cotal-ai/workspace`) — never a second opinion here.
@@ -4622,30 +4618,6 @@ async function refuseUntrustedListener(server, creds) {
4622
4618
  : /^tls:/i.test(server) ? `serve a certificate that names ${hostname}, then run \`cotal up\` again` : `pass --server tls://${hostname}:${port}, so every dial checks the certificate against ${hostname}`,
4623
4619
  });
4624
4620
  }
4625
- /** The broker's version, and whether `space`'s presence stream exists file-backed. Cotal creates
4626
- * it in memory (#1356), so only a bucket an older cotal created is file-backed; an absent one
4627
- * will be created in memory by `setupSpaceStreams`. */
4628
- async function brokerVersion(server, space, creds) {
4629
- const nc = await dialerFor(server)({ servers: server, ...standaloneConnectOpts({ creds, tls: false }) });
4630
- try {
4631
- requireBrokerFloor(nc);
4632
- const version = nc.info?.version ?? "";
4633
- let presenceFileBacked = false;
4634
- try {
4635
- const info = await (await jetstreamManager(nc)).streams.info(`KV_${presenceBucket(space)}`);
4636
- presenceFileBacked = info.config.storage === StorageType.File;
4637
- }
4638
- catch (e) {
4639
- const err = e;
4640
- if (err.api_error?.err_code !== 10059 && !/stream not found/i.test(err.message ?? ""))
4641
- throw e;
4642
- }
4643
- return { version, presenceFileBacked };
4644
- }
4645
- finally {
4646
- await drainAndClose(nc);
4647
- }
4648
- }
4649
4621
  // #1356: the presence bucket's file-backed latch is fixed in nats-server 2.14.5. Below that,
4650
4622
  // `cotal up` warns when the space's presence bucket is file-backed (never refuses: 2.14.0 meets the
4651
4623
  // SPEC §13.12 floor and is the bundled broker). A memory-backed bucket has no file store to latch.
@@ -4659,726 +4631,4 @@ function belowPresenceSafeBroker(version) {
4659
4631
  return p.minor < 14;
4660
4632
  return p.patch < 5;
4661
4633
  }
4662
- /** Wildcard binds mean "every interface", so they are NOT an address a client can be told to dial:
4663
- * the probe/registry URL stays whatever it already is (loopback by default), which the wildcard
4664
- * bind necessarily covers. */
4665
- const WILDCARD_HOSTS = new Set(["0.0.0.0", "::", "[::]"]);
4666
- /** Establish that a bind-host value IS a host, BEFORE anything brackets it, and return the
4667
- * bracketed literal a URL can hold (#1697).
4668
- *
4669
- * `--host` is the bind address; its sibling `--server` takes a URL, the registry stores and prints
4670
- * URLs, and every message in this area shows one — so an operator plausibly types the URL here
4671
- * (the manifest's `broker.host` carries the same ambiguity against `broker.servers`). Unrejected,
4672
- * the IPv6 bracketing wrapped it into `nats://[nats://127.0.0.1:4222]:4222`, which is not a URL at
4673
- * all. Nothing checked the derived string: the first code to look at it compared it with the
4674
- * space's registry record, failed for a reason unrelated to what was typed, and showed the
4675
- * operator the "registered by hand" refusal whose remedy de-registers a live mesh. Refused by name
4676
- * here instead — pointing at the URL-carrying sibling — and a value that still cannot serve as a
4677
- * URL host (a `host:port` spelling, say) is refused rather than reaching that comparison as a
4678
- * silently wrong server string. Never rewritten: a value this flag cannot use is an error, not a
4679
- * URL to derive from. */
4680
- function assertBindableHost(host, source, urlSource) {
4681
- if (/^[a-z][a-z0-9+.-]*:\/\//i.test(host)) {
4682
- console.error(c.red(`✗ ${source} ${host} looks like a URL - it takes a bind host only (an IP or hostname, no scheme); pass the broker URL with ${urlSource} instead`));
4683
- process.exit(1);
4684
- }
4685
- const literal = host.includes(":") && !host.startsWith("[") ? `[${host}]` : host;
4686
- try {
4687
- // ONE parse, both consumers served from it: `literal` builds the derived URL (a URL host needs
4688
- // the brackets), `hostname` compares against the explicit server's (the URL API strips them).
4689
- return { literal, hostname: new URL(`nats://${literal}:1`).hostname };
4690
- }
4691
- catch {
4692
- console.error(c.red(`✗ ${source} ${host} is not a valid bind host - an IP or hostname only, with no port; the port comes from ${urlSource} (or its default), never from the bind host`));
4693
- process.exit(1);
4694
- }
4695
- }
4696
- /**
4697
- * Reconcile the bind address (`--host`, manifest `broker.host`) with the broker URL the readiness
4698
- * probe, the mesh registry, and every later client use.
4699
- *
4700
- * They must name the same address. Left independent, `--host <non-loopback>` bound correctly and was
4701
- * then probed at the loopback default: the probe found nothing, timed out, and the caller SIGTERM'd
4702
- * a broker that had started perfectly, so `--host` alone could never succeed. With no explicit URL,
4703
- * derive one from the host (keeping the implicit URL's port); with both, refuse a contradicting pair rather
4704
- * than starting a broker that nothing can reach.
4705
- */
4706
- function reconcileHostAndServer(host, explicitServer, source = "--host", urlSource = "--server", implicitServer = DEFAULT_SERVER) {
4707
- const url = new URL(explicitServer ?? implicitServer);
4708
- if (WILDCARD_HOSTS.has(host))
4709
- return explicitServer ?? implicitServer;
4710
- const { literal, hostname } = assertBindableHost(host, source, urlSource);
4711
- if (!explicitServer)
4712
- return `nats://${literal}:${url.port || "4222"}`;
4713
- // NO parse on this path: `assertBindableHost` just parsed the identical literal above, so the
4714
- // mismatch check compares two parsed hostnames and can only ever print its diagnostic and exit 1
4715
- // — the "never throw a raw Invalid URL" requirement (#1697) holds by construction, not by a
4716
- // second guard that no input could reach.
4717
- if (url.hostname !== hostname) {
4718
- console.error(c.red(`✗ ${source} ${host} and ${urlSource} ${explicitServer} name different addresses - the broker would bind ${host} but be probed at ${url.hostname}. Pass one, or make them agree.`));
4719
- process.exit(1);
4720
- }
4721
- return explicitServer;
4722
- }
4723
- /** Bind the manifest's exact listener address before any team-boot write. Releasing this
4724
- * socket is not a reservation: the real broker still owns the final bind verdict. */
4725
- async function assertFreshTeamBindAvailable(server, host, space) {
4726
- const url = new URL(server), port = Number(url.port || "4222");
4727
- const displayServer = brokerAddressForDisplay(server) ?? "not displayable";
4728
- if (!Number.isSafeInteger(port) || port < 1 || port > 65535)
4729
- throw new CommandFailure("refused", "USAGE_INVALID", "the fresh team broker needs a concrete TCP port before it can check its bind address", { target: { space } });
4730
- await new Promise((resolve, reject) => {
4731
- const socket = createServer(), controller = new AbortController();
4732
- socket.unref();
4733
- let settled = false;
4734
- const finish = (error) => {
4735
- if (settled)
4736
- return;
4737
- settled = true;
4738
- clearTimeout(timer);
4739
- if (error)
4740
- reject(error);
4741
- else
4742
- resolve();
4743
- };
4744
- const timer = setTimeout(() => {
4745
- controller.abort();
4746
- finish(new CommandFailure("refused", "TARGET_UNAVAILABLE", "the local broker bind inspection did not complete within its deadline; no absence or startup eligibility was inferred", { target: { space, server: displayServer } }));
4747
- }, 1500);
4748
- socket.once("error", () => finish(new CommandFailure("refused", "TARGET_UNAVAILABLE", "the selected broker address cannot be bound as a new local listener; no existing or remote broker was adopted", { target: { space, server: displayServer }, remedy: "inspect this local bind address and any process already listening there" })));
4749
- try {
4750
- socket.listen({ port, host, signal: controller.signal }, () => {
4751
- if (settled)
4752
- return;
4753
- socket.close((error) => finish(error ? new CommandFailure("failed", "OPERATION_FAILED", "the temporary bind inspection did not confirm closure; no broker was started", { target: { space, server: displayServer } }) : undefined));
4754
- });
4755
- }
4756
- catch {
4757
- controller.abort();
4758
- finish(new CommandFailure("refused", "TARGET_UNAVAILABLE", "the selected broker bind address was rejected before startup; no other listener was chosen", { target: { space, server: displayServer } }));
4759
- }
4760
- });
4761
- }
4762
- function registeredAddressHolder(server, space) {
4763
- const key = brokerAddressKey(server);
4764
- if (key === undefined)
4765
- return undefined;
4766
- const root = canonicalRoot(cotalRoot());
4767
- return loadMeshes().find((m) => m.space !== space && canonicalRoot(m.root) !== root && brokerAddressKey(m.server) === key);
4768
- }
4769
- /** Refuse an address that a space registered for another folder keeps while its broker is stopped,
4770
- * as an occupied one is refused. Starting there would leave two registrations naming one broker:
4771
- * whichever stack runs answers for both, and the other one's `down` and reads reach it. Every
4772
- * start that names its own address asks this, a manifest's `broker.servers` included, and
4773
- * `elsewhere` names the way to move the one being started. A space this start takes the name of is
4774
- * left to the name rules. */
4775
- function refuseRegisteredAddress(server, space, elsewhere) {
4776
- const held = registeredAddressHolder(server, space);
4777
- if (!held)
4778
- return;
4779
- throw new CommandFailure("refused", "CONFLICT", `${server} is the broker address of "${held.space}", registered for ${held.root} and stopped; nothing was started`, {
4780
- target: { root: cotalRoot(), server, space, heldSpace: held.space, heldBy: held.root },
4781
- remedy: `${elsewhere}, or free that one with \`cotal space forget ${held.space}\``,
4782
- });
4783
- }
4784
- function membershipConversionRefusal(space, remedy = "stop the stack with `cotal down --yes`, then run `cotal up --recreate-membership-store`") {
4785
- return new CommandFailure("refused", "LIFECYCLE_BLOCKED", `space ${space} has a legacy File-backed membership store; it was not changed while its broker or membership services may be in use`, {
4786
- target: { space }, remedy,
4787
- });
4788
- }
4789
- async function fileMembershipStore(server, space, creds, stockOnly = false) {
4790
- const nc = await dialerFor(server)({ servers: server, ...standaloneConnectOpts({ creds, tls: false }) });
4791
- try {
4792
- requireBrokerFloor(nc);
4793
- const { config } = await (await jetstreamManager(nc)).streams.info(`KV_${membershipStoreDefinition(space).bucket}`);
4794
- if (config.storage !== StorageType.File)
4795
- return false;
4796
- if (stockOnly && (![-1, LEGACY_MEMBERSHIP_MAX_BYTES].includes(config.max_bytes) || config.max_msgs_per_subject !== 1 || ![-1, MEMBERSHIP_MAX_VALUE_SIZE].includes(config.max_msg_size)))
4797
- throw membershipConversionRefusal(space);
4798
- return true;
4799
- }
4800
- catch (error) {
4801
- if (isJetStreamMissing(error, JetStreamApiCodes.StreamNotFound))
4802
- return false;
4803
- throw error;
4804
- }
4805
- finally {
4806
- await drainAndClose(nc);
4807
- }
4808
- }
4809
- /** Create or verify space infrastructure before any services start on this broker.
4810
- * Only a fresh owned local boot may automatically replace its derived legacy membership feed. */
4811
- async function postStart(server, space, setup, seedFile, recreateIssuedStores, recreateMembershipStore, freshOwnedLocalBroker = false) {
4812
- if (recreateIssuedStores !== undefined)
4813
- await recreateIssuedStoresBeforeSetup(server, space, setup !== undefined, recreateIssuedStores);
4814
- const legacyMembership = await fileMembershipStore(server, space, setup?.creds, recreateMembershipStore !== true);
4815
- if (legacyMembership) {
4816
- const running = serviceInstances(space).filter((row) => row.record.value.definition !== STACK_DEFINITION.broker).some((row) => !["gone", "previous-boot", "foreign-pid"].includes(observeServiceProcess(row.record.value)));
4817
- if ((!freshOwnedLocalBroker && !recreateMembershipStore) || running)
4818
- throw membershipConversionRefusal(space);
4819
- }
4820
- const convertMembership = legacyMembership && (freshOwnedLocalBroker || recreateMembershipStore === true);
4821
- let recreateCreds;
4822
- if (convertMembership && setup !== undefined) {
4823
- const auth = await getSpaceAuth(workspaceSecretStore(cotalRoot()), space);
4824
- if (!auth)
4825
- throw new Error(`space "${space}" has no trust material under ${authDir(cotalRoot())}; its membership store was not touched`);
4826
- recreateCreds = await mintCreds(auth, newIdentity(), "membership-store-recreate");
4827
- }
4828
- try {
4829
- await setupSpaceStreams({
4830
- servers: server,
4831
- space,
4832
- creds: setup?.creds,
4833
- ...(convertMembership ? { recreateFileMembership: { creds: recreateCreds } } : {}),
4834
- });
4835
- }
4836
- catch (error) {
4837
- // Nothing of the stack runs yet, and the caller stops this broker again, so this is a refusal.
4838
- if (error instanceof IssuedStoreBeforeRetentionError)
4839
- throw new CommandFailure("refused", "CONFLICT", error.message, { target: { space, store: error.bucket }, remedy: `stop every other issuer and resolver of space ${space}, then add --recreate-issued-stores <backup-dir> to the \`cotal up\` that starts it` });
4840
- throw error;
4841
- }
4842
- if (convertMembership)
4843
- console.error(`Converted ${membershipStoreDefinition(space).bucket} from File to Memory; broker-sourced membership rebuilds on startup.`);
4844
- try {
4845
- if (seedFile) {
4846
- await seedChannelRegistry({ servers: server, space, creds: setup?.creds, file: seedFile });
4847
- }
4848
- // SPEC §4: `defaults.deliveryClass` MUST be written at space creation so the effective default is
4849
- // discoverable on the wire, never inferred from the `?? "durable"` resolution fallback. Auth mode
4850
- // (`setup` present ⇒ the delivery daemon is up) is local/self-hosted ⇒ `durable`; open mode has no
4851
- // daemon and is live-only ⇒ `live`. Runs after the seed so an explicit `channels.json` default wins.
4852
- // A key that does not decode is not replaced by either write.
4853
- await ensureDefaultDeliveryClass({
4854
- servers: server,
4855
- space,
4856
- creds: setup?.creds,
4857
- deliveryClass: setup ? "durable" : "live",
4858
- });
4859
- }
4860
- catch (error) {
4861
- if (!(error instanceof UndecodableRegistryEntry))
4862
- throw error;
4863
- throw new CommandFailure("refused", "CONFLICT", error.message, { target: { space }, remedy: "read the key and replace the value; the bytes were left as they are" });
4864
- }
4865
- }
4866
- /** `--recreate-issued-stores`: on the broker this boot just started, before any issuer or resolver
4867
- * of the space runs, back up and delete the space's issued-authority stores created before bounded
4868
- * retention, so the stream setup that follows creates them in the current shape. It runs the core
4869
- * step an embedder runs, on a one-shot `issued-store-recreate` credential minted from the root's
4870
- * trust; an open space uses its bare connection, as stream setup does. */
4871
- async function recreateIssuedStoresBeforeSetup(server, space, authenticated, backupDir) {
4872
- let creds;
4873
- let inboxPrefix = "_INBOX";
4874
- if (authenticated) {
4875
- const auth = await getSpaceAuth(workspaceSecretStore(cotalRoot()), space);
4876
- if (!auth)
4877
- throw new Error(`space "${space}" has no trust material under ${authDir(cotalRoot())}; its issued-authority stores were not touched`);
4878
- const identity = newIdentity();
4879
- creds = await mintCreds(auth, identity, "issued-store-recreate");
4880
- inboxPrefix = `_INBOX_${identity.id}`;
4881
- }
4882
- const nc = await dialerFor(server)({ servers: server, ...standaloneConnectOpts({ creds, tls: false }), inboxPrefix });
4883
- let removed;
4884
- try {
4885
- removed = await removeIssuedStoresBeforeRetention(nc, { space, backupDir, inboxPrefix });
4886
- }
4887
- catch (error) {
4888
- if (error instanceof IssuedStoreRecreateRefusal)
4889
- throw new CommandFailure("refused", error.reason === "nothing-to-recreate" ? "CONFLICT" : "USAGE_INVALID", error.message, { target: { space, backupDir }, remedy: error.reason === "nothing-to-recreate" ? "start the space without --recreate-issued-stores" : "name a directory that does not exist yet, inside one that does" });
4890
- throw error;
4891
- }
4892
- finally {
4893
- await drainAndClose(nc);
4894
- }
4895
- for (const store of removed)
4896
- console.log(`→ backed up ${store.stream} (${store.messages} messages) to ${store.backup}, then deleted it`);
4897
- console.log(c.dim("• the issued-authority stores are created again in the current shape; every generation issued before the upgrade is refused from now on"));
4898
- }
4899
- /** A resume or restore skips `postStart` because the preserved store already holds every canonical
4900
- * stream. A memory-backed bucket is the exception: the broker stop that preserved the store emptied
4901
- * it, stream and all (#1356 made presence memory-backed). Recreate those, and only those, from the
4902
- * same `ttlBuckets` list `setupSpaceStreams` creates them from, before any daemon opens them.
4903
- * Only an ordinary resume that just started this listener may opt into replacing a File feed. */
4904
- async function recreateMemoryBuckets(server, space, setup, ownedResume) {
4905
- const legacy = await fileMembershipStore(server, space, setup?.creds);
4906
- if (legacy) {
4907
- if (!ownedResume?.convertMembership)
4908
- throw membershipConversionRefusal(space, ownedResume && "retry this preserved resume with `cotal up --recreate-membership-store`");
4909
- const running = serviceInstances(space).filter((row) => row.record.value.definition !== STACK_DEFINITION.broker).some((row) => !["gone", "previous-boot", "foreign-pid"].includes(observeServiceProcess(row.record.value)));
4910
- if (running)
4911
- throw membershipConversionRefusal(space, "stop the remaining membership services, then retry the preserved resume with `cotal up --recreate-membership-store`");
4912
- try {
4913
- const auth = setup && await getSpaceAuth(workspaceSecretStore(cotalRoot()), space);
4914
- if (setup && !auth)
4915
- throw new Error(`space "${space}" has no trust material under ${authDir(cotalRoot())}`);
4916
- await recreateMembershipStore({
4917
- servers: server, space, provisionerCreds: setup?.creds,
4918
- recreateCreds: auth ? await mintCreds(auth, newIdentity(), "membership-store-recreate") : undefined,
4919
- });
4920
- }
4921
- catch (error) {
4922
- throw new CommandFailure("failed", "OPERATION_FAILED", `could not convert the preserved membership store: ${error.message}`, {
4923
- target: { space }, remedy: "fix the reported cause, then retry this preserved resume with `cotal up --recreate-membership-store`",
4924
- });
4925
- }
4926
- console.error(`Converted ${membershipStoreDefinition(space).bucket} from File to Memory; broker-sourced membership rebuilds on startup.`);
4927
- }
4928
- const nc = await dialerFor(server)({ servers: server, ...standaloneConnectOpts({ creds: setup?.creds, tls: false }) });
4929
- try {
4930
- requireBrokerFloor(nc);
4931
- const kvm = new Kvm(nc);
4932
- for (const [bucket, ttl, storage] of ttlBuckets(space))
4933
- if (storage === StorageType.Memory)
4934
- await kvm.create(bucket, { ttl, storage });
4935
- if (!legacy) {
4936
- const membership = membershipStoreDefinition(space);
4937
- await kvm.create(membership.bucket, membership.createOptions);
4938
- }
4939
- }
4940
- finally {
4941
- await drainAndClose(nc);
4942
- }
4943
- }
4944
- /** An adopted listener may have been bound by an `up` that stopped before {@link recreateMemoryBuckets},
4945
- * so the memory buckets the daemons open can be missing on it. An existing bucket is left as it is. */
4946
- async function recreateAdoptedMemoryBuckets(root, space, server, mode) {
4947
- if (mode === "open")
4948
- return recreateMemoryBuckets(server, space);
4949
- const auth = await getSpaceAuth(workspaceSecretStore(root), space);
4950
- if (!auth)
4951
- throw new Error(`space "${space}" has no trust material under ${authDir(root)}; cannot recreate its memory buckets on the adopted listener`);
4952
- await recreateMemoryBuckets(server, space, { creds: await mintCreds(auth, newIdentity(), "provisioner") });
4953
- }
4954
- /** `cotal space delete` removes a space's streams from a broker that keeps running. When a stack
4955
- * reuses that broker and every canonical stream of the space is gone, create them again, empty, as
4956
- * a broker start does, and return true. A broker that still holds any of them is left as it is. */
4957
- async function recreateDeletedStreams(opts) {
4958
- let setup;
4959
- if (opts.mode !== "open") {
4960
- const auth = await getSpaceAuth(workspaceSecretStore(opts.root), opts.space);
4961
- if (!auth)
4962
- throw new Error(`space "${opts.space}" has no trust material under ${authDir(opts.root)}; cannot read its streams on the running broker`);
4963
- setup = { creds: await mintCreds(auth, newIdentity(), "provisioner") };
4964
- }
4965
- if (await fileMembershipStore(opts.server, opts.space, setup?.creds))
4966
- throw membershipConversionRefusal(opts.space);
4967
- if (opts.mode === "user")
4968
- return false; // User-auth running stacks retain their existing stream lifecycle.
4969
- const nc = await dialerFor(opts.server)({ servers: opts.server, ...standaloneConnectOpts({ creds: setup?.creds, tls: false }) });
4970
- let held = false;
4971
- try {
4972
- requireBrokerFloor(nc);
4973
- const jsm = await jetstreamManager(nc);
4974
- for (const name of spaceDeletionStreams(opts.space)) {
4975
- try {
4976
- await jsm.streams.info(name);
4977
- held = true;
4978
- break;
4979
- }
4980
- catch (error) {
4981
- if (!isJetStreamMissing(error, JetStreamApiCodes.StreamNotFound))
4982
- throw error;
4983
- }
4984
- }
4985
- }
4986
- finally {
4987
- await drainAndClose(nc);
4988
- }
4989
- if (held)
4990
- return false;
4991
- await postStart(opts.server, opts.space, setup, opts.seed ?? loadChannelsFile(opts.channels));
4992
- return true;
4993
- }
4994
- /**
4995
- * Render and write the config for an OPEN (no-auth) broker, returning its path. It names `space`,
4996
- * because an open root holds no account that would ({@link namedOpenConfig}).
4997
- *
4998
- * The `authSetup` sibling for the no-auth mode. Open mode previously launched nats-server from
4999
- * bare CLI flags and so never passed through any renderer — meaning the REQUIRED transport union
5000
- * on the config renderers covered the auth path only, and a `--tls-cert`/`--tls-key` pair given to
5001
- * an open-mode `up` would have been accepted while the broker came up in cleartext. Routing open
5002
- * mode through a renderer is what makes the union total: there is now no route to a listener that
5003
- * does not state its transport.
5004
- */
5005
- function writeOpenBrokerConf(storeDir, space, opts) {
5006
- const confPath = cotalPath("server-open.conf");
5007
- writeBrokerConfig(confPath, namedOpenConfig(openServerConfig({ brokerVersion: opts.brokerVersion, port: opts.port, host: opts.host, storeDir: configuredStoreDir(cotalRoot(), storeDir), maxFileStore: opts.maxFileStore, maxPayload: opts.maxPayload, logFile: opts.logFile, logfileSizeLimit: opts.logfileSizeLimit, logfileMaxNum: opts.logfileMaxNum, transport: opts.transport }), space));
5008
- return confPath;
5009
- }
5010
- /** Write a broker configuration that `up` renders again on every start. Something other than this
5011
- * account's own regular file at its path, such as a symlink or a folder, is refused by name and
5012
- * left as it is. Moving it aside loses nothing, because the next `up` writes the file again.
5013
- * Other write failures name the path and errno, and remain known failures before a launch. */
5014
- function writeBrokerConfig(path, text) {
5015
- try {
5016
- writeSecretFile(path, text);
5017
- }
5018
- catch (error) {
5019
- const code = error.code;
5020
- // A nonblocking write-only open can fail ENXIO for non-regular entries before the secure
5021
- // writer can inspect its descriptor. An absent or regular entry still means a write failure.
5022
- const entry = code === "EPERM" || code === "EISDIR" || code === "EACCES" || code === "ENXIO" ? lstatSync(path, { throwIfNoEntry: false }) : undefined;
5023
- if (code !== "EPERM" && code !== "EISDIR" && code !== "EACCES" && (!entry || entry.isFile()))
5024
- throw new CommandFailure("failed", "OPERATION_FAILED", `up could not write the broker configuration ${path}${code ? ` (${code})` : ""}; nothing was started`, {
5025
- target: { path }, remedy: `correct the write failure at ${path}, then run \`cotal up\` again, which writes the configuration again`,
5026
- });
5027
- const what = entry?.isSymbolicLink() ? "is a symlink" : entry?.isDirectory() ? "is a folder" : code === "EACCES" ? "cannot be written by this account" : "is not a regular file this account owns";
5028
- throw new CommandFailure("refused", "PERMISSION_DENIED", `the broker configuration ${path} ${what}, so up cannot write it; it was left as it is and nothing was started`, {
5029
- target: { path }, remedy: `move it aside, as mv ${shellWord(path)} ${shellWord(`${path}.old`)} does, then run \`cotal up\` again, which writes it from the space's trust`,
5030
- });
5031
- }
5032
- }
5033
- /** The refusal for a trust record of the space that this account cannot read. It holds the space's
5034
- * keys, so the step makes it readable again and never removes it. Any other error as it is. */
5035
- function unreadableTrust(error) {
5036
- const { code, path } = error;
5037
- if (code !== "EACCES" && code !== "EPERM" || typeof path !== "string")
5038
- return error;
5039
- return new CommandFailure("refused", "PERMISSION_DENIED", `the space's trust record ${path} cannot be read by this account (${code}); nothing was started`, {
5040
- target: { path }, remedy: `make it readable by you again, as chmod 600 ${shellWord(path)} does, then run \`cotal up\` again; it holds the space's keys, so keep it`,
5041
- });
5042
- }
5043
- /** Ensure the space's trust material exists and render a server config. The caller can mint
5044
- * the setup credential after connector reconciliation. The account signing key
5045
- * in `.cotal/auth` is what `cotal mint` and the manager later use to issue per-agent creds.
5046
- *
5047
- * USER MODE (`user` set): additionally run the registered auth provider's `prepareServer` over the
5048
- * SPACE-SCOPED state dir (`.cotal/auth/<space>/` — the multi-space-ready layout; nothing user-auth
5049
- * lives flat) and preload its extra account(s) into the broker config. The inverse is fail-closed:
5050
- * a space whose user-auth state exists MUST keep being started with --user-auth — regenerating the
5051
- * config without the callout account would silently break every sentinel connect.
5052
- *
5053
- * `rotateSys` (`cotal up --rotate-sys`) is the class-3 renewal for an EXISTING space: rotate the
5054
- * system account, re-mint `membership-observer.creds` + `connection-evictor.creds` against the
5055
- * successor, and render the config from the ROTATED record so the broker this `up` starts is the one
5056
- * that trusts them. It belongs here because this is the single site that both owns the trust record
5057
- * and renders `server.conf`; anywhere else would publish creds the live broker cannot honor. */
5058
- async function authSetup(storeDir, server, space, host = "127.0.0.1", user,
5059
- // NON-OPTIONAL, and it used to default to `{ kind: "plaintext" }`. That default was the hole: the
5060
- // manifest path called this with five arguments and silently got a cleartext listener while the
5061
- // operator's `--tls-cert` sat validated and unused. A default here cannot be right, because the
5062
- // safe value and the common value are different values — every caller knows its transport, and
5063
- // the one that does not is the one that must not compile.
5064
- transport, rotateSys = false, maxFileStore, quietBoot = false,
5065
- // `--auth-timeout`, `--max-payload` and `--account-resolver`. Each absent value falls back to the one the root's broker
5066
- // policy records, so a bare `up` renders what an earlier `up` set. They arrive as one object
5067
- // rather than two trailing optional numbers: a transposed pair of those renders a wrong
5068
- // configuration in silence.
5069
- requested = {}) {
5070
- const dir = authDir(cotalRoot()); // the broker config (server.conf) still lands under the FS auth dir
5071
- const store = workspaceSecretStore(cotalRoot());
5072
- let auth = await getSpaceAuth(store, space).catch((error) => { throw unreadableTrust(error); });
5073
- if (!auth) {
5074
- auth = await createSpaceAuth(space);
5075
- // The trust record is written last. Until it exists the next up treats the space as fresh and
5076
- // mints all of this again, so an up stopped partway never leaves a space without its $SYS creds.
5077
- await provisionMembershipCreds(auth, cotalRoot(), space); // the observer is minted while the $SYS seed is in memory (fresh-space only)
5078
- // Smoke only: hold a new space with part of its material written, so a signal can land there.
5079
- if (process.env.COTAL_SMOKE_HOLD_IN_SPACE_AUTH === "1")
5080
- await new Promise((done) => setTimeout(done, 60_000));
5081
- await retainSystemSigningSeed(store, auth); // the host keeps the seed itself, beside the record, for own-broker caller issuance
5082
- await putSpaceAuth(store, auth); // strips the $SYS seed at rest
5083
- // A fresh space's $SYS material was just minted from the seed this branch holds in memory, so
5084
- // the ASK is already satisfied, so say so rather than rotating a one-second-old account, and never
5085
- // report a rotation that did not happen.
5086
- if (rotateSys)
5087
- console.log(c.dim("• --rotate-sys: this space is new, so its $SYS creds were just minted - nothing to rotate"));
5088
- }
5089
- else if (rotateSys) {
5090
- // Third and last of the stopped-broker checks, at the one point every rotation path converges on.
5091
- // The other two live in `up`'s reachable-listener branch: this root's recorded mesh at the
5092
- // requested address, and any UNIDENTIFIED listener there (which refuses rather than free-porting
5093
- // around a broker that may be serving this root's own server.conf and store). This one reads the
5094
- // root's ownership records for a broker at an address nobody probed. It reports what those
5095
- // records say, not what the process table says (see its own comment for the residual), and fails
5096
- // CLOSED, so an ambiguous record refuses exactly like a live one.
5097
- await assertRootBrokerStopped(cotalRoot());
5098
- // Fails loud: a caller that swallowed this would boot the broker on the RETIRED system account
5099
- // while `doctor auth` reported the rotation as done.
5100
- const rot = await rotateSystemCreds(cotalRoot(), space);
5101
- auth = rot.auth; // the config below MUST be rendered from the successor, never the pre-rotation copy
5102
- console.log(c.green(`✓ rotated the system account for "${space}"`) +
5103
- c.dim(` (generation ${rot.gen}) - re-minted ${SYSTEM_CREDS_FILES.join(" + ")}${rot.expiresAt ? `, valid to ${new Date(rot.expiresAt * 1000).toISOString().slice(0, 10)}` : ""}`));
5104
- // Say exactly what is true. The retirement is CONFIG-LOAD-BOUND: an old cred dies against any
5105
- // broker that loads the successor config, which is every broker started from this root from here
5106
- // on, but a stale nats-server still holding the pre-rotation config in memory would keep
5107
- // honoring it, so "now dead" without that qualifier oversells the guarantee.
5108
- console.log(c.dim(" the data account, every agent cred and the JetStream store are untouched. The OLD $SYS creds are refused by any broker that loads this config; a stale broker still running the previous config would still honor them, so stop those first."));
5109
- // A full backup binds to the trust chain it was taken against: `rootChainCommitment` hashes the
5110
- // operator JWT and the system account, both of which just changed, so `cotal up --restore`
5111
- // refuses every full artifact taken before this moment. That is correct (it is a different trust
5112
- // root), but it is only obvious to someone who has read the fingerprint code, and rotation is
5113
- // now a routine 30-day act rather than a once-per-space event. Say it at the moment it becomes
5114
- // true, not in a doc the operator reads after the restore has already failed.
5115
- console.log(c.dim(" NOTE: full backups taken before this rotation can no longer be restored (they are bound to the retired trust chain) - take a fresh `cotal backup` once the mesh is up."));
5116
- }
5117
- // The DATA half of the membership bundle, on EVERY path — see healMembershipDataCreds.
5118
- await healMembershipDataCreds(auth, cotalRoot(), space, quietBoot);
5119
- await provisionWebCreds(auth, cotalRoot(), space, quietBoot);
5120
- // The $SYS creds must be signed by the system account THIS boot is about to put in `server.conf`.
5121
- // A rotation that committed the trust record and then died leaves them stale, unexpired, and
5122
- // broker-dead and, crash-before-either-write, stale in a way that no comparison between the two
5123
- // FILES can see (they agree with each other; they just disagree with the record). This is the one
5124
- // place holding both, on the one path that renders the config, so it is where the split is caught.
5125
- //
5126
- // REFUSE, do not warn. A warning is what the `--detach` path turns into an unread log line under a
5127
- // green "✓ running in the background", which is the false success this whole change exists to
5128
- // remove. And what stays broken is not only the display feed: live connection EVICTION rides the
5129
- // same pair, so booting here would silently downgrade revocation to deny-new for the life of the
5130
- // mesh. The repo's posture is to throw rather than degrade, and the recovery is one command that
5131
- // this message names.
5132
- const stale = staleSystemCreds(cotalRoot(), auth.sys.pub, space);
5133
- if (stale.length)
5134
- throw new Error(`${stale.map((x) => `${x.file} (signed by ${x.iss ? `${x.iss.slice(0, 12)}…` : "an unreadable issuer"})`).join(", ")} ` +
5135
- `${stale.length === 1 ? "is" : "are"} not signed by this space's system account (${auth.sys.pub.slice(0, 12)}…) - ` +
5136
- "an interrupted rotation left the $SYS creds behind the trust record, so the broker would deny them and live eviction + the membership feed would stay down. " +
5137
- "Re-run the rotation to land a complete generation: `cotal up --rotate-sys`");
5138
- const stateDir = userAuthStateDir(cotalRoot(), space); // the provider's space-scoped state dir
5139
- if (!user && hasUserAuthState(cotalRoot(), space)) {
5140
- throw new Error(`space "${space}" has user auth enabled (state under ${stateDir}) - start it with \`cotal up --user-auth\`, or remove that directory deliberately to disable user auth (existing logins/grants die with it)`);
5141
- }
5142
- let prepared;
5143
- if (user) {
5144
- // Registry composition: the provider came from the composition root (bin/cotal.ts imports
5145
- // @cotal-ai/auth); this package never imports it. No provider ⇒ resolveAuthProvider throws the
5146
- // exact fix. The narrow input is a capability boundary: operator seed (signs the provider's
5147
- // account once) + the data account's pub/signingSeed (projected for the service's minting duty).
5148
- try {
5149
- prepared = await resolveAuthProvider().prepareServer({
5150
- space,
5151
- operatorSeed: auth.operator.seed,
5152
- account: { pub: auth.account.pub, signingSeed: auth.account.signingSeed },
5153
- store: workspaceSecretStore(cotalRoot()),
5154
- dir: stateDir,
5155
- idpUrl: user.idpUrl,
5156
- });
5157
- }
5158
- catch (e) {
5159
- throw e instanceof Error ? e : new Error(String(e));
5160
- }
5161
- }
5162
- const port = Number(new URL(server).port) || 4222;
5163
- // A reused controller manager advertises its launch-time WebSocket port.
5164
- const wsPort = requested.wsPort ?? await freePort(host);
5165
- const confPath = resolve(dir, "server.conf");
5166
- // EVERY tenant of this root, not just the one being booted: `resolver_preload` is a whole-broker
5167
- // map, so a config rendered from one space evicts the rest silently. `auth` leads the list because
5168
- // this function's copy can be fresher than the disk (a space created above, or one whose trust
5169
- // record `--rotate-sys` just replaced). Refuses on an unreadable record rather than dropping it.
5170
- const spaces = preloadSpaceAccounts(dir, auth);
5171
- const enabled = userAuthSpacesOnDisk(dir);
5172
- for (const enabledSpace of enabled) {
5173
- if (!spaces.some((s) => s.space === enabledSpace))
5174
- throw new Error(`space "${enabledSpace}" has user auth enabled but no data account record - refusing to render an incomplete broker resolver`);
5175
- }
5176
- const extraAccounts = [];
5177
- for (const enabledSpace of enabled) {
5178
- const accounts = enabledSpace === space && prepared
5179
- ? prepared.extraAccounts
5180
- : await resolveAuthProvider().preloadAccounts({ store, space: enabledSpace });
5181
- extraAccounts.push(...accounts);
5182
- }
5183
- // Owner-private regardless of umask, as `writeOpenBrokerConf` writes the open configuration: the
5184
- // broker preset refuses a configuration that other local users can write.
5185
- const recorded = readBrokerPolicy(cotalRoot());
5186
- const authTimeout = requested.authTimeout ?? recorded?.authTimeout;
5187
- const maxPayload = requested.maxPayload ?? recorded?.maxPayload;
5188
- if (requested.manager === true)
5189
- assertManagerPayload(maxPayload);
5190
- const resolverChoice = requested.accountResolver ?? recorded?.accountResolver ?? "memory";
5191
- const accountResolver = brokerAccountResolver(cotalRoot(), resolverChoice === "full" ? "full" : undefined);
5192
- // Owner-private like the auth dir: nats-server writes each pushed claim here.
5193
- if (accountResolver.kind === "full")
5194
- mkSecretDir(accountResolver.directory);
5195
- const brokerBinary = await resolveNatsServer();
5196
- if (!brokerBinary.version)
5197
- throw unreadVersion(brokerBinary);
5198
- const render = (ws) => writeBrokerConfig(confPath, serverConfig(auth, spaces, { brokerVersion: brokerBinary.version, transport, port, storeDir: configuredStoreDir(cotalRoot(), storeDir), maxFileStore, authTimeout, maxPayload, accountResolver, logFile: requested.logFile, logfileSizeLimit: requested.logfileSizeLimit, logfileMaxNum: requested.logfileMaxNum, host, wsPort: ws, wsHost: host, extraAccounts }));
5199
- render(wsPort);
5200
- // The chosen port is free now, but nothing holds it until the broker binds it. When another process
5201
- // takes it first, the broker exits before readiness, and a controller stack start renders this
5202
- // configuration again on a newly chosen port.
5203
- const moveWebsocketPort = async () => { const moved = await freePort(host); render(moved); return moved; };
5204
- // Connector reconciliation can outlast the provisioner's lifetime. Mint only when boot needs it
5205
- // to probe the listener, create streams and buckets, or seed the channel registry.
5206
- const mintProvisioner = () => mintCreds(auth, newIdentity(), "provisioner");
5207
- return { brokerBinary, confPath, mintProvisioner, wsPort, moveWebsocketPort, ...(prepared ? { prepared, stateDir } : {}), ...(authTimeout !== undefined ? { authTimeout } : {}), ...(maxPayload !== undefined ? { maxPayload } : {}), accountResolver: resolverChoice };
5208
- }
5209
- /**
5210
- * Refuse the rotation if this root's own bookkeeping still shows a broker running. This is a
5211
- * BEST-EFFORT check over Cotal-managed ownership records, NOT a proof that no process is serving this
5212
- * root, and the difference matters: a survivor keeps honoring the retired account from memory, and a
5213
- * second broker on the successor opens that survivor's JetStream store underneath it.
5214
- *
5215
- * Two records, because either alone has a blind spot. The PID FILE catches a broker this root started
5216
- * whose registry row was lost. The REGISTRY sweep catches one recorded for this root at some OTHER
5217
- * address, which no probe of the requested URL would reach. Both fail CLOSED: an unreadable or
5218
- * malformed pid file refuses exactly like a live one, since "cannot tell" and "still running" have
5219
- * the same consequence.
5220
- *
5221
- * WHAT IT CANNOT SEE: both records are mutable, and neither is written by a broker started outside
5222
- * `cotal up`. Delete both while the process lives, or run
5223
- * `nats-server -c <root>/.cotal/auth/server.conf` by hand, and this returns success having probed
5224
- * nothing. The requested address is covered separately (an unidentified listener there refuses the
5225
- * rotation rather than moving to a free port), which leaves a hand-started broker on a DIFFERENT port
5226
- * as the honest residual. Closing that needs something a survivor holds and cannot delete, an
5227
- * exclusive store lock, which does not exist today; until it does, do not run `nats-server` against
5228
- * this root's config outside `cotal up`.
5229
- *
5230
- * Not a general `up` guard: an ordinary boot adopting or replacing a listener is a supported flow with
5231
- * its own claim machinery. This is specifically the precondition for retiring an authority.
5232
- */
5233
- async function assertRootBrokerStopped(root) {
5234
- const pidPath = join(root, ".cotal", NATS_PIDFILE);
5235
- if (existsSync(pidPath)) {
5236
- let raw;
5237
- try {
5238
- raw = readFileSync(pidPath, "utf8").trim();
5239
- }
5240
- catch (e) {
5241
- throw new Error(`--rotate-sys: ${pidPath} exists but cannot be read (${e.message}) - refusing to rotate while a broker for this root may still be running; \`cotal down\` first`);
5242
- }
5243
- const pid = Number(raw);
5244
- if (!Number.isInteger(pid) || pid <= 0)
5245
- throw new Error(`--rotate-sys: ${pidPath} does not hold a pid (${JSON.stringify(raw)}) - refusing to rotate while a broker for this root may still be running; \`cotal down\` first`);
5246
- let live;
5247
- try {
5248
- process.kill(pid, 0); // signal 0 is a liveness probe, it signals nothing
5249
- live = true;
5250
- }
5251
- catch (e) {
5252
- // EPERM means the process EXISTS and is not ours to signal, i.e. alive for this purpose.
5253
- live = e.code === "EPERM";
5254
- }
5255
- if (live)
5256
- throw new Error(`--rotate-sys: this root's broker is still running (pid ${pid}) - it would keep serving the retired system account, and a second broker would share its JetStream store. Stop it first: \`cotal down\``);
5257
- }
5258
- // A broker recorded for this root at ANY address, still answering. The rotate refusal earlier in
5259
- // `up` only sees the URL this invocation asked for; this sees the ones it did not.
5260
- for (const m of meshesForRoot(root)) {
5261
- if (await isReachable(m.server))
5262
- throw new Error(`--rotate-sys: mesh "${m.space}" for this root is still reachable at ${m.server} - stop it first (\`cotal down\`), then rotate`);
5263
- }
5264
- }
5265
- /** Provision the DATA-account half of the membership bundle, on EVERY `up` rather than only a fresh
5266
- * space. Idempotent: it writes only what is absent and is silent when both are present.
5267
- *
5268
- * WHY THIS IS SEPARATE FROM {@link provisionMembershipCreds}. That function mints the whole bundle
5269
- * in the fresh-space branch because the `$SYS` signing seed exists only there and is never
5270
- * persisted — true of `membership-observer.creds` and `connection-evictor.creds`. The delivery daemon
5271
- * mints a missing evictor itself on a single-space root that retained its system-account signing
5272
- * seed, so that one no longer needs a rotation; a root without the seed still needs one. It is NOT
5273
- * true of the other two.
5274
- * `membership-rw.creds` is signed by the DATA account, whose signing seed IS persisted, and
5275
- * `membership.json` is just that account's public id. Neither needs the `$SYS` window, so binding
5276
- * them to it left every space provisioned before the feature permanently without the feed.
5277
- *
5278
- * That gap was not theoretical. A space with a complete `$SYS` pair, missing only the rw cred,
5279
- * reported `the membership bundle is incomplete here (missing membership-rw.creds)` on every
5280
- * delivery-daemon start and served a traffic-only graph, and the documented remedy did not work:
5281
- * `--rotate-sys` re-mints the `$SYS` pair and never calls the provisioner, so it wrote neither the
5282
- * rw cred nor the account id. `mintMembershipObserverCreds` even names that rotation as the fix in
5283
- * its own error text — advice that could not succeed. Healing here fixes both spellings at once:
5284
- * the ordinary `up` repairs the data half with no rotation at all, and a rotation now repairs it
5285
- * too, because this runs after both branches converge. */
5286
- async function healMembershipDataCreds(auth, root, space, quietBoot = false) {
5287
- try {
5288
- const store = workspaceSecretStore(root);
5289
- // THE RESOLVERS, not the bare kinds (P7 §2 rule 1). Both reads below are absent-means-MINT, which
5290
- // is precisely why the location must be resolved through the choke point: a canonical read on a
5291
- // root whose material is still flat answers "absent" and mints a SECOND live cred beside the one
5292
- // the running daemons hold. `up` is a workstation composition by construction, so the resolver
5293
- // gets the FS arm and moves the material on this first touch.
5294
- const composition = { injected: false, root };
5295
- const rwKey = membershipRwCredsKey(space, composition);
5296
- const wrote = [];
5297
- const rw = await store.get(rwKey);
5298
- if (rw === undefined) {
5299
- await store.put(rwKey, await mintCreds(auth, newIdentity(), "membership-rw"));
5300
- wrote.push(MEMBERSHIP_RW_CREDS_KIND); // the KIND is what an operator reads, never the segmented key
5301
- }
5302
- else if (credsProblem(rw) !== undefined && !quietBoot)
5303
- console.error(c.yellow(`! ${unparsableDaemonCredsNotice([MEMBERSHIP_RW_CREDS_KIND])}`));
5304
- const configPath = membershipConfigPath(root, space);
5305
- if (!existsSync(configPath)) {
5306
- mkSecretDir(dirname(configPath)); // harden the per-space dir before the file lands, as the fresh path does
5307
- writeSecretFile(configPath, JSON.stringify({ accountId: auth.account.pub }));
5308
- wrote.push(MEMBERSHIP_CONFIG_KIND);
5309
- }
5310
- if (wrote.length && !quietBoot)
5311
- console.log(c.dim(`• membership: provisioned ${wrote.join(" + ")} - the data-account half needs no system-account rotation`));
5312
- }
5313
- catch (e) {
5314
- // Best-effort, exactly like the fresh-space provisioner: a failure here leaves the graph on
5315
- // traffic-only and leaves delivery untouched. It must never keep the mesh from starting.
5316
- console.error(c.dim(`• broker-sourced membership not repaired: ${e.message}`));
5317
- }
5318
- }
5319
- /** The web dashboard's read-only cred, on EVERY `up` of a static space: `cotal service start web`
5320
- * defaults its `--creds` to this file. Idempotent and absent-means-mint, through the resolver as
5321
- * {@link healMembershipDataCreds} is. It is the `observer` profile, minted without an expiry, as the
5322
- * `cotal auth mint --profile observer` recipe this replaces was: the dashboard reads the file once at
5323
- * start and holds its connection, and no renewal owner reloads it. Best-effort for the same reason as
5324
- * the membership heal: a failure here must never keep the mesh from starting. */
5325
- async function provisionWebCreds(auth, root, space, quietBoot = false) {
5326
- try {
5327
- const store = workspaceSecretStore(root);
5328
- const key = webCredsKey(space, { injected: false, root });
5329
- if ((await store.get(key)) !== undefined)
5330
- return;
5331
- await store.put(key, await mintCreds(auth, newIdentity(), "observer"));
5332
- if (!quietBoot)
5333
- for (const line of hang("• ", `web: provisioned ${WEB_CREDS_KIND} - the dashboard's read-only credential, the \`service start web\` default`, terminalWidth(process.stdout)))
5334
- console.log(c.dim(line));
5335
- }
5336
- catch (e) {
5337
- console.error(c.dim(`• web dashboard credential not provisioned: ${e.message}`));
5338
- }
5339
- }
5340
- /** Mint the two scoped creds the delivery daemon's membership feed loads (broker-sourced graph
5341
- * membership), at the FRESH `cotal up` while the in-memory `$SYS` signing seed still exists:
5342
- * - `membership-observer.creds` — SYSTEM-account CONNZ reader (the only window it is minted here:
5343
- * the trust record carries no `$SYS` seed, and the retained custody record serves caller issuance only).
5344
- * - `membership-rw.creds` — DATA-account members-read + feed-write.
5345
- * - `membership.json` — the DATA account id (the CONNZ/event subjects pin it; non-secret, but kept
5346
- * 0600 alongside the creds).
5347
- * All 0600. Best-effort: a failure logs and leaves the feed disabled (the graph degrades to traffic-
5348
- * only, delivery is untouched). Runs only on a FRESH space (the `if (!auth)` branch); a normal down/up
5349
- * keeps `.cotal/auth` + these creds and reuses them. A space provisioned before this feature has no
5350
- * in-memory `$SYS` seed, so it gains membership only when its auth is regenerated (a fresh `.cotal/auth`)
5351
- * — a documented migration property, not a silent no-op.
5352
- * Coupling: `cotal clean all` deletes this identity-derived set (removeLocalState in clean.ts) —
5353
- * a cred added here must be added to that removal list too. `membership-rw.creds` is a MIGRATED kind:
5354
- * its write/read/delete all go through the {@link SecretStore} seam (here, the feed reader, and clean),
5355
- * so the renewal owner can re-sign it into a hosted store. The observer / evictor / config stay on the
5356
- * raw FS (static $SYS creds + non-secret config, not renewable kinds). */
5357
- async function provisionMembershipCreds(auth, root, space) {
5358
- try {
5359
- const observer = await mintMembershipObserverCreds(auth, newIdentity());
5360
- const rw = await mintCreds(auth, newIdentity(), "membership-rw");
5361
- // D5 slice 4: the KICK-only connection-evictor cred — same mint-only-at-fresh-`up` window as
5362
- // the observer ($SYS seed in memory here). The delivery daemon pairs it with the observer to
5363
- // close a revoked/removed principal's live connections. A space without it degrades to
5364
- // deny-new-only (durable reauth) — surfaced loudly by the removal path, never silent.
5365
- const evictor = await mintConnectionEvictorCreds(auth, newIdentity());
5366
- // All four land through the per-kind resolvers (P7 §2 rule 1), and all four through the store's
5367
- // `put`, which is the same `mkSecretDir` + atomic write the raw `writeSecretFile` did — the
5368
- // difference being that it hardens the PER-SPACE dir the material now lives in rather than
5369
- // `.cotal/` itself. This is the fresh-space branch, so nothing is there to migrate; it calls the
5370
- // resolvers anyway because a kind with two write paths is a kind that grows two layouts.
5371
- const composition = { injected: false, root };
5372
- const store = workspaceSecretStore(root);
5373
- await store.put(membershipObserverCredsKey(space, composition), observer);
5374
- await store.put(membershipRwCredsKey(space, composition), rw);
5375
- await store.put(connectionEvictorCredsKey(space, composition), evictor);
5376
- const configPath = membershipConfigPath(root, space);
5377
- mkSecretDir(dirname(configPath));
5378
- writeSecretFile(configPath, JSON.stringify({ accountId: auth.account.pub }));
5379
- }
5380
- catch (e) {
5381
- console.error(c.dim(`• broker-sourced membership not provisioned: ${e.message}`));
5382
- }
5383
- }
5384
4634
  //# sourceMappingURL=up.js.map