1xops 0.2.3 → 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.
package/bin/1xops.mjs CHANGED
@@ -11,7 +11,7 @@ const { version } = JSON.parse(readFileSync(new URL('../package.json', import.me
11
11
 
12
12
  const HELP = `Usage: 1xops <command> [options]
13
13
 
14
- doctor check prerequisites and read-only sign-in [--aws-profile NAME]
14
+ doctor check prerequisites, sign-in and connectors [--aws-profile NAME] [--file PATH]
15
15
  install add the marketplaces and install the plugin [--scope user|project|local] [--yes]
16
16
  setup guided setup: asks questions, writes ${DEFAULT_FILE} [--file PATH]
17
17
  config write settings and connectors for a scope [--scope ${SCOPES.join('|')}] [--dir DIR]
@@ -33,7 +33,7 @@ if (!command || command === '--help' || command === '-h') {
33
33
  }
34
34
 
35
35
  const OPTIONS = {
36
- doctor: { 'aws-profile': { type: 'string' } },
36
+ doctor: { 'aws-profile': { type: 'string' }, file: { type: 'string', default: DEFAULT_FILE } },
37
37
  install: { scope: { type: 'string', default: 'user' }, yes: { type: 'boolean', default: false } },
38
38
  setup: { file: { type: 'string', default: DEFAULT_FILE } },
39
39
  config: {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "1xops",
3
- "version": "0.2.3",
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 ──────────────────────────────────────────────────────────────────
@@ -86,14 +95,84 @@ export function checkSignIn(awsProfile) {
86
95
  return rows;
87
96
  }
88
97
 
98
+ // (status, fix) for a failed AWS identity call, from the AWS CLI's own error text.
99
+ export function awsFix(error, profile) {
100
+ if (/could not be found/i.test(error)) return ['missing', `profile ${profile} not found: aws configure sso --profile ${profile}, or set AWS_CONFIG_FILE`];
101
+ if (/expired|refresh failed|sso.*token|nocredentials|unable to locate credentials/i.test(error)) return ['signed out', `aws sso login --profile ${profile}`];
102
+ const first = error.split('\n').find((l) => l.trim()) ?? 'AWS identity call failed';
103
+ return ['check', first.replace(/^aws: \[ERROR\]: /, '').slice(0, 120)];
104
+ }
105
+
106
+ // read: Reader roles only; write: any role that can change things; unknown: no roles seen.
107
+ export function azureAccess(roles = []) {
108
+ if (!roles.length) return 'unknown';
109
+ if (roles.some((r) => /owner|contributor|administrator/i.test(r))) return 'write';
110
+ if (roles.every((r) => /reader/i.test(r))) return 'read';
111
+ return 'unknown';
112
+ }
113
+ const AZURE_ACCESS = { read: 'read-only', write: 'can change things: use a read-only (Reader) identity', unknown: 'access unknown: use a read-only (Reader) identity' };
114
+
115
+ function awsConnector(v, values) {
116
+ const name = `aws ${v}`;
117
+ const profile = values[v] || process.env[v] || '';
118
+ if (!profile) return [name, 'missing', `set ${v} in .env.1xops or the shell (1xops setup)`];
119
+ if (!which('aws')) return [name, 'missing', 'install the AWS CLI'];
120
+ const { code, out } = run('aws', ['sts', 'get-caller-identity', '--output', 'json', '--profile', profile]);
121
+ if (code !== 0) return [name, ...awsFix(out, profile)];
122
+ let id;
123
+ try { id = JSON.parse(out); } catch { return [name, 'check', 'AWS identity call returned no account']; }
124
+ const access = accessFromRole(id.Arn ?? '');
125
+ return [name, access === 'read' ? 'ready' : 'check', `profile ${profile}, account ${mask(id.Account ?? '')}, ${ACCESS[access]}`];
126
+ }
127
+
128
+ function azureConnector() {
129
+ if (!which('az')) return ['azure', 'missing', 'install the Azure CLI'];
130
+ const who = run('az', ['account', 'show', '--query', 'user.name', '--output', 'tsv']);
131
+ if (who.code !== 0 || !who.out) return ['azure', 'signed out', 'az login with a read-only (Reader) identity, in its own AZURE_CONFIG_DIR'];
132
+ const roles = run('az', ['role', 'assignment', 'list', '--assignee', who.out, '--all', '--query', '[].roleDefinitionName', '--output', 'json'], 60000);
133
+ let names = [];
134
+ try { names = roles.code === 0 ? JSON.parse(roles.out) : []; } catch { /* not JSON */ }
135
+ const access = azureAccess(names);
136
+ return ['azure', access === 'read' ? 'ready' : 'check', AZURE_ACCESS[access]];
137
+ }
138
+
139
+ // [connector, status, fix] for each connector in .env.1xops. Read-only identity calls only.
140
+ export function checkConnectors(file) {
141
+ if (!existsSync(file)) return [['connectors', 'missing', `no ${file} here: run 1xops setup`]];
142
+ let cfg;
143
+ try { cfg = cf.load(file); } catch (err) { return [['connectors', 'missing', err.message]]; }
144
+ if (!Object.keys(cfg.connectors).length) return [['connectors', 'missing', `ONEXOPS_CONNECTORS is empty in ${file}: run 1xops setup`]];
145
+ const rows = [];
146
+ for (const connector of Object.keys(cfg.connectors)) {
147
+ let servers;
148
+ try { servers = s.loadProfile(connector).mcpServers; } catch (err) { rows.push([connector, 'missing', err.message]); continue; }
149
+ const awsVars = [];
150
+ let azure = false;
151
+ for (const [serverName, server] of Object.entries(servers)) {
152
+ const env = server.env ?? {};
153
+ if ('AWS_PROFILE' in env) awsVars.push(...[...env.AWS_PROFILE.matchAll(/\$\{([A-Z0-9_]+)(?::-[^}]*)?\}/g)].map((m) => m[1]));
154
+ else if ('AZURE_TENANT_ID' in env) azure = true;
155
+ else if (server.type === 'http') rows.push([serverName, 'check', `signs in inside the host: run /mcp and choose ${serverName}`]);
156
+ else rows.push([serverName, 'check', 'no sign-in check for this connector']);
157
+ }
158
+ rows.push(...[...new Set(awsVars)].map((v) => awsConnector(v, cfg.values)));
159
+ if (azure) rows.push(azureConnector());
160
+ }
161
+ return rows;
162
+ }
163
+
164
+ const RESULT_STYLE = { ok: 'green', ready: 'green', missing: 'red', 'signed out': 'yellow', check: 'yellow' };
165
+
89
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)…'));
90
170
  const rows = [...checkTools(), ...checkSignIn(opts['aws-profile'])];
91
- const shown = rows.map(([name, required, ok, detail]) => [
92
- name,
93
- required ? 'required' : 'optional',
94
- ok ? color('green', 'ok') : required ? color('red', 'missing') : color('yellow', 'check'),
95
- scrub(detail),
96
- ]);
171
+ const connectors = checkConnectors(opts.file);
172
+ if (tty) process.stdout.write('\r\x1b[K');
173
+ const shown = rows.map(([name, required, ok, detail]) => [name, required ? 'required' : 'optional', ok ? 'ok' : required ? 'missing' : 'check', scrub(detail)]);
174
+ shown.push(...connectors.map(([name, status, fix]) => [name, 'connector', status, scrub(fix)]));
175
+ for (const r of shown) r[2] = color(RESULT_STYLE[r[2]], r[2]);
97
176
  table(`1xops ${version} doctor`, ['check', 'needed', 'result', 'detail'], shown);
98
177
  const failed = rows.filter((r) => r[1] && !r[2]).map((r) => r[0]);
99
178
  if (failed.length) {
@@ -279,7 +358,8 @@ function detect() {
279
358
  if (profilesOut.code === 0 && profilesOut.out) found.awsProfiles = profilesOut.out.split(/\s+/);
280
359
  const region = process.env.AWS_REGION || (ok('aws', ['configure', 'get', 'region']).code === 0 ? ok('aws', ['configure', 'get', 'region']).out : '');
281
360
  if (region) found.AWS_REGION = region;
282
- 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: '' };
283
363
  if (az.code === 0 && az.out) {
284
364
  try {
285
365
  const ids = JSON.parse(az.out);
@@ -290,6 +370,32 @@ function detect() {
290
370
  return found;
291
371
  }
292
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
+
293
399
  export async function setup(opts) {
294
400
  const rl = createInterface({ input: process.stdin, output: process.stdout, terminal: false });
295
401
  const lines = rl[Symbol.asyncIterator]();
@@ -318,7 +424,20 @@ export async function setup(opts) {
318
424
  if (!(await yes(`Add ${name}: ${profile.description ?? ''}?`, false))) continue;
319
425
  const values = {};
320
426
  for (const v of cf.variables(profile)) {
321
- 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
+ }
322
441
  const value = await ask(` ${v} (blank to skip)`, process.env[v] || found[v] || '');
323
442
  if (value) values[v] = value;
324
443
  }
package/src/settings.mjs CHANGED
@@ -28,6 +28,36 @@ export const BASELINE = {
28
28
  'Bash(gh release *)',
29
29
  'Bash(terraform apply *)',
30
30
  'Bash(terraform destroy *)',
31
+ 'Bash(aws * create-*)',
32
+ 'Bash(aws * delete-*)',
33
+ 'Bash(aws * put-*)',
34
+ 'Bash(aws * update-*)',
35
+ 'Bash(aws * modify-*)',
36
+ 'Bash(aws * terminate-*)',
37
+ 'Bash(aws * start-*)',
38
+ 'Bash(aws * stop-*)',
39
+ 'Bash(aws * attach-*)',
40
+ 'Bash(aws * detach-*)',
41
+ 'Bash(aws * tag-*)',
42
+ 'Bash(aws * untag-*)',
43
+ 'Bash(aws s3 cp *)',
44
+ 'Bash(aws s3 mv *)',
45
+ 'Bash(aws s3 rm *)',
46
+ 'Bash(aws s3 sync *)',
47
+ 'Bash(aws cloudformation deploy *)',
48
+ 'Bash(az * create*)',
49
+ 'Bash(az * delete*)',
50
+ 'Bash(az * update*)',
51
+ 'Bash(az * start*)',
52
+ 'Bash(az * stop*)',
53
+ 'Bash(az * restart*)',
54
+ 'Bash(az * deallocate*)',
55
+ 'Bash(az * assign*)',
56
+ 'Bash(az * add*)',
57
+ 'Bash(az * remove*)',
58
+ 'Bash(az * import*)',
59
+ 'Bash(az * invoke*)',
60
+ 'Bash(az rest *)',
31
61
  ],
32
62
  },
33
63
  };