@engini/cli 0.34.0 → 0.36.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 +121 -14
- package/dist/chunk-XNKWQPRX.js +984 -0
- package/dist/cli.js +1355 -636
- package/dist/session-IWURAIVM.js +17 -0
- package/package.json +2 -2
|
@@ -0,0 +1,984 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// src/session.ts
|
|
4
|
+
import { dirname as dirname2, join as join2 } from "path";
|
|
5
|
+
|
|
6
|
+
// src/active.ts
|
|
7
|
+
import { createHash } from "crypto";
|
|
8
|
+
|
|
9
|
+
// src/config.ts
|
|
10
|
+
import {
|
|
11
|
+
chmodSync,
|
|
12
|
+
existsSync,
|
|
13
|
+
linkSync,
|
|
14
|
+
mkdirSync,
|
|
15
|
+
readFileSync,
|
|
16
|
+
renameSync,
|
|
17
|
+
rmSync,
|
|
18
|
+
statSync,
|
|
19
|
+
writeFileSync
|
|
20
|
+
} from "fs";
|
|
21
|
+
import { randomBytes } from "crypto";
|
|
22
|
+
import { homedir } from "os";
|
|
23
|
+
import { dirname, join } from "path";
|
|
24
|
+
import { parse, stringify } from "smol-toml";
|
|
25
|
+
|
|
26
|
+
// src/prompt.ts
|
|
27
|
+
import { spawn } from "child_process";
|
|
28
|
+
import { createInterface } from "readline";
|
|
29
|
+
function openBrowser(url, deps = {}) {
|
|
30
|
+
let protocol;
|
|
31
|
+
try {
|
|
32
|
+
protocol = new URL(url).protocol;
|
|
33
|
+
} catch {
|
|
34
|
+
return false;
|
|
35
|
+
}
|
|
36
|
+
if (protocol !== "https:" && protocol !== "http:") return false;
|
|
37
|
+
const platform = deps.platform ?? process.platform;
|
|
38
|
+
const run = deps.spawn ?? spawn;
|
|
39
|
+
const [command, args] = platform === "win32" ? ["rundll32", ["url.dll,FileProtocolHandler", url]] : [platform === "darwin" ? "open" : "xdg-open", [url]];
|
|
40
|
+
try {
|
|
41
|
+
const child = run(command, args, { stdio: "ignore", detached: true, shell: false });
|
|
42
|
+
child.on("error", () => {
|
|
43
|
+
});
|
|
44
|
+
child.unref();
|
|
45
|
+
return true;
|
|
46
|
+
} catch {
|
|
47
|
+
return false;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
var PromptCancelled = class extends Error {
|
|
51
|
+
constructor() {
|
|
52
|
+
super("cancelled");
|
|
53
|
+
this.name = "PromptCancelled";
|
|
54
|
+
}
|
|
55
|
+
};
|
|
56
|
+
var PromptStreamEnded = class extends Error {
|
|
57
|
+
constructor() {
|
|
58
|
+
super("stdin ended before an answer was given");
|
|
59
|
+
this.name = "PromptStreamEnded";
|
|
60
|
+
}
|
|
61
|
+
};
|
|
62
|
+
async function readStdin(stream = process.stdin) {
|
|
63
|
+
const chunks = [];
|
|
64
|
+
for await (const chunk of stream) {
|
|
65
|
+
chunks.push(typeof chunk === "string" ? Buffer.from(chunk) : chunk);
|
|
66
|
+
}
|
|
67
|
+
return Buffer.concat(chunks).toString("utf8").replace(/\r?\n$/, "");
|
|
68
|
+
}
|
|
69
|
+
function ask(rl, question) {
|
|
70
|
+
return new Promise((resolve, reject) => {
|
|
71
|
+
let answered = false;
|
|
72
|
+
rl.question(question, (value) => {
|
|
73
|
+
answered = true;
|
|
74
|
+
resolve(value);
|
|
75
|
+
});
|
|
76
|
+
rl.once("close", () => {
|
|
77
|
+
if (!answered) reject(new PromptStreamEnded());
|
|
78
|
+
});
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
async function confirm(question) {
|
|
82
|
+
const rl = createInterface({ input: process.stdin, output: process.stdout });
|
|
83
|
+
try {
|
|
84
|
+
const answer = (await ask(rl, `${question} [y/N] `)).trim().toLowerCase();
|
|
85
|
+
return answer === "y" || answer === "yes";
|
|
86
|
+
} finally {
|
|
87
|
+
rl.close();
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
async function promptText(label, fallback = "") {
|
|
91
|
+
const suffix = fallback ? ` [${fallback}]` : "";
|
|
92
|
+
const rl = createInterface({ input: process.stdin, output: process.stdout });
|
|
93
|
+
try {
|
|
94
|
+
const answer = (await ask(rl, `${label}${suffix}: `)).trim();
|
|
95
|
+
return answer || fallback;
|
|
96
|
+
} finally {
|
|
97
|
+
rl.close();
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
var ESC = "\x1B";
|
|
101
|
+
var CTRL_C = "";
|
|
102
|
+
var CTRL_D = "";
|
|
103
|
+
var CTRL_U = "";
|
|
104
|
+
var DEL = "\x7F";
|
|
105
|
+
var BACKSPACE = "\b";
|
|
106
|
+
var MAX_ESCAPE_LENGTH = 256;
|
|
107
|
+
function escapeKind(pending) {
|
|
108
|
+
if (pending.length < 2) return "incomplete";
|
|
109
|
+
const second = pending[1];
|
|
110
|
+
if (second !== "[" && second !== "O") return "two-char";
|
|
111
|
+
if (pending.length < 3) return "incomplete";
|
|
112
|
+
const last = pending[pending.length - 1];
|
|
113
|
+
return last >= "@" && last <= "~" ? "csi" : "incomplete";
|
|
114
|
+
}
|
|
115
|
+
function promptHidden(label, opts = {}) {
|
|
116
|
+
const streams = opts.streams ?? { input: process.stdin, output: process.stdout };
|
|
117
|
+
const { input, output } = streams;
|
|
118
|
+
const wasRaw = Boolean(input.isRaw);
|
|
119
|
+
let raw = false;
|
|
120
|
+
if (input.isTTY && typeof input.setRawMode === "function") {
|
|
121
|
+
try {
|
|
122
|
+
input.setRawMode(true);
|
|
123
|
+
raw = true;
|
|
124
|
+
} catch {
|
|
125
|
+
raw = false;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
const mask = (opts.mask ?? true) && raw;
|
|
129
|
+
return new Promise((resolve, reject) => {
|
|
130
|
+
let settled = false;
|
|
131
|
+
const write = (s) => {
|
|
132
|
+
try {
|
|
133
|
+
output.write(s);
|
|
134
|
+
} catch {
|
|
135
|
+
}
|
|
136
|
+
};
|
|
137
|
+
let restored = false;
|
|
138
|
+
const restore = () => {
|
|
139
|
+
if (restored) return;
|
|
140
|
+
restored = true;
|
|
141
|
+
try {
|
|
142
|
+
if (raw) input.setRawMode?.(wasRaw);
|
|
143
|
+
} catch {
|
|
144
|
+
}
|
|
145
|
+
try {
|
|
146
|
+
input.pause();
|
|
147
|
+
} catch {
|
|
148
|
+
}
|
|
149
|
+
};
|
|
150
|
+
const usingRealStdin = input === process.stdin;
|
|
151
|
+
if (usingRealStdin) process.once("exit", restore);
|
|
152
|
+
const detach = () => {
|
|
153
|
+
input.removeListener("data", onData);
|
|
154
|
+
input.removeListener("end", onEnd);
|
|
155
|
+
input.removeListener("error", onEnd);
|
|
156
|
+
if (usingRealStdin) process.removeListener("exit", restore);
|
|
157
|
+
};
|
|
158
|
+
const finish = (err, result) => {
|
|
159
|
+
if (settled) return;
|
|
160
|
+
settled = true;
|
|
161
|
+
detach();
|
|
162
|
+
restore();
|
|
163
|
+
write("\n");
|
|
164
|
+
if (err) reject(err);
|
|
165
|
+
else resolve(result);
|
|
166
|
+
};
|
|
167
|
+
function onEnd() {
|
|
168
|
+
finish(new PromptStreamEnded());
|
|
169
|
+
}
|
|
170
|
+
let buf = "";
|
|
171
|
+
let pending = "";
|
|
172
|
+
const eraseOne = () => {
|
|
173
|
+
const cps = Array.from(buf);
|
|
174
|
+
cps.pop();
|
|
175
|
+
buf = cps.join("");
|
|
176
|
+
};
|
|
177
|
+
const clearLine = () => {
|
|
178
|
+
if (mask) write("\b \b".repeat(Array.from(buf).length));
|
|
179
|
+
buf = "";
|
|
180
|
+
};
|
|
181
|
+
const onData = (chunk) => {
|
|
182
|
+
const chars = Array.from(chunk);
|
|
183
|
+
let discarding = false;
|
|
184
|
+
for (let i = 0; i < chars.length; i++) {
|
|
185
|
+
const ch = chars[i];
|
|
186
|
+
if (ch === CTRL_C || ch === CTRL_D) return finish(new PromptCancelled());
|
|
187
|
+
if (ch === "\r" || ch === "\n") {
|
|
188
|
+
const rest = chars.slice(i + 1).join("");
|
|
189
|
+
return finish(null, { value: buf.trim(), truncated: rest.trim().length > 0 });
|
|
190
|
+
}
|
|
191
|
+
if (discarding) continue;
|
|
192
|
+
if (pending) {
|
|
193
|
+
pending += ch;
|
|
194
|
+
if (pending.length > MAX_ESCAPE_LENGTH) {
|
|
195
|
+
clearLine();
|
|
196
|
+
pending = "";
|
|
197
|
+
discarding = true;
|
|
198
|
+
continue;
|
|
199
|
+
}
|
|
200
|
+
const kind = escapeKind(pending);
|
|
201
|
+
if (kind === "csi") {
|
|
202
|
+
pending = "";
|
|
203
|
+
} else if (kind === "two-char") {
|
|
204
|
+
if (pending[1] === ESC) {
|
|
205
|
+
pending = ESC;
|
|
206
|
+
continue;
|
|
207
|
+
}
|
|
208
|
+
clearLine();
|
|
209
|
+
pending = "";
|
|
210
|
+
}
|
|
211
|
+
continue;
|
|
212
|
+
}
|
|
213
|
+
if (ch === ESC) {
|
|
214
|
+
pending = ch;
|
|
215
|
+
continue;
|
|
216
|
+
}
|
|
217
|
+
if (ch === DEL || ch === BACKSPACE) {
|
|
218
|
+
if (buf.length > 0) {
|
|
219
|
+
eraseOne();
|
|
220
|
+
if (mask) write("\b \b");
|
|
221
|
+
}
|
|
222
|
+
continue;
|
|
223
|
+
}
|
|
224
|
+
if (ch === CTRL_U) {
|
|
225
|
+
clearLine();
|
|
226
|
+
continue;
|
|
227
|
+
}
|
|
228
|
+
if (ch < " ") continue;
|
|
229
|
+
buf += ch;
|
|
230
|
+
if (mask) write("*");
|
|
231
|
+
}
|
|
232
|
+
};
|
|
233
|
+
try {
|
|
234
|
+
input.resume();
|
|
235
|
+
input.setEncoding("utf8");
|
|
236
|
+
write(`${label}: `);
|
|
237
|
+
input.on("data", onData);
|
|
238
|
+
input.on("end", onEnd);
|
|
239
|
+
input.on("error", onEnd);
|
|
240
|
+
} catch (err) {
|
|
241
|
+
finish(err instanceof Error ? err : new Error(String(err)));
|
|
242
|
+
}
|
|
243
|
+
});
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
// src/conventions.ts
|
|
247
|
+
var Exit = /* @__PURE__ */ ((Exit2) => {
|
|
248
|
+
Exit2[Exit2["OK"] = 0] = "OK";
|
|
249
|
+
Exit2[Exit2["GENERIC"] = 1] = "GENERIC";
|
|
250
|
+
Exit2[Exit2["USAGE"] = 2] = "USAGE";
|
|
251
|
+
Exit2[Exit2["AUTH"] = 3] = "AUTH";
|
|
252
|
+
Exit2[Exit2["NOT_FOUND"] = 4] = "NOT_FOUND";
|
|
253
|
+
Exit2[Exit2["VALIDATION"] = 5] = "VALIDATION";
|
|
254
|
+
Exit2[Exit2["TIMEOUT"] = 124] = "TIMEOUT";
|
|
255
|
+
return Exit2;
|
|
256
|
+
})(Exit || {});
|
|
257
|
+
var ERROR_NAMES = {
|
|
258
|
+
[1 /* GENERIC */]: "Error",
|
|
259
|
+
[2 /* USAGE */]: "UsageError",
|
|
260
|
+
[3 /* AUTH */]: "AuthError",
|
|
261
|
+
[4 /* NOT_FOUND */]: "ResourceNotFound",
|
|
262
|
+
[5 /* VALIDATION */]: "ValidationError",
|
|
263
|
+
[124 /* TIMEOUT */]: "Timeout"
|
|
264
|
+
};
|
|
265
|
+
var CliError = class extends Error {
|
|
266
|
+
constructor(code) {
|
|
267
|
+
super(`CliExit(${code})`);
|
|
268
|
+
this.code = code;
|
|
269
|
+
this.name = "CliError";
|
|
270
|
+
}
|
|
271
|
+
code;
|
|
272
|
+
};
|
|
273
|
+
function isTty() {
|
|
274
|
+
return Boolean(process.stdout.isTTY);
|
|
275
|
+
}
|
|
276
|
+
function isInteractive() {
|
|
277
|
+
return Boolean(process.stdout.isTTY && process.stdin.isTTY);
|
|
278
|
+
}
|
|
279
|
+
var context = { forceJson: false, quiet: false, dryRun: false };
|
|
280
|
+
function setOutputContext(ctx) {
|
|
281
|
+
context = ctx;
|
|
282
|
+
}
|
|
283
|
+
function pairFlags() {
|
|
284
|
+
return { workspace: context.workspaceFlag, environment: context.environmentFlag };
|
|
285
|
+
}
|
|
286
|
+
function isMutating() {
|
|
287
|
+
return Boolean(context.mutating);
|
|
288
|
+
}
|
|
289
|
+
function isPairRequired() {
|
|
290
|
+
return Boolean(context.needsPair);
|
|
291
|
+
}
|
|
292
|
+
function setScopeContext(scope) {
|
|
293
|
+
context.scope = scope;
|
|
294
|
+
}
|
|
295
|
+
function dryRun() {
|
|
296
|
+
return context.dryRun;
|
|
297
|
+
}
|
|
298
|
+
function outputFlags() {
|
|
299
|
+
return { forceJson: context.forceJson, quiet: context.quiet };
|
|
300
|
+
}
|
|
301
|
+
function formatValue(value) {
|
|
302
|
+
return typeof value === "string" ? value : JSON.stringify(value);
|
|
303
|
+
}
|
|
304
|
+
function pretty(obj) {
|
|
305
|
+
if (obj !== null && typeof obj === "object" && !Array.isArray(obj)) {
|
|
306
|
+
for (const [key, value] of Object.entries(obj)) {
|
|
307
|
+
console.log(`${key}: ${formatValue(value)}`);
|
|
308
|
+
}
|
|
309
|
+
} else if (Array.isArray(obj)) {
|
|
310
|
+
for (const item of obj) {
|
|
311
|
+
console.log(formatValue(item));
|
|
312
|
+
}
|
|
313
|
+
} else {
|
|
314
|
+
console.log(formatValue(obj));
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
function printOutput(obj) {
|
|
318
|
+
if (context.dryRun && context.scope !== void 0 && obj !== null && typeof obj === "object" && !Array.isArray(obj) && !("scope" in obj)) {
|
|
319
|
+
obj = { ...obj, scope: context.scope };
|
|
320
|
+
}
|
|
321
|
+
if (context.forceJson) {
|
|
322
|
+
console.log(JSON.stringify(obj, null, 2));
|
|
323
|
+
} else if (!isTty()) {
|
|
324
|
+
console.log(JSON.stringify(obj));
|
|
325
|
+
} else {
|
|
326
|
+
pretty(obj);
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
function progress(message) {
|
|
330
|
+
if (isTty() && !context.quiet) console.error(message);
|
|
331
|
+
}
|
|
332
|
+
var notesShown = /* @__PURE__ */ new Set();
|
|
333
|
+
function note(message) {
|
|
334
|
+
if (notesShown.has(message)) return;
|
|
335
|
+
notesShown.add(message);
|
|
336
|
+
progress(message);
|
|
337
|
+
}
|
|
338
|
+
function selectedProfile() {
|
|
339
|
+
if (context.profileFlag !== void 0) return { name: context.profileFlag, source: "flag" };
|
|
340
|
+
const name = process.env.ENGINI_PROFILE;
|
|
341
|
+
if (!name) return void 0;
|
|
342
|
+
const problem = validateProfileName(name);
|
|
343
|
+
if (problem) fail(2 /* USAGE */, `ENGINI_PROFILE: ${problem}`);
|
|
344
|
+
if (process.env.ENGINI_API_TOKEN) {
|
|
345
|
+
fail(
|
|
346
|
+
2 /* USAGE */,
|
|
347
|
+
"ENGINI_PROFILE and ENGINI_API_TOKEN are both set - the CLI will not guess which account you mean.",
|
|
348
|
+
"Unset one of them, or pass --profile <name> to choose."
|
|
349
|
+
);
|
|
350
|
+
}
|
|
351
|
+
return { name, source: "env" };
|
|
352
|
+
}
|
|
353
|
+
function profileResumeFlag() {
|
|
354
|
+
const selected = selectedProfile();
|
|
355
|
+
let out = selected ? ` --profile ${selected.name}` : "";
|
|
356
|
+
const ws = context.workspaceFlag ?? process.env.ENGINI_WORKSPACE_ID;
|
|
357
|
+
const env = context.environmentFlag ?? process.env.ENGINI_ENVIRONMENT_ID;
|
|
358
|
+
if (ws && env) out += ` --workspace ${ws} --environment ${env}`;
|
|
359
|
+
return out;
|
|
360
|
+
}
|
|
361
|
+
var LEGACY_KEY_VAR = "ENGINI_API_KEY";
|
|
362
|
+
function assertNoLegacyKeyEnv() {
|
|
363
|
+
if (!process.env[LEGACY_KEY_VAR]) return;
|
|
364
|
+
fail(
|
|
365
|
+
2 /* USAGE */,
|
|
366
|
+
`${LEGACY_KEY_VAR} is no longer read by the engini CLI.`,
|
|
367
|
+
`Save the key in a profile: printf %s "$KEY" | engini login key --profile ci, then use --profile ci. (Unset ${LEGACY_KEY_VAR} first - this check runs on every command.)`
|
|
368
|
+
);
|
|
369
|
+
}
|
|
370
|
+
function fail(code, message, hint, extra) {
|
|
371
|
+
if (isTty()) {
|
|
372
|
+
console.error(`Error: ${message}`);
|
|
373
|
+
if (hint) console.error(`Hint: ${hint}`);
|
|
374
|
+
if (extra?.diagnostics?.length) {
|
|
375
|
+
for (const line of diagnosticTable(extra.diagnostics)) console.error(line);
|
|
376
|
+
}
|
|
377
|
+
} else {
|
|
378
|
+
const payload = {
|
|
379
|
+
error: ERROR_NAMES[code] ?? "Error",
|
|
380
|
+
message,
|
|
381
|
+
exit_code: code
|
|
382
|
+
};
|
|
383
|
+
if (hint) payload.hint = hint;
|
|
384
|
+
if (extra?.code !== void 0) payload.code = extra.code;
|
|
385
|
+
if (extra?.path) payload.path = extra.path;
|
|
386
|
+
if (extra?.currentRevisionId != null) payload.current_revision_id = extra.currentRevisionId;
|
|
387
|
+
if (extra?.diagnostics?.length) payload.diagnostics = extra.diagnostics;
|
|
388
|
+
console.error(JSON.stringify(payload));
|
|
389
|
+
}
|
|
390
|
+
throw new CliError(code);
|
|
391
|
+
}
|
|
392
|
+
function diagnosticTable(rows) {
|
|
393
|
+
const header = ["SEVERITY", "CODE", "STEP", "FIELD", "MESSAGE"];
|
|
394
|
+
const body = rows.map((d) => [d.severity, d.code, d.stepKey ?? "-", d.field ?? "-", d.message]);
|
|
395
|
+
const widths = header.map((h, i) => Math.max(h.length, ...body.map((r) => r[i].length)));
|
|
396
|
+
const line = (cells) => cells.map((c, i) => i === cells.length - 1 ? c : c.padEnd(widths[i])).join(" ");
|
|
397
|
+
return [line(header), ...body.map(line)];
|
|
398
|
+
}
|
|
399
|
+
function mapCommanderExitCode(exitCode) {
|
|
400
|
+
const code = exitCode ?? 1;
|
|
401
|
+
return code === 0 ? 0 /* OK */ : 2 /* USAGE */;
|
|
402
|
+
}
|
|
403
|
+
function maskSecret(value) {
|
|
404
|
+
return value.length > 8 ? `${value.slice(0, 4)}\u2026${value.slice(-4)}` : "****";
|
|
405
|
+
}
|
|
406
|
+
async function confirmOrFail(prompt, opts) {
|
|
407
|
+
if (opts.force) return;
|
|
408
|
+
if (isInteractive()) {
|
|
409
|
+
if (!await confirm(prompt)) {
|
|
410
|
+
throw new CliError(0 /* OK */);
|
|
411
|
+
}
|
|
412
|
+
return;
|
|
413
|
+
}
|
|
414
|
+
fail(2 /* USAGE */, `${prompt} Pass --force to proceed non-interactively.`);
|
|
415
|
+
}
|
|
416
|
+
var SCHEMA_VERSION = "1";
|
|
417
|
+
var UNIVERSAL_FLAGS = /* @__PURE__ */ new Set(["--json", "--quiet", "--schema", "--dry-run"]);
|
|
418
|
+
function schemaKey(name) {
|
|
419
|
+
return name.replace(/^--?/, "").replace(/-/g, "_");
|
|
420
|
+
}
|
|
421
|
+
function optionTakesValue(option) {
|
|
422
|
+
return option.required || option.optional;
|
|
423
|
+
}
|
|
424
|
+
function buildSchema(command, mutating) {
|
|
425
|
+
const args = {};
|
|
426
|
+
for (const arg of command.registeredArguments) {
|
|
427
|
+
args[schemaKey(arg.name())] = { type: "string", required: arg.required };
|
|
428
|
+
}
|
|
429
|
+
for (const option of command.options) {
|
|
430
|
+
if (UNIVERSAL_FLAGS.has(option.long ?? "")) continue;
|
|
431
|
+
const key = schemaKey(option.long ?? option.short ?? "");
|
|
432
|
+
args[key] = {
|
|
433
|
+
type: optionTakesValue(option) ? "string" : "boolean",
|
|
434
|
+
required: option.mandatory
|
|
435
|
+
};
|
|
436
|
+
}
|
|
437
|
+
return {
|
|
438
|
+
$schema: "https://json-schema.org/draft/2020-12/schema",
|
|
439
|
+
version: SCHEMA_VERSION,
|
|
440
|
+
mutating,
|
|
441
|
+
args,
|
|
442
|
+
output: null
|
|
443
|
+
};
|
|
444
|
+
}
|
|
445
|
+
function rootProfileFlag(command) {
|
|
446
|
+
let root = command;
|
|
447
|
+
while (root.parent) root = root.parent;
|
|
448
|
+
const value = root === command ? void 0 : root.opts().profile;
|
|
449
|
+
return typeof value === "string" ? value : void 0;
|
|
450
|
+
}
|
|
451
|
+
function addUniversalOptions(command, opts = {}) {
|
|
452
|
+
command.option("--json", "Pretty JSON output").option("--quiet", "Suppress non-essential output").option("--schema", "Print this command's args/output schema as JSON");
|
|
453
|
+
if (opts.profile !== false) {
|
|
454
|
+
command.option("--profile <name>", "Use this profile for this command").option("--workspace <id>", "Act in this workspace (GUID; with --environment; browser-login profiles)").option("--environment <id>", "Act in this environment (GUID; with --workspace)");
|
|
455
|
+
}
|
|
456
|
+
if (opts.mutating) {
|
|
457
|
+
command.option("--dry-run", "Preview without executing");
|
|
458
|
+
}
|
|
459
|
+
return command;
|
|
460
|
+
}
|
|
461
|
+
async function runCommand(command, opts, mutating, body, options = {}) {
|
|
462
|
+
if (opts.schema) {
|
|
463
|
+
console.log(JSON.stringify(buildSchema(command, mutating), null, 2));
|
|
464
|
+
throw new CliError(0 /* OK */);
|
|
465
|
+
}
|
|
466
|
+
const local = typeof opts.profile === "string" ? opts.profile : void 0;
|
|
467
|
+
const global = rootProfileFlag(command);
|
|
468
|
+
if (global !== void 0 && !command.options.some((o) => o.long === "--profile")) {
|
|
469
|
+
fail(2 /* USAGE */, "--profile does not apply to this command.");
|
|
470
|
+
}
|
|
471
|
+
if (local !== void 0 && global !== void 0 && local !== global) {
|
|
472
|
+
fail(2 /* USAGE */, `--profile was given twice with different values ("${global}" and "${local}").`);
|
|
473
|
+
}
|
|
474
|
+
const profile = local ?? global;
|
|
475
|
+
if (profile !== void 0) {
|
|
476
|
+
const problem = validateProfileName(profile);
|
|
477
|
+
if (problem) fail(2 /* USAGE */, `--profile: ${problem}`);
|
|
478
|
+
}
|
|
479
|
+
setOutputContext({
|
|
480
|
+
forceJson: Boolean(opts.json),
|
|
481
|
+
quiet: Boolean(opts.quiet),
|
|
482
|
+
dryRun: Boolean(opts.dryRun),
|
|
483
|
+
profileFlag: profile,
|
|
484
|
+
workspaceFlag: typeof opts.workspace === "string" ? opts.workspace : void 0,
|
|
485
|
+
environmentFlag: typeof opts.environment === "string" ? opts.environment : void 0,
|
|
486
|
+
mutating,
|
|
487
|
+
needsPair: Boolean(options.needsPair)
|
|
488
|
+
});
|
|
489
|
+
try {
|
|
490
|
+
assertNoLegacyKeyEnv();
|
|
491
|
+
if (!options.offline) await (await import("./session-IWURAIVM.js")).preflight();
|
|
492
|
+
await body();
|
|
493
|
+
} catch (err) {
|
|
494
|
+
if (err instanceof PromptCancelled) {
|
|
495
|
+
fail(2 /* USAGE */, "Cancelled.");
|
|
496
|
+
}
|
|
497
|
+
if (err instanceof PromptStreamEnded) {
|
|
498
|
+
fail(
|
|
499
|
+
2 /* USAGE */,
|
|
500
|
+
"Input ended before the prompt was answered.",
|
|
501
|
+
"Pass the required values as flags when running non-interactively."
|
|
502
|
+
);
|
|
503
|
+
}
|
|
504
|
+
throw err;
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
// src/config.ts
|
|
509
|
+
var CONFIG_SCHEMA_VERSION = 2;
|
|
510
|
+
var DEFAULT_API_URL = "https://api.engini.io";
|
|
511
|
+
var DEFAULT_IDENTITY_URL = "https://app.engini.io";
|
|
512
|
+
function profileDefaults() {
|
|
513
|
+
return { api_url: DEFAULT_API_URL, identity_url: DEFAULT_IDENTITY_URL };
|
|
514
|
+
}
|
|
515
|
+
function emptyConfig() {
|
|
516
|
+
return { config_schema_version: CONFIG_SCHEMA_VERSION, profiles: {} };
|
|
517
|
+
}
|
|
518
|
+
var PROFILE_NAME = /^[a-z0-9][a-z0-9_-]{0,63}$/;
|
|
519
|
+
var WINDOWS_DEVICE = /^(con|prn|aux|nul|com[0-9]|lpt[0-9])$/;
|
|
520
|
+
function validateProfileName(name) {
|
|
521
|
+
if (!PROFILE_NAME.test(name)) {
|
|
522
|
+
return `Invalid profile name "${name}": use 1-64 lowercase letters, digits, "-" or "_", starting with a letter or digit.`;
|
|
523
|
+
}
|
|
524
|
+
if (WINDOWS_DEVICE.test(name)) return `Invalid profile name "${name}": reserved on Windows.`;
|
|
525
|
+
return null;
|
|
526
|
+
}
|
|
527
|
+
function getProfile(config, name) {
|
|
528
|
+
return Object.hasOwn(config.profiles, name) ? config.profiles[name] : void 0;
|
|
529
|
+
}
|
|
530
|
+
function configPath() {
|
|
531
|
+
const base = process.platform === "win32" ? process.env.APPDATA ?? homedir() : process.env.XDG_CONFIG_HOME ?? join(homedir(), ".config");
|
|
532
|
+
return join(base, "engini", "config.toml");
|
|
533
|
+
}
|
|
534
|
+
function asString(value) {
|
|
535
|
+
return typeof value === "string" ? value : void 0;
|
|
536
|
+
}
|
|
537
|
+
function readProfile(data) {
|
|
538
|
+
const profile = { ...data, ...profileDefaults() };
|
|
539
|
+
profile.api_url = asString(data.api_url) ?? profile.api_url;
|
|
540
|
+
profile.identity_url = asString(data.identity_url) ?? profile.identity_url;
|
|
541
|
+
profile.api_key = asString(data.api_key);
|
|
542
|
+
profile.api_token = asString(data.api_token);
|
|
543
|
+
profile.company_token = asString(data.company_token);
|
|
544
|
+
profile.company = asString(data.company);
|
|
545
|
+
profile.workspace = asString(data.workspace);
|
|
546
|
+
profile.environment = asString(data.environment);
|
|
547
|
+
profile.description = asString(data.description);
|
|
548
|
+
profile.auth_kind = typeof data.auth_kind === "string" ? data.auth_kind : void 0;
|
|
549
|
+
profile.login_method = typeof data.login_method === "string" ? data.login_method : void 0;
|
|
550
|
+
return profile;
|
|
551
|
+
}
|
|
552
|
+
var FLAT_KEYS = ["api_url", "identity_url", "api_key", "api_token", "company_token", "auth_kind"];
|
|
553
|
+
function isRecord(value) {
|
|
554
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
555
|
+
}
|
|
556
|
+
function loadConfig(path = configPath()) {
|
|
557
|
+
const config = emptyConfig();
|
|
558
|
+
if (!existsSync(path)) return config;
|
|
559
|
+
let data;
|
|
560
|
+
try {
|
|
561
|
+
data = parse(readFileSync(path, "utf8"));
|
|
562
|
+
} catch {
|
|
563
|
+
fail(1 /* GENERIC */, `Cannot parse ${path}`, "Fix or delete the file, then run `engini login`.");
|
|
564
|
+
}
|
|
565
|
+
if (isRecord(data.profiles)) {
|
|
566
|
+
for (const [name, value] of Object.entries(data.profiles)) {
|
|
567
|
+
if (validateProfileName(name) === null && isRecord(value)) config.profiles[name] = readProfile(value);
|
|
568
|
+
}
|
|
569
|
+
config.default_profile = asString(data.default_profile) ?? asString(data.active_profile);
|
|
570
|
+
const known = [
|
|
571
|
+
"config_schema_version",
|
|
572
|
+
"default_profile",
|
|
573
|
+
"active_profile",
|
|
574
|
+
"profiles",
|
|
575
|
+
"api_key",
|
|
576
|
+
"api_token",
|
|
577
|
+
"company_token"
|
|
578
|
+
];
|
|
579
|
+
const extra = Object.fromEntries(Object.entries(data).filter(([key]) => !known.includes(key)));
|
|
580
|
+
if (Object.keys(extra).length > 0) config.extra = extra;
|
|
581
|
+
} else if (FLAT_KEYS.some((key) => key in data)) {
|
|
582
|
+
const { config_schema_version: _version, ...flat } = data;
|
|
583
|
+
config.profiles.default = readProfile(flat);
|
|
584
|
+
config.default_profile = "default";
|
|
585
|
+
}
|
|
586
|
+
return config;
|
|
587
|
+
}
|
|
588
|
+
function saveConfig(config, path = configPath()) {
|
|
589
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
590
|
+
const profiles = {};
|
|
591
|
+
for (const [name, profile] of Object.entries(config.profiles)) {
|
|
592
|
+
const row = {};
|
|
593
|
+
for (const [key, value] of Object.entries(profile)) if (value !== void 0) row[key] = value;
|
|
594
|
+
profiles[name] = row;
|
|
595
|
+
}
|
|
596
|
+
const data = { ...config.extra, config_schema_version: CONFIG_SCHEMA_VERSION };
|
|
597
|
+
if (config.default_profile !== void 0) data.default_profile = config.default_profile;
|
|
598
|
+
data.profiles = profiles;
|
|
599
|
+
const temp = `${path}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`;
|
|
600
|
+
try {
|
|
601
|
+
writeFileSync(temp, stringify(data), { mode: 384, flag: "wx" });
|
|
602
|
+
if (process.platform !== "win32") chmodSync(temp, 384);
|
|
603
|
+
renameWithRetry(temp, path);
|
|
604
|
+
} finally {
|
|
605
|
+
rmSync(temp, { force: true });
|
|
606
|
+
}
|
|
607
|
+
}
|
|
608
|
+
function renameWithRetry(from, to) {
|
|
609
|
+
for (let attempt = 1; ; attempt++) {
|
|
610
|
+
try {
|
|
611
|
+
renameSync(from, to);
|
|
612
|
+
return;
|
|
613
|
+
} catch (err) {
|
|
614
|
+
const code = err.code;
|
|
615
|
+
if (attempt >= 3 || code !== "EPERM" && code !== "EBUSY") throw err;
|
|
616
|
+
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 50 * attempt);
|
|
617
|
+
}
|
|
618
|
+
}
|
|
619
|
+
}
|
|
620
|
+
var sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
621
|
+
var LOCK_WAIT_MS = 2e3;
|
|
622
|
+
var LOCK_STALE_MS = 1e4;
|
|
623
|
+
var LOCK_WAIT_ROTATED_MS = LOCK_STALE_MS + 2e3;
|
|
624
|
+
var OAUTH_FIELDS = [
|
|
625
|
+
"auth_url",
|
|
626
|
+
"access_token",
|
|
627
|
+
"access_expires_at",
|
|
628
|
+
"refresh_token",
|
|
629
|
+
"session_expires_at",
|
|
630
|
+
"scope_mode",
|
|
631
|
+
"workspace_id",
|
|
632
|
+
"environment_id"
|
|
633
|
+
];
|
|
634
|
+
async function withFileLock(lock, opts, fn) {
|
|
635
|
+
mkdirSync(dirname(lock), { recursive: true });
|
|
636
|
+
const token = `${process.pid}.${randomBytes(8).toString("hex")}`;
|
|
637
|
+
const deadline = Date.now() + opts.waitMs;
|
|
638
|
+
for (; ; ) {
|
|
639
|
+
try {
|
|
640
|
+
writeFileSync(lock, token, { flag: "wx", mode: 384 });
|
|
641
|
+
break;
|
|
642
|
+
} catch (err) {
|
|
643
|
+
if (err.code !== "EEXIST") throw err;
|
|
644
|
+
try {
|
|
645
|
+
if (Date.now() - statSync(lock).mtimeMs > opts.staleMs) {
|
|
646
|
+
const stale = `${lock}.stale.${randomBytes(4).toString("hex")}`;
|
|
647
|
+
renameSync(lock, stale);
|
|
648
|
+
if (Date.now() - statSync(stale).mtimeMs <= opts.staleMs) {
|
|
649
|
+
try {
|
|
650
|
+
linkSync(stale, lock);
|
|
651
|
+
} catch {
|
|
652
|
+
}
|
|
653
|
+
}
|
|
654
|
+
rmSync(stale, { force: true });
|
|
655
|
+
continue;
|
|
656
|
+
}
|
|
657
|
+
} catch {
|
|
658
|
+
continue;
|
|
659
|
+
}
|
|
660
|
+
if (Date.now() > deadline) fail(1 /* GENERIC */, opts.lockedMessage);
|
|
661
|
+
await sleep(25);
|
|
662
|
+
}
|
|
663
|
+
}
|
|
664
|
+
try {
|
|
665
|
+
return await fn();
|
|
666
|
+
} finally {
|
|
667
|
+
try {
|
|
668
|
+
if (readFileSync(lock, "utf8") === token) rmSync(lock, { force: true });
|
|
669
|
+
} catch {
|
|
670
|
+
}
|
|
671
|
+
}
|
|
672
|
+
}
|
|
673
|
+
async function updateConfig(mutate, path = configPath(), waitMs = LOCK_WAIT_MS) {
|
|
674
|
+
const lock = `${path}.lock`;
|
|
675
|
+
return withFileLock(
|
|
676
|
+
lock,
|
|
677
|
+
{ waitMs, staleMs: LOCK_STALE_MS, lockedMessage: `Config is locked (${lock}); try again.` },
|
|
678
|
+
() => {
|
|
679
|
+
const config = loadConfig(path);
|
|
680
|
+
mutate(config);
|
|
681
|
+
saveConfig(config, path);
|
|
682
|
+
return config;
|
|
683
|
+
}
|
|
684
|
+
);
|
|
685
|
+
}
|
|
686
|
+
|
|
687
|
+
// src/active.ts
|
|
688
|
+
function resolveActive(config = loadConfig()) {
|
|
689
|
+
const selected = selectedProfile();
|
|
690
|
+
if (selected) {
|
|
691
|
+
const profile = getProfile(config, selected.name);
|
|
692
|
+
if (!profile) {
|
|
693
|
+
fail(
|
|
694
|
+
4 /* NOT_FOUND */,
|
|
695
|
+
`Unknown profile "${selected.name}".`,
|
|
696
|
+
`List profiles with \`engini profile list\`, or create it with \`engini login key --profile ${selected.name}\`.`
|
|
697
|
+
);
|
|
698
|
+
}
|
|
699
|
+
return { name: selected.name, source: selected.source, profile };
|
|
700
|
+
}
|
|
701
|
+
const defaultName = config.default_profile;
|
|
702
|
+
const defaultProfile = defaultName !== void 0 ? getProfile(config, defaultName) : void 0;
|
|
703
|
+
if (process.env.ENGINI_API_TOKEN) {
|
|
704
|
+
return {
|
|
705
|
+
source: "env-credential",
|
|
706
|
+
profile: {
|
|
707
|
+
...profileDefaults(),
|
|
708
|
+
...defaultProfile && { api_url: defaultProfile.api_url, identity_url: defaultProfile.identity_url }
|
|
709
|
+
}
|
|
710
|
+
};
|
|
711
|
+
}
|
|
712
|
+
if (defaultProfile) return { name: defaultName, source: "default", profile: defaultProfile };
|
|
713
|
+
return { source: "none", profile: profileDefaults() };
|
|
714
|
+
}
|
|
715
|
+
function sandboxKey(active = resolveActive()) {
|
|
716
|
+
if (active.name !== void 0) return active.name;
|
|
717
|
+
const token = process.env.ENGINI_API_TOKEN;
|
|
718
|
+
if (active.source === "env-credential" && token) {
|
|
719
|
+
const company = process.env.ENGINI_COMPANY_TOKEN ?? "";
|
|
720
|
+
return `_env-${createHash("sha256").update(`${token}\0${company}`).digest("hex").slice(0, 8)}`;
|
|
721
|
+
}
|
|
722
|
+
return "_none";
|
|
723
|
+
}
|
|
724
|
+
|
|
725
|
+
// src/scope.ts
|
|
726
|
+
var GUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
727
|
+
var WS_VAR = "ENGINI_WORKSPACE_ID";
|
|
728
|
+
var ENV_VAR = "ENGINI_ENVIRONMENT_ID";
|
|
729
|
+
function guidProblem(value, label) {
|
|
730
|
+
return GUID.test(value) ? null : `${label} must be a workspace/environment id (a GUID), got "${value}".`;
|
|
731
|
+
}
|
|
732
|
+
function checkedPair(workspace, environment, labels) {
|
|
733
|
+
if (!workspace && !environment) return void 0;
|
|
734
|
+
if (!workspace || !environment) {
|
|
735
|
+
fail(2 /* USAGE */, `Pass ${labels[0]} and ${labels[1]} together, or neither.`);
|
|
736
|
+
}
|
|
737
|
+
for (const [value, label] of [
|
|
738
|
+
[workspace, labels[0]],
|
|
739
|
+
[environment, labels[1]]
|
|
740
|
+
]) {
|
|
741
|
+
const problem = guidProblem(value, label);
|
|
742
|
+
if (problem) fail(2 /* USAGE */, problem);
|
|
743
|
+
}
|
|
744
|
+
return { workspaceId: workspace, environmentId: environment };
|
|
745
|
+
}
|
|
746
|
+
function namedPair() {
|
|
747
|
+
const flags = pairFlags();
|
|
748
|
+
const fromFlag = checkedPair(flags.workspace, flags.environment, ["--workspace", "--environment"]);
|
|
749
|
+
if (fromFlag) return { pair: fromFlag, source: "flag" };
|
|
750
|
+
const fromEnv = checkedPair(process.env[WS_VAR], process.env[ENV_VAR], [WS_VAR, ENV_VAR]);
|
|
751
|
+
if (fromEnv) return { pair: fromEnv, source: "env" };
|
|
752
|
+
return void 0;
|
|
753
|
+
}
|
|
754
|
+
function samePair(a, b) {
|
|
755
|
+
return a.workspaceId.toLowerCase() === b.workspaceId.toLowerCase() && a.environmentId.toLowerCase() === b.environmentId.toLowerCase();
|
|
756
|
+
}
|
|
757
|
+
function profilePair(active) {
|
|
758
|
+
const { workspace_id: ws, environment_id: env } = active.profile;
|
|
759
|
+
return ws && env ? { workspaceId: ws, environmentId: env } : void 0;
|
|
760
|
+
}
|
|
761
|
+
function resolvePair(active) {
|
|
762
|
+
const named = namedPair();
|
|
763
|
+
const profile = active.profile;
|
|
764
|
+
const isOAuth = active.source !== "env-credential" && profile.auth_kind === "oauth";
|
|
765
|
+
if (!isOAuth) {
|
|
766
|
+
const hasCredential = active.source === "env-credential" || Boolean(profile.api_key || profile.api_token);
|
|
767
|
+
if (named && hasCredential) {
|
|
768
|
+
const what = profile.api_key && active.source !== "env-credential" ? "an API key" : "a token credential";
|
|
769
|
+
fail(
|
|
770
|
+
2 /* USAGE */,
|
|
771
|
+
`--workspace/--environment (or ${WS_VAR}/${ENV_VAR}) cannot be used with ${what}.`,
|
|
772
|
+
"An API key is pinned to one workspace and environment; pick another key's profile with --profile instead."
|
|
773
|
+
);
|
|
774
|
+
}
|
|
775
|
+
return { source: profile.api_key && active.source !== "env-credential" ? "key" : "none" };
|
|
776
|
+
}
|
|
777
|
+
if (named) {
|
|
778
|
+
const own = profilePair(active);
|
|
779
|
+
if (profile.scope_mode === "pair" && own && !samePair(own, named.pair)) {
|
|
780
|
+
fail(
|
|
781
|
+
2 /* USAGE */,
|
|
782
|
+
`Profile "${active.name}" was approved for one workspace/environment only (${own.workspaceId}/${own.environmentId}).`,
|
|
783
|
+
`Drop --workspace/--environment, or run \`engini login --profile ${active.name}\` and approve "everything".`
|
|
784
|
+
);
|
|
785
|
+
}
|
|
786
|
+
return named;
|
|
787
|
+
}
|
|
788
|
+
const stored = profilePair(active);
|
|
789
|
+
if (stored) return { pair: stored, source: "profile" };
|
|
790
|
+
if (isMutating() || isPairRequired()) {
|
|
791
|
+
fail(
|
|
792
|
+
2 /* USAGE */,
|
|
793
|
+
`Profile "${active.name}" has no default workspace/environment, so this ${isMutating() ? "write has nowhere to land" : "command has no workspace to read from"}.`,
|
|
794
|
+
`Pass --workspace <id> --environment <id> (see \`engini whoami\`), or set a default with \`engini login --profile ${active.name} --workspace <id> --environment <id>\`.`
|
|
795
|
+
);
|
|
796
|
+
}
|
|
797
|
+
return { source: "none" };
|
|
798
|
+
}
|
|
799
|
+
function flattenScopes(scopes) {
|
|
800
|
+
const rows = [];
|
|
801
|
+
for (const ws of scopes ?? []) {
|
|
802
|
+
for (const env of ws.environments ?? []) {
|
|
803
|
+
rows.push({
|
|
804
|
+
workspace: { id: ws.id, name: ws.name ?? null },
|
|
805
|
+
environment: { id: env.id, name: env.name ?? null, type: env.type ?? null }
|
|
806
|
+
});
|
|
807
|
+
}
|
|
808
|
+
}
|
|
809
|
+
return rows;
|
|
810
|
+
}
|
|
811
|
+
function findScope(rows, pair) {
|
|
812
|
+
return rows.find((r) => samePair({ workspaceId: r.workspace.id, environmentId: r.environment.id }, pair));
|
|
813
|
+
}
|
|
814
|
+
|
|
815
|
+
// src/session.ts
|
|
816
|
+
var CLIENT_ID = "engini-cli";
|
|
817
|
+
var REFRESH_MARGIN_MS = 10 * 60 * 1e3;
|
|
818
|
+
var REFRESH_LOCK_WAIT_MS = 2e4;
|
|
819
|
+
var REFRESH_LOCK_STALE_MS = 6e4;
|
|
820
|
+
var REFRESH_TIMEOUT_MS = 15e3;
|
|
821
|
+
var REVOKE_TIMEOUT_MS = 5e3;
|
|
822
|
+
function refreshLockPath(profileName) {
|
|
823
|
+
return join2(dirname2(configPath()), `refresh-${profileName}.lock`);
|
|
824
|
+
}
|
|
825
|
+
function withRefreshLock(profileName, fn) {
|
|
826
|
+
const lock = refreshLockPath(profileName);
|
|
827
|
+
return withFileLock(
|
|
828
|
+
lock,
|
|
829
|
+
{
|
|
830
|
+
waitMs: REFRESH_LOCK_WAIT_MS,
|
|
831
|
+
staleMs: REFRESH_LOCK_STALE_MS,
|
|
832
|
+
lockedMessage: `Another engini process is refreshing profile "${profileName}" (${lock}); try again.`
|
|
833
|
+
},
|
|
834
|
+
fn
|
|
835
|
+
);
|
|
836
|
+
}
|
|
837
|
+
function expiresAtMs(value) {
|
|
838
|
+
const ms = value ? Date.parse(value) : Number.NaN;
|
|
839
|
+
return Number.isNaN(ms) ? 0 : ms;
|
|
840
|
+
}
|
|
841
|
+
function expiredMessage(name) {
|
|
842
|
+
return [
|
|
843
|
+
`Your engini session for profile ${name} expired.`,
|
|
844
|
+
`Run \`engini login --profile ${name}\`.`
|
|
845
|
+
];
|
|
846
|
+
}
|
|
847
|
+
async function ensureFreshSession(profileName, opts = {}) {
|
|
848
|
+
const quick = getProfile(loadConfig(), profileName);
|
|
849
|
+
if (!quick || quick.auth_kind !== "oauth") return;
|
|
850
|
+
if (!opts.force && expiresAtMs(quick.access_expires_at) - Date.now() >= REFRESH_MARGIN_MS) return;
|
|
851
|
+
await withRefreshLock(profileName, async () => {
|
|
852
|
+
const profile = getProfile(loadConfig(), profileName);
|
|
853
|
+
if (!profile || profile.auth_kind !== "oauth") return;
|
|
854
|
+
const remaining = expiresAtMs(profile.access_expires_at) - Date.now();
|
|
855
|
+
const rotatedByOther = opts.rejectedAccessToken !== void 0 && profile.access_token !== opts.rejectedAccessToken;
|
|
856
|
+
if (!opts.force && remaining >= REFRESH_MARGIN_MS) return;
|
|
857
|
+
if (opts.force && rotatedByOther && remaining > 0) return;
|
|
858
|
+
const [expired, relogin] = expiredMessage(profileName);
|
|
859
|
+
if (!profile.refresh_token || !profile.auth_url) fail(3 /* AUTH */, expired, relogin);
|
|
860
|
+
let res;
|
|
861
|
+
try {
|
|
862
|
+
res = await fetch(`${profile.auth_url.replace(/\/+$/, "")}/api/oauth/token`, {
|
|
863
|
+
method: "POST",
|
|
864
|
+
headers: { "content-type": "application/x-www-form-urlencoded", accept: "application/json" },
|
|
865
|
+
body: new URLSearchParams({
|
|
866
|
+
grant_type: "refresh_token",
|
|
867
|
+
refresh_token: profile.refresh_token,
|
|
868
|
+
client_id: CLIENT_ID
|
|
869
|
+
}).toString(),
|
|
870
|
+
signal: AbortSignal.timeout(REFRESH_TIMEOUT_MS)
|
|
871
|
+
});
|
|
872
|
+
} catch {
|
|
873
|
+
return keepOrFail(profileName, remaining, "could not reach the sign-in server");
|
|
874
|
+
}
|
|
875
|
+
if (res.status === 400 || res.status === 401) {
|
|
876
|
+
fail(3 /* AUTH */, expired, relogin);
|
|
877
|
+
}
|
|
878
|
+
if (!res.ok) return keepOrFail(profileName, remaining, `the sign-in server answered ${res.status}`);
|
|
879
|
+
let body;
|
|
880
|
+
try {
|
|
881
|
+
body = await res.json();
|
|
882
|
+
} catch {
|
|
883
|
+
return keepOrFail(profileName, remaining, "the sign-in server sent an unreadable answer");
|
|
884
|
+
}
|
|
885
|
+
if (typeof body.access_token !== "string" || typeof body.expires_in !== "number") {
|
|
886
|
+
return keepOrFail(profileName, remaining, "the sign-in server sent an incomplete answer");
|
|
887
|
+
}
|
|
888
|
+
const access = body.access_token;
|
|
889
|
+
const refresh = typeof body.refresh_token === "string" ? body.refresh_token : profile.refresh_token;
|
|
890
|
+
const accessExpiresAt = new Date(Date.now() + body.expires_in * 1e3).toISOString();
|
|
891
|
+
await updateConfig((config) => {
|
|
892
|
+
const current = getProfile(config, profileName);
|
|
893
|
+
if (!current) return;
|
|
894
|
+
current.access_token = access;
|
|
895
|
+
current.refresh_token = refresh;
|
|
896
|
+
current.access_expires_at = accessExpiresAt;
|
|
897
|
+
}, void 0, LOCK_WAIT_ROTATED_MS);
|
|
898
|
+
});
|
|
899
|
+
}
|
|
900
|
+
function keepOrFail(profileName, remainingMs, why) {
|
|
901
|
+
if (remainingMs > 0) {
|
|
902
|
+
note(`Could not refresh the engini session for profile ${profileName} (${why}); using the current token.`);
|
|
903
|
+
return;
|
|
904
|
+
}
|
|
905
|
+
fail(1 /* GENERIC */, `Could not refresh the engini session for profile ${profileName}: ${why}.`, "Try again shortly.");
|
|
906
|
+
}
|
|
907
|
+
async function revokeSession(profile) {
|
|
908
|
+
if (!profile.auth_url || !profile.refresh_token) return false;
|
|
909
|
+
try {
|
|
910
|
+
const res = await fetch(`${profile.auth_url.replace(/\/+$/, "")}/api/oauth/revoke`, {
|
|
911
|
+
method: "POST",
|
|
912
|
+
headers: { "content-type": "application/x-www-form-urlencoded" },
|
|
913
|
+
body: new URLSearchParams({ token: profile.refresh_token, client_id: CLIENT_ID }).toString(),
|
|
914
|
+
signal: AbortSignal.timeout(REVOKE_TIMEOUT_MS)
|
|
915
|
+
});
|
|
916
|
+
return res.ok;
|
|
917
|
+
} catch {
|
|
918
|
+
return false;
|
|
919
|
+
}
|
|
920
|
+
}
|
|
921
|
+
async function preflight() {
|
|
922
|
+
const active = resolveActive();
|
|
923
|
+
const { pair, source } = resolvePair(active);
|
|
924
|
+
if (active.name === void 0 || active.source === "env-credential" || active.profile.auth_kind !== "oauth") {
|
|
925
|
+
return;
|
|
926
|
+
}
|
|
927
|
+
await ensureFreshSession(active.name);
|
|
928
|
+
setScopeContext({
|
|
929
|
+
workspace_id: pair?.workspaceId ?? null,
|
|
930
|
+
environment_id: pair?.environmentId ?? null,
|
|
931
|
+
source
|
|
932
|
+
});
|
|
933
|
+
if (isMutating() && pair) {
|
|
934
|
+
note(`Acting in ${pair.workspaceId}/${pair.environmentId} (from ${source}).`);
|
|
935
|
+
}
|
|
936
|
+
}
|
|
937
|
+
|
|
938
|
+
export {
|
|
939
|
+
DEFAULT_API_URL,
|
|
940
|
+
profileDefaults,
|
|
941
|
+
validateProfileName,
|
|
942
|
+
getProfile,
|
|
943
|
+
configPath,
|
|
944
|
+
loadConfig,
|
|
945
|
+
OAUTH_FIELDS,
|
|
946
|
+
updateConfig,
|
|
947
|
+
openBrowser,
|
|
948
|
+
PromptCancelled,
|
|
949
|
+
PromptStreamEnded,
|
|
950
|
+
readStdin,
|
|
951
|
+
confirm,
|
|
952
|
+
promptText,
|
|
953
|
+
promptHidden,
|
|
954
|
+
resolveActive,
|
|
955
|
+
sandboxKey,
|
|
956
|
+
checkedPair,
|
|
957
|
+
resolvePair,
|
|
958
|
+
flattenScopes,
|
|
959
|
+
findScope,
|
|
960
|
+
CLIENT_ID,
|
|
961
|
+
refreshLockPath,
|
|
962
|
+
withRefreshLock,
|
|
963
|
+
ensureFreshSession,
|
|
964
|
+
revokeSession,
|
|
965
|
+
preflight,
|
|
966
|
+
Exit,
|
|
967
|
+
CliError,
|
|
968
|
+
isTty,
|
|
969
|
+
isInteractive,
|
|
970
|
+
dryRun,
|
|
971
|
+
outputFlags,
|
|
972
|
+
printOutput,
|
|
973
|
+
progress,
|
|
974
|
+
note,
|
|
975
|
+
selectedProfile,
|
|
976
|
+
profileResumeFlag,
|
|
977
|
+
assertNoLegacyKeyEnv,
|
|
978
|
+
fail,
|
|
979
|
+
mapCommanderExitCode,
|
|
980
|
+
maskSecret,
|
|
981
|
+
confirmOrFail,
|
|
982
|
+
addUniversalOptions,
|
|
983
|
+
runCommand
|
|
984
|
+
};
|