@cotal-ai/cli 0.112.0 → 0.113.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.
@@ -5,7 +5,7 @@ import { createConnection, createServer, isIP } from "node:net";
5
5
  import { homedir, hostname } from "node:os";
6
6
  import { accessSync, constants, mkdirSync, readFileSync, existsSync, statSync, closeSync, lstatSync, realpathSync, readdirSync, rmdirSync, unlinkSync, } from "node:fs";
7
7
  import { basename, dirname, isAbsolute, join, resolve } from "node:path";
8
- import { isReachable, dialerFor, DEFAULT_SERVER, DEFAULT_SPACE, createSpaceAuth, serverConfig, openServerConfig, validateTlsMaterial, credsProblem, mintCreds, mintLifecycleUid, DEV_OWNER, mintConnectionEvictorCreds, mintMembershipObserverCreds, newIdentity, setupSpaceStreams, reconcileSpaceTtls, ttlBuckets, standaloneConnectOpts, requireBrokerFloor, parseServerVersion, presenceBucket, MEMBERSHIP_MAX_BYTES, spaceDeletionStreams, isJetStreamMissing, seedChannelRegistry, ensureDefaultDeliveryClass, assertValidChannel, isConcreteChannel, validateChannelConfig, validateChannelDefaults, LEASE_TTL_MS, mkSecretDir, openPrivateAppend, realDirNoSymlink, writeSecretFile, writeSecretFileAtomic, utf16Problem, } from "@cotal-ai/core";
8
+ import { isReachable, dialerFor, DEFAULT_SERVER, DEFAULT_SPACE, createSpaceAuth, serverConfig, openServerConfig, validateTlsMaterial, credsProblem, mintCreds, mintLifecycleUid, DEV_OWNER, mintConnectionEvictorCreds, mintMembershipObserverCreds, newIdentity, setupSpaceStreams, removeIssuedStoresBeforeRetention, IssuedStoreBeforeRetentionError, IssuedStoreRecreateRefusal, reconcileSpaceTtls, ttlBuckets, standaloneConnectOpts, requireBrokerFloor, parseServerVersion, presenceBucket, MEMBERSHIP_MAX_BYTES, spaceDeletionStreams, isJetStreamMissing, seedChannelRegistry, ensureDefaultDeliveryClass, assertValidChannel, isConcreteChannel, validateChannelConfig, validateChannelDefaults, LEASE_TTL_MS, mkSecretDir, openPrivateAppend, realDirNoSymlink, writeSecretFile, writeSecretFileAtomic, utf16Problem, } from "@cotal-ai/core";
9
9
  import { JetStreamApiCodes, jetstreamManager, StorageType } from "@nats-io/jetstream";
10
10
  import { Kvm } from "@nats-io/kv";
11
11
  import { assertManagerName, readManagerName, readManagerSeatCap, recordManagerName, recordManagerSeatCap, parseSeatCapFlag, seatCapText, assertRecordIdentity, formatRecord, identityRecord, parseRecord, CommandFailure, commandFailureReport, isCommandFailure, protectedLocalDirectory, jsonFlag, plainFlag, renderReport, terminalWidth, assertSingleSpaceBroker, assertUserAuthInfo, authDir, brokerAddressForDisplay, brokerPolicyPath, getSoleSpaceAuth, soleSpaceOf, getSpaceAuth, hasUserAuthState, listSpaceAccounts, preloadSpaceAccounts, putSpaceAuth, brokerAddressKey, canonicalRoot, rootPathProblem, rootControlProblem, clearCurrent, findMesh, findPreparedSpace, homeCotalDir, getCurrent, loadMeshes, preparedSpaceAt, removePreparedSpace, localMeshesForRoot, keepsRegistration, oneLine, presentationOf, writeResult, connectionEvictorCredsKey, membershipConfigPath, membershipObserverCredsKey, membershipRwCredsKey, MEMBERSHIP_CONFIG_KIND, MEMBERSHIP_RW_CREDS_KIND, parsePositiveIntegerFlag, recordMesh, retainedLegacyBroker, meshesForRoot, removeMesh, rotateSystemCreds, setCurrent, staleSystemCreds, SYSTEM_CREDS_FILES, userAuthStateDir, userAuthSpacesOnDisk, workspaceSecretStore, acquireMaintenanceLock, assertStoreIdentity, assessMaintenanceClaim, assessRestoreClaim, beginOrdinaryResume, bindOrdinaryResumeListener, consumeRetiredMaintenance, markOrdinaryResumeActive, markOrdinaryResumeDegraded, replaceDeadOrdinaryResumeListener, localProcessOwnerStatus, readMaintenanceJournal, rootNamesNoSpace, readMaintenanceResumeDocument, seatCheckpointDir, readStoreIdentity, recordOrdinaryResumeManagerCommit, releaseMaintenanceLock, retireOrdinaryResume, settleTokenHandoff, sweepTokenHandoff, writeTokenHandoff, sameStoreIdentity, cutController, readBrokerPolicy, writeBrokerPolicy, removePidPair, writePidPair, isLoopbackHost, connectUserControlOrThrow, userViewAuth, recordOperationSpace, recordsElsewhereError, recordOperationWarning, retainSystemSigningSeed, restoreLeftOut, SPACE_NAME_MAX, spaceNameTooLong, MIN_FILE_STORE, NATS_PIDFILE, exitCode, } from "@cotal-ai/workspace";
@@ -104,6 +104,7 @@ export const upFlags = [
104
104
  { name: "service-endpoints", type: "boolean", description: "with --user-auth: the auth service also hosts service endpoints (the registration door and the owner-decision host route)" },
105
105
  { name: "agent-provisioning-url", type: "string", value: "<https://…>", description: "with --exchange-public-port: the deployment's remote agent-provisioning endpoint the public bundle advertises" },
106
106
  { name: "rotate-sys", type: "boolean", description: "renew the expired/expiring $SYS creds by rotating the system account (agents, data and creds survive; needs a stopped mesh)" },
107
+ { name: "recreate-issued-stores", type: "string", value: "<backup-dir>", description: "back up this space's issued-authority stores created before 0.111.0 into a new <backup-dir>, delete them and create them again (needs a stopped stack and every other issuer of the space stopped)" },
107
108
  { name: "detach", type: "boolean", short: "d", description: "run in the background (the default; stop with cotal down)" },
108
109
  { name: "foreground", type: "boolean", description: "keep a non-manifest native stack in this terminal; -f currently refuses" },
109
110
  { name: "runtime", type: "string", value: "<name>", description: "agent runtime for the mesh manager (default pty; extension runtimes are explicit-only, see `cotal runtimes`); with -f overrides the manifest's runtime" },
@@ -127,13 +128,21 @@ export function upComplete(argv) {
127
128
  return { items: ["pty", ...extensionNames("runtime")].filter((v, i, a) => a.indexOf(v) === i).map((value) => ({ value })), directive: "nofiles" };
128
129
  if (flag?.name === "restore-only")
129
130
  return { items: [{ value: "registry" }], directive: "nofiles" };
130
- if (flag && ["root", "restore", "file", "channels", "tls-cert", "tls-key", "store-dir"].includes(flag.name))
131
+ if (flag && ["root", "restore", "recreate-issued-stores", "file", "channels", "tls-cert", "tls-key", "store-dir"].includes(flag.name))
131
132
  return { items: [], directive: "default" };
132
133
  if (flag)
133
134
  return { items: [], directive: "nofiles" };
134
135
  const items = upFlags.map((f) => ({ value: `--${f.name}`, description: f.description }));
135
136
  return { items, directive: items.length ? "nofiles" : "default" };
136
137
  }
138
+ /** `--recreate-issued-stores <backup-dir>` names a directory the step creates, so it must not exist
139
+ * and its parent must. Checked before anything starts; the step checks again when it creates it. */
140
+ function assertIssuedBackupDirArgument(raw) {
141
+ const dir = resolve(raw);
142
+ const problem = !raw.trim() ? "is empty" : existsSync(dir) ? `${dir} already exists` : !existsSync(dirname(dir)) ? `${dirname(dir)} does not exist` : undefined;
143
+ if (problem)
144
+ throw new CommandFailure("refused", "USAGE_INVALID", `--recreate-issued-stores names a new backup directory, and ${problem}; nothing was started`, { target: { backupDir: dir }, remedy: "name a directory that does not exist yet, inside one that does" });
145
+ }
137
146
  /** Launch intent is checked by the kernel before seed or effect preparation. A recovery
138
147
  * re-entry supplies its recorded mode explicitly rather than inheriting the new public default. */
139
148
  export function validateUpArguments(args) {
@@ -208,6 +217,11 @@ export function validateUpArguments(args) {
208
217
  throw new CommandFailure("refused", "USAGE_INVALID", "--restore cannot be combined with --file/-f or --channels");
209
218
  if (args.values.restore && args.values["rotate-sys"] === true)
210
219
  throw new CommandFailure("refused", "USAGE_INVALID", "--restore cannot be combined with --rotate-sys", { remedy: "restore the space and verify it first, then rotate: cotal down, then cotal up --rotate-sys" });
220
+ if (args.values["recreate-issued-stores"] !== undefined) {
221
+ if (args.values.file !== undefined || args.values.restore !== undefined)
222
+ throw new CommandFailure("refused", "USAGE_INVALID", `--recreate-issued-stores cannot be combined with ${args.values.file !== undefined ? "--file/-f" : "--restore"}; nothing was started`, { remedy: "run cotal up --space <space> --recreate-issued-stores <backup-dir> on its own first" });
223
+ assertIssuedBackupDirArgument(String(args.values["recreate-issued-stores"]));
224
+ }
211
225
  if (args.values.root !== undefined)
212
226
  preparedUpRoot(String(args.values.root));
213
227
  else if (!(args.values.file && args.values["dry-run"] === true)) {
@@ -865,6 +879,8 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
865
879
  // `up` that has already begun adopting a maintenance attempt.
866
880
  if (values["rotate-sys"] && readMaintenanceJournal(root))
867
881
  throw new Error("--rotate-sys is refused while this root has a maintenance attempt to recover - finish or roll back that attempt (`cotal up` alone recovers it), then `cotal down` and `cotal up --rotate-sys`");
882
+ if (values["recreate-issued-stores"] !== undefined && readMaintenanceJournal(root))
883
+ throw new CommandFailure("refused", "LIFECYCLE_BLOCKED", "--recreate-issued-stores needs a fresh broker start, and this root has a maintenance attempt to recover; nothing was started", { target: { root }, remedy: "finish or roll back that attempt first (cotal up alone recovers it)" });
868
884
  // Raised here for the stronger reason the journal itself carries: a pending maintenance attempt
869
885
  // means the store is mid-recovery, and a broker-only boot over it is wrong with or without the
870
886
  // manager half. The manager half is why the FLAG specifically cannot apply. A settled active
@@ -1233,15 +1249,19 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
1233
1249
  if (!values["dry-run"]) {
1234
1250
  const spaceForRoot = values.space ?? folderSpace();
1235
1251
  if (values.file) {
1252
+ // Only a manifest error is deferred: the -f path reports it from the same load. The pin's refusal
1253
+ // is not one of those errors, and the path that finds a broker already answering the manifest's
1254
+ // address never reaches the later pin in startMeshDetached, so the catch used to discard it.
1255
+ let prepared;
1236
1256
  try {
1237
- const prepared = loadManifest(resolve(values.file));
1238
- // A --space that names another space is refused by the -f path below, before anything is written.
1239
- if (values.space === undefined || values.space === prepared.manifest.space)
1240
- ensureRootForSpace(prepared.manifest.space);
1257
+ prepared = loadManifest(resolve(values.file));
1241
1258
  }
1242
1259
  catch {
1243
1260
  // Manifest errors are reported by the -f path with the same load; do not double-print.
1244
1261
  }
1262
+ // A --space that names another space is refused by the -f path below, before anything is written.
1263
+ if (prepared && (values.space === undefined || values.space === prepared.manifest.space))
1264
+ ensureRootForSpace(prepared.manifest.space);
1245
1265
  }
1246
1266
  else {
1247
1267
  ensureRootForSpace(spaceForRoot);
@@ -1354,7 +1374,7 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
1354
1374
  const stackServer = values.server ?? readStackJournal(meshRoot)?.journal.server ?? localMeshesForRoot(meshRoot).find((m) => m.space === stackSpace)?.server ?? await unrecordedStackServer(meshRoot, stackSpace, values.host);
1355
1375
  if (values.foreground && presentation !== "json")
1356
1376
  stackUpForegroundNotice(presentation, stackSpace, takeover);
1357
- await stackUp({ maintenanceLock: stackLock, root: meshRoot, space: stackSpace, server: stackServer, transport, runtime: values.runtime ?? "pty", noManager, ...(stackMode ? { mode: stackMode } : {}), ...(values.idp ? { idp: values.idp } : {}), ...(values.host ? { host: values.host } : {}), ...(values["store-dir"] ? { storeDir: values["store-dir"] } : {}), ...(values["rotate-sys"] ? { rotateSys: true } : {}), ...(maxFileStore !== undefined ? { maxFileStore } : {}), ...(authTimeout !== undefined ? { authTimeout } : {}), ...(maxSessions !== undefined ? { maxSessions } : {}), ...(values.channels ? { channels: values.channels } : {}), ...(values.__invokedRoot ? { invokedRoot: values.__invokedRoot } : {}), foreground: values.foreground === true, presentation }, native);
1377
+ await stackUp({ maintenanceLock: stackLock, root: meshRoot, space: stackSpace, server: stackServer, transport, runtime: values.runtime ?? "pty", noManager, ...(stackMode ? { mode: stackMode } : {}), ...(values.idp ? { idp: values.idp } : {}), ...(values.host ? { host: values.host } : {}), ...(values["store-dir"] ? { storeDir: values["store-dir"] } : {}), ...(values["rotate-sys"] ? { rotateSys: true } : {}), ...(values["recreate-issued-stores"] !== undefined ? { recreateIssuedStores: resolve(values["recreate-issued-stores"]) } : {}), ...(maxFileStore !== undefined ? { maxFileStore } : {}), ...(authTimeout !== undefined ? { authTimeout } : {}), ...(maxSessions !== undefined ? { maxSessions } : {}), ...(values.channels ? { channels: values.channels } : {}), ...(values.__invokedRoot ? { invokedRoot: values.__invokedRoot } : {}), foreground: values.foreground === true, presentation }, native);
1358
1378
  }
1359
1379
  finally {
1360
1380
  releaseMaintenanceLock(stackLock);
@@ -1660,6 +1680,8 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
1660
1680
  console.error(c.red(`✗ mesh "${held.space}" is already running at ${server} - a running broker can't rotate its system account (it would keep serving the retired one); \`cotal down\` it first, then \`cotal up --rotate-sys\``));
1661
1681
  process.exit(1);
1662
1682
  }
1683
+ if (values["recreate-issued-stores"] !== undefined)
1684
+ throw new CommandFailure("refused", "LIFECYCLE_BLOCKED", `mesh "${held.space}" is already running at ${server}, and its issued-authority stores are recreated only on a fresh broker start, before any issuer runs; nothing was changed`, { target: { space: held.space }, remedy: "stop the stack first, then run cotal up --recreate-issued-stores <backup-dir> again" });
1663
1685
  // `--foreground` asks this terminal to hold the stack's lifetime, but this branch starts
1664
1686
  // nothing here: it used to print `✓ already running`, restart a missing manager detached and
1665
1687
  // exit 0. A service unit relying on `--foreground` read that exit as the stack ending, stopped
@@ -1940,6 +1962,7 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
1940
1962
  open: values.open,
1941
1963
  userAuth: wantUser ? { idpUrl: values.idp } : undefined,
1942
1964
  rotateSys: values["rotate-sys"],
1965
+ ...(values["recreate-issued-stores"] !== undefined ? { recreateIssuedStores: resolve(values["recreate-issued-stores"]) } : {}),
1943
1966
  publicExchange,
1944
1967
  channels: values.channels,
1945
1968
  // The RAW flag, not the loopback-defaulted `host` above: `startMeshDetached` applies the same
@@ -2207,6 +2230,7 @@ async function runUp(args, inheritedLock, onAdopt, freshTeamBoot = false, restor
2207
2230
  };
2208
2231
  const { authService, controlPlane } = await serveReadyListener({
2209
2232
  child, server, space, storeDir, setup, seedFile, transport,
2233
+ ...(values["recreate-issued-stores"] !== undefined ? { recreateIssuedStores: resolve(values["recreate-issued-stores"]) } : {}),
2210
2234
  host: values.host,
2211
2235
  maxSessions,
2212
2236
  maxFileStore,
@@ -3181,7 +3205,7 @@ export function controllerStackNative() {
3181
3205
  const prepared = await prepareBrokerStart({ transport: opts.transport, server: opts.server, space: opts.space, ...(opts.open ? { open: true } : {}), ...(opts.userAuth ? { userAuth: opts.userAuth } : {}), ...(opts.host ? { host: opts.host } : {}), ...(opts.storeDir ? { storeDir: opts.storeDir } : {}), ...(opts.existingStore ? { existingStore: opts.existingStore } : {}), ...(opts.maxFileStore !== undefined ? { maxFileStore: opts.maxFileStore } : {}), ...(opts.authTimeout !== undefined ? { authTimeout: opts.authTimeout } : {}), ...(opts.seed !== undefined ? { seed: opts.seed } : opts.channels ? { channels: opts.channels } : {}), quietBoot: true });
3182
3206
  return { root: prepared.root, server: prepared.server, space: prepared.space, storeDir: prepared.storeDir, transport: prepared.transport, ...(prepared.setup ? { setup: { creds: prepared.setup.creds, wsPort: prepared.setup.wsPort } } : {}), ...(prepared.setup?.prepared && prepared.setup.stateDir ? { user: { prepared: prepared.setup.prepared, stateDir: prepared.setup.stateDir } } : {}), confPath: prepared.confPath, bin: prepared.bin, source: prepared.source, version: prepared.version, seedFile: prepared.seedFile, ...(prepared.setup?.authTimeout !== undefined ? { authTimeout: prepared.setup.authTimeout } : {}) };
3183
3207
  },
3184
- initializeStreams: (server, space, setup, seedFile) => postStart(server, space, setup, seedFile),
3208
+ initializeStreams: (server, space, setup, seedFile, recreateIssuedStores) => postStart(server, space, setup, seedFile, recreateIssuedStores),
3185
3209
  recreateDeletedStreams: ({ seed, ...opts }) => recreateDeletedStreams({ ...opts, ...(seed !== undefined ? { seed: seed } : {}) }),
3186
3210
  recordMesh: (entry) => recordOurMesh({ ...entry, ts: new Date().toISOString() }, "started", true),
3187
3211
  commitTransport: (root, chosen, authTimeout) => commitTransportPolicy(root, chosen, true, undefined, authTimeout),
@@ -3646,7 +3670,7 @@ async function awaitSpawnedListener(l) {
3646
3670
  const { child, server, space } = l;
3647
3671
  let facts;
3648
3672
  try {
3649
- if (!(await waitReady(server, l.creds, l.tls)))
3673
+ if (!(await waitReady(server, l.creds, l.tls, l.log)))
3650
3674
  throw exitedBeforeReady(l) ?? new Error(`nats-server did not become reachable at ${server} - see ${l.log}`);
3651
3675
  facts = await brokerVersion(server, space, l.creds);
3652
3676
  }
@@ -3689,7 +3713,7 @@ async function serveReadyListener(l) {
3689
3713
  await recreateMemoryBuckets(server, space, setup);
3690
3714
  else {
3691
3715
  try {
3692
- await postStart(server, space, setup, l.seedFile);
3716
+ await postStart(server, space, setup, l.seedFile, l.recreateIssuedStores);
3693
3717
  }
3694
3718
  catch (e) {
3695
3719
  await stopFailedListener(child);
@@ -3836,6 +3860,7 @@ opts) {
3836
3860
  await awaitSpawnedListener({ child, executable: { path: bin, source, version }, server, space, creds: setup?.creds, tls: transport.kind === "tls-required", log: logPath, boundListener: opts.boundListener });
3837
3861
  const { authService, controlPlane } = await serveReadyListener({
3838
3862
  child, server, space, storeDir, setup, seedFile, transport,
3863
+ ...(opts.recreateIssuedStores !== undefined ? { recreateIssuedStores: opts.recreateIssuedStores } : {}),
3839
3864
  host: opts.host,
3840
3865
  maxSessions: opts.maxSessions,
3841
3866
  maxFileStore: opts.maxFileStore,
@@ -4197,18 +4222,59 @@ function seedPersonaAfterUp(root, quiet = false) {
4197
4222
  if (written && !quiet)
4198
4223
  console.log(c.dim(` wrote ${written.what}: ${written.path}`));
4199
4224
  }
4200
- async function waitReady(server, creds, tls = false) {
4201
- for (let i = 0; i < 50; i++) {
4202
- // An open listener answers the plaintext probe before any handshake, so TLS is checked either way.
4225
+ async function waitReady(server, creds, tls = false, log) {
4226
+ // Fifty silent probes is the bound for a broker that is not advancing. A listener that is up, or a
4227
+ // broker log that keeps growing or recording a JetStream restore, is evidence the process is still
4228
+ // recovering, so the wait continues instead of stopping it at a fixed count.
4229
+ let evidence = 0;
4230
+ let silent = 0;
4231
+ for (let i = 0; silent < 50; i++) {
4203
4232
  const reachable = await isReachable(server, creds ? { creds } : undefined);
4204
4233
  if (tls)
4205
4234
  await refuseUntrustedListener(server, creds);
4206
4235
  if (reachable)
4207
4236
  return true;
4237
+ const { evidence: next, restoring } = brokerRecoveryEvidence(log);
4238
+ // Any restore evidence seen during the wait is progress, including evidence already present on
4239
+ // the first probe. A restore that has started and not finished is progress on every probe, since
4240
+ // the broker writes nothing to its log until it completes; the probe cap bounds that wait. Only a
4241
+ // probe with no new evidence and no restore in flight counts toward the silent bound.
4242
+ if (next > evidence || restoring) {
4243
+ evidence = Math.max(evidence, next);
4244
+ silent = 0;
4245
+ }
4246
+ else {
4247
+ silent++;
4248
+ }
4249
+ if (i >= 1_500)
4250
+ return false;
4208
4251
  await new Promise((r) => setTimeout(r, 200));
4209
4252
  }
4210
4253
  return false;
4211
4254
  }
4255
+ /** Bytes plus completed-restore lines in the broker log, and whether a restore is in flight. A
4256
+ * foreground launch inherits the terminal and has no file to read, so it contributes no evidence
4257
+ * and keeps the silent-probe bound. */
4258
+ function brokerRecoveryEvidence(log) {
4259
+ const none = { evidence: 0, restoring: false };
4260
+ if (!log || log.startsWith("the terminal"))
4261
+ return none;
4262
+ let text = "";
4263
+ let size = 0;
4264
+ try {
4265
+ const stat = statSync(log);
4266
+ if (!stat.isFile())
4267
+ return none;
4268
+ size = stat.size;
4269
+ text = readFileSync(log, "utf8");
4270
+ }
4271
+ catch {
4272
+ return none;
4273
+ }
4274
+ const started = text.match(/Starting restore/g)?.length ?? 0;
4275
+ const restored = text.match(/Restored \d/g)?.length ?? 0;
4276
+ return { evidence: size + restored, restoring: started > restored };
4277
+ }
4212
4278
  /** Node's codes for a certificate chain this client does not trust. */
4213
4279
  const UNTRUSTED_CERTIFICATE = new Set(["DEPTH_ZERO_SELF_SIGNED_CERT", "SELF_SIGNED_CERT_IN_CHAIN", "UNABLE_TO_GET_ISSUER_CERT", "UNABLE_TO_GET_ISSUER_CERT_LOCALLY", "UNABLE_TO_VERIFY_LEAF_SIGNATURE", "CERT_UNTRUSTED"]);
4214
4280
  /** Throw when the TLS listener at `server` answers and this client refuses its certificate in the
@@ -4451,8 +4517,18 @@ function freePort(host, requestedPort = 0) {
4451
4517
  * before an endpoint has joined (e.g. `cotal spawn`'s DM-inbox provisioning, `cotal_purge`,
4452
4518
  * `history clear`) finds the streams instead of failing with StreamNotFound. Open connects
4453
4519
  * without creds (no authenticator). */
4454
- async function postStart(server, space, setup, seedFile) {
4455
- await setupSpaceStreams({ servers: server, space, creds: setup?.creds });
4520
+ async function postStart(server, space, setup, seedFile, recreateIssuedStores) {
4521
+ if (recreateIssuedStores !== undefined)
4522
+ await recreateIssuedStoresBeforeSetup(server, space, setup !== undefined, recreateIssuedStores);
4523
+ try {
4524
+ await setupSpaceStreams({ servers: server, space, creds: setup?.creds });
4525
+ }
4526
+ catch (error) {
4527
+ // Nothing of the stack runs yet, and the caller stops this broker again, so this is a refusal.
4528
+ if (error instanceof IssuedStoreBeforeRetentionError)
4529
+ throw new CommandFailure("refused", "CONFLICT", error.message, { target: { space, store: error.bucket }, remedy: `stop every other issuer and resolver of space ${space}, then add --recreate-issued-stores <backup-dir> to the cotal up that starts it` });
4530
+ throw error;
4531
+ }
4456
4532
  if (seedFile) {
4457
4533
  await seedChannelRegistry({ servers: server, space, creds: setup?.creds, file: seedFile });
4458
4534
  }
@@ -4467,6 +4543,39 @@ async function postStart(server, space, setup, seedFile) {
4467
4543
  deliveryClass: setup ? "durable" : "live",
4468
4544
  });
4469
4545
  }
4546
+ /** `--recreate-issued-stores`: on the broker this boot just started, before any issuer or resolver
4547
+ * of the space runs, back up and delete the space's issued-authority stores created before bounded
4548
+ * retention, so the stream setup that follows creates them in the current shape. It runs the core
4549
+ * step an embedder runs, on a one-shot `issued-store-recreate` credential minted from the root's
4550
+ * trust; an open space uses its bare connection, as stream setup does. */
4551
+ async function recreateIssuedStoresBeforeSetup(server, space, authenticated, backupDir) {
4552
+ let creds;
4553
+ let inboxPrefix = "_INBOX";
4554
+ if (authenticated) {
4555
+ const auth = await getSpaceAuth(workspaceSecretStore(cotalRoot()), space);
4556
+ if (!auth)
4557
+ throw new Error(`space "${space}" has no trust material under ${authDir(cotalRoot())}; its issued-authority stores were not touched`);
4558
+ const identity = newIdentity();
4559
+ creds = await mintCreds(auth, identity, "issued-store-recreate");
4560
+ inboxPrefix = `_INBOX_${identity.id}`;
4561
+ }
4562
+ const nc = await dialerFor(server)({ servers: server, ...standaloneConnectOpts({ creds, tls: false }), inboxPrefix });
4563
+ let removed;
4564
+ try {
4565
+ removed = await removeIssuedStoresBeforeRetention(nc, { space, backupDir, inboxPrefix });
4566
+ }
4567
+ catch (error) {
4568
+ if (error instanceof IssuedStoreRecreateRefusal)
4569
+ throw new CommandFailure("refused", error.reason === "nothing-to-recreate" ? "CONFLICT" : "USAGE_INVALID", error.message, { target: { space, backupDir }, remedy: error.reason === "nothing-to-recreate" ? "start the space without --recreate-issued-stores" : "name a directory that does not exist yet, inside one that does" });
4570
+ throw error;
4571
+ }
4572
+ finally {
4573
+ await nc.drain().catch(() => nc.close());
4574
+ }
4575
+ for (const store of removed)
4576
+ console.log(`→ backed up ${store.stream} (${store.messages} messages) to ${store.backup}, then deleted it`);
4577
+ console.log(c.dim("• the issued-authority stores are created again in the current shape; every generation issued before the upgrade is refused from now on"));
4578
+ }
4470
4579
  /** A resume or restore skips `postStart` because the preserved store already holds every canonical
4471
4580
  * stream. A memory-backed bucket is the exception: the broker stop that preserved the store emptied
4472
4581
  * it, stream and all (#1356 made presence memory-backed). Recreate those, and only those, from the