@cotal-ai/cli 0.175.0 → 0.175.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.
- package/dist/command.d.ts.map +1 -1
- package/dist/command.js +27 -20
- package/dist/command.js.map +1 -1
- package/dist/commands/agents.d.ts +1 -1
- package/dist/commands/agents.d.ts.map +1 -1
- package/dist/commands/agents.js +25 -14
- package/dist/commands/agents.js.map +1 -1
- package/dist/commands/backup-read.d.ts.map +1 -1
- package/dist/commands/backup-read.js +15 -11
- package/dist/commands/backup-read.js.map +1 -1
- package/dist/commands/backup.d.ts.map +1 -1
- package/dist/commands/backup.js +8 -2
- package/dist/commands/backup.js.map +1 -1
- package/dist/commands/clean.d.ts.map +1 -1
- package/dist/commands/clean.js +8 -3
- package/dist/commands/clean.js.map +1 -1
- package/dist/commands/config.d.ts.map +1 -1
- package/dist/commands/config.js +3 -3
- package/dist/commands/config.js.map +1 -1
- package/dist/commands/doctor.d.ts.map +1 -1
- package/dist/commands/doctor.js +3 -1
- package/dist/commands/doctor.js.map +1 -1
- package/dist/commands/down.d.ts.map +1 -1
- package/dist/commands/down.js +16 -9
- package/dist/commands/down.js.map +1 -1
- package/dist/commands/endpoint-authoring.d.ts.map +1 -1
- package/dist/commands/endpoint-authoring.js +15 -5
- package/dist/commands/endpoint-authoring.js.map +1 -1
- package/dist/commands/endpoint.d.ts.map +1 -1
- package/dist/commands/endpoint.js +2 -0
- package/dist/commands/endpoint.js.map +1 -1
- package/dist/commands/help.js +1 -1
- package/dist/commands/help.js.map +1 -1
- package/dist/commands/history-clear.d.ts.map +1 -1
- package/dist/commands/history-clear.js +14 -3
- package/dist/commands/history-clear.js.map +1 -1
- package/dist/commands/models.d.ts.map +1 -1
- package/dist/commands/models.js +9 -10
- package/dist/commands/models.js.map +1 -1
- package/dist/commands/personas.d.ts.map +1 -1
- package/dist/commands/personas.js +10 -3
- package/dist/commands/personas.js.map +1 -1
- package/dist/commands/removed-start.d.ts +4 -0
- package/dist/commands/removed-start.d.ts.map +1 -0
- package/dist/commands/removed-start.js +68 -0
- package/dist/commands/removed-start.js.map +1 -0
- package/dist/commands/revoke-credential.d.ts.map +1 -1
- package/dist/commands/revoke-credential.js +9 -6
- package/dist/commands/revoke-credential.js.map +1 -1
- package/dist/commands/service-actions.d.ts.map +1 -1
- package/dist/commands/service-actions.js +4 -2
- package/dist/commands/service-actions.js.map +1 -1
- package/dist/commands/service-registry.d.ts.map +1 -1
- package/dist/commands/service-registry.js +21 -3
- package/dist/commands/service-registry.js.map +1 -1
- package/dist/commands/space-delete.d.ts.map +1 -1
- package/dist/commands/space-delete.js +4 -3
- package/dist/commands/space-delete.js.map +1 -1
- package/dist/commands/space-registration.d.ts +2 -0
- package/dist/commands/space-registration.d.ts.map +1 -1
- package/dist/commands/space-registration.js +15 -8
- package/dist/commands/space-registration.js.map +1 -1
- package/dist/commands/space.d.ts +1 -1
- package/dist/commands/space.d.ts.map +1 -1
- package/dist/commands/space.js +7 -4
- package/dist/commands/space.js.map +1 -1
- package/dist/commands/spawn-flags.d.ts +2 -0
- package/dist/commands/spawn-flags.d.ts.map +1 -1
- package/dist/commands/spawn-flags.js +1 -1
- package/dist/commands/spawn-flags.js.map +1 -1
- package/dist/commands/spawn-preview.js +1 -1
- package/dist/commands/spawn-preview.js.map +1 -1
- package/dist/commands/spawn.js +1 -1
- package/dist/commands/spawn.js.map +1 -1
- package/dist/commands/stack-down.d.ts +3 -1
- package/dist/commands/stack-down.d.ts.map +1 -1
- package/dist/commands/stack-down.js +56 -6
- package/dist/commands/stack-down.js.map +1 -1
- package/dist/commands/stack-up.d.ts +9 -9
- package/dist/commands/stack-up.d.ts.map +1 -1
- package/dist/commands/stack-up.js +23 -31
- package/dist/commands/stack-up.js.map +1 -1
- package/dist/commands/status-health.d.ts +2 -2
- package/dist/commands/status-health.d.ts.map +1 -1
- package/dist/commands/status-health.js +19 -2
- package/dist/commands/status-health.js.map +1 -1
- package/dist/commands/status-meshes.js +3 -3
- package/dist/commands/status-meshes.js.map +1 -1
- package/dist/commands/status.js +1 -1
- package/dist/commands/status.js.map +1 -1
- package/dist/commands/team-agent-apply.d.ts.map +1 -1
- package/dist/commands/team-agent-apply.js +5 -4
- package/dist/commands/team-agent-apply.js.map +1 -1
- package/dist/commands/team-deploy-apply.d.ts.map +1 -1
- package/dist/commands/team-deploy-apply.js +9 -3
- package/dist/commands/team-deploy-apply.js.map +1 -1
- package/dist/commands/team.js +2 -2
- package/dist/commands/team.js.map +1 -1
- package/dist/commands/up-args.d.ts +65 -0
- package/dist/commands/up-args.d.ts.map +1 -0
- package/dist/commands/up-args.js +541 -0
- package/dist/commands/up-args.js.map +1 -0
- package/dist/commands/up-detach.d.ts +373 -0
- package/dist/commands/up-detach.d.ts.map +1 -0
- package/dist/commands/up-detach.js +819 -0
- package/dist/commands/up-detach.js.map +1 -0
- package/dist/commands/up-manifest.d.ts +109 -0
- package/dist/commands/up-manifest.d.ts.map +1 -0
- package/dist/commands/up-manifest.js +549 -0
- package/dist/commands/up-manifest.js.map +1 -0
- package/dist/commands/up-stores.d.ts +2 -2
- package/dist/commands/up-stores.d.ts.map +1 -1
- package/dist/commands/up-stores.js +5 -5
- package/dist/commands/up-stores.js.map +1 -1
- package/dist/commands/up.d.ts +7 -245
- package/dist/commands/up.d.ts.map +1 -1
- package/dist/commands/up.js +39 -1882
- package/dist/commands/up.js.map +1 -1
- package/dist/commands/update-release.d.ts +2 -4
- package/dist/commands/update-release.d.ts.map +1 -1
- package/dist/commands/update-release.js +30 -12
- package/dist/commands/update-release.js.map +1 -1
- package/dist/commands/update.d.ts +3 -3
- package/dist/commands/update.d.ts.map +1 -1
- package/dist/commands/update.js +29 -25
- package/dist/commands/update.js.map +1 -1
- package/dist/help.d.ts +1 -1
- package/dist/help.d.ts.map +1 -1
- package/dist/help.js +6 -2
- package/dist/help.js.map +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +5 -9
- package/dist/index.js.map +1 -1
- package/dist/lib/backup-artifact.d.ts +2 -2
- package/dist/lib/backup-artifact.d.ts.map +1 -1
- package/dist/lib/backup-artifact.js +39 -14
- package/dist/lib/backup-artifact.js.map +1 -1
- package/dist/lib/broker-service.d.ts +2 -0
- package/dist/lib/broker-service.d.ts.map +1 -1
- package/dist/lib/broker-service.js +13 -0
- package/dist/lib/broker-service.js.map +1 -1
- package/dist/lib/confirmation-required.d.ts.map +1 -1
- package/dist/lib/confirmation-required.js +7 -1
- package/dist/lib/confirmation-required.js.map +1 -1
- package/dist/lib/credential-authority.d.ts.map +1 -1
- package/dist/lib/credential-authority.js +13 -1
- package/dist/lib/credential-authority.js.map +1 -1
- package/dist/lib/foreground-hold.d.ts +2 -1
- package/dist/lib/foreground-hold.d.ts.map +1 -1
- package/dist/lib/foreground-hold.js +25 -7
- package/dist/lib/foreground-hold.js.map +1 -1
- package/dist/lib/nearest-word.d.ts +3 -4
- package/dist/lib/nearest-word.d.ts.map +1 -1
- package/dist/lib/nearest-word.js +9 -5
- package/dist/lib/nearest-word.js.map +1 -1
- package/dist/lib/persona-files.d.ts +1 -1
- package/dist/lib/persona-files.d.ts.map +1 -1
- package/dist/lib/persona-files.js +23 -5
- package/dist/lib/persona-files.js.map +1 -1
- package/dist/lib/service-preset-target.d.ts +3 -2
- package/dist/lib/service-preset-target.d.ts.map +1 -1
- package/dist/lib/service-preset-target.js +8 -3
- package/dist/lib/service-preset-target.js.map +1 -1
- package/dist/lib/service-presets.d.ts.map +1 -1
- package/dist/lib/service-presets.js +17 -9
- package/dist/lib/service-presets.js.map +1 -1
- package/dist/lib/service-process.d.ts +2 -2
- package/dist/lib/service-process.d.ts.map +1 -1
- package/dist/lib/service-process.js +7 -4
- package/dist/lib/service-process.js.map +1 -1
- package/dist/lib/spawn-defaults.d.ts +2 -2
- package/dist/lib/spawn-defaults.d.ts.map +1 -1
- package/dist/lib/spawn-defaults.js +3 -3
- package/dist/lib/spawn-defaults.js.map +1 -1
- package/dist/lib/stack-journal.d.ts +2 -2
- package/dist/lib/stack-journal.d.ts.map +1 -1
- package/dist/lib/stack-journal.js +9 -5
- package/dist/lib/stack-journal.js.map +1 -1
- package/dist/lib/store-dir.js +1 -1
- package/dist/lib/store-dir.js.map +1 -1
- package/dist/lib/team-deploy-inspection.d.ts +3 -1
- package/dist/lib/team-deploy-inspection.d.ts.map +1 -1
- package/dist/lib/team-deploy-inspection.js +23 -2
- package/dist/lib/team-deploy-inspection.js.map +1 -1
- package/package.json +4 -4
|
@@ -0,0 +1,819 @@
|
|
|
1
|
+
import { noManagerCredentialWarning } from "../lib/daemon-credential-warning.js";
|
|
2
|
+
import {} from "node:child_process";
|
|
3
|
+
import { openBrokerLog } from "../lib/broker-log.js";
|
|
4
|
+
import { spawnBroker } from "../lib/broker-spawn.js";
|
|
5
|
+
import { mkdirSync, readFileSync, existsSync, statSync, closeSync, realpathSync } from "node:fs";
|
|
6
|
+
import { dirname, isAbsolute, join, resolve } from "node:path";
|
|
7
|
+
import { isReachable, dialerFor, DEFAULT_SERVER, DEFAULT_SPACE, standaloneConnectOpts, parseServerVersion, EpEnvelopeError, writeSecretFile, } from "@cotal-ai/core";
|
|
8
|
+
import { CommandFailure, assertUserAuthInfo, authDir, soleSpaceOf, hasUserAuthState, listSpaceAccounts, canonicalRoot, findMesh, findPreparedSpace, homeCotalDir, getCurrent, preparedSpaceAt, removePreparedSpace, localMeshesForRoot, recordMesh, removeMesh, setAdoptedCurrent, userAuthStateDir, readMaintenanceJournal, readBrokerPolicy, removePidPair, writePidPair, verifyIdentityPin, isLoopbackHost, recordOperationWarning, NATS_PIDFILE, MANAGER_PIDFILE, DELIVERY_PIDFILE, AUTH_PIDFILE, localProcessPath, UNTRUSTED_CERTIFICATE, canonicalLocalProcessPath, DELIVERY_LOGFILE, terminalWidth, codeSpan, } from "@cotal-ai/workspace";
|
|
9
|
+
import { ensureAuthService } from "../lib/auth-proc.js";
|
|
10
|
+
import { c, hang, stderrLine } from "../ui.js";
|
|
11
|
+
import { natsServerLabel, resolveNatsServer, unreadVersion } from "../lib/nats-bin.js";
|
|
12
|
+
import { cotalPath, cotalRoot } from "../lib/paths.js";
|
|
13
|
+
import { seedDefaultPersona } from "../lib/default-persona.js";
|
|
14
|
+
import { seedBeforeLaunch } from "../seed/launch.js";
|
|
15
|
+
import { deliveryUp, ensureControlPlane } from "../lib/delivery-proc.js";
|
|
16
|
+
import { RESPONDER_UNBOUND_CONSEQUENCE } from "../lib/delivery-responder.js";
|
|
17
|
+
import { displayCmd } from "../lib/self-exec.js";
|
|
18
|
+
import { shellWord } from "../lib/endpoint-errors.js";
|
|
19
|
+
import { managerUp } from "../lib/manager-proc.js";
|
|
20
|
+
import { recheckExistingStore, keptOnUp, selectedOnUp } from "./stack-up.js";
|
|
21
|
+
import { knownStackRecoveryHost, readStackJournal } from "../lib/stack-journal.js";
|
|
22
|
+
import { warnForeignStoreEntries } from "../lib/store-dir.js";
|
|
23
|
+
import { brokerAddressConflict } from "../lib/broker-service.js";
|
|
24
|
+
import { pendingOrdinaryResumes } from "./up-pending.js";
|
|
25
|
+
import { authTimeoutArgs, loadChannelsFile, commitTransportPolicy, assertServesDialHost } from "./up-transport.js";
|
|
26
|
+
import { postStart, recreateMemoryBuckets } from "./up-stores.js";
|
|
27
|
+
import { brokerVersion, writeOpenBrokerConf, authSetup } from "./up-broker-auth.js";
|
|
28
|
+
import { folderSpace } from "./up-args.js";
|
|
29
|
+
function waitForChildExit(child, timeoutMs) {
|
|
30
|
+
if (child.exitCode !== null || child.signalCode !== null)
|
|
31
|
+
return Promise.resolve(true);
|
|
32
|
+
return new Promise((resolveExit) => {
|
|
33
|
+
const onExit = () => finish(true);
|
|
34
|
+
const timer = setTimeout(() => finish(false), timeoutMs);
|
|
35
|
+
const finish = (exited) => {
|
|
36
|
+
clearTimeout(timer);
|
|
37
|
+
child.off("exit", onExit);
|
|
38
|
+
resolveExit(exited);
|
|
39
|
+
};
|
|
40
|
+
child.once("exit", onExit);
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
/** Listeners {@link stopFailedListener} is stopping. Their launch reports its own error, so the
|
|
44
|
+
* foreground's broker-exit handler must not report that exit as a crash and exit first. */
|
|
45
|
+
export const failedListeners = new WeakSet();
|
|
46
|
+
/**
|
|
47
|
+
* Stop a listener whose launch failed before it served. A signal is not proof of exit, so SIGTERM
|
|
48
|
+
* escalates to SIGKILL and `nats.pid` is removed only once the exit is observed. A listener that
|
|
49
|
+
* outlives both keeps its record and fails loud with its pid. A listener whose pid publish threw
|
|
50
|
+
* passes `published` false and leaves `nats.pid` as found.
|
|
51
|
+
*/
|
|
52
|
+
async function stopFailedListener(child, published = true) {
|
|
53
|
+
failedListeners.add(child);
|
|
54
|
+
child.kill("SIGTERM");
|
|
55
|
+
if (!await waitForChildExit(child, 5_000)) {
|
|
56
|
+
child.kill("SIGKILL");
|
|
57
|
+
if (!await waitForChildExit(child, 5_000))
|
|
58
|
+
throw new Error(`nats-server process ${child.pid ?? "unknown"} did not exit after SIGKILL`);
|
|
59
|
+
}
|
|
60
|
+
if (published)
|
|
61
|
+
removePidPair(cotalPath(NATS_PIDFILE), String(child.pid));
|
|
62
|
+
}
|
|
63
|
+
/** Bring the space's USER-AUTH service up with the broker (user mode only — `setup.prepared` is the
|
|
64
|
+
* provider's output). Loud both ways (U5): a ready service prints the login line; a service that
|
|
65
|
+
* never became ready prints the exact consequence + recourse. Returns the registry metadata either
|
|
66
|
+
* way — the mesh IS a user-auth mesh even while its service is down (connects must say "auth
|
|
67
|
+
* service down", never fall back to static semantics) — plus `ok`, so the exiting `up` surfaces
|
|
68
|
+
* (detach / manifest / refresh-heal) turn a dead identity plane into a NON-ZERO exit: automation
|
|
69
|
+
* must not read "user mesh up" from a mesh whose every user connect will be denied. */
|
|
70
|
+
export async function startUserAuthService(space, server, setup, publicExchange, quietBoot = false) {
|
|
71
|
+
if (!setup?.prepared || !setup.stateDir)
|
|
72
|
+
return { ok: true };
|
|
73
|
+
try {
|
|
74
|
+
const raw = await ensureAuthService({ space, server, stateDir: setup.stateDir, prepared: setup.prepared, extraArgs: publicExchange });
|
|
75
|
+
// The PUBLIC face's advertised URL (when enabled) supersedes the loopback bind in the registry's
|
|
76
|
+
// convenience endpoint — the discovery bundle is GENERATED from what the daemon actually serves,
|
|
77
|
+
// never hand-written. The provider reports it; nothing here reads provider state files.
|
|
78
|
+
const base = typeof raw.publicUrl === "string" ? raw.publicUrl : String(raw.url);
|
|
79
|
+
const endpoints = { url: base, ...(typeof raw.publicUrl === "string" ? { managerAuthorityUrl: `${base.replace(/\/$/, "")}/manager-service-authority` } : {}) };
|
|
80
|
+
const info = assertUserAuthInfo({ ...setup.prepared.publicAuth, endpoints });
|
|
81
|
+
if (!quietBoot)
|
|
82
|
+
console.log(c.green("✓ user-auth service up") + c.dim(` - sign in with: \`cotal login --idp ${info.idp.url}\``));
|
|
83
|
+
return { userAuth: info, ok: true };
|
|
84
|
+
}
|
|
85
|
+
catch (e) {
|
|
86
|
+
// A typed refusal leads with its code and each detail's reason, e.g. a plane claim's
|
|
87
|
+
// `unknown` liveness against its `live-peer` contention, so no caller parses the copy.
|
|
88
|
+
const typed = e instanceof EpEnvelopeError
|
|
89
|
+
? ` [${[e.code, ...(e.details ?? []).map((d) => typeof d.reason === "string" ? `${d.kind}: ${d.reason}` : d.kind)].join("; ")}]`
|
|
90
|
+
: "";
|
|
91
|
+
stderrLine("✗ ", `user-auth service did not come up${typed} (${e.message}) - user connects to "${space}" will fail until a re-\`cotal up\` succeeds`, c.red);
|
|
92
|
+
return { userAuth: assertUserAuthInfo(setup.prepared.publicAuth), ok: false };
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
/** Start the CONTROL PLANE alongside the broker: old-manager preflight → delivery daemon (auth
|
|
96
|
+
* mode only) → detached manager. `up` is the launching command — since `setup` became
|
|
97
|
+
* configure-only (stage 2b), the whole local stack comes up HERE, so `spawn --detach` /
|
|
98
|
+
* cotal_spawn find a manager without any setup side effect. Coupled to the broker by the
|
|
99
|
+
* daemon's watchdog + the `up`/`down` teardown. `mgr` rides through to the manager start — the
|
|
100
|
+
* `up -f` path hands THE manager its runtime + resolved launch spec here (one manager per space,
|
|
101
|
+
* so the launch can never be a second supervise). Returns the control plane it ensured, or
|
|
102
|
+
* `undefined` when it is degraded, so a caller whose output claims a manager (the `up -f` launching
|
|
103
|
+
* line) can tell the truth. */
|
|
104
|
+
export async function startDeliveryWithBroker(space, server,
|
|
105
|
+
/**
|
|
106
|
+
* Whether this listener requires TLS, decided by the CALLER.
|
|
107
|
+
*
|
|
108
|
+
* NON-OPTIONAL, for exactly the reason {@link DetachOpts.transport} is. This used to be an
|
|
109
|
+
* optional `transport` that the callee fell back on `readBrokerPolicy(cotalRoot())` for whenever
|
|
110
|
+
* it was absent — and the refresh path (#836) never passed it. That path decides the same fact
|
|
111
|
+
* from the mesh-registry entry AND the live `INFO`, refuses on any disagreement, and then handed
|
|
112
|
+
* the decision to nobody: a root whose registry records `tlsRequired` while holding no
|
|
113
|
+
* `broker-policy.json` (registered with `cotal meshes add --tls`, or a mesh that predates the
|
|
114
|
+
* policy file) relaunched the delivery daemon FLAGLESS against a TLS broker. Nothing looked
|
|
115
|
+
* wrong, because the daemon still upgrades on the server's unauthenticated INFO — and it holds a
|
|
116
|
+
* STANDING credential and reconnects unattended, so that exposure repeats with nobody watching.
|
|
117
|
+
*
|
|
118
|
+
* A second durable record consulted in the callee is how the caller's copy went silently unused.
|
|
119
|
+
* One decision, and it arrives as an argument.
|
|
120
|
+
*/
|
|
121
|
+
tlsRequired, mgr, afterDelivery, isStopping) {
|
|
122
|
+
try {
|
|
123
|
+
const plane = await ensureControlPlane({ space, server, tls: tlsRequired, ...(mgr ?? {}) }, afterDelivery);
|
|
124
|
+
// #1576: `up` either BINDS the responder or SAYS SO HERE. The delivery daemon is a hard
|
|
125
|
+
// dependency of spawn, retirement and the durable backstop, and this function used to return `true` for a boot
|
|
126
|
+
// that started a daemon whose responder never bound — so `cotal up` printed its success banner
|
|
127
|
+
// over a control plane that could not perform any of the three. The reporter's fleet ran 22
|
|
128
|
+
// hours in that state. This is not a failure of `up` (live messaging is unaffected and the
|
|
129
|
+
// responder may still bind), so it does not throw; it states the condition and its consequence.
|
|
130
|
+
if (plane.responderBound === false)
|
|
131
|
+
console.error(c.yellow(`! delivery responder did not bind before this boot finished - ${RESPONDER_UNBOUND_CONSEQUENCE}`) +
|
|
132
|
+
c.dim(`\n The daemon process is running and the wait is open-ended; boot durable joins reconcile by themselves once it binds (agents do NOT need respawning).\n Watch it with \`${displayCmd()} status --components\`.`));
|
|
133
|
+
return plane;
|
|
134
|
+
}
|
|
135
|
+
catch (e) {
|
|
136
|
+
// A running mesh must report its missing control plane. A foreground stop can remove the
|
|
137
|
+
// manager while this startup observation is still pending; that is intentional teardown.
|
|
138
|
+
if (!isStopping?.())
|
|
139
|
+
reportDegradedControlPlane(e.message);
|
|
140
|
+
return undefined;
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
/** The degraded control plane on stderr: each line of `why`, then its consequence, wrapped to the
|
|
144
|
+
* terminal as every other warning is. */
|
|
145
|
+
export function reportDegradedControlPlane(why) {
|
|
146
|
+
const [first, ...rest] = why.split("\n");
|
|
147
|
+
stderrLine("! ", `control plane degraded: ${first}`, c.dim);
|
|
148
|
+
for (const line of [...rest, "Spawn and retirement require a functioning control plane."])
|
|
149
|
+
stderrLine(" ", line, c.dim);
|
|
150
|
+
}
|
|
151
|
+
/**
|
|
152
|
+
* Publish a spawned listener's pid, and bind a maintenance-bound one to its attempt, before anything
|
|
153
|
+
* waits on it. A launch that dies before its listener serves then leaves `nats.pid` for `cotal down`
|
|
154
|
+
* and a journal naming the exact process for recovery to adopt or retire. A publish or bind that
|
|
155
|
+
* throws stops the listener. Both launch modes call it right after the spawn.
|
|
156
|
+
*/
|
|
157
|
+
export async function recordSpawnedListener(child, startedAt, bound) {
|
|
158
|
+
if (!child.pid)
|
|
159
|
+
throw new Error("nats-server spawned with no pid");
|
|
160
|
+
try {
|
|
161
|
+
writeSecretFile(cotalPath("stack-home.json"), JSON.stringify({ home: canonicalRoot(homeCotalDir()) }));
|
|
162
|
+
writePidPair(cotalPath(NATS_PIDFILE), child.pid); // #969/#1238: publish the pair by rename, never torn
|
|
163
|
+
}
|
|
164
|
+
catch (error) {
|
|
165
|
+
// The entry at `nats.pid` may be the one that refused the publish (a directory there fails the
|
|
166
|
+
// rename), so it is left as found: unrecording would read it and throw over this error.
|
|
167
|
+
await stopFailedListener(child, false);
|
|
168
|
+
throw error;
|
|
169
|
+
}
|
|
170
|
+
if (!bound)
|
|
171
|
+
return;
|
|
172
|
+
if (process.env.COTAL_SMOKE_EXIT_AFTER_RESTORE_LISTENER_SPAWN === "1")
|
|
173
|
+
process.exit(87);
|
|
174
|
+
try {
|
|
175
|
+
bound.onSpawn(child.pid, startedAt);
|
|
176
|
+
}
|
|
177
|
+
catch (error) {
|
|
178
|
+
await stopFailedListener(child);
|
|
179
|
+
throw error;
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
/**
|
|
183
|
+
* Everything between spawning a listener and serving it: readiness, the broker version read and a
|
|
184
|
+
* bound listener's identity check. Foreground `up` and {@link startMeshDetached} both call it, so a
|
|
185
|
+
* guard added here reaches both launch modes (#2924).
|
|
186
|
+
*
|
|
187
|
+
* A listener that never answers or whose version read throws is stopped and its `nats.pid` removed
|
|
188
|
+
* before `up` fails. Nothing has recorded the mesh yet, so a listener left running would hold the
|
|
189
|
+
* port with no registry entry. A bound listener that fails its identity check is kept: its
|
|
190
|
+
* maintenance journal is already bound to it.
|
|
191
|
+
*/
|
|
192
|
+
export async function awaitSpawnedListener(l) {
|
|
193
|
+
const { child, server, space } = l;
|
|
194
|
+
let facts;
|
|
195
|
+
try {
|
|
196
|
+
if (!(await waitReady(server, l.creds, l.tls, l.log)))
|
|
197
|
+
throw exitedBeforeReady(l) ?? new Error(`nats-server did not become reachable at ${server} - see ${l.log}`);
|
|
198
|
+
facts = await brokerVersion(server, space, l.creds);
|
|
199
|
+
}
|
|
200
|
+
catch (e) {
|
|
201
|
+
await stopFailedListener(child);
|
|
202
|
+
throw e;
|
|
203
|
+
}
|
|
204
|
+
if (belowPresenceSafeBroker(facts.version) && facts.presenceFileBacked)
|
|
205
|
+
console.error(c.yellow(`! nats-server ${facts.version} is below 2.14.5 and the presence bucket of "${space}" is file-backed: it can latch after a stall and close the mesh to new joins (#1356); put a nats-server 2.14.5 or newer on PATH (it wins over the bundled one)`));
|
|
206
|
+
if (l.boundListener)
|
|
207
|
+
await l.boundListener.verify();
|
|
208
|
+
}
|
|
209
|
+
/** The failure of a listener that exited before it answered: the executable, the exit code or signal
|
|
210
|
+
* Node observed, and where its output went. Undefined when no exit was observed, so a listener that
|
|
211
|
+
* only stayed silent keeps an unconfirmed outcome. */
|
|
212
|
+
function exitedBeforeReady(l) {
|
|
213
|
+
const { exitCode, signalCode } = l.child;
|
|
214
|
+
if (exitCode === null && signalCode === null)
|
|
215
|
+
return undefined;
|
|
216
|
+
const exit = exitCode !== null ? `exited with code ${exitCode}` : `was stopped by ${signalCode}`;
|
|
217
|
+
return new CommandFailure("failed", "OPERATION_FAILED", `${natsServerLabel(l.executable)} ${exit} before it answered at ${l.server}; see ${l.log}`, {
|
|
218
|
+
target: { executable: l.executable.path, ...(exitCode !== null ? { exitCode } : { signal: signalCode }), server: l.server, log: l.log },
|
|
219
|
+
remedy: listenerExitRemedy(l.executable, l.log),
|
|
220
|
+
});
|
|
221
|
+
}
|
|
222
|
+
/** The next step for a listener that exited before it answered: read its output, then fix a
|
|
223
|
+
* nats-server found on PATH or take it off PATH, and start again. */
|
|
224
|
+
export function listenerExitRemedy(executable, log) {
|
|
225
|
+
return executable.source === "path" ? `read ${log}, then fix ${executable.path} or take it off PATH so cotal uses its bundled nats-server, and run \`cotal up\` again` : `read ${log}, then run \`cotal up\` again`;
|
|
226
|
+
}
|
|
227
|
+
/**
|
|
228
|
+
* Everything a launch runs once its listener answers: the space setup, the user-auth service, the
|
|
229
|
+
* mesh record, the transport commit and the control plane. Foreground `up` and
|
|
230
|
+
* {@link startMeshDetached} both call it, so the two launch modes cannot drift apart (#2496).
|
|
231
|
+
*
|
|
232
|
+
* A fresh boot whose setup throws stops the listener and removes `nats.pid` before rethrowing the
|
|
233
|
+
* original error. Nothing has recorded the mesh yet, so a listener left running would hold the port
|
|
234
|
+
* with no registry entry for `cotal down` to reach. A channel seed with an unparseable value fails
|
|
235
|
+
* here. A resume keeps its listener: its maintenance journal is already bound to it.
|
|
236
|
+
*/
|
|
237
|
+
export async function serveReadyListener(l) {
|
|
238
|
+
const { child, server, space, setup, transport } = l;
|
|
239
|
+
try {
|
|
240
|
+
if (l.resumeAttempt) {
|
|
241
|
+
const ordinaryResume = pendingOrdinaryResumes.has(l.resumeAttempt);
|
|
242
|
+
await recreateMemoryBuckets(server, space, setup, ordinaryResume ? { convertMembership: l.recreateMembershipStore === true } : undefined);
|
|
243
|
+
}
|
|
244
|
+
else {
|
|
245
|
+
await postStart(server, space, setup, l.seedFile, l.recreateIssuedStores, l.recreateMembershipStore, true);
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
catch (e) {
|
|
249
|
+
await stopFailedListener(child);
|
|
250
|
+
throw e;
|
|
251
|
+
}
|
|
252
|
+
// Register the prepared trust before delivery starts. Auth follows delivery's liveness oracle,
|
|
253
|
+
// then the manager: a crashed auth claim cannot be reclaimed while that oracle is absent.
|
|
254
|
+
let svc = {
|
|
255
|
+
ok: setup?.prepared === undefined,
|
|
256
|
+
...(setup?.prepared ? { userAuth: assertUserAuthInfo(setup.prepared.publicAuth) } : {}),
|
|
257
|
+
};
|
|
258
|
+
// Record BEFORE the control plane comes up: the manager's fail-closed mode detection requires
|
|
259
|
+
// an authoritative registry entry (marker-without-registry is a refused start, not a guess),
|
|
260
|
+
// so the record must exist by the time it boots. A manager/delivery failure after this leaves
|
|
261
|
+
// a recorded-but-degraded mesh — the documented, healable posture.
|
|
262
|
+
// Read the prior host and session limit before replacing the registry entry on resume.
|
|
263
|
+
const attachHost = attachHostFor(space, l.host);
|
|
264
|
+
const maxSessions = maxSessionsFor(space, l.maxSessions);
|
|
265
|
+
try {
|
|
266
|
+
recordOurMesh({
|
|
267
|
+
space, server, root: cotalRoot(),
|
|
268
|
+
mode: setup?.prepared ? "user" : setup ? "auth" : "open",
|
|
269
|
+
// Record the transport decision even for plaintext. Omit the host unless the operator chose one.
|
|
270
|
+
tlsRequired: transport.kind === "tls-required",
|
|
271
|
+
...(svc.userAuth ? { userAuth: svc.userAuth } : {}),
|
|
272
|
+
...(attachHost ? { attachHost } : {}),
|
|
273
|
+
...(maxSessions !== undefined ? { maxSessions } : {}),
|
|
274
|
+
...(l.maxFileStore !== undefined ? { maxFileStore: l.maxFileStore } : {}),
|
|
275
|
+
storeDir: l.storeDir,
|
|
276
|
+
ts: new Date().toISOString(),
|
|
277
|
+
}, "started", l.quietBoot);
|
|
278
|
+
}
|
|
279
|
+
catch (e) {
|
|
280
|
+
await stopFailedListener(child);
|
|
281
|
+
throw e;
|
|
282
|
+
}
|
|
283
|
+
// Commit the policy only for a listener that is up and recorded (S5), and before the control
|
|
284
|
+
// plane (S9). startDeliveryWithBroker is HANDED the transport decision, so it does not depend on
|
|
285
|
+
// the file at all.
|
|
286
|
+
commitTransportPolicy(cotalRoot(), transport, l.quietBoot, server, { authTimeout: setup?.authTimeout, maxPayload: l.maxPayload ?? setup?.maxPayload, accountResolver: setup?.accountResolver });
|
|
287
|
+
// An open mesh has no delivery daemon. Its mode is passed down because the root can still hold a
|
|
288
|
+
// static stack's accounts. Class-2 credential renewal is NOT wired here: the MANAGER is the
|
|
289
|
+
// renewal owner (it is resident in every mesh mode, where a foreground `up` process is not).
|
|
290
|
+
const controlPlane = await startDeliveryWithBroker(space, server, transport.kind === "tls-required", {
|
|
291
|
+
open: setup === undefined,
|
|
292
|
+
onDeliveryExit: l.onDeliveryExit,
|
|
293
|
+
runtime: l.runtime,
|
|
294
|
+
launch: l.launch,
|
|
295
|
+
// The address the broker was bound to. This is what lets `cotal attach` reach this manager
|
|
296
|
+
// from another machine; without it the attach face stays loopback-only, so exposing terminals
|
|
297
|
+
// is never a side effect of anything but the operator binding the mesh somewhere reachable.
|
|
298
|
+
attachHost,
|
|
299
|
+
maxSessions,
|
|
300
|
+
managerSeatCap: l.managerSeatCap,
|
|
301
|
+
noManager: l.noManager,
|
|
302
|
+
resumeAttempt: l.resumeAttempt,
|
|
303
|
+
resumeCommit: l.resumeCommit,
|
|
304
|
+
wsPort: setup?.wsPort, // P2 item 6: the console session client's broker ws port
|
|
305
|
+
}, async () => {
|
|
306
|
+
svc = await startUserAuthService(space, server, setup, [...(l.publicExchange ?? []), ...authTimeoutArgs(setup?.authTimeout)], l.quietBoot);
|
|
307
|
+
if (svc.userAuth)
|
|
308
|
+
recordOurMesh({ space, server, root: cotalRoot(), mode: "user", userAuth: svc.userAuth, ts: new Date().toISOString() }, "refresh", true);
|
|
309
|
+
}, l.isStopping);
|
|
310
|
+
const registered = findMesh(space);
|
|
311
|
+
if (registered)
|
|
312
|
+
recordOurMesh(registered, "refresh", true);
|
|
313
|
+
seedPersonaAfterUp(cotalRoot(), l.quietBoot);
|
|
314
|
+
return { authService: svc.ok, controlPlane };
|
|
315
|
+
}
|
|
316
|
+
/** Prepare the existing broker's local trust, configuration and launch inputs without starting a
|
|
317
|
+
* listener, auth service, delivery daemon or manager. This is an explicit mutating phase, not a
|
|
318
|
+
* dry-run or service-adapter planning hook. Its returned setup includes private authority material
|
|
319
|
+
* for the coordinating caller only; it must not be logged or serialized into a public receipt. */
|
|
320
|
+
export async function prepareBrokerStart(opts) {
|
|
321
|
+
const server = opts.server ?? DEFAULT_SERVER;
|
|
322
|
+
const useAuth = !opts.open;
|
|
323
|
+
// Belt on the one boot that both renders the broker config and can be reached by any caller: an
|
|
324
|
+
// open boot skips `authSetup` entirely, so a `rotateSys` arriving here would be dropped in silence
|
|
325
|
+
// rather than refused. Callers guard this too; this is the seam that cannot be bypassed.
|
|
326
|
+
if (opts.rotateSys && !useAuth)
|
|
327
|
+
throw new Error("startMeshDetached: --rotate-sys is for auth meshes; an open mesh has no system account or $SYS credentials to rotate");
|
|
328
|
+
const space = opts.space ?? folderSpace();
|
|
329
|
+
ensureRootForSpace(space); // may pin the cwd as this space's root — before any cotalPath use
|
|
330
|
+
refuseStartOverUserState(Boolean(opts.open), opts.userAuth !== undefined, space);
|
|
331
|
+
const root = cotalRoot();
|
|
332
|
+
const storeDir = opts.storeDir ? resolve(opts.storeDir) : cotalPath("nats");
|
|
333
|
+
if (opts.storeDir)
|
|
334
|
+
warnForeignStoreEntries(storeDir);
|
|
335
|
+
if (opts.existingStore) {
|
|
336
|
+
if (opts.existingStore.named !== storeDir)
|
|
337
|
+
throw new Error("prepareBrokerStart: the pinned existing store is not the store being prepared");
|
|
338
|
+
recheckExistingStore(opts.existingStore, { space, storeDir });
|
|
339
|
+
}
|
|
340
|
+
else
|
|
341
|
+
mkdirSync(storeDir, { recursive: true, mode: 0o700 });
|
|
342
|
+
await claimSpace(space, server, root);
|
|
343
|
+
const seedFile = opts.seed ?? loadChannelsFile(opts.channels);
|
|
344
|
+
const host = opts.host ?? "127.0.0.1";
|
|
345
|
+
// The transport arrives decided. The dial-host SAN is re-checked here because THIS is where the
|
|
346
|
+
// effective server is finally known — a manifest may name a different host than the flags did, and
|
|
347
|
+
// a certificate that is valid for one is not thereby valid for the other.
|
|
348
|
+
const transport = assertServesDialHost(opts.transport, new URL(server).hostname);
|
|
349
|
+
if (opts.logFile === undefined && (opts.logfileSizeLimit !== undefined || opts.logfileMaxNum !== undefined))
|
|
350
|
+
throw new Error("rotation bounds require --log-file");
|
|
351
|
+
const logFile = opts.logFile === undefined ? undefined : resolve(opts.logFile);
|
|
352
|
+
if (logFile !== undefined)
|
|
353
|
+
mkdirSync(dirname(logFile), { recursive: true, mode: 0o700 });
|
|
354
|
+
if (logFile !== undefined) {
|
|
355
|
+
let fd;
|
|
356
|
+
try {
|
|
357
|
+
fd = openBrokerLog(logFile);
|
|
358
|
+
}
|
|
359
|
+
finally {
|
|
360
|
+
if (fd !== undefined)
|
|
361
|
+
closeSync(fd);
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
const setup = useAuth ? await authSetup(storeDir, server, space, host, opts.userAuth, transport, opts.rotateSys, opts.maxFileStore, opts.quietBoot, { authTimeout: opts.authTimeout, maxPayload: opts.maxPayload, accountResolver: opts.accountResolver, manager: opts.noManager !== true, logFile, logfileSizeLimit: opts.logfileSizeLimit, logfileMaxNum: opts.logfileMaxNum, wsPort: opts.wsPort }) : undefined;
|
|
365
|
+
const maxPayload = setup?.maxPayload ?? opts.maxPayload ?? readBrokerPolicy(root)?.maxPayload;
|
|
366
|
+
const port = Number(new URL(server).port) || 4222;
|
|
367
|
+
// Same rule as the foreground path: every route to a listener names its transport (see
|
|
368
|
+
// `writeOpenBrokerConf`). Detach must not be the mode where the fence quietly does not apply.
|
|
369
|
+
const renderingBinary = setup?.brokerBinary ?? await resolveNatsServer();
|
|
370
|
+
if (!renderingBinary.version)
|
|
371
|
+
throw unreadVersion(renderingBinary);
|
|
372
|
+
const confPath = setup ? setup.confPath : writeOpenBrokerConf(storeDir, space, { brokerVersion: renderingBinary.version, port, host, transport, maxFileStore: opts.maxFileStore, maxPayload, logFile, logfileSizeLimit: opts.logfileSizeLimit, logfileMaxNum: opts.logfileMaxNum });
|
|
373
|
+
// Trust preparation awaits; the pinned store is checked again before its config is handed back.
|
|
374
|
+
if (opts.existingStore)
|
|
375
|
+
recheckExistingStore(opts.existingStore, { space, storeDir });
|
|
376
|
+
const args = [
|
|
377
|
+
"-c", confPath,
|
|
378
|
+
...(opts.boundListener ? ["--name", opts.boundListener.serverName] : []),
|
|
379
|
+
];
|
|
380
|
+
const { path: bin, source, version } = renderingBinary;
|
|
381
|
+
return { root, server, space, useAuth, storeDir, seedFile, host, transport, setup, maxPayload, confPath, args, bin, source, version };
|
|
382
|
+
}
|
|
383
|
+
/**
|
|
384
|
+
* Start a background nats-server (JetStream), wait until it's reachable, pre-create the
|
|
385
|
+
* space's streams, and leave it running detached (pid in `.cotal/nats.pid`). Used by
|
|
386
|
+
* `up --detach`. The child writes to the log file, so it survives the parent exiting.
|
|
387
|
+
*/
|
|
388
|
+
export async function startMeshDetached(
|
|
389
|
+
// The `= {}` default is gone with the optional transport: an options object that can be omitted
|
|
390
|
+
// entirely cannot carry a mandatory decision.
|
|
391
|
+
opts) {
|
|
392
|
+
const { server, space, useAuth, storeDir, seedFile, transport, setup: brokerSetup, maxPayload, args, bin, source, version } = await prepareBrokerStart(opts);
|
|
393
|
+
await seedBeforeLaunch();
|
|
394
|
+
const setup = brokerSetup && { ...brokerSetup, creds: await brokerSetup.mintProvisioner() };
|
|
395
|
+
const logPath = cotalPath("nats.log");
|
|
396
|
+
const fd = openBrokerLog(logPath);
|
|
397
|
+
const listenerStartedAt = new Date().toISOString();
|
|
398
|
+
let child;
|
|
399
|
+
try {
|
|
400
|
+
child = spawnBroker(bin, args, { cwd: cotalRoot(), detached: true, stdio: ["ignore", fd, fd] });
|
|
401
|
+
}
|
|
402
|
+
finally {
|
|
403
|
+
closeSync(fd);
|
|
404
|
+
}
|
|
405
|
+
await recordSpawnedListener(child, listenerStartedAt, opts.boundListener);
|
|
406
|
+
child.unref();
|
|
407
|
+
await awaitSpawnedListener({ child, executable: { path: bin, source, version }, server, space, creds: setup?.creds, tls: transport.kind === "tls-required", log: logPath, boundListener: opts.boundListener });
|
|
408
|
+
const { authService, controlPlane } = await serveReadyListener({
|
|
409
|
+
child, server, space, storeDir, setup, seedFile, transport, maxPayload,
|
|
410
|
+
...(opts.recreateIssuedStores !== undefined ? { recreateIssuedStores: opts.recreateIssuedStores } : {}),
|
|
411
|
+
...(opts.recreateMembershipStore ? { recreateMembershipStore: true } : {}),
|
|
412
|
+
host: opts.host,
|
|
413
|
+
maxSessions: opts.maxSessions,
|
|
414
|
+
managerSeatCap: opts.managerSeatCap,
|
|
415
|
+
maxFileStore: opts.maxFileStore,
|
|
416
|
+
publicExchange: opts.publicExchange,
|
|
417
|
+
resumeAttempt: opts.resumeAttempt,
|
|
418
|
+
resumeCommit: opts.resumeCommit,
|
|
419
|
+
runtime: opts.runtime,
|
|
420
|
+
launch: opts.launch,
|
|
421
|
+
noManager: opts.noManager,
|
|
422
|
+
quietBoot: opts.quietBoot,
|
|
423
|
+
});
|
|
424
|
+
if (opts.noManager && useAuth && controlPlane)
|
|
425
|
+
recordOperationWarning(await noManagerCredentialWarning(cotalRoot(), space));
|
|
426
|
+
const delivery = useAuth && deliveryUp(space);
|
|
427
|
+
// A daemon this boot started can still stop before the boot ends, such as on a SIGTERM while the
|
|
428
|
+
// manager starts, and it removes its own record as it goes.
|
|
429
|
+
const lost = controlPlane?.delivery?.started && !delivery ? controlPlane.delivery : undefined;
|
|
430
|
+
return {
|
|
431
|
+
server,
|
|
432
|
+
pid: child.pid ?? 0,
|
|
433
|
+
executable: natsServerLabel({ path: bin, source, version }),
|
|
434
|
+
controlPlane: controlPlane !== undefined,
|
|
435
|
+
authService,
|
|
436
|
+
deliveryResponderBound: useAuth ? controlPlane?.responderBound === true : null,
|
|
437
|
+
delivery,
|
|
438
|
+
...(lost ? { deliveryLost: `the delivery daemon started for space "${space}" (pid ${lost.pid}) exited before this boot finished. It logged its reason to ${canonicalLocalProcessPath(DELIVERY_LOGFILE, { root: cotalRoot(), space })}` } : {}),
|
|
439
|
+
manager: managerUp(space),
|
|
440
|
+
};
|
|
441
|
+
}
|
|
442
|
+
/** Refuse a broker address another program holds without answering NATS, such as a web server, as
|
|
443
|
+
* the controller stack refuses it. nats-server would exit on its bind with only a log line, and the
|
|
444
|
+
* readiness probe would wait on that program instead. `command` is the start the remedy reruns. */
|
|
445
|
+
export async function assertBrokerAddressFree(server, command, bindHost) {
|
|
446
|
+
const conflict = await brokerAddressConflict(server, command, bindHost);
|
|
447
|
+
if (!conflict)
|
|
448
|
+
return;
|
|
449
|
+
throw new CommandFailure("refused", "CONFLICT", `${conflict.message} (bind failed: address already in use); no broker was launched`, {
|
|
450
|
+
target: { root: cotalRoot(), server, bindError: "EADDRINUSE" }, remedy: conflict.remedy,
|
|
451
|
+
});
|
|
452
|
+
}
|
|
453
|
+
/** THE FLIP: a start without `--user-auth` must never boot a broker over a root whose space has
|
|
454
|
+
* user-auth state on disk. `--open` would serve the space's existing JetStream store to anyone and
|
|
455
|
+
* re-record the mesh "open" over its user entry; a static start would boot without the callout that
|
|
456
|
+
* state belongs to. Refused before the store, the space claim or the trust is touched, so the
|
|
457
|
+
* refusal is a refusal and not an unconfirmed outcome. authSetup keeps the same rule for the
|
|
458
|
+
* routes that reach it without passing here. */
|
|
459
|
+
export function refuseStartOverUserState(open, userAuth, space) {
|
|
460
|
+
if (userAuth || !hasUserAuthState(cotalRoot(), space))
|
|
461
|
+
return;
|
|
462
|
+
const stateDir = userAuthStateDir(cotalRoot(), space);
|
|
463
|
+
throw new CommandFailure("refused", "CONFLICT", `space "${space}" has user auth enabled (state under ${stateDir})${open ? ", and --open would serve its streams without auth" : ""}; nothing was started`, {
|
|
464
|
+
target: { root: cotalRoot(), space },
|
|
465
|
+
remedy: `${open ? "replace --open with --user-auth" : "add --user-auth"} to start it with user auth, or remove ${shellWord(stateDir)} deliberately to disable user auth (existing logins and grants die with it)`,
|
|
466
|
+
});
|
|
467
|
+
}
|
|
468
|
+
/** Pin cwd as its own mesh root when the nearest ancestor root already belongs to a DIFFERENT
|
|
469
|
+
* space — mode-independent.
|
|
470
|
+
*
|
|
471
|
+
* Auth path: a root's `.cotal/auth` is space-bound, so an explicit `--space` naming another space
|
|
472
|
+
* cannot share that trust material. Open path: the same ancestor still owns policy, store, pid
|
|
473
|
+
* and MeshEntry; reusing it for a second space collides those (S4 open arm — child `--open --tls-*`
|
|
474
|
+
* wrote the parent's broker-policy and nats.pid while a second broker shared the JetStream store).
|
|
475
|
+
*
|
|
476
|
+
* A mismatch only exists when the resolved space differs from what the ancestor already hosts.
|
|
477
|
+
* When the root was merely inherited (cwd has no `.cotal`), honor the new-space intent by making
|
|
478
|
+
* cwd its own root. Only a folder that itself holds the other space's material refuses.
|
|
479
|
+
* (When multi-space-per-root lands, that refusal becomes provision-the-new-space instead.)
|
|
480
|
+
*
|
|
481
|
+
* The question this asks is "does this root hold the space being booted", NOT "what is THE space of
|
|
482
|
+
* this root". A root holding several tenants has no sole space, and asking for one there threw
|
|
483
|
+
* before the boot could reach the config render - so a `cotal up --space alpha` against a root that
|
|
484
|
+
* legitimately holds alpha and beta refused on ambiguity that its own `--space` had already
|
|
485
|
+
* resolved. The tenant list answers the real question without picking. */
|
|
486
|
+
export function ensureRootForSpace(space) {
|
|
487
|
+
const root = cotalRoot();
|
|
488
|
+
const cwd = process.cwd();
|
|
489
|
+
// A prepared space starts only in the root `cotal space create` gave it. Checked before the mkdir
|
|
490
|
+
// below, so a refused start leaves nothing behind.
|
|
491
|
+
const prepared = findPreparedSpace(space);
|
|
492
|
+
if (prepared && canonicalRoot(prepared.root) !== canonicalRoot(root)) {
|
|
493
|
+
const gone = !existsSync(prepared.root);
|
|
494
|
+
throw new CommandFailure("refused", "TARGET_UNAVAILABLE", `space "${space}" is prepared in ${prepared.root}${gone ? ", which no longer exists" : ""}`, {
|
|
495
|
+
target: { space, root: prepared.root },
|
|
496
|
+
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`,
|
|
497
|
+
});
|
|
498
|
+
}
|
|
499
|
+
// Auth material, a locally started registration, or a preparation names what this root hosts.
|
|
500
|
+
// A remote registration uses the root as a connection folder, not as a stack root.
|
|
501
|
+
const hosted = listSpaceAccounts(authDir(root));
|
|
502
|
+
if (hosted.includes(space))
|
|
503
|
+
return;
|
|
504
|
+
const existing = hosted.length
|
|
505
|
+
? hosted
|
|
506
|
+
: [localMeshesForRoot(root)[0]?.space ?? preparedSpaceAt(root)?.space].filter((s) => !!s);
|
|
507
|
+
if (existing.length === 0 || existing.includes(space))
|
|
508
|
+
return;
|
|
509
|
+
const names = existing.map((s) => `"${s}"`).join(", ");
|
|
510
|
+
if (root !== cwd) {
|
|
511
|
+
mkdirSync(join(cwd, ".cotal"), { recursive: true, mode: 0o700 });
|
|
512
|
+
console.log(c.dim(`nearest mesh root ${root} hosts ${names} - making this folder its own root for "${space}"`));
|
|
513
|
+
return;
|
|
514
|
+
}
|
|
515
|
+
throw new CommandFailure("refused", "CONFLICT", `this folder is the root of ${names} (${root}/.cotal), so it can't also run "${space}"`, {
|
|
516
|
+
target: { space, root, hosted: existing },
|
|
517
|
+
remedy: `run ${existing.length === 1 ? names : "one of those"} with ${codeSpan(`cotal up --root ${shellWord(root)} --space ${existing.length === 1 ? shellWord(existing[0]) : "<name>"}`)}, or start "${space}" from a different folder (it becomes that mesh's own root)`,
|
|
518
|
+
});
|
|
519
|
+
}
|
|
520
|
+
/** Whether `space` is the default space a bare `up` starts because this folder names none. */
|
|
521
|
+
export function unnamedDefault(root, space) {
|
|
522
|
+
return space === DEFAULT_SPACE && soleSpaceOf(authDir(root)) === undefined && !preparedSpaceAt(root) && !localMeshesForRoot(root).length && !readStackJournal(root);
|
|
523
|
+
}
|
|
524
|
+
/** The remedy for a hand-registered (`origin === "manual"`) space `claimSpace` refuses to touch.
|
|
525
|
+
* Branches on whether the REGISTERED server is loopback, the one authority for that being
|
|
526
|
+
* `isLoopbackHost` (`@cotal-ai/workspace`) — never a second opinion here.
|
|
527
|
+
*
|
|
528
|
+
* Non-loopback: the mesh runs on another machine and this one does not take over its control
|
|
529
|
+
* plane by deleting the registry route (that route is what attach, spawn-from-anywhere, and
|
|
530
|
+
* every read verb hang off) or by forking the identity under a different `--space`. The actual
|
|
531
|
+
* next step is running that control plane FROM here, against the broker the record already
|
|
532
|
+
* names: `cotal supervise` (plus `cotal deliver` for the daemon). Dropping the record
|
|
533
|
+
* (`meshes rm`) is a separate decision for a genuinely stale record, out of scope here.
|
|
534
|
+
*
|
|
535
|
+
* Loopback: unchanged — a loopback registration this machine cannot reach the "real" mesh behind
|
|
536
|
+
* (or is stale) keeps the original two-way remedy, byte for byte.
|
|
537
|
+
*
|
|
538
|
+
* A server string `new URL` rejects is a record shape this function never validated before
|
|
539
|
+
* (nothing here parsed it), so it keeps the loopback wording rather than growing a parser. */
|
|
540
|
+
function manualClaimRemedy(space, server) {
|
|
541
|
+
let loopback = true;
|
|
542
|
+
try {
|
|
543
|
+
loopback = isLoopbackHost(new URL(server).hostname);
|
|
544
|
+
}
|
|
545
|
+
catch {
|
|
546
|
+
loopback = true;
|
|
547
|
+
}
|
|
548
|
+
if (!loopback)
|
|
549
|
+
return `\`cotal supervise --space ${space} --server ${server}\` to run its control plane from here (and \`cotal deliver --space ${space} --server ${server}\` for the daemon)`;
|
|
550
|
+
return `\`cotal meshes rm ${space}\` to drop that record first, or start this one under a different \`--space\``;
|
|
551
|
+
}
|
|
552
|
+
/** Where a prior holder's absolute root physically resolves, or undefined when it is proven gone: it
|
|
553
|
+
* does not resolve (ENOENT, ENOTDIR) or resolves to something other than a directory. Any other
|
|
554
|
+
* failure, such as EACCES, EPERM, EIO or ELOOP, proves nothing about the root or its journal, so the
|
|
555
|
+
* name is kept and the refusal says why. No lexical spelling stands in for the physical path: under
|
|
556
|
+
* an unreadable ancestor, `<root>/link/..` resolves lexically to `<root>` while it names another. */
|
|
557
|
+
function priorRootPath(space, root) {
|
|
558
|
+
let real;
|
|
559
|
+
let kind;
|
|
560
|
+
try {
|
|
561
|
+
real = realpathSync.native(root);
|
|
562
|
+
kind = statSync(real);
|
|
563
|
+
}
|
|
564
|
+
catch (e) {
|
|
565
|
+
const code = e.code;
|
|
566
|
+
if (code === "ENOENT" || code === "ENOTDIR")
|
|
567
|
+
return undefined;
|
|
568
|
+
throw new CommandFailure("refused", code === "EACCES" || code === "EPERM" ? "PERMISSION_DENIED" : "TARGET_UNAVAILABLE", `space "${space}" is registered to ${root}, which could not be resolved (${code ?? String(e)}) - \`cotal up\` did not take the name`, { target: { space, root }, remedy: `restore access to ${root} and run this again, or start this stack under a different \`--space\`` });
|
|
569
|
+
}
|
|
570
|
+
return kind.isDirectory() ? real : undefined;
|
|
571
|
+
}
|
|
572
|
+
/** A space name maps to one mesh in the registry (the key `--space`/`use`/`down` act on). Before
|
|
573
|
+
* starting a broker, refuse to reuse a space already claimed by a DIFFERENT live mesh — a stale/dead
|
|
574
|
+
* holder is reclaimed, and said so when it was another root's, unless that root still holds a
|
|
575
|
+
* maintenance journal. Re-`up`ping the same mesh (same server + root) is a refresh (port-reachable
|
|
576
|
+
* path). NOTE: this is a best-effort sequential guard — two `cotal up --space X` racing from
|
|
577
|
+
* different roots within the same instant can both pass the check before either records; that
|
|
578
|
+
* concurrent case is out of scope (a single-operator CLI action), not synchronized with a lock. */
|
|
579
|
+
export async function claimSpace(space, server, root) {
|
|
580
|
+
const existing = findMesh(space);
|
|
581
|
+
if (!existing)
|
|
582
|
+
return;
|
|
583
|
+
// A relative recorded root names no directory without a guess against the cwd, so it is never
|
|
584
|
+
// taken as this root, compared with it or reclaimed. Its record stays until it is removed by hand.
|
|
585
|
+
const relative = !isAbsolute(existing.root);
|
|
586
|
+
if (!relative && existing.server === server && existing.root === root)
|
|
587
|
+
return;
|
|
588
|
+
// Every refusal below is made before the registry changes, so it is typed as refused with its own
|
|
589
|
+
// remedy, and the controller and legacy routes both show the reason and exit 2.
|
|
590
|
+
const target = { space, root: existing.root, server: existing.server };
|
|
591
|
+
// An OPERATOR-REGISTERED holder is decided FIRST, before liveness, because liveness changes
|
|
592
|
+
// nothing about it and the two outcomes would otherwise print the wrong remedy. It is never
|
|
593
|
+
// reclaimed: unreachable is not proof the mesh is gone (the record describes a broker on another
|
|
594
|
+
// machine), the reclaim runs BEFORE this launch starts anything, and `cotal down` — what the
|
|
595
|
+
// liveness branch below would advise — cannot stop a mesh this machine does not run.
|
|
596
|
+
if (existing.origin === "manual" || existing.origin === "catalog")
|
|
597
|
+
throw new CommandFailure("refused", "CONFLICT", `space "${space}" is registered to a mesh at ${existing.server} (${existing.root}) - it is ${existing.origin === "catalog" ? "owned by a signed-in space catalog" : "registered by hand"}, so \`cotal up\` neither takes it over nor reclaims the name`, { target, remedy: existing.origin === "catalog" ? "use a different `--space`, or remove access at the IdP and run `cotal sync`" : manualClaimRemedy(space, existing.server) });
|
|
598
|
+
if (relative)
|
|
599
|
+
throw new CommandFailure("refused", "CONFLICT", `space "${space}" is registered to ${existing.root}, which is not an absolute path - \`cotal up\` did not take the name`, { target, remedy: `drop that record with \`cotal meshes rm ${space}\`, or start this stack under a different \`--space\`` });
|
|
600
|
+
if (await isReachable(existing.server)) {
|
|
601
|
+
// A space name is this machine's, so a separate space here needs a name of its own.
|
|
602
|
+
let controller = false;
|
|
603
|
+
try {
|
|
604
|
+
controller = readStackJournal(existing.root)?.journal.space === space;
|
|
605
|
+
}
|
|
606
|
+
catch { /* named with the legacy stop */ }
|
|
607
|
+
// THIS project's own space, running at its own address, started again with another one. The
|
|
608
|
+
// refusal below belongs to a name another folder holds: it reads as if this folder were a
|
|
609
|
+
// stranger to the space and offers to start a separate one here, when the folder IS that
|
|
610
|
+
// space's project and a start naming no address joins the mesh already running in it. No
|
|
611
|
+
// command moves a stack that ran to another address, so say which address it runs at.
|
|
612
|
+
// The address must differ for this sentence to be true: the early return above compares roots
|
|
613
|
+
// as written while this compares them resolved, so a record naming this root by another
|
|
614
|
+
// spelling reaches here at its OWN address, and that case keeps the refusal below.
|
|
615
|
+
if (canonicalRoot(existing.root) === canonicalRoot(root) && existing.server !== server)
|
|
616
|
+
throw new CommandFailure("refused", "CONFLICT", `space "${space}" already runs from this project at ${existing.server}, and this start names ${server}; nothing was started`, {
|
|
617
|
+
target,
|
|
618
|
+
remedy: `run \`cotal up\` here with no --server or --host to reach the mesh at ${existing.server}, or stop it first with \`cotal down${controller ? " --yes" : ""}\` in ${shellWord(existing.root)}`,
|
|
619
|
+
});
|
|
620
|
+
throw new CommandFailure("refused", "CONFLICT", `space "${space}" is already in use by a mesh at ${existing.server} (${existing.root})`, { target, remedy: `start a separate space in this folder with \`cotal up --space <name>\`, naming one no other folder uses, or stop "${space}" first with \`cotal down${controller ? " --yes" : ""}\` in ${shellWord(existing.root)}` });
|
|
621
|
+
}
|
|
622
|
+
// The recorded root is this root only where it physically resolves, so it is resolved before any
|
|
623
|
+
// comparison, and one that cannot be resolved refuses. A dead holder at another root keeps its name
|
|
624
|
+
// while that root holds a preserved cut or a restore: taking it would cut that root's recovery off
|
|
625
|
+
// from its space. A journal that cannot be read keeps it too. A root proven gone or not a directory
|
|
626
|
+
// has no journal to read; a readable root without one is reclaimed.
|
|
627
|
+
const prior = priorRootPath(space, existing.root);
|
|
628
|
+
const otherRoot = prior !== canonicalRoot(root);
|
|
629
|
+
if (otherRoot && prior !== undefined) {
|
|
630
|
+
let held;
|
|
631
|
+
try {
|
|
632
|
+
held = readMaintenanceJournal(existing.root)?.state;
|
|
633
|
+
}
|
|
634
|
+
catch {
|
|
635
|
+
held = "unreadable";
|
|
636
|
+
}
|
|
637
|
+
if (held)
|
|
638
|
+
throw new CommandFailure("refused", "LIFECYCLE_BLOCKED", `space "${space}" is registered to ${existing.root}, whose maintenance journal holds a preserved cut or a restore (state ${held}) - \`cotal up\` did not take the name`, { target, remedy: `finish that attempt from ${existing.root}, or start this stack under a different \`--space\`` });
|
|
639
|
+
}
|
|
640
|
+
removeMesh(space); // the prior holder's broker is gone — reclaim the name
|
|
641
|
+
if (otherRoot)
|
|
642
|
+
console.error(`• space "${space}" was registered to ${existing.root}, whose broker at ${existing.server} is not running - this up takes the name over`);
|
|
643
|
+
}
|
|
644
|
+
/**
|
|
645
|
+
* The manager attach/console BIND host for a launch into `space`.
|
|
646
|
+
*
|
|
647
|
+
* Exposure is an operator DECISION, made at `up --host` and recorded on the mesh entry. Every later
|
|
648
|
+
* launch for the same mesh — a same-root repair, adopting a preserved or restored listener, a
|
|
649
|
+
* manifest deploy — has no `--host` of its own to consult, so it reads the decision back. Without
|
|
650
|
+
* this a replacement manager falls to loopback and remote `cotal attach` dies at the first repair,
|
|
651
|
+
* silently: the broker and every agent stay up, only the terminal face moves.
|
|
652
|
+
*
|
|
653
|
+
* An explicit host on THIS invocation always wins, so an operator can widen or narrow exposure by
|
|
654
|
+
* saying so. Absent both, undefined — the manager's own loopback default, unchanged.
|
|
655
|
+
*/
|
|
656
|
+
export function attachHostFor(space, explicit) {
|
|
657
|
+
return explicit ?? findMesh(space)?.attachHost;
|
|
658
|
+
}
|
|
659
|
+
/**
|
|
660
|
+
* The manager live-session ceiling for a launch into `space`.
|
|
661
|
+
*
|
|
662
|
+
* Like {@link attachHostFor}, this is an operator DECISION (`--max-sessions`), not something later
|
|
663
|
+
* commands can reconstruct. Every later manager launch — same-root repair, resume, `spawn -f` —
|
|
664
|
+
* has no flag of its own unless the operator typed one, so it reads the decision back. Without
|
|
665
|
+
* this a replacement manager silently falls to 64 and the next console pane past that is refused.
|
|
666
|
+
*
|
|
667
|
+
* An explicit value on THIS invocation always wins. Absent both, undefined — the plane's own
|
|
668
|
+
* default of 64, unchanged, and nothing is recorded as though chosen.
|
|
669
|
+
*/
|
|
670
|
+
export function maxSessionsFor(space, explicit) {
|
|
671
|
+
return explicit ?? findMesh(space)?.maxSessions;
|
|
672
|
+
}
|
|
673
|
+
/** {@link recordOurMesh} under a name that says it is a test seam: the origin rule it enforces is
|
|
674
|
+
* asserted directly by the registry smoke, since reaching each branch through a full `up` would
|
|
675
|
+
* need a live broker per case. */
|
|
676
|
+
export const recordOurMeshForTest = (m, provenance) => recordOurMesh(m, provenance);
|
|
677
|
+
/** Record this mesh in the registry, and set it as the `current` default when there's no usable one
|
|
678
|
+
* — i.e. the first mesh, OR when `current` dangles at a space that's no longer in the registry (a
|
|
679
|
+
* ghost pointer is not a default), and say so. Never silently redirect a `current` that still resolves
|
|
680
|
+
* to a live mesh; just say another is the default and how to switch. */
|
|
681
|
+
export function recordOurMesh(m, provenance, quietBoot = false) {
|
|
682
|
+
const cur = getCurrent();
|
|
683
|
+
const usableCurrent = cur && (findMesh(cur) || findPreparedSpace(cur)) ? cur : undefined; // compute before recording m
|
|
684
|
+
const prior = findMesh(m.space);
|
|
685
|
+
const origin = provenance === "refresh" && (prior?.origin === "manual" || prior?.origin === "catalog") ? prior.origin : "up";
|
|
686
|
+
// A REFRESH starts nothing: it concluded the mesh is up from reachability alone, so `m` holds only
|
|
687
|
+
// what THIS launch decided, and every other field is the record as it stands now. That covers the
|
|
688
|
+
// operator's past decisions (origin, overlay consent, TLS requirement) and anything another writer
|
|
689
|
+
// committed while the refresh ensured the control plane; rebuilding from the refresh's earlier
|
|
690
|
+
// read reverted those and still exited 0. A `started` takeover may replace the record outright
|
|
691
|
+
// (that launch really is the mesh now).
|
|
692
|
+
if (provenance === "refresh" && !prior)
|
|
693
|
+
throw new Error(`mesh "${m.space}" was removed from the registry while \`cotal up\` refreshed it - not re-recording it from an earlier read`);
|
|
694
|
+
const nativeMembers = [];
|
|
695
|
+
for (const [role, template] of [["manager", MANAGER_PIDFILE], ["delivery", DELIVERY_PIDFILE], ["auth", AUTH_PIDFILE], ["broker", NATS_PIDFILE]]) {
|
|
696
|
+
const pin = verifyIdentityPin(role === "broker" ? join(m.root, ".cotal", template) : localProcessPath(template, { root: m.root, space: m.space }));
|
|
697
|
+
if (pin.kind === "match")
|
|
698
|
+
nativeMembers.push({ role, process: pin.record });
|
|
699
|
+
}
|
|
700
|
+
const nativeHost = nativeMembers.length ? knownStackRecoveryHost() : undefined;
|
|
701
|
+
const recorded = { ...m, origin, ...(nativeHost !== undefined ? { nativeMembers, nativeHost } : {}) };
|
|
702
|
+
recordMesh(provenance === "refresh" ? { ...prior, ...recorded, stoppedByDown: undefined, stoppedWithAgents: undefined } : recorded);
|
|
703
|
+
removePreparedSpace(m.space); // started: the registration is its record now
|
|
704
|
+
if (!usableCurrent) {
|
|
705
|
+
setAdoptedCurrent(m.space);
|
|
706
|
+
if (!quietBoot)
|
|
707
|
+
for (const line of hang("", selectedOnUp(m.space), terminalWidth(process.stdout), c.dim))
|
|
708
|
+
console.log(line);
|
|
709
|
+
return;
|
|
710
|
+
}
|
|
711
|
+
if (usableCurrent !== m.space && !quietBoot)
|
|
712
|
+
for (const line of hang("", keptOnUp(m.space, usableCurrent), terminalWidth(process.stdout), c.dim))
|
|
713
|
+
console.log(line);
|
|
714
|
+
}
|
|
715
|
+
/** Write the default persona into the root this `up` started or refreshed when it has none, and
|
|
716
|
+
* say so. The mesh is already up, so a write that fails is reported and the start stands. */
|
|
717
|
+
export function seedPersonaAfterUp(root, quiet = false) {
|
|
718
|
+
let written;
|
|
719
|
+
try {
|
|
720
|
+
written = seedDefaultPersona(root);
|
|
721
|
+
}
|
|
722
|
+
catch (e) {
|
|
723
|
+
console.error(c.yellow(`! the default persona was not written in ${root}: ${e.message}`));
|
|
724
|
+
return;
|
|
725
|
+
}
|
|
726
|
+
if (written && !quiet)
|
|
727
|
+
for (const line of hang(" ", `wrote ${written.what}: ${written.path}`, terminalWidth(process.stdout)))
|
|
728
|
+
console.log(c.dim(line));
|
|
729
|
+
}
|
|
730
|
+
async function waitReady(server, creds, tls = false, log) {
|
|
731
|
+
// Fifty silent probes is the bound for a broker that is not advancing. A listener that is up, or a
|
|
732
|
+
// broker log that keeps growing or recording a JetStream restore, is evidence the process is still
|
|
733
|
+
// recovering, so the wait continues instead of stopping it at a fixed count.
|
|
734
|
+
let evidence = 0;
|
|
735
|
+
let silent = 0;
|
|
736
|
+
for (let i = 0; silent < 50; i++) {
|
|
737
|
+
const reachable = await isReachable(server, creds ? { creds } : undefined);
|
|
738
|
+
if (tls)
|
|
739
|
+
await refuseUntrustedListener(server, creds);
|
|
740
|
+
if (reachable)
|
|
741
|
+
return true;
|
|
742
|
+
const { evidence: next, restoring } = brokerRecoveryEvidence(log);
|
|
743
|
+
// Any restore evidence seen during the wait is progress, including evidence already present on
|
|
744
|
+
// the first probe. A restore that has started and not finished is progress on every probe, since
|
|
745
|
+
// the broker writes nothing to its log until it completes; the probe cap bounds that wait. Only a
|
|
746
|
+
// probe with no new evidence and no restore in flight counts toward the silent bound.
|
|
747
|
+
if (next > evidence || restoring) {
|
|
748
|
+
evidence = Math.max(evidence, next);
|
|
749
|
+
silent = 0;
|
|
750
|
+
}
|
|
751
|
+
else {
|
|
752
|
+
silent++;
|
|
753
|
+
}
|
|
754
|
+
if (i >= 1_500)
|
|
755
|
+
return false;
|
|
756
|
+
await new Promise((r) => setTimeout(r, 200));
|
|
757
|
+
}
|
|
758
|
+
return false;
|
|
759
|
+
}
|
|
760
|
+
/** Bytes plus completed-restore lines in the broker log, and whether a restore is in flight. A
|
|
761
|
+
* foreground broker logging to the terminal has no file to read, so it keeps the silent-probe bound. */
|
|
762
|
+
function brokerRecoveryEvidence(log) {
|
|
763
|
+
const none = { evidence: 0, restoring: false };
|
|
764
|
+
if (!log || log.startsWith("the terminal"))
|
|
765
|
+
return none;
|
|
766
|
+
let text = "";
|
|
767
|
+
let size = 0;
|
|
768
|
+
try {
|
|
769
|
+
const stat = statSync(log);
|
|
770
|
+
if (!stat.isFile())
|
|
771
|
+
return none;
|
|
772
|
+
size = stat.size;
|
|
773
|
+
text = readFileSync(log, "utf8");
|
|
774
|
+
}
|
|
775
|
+
catch {
|
|
776
|
+
return none;
|
|
777
|
+
}
|
|
778
|
+
const started = text.match(/Starting restore/g)?.length ?? 0;
|
|
779
|
+
const restored = text.match(/Restored \d/g)?.length ?? 0;
|
|
780
|
+
return { evidence: size + restored, restoring: started > restored };
|
|
781
|
+
}
|
|
782
|
+
/** Throw when the TLS listener at `server` answers and this client refuses its certificate in the
|
|
783
|
+
* handshake, which waiting does not change. It dials as the setup that follows does. */
|
|
784
|
+
async function refuseUntrustedListener(server, creds) {
|
|
785
|
+
let code, reason = "";
|
|
786
|
+
try {
|
|
787
|
+
const nc = await dialerFor(server)({ servers: server, timeout: 1_000, reconnect: false, maxReconnectAttempts: 0, ...standaloneConnectOpts({ creds, tls: false }) });
|
|
788
|
+
await nc.close();
|
|
789
|
+
return;
|
|
790
|
+
}
|
|
791
|
+
catch (e) {
|
|
792
|
+
code = e?.code;
|
|
793
|
+
reason = e instanceof Error ? e.message.split(";")[0] : String(e);
|
|
794
|
+
}
|
|
795
|
+
const untrusted = typeof code === "string" && UNTRUSTED_CERTIFICATE.has(code);
|
|
796
|
+
if (!untrusted && code !== "ERR_TLS_CERT_ALTNAME_INVALID")
|
|
797
|
+
return;
|
|
798
|
+
const { hostname, port } = new URL(server);
|
|
799
|
+
throw new CommandFailure("failed", "OPERATION_FAILED", `nats-server answered at ${server}, but this client refused its TLS certificate in the handshake (${reason}); up stopped it and recorded nothing`, {
|
|
800
|
+
native: { code: String(code) },
|
|
801
|
+
remedy: untrusted
|
|
802
|
+
? "trust the certificate's CA, or a self-signed certificate itself, by setting NODE_EXTRA_CA_CERTS to that PEM file for `cotal up` and every cotal command of this space, then run `cotal up` again"
|
|
803
|
+
: /^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}`,
|
|
804
|
+
});
|
|
805
|
+
}
|
|
806
|
+
// #1356: the presence bucket's file-backed latch is fixed in nats-server 2.14.5. Below that,
|
|
807
|
+
// `cotal up` warns when the space's presence bucket is file-backed (never refuses: 2.14.0 meets the
|
|
808
|
+
// SPEC §13.12 floor and is the bundled broker). A memory-backed bucket has no file store to latch.
|
|
809
|
+
export function belowPresenceSafeBroker(version) {
|
|
810
|
+
const p = parseServerVersion(version);
|
|
811
|
+
if (!p)
|
|
812
|
+
return false;
|
|
813
|
+
if (p.major !== 2)
|
|
814
|
+
return p.major < 2;
|
|
815
|
+
if (p.minor !== 14)
|
|
816
|
+
return p.minor < 14;
|
|
817
|
+
return p.patch < 5;
|
|
818
|
+
}
|
|
819
|
+
//# sourceMappingURL=up-detach.js.map
|