@slayzone/cli 0.36.1 → 0.36.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.
Files changed (2) hide show
  1. package/dist/slay.js +606 -266
  2. package/package.json +1 -1
package/dist/slay.js CHANGED
@@ -5027,7 +5027,7 @@ var require_abort_controller = __commonJS({
5027
5027
  value: "AbortSignal"
5028
5028
  });
5029
5029
  }
5030
- var AbortController = class {
5030
+ var AbortController2 = class {
5031
5031
  /**
5032
5032
  * Initialize this controller.
5033
5033
  */
@@ -5055,21 +5055,21 @@ var require_abort_controller = __commonJS({
5055
5055
  }
5056
5056
  return signal;
5057
5057
  }
5058
- Object.defineProperties(AbortController.prototype, {
5058
+ Object.defineProperties(AbortController2.prototype, {
5059
5059
  signal: { enumerable: true },
5060
5060
  abort: { enumerable: true }
5061
5061
  });
5062
5062
  if (typeof Symbol === "function" && typeof Symbol.toStringTag === "symbol") {
5063
- Object.defineProperty(AbortController.prototype, Symbol.toStringTag, {
5063
+ Object.defineProperty(AbortController2.prototype, Symbol.toStringTag, {
5064
5064
  configurable: true,
5065
5065
  value: "AbortController"
5066
5066
  });
5067
5067
  }
5068
- exports2.AbortController = AbortController;
5068
+ exports2.AbortController = AbortController2;
5069
5069
  exports2.AbortSignal = AbortSignal2;
5070
- exports2.default = AbortController;
5071
- module2.exports = AbortController;
5072
- module2.exports.AbortController = module2.exports["default"] = AbortController;
5070
+ exports2.default = AbortController2;
5071
+ module2.exports = AbortController2;
5072
+ module2.exports.AbortController = module2.exports["default"] = AbortController2;
5073
5073
  module2.exports.AbortSignal = AbortSignal2;
5074
5074
  }
5075
5075
  });
@@ -5085,7 +5085,7 @@ var require_util2 = __commonJS({
5085
5085
  } = require_errors();
5086
5086
  var { kResistStopPropagation, AggregateError, SymbolDispose } = require_primordials();
5087
5087
  var AbortSignal2 = globalThis.AbortSignal || require_abort_controller().AbortSignal;
5088
- var AbortController = globalThis.AbortController || require_abort_controller().AbortController;
5088
+ var AbortController2 = globalThis.AbortController || require_abort_controller().AbortController;
5089
5089
  var AsyncFunction = Object.getPrototypeOf(async function() {
5090
5090
  }).constructor;
5091
5091
  var Blob = globalThis.Blob || bufferModule.Blob;
@@ -5189,7 +5189,7 @@ var require_util2 = __commonJS({
5189
5189
  if (signals.length === 1) {
5190
5190
  return signals[0];
5191
5191
  }
5192
- const ac = new AbortController();
5192
+ const ac = new AbortController2();
5193
5193
  const abort = () => ac.abort();
5194
5194
  signals.forEach((signal) => {
5195
5195
  validateAbortSignal(signal, "signals");
@@ -8547,7 +8547,7 @@ var require_duplexify = __commonJS({
8547
8547
  } : function isBlob2(b) {
8548
8548
  return false;
8549
8549
  };
8550
- var AbortController = globalThis.AbortController || require_abort_controller().AbortController;
8550
+ var AbortController2 = globalThis.AbortController || require_abort_controller().AbortController;
8551
8551
  var { FunctionPrototypeCall } = require_primordials();
8552
8552
  var Duplexify = class extends Duplex {
8553
8553
  constructor(options) {
@@ -8703,7 +8703,7 @@ var require_duplexify = __commonJS({
8703
8703
  };
8704
8704
  function fromAsyncGen(fn) {
8705
8705
  let { promise, resolve: resolve2 } = createDeferredPromise();
8706
- const ac = new AbortController();
8706
+ const ac = new AbortController2();
8707
8707
  const signal = ac.signal;
8708
8708
  const value = fn(
8709
8709
  (async function* () {
@@ -9130,7 +9130,7 @@ var require_pipeline = __commonJS({
9130
9130
  isReadableStream,
9131
9131
  isReadableFinished
9132
9132
  } = require_utils();
9133
- var AbortController = globalThis.AbortController || require_abort_controller().AbortController;
9133
+ var AbortController2 = globalThis.AbortController || require_abort_controller().AbortController;
9134
9134
  var PassThrough3;
9135
9135
  var Readable3;
9136
9136
  var addAbortListener;
@@ -9266,7 +9266,7 @@ var require_pipeline = __commonJS({
9266
9266
  if (streams.length < 2) {
9267
9267
  throw new ERR_MISSING_ARGS("streams");
9268
9268
  }
9269
- const ac = new AbortController();
9269
+ const ac = new AbortController2();
9270
9270
  const signal = ac.signal;
9271
9271
  const outerSignal = opts === null || opts === void 0 ? void 0 : opts.signal;
9272
9272
  const lastStreamCleanup = [];
@@ -9724,7 +9724,7 @@ var require_compose = __commonJS({
9724
9724
  var require_operators = __commonJS({
9725
9725
  "../../../node_modules/readable-stream/lib/internal/streams/operators.js"(exports2, module2) {
9726
9726
  "use strict";
9727
- var AbortController = globalThis.AbortController || require_abort_controller().AbortController;
9727
+ var AbortController2 = globalThis.AbortController || require_abort_controller().AbortController;
9728
9728
  var {
9729
9729
  codes: { ERR_INVALID_ARG_VALUE, ERR_INVALID_ARG_TYPE, ERR_MISSING_ARGS, ERR_OUT_OF_RANGE },
9730
9730
  AbortError
@@ -9982,7 +9982,7 @@ var require_operators = __commonJS({
9982
9982
  await finished(this.destroy(err));
9983
9983
  throw err;
9984
9984
  }
9985
- const ac = new AbortController();
9985
+ const ac = new AbortController2();
9986
9986
  const signal = ac.signal;
9987
9987
  if (options !== null && options !== void 0 && options.signal) {
9988
9988
  const opts = {
@@ -16217,14 +16217,16 @@ var HUB_SWITCH_ENV = {
16217
16217
  enablePassword: "SLAYZONE_HUB_ENABLE_PASSWORD",
16218
16218
  enableSso: "SLAYZONE_HUB_ENABLE_SSO",
16219
16219
  enableProcesses: "SLAYZONE_HUB_ENABLE_PROCESSES",
16220
- enableIntegrations: "SLAYZONE_HUB_ENABLE_INTEGRATIONS"
16220
+ enableIntegrations: "SLAYZONE_HUB_ENABLE_INTEGRATIONS",
16221
+ enableTelemetry: "SLAYZONE_HUB_ENABLE_TELEMETRY"
16221
16222
  };
16222
16223
  var HUB_SWITCH_DEFAULTS = {
16223
16224
  requireLogin: false,
16224
16225
  enablePassword: true,
16225
16226
  enableSso: false,
16226
16227
  enableProcesses: true,
16227
- enableIntegrations: true
16228
+ enableIntegrations: true,
16229
+ enableTelemetry: true
16228
16230
  };
16229
16231
  var HUB_SSO_ENV = {
16230
16232
  tenantId: "SLAYZONE_HUB_SSO_TENANT_ID",
@@ -16275,7 +16277,7 @@ var SIDECAR_FIXED_PORT = {
16275
16277
  var HUB_PORT_BLOCK = { start: 51100, end: 51199 };
16276
16278
 
16277
16279
  // ../../shared/platform/src/hub-discovery.ts
16278
- var DEFAULT_TIMEOUT_MS = 300;
16280
+ var DEFAULT_TIMEOUT_MS = 3e3;
16279
16281
  var DEFAULT_CONCURRENCY = 32;
16280
16282
  function probe(host, port, timeoutMs) {
16281
16283
  return new Promise((resolve2) => {
@@ -16346,8 +16348,10 @@ function parseSwitches(raw) {
16346
16348
  const o = raw;
16347
16349
  const out = { ...HUB_SWITCH_DEFAULTS };
16348
16350
  for (const key of Object.keys(HUB_SWITCH_ENV)) {
16349
- if (typeof o[key] !== "boolean") return null;
16350
- out[key] = o[key];
16351
+ const value = o[key];
16352
+ if (value === void 0) continue;
16353
+ if (typeof value !== "boolean") return null;
16354
+ out[key] = value;
16351
16355
  }
16352
16356
  return out;
16353
16357
  }
@@ -16441,7 +16445,8 @@ var MESSAGES = {
16441
16445
  NO_COMPUTER_CONNECTED: `Connect a computer: this hub does not read project files or run git, gh or other commands itself (${HUB_SWITCH_ENV.enableProcesses}=0).`,
16442
16446
  HUB_PASSWORD_DISABLED: `Password sign-in is switched off on this hub (${HUB_SWITCH_ENV.enablePassword}=0).`,
16443
16447
  HUB_CONVEX_NOT_CONFIGURED: `GitHub sign-in is off on this hub: no Convex deployment is configured (${HUB_CONVEX_ADDRESS_ENV}).`,
16444
- HUB_CONVEX_MISMATCH: `This hub starts GitHub sign-in only against its own Convex deployment (${HUB_CONVEX_ADDRESS_ENV}); the request named another.`
16448
+ HUB_CONVEX_MISMATCH: `This hub starts GitHub sign-in only against its own Convex deployment (${HUB_CONVEX_ADDRESS_ENV}); the request named another.`,
16449
+ HUB_TELEMETRY_DISABLED: `GitHub sign-in (leaderboard, feedback) is off on this hub: third-party telemetry is switched off (${HUB_SWITCH_ENV.enableTelemetry}=0).`
16445
16450
  };
16446
16451
  var VARIABLES = {
16447
16452
  HUB_PROCESSES_DISABLED: HUB_SWITCH_ENV.enableProcesses,
@@ -16449,7 +16454,8 @@ var VARIABLES = {
16449
16454
  NO_COMPUTER_CONNECTED: HUB_SWITCH_ENV.enableProcesses,
16450
16455
  HUB_PASSWORD_DISABLED: HUB_SWITCH_ENV.enablePassword,
16451
16456
  HUB_CONVEX_NOT_CONFIGURED: HUB_CONVEX_ADDRESS_ENV,
16452
- HUB_CONVEX_MISMATCH: HUB_CONVEX_ADDRESS_ENV
16457
+ HUB_CONVEX_MISMATCH: HUB_CONVEX_ADDRESS_ENV,
16458
+ HUB_TELEMETRY_DISABLED: HUB_SWITCH_ENV.enableTelemetry
16453
16459
  };
16454
16460
 
16455
16461
  // ../../shared/platform/src/cli-install.ts
@@ -16486,6 +16492,10 @@ function getHubTargetPath() {
16486
16492
  const name = process.env.SLAYZONE_DEV === "1" ? "hub-target.dev.json" : "hub-target.json";
16487
16493
  return import_path2.default.join(getCliStateDir(), name);
16488
16494
  }
16495
+ function getBreakGlassPath() {
16496
+ const name = process.env.SLAYZONE_DEV === "1" ? "break-glass.dev.json" : "break-glass.json";
16497
+ return import_path2.default.join(getCliStateDir(), name);
16498
+ }
16489
16499
  function getServiceRuntimeDir(kind) {
16490
16500
  return import_path2.default.join(getCliStateDir(), `${kind}-runtime`);
16491
16501
  }
@@ -16503,9 +16513,15 @@ var hubOverride = null;
16503
16513
  function setHubOverride(target) {
16504
16514
  hubOverride = target;
16505
16515
  }
16516
+ function isTaskTerminal() {
16517
+ return (process.env.SLAYZONE_TASK_ID ?? "").trim() !== "";
16518
+ }
16506
16519
  function getHubConfigPath() {
16507
16520
  return getHubTargetPath();
16508
16521
  }
16522
+ function getBreakGlassSessionPath() {
16523
+ return getBreakGlassPath();
16524
+ }
16509
16525
  function normalizeHubUrl(raw) {
16510
16526
  const trimmed = raw.trim();
16511
16527
  if (!trimmed) return null;
@@ -16523,80 +16539,130 @@ function hubFilePathForRead() {
16523
16539
  if (import_fs2.default.existsSync(current)) return current;
16524
16540
  return legacyHubTargetPaths()[0] ?? current;
16525
16541
  }
16526
- function readHubFile() {
16527
- const configPath = hubFilePathForRead();
16542
+ function readJsonObject(file, label) {
16528
16543
  let rawText;
16529
16544
  try {
16530
- rawText = import_fs2.default.readFileSync(configPath, "utf-8");
16545
+ rawText = import_fs2.default.readFileSync(file, "utf-8");
16531
16546
  } catch (e) {
16532
- if (e.code !== "ENOENT") {
16533
- console.error(`Warning: could not read hub config at ${configPath} \u2014 using local app.`);
16547
+ if (label && e.code !== "ENOENT") {
16548
+ console.error(`Warning: could not read ${label} at ${file} \u2014 ignoring it.`);
16534
16549
  }
16535
16550
  return null;
16536
16551
  }
16537
16552
  try {
16538
16553
  const parsed = JSON.parse(rawText);
16539
- if (typeof parsed !== "object" || parsed === null) {
16540
- throw new Error("not an object");
16541
- }
16542
- const config = parsed;
16543
- if (typeof config.url !== "string" || config.url.trim() === "") {
16544
- throw new Error("missing url");
16545
- }
16546
- return config;
16554
+ if (typeof parsed !== "object" || parsed === null) throw new Error("not an object");
16555
+ return parsed;
16547
16556
  } catch {
16548
- console.error(`Warning: ignoring invalid hub config at ${configPath} \u2014 using local app.`);
16557
+ if (label) console.error(`Warning: ignoring invalid ${label} at ${file}.`);
16549
16558
  return null;
16550
16559
  }
16551
16560
  }
16552
- function resolveHubTarget() {
16553
- if (hubOverride) return hubOverride;
16554
- const envAddress = process.env.SLAYZONE_HUB_ADDRESS;
16561
+ function readHubFile(warn) {
16562
+ const configPath = hubFilePathForRead();
16563
+ const config = readJsonObject(configPath, warn ? "hub config" : null);
16564
+ if (!config) return null;
16565
+ if (typeof config.url !== "string" || config.url.trim() === "") {
16566
+ if (warn) console.error(`Warning: ignoring invalid hub config at ${configPath}.`);
16567
+ return null;
16568
+ }
16569
+ return config;
16570
+ }
16571
+ function storedTarget(warn) {
16572
+ const file = readHubFile(warn);
16573
+ if (!file) return null;
16574
+ const baseUrl = normalizeHubUrl(file.url);
16575
+ if (!baseUrl) {
16576
+ if (warn) console.error(`Warning: ignoring invalid hub URL in ${getHubConfigPath()}.`);
16577
+ return null;
16578
+ }
16579
+ const fileToken = typeof file.token === "string" && file.token !== "" ? file.token : null;
16555
16580
  const envToken = process.env.SLAYZONE_HUB_TOKEN;
16556
- if (envAddress && envAddress.trim() !== "") {
16557
- const addr = envAddress.trim();
16558
- const baseUrl = isBareAuthority(addr) ? normalizeHubUrl(hubUrlFromAddr(addr, "http")) : null;
16559
- if (!baseUrl) {
16560
- console.error(
16561
- `Invalid SLAYZONE_HUB_ADDRESS (expected host[:port], no scheme/path): ${envAddress}`
16562
- );
16563
- process.exit(1);
16564
- }
16565
- return { baseUrl, token: envToken || null };
16581
+ return { baseUrl, token: envToken !== void 0 ? envToken || null : fileToken, source: "file" };
16582
+ }
16583
+ function envTarget() {
16584
+ const envAddress = process.env.SLAYZONE_HUB_ADDRESS;
16585
+ if (!envAddress || envAddress.trim() === "") return null;
16586
+ const addr = envAddress.trim();
16587
+ const baseUrl = isBareAuthority(addr) ? normalizeHubUrl(hubUrlFromAddr(addr, "http")) : null;
16588
+ if (!baseUrl) {
16589
+ console.error(
16590
+ `Invalid SLAYZONE_HUB_ADDRESS (expected host[:port], no scheme/path): ${envAddress}`
16591
+ );
16592
+ process.exit(1);
16566
16593
  }
16567
- const file = readHubFile();
16568
- if (file) {
16569
- const baseUrl = normalizeHubUrl(file.url);
16570
- if (!baseUrl) {
16571
- console.error(`Warning: ignoring invalid hub URL in ${getHubConfigPath()} \u2014 using local app.`);
16572
- return null;
16573
- }
16574
- const fileToken = typeof file.token === "string" && file.token !== "" ? file.token : null;
16575
- return { baseUrl, token: envToken !== void 0 ? envToken || null : fileToken };
16594
+ const envToken = process.env.SLAYZONE_HUB_TOKEN;
16595
+ if (envToken !== void 0) return { baseUrl, token: envToken || null, source: "env" };
16596
+ const stored = storedTarget(false);
16597
+ return { baseUrl, token: stored?.baseUrl === baseUrl ? stored.token : null, source: "env" };
16598
+ }
16599
+ function flagTarget() {
16600
+ return hubOverride ? { ...hubOverride, source: "flag" } : null;
16601
+ }
16602
+ function resolveTaskCommandTarget() {
16603
+ return flagTarget() ?? envTarget() ?? (isTaskTerminal() ? null : storedTarget(true));
16604
+ }
16605
+ function resolveHubCommandTarget() {
16606
+ const flag = flagTarget();
16607
+ if (flag) return flag;
16608
+ const session = readBreakGlassSession();
16609
+ if (session && !isBreakGlassExpired(session)) {
16610
+ return { baseUrl: session.url, token: session.token, source: "break-glass" };
16576
16611
  }
16577
- return null;
16612
+ return isTaskTerminal() ? storedTarget(true) ?? envTarget() : envTarget() ?? storedTarget(true);
16613
+ }
16614
+ function writePrivateJson(file, payload) {
16615
+ import_fs2.default.mkdirSync(import_path3.default.dirname(file), { recursive: true });
16616
+ import_fs2.default.writeFileSync(file, `${JSON.stringify(payload, null, 2)}
16617
+ `, { mode: 384 });
16618
+ import_fs2.default.chmodSync(file, 384);
16578
16619
  }
16579
16620
  function writeHubConfig(url, token) {
16580
16621
  const configPath = getHubConfigPath();
16581
- import_fs2.default.mkdirSync(import_path3.default.dirname(configPath), { recursive: true });
16582
16622
  const payload = token ? { url, token } : { url };
16583
- import_fs2.default.writeFileSync(configPath, `${JSON.stringify(payload, null, 2)}
16584
- `, { mode: 384 });
16585
- import_fs2.default.chmodSync(configPath, 384);
16623
+ writePrivateJson(configPath, payload);
16586
16624
  return configPath;
16587
16625
  }
16588
16626
  function removeHubConfig() {
16589
16627
  let removed = false;
16590
16628
  for (const target of [getHubConfigPath(), ...legacyHubTargetPaths()]) {
16591
- try {
16592
- import_fs2.default.unlinkSync(target);
16593
- removed = true;
16594
- } catch (e) {
16595
- if (e.code !== "ENOENT") throw e;
16596
- }
16629
+ if (unlinkIfPresent(target)) removed = true;
16597
16630
  }
16598
16631
  return removed;
16599
16632
  }
16633
+ function readBreakGlassSession() {
16634
+ const file = getBreakGlassSessionPath();
16635
+ const raw = readJsonObject(file, "break-glass session");
16636
+ if (!raw) return null;
16637
+ const { url, token, expiresAt } = raw;
16638
+ const baseUrl = typeof url === "string" ? normalizeHubUrl(url) : null;
16639
+ if (!baseUrl || typeof token !== "string" || token === "") {
16640
+ console.error(`Warning: ignoring invalid break-glass session at ${file}.`);
16641
+ return null;
16642
+ }
16643
+ return { url: baseUrl, token, expiresAt: typeof expiresAt === "string" ? expiresAt : "?" };
16644
+ }
16645
+ function isBreakGlassExpired(session, now = Date.now()) {
16646
+ const at = Date.parse(session.expiresAt);
16647
+ return !Number.isNaN(at) && at <= now;
16648
+ }
16649
+ function writeBreakGlassSession(session) {
16650
+ const file = getBreakGlassSessionPath();
16651
+ writePrivateJson(file, session);
16652
+ return file;
16653
+ }
16654
+ function removeBreakGlassSession() {
16655
+ return unlinkIfPresent(getBreakGlassSessionPath());
16656
+ }
16657
+ function unlinkIfPresent(file) {
16658
+ try {
16659
+ import_fs2.default.unlinkSync(file);
16660
+ return true;
16661
+ } catch (e) {
16662
+ if (e.code !== "ENOENT") throw e;
16663
+ return false;
16664
+ }
16665
+ }
16600
16666
 
16601
16667
  // src/local-hub.ts
16602
16668
  var import_node_path3 = __toESM(require("node:path"), 1);
@@ -16607,8 +16673,7 @@ function expectedRoot() {
16607
16673
  const root = process.env.SLAYZONE_ROOT?.trim();
16608
16674
  return root ? import_node_path3.default.resolve(root) : null;
16609
16675
  }
16610
- async function probeFixedPort() {
16611
- const port = fixedPortForChannel();
16676
+ async function probeFixedPort(port = fixedPortForChannel()) {
16612
16677
  const hub = await findHub(String(port));
16613
16678
  if (!hub) return { kind: "absent" };
16614
16679
  const expected = expectedRoot();
@@ -16618,7 +16683,7 @@ async function probeFixedPort() {
16618
16683
  return { kind: "found", port: hub.port, root: hub.root, authRequired: hub.authRequired };
16619
16684
  }
16620
16685
  async function isCoLocatedHub() {
16621
- const configured = resolveHubTarget();
16686
+ const configured = resolveTaskCommandTarget();
16622
16687
  if (!configured) return true;
16623
16688
  try {
16624
16689
  const host = new URL(configured.baseUrl).hostname.replace(/^\[|\]$/g, "");
@@ -16630,8 +16695,14 @@ async function isCoLocatedHub() {
16630
16695
 
16631
16696
  // src/api.ts
16632
16697
  async function resolveTarget() {
16633
- const hub = resolveHubTarget();
16698
+ const hub = resolveTaskCommandTarget();
16634
16699
  if (hub) return { baseUrl: hub.baseUrl, token: hub.token, hub: true };
16700
+ if (isTaskTerminal() && !process.env.SLAYZONE_ROOT?.trim()) {
16701
+ console.error(
16702
+ "This is a task terminal (SLAYZONE_TASK_ID is set), but it does not say which app\nspawned it: neither SLAYZONE_HUB_ADDRESS nor SLAYZONE_ROOT is set. Refusing to guess.\nOpen a new terminal from the app, or name the hub with `slay --hub <name|port>`."
16703
+ );
16704
+ process.exit(1);
16705
+ }
16635
16706
  const probe2 = await probeFixedPort();
16636
16707
  if (probe2.kind === "foreign") {
16637
16708
  console.error(
@@ -17031,7 +17102,7 @@ async function postHubNotify(hub, timeoutMs = 3e3) {
17031
17102
  }
17032
17103
  }
17033
17104
  async function notifyApp() {
17034
- const hub = resolveHubTarget();
17105
+ const hub = resolveTaskCommandTarget();
17035
17106
  if (hub) {
17036
17107
  const ok = await postHubNotify(hub);
17037
17108
  if (!ok) {
@@ -21835,7 +21906,7 @@ var import_path8 = __toESM(require("path"), 1);
21835
21906
  var import_node_stream = require("node:stream");
21836
21907
  var import_promises2 = require("node:stream/promises");
21837
21908
 
21838
- // ../../domains/task/src/shared/types.ts
21909
+ // ../../domains/task-contracts/src/types.ts
21839
21910
  var COLD_RESPAWN_MS = 30 * 60 * 1e3;
21840
21911
  var px = (value) => ({ value, unit: "px" });
21841
21912
  var PANEL_LAYOUT_DEFAULTS = {
@@ -22769,7 +22840,7 @@ function safeRandomUUID() {
22769
22840
  return `insecure-ctx-${Date.now()}-${fallbackUuidCounter}`;
22770
22841
  }
22771
22842
 
22772
- // ../../domains/projects/src/shared/create-project.ts
22843
+ // ../../domains/projects-contracts/src/create-project.ts
22773
22844
  var HEX_COLOR_RE = /^#[0-9a-fA-F]{6}$/;
22774
22845
  function normalizeProjectName(name) {
22775
22846
  const trimmed = name.trim();
@@ -26055,7 +26126,8 @@ var HUB_CONFIG_SWITCH_KEYS = [
26055
26126
  "enablePassword",
26056
26127
  "enableSso",
26057
26128
  "enableProcesses",
26058
- "enableIntegrations"
26129
+ "enableIntegrations",
26130
+ "enableTelemetry"
26059
26131
  ];
26060
26132
  function getHubConfigFilePath() {
26061
26133
  return (0, import_node_path6.join)(getSlayzoneHomeDir(), "hub.config.json");
@@ -26095,7 +26167,7 @@ function coerceComputerConfig(raw) {
26095
26167
  }
26096
26168
  return cfg;
26097
26169
  }
26098
- function readJsonObject(path12) {
26170
+ function readJsonObject2(path12) {
26099
26171
  let raw;
26100
26172
  try {
26101
26173
  raw = (0, import_node_fs5.readFileSync)(path12, "utf8");
@@ -26141,7 +26213,7 @@ function saveHubConfigFile(cfg, path12 = getHubConfigFilePath()) {
26141
26213
  writeJsonAtomic(path12, cfg);
26142
26214
  }
26143
26215
  function updateHubConfigFile(patch, path12 = getHubConfigFilePath()) {
26144
- const current = readJsonObject(path12);
26216
+ const current = readJsonObject2(path12);
26145
26217
  const merged = current ? coerceHubConfig(current) : {};
26146
26218
  for (const [k, v] of Object.entries(patch)) {
26147
26219
  if (v !== void 0) merged[k] = v;
@@ -26150,16 +26222,16 @@ function updateHubConfigFile(patch, path12 = getHubConfigFilePath()) {
26150
26222
  return merged;
26151
26223
  }
26152
26224
  function loadComputerConfigFile(path12 = getComputerConfigFilePath()) {
26153
- const raw = readJsonObject(path12);
26225
+ const raw = readJsonObject2(path12);
26154
26226
  if (raw) return coerceComputerConfig(raw);
26155
- const legacy = readJsonObject(legacyConfigFilePathFor(path12));
26227
+ const legacy = readJsonObject2(legacyConfigFilePathFor(path12));
26156
26228
  return legacy ? coerceComputerConfig(legacy) : {};
26157
26229
  }
26158
26230
  function saveComputerConfigFile(cfg, path12 = getComputerConfigFilePath()) {
26159
26231
  writeJsonAtomic(path12, cfg);
26160
26232
  }
26161
26233
  function updateComputerConfigFile(patch, path12 = getComputerConfigFilePath()) {
26162
- const current = readJsonObject(path12);
26234
+ const current = readJsonObject2(path12);
26163
26235
  const merged = current ? coerceComputerConfig(current) : {};
26164
26236
  for (const [k, v] of Object.entries(patch)) {
26165
26237
  if (v !== void 0) merged[k] = v;
@@ -26468,7 +26540,7 @@ var import_node_child_process3 = require("node:child_process");
26468
26540
  var import_node_fs7 = require("node:fs");
26469
26541
  var import_node_module = require("node:module");
26470
26542
  var import_node_path8 = require("node:path");
26471
- var CLI_VERSION = true ? "0.36.1" : "";
26543
+ var CLI_VERSION = true ? "0.36.2" : "";
26472
26544
  function fail(message) {
26473
26545
  console.error(message);
26474
26546
  process.exit(1);
@@ -26792,7 +26864,7 @@ function supervisorStatus(kind, backend, name) {
26792
26864
 
26793
26865
  // src/hub-request.ts
26794
26866
  async function resolveHubRequestTarget(what, discover = () => discoverHubs()) {
26795
- const configured = resolveHubTarget();
26867
+ const configured = resolveHubCommandTarget();
26796
26868
  if (configured) return configured;
26797
26869
  const running = await discover();
26798
26870
  if (running.length === 0) {
@@ -26845,57 +26917,333 @@ ${hint}` : ""}`);
26845
26917
 
26846
26918
  // src/hub-sign-in.ts
26847
26919
  var import_node_child_process4 = require("node:child_process");
26848
- var import_node_http3 = __toESM(require("node:http"), 1);
26849
- var import_node_https = __toESM(require("node:https"), 1);
26850
- var CLI_DEVICE_CLIENT_ID = "slayzone-cli";
26851
- var DEVICE_GRANT = "urn:ietf:params:oauth:grant-type:device_code";
26852
- function postAuthJson(url, body, timeoutMs = 1e4) {
26853
- const payload = JSON.stringify(body);
26854
- const request2 = url.startsWith("https:") ? import_node_https.default.request : import_node_http3.default.request;
26855
- return new Promise((resolve2, reject) => {
26856
- const req = request2(
26857
- url,
26858
- {
26859
- method: "POST",
26860
- timeout: timeoutMs,
26861
- headers: {
26862
- "content-type": "application/json",
26863
- "content-length": Buffer.byteLength(payload)
26864
- }
26865
- },
26866
- (res) => {
26867
- const chunks = [];
26868
- res.on("data", (chunk) => chunks.push(chunk));
26869
- res.on("end", () => {
26870
- const headers = new Headers();
26871
- for (const [name, value] of Object.entries(res.headers)) {
26872
- for (const v of Array.isArray(value) ? value : value === void 0 ? [] : [value]) {
26873
- headers.append(name, v);
26874
- }
26875
- }
26876
- resolve2(new Response(Buffer.concat(chunks), { status: res.statusCode ?? 500, headers }));
26877
- });
26878
- res.on("error", reject);
26879
- }
26880
- );
26881
- req.on("error", reject);
26882
- req.on("timeout", () => req.destroy(new Error(`timed out after ${timeoutMs}ms`)));
26883
- req.end(payload);
26920
+
26921
+ // ../../domains/hub-auth/src/client/transport.ts
26922
+ var HUB_TRANSPORT_TIMEOUT = "HUB_TRANSPORT_TIMEOUT";
26923
+ var HubTransportTimeoutError = class extends Error {
26924
+ code = HUB_TRANSPORT_TIMEOUT;
26925
+ timeoutMs;
26926
+ constructor(timeoutMs) {
26927
+ super(`timed out after ${timeoutMs}ms`);
26928
+ this.name = "HubTransportTimeoutError";
26929
+ this.timeoutMs = timeoutMs;
26930
+ }
26931
+ };
26932
+ function isHubTransportTimeout(err) {
26933
+ return typeof err === "object" && err !== null && err.code === HUB_TRANSPORT_TIMEOUT;
26934
+ }
26935
+ function transportErrorText(err) {
26936
+ return err instanceof Error ? err.message : String(err);
26937
+ }
26938
+
26939
+ // ../../domains/hub-auth/src/client/protocol.ts
26940
+ var HUB_AUTH_PATHS = {
26941
+ health: "/health",
26942
+ signInEmail: "/api/auth/sign-in/email",
26943
+ deviceCode: "/api/auth/device/code",
26944
+ deviceToken: "/api/auth/device/token",
26945
+ session: "/api/auth/get-session"
26946
+ };
26947
+ var HUB_DEVICE_CLIENT_IDS = {
26948
+ cli: "slayzone-cli",
26949
+ desktop: "slayzone-desktop"
26950
+ };
26951
+ var DEVICE_CODE_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:device_code";
26952
+ var HEALTH_MAX_CHARS = 4096;
26953
+ var AUTH_MAX_CHARS = 65536;
26954
+ var AUTH_TIMEOUT_MS = 1e4;
26955
+ function parseJson(text) {
26956
+ try {
26957
+ return JSON.parse(text);
26958
+ } catch {
26959
+ return void 0;
26960
+ }
26961
+ }
26962
+ function jsonObject(text) {
26963
+ const parsed = parseJson(text);
26964
+ return parsed && typeof parsed === "object" ? parsed : {};
26965
+ }
26966
+ function stringOf(value) {
26967
+ return typeof value === "string" ? value : void 0;
26968
+ }
26969
+ function postJson2(transport, url, body, timeoutMs) {
26970
+ return transport({
26971
+ method: "POST",
26972
+ url,
26973
+ headers: { "content-type": "application/json" },
26974
+ body: JSON.stringify(body),
26975
+ timeoutMs,
26976
+ maxResponseChars: AUTH_MAX_CHARS
26884
26977
  });
26885
26978
  }
26886
- async function readSignInMethods(baseUrl) {
26979
+
26980
+ // ../../domains/hub-auth/src/client/health.ts
26981
+ async function fetchHubHealth(transport, baseUrl, timeoutMs) {
26982
+ try {
26983
+ const res = await transport({
26984
+ method: "GET",
26985
+ url: `${baseUrl}${HUB_AUTH_PATHS.health}`,
26986
+ headers: {},
26987
+ timeoutMs,
26988
+ maxResponseChars: HEALTH_MAX_CHARS
26989
+ });
26990
+ return { reachable: true, status: res.status, json: parseJson(res.text) };
26991
+ } catch (err) {
26992
+ return isHubTransportTimeout(err) ? {
26993
+ reachable: false,
26994
+ reason: "timeout",
26995
+ error: `Health check timed out after ${timeoutMs}ms`
26996
+ } : { reachable: false, reason: "unreachable", error: transportErrorText(err) };
26997
+ }
26998
+ }
26999
+ function signInMethodsOf(health) {
27000
+ if (health === null || health === void 0) return void 0;
27001
+ const switches = health.switches;
27002
+ if (!switches) return void 0;
27003
+ const sw = switches;
27004
+ return { sso: sw.enableSso === true, password: sw.enablePassword !== false };
27005
+ }
27006
+
27007
+ // ../../domains/hub-auth/src/client/password.ts
27008
+ async function signInWithPassword(transport, baseUrl, credentials, timeoutMs = AUTH_TIMEOUT_MS) {
26887
27009
  let res;
26888
27010
  try {
26889
- res = await fetch(`${baseUrl}/health`, { signal: AbortSignal.timeout(1e4) });
26890
- } catch {
26891
- fail(`Could not reach the hub at ${baseUrl}.`);
27011
+ res = await postJson2(
27012
+ transport,
27013
+ `${baseUrl}${HUB_AUTH_PATHS.signInEmail}`,
27014
+ { email: credentials.email, password: credentials.password },
27015
+ timeoutMs
27016
+ );
27017
+ } catch (err) {
27018
+ return isHubTransportTimeout(err) ? { ok: false, reason: "timeout", error: `Sign-in timed out after ${timeoutMs}ms` } : { ok: false, reason: "unreachable", error: transportErrorText(err) };
27019
+ }
27020
+ const { status } = res;
27021
+ if (status >= 400) {
27022
+ const body2 = jsonObject(res.text);
27023
+ return {
27024
+ ok: false,
27025
+ reason: "refused",
27026
+ status,
27027
+ code: stringOf(body2.code),
27028
+ hubError: stringOf(body2.error),
27029
+ error: `Sign-in failed (HTTP ${status})`
27030
+ };
27031
+ }
27032
+ const headerToken = res.header("set-auth-token");
27033
+ if (headerToken) return { ok: true, token: headerToken };
27034
+ const body = parseJson(res.text);
27035
+ if (body === null || body === void 0) {
27036
+ return { ok: false, reason: "bad-response", status, error: "Bad sign-in response" };
27037
+ }
27038
+ const token = body.token;
27039
+ if (typeof token === "string" && token) return { ok: true, token };
27040
+ return { ok: false, reason: "no-token", status, error: "Hub returned no token" };
27041
+ }
27042
+
27043
+ // ../../domains/hub-auth/src/client/device.ts
27044
+ async function requestDeviceCode(transport, baseUrl, clientId, timeoutMs = AUTH_TIMEOUT_MS) {
27045
+ let res;
27046
+ try {
27047
+ res = await postJson2(
27048
+ transport,
27049
+ `${baseUrl}${HUB_AUTH_PATHS.deviceCode}`,
27050
+ { client_id: clientId },
27051
+ timeoutMs
27052
+ );
27053
+ } catch (err) {
27054
+ return {
27055
+ ok: false,
27056
+ reason: isHubTransportTimeout(err) ? "timeout" : "unreachable",
27057
+ error: transportErrorText(err)
27058
+ };
27059
+ }
27060
+ const j = jsonObject(res.text);
27061
+ const deviceCode = stringOf(j.device_code) ?? "";
27062
+ const userCode = stringOf(j.user_code) ?? "";
27063
+ const page = stringOf(j.verification_uri_complete) || stringOf(j.verification_uri) || "";
27064
+ if (res.status !== 200 || !deviceCode || !userCode || !page) {
27065
+ const description = stringOf(j.error_description);
27066
+ return {
27067
+ ok: false,
27068
+ reason: "refused",
27069
+ status: res.status,
27070
+ description,
27071
+ error: `The hub did not start a sign-in (HTTP ${res.status})${description ? `: ${description}` : ""}`
27072
+ };
26892
27073
  }
26893
- const health = await res.json().catch(() => ({}));
26894
27074
  return {
26895
- sso: health.switches?.enableSso === true,
26896
- password: health.switches?.enablePassword !== false
27075
+ ok: true,
27076
+ deviceCode,
27077
+ userCode: `${userCode.slice(0, 4)}-${userCode.slice(4)}`,
27078
+ verificationUri: page,
27079
+ expiresInSec: typeof j.expires_in === "number" ? j.expires_in : 600,
27080
+ intervalSec: typeof j.interval === "number" ? Math.max(5, j.interval) : 5
26897
27081
  };
26898
27082
  }
27083
+ function isHubOwnPage(baseUrl, page) {
27084
+ try {
27085
+ const target = new URL(page);
27086
+ return (target.protocol === "https:" || target.protocol === "http:") && target.host === new URL(baseUrl).host;
27087
+ } catch {
27088
+ return false;
27089
+ }
27090
+ }
27091
+ var POLL_TIMEOUT_MS = 1e4;
27092
+ var SLOW_DOWN_STEP_MS = 5e3;
27093
+ var defaultSleep = (ms) => new Promise((r) => setTimeout(r, ms));
27094
+ async function waitForDeviceToken(transport, baseUrl, clientId, code, opts = {}) {
27095
+ const tokenUrl = `${baseUrl}${HUB_AUTH_PATHS.deviceToken}`;
27096
+ const sleep = opts.sleep ?? defaultSleep;
27097
+ const now = opts.now ?? Date.now;
27098
+ let intervalMs = code.intervalSec * 1e3;
27099
+ const deadline = now() + code.expiresInSec * 1e3;
27100
+ while (now() < deadline + intervalMs) {
27101
+ await sleep(intervalMs);
27102
+ if (opts.signal?.aborted) return { ok: false, reason: "cancelled", error: "Sign-in cancelled" };
27103
+ let res;
27104
+ try {
27105
+ res = await postJson2(
27106
+ transport,
27107
+ tokenUrl,
27108
+ { grant_type: DEVICE_CODE_GRANT_TYPE, device_code: code.deviceCode, client_id: clientId },
27109
+ POLL_TIMEOUT_MS
27110
+ );
27111
+ } catch {
27112
+ continue;
27113
+ }
27114
+ const { status } = res;
27115
+ const body = jsonObject(res.text);
27116
+ const { error, access_token: token } = body;
27117
+ if (status === 200 && typeof token === "string" && token) return { ok: true, token };
27118
+ if (error === "authorization_pending") continue;
27119
+ if (error === "slow_down") {
27120
+ intervalMs += SLOW_DOWN_STEP_MS;
27121
+ continue;
27122
+ }
27123
+ if (error === "access_denied") {
27124
+ return { ok: false, reason: "denied", status, error: "Sign-in was denied in the browser" };
27125
+ }
27126
+ if (error === "expired_token") {
27127
+ return { ok: false, reason: "expired", status, error: "The sign-in code expired" };
27128
+ }
27129
+ if (body.code === "ACCOUNT_DISABLED") {
27130
+ return {
27131
+ ok: false,
27132
+ reason: "disabled",
27133
+ status,
27134
+ error: "This account is disabled on the hub"
27135
+ };
27136
+ }
27137
+ const description = stringOf(body.error_description);
27138
+ return {
27139
+ ok: false,
27140
+ reason: "failed",
27141
+ status,
27142
+ description,
27143
+ error: `Sign-in failed (HTTP ${status})${description === void 0 ? "" : `: ${description}`}`
27144
+ };
27145
+ }
27146
+ return { ok: false, reason: "expired", error: "The sign-in code expired" };
27147
+ }
27148
+
27149
+ // ../../domains/hub-auth/src/client/session.ts
27150
+ async function fetchSessionEmail(transport, baseUrl, token, timeoutMs = AUTH_TIMEOUT_MS) {
27151
+ try {
27152
+ const res = await transport({
27153
+ method: "GET",
27154
+ url: `${baseUrl}${HUB_AUTH_PATHS.session}`,
27155
+ headers: { authorization: `Bearer ${token}` },
27156
+ timeoutMs,
27157
+ maxResponseChars: AUTH_MAX_CHARS
27158
+ });
27159
+ const body = parseJson(res.text);
27160
+ return typeof body?.user?.email === "string" ? body.user.email : null;
27161
+ } catch {
27162
+ return null;
27163
+ }
27164
+ }
27165
+
27166
+ // ../../domains/hub-auth/src/client/sign-in-error.ts
27167
+ var ASK_ADMIN = "If it keeps failing, ask your administrator.";
27168
+ var MESSAGES2 = {
27169
+ // T-09 refuses every ID token that fails its checks with this generic code: another
27170
+ // tenant, no MFA, no SlayZone app role, no email (the audit line names which).
27171
+ unable_to_get_user_info: "Microsoft refused this account for this hub: it may belong to another organisation, have signed in without multi-factor authentication, or not be assigned to SlayZone. Ask your administrator.",
27172
+ ACCOUNT_DISABLED: "This account is disabled on this hub. Ask your administrator.",
27173
+ account_not_linked: "The email of this Microsoft account already belongs to another account on this hub, so it cannot sign in. Ask your administrator.",
27174
+ unable_to_link_account: "This Microsoft account could not be connected to an account on this hub. Ask your administrator.",
27175
+ access_denied: "Sign-in was cancelled at Microsoft. Try again.",
27176
+ state_mismatch: "The sign-in took too long or was started in another tab. Try again.",
27177
+ please_restart_the_process: "The sign-in took too long or was started in another tab. Try again.",
27178
+ invalid_callback_request: "The sign-in took too long or was started in another tab. Try again.",
27179
+ no_session: `Microsoft sign-in did not complete. Try again. ${ASK_ADMIN}`
27180
+ };
27181
+
27182
+ // ../../domains/hub-auth/src/client-node/index.ts
27183
+ var import_node_http3 = __toESM(require("node:http"), 1);
27184
+ var import_node_https = __toESM(require("node:https"), 1);
27185
+ function firstValue(value) {
27186
+ if (Array.isArray(value)) return value[0] ?? null;
27187
+ return value ?? null;
27188
+ }
27189
+ var nodeHubTransport = (request2) => new Promise((resolve2, reject) => {
27190
+ const send = request2.url.startsWith("https:") ? import_node_https.default.request : import_node_http3.default.request;
27191
+ const headers = { ...request2.headers };
27192
+ if (request2.body !== void 0) headers["content-length"] = Buffer.byteLength(request2.body);
27193
+ const req = send(
27194
+ request2.url,
27195
+ { method: request2.method, timeout: request2.timeoutMs, headers },
27196
+ (res) => {
27197
+ let text = "";
27198
+ res.setEncoding("utf8");
27199
+ res.on("data", (chunk) => {
27200
+ if (text.length < request2.maxResponseChars) text += chunk;
27201
+ });
27202
+ res.on(
27203
+ "end",
27204
+ () => resolve2({
27205
+ status: res.statusCode ?? 0,
27206
+ header: (name) => firstValue(res.headers[name.toLowerCase()]),
27207
+ text
27208
+ })
27209
+ );
27210
+ res.on("error", reject);
27211
+ }
27212
+ );
27213
+ req.on("error", reject);
27214
+ req.on("timeout", () => req.destroy(new HubTransportTimeoutError(request2.timeoutMs)));
27215
+ req.end(request2.body);
27216
+ });
27217
+
27218
+ // src/hub-sign-in.ts
27219
+ var CLI_DEVICE_CLIENT_ID = HUB_DEVICE_CLIENT_IDS.cli;
27220
+ async function readSignInMethods(baseUrl) {
27221
+ const health = await fetchHubHealth(nodeHubTransport, baseUrl, 1e4);
27222
+ if (!health.reachable) fail(`Could not reach the hub at ${baseUrl}.`);
27223
+ return signInMethodsOf(health.json) ?? { sso: false, password: true };
27224
+ }
27225
+ async function hubSignIn(baseUrl, email, password) {
27226
+ const result = await signInWithPassword(nodeHubTransport, baseUrl, { email, password });
27227
+ if (result.ok) return result.token;
27228
+ if (result.reason === "unreachable" || result.reason === "timeout") {
27229
+ fail(`Could not reach the hub at ${baseUrl}.`);
27230
+ }
27231
+ if (result.reason === "refused") {
27232
+ if (result.code === "HUB_PASSWORD_DISABLED") {
27233
+ fail(`Sign-in refused: ${result.hubError ?? "password sign-in is off on this hub"}`);
27234
+ }
27235
+ if (result.code === "ACCOUNT_DISABLED") {
27236
+ fail(
27237
+ "Sign-in refused: this account is disabled on the hub. An operator can enable it with `slay hub users enable <email>`."
27238
+ );
27239
+ }
27240
+ fail(
27241
+ `Sign-in failed (HTTP ${result.status}).
27242
+ Check the email and password. List the accounts on the hub box with \`slay hub users ls\`, or create one with \`slay hub users add <email>\`.`
27243
+ );
27244
+ }
27245
+ fail("The hub accepted the sign-in but returned no token.");
27246
+ }
26899
27247
  function tryOpenBrowser(url) {
26900
27248
  if (!/^https?:\/\//.test(url)) return;
26901
27249
  if (process.env.SSH_CONNECTION || process.env.SSH_TTY) return;
@@ -26917,76 +27265,44 @@ function tryOpenBrowser(url) {
26917
27265
  } catch {
26918
27266
  }
26919
27267
  }
26920
- var sleep = (ms) => new Promise((r) => setTimeout(r, ms));
27268
+ function openApprovalPage(baseUrl, page, open = tryOpenBrowser) {
27269
+ if (!isHubOwnPage(baseUrl, page)) return false;
27270
+ open(page);
27271
+ return true;
27272
+ }
26921
27273
  async function deviceSignIn(baseUrl, opts) {
26922
27274
  const clientId = opts.clientId ?? CLI_DEVICE_CLIENT_ID;
26923
- let res;
26924
- try {
26925
- res = await postAuthJson(`${baseUrl}/api/auth/device/code`, { client_id: clientId });
26926
- } catch {
26927
- fail(`Could not reach the hub at ${baseUrl}.`);
26928
- }
26929
- const code = await res.json().catch(() => ({}));
26930
- if (!res.ok || !code.device_code || !code.user_code || !code.verification_uri) {
27275
+ const code = await requestDeviceCode(nodeHubTransport, baseUrl, clientId);
27276
+ if (!code.ok) {
27277
+ if (code.reason !== "refused") fail(`Could not reach the hub at ${baseUrl}.`);
26931
27278
  fail(
26932
- `The hub did not start a sign-in (HTTP ${res.status})` + (typeof code.error_description === "string" ? `: ${code.error_description}` : ".")
27279
+ `The hub did not start a sign-in (HTTP ${code.status})` + (code.description !== void 0 ? `: ${code.description}` : ".")
26933
27280
  );
26934
27281
  }
26935
- const page = code.verification_uri_complete ?? code.verification_uri;
26936
- const userCode = `${code.user_code.slice(0, 4)}-${code.user_code.slice(4)}`;
26937
- const minutes = Math.round((code.expires_in ?? 600) / 60);
27282
+ const page = code.verificationUri;
27283
+ const minutes = Math.round(code.expiresInSec / 60);
26938
27284
  console.log("To sign in, open this page in a browser (on any device) and approve:");
26939
27285
  console.log(` ${page}`);
26940
- console.log(`Check that the page shows this code: ${userCode} (valid ${minutes} min)`);
26941
- if (opts.openBrowser) tryOpenBrowser(page);
27286
+ console.log(`Check that the page shows this code: ${code.userCode} (valid ${minutes} min)`);
27287
+ if (opts.openBrowser && !openApprovalPage(baseUrl, page)) {
27288
+ console.log("Not opening it automatically: the page is not on this hub.");
27289
+ }
26942
27290
  console.log("Waiting for approval\u2026");
26943
- let intervalMs = Math.max(5, code.interval ?? 5) * 1e3;
26944
- const deadline = Date.now() + (code.expires_in ?? 600) * 1e3;
26945
- while (Date.now() < deadline + intervalMs) {
26946
- await sleep(intervalMs);
26947
- let poll;
26948
- try {
26949
- poll = await postAuthJson(`${baseUrl}/api/auth/device/token`, {
26950
- grant_type: DEVICE_GRANT,
26951
- device_code: code.device_code,
26952
- client_id: clientId
26953
- });
26954
- } catch {
26955
- continue;
26956
- }
26957
- const body = await poll.json().catch(() => ({}));
26958
- if (poll.ok && typeof body.access_token === "string" && body.access_token) {
26959
- return body.access_token;
26960
- }
26961
- if (body.error === "authorization_pending") continue;
26962
- if (body.error === "slow_down") {
26963
- intervalMs += 5e3;
26964
- continue;
26965
- }
26966
- if (body.error === "access_denied") fail("Sign-in was denied in the browser.");
26967
- if (body.error === "expired_token") {
26968
- fail("The code expired before it was approved. Run `slay hub login` again.");
26969
- }
26970
- if (body.code === "ACCOUNT_DISABLED") {
26971
- fail("Sign-in refused: this account is disabled on the hub. Ask a hub admin to enable it.");
26972
- }
26973
- fail(
26974
- `Sign-in failed (HTTP ${poll.status})` + (typeof body.error_description === "string" ? `: ${body.error_description}` : ".")
26975
- );
27291
+ const result = await waitForDeviceToken(nodeHubTransport, baseUrl, clientId, code);
27292
+ if (result.ok) return result.token;
27293
+ if (result.reason === "denied") fail("Sign-in was denied in the browser.");
27294
+ if (result.reason === "expired") {
27295
+ fail("The code expired before it was approved. Run `slay hub login` again.");
26976
27296
  }
26977
- fail("The code expired before it was approved. Run `slay hub login` again.");
26978
- }
26979
- async function signedInEmail(baseUrl, token) {
26980
- try {
26981
- const res = await fetch(`${baseUrl}/api/auth/get-session`, {
26982
- headers: { authorization: `Bearer ${token}` },
26983
- signal: AbortSignal.timeout(1e4)
26984
- });
26985
- const body = await res.json().catch(() => null);
26986
- return typeof body?.user?.email === "string" ? body.user.email : null;
26987
- } catch {
26988
- return null;
27297
+ if (result.reason === "disabled") {
27298
+ fail("Sign-in refused: this account is disabled on the hub. Ask a hub admin to enable it.");
26989
27299
  }
27300
+ fail(
27301
+ `Sign-in failed (HTTP ${result.status})` + (result.description !== void 0 ? `: ${result.description}` : ".")
27302
+ );
27303
+ }
27304
+ function signedInEmail(baseUrl, token) {
27305
+ return fetchSessionEmail(nodeHubTransport, baseUrl, token);
26990
27306
  }
26991
27307
 
26992
27308
  // ../../shared/platform/src/hub-auth-secret.ts
@@ -27102,21 +27418,22 @@ function hubBreakGlassCommand() {
27102
27418
  }
27103
27419
  const outcome = await redeem(url, verifier);
27104
27420
  if (outcome.ok) {
27105
- const configPath = writeHubConfig(url, outcome.token);
27421
+ const sessionPath = writeBreakGlassSession({
27422
+ url,
27423
+ token: outcome.token,
27424
+ expiresAt: outcome.expiresAt
27425
+ });
27106
27426
  console.log(
27107
27427
  `
27108
27428
  Break-glass session open as ${outcome.email} until ${outcome.expiresAt}.`
27109
27429
  );
27110
- console.log(`Token stored: ${configPath} (it replaces the stored hub target).`);
27430
+ console.log(
27431
+ `Session stored: ${sessionPath}. Hub commands use it until it ends; the stored hub target is unchanged.`
27432
+ );
27111
27433
  console.log("");
27112
27434
  console.log(" slay hub users ls | disable <email> | enable <email>");
27113
27435
  console.log(" slay hub computers ls | revoke <id> | unrevoke <id>");
27114
27436
  console.log(" slay hub break-glass end (when done)");
27115
- if (process.env.SLAYZONE_HUB_TOKEN) {
27116
- console.error(
27117
- "Note: SLAYZONE_HUB_TOKEN is set in the environment and takes precedence over this token."
27118
- );
27119
- }
27120
27437
  return;
27121
27438
  }
27122
27439
  if (outcome.status === 403) {
@@ -27130,21 +27447,37 @@ Break-glass session open as ${outcome.email} until ${outcome.expiresAt}.`
27130
27447
  }
27131
27448
  });
27132
27449
  cmd.command("end").description("End this CLI\u2019s break-glass session now and forget its token").action(async () => {
27133
- const target = resolveHubTarget();
27450
+ const session = readBreakGlassSession();
27451
+ const target = session ? { baseUrl: session.url, token: session.token, source: "break-glass" } : resolveHubCommandTarget();
27134
27452
  if (!target?.token?.startsWith(BREAK_GLASS_TOKEN_PREFIX)) {
27135
27453
  fail(
27136
27454
  "No break-glass session is stored for this CLI. On the hub machine, `slayzone-hub break-glass end` ends any."
27137
27455
  );
27138
27456
  }
27139
- await hubRequest({
27140
- target,
27141
- path: BREAK_GLASS_PATH,
27142
- method: "DELETE",
27143
- unwrap: "raw",
27144
- hints: { 401: "The session has already ended (expired, or ended on the hub machine)." }
27145
- });
27146
- if (!process.env.SLAYZONE_HUB_ADDRESS) removeHubConfig();
27147
- console.log("Break-glass session ended: the account is disabled and its token forgotten.");
27457
+ let res;
27458
+ try {
27459
+ res = await fetch(`${target.baseUrl}${BREAK_GLASS_PATH}`, {
27460
+ method: "DELETE",
27461
+ headers: { Authorization: `Bearer ${target.token}` },
27462
+ signal: AbortSignal.timeout(1e4)
27463
+ });
27464
+ } catch {
27465
+ fail(
27466
+ `Could not reach the hub at ${target.baseUrl}. The session stays stored; it ends on its own when it expires.`
27467
+ );
27468
+ }
27469
+ const alreadyEnded = res.status === 401;
27470
+ if (!res.ok && !alreadyEnded) {
27471
+ const body = await res.json().catch(() => ({}));
27472
+ fail(
27473
+ `Break-glass end failed: ${typeof body.error === "string" ? body.error : `HTTP ${res.status}`}`
27474
+ );
27475
+ }
27476
+ if (target.source === "break-glass") removeBreakGlassSession();
27477
+ else if (target.source === "file") removeHubConfig();
27478
+ console.log(
27479
+ alreadyEnded ? "The break-glass session had already ended (expired, or ended on the hub machine); its token is forgotten." : "Break-glass session ended: the account is disabled and its token forgotten."
27480
+ );
27148
27481
  });
27149
27482
  return cmd;
27150
27483
  }
@@ -27409,37 +27742,6 @@ async function readPasswordFromStdin() {
27409
27742
  for await (const chunk of process.stdin) chunks.push(chunk);
27410
27743
  return Buffer.concat(chunks).toString("utf8").replace(/\r?\n$/, "");
27411
27744
  }
27412
- async function hubSignIn(baseUrl, email, password) {
27413
- let res;
27414
- try {
27415
- res = await postAuthJson(`${baseUrl}/api/auth/sign-in/email`, { email, password });
27416
- } catch {
27417
- fail(`Could not reach the hub at ${baseUrl}.`);
27418
- }
27419
- if (!res.ok) {
27420
- const body2 = await res.json().catch(() => ({}));
27421
- const code = body2.code;
27422
- if (code === "HUB_PASSWORD_DISABLED") {
27423
- fail(
27424
- `Sign-in refused: ${typeof body2.error === "string" ? body2.error : "password sign-in is off on this hub"}`
27425
- );
27426
- }
27427
- if (code === "ACCOUNT_DISABLED") {
27428
- fail(
27429
- "Sign-in refused: this account is disabled on the hub. An operator can enable it with `slay hub users enable <email>`."
27430
- );
27431
- }
27432
- fail(
27433
- `Sign-in failed (HTTP ${res.status}).
27434
- Check the email and password. List the accounts on the hub box with \`slay hub users ls\`, or create one with \`slay hub users add <email>\`.`
27435
- );
27436
- }
27437
- const header = res.headers.get("set-auth-token");
27438
- if (header) return header;
27439
- const body = await res.json().catch(() => ({}));
27440
- if (typeof body.token === "string" && body.token) return body.token;
27441
- fail("The hub accepted the sign-in but returned no token.");
27442
- }
27443
27745
  function hubUsersRequest(method, body) {
27444
27746
  return resolveHubRequestTarget("hub users \u2026", discoverAllHubs).then(
27445
27747
  (target) => hubRequest({
@@ -27519,6 +27821,38 @@ function hubUsersCommand() {
27519
27821
  });
27520
27822
  return users;
27521
27823
  }
27824
+ function noteStoredTargetScope() {
27825
+ if (isTaskTerminal()) {
27826
+ console.error(
27827
+ "Note: this is a task terminal. Task commands here (tasks, artifacts, pty, \u2026) keep\ngoing to the hub that spawned it; hub commands (hub users, hub computers,\ncomputer mint) use this target. `slay hub current` shows both."
27828
+ );
27829
+ } else if (process.env.SLAYZONE_HUB_ADDRESS) {
27830
+ console.error("Note: SLAYZONE_HUB_ADDRESS is set and takes precedence over this config.");
27831
+ }
27832
+ }
27833
+ function describeTargetSource(target) {
27834
+ switch (target.source) {
27835
+ case "flag":
27836
+ return "--hub";
27837
+ case "break-glass":
27838
+ return `break-glass session, ${getBreakGlassSessionPath()}`;
27839
+ case "env":
27840
+ return isTaskTerminal() ? "SLAYZONE_HUB_ADDRESS (the hub that spawned this task terminal)" : "SLAYZONE_HUB_ADDRESS env";
27841
+ case "file":
27842
+ return `${getHubConfigPath()} (slay hub use / login)`;
27843
+ }
27844
+ }
27845
+ async function probeHealth(target) {
27846
+ try {
27847
+ const res = await fetch(`${target.baseUrl}/health`, {
27848
+ headers: target.token ? { Authorization: `Bearer ${target.token}` } : {},
27849
+ signal: AbortSignal.timeout(5e3)
27850
+ });
27851
+ return res.ok ? { ok: true, line: `Health: ok (HTTP ${res.status})` } : { ok: false, line: `Health: failed (HTTP ${res.status})` };
27852
+ } catch {
27853
+ return { ok: false, line: `Health: unreachable (could not connect to ${target.baseUrl})` };
27854
+ }
27855
+ }
27522
27856
  function hubCommand() {
27523
27857
  const cmd = new Command("hub").description("Run, list and target SlayZone hubs").showSuggestionAfterError(true).showHelpAfterError(true);
27524
27858
  cmd.command("ls").description("List the hubs running on this machine").option("--json", "Output as JSON").action(async (opts) => {
@@ -27815,9 +28149,7 @@ then \`slay hub start ${name}\`.`
27815
28149
  const configPath = writeHubConfig(url, opts.token ?? null);
27816
28150
  console.log(`Now targeting: ${url}`);
27817
28151
  console.log(`Config written: ${configPath}`);
27818
- if (process.env.SLAYZONE_HUB_ADDRESS) {
27819
- console.error("Note: SLAYZONE_HUB_ADDRESS is set and takes precedence over this config.");
27820
- }
28152
+ noteStoredTargetScope();
27821
28153
  });
27822
28154
  cmd.command("login <url>").description("Sign in to a hub and store its bearer token for this CLI").option(
27823
28155
  "--email <email>",
@@ -27858,6 +28190,7 @@ then \`slay hub start ${name}\`.`
27858
28190
  const configPath = writeHubConfig(url, token);
27859
28191
  console.log(`Signed in to ${url} as ${who}.`);
27860
28192
  console.log(`Token stored: ${configPath}`);
28193
+ noteStoredTargetScope();
27861
28194
  if (process.env.SLAYZONE_HUB_TOKEN) {
27862
28195
  console.error(
27863
28196
  "Note: SLAYZONE_HUB_TOKEN is set in the environment and takes precedence over this config."
@@ -27865,37 +28198,44 @@ then \`slay hub start ${name}\`.`
27865
28198
  }
27866
28199
  }
27867
28200
  );
27868
- cmd.command("current").description("Show which hub this CLI targets, and probe it").action(async () => {
27869
- const target = resolveHubTarget();
27870
- if (!target) {
27871
- console.log("No hub configured \u2014 using the local app.");
27872
- return;
27873
- }
27874
- const source = process.env.SLAYZONE_HUB_ADDRESS ? "SLAYZONE_HUB_ADDRESS env" : getHubConfigPath();
27875
- console.log(`Hub: ${target.baseUrl}`);
27876
- console.log(`Source: ${source}`);
27877
- console.log(`Token: ${target.token ? "set" : "not set"}`);
27878
- try {
27879
- const headers = target.token ? { Authorization: `Bearer ${target.token}` } : {};
27880
- const res = await fetch(`${target.baseUrl}/health`, {
27881
- headers,
27882
- signal: AbortSignal.timeout(5e3)
27883
- });
27884
- if (res.ok) {
27885
- console.log(`Health: ok (HTTP ${res.status})`);
27886
- } else {
27887
- console.error(`Health: failed (HTTP ${res.status})`);
27888
- process.exit(1);
28201
+ cmd.command("current").description("Show which hub task commands and hub commands target, and probe them").action(async () => {
28202
+ const probes = /* @__PURE__ */ new Map();
28203
+ let healthy = true;
28204
+ const blocks = [
28205
+ [
28206
+ "Task commands (tasks, artifacts, pty, \u2026)",
28207
+ resolveTaskCommandTarget(),
28208
+ "the local app (no hub configured)"
28209
+ ],
28210
+ [
28211
+ "Hub commands (hub users, hub computers, computer mint)",
28212
+ resolveHubCommandTarget(),
28213
+ "none configured: the one hub running on this machine, if exactly one is"
28214
+ ]
28215
+ ];
28216
+ for (const [label, target, none] of blocks) {
28217
+ console.log(`${label}:`);
28218
+ if (!target) {
28219
+ console.log(` Hub: ${none}`);
28220
+ continue;
27889
28221
  }
27890
- } catch {
27891
- console.error(`Health: unreachable (could not connect to ${target.baseUrl})`);
27892
- process.exit(1);
27893
- }
28222
+ console.log(` Hub: ${target.baseUrl}`);
28223
+ console.log(` Source: ${describeTargetSource(target)}`);
28224
+ console.log(` Token: ${target.token ? "set" : "not set"}`);
28225
+ const key = `${target.baseUrl}
28226
+ ${target.token ?? ""}`;
28227
+ if (!probes.has(key)) probes.set(key, probeHealth(target));
28228
+ const result = await probes.get(key);
28229
+ if (result.ok) console.log(` ${result.line}`);
28230
+ else console.error(` ${result.line}`);
28231
+ healthy &&= result.ok;
28232
+ }
28233
+ if (!healthy) process.exit(1);
27894
28234
  });
27895
28235
  cmd.command("forget").description("Drop the stored hub target (back to the local app)").action(() => {
27896
28236
  const removed = removeHubConfig();
27897
28237
  console.log(removed ? `Removed: ${getHubConfigPath()}` : "No hub target to remove.");
27898
- if (process.env.SLAYZONE_HUB_ADDRESS) {
28238
+ if (process.env.SLAYZONE_HUB_ADDRESS && !isTaskTerminal()) {
27899
28239
  console.error("Note: SLAYZONE_HUB_ADDRESS is still set in the environment.");
27900
28240
  }
27901
28241
  });
@@ -27977,7 +28317,7 @@ async function hubComputers() {
27977
28317
  let baseUrl;
27978
28318
  let token = null;
27979
28319
  try {
27980
- const configured = resolveHubTarget();
28320
+ const configured = resolveHubCommandTarget();
27981
28321
  if (configured) {
27982
28322
  baseUrl = configured.baseUrl;
27983
28323
  token = configured.token;
@@ -28762,7 +29102,7 @@ function updateCommand() {
28762
29102
  }
28763
29103
 
28764
29104
  // src/index.ts
28765
- var program2 = new Command().name("slay").description("SlayZone CLI").version("0.36.1").option("--dev", "Use development database (slayzone.dev.data.sqlite)").option("--hub <name|port>", "Target a specific hub on this machine (see `slay hub ls`)").showSuggestionAfterError(true).showHelpAfterError(true).hook("preAction", async (thisCommand) => {
29105
+ var program2 = new Command().name("slay").description("SlayZone CLI").version("0.36.2").option("--dev", "Use development database (slayzone.dev.data.sqlite)").option("--hub <name|port>", "Target a specific hub on this machine (see `slay hub ls`)").showSuggestionAfterError(true).showHelpAfterError(true).hook("preAction", async (thisCommand) => {
28766
29106
  const root = thisCommand.parent ?? thisCommand;
28767
29107
  const opts = root.opts();
28768
29108
  if (opts.dev) process.env.SLAYZONE_DEV = "1";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@slayzone/cli",
3
- "version": "0.36.1",
3
+ "version": "0.36.2",
4
4
  "description": "SlayZone CLI — run, list and target SlayZone hubs; drive tasks, ptys and projects",
5
5
  "license": "GPL-3.0-only",
6
6
  "private": false,