evalctl 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +149 -2
- package/dist/cli.d.ts +13 -0
- package/dist/cli.js +294 -0
- package/dist/client.d.ts +53 -0
- package/dist/client.js +269 -0
- package/dist/commands/auth.d.ts +6 -0
- package/dist/commands/auth.js +341 -0
- package/dist/commands/common.d.ts +17 -0
- package/dist/commands/common.js +53 -0
- package/dist/commands/export.d.ts +2 -0
- package/dist/commands/export.js +54 -0
- package/dist/commands/index.d.ts +3 -0
- package/dist/commands/index.js +10 -0
- package/dist/commands/info.d.ts +2 -0
- package/dist/commands/info.js +208 -0
- package/dist/commands/runs.d.ts +2 -0
- package/dist/commands/runs.js +325 -0
- package/dist/commands/scenarios.d.ts +2 -0
- package/dist/commands/scenarios.js +585 -0
- package/dist/commands/screens.d.ts +2 -0
- package/dist/commands/screens.js +139 -0
- package/dist/config.d.ts +52 -0
- package/dist/config.js +281 -0
- package/dist/context.d.ts +64 -0
- package/dist/context.js +1 -0
- package/dist/diff.d.ts +7 -0
- package/dist/diff.js +122 -0
- package/dist/errors.d.ts +22 -0
- package/dist/errors.js +35 -0
- package/dist/fsutil.d.ts +34 -0
- package/dist/fsutil.js +245 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +18 -0
- package/dist/output.d.ts +38 -0
- package/dist/output.js +156 -0
- package/dist/prompt.d.ts +29 -0
- package/dist/prompt.js +195 -0
- package/dist/sidecar.d.ts +39 -0
- package/dist/sidecar.js +138 -0
- package/dist/state.d.ts +14 -0
- package/dist/state.js +48 -0
- package/dist/util.d.ts +21 -0
- package/dist/util.js +77 -0
- package/dist/version.d.ts +2 -0
- package/dist/version.js +12 -0
- package/dist/yaml-text.d.ts +15 -0
- package/dist/yaml-text.js +103 -0
- package/package.json +62 -4
package/dist/client.js
ADDED
|
@@ -0,0 +1,269 @@
|
|
|
1
|
+
import { setTimeout as sleep } from "node:timers/promises";
|
|
2
|
+
import { CliError, EXIT_AUTH, EXIT_RUNTIME, exitCodeForStatus } from "./errors.js";
|
|
3
|
+
import { VERSION } from "./version.js";
|
|
4
|
+
import { cellText, isObject, oneLine, truncate } from "./util.js";
|
|
5
|
+
export const REQUEST_TIMEOUT_MS = 30_000;
|
|
6
|
+
export const MAX_RESPONSE_BYTES = 64 * 1024 * 1024;
|
|
7
|
+
export const MAX_RATE_LIMIT_RETRIES = 2;
|
|
8
|
+
export const MAX_RETRY_SLEEP_MS = 5_000;
|
|
9
|
+
// Headers a browser sends to say which page a request came from. This client is not a page, so a caller can
|
|
10
|
+
// never add them by accident.
|
|
11
|
+
const FORBIDDEN_REQUEST_HEADERS = /^(?:origin|sec-fetch-.*)$/i;
|
|
12
|
+
function defaultSleep(ms, signal) {
|
|
13
|
+
return sleep(ms, undefined, { signal });
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Milliseconds to wait for a numeric `Retry-After` (seconds); null when the header is absent or not a number, and also
|
|
17
|
+
* when the wait is longer than `MAX_RETRY_SLEEP_MS`: a lockout or a per-minute limit would still answer 429 after a short
|
|
18
|
+
* sleep, so retrying only adds delay. The caller gets the 429 at once and can read the wait in its message.
|
|
19
|
+
*/
|
|
20
|
+
export function retryDelayMs(header) {
|
|
21
|
+
if (header === undefined || !/^\s*\d+(?:\.\d+)?\s*$/.test(header)) {
|
|
22
|
+
return null;
|
|
23
|
+
}
|
|
24
|
+
const ms = Number(header) * 1000;
|
|
25
|
+
return ms > MAX_RETRY_SLEEP_MS ? null : ms;
|
|
26
|
+
}
|
|
27
|
+
/** The whole seconds a numeric `Retry-After` asks for, or null; shown to the person when a 429 is not retried. */
|
|
28
|
+
function retryAfterSeconds(header) {
|
|
29
|
+
if (header === undefined || !/^\s*\d+(?:\.\d+)?\s*$/.test(header)) {
|
|
30
|
+
return null;
|
|
31
|
+
}
|
|
32
|
+
const seconds = Math.ceil(Number(header));
|
|
33
|
+
return Number.isSafeInteger(seconds) ? seconds : null;
|
|
34
|
+
}
|
|
35
|
+
/** A short, safe description of a body that is not JSON: never the raw page, at most one trimmed line. */
|
|
36
|
+
export function describeNonJson(text, contentType) {
|
|
37
|
+
const looksHtml = /html/i.test(contentType) || /^\s*<(?:!doctype|html|head|body)/i.test(text);
|
|
38
|
+
let snippet;
|
|
39
|
+
if (looksHtml) {
|
|
40
|
+
const heading = /<title[^>]*>([\s\S]*?)<\/title>/i.exec(text) ?? /<h1[^>]*>([\s\S]*?)<\/h1>/i.exec(text);
|
|
41
|
+
snippet = heading?.[1] ?? text.replace(/<(script|style)[\s\S]*?<\/\1>/gi, " ");
|
|
42
|
+
}
|
|
43
|
+
else {
|
|
44
|
+
snippet = text;
|
|
45
|
+
}
|
|
46
|
+
const plain = oneLine(snippet.replace(/<[^>]*>/g, " "))
|
|
47
|
+
.replace(/ /g, " ")
|
|
48
|
+
.replace(/</g, "<")
|
|
49
|
+
.replace(/>/g, ">")
|
|
50
|
+
.replace(/"/g, '"')
|
|
51
|
+
.replace(/'/g, "'")
|
|
52
|
+
.replace(/&/g, "&")
|
|
53
|
+
.replace(/\s+/g, " ")
|
|
54
|
+
.trim();
|
|
55
|
+
const kind = looksHtml ? "an HTML page" : contentType !== "" ? `a ${contentType.split(";")[0]?.trim() ?? "non-JSON"} body` : "a non-JSON body";
|
|
56
|
+
return plain === "" ? kind : `${kind}: "${truncate(plain, 160)}"`;
|
|
57
|
+
}
|
|
58
|
+
function causeOf(err) {
|
|
59
|
+
return err instanceof Error ? err.cause : undefined;
|
|
60
|
+
}
|
|
61
|
+
function causeCode(cause) {
|
|
62
|
+
if (typeof cause !== "object" || cause === null) {
|
|
63
|
+
return undefined;
|
|
64
|
+
}
|
|
65
|
+
if ("code" in cause && typeof cause.code === "string") {
|
|
66
|
+
return cause.code;
|
|
67
|
+
}
|
|
68
|
+
// Dual-stack connection failures arrive as an AggregateError whose members carry the code.
|
|
69
|
+
if ("errors" in cause && Array.isArray(cause.errors)) {
|
|
70
|
+
for (const inner of cause.errors) {
|
|
71
|
+
const code = causeCode(inner);
|
|
72
|
+
if (code !== undefined) {
|
|
73
|
+
return code;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
return undefined;
|
|
78
|
+
}
|
|
79
|
+
export class ApiClient {
|
|
80
|
+
serverUrl;
|
|
81
|
+
token;
|
|
82
|
+
timeoutMs;
|
|
83
|
+
maxResponseBytes;
|
|
84
|
+
fetchFn;
|
|
85
|
+
sleepFn;
|
|
86
|
+
constructor(serverUrl, token = null, options = {}) {
|
|
87
|
+
this.serverUrl = serverUrl.replace(/\/+$/, "");
|
|
88
|
+
this.token = token;
|
|
89
|
+
this.timeoutMs = options.timeoutMs ?? REQUEST_TIMEOUT_MS;
|
|
90
|
+
this.maxResponseBytes = options.maxResponseBytes ?? MAX_RESPONSE_BYTES;
|
|
91
|
+
this.fetchFn = options.fetchFn ?? fetch;
|
|
92
|
+
this.sleepFn = options.sleepFn ?? defaultSleep;
|
|
93
|
+
}
|
|
94
|
+
buildUrl(path, query) {
|
|
95
|
+
let url = `${this.serverUrl}${path}`;
|
|
96
|
+
if (query !== undefined) {
|
|
97
|
+
const params = new URLSearchParams();
|
|
98
|
+
for (const [key, value] of Object.entries(query)) {
|
|
99
|
+
if (value !== undefined && value !== null && value !== "") {
|
|
100
|
+
params.append(key, cellText(value));
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
const text = params.toString();
|
|
104
|
+
if (text !== "") {
|
|
105
|
+
url = `${url}?${text}`;
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
return url;
|
|
109
|
+
}
|
|
110
|
+
async attempt(method, url, headers, payload, signal) {
|
|
111
|
+
const timeout = AbortSignal.timeout(this.timeoutMs);
|
|
112
|
+
try {
|
|
113
|
+
const response = await this.fetchFn(url, {
|
|
114
|
+
method,
|
|
115
|
+
headers,
|
|
116
|
+
...(payload === undefined ? {} : { body: payload }),
|
|
117
|
+
redirect: "error",
|
|
118
|
+
signal: signal === undefined ? timeout : AbortSignal.any([signal, timeout]),
|
|
119
|
+
});
|
|
120
|
+
const bytes = await this.readBounded(response, url);
|
|
121
|
+
const responseHeaders = {};
|
|
122
|
+
response.headers.forEach((value, key) => {
|
|
123
|
+
responseHeaders[key.toLowerCase()] = value;
|
|
124
|
+
});
|
|
125
|
+
return { status: response.status, statusText: response.statusText, headers: responseHeaders, bytes };
|
|
126
|
+
}
|
|
127
|
+
catch (err) {
|
|
128
|
+
throw this.mapTransportError(err, method, url);
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
async readBounded(response, url) {
|
|
132
|
+
const cap = this.maxResponseBytes;
|
|
133
|
+
const tooLarge = () => new CliError(`Response from ${url} exceeded ${cap} bytes`, { exitCode: EXIT_RUNTIME });
|
|
134
|
+
const declared = Number(response.headers.get("content-length"));
|
|
135
|
+
if (Number.isFinite(declared) && declared > cap) {
|
|
136
|
+
await response.body?.cancel();
|
|
137
|
+
throw tooLarge();
|
|
138
|
+
}
|
|
139
|
+
if (response.body === null) {
|
|
140
|
+
return Buffer.alloc(0);
|
|
141
|
+
}
|
|
142
|
+
const reader = response.body.getReader();
|
|
143
|
+
const chunks = [];
|
|
144
|
+
let total = 0;
|
|
145
|
+
for (;;) {
|
|
146
|
+
const { done, value } = (await reader.read());
|
|
147
|
+
if (done || value === undefined) {
|
|
148
|
+
break;
|
|
149
|
+
}
|
|
150
|
+
total += value.byteLength;
|
|
151
|
+
if (total > cap) {
|
|
152
|
+
await reader.cancel();
|
|
153
|
+
throw tooLarge();
|
|
154
|
+
}
|
|
155
|
+
chunks.push(Buffer.from(value));
|
|
156
|
+
}
|
|
157
|
+
return Buffer.concat(chunks);
|
|
158
|
+
}
|
|
159
|
+
mapTransportError(err, method, url) {
|
|
160
|
+
if (err instanceof CliError) {
|
|
161
|
+
return err;
|
|
162
|
+
}
|
|
163
|
+
if (err instanceof Error && (err.name === "TimeoutError" || err.name === "AbortError")) {
|
|
164
|
+
return new CliError(`${method} ${url} timed out after ${this.timeoutMs} ms`, { exitCode: EXIT_RUNTIME });
|
|
165
|
+
}
|
|
166
|
+
const cause = causeOf(err);
|
|
167
|
+
const causeMessage = cause instanceof Error ? cause.message : "";
|
|
168
|
+
if (/redirect/i.test(causeMessage)) {
|
|
169
|
+
const message = "The server answered with a redirect. evalctl never follows redirects, so the token cannot be sent to another " +
|
|
170
|
+
"location; check the --server URL (scheme, host and base path).";
|
|
171
|
+
return new CliError(message, {
|
|
172
|
+
exitCode: EXIT_RUNTIME,
|
|
173
|
+
payload: { ok: false, error: "redirect_refused", message },
|
|
174
|
+
});
|
|
175
|
+
}
|
|
176
|
+
const detail = causeCode(cause) ?? (causeMessage !== "" ? causeMessage : err instanceof Error ? err.message : String(err));
|
|
177
|
+
return new CliError(`Request to ${url} failed: ${oneLine(detail)}`, { exitCode: EXIT_RUNTIME });
|
|
178
|
+
}
|
|
179
|
+
/** Sends one JSON request and returns the parsed response; non-2xx statuses raise a `CliError` unless allowed. */
|
|
180
|
+
async request(method, path, options = {}) {
|
|
181
|
+
const requireAuth = options.requireAuth ?? true;
|
|
182
|
+
if (requireAuth && this.token === null) {
|
|
183
|
+
throw new CliError("No API token configured. Run 'login' or set EVALCTL_TOKEN.", {
|
|
184
|
+
exitCode: EXIT_AUTH,
|
|
185
|
+
payload: { ok: false, error: "not_logged_in", message: "No API token configured." },
|
|
186
|
+
});
|
|
187
|
+
}
|
|
188
|
+
const url = this.buildUrl(path, options.query);
|
|
189
|
+
const headers = {
|
|
190
|
+
Accept: "application/json",
|
|
191
|
+
"User-Agent": `evalctl/${VERSION} (node/${process.versions.node}; ${process.platform})`,
|
|
192
|
+
};
|
|
193
|
+
if (requireAuth && this.token !== null) {
|
|
194
|
+
headers["Authorization"] = `Bearer ${this.token}`;
|
|
195
|
+
}
|
|
196
|
+
// One serialization decides both the bytes and Content-Length: the server refuses chunked bodies.
|
|
197
|
+
let payload;
|
|
198
|
+
if (options.jsonBody !== undefined) {
|
|
199
|
+
payload = Buffer.from(JSON.stringify(options.jsonBody), "utf8");
|
|
200
|
+
headers["Content-Type"] = "application/json";
|
|
201
|
+
headers["Content-Length"] = String(payload.byteLength);
|
|
202
|
+
}
|
|
203
|
+
for (const [name, value] of Object.entries(options.headers ?? {})) {
|
|
204
|
+
if (FORBIDDEN_REQUEST_HEADERS.test(name)) {
|
|
205
|
+
throw new Error(`evalctl never sends the ${name} header`);
|
|
206
|
+
}
|
|
207
|
+
headers[name] = value;
|
|
208
|
+
}
|
|
209
|
+
let raw;
|
|
210
|
+
for (let retry = 0;; retry += 1) {
|
|
211
|
+
raw = await this.attempt(method, url, headers, payload, options.signal);
|
|
212
|
+
// Only a rate limit that says how long to wait is worth waiting for: a quota or token cap has no Retry-After.
|
|
213
|
+
const delay = raw.status === 429 ? retryDelayMs(raw.headers["retry-after"]) : null;
|
|
214
|
+
if (delay === null || retry >= MAX_RATE_LIMIT_RETRIES) {
|
|
215
|
+
break;
|
|
216
|
+
}
|
|
217
|
+
await this.sleepFn(delay, options.signal);
|
|
218
|
+
}
|
|
219
|
+
return this.finish(raw, method, path, options.allowStatuses ?? []);
|
|
220
|
+
}
|
|
221
|
+
finish(raw, method, path, allowStatuses) {
|
|
222
|
+
const text = new TextDecoder("utf-8").decode(raw.bytes);
|
|
223
|
+
const contentType = raw.headers["content-type"] ?? "";
|
|
224
|
+
let parsed;
|
|
225
|
+
let isJson = false;
|
|
226
|
+
if (text.trim() === "") {
|
|
227
|
+
parsed = {};
|
|
228
|
+
isJson = raw.status >= 200 && raw.status < 300;
|
|
229
|
+
}
|
|
230
|
+
else {
|
|
231
|
+
try {
|
|
232
|
+
parsed = JSON.parse(text);
|
|
233
|
+
isJson = true;
|
|
234
|
+
}
|
|
235
|
+
catch {
|
|
236
|
+
parsed = undefined;
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
const ok = raw.status >= 200 && raw.status < 300;
|
|
240
|
+
if (ok) {
|
|
241
|
+
if (!isJson || !isObject(parsed)) {
|
|
242
|
+
throw new CliError(`Expected a JSON object from ${method} ${path} but received ${describeNonJson(text, contentType)}`, { exitCode: EXIT_RUNTIME });
|
|
243
|
+
}
|
|
244
|
+
return { status: raw.status, headers: raw.headers, body: parsed };
|
|
245
|
+
}
|
|
246
|
+
let body;
|
|
247
|
+
if (isJson && isObject(parsed)) {
|
|
248
|
+
body = parsed;
|
|
249
|
+
}
|
|
250
|
+
else if (isJson) {
|
|
251
|
+
body = { error: `http_${raw.status}`, message: oneLine(cellText(parsed)) };
|
|
252
|
+
}
|
|
253
|
+
else {
|
|
254
|
+
body = { error: `http_${raw.status}`, message: describeNonJson(text, contentType) };
|
|
255
|
+
}
|
|
256
|
+
if (allowStatuses.includes(raw.status)) {
|
|
257
|
+
return { status: raw.status, headers: raw.headers, body };
|
|
258
|
+
}
|
|
259
|
+
const errCode = typeof body["error"] === "string" ? oneLine(body["error"]) : `http_${raw.status}`;
|
|
260
|
+
const detail = typeof body["message"] === "string" && body["message"] !== "" ? body["message"] : raw.statusText;
|
|
261
|
+
const prefix = raw.status === 409 || raw.status === 428 ? "Conflict HTTP" : "HTTP";
|
|
262
|
+
const wait = raw.status === 429 ? retryAfterSeconds(raw.headers["retry-after"]) : null;
|
|
263
|
+
const advice = wait === null ? "" : ` Try again in ${wait} s.`;
|
|
264
|
+
throw new CliError(`${prefix} ${raw.status} (${errCode}): ${oneLine(detail)}${advice}`, {
|
|
265
|
+
exitCode: exitCodeForStatus(raw.status),
|
|
266
|
+
payload: body,
|
|
267
|
+
});
|
|
268
|
+
}
|
|
269
|
+
}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { CommandContext, CommandSpec } from "../context.js";
|
|
2
|
+
/** `login`: trades email and password for an API token and saves it, never the password, in the config file. */
|
|
3
|
+
export declare function cmdLogin(ctx: CommandContext): Promise<number>;
|
|
4
|
+
/** `logout`: revokes the token on the server and removes it from the config file. */
|
|
5
|
+
export declare function cmdLogout(ctx: CommandContext): Promise<number>;
|
|
6
|
+
export declare const authCommands: readonly CommandSpec[];
|
|
@@ -0,0 +1,341 @@
|
|
|
1
|
+
import { ApiClient } from "../client.js";
|
|
2
|
+
import { configPermWarning, isNonLoopbackHttp, resolveServer, resolveToken, sameServerOrigin, saveConfig, withoutTokenFields, ENV_TOKEN, ENV_SERVER, normalizeServerUrl, } from "../config.js";
|
|
3
|
+
import { assertCanConfirm } from "./common.js";
|
|
4
|
+
import { CliError, EXIT_OK, EXIT_RUNTIME, EXIT_VALIDATION } from "../errors.js";
|
|
5
|
+
import { displayText, emitJson, errOut, formatTable, formatTimestamp, out } from "../output.js";
|
|
6
|
+
import { confirmPrompt, promptLine, promptPassword, readStdin } from "../prompt.js";
|
|
7
|
+
import { asArray, isObject, nonEmptyString, utcNowIso } from "../util.js";
|
|
8
|
+
function promptIO(ctx) {
|
|
9
|
+
return { input: ctx.io.stdin, output: ctx.io.promptOutput };
|
|
10
|
+
}
|
|
11
|
+
function positiveInt(flag, raw) {
|
|
12
|
+
const value = Number(raw);
|
|
13
|
+
if (!/^\d+$/.test(raw) || !Number.isSafeInteger(value) || value <= 0) {
|
|
14
|
+
throw new CliError(`--${flag} must be a positive whole number.`, { exitCode: EXIT_VALIDATION });
|
|
15
|
+
}
|
|
16
|
+
return value;
|
|
17
|
+
}
|
|
18
|
+
function requireField(res, key) {
|
|
19
|
+
const value = res[key];
|
|
20
|
+
if (typeof value !== "string" || value === "") {
|
|
21
|
+
throw new CliError(`Unexpected login response: "${key}" is missing.`, { exitCode: EXIT_RUNTIME });
|
|
22
|
+
}
|
|
23
|
+
return value;
|
|
24
|
+
}
|
|
25
|
+
/** `login`: trades email and password for an API token and saves it, never the password, in the config file. */
|
|
26
|
+
export async function cmdLogin(ctx) {
|
|
27
|
+
const { global: g, io } = ctx;
|
|
28
|
+
const cfg = ctx.config();
|
|
29
|
+
const serverUrl = resolveServer(g.server, cfg, io.env);
|
|
30
|
+
if (isNonLoopbackHttp(serverUrl)) {
|
|
31
|
+
errOut(`Warning: logging in over unencrypted HTTP (${serverUrl}); credentials and API tokens travel in cleartext. Prefer HTTPS.`);
|
|
32
|
+
}
|
|
33
|
+
const ttlHoursRaw = ctx.opt("ttl-hours");
|
|
34
|
+
const ttlSecondsRaw = ctx.opt("ttl-s");
|
|
35
|
+
if (ttlHoursRaw !== undefined && ttlSecondsRaw !== undefined) {
|
|
36
|
+
throw new CliError("Pass either --ttl-hours or --ttl-s, not both.", { exitCode: EXIT_VALIDATION });
|
|
37
|
+
}
|
|
38
|
+
let ttlSeconds;
|
|
39
|
+
if (ttlSecondsRaw !== undefined) {
|
|
40
|
+
ttlSeconds = positiveInt("ttl-s", ttlSecondsRaw);
|
|
41
|
+
}
|
|
42
|
+
else if (ttlHoursRaw !== undefined) {
|
|
43
|
+
const hours = Number(ttlHoursRaw);
|
|
44
|
+
if (ttlHoursRaw.trim() === "" || !Number.isFinite(hours) || hours <= 0) {
|
|
45
|
+
throw new CliError("--ttl-hours must be a positive finite number.", { exitCode: EXIT_VALIDATION });
|
|
46
|
+
}
|
|
47
|
+
ttlSeconds = Math.max(1, Math.round(hours * 3600));
|
|
48
|
+
// 1e308 hours overflows to Infinity, which JSON writes as null: the server would then quietly use its default.
|
|
49
|
+
if (!Number.isSafeInteger(ttlSeconds)) {
|
|
50
|
+
throw new CliError("--ttl-hours must be a positive number of hours that fits in whole seconds.", { exitCode: EXIT_VALIDATION });
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
const idleRaw = ctx.opt("idle-s");
|
|
54
|
+
const idleSeconds = idleRaw === undefined ? undefined : positiveInt("idle-s", idleRaw);
|
|
55
|
+
const scope = ctx.opt("scope") ?? "read_write";
|
|
56
|
+
const label = ctx.opt("label") ?? `evalctl@${io.hostname()}`.slice(0, 64);
|
|
57
|
+
if (g.dryRun) {
|
|
58
|
+
const plan = {
|
|
59
|
+
ok: true,
|
|
60
|
+
dry_run: true,
|
|
61
|
+
action: "login",
|
|
62
|
+
server: serverUrl,
|
|
63
|
+
email: nonEmptyString(ctx.opt("email")) ?? null,
|
|
64
|
+
scope,
|
|
65
|
+
label,
|
|
66
|
+
ttl_s: ttlSeconds ?? null,
|
|
67
|
+
idle_s: idleSeconds ?? null,
|
|
68
|
+
config_path: ctx.configPath,
|
|
69
|
+
};
|
|
70
|
+
if (g.json) {
|
|
71
|
+
emitJson(plan);
|
|
72
|
+
}
|
|
73
|
+
else {
|
|
74
|
+
out(`Dry run: would log in to ${displayText(serverUrl)} as ${displayText(plan["email"] ?? "(email prompted)")} with scope ${scope}.`);
|
|
75
|
+
out(`Dry run: would save the token in ${ctx.configPath}; nothing was sent.`);
|
|
76
|
+
}
|
|
77
|
+
return EXIT_OK;
|
|
78
|
+
}
|
|
79
|
+
let email = nonEmptyString(ctx.opt("email"));
|
|
80
|
+
if (email === undefined) {
|
|
81
|
+
if (io.stdin.isTTY !== true) {
|
|
82
|
+
throw new CliError("Pass --email when stdin is not interactive.", { exitCode: EXIT_VALIDATION });
|
|
83
|
+
}
|
|
84
|
+
email = (await promptLine("Email: ", promptIO(ctx))).trim();
|
|
85
|
+
}
|
|
86
|
+
const password = ctx.flag("password-stdin") ? await readStdin(io.stdin) : await promptPassword("Password: ", promptIO(ctx));
|
|
87
|
+
if (email === "" || password === "") {
|
|
88
|
+
throw new CliError("Email and password are required.", { exitCode: EXIT_VALIDATION });
|
|
89
|
+
}
|
|
90
|
+
const payload = { email, password, scope, label };
|
|
91
|
+
if (ttlSeconds !== undefined) {
|
|
92
|
+
payload["ttl_s"] = ttlSeconds;
|
|
93
|
+
}
|
|
94
|
+
if (idleSeconds !== undefined) {
|
|
95
|
+
payload["idle_s"] = idleSeconds;
|
|
96
|
+
}
|
|
97
|
+
const anonymous = new ApiClient(serverUrl, null, io.clientOptions);
|
|
98
|
+
const { body: res } = await anonymous.request("POST", "/api/tokens", { jsonBody: payload, requireAuth: false });
|
|
99
|
+
const token = requireField(res, "token");
|
|
100
|
+
const saved = {
|
|
101
|
+
...cfg,
|
|
102
|
+
server: serverUrl,
|
|
103
|
+
token,
|
|
104
|
+
token_id: requireField(res, "token_id"),
|
|
105
|
+
email: requireField(res, "email"),
|
|
106
|
+
scope: requireField(res, "scope"),
|
|
107
|
+
label: res["label"] ?? label,
|
|
108
|
+
abs_expires: res["abs_expires"] ?? null,
|
|
109
|
+
idle_seconds: res["idle_seconds"] ?? null,
|
|
110
|
+
saved_at: utcNowIso(),
|
|
111
|
+
};
|
|
112
|
+
delete saved["password"];
|
|
113
|
+
try {
|
|
114
|
+
saveConfig(ctx.configPath, saved);
|
|
115
|
+
}
|
|
116
|
+
catch (err) {
|
|
117
|
+
// A token nobody can read back would live on the server unused; take it away again before reporting.
|
|
118
|
+
await new ApiClient(serverUrl, token, io.clientOptions)
|
|
119
|
+
.request("DELETE", "/api/tokens/current", { allowStatuses: [401] })
|
|
120
|
+
.catch(() => undefined);
|
|
121
|
+
throw err;
|
|
122
|
+
}
|
|
123
|
+
const summary = { ...res, server: serverUrl, config_path: ctx.configPath };
|
|
124
|
+
delete summary["token"];
|
|
125
|
+
if (g.json) {
|
|
126
|
+
emitJson(summary);
|
|
127
|
+
}
|
|
128
|
+
else {
|
|
129
|
+
out(`Logged in as ${displayText(saved["email"])} (${displayText(saved["scope"])}) on ${serverUrl}`);
|
|
130
|
+
out(`Token: ${displayText(saved["token_id"])} (prefix ${displayText(res["prefix"])}), expires ${formatTimestamp(saved["abs_expires"])}`);
|
|
131
|
+
out(`Saved config: ${ctx.configPath}`);
|
|
132
|
+
const warning = configPermWarning(ctx.configPath, io.platform);
|
|
133
|
+
if (warning !== null) {
|
|
134
|
+
errOut(`Note: ${warning}`);
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
return EXIT_OK;
|
|
138
|
+
}
|
|
139
|
+
/** `logout`: revokes the token on the server and removes it from the config file. */
|
|
140
|
+
export async function cmdLogout(ctx) {
|
|
141
|
+
const { global: g, io } = ctx;
|
|
142
|
+
const cfg = ctx.config();
|
|
143
|
+
const rawServer = nonEmptyString(g.server) ?? nonEmptyString(io.env[ENV_SERVER]) ?? nonEmptyString(cfg["server"]);
|
|
144
|
+
const serverUrl = rawServer === undefined ? null : normalizeServerUrl(rawServer);
|
|
145
|
+
const envToken = nonEmptyString(io.env[ENV_TOKEN]);
|
|
146
|
+
const token = serverUrl === null ? null : resolveToken(cfg, serverUrl, io.env);
|
|
147
|
+
const savedServer = nonEmptyString(cfg["server"]);
|
|
148
|
+
// The saved login is cleared only when this run is about that login: never by an environment token or another server.
|
|
149
|
+
const clearsSavedLogin = envToken === undefined && (serverUrl === null || (savedServer !== undefined && sameServerOrigin(serverUrl, savedServer)));
|
|
150
|
+
if (g.dryRun) {
|
|
151
|
+
const info = {
|
|
152
|
+
ok: true,
|
|
153
|
+
dry_run: true,
|
|
154
|
+
server: serverUrl,
|
|
155
|
+
would_revoke_server: token !== null && serverUrl !== null,
|
|
156
|
+
would_clear_config: clearsSavedLogin && ["token", "token_id"].some((key) => key in cfg),
|
|
157
|
+
};
|
|
158
|
+
if (g.json) {
|
|
159
|
+
emitJson(info);
|
|
160
|
+
}
|
|
161
|
+
else {
|
|
162
|
+
out(`Dry run: would logout on ${serverUrl ?? "local config"} ` +
|
|
163
|
+
`(revoke_server=${String(info.would_revoke_server)}, clear_config=${String(info.would_clear_config)}).`);
|
|
164
|
+
}
|
|
165
|
+
return EXIT_OK;
|
|
166
|
+
}
|
|
167
|
+
let serverRevoked = false;
|
|
168
|
+
let note = "";
|
|
169
|
+
if (token !== null && serverUrl !== null) {
|
|
170
|
+
const client = new ApiClient(serverUrl, token, io.clientOptions);
|
|
171
|
+
const { status } = await client.request("DELETE", "/api/tokens/current", { allowStatuses: [401] });
|
|
172
|
+
if (status === 200) {
|
|
173
|
+
serverRevoked = true;
|
|
174
|
+
}
|
|
175
|
+
else {
|
|
176
|
+
note = "Token was already expired or revoked on server.";
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
else if (token === null) {
|
|
180
|
+
note = "No active token configured.";
|
|
181
|
+
}
|
|
182
|
+
let configCleared = false;
|
|
183
|
+
if (clearsSavedLogin) {
|
|
184
|
+
const { config, removed } = withoutTokenFields(cfg);
|
|
185
|
+
if (removed) {
|
|
186
|
+
saveConfig(ctx.configPath, config);
|
|
187
|
+
configCleared = true;
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
const result = { ok: true, server_revoked: serverRevoked, config_cleared: configCleared };
|
|
191
|
+
if (note !== "") {
|
|
192
|
+
result["note"] = note;
|
|
193
|
+
}
|
|
194
|
+
if (g.json) {
|
|
195
|
+
emitJson(result);
|
|
196
|
+
}
|
|
197
|
+
else if (serverRevoked && configCleared) {
|
|
198
|
+
out("Logged out; server token revoked and local config cleared.");
|
|
199
|
+
}
|
|
200
|
+
else if (serverRevoked) {
|
|
201
|
+
out("Logged out; server token revoked (local config left intact).");
|
|
202
|
+
}
|
|
203
|
+
else {
|
|
204
|
+
out(`Logged out locally. ${note}`.trim());
|
|
205
|
+
}
|
|
206
|
+
return EXIT_OK;
|
|
207
|
+
}
|
|
208
|
+
async function tokensList(ctx) {
|
|
209
|
+
const { body } = await ctx.client().request("GET", "/api/tokens");
|
|
210
|
+
if (ctx.global.json) {
|
|
211
|
+
emitJson(body);
|
|
212
|
+
return EXIT_OK;
|
|
213
|
+
}
|
|
214
|
+
const tokens = asArray(body["tokens"]).filter(isObject);
|
|
215
|
+
if (tokens.length === 0) {
|
|
216
|
+
out("No active API tokens.");
|
|
217
|
+
return EXIT_OK;
|
|
218
|
+
}
|
|
219
|
+
const rows = tokens.map((t) => [
|
|
220
|
+
t["token_id"],
|
|
221
|
+
t["prefix"],
|
|
222
|
+
t["scope"],
|
|
223
|
+
t["label"] || "-",
|
|
224
|
+
formatTimestamp(t["last_used"]),
|
|
225
|
+
formatTimestamp(t["abs_expires"]),
|
|
226
|
+
]);
|
|
227
|
+
out(formatTable(["TOKEN_ID", "PREFIX", "SCOPE", "LABEL", "LAST_USED", "EXPIRES"], rows));
|
|
228
|
+
return EXIT_OK;
|
|
229
|
+
}
|
|
230
|
+
async function tokensRevoke(ctx) {
|
|
231
|
+
const tokenId = nonEmptyString(ctx.positionals[0]);
|
|
232
|
+
if (tokenId === undefined) {
|
|
233
|
+
throw new CliError("Pass the ID of the token to revoke (see 'tokens list').", { exitCode: EXIT_VALIDATION });
|
|
234
|
+
}
|
|
235
|
+
if (ctx.global.dryRun) {
|
|
236
|
+
if (ctx.global.json) {
|
|
237
|
+
emitJson({ ok: true, dry_run: true, action: "revoke", token_id: tokenId });
|
|
238
|
+
}
|
|
239
|
+
else {
|
|
240
|
+
out(`Dry run: would revoke token '${displayText(tokenId)}'.`);
|
|
241
|
+
}
|
|
242
|
+
return EXIT_OK;
|
|
243
|
+
}
|
|
244
|
+
const { body } = await ctx.client().request("DELETE", `/api/tokens/${encodeURIComponent(tokenId)}`);
|
|
245
|
+
if (ctx.global.json) {
|
|
246
|
+
emitJson(body);
|
|
247
|
+
}
|
|
248
|
+
else {
|
|
249
|
+
out(`Revoked token ${displayText(tokenId)}.`);
|
|
250
|
+
}
|
|
251
|
+
return EXIT_OK;
|
|
252
|
+
}
|
|
253
|
+
async function tokensRevokeAll(ctx) {
|
|
254
|
+
const { global: g, io } = ctx;
|
|
255
|
+
if (g.dryRun) {
|
|
256
|
+
if (g.json) {
|
|
257
|
+
emitJson({ ok: true, dry_run: true, action: "revoke-all" });
|
|
258
|
+
}
|
|
259
|
+
else {
|
|
260
|
+
out("Dry run: would revoke ALL API tokens for this account.");
|
|
261
|
+
}
|
|
262
|
+
return EXIT_OK;
|
|
263
|
+
}
|
|
264
|
+
assertCanConfirm(ctx);
|
|
265
|
+
const confirmed = await confirmPrompt("Revoke ALL API tokens for this account? [y/N]: ", ctx.flag("yes"), promptIO(ctx));
|
|
266
|
+
if (!confirmed) {
|
|
267
|
+
throw new CliError("Aborted token revocation. Pass --yes to confirm without a prompt.", { exitCode: EXIT_RUNTIME });
|
|
268
|
+
}
|
|
269
|
+
const client = ctx.client();
|
|
270
|
+
const { body } = await client.request("POST", "/api/tokens/revoke-all", { jsonBody: {} });
|
|
271
|
+
const cfg = ctx.config();
|
|
272
|
+
const savedServer = nonEmptyString(cfg["server"]);
|
|
273
|
+
if (nonEmptyString(io.env[ENV_TOKEN]) === undefined &&
|
|
274
|
+
nonEmptyString(cfg["token"]) !== undefined &&
|
|
275
|
+
savedServer !== undefined &&
|
|
276
|
+
sameServerOrigin(client.serverUrl, savedServer)) {
|
|
277
|
+
saveConfig(ctx.configPath, withoutTokenFields(cfg).config);
|
|
278
|
+
}
|
|
279
|
+
if (g.json) {
|
|
280
|
+
emitJson(body);
|
|
281
|
+
}
|
|
282
|
+
else {
|
|
283
|
+
out(`Revoked ${displayText(body["revoked"] ?? "0")} token(s).`);
|
|
284
|
+
}
|
|
285
|
+
return EXIT_OK;
|
|
286
|
+
}
|
|
287
|
+
const yesOption = { type: "boolean", short: "y", description: "Skip the confirmation prompt" };
|
|
288
|
+
export const authCommands = [
|
|
289
|
+
{
|
|
290
|
+
name: "login",
|
|
291
|
+
summary: "Sign in and store an API token",
|
|
292
|
+
usage: "login [--email EMAIL] [--password-stdin] [--scope read|read_write] [--ttl-hours N | --ttl-s N] [--idle-s N]",
|
|
293
|
+
options: {
|
|
294
|
+
email: { type: "string", placeholder: "EMAIL", description: "Account email address" },
|
|
295
|
+
"password-stdin": { type: "boolean", description: "Read the password from stdin instead of prompting" },
|
|
296
|
+
scope: {
|
|
297
|
+
type: "string",
|
|
298
|
+
placeholder: "SCOPE",
|
|
299
|
+
choices: ["read", "read_write"],
|
|
300
|
+
default: "read_write",
|
|
301
|
+
description: "What the token may do; use read for people and jobs that only look",
|
|
302
|
+
},
|
|
303
|
+
label: { type: "string", placeholder: "TEXT", description: "Label shown in 'tokens list' (default: evalctl@<host name>)" },
|
|
304
|
+
"ttl-hours": { type: "string", placeholder: "N", description: "Token lifetime in hours (default: the server's)" },
|
|
305
|
+
"ttl-s": { type: "string", placeholder: "N", description: "Token lifetime in seconds (default: the server's)" },
|
|
306
|
+
"idle-s": { type: "string", placeholder: "N", description: "Seconds without use after which the token expires (default: the server's)" },
|
|
307
|
+
},
|
|
308
|
+
positionals: { min: 0, max: 0 },
|
|
309
|
+
handler: cmdLogin,
|
|
310
|
+
},
|
|
311
|
+
{
|
|
312
|
+
name: "logout",
|
|
313
|
+
summary: "Revoke the current token and clear the saved login",
|
|
314
|
+
usage: "logout",
|
|
315
|
+
positionals: { min: 0, max: 0 },
|
|
316
|
+
handler: cmdLogout,
|
|
317
|
+
},
|
|
318
|
+
{
|
|
319
|
+
name: "tokens",
|
|
320
|
+
summary: "Manage API tokens (list, revoke, revoke-all)",
|
|
321
|
+
usage: "tokens <list|revoke|revoke-all>",
|
|
322
|
+
subcommands: [
|
|
323
|
+
{ name: "list", summary: "List active tokens", usage: "tokens list", positionals: { min: 0, max: 0 }, handler: tokensList },
|
|
324
|
+
{
|
|
325
|
+
name: "revoke",
|
|
326
|
+
summary: "Revoke one token by id",
|
|
327
|
+
usage: "tokens revoke <token-id>",
|
|
328
|
+
positionals: { min: 1, max: 1 },
|
|
329
|
+
handler: tokensRevoke,
|
|
330
|
+
},
|
|
331
|
+
{
|
|
332
|
+
name: "revoke-all",
|
|
333
|
+
summary: "Revoke every token of this account",
|
|
334
|
+
usage: "tokens revoke-all [--yes]",
|
|
335
|
+
options: { yes: yesOption },
|
|
336
|
+
positionals: { min: 0, max: 0 },
|
|
337
|
+
handler: tokensRevokeAll,
|
|
338
|
+
},
|
|
339
|
+
],
|
|
340
|
+
},
|
|
341
|
+
];
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { CommandContext, OptionSpec } from "../context.js";
|
|
2
|
+
import { type JsonObject } from "../util.js";
|
|
3
|
+
export declare const ack: OptionSpec;
|
|
4
|
+
export declare const yes: OptionSpec;
|
|
5
|
+
export declare const originChoices: readonly ["git", "server", "all"];
|
|
6
|
+
export declare const statusChoices: readonly ["active", "archived", "all"];
|
|
7
|
+
export declare const MAX_SCENARIO_BYTES: number;
|
|
8
|
+
export declare const MAX_SCREEN_BYTES: number;
|
|
9
|
+
export declare const AUTHORING_BODY_LIMIT: number;
|
|
10
|
+
export declare function acknowledgedWarnings(ctx: CommandContext): JsonObject;
|
|
11
|
+
export declare function isReservedScenarioId(value: string): boolean;
|
|
12
|
+
export declare function isScenarioId(value: unknown): value is string;
|
|
13
|
+
export declare function isScreenName(value: unknown): value is string;
|
|
14
|
+
export declare function authoringBody(body: JsonObject): JsonObject;
|
|
15
|
+
/** Without a terminal nobody could answer a prompt, so say that plainly instead of reporting a refusal nobody made. */
|
|
16
|
+
export declare function assertCanConfirm(ctx: CommandContext): void;
|
|
17
|
+
export declare function confirmAction(ctx: CommandContext, prompt: string, declined: string): Promise<void>;
|