@nouter/platform-cli 0.1.0 → 0.2.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 (2) hide show
  1. package/dist/index.js +713 -40
  2. package/package.json +2 -2
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,7 +7377,7 @@ 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,
@@ -8248,6 +8248,153 @@ function formatApplyResults(results) {
8248
8248
  return lines;
8249
8249
  }
8250
8250
 
8251
+ // src/identity-token.ts
8252
+ import { readFileSync as readFileSync2 } from "node:fs";
8253
+ var IdentityTokenError = class extends Error {
8254
+ constructor(message) {
8255
+ super(message);
8256
+ this.name = "IdentityTokenError";
8257
+ }
8258
+ };
8259
+ var NON_EMPTY = (value) => typeof value === "string" && value.length > 0;
8260
+ function identityTokenSourceFromEnv(env = process.env) {
8261
+ const value = env.NOUTER_PLATFORM_IDENTITY_TOKEN;
8262
+ if (NON_EMPTY(value)) return { kind: "value", token: value };
8263
+ const path = env.NOUTER_PLATFORM_IDENTITY_TOKEN_FILE;
8264
+ if (NON_EMPTY(path)) return { kind: "file", path };
8265
+ return null;
8266
+ }
8267
+ var PRINTABLE = /^[\x21-\x7e]+$/u;
8268
+ function clean(token) {
8269
+ const trimmed = token.trim();
8270
+ if (trimmed.length === 0) throw new IdentityTokenError("The identity token is empty.");
8271
+ if (!PRINTABLE.test(trimmed)) {
8272
+ throw new IdentityTokenError("The identity token has characters the CLI cannot use.");
8273
+ }
8274
+ return trimmed;
8275
+ }
8276
+ function createIdentityTokenReader(source, read = (path) => readFileSync2(path, "utf8")) {
8277
+ if (source.kind === "value") {
8278
+ return { read: () => clean(source.token) };
8279
+ }
8280
+ return {
8281
+ read() {
8282
+ let contents;
8283
+ try {
8284
+ contents = read(source.path);
8285
+ } catch {
8286
+ throw new IdentityTokenError(`Could not read the identity token file ${source.path}.`);
8287
+ }
8288
+ return clean(contents);
8289
+ }
8290
+ };
8291
+ }
8292
+
8293
+ // src/federation.ts
8294
+ var FederationError = class extends Error {
8295
+ constructor(message) {
8296
+ super(message);
8297
+ this.name = "FederationError";
8298
+ }
8299
+ };
8300
+ var GRANT_TYPE = "urn:ietf:params:oauth:grant-type:jwt-bearer";
8301
+ var REFRESH_MARGIN_SECONDS = 30;
8302
+ var MIN_EXPIRES_IN = 60;
8303
+ var MAX_EXPIRES_IN = 86400;
8304
+ var present = (value) => typeof value === "string" && value.length > 0;
8305
+ function federationSettingsFromEnv(env = process.env) {
8306
+ if (!present(env.NOUTER_PLATFORM_FEDERATION_RULE_ID)) return null;
8307
+ if (!present(env.NOUTER_PLATFORM_ORGANIZATION_ID)) {
8308
+ throw new FederationError(
8309
+ "NOUTER_PLATFORM_ORGANIZATION_ID is required when NOUTER_PLATFORM_FEDERATION_RULE_ID is set."
8310
+ );
8311
+ }
8312
+ const identityToken = identityTokenSourceFromEnv(env);
8313
+ if (identityToken === null) {
8314
+ throw new IdentityTokenError(
8315
+ "NOUTER_PLATFORM_IDENTITY_TOKEN or NOUTER_PLATFORM_IDENTITY_TOKEN_FILE is required when NOUTER_PLATFORM_FEDERATION_RULE_ID is set."
8316
+ );
8317
+ }
8318
+ return {
8319
+ ruleId: env.NOUTER_PLATFORM_FEDERATION_RULE_ID,
8320
+ organizationId: env.NOUTER_PLATFORM_ORGANIZATION_ID,
8321
+ ...present(env.NOUTER_PLATFORM_SERVICE_ACCOUNT_ID) && { serviceAccountId: env.NOUTER_PLATFORM_SERVICE_ACCOUNT_ID },
8322
+ ...present(env.NOUTER_PLATFORM_WORKSPACE_ID) && { workspaceId: env.NOUTER_PLATFORM_WORKSPACE_ID },
8323
+ identityToken
8324
+ };
8325
+ }
8326
+ function parseToken(payload) {
8327
+ if (typeof payload !== "object" || payload === null) return null;
8328
+ const body = payload;
8329
+ if (typeof body.access_token !== "string" || !body.access_token.startsWith("oma_oat_")) return null;
8330
+ if (body.token_type !== "Bearer") return null;
8331
+ if (typeof body.expires_in !== "number" || !Number.isInteger(body.expires_in) || body.expires_in < MIN_EXPIRES_IN || body.expires_in > MAX_EXPIRES_IN) {
8332
+ return null;
8333
+ }
8334
+ if (typeof body.scope !== "string" || body.scope.trim().length === 0) return null;
8335
+ return {
8336
+ accessToken: body.access_token,
8337
+ expiresIn: body.expires_in,
8338
+ scopes: body.scope.split(" ").filter((scope) => scope.length > 0)
8339
+ };
8340
+ }
8341
+ async function exchange(baseUrl, settings, assertion, fetch, timeoutMs) {
8342
+ let response;
8343
+ try {
8344
+ response = await fetch(`${baseUrl}/v1/oauth/token`, {
8345
+ method: "POST",
8346
+ headers: { "content-type": "application/json", accept: "application/json" },
8347
+ body: JSON.stringify({
8348
+ grant_type: GRANT_TYPE,
8349
+ assertion,
8350
+ federation_rule_id: settings.ruleId,
8351
+ organization_id: settings.organizationId,
8352
+ ...settings.serviceAccountId !== void 0 && { service_account_id: settings.serviceAccountId },
8353
+ ...settings.workspaceId !== void 0 && { workspace_id: settings.workspaceId }
8354
+ }),
8355
+ signal: AbortSignal.timeout(timeoutMs)
8356
+ });
8357
+ } catch {
8358
+ throw new FederationError("The federation exchange failed (network error).");
8359
+ }
8360
+ if (response.status === 401) {
8361
+ throw new FederationError("Authentication failed");
8362
+ }
8363
+ if (!response.ok) {
8364
+ throw new FederationError(`The federation exchange failed (the server answered ${response.status}).`);
8365
+ }
8366
+ let payload;
8367
+ try {
8368
+ payload = await response.json();
8369
+ } catch {
8370
+ throw new FederationError("The federation exchange returned an unexpected response.");
8371
+ }
8372
+ const token = parseToken(payload);
8373
+ if (token === null) throw new FederationError("The federation exchange returned an unexpected response.");
8374
+ return token;
8375
+ }
8376
+ function createFederationTokenProvider(options) {
8377
+ const now = options.now ?? Date.now;
8378
+ const reader = createIdentityTokenReader(options.settings.identityToken, options.readFile);
8379
+ let cached = null;
8380
+ return {
8381
+ async getToken() {
8382
+ const assertion = reader.read();
8383
+ const current = now();
8384
+ if (cached !== null && cached.assertion === assertion && current < cached.refreshAt) {
8385
+ return cached.token;
8386
+ }
8387
+ const token = await exchange(options.baseUrl, options.settings, assertion, options.fetch, options.timeoutMs);
8388
+ cached = {
8389
+ token,
8390
+ assertion,
8391
+ refreshAt: current + Math.max(token.expiresIn - REFRESH_MARGIN_SECONDS, 0) * 1e3
8392
+ };
8393
+ return token;
8394
+ }
8395
+ };
8396
+ }
8397
+
8251
8398
  // src/login-callback.ts
8252
8399
  import { timingSafeEqual } from "node:crypto";
8253
8400
  import { createServer } from "node:http";
@@ -8445,7 +8592,7 @@ function readConfig(options = {}) {
8445
8592
  }
8446
8593
  if (mode !== void 0) warnAboutLoosePermissions(path, mode, platform, warn);
8447
8594
  try {
8448
- const parsed = JSON.parse(readFileSync2(path, "utf8"));
8595
+ const parsed = JSON.parse(readFileSync3(path, "utf8"));
8449
8596
  if (typeof parsed.apiKey !== "string" || parsed.apiKey.length === 0) return null;
8450
8597
  const baseUrl = typeof parsed.baseUrl === "string" && parsed.baseUrl.length > 0 ? parsed.baseUrl : null;
8451
8598
  return { baseUrl, apiKey: parsed.apiKey };
@@ -8555,12 +8702,65 @@ function requireBaseUrl(stored, hint = BASE_URL_HINT) {
8555
8702
  }
8556
8703
  return normalizeBaseUrl(candidate);
8557
8704
  }
8558
- function resolveAuth(deps) {
8705
+ function environmentApiKey(env = process.env) {
8706
+ const documented = env.NOUTER_PLATFORM_API_KEY;
8707
+ if (documented && documented.length > 0) return { name: "NOUTER_PLATFORM_API_KEY", value: documented };
8708
+ return null;
8709
+ }
8710
+ function federationSettingsOrNull() {
8711
+ try {
8712
+ return federationSettingsFromEnv(process.env);
8713
+ } catch (error) {
8714
+ if (error instanceof FederationError || error instanceof IdentityTokenError) throw new CliError(error.message);
8715
+ throw error;
8716
+ }
8717
+ }
8718
+ var cachedFederationProvider = null;
8719
+ function federationProviderFor(baseUrl, settings, deps) {
8720
+ const key = JSON.stringify([
8721
+ baseUrl,
8722
+ settings.ruleId,
8723
+ settings.organizationId,
8724
+ settings.serviceAccountId ?? "",
8725
+ settings.workspaceId ?? "",
8726
+ settings.identityToken
8727
+ ]);
8728
+ if (cachedFederationProvider !== null && cachedFederationProvider.key === key) {
8729
+ return cachedFederationProvider.provider;
8730
+ }
8731
+ const provider = createFederationTokenProvider({
8732
+ baseUrl,
8733
+ settings,
8734
+ fetch: deps.fetch,
8735
+ timeoutMs: deps.requestTimeoutMs
8736
+ });
8737
+ cachedFederationProvider = { key, provider };
8738
+ return provider;
8739
+ }
8740
+ function federationFailure(error) {
8741
+ if (error instanceof FederationError || error instanceof IdentityTokenError) throw new CliError(error.message);
8742
+ throw error;
8743
+ }
8744
+ async function resolveAuth(deps) {
8559
8745
  const stored = readConfig({ warn: deps.writeStderr });
8560
- const envKey = process.env.NOUTER_PLATFORM_API_KEY;
8561
8746
  const envBase = process.env.NOUTER_PLATFORM_BASE_URL;
8562
- if (envKey && envKey.length > 0) {
8563
- return { baseUrl: requireBaseUrl(stored), apiKey: envKey };
8747
+ const envKey = environmentApiKey();
8748
+ const federationConfigured = typeof process.env.NOUTER_PLATFORM_FEDERATION_RULE_ID === "string" && process.env.NOUTER_PLATFORM_FEDERATION_RULE_ID.length > 0;
8749
+ if (envKey !== null) {
8750
+ if (federationConfigured) {
8751
+ deps.writeStderr(
8752
+ `Warning: ${envKey.name} is set and wins over the federation credentials; unset it to use NOUTER_PLATFORM_FEDERATION_RULE_ID.`
8753
+ );
8754
+ }
8755
+ return { baseUrl: requireBaseUrl(stored), credential: envKey.value, transport: "api-key" };
8756
+ }
8757
+ if (federationConfigured) {
8758
+ const settings = federationSettingsOrNull();
8759
+ if (settings !== null) {
8760
+ const baseUrl = requireBaseUrl(stored);
8761
+ const token = await federationProviderFor(baseUrl, settings, deps).getToken().catch(federationFailure);
8762
+ return { baseUrl, credential: token.accessToken, transport: "bearer" };
8763
+ }
8564
8764
  }
8565
8765
  if (!stored) {
8566
8766
  throw new CliError("Not authenticated. Run `nouter-platform login --api-key` or set NOUTER_PLATFORM_API_KEY.");
@@ -8578,22 +8778,25 @@ function resolveAuth(deps) {
8578
8778
  `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
8779
  );
8580
8780
  }
8581
- return { baseUrl: envBaseUrl, apiKey: stored.apiKey };
8781
+ return { baseUrl: envBaseUrl, credential: stored.apiKey, transport: "api-key" };
8582
8782
  }
8583
- return { baseUrl: storedBaseUrl, apiKey: stored.apiKey };
8783
+ return { baseUrl: storedBaseUrl, credential: stored.apiKey, transport: "api-key" };
8584
8784
  }
8585
- function clientFor(baseUrl, apiKey, deps, options = {}) {
8586
- return new NouterPlatform({
8587
- apiKey,
8588
- baseURL: baseUrl,
8785
+ function clientFor(auth, deps, options = {}) {
8786
+ const common = {
8787
+ baseURL: auth.baseUrl,
8589
8788
  fetch: deps.fetch,
8590
8789
  userAgent: USER_AGENT,
8591
8790
  ...options.maxRetries !== void 0 && { maxRetries: options.maxRetries }
8592
- });
8791
+ };
8792
+ return auth.transport === "bearer" ? new NouterPlatform({ ...common, authToken: auth.credential }) : new NouterPlatform({ ...common, apiKey: auth.credential });
8793
+ }
8794
+ function apiKeyAuth(baseUrl, apiKey) {
8795
+ return { baseUrl, credential: apiKey, transport: "api-key" };
8593
8796
  }
8594
- async function fetchMe(baseUrl, apiKey, deps) {
8797
+ async function fetchMe(auth, deps) {
8595
8798
  try {
8596
- return await clientFor(baseUrl, apiKey, deps).platform.request({
8799
+ return await clientFor(auth, deps).platform.request({
8597
8800
  method: "get",
8598
8801
  path: "/v1/oma/me",
8599
8802
  signal: AbortSignal.timeout(deps.requestTimeoutMs)
@@ -8633,7 +8836,7 @@ async function loginWithApiKey(deps) {
8633
8836
  if (!/^[\x21-\x7e]+$/.test(apiKey)) {
8634
8837
  throw new CliError("The API key has characters the CLI cannot use. Pipe it in again.");
8635
8838
  }
8636
- const me = await fetchMe(baseUrl, apiKey, deps);
8839
+ const me = await fetchMe(apiKeyAuth(baseUrl, apiKey), deps);
8637
8840
  writeConfig({ baseUrl, apiKey });
8638
8841
  deps.writeStdout(`Logged in to ${organizationOf(me) ?? "the organization"}.`);
8639
8842
  return 0;
@@ -8651,7 +8854,7 @@ async function loginWithBrowser(deps) {
8651
8854
  ${consoleUrl.toString()}`);
8652
8855
  deps.openBrowser(consoleUrl.toString());
8653
8856
  const delivered = await callback.waitForResult();
8654
- const me = await fetchMe(baseUrl, delivered.token, deps);
8857
+ const me = await fetchMe(apiKeyAuth(baseUrl, delivered.token), deps);
8655
8858
  writeConfig({ baseUrl, apiKey: delivered.token });
8656
8859
  const organization = delivered.tenantName ?? organizationOf(me) ?? "the organization";
8657
8860
  deps.writeStdout(`Logged in to ${organization}.`);
@@ -8695,9 +8898,9 @@ function modelOf(agent) {
8695
8898
  return model?.id ?? "";
8696
8899
  }
8697
8900
  async function listAgents(deps, json) {
8698
- const auth = resolveAuth(deps);
8901
+ const auth = await resolveAuth(deps);
8699
8902
  try {
8700
- const client = clientFor(auth.baseUrl, auth.apiKey, deps);
8903
+ const client = clientFor(auth, deps);
8701
8904
  const agents = [];
8702
8905
  for await (const agent of client.beta.agents.list()) agents.push(agent);
8703
8906
  if (json) {
@@ -8726,9 +8929,9 @@ async function listAgents(deps, json) {
8726
8929
  }
8727
8930
  }
8728
8931
  async function getAgent(id, deps) {
8729
- const auth = resolveAuth(deps);
8932
+ const auth = await resolveAuth(deps);
8730
8933
  try {
8731
- const client = clientFor(auth.baseUrl, auth.apiKey, deps);
8934
+ const client = clientFor(auth, deps);
8732
8935
  const agent = await client.beta.agents.retrieve(id);
8733
8936
  deps.writeStdout(`Name: ${agent.name}`);
8734
8937
  deps.writeStdout(`ID: ${agent.id}`);
@@ -8741,9 +8944,9 @@ async function getAgent(id, deps) {
8741
8944
  }
8742
8945
  }
8743
8946
  async function listEnvironments(deps, json) {
8744
- const auth = resolveAuth(deps);
8947
+ const auth = await resolveAuth(deps);
8745
8948
  try {
8746
- const client = clientFor(auth.baseUrl, auth.apiKey, deps);
8949
+ const client = clientFor(auth, deps);
8747
8950
  const environments = [];
8748
8951
  for await (const environment of client.beta.environments.list()) environments.push(environment);
8749
8952
  if (json) {
@@ -8771,9 +8974,9 @@ async function listEnvironments(deps, json) {
8771
8974
  }
8772
8975
  }
8773
8976
  async function getEnvironment(id, deps) {
8774
- const auth = resolveAuth(deps);
8977
+ const auth = await resolveAuth(deps);
8775
8978
  try {
8776
- const client = clientFor(auth.baseUrl, auth.apiKey, deps);
8979
+ const client = clientFor(auth, deps);
8777
8980
  const environment = await client.beta.environments.retrieve(id);
8778
8981
  deps.writeStdout(`Name: ${environment.name}`);
8779
8982
  deps.writeStdout(`ID: ${environment.id}`);
@@ -8784,6 +8987,454 @@ async function getEnvironment(id, deps) {
8784
8987
  throw new CliError(`Could not read environment ${id}: ${describeApiFailure(error)}`);
8785
8988
  }
8786
8989
  }
8990
+ function parseOptions(args, spec) {
8991
+ const values = /* @__PURE__ */ new Map();
8992
+ const booleans = /* @__PURE__ */ new Set();
8993
+ const positionals = [];
8994
+ const booleanNames = spec.booleans ?? [];
8995
+ for (let index = 0; index < args.length; index += 1) {
8996
+ const argument = args[index];
8997
+ if (!argument.startsWith("--")) {
8998
+ positionals.push(argument);
8999
+ continue;
9000
+ }
9001
+ const equals = argument.indexOf("=");
9002
+ const name = equals === -1 ? argument : argument.slice(0, equals);
9003
+ const inline = equals === -1 ? void 0 : argument.slice(equals + 1);
9004
+ if (booleanNames.includes(name)) {
9005
+ if (inline !== void 0) throw new CliError(`The option ${name} takes no value.`);
9006
+ booleans.add(name);
9007
+ continue;
9008
+ }
9009
+ if (!spec.values.includes(name)) throw new CliError(`Unknown option: ${name}.`);
9010
+ const value = inline ?? args[index + 1];
9011
+ if (value === void 0) throw new CliError(`The option ${name} needs a value.`);
9012
+ if (inline === void 0) index += 1;
9013
+ const list = values.get(name) ?? [];
9014
+ list.push(value);
9015
+ values.set(name, list);
9016
+ }
9017
+ return { positionals, values, booleans };
9018
+ }
9019
+ function lastOption(options, name) {
9020
+ return options.values.get(name)?.at(-1);
9021
+ }
9022
+ function requiredOption(options, name) {
9023
+ const value = lastOption(options, name);
9024
+ if (value === void 0 || value.length === 0) throw new CliError(`The option ${name} is required.`);
9025
+ return value;
9026
+ }
9027
+ function integerOption(options, name, min, max) {
9028
+ const raw = lastOption(options, name);
9029
+ if (raw === void 0) return void 0;
9030
+ if (!/^\d+$/.test(raw)) throw new CliError(`The option ${name} must be an integer.`);
9031
+ const value = Number(raw);
9032
+ if (value < min || value > max) {
9033
+ throw new CliError(`The option ${name} must be between ${min} and ${max}.`);
9034
+ }
9035
+ return value;
9036
+ }
9037
+ function booleanOption(options, name) {
9038
+ const raw = lastOption(options, name);
9039
+ if (raw === void 0) return void 0;
9040
+ if (raw === "true") return true;
9041
+ if (raw === "false") return false;
9042
+ throw new CliError(`The option ${name} must be "true" or "false".`);
9043
+ }
9044
+ async function listAll(client, path, query = {}) {
9045
+ const items = [];
9046
+ let page;
9047
+ do {
9048
+ const response = await client.platform.request({
9049
+ method: "get",
9050
+ path,
9051
+ query: { ...query, ...page !== null && page !== void 0 ? { page } : {} }
9052
+ });
9053
+ items.push(...response.data);
9054
+ page = response.next_page;
9055
+ } while (page !== null && page !== void 0 && page.length > 0);
9056
+ return items;
9057
+ }
9058
+ var statusOf = (record) => record.archived_at === null ? "active" : "archived";
9059
+ function matchSummary(match) {
9060
+ const parts = [];
9061
+ if (match.subject_prefix !== void 0) parts.push(`subject:${match.subject_prefix}`);
9062
+ if (match.audience !== void 0) parts.push(`aud:${match.audience}`);
9063
+ for (const [key, value] of Object.entries(match.claims ?? {})) parts.push(`${key}=${value}`);
9064
+ return parts.join(", ");
9065
+ }
9066
+ async function serviceAccountsCommand(argv, deps) {
9067
+ const [subcommand, ...args] = argv;
9068
+ if (subcommand === "list") {
9069
+ const options = parseOptions(args, { values: [], booleans: ["--include-archived", "--json"] });
9070
+ if (options.positionals.length > 0) throw new CliError("Usage: nouter-platform service-accounts list [--include-archived] [--json]");
9071
+ const auth = await resolveAuth(deps);
9072
+ try {
9073
+ const client = clientFor(auth, deps);
9074
+ const accounts = await listAll(
9075
+ client,
9076
+ "/v1/oma/service_accounts",
9077
+ options.booleans.has("--include-archived") ? { include_archived: "true" } : {}
9078
+ );
9079
+ if (options.booleans.has("--json")) {
9080
+ deps.writeStdout(JSON.stringify(accounts, null, 2));
9081
+ return 0;
9082
+ }
9083
+ if (accounts.length === 0) {
9084
+ deps.writeStdout("No service accounts.");
9085
+ return 0;
9086
+ }
9087
+ deps.writeStdout(
9088
+ table([
9089
+ ["ID", "NAME", "ROLE", "STATUS", "CREATED"],
9090
+ ...accounts.map((account) => [
9091
+ account.id,
9092
+ account.name,
9093
+ account.organization_role,
9094
+ statusOf(account),
9095
+ account.created_at
9096
+ ])
9097
+ ])
9098
+ );
9099
+ return 0;
9100
+ } catch (error) {
9101
+ if (error instanceof CliError) throw error;
9102
+ throw new CliError(`Could not list service accounts: ${describeApiFailure(error)}`);
9103
+ }
9104
+ }
9105
+ if (subcommand === "create") {
9106
+ const options = parseOptions(args, { values: ["--name", "--organization-role"], booleans: ["--json"] });
9107
+ const name = requiredOption(options, "--name");
9108
+ const role = requiredOption(options, "--organization-role");
9109
+ if (role !== "developer" && role !== "admin") {
9110
+ throw new CliError(`The organization role must be "developer" or "admin" (got "${role}").`);
9111
+ }
9112
+ const auth = await resolveAuth(deps);
9113
+ try {
9114
+ const account = await clientFor(auth, deps).platform.request({
9115
+ method: "post",
9116
+ path: "/v1/oma/service_accounts",
9117
+ body: { name, organization_role: role }
9118
+ });
9119
+ if (options.booleans.has("--json")) deps.writeStdout(JSON.stringify(account, null, 2));
9120
+ else deps.writeStdout(`Created service account ${account.id} (${account.name}).`);
9121
+ return 0;
9122
+ } catch (error) {
9123
+ if (error instanceof CliError) throw error;
9124
+ throw new CliError(`Could not create the service account: ${describeApiFailure(error)}`);
9125
+ }
9126
+ }
9127
+ if (subcommand === "archive") {
9128
+ const options = parseOptions(args, { values: [], booleans: [] });
9129
+ const id = options.positionals[0];
9130
+ if (id === void 0 || options.positionals.length > 1) {
9131
+ throw new CliError("Usage: nouter-platform service-accounts archive <service-account-id>");
9132
+ }
9133
+ const auth = await resolveAuth(deps);
9134
+ try {
9135
+ const account = await clientFor(auth, deps).platform.request({
9136
+ method: "post",
9137
+ path: `/v1/oma/service_accounts/${id}/archive`
9138
+ });
9139
+ deps.writeStdout(`Archived service account ${account.id}.`);
9140
+ return 0;
9141
+ } catch (error) {
9142
+ if (error instanceof CliError) throw error;
9143
+ throw new CliError(`Could not archive service account ${id}: ${describeApiFailure(error)}`);
9144
+ }
9145
+ }
9146
+ return usageError("service-accounts list|create|archive", deps);
9147
+ }
9148
+ async function federationIssuersCommand(argv, deps) {
9149
+ const [subcommand, ...args] = argv;
9150
+ if (subcommand === "list") {
9151
+ const options = parseOptions(args, { values: [], booleans: ["--include-archived", "--json"] });
9152
+ if (options.positionals.length > 0) throw new CliError("Usage: nouter-platform federation issuers list [--include-archived] [--json]");
9153
+ const auth = await resolveAuth(deps);
9154
+ try {
9155
+ const client = clientFor(auth, deps);
9156
+ const issuers = await listAll(
9157
+ client,
9158
+ "/v1/oma/federation_issuers",
9159
+ options.booleans.has("--include-archived") ? { include_archived: "true" } : {}
9160
+ );
9161
+ if (options.booleans.has("--json")) {
9162
+ deps.writeStdout(JSON.stringify(issuers, null, 2));
9163
+ return 0;
9164
+ }
9165
+ if (issuers.length === 0) {
9166
+ deps.writeStdout("No federation issuers.");
9167
+ return 0;
9168
+ }
9169
+ deps.writeStdout(
9170
+ table([
9171
+ ["ID", "NAME", "PROVIDER", "ISSUER URL", "STATUS", "CREATED"],
9172
+ ...issuers.map((issuer) => [
9173
+ issuer.id,
9174
+ issuer.name,
9175
+ issuer.provider,
9176
+ issuer.issuer_url,
9177
+ statusOf(issuer),
9178
+ issuer.created_at
9179
+ ])
9180
+ ])
9181
+ );
9182
+ return 0;
9183
+ } catch (error) {
9184
+ if (error instanceof CliError) throw error;
9185
+ throw new CliError(`Could not list federation issuers: ${describeApiFailure(error)}`);
9186
+ }
9187
+ }
9188
+ if (subcommand === "create") {
9189
+ const options = parseOptions(args, {
9190
+ values: ["--name", "--provider", "--issuer-url", "--jwks-url", "--check-jti", "--max-token-lifetime"],
9191
+ booleans: ["--json"]
9192
+ });
9193
+ const name = requiredOption(options, "--name");
9194
+ const provider = requiredOption(options, "--provider");
9195
+ if (provider !== "github" && provider !== "gcp" && provider !== "aws" && provider !== "custom") {
9196
+ throw new CliError(`The provider must be one of github, gcp, aws or custom (got "${provider}").`);
9197
+ }
9198
+ const issuerUrl = requiredOption(options, "--issuer-url");
9199
+ const jwksUrl = lastOption(options, "--jwks-url");
9200
+ const checkJti = booleanOption(options, "--check-jti");
9201
+ const maxLifetime = integerOption(options, "--max-token-lifetime", 60, 86400);
9202
+ const body = { name, provider, issuer_url: issuerUrl };
9203
+ if (jwksUrl !== void 0) body.jwks = { type: "explicit_url", url: jwksUrl };
9204
+ if (checkJti !== void 0) body.check_jti = checkJti;
9205
+ if (maxLifetime !== void 0) body.max_token_lifetime_seconds = maxLifetime;
9206
+ const auth = await resolveAuth(deps);
9207
+ try {
9208
+ const issuer = await clientFor(auth, deps).platform.request({
9209
+ method: "post",
9210
+ path: "/v1/oma/federation_issuers",
9211
+ body
9212
+ });
9213
+ if (options.booleans.has("--json")) deps.writeStdout(JSON.stringify(issuer, null, 2));
9214
+ else deps.writeStdout(`Created federation issuer ${issuer.id} (${issuer.name}).`);
9215
+ return 0;
9216
+ } catch (error) {
9217
+ if (error instanceof CliError) throw error;
9218
+ throw new CliError(`Could not create the federation issuer: ${describeApiFailure(error)}`);
9219
+ }
9220
+ }
9221
+ if (subcommand === "archive") {
9222
+ const options = parseOptions(args, { values: [], booleans: [] });
9223
+ const id = options.positionals[0];
9224
+ if (id === void 0 || options.positionals.length > 1) {
9225
+ throw new CliError("Usage: nouter-platform federation issuers archive <issuer-id>");
9226
+ }
9227
+ const auth = await resolveAuth(deps);
9228
+ try {
9229
+ const issuer = await clientFor(auth, deps).platform.request({
9230
+ method: "post",
9231
+ path: `/v1/oma/federation_issuers/${id}/archive`
9232
+ });
9233
+ deps.writeStdout(`Archived federation issuer ${issuer.id}.`);
9234
+ return 0;
9235
+ } catch (error) {
9236
+ if (error instanceof CliError) throw error;
9237
+ throw new CliError(`Could not archive federation issuer ${id}: ${describeApiFailure(error)}`);
9238
+ }
9239
+ }
9240
+ return usageError("federation issuers list|create|archive", deps);
9241
+ }
9242
+ async function federationRulesCommand(argv, deps) {
9243
+ const [subcommand, ...args] = argv;
9244
+ if (subcommand === "list") {
9245
+ const options = parseOptions(args, {
9246
+ values: ["--issuer"],
9247
+ booleans: ["--include-archived", "--json"]
9248
+ });
9249
+ if (options.positionals.length > 0) {
9250
+ throw new CliError("Usage: nouter-platform federation rules list [--issuer <issuer-id>] [--include-archived] [--json]");
9251
+ }
9252
+ const issuerId = lastOption(options, "--issuer");
9253
+ const auth = await resolveAuth(deps);
9254
+ try {
9255
+ const client = clientFor(auth, deps);
9256
+ const rules = await listAll(client, "/v1/oma/federation_rules", {
9257
+ ...options.booleans.has("--include-archived") ? { include_archived: "true" } : {},
9258
+ ...issuerId !== void 0 ? { issuer_id: issuerId } : {}
9259
+ });
9260
+ if (options.booleans.has("--json")) {
9261
+ deps.writeStdout(JSON.stringify(rules, null, 2));
9262
+ return 0;
9263
+ }
9264
+ if (rules.length === 0) {
9265
+ deps.writeStdout("No federation rules.");
9266
+ return 0;
9267
+ }
9268
+ deps.writeStdout(
9269
+ table([
9270
+ ["ID", "NAME", "ISSUER", "TARGET", "WORKSPACE", "MATCH", "SCOPES", "STATUS", "CREATED"],
9271
+ ...rules.map((rule) => [
9272
+ rule.id,
9273
+ rule.name,
9274
+ rule.issuer_id,
9275
+ rule.target.service_account_id,
9276
+ rule.applies_to_all_workspaces ? "all" : rule.workspace_id ?? "",
9277
+ matchSummary(rule.match),
9278
+ rule.scopes.join(","),
9279
+ statusOf(rule),
9280
+ rule.created_at
9281
+ ])
9282
+ ])
9283
+ );
9284
+ return 0;
9285
+ } catch (error) {
9286
+ if (error instanceof CliError) throw error;
9287
+ throw new CliError(`Could not list federation rules: ${describeApiFailure(error)}`);
9288
+ }
9289
+ }
9290
+ if (subcommand === "create") {
9291
+ const options = parseOptions(args, {
9292
+ values: [
9293
+ "--name",
9294
+ "--issuer",
9295
+ "--service-account",
9296
+ "--subject-prefix",
9297
+ "--audience",
9298
+ "--claim",
9299
+ "--workspace",
9300
+ "--scopes",
9301
+ "--token-lifetime"
9302
+ ],
9303
+ booleans: ["--all-workspaces", "--json"]
9304
+ });
9305
+ const name = requiredOption(options, "--name");
9306
+ const issuerId = requiredOption(options, "--issuer");
9307
+ const serviceAccountId = requiredOption(options, "--service-account");
9308
+ const subjectPrefix = lastOption(options, "--subject-prefix");
9309
+ const audience = lastOption(options, "--audience");
9310
+ const claims = {};
9311
+ for (const claim of options.values.get("--claim") ?? []) {
9312
+ const equals = claim.indexOf("=");
9313
+ if (equals <= 0) throw new CliError("The option --claim expects key=value.");
9314
+ claims[claim.slice(0, equals)] = claim.slice(equals + 1);
9315
+ }
9316
+ if (subjectPrefix === void 0 && Object.keys(claims).length === 0) {
9317
+ throw new CliError("The rule needs --subject-prefix or at least one --claim.");
9318
+ }
9319
+ const match = {
9320
+ ...subjectPrefix !== void 0 && { subject_prefix: subjectPrefix },
9321
+ ...audience !== void 0 && { audience },
9322
+ ...Object.keys(claims).length > 0 && { claims }
9323
+ };
9324
+ const workspaceId = lastOption(options, "--workspace");
9325
+ const allWorkspaces = options.booleans.has("--all-workspaces");
9326
+ if (allWorkspaces && workspaceId !== void 0) {
9327
+ throw new CliError("--workspace and --all-workspaces are mutually exclusive.");
9328
+ }
9329
+ if (!allWorkspaces && workspaceId === void 0) {
9330
+ throw new CliError("The rule needs --workspace <workspace-id> or --all-workspaces.");
9331
+ }
9332
+ const scopes = (options.values.get("--scopes") ?? []).flatMap((value) => value.split(",")).map((scope) => scope.trim()).filter((scope) => scope.length > 0);
9333
+ if (scopes.length === 0) throw new CliError("The option --scopes is required.");
9334
+ const lifetime = integerOption(options, "--token-lifetime", 60, 86400);
9335
+ const body = {
9336
+ name,
9337
+ issuer_id: issuerId,
9338
+ match,
9339
+ target: { type: "service_account", service_account_id: serviceAccountId },
9340
+ scopes,
9341
+ ...workspaceId !== void 0 && { workspace_id: workspaceId },
9342
+ ...allWorkspaces && { applies_to_all_workspaces: true },
9343
+ ...lifetime !== void 0 && { token_lifetime_seconds: lifetime }
9344
+ };
9345
+ const auth = await resolveAuth(deps);
9346
+ try {
9347
+ const rule = await clientFor(auth, deps).platform.request({
9348
+ method: "post",
9349
+ path: "/v1/oma/federation_rules",
9350
+ body
9351
+ });
9352
+ if (options.booleans.has("--json")) deps.writeStdout(JSON.stringify(rule, null, 2));
9353
+ else deps.writeStdout(`Created federation rule ${rule.id} (${rule.name}).`);
9354
+ return 0;
9355
+ } catch (error) {
9356
+ if (error instanceof CliError) throw error;
9357
+ throw new CliError(`Could not create the federation rule: ${describeApiFailure(error)}`);
9358
+ }
9359
+ }
9360
+ if (subcommand === "archive") {
9361
+ const options = parseOptions(args, { values: [], booleans: [] });
9362
+ const id = options.positionals[0];
9363
+ if (id === void 0 || options.positionals.length > 1) {
9364
+ throw new CliError("Usage: nouter-platform federation rules archive <rule-id>");
9365
+ }
9366
+ const auth = await resolveAuth(deps);
9367
+ try {
9368
+ const rule = await clientFor(auth, deps).platform.request({
9369
+ method: "post",
9370
+ path: `/v1/oma/federation_rules/${id}/archive`
9371
+ });
9372
+ deps.writeStdout(`Archived federation rule ${rule.id}.`);
9373
+ return 0;
9374
+ } catch (error) {
9375
+ if (error instanceof CliError) throw error;
9376
+ throw new CliError(`Could not archive federation rule ${id}: ${describeApiFailure(error)}`);
9377
+ }
9378
+ }
9379
+ return usageError("federation rules list|create|archive", deps);
9380
+ }
9381
+ async function federationTokenCommand(argv, deps) {
9382
+ const options = parseOptions(argv, { values: [], booleans: ["--json"] });
9383
+ if (options.positionals.length > 0) throw new CliError("Usage: nouter-platform federation token [--json]");
9384
+ const settings = federationSettingsOrNull();
9385
+ if (settings === null) {
9386
+ throw new CliError(
9387
+ "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."
9388
+ );
9389
+ }
9390
+ const stored = readConfig({ warn: deps.writeStderr });
9391
+ const baseUrl = requireBaseUrl(stored);
9392
+ const token = await federationProviderFor(baseUrl, settings, deps).getToken().catch(federationFailure);
9393
+ if (options.booleans.has("--json")) {
9394
+ deps.writeStdout(
9395
+ JSON.stringify(
9396
+ {
9397
+ access_token: token.accessToken,
9398
+ token_type: "Bearer",
9399
+ expires_in: token.expiresIn,
9400
+ scope: token.scopes.join(" ")
9401
+ },
9402
+ null,
9403
+ 2
9404
+ )
9405
+ );
9406
+ } else {
9407
+ deps.writeStdout(token.accessToken);
9408
+ }
9409
+ return 0;
9410
+ }
9411
+ function authStatus(deps) {
9412
+ const stored = readConfig({ warn: deps.writeStderr });
9413
+ const envKey = environmentApiKey();
9414
+ const rule = process.env.NOUTER_PLATFORM_FEDERATION_RULE_ID;
9415
+ const organization = process.env.NOUTER_PLATFORM_ORGANIZATION_ID;
9416
+ const identity = identityTokenSourceFromEnv(process.env);
9417
+ const envBase = process.env.NOUTER_PLATFORM_BASE_URL;
9418
+ const rawBaseUrl = envBase && envBase.length > 0 ? envBase : stored?.baseUrl ?? null;
9419
+ let baseUrl = null;
9420
+ if (rawBaseUrl !== null) {
9421
+ try {
9422
+ const parsed = new URL(rawBaseUrl);
9423
+ baseUrl = `${parsed.origin}${parsed.pathname.replace(/\/+$/, "")}`;
9424
+ } catch {
9425
+ baseUrl = "(invalid URL)";
9426
+ }
9427
+ }
9428
+ let source;
9429
+ if (envKey !== null) source = `API key (${envKey.name})`;
9430
+ else if (typeof rule === "string" && rule.length > 0 && typeof organization === "string" && organization.length > 0 && identity !== null) {
9431
+ source = `federation (rule ${rule})`;
9432
+ } else if (stored !== null) source = "login token";
9433
+ else source = "none";
9434
+ deps.writeStdout(`Source: ${source}`);
9435
+ if (baseUrl !== null) deps.writeStdout(`Base URL: ${baseUrl}`);
9436
+ return source === "none" ? 1 : 0;
9437
+ }
8787
9438
  function applyClientFor(client) {
8788
9439
  return {
8789
9440
  async listAgents() {
@@ -8844,8 +9495,8 @@ async function applyCommand(argv, deps) {
8844
9495
  if (error instanceof ApplyValidationError) throw new CliError(error.message);
8845
9496
  throw error;
8846
9497
  }
8847
- const auth = resolveAuth(deps);
8848
- const client = applyClientFor(clientFor(auth.baseUrl, auth.apiKey, deps, { maxRetries: 0 }));
9498
+ const auth = await resolveAuth(deps);
9499
+ const client = applyClientFor(clientFor(auth, deps, { maxRetries: 0 }));
8849
9500
  let current;
8850
9501
  try {
8851
9502
  current = {
@@ -8876,16 +9527,25 @@ function printHelp(deps) {
8876
9527
  "Usage: nouter-platform <command> [options]",
8877
9528
  "",
8878
9529
  "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",
9530
+ " login --api-key (key from stdin) or --browser",
9531
+ " logout Remove the stored API key (local only; revoke it in the console)",
9532
+ " whoami Show the organization, role and scopes",
9533
+ " auth status: show which credential the CLI would use",
9534
+ " agents list | get <agent-id>",
9535
+ " environments list | get <environment-id>",
9536
+ " service-accounts list | create | archive",
9537
+ " federation issuers list|create|archive | rules list|create|archive | token",
9538
+ " apply Apply agents and environments from files",
8885
9539
  "",
8886
9540
  "Environment:",
8887
- " NOUTER_PLATFORM_API_KEY API key; wins over the stored key",
8888
- " NOUTER_PLATFORM_BASE_URL API base URL"
9541
+ " NOUTER_PLATFORM_API_KEY API key; wins over the stored key and the federation",
9542
+ " NOUTER_PLATFORM_BASE_URL API base URL",
9543
+ " NOUTER_PLATFORM_FEDERATION_RULE_ID Enable the federated credential for this rule",
9544
+ " NOUTER_PLATFORM_ORGANIZATION_ID The organization of the federation rule",
9545
+ " NOUTER_PLATFORM_SERVICE_ACCOUNT_ID The service account, when the rule spans several",
9546
+ " NOUTER_PLATFORM_WORKSPACE_ID The workspace, when the rule spans several",
9547
+ " NOUTER_PLATFORM_IDENTITY_TOKEN The OIDC assertion, or",
9548
+ " NOUTER_PLATFORM_IDENTITY_TOKEN_FILE The file with the OIDC assertion"
8889
9549
  ].join("\n")
8890
9550
  );
8891
9551
  }
@@ -8906,8 +9566,8 @@ async function dispatch(argv, deps) {
8906
9566
  deps.writeStdout(clearConfig() ? "Logged out." : "No stored key.");
8907
9567
  return 0;
8908
9568
  case "whoami": {
8909
- const auth = resolveAuth(deps);
8910
- printWhoami(await fetchMe(auth.baseUrl, auth.apiKey, deps), deps);
9569
+ const auth = await resolveAuth(deps);
9570
+ printWhoami(await fetchMe(auth, deps), deps);
8911
9571
  return 0;
8912
9572
  }
8913
9573
  case "agents": {
@@ -8924,6 +9584,19 @@ async function dispatch(argv, deps) {
8924
9584
  if (subcommand === "get" && args[0]) return await getEnvironment(args[0], deps);
8925
9585
  return usageError("environments list|get <environment-id>", deps);
8926
9586
  }
9587
+ case "auth": {
9588
+ if (rest.length === 1 && rest[0] === "status") return authStatus(deps);
9589
+ return usageError("auth status", deps);
9590
+ }
9591
+ case "service-accounts":
9592
+ return await serviceAccountsCommand(rest, deps);
9593
+ case "federation": {
9594
+ const [group, ...args] = rest;
9595
+ if (group === "issuers") return await federationIssuersCommand(args, deps);
9596
+ if (group === "rules") return await federationRulesCommand(args, deps);
9597
+ if (group === "token") return await federationTokenCommand(args, deps);
9598
+ return usageError("federation issuers|rules|token", deps);
9599
+ }
8927
9600
  case "apply":
8928
9601
  return await applyCommand(rest, deps);
8929
9602
  default:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nouter/platform-cli",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "CLI for the Nouter platform",
5
5
  "type": "module",
6
6
  "bin": {
@@ -46,7 +46,7 @@
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.2.0",
50
50
  "yaml": "2.9.1"
51
51
  },
52
52
  "devDependencies": {