neonctl 0.0.1 → 0.0.2

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,11 +1,32 @@
1
1
  {
2
- "name": "neonctl",
3
- "version": "0.0.1",
4
- "description": "",
5
- "main": "index.js",
6
- "scripts": {
7
- "test": "echo \"Error: no test specified\" && exit 1"
8
- },
9
- "author": "Eduard Dyckman",
10
- "license": "ISC"
2
+ "name": "neonctl",
3
+ "version": "0.0.2",
4
+ "description": "CLI tool for NeonDB Cloud management",
5
+ "main": "index.js",
6
+ "author": "NeonDB",
7
+ "license": "MIT",
8
+ "private": false,
9
+ "devDependencies": {
10
+ "@types/node": "^18.7.13",
11
+ "@types/yargs": "^17.0.11",
12
+ "@typescript-eslint/eslint-plugin": "^5.34.0",
13
+ "@typescript-eslint/parser": "^5.34.0",
14
+ "eslint": "^8.22.0",
15
+ "prettier": "^2.7.1",
16
+ "ts-node": "^10.9.1",
17
+ "typescript": "^4.7.4"
18
+ },
19
+ "dependencies": {
20
+ "open": "^8.4.0",
21
+ "openid-client": "^5.1.9",
22
+ "yargs": "^17.5.1"
23
+ },
24
+ "scripts": {
25
+ "dev": "node dev.js",
26
+ "debug": "node --inspect-brk dev.js",
27
+ "build": "tsc",
28
+ "clean": "rm -rf dist",
29
+ "start": "node index.js",
30
+ "publish": "yarn build && cd dist && npm publish"
31
+ }
11
32
  }
@@ -0,0 +1,32 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.apiCall = void 0;
4
+ const https_1 = require("https");
5
+ const apiCall = ({ apiHost, token, path, body, method = 'GET', }) => new Promise((resolve, reject) => {
6
+ const req = (0, https_1.request)(`${apiHost}/api/v1/${path}`, {
7
+ headers: {
8
+ Authorization: `Bearer ${token}`,
9
+ Accept: 'application/json',
10
+ 'Content-Type': 'application/json',
11
+ },
12
+ method,
13
+ }, (res) => {
14
+ if (res.statusCode !== 200) {
15
+ reject(new Error(`${res.statusCode}: ${res.statusMessage}`));
16
+ return;
17
+ }
18
+ let result = '';
19
+ res.on('data', (data) => {
20
+ result += data;
21
+ });
22
+ res.on('end', () => {
23
+ resolve(result);
24
+ });
25
+ });
26
+ req.on('error', reject);
27
+ if (body) {
28
+ req.write(JSON.stringify(body));
29
+ }
30
+ req.end();
31
+ });
32
+ exports.apiCall = apiCall;
@@ -0,0 +1,23 @@
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.createProject = exports.listProjects = void 0;
13
+ 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' })); });
15
+ 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
+ });
23
+ exports.createProject = createProject;
package/src/auth.js ADDED
@@ -0,0 +1,87 @@
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
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.auth = void 0;
16
+ const openid_client_1 = require("openid-client");
17
+ const node_http_1 = require("node:http");
18
+ const node_fs_1 = require("node:fs");
19
+ const node_path_1 = require("node:path");
20
+ const open_1 = __importDefault(require("open"));
21
+ const log_1 = require("./log");
22
+ // what port to listen on for incoming requests
23
+ const CONFIG_LISTEN_PORT = 5555;
24
+ // oauth server timeouts
25
+ const SERVER_TIMEOUT = 10000;
26
+ // where to wait for incoming redirect request from oauth server to arrive
27
+ const REDIRECT_URI = 'http://127.0.0.1:5555/callback';
28
+ // These scopes cannot be cancelled, they are always needed.
29
+ const DEFAULT_SCOPES = ['openid', 'offline'];
30
+ const auth = ({ oauthHost, clientId }) => __awaiter(void 0, void 0, void 0, function* () {
31
+ openid_client_1.custom.setHttpOptionsDefaults({
32
+ timeout: SERVER_TIMEOUT,
33
+ });
34
+ log_1.log.info('Discovering oauth server');
35
+ const issuer = yield openid_client_1.Issuer.discover(oauthHost);
36
+ const neonOAuthClient = new issuer.Client({
37
+ token_endpoint_auth_method: 'none',
38
+ client_id: clientId,
39
+ redirect_uris: [REDIRECT_URI],
40
+ response_types: ['code'],
41
+ });
42
+ // https://datatracker.ietf.org/doc/html/rfc6819#section-4.4.1.8
43
+ const state = openid_client_1.generators.state();
44
+ // we store the code_verifier in memory
45
+ const codeVerifier = openid_client_1.generators.codeVerifier();
46
+ const codeChallenge = openid_client_1.generators.codeChallenge(codeVerifier);
47
+ 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* () {
52
+ var _a;
53
+ //
54
+ // Wait for callback and follow oauth flow.
55
+ //
56
+ if (!((_a = request.url) === null || _a === void 0 ? void 0 : _a.startsWith('/callback'))) {
57
+ response.writeHead(404);
58
+ response.end();
59
+ return;
60
+ }
61
+ log_1.log.info(`Callback received: ${request.url}`);
62
+ const params = neonOAuthClient.callbackParams(request);
63
+ const tokenSet = yield neonOAuthClient.callback(REDIRECT_URI, params, {
64
+ code_verifier: codeVerifier,
65
+ state,
66
+ });
67
+ response.writeHead(200, { 'Content-Type': 'text/html' });
68
+ (0, node_fs_1.createReadStream)((0, node_path_1.join)(__dirname, './callback.html')).pipe(response);
69
+ resolve(tokenSet);
70
+ server.close();
71
+ }));
72
+ server.listen(CONFIG_LISTEN_PORT, () => {
73
+ log_1.log.info(`Listening on port ${CONFIG_LISTEN_PORT}`);
74
+ });
75
+ //
76
+ // Open browser to let user authenticate
77
+ //
78
+ const authUrl = neonOAuthClient.authorizationUrl({
79
+ scope: DEFAULT_SCOPES.join(' '),
80
+ state,
81
+ code_challenge: codeChallenge,
82
+ code_challenge_method: 'S256',
83
+ });
84
+ (0, open_1.default)(authUrl);
85
+ });
86
+ });
87
+ exports.auth = auth;
@@ -0,0 +1,85 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
26
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
27
+ return new (P || (P = Promise))(function (resolve, reject) {
28
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
29
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
30
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
31
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
32
+ });
33
+ };
34
+ Object.defineProperty(exports, "__esModule", { value: true });
35
+ exports.ensureAuth = exports.validateAuth = exports.authFlow = void 0;
36
+ const node_path_1 = require("node:path");
37
+ const node_fs_1 = require("node:fs");
38
+ const auth_1 = require("../auth");
39
+ const projects_1 = require("../api/projects");
40
+ const log_1 = require("../log");
41
+ const CREDENTIALS_FILE = 'credentials.json';
42
+ const authFlow = ({ configDir, oauthHost, clientId, }) => __awaiter(void 0, void 0, void 0, function* () {
43
+ if (!clientId) {
44
+ throw new Error('Missing client id');
45
+ }
46
+ const tokenSet = yield (0, auth_1.auth)({
47
+ oauthHost: oauthHost,
48
+ clientId: clientId,
49
+ });
50
+ const credentialsPath = (0, node_path_1.join)(configDir, CREDENTIALS_FILE);
51
+ (0, node_fs_1.writeFileSync)(credentialsPath, JSON.stringify(tokenSet));
52
+ log_1.log.info(`Saved credentials to ${credentialsPath}`);
53
+ log_1.log.info('Auth complete');
54
+ return tokenSet.access_token || '';
55
+ });
56
+ 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
+ const ensureAuth = (props) => __awaiter(void 0, void 0, void 0, function* () {
71
+ const credentialsPath = (0, node_path_1.join)(props.configDir, CREDENTIALS_FILE);
72
+ 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 }))) {
75
+ props.token = token;
76
+ }
77
+ else {
78
+ props.token = yield (0, exports.authFlow)(props);
79
+ }
80
+ }
81
+ else {
82
+ props.token = yield (0, exports.authFlow)(props);
83
+ }
84
+ });
85
+ exports.ensureAuth = ensureAuth;
@@ -0,0 +1,20 @@
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
+ 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
+ }
20
+ });
package/src/config.js ADDED
@@ -0,0 +1,22 @@
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.ensureConfigDir = exports.defaultDir = void 0;
13
+ const node_path_1 = require("node:path");
14
+ const node_fs_1 = require("node:fs");
15
+ const DIR_NAME = '.neonctl';
16
+ exports.defaultDir = (0, node_path_1.join)(process.cwd(), DIR_NAME);
17
+ const ensureConfigDir = ({ configDir, }) => __awaiter(void 0, void 0, void 0, function* () {
18
+ if (!(0, node_fs_1.existsSync)(configDir)) {
19
+ (0, node_fs_1.mkdirSync)(configDir);
20
+ }
21
+ });
22
+ exports.ensureConfigDir = ensureConfigDir;
package/src/index.js ADDED
@@ -0,0 +1,88 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
26
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
27
+ return new (P || (P = Promise))(function (resolve, reject) {
28
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
29
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
30
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
31
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
32
+ });
33
+ };
34
+ var __importDefault = (this && this.__importDefault) || function (mod) {
35
+ return (mod && mod.__esModule) ? mod : { "default": mod };
36
+ };
37
+ Object.defineProperty(exports, "__esModule", { value: true });
38
+ const yargs = __importStar(require("yargs"));
39
+ const package_json_1 = __importDefault(require("../package.json"));
40
+ const auth_1 = require("./commands/auth");
41
+ const config_1 = require("./config");
42
+ const builder = yargs
43
+ .scriptName(package_json_1.default.name)
44
+ .usage('$0 <cmd> [args]')
45
+ .help()
46
+ .option('apiHost', {
47
+ describe: 'The API host',
48
+ 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
+ })
58
+ // Setup config directory
59
+ .option('configDir', {
60
+ describe: 'Path to config directory',
61
+ type: 'string',
62
+ default: config_1.defaultDir,
63
+ })
64
+ .middleware(config_1.ensureConfigDir)
65
+ // Auth flow
66
+ .command('auth', 'Authenticate user', (yargs) => yargs, (args) => __awaiter(void 0, void 0, void 0, function* () {
67
+ (yield Promise.resolve().then(() => __importStar(require('./commands/auth')))).authFlow(args);
68
+ }))
69
+ // Ensure auth token
70
+ .option('token', {
71
+ describe: 'Auth token',
72
+ type: 'string',
73
+ default: '',
74
+ })
75
+ .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);
83
+ }));
84
+ (() => __awaiter(void 0, void 0, void 0, function* () {
85
+ if ((yield builder.argv)._.length === 0) {
86
+ yargs.showHelp();
87
+ }
88
+ }))();
package/src/log.js ADDED
@@ -0,0 +1,8 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.log = void 0;
4
+ exports.log = {
5
+ info: (message) => {
6
+ process.stderr.write(`${message}\n`);
7
+ },
8
+ };