@nouter/platform-cli 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +14 -0
  2. package/dist/index.js +957 -51
  3. package/package.json +5 -5
package/README.md CHANGED
@@ -11,6 +11,20 @@ Repository: <https://github.com/Nouter-ai/platform>
11
11
 
12
12
  ## Install
13
13
 
14
+ If the repository keeps the `apply` documents (agents and environments as
15
+ files), add the CLI as a devDependency and commit the lockfile: everyone and the
16
+ CI run the same version.
17
+
18
+ ```bash
19
+ npm i -D @nouter/platform-cli
20
+ npx nouter-platform apply -f ./resources --dry-run
21
+ ```
22
+
23
+ With pnpm, `pnpm add -D @nouter/platform-cli` and
24
+ `pnpm exec nouter-platform apply -f ./resources --dry-run` do the same.
25
+
26
+ The global install is for a one-off use outside a repo:
27
+
14
28
  ```bash
15
29
  npm i -g @nouter/platform-cli
16
30
  ```
package/dist/index.js CHANGED
@@ -7228,13 +7228,13 @@ var require_public_api = __commonJS({
7228
7228
  var identity = require_identity();
7229
7229
  var lineCounter = require_line_counter();
7230
7230
  var parser = require_parser();
7231
- function parseOptions(options) {
7231
+ function parseOptions2(options) {
7232
7232
  const prettyErrors = options.prettyErrors !== false;
7233
7233
  const lineCounter$1 = options.lineCounter || prettyErrors && new lineCounter.LineCounter() || null;
7234
7234
  return { lineCounter: lineCounter$1, prettyErrors };
7235
7235
  }
7236
7236
  function parseAllDocuments2(source, options = {}) {
7237
- const { lineCounter: lineCounter2, prettyErrors } = parseOptions(options);
7237
+ const { lineCounter: lineCounter2, prettyErrors } = parseOptions2(options);
7238
7238
  const parser$1 = new parser.Parser(lineCounter2?.addNewLine);
7239
7239
  const composer$1 = new composer.Composer(options);
7240
7240
  const docs = Array.from(composer$1.compose(parser$1.parse(source)));
@@ -7248,7 +7248,7 @@ var require_public_api = __commonJS({
7248
7248
  return Object.assign([], { empty: true }, composer$1.streamInfo());
7249
7249
  }
7250
7250
  function parseDocument(source, options = {}) {
7251
- const { lineCounter: lineCounter2, prettyErrors } = parseOptions(options);
7251
+ const { lineCounter: lineCounter2, prettyErrors } = parseOptions2(options);
7252
7252
  const parser$1 = new parser.Parser(lineCounter2?.addNewLine);
7253
7253
  const composer$1 = new composer.Composer(options);
7254
7254
  let doc = null;
@@ -7377,14 +7377,15 @@ import {
7377
7377
  lstatSync,
7378
7378
  mkdirSync,
7379
7379
  openSync,
7380
- readFileSync as readFileSync2,
7380
+ readFileSync as readFileSync3,
7381
7381
  renameSync,
7382
7382
  statSync as statSync2,
7383
7383
  unlinkSync,
7384
7384
  writeSync
7385
7385
  } from "node:fs";
7386
7386
  import { homedir, hostname } from "node:os";
7387
- import { join as join2 } from "node:path";
7387
+ import { dirname, join as join2 } from "node:path";
7388
+ import { fileURLToPath } from "node:url";
7388
7389
  import {
7389
7390
  NouterPlatform
7390
7391
  } from "@nouter/platform";
@@ -8248,6 +8249,339 @@ function formatApplyResults(results) {
8248
8249
  return lines;
8249
8250
  }
8250
8251
 
8252
+ // src/commands.ts
8253
+ var COMMANDS = [
8254
+ {
8255
+ path: "login",
8256
+ summary: "Store an API key (from stdin) or log in through the browser",
8257
+ values: [],
8258
+ booleans: ["--api-key", "--browser"],
8259
+ positionals: []
8260
+ },
8261
+ {
8262
+ path: "logout",
8263
+ summary: "Remove the stored API key from this machine",
8264
+ values: [],
8265
+ booleans: [],
8266
+ positionals: []
8267
+ },
8268
+ {
8269
+ path: "whoami",
8270
+ summary: "Show the organization, the role and the scopes",
8271
+ values: [],
8272
+ booleans: [],
8273
+ positionals: []
8274
+ },
8275
+ {
8276
+ path: "auth status",
8277
+ summary: "Show which credential the CLI would use, without printing it",
8278
+ values: [],
8279
+ booleans: [],
8280
+ positionals: []
8281
+ },
8282
+ {
8283
+ path: "version",
8284
+ summary: "Show the CLI version and the version of the SDK it ships",
8285
+ values: [],
8286
+ booleans: [],
8287
+ positionals: []
8288
+ },
8289
+ {
8290
+ path: "agents list",
8291
+ summary: "List every agent",
8292
+ values: [],
8293
+ booleans: ["--json"],
8294
+ positionals: []
8295
+ },
8296
+ {
8297
+ path: "agents get",
8298
+ summary: "Show one agent by id",
8299
+ values: [],
8300
+ booleans: [],
8301
+ positionals: ["<agent-id>"]
8302
+ },
8303
+ {
8304
+ path: "environments list",
8305
+ summary: "List every environment",
8306
+ values: [],
8307
+ booleans: ["--json"],
8308
+ positionals: []
8309
+ },
8310
+ {
8311
+ path: "environments get",
8312
+ summary: "Show one environment by id",
8313
+ values: [],
8314
+ booleans: [],
8315
+ positionals: ["<environment-id>"]
8316
+ },
8317
+ {
8318
+ path: "service-accounts list",
8319
+ summary: "List the service accounts",
8320
+ values: [],
8321
+ booleans: ["--include-archived", "--json"],
8322
+ positionals: []
8323
+ },
8324
+ {
8325
+ path: "service-accounts create",
8326
+ summary: "Create a service account",
8327
+ values: ["--name", "--organization-role"],
8328
+ booleans: ["--json"],
8329
+ positionals: []
8330
+ },
8331
+ {
8332
+ path: "service-accounts archive",
8333
+ summary: "Archive a service account by id",
8334
+ values: [],
8335
+ booleans: [],
8336
+ positionals: ["<service-account-id>"]
8337
+ },
8338
+ {
8339
+ path: "federation issuers list",
8340
+ summary: "List the federation issuers",
8341
+ values: [],
8342
+ booleans: ["--include-archived", "--json"],
8343
+ positionals: []
8344
+ },
8345
+ {
8346
+ path: "federation issuers create",
8347
+ summary: "Create a federation issuer",
8348
+ values: ["--name", "--provider", "--issuer-url", "--jwks-url", "--check-jti", "--max-token-lifetime"],
8349
+ booleans: ["--json"],
8350
+ positionals: []
8351
+ },
8352
+ {
8353
+ path: "federation issuers archive",
8354
+ summary: "Archive a federation issuer by id",
8355
+ values: [],
8356
+ booleans: [],
8357
+ positionals: ["<issuer-id>"]
8358
+ },
8359
+ {
8360
+ path: "federation rules list",
8361
+ summary: "List the federation rules, optionally by issuer",
8362
+ values: ["--issuer"],
8363
+ booleans: ["--include-archived", "--json"],
8364
+ positionals: []
8365
+ },
8366
+ {
8367
+ path: "federation rules create",
8368
+ summary: "Create a federation rule",
8369
+ values: [
8370
+ "--name",
8371
+ "--issuer",
8372
+ "--service-account",
8373
+ "--subject-prefix",
8374
+ "--audience",
8375
+ "--claim",
8376
+ "--workspace",
8377
+ "--scopes",
8378
+ "--token-lifetime"
8379
+ ],
8380
+ booleans: ["--all-workspaces", "--json"],
8381
+ positionals: []
8382
+ },
8383
+ {
8384
+ path: "federation rules archive",
8385
+ summary: "Archive a federation rule by id",
8386
+ values: [],
8387
+ booleans: [],
8388
+ positionals: ["<rule-id>"]
8389
+ },
8390
+ {
8391
+ path: "federation token",
8392
+ summary: "Exchange the federated identity for a platform access token",
8393
+ values: [],
8394
+ booleans: ["--json"],
8395
+ positionals: []
8396
+ },
8397
+ {
8398
+ path: "apply",
8399
+ summary: "Apply agents and environments from files",
8400
+ values: ["--file"],
8401
+ booleans: ["--dry-run", "--rotate-secrets"],
8402
+ positionals: [],
8403
+ shortValues: ["-f"]
8404
+ }
8405
+ ];
8406
+ var BY_PATH = new Map(COMMANDS.map((command) => [command.path, command]));
8407
+ function specFor(path) {
8408
+ const spec = BY_PATH.get(path);
8409
+ if (spec === void 0) throw new Error(`Unknown command path: ${path}`);
8410
+ return spec;
8411
+ }
8412
+
8413
+ // src/identity-token.ts
8414
+ import { readFileSync as readFileSync2 } from "node:fs";
8415
+ var IdentityTokenError = class extends Error {
8416
+ constructor(message) {
8417
+ super(message);
8418
+ this.name = "IdentityTokenError";
8419
+ }
8420
+ };
8421
+ var NON_EMPTY = (value) => typeof value === "string" && value.length > 0;
8422
+ function identityTokenSourceFromEnv(env = process.env) {
8423
+ const value = env.NOUTER_PLATFORM_IDENTITY_TOKEN;
8424
+ if (NON_EMPTY(value)) return { kind: "value", token: value };
8425
+ const path = env.NOUTER_PLATFORM_IDENTITY_TOKEN_FILE;
8426
+ if (NON_EMPTY(path)) return { kind: "file", path };
8427
+ return null;
8428
+ }
8429
+ var PRINTABLE = /^[\x21-\x7e]+$/u;
8430
+ function clean(token) {
8431
+ const trimmed = token.trim();
8432
+ if (trimmed.length === 0) throw new IdentityTokenError("The identity token is empty.");
8433
+ if (!PRINTABLE.test(trimmed)) {
8434
+ throw new IdentityTokenError("The identity token has characters the CLI cannot use.");
8435
+ }
8436
+ return trimmed;
8437
+ }
8438
+ function createIdentityTokenReader(source, read = (path) => readFileSync2(path, "utf8")) {
8439
+ if (source.kind === "value") {
8440
+ return { read: () => clean(source.token) };
8441
+ }
8442
+ return {
8443
+ read() {
8444
+ let contents;
8445
+ try {
8446
+ contents = read(source.path);
8447
+ } catch {
8448
+ throw new IdentityTokenError(`Could not read the identity token file ${source.path}.`);
8449
+ }
8450
+ return clean(contents);
8451
+ }
8452
+ };
8453
+ }
8454
+
8455
+ // src/non-api-host.ts
8456
+ function hostOf(url) {
8457
+ try {
8458
+ return new URL(url).host;
8459
+ } catch {
8460
+ return url;
8461
+ }
8462
+ }
8463
+ function notTheApiMessage(url, response) {
8464
+ const status = response.status;
8465
+ if (status >= 500) return null;
8466
+ const contentType = (response.headers.get("content-type") ?? "").trim();
8467
+ const mediaType = contentType.toLowerCase();
8468
+ const isRedirect = status >= 300 && status < 400;
8469
+ const isHtml = mediaType.startsWith("text/html");
8470
+ const followedToNonJson = response.redirected && !mediaType.includes("application/json");
8471
+ if (!isRedirect && !isHtml && !followedToNonJson) return null;
8472
+ return `this host is not the API: ${hostOf(url)} responded ${status} ${contentType || "(no content-type)"}`;
8473
+ }
8474
+
8475
+ // src/federation.ts
8476
+ var FederationError = class extends Error {
8477
+ constructor(message) {
8478
+ super(message);
8479
+ this.name = "FederationError";
8480
+ }
8481
+ };
8482
+ var GRANT_TYPE = "urn:ietf:params:oauth:grant-type:jwt-bearer";
8483
+ var REFRESH_MARGIN_SECONDS = 30;
8484
+ var MIN_EXPIRES_IN = 60;
8485
+ var MAX_EXPIRES_IN = 86400;
8486
+ var present = (value) => typeof value === "string" && value.length > 0;
8487
+ function federationSettingsFromEnv(env = process.env) {
8488
+ if (!present(env.NOUTER_PLATFORM_FEDERATION_RULE_ID)) return null;
8489
+ if (!present(env.NOUTER_PLATFORM_ORGANIZATION_ID)) {
8490
+ throw new FederationError(
8491
+ "NOUTER_PLATFORM_ORGANIZATION_ID is required when NOUTER_PLATFORM_FEDERATION_RULE_ID is set."
8492
+ );
8493
+ }
8494
+ const identityToken = identityTokenSourceFromEnv(env);
8495
+ if (identityToken === null) {
8496
+ throw new IdentityTokenError(
8497
+ "NOUTER_PLATFORM_IDENTITY_TOKEN or NOUTER_PLATFORM_IDENTITY_TOKEN_FILE is required when NOUTER_PLATFORM_FEDERATION_RULE_ID is set."
8498
+ );
8499
+ }
8500
+ return {
8501
+ ruleId: env.NOUTER_PLATFORM_FEDERATION_RULE_ID,
8502
+ organizationId: env.NOUTER_PLATFORM_ORGANIZATION_ID,
8503
+ ...present(env.NOUTER_PLATFORM_SERVICE_ACCOUNT_ID) && { serviceAccountId: env.NOUTER_PLATFORM_SERVICE_ACCOUNT_ID },
8504
+ ...present(env.NOUTER_PLATFORM_WORKSPACE_ID) && { workspaceId: env.NOUTER_PLATFORM_WORKSPACE_ID },
8505
+ identityToken
8506
+ };
8507
+ }
8508
+ function parseToken(payload) {
8509
+ if (typeof payload !== "object" || payload === null) return null;
8510
+ const body = payload;
8511
+ if (typeof body.access_token !== "string" || !body.access_token.startsWith("oma_oat_")) return null;
8512
+ if (body.token_type !== "Bearer") return null;
8513
+ if (typeof body.expires_in !== "number" || !Number.isInteger(body.expires_in) || body.expires_in < MIN_EXPIRES_IN || body.expires_in > MAX_EXPIRES_IN) {
8514
+ return null;
8515
+ }
8516
+ if (typeof body.scope !== "string" || body.scope.trim().length === 0) return null;
8517
+ return {
8518
+ accessToken: body.access_token,
8519
+ expiresIn: body.expires_in,
8520
+ scopes: body.scope.split(" ").filter((scope) => scope.length > 0)
8521
+ };
8522
+ }
8523
+ async function exchange(baseUrl, settings, assertion, fetch, timeoutMs) {
8524
+ let response;
8525
+ try {
8526
+ response = await fetch(`${baseUrl}/v1/oauth/token`, {
8527
+ method: "POST",
8528
+ headers: { "content-type": "application/json", accept: "application/json" },
8529
+ body: JSON.stringify({
8530
+ grant_type: GRANT_TYPE,
8531
+ assertion,
8532
+ federation_rule_id: settings.ruleId,
8533
+ organization_id: settings.organizationId,
8534
+ ...settings.serviceAccountId !== void 0 && { service_account_id: settings.serviceAccountId },
8535
+ ...settings.workspaceId !== void 0 && { workspace_id: settings.workspaceId }
8536
+ }),
8537
+ signal: AbortSignal.timeout(timeoutMs),
8538
+ // La aserción va en el cuerpo: si el host redirige (la consola detrás de un IdP), seguir el 3xx la llevaría a
8539
+ // otro origen. Se corta acá con el mismo mensaje que el cliente.
8540
+ redirect: "manual"
8541
+ });
8542
+ } catch {
8543
+ throw new FederationError("The federation exchange failed (network error).");
8544
+ }
8545
+ const notTheApi = notTheApiMessage(`${baseUrl}/v1/oauth/token`, response);
8546
+ if (notTheApi !== null) throw new FederationError(notTheApi);
8547
+ if (response.status === 401) {
8548
+ throw new FederationError("Authentication failed");
8549
+ }
8550
+ if (!response.ok) {
8551
+ throw new FederationError(`The federation exchange failed (the server answered ${response.status}).`);
8552
+ }
8553
+ let payload;
8554
+ try {
8555
+ payload = await response.json();
8556
+ } catch {
8557
+ throw new FederationError("The federation exchange returned an unexpected response.");
8558
+ }
8559
+ const token = parseToken(payload);
8560
+ if (token === null) throw new FederationError("The federation exchange returned an unexpected response.");
8561
+ return token;
8562
+ }
8563
+ function createFederationTokenProvider(options) {
8564
+ const now = options.now ?? Date.now;
8565
+ const reader = createIdentityTokenReader(options.settings.identityToken, options.readFile);
8566
+ let cached = null;
8567
+ return {
8568
+ async getToken() {
8569
+ const assertion = reader.read();
8570
+ const current = now();
8571
+ if (cached !== null && cached.assertion === assertion && current < cached.refreshAt) {
8572
+ return cached.token;
8573
+ }
8574
+ const token = await exchange(options.baseUrl, options.settings, assertion, options.fetch, options.timeoutMs);
8575
+ cached = {
8576
+ token,
8577
+ assertion,
8578
+ refreshAt: current + Math.max(token.expiresIn - REFRESH_MARGIN_SECONDS, 0) * 1e3
8579
+ };
8580
+ return token;
8581
+ }
8582
+ };
8583
+ }
8584
+
8251
8585
  // src/login-callback.ts
8252
8586
  import { timingSafeEqual } from "node:crypto";
8253
8587
  import { createServer } from "node:http";
@@ -8403,7 +8737,9 @@ async function readBody(request) {
8403
8737
  }
8404
8738
 
8405
8739
  // src/index.ts
8406
- var USER_AGENT = "NouterPlatform-CLI/0.1";
8740
+ function cliUserAgent() {
8741
+ return `nouter-platform-cli/${cliVersion()} node/${process.versions.node}`;
8742
+ }
8407
8743
  var REQUEST_TIMEOUT_MS = 3e4;
8408
8744
  var CONFIG_DIRECTORY = "nouter-platform";
8409
8745
  var CONFIG_FILE = "config.json";
@@ -8445,7 +8781,7 @@ function readConfig(options = {}) {
8445
8781
  }
8446
8782
  if (mode !== void 0) warnAboutLoosePermissions(path, mode, platform, warn);
8447
8783
  try {
8448
- const parsed = JSON.parse(readFileSync2(path, "utf8"));
8784
+ const parsed = JSON.parse(readFileSync3(path, "utf8"));
8449
8785
  if (typeof parsed.apiKey !== "string" || parsed.apiKey.length === 0) return null;
8450
8786
  const baseUrl = typeof parsed.baseUrl === "string" && parsed.baseUrl.length > 0 ? parsed.baseUrl : null;
8451
8787
  return { baseUrl, apiKey: parsed.apiKey };
@@ -8555,12 +8891,65 @@ function requireBaseUrl(stored, hint = BASE_URL_HINT) {
8555
8891
  }
8556
8892
  return normalizeBaseUrl(candidate);
8557
8893
  }
8558
- function resolveAuth(deps) {
8894
+ function environmentApiKey(env = process.env) {
8895
+ const documented = env.NOUTER_PLATFORM_API_KEY;
8896
+ if (documented && documented.length > 0) return { name: "NOUTER_PLATFORM_API_KEY", value: documented };
8897
+ return null;
8898
+ }
8899
+ function federationSettingsOrNull() {
8900
+ try {
8901
+ return federationSettingsFromEnv(process.env);
8902
+ } catch (error) {
8903
+ if (error instanceof FederationError || error instanceof IdentityTokenError) throw new CliError(error.message);
8904
+ throw error;
8905
+ }
8906
+ }
8907
+ var cachedFederationProvider = null;
8908
+ function federationProviderFor(baseUrl, settings, deps) {
8909
+ const key = JSON.stringify([
8910
+ baseUrl,
8911
+ settings.ruleId,
8912
+ settings.organizationId,
8913
+ settings.serviceAccountId ?? "",
8914
+ settings.workspaceId ?? "",
8915
+ settings.identityToken
8916
+ ]);
8917
+ if (cachedFederationProvider !== null && cachedFederationProvider.key === key) {
8918
+ return cachedFederationProvider.provider;
8919
+ }
8920
+ const provider = createFederationTokenProvider({
8921
+ baseUrl,
8922
+ settings,
8923
+ fetch: deps.fetch,
8924
+ timeoutMs: deps.requestTimeoutMs
8925
+ });
8926
+ cachedFederationProvider = { key, provider };
8927
+ return provider;
8928
+ }
8929
+ function federationFailure(error) {
8930
+ if (error instanceof FederationError || error instanceof IdentityTokenError) throw new CliError(error.message);
8931
+ throw error;
8932
+ }
8933
+ async function resolveAuth(deps) {
8559
8934
  const stored = readConfig({ warn: deps.writeStderr });
8560
- const envKey = process.env.NOUTER_PLATFORM_API_KEY;
8561
8935
  const envBase = process.env.NOUTER_PLATFORM_BASE_URL;
8562
- if (envKey && envKey.length > 0) {
8563
- return { baseUrl: requireBaseUrl(stored), apiKey: envKey };
8936
+ const envKey = environmentApiKey();
8937
+ const federationConfigured = typeof process.env.NOUTER_PLATFORM_FEDERATION_RULE_ID === "string" && process.env.NOUTER_PLATFORM_FEDERATION_RULE_ID.length > 0;
8938
+ if (envKey !== null) {
8939
+ if (federationConfigured) {
8940
+ deps.writeStderr(
8941
+ `Warning: ${envKey.name} is set and wins over the federation credentials; unset it to use NOUTER_PLATFORM_FEDERATION_RULE_ID.`
8942
+ );
8943
+ }
8944
+ return { baseUrl: requireBaseUrl(stored), credential: envKey.value, transport: "api-key" };
8945
+ }
8946
+ if (federationConfigured) {
8947
+ const settings = federationSettingsOrNull();
8948
+ if (settings !== null) {
8949
+ const baseUrl = requireBaseUrl(stored);
8950
+ const token = await federationProviderFor(baseUrl, settings, deps).getToken().catch(federationFailure);
8951
+ return { baseUrl, credential: token.accessToken, transport: "bearer" };
8952
+ }
8564
8953
  }
8565
8954
  if (!stored) {
8566
8955
  throw new CliError("Not authenticated. Run `nouter-platform login --api-key` or set NOUTER_PLATFORM_API_KEY.");
@@ -8578,27 +8967,38 @@ function resolveAuth(deps) {
8578
8967
  `The stored API key was saved for ${storedBaseUrl}, but NOUTER_PLATFORM_BASE_URL points to ${envBaseUrl}. Run \`nouter-platform login\` against ${envBaseUrl} to store a key for it, or set NOUTER_PLATFORM_API_KEY.`
8579
8968
  );
8580
8969
  }
8581
- return { baseUrl: envBaseUrl, apiKey: stored.apiKey };
8970
+ return { baseUrl: envBaseUrl, credential: stored.apiKey, transport: "api-key" };
8582
8971
  }
8583
- return { baseUrl: storedBaseUrl, apiKey: stored.apiKey };
8972
+ return { baseUrl: storedBaseUrl, credential: stored.apiKey, transport: "api-key" };
8584
8973
  }
8585
- function clientFor(baseUrl, apiKey, deps, options = {}) {
8586
- return new NouterPlatform({
8587
- apiKey,
8588
- baseURL: baseUrl,
8974
+ var notTheApiMiddleware = async (request, next) => {
8975
+ const response = await next({ ...request, redirect: "manual" });
8976
+ const message = notTheApiMessage(request.url, response);
8977
+ if (message !== null) throw new CliError(message);
8978
+ return response;
8979
+ };
8980
+ function clientFor(auth, deps, options = {}) {
8981
+ const common = {
8982
+ baseURL: auth.baseUrl,
8589
8983
  fetch: deps.fetch,
8590
- userAgent: USER_AGENT,
8984
+ userAgent: cliUserAgent(),
8985
+ middleware: [notTheApiMiddleware],
8591
8986
  ...options.maxRetries !== void 0 && { maxRetries: options.maxRetries }
8592
- });
8987
+ };
8988
+ return auth.transport === "bearer" ? new NouterPlatform({ ...common, authToken: auth.credential }) : new NouterPlatform({ ...common, apiKey: auth.credential });
8989
+ }
8990
+ function apiKeyAuth(baseUrl, apiKey) {
8991
+ return { baseUrl, credential: apiKey, transport: "api-key" };
8593
8992
  }
8594
- async function fetchMe(baseUrl, apiKey, deps) {
8993
+ async function fetchMe(auth, deps) {
8595
8994
  try {
8596
- return await clientFor(baseUrl, apiKey, deps).platform.request({
8995
+ return await clientFor(auth, deps).platform.request({
8597
8996
  method: "get",
8598
8997
  path: "/v1/oma/me",
8599
8998
  signal: AbortSignal.timeout(deps.requestTimeoutMs)
8600
8999
  });
8601
9000
  } catch (error) {
9001
+ if (error instanceof CliError) throw error;
8602
9002
  throw new CliError(`Could not read the account: ${describeApiFailure(error)}`);
8603
9003
  }
8604
9004
  }
@@ -8633,7 +9033,7 @@ async function loginWithApiKey(deps) {
8633
9033
  if (!/^[\x21-\x7e]+$/.test(apiKey)) {
8634
9034
  throw new CliError("The API key has characters the CLI cannot use. Pipe it in again.");
8635
9035
  }
8636
- const me = await fetchMe(baseUrl, apiKey, deps);
9036
+ const me = await fetchMe(apiKeyAuth(baseUrl, apiKey), deps);
8637
9037
  writeConfig({ baseUrl, apiKey });
8638
9038
  deps.writeStdout(`Logged in to ${organizationOf(me) ?? "the organization"}.`);
8639
9039
  return 0;
@@ -8651,7 +9051,7 @@ async function loginWithBrowser(deps) {
8651
9051
  ${consoleUrl.toString()}`);
8652
9052
  deps.openBrowser(consoleUrl.toString());
8653
9053
  const delivered = await callback.waitForResult();
8654
- const me = await fetchMe(baseUrl, delivered.token, deps);
9054
+ const me = await fetchMe(apiKeyAuth(baseUrl, delivered.token), deps);
8655
9055
  writeConfig({ baseUrl, apiKey: delivered.token });
8656
9056
  const organization = delivered.tenantName ?? organizationOf(me) ?? "the organization";
8657
9057
  deps.writeStdout(`Logged in to ${organization}.`);
@@ -8662,14 +9062,15 @@ async function loginWithBrowser(deps) {
8662
9062
  }
8663
9063
  function login(argv, deps) {
8664
9064
  const rejectedValue = argv.some((argument) => argument.startsWith("--api-key="));
8665
- const unknown = argv.filter((argument) => argument !== "--api-key" && argument !== "--browser");
9065
+ const allowed = MANUAL_FLAGS.login;
9066
+ const unknown = argv.filter((argument) => !allowed.includes(argument));
8666
9067
  if (rejectedValue || unknown.length > 0) {
8667
9068
  throw new CliError(
8668
9069
  "The API key must come from stdin: use `nouter-platform login --api-key` with no value."
8669
9070
  );
8670
9071
  }
8671
- const withApiKey = argv.includes("--api-key");
8672
- const withBrowser = argv.includes("--browser");
9072
+ const withApiKey = argv.includes(allowed[0]);
9073
+ const withBrowser = argv.includes(allowed[1]);
8673
9074
  if (withApiKey && withBrowser) {
8674
9075
  throw new CliError("Choose one way to log in: `--api-key` (from stdin) or `--browser`.");
8675
9076
  }
@@ -8695,9 +9096,9 @@ function modelOf(agent) {
8695
9096
  return model?.id ?? "";
8696
9097
  }
8697
9098
  async function listAgents(deps, json) {
8698
- const auth = resolveAuth(deps);
9099
+ const auth = await resolveAuth(deps);
8699
9100
  try {
8700
- const client = clientFor(auth.baseUrl, auth.apiKey, deps);
9101
+ const client = clientFor(auth, deps);
8701
9102
  const agents = [];
8702
9103
  for await (const agent of client.beta.agents.list()) agents.push(agent);
8703
9104
  if (json) {
@@ -8726,9 +9127,9 @@ async function listAgents(deps, json) {
8726
9127
  }
8727
9128
  }
8728
9129
  async function getAgent(id, deps) {
8729
- const auth = resolveAuth(deps);
9130
+ const auth = await resolveAuth(deps);
8730
9131
  try {
8731
- const client = clientFor(auth.baseUrl, auth.apiKey, deps);
9132
+ const client = clientFor(auth, deps);
8732
9133
  const agent = await client.beta.agents.retrieve(id);
8733
9134
  deps.writeStdout(`Name: ${agent.name}`);
8734
9135
  deps.writeStdout(`ID: ${agent.id}`);
@@ -8741,9 +9142,9 @@ async function getAgent(id, deps) {
8741
9142
  }
8742
9143
  }
8743
9144
  async function listEnvironments(deps, json) {
8744
- const auth = resolveAuth(deps);
9145
+ const auth = await resolveAuth(deps);
8745
9146
  try {
8746
- const client = clientFor(auth.baseUrl, auth.apiKey, deps);
9147
+ const client = clientFor(auth, deps);
8747
9148
  const environments = [];
8748
9149
  for await (const environment of client.beta.environments.list()) environments.push(environment);
8749
9150
  if (json) {
@@ -8771,9 +9172,9 @@ async function listEnvironments(deps, json) {
8771
9172
  }
8772
9173
  }
8773
9174
  async function getEnvironment(id, deps) {
8774
- const auth = resolveAuth(deps);
9175
+ const auth = await resolveAuth(deps);
8775
9176
  try {
8776
- const client = clientFor(auth.baseUrl, auth.apiKey, deps);
9177
+ const client = clientFor(auth, deps);
8777
9178
  const environment = await client.beta.environments.retrieve(id);
8778
9179
  deps.writeStdout(`Name: ${environment.name}`);
8779
9180
  deps.writeStdout(`ID: ${environment.id}`);
@@ -8784,6 +9185,443 @@ async function getEnvironment(id, deps) {
8784
9185
  throw new CliError(`Could not read environment ${id}: ${describeApiFailure(error)}`);
8785
9186
  }
8786
9187
  }
9188
+ var MANUAL_FLAGS = {
9189
+ login: ["--api-key", "--browser"],
9190
+ "agents list": ["--json"],
9191
+ "agents get": [],
9192
+ "environments list": ["--json"],
9193
+ "environments get": [],
9194
+ apply: ["--file", "-f", "--dry-run", "--rotate-secrets"]
9195
+ };
9196
+ function parseOptions(args, spec) {
9197
+ const values = /* @__PURE__ */ new Map();
9198
+ const booleans = /* @__PURE__ */ new Set();
9199
+ const positionals = [];
9200
+ const booleanNames = spec.booleans ?? [];
9201
+ for (let index = 0; index < args.length; index += 1) {
9202
+ const argument = args[index];
9203
+ if (!argument.startsWith("--")) {
9204
+ positionals.push(argument);
9205
+ continue;
9206
+ }
9207
+ const equals = argument.indexOf("=");
9208
+ const name = equals === -1 ? argument : argument.slice(0, equals);
9209
+ const inline = equals === -1 ? void 0 : argument.slice(equals + 1);
9210
+ if (booleanNames.includes(name)) {
9211
+ if (inline !== void 0) throw new CliError(`The option ${name} takes no value.`);
9212
+ booleans.add(name);
9213
+ continue;
9214
+ }
9215
+ if (!spec.values.includes(name)) throw new CliError(`Unknown option: ${name}.`);
9216
+ const value = inline ?? args[index + 1];
9217
+ if (value === void 0) throw new CliError(`The option ${name} needs a value.`);
9218
+ if (inline === void 0) index += 1;
9219
+ const list = values.get(name) ?? [];
9220
+ list.push(value);
9221
+ values.set(name, list);
9222
+ }
9223
+ return { positionals, values, booleans };
9224
+ }
9225
+ function lastOption(options, name) {
9226
+ return options.values.get(name)?.at(-1);
9227
+ }
9228
+ function requiredOption(options, name) {
9229
+ const value = lastOption(options, name);
9230
+ if (value === void 0 || value.length === 0) throw new CliError(`The option ${name} is required.`);
9231
+ return value;
9232
+ }
9233
+ function integerOption(options, name, min, max) {
9234
+ const raw = lastOption(options, name);
9235
+ if (raw === void 0) return void 0;
9236
+ if (!/^\d+$/.test(raw)) throw new CliError(`The option ${name} must be an integer.`);
9237
+ const value = Number(raw);
9238
+ if (value < min || value > max) {
9239
+ throw new CliError(`The option ${name} must be between ${min} and ${max}.`);
9240
+ }
9241
+ return value;
9242
+ }
9243
+ function booleanOption(options, name) {
9244
+ const raw = lastOption(options, name);
9245
+ if (raw === void 0) return void 0;
9246
+ if (raw === "true") return true;
9247
+ if (raw === "false") return false;
9248
+ throw new CliError(`The option ${name} must be "true" or "false".`);
9249
+ }
9250
+ async function listAll(client, path, query = {}) {
9251
+ const items = [];
9252
+ let page;
9253
+ do {
9254
+ const response = await client.platform.request({
9255
+ method: "get",
9256
+ path,
9257
+ query: { ...query, ...page !== null && page !== void 0 ? { page } : {} }
9258
+ });
9259
+ items.push(...response.data);
9260
+ page = response.next_page;
9261
+ } while (page !== null && page !== void 0 && page.length > 0);
9262
+ return items;
9263
+ }
9264
+ var statusOf = (record) => record.archived_at === null ? "active" : "archived";
9265
+ function matchSummary(match) {
9266
+ const parts = [];
9267
+ if (match.subject_prefix !== void 0) parts.push(`subject:${match.subject_prefix}`);
9268
+ if (match.audience !== void 0) parts.push(`aud:${match.audience}`);
9269
+ for (const [key, value] of Object.entries(match.claims ?? {})) parts.push(`${key}=${value}`);
9270
+ return parts.join(", ");
9271
+ }
9272
+ async function serviceAccountsCommand(argv, deps) {
9273
+ const [subcommand, ...args] = argv;
9274
+ if (subcommand === "list") {
9275
+ const options = parseOptions(args, specFor("service-accounts list"));
9276
+ if (options.positionals.length > 0) throw new CliError("Usage: nouter-platform service-accounts list [--include-archived] [--json]");
9277
+ const auth = await resolveAuth(deps);
9278
+ try {
9279
+ const client = clientFor(auth, deps);
9280
+ const accounts = await listAll(
9281
+ client,
9282
+ "/v1/oma/service_accounts",
9283
+ options.booleans.has("--include-archived") ? { include_archived: "true" } : {}
9284
+ );
9285
+ if (options.booleans.has("--json")) {
9286
+ deps.writeStdout(JSON.stringify(accounts, null, 2));
9287
+ return 0;
9288
+ }
9289
+ if (accounts.length === 0) {
9290
+ deps.writeStdout("No service accounts.");
9291
+ return 0;
9292
+ }
9293
+ deps.writeStdout(
9294
+ table([
9295
+ ["ID", "NAME", "ROLE", "STATUS", "CREATED"],
9296
+ ...accounts.map((account) => [
9297
+ account.id,
9298
+ account.name,
9299
+ account.organization_role,
9300
+ statusOf(account),
9301
+ account.created_at
9302
+ ])
9303
+ ])
9304
+ );
9305
+ return 0;
9306
+ } catch (error) {
9307
+ if (error instanceof CliError) throw error;
9308
+ throw new CliError(`Could not list service accounts: ${describeApiFailure(error)}`);
9309
+ }
9310
+ }
9311
+ if (subcommand === "create") {
9312
+ const options = parseOptions(args, specFor("service-accounts create"));
9313
+ const name = requiredOption(options, "--name");
9314
+ const role = requiredOption(options, "--organization-role");
9315
+ if (role !== "developer" && role !== "admin") {
9316
+ throw new CliError(`The organization role must be "developer" or "admin" (got "${role}").`);
9317
+ }
9318
+ const auth = await resolveAuth(deps);
9319
+ try {
9320
+ const account = await clientFor(auth, deps).platform.request({
9321
+ method: "post",
9322
+ path: "/v1/oma/service_accounts",
9323
+ body: { name, organization_role: role }
9324
+ });
9325
+ if (options.booleans.has("--json")) deps.writeStdout(JSON.stringify(account, null, 2));
9326
+ else deps.writeStdout(`Created service account ${account.id} (${account.name}).`);
9327
+ return 0;
9328
+ } catch (error) {
9329
+ if (error instanceof CliError) throw error;
9330
+ throw new CliError(`Could not create the service account: ${describeApiFailure(error)}`);
9331
+ }
9332
+ }
9333
+ if (subcommand === "archive") {
9334
+ const options = parseOptions(args, specFor("service-accounts archive"));
9335
+ const id = options.positionals[0];
9336
+ if (id === void 0 || options.positionals.length > 1) {
9337
+ throw new CliError("Usage: nouter-platform service-accounts archive <service-account-id>");
9338
+ }
9339
+ const auth = await resolveAuth(deps);
9340
+ try {
9341
+ const account = await clientFor(auth, deps).platform.request({
9342
+ method: "post",
9343
+ path: `/v1/oma/service_accounts/${id}/archive`
9344
+ });
9345
+ deps.writeStdout(`Archived service account ${account.id}.`);
9346
+ return 0;
9347
+ } catch (error) {
9348
+ if (error instanceof CliError) throw error;
9349
+ throw new CliError(`Could not archive service account ${id}: ${describeApiFailure(error)}`);
9350
+ }
9351
+ }
9352
+ return usageError("service-accounts list|create|archive", deps);
9353
+ }
9354
+ async function federationIssuersCommand(argv, deps) {
9355
+ const [subcommand, ...args] = argv;
9356
+ if (subcommand === "list") {
9357
+ const options = parseOptions(args, specFor("federation issuers list"));
9358
+ if (options.positionals.length > 0) throw new CliError("Usage: nouter-platform federation issuers list [--include-archived] [--json]");
9359
+ const auth = await resolveAuth(deps);
9360
+ try {
9361
+ const client = clientFor(auth, deps);
9362
+ const issuers = await listAll(
9363
+ client,
9364
+ "/v1/oma/federation_issuers",
9365
+ options.booleans.has("--include-archived") ? { include_archived: "true" } : {}
9366
+ );
9367
+ if (options.booleans.has("--json")) {
9368
+ deps.writeStdout(JSON.stringify(issuers, null, 2));
9369
+ return 0;
9370
+ }
9371
+ if (issuers.length === 0) {
9372
+ deps.writeStdout("No federation issuers.");
9373
+ return 0;
9374
+ }
9375
+ deps.writeStdout(
9376
+ table([
9377
+ ["ID", "NAME", "PROVIDER", "ISSUER URL", "STATUS", "CREATED"],
9378
+ ...issuers.map((issuer) => [
9379
+ issuer.id,
9380
+ issuer.name,
9381
+ issuer.provider,
9382
+ issuer.issuer_url,
9383
+ statusOf(issuer),
9384
+ issuer.created_at
9385
+ ])
9386
+ ])
9387
+ );
9388
+ return 0;
9389
+ } catch (error) {
9390
+ if (error instanceof CliError) throw error;
9391
+ throw new CliError(`Could not list federation issuers: ${describeApiFailure(error)}`);
9392
+ }
9393
+ }
9394
+ if (subcommand === "create") {
9395
+ const options = parseOptions(args, specFor("federation issuers create"));
9396
+ const name = requiredOption(options, "--name");
9397
+ const provider = requiredOption(options, "--provider");
9398
+ if (provider !== "github" && provider !== "gcp" && provider !== "aws" && provider !== "custom") {
9399
+ throw new CliError(`The provider must be one of github, gcp, aws or custom (got "${provider}").`);
9400
+ }
9401
+ const issuerUrl = requiredOption(options, "--issuer-url");
9402
+ const jwksUrl = lastOption(options, "--jwks-url");
9403
+ const checkJti = booleanOption(options, "--check-jti");
9404
+ const maxLifetime = integerOption(options, "--max-token-lifetime", 60, 86400);
9405
+ const body = { name, provider, issuer_url: issuerUrl };
9406
+ if (jwksUrl !== void 0) body.jwks = { type: "explicit_url", url: jwksUrl };
9407
+ if (checkJti !== void 0) body.check_jti = checkJti;
9408
+ if (maxLifetime !== void 0) body.max_token_lifetime_seconds = maxLifetime;
9409
+ const auth = await resolveAuth(deps);
9410
+ try {
9411
+ const issuer = await clientFor(auth, deps).platform.request({
9412
+ method: "post",
9413
+ path: "/v1/oma/federation_issuers",
9414
+ body
9415
+ });
9416
+ if (options.booleans.has("--json")) deps.writeStdout(JSON.stringify(issuer, null, 2));
9417
+ else deps.writeStdout(`Created federation issuer ${issuer.id} (${issuer.name}).`);
9418
+ return 0;
9419
+ } catch (error) {
9420
+ if (error instanceof CliError) throw error;
9421
+ throw new CliError(`Could not create the federation issuer: ${describeApiFailure(error)}`);
9422
+ }
9423
+ }
9424
+ if (subcommand === "archive") {
9425
+ const options = parseOptions(args, specFor("federation issuers archive"));
9426
+ const id = options.positionals[0];
9427
+ if (id === void 0 || options.positionals.length > 1) {
9428
+ throw new CliError("Usage: nouter-platform federation issuers archive <issuer-id>");
9429
+ }
9430
+ const auth = await resolveAuth(deps);
9431
+ try {
9432
+ const issuer = await clientFor(auth, deps).platform.request({
9433
+ method: "post",
9434
+ path: `/v1/oma/federation_issuers/${id}/archive`
9435
+ });
9436
+ deps.writeStdout(`Archived federation issuer ${issuer.id}.`);
9437
+ return 0;
9438
+ } catch (error) {
9439
+ if (error instanceof CliError) throw error;
9440
+ throw new CliError(`Could not archive federation issuer ${id}: ${describeApiFailure(error)}`);
9441
+ }
9442
+ }
9443
+ return usageError("federation issuers list|create|archive", deps);
9444
+ }
9445
+ async function federationRulesCommand(argv, deps) {
9446
+ const [subcommand, ...args] = argv;
9447
+ if (subcommand === "list") {
9448
+ const options = parseOptions(args, specFor("federation rules list"));
9449
+ if (options.positionals.length > 0) {
9450
+ throw new CliError("Usage: nouter-platform federation rules list [--issuer <issuer-id>] [--include-archived] [--json]");
9451
+ }
9452
+ const issuerId = lastOption(options, "--issuer");
9453
+ const auth = await resolveAuth(deps);
9454
+ try {
9455
+ const client = clientFor(auth, deps);
9456
+ const rules = await listAll(client, "/v1/oma/federation_rules", {
9457
+ ...options.booleans.has("--include-archived") ? { include_archived: "true" } : {},
9458
+ ...issuerId !== void 0 ? { issuer_id: issuerId } : {}
9459
+ });
9460
+ if (options.booleans.has("--json")) {
9461
+ deps.writeStdout(JSON.stringify(rules, null, 2));
9462
+ return 0;
9463
+ }
9464
+ if (rules.length === 0) {
9465
+ deps.writeStdout("No federation rules.");
9466
+ return 0;
9467
+ }
9468
+ deps.writeStdout(
9469
+ table([
9470
+ ["ID", "NAME", "ISSUER", "TARGET", "WORKSPACE", "MATCH", "SCOPES", "STATUS", "CREATED"],
9471
+ ...rules.map((rule) => [
9472
+ rule.id,
9473
+ rule.name,
9474
+ rule.issuer_id,
9475
+ rule.target.service_account_id,
9476
+ rule.applies_to_all_workspaces ? "all" : rule.workspace_id ?? "",
9477
+ matchSummary(rule.match),
9478
+ rule.scopes.join(","),
9479
+ statusOf(rule),
9480
+ rule.created_at
9481
+ ])
9482
+ ])
9483
+ );
9484
+ return 0;
9485
+ } catch (error) {
9486
+ if (error instanceof CliError) throw error;
9487
+ throw new CliError(`Could not list federation rules: ${describeApiFailure(error)}`);
9488
+ }
9489
+ }
9490
+ if (subcommand === "create") {
9491
+ const options = parseOptions(args, specFor("federation rules create"));
9492
+ const name = requiredOption(options, "--name");
9493
+ const issuerId = requiredOption(options, "--issuer");
9494
+ const serviceAccountId = requiredOption(options, "--service-account");
9495
+ const subjectPrefix = lastOption(options, "--subject-prefix");
9496
+ const audience = lastOption(options, "--audience");
9497
+ const claims = {};
9498
+ for (const claim of options.values.get("--claim") ?? []) {
9499
+ const equals = claim.indexOf("=");
9500
+ if (equals <= 0) throw new CliError("The option --claim expects key=value.");
9501
+ claims[claim.slice(0, equals)] = claim.slice(equals + 1);
9502
+ }
9503
+ if (subjectPrefix === void 0 && Object.keys(claims).length === 0) {
9504
+ throw new CliError("The rule needs --subject-prefix or at least one --claim.");
9505
+ }
9506
+ const match = {
9507
+ ...subjectPrefix !== void 0 && { subject_prefix: subjectPrefix },
9508
+ ...audience !== void 0 && { audience },
9509
+ ...Object.keys(claims).length > 0 && { claims }
9510
+ };
9511
+ const workspaceId = lastOption(options, "--workspace");
9512
+ const allWorkspaces = options.booleans.has("--all-workspaces");
9513
+ if (allWorkspaces && workspaceId !== void 0) {
9514
+ throw new CliError("--workspace and --all-workspaces are mutually exclusive.");
9515
+ }
9516
+ if (!allWorkspaces && workspaceId === void 0) {
9517
+ throw new CliError("The rule needs --workspace <workspace-id> or --all-workspaces.");
9518
+ }
9519
+ const scopes = (options.values.get("--scopes") ?? []).flatMap((value) => value.split(",")).map((scope) => scope.trim()).filter((scope) => scope.length > 0);
9520
+ if (scopes.length === 0) throw new CliError("The option --scopes is required.");
9521
+ const lifetime = integerOption(options, "--token-lifetime", 60, 86400);
9522
+ const body = {
9523
+ name,
9524
+ issuer_id: issuerId,
9525
+ match,
9526
+ target: { type: "service_account", service_account_id: serviceAccountId },
9527
+ scopes,
9528
+ ...workspaceId !== void 0 && { workspace_id: workspaceId },
9529
+ ...allWorkspaces && { applies_to_all_workspaces: true },
9530
+ ...lifetime !== void 0 && { token_lifetime_seconds: lifetime }
9531
+ };
9532
+ const auth = await resolveAuth(deps);
9533
+ try {
9534
+ const rule = await clientFor(auth, deps).platform.request({
9535
+ method: "post",
9536
+ path: "/v1/oma/federation_rules",
9537
+ body
9538
+ });
9539
+ if (options.booleans.has("--json")) deps.writeStdout(JSON.stringify(rule, null, 2));
9540
+ else deps.writeStdout(`Created federation rule ${rule.id} (${rule.name}).`);
9541
+ return 0;
9542
+ } catch (error) {
9543
+ if (error instanceof CliError) throw error;
9544
+ throw new CliError(`Could not create the federation rule: ${describeApiFailure(error)}`);
9545
+ }
9546
+ }
9547
+ if (subcommand === "archive") {
9548
+ const options = parseOptions(args, specFor("federation rules archive"));
9549
+ const id = options.positionals[0];
9550
+ if (id === void 0 || options.positionals.length > 1) {
9551
+ throw new CliError("Usage: nouter-platform federation rules archive <rule-id>");
9552
+ }
9553
+ const auth = await resolveAuth(deps);
9554
+ try {
9555
+ const rule = await clientFor(auth, deps).platform.request({
9556
+ method: "post",
9557
+ path: `/v1/oma/federation_rules/${id}/archive`
9558
+ });
9559
+ deps.writeStdout(`Archived federation rule ${rule.id}.`);
9560
+ return 0;
9561
+ } catch (error) {
9562
+ if (error instanceof CliError) throw error;
9563
+ throw new CliError(`Could not archive federation rule ${id}: ${describeApiFailure(error)}`);
9564
+ }
9565
+ }
9566
+ return usageError("federation rules list|create|archive", deps);
9567
+ }
9568
+ async function federationTokenCommand(argv, deps) {
9569
+ const options = parseOptions(argv, specFor("federation token"));
9570
+ if (options.positionals.length > 0) throw new CliError("Usage: nouter-platform federation token [--json]");
9571
+ const settings = federationSettingsOrNull();
9572
+ if (settings === null) {
9573
+ throw new CliError(
9574
+ "The federation is not configured: set NOUTER_PLATFORM_FEDERATION_RULE_ID, NOUTER_PLATFORM_ORGANIZATION_ID and NOUTER_PLATFORM_IDENTITY_TOKEN or NOUTER_PLATFORM_IDENTITY_TOKEN_FILE."
9575
+ );
9576
+ }
9577
+ const stored = readConfig({ warn: deps.writeStderr });
9578
+ const baseUrl = requireBaseUrl(stored);
9579
+ const token = await federationProviderFor(baseUrl, settings, deps).getToken().catch(federationFailure);
9580
+ if (options.booleans.has("--json")) {
9581
+ deps.writeStdout(
9582
+ JSON.stringify(
9583
+ {
9584
+ access_token: token.accessToken,
9585
+ token_type: "Bearer",
9586
+ expires_in: token.expiresIn,
9587
+ scope: token.scopes.join(" ")
9588
+ },
9589
+ null,
9590
+ 2
9591
+ )
9592
+ );
9593
+ } else {
9594
+ deps.writeStdout(token.accessToken);
9595
+ }
9596
+ return 0;
9597
+ }
9598
+ function authStatus(deps) {
9599
+ const stored = readConfig({ warn: deps.writeStderr });
9600
+ const envKey = environmentApiKey();
9601
+ const rule = process.env.NOUTER_PLATFORM_FEDERATION_RULE_ID;
9602
+ const organization = process.env.NOUTER_PLATFORM_ORGANIZATION_ID;
9603
+ const identity = identityTokenSourceFromEnv(process.env);
9604
+ const envBase = process.env.NOUTER_PLATFORM_BASE_URL;
9605
+ const rawBaseUrl = envBase && envBase.length > 0 ? envBase : stored?.baseUrl ?? null;
9606
+ let baseUrl = null;
9607
+ if (rawBaseUrl !== null) {
9608
+ try {
9609
+ const parsed = new URL(rawBaseUrl);
9610
+ baseUrl = `${parsed.origin}${parsed.pathname.replace(/\/+$/, "")}`;
9611
+ } catch {
9612
+ baseUrl = "(invalid URL)";
9613
+ }
9614
+ }
9615
+ let source;
9616
+ if (envKey !== null) source = `API key (${envKey.name})`;
9617
+ else if (typeof rule === "string" && rule.length > 0 && typeof organization === "string" && organization.length > 0 && identity !== null) {
9618
+ source = `federation (rule ${rule})`;
9619
+ } else if (stored !== null) source = "login token";
9620
+ else source = "none";
9621
+ deps.writeStdout(`Source: ${source}`);
9622
+ if (baseUrl !== null) deps.writeStdout(`Base URL: ${baseUrl}`);
9623
+ return source === "none" ? 1 : 0;
9624
+ }
8787
9625
  function applyClientFor(client) {
8788
9626
  return {
8789
9627
  async listAgents() {
@@ -8821,16 +9659,17 @@ async function applyCommand(argv, deps) {
8821
9659
  const inputs = [];
8822
9660
  let dryRun = false;
8823
9661
  let rotateSecrets = false;
9662
+ const [fileFlag, shortFileFlag, dryRunFlag, rotateSecretsFlag] = MANUAL_FLAGS.apply;
8824
9663
  for (let index = 0; index < argv.length; index += 1) {
8825
9664
  const argument = argv[index];
8826
- if (argument === "-f" || argument === "--file") {
9665
+ if (argument === shortFileFlag || argument === fileFlag) {
8827
9666
  const input = argv[index + 1];
8828
9667
  if (input === void 0 || input.startsWith("-")) return applyUsage(deps);
8829
9668
  inputs.push(input);
8830
9669
  index += 1;
8831
- } else if (argument === "--dry-run") {
9670
+ } else if (argument === dryRunFlag) {
8832
9671
  dryRun = true;
8833
- } else if (argument === "--rotate-secrets") {
9672
+ } else if (argument === rotateSecretsFlag) {
8834
9673
  rotateSecrets = true;
8835
9674
  } else {
8836
9675
  return applyUsage(deps);
@@ -8844,8 +9683,8 @@ async function applyCommand(argv, deps) {
8844
9683
  if (error instanceof ApplyValidationError) throw new CliError(error.message);
8845
9684
  throw error;
8846
9685
  }
8847
- const auth = resolveAuth(deps);
8848
- const client = applyClientFor(clientFor(auth.baseUrl, auth.apiKey, deps, { maxRetries: 0 }));
9686
+ const auth = await resolveAuth(deps);
9687
+ const client = applyClientFor(clientFor(auth, deps, { maxRetries: 0 }));
8849
9688
  let current;
8850
9689
  try {
8851
9690
  current = {
@@ -8853,6 +9692,7 @@ async function applyCommand(argv, deps) {
8853
9692
  environments: await client.listEnvironments()
8854
9693
  };
8855
9694
  } catch (error) {
9695
+ if (error instanceof CliError) throw error;
8856
9696
  throw new CliError(`Could not read the current agents and environments: ${describeApiFailure(error)}`);
8857
9697
  }
8858
9698
  let plan;
@@ -8876,19 +9716,62 @@ function printHelp(deps) {
8876
9716
  "Usage: nouter-platform <command> [options]",
8877
9717
  "",
8878
9718
  "Commands:",
8879
- " login --api-key (key from stdin) or --browser",
8880
- " logout Remove the stored API key (local only; revoke it in the console)",
8881
- " whoami Show the organization, role and scopes",
8882
- " agents list | get <agent-id>",
8883
- " environments list | get <environment-id>",
8884
- " apply Apply agents and environments from files",
9719
+ " login --api-key (key from stdin) or --browser",
9720
+ " logout Remove the stored API key (local only; revoke it in the console)",
9721
+ " whoami Show the organization, role and scopes",
9722
+ " auth status: show which credential the CLI would use",
9723
+ " version Show the CLI version and the SDK version it ships",
9724
+ " agents list | get <agent-id>",
9725
+ " environments list | get <environment-id>",
9726
+ " service-accounts list | create | archive",
9727
+ " federation issuers list|create|archive | rules list|create|archive | token",
9728
+ " apply Apply agents and environments from files",
9729
+ "",
9730
+ "Options:",
9731
+ " -h, --help Show this help",
9732
+ " -v, --version Show the version",
8885
9733
  "",
8886
9734
  "Environment:",
8887
- " NOUTER_PLATFORM_API_KEY API key; wins over the stored key",
8888
- " NOUTER_PLATFORM_BASE_URL API base URL"
9735
+ " NOUTER_PLATFORM_API_KEY API key; wins over the stored key and the federation",
9736
+ " NOUTER_PLATFORM_BASE_URL API base URL",
9737
+ " NOUTER_PLATFORM_FEDERATION_RULE_ID Enable the federated credential for this rule",
9738
+ " NOUTER_PLATFORM_ORGANIZATION_ID The organization of the federation rule",
9739
+ " NOUTER_PLATFORM_SERVICE_ACCOUNT_ID The service account, when the rule spans several",
9740
+ " NOUTER_PLATFORM_WORKSPACE_ID The workspace, when the rule spans several",
9741
+ " NOUTER_PLATFORM_IDENTITY_TOKEN The OIDC assertion, or",
9742
+ " NOUTER_PLATFORM_IDENTITY_TOKEN_FILE The file with the OIDC assertion"
8889
9743
  ].join("\n")
8890
9744
  );
8891
9745
  }
9746
+ function manifestAt(path) {
9747
+ try {
9748
+ return JSON.parse(readFileSync3(path, "utf8"));
9749
+ } catch {
9750
+ return null;
9751
+ }
9752
+ }
9753
+ function cliVersion() {
9754
+ return manifestAt(fileURLToPath(new URL("../package.json", import.meta.url)))?.version ?? "unknown";
9755
+ }
9756
+ function sdkVersion() {
9757
+ let directory;
9758
+ try {
9759
+ directory = dirname(fileURLToPath(import.meta.resolve("@nouter/platform")));
9760
+ } catch {
9761
+ return "unknown";
9762
+ }
9763
+ for (let depth = 0; depth < 8; depth += 1) {
9764
+ const manifest = manifestAt(join2(directory, "package.json"));
9765
+ if (manifest?.name === "@nouter/platform" && typeof manifest.version === "string") return manifest.version;
9766
+ const parent = dirname(directory);
9767
+ if (parent === directory) break;
9768
+ directory = parent;
9769
+ }
9770
+ return "unknown";
9771
+ }
9772
+ function versionLine() {
9773
+ return `nouter-platform-cli ${cliVersion()} (sdk ${sdkVersion()})`;
9774
+ }
8892
9775
  function usageError(command, deps) {
8893
9776
  deps.writeStderr(`Usage: nouter-platform ${command} ...`);
8894
9777
  return 1;
@@ -8899,6 +9782,10 @@ async function dispatch(argv, deps) {
8899
9782
  printHelp(deps);
8900
9783
  return 0;
8901
9784
  }
9785
+ if (command === "--version" || command === "-v") {
9786
+ deps.writeStdout(versionLine());
9787
+ return 0;
9788
+ }
8902
9789
  switch (command) {
8903
9790
  case "login":
8904
9791
  return await login(rest, deps);
@@ -8906,24 +9793,43 @@ async function dispatch(argv, deps) {
8906
9793
  deps.writeStdout(clearConfig() ? "Logged out." : "No stored key.");
8907
9794
  return 0;
8908
9795
  case "whoami": {
8909
- const auth = resolveAuth(deps);
8910
- printWhoami(await fetchMe(auth.baseUrl, auth.apiKey, deps), deps);
9796
+ const auth = await resolveAuth(deps);
9797
+ printWhoami(await fetchMe(auth, deps), deps);
8911
9798
  return 0;
8912
9799
  }
8913
9800
  case "agents": {
8914
9801
  const [subcommand, ...args] = rest;
8915
- const json = args.includes("--json") || rest.includes("--json");
9802
+ const jsonFlag = MANUAL_FLAGS["agents list"][0];
9803
+ const json = subcommand === "list" && (args.includes(jsonFlag) || rest.includes(jsonFlag));
8916
9804
  if (subcommand === "list") return await listAgents(deps, json);
8917
9805
  if (subcommand === "get" && args[0]) return await getAgent(args[0], deps);
8918
9806
  return usageError("agents list|get <agent-id>", deps);
8919
9807
  }
8920
9808
  case "environments": {
8921
9809
  const [subcommand, ...args] = rest;
8922
- const json = args.includes("--json") || rest.includes("--json");
9810
+ const jsonFlag = MANUAL_FLAGS["environments list"][0];
9811
+ const json = subcommand === "list" && (args.includes(jsonFlag) || rest.includes(jsonFlag));
8923
9812
  if (subcommand === "list") return await listEnvironments(deps, json);
8924
9813
  if (subcommand === "get" && args[0]) return await getEnvironment(args[0], deps);
8925
9814
  return usageError("environments list|get <environment-id>", deps);
8926
9815
  }
9816
+ case "auth": {
9817
+ if (rest.length === 1 && rest[0] === "status") return authStatus(deps);
9818
+ return usageError("auth status", deps);
9819
+ }
9820
+ case "version":
9821
+ if (rest.length > 0) return usageError("version", deps);
9822
+ deps.writeStdout(versionLine());
9823
+ return 0;
9824
+ case "service-accounts":
9825
+ return await serviceAccountsCommand(rest, deps);
9826
+ case "federation": {
9827
+ const [group, ...args] = rest;
9828
+ if (group === "issuers") return await federationIssuersCommand(args, deps);
9829
+ if (group === "rules") return await federationRulesCommand(args, deps);
9830
+ if (group === "token") return await federationTokenCommand(args, deps);
9831
+ return usageError("federation issuers|rules|token", deps);
9832
+ }
8927
9833
  case "apply":
8928
9834
  return await applyCommand(rest, deps);
8929
9835
  default:
package/package.json CHANGED
@@ -1,10 +1,10 @@
1
1
  {
2
2
  "name": "@nouter/platform-cli",
3
- "version": "0.1.0",
3
+ "version": "0.3.0",
4
4
  "description": "CLI for the Nouter platform",
5
5
  "type": "module",
6
6
  "bin": {
7
- "nouter-platform": "./dist/index.js"
7
+ "nouter-platform": "dist/index.js"
8
8
  },
9
9
  "files": [
10
10
  "dist",
@@ -13,7 +13,7 @@
13
13
  "NOTICE"
14
14
  ],
15
15
  "engines": {
16
- "node": ">=20"
16
+ "node": ">=20.6"
17
17
  },
18
18
  "scripts": {
19
19
  "prebuild": "pnpm --filter @nouter/platform build",
@@ -39,14 +39,14 @@
39
39
  "homepage": "https://github.com/Nouter-ai/platform",
40
40
  "repository": {
41
41
  "type": "git",
42
- "url": "https://github.com/Nouter-ai/platform",
42
+ "url": "git+https://github.com/Nouter-ai/platform.git",
43
43
  "directory": "packages/cli"
44
44
  },
45
45
  "bugs": {
46
46
  "url": "https://github.com/Nouter-ai/platform/issues"
47
47
  },
48
48
  "dependencies": {
49
- "@nouter/platform": "^0.1.0",
49
+ "@nouter/platform": "^0.3.0",
50
50
  "yaml": "2.9.1"
51
51
  },
52
52
  "devDependencies": {