@mytmpvpn/mytmpvpn-cli 1.1.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/.gitlab-ci.yml ADDED
@@ -0,0 +1,16 @@
1
+ # The Docker image that will be used to build your app
2
+ image: node:lts
3
+ # Functions that should be executed before the build script is run
4
+ before_script:
5
+ - npm ci
6
+ pages:
7
+ script:
8
+ - npm run build
9
+ artifacts:
10
+ paths:
11
+ # The folder that contains the files to be exposed at the Page URL
12
+ - public
13
+ rules:
14
+ # This ensures that only pushes to the default branch will trigger
15
+ # a pages deploy
16
+ - if: $CI_COMMIT_REF_NAME == $CI_DEFAULT_BRANCH
package/README.md ADDED
@@ -0,0 +1,63 @@
1
+ # mytmpvpn-cli
2
+
3
+ Command Line Interface for the [`MyTmpVpn`](https://gitlab.com/mytmpvpn) project.
4
+
5
+ ## Getting started
6
+
7
+ ### Pre-requisite && how to build?
8
+
9
+ 1. Install npm: https://docs.npmjs.com/downloading-and-installing-node-js-and-npm
10
+ 1. Create a parent directory:\
11
+ `mkdir mytmpvpn`
12
+ 1. Clone all projects **inside this parent directory**:\
13
+ `cd mytmpvpn;`\
14
+ `for project in mytmpvpn-common mytmpvpn-client mytmpvpn-cli;do git clone git@gitlab.com:mytmpvpn/${project}.git;done`
15
+ 1. Get the `mytmpvpn-appconfig.json` from the backend owner and put the file in `mytmpvpn-client/src` folder:\
16
+ `cp mytmpvpn-appconfig-from-backend-owner.json mytmpvpn-client/src`
17
+ 1. Go to the `mytmpvpn-cli` project and build everything: `cd mytmpvpn-cli; npm run build-all`
18
+
19
+ From there you should be able to:
20
+ 1. execute the mytmpvpn CLI: `npx mytmpvpn`
21
+ 1. Develop inside each project.
22
+
23
+ ## TODO: write down remaining sections
24
+
25
+ ## Name
26
+ Choose a self-explaining name for your project.
27
+
28
+ ## Description
29
+ Let people know what your project can do specifically. Provide context and add a link to any reference visitors might be unfamiliar with. A list of Features or a Background subsection can also be added here. If there are alternatives to your project, this is a good place to list differentiating factors.
30
+
31
+ ## Badges
32
+ On some READMEs, you may see small images that convey metadata, such as whether or not all the tests are passing for the project. You can use Shields to add some to your README. Many services also have instructions for adding a badge.
33
+
34
+ ## Visuals
35
+ Depending on what you are making, it can be a good idea to include screenshots or even a video (you'll frequently see GIFs rather than actual videos). Tools like ttygif can help, but check out Asciinema for a more sophisticated method.
36
+
37
+ ## Installation
38
+ Within a particular ecosystem, there may be a common way of installing things, such as using Yarn, NuGet, or Homebrew. However, consider the possibility that whoever is reading your README is a novice and would like more guidance. Listing specific steps helps remove ambiguity and gets people to using your project as quickly as possible. If it only runs in a specific context like a particular programming language version or operating system or has dependencies that have to be installed manually, also add a Requirements subsection.
39
+
40
+ ## Usage
41
+ Use examples liberally, and show the expected output if you can. It's helpful to have inline the smallest example of usage that you can demonstrate, while providing links to more sophisticated examples if they are too long to reasonably include in the README.
42
+
43
+ ## Support
44
+ Tell people where they can go to for help. It can be any combination of an issue tracker, a chat room, an email address, etc.
45
+
46
+ ## Roadmap
47
+ If you have ideas for releases in the future, it is a good idea to list them in the README.
48
+
49
+ ## Contributing
50
+ State if you are open to contributions and what your requirements are for accepting them.
51
+
52
+ For people who want to make changes to your project, it's helpful to have some documentation on how to get started. Perhaps there is a script that they should run or some environment variables that they need to set. Make these steps explicit. These instructions could also be useful to your future self.
53
+
54
+ You can also document commands to lint the code or run tests. These steps help to ensure high code quality and reduce the likelihood that the changes inadvertently break something. Having instructions for running tests is especially helpful if it requires external setup, such as starting a Selenium server for testing in a browser.
55
+
56
+ ## Authors and acknowledgment
57
+ Show your appreciation to those who have contributed to the project.
58
+
59
+ ## License
60
+ For open source projects, say how it is licensed.
61
+
62
+ ## Project status
63
+ If you have run out of energy or time for your project, put a note at the top of the README saying that development has slowed down or stopped completely. Someone may choose to fork your project or volunteer to step in as a maintainer or owner, allowing your project to keep going. You can also make an explicit request for maintainers.
@@ -0,0 +1,11 @@
1
+ #!/bin/bash
2
+
3
+ # This script is to simplify development with dependencies
4
+
5
+ # Order matters!
6
+ PROJECTS="../mytmpvpn-common ../mytmpvpn-client ../mytmpvpn-cli"
7
+
8
+ for project in ${PROJECTS};do
9
+ echo "#### Building ${project}"
10
+ (cd ${project} && npm install && npm run link-deps && npm run build)
11
+ done
@@ -0,0 +1,335 @@
1
+ #!/usr/bin/env -S NODE_NO_WARNINGS=1 node
2
+ "use strict";
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ // Use NODE_NO_WARNINGS=1 to get rid of the fetch node deprecated API
5
+ // https://github.com/netlify/cli/issues/4608 -- but it hangs the process: https://github.com/nodejs/node/issues/21960
6
+ const fs = require("fs");
7
+ const path = require("path");
8
+ const commander_1 = require("commander");
9
+ const log = require("loglevel");
10
+ log.setDefaultLevel("info");
11
+ const vpnlib = require("@mytmpvpn/mytmpvpn-common/models/vpn");
12
+ const peanuts = require("@mytmpvpn/mytmpvpn-common/models/peanuts");
13
+ const appconfig_1 = require("@mytmpvpn/mytmpvpn-client/appconfig");
14
+ const userconfig_1 = require("@mytmpvpn/mytmpvpn-client/userconfig");
15
+ const auth = require("@mytmpvpn/mytmpvpn-client/auth");
16
+ const mytmpvpn_client_1 = require("@mytmpvpn/mytmpvpn-client/mytmpvpn-client");
17
+ const program = new commander_1.Command();
18
+ function handleError(error, verbose = false) {
19
+ if (error.response) {
20
+ // The request was made and the server responded with a status code
21
+ // that falls out of the range of 2xx
22
+ try {
23
+ log.error(`[${error.response.status}] - ${JSON.stringify(error.response.data)}`);
24
+ }
25
+ catch (Error) {
26
+ log.error(`[${error.response.status}] - ${JSON.stringify(error.message)}`);
27
+ }
28
+ log.debug(error.response.headers);
29
+ }
30
+ else if (error.request) {
31
+ // The request was made but no response was received
32
+ // `error.request` is an instance of XMLHttpRequest in the browser and an instance of
33
+ // http.ClientRequest in node.js
34
+ log.error(`No reponse received. Check your profile and your appConfig`);
35
+ }
36
+ else {
37
+ // Something happened in setting up the request that triggered an Error
38
+ log.error(`Error while setting up the request ${JSON.stringify(error)}`);
39
+ }
40
+ log.trace(`Stack trace: ${error}`);
41
+ }
42
+ program
43
+ .name('mytmpvpn-cli')
44
+ .description('MyTmpVpn CLI')
45
+ .version('0.0.1')
46
+ .option('--verbose', 'Produce more logs')
47
+ .option('--appConfig <file>', 'Path to the application config file', (0, appconfig_1.getDefaultAppConfigFile)())
48
+ .option('--userConfig <file>', 'Path to the user config file', (0, userconfig_1.getDefaultUserConfigFile)())
49
+ .option('--profile <name>', 'Name of the profile in the user config file to use', (0, userconfig_1.getDefaultUserProfile)());
50
+ program.on('option:verbose', function () {
51
+ log.setDefaultLevel("trace");
52
+ });
53
+ program.command('list-peanuts-packs')
54
+ .description(`Returns the list of peanuts packs you can purchase. A peanuts pack contains a given number of peanuts. You need a minimum of ${peanuts.PEANUTS_CONFIG.min} peanuts to create a vpn`)
55
+ .action((_, command) => {
56
+ const options = command.optsWithGlobals();
57
+ const appConfig = (0, appconfig_1.loadAppConfig)(options.appConfig);
58
+ // We don't need authenticated user to call this API
59
+ const client = new mytmpvpn_client_1.MyTmpVpnClient(appConfig.apiUrl);
60
+ client.listPeanutsPacks()
61
+ .then(((packs) => {
62
+ log.info(JSON.stringify(packs, null, 2));
63
+ }))
64
+ .catch((err) => handleError(err));
65
+ });
66
+ program.command('get-peanuts-balance')
67
+ .description('Get the current peanuts balance')
68
+ .action((_, command) => {
69
+ const options = command.optsWithGlobals();
70
+ log.debug(`Get peanuts balance`);
71
+ auth.getLoggedInClientFromFiles({ appConfigFile: options.appConfig, userConfigFile: options.userConfig, profileName: options.profile }, (err, client) => {
72
+ if (err) {
73
+ handleError(err, options.verbose);
74
+ return;
75
+ }
76
+ client.getPeanutsBalance().then(balance => {
77
+ log.info(balance);
78
+ }).catch(err => {
79
+ handleError(err);
80
+ });
81
+ });
82
+ });
83
+ program.command('list-regions')
84
+ .description('Returns the list of all regions where vpn can be created')
85
+ .action((_, command) => {
86
+ const options = command.optsWithGlobals();
87
+ const appConfig = (0, appconfig_1.loadAppConfig)(options.appConfig);
88
+ // We don't need authenticated user to call this API
89
+ const client = new mytmpvpn_client_1.MyTmpVpnClient(appConfig.apiUrl);
90
+ client.listRegions()
91
+ .then(((regions) => {
92
+ log.info(JSON.stringify(regions, null, 2));
93
+ }))
94
+ .catch((err) => handleError(err));
95
+ });
96
+ program.command('create')
97
+ .description('Create a new vpn')
98
+ .argument('<region>', 'region where the vpn should be created, as returned by list-regions')
99
+ .option('--sync', 'wait for vpn creation completion')
100
+ .addOption(new commander_1.Option('--type <type>', 'Type of VPN')
101
+ .choices(vpnlib.getVpnConfigTypes())
102
+ .default(vpnlib.VpnType.WireGuard))
103
+ .option('--peanuts <nb>', 'Max number of peanuts to use (specify -1 for maximum)', '-1')
104
+ .action((region, _, command) => {
105
+ const options = command.optsWithGlobals();
106
+ const syncStr = options.sync ? "synchronously" : "asynchronously";
107
+ log.debug(`Creating new ${options.type} vpn into ${region} ${syncStr}`);
108
+ auth.getLoggedInClientFromFiles({ appConfigFile: options.appConfig, userConfigFile: options.userConfig, profileName: options.profile }, (err, client) => {
109
+ if (err) {
110
+ handleError(err, options.verbose);
111
+ return;
112
+ }
113
+ client.createVpn(region, { type: options.type, maxPeanuts: options.peanuts }).then(vpn => {
114
+ if (!options.sync) {
115
+ log.info(vpn);
116
+ return;
117
+ }
118
+ client.waitUntilVpnStateIs(vpn.vpnId, vpnlib.VpnState.Running).then(updatedVpn => {
119
+ log.info(updatedVpn);
120
+ }).catch(err => {
121
+ handleError(err);
122
+ });
123
+ }).catch(err => {
124
+ handleError(err);
125
+ });
126
+ });
127
+ });
128
+ program.command('delete')
129
+ .description('Delete a vpn')
130
+ .argument('<vpnId>', 'vpnId to delete')
131
+ .option('--sync', 'wait for vpn deletion completion')
132
+ .action((vpnId, _, command) => {
133
+ const options = command.optsWithGlobals();
134
+ const syncStr = options.sync ? "synchronously" : "asynchronously";
135
+ log.debug(`Deleting vpn ${vpnId} ${syncStr}`);
136
+ auth.getLoggedInClientFromFiles({ appConfigFile: options.appConfig, userConfigFile: options.userConfig, profileName: options.profile }, (err, client) => {
137
+ if (err) {
138
+ handleError(err.message || JSON.stringify(err));
139
+ return;
140
+ }
141
+ client.deleteVpn(vpnId).then(vpn => {
142
+ if (!options.sync) {
143
+ log.info(JSON.stringify(vpn));
144
+ return;
145
+ }
146
+ client.waitUntilVpnStateIs(vpnId, vpnlib.VpnState.Deleted).then(updatedVpn => {
147
+ log.info(updatedVpn);
148
+ return;
149
+ }).catch(err => {
150
+ handleError(err.response?.data || JSON.stringify(err));
151
+ });
152
+ }).catch(err => {
153
+ handleError(err.response?.data || JSON.stringify(err));
154
+ });
155
+ });
156
+ });
157
+ program.command('get')
158
+ .description('Get information on a vpn')
159
+ .argument('<vpnId>', 'vpnId to get information from')
160
+ .action((vpnId, _, command) => {
161
+ const options = command.optsWithGlobals();
162
+ auth.getLoggedInClientFromFiles({ appConfigFile: options.appConfig, userConfigFile: options.userConfig, profileName: options.profile }, (err, client) => {
163
+ if (err) {
164
+ handleError(err);
165
+ return;
166
+ }
167
+ client.getVpn(vpnId)
168
+ .then(result => log.info(result))
169
+ .catch(err => handleError(err));
170
+ });
171
+ });
172
+ program.command('download-config')
173
+ .description('Download configuration of the given vpn to the given file')
174
+ .argument('<vpnId>', 'vpnId to get config file from')
175
+ .option('--file <file>', 'file where the config should be downloaded to. Default is <vpnId>.tar.gz')
176
+ .option('--path <path>', 'path where the config file should be written to', (0, userconfig_1.getDefaultUserConfigDir)())
177
+ .action((vpnId, _, command) => {
178
+ const options = command.optsWithGlobals();
179
+ const file = options.file ? options.file : `${vpnId}.tar.gz`;
180
+ const fullpath = path.join(options.path, file);
181
+ auth.getLoggedInClientFromFiles({ appConfigFile: options.appConfig, userConfigFile: options.userConfig, profileName: options.profile }, (err, client) => {
182
+ if (err) {
183
+ handleError(err);
184
+ return;
185
+ }
186
+ client.getVpnConfig(vpnId, fs.createWriteStream(fullpath))
187
+ .then(() => log.info(fullpath))
188
+ .catch(err => handleError(err));
189
+ });
190
+ });
191
+ program.command('list')
192
+ .description('List all vpns')
193
+ .option('--region <region>', 'region to list vpns from')
194
+ .option('--exclude-state <state>', 'state to exclude from the list', 'DELETED')
195
+ .action((_, command) => {
196
+ const options = command.optsWithGlobals();
197
+ auth.getLoggedInClientFromFiles({ appConfigFile: options.appConfig, userConfigFile: options.userConfig, profileName: options.profile }, (err, client) => {
198
+ if (err) {
199
+ handleError(err);
200
+ return;
201
+ }
202
+ client.listVpns(options.state)
203
+ .then(vpns => {
204
+ log.info(JSON.stringify(vpns, null, 2));
205
+ })
206
+ .catch(err => handleError(err));
207
+ });
208
+ });
209
+ program.command('wait')
210
+ .description('Wait for vpn operation completion')
211
+ .argument('<vpnId>', 'the vpnId to wait a status change for')
212
+ .argument('<state>', 'the state to wait for')
213
+ .action((vpnId, state, _, command) => {
214
+ const options = command.optsWithGlobals();
215
+ const actualState = vpnlib.VpnState[state];
216
+ if (!actualState) {
217
+ handleError(`Unknown state: ${state}. Valid states: ${Object.values(vpnlib.VpnState)}`);
218
+ return;
219
+ }
220
+ log.debug(`Waiting for ${vpnId} state to be (at least) ${state}`);
221
+ auth.getLoggedInClientFromFiles({ appConfigFile: options.appConfig, userConfigFile: options.userConfig, profileName: options.profile }, (err, client) => {
222
+ if (err) {
223
+ handleError(err);
224
+ return;
225
+ }
226
+ client.waitUntilVpnStateIs(vpnId, actualState)
227
+ .then(vpn => {
228
+ log.info(vpn);
229
+ })
230
+ .catch(err => handleError(err));
231
+ });
232
+ });
233
+ program.command('register')
234
+ .description('Register a new user to the MyTmpVpn application')
235
+ .argument('<username>', 'the email/phone that will identify your account')
236
+ .argument('<password>', 'a password')
237
+ .action((username, password, _, command) => {
238
+ const options = command.optsWithGlobals();
239
+ var userConfig;
240
+ if (fs.existsSync(options.userConfig)) {
241
+ userConfig = (0, userconfig_1.loadUserConfig)(options.userConfig);
242
+ if (userConfig.profiles[options.profile]) {
243
+ handleError(`Profile ${options.profile} already exists in ${options.userConfig}, specify another profile name using --profile`);
244
+ return;
245
+ }
246
+ userConfig.profiles[options.profile] = {
247
+ username: username,
248
+ password: password
249
+ };
250
+ }
251
+ else {
252
+ userConfig = {
253
+ version: 1,
254
+ profiles: {
255
+ default: {
256
+ username: username,
257
+ password: password
258
+ }
259
+ }
260
+ };
261
+ }
262
+ auth.registerUserFromFiles(options.appConfig, username, password, (err, result) => {
263
+ if (err) {
264
+ handleError(err);
265
+ return;
266
+ }
267
+ log.info(`Please confirm your identity with the code sent to ${username}`);
268
+ fs.mkdir(path.dirname(options.userConfig), { recursive: true }, (err, path) => {
269
+ if (err) {
270
+ handleError(err);
271
+ return;
272
+ }
273
+ log.debug(`Directory: ${path} created`);
274
+ fs.writeFile(options.userConfig, JSON.stringify(userConfig, null, 2), (err) => {
275
+ if (err) {
276
+ handleError(err);
277
+ return;
278
+ }
279
+ });
280
+ log.info(`A new profile has been created for ${options.profile} in ${options.userConfig}`);
281
+ });
282
+ });
283
+ });
284
+ program.command('confirm-registration')
285
+ .description('Confirm registration to the MyTmpVpn application using the code that was sent to email/phone')
286
+ .argument('<username>', 'the email/phone that identify your account')
287
+ .argument('<code>', 'the code received')
288
+ .action((username, code, _, command) => {
289
+ const options = command.optsWithGlobals();
290
+ auth.confirmUserFromFiles(options.appConfig, username, code, (err, result) => {
291
+ if (err) {
292
+ handleError(err);
293
+ return;
294
+ }
295
+ log.debug(result);
296
+ log.info(`User ${username} confirmed!`);
297
+ });
298
+ });
299
+ program.addHelpText('after', `
300
+
301
+ Examples:
302
+
303
+ # Before doing anything, you need to register to the MyTmpVpn service:
304
+
305
+ $ mytmpvpn register 'your@email.com' 'StrongPassword' # Min: 8 characters with digit, lower, upper and symbols
306
+ $ mytmpvpn confirm-registration 'code' # The code you've received by email
307
+
308
+ # You then need to buy some peanuts, the list of peanuts packs can be fetched using:
309
+
310
+ $ mytmpvpn list-peanuts-packs
311
+
312
+ # Visit one of those URLs returned, and complete the purchase.
313
+ # There is no CLI for purchasing peanuts-packs.
314
+ # Once you have purchased some peanuts, your peanuts balance should show it:
315
+
316
+ $ mytmpvpn get-peanuts-balance
317
+
318
+ # Then you can use the following command at will:
319
+
320
+ # List available regions:
321
+ $ mytmpvpn list-regions
322
+
323
+ # Create a new vpn in Paris:
324
+ $ mytmpvpn --sync create 'paris' # This takes several minutes, please be patient or remove --sync
325
+
326
+ # List all my vpns:
327
+ $ mytmpvpn list
328
+
329
+ # Fetch the configuration of a given vpn
330
+ $ mytmpvpn download-config 'vpn-id' # The vpn-id is provided by the list command
331
+
332
+ # Delete a given vpn
333
+ $ mytmpvpn delete 'vpn-id' # The vpn-id is provided by the list command
334
+ `);
335
+ program.parse();
package/package.json ADDED
@@ -0,0 +1,40 @@
1
+ {
2
+ "name": "@mytmpvpn/mytmpvpn-cli",
3
+ "version": "1.1.0",
4
+ "description": "MyTmpVpn CLI",
5
+ "main": "./dist/mytmpvpn.js",
6
+ "bin": {
7
+ "@mytmpvpn/mytmpvpn": "./dist/mytmpvpn.js",
8
+ "mytmpvpn": "./dist/mytmpvpn.js"
9
+ },
10
+ "scripts": {
11
+ "build": "tsc --build && chmod +x dist/mytmpvpn.js",
12
+ "watch": "tsc -w",
13
+ "test": "jest",
14
+ "clean": "rm -rf dist/",
15
+ "link-deps": "npm link ../mytmpvpn-common ../mytmpvpn-client",
16
+ "build-all": "./build-all-dependencies"
17
+ },
18
+ "keywords": [
19
+ "VPN"
20
+ ],
21
+ "author": {
22
+ "name": "Pierre Vigneras",
23
+ "email": "pierre.vigneras@gmail.com",
24
+ "url": "https://www.linkedin.com/in/pierrevigneras/"
25
+ },
26
+ "license": "GNU AGPL",
27
+ "dependencies": {
28
+ "commander": "^9.4.1",
29
+ "loglevel": "^1.8.1",
30
+ "@mytmpvpn/mytmpvpn-client": "^1.0.0",
31
+ "@mytmpvpn/mytmpvpn-common": "^1.1.0"
32
+ },
33
+ "devDependencies": {
34
+ "@types/jest": "^29.2.2",
35
+ "@types/node": "^18.11.9",
36
+ "jest": "^29.3.0",
37
+ "ts-jest": "^29.0.3",
38
+ "typescript": "^4.8.4"
39
+ }
40
+ }