@nouter/platform-cli 0.3.0 → 0.4.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.
- package/README.md +68 -6
- package/dist/index.js +2302 -410
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -7368,23 +7368,10 @@ var require_dist = __commonJS({
|
|
|
7368
7368
|
|
|
7369
7369
|
// src/index.ts
|
|
7370
7370
|
import { spawn } from "node:child_process";
|
|
7371
|
-
import { randomBytes } from "node:crypto";
|
|
7372
|
-
import {
|
|
7373
|
-
|
|
7374
|
-
|
|
7375
|
-
existsSync,
|
|
7376
|
-
fchmodSync,
|
|
7377
|
-
lstatSync,
|
|
7378
|
-
mkdirSync,
|
|
7379
|
-
openSync,
|
|
7380
|
-
readFileSync as readFileSync3,
|
|
7381
|
-
renameSync,
|
|
7382
|
-
statSync as statSync2,
|
|
7383
|
-
unlinkSync,
|
|
7384
|
-
writeSync
|
|
7385
|
-
} from "node:fs";
|
|
7386
|
-
import { homedir, hostname } from "node:os";
|
|
7387
|
-
import { dirname, join as join2 } from "node:path";
|
|
7371
|
+
import { randomBytes as randomBytes3 } from "node:crypto";
|
|
7372
|
+
import { readFileSync as readFileSync4 } from "node:fs";
|
|
7373
|
+
import { hostname } from "node:os";
|
|
7374
|
+
import { dirname, join as join3 } from "node:path";
|
|
7388
7375
|
import { fileURLToPath } from "node:url";
|
|
7389
7376
|
import {
|
|
7390
7377
|
NouterPlatform
|
|
@@ -8249,230 +8236,1405 @@ function formatApplyResults(results) {
|
|
|
8249
8236
|
return lines;
|
|
8250
8237
|
}
|
|
8251
8238
|
|
|
8252
|
-
// src/
|
|
8253
|
-
|
|
8254
|
-
|
|
8255
|
-
|
|
8256
|
-
|
|
8257
|
-
|
|
8258
|
-
|
|
8259
|
-
|
|
8260
|
-
|
|
8261
|
-
|
|
8262
|
-
|
|
8263
|
-
|
|
8264
|
-
|
|
8265
|
-
|
|
8266
|
-
|
|
8267
|
-
|
|
8268
|
-
|
|
8269
|
-
|
|
8270
|
-
|
|
8271
|
-
|
|
8272
|
-
|
|
8273
|
-
|
|
8274
|
-
|
|
8275
|
-
|
|
8276
|
-
|
|
8277
|
-
|
|
8278
|
-
|
|
8279
|
-
|
|
8280
|
-
|
|
8281
|
-
},
|
|
8282
|
-
|
|
8283
|
-
|
|
8284
|
-
|
|
8285
|
-
|
|
8286
|
-
|
|
8287
|
-
|
|
8288
|
-
|
|
8289
|
-
|
|
8290
|
-
|
|
8291
|
-
|
|
8292
|
-
|
|
8293
|
-
|
|
8294
|
-
|
|
8295
|
-
|
|
8296
|
-
|
|
8297
|
-
|
|
8298
|
-
|
|
8299
|
-
|
|
8300
|
-
|
|
8301
|
-
|
|
8302
|
-
|
|
8303
|
-
|
|
8304
|
-
|
|
8305
|
-
|
|
8306
|
-
|
|
8307
|
-
|
|
8308
|
-
|
|
8309
|
-
|
|
8310
|
-
|
|
8311
|
-
|
|
8312
|
-
|
|
8313
|
-
|
|
8314
|
-
|
|
8315
|
-
|
|
8316
|
-
|
|
8317
|
-
|
|
8318
|
-
|
|
8319
|
-
|
|
8320
|
-
|
|
8321
|
-
|
|
8322
|
-
|
|
8323
|
-
},
|
|
8239
|
+
// src/api-errors.ts
|
|
8240
|
+
function describeApiFailure(error) {
|
|
8241
|
+
const candidate = error;
|
|
8242
|
+
const status = typeof candidate.status === "number" ? candidate.status : void 0;
|
|
8243
|
+
if (status !== void 0) {
|
|
8244
|
+
const type = candidate.error?.error?.type ?? candidate.error?.type ?? candidate.type;
|
|
8245
|
+
const code2 = candidate.error?.error?.details?.error_code ?? candidate.errorCode;
|
|
8246
|
+
const detail = [type, code2].filter((part) => typeof part === "string" && part.length > 0).join(", ");
|
|
8247
|
+
const requestId = candidate.request_id ?? candidate.error?.request_id ?? candidate.requestId ?? candidate.requestID;
|
|
8248
|
+
return `the server answered ${status}${detail ? ` (${detail})` : ""}${requestId ? `, request ${requestId}` : ""}`;
|
|
8249
|
+
}
|
|
8250
|
+
const name = error.name;
|
|
8251
|
+
const causeName = candidate.cause?.name;
|
|
8252
|
+
if (name === "AbortError" || name === "TimeoutError" || name === "APIConnectionTimeoutError" || // El SDK envuelve el aborto propio (nuestro `AbortSignal.timeout`) en este error.
|
|
8253
|
+
name === "APIUserAbortError" || causeName === "AbortError" || causeName === "TimeoutError" || candidate.cause?.code === "ABORT_ERR") {
|
|
8254
|
+
return "the request timed out";
|
|
8255
|
+
}
|
|
8256
|
+
const code = candidate.cause?.code;
|
|
8257
|
+
return code ? `the request failed (${code})` : "the request failed";
|
|
8258
|
+
}
|
|
8259
|
+
|
|
8260
|
+
// src/feedback.ts
|
|
8261
|
+
var import_yaml2 = __toESM(require_dist(), 1);
|
|
8262
|
+
import { randomUUID } from "node:crypto";
|
|
8263
|
+
import { closeSync, constants, fstatSync, openSync, readSync } from "node:fs";
|
|
8264
|
+
import { createInterface } from "node:readline/promises";
|
|
8265
|
+
|
|
8266
|
+
// src/printable.ts
|
|
8267
|
+
var UNSAFE_CHARACTERS = new RegExp(
|
|
8268
|
+
"[\\u0000-\\u0008\\u000b-\\u001f\\u007f-\\u009f\\u061c\\u200b-\\u200f\\u2028-\\u202e\\u2060-\\u2069\\ufeff\\ufe00-\\ufe0f\\u{e0000}-\\u{e007f}]",
|
|
8269
|
+
"gu"
|
|
8270
|
+
);
|
|
8271
|
+
function printable(text) {
|
|
8272
|
+
return text.replace(UNSAFE_CHARACTERS, "\uFFFD");
|
|
8273
|
+
}
|
|
8274
|
+
|
|
8275
|
+
// src/non-api-host.ts
|
|
8276
|
+
function hostOf(url) {
|
|
8277
|
+
try {
|
|
8278
|
+
return new URL(url).host;
|
|
8279
|
+
} catch {
|
|
8280
|
+
return url;
|
|
8281
|
+
}
|
|
8282
|
+
}
|
|
8283
|
+
function notTheApiMessage(url, response) {
|
|
8284
|
+
const status = response.status;
|
|
8285
|
+
if (status >= 500) return null;
|
|
8286
|
+
const contentType = (response.headers.get("content-type") ?? "").trim();
|
|
8287
|
+
const mediaType = contentType.toLowerCase();
|
|
8288
|
+
const isRedirect = status >= 300 && status < 400;
|
|
8289
|
+
const isHtml = mediaType.startsWith("text/html");
|
|
8290
|
+
const followedToNonJson = response.redirected && !mediaType.includes("application/json");
|
|
8291
|
+
if (!isRedirect && !isHtml && !followedToNonJson) return null;
|
|
8292
|
+
const shown = printable(contentType || "(no content-type)");
|
|
8293
|
+
return `this host is not the API: ${hostOf(url)} responded ${status} ${shown}`;
|
|
8294
|
+
}
|
|
8295
|
+
|
|
8296
|
+
// src/feedback.ts
|
|
8297
|
+
var FEEDBACK_FLAG = "NOUTER_PLATFORM_FEEDBACK";
|
|
8298
|
+
var FEEDBACK_DISABLED_MESSAGE = "Feedback commands are disabled; set NOUTER_PLATFORM_FEEDBACK=1";
|
|
8299
|
+
var FEEDBACK_CREATE_VALUES = ["--title", "--field", "--fields"];
|
|
8300
|
+
var FEEDBACK_CREATE_BOOLEANS = ["--yes", "--confirm-duplicate", "--json"];
|
|
8301
|
+
var FEEDBACK_SHOW_VALUES = [];
|
|
8302
|
+
var FEEDBACK_SHOW_BOOLEANS = ["--json"];
|
|
8303
|
+
var FEEDBACK_VOTE_VALUES = [];
|
|
8304
|
+
var FEEDBACK_VOTE_BOOLEANS = [];
|
|
8305
|
+
var FEEDBACK_COMMENT_VALUES = ["--body", "--body-file"];
|
|
8306
|
+
var FEEDBACK_COMMENT_BOOLEANS = [];
|
|
8307
|
+
var FEEDBACK_LIST_VALUES = ["--cursor"];
|
|
8308
|
+
var FEEDBACK_LIST_BOOLEANS = ["--json"];
|
|
8309
|
+
var FEEDBACK_COMMANDS = [
|
|
8324
8310
|
{
|
|
8325
|
-
path: "
|
|
8326
|
-
summary: "
|
|
8327
|
-
values:
|
|
8328
|
-
booleans:
|
|
8311
|
+
path: "feedback bug",
|
|
8312
|
+
summary: "Report a bug to the Nouter feedback repository",
|
|
8313
|
+
values: FEEDBACK_CREATE_VALUES,
|
|
8314
|
+
booleans: FEEDBACK_CREATE_BOOLEANS,
|
|
8329
8315
|
positionals: []
|
|
8330
8316
|
},
|
|
8331
8317
|
{
|
|
8332
|
-
path: "
|
|
8333
|
-
summary: "
|
|
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"],
|
|
8318
|
+
path: "feedback feature",
|
|
8319
|
+
summary: "Request a feature in the Nouter feedback repository",
|
|
8320
|
+
values: FEEDBACK_CREATE_VALUES,
|
|
8321
|
+
booleans: FEEDBACK_CREATE_BOOLEANS,
|
|
8343
8322
|
positionals: []
|
|
8344
8323
|
},
|
|
8345
8324
|
{
|
|
8346
|
-
path: "
|
|
8347
|
-
summary: "
|
|
8348
|
-
values:
|
|
8349
|
-
booleans:
|
|
8325
|
+
path: "feedback question",
|
|
8326
|
+
summary: "Ask a question in the Nouter feedback repository",
|
|
8327
|
+
values: FEEDBACK_CREATE_VALUES,
|
|
8328
|
+
booleans: FEEDBACK_CREATE_BOOLEANS,
|
|
8350
8329
|
positionals: []
|
|
8351
8330
|
},
|
|
8352
8331
|
{
|
|
8353
|
-
path: "
|
|
8354
|
-
summary: "
|
|
8355
|
-
values:
|
|
8356
|
-
booleans:
|
|
8357
|
-
positionals: ["<
|
|
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: []
|
|
8332
|
+
path: "feedback show",
|
|
8333
|
+
summary: "Show one feedback issue, its body and its replies",
|
|
8334
|
+
values: FEEDBACK_SHOW_VALUES,
|
|
8335
|
+
booleans: FEEDBACK_SHOW_BOOLEANS,
|
|
8336
|
+
positionals: ["<n>"]
|
|
8365
8337
|
},
|
|
8366
8338
|
{
|
|
8367
|
-
path: "
|
|
8368
|
-
summary: "
|
|
8369
|
-
values:
|
|
8370
|
-
|
|
8371
|
-
|
|
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: []
|
|
8339
|
+
path: "feedback vote",
|
|
8340
|
+
summary: "Vote for a feedback issue",
|
|
8341
|
+
values: FEEDBACK_VOTE_VALUES,
|
|
8342
|
+
booleans: FEEDBACK_VOTE_BOOLEANS,
|
|
8343
|
+
positionals: ["<n>"]
|
|
8382
8344
|
},
|
|
8383
8345
|
{
|
|
8384
|
-
path: "
|
|
8385
|
-
summary: "
|
|
8386
|
-
values:
|
|
8387
|
-
booleans:
|
|
8388
|
-
positionals: ["<
|
|
8346
|
+
path: "feedback comment",
|
|
8347
|
+
summary: "Comment on a feedback issue",
|
|
8348
|
+
values: FEEDBACK_COMMENT_VALUES,
|
|
8349
|
+
booleans: FEEDBACK_COMMENT_BOOLEANS,
|
|
8350
|
+
positionals: ["<n>"]
|
|
8389
8351
|
},
|
|
8390
8352
|
{
|
|
8391
|
-
path: "
|
|
8392
|
-
summary: "
|
|
8393
|
-
values:
|
|
8394
|
-
booleans:
|
|
8353
|
+
path: "feedback list",
|
|
8354
|
+
summary: "List the feedback issues you opened, voted for or commented on",
|
|
8355
|
+
values: FEEDBACK_LIST_VALUES,
|
|
8356
|
+
booleans: FEEDBACK_LIST_BOOLEANS,
|
|
8395
8357
|
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
8358
|
}
|
|
8405
8359
|
];
|
|
8406
|
-
|
|
8407
|
-
|
|
8408
|
-
|
|
8409
|
-
|
|
8410
|
-
return
|
|
8411
|
-
|
|
8412
|
-
|
|
8413
|
-
|
|
8414
|
-
|
|
8415
|
-
var
|
|
8416
|
-
|
|
8417
|
-
|
|
8418
|
-
|
|
8360
|
+
function feedbackEnabled(env = process.env) {
|
|
8361
|
+
return env[FEEDBACK_FLAG] === "1";
|
|
8362
|
+
}
|
|
8363
|
+
function feedbackHelpLines() {
|
|
8364
|
+
if (!feedbackEnabled()) return [];
|
|
8365
|
+
return [" feedback bug | feature | question | show | vote | comment | list"];
|
|
8366
|
+
}
|
|
8367
|
+
var FEEDBACK_MAX_TITLE = 200;
|
|
8368
|
+
var FEEDBACK_MAX_TEXT = 8e3;
|
|
8369
|
+
var FEEDBACK_MAX_INPUT_FILE_BYTES = 1024 * 1024;
|
|
8370
|
+
var FEEDBACK_MAX_FIELDS = 50;
|
|
8371
|
+
var FEEDBACK_KINDS = ["bug", "feature", "question"];
|
|
8372
|
+
var FORM_FIELD_TYPES = ["textarea", "input", "dropdown", "checkboxes"];
|
|
8373
|
+
var FeedbackApiError = class extends Error {
|
|
8374
|
+
status;
|
|
8375
|
+
code;
|
|
8376
|
+
requestId;
|
|
8377
|
+
retryAfterMs;
|
|
8378
|
+
fields;
|
|
8379
|
+
candidates;
|
|
8380
|
+
formsVersion;
|
|
8381
|
+
constructor(init) {
|
|
8382
|
+
super(`the feedback API answered ${init.status} (${init.code})`);
|
|
8383
|
+
this.name = "FeedbackApiError";
|
|
8384
|
+
this.status = init.status;
|
|
8385
|
+
this.code = init.code;
|
|
8386
|
+
this.requestId = init.requestId;
|
|
8387
|
+
this.retryAfterMs = init.retryAfterMs;
|
|
8388
|
+
this.fields = init.fields ?? [];
|
|
8389
|
+
this.candidates = init.candidates ?? [];
|
|
8390
|
+
this.formsVersion = init.formsVersion ?? null;
|
|
8419
8391
|
}
|
|
8420
8392
|
};
|
|
8421
|
-
|
|
8422
|
-
|
|
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;
|
|
8393
|
+
function isObject2(value) {
|
|
8394
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
8428
8395
|
}
|
|
8429
|
-
|
|
8430
|
-
|
|
8431
|
-
const
|
|
8432
|
-
|
|
8433
|
-
|
|
8434
|
-
|
|
8396
|
+
function parseRetryAfterMs(value) {
|
|
8397
|
+
if (value === null) return null;
|
|
8398
|
+
const seconds = Number(value);
|
|
8399
|
+
return Number.isInteger(seconds) && seconds >= 0 ? seconds * 1e3 : null;
|
|
8400
|
+
}
|
|
8401
|
+
function parseFields(value) {
|
|
8402
|
+
if (!Array.isArray(value)) return [];
|
|
8403
|
+
const fields = [];
|
|
8404
|
+
for (const raw of value) {
|
|
8405
|
+
if (!isObject2(raw)) continue;
|
|
8406
|
+
if (typeof raw.field !== "string" || typeof raw.problem !== "string") continue;
|
|
8407
|
+
fields.push({ field: raw.field, problem: raw.problem });
|
|
8408
|
+
}
|
|
8409
|
+
return fields;
|
|
8410
|
+
}
|
|
8411
|
+
function parseCandidates(value) {
|
|
8412
|
+
if (!Array.isArray(value)) return [];
|
|
8413
|
+
const candidates = [];
|
|
8414
|
+
for (const raw of value) {
|
|
8415
|
+
if (!isObject2(raw)) continue;
|
|
8416
|
+
if (typeof raw.issue !== "number" || typeof raw.title !== "string") continue;
|
|
8417
|
+
if (typeof raw.url !== "string" || typeof raw.state !== "string") continue;
|
|
8418
|
+
candidates.push({ issue: raw.issue, title: raw.title, url: raw.url, state: raw.state });
|
|
8419
|
+
}
|
|
8420
|
+
return candidates;
|
|
8421
|
+
}
|
|
8422
|
+
function parseApiError(status, body, headers) {
|
|
8423
|
+
const root = isObject2(body) ? body : {};
|
|
8424
|
+
const error = isObject2(root.error) ? root.error : {};
|
|
8425
|
+
const details = isObject2(error.details) ? error.details : {};
|
|
8426
|
+
const code = typeof details.error_code === "string" && details.error_code.length > 0 ? details.error_code : typeof error.type === "string" && error.type.length > 0 ? error.type : "unknown_error";
|
|
8427
|
+
const requestId = typeof root.request_id === "string" && root.request_id.length > 0 ? root.request_id : headers.get("request-id") ?? headers.get("x-request-id");
|
|
8428
|
+
const retryAfterMs = typeof error.retry_after_ms === "number" ? error.retry_after_ms : parseRetryAfterMs(headers.get("retry-after"));
|
|
8429
|
+
return new FeedbackApiError({
|
|
8430
|
+
status,
|
|
8431
|
+
code,
|
|
8432
|
+
requestId,
|
|
8433
|
+
retryAfterMs,
|
|
8434
|
+
fields: parseFields(details.fields),
|
|
8435
|
+
candidates: parseCandidates(details.candidates),
|
|
8436
|
+
formsVersion: typeof details.forms_version === "number" ? details.forms_version : null
|
|
8437
|
+
});
|
|
8438
|
+
}
|
|
8439
|
+
function retrySeconds(error) {
|
|
8440
|
+
return error.retryAfterMs === null ? 60 : Math.max(1, Math.ceil(error.retryAfterMs / 1e3));
|
|
8441
|
+
}
|
|
8442
|
+
function describeCode(error) {
|
|
8443
|
+
switch (error.code) {
|
|
8444
|
+
case "person_required":
|
|
8445
|
+
return "This command needs a personal login; run `nouter-platform login`.";
|
|
8446
|
+
case "sensitive_data":
|
|
8447
|
+
return "The text seems to contain customer data, personal data or secrets.";
|
|
8448
|
+
case "daily_limit":
|
|
8449
|
+
return `The daily feedback limit was reached; try again in ${retrySeconds(error)} seconds.`;
|
|
8450
|
+
case "invalid_fields":
|
|
8451
|
+
return "The fields do not match the form.";
|
|
8452
|
+
case "possible_duplicates":
|
|
8453
|
+
return "There are open issues with a similar title.";
|
|
8454
|
+
case "not_found":
|
|
8455
|
+
return "The feedback issue was not found.";
|
|
8456
|
+
case "feedback_timeout":
|
|
8457
|
+
return "The feedback service took too long to answer; try again later.";
|
|
8458
|
+
case "feedback_unavailable":
|
|
8459
|
+
case "github_unavailable":
|
|
8460
|
+
case "review_unavailable":
|
|
8461
|
+
return "Feedback is not available right now; try again later.";
|
|
8462
|
+
default:
|
|
8463
|
+
return `The feedback service answered ${error.status}${error.code === "unknown_error" ? "" : ` (${printable(error.code)})`}; try again later.`;
|
|
8435
8464
|
}
|
|
8436
|
-
return trimmed;
|
|
8437
8465
|
}
|
|
8438
|
-
function
|
|
8439
|
-
|
|
8440
|
-
|
|
8466
|
+
function describeFeedbackFailure(error) {
|
|
8467
|
+
const suffix = error.requestId === null ? "" : ` (request ${printable(error.requestId)})`;
|
|
8468
|
+
const lines = [`${describeCode(error)}${suffix}`];
|
|
8469
|
+
if (error.code === "invalid_fields") {
|
|
8470
|
+
for (const field of error.fields) lines.push(`${printable(field.field)}: ${printable(field.problem)}`);
|
|
8441
8471
|
}
|
|
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
|
-
};
|
|
8472
|
+
return lines;
|
|
8453
8473
|
}
|
|
8454
|
-
|
|
8455
|
-
|
|
8456
|
-
|
|
8474
|
+
function isTimeout(error) {
|
|
8475
|
+
const value = error;
|
|
8476
|
+
return value?.name === "TimeoutError" || value?.name === "AbortError" || value?.cause?.name === "TimeoutError" || value?.cause?.name === "AbortError" || value?.cause?.code === "ABORT_ERR";
|
|
8477
|
+
}
|
|
8478
|
+
function describeNetworkFailure(error) {
|
|
8479
|
+
const value = error;
|
|
8480
|
+
return value?.cause?.code ?? value?.name ?? "network error";
|
|
8481
|
+
}
|
|
8482
|
+
async function feedbackRequest(auth, method, path, body, deps, headers = {}) {
|
|
8483
|
+
const url = `${auth.baseUrl.replace(/\/+$/, "")}${path}`;
|
|
8484
|
+
const requestHeaders = {
|
|
8485
|
+
Accept: "application/json",
|
|
8486
|
+
"User-Agent": deps.userAgent,
|
|
8487
|
+
...headers
|
|
8488
|
+
};
|
|
8489
|
+
if (auth.transport === "bearer") requestHeaders.Authorization = `Bearer ${auth.credential}`;
|
|
8490
|
+
else requestHeaders["x-api-key"] = auth.credential;
|
|
8491
|
+
const payload = body === void 0 ? void 0 : JSON.stringify(body);
|
|
8492
|
+
if (payload !== void 0) requestHeaders["Content-Type"] = "application/json";
|
|
8493
|
+
let response;
|
|
8457
8494
|
try {
|
|
8458
|
-
|
|
8495
|
+
response = await deps.fetch(url, {
|
|
8496
|
+
method,
|
|
8497
|
+
headers: requestHeaders,
|
|
8498
|
+
...payload !== void 0 && { body: payload },
|
|
8499
|
+
redirect: "manual",
|
|
8500
|
+
signal: AbortSignal.timeout(deps.requestTimeoutMs)
|
|
8501
|
+
});
|
|
8502
|
+
} catch (error) {
|
|
8503
|
+
if (isTimeout(error)) throw new deps.CliError("The feedback request timed out; try again later.");
|
|
8504
|
+
throw new deps.CliError(
|
|
8505
|
+
`The feedback request could not reach the API (${describeNetworkFailure(error)}); try again later.`
|
|
8506
|
+
);
|
|
8507
|
+
}
|
|
8508
|
+
const notApi = notTheApiMessage(url, response);
|
|
8509
|
+
if (notApi !== null) throw new deps.CliError(printable(notApi));
|
|
8510
|
+
const text = await response.text();
|
|
8511
|
+
let parsed;
|
|
8512
|
+
let invalid = false;
|
|
8513
|
+
try {
|
|
8514
|
+
parsed = text === "" ? void 0 : JSON.parse(text);
|
|
8459
8515
|
} catch {
|
|
8460
|
-
|
|
8516
|
+
invalid = true;
|
|
8517
|
+
}
|
|
8518
|
+
if (!response.ok) throw parseApiError(response.status, invalid ? void 0 : parsed, response.headers);
|
|
8519
|
+
if (invalid) throw new deps.CliError("The feedback service answered with something that is not JSON.");
|
|
8520
|
+
return parsed;
|
|
8521
|
+
}
|
|
8522
|
+
function parseFormFields(value) {
|
|
8523
|
+
if (!Array.isArray(value)) return null;
|
|
8524
|
+
const fields = [];
|
|
8525
|
+
for (const raw of value) {
|
|
8526
|
+
if (!isObject2(raw)) return null;
|
|
8527
|
+
if (typeof raw.id !== "string" || typeof raw.label !== "string" || typeof raw.required !== "boolean") {
|
|
8528
|
+
return null;
|
|
8529
|
+
}
|
|
8530
|
+
if (!FORM_FIELD_TYPES.includes(raw.type)) return null;
|
|
8531
|
+
const field = {
|
|
8532
|
+
id: printable(raw.id),
|
|
8533
|
+
type: raw.type,
|
|
8534
|
+
label: printable(raw.label),
|
|
8535
|
+
required: raw.required
|
|
8536
|
+
};
|
|
8537
|
+
if (Array.isArray(raw.options) && raw.options.every((option) => typeof option === "string")) {
|
|
8538
|
+
field.options = raw.options.map((option) => printable(option));
|
|
8539
|
+
}
|
|
8540
|
+
if (typeof raw.maxLength === "number") field.maxLength = raw.maxLength;
|
|
8541
|
+
fields.push(field);
|
|
8461
8542
|
}
|
|
8543
|
+
return fields;
|
|
8462
8544
|
}
|
|
8463
|
-
function
|
|
8464
|
-
const
|
|
8465
|
-
if (
|
|
8466
|
-
const
|
|
8467
|
-
|
|
8468
|
-
|
|
8469
|
-
|
|
8470
|
-
const
|
|
8471
|
-
if (!
|
|
8472
|
-
|
|
8473
|
-
|
|
8474
|
-
|
|
8475
|
-
|
|
8545
|
+
async function loadForms(auth, deps) {
|
|
8546
|
+
const body = await feedbackRequest(auth, "GET", "/v1/feedback/forms", void 0, deps);
|
|
8547
|
+
if (!isObject2(body)) throw new deps.CliError("The feedback service returned forms in an unexpected shape.");
|
|
8548
|
+
const version = body.version;
|
|
8549
|
+
if (typeof version !== "number" || !Number.isInteger(version) || version < 1) {
|
|
8550
|
+
throw new deps.CliError("The feedback service returned forms without a version.");
|
|
8551
|
+
}
|
|
8552
|
+
const rawForms = body.forms;
|
|
8553
|
+
if (!isObject2(rawForms)) throw new deps.CliError("The feedback service returned forms without fields.");
|
|
8554
|
+
const forms = {};
|
|
8555
|
+
for (const kind of FEEDBACK_KINDS) {
|
|
8556
|
+
const raw = rawForms[kind];
|
|
8557
|
+
if (!isObject2(raw) || typeof raw.name !== "string") {
|
|
8558
|
+
throw new deps.CliError(`The feedback service returned a broken "${kind}" form.`);
|
|
8559
|
+
}
|
|
8560
|
+
const fields = parseFormFields(raw.fields);
|
|
8561
|
+
if (fields === null) {
|
|
8562
|
+
throw new deps.CliError(`The feedback service returned the "${kind}" form without fields.`);
|
|
8563
|
+
}
|
|
8564
|
+
forms[kind] = { name: raw.name, fields };
|
|
8565
|
+
}
|
|
8566
|
+
return { version, forms };
|
|
8567
|
+
}
|
|
8568
|
+
function parseFeedbackOptions(args, values, booleans, CliError2) {
|
|
8569
|
+
const parsed = { values: /* @__PURE__ */ new Map(), booleans: /* @__PURE__ */ new Set(), positionals: [] };
|
|
8570
|
+
for (let index = 0; index < args.length; index += 1) {
|
|
8571
|
+
const argument = args[index];
|
|
8572
|
+
if (!argument.startsWith("--")) {
|
|
8573
|
+
parsed.positionals.push(argument);
|
|
8574
|
+
continue;
|
|
8575
|
+
}
|
|
8576
|
+
const equals = argument.indexOf("=");
|
|
8577
|
+
const name = equals === -1 ? argument : argument.slice(0, equals);
|
|
8578
|
+
const inline = equals === -1 ? void 0 : argument.slice(equals + 1);
|
|
8579
|
+
if (booleans.includes(name)) {
|
|
8580
|
+
if (inline !== void 0) throw new CliError2(`The option ${name} takes no value.`);
|
|
8581
|
+
parsed.booleans.add(name);
|
|
8582
|
+
continue;
|
|
8583
|
+
}
|
|
8584
|
+
if (!values.includes(name)) throw new CliError2(`Unknown option: ${name}.`);
|
|
8585
|
+
const value = inline ?? args[index + 1];
|
|
8586
|
+
if (value === void 0) throw new CliError2(`The option ${name} needs a value.`);
|
|
8587
|
+
if (inline === void 0) index += 1;
|
|
8588
|
+
const list = parsed.values.get(name) ?? [];
|
|
8589
|
+
list.push(value);
|
|
8590
|
+
parsed.values.set(name, list);
|
|
8591
|
+
}
|
|
8592
|
+
return parsed;
|
|
8593
|
+
}
|
|
8594
|
+
function lastValue(options, name) {
|
|
8595
|
+
return options.values.get(name)?.at(-1);
|
|
8596
|
+
}
|
|
8597
|
+
var NOTE_JSON_NEEDS_YES = "--json needs --yes: without a terminal, the report cannot be confirmed.";
|
|
8598
|
+
function parseFieldFlags(values, deps) {
|
|
8599
|
+
const fields = {};
|
|
8600
|
+
for (const raw of values) {
|
|
8601
|
+
const equals = raw.indexOf("=");
|
|
8602
|
+
if (equals <= 0) throw new deps.CliError(`--field expects id=value (got "${printable(raw)}").`);
|
|
8603
|
+
fields[raw.slice(0, equals)] = raw.slice(equals + 1);
|
|
8604
|
+
}
|
|
8605
|
+
return fields;
|
|
8606
|
+
}
|
|
8607
|
+
function readSmallInputFile(path, label2, deps) {
|
|
8608
|
+
let fd;
|
|
8609
|
+
try {
|
|
8610
|
+
fd = openSync(path, constants.O_RDONLY | constants.O_NONBLOCK);
|
|
8611
|
+
} catch {
|
|
8612
|
+
throw new deps.CliError(`Could not read the ${label2} ${printable(path)}.`);
|
|
8613
|
+
}
|
|
8614
|
+
try {
|
|
8615
|
+
if (!fstatSync(fd).isFile()) {
|
|
8616
|
+
throw new deps.CliError(`The ${label2} is not a regular file.`);
|
|
8617
|
+
}
|
|
8618
|
+
const buffer = Buffer.alloc(FEEDBACK_MAX_INPUT_FILE_BYTES + 1);
|
|
8619
|
+
let total = 0;
|
|
8620
|
+
for (; ; ) {
|
|
8621
|
+
const read = readSync(fd, buffer, total, buffer.length - total, null);
|
|
8622
|
+
if (read === 0) break;
|
|
8623
|
+
total += read;
|
|
8624
|
+
if (total > FEEDBACK_MAX_INPUT_FILE_BYTES) {
|
|
8625
|
+
throw new deps.CliError(`The ${label2} is larger than 1 MiB.`);
|
|
8626
|
+
}
|
|
8627
|
+
}
|
|
8628
|
+
return buffer.subarray(0, total).toString("utf8");
|
|
8629
|
+
} catch (error) {
|
|
8630
|
+
if (error instanceof deps.CliError) throw error;
|
|
8631
|
+
throw new deps.CliError(`Could not read the ${label2} ${printable(path)}.`);
|
|
8632
|
+
} finally {
|
|
8633
|
+
closeSync(fd);
|
|
8634
|
+
}
|
|
8635
|
+
}
|
|
8636
|
+
function readFieldsFile(path, deps) {
|
|
8637
|
+
const text = readSmallInputFile(path, "--fields file", deps);
|
|
8638
|
+
let parsed;
|
|
8639
|
+
try {
|
|
8640
|
+
parsed = JSON.parse(text);
|
|
8641
|
+
} catch {
|
|
8642
|
+
try {
|
|
8643
|
+
parsed = (0, import_yaml2.parse)(text);
|
|
8644
|
+
} catch {
|
|
8645
|
+
throw new deps.CliError("The --fields file is not valid JSON or YAML.");
|
|
8646
|
+
}
|
|
8647
|
+
}
|
|
8648
|
+
if (!isObject2(parsed)) throw new deps.CliError("The --fields file must be an object of field ids.");
|
|
8649
|
+
const fields = {};
|
|
8650
|
+
for (const [id, value] of Object.entries(parsed)) {
|
|
8651
|
+
if (typeof value !== "string" && typeof value !== "boolean") {
|
|
8652
|
+
throw new deps.CliError(`The --fields file has a non-text value for ${printable(id)}.`);
|
|
8653
|
+
}
|
|
8654
|
+
fields[id] = value;
|
|
8655
|
+
}
|
|
8656
|
+
return fields;
|
|
8657
|
+
}
|
|
8658
|
+
function isChecked(value) {
|
|
8659
|
+
return typeof value === "boolean" ? value : /^(true|yes|y|1)$/i.test(value.trim());
|
|
8660
|
+
}
|
|
8661
|
+
function validateFields(form, provided, deps) {
|
|
8662
|
+
const known = new Set(form.fields.map((field) => field.id));
|
|
8663
|
+
for (const id of Object.keys(provided)) {
|
|
8664
|
+
if (!known.has(id)) throw new deps.CliError(`Unknown field: ${printable(id)}.`);
|
|
8665
|
+
}
|
|
8666
|
+
if (Object.keys(provided).length > FEEDBACK_MAX_FIELDS) {
|
|
8667
|
+
throw new deps.CliError(`At most ${FEEDBACK_MAX_FIELDS} fields can be sent.`);
|
|
8668
|
+
}
|
|
8669
|
+
const fields = {};
|
|
8670
|
+
for (const field of form.fields) {
|
|
8671
|
+
const raw = provided[field.id];
|
|
8672
|
+
if (raw === void 0) {
|
|
8673
|
+
if (field.required) throw new deps.CliError(`Missing required field: ${field.id}.`);
|
|
8674
|
+
if (field.type === "checkboxes") throw new deps.CliError(`The field ${field.id} must be checked.`);
|
|
8675
|
+
continue;
|
|
8676
|
+
}
|
|
8677
|
+
if (field.type === "checkboxes") {
|
|
8678
|
+
if (!isChecked(raw)) {
|
|
8679
|
+
throw new deps.CliError(
|
|
8680
|
+
field.required ? `Missing required field: ${field.id}.` : `The field ${field.id} must be checked.`
|
|
8681
|
+
);
|
|
8682
|
+
}
|
|
8683
|
+
fields[field.id] = true;
|
|
8684
|
+
continue;
|
|
8685
|
+
}
|
|
8686
|
+
if (typeof raw !== "string") throw new deps.CliError(`The field ${field.id} must be text.`);
|
|
8687
|
+
if (field.required && raw.trim() === "") throw new deps.CliError(`Missing required field: ${field.id}.`);
|
|
8688
|
+
if (field.type === "dropdown" && field.options !== void 0 && !field.options.includes(raw)) {
|
|
8689
|
+
throw new deps.CliError(
|
|
8690
|
+
`Invalid value for ${printable(field.id)}: "${printable(raw)}". Allowed: ${field.options.join(", ")}.`
|
|
8691
|
+
);
|
|
8692
|
+
}
|
|
8693
|
+
const maxLength = field.maxLength ?? FEEDBACK_MAX_TEXT;
|
|
8694
|
+
if (raw.length > maxLength) {
|
|
8695
|
+
throw new deps.CliError(`The value of ${field.id} must be at most ${maxLength} characters.`);
|
|
8696
|
+
}
|
|
8697
|
+
fields[field.id] = raw;
|
|
8698
|
+
}
|
|
8699
|
+
return fields;
|
|
8700
|
+
}
|
|
8701
|
+
async function promptLine(question) {
|
|
8702
|
+
const readline = createInterface({ input: process.stdin, output: process.stdout });
|
|
8703
|
+
try {
|
|
8704
|
+
return /^y(es)?$/i.test((await readline.question(question)).trim());
|
|
8705
|
+
} finally {
|
|
8706
|
+
readline.close();
|
|
8707
|
+
}
|
|
8708
|
+
}
|
|
8709
|
+
function printCreatePreview(kind, title, form, fields, deps) {
|
|
8710
|
+
deps.writeStdout(`${kind}: ${printable(title)}`);
|
|
8711
|
+
for (const field of form.fields) {
|
|
8712
|
+
const value = fields[field.id];
|
|
8713
|
+
if (value === void 0) continue;
|
|
8714
|
+
deps.writeStdout(
|
|
8715
|
+
value === true ? ` [x] ${field.label}` : ` ${field.label}: ${printable(value)}`
|
|
8716
|
+
);
|
|
8717
|
+
}
|
|
8718
|
+
}
|
|
8719
|
+
function printFeedbackError(error, deps) {
|
|
8720
|
+
for (const line of describeFeedbackFailure(error)) deps.writeStderr(line);
|
|
8721
|
+
if (error.code === "invalid_fields" && error.formsVersion !== null) {
|
|
8722
|
+
deps.writeStderr(
|
|
8723
|
+
`The forms changed (version ${error.formsVersion}); run the command again with the new form.`
|
|
8724
|
+
);
|
|
8725
|
+
}
|
|
8726
|
+
}
|
|
8727
|
+
function printCreateResult(body, options, deps) {
|
|
8728
|
+
if (options.booleans.has("--json")) {
|
|
8729
|
+
deps.writeStdout(JSON.stringify(body, null, 2));
|
|
8730
|
+
return 0;
|
|
8731
|
+
}
|
|
8732
|
+
if (isObject2(body) && body.dryRun === true && isObject2(body.wouldCreate)) {
|
|
8733
|
+
deps.writeStdout("Dry run: the issue would be created with:");
|
|
8734
|
+
deps.writeStdout(` Title: ${printable(String(body.wouldCreate.title ?? ""))}`);
|
|
8735
|
+
if (Array.isArray(body.wouldCreate.labels)) {
|
|
8736
|
+
deps.writeStdout(` Labels: ${printable(body.wouldCreate.labels.join(", "))}`);
|
|
8737
|
+
}
|
|
8738
|
+
deps.writeStdout(` Body:
|
|
8739
|
+
${printable(String(body.wouldCreate.body ?? ""))}`);
|
|
8740
|
+
return 0;
|
|
8741
|
+
}
|
|
8742
|
+
if (!isObject2(body)) throw new deps.CliError("The feedback service returned an unexpected answer.");
|
|
8743
|
+
const issue = typeof body.issue === "number" ? body.issue : "?";
|
|
8744
|
+
const url = typeof body.url === "string" ? printable(body.url) : "";
|
|
8745
|
+
deps.writeStdout(`Opened issue #${issue}${url ? `: ${url}` : ""}`);
|
|
8746
|
+
return 0;
|
|
8747
|
+
}
|
|
8748
|
+
async function handleDuplicates(error, options, resend, deps) {
|
|
8749
|
+
if (options.booleans.has("--json")) {
|
|
8750
|
+
const body = { error: "possible_duplicates", requestId: error.requestId, candidates: error.candidates };
|
|
8751
|
+
deps.writeStdout(JSON.stringify(body, null, 2));
|
|
8752
|
+
return 1;
|
|
8753
|
+
}
|
|
8754
|
+
if (error.candidates.length === 0) deps.writeStdout("Possible duplicates were reported, but none were listed.");
|
|
8755
|
+
for (const candidate of error.candidates) {
|
|
8756
|
+
deps.writeStdout(
|
|
8757
|
+
`#${candidate.issue} ${printable(candidate.title)} (${printable(candidate.state)}) ${printable(candidate.url)}`
|
|
8758
|
+
);
|
|
8759
|
+
}
|
|
8760
|
+
if (options.booleans.has("--confirm-duplicate")) return resend();
|
|
8761
|
+
if (process.stdin.isTTY === true) {
|
|
8762
|
+
if (await promptLine("Open a new issue anyway? [y/N] ")) return resend();
|
|
8763
|
+
deps.writeStdout("Nothing was sent. Vote for an existing issue with `nouter-platform feedback vote <n>`.");
|
|
8764
|
+
return 0;
|
|
8765
|
+
}
|
|
8766
|
+
deps.writeStderr(
|
|
8767
|
+
"Possible duplicates were found. Re-run with --confirm-duplicate to open a new issue anyway."
|
|
8768
|
+
);
|
|
8769
|
+
return 1;
|
|
8770
|
+
}
|
|
8771
|
+
async function feedbackCreate(kind, argv, deps) {
|
|
8772
|
+
const options = parseFeedbackOptions(argv, FEEDBACK_CREATE_VALUES, FEEDBACK_CREATE_BOOLEANS, deps.CliError);
|
|
8773
|
+
if (options.positionals.length > 0) {
|
|
8774
|
+
throw new deps.CliError(`Usage: nouter-platform feedback ${kind} --title <title> [--field id=value]...`);
|
|
8775
|
+
}
|
|
8776
|
+
const title = (lastValue(options, "--title") ?? "").trim();
|
|
8777
|
+
if (title.length === 0) throw new deps.CliError("The option --title is required.");
|
|
8778
|
+
if (title.length > FEEDBACK_MAX_TITLE) {
|
|
8779
|
+
throw new deps.CliError(`The title must be at most ${FEEDBACK_MAX_TITLE} characters.`);
|
|
8780
|
+
}
|
|
8781
|
+
if (options.booleans.has("--json") && !options.booleans.has("--yes")) {
|
|
8782
|
+
throw new deps.CliError(NOTE_JSON_NEEDS_YES);
|
|
8783
|
+
}
|
|
8784
|
+
const fileFields = options.values.has("--fields") ? readFieldsFile(lastValue(options, "--fields"), deps) : {};
|
|
8785
|
+
const provided = {
|
|
8786
|
+
...fileFields,
|
|
8787
|
+
...parseFieldFlags(options.values.get("--field") ?? [], deps)
|
|
8788
|
+
};
|
|
8789
|
+
const auth = await deps.resolveAuth();
|
|
8790
|
+
let forms;
|
|
8791
|
+
try {
|
|
8792
|
+
forms = await loadForms(auth, deps);
|
|
8793
|
+
} catch (error) {
|
|
8794
|
+
if (!(error instanceof FeedbackApiError)) throw error;
|
|
8795
|
+
printFeedbackError(error, deps);
|
|
8796
|
+
return 1;
|
|
8797
|
+
}
|
|
8798
|
+
const form = forms.forms[kind];
|
|
8799
|
+
const fields = validateFields(form, provided, deps);
|
|
8800
|
+
if (!options.booleans.has("--yes")) {
|
|
8801
|
+
if (process.stdin.isTTY !== true) {
|
|
8802
|
+
deps.writeStdout("Nothing was sent: run the command in a terminal or pass --yes.");
|
|
8803
|
+
return 0;
|
|
8804
|
+
}
|
|
8805
|
+
printCreatePreview(kind, title, form, fields, deps);
|
|
8806
|
+
if (!await promptLine("Send this report? [y/N] ")) {
|
|
8807
|
+
deps.writeStdout("Nothing was sent.");
|
|
8808
|
+
return 0;
|
|
8809
|
+
}
|
|
8810
|
+
}
|
|
8811
|
+
const send = async (confirmDuplicateCheck) => {
|
|
8812
|
+
const body = { kind, title, fields, formsVersion: forms.version, confirmDuplicateCheck };
|
|
8813
|
+
try {
|
|
8814
|
+
const result = await feedbackRequest(auth, "POST", "/v1/feedback", body, deps, {
|
|
8815
|
+
"Idempotency-Key": randomUUID()
|
|
8816
|
+
});
|
|
8817
|
+
return printCreateResult(result, options, deps);
|
|
8818
|
+
} catch (error) {
|
|
8819
|
+
if (!(error instanceof FeedbackApiError)) throw error;
|
|
8820
|
+
if (error.code === "possible_duplicates" && !confirmDuplicateCheck) {
|
|
8821
|
+
return handleDuplicates(error, options, () => send(true), deps);
|
|
8822
|
+
}
|
|
8823
|
+
printFeedbackError(error, deps);
|
|
8824
|
+
return 1;
|
|
8825
|
+
}
|
|
8826
|
+
};
|
|
8827
|
+
return send(false);
|
|
8828
|
+
}
|
|
8829
|
+
function parseIssueArgument(raw, deps) {
|
|
8830
|
+
if (raw === void 0 || !/^\d{1,10}$/.test(raw)) {
|
|
8831
|
+
throw new deps.CliError("The issue number must be a positive integer.");
|
|
8832
|
+
}
|
|
8833
|
+
const issue = Number(raw);
|
|
8834
|
+
if (!Number.isInteger(issue) || issue < 1) throw new deps.CliError("The issue number must be a positive integer.");
|
|
8835
|
+
return issue;
|
|
8836
|
+
}
|
|
8837
|
+
function stringArray(value) {
|
|
8838
|
+
return Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
|
|
8839
|
+
}
|
|
8840
|
+
function parseThread(body, deps) {
|
|
8841
|
+
if (!isObject2(body) || typeof body.issue !== "number" || typeof body.title !== "string" || typeof body.body !== "string") {
|
|
8842
|
+
throw new deps.CliError("The feedback service returned an unexpected thread.");
|
|
8843
|
+
}
|
|
8844
|
+
const comments = Array.isArray(body.comments) ? body.comments.filter(isObject2).map((raw) => ({
|
|
8845
|
+
author: typeof raw.author === "string" ? raw.author : "",
|
|
8846
|
+
role: typeof raw.role === "string" ? raw.role : "community",
|
|
8847
|
+
body: typeof raw.body === "string" ? raw.body : "",
|
|
8848
|
+
createdAt: typeof raw.createdAt === "string" ? raw.createdAt : "",
|
|
8849
|
+
url: typeof raw.url === "string" ? raw.url : ""
|
|
8850
|
+
})) : [];
|
|
8851
|
+
return {
|
|
8852
|
+
issue: body.issue,
|
|
8853
|
+
title: body.title,
|
|
8854
|
+
url: typeof body.url === "string" ? body.url : "",
|
|
8855
|
+
state: typeof body.state === "string" ? body.state : "",
|
|
8856
|
+
labels: stringArray(body.labels),
|
|
8857
|
+
toolVotes: typeof body.toolVotes === "number" ? body.toolVotes : 0,
|
|
8858
|
+
body: body.body,
|
|
8859
|
+
comments,
|
|
8860
|
+
lastCommentAt: typeof body.lastCommentAt === "string" ? body.lastCommentAt : null
|
|
8861
|
+
};
|
|
8862
|
+
}
|
|
8863
|
+
function parseMine(body, deps) {
|
|
8864
|
+
if (!isObject2(body) || !Array.isArray(body.items)) {
|
|
8865
|
+
throw new deps.CliError("The feedback service returned an unexpected list.");
|
|
8866
|
+
}
|
|
8867
|
+
const items = body.items.filter(isObject2).map((raw) => ({
|
|
8868
|
+
issue: typeof raw.issue === "number" ? raw.issue : 0,
|
|
8869
|
+
title: typeof raw.title === "string" ? raw.title : "",
|
|
8870
|
+
url: typeof raw.url === "string" ? raw.url : "",
|
|
8871
|
+
state: typeof raw.state === "string" ? raw.state : "",
|
|
8872
|
+
labels: stringArray(raw.labels),
|
|
8873
|
+
comments: typeof raw.comments === "number" ? raw.comments : 0,
|
|
8874
|
+
lastCommentAt: typeof raw.lastCommentAt === "string" ? raw.lastCommentAt : null,
|
|
8875
|
+
mine: typeof raw.mine === "string" ? raw.mine : ""
|
|
8876
|
+
}));
|
|
8877
|
+
return { items, nextCursor: typeof body.nextCursor === "string" ? body.nextCursor : null };
|
|
8878
|
+
}
|
|
8879
|
+
function formatThread(thread) {
|
|
8880
|
+
const lines = [
|
|
8881
|
+
`#${thread.issue} ${printable(thread.title)} (${printable(thread.state)})`,
|
|
8882
|
+
printable(thread.url),
|
|
8883
|
+
`Labels: ${thread.labels.length > 0 ? printable(thread.labels.join(", ")) : "(none)"}`,
|
|
8884
|
+
`Tool votes: ${thread.toolVotes}`,
|
|
8885
|
+
"",
|
|
8886
|
+
printable(thread.body)
|
|
8887
|
+
];
|
|
8888
|
+
if (thread.comments.length > 0) {
|
|
8889
|
+
lines.push("", "Comments:");
|
|
8890
|
+
for (const comment of thread.comments) {
|
|
8891
|
+
lines.push(`[${printable(comment.role)}] ${printable(comment.author)}: ${printable(comment.body)}`);
|
|
8892
|
+
}
|
|
8893
|
+
}
|
|
8894
|
+
return lines;
|
|
8895
|
+
}
|
|
8896
|
+
function formatMine(mine) {
|
|
8897
|
+
if (mine.items.length === 0) return ["No feedback issues."];
|
|
8898
|
+
const lines = [];
|
|
8899
|
+
for (const item of mine.items) {
|
|
8900
|
+
lines.push(`#${item.issue} ${printable(item.title)} (${printable(item.state)}, ${printable(item.mine)})`);
|
|
8901
|
+
lines.push(` ${printable(item.url)}`);
|
|
8902
|
+
const lastComment = item.lastCommentAt === null ? "none" : printable(item.lastCommentAt);
|
|
8903
|
+
lines.push(` comments: ${item.comments}, last comment: ${lastComment}`);
|
|
8904
|
+
}
|
|
8905
|
+
return lines;
|
|
8906
|
+
}
|
|
8907
|
+
async function feedbackShow(argv, deps) {
|
|
8908
|
+
const options = parseFeedbackOptions(argv, FEEDBACK_SHOW_VALUES, FEEDBACK_SHOW_BOOLEANS, deps.CliError);
|
|
8909
|
+
if (options.positionals.length !== 1) throw new deps.CliError("Usage: nouter-platform feedback show <n>");
|
|
8910
|
+
const issue = parseIssueArgument(options.positionals[0], deps);
|
|
8911
|
+
const auth = await deps.resolveAuth();
|
|
8912
|
+
try {
|
|
8913
|
+
const body = await feedbackRequest(auth, "GET", `/v1/feedback/issues/${issue}`, void 0, deps);
|
|
8914
|
+
if (options.booleans.has("--json")) {
|
|
8915
|
+
deps.writeStdout(JSON.stringify(body, null, 2));
|
|
8916
|
+
return 0;
|
|
8917
|
+
}
|
|
8918
|
+
for (const line of formatThread(parseThread(body, deps))) deps.writeStdout(line);
|
|
8919
|
+
return 0;
|
|
8920
|
+
} catch (error) {
|
|
8921
|
+
if (error instanceof FeedbackApiError) {
|
|
8922
|
+
printFeedbackError(error, deps);
|
|
8923
|
+
return 1;
|
|
8924
|
+
}
|
|
8925
|
+
throw error;
|
|
8926
|
+
}
|
|
8927
|
+
}
|
|
8928
|
+
async function feedbackList(argv, deps) {
|
|
8929
|
+
const options = parseFeedbackOptions(argv, FEEDBACK_LIST_VALUES, FEEDBACK_LIST_BOOLEANS, deps.CliError);
|
|
8930
|
+
if (options.positionals.length > 0) {
|
|
8931
|
+
throw new deps.CliError("Usage: nouter-platform feedback list [--cursor <offset>] [--json]");
|
|
8932
|
+
}
|
|
8933
|
+
const cursor = lastValue(options, "--cursor");
|
|
8934
|
+
if (cursor !== void 0 && !/^\d{1,10}$/.test(cursor)) {
|
|
8935
|
+
throw new deps.CliError("The cursor must be a number of up to 10 digits.");
|
|
8936
|
+
}
|
|
8937
|
+
const auth = await deps.resolveAuth();
|
|
8938
|
+
const query = cursor === void 0 ? "" : `?${new URLSearchParams({ cursor }).toString()}`;
|
|
8939
|
+
try {
|
|
8940
|
+
const body = await feedbackRequest(auth, "GET", `/v1/feedback/mine${query}`, void 0, deps);
|
|
8941
|
+
if (options.booleans.has("--json")) deps.writeStdout(JSON.stringify(body, null, 2));
|
|
8942
|
+
else for (const line of formatMine(parseMine(body, deps))) deps.writeStdout(line);
|
|
8943
|
+
const nextCursor = isObject2(body) && typeof body.nextCursor === "string" ? body.nextCursor : null;
|
|
8944
|
+
if (nextCursor !== null) {
|
|
8945
|
+
deps.writeStderr(`There are more issues: run with --cursor ${printable(nextCursor)}.`);
|
|
8946
|
+
}
|
|
8947
|
+
return 0;
|
|
8948
|
+
} catch (error) {
|
|
8949
|
+
if (error instanceof FeedbackApiError) {
|
|
8950
|
+
printFeedbackError(error, deps);
|
|
8951
|
+
return 1;
|
|
8952
|
+
}
|
|
8953
|
+
throw error;
|
|
8954
|
+
}
|
|
8955
|
+
}
|
|
8956
|
+
function parseVoteResult(body, deps) {
|
|
8957
|
+
if (!isObject2(body) || typeof body.issue !== "number") {
|
|
8958
|
+
throw new deps.CliError("The feedback service returned an unexpected vote.");
|
|
8959
|
+
}
|
|
8960
|
+
return {
|
|
8961
|
+
issue: body.issue,
|
|
8962
|
+
voted: body.voted === true,
|
|
8963
|
+
alreadyVoted: body.alreadyVoted === true,
|
|
8964
|
+
toolVotes: typeof body.toolVotes === "number" ? body.toolVotes : 0
|
|
8965
|
+
};
|
|
8966
|
+
}
|
|
8967
|
+
function parseCommentResult(body, deps) {
|
|
8968
|
+
if (!isObject2(body) || typeof body.issue !== "number" || typeof body.commentUrl !== "string") {
|
|
8969
|
+
throw new deps.CliError("The feedback service returned an unexpected comment.");
|
|
8970
|
+
}
|
|
8971
|
+
return {
|
|
8972
|
+
issue: body.issue,
|
|
8973
|
+
commentUrl: body.commentUrl,
|
|
8974
|
+
ref: typeof body.ref === "string" ? body.ref : ""
|
|
8975
|
+
};
|
|
8976
|
+
}
|
|
8977
|
+
function readBodyFile(path, deps) {
|
|
8978
|
+
return readSmallInputFile(path, "--body-file", deps);
|
|
8979
|
+
}
|
|
8980
|
+
async function feedbackVote(argv, deps) {
|
|
8981
|
+
const options = parseFeedbackOptions(argv, FEEDBACK_VOTE_VALUES, FEEDBACK_VOTE_BOOLEANS, deps.CliError);
|
|
8982
|
+
if (options.positionals.length !== 1) throw new deps.CliError("Usage: nouter-platform feedback vote <n>");
|
|
8983
|
+
const issue = parseIssueArgument(options.positionals[0], deps);
|
|
8984
|
+
const auth = await deps.resolveAuth();
|
|
8985
|
+
try {
|
|
8986
|
+
const body = await feedbackRequest(auth, "POST", "/v1/feedback/votes", { issue }, deps, {
|
|
8987
|
+
"Idempotency-Key": randomUUID()
|
|
8988
|
+
});
|
|
8989
|
+
if (isObject2(body) && body.dryRun === true) {
|
|
8990
|
+
deps.writeStdout("Dry run: the vote was not recorded.");
|
|
8991
|
+
return 0;
|
|
8992
|
+
}
|
|
8993
|
+
const result = parseVoteResult(body, deps);
|
|
8994
|
+
const verb = result.alreadyVoted ? "Already voted on" : "Voted on";
|
|
8995
|
+
deps.writeStdout(`${verb} #${result.issue} (${result.toolVotes} votes).`);
|
|
8996
|
+
return 0;
|
|
8997
|
+
} catch (error) {
|
|
8998
|
+
if (error instanceof FeedbackApiError) {
|
|
8999
|
+
printFeedbackError(error, deps);
|
|
9000
|
+
return 1;
|
|
9001
|
+
}
|
|
9002
|
+
throw error;
|
|
9003
|
+
}
|
|
9004
|
+
}
|
|
9005
|
+
async function feedbackComment(argv, deps) {
|
|
9006
|
+
const options = parseFeedbackOptions(argv, FEEDBACK_COMMENT_VALUES, FEEDBACK_COMMENT_BOOLEANS, deps.CliError);
|
|
9007
|
+
if (options.positionals.length !== 1) {
|
|
9008
|
+
throw new deps.CliError("Usage: nouter-platform feedback comment <n> --body <text>|--body-file <path>");
|
|
9009
|
+
}
|
|
9010
|
+
const issue = parseIssueArgument(options.positionals[0], deps);
|
|
9011
|
+
const inline = lastValue(options, "--body");
|
|
9012
|
+
const file = lastValue(options, "--body-file");
|
|
9013
|
+
if (inline !== void 0 && file !== void 0) {
|
|
9014
|
+
throw new deps.CliError("Use either --body or --body-file, not both.");
|
|
9015
|
+
}
|
|
9016
|
+
if (inline === void 0 && file === void 0) {
|
|
9017
|
+
throw new deps.CliError("A comment needs --body <text> or --body-file <path>.");
|
|
9018
|
+
}
|
|
9019
|
+
const text = inline ?? readBodyFile(file, deps);
|
|
9020
|
+
if (text.trim() === "") throw new deps.CliError("The comment cannot be empty.");
|
|
9021
|
+
if (text.length > FEEDBACK_MAX_TEXT) {
|
|
9022
|
+
throw new deps.CliError(`The comment must be at most ${FEEDBACK_MAX_TEXT} characters.`);
|
|
9023
|
+
}
|
|
9024
|
+
const auth = await deps.resolveAuth();
|
|
9025
|
+
try {
|
|
9026
|
+
const body = await feedbackRequest(auth, "POST", "/v1/feedback/comments", { issue, body: text }, deps, {
|
|
9027
|
+
"Idempotency-Key": randomUUID()
|
|
9028
|
+
});
|
|
9029
|
+
if (isObject2(body) && body.dryRun === true) {
|
|
9030
|
+
deps.writeStdout("Dry run: the comment was not posted.");
|
|
9031
|
+
return 0;
|
|
9032
|
+
}
|
|
9033
|
+
const result = parseCommentResult(body, deps);
|
|
9034
|
+
deps.writeStdout(`Comment added: ${printable(result.commentUrl)}`);
|
|
9035
|
+
return 0;
|
|
9036
|
+
} catch (error) {
|
|
9037
|
+
if (error instanceof FeedbackApiError) {
|
|
9038
|
+
printFeedbackError(error, deps);
|
|
9039
|
+
return 1;
|
|
9040
|
+
}
|
|
9041
|
+
throw error;
|
|
9042
|
+
}
|
|
9043
|
+
}
|
|
9044
|
+
async function feedbackCommand(argv, deps) {
|
|
9045
|
+
if (!feedbackEnabled()) {
|
|
9046
|
+
deps.writeStderr(FEEDBACK_DISABLED_MESSAGE);
|
|
9047
|
+
return 1;
|
|
9048
|
+
}
|
|
9049
|
+
const [subcommand, ...rest] = argv;
|
|
9050
|
+
switch (subcommand) {
|
|
9051
|
+
case "bug":
|
|
9052
|
+
case "feature":
|
|
9053
|
+
case "question":
|
|
9054
|
+
return await feedbackCreate(subcommand, rest, deps);
|
|
9055
|
+
case "show":
|
|
9056
|
+
return await feedbackShow(rest, deps);
|
|
9057
|
+
case "list":
|
|
9058
|
+
return await feedbackList(rest, deps);
|
|
9059
|
+
case "vote":
|
|
9060
|
+
return await feedbackVote(rest, deps);
|
|
9061
|
+
case "comment":
|
|
9062
|
+
return await feedbackComment(rest, deps);
|
|
9063
|
+
default:
|
|
9064
|
+
deps.writeStderr("Usage: nouter-platform feedback bug|feature|question|show|vote|comment|list");
|
|
9065
|
+
return 1;
|
|
9066
|
+
}
|
|
9067
|
+
}
|
|
9068
|
+
|
|
9069
|
+
// src/commands.ts
|
|
9070
|
+
var COMMANDS = [
|
|
9071
|
+
{
|
|
9072
|
+
path: "login",
|
|
9073
|
+
summary: "Log in through the browser or a pasted code, or store an API key from stdin",
|
|
9074
|
+
values: [],
|
|
9075
|
+
booleans: ["--api-key", "--browser", "--paste"],
|
|
9076
|
+
positionals: []
|
|
9077
|
+
},
|
|
9078
|
+
{
|
|
9079
|
+
path: "logout",
|
|
9080
|
+
summary: "Revoke the CLI session and remove the stored credential (--all: every session)",
|
|
9081
|
+
values: [],
|
|
9082
|
+
booleans: ["--all"],
|
|
9083
|
+
positionals: []
|
|
9084
|
+
},
|
|
9085
|
+
{
|
|
9086
|
+
path: "whoami",
|
|
9087
|
+
summary: "Show the organization, the role, the scopes and the session",
|
|
9088
|
+
values: [],
|
|
9089
|
+
booleans: ["--json"],
|
|
9090
|
+
positionals: []
|
|
9091
|
+
},
|
|
9092
|
+
{
|
|
9093
|
+
path: "auth status",
|
|
9094
|
+
summary: "Show which credential the CLI would use, without printing it",
|
|
9095
|
+
values: [],
|
|
9096
|
+
booleans: [],
|
|
9097
|
+
positionals: []
|
|
9098
|
+
},
|
|
9099
|
+
{
|
|
9100
|
+
path: "auth sessions list",
|
|
9101
|
+
summary: "List the CLI sessions of the stored session",
|
|
9102
|
+
values: [],
|
|
9103
|
+
booleans: ["--json"],
|
|
9104
|
+
positionals: []
|
|
9105
|
+
},
|
|
9106
|
+
{
|
|
9107
|
+
path: "auth sessions revoke",
|
|
9108
|
+
summary: "Revoke one of the CLI sessions of this user",
|
|
9109
|
+
values: [],
|
|
9110
|
+
booleans: ["--json"],
|
|
9111
|
+
positionals: ["<session-id>"]
|
|
9112
|
+
},
|
|
9113
|
+
{
|
|
9114
|
+
path: "version",
|
|
9115
|
+
summary: "Show the CLI version and the version of the SDK it ships",
|
|
9116
|
+
values: [],
|
|
9117
|
+
booleans: [],
|
|
9118
|
+
positionals: []
|
|
9119
|
+
},
|
|
9120
|
+
{
|
|
9121
|
+
path: "agents list",
|
|
9122
|
+
summary: "List every agent",
|
|
9123
|
+
values: [],
|
|
9124
|
+
booleans: ["--json"],
|
|
9125
|
+
positionals: []
|
|
9126
|
+
},
|
|
9127
|
+
{
|
|
9128
|
+
path: "agents get",
|
|
9129
|
+
summary: "Show one agent by id",
|
|
9130
|
+
values: [],
|
|
9131
|
+
booleans: [],
|
|
9132
|
+
positionals: ["<agent-id>"]
|
|
9133
|
+
},
|
|
9134
|
+
{
|
|
9135
|
+
path: "environments list",
|
|
9136
|
+
summary: "List every environment",
|
|
9137
|
+
values: [],
|
|
9138
|
+
booleans: ["--json"],
|
|
9139
|
+
positionals: []
|
|
9140
|
+
},
|
|
9141
|
+
{
|
|
9142
|
+
path: "environments get",
|
|
9143
|
+
summary: "Show one environment by id",
|
|
9144
|
+
values: [],
|
|
9145
|
+
booleans: [],
|
|
9146
|
+
positionals: ["<environment-id>"]
|
|
9147
|
+
},
|
|
9148
|
+
{
|
|
9149
|
+
path: "sessions list",
|
|
9150
|
+
summary: "List the sessions, with the filters the API accepts",
|
|
9151
|
+
values: ["--agent", "--agent-version", "--user-profile", "--status", "--since", "--until", "--order"],
|
|
9152
|
+
booleans: ["--include-archived", "--json"],
|
|
9153
|
+
positionals: []
|
|
9154
|
+
},
|
|
9155
|
+
{
|
|
9156
|
+
path: "sessions get",
|
|
9157
|
+
summary: "Show one session by id",
|
|
9158
|
+
values: [],
|
|
9159
|
+
booleans: ["--json"],
|
|
9160
|
+
positionals: ["<session-id>"]
|
|
9161
|
+
},
|
|
9162
|
+
{
|
|
9163
|
+
path: "sessions events",
|
|
9164
|
+
summary: "List the events and the traces of a session",
|
|
9165
|
+
values: ["--type", "--since", "--until", "--order"],
|
|
9166
|
+
booleans: ["--json"],
|
|
9167
|
+
positionals: ["<session-id>"]
|
|
9168
|
+
},
|
|
9169
|
+
{
|
|
9170
|
+
path: "usage",
|
|
9171
|
+
summary: "Show the usage and the cost by day, model, agent, person or session",
|
|
9172
|
+
values: ["--days", "--since", "--until", "--group-by", "--user-profile", "--limit", "--page"],
|
|
9173
|
+
booleans: ["--json"],
|
|
9174
|
+
positionals: []
|
|
9175
|
+
},
|
|
9176
|
+
{
|
|
9177
|
+
path: "service-accounts list",
|
|
9178
|
+
summary: "List the service accounts",
|
|
9179
|
+
values: [],
|
|
9180
|
+
booleans: ["--include-archived", "--json"],
|
|
9181
|
+
positionals: []
|
|
9182
|
+
},
|
|
9183
|
+
{
|
|
9184
|
+
path: "service-accounts create",
|
|
9185
|
+
summary: "Create a service account",
|
|
9186
|
+
values: ["--name", "--organization-role"],
|
|
9187
|
+
booleans: ["--json"],
|
|
9188
|
+
positionals: []
|
|
9189
|
+
},
|
|
9190
|
+
{
|
|
9191
|
+
path: "service-accounts archive",
|
|
9192
|
+
summary: "Archive a service account by id",
|
|
9193
|
+
values: [],
|
|
9194
|
+
booleans: [],
|
|
9195
|
+
positionals: ["<service-account-id>"]
|
|
9196
|
+
},
|
|
9197
|
+
{
|
|
9198
|
+
path: "federation issuers list",
|
|
9199
|
+
summary: "List the federation issuers",
|
|
9200
|
+
values: [],
|
|
9201
|
+
booleans: ["--include-archived", "--json"],
|
|
9202
|
+
positionals: []
|
|
9203
|
+
},
|
|
9204
|
+
{
|
|
9205
|
+
path: "federation issuers create",
|
|
9206
|
+
summary: "Create a federation issuer",
|
|
9207
|
+
values: ["--name", "--provider", "--issuer-url", "--jwks-url", "--check-jti", "--max-token-lifetime"],
|
|
9208
|
+
booleans: ["--json"],
|
|
9209
|
+
positionals: []
|
|
9210
|
+
},
|
|
9211
|
+
{
|
|
9212
|
+
path: "federation issuers archive",
|
|
9213
|
+
summary: "Archive a federation issuer by id",
|
|
9214
|
+
values: [],
|
|
9215
|
+
booleans: [],
|
|
9216
|
+
positionals: ["<issuer-id>"]
|
|
9217
|
+
},
|
|
9218
|
+
{
|
|
9219
|
+
path: "federation rules list",
|
|
9220
|
+
summary: "List the federation rules, optionally by issuer",
|
|
9221
|
+
values: ["--issuer"],
|
|
9222
|
+
booleans: ["--include-archived", "--json"],
|
|
9223
|
+
positionals: []
|
|
9224
|
+
},
|
|
9225
|
+
{
|
|
9226
|
+
path: "federation rules create",
|
|
9227
|
+
summary: "Create a federation rule",
|
|
9228
|
+
values: [
|
|
9229
|
+
"--name",
|
|
9230
|
+
"--issuer",
|
|
9231
|
+
"--service-account",
|
|
9232
|
+
"--subject-prefix",
|
|
9233
|
+
"--audience",
|
|
9234
|
+
"--claim",
|
|
9235
|
+
"--workspace",
|
|
9236
|
+
"--scopes",
|
|
9237
|
+
"--token-lifetime"
|
|
9238
|
+
],
|
|
9239
|
+
booleans: ["--all-workspaces", "--json"],
|
|
9240
|
+
positionals: []
|
|
9241
|
+
},
|
|
9242
|
+
{
|
|
9243
|
+
path: "federation rules archive",
|
|
9244
|
+
summary: "Archive a federation rule by id",
|
|
9245
|
+
values: [],
|
|
9246
|
+
booleans: [],
|
|
9247
|
+
positionals: ["<rule-id>"]
|
|
9248
|
+
},
|
|
9249
|
+
{
|
|
9250
|
+
path: "federation token",
|
|
9251
|
+
summary: "Exchange the federated identity for a platform access token",
|
|
9252
|
+
values: [],
|
|
9253
|
+
booleans: ["--json"],
|
|
9254
|
+
positionals: []
|
|
9255
|
+
},
|
|
9256
|
+
{
|
|
9257
|
+
path: "elevate",
|
|
9258
|
+
summary: "Confirm it's you for two hours, through the browser or a pasted code",
|
|
9259
|
+
values: [],
|
|
9260
|
+
booleans: ["--browser", "--paste"],
|
|
9261
|
+
positionals: []
|
|
9262
|
+
},
|
|
9263
|
+
{
|
|
9264
|
+
path: "apply",
|
|
9265
|
+
summary: "Apply agents and environments from files",
|
|
9266
|
+
values: ["--file"],
|
|
9267
|
+
booleans: ["--dry-run", "--rotate-secrets"],
|
|
9268
|
+
positionals: [],
|
|
9269
|
+
shortValues: ["-f"]
|
|
9270
|
+
},
|
|
9271
|
+
...FEEDBACK_COMMANDS
|
|
9272
|
+
];
|
|
9273
|
+
var BY_PATH = new Map(COMMANDS.map((command) => [command.path, command]));
|
|
9274
|
+
function specFor(path) {
|
|
9275
|
+
const spec = BY_PATH.get(path);
|
|
9276
|
+
if (spec === void 0) throw new Error(`Unknown command path: ${path}`);
|
|
9277
|
+
return spec;
|
|
9278
|
+
}
|
|
9279
|
+
|
|
9280
|
+
// src/config-file.ts
|
|
9281
|
+
import { randomBytes } from "node:crypto";
|
|
9282
|
+
import {
|
|
9283
|
+
chmodSync,
|
|
9284
|
+
closeSync as closeSync2,
|
|
9285
|
+
existsSync,
|
|
9286
|
+
fchmodSync,
|
|
9287
|
+
lstatSync,
|
|
9288
|
+
mkdirSync,
|
|
9289
|
+
openSync as openSync2,
|
|
9290
|
+
readFileSync as readFileSync2,
|
|
9291
|
+
renameSync,
|
|
9292
|
+
statSync as statSync2,
|
|
9293
|
+
unlinkSync,
|
|
9294
|
+
writeSync
|
|
9295
|
+
} from "node:fs";
|
|
9296
|
+
import { homedir } from "node:os";
|
|
9297
|
+
import { join as join2 } from "node:path";
|
|
9298
|
+
var CONFIG_DIRECTORY = "nouter-platform";
|
|
9299
|
+
var CONFIG_FILE = "config.json";
|
|
9300
|
+
var CLI_CLIENT_ID = "nouter-platform";
|
|
9301
|
+
var ConfigStorageError = class extends Error {
|
|
9302
|
+
code = "STORAGE_INSECURE";
|
|
9303
|
+
exitCode = 77;
|
|
9304
|
+
constructor(message) {
|
|
9305
|
+
super(message);
|
|
9306
|
+
this.name = "ConfigStorageError";
|
|
9307
|
+
}
|
|
9308
|
+
};
|
|
9309
|
+
function configDirectory() {
|
|
9310
|
+
const xdg = process.env.XDG_CONFIG_HOME;
|
|
9311
|
+
const base = xdg && xdg.length > 0 ? xdg : join2(process.env.HOME ?? homedir(), ".config");
|
|
9312
|
+
return join2(base, CONFIG_DIRECTORY);
|
|
9313
|
+
}
|
|
9314
|
+
function configPath() {
|
|
9315
|
+
return join2(configDirectory(), CONFIG_FILE);
|
|
9316
|
+
}
|
|
9317
|
+
function readConfig(options = {}) {
|
|
9318
|
+
const platform = options.platform ?? process.platform;
|
|
9319
|
+
const path = configPath();
|
|
9320
|
+
if (!existsSync(path)) return null;
|
|
9321
|
+
if (platform !== "win32") {
|
|
9322
|
+
const mode = statSync2(path).mode;
|
|
9323
|
+
if ((mode & 63) !== 0) {
|
|
9324
|
+
const shown = (mode & 511).toString(8).padStart(3, "0");
|
|
9325
|
+
throw new ConfigStorageError(
|
|
9326
|
+
`The config file ${path} is readable by other users (mode ${shown}); run \`chmod 600 ${path}\` or \`nouter-platform logout\`.`
|
|
9327
|
+
);
|
|
9328
|
+
}
|
|
9329
|
+
}
|
|
9330
|
+
try {
|
|
9331
|
+
const parsed = JSON.parse(readFileSync2(path, "utf8"));
|
|
9332
|
+
if (typeof parsed.apiKey !== "string" || parsed.apiKey.length === 0) return null;
|
|
9333
|
+
const loaded = {
|
|
9334
|
+
baseUrl: typeof parsed.baseUrl === "string" && parsed.baseUrl.length > 0 ? parsed.baseUrl : null,
|
|
9335
|
+
apiKey: parsed.apiKey
|
|
9336
|
+
};
|
|
9337
|
+
if (typeof parsed.iss === "string" && parsed.iss.length > 0) loaded.iss = parsed.iss;
|
|
9338
|
+
if (typeof parsed.clientId === "string" && parsed.clientId.length > 0) loaded.clientId = parsed.clientId;
|
|
9339
|
+
if (typeof parsed.sessionId === "string" && parsed.sessionId.length > 0) loaded.sessionId = parsed.sessionId;
|
|
9340
|
+
return loaded;
|
|
9341
|
+
} catch (error) {
|
|
9342
|
+
if (error instanceof ConfigStorageError) throw error;
|
|
9343
|
+
return null;
|
|
9344
|
+
}
|
|
9345
|
+
}
|
|
9346
|
+
function rejectSymlink(path, what) {
|
|
9347
|
+
let stats;
|
|
9348
|
+
try {
|
|
9349
|
+
stats = lstatSync(path);
|
|
9350
|
+
} catch (error) {
|
|
9351
|
+
if (error.code === "ENOENT") return;
|
|
9352
|
+
throw error;
|
|
9353
|
+
}
|
|
9354
|
+
if (stats.isSymbolicLink()) {
|
|
9355
|
+
throw new Error(`${what} is a symbolic link; refusing to follow it.`);
|
|
9356
|
+
}
|
|
9357
|
+
}
|
|
9358
|
+
function writeConfig(config) {
|
|
9359
|
+
const directory = configDirectory();
|
|
9360
|
+
mkdirSync(directory, { recursive: true, mode: 448 });
|
|
9361
|
+
rejectSymlink(directory, "The config directory");
|
|
9362
|
+
try {
|
|
9363
|
+
chmodSync(directory, 448);
|
|
9364
|
+
} catch {
|
|
9365
|
+
throw new Error(`Could not set the config directory ${directory} to 0700.`);
|
|
9366
|
+
}
|
|
9367
|
+
const path = configPath();
|
|
9368
|
+
rejectSymlink(path, "The config file");
|
|
9369
|
+
const temporary = join2(directory, `.config.json.${randomBytes(6).toString("hex")}.tmp`);
|
|
9370
|
+
const fd = openSync2(temporary, "wx", 384);
|
|
9371
|
+
let open = true;
|
|
9372
|
+
try {
|
|
9373
|
+
try {
|
|
9374
|
+
fchmodSync(fd, 384);
|
|
9375
|
+
} catch {
|
|
9376
|
+
throw new Error("Could not set the config file to 0600.");
|
|
9377
|
+
}
|
|
9378
|
+
writeSync(fd, `${JSON.stringify(config, null, 2)}
|
|
9379
|
+
`);
|
|
9380
|
+
closeSync2(fd);
|
|
9381
|
+
open = false;
|
|
9382
|
+
renameSync(temporary, path);
|
|
9383
|
+
} catch (error) {
|
|
9384
|
+
if (open) {
|
|
9385
|
+
try {
|
|
9386
|
+
closeSync2(fd);
|
|
9387
|
+
} catch {
|
|
9388
|
+
}
|
|
9389
|
+
}
|
|
9390
|
+
try {
|
|
9391
|
+
unlinkSync(temporary);
|
|
9392
|
+
} catch {
|
|
9393
|
+
}
|
|
9394
|
+
throw error;
|
|
9395
|
+
}
|
|
9396
|
+
}
|
|
9397
|
+
function clearConfig() {
|
|
9398
|
+
const path = configPath();
|
|
9399
|
+
if (!existsSync(path)) return false;
|
|
9400
|
+
unlinkSync(path);
|
|
9401
|
+
return true;
|
|
9402
|
+
}
|
|
9403
|
+
|
|
9404
|
+
// src/sessions-usage.ts
|
|
9405
|
+
var SESSION_STATUSES = ["rescheduling", "running", "idle", "terminated"];
|
|
9406
|
+
var USAGE_GROUP_BY = ["day", "model", "agent", "agent_version", "user_profile", "session"];
|
|
9407
|
+
function formatCents(amount) {
|
|
9408
|
+
if (amount === null || amount === void 0) return "-";
|
|
9409
|
+
const match = /^(-?)(\d+)$/.exec(amount);
|
|
9410
|
+
if (match === null) return amount;
|
|
9411
|
+
const sign = match[1] === "-" ? "-$" : "$";
|
|
9412
|
+
const digits = match[2].padStart(3, "0");
|
|
9413
|
+
return `${sign}${digits.slice(0, -2)}.${digits.slice(-2)}`;
|
|
9414
|
+
}
|
|
9415
|
+
function formatMicros(cost) {
|
|
9416
|
+
if (cost === null || cost === void 0) return "-";
|
|
9417
|
+
const match = /^(-?)(\d+)$/.exec(cost);
|
|
9418
|
+
if (match === null) return cost;
|
|
9419
|
+
const sign = match[1] === "-" ? "-$" : "$";
|
|
9420
|
+
const digits = match[2].padStart(7, "0");
|
|
9421
|
+
return `${sign}${digits.slice(0, -6)}.${digits.slice(-6)}`;
|
|
9422
|
+
}
|
|
9423
|
+
function formatCount(value) {
|
|
9424
|
+
return String(value).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
|
|
9425
|
+
}
|
|
9426
|
+
function isRealDate(year, month, day) {
|
|
9427
|
+
if (month < 1 || month > 12 || day < 1) return false;
|
|
9428
|
+
const lastDay = new Date(Date.UTC(year, month, 0)).getUTCDate();
|
|
9429
|
+
return day <= lastDay;
|
|
9430
|
+
}
|
|
9431
|
+
function normalizeInstant(value, boundary) {
|
|
9432
|
+
const dateOnly = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value);
|
|
9433
|
+
if (dateOnly !== null) {
|
|
9434
|
+
const [, year, month, day] = dateOnly;
|
|
9435
|
+
if (!isRealDate(Number(year), Number(month), Number(day))) return null;
|
|
9436
|
+
return boundary === "start" ? `${value}T00:00:00Z` : `${value}T23:59:59.999Z`;
|
|
9437
|
+
}
|
|
9438
|
+
const rfc3339 = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/.exec(value);
|
|
9439
|
+
if (rfc3339 !== null) {
|
|
9440
|
+
const [, year, month, day, hour, minute, second] = rfc3339;
|
|
9441
|
+
if (!isRealDate(Number(year), Number(month), Number(day))) return null;
|
|
9442
|
+
if (Number(hour) > 23 || Number(minute) > 59 || Number(second) > 59) return null;
|
|
9443
|
+
return value;
|
|
9444
|
+
}
|
|
9445
|
+
return null;
|
|
9446
|
+
}
|
|
9447
|
+
function splitList(values) {
|
|
9448
|
+
const result = [];
|
|
9449
|
+
for (const value of values ?? []) {
|
|
9450
|
+
for (const part of value.split(",")) {
|
|
9451
|
+
const trimmed = part.trim();
|
|
9452
|
+
if (trimmed.length > 0 && !result.includes(trimmed)) result.push(trimmed);
|
|
9453
|
+
}
|
|
9454
|
+
}
|
|
9455
|
+
return result;
|
|
9456
|
+
}
|
|
9457
|
+
var SUMMARY_LIMIT = 80;
|
|
9458
|
+
function collapse(text) {
|
|
9459
|
+
return text.replace(/\s+/g, " ").trim();
|
|
9460
|
+
}
|
|
9461
|
+
function eventSummary(event) {
|
|
9462
|
+
if (event.type === "user.message" || event.type === "agent.message") {
|
|
9463
|
+
const text = collapse(
|
|
9464
|
+
(event.content ?? []).filter((block) => block.type === "text" && typeof block.text === "string").map((block) => block.text).join(" ")
|
|
9465
|
+
);
|
|
9466
|
+
if (text.length === 0) return "-";
|
|
9467
|
+
return text.length > SUMMARY_LIMIT ? `${text.slice(0, SUMMARY_LIMIT)}\u2026` : text;
|
|
9468
|
+
}
|
|
9469
|
+
if (event.type === "span.model_request_end") {
|
|
9470
|
+
return `${event.model_usage?.input_tokens ?? 0} in / ${event.model_usage?.output_tokens ?? 0} out`;
|
|
9471
|
+
}
|
|
9472
|
+
if (event.type === "span.outcome_evaluation_end") {
|
|
9473
|
+
return typeof event.result === "string" ? event.result : "-";
|
|
9474
|
+
}
|
|
9475
|
+
return "-";
|
|
9476
|
+
}
|
|
9477
|
+
function agentLabel(session) {
|
|
9478
|
+
if (session.agent?.id === void 0 || session.agent.version === void 0) return "-";
|
|
9479
|
+
return `${session.agent.id}@${session.agent.version}`;
|
|
9480
|
+
}
|
|
9481
|
+
function sessionRow(session) {
|
|
9482
|
+
return [
|
|
9483
|
+
session.id,
|
|
9484
|
+
session.status,
|
|
9485
|
+
agentLabel(session),
|
|
9486
|
+
session.user_profile_id ?? "-",
|
|
9487
|
+
session.created_at,
|
|
9488
|
+
formatCents(session.usage?.list_cost?.amount)
|
|
9489
|
+
];
|
|
9490
|
+
}
|
|
9491
|
+
function lineOf(label2, value) {
|
|
9492
|
+
return `${`${label2}:`.padEnd(17)} ${value}`;
|
|
9493
|
+
}
|
|
9494
|
+
function createdByLabel(createdBy) {
|
|
9495
|
+
if (!createdBy) return "-";
|
|
9496
|
+
const type = createdBy.type ?? "user";
|
|
9497
|
+
const id = createdBy.id ?? "";
|
|
9498
|
+
const name = createdBy.name ? ` (${createdBy.name})` : "";
|
|
9499
|
+
return `${type} ${id}${name}`.trim();
|
|
9500
|
+
}
|
|
9501
|
+
function statsLabel(stats) {
|
|
9502
|
+
if (stats?.active_seconds === void 0 || stats.duration_seconds === void 0) return "-";
|
|
9503
|
+
return `${stats.active_seconds.toFixed(1)}s active / ${stats.duration_seconds.toFixed(1)}s total`;
|
|
9504
|
+
}
|
|
9505
|
+
function tokensLabel(usage) {
|
|
9506
|
+
if (usage === void 0) return "-";
|
|
9507
|
+
const cacheWrite = (usage.cache_creation?.ephemeral_1h_input_tokens ?? 0) + (usage.cache_creation?.ephemeral_5m_input_tokens ?? 0);
|
|
9508
|
+
return [
|
|
9509
|
+
`${formatCount(usage.input_tokens ?? 0)} in`,
|
|
9510
|
+
`${formatCount(usage.output_tokens ?? 0)} out`,
|
|
9511
|
+
`${formatCount(usage.cache_read_input_tokens ?? 0)} cache read`,
|
|
9512
|
+
`${formatCount(cacheWrite)} cache write`
|
|
9513
|
+
].join(" / ");
|
|
9514
|
+
}
|
|
9515
|
+
function costLabel(usage) {
|
|
9516
|
+
const listCost = usage?.list_cost;
|
|
9517
|
+
if (listCost === null || listCost === void 0 || listCost.amount === void 0 || listCost.amount === null) {
|
|
9518
|
+
return "-";
|
|
9519
|
+
}
|
|
9520
|
+
return `${formatCents(listCost.amount)} ${listCost.currency ?? "USD"}`;
|
|
9521
|
+
}
|
|
9522
|
+
function sessionDetail(session) {
|
|
9523
|
+
return [
|
|
9524
|
+
lineOf("ID", session.id),
|
|
9525
|
+
lineOf("Title", session.title ?? "-"),
|
|
9526
|
+
lineOf("Status", session.status),
|
|
9527
|
+
lineOf("Agent", agentLabel(session)),
|
|
9528
|
+
lineOf("Environment", session.environment_id ?? "-"),
|
|
9529
|
+
lineOf("User profile", session.user_profile_id ?? "-"),
|
|
9530
|
+
lineOf("Created by", createdByLabel(session.created_by)),
|
|
9531
|
+
lineOf("Created", session.created_at),
|
|
9532
|
+
lineOf("Updated", session.updated_at ?? "-"),
|
|
9533
|
+
lineOf("Archived", session.archived_at ?? "-"),
|
|
9534
|
+
lineOf("Deployment", session.deployment_id ?? "-"),
|
|
9535
|
+
lineOf("Sandbox", session._oma?.sandbox_mode ?? "-"),
|
|
9536
|
+
lineOf("Conversation key", session.conversation_key ?? "-"),
|
|
9537
|
+
lineOf("Stats", statsLabel(session.stats)),
|
|
9538
|
+
lineOf("Tokens", tokensLabel(session.usage)),
|
|
9539
|
+
lineOf("Cost", costLabel(session.usage))
|
|
9540
|
+
];
|
|
9541
|
+
}
|
|
9542
|
+
function eventRow(event) {
|
|
9543
|
+
return [event.processed_at ?? "-", event.type, event.id, eventSummary(event)];
|
|
9544
|
+
}
|
|
9545
|
+
function table(rows) {
|
|
9546
|
+
const widths = rows[0].map((_, column) => Math.max(...rows.map((row) => (row[column] ?? "").length)));
|
|
9547
|
+
return rows.map((row) => row.map((cell, column) => (cell ?? "").padEnd(widths[column])).join(" ").trimEnd()).join("\n");
|
|
9548
|
+
}
|
|
9549
|
+
var DIMENSIONS = {
|
|
9550
|
+
day: { title: "DAY", value: (row) => row.day ?? "-" },
|
|
9551
|
+
model: { title: "MODEL", value: (row) => row.model ?? "-" },
|
|
9552
|
+
agent: { title: "AGENT", value: (row) => row.agent_id ?? "-" },
|
|
9553
|
+
agent_version: {
|
|
9554
|
+
title: "AGENT VERSION",
|
|
9555
|
+
value: (row) => row.agent_version === null || row.agent_version === void 0 ? "(none)" : String(row.agent_version)
|
|
9556
|
+
},
|
|
9557
|
+
user_profile: { title: "USER", value: (row) => row.user_profile_id ?? "-" },
|
|
9558
|
+
session: { title: "SESSION", value: (row) => row.session_id ?? "-" }
|
|
9559
|
+
};
|
|
9560
|
+
function costCell(row) {
|
|
9561
|
+
if (row.cost_micros === null) return "-";
|
|
9562
|
+
return `${formatMicros(row.cost_micros)}${row.unpriced_requests > 0 ? "*" : ""}`;
|
|
9563
|
+
}
|
|
9564
|
+
function usageTable(report) {
|
|
9565
|
+
const dimensions = report.group_by.map((group) => DIMENSIONS[group]).filter((dimension) => dimension !== void 0);
|
|
9566
|
+
const header = [
|
|
9567
|
+
...dimensions.map((dimension) => dimension.title),
|
|
9568
|
+
"REQUESTS",
|
|
9569
|
+
"ERRORS",
|
|
9570
|
+
"INPUT",
|
|
9571
|
+
"OUTPUT",
|
|
9572
|
+
"CACHE READ",
|
|
9573
|
+
"CACHE WRITE",
|
|
9574
|
+
"COST"
|
|
9575
|
+
];
|
|
9576
|
+
const rows = report.rows.map((row) => [
|
|
9577
|
+
...dimensions.map((dimension) => dimension.value(row)),
|
|
9578
|
+
formatCount(row.requests),
|
|
9579
|
+
formatCount(row.error_requests),
|
|
9580
|
+
formatCount(row.input_tokens),
|
|
9581
|
+
formatCount(row.output_tokens),
|
|
9582
|
+
formatCount(row.cache_read_input_tokens),
|
|
9583
|
+
formatCount(row.cache_creation_input_tokens),
|
|
9584
|
+
costCell(row)
|
|
9585
|
+
]);
|
|
9586
|
+
const heading = `Usage ${report.from} to ${report.to} (UTC), grouped by ${report.group_by.join(", ")}.`;
|
|
9587
|
+
return `${heading}
|
|
9588
|
+
|
|
9589
|
+
${table([header, ...rows])}`;
|
|
9590
|
+
}
|
|
9591
|
+
function unpricedTotal(report) {
|
|
9592
|
+
return report.rows.reduce((total, row) => total + row.unpriced_requests, 0);
|
|
9593
|
+
}
|
|
9594
|
+
|
|
9595
|
+
// src/identity-token.ts
|
|
9596
|
+
import { readFileSync as readFileSync3 } from "node:fs";
|
|
9597
|
+
var IdentityTokenError = class extends Error {
|
|
9598
|
+
constructor(message) {
|
|
9599
|
+
super(message);
|
|
9600
|
+
this.name = "IdentityTokenError";
|
|
9601
|
+
}
|
|
9602
|
+
};
|
|
9603
|
+
var NON_EMPTY = (value) => typeof value === "string" && value.length > 0;
|
|
9604
|
+
function identityTokenSourceFromEnv(env = process.env) {
|
|
9605
|
+
const value = env.NOUTER_PLATFORM_IDENTITY_TOKEN;
|
|
9606
|
+
if (NON_EMPTY(value)) return { kind: "value", token: value };
|
|
9607
|
+
const path = env.NOUTER_PLATFORM_IDENTITY_TOKEN_FILE;
|
|
9608
|
+
if (NON_EMPTY(path)) return { kind: "file", path };
|
|
9609
|
+
return null;
|
|
9610
|
+
}
|
|
9611
|
+
var PRINTABLE = /^[\x21-\x7e]+$/u;
|
|
9612
|
+
function clean(token) {
|
|
9613
|
+
const trimmed = token.trim();
|
|
9614
|
+
if (trimmed.length === 0) throw new IdentityTokenError("The identity token is empty.");
|
|
9615
|
+
if (!PRINTABLE.test(trimmed)) {
|
|
9616
|
+
throw new IdentityTokenError("The identity token has characters the CLI cannot use.");
|
|
9617
|
+
}
|
|
9618
|
+
return trimmed;
|
|
9619
|
+
}
|
|
9620
|
+
function createIdentityTokenReader(source, read = (path) => readFileSync3(path, "utf8")) {
|
|
9621
|
+
if (source.kind === "value") {
|
|
9622
|
+
return { read: () => clean(source.token) };
|
|
9623
|
+
}
|
|
9624
|
+
return {
|
|
9625
|
+
read() {
|
|
9626
|
+
let contents;
|
|
9627
|
+
try {
|
|
9628
|
+
contents = read(source.path);
|
|
9629
|
+
} catch {
|
|
9630
|
+
throw new IdentityTokenError(`Could not read the identity token file ${source.path}.`);
|
|
9631
|
+
}
|
|
9632
|
+
return clean(contents);
|
|
9633
|
+
}
|
|
9634
|
+
};
|
|
9635
|
+
}
|
|
9636
|
+
|
|
9637
|
+
// src/federation.ts
|
|
8476
9638
|
var FederationError = class extends Error {
|
|
8477
9639
|
constructor(message) {
|
|
8478
9640
|
super(message);
|
|
@@ -8585,8 +9747,14 @@ function createFederationTokenProvider(options) {
|
|
|
8585
9747
|
// src/login-callback.ts
|
|
8586
9748
|
import { timingSafeEqual } from "node:crypto";
|
|
8587
9749
|
import { createServer } from "node:http";
|
|
8588
|
-
var LOGIN_CALLBACK_TIMEOUT_MS =
|
|
9750
|
+
var LOGIN_CALLBACK_TIMEOUT_MS = 10 * 60 * 1e3;
|
|
8589
9751
|
var MAX_BODY_BYTES = 16 * 1024;
|
|
9752
|
+
function statesMatch(expected, given) {
|
|
9753
|
+
if (given === null) return false;
|
|
9754
|
+
const left = Buffer.from(expected, "utf8");
|
|
9755
|
+
const right = Buffer.from(given, "utf8");
|
|
9756
|
+
return right.length === left.length && timingSafeEqual(right, left);
|
|
9757
|
+
}
|
|
8590
9758
|
var LoginAccessDeniedError = class extends Error {
|
|
8591
9759
|
constructor() {
|
|
8592
9760
|
super("The login was canceled (access_denied).");
|
|
@@ -8595,7 +9763,7 @@ var LoginAccessDeniedError = class extends Error {
|
|
|
8595
9763
|
};
|
|
8596
9764
|
var LoginCallbackTimeoutError = class extends Error {
|
|
8597
9765
|
constructor() {
|
|
8598
|
-
super("The login timed out after
|
|
9766
|
+
super("The login timed out after ten minutes.");
|
|
8599
9767
|
this.name = "LoginCallbackTimeoutError";
|
|
8600
9768
|
}
|
|
8601
9769
|
};
|
|
@@ -8618,12 +9786,7 @@ function startLoginCallback(options) {
|
|
|
8618
9786
|
sendHtml(response, 500, "The login callback could not read the request.");
|
|
8619
9787
|
});
|
|
8620
9788
|
});
|
|
8621
|
-
|
|
8622
|
-
if (given === null) return false;
|
|
8623
|
-
const expected = Buffer.from(options.state, "utf8");
|
|
8624
|
-
const received = Buffer.from(given, "utf8");
|
|
8625
|
-
return received.length === expected.length && timingSafeEqual(received, expected);
|
|
8626
|
-
}
|
|
9789
|
+
const stateMatches = (given) => statesMatch(options.state, given);
|
|
8627
9790
|
const finish = (action) => {
|
|
8628
9791
|
if (settled) return false;
|
|
8629
9792
|
settled = true;
|
|
@@ -8658,18 +9821,12 @@ function startLoginCallback(options) {
|
|
|
8658
9821
|
}
|
|
8659
9822
|
return;
|
|
8660
9823
|
}
|
|
8661
|
-
const
|
|
8662
|
-
if (!
|
|
8663
|
-
sendHtml(response, 400, "Missing
|
|
9824
|
+
const code = form.get("code");
|
|
9825
|
+
if (!code) {
|
|
9826
|
+
sendHtml(response, 400, "Missing code.");
|
|
8664
9827
|
return;
|
|
8665
9828
|
}
|
|
8666
|
-
const delivered = {
|
|
8667
|
-
token,
|
|
8668
|
-
keyId: form.get("key_id"),
|
|
8669
|
-
tenantId: form.get("tenant_id"),
|
|
8670
|
-
tenantName: form.get("tenant_name"),
|
|
8671
|
-
role: form.get("role")
|
|
8672
|
-
};
|
|
9829
|
+
const delivered = { code };
|
|
8673
9830
|
if (finish(() => resolveResult(delivered))) {
|
|
8674
9831
|
sendHtml(response, 200, "Login approved. You can close this window.");
|
|
8675
9832
|
} else {
|
|
@@ -8701,6 +9858,10 @@ function startLoginCallback(options) {
|
|
|
8701
9858
|
}
|
|
8702
9859
|
resolveServer({
|
|
8703
9860
|
callbackUrl: `http://127.0.0.1:${address.port}/callback`,
|
|
9861
|
+
address: () => {
|
|
9862
|
+
const bound = server.address();
|
|
9863
|
+
return typeof bound === "object" && bound !== null ? { address: bound.address, port: bound.port } : null;
|
|
9864
|
+
},
|
|
8704
9865
|
waitForResult: () => result,
|
|
8705
9866
|
close: () => new Promise((resolveClose) => {
|
|
8706
9867
|
settled = true;
|
|
@@ -8736,132 +9897,59 @@ async function readBody(request) {
|
|
|
8736
9897
|
return body;
|
|
8737
9898
|
}
|
|
8738
9899
|
|
|
9900
|
+
// src/pkce.ts
|
|
9901
|
+
import { createHash, randomBytes as randomBytes2 } from "node:crypto";
|
|
9902
|
+
function generateCodeVerifier() {
|
|
9903
|
+
return randomBytes2(32).toString("base64url");
|
|
9904
|
+
}
|
|
9905
|
+
function codeChallengeFor(verifier) {
|
|
9906
|
+
return createHash("sha256").update(verifier).digest("base64url");
|
|
9907
|
+
}
|
|
9908
|
+
|
|
8739
9909
|
// src/index.ts
|
|
8740
9910
|
function cliUserAgent() {
|
|
8741
9911
|
return `nouter-platform-cli/${cliVersion()} node/${process.versions.node}`;
|
|
8742
9912
|
}
|
|
8743
9913
|
var REQUEST_TIMEOUT_MS = 3e4;
|
|
8744
|
-
var CONFIG_DIRECTORY = "nouter-platform";
|
|
8745
|
-
var CONFIG_FILE = "config.json";
|
|
8746
9914
|
var CliError = class extends Error {
|
|
8747
9915
|
exitCode;
|
|
8748
|
-
|
|
9916
|
+
/** El código estable de R9 que viaja como `error.code` con `--json`. */
|
|
9917
|
+
code;
|
|
9918
|
+
constructor(message, exitCode = 1, code) {
|
|
8749
9919
|
super(message);
|
|
8750
9920
|
this.name = "CliError";
|
|
8751
9921
|
this.exitCode = exitCode;
|
|
9922
|
+
if (code !== void 0) this.code = code;
|
|
8752
9923
|
}
|
|
8753
9924
|
};
|
|
8754
|
-
function
|
|
8755
|
-
const xdg = process.env.XDG_CONFIG_HOME;
|
|
8756
|
-
const base = xdg && xdg.length > 0 ? xdg : join2(process.env.HOME ?? homedir(), ".config");
|
|
8757
|
-
return join2(base, CONFIG_DIRECTORY);
|
|
8758
|
-
}
|
|
8759
|
-
function configPath() {
|
|
8760
|
-
return join2(configDirectory(), CONFIG_FILE);
|
|
8761
|
-
}
|
|
8762
|
-
var warnedAboutLoosePermissions = false;
|
|
8763
|
-
function warnAboutLoosePermissions(path, mode, platform, warn) {
|
|
8764
|
-
if (platform === "win32" || warnedAboutLoosePermissions) return;
|
|
8765
|
-
if ((mode & 63) === 0) return;
|
|
8766
|
-
warnedAboutLoosePermissions = true;
|
|
8767
|
-
const shown = (mode & 511).toString(8).padStart(3, "0");
|
|
8768
|
-
warn(`Warning: the config file ${path} is readable by other users (mode ${shown}); run \`chmod 600 ${path}\`.`);
|
|
8769
|
-
}
|
|
8770
|
-
function readConfig(options = {}) {
|
|
8771
|
-
const platform = options.platform ?? process.platform;
|
|
8772
|
-
const warn = options.warn ?? ((message) => process.stderr.write(`${message}
|
|
8773
|
-
`));
|
|
8774
|
-
const path = configPath();
|
|
8775
|
-
if (!existsSync(path)) return null;
|
|
8776
|
-
let mode;
|
|
8777
|
-
try {
|
|
8778
|
-
mode = statSync2(path).mode;
|
|
8779
|
-
} catch {
|
|
8780
|
-
mode = void 0;
|
|
8781
|
-
}
|
|
8782
|
-
if (mode !== void 0) warnAboutLoosePermissions(path, mode, platform, warn);
|
|
8783
|
-
try {
|
|
8784
|
-
const parsed = JSON.parse(readFileSync3(path, "utf8"));
|
|
8785
|
-
if (typeof parsed.apiKey !== "string" || parsed.apiKey.length === 0) return null;
|
|
8786
|
-
const baseUrl = typeof parsed.baseUrl === "string" && parsed.baseUrl.length > 0 ? parsed.baseUrl : null;
|
|
8787
|
-
return { baseUrl, apiKey: parsed.apiKey };
|
|
8788
|
-
} catch {
|
|
8789
|
-
return null;
|
|
8790
|
-
}
|
|
8791
|
-
}
|
|
8792
|
-
function rejectSymlink(path, what) {
|
|
8793
|
-
let stats;
|
|
8794
|
-
try {
|
|
8795
|
-
stats = lstatSync(path);
|
|
8796
|
-
} catch (error) {
|
|
8797
|
-
if (error.code === "ENOENT") return;
|
|
8798
|
-
throw error;
|
|
8799
|
-
}
|
|
8800
|
-
if (stats.isSymbolicLink()) {
|
|
8801
|
-
throw new CliError(`${what} is a symbolic link; refusing to follow it.`);
|
|
8802
|
-
}
|
|
8803
|
-
}
|
|
8804
|
-
function writeConfig(config) {
|
|
8805
|
-
const directory = configDirectory();
|
|
8806
|
-
mkdirSync(directory, { recursive: true, mode: 448 });
|
|
8807
|
-
rejectSymlink(directory, "The config directory");
|
|
8808
|
-
try {
|
|
8809
|
-
chmodSync(directory, 448);
|
|
8810
|
-
} catch {
|
|
8811
|
-
throw new CliError(`Could not set the config directory ${directory} to 0700.`);
|
|
8812
|
-
}
|
|
8813
|
-
const path = configPath();
|
|
8814
|
-
rejectSymlink(path, "The config file");
|
|
8815
|
-
const temporary = join2(directory, `.config.json.${randomBytes(6).toString("hex")}.tmp`);
|
|
8816
|
-
const fd = openSync(temporary, "wx", 384);
|
|
8817
|
-
let open = true;
|
|
8818
|
-
try {
|
|
8819
|
-
try {
|
|
8820
|
-
fchmodSync(fd, 384);
|
|
8821
|
-
} catch {
|
|
8822
|
-
throw new CliError("Could not set the config file to 0600.");
|
|
8823
|
-
}
|
|
8824
|
-
writeSync(fd, `${JSON.stringify(config, null, 2)}
|
|
8825
|
-
`);
|
|
8826
|
-
closeSync(fd);
|
|
8827
|
-
open = false;
|
|
8828
|
-
renameSync(temporary, path);
|
|
8829
|
-
} catch (error) {
|
|
8830
|
-
if (open) {
|
|
8831
|
-
try {
|
|
8832
|
-
closeSync(fd);
|
|
8833
|
-
} catch {
|
|
8834
|
-
}
|
|
8835
|
-
}
|
|
8836
|
-
try {
|
|
8837
|
-
unlinkSync(temporary);
|
|
8838
|
-
} catch {
|
|
8839
|
-
}
|
|
8840
|
-
throw error;
|
|
8841
|
-
}
|
|
8842
|
-
}
|
|
8843
|
-
function clearConfig() {
|
|
8844
|
-
const path = configPath();
|
|
8845
|
-
if (!existsSync(path)) return false;
|
|
8846
|
-
unlinkSync(path);
|
|
8847
|
-
return true;
|
|
8848
|
-
}
|
|
8849
|
-
function describeApiFailure(error) {
|
|
9925
|
+
function serverErrorType(error) {
|
|
8850
9926
|
const candidate = error;
|
|
8851
|
-
const
|
|
8852
|
-
if (
|
|
8853
|
-
|
|
8854
|
-
|
|
8855
|
-
|
|
8856
|
-
|
|
8857
|
-
|
|
8858
|
-
const
|
|
8859
|
-
if (
|
|
8860
|
-
|
|
8861
|
-
return "the request timed out";
|
|
9927
|
+
const inner = candidate.error?.error?.type;
|
|
9928
|
+
if (typeof inner === "string") return inner;
|
|
9929
|
+
const outer = candidate.error?.type;
|
|
9930
|
+
return typeof outer === "string" ? outer : void 0;
|
|
9931
|
+
}
|
|
9932
|
+
var SESSION_LIMIT_CODES = /* @__PURE__ */ new Set(["SESSION_EXPIRED", "SESSION_IDLE", "SESSION_REVOKED"]);
|
|
9933
|
+
function apiFailure(error, fallback) {
|
|
9934
|
+
const typeName = serverErrorType(error);
|
|
9935
|
+
if (typeName !== void 0 && (SESSION_LIMIT_CODES.has(typeName) || typeName === "ELEVATION_REQUIRED")) {
|
|
9936
|
+
return new CliError(`${fallback}: ${describeApiFailure(error)}`, 77, typeName);
|
|
8862
9937
|
}
|
|
8863
|
-
|
|
8864
|
-
|
|
9938
|
+
return new CliError(`${fallback}: ${describeApiFailure(error)}`);
|
|
9939
|
+
}
|
|
9940
|
+
function isCliSessionToken(value) {
|
|
9941
|
+
return value.startsWith("nps_");
|
|
9942
|
+
}
|
|
9943
|
+
function isElevationRequired(error) {
|
|
9944
|
+
const candidate = error;
|
|
9945
|
+
return candidate.status === 403 && serverErrorType(error) === "ELEVATION_REQUIRED";
|
|
9946
|
+
}
|
|
9947
|
+
function elevationCliError(error) {
|
|
9948
|
+
return new CliError(
|
|
9949
|
+
`This operation needs elevation and the request was not elevated. Run \`nouter-platform elevate\` and try again (${describeApiFailure(error)}).`,
|
|
9950
|
+
77,
|
|
9951
|
+
"ELEVATION_REQUIRED"
|
|
9952
|
+
);
|
|
8865
9953
|
}
|
|
8866
9954
|
var BASE_URL_HINT = "Set NOUTER_PLATFORM_BASE_URL or run `nouter-platform login`.";
|
|
8867
9955
|
var LOGIN_BASE_URL_HINT = "Set NOUTER_PLATFORM_BASE_URL before logging in.";
|
|
@@ -8883,6 +9971,15 @@ function normalizeBaseUrl(value) {
|
|
|
8883
9971
|
}
|
|
8884
9972
|
return `${url.origin}${url.pathname.replace(/\/+$/, "")}`;
|
|
8885
9973
|
}
|
|
9974
|
+
function sanitizeHostname(raw) {
|
|
9975
|
+
const clean2 = raw.replace(
|
|
9976
|
+
/[\u0000-\u001F\u007F-\u009F\u061C\u200B-\u200F\u2028-\u202E\u2066-\u2069\uFEFF]/g,
|
|
9977
|
+
""
|
|
9978
|
+
);
|
|
9979
|
+
const trimmed = clean2.trim();
|
|
9980
|
+
if (trimmed.length === 0) return "unknown";
|
|
9981
|
+
return trimmed.slice(0, 253);
|
|
9982
|
+
}
|
|
8886
9983
|
function requireBaseUrl(stored, hint = BASE_URL_HINT) {
|
|
8887
9984
|
const envBase = process.env.NOUTER_PLATFORM_BASE_URL;
|
|
8888
9985
|
const candidate = envBase && envBase.length > 0 ? envBase : stored?.baseUrl;
|
|
@@ -8931,7 +10028,7 @@ function federationFailure(error) {
|
|
|
8931
10028
|
throw error;
|
|
8932
10029
|
}
|
|
8933
10030
|
async function resolveAuth(deps) {
|
|
8934
|
-
const stored = readConfig(
|
|
10031
|
+
const stored = readConfig();
|
|
8935
10032
|
const envBase = process.env.NOUTER_PLATFORM_BASE_URL;
|
|
8936
10033
|
const envKey = environmentApiKey();
|
|
8937
10034
|
const federationConfigured = typeof process.env.NOUTER_PLATFORM_FEDERATION_RULE_ID === "string" && process.env.NOUTER_PLATFORM_FEDERATION_RULE_ID.length > 0;
|
|
@@ -8954,22 +10051,37 @@ async function resolveAuth(deps) {
|
|
|
8954
10051
|
if (!stored) {
|
|
8955
10052
|
throw new CliError("Not authenticated. Run `nouter-platform login --api-key` or set NOUTER_PLATFORM_API_KEY.");
|
|
8956
10053
|
}
|
|
10054
|
+
const session = isCliSessionToken(stored.apiKey);
|
|
8957
10055
|
if (stored.baseUrl === null) {
|
|
8958
10056
|
throw new CliError(
|
|
8959
10057
|
"The stored config has no API base URL, so the key's host is unknown. Run `nouter-platform login` again against your API URL, or set NOUTER_PLATFORM_API_KEY."
|
|
8960
10058
|
);
|
|
8961
10059
|
}
|
|
10060
|
+
if (session && stored.clientId !== void 0 && stored.clientId !== CLI_CLIENT_ID) {
|
|
10061
|
+
throw new CliError(
|
|
10062
|
+
`The stored CLI session belongs to the client ${stored.clientId}, not ${CLI_CLIENT_ID}. Run \`nouter-platform login\` again.`,
|
|
10063
|
+
77,
|
|
10064
|
+
"WRONG_INSTALLATION"
|
|
10065
|
+
);
|
|
10066
|
+
}
|
|
8962
10067
|
const storedBaseUrl = normalizeBaseUrl(stored.baseUrl);
|
|
8963
10068
|
if (envBase && envBase.length > 0) {
|
|
8964
10069
|
const envBaseUrl = normalizeBaseUrl(envBase);
|
|
8965
10070
|
if (envBaseUrl !== storedBaseUrl) {
|
|
10071
|
+
if (session) {
|
|
10072
|
+
throw new CliError(
|
|
10073
|
+
`The stored CLI session belongs to the installation ${storedBaseUrl}, not ${envBaseUrl}. Run \`nouter-platform login\` against ${envBaseUrl}.`,
|
|
10074
|
+
77,
|
|
10075
|
+
"WRONG_INSTALLATION"
|
|
10076
|
+
);
|
|
10077
|
+
}
|
|
8966
10078
|
throw new CliError(
|
|
8967
10079
|
`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.`
|
|
8968
10080
|
);
|
|
8969
10081
|
}
|
|
8970
|
-
return { baseUrl: envBaseUrl, credential: stored.apiKey, transport: "api-key" };
|
|
10082
|
+
return { baseUrl: envBaseUrl, credential: stored.apiKey, transport: session ? "bearer" : "api-key" };
|
|
8971
10083
|
}
|
|
8972
|
-
return { baseUrl: storedBaseUrl, credential: stored.apiKey, transport: "api-key" };
|
|
10084
|
+
return { baseUrl: storedBaseUrl, credential: stored.apiKey, transport: session ? "bearer" : "api-key" };
|
|
8973
10085
|
}
|
|
8974
10086
|
var notTheApiMiddleware = async (request, next) => {
|
|
8975
10087
|
const response = await next({ ...request, redirect: "manual" });
|
|
@@ -8999,7 +10111,7 @@ async function fetchMe(auth, deps) {
|
|
|
8999
10111
|
});
|
|
9000
10112
|
} catch (error) {
|
|
9001
10113
|
if (error instanceof CliError) throw error;
|
|
9002
|
-
throw
|
|
10114
|
+
throw apiFailure(error, "Could not read the account");
|
|
9003
10115
|
}
|
|
9004
10116
|
}
|
|
9005
10117
|
function organizationOf(me) {
|
|
@@ -9015,8 +10127,10 @@ function roleOf(me) {
|
|
|
9015
10127
|
return me.tenants?.[0]?.role ?? null;
|
|
9016
10128
|
}
|
|
9017
10129
|
function loginBaseUrl(deps) {
|
|
10130
|
+
const envBase = process.env.NOUTER_PLATFORM_BASE_URL;
|
|
10131
|
+
const stored = envBase && envBase.length > 0 ? null : readConfig();
|
|
9018
10132
|
try {
|
|
9019
|
-
return requireBaseUrl(
|
|
10133
|
+
return requireBaseUrl(stored, LOGIN_BASE_URL_HINT);
|
|
9020
10134
|
} catch (error) {
|
|
9021
10135
|
if (error instanceof CliError && !error.message.includes("NOUTER_PLATFORM_BASE_URL")) {
|
|
9022
10136
|
throw new CliError(`${error.message} ${LOGIN_BASE_URL_HINT}`);
|
|
@@ -9024,6 +10138,30 @@ function loginBaseUrl(deps) {
|
|
|
9024
10138
|
throw error;
|
|
9025
10139
|
}
|
|
9026
10140
|
}
|
|
10141
|
+
function remoteSessionSignal(env, platform) {
|
|
10142
|
+
if (typeof env.SSH_CONNECTION === "string" && env.SSH_CONNECTION.length > 0) return "SSH_CONNECTION";
|
|
10143
|
+
if (typeof env.SSH_TTY === "string" && env.SSH_TTY.length > 0) return "SSH_TTY";
|
|
10144
|
+
if (env.CODESPACES === "true") return "CODESPACES";
|
|
10145
|
+
if (platform === "linux" && !env.DISPLAY && !env.WAYLAND_DISPLAY) return "no DISPLAY or WAYLAND_DISPLAY";
|
|
10146
|
+
return null;
|
|
10147
|
+
}
|
|
10148
|
+
function resolveLoginMode(args, env, platform) {
|
|
10149
|
+
if (args.includes("--browser")) return { mode: "loopback", signal: null };
|
|
10150
|
+
if (args.includes("--paste")) return { mode: "paste", signal: null };
|
|
10151
|
+
const signal = remoteSessionSignal(env, platform);
|
|
10152
|
+
return signal === null ? { mode: "loopback", signal: null } : { mode: "paste", signal };
|
|
10153
|
+
}
|
|
10154
|
+
function loginEnvironment(deps) {
|
|
10155
|
+
return deps.env ?? process.env;
|
|
10156
|
+
}
|
|
10157
|
+
function loginPlatform(deps) {
|
|
10158
|
+
return deps.platform ?? process.platform;
|
|
10159
|
+
}
|
|
10160
|
+
function announceRemoteSession(signal, deps) {
|
|
10161
|
+
deps.writeStderr(
|
|
10162
|
+
`Remote session detected (${signal}): using paste mode. Run \`nouter-platform login --browser\` to force the browser flow.`
|
|
10163
|
+
);
|
|
10164
|
+
}
|
|
9027
10165
|
async function loginWithApiKey(deps) {
|
|
9028
10166
|
const baseUrl = loginBaseUrl(deps);
|
|
9029
10167
|
const apiKey = (await deps.readStdin()).trim();
|
|
@@ -9038,27 +10176,198 @@ async function loginWithApiKey(deps) {
|
|
|
9038
10176
|
deps.writeStdout(`Logged in to ${organizationOf(me) ?? "the organization"}.`);
|
|
9039
10177
|
return 0;
|
|
9040
10178
|
}
|
|
9041
|
-
async function
|
|
9042
|
-
const
|
|
9043
|
-
|
|
9044
|
-
|
|
10179
|
+
async function cliJsonRequest(deps, url, init) {
|
|
10180
|
+
const headers = { accept: "application/json" };
|
|
10181
|
+
if (init.body !== void 0) headers["content-type"] = "application/json";
|
|
10182
|
+
if (init.token !== void 0) headers.authorization = `Bearer ${init.token}`;
|
|
10183
|
+
let response;
|
|
10184
|
+
try {
|
|
10185
|
+
response = await deps.fetch(url, {
|
|
10186
|
+
method: init.method,
|
|
10187
|
+
headers,
|
|
10188
|
+
...init.body !== void 0 && { body: JSON.stringify(init.body) },
|
|
10189
|
+
signal: AbortSignal.timeout(deps.requestTimeoutMs)
|
|
10190
|
+
});
|
|
10191
|
+
} catch (error) {
|
|
10192
|
+
throw new CliError(`The request failed: ${describeApiFailure(error)}`, 75, "LOGIN_TIMEOUT");
|
|
10193
|
+
}
|
|
10194
|
+
const text = await response.text();
|
|
10195
|
+
let body = null;
|
|
10196
|
+
if (text.length > 0) {
|
|
10197
|
+
try {
|
|
10198
|
+
body = JSON.parse(text);
|
|
10199
|
+
} catch {
|
|
10200
|
+
body = text;
|
|
10201
|
+
}
|
|
10202
|
+
}
|
|
10203
|
+
return { status: response.status, body };
|
|
10204
|
+
}
|
|
10205
|
+
function bodyField(body, name) {
|
|
10206
|
+
if (typeof body !== "object" || body === null) return void 0;
|
|
10207
|
+
return body[name];
|
|
10208
|
+
}
|
|
10209
|
+
function loginApiError(status, body, fallback) {
|
|
10210
|
+
const type = bodyField(bodyField(body, "error"), "type");
|
|
10211
|
+
const message = bodyField(bodyField(body, "error"), "message");
|
|
10212
|
+
const detail = message && message.length > 0 ? message : `the server answered ${status}`;
|
|
10213
|
+
if (type !== void 0 && (SESSION_LIMIT_CODES.has(type) || type === "ELEVATION_REQUIRED")) {
|
|
10214
|
+
return new CliError(`${fallback}: ${detail}`, 77, type);
|
|
10215
|
+
}
|
|
10216
|
+
if (status >= 500 || status === 429) return new CliError(`${fallback}: ${detail}`, 75, "LOGIN_TIMEOUT");
|
|
10217
|
+
return new CliError(`${fallback}: ${detail}`, 1);
|
|
10218
|
+
}
|
|
10219
|
+
async function startAuthorization(baseUrl, deps, body, token) {
|
|
10220
|
+
const answer = await cliJsonRequest(deps, `${baseUrl}/v1/oma/cli/authorize/start`, {
|
|
10221
|
+
method: "POST",
|
|
10222
|
+
body,
|
|
10223
|
+
...token !== void 0 && { token }
|
|
10224
|
+
});
|
|
10225
|
+
const requestId = bodyField(answer.body, "request_id");
|
|
10226
|
+
if (answer.status !== 200 || typeof requestId !== "string" || requestId.length === 0) {
|
|
10227
|
+
throw loginApiError(answer.status, answer.body, "Could not start the login");
|
|
10228
|
+
}
|
|
10229
|
+
return requestId;
|
|
10230
|
+
}
|
|
10231
|
+
async function redeemCode(baseUrl, deps, code, verifier) {
|
|
10232
|
+
const answer = await cliJsonRequest(deps, `${baseUrl}/v1/oma/cli/sessions`, {
|
|
10233
|
+
method: "POST",
|
|
10234
|
+
body: { code, code_verifier: verifier }
|
|
10235
|
+
});
|
|
10236
|
+
const sessionId = bodyField(answer.body, "session_id");
|
|
10237
|
+
if (answer.status === 200 && typeof sessionId === "string") {
|
|
10238
|
+
if (bodyField(answer.body, "elevated") === true) return { kind: "elevated", sessionId };
|
|
10239
|
+
const token = bodyField(answer.body, "token");
|
|
10240
|
+
if (typeof token === "string" && token.length > 0) return { kind: "session", token, sessionId };
|
|
10241
|
+
}
|
|
10242
|
+
const type = bodyField(bodyField(answer.body, "error"), "type");
|
|
10243
|
+
if (type === "ELEVATION_REQUIRED") {
|
|
10244
|
+
throw new CliError(
|
|
10245
|
+
"This CLI session needs a fresh console login to elevate. Run `nouter-platform elevate` and sign in again.",
|
|
10246
|
+
77,
|
|
10247
|
+
"ELEVATION_REQUIRED"
|
|
10248
|
+
);
|
|
10249
|
+
}
|
|
10250
|
+
if (answer.status === 400) {
|
|
10251
|
+
throw new CliError(
|
|
10252
|
+
"The authorization code is invalid, expired, or already used. Run `nouter-platform login` again.",
|
|
10253
|
+
75,
|
|
10254
|
+
"LOGIN_TIMEOUT"
|
|
10255
|
+
);
|
|
10256
|
+
}
|
|
10257
|
+
throw loginApiError(answer.status, answer.body, "Could not redeem the login code");
|
|
10258
|
+
}
|
|
10259
|
+
function consoleUrlFor(baseUrl, requestId, state, callback) {
|
|
10260
|
+
const url = new URL("/cli/login", baseUrl);
|
|
10261
|
+
url.searchParams.set("request_id", requestId);
|
|
10262
|
+
url.searchParams.set("state", state);
|
|
10263
|
+
if (callback !== void 0) url.searchParams.set("callback", callback);
|
|
10264
|
+
return url.toString();
|
|
10265
|
+
}
|
|
10266
|
+
async function awaitPastedCode(deps, state) {
|
|
10267
|
+
deps.writeStdout("Paste code here if prompted >");
|
|
10268
|
+
const readSecret = deps.readSecret ?? deps.readStdin;
|
|
10269
|
+
const pasted = (await readSecret()).trim();
|
|
10270
|
+
const hash = pasted.lastIndexOf("#");
|
|
10271
|
+
if (hash <= 0 || hash === pasted.length - 1) {
|
|
10272
|
+
throw new CliError(
|
|
10273
|
+
"The pasted code is not in the code#state form. Copy it again from the page that this command opened.",
|
|
10274
|
+
64,
|
|
10275
|
+
"STATE_MISMATCH"
|
|
10276
|
+
);
|
|
10277
|
+
}
|
|
10278
|
+
const code = pasted.slice(0, hash);
|
|
10279
|
+
const pastedState = pasted.slice(hash + 1);
|
|
10280
|
+
if (!statesMatch(state, pastedState)) {
|
|
10281
|
+
throw new CliError(
|
|
10282
|
+
"The pasted code belongs to another login attempt. Copy it again from the page that this command opened.",
|
|
10283
|
+
64,
|
|
10284
|
+
"STATE_MISMATCH"
|
|
10285
|
+
);
|
|
10286
|
+
}
|
|
10287
|
+
return code;
|
|
10288
|
+
}
|
|
10289
|
+
function previousBaseUrlOf(previous) {
|
|
10290
|
+
if (previous === null || previous.baseUrl === null) return null;
|
|
9045
10291
|
try {
|
|
9046
|
-
|
|
9047
|
-
|
|
9048
|
-
|
|
9049
|
-
|
|
10292
|
+
return normalizeBaseUrl(previous.baseUrl);
|
|
10293
|
+
} catch {
|
|
10294
|
+
return null;
|
|
10295
|
+
}
|
|
10296
|
+
}
|
|
10297
|
+
async function revokeStoredSession(baseUrl, deps, token) {
|
|
10298
|
+
try {
|
|
10299
|
+
await cliJsonRequest(deps, `${baseUrl}/v1/oma/cli/sessions/current`, { method: "DELETE", token });
|
|
10300
|
+
} catch {
|
|
10301
|
+
}
|
|
10302
|
+
}
|
|
10303
|
+
async function loginWithCode(argv, deps) {
|
|
10304
|
+
const baseUrl = loginBaseUrl(deps);
|
|
10305
|
+
const previous = readConfig();
|
|
10306
|
+
const choice = resolveLoginMode(argv, loginEnvironment(deps), loginPlatform(deps));
|
|
10307
|
+
if (choice.signal !== null) announceRemoteSession(choice.signal, deps);
|
|
10308
|
+
const verifier = generateCodeVerifier();
|
|
10309
|
+
const requestId = await startAuthorization(baseUrl, deps, {
|
|
10310
|
+
code_challenge: codeChallengeFor(verifier),
|
|
10311
|
+
code_challenge_method: "S256",
|
|
10312
|
+
hostname: sanitizeHostname(hostname()),
|
|
10313
|
+
mode: choice.mode,
|
|
10314
|
+
purpose: "login"
|
|
10315
|
+
});
|
|
10316
|
+
const state = randomBytes3(32).toString("base64url");
|
|
10317
|
+
let code;
|
|
10318
|
+
if (choice.mode === "loopback") {
|
|
10319
|
+
const callback = await startLoginCallback({ state, timeoutMs: LOGIN_CALLBACK_TIMEOUT_MS });
|
|
10320
|
+
let consoleUrl;
|
|
10321
|
+
try {
|
|
10322
|
+
consoleUrl = consoleUrlFor(baseUrl, requestId, state, callback.callbackUrl);
|
|
10323
|
+
} catch (error) {
|
|
10324
|
+
await callback.close();
|
|
10325
|
+
throw error;
|
|
10326
|
+
}
|
|
10327
|
+
try {
|
|
10328
|
+
deps.writeStdout(`Open this URL to approve the login:
|
|
10329
|
+
${consoleUrl}`);
|
|
10330
|
+
deps.openBrowser(consoleUrl);
|
|
10331
|
+
code = (await callback.waitForResult()).code;
|
|
10332
|
+
} catch (error) {
|
|
10333
|
+
if (error instanceof LoginCallbackTimeoutError) {
|
|
10334
|
+
throw new CliError("The login timed out after ten minutes. Run `nouter-platform login` again.", 75, "LOGIN_TIMEOUT");
|
|
10335
|
+
}
|
|
10336
|
+
throw error;
|
|
10337
|
+
} finally {
|
|
10338
|
+
await callback.close();
|
|
10339
|
+
}
|
|
10340
|
+
} else {
|
|
9050
10341
|
deps.writeStdout(`Open this URL to approve the login:
|
|
9051
|
-
${
|
|
9052
|
-
deps.openBrowser(
|
|
9053
|
-
|
|
9054
|
-
|
|
9055
|
-
|
|
9056
|
-
|
|
9057
|
-
|
|
9058
|
-
|
|
9059
|
-
|
|
9060
|
-
|
|
10342
|
+
${consoleUrlFor(baseUrl, requestId, state)}`);
|
|
10343
|
+
deps.openBrowser(consoleUrlFor(baseUrl, requestId, state));
|
|
10344
|
+
code = await awaitPastedCode(deps, state);
|
|
10345
|
+
}
|
|
10346
|
+
const outcome = await redeemCode(baseUrl, deps, code, verifier);
|
|
10347
|
+
if (outcome.kind !== "session" || outcome.token === void 0) {
|
|
10348
|
+
throw new CliError("The server did not return a CLI session. Run `nouter-platform login` again.", 75, "LOGIN_TIMEOUT");
|
|
10349
|
+
}
|
|
10350
|
+
writeConfig({
|
|
10351
|
+
baseUrl,
|
|
10352
|
+
apiKey: outcome.token,
|
|
10353
|
+
iss: baseUrl,
|
|
10354
|
+
clientId: CLI_CLIENT_ID,
|
|
10355
|
+
sessionId: outcome.sessionId
|
|
10356
|
+
});
|
|
10357
|
+
const previousBaseUrl = previousBaseUrlOf(previous);
|
|
10358
|
+
if (previous !== null && previousBaseUrl === baseUrl && isCliSessionToken(previous.apiKey) && previous.apiKey !== outcome.token) {
|
|
10359
|
+
await revokeStoredSession(previousBaseUrl, deps, previous.apiKey);
|
|
10360
|
+
} else if (previous !== null && previousBaseUrl !== null && previousBaseUrl !== baseUrl) {
|
|
10361
|
+
deps.writeStderr(
|
|
10362
|
+
`The previous session of ${new URL(previousBaseUrl).host} was not revoked; revoke it from that console.`
|
|
10363
|
+
);
|
|
9061
10364
|
}
|
|
10365
|
+
const organization = await fetchMe(
|
|
10366
|
+
{ baseUrl, credential: outcome.token, transport: "bearer" },
|
|
10367
|
+
deps
|
|
10368
|
+
).then((me) => organizationOf(me)).catch(() => null);
|
|
10369
|
+
deps.writeStdout(`Logged in to ${organization ?? "the organization"}.`);
|
|
10370
|
+
return 0;
|
|
9062
10371
|
}
|
|
9063
10372
|
function login(argv, deps) {
|
|
9064
10373
|
const rejectedValue = argv.some((argument) => argument.startsWith("--api-key="));
|
|
@@ -9069,16 +10378,273 @@ function login(argv, deps) {
|
|
|
9069
10378
|
"The API key must come from stdin: use `nouter-platform login --api-key` with no value."
|
|
9070
10379
|
);
|
|
9071
10380
|
}
|
|
9072
|
-
const withApiKey = argv.includes(
|
|
9073
|
-
const withBrowser = argv.includes(
|
|
9074
|
-
|
|
9075
|
-
|
|
10381
|
+
const withApiKey = argv.includes("--api-key");
|
|
10382
|
+
const withBrowser = argv.includes("--browser");
|
|
10383
|
+
const withPaste = argv.includes("--paste");
|
|
10384
|
+
const chosen = [withApiKey, withBrowser, withPaste].filter(Boolean).length;
|
|
10385
|
+
if (chosen > 1) {
|
|
10386
|
+
throw new CliError("Choose one way to log in: `--api-key` (from stdin), `--browser` or `--paste`.");
|
|
9076
10387
|
}
|
|
9077
10388
|
if (withApiKey) return loginWithApiKey(deps);
|
|
9078
|
-
|
|
9079
|
-
|
|
9080
|
-
|
|
10389
|
+
return loginWithCode(argv, deps);
|
|
10390
|
+
}
|
|
10391
|
+
var SESSION_TTL_MS = 7 * 24 * 60 * 60 * 1e3;
|
|
10392
|
+
var SESSION_IDLE_MS = 24 * 60 * 60 * 1e3;
|
|
10393
|
+
function isoTime(value) {
|
|
10394
|
+
return typeof value === "number" ? new Date(value).toISOString() : "";
|
|
10395
|
+
}
|
|
10396
|
+
function requireCliSession(auth) {
|
|
10397
|
+
if (!isCliSessionToken(auth.credential)) {
|
|
10398
|
+
throw new CliError(
|
|
10399
|
+
"This command needs a CLI session. Run `nouter-platform login` first; a machine key cannot manage sessions.",
|
|
10400
|
+
77,
|
|
10401
|
+
"SESSION_REQUIRED"
|
|
10402
|
+
);
|
|
10403
|
+
}
|
|
10404
|
+
}
|
|
10405
|
+
async function currentSession(auth, deps) {
|
|
10406
|
+
const id = readConfig()?.sessionId;
|
|
10407
|
+
if (id === void 0) return null;
|
|
10408
|
+
try {
|
|
10409
|
+
const answer = await cliJsonRequest(deps, `${auth.baseUrl}/v1/oma/cli/sessions`, {
|
|
10410
|
+
method: "GET",
|
|
10411
|
+
token: auth.credential
|
|
10412
|
+
});
|
|
10413
|
+
if (answer.status !== 200) return null;
|
|
10414
|
+
const sessions = bodyField(answer.body, "sessions") ?? [];
|
|
10415
|
+
return sessions.find((session) => session.id === id) ?? null;
|
|
10416
|
+
} catch {
|
|
10417
|
+
return null;
|
|
10418
|
+
}
|
|
10419
|
+
}
|
|
10420
|
+
async function sessionsList(deps, json) {
|
|
10421
|
+
const auth = await resolveAuth(deps);
|
|
10422
|
+
requireCliSession(auth);
|
|
10423
|
+
const answer = await cliJsonRequest(deps, `${auth.baseUrl}/v1/oma/cli/sessions`, {
|
|
10424
|
+
method: "GET",
|
|
10425
|
+
token: auth.credential
|
|
10426
|
+
});
|
|
10427
|
+
if (answer.status !== 200) throw loginApiError(answer.status, answer.body, "Could not list the CLI sessions");
|
|
10428
|
+
const sessions = bodyField(answer.body, "sessions") ?? [];
|
|
10429
|
+
if (json) {
|
|
10430
|
+
deps.writeStdout(JSON.stringify(sessions, null, 2));
|
|
10431
|
+
return 0;
|
|
10432
|
+
}
|
|
10433
|
+
if (sessions.length === 0) {
|
|
10434
|
+
deps.writeStdout("No CLI sessions.");
|
|
10435
|
+
return 0;
|
|
10436
|
+
}
|
|
10437
|
+
deps.writeStdout(
|
|
10438
|
+
table([
|
|
10439
|
+
["ID", "HOSTNAME", "MODE", "CREATED", "LAST USED", "ELEVATED UNTIL"],
|
|
10440
|
+
...sessions.map((session) => [
|
|
10441
|
+
session.id,
|
|
10442
|
+
session.hostname,
|
|
10443
|
+
session.mode,
|
|
10444
|
+
isoTime(session.created_at),
|
|
10445
|
+
isoTime(session.last_used_at),
|
|
10446
|
+
isoTime(session.elevated_until)
|
|
10447
|
+
])
|
|
10448
|
+
])
|
|
10449
|
+
);
|
|
10450
|
+
return 0;
|
|
10451
|
+
}
|
|
10452
|
+
async function sessionsRevoke(deps, id, json) {
|
|
10453
|
+
const auth = await resolveAuth(deps);
|
|
10454
|
+
requireCliSession(auth);
|
|
10455
|
+
const answer = await cliJsonRequest(deps, `${auth.baseUrl}/v1/oma/cli/sessions/${encodeURIComponent(id)}`, {
|
|
10456
|
+
method: "DELETE",
|
|
10457
|
+
token: auth.credential
|
|
10458
|
+
});
|
|
10459
|
+
if (answer.status === 404) throw new CliError("CLI session not found.", 1);
|
|
10460
|
+
if (answer.status < 200 || answer.status >= 300) {
|
|
10461
|
+
throw loginApiError(answer.status, answer.body, "Could not revoke the CLI session");
|
|
10462
|
+
}
|
|
10463
|
+
if (json) {
|
|
10464
|
+
deps.writeStdout(JSON.stringify(answer.body, null, 2));
|
|
10465
|
+
return 0;
|
|
10466
|
+
}
|
|
10467
|
+
deps.writeStdout(`Revoked CLI session ${id}.`);
|
|
10468
|
+
return 0;
|
|
10469
|
+
}
|
|
10470
|
+
async function authSessionsCommand(argv, deps) {
|
|
10471
|
+
const [subcommand, ...args] = argv;
|
|
10472
|
+
if (subcommand === "list") {
|
|
10473
|
+
const options = parseOptions(args, specFor("auth sessions list"));
|
|
10474
|
+
if (options.positionals.length > 0) throw new CliError("Usage: nouter-platform auth sessions list [--json]");
|
|
10475
|
+
return sessionsList(deps, options.booleans.has("--json"));
|
|
10476
|
+
}
|
|
10477
|
+
if (subcommand === "revoke") {
|
|
10478
|
+
const options = parseOptions(args, specFor("auth sessions revoke"));
|
|
10479
|
+
const id = options.positionals[0];
|
|
10480
|
+
if (id === void 0 || options.positionals.length > 1) {
|
|
10481
|
+
throw new CliError("Usage: nouter-platform auth sessions revoke <session-id> [--json]");
|
|
10482
|
+
}
|
|
10483
|
+
return sessionsRevoke(deps, id, options.booleans.has("--json"));
|
|
10484
|
+
}
|
|
10485
|
+
return usageError("auth sessions list|revoke <session-id>", deps);
|
|
10486
|
+
}
|
|
10487
|
+
async function elevateSession(auth, deps, choice) {
|
|
10488
|
+
requireCliSession(auth);
|
|
10489
|
+
if (choice.signal !== null) announceRemoteSession(choice.signal, deps);
|
|
10490
|
+
const verifier = generateCodeVerifier();
|
|
10491
|
+
const requestId = await startAuthorization(
|
|
10492
|
+
auth.baseUrl,
|
|
10493
|
+
deps,
|
|
10494
|
+
{
|
|
10495
|
+
code_challenge: codeChallengeFor(verifier),
|
|
10496
|
+
code_challenge_method: "S256",
|
|
10497
|
+
hostname: sanitizeHostname(hostname()),
|
|
10498
|
+
mode: choice.mode,
|
|
10499
|
+
purpose: "elevate"
|
|
10500
|
+
},
|
|
10501
|
+
auth.credential
|
|
9081
10502
|
);
|
|
10503
|
+
const state = randomBytes3(32).toString("base64url");
|
|
10504
|
+
let code;
|
|
10505
|
+
if (choice.mode === "loopback") {
|
|
10506
|
+
const callback = await startLoginCallback({ state, timeoutMs: LOGIN_CALLBACK_TIMEOUT_MS });
|
|
10507
|
+
try {
|
|
10508
|
+
const consoleUrl = consoleUrlFor(auth.baseUrl, requestId, state, callback.callbackUrl);
|
|
10509
|
+
deps.writeStdout(`Open this URL to confirm it's you:
|
|
10510
|
+
${consoleUrl}`);
|
|
10511
|
+
deps.openBrowser(consoleUrl);
|
|
10512
|
+
code = (await callback.waitForResult()).code;
|
|
10513
|
+
} catch (error) {
|
|
10514
|
+
if (error instanceof LoginCallbackTimeoutError) {
|
|
10515
|
+
throw new CliError("The elevation timed out after ten minutes. Run `nouter-platform elevate` again.", 75, "LOGIN_TIMEOUT");
|
|
10516
|
+
}
|
|
10517
|
+
throw error;
|
|
10518
|
+
} finally {
|
|
10519
|
+
await callback.close();
|
|
10520
|
+
}
|
|
10521
|
+
} else {
|
|
10522
|
+
const consoleUrl = consoleUrlFor(auth.baseUrl, requestId, state);
|
|
10523
|
+
deps.writeStdout(`Open this URL to confirm it's you:
|
|
10524
|
+
${consoleUrl}`);
|
|
10525
|
+
deps.openBrowser(consoleUrl);
|
|
10526
|
+
code = await awaitPastedCode(deps, state);
|
|
10527
|
+
}
|
|
10528
|
+
const outcome = await redeemCode(auth.baseUrl, deps, code, verifier);
|
|
10529
|
+
if (outcome.kind !== "elevated") {
|
|
10530
|
+
throw new CliError("The server did not elevate the session. Run `nouter-platform elevate` again.", 75, "ELEVATION_REQUIRED");
|
|
10531
|
+
}
|
|
10532
|
+
deps.writeStdout("Elevated for two hours.");
|
|
10533
|
+
return 0;
|
|
10534
|
+
}
|
|
10535
|
+
async function elevateCommand(argv, deps) {
|
|
10536
|
+
const options = parseOptions(argv, specFor("elevate"));
|
|
10537
|
+
if (options.positionals.length > 0) throw new CliError("Usage: nouter-platform elevate [--browser|--paste]");
|
|
10538
|
+
const auth = await resolveAuth(deps);
|
|
10539
|
+
return elevateSession(auth, deps, resolveLoginMode(argv, loginEnvironment(deps), loginPlatform(deps)));
|
|
10540
|
+
}
|
|
10541
|
+
function interactiveTerminal(deps) {
|
|
10542
|
+
if (deps.isInteractive !== void 0) return deps.isInteractive();
|
|
10543
|
+
return Boolean(process.stdin.isTTY && process.stdout.isTTY);
|
|
10544
|
+
}
|
|
10545
|
+
async function elevatedRequest(auth, deps, request) {
|
|
10546
|
+
const client = clientFor(auth, deps);
|
|
10547
|
+
try {
|
|
10548
|
+
return await request(client);
|
|
10549
|
+
} catch (error) {
|
|
10550
|
+
if (!isElevationRequired(error)) throw error;
|
|
10551
|
+
if (!interactiveTerminal(deps) || !isCliSessionToken(auth.credential)) throw elevationCliError(error);
|
|
10552
|
+
deps.writeStderr("This operation needs elevation; confirming it's you...");
|
|
10553
|
+
await elevateSession(auth, deps, resolveLoginMode([], loginEnvironment(deps), loginPlatform(deps)));
|
|
10554
|
+
try {
|
|
10555
|
+
return await request(client);
|
|
10556
|
+
} catch (retryError) {
|
|
10557
|
+
if (isElevationRequired(retryError)) throw elevationCliError(retryError);
|
|
10558
|
+
throw retryError;
|
|
10559
|
+
}
|
|
10560
|
+
}
|
|
10561
|
+
}
|
|
10562
|
+
function isDeadSessionBody(body) {
|
|
10563
|
+
const type = bodyField(bodyField(body, "error"), "type");
|
|
10564
|
+
return type === "SESSION_EXPIRED" || type === "SESSION_REVOKED";
|
|
10565
|
+
}
|
|
10566
|
+
async function logoutCommand(argv, deps) {
|
|
10567
|
+
const options = parseOptions(argv, specFor("logout"));
|
|
10568
|
+
if (options.positionals.length > 0) throw new CliError("Usage: nouter-platform logout [--all]");
|
|
10569
|
+
const all = options.booleans.has("--all");
|
|
10570
|
+
let stored;
|
|
10571
|
+
try {
|
|
10572
|
+
stored = readConfig();
|
|
10573
|
+
} catch (error) {
|
|
10574
|
+
if (!(error instanceof ConfigStorageError)) throw error;
|
|
10575
|
+
clearConfig();
|
|
10576
|
+
throw error;
|
|
10577
|
+
}
|
|
10578
|
+
if (stored === null) {
|
|
10579
|
+
deps.writeStdout("No stored key.");
|
|
10580
|
+
return 0;
|
|
10581
|
+
}
|
|
10582
|
+
let failure = null;
|
|
10583
|
+
let otherSessionsNotRevoked = false;
|
|
10584
|
+
if (stored.baseUrl !== null && isCliSessionToken(stored.apiKey)) {
|
|
10585
|
+
const path = all ? "/v1/oma/cli/sessions" : "/v1/oma/cli/sessions/current";
|
|
10586
|
+
try {
|
|
10587
|
+
const baseUrl = normalizeBaseUrl(stored.baseUrl);
|
|
10588
|
+
const answer = await cliJsonRequest(deps, `${baseUrl}${path}`, { method: "DELETE", token: stored.apiKey });
|
|
10589
|
+
if (answer.status === 401 && isDeadSessionBody(answer.body)) {
|
|
10590
|
+
if (all) otherSessionsNotRevoked = true;
|
|
10591
|
+
} else if (answer.status < 200 || answer.status >= 300) {
|
|
10592
|
+
failure = `the server answered ${answer.status}`;
|
|
10593
|
+
}
|
|
10594
|
+
} catch (error) {
|
|
10595
|
+
failure = error instanceof CliError ? error.message : describeApiFailure(error);
|
|
10596
|
+
}
|
|
10597
|
+
}
|
|
10598
|
+
clearConfig();
|
|
10599
|
+
if (otherSessionsNotRevoked) {
|
|
10600
|
+
deps.writeStderr(
|
|
10601
|
+
"Your stored session had already ended, so other CLI sessions were not revoked. Revoke them in the console (Settings \u2192 Profile \u2192 CLI sessions)."
|
|
10602
|
+
);
|
|
10603
|
+
return 2;
|
|
10604
|
+
}
|
|
10605
|
+
if (failure !== null) {
|
|
10606
|
+
const expires = new Date(Date.now() + SESSION_TTL_MS).toISOString();
|
|
10607
|
+
deps.writeStderr(
|
|
10608
|
+
`The server session could not be revoked; it expires on ${expires} or revoke it with \`nouter-platform auth sessions revoke\`.`
|
|
10609
|
+
);
|
|
10610
|
+
return 2;
|
|
10611
|
+
}
|
|
10612
|
+
if (all && !isCliSessionToken(stored.apiKey)) {
|
|
10613
|
+
deps.writeStdout("Removed the stored machine key. Revoke it in the console when you no longer need it.");
|
|
10614
|
+
return 0;
|
|
10615
|
+
}
|
|
10616
|
+
deps.writeStdout(all ? "Logged out of every CLI session." : "Logged out.");
|
|
10617
|
+
return 0;
|
|
10618
|
+
}
|
|
10619
|
+
async function whoamiCommand(argv, deps) {
|
|
10620
|
+
const options = parseOptions(argv, specFor("whoami"));
|
|
10621
|
+
if (options.positionals.length > 0) throw new CliError("Usage: nouter-platform whoami [--json]");
|
|
10622
|
+
const auth = await resolveAuth(deps);
|
|
10623
|
+
const me = await fetchMe(auth, deps);
|
|
10624
|
+
const session = isCliSessionToken(auth.credential) ? await currentSession(auth, deps) : null;
|
|
10625
|
+
const sessionView = session === null ? null : {
|
|
10626
|
+
id: session.id,
|
|
10627
|
+
mode: session.mode,
|
|
10628
|
+
created_at: session.created_at,
|
|
10629
|
+
expires_at: session.created_at + SESSION_TTL_MS,
|
|
10630
|
+
last_used_at: session.last_used_at,
|
|
10631
|
+
idle_cutoff: (session.last_used_at ?? session.created_at) + SESSION_IDLE_MS,
|
|
10632
|
+
elevated_until: session.elevated_until
|
|
10633
|
+
};
|
|
10634
|
+
if (options.booleans.has("--json")) {
|
|
10635
|
+
deps.writeStdout(JSON.stringify({ ...me, installation: auth.baseUrl, session: sessionView }, null, 2));
|
|
10636
|
+
return 0;
|
|
10637
|
+
}
|
|
10638
|
+
printWhoami(me, deps);
|
|
10639
|
+
deps.writeStdout(`Installation: ${auth.baseUrl}`);
|
|
10640
|
+
if (sessionView !== null) {
|
|
10641
|
+
deps.writeStdout(`Session expires at: ${isoTime(sessionView.expires_at)}`);
|
|
10642
|
+
deps.writeStdout(`Idle cutoff: ${isoTime(sessionView.idle_cutoff)}`);
|
|
10643
|
+
deps.writeStdout(
|
|
10644
|
+
`Elevated until: ${sessionView.elevated_until === null ? "(not elevated)" : isoTime(sessionView.elevated_until)}`
|
|
10645
|
+
);
|
|
10646
|
+
}
|
|
10647
|
+
return 0;
|
|
9082
10648
|
}
|
|
9083
10649
|
function printWhoami(me, deps) {
|
|
9084
10650
|
deps.writeStdout(`Organization: ${organizationOf(me) ?? "(none)"}`);
|
|
@@ -9086,10 +10652,6 @@ function printWhoami(me, deps) {
|
|
|
9086
10652
|
const scopes = Array.isArray(me.scopes) ? me.scopes : [];
|
|
9087
10653
|
deps.writeStdout(`Scopes: ${scopes.length > 0 ? scopes.join(", ") : "(the server does not report scopes)"}`);
|
|
9088
10654
|
}
|
|
9089
|
-
function table(rows) {
|
|
9090
|
-
const widths = rows[0].map((_, column) => Math.max(...rows.map((row) => (row[column] ?? "").length)));
|
|
9091
|
-
return rows.map((row) => row.map((cell, column) => (cell ?? "").padEnd(widths[column])).join(" ").trimEnd()).join("\n");
|
|
9092
|
-
}
|
|
9093
10655
|
function modelOf(agent) {
|
|
9094
10656
|
const model = agent.model;
|
|
9095
10657
|
if (typeof model === "string") return model;
|
|
@@ -9185,8 +10747,265 @@ async function getEnvironment(id, deps) {
|
|
|
9185
10747
|
throw new CliError(`Could not read environment ${id}: ${describeApiFailure(error)}`);
|
|
9186
10748
|
}
|
|
9187
10749
|
}
|
|
10750
|
+
async function collectPages(fetchPage, params) {
|
|
10751
|
+
const items = [];
|
|
10752
|
+
const seen = /* @__PURE__ */ new Set();
|
|
10753
|
+
let page;
|
|
10754
|
+
for (; ; ) {
|
|
10755
|
+
if (page !== void 0) params.page = page;
|
|
10756
|
+
const result = await fetchPage(params);
|
|
10757
|
+
items.push(...result.data);
|
|
10758
|
+
const next = result.next_page;
|
|
10759
|
+
if (next === null || next === void 0) return items;
|
|
10760
|
+
if (seen.has(next)) {
|
|
10761
|
+
throw new CliError("The server returned the same page cursor twice; stopped to avoid an endless loop.");
|
|
10762
|
+
}
|
|
10763
|
+
seen.add(next);
|
|
10764
|
+
page = next;
|
|
10765
|
+
}
|
|
10766
|
+
}
|
|
10767
|
+
async function listSessions(args, deps) {
|
|
10768
|
+
const options = parseOptions(args, specFor("sessions list"));
|
|
10769
|
+
if (options.positionals.length > 0) {
|
|
10770
|
+
throw new CliError("Usage: nouter-platform sessions list [--agent <agent-id>] [--status <status>] ...");
|
|
10771
|
+
}
|
|
10772
|
+
const agentId = lastOption(options, "--agent");
|
|
10773
|
+
const agentVersionRaw = lastOption(options, "--agent-version");
|
|
10774
|
+
let agentVersion;
|
|
10775
|
+
if (agentVersionRaw !== void 0) {
|
|
10776
|
+
if (!/^\d+$/.test(agentVersionRaw) || Number(agentVersionRaw) < 1) {
|
|
10777
|
+
throw new CliError("The option --agent-version must be a positive integer.");
|
|
10778
|
+
}
|
|
10779
|
+
if (agentId === void 0) throw new CliError("The option --agent-version needs --agent.");
|
|
10780
|
+
agentVersion = Number(agentVersionRaw);
|
|
10781
|
+
}
|
|
10782
|
+
const statuses = splitList(options.values.get("--status"));
|
|
10783
|
+
for (const status of statuses) {
|
|
10784
|
+
if (!SESSION_STATUSES.includes(status)) {
|
|
10785
|
+
throw new CliError(`The option --status must be one of ${SESSION_STATUSES.join(", ")}.`);
|
|
10786
|
+
}
|
|
10787
|
+
}
|
|
10788
|
+
const sinceRaw = lastOption(options, "--since");
|
|
10789
|
+
const since = sinceRaw === void 0 ? void 0 : normalizeInstant(sinceRaw, "start");
|
|
10790
|
+
if (sinceRaw !== void 0 && since === null) {
|
|
10791
|
+
throw new CliError("The option --since must be YYYY-MM-DD or RFC 3339.");
|
|
10792
|
+
}
|
|
10793
|
+
const untilRaw = lastOption(options, "--until");
|
|
10794
|
+
const until = untilRaw === void 0 ? void 0 : normalizeInstant(untilRaw, "end");
|
|
10795
|
+
if (untilRaw !== void 0 && until === null) {
|
|
10796
|
+
throw new CliError("The option --until must be YYYY-MM-DD or RFC 3339.");
|
|
10797
|
+
}
|
|
10798
|
+
const order = lastOption(options, "--order");
|
|
10799
|
+
if (order !== void 0 && order !== "asc" && order !== "desc") {
|
|
10800
|
+
throw new CliError("The option --order must be asc or desc.");
|
|
10801
|
+
}
|
|
10802
|
+
const params = { limit: 100 };
|
|
10803
|
+
if (agentId !== void 0) params.agent_id = agentId;
|
|
10804
|
+
if (agentVersion !== void 0) params.agent_version = agentVersion;
|
|
10805
|
+
const userProfileId = lastOption(options, "--user-profile");
|
|
10806
|
+
if (userProfileId !== void 0) params.user_profile_id = userProfileId;
|
|
10807
|
+
if (statuses.length > 0) params.statuses = statuses;
|
|
10808
|
+
if (since !== void 0 && since !== null) params["created_at[gte]"] = since;
|
|
10809
|
+
if (until !== void 0 && until !== null) params["created_at[lte]"] = until;
|
|
10810
|
+
if (order !== void 0) params.order = order;
|
|
10811
|
+
if (options.booleans.has("--include-archived")) params.include_archived = true;
|
|
10812
|
+
const auth = await resolveAuth(deps);
|
|
10813
|
+
try {
|
|
10814
|
+
const client = clientFor(auth, deps);
|
|
10815
|
+
const sessions = await collectPages(
|
|
10816
|
+
(query) => client.beta.sessions.list(query),
|
|
10817
|
+
params
|
|
10818
|
+
);
|
|
10819
|
+
if (options.booleans.has("--json")) {
|
|
10820
|
+
deps.writeStdout(JSON.stringify(sessions, null, 2));
|
|
10821
|
+
return 0;
|
|
10822
|
+
}
|
|
10823
|
+
if (sessions.length === 0) {
|
|
10824
|
+
deps.writeStdout("No sessions.");
|
|
10825
|
+
return 0;
|
|
10826
|
+
}
|
|
10827
|
+
deps.writeStdout(
|
|
10828
|
+
table([["ID", "STATUS", "AGENT", "USER", "CREATED", "COST"], ...sessions.map((session) => sessionRow(session))])
|
|
10829
|
+
);
|
|
10830
|
+
return 0;
|
|
10831
|
+
} catch (error) {
|
|
10832
|
+
if (error instanceof CliError) throw error;
|
|
10833
|
+
throw new CliError(`Could not list sessions: ${describeApiFailure(error)}`);
|
|
10834
|
+
}
|
|
10835
|
+
}
|
|
10836
|
+
async function getSession(args, deps) {
|
|
10837
|
+
const options = parseOptions(args, specFor("sessions get"));
|
|
10838
|
+
const id = options.positionals[0];
|
|
10839
|
+
if (id === void 0 || options.positionals.length > 1) {
|
|
10840
|
+
throw new CliError("Usage: nouter-platform sessions get <session-id> [--json]");
|
|
10841
|
+
}
|
|
10842
|
+
const auth = await resolveAuth(deps);
|
|
10843
|
+
try {
|
|
10844
|
+
const session = await clientFor(auth, deps).beta.sessions.retrieve(id);
|
|
10845
|
+
if (options.booleans.has("--json")) {
|
|
10846
|
+
deps.writeStdout(JSON.stringify(session, null, 2));
|
|
10847
|
+
return 0;
|
|
10848
|
+
}
|
|
10849
|
+
for (const line of sessionDetail(session)) deps.writeStdout(line);
|
|
10850
|
+
return 0;
|
|
10851
|
+
} catch (error) {
|
|
10852
|
+
if (error instanceof CliError) throw error;
|
|
10853
|
+
throw new CliError(`Could not read session ${id}: ${describeApiFailure(error)}`);
|
|
10854
|
+
}
|
|
10855
|
+
}
|
|
10856
|
+
async function listSessionEvents(args, deps) {
|
|
10857
|
+
const options = parseOptions(args, specFor("sessions events"));
|
|
10858
|
+
const id = options.positionals[0];
|
|
10859
|
+
if (id === void 0 || options.positionals.length > 1) {
|
|
10860
|
+
throw new CliError("Usage: nouter-platform sessions events <session-id> [--type <event-type>] ...");
|
|
10861
|
+
}
|
|
10862
|
+
const types = splitList(options.values.get("--type"));
|
|
10863
|
+
const sinceRaw = lastOption(options, "--since");
|
|
10864
|
+
const since = sinceRaw === void 0 ? void 0 : normalizeInstant(sinceRaw, "start");
|
|
10865
|
+
if (sinceRaw !== void 0 && since === null) {
|
|
10866
|
+
throw new CliError("The option --since must be YYYY-MM-DD or RFC 3339.");
|
|
10867
|
+
}
|
|
10868
|
+
const untilRaw = lastOption(options, "--until");
|
|
10869
|
+
const until = untilRaw === void 0 ? void 0 : normalizeInstant(untilRaw, "end");
|
|
10870
|
+
if (untilRaw !== void 0 && until === null) {
|
|
10871
|
+
throw new CliError("The option --until must be YYYY-MM-DD or RFC 3339.");
|
|
10872
|
+
}
|
|
10873
|
+
const order = lastOption(options, "--order") ?? "asc";
|
|
10874
|
+
if (order !== "asc" && order !== "desc") {
|
|
10875
|
+
throw new CliError("The option --order must be asc or desc.");
|
|
10876
|
+
}
|
|
10877
|
+
const params = { limit: 100, order };
|
|
10878
|
+
if (types.length > 0) params.types = types;
|
|
10879
|
+
if (since !== void 0 && since !== null) params["created_at[gte]"] = since;
|
|
10880
|
+
if (until !== void 0 && until !== null) params["created_at[lte]"] = until;
|
|
10881
|
+
const auth = await resolveAuth(deps);
|
|
10882
|
+
try {
|
|
10883
|
+
const client = clientFor(auth, deps);
|
|
10884
|
+
const events = await collectPages(
|
|
10885
|
+
(query) => client.beta.sessions.events.list(id, query),
|
|
10886
|
+
params
|
|
10887
|
+
);
|
|
10888
|
+
if (options.booleans.has("--json")) {
|
|
10889
|
+
deps.writeStdout(JSON.stringify(events, null, 2));
|
|
10890
|
+
return 0;
|
|
10891
|
+
}
|
|
10892
|
+
if (events.length === 0) {
|
|
10893
|
+
deps.writeStdout("No events.");
|
|
10894
|
+
return 0;
|
|
10895
|
+
}
|
|
10896
|
+
deps.writeStdout(
|
|
10897
|
+
table([["PROCESSED_AT", "TYPE", "ID", "SUMMARY"], ...events.map((event) => eventRow(event))])
|
|
10898
|
+
);
|
|
10899
|
+
return 0;
|
|
10900
|
+
} catch (error) {
|
|
10901
|
+
if (error instanceof CliError) throw error;
|
|
10902
|
+
throw new CliError(`Could not list the events of session ${id}: ${describeApiFailure(error)}`);
|
|
10903
|
+
}
|
|
10904
|
+
}
|
|
10905
|
+
async function sessionsCommand(argv, deps) {
|
|
10906
|
+
const [subcommand, ...args] = argv;
|
|
10907
|
+
if (subcommand === "list") return await listSessions(args, deps);
|
|
10908
|
+
if (subcommand === "get") return await getSession(args, deps);
|
|
10909
|
+
if (subcommand === "events") return await listSessionEvents(args, deps);
|
|
10910
|
+
return usageError("sessions list|get <session-id>|events <session-id>", deps);
|
|
10911
|
+
}
|
|
10912
|
+
async function usageCommand(argv, deps) {
|
|
10913
|
+
const options = parseOptions(argv, specFor("usage"));
|
|
10914
|
+
if (options.positionals.length > 0) {
|
|
10915
|
+
throw new CliError("Usage: nouter-platform usage [--days 7|30|90] [--group-by <dimension>] [--json]");
|
|
10916
|
+
}
|
|
10917
|
+
const daysRaw = lastOption(options, "--days");
|
|
10918
|
+
if (daysRaw !== void 0 && daysRaw !== "7" && daysRaw !== "30" && daysRaw !== "90") {
|
|
10919
|
+
throw new CliError("The option --days must be 7, 30 or 90.");
|
|
10920
|
+
}
|
|
10921
|
+
const sinceRaw = lastOption(options, "--since");
|
|
10922
|
+
const untilRaw = lastOption(options, "--until");
|
|
10923
|
+
const hasRange = sinceRaw !== void 0 || untilRaw !== void 0;
|
|
10924
|
+
if (daysRaw !== void 0 && hasRange) {
|
|
10925
|
+
throw new CliError("Use --days or --since/--until, not both.");
|
|
10926
|
+
}
|
|
10927
|
+
const since = sinceRaw === void 0 ? void 0 : normalizeInstant(sinceRaw, "start");
|
|
10928
|
+
if (since === null) {
|
|
10929
|
+
throw new CliError("The option --since must be YYYY-MM-DD or RFC 3339.");
|
|
10930
|
+
}
|
|
10931
|
+
const until = untilRaw === void 0 ? void 0 : normalizeInstant(untilRaw, "end");
|
|
10932
|
+
if (until === null) {
|
|
10933
|
+
throw new CliError("The option --until must be YYYY-MM-DD or RFC 3339.");
|
|
10934
|
+
}
|
|
10935
|
+
if (since !== void 0 && until !== void 0 && Date.parse(since) > Date.parse(until)) {
|
|
10936
|
+
throw new CliError("The option --since must not be after --until.");
|
|
10937
|
+
}
|
|
10938
|
+
const groupBy = splitList(options.values.get("--group-by"));
|
|
10939
|
+
const dimensions = groupBy.length === 0 ? ["day"] : groupBy;
|
|
10940
|
+
for (const dimension of dimensions) {
|
|
10941
|
+
if (!USAGE_GROUP_BY.includes(dimension)) {
|
|
10942
|
+
throw new CliError(`The option --group-by must be one of ${USAGE_GROUP_BY.join(", ")}.`);
|
|
10943
|
+
}
|
|
10944
|
+
}
|
|
10945
|
+
if (dimensions.length > 5) {
|
|
10946
|
+
throw new CliError("The option --group-by takes at most 5 dimensions.");
|
|
10947
|
+
}
|
|
10948
|
+
const params = {
|
|
10949
|
+
group_by: dimensions,
|
|
10950
|
+
limit: integerOption(options, "--limit", 1, 1e4) ?? 1e3
|
|
10951
|
+
};
|
|
10952
|
+
if (hasRange) {
|
|
10953
|
+
if (sinceRaw !== void 0) params.starting_at = sinceRaw;
|
|
10954
|
+
if (untilRaw !== void 0) params.ending_at = untilRaw;
|
|
10955
|
+
} else {
|
|
10956
|
+
params.days = daysRaw ?? "30";
|
|
10957
|
+
}
|
|
10958
|
+
const userProfileId = lastOption(options, "--user-profile");
|
|
10959
|
+
if (userProfileId !== void 0) params.user_profile_id = userProfileId;
|
|
10960
|
+
const page = lastOption(options, "--page");
|
|
10961
|
+
if (page !== void 0) params.page = page;
|
|
10962
|
+
const auth = await resolveAuth(deps);
|
|
10963
|
+
try {
|
|
10964
|
+
const report = await clientFor(auth, deps).platform.usage.list(params);
|
|
10965
|
+
const view = report;
|
|
10966
|
+
if (options.booleans.has("--json")) {
|
|
10967
|
+
deps.writeStdout(JSON.stringify(report, null, 2));
|
|
10968
|
+
} else {
|
|
10969
|
+
deps.writeStdout(usageTable(view));
|
|
10970
|
+
if (view.rows.some((row) => row.cost_micros !== null && row.unpriced_requests > 0)) {
|
|
10971
|
+
deps.writeStdout(`* partial: ${unpricedTotal(view)} requests without a price.`);
|
|
10972
|
+
}
|
|
10973
|
+
}
|
|
10974
|
+
if (view.next_page !== void 0 && view.next_page !== null) {
|
|
10975
|
+
deps.writeStderr(`Next page: ${nextPageCommand(params, view.next_page)}`);
|
|
10976
|
+
}
|
|
10977
|
+
return 0;
|
|
10978
|
+
} catch (error) {
|
|
10979
|
+
if (error instanceof CliError) throw error;
|
|
10980
|
+
throw new CliError(`Could not read the usage: ${describeApiFailure(error)}`);
|
|
10981
|
+
}
|
|
10982
|
+
}
|
|
10983
|
+
function nextPageCommand(params, cursor) {
|
|
10984
|
+
const parts = ["nouter-platform", "usage"];
|
|
10985
|
+
const groupBy = params.group_by ?? [];
|
|
10986
|
+
if (groupBy.length > 0 && !(groupBy.length === 1 && groupBy[0] === "day")) {
|
|
10987
|
+
parts.push("--group-by", groupBy.join(","));
|
|
10988
|
+
}
|
|
10989
|
+
const hasRange = params.starting_at !== void 0 || params.ending_at !== void 0;
|
|
10990
|
+
if (hasRange) {
|
|
10991
|
+
if (params.starting_at !== void 0) parts.push("--since", shellQuote(params.starting_at));
|
|
10992
|
+
if (params.ending_at !== void 0) parts.push("--until", shellQuote(params.ending_at));
|
|
10993
|
+
} else if (params.days !== void 0 && params.days !== "30") {
|
|
10994
|
+
parts.push("--days", params.days);
|
|
10995
|
+
}
|
|
10996
|
+
if (params.user_profile_id !== void 0) {
|
|
10997
|
+
parts.push("--user-profile", shellQuote(params.user_profile_id));
|
|
10998
|
+
}
|
|
10999
|
+
if (params.limit !== void 0 && params.limit !== 1e3) parts.push("--limit", String(params.limit));
|
|
11000
|
+
parts.push("--page", shellQuote(cursor));
|
|
11001
|
+
return parts.join(" ");
|
|
11002
|
+
}
|
|
11003
|
+
function shellQuote(value) {
|
|
11004
|
+
if (/^[A-Za-z0-9._~:@%+=,/-]+$/.test(value)) return value;
|
|
11005
|
+
return `'${value.replace(/'/g, "'\\''")}'`;
|
|
11006
|
+
}
|
|
9188
11007
|
var MANUAL_FLAGS = {
|
|
9189
|
-
login: ["--api-key", "--browser"],
|
|
11008
|
+
login: ["--api-key", "--browser", "--paste"],
|
|
9190
11009
|
"agents list": ["--json"],
|
|
9191
11010
|
"agents get": [],
|
|
9192
11011
|
"environments list": ["--json"],
|
|
@@ -9338,15 +11157,15 @@ async function serviceAccountsCommand(argv, deps) {
|
|
|
9338
11157
|
}
|
|
9339
11158
|
const auth = await resolveAuth(deps);
|
|
9340
11159
|
try {
|
|
9341
|
-
const account = await
|
|
11160
|
+
const account = await elevatedRequest(auth, deps, (client) => client.platform.request({
|
|
9342
11161
|
method: "post",
|
|
9343
11162
|
path: `/v1/oma/service_accounts/${id}/archive`
|
|
9344
|
-
});
|
|
11163
|
+
}));
|
|
9345
11164
|
deps.writeStdout(`Archived service account ${account.id}.`);
|
|
9346
11165
|
return 0;
|
|
9347
11166
|
} catch (error) {
|
|
9348
11167
|
if (error instanceof CliError) throw error;
|
|
9349
|
-
throw
|
|
11168
|
+
throw apiFailure(error, `Could not archive service account ${id}`);
|
|
9350
11169
|
}
|
|
9351
11170
|
}
|
|
9352
11171
|
return usageError("service-accounts list|create|archive", deps);
|
|
@@ -9429,15 +11248,15 @@ async function federationIssuersCommand(argv, deps) {
|
|
|
9429
11248
|
}
|
|
9430
11249
|
const auth = await resolveAuth(deps);
|
|
9431
11250
|
try {
|
|
9432
|
-
const issuer = await
|
|
11251
|
+
const issuer = await elevatedRequest(auth, deps, (client) => client.platform.request({
|
|
9433
11252
|
method: "post",
|
|
9434
11253
|
path: `/v1/oma/federation_issuers/${id}/archive`
|
|
9435
|
-
});
|
|
11254
|
+
}));
|
|
9436
11255
|
deps.writeStdout(`Archived federation issuer ${issuer.id}.`);
|
|
9437
11256
|
return 0;
|
|
9438
11257
|
} catch (error) {
|
|
9439
11258
|
if (error instanceof CliError) throw error;
|
|
9440
|
-
throw
|
|
11259
|
+
throw apiFailure(error, `Could not archive federation issuer ${id}`);
|
|
9441
11260
|
}
|
|
9442
11261
|
}
|
|
9443
11262
|
return usageError("federation issuers list|create|archive", deps);
|
|
@@ -9552,15 +11371,15 @@ async function federationRulesCommand(argv, deps) {
|
|
|
9552
11371
|
}
|
|
9553
11372
|
const auth = await resolveAuth(deps);
|
|
9554
11373
|
try {
|
|
9555
|
-
const rule = await
|
|
11374
|
+
const rule = await elevatedRequest(auth, deps, (client) => client.platform.request({
|
|
9556
11375
|
method: "post",
|
|
9557
11376
|
path: `/v1/oma/federation_rules/${id}/archive`
|
|
9558
|
-
});
|
|
11377
|
+
}));
|
|
9559
11378
|
deps.writeStdout(`Archived federation rule ${rule.id}.`);
|
|
9560
11379
|
return 0;
|
|
9561
11380
|
} catch (error) {
|
|
9562
11381
|
if (error instanceof CliError) throw error;
|
|
9563
|
-
throw
|
|
11382
|
+
throw apiFailure(error, `Could not archive federation rule ${id}`);
|
|
9564
11383
|
}
|
|
9565
11384
|
}
|
|
9566
11385
|
return usageError("federation rules list|create|archive", deps);
|
|
@@ -9574,7 +11393,7 @@ async function federationTokenCommand(argv, deps) {
|
|
|
9574
11393
|
"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
11394
|
);
|
|
9576
11395
|
}
|
|
9577
|
-
const stored = readConfig(
|
|
11396
|
+
const stored = readConfig();
|
|
9578
11397
|
const baseUrl = requireBaseUrl(stored);
|
|
9579
11398
|
const token = await federationProviderFor(baseUrl, settings, deps).getToken().catch(federationFailure);
|
|
9580
11399
|
if (options.booleans.has("--json")) {
|
|
@@ -9596,7 +11415,7 @@ async function federationTokenCommand(argv, deps) {
|
|
|
9596
11415
|
return 0;
|
|
9597
11416
|
}
|
|
9598
11417
|
function authStatus(deps) {
|
|
9599
|
-
const stored = readConfig(
|
|
11418
|
+
const stored = readConfig();
|
|
9600
11419
|
const envKey = environmentApiKey();
|
|
9601
11420
|
const rule = process.env.NOUTER_PLATFORM_FEDERATION_RULE_ID;
|
|
9602
11421
|
const organization = process.env.NOUTER_PLATFORM_ORGANIZATION_ID;
|
|
@@ -9716,16 +11535,20 @@ function printHelp(deps) {
|
|
|
9716
11535
|
"Usage: nouter-platform <command> [options]",
|
|
9717
11536
|
"",
|
|
9718
11537
|
"Commands:",
|
|
9719
|
-
" login
|
|
9720
|
-
" logout
|
|
9721
|
-
" whoami Show the organization, role and scopes",
|
|
9722
|
-
" auth status
|
|
11538
|
+
" login Log in through the browser or a pasted code, or store an API key (--api-key)",
|
|
11539
|
+
" logout Revoke the CLI session and remove the stored credential (--all: every session)",
|
|
11540
|
+
" whoami Show the organization, role and scopes (--json)",
|
|
11541
|
+
" auth status | sessions list|revoke <session-id>",
|
|
9723
11542
|
" version Show the CLI version and the SDK version it ships",
|
|
9724
11543
|
" agents list | get <agent-id>",
|
|
9725
11544
|
" environments list | get <environment-id>",
|
|
11545
|
+
" sessions list | get <session-id> | events <session-id>",
|
|
11546
|
+
" usage Show the usage and the cost by day, model, agent, person or session",
|
|
9726
11547
|
" service-accounts list | create | archive",
|
|
9727
11548
|
" federation issuers list|create|archive | rules list|create|archive | token",
|
|
11549
|
+
" elevate Confirm it's you for two hours (--browser | --paste)",
|
|
9728
11550
|
" apply Apply agents and environments from files",
|
|
11551
|
+
...feedbackHelpLines(),
|
|
9729
11552
|
"",
|
|
9730
11553
|
"Options:",
|
|
9731
11554
|
" -h, --help Show this help",
|
|
@@ -9745,7 +11568,7 @@ function printHelp(deps) {
|
|
|
9745
11568
|
}
|
|
9746
11569
|
function manifestAt(path) {
|
|
9747
11570
|
try {
|
|
9748
|
-
return JSON.parse(
|
|
11571
|
+
return JSON.parse(readFileSync4(path, "utf8"));
|
|
9749
11572
|
} catch {
|
|
9750
11573
|
return null;
|
|
9751
11574
|
}
|
|
@@ -9761,7 +11584,7 @@ function sdkVersion() {
|
|
|
9761
11584
|
return "unknown";
|
|
9762
11585
|
}
|
|
9763
11586
|
for (let depth = 0; depth < 8; depth += 1) {
|
|
9764
|
-
const manifest = manifestAt(
|
|
11587
|
+
const manifest = manifestAt(join3(directory, "package.json"));
|
|
9765
11588
|
if (manifest?.name === "@nouter/platform" && typeof manifest.version === "string") return manifest.version;
|
|
9766
11589
|
const parent = dirname(directory);
|
|
9767
11590
|
if (parent === directory) break;
|
|
@@ -9790,13 +11613,11 @@ async function dispatch(argv, deps) {
|
|
|
9790
11613
|
case "login":
|
|
9791
11614
|
return await login(rest, deps);
|
|
9792
11615
|
case "logout":
|
|
9793
|
-
|
|
9794
|
-
|
|
9795
|
-
|
|
9796
|
-
|
|
9797
|
-
|
|
9798
|
-
return 0;
|
|
9799
|
-
}
|
|
11616
|
+
return await logoutCommand(rest, deps);
|
|
11617
|
+
case "whoami":
|
|
11618
|
+
return await whoamiCommand(rest, deps);
|
|
11619
|
+
case "elevate":
|
|
11620
|
+
return await elevateCommand(rest, deps);
|
|
9800
11621
|
case "agents": {
|
|
9801
11622
|
const [subcommand, ...args] = rest;
|
|
9802
11623
|
const jsonFlag = MANUAL_FLAGS["agents list"][0];
|
|
@@ -9815,8 +11636,13 @@ async function dispatch(argv, deps) {
|
|
|
9815
11636
|
}
|
|
9816
11637
|
case "auth": {
|
|
9817
11638
|
if (rest.length === 1 && rest[0] === "status") return authStatus(deps);
|
|
9818
|
-
|
|
11639
|
+
if (rest[0] === "sessions") return await authSessionsCommand(rest.slice(1), deps);
|
|
11640
|
+
return usageError("auth status | sessions list|revoke <session-id>", deps);
|
|
9819
11641
|
}
|
|
11642
|
+
case "sessions":
|
|
11643
|
+
return await sessionsCommand(rest, deps);
|
|
11644
|
+
case "usage":
|
|
11645
|
+
return await usageCommand(rest, deps);
|
|
9820
11646
|
case "version":
|
|
9821
11647
|
if (rest.length > 0) return usageError("version", deps);
|
|
9822
11648
|
deps.writeStdout(versionLine());
|
|
@@ -9832,26 +11658,78 @@ async function dispatch(argv, deps) {
|
|
|
9832
11658
|
}
|
|
9833
11659
|
case "apply":
|
|
9834
11660
|
return await applyCommand(rest, deps);
|
|
11661
|
+
case "feedback":
|
|
11662
|
+
return await feedbackCommand(rest, {
|
|
11663
|
+
CliError,
|
|
11664
|
+
resolveAuth: () => resolveAuth(deps),
|
|
11665
|
+
userAgent: cliUserAgent(),
|
|
11666
|
+
writeStdout: deps.writeStdout,
|
|
11667
|
+
writeStderr: deps.writeStderr,
|
|
11668
|
+
fetch: deps.fetch,
|
|
11669
|
+
requestTimeoutMs: deps.requestTimeoutMs
|
|
11670
|
+
});
|
|
9835
11671
|
default:
|
|
9836
11672
|
deps.writeStderr(`Unknown command: ${command}`);
|
|
9837
11673
|
deps.writeStderr("Run `nouter-platform --help` for the command list.");
|
|
9838
11674
|
return 1;
|
|
9839
11675
|
}
|
|
9840
11676
|
}
|
|
11677
|
+
async function readAllStdin() {
|
|
11678
|
+
const chunks = [];
|
|
11679
|
+
for await (const chunk of process.stdin) chunks.push(Buffer.from(chunk));
|
|
11680
|
+
return Buffer.concat(chunks).toString("utf8");
|
|
11681
|
+
}
|
|
11682
|
+
async function readSecretFromTty() {
|
|
11683
|
+
const stdin = process.stdin;
|
|
11684
|
+
if (!stdin.isTTY) return await readAllStdin();
|
|
11685
|
+
return await new Promise((resolve) => {
|
|
11686
|
+
const wasRaw = Boolean(stdin.isRaw);
|
|
11687
|
+
stdin.setRawMode(true);
|
|
11688
|
+
stdin.resume();
|
|
11689
|
+
stdin.setEncoding("utf8");
|
|
11690
|
+
let value = "";
|
|
11691
|
+
const settle = (result) => {
|
|
11692
|
+
stdin.setRawMode(wasRaw);
|
|
11693
|
+
stdin.pause();
|
|
11694
|
+
stdin.removeListener("data", onData);
|
|
11695
|
+
process.stdout.write("\n");
|
|
11696
|
+
resolve(result);
|
|
11697
|
+
};
|
|
11698
|
+
const onData = (chunk) => {
|
|
11699
|
+
for (const char of chunk) {
|
|
11700
|
+
if (char === "\r" || char === "\n") {
|
|
11701
|
+
settle(value);
|
|
11702
|
+
return;
|
|
11703
|
+
}
|
|
11704
|
+
if (char === "") {
|
|
11705
|
+
stdin.setRawMode(wasRaw);
|
|
11706
|
+
stdin.pause();
|
|
11707
|
+
process.exit(130);
|
|
11708
|
+
}
|
|
11709
|
+
if (char === "\x7F") {
|
|
11710
|
+
value = value.slice(0, -1);
|
|
11711
|
+
continue;
|
|
11712
|
+
}
|
|
11713
|
+
value += char;
|
|
11714
|
+
}
|
|
11715
|
+
};
|
|
11716
|
+
stdin.on("data", onData);
|
|
11717
|
+
});
|
|
11718
|
+
}
|
|
9841
11719
|
function defaultDependencies() {
|
|
9842
11720
|
return {
|
|
9843
11721
|
writeStdout: (text) => process.stdout.write(`${text}
|
|
9844
11722
|
`),
|
|
9845
11723
|
writeStderr: (text) => process.stderr.write(`${text}
|
|
9846
11724
|
`),
|
|
9847
|
-
readStdin:
|
|
9848
|
-
|
|
9849
|
-
for await (const chunk of process.stdin) chunks.push(Buffer.from(chunk));
|
|
9850
|
-
return Buffer.concat(chunks).toString("utf8");
|
|
9851
|
-
},
|
|
11725
|
+
readStdin: readAllStdin,
|
|
11726
|
+
readSecret: readSecretFromTty,
|
|
9852
11727
|
fetch: globalThis.fetch,
|
|
9853
11728
|
openBrowser: openInBrowser,
|
|
9854
|
-
requestTimeoutMs: REQUEST_TIMEOUT_MS
|
|
11729
|
+
requestTimeoutMs: REQUEST_TIMEOUT_MS,
|
|
11730
|
+
env: process.env,
|
|
11731
|
+
platform: process.platform,
|
|
11732
|
+
isInteractive: () => Boolean(process.stdin.isTTY && process.stdout.isTTY)
|
|
9855
11733
|
};
|
|
9856
11734
|
}
|
|
9857
11735
|
function openInBrowser(url, options = {}) {
|
|
@@ -9891,19 +11769,33 @@ function scrubArgv() {
|
|
|
9891
11769
|
}
|
|
9892
11770
|
async function main(argv, overrides = {}) {
|
|
9893
11771
|
const deps = { ...defaultDependencies(), ...overrides };
|
|
11772
|
+
const json = argv.includes("--json");
|
|
11773
|
+
const reportError = (message, code) => {
|
|
11774
|
+
if (json) {
|
|
11775
|
+
const envelope = { error: { message } };
|
|
11776
|
+
if (code !== void 0) envelope.error.code = code;
|
|
11777
|
+
deps.writeStderr(JSON.stringify(envelope));
|
|
11778
|
+
} else {
|
|
11779
|
+
deps.writeStderr(message);
|
|
11780
|
+
}
|
|
11781
|
+
};
|
|
9894
11782
|
scrubArgv();
|
|
9895
11783
|
try {
|
|
9896
11784
|
return await dispatch(argv, deps);
|
|
9897
11785
|
} catch (error) {
|
|
9898
11786
|
if (error instanceof LoginAccessDeniedError) {
|
|
9899
|
-
|
|
11787
|
+
reportError(error.message);
|
|
9900
11788
|
return 1;
|
|
9901
11789
|
}
|
|
11790
|
+
if (error instanceof ConfigStorageError) {
|
|
11791
|
+
reportError(error.message, error.code);
|
|
11792
|
+
return error.exitCode;
|
|
11793
|
+
}
|
|
9902
11794
|
if (error instanceof CliError) {
|
|
9903
|
-
|
|
11795
|
+
reportError(error.message, error.code);
|
|
9904
11796
|
return error.exitCode;
|
|
9905
11797
|
}
|
|
9906
|
-
|
|
11798
|
+
reportError(error.message || "Unexpected error.");
|
|
9907
11799
|
return 1;
|
|
9908
11800
|
}
|
|
9909
11801
|
}
|