@ohos-ports/pm2 0.0.0-stage → 7.1.2-beta.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.
Files changed (267) hide show
  1. package/CHANGELOG.md +2607 -0
  2. package/CONTRIBUTING.md +124 -0
  3. package/GNU-AGPL-3.0.txt +665 -0
  4. package/LICENSE +1 -0
  5. package/README.md +255 -2
  6. package/SECURITY.md +41 -0
  7. package/bin/pm2 +3 -0
  8. package/bin/pm2-dev +3 -0
  9. package/bin/pm2-docker +3 -0
  10. package/bin/pm2-runtime +3 -0
  11. package/bin/pm2.ps1 +3 -0
  12. package/constants.js +113 -0
  13. package/index.js +12 -0
  14. package/lib/API/Configuration.js +212 -0
  15. package/lib/API/Containerizer.js +335 -0
  16. package/lib/API/Dashboard.js +726 -0
  17. package/lib/API/Deploy.js +117 -0
  18. package/lib/API/Extra.js +798 -0
  19. package/lib/API/ExtraMgmt/Docker.js +30 -0
  20. package/lib/API/Log.js +388 -0
  21. package/lib/API/LogManagement.js +351 -0
  22. package/lib/API/Modules/LOCAL.js +122 -0
  23. package/lib/API/Modules/Modularizer.js +148 -0
  24. package/lib/API/Modules/NPM.js +443 -0
  25. package/lib/API/Modules/TAR.js +368 -0
  26. package/lib/API/Modules/flagExt.js +46 -0
  27. package/lib/API/Modules/index.js +120 -0
  28. package/lib/API/Monit.js +247 -0
  29. package/lib/API/Serve.js +497 -0
  30. package/lib/API/Startup.js +630 -0
  31. package/lib/API/UX/helpers.js +213 -0
  32. package/lib/API/UX/index.js +9 -0
  33. package/lib/API/UX/pm2-describe.js +197 -0
  34. package/lib/API/UX/pm2-ls-minimal.js +31 -0
  35. package/lib/API/UX/pm2-ls.js +581 -0
  36. package/lib/API/Version.js +383 -0
  37. package/lib/API/interpreter.json +12 -0
  38. package/lib/API/pm2-plus/PM2IO.js +381 -0
  39. package/lib/API/pm2-plus/auth-strategies/CliAuth.js +306 -0
  40. package/lib/API/pm2-plus/auth-strategies/WebAuth.js +195 -0
  41. package/lib/API/pm2-plus/helpers.js +97 -0
  42. package/lib/API/pm2-plus/link.js +126 -0
  43. package/lib/API/pm2-plus/pres/motd +16 -0
  44. package/lib/API/pm2-plus/pres/motd.update +26 -0
  45. package/lib/API/pm2-plus/pres/welcome +28 -0
  46. package/lib/API/pm2-plus/process-selector.js +52 -0
  47. package/lib/API/schema.json +375 -0
  48. package/lib/API.js +1980 -0
  49. package/lib/Client.js +793 -0
  50. package/lib/Common.js +949 -0
  51. package/lib/Configuration.js +309 -0
  52. package/lib/Daemon.js +468 -0
  53. package/lib/Event.js +37 -0
  54. package/lib/God/ActionMethods.js +955 -0
  55. package/lib/God/ClusterMode.js +192 -0
  56. package/lib/God/ForkMode.js +205 -0
  57. package/lib/God/Methods.js +292 -0
  58. package/lib/God/Reload.js +300 -0
  59. package/lib/God/StdioLogger.js +239 -0
  60. package/lib/God.js +653 -0
  61. package/lib/HttpInterface.js +75 -0
  62. package/lib/OtelManager.js +74 -0
  63. package/lib/ProcessContainer.js +321 -0
  64. package/lib/ProcessContainerBun.js +355 -0
  65. package/lib/ProcessContainerFork.js +42 -0
  66. package/lib/ProcessContainerForkBun.js +31 -0
  67. package/lib/ProcessUtils.js +74 -0
  68. package/lib/TreeKill.js +111 -0
  69. package/lib/Utility.js +304 -0
  70. package/lib/VersionCheck.js +46 -0
  71. package/lib/Watcher.js +117 -0
  72. package/lib/Worker.js +200 -0
  73. package/lib/binaries/CLI.js +1092 -0
  74. package/lib/binaries/DevCLI.js +183 -0
  75. package/lib/binaries/Runtime.js +101 -0
  76. package/lib/binaries/Runtime4Docker.js +192 -0
  77. package/lib/completion.js +229 -0
  78. package/lib/completion.sh +40 -0
  79. package/lib/motd +36 -0
  80. package/lib/templates/Dockerfiles/Dockerfile-nodejs.tpl +8 -0
  81. package/lib/templates/ecosystem-es.tpl +24 -0
  82. package/lib/templates/ecosystem-simple-es.tpl +8 -0
  83. package/lib/templates/ecosystem-simple.tpl +6 -0
  84. package/lib/templates/ecosystem.tpl +22 -0
  85. package/lib/templates/init-scripts/launchd.tpl +35 -0
  86. package/lib/templates/init-scripts/openrc.tpl +52 -0
  87. package/lib/templates/init-scripts/pm2-init-amazon.sh +86 -0
  88. package/lib/templates/init-scripts/rcd-openbsd.tpl +41 -0
  89. package/lib/templates/init-scripts/rcd.tpl +44 -0
  90. package/lib/templates/init-scripts/smf.tpl +43 -0
  91. package/lib/templates/init-scripts/systemd-online.tpl +22 -0
  92. package/lib/templates/init-scripts/systemd.tpl +22 -0
  93. package/lib/templates/init-scripts/upstart.tpl +103 -0
  94. package/lib/templates/logrotate.d/pm2 +10 -0
  95. package/lib/templates/sample-apps/http-server/README.md +14 -0
  96. package/lib/templates/sample-apps/http-server/api.js +9 -0
  97. package/lib/templates/sample-apps/http-server/ecosystem.config.js +14 -0
  98. package/lib/templates/sample-apps/http-server/package.json +11 -0
  99. package/lib/templates/sample-apps/pm2-plus-metrics-actions/README.md +45 -0
  100. package/lib/templates/sample-apps/pm2-plus-metrics-actions/custom-metrics.js +66 -0
  101. package/lib/templates/sample-apps/pm2-plus-metrics-actions/ecosystem.config.js +12 -0
  102. package/lib/templates/sample-apps/pm2-plus-metrics-actions/package.json +11 -0
  103. package/lib/templates/sample-apps/python-app/README.md +4 -0
  104. package/lib/templates/sample-apps/python-app/echo.py +7 -0
  105. package/lib/templates/sample-apps/python-app/ecosystem.config.js +12 -0
  106. package/lib/templates/sample-apps/python-app/package.json +11 -0
  107. package/lib/tools/Config.js +251 -0
  108. package/lib/tools/SysMetrics.js +375 -0
  109. package/lib/tools/copydirSync.js +101 -0
  110. package/lib/tools/deleteFolderRecursive.js +19 -0
  111. package/lib/tools/find-package-json.js +74 -0
  112. package/lib/tools/fmt.js +72 -0
  113. package/lib/tools/interpreter.js +88 -0
  114. package/lib/tools/isbinaryfile.js +94 -0
  115. package/lib/tools/json5.js +752 -0
  116. package/lib/tools/multimeter/bar.js +111 -0
  117. package/lib/tools/multimeter/charm/encode.js +18 -0
  118. package/lib/tools/multimeter/charm/index.js +305 -0
  119. package/lib/tools/multimeter/index.js +76 -0
  120. package/lib/tools/open.js +56 -0
  121. package/lib/tools/passwd.js +58 -0
  122. package/lib/tools/pm2-config-keys.js +165 -0
  123. package/lib/tools/prompt.js +76 -0
  124. package/lib/tools/serviceStop.js +149 -0
  125. package/lib/tools/sexec.js +55 -0
  126. package/lib/tools/treeify.js +113 -0
  127. package/lib/tools/typestrip.js +55 -0
  128. package/lib/tools/which.js +120 -0
  129. package/lib/tools/xdg-open +861 -0
  130. package/modules/blessed/LICENSE +20 -0
  131. package/modules/blessed/README.md +34 -0
  132. package/modules/blessed/index.js +1 -0
  133. package/modules/blessed/lib/alias.js +526 -0
  134. package/modules/blessed/lib/blessed.js +32 -0
  135. package/modules/blessed/lib/colors.js +530 -0
  136. package/modules/blessed/lib/events.js +189 -0
  137. package/modules/blessed/lib/gpmclient.js +221 -0
  138. package/modules/blessed/lib/helpers.js +165 -0
  139. package/modules/blessed/lib/keys.js +339 -0
  140. package/modules/blessed/lib/program.js +4297 -0
  141. package/modules/blessed/lib/tput.js +3022 -0
  142. package/modules/blessed/lib/unicode.js +885 -0
  143. package/modules/blessed/lib/widget.js +32 -0
  144. package/modules/blessed/lib/widgets/box.js +34 -0
  145. package/modules/blessed/lib/widgets/element.js +2570 -0
  146. package/modules/blessed/lib/widgets/list.js +599 -0
  147. package/modules/blessed/lib/widgets/log.js +83 -0
  148. package/modules/blessed/lib/widgets/node.js +282 -0
  149. package/modules/blessed/lib/widgets/screen.js +2298 -0
  150. package/modules/blessed/lib/widgets/scrollablebox.js +389 -0
  151. package/modules/blessed/lib/widgets/scrollabletext.js +35 -0
  152. package/modules/blessed/lib/widgets/text.js +35 -0
  153. package/modules/blessed/usr/linux +0 -0
  154. package/modules/blessed/usr/windows-ansi +0 -0
  155. package/modules/blessed/usr/xterm +0 -0
  156. package/modules/blessed/usr/xterm-256color +0 -0
  157. package/modules/blessed/usr/xterm.termcap +243 -0
  158. package/modules/chokidar/LICENSE +21 -0
  159. package/modules/chokidar/VENDORED.md +76 -0
  160. package/modules/chokidar/index.js +979 -0
  161. package/modules/chokidar/lib/brace-expand.js +180 -0
  162. package/modules/chokidar/lib/constants.js +66 -0
  163. package/modules/chokidar/lib/fsevents-handler.js +526 -0
  164. package/modules/chokidar/lib/nodefs-handler.js +654 -0
  165. package/modules/fclone.js +49 -0
  166. package/modules/pm2-axon/index.js +2 -0
  167. package/modules/pm2-axon/lib/configurable/History.md +5 -0
  168. package/modules/pm2-axon/lib/configurable/Makefile +7 -0
  169. package/modules/pm2-axon/lib/configurable/Readme.md +57 -0
  170. package/modules/pm2-axon/lib/configurable/index.js +2 -0
  171. package/modules/pm2-axon/lib/configurable/lib/configurable.js +47 -0
  172. package/modules/pm2-axon/lib/configurable/package.json +68 -0
  173. package/modules/pm2-axon/lib/index.js +44 -0
  174. package/modules/pm2-axon/lib/plugins/queue.js +71 -0
  175. package/modules/pm2-axon/lib/plugins/round-robin.js +55 -0
  176. package/modules/pm2-axon/lib/sockets/pub-emitter.js +26 -0
  177. package/modules/pm2-axon/lib/sockets/pub.js +77 -0
  178. package/modules/pm2-axon/lib/sockets/pull.js +37 -0
  179. package/modules/pm2-axon/lib/sockets/push.js +32 -0
  180. package/modules/pm2-axon/lib/sockets/rep.js +73 -0
  181. package/modules/pm2-axon/lib/sockets/req.js +101 -0
  182. package/modules/pm2-axon/lib/sockets/sock.js +430 -0
  183. package/modules/pm2-axon/lib/sockets/sub-emitter.js +92 -0
  184. package/modules/pm2-axon/lib/sockets/sub.js +147 -0
  185. package/modules/pm2-axon/lib/utils.js +19 -0
  186. package/modules/pm2-axon-rpc/index.js +3 -0
  187. package/modules/pm2-axon-rpc/lib/client.js +63 -0
  188. package/modules/pm2-axon-rpc/lib/server.js +139 -0
  189. package/modules/pm2-io-agent/LICENSE +661 -0
  190. package/modules/pm2-io-agent/README.md +62 -0
  191. package/modules/pm2-io-agent/config.js +30 -0
  192. package/modules/pm2-io-agent/constants.js +118 -0
  193. package/modules/pm2-io-agent/index.js +2 -0
  194. package/modules/pm2-io-agent/src/InteractorClient.js +513 -0
  195. package/modules/pm2-io-agent/src/InteractorDaemon.js +455 -0
  196. package/modules/pm2-io-agent/src/PM2Client.js +112 -0
  197. package/modules/pm2-io-agent/src/PM2Interface.js +180 -0
  198. package/modules/pm2-io-agent/src/TransporterInterface.js +173 -0
  199. package/modules/pm2-io-agent/src/Utility.js +392 -0
  200. package/modules/pm2-io-agent/src/WatchDog.js +70 -0
  201. package/modules/pm2-io-agent/src/push/DataRetriever.js +77 -0
  202. package/modules/pm2-io-agent/src/push/PushInteractor.js +206 -0
  203. package/modules/pm2-io-agent/src/push/TransactionAggregator.js +670 -0
  204. package/modules/pm2-io-agent/src/reverse/ReverseInteractor.js +128 -0
  205. package/modules/pm2-io-agent/src/transporters/Transporter.js +129 -0
  206. package/modules/pm2-io-agent/src/transporters/WebsocketTransport.js +202 -0
  207. package/modules/pm2-io-agent/src/utils/BinaryHeap.js +135 -0
  208. package/modules/pm2-io-agent/src/utils/EDS.js +111 -0
  209. package/modules/pm2-io-agent/src/utils/probes/Histogram.js +204 -0
  210. package/modules/pm2-io-agent/src/utils/units.js +10 -0
  211. package/modules/pm2-io-bpm/configuration.js +141 -0
  212. package/modules/pm2-io-bpm/constants.js +10 -0
  213. package/modules/pm2-io-bpm/featureManager.js +110 -0
  214. package/modules/pm2-io-bpm/features/dependencies.js +48 -0
  215. package/modules/pm2-io-bpm/features/events.js +50 -0
  216. package/modules/pm2-io-bpm/features/metrics.js +102 -0
  217. package/modules/pm2-io-bpm/features/notify.js +238 -0
  218. package/modules/pm2-io-bpm/features/profiling.js +70 -0
  219. package/modules/pm2-io-bpm/features/tracing.js +174 -0
  220. package/modules/pm2-io-bpm/index.js +11 -0
  221. package/modules/pm2-io-bpm/metrics/eventLoopMetrics.js +136 -0
  222. package/modules/pm2-io-bpm/metrics/httpMetrics.js +175 -0
  223. package/modules/pm2-io-bpm/metrics/network.js +132 -0
  224. package/modules/pm2-io-bpm/metrics/runtime.js +161 -0
  225. package/modules/pm2-io-bpm/metrics/v8.js +104 -0
  226. package/modules/pm2-io-bpm/otel/constants.js +7 -0
  227. package/modules/pm2-io-bpm/otel/custom-zipkin-exporter/platform/index.js +17 -0
  228. package/modules/pm2-io-bpm/otel/custom-zipkin-exporter/platform/node/index.js +17 -0
  229. package/modules/pm2-io-bpm/otel/custom-zipkin-exporter/platform/node/util.js +51 -0
  230. package/modules/pm2-io-bpm/otel/custom-zipkin-exporter/transform.js +137 -0
  231. package/modules/pm2-io-bpm/otel/custom-zipkin-exporter/types.js +24 -0
  232. package/modules/pm2-io-bpm/otel/custom-zipkin-exporter/utils.js +23 -0
  233. package/modules/pm2-io-bpm/otel/custom-zipkin-exporter/zipkin.js +149 -0
  234. package/modules/pm2-io-bpm/pmx.js +380 -0
  235. package/modules/pm2-io-bpm/profilers/addonProfiler.js +193 -0
  236. package/modules/pm2-io-bpm/profilers/inspectorProfiler.js +302 -0
  237. package/modules/pm2-io-bpm/serviceManager.js +21 -0
  238. package/modules/pm2-io-bpm/services/actions.js +159 -0
  239. package/modules/pm2-io-bpm/services/inspector.js +43 -0
  240. package/modules/pm2-io-bpm/services/metrics.js +186 -0
  241. package/modules/pm2-io-bpm/services/runtimeStats.js +54 -0
  242. package/modules/pm2-io-bpm/services/transport.js +11 -0
  243. package/modules/pm2-io-bpm/transports/IPCTransport.js +115 -0
  244. package/modules/pm2-io-bpm/utils/BinaryHeap.js +134 -0
  245. package/modules/pm2-io-bpm/utils/EDS.js +113 -0
  246. package/modules/pm2-io-bpm/utils/EWMA.js +32 -0
  247. package/modules/pm2-io-bpm/utils/autocast.js +61 -0
  248. package/modules/pm2-io-bpm/utils/metrics/counter.js +33 -0
  249. package/modules/pm2-io-bpm/utils/metrics/gauge.js +23 -0
  250. package/modules/pm2-io-bpm/utils/metrics/histogram.js +192 -0
  251. package/modules/pm2-io-bpm/utils/metrics/meter.js +46 -0
  252. package/modules/pm2-io-bpm/utils/miscellaneous.js +19 -0
  253. package/modules/pm2-io-bpm/utils/module.js +67 -0
  254. package/modules/pm2-io-bpm/utils/shimmer.js +19 -0
  255. package/modules/pm2-io-bpm/utils/stackParser.js +160 -0
  256. package/modules/pm2-io-bpm/utils/transactionAggregator.js +429 -0
  257. package/modules/pm2-io-bpm/utils/units.js +16 -0
  258. package/modules/vizion/LICENSE +13 -0
  259. package/modules/vizion/README.md +133 -0
  260. package/modules/vizion/index.js +1 -0
  261. package/modules/vizion/lib/git/git.js +247 -0
  262. package/modules/vizion/lib/vizion.js +52 -0
  263. package/package.json +170 -4
  264. package/paths.js +121 -0
  265. package/pm2 +11 -0
  266. package/types/index.d.ts +732 -0
  267. package/types/tsconfig.json +14 -0
@@ -0,0 +1,381 @@
1
+ 'use strict'
2
+
3
+ var cst = require('../../../constants.js');
4
+ const chalk = require('ansis');
5
+ const path = require('path');
6
+ const fs = require('fs');
7
+ const Table = require('cli-tableau');
8
+ const pkg = require('../../../package.json')
9
+ const IOAPI = require('@pm2/js-api')
10
+ const promptly = require('../../tools/prompt')
11
+ var CLIStrategy = require('./auth-strategies/CliAuth')
12
+ var WebStrategy = require('./auth-strategies/WebAuth')
13
+ const execFile = require('child_process').execFile
14
+
15
+ const OAUTH_CLIENT_ID_WEB = '138558311'
16
+ const OAUTH_CLIENT_ID_CLI = '0943857435'
17
+
18
+ module.exports = class PM2ioHandler {
19
+
20
+ static usePM2Client (instance) {
21
+ this.pm2 = instance
22
+ }
23
+
24
+ static strategy () {
25
+ switch (process.platform) {
26
+ case 'darwin': {
27
+ return new WebStrategy({
28
+ client_id: OAUTH_CLIENT_ID_WEB
29
+ })
30
+ }
31
+ case 'win32': {
32
+ return new WebStrategy({
33
+ client_id: OAUTH_CLIENT_ID_WEB
34
+ })
35
+ }
36
+ case 'linux': {
37
+ const isDesktop = process.env.XDG_CURRENT_DESKTOP || process.env.XDG_SESSION_DESKTOP || process.env.DISPLAY
38
+ const isSSH = process.env.SSH_TTY || process.env.SSH_CONNECTION
39
+ if (isDesktop && !isSSH) {
40
+ return new WebStrategy({
41
+ client_id: OAUTH_CLIENT_ID_WEB
42
+ })
43
+ } else {
44
+ return new CLIStrategy({
45
+ client_id: OAUTH_CLIENT_ID_CLI
46
+ })
47
+ }
48
+ }
49
+ default: {
50
+ return new CLIStrategy({
51
+ client_id: OAUTH_CLIENT_ID_CLI
52
+ })
53
+ }
54
+ }
55
+ }
56
+
57
+ static init () {
58
+ this._strategy = this.strategy()
59
+ /**
60
+ * If you are using a local backend you should give those options :
61
+ * {
62
+ * services: {
63
+ * API: 'http://localhost:3000',
64
+ * OAUTH: 'http://localhost:3100'
65
+ * }
66
+ * }
67
+ */
68
+ this.io = new IOAPI().use(this._strategy)
69
+ }
70
+
71
+ static launch (command, opts) {
72
+ // first init the strategy and the io client
73
+ this.init()
74
+
75
+ switch (command) {
76
+ case 'connect' :
77
+ case 'login' :
78
+ case 'register' :
79
+ case undefined :
80
+ case 'authenticate' : {
81
+ this.authenticate()
82
+ break
83
+ }
84
+ case 'validate' : {
85
+ this.validateAccount(opts)
86
+ break
87
+ }
88
+ case 'help' :
89
+ case 'welcome': {
90
+ var dt = fs.readFileSync(path.join(__dirname, './pres/welcome'));
91
+ console.log(dt.toString());
92
+ return process.exit(0)
93
+ }
94
+ case 'logout': {
95
+ this._strategy.isAuthenticated().then(isConnected => {
96
+ // try to kill the agent anyway
97
+ this.pm2.killAgent(err => {})
98
+
99
+ if (isConnected === false) {
100
+ console.log(`${cst.PM2_IO_MSG} Already disconnected`)
101
+ return process.exit(0)
102
+ }
103
+
104
+ this._strategy._retrieveTokens((err, tokens) => {
105
+ if (err) {
106
+ console.log(`${cst.PM2_IO_MSG} Successfully disconnected`)
107
+ return process.exit(0)
108
+ }
109
+ this._strategy.deleteTokens(this.io).then(_ => {
110
+ console.log(`${cst.PM2_IO_MSG} Successfully disconnected`)
111
+ return process.exit(0)
112
+ }).catch(err => {
113
+ console.log(`${cst.PM2_IO_MSG_ERR} Unexpected error: ${err.message}`)
114
+ return process.exit(1)
115
+ })
116
+ })
117
+ }).catch(err => {
118
+ console.error(`${cst.PM2_IO_MSG_ERR} Failed to logout: ${err.message}`)
119
+ console.error(`${cst.PM2_IO_MSG_ERR} You can also contact us to get help: contact@pm2.io`)
120
+ })
121
+ break
122
+ }
123
+ case 'create': {
124
+ this._strategy.isAuthenticated().then(res => {
125
+ // if the user isn't authenticated, we make them do the whole flow
126
+ if (res !== true) {
127
+ this.authenticate()
128
+ } else {
129
+ this.createBucket(this.createBucketHandler.bind(this))
130
+ }
131
+ }).catch(err => {
132
+ console.error(`${cst.PM2_IO_MSG_ERR} Failed to create to the bucket: ${err.message}`)
133
+ console.error(`${cst.PM2_IO_MSG_ERR} You can also contact us to get help: contact@pm2.io`)
134
+ })
135
+ break
136
+ }
137
+ case 'web': {
138
+ this._strategy.isAuthenticated().then(res => {
139
+ // if the user isn't authenticated, we make them do the whole flow
140
+ if (res === false) {
141
+ console.error(`${cst.PM2_IO_MSG_ERR} You need to be authenticated to do that, please use: pm2 plus login`)
142
+ return process.exit(1)
143
+ }
144
+ this._strategy._retrieveTokens(() => {
145
+ return this.openUI()
146
+ })
147
+ }).catch(err => {
148
+ console.error(`${cst.PM2_IO_MSG_ERR} Failed to open the UI: ${err.message}`)
149
+ console.error(`${cst.PM2_IO_MSG_ERR} You can also contact us to get help: contact@pm2.io`)
150
+ })
151
+ break
152
+ }
153
+ default : {
154
+ console.log(`${cst.PM2_IO_MSG_ERR} Invalid command ${command}, available : login,register,validate,connect or web`)
155
+ process.exit(1)
156
+ }
157
+ }
158
+ }
159
+
160
+ static openUI () {
161
+ this.io.bucket.retrieveAll().then(res => {
162
+ const buckets = res.data
163
+
164
+ if (buckets.length === 0) {
165
+ return this.createBucket((err, bucket) => {
166
+ if (err) {
167
+ console.error(`${cst.PM2_IO_MSG_ERR} Failed to connect to the bucket: ${err.message}`)
168
+ if (bucket) {
169
+ console.error(`${cst.PM2_IO_MSG_ERR} You can retry using: pm2 plus link ${bucket.secret_id} ${bucket.public_id}`)
170
+ }
171
+ console.error(`${cst.PM2_IO_MSG_ERR} You can also contact us to get help: contact@pm2.io`)
172
+ return process.exit(0)
173
+ }
174
+ const targetURL = `https://app.pm2.io/#/bucket/${bucket._id}`
175
+ console.log(`${cst.PM2_IO_MSG} Please follow the popup or go to this URL :`, '\n', ' ', targetURL)
176
+ this.open(targetURL)
177
+ return process.exit(0)
178
+ })
179
+ }
180
+
181
+ var table = new Table({
182
+ style : {'padding-left' : 1, head : ['cyan', 'bold'], compact : true},
183
+ head : ['Bucket name', 'Plan type']
184
+ })
185
+
186
+ buckets.forEach(function(bucket) {
187
+ table.push([bucket.name, bucket.credits.offer_type])
188
+ })
189
+ console.log(table.toString())
190
+ console.log(`${cst.PM2_IO_MSG} If you don't want to open the UI to a bucket, type 'none'`)
191
+
192
+ const choices = buckets.map(bucket => bucket.name)
193
+ choices.push('none')
194
+
195
+ promptly.choose(`${cst.PM2_IO_MSG} Type the name of the bucket you want to connect to :`, choices, (err, value) => {
196
+ if (value === 'none') process.exit(0)
197
+
198
+ const bucket = buckets.find(bucket => bucket.name === value)
199
+ if (bucket === undefined) return process.exit(0)
200
+
201
+ const targetURL = `https://app.pm2.io/#/bucket/${bucket._id}`
202
+ console.log(`${cst.PM2_IO_MSG} Please follow the popup or go to this URL :`, '\n', ' ', targetURL)
203
+ this.open(targetURL)
204
+ return process.exit(0)
205
+ })
206
+ })
207
+ }
208
+
209
+ static validateAccount (token) {
210
+ this.io.auth.validEmail(token)
211
+ .then(res => {
212
+ console.log(`${cst.PM2_IO_MSG} Email succesfully validated.`)
213
+ console.log(`${cst.PM2_IO_MSG} You can now proceed and use: pm2 plus connect`)
214
+ return process.exit(0)
215
+ }).catch(err => {
216
+ if (err.status === 401) {
217
+ console.error(`${cst.PM2_IO_MSG_ERR} Invalid token`)
218
+ return process.exit(1)
219
+ } else if (err.status === 301) {
220
+ console.log(`${cst.PM2_IO_MSG} Email succesfully validated.`)
221
+ console.log(`${cst.PM2_IO_MSG} You can now proceed and use: pm2 plus connect`)
222
+ return process.exit(0)
223
+ }
224
+ const msg = err.data ? err.data.error_description || err.data.msg : err.message
225
+ console.error(`${cst.PM2_IO_MSG_ERR} Failed to validate your email: ${msg}`)
226
+ console.error(`${cst.PM2_IO_MSG_ERR} You can also contact us to get help: contact@pm2.io`)
227
+ return process.exit(1)
228
+ })
229
+ }
230
+
231
+ static createBucketHandler (err, bucket) {
232
+ if (err) {
233
+ console.trace(`${cst.PM2_IO_MSG_ERR} Failed to connect to the bucket: ${err.message}`)
234
+ if (bucket) {
235
+ console.error(`${cst.PM2_IO_MSG_ERR} You can retry using: pm2 plus link ${bucket.secret_id} ${bucket.public_id}`)
236
+ }
237
+ console.error(`${cst.PM2_IO_MSG_ERR} You can also contact us to get help: contact@pm2.io`)
238
+ return process.exit(0)
239
+ }
240
+ if (bucket === undefined) {
241
+ return process.exit(0)
242
+ }
243
+ console.log(`${cst.PM2_IO_MSG} Successfully connected to bucket ${bucket.name}`)
244
+ var targetURL = `https://app.pm2.io/#/bucket/${bucket._id}`
245
+ console.log(`${cst.PM2_IO_MSG} You can use the web interface over there: ${targetURL}`)
246
+ this.open(targetURL)
247
+ return process.exit(0)
248
+ }
249
+
250
+ static createBucket (cb) {
251
+ console.log(`${cst.PM2_IO_MSG} By default we allow you to trial PM2 Plus for 14 days without any credit card.`)
252
+
253
+ this.io.bucket.create({
254
+ name: 'PM2 Plus Monitoring'
255
+ }).then(res => {
256
+ const bucket = res.data.bucket
257
+
258
+ console.log(`${cst.PM2_IO_MSG} Successfully created the bucket`)
259
+ this.pm2.link({
260
+ public_key: bucket.public_id,
261
+ secret_key: bucket.secret_id,
262
+ pm2_version: pkg.version
263
+ }, (err) => {
264
+ if (err) {
265
+ return cb(new Error('Failed to connect your local PM2 to your bucket'), bucket)
266
+ } else {
267
+ return cb(null, bucket)
268
+ }
269
+ })
270
+ }).catch(err => {
271
+ return cb(new Error(`Failed to create a bucket: ${err.message}`))
272
+ })
273
+ }
274
+
275
+ /**
276
+ * Connect the local agent to a specific bucket
277
+ * @param {Function} cb
278
+ */
279
+ static connectToBucket (cb) {
280
+ this.io.bucket.retrieveAll().then(res => {
281
+ const buckets = res.data
282
+
283
+ if (buckets.length === 0) {
284
+ return this.createBucket(cb)
285
+ }
286
+
287
+ var table = new Table({
288
+ style : {'padding-left' : 1, head : ['cyan', 'bold'], compact : true},
289
+ head : ['Bucket name', 'Plan type']
290
+ })
291
+
292
+ buckets.forEach(function(bucket) {
293
+ table.push([bucket.name, bucket.payment.offer_type])
294
+ })
295
+ console.log(table.toString())
296
+ console.log(`${cst.PM2_IO_MSG} If you don't want to connect to a bucket, type 'none'`)
297
+
298
+ const choices = buckets.map(bucket => bucket.name)
299
+ choices.push('none')
300
+
301
+ promptly.choose(`${cst.PM2_IO_MSG} Type the name of the bucket you want to connect to :`, choices, (err, value) => {
302
+ if (value === 'none') return cb()
303
+
304
+ const bucket = buckets.find(bucket => bucket.name === value)
305
+ if (bucket === undefined) return cb()
306
+ this.pm2.link({
307
+ public_key: bucket.public_id,
308
+ secret_key: bucket.secret_id,
309
+ pm2_version: pkg.version
310
+ }, (err) => {
311
+ return err ? cb(err) : cb(null, bucket)
312
+ })
313
+ })
314
+ })
315
+ }
316
+
317
+ /**
318
+ * Authenticate the user with either of the strategy
319
+ * @param {Function} cb
320
+ */
321
+ static authenticate () {
322
+ this._strategy._retrieveTokens((err, tokens) => {
323
+ if (err) {
324
+ const msg = err.data ? err.data.error_description || err.data.msg : err.message
325
+ console.log(`${cst.PM2_IO_MSG_ERR} Unexpected error : ${msg}`)
326
+ return process.exit(1)
327
+ }
328
+ console.log(`${cst.PM2_IO_MSG} Successfully authenticated`)
329
+ this.io.user.retrieve().then(res => {
330
+ const user = res.data
331
+
332
+ this.io.user.retrieve().then(res => {
333
+ const tmpUser = res.data
334
+ console.log(`${cst.PM2_IO_MSG} Successfully validated`)
335
+ this.connectToBucket(this.createBucketHandler.bind(this))
336
+ })
337
+ })
338
+ })
339
+ }
340
+
341
+ static open (target, appName, callback) {
342
+ if (typeof (appName) === 'function') {
343
+ callback = appName
344
+ appName = null
345
+ }
346
+
347
+ let cmd
348
+ let args = []
349
+
350
+ switch (process.platform) {
351
+ case 'darwin': {
352
+ cmd = 'open'
353
+ if (appName) args.push('-a', appName)
354
+ args.push(target)
355
+ break
356
+ }
357
+ case 'win32': {
358
+ cmd = 'cmd'
359
+ args = ['/c', 'start', '""']
360
+ if (appName) args.push(appName)
361
+ args.push(target)
362
+ break
363
+ }
364
+ default: {
365
+ cmd = appName || 'xdg-open'
366
+ args.push(target)
367
+ break
368
+ }
369
+ }
370
+
371
+ if (process.env.SUDO_USER) {
372
+ if (!/^[a-zA-Z0-9._-]+$/.test(process.env.SUDO_USER)) {
373
+ return callback && callback(new Error('Invalid SUDO_USER'))
374
+ }
375
+ args = ['-u', process.env.SUDO_USER, cmd].concat(args)
376
+ cmd = 'sudo'
377
+ }
378
+
379
+ return execFile(cmd, args, callback)
380
+ }
381
+ }
@@ -0,0 +1,306 @@
1
+ 'use strict'
2
+
3
+ const AuthStrategy = require('@pm2/js-api/src/auth_strategies/strategy')
4
+ const http = require('http')
5
+ const fs = require('fs')
6
+ const exec = require('child_process').exec
7
+ const tryEach = require('async/tryEach')
8
+ const path = require('path')
9
+ const os = require('os')
10
+ const chalk = require('ansis')
11
+ const cst = require('../../../../constants.js')
12
+ const promptly = require('../../../tools/prompt')
13
+
14
+ module.exports = class CliStrategy extends AuthStrategy {
15
+ // the client will try to call this but we handle this part ourselves
16
+ retrieveTokens (km, cb) {
17
+ this.authenticated = false
18
+ this.callback = cb
19
+ this.km = km
20
+ this.BASE_URI = 'https://id.keymetrics.io';
21
+ }
22
+
23
+ // so the cli know if we need to tell user to login/register
24
+ isAuthenticated () {
25
+ return new Promise((resolve, reject) => {
26
+ if (this.authenticated) return resolve(true)
27
+
28
+ let tokensPath = cst.PM2_IO_ACCESS_TOKEN
29
+ fs.readFile(tokensPath, (err, tokens) => {
30
+ if (err && err.code === 'ENOENT') return resolve(false)
31
+ if (err) return reject(err)
32
+
33
+ // verify that the token is valid
34
+ try {
35
+ tokens = JSON.parse(tokens || '{}')
36
+ } catch (err) {
37
+ fs.unlinkSync(tokensPath)
38
+ return resolve(false)
39
+ }
40
+
41
+ // if the refresh tokens is here, the user could be automatically authenticated
42
+ return resolve(typeof tokens.refresh_token === 'string')
43
+ })
44
+ })
45
+ }
46
+
47
+ verifyToken (refresh) {
48
+ return this.km.auth.retrieveToken({
49
+ client_id: this.client_id,
50
+ refresh_token: refresh
51
+ })
52
+ }
53
+
54
+ // called when we are sure the user asked to be logged in
55
+ _retrieveTokens (optionalCallback) {
56
+ const km = this.km
57
+ const cb = this.callback
58
+
59
+ tryEach([
60
+ // try to find the token via the environment
61
+ (next) => {
62
+ if (!process.env.PM2_IO_TOKEN) {
63
+ return next(new Error('No token in env'))
64
+ }
65
+ this.verifyToken(process.env.PM2_IO_TOKEN)
66
+ .then((res) => {
67
+ return next(null, res.data)
68
+ }).catch(next)
69
+ },
70
+ // try to find it in the file system
71
+ (next) => {
72
+ fs.readFile(cst.PM2_IO_ACCESS_TOKEN, (err, tokens) => {
73
+ if (err) return next(err)
74
+ // verify that the token is valid
75
+ tokens = JSON.parse(tokens || '{}')
76
+ if (new Date(tokens.expire_at) > new Date(new Date().toISOString())) {
77
+ return next(null, tokens)
78
+ }
79
+
80
+ this.verifyToken(tokens.refresh_token)
81
+ .then((res) => {
82
+ return next(null, res.data)
83
+ }).catch(next)
84
+ })
85
+ },
86
+ // otherwise make the whole flow
87
+ (next) => {
88
+ return this.authenticate((err, data) => {
89
+ if (err instanceof Error) return next(err)
90
+ // verify that the token is valid
91
+ this.verifyToken(data.refresh_token)
92
+ .then((res) => {
93
+ return next(null, res.data)
94
+ }).catch(next)
95
+ })
96
+ }
97
+ ], (err, result) => {
98
+ // if present run the optional callback
99
+ if (typeof optionalCallback === 'function') {
100
+ optionalCallback(err, result)
101
+ }
102
+
103
+ if (result.refresh_token) {
104
+ this.authenticated = true
105
+ let file = cst.PM2_IO_ACCESS_TOKEN
106
+ fs.writeFile(file, JSON.stringify(result), () => {
107
+ return cb(err, result)
108
+ })
109
+ } else {
110
+ return cb(err, result)
111
+ }
112
+ })
113
+ }
114
+
115
+ authenticate (cb) {
116
+ console.log(`${cst.PM2_IO_MSG} Using non-browser authentication.`)
117
+ promptly.confirm(`${cst.PM2_IO_MSG} Do you have a pm2.io account? (y/n)`, (err, answer) => {
118
+ // Either login or register
119
+ return answer === true ? this.login(cb) : this.register(cb)
120
+ })
121
+ }
122
+
123
+ login (cb) {
124
+ let retry = () => {
125
+ promptly.prompt(`${cst.PM2_IO_MSG} Your username or email: `, (err, username) => {
126
+ if (err) return retry();
127
+
128
+ promptly.password(`${cst.PM2_IO_MSG} Your password: `, { replace : '*' }, (err, password) => {
129
+ if (err) return retry();
130
+
131
+ console.log(`${cst.PM2_IO_MSG} Authenticating ...`)
132
+ this._loginUser({
133
+ username: username,
134
+ password: password
135
+ }, (err, data) => {
136
+ if (err) {
137
+ console.error(`${cst.PM2_IO_MSG_ERR} Failed to authenticate: ${err.message}`)
138
+ return retry()
139
+ }
140
+ return cb(null, data)
141
+ })
142
+ })
143
+ })
144
+ }
145
+
146
+ retry()
147
+ }
148
+
149
+ register (cb) {
150
+ console.log(`${cst.PM2_IO_MSG} No problem ! We just need few informations to create your account`)
151
+
152
+ var retry = () => {
153
+ promptly.prompt(`${cst.PM2_IO_MSG} Please choose an username :`, {
154
+ validator : this._validateUsername,
155
+ retry : true
156
+ }, (err, username) => {
157
+ promptly.prompt(`${cst.PM2_IO_MSG} Please choose an email :`, {
158
+ validator : this._validateEmail,
159
+ retry : true
160
+ },(err, email) => {
161
+ promptly.password(`${cst.PM2_IO_MSG} Please choose a password :`, { replace : '*' }, (err, password) => {
162
+ promptly.confirm(`${cst.PM2_IO_MSG} Do you accept the terms and privacy policy (https://pm2.io/legals/terms_conditions.pdf) ? (y/n)`, (err, answer) => {
163
+ if (err) {
164
+ console.error(chalk.bold.red(err));
165
+ return retry()
166
+ } else if (answer === false) {
167
+ console.error(`${cst.PM2_IO_MSG_ERR} You must accept the terms and privacy policy to contiue.`)
168
+ return retry()
169
+ }
170
+
171
+ this._registerUser({
172
+ email : email,
173
+ password : password,
174
+ username : username
175
+ }, (err, data) => {
176
+ console.log('\n')
177
+ if (err) {
178
+ console.error(`${cst.PM2_IO_MSG_ERR} Unexpect error: ${err.message}`)
179
+ console.error(`${cst.PM2_IO_MSG_ERR} You can also contact us to get help: contact@pm2.io`)
180
+ return process.exit(1)
181
+ }
182
+ return cb(undefined, data)
183
+ })
184
+ })
185
+ })
186
+ })
187
+ })
188
+ }
189
+ retry()
190
+ }
191
+
192
+ /**
193
+ * Register function
194
+ * @param opts.username
195
+ * @param opts.password
196
+ * @param opts.email
197
+ */
198
+ _registerUser (opts, cb) {
199
+ const data = Object.assign(opts, {
200
+ password_confirmation: opts.password,
201
+ accept_terms: true
202
+ })
203
+ fetch(this.BASE_URI + '/api/oauth/register', {
204
+ method: 'POST',
205
+ headers: {
206
+ 'Content-Type': 'application/json',
207
+ 'X-Register-Provider': 'pm2-register',
208
+ 'x-client-id': this.client_id
209
+ },
210
+ body: JSON.stringify(data)
211
+ })
212
+ .then(res => res.json())
213
+ .then(body => {
214
+ if (body.email && body.email.message) return cb(new Error(body.email.message))
215
+ if (body.username && body.username.message) return cb(new Error(body.username.message))
216
+ if (!body.access_token) return cb(new Error(body.msg))
217
+ return cb(null, {
218
+ refresh_token : body.refresh_token.token,
219
+ access_token : body.access_token.token
220
+ })
221
+ })
222
+ .catch(err => cb(err));
223
+ }
224
+
225
+ _loginUser (user_info, cb) {
226
+ const URL_AUTH = '/api/oauth/authorize?response_type=token&scope=all&client_id=' +
227
+ this.client_id + '&redirect_uri=http://localhost:43532';
228
+
229
+ var extractCookies = (res) => {
230
+ return (res.headers.getSetCookie() || [])
231
+ .map(c => c.split(';')[0]).join('; ');
232
+ };
233
+
234
+ fetch(this.BASE_URI + URL_AUTH, { redirect: 'manual' })
235
+ .then(res => {
236
+ var cookie = extractCookies(res);
237
+
238
+ return fetch(this.BASE_URI + '/api/oauth/login', {
239
+ method: 'POST',
240
+ headers: {
241
+ 'Content-Type': 'application/json',
242
+ 'Cookie': cookie
243
+ },
244
+ body: JSON.stringify(user_info),
245
+ redirect: 'manual'
246
+ }).then(resp => {
247
+ if (resp.status != 200 && resp.status != 302) return cb(new Error('Wrong credentials'))
248
+
249
+ var location = resp.headers.get('x-redirect')
250
+ if (!location) return cb(new Error('Missing redirect header from server'))
251
+
252
+ return fetch(this.BASE_URI + location, {
253
+ headers: { 'Cookie': cookie },
254
+ redirect: 'manual'
255
+ }).then(res => {
256
+ var redirectLocation = res.headers.get('location')
257
+ if (!redirectLocation) return cb(new Error('Missing location header from server'))
258
+ var parsedLocation = new URL(redirectLocation, this.BASE_URI);
259
+ var refresh_token = parsedLocation.searchParams.get('access_token');
260
+
261
+ return fetch(this.BASE_URI + '/api/oauth/token', {
262
+ method: 'POST',
263
+ headers: {
264
+ 'Content-Type': 'application/json',
265
+ 'Cookie': cookie
266
+ },
267
+ body: JSON.stringify({
268
+ client_id : this.client_id,
269
+ grant_type : 'refresh_token',
270
+ refresh_token : refresh_token,
271
+ scope : 'all'
272
+ })
273
+ }).then(res => res.json()).then(body => cb(null, body));
274
+ });
275
+ });
276
+ })
277
+ .catch(err => cb(err));
278
+ }
279
+
280
+ _validateEmail (email) {
281
+ var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
282
+ if (re.test(email) == false)
283
+ throw new Error('Not an email');
284
+ return email;
285
+ }
286
+
287
+ _validateUsername (value) {
288
+ if (value.length < 6) {
289
+ throw new Error('Min length of 6');
290
+ }
291
+ return value;
292
+ };
293
+
294
+ deleteTokens (km) {
295
+ return new Promise((resolve, reject) => {
296
+ // revoke the refreshToken
297
+ km.auth.revoke()
298
+ .then(res => {
299
+ // remove the token from the filesystem
300
+ let file = cst.PM2_IO_ACCESS_TOKEN
301
+ fs.unlinkSync(file)
302
+ return resolve(res)
303
+ }).catch(reject)
304
+ })
305
+ }
306
+ }