1xops 0.2.4 → 0.2.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/package.json +1 -1
  2. package/src/commands.mjs +146 -23
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "1xops",
3
- "version": "0.2.4",
3
+ "version": "0.2.6",
4
4
  "description": "1xops by OceanSoft.io: set up the 1xops plugin, settings and read-only cloud connectors for an organisation, team or person. Native Node.js, no dependencies.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "Nhat-Thanh Nguyen <nnthanh101@gmail.com> (https://www.oceansoft.io)",
package/src/commands.mjs CHANGED
@@ -1,8 +1,9 @@
1
1
  // The 1xops commands: doctor, install, config, env, profiles, setup. Same behaviour as the Python
2
2
  // package (packages/python/src/one_xops/cli.py and setup.py). Nothing changes unless --yes is given.
3
3
  import { spawnSync } from 'node:child_process';
4
- import { accessSync, constants, existsSync, mkdirSync, renameSync, writeFileSync } from 'node:fs';
5
- import path from 'node:path';
4
+ import { accessSync, constants, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
5
+ import { homedir } from 'node:os';
6
+ import path, { join } from 'node:path';
6
7
  import { createInterface } from 'node:readline/promises';
7
8
  import { styleText } from 'node:util';
8
9
  import * as cf from './config-file.mjs';
@@ -41,12 +42,51 @@ export function accessFromRole(arn = '') {
41
42
  }
42
43
  const ACCESS = { read: 'read-only', write: 'can change things: use a read-only role', unknown: 'access unknown: use a read-only role' };
43
44
 
45
+ // The same look as the Python CLI's rich table: a heavy header, light rows, colour on a terminal. No dependency.
46
+ // On a terminal the table fits the window: the widest columns shrink and their cells wrap, as rich does.
47
+ // Piped (the assistant, evidence) it sizes to its content, so both CLIs print the same bytes.
48
+ const visible = (s) => String(s).replace(/\x1b\[[0-9;]*m/g, '').length;
49
+ function wrap(text, w) {
50
+ if (visible(text) <= w) return [String(text)];
51
+ // A coloured cell wraps on its plain text; each line then gets the colour again, so no code is cut or bleeds.
52
+ const styled = String(text).match(/^(\x1b\[[0-9;]*m)(.*?)(\x1b\[[0-9;]*m)$/s);
53
+ if (styled) return wrap(styled[2], w).map((l) => styled[1] + l + styled[3]);
54
+ const lines = [];
55
+ let line = '';
56
+ for (const word of String(text).split(' ')) {
57
+ for (let piece = word; piece.length; ) {
58
+ const room = line ? w - line.length - 1 : w;
59
+ if (piece.length <= room) { line = line ? `${line} ${piece}` : piece; piece = ''; }
60
+ else if (line) { lines.push(line); line = ''; }
61
+ else { lines.push(piece.slice(0, w)); piece = piece.slice(w); }
62
+ }
63
+ }
64
+ if (line) lines.push(line);
65
+ return lines;
66
+ }
44
67
  function table(title, columns, rows) {
45
- const width = columns.map((c, i) => Math.max(c.length, ...rows.map((r) => String(r[i]).length)));
46
- const line = (cells) => cells.map((c, i) => String(c).padEnd(width[i])).join(' ');
47
- console.log(color('bold', title));
48
- console.log(color('dim', line(columns)));
49
- for (const r of rows) console.log(line(r));
68
+ const width = columns.map((c, i) => Math.max(c.length, ...rows.map((r) => visible(r[i]))));
69
+ const limit = process.stdout.isTTY ? (process.stdout.columns || 80) - (3 * width.length + 1) : Infinity;
70
+ while (width.reduce((a, w) => a + w, 0) > limit) {
71
+ const i = width.indexOf(Math.max(...width));
72
+ if (width[i] <= 8) break;
73
+ width[i] -= 1;
74
+ }
75
+ const pad = (c, i) => String(c) + ' '.repeat(Math.max(0, width[i] - visible(c)));
76
+ const cells = (r, bar) => {
77
+ const parts = r.map((c, i) => wrap(c, width[i]));
78
+ const height = Math.max(...parts.map((p) => p.length));
79
+ return Array.from({ length: height }, (_, k) => `${bar} ${parts.map((p, i) => pad(p[k] ?? '', i)).join(` ${bar} `)} ${bar}`).join('\n');
80
+ };
81
+ const rule = (l, m, r, h) => l + width.map((w) => h.repeat(w + 2)).join(m) + r;
82
+ const total = width.reduce((a, w) => a + w + 3, 1);
83
+ const left = Math.max(0, Math.floor((total - title.length) / 2));
84
+ console.log(' '.repeat(left) + color('bold', title) + ' '.repeat(Math.max(0, total - left - title.length)));
85
+ console.log(rule('┏', '┳', '┓', '━'));
86
+ console.log(cells(columns.map((c) => color('bold', c)), '┃'));
87
+ console.log(rule('┡', '╇', '┩', '━'));
88
+ for (const r of rows) console.log(cells(r, '│'));
89
+ console.log(rule('└', '┴', '┘', '─'));
50
90
  }
51
91
 
52
92
  // ── doctor ──────────────────────────────────────────────────────────────────
@@ -155,11 +195,24 @@ export function checkConnectors(file) {
155
195
  const RESULT_STYLE = { ok: 'green', ready: 'green', missing: 'red', 'signed out': 'yellow', check: 'yellow' };
156
196
 
157
197
  export function doctor(opts, version) {
198
+ // The identity calls take seconds; a status line on a terminal (cleared after), nothing when piped.
199
+ const tty = process.stdout.isTTY;
200
+ if (tty) process.stdout.write(color('dim', 'Checking tools, sign-ins and connectors (read-only)…'));
158
201
  const rows = [...checkTools(), ...checkSignIn(opts['aws-profile'])];
202
+ const connectors = checkConnectors(opts.file);
203
+ if (tty) process.stdout.write('\r\x1b[K');
159
204
  const shown = rows.map(([name, required, ok, detail]) => [name, required ? 'required' : 'optional', ok ? 'ok' : required ? 'missing' : 'check', scrub(detail)]);
160
- shown.push(...checkConnectors(opts.file).map(([name, status, fix]) => [name, 'connector', status, scrub(fix)]));
205
+ shown.push(...connectors.map(([name, status, fix]) => [name, 'connector', status, scrub(fix)]));
206
+ // Required tools and configured connectors that are not ok or ready. Optional tools stay in the table only.
207
+ const todo = shown.filter((r) => r[2] !== 'ok' && r[2] !== 'ready' && r[1] !== 'optional');
161
208
  for (const r of shown) r[2] = color(RESULT_STYLE[r[2]], r[2]);
162
209
  table(`1xops ${version} doctor`, ['check', 'needed', 'result', 'detail'], shown);
210
+ // What to do next, in table order (see todo above).
211
+ if (!todo.length) console.log(color('green', 'All set: nothing to fix.'));
212
+ else {
213
+ console.log(color('bold', 'Next:'));
214
+ todo.forEach((r, i) => console.log(` ${i + 1}. ${r[0]}: ${r[3]}`));
215
+ }
163
216
  const failed = rows.filter((r) => r[1] && !r[2]).map((r) => r[0]);
164
217
  if (failed.length) {
165
218
  console.log(color('red', `Required: ${failed.join(', ')}`));
@@ -206,21 +259,21 @@ function diffLines(a, b) {
206
259
  let i = 0, j = 0;
207
260
  while (i < n || j < m) {
208
261
  if (i < n && j < m && a[i] === b[j]) { out.push(` ${a[i]}`); i++; j++; }
209
- else if (j < m && (i === n || lcs[i][j + 1] >= lcs[i + 1][j])) out.push(`+${b[j++]}`);
210
- else out.push(`-${a[i++]}`);
262
+ else if (i < n && (j === m || lcs[i + 1][j] >= lcs[i][j + 1])) out.push(`-${a[i++]}`); // removed first, as difflib
263
+ else out.push(`+${b[j++]}`);
211
264
  }
212
265
  return out;
213
266
  }
214
267
 
215
- function showChange(file, before, after) {
268
+ function showChange(file, before, after, linesToo = true) {
216
269
  if (s.dumps(before) === s.dumps(after)) {
217
270
  console.log(color('dim', `${file}: already up to date`));
218
271
  return false;
219
272
  }
220
- console.log(`--- ${file}\n+++ ${file}`);
221
- for (const l of diffLines(s.dumps(before).trimEnd().split('\n'), s.dumps(after).trimEnd().split('\n'))) {
222
- if (l[0] !== ' ') console.log(l);
223
- }
273
+ const lines = diffLines(s.dumps(before).trimEnd().split('\n'), s.dumps(after).trimEnd().split('\n')).filter((l) => l[0] !== ' ');
274
+ const added = lines.filter((l) => l[0] === '+').length;
275
+ console.log(color('bold', `${file}: ${added} lines added, ${lines.length - added} removed`));
276
+ if (linesToo) for (const l of lines) console.log(color(l[0] === '+' ? 'green' : 'red', l));
224
277
  return true;
225
278
  }
226
279
 
@@ -266,7 +319,7 @@ export function config(opts) {
266
319
  const target = s.settingsPath(scope, project, out);
267
320
  const before = s.readJson(target);
268
321
  const after = s.merge(before, wanted);
269
- if (showChange(target, before, after)) planned.push([target, after]);
322
+ if (showChange(target, before, after, opts.preview !== 'summary')) planned.push([target, after]);
270
323
 
271
324
  const hostCmds = [];
272
325
  if (Object.keys(servers).length) {
@@ -274,7 +327,7 @@ export function config(opts) {
274
327
  if (mcpFile) {
275
328
  const b = s.readJson(mcpFile);
276
329
  const a = s.merge(b, { mcpServers: servers });
277
- if (showChange(mcpFile, b, a)) planned.push([mcpFile, a]);
330
+ if (showChange(mcpFile, b, a, opts.preview !== 'summary')) planned.push([mcpFile, a]);
278
331
  } else {
279
332
  const hostScope = scope === 'personal' ? 'user' : 'local';
280
333
  for (const [name, spec] of Object.entries(servers)) {
@@ -285,7 +338,7 @@ export function config(opts) {
285
338
  }
286
339
 
287
340
  if (!opts.yes) {
288
- console.log('Dry run. Re-run with --yes to write these changes.');
341
+ if (!opts.preview) console.log('Dry run. Re-run with --yes to write these changes.');
289
342
  return 0;
290
343
  }
291
344
  if (hostCmds.length && !which(s.HOST)) {
@@ -344,7 +397,8 @@ function detect() {
344
397
  if (profilesOut.code === 0 && profilesOut.out) found.awsProfiles = profilesOut.out.split(/\s+/);
345
398
  const region = process.env.AWS_REGION || (ok('aws', ['configure', 'get', 'region']).code === 0 ? ok('aws', ['configure', 'get', 'region']).out : '');
346
399
  if (region) found.AWS_REGION = region;
347
- const az = ok('az', ['account', 'show', '--query', '{t:tenantId,s:id}', '--output', 'json']);
400
+ // Azure IDs are read only from a separate read-only identity (AZURE_CONFIG_DIR), never the default login.
401
+ const az = process.env.AZURE_CONFIG_DIR ? ok('az', ['account', 'show', '--query', '{t:tenantId,s:id}', '--output', 'json']) : { code: 1, out: '' };
348
402
  if (az.code === 0 && az.out) {
349
403
  try {
350
404
  const ids = JSON.parse(az.out);
@@ -355,6 +409,39 @@ function detect() {
355
409
  return found;
356
410
  }
357
411
 
412
+ // (name, masked account, role) of AWS profiles whose configured role cannot change things. Read from the local AWS
413
+ // config only: no cloud call. Unknown and can-change profiles are left out.
414
+ export function readOnlyProfiles() {
415
+ const cfg = process.env.AWS_CONFIG_FILE || join(homedir(), '.aws', 'config');
416
+ if (!existsSync(cfg)) return [];
417
+ const found = [];
418
+ let name = '';
419
+ let kv = {};
420
+ const flush = () => {
421
+ const arn = kv.role_arn ?? '';
422
+ const role = kv.sso_role_name || arn.split('/').pop();
423
+ if (name && role && accessFromRole(`:assumed-role/${role}/`) === 'read') {
424
+ const acct = kv.sso_account_id || arn.split(':')[4] || '';
425
+ found.push([name, acct ? `****${acct.slice(-4)}` : '-', role]);
426
+ }
427
+ };
428
+ for (const raw of readFileSync(cfg, 'utf8').split('\n')) {
429
+ const line = raw.trim();
430
+ const m = line.match(/^\[(?:profile\s+)?([^\]]+)\]/);
431
+ if (m) { flush(); name = m[1].trim(); kv = {}; }
432
+ else if (line.includes('=') && !/^[#;]/.test(line)) { const i = line.indexOf('='); kv[line.slice(0, i).trim()] = line.slice(i + 1).trim(); }
433
+ }
434
+ flush();
435
+ return found.sort((a, b) => (a[1] < b[1] ? -1 : a[1] > b[1] ? 1 : a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0));
436
+ }
437
+
438
+ const SCOPE_HELP = {
439
+ org: 'managed files for IT, every person in the organisation',
440
+ team: 'a shared project or tenant folder',
441
+ local: 'you, in this project only',
442
+ personal: 'you, in every project',
443
+ };
444
+
358
445
  export async function setup(opts) {
359
446
  const rl = createInterface({ input: process.stdin, output: process.stdout, terminal: false });
360
447
  const lines = rl[Symbol.asyncIterator]();
@@ -371,19 +458,54 @@ export async function setup(opts) {
371
458
  try {
372
459
  const file = opts.file;
373
460
  console.log(`${color('bold', '1xops setup')} — non-secret values only; secrets stay in your sign-in.\n`);
461
+ table('Who the settings are for', ['scope', 'for'], s.SCOPES.map((n) => [n, SCOPE_HELP[n]]));
374
462
  let scope;
375
- do scope = await ask(`Scope (${s.SCOPES.join(' | ')})`, 'team'); while (!s.SCOPES.includes(scope));
463
+ do scope = await ask(`Scope (${s.SCOPES.join('/')})`, 'team'); while (!s.SCOPES.includes(scope));
376
464
  const conf = { scope };
377
465
  if (scope === 'team' || scope === 'local') conf.dir = await ask('Project or tenant folder', '.');
378
466
  if (scope === 'org') conf.out = await ask('Folder to write the managed files to', '.');
379
467
  const found = detect();
380
468
  const connectors = {};
469
+ let listed = false;
381
470
  for (const name of s.builtinProfiles()) {
382
471
  const profile = s.loadProfile(name);
383
472
  if (!(await yes(`Add ${name}: ${profile.description ?? ''}?`, false))) continue;
384
473
  const values = {};
385
474
  for (const v of cf.variables(profile)) {
386
- if (v.endsWith('_PROFILE') && found.awsProfiles) console.log(` AWS profiles on this machine: ${found.awsProfiles.join(', ')}`);
475
+ if (v.endsWith('_PROFILE')) {
476
+ // Pick a read-only AWS profile: by number, or type part of a name to filter. A name outside the read-only
477
+ // list cannot get in. The list is shown once; later questions refer to it.
478
+ const options = readOnlyProfiles();
479
+ if (!options.length) {
480
+ if (!listed) { // say it once, not once per variable
481
+ console.log(' No read-only AWS profile in ~/.aws/config yet.');
482
+ console.log(' Create one with: aws configure sso (a role such as ReadOnlyAccess).');
483
+ console.log(' Until then /1xops:check shows this connector as missing.');
484
+ listed = true;
485
+ }
486
+ continue;
487
+ }
488
+ const numbered = options.map((o, i) => [i + 1, o]);
489
+ const show = (rows, title) => table(title, ['#', 'profile', 'account', 'role'], rows.map(([n, [name, acct, role]]) => [String(n).padStart(String(options.length).length), name, acct, role]));
490
+ if (!listed) { show(numbered, `Read-only AWS profiles (${options.length})`); listed = true; }
491
+ const current = numbered.find(([, [name]]) => name === process.env[v]);
492
+ const hint = current ? `Enter keeps ${current[0]}, - skips` : 'Enter skips';
493
+ for (;;) {
494
+ const pick = (await ask(` ${v}: number or part of a name (${hint})`, current ? String(current[0]) : '')).trim();
495
+ if (!pick || pick === '-') break;
496
+ if (/^\d+$/.test(pick)) {
497
+ if (Number(pick) >= 1 && Number(pick) <= options.length) { values[v] = options[Number(pick) - 1][0]; break; }
498
+ console.log(` No profile number ${pick}: pick 1 to ${options.length}.`);
499
+ continue;
500
+ }
501
+ const q = pick.toLowerCase();
502
+ const matches = numbered.filter(([, [name, , role]]) => name.toLowerCase().includes(q) || role.toLowerCase().includes(q));
503
+ if (matches.length === 1) { values[v] = matches[0][1][0]; break; }
504
+ if (matches.length) show(matches, `Matching '${pick}' (${matches.length})`);
505
+ else console.log(` No read-only profile matches '${pick}'.`);
506
+ }
507
+ continue;
508
+ }
387
509
  const value = await ask(` ${v} (blank to skip)`, process.env[v] || found[v] || '');
388
510
  if (value) values[v] = value;
389
511
  }
@@ -394,14 +516,15 @@ export async function setup(opts) {
394
516
  conf.connectors = connectors;
395
517
 
396
518
  const text = cf.dump(conf);
397
- console.log(`\n${file}\n${text}`);
519
+ console.log(`\n${color('bold', file)}\n${text}`);
398
520
  if (existsSync(file) && !(await yes(`${file} exists. Replace it?`, false))) return 1;
399
521
  if (!(await yes(`Write ${file}?`, true))) return 1;
400
522
  write(file, text);
401
523
  cf.load(file); // same checks as `1xops config --file`
402
524
 
403
525
  console.log('\nChanges this would make:');
404
- if (config({ file }) !== 0) return 2;
526
+ if (config({ file, preview: 'summary' }) !== 0) return 2;
527
+ if (await yes('Show every line first?', false)) config({ file, preview: 'full' });
405
528
  if (await yes('Apply them now?', false)) return config({ file, yes: true });
406
529
  console.log(`Apply later with: 1xops config --file ${file} --yes`);
407
530
  return 0;