@cotal-ai/cli 0.174.0 → 0.174.2

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.
@@ -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";
@@ -61,7 +61,7 @@ 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";
@@ -73,6 +73,7 @@ import { freePort, freshStackServer, retryStackAddress, serverWithFreePort } fro
73
73
  import { askManager } from "@cotal-ai/workspace/control";
74
74
  import { cliControl } from "../lib/control.js";
75
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. */
@@ -4997,343 +4998,6 @@ async function recreateDeletedStreams(opts) {
4997
4998
  await postStart(opts.server, opts.space, setup, opts.seed ?? loadChannelsFile(opts.channels));
4998
4999
  return true;
4999
5000
  }
5000
- function parseMaxFileStore(raw) {
5001
- return parsePositiveIntegerFlag("--max-file-store", raw);
5002
- }
5003
- /** `--auth-timeout`, whole seconds from 1 to 60. nats-server warns above 60 that the value is
5004
- * probably a mistake, and a stalled callout holds every connect that long. */
5005
- function parseAuthTimeout(raw) {
5006
- const seconds = parsePositiveIntegerFlag("--auth-timeout", raw);
5007
- if (seconds !== undefined && seconds > MAX_AUTH_TIMEOUT_SECONDS)
5008
- 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` });
5009
- return seconds;
5010
- }
5011
- const MAX_AUTH_TIMEOUT_SECONDS = 60;
5012
- /** `--max-payload`, a positive whole number of bytes. nats-server refuses to start above 64 MiB, so
5013
- * the refusal names that bound rather than letting the broker exit on its own configuration. */
5014
- function parseMaxPayload(raw) {
5015
- const bytes = parsePositiveIntegerFlag("--max-payload", raw);
5016
- if (bytes !== undefined && bytes > MAX_BROKER_PAYLOAD_BYTES)
5017
- 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` });
5018
- return bytes;
5019
- }
5020
- const MAX_BROKER_PAYLOAD_BYTES = 64 * 1024 * 1024;
5021
- /** `--account-resolver`, memory or full. */
5022
- function parseAccountResolver(raw) {
5023
- if (raw === undefined || raw === "memory" || raw === "full")
5024
- return raw;
5025
- 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" });
5026
- }
5027
- /** The auth-service daemon argv that gives the callout the broker's timeout as its deadline. Built
5028
- * only from the value the broker configuration rendered, so the two never differ. */
5029
- function authTimeoutArgs(seconds) {
5030
- return seconds === undefined ? [] : ["--auth-timeout", String(seconds)];
5031
- }
5032
- /** Load the declarative channels-config file to seed the registry. An explicit `--channels`
5033
- * path that's missing is a hard error; the default `.cotal/channels.json` is optional (absent
5034
- * ⇒ nothing to seed). */
5035
- function loadChannelsFile(explicit) {
5036
- if (explicit)
5037
- return readChannelsFile(resolve(explicit));
5038
- return readDefaultChannelsFile(cotalRoot());
5039
- }
5040
- /** Refuse `up --space` of a space this machine started from another folder while its broker answers,
5041
- * naming that folder: the stack there is the one to use or stop. */
5042
- async function refuseRunningElsewhere(space, root) {
5043
- const owner = findMesh(space);
5044
- if (!owner || owner.origin === "manual" || owner.origin === "catalog" || !isAbsolute(owner.root) || canonicalRoot(owner.root) === canonicalRoot(root) || !(await isReachable(owner.server)))
5045
- return;
5046
- let controller = false;
5047
- try {
5048
- controller = readStackJournal(owner.root)?.journal.space === space;
5049
- }
5050
- catch { /* named with the legacy stop */ }
5051
- const rootExists = existsSync(owner.root);
5052
- const moved = !controller && !retainedLegacyBroker(owner.root) && recordsElsewhereError(root)?.details.stackSpace === space;
5053
- const remedy = moved
5054
- ? `${rootExists ? `move what is now at ${owner.root} aside, then ` : ""}move this folder back to ${owner.root} and run \`cotal down --yes\` there`
5055
- : !rootExists
5056
- ? `restore the original project at ${owner.root}, then run \`cotal down --yes\` there`
5057
- : `use it from here with --space ${space}, or stop it with \`cotal down${controller ? " --yes" : ""}\` in ${owner.root}`;
5058
- 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 });
5059
- }
5060
- /** Refuses a bare `up` in a folder holding the records of a space this machine registers for another
5061
- * folder, as a copy, a moved folder and one whose name a later `up` took over keep them. The retained
5062
- * launcher writes no stack journal, so this is that launcher's form of the journal's refusal: it
5063
- * names that folder and the step reads there name. When that folder is gone and its broker does not
5064
- * answer, it also names the `--space` that takes the name over to run the stack from this folder. */
5065
- async function refuseRecordsElsewhere(root) {
5066
- const records = recordsElsewhereError(root)?.details;
5067
- if (!records?.lastRun || records.stackSpace === undefined || records.recordedRoot === undefined || records.stackRemedy === undefined)
5068
- return;
5069
- const space = records.stackSpace;
5070
- const takeover = !existsSync(records.recordedRoot) && !(await isReachable(findMesh(space)?.server ?? records.server ?? DEFAULT_SERVER));
5071
- 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`, {
5072
- target: { root, space, recordedRoot: records.recordedRoot },
5073
- remedy: takeover ? `${records.stackRemedy}; or, to run it from this folder, take the name over with \`cotal up --space ${space}\`` : records.stackRemedy,
5074
- });
5075
- }
5076
- /**
5077
- * Turn the `--tls-cert`/`--tls-key` pair into a validated {@link BrokerTransport}, or `plaintext`
5078
- * when neither was given.
5079
- *
5080
- * REFUSES BEFORE LAUNCH, never after. Everything it rejects would otherwise become a running broker
5081
- * in some wrong state, and the two failure modes are not symmetrical: a broker that will not start
5082
- * is an operator reading an error, while a broker that starts wrong is an operator believing they
5083
- * have TLS. So the validation is deliberately ours and deliberately early.
5084
- *
5085
- * `validateTlsMaterial` does the substantive checks — readability, private-key mode, PEM pair
5086
- * match, validity window, dial-host SAN — because nats-server's are not sufficient. Missing,
5087
- * unreadable and mismatched pairs do stop it before it opens a listener, but an EXPIRED certificate
5088
- * does not: it reports the config valid, starts, logs "Server is ready" and "TLS required", and
5089
- * only the client then fails. An expired cert must never yield "mesh up".
5090
- *
5091
- * @param dialHost the hostname clients will verify against, which is NOT the bind host — a broker
5092
- * may bind `0.0.0.0` while clients dial `broker.example`.
5093
- */
5094
- function resolveTransport(values, dialHost, root,
5095
- /** `persist` defaults false (commit-after-apply). `quiet` suppresses serving/inheriting lines
5096
- * until the caller announces after a successful apply. */
5097
- opts = {}) {
5098
- const certFile = values["tls-cert"], keyFile = values["tls-key"];
5099
- const quiet = opts.quiet === true;
5100
- // NO FLAGS: inherit the RECORDED decision rather than defaulting to plaintext. This is the half
5101
- // that makes a bare `cotal up` after a `cotal down` keep serving TLS. Without it the decision
5102
- // lives only in the argv of whichever invocation first made it, and the most ordinary operator
5103
- // gesture there is - stop the mesh, start it again - silently downgrades a broker that was
5104
- // deliberately put on TLS. `readBrokerPolicy` refuses rather than degrading if the recorded
5105
- // material has gone missing, so a moved cert fails loud here instead of coming up in cleartext.
5106
- if (!certFile && !keyFile) {
5107
- let recorded;
5108
- try {
5109
- recorded = readBrokerPolicy(root);
5110
- }
5111
- catch (e) {
5112
- stderrLine("✗ ", `${e instanceof Error ? e.message : String(e)}`, c.red);
5113
- process.exit(1);
5114
- }
5115
- if (recorded?.transport.kind === "tls-required") {
5116
- if (!quiet)
5117
- console.log(c.dim("TLS: inheriting the recorded broker policy (no --tls-cert/--tls-key given)"));
5118
- return validateRecorded(recorded.transport, dialHost, { quiet });
5119
- }
5120
- return { kind: "plaintext" };
5121
- }
5122
- // Half a pair is a mistake, never a configuration. Refusing names the missing half rather than
5123
- // failing later inside nats-server with a message about a file the operator did not mention.
5124
- if (!certFile || !keyFile) {
5125
- stderrLine("✗ ", `--tls-cert and --tls-key must be given together (missing ${certFile ? "--tls-key" : "--tls-cert"})`, c.red);
5126
- process.exit(1);
5127
- }
5128
- const transport = { kind: "tls-required", certFile: resolve(certFile), keyFile: resolve(keyFile) };
5129
- const validated = validateRecorded(transport, dialHost, { quiet });
5130
- // RECORD only when the caller has already applied the transport (started a matching listener).
5131
- // Eager write here is S5: a refuse path cannot unwrite, and the next bare up inherits fiction.
5132
- if (opts.persist === true)
5133
- writeBrokerPolicy(root, { version: 1, transport: validated });
5134
- return validated;
5135
- }
5136
- /** A `tls://` broker address is recorded as required TLS, and every later dial through the record
5137
- * trusts it. Refuse it, before anything starts, when this start would serve plaintext. */
5138
- function assertTlsIntentServed(server, transport, source) {
5139
- const tls = server.split(",").some((url) => url.trim().toLowerCase().startsWith("tls://"));
5140
- if (tls && transport.kind !== "tls-required")
5141
- 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 });
5142
- }
5143
- /** A broker that serves TLS is dialed `tls://`, so an address naming `nats://` would be recorded,
5144
- * registered and handed to every later client as plaintext. Refuse it before anything starts,
5145
- * naming the recorded policy that serves TLS and the address to pass instead. */
5146
- function assertTlsAddressServed(server, transport, root) {
5147
- if (transport.kind !== "tls-required")
5148
- return;
5149
- if (!server.split(",").some((url) => /^nats:\/\//i.test(url.trim())))
5150
- return;
5151
- 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`, {
5152
- target: { root, server: brokerAddressForDisplay(server) ?? "not displayable" },
5153
- remedy: `pass --server ${tlsAddress(server)}`,
5154
- selfContained: true,
5155
- });
5156
- }
5157
- /** Persist a transport, and the auth callout timeout, payload limit and account resolver the broker
5158
- * configuration rendered, after its listener starts; a structured boot leaves stdout to its receipt.
5159
- * An absent `accountResolver` keeps the recorded one, and a memory start replaces a recorded full
5160
- * one even when nothing else is left to record. */
5161
- function commitTransportPolicy(root, transport, quietBoot = false, server, limits) {
5162
- const { authTimeout, maxPayload } = limits ?? {};
5163
- const recordedResolver = readBrokerPolicy(root)?.accountResolver;
5164
- const full = (limits?.accountResolver ?? recordedResolver ?? "memory") === "full";
5165
- if (transport.kind !== "tls-required" && authTimeout === undefined && maxPayload === undefined && !full && recordedResolver === undefined)
5166
- return;
5167
- writeBrokerPolicy(root, { version: 1, transport, ...(authTimeout !== undefined ? { authTimeout } : {}), ...(maxPayload !== undefined ? { maxPayload } : {}),
5168
- ...(full ? { accountResolver: "full" } : {}) });
5169
- if (!quietBoot)
5170
- announceTransport(transport, server);
5171
- }
5172
- /** The `tls://` form of a broker URL, or of each URL in a list. */
5173
- const tlsAddress = (server) => server.split(",").map((url) => url.trim().replace(/^nats:/i, "tls:")).join(",");
5174
- function announceTransport(transport, server) {
5175
- if (transport.kind !== "tls-required")
5176
- return;
5177
- try {
5178
- const material = validateTlsMaterial(transport, {});
5179
- console.log(c.dim(`TLS: serving ${material.subject}${server ? ` at ${server}` : ""}, valid until ${material.notAfter.toISOString()}`));
5180
- }
5181
- catch {
5182
- // Already validated at decide-time; announce is best-effort display.
5183
- }
5184
- }
5185
- /** Read the live INFO greeting and report whether the listener requires TLS.
5186
- * `undefined` means no usable INFO (timeout / closed) — caller treats as unknown. */
5187
- async function liveListenerRequiresTls(server, timeoutMs = 2000) {
5188
- let host;
5189
- let port;
5190
- try {
5191
- const u = new URL(server);
5192
- host = u.hostname || "127.0.0.1";
5193
- port = Number(u.port) || 4222;
5194
- }
5195
- catch {
5196
- return undefined;
5197
- }
5198
- return await new Promise((res) => {
5199
- const sock = createConnection({ host, port });
5200
- let buf = "";
5201
- const done = (v) => {
5202
- try {
5203
- sock.destroy();
5204
- }
5205
- catch { /* */ }
5206
- res(v);
5207
- };
5208
- sock.setTimeout(timeoutMs, () => done(undefined));
5209
- sock.on("error", () => done(undefined));
5210
- sock.on("close", () => done(undefined));
5211
- sock.on("data", (d) => {
5212
- buf += d.toString("utf8");
5213
- const nl = buf.indexOf("\r\n");
5214
- if (nl < 0)
5215
- return;
5216
- const line = buf.slice(0, nl);
5217
- try {
5218
- const info = JSON.parse(line.replace(/^INFO\s+/, ""));
5219
- done(info.tls_required === true);
5220
- }
5221
- catch {
5222
- done(undefined);
5223
- }
5224
- });
5225
- });
5226
- }
5227
- /**
5228
- * Re-assert that `transport` is valid for the host clients will actually dial, and exit loudly if
5229
- * not. A no-op for plaintext.
5230
- *
5231
- * This exists because the transport is decided ONCE, early, before the route is known, so that no
5232
- * route can be reached without one — but the effective dial host is decided LATE and differs per
5233
- * route: a manifest may set `broker.host`, and a certificate valid for the flag-derived host is not
5234
- * thereby valid for that one. Deciding early and checking late is the only ordering that satisfies
5235
- * both, so the check is deliberately separate from the decision rather than folded into it.
5236
- *
5237
- * Quiet on success: `resolveTransport` already printed what is being served, and a second identical
5238
- * line reads like a second broker.
5239
- */
5240
- function assertServesDialHost(transport, dialHost) {
5241
- if (transport.kind !== "tls-required" || dialHost === undefined)
5242
- return transport;
5243
- try {
5244
- validateTlsMaterial(transport, { dialHost });
5245
- }
5246
- catch (e) {
5247
- stderrLine("✗ ", `${e instanceof Error ? e.message : String(e)}`, c.red);
5248
- process.exit(1);
5249
- }
5250
- return transport;
5251
- }
5252
- /**
5253
- * The client-side TLS requirement to persist for a listener THIS PROCESS DID NOT START — the
5254
- * restore and ordinary-resume paths, which adopt a broker that is already listening.
5255
- *
5256
- * They have no `transport` in scope because they never decided one, so the honest source is the
5257
- * recorded policy: the listener they are adopting was started from it. Reading it here is what stops
5258
- * a resume from writing a registry entry that says "plaintext" over a broker serving TLS — clients
5259
- * resolved from that entry would then connect without requiring it, which is the downgrade this
5260
- * feature exists to prevent, arriving by way of a recovery path rather than a launch.
5261
- *
5262
- * Fails loud on an unusable policy for the same reason `resolveTransport` does: a resume that cannot
5263
- * tell what it is adopting must not guess.
5264
- */
5265
- function adoptedTlsRequired(root) {
5266
- try {
5267
- return readBrokerPolicy(root)?.transport.kind === "tls-required";
5268
- }
5269
- catch (e) {
5270
- stderrLine("✗ ", `${e instanceof Error ? e.message : String(e)}`, c.red);
5271
- process.exit(1);
5272
- }
5273
- }
5274
- /** Validate a TLS pair and exit loudly on anything wrong. Shared by the flag path and the
5275
- * recorded-policy path so a cert that rots on disk is caught on the NEXT `up`, not only on the
5276
- * one that first configured it. */
5277
- function validateRecorded(transport, dialHost, opts = {}) {
5278
- try {
5279
- const material = validateTlsMaterial(transport, dialHost !== undefined ? { dialHost } : {});
5280
- if (!opts.quiet)
5281
- console.log(c.dim(`TLS: serving ${material.subject}, valid until ${material.notAfter.toISOString()}`));
5282
- }
5283
- catch (e) {
5284
- // Surface the CERTIFICATE cause. A TLS failure reported as a generic startup error invites the
5285
- // wrong remedy - operators go looking at ports and firewalls when the answer is the cert.
5286
- stderrLine("✗ ", `${e instanceof Error ? e.message : String(e)}`, c.red);
5287
- process.exit(1);
5288
- }
5289
- return transport;
5290
- }
5291
- /** A start that names no store would open an empty second store and leave the data where it was:
5292
- * while the last served store holds data and the default store holds none, refuse and name it. */
5293
- function refuseUnnamedLastStore(storeDir) {
5294
- if (existsSync(join(storeDir, "jetstream")))
5295
- return;
5296
- const last = lastServedStore(cotalRoot(), storeDir);
5297
- if (last !== undefined)
5298
- 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` });
5299
- }
5300
- /** The store a bare start that names none opens: the store this root's last broker served, while
5301
- * it holds data and the default store holds none, since the default would open empty and leave the
5302
- * data where it was. When the broker configs name two such stores, the start refuses as
5303
- * {@link refuseUnnamedLastStore} does, because which one to reopen is the operator's choice. */
5304
- function reopenLastStore(storeDir) {
5305
- if (existsSync(join(storeDir, "jetstream")))
5306
- return undefined;
5307
- const last = lastServedStores(cotalRoot(), storeDir);
5308
- if (last.length > 1)
5309
- refuseUnnamedLastStore(storeDir);
5310
- if (last.length === 1)
5311
- for (const line of hang("", `reopening ${last[0]}, the store this root's last broker served`, terminalWidth(process.stdout), c.dim))
5312
- console.log(line);
5313
- return last[0];
5314
- }
5315
- /** A `--store-dir` that does not exist yet, while the last served store holds data, is taken for a
5316
- * mistyped path: the start would open a new empty store there. Creating the directory first names a
5317
- * new store on purpose. */
5318
- function refuseMissingNamedStore(storeDir) {
5319
- if (existsSync(storeDir))
5320
- return;
5321
- const last = lastServedStore(cotalRoot(), storeDir);
5322
- if (last !== undefined)
5323
- 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` });
5324
- }
5325
- /** A start's store against the other spaces that use it. A `--store-dir` this root's last broker did
5326
- * not serve refuses while another space uses it. The default or last served store starts with a
5327
- * warning, and one whose folder that broker served is missing starts empty with a warning. */
5328
- function checkStartStore(storeDir, space) {
5329
- const path = storeDir === undefined ? cotalPath("nats") : resolve(storeDir);
5330
- const served = servedStore(cotalRoot(), path);
5331
- const tenants = sharedStoreAtStart(path, space, storeDir === undefined || served);
5332
- if (tenants.length)
5333
- console.error(c.yellow(`! ${sharedStoreWarning(path, tenants)}`));
5334
- if (served && !existsSync(path))
5335
- console.error(c.yellow(`! ${missingStoreWarning(path)}`));
5336
- }
5337
5001
  /**
5338
5002
  * Render and write the config for an OPEN (no-auth) broker, returning its path. It names `space`,
5339
5003
  * because an open root holds no account that would ({@link namedOpenConfig}).