1xops 0.2.2 → 0.2.4

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.2",
3
+ "version": "0.2.4",
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
@@ -30,6 +30,16 @@ export function run(cmd, args, timeout = 20000) {
30
30
  }
31
31
 
32
32
  export const mask = (account) => (account.length >= 4 ? `****${account.slice(-4)}` : '****');
33
+ // Any 12-digit run (an AWS account ID) in any text, masked: doctor output is pasted onto issues as evidence.
34
+ export const scrub = (text) => String(text).replace(/\d{12}/g, (d) => mask(d));
35
+ // read: the role cannot change anything; write: it can; unknown: cannot tell from the name.
36
+ export function accessFromRole(arn = '') {
37
+ const role = arn.match(/:assumed-role\/([^/]+)\//)?.[1] ?? arn.match(/:(user|root)\b/)?.[1] ?? '';
38
+ if (/readonly|viewonly|securityaudit|readaccess|viewer/i.test(role)) return 'read';
39
+ if (/admin|poweruser|fullaccess|root/i.test(role)) return 'write';
40
+ return 'unknown';
41
+ }
42
+ const ACCESS = { read: 'read-only', write: 'can change things: use a read-only role', unknown: 'access unknown: use a read-only role' };
33
43
 
34
44
  function table(title, columns, rows) {
35
45
  const width = columns.map((c, i) => Math.max(c.length, ...rows.map((r) => String(r[i]).length)));
@@ -58,9 +68,11 @@ export function checkSignIn(awsProfile) {
58
68
  const args = ['sts', 'get-caller-identity', '--output', 'json', ...(awsProfile ? ['--profile', awsProfile] : [])];
59
69
  const { code, out } = run('aws', args);
60
70
  if (code === 0) {
61
- let account = '';
62
- try { account = JSON.parse(out).Account ?? ''; } catch { /* not JSON */ }
63
- rows.push(['aws sign-in', false, true, `signed in, account ${mask(account)}`]);
71
+ let id = {};
72
+ try { id = JSON.parse(out); } catch { /* not JSON */ }
73
+ const access = accessFromRole(id.Arn);
74
+ rows.push(['aws sign-in', false, true, `signed in, account ${mask(id.Account ?? '')}`]);
75
+ rows.push(['aws access', false, access === 'read', ACCESS[access]]);
64
76
  } else rows.push(['aws sign-in', false, false, 'not signed in (aws sso login)']);
65
77
  }
66
78
  if (which('az')) {
@@ -74,14 +86,79 @@ export function checkSignIn(awsProfile) {
74
86
  return rows;
75
87
  }
76
88
 
89
+ // (status, fix) for a failed AWS identity call, from the AWS CLI's own error text.
90
+ export function awsFix(error, profile) {
91
+ if (/could not be found/i.test(error)) return ['missing', `profile ${profile} not found: aws configure sso --profile ${profile}, or set AWS_CONFIG_FILE`];
92
+ if (/expired|refresh failed|sso.*token|nocredentials|unable to locate credentials/i.test(error)) return ['signed out', `aws sso login --profile ${profile}`];
93
+ const first = error.split('\n').find((l) => l.trim()) ?? 'AWS identity call failed';
94
+ return ['check', first.replace(/^aws: \[ERROR\]: /, '').slice(0, 120)];
95
+ }
96
+
97
+ // read: Reader roles only; write: any role that can change things; unknown: no roles seen.
98
+ export function azureAccess(roles = []) {
99
+ if (!roles.length) return 'unknown';
100
+ if (roles.some((r) => /owner|contributor|administrator/i.test(r))) return 'write';
101
+ if (roles.every((r) => /reader/i.test(r))) return 'read';
102
+ return 'unknown';
103
+ }
104
+ 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' };
105
+
106
+ function awsConnector(v, values) {
107
+ const name = `aws ${v}`;
108
+ const profile = values[v] || process.env[v] || '';
109
+ if (!profile) return [name, 'missing', `set ${v} in .env.1xops or the shell (1xops setup)`];
110
+ if (!which('aws')) return [name, 'missing', 'install the AWS CLI'];
111
+ const { code, out } = run('aws', ['sts', 'get-caller-identity', '--output', 'json', '--profile', profile]);
112
+ if (code !== 0) return [name, ...awsFix(out, profile)];
113
+ let id;
114
+ try { id = JSON.parse(out); } catch { return [name, 'check', 'AWS identity call returned no account']; }
115
+ const access = accessFromRole(id.Arn ?? '');
116
+ return [name, access === 'read' ? 'ready' : 'check', `profile ${profile}, account ${mask(id.Account ?? '')}, ${ACCESS[access]}`];
117
+ }
118
+
119
+ function azureConnector() {
120
+ if (!which('az')) return ['azure', 'missing', 'install the Azure CLI'];
121
+ const who = run('az', ['account', 'show', '--query', 'user.name', '--output', 'tsv']);
122
+ if (who.code !== 0 || !who.out) return ['azure', 'signed out', 'az login with a read-only (Reader) identity, in its own AZURE_CONFIG_DIR'];
123
+ const roles = run('az', ['role', 'assignment', 'list', '--assignee', who.out, '--all', '--query', '[].roleDefinitionName', '--output', 'json'], 60000);
124
+ let names = [];
125
+ try { names = roles.code === 0 ? JSON.parse(roles.out) : []; } catch { /* not JSON */ }
126
+ const access = azureAccess(names);
127
+ return ['azure', access === 'read' ? 'ready' : 'check', AZURE_ACCESS[access]];
128
+ }
129
+
130
+ // [connector, status, fix] for each connector in .env.1xops. Read-only identity calls only.
131
+ export function checkConnectors(file) {
132
+ if (!existsSync(file)) return [['connectors', 'missing', `no ${file} here: run 1xops setup`]];
133
+ let cfg;
134
+ try { cfg = cf.load(file); } catch (err) { return [['connectors', 'missing', err.message]]; }
135
+ if (!Object.keys(cfg.connectors).length) return [['connectors', 'missing', `ONEXOPS_CONNECTORS is empty in ${file}: run 1xops setup`]];
136
+ const rows = [];
137
+ for (const connector of Object.keys(cfg.connectors)) {
138
+ let servers;
139
+ try { servers = s.loadProfile(connector).mcpServers; } catch (err) { rows.push([connector, 'missing', err.message]); continue; }
140
+ const awsVars = [];
141
+ let azure = false;
142
+ for (const [serverName, server] of Object.entries(servers)) {
143
+ const env = server.env ?? {};
144
+ if ('AWS_PROFILE' in env) awsVars.push(...[...env.AWS_PROFILE.matchAll(/\$\{([A-Z0-9_]+)(?::-[^}]*)?\}/g)].map((m) => m[1]));
145
+ else if ('AZURE_TENANT_ID' in env) azure = true;
146
+ else if (server.type === 'http') rows.push([serverName, 'check', `signs in inside the host: run /mcp and choose ${serverName}`]);
147
+ else rows.push([serverName, 'check', 'no sign-in check for this connector']);
148
+ }
149
+ rows.push(...[...new Set(awsVars)].map((v) => awsConnector(v, cfg.values)));
150
+ if (azure) rows.push(azureConnector());
151
+ }
152
+ return rows;
153
+ }
154
+
155
+ const RESULT_STYLE = { ok: 'green', ready: 'green', missing: 'red', 'signed out': 'yellow', check: 'yellow' };
156
+
77
157
  export function doctor(opts, version) {
78
158
  const rows = [...checkTools(), ...checkSignIn(opts['aws-profile'])];
79
- const shown = rows.map(([name, required, ok, detail]) => [
80
- name,
81
- required ? 'required' : 'optional',
82
- ok ? color('green', 'ok') : required ? color('red', 'missing') : color('yellow', 'optional'),
83
- detail,
84
- ]);
159
+ 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)]));
161
+ for (const r of shown) r[2] = color(RESULT_STYLE[r[2]], r[2]);
85
162
  table(`1xops ${version} doctor`, ['check', 'needed', 'result', 'detail'], shown);
86
163
  const failed = rows.filter((r) => r[1] && !r[2]).map((r) => r[0]);
87
164
  if (failed.length) {
@@ -150,7 +227,7 @@ function showChange(file, before, after) {
150
227
  function write(file, data) {
151
228
  mkdirSync(path.dirname(file), { recursive: true });
152
229
  const tmp = `${file}.tmp`;
153
- writeFileSync(tmp, s.dumps(data));
230
+ writeFileSync(tmp, typeof data === 'string' ? data : s.dumps(data), { flush: true }); // on disk before the swap
154
231
  renameSync(tmp, file);
155
232
  }
156
233
 
@@ -320,7 +397,7 @@ export async function setup(opts) {
320
397
  console.log(`\n${file}\n${text}`);
321
398
  if (existsSync(file) && !(await yes(`${file} exists. Replace it?`, false))) return 1;
322
399
  if (!(await yes(`Write ${file}?`, true))) return 1;
323
- writeFileSync(file, text);
400
+ write(file, text);
324
401
  cf.load(file); // same checks as `1xops config --file`
325
402
 
326
403
  console.log('\nChanges this would make:');
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
  };