clever-tools 3.10.1 → 3.12.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.
@@ -0,0 +1,276 @@
1
+ import colors from 'colors/safe.js';
2
+ import * as User from '../models/user.js';
3
+ import * as Organisation from '../models/organisation.js';
4
+
5
+ import crypto from 'node:crypto';
6
+ import { Logger } from '../logger.js';
7
+ import { sendToApi } from './send-to-api.js';
8
+ import { checkMembersToLink } from './ng-resources.js';
9
+ import { searchNetworkGroupOrResource } from '../clever-client/ng.js';
10
+ import { createNetworkGroup, deleteNetworkGroup, getNetworkGroup, getNetworkGroupWireGuardConfiguration, listNetworkGroups } from '@clevercloud/client/esm/api/v4/network-group.js';
11
+
12
+ export const POLLING_TIMEOUT_MS = 30_000;
13
+ export const POLLING_INTERVAL_MS = 1000;
14
+ export const DOMAIN = 'cc-ng.cloud';
15
+ const TYPE_PREFIXES = {
16
+ app_: 'APPLICATION',
17
+ addon_: 'ADDON',
18
+ external_: 'EXTERNAL',
19
+ };
20
+
21
+ /**
22
+ * Ask for a Network Group creation
23
+ * @param {string} label The Network Group label
24
+ * @param {string} description The Network Group description
25
+ * @param {string} tags The Network Group tags
26
+ * @param {Array<string>} membersIds The members to link to the Network Group
27
+ * @param {string} orgaIdOrName The owner ID or name
28
+ * @throws {Error} If the Network Group label is missing
29
+ */
30
+ export async function create (label, description, tags, membersIds, orgaIdOrName) {
31
+ const id = `ng_${crypto.randomUUID()}`;
32
+ const ownerId = await getOwnerIdFromOrgaIdOrName(orgaIdOrName);
33
+
34
+ if (membersIds?.length > 0) {
35
+ await checkMembersToLink(membersIds, ownerId);
36
+ }
37
+
38
+ const members = constructMembers(id, membersIds || []);
39
+ const body = { ownerId, id, label, description, tags, members };
40
+
41
+ Logger.info(`Creating Network Group ${label} (${id}) from owner ${ownerId}`);
42
+ Logger.info(`${members.length} members will be added: ${members.map((m) => m.id).join(', ')}`);
43
+ Logger.debug(`Sending body: ${JSON.stringify(body, null, 2)}`);
44
+ await createNetworkGroup({ ownerId }, body).then(sendToApi);
45
+
46
+ await pollNetworkGroup(ownerId, id, { waitForMembers: membersIds });
47
+ Logger.info(`Network Group ${label} (${id}) created from owner ${ownerId}`);
48
+ }
49
+
50
+ /**
51
+ * Ask for a Network Group deletion
52
+ * @param {object} ngIdOrLabel The Network Group ID or Label
53
+ * @param {object} orgaIdOrName The owner ID or name
54
+ * @throws {Error} If the Network Group is not found
55
+ */
56
+ export async function destroy (ngIdOrLabel, orgaIdOrName) {
57
+ const [found] = await searchNgOrResource(ngIdOrLabel, orgaIdOrName, 'NetworkGroup');
58
+
59
+ if (!found) {
60
+ throw new Error(`Network Group ${colors.red(ngIdOrLabel.ngId ?? ngIdOrLabel.ngResourceLabel)} not found`);
61
+ }
62
+
63
+ await deleteNetworkGroup({ ownerId: found.ownerId, networkGroupId: found.id }).then(sendToApi);
64
+ Logger.info(`Deleting Network Group ${found.id} from owner ${found.ownerId}`);
65
+ await pollNetworkGroup(found.ownerId, found.id, { waitForDeletion: true });
66
+ Logger.info(`Network Group ${found.id} deleted from owner ${found.ownerId}`);
67
+ }
68
+
69
+ /**
70
+ * Get the Wireguard configuration of a Network Group peer
71
+ * @param {object} peerIdOrLabel The Peer ID or Label
72
+ * @param {object} ngIdOrLabel The Network Group ID or Label
73
+ * @param {object} orgaIdOrName The owner ID or name
74
+ * @returns {Promise<Object>} The Peer Wireguard configuration
75
+ * @throws {Error} If the Peer is not found
76
+ * @throws {Error} If the Network Group is not found
77
+ * @throws {Error} If the Peer is not in the Network Group
78
+ */
79
+ export async function getPeerConfig (peerIdOrLabel, ngIdOrLabel, orgaIdOrName) {
80
+ const [parentNg] = await searchNgOrResource(ngIdOrLabel, orgaIdOrName, 'NetworkGroup');
81
+
82
+ if (!parentNg) {
83
+ throw new Error(`Network Group ${colors.red(ngIdOrLabel.ngId ?? ngIdOrLabel.ngResourceLabel)} not found`);
84
+ }
85
+
86
+ const [peer] = await searchNgOrResource(peerIdOrLabel, orgaIdOrName, 'Peer');
87
+
88
+ // peer.id is catched as a ngResourceLabel as it's a string with no distinctive prefix for now, it will change from API
89
+ if (!peer || (peerIdOrLabel.ngResourceLabel && (peerIdOrLabel.ngResourceLabel !== peer.label && peerIdOrLabel.ngResourceLabel !== peer.id))) {
90
+ throw new Error(`Peer ${colors.red(peerIdOrLabel.ngResourceLabel ?? peerIdOrLabel.member)} not found`);
91
+ }
92
+
93
+ if (!parentNg.peers.find((p) => p.id === peer.id)) {
94
+ throw new Error(`Peer ${colors.red(peer.id)} is not in Network Group ${colors.red(parentNg.id)}`);
95
+ }
96
+
97
+ Logger.debug(`Getting configuration for Peer ${peer.id}`);
98
+ const result = await getNetworkGroupWireGuardConfiguration({
99
+ ownerId: parentNg.ownerId,
100
+ networkGroupId: parentNg.id,
101
+ peerId: peer.id,
102
+ }).then(sendToApi);
103
+ Logger.debug(`Received from API:\n${JSON.stringify(result, null, 2)}`);
104
+
105
+ return result;
106
+ }
107
+
108
+ /**
109
+ * Get a Network group from an owner with members and peers
110
+ * @param {string} networkGroupId The Network Group ID
111
+ * @param {string} orgaIdOrName The owner ID or name
112
+ * @returns {Promise<Array<Object>>} The Network Groups
113
+ */
114
+ export async function getNG (networkGroupId, orgaIdOrName) {
115
+ const ownerId = await getOwnerIdFromOrgaIdOrName(orgaIdOrName);
116
+
117
+ Logger.info(`Get Network Group ${networkGroupId} for owner ${ownerId}`);
118
+ const result = await getNetworkGroup({ networkGroupId, ownerId }).then(sendToApi);
119
+ Logger.debug(`Received from API:\n${JSON.stringify(result, null, 2)}`);
120
+
121
+ return result;
122
+ }
123
+
124
+ /**
125
+ * Get all Network Groups from an owner with members and peers
126
+ * @param {string} orgaIdOrName The owner ID or name
127
+ * @returns {Promise<Array<Object>>} The Network Groups
128
+ */
129
+ export async function getAllNGs (orgaIdOrName) {
130
+ const ownerId = await getOwnerIdFromOrgaIdOrName(orgaIdOrName);
131
+
132
+ Logger.info(`Listing Network Groups from owner ${ownerId}`);
133
+ const result = await listNetworkGroups({ ownerId }).then(sendToApi);
134
+ Logger.debug(`Received from API:\n${JSON.stringify(result, null, 2)}`);
135
+ return result;
136
+ }
137
+
138
+ /**
139
+ * Search a Network Group or a resource (member/peer)
140
+ * @param {string|Object} idOrLabel The ID or label to look for
141
+ * @param {Object} orgaIdOrName The owner ID or name
142
+ * @param {string} [type] Look only for a specific type (NetworkGroup, Member, CleverPeer, ExternalPeer, Peer), can be 'single', default to 'all'
143
+ * @param {boolean} exactMatch Look for exact match, default to true
144
+ * @throws {Error} If multiple Network Groups or member/peer are found in single_result mode
145
+ * @returns {Promise<Object>} Found results
146
+ */
147
+ export async function searchNgOrResource (idOrLabel, orgaIdOrName, type = 'all', exactMatch = true) {
148
+ const ownerId = await getOwnerIdFromOrgaIdOrName(orgaIdOrName);
149
+
150
+ // If idOrLabel is a string we use it, or we look through multiple keys
151
+ const query = typeof idOrLabel === 'string'
152
+ ? idOrLabel
153
+ : (
154
+ idOrLabel.ngId
155
+ ?? idOrLabel.memberId
156
+ ?? idOrLabel.ngResourceLabel
157
+ );
158
+
159
+ const found = await searchNetworkGroupOrResource({ ownerId, query }).then(sendToApi);
160
+
161
+ let filtered = found;
162
+ switch (type) {
163
+ case 'all':
164
+ case 'single':
165
+ break;
166
+ case 'Peer':
167
+ filtered = found.filter((f) => f.type === 'CleverPeer' || f.type === 'ExternalPeer');
168
+ break;
169
+ case 'CleverPeer':
170
+ case 'ExternalPeer':
171
+ case 'Member':
172
+ case 'NetworkGroup':
173
+ filtered = found.filter((f) => f.type === type);
174
+ break;
175
+ default:
176
+ throw new Error(`Unsupported type: ${type}`);
177
+ }
178
+
179
+ if (exactMatch) {
180
+ filtered = filtered.filter((f) => f.id === query || f.label === query);
181
+ }
182
+
183
+ if (filtered.length > 1 && type !== 'all') {
184
+ throw new Error(`Multiple resources found for ${colors.red(query)}, use ID instead:
185
+ ${filtered.map((f) => ` • ${f.id} ${colors.grey(`(${f.label} - ${f.type})`)}`).join('\n')}`);
186
+ }
187
+
188
+ // Deduplicate results
189
+ return filtered.filter((item, index, array) => array.findIndex((element) => (element.id === item.id)) === index);
190
+ }
191
+
192
+ /**
193
+ * Construct members from members_ids
194
+ * @param {string} ngId The Network Group ID
195
+ * @param {Array<string>} membersIds The members IDs
196
+ * @returns {Array<Object>} Array of members with id, domainName and kind
197
+ */
198
+ export function constructMembers (ngId, membersIds) {
199
+ return membersIds.map((id) => {
200
+ const domainName = `${id}.m.${ngId}.${DOMAIN}`;
201
+ const prefixToType = TYPE_PREFIXES;
202
+
203
+ return {
204
+ id,
205
+ domainName,
206
+ // Get kind from prefix match in id (app_*, addon_*, external_*) or default to 'APPLICATION'
207
+ kind: prefixToType[Object.keys(prefixToType).find((p) => id.startsWith(p))]
208
+ ?? TYPE_PREFIXES.app_,
209
+ };
210
+ });
211
+ }
212
+
213
+ /**
214
+ * Poll Network Groups to check its status and members
215
+ * @param {string} ownerId The owner ID
216
+ * @param {string} ngId The Network Group ID
217
+ * @param {Array<string>} waitForMembers The members IDs to wait for
218
+ * @param {boolean} waitForDeletion Wait for the Network Group deletion
219
+ * @throws {Error} When timeout is reached
220
+ * @returns {Promise<void>}
221
+ */
222
+ async function pollNetworkGroup (ownerId, ngId, { waitForMembers = null, waitForDeletion = false } = {}) {
223
+ return new Promise((resolve, reject) => {
224
+ Logger.info(`Polling Network Groups from owner ${ownerId}`);
225
+ const timeoutTime = Date.now() + (POLLING_TIMEOUT_MS);
226
+
227
+ async function pollOnce () {
228
+ if (Date.now() > timeoutTime) {
229
+ const action = waitForDeletion ? 'deletion of' : 'creation of';
230
+ reject(new Error(`Timeout while checking ${action} Network Group ${ngId}`));
231
+ return;
232
+ }
233
+
234
+ try {
235
+ const ngs = await listNetworkGroups({ ownerId }).then(sendToApi);
236
+ const ng = ngs.find((ng) => ng.id === ngId);
237
+
238
+ if (waitForDeletion && !ng) {
239
+ resolve();
240
+ return;
241
+ }
242
+
243
+ if (!waitForDeletion && ng) {
244
+ if (waitForMembers?.length) {
245
+ const members = ng.members.filter((member) => waitForMembers.includes(member.id));
246
+ if (members.length !== waitForMembers.length) {
247
+ Logger.debug(`Waiting for members: ${waitForMembers.join(', ')}`);
248
+ setTimeout(pollOnce, POLLING_INTERVAL_MS);
249
+ return;
250
+ }
251
+ }
252
+ resolve();
253
+ return;
254
+ }
255
+
256
+ setTimeout(pollOnce, POLLING_INTERVAL_MS);
257
+ }
258
+ catch (error) {
259
+ reject(error);
260
+ }
261
+ }
262
+
263
+ pollOnce();
264
+ });
265
+ }
266
+
267
+ /**
268
+ * Get the owner ID from an Organisation ID or name
269
+ * @param {object} orgaIdOrName The Organisation ID or name
270
+ * @returns {Promise<string>} The owner ID
271
+ */
272
+ async function getOwnerIdFromOrgaIdOrName (orgaIdOrName) {
273
+ return orgaIdOrName != null
274
+ ? Organisation.getId(orgaIdOrName)
275
+ : User.getCurrentId();
276
+ }
@@ -1,10 +1,11 @@
1
1
  import { Logger } from '../logger.js';
2
2
  import { addOauthHeader } from '@clevercloud/client/esm/oauth.js';
3
- import { conf, loadOAuthConf } from '../models/configuration.js';
4
- import { execWarpscript } from '@clevercloud/client/esm/request-warp10.superagent.js';
3
+ import { conf, loadOAuthConf } from './configuration.js';
5
4
  import { prefixUrl } from '@clevercloud/client/esm/prefix-url.js';
6
5
  import { request } from '@clevercloud/client/esm/request.fetch.js';
7
6
  import { subtle as cryptoSuble } from 'node:crypto';
7
+ import { addOauthHeaderPlaintext } from '../clever-client/auth-bridge.js';
8
+ import colors from 'colors/safe.js';
8
9
 
9
10
  // Required for @clevercloud/client with "old" Node.js
10
11
  if (globalThis.crypto == null) {
@@ -36,6 +37,19 @@ export async function sendToApi (requestParams) {
36
37
  .catch(processError);
37
38
  }
38
39
 
40
+ export async function sendToAuthBridge (requestParams) {
41
+ const tokens = await loadTokens();
42
+ return Promise.resolve(requestParams)
43
+ .then(prefixUrl(conf.AUTH_BRIDGE_HOST))
44
+ .then(addOauthHeaderPlaintext(tokens))
45
+ .then((requestParams) => {
46
+ Logger.debug(`${requestParams.method.toUpperCase()} ${requestParams.url} ? ${JSON.stringify(requestParams.queryParams)}`);
47
+ return requestParams;
48
+ })
49
+ .then(request)
50
+ .catch(processError);
51
+ }
52
+
39
53
  export function processError (error) {
40
54
  const code = error.code ?? error?.cause?.code;
41
55
  if (code === 'EAI_AGAIN') {
@@ -44,15 +58,12 @@ export function processError (error) {
44
58
  if (code === 'ECONNRESET') {
45
59
  throw new Error('The connection to the Clever Cloud API was closed abruptly, please try again.', { cause: error });
46
60
  }
61
+ if (error?.response?.status === 401) {
62
+ throw new Error(`You're not logged in, use ${colors.red('clever login')} command to connect to your Clever Cloud account`, { cause: error });
63
+ }
47
64
  throw error;
48
65
  }
49
66
 
50
- export function sendToWarp10 (requestParams) {
51
- return Promise.resolve(requestParams)
52
- .then(prefixUrl(conf.WARP_10_EXEC_URL))
53
- .then((requestParams) => execWarpscript(requestParams, { retry: 1 }));
54
- }
55
-
56
67
  export async function getHostAndTokens () {
57
68
  const tokens = await loadTokens();
58
69
  return {
package/src/parsers.js CHANGED
@@ -2,7 +2,6 @@ import cliparse from 'cliparse';
2
2
 
3
3
  import * as Application from './models/application.js';
4
4
  import ISO8601 from 'iso8601-duration';
5
- import Duration from 'duration-js';
6
5
 
7
6
  const addonOptionsRegex = /^[\w-]+=.+$/;
8
7
 
@@ -56,6 +55,20 @@ export function date (dateString) {
56
55
  return duration;
57
56
  }
58
57
 
58
+ export function futureDateOrDuration (dateString) {
59
+ const date = new Date(dateString);
60
+ if (isNaN(dateString) && !isNaN(date.getTime())) {
61
+ return cliparse.parsers.success(date);
62
+ }
63
+
64
+ const duration = durationInSeconds(dateString);
65
+ if (duration.success) {
66
+ return cliparse.parsers.success(new Date(Date.now() + (duration.success * 1000)));
67
+ }
68
+
69
+ return duration;
70
+ }
71
+
59
72
  const appIdRegex = /^app_[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
60
73
 
61
74
  export function appIdOrName (string) {
@@ -163,8 +176,8 @@ export function durationInSeconds (durationStr = '') {
163
176
  }
164
177
 
165
178
  try {
166
- const duration = Duration.parse(durationStr);
167
- return cliparse.parsers.success(duration.seconds());
179
+ const durationInSeconds = parseSimpleDuration(durationStr);
180
+ return cliparse.parsers.success(durationInSeconds);
168
181
  }
169
182
  catch (err) {
170
183
  const n = Number.parseInt(durationStr);
@@ -175,3 +188,44 @@ export function durationInSeconds (durationStr = '') {
175
188
  return cliparse.parsers.success(n);
176
189
  }
177
190
  }
191
+
192
+ const SHORT_UNITS_TO_ISO = {
193
+ ms: (v) => `PT${(v / 1000).toFixed(3)}S`,
194
+ s: (v) => `PT${v}S`,
195
+ m: (v) => `PT${v}M`,
196
+ h: (v) => `PT${v}H`,
197
+ d: (v) => `P${v}D`,
198
+ w: (v) => `P${v}W`,
199
+ M: (v) => `P${v}M`,
200
+ y: (v) => `P${v}Y`,
201
+ };
202
+
203
+ function parseSimpleDuration (durationStr) {
204
+ const { rawValue, unit } = durationStr.match(/^(?<rawValue>\d+)(?<unit>.*)$/)?.groups ?? {};
205
+ if (unit in SHORT_UNITS_TO_ISO) {
206
+ const value = Number(rawValue);
207
+ const isoDuration = SHORT_UNITS_TO_ISO[unit](value);
208
+ const d = ISO8601.parse(isoDuration);
209
+ return ISO8601.toSeconds(d);
210
+ }
211
+ }
212
+
213
+ // Network groups parsers
214
+ export function ngResourceType (string) {
215
+ if (string.startsWith('ng_')) {
216
+ return cliparse.parsers.success({ ngId: string });
217
+ }
218
+ if (string.startsWith('app_') || string.startsWith('addon_') || string.startsWith('external_')) {
219
+ return cliparse.parsers.success({ memberId: string });
220
+ }
221
+ return cliparse.parsers.success({ ngResourceLabel: string });
222
+ }
223
+
224
+ export function ngValidType (string) {
225
+ if (string === 'NetworkGroup' || string === 'Member' || string === 'CleverPeer' || string === 'ExternalPeer') {
226
+ return cliparse.parsers.success(string);
227
+ }
228
+ else {
229
+ return cliparse.parsers.error(`Invalid Network Group resource type: ${string}`);
230
+ }
231
+ }
@@ -0,0 +1,10 @@
1
+ import { password } from '@inquirer/prompts';
2
+
3
+ export function promptPassword (message) {
4
+ return password({ message, mask: true }).catch((error) => {
5
+ if (error instanceof Error && error.name === 'ExitPromptError') {
6
+ process.exit(1);
7
+ }
8
+ throw error;
9
+ });
10
+ }