neonctl 0.0.9 → 0.3.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "neonctl",
3
- "version": "0.0.9",
3
+ "version": "0.3.0",
4
4
  "description": "CLI tool for NeonDB Cloud management",
5
5
  "main": "index.js",
6
6
  "author": "NeonDB",
@@ -24,6 +24,10 @@
24
24
  "openid-client": "^5.1.9",
25
25
  "yargs": "^17.5.1"
26
26
  },
27
+ "publishConfig": {
28
+ "access": "public",
29
+ "registry": "https://registry.npmjs.org/"
30
+ },
27
31
  "scripts": {
28
32
  "dev": "node dev.js",
29
33
  "debug": "node --inspect-brk dev.js",
@@ -1,9 +1,49 @@
1
1
  "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
2
11
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.apiCall = void 0;
4
- const https_1 = require("https");
12
+ exports.apiCall = exports.ApiError = void 0;
13
+ const node_https_1 = require("node:https");
14
+ class ApiError extends Error {
15
+ constructor(response) {
16
+ super(response.statusMessage);
17
+ this.response = response;
18
+ }
19
+ getApiError() {
20
+ return __awaiter(this, void 0, void 0, function* () {
21
+ return new Promise((resolve, reject) => {
22
+ const data = [];
23
+ this.response
24
+ .on('data', (chunk) => {
25
+ data.push(chunk);
26
+ })
27
+ .on('end', () => {
28
+ try {
29
+ const json = JSON.parse(data.join(''));
30
+ resolve((json === null || json === void 0 ? void 0 : json.message) ||
31
+ `${this.response.statusCode}:${this.message}:${data.join('')}`);
32
+ }
33
+ catch (e) {
34
+ reject(e);
35
+ }
36
+ })
37
+ .on('error', (e) => {
38
+ reject(e);
39
+ });
40
+ });
41
+ });
42
+ }
43
+ }
44
+ exports.ApiError = ApiError;
5
45
  const apiCall = ({ apiHost, token, path, body, method = 'GET', }) => new Promise((resolve, reject) => {
6
- const req = (0, https_1.request)(`${apiHost}/api/v1/${path}`, {
46
+ const req = (0, node_https_1.request)(`${apiHost}/api/v1/${path}`, {
7
47
  headers: {
8
48
  Authorization: `Bearer ${token}`,
9
49
  Accept: 'application/json',
@@ -11,8 +51,8 @@ const apiCall = ({ apiHost, token, path, body, method = 'GET', }) => new Promise
11
51
  },
12
52
  method,
13
53
  }, (res) => {
14
- if (res.statusCode !== 200) {
15
- reject(new Error(`${res.statusCode}: ${res.statusMessage}`));
54
+ if (!res.statusCode || res.statusCode >= 400) {
55
+ reject(new ApiError(res));
16
56
  return;
17
57
  }
18
58
  let result = '';
@@ -1,23 +1,12 @@
1
1
  "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
2
  Object.defineProperty(exports, "__esModule", { value: true });
12
3
  exports.createProject = exports.listProjects = void 0;
13
4
  const gateway_1 = require("./gateway");
14
- const listProjects = (props) => __awaiter(void 0, void 0, void 0, function* () { return (0, gateway_1.apiCall)(Object.assign(Object.assign({}, props), { path: 'projects', method: 'GET' })); });
5
+ const listProjects = (props) => (0, gateway_1.apiCall)(Object.assign(Object.assign({}, props), { path: 'projects', method: 'GET' }));
15
6
  exports.listProjects = listProjects;
16
- const createProject = (props) => __awaiter(void 0, void 0, void 0, function* () {
17
- return (0, gateway_1.apiCall)(Object.assign(Object.assign({}, props), { body: {
18
- instance_handle: props.instanceHandle,
19
- platform_id: props.platformId,
20
- region_id: props.regionId,
21
- }, path: 'projects', method: 'POST' }));
22
- });
7
+ const createProject = (props) => (0, gateway_1.apiCall)(Object.assign(Object.assign({}, props), { body: {
8
+ project: {
9
+ settings: props.settings,
10
+ },
11
+ }, path: 'projects', method: 'POST' }));
23
12
  exports.createProject = createProject;
@@ -0,0 +1,6 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.apiMe = void 0;
4
+ const gateway_1 = require("./gateway");
5
+ const apiMe = (props) => (0, gateway_1.apiCall)(Object.assign(Object.assign({}, props), { path: 'users/me', method: 'GET' }));
6
+ exports.apiMe = apiMe;
package/src/auth.js CHANGED
@@ -19,24 +19,30 @@ const node_fs_1 = require("node:fs");
19
19
  const node_path_1 = require("node:path");
20
20
  const open_1 = __importDefault(require("open"));
21
21
  const log_1 = require("./log");
22
- // what port to listen on for incoming requests
23
- const CONFIG_LISTEN_PORT = 5555;
24
22
  // oauth server timeouts
25
23
  const SERVER_TIMEOUT = 10000;
26
24
  // where to wait for incoming redirect request from oauth server to arrive
27
- const REDIRECT_URI = 'http://127.0.0.1:5555/callback';
25
+ const REDIRECT_URI = (port) => `http://127.0.0.1:${port}/callback`;
28
26
  // These scopes cannot be cancelled, they are always needed.
29
- const DEFAULT_SCOPES = ['openid', 'offline'];
27
+ const DEFAULT_SCOPES = ['openid', 'offline', 'urn:neoncloud:projects:create'];
30
28
  const auth = ({ oauthHost, clientId }) => __awaiter(void 0, void 0, void 0, function* () {
31
29
  openid_client_1.custom.setHttpOptionsDefaults({
32
30
  timeout: SERVER_TIMEOUT,
33
31
  });
34
32
  log_1.log.info('Discovering oauth server');
35
33
  const issuer = yield openid_client_1.Issuer.discover(oauthHost);
34
+ //
35
+ // Start HTTP server and wait till /callback is hit
36
+ //
37
+ const server = (0, node_http_1.createServer)();
38
+ server.listen(0, function () {
39
+ log_1.log.info(`Listening on port ${this.address().port}`);
40
+ });
41
+ const listen_port = server.address().port;
36
42
  const neonOAuthClient = new issuer.Client({
37
43
  token_endpoint_auth_method: 'none',
38
44
  client_id: clientId,
39
- redirect_uris: [REDIRECT_URI],
45
+ redirect_uris: [REDIRECT_URI(listen_port)],
40
46
  response_types: ['code'],
41
47
  });
42
48
  // https://datatracker.ietf.org/doc/html/rfc6819#section-4.4.1.8
@@ -45,10 +51,7 @@ const auth = ({ oauthHost, clientId }) => __awaiter(void 0, void 0, void 0, func
45
51
  const codeVerifier = openid_client_1.generators.codeVerifier();
46
52
  const codeChallenge = openid_client_1.generators.codeChallenge(codeVerifier);
47
53
  return new Promise((resolve) => {
48
- //
49
- // Start HTTP server and wait till /callback is hit
50
- //
51
- const server = (0, node_http_1.createServer)((request, response) => __awaiter(void 0, void 0, void 0, function* () {
54
+ server.on('request', (request, response) => __awaiter(void 0, void 0, void 0, function* () {
52
55
  var _a;
53
56
  //
54
57
  // Wait for callback and follow oauth flow.
@@ -60,7 +63,7 @@ const auth = ({ oauthHost, clientId }) => __awaiter(void 0, void 0, void 0, func
60
63
  }
61
64
  log_1.log.info(`Callback received: ${request.url}`);
62
65
  const params = neonOAuthClient.callbackParams(request);
63
- const tokenSet = yield neonOAuthClient.callback(REDIRECT_URI, params, {
66
+ const tokenSet = yield neonOAuthClient.callback(REDIRECT_URI(listen_port), params, {
64
67
  code_verifier: codeVerifier,
65
68
  state,
66
69
  });
@@ -69,9 +72,6 @@ const auth = ({ oauthHost, clientId }) => __awaiter(void 0, void 0, void 0, func
69
72
  resolve(tokenSet);
70
73
  server.close();
71
74
  }));
72
- server.listen(CONFIG_LISTEN_PORT, () => {
73
- log_1.log.info(`Listening on port ${CONFIG_LISTEN_PORT}`);
74
- });
75
75
  //
76
76
  // Open browser to let user authenticate
77
77
  //
@@ -32,14 +32,13 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
32
32
  });
33
33
  };
34
34
  Object.defineProperty(exports, "__esModule", { value: true });
35
- exports.ensureAuth = exports.validateAuth = exports.authFlow = void 0;
35
+ exports.ensureAuth = exports.authFlow = void 0;
36
36
  const node_path_1 = require("node:path");
37
37
  const node_fs_1 = require("node:fs");
38
38
  const auth_1 = require("../auth");
39
- const projects_1 = require("../api/projects");
40
39
  const log_1 = require("../log");
41
40
  const CREDENTIALS_FILE = 'credentials.json';
42
- const authFlow = ({ configDir, oauthHost, clientId, }) => __awaiter(void 0, void 0, void 0, function* () {
41
+ const authFlow = ({ 'config-dir': configDir, 'oauth-host': oauthHost, 'client-id': clientId, }) => __awaiter(void 0, void 0, void 0, function* () {
43
42
  if (!clientId) {
44
43
  throw new Error('Missing client id');
45
44
  }
@@ -54,32 +53,23 @@ const authFlow = ({ configDir, oauthHost, clientId, }) => __awaiter(void 0, void
54
53
  return tokenSet.access_token || '';
55
54
  });
56
55
  exports.authFlow = authFlow;
57
- const validateAuth = (props) => __awaiter(void 0, void 0, void 0, function* () {
58
- try {
59
- yield (0, projects_1.listProjects)(props);
60
- }
61
- catch (e) {
62
- if (e.message.startsWith('401:')) {
63
- return false;
64
- }
65
- throw e;
66
- }
67
- return true;
68
- });
69
- exports.validateAuth = validateAuth;
70
56
  const ensureAuth = (props) => __awaiter(void 0, void 0, void 0, function* () {
71
- const credentialsPath = (0, node_path_1.join)(props.configDir, CREDENTIALS_FILE);
57
+ if (props._[0] === 'auth') {
58
+ return;
59
+ }
60
+ const credentialsPath = (0, node_path_1.join)(props['config-dir'], CREDENTIALS_FILE);
72
61
  if ((0, node_fs_1.existsSync)(credentialsPath)) {
73
- const token = (yield Promise.resolve().then(() => __importStar(require(credentialsPath)))).access_token;
74
- if (yield (0, exports.validateAuth)(Object.assign(Object.assign({}, props), { token }))) {
62
+ try {
63
+ const token = (yield Promise.resolve().then(() => __importStar(require(credentialsPath)))).access_token;
75
64
  props.token = token;
65
+ return;
76
66
  }
77
- else {
78
- props.token = yield (0, exports.authFlow)(props);
67
+ catch (e) {
68
+ yield (0, exports.authFlow)(props);
79
69
  }
80
70
  }
81
71
  else {
82
- props.token = yield (0, exports.authFlow)(props);
72
+ yield (0, exports.authFlow)(props);
83
73
  }
84
74
  });
85
75
  exports.ensureAuth = ensureAuth;
@@ -9,12 +9,13 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
9
9
  });
10
10
  };
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.create = exports.list = void 0;
12
13
  const projects_1 = require("../api/projects");
13
- exports.default = (props) => __awaiter(void 0, void 0, void 0, function* () {
14
- if (props.sub === 'list' || props.sub === undefined) {
15
- process.stdout.write(yield (0, projects_1.listProjects)(props));
16
- }
17
- else if (props.sub === 'create') {
18
- process.stdout.write(yield (0, projects_1.createProject)(Object.assign(Object.assign({}, props), { instanceHandle: 'scalable', platformId: 'serverless', regionId: 'us-west-2' })));
19
- }
14
+ const list = (props) => __awaiter(void 0, void 0, void 0, function* () {
15
+ process.stdout.write(yield (0, projects_1.listProjects)(props));
20
16
  });
17
+ exports.list = list;
18
+ const create = (props) => __awaiter(void 0, void 0, void 0, function* () {
19
+ process.stdout.write(yield (0, projects_1.createProject)(Object.assign(Object.assign({}, props), { settings: {} })));
20
+ });
21
+ exports.create = create;
@@ -0,0 +1,17 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.me = void 0;
13
+ const users_1 = require("../api/users");
14
+ const me = (props) => __awaiter(void 0, void 0, void 0, function* () {
15
+ process.stdout.write(yield (0, users_1.apiMe)(props));
16
+ });
17
+ exports.me = me;
package/src/config.js CHANGED
@@ -14,7 +14,7 @@ const node_path_1 = require("node:path");
14
14
  const node_fs_1 = require("node:fs");
15
15
  const DIR_NAME = '.neonctl';
16
16
  exports.defaultDir = (0, node_path_1.join)(process.cwd(), DIR_NAME);
17
- const ensureConfigDir = ({ configDir, }) => __awaiter(void 0, void 0, void 0, function* () {
17
+ const ensureConfigDir = ({ 'config-dir': configDir, }) => __awaiter(void 0, void 0, void 0, function* () {
18
18
  if (!(0, node_fs_1.existsSync)(configDir)) {
19
19
  (0, node_fs_1.mkdirSync)(configDir);
20
20
  }
package/src/index.js CHANGED
@@ -37,32 +37,44 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
37
37
  Object.defineProperty(exports, "__esModule", { value: true });
38
38
  const yargs = __importStar(require("yargs"));
39
39
  const package_json_1 = __importDefault(require("../package.json"));
40
+ const gateway_1 = require("./api/gateway");
40
41
  const auth_1 = require("./commands/auth");
41
42
  const config_1 = require("./config");
43
+ const log_1 = require("./log");
44
+ const showHelpMiddleware = (argv) => {
45
+ if (argv._.length === 1) {
46
+ yargs.showHelp();
47
+ }
48
+ };
42
49
  const builder = yargs
43
50
  .scriptName(package_json_1.default.name)
44
- .usage('$0 <cmd> [args]')
51
+ .usage('usage: $0 <cmd> [args]')
45
52
  .help()
46
- .option('apiHost', {
53
+ .option('json', {
54
+ describe: 'Set output format to JSON',
55
+ type: 'boolean',
56
+ })
57
+ .option('api-host', {
47
58
  describe: 'The API host',
48
59
  default: 'https://console.neon.tech',
49
- })
50
- .option('oauthHost', {
51
- description: 'URL to Neon OAUTH host',
52
- default: 'https://oauth2.neon.tech',
53
- })
54
- .option('clientId', {
55
- description: 'OAuth client id',
56
- type: 'string',
57
60
  })
58
61
  // Setup config directory
59
- .option('configDir', {
62
+ .option('config-dir', {
60
63
  describe: 'Path to config directory',
61
64
  type: 'string',
62
65
  default: config_1.defaultDir,
63
66
  })
64
67
  .middleware(config_1.ensureConfigDir)
65
68
  // Auth flow
69
+ .option('oauth-host', {
70
+ description: 'URL to Neon OAUTH host',
71
+ default: 'https://oauth2.neon.tech',
72
+ })
73
+ .option('client-id', {
74
+ description: 'OAuth client id',
75
+ type: 'string',
76
+ default: 'neonctl',
77
+ })
66
78
  .command('auth', 'Authenticate user', (yargs) => yargs, (args) => __awaiter(void 0, void 0, void 0, function* () {
67
79
  (yield Promise.resolve().then(() => __importStar(require('./commands/auth')))).authFlow(args);
68
80
  }))
@@ -73,16 +85,38 @@ const builder = yargs
73
85
  default: '',
74
86
  })
75
87
  .middleware(auth_1.ensureAuth)
76
- .command('projects [sub]', 'Manage projects', (yargs) => __awaiter(void 0, void 0, void 0, function* () {
77
- return yargs.positional('sub', {
78
- describe: 'Subcommand',
79
- choices: ['list', 'create'],
80
- });
81
- }), (args) => __awaiter(void 0, void 0, void 0, function* () {
82
- (yield Promise.resolve().then(() => __importStar(require('./commands/projects')))).default(args);
88
+ .command('me', 'Get user info', (yargs) => yargs, (args) => __awaiter(void 0, void 0, void 0, function* () {
89
+ yield (yield Promise.resolve().then(() => __importStar(require('./commands/users')))).me(args);
90
+ }))
91
+ .command('projects', 'Manage projects', (yargs) => __awaiter(void 0, void 0, void 0, function* () {
92
+ yargs
93
+ .usage('usage: $0 projects <cmd> [args]')
94
+ // .command(
95
+ // 'list',
96
+ // 'List projects',
97
+ // (yargs) => yargs,
98
+ // async (args) => {
99
+ // await (await import('./commands/projects')).list(args);
100
+ // }
101
+ // )
102
+ .command('create', 'Create a project', (yargs) => yargs, (args) => __awaiter(void 0, void 0, void 0, function* () {
103
+ yield (yield Promise.resolve().then(() => __importStar(require('./commands/projects')))).create(args);
104
+ }))
105
+ .middleware(showHelpMiddleware);
106
+ }))
107
+ .strict()
108
+ .fail((msg, err) => __awaiter(void 0, void 0, void 0, function* () {
109
+ if (err instanceof gateway_1.ApiError) {
110
+ log_1.log.error(yield err.getApiError());
111
+ }
112
+ else {
113
+ log_1.log.error(msg || err.message);
114
+ }
115
+ process.exit(1);
83
116
  }));
84
117
  (() => __awaiter(void 0, void 0, void 0, function* () {
85
- if ((yield builder.argv)._.length === 0) {
118
+ const args = yield builder.argv;
119
+ if (args._.length === 0) {
86
120
  yargs.showHelp();
87
121
  }
88
122
  }))();
package/src/log.js CHANGED
@@ -1,8 +1,12 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.log = void 0;
4
+ const node_util_1 = require("node:util");
4
5
  exports.log = {
5
- info: (message) => {
6
- process.stderr.write(`${message}\n`);
6
+ info: (...args) => {
7
+ process.stderr.write(`INFO: ${(0, node_util_1.format)(...args)}\n`);
8
+ },
9
+ error: (...args) => {
10
+ process.stderr.write(`ERROR: ${(0, node_util_1.format)(...args)}\n`);
7
11
  },
8
12
  };
package/src/types.js ADDED
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });