1xops 0.2.4 → 0.2.5

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 +64 -10
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "1xops",
3
- "version": "0.2.4",
3
+ "version": "0.2.5",
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,20 @@ 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
+ const visible = (s) => String(s).replace(/\x1b\[[0-9;]*m/g, '').length;
44
47
  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));
48
+ const width = columns.map((c, i) => Math.max(c.length, ...rows.map((r) => visible(r[i]))));
49
+ const cells = (r, bar) => `${bar} ${r.map((c, i) => String(c) + ' '.repeat(width[i] - visible(c))).join(` ${bar} `)} ${bar}`;
50
+ const rule = (l, m, r, h) => l + width.map((w) => h.repeat(w + 2)).join(m) + r;
51
+ const total = width.reduce((a, w) => a + w + 3, 1);
52
+ const left = Math.max(0, Math.floor((total - title.length) / 2));
53
+ console.log(' '.repeat(left) + color('bold', title) + ' '.repeat(Math.max(0, total - left - title.length)));
54
+ console.log(rule('┏', '┳', '┓', '━'));
55
+ console.log(cells(columns.map((c) => color('bold', c)), '┃'));
56
+ console.log(rule('┡', '╇', '┩', '━'));
57
+ for (const r of rows) console.log(cells(r, '│'));
58
+ console.log(rule('└', '┴', '┘', '─'));
50
59
  }
51
60
 
52
61
  // ── doctor ──────────────────────────────────────────────────────────────────
@@ -155,9 +164,14 @@ export function checkConnectors(file) {
155
164
  const RESULT_STYLE = { ok: 'green', ready: 'green', missing: 'red', 'signed out': 'yellow', check: 'yellow' };
156
165
 
157
166
  export function doctor(opts, version) {
167
+ // The identity calls take seconds; a status line on a terminal (cleared after), nothing when piped.
168
+ const tty = process.stdout.isTTY;
169
+ if (tty) process.stdout.write(color('dim', 'Checking tools, sign-ins and connectors (read-only)…'));
158
170
  const rows = [...checkTools(), ...checkSignIn(opts['aws-profile'])];
171
+ const connectors = checkConnectors(opts.file);
172
+ if (tty) process.stdout.write('\r\x1b[K');
159
173
  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)]));
174
+ shown.push(...connectors.map(([name, status, fix]) => [name, 'connector', status, scrub(fix)]));
161
175
  for (const r of shown) r[2] = color(RESULT_STYLE[r[2]], r[2]);
162
176
  table(`1xops ${version} doctor`, ['check', 'needed', 'result', 'detail'], shown);
163
177
  const failed = rows.filter((r) => r[1] && !r[2]).map((r) => r[0]);
@@ -344,7 +358,8 @@ function detect() {
344
358
  if (profilesOut.code === 0 && profilesOut.out) found.awsProfiles = profilesOut.out.split(/\s+/);
345
359
  const region = process.env.AWS_REGION || (ok('aws', ['configure', 'get', 'region']).code === 0 ? ok('aws', ['configure', 'get', 'region']).out : '');
346
360
  if (region) found.AWS_REGION = region;
347
- const az = ok('az', ['account', 'show', '--query', '{t:tenantId,s:id}', '--output', 'json']);
361
+ // Azure IDs are read only from a separate read-only identity (AZURE_CONFIG_DIR), never the default login.
362
+ const az = process.env.AZURE_CONFIG_DIR ? ok('az', ['account', 'show', '--query', '{t:tenantId,s:id}', '--output', 'json']) : { code: 1, out: '' };
348
363
  if (az.code === 0 && az.out) {
349
364
  try {
350
365
  const ids = JSON.parse(az.out);
@@ -355,6 +370,32 @@ function detect() {
355
370
  return found;
356
371
  }
357
372
 
373
+ // (name, masked account, role) of AWS profiles whose configured role cannot change things. Read from the local AWS
374
+ // config only: no cloud call. Unknown and can-change profiles are left out.
375
+ export function readOnlyProfiles() {
376
+ const cfg = process.env.AWS_CONFIG_FILE || join(homedir(), '.aws', 'config');
377
+ if (!existsSync(cfg)) return [];
378
+ const found = [];
379
+ let name = '';
380
+ let kv = {};
381
+ const flush = () => {
382
+ const arn = kv.role_arn ?? '';
383
+ const role = kv.sso_role_name || arn.split('/').pop();
384
+ if (name && role && accessFromRole(`:assumed-role/${role}/`) === 'read') {
385
+ const acct = kv.sso_account_id || arn.split(':')[4] || '';
386
+ found.push([name, acct ? `****${acct.slice(-4)}` : '-', role]);
387
+ }
388
+ };
389
+ for (const raw of readFileSync(cfg, 'utf8').split('\n')) {
390
+ const line = raw.trim();
391
+ const m = line.match(/^\[(?:profile\s+)?([^\]]+)\]/);
392
+ if (m) { flush(); name = m[1].trim(); kv = {}; }
393
+ else if (line.includes('=') && !/^[#;]/.test(line)) { const i = line.indexOf('='); kv[line.slice(0, i).trim()] = line.slice(i + 1).trim(); }
394
+ }
395
+ flush();
396
+ 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));
397
+ }
398
+
358
399
  export async function setup(opts) {
359
400
  const rl = createInterface({ input: process.stdin, output: process.stdout, terminal: false });
360
401
  const lines = rl[Symbol.asyncIterator]();
@@ -383,7 +424,20 @@ export async function setup(opts) {
383
424
  if (!(await yes(`Add ${name}: ${profile.description ?? ''}?`, false))) continue;
384
425
  const values = {};
385
426
  for (const v of cf.variables(profile)) {
386
- if (v.endsWith('_PROFILE') && found.awsProfiles) console.log(` AWS profiles on this machine: ${found.awsProfiles.join(', ')}`);
427
+ if (v.endsWith('_PROFILE')) {
428
+ // Pick a read-only AWS profile by number. No typing: a mistyped or admin profile cannot get in.
429
+ const options = readOnlyProfiles();
430
+ if (!options.length) {
431
+ console.log(` ${v}: no read-only AWS profile found in ~/.aws/config. Create one (an SSO role such as ReadOnlyAccess) with: aws configure sso. This connector will show as missing in /1xops:check until then.`);
432
+ continue;
433
+ }
434
+ console.log(` ${v}: read-only profiles only`);
435
+ options.forEach(([n, acct, role], i) => console.log(` ${i + 1}) ${n} ${acct} ${role}`));
436
+ let pick;
437
+ do pick = await ask(' Number (Enter to skip)'); while (pick && !(Number(pick) >= 1 && Number(pick) <= options.length));
438
+ if (pick) values[v] = options[Number(pick) - 1][0];
439
+ continue;
440
+ }
387
441
  const value = await ask(` ${v} (blank to skip)`, process.env[v] || found[v] || '');
388
442
  if (value) values[v] = value;
389
443
  }